]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libzfs/libzfs_util.c
Add basic zfs ioc input nvpair validation
[FreeBSD/FreeBSD.git] / lib / libzfs / libzfs_util.c
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. All rights reserved.
25  * Copyright (c) 2011, 2018 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/stat.h>
45 #include <sys/mnttab.h>
46 #include <sys/mntent.h>
47 #include <sys/types.h>
48 #include <sys/wait.h>
49
50 #include <libzfs.h>
51 #include <libzfs_core.h>
52
53 #include "libzfs_impl.h"
54 #include "zfs_prop.h"
55 #include "zfeature_common.h"
56 #include <zfs_fletcher.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_init(int error)
66 {
67         switch (error) {
68         case ENXIO:
69                 return (dgettext(TEXT_DOMAIN, "The ZFS modules are not "
70                     "loaded.\nTry running '/sbin/modprobe zfs' as root "
71                     "to load them.\n"));
72         case ENOENT:
73                 return (dgettext(TEXT_DOMAIN, "/dev/zfs and /proc/self/mounts "
74                     "are required.\nTry running 'udevadm trigger' and 'mount "
75                     "-t proc proc /proc' as root.\n"));
76         case ENOEXEC:
77                 return (dgettext(TEXT_DOMAIN, "The ZFS modules cannot be "
78                     "auto-loaded.\nTry running '/sbin/modprobe zfs' as "
79                     "root to manually load them.\n"));
80         case EACCES:
81                 return (dgettext(TEXT_DOMAIN, "Permission denied the "
82                     "ZFS utilities must be run as root.\n"));
83         default:
84                 return (dgettext(TEXT_DOMAIN, "Failed to initialize the "
85                     "libzfs library.\n"));
86         }
87 }
88
89 const char *
90 libzfs_error_action(libzfs_handle_t *hdl)
91 {
92         return (hdl->libzfs_action);
93 }
94
95 const char *
96 libzfs_error_description(libzfs_handle_t *hdl)
97 {
98         if (hdl->libzfs_desc[0] != '\0')
99                 return (hdl->libzfs_desc);
100
101         switch (hdl->libzfs_error) {
102         case EZFS_NOMEM:
103                 return (dgettext(TEXT_DOMAIN, "out of memory"));
104         case EZFS_BADPROP:
105                 return (dgettext(TEXT_DOMAIN, "invalid property value"));
106         case EZFS_PROPREADONLY:
107                 return (dgettext(TEXT_DOMAIN, "read-only property"));
108         case EZFS_PROPTYPE:
109                 return (dgettext(TEXT_DOMAIN, "property doesn't apply to "
110                     "datasets of this type"));
111         case EZFS_PROPNONINHERIT:
112                 return (dgettext(TEXT_DOMAIN, "property cannot be inherited"));
113         case EZFS_PROPSPACE:
114                 return (dgettext(TEXT_DOMAIN, "invalid quota or reservation"));
115         case EZFS_BADTYPE:
116                 return (dgettext(TEXT_DOMAIN, "operation not applicable to "
117                     "datasets of this type"));
118         case EZFS_BUSY:
119                 return (dgettext(TEXT_DOMAIN, "pool or dataset is busy"));
120         case EZFS_EXISTS:
121                 return (dgettext(TEXT_DOMAIN, "pool or dataset exists"));
122         case EZFS_NOENT:
123                 return (dgettext(TEXT_DOMAIN, "no such pool or dataset"));
124         case EZFS_BADSTREAM:
125                 return (dgettext(TEXT_DOMAIN, "invalid backup stream"));
126         case EZFS_DSREADONLY:
127                 return (dgettext(TEXT_DOMAIN, "dataset is read-only"));
128         case EZFS_VOLTOOBIG:
129                 return (dgettext(TEXT_DOMAIN, "volume size exceeds limit for "
130                     "this system"));
131         case EZFS_INVALIDNAME:
132                 return (dgettext(TEXT_DOMAIN, "invalid name"));
133         case EZFS_BADRESTORE:
134                 return (dgettext(TEXT_DOMAIN, "unable to restore to "
135                     "destination"));
136         case EZFS_BADBACKUP:
137                 return (dgettext(TEXT_DOMAIN, "backup failed"));
138         case EZFS_BADTARGET:
139                 return (dgettext(TEXT_DOMAIN, "invalid target vdev"));
140         case EZFS_NODEVICE:
141                 return (dgettext(TEXT_DOMAIN, "no such device in pool"));
142         case EZFS_BADDEV:
143                 return (dgettext(TEXT_DOMAIN, "invalid device"));
144         case EZFS_NOREPLICAS:
145                 return (dgettext(TEXT_DOMAIN, "no valid replicas"));
146         case EZFS_RESILVERING:
147                 return (dgettext(TEXT_DOMAIN, "currently resilvering"));
148         case EZFS_BADVERSION:
149                 return (dgettext(TEXT_DOMAIN, "unsupported version or "
150                     "feature"));
151         case EZFS_POOLUNAVAIL:
152                 return (dgettext(TEXT_DOMAIN, "pool is unavailable"));
153         case EZFS_DEVOVERFLOW:
154                 return (dgettext(TEXT_DOMAIN, "too many devices in one vdev"));
155         case EZFS_BADPATH:
156                 return (dgettext(TEXT_DOMAIN, "must be an absolute path"));
157         case EZFS_CROSSTARGET:
158                 return (dgettext(TEXT_DOMAIN, "operation crosses datasets or "
159                     "pools"));
160         case EZFS_ZONED:
161                 return (dgettext(TEXT_DOMAIN, "dataset in use by local zone"));
162         case EZFS_MOUNTFAILED:
163                 return (dgettext(TEXT_DOMAIN, "mount failed"));
164         case EZFS_UMOUNTFAILED:
165                 return (dgettext(TEXT_DOMAIN, "umount failed"));
166         case EZFS_UNSHARENFSFAILED:
167                 return (dgettext(TEXT_DOMAIN, "unshare(1M) failed"));
168         case EZFS_SHARENFSFAILED:
169                 return (dgettext(TEXT_DOMAIN, "share(1M) failed"));
170         case EZFS_UNSHARESMBFAILED:
171                 return (dgettext(TEXT_DOMAIN, "smb remove share failed"));
172         case EZFS_SHARESMBFAILED:
173                 return (dgettext(TEXT_DOMAIN, "smb add share failed"));
174         case EZFS_PERM:
175                 return (dgettext(TEXT_DOMAIN, "permission denied"));
176         case EZFS_NOSPC:
177                 return (dgettext(TEXT_DOMAIN, "out of space"));
178         case EZFS_FAULT:
179                 return (dgettext(TEXT_DOMAIN, "bad address"));
180         case EZFS_IO:
181                 return (dgettext(TEXT_DOMAIN, "I/O error"));
182         case EZFS_INTR:
183                 return (dgettext(TEXT_DOMAIN, "signal received"));
184         case EZFS_ISSPARE:
185                 return (dgettext(TEXT_DOMAIN, "device is reserved as a hot "
186                     "spare"));
187         case EZFS_INVALCONFIG:
188                 return (dgettext(TEXT_DOMAIN, "invalid vdev configuration"));
189         case EZFS_RECURSIVE:
190                 return (dgettext(TEXT_DOMAIN, "recursive dataset dependency"));
191         case EZFS_NOHISTORY:
192                 return (dgettext(TEXT_DOMAIN, "no history available"));
193         case EZFS_POOLPROPS:
194                 return (dgettext(TEXT_DOMAIN, "failed to retrieve "
195                     "pool properties"));
196         case EZFS_POOL_NOTSUP:
197                 return (dgettext(TEXT_DOMAIN, "operation not supported "
198                     "on this type of pool"));
199         case EZFS_POOL_INVALARG:
200                 return (dgettext(TEXT_DOMAIN, "invalid argument for "
201                     "this pool operation"));
202         case EZFS_NAMETOOLONG:
203                 return (dgettext(TEXT_DOMAIN, "dataset name is too long"));
204         case EZFS_OPENFAILED:
205                 return (dgettext(TEXT_DOMAIN, "open failed"));
206         case EZFS_NOCAP:
207                 return (dgettext(TEXT_DOMAIN,
208                     "disk capacity information could not be retrieved"));
209         case EZFS_LABELFAILED:
210                 return (dgettext(TEXT_DOMAIN, "write of label failed"));
211         case EZFS_BADWHO:
212                 return (dgettext(TEXT_DOMAIN, "invalid user/group"));
213         case EZFS_BADPERM:
214                 return (dgettext(TEXT_DOMAIN, "invalid permission"));
215         case EZFS_BADPERMSET:
216                 return (dgettext(TEXT_DOMAIN, "invalid permission set name"));
217         case EZFS_NODELEGATION:
218                 return (dgettext(TEXT_DOMAIN, "delegated administration is "
219                     "disabled on pool"));
220         case EZFS_BADCACHE:
221                 return (dgettext(TEXT_DOMAIN, "invalid or missing cache file"));
222         case EZFS_ISL2CACHE:
223                 return (dgettext(TEXT_DOMAIN, "device is in use as a cache"));
224         case EZFS_VDEVNOTSUP:
225                 return (dgettext(TEXT_DOMAIN, "vdev specification is not "
226                     "supported"));
227         case EZFS_NOTSUP:
228                 return (dgettext(TEXT_DOMAIN, "operation not supported "
229                     "on this dataset"));
230         case EZFS_IOC_NOTSUPPORTED:
231                 return (dgettext(TEXT_DOMAIN, "operation not supported by "
232                     "zfs kernel module"));
233         case EZFS_ACTIVE_SPARE:
234                 return (dgettext(TEXT_DOMAIN, "pool has active shared spare "
235                     "device"));
236         case EZFS_UNPLAYED_LOGS:
237                 return (dgettext(TEXT_DOMAIN, "log device has unplayed intent "
238                     "logs"));
239         case EZFS_REFTAG_RELE:
240                 return (dgettext(TEXT_DOMAIN, "no such tag on this dataset"));
241         case EZFS_REFTAG_HOLD:
242                 return (dgettext(TEXT_DOMAIN, "tag already exists on this "
243                     "dataset"));
244         case EZFS_TAGTOOLONG:
245                 return (dgettext(TEXT_DOMAIN, "tag too long"));
246         case EZFS_PIPEFAILED:
247                 return (dgettext(TEXT_DOMAIN, "pipe create failed"));
248         case EZFS_THREADCREATEFAILED:
249                 return (dgettext(TEXT_DOMAIN, "thread create failed"));
250         case EZFS_POSTSPLIT_ONLINE:
251                 return (dgettext(TEXT_DOMAIN, "disk was split from this pool "
252                     "into a new one"));
253         case EZFS_SCRUB_PAUSED:
254                 return (dgettext(TEXT_DOMAIN, "scrub is paused; "
255                     "use 'zpool scrub' to resume"));
256         case EZFS_SCRUBBING:
257                 return (dgettext(TEXT_DOMAIN, "currently scrubbing; "
258                     "use 'zpool scrub -s' to cancel current scrub"));
259         case EZFS_NO_SCRUB:
260                 return (dgettext(TEXT_DOMAIN, "there is no active scrub"));
261         case EZFS_DIFF:
262                 return (dgettext(TEXT_DOMAIN, "unable to generate diffs"));
263         case EZFS_DIFFDATA:
264                 return (dgettext(TEXT_DOMAIN, "invalid diff data"));
265         case EZFS_POOLREADONLY:
266                 return (dgettext(TEXT_DOMAIN, "pool is read-only"));
267         case EZFS_NO_PENDING:
268                 return (dgettext(TEXT_DOMAIN, "operation is not "
269                     "in progress"));
270         case EZFS_CHECKPOINT_EXISTS:
271                 return (dgettext(TEXT_DOMAIN, "checkpoint exists"));
272         case EZFS_DISCARDING_CHECKPOINT:
273                 return (dgettext(TEXT_DOMAIN, "currently discarding "
274                     "checkpoint"));
275         case EZFS_NO_CHECKPOINT:
276                 return (dgettext(TEXT_DOMAIN, "checkpoint does not exist"));
277         case EZFS_DEVRM_IN_PROGRESS:
278                 return (dgettext(TEXT_DOMAIN, "device removal in progress"));
279         case EZFS_VDEV_TOO_BIG:
280                 return (dgettext(TEXT_DOMAIN, "device exceeds supported size"));
281         case EZFS_ACTIVE_POOL:
282                 return (dgettext(TEXT_DOMAIN, "pool is imported on a "
283                     "different host"));
284         case EZFS_CRYPTOFAILED:
285                 return (dgettext(TEXT_DOMAIN, "encryption failure"));
286         case EZFS_UNKNOWN:
287                 return (dgettext(TEXT_DOMAIN, "unknown error"));
288         default:
289                 assert(hdl->libzfs_error == 0);
290                 return (dgettext(TEXT_DOMAIN, "no error"));
291         }
292 }
293
294 /*PRINTFLIKE2*/
295 void
296 zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
297 {
298         va_list ap;
299
300         va_start(ap, fmt);
301
302         (void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
303             fmt, ap);
304         hdl->libzfs_desc_active = 1;
305
306         va_end(ap);
307 }
308
309 static void
310 zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
311 {
312         (void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
313             fmt, ap);
314         hdl->libzfs_error = error;
315
316         if (hdl->libzfs_desc_active)
317                 hdl->libzfs_desc_active = 0;
318         else
319                 hdl->libzfs_desc[0] = '\0';
320
321         if (hdl->libzfs_printerr) {
322                 if (error == EZFS_UNKNOWN) {
323                         (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
324                             "error: %s\n"), libzfs_error_description(hdl));
325                         abort();
326                 }
327
328                 (void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
329                     libzfs_error_description(hdl));
330                 if (error == EZFS_NOMEM)
331                         exit(1);
332         }
333 }
334
335 int
336 zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
337 {
338         return (zfs_error_fmt(hdl, error, "%s", msg));
339 }
340
341 /*PRINTFLIKE3*/
342 int
343 zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
344 {
345         va_list ap;
346
347         va_start(ap, fmt);
348
349         zfs_verror(hdl, error, fmt, ap);
350
351         va_end(ap);
352
353         return (-1);
354 }
355
356 static int
357 zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
358     va_list ap)
359 {
360         switch (error) {
361         case EPERM:
362         case EACCES:
363                 zfs_verror(hdl, EZFS_PERM, fmt, ap);
364                 return (-1);
365
366         case ECANCELED:
367                 zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
368                 return (-1);
369
370         case EIO:
371                 zfs_verror(hdl, EZFS_IO, fmt, ap);
372                 return (-1);
373
374         case EFAULT:
375                 zfs_verror(hdl, EZFS_FAULT, fmt, ap);
376                 return (-1);
377
378         case EINTR:
379                 zfs_verror(hdl, EZFS_INTR, fmt, ap);
380                 return (-1);
381         }
382
383         return (0);
384 }
385
386 int
387 zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
388 {
389         return (zfs_standard_error_fmt(hdl, error, "%s", msg));
390 }
391
392 /*PRINTFLIKE3*/
393 int
394 zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
395 {
396         va_list ap;
397
398         va_start(ap, fmt);
399
400         if (zfs_common_error(hdl, error, fmt, ap) != 0) {
401                 va_end(ap);
402                 return (-1);
403         }
404
405         switch (error) {
406         case ENXIO:
407         case ENODEV:
408         case EPIPE:
409                 zfs_verror(hdl, EZFS_IO, fmt, ap);
410                 break;
411
412         case ENOENT:
413                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
414                     "dataset does not exist"));
415                 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
416                 break;
417
418         case ENOSPC:
419         case EDQUOT:
420                 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
421                 break;
422
423         case EEXIST:
424                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
425                     "dataset already exists"));
426                 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
427                 break;
428
429         case EBUSY:
430                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
431                     "dataset is busy"));
432                 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
433                 break;
434         case EROFS:
435                 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
436                 break;
437         case ENAMETOOLONG:
438                 zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
439                 break;
440         case ENOTSUP:
441                 zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
442                 break;
443         case EAGAIN:
444                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
445                     "pool I/O is currently suspended"));
446                 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
447                 break;
448         case EREMOTEIO:
449                 zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
450                 break;
451         case ZFS_ERR_IOC_CMD_UNAVAIL:
452                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
453                     "module does not support this operation. A reboot may "
454                     "be required to enable this operation."));
455                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
456                 break;
457         case ZFS_ERR_IOC_ARG_UNAVAIL:
458                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
459                     "module does not support an option for this operation. "
460                     "A reboot may be required to enable this option."));
461                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
462                 break;
463         case ZFS_ERR_IOC_ARG_REQUIRED:
464         case ZFS_ERR_IOC_ARG_BADTYPE:
465                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
466                 break;
467         default:
468                 zfs_error_aux(hdl, strerror(error));
469                 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
470                 break;
471         }
472
473         va_end(ap);
474         return (-1);
475 }
476
477 int
478 zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
479 {
480         return (zpool_standard_error_fmt(hdl, error, "%s", msg));
481 }
482
483 /*PRINTFLIKE3*/
484 int
485 zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
486 {
487         va_list ap;
488
489         va_start(ap, fmt);
490
491         if (zfs_common_error(hdl, error, fmt, ap) != 0) {
492                 va_end(ap);
493                 return (-1);
494         }
495
496         switch (error) {
497         case ENODEV:
498                 zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
499                 break;
500
501         case ENOENT:
502                 zfs_error_aux(hdl,
503                     dgettext(TEXT_DOMAIN, "no such pool or dataset"));
504                 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
505                 break;
506
507         case EEXIST:
508                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
509                     "pool already exists"));
510                 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
511                 break;
512
513         case EBUSY:
514                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
515                 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
516                 break;
517
518         /* There is no pending operation to cancel */
519         case ENOTACTIVE:
520                 zfs_verror(hdl, EZFS_NO_PENDING, fmt, ap);
521                 break;
522
523         case ENXIO:
524                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
525                     "one or more devices is currently unavailable"));
526                 zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
527                 break;
528
529         case ENAMETOOLONG:
530                 zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
531                 break;
532
533         case ENOTSUP:
534                 zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
535                 break;
536
537         case EINVAL:
538                 zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
539                 break;
540
541         case ENOSPC:
542         case EDQUOT:
543                 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
544                 return (-1);
545
546         case EAGAIN:
547                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
548                     "pool I/O is currently suspended"));
549                 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
550                 break;
551
552         case EROFS:
553                 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
554                 break;
555         case EDOM:
556                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
557                     "block size out of range or does not match"));
558                 zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
559                 break;
560         case EREMOTEIO:
561                 zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
562                 break;
563         case ZFS_ERR_CHECKPOINT_EXISTS:
564                 zfs_verror(hdl, EZFS_CHECKPOINT_EXISTS, fmt, ap);
565                 break;
566         case ZFS_ERR_DISCARDING_CHECKPOINT:
567                 zfs_verror(hdl, EZFS_DISCARDING_CHECKPOINT, fmt, ap);
568                 break;
569         case ZFS_ERR_NO_CHECKPOINT:
570                 zfs_verror(hdl, EZFS_NO_CHECKPOINT, fmt, ap);
571                 break;
572         case ZFS_ERR_DEVRM_IN_PROGRESS:
573                 zfs_verror(hdl, EZFS_DEVRM_IN_PROGRESS, fmt, ap);
574                 break;
575         case ZFS_ERR_VDEV_TOO_BIG:
576                 zfs_verror(hdl, EZFS_VDEV_TOO_BIG, fmt, ap);
577                 break;
578         case ZFS_ERR_IOC_CMD_UNAVAIL:
579                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
580                     "module does not support this operation. A reboot may "
581                     "be required to enable this operation."));
582                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
583                 break;
584         case ZFS_ERR_IOC_ARG_UNAVAIL:
585                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
586                     "module does not support an option for this operation. "
587                     "A reboot may be required to enable this option."));
588                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
589                 break;
590         case ZFS_ERR_IOC_ARG_REQUIRED:
591         case ZFS_ERR_IOC_ARG_BADTYPE:
592                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
593                 break;
594         default:
595                 zfs_error_aux(hdl, strerror(error));
596                 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
597         }
598
599         va_end(ap);
600         return (-1);
601 }
602
603 /*
604  * Display an out of memory error message and abort the current program.
605  */
606 int
607 no_memory(libzfs_handle_t *hdl)
608 {
609         return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
610 }
611
612 /*
613  * A safe form of malloc() which will die if the allocation fails.
614  */
615 void *
616 zfs_alloc(libzfs_handle_t *hdl, size_t size)
617 {
618         void *data;
619
620         if ((data = calloc(1, size)) == NULL)
621                 (void) no_memory(hdl);
622
623         return (data);
624 }
625
626 /*
627  * A safe form of asprintf() which will die if the allocation fails.
628  */
629 /*PRINTFLIKE2*/
630 char *
631 zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
632 {
633         va_list ap;
634         char *ret;
635         int err;
636
637         va_start(ap, fmt);
638
639         err = vasprintf(&ret, fmt, ap);
640
641         va_end(ap);
642
643         if (err < 0)
644                 (void) no_memory(hdl);
645
646         return (ret);
647 }
648
649 /*
650  * A safe form of realloc(), which also zeroes newly allocated space.
651  */
652 void *
653 zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
654 {
655         void *ret;
656
657         if ((ret = realloc(ptr, newsize)) == NULL) {
658                 (void) no_memory(hdl);
659                 return (NULL);
660         }
661
662         bzero((char *)ret + oldsize, (newsize - oldsize));
663         return (ret);
664 }
665
666 /*
667  * A safe form of strdup() which will die if the allocation fails.
668  */
669 char *
670 zfs_strdup(libzfs_handle_t *hdl, const char *str)
671 {
672         char *ret;
673
674         if ((ret = strdup(str)) == NULL)
675                 (void) no_memory(hdl);
676
677         return (ret);
678 }
679
680 /*
681  * Convert a number to an appropriately human-readable output.
682  */
683 void
684 zfs_nicenum_format(uint64_t num, char *buf, size_t buflen,
685     enum zfs_nicenum_format format)
686 {
687         uint64_t n = num;
688         int index = 0;
689         const char *u;
690         const char *units[3][7] = {
691             [ZFS_NICENUM_1024] = {"", "K", "M", "G", "T", "P", "E"},
692             [ZFS_NICENUM_BYTES] = {"B", "K", "M", "G", "T", "P", "E"},
693             [ZFS_NICENUM_TIME] = {"ns", "us", "ms", "s", "?", "?", "?"}
694         };
695
696         const int units_len[] = {[ZFS_NICENUM_1024] = 6,
697             [ZFS_NICENUM_BYTES] = 6,
698             [ZFS_NICENUM_TIME] = 4};
699
700         const int k_unit[] = {  [ZFS_NICENUM_1024] = 1024,
701             [ZFS_NICENUM_BYTES] = 1024,
702             [ZFS_NICENUM_TIME] = 1000};
703
704         double val;
705
706         if (format == ZFS_NICENUM_RAW) {
707                 snprintf(buf, buflen, "%llu", (u_longlong_t)num);
708                 return;
709         } else if (format == ZFS_NICENUM_RAWTIME && num > 0) {
710                 snprintf(buf, buflen, "%llu", (u_longlong_t)num);
711                 return;
712         } else if (format == ZFS_NICENUM_RAWTIME && num == 0) {
713                 snprintf(buf, buflen, "%s", "-");
714                 return;
715         }
716
717         while (n >= k_unit[format] && index < units_len[format]) {
718                 n /= k_unit[format];
719                 index++;
720         }
721
722         u = units[format][index];
723
724         /* Don't print zero latencies since they're invalid */
725         if ((format == ZFS_NICENUM_TIME) && (num == 0)) {
726                 (void) snprintf(buf, buflen, "-");
727         } else if ((index == 0) || ((num %
728             (uint64_t)powl(k_unit[format], index)) == 0)) {
729                 /*
730                  * If this is an even multiple of the base, always display
731                  * without any decimal precision.
732                  */
733                 (void) snprintf(buf, buflen, "%llu%s", (u_longlong_t)n, u);
734
735         } else {
736                 /*
737                  * We want to choose a precision that reflects the best choice
738                  * for fitting in 5 characters.  This can get rather tricky when
739                  * we have numbers that are very close to an order of magnitude.
740                  * For example, when displaying 10239 (which is really 9.999K),
741                  * we want only a single place of precision for 10.0K.  We could
742                  * develop some complex heuristics for this, but it's much
743                  * easier just to try each combination in turn.
744                  */
745                 int i;
746                 for (i = 2; i >= 0; i--) {
747                         val = (double)num /
748                             (uint64_t)powl(k_unit[format], index);
749
750                         /*
751                          * Don't print floating point values for time.  Note,
752                          * we use floor() instead of round() here, since
753                          * round can result in undesirable results.  For
754                          * example, if "num" is in the range of
755                          * 999500-999999, it will print out "1000us".  This
756                          * doesn't happen if we use floor().
757                          */
758                         if (format == ZFS_NICENUM_TIME) {
759                                 if (snprintf(buf, buflen, "%d%s",
760                                     (unsigned int) floor(val), u) <= 5)
761                                         break;
762
763                         } else {
764                                 if (snprintf(buf, buflen, "%.*f%s", i,
765                                     val, u) <= 5)
766                                         break;
767                         }
768                 }
769         }
770 }
771
772 /*
773  * Convert a number to an appropriately human-readable output.
774  */
775 void
776 zfs_nicenum(uint64_t num, char *buf, size_t buflen)
777 {
778         zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_1024);
779 }
780
781 /*
782  * Convert a time to an appropriately human-readable output.
783  * @num:        Time in nanoseconds
784  */
785 void
786 zfs_nicetime(uint64_t num, char *buf, size_t buflen)
787 {
788         zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_TIME);
789 }
790
791 /*
792  * Print out a raw number with correct column spacing
793  */
794 void
795 zfs_niceraw(uint64_t num, char *buf, size_t buflen)
796 {
797         zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_RAW);
798 }
799
800 /*
801  * Convert a number of bytes to an appropriately human-readable output.
802  */
803 void
804 zfs_nicebytes(uint64_t num, char *buf, size_t buflen)
805 {
806         zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_BYTES);
807 }
808
809 void
810 libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
811 {
812         hdl->libzfs_printerr = printerr;
813 }
814
815 static int
816 libzfs_module_loaded(const char *module)
817 {
818         const char path_prefix[] = "/sys/module/";
819         char path[256];
820
821         memcpy(path, path_prefix, sizeof (path_prefix) - 1);
822         strcpy(path + sizeof (path_prefix) - 1, module);
823
824         return (access(path, F_OK) == 0);
825 }
826
827
828 /*
829  * Read lines from an open file descriptor and store them in an array of
830  * strings until EOF.  lines[] will be allocated and populated with all the
831  * lines read.  All newlines are replaced with NULL terminators for
832  * convenience.  lines[] must be freed after use with libzfs_free_str_array().
833  *
834  * Returns the number of lines read.
835  */
836 static int
837 libzfs_read_stdout_from_fd(int fd, char **lines[])
838 {
839
840         FILE *fp;
841         int lines_cnt = 0;
842         size_t len = 0;
843         char *line = NULL;
844         char **tmp_lines = NULL, **tmp;
845         char *nl = NULL;
846         int rc;
847
848         fp = fdopen(fd, "r");
849         if (fp == NULL)
850                 return (0);
851         while (1) {
852                 rc = getline(&line, &len, fp);
853                 if (rc == -1)
854                         break;
855
856                 tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
857                 if (tmp == NULL) {
858                         /* Return the lines we were able to process */
859                         break;
860                 }
861                 tmp_lines = tmp;
862
863                 /* Terminate newlines */
864                 if ((nl = strchr(line, '\n')) != NULL)
865                         *nl = '\0';
866                 tmp_lines[lines_cnt] = line;
867                 lines_cnt++;
868                 line = NULL;
869         }
870         fclose(fp);
871         *lines = tmp_lines;
872         return (lines_cnt);
873 }
874
875 static int
876 libzfs_run_process_impl(const char *path, char *argv[], char *env[], int flags,
877     char **lines[], int *lines_cnt)
878 {
879         pid_t pid;
880         int error, devnull_fd;
881         int link[2];
882
883         /*
884          * Setup a pipe between our child and parent process if we're
885          * reading stdout.
886          */
887         if ((lines != NULL) && pipe(link) == -1)
888                 return (-ESTRPIPE);
889
890         pid = vfork();
891         if (pid == 0) {
892                 /* Child process */
893                 devnull_fd = open("/dev/null", O_WRONLY);
894
895                 if (devnull_fd < 0)
896                         _exit(-1);
897
898                 if (!(flags & STDOUT_VERBOSE) && (lines == NULL))
899                         (void) dup2(devnull_fd, STDOUT_FILENO);
900                 else if (lines != NULL) {
901                         /* Save the output to lines[] */
902                         dup2(link[1], STDOUT_FILENO);
903                         close(link[0]);
904                         close(link[1]);
905                 }
906
907                 if (!(flags & STDERR_VERBOSE))
908                         (void) dup2(devnull_fd, STDERR_FILENO);
909
910                 close(devnull_fd);
911
912                 if (flags & NO_DEFAULT_PATH) {
913                         if (env == NULL)
914                                 execv(path, argv);
915                         else
916                                 execve(path, argv, env);
917                 } else {
918                         if (env == NULL)
919                                 execvp(path, argv);
920                         else
921                                 execvpe(path, argv, env);
922                 }
923
924                 _exit(-1);
925         } else if (pid > 0) {
926                 /* Parent process */
927                 int status;
928
929                 while ((error = waitpid(pid, &status, 0)) == -1 &&
930                     errno == EINTR) { }
931                 if (error < 0 || !WIFEXITED(status))
932                         return (-1);
933
934                 if (lines != NULL) {
935                         close(link[1]);
936                         *lines_cnt = libzfs_read_stdout_from_fd(link[0], lines);
937                 }
938                 return (WEXITSTATUS(status));
939         }
940
941         return (-1);
942 }
943
944 int
945 libzfs_run_process(const char *path, char *argv[], int flags)
946 {
947         return (libzfs_run_process_impl(path, argv, NULL, flags, NULL, NULL));
948 }
949
950 /*
951  * Run a command and store its stdout lines in an array of strings (lines[]).
952  * lines[] is allocated and populated for you, and the number of lines is set in
953  * lines_cnt.  lines[] must be freed after use with libzfs_free_str_array().
954  * All newlines (\n) in lines[] are terminated for convenience.
955  */
956 int
957 libzfs_run_process_get_stdout(const char *path, char *argv[], char *env[],
958     char **lines[], int *lines_cnt)
959 {
960         return (libzfs_run_process_impl(path, argv, env, 0, lines, lines_cnt));
961 }
962
963 /*
964  * Same as libzfs_run_process_get_stdout(), but run without $PATH set.  This
965  * means that *path needs to be the full path to the executable.
966  */
967 int
968 libzfs_run_process_get_stdout_nopath(const char *path, char *argv[],
969     char *env[], char **lines[], int *lines_cnt)
970 {
971         return (libzfs_run_process_impl(path, argv, env, NO_DEFAULT_PATH,
972             lines, lines_cnt));
973 }
974
975 /*
976  * Free an array of strings.  Free both the strings contained in the array and
977  * the array itself.
978  */
979 void
980 libzfs_free_str_array(char **strs, int count)
981 {
982         while (--count >= 0)
983                 free(strs[count]);
984
985         free(strs);
986 }
987
988 /*
989  * Returns 1 if environment variable is set to "YES", "yes", "ON", "on", or
990  * a non-zero number.
991  *
992  * Returns 0 otherwise.
993  */
994 int
995 libzfs_envvar_is_set(char *envvar)
996 {
997         char *env = getenv(envvar);
998         if (env && (strtoul(env, NULL, 0) > 0 ||
999             (!strncasecmp(env, "YES", 3) && strnlen(env, 4) == 3) ||
1000             (!strncasecmp(env, "ON", 2) && strnlen(env, 3) == 2)))
1001                 return (1);
1002
1003         return (0);
1004 }
1005
1006 /*
1007  * Verify the required ZFS_DEV device is available and optionally attempt
1008  * to load the ZFS modules.  Under normal circumstances the modules
1009  * should already have been loaded by some external mechanism.
1010  *
1011  * Environment variables:
1012  * - ZFS_MODULE_LOADING="YES|yes|ON|on" - Attempt to load modules.
1013  * - ZFS_MODULE_TIMEOUT="<seconds>"     - Seconds to wait for ZFS_DEV
1014  */
1015 static int
1016 libzfs_load_module(const char *module)
1017 {
1018         char *argv[4] = {"/sbin/modprobe", "-q", (char *)module, (char *)0};
1019         char *load_str, *timeout_str;
1020         long timeout = 10; /* seconds */
1021         long busy_timeout = 10; /* milliseconds */
1022         int load = 0, fd;
1023         hrtime_t start;
1024
1025         /* Optionally request module loading */
1026         if (!libzfs_module_loaded(module)) {
1027                 load_str = getenv("ZFS_MODULE_LOADING");
1028                 if (load_str) {
1029                         if (!strncasecmp(load_str, "YES", strlen("YES")) ||
1030                             !strncasecmp(load_str, "ON", strlen("ON")))
1031                                 load = 1;
1032                         else
1033                                 load = 0;
1034                 }
1035
1036                 if (load) {
1037                         if (libzfs_run_process("/sbin/modprobe", argv, 0))
1038                                 return (ENOEXEC);
1039
1040                         if (!libzfs_module_loaded(module))
1041                                 return (ENXIO);
1042                 }
1043         }
1044
1045         /*
1046          * Device creation by udev is asynchronous and waiting may be
1047          * required.  Busy wait for 10ms and then fall back to polling every
1048          * 10ms for the allowed timeout (default 10s, max 10m).  This is
1049          * done to optimize for the common case where the device is
1050          * immediately available and to avoid penalizing the possible
1051          * case where udev is slow or unable to create the device.
1052          */
1053         timeout_str = getenv("ZFS_MODULE_TIMEOUT");
1054         if (timeout_str) {
1055                 timeout = strtol(timeout_str, NULL, 0);
1056                 timeout = MAX(MIN(timeout, (10 * 60)), 0); /* 0 <= N <= 600 */
1057         }
1058
1059         start = gethrtime();
1060         do {
1061                 fd = open(ZFS_DEV, O_RDWR);
1062                 if (fd >= 0) {
1063                         (void) close(fd);
1064                         return (0);
1065                 } else if (errno != ENOENT) {
1066                         return (errno);
1067                 } else if (NSEC2MSEC(gethrtime() - start) < busy_timeout) {
1068                         sched_yield();
1069                 } else {
1070                         usleep(10 * MILLISEC);
1071                 }
1072         } while (NSEC2MSEC(gethrtime() - start) < (timeout * MILLISEC));
1073
1074         return (ENOENT);
1075 }
1076
1077 libzfs_handle_t *
1078 libzfs_init(void)
1079 {
1080         libzfs_handle_t *hdl;
1081         int error;
1082
1083         error = libzfs_load_module(ZFS_DRIVER);
1084         if (error) {
1085                 errno = error;
1086                 return (NULL);
1087         }
1088
1089         if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
1090                 return (NULL);
1091         }
1092
1093         if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR)) < 0) {
1094                 free(hdl);
1095                 return (NULL);
1096         }
1097
1098 #ifdef HAVE_SETMNTENT
1099         if ((hdl->libzfs_mnttab = setmntent(MNTTAB, "r")) == NULL) {
1100 #else
1101         if ((hdl->libzfs_mnttab = fopen(MNTTAB, "r")) == NULL) {
1102 #endif
1103                 (void) close(hdl->libzfs_fd);
1104                 free(hdl);
1105                 return (NULL);
1106         }
1107
1108         hdl->libzfs_sharetab = fopen(ZFS_SHARETAB, "r");
1109
1110         if (libzfs_core_init() != 0) {
1111                 (void) close(hdl->libzfs_fd);
1112                 (void) fclose(hdl->libzfs_mnttab);
1113                 if (hdl->libzfs_sharetab)
1114                         (void) fclose(hdl->libzfs_sharetab);
1115                 free(hdl);
1116                 return (NULL);
1117         }
1118
1119         zfs_prop_init();
1120         zpool_prop_init();
1121         zpool_feature_init();
1122         libzfs_mnttab_init(hdl);
1123         fletcher_4_init();
1124
1125         if (getenv("ZFS_PROP_DEBUG") != NULL) {
1126                 hdl->libzfs_prop_debug = B_TRUE;
1127         }
1128
1129         /*
1130          * For testing, remove some settable properties and features
1131          */
1132         if (libzfs_envvar_is_set("ZFS_SYSFS_PROP_SUPPORT_TEST")) {
1133                 zprop_desc_t *proptbl;
1134
1135                 proptbl = zpool_prop_get_table();
1136                 proptbl[ZPOOL_PROP_COMMENT].pd_zfs_mod_supported = B_FALSE;
1137
1138                 proptbl = zfs_prop_get_table();
1139                 proptbl[ZFS_PROP_DNODESIZE].pd_zfs_mod_supported = B_FALSE;
1140
1141                 zfeature_info_t *ftbl = spa_feature_table;
1142                 ftbl[SPA_FEATURE_LARGE_BLOCKS].fi_zfs_mod_supported = B_FALSE;
1143         }
1144
1145         return (hdl);
1146 }
1147
1148 void
1149 libzfs_fini(libzfs_handle_t *hdl)
1150 {
1151         (void) close(hdl->libzfs_fd);
1152         if (hdl->libzfs_mnttab)
1153 #ifdef HAVE_SETMNTENT
1154                 (void) endmntent(hdl->libzfs_mnttab);
1155 #else
1156                 (void) fclose(hdl->libzfs_mnttab);
1157 #endif
1158         if (hdl->libzfs_sharetab)
1159                 (void) fclose(hdl->libzfs_sharetab);
1160         zfs_uninit_libshare(hdl);
1161         zpool_free_handles(hdl);
1162         namespace_clear(hdl);
1163         libzfs_mnttab_fini(hdl);
1164         libzfs_core_fini();
1165         fletcher_4_fini();
1166         free(hdl);
1167 }
1168
1169 libzfs_handle_t *
1170 zpool_get_handle(zpool_handle_t *zhp)
1171 {
1172         return (zhp->zpool_hdl);
1173 }
1174
1175 libzfs_handle_t *
1176 zfs_get_handle(zfs_handle_t *zhp)
1177 {
1178         return (zhp->zfs_hdl);
1179 }
1180
1181 zpool_handle_t *
1182 zfs_get_pool_handle(const zfs_handle_t *zhp)
1183 {
1184         return (zhp->zpool_hdl);
1185 }
1186
1187 /*
1188  * Given a name, determine whether or not it's a valid path
1189  * (starts with '/' or "./").  If so, walk the mnttab trying
1190  * to match the device number.  If not, treat the path as an
1191  * fs/vol/snap/bkmark name.
1192  */
1193 zfs_handle_t *
1194 zfs_path_to_zhandle(libzfs_handle_t *hdl, char *path, zfs_type_t argtype)
1195 {
1196         struct stat64 statbuf;
1197         struct extmnttab entry;
1198         int ret;
1199
1200         if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1201                 /*
1202                  * It's not a valid path, assume it's a name of type 'argtype'.
1203                  */
1204                 return (zfs_open(hdl, path, argtype));
1205         }
1206
1207         if (stat64(path, &statbuf) != 0) {
1208                 (void) fprintf(stderr, "%s: %s\n", path, strerror(errno));
1209                 return (NULL);
1210         }
1211
1212         /* Reopen MNTTAB to prevent reading stale data from open file */
1213         if (freopen(MNTTAB, "r", hdl->libzfs_mnttab) == NULL)
1214                 return (NULL);
1215
1216         while ((ret = getextmntent(hdl->libzfs_mnttab, &entry, 0)) == 0) {
1217                 if (makedevice(entry.mnt_major, entry.mnt_minor) ==
1218                     statbuf.st_dev) {
1219                         break;
1220                 }
1221         }
1222         if (ret != 0) {
1223                 return (NULL);
1224         }
1225
1226         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1227                 (void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1228                     path);
1229                 return (NULL);
1230         }
1231
1232         return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1233 }
1234
1235 /*
1236  * Append partition suffix to an otherwise fully qualified device path.
1237  * This is used to generate the name the full path as its stored in
1238  * ZPOOL_CONFIG_PATH for whole disk devices.  On success the new length
1239  * of 'path' will be returned on error a negative value is returned.
1240  */
1241 int
1242 zfs_append_partition(char *path, size_t max_len)
1243 {
1244         int len = strlen(path);
1245
1246         if ((strncmp(path, UDISK_ROOT, strlen(UDISK_ROOT)) == 0) ||
1247             (strncmp(path, ZVOL_ROOT, strlen(ZVOL_ROOT)) == 0)) {
1248                 if (len + 6 >= max_len)
1249                         return (-1);
1250
1251                 (void) strcat(path, "-part1");
1252                 len += 6;
1253         } else {
1254                 if (len + 2 >= max_len)
1255                         return (-1);
1256
1257                 if (isdigit(path[len-1])) {
1258                         (void) strcat(path, "p1");
1259                         len += 2;
1260                 } else {
1261                         (void) strcat(path, "1");
1262                         len += 1;
1263                 }
1264         }
1265
1266         return (len);
1267 }
1268
1269 /*
1270  * Given a shorthand device name check if a file by that name exists in any
1271  * of the 'zpool_default_import_path' or ZPOOL_IMPORT_PATH directories.  If
1272  * one is found, store its fully qualified path in the 'path' buffer passed
1273  * by the caller and return 0, otherwise return an error.
1274  */
1275 int
1276 zfs_resolve_shortname(const char *name, char *path, size_t len)
1277 {
1278         int i, error = -1;
1279         char *dir, *env, *envdup;
1280
1281         env = getenv("ZPOOL_IMPORT_PATH");
1282         errno = ENOENT;
1283
1284         if (env) {
1285                 envdup = strdup(env);
1286                 dir = strtok(envdup, ":");
1287                 while (dir && error) {
1288                         (void) snprintf(path, len, "%s/%s", dir, name);
1289                         error = access(path, F_OK);
1290                         dir = strtok(NULL, ":");
1291                 }
1292                 free(envdup);
1293         } else {
1294                 for (i = 0; i < DEFAULT_IMPORT_PATH_SIZE && error < 0; i++) {
1295                         (void) snprintf(path, len, "%s/%s",
1296                             zpool_default_import_path[i], name);
1297                         error = access(path, F_OK);
1298                 }
1299         }
1300
1301         return (error ? ENOENT : 0);
1302 }
1303
1304 /*
1305  * Given a shorthand device name look for a match against 'cmp_name'.  This
1306  * is done by checking all prefix expansions using either the default
1307  * 'zpool_default_import_paths' or the ZPOOL_IMPORT_PATH environment
1308  * variable.  Proper partition suffixes will be appended if this is a
1309  * whole disk.  When a match is found 0 is returned otherwise ENOENT.
1310  */
1311 static int
1312 zfs_strcmp_shortname(char *name, char *cmp_name, int wholedisk)
1313 {
1314         int path_len, cmp_len, i = 0, error = ENOENT;
1315         char *dir, *env, *envdup = NULL;
1316         char path_name[MAXPATHLEN];
1317
1318         cmp_len = strlen(cmp_name);
1319         env = getenv("ZPOOL_IMPORT_PATH");
1320
1321         if (env) {
1322                 envdup = strdup(env);
1323                 dir = strtok(envdup, ":");
1324         } else {
1325                 dir =  zpool_default_import_path[i];
1326         }
1327
1328         while (dir) {
1329                 /* Trim trailing directory slashes from ZPOOL_IMPORT_PATH */
1330                 while (dir[strlen(dir)-1] == '/')
1331                         dir[strlen(dir)-1] = '\0';
1332
1333                 path_len = snprintf(path_name, MAXPATHLEN, "%s/%s", dir, name);
1334                 if (wholedisk)
1335                         path_len = zfs_append_partition(path_name, MAXPATHLEN);
1336
1337                 if ((path_len == cmp_len) && strcmp(path_name, cmp_name) == 0) {
1338                         error = 0;
1339                         break;
1340                 }
1341
1342                 if (env) {
1343                         dir = strtok(NULL, ":");
1344                 } else if (++i < DEFAULT_IMPORT_PATH_SIZE) {
1345                         dir = zpool_default_import_path[i];
1346                 } else {
1347                         dir = NULL;
1348                 }
1349         }
1350
1351         if (env)
1352                 free(envdup);
1353
1354         return (error);
1355 }
1356
1357 /*
1358  * Given either a shorthand or fully qualified path name look for a match
1359  * against 'cmp'.  The passed name will be expanded as needed for comparison
1360  * purposes and redundant slashes stripped to ensure an accurate match.
1361  */
1362 int
1363 zfs_strcmp_pathname(char *name, char *cmp, int wholedisk)
1364 {
1365         int path_len, cmp_len;
1366         char path_name[MAXPATHLEN];
1367         char cmp_name[MAXPATHLEN];
1368         char *dir, *dup;
1369
1370         /* Strip redundant slashes if one exists due to ZPOOL_IMPORT_PATH */
1371         memset(cmp_name, 0, MAXPATHLEN);
1372         dup = strdup(cmp);
1373         dir = strtok(dup, "/");
1374         while (dir) {
1375                 strlcat(cmp_name, "/", sizeof (cmp_name));
1376                 strlcat(cmp_name, dir, sizeof (cmp_name));
1377                 dir = strtok(NULL, "/");
1378         }
1379         free(dup);
1380
1381         if (name[0] != '/')
1382                 return (zfs_strcmp_shortname(name, cmp_name, wholedisk));
1383
1384         (void) strlcpy(path_name, name, MAXPATHLEN);
1385         path_len = strlen(path_name);
1386         cmp_len = strlen(cmp_name);
1387
1388         if (wholedisk) {
1389                 path_len = zfs_append_partition(path_name, MAXPATHLEN);
1390                 if (path_len == -1)
1391                         return (ENOMEM);
1392         }
1393
1394         if ((path_len != cmp_len) || strcmp(path_name, cmp_name))
1395                 return (ENOENT);
1396
1397         return (0);
1398 }
1399
1400 /*
1401  * Given a full path to a device determine if that device appears in the
1402  * import search path.  If it does return the first match and store the
1403  * index in the passed 'order' variable, otherwise return an error.
1404  */
1405 int
1406 zfs_path_order(char *name, int *order)
1407 {
1408         int i = 0, error = ENOENT;
1409         char *dir, *env, *envdup;
1410
1411         env = getenv("ZPOOL_IMPORT_PATH");
1412         if (env) {
1413                 envdup = strdup(env);
1414                 dir = strtok(envdup, ":");
1415                 while (dir) {
1416                         if (strncmp(name, dir, strlen(dir)) == 0) {
1417                                 *order = i;
1418                                 error = 0;
1419                                 break;
1420                         }
1421                         dir = strtok(NULL, ":");
1422                         i++;
1423                 }
1424                 free(envdup);
1425         } else {
1426                 for (i = 0; i < DEFAULT_IMPORT_PATH_SIZE; i++) {
1427                         if (strncmp(name, zpool_default_import_path[i],
1428                             strlen(zpool_default_import_path[i])) == 0) {
1429                                 *order = i;
1430                                 error = 0;
1431                                 break;
1432                         }
1433                 }
1434         }
1435
1436         return (error);
1437 }
1438
1439 /*
1440  * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1441  * an ioctl().
1442  */
1443 int
1444 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1445 {
1446         if (len == 0)
1447                 len = 16 * 1024;
1448         zc->zc_nvlist_dst_size = len;
1449         zc->zc_nvlist_dst =
1450             (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1451         if (zc->zc_nvlist_dst == 0)
1452                 return (-1);
1453
1454         return (0);
1455 }
1456
1457 /*
1458  * Called when an ioctl() which returns an nvlist fails with ENOMEM.  This will
1459  * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1460  * filled in by the kernel to indicate the actual required size.
1461  */
1462 int
1463 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1464 {
1465         free((void *)(uintptr_t)zc->zc_nvlist_dst);
1466         zc->zc_nvlist_dst =
1467             (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1468         if (zc->zc_nvlist_dst == 0)
1469                 return (-1);
1470
1471         return (0);
1472 }
1473
1474 /*
1475  * Called to free the src and dst nvlists stored in the command structure.
1476  */
1477 void
1478 zcmd_free_nvlists(zfs_cmd_t *zc)
1479 {
1480         free((void *)(uintptr_t)zc->zc_nvlist_conf);
1481         free((void *)(uintptr_t)zc->zc_nvlist_src);
1482         free((void *)(uintptr_t)zc->zc_nvlist_dst);
1483         zc->zc_nvlist_conf = 0;
1484         zc->zc_nvlist_src = 0;
1485         zc->zc_nvlist_dst = 0;
1486 }
1487
1488 static int
1489 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1490     nvlist_t *nvl)
1491 {
1492         char *packed;
1493         size_t len;
1494
1495         verify(nvlist_size(nvl, &len, NV_ENCODE_NATIVE) == 0);
1496
1497         if ((packed = zfs_alloc(hdl, len)) == NULL)
1498                 return (-1);
1499
1500         verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1501
1502         *outnv = (uint64_t)(uintptr_t)packed;
1503         *outlen = len;
1504
1505         return (0);
1506 }
1507
1508 int
1509 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1510 {
1511         return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1512             &zc->zc_nvlist_conf_size, nvl));
1513 }
1514
1515 int
1516 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1517 {
1518         return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1519             &zc->zc_nvlist_src_size, nvl));
1520 }
1521
1522 /*
1523  * Unpacks an nvlist from the ZFS ioctl command structure.
1524  */
1525 int
1526 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1527 {
1528         if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1529             zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1530                 return (no_memory(hdl));
1531
1532         return (0);
1533 }
1534
1535 int
1536 zfs_ioctl(libzfs_handle_t *hdl, int request, zfs_cmd_t *zc)
1537 {
1538         return (ioctl(hdl->libzfs_fd, request, zc));
1539 }
1540
1541 /*
1542  * ================================================================
1543  * API shared by zfs and zpool property management
1544  * ================================================================
1545  */
1546
1547 static void
1548 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1549 {
1550         zprop_list_t *pl = cbp->cb_proplist;
1551         int i;
1552         char *title;
1553         size_t len;
1554
1555         cbp->cb_first = B_FALSE;
1556         if (cbp->cb_scripted)
1557                 return;
1558
1559         /*
1560          * Start with the length of the column headers.
1561          */
1562         cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1563         cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1564             "PROPERTY"));
1565         cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1566             "VALUE"));
1567         cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1568             "RECEIVED"));
1569         cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1570             "SOURCE"));
1571
1572         /* first property is always NAME */
1573         assert(cbp->cb_proplist->pl_prop ==
1574             ((type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME : ZFS_PROP_NAME));
1575
1576         /*
1577          * Go through and calculate the widths for each column.  For the
1578          * 'source' column, we kludge it up by taking the worst-case scenario of
1579          * inheriting from the longest name.  This is acceptable because in the
1580          * majority of cases 'SOURCE' is the last column displayed, and we don't
1581          * use the width anyway.  Note that the 'VALUE' column can be oversized,
1582          * if the name of the property is much longer than any values we find.
1583          */
1584         for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1585                 /*
1586                  * 'PROPERTY' column
1587                  */
1588                 if (pl->pl_prop != ZPROP_INVAL) {
1589                         const char *propname = (type == ZFS_TYPE_POOL) ?
1590                             zpool_prop_to_name(pl->pl_prop) :
1591                             zfs_prop_to_name(pl->pl_prop);
1592
1593                         len = strlen(propname);
1594                         if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1595                                 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1596                 } else {
1597                         len = strlen(pl->pl_user_prop);
1598                         if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1599                                 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1600                 }
1601
1602                 /*
1603                  * 'VALUE' column.  The first property is always the 'name'
1604                  * property that was tacked on either by /sbin/zfs's
1605                  * zfs_do_get() or when calling zprop_expand_list(), so we
1606                  * ignore its width.  If the user specified the name property
1607                  * to display, then it will be later in the list in any case.
1608                  */
1609                 if (pl != cbp->cb_proplist &&
1610                     pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1611                         cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1612
1613                 /* 'RECEIVED' column. */
1614                 if (pl != cbp->cb_proplist &&
1615                     pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1616                         cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1617
1618                 /*
1619                  * 'NAME' and 'SOURCE' columns
1620                  */
1621                 if (pl->pl_prop == (type == ZFS_TYPE_POOL ? ZPOOL_PROP_NAME :
1622                     ZFS_PROP_NAME) &&
1623                     pl->pl_width > cbp->cb_colwidths[GET_COL_NAME]) {
1624                         cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1625                         cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1626                             strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1627                 }
1628         }
1629
1630         /*
1631          * Now go through and print the headers.
1632          */
1633         for (i = 0; i < ZFS_GET_NCOLS; i++) {
1634                 switch (cbp->cb_columns[i]) {
1635                 case GET_COL_NAME:
1636                         title = dgettext(TEXT_DOMAIN, "NAME");
1637                         break;
1638                 case GET_COL_PROPERTY:
1639                         title = dgettext(TEXT_DOMAIN, "PROPERTY");
1640                         break;
1641                 case GET_COL_VALUE:
1642                         title = dgettext(TEXT_DOMAIN, "VALUE");
1643                         break;
1644                 case GET_COL_RECVD:
1645                         title = dgettext(TEXT_DOMAIN, "RECEIVED");
1646                         break;
1647                 case GET_COL_SOURCE:
1648                         title = dgettext(TEXT_DOMAIN, "SOURCE");
1649                         break;
1650                 default:
1651                         title = NULL;
1652                 }
1653
1654                 if (title != NULL) {
1655                         if (i == (ZFS_GET_NCOLS - 1) ||
1656                             cbp->cb_columns[i + 1] == GET_COL_NONE)
1657                                 (void) printf("%s", title);
1658                         else
1659                                 (void) printf("%-*s  ",
1660                                     cbp->cb_colwidths[cbp->cb_columns[i]],
1661                                     title);
1662                 }
1663         }
1664         (void) printf("\n");
1665 }
1666
1667 /*
1668  * Display a single line of output, according to the settings in the callback
1669  * structure.
1670  */
1671 void
1672 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1673     const char *propname, const char *value, zprop_source_t sourcetype,
1674     const char *source, const char *recvd_value)
1675 {
1676         int i;
1677         const char *str = NULL;
1678         char buf[128];
1679
1680         /*
1681          * Ignore those source types that the user has chosen to ignore.
1682          */
1683         if ((sourcetype & cbp->cb_sources) == 0)
1684                 return;
1685
1686         if (cbp->cb_first)
1687                 zprop_print_headers(cbp, cbp->cb_type);
1688
1689         for (i = 0; i < ZFS_GET_NCOLS; i++) {
1690                 switch (cbp->cb_columns[i]) {
1691                 case GET_COL_NAME:
1692                         str = name;
1693                         break;
1694
1695                 case GET_COL_PROPERTY:
1696                         str = propname;
1697                         break;
1698
1699                 case GET_COL_VALUE:
1700                         str = value;
1701                         break;
1702
1703                 case GET_COL_SOURCE:
1704                         switch (sourcetype) {
1705                         case ZPROP_SRC_NONE:
1706                                 str = "-";
1707                                 break;
1708
1709                         case ZPROP_SRC_DEFAULT:
1710                                 str = "default";
1711                                 break;
1712
1713                         case ZPROP_SRC_LOCAL:
1714                                 str = "local";
1715                                 break;
1716
1717                         case ZPROP_SRC_TEMPORARY:
1718                                 str = "temporary";
1719                                 break;
1720
1721                         case ZPROP_SRC_INHERITED:
1722                                 (void) snprintf(buf, sizeof (buf),
1723                                     "inherited from %s", source);
1724                                 str = buf;
1725                                 break;
1726                         case ZPROP_SRC_RECEIVED:
1727                                 str = "received";
1728                                 break;
1729
1730                         default:
1731                                 str = NULL;
1732                                 assert(!"unhandled zprop_source_t");
1733                         }
1734                         break;
1735
1736                 case GET_COL_RECVD:
1737                         str = (recvd_value == NULL ? "-" : recvd_value);
1738                         break;
1739
1740                 default:
1741                         continue;
1742                 }
1743
1744                 if (i == (ZFS_GET_NCOLS - 1) ||
1745                     cbp->cb_columns[i + 1] == GET_COL_NONE)
1746                         (void) printf("%s", str);
1747                 else if (cbp->cb_scripted)
1748                         (void) printf("%s\t", str);
1749                 else
1750                         (void) printf("%-*s  ",
1751                             cbp->cb_colwidths[cbp->cb_columns[i]],
1752                             str);
1753         }
1754
1755         (void) printf("\n");
1756 }
1757
1758 /*
1759  * Given a numeric suffix, convert the value into a number of bits that the
1760  * resulting value must be shifted.
1761  */
1762 static int
1763 str2shift(libzfs_handle_t *hdl, const char *buf)
1764 {
1765         const char *ends = "BKMGTPEZ";
1766         int i;
1767
1768         if (buf[0] == '\0')
1769                 return (0);
1770         for (i = 0; i < strlen(ends); i++) {
1771                 if (toupper(buf[0]) == ends[i])
1772                         break;
1773         }
1774         if (i == strlen(ends)) {
1775                 if (hdl)
1776                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1777                             "invalid numeric suffix '%s'"), buf);
1778                 return (-1);
1779         }
1780
1781         /*
1782          * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1783          * However, 'BB' and 'BiB' are disallowed.
1784          */
1785         if (buf[1] == '\0' ||
1786             (toupper(buf[0]) != 'B' &&
1787             ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1788             (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1789             buf[3] == '\0'))))
1790                 return (10 * i);
1791
1792         if (hdl)
1793                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1794                     "invalid numeric suffix '%s'"), buf);
1795         return (-1);
1796 }
1797
1798 /*
1799  * Convert a string of the form '100G' into a real number.  Used when setting
1800  * properties or creating a volume.  'buf' is used to place an extended error
1801  * message for the caller to use.
1802  */
1803 int
1804 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1805 {
1806         char *end;
1807         int shift;
1808
1809         *num = 0;
1810
1811         /* Check to see if this looks like a number.  */
1812         if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1813                 if (hdl)
1814                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1815                             "bad numeric value '%s'"), value);
1816                 return (-1);
1817         }
1818
1819         /* Rely on strtoull() to process the numeric portion.  */
1820         errno = 0;
1821         *num = strtoull(value, &end, 10);
1822
1823         /*
1824          * Check for ERANGE, which indicates that the value is too large to fit
1825          * in a 64-bit value.
1826          */
1827         if (errno == ERANGE) {
1828                 if (hdl)
1829                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1830                             "numeric value is too large"));
1831                 return (-1);
1832         }
1833
1834         /*
1835          * If we have a decimal value, then do the computation with floating
1836          * point arithmetic.  Otherwise, use standard arithmetic.
1837          */
1838         if (*end == '.') {
1839                 double fval = strtod(value, &end);
1840
1841                 if ((shift = str2shift(hdl, end)) == -1)
1842                         return (-1);
1843
1844                 fval *= pow(2, shift);
1845
1846                 if (fval > UINT64_MAX) {
1847                         if (hdl)
1848                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1849                                     "numeric value is too large"));
1850                         return (-1);
1851                 }
1852
1853                 *num = (uint64_t)fval;
1854         } else {
1855                 if ((shift = str2shift(hdl, end)) == -1)
1856                         return (-1);
1857
1858                 /* Check for overflow */
1859                 if (shift >= 64 || (*num << shift) >> shift != *num) {
1860                         if (hdl)
1861                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1862                                     "numeric value is too large"));
1863                         return (-1);
1864                 }
1865
1866                 *num <<= shift;
1867         }
1868
1869         return (0);
1870 }
1871
1872 /*
1873  * Given a propname=value nvpair to set, parse any numeric properties
1874  * (index, boolean, etc) if they are specified as strings and add the
1875  * resulting nvpair to the returned nvlist.
1876  *
1877  * At the DSL layer, all properties are either 64-bit numbers or strings.
1878  * We want the user to be able to ignore this fact and specify properties
1879  * as native values (numbers, for example) or as strings (to simplify
1880  * command line utilities).  This also handles converting index types
1881  * (compression, checksum, etc) from strings to their on-disk index.
1882  */
1883 int
1884 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1885     zfs_type_t type, nvlist_t *ret, char **svalp, uint64_t *ivalp,
1886     const char *errbuf)
1887 {
1888         data_type_t datatype = nvpair_type(elem);
1889         zprop_type_t proptype;
1890         const char *propname;
1891         char *value;
1892         boolean_t isnone = B_FALSE;
1893         boolean_t isauto = B_FALSE;
1894         int err = 0;
1895
1896         if (type == ZFS_TYPE_POOL) {
1897                 proptype = zpool_prop_get_type(prop);
1898                 propname = zpool_prop_to_name(prop);
1899         } else {
1900                 proptype = zfs_prop_get_type(prop);
1901                 propname = zfs_prop_to_name(prop);
1902         }
1903
1904         /*
1905          * Convert any properties to the internal DSL value types.
1906          */
1907         *svalp = NULL;
1908         *ivalp = 0;
1909
1910         switch (proptype) {
1911         case PROP_TYPE_STRING:
1912                 if (datatype != DATA_TYPE_STRING) {
1913                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1914                             "'%s' must be a string"), nvpair_name(elem));
1915                         goto error;
1916                 }
1917                 err = nvpair_value_string(elem, svalp);
1918                 if (err != 0) {
1919                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1920                             "'%s' is invalid"), nvpair_name(elem));
1921                         goto error;
1922                 }
1923                 if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1924                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1925                             "'%s' is too long"), nvpair_name(elem));
1926                         goto error;
1927                 }
1928                 break;
1929
1930         case PROP_TYPE_NUMBER:
1931                 if (datatype == DATA_TYPE_STRING) {
1932                         (void) nvpair_value_string(elem, &value);
1933                         if (strcmp(value, "none") == 0) {
1934                                 isnone = B_TRUE;
1935                         } else if (strcmp(value, "auto") == 0) {
1936                                 isauto = B_TRUE;
1937                         } else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1938                                 goto error;
1939                         }
1940                 } else if (datatype == DATA_TYPE_UINT64) {
1941                         (void) nvpair_value_uint64(elem, ivalp);
1942                 } else {
1943                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1944                             "'%s' must be a number"), nvpair_name(elem));
1945                         goto error;
1946                 }
1947
1948                 /*
1949                  * Quota special: force 'none' and don't allow 0.
1950                  */
1951                 if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1952                     (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1953                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1954                             "use 'none' to disable quota/refquota"));
1955                         goto error;
1956                 }
1957
1958                 /*
1959                  * Special handling for "*_limit=none". In this case it's not
1960                  * 0 but UINT64_MAX.
1961                  */
1962                 if ((type & ZFS_TYPE_DATASET) && isnone &&
1963                     (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1964                     prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1965                         *ivalp = UINT64_MAX;
1966                 }
1967
1968                 /*
1969                  * Special handling for setting 'refreservation' to 'auto'.  Use
1970                  * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1971                  * 'auto' is only allowed on volumes.
1972                  */
1973                 if (isauto) {
1974                         switch (prop) {
1975                         case ZFS_PROP_REFRESERVATION:
1976                                 if ((type & ZFS_TYPE_VOLUME) == 0) {
1977                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1978                                             "'%s=auto' only allowed on "
1979                                             "volumes"), nvpair_name(elem));
1980                                         goto error;
1981                                 }
1982                                 *ivalp = UINT64_MAX;
1983                                 break;
1984                         default:
1985                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1986                                     "'auto' is invalid value for '%s'"),
1987                                     nvpair_name(elem));
1988                                 goto error;
1989                         }
1990                 }
1991
1992                 break;
1993
1994         case PROP_TYPE_INDEX:
1995                 if (datatype != DATA_TYPE_STRING) {
1996                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1997                             "'%s' must be a string"), nvpair_name(elem));
1998                         goto error;
1999                 }
2000
2001                 (void) nvpair_value_string(elem, &value);
2002
2003                 if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
2004                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2005                             "'%s' must be one of '%s'"), propname,
2006                             zprop_values(prop, type));
2007                         goto error;
2008                 }
2009                 break;
2010
2011         default:
2012                 abort();
2013         }
2014
2015         /*
2016          * Add the result to our return set of properties.
2017          */
2018         if (*svalp != NULL) {
2019                 if (nvlist_add_string(ret, propname, *svalp) != 0) {
2020                         (void) no_memory(hdl);
2021                         return (-1);
2022                 }
2023         } else {
2024                 if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
2025                         (void) no_memory(hdl);
2026                         return (-1);
2027                 }
2028         }
2029
2030         return (0);
2031 error:
2032         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
2033         return (-1);
2034 }
2035
2036 static int
2037 addlist(libzfs_handle_t *hdl, char *propname, zprop_list_t **listp,
2038     zfs_type_t type)
2039 {
2040         int prop;
2041         zprop_list_t *entry;
2042
2043         prop = zprop_name_to_prop(propname, type);
2044
2045         if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
2046                 prop = ZPROP_INVAL;
2047
2048         /*
2049          * When no property table entry can be found, return failure if
2050          * this is a pool property or if this isn't a user-defined
2051          * dataset property,
2052          */
2053         if (prop == ZPROP_INVAL && ((type == ZFS_TYPE_POOL &&
2054             !zpool_prop_feature(propname) &&
2055             !zpool_prop_unsupported(propname)) ||
2056             (type == ZFS_TYPE_DATASET && !zfs_prop_user(propname) &&
2057             !zfs_prop_userquota(propname) && !zfs_prop_written(propname)))) {
2058                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2059                     "invalid property '%s'"), propname);
2060                 return (zfs_error(hdl, EZFS_BADPROP,
2061                     dgettext(TEXT_DOMAIN, "bad property list")));
2062         }
2063
2064         if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
2065                 return (-1);
2066
2067         entry->pl_prop = prop;
2068         if (prop == ZPROP_INVAL) {
2069                 if ((entry->pl_user_prop = zfs_strdup(hdl, propname)) ==
2070                     NULL) {
2071                         free(entry);
2072                         return (-1);
2073                 }
2074                 entry->pl_width = strlen(propname);
2075         } else {
2076                 entry->pl_width = zprop_width(prop, &entry->pl_fixed,
2077                     type);
2078         }
2079
2080         *listp = entry;
2081
2082         return (0);
2083 }
2084
2085 /*
2086  * Given a comma-separated list of properties, construct a property list
2087  * containing both user-defined and native properties.  This function will
2088  * return a NULL list if 'all' is specified, which can later be expanded
2089  * by zprop_expand_list().
2090  */
2091 int
2092 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
2093     zfs_type_t type)
2094 {
2095         *listp = NULL;
2096
2097         /*
2098          * If 'all' is specified, return a NULL list.
2099          */
2100         if (strcmp(props, "all") == 0)
2101                 return (0);
2102
2103         /*
2104          * If no props were specified, return an error.
2105          */
2106         if (props[0] == '\0') {
2107                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2108                     "no properties specified"));
2109                 return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
2110                     "bad property list")));
2111         }
2112
2113         /*
2114          * It would be nice to use getsubopt() here, but the inclusion of column
2115          * aliases makes this more effort than it's worth.
2116          */
2117         while (*props != '\0') {
2118                 size_t len;
2119                 char *p;
2120                 char c;
2121
2122                 if ((p = strchr(props, ',')) == NULL) {
2123                         len = strlen(props);
2124                         p = props + len;
2125                 } else {
2126                         len = p - props;
2127                 }
2128
2129                 /*
2130                  * Check for empty options.
2131                  */
2132                 if (len == 0) {
2133                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2134                             "empty property name"));
2135                         return (zfs_error(hdl, EZFS_BADPROP,
2136                             dgettext(TEXT_DOMAIN, "bad property list")));
2137                 }
2138
2139                 /*
2140                  * Check all regular property names.
2141                  */
2142                 c = props[len];
2143                 props[len] = '\0';
2144
2145                 if (strcmp(props, "space") == 0) {
2146                         static char *spaceprops[] = {
2147                                 "name", "avail", "used", "usedbysnapshots",
2148                                 "usedbydataset", "usedbyrefreservation",
2149                                 "usedbychildren", NULL
2150                         };
2151                         int i;
2152
2153                         for (i = 0; spaceprops[i]; i++) {
2154                                 if (addlist(hdl, spaceprops[i], listp, type))
2155                                         return (-1);
2156                                 listp = &(*listp)->pl_next;
2157                         }
2158                 } else {
2159                         if (addlist(hdl, props, listp, type))
2160                                 return (-1);
2161                         listp = &(*listp)->pl_next;
2162                 }
2163
2164                 props = p;
2165                 if (c == ',')
2166                         props++;
2167         }
2168
2169         return (0);
2170 }
2171
2172 void
2173 zprop_free_list(zprop_list_t *pl)
2174 {
2175         zprop_list_t *next;
2176
2177         while (pl != NULL) {
2178                 next = pl->pl_next;
2179                 free(pl->pl_user_prop);
2180                 free(pl);
2181                 pl = next;
2182         }
2183 }
2184
2185 typedef struct expand_data {
2186         zprop_list_t    **last;
2187         libzfs_handle_t *hdl;
2188         zfs_type_t type;
2189 } expand_data_t;
2190
2191 int
2192 zprop_expand_list_cb(int prop, void *cb)
2193 {
2194         zprop_list_t *entry;
2195         expand_data_t *edp = cb;
2196
2197         if ((entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t))) == NULL)
2198                 return (ZPROP_INVAL);
2199
2200         entry->pl_prop = prop;
2201         entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
2202         entry->pl_all = B_TRUE;
2203
2204         *(edp->last) = entry;
2205         edp->last = &entry->pl_next;
2206
2207         return (ZPROP_CONT);
2208 }
2209
2210 int
2211 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
2212 {
2213         zprop_list_t *entry;
2214         zprop_list_t **last;
2215         expand_data_t exp;
2216
2217         if (*plp == NULL) {
2218                 /*
2219                  * If this is the very first time we've been called for an 'all'
2220                  * specification, expand the list to include all native
2221                  * properties.
2222                  */
2223                 last = plp;
2224
2225                 exp.last = last;
2226                 exp.hdl = hdl;
2227                 exp.type = type;
2228
2229                 if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
2230                     B_FALSE, type) == ZPROP_INVAL)
2231                         return (-1);
2232
2233                 /*
2234                  * Add 'name' to the beginning of the list, which is handled
2235                  * specially.
2236                  */
2237                 if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
2238                         return (-1);
2239
2240                 entry->pl_prop = (type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME :
2241                     ZFS_PROP_NAME;
2242                 entry->pl_width = zprop_width(entry->pl_prop,
2243                     &entry->pl_fixed, type);
2244                 entry->pl_all = B_TRUE;
2245                 entry->pl_next = *plp;
2246                 *plp = entry;
2247         }
2248         return (0);
2249 }
2250
2251 int
2252 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
2253     zfs_type_t type)
2254 {
2255         return (zprop_iter_common(func, cb, show_all, ordered, type));
2256 }