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