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