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