xref: /illumos-gate/usr/src/lib/libzfs/common/libzfs_util.c (revision 6ccda740e007c01cb5d1436fe337851ff8c5d422)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2019 Joyent, Inc.
25  * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
26  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
27  * Copyright (c) 2017 Datto Inc.
28  */
29 
30 /*
31  * Internal utility routines for the ZFS library.
32  */
33 
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <libintl.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <strings.h>
41 #include <unistd.h>
42 #include <ctype.h>
43 #include <math.h>
44 #include <sys/filio.h>
45 #include <sys/mnttab.h>
46 #include <sys/mntent.h>
47 #include <sys/types.h>
48 #include <libcmdutils.h>
49 
50 #include <libzfs.h>
51 #include <libzfs_core.h>
52 
53 #include "libzfs_impl.h"
54 #include "zfs_prop.h"
55 #include "zfs_comutil.h"
56 #include "zfeature_common.h"
57 
58 int
59 libzfs_errno(libzfs_handle_t *hdl)
60 {
61 	return (hdl->libzfs_error);
62 }
63 
64 const char *
65 libzfs_error_action(libzfs_handle_t *hdl)
66 {
67 	return (hdl->libzfs_action);
68 }
69 
70 const char *
71 libzfs_error_description(libzfs_handle_t *hdl)
72 {
73 	if (hdl->libzfs_desc[0] != '\0')
74 		return (hdl->libzfs_desc);
75 
76 	switch (hdl->libzfs_error) {
77 	case EZFS_NOMEM:
78 		return (dgettext(TEXT_DOMAIN, "out of memory"));
79 	case EZFS_BADPROP:
80 		return (dgettext(TEXT_DOMAIN, "invalid property value"));
81 	case EZFS_PROPREADONLY:
82 		return (dgettext(TEXT_DOMAIN, "read-only property"));
83 	case EZFS_PROPTYPE:
84 		return (dgettext(TEXT_DOMAIN, "property doesn't apply to "
85 		    "datasets of this type"));
86 	case EZFS_PROPNONINHERIT:
87 		return (dgettext(TEXT_DOMAIN, "property cannot be inherited"));
88 	case EZFS_PROPSPACE:
89 		return (dgettext(TEXT_DOMAIN, "invalid quota or reservation"));
90 	case EZFS_BADTYPE:
91 		return (dgettext(TEXT_DOMAIN, "operation not applicable to "
92 		    "datasets of this type"));
93 	case EZFS_BUSY:
94 		return (dgettext(TEXT_DOMAIN, "pool or dataset is busy"));
95 	case EZFS_EXISTS:
96 		return (dgettext(TEXT_DOMAIN, "pool or dataset exists"));
97 	case EZFS_NOENT:
98 		return (dgettext(TEXT_DOMAIN, "no such pool or dataset"));
99 	case EZFS_BADSTREAM:
100 		return (dgettext(TEXT_DOMAIN, "invalid backup stream"));
101 	case EZFS_DSREADONLY:
102 		return (dgettext(TEXT_DOMAIN, "dataset is read-only"));
103 	case EZFS_VOLTOOBIG:
104 		return (dgettext(TEXT_DOMAIN, "volume size exceeds limit for "
105 		    "this system"));
106 	case EZFS_INVALIDNAME:
107 		return (dgettext(TEXT_DOMAIN, "invalid name"));
108 	case EZFS_BADRESTORE:
109 		return (dgettext(TEXT_DOMAIN, "unable to restore to "
110 		    "destination"));
111 	case EZFS_BADBACKUP:
112 		return (dgettext(TEXT_DOMAIN, "backup failed"));
113 	case EZFS_BADTARGET:
114 		return (dgettext(TEXT_DOMAIN, "invalid target vdev"));
115 	case EZFS_NODEVICE:
116 		return (dgettext(TEXT_DOMAIN, "no such device in pool"));
117 	case EZFS_BADDEV:
118 		return (dgettext(TEXT_DOMAIN, "invalid device"));
119 	case EZFS_NOREPLICAS:
120 		return (dgettext(TEXT_DOMAIN, "no valid replicas"));
121 	case EZFS_RESILVERING:
122 		return (dgettext(TEXT_DOMAIN, "currently resilvering"));
123 	case EZFS_BADVERSION:
124 		return (dgettext(TEXT_DOMAIN, "unsupported version or "
125 		    "feature"));
126 	case EZFS_POOLUNAVAIL:
127 		return (dgettext(TEXT_DOMAIN, "pool is unavailable"));
128 	case EZFS_DEVOVERFLOW:
129 		return (dgettext(TEXT_DOMAIN, "too many devices in one vdev"));
130 	case EZFS_BADPATH:
131 		return (dgettext(TEXT_DOMAIN, "must be an absolute path"));
132 	case EZFS_CROSSTARGET:
133 		return (dgettext(TEXT_DOMAIN, "operation crosses datasets or "
134 		    "pools"));
135 	case EZFS_ZONED:
136 		return (dgettext(TEXT_DOMAIN, "dataset in use by local zone"));
137 	case EZFS_MOUNTFAILED:
138 		return (dgettext(TEXT_DOMAIN, "mount failed"));
139 	case EZFS_UMOUNTFAILED:
140 		return (dgettext(TEXT_DOMAIN, "umount failed"));
141 	case EZFS_UNSHARENFSFAILED:
142 		return (dgettext(TEXT_DOMAIN, "unshare(1M) failed"));
143 	case EZFS_SHARENFSFAILED:
144 		return (dgettext(TEXT_DOMAIN, "share(1M) failed"));
145 	case EZFS_UNSHARESMBFAILED:
146 		return (dgettext(TEXT_DOMAIN, "smb remove share failed"));
147 	case EZFS_SHARESMBFAILED:
148 		return (dgettext(TEXT_DOMAIN, "smb add share failed"));
149 	case EZFS_PERM:
150 		return (dgettext(TEXT_DOMAIN, "permission denied"));
151 	case EZFS_NOSPC:
152 		return (dgettext(TEXT_DOMAIN, "out of space"));
153 	case EZFS_FAULT:
154 		return (dgettext(TEXT_DOMAIN, "bad address"));
155 	case EZFS_IO:
156 		return (dgettext(TEXT_DOMAIN, "I/O error"));
157 	case EZFS_INTR:
158 		return (dgettext(TEXT_DOMAIN, "signal received"));
159 	case EZFS_ISSPARE:
160 		return (dgettext(TEXT_DOMAIN, "device is reserved as a hot "
161 		    "spare"));
162 	case EZFS_INVALCONFIG:
163 		return (dgettext(TEXT_DOMAIN, "invalid vdev configuration"));
164 	case EZFS_RECURSIVE:
165 		return (dgettext(TEXT_DOMAIN, "recursive dataset dependency"));
166 	case EZFS_NOHISTORY:
167 		return (dgettext(TEXT_DOMAIN, "no history available"));
168 	case EZFS_POOLPROPS:
169 		return (dgettext(TEXT_DOMAIN, "failed to retrieve "
170 		    "pool properties"));
171 	case EZFS_POOL_NOTSUP:
172 		return (dgettext(TEXT_DOMAIN, "operation not supported "
173 		    "on this type of pool"));
174 	case EZFS_POOL_INVALARG:
175 		return (dgettext(TEXT_DOMAIN, "invalid argument for "
176 		    "this pool operation"));
177 	case EZFS_NAMETOOLONG:
178 		return (dgettext(TEXT_DOMAIN, "dataset name is too long"));
179 	case EZFS_OPENFAILED:
180 		return (dgettext(TEXT_DOMAIN, "open failed"));
181 	case EZFS_NOCAP:
182 		return (dgettext(TEXT_DOMAIN,
183 		    "disk capacity information could not be retrieved"));
184 	case EZFS_LABELFAILED:
185 		return (dgettext(TEXT_DOMAIN, "write of label failed"));
186 	case EZFS_BADWHO:
187 		return (dgettext(TEXT_DOMAIN, "invalid user/group"));
188 	case EZFS_BADPERM:
189 		return (dgettext(TEXT_DOMAIN, "invalid permission"));
190 	case EZFS_BADPERMSET:
191 		return (dgettext(TEXT_DOMAIN, "invalid permission set name"));
192 	case EZFS_NODELEGATION:
193 		return (dgettext(TEXT_DOMAIN, "delegated administration is "
194 		    "disabled on pool"));
195 	case EZFS_BADCACHE:
196 		return (dgettext(TEXT_DOMAIN, "invalid or missing cache file"));
197 	case EZFS_ISL2CACHE:
198 		return (dgettext(TEXT_DOMAIN, "device is in use as a cache"));
199 	case EZFS_VDEVNOTSUP:
200 		return (dgettext(TEXT_DOMAIN, "vdev specification is not "
201 		    "supported"));
202 	case EZFS_NOTSUP:
203 		return (dgettext(TEXT_DOMAIN, "operation not supported "
204 		    "on this dataset"));
205 	case EZFS_ACTIVE_SPARE:
206 		return (dgettext(TEXT_DOMAIN, "pool has active shared spare "
207 		    "device"));
208 	case EZFS_UNPLAYED_LOGS:
209 		return (dgettext(TEXT_DOMAIN, "log device has unplayed intent "
210 		    "logs"));
211 	case EZFS_REFTAG_RELE:
212 		return (dgettext(TEXT_DOMAIN, "no such tag on this dataset"));
213 	case EZFS_REFTAG_HOLD:
214 		return (dgettext(TEXT_DOMAIN, "tag already exists on this "
215 		    "dataset"));
216 	case EZFS_TAGTOOLONG:
217 		return (dgettext(TEXT_DOMAIN, "tag too long"));
218 	case EZFS_PIPEFAILED:
219 		return (dgettext(TEXT_DOMAIN, "pipe create failed"));
220 	case EZFS_THREADCREATEFAILED:
221 		return (dgettext(TEXT_DOMAIN, "thread create failed"));
222 	case EZFS_POSTSPLIT_ONLINE:
223 		return (dgettext(TEXT_DOMAIN, "disk was split from this pool "
224 		    "into a new one"));
225 	case EZFS_SCRUB_PAUSED:
226 		return (dgettext(TEXT_DOMAIN, "scrub is paused; "
227 		    "use 'zpool scrub' to resume"));
228 	case EZFS_SCRUBBING:
229 		return (dgettext(TEXT_DOMAIN, "currently scrubbing; "
230 		    "use 'zpool scrub -s' to cancel current scrub"));
231 	case EZFS_NO_SCRUB:
232 		return (dgettext(TEXT_DOMAIN, "there is no active scrub"));
233 	case EZFS_DIFF:
234 		return (dgettext(TEXT_DOMAIN, "unable to generate diffs"));
235 	case EZFS_DIFFDATA:
236 		return (dgettext(TEXT_DOMAIN, "invalid diff data"));
237 	case EZFS_POOLREADONLY:
238 		return (dgettext(TEXT_DOMAIN, "pool is read-only"));
239 	case EZFS_NO_PENDING:
240 		return (dgettext(TEXT_DOMAIN, "operation is not "
241 		    "in progress"));
242 	case EZFS_CHECKPOINT_EXISTS:
243 		return (dgettext(TEXT_DOMAIN, "checkpoint exists"));
244 	case EZFS_DISCARDING_CHECKPOINT:
245 		return (dgettext(TEXT_DOMAIN, "currently discarding "
246 		    "checkpoint"));
247 	case EZFS_NO_CHECKPOINT:
248 		return (dgettext(TEXT_DOMAIN, "checkpoint does not exist"));
249 	case EZFS_DEVRM_IN_PROGRESS:
250 		return (dgettext(TEXT_DOMAIN, "device removal in progress"));
251 	case EZFS_VDEV_TOO_BIG:
252 		return (dgettext(TEXT_DOMAIN, "device exceeds supported size"));
253 	case EZFS_ACTIVE_POOL:
254 		return (dgettext(TEXT_DOMAIN, "pool is imported on a "
255 		    "different host"));
256 	case EZFS_TOOMANY:
257 		return (dgettext(TEXT_DOMAIN, "argument list too long"));
258 	case EZFS_INITIALIZING:
259 		return (dgettext(TEXT_DOMAIN, "currently initializing"));
260 	case EZFS_NO_INITIALIZE:
261 		return (dgettext(TEXT_DOMAIN, "there is no active "
262 		    "initialization"));
263 	case EZFS_WRONG_PARENT:
264 		return (dgettext(TEXT_DOMAIN, "invalid parent dataset"));
265 	case EZFS_NO_RESILVER_DEFER:
266 		return (dgettext(TEXT_DOMAIN, "this action requires the "
267 		    "resilver_defer feature"));
268 	case EZFS_CRYPTOFAILED:
269 		return (dgettext(TEXT_DOMAIN, "encryption failure"));
270 	case EZFS_UNKNOWN:
271 		return (dgettext(TEXT_DOMAIN, "unknown error"));
272 	default:
273 		assert(hdl->libzfs_error == 0);
274 		return (dgettext(TEXT_DOMAIN, "no error"));
275 	}
276 }
277 
278 /*PRINTFLIKE2*/
279 void
280 zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
281 {
282 	va_list ap;
283 
284 	va_start(ap, fmt);
285 
286 	(void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
287 	    fmt, ap);
288 	hdl->libzfs_desc_active = 1;
289 
290 	va_end(ap);
291 }
292 
293 static void
294 zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
295 {
296 	(void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
297 	    fmt, ap);
298 	hdl->libzfs_error = error;
299 
300 	if (hdl->libzfs_desc_active)
301 		hdl->libzfs_desc_active = 0;
302 	else
303 		hdl->libzfs_desc[0] = '\0';
304 
305 	if (hdl->libzfs_printerr) {
306 		if (error == EZFS_UNKNOWN) {
307 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
308 			    "error: %s\n"), libzfs_error_description(hdl));
309 			abort();
310 		}
311 
312 		(void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
313 		    libzfs_error_description(hdl));
314 		if (error == EZFS_NOMEM)
315 			exit(1);
316 	}
317 }
318 
319 int
320 zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
321 {
322 	return (zfs_error_fmt(hdl, error, "%s", msg));
323 }
324 
325 /*PRINTFLIKE3*/
326 int
327 zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
328 {
329 	va_list ap;
330 
331 	va_start(ap, fmt);
332 
333 	zfs_verror(hdl, error, fmt, ap);
334 
335 	va_end(ap);
336 
337 	return (-1);
338 }
339 
340 static int
341 zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
342     va_list ap)
343 {
344 	switch (error) {
345 	case EPERM:
346 	case EACCES:
347 		zfs_verror(hdl, EZFS_PERM, fmt, ap);
348 		return (-1);
349 
350 	case ECANCELED:
351 		zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
352 		return (-1);
353 
354 	case EIO:
355 		zfs_verror(hdl, EZFS_IO, fmt, ap);
356 		return (-1);
357 
358 	case EFAULT:
359 		zfs_verror(hdl, EZFS_FAULT, fmt, ap);
360 		return (-1);
361 
362 	case EINTR:
363 		zfs_verror(hdl, EZFS_INTR, fmt, ap);
364 		return (-1);
365 	}
366 
367 	return (0);
368 }
369 
370 int
371 zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
372 {
373 	return (zfs_standard_error_fmt(hdl, error, "%s", msg));
374 }
375 
376 /*PRINTFLIKE3*/
377 int
378 zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
379 {
380 	va_list ap;
381 
382 	va_start(ap, fmt);
383 
384 	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
385 		va_end(ap);
386 		return (-1);
387 	}
388 
389 	switch (error) {
390 	case ENXIO:
391 	case ENODEV:
392 	case EPIPE:
393 		zfs_verror(hdl, EZFS_IO, fmt, ap);
394 		break;
395 
396 	case ENOENT:
397 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
398 		    "dataset does not exist"));
399 		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
400 		break;
401 
402 	case ENOSPC:
403 	case EDQUOT:
404 		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
405 		return (-1);
406 
407 	case EEXIST:
408 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
409 		    "dataset already exists"));
410 		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
411 		break;
412 
413 	case EBUSY:
414 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
415 		    "dataset is busy"));
416 		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
417 		break;
418 	case EROFS:
419 		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
420 		break;
421 	case ENAMETOOLONG:
422 		zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
423 		break;
424 	case ENOTSUP:
425 		zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
426 		break;
427 	case EAGAIN:
428 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
429 		    "pool I/O is currently suspended"));
430 		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
431 		break;
432 	case EREMOTEIO:
433 		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
434 		break;
435 	default:
436 		zfs_error_aux(hdl, strerror(error));
437 		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
438 		break;
439 	}
440 
441 	va_end(ap);
442 	return (-1);
443 }
444 
445 int
446 zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
447 {
448 	return (zpool_standard_error_fmt(hdl, error, "%s", msg));
449 }
450 
451 /*PRINTFLIKE3*/
452 int
453 zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
454 {
455 	va_list ap;
456 
457 	va_start(ap, fmt);
458 
459 	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
460 		va_end(ap);
461 		return (-1);
462 	}
463 
464 	switch (error) {
465 	case ENODEV:
466 		zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
467 		break;
468 
469 	case ENOENT:
470 		zfs_error_aux(hdl,
471 		    dgettext(TEXT_DOMAIN, "no such pool or dataset"));
472 		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
473 		break;
474 
475 	case EEXIST:
476 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
477 		    "pool already exists"));
478 		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
479 		break;
480 
481 	case EBUSY:
482 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
483 		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
484 		break;
485 
486 	case ENXIO:
487 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
488 		    "one or more devices is currently unavailable"));
489 		zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
490 		break;
491 
492 	case ENAMETOOLONG:
493 		zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
494 		break;
495 
496 	case ENOTSUP:
497 		zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
498 		break;
499 
500 	case EINVAL:
501 		zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
502 		break;
503 
504 	case ENOSPC:
505 	case EDQUOT:
506 		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
507 		return (-1);
508 
509 	case EAGAIN:
510 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
511 		    "pool I/O is currently suspended"));
512 		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
513 		break;
514 
515 	case EROFS:
516 		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
517 		break;
518 	/* There is no pending operation to cancel */
519 	case ENOTACTIVE:
520 		zfs_verror(hdl, EZFS_NO_PENDING, fmt, ap);
521 		break;
522 	case EREMOTEIO:
523 		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
524 		break;
525 	case ZFS_ERR_CHECKPOINT_EXISTS:
526 		zfs_verror(hdl, EZFS_CHECKPOINT_EXISTS, fmt, ap);
527 		break;
528 	case ZFS_ERR_DISCARDING_CHECKPOINT:
529 		zfs_verror(hdl, EZFS_DISCARDING_CHECKPOINT, fmt, ap);
530 		break;
531 	case ZFS_ERR_NO_CHECKPOINT:
532 		zfs_verror(hdl, EZFS_NO_CHECKPOINT, fmt, ap);
533 		break;
534 	case ZFS_ERR_DEVRM_IN_PROGRESS:
535 		zfs_verror(hdl, EZFS_DEVRM_IN_PROGRESS, fmt, ap);
536 		break;
537 	case ZFS_ERR_VDEV_TOO_BIG:
538 		zfs_verror(hdl, EZFS_VDEV_TOO_BIG, fmt, ap);
539 		break;
540 	default:
541 		zfs_error_aux(hdl, strerror(error));
542 		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
543 	}
544 
545 	va_end(ap);
546 	return (-1);
547 }
548 
549 /*
550  * Display an out of memory error message and abort the current program.
551  */
552 int
553 no_memory(libzfs_handle_t *hdl)
554 {
555 	return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
556 }
557 
558 /*
559  * A safe form of malloc() which will die if the allocation fails.
560  */
561 void *
562 zfs_alloc(libzfs_handle_t *hdl, size_t size)
563 {
564 	void *data;
565 
566 	if ((data = calloc(1, size)) == NULL)
567 		(void) no_memory(hdl);
568 
569 	return (data);
570 }
571 
572 /*
573  * A safe form of asprintf() which will die if the allocation fails.
574  */
575 /*PRINTFLIKE2*/
576 char *
577 zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
578 {
579 	va_list ap;
580 	char *ret;
581 	int err;
582 
583 	va_start(ap, fmt);
584 
585 	err = vasprintf(&ret, fmt, ap);
586 
587 	va_end(ap);
588 
589 	if (err < 0)
590 		(void) no_memory(hdl);
591 
592 	return (ret);
593 }
594 
595 /*
596  * A safe form of realloc(), which also zeroes newly allocated space.
597  */
598 void *
599 zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
600 {
601 	void *ret;
602 
603 	if ((ret = realloc(ptr, newsize)) == NULL) {
604 		(void) no_memory(hdl);
605 		return (NULL);
606 	}
607 
608 	bzero((char *)ret + oldsize, (newsize - oldsize));
609 	return (ret);
610 }
611 
612 /*
613  * A safe form of strdup() which will die if the allocation fails.
614  */
615 char *
616 zfs_strdup(libzfs_handle_t *hdl, const char *str)
617 {
618 	char *ret;
619 
620 	if ((ret = strdup(str)) == NULL)
621 		(void) no_memory(hdl);
622 
623 	return (ret);
624 }
625 
626 /*
627  * Convert a number to an appropriately human-readable output.
628  */
629 void
630 zfs_nicenum(uint64_t num, char *buf, size_t buflen)
631 {
632 	nicenum(num, buf, buflen);
633 }
634 
635 void
636 libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
637 {
638 	hdl->libzfs_printerr = printerr;
639 }
640 
641 libzfs_handle_t *
642 libzfs_init(void)
643 {
644 	libzfs_handle_t *hdl;
645 
646 	if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
647 		return (NULL);
648 	}
649 
650 	if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR)) < 0) {
651 		free(hdl);
652 		return (NULL);
653 	}
654 
655 	if ((hdl->libzfs_mnttab = fopen(MNTTAB, "rF")) == NULL) {
656 		(void) close(hdl->libzfs_fd);
657 		free(hdl);
658 		return (NULL);
659 	}
660 
661 	hdl->libzfs_sharetab = fopen("/etc/dfs/sharetab", "rF");
662 
663 	if (libzfs_core_init() != 0) {
664 		(void) close(hdl->libzfs_fd);
665 		(void) fclose(hdl->libzfs_mnttab);
666 		(void) fclose(hdl->libzfs_sharetab);
667 		free(hdl);
668 		return (NULL);
669 	}
670 
671 	zfs_prop_init();
672 	zpool_prop_init();
673 	zpool_feature_init();
674 	libzfs_mnttab_init(hdl);
675 
676 	if (getenv("ZFS_PROP_DEBUG") != NULL) {
677 		hdl->libzfs_prop_debug = B_TRUE;
678 	}
679 
680 	return (hdl);
681 }
682 
683 void
684 libzfs_fini(libzfs_handle_t *hdl)
685 {
686 	(void) close(hdl->libzfs_fd);
687 	if (hdl->libzfs_mnttab)
688 		(void) fclose(hdl->libzfs_mnttab);
689 	if (hdl->libzfs_sharetab)
690 		(void) fclose(hdl->libzfs_sharetab);
691 	zfs_uninit_libshare(hdl);
692 	zpool_free_handles(hdl);
693 	libzfs_fru_clear(hdl, B_TRUE);
694 	namespace_clear(hdl);
695 	libzfs_mnttab_fini(hdl);
696 	libzfs_core_fini();
697 	free(hdl);
698 }
699 
700 libzfs_handle_t *
701 zpool_get_handle(zpool_handle_t *zhp)
702 {
703 	return (zhp->zpool_hdl);
704 }
705 
706 libzfs_handle_t *
707 zfs_get_handle(zfs_handle_t *zhp)
708 {
709 	return (zhp->zfs_hdl);
710 }
711 
712 zpool_handle_t *
713 zfs_get_pool_handle(const zfs_handle_t *zhp)
714 {
715 	return (zhp->zpool_hdl);
716 }
717 
718 /*
719  * Given a name, determine whether or not it's a valid path
720  * (starts with '/' or "./").  If so, walk the mnttab trying
721  * to match the device number.  If not, treat the path as an
722  * fs/vol/snap/bkmark name.
723  */
724 zfs_handle_t *
725 zfs_path_to_zhandle(libzfs_handle_t *hdl, char *path, zfs_type_t argtype)
726 {
727 	struct stat64 statbuf;
728 	struct extmnttab entry;
729 	int ret;
730 
731 	if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
732 		/*
733 		 * It's not a valid path, assume it's a name of type 'argtype'.
734 		 */
735 		return (zfs_open(hdl, path, argtype));
736 	}
737 
738 	if (stat64(path, &statbuf) != 0) {
739 		(void) fprintf(stderr, "%s: %s\n", path, strerror(errno));
740 		return (NULL);
741 	}
742 
743 	rewind(hdl->libzfs_mnttab);
744 	while ((ret = getextmntent(hdl->libzfs_mnttab, &entry, 0)) == 0) {
745 		if (makedevice(entry.mnt_major, entry.mnt_minor) ==
746 		    statbuf.st_dev) {
747 			break;
748 		}
749 	}
750 	if (ret != 0) {
751 		return (NULL);
752 	}
753 
754 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
755 		(void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
756 		    path);
757 		return (NULL);
758 	}
759 
760 	return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
761 }
762 
763 /*
764  * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
765  * an ioctl().
766  */
767 int
768 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
769 {
770 	if (len == 0)
771 		len = 16 * 1024;
772 	zc->zc_nvlist_dst_size = len;
773 	zc->zc_nvlist_dst =
774 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
775 	if (zc->zc_nvlist_dst == 0)
776 		return (-1);
777 
778 	return (0);
779 }
780 
781 /*
782  * Called when an ioctl() which returns an nvlist fails with ENOMEM.  This will
783  * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
784  * filled in by the kernel to indicate the actual required size.
785  */
786 int
787 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
788 {
789 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
790 	zc->zc_nvlist_dst =
791 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
792 	if (zc->zc_nvlist_dst == 0)
793 		return (-1);
794 
795 	return (0);
796 }
797 
798 /*
799  * Called to free the src and dst nvlists stored in the command structure.
800  */
801 void
802 zcmd_free_nvlists(zfs_cmd_t *zc)
803 {
804 	free((void *)(uintptr_t)zc->zc_nvlist_conf);
805 	free((void *)(uintptr_t)zc->zc_nvlist_src);
806 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
807 	zc->zc_nvlist_conf = 0;
808 	zc->zc_nvlist_src = 0;
809 	zc->zc_nvlist_dst = 0;
810 }
811 
812 static int
813 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
814     nvlist_t *nvl)
815 {
816 	char *packed;
817 	size_t len;
818 
819 	verify(nvlist_size(nvl, &len, NV_ENCODE_NATIVE) == 0);
820 
821 	if ((packed = zfs_alloc(hdl, len)) == NULL)
822 		return (-1);
823 
824 	verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
825 
826 	*outnv = (uint64_t)(uintptr_t)packed;
827 	*outlen = len;
828 
829 	return (0);
830 }
831 
832 int
833 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
834 {
835 	return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
836 	    &zc->zc_nvlist_conf_size, nvl));
837 }
838 
839 int
840 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
841 {
842 	return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
843 	    &zc->zc_nvlist_src_size, nvl));
844 }
845 
846 /*
847  * Unpacks an nvlist from the ZFS ioctl command structure.
848  */
849 int
850 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
851 {
852 	if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
853 	    zc->zc_nvlist_dst_size, nvlp, 0) != 0)
854 		return (no_memory(hdl));
855 
856 	return (0);
857 }
858 
859 int
860 zfs_ioctl(libzfs_handle_t *hdl, int request, zfs_cmd_t *zc)
861 {
862 	return (ioctl(hdl->libzfs_fd, request, zc));
863 }
864 
865 /*
866  * ================================================================
867  * API shared by zfs and zpool property management
868  * ================================================================
869  */
870 
871 static void
872 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
873 {
874 	zprop_list_t *pl = cbp->cb_proplist;
875 	int i;
876 	char *title;
877 	size_t len;
878 
879 	cbp->cb_first = B_FALSE;
880 	if (cbp->cb_scripted)
881 		return;
882 
883 	/*
884 	 * Start with the length of the column headers.
885 	 */
886 	cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
887 	cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
888 	    "PROPERTY"));
889 	cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
890 	    "VALUE"));
891 	cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
892 	    "RECEIVED"));
893 	cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
894 	    "SOURCE"));
895 
896 	/* first property is always NAME */
897 	assert(cbp->cb_proplist->pl_prop ==
898 	    ((type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME : ZFS_PROP_NAME));
899 
900 	/*
901 	 * Go through and calculate the widths for each column.  For the
902 	 * 'source' column, we kludge it up by taking the worst-case scenario of
903 	 * inheriting from the longest name.  This is acceptable because in the
904 	 * majority of cases 'SOURCE' is the last column displayed, and we don't
905 	 * use the width anyway.  Note that the 'VALUE' column can be oversized,
906 	 * if the name of the property is much longer than any values we find.
907 	 */
908 	for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
909 		/*
910 		 * 'PROPERTY' column
911 		 */
912 		if (pl->pl_prop != ZPROP_INVAL) {
913 			const char *propname = (type == ZFS_TYPE_POOL) ?
914 			    zpool_prop_to_name(pl->pl_prop) :
915 			    zfs_prop_to_name(pl->pl_prop);
916 
917 			len = strlen(propname);
918 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
919 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
920 		} else {
921 			len = strlen(pl->pl_user_prop);
922 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
923 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
924 		}
925 
926 		/*
927 		 * 'VALUE' column.  The first property is always the 'name'
928 		 * property that was tacked on either by /sbin/zfs's
929 		 * zfs_do_get() or when calling zprop_expand_list(), so we
930 		 * ignore its width.  If the user specified the name property
931 		 * to display, then it will be later in the list in any case.
932 		 */
933 		if (pl != cbp->cb_proplist &&
934 		    pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
935 			cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
936 
937 		/* 'RECEIVED' column. */
938 		if (pl != cbp->cb_proplist &&
939 		    pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
940 			cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
941 
942 		/*
943 		 * 'NAME' and 'SOURCE' columns
944 		 */
945 		if (pl->pl_prop == (type == ZFS_TYPE_POOL ? ZPOOL_PROP_NAME :
946 		    ZFS_PROP_NAME) &&
947 		    pl->pl_width > cbp->cb_colwidths[GET_COL_NAME]) {
948 			cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
949 			cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
950 			    strlen(dgettext(TEXT_DOMAIN, "inherited from"));
951 		}
952 	}
953 
954 	/*
955 	 * Now go through and print the headers.
956 	 */
957 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
958 		switch (cbp->cb_columns[i]) {
959 		case GET_COL_NAME:
960 			title = dgettext(TEXT_DOMAIN, "NAME");
961 			break;
962 		case GET_COL_PROPERTY:
963 			title = dgettext(TEXT_DOMAIN, "PROPERTY");
964 			break;
965 		case GET_COL_VALUE:
966 			title = dgettext(TEXT_DOMAIN, "VALUE");
967 			break;
968 		case GET_COL_RECVD:
969 			title = dgettext(TEXT_DOMAIN, "RECEIVED");
970 			break;
971 		case GET_COL_SOURCE:
972 			title = dgettext(TEXT_DOMAIN, "SOURCE");
973 			break;
974 		default:
975 			title = NULL;
976 		}
977 
978 		if (title != NULL) {
979 			if (i == (ZFS_GET_NCOLS - 1) ||
980 			    cbp->cb_columns[i + 1] == GET_COL_NONE)
981 				(void) printf("%s", title);
982 			else
983 				(void) printf("%-*s  ",
984 				    cbp->cb_colwidths[cbp->cb_columns[i]],
985 				    title);
986 		}
987 	}
988 	(void) printf("\n");
989 }
990 
991 /*
992  * Display a single line of output, according to the settings in the callback
993  * structure.
994  */
995 void
996 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
997     const char *propname, const char *value, zprop_source_t sourcetype,
998     const char *source, const char *recvd_value)
999 {
1000 	int i;
1001 	const char *str = NULL;
1002 	char buf[128];
1003 
1004 	/*
1005 	 * Ignore those source types that the user has chosen to ignore.
1006 	 */
1007 	if ((sourcetype & cbp->cb_sources) == 0)
1008 		return;
1009 
1010 	if (cbp->cb_first)
1011 		zprop_print_headers(cbp, cbp->cb_type);
1012 
1013 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1014 		switch (cbp->cb_columns[i]) {
1015 		case GET_COL_NAME:
1016 			str = name;
1017 			break;
1018 
1019 		case GET_COL_PROPERTY:
1020 			str = propname;
1021 			break;
1022 
1023 		case GET_COL_VALUE:
1024 			str = value;
1025 			break;
1026 
1027 		case GET_COL_SOURCE:
1028 			switch (sourcetype) {
1029 			case ZPROP_SRC_NONE:
1030 				str = "-";
1031 				break;
1032 
1033 			case ZPROP_SRC_DEFAULT:
1034 				str = "default";
1035 				break;
1036 
1037 			case ZPROP_SRC_LOCAL:
1038 				str = "local";
1039 				break;
1040 
1041 			case ZPROP_SRC_TEMPORARY:
1042 				str = "temporary";
1043 				break;
1044 
1045 			case ZPROP_SRC_INHERITED:
1046 				(void) snprintf(buf, sizeof (buf),
1047 				    "inherited from %s", source);
1048 				str = buf;
1049 				break;
1050 			case ZPROP_SRC_RECEIVED:
1051 				str = "received";
1052 				break;
1053 
1054 			default:
1055 				str = NULL;
1056 				assert(!"unhandled zprop_source_t");
1057 			}
1058 			break;
1059 
1060 		case GET_COL_RECVD:
1061 			str = (recvd_value == NULL ? "-" : recvd_value);
1062 			break;
1063 
1064 		default:
1065 			continue;
1066 		}
1067 
1068 		if (cbp->cb_columns[i + 1] == GET_COL_NONE)
1069 			(void) printf("%s", str);
1070 		else if (cbp->cb_scripted)
1071 			(void) printf("%s\t", str);
1072 		else
1073 			(void) printf("%-*s  ",
1074 			    cbp->cb_colwidths[cbp->cb_columns[i]],
1075 			    str);
1076 	}
1077 
1078 	(void) printf("\n");
1079 }
1080 
1081 /*
1082  * Given a numeric suffix, convert the value into a number of bits that the
1083  * resulting value must be shifted.
1084  */
1085 static int
1086 str2shift(libzfs_handle_t *hdl, const char *buf)
1087 {
1088 	const char *ends = "BKMGTPEZ";
1089 	int i;
1090 
1091 	if (buf[0] == '\0')
1092 		return (0);
1093 	for (i = 0; i < strlen(ends); i++) {
1094 		if (toupper(buf[0]) == ends[i])
1095 			break;
1096 	}
1097 	if (i == strlen(ends)) {
1098 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1099 		    "invalid numeric suffix '%s'"), buf);
1100 		return (-1);
1101 	}
1102 
1103 	/*
1104 	 * We want to allow trailing 'b' characters for 'GB' or 'Mb'.  But don't
1105 	 * allow 'BB' - that's just weird.
1106 	 */
1107 	if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0' &&
1108 	    toupper(buf[0]) != 'B'))
1109 		return (10*i);
1110 
1111 	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1112 	    "invalid numeric suffix '%s'"), buf);
1113 	return (-1);
1114 }
1115 
1116 /*
1117  * Convert a string of the form '100G' into a real number.  Used when setting
1118  * properties or creating a volume.  'buf' is used to place an extended error
1119  * message for the caller to use.
1120  */
1121 int
1122 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1123 {
1124 	char *end;
1125 	int shift;
1126 
1127 	*num = 0;
1128 
1129 	/* Check to see if this looks like a number.  */
1130 	if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1131 		if (hdl)
1132 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1133 			    "bad numeric value '%s'"), value);
1134 		return (-1);
1135 	}
1136 
1137 	/* Rely on strtoull() to process the numeric portion.  */
1138 	errno = 0;
1139 	*num = strtoull(value, &end, 10);
1140 
1141 	/*
1142 	 * Check for ERANGE, which indicates that the value is too large to fit
1143 	 * in a 64-bit value.
1144 	 */
1145 	if (errno == ERANGE) {
1146 		if (hdl)
1147 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1148 			    "numeric value is too large"));
1149 		return (-1);
1150 	}
1151 
1152 	/*
1153 	 * If we have a decimal value, then do the computation with floating
1154 	 * point arithmetic.  Otherwise, use standard arithmetic.
1155 	 */
1156 	if (*end == '.') {
1157 		double fval = strtod(value, &end);
1158 
1159 		if ((shift = str2shift(hdl, end)) == -1)
1160 			return (-1);
1161 
1162 		fval *= pow(2, shift);
1163 
1164 		if (fval > UINT64_MAX) {
1165 			if (hdl)
1166 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1167 				    "numeric value is too large"));
1168 			return (-1);
1169 		}
1170 
1171 		*num = (uint64_t)fval;
1172 	} else {
1173 		if ((shift = str2shift(hdl, end)) == -1)
1174 			return (-1);
1175 
1176 		/* Check for overflow */
1177 		if (shift >= 64 || (*num << shift) >> shift != *num) {
1178 			if (hdl)
1179 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1180 				    "numeric value is too large"));
1181 			return (-1);
1182 		}
1183 
1184 		*num <<= shift;
1185 	}
1186 
1187 	return (0);
1188 }
1189 
1190 /*
1191  * Given a propname=value nvpair to set, parse any numeric properties
1192  * (index, boolean, etc) if they are specified as strings and add the
1193  * resulting nvpair to the returned nvlist.
1194  *
1195  * At the DSL layer, all properties are either 64-bit numbers or strings.
1196  * We want the user to be able to ignore this fact and specify properties
1197  * as native values (numbers, for example) or as strings (to simplify
1198  * command line utilities).  This also handles converting index types
1199  * (compression, checksum, etc) from strings to their on-disk index.
1200  */
1201 int
1202 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1203     zfs_type_t type, nvlist_t *ret, char **svalp, uint64_t *ivalp,
1204     const char *errbuf)
1205 {
1206 	data_type_t datatype = nvpair_type(elem);
1207 	zprop_type_t proptype;
1208 	const char *propname;
1209 	char *value;
1210 	boolean_t isnone = B_FALSE;
1211 	boolean_t isauto = B_FALSE;
1212 
1213 	if (type == ZFS_TYPE_POOL) {
1214 		proptype = zpool_prop_get_type(prop);
1215 		propname = zpool_prop_to_name(prop);
1216 	} else {
1217 		proptype = zfs_prop_get_type(prop);
1218 		propname = zfs_prop_to_name(prop);
1219 	}
1220 
1221 	/*
1222 	 * Convert any properties to the internal DSL value types.
1223 	 */
1224 	*svalp = NULL;
1225 	*ivalp = 0;
1226 
1227 	switch (proptype) {
1228 	case PROP_TYPE_STRING:
1229 		if (datatype != DATA_TYPE_STRING) {
1230 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1231 			    "'%s' must be a string"), nvpair_name(elem));
1232 			goto error;
1233 		}
1234 		(void) nvpair_value_string(elem, svalp);
1235 		if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1236 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1237 			    "'%s' is too long"), nvpair_name(elem));
1238 			goto error;
1239 		}
1240 		break;
1241 
1242 	case PROP_TYPE_NUMBER:
1243 		if (datatype == DATA_TYPE_STRING) {
1244 			(void) nvpair_value_string(elem, &value);
1245 			if (strcmp(value, "none") == 0) {
1246 				isnone = B_TRUE;
1247 			} else if (strcmp(value, "auto") == 0) {
1248 				isauto = B_TRUE;
1249 			} else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1250 				goto error;
1251 			}
1252 		} else if (datatype == DATA_TYPE_UINT64) {
1253 			(void) nvpair_value_uint64(elem, ivalp);
1254 		} else {
1255 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1256 			    "'%s' must be a number"), nvpair_name(elem));
1257 			goto error;
1258 		}
1259 
1260 		/*
1261 		 * Quota special: force 'none' and don't allow 0.
1262 		 */
1263 		if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1264 		    (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1265 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1266 			    "use 'none' to disable quota/refquota"));
1267 			goto error;
1268 		}
1269 
1270 		/*
1271 		 * Special handling for "*_limit=none". In this case it's not
1272 		 * 0 but UINT64_MAX.
1273 		 */
1274 		if ((type & ZFS_TYPE_DATASET) && isnone &&
1275 		    (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1276 		    prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1277 			*ivalp = UINT64_MAX;
1278 		}
1279 
1280 		/*
1281 		 * Special handling for setting 'refreservation' to 'auto'.  Use
1282 		 * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1283 		 * 'auto' is only allowed on volumes.
1284 		 */
1285 		if (isauto) {
1286 			switch (prop) {
1287 			case ZFS_PROP_REFRESERVATION:
1288 				if ((type & ZFS_TYPE_VOLUME) == 0) {
1289 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1290 					    "'%s=auto' only allowed on "
1291 					    "volumes"), nvpair_name(elem));
1292 					goto error;
1293 				}
1294 				*ivalp = UINT64_MAX;
1295 				break;
1296 			default:
1297 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1298 				    "'auto' is invalid value for '%s'"),
1299 				    nvpair_name(elem));
1300 				goto error;
1301 			}
1302 		}
1303 
1304 		break;
1305 
1306 	case PROP_TYPE_INDEX:
1307 		if (datatype != DATA_TYPE_STRING) {
1308 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1309 			    "'%s' must be a string"), nvpair_name(elem));
1310 			goto error;
1311 		}
1312 
1313 		(void) nvpair_value_string(elem, &value);
1314 
1315 		if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1316 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1317 			    "'%s' must be one of '%s'"), propname,
1318 			    zprop_values(prop, type));
1319 			goto error;
1320 		}
1321 		break;
1322 
1323 	default:
1324 		abort();
1325 	}
1326 
1327 	/*
1328 	 * Add the result to our return set of properties.
1329 	 */
1330 	if (*svalp != NULL) {
1331 		if (nvlist_add_string(ret, propname, *svalp) != 0) {
1332 			(void) no_memory(hdl);
1333 			return (-1);
1334 		}
1335 	} else {
1336 		if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1337 			(void) no_memory(hdl);
1338 			return (-1);
1339 		}
1340 	}
1341 
1342 	return (0);
1343 error:
1344 	(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1345 	return (-1);
1346 }
1347 
1348 static int
1349 addlist(libzfs_handle_t *hdl, char *propname, zprop_list_t **listp,
1350     zfs_type_t type)
1351 {
1352 	int prop;
1353 	zprop_list_t *entry;
1354 
1355 	prop = zprop_name_to_prop(propname, type);
1356 
1357 	if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type))
1358 		prop = ZPROP_INVAL;
1359 
1360 	/*
1361 	 * When no property table entry can be found, return failure if
1362 	 * this is a pool property or if this isn't a user-defined
1363 	 * dataset property,
1364 	 */
1365 	if (prop == ZPROP_INVAL && ((type == ZFS_TYPE_POOL &&
1366 	    !zpool_prop_feature(propname) &&
1367 	    !zpool_prop_unsupported(propname)) ||
1368 	    (type == ZFS_TYPE_DATASET && !zfs_prop_user(propname) &&
1369 	    !zfs_prop_userquota(propname) && !zfs_prop_written(propname)))) {
1370 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1371 		    "invalid property '%s'"), propname);
1372 		return (zfs_error(hdl, EZFS_BADPROP,
1373 		    dgettext(TEXT_DOMAIN, "bad property list")));
1374 	}
1375 
1376 	if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1377 		return (-1);
1378 
1379 	entry->pl_prop = prop;
1380 	if (prop == ZPROP_INVAL) {
1381 		if ((entry->pl_user_prop = zfs_strdup(hdl, propname)) ==
1382 		    NULL) {
1383 			free(entry);
1384 			return (-1);
1385 		}
1386 		entry->pl_width = strlen(propname);
1387 	} else {
1388 		entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1389 		    type);
1390 	}
1391 
1392 	*listp = entry;
1393 
1394 	return (0);
1395 }
1396 
1397 /*
1398  * Given a comma-separated list of properties, construct a property list
1399  * containing both user-defined and native properties.  This function will
1400  * return a NULL list if 'all' is specified, which can later be expanded
1401  * by zprop_expand_list().
1402  */
1403 int
1404 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1405     zfs_type_t type)
1406 {
1407 	*listp = NULL;
1408 
1409 	/*
1410 	 * If 'all' is specified, return a NULL list.
1411 	 */
1412 	if (strcmp(props, "all") == 0)
1413 		return (0);
1414 
1415 	/*
1416 	 * If no props were specified, return an error.
1417 	 */
1418 	if (props[0] == '\0') {
1419 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1420 		    "no properties specified"));
1421 		return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1422 		    "bad property list")));
1423 	}
1424 
1425 	/*
1426 	 * It would be nice to use getsubopt() here, but the inclusion of column
1427 	 * aliases makes this more effort than it's worth.
1428 	 */
1429 	while (*props != '\0') {
1430 		size_t len;
1431 		char *p;
1432 		char c;
1433 
1434 		if ((p = strchr(props, ',')) == NULL) {
1435 			len = strlen(props);
1436 			p = props + len;
1437 		} else {
1438 			len = p - props;
1439 		}
1440 
1441 		/*
1442 		 * Check for empty options.
1443 		 */
1444 		if (len == 0) {
1445 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1446 			    "empty property name"));
1447 			return (zfs_error(hdl, EZFS_BADPROP,
1448 			    dgettext(TEXT_DOMAIN, "bad property list")));
1449 		}
1450 
1451 		/*
1452 		 * Check all regular property names.
1453 		 */
1454 		c = props[len];
1455 		props[len] = '\0';
1456 
1457 		if (strcmp(props, "space") == 0) {
1458 			static char *spaceprops[] = {
1459 				"name", "avail", "used", "usedbysnapshots",
1460 				"usedbydataset", "usedbyrefreservation",
1461 				"usedbychildren", NULL
1462 			};
1463 			int i;
1464 
1465 			for (i = 0; spaceprops[i]; i++) {
1466 				if (addlist(hdl, spaceprops[i], listp, type))
1467 					return (-1);
1468 				listp = &(*listp)->pl_next;
1469 			}
1470 		} else {
1471 			if (addlist(hdl, props, listp, type))
1472 				return (-1);
1473 			listp = &(*listp)->pl_next;
1474 		}
1475 
1476 		props = p;
1477 		if (c == ',')
1478 			props++;
1479 	}
1480 
1481 	return (0);
1482 }
1483 
1484 void
1485 zprop_free_list(zprop_list_t *pl)
1486 {
1487 	zprop_list_t *next;
1488 
1489 	while (pl != NULL) {
1490 		next = pl->pl_next;
1491 		free(pl->pl_user_prop);
1492 		free(pl);
1493 		pl = next;
1494 	}
1495 }
1496 
1497 typedef struct expand_data {
1498 	zprop_list_t	**last;
1499 	libzfs_handle_t	*hdl;
1500 	zfs_type_t type;
1501 } expand_data_t;
1502 
1503 int
1504 zprop_expand_list_cb(int prop, void *cb)
1505 {
1506 	zprop_list_t *entry;
1507 	expand_data_t *edp = cb;
1508 
1509 	if ((entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t))) == NULL)
1510 		return (ZPROP_INVAL);
1511 
1512 	entry->pl_prop = prop;
1513 	entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
1514 	entry->pl_all = B_TRUE;
1515 
1516 	*(edp->last) = entry;
1517 	edp->last = &entry->pl_next;
1518 
1519 	return (ZPROP_CONT);
1520 }
1521 
1522 int
1523 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
1524 {
1525 	zprop_list_t *entry;
1526 	zprop_list_t **last;
1527 	expand_data_t exp;
1528 
1529 	if (*plp == NULL) {
1530 		/*
1531 		 * If this is the very first time we've been called for an 'all'
1532 		 * specification, expand the list to include all native
1533 		 * properties.
1534 		 */
1535 		last = plp;
1536 
1537 		exp.last = last;
1538 		exp.hdl = hdl;
1539 		exp.type = type;
1540 
1541 		if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
1542 		    B_FALSE, type) == ZPROP_INVAL)
1543 			return (-1);
1544 
1545 		/*
1546 		 * Add 'name' to the beginning of the list, which is handled
1547 		 * specially.
1548 		 */
1549 		if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1550 			return (-1);
1551 
1552 		entry->pl_prop = (type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME :
1553 		    ZFS_PROP_NAME;
1554 		entry->pl_width = zprop_width(entry->pl_prop,
1555 		    &entry->pl_fixed, type);
1556 		entry->pl_all = B_TRUE;
1557 		entry->pl_next = *plp;
1558 		*plp = entry;
1559 	}
1560 	return (0);
1561 }
1562 
1563 int
1564 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
1565     zfs_type_t type)
1566 {
1567 	return (zprop_iter_common(func, cb, show_all, ordered, type));
1568 }
1569 
1570 /*
1571  * zfs_get_hole_count retrieves the number of holes (blocks which are
1572  * zero-filled) in the specified file using the _FIO_COUNT_FILLED ioctl. It
1573  * also optionally fetches the block size when bs is non-NULL. With hole count
1574  * and block size the full space consumed by the holes of a file can be
1575  * calculated.
1576  *
1577  * On success, zero is returned, the count argument is set to the
1578  * number of holes, and the bs argument is set to the block size (if it is
1579  * not NULL). On error, a non-zero errno is returned and the values in count
1580  * and bs are undefined.
1581  */
1582 int
1583 zfs_get_hole_count(const char *path, uint64_t *count, uint64_t *bs)
1584 {
1585 	int fd, err;
1586 	struct stat64 ss;
1587 	uint64_t fill;
1588 
1589 	fd = open(path, O_RDONLY | O_LARGEFILE);
1590 	if (fd == -1)
1591 		return (errno);
1592 
1593 	if (ioctl(fd, _FIO_COUNT_FILLED, &fill) == -1) {
1594 		err = errno;
1595 		(void) close(fd);
1596 		return (err);
1597 	}
1598 
1599 	if (fstat64(fd, &ss) == -1) {
1600 		err = errno;
1601 		(void) close(fd);
1602 		return (err);
1603 	}
1604 
1605 	*count = (ss.st_size + ss.st_blksize - 1) / ss.st_blksize - fill;
1606 	VERIFY3S(*count, >=, 0);
1607 	if (bs != NULL) {
1608 		*bs = ss.st_blksize;
1609 	}
1610 
1611 	if (close(fd) == -1) {
1612 		return (errno);
1613 	}
1614 	return (0);
1615 }
1616 
1617 ulong_t
1618 get_system_hostid(void)
1619 {
1620 	char *env;
1621 
1622 	/*
1623 	 * Allow the hostid to be subverted for testing.
1624 	 */
1625 	env = getenv("ZFS_HOSTID");
1626 	if (env) {
1627 		ulong_t hostid = strtoull(env, NULL, 16);
1628 		return (hostid & 0xFFFFFFFF);
1629 	}
1630 
1631 	return (gethostid());
1632 }
1633