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