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