xref: /freebsd/sys/contrib/openzfs/lib/libzfs/libzfs_util.c (revision d30a1689f5b37e78ea189232a8b94a7011dc0dc8)
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 https://opensource.org/licenses/CDDL-1.0.
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 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2020 Joyent, Inc. All rights reserved.
25  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
26  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
27  * Copyright (c) 2017 Datto Inc.
28  * Copyright (c) 2020 The FreeBSD Foundation
29  *
30  * Portions of this software were developed by Allan Jude
31  * under sponsorship from the FreeBSD Foundation.
32  */
33 
34 /*
35  * Internal utility routines for the ZFS library.
36  */
37 
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <libintl.h>
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <strings.h>
45 #include <unistd.h>
46 #include <math.h>
47 #if LIBFETCH_DYNAMIC
48 #include <dlfcn.h>
49 #endif
50 #include <sys/stat.h>
51 #include <sys/mnttab.h>
52 #include <sys/mntent.h>
53 #include <sys/types.h>
54 #include <sys/wait.h>
55 
56 #include <libzfs.h>
57 #include <libzfs_core.h>
58 
59 #include "libzfs_impl.h"
60 #include "zfs_prop.h"
61 #include "zfeature_common.h"
62 #include <zfs_fletcher.h>
63 #include <libzutil.h>
64 
65 /*
66  * We only care about the scheme in order to match the scheme
67  * with the handler. Each handler should validate the full URI
68  * as necessary.
69  */
70 #define	URI_REGEX	"^\\([A-Za-z][A-Za-z0-9+.\\-]*\\):"
71 
72 int
73 libzfs_errno(libzfs_handle_t *hdl)
74 {
75 	return (hdl->libzfs_error);
76 }
77 
78 const char *
79 libzfs_error_action(libzfs_handle_t *hdl)
80 {
81 	return (hdl->libzfs_action);
82 }
83 
84 const char *
85 libzfs_error_description(libzfs_handle_t *hdl)
86 {
87 	if (hdl->libzfs_desc[0] != '\0')
88 		return (hdl->libzfs_desc);
89 
90 	switch (hdl->libzfs_error) {
91 	case EZFS_NOMEM:
92 		return (dgettext(TEXT_DOMAIN, "out of memory"));
93 	case EZFS_BADPROP:
94 		return (dgettext(TEXT_DOMAIN, "invalid property value"));
95 	case EZFS_PROPREADONLY:
96 		return (dgettext(TEXT_DOMAIN, "read-only property"));
97 	case EZFS_PROPTYPE:
98 		return (dgettext(TEXT_DOMAIN, "property doesn't apply to "
99 		    "datasets of this type"));
100 	case EZFS_PROPNONINHERIT:
101 		return (dgettext(TEXT_DOMAIN, "property cannot be inherited"));
102 	case EZFS_PROPSPACE:
103 		return (dgettext(TEXT_DOMAIN, "invalid quota or reservation"));
104 	case EZFS_BADTYPE:
105 		return (dgettext(TEXT_DOMAIN, "operation not applicable to "
106 		    "datasets of this type"));
107 	case EZFS_BUSY:
108 		return (dgettext(TEXT_DOMAIN, "pool or dataset is busy"));
109 	case EZFS_EXISTS:
110 		return (dgettext(TEXT_DOMAIN, "pool or dataset exists"));
111 	case EZFS_NOENT:
112 		return (dgettext(TEXT_DOMAIN, "no such pool or dataset"));
113 	case EZFS_BADSTREAM:
114 		return (dgettext(TEXT_DOMAIN, "invalid backup stream"));
115 	case EZFS_DSREADONLY:
116 		return (dgettext(TEXT_DOMAIN, "dataset is read-only"));
117 	case EZFS_VOLTOOBIG:
118 		return (dgettext(TEXT_DOMAIN, "volume size exceeds limit for "
119 		    "this system"));
120 	case EZFS_INVALIDNAME:
121 		return (dgettext(TEXT_DOMAIN, "invalid name"));
122 	case EZFS_BADRESTORE:
123 		return (dgettext(TEXT_DOMAIN, "unable to restore to "
124 		    "destination"));
125 	case EZFS_BADBACKUP:
126 		return (dgettext(TEXT_DOMAIN, "backup failed"));
127 	case EZFS_BADTARGET:
128 		return (dgettext(TEXT_DOMAIN, "invalid target vdev"));
129 	case EZFS_NODEVICE:
130 		return (dgettext(TEXT_DOMAIN, "no such device in pool"));
131 	case EZFS_BADDEV:
132 		return (dgettext(TEXT_DOMAIN, "invalid device"));
133 	case EZFS_NOREPLICAS:
134 		return (dgettext(TEXT_DOMAIN, "no valid replicas"));
135 	case EZFS_RESILVERING:
136 		return (dgettext(TEXT_DOMAIN, "currently resilvering"));
137 	case EZFS_BADVERSION:
138 		return (dgettext(TEXT_DOMAIN, "unsupported version or "
139 		    "feature"));
140 	case EZFS_POOLUNAVAIL:
141 		return (dgettext(TEXT_DOMAIN, "pool is unavailable"));
142 	case EZFS_DEVOVERFLOW:
143 		return (dgettext(TEXT_DOMAIN, "too many devices in one vdev"));
144 	case EZFS_BADPATH:
145 		return (dgettext(TEXT_DOMAIN, "must be an absolute path"));
146 	case EZFS_CROSSTARGET:
147 		return (dgettext(TEXT_DOMAIN, "operation crosses datasets or "
148 		    "pools"));
149 	case EZFS_ZONED:
150 		return (dgettext(TEXT_DOMAIN, "dataset in use by local zone"));
151 	case EZFS_MOUNTFAILED:
152 		return (dgettext(TEXT_DOMAIN, "mount failed"));
153 	case EZFS_UMOUNTFAILED:
154 		return (dgettext(TEXT_DOMAIN, "unmount failed"));
155 	case EZFS_UNSHARENFSFAILED:
156 		return (dgettext(TEXT_DOMAIN, "NFS share removal failed"));
157 	case EZFS_SHARENFSFAILED:
158 		return (dgettext(TEXT_DOMAIN, "NFS share creation failed"));
159 	case EZFS_UNSHARESMBFAILED:
160 		return (dgettext(TEXT_DOMAIN, "SMB share removal failed"));
161 	case EZFS_SHARESMBFAILED:
162 		return (dgettext(TEXT_DOMAIN, "SMB share creation failed"));
163 	case EZFS_PERM:
164 		return (dgettext(TEXT_DOMAIN, "permission denied"));
165 	case EZFS_NOSPC:
166 		return (dgettext(TEXT_DOMAIN, "out of space"));
167 	case EZFS_FAULT:
168 		return (dgettext(TEXT_DOMAIN, "bad address"));
169 	case EZFS_IO:
170 		return (dgettext(TEXT_DOMAIN, "I/O error"));
171 	case EZFS_INTR:
172 		return (dgettext(TEXT_DOMAIN, "signal received"));
173 	case EZFS_CKSUM:
174 		return (dgettext(TEXT_DOMAIN, "insufficient replicas"));
175 	case EZFS_ISSPARE:
176 		return (dgettext(TEXT_DOMAIN, "device is reserved as a hot "
177 		    "spare"));
178 	case EZFS_INVALCONFIG:
179 		return (dgettext(TEXT_DOMAIN, "invalid vdev configuration"));
180 	case EZFS_RECURSIVE:
181 		return (dgettext(TEXT_DOMAIN, "recursive dataset dependency"));
182 	case EZFS_NOHISTORY:
183 		return (dgettext(TEXT_DOMAIN, "no history available"));
184 	case EZFS_POOLPROPS:
185 		return (dgettext(TEXT_DOMAIN, "failed to retrieve "
186 		    "pool properties"));
187 	case EZFS_POOL_NOTSUP:
188 		return (dgettext(TEXT_DOMAIN, "operation not supported "
189 		    "on this type of pool"));
190 	case EZFS_POOL_INVALARG:
191 		return (dgettext(TEXT_DOMAIN, "invalid argument for "
192 		    "this pool operation"));
193 	case EZFS_NAMETOOLONG:
194 		return (dgettext(TEXT_DOMAIN, "dataset name is too long"));
195 	case EZFS_OPENFAILED:
196 		return (dgettext(TEXT_DOMAIN, "open failed"));
197 	case EZFS_NOCAP:
198 		return (dgettext(TEXT_DOMAIN,
199 		    "disk capacity information could not be retrieved"));
200 	case EZFS_LABELFAILED:
201 		return (dgettext(TEXT_DOMAIN, "write of label failed"));
202 	case EZFS_BADWHO:
203 		return (dgettext(TEXT_DOMAIN, "invalid user/group"));
204 	case EZFS_BADPERM:
205 		return (dgettext(TEXT_DOMAIN, "invalid permission"));
206 	case EZFS_BADPERMSET:
207 		return (dgettext(TEXT_DOMAIN, "invalid permission set name"));
208 	case EZFS_NODELEGATION:
209 		return (dgettext(TEXT_DOMAIN, "delegated administration is "
210 		    "disabled on pool"));
211 	case EZFS_BADCACHE:
212 		return (dgettext(TEXT_DOMAIN, "invalid or missing cache file"));
213 	case EZFS_ISL2CACHE:
214 		return (dgettext(TEXT_DOMAIN, "device is in use as a cache"));
215 	case EZFS_VDEVNOTSUP:
216 		return (dgettext(TEXT_DOMAIN, "vdev specification is not "
217 		    "supported"));
218 	case EZFS_NOTSUP:
219 		return (dgettext(TEXT_DOMAIN, "operation not supported "
220 		    "on this dataset"));
221 	case EZFS_IOC_NOTSUPPORTED:
222 		return (dgettext(TEXT_DOMAIN, "operation not supported by "
223 		    "zfs kernel module"));
224 	case EZFS_ACTIVE_SPARE:
225 		return (dgettext(TEXT_DOMAIN, "pool has active shared spare "
226 		    "device"));
227 	case EZFS_UNPLAYED_LOGS:
228 		return (dgettext(TEXT_DOMAIN, "log device has unplayed intent "
229 		    "logs"));
230 	case EZFS_REFTAG_RELE:
231 		return (dgettext(TEXT_DOMAIN, "no such tag on this dataset"));
232 	case EZFS_REFTAG_HOLD:
233 		return (dgettext(TEXT_DOMAIN, "tag already exists on this "
234 		    "dataset"));
235 	case EZFS_TAGTOOLONG:
236 		return (dgettext(TEXT_DOMAIN, "tag too long"));
237 	case EZFS_PIPEFAILED:
238 		return (dgettext(TEXT_DOMAIN, "pipe create failed"));
239 	case EZFS_THREADCREATEFAILED:
240 		return (dgettext(TEXT_DOMAIN, "thread create failed"));
241 	case EZFS_POSTSPLIT_ONLINE:
242 		return (dgettext(TEXT_DOMAIN, "disk was split from this pool "
243 		    "into a new one"));
244 	case EZFS_SCRUB_PAUSED:
245 		return (dgettext(TEXT_DOMAIN, "scrub is paused; "
246 		    "use 'zpool scrub' to resume"));
247 	case EZFS_SCRUBBING:
248 		return (dgettext(TEXT_DOMAIN, "currently scrubbing; "
249 		    "use 'zpool scrub -s' to cancel current scrub"));
250 	case EZFS_NO_SCRUB:
251 		return (dgettext(TEXT_DOMAIN, "there is no active scrub"));
252 	case EZFS_DIFF:
253 		return (dgettext(TEXT_DOMAIN, "unable to generate diffs"));
254 	case EZFS_DIFFDATA:
255 		return (dgettext(TEXT_DOMAIN, "invalid diff data"));
256 	case EZFS_POOLREADONLY:
257 		return (dgettext(TEXT_DOMAIN, "pool is read-only"));
258 	case EZFS_NO_PENDING:
259 		return (dgettext(TEXT_DOMAIN, "operation is not "
260 		    "in progress"));
261 	case EZFS_CHECKPOINT_EXISTS:
262 		return (dgettext(TEXT_DOMAIN, "checkpoint exists"));
263 	case EZFS_DISCARDING_CHECKPOINT:
264 		return (dgettext(TEXT_DOMAIN, "currently discarding "
265 		    "checkpoint"));
266 	case EZFS_NO_CHECKPOINT:
267 		return (dgettext(TEXT_DOMAIN, "checkpoint does not exist"));
268 	case EZFS_DEVRM_IN_PROGRESS:
269 		return (dgettext(TEXT_DOMAIN, "device removal in progress"));
270 	case EZFS_VDEV_TOO_BIG:
271 		return (dgettext(TEXT_DOMAIN, "device exceeds supported size"));
272 	case EZFS_ACTIVE_POOL:
273 		return (dgettext(TEXT_DOMAIN, "pool is imported on a "
274 		    "different host"));
275 	case EZFS_CRYPTOFAILED:
276 		return (dgettext(TEXT_DOMAIN, "encryption failure"));
277 	case EZFS_TOOMANY:
278 		return (dgettext(TEXT_DOMAIN, "argument list too long"));
279 	case EZFS_INITIALIZING:
280 		return (dgettext(TEXT_DOMAIN, "currently initializing"));
281 	case EZFS_NO_INITIALIZE:
282 		return (dgettext(TEXT_DOMAIN, "there is no active "
283 		    "initialization"));
284 	case EZFS_WRONG_PARENT:
285 		return (dgettext(TEXT_DOMAIN, "invalid parent dataset"));
286 	case EZFS_TRIMMING:
287 		return (dgettext(TEXT_DOMAIN, "currently trimming"));
288 	case EZFS_NO_TRIM:
289 		return (dgettext(TEXT_DOMAIN, "there is no active trim"));
290 	case EZFS_TRIM_NOTSUP:
291 		return (dgettext(TEXT_DOMAIN, "trim operations are not "
292 		    "supported by this device"));
293 	case EZFS_NO_RESILVER_DEFER:
294 		return (dgettext(TEXT_DOMAIN, "this action requires the "
295 		    "resilver_defer feature"));
296 	case EZFS_EXPORT_IN_PROGRESS:
297 		return (dgettext(TEXT_DOMAIN, "pool export in progress"));
298 	case EZFS_REBUILDING:
299 		return (dgettext(TEXT_DOMAIN, "currently sequentially "
300 		    "resilvering"));
301 	case EZFS_VDEV_NOTSUP:
302 		return (dgettext(TEXT_DOMAIN, "operation not supported "
303 		    "on this type of vdev"));
304 	case EZFS_NOT_USER_NAMESPACE:
305 		return (dgettext(TEXT_DOMAIN, "the provided file "
306 		    "was not a user namespace file"));
307 	case EZFS_UNKNOWN:
308 		return (dgettext(TEXT_DOMAIN, "unknown error"));
309 	default:
310 		assert(hdl->libzfs_error == 0);
311 		return (dgettext(TEXT_DOMAIN, "no error"));
312 	}
313 }
314 
315 void
316 zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
317 {
318 	va_list ap;
319 
320 	va_start(ap, fmt);
321 
322 	(void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
323 	    fmt, ap);
324 	hdl->libzfs_desc_active = 1;
325 
326 	va_end(ap);
327 }
328 
329 static void
330 zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
331 {
332 	(void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
333 	    fmt, ap);
334 	hdl->libzfs_error = error;
335 
336 	if (hdl->libzfs_desc_active)
337 		hdl->libzfs_desc_active = 0;
338 	else
339 		hdl->libzfs_desc[0] = '\0';
340 
341 	if (hdl->libzfs_printerr) {
342 		if (error == EZFS_UNKNOWN) {
343 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
344 			    "error: %s: %s\n"), hdl->libzfs_action,
345 			    libzfs_error_description(hdl));
346 			abort();
347 		}
348 
349 		(void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
350 		    libzfs_error_description(hdl));
351 		if (error == EZFS_NOMEM)
352 			exit(1);
353 	}
354 }
355 
356 int
357 zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
358 {
359 	return (zfs_error_fmt(hdl, error, "%s", msg));
360 }
361 
362 int
363 zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
364 {
365 	va_list ap;
366 
367 	va_start(ap, fmt);
368 
369 	zfs_verror(hdl, error, fmt, ap);
370 
371 	va_end(ap);
372 
373 	return (-1);
374 }
375 
376 static int
377 zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
378     va_list ap)
379 {
380 	switch (error) {
381 	case EPERM:
382 	case EACCES:
383 		zfs_verror(hdl, EZFS_PERM, fmt, ap);
384 		return (-1);
385 
386 	case ECANCELED:
387 		zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
388 		return (-1);
389 
390 	case EIO:
391 		zfs_verror(hdl, EZFS_IO, fmt, ap);
392 		return (-1);
393 
394 	case EFAULT:
395 		zfs_verror(hdl, EZFS_FAULT, fmt, ap);
396 		return (-1);
397 
398 	case EINTR:
399 		zfs_verror(hdl, EZFS_INTR, fmt, ap);
400 		return (-1);
401 
402 	case ECKSUM:
403 		zfs_verror(hdl, EZFS_CKSUM, fmt, ap);
404 		return (-1);
405 	}
406 
407 	return (0);
408 }
409 
410 int
411 zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
412 {
413 	return (zfs_standard_error_fmt(hdl, error, "%s", msg));
414 }
415 
416 int
417 zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
418 {
419 	va_list ap;
420 
421 	va_start(ap, fmt);
422 
423 	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
424 		va_end(ap);
425 		return (-1);
426 	}
427 
428 	switch (error) {
429 	case ENXIO:
430 	case ENODEV:
431 	case EPIPE:
432 		zfs_verror(hdl, EZFS_IO, fmt, ap);
433 		break;
434 
435 	case ENOENT:
436 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
437 		    "dataset does not exist"));
438 		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
439 		break;
440 
441 	case ENOSPC:
442 	case EDQUOT:
443 		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
444 		break;
445 
446 	case EEXIST:
447 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
448 		    "dataset already exists"));
449 		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
450 		break;
451 
452 	case EBUSY:
453 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
454 		    "dataset is busy"));
455 		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
456 		break;
457 	case EROFS:
458 		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
459 		break;
460 	case ENAMETOOLONG:
461 		zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
462 		break;
463 	case ENOTSUP:
464 		zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
465 		break;
466 	case EAGAIN:
467 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
468 		    "pool I/O is currently suspended"));
469 		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
470 		break;
471 	case EREMOTEIO:
472 		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
473 		break;
474 	case ZFS_ERR_UNKNOWN_SEND_STREAM_FEATURE:
475 	case ZFS_ERR_IOC_CMD_UNAVAIL:
476 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
477 		    "module does not support this operation. A reboot may "
478 		    "be required to enable this operation."));
479 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
480 		break;
481 	case ZFS_ERR_IOC_ARG_UNAVAIL:
482 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
483 		    "module does not support an option for this operation. "
484 		    "A reboot may be required to enable this option."));
485 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
486 		break;
487 	case ZFS_ERR_IOC_ARG_REQUIRED:
488 	case ZFS_ERR_IOC_ARG_BADTYPE:
489 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
490 		break;
491 	case ZFS_ERR_WRONG_PARENT:
492 		zfs_verror(hdl, EZFS_WRONG_PARENT, fmt, ap);
493 		break;
494 	case ZFS_ERR_BADPROP:
495 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
496 		break;
497 	case ZFS_ERR_NOT_USER_NAMESPACE:
498 		zfs_verror(hdl, EZFS_NOT_USER_NAMESPACE, fmt, ap);
499 		break;
500 	default:
501 		zfs_error_aux(hdl, "%s", strerror(error));
502 		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
503 		break;
504 	}
505 
506 	va_end(ap);
507 	return (-1);
508 }
509 
510 void
511 zfs_setprop_error(libzfs_handle_t *hdl, zfs_prop_t prop, int err,
512     char *errbuf)
513 {
514 	switch (err) {
515 
516 	case ENOSPC:
517 		/*
518 		 * For quotas and reservations, ENOSPC indicates
519 		 * something different; setting a quota or reservation
520 		 * doesn't use any disk space.
521 		 */
522 		switch (prop) {
523 		case ZFS_PROP_QUOTA:
524 		case ZFS_PROP_REFQUOTA:
525 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
526 			    "size is less than current used or "
527 			    "reserved space"));
528 			(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
529 			break;
530 
531 		case ZFS_PROP_RESERVATION:
532 		case ZFS_PROP_REFRESERVATION:
533 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
534 			    "size is greater than available space"));
535 			(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
536 			break;
537 
538 		default:
539 			(void) zfs_standard_error(hdl, err, errbuf);
540 			break;
541 		}
542 		break;
543 
544 	case EBUSY:
545 		(void) zfs_standard_error(hdl, EBUSY, errbuf);
546 		break;
547 
548 	case EROFS:
549 		(void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
550 		break;
551 
552 	case E2BIG:
553 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
554 		    "property value too long"));
555 		(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
556 		break;
557 
558 	case ENOTSUP:
559 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
560 		    "pool and or dataset must be upgraded to set this "
561 		    "property or value"));
562 		(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
563 		break;
564 
565 	case ERANGE:
566 		if (prop == ZFS_PROP_COMPRESSION ||
567 		    prop == ZFS_PROP_DNODESIZE ||
568 		    prop == ZFS_PROP_RECORDSIZE) {
569 			(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
570 			    "property setting is not allowed on "
571 			    "bootable datasets"));
572 			(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
573 		} else if (prop == ZFS_PROP_CHECKSUM ||
574 		    prop == ZFS_PROP_DEDUP) {
575 			(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
576 			    "property setting is not allowed on "
577 			    "root pools"));
578 			(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
579 		} else {
580 			(void) zfs_standard_error(hdl, err, errbuf);
581 		}
582 		break;
583 
584 	case EINVAL:
585 		if (prop == ZPROP_INVAL) {
586 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
587 		} else {
588 			(void) zfs_standard_error(hdl, err, errbuf);
589 		}
590 		break;
591 
592 	case ZFS_ERR_BADPROP:
593 		(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
594 		break;
595 
596 	case EACCES:
597 		if (prop == ZFS_PROP_KEYLOCATION) {
598 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
599 			    "keylocation may only be set on encryption roots"));
600 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
601 		} else {
602 			(void) zfs_standard_error(hdl, err, errbuf);
603 		}
604 		break;
605 
606 	case EOVERFLOW:
607 		/*
608 		 * This platform can't address a volume this big.
609 		 */
610 #ifdef _ILP32
611 		if (prop == ZFS_PROP_VOLSIZE) {
612 			(void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
613 			break;
614 		}
615 		zfs_fallthrough;
616 #endif
617 	default:
618 		(void) zfs_standard_error(hdl, err, errbuf);
619 	}
620 }
621 
622 int
623 zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
624 {
625 	return (zpool_standard_error_fmt(hdl, error, "%s", msg));
626 }
627 
628 int
629 zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
630 {
631 	va_list ap;
632 
633 	va_start(ap, fmt);
634 
635 	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
636 		va_end(ap);
637 		return (-1);
638 	}
639 
640 	switch (error) {
641 	case ENODEV:
642 		zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
643 		break;
644 
645 	case ENOENT:
646 		zfs_error_aux(hdl,
647 		    dgettext(TEXT_DOMAIN, "no such pool or dataset"));
648 		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
649 		break;
650 
651 	case EEXIST:
652 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
653 		    "pool already exists"));
654 		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
655 		break;
656 
657 	case EBUSY:
658 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
659 		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
660 		break;
661 
662 	/* There is no pending operation to cancel */
663 	case ENOTACTIVE:
664 		zfs_verror(hdl, EZFS_NO_PENDING, fmt, ap);
665 		break;
666 
667 	case ENXIO:
668 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
669 		    "one or more devices is currently unavailable"));
670 		zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
671 		break;
672 
673 	case ENAMETOOLONG:
674 		zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
675 		break;
676 
677 	case ENOTSUP:
678 		zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
679 		break;
680 
681 	case EINVAL:
682 		zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
683 		break;
684 
685 	case ENOSPC:
686 	case EDQUOT:
687 		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
688 		break;
689 
690 	case EAGAIN:
691 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
692 		    "pool I/O is currently suspended"));
693 		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
694 		break;
695 
696 	case EROFS:
697 		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
698 		break;
699 	case EDOM:
700 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
701 		    "block size out of range or does not match"));
702 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
703 		break;
704 	case EREMOTEIO:
705 		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
706 		break;
707 	case ZFS_ERR_CHECKPOINT_EXISTS:
708 		zfs_verror(hdl, EZFS_CHECKPOINT_EXISTS, fmt, ap);
709 		break;
710 	case ZFS_ERR_DISCARDING_CHECKPOINT:
711 		zfs_verror(hdl, EZFS_DISCARDING_CHECKPOINT, fmt, ap);
712 		break;
713 	case ZFS_ERR_NO_CHECKPOINT:
714 		zfs_verror(hdl, EZFS_NO_CHECKPOINT, fmt, ap);
715 		break;
716 	case ZFS_ERR_DEVRM_IN_PROGRESS:
717 		zfs_verror(hdl, EZFS_DEVRM_IN_PROGRESS, fmt, ap);
718 		break;
719 	case ZFS_ERR_VDEV_TOO_BIG:
720 		zfs_verror(hdl, EZFS_VDEV_TOO_BIG, fmt, ap);
721 		break;
722 	case ZFS_ERR_EXPORT_IN_PROGRESS:
723 		zfs_verror(hdl, EZFS_EXPORT_IN_PROGRESS, fmt, ap);
724 		break;
725 	case ZFS_ERR_RESILVER_IN_PROGRESS:
726 		zfs_verror(hdl, EZFS_RESILVERING, fmt, ap);
727 		break;
728 	case ZFS_ERR_REBUILD_IN_PROGRESS:
729 		zfs_verror(hdl, EZFS_REBUILDING, fmt, ap);
730 		break;
731 	case ZFS_ERR_BADPROP:
732 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
733 		break;
734 	case ZFS_ERR_VDEV_NOTSUP:
735 		zfs_verror(hdl, EZFS_VDEV_NOTSUP, fmt, ap);
736 		break;
737 	case ZFS_ERR_IOC_CMD_UNAVAIL:
738 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
739 		    "module does not support this operation. A reboot may "
740 		    "be required to enable this operation."));
741 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
742 		break;
743 	case ZFS_ERR_IOC_ARG_UNAVAIL:
744 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
745 		    "module does not support an option for this operation. "
746 		    "A reboot may be required to enable this option."));
747 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
748 		break;
749 	case ZFS_ERR_IOC_ARG_REQUIRED:
750 	case ZFS_ERR_IOC_ARG_BADTYPE:
751 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
752 		break;
753 	default:
754 		zfs_error_aux(hdl, "%s", strerror(error));
755 		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
756 	}
757 
758 	va_end(ap);
759 	return (-1);
760 }
761 
762 /*
763  * Display an out of memory error message and abort the current program.
764  */
765 int
766 no_memory(libzfs_handle_t *hdl)
767 {
768 	return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
769 }
770 
771 /*
772  * A safe form of malloc() which will die if the allocation fails.
773  */
774 void *
775 zfs_alloc(libzfs_handle_t *hdl, size_t size)
776 {
777 	void *data;
778 
779 	if ((data = calloc(1, size)) == NULL)
780 		(void) no_memory(hdl);
781 
782 	return (data);
783 }
784 
785 /*
786  * A safe form of asprintf() which will die if the allocation fails.
787  */
788 char *
789 zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
790 {
791 	va_list ap;
792 	char *ret;
793 	int err;
794 
795 	va_start(ap, fmt);
796 
797 	err = vasprintf(&ret, fmt, ap);
798 
799 	va_end(ap);
800 
801 	if (err < 0) {
802 		(void) no_memory(hdl);
803 		ret = NULL;
804 	}
805 
806 	return (ret);
807 }
808 
809 /*
810  * A safe form of realloc(), which also zeroes newly allocated space.
811  */
812 void *
813 zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
814 {
815 	void *ret;
816 
817 	if ((ret = realloc(ptr, newsize)) == NULL) {
818 		(void) no_memory(hdl);
819 		return (NULL);
820 	}
821 
822 	memset((char *)ret + oldsize, 0, newsize - oldsize);
823 	return (ret);
824 }
825 
826 /*
827  * A safe form of strdup() which will die if the allocation fails.
828  */
829 char *
830 zfs_strdup(libzfs_handle_t *hdl, const char *str)
831 {
832 	char *ret;
833 
834 	if ((ret = strdup(str)) == NULL)
835 		(void) no_memory(hdl);
836 
837 	return (ret);
838 }
839 
840 void
841 libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
842 {
843 	hdl->libzfs_printerr = printerr;
844 }
845 
846 /*
847  * Read lines from an open file descriptor and store them in an array of
848  * strings until EOF.  lines[] will be allocated and populated with all the
849  * lines read.  All newlines are replaced with NULL terminators for
850  * convenience.  lines[] must be freed after use with libzfs_free_str_array().
851  *
852  * Returns the number of lines read.
853  */
854 static int
855 libzfs_read_stdout_from_fd(int fd, char **lines[])
856 {
857 
858 	FILE *fp;
859 	int lines_cnt = 0;
860 	size_t len = 0;
861 	char *line = NULL;
862 	char **tmp_lines = NULL, **tmp;
863 
864 	fp = fdopen(fd, "r");
865 	if (fp == NULL) {
866 		close(fd);
867 		return (0);
868 	}
869 	while (getline(&line, &len, fp) != -1) {
870 		tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
871 		if (tmp == NULL) {
872 			/* Return the lines we were able to process */
873 			break;
874 		}
875 		tmp_lines = tmp;
876 
877 		/* Remove newline if not EOF */
878 		if (line[strlen(line) - 1] == '\n')
879 			line[strlen(line) - 1] = '\0';
880 
881 		tmp_lines[lines_cnt] = strdup(line);
882 		if (tmp_lines[lines_cnt] == NULL)
883 			break;
884 		++lines_cnt;
885 	}
886 	free(line);
887 	fclose(fp);
888 	*lines = tmp_lines;
889 	return (lines_cnt);
890 }
891 
892 static int
893 libzfs_run_process_impl(const char *path, char *argv[], char *env[], int flags,
894     char **lines[], int *lines_cnt)
895 {
896 	pid_t pid;
897 	int error, devnull_fd;
898 	int link[2];
899 
900 	/*
901 	 * Setup a pipe between our child and parent process if we're
902 	 * reading stdout.
903 	 */
904 	if (lines != NULL && pipe2(link, O_NONBLOCK | O_CLOEXEC) == -1)
905 		return (-EPIPE);
906 
907 	pid = fork();
908 	if (pid == 0) {
909 		/* Child process */
910 		devnull_fd = open("/dev/null", O_WRONLY | O_CLOEXEC);
911 
912 		if (devnull_fd < 0)
913 			_exit(-1);
914 
915 		if (!(flags & STDOUT_VERBOSE) && (lines == NULL))
916 			(void) dup2(devnull_fd, STDOUT_FILENO);
917 		else if (lines != NULL) {
918 			/* Save the output to lines[] */
919 			dup2(link[1], STDOUT_FILENO);
920 		}
921 
922 		if (!(flags & STDERR_VERBOSE))
923 			(void) dup2(devnull_fd, STDERR_FILENO);
924 
925 		if (flags & NO_DEFAULT_PATH) {
926 			if (env == NULL)
927 				execv(path, argv);
928 			else
929 				execve(path, argv, env);
930 		} else {
931 			if (env == NULL)
932 				execvp(path, argv);
933 			else
934 				execvpe(path, argv, env);
935 		}
936 
937 		_exit(-1);
938 	} else if (pid > 0) {
939 		/* Parent process */
940 		int status;
941 
942 		while ((error = waitpid(pid, &status, 0)) == -1 &&
943 		    errno == EINTR)
944 			;
945 		if (error < 0 || !WIFEXITED(status))
946 			return (-1);
947 
948 		if (lines != NULL) {
949 			close(link[1]);
950 			*lines_cnt = libzfs_read_stdout_from_fd(link[0], lines);
951 		}
952 		return (WEXITSTATUS(status));
953 	}
954 
955 	return (-1);
956 }
957 
958 int
959 libzfs_run_process(const char *path, char *argv[], int flags)
960 {
961 	return (libzfs_run_process_impl(path, argv, NULL, flags, NULL, NULL));
962 }
963 
964 /*
965  * Run a command and store its stdout lines in an array of strings (lines[]).
966  * lines[] is allocated and populated for you, and the number of lines is set in
967  * lines_cnt.  lines[] must be freed after use with libzfs_free_str_array().
968  * All newlines (\n) in lines[] are terminated for convenience.
969  */
970 int
971 libzfs_run_process_get_stdout(const char *path, char *argv[], char *env[],
972     char **lines[], int *lines_cnt)
973 {
974 	return (libzfs_run_process_impl(path, argv, env, 0, lines, lines_cnt));
975 }
976 
977 /*
978  * Same as libzfs_run_process_get_stdout(), but run without $PATH set.  This
979  * means that *path needs to be the full path to the executable.
980  */
981 int
982 libzfs_run_process_get_stdout_nopath(const char *path, char *argv[],
983     char *env[], char **lines[], int *lines_cnt)
984 {
985 	return (libzfs_run_process_impl(path, argv, env, NO_DEFAULT_PATH,
986 	    lines, lines_cnt));
987 }
988 
989 /*
990  * Free an array of strings.  Free both the strings contained in the array and
991  * the array itself.
992  */
993 void
994 libzfs_free_str_array(char **strs, int count)
995 {
996 	while (--count >= 0)
997 		free(strs[count]);
998 
999 	free(strs);
1000 }
1001 
1002 /*
1003  * Returns 1 if environment variable is set to "YES", "yes", "ON", "on", or
1004  * a non-zero number.
1005  *
1006  * Returns 0 otherwise.
1007  */
1008 boolean_t
1009 libzfs_envvar_is_set(const char *envvar)
1010 {
1011 	char *env = getenv(envvar);
1012 	return (env && (strtoul(env, NULL, 0) > 0 ||
1013 	    (!strncasecmp(env, "YES", 3) && strnlen(env, 4) == 3) ||
1014 	    (!strncasecmp(env, "ON", 2) && strnlen(env, 3) == 2)));
1015 }
1016 
1017 libzfs_handle_t *
1018 libzfs_init(void)
1019 {
1020 	libzfs_handle_t *hdl;
1021 	int error;
1022 	char *env;
1023 
1024 	if ((error = libzfs_load_module()) != 0) {
1025 		errno = error;
1026 		return (NULL);
1027 	}
1028 
1029 	if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
1030 		return (NULL);
1031 	}
1032 
1033 	if (regcomp(&hdl->libzfs_urire, URI_REGEX, 0) != 0) {
1034 		free(hdl);
1035 		return (NULL);
1036 	}
1037 
1038 	if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR|O_EXCL|O_CLOEXEC)) < 0) {
1039 		free(hdl);
1040 		return (NULL);
1041 	}
1042 
1043 	if (libzfs_core_init() != 0) {
1044 		(void) close(hdl->libzfs_fd);
1045 		free(hdl);
1046 		return (NULL);
1047 	}
1048 
1049 	zfs_prop_init();
1050 	zpool_prop_init();
1051 	zpool_feature_init();
1052 	vdev_prop_init();
1053 	libzfs_mnttab_init(hdl);
1054 	fletcher_4_init();
1055 
1056 	if (getenv("ZFS_PROP_DEBUG") != NULL) {
1057 		hdl->libzfs_prop_debug = B_TRUE;
1058 	}
1059 	if ((env = getenv("ZFS_SENDRECV_MAX_NVLIST")) != NULL) {
1060 		if ((error = zfs_nicestrtonum(hdl, env,
1061 		    &hdl->libzfs_max_nvlist))) {
1062 			errno = error;
1063 			(void) close(hdl->libzfs_fd);
1064 			free(hdl);
1065 			return (NULL);
1066 		}
1067 	} else {
1068 		hdl->libzfs_max_nvlist = (SPA_MAXBLOCKSIZE * 4);
1069 	}
1070 
1071 	/*
1072 	 * For testing, remove some settable properties and features
1073 	 */
1074 	if (libzfs_envvar_is_set("ZFS_SYSFS_PROP_SUPPORT_TEST")) {
1075 		zprop_desc_t *proptbl;
1076 
1077 		proptbl = zpool_prop_get_table();
1078 		proptbl[ZPOOL_PROP_COMMENT].pd_zfs_mod_supported = B_FALSE;
1079 
1080 		proptbl = zfs_prop_get_table();
1081 		proptbl[ZFS_PROP_DNODESIZE].pd_zfs_mod_supported = B_FALSE;
1082 
1083 		zfeature_info_t *ftbl = spa_feature_table;
1084 		ftbl[SPA_FEATURE_LARGE_BLOCKS].fi_zfs_mod_supported = B_FALSE;
1085 	}
1086 
1087 	return (hdl);
1088 }
1089 
1090 void
1091 libzfs_fini(libzfs_handle_t *hdl)
1092 {
1093 	(void) close(hdl->libzfs_fd);
1094 	zpool_free_handles(hdl);
1095 	namespace_clear(hdl);
1096 	libzfs_mnttab_fini(hdl);
1097 	libzfs_core_fini();
1098 	regfree(&hdl->libzfs_urire);
1099 	fletcher_4_fini();
1100 #if LIBFETCH_DYNAMIC
1101 	if (hdl->libfetch != (void *)-1 && hdl->libfetch != NULL)
1102 		(void) dlclose(hdl->libfetch);
1103 	free(hdl->libfetch_load_error);
1104 #endif
1105 	free(hdl);
1106 }
1107 
1108 libzfs_handle_t *
1109 zpool_get_handle(zpool_handle_t *zhp)
1110 {
1111 	return (zhp->zpool_hdl);
1112 }
1113 
1114 libzfs_handle_t *
1115 zfs_get_handle(zfs_handle_t *zhp)
1116 {
1117 	return (zhp->zfs_hdl);
1118 }
1119 
1120 zpool_handle_t *
1121 zfs_get_pool_handle(const zfs_handle_t *zhp)
1122 {
1123 	return (zhp->zpool_hdl);
1124 }
1125 
1126 /*
1127  * Given a name, determine whether or not it's a valid path
1128  * (starts with '/' or "./").  If so, walk the mnttab trying
1129  * to match the device number.  If not, treat the path as an
1130  * fs/vol/snap/bkmark name.
1131  */
1132 zfs_handle_t *
1133 zfs_path_to_zhandle(libzfs_handle_t *hdl, const char *path, zfs_type_t argtype)
1134 {
1135 	struct stat64 statbuf;
1136 	struct extmnttab entry;
1137 
1138 	if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1139 		/*
1140 		 * It's not a valid path, assume it's a name of type 'argtype'.
1141 		 */
1142 		return (zfs_open(hdl, path, argtype));
1143 	}
1144 
1145 	if (getextmntent(path, &entry, &statbuf) != 0)
1146 		return (NULL);
1147 
1148 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1149 		(void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1150 		    path);
1151 		return (NULL);
1152 	}
1153 
1154 	return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1155 }
1156 
1157 /*
1158  * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1159  * an ioctl().
1160  */
1161 void
1162 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1163 {
1164 	if (len == 0)
1165 		len = 256 * 1024;
1166 	zc->zc_nvlist_dst_size = len;
1167 	zc->zc_nvlist_dst =
1168 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1169 }
1170 
1171 /*
1172  * Called when an ioctl() which returns an nvlist fails with ENOMEM.  This will
1173  * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1174  * filled in by the kernel to indicate the actual required size.
1175  */
1176 void
1177 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1178 {
1179 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
1180 	zc->zc_nvlist_dst =
1181 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1182 }
1183 
1184 /*
1185  * Called to free the src and dst nvlists stored in the command structure.
1186  */
1187 void
1188 zcmd_free_nvlists(zfs_cmd_t *zc)
1189 {
1190 	free((void *)(uintptr_t)zc->zc_nvlist_conf);
1191 	free((void *)(uintptr_t)zc->zc_nvlist_src);
1192 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
1193 	zc->zc_nvlist_conf = 0;
1194 	zc->zc_nvlist_src = 0;
1195 	zc->zc_nvlist_dst = 0;
1196 }
1197 
1198 static void
1199 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1200     nvlist_t *nvl)
1201 {
1202 	char *packed;
1203 
1204 	size_t len = fnvlist_size(nvl);
1205 	packed = zfs_alloc(hdl, len);
1206 
1207 	verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1208 
1209 	*outnv = (uint64_t)(uintptr_t)packed;
1210 	*outlen = len;
1211 }
1212 
1213 void
1214 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1215 {
1216 	zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1217 	    &zc->zc_nvlist_conf_size, nvl);
1218 }
1219 
1220 void
1221 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1222 {
1223 	zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1224 	    &zc->zc_nvlist_src_size, nvl);
1225 }
1226 
1227 /*
1228  * Unpacks an nvlist from the ZFS ioctl command structure.
1229  */
1230 int
1231 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1232 {
1233 	if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1234 	    zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1235 		return (no_memory(hdl));
1236 
1237 	return (0);
1238 }
1239 
1240 /*
1241  * ================================================================
1242  * API shared by zfs and zpool property management
1243  * ================================================================
1244  */
1245 
1246 static void
1247 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1248 {
1249 	zprop_list_t *pl = cbp->cb_proplist;
1250 	int i;
1251 	char *title;
1252 	size_t len;
1253 
1254 	cbp->cb_first = B_FALSE;
1255 	if (cbp->cb_scripted)
1256 		return;
1257 
1258 	/*
1259 	 * Start with the length of the column headers.
1260 	 */
1261 	cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1262 	cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1263 	    "PROPERTY"));
1264 	cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1265 	    "VALUE"));
1266 	cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1267 	    "RECEIVED"));
1268 	cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1269 	    "SOURCE"));
1270 
1271 	/* first property is always NAME */
1272 	assert(cbp->cb_proplist->pl_prop ==
1273 	    ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1274 	    ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME)));
1275 
1276 	/*
1277 	 * Go through and calculate the widths for each column.  For the
1278 	 * 'source' column, we kludge it up by taking the worst-case scenario of
1279 	 * inheriting from the longest name.  This is acceptable because in the
1280 	 * majority of cases 'SOURCE' is the last column displayed, and we don't
1281 	 * use the width anyway.  Note that the 'VALUE' column can be oversized,
1282 	 * if the name of the property is much longer than any values we find.
1283 	 */
1284 	for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1285 		/*
1286 		 * 'PROPERTY' column
1287 		 */
1288 		if (pl->pl_prop != ZPROP_USERPROP) {
1289 			const char *propname = (type == ZFS_TYPE_POOL) ?
1290 			    zpool_prop_to_name(pl->pl_prop) :
1291 			    ((type == ZFS_TYPE_VDEV) ?
1292 			    vdev_prop_to_name(pl->pl_prop) :
1293 			    zfs_prop_to_name(pl->pl_prop));
1294 
1295 			assert(propname != NULL);
1296 			len = strlen(propname);
1297 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1298 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1299 		} else {
1300 			assert(pl->pl_user_prop != NULL);
1301 			len = strlen(pl->pl_user_prop);
1302 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1303 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1304 		}
1305 
1306 		/*
1307 		 * 'VALUE' column.  The first property is always the 'name'
1308 		 * property that was tacked on either by /sbin/zfs's
1309 		 * zfs_do_get() or when calling zprop_expand_list(), so we
1310 		 * ignore its width.  If the user specified the name property
1311 		 * to display, then it will be later in the list in any case.
1312 		 */
1313 		if (pl != cbp->cb_proplist &&
1314 		    pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1315 			cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1316 
1317 		/* 'RECEIVED' column. */
1318 		if (pl != cbp->cb_proplist &&
1319 		    pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1320 			cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1321 
1322 		/*
1323 		 * 'NAME' and 'SOURCE' columns
1324 		 */
1325 		if (pl->pl_prop == ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1326 		    ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME :
1327 		    ZFS_PROP_NAME)) && pl->pl_width >
1328 		    cbp->cb_colwidths[GET_COL_NAME]) {
1329 			cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1330 			cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1331 			    strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1332 		}
1333 	}
1334 
1335 	/*
1336 	 * Now go through and print the headers.
1337 	 */
1338 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1339 		switch (cbp->cb_columns[i]) {
1340 		case GET_COL_NAME:
1341 			title = dgettext(TEXT_DOMAIN, "NAME");
1342 			break;
1343 		case GET_COL_PROPERTY:
1344 			title = dgettext(TEXT_DOMAIN, "PROPERTY");
1345 			break;
1346 		case GET_COL_VALUE:
1347 			title = dgettext(TEXT_DOMAIN, "VALUE");
1348 			break;
1349 		case GET_COL_RECVD:
1350 			title = dgettext(TEXT_DOMAIN, "RECEIVED");
1351 			break;
1352 		case GET_COL_SOURCE:
1353 			title = dgettext(TEXT_DOMAIN, "SOURCE");
1354 			break;
1355 		default:
1356 			title = NULL;
1357 		}
1358 
1359 		if (title != NULL) {
1360 			if (i == (ZFS_GET_NCOLS - 1) ||
1361 			    cbp->cb_columns[i + 1] == GET_COL_NONE)
1362 				(void) printf("%s", title);
1363 			else
1364 				(void) printf("%-*s  ",
1365 				    cbp->cb_colwidths[cbp->cb_columns[i]],
1366 				    title);
1367 		}
1368 	}
1369 	(void) printf("\n");
1370 }
1371 
1372 /*
1373  * Display a single line of output, according to the settings in the callback
1374  * structure.
1375  */
1376 void
1377 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1378     const char *propname, const char *value, zprop_source_t sourcetype,
1379     const char *source, const char *recvd_value)
1380 {
1381 	int i;
1382 	const char *str = NULL;
1383 	char buf[128];
1384 
1385 	/*
1386 	 * Ignore those source types that the user has chosen to ignore.
1387 	 */
1388 	if ((sourcetype & cbp->cb_sources) == 0)
1389 		return;
1390 
1391 	if (cbp->cb_first)
1392 		zprop_print_headers(cbp, cbp->cb_type);
1393 
1394 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1395 		switch (cbp->cb_columns[i]) {
1396 		case GET_COL_NAME:
1397 			str = name;
1398 			break;
1399 
1400 		case GET_COL_PROPERTY:
1401 			str = propname;
1402 			break;
1403 
1404 		case GET_COL_VALUE:
1405 			str = value;
1406 			break;
1407 
1408 		case GET_COL_SOURCE:
1409 			switch (sourcetype) {
1410 			case ZPROP_SRC_NONE:
1411 				str = "-";
1412 				break;
1413 
1414 			case ZPROP_SRC_DEFAULT:
1415 				str = "default";
1416 				break;
1417 
1418 			case ZPROP_SRC_LOCAL:
1419 				str = "local";
1420 				break;
1421 
1422 			case ZPROP_SRC_TEMPORARY:
1423 				str = "temporary";
1424 				break;
1425 
1426 			case ZPROP_SRC_INHERITED:
1427 				(void) snprintf(buf, sizeof (buf),
1428 				    "inherited from %s", source);
1429 				str = buf;
1430 				break;
1431 			case ZPROP_SRC_RECEIVED:
1432 				str = "received";
1433 				break;
1434 
1435 			default:
1436 				str = NULL;
1437 				assert(!"unhandled zprop_source_t");
1438 			}
1439 			break;
1440 
1441 		case GET_COL_RECVD:
1442 			str = (recvd_value == NULL ? "-" : recvd_value);
1443 			break;
1444 
1445 		default:
1446 			continue;
1447 		}
1448 
1449 		if (i == (ZFS_GET_NCOLS - 1) ||
1450 		    cbp->cb_columns[i + 1] == GET_COL_NONE)
1451 			(void) printf("%s", str);
1452 		else if (cbp->cb_scripted)
1453 			(void) printf("%s\t", str);
1454 		else
1455 			(void) printf("%-*s  ",
1456 			    cbp->cb_colwidths[cbp->cb_columns[i]],
1457 			    str);
1458 	}
1459 
1460 	(void) printf("\n");
1461 }
1462 
1463 /*
1464  * Given a numeric suffix, convert the value into a number of bits that the
1465  * resulting value must be shifted.
1466  */
1467 static int
1468 str2shift(libzfs_handle_t *hdl, const char *buf)
1469 {
1470 	const char *ends = "BKMGTPEZ";
1471 	int i;
1472 
1473 	if (buf[0] == '\0')
1474 		return (0);
1475 	for (i = 0; i < strlen(ends); i++) {
1476 		if (toupper(buf[0]) == ends[i])
1477 			break;
1478 	}
1479 	if (i == strlen(ends)) {
1480 		if (hdl)
1481 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1482 			    "invalid numeric suffix '%s'"), buf);
1483 		return (-1);
1484 	}
1485 
1486 	/*
1487 	 * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1488 	 * However, 'BB' and 'BiB' are disallowed.
1489 	 */
1490 	if (buf[1] == '\0' ||
1491 	    (toupper(buf[0]) != 'B' &&
1492 	    ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1493 	    (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1494 	    buf[3] == '\0'))))
1495 		return (10 * i);
1496 
1497 	if (hdl)
1498 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1499 		    "invalid numeric suffix '%s'"), buf);
1500 	return (-1);
1501 }
1502 
1503 /*
1504  * Convert a string of the form '100G' into a real number.  Used when setting
1505  * properties or creating a volume.  'buf' is used to place an extended error
1506  * message for the caller to use.
1507  */
1508 int
1509 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1510 {
1511 	char *end;
1512 	int shift;
1513 
1514 	*num = 0;
1515 
1516 	/* Check to see if this looks like a number.  */
1517 	if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1518 		if (hdl)
1519 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1520 			    "bad numeric value '%s'"), value);
1521 		return (-1);
1522 	}
1523 
1524 	/* Rely on strtoull() to process the numeric portion.  */
1525 	errno = 0;
1526 	*num = strtoull(value, &end, 10);
1527 
1528 	/*
1529 	 * Check for ERANGE, which indicates that the value is too large to fit
1530 	 * in a 64-bit value.
1531 	 */
1532 	if (errno == ERANGE) {
1533 		if (hdl)
1534 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1535 			    "numeric value is too large"));
1536 		return (-1);
1537 	}
1538 
1539 	/*
1540 	 * If we have a decimal value, then do the computation with floating
1541 	 * point arithmetic.  Otherwise, use standard arithmetic.
1542 	 */
1543 	if (*end == '.') {
1544 		double fval = strtod(value, &end);
1545 
1546 		if ((shift = str2shift(hdl, end)) == -1)
1547 			return (-1);
1548 
1549 		fval *= pow(2, shift);
1550 
1551 		/*
1552 		 * UINT64_MAX is not exactly representable as a double.
1553 		 * The closest representation is UINT64_MAX + 1, so we
1554 		 * use a >= comparison instead of > for the bounds check.
1555 		 */
1556 		if (fval >= (double)UINT64_MAX) {
1557 			if (hdl)
1558 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1559 				    "numeric value is too large"));
1560 			return (-1);
1561 		}
1562 
1563 		*num = (uint64_t)fval;
1564 	} else {
1565 		if ((shift = str2shift(hdl, end)) == -1)
1566 			return (-1);
1567 
1568 		/* Check for overflow */
1569 		if (shift >= 64 || (*num << shift) >> shift != *num) {
1570 			if (hdl)
1571 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1572 				    "numeric value is too large"));
1573 			return (-1);
1574 		}
1575 
1576 		*num <<= shift;
1577 	}
1578 
1579 	return (0);
1580 }
1581 
1582 /*
1583  * Given a propname=value nvpair to set, parse any numeric properties
1584  * (index, boolean, etc) if they are specified as strings and add the
1585  * resulting nvpair to the returned nvlist.
1586  *
1587  * At the DSL layer, all properties are either 64-bit numbers or strings.
1588  * We want the user to be able to ignore this fact and specify properties
1589  * as native values (numbers, for example) or as strings (to simplify
1590  * command line utilities).  This also handles converting index types
1591  * (compression, checksum, etc) from strings to their on-disk index.
1592  */
1593 int
1594 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1595     zfs_type_t type, nvlist_t *ret, char **svalp, uint64_t *ivalp,
1596     const char *errbuf)
1597 {
1598 	data_type_t datatype = nvpair_type(elem);
1599 	zprop_type_t proptype;
1600 	const char *propname;
1601 	char *value;
1602 	boolean_t isnone = B_FALSE;
1603 	boolean_t isauto = B_FALSE;
1604 	int err = 0;
1605 
1606 	if (type == ZFS_TYPE_POOL) {
1607 		proptype = zpool_prop_get_type(prop);
1608 		propname = zpool_prop_to_name(prop);
1609 	} else if (type == ZFS_TYPE_VDEV) {
1610 		proptype = vdev_prop_get_type(prop);
1611 		propname = vdev_prop_to_name(prop);
1612 	} else {
1613 		proptype = zfs_prop_get_type(prop);
1614 		propname = zfs_prop_to_name(prop);
1615 	}
1616 
1617 	/*
1618 	 * Convert any properties to the internal DSL value types.
1619 	 */
1620 	*svalp = NULL;
1621 	*ivalp = 0;
1622 
1623 	switch (proptype) {
1624 	case PROP_TYPE_STRING:
1625 		if (datatype != DATA_TYPE_STRING) {
1626 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1627 			    "'%s' must be a string"), nvpair_name(elem));
1628 			goto error;
1629 		}
1630 		err = nvpair_value_string(elem, svalp);
1631 		if (err != 0) {
1632 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1633 			    "'%s' is invalid"), nvpair_name(elem));
1634 			goto error;
1635 		}
1636 		if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1637 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1638 			    "'%s' is too long"), nvpair_name(elem));
1639 			goto error;
1640 		}
1641 		break;
1642 
1643 	case PROP_TYPE_NUMBER:
1644 		if (datatype == DATA_TYPE_STRING) {
1645 			(void) nvpair_value_string(elem, &value);
1646 			if (strcmp(value, "none") == 0) {
1647 				isnone = B_TRUE;
1648 			} else if (strcmp(value, "auto") == 0) {
1649 				isauto = B_TRUE;
1650 			} else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1651 				goto error;
1652 			}
1653 		} else if (datatype == DATA_TYPE_UINT64) {
1654 			(void) nvpair_value_uint64(elem, ivalp);
1655 		} else {
1656 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1657 			    "'%s' must be a number"), nvpair_name(elem));
1658 			goto error;
1659 		}
1660 
1661 		/*
1662 		 * Quota special: force 'none' and don't allow 0.
1663 		 */
1664 		if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1665 		    (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1666 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1667 			    "use 'none' to disable quota/refquota"));
1668 			goto error;
1669 		}
1670 
1671 		/*
1672 		 * Special handling for "*_limit=none". In this case it's not
1673 		 * 0 but UINT64_MAX.
1674 		 */
1675 		if ((type & ZFS_TYPE_DATASET) && isnone &&
1676 		    (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1677 		    prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1678 			*ivalp = UINT64_MAX;
1679 		}
1680 
1681 		/*
1682 		 * Special handling for setting 'refreservation' to 'auto'.  Use
1683 		 * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1684 		 * 'auto' is only allowed on volumes.
1685 		 */
1686 		if (isauto) {
1687 			switch (prop) {
1688 			case ZFS_PROP_REFRESERVATION:
1689 				if ((type & ZFS_TYPE_VOLUME) == 0) {
1690 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1691 					    "'%s=auto' only allowed on "
1692 					    "volumes"), nvpair_name(elem));
1693 					goto error;
1694 				}
1695 				*ivalp = UINT64_MAX;
1696 				break;
1697 			default:
1698 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1699 				    "'auto' is invalid value for '%s'"),
1700 				    nvpair_name(elem));
1701 				goto error;
1702 			}
1703 		}
1704 
1705 		break;
1706 
1707 	case PROP_TYPE_INDEX:
1708 		if (datatype != DATA_TYPE_STRING) {
1709 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1710 			    "'%s' must be a string"), nvpair_name(elem));
1711 			goto error;
1712 		}
1713 
1714 		(void) nvpair_value_string(elem, &value);
1715 
1716 		if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1717 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1718 			    "'%s' must be one of '%s'"), propname,
1719 			    zprop_values(prop, type));
1720 			goto error;
1721 		}
1722 		break;
1723 
1724 	default:
1725 		abort();
1726 	}
1727 
1728 	/*
1729 	 * Add the result to our return set of properties.
1730 	 */
1731 	if (*svalp != NULL) {
1732 		if (nvlist_add_string(ret, propname, *svalp) != 0) {
1733 			(void) no_memory(hdl);
1734 			return (-1);
1735 		}
1736 	} else {
1737 		if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1738 			(void) no_memory(hdl);
1739 			return (-1);
1740 		}
1741 	}
1742 
1743 	return (0);
1744 error:
1745 	(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1746 	return (-1);
1747 }
1748 
1749 static int
1750 addlist(libzfs_handle_t *hdl, const char *propname, zprop_list_t **listp,
1751     zfs_type_t type)
1752 {
1753 	int prop = zprop_name_to_prop(propname, type);
1754 	if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
1755 		prop = ZPROP_INVAL;
1756 
1757 	/*
1758 	 * Return failure if no property table entry was found and this isn't
1759 	 * a user-defined property.
1760 	 */
1761 	if (prop == ZPROP_USERPROP && ((type == ZFS_TYPE_POOL &&
1762 	    !zpool_prop_feature(propname) &&
1763 	    !zpool_prop_unsupported(propname)) ||
1764 	    ((type == ZFS_TYPE_DATASET) && !zfs_prop_user(propname) &&
1765 	    !zfs_prop_userquota(propname) && !zfs_prop_written(propname)) ||
1766 	    ((type == ZFS_TYPE_VDEV) && !vdev_prop_user(propname)))) {
1767 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1768 		    "invalid property '%s'"), propname);
1769 		return (zfs_error(hdl, EZFS_BADPROP,
1770 		    dgettext(TEXT_DOMAIN, "bad property list")));
1771 	}
1772 
1773 	zprop_list_t *entry = zfs_alloc(hdl, sizeof (*entry));
1774 
1775 	entry->pl_prop = prop;
1776 	if (prop == ZPROP_USERPROP) {
1777 		entry->pl_user_prop = zfs_strdup(hdl, propname);
1778 		entry->pl_width = strlen(propname);
1779 	} else {
1780 		entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1781 		    type);
1782 	}
1783 
1784 	*listp = entry;
1785 
1786 	return (0);
1787 }
1788 
1789 /*
1790  * Given a comma-separated list of properties, construct a property list
1791  * containing both user-defined and native properties.  This function will
1792  * return a NULL list if 'all' is specified, which can later be expanded
1793  * by zprop_expand_list().
1794  */
1795 int
1796 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1797     zfs_type_t type)
1798 {
1799 	*listp = NULL;
1800 
1801 	/*
1802 	 * If 'all' is specified, return a NULL list.
1803 	 */
1804 	if (strcmp(props, "all") == 0)
1805 		return (0);
1806 
1807 	/*
1808 	 * If no props were specified, return an error.
1809 	 */
1810 	if (props[0] == '\0') {
1811 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1812 		    "no properties specified"));
1813 		return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1814 		    "bad property list")));
1815 	}
1816 
1817 	for (char *p; (p = strsep(&props, ",")); )
1818 		if (strcmp(p, "space") == 0) {
1819 			static const char *const spaceprops[] = {
1820 				"name", "avail", "used", "usedbysnapshots",
1821 				"usedbydataset", "usedbyrefreservation",
1822 				"usedbychildren"
1823 			};
1824 
1825 			for (int i = 0; i < ARRAY_SIZE(spaceprops); i++) {
1826 				if (addlist(hdl, spaceprops[i], listp, type))
1827 					return (-1);
1828 				listp = &(*listp)->pl_next;
1829 			}
1830 		} else {
1831 			if (addlist(hdl, p, listp, type))
1832 				return (-1);
1833 			listp = &(*listp)->pl_next;
1834 		}
1835 
1836 	return (0);
1837 }
1838 
1839 void
1840 zprop_free_list(zprop_list_t *pl)
1841 {
1842 	zprop_list_t *next;
1843 
1844 	while (pl != NULL) {
1845 		next = pl->pl_next;
1846 		free(pl->pl_user_prop);
1847 		free(pl);
1848 		pl = next;
1849 	}
1850 }
1851 
1852 typedef struct expand_data {
1853 	zprop_list_t	**last;
1854 	libzfs_handle_t	*hdl;
1855 	zfs_type_t type;
1856 } expand_data_t;
1857 
1858 static int
1859 zprop_expand_list_cb(int prop, void *cb)
1860 {
1861 	zprop_list_t *entry;
1862 	expand_data_t *edp = cb;
1863 
1864 	entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t));
1865 
1866 	entry->pl_prop = prop;
1867 	entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
1868 	entry->pl_all = B_TRUE;
1869 
1870 	*(edp->last) = entry;
1871 	edp->last = &entry->pl_next;
1872 
1873 	return (ZPROP_CONT);
1874 }
1875 
1876 int
1877 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
1878 {
1879 	zprop_list_t *entry;
1880 	zprop_list_t **last;
1881 	expand_data_t exp;
1882 
1883 	if (*plp == NULL) {
1884 		/*
1885 		 * If this is the very first time we've been called for an 'all'
1886 		 * specification, expand the list to include all native
1887 		 * properties.
1888 		 */
1889 		last = plp;
1890 
1891 		exp.last = last;
1892 		exp.hdl = hdl;
1893 		exp.type = type;
1894 
1895 		if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
1896 		    B_FALSE, type) == ZPROP_INVAL)
1897 			return (-1);
1898 
1899 		/*
1900 		 * Add 'name' to the beginning of the list, which is handled
1901 		 * specially.
1902 		 */
1903 		entry = zfs_alloc(hdl, sizeof (zprop_list_t));
1904 		entry->pl_prop = ((type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME :
1905 		    ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME));
1906 		entry->pl_width = zprop_width(entry->pl_prop,
1907 		    &entry->pl_fixed, type);
1908 		entry->pl_all = B_TRUE;
1909 		entry->pl_next = *plp;
1910 		*plp = entry;
1911 	}
1912 	return (0);
1913 }
1914 
1915 int
1916 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
1917     zfs_type_t type)
1918 {
1919 	return (zprop_iter_common(func, cb, show_all, ordered, type));
1920 }
1921 
1922 const char *
1923 zfs_version_userland(void)
1924 {
1925 	return (ZFS_META_ALIAS);
1926 }
1927 
1928 /*
1929  * Prints both zfs userland and kernel versions
1930  * Returns 0 on success, and -1 on error
1931  */
1932 int
1933 zfs_version_print(void)
1934 {
1935 	(void) puts(ZFS_META_ALIAS);
1936 
1937 	char *kver = zfs_version_kernel();
1938 	if (kver == NULL) {
1939 		fprintf(stderr, "zfs_version_kernel() failed: %s\n",
1940 		    strerror(errno));
1941 		return (-1);
1942 	}
1943 
1944 	(void) printf("zfs-kmod-%s\n", kver);
1945 	free(kver);
1946 	return (0);
1947 }
1948 
1949 /*
1950  * Return 1 if the user requested ANSI color output, and our terminal supports
1951  * it.  Return 0 for no color.
1952  */
1953 static int
1954 use_color(void)
1955 {
1956 	static int use_color = -1;
1957 	char *term;
1958 
1959 	/*
1960 	 * Optimization:
1961 	 *
1962 	 * For each zpool invocation, we do a single check to see if we should
1963 	 * be using color or not, and cache that value for the lifetime of the
1964 	 * the zpool command.  That makes it cheap to call use_color() when
1965 	 * we're printing with color.  We assume that the settings are not going
1966 	 * to change during the invocation of a zpool command (the user isn't
1967 	 * going to change the ZFS_COLOR value while zpool is running, for
1968 	 * example).
1969 	 */
1970 	if (use_color != -1) {
1971 		/*
1972 		 * We've already figured out if we should be using color or
1973 		 * not.  Return the cached value.
1974 		 */
1975 		return (use_color);
1976 	}
1977 
1978 	term = getenv("TERM");
1979 	/*
1980 	 * The user sets the ZFS_COLOR env var set to enable zpool ANSI color
1981 	 * output.  However if NO_COLOR is set (https://no-color.org/) then
1982 	 * don't use it.  Also, don't use color if terminal doesn't support
1983 	 * it.
1984 	 */
1985 	if (libzfs_envvar_is_set("ZFS_COLOR") &&
1986 	    !libzfs_envvar_is_set("NO_COLOR") &&
1987 	    isatty(STDOUT_FILENO) && term && strcmp("dumb", term) != 0 &&
1988 	    strcmp("unknown", term) != 0) {
1989 		/* Color supported */
1990 		use_color = 1;
1991 	} else {
1992 		use_color = 0;
1993 	}
1994 
1995 	return (use_color);
1996 }
1997 
1998 /*
1999  * color_start() and color_end() are used for when you want to colorize a block
2000  * of text.  For example:
2001  *
2002  * color_start(ANSI_RED_FG)
2003  * printf("hello");
2004  * printf("world");
2005  * color_end();
2006  */
2007 void
2008 color_start(const char *color)
2009 {
2010 	if (use_color())
2011 		fputs(color, stdout);
2012 }
2013 
2014 void
2015 color_end(void)
2016 {
2017 	if (use_color())
2018 		fputs(ANSI_RESET, stdout);
2019 }
2020 
2021 /* printf() with a color.  If color is NULL, then do a normal printf. */
2022 int
2023 printf_color(const char *color, const char *format, ...)
2024 {
2025 	va_list aptr;
2026 	int rc;
2027 
2028 	if (color)
2029 		color_start(color);
2030 
2031 	va_start(aptr, format);
2032 	rc = vprintf(format, aptr);
2033 	va_end(aptr);
2034 
2035 	if (color)
2036 		color_end();
2037 
2038 	return (rc);
2039 }
2040