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 != NULL)
688 		(void) fclose(hdl->libzfs_mnttab);
689 	if (hdl->libzfs_sharetab != NULL)
690 		(void) fclose(hdl->libzfs_sharetab);
691 	if (hdl->libzfs_devlink != NULL)
692 		(void) di_devlink_fini(&hdl->libzfs_devlink);
693 	zfs_uninit_libshare(hdl);
694 	zpool_free_handles(hdl);
695 	libzfs_fru_clear(hdl, B_TRUE);
696 	namespace_clear(hdl);
697 	libzfs_mnttab_fini(hdl);
698 	libzfs_core_fini();
699 	free(hdl);
700 }
701 
702 libzfs_handle_t *
703 zpool_get_handle(zpool_handle_t *zhp)
704 {
705 	return (zhp->zpool_hdl);
706 }
707 
708 libzfs_handle_t *
709 zfs_get_handle(zfs_handle_t *zhp)
710 {
711 	return (zhp->zfs_hdl);
712 }
713 
714 zpool_handle_t *
715 zfs_get_pool_handle(const zfs_handle_t *zhp)
716 {
717 	return (zhp->zpool_hdl);
718 }
719 
720 /*
721  * Given a name, determine whether or not it's a valid path
722  * (starts with '/' or "./").  If so, walk the mnttab trying
723  * to match the device number.  If not, treat the path as an
724  * fs/vol/snap/bkmark name.
725  */
726 zfs_handle_t *
727 zfs_path_to_zhandle(libzfs_handle_t *hdl, char *path, zfs_type_t argtype)
728 {
729 	struct stat64 statbuf;
730 	struct extmnttab entry;
731 	int ret;
732 
733 	if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
734 		/*
735 		 * It's not a valid path, assume it's a name of type 'argtype'.
736 		 */
737 		return (zfs_open(hdl, path, argtype));
738 	}
739 
740 	if (stat64(path, &statbuf) != 0) {
741 		(void) fprintf(stderr, "%s: %s\n", path, strerror(errno));
742 		return (NULL);
743 	}
744 
745 	rewind(hdl->libzfs_mnttab);
746 	while ((ret = getextmntent(hdl->libzfs_mnttab, &entry, 0)) == 0) {
747 		if (makedevice(entry.mnt_major, entry.mnt_minor) ==
748 		    statbuf.st_dev) {
749 			break;
750 		}
751 	}
752 	if (ret != 0) {
753 		return (NULL);
754 	}
755 
756 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
757 		(void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
758 		    path);
759 		return (NULL);
760 	}
761 
762 	return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
763 }
764 
765 /*
766  * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
767  * an ioctl().
768  */
769 int
770 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
771 {
772 	if (len == 0)
773 		len = 16 * 1024;
774 	zc->zc_nvlist_dst_size = len;
775 	zc->zc_nvlist_dst =
776 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
777 	if (zc->zc_nvlist_dst == 0)
778 		return (-1);
779 
780 	return (0);
781 }
782 
783 /*
784  * Called when an ioctl() which returns an nvlist fails with ENOMEM.  This will
785  * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
786  * filled in by the kernel to indicate the actual required size.
787  */
788 int
789 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
790 {
791 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
792 	zc->zc_nvlist_dst =
793 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
794 	if (zc->zc_nvlist_dst == 0)
795 		return (-1);
796 
797 	return (0);
798 }
799 
800 /*
801  * Called to free the src and dst nvlists stored in the command structure.
802  */
803 void
804 zcmd_free_nvlists(zfs_cmd_t *zc)
805 {
806 	free((void *)(uintptr_t)zc->zc_nvlist_conf);
807 	free((void *)(uintptr_t)zc->zc_nvlist_src);
808 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
809 	zc->zc_nvlist_conf = 0;
810 	zc->zc_nvlist_src = 0;
811 	zc->zc_nvlist_dst = 0;
812 }
813 
814 static int
815 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
816     nvlist_t *nvl)
817 {
818 	char *packed;
819 	size_t len;
820 
821 	verify(nvlist_size(nvl, &len, NV_ENCODE_NATIVE) == 0);
822 
823 	if ((packed = zfs_alloc(hdl, len)) == NULL)
824 		return (-1);
825 
826 	verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
827 
828 	*outnv = (uint64_t)(uintptr_t)packed;
829 	*outlen = len;
830 
831 	return (0);
832 }
833 
834 int
835 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
836 {
837 	return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
838 	    &zc->zc_nvlist_conf_size, nvl));
839 }
840 
841 int
842 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
843 {
844 	return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
845 	    &zc->zc_nvlist_src_size, nvl));
846 }
847 
848 /*
849  * Unpacks an nvlist from the ZFS ioctl command structure.
850  */
851 int
852 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
853 {
854 	if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
855 	    zc->zc_nvlist_dst_size, nvlp, 0) != 0)
856 		return (no_memory(hdl));
857 
858 	return (0);
859 }
860 
861 int
862 zfs_ioctl(libzfs_handle_t *hdl, int request, zfs_cmd_t *zc)
863 {
864 	return (ioctl(hdl->libzfs_fd, request, zc));
865 }
866 
867 /*
868  * ================================================================
869  * API shared by zfs and zpool property management
870  * ================================================================
871  */
872 
873 static void
874 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
875 {
876 	zprop_list_t *pl = cbp->cb_proplist;
877 	int i;
878 	char *title;
879 	size_t len;
880 
881 	cbp->cb_first = B_FALSE;
882 	if (cbp->cb_scripted)
883 		return;
884 
885 	/*
886 	 * Start with the length of the column headers.
887 	 */
888 	cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
889 	cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
890 	    "PROPERTY"));
891 	cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
892 	    "VALUE"));
893 	cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
894 	    "RECEIVED"));
895 	cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
896 	    "SOURCE"));
897 
898 	/* first property is always NAME */
899 	assert(cbp->cb_proplist->pl_prop ==
900 	    ((type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME : ZFS_PROP_NAME));
901 
902 	/*
903 	 * Go through and calculate the widths for each column.  For the
904 	 * 'source' column, we kludge it up by taking the worst-case scenario of
905 	 * inheriting from the longest name.  This is acceptable because in the
906 	 * majority of cases 'SOURCE' is the last column displayed, and we don't
907 	 * use the width anyway.  Note that the 'VALUE' column can be oversized,
908 	 * if the name of the property is much longer than any values we find.
909 	 */
910 	for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
911 		/*
912 		 * 'PROPERTY' column
913 		 */
914 		if (pl->pl_prop != ZPROP_INVAL) {
915 			const char *propname = (type == ZFS_TYPE_POOL) ?
916 			    zpool_prop_to_name(pl->pl_prop) :
917 			    zfs_prop_to_name(pl->pl_prop);
918 
919 			len = strlen(propname);
920 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
921 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
922 		} else {
923 			len = strlen(pl->pl_user_prop);
924 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
925 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
926 		}
927 
928 		/*
929 		 * 'VALUE' column.  The first property is always the 'name'
930 		 * property that was tacked on either by /sbin/zfs's
931 		 * zfs_do_get() or when calling zprop_expand_list(), so we
932 		 * ignore its width.  If the user specified the name property
933 		 * to display, then it will be later in the list in any case.
934 		 */
935 		if (pl != cbp->cb_proplist &&
936 		    pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
937 			cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
938 
939 		/* 'RECEIVED' column. */
940 		if (pl != cbp->cb_proplist &&
941 		    pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
942 			cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
943 
944 		/*
945 		 * 'NAME' and 'SOURCE' columns
946 		 */
947 		if (pl->pl_prop == (type == ZFS_TYPE_POOL ? ZPOOL_PROP_NAME :
948 		    ZFS_PROP_NAME) &&
949 		    pl->pl_width > cbp->cb_colwidths[GET_COL_NAME]) {
950 			cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
951 			cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
952 			    strlen(dgettext(TEXT_DOMAIN, "inherited from"));
953 		}
954 	}
955 
956 	/*
957 	 * Now go through and print the headers.
958 	 */
959 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
960 		switch (cbp->cb_columns[i]) {
961 		case GET_COL_NAME:
962 			title = dgettext(TEXT_DOMAIN, "NAME");
963 			break;
964 		case GET_COL_PROPERTY:
965 			title = dgettext(TEXT_DOMAIN, "PROPERTY");
966 			break;
967 		case GET_COL_VALUE:
968 			title = dgettext(TEXT_DOMAIN, "VALUE");
969 			break;
970 		case GET_COL_RECVD:
971 			title = dgettext(TEXT_DOMAIN, "RECEIVED");
972 			break;
973 		case GET_COL_SOURCE:
974 			title = dgettext(TEXT_DOMAIN, "SOURCE");
975 			break;
976 		default:
977 			title = NULL;
978 		}
979 
980 		if (title != NULL) {
981 			if (i == (ZFS_GET_NCOLS - 1) ||
982 			    cbp->cb_columns[i + 1] == GET_COL_NONE)
983 				(void) printf("%s", title);
984 			else
985 				(void) printf("%-*s  ",
986 				    cbp->cb_colwidths[cbp->cb_columns[i]],
987 				    title);
988 		}
989 	}
990 	(void) printf("\n");
991 }
992 
993 /*
994  * Display a single line of output, according to the settings in the callback
995  * structure.
996  */
997 void
998 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
999     const char *propname, const char *value, zprop_source_t sourcetype,
1000     const char *source, const char *recvd_value)
1001 {
1002 	int i;
1003 	const char *str = NULL;
1004 	char buf[128];
1005 
1006 	/*
1007 	 * Ignore those source types that the user has chosen to ignore.
1008 	 */
1009 	if ((sourcetype & cbp->cb_sources) == 0)
1010 		return;
1011 
1012 	if (cbp->cb_first)
1013 		zprop_print_headers(cbp, cbp->cb_type);
1014 
1015 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1016 		switch (cbp->cb_columns[i]) {
1017 		case GET_COL_NAME:
1018 			str = name;
1019 			break;
1020 
1021 		case GET_COL_PROPERTY:
1022 			str = propname;
1023 			break;
1024 
1025 		case GET_COL_VALUE:
1026 			str = value;
1027 			break;
1028 
1029 		case GET_COL_SOURCE:
1030 			switch (sourcetype) {
1031 			case ZPROP_SRC_NONE:
1032 				str = "-";
1033 				break;
1034 
1035 			case ZPROP_SRC_DEFAULT:
1036 				str = "default";
1037 				break;
1038 
1039 			case ZPROP_SRC_LOCAL:
1040 				str = "local";
1041 				break;
1042 
1043 			case ZPROP_SRC_TEMPORARY:
1044 				str = "temporary";
1045 				break;
1046 
1047 			case ZPROP_SRC_INHERITED:
1048 				(void) snprintf(buf, sizeof (buf),
1049 				    "inherited from %s", source);
1050 				str = buf;
1051 				break;
1052 			case ZPROP_SRC_RECEIVED:
1053 				str = "received";
1054 				break;
1055 
1056 			default:
1057 				str = NULL;
1058 				assert(!"unhandled zprop_source_t");
1059 			}
1060 			break;
1061 
1062 		case GET_COL_RECVD:
1063 			str = (recvd_value == NULL ? "-" : recvd_value);
1064 			break;
1065 
1066 		default:
1067 			continue;
1068 		}
1069 
1070 		if (cbp->cb_columns[i + 1] == GET_COL_NONE)
1071 			(void) printf("%s", str);
1072 		else if (cbp->cb_scripted)
1073 			(void) printf("%s\t", str);
1074 		else
1075 			(void) printf("%-*s  ",
1076 			    cbp->cb_colwidths[cbp->cb_columns[i]],
1077 			    str);
1078 	}
1079 
1080 	(void) printf("\n");
1081 }
1082 
1083 /*
1084  * Given a numeric suffix, convert the value into a number of bits that the
1085  * resulting value must be shifted.
1086  */
1087 static int
1088 str2shift(libzfs_handle_t *hdl, const char *buf)
1089 {
1090 	const char *ends = "BKMGTPEZ";
1091 	int i;
1092 
1093 	if (buf[0] == '\0')
1094 		return (0);
1095 	for (i = 0; i < strlen(ends); i++) {
1096 		if (toupper(buf[0]) == ends[i])
1097 			break;
1098 	}
1099 	if (i == strlen(ends)) {
1100 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1101 		    "invalid numeric suffix '%s'"), buf);
1102 		return (-1);
1103 	}
1104 
1105 	/*
1106 	 * We want to allow trailing 'b' characters for 'GB' or 'Mb'.  But don't
1107 	 * allow 'BB' - that's just weird.
1108 	 */
1109 	if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0' &&
1110 	    toupper(buf[0]) != 'B'))
1111 		return (10*i);
1112 
1113 	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1114 	    "invalid numeric suffix '%s'"), buf);
1115 	return (-1);
1116 }
1117 
1118 /*
1119  * Convert a string of the form '100G' into a real number.  Used when setting
1120  * properties or creating a volume.  'buf' is used to place an extended error
1121  * message for the caller to use.
1122  */
1123 int
1124 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1125 {
1126 	char *end;
1127 	int shift;
1128 
1129 	*num = 0;
1130 
1131 	/* Check to see if this looks like a number.  */
1132 	if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1133 		if (hdl)
1134 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1135 			    "bad numeric value '%s'"), value);
1136 		return (-1);
1137 	}
1138 
1139 	/* Rely on strtoull() to process the numeric portion.  */
1140 	errno = 0;
1141 	*num = strtoull(value, &end, 10);
1142 
1143 	/*
1144 	 * Check for ERANGE, which indicates that the value is too large to fit
1145 	 * in a 64-bit value.
1146 	 */
1147 	if (errno == ERANGE) {
1148 		if (hdl)
1149 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1150 			    "numeric value is too large"));
1151 		return (-1);
1152 	}
1153 
1154 	/*
1155 	 * If we have a decimal value, then do the computation with floating
1156 	 * point arithmetic.  Otherwise, use standard arithmetic.
1157 	 */
1158 	if (*end == '.') {
1159 		double fval = strtod(value, &end);
1160 
1161 		if ((shift = str2shift(hdl, end)) == -1)
1162 			return (-1);
1163 
1164 		fval *= pow(2, shift);
1165 
1166 		if (fval > UINT64_MAX) {
1167 			if (hdl)
1168 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1169 				    "numeric value is too large"));
1170 			return (-1);
1171 		}
1172 
1173 		*num = (uint64_t)fval;
1174 	} else {
1175 		if ((shift = str2shift(hdl, end)) == -1)
1176 			return (-1);
1177 
1178 		/* Check for overflow */
1179 		if (shift >= 64 || (*num << shift) >> shift != *num) {
1180 			if (hdl)
1181 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1182 				    "numeric value is too large"));
1183 			return (-1);
1184 		}
1185 
1186 		*num <<= shift;
1187 	}
1188 
1189 	return (0);
1190 }
1191 
1192 /*
1193  * Given a propname=value nvpair to set, parse any numeric properties
1194  * (index, boolean, etc) if they are specified as strings and add the
1195  * resulting nvpair to the returned nvlist.
1196  *
1197  * At the DSL layer, all properties are either 64-bit numbers or strings.
1198  * We want the user to be able to ignore this fact and specify properties
1199  * as native values (numbers, for example) or as strings (to simplify
1200  * command line utilities).  This also handles converting index types
1201  * (compression, checksum, etc) from strings to their on-disk index.
1202  */
1203 int
1204 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1205     zfs_type_t type, nvlist_t *ret, char **svalp, uint64_t *ivalp,
1206     const char *errbuf)
1207 {
1208 	data_type_t datatype = nvpair_type(elem);
1209 	zprop_type_t proptype;
1210 	const char *propname;
1211 	char *value;
1212 	boolean_t isnone = B_FALSE;
1213 	boolean_t isauto = B_FALSE;
1214 
1215 	if (type == ZFS_TYPE_POOL) {
1216 		proptype = zpool_prop_get_type(prop);
1217 		propname = zpool_prop_to_name(prop);
1218 	} else {
1219 		proptype = zfs_prop_get_type(prop);
1220 		propname = zfs_prop_to_name(prop);
1221 	}
1222 
1223 	/*
1224 	 * Convert any properties to the internal DSL value types.
1225 	 */
1226 	*svalp = NULL;
1227 	*ivalp = 0;
1228 
1229 	switch (proptype) {
1230 	case PROP_TYPE_STRING:
1231 		if (datatype != DATA_TYPE_STRING) {
1232 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1233 			    "'%s' must be a string"), nvpair_name(elem));
1234 			goto error;
1235 		}
1236 		(void) nvpair_value_string(elem, svalp);
1237 		if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1238 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1239 			    "'%s' is too long"), nvpair_name(elem));
1240 			goto error;
1241 		}
1242 		break;
1243 
1244 	case PROP_TYPE_NUMBER:
1245 		if (datatype == DATA_TYPE_STRING) {
1246 			(void) nvpair_value_string(elem, &value);
1247 			if (strcmp(value, "none") == 0) {
1248 				isnone = B_TRUE;
1249 			} else if (strcmp(value, "auto") == 0) {
1250 				isauto = B_TRUE;
1251 			} else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1252 				goto error;
1253 			}
1254 		} else if (datatype == DATA_TYPE_UINT64) {
1255 			(void) nvpair_value_uint64(elem, ivalp);
1256 		} else {
1257 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1258 			    "'%s' must be a number"), nvpair_name(elem));
1259 			goto error;
1260 		}
1261 
1262 		/*
1263 		 * Quota special: force 'none' and don't allow 0.
1264 		 */
1265 		if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1266 		    (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1267 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1268 			    "use 'none' to disable quota/refquota"));
1269 			goto error;
1270 		}
1271 
1272 		/*
1273 		 * Special handling for "*_limit=none". In this case it's not
1274 		 * 0 but UINT64_MAX.
1275 		 */
1276 		if ((type & ZFS_TYPE_DATASET) && isnone &&
1277 		    (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1278 		    prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1279 			*ivalp = UINT64_MAX;
1280 		}
1281 
1282 		/*
1283 		 * Special handling for setting 'refreservation' to 'auto'.  Use
1284 		 * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1285 		 * 'auto' is only allowed on volumes.
1286 		 */
1287 		if (isauto) {
1288 			switch (prop) {
1289 			case ZFS_PROP_REFRESERVATION:
1290 				if ((type & ZFS_TYPE_VOLUME) == 0) {
1291 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1292 					    "'%s=auto' only allowed on "
1293 					    "volumes"), nvpair_name(elem));
1294 					goto error;
1295 				}
1296 				*ivalp = UINT64_MAX;
1297 				break;
1298 			default:
1299 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1300 				    "'auto' is invalid value for '%s'"),
1301 				    nvpair_name(elem));
1302 				goto error;
1303 			}
1304 		}
1305 
1306 		break;
1307 
1308 	case PROP_TYPE_INDEX:
1309 		if (datatype != DATA_TYPE_STRING) {
1310 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1311 			    "'%s' must be a string"), nvpair_name(elem));
1312 			goto error;
1313 		}
1314 
1315 		(void) nvpair_value_string(elem, &value);
1316 
1317 		if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1318 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1319 			    "'%s' must be one of '%s'"), propname,
1320 			    zprop_values(prop, type));
1321 			goto error;
1322 		}
1323 		break;
1324 
1325 	default:
1326 		abort();
1327 	}
1328 
1329 	/*
1330 	 * Add the result to our return set of properties.
1331 	 */
1332 	if (*svalp != NULL) {
1333 		if (nvlist_add_string(ret, propname, *svalp) != 0) {
1334 			(void) no_memory(hdl);
1335 			return (-1);
1336 		}
1337 	} else {
1338 		if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1339 			(void) no_memory(hdl);
1340 			return (-1);
1341 		}
1342 	}
1343 
1344 	return (0);
1345 error:
1346 	(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1347 	return (-1);
1348 }
1349 
1350 static int
1351 addlist(libzfs_handle_t *hdl, char *propname, zprop_list_t **listp,
1352     zfs_type_t type)
1353 {
1354 	int prop;
1355 	zprop_list_t *entry;
1356 
1357 	prop = zprop_name_to_prop(propname, type);
1358 
1359 	if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type))
1360 		prop = ZPROP_INVAL;
1361 
1362 	/*
1363 	 * When no property table entry can be found, return failure if
1364 	 * this is a pool property or if this isn't a user-defined
1365 	 * dataset property,
1366 	 */
1367 	if (prop == ZPROP_INVAL && ((type == ZFS_TYPE_POOL &&
1368 	    !zpool_prop_feature(propname) &&
1369 	    !zpool_prop_unsupported(propname)) ||
1370 	    (type == ZFS_TYPE_DATASET && !zfs_prop_user(propname) &&
1371 	    !zfs_prop_userquota(propname) && !zfs_prop_written(propname)))) {
1372 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1373 		    "invalid property '%s'"), propname);
1374 		return (zfs_error(hdl, EZFS_BADPROP,
1375 		    dgettext(TEXT_DOMAIN, "bad property list")));
1376 	}
1377 
1378 	if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1379 		return (-1);
1380 
1381 	entry->pl_prop = prop;
1382 	if (prop == ZPROP_INVAL) {
1383 		if ((entry->pl_user_prop = zfs_strdup(hdl, propname)) ==
1384 		    NULL) {
1385 			free(entry);
1386 			return (-1);
1387 		}
1388 		entry->pl_width = strlen(propname);
1389 	} else {
1390 		entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1391 		    type);
1392 	}
1393 
1394 	*listp = entry;
1395 
1396 	return (0);
1397 }
1398 
1399 /*
1400  * Given a comma-separated list of properties, construct a property list
1401  * containing both user-defined and native properties.  This function will
1402  * return a NULL list if 'all' is specified, which can later be expanded
1403  * by zprop_expand_list().
1404  */
1405 int
1406 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1407     zfs_type_t type)
1408 {
1409 	*listp = NULL;
1410 
1411 	/*
1412 	 * If 'all' is specified, return a NULL list.
1413 	 */
1414 	if (strcmp(props, "all") == 0)
1415 		return (0);
1416 
1417 	/*
1418 	 * If no props were specified, return an error.
1419 	 */
1420 	if (props[0] == '\0') {
1421 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1422 		    "no properties specified"));
1423 		return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1424 		    "bad property list")));
1425 	}
1426 
1427 	/*
1428 	 * It would be nice to use getsubopt() here, but the inclusion of column
1429 	 * aliases makes this more effort than it's worth.
1430 	 */
1431 	while (*props != '\0') {
1432 		size_t len;
1433 		char *p;
1434 		char c;
1435 
1436 		if ((p = strchr(props, ',')) == NULL) {
1437 			len = strlen(props);
1438 			p = props + len;
1439 		} else {
1440 			len = p - props;
1441 		}
1442 
1443 		/*
1444 		 * Check for empty options.
1445 		 */
1446 		if (len == 0) {
1447 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1448 			    "empty property name"));
1449 			return (zfs_error(hdl, EZFS_BADPROP,
1450 			    dgettext(TEXT_DOMAIN, "bad property list")));
1451 		}
1452 
1453 		/*
1454 		 * Check all regular property names.
1455 		 */
1456 		c = props[len];
1457 		props[len] = '\0';
1458 
1459 		if (strcmp(props, "space") == 0) {
1460 			static char *spaceprops[] = {
1461 				"name", "avail", "used", "usedbysnapshots",
1462 				"usedbydataset", "usedbyrefreservation",
1463 				"usedbychildren", NULL
1464 			};
1465 			int i;
1466 
1467 			for (i = 0; spaceprops[i]; i++) {
1468 				if (addlist(hdl, spaceprops[i], listp, type))
1469 					return (-1);
1470 				listp = &(*listp)->pl_next;
1471 			}
1472 		} else {
1473 			if (addlist(hdl, props, listp, type))
1474 				return (-1);
1475 			listp = &(*listp)->pl_next;
1476 		}
1477 
1478 		props = p;
1479 		if (c == ',')
1480 			props++;
1481 	}
1482 
1483 	return (0);
1484 }
1485 
1486 void
1487 zprop_free_list(zprop_list_t *pl)
1488 {
1489 	zprop_list_t *next;
1490 
1491 	while (pl != NULL) {
1492 		next = pl->pl_next;
1493 		free(pl->pl_user_prop);
1494 		free(pl);
1495 		pl = next;
1496 	}
1497 }
1498 
1499 typedef struct expand_data {
1500 	zprop_list_t	**last;
1501 	libzfs_handle_t	*hdl;
1502 	zfs_type_t type;
1503 } expand_data_t;
1504 
1505 int
1506 zprop_expand_list_cb(int prop, void *cb)
1507 {
1508 	zprop_list_t *entry;
1509 	expand_data_t *edp = cb;
1510 
1511 	if ((entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t))) == NULL)
1512 		return (ZPROP_INVAL);
1513 
1514 	entry->pl_prop = prop;
1515 	entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
1516 	entry->pl_all = B_TRUE;
1517 
1518 	*(edp->last) = entry;
1519 	edp->last = &entry->pl_next;
1520 
1521 	return (ZPROP_CONT);
1522 }
1523 
1524 int
1525 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
1526 {
1527 	zprop_list_t *entry;
1528 	zprop_list_t **last;
1529 	expand_data_t exp;
1530 
1531 	if (*plp == NULL) {
1532 		/*
1533 		 * If this is the very first time we've been called for an 'all'
1534 		 * specification, expand the list to include all native
1535 		 * properties.
1536 		 */
1537 		last = plp;
1538 
1539 		exp.last = last;
1540 		exp.hdl = hdl;
1541 		exp.type = type;
1542 
1543 		if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
1544 		    B_FALSE, type) == ZPROP_INVAL)
1545 			return (-1);
1546 
1547 		/*
1548 		 * Add 'name' to the beginning of the list, which is handled
1549 		 * specially.
1550 		 */
1551 		if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1552 			return (-1);
1553 
1554 		entry->pl_prop = (type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME :
1555 		    ZFS_PROP_NAME;
1556 		entry->pl_width = zprop_width(entry->pl_prop,
1557 		    &entry->pl_fixed, type);
1558 		entry->pl_all = B_TRUE;
1559 		entry->pl_next = *plp;
1560 		*plp = entry;
1561 	}
1562 	return (0);
1563 }
1564 
1565 int
1566 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
1567     zfs_type_t type)
1568 {
1569 	return (zprop_iter_common(func, cb, show_all, ordered, type));
1570 }
1571 
1572 /*
1573  * zfs_get_hole_count retrieves the number of holes (blocks which are
1574  * zero-filled) in the specified file using the _FIO_COUNT_FILLED ioctl. It
1575  * also optionally fetches the block size when bs is non-NULL. With hole count
1576  * and block size the full space consumed by the holes of a file can be
1577  * calculated.
1578  *
1579  * On success, zero is returned, the count argument is set to the
1580  * number of holes, and the bs argument is set to the block size (if it is
1581  * not NULL). On error, a non-zero errno is returned and the values in count
1582  * and bs are undefined.
1583  */
1584 int
1585 zfs_get_hole_count(const char *path, uint64_t *count, uint64_t *bs)
1586 {
1587 	int fd, err;
1588 	struct stat64 ss;
1589 	uint64_t fill;
1590 
1591 	fd = open(path, O_RDONLY | O_LARGEFILE);
1592 	if (fd == -1)
1593 		return (errno);
1594 
1595 	if (ioctl(fd, _FIO_COUNT_FILLED, &fill) == -1) {
1596 		err = errno;
1597 		(void) close(fd);
1598 		return (err);
1599 	}
1600 
1601 	if (fstat64(fd, &ss) == -1) {
1602 		err = errno;
1603 		(void) close(fd);
1604 		return (err);
1605 	}
1606 
1607 	*count = (ss.st_size + ss.st_blksize - 1) / ss.st_blksize - fill;
1608 	VERIFY3S(*count, >=, 0);
1609 	if (bs != NULL) {
1610 		*bs = ss.st_blksize;
1611 	}
1612 
1613 	if (close(fd) == -1) {
1614 		return (errno);
1615 	}
1616 	return (0);
1617 }
1618 
1619 ulong_t
1620 get_system_hostid(void)
1621 {
1622 	char *env;
1623 
1624 	/*
1625 	 * Allow the hostid to be subverted for testing.
1626 	 */
1627 	env = getenv("ZFS_HOSTID");
1628 	if (env) {
1629 		ulong_t hostid = strtoull(env, NULL, 16);
1630 		return (hostid & 0xFFFFFFFF);
1631 	}
1632 
1633 	return (gethostid());
1634 }
1635