xref: /freebsd/sys/contrib/openzfs/lib/libzfs/libzfs_util.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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 scrub"));
247 	case EZFS_SCRUB_PAUSED_TO_CANCEL:
248 		return (dgettext(TEXT_DOMAIN, "scrub is paused; "
249 		    "use 'zpool scrub' to resume or 'zpool scrub -s' to "
250 		    "cancel scrub"));
251 	case EZFS_SCRUBBING:
252 		return (dgettext(TEXT_DOMAIN, "currently scrubbing; "
253 		    "use 'zpool scrub -s' to cancel scrub"));
254 	case EZFS_ERRORSCRUBBING:
255 		return (dgettext(TEXT_DOMAIN, "currently error scrubbing; "
256 		    "use 'zpool scrub -s' to cancel error scrub"));
257 	case EZFS_ERRORSCRUB_PAUSED:
258 		return (dgettext(TEXT_DOMAIN, "error scrub is paused; "
259 		    "use 'zpool scrub -e' to resume error scrub"));
260 	case EZFS_NO_SCRUB:
261 		return (dgettext(TEXT_DOMAIN, "there is no active scrub"));
262 	case EZFS_DIFF:
263 		return (dgettext(TEXT_DOMAIN, "unable to generate diffs"));
264 	case EZFS_DIFFDATA:
265 		return (dgettext(TEXT_DOMAIN, "invalid diff data"));
266 	case EZFS_POOLREADONLY:
267 		return (dgettext(TEXT_DOMAIN, "pool is read-only"));
268 	case EZFS_NO_PENDING:
269 		return (dgettext(TEXT_DOMAIN, "operation is not "
270 		    "in progress"));
271 	case EZFS_CHECKPOINT_EXISTS:
272 		return (dgettext(TEXT_DOMAIN, "checkpoint exists"));
273 	case EZFS_DISCARDING_CHECKPOINT:
274 		return (dgettext(TEXT_DOMAIN, "currently discarding "
275 		    "checkpoint"));
276 	case EZFS_NO_CHECKPOINT:
277 		return (dgettext(TEXT_DOMAIN, "checkpoint does not exist"));
278 	case EZFS_DEVRM_IN_PROGRESS:
279 		return (dgettext(TEXT_DOMAIN, "device removal in progress"));
280 	case EZFS_VDEV_TOO_BIG:
281 		return (dgettext(TEXT_DOMAIN, "device exceeds supported size"));
282 	case EZFS_ACTIVE_POOL:
283 		return (dgettext(TEXT_DOMAIN, "pool is imported on a "
284 		    "different host"));
285 	case EZFS_CRYPTOFAILED:
286 		return (dgettext(TEXT_DOMAIN, "encryption failure"));
287 	case EZFS_TOOMANY:
288 		return (dgettext(TEXT_DOMAIN, "argument list too long"));
289 	case EZFS_INITIALIZING:
290 		return (dgettext(TEXT_DOMAIN, "currently initializing"));
291 	case EZFS_NO_INITIALIZE:
292 		return (dgettext(TEXT_DOMAIN, "there is no active "
293 		    "initialization"));
294 	case EZFS_WRONG_PARENT:
295 		return (dgettext(TEXT_DOMAIN, "invalid parent dataset"));
296 	case EZFS_TRIMMING:
297 		return (dgettext(TEXT_DOMAIN, "currently trimming"));
298 	case EZFS_NO_TRIM:
299 		return (dgettext(TEXT_DOMAIN, "there is no active trim"));
300 	case EZFS_TRIM_NOTSUP:
301 		return (dgettext(TEXT_DOMAIN, "trim operations are not "
302 		    "supported by this device"));
303 	case EZFS_NO_RESILVER_DEFER:
304 		return (dgettext(TEXT_DOMAIN, "this action requires the "
305 		    "resilver_defer feature"));
306 	case EZFS_EXPORT_IN_PROGRESS:
307 		return (dgettext(TEXT_DOMAIN, "pool export in progress"));
308 	case EZFS_REBUILDING:
309 		return (dgettext(TEXT_DOMAIN, "currently sequentially "
310 		    "resilvering"));
311 	case EZFS_VDEV_NOTSUP:
312 		return (dgettext(TEXT_DOMAIN, "operation not supported "
313 		    "on this type of vdev"));
314 	case EZFS_NOT_USER_NAMESPACE:
315 		return (dgettext(TEXT_DOMAIN, "the provided file "
316 		    "was not a user namespace file"));
317 	case EZFS_RESUME_EXISTS:
318 		return (dgettext(TEXT_DOMAIN, "Resuming recv on existing "
319 		    "dataset without force"));
320 	case EZFS_RAIDZ_EXPAND_IN_PROGRESS:
321 		return (dgettext(TEXT_DOMAIN, "raidz expansion in progress"));
322 	case EZFS_UNKNOWN:
323 		return (dgettext(TEXT_DOMAIN, "unknown error"));
324 	default:
325 		assert(hdl->libzfs_error == 0);
326 		return (dgettext(TEXT_DOMAIN, "no error"));
327 	}
328 }
329 
330 void
331 zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
332 {
333 	va_list ap;
334 
335 	va_start(ap, fmt);
336 
337 	(void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
338 	    fmt, ap);
339 	hdl->libzfs_desc_active = 1;
340 
341 	va_end(ap);
342 }
343 
344 static void
345 zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
346 {
347 	(void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
348 	    fmt, ap);
349 	hdl->libzfs_error = error;
350 
351 	if (hdl->libzfs_desc_active)
352 		hdl->libzfs_desc_active = 0;
353 	else
354 		hdl->libzfs_desc[0] = '\0';
355 
356 	if (hdl->libzfs_printerr) {
357 		if (error == EZFS_UNKNOWN) {
358 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
359 			    "error: %s: %s\n"), hdl->libzfs_action,
360 			    libzfs_error_description(hdl));
361 			abort();
362 		}
363 
364 		(void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
365 		    libzfs_error_description(hdl));
366 		if (error == EZFS_NOMEM)
367 			exit(1);
368 	}
369 }
370 
371 int
372 zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
373 {
374 	return (zfs_error_fmt(hdl, error, "%s", msg));
375 }
376 
377 int
378 zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
379 {
380 	va_list ap;
381 
382 	va_start(ap, fmt);
383 
384 	zfs_verror(hdl, error, fmt, ap);
385 
386 	va_end(ap);
387 
388 	return (-1);
389 }
390 
391 static int
392 zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
393     va_list ap)
394 {
395 	switch (error) {
396 	case EPERM:
397 	case EACCES:
398 		zfs_verror(hdl, EZFS_PERM, fmt, ap);
399 		return (-1);
400 
401 	case ECANCELED:
402 		zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
403 		return (-1);
404 
405 	case EIO:
406 		zfs_verror(hdl, EZFS_IO, fmt, ap);
407 		return (-1);
408 
409 	case EFAULT:
410 		zfs_verror(hdl, EZFS_FAULT, fmt, ap);
411 		return (-1);
412 
413 	case EINTR:
414 		zfs_verror(hdl, EZFS_INTR, fmt, ap);
415 		return (-1);
416 
417 	case ECKSUM:
418 		zfs_verror(hdl, EZFS_CKSUM, fmt, ap);
419 		return (-1);
420 	}
421 
422 	return (0);
423 }
424 
425 int
426 zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
427 {
428 	return (zfs_standard_error_fmt(hdl, error, "%s", msg));
429 }
430 
431 int
432 zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
433 {
434 	va_list ap;
435 
436 	va_start(ap, fmt);
437 
438 	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
439 		va_end(ap);
440 		return (-1);
441 	}
442 
443 	switch (error) {
444 	case ENXIO:
445 	case ENODEV:
446 	case EPIPE:
447 		zfs_verror(hdl, EZFS_IO, fmt, ap);
448 		break;
449 
450 	case ENOENT:
451 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
452 		    "dataset does not exist"));
453 		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
454 		break;
455 
456 	case ENOSPC:
457 	case EDQUOT:
458 		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
459 		break;
460 
461 	case EEXIST:
462 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
463 		    "dataset already exists"));
464 		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
465 		break;
466 
467 	case EBUSY:
468 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
469 		    "dataset is busy"));
470 		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
471 		break;
472 	case EROFS:
473 		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
474 		break;
475 	case ENAMETOOLONG:
476 		zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
477 		break;
478 	case ENOTSUP:
479 		zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
480 		break;
481 	case EAGAIN:
482 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
483 		    "pool I/O is currently suspended"));
484 		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
485 		break;
486 	case EREMOTEIO:
487 		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
488 		break;
489 	case ZFS_ERR_UNKNOWN_SEND_STREAM_FEATURE:
490 	case ZFS_ERR_IOC_CMD_UNAVAIL:
491 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
492 		    "module does not support this operation. A reboot may "
493 		    "be required to enable this operation."));
494 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
495 		break;
496 	case ZFS_ERR_IOC_ARG_UNAVAIL:
497 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
498 		    "module does not support an option for this operation. "
499 		    "A reboot may be required to enable this option."));
500 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
501 		break;
502 	case ZFS_ERR_IOC_ARG_REQUIRED:
503 	case ZFS_ERR_IOC_ARG_BADTYPE:
504 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
505 		break;
506 	case ZFS_ERR_WRONG_PARENT:
507 		zfs_verror(hdl, EZFS_WRONG_PARENT, fmt, ap);
508 		break;
509 	case ZFS_ERR_BADPROP:
510 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
511 		break;
512 	case ZFS_ERR_NOT_USER_NAMESPACE:
513 		zfs_verror(hdl, EZFS_NOT_USER_NAMESPACE, fmt, ap);
514 		break;
515 	default:
516 		zfs_error_aux(hdl, "%s", zfs_strerror(error));
517 		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
518 		break;
519 	}
520 
521 	va_end(ap);
522 	return (-1);
523 }
524 
525 void
526 zfs_setprop_error(libzfs_handle_t *hdl, zfs_prop_t prop, int err,
527     char *errbuf)
528 {
529 	switch (err) {
530 
531 	case ENOSPC:
532 		/*
533 		 * For quotas and reservations, ENOSPC indicates
534 		 * something different; setting a quota or reservation
535 		 * doesn't use any disk space.
536 		 */
537 		switch (prop) {
538 		case ZFS_PROP_QUOTA:
539 		case ZFS_PROP_REFQUOTA:
540 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
541 			    "size is less than current used or "
542 			    "reserved space"));
543 			(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
544 			break;
545 
546 		case ZFS_PROP_RESERVATION:
547 		case ZFS_PROP_REFRESERVATION:
548 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
549 			    "size is greater than available space"));
550 			(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
551 			break;
552 
553 		default:
554 			(void) zfs_standard_error(hdl, err, errbuf);
555 			break;
556 		}
557 		break;
558 
559 	case EBUSY:
560 		(void) zfs_standard_error(hdl, EBUSY, errbuf);
561 		break;
562 
563 	case EROFS:
564 		(void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
565 		break;
566 
567 	case E2BIG:
568 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
569 		    "property value too long"));
570 		(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
571 		break;
572 
573 	case ENOTSUP:
574 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
575 		    "pool and or dataset must be upgraded to set this "
576 		    "property or value"));
577 		(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
578 		break;
579 
580 	case ERANGE:
581 		if (prop == ZFS_PROP_COMPRESSION ||
582 		    prop == ZFS_PROP_DNODESIZE ||
583 		    prop == ZFS_PROP_RECORDSIZE) {
584 			(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
585 			    "property setting is not allowed on "
586 			    "bootable datasets"));
587 			(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
588 		} else if (prop == ZFS_PROP_CHECKSUM ||
589 		    prop == ZFS_PROP_DEDUP) {
590 			(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
591 			    "property setting is not allowed on "
592 			    "root pools"));
593 			(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
594 		} else {
595 			(void) zfs_standard_error(hdl, err, errbuf);
596 		}
597 		break;
598 
599 	case EINVAL:
600 		if (prop == ZPROP_INVAL) {
601 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
602 		} else {
603 			(void) zfs_standard_error(hdl, err, errbuf);
604 		}
605 		break;
606 
607 	case ZFS_ERR_BADPROP:
608 		(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
609 		break;
610 
611 	case EACCES:
612 		if (prop == ZFS_PROP_KEYLOCATION) {
613 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
614 			    "keylocation may only be set on encryption roots"));
615 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
616 		} else {
617 			(void) zfs_standard_error(hdl, err, errbuf);
618 		}
619 		break;
620 
621 	case EOVERFLOW:
622 		/*
623 		 * This platform can't address a volume this big.
624 		 */
625 #ifdef _ILP32
626 		if (prop == ZFS_PROP_VOLSIZE) {
627 			(void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
628 			break;
629 		}
630 		zfs_fallthrough;
631 #endif
632 	default:
633 		(void) zfs_standard_error(hdl, err, errbuf);
634 	}
635 }
636 
637 int
638 zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
639 {
640 	return (zpool_standard_error_fmt(hdl, error, "%s", msg));
641 }
642 
643 int
644 zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
645 {
646 	va_list ap;
647 
648 	va_start(ap, fmt);
649 
650 	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
651 		va_end(ap);
652 		return (-1);
653 	}
654 
655 	switch (error) {
656 	case ENODEV:
657 		zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
658 		break;
659 
660 	case ENOENT:
661 		zfs_error_aux(hdl,
662 		    dgettext(TEXT_DOMAIN, "no such pool or dataset"));
663 		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
664 		break;
665 
666 	case EEXIST:
667 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
668 		    "pool already exists"));
669 		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
670 		break;
671 
672 	case EBUSY:
673 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
674 		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
675 		break;
676 
677 	/* There is no pending operation to cancel */
678 	case ENOTACTIVE:
679 		zfs_verror(hdl, EZFS_NO_PENDING, fmt, ap);
680 		break;
681 
682 	case ENXIO:
683 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
684 		    "one or more devices is currently unavailable"));
685 		zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
686 		break;
687 
688 	case ENAMETOOLONG:
689 		zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
690 		break;
691 
692 	case ENOTSUP:
693 		zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
694 		break;
695 
696 	case EINVAL:
697 		zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
698 		break;
699 
700 	case ENOSPC:
701 	case EDQUOT:
702 		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
703 		break;
704 
705 	case EAGAIN:
706 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
707 		    "pool I/O is currently suspended"));
708 		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
709 		break;
710 
711 	case EROFS:
712 		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
713 		break;
714 	case EDOM:
715 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
716 		    "block size out of range or does not match"));
717 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
718 		break;
719 	case EREMOTEIO:
720 		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
721 		break;
722 	case ZFS_ERR_CHECKPOINT_EXISTS:
723 		zfs_verror(hdl, EZFS_CHECKPOINT_EXISTS, fmt, ap);
724 		break;
725 	case ZFS_ERR_DISCARDING_CHECKPOINT:
726 		zfs_verror(hdl, EZFS_DISCARDING_CHECKPOINT, fmt, ap);
727 		break;
728 	case ZFS_ERR_NO_CHECKPOINT:
729 		zfs_verror(hdl, EZFS_NO_CHECKPOINT, fmt, ap);
730 		break;
731 	case ZFS_ERR_DEVRM_IN_PROGRESS:
732 		zfs_verror(hdl, EZFS_DEVRM_IN_PROGRESS, fmt, ap);
733 		break;
734 	case ZFS_ERR_VDEV_TOO_BIG:
735 		zfs_verror(hdl, EZFS_VDEV_TOO_BIG, fmt, ap);
736 		break;
737 	case ZFS_ERR_EXPORT_IN_PROGRESS:
738 		zfs_verror(hdl, EZFS_EXPORT_IN_PROGRESS, fmt, ap);
739 		break;
740 	case ZFS_ERR_RESILVER_IN_PROGRESS:
741 		zfs_verror(hdl, EZFS_RESILVERING, fmt, ap);
742 		break;
743 	case ZFS_ERR_REBUILD_IN_PROGRESS:
744 		zfs_verror(hdl, EZFS_REBUILDING, fmt, ap);
745 		break;
746 	case ZFS_ERR_BADPROP:
747 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
748 		break;
749 	case ZFS_ERR_VDEV_NOTSUP:
750 		zfs_verror(hdl, EZFS_VDEV_NOTSUP, fmt, ap);
751 		break;
752 	case ZFS_ERR_IOC_CMD_UNAVAIL:
753 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
754 		    "module does not support this operation. A reboot may "
755 		    "be required to enable this operation."));
756 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
757 		break;
758 	case ZFS_ERR_IOC_ARG_UNAVAIL:
759 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
760 		    "module does not support an option for this operation. "
761 		    "A reboot may be required to enable this option."));
762 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
763 		break;
764 	case ZFS_ERR_IOC_ARG_REQUIRED:
765 	case ZFS_ERR_IOC_ARG_BADTYPE:
766 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
767 		break;
768 	case ZFS_ERR_RAIDZ_EXPAND_IN_PROGRESS:
769 		zfs_verror(hdl, EZFS_RAIDZ_EXPAND_IN_PROGRESS, fmt, ap);
770 		break;
771 	default:
772 		zfs_error_aux(hdl, "%s", zfs_strerror(error));
773 		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
774 	}
775 
776 	va_end(ap);
777 	return (-1);
778 }
779 
780 /*
781  * Display an out of memory error message and abort the current program.
782  */
783 int
784 no_memory(libzfs_handle_t *hdl)
785 {
786 	return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
787 }
788 
789 /*
790  * A safe form of malloc() which will die if the allocation fails.
791  */
792 void *
793 zfs_alloc(libzfs_handle_t *hdl, size_t size)
794 {
795 	void *data;
796 
797 	if ((data = calloc(1, size)) == NULL)
798 		(void) no_memory(hdl);
799 
800 	return (data);
801 }
802 
803 /*
804  * A safe form of asprintf() which will die if the allocation fails.
805  */
806 char *
807 zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
808 {
809 	va_list ap;
810 	char *ret;
811 	int err;
812 
813 	va_start(ap, fmt);
814 
815 	err = vasprintf(&ret, fmt, ap);
816 
817 	va_end(ap);
818 
819 	if (err < 0) {
820 		(void) no_memory(hdl);
821 		ret = NULL;
822 	}
823 
824 	return (ret);
825 }
826 
827 /*
828  * A safe form of realloc(), which also zeroes newly allocated space.
829  */
830 void *
831 zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
832 {
833 	void *ret;
834 
835 	if ((ret = realloc(ptr, newsize)) == NULL) {
836 		(void) no_memory(hdl);
837 		return (NULL);
838 	}
839 
840 	memset((char *)ret + oldsize, 0, newsize - oldsize);
841 	return (ret);
842 }
843 
844 /*
845  * A safe form of strdup() which will die if the allocation fails.
846  */
847 char *
848 zfs_strdup(libzfs_handle_t *hdl, const char *str)
849 {
850 	char *ret;
851 
852 	if ((ret = strdup(str)) == NULL)
853 		(void) no_memory(hdl);
854 
855 	return (ret);
856 }
857 
858 void
859 libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
860 {
861 	hdl->libzfs_printerr = printerr;
862 }
863 
864 /*
865  * Read lines from an open file descriptor and store them in an array of
866  * strings until EOF.  lines[] will be allocated and populated with all the
867  * lines read.  All newlines are replaced with NULL terminators for
868  * convenience.  lines[] must be freed after use with libzfs_free_str_array().
869  *
870  * Returns the number of lines read.
871  */
872 static int
873 libzfs_read_stdout_from_fd(int fd, char **lines[])
874 {
875 
876 	FILE *fp;
877 	int lines_cnt = 0;
878 	size_t len = 0;
879 	char *line = NULL;
880 	char **tmp_lines = NULL, **tmp;
881 
882 	fp = fdopen(fd, "r");
883 	if (fp == NULL) {
884 		close(fd);
885 		return (0);
886 	}
887 	while (getline(&line, &len, fp) != -1) {
888 		tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
889 		if (tmp == NULL) {
890 			/* Return the lines we were able to process */
891 			break;
892 		}
893 		tmp_lines = tmp;
894 
895 		/* Remove newline if not EOF */
896 		if (line[strlen(line) - 1] == '\n')
897 			line[strlen(line) - 1] = '\0';
898 
899 		tmp_lines[lines_cnt] = strdup(line);
900 		if (tmp_lines[lines_cnt] == NULL)
901 			break;
902 		++lines_cnt;
903 	}
904 	free(line);
905 	fclose(fp);
906 	*lines = tmp_lines;
907 	return (lines_cnt);
908 }
909 
910 static int
911 libzfs_run_process_impl(const char *path, char *argv[], char *env[], int flags,
912     char **lines[], int *lines_cnt)
913 {
914 	pid_t pid;
915 	int error, devnull_fd;
916 	int link[2];
917 
918 	/*
919 	 * Setup a pipe between our child and parent process if we're
920 	 * reading stdout.
921 	 */
922 	if (lines != NULL && pipe2(link, O_NONBLOCK | O_CLOEXEC) == -1)
923 		return (-EPIPE);
924 
925 	pid = fork();
926 	if (pid == 0) {
927 		/* Child process */
928 		devnull_fd = open("/dev/null", O_WRONLY | O_CLOEXEC);
929 
930 		if (devnull_fd < 0)
931 			_exit(-1);
932 
933 		if (!(flags & STDOUT_VERBOSE) && (lines == NULL))
934 			(void) dup2(devnull_fd, STDOUT_FILENO);
935 		else if (lines != NULL) {
936 			/* Save the output to lines[] */
937 			dup2(link[1], STDOUT_FILENO);
938 		}
939 
940 		if (!(flags & STDERR_VERBOSE))
941 			(void) dup2(devnull_fd, STDERR_FILENO);
942 
943 		if (flags & NO_DEFAULT_PATH) {
944 			if (env == NULL)
945 				execv(path, argv);
946 			else
947 				execve(path, argv, env);
948 		} else {
949 			if (env == NULL)
950 				execvp(path, argv);
951 			else
952 				execvpe(path, argv, env);
953 		}
954 
955 		_exit(-1);
956 	} else if (pid > 0) {
957 		/* Parent process */
958 		int status;
959 
960 		while ((error = waitpid(pid, &status, 0)) == -1 &&
961 		    errno == EINTR)
962 			;
963 		if (error < 0 || !WIFEXITED(status))
964 			return (-1);
965 
966 		if (lines != NULL) {
967 			close(link[1]);
968 			*lines_cnt = libzfs_read_stdout_from_fd(link[0], lines);
969 		}
970 		return (WEXITSTATUS(status));
971 	}
972 
973 	return (-1);
974 }
975 
976 int
977 libzfs_run_process(const char *path, char *argv[], int flags)
978 {
979 	return (libzfs_run_process_impl(path, argv, NULL, flags, NULL, NULL));
980 }
981 
982 /*
983  * Run a command and store its stdout lines in an array of strings (lines[]).
984  * lines[] is allocated and populated for you, and the number of lines is set in
985  * lines_cnt.  lines[] must be freed after use with libzfs_free_str_array().
986  * All newlines (\n) in lines[] are terminated for convenience.
987  */
988 int
989 libzfs_run_process_get_stdout(const char *path, char *argv[], char *env[],
990     char **lines[], int *lines_cnt)
991 {
992 	return (libzfs_run_process_impl(path, argv, env, 0, lines, lines_cnt));
993 }
994 
995 /*
996  * Same as libzfs_run_process_get_stdout(), but run without $PATH set.  This
997  * means that *path needs to be the full path to the executable.
998  */
999 int
1000 libzfs_run_process_get_stdout_nopath(const char *path, char *argv[],
1001     char *env[], char **lines[], int *lines_cnt)
1002 {
1003 	return (libzfs_run_process_impl(path, argv, env, NO_DEFAULT_PATH,
1004 	    lines, lines_cnt));
1005 }
1006 
1007 /*
1008  * Free an array of strings.  Free both the strings contained in the array and
1009  * the array itself.
1010  */
1011 void
1012 libzfs_free_str_array(char **strs, int count)
1013 {
1014 	while (--count >= 0)
1015 		free(strs[count]);
1016 
1017 	free(strs);
1018 }
1019 
1020 /*
1021  * Returns 1 if environment variable is set to "YES", "yes", "ON", "on", or
1022  * a non-zero number.
1023  *
1024  * Returns 0 otherwise.
1025  */
1026 boolean_t
1027 libzfs_envvar_is_set(const char *envvar)
1028 {
1029 	char *env = getenv(envvar);
1030 	return (env && (strtoul(env, NULL, 0) > 0 ||
1031 	    (!strncasecmp(env, "YES", 3) && strnlen(env, 4) == 3) ||
1032 	    (!strncasecmp(env, "ON", 2) && strnlen(env, 3) == 2)));
1033 }
1034 
1035 libzfs_handle_t *
1036 libzfs_init(void)
1037 {
1038 	libzfs_handle_t *hdl;
1039 	int error;
1040 	char *env;
1041 
1042 	if ((error = libzfs_load_module()) != 0) {
1043 		errno = error;
1044 		return (NULL);
1045 	}
1046 
1047 	if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
1048 		return (NULL);
1049 	}
1050 
1051 	if (regcomp(&hdl->libzfs_urire, URI_REGEX, 0) != 0) {
1052 		free(hdl);
1053 		return (NULL);
1054 	}
1055 
1056 	if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR|O_EXCL|O_CLOEXEC)) < 0) {
1057 		free(hdl);
1058 		return (NULL);
1059 	}
1060 
1061 	if (libzfs_core_init() != 0) {
1062 		(void) close(hdl->libzfs_fd);
1063 		free(hdl);
1064 		return (NULL);
1065 	}
1066 
1067 	zfs_prop_init();
1068 	zpool_prop_init();
1069 	zpool_feature_init();
1070 	vdev_prop_init();
1071 	libzfs_mnttab_init(hdl);
1072 	fletcher_4_init();
1073 
1074 	if (getenv("ZFS_PROP_DEBUG") != NULL) {
1075 		hdl->libzfs_prop_debug = B_TRUE;
1076 	}
1077 	if ((env = getenv("ZFS_SENDRECV_MAX_NVLIST")) != NULL) {
1078 		if ((error = zfs_nicestrtonum(hdl, env,
1079 		    &hdl->libzfs_max_nvlist))) {
1080 			errno = error;
1081 			(void) close(hdl->libzfs_fd);
1082 			free(hdl);
1083 			return (NULL);
1084 		}
1085 	} else {
1086 		hdl->libzfs_max_nvlist = (SPA_MAXBLOCKSIZE * 4);
1087 	}
1088 
1089 	/*
1090 	 * For testing, remove some settable properties and features
1091 	 */
1092 	if (libzfs_envvar_is_set("ZFS_SYSFS_PROP_SUPPORT_TEST")) {
1093 		zprop_desc_t *proptbl;
1094 
1095 		proptbl = zpool_prop_get_table();
1096 		proptbl[ZPOOL_PROP_COMMENT].pd_zfs_mod_supported = B_FALSE;
1097 
1098 		proptbl = zfs_prop_get_table();
1099 		proptbl[ZFS_PROP_DNODESIZE].pd_zfs_mod_supported = B_FALSE;
1100 
1101 		zfeature_info_t *ftbl = spa_feature_table;
1102 		ftbl[SPA_FEATURE_LARGE_BLOCKS].fi_zfs_mod_supported = B_FALSE;
1103 	}
1104 
1105 	return (hdl);
1106 }
1107 
1108 void
1109 libzfs_fini(libzfs_handle_t *hdl)
1110 {
1111 	(void) close(hdl->libzfs_fd);
1112 	zpool_free_handles(hdl);
1113 	namespace_clear(hdl);
1114 	libzfs_mnttab_fini(hdl);
1115 	libzfs_core_fini();
1116 	regfree(&hdl->libzfs_urire);
1117 	fletcher_4_fini();
1118 #if LIBFETCH_DYNAMIC
1119 	if (hdl->libfetch != (void *)-1 && hdl->libfetch != NULL)
1120 		(void) dlclose(hdl->libfetch);
1121 	free(hdl->libfetch_load_error);
1122 #endif
1123 	free(hdl);
1124 }
1125 
1126 libzfs_handle_t *
1127 zpool_get_handle(zpool_handle_t *zhp)
1128 {
1129 	return (zhp->zpool_hdl);
1130 }
1131 
1132 libzfs_handle_t *
1133 zfs_get_handle(zfs_handle_t *zhp)
1134 {
1135 	return (zhp->zfs_hdl);
1136 }
1137 
1138 zpool_handle_t *
1139 zfs_get_pool_handle(const zfs_handle_t *zhp)
1140 {
1141 	return (zhp->zpool_hdl);
1142 }
1143 
1144 /*
1145  * Given a name, determine whether or not it's a valid path
1146  * (starts with '/' or "./").  If so, walk the mnttab trying
1147  * to match the device number.  If not, treat the path as an
1148  * fs/vol/snap/bkmark name.
1149  */
1150 zfs_handle_t *
1151 zfs_path_to_zhandle(libzfs_handle_t *hdl, const char *path, zfs_type_t argtype)
1152 {
1153 	struct stat64 statbuf;
1154 	struct extmnttab entry;
1155 
1156 	if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1157 		/*
1158 		 * It's not a valid path, assume it's a name of type 'argtype'.
1159 		 */
1160 		return (zfs_open(hdl, path, argtype));
1161 	}
1162 
1163 	if (getextmntent(path, &entry, &statbuf) != 0)
1164 		return (NULL);
1165 
1166 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1167 		(void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1168 		    path);
1169 		return (NULL);
1170 	}
1171 
1172 	return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1173 }
1174 
1175 /*
1176  * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1177  * an ioctl().
1178  */
1179 void
1180 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1181 {
1182 	if (len == 0)
1183 		len = 256 * 1024;
1184 	zc->zc_nvlist_dst_size = len;
1185 	zc->zc_nvlist_dst =
1186 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1187 }
1188 
1189 /*
1190  * Called when an ioctl() which returns an nvlist fails with ENOMEM.  This will
1191  * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1192  * filled in by the kernel to indicate the actual required size.
1193  */
1194 void
1195 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1196 {
1197 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
1198 	zc->zc_nvlist_dst =
1199 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1200 }
1201 
1202 /*
1203  * Called to free the src and dst nvlists stored in the command structure.
1204  */
1205 void
1206 zcmd_free_nvlists(zfs_cmd_t *zc)
1207 {
1208 	free((void *)(uintptr_t)zc->zc_nvlist_conf);
1209 	free((void *)(uintptr_t)zc->zc_nvlist_src);
1210 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
1211 	zc->zc_nvlist_conf = 0;
1212 	zc->zc_nvlist_src = 0;
1213 	zc->zc_nvlist_dst = 0;
1214 }
1215 
1216 static void
1217 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1218     nvlist_t *nvl)
1219 {
1220 	char *packed;
1221 
1222 	size_t len = fnvlist_size(nvl);
1223 	packed = zfs_alloc(hdl, len);
1224 
1225 	verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1226 
1227 	*outnv = (uint64_t)(uintptr_t)packed;
1228 	*outlen = len;
1229 }
1230 
1231 void
1232 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1233 {
1234 	zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1235 	    &zc->zc_nvlist_conf_size, nvl);
1236 }
1237 
1238 void
1239 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1240 {
1241 	zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1242 	    &zc->zc_nvlist_src_size, nvl);
1243 }
1244 
1245 /*
1246  * Unpacks an nvlist from the ZFS ioctl command structure.
1247  */
1248 int
1249 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1250 {
1251 	if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1252 	    zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1253 		return (no_memory(hdl));
1254 
1255 	return (0);
1256 }
1257 
1258 /*
1259  * ================================================================
1260  * API shared by zfs and zpool property management
1261  * ================================================================
1262  */
1263 
1264 static void
1265 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1266 {
1267 	zprop_list_t *pl;
1268 	int i;
1269 	char *title;
1270 	size_t len;
1271 
1272 	cbp->cb_first = B_FALSE;
1273 	if (cbp->cb_scripted)
1274 		return;
1275 
1276 	/*
1277 	 * Start with the length of the column headers.
1278 	 */
1279 	cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1280 	cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1281 	    "PROPERTY"));
1282 	cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1283 	    "VALUE"));
1284 	cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1285 	    "RECEIVED"));
1286 	cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1287 	    "SOURCE"));
1288 
1289 	/* first property is always NAME */
1290 	assert(cbp->cb_proplist->pl_prop ==
1291 	    ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1292 	    ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME)));
1293 
1294 	/*
1295 	 * Go through and calculate the widths for each column.  For the
1296 	 * 'source' column, we kludge it up by taking the worst-case scenario of
1297 	 * inheriting from the longest name.  This is acceptable because in the
1298 	 * majority of cases 'SOURCE' is the last column displayed, and we don't
1299 	 * use the width anyway.  Note that the 'VALUE' column can be oversized,
1300 	 * if the name of the property is much longer than any values we find.
1301 	 */
1302 	for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1303 		/*
1304 		 * 'PROPERTY' column
1305 		 */
1306 		if (pl->pl_prop != ZPROP_USERPROP) {
1307 			const char *propname = (type == ZFS_TYPE_POOL) ?
1308 			    zpool_prop_to_name(pl->pl_prop) :
1309 			    ((type == ZFS_TYPE_VDEV) ?
1310 			    vdev_prop_to_name(pl->pl_prop) :
1311 			    zfs_prop_to_name(pl->pl_prop));
1312 
1313 			assert(propname != NULL);
1314 			len = strlen(propname);
1315 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1316 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1317 		} else {
1318 			assert(pl->pl_user_prop != NULL);
1319 			len = strlen(pl->pl_user_prop);
1320 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1321 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1322 		}
1323 
1324 		/*
1325 		 * 'VALUE' column.  The first property is always the 'name'
1326 		 * property that was tacked on either by /sbin/zfs's
1327 		 * zfs_do_get() or when calling zprop_expand_list(), so we
1328 		 * ignore its width.  If the user specified the name property
1329 		 * to display, then it will be later in the list in any case.
1330 		 */
1331 		if (pl != cbp->cb_proplist &&
1332 		    pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1333 			cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1334 
1335 		/* 'RECEIVED' column. */
1336 		if (pl != cbp->cb_proplist &&
1337 		    pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1338 			cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1339 
1340 		/*
1341 		 * 'NAME' and 'SOURCE' columns
1342 		 */
1343 		if (pl->pl_prop == ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1344 		    ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME :
1345 		    ZFS_PROP_NAME)) && pl->pl_width >
1346 		    cbp->cb_colwidths[GET_COL_NAME]) {
1347 			cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1348 			cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1349 			    strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1350 		}
1351 	}
1352 
1353 	/*
1354 	 * Now go through and print the headers.
1355 	 */
1356 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1357 		switch (cbp->cb_columns[i]) {
1358 		case GET_COL_NAME:
1359 			title = dgettext(TEXT_DOMAIN, "NAME");
1360 			break;
1361 		case GET_COL_PROPERTY:
1362 			title = dgettext(TEXT_DOMAIN, "PROPERTY");
1363 			break;
1364 		case GET_COL_VALUE:
1365 			title = dgettext(TEXT_DOMAIN, "VALUE");
1366 			break;
1367 		case GET_COL_RECVD:
1368 			title = dgettext(TEXT_DOMAIN, "RECEIVED");
1369 			break;
1370 		case GET_COL_SOURCE:
1371 			title = dgettext(TEXT_DOMAIN, "SOURCE");
1372 			break;
1373 		default:
1374 			title = NULL;
1375 		}
1376 
1377 		if (title != NULL) {
1378 			if (i == (ZFS_GET_NCOLS - 1) ||
1379 			    cbp->cb_columns[i + 1] == GET_COL_NONE)
1380 				(void) printf("%s", title);
1381 			else
1382 				(void) printf("%-*s  ",
1383 				    cbp->cb_colwidths[cbp->cb_columns[i]],
1384 				    title);
1385 		}
1386 	}
1387 	(void) printf("\n");
1388 }
1389 
1390 /*
1391  * Display a single line of output, according to the settings in the callback
1392  * structure.
1393  */
1394 void
1395 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1396     const char *propname, const char *value, zprop_source_t sourcetype,
1397     const char *source, const char *recvd_value)
1398 {
1399 	int i;
1400 	const char *str = NULL;
1401 	char buf[128];
1402 
1403 	/*
1404 	 * Ignore those source types that the user has chosen to ignore.
1405 	 */
1406 	if ((sourcetype & cbp->cb_sources) == 0)
1407 		return;
1408 
1409 	if (cbp->cb_first)
1410 		zprop_print_headers(cbp, cbp->cb_type);
1411 
1412 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1413 		switch (cbp->cb_columns[i]) {
1414 		case GET_COL_NAME:
1415 			str = name;
1416 			break;
1417 
1418 		case GET_COL_PROPERTY:
1419 			str = propname;
1420 			break;
1421 
1422 		case GET_COL_VALUE:
1423 			str = value;
1424 			break;
1425 
1426 		case GET_COL_SOURCE:
1427 			switch (sourcetype) {
1428 			case ZPROP_SRC_NONE:
1429 				str = "-";
1430 				break;
1431 
1432 			case ZPROP_SRC_DEFAULT:
1433 				str = "default";
1434 				break;
1435 
1436 			case ZPROP_SRC_LOCAL:
1437 				str = "local";
1438 				break;
1439 
1440 			case ZPROP_SRC_TEMPORARY:
1441 				str = "temporary";
1442 				break;
1443 
1444 			case ZPROP_SRC_INHERITED:
1445 				(void) snprintf(buf, sizeof (buf),
1446 				    "inherited from %s", source);
1447 				str = buf;
1448 				break;
1449 			case ZPROP_SRC_RECEIVED:
1450 				str = "received";
1451 				break;
1452 
1453 			default:
1454 				str = NULL;
1455 				assert(!"unhandled zprop_source_t");
1456 			}
1457 			break;
1458 
1459 		case GET_COL_RECVD:
1460 			str = (recvd_value == NULL ? "-" : recvd_value);
1461 			break;
1462 
1463 		default:
1464 			continue;
1465 		}
1466 
1467 		if (i == (ZFS_GET_NCOLS - 1) ||
1468 		    cbp->cb_columns[i + 1] == GET_COL_NONE)
1469 			(void) printf("%s", str);
1470 		else if (cbp->cb_scripted)
1471 			(void) printf("%s\t", str);
1472 		else
1473 			(void) printf("%-*s  ",
1474 			    cbp->cb_colwidths[cbp->cb_columns[i]],
1475 			    str);
1476 	}
1477 
1478 	(void) printf("\n");
1479 }
1480 
1481 /*
1482  * Given a numeric suffix, convert the value into a number of bits that the
1483  * resulting value must be shifted.
1484  */
1485 static int
1486 str2shift(libzfs_handle_t *hdl, const char *buf)
1487 {
1488 	const char *ends = "BKMGTPEZ";
1489 	int i;
1490 
1491 	if (buf[0] == '\0')
1492 		return (0);
1493 	for (i = 0; i < strlen(ends); i++) {
1494 		if (toupper(buf[0]) == ends[i])
1495 			break;
1496 	}
1497 	if (i == strlen(ends)) {
1498 		if (hdl)
1499 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1500 			    "invalid numeric suffix '%s'"), buf);
1501 		return (-1);
1502 	}
1503 
1504 	/*
1505 	 * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1506 	 * However, 'BB' and 'BiB' are disallowed.
1507 	 */
1508 	if (buf[1] == '\0' ||
1509 	    (toupper(buf[0]) != 'B' &&
1510 	    ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1511 	    (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1512 	    buf[3] == '\0'))))
1513 		return (10 * i);
1514 
1515 	if (hdl)
1516 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1517 		    "invalid numeric suffix '%s'"), buf);
1518 	return (-1);
1519 }
1520 
1521 /*
1522  * Convert a string of the form '100G' into a real number.  Used when setting
1523  * properties or creating a volume.  'buf' is used to place an extended error
1524  * message for the caller to use.
1525  */
1526 int
1527 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1528 {
1529 	char *end;
1530 	int shift;
1531 
1532 	*num = 0;
1533 
1534 	/* Check to see if this looks like a number.  */
1535 	if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1536 		if (hdl)
1537 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1538 			    "bad numeric value '%s'"), value);
1539 		return (-1);
1540 	}
1541 
1542 	/* Rely on strtoull() to process the numeric portion.  */
1543 	errno = 0;
1544 	*num = strtoull(value, &end, 10);
1545 
1546 	/*
1547 	 * Check for ERANGE, which indicates that the value is too large to fit
1548 	 * in a 64-bit value.
1549 	 */
1550 	if (errno == ERANGE) {
1551 		if (hdl)
1552 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1553 			    "numeric value is too large"));
1554 		return (-1);
1555 	}
1556 
1557 	/*
1558 	 * If we have a decimal value, then do the computation with floating
1559 	 * point arithmetic.  Otherwise, use standard arithmetic.
1560 	 */
1561 	if (*end == '.') {
1562 		double fval = strtod(value, &end);
1563 
1564 		if ((shift = str2shift(hdl, end)) == -1)
1565 			return (-1);
1566 
1567 		fval *= pow(2, shift);
1568 
1569 		/*
1570 		 * UINT64_MAX is not exactly representable as a double.
1571 		 * The closest representation is UINT64_MAX + 1, so we
1572 		 * use a >= comparison instead of > for the bounds check.
1573 		 */
1574 		if (fval >= (double)UINT64_MAX) {
1575 			if (hdl)
1576 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1577 				    "numeric value is too large"));
1578 			return (-1);
1579 		}
1580 
1581 		*num = (uint64_t)fval;
1582 	} else {
1583 		if ((shift = str2shift(hdl, end)) == -1)
1584 			return (-1);
1585 
1586 		/* Check for overflow */
1587 		if (shift >= 64 || (*num << shift) >> shift != *num) {
1588 			if (hdl)
1589 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1590 				    "numeric value is too large"));
1591 			return (-1);
1592 		}
1593 
1594 		*num <<= shift;
1595 	}
1596 
1597 	return (0);
1598 }
1599 
1600 /*
1601  * Given a propname=value nvpair to set, parse any numeric properties
1602  * (index, boolean, etc) if they are specified as strings and add the
1603  * resulting nvpair to the returned nvlist.
1604  *
1605  * At the DSL layer, all properties are either 64-bit numbers or strings.
1606  * We want the user to be able to ignore this fact and specify properties
1607  * as native values (numbers, for example) or as strings (to simplify
1608  * command line utilities).  This also handles converting index types
1609  * (compression, checksum, etc) from strings to their on-disk index.
1610  */
1611 int
1612 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1613     zfs_type_t type, nvlist_t *ret, const char **svalp, uint64_t *ivalp,
1614     const char *errbuf)
1615 {
1616 	data_type_t datatype = nvpair_type(elem);
1617 	zprop_type_t proptype;
1618 	const char *propname;
1619 	const char *value;
1620 	boolean_t isnone = B_FALSE;
1621 	boolean_t isauto = B_FALSE;
1622 	int err = 0;
1623 
1624 	if (type == ZFS_TYPE_POOL) {
1625 		proptype = zpool_prop_get_type(prop);
1626 		propname = zpool_prop_to_name(prop);
1627 	} else if (type == ZFS_TYPE_VDEV) {
1628 		proptype = vdev_prop_get_type(prop);
1629 		propname = vdev_prop_to_name(prop);
1630 	} else {
1631 		proptype = zfs_prop_get_type(prop);
1632 		propname = zfs_prop_to_name(prop);
1633 	}
1634 
1635 	/*
1636 	 * Convert any properties to the internal DSL value types.
1637 	 */
1638 	*svalp = NULL;
1639 	*ivalp = 0;
1640 
1641 	switch (proptype) {
1642 	case PROP_TYPE_STRING:
1643 		if (datatype != DATA_TYPE_STRING) {
1644 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1645 			    "'%s' must be a string"), nvpair_name(elem));
1646 			goto error;
1647 		}
1648 		err = nvpair_value_string(elem, svalp);
1649 		if (err != 0) {
1650 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1651 			    "'%s' is invalid"), nvpair_name(elem));
1652 			goto error;
1653 		}
1654 		if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1655 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1656 			    "'%s' is too long"), nvpair_name(elem));
1657 			goto error;
1658 		}
1659 		break;
1660 
1661 	case PROP_TYPE_NUMBER:
1662 		if (datatype == DATA_TYPE_STRING) {
1663 			(void) nvpair_value_string(elem, &value);
1664 			if (strcmp(value, "none") == 0) {
1665 				isnone = B_TRUE;
1666 			} else if (strcmp(value, "auto") == 0) {
1667 				isauto = B_TRUE;
1668 			} else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1669 				goto error;
1670 			}
1671 		} else if (datatype == DATA_TYPE_UINT64) {
1672 			(void) nvpair_value_uint64(elem, ivalp);
1673 		} else {
1674 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1675 			    "'%s' must be a number"), nvpair_name(elem));
1676 			goto error;
1677 		}
1678 
1679 		/*
1680 		 * Quota special: force 'none' and don't allow 0.
1681 		 */
1682 		if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1683 		    (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1684 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1685 			    "use 'none' to disable quota/refquota"));
1686 			goto error;
1687 		}
1688 
1689 		/*
1690 		 * Special handling for "*_limit=none". In this case it's not
1691 		 * 0 but UINT64_MAX.
1692 		 */
1693 		if ((type & ZFS_TYPE_DATASET) && isnone &&
1694 		    (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1695 		    prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1696 			*ivalp = UINT64_MAX;
1697 		}
1698 
1699 		/*
1700 		 * Special handling for "checksum_*=none". In this case it's not
1701 		 * 0 but UINT64_MAX.
1702 		 */
1703 		if ((type & ZFS_TYPE_VDEV) && isnone &&
1704 		    (prop == VDEV_PROP_CHECKSUM_N ||
1705 		    prop == VDEV_PROP_CHECKSUM_T ||
1706 		    prop == VDEV_PROP_IO_N ||
1707 		    prop == VDEV_PROP_IO_T ||
1708 		    prop == VDEV_PROP_SLOW_IO_N ||
1709 		    prop == VDEV_PROP_SLOW_IO_T)) {
1710 			*ivalp = UINT64_MAX;
1711 		}
1712 
1713 		/*
1714 		 * Special handling for setting 'refreservation' to 'auto'.  Use
1715 		 * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1716 		 * 'auto' is only allowed on volumes.
1717 		 */
1718 		if (isauto) {
1719 			switch (prop) {
1720 			case ZFS_PROP_REFRESERVATION:
1721 				if ((type & ZFS_TYPE_VOLUME) == 0) {
1722 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1723 					    "'%s=auto' only allowed on "
1724 					    "volumes"), nvpair_name(elem));
1725 					goto error;
1726 				}
1727 				*ivalp = UINT64_MAX;
1728 				break;
1729 			default:
1730 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1731 				    "'auto' is invalid value for '%s'"),
1732 				    nvpair_name(elem));
1733 				goto error;
1734 			}
1735 		}
1736 
1737 		break;
1738 
1739 	case PROP_TYPE_INDEX:
1740 		if (datatype != DATA_TYPE_STRING) {
1741 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1742 			    "'%s' must be a string"), nvpair_name(elem));
1743 			goto error;
1744 		}
1745 
1746 		(void) nvpair_value_string(elem, &value);
1747 
1748 		if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1749 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1750 			    "'%s' must be one of '%s'"), propname,
1751 			    zprop_values(prop, type));
1752 			goto error;
1753 		}
1754 		break;
1755 
1756 	default:
1757 		abort();
1758 	}
1759 
1760 	/*
1761 	 * Add the result to our return set of properties.
1762 	 */
1763 	if (*svalp != NULL) {
1764 		if (nvlist_add_string(ret, propname, *svalp) != 0) {
1765 			(void) no_memory(hdl);
1766 			return (-1);
1767 		}
1768 	} else {
1769 		if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1770 			(void) no_memory(hdl);
1771 			return (-1);
1772 		}
1773 	}
1774 
1775 	return (0);
1776 error:
1777 	(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1778 	return (-1);
1779 }
1780 
1781 static int
1782 addlist(libzfs_handle_t *hdl, const char *propname, zprop_list_t **listp,
1783     zfs_type_t type)
1784 {
1785 	int prop = zprop_name_to_prop(propname, type);
1786 	if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
1787 		prop = ZPROP_INVAL;
1788 
1789 	/*
1790 	 * Return failure if no property table entry was found and this isn't
1791 	 * a user-defined property.
1792 	 */
1793 	if (prop == ZPROP_USERPROP && ((type == ZFS_TYPE_POOL &&
1794 	    !zfs_prop_user(propname) &&
1795 	    !zpool_prop_feature(propname) &&
1796 	    !zpool_prop_unsupported(propname)) ||
1797 	    ((type == ZFS_TYPE_DATASET) && !zfs_prop_user(propname) &&
1798 	    !zfs_prop_userquota(propname) && !zfs_prop_written(propname)) ||
1799 	    ((type == ZFS_TYPE_VDEV) && !vdev_prop_user(propname)))) {
1800 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1801 		    "invalid property '%s'"), propname);
1802 		return (zfs_error(hdl, EZFS_BADPROP,
1803 		    dgettext(TEXT_DOMAIN, "bad property list")));
1804 	}
1805 
1806 	zprop_list_t *entry = zfs_alloc(hdl, sizeof (*entry));
1807 
1808 	entry->pl_prop = prop;
1809 	if (prop == ZPROP_USERPROP) {
1810 		entry->pl_user_prop = zfs_strdup(hdl, propname);
1811 		entry->pl_width = strlen(propname);
1812 	} else {
1813 		entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1814 		    type);
1815 	}
1816 
1817 	*listp = entry;
1818 
1819 	return (0);
1820 }
1821 
1822 /*
1823  * Given a comma-separated list of properties, construct a property list
1824  * containing both user-defined and native properties.  This function will
1825  * return a NULL list if 'all' is specified, which can later be expanded
1826  * by zprop_expand_list().
1827  */
1828 int
1829 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1830     zfs_type_t type)
1831 {
1832 	*listp = NULL;
1833 
1834 	/*
1835 	 * If 'all' is specified, return a NULL list.
1836 	 */
1837 	if (strcmp(props, "all") == 0)
1838 		return (0);
1839 
1840 	/*
1841 	 * If no props were specified, return an error.
1842 	 */
1843 	if (props[0] == '\0') {
1844 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1845 		    "no properties specified"));
1846 		return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1847 		    "bad property list")));
1848 	}
1849 
1850 	for (char *p; (p = strsep(&props, ",")); )
1851 		if (strcmp(p, "space") == 0) {
1852 			static const char *const spaceprops[] = {
1853 				"name", "avail", "used", "usedbysnapshots",
1854 				"usedbydataset", "usedbyrefreservation",
1855 				"usedbychildren"
1856 			};
1857 
1858 			for (int i = 0; i < ARRAY_SIZE(spaceprops); i++) {
1859 				if (addlist(hdl, spaceprops[i], listp, type))
1860 					return (-1);
1861 				listp = &(*listp)->pl_next;
1862 			}
1863 		} else {
1864 			if (addlist(hdl, p, listp, type))
1865 				return (-1);
1866 			listp = &(*listp)->pl_next;
1867 		}
1868 
1869 	return (0);
1870 }
1871 
1872 void
1873 zprop_free_list(zprop_list_t *pl)
1874 {
1875 	zprop_list_t *next;
1876 
1877 	while (pl != NULL) {
1878 		next = pl->pl_next;
1879 		free(pl->pl_user_prop);
1880 		free(pl);
1881 		pl = next;
1882 	}
1883 }
1884 
1885 typedef struct expand_data {
1886 	zprop_list_t	**last;
1887 	libzfs_handle_t	*hdl;
1888 	zfs_type_t type;
1889 } expand_data_t;
1890 
1891 static int
1892 zprop_expand_list_cb(int prop, void *cb)
1893 {
1894 	zprop_list_t *entry;
1895 	expand_data_t *edp = cb;
1896 
1897 	entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t));
1898 
1899 	entry->pl_prop = prop;
1900 	entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
1901 	entry->pl_all = B_TRUE;
1902 
1903 	*(edp->last) = entry;
1904 	edp->last = &entry->pl_next;
1905 
1906 	return (ZPROP_CONT);
1907 }
1908 
1909 int
1910 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
1911 {
1912 	zprop_list_t *entry;
1913 	zprop_list_t **last;
1914 	expand_data_t exp;
1915 
1916 	if (*plp == NULL) {
1917 		/*
1918 		 * If this is the very first time we've been called for an 'all'
1919 		 * specification, expand the list to include all native
1920 		 * properties.
1921 		 */
1922 		last = plp;
1923 
1924 		exp.last = last;
1925 		exp.hdl = hdl;
1926 		exp.type = type;
1927 
1928 		if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
1929 		    B_FALSE, type) == ZPROP_INVAL)
1930 			return (-1);
1931 
1932 		/*
1933 		 * Add 'name' to the beginning of the list, which is handled
1934 		 * specially.
1935 		 */
1936 		entry = zfs_alloc(hdl, sizeof (zprop_list_t));
1937 		entry->pl_prop = ((type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME :
1938 		    ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME));
1939 		entry->pl_width = zprop_width(entry->pl_prop,
1940 		    &entry->pl_fixed, type);
1941 		entry->pl_all = B_TRUE;
1942 		entry->pl_next = *plp;
1943 		*plp = entry;
1944 	}
1945 	return (0);
1946 }
1947 
1948 int
1949 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
1950     zfs_type_t type)
1951 {
1952 	return (zprop_iter_common(func, cb, show_all, ordered, type));
1953 }
1954 
1955 const char *
1956 zfs_version_userland(void)
1957 {
1958 	return (ZFS_META_ALIAS);
1959 }
1960 
1961 /*
1962  * Prints both zfs userland and kernel versions
1963  * Returns 0 on success, and -1 on error
1964  */
1965 int
1966 zfs_version_print(void)
1967 {
1968 	(void) puts(ZFS_META_ALIAS);
1969 
1970 	char *kver = zfs_version_kernel();
1971 	if (kver == NULL) {
1972 		fprintf(stderr, "zfs_version_kernel() failed: %s\n",
1973 		    zfs_strerror(errno));
1974 		return (-1);
1975 	}
1976 
1977 	(void) printf("zfs-kmod-%s\n", kver);
1978 	free(kver);
1979 	return (0);
1980 }
1981 
1982 /*
1983  * Return 1 if the user requested ANSI color output, and our terminal supports
1984  * it.  Return 0 for no color.
1985  */
1986 int
1987 use_color(void)
1988 {
1989 	static int use_color = -1;
1990 	char *term;
1991 
1992 	/*
1993 	 * Optimization:
1994 	 *
1995 	 * For each zpool invocation, we do a single check to see if we should
1996 	 * be using color or not, and cache that value for the lifetime of the
1997 	 * the zpool command.  That makes it cheap to call use_color() when
1998 	 * we're printing with color.  We assume that the settings are not going
1999 	 * to change during the invocation of a zpool command (the user isn't
2000 	 * going to change the ZFS_COLOR value while zpool is running, for
2001 	 * example).
2002 	 */
2003 	if (use_color != -1) {
2004 		/*
2005 		 * We've already figured out if we should be using color or
2006 		 * not.  Return the cached value.
2007 		 */
2008 		return (use_color);
2009 	}
2010 
2011 	term = getenv("TERM");
2012 	/*
2013 	 * The user sets the ZFS_COLOR env var set to enable zpool ANSI color
2014 	 * output.  However if NO_COLOR is set (https://no-color.org/) then
2015 	 * don't use it.  Also, don't use color if terminal doesn't support
2016 	 * it.
2017 	 */
2018 	if (libzfs_envvar_is_set("ZFS_COLOR") &&
2019 	    !libzfs_envvar_is_set("NO_COLOR") &&
2020 	    isatty(STDOUT_FILENO) && term && strcmp("dumb", term) != 0 &&
2021 	    strcmp("unknown", term) != 0) {
2022 		/* Color supported */
2023 		use_color = 1;
2024 	} else {
2025 		use_color = 0;
2026 	}
2027 
2028 	return (use_color);
2029 }
2030 
2031 /*
2032  * The functions color_start() and color_end() are used for when you want
2033  * to colorize a block of text.
2034  *
2035  * For example:
2036  * color_start(ANSI_RED)
2037  * printf("hello");
2038  * printf("world");
2039  * color_end();
2040  */
2041 void
2042 color_start(const char *color)
2043 {
2044 	if (color && use_color()) {
2045 		fputs(color, stdout);
2046 		fflush(stdout);
2047 	}
2048 }
2049 
2050 void
2051 color_end(void)
2052 {
2053 	if (use_color()) {
2054 		fputs(ANSI_RESET, stdout);
2055 		fflush(stdout);
2056 	}
2057 
2058 }
2059 
2060 /*
2061  * printf() with a color. If color is NULL, then do a normal printf.
2062  */
2063 int
2064 printf_color(const char *color, const char *format, ...)
2065 {
2066 	va_list aptr;
2067 	int rc;
2068 
2069 	if (color)
2070 		color_start(color);
2071 
2072 	va_start(aptr, format);
2073 	rc = vprintf(format, aptr);
2074 	va_end(aptr);
2075 
2076 	if (color)
2077 		color_end();
2078 
2079 	return (rc);
2080 }
2081 
2082 /* PATH + 5 env vars + a NULL entry = 7 */
2083 #define	ZPOOL_VDEV_SCRIPT_ENV_COUNT 7
2084 
2085 /*
2086  * There's a few places where ZFS will call external scripts (like the script
2087  * in zpool.d/ and `zfs_prepare_disk`).  These scripts are called with a
2088  * reduced $PATH, and some vdev specific environment vars set.  This function
2089  * will allocate an populate the environment variable array that is passed to
2090  * these scripts.  The user must free the arrays with zpool_vdev_free_env() when
2091  * they are done.
2092  *
2093  * The following env vars will be set (but value could be blank):
2094  *
2095  * POOL_NAME
2096  * VDEV_PATH
2097  * VDEV_UPATH
2098  * VDEV_ENC_SYSFS_PATH
2099  *
2100  * In addition, you can set an optional environment variable named 'opt_key'
2101  * to 'opt_val' if you want.
2102  *
2103  * Returns allocated env[] array on success, NULL otherwise.
2104  */
2105 char **
2106 zpool_vdev_script_alloc_env(const char *pool_name,
2107     const char *vdev_path, const char *vdev_upath,
2108     const char *vdev_enc_sysfs_path, const char *opt_key, const char *opt_val)
2109 {
2110 	char **env = NULL;
2111 	int rc;
2112 
2113 	env = calloc(ZPOOL_VDEV_SCRIPT_ENV_COUNT, sizeof (*env));
2114 	if (!env)
2115 		return (NULL);
2116 
2117 	env[0] = strdup("PATH=/bin:/sbin:/usr/bin:/usr/sbin");
2118 	if (!env[0])
2119 		goto error;
2120 
2121 	/* Setup our custom environment variables */
2122 	rc = asprintf(&env[1], "POOL_NAME=%s", pool_name ? pool_name : "");
2123 	if (rc == -1) {
2124 		env[1] = NULL;
2125 		goto error;
2126 	}
2127 
2128 	rc = asprintf(&env[2], "VDEV_PATH=%s", vdev_path ? vdev_path : "");
2129 	if (rc == -1) {
2130 		env[2] = NULL;
2131 		goto error;
2132 	}
2133 
2134 	rc = asprintf(&env[3], "VDEV_UPATH=%s", vdev_upath ? vdev_upath : "");
2135 	if (rc == -1) {
2136 		env[3] = NULL;
2137 		goto error;
2138 	}
2139 
2140 	rc = asprintf(&env[4], "VDEV_ENC_SYSFS_PATH=%s",
2141 	    vdev_enc_sysfs_path ?  vdev_enc_sysfs_path : "");
2142 	if (rc == -1) {
2143 		env[4] = NULL;
2144 		goto error;
2145 	}
2146 
2147 	if (opt_key != NULL) {
2148 		rc = asprintf(&env[5], "%s=%s", opt_key,
2149 		    opt_val ? opt_val : "");
2150 		if (rc == -1) {
2151 			env[5] = NULL;
2152 			goto error;
2153 		}
2154 	}
2155 
2156 	return (env);
2157 
2158 error:
2159 	for (int i = 0; i < ZPOOL_VDEV_SCRIPT_ENV_COUNT; i++)
2160 		free(env[i]);
2161 
2162 	free(env);
2163 
2164 	return (NULL);
2165 }
2166 
2167 /*
2168  * Free the env[] array that was allocated by zpool_vdev_script_alloc_env().
2169  */
2170 void
2171 zpool_vdev_script_free_env(char **env)
2172 {
2173 	for (int i = 0; i < ZPOOL_VDEV_SCRIPT_ENV_COUNT; i++)
2174 		free(env[i]);
2175 
2176 	free(env);
2177 }
2178 
2179 /*
2180  * Prepare a disk by (optionally) running a program before labeling the disk.
2181  * This can be useful for installing disk firmware or doing some pre-flight
2182  * checks on the disk before it becomes part of the pool.  The program run is
2183  * located at ZFSEXECDIR/zfs_prepare_disk
2184  * (E.x: /usr/local/libexec/zfs/zfs_prepare_disk).
2185  *
2186  * Return 0 on success, non-zero on failure.
2187  */
2188 int
2189 zpool_prepare_disk(zpool_handle_t *zhp, nvlist_t *vdev_nv,
2190     const char *prepare_str, char **lines[], int *lines_cnt)
2191 {
2192 	const char *script_path = ZFSEXECDIR "/zfs_prepare_disk";
2193 	const char *pool_name;
2194 	int rc = 0;
2195 
2196 	/* Path to script and a NULL entry */
2197 	char *argv[2] = {(char *)script_path};
2198 	char **env = NULL;
2199 	const char *path = NULL, *enc_sysfs_path = NULL;
2200 	char *upath;
2201 	*lines_cnt = 0;
2202 
2203 	if (access(script_path, X_OK) != 0) {
2204 		/* No script, nothing to do */
2205 		return (0);
2206 	}
2207 
2208 	(void) nvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH, &path);
2209 	(void) nvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH,
2210 	    &enc_sysfs_path);
2211 
2212 	upath = zfs_get_underlying_path(path);
2213 	pool_name = zhp ? zpool_get_name(zhp) : NULL;
2214 
2215 	env = zpool_vdev_script_alloc_env(pool_name, path, upath,
2216 	    enc_sysfs_path, "VDEV_PREPARE", prepare_str);
2217 
2218 	free(upath);
2219 
2220 	if (env == NULL) {
2221 		return (ENOMEM);
2222 	}
2223 
2224 	rc = libzfs_run_process_get_stdout(script_path, argv, env, lines,
2225 	    lines_cnt);
2226 
2227 	zpool_vdev_script_free_env(env);
2228 
2229 	return (rc);
2230 }
2231 
2232 /*
2233  * Optionally run a script and then label a disk.  The script can be used to
2234  * prepare a disk for inclusion into the pool.  For example, it might update
2235  * the disk's firmware or check its health.
2236  *
2237  * The 'name' provided is the short name, stripped of any leading
2238  * /dev path, and is passed to zpool_label_disk. vdev_nv is the nvlist for
2239  * the vdev.  prepare_str is a string that gets passed as the VDEV_PREPARE
2240  * env variable to the script.
2241  *
2242  * The following env vars are passed to the script:
2243  *
2244  * POOL_NAME:		The pool name (blank during zpool create)
2245  * VDEV_PREPARE:	Reason why the disk is being prepared for inclusion:
2246  *			"create", "add", "replace", or "autoreplace"
2247  * VDEV_PATH:		Path to the disk
2248  * VDEV_UPATH:		One of the 'underlying paths' to the disk.  This is
2249  * 			useful for DM devices.
2250  * VDEV_ENC_SYSFS_PATH:	Path to the disk's enclosure sysfs path, if available.
2251  *
2252  * Note, some of these values can be blank.
2253  *
2254  * Return 0 on success, non-zero otherwise.
2255  */
2256 int
2257 zpool_prepare_and_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp,
2258     const char *name, nvlist_t *vdev_nv, const char *prepare_str,
2259     char **lines[], int *lines_cnt)
2260 {
2261 	int rc;
2262 	char vdev_path[MAXPATHLEN];
2263 	(void) snprintf(vdev_path, sizeof (vdev_path), "%s/%s", DISK_ROOT,
2264 	    name);
2265 
2266 	/* zhp will be NULL when creating a pool */
2267 	rc = zpool_prepare_disk(zhp, vdev_nv, prepare_str, lines, lines_cnt);
2268 	if (rc != 0)
2269 		return (rc);
2270 
2271 	rc = zpool_label_disk(hdl, zhp, name);
2272 	return (rc);
2273 }
2274