]> granicus.if.org Git - zfs/blob - lib/libzfs/libzfs_util.c
ZVOLs should not be allowed to have children
[zfs] / 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 <math.h>
43 #include <sys/stat.h>
44 #include <sys/mnttab.h>
45 #include <sys/mntent.h>
46 #include <sys/types.h>
47 #include <sys/wait.h>
48
49 #include <libzfs.h>
50 #include <libzfs_core.h>
51
52 #include "libzfs_impl.h"
53 #include "zfs_prop.h"
54 #include "zfeature_common.h"
55 #include <zfs_fletcher.h>
56 #include <libzutil.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_TOOMANY:
287                 return (dgettext(TEXT_DOMAIN, "argument list too long"));
288         case EZFS_INITIALIZING:
289                 return (dgettext(TEXT_DOMAIN, "currently initializing"));
290         case EZFS_NO_INITIALIZE:
291                 return (dgettext(TEXT_DOMAIN, "there is no active "
292                     "initialization"));
293         case EZFS_WRONG_PARENT:
294                 return (dgettext(TEXT_DOMAIN, "invalid parent dataset"));
295         case EZFS_UNKNOWN:
296                 return (dgettext(TEXT_DOMAIN, "unknown error"));
297         default:
298                 assert(hdl->libzfs_error == 0);
299                 return (dgettext(TEXT_DOMAIN, "no error"));
300         }
301 }
302
303 /*PRINTFLIKE2*/
304 void
305 zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
306 {
307         va_list ap;
308
309         va_start(ap, fmt);
310
311         (void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
312             fmt, ap);
313         hdl->libzfs_desc_active = 1;
314
315         va_end(ap);
316 }
317
318 static void
319 zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
320 {
321         (void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
322             fmt, ap);
323         hdl->libzfs_error = error;
324
325         if (hdl->libzfs_desc_active)
326                 hdl->libzfs_desc_active = 0;
327         else
328                 hdl->libzfs_desc[0] = '\0';
329
330         if (hdl->libzfs_printerr) {
331                 if (error == EZFS_UNKNOWN) {
332                         (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
333                             "error: %s\n"), libzfs_error_description(hdl));
334                         abort();
335                 }
336
337                 (void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
338                     libzfs_error_description(hdl));
339                 if (error == EZFS_NOMEM)
340                         exit(1);
341         }
342 }
343
344 int
345 zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
346 {
347         return (zfs_error_fmt(hdl, error, "%s", msg));
348 }
349
350 /*PRINTFLIKE3*/
351 int
352 zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
353 {
354         va_list ap;
355
356         va_start(ap, fmt);
357
358         zfs_verror(hdl, error, fmt, ap);
359
360         va_end(ap);
361
362         return (-1);
363 }
364
365 static int
366 zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
367     va_list ap)
368 {
369         switch (error) {
370         case EPERM:
371         case EACCES:
372                 zfs_verror(hdl, EZFS_PERM, fmt, ap);
373                 return (-1);
374
375         case ECANCELED:
376                 zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
377                 return (-1);
378
379         case EIO:
380                 zfs_verror(hdl, EZFS_IO, fmt, ap);
381                 return (-1);
382
383         case EFAULT:
384                 zfs_verror(hdl, EZFS_FAULT, fmt, ap);
385                 return (-1);
386
387         case EINTR:
388                 zfs_verror(hdl, EZFS_INTR, fmt, ap);
389                 return (-1);
390         }
391
392         return (0);
393 }
394
395 int
396 zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
397 {
398         return (zfs_standard_error_fmt(hdl, error, "%s", msg));
399 }
400
401 /*PRINTFLIKE3*/
402 int
403 zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
404 {
405         va_list ap;
406
407         va_start(ap, fmt);
408
409         if (zfs_common_error(hdl, error, fmt, ap) != 0) {
410                 va_end(ap);
411                 return (-1);
412         }
413
414         switch (error) {
415         case ENXIO:
416         case ENODEV:
417         case EPIPE:
418                 zfs_verror(hdl, EZFS_IO, fmt, ap);
419                 break;
420
421         case ENOENT:
422                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
423                     "dataset does not exist"));
424                 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
425                 break;
426
427         case ENOSPC:
428         case EDQUOT:
429                 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
430                 break;
431
432         case EEXIST:
433                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
434                     "dataset already exists"));
435                 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
436                 break;
437
438         case EBUSY:
439                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
440                     "dataset is busy"));
441                 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
442                 break;
443         case EROFS:
444                 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
445                 break;
446         case ENAMETOOLONG:
447                 zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
448                 break;
449         case ENOTSUP:
450                 zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
451                 break;
452         case EAGAIN:
453                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
454                     "pool I/O is currently suspended"));
455                 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
456                 break;
457         case EREMOTEIO:
458                 zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
459                 break;
460         case ZFS_ERR_IOC_CMD_UNAVAIL:
461                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
462                     "module does not support this operation. A reboot may "
463                     "be required to enable this operation."));
464                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
465                 break;
466         case ZFS_ERR_IOC_ARG_UNAVAIL:
467                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
468                     "module does not support an option for this operation. "
469                     "A reboot may be required to enable this option."));
470                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
471                 break;
472         case ZFS_ERR_IOC_ARG_REQUIRED:
473         case ZFS_ERR_IOC_ARG_BADTYPE:
474                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
475                 break;
476         case ZFS_ERR_WRONG_PARENT:
477                 zfs_verror(hdl, EZFS_WRONG_PARENT, fmt, ap);
478                 break;
479         default:
480                 zfs_error_aux(hdl, strerror(error));
481                 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
482                 break;
483         }
484
485         va_end(ap);
486         return (-1);
487 }
488
489 int
490 zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
491 {
492         return (zpool_standard_error_fmt(hdl, error, "%s", msg));
493 }
494
495 /*PRINTFLIKE3*/
496 int
497 zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
498 {
499         va_list ap;
500
501         va_start(ap, fmt);
502
503         if (zfs_common_error(hdl, error, fmt, ap) != 0) {
504                 va_end(ap);
505                 return (-1);
506         }
507
508         switch (error) {
509         case ENODEV:
510                 zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
511                 break;
512
513         case ENOENT:
514                 zfs_error_aux(hdl,
515                     dgettext(TEXT_DOMAIN, "no such pool or dataset"));
516                 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
517                 break;
518
519         case EEXIST:
520                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
521                     "pool already exists"));
522                 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
523                 break;
524
525         case EBUSY:
526                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
527                 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
528                 break;
529
530         /* There is no pending operation to cancel */
531         case ENOTACTIVE:
532                 zfs_verror(hdl, EZFS_NO_PENDING, fmt, ap);
533                 break;
534
535         case ENXIO:
536                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
537                     "one or more devices is currently unavailable"));
538                 zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
539                 break;
540
541         case ENAMETOOLONG:
542                 zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
543                 break;
544
545         case ENOTSUP:
546                 zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
547                 break;
548
549         case EINVAL:
550                 zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
551                 break;
552
553         case ENOSPC:
554         case EDQUOT:
555                 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
556                 return (-1);
557
558         case EAGAIN:
559                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
560                     "pool I/O is currently suspended"));
561                 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
562                 break;
563
564         case EROFS:
565                 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
566                 break;
567         case EDOM:
568                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
569                     "block size out of range or does not match"));
570                 zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
571                 break;
572         case EREMOTEIO:
573                 zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
574                 break;
575         case ZFS_ERR_CHECKPOINT_EXISTS:
576                 zfs_verror(hdl, EZFS_CHECKPOINT_EXISTS, fmt, ap);
577                 break;
578         case ZFS_ERR_DISCARDING_CHECKPOINT:
579                 zfs_verror(hdl, EZFS_DISCARDING_CHECKPOINT, fmt, ap);
580                 break;
581         case ZFS_ERR_NO_CHECKPOINT:
582                 zfs_verror(hdl, EZFS_NO_CHECKPOINT, fmt, ap);
583                 break;
584         case ZFS_ERR_DEVRM_IN_PROGRESS:
585                 zfs_verror(hdl, EZFS_DEVRM_IN_PROGRESS, fmt, ap);
586                 break;
587         case ZFS_ERR_VDEV_TOO_BIG:
588                 zfs_verror(hdl, EZFS_VDEV_TOO_BIG, fmt, ap);
589                 break;
590         case ZFS_ERR_IOC_CMD_UNAVAIL:
591                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
592                     "module does not support this operation. A reboot may "
593                     "be required to enable this operation."));
594                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
595                 break;
596         case ZFS_ERR_IOC_ARG_UNAVAIL:
597                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
598                     "module does not support an option for this operation. "
599                     "A reboot may be required to enable this option."));
600                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
601                 break;
602         case ZFS_ERR_IOC_ARG_REQUIRED:
603         case ZFS_ERR_IOC_ARG_BADTYPE:
604                 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
605                 break;
606         default:
607                 zfs_error_aux(hdl, strerror(error));
608                 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
609         }
610
611         va_end(ap);
612         return (-1);
613 }
614
615 /*
616  * Display an out of memory error message and abort the current program.
617  */
618 int
619 no_memory(libzfs_handle_t *hdl)
620 {
621         return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
622 }
623
624 /*
625  * A safe form of malloc() which will die if the allocation fails.
626  */
627 void *
628 zfs_alloc(libzfs_handle_t *hdl, size_t size)
629 {
630         void *data;
631
632         if ((data = calloc(1, size)) == NULL)
633                 (void) no_memory(hdl);
634
635         return (data);
636 }
637
638 /*
639  * A safe form of asprintf() which will die if the allocation fails.
640  */
641 /*PRINTFLIKE2*/
642 char *
643 zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
644 {
645         va_list ap;
646         char *ret;
647         int err;
648
649         va_start(ap, fmt);
650
651         err = vasprintf(&ret, fmt, ap);
652
653         va_end(ap);
654
655         if (err < 0)
656                 (void) no_memory(hdl);
657
658         return (ret);
659 }
660
661 /*
662  * A safe form of realloc(), which also zeroes newly allocated space.
663  */
664 void *
665 zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
666 {
667         void *ret;
668
669         if ((ret = realloc(ptr, newsize)) == NULL) {
670                 (void) no_memory(hdl);
671                 return (NULL);
672         }
673
674         bzero((char *)ret + oldsize, (newsize - oldsize));
675         return (ret);
676 }
677
678 /*
679  * A safe form of strdup() which will die if the allocation fails.
680  */
681 char *
682 zfs_strdup(libzfs_handle_t *hdl, const char *str)
683 {
684         char *ret;
685
686         if ((ret = strdup(str)) == NULL)
687                 (void) no_memory(hdl);
688
689         return (ret);
690 }
691
692 void
693 libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
694 {
695         hdl->libzfs_printerr = printerr;
696 }
697
698 static int
699 libzfs_module_loaded(const char *module)
700 {
701         const char path_prefix[] = "/sys/module/";
702         char path[256];
703
704         memcpy(path, path_prefix, sizeof (path_prefix) - 1);
705         strcpy(path + sizeof (path_prefix) - 1, module);
706
707         return (access(path, F_OK) == 0);
708 }
709
710
711 /*
712  * Read lines from an open file descriptor and store them in an array of
713  * strings until EOF.  lines[] will be allocated and populated with all the
714  * lines read.  All newlines are replaced with NULL terminators for
715  * convenience.  lines[] must be freed after use with libzfs_free_str_array().
716  *
717  * Returns the number of lines read.
718  */
719 static int
720 libzfs_read_stdout_from_fd(int fd, char **lines[])
721 {
722
723         FILE *fp;
724         int lines_cnt = 0;
725         size_t len = 0;
726         char *line = NULL;
727         char **tmp_lines = NULL, **tmp;
728         char *nl = NULL;
729         int rc;
730
731         fp = fdopen(fd, "r");
732         if (fp == NULL)
733                 return (0);
734         while (1) {
735                 rc = getline(&line, &len, fp);
736                 if (rc == -1)
737                         break;
738
739                 tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
740                 if (tmp == NULL) {
741                         /* Return the lines we were able to process */
742                         break;
743                 }
744                 tmp_lines = tmp;
745
746                 /* Terminate newlines */
747                 if ((nl = strchr(line, '\n')) != NULL)
748                         *nl = '\0';
749                 tmp_lines[lines_cnt] = line;
750                 lines_cnt++;
751                 line = NULL;
752         }
753         fclose(fp);
754         *lines = tmp_lines;
755         return (lines_cnt);
756 }
757
758 static int
759 libzfs_run_process_impl(const char *path, char *argv[], char *env[], int flags,
760     char **lines[], int *lines_cnt)
761 {
762         pid_t pid;
763         int error, devnull_fd;
764         int link[2];
765
766         /*
767          * Setup a pipe between our child and parent process if we're
768          * reading stdout.
769          */
770         if ((lines != NULL) && pipe(link) == -1)
771                 return (-ESTRPIPE);
772
773         pid = vfork();
774         if (pid == 0) {
775                 /* Child process */
776                 devnull_fd = open("/dev/null", O_WRONLY);
777
778                 if (devnull_fd < 0)
779                         _exit(-1);
780
781                 if (!(flags & STDOUT_VERBOSE) && (lines == NULL))
782                         (void) dup2(devnull_fd, STDOUT_FILENO);
783                 else if (lines != NULL) {
784                         /* Save the output to lines[] */
785                         dup2(link[1], STDOUT_FILENO);
786                         close(link[0]);
787                         close(link[1]);
788                 }
789
790                 if (!(flags & STDERR_VERBOSE))
791                         (void) dup2(devnull_fd, STDERR_FILENO);
792
793                 close(devnull_fd);
794
795                 if (flags & NO_DEFAULT_PATH) {
796                         if (env == NULL)
797                                 execv(path, argv);
798                         else
799                                 execve(path, argv, env);
800                 } else {
801                         if (env == NULL)
802                                 execvp(path, argv);
803                         else
804                                 execvpe(path, argv, env);
805                 }
806
807                 _exit(-1);
808         } else if (pid > 0) {
809                 /* Parent process */
810                 int status;
811
812                 while ((error = waitpid(pid, &status, 0)) == -1 &&
813                     errno == EINTR) { }
814                 if (error < 0 || !WIFEXITED(status))
815                         return (-1);
816
817                 if (lines != NULL) {
818                         close(link[1]);
819                         *lines_cnt = libzfs_read_stdout_from_fd(link[0], lines);
820                 }
821                 return (WEXITSTATUS(status));
822         }
823
824         return (-1);
825 }
826
827 int
828 libzfs_run_process(const char *path, char *argv[], int flags)
829 {
830         return (libzfs_run_process_impl(path, argv, NULL, flags, NULL, NULL));
831 }
832
833 /*
834  * Run a command and store its stdout lines in an array of strings (lines[]).
835  * lines[] is allocated and populated for you, and the number of lines is set in
836  * lines_cnt.  lines[] must be freed after use with libzfs_free_str_array().
837  * All newlines (\n) in lines[] are terminated for convenience.
838  */
839 int
840 libzfs_run_process_get_stdout(const char *path, char *argv[], char *env[],
841     char **lines[], int *lines_cnt)
842 {
843         return (libzfs_run_process_impl(path, argv, env, 0, lines, lines_cnt));
844 }
845
846 /*
847  * Same as libzfs_run_process_get_stdout(), but run without $PATH set.  This
848  * means that *path needs to be the full path to the executable.
849  */
850 int
851 libzfs_run_process_get_stdout_nopath(const char *path, char *argv[],
852     char *env[], char **lines[], int *lines_cnt)
853 {
854         return (libzfs_run_process_impl(path, argv, env, NO_DEFAULT_PATH,
855             lines, lines_cnt));
856 }
857
858 /*
859  * Free an array of strings.  Free both the strings contained in the array and
860  * the array itself.
861  */
862 void
863 libzfs_free_str_array(char **strs, int count)
864 {
865         while (--count >= 0)
866                 free(strs[count]);
867
868         free(strs);
869 }
870
871 /*
872  * Returns 1 if environment variable is set to "YES", "yes", "ON", "on", or
873  * a non-zero number.
874  *
875  * Returns 0 otherwise.
876  */
877 int
878 libzfs_envvar_is_set(char *envvar)
879 {
880         char *env = getenv(envvar);
881         if (env && (strtoul(env, NULL, 0) > 0 ||
882             (!strncasecmp(env, "YES", 3) && strnlen(env, 4) == 3) ||
883             (!strncasecmp(env, "ON", 2) && strnlen(env, 3) == 2)))
884                 return (1);
885
886         return (0);
887 }
888
889 /*
890  * Verify the required ZFS_DEV device is available and optionally attempt
891  * to load the ZFS modules.  Under normal circumstances the modules
892  * should already have been loaded by some external mechanism.
893  *
894  * Environment variables:
895  * - ZFS_MODULE_LOADING="YES|yes|ON|on" - Attempt to load modules.
896  * - ZFS_MODULE_TIMEOUT="<seconds>"     - Seconds to wait for ZFS_DEV
897  */
898 static int
899 libzfs_load_module(const char *module)
900 {
901         char *argv[4] = {"/sbin/modprobe", "-q", (char *)module, (char *)0};
902         char *load_str, *timeout_str;
903         long timeout = 10; /* seconds */
904         long busy_timeout = 10; /* milliseconds */
905         int load = 0, fd;
906         hrtime_t start;
907
908         /* Optionally request module loading */
909         if (!libzfs_module_loaded(module)) {
910                 load_str = getenv("ZFS_MODULE_LOADING");
911                 if (load_str) {
912                         if (!strncasecmp(load_str, "YES", strlen("YES")) ||
913                             !strncasecmp(load_str, "ON", strlen("ON")))
914                                 load = 1;
915                         else
916                                 load = 0;
917                 }
918
919                 if (load) {
920                         if (libzfs_run_process("/sbin/modprobe", argv, 0))
921                                 return (ENOEXEC);
922                 }
923
924                 if (!libzfs_module_loaded(module))
925                         return (ENXIO);
926         }
927
928         /*
929          * Device creation by udev is asynchronous and waiting may be
930          * required.  Busy wait for 10ms and then fall back to polling every
931          * 10ms for the allowed timeout (default 10s, max 10m).  This is
932          * done to optimize for the common case where the device is
933          * immediately available and to avoid penalizing the possible
934          * case where udev is slow or unable to create the device.
935          */
936         timeout_str = getenv("ZFS_MODULE_TIMEOUT");
937         if (timeout_str) {
938                 timeout = strtol(timeout_str, NULL, 0);
939                 timeout = MAX(MIN(timeout, (10 * 60)), 0); /* 0 <= N <= 600 */
940         }
941
942         start = gethrtime();
943         do {
944                 fd = open(ZFS_DEV, O_RDWR);
945                 if (fd >= 0) {
946                         (void) close(fd);
947                         return (0);
948                 } else if (errno != ENOENT) {
949                         return (errno);
950                 } else if (NSEC2MSEC(gethrtime() - start) < busy_timeout) {
951                         sched_yield();
952                 } else {
953                         usleep(10 * MILLISEC);
954                 }
955         } while (NSEC2MSEC(gethrtime() - start) < (timeout * MILLISEC));
956
957         return (ENOENT);
958 }
959
960 libzfs_handle_t *
961 libzfs_init(void)
962 {
963         libzfs_handle_t *hdl;
964         int error;
965
966         error = libzfs_load_module(ZFS_DRIVER);
967         if (error) {
968                 errno = error;
969                 return (NULL);
970         }
971
972         if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
973                 return (NULL);
974         }
975
976         if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR)) < 0) {
977                 free(hdl);
978                 return (NULL);
979         }
980
981 #ifdef HAVE_SETMNTENT
982         if ((hdl->libzfs_mnttab = setmntent(MNTTAB, "r")) == NULL) {
983 #else
984         if ((hdl->libzfs_mnttab = fopen(MNTTAB, "r")) == NULL) {
985 #endif
986                 (void) close(hdl->libzfs_fd);
987                 free(hdl);
988                 return (NULL);
989         }
990
991         hdl->libzfs_sharetab = fopen(ZFS_SHARETAB, "r");
992
993         if (libzfs_core_init() != 0) {
994                 (void) close(hdl->libzfs_fd);
995                 (void) fclose(hdl->libzfs_mnttab);
996                 if (hdl->libzfs_sharetab)
997                         (void) fclose(hdl->libzfs_sharetab);
998                 free(hdl);
999                 return (NULL);
1000         }
1001
1002         zfs_prop_init();
1003         zpool_prop_init();
1004         zpool_feature_init();
1005         libzfs_mnttab_init(hdl);
1006         fletcher_4_init();
1007
1008         if (getenv("ZFS_PROP_DEBUG") != NULL) {
1009                 hdl->libzfs_prop_debug = B_TRUE;
1010         }
1011
1012         /*
1013          * For testing, remove some settable properties and features
1014          */
1015         if (libzfs_envvar_is_set("ZFS_SYSFS_PROP_SUPPORT_TEST")) {
1016                 zprop_desc_t *proptbl;
1017
1018                 proptbl = zpool_prop_get_table();
1019                 proptbl[ZPOOL_PROP_COMMENT].pd_zfs_mod_supported = B_FALSE;
1020
1021                 proptbl = zfs_prop_get_table();
1022                 proptbl[ZFS_PROP_DNODESIZE].pd_zfs_mod_supported = B_FALSE;
1023
1024                 zfeature_info_t *ftbl = spa_feature_table;
1025                 ftbl[SPA_FEATURE_LARGE_BLOCKS].fi_zfs_mod_supported = B_FALSE;
1026         }
1027
1028         return (hdl);
1029 }
1030
1031 void
1032 libzfs_fini(libzfs_handle_t *hdl)
1033 {
1034         (void) close(hdl->libzfs_fd);
1035         if (hdl->libzfs_mnttab)
1036 #ifdef HAVE_SETMNTENT
1037                 (void) endmntent(hdl->libzfs_mnttab);
1038 #else
1039                 (void) fclose(hdl->libzfs_mnttab);
1040 #endif
1041         if (hdl->libzfs_sharetab)
1042                 (void) fclose(hdl->libzfs_sharetab);
1043         zfs_uninit_libshare(hdl);
1044         zpool_free_handles(hdl);
1045         namespace_clear(hdl);
1046         libzfs_mnttab_fini(hdl);
1047         libzfs_core_fini();
1048         fletcher_4_fini();
1049         free(hdl);
1050 }
1051
1052 libzfs_handle_t *
1053 zpool_get_handle(zpool_handle_t *zhp)
1054 {
1055         return (zhp->zpool_hdl);
1056 }
1057
1058 libzfs_handle_t *
1059 zfs_get_handle(zfs_handle_t *zhp)
1060 {
1061         return (zhp->zfs_hdl);
1062 }
1063
1064 zpool_handle_t *
1065 zfs_get_pool_handle(const zfs_handle_t *zhp)
1066 {
1067         return (zhp->zpool_hdl);
1068 }
1069
1070 /*
1071  * Given a name, determine whether or not it's a valid path
1072  * (starts with '/' or "./").  If so, walk the mnttab trying
1073  * to match the device number.  If not, treat the path as an
1074  * fs/vol/snap/bkmark name.
1075  */
1076 zfs_handle_t *
1077 zfs_path_to_zhandle(libzfs_handle_t *hdl, char *path, zfs_type_t argtype)
1078 {
1079         struct stat64 statbuf;
1080         struct extmnttab entry;
1081         int ret;
1082
1083         if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1084                 /*
1085                  * It's not a valid path, assume it's a name of type 'argtype'.
1086                  */
1087                 return (zfs_open(hdl, path, argtype));
1088         }
1089
1090         if (stat64(path, &statbuf) != 0) {
1091                 (void) fprintf(stderr, "%s: %s\n", path, strerror(errno));
1092                 return (NULL);
1093         }
1094
1095         /* Reopen MNTTAB to prevent reading stale data from open file */
1096         if (freopen(MNTTAB, "r", hdl->libzfs_mnttab) == NULL)
1097                 return (NULL);
1098
1099         while ((ret = getextmntent(hdl->libzfs_mnttab, &entry, 0)) == 0) {
1100                 if (makedevice(entry.mnt_major, entry.mnt_minor) ==
1101                     statbuf.st_dev) {
1102                         break;
1103                 }
1104         }
1105         if (ret != 0) {
1106                 return (NULL);
1107         }
1108
1109         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1110                 (void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1111                     path);
1112                 return (NULL);
1113         }
1114
1115         return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1116 }
1117
1118 /*
1119  * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1120  * an ioctl().
1121  */
1122 int
1123 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1124 {
1125         if (len == 0)
1126                 len = 16 * 1024;
1127         zc->zc_nvlist_dst_size = len;
1128         zc->zc_nvlist_dst =
1129             (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1130         if (zc->zc_nvlist_dst == 0)
1131                 return (-1);
1132
1133         return (0);
1134 }
1135
1136 /*
1137  * Called when an ioctl() which returns an nvlist fails with ENOMEM.  This will
1138  * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1139  * filled in by the kernel to indicate the actual required size.
1140  */
1141 int
1142 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1143 {
1144         free((void *)(uintptr_t)zc->zc_nvlist_dst);
1145         zc->zc_nvlist_dst =
1146             (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1147         if (zc->zc_nvlist_dst == 0)
1148                 return (-1);
1149
1150         return (0);
1151 }
1152
1153 /*
1154  * Called to free the src and dst nvlists stored in the command structure.
1155  */
1156 void
1157 zcmd_free_nvlists(zfs_cmd_t *zc)
1158 {
1159         free((void *)(uintptr_t)zc->zc_nvlist_conf);
1160         free((void *)(uintptr_t)zc->zc_nvlist_src);
1161         free((void *)(uintptr_t)zc->zc_nvlist_dst);
1162         zc->zc_nvlist_conf = 0;
1163         zc->zc_nvlist_src = 0;
1164         zc->zc_nvlist_dst = 0;
1165 }
1166
1167 static int
1168 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1169     nvlist_t *nvl)
1170 {
1171         char *packed;
1172         size_t len;
1173
1174         verify(nvlist_size(nvl, &len, NV_ENCODE_NATIVE) == 0);
1175
1176         if ((packed = zfs_alloc(hdl, len)) == NULL)
1177                 return (-1);
1178
1179         verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1180
1181         *outnv = (uint64_t)(uintptr_t)packed;
1182         *outlen = len;
1183
1184         return (0);
1185 }
1186
1187 int
1188 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1189 {
1190         return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1191             &zc->zc_nvlist_conf_size, nvl));
1192 }
1193
1194 int
1195 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1196 {
1197         return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1198             &zc->zc_nvlist_src_size, nvl));
1199 }
1200
1201 /*
1202  * Unpacks an nvlist from the ZFS ioctl command structure.
1203  */
1204 int
1205 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1206 {
1207         if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1208             zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1209                 return (no_memory(hdl));
1210
1211         return (0);
1212 }
1213
1214 int
1215 zfs_ioctl(libzfs_handle_t *hdl, int request, zfs_cmd_t *zc)
1216 {
1217         return (ioctl(hdl->libzfs_fd, request, zc));
1218 }
1219
1220 /*
1221  * ================================================================
1222  * API shared by zfs and zpool property management
1223  * ================================================================
1224  */
1225
1226 static void
1227 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1228 {
1229         zprop_list_t *pl = cbp->cb_proplist;
1230         int i;
1231         char *title;
1232         size_t len;
1233
1234         cbp->cb_first = B_FALSE;
1235         if (cbp->cb_scripted)
1236                 return;
1237
1238         /*
1239          * Start with the length of the column headers.
1240          */
1241         cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1242         cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1243             "PROPERTY"));
1244         cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1245             "VALUE"));
1246         cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1247             "RECEIVED"));
1248         cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1249             "SOURCE"));
1250
1251         /* first property is always NAME */
1252         assert(cbp->cb_proplist->pl_prop ==
1253             ((type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME : ZFS_PROP_NAME));
1254
1255         /*
1256          * Go through and calculate the widths for each column.  For the
1257          * 'source' column, we kludge it up by taking the worst-case scenario of
1258          * inheriting from the longest name.  This is acceptable because in the
1259          * majority of cases 'SOURCE' is the last column displayed, and we don't
1260          * use the width anyway.  Note that the 'VALUE' column can be oversized,
1261          * if the name of the property is much longer than any values we find.
1262          */
1263         for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1264                 /*
1265                  * 'PROPERTY' column
1266                  */
1267                 if (pl->pl_prop != ZPROP_INVAL) {
1268                         const char *propname = (type == ZFS_TYPE_POOL) ?
1269                             zpool_prop_to_name(pl->pl_prop) :
1270                             zfs_prop_to_name(pl->pl_prop);
1271
1272                         len = strlen(propname);
1273                         if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1274                                 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1275                 } else {
1276                         len = strlen(pl->pl_user_prop);
1277                         if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1278                                 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1279                 }
1280
1281                 /*
1282                  * 'VALUE' column.  The first property is always the 'name'
1283                  * property that was tacked on either by /sbin/zfs's
1284                  * zfs_do_get() or when calling zprop_expand_list(), so we
1285                  * ignore its width.  If the user specified the name property
1286                  * to display, then it will be later in the list in any case.
1287                  */
1288                 if (pl != cbp->cb_proplist &&
1289                     pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1290                         cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1291
1292                 /* 'RECEIVED' column. */
1293                 if (pl != cbp->cb_proplist &&
1294                     pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1295                         cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1296
1297                 /*
1298                  * 'NAME' and 'SOURCE' columns
1299                  */
1300                 if (pl->pl_prop == (type == ZFS_TYPE_POOL ? ZPOOL_PROP_NAME :
1301                     ZFS_PROP_NAME) &&
1302                     pl->pl_width > cbp->cb_colwidths[GET_COL_NAME]) {
1303                         cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1304                         cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1305                             strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1306                 }
1307         }
1308
1309         /*
1310          * Now go through and print the headers.
1311          */
1312         for (i = 0; i < ZFS_GET_NCOLS; i++) {
1313                 switch (cbp->cb_columns[i]) {
1314                 case GET_COL_NAME:
1315                         title = dgettext(TEXT_DOMAIN, "NAME");
1316                         break;
1317                 case GET_COL_PROPERTY:
1318                         title = dgettext(TEXT_DOMAIN, "PROPERTY");
1319                         break;
1320                 case GET_COL_VALUE:
1321                         title = dgettext(TEXT_DOMAIN, "VALUE");
1322                         break;
1323                 case GET_COL_RECVD:
1324                         title = dgettext(TEXT_DOMAIN, "RECEIVED");
1325                         break;
1326                 case GET_COL_SOURCE:
1327                         title = dgettext(TEXT_DOMAIN, "SOURCE");
1328                         break;
1329                 default:
1330                         title = NULL;
1331                 }
1332
1333                 if (title != NULL) {
1334                         if (i == (ZFS_GET_NCOLS - 1) ||
1335                             cbp->cb_columns[i + 1] == GET_COL_NONE)
1336                                 (void) printf("%s", title);
1337                         else
1338                                 (void) printf("%-*s  ",
1339                                     cbp->cb_colwidths[cbp->cb_columns[i]],
1340                                     title);
1341                 }
1342         }
1343         (void) printf("\n");
1344 }
1345
1346 /*
1347  * Display a single line of output, according to the settings in the callback
1348  * structure.
1349  */
1350 void
1351 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1352     const char *propname, const char *value, zprop_source_t sourcetype,
1353     const char *source, const char *recvd_value)
1354 {
1355         int i;
1356         const char *str = NULL;
1357         char buf[128];
1358
1359         /*
1360          * Ignore those source types that the user has chosen to ignore.
1361          */
1362         if ((sourcetype & cbp->cb_sources) == 0)
1363                 return;
1364
1365         if (cbp->cb_first)
1366                 zprop_print_headers(cbp, cbp->cb_type);
1367
1368         for (i = 0; i < ZFS_GET_NCOLS; i++) {
1369                 switch (cbp->cb_columns[i]) {
1370                 case GET_COL_NAME:
1371                         str = name;
1372                         break;
1373
1374                 case GET_COL_PROPERTY:
1375                         str = propname;
1376                         break;
1377
1378                 case GET_COL_VALUE:
1379                         str = value;
1380                         break;
1381
1382                 case GET_COL_SOURCE:
1383                         switch (sourcetype) {
1384                         case ZPROP_SRC_NONE:
1385                                 str = "-";
1386                                 break;
1387
1388                         case ZPROP_SRC_DEFAULT:
1389                                 str = "default";
1390                                 break;
1391
1392                         case ZPROP_SRC_LOCAL:
1393                                 str = "local";
1394                                 break;
1395
1396                         case ZPROP_SRC_TEMPORARY:
1397                                 str = "temporary";
1398                                 break;
1399
1400                         case ZPROP_SRC_INHERITED:
1401                                 (void) snprintf(buf, sizeof (buf),
1402                                     "inherited from %s", source);
1403                                 str = buf;
1404                                 break;
1405                         case ZPROP_SRC_RECEIVED:
1406                                 str = "received";
1407                                 break;
1408
1409                         default:
1410                                 str = NULL;
1411                                 assert(!"unhandled zprop_source_t");
1412                         }
1413                         break;
1414
1415                 case GET_COL_RECVD:
1416                         str = (recvd_value == NULL ? "-" : recvd_value);
1417                         break;
1418
1419                 default:
1420                         continue;
1421                 }
1422
1423                 if (i == (ZFS_GET_NCOLS - 1) ||
1424                     cbp->cb_columns[i + 1] == GET_COL_NONE)
1425                         (void) printf("%s", str);
1426                 else if (cbp->cb_scripted)
1427                         (void) printf("%s\t", str);
1428                 else
1429                         (void) printf("%-*s  ",
1430                             cbp->cb_colwidths[cbp->cb_columns[i]],
1431                             str);
1432         }
1433
1434         (void) printf("\n");
1435 }
1436
1437 /*
1438  * Given a numeric suffix, convert the value into a number of bits that the
1439  * resulting value must be shifted.
1440  */
1441 static int
1442 str2shift(libzfs_handle_t *hdl, const char *buf)
1443 {
1444         const char *ends = "BKMGTPEZ";
1445         int i;
1446
1447         if (buf[0] == '\0')
1448                 return (0);
1449         for (i = 0; i < strlen(ends); i++) {
1450                 if (toupper(buf[0]) == ends[i])
1451                         break;
1452         }
1453         if (i == strlen(ends)) {
1454                 if (hdl)
1455                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1456                             "invalid numeric suffix '%s'"), buf);
1457                 return (-1);
1458         }
1459
1460         /*
1461          * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1462          * However, 'BB' and 'BiB' are disallowed.
1463          */
1464         if (buf[1] == '\0' ||
1465             (toupper(buf[0]) != 'B' &&
1466             ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1467             (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1468             buf[3] == '\0'))))
1469                 return (10 * i);
1470
1471         if (hdl)
1472                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1473                     "invalid numeric suffix '%s'"), buf);
1474         return (-1);
1475 }
1476
1477 /*
1478  * Convert a string of the form '100G' into a real number.  Used when setting
1479  * properties or creating a volume.  'buf' is used to place an extended error
1480  * message for the caller to use.
1481  */
1482 int
1483 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1484 {
1485         char *end;
1486         int shift;
1487
1488         *num = 0;
1489
1490         /* Check to see if this looks like a number.  */
1491         if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1492                 if (hdl)
1493                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1494                             "bad numeric value '%s'"), value);
1495                 return (-1);
1496         }
1497
1498         /* Rely on strtoull() to process the numeric portion.  */
1499         errno = 0;
1500         *num = strtoull(value, &end, 10);
1501
1502         /*
1503          * Check for ERANGE, which indicates that the value is too large to fit
1504          * in a 64-bit value.
1505          */
1506         if (errno == ERANGE) {
1507                 if (hdl)
1508                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1509                             "numeric value is too large"));
1510                 return (-1);
1511         }
1512
1513         /*
1514          * If we have a decimal value, then do the computation with floating
1515          * point arithmetic.  Otherwise, use standard arithmetic.
1516          */
1517         if (*end == '.') {
1518                 double fval = strtod(value, &end);
1519
1520                 if ((shift = str2shift(hdl, end)) == -1)
1521                         return (-1);
1522
1523                 fval *= pow(2, shift);
1524
1525                 if (fval > UINT64_MAX) {
1526                         if (hdl)
1527                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1528                                     "numeric value is too large"));
1529                         return (-1);
1530                 }
1531
1532                 *num = (uint64_t)fval;
1533         } else {
1534                 if ((shift = str2shift(hdl, end)) == -1)
1535                         return (-1);
1536
1537                 /* Check for overflow */
1538                 if (shift >= 64 || (*num << shift) >> shift != *num) {
1539                         if (hdl)
1540                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1541                                     "numeric value is too large"));
1542                         return (-1);
1543                 }
1544
1545                 *num <<= shift;
1546         }
1547
1548         return (0);
1549 }
1550
1551 /*
1552  * Given a propname=value nvpair to set, parse any numeric properties
1553  * (index, boolean, etc) if they are specified as strings and add the
1554  * resulting nvpair to the returned nvlist.
1555  *
1556  * At the DSL layer, all properties are either 64-bit numbers or strings.
1557  * We want the user to be able to ignore this fact and specify properties
1558  * as native values (numbers, for example) or as strings (to simplify
1559  * command line utilities).  This also handles converting index types
1560  * (compression, checksum, etc) from strings to their on-disk index.
1561  */
1562 int
1563 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1564     zfs_type_t type, nvlist_t *ret, char **svalp, uint64_t *ivalp,
1565     const char *errbuf)
1566 {
1567         data_type_t datatype = nvpair_type(elem);
1568         zprop_type_t proptype;
1569         const char *propname;
1570         char *value;
1571         boolean_t isnone = B_FALSE;
1572         boolean_t isauto = B_FALSE;
1573         int err = 0;
1574
1575         if (type == ZFS_TYPE_POOL) {
1576                 proptype = zpool_prop_get_type(prop);
1577                 propname = zpool_prop_to_name(prop);
1578         } else {
1579                 proptype = zfs_prop_get_type(prop);
1580                 propname = zfs_prop_to_name(prop);
1581         }
1582
1583         /*
1584          * Convert any properties to the internal DSL value types.
1585          */
1586         *svalp = NULL;
1587         *ivalp = 0;
1588
1589         switch (proptype) {
1590         case PROP_TYPE_STRING:
1591                 if (datatype != DATA_TYPE_STRING) {
1592                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1593                             "'%s' must be a string"), nvpair_name(elem));
1594                         goto error;
1595                 }
1596                 err = nvpair_value_string(elem, svalp);
1597                 if (err != 0) {
1598                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1599                             "'%s' is invalid"), nvpair_name(elem));
1600                         goto error;
1601                 }
1602                 if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1603                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1604                             "'%s' is too long"), nvpair_name(elem));
1605                         goto error;
1606                 }
1607                 break;
1608
1609         case PROP_TYPE_NUMBER:
1610                 if (datatype == DATA_TYPE_STRING) {
1611                         (void) nvpair_value_string(elem, &value);
1612                         if (strcmp(value, "none") == 0) {
1613                                 isnone = B_TRUE;
1614                         } else if (strcmp(value, "auto") == 0) {
1615                                 isauto = B_TRUE;
1616                         } else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1617                                 goto error;
1618                         }
1619                 } else if (datatype == DATA_TYPE_UINT64) {
1620                         (void) nvpair_value_uint64(elem, ivalp);
1621                 } else {
1622                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1623                             "'%s' must be a number"), nvpair_name(elem));
1624                         goto error;
1625                 }
1626
1627                 /*
1628                  * Quota special: force 'none' and don't allow 0.
1629                  */
1630                 if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1631                     (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1632                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1633                             "use 'none' to disable quota/refquota"));
1634                         goto error;
1635                 }
1636
1637                 /*
1638                  * Special handling for "*_limit=none". In this case it's not
1639                  * 0 but UINT64_MAX.
1640                  */
1641                 if ((type & ZFS_TYPE_DATASET) && isnone &&
1642                     (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1643                     prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1644                         *ivalp = UINT64_MAX;
1645                 }
1646
1647                 /*
1648                  * Special handling for setting 'refreservation' to 'auto'.  Use
1649                  * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1650                  * 'auto' is only allowed on volumes.
1651                  */
1652                 if (isauto) {
1653                         switch (prop) {
1654                         case ZFS_PROP_REFRESERVATION:
1655                                 if ((type & ZFS_TYPE_VOLUME) == 0) {
1656                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1657                                             "'%s=auto' only allowed on "
1658                                             "volumes"), nvpair_name(elem));
1659                                         goto error;
1660                                 }
1661                                 *ivalp = UINT64_MAX;
1662                                 break;
1663                         default:
1664                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1665                                     "'auto' is invalid value for '%s'"),
1666                                     nvpair_name(elem));
1667                                 goto error;
1668                         }
1669                 }
1670
1671                 break;
1672
1673         case PROP_TYPE_INDEX:
1674                 if (datatype != DATA_TYPE_STRING) {
1675                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1676                             "'%s' must be a string"), nvpair_name(elem));
1677                         goto error;
1678                 }
1679
1680                 (void) nvpair_value_string(elem, &value);
1681
1682                 if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1683                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1684                             "'%s' must be one of '%s'"), propname,
1685                             zprop_values(prop, type));
1686                         goto error;
1687                 }
1688                 break;
1689
1690         default:
1691                 abort();
1692         }
1693
1694         /*
1695          * Add the result to our return set of properties.
1696          */
1697         if (*svalp != NULL) {
1698                 if (nvlist_add_string(ret, propname, *svalp) != 0) {
1699                         (void) no_memory(hdl);
1700                         return (-1);
1701                 }
1702         } else {
1703                 if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1704                         (void) no_memory(hdl);
1705                         return (-1);
1706                 }
1707         }
1708
1709         return (0);
1710 error:
1711         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1712         return (-1);
1713 }
1714
1715 static int
1716 addlist(libzfs_handle_t *hdl, char *propname, zprop_list_t **listp,
1717     zfs_type_t type)
1718 {
1719         int prop;
1720         zprop_list_t *entry;
1721
1722         prop = zprop_name_to_prop(propname, type);
1723
1724         if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
1725                 prop = ZPROP_INVAL;
1726
1727         /*
1728          * When no property table entry can be found, return failure if
1729          * this is a pool property or if this isn't a user-defined
1730          * dataset property,
1731          */
1732         if (prop == ZPROP_INVAL && ((type == ZFS_TYPE_POOL &&
1733             !zpool_prop_feature(propname) &&
1734             !zpool_prop_unsupported(propname)) ||
1735             (type == ZFS_TYPE_DATASET && !zfs_prop_user(propname) &&
1736             !zfs_prop_userquota(propname) && !zfs_prop_written(propname)))) {
1737                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1738                     "invalid property '%s'"), propname);
1739                 return (zfs_error(hdl, EZFS_BADPROP,
1740                     dgettext(TEXT_DOMAIN, "bad property list")));
1741         }
1742
1743         if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1744                 return (-1);
1745
1746         entry->pl_prop = prop;
1747         if (prop == ZPROP_INVAL) {
1748                 if ((entry->pl_user_prop = zfs_strdup(hdl, propname)) ==
1749                     NULL) {
1750                         free(entry);
1751                         return (-1);
1752                 }
1753                 entry->pl_width = strlen(propname);
1754         } else {
1755                 entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1756                     type);
1757         }
1758
1759         *listp = entry;
1760
1761         return (0);
1762 }
1763
1764 /*
1765  * Given a comma-separated list of properties, construct a property list
1766  * containing both user-defined and native properties.  This function will
1767  * return a NULL list if 'all' is specified, which can later be expanded
1768  * by zprop_expand_list().
1769  */
1770 int
1771 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1772     zfs_type_t type)
1773 {
1774         *listp = NULL;
1775
1776         /*
1777          * If 'all' is specified, return a NULL list.
1778          */
1779         if (strcmp(props, "all") == 0)
1780                 return (0);
1781
1782         /*
1783          * If no props were specified, return an error.
1784          */
1785         if (props[0] == '\0') {
1786                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1787                     "no properties specified"));
1788                 return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1789                     "bad property list")));
1790         }
1791
1792         /*
1793          * It would be nice to use getsubopt() here, but the inclusion of column
1794          * aliases makes this more effort than it's worth.
1795          */
1796         while (*props != '\0') {
1797                 size_t len;
1798                 char *p;
1799                 char c;
1800
1801                 if ((p = strchr(props, ',')) == NULL) {
1802                         len = strlen(props);
1803                         p = props + len;
1804                 } else {
1805                         len = p - props;
1806                 }
1807
1808                 /*
1809                  * Check for empty options.
1810                  */
1811                 if (len == 0) {
1812                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1813                             "empty property name"));
1814                         return (zfs_error(hdl, EZFS_BADPROP,
1815                             dgettext(TEXT_DOMAIN, "bad property list")));
1816                 }
1817
1818                 /*
1819                  * Check all regular property names.
1820                  */
1821                 c = props[len];
1822                 props[len] = '\0';
1823
1824                 if (strcmp(props, "space") == 0) {
1825                         static char *spaceprops[] = {
1826                                 "name", "avail", "used", "usedbysnapshots",
1827                                 "usedbydataset", "usedbyrefreservation",
1828                                 "usedbychildren", NULL
1829                         };
1830                         int i;
1831
1832                         for (i = 0; spaceprops[i]; i++) {
1833                                 if (addlist(hdl, spaceprops[i], listp, type))
1834                                         return (-1);
1835                                 listp = &(*listp)->pl_next;
1836                         }
1837                 } else {
1838                         if (addlist(hdl, props, listp, type))
1839                                 return (-1);
1840                         listp = &(*listp)->pl_next;
1841                 }
1842
1843                 props = p;
1844                 if (c == ',')
1845                         props++;
1846         }
1847
1848         return (0);
1849 }
1850
1851 void
1852 zprop_free_list(zprop_list_t *pl)
1853 {
1854         zprop_list_t *next;
1855
1856         while (pl != NULL) {
1857                 next = pl->pl_next;
1858                 free(pl->pl_user_prop);
1859                 free(pl);
1860                 pl = next;
1861         }
1862 }
1863
1864 typedef struct expand_data {
1865         zprop_list_t    **last;
1866         libzfs_handle_t *hdl;
1867         zfs_type_t type;
1868 } expand_data_t;
1869
1870 int
1871 zprop_expand_list_cb(int prop, void *cb)
1872 {
1873         zprop_list_t *entry;
1874         expand_data_t *edp = cb;
1875
1876         if ((entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t))) == NULL)
1877                 return (ZPROP_INVAL);
1878
1879         entry->pl_prop = prop;
1880         entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
1881         entry->pl_all = B_TRUE;
1882
1883         *(edp->last) = entry;
1884         edp->last = &entry->pl_next;
1885
1886         return (ZPROP_CONT);
1887 }
1888
1889 int
1890 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
1891 {
1892         zprop_list_t *entry;
1893         zprop_list_t **last;
1894         expand_data_t exp;
1895
1896         if (*plp == NULL) {
1897                 /*
1898                  * If this is the very first time we've been called for an 'all'
1899                  * specification, expand the list to include all native
1900                  * properties.
1901                  */
1902                 last = plp;
1903
1904                 exp.last = last;
1905                 exp.hdl = hdl;
1906                 exp.type = type;
1907
1908                 if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
1909                     B_FALSE, type) == ZPROP_INVAL)
1910                         return (-1);
1911
1912                 /*
1913                  * Add 'name' to the beginning of the list, which is handled
1914                  * specially.
1915                  */
1916                 if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1917                         return (-1);
1918
1919                 entry->pl_prop = (type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME :
1920                     ZFS_PROP_NAME;
1921                 entry->pl_width = zprop_width(entry->pl_prop,
1922                     &entry->pl_fixed, type);
1923                 entry->pl_all = B_TRUE;
1924                 entry->pl_next = *plp;
1925                 *plp = entry;
1926         }
1927         return (0);
1928 }
1929
1930 int
1931 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
1932     zfs_type_t type)
1933 {
1934         return (zprop_iter_common(func, cb, show_all, ordered, type));
1935 }