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