]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - cmd/zpool/zpool_main.c
Invalidate cache during a zpool labelclear
[FreeBSD/FreeBSD.git] / cmd / zpool / zpool_main.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 2011 Nexenta Systems, Inc. All rights reserved.
25  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
26  * Copyright (c) 2012 by Frederik Wessels. All rights reserved.
27  * Copyright (c) 2012 by Cyril Plisko. All rights reserved.
28  * Copyright (c) 2013 by Prasad Joshi (sTec). All rights reserved.
29  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
30  */
31
32 #include <assert.h>
33 #include <ctype.h>
34 #include <dirent.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <libgen.h>
38 #include <libintl.h>
39 #include <libuutil.h>
40 #include <locale.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <strings.h>
45 #include <unistd.h>
46 #include <pwd.h>
47 #include <zone.h>
48 #include <zfs_prop.h>
49 #include <sys/fs/zfs.h>
50 #include <sys/stat.h>
51 #include <sys/fm/fs/zfs.h>
52 #include <sys/fm/util.h>
53 #include <sys/fm/protocol.h>
54 #include <sys/zfs_ioctl.h>
55 #include <math.h>
56
57 #include <libzfs.h>
58
59 #include "zpool_util.h"
60 #include "zfs_comutil.h"
61 #include "zfeature_common.h"
62
63 #include "statcommon.h"
64
65 static int zpool_do_create(int, char **);
66 static int zpool_do_destroy(int, char **);
67
68 static int zpool_do_add(int, char **);
69 static int zpool_do_remove(int, char **);
70 static int zpool_do_labelclear(int, char **);
71
72 static int zpool_do_list(int, char **);
73 static int zpool_do_iostat(int, char **);
74 static int zpool_do_status(int, char **);
75
76 static int zpool_do_online(int, char **);
77 static int zpool_do_offline(int, char **);
78 static int zpool_do_clear(int, char **);
79 static int zpool_do_reopen(int, char **);
80
81 static int zpool_do_reguid(int, char **);
82
83 static int zpool_do_attach(int, char **);
84 static int zpool_do_detach(int, char **);
85 static int zpool_do_replace(int, char **);
86 static int zpool_do_split(int, char **);
87
88 static int zpool_do_scrub(int, char **);
89
90 static int zpool_do_import(int, char **);
91 static int zpool_do_export(int, char **);
92
93 static int zpool_do_upgrade(int, char **);
94
95 static int zpool_do_history(int, char **);
96 static int zpool_do_events(int, char **);
97
98 static int zpool_do_get(int, char **);
99 static int zpool_do_set(int, char **);
100
101 /*
102  * These libumem hooks provide a reasonable set of defaults for the allocator's
103  * debugging facilities.
104  */
105
106 #ifdef DEBUG
107 const char *
108 _umem_debug_init(void)
109 {
110         return ("default,verbose"); /* $UMEM_DEBUG setting */
111 }
112
113 const char *
114 _umem_logging_init(void)
115 {
116         return ("fail,contents"); /* $UMEM_LOGGING setting */
117 }
118 #endif
119
120 typedef enum {
121         HELP_ADD,
122         HELP_ATTACH,
123         HELP_CLEAR,
124         HELP_CREATE,
125         HELP_DESTROY,
126         HELP_DETACH,
127         HELP_EXPORT,
128         HELP_HISTORY,
129         HELP_IMPORT,
130         HELP_IOSTAT,
131         HELP_LABELCLEAR,
132         HELP_LIST,
133         HELP_OFFLINE,
134         HELP_ONLINE,
135         HELP_REPLACE,
136         HELP_REMOVE,
137         HELP_SCRUB,
138         HELP_STATUS,
139         HELP_UPGRADE,
140         HELP_EVENTS,
141         HELP_GET,
142         HELP_SET,
143         HELP_SPLIT,
144         HELP_REGUID,
145         HELP_REOPEN
146 } zpool_help_t;
147
148
149 /*
150  * Flags for stats to display with "zpool iostats"
151  */
152 enum iostat_type {
153         IOS_DEFAULT = 0,
154         IOS_LATENCY = 1,
155         IOS_QUEUES = 2,
156         IOS_L_HISTO = 3,
157         IOS_RQ_HISTO = 4,
158         IOS_COUNT,      /* always last element */
159 };
160
161 /* iostat_type entries as bitmasks */
162 #define IOS_DEFAULT_M   (1ULL << IOS_DEFAULT)
163 #define IOS_LATENCY_M   (1ULL << IOS_LATENCY)
164 #define IOS_QUEUES_M    (1ULL << IOS_QUEUES)
165 #define IOS_L_HISTO_M   (1ULL << IOS_L_HISTO)
166 #define IOS_RQ_HISTO_M  (1ULL << IOS_RQ_HISTO)
167
168 /* Mask of all the histo bits */
169 #define IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
170
171 /*
172  * Lookup table for iostat flags to nvlist names.  Basically a list
173  * of all the nvlists a flag requires.  Also specifies the order in
174  * which data gets printed in zpool iostat.
175  */
176 static const char *vsx_type_to_nvlist[IOS_COUNT][11] = {
177         [IOS_L_HISTO] = {
178             ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
179             ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
180             ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
181             ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
182             ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
183             ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
184             ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
185             ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
186             ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
187             NULL},
188         [IOS_LATENCY] = {
189             ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
190             ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
191             ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
192             ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
193             NULL},
194         [IOS_QUEUES] = {
195             ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
196             ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
197             ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
198             ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
199             ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
200             NULL},
201         [IOS_RQ_HISTO] = {
202             ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
203             ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
204             ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
205             ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
206             ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
207             ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
208             ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
209             ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
210             ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
211             ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
212             NULL},
213 };
214
215
216 /*
217  * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
218  * Right now, only one histo bit is ever set at one time, so we can
219  * just do a highbit64(a)
220  */
221 #define IOS_HISTO_IDX(a)        (highbit64(a & IOS_ANYHISTO_M) - 1)
222
223 typedef struct zpool_command {
224         const char      *name;
225         int             (*func)(int, char **);
226         zpool_help_t    usage;
227 } zpool_command_t;
228
229 /*
230  * Master command table.  Each ZFS command has a name, associated function, and
231  * usage message.  The usage messages need to be internationalized, so we have
232  * to have a function to return the usage message based on a command index.
233  *
234  * These commands are organized according to how they are displayed in the usage
235  * message.  An empty command (one with a NULL name) indicates an empty line in
236  * the generic usage message.
237  */
238 static zpool_command_t command_table[] = {
239         { "create",     zpool_do_create,        HELP_CREATE             },
240         { "destroy",    zpool_do_destroy,       HELP_DESTROY            },
241         { NULL },
242         { "add",        zpool_do_add,           HELP_ADD                },
243         { "remove",     zpool_do_remove,        HELP_REMOVE             },
244         { NULL },
245         { "labelclear", zpool_do_labelclear,    HELP_LABELCLEAR         },
246         { NULL },
247         { "list",       zpool_do_list,          HELP_LIST               },
248         { "iostat",     zpool_do_iostat,        HELP_IOSTAT             },
249         { "status",     zpool_do_status,        HELP_STATUS             },
250         { NULL },
251         { "online",     zpool_do_online,        HELP_ONLINE             },
252         { "offline",    zpool_do_offline,       HELP_OFFLINE            },
253         { "clear",      zpool_do_clear,         HELP_CLEAR              },
254         { "reopen",     zpool_do_reopen,        HELP_REOPEN             },
255         { NULL },
256         { "attach",     zpool_do_attach,        HELP_ATTACH             },
257         { "detach",     zpool_do_detach,        HELP_DETACH             },
258         { "replace",    zpool_do_replace,       HELP_REPLACE            },
259         { "split",      zpool_do_split,         HELP_SPLIT              },
260         { NULL },
261         { "scrub",      zpool_do_scrub,         HELP_SCRUB              },
262         { NULL },
263         { "import",     zpool_do_import,        HELP_IMPORT             },
264         { "export",     zpool_do_export,        HELP_EXPORT             },
265         { "upgrade",    zpool_do_upgrade,       HELP_UPGRADE            },
266         { "reguid",     zpool_do_reguid,        HELP_REGUID             },
267         { NULL },
268         { "history",    zpool_do_history,       HELP_HISTORY            },
269         { "events",     zpool_do_events,        HELP_EVENTS             },
270         { NULL },
271         { "get",        zpool_do_get,           HELP_GET                },
272         { "set",        zpool_do_set,           HELP_SET                },
273 };
274
275 #define NCOMMAND        (ARRAY_SIZE(command_table))
276
277 static zpool_command_t *current_command;
278 static char history_str[HIS_MAX_RECORD_LEN];
279 static boolean_t log_history = B_TRUE;
280 static uint_t timestamp_fmt = NODATE;
281
282 static const char *
283 get_usage(zpool_help_t idx)
284 {
285         switch (idx) {
286         case HELP_ADD:
287                 return (gettext("\tadd [-fgLnP] [-o property=value] "
288                     "<pool> <vdev> ...\n"));
289         case HELP_ATTACH:
290                 return (gettext("\tattach [-f] [-o property=value] "
291                     "<pool> <device> <new-device>\n"));
292         case HELP_CLEAR:
293                 return (gettext("\tclear [-nF] <pool> [device]\n"));
294         case HELP_CREATE:
295                 return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
296                     "\t    [-O file-system-property=value] ... \n"
297                     "\t    [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
298         case HELP_DESTROY:
299                 return (gettext("\tdestroy [-f] <pool>\n"));
300         case HELP_DETACH:
301                 return (gettext("\tdetach <pool> <device>\n"));
302         case HELP_EXPORT:
303                 return (gettext("\texport [-af] <pool> ...\n"));
304         case HELP_HISTORY:
305                 return (gettext("\thistory [-il] [<pool>] ...\n"));
306         case HELP_IMPORT:
307                 return (gettext("\timport [-d dir] [-D]\n"
308                     "\timport [-d dir | -c cachefile] [-F [-n]] <pool | id>\n"
309                     "\timport [-o mntopts] [-o property=value] ... \n"
310                     "\t    [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
311                     "[-R root] [-F [-n]] -a\n"
312                     "\timport [-o mntopts] [-o property=value] ... \n"
313                     "\t    [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
314                     "[-R root] [-F [-n]]\n"
315                     "\t    <pool | id> [newpool]\n"));
316         case HELP_IOSTAT:
317                 return (gettext("\tiostat [-c CMD] [-T d | u] [-ghHLpPvy] "
318                     "[[-lq]|[-r|-w]]\n"
319                     "\t    [[pool ...]|[pool vdev ...]|[vdev ...]] "
320                     "[interval [count]]\n"));
321         case HELP_LABELCLEAR:
322                 return (gettext("\tlabelclear [-f] <vdev>\n"));
323         case HELP_LIST:
324                 return (gettext("\tlist [-gHLpPv] [-o property[,...]] "
325                     "[-T d|u] [pool] ... [interval [count]]\n"));
326         case HELP_OFFLINE:
327                 return (gettext("\toffline [-t] <pool> <device> ...\n"));
328         case HELP_ONLINE:
329                 return (gettext("\tonline <pool> <device> ...\n"));
330         case HELP_REPLACE:
331                 return (gettext("\treplace [-f] [-o property=value] "
332                     "<pool> <device> [new-device]\n"));
333         case HELP_REMOVE:
334                 return (gettext("\tremove <pool> <device> ...\n"));
335         case HELP_REOPEN:
336                 return (gettext("\treopen <pool>\n"));
337         case HELP_SCRUB:
338                 return (gettext("\tscrub [-s] <pool> ...\n"));
339         case HELP_STATUS:
340                 return (gettext("\tstatus [-c CMD] [-gLPvxD] [-T d|u] [pool]"
341                     " ... [interval [count]]\n"));
342         case HELP_UPGRADE:
343                 return (gettext("\tupgrade\n"
344                     "\tupgrade -v\n"
345                     "\tupgrade [-V version] <-a | pool ...>\n"));
346         case HELP_EVENTS:
347                 return (gettext("\tevents [-vHfc]\n"));
348         case HELP_GET:
349                 return (gettext("\tget [-Hp] [-o \"all\" | field[,...]] "
350                     "<\"all\" | property[,...]> <pool> ...\n"));
351         case HELP_SET:
352                 return (gettext("\tset <property=value> <pool> \n"));
353         case HELP_SPLIT:
354                 return (gettext("\tsplit [-gLnP] [-R altroot] [-o mntopts]\n"
355                     "\t    [-o property=value] <pool> <newpool> "
356                     "[<device> ...]\n"));
357         case HELP_REGUID:
358                 return (gettext("\treguid <pool>\n"));
359         }
360
361         abort();
362         /* NOTREACHED */
363 }
364
365
366 /*
367  * Callback routine that will print out a pool property value.
368  */
369 static int
370 print_prop_cb(int prop, void *cb)
371 {
372         FILE *fp = cb;
373
374         (void) fprintf(fp, "\t%-15s  ", zpool_prop_to_name(prop));
375
376         if (zpool_prop_readonly(prop))
377                 (void) fprintf(fp, "  NO   ");
378         else
379                 (void) fprintf(fp, " YES   ");
380
381         if (zpool_prop_values(prop) == NULL)
382                 (void) fprintf(fp, "-\n");
383         else
384                 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
385
386         return (ZPROP_CONT);
387 }
388
389 /*
390  * Display usage message.  If we're inside a command, display only the usage for
391  * that command.  Otherwise, iterate over the entire command table and display
392  * a complete usage message.
393  */
394 void
395 usage(boolean_t requested)
396 {
397         FILE *fp = requested ? stdout : stderr;
398
399         if (current_command == NULL) {
400                 int i;
401
402                 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
403                 (void) fprintf(fp,
404                     gettext("where 'command' is one of the following:\n\n"));
405
406                 for (i = 0; i < NCOMMAND; i++) {
407                         if (command_table[i].name == NULL)
408                                 (void) fprintf(fp, "\n");
409                         else
410                                 (void) fprintf(fp, "%s",
411                                     get_usage(command_table[i].usage));
412                 }
413         } else {
414                 (void) fprintf(fp, gettext("usage:\n"));
415                 (void) fprintf(fp, "%s", get_usage(current_command->usage));
416         }
417
418         if (current_command != NULL &&
419             ((strcmp(current_command->name, "set") == 0) ||
420             (strcmp(current_command->name, "get") == 0) ||
421             (strcmp(current_command->name, "list") == 0))) {
422
423                 (void) fprintf(fp,
424                     gettext("\nthe following properties are supported:\n"));
425
426                 (void) fprintf(fp, "\n\t%-15s  %s   %s\n\n",
427                     "PROPERTY", "EDIT", "VALUES");
428
429                 /* Iterate over all properties */
430                 (void) zprop_iter(print_prop_cb, fp, B_FALSE, B_TRUE,
431                     ZFS_TYPE_POOL);
432
433                 (void) fprintf(fp, "\t%-15s   ", "feature@...");
434                 (void) fprintf(fp, "YES   disabled | enabled | active\n");
435
436                 (void) fprintf(fp, gettext("\nThe feature@ properties must be "
437                     "appended with a feature name.\nSee zpool-features(5).\n"));
438         }
439
440         /*
441          * See comments at end of main().
442          */
443         if (getenv("ZFS_ABORT") != NULL) {
444                 (void) printf("dumping core by request\n");
445                 abort();
446         }
447
448         exit(requested ? 0 : 2);
449 }
450
451 void
452 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
453     boolean_t print_logs, int name_flags)
454 {
455         nvlist_t **child;
456         uint_t c, children;
457         char *vname;
458
459         if (name != NULL)
460                 (void) printf("\t%*s%s\n", indent, "", name);
461
462         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
463             &child, &children) != 0)
464                 return;
465
466         for (c = 0; c < children; c++) {
467                 uint64_t is_log = B_FALSE;
468
469                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
470                     &is_log);
471                 if ((is_log && !print_logs) || (!is_log && print_logs))
472                         continue;
473
474                 vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
475                 print_vdev_tree(zhp, vname, child[c], indent + 2,
476                     B_FALSE, name_flags);
477                 free(vname);
478         }
479 }
480
481 static boolean_t
482 prop_list_contains_feature(nvlist_t *proplist)
483 {
484         nvpair_t *nvp;
485         for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
486             nvp = nvlist_next_nvpair(proplist, nvp)) {
487                 if (zpool_prop_feature(nvpair_name(nvp)))
488                         return (B_TRUE);
489         }
490         return (B_FALSE);
491 }
492
493 /*
494  * Add a property pair (name, string-value) into a property nvlist.
495  */
496 static int
497 add_prop_list(const char *propname, char *propval, nvlist_t **props,
498     boolean_t poolprop)
499 {
500         zpool_prop_t prop = ZPROP_INVAL;
501         zfs_prop_t fprop;
502         nvlist_t *proplist;
503         const char *normnm;
504         char *strval;
505
506         if (*props == NULL &&
507             nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
508                 (void) fprintf(stderr,
509                     gettext("internal error: out of memory\n"));
510                 return (1);
511         }
512
513         proplist = *props;
514
515         if (poolprop) {
516                 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
517
518                 if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL &&
519                     !zpool_prop_feature(propname)) {
520                         (void) fprintf(stderr, gettext("property '%s' is "
521                             "not a valid pool property\n"), propname);
522                         return (2);
523                 }
524
525                 /*
526                  * feature@ properties and version should not be specified
527                  * at the same time.
528                  */
529                 if ((prop == ZPROP_INVAL && zpool_prop_feature(propname) &&
530                     nvlist_exists(proplist, vname)) ||
531                     (prop == ZPOOL_PROP_VERSION &&
532                     prop_list_contains_feature(proplist))) {
533                         (void) fprintf(stderr, gettext("'feature@' and "
534                             "'version' properties cannot be specified "
535                             "together\n"));
536                         return (2);
537                 }
538
539
540                 if (zpool_prop_feature(propname))
541                         normnm = propname;
542                 else
543                         normnm = zpool_prop_to_name(prop);
544         } else {
545                 if ((fprop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
546                         normnm = zfs_prop_to_name(fprop);
547                 } else {
548                         normnm = propname;
549                 }
550         }
551
552         if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
553             prop != ZPOOL_PROP_CACHEFILE) {
554                 (void) fprintf(stderr, gettext("property '%s' "
555                     "specified multiple times\n"), propname);
556                 return (2);
557         }
558
559         if (nvlist_add_string(proplist, normnm, propval) != 0) {
560                 (void) fprintf(stderr, gettext("internal "
561                     "error: out of memory\n"));
562                 return (1);
563         }
564
565         return (0);
566 }
567
568 /*
569  * Set a default property pair (name, string-value) in a property nvlist
570  */
571 static int
572 add_prop_list_default(const char *propname, char *propval, nvlist_t **props,
573     boolean_t poolprop)
574 {
575         char *pval;
576
577         if (nvlist_lookup_string(*props, propname, &pval) == 0)
578                 return (0);
579
580         return (add_prop_list(propname, propval, props, B_TRUE));
581 }
582
583 /*
584  * zpool add [-fgLnP] [-o property=value] <pool> <vdev> ...
585  *
586  *      -f      Force addition of devices, even if they appear in use
587  *      -g      Display guid for individual vdev name.
588  *      -L      Follow links when resolving vdev path name.
589  *      -n      Do not add the devices, but display the resulting layout if
590  *              they were to be added.
591  *      -o      Set property=value.
592  *      -P      Display full path for vdev name.
593  *
594  * Adds the given vdevs to 'pool'.  As with create, the bulk of this work is
595  * handled by get_vdev_spec(), which constructs the nvlist needed to pass to
596  * libzfs.
597  */
598 int
599 zpool_do_add(int argc, char **argv)
600 {
601         boolean_t force = B_FALSE;
602         boolean_t dryrun = B_FALSE;
603         int name_flags = 0;
604         int c;
605         nvlist_t *nvroot;
606         char *poolname;
607         int ret;
608         zpool_handle_t *zhp;
609         nvlist_t *config;
610         nvlist_t *props = NULL;
611         char *propval;
612
613         /* check options */
614         while ((c = getopt(argc, argv, "fgLno:P")) != -1) {
615                 switch (c) {
616                 case 'f':
617                         force = B_TRUE;
618                         break;
619                 case 'g':
620                         name_flags |= VDEV_NAME_GUID;
621                         break;
622                 case 'L':
623                         name_flags |= VDEV_NAME_FOLLOW_LINKS;
624                         break;
625                 case 'n':
626                         dryrun = B_TRUE;
627                         break;
628                 case 'o':
629                         if ((propval = strchr(optarg, '=')) == NULL) {
630                                 (void) fprintf(stderr, gettext("missing "
631                                     "'=' for -o option\n"));
632                                 usage(B_FALSE);
633                         }
634                         *propval = '\0';
635                         propval++;
636
637                         if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
638                             (add_prop_list(optarg, propval, &props, B_TRUE)))
639                                 usage(B_FALSE);
640                         break;
641                 case 'P':
642                         name_flags |= VDEV_NAME_PATH;
643                         break;
644                 case '?':
645                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
646                             optopt);
647                         usage(B_FALSE);
648                 }
649         }
650
651         argc -= optind;
652         argv += optind;
653
654         /* get pool name and check number of arguments */
655         if (argc < 1) {
656                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
657                 usage(B_FALSE);
658         }
659         if (argc < 2) {
660                 (void) fprintf(stderr, gettext("missing vdev specification\n"));
661                 usage(B_FALSE);
662         }
663
664         poolname = argv[0];
665
666         argc--;
667         argv++;
668
669         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
670                 return (1);
671
672         if ((config = zpool_get_config(zhp, NULL)) == NULL) {
673                 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
674                     poolname);
675                 zpool_close(zhp);
676                 return (1);
677         }
678
679         /* pass off to get_vdev_spec for processing */
680         nvroot = make_root_vdev(zhp, props, force, !force, B_FALSE, dryrun,
681             argc, argv);
682         if (nvroot == NULL) {
683                 zpool_close(zhp);
684                 return (1);
685         }
686
687         if (dryrun) {
688                 nvlist_t *poolnvroot;
689                 nvlist_t **l2child;
690                 uint_t l2children, c;
691                 char *vname;
692                 boolean_t hadcache = B_FALSE;
693
694                 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
695                     &poolnvroot) == 0);
696
697                 (void) printf(gettext("would update '%s' to the following "
698                     "configuration:\n"), zpool_get_name(zhp));
699
700                 /* print original main pool and new tree */
701                 print_vdev_tree(zhp, poolname, poolnvroot, 0, B_FALSE,
702                     name_flags);
703                 print_vdev_tree(zhp, NULL, nvroot, 0, B_FALSE, name_flags);
704
705                 /* Do the same for the logs */
706                 if (num_logs(poolnvroot) > 0) {
707                         print_vdev_tree(zhp, "logs", poolnvroot, 0, B_TRUE,
708                             name_flags);
709                         print_vdev_tree(zhp, NULL, nvroot, 0, B_TRUE,
710                             name_flags);
711                 } else if (num_logs(nvroot) > 0) {
712                         print_vdev_tree(zhp, "logs", nvroot, 0, B_TRUE,
713                             name_flags);
714                 }
715
716                 /* Do the same for the caches */
717                 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
718                     &l2child, &l2children) == 0 && l2children) {
719                         hadcache = B_TRUE;
720                         (void) printf(gettext("\tcache\n"));
721                         for (c = 0; c < l2children; c++) {
722                                 vname = zpool_vdev_name(g_zfs, NULL,
723                                     l2child[c], name_flags);
724                                 (void) printf("\t  %s\n", vname);
725                                 free(vname);
726                         }
727                 }
728                 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
729                     &l2child, &l2children) == 0 && l2children) {
730                         if (!hadcache)
731                                 (void) printf(gettext("\tcache\n"));
732                         for (c = 0; c < l2children; c++) {
733                                 vname = zpool_vdev_name(g_zfs, NULL,
734                                     l2child[c], name_flags);
735                                 (void) printf("\t  %s\n", vname);
736                                 free(vname);
737                         }
738                 }
739
740                 ret = 0;
741         } else {
742                 ret = (zpool_add(zhp, nvroot) != 0);
743         }
744
745         nvlist_free(props);
746         nvlist_free(nvroot);
747         zpool_close(zhp);
748
749         return (ret);
750 }
751
752 /*
753  * zpool remove  <pool> <vdev> ...
754  *
755  * Removes the given vdev from the pool.  Currently, this supports removing
756  * spares, cache, and log devices from the pool.
757  */
758 int
759 zpool_do_remove(int argc, char **argv)
760 {
761         char *poolname;
762         int i, ret = 0;
763         zpool_handle_t *zhp = NULL;
764
765         argc--;
766         argv++;
767
768         /* get pool name and check number of arguments */
769         if (argc < 1) {
770                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
771                 usage(B_FALSE);
772         }
773         if (argc < 2) {
774                 (void) fprintf(stderr, gettext("missing device\n"));
775                 usage(B_FALSE);
776         }
777
778         poolname = argv[0];
779
780         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
781                 return (1);
782
783         for (i = 1; i < argc; i++) {
784                 if (zpool_vdev_remove(zhp, argv[i]) != 0)
785                         ret = 1;
786         }
787         zpool_close(zhp);
788
789         return (ret);
790 }
791
792 /*
793  * zpool labelclear [-f] <vdev>
794  *
795  *      -f      Force clearing the label for the vdevs which are members of
796  *              the exported or foreign pools.
797  *
798  * Verifies that the vdev is not active and zeros out the label information
799  * on the device.
800  */
801 int
802 zpool_do_labelclear(int argc, char **argv)
803 {
804         char vdev[MAXPATHLEN];
805         char *name = NULL;
806         struct stat st;
807         int c, fd = -1, ret = 0;
808         nvlist_t *config;
809         pool_state_t state;
810         boolean_t inuse = B_FALSE;
811         boolean_t force = B_FALSE;
812
813         /* check options */
814         while ((c = getopt(argc, argv, "f")) != -1) {
815                 switch (c) {
816                 case 'f':
817                         force = B_TRUE;
818                         break;
819                 default:
820                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
821                             optopt);
822                         usage(B_FALSE);
823                 }
824         }
825
826         argc -= optind;
827         argv += optind;
828
829         /* get vdev name */
830         if (argc < 1) {
831                 (void) fprintf(stderr, gettext("missing vdev name\n"));
832                 usage(B_FALSE);
833         }
834         if (argc > 1) {
835                 (void) fprintf(stderr, gettext("too many arguments\n"));
836                 usage(B_FALSE);
837         }
838
839         /*
840          * Check if we were given absolute path and use it as is.
841          * Otherwise if the provided vdev name doesn't point to a file,
842          * try prepending expected disk paths and partition numbers.
843          */
844         (void) strlcpy(vdev, argv[0], sizeof (vdev));
845         if (vdev[0] != '/' && stat(vdev, &st) != 0) {
846                 int error;
847
848                 error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
849                 if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
850                         if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
851                                 error = ENOENT;
852                 }
853
854                 if (error || (stat(vdev, &st) != 0)) {
855                         (void) fprintf(stderr, gettext(
856                             "failed to find device %s, try specifying absolute "
857                             "path instead\n"), argv[0]);
858                         return (1);
859                 }
860         }
861
862         if ((fd = open(vdev, O_RDWR)) < 0) {
863                 (void) fprintf(stderr, gettext("failed to open %s: %s\n"),
864                     vdev, strerror(errno));
865                 return (1);
866         }
867
868         if (ioctl(fd, BLKFLSBUF) != 0)
869                 (void) fprintf(stderr, gettext("failed to invalidate "
870                     "cache for %s: %s\n"), vdev, strerror(errno));
871
872         if (zpool_read_label(fd, &config, NULL) != 0 || config == NULL) {
873                 (void) fprintf(stderr,
874                     gettext("failed to check state for %s\n"), vdev);
875                 return (1);
876         }
877         nvlist_free(config);
878
879         ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
880         if (ret != 0) {
881                 (void) fprintf(stderr,
882                     gettext("failed to check state for %s\n"), vdev);
883                 return (1);
884         }
885
886         if (!inuse)
887                 goto wipe_label;
888
889         switch (state) {
890         default:
891         case POOL_STATE_ACTIVE:
892         case POOL_STATE_SPARE:
893         case POOL_STATE_L2CACHE:
894                 (void) fprintf(stderr, gettext(
895                     "%s is a member (%s) of pool \"%s\"\n"),
896                     vdev, zpool_pool_state_to_name(state), name);
897                 ret = 1;
898                 goto errout;
899
900         case POOL_STATE_EXPORTED:
901                 if (force)
902                         break;
903                 (void) fprintf(stderr, gettext(
904                     "use '-f' to override the following error:\n"
905                     "%s is a member of exported pool \"%s\"\n"),
906                     vdev, name);
907                 ret = 1;
908                 goto errout;
909
910         case POOL_STATE_POTENTIALLY_ACTIVE:
911                 if (force)
912                         break;
913                 (void) fprintf(stderr, gettext(
914                     "use '-f' to override the following error:\n"
915                     "%s is a member of potentially active pool \"%s\"\n"),
916                     vdev, name);
917                 ret = 1;
918                 goto errout;
919
920         case POOL_STATE_DESTROYED:
921                 /* inuse should never be set for a destroyed pool */
922                 assert(0);
923                 break;
924         }
925
926 wipe_label:
927         ret = zpool_clear_label(fd);
928         if (ret != 0) {
929                 (void) fprintf(stderr,
930                     gettext("failed to clear label for %s\n"), vdev);
931         }
932
933 errout:
934         free(name);
935         (void) close(fd);
936
937         return (ret);
938 }
939
940 /*
941  * zpool create [-fnd] [-o property=value] ...
942  *              [-O file-system-property=value] ...
943  *              [-R root] [-m mountpoint] <pool> <dev> ...
944  *
945  *      -f      Force creation, even if devices appear in use
946  *      -n      Do not create the pool, but display the resulting layout if it
947  *              were to be created.
948  *      -R      Create a pool under an alternate root
949  *      -m      Set default mountpoint for the root dataset.  By default it's
950  *              '/<pool>'
951  *      -o      Set property=value.
952  *      -o      Set feature@feature=enabled|disabled.
953  *      -d      Don't automatically enable all supported pool features
954  *              (individual features can be enabled with -o).
955  *      -O      Set fsproperty=value in the pool's root file system
956  *
957  * Creates the named pool according to the given vdev specification.  The
958  * bulk of the vdev processing is done in get_vdev_spec() in zpool_vdev.c.  Once
959  * we get the nvlist back from get_vdev_spec(), we either print out the contents
960  * (if '-n' was specified), or pass it to libzfs to do the creation.
961  */
962 int
963 zpool_do_create(int argc, char **argv)
964 {
965         boolean_t force = B_FALSE;
966         boolean_t dryrun = B_FALSE;
967         boolean_t enable_all_pool_feat = B_TRUE;
968         int c;
969         nvlist_t *nvroot = NULL;
970         char *poolname;
971         char *tname = NULL;
972         int ret = 1;
973         char *altroot = NULL;
974         char *mountpoint = NULL;
975         nvlist_t *fsprops = NULL;
976         nvlist_t *props = NULL;
977         char *propval;
978
979         /* check options */
980         while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
981                 switch (c) {
982                 case 'f':
983                         force = B_TRUE;
984                         break;
985                 case 'n':
986                         dryrun = B_TRUE;
987                         break;
988                 case 'd':
989                         enable_all_pool_feat = B_FALSE;
990                         break;
991                 case 'R':
992                         altroot = optarg;
993                         if (add_prop_list(zpool_prop_to_name(
994                             ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
995                                 goto errout;
996                         if (add_prop_list_default(zpool_prop_to_name(
997                             ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
998                                 goto errout;
999                         break;
1000                 case 'm':
1001                         /* Equivalent to -O mountpoint=optarg */
1002                         mountpoint = optarg;
1003                         break;
1004                 case 'o':
1005                         if ((propval = strchr(optarg, '=')) == NULL) {
1006                                 (void) fprintf(stderr, gettext("missing "
1007                                     "'=' for -o option\n"));
1008                                 goto errout;
1009                         }
1010                         *propval = '\0';
1011                         propval++;
1012
1013                         if (add_prop_list(optarg, propval, &props, B_TRUE))
1014                                 goto errout;
1015
1016                         /*
1017                          * If the user is creating a pool that doesn't support
1018                          * feature flags, don't enable any features.
1019                          */
1020                         if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
1021                                 char *end;
1022                                 u_longlong_t ver;
1023
1024                                 ver = strtoull(propval, &end, 10);
1025                                 if (*end == '\0' &&
1026                                     ver < SPA_VERSION_FEATURES) {
1027                                         enable_all_pool_feat = B_FALSE;
1028                                 }
1029                         }
1030                         if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
1031                                 altroot = propval;
1032                         break;
1033                 case 'O':
1034                         if ((propval = strchr(optarg, '=')) == NULL) {
1035                                 (void) fprintf(stderr, gettext("missing "
1036                                     "'=' for -O option\n"));
1037                                 goto errout;
1038                         }
1039                         *propval = '\0';
1040                         propval++;
1041
1042                         /*
1043                          * Mountpoints are checked and then added later.
1044                          * Uniquely among properties, they can be specified
1045                          * more than once, to avoid conflict with -m.
1046                          */
1047                         if (0 == strcmp(optarg,
1048                             zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
1049                                 mountpoint = propval;
1050                         } else if (add_prop_list(optarg, propval, &fsprops,
1051                             B_FALSE)) {
1052                                 goto errout;
1053                         }
1054                         break;
1055                 case 't':
1056                         /*
1057                          * Sanity check temporary pool name.
1058                          */
1059                         if (strchr(optarg, '/') != NULL) {
1060                                 (void) fprintf(stderr, gettext("cannot create "
1061                                     "'%s': invalid character '/' in temporary "
1062                                     "name\n"), optarg);
1063                                 (void) fprintf(stderr, gettext("use 'zfs "
1064                                     "create' to create a dataset\n"));
1065                                 goto errout;
1066                         }
1067
1068                         if (add_prop_list(zpool_prop_to_name(
1069                             ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
1070                                 goto errout;
1071                         if (add_prop_list_default(zpool_prop_to_name(
1072                             ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1073                                 goto errout;
1074                         tname = optarg;
1075                         break;
1076                 case ':':
1077                         (void) fprintf(stderr, gettext("missing argument for "
1078                             "'%c' option\n"), optopt);
1079                         goto badusage;
1080                 case '?':
1081                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1082                             optopt);
1083                         goto badusage;
1084                 }
1085         }
1086
1087         argc -= optind;
1088         argv += optind;
1089
1090         /* get pool name and check number of arguments */
1091         if (argc < 1) {
1092                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1093                 goto badusage;
1094         }
1095         if (argc < 2) {
1096                 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1097                 goto badusage;
1098         }
1099
1100         poolname = argv[0];
1101
1102         /*
1103          * As a special case, check for use of '/' in the name, and direct the
1104          * user to use 'zfs create' instead.
1105          */
1106         if (strchr(poolname, '/') != NULL) {
1107                 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
1108                     "character '/' in pool name\n"), poolname);
1109                 (void) fprintf(stderr, gettext("use 'zfs create' to "
1110                     "create a dataset\n"));
1111                 goto errout;
1112         }
1113
1114         /* pass off to get_vdev_spec for bulk processing */
1115         nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
1116             argc - 1, argv + 1);
1117         if (nvroot == NULL)
1118                 goto errout;
1119
1120         /* make_root_vdev() allows 0 toplevel children if there are spares */
1121         if (!zfs_allocatable_devs(nvroot)) {
1122                 (void) fprintf(stderr, gettext("invalid vdev "
1123                     "specification: at least one toplevel vdev must be "
1124                     "specified\n"));
1125                 goto errout;
1126         }
1127
1128         if (altroot != NULL && altroot[0] != '/') {
1129                 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
1130                     "must be an absolute path\n"), altroot);
1131                 goto errout;
1132         }
1133
1134         /*
1135          * Check the validity of the mountpoint and direct the user to use the
1136          * '-m' mountpoint option if it looks like its in use.
1137          */
1138         if (mountpoint == NULL ||
1139             (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
1140             strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
1141                 char buf[MAXPATHLEN];
1142                 DIR *dirp;
1143
1144                 if (mountpoint && mountpoint[0] != '/') {
1145                         (void) fprintf(stderr, gettext("invalid mountpoint "
1146                             "'%s': must be an absolute path, 'legacy', or "
1147                             "'none'\n"), mountpoint);
1148                         goto errout;
1149                 }
1150
1151                 if (mountpoint == NULL) {
1152                         if (altroot != NULL)
1153                                 (void) snprintf(buf, sizeof (buf), "%s/%s",
1154                                     altroot, poolname);
1155                         else
1156                                 (void) snprintf(buf, sizeof (buf), "/%s",
1157                                     poolname);
1158                 } else {
1159                         if (altroot != NULL)
1160                                 (void) snprintf(buf, sizeof (buf), "%s%s",
1161                                     altroot, mountpoint);
1162                         else
1163                                 (void) snprintf(buf, sizeof (buf), "%s",
1164                                     mountpoint);
1165                 }
1166
1167                 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
1168                         (void) fprintf(stderr, gettext("mountpoint '%s' : "
1169                             "%s\n"), buf, strerror(errno));
1170                         (void) fprintf(stderr, gettext("use '-m' "
1171                             "option to provide a different default\n"));
1172                         goto errout;
1173                 } else if (dirp) {
1174                         int count = 0;
1175
1176                         while (count < 3 && readdir(dirp) != NULL)
1177                                 count++;
1178                         (void) closedir(dirp);
1179
1180                         if (count > 2) {
1181                                 (void) fprintf(stderr, gettext("mountpoint "
1182                                     "'%s' exists and is not empty\n"), buf);
1183                                 (void) fprintf(stderr, gettext("use '-m' "
1184                                     "option to provide a "
1185                                     "different default\n"));
1186                                 goto errout;
1187                         }
1188                 }
1189         }
1190
1191         /*
1192          * Now that the mountpoint's validity has been checked, ensure that
1193          * the property is set appropriately prior to creating the pool.
1194          */
1195         if (mountpoint != NULL) {
1196                 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
1197                     mountpoint, &fsprops, B_FALSE);
1198                 if (ret != 0)
1199                         goto errout;
1200         }
1201
1202         ret = 1;
1203         if (dryrun) {
1204                 /*
1205                  * For a dry run invocation, print out a basic message and run
1206                  * through all the vdevs in the list and print out in an
1207                  * appropriate hierarchy.
1208                  */
1209                 (void) printf(gettext("would create '%s' with the "
1210                     "following layout:\n\n"), poolname);
1211
1212                 print_vdev_tree(NULL, poolname, nvroot, 0, B_FALSE, 0);
1213                 if (num_logs(nvroot) > 0)
1214                         print_vdev_tree(NULL, "logs", nvroot, 0, B_TRUE, 0);
1215
1216                 ret = 0;
1217         } else {
1218                 /*
1219                  * Hand off to libzfs.
1220                  */
1221                 spa_feature_t i;
1222                 for (i = 0; i < SPA_FEATURES; i++) {
1223                         char propname[MAXPATHLEN];
1224                         char *propval;
1225                         zfeature_info_t *feat = &spa_feature_table[i];
1226
1227                         (void) snprintf(propname, sizeof (propname),
1228                             "feature@%s", feat->fi_uname);
1229
1230                         /*
1231                          * Only features contained in props will be enabled:
1232                          * remove from the nvlist every ZFS_FEATURE_DISABLED
1233                          * value and add every missing ZFS_FEATURE_ENABLED if
1234                          * enable_all_pool_feat is set.
1235                          */
1236                         if (!nvlist_lookup_string(props, propname, &propval)) {
1237                                 if (strcmp(propval, ZFS_FEATURE_DISABLED) == 0)
1238                                         (void) nvlist_remove_all(props,
1239                                             propname);
1240                         } else if (enable_all_pool_feat) {
1241                                 ret = add_prop_list(propname,
1242                                     ZFS_FEATURE_ENABLED, &props, B_TRUE);
1243                                 if (ret != 0)
1244                                         goto errout;
1245                         }
1246                 }
1247
1248                 ret = 1;
1249                 if (zpool_create(g_zfs, poolname,
1250                     nvroot, props, fsprops) == 0) {
1251                         zfs_handle_t *pool = zfs_open(g_zfs,
1252                             tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
1253                         if (pool != NULL) {
1254                                 if (zfs_mount(pool, NULL, 0) == 0)
1255                                         ret = zfs_shareall(pool);
1256                                 zfs_close(pool);
1257                         }
1258                 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
1259                         (void) fprintf(stderr, gettext("pool name may have "
1260                             "been omitted\n"));
1261                 }
1262         }
1263
1264 errout:
1265         nvlist_free(nvroot);
1266         nvlist_free(fsprops);
1267         nvlist_free(props);
1268         return (ret);
1269 badusage:
1270         nvlist_free(fsprops);
1271         nvlist_free(props);
1272         usage(B_FALSE);
1273         return (2);
1274 }
1275
1276 /*
1277  * zpool destroy <pool>
1278  *
1279  *      -f      Forcefully unmount any datasets
1280  *
1281  * Destroy the given pool.  Automatically unmounts any datasets in the pool.
1282  */
1283 int
1284 zpool_do_destroy(int argc, char **argv)
1285 {
1286         boolean_t force = B_FALSE;
1287         int c;
1288         char *pool;
1289         zpool_handle_t *zhp;
1290         int ret;
1291
1292         /* check options */
1293         while ((c = getopt(argc, argv, "f")) != -1) {
1294                 switch (c) {
1295                 case 'f':
1296                         force = B_TRUE;
1297                         break;
1298                 case '?':
1299                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1300                             optopt);
1301                         usage(B_FALSE);
1302                 }
1303         }
1304
1305         argc -= optind;
1306         argv += optind;
1307
1308         /* check arguments */
1309         if (argc < 1) {
1310                 (void) fprintf(stderr, gettext("missing pool argument\n"));
1311                 usage(B_FALSE);
1312         }
1313         if (argc > 1) {
1314                 (void) fprintf(stderr, gettext("too many arguments\n"));
1315                 usage(B_FALSE);
1316         }
1317
1318         pool = argv[0];
1319
1320         if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
1321                 /*
1322                  * As a special case, check for use of '/' in the name, and
1323                  * direct the user to use 'zfs destroy' instead.
1324                  */
1325                 if (strchr(pool, '/') != NULL)
1326                         (void) fprintf(stderr, gettext("use 'zfs destroy' to "
1327                             "destroy a dataset\n"));
1328                 return (1);
1329         }
1330
1331         if (zpool_disable_datasets(zhp, force) != 0) {
1332                 (void) fprintf(stderr, gettext("could not destroy '%s': "
1333                     "could not unmount datasets\n"), zpool_get_name(zhp));
1334                 zpool_close(zhp);
1335                 return (1);
1336         }
1337
1338         /* The history must be logged as part of the export */
1339         log_history = B_FALSE;
1340
1341         ret = (zpool_destroy(zhp, history_str) != 0);
1342
1343         zpool_close(zhp);
1344
1345         return (ret);
1346 }
1347
1348 typedef struct export_cbdata {
1349         boolean_t force;
1350         boolean_t hardforce;
1351 } export_cbdata_t;
1352
1353 /*
1354  * Export one pool
1355  */
1356 int
1357 zpool_export_one(zpool_handle_t *zhp, void *data)
1358 {
1359         export_cbdata_t *cb = data;
1360
1361         if (zpool_disable_datasets(zhp, cb->force) != 0)
1362                 return (1);
1363
1364         /* The history must be logged as part of the export */
1365         log_history = B_FALSE;
1366
1367         if (cb->hardforce) {
1368                 if (zpool_export_force(zhp, history_str) != 0)
1369                         return (1);
1370         } else if (zpool_export(zhp, cb->force, history_str) != 0) {
1371                 return (1);
1372         }
1373
1374         return (0);
1375 }
1376
1377 /*
1378  * zpool export [-f] <pool> ...
1379  *
1380  *      -a      Export all pools
1381  *      -f      Forcefully unmount datasets
1382  *
1383  * Export the given pools.  By default, the command will attempt to cleanly
1384  * unmount any active datasets within the pool.  If the '-f' flag is specified,
1385  * then the datasets will be forcefully unmounted.
1386  */
1387 int
1388 zpool_do_export(int argc, char **argv)
1389 {
1390         export_cbdata_t cb;
1391         boolean_t do_all = B_FALSE;
1392         boolean_t force = B_FALSE;
1393         boolean_t hardforce = B_FALSE;
1394         int c, ret;
1395
1396         /* check options */
1397         while ((c = getopt(argc, argv, "afF")) != -1) {
1398                 switch (c) {
1399                 case 'a':
1400                         do_all = B_TRUE;
1401                         break;
1402                 case 'f':
1403                         force = B_TRUE;
1404                         break;
1405                 case 'F':
1406                         hardforce = B_TRUE;
1407                         break;
1408                 case '?':
1409                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1410                             optopt);
1411                         usage(B_FALSE);
1412                 }
1413         }
1414
1415         cb.force = force;
1416         cb.hardforce = hardforce;
1417         argc -= optind;
1418         argv += optind;
1419
1420         if (do_all) {
1421                 if (argc != 0) {
1422                         (void) fprintf(stderr, gettext("too many arguments\n"));
1423                         usage(B_FALSE);
1424                 }
1425
1426                 return (for_each_pool(argc, argv, B_TRUE, NULL,
1427                     zpool_export_one, &cb));
1428         }
1429
1430         /* check arguments */
1431         if (argc < 1) {
1432                 (void) fprintf(stderr, gettext("missing pool argument\n"));
1433                 usage(B_FALSE);
1434         }
1435
1436         ret = for_each_pool(argc, argv, B_TRUE, NULL, zpool_export_one, &cb);
1437
1438         return (ret);
1439 }
1440
1441 /*
1442  * Given a vdev configuration, determine the maximum width needed for the device
1443  * name column.
1444  */
1445 static int
1446 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
1447     int name_flags)
1448 {
1449         char *name;
1450         nvlist_t **child;
1451         uint_t c, children;
1452         int ret;
1453
1454         name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
1455         if (strlen(name) + depth > max)
1456                 max = strlen(name) + depth;
1457
1458         free(name);
1459
1460         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1461             &child, &children) == 0) {
1462                 for (c = 0; c < children; c++)
1463                         if ((ret = max_width(zhp, child[c], depth + 2,
1464                             max, name_flags)) > max)
1465                                 max = ret;
1466         }
1467
1468         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1469             &child, &children) == 0) {
1470                 for (c = 0; c < children; c++)
1471                         if ((ret = max_width(zhp, child[c], depth + 2,
1472                             max, name_flags)) > max)
1473                                 max = ret;
1474         }
1475
1476         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1477             &child, &children) == 0) {
1478                 for (c = 0; c < children; c++)
1479                         if ((ret = max_width(zhp, child[c], depth + 2,
1480                             max, name_flags)) > max)
1481                                 max = ret;
1482         }
1483
1484         return (max);
1485 }
1486
1487 typedef struct spare_cbdata {
1488         uint64_t        cb_guid;
1489         zpool_handle_t  *cb_zhp;
1490 } spare_cbdata_t;
1491
1492 static boolean_t
1493 find_vdev(nvlist_t *nv, uint64_t search)
1494 {
1495         uint64_t guid;
1496         nvlist_t **child;
1497         uint_t c, children;
1498
1499         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1500             search == guid)
1501                 return (B_TRUE);
1502
1503         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1504             &child, &children) == 0) {
1505                 for (c = 0; c < children; c++)
1506                         if (find_vdev(child[c], search))
1507                                 return (B_TRUE);
1508         }
1509
1510         return (B_FALSE);
1511 }
1512
1513 static int
1514 find_spare(zpool_handle_t *zhp, void *data)
1515 {
1516         spare_cbdata_t *cbp = data;
1517         nvlist_t *config, *nvroot;
1518
1519         config = zpool_get_config(zhp, NULL);
1520         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1521             &nvroot) == 0);
1522
1523         if (find_vdev(nvroot, cbp->cb_guid)) {
1524                 cbp->cb_zhp = zhp;
1525                 return (1);
1526         }
1527
1528         zpool_close(zhp);
1529         return (0);
1530 }
1531
1532 typedef struct status_cbdata {
1533         int             cb_count;
1534         int             cb_name_flags;
1535         int             cb_namewidth;
1536         boolean_t       cb_allpools;
1537         boolean_t       cb_verbose;
1538         boolean_t       cb_explain;
1539         boolean_t       cb_first;
1540         boolean_t       cb_dedup_stats;
1541         boolean_t       cb_print_status;
1542         vdev_cmd_data_list_t    *vcdl;
1543 } status_cbdata_t;
1544
1545 /* Print output line for specific vdev in a specific pool */
1546 static void
1547 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, char *path)
1548 {
1549         int i;
1550         for (i = 0; i < vcdl->count; i++) {
1551                 if ((strcmp(vcdl->data[i].path, path) == 0) &&
1552                     (strcmp(vcdl->data[i].pool, pool) == 0)) {
1553                         printf("%s", vcdl->data[i].line);
1554                         break;
1555                 }
1556         }
1557 }
1558
1559 /*
1560  * Print out configuration state as requested by status_callback.
1561  */
1562 static void
1563 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
1564     nvlist_t *nv, int depth, boolean_t isspare)
1565 {
1566         nvlist_t **child;
1567         uint_t c, children;
1568         pool_scan_stat_t *ps = NULL;
1569         vdev_stat_t *vs;
1570         char rbuf[6], wbuf[6], cbuf[6];
1571         char *vname;
1572         uint64_t notpresent;
1573         spare_cbdata_t spare_cb;
1574         char *state;
1575         char *path = NULL;
1576
1577         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1578             &child, &children) != 0)
1579                 children = 0;
1580
1581         verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1582             (uint64_t **)&vs, &c) == 0);
1583
1584         state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1585         if (isspare) {
1586                 /*
1587                  * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
1588                  * online drives.
1589                  */
1590                 if (vs->vs_aux == VDEV_AUX_SPARED)
1591                         state = "INUSE";
1592                 else if (vs->vs_state == VDEV_STATE_HEALTHY)
1593                         state = "AVAIL";
1594         }
1595
1596         (void) printf("\t%*s%-*s  %-8s", depth, "", cb->cb_namewidth - depth,
1597             name, state);
1598
1599         if (!isspare) {
1600                 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
1601                 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
1602                 zfs_nicenum(vs->vs_checksum_errors, cbuf, sizeof (cbuf));
1603                 (void) printf(" %5s %5s %5s", rbuf, wbuf, cbuf);
1604         }
1605
1606         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
1607             &notpresent) == 0) {
1608                 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
1609                 (void) printf("  was %s", path);
1610         } else if (vs->vs_aux != 0) {
1611                 (void) printf("  ");
1612
1613                 switch (vs->vs_aux) {
1614                 case VDEV_AUX_OPEN_FAILED:
1615                         (void) printf(gettext("cannot open"));
1616                         break;
1617
1618                 case VDEV_AUX_BAD_GUID_SUM:
1619                         (void) printf(gettext("missing device"));
1620                         break;
1621
1622                 case VDEV_AUX_NO_REPLICAS:
1623                         (void) printf(gettext("insufficient replicas"));
1624                         break;
1625
1626                 case VDEV_AUX_VERSION_NEWER:
1627                         (void) printf(gettext("newer version"));
1628                         break;
1629
1630                 case VDEV_AUX_UNSUP_FEAT:
1631                         (void) printf(gettext("unsupported feature(s)"));
1632                         break;
1633
1634                 case VDEV_AUX_SPARED:
1635                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
1636                             &spare_cb.cb_guid) == 0);
1637                         if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1638                                 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1639                                     zpool_get_name(zhp)) == 0)
1640                                         (void) printf(gettext("currently in "
1641                                             "use"));
1642                                 else
1643                                         (void) printf(gettext("in use by "
1644                                             "pool '%s'"),
1645                                             zpool_get_name(spare_cb.cb_zhp));
1646                                 zpool_close(spare_cb.cb_zhp);
1647                         } else {
1648                                 (void) printf(gettext("currently in use"));
1649                         }
1650                         break;
1651
1652                 case VDEV_AUX_ERR_EXCEEDED:
1653                         (void) printf(gettext("too many errors"));
1654                         break;
1655
1656                 case VDEV_AUX_IO_FAILURE:
1657                         (void) printf(gettext("experienced I/O failures"));
1658                         break;
1659
1660                 case VDEV_AUX_BAD_LOG:
1661                         (void) printf(gettext("bad intent log"));
1662                         break;
1663
1664                 case VDEV_AUX_EXTERNAL:
1665                         (void) printf(gettext("external device fault"));
1666                         break;
1667
1668                 case VDEV_AUX_SPLIT_POOL:
1669                         (void) printf(gettext("split into new pool"));
1670                         break;
1671
1672                 default:
1673                         (void) printf(gettext("corrupted data"));
1674                         break;
1675                 }
1676         }
1677
1678         (void) nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_SCAN_STATS,
1679             (uint64_t **)&ps, &c);
1680
1681         if (ps && ps->pss_state == DSS_SCANNING &&
1682             vs->vs_scan_processed != 0 && children == 0) {
1683                 (void) printf(gettext("  (%s)"),
1684                     (ps->pss_func == POOL_SCAN_RESILVER) ?
1685                     "resilvering" : "repairing");
1686         }
1687
1688         if (cb->vcdl != NULL) {
1689                 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
1690                         printf("  ");
1691                         zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
1692                 }
1693         }
1694
1695         (void) printf("\n");
1696
1697         for (c = 0; c < children; c++) {
1698                 uint64_t islog = B_FALSE, ishole = B_FALSE;
1699
1700                 /* Don't print logs or holes here */
1701                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1702                     &islog);
1703                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
1704                     &ishole);
1705                 if (islog || ishole)
1706                         continue;
1707                 vname = zpool_vdev_name(g_zfs, zhp, child[c],
1708                     cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1709                 print_status_config(zhp, cb, vname, child[c], depth + 2,
1710                     isspare);
1711                 free(vname);
1712         }
1713 }
1714
1715 /*
1716  * Print the configuration of an exported pool.  Iterate over all vdevs in the
1717  * pool, printing out the name and status for each one.
1718  */
1719 static void
1720 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
1721     int depth)
1722 {
1723         nvlist_t **child;
1724         uint_t c, children;
1725         vdev_stat_t *vs;
1726         char *type, *vname;
1727
1728         verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1729         if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
1730             strcmp(type, VDEV_TYPE_HOLE) == 0)
1731                 return;
1732
1733         verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1734             (uint64_t **)&vs, &c) == 0);
1735
1736         (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
1737         (void) printf("  %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
1738
1739         if (vs->vs_aux != 0) {
1740                 (void) printf("  ");
1741
1742                 switch (vs->vs_aux) {
1743                 case VDEV_AUX_OPEN_FAILED:
1744                         (void) printf(gettext("cannot open"));
1745                         break;
1746
1747                 case VDEV_AUX_BAD_GUID_SUM:
1748                         (void) printf(gettext("missing device"));
1749                         break;
1750
1751                 case VDEV_AUX_NO_REPLICAS:
1752                         (void) printf(gettext("insufficient replicas"));
1753                         break;
1754
1755                 case VDEV_AUX_VERSION_NEWER:
1756                         (void) printf(gettext("newer version"));
1757                         break;
1758
1759                 case VDEV_AUX_UNSUP_FEAT:
1760                         (void) printf(gettext("unsupported feature(s)"));
1761                         break;
1762
1763                 case VDEV_AUX_ERR_EXCEEDED:
1764                         (void) printf(gettext("too many errors"));
1765                         break;
1766
1767                 default:
1768                         (void) printf(gettext("corrupted data"));
1769                         break;
1770                 }
1771         }
1772         (void) printf("\n");
1773
1774         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1775             &child, &children) != 0)
1776                 return;
1777
1778         for (c = 0; c < children; c++) {
1779                 uint64_t is_log = B_FALSE;
1780
1781                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1782                     &is_log);
1783                 if (is_log)
1784                         continue;
1785
1786                 vname = zpool_vdev_name(g_zfs, NULL, child[c],
1787                     cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1788                 print_import_config(cb, vname, child[c], depth + 2);
1789                 free(vname);
1790         }
1791
1792         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1793             &child, &children) == 0) {
1794                 (void) printf(gettext("\tcache\n"));
1795                 for (c = 0; c < children; c++) {
1796                         vname = zpool_vdev_name(g_zfs, NULL, child[c],
1797                             cb->cb_name_flags);
1798                         (void) printf("\t  %s\n", vname);
1799                         free(vname);
1800                 }
1801         }
1802
1803         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1804             &child, &children) == 0) {
1805                 (void) printf(gettext("\tspares\n"));
1806                 for (c = 0; c < children; c++) {
1807                         vname = zpool_vdev_name(g_zfs, NULL, child[c],
1808                             cb->cb_name_flags);
1809                         (void) printf("\t  %s\n", vname);
1810                         free(vname);
1811                 }
1812         }
1813 }
1814
1815 /*
1816  * Print log vdevs.
1817  * Logs are recorded as top level vdevs in the main pool child array
1818  * but with "is_log" set to 1. We use either print_status_config() or
1819  * print_import_config() to print the top level logs then any log
1820  * children (eg mirrored slogs) are printed recursively - which
1821  * works because only the top level vdev is marked "is_log"
1822  */
1823 static void
1824 print_logs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv)
1825 {
1826         uint_t c, children;
1827         nvlist_t **child;
1828
1829         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
1830             &children) != 0)
1831                 return;
1832
1833         (void) printf(gettext("\tlogs\n"));
1834
1835         for (c = 0; c < children; c++) {
1836                 uint64_t is_log = B_FALSE;
1837                 char *name;
1838
1839                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1840                     &is_log);
1841                 if (!is_log)
1842                         continue;
1843                 name = zpool_vdev_name(g_zfs, zhp, child[c],
1844                     cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1845                 if (cb->cb_print_status)
1846                         print_status_config(zhp, cb, name, child[c], 2,
1847                             B_FALSE);
1848                 else
1849                         print_import_config(cb, name, child[c], 2);
1850                 free(name);
1851         }
1852 }
1853
1854 /*
1855  * Display the status for the given pool.
1856  */
1857 static void
1858 show_import(nvlist_t *config)
1859 {
1860         uint64_t pool_state;
1861         vdev_stat_t *vs;
1862         char *name;
1863         uint64_t guid;
1864         char *msgid;
1865         nvlist_t *nvroot;
1866         zpool_status_t reason;
1867         zpool_errata_t errata;
1868         const char *health;
1869         uint_t vsc;
1870         char *comment;
1871         status_cbdata_t cb = { 0 };
1872
1873         verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1874             &name) == 0);
1875         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1876             &guid) == 0);
1877         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
1878             &pool_state) == 0);
1879         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1880             &nvroot) == 0);
1881
1882         verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
1883             (uint64_t **)&vs, &vsc) == 0);
1884         health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1885
1886         reason = zpool_import_status(config, &msgid, &errata);
1887
1888         (void) printf(gettext("   pool: %s\n"), name);
1889         (void) printf(gettext("     id: %llu\n"), (u_longlong_t)guid);
1890         (void) printf(gettext("  state: %s"), health);
1891         if (pool_state == POOL_STATE_DESTROYED)
1892                 (void) printf(gettext(" (DESTROYED)"));
1893         (void) printf("\n");
1894
1895         switch (reason) {
1896         case ZPOOL_STATUS_MISSING_DEV_R:
1897         case ZPOOL_STATUS_MISSING_DEV_NR:
1898         case ZPOOL_STATUS_BAD_GUID_SUM:
1899                 (void) printf(gettext(" status: One or more devices are "
1900                     "missing from the system.\n"));
1901                 break;
1902
1903         case ZPOOL_STATUS_CORRUPT_LABEL_R:
1904         case ZPOOL_STATUS_CORRUPT_LABEL_NR:
1905                 (void) printf(gettext(" status: One or more devices contains "
1906                     "corrupted data.\n"));
1907                 break;
1908
1909         case ZPOOL_STATUS_CORRUPT_DATA:
1910                 (void) printf(
1911                     gettext(" status: The pool data is corrupted.\n"));
1912                 break;
1913
1914         case ZPOOL_STATUS_OFFLINE_DEV:
1915                 (void) printf(gettext(" status: One or more devices "
1916                     "are offlined.\n"));
1917                 break;
1918
1919         case ZPOOL_STATUS_CORRUPT_POOL:
1920                 (void) printf(gettext(" status: The pool metadata is "
1921                     "corrupted.\n"));
1922                 break;
1923
1924         case ZPOOL_STATUS_VERSION_OLDER:
1925                 (void) printf(gettext(" status: The pool is formatted using a "
1926                     "legacy on-disk version.\n"));
1927                 break;
1928
1929         case ZPOOL_STATUS_VERSION_NEWER:
1930                 (void) printf(gettext(" status: The pool is formatted using an "
1931                     "incompatible version.\n"));
1932                 break;
1933
1934         case ZPOOL_STATUS_FEAT_DISABLED:
1935                 (void) printf(gettext(" status: Some supported features are "
1936                     "not enabled on the pool.\n"));
1937                 break;
1938
1939         case ZPOOL_STATUS_UNSUP_FEAT_READ:
1940                 (void) printf(gettext("status: The pool uses the following "
1941                     "feature(s) not supported on this system:\n"));
1942                 zpool_print_unsup_feat(config);
1943                 break;
1944
1945         case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
1946                 (void) printf(gettext("status: The pool can only be accessed "
1947                     "in read-only mode on this system. It\n\tcannot be "
1948                     "accessed in read-write mode because it uses the "
1949                     "following\n\tfeature(s) not supported on this system:\n"));
1950                 zpool_print_unsup_feat(config);
1951                 break;
1952
1953         case ZPOOL_STATUS_HOSTID_MISMATCH:
1954                 (void) printf(gettext(" status: The pool was last accessed by "
1955                     "another system.\n"));
1956                 break;
1957
1958         case ZPOOL_STATUS_FAULTED_DEV_R:
1959         case ZPOOL_STATUS_FAULTED_DEV_NR:
1960                 (void) printf(gettext(" status: One or more devices are "
1961                     "faulted.\n"));
1962                 break;
1963
1964         case ZPOOL_STATUS_BAD_LOG:
1965                 (void) printf(gettext(" status: An intent log record cannot be "
1966                     "read.\n"));
1967                 break;
1968
1969         case ZPOOL_STATUS_RESILVERING:
1970                 (void) printf(gettext(" status: One or more devices were being "
1971                     "resilvered.\n"));
1972                 break;
1973
1974         case ZPOOL_STATUS_ERRATA:
1975                 (void) printf(gettext(" status: Errata #%d detected.\n"),
1976                     errata);
1977                 break;
1978
1979         default:
1980                 /*
1981                  * No other status can be seen when importing pools.
1982                  */
1983                 assert(reason == ZPOOL_STATUS_OK);
1984         }
1985
1986         /*
1987          * Print out an action according to the overall state of the pool.
1988          */
1989         if (vs->vs_state == VDEV_STATE_HEALTHY) {
1990                 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
1991                     reason == ZPOOL_STATUS_FEAT_DISABLED) {
1992                         (void) printf(gettext(" action: The pool can be "
1993                             "imported using its name or numeric identifier, "
1994                             "though\n\tsome features will not be available "
1995                             "without an explicit 'zpool upgrade'.\n"));
1996                 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
1997                         (void) printf(gettext(" action: The pool can be "
1998                             "imported using its name or numeric "
1999                             "identifier and\n\tthe '-f' flag.\n"));
2000                 } else if (reason == ZPOOL_STATUS_ERRATA) {
2001                         switch (errata) {
2002                         case ZPOOL_ERRATA_NONE:
2003                                 break;
2004
2005                         case ZPOOL_ERRATA_ZOL_2094_SCRUB:
2006                                 (void) printf(gettext(" action: The pool can "
2007                                     "be imported using its name or numeric "
2008                                     "identifier,\n\thowever there is a compat"
2009                                     "ibility issue which should be corrected"
2010                                     "\n\tby running 'zpool scrub'\n"));
2011                                 break;
2012
2013                         case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
2014                                 (void) printf(gettext(" action: The pool can"
2015                                     "not be imported with this version of ZFS "
2016                                     "due to\n\tan active asynchronous destroy. "
2017                                     "Revert to an earlier version\n\tand "
2018                                     "allow the destroy to complete before "
2019                                     "updating.\n"));
2020                                 break;
2021
2022                         default:
2023                                 /*
2024                                  * All errata must contain an action message.
2025                                  */
2026                                 assert(0);
2027                         }
2028                 } else {
2029                         (void) printf(gettext(" action: The pool can be "
2030                             "imported using its name or numeric "
2031                             "identifier.\n"));
2032                 }
2033         } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
2034                 (void) printf(gettext(" action: The pool can be imported "
2035                     "despite missing or damaged devices.  The\n\tfault "
2036                     "tolerance of the pool may be compromised if imported.\n"));
2037         } else {
2038                 switch (reason) {
2039                 case ZPOOL_STATUS_VERSION_NEWER:
2040                         (void) printf(gettext(" action: The pool cannot be "
2041                             "imported.  Access the pool on a system running "
2042                             "newer\n\tsoftware, or recreate the pool from "
2043                             "backup.\n"));
2044                         break;
2045                 case ZPOOL_STATUS_UNSUP_FEAT_READ:
2046                         (void) printf(gettext("action: The pool cannot be "
2047                             "imported. Access the pool on a system that "
2048                             "supports\n\tthe required feature(s), or recreate "
2049                             "the pool from backup.\n"));
2050                         break;
2051                 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2052                         (void) printf(gettext("action: The pool cannot be "
2053                             "imported in read-write mode. Import the pool "
2054                             "with\n"
2055                             "\t\"-o readonly=on\", access the pool on a system "
2056                             "that supports the\n\trequired feature(s), or "
2057                             "recreate the pool from backup.\n"));
2058                         break;
2059                 case ZPOOL_STATUS_MISSING_DEV_R:
2060                 case ZPOOL_STATUS_MISSING_DEV_NR:
2061                 case ZPOOL_STATUS_BAD_GUID_SUM:
2062                         (void) printf(gettext(" action: The pool cannot be "
2063                             "imported. Attach the missing\n\tdevices and try "
2064                             "again.\n"));
2065                         break;
2066                 default:
2067                         (void) printf(gettext(" action: The pool cannot be "
2068                             "imported due to damaged devices or data.\n"));
2069                 }
2070         }
2071
2072         /* Print the comment attached to the pool. */
2073         if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2074                 (void) printf(gettext("comment: %s\n"), comment);
2075
2076         /*
2077          * If the state is "closed" or "can't open", and the aux state
2078          * is "corrupt data":
2079          */
2080         if (((vs->vs_state == VDEV_STATE_CLOSED) ||
2081             (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
2082             (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
2083                 if (pool_state == POOL_STATE_DESTROYED)
2084                         (void) printf(gettext("\tThe pool was destroyed, "
2085                             "but can be imported using the '-Df' flags.\n"));
2086                 else if (pool_state != POOL_STATE_EXPORTED)
2087                         (void) printf(gettext("\tThe pool may be active on "
2088                             "another system, but can be imported using\n\t"
2089                             "the '-f' flag.\n"));
2090         }
2091
2092         if (msgid != NULL)
2093                 (void) printf(gettext("   see: http://zfsonlinux.org/msg/%s\n"),
2094                     msgid);
2095
2096         (void) printf(gettext(" config:\n\n"));
2097
2098         cb.cb_namewidth = max_width(NULL, nvroot, 0, 0, VDEV_NAME_TYPE_ID);
2099         if (cb.cb_namewidth < 10)
2100                 cb.cb_namewidth = 10;
2101
2102         print_import_config(&cb, name, nvroot, 0);
2103         if (num_logs(nvroot) > 0)
2104                 print_logs(NULL, &cb, nvroot);
2105
2106         if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
2107                 (void) printf(gettext("\n\tAdditional devices are known to "
2108                     "be part of this pool, though their\n\texact "
2109                     "configuration cannot be determined.\n"));
2110         }
2111 }
2112
2113 /*
2114  * Perform the import for the given configuration.  This passes the heavy
2115  * lifting off to zpool_import_props(), and then mounts the datasets contained
2116  * within the pool.
2117  */
2118 static int
2119 do_import(nvlist_t *config, const char *newname, const char *mntopts,
2120     nvlist_t *props, int flags)
2121 {
2122         zpool_handle_t *zhp;
2123         char *name;
2124         uint64_t state;
2125         uint64_t version;
2126
2127         verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2128             &name) == 0);
2129
2130         verify(nvlist_lookup_uint64(config,
2131             ZPOOL_CONFIG_POOL_STATE, &state) == 0);
2132         verify(nvlist_lookup_uint64(config,
2133             ZPOOL_CONFIG_VERSION, &version) == 0);
2134         if (!SPA_VERSION_IS_SUPPORTED(version)) {
2135                 (void) fprintf(stderr, gettext("cannot import '%s': pool "
2136                     "is formatted using an unsupported ZFS version\n"), name);
2137                 return (1);
2138         } else if (state != POOL_STATE_EXPORTED &&
2139             !(flags & ZFS_IMPORT_ANY_HOST)) {
2140                 uint64_t hostid = 0;
2141                 unsigned long system_hostid = get_system_hostid();
2142
2143                 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
2144                     &hostid);
2145
2146                 if (hostid != 0 && (unsigned long)hostid != system_hostid) {
2147                         char *hostname;
2148                         uint64_t timestamp;
2149                         time_t t;
2150
2151                         verify(nvlist_lookup_string(config,
2152                             ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2153                         verify(nvlist_lookup_uint64(config,
2154                             ZPOOL_CONFIG_TIMESTAMP, &timestamp) == 0);
2155                         t = timestamp;
2156                         (void) fprintf(stderr, gettext("cannot import "
2157                             "'%s': pool may be in use from other "
2158                             "system, it was last accessed by %s "
2159                             "(hostid: 0x%lx) on %s"), name, hostname,
2160                             (unsigned long)hostid,
2161                             asctime(localtime(&t)));
2162                         (void) fprintf(stderr, gettext("use '-f' to "
2163                             "import anyway\n"));
2164                         return (1);
2165                 }
2166         }
2167
2168         if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
2169                 return (1);
2170
2171         if (newname != NULL)
2172                 name = (char *)newname;
2173
2174         if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
2175                 return (1);
2176
2177         if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
2178             !(flags & ZFS_IMPORT_ONLY) &&
2179             zpool_enable_datasets(zhp, mntopts, 0) != 0) {
2180                 zpool_close(zhp);
2181                 return (1);
2182         }
2183
2184         zpool_close(zhp);
2185         return (0);
2186 }
2187
2188 /*
2189  * zpool import [-d dir] [-D]
2190  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D]
2191  *              [-d dir | -c cachefile] [-f] -a
2192  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D]
2193  *              [-d dir | -c cachefile] [-f] [-n] [-F] <pool | id> [newpool]
2194  *
2195  *       -c     Read pool information from a cachefile instead of searching
2196  *              devices.
2197  *
2198  *       -d     Scan in a specific directory, other than /dev/.  More than
2199  *              one directory can be specified using multiple '-d' options.
2200  *
2201  *       -D     Scan for previously destroyed pools or import all or only
2202  *              specified destroyed pools.
2203  *
2204  *       -R     Temporarily import the pool, with all mountpoints relative to
2205  *              the given root.  The pool will remain exported when the machine
2206  *              is rebooted.
2207  *
2208  *       -V     Import even in the presence of faulted vdevs.  This is an
2209  *              intentionally undocumented option for testing purposes, and
2210  *              treats the pool configuration as complete, leaving any bad
2211  *              vdevs in the FAULTED state. In other words, it does verbatim
2212  *              import.
2213  *
2214  *       -f     Force import, even if it appears that the pool is active.
2215  *
2216  *       -F     Attempt rewind if necessary.
2217  *
2218  *       -n     See if rewind would work, but don't actually rewind.
2219  *
2220  *       -N     Import the pool but don't mount datasets.
2221  *
2222  *       -T     Specify a starting txg to use for import. This option is
2223  *              intentionally undocumented option for testing purposes.
2224  *
2225  *       -a     Import all pools found.
2226  *
2227  *       -o     Set property=value and/or temporary mount options (without '=').
2228  *
2229  *       -s     Scan using the default search path, the libblkid cache will
2230  *              not be consulted.
2231  *
2232  * The import command scans for pools to import, and import pools based on pool
2233  * name and GUID.  The pool can also be renamed as part of the import process.
2234  */
2235 int
2236 zpool_do_import(int argc, char **argv)
2237 {
2238         char **searchdirs = NULL;
2239         char *env, *envdup = NULL;
2240         int nsearch = 0;
2241         int c;
2242         int err = 0;
2243         nvlist_t *pools = NULL;
2244         boolean_t do_all = B_FALSE;
2245         boolean_t do_destroyed = B_FALSE;
2246         char *mntopts = NULL;
2247         nvpair_t *elem;
2248         nvlist_t *config;
2249         uint64_t searchguid = 0;
2250         char *searchname = NULL;
2251         char *propval;
2252         nvlist_t *found_config;
2253         nvlist_t *policy = NULL;
2254         nvlist_t *props = NULL;
2255         boolean_t first;
2256         int flags = ZFS_IMPORT_NORMAL;
2257         uint32_t rewind_policy = ZPOOL_NO_REWIND;
2258         boolean_t dryrun = B_FALSE;
2259         boolean_t do_rewind = B_FALSE;
2260         boolean_t xtreme_rewind = B_FALSE;
2261         boolean_t do_scan = B_FALSE;
2262         uint64_t pool_state, txg = -1ULL;
2263         char *cachefile = NULL;
2264         importargs_t idata = { 0 };
2265         char *endptr;
2266
2267         /* check options */
2268         while ((c = getopt(argc, argv, ":aCc:d:DEfFmnNo:R:stT:VX")) != -1) {
2269                 switch (c) {
2270                 case 'a':
2271                         do_all = B_TRUE;
2272                         break;
2273                 case 'c':
2274                         cachefile = optarg;
2275                         break;
2276                 case 'd':
2277                         if (searchdirs == NULL) {
2278                                 searchdirs = safe_malloc(sizeof (char *));
2279                         } else {
2280                                 char **tmp = safe_malloc((nsearch + 1) *
2281                                     sizeof (char *));
2282                                 bcopy(searchdirs, tmp, nsearch *
2283                                     sizeof (char *));
2284                                 free(searchdirs);
2285                                 searchdirs = tmp;
2286                         }
2287                         searchdirs[nsearch++] = optarg;
2288                         break;
2289                 case 'D':
2290                         do_destroyed = B_TRUE;
2291                         break;
2292                 case 'f':
2293                         flags |= ZFS_IMPORT_ANY_HOST;
2294                         break;
2295                 case 'F':
2296                         do_rewind = B_TRUE;
2297                         break;
2298                 case 'm':
2299                         flags |= ZFS_IMPORT_MISSING_LOG;
2300                         break;
2301                 case 'n':
2302                         dryrun = B_TRUE;
2303                         break;
2304                 case 'N':
2305                         flags |= ZFS_IMPORT_ONLY;
2306                         break;
2307                 case 'o':
2308                         if ((propval = strchr(optarg, '=')) != NULL) {
2309                                 *propval = '\0';
2310                                 propval++;
2311                                 if (add_prop_list(optarg, propval,
2312                                     &props, B_TRUE))
2313                                         goto error;
2314                         } else {
2315                                 mntopts = optarg;
2316                         }
2317                         break;
2318                 case 'R':
2319                         if (add_prop_list(zpool_prop_to_name(
2320                             ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
2321                                 goto error;
2322                         if (add_prop_list_default(zpool_prop_to_name(
2323                             ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
2324                                 goto error;
2325                         break;
2326                 case 's':
2327                         do_scan = B_TRUE;
2328                         break;
2329                 case 't':
2330                         flags |= ZFS_IMPORT_TEMP_NAME;
2331                         if (add_prop_list_default(zpool_prop_to_name(
2332                             ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
2333                                 goto error;
2334                         break;
2335
2336                 case 'T':
2337                         errno = 0;
2338                         txg = strtoull(optarg, &endptr, 0);
2339                         if (errno != 0 || *endptr != '\0') {
2340                                 (void) fprintf(stderr,
2341                                     gettext("invalid txg value\n"));
2342                                 usage(B_FALSE);
2343                         }
2344                         rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
2345                         break;
2346                 case 'V':
2347                         flags |= ZFS_IMPORT_VERBATIM;
2348                         break;
2349                 case 'X':
2350                         xtreme_rewind = B_TRUE;
2351                         break;
2352                 case ':':
2353                         (void) fprintf(stderr, gettext("missing argument for "
2354                             "'%c' option\n"), optopt);
2355                         usage(B_FALSE);
2356                         break;
2357                 case '?':
2358                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2359                             optopt);
2360                         usage(B_FALSE);
2361                 }
2362         }
2363
2364         argc -= optind;
2365         argv += optind;
2366
2367         if (cachefile && nsearch != 0) {
2368                 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
2369                 usage(B_FALSE);
2370         }
2371
2372         if ((dryrun || xtreme_rewind) && !do_rewind) {
2373                 (void) fprintf(stderr,
2374                     gettext("-n or -X only meaningful with -F\n"));
2375                 usage(B_FALSE);
2376         }
2377         if (dryrun)
2378                 rewind_policy = ZPOOL_TRY_REWIND;
2379         else if (do_rewind)
2380                 rewind_policy = ZPOOL_DO_REWIND;
2381         if (xtreme_rewind)
2382                 rewind_policy |= ZPOOL_EXTREME_REWIND;
2383
2384         /* In the future, we can capture further policy and include it here */
2385         if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
2386             nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, txg) != 0 ||
2387             nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
2388                 goto error;
2389
2390         /* check argument count */
2391         if (do_all) {
2392                 if (argc != 0) {
2393                         (void) fprintf(stderr, gettext("too many arguments\n"));
2394                         usage(B_FALSE);
2395                 }
2396         } else {
2397                 if (argc > 2) {
2398                         (void) fprintf(stderr, gettext("too many arguments\n"));
2399                         usage(B_FALSE);
2400                 }
2401         }
2402
2403         /*
2404          * Check for the effective uid.  We do this explicitly here because
2405          * otherwise any attempt to discover pools will silently fail.
2406          */
2407         if (argc == 0 && geteuid() != 0) {
2408                 (void) fprintf(stderr, gettext("cannot "
2409                     "discover pools: permission denied\n"));
2410                 if (searchdirs != NULL)
2411                         free(searchdirs);
2412
2413                 nvlist_free(props);
2414                 nvlist_free(policy);
2415                 return (1);
2416         }
2417
2418         /*
2419          * Depending on the arguments given, we do one of the following:
2420          *
2421          *      <none>  Iterate through all pools and display information about
2422          *              each one.
2423          *
2424          *      -a      Iterate through all pools and try to import each one.
2425          *
2426          *      <id>    Find the pool that corresponds to the given GUID/pool
2427          *              name and import that one.
2428          *
2429          *      -D      Above options applies only to destroyed pools.
2430          */
2431         if (argc != 0) {
2432                 char *endptr;
2433
2434                 errno = 0;
2435                 searchguid = strtoull(argv[0], &endptr, 10);
2436                 if (errno != 0 || *endptr != '\0') {
2437                         searchname = argv[0];
2438                         searchguid = 0;
2439                 }
2440                 found_config = NULL;
2441
2442                 /*
2443                  * User specified a name or guid.  Ensure it's unique.
2444                  */
2445                 idata.unique = B_TRUE;
2446         }
2447
2448         /*
2449          * Check the environment for the preferred search path.
2450          */
2451         if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
2452                 char *dir;
2453
2454                 envdup = strdup(env);
2455
2456                 dir = strtok(envdup, ":");
2457                 while (dir != NULL) {
2458                         if (searchdirs == NULL) {
2459                                 searchdirs = safe_malloc(sizeof (char *));
2460                         } else {
2461                                 char **tmp = safe_malloc((nsearch + 1) *
2462                                     sizeof (char *));
2463                                 bcopy(searchdirs, tmp, nsearch *
2464                                     sizeof (char *));
2465                                 free(searchdirs);
2466                                 searchdirs = tmp;
2467                         }
2468                         searchdirs[nsearch++] = dir;
2469                         dir = strtok(NULL, ":");
2470                 }
2471         }
2472
2473         idata.path = searchdirs;
2474         idata.paths = nsearch;
2475         idata.poolname = searchname;
2476         idata.guid = searchguid;
2477         idata.cachefile = cachefile;
2478         idata.scan = do_scan;
2479
2480         /*
2481          * Under Linux the zpool_find_import_impl() function leverages the
2482          * taskq implementation to parallelize device scanning.  It is
2483          * therefore necessary to initialize this functionality for the
2484          * duration of the zpool_search_import() function.
2485          */
2486         thread_init();
2487         pools = zpool_search_import(g_zfs, &idata);
2488         thread_fini();
2489
2490         if (pools != NULL && idata.exists &&
2491             (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
2492                 (void) fprintf(stderr, gettext("cannot import '%s': "
2493                     "a pool with that name already exists\n"),
2494                     argv[0]);
2495                 (void) fprintf(stderr, gettext("use the form '%s "
2496                     "<pool | id> <newpool>' to give it a new name\n"),
2497                     "zpool import");
2498                 err = 1;
2499         } else if (pools == NULL && idata.exists) {
2500                 (void) fprintf(stderr, gettext("cannot import '%s': "
2501                     "a pool with that name is already created/imported,\n"),
2502                     argv[0]);
2503                 (void) fprintf(stderr, gettext("and no additional pools "
2504                     "with that name were found\n"));
2505                 err = 1;
2506         } else if (pools == NULL) {
2507                 if (argc != 0) {
2508                         (void) fprintf(stderr, gettext("cannot import '%s': "
2509                             "no such pool available\n"), argv[0]);
2510                 }
2511                 err = 1;
2512         }
2513
2514         if (err == 1) {
2515                 if (searchdirs != NULL)
2516                         free(searchdirs);
2517                 if (envdup != NULL)
2518                         free(envdup);
2519                 nvlist_free(policy);
2520                 nvlist_free(pools);
2521                 nvlist_free(props);
2522                 return (1);
2523         }
2524
2525         /*
2526          * At this point we have a list of import candidate configs. Even if
2527          * we were searching by pool name or guid, we still need to
2528          * post-process the list to deal with pool state and possible
2529          * duplicate names.
2530          */
2531         err = 0;
2532         elem = NULL;
2533         first = B_TRUE;
2534         while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2535
2536                 verify(nvpair_value_nvlist(elem, &config) == 0);
2537
2538                 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2539                     &pool_state) == 0);
2540                 if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
2541                         continue;
2542                 if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
2543                         continue;
2544
2545                 verify(nvlist_add_nvlist(config, ZPOOL_REWIND_POLICY,
2546                     policy) == 0);
2547
2548                 if (argc == 0) {
2549                         if (first)
2550                                 first = B_FALSE;
2551                         else if (!do_all)
2552                                 (void) printf("\n");
2553
2554                         if (do_all) {
2555                                 err |= do_import(config, NULL, mntopts,
2556                                     props, flags);
2557                         } else {
2558                                 show_import(config);
2559                         }
2560                 } else if (searchname != NULL) {
2561                         char *name;
2562
2563                         /*
2564                          * We are searching for a pool based on name.
2565                          */
2566                         verify(nvlist_lookup_string(config,
2567                             ZPOOL_CONFIG_POOL_NAME, &name) == 0);
2568
2569                         if (strcmp(name, searchname) == 0) {
2570                                 if (found_config != NULL) {
2571                                         (void) fprintf(stderr, gettext(
2572                                             "cannot import '%s': more than "
2573                                             "one matching pool\n"), searchname);
2574                                         (void) fprintf(stderr, gettext(
2575                                             "import by numeric ID instead\n"));
2576                                         err = B_TRUE;
2577                                 }
2578                                 found_config = config;
2579                         }
2580                 } else {
2581                         uint64_t guid;
2582
2583                         /*
2584                          * Search for a pool by guid.
2585                          */
2586                         verify(nvlist_lookup_uint64(config,
2587                             ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
2588
2589                         if (guid == searchguid)
2590                                 found_config = config;
2591                 }
2592         }
2593
2594         /*
2595          * If we were searching for a specific pool, verify that we found a
2596          * pool, and then do the import.
2597          */
2598         if (argc != 0 && err == 0) {
2599                 if (found_config == NULL) {
2600                         (void) fprintf(stderr, gettext("cannot import '%s': "
2601                             "no such pool available\n"), argv[0]);
2602                         err = B_TRUE;
2603                 } else {
2604                         err |= do_import(found_config, argc == 1 ? NULL :
2605                             argv[1], mntopts, props, flags);
2606                 }
2607         }
2608
2609         /*
2610          * If we were just looking for pools, report an error if none were
2611          * found.
2612          */
2613         if (argc == 0 && first)
2614                 (void) fprintf(stderr,
2615                     gettext("no pools available to import\n"));
2616
2617 error:
2618         nvlist_free(props);
2619         nvlist_free(pools);
2620         nvlist_free(policy);
2621         if (searchdirs != NULL)
2622                 free(searchdirs);
2623         if (envdup != NULL)
2624                 free(envdup);
2625
2626         return (err ? 1 : 0);
2627 }
2628
2629 typedef struct iostat_cbdata {
2630         uint64_t cb_flags;
2631         int cb_name_flags;
2632         int cb_namewidth;
2633         int cb_iteration;
2634         char **cb_vdev_names; /* Only show these vdevs */
2635         unsigned int cb_vdev_names_count;
2636         boolean_t cb_verbose;
2637         boolean_t cb_literal;
2638         boolean_t cb_scripted;
2639         zpool_list_t *cb_list;
2640         vdev_cmd_data_list_t *vcdl;
2641 } iostat_cbdata_t;
2642
2643 /*  iostat labels */
2644 typedef struct name_and_columns {
2645         const char *name;       /* Column name */
2646         unsigned int columns;   /* Center name to this number of columns */
2647 } name_and_columns_t;
2648
2649 #define IOSTAT_MAX_LABELS       11      /* Max number of labels on one line */
2650
2651 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
2652 {
2653         [IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
2654             {NULL}},
2655         [IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
2656             {"asyncq_wait", 2}, {"scrub"}},
2657         [IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
2658             {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
2659             {NULL}},
2660         [IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2},
2661             {"sync_queue", 2}, {"async_queue", 2}, {NULL}},
2662         [IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
2663             {"async_read", 2}, {"async_write", 2}, {"scrub", 2}, {NULL}},
2664
2665 };
2666
2667 /* Shorthand - if "columns" field not set, default to 1 column */
2668 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
2669 {
2670         [IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
2671             {"write"}, {NULL}},
2672         [IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
2673             {"write"}, {"read"}, {"write"}, {"wait"}, {NULL}},
2674         [IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
2675             {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
2676         [IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
2677             {"write"}, {"read"}, {"write"}, {"scrub"}, {NULL}},
2678         [IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
2679             {"ind"}, {"agg"}, {"ind"}, {"agg"}, {NULL}},
2680 };
2681
2682 static const char *histo_to_title[] = {
2683         [IOS_L_HISTO] = "latency",
2684         [IOS_RQ_HISTO] = "req_size",
2685 };
2686
2687 /*
2688  * Return the number of labels in a null-terminated name_and_columns_t
2689  * array.
2690  *
2691  */
2692 static unsigned int
2693 label_array_len(const name_and_columns_t *labels)
2694 {
2695         int i = 0;
2696
2697         while (labels[i].name)
2698                 i++;
2699
2700         return (i);
2701 }
2702
2703 /*
2704  * Return the number of strings in a null-terminated string array.
2705  * For example:
2706  *
2707  *     const char foo[] = {"bar", "baz", NULL}
2708  *
2709  * returns 2
2710  */
2711 static uint64_t
2712 str_array_len(const char *array[])
2713 {
2714         uint64_t i = 0;
2715         while (array[i])
2716                 i++;
2717
2718         return (i);
2719 }
2720
2721
2722 /*
2723  * Return a default column width for default/latency/queue columns. This does
2724  * not include histograms, which have their columns autosized.
2725  */
2726 static unsigned int
2727 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
2728 {
2729         unsigned long column_width = 5; /* Normal niceprint */
2730         static unsigned long widths[] = {
2731                 /*
2732                  * Choose some sane default column sizes for printing the
2733                  * raw numbers.
2734                  */
2735                 [IOS_DEFAULT] = 15, /* 1PB capacity */
2736                 [IOS_LATENCY] = 10, /* 1B ns = 10sec */
2737                 [IOS_QUEUES] = 6,   /* 1M queue entries */
2738         };
2739
2740         if (cb->cb_literal)
2741                 column_width = widths[type];
2742
2743         return (column_width);
2744 }
2745
2746 /*
2747  * Print the column labels, i.e:
2748  *
2749  *   capacity     operations     bandwidth
2750  * alloc   free   read  write   read  write  ...
2751  *
2752  * If force_column_width is set, use it for the column width.  If not set, use
2753  * the default column width.
2754  */
2755 void
2756 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
2757     const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
2758 {
2759         int i, idx, s;
2760         unsigned int text_start, rw_column_width, spaces_to_end;
2761         uint64_t flags = cb->cb_flags;
2762         uint64_t f;
2763         unsigned int column_width = force_column_width;
2764
2765         /* For each bit set in flags */
2766         for (f = flags; f; f &= ~(1ULL << idx)) {
2767                 idx = lowbit64(f) - 1;
2768                 if (!force_column_width)
2769                         column_width = default_column_width(cb, idx);
2770                 /* Print our top labels centered over "read  write" label. */
2771                 for (i = 0; i < label_array_len(labels[idx]); i++) {
2772                         const char *name = labels[idx][i].name;
2773                         /*
2774                          * We treat labels[][].columns == 0 as shorthand
2775                          * for one column.  It makes writing out the label
2776                          * tables more concise.
2777                          */
2778                         unsigned int columns = MAX(1, labels[idx][i].columns);
2779                         unsigned int slen = strlen(name);
2780
2781                         rw_column_width = (column_width * columns) +
2782                             (2 * (columns - 1));
2783
2784                         text_start = (int)((rw_column_width)/columns -
2785                             slen/columns);
2786
2787                         printf("  ");   /* Two spaces between columns */
2788
2789                         /* Space from beginning of column to label */
2790                         for (s = 0; s < text_start; s++)
2791                                 printf(" ");
2792
2793                         printf("%s", name);
2794
2795                         /* Print space after label to end of column */
2796                         spaces_to_end = rw_column_width - text_start - slen;
2797                         for (s = 0; s < spaces_to_end; s++)
2798                                 printf(" ");
2799
2800                 }
2801         }
2802         printf("\n");
2803 }
2804
2805 /*
2806  * Utility function to print out a line of dashes like:
2807  *
2808  *      --------------------------------  -----  -----  -----  -----  -----
2809  *
2810  * ...or a dashed named-row line like:
2811  *
2812  *      logs                                  -      -      -      -      -
2813  *
2814  * @cb:                         iostat data
2815  *
2816  * @force_column_width          If non-zero, use the value as the column width.
2817  *                              Otherwise use the default column widths.
2818  *
2819  * @name:                       Print a dashed named-row line starting
2820  *                              with @name.  Otherwise, print a regular
2821  *                              dashed line.
2822  */
2823 static void
2824 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
2825     const char *name)
2826 {
2827         int i;
2828         unsigned int namewidth;
2829         uint64_t flags = cb->cb_flags;
2830         uint64_t f;
2831         int idx;
2832         const name_and_columns_t *labels;
2833         const char *title;
2834
2835
2836         if (cb->cb_flags & IOS_ANYHISTO_M) {
2837                 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
2838         } else if (cb->cb_vdev_names_count) {
2839                 title = "vdev";
2840         } else  {
2841                 title = "pool";
2842         }
2843
2844         namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
2845             name ? strlen(name) : 0);
2846
2847
2848         if (name) {
2849                 printf("%-*s", namewidth, name);
2850         } else {
2851                 for (i = 0; i < namewidth; i++)
2852                         (void) printf("-");
2853         }
2854
2855         /* For each bit in flags */
2856         for (f = flags; f; f &= ~(1ULL << idx)) {
2857                 unsigned int column_width;
2858                 idx = lowbit64(f) - 1;
2859                 if (force_column_width)
2860                         column_width = force_column_width;
2861                 else
2862                         column_width = default_column_width(cb, idx);
2863
2864                 labels = iostat_bottom_labels[idx];
2865                 for (i = 0; i < label_array_len(labels); i++) {
2866                         if (name)
2867                                 printf("  %*s-", column_width - 1, " ");
2868                         else
2869                                 printf("  %.*s", column_width,
2870                                     "--------------------");
2871                 }
2872         }
2873         printf("\n");
2874 }
2875
2876
2877 static void
2878 print_iostat_separator_impl(iostat_cbdata_t *cb,
2879     unsigned int force_column_width)
2880 {
2881         print_iostat_dashes(cb, force_column_width, NULL);
2882 }
2883
2884 static void
2885 print_iostat_separator(iostat_cbdata_t *cb)
2886 {
2887         print_iostat_separator_impl(cb, 0);
2888 }
2889
2890 static void
2891 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
2892     const char *histo_vdev_name)
2893 {
2894         unsigned int namewidth;
2895         const char *title;
2896
2897         if (cb->cb_flags & IOS_ANYHISTO_M) {
2898                 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
2899         } else if (cb->cb_vdev_names_count) {
2900                 title = "vdev";
2901         } else  {
2902                 title = "pool";
2903         }
2904
2905         namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
2906             histo_vdev_name ? strlen(histo_vdev_name) : 0);
2907
2908         if (histo_vdev_name)
2909                 printf("%-*s", namewidth, histo_vdev_name);
2910         else
2911                 printf("%*s", namewidth, "");
2912
2913
2914         print_iostat_labels(cb, force_column_width, iostat_top_labels);
2915
2916         printf("%-*s", namewidth, title);
2917
2918         print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
2919
2920         print_iostat_separator_impl(cb, force_column_width);
2921 }
2922
2923 static void
2924 print_iostat_header(iostat_cbdata_t *cb)
2925 {
2926         print_iostat_header_impl(cb, 0, NULL);
2927 }
2928
2929
2930 /*
2931  * Display a single statistic.
2932  */
2933 static void
2934 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
2935     unsigned int column_size, boolean_t scripted)
2936 {
2937         char buf[64];
2938
2939         zfs_nicenum_format(value, buf, sizeof (buf), format);
2940
2941         if (scripted)
2942                 printf("\t%s", buf);
2943         else
2944                 printf("  %*s", column_size, buf);
2945 }
2946
2947 /*
2948  * Calculate the default vdev stats
2949  *
2950  * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
2951  * stats into calcvs.
2952  */
2953 static void
2954 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
2955     vdev_stat_t *calcvs)
2956 {
2957         int i;
2958
2959         memcpy(calcvs, newvs, sizeof (*calcvs));
2960         for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
2961                 calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
2962
2963         for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
2964                 calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
2965 }
2966
2967 /*
2968  * Internal representation of the extended iostats data.
2969  *
2970  * The extended iostat stats are exported in nvlists as either uint64_t arrays
2971  * or single uint64_t's.  We make both look like arrays to make them easier
2972  * to process.  In order to make single uint64_t's look like arrays, we set
2973  * __data to the stat data, and then set *data = &__data with count = 1.  Then,
2974  * we can just use *data and count.
2975  */
2976 struct stat_array {
2977         uint64_t *data;
2978         uint_t count;   /* Number of entries in data[] */
2979         uint64_t __data; /* Only used when data is a single uint64_t */
2980 };
2981
2982 static uint64_t
2983 stat_histo_max(struct stat_array *nva, unsigned int len)
2984 {
2985         uint64_t max = 0;
2986         int i;
2987         for (i = 0; i < len; i++)
2988                 max = MAX(max, array64_max(nva[i].data, nva[i].count));
2989
2990         return (max);
2991 }
2992
2993 /*
2994  * Helper function to lookup a uint64_t array or uint64_t value and store its
2995  * data as a stat_array.  If the nvpair is a single uint64_t value, then we make
2996  * it look like a one element array to make it easier to process.
2997  */
2998 static int
2999 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
3000     struct stat_array *nva)
3001 {
3002         nvpair_t *tmp;
3003         int ret;
3004
3005         verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
3006         switch (nvpair_type(tmp)) {
3007         case DATA_TYPE_UINT64_ARRAY:
3008                 ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
3009                 break;
3010         case DATA_TYPE_UINT64:
3011                 ret = nvpair_value_uint64(tmp, &nva->__data);
3012                 nva->data = &nva->__data;
3013                 nva->count = 1;
3014                 break;
3015         default:
3016                 /* Not a uint64_t */
3017                 ret = EINVAL;
3018                 break;
3019         }
3020
3021         return (ret);
3022 }
3023
3024 /*
3025  * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
3026  * subtract them, and return the results in a newly allocated stat_array.
3027  * You must free the returned array after you are done with it with
3028  * free_calc_stats().
3029  *
3030  * Additionally, you can set "oldnv" to NULL if you simply want the newnv
3031  * values.
3032  */
3033 static struct stat_array *
3034 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
3035     nvlist_t *newnv)
3036 {
3037         nvlist_t *oldnvx = NULL, *newnvx;
3038         struct stat_array *oldnva, *newnva, *calcnva;
3039         int i, j;
3040         unsigned int alloc_size = (sizeof (struct stat_array)) * len;
3041
3042         /* Extract our extended stats nvlist from the main list */
3043         verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
3044             &newnvx) == 0);
3045         if (oldnv) {
3046                 verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
3047                     &oldnvx) == 0);
3048         }
3049
3050         newnva = safe_malloc(alloc_size);
3051         oldnva = safe_malloc(alloc_size);
3052         calcnva = safe_malloc(alloc_size);
3053
3054         for (j = 0; j < len; j++) {
3055                 verify(nvpair64_to_stat_array(newnvx, names[j],
3056                     &newnva[j]) == 0);
3057                 calcnva[j].count = newnva[j].count;
3058                 alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
3059                 calcnva[j].data = safe_malloc(alloc_size);
3060                 memcpy(calcnva[j].data, newnva[j].data, alloc_size);
3061
3062                 if (oldnvx) {
3063                         verify(nvpair64_to_stat_array(oldnvx, names[j],
3064                             &oldnva[j]) == 0);
3065                         for (i = 0; i < oldnva[j].count; i++)
3066                                 calcnva[j].data[i] -= oldnva[j].data[i];
3067                 }
3068         }
3069         free(newnva);
3070         free(oldnva);
3071         return (calcnva);
3072 }
3073
3074 static void
3075 free_calc_stats(struct stat_array *nva, unsigned int len)
3076 {
3077         int i;
3078         for (i = 0; i < len; i++)
3079                 free(nva[i].data);
3080
3081         free(nva);
3082 }
3083
3084 static void
3085 print_iostat_histo(struct stat_array *nva, unsigned int len,
3086     iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
3087     double scale)
3088 {
3089         int i, j;
3090         char buf[6];
3091         uint64_t val;
3092         enum zfs_nicenum_format format;
3093         unsigned int buckets;
3094         unsigned int start_bucket;
3095
3096         if (cb->cb_literal)
3097                 format = ZFS_NICENUM_RAW;
3098         else
3099                 format = ZFS_NICENUM_1024;
3100
3101         /* All these histos are the same size, so just use nva[0].count */
3102         buckets = nva[0].count;
3103
3104         if (cb->cb_flags & IOS_RQ_HISTO_M) {
3105                 /* Start at 512 - req size should never be lower than this */
3106                 start_bucket = 9;
3107         } else {
3108                 start_bucket = 0;
3109         }
3110
3111         for (j = start_bucket; j < buckets; j++) {
3112                 /* Print histogram bucket label */
3113                 if (cb->cb_flags & IOS_L_HISTO_M) {
3114                         /* Ending range of this bucket */
3115                         val = (1UL << (j + 1)) - 1;
3116                         zfs_nicetime(val, buf, sizeof (buf));
3117                 } else {
3118                         /* Request size (starting range of bucket) */
3119                         val = (1UL << j);
3120                         zfs_nicenum(val, buf, sizeof (buf));
3121                 }
3122
3123                 if (cb->cb_scripted)
3124                         printf("%llu", (u_longlong_t)val);
3125                 else
3126                         printf("%-*s", namewidth, buf);
3127
3128                 /* Print the values on the line */
3129                 for (i = 0; i < len; i++) {
3130                         print_one_stat(nva[i].data[j] * scale, format,
3131                             column_width, cb->cb_scripted);
3132                 }
3133                 printf("\n");
3134         }
3135 }
3136
3137 static void
3138 print_solid_separator(unsigned int length)
3139 {
3140         while (length--)
3141                 printf("-");
3142         printf("\n");
3143 }
3144
3145 static void
3146 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
3147     nvlist_t *newnv, double scale, const char *name)
3148 {
3149         unsigned int column_width;
3150         unsigned int namewidth;
3151         unsigned int entire_width;
3152         enum iostat_type type;
3153         struct stat_array *nva;
3154         const char **names;
3155         unsigned int names_len;
3156
3157         /* What type of histo are we? */
3158         type = IOS_HISTO_IDX(cb->cb_flags);
3159
3160         /* Get NULL-terminated array of nvlist names for our histo */
3161         names = vsx_type_to_nvlist[type];
3162         names_len = str_array_len(names); /* num of names */
3163
3164         nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
3165
3166         if (cb->cb_literal) {
3167                 column_width = MAX(5,
3168                     (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
3169         } else {
3170                 column_width = 5;
3171         }
3172
3173         namewidth = MAX(cb->cb_namewidth,
3174             strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
3175
3176         /*
3177          * Calculate the entire line width of what we're printing.  The
3178          * +2 is for the two spaces between columns:
3179          */
3180         /*       read  write                            */
3181         /*      -----  -----                            */
3182         /*      |___|  <---------- column_width         */
3183         /*                                              */
3184         /*      |__________|  <--- entire_width         */
3185         /*                                              */
3186         entire_width = namewidth + (column_width + 2) *
3187             label_array_len(iostat_bottom_labels[type]);
3188
3189         if (cb->cb_scripted)
3190                 printf("%s\n", name);
3191         else
3192                 print_iostat_header_impl(cb, column_width, name);
3193
3194         print_iostat_histo(nva, names_len, cb, column_width,
3195             namewidth, scale);
3196
3197         free_calc_stats(nva, names_len);
3198         if (!cb->cb_scripted)
3199                 print_solid_separator(entire_width);
3200 }
3201
3202 /*
3203  * Calculate the average latency of a power-of-two latency histogram
3204  */
3205 static uint64_t
3206 single_histo_average(uint64_t *histo, unsigned int buckets)
3207 {
3208         int i;
3209         uint64_t count = 0, total = 0;
3210
3211         for (i = 0; i < buckets; i++) {
3212                 /*
3213                  * Our buckets are power-of-two latency ranges.  Use the
3214                  * midpoint latency of each bucket to calculate the average.
3215                  * For example:
3216                  *
3217                  * Bucket          Midpoint
3218                  * 8ns-15ns:       12ns
3219                  * 16ns-31ns:      24ns
3220                  * ...
3221                  */
3222                 if (histo[i] != 0) {
3223                         total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
3224                         count += histo[i];
3225                 }
3226         }
3227
3228         /* Prevent divide by zero */
3229         return (count == 0 ? 0 : total / count);
3230 }
3231
3232 static void
3233 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *oldnv,
3234     nvlist_t *newnv, double scale)
3235 {
3236         int i;
3237         uint64_t val;
3238         const char *names[] = {
3239                 ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
3240                 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
3241                 ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
3242                 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
3243                 ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
3244                 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
3245                 ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
3246                 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
3247                 ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
3248                 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
3249         };
3250
3251         struct stat_array *nva;
3252
3253         unsigned int column_width = default_column_width(cb, IOS_QUEUES);
3254         enum zfs_nicenum_format format;
3255
3256         nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
3257
3258         if (cb->cb_literal)
3259                 format = ZFS_NICENUM_RAW;
3260         else
3261                 format = ZFS_NICENUM_1024;
3262
3263         for (i = 0; i < ARRAY_SIZE(names); i++) {
3264                 val = nva[i].data[0] * scale;
3265                 print_one_stat(val, format, column_width, cb->cb_scripted);
3266         }
3267
3268         free_calc_stats(nva, ARRAY_SIZE(names));
3269 }
3270
3271 static void
3272 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
3273     nvlist_t *newnv, double scale)
3274 {
3275         int i;
3276         uint64_t val;
3277         const char *names[] = {
3278                 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
3279                 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
3280                 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
3281                 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
3282                 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
3283                 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
3284                 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
3285                 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
3286                 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
3287         };
3288         struct stat_array *nva;
3289
3290         unsigned int column_width = default_column_width(cb, IOS_LATENCY);
3291         enum zfs_nicenum_format format;
3292
3293         nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
3294
3295         if (cb->cb_literal)
3296                 format = ZFS_NICENUM_RAW;
3297         else
3298                 format = ZFS_NICENUM_TIME;
3299
3300         /* Print our avg latencies on the line */
3301         for (i = 0; i < ARRAY_SIZE(names); i++) {
3302                 /* Compute average latency for a latency histo */
3303                 val = single_histo_average(nva[i].data, nva[i].count) * scale;
3304                 print_one_stat(val, format, column_width, cb->cb_scripted);
3305         }
3306         free_calc_stats(nva, ARRAY_SIZE(names));
3307 }
3308
3309 /*
3310  * Print default statistics (capacity/operations/bandwidth)
3311  */
3312 static void
3313 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
3314 {
3315         unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
3316         enum zfs_nicenum_format format;
3317         char na;        /* char to print for "not applicable" values */
3318
3319         if (cb->cb_literal) {
3320                 format = ZFS_NICENUM_RAW;
3321                 na = '0';
3322         } else {
3323                 format = ZFS_NICENUM_1024;
3324                 na = '-';
3325         }
3326
3327         /* only toplevel vdevs have capacity stats */
3328         if (vs->vs_space == 0) {
3329                 if (cb->cb_scripted)
3330                         printf("\t%c\t%c", na, na);
3331                 else
3332                         printf("  %*c  %*c", column_width, na, column_width,
3333                             na);
3334         } else {
3335                 print_one_stat(vs->vs_alloc, format, column_width,
3336                     cb->cb_scripted);
3337                 print_one_stat(vs->vs_space - vs->vs_alloc, format,
3338                     column_width, cb->cb_scripted);
3339         }
3340
3341         print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
3342             format, column_width, cb->cb_scripted);
3343         print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
3344             format, column_width, cb->cb_scripted);
3345         print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
3346             format, column_width, cb->cb_scripted);
3347         print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
3348             format, column_width, cb->cb_scripted);
3349 }
3350
3351 /*
3352  * Print out all the statistics for the given vdev.  This can either be the
3353  * toplevel configuration, or called recursively.  If 'name' is NULL, then this
3354  * is a verbose output, and we don't want to display the toplevel pool stats.
3355  *
3356  * Returns the number of stat lines printed.
3357  */
3358 unsigned int
3359 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
3360     nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
3361 {
3362         nvlist_t **oldchild, **newchild;
3363         uint_t c, children;
3364         vdev_stat_t *oldvs, *newvs, *calcvs;
3365         vdev_stat_t zerovs = { 0 };
3366         char *vname;
3367         int i;
3368         int ret = 0;
3369         uint64_t tdelta;
3370         double scale;
3371
3372         calcvs = safe_malloc(sizeof (*calcvs));
3373
3374         if (oldnv != NULL) {
3375                 verify(nvlist_lookup_uint64_array(oldnv,
3376                     ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
3377         } else {
3378                 oldvs = &zerovs;
3379         }
3380
3381         /* Do we only want to see a specific vdev? */
3382         for (i = 0; i < cb->cb_vdev_names_count; i++) {
3383                 /* Yes we do.  Is this the vdev? */
3384                 if (strcmp(name, cb->cb_vdev_names[i]) == 0) {
3385                         /*
3386                          * This is our vdev.  Since it is the only vdev we
3387                          * will be displaying, make depth = 0 so that it
3388                          * doesn't get indented.
3389                          */
3390                         depth = 0;
3391                         break;
3392                 }
3393         }
3394
3395         if (cb->cb_vdev_names_count && (i == cb->cb_vdev_names_count)) {
3396                 /* Couldn't match the name */
3397                 goto children;
3398         }
3399
3400
3401         verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
3402             (uint64_t **)&newvs, &c) == 0);
3403
3404         /*
3405          * Print the vdev name unless it's is a histogram.  Histograms
3406          * display the vdev name in the header itself.
3407          */
3408         if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
3409                 if (cb->cb_scripted) {
3410                         printf("%s", name);
3411                 } else {
3412                         if (strlen(name) + depth > cb->cb_namewidth)
3413                                 (void) printf("%*s%s", depth, "", name);
3414                         else
3415                                 (void) printf("%*s%s%*s", depth, "", name,
3416                                     (int)(cb->cb_namewidth - strlen(name) -
3417                                     depth), "");
3418                 }
3419         }
3420
3421         /* Calculate our scaling factor */
3422         tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
3423         if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
3424                 /*
3425                  * If we specify printing histograms with no time interval, then
3426                  * print the histogram numbers over the entire lifetime of the
3427                  * vdev.
3428                  */
3429                 scale = 1;
3430         } else {
3431                 if (tdelta == 0)
3432                         scale = 1.0;
3433                 else
3434                         scale = (double)NANOSEC / tdelta;
3435         }
3436
3437         if (cb->cb_flags & IOS_DEFAULT_M) {
3438                 calc_default_iostats(oldvs, newvs, calcvs);
3439                 print_iostat_default(calcvs, cb, scale);
3440         }
3441         if (cb->cb_flags & IOS_LATENCY_M)
3442                 print_iostat_latency(cb, oldnv, newnv, scale);
3443         if (cb->cb_flags & IOS_QUEUES_M)
3444                 print_iostat_queues(cb, oldnv, newnv, scale);
3445         if (cb->cb_flags & IOS_ANYHISTO_M) {
3446                 printf("\n");
3447                 print_iostat_histos(cb, oldnv, newnv, scale, name);
3448         }
3449
3450         if (cb->vcdl != NULL) {
3451                 char *path;
3452                 if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
3453                     &path) == 0) {
3454                         if (!(cb->cb_flags & IOS_ANYHISTO_M))
3455                                 printf("  ");
3456                         zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
3457                         if (cb->cb_flags & IOS_ANYHISTO_M)
3458                                 printf("\n");
3459                 }
3460         }
3461
3462         if (!(cb->cb_flags & IOS_ANYHISTO_M))
3463                 printf("\n");
3464
3465         ret++;
3466
3467 children:
3468
3469         free(calcvs);
3470
3471         if (!cb->cb_verbose)
3472                 return (ret);
3473
3474         if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
3475             &newchild, &children) != 0)
3476                 return (ret);
3477
3478         if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
3479             &oldchild, &c) != 0)
3480                 return (ret);
3481
3482         for (c = 0; c < children; c++) {
3483                 uint64_t ishole = B_FALSE, islog = B_FALSE;
3484
3485                 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
3486                     &ishole);
3487
3488                 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
3489                     &islog);
3490
3491                 if (ishole || islog)
3492                         continue;
3493
3494                 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3495                     cb->cb_name_flags);
3496                 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
3497                     newchild[c], cb, depth + 2);
3498                 free(vname);
3499         }
3500
3501         /*
3502          * Log device section
3503          */
3504
3505         if (num_logs(newnv) > 0) {
3506                 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
3507                     !cb->cb_vdev_names) {
3508                         print_iostat_dashes(cb, 0, "logs");
3509                 }
3510
3511                 for (c = 0; c < children; c++) {
3512                         uint64_t islog = B_FALSE;
3513                         (void) nvlist_lookup_uint64(newchild[c],
3514                             ZPOOL_CONFIG_IS_LOG, &islog);
3515
3516                         if (islog) {
3517                                 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3518                                     cb->cb_name_flags);
3519                                 ret += print_vdev_stats(zhp, vname, oldnv ?
3520                                     oldchild[c] : NULL, newchild[c],
3521                                     cb, depth + 2);
3522                                 free(vname);
3523                         }
3524                 }
3525
3526         }
3527
3528         /*
3529          * Include level 2 ARC devices in iostat output
3530          */
3531         if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
3532             &newchild, &children) != 0)
3533                 return (ret);
3534
3535         if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
3536             &oldchild, &c) != 0)
3537                 return (ret);
3538
3539         if (children > 0) {
3540                 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
3541                     !cb->cb_vdev_names) {
3542                         print_iostat_dashes(cb, 0, "cache");
3543                 }
3544
3545                 for (c = 0; c < children; c++) {
3546                         vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3547                             cb->cb_name_flags);
3548                         ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
3549                             : NULL, newchild[c], cb, depth + 2);
3550                         free(vname);
3551                 }
3552         }
3553
3554         return (ret);
3555 }
3556
3557 static int
3558 refresh_iostat(zpool_handle_t *zhp, void *data)
3559 {
3560         iostat_cbdata_t *cb = data;
3561         boolean_t missing;
3562
3563         /*
3564          * If the pool has disappeared, remove it from the list and continue.
3565          */
3566         if (zpool_refresh_stats(zhp, &missing) != 0)
3567                 return (-1);
3568
3569         if (missing)
3570                 pool_list_remove(cb->cb_list, zhp);
3571
3572         return (0);
3573 }
3574
3575 /*
3576  * Callback to print out the iostats for the given pool.
3577  */
3578 int
3579 print_iostat(zpool_handle_t *zhp, void *data)
3580 {
3581         iostat_cbdata_t *cb = data;
3582         nvlist_t *oldconfig, *newconfig;
3583         nvlist_t *oldnvroot, *newnvroot;
3584         int ret;
3585
3586         newconfig = zpool_get_config(zhp, &oldconfig);
3587
3588         if (cb->cb_iteration == 1)
3589                 oldconfig = NULL;
3590
3591         verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
3592             &newnvroot) == 0);
3593
3594         if (oldconfig == NULL)
3595                 oldnvroot = NULL;
3596         else
3597                 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
3598                     &oldnvroot) == 0);
3599
3600         ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
3601             cb, 0);
3602         if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
3603             !cb->cb_scripted && cb->cb_verbose && !cb->cb_vdev_names_count) {
3604                 print_iostat_separator(cb);
3605         }
3606
3607         return (ret);
3608 }
3609
3610 static int
3611 get_columns(void)
3612 {
3613         struct winsize ws;
3614         int columns = 80;
3615         int error;
3616
3617         if (isatty(STDOUT_FILENO)) {
3618                 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
3619                 if (error == 0)
3620                         columns = ws.ws_col;
3621         } else {
3622                 columns = 999;
3623         }
3624
3625         return (columns);
3626 }
3627
3628 int
3629 get_namewidth(zpool_handle_t *zhp, void *data)
3630 {
3631         iostat_cbdata_t *cb = data;
3632         nvlist_t *config, *nvroot;
3633         int columns;
3634
3635         if ((config = zpool_get_config(zhp, NULL)) != NULL) {
3636                 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3637                     &nvroot) == 0);
3638                 unsigned int poolname_len = strlen(zpool_get_name(zhp));
3639                 if (!cb->cb_verbose)
3640                         cb->cb_namewidth = poolname_len;
3641                 else
3642                         cb->cb_namewidth = MAX(poolname_len,
3643                             max_width(zhp, nvroot, 0, cb->cb_namewidth,
3644                             cb->cb_name_flags));
3645         }
3646         /*
3647          * The width must be at least 10, but may be as large as the
3648          * column width - 42 so that we can still fit in one line.
3649          */
3650         columns = get_columns();
3651
3652         if (cb->cb_namewidth < 10)
3653                 cb->cb_namewidth = 10;
3654         if (cb->cb_namewidth > columns - 42)
3655                 cb->cb_namewidth = columns - 42;
3656
3657         return (0);
3658 }
3659
3660 /*
3661  * Parse the input string, get the 'interval' and 'count' value if there is one.
3662  */
3663 static void
3664 get_interval_count(int *argcp, char **argv, float *iv,
3665     unsigned long *cnt)
3666 {
3667         float interval = 0;
3668         unsigned long count = 0;
3669         int argc = *argcp;
3670
3671         /*
3672          * Determine if the last argument is an integer or a pool name
3673          */
3674         if (argc > 0 && isnumber(argv[argc - 1])) {
3675                 char *end;
3676
3677                 errno = 0;
3678                 interval = strtof(argv[argc - 1], &end);
3679
3680                 if (*end == '\0' && errno == 0) {
3681                         if (interval == 0) {
3682                                 (void) fprintf(stderr, gettext("interval "
3683                                     "cannot be zero\n"));
3684                                 usage(B_FALSE);
3685                         }
3686                         /*
3687                          * Ignore the last parameter
3688                          */
3689                         argc--;
3690                 } else {
3691                         /*
3692                          * If this is not a valid number, just plow on.  The
3693                          * user will get a more informative error message later
3694                          * on.
3695                          */
3696                         interval = 0;
3697                 }
3698         }
3699
3700         /*
3701          * If the last argument is also an integer, then we have both a count
3702          * and an interval.
3703          */
3704         if (argc > 0 && isnumber(argv[argc - 1])) {
3705                 char *end;
3706
3707                 errno = 0;
3708                 count = interval;
3709                 interval = strtof(argv[argc - 1], &end);
3710
3711                 if (*end == '\0' && errno == 0) {
3712                         if (interval == 0) {
3713                                 (void) fprintf(stderr, gettext("interval "
3714                                     "cannot be zero\n"));
3715                                 usage(B_FALSE);
3716                         }
3717
3718                         /*
3719                          * Ignore the last parameter
3720                          */
3721                         argc--;
3722                 } else {
3723                         interval = 0;
3724                 }
3725         }
3726
3727         *iv = interval;
3728         *cnt = count;
3729         *argcp = argc;
3730 }
3731
3732 static void
3733 get_timestamp_arg(char c)
3734 {
3735         if (c == 'u')
3736                 timestamp_fmt = UDATE;
3737         else if (c == 'd')
3738                 timestamp_fmt = DDATE;
3739         else
3740                 usage(B_FALSE);
3741 }
3742
3743 /*
3744  * Return stat flags that are supported by all pools by both the module and
3745  * zpool iostat.  "*data" should be initialized to all 0xFFs before running.
3746  * It will get ANDed down until only the flags that are supported on all pools
3747  * remain.
3748  */
3749 static int
3750 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
3751 {
3752         uint64_t *mask = data;
3753         nvlist_t *config, *nvroot, *nvx;
3754         uint64_t flags = 0;
3755         int i, j;
3756
3757         config = zpool_get_config(zhp, NULL);
3758         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3759             &nvroot) == 0);
3760
3761         /* Default stats are always supported, but for completeness.. */
3762         if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
3763                 flags |= IOS_DEFAULT_M;
3764
3765         /* Get our extended stats nvlist from the main list */
3766         if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
3767             &nvx) != 0) {
3768                 /*
3769                  * No extended stats; they're probably running an older
3770                  * module.  No big deal, we support that too.
3771                  */
3772                 goto end;
3773         }
3774
3775         /* For each extended stat, make sure all its nvpairs are supported */
3776         for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
3777                 if (!vsx_type_to_nvlist[j][0])
3778                         continue;
3779
3780                 /* Start off by assuming the flag is supported, then check */
3781                 flags |= (1ULL << j);
3782                 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
3783                         if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
3784                                 /* flag isn't supported */
3785                                 flags = flags & ~(1ULL  << j);
3786                                 break;
3787                         }
3788                 }
3789         }
3790 end:
3791         *mask = *mask & flags;
3792         return (0);
3793 }
3794
3795 /*
3796  * Return a bitmask of stats that are supported on all pools by both the module
3797  * and zpool iostat.
3798  */
3799 static uint64_t
3800 get_stat_flags(zpool_list_t *list)
3801 {
3802         uint64_t mask = -1;
3803
3804         /*
3805          * get_stat_flags_cb() will lop off bits from "mask" until only the
3806          * flags that are supported on all pools remain.
3807          */
3808         pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
3809         return (mask);
3810 }
3811
3812 /*
3813  * Return 1 if cb_data->cb_vdev_names[0] is this vdev's name, 0 otherwise.
3814  */
3815 static int
3816 is_vdev_cb(zpool_handle_t *zhp, nvlist_t *nv, void *cb_data)
3817 {
3818         iostat_cbdata_t *cb = cb_data;
3819         char *name = NULL;
3820         int ret = 0;
3821
3822         name = zpool_vdev_name(g_zfs, zhp, nv, cb->cb_name_flags);
3823
3824         if (strcmp(name, cb->cb_vdev_names[0]) == 0)
3825                 ret = 1; /* match */
3826         free(name);
3827
3828         return (ret);
3829 }
3830
3831 /*
3832  * Returns 1 if cb_data->cb_vdev_names[0] is a vdev name, 0 otherwise.
3833  */
3834 static int
3835 is_vdev(zpool_handle_t *zhp, void *cb_data)
3836 {
3837         return (for_each_vdev(zhp, is_vdev_cb, cb_data));
3838 }
3839
3840 /*
3841  * Check if vdevs are in a pool
3842  *
3843  * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
3844  * return 0.  If pool_name is NULL, then search all pools.
3845  */
3846 static int
3847 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
3848     iostat_cbdata_t *cb)
3849 {
3850         char **tmp_name;
3851         int ret = 0;
3852         int i;
3853         int pool_count = 0;
3854
3855         if ((argc == 0) || !*argv)
3856                 return (0);
3857
3858         if (pool_name)
3859                 pool_count = 1;
3860
3861         /* Temporarily hijack cb_vdev_names for a second... */
3862         tmp_name = cb->cb_vdev_names;
3863
3864         /* Go though our list of prospective vdev names */
3865         for (i = 0; i < argc; i++) {
3866                 cb->cb_vdev_names = argv + i;
3867
3868                 /* Is this name a vdev in our pools? */
3869                 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
3870                     is_vdev, cb);
3871                 if (!ret) {
3872                         /* No match */
3873                         break;
3874                 }
3875         }
3876
3877         cb->cb_vdev_names = tmp_name;
3878
3879         return (ret);
3880 }
3881
3882 static int
3883 is_pool_cb(zpool_handle_t *zhp, void *data)
3884 {
3885         char *name = data;
3886         if (strcmp(name, zpool_get_name(zhp)) == 0)
3887                 return (1);
3888
3889         return (0);
3890 }
3891
3892 /*
3893  * Do we have a pool named *name?  If so, return 1, otherwise 0.
3894  */
3895 static int
3896 is_pool(char *name)
3897 {
3898         return (for_each_pool(0, NULL, B_TRUE, NULL,  is_pool_cb, name));
3899 }
3900
3901 /* Are all our argv[] strings pool names?  If so return 1, 0 otherwise. */
3902 static int
3903 are_all_pools(int argc, char **argv)
3904 {
3905         if ((argc == 0) || !*argv)
3906                 return (0);
3907
3908         while (--argc >= 0)
3909                 if (!is_pool(argv[argc]))
3910                         return (0);
3911
3912         return (1);
3913 }
3914
3915 /*
3916  * Helper function to print out vdev/pool names we can't resolve.  Used for an
3917  * error message.
3918  */
3919 static void
3920 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
3921     iostat_cbdata_t *cb)
3922 {
3923         int i;
3924         char *name;
3925         char *str;
3926         for (i = 0; i < argc; i++) {
3927                 name = argv[i];
3928
3929                 if (is_pool(name))
3930                         str = gettext("pool");
3931                 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
3932                         str = gettext("vdev in this pool");
3933                 else if (are_vdevs_in_pool(1, &name, NULL, cb))
3934                         str = gettext("vdev in another pool");
3935                 else
3936                         str = gettext("unknown");
3937
3938                 fprintf(stderr, "\t%s (%s)\n", name, str);
3939         }
3940 }
3941
3942 /*
3943  * Same as get_interval_count(), but with additional checks to not misinterpret
3944  * guids as interval/count values.  Assumes VDEV_NAME_GUID is set in
3945  * cb.cb_name_flags.
3946  */
3947 static void
3948 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
3949     unsigned long *count, iostat_cbdata_t *cb)
3950 {
3951         char **tmpargv = argv;
3952         int argc_for_interval = 0;
3953
3954         /* Is the last arg an interval value?  Or a guid? */
3955         if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL, cb)) {
3956                 /*
3957                  * The last arg is not a guid, so it's probably an
3958                  * interval value.
3959                  */
3960                 argc_for_interval++;
3961
3962                 if (*argc >= 2 &&
3963                     !are_vdevs_in_pool(1, &argv[*argc - 2], NULL, cb)) {
3964                         /*
3965                          * The 2nd to last arg is not a guid, so it's probably
3966                          * an interval value.
3967                          */
3968                         argc_for_interval++;
3969                 }
3970         }
3971
3972         /* Point to our list of possible intervals */
3973         tmpargv = &argv[*argc - argc_for_interval];
3974
3975         *argc = *argc - argc_for_interval;
3976         get_interval_count(&argc_for_interval, tmpargv,
3977             interval, count);
3978 }
3979
3980 /*
3981  * Floating point sleep().  Allows you to pass in a floating point value for
3982  * seconds.
3983  */
3984 static void
3985 fsleep(float sec)
3986 {
3987         struct timespec req;
3988         req.tv_sec = floor(sec);
3989         req.tv_nsec = (sec - (float)req.tv_sec) * NANOSEC;
3990         nanosleep(&req, NULL);
3991 }
3992
3993
3994 /*
3995  * zpool iostat [-c CMD] [-ghHLpPvy] [[-lq]|[-r|-w]] [-n name] [-T d|u]
3996  *              [[ pool ...]|[pool vdev ...]|[vdev ...]]
3997  *              [interval [count]]
3998  *
3999  *      -c CMD  For each vdev, run command CMD
4000  *      -g      Display guid for individual vdev name.
4001  *      -L      Follow links when resolving vdev path name.
4002  *      -P      Display full path for vdev name.
4003  *      -v      Display statistics for individual vdevs
4004  *      -h      Display help
4005  *      -p      Display values in parsable (exact) format.
4006  *      -H      Scripted mode.  Don't display headers, and separate properties
4007  *              by a single tab.
4008  *      -l      Display average latency
4009  *      -q      Display queue depths
4010  *      -w      Display latency histograms
4011  *      -r      Display request size histogram
4012  *      -T      Display a timestamp in date(1) or Unix format
4013  *
4014  * This command can be tricky because we want to be able to deal with pool
4015  * creation/destruction as well as vdev configuration changes.  The bulk of this
4016  * processing is handled by the pool_list_* routines in zpool_iter.c.  We rely
4017  * on pool_list_update() to detect the addition of new pools.  Configuration
4018  * changes are all handled within libzfs.
4019  */
4020 int
4021 zpool_do_iostat(int argc, char **argv)
4022 {
4023         int c;
4024         int ret;
4025         int npools;
4026         float interval = 0;
4027         unsigned long count = 0;
4028         zpool_list_t *list;
4029         boolean_t verbose = B_FALSE;
4030         boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
4031         boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
4032         boolean_t omit_since_boot = B_FALSE;
4033         boolean_t guid = B_FALSE;
4034         boolean_t follow_links = B_FALSE;
4035         boolean_t full_name = B_FALSE;
4036         iostat_cbdata_t cb = { 0 };
4037         char *cmd = NULL;
4038
4039         /* Used for printing error message */
4040         const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
4041             [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
4042
4043         uint64_t unsupported_flags;
4044
4045         /* check options */
4046         while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwH")) != -1) {
4047                 switch (c) {
4048                 case 'c':
4049                         cmd = optarg;
4050                         break;
4051                 case 'g':
4052                         guid = B_TRUE;
4053                         break;
4054                 case 'L':
4055                         follow_links = B_TRUE;
4056                         break;
4057                 case 'P':
4058                         full_name = B_TRUE;
4059                         break;
4060                 case 'T':
4061                         get_timestamp_arg(*optarg);
4062                         break;
4063                 case 'v':
4064                         verbose = B_TRUE;
4065                         break;
4066                 case 'p':
4067                         parsable = B_TRUE;
4068                         break;
4069                 case 'l':
4070                         latency = B_TRUE;
4071                         break;
4072                 case 'q':
4073                         queues = B_TRUE;
4074                         break;
4075                 case 'H':
4076                         scripted = B_TRUE;
4077                         break;
4078                 case 'w':
4079                         l_histo = B_TRUE;
4080                         break;
4081                 case 'r':
4082                         rq_histo = B_TRUE;
4083                         break;
4084                 case 'y':
4085                         omit_since_boot = B_TRUE;
4086                         break;
4087                 case 'h':
4088                         usage(B_FALSE);
4089                         break;
4090                 case '?':
4091                         if (optopt == 'c') {
4092                                 fprintf(stderr,
4093                                     gettext("Missing CMD for -c\n"));
4094                         } else {
4095                                 fprintf(stderr,
4096                                     gettext("invalid option '%c'\n"), optopt);
4097                         }
4098                         usage(B_FALSE);
4099                 }
4100         }
4101
4102         argc -= optind;
4103         argv += optind;
4104
4105         cb.cb_literal = parsable;
4106         cb.cb_scripted = scripted;
4107
4108         if (guid)
4109                 cb.cb_name_flags |= VDEV_NAME_GUID;
4110         if (follow_links)
4111                 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
4112         if (full_name)
4113                 cb.cb_name_flags |= VDEV_NAME_PATH;
4114         cb.cb_iteration = 0;
4115         cb.cb_namewidth = 0;
4116         cb.cb_verbose = verbose;
4117
4118         /* Get our interval and count values (if any) */
4119         if (guid) {
4120                 get_interval_count_filter_guids(&argc, argv, &interval,
4121                     &count, &cb);
4122         } else {
4123                 get_interval_count(&argc, argv, &interval, &count);
4124         }
4125
4126         if (argc == 0) {
4127                 /* No args, so just print the defaults. */
4128         } else if (are_all_pools(argc, argv)) {
4129                 /* All the args are pool names */
4130         } else if (are_vdevs_in_pool(argc, argv, NULL, &cb)) {
4131                 /* All the args are vdevs */
4132                 cb.cb_vdev_names = argv;
4133                 cb.cb_vdev_names_count = argc;
4134                 argc = 0; /* No pools to process */
4135         } else if (are_all_pools(1, argv)) {
4136                 /* The first arg is a pool name */
4137                 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0], &cb)) {
4138                         /* ...and the rest are vdev names */
4139                         cb.cb_vdev_names = argv + 1;
4140                         cb.cb_vdev_names_count = argc - 1;
4141                         argc = 1; /* One pool to process */
4142                 } else {
4143                         fprintf(stderr, gettext("Expected either a list of "));
4144                         fprintf(stderr, gettext("pools, or list of vdevs in"));
4145                         fprintf(stderr, " \"%s\", ", argv[0]);
4146                         fprintf(stderr, gettext("but got:\n"));
4147                         error_list_unresolved_vdevs(argc - 1, argv + 1,
4148                             argv[0], &cb);
4149                         fprintf(stderr, "\n");
4150                         usage(B_FALSE);
4151                         return (1);
4152                 }
4153         } else {
4154                 /*
4155                  * The args don't make sense. The first arg isn't a pool name,
4156                  * nor are all the args vdevs.
4157                  */
4158                 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
4159                 fprintf(stderr, "\n");
4160                 return (1);
4161         }
4162
4163         if (cb.cb_vdev_names_count != 0) {
4164                 /*
4165                  * If user specified vdevs, it implies verbose.
4166                  */
4167                 cb.cb_verbose = B_TRUE;
4168         }
4169
4170         /*
4171          * Construct the list of all interesting pools.
4172          */
4173         ret = 0;
4174         if ((list = pool_list_get(argc, argv, NULL, &ret)) == NULL)
4175                 return (1);
4176
4177         if (pool_list_count(list) == 0 && argc != 0) {
4178                 pool_list_free(list);
4179                 return (1);
4180         }
4181
4182         if (pool_list_count(list) == 0 && interval == 0) {
4183                 pool_list_free(list);
4184                 (void) fprintf(stderr, gettext("no pools available\n"));
4185                 return (1);
4186         }
4187
4188         if ((l_histo || rq_histo) && (queues || latency)) {
4189                 pool_list_free(list);
4190                 (void) fprintf(stderr,
4191                     gettext("[-r|-w] isn't allowed with [-q|-l]\n"));
4192                 usage(B_FALSE);
4193                 return (1);
4194         }
4195
4196         if (l_histo && rq_histo) {
4197                 pool_list_free(list);
4198                 (void) fprintf(stderr,
4199                     gettext("Only one of [-r|-w] can be passed at a time\n"));
4200                 usage(B_FALSE);
4201                 return (1);
4202         }
4203
4204         /*
4205          * Enter the main iostat loop.
4206          */
4207         cb.cb_list = list;
4208
4209         if (l_histo) {
4210                 /*
4211                  * Histograms tables look out of place when you try to display
4212                  * them with the other stats, so make a rule that you can only
4213                  * print histograms by themselves.
4214                  */
4215                 cb.cb_flags = IOS_L_HISTO_M;
4216         } else if (rq_histo) {
4217                 cb.cb_flags = IOS_RQ_HISTO_M;
4218         } else {
4219                 cb.cb_flags = IOS_DEFAULT_M;
4220                 if (latency)
4221                         cb.cb_flags |= IOS_LATENCY_M;
4222                 if (queues)
4223                         cb.cb_flags |= IOS_QUEUES_M;
4224         }
4225
4226         /*
4227          * See if the module supports all the stats we want to display.
4228          */
4229         unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
4230         if (unsupported_flags) {
4231                 uint64_t f;
4232                 int idx;
4233                 fprintf(stderr,
4234                     gettext("The loaded zfs module doesn't support:"));
4235
4236                 /* for each bit set in unsupported_flags */
4237                 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
4238                         idx = lowbit64(f) - 1;
4239                         fprintf(stderr, " -%c", flag_to_arg[idx]);
4240                 }
4241
4242                 fprintf(stderr, ".  Try running a newer module.\n");
4243                 pool_list_free(list);
4244
4245                 return (1);
4246         }
4247
4248         for (;;) {
4249                 if ((npools = pool_list_count(list)) == 0)
4250                         (void) fprintf(stderr, gettext("no pools available\n"));
4251                 else {
4252                         /*
4253                          * If this is the first iteration and -y was supplied
4254                          * we skip any printing.
4255                          */
4256                         boolean_t skip = (omit_since_boot &&
4257                             cb.cb_iteration == 0);
4258
4259                         /*
4260                          * Refresh all statistics.  This is done as an
4261                          * explicit step before calculating the maximum name
4262                          * width, so that any * configuration changes are
4263                          * properly accounted for.
4264                          */
4265                         (void) pool_list_iter(list, B_FALSE, refresh_iostat,
4266                             &cb);
4267
4268                         /*
4269                          * Iterate over all pools to determine the maximum width
4270                          * for the pool / device name column across all pools.
4271                          */
4272                         cb.cb_namewidth = 0;
4273                         (void) pool_list_iter(list, B_FALSE, get_namewidth,
4274                             &cb);
4275
4276                         if (timestamp_fmt != NODATE)
4277                                 print_timestamp(timestamp_fmt);
4278
4279                         /*
4280                          * If it's the first time and we're not skipping it,
4281                          * or either skip or verbose mode, print the header.
4282                          *
4283                          * The histogram code explicitly prints its header on
4284                          * every vdev, so skip this for histograms.
4285                          */
4286                         if (((++cb.cb_iteration == 1 && !skip) ||
4287                             (skip != verbose)) &&
4288                             (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
4289                             !cb.cb_scripted)
4290                                 print_iostat_header(&cb);
4291
4292                         if (skip) {
4293                                 (void) fsleep(interval);
4294                                 continue;
4295                         }
4296
4297                         if (cmd != NULL && cb.cb_verbose)
4298                                 cb.vcdl = all_pools_for_each_vdev_run(argc,
4299                                     argv, cmd, g_zfs, cb.cb_vdev_names,
4300                                     cb.cb_vdev_names_count, cb.cb_name_flags);
4301
4302                         pool_list_iter(list, B_FALSE, print_iostat, &cb);
4303
4304                         if (cb.vcdl != NULL)
4305                                 free_vdev_cmd_data_list(cb.vcdl);
4306
4307                         /*
4308                          * If there's more than one pool, and we're not in
4309                          * verbose mode (which prints a separator for us),
4310                          * then print a separator.
4311                          *
4312                          * In addition, if we're printing specific vdevs then
4313                          * we also want an ending separator.
4314                          */
4315                         if (((npools > 1 && !verbose &&
4316                             !(cb.cb_flags & IOS_ANYHISTO_M)) ||
4317                             (!(cb.cb_flags & IOS_ANYHISTO_M) &&
4318                             cb.cb_vdev_names_count)) &&
4319                             !cb.cb_scripted) {
4320                                 print_iostat_separator(&cb);
4321                         }
4322                 }
4323
4324                 /*
4325                  * Flush the output so that redirection to a file isn't buffered
4326                  * indefinitely.
4327                  */
4328                 (void) fflush(stdout);
4329
4330                 if (interval == 0)
4331                         break;
4332
4333                 if (count != 0 && --count == 0)
4334                         break;
4335
4336                 (void) fsleep(interval);
4337         }
4338
4339         pool_list_free(list);
4340
4341         return (ret);
4342 }
4343
4344 typedef struct list_cbdata {
4345         boolean_t       cb_verbose;
4346         int             cb_name_flags;
4347         int             cb_namewidth;
4348         boolean_t       cb_scripted;
4349         zprop_list_t    *cb_proplist;
4350         boolean_t       cb_literal;
4351 } list_cbdata_t;
4352
4353 /*
4354  * Given a list of columns to display, output appropriate headers for each one.
4355  */
4356 static void
4357 print_header(list_cbdata_t *cb)
4358 {
4359         zprop_list_t *pl = cb->cb_proplist;
4360         char headerbuf[ZPOOL_MAXPROPLEN];
4361         const char *header;
4362         boolean_t first = B_TRUE;
4363         boolean_t right_justify;
4364         size_t width = 0;
4365
4366         for (; pl != NULL; pl = pl->pl_next) {
4367                 width = pl->pl_width;
4368                 if (first && cb->cb_verbose) {
4369                         /*
4370                          * Reset the width to accommodate the verbose listing
4371                          * of devices.
4372                          */
4373                         width = cb->cb_namewidth;
4374                 }
4375
4376                 if (!first)
4377                         (void) printf("  ");
4378                 else
4379                         first = B_FALSE;
4380
4381                 right_justify = B_FALSE;
4382                 if (pl->pl_prop != ZPROP_INVAL) {
4383                         header = zpool_prop_column_name(pl->pl_prop);
4384                         right_justify = zpool_prop_align_right(pl->pl_prop);
4385                 } else {
4386                         int i;
4387
4388                         for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
4389                                 headerbuf[i] = toupper(pl->pl_user_prop[i]);
4390                         headerbuf[i] = '\0';
4391                         header = headerbuf;
4392                 }
4393
4394                 if (pl->pl_next == NULL && !right_justify)
4395                         (void) printf("%s", header);
4396                 else if (right_justify)
4397                         (void) printf("%*s", (int)width, header);
4398                 else
4399                         (void) printf("%-*s", (int)width, header);
4400         }
4401
4402         (void) printf("\n");
4403 }
4404
4405 /*
4406  * Given a pool and a list of properties, print out all the properties according
4407  * to the described layout.
4408  */
4409 static void
4410 print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
4411 {
4412         zprop_list_t *pl = cb->cb_proplist;
4413         boolean_t first = B_TRUE;
4414         char property[ZPOOL_MAXPROPLEN];
4415         char *propstr;
4416         boolean_t right_justify;
4417         size_t width;
4418
4419         for (; pl != NULL; pl = pl->pl_next) {
4420
4421                 width = pl->pl_width;
4422                 if (first && cb->cb_verbose) {
4423                         /*
4424                          * Reset the width to accommodate the verbose listing
4425                          * of devices.
4426                          */
4427                         width = cb->cb_namewidth;
4428                 }
4429
4430                 if (!first) {
4431                         if (cb->cb_scripted)
4432                                 (void) printf("\t");
4433                         else
4434                                 (void) printf("  ");
4435                 } else {
4436                         first = B_FALSE;
4437                 }
4438
4439                 right_justify = B_FALSE;
4440                 if (pl->pl_prop != ZPROP_INVAL) {
4441                         if (zpool_get_prop(zhp, pl->pl_prop, property,
4442                             sizeof (property), NULL, cb->cb_literal) != 0)
4443                                 propstr = "-";
4444                         else
4445                                 propstr = property;
4446
4447                         right_justify = zpool_prop_align_right(pl->pl_prop);
4448                 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
4449                     zpool_prop_unsupported(pl->pl_user_prop)) &&
4450                     zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
4451                     sizeof (property)) == 0) {
4452                         propstr = property;
4453                 } else {
4454                         propstr = "-";
4455                 }
4456
4457
4458                 /*
4459                  * If this is being called in scripted mode, or if this is the
4460                  * last column and it is left-justified, don't include a width
4461                  * format specifier.
4462                  */
4463                 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
4464                         (void) printf("%s", propstr);
4465                 else if (right_justify)
4466                         (void) printf("%*s", (int)width, propstr);
4467                 else
4468                         (void) printf("%-*s", (int)width, propstr);
4469         }
4470
4471         (void) printf("\n");
4472 }
4473
4474 static void
4475 print_one_column(zpool_prop_t prop, uint64_t value, boolean_t scripted,
4476     boolean_t valid, enum zfs_nicenum_format format)
4477 {
4478         char propval[64];
4479         boolean_t fixed;
4480         size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
4481
4482         switch (prop) {
4483         case ZPOOL_PROP_EXPANDSZ:
4484                 if (value == 0)
4485                         (void) strlcpy(propval, "-", sizeof (propval));
4486                 else
4487                         zfs_nicenum_format(value, propval, sizeof (propval),
4488                             format);
4489                 break;
4490         case ZPOOL_PROP_FRAGMENTATION:
4491                 if (value == ZFS_FRAG_INVALID) {
4492                         (void) strlcpy(propval, "-", sizeof (propval));
4493                 } else if (format == ZFS_NICENUM_RAW) {
4494                         (void) snprintf(propval, sizeof (propval), "%llu",
4495                             (unsigned long long)value);
4496                 } else {
4497                         (void) snprintf(propval, sizeof (propval), "%llu%%",
4498                             (unsigned long long)value);
4499                 }
4500                 break;
4501         case ZPOOL_PROP_CAPACITY:
4502                 if (format == ZFS_NICENUM_RAW)
4503                         (void) snprintf(propval, sizeof (propval), "%llu",
4504                             (unsigned long long)value);
4505                 else
4506                         (void) snprintf(propval, sizeof (propval), "%llu%%",
4507                             (unsigned long long)value);
4508                 break;
4509         default:
4510                 zfs_nicenum_format(value, propval, sizeof (propval), format);
4511         }
4512
4513         if (!valid)
4514                 (void) strlcpy(propval, "-", sizeof (propval));
4515
4516         if (scripted)
4517                 (void) printf("\t%s", propval);
4518         else
4519                 (void) printf("  %*s", (int)width, propval);
4520 }
4521
4522 void
4523 print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
4524     list_cbdata_t *cb, int depth)
4525 {
4526         nvlist_t **child;
4527         vdev_stat_t *vs;
4528         uint_t c, children;
4529         char *vname;
4530         boolean_t scripted = cb->cb_scripted;
4531         uint64_t islog = B_FALSE;
4532         boolean_t haslog = B_FALSE;
4533         char *dashes = "%-*s      -      -      -         -      -      -\n";
4534
4535         verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
4536             (uint64_t **)&vs, &c) == 0);
4537
4538         if (name != NULL) {
4539                 boolean_t toplevel = (vs->vs_space != 0);
4540                 uint64_t cap;
4541                 enum zfs_nicenum_format format;
4542
4543                 if (cb->cb_literal)
4544                         format = ZFS_NICENUM_RAW;
4545                 else
4546                         format = ZFS_NICENUM_1024;
4547
4548                 if (scripted)
4549                         (void) printf("\t%s", name);
4550                 else if (strlen(name) + depth > cb->cb_namewidth)
4551                         (void) printf("%*s%s", depth, "", name);
4552                 else
4553                         (void) printf("%*s%s%*s", depth, "", name,
4554                             (int)(cb->cb_namewidth - strlen(name) - depth), "");
4555
4556                 /*
4557                  * Print the properties for the individual vdevs. Some
4558                  * properties are only applicable to toplevel vdevs. The
4559                  * 'toplevel' boolean value is passed to the print_one_column()
4560                  * to indicate that the value is valid.
4561                  */
4562                 print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, scripted,
4563                     toplevel, format);
4564                 print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, scripted,
4565                     toplevel, format);
4566                 print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
4567                     scripted, toplevel, format);
4568                 print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, scripted,
4569                     B_TRUE, format);
4570                 print_one_column(ZPOOL_PROP_FRAGMENTATION,
4571                     vs->vs_fragmentation, scripted,
4572                     (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
4573                     format);
4574                 cap = (vs->vs_space == 0) ? 0 :
4575                     (vs->vs_alloc * 100 / vs->vs_space);
4576                 print_one_column(ZPOOL_PROP_CAPACITY, cap, scripted, toplevel,
4577                     format);
4578                 (void) printf("\n");
4579         }
4580
4581         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
4582             &child, &children) != 0)
4583                 return;
4584
4585         for (c = 0; c < children; c++) {
4586                 uint64_t ishole = B_FALSE;
4587
4588                 if (nvlist_lookup_uint64(child[c],
4589                     ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
4590                         continue;
4591
4592                 if (nvlist_lookup_uint64(child[c],
4593                     ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog) {
4594                         haslog = B_TRUE;
4595                         continue;
4596                 }
4597
4598                 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4599                     cb->cb_name_flags);
4600                 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4601                 free(vname);
4602         }
4603
4604         if (haslog == B_TRUE) {
4605                 /* LINTED E_SEC_PRINTF_VAR_FMT */
4606                 (void) printf(dashes, cb->cb_namewidth, "log");
4607                 for (c = 0; c < children; c++) {
4608                         if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
4609                             &islog) != 0 || !islog)
4610                                 continue;
4611                         vname = zpool_vdev_name(g_zfs, zhp, child[c],
4612                             cb->cb_name_flags);
4613                         print_list_stats(zhp, vname, child[c], cb, depth + 2);
4614                         free(vname);
4615                 }
4616         }
4617
4618         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
4619             &child, &children) == 0 && children > 0) {
4620                 /* LINTED E_SEC_PRINTF_VAR_FMT */
4621                 (void) printf(dashes, cb->cb_namewidth, "cache");
4622                 for (c = 0; c < children; c++) {
4623                         vname = zpool_vdev_name(g_zfs, zhp, child[c],
4624                             cb->cb_name_flags);
4625                         print_list_stats(zhp, vname, child[c], cb, depth + 2);
4626                         free(vname);
4627                 }
4628         }
4629
4630         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
4631             &children) == 0 && children > 0) {
4632                 /* LINTED E_SEC_PRINTF_VAR_FMT */
4633                 (void) printf(dashes, cb->cb_namewidth, "spare");
4634                 for (c = 0; c < children; c++) {
4635                         vname = zpool_vdev_name(g_zfs, zhp, child[c],
4636                             cb->cb_name_flags);
4637                         print_list_stats(zhp, vname, child[c], cb, depth + 2);
4638                         free(vname);
4639                 }
4640         }
4641 }
4642
4643
4644 /*
4645  * Generic callback function to list a pool.
4646  */
4647 int
4648 list_callback(zpool_handle_t *zhp, void *data)
4649 {
4650         list_cbdata_t *cbp = data;
4651         nvlist_t *config;
4652         nvlist_t *nvroot;
4653
4654         config = zpool_get_config(zhp, NULL);
4655
4656         print_pool(zhp, cbp);
4657         if (!cbp->cb_verbose)
4658                 return (0);
4659
4660         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4661             &nvroot) == 0);
4662         print_list_stats(zhp, NULL, nvroot, cbp, 0);
4663
4664         return (0);
4665 }
4666
4667 /*
4668  * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
4669  *
4670  *      -g      Display guid for individual vdev name.
4671  *      -H      Scripted mode.  Don't display headers, and separate properties
4672  *              by a single tab.
4673  *      -L      Follow links when resolving vdev path name.
4674  *      -o      List of properties to display.  Defaults to
4675  *              "name,size,allocated,free,expandsize,fragmentation,capacity,"
4676  *              "dedupratio,health,altroot"
4677  *      -p      Display values in parsable (exact) format.
4678  *      -P      Display full path for vdev name.
4679  *      -T      Display a timestamp in date(1) or Unix format
4680  *
4681  * List all pools in the system, whether or not they're healthy.  Output space
4682  * statistics for each one, as well as health status summary.
4683  */
4684 int
4685 zpool_do_list(int argc, char **argv)
4686 {
4687         int c;
4688         int ret = 0;
4689         list_cbdata_t cb = { 0 };
4690         static char default_props[] =
4691             "name,size,allocated,free,expandsize,fragmentation,capacity,"
4692             "dedupratio,health,altroot";
4693         char *props = default_props;
4694         float interval = 0;
4695         unsigned long count = 0;
4696         zpool_list_t *list;
4697         boolean_t first = B_TRUE;
4698
4699         /* check options */
4700         while ((c = getopt(argc, argv, ":gHLo:pPT:v")) != -1) {
4701                 switch (c) {
4702                 case 'g':
4703                         cb.cb_name_flags |= VDEV_NAME_GUID;
4704                         break;
4705                 case 'H':
4706                         cb.cb_scripted = B_TRUE;
4707                         break;
4708                 case 'L':
4709                         cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
4710                         break;
4711                 case 'o':
4712                         props = optarg;
4713                         break;
4714                 case 'P':
4715                         cb.cb_name_flags |= VDEV_NAME_PATH;
4716                         break;
4717                 case 'p':
4718                         cb.cb_literal = B_TRUE;
4719                         break;
4720                 case 'T':
4721                         get_timestamp_arg(*optarg);
4722                         break;
4723                 case 'v':
4724                         cb.cb_verbose = B_TRUE;
4725                         break;
4726                 case ':':
4727                         (void) fprintf(stderr, gettext("missing argument for "
4728                             "'%c' option\n"), optopt);
4729                         usage(B_FALSE);
4730                         break;
4731                 case '?':
4732                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4733                             optopt);
4734                         usage(B_FALSE);
4735                 }
4736         }
4737
4738         argc -= optind;
4739         argv += optind;
4740
4741         get_interval_count(&argc, argv, &interval, &count);
4742
4743         if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
4744                 usage(B_FALSE);
4745
4746         for (;;) {
4747                 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
4748                     &ret)) == NULL)
4749                         return (1);
4750
4751                 if (pool_list_count(list) == 0)
4752                         break;
4753
4754                 if (timestamp_fmt != NODATE)
4755                         print_timestamp(timestamp_fmt);
4756
4757                 if (!cb.cb_scripted && (first || cb.cb_verbose)) {
4758                         print_header(&cb);
4759                         first = B_FALSE;
4760                 }
4761                 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
4762
4763                 if (interval == 0)
4764                         break;
4765
4766                 if (count != 0 && --count == 0)
4767                         break;
4768
4769                 pool_list_free(list);
4770                 (void) fsleep(interval);
4771         }
4772
4773         if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
4774                 (void) printf(gettext("no pools available\n"));
4775                 ret = 0;
4776         }
4777
4778         pool_list_free(list);
4779         zprop_free_list(cb.cb_proplist);
4780         return (ret);
4781 }
4782
4783 static int
4784 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
4785 {
4786         boolean_t force = B_FALSE;
4787         int c;
4788         nvlist_t *nvroot;
4789         char *poolname, *old_disk, *new_disk;
4790         zpool_handle_t *zhp;
4791         nvlist_t *props = NULL;
4792         char *propval;
4793         int ret;
4794
4795         /* check options */
4796         while ((c = getopt(argc, argv, "fo:")) != -1) {
4797                 switch (c) {
4798                 case 'f':
4799                         force = B_TRUE;
4800                         break;
4801                 case 'o':
4802                         if ((propval = strchr(optarg, '=')) == NULL) {
4803                                 (void) fprintf(stderr, gettext("missing "
4804                                     "'=' for -o option\n"));
4805                                 usage(B_FALSE);
4806                         }
4807                         *propval = '\0';
4808                         propval++;
4809
4810                         if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
4811                             (add_prop_list(optarg, propval, &props, B_TRUE)))
4812                                 usage(B_FALSE);
4813                         break;
4814                 case '?':
4815                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4816                             optopt);
4817                         usage(B_FALSE);
4818                 }
4819         }
4820
4821         argc -= optind;
4822         argv += optind;
4823
4824         /* get pool name and check number of arguments */
4825         if (argc < 1) {
4826                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
4827                 usage(B_FALSE);
4828         }
4829
4830         poolname = argv[0];
4831
4832         if (argc < 2) {
4833                 (void) fprintf(stderr,
4834                     gettext("missing <device> specification\n"));
4835                 usage(B_FALSE);
4836         }
4837
4838         old_disk = argv[1];
4839
4840         if (argc < 3) {
4841                 if (!replacing) {
4842                         (void) fprintf(stderr,
4843                             gettext("missing <new_device> specification\n"));
4844                         usage(B_FALSE);
4845                 }
4846                 new_disk = old_disk;
4847                 argc -= 1;
4848                 argv += 1;
4849         } else {
4850                 new_disk = argv[2];
4851                 argc -= 2;
4852                 argv += 2;
4853         }
4854
4855         if (argc > 1) {
4856                 (void) fprintf(stderr, gettext("too many arguments\n"));
4857                 usage(B_FALSE);
4858         }
4859
4860         if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
4861                 nvlist_free(props);
4862                 return (1);
4863         }
4864
4865         if (zpool_get_config(zhp, NULL) == NULL) {
4866                 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
4867                     poolname);
4868                 zpool_close(zhp);
4869                 nvlist_free(props);
4870                 return (1);
4871         }
4872
4873         nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
4874             argc, argv);
4875         if (nvroot == NULL) {
4876                 zpool_close(zhp);
4877                 nvlist_free(props);
4878                 return (1);
4879         }
4880
4881         ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing);
4882
4883         nvlist_free(props);
4884         nvlist_free(nvroot);
4885         zpool_close(zhp);
4886
4887         return (ret);
4888 }
4889
4890 /*
4891  * zpool replace [-f] <pool> <device> <new_device>
4892  *
4893  *      -f      Force attach, even if <new_device> appears to be in use.
4894  *
4895  * Replace <device> with <new_device>.
4896  */
4897 /* ARGSUSED */
4898 int
4899 zpool_do_replace(int argc, char **argv)
4900 {
4901         return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
4902 }
4903
4904 /*
4905  * zpool attach [-f] [-o property=value] <pool> <device> <new_device>
4906  *
4907  *      -f      Force attach, even if <new_device> appears to be in use.
4908  *      -o      Set property=value.
4909  *
4910  * Attach <new_device> to the mirror containing <device>.  If <device> is not
4911  * part of a mirror, then <device> will be transformed into a mirror of
4912  * <device> and <new_device>.  In either case, <new_device> will begin life
4913  * with a DTL of [0, now], and will immediately begin to resilver itself.
4914  */
4915 int
4916 zpool_do_attach(int argc, char **argv)
4917 {
4918         return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
4919 }
4920
4921 /*
4922  * zpool detach [-f] <pool> <device>
4923  *
4924  *      -f      Force detach of <device>, even if DTLs argue against it
4925  *              (not supported yet)
4926  *
4927  * Detach a device from a mirror.  The operation will be refused if <device>
4928  * is the last device in the mirror, or if the DTLs indicate that this device
4929  * has the only valid copy of some data.
4930  */
4931 /* ARGSUSED */
4932 int
4933 zpool_do_detach(int argc, char **argv)
4934 {
4935         int c;
4936         char *poolname, *path;
4937         zpool_handle_t *zhp;
4938         int ret;
4939
4940         /* check options */
4941         while ((c = getopt(argc, argv, "f")) != -1) {
4942                 switch (c) {
4943                 case 'f':
4944                 case '?':
4945                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4946                             optopt);
4947                         usage(B_FALSE);
4948                 }
4949         }
4950
4951         argc -= optind;
4952         argv += optind;
4953
4954         /* get pool name and check number of arguments */
4955         if (argc < 1) {
4956                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
4957                 usage(B_FALSE);
4958         }
4959
4960         if (argc < 2) {
4961                 (void) fprintf(stderr,
4962                     gettext("missing <device> specification\n"));
4963                 usage(B_FALSE);
4964         }
4965
4966         poolname = argv[0];
4967         path = argv[1];
4968
4969         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
4970                 return (1);
4971
4972         ret = zpool_vdev_detach(zhp, path);
4973
4974         zpool_close(zhp);
4975
4976         return (ret);
4977 }
4978
4979 /*
4980  * zpool split [-gLnP] [-o prop=val] ...
4981  *              [-o mntopt] ...
4982  *              [-R altroot] <pool> <newpool> [<device> ...]
4983  *
4984  *      -g      Display guid for individual vdev name.
4985  *      -L      Follow links when resolving vdev path name.
4986  *      -n      Do not split the pool, but display the resulting layout if
4987  *              it were to be split.
4988  *      -o      Set property=value, or set mount options.
4989  *      -P      Display full path for vdev name.
4990  *      -R      Mount the split-off pool under an alternate root.
4991  *
4992  * Splits the named pool and gives it the new pool name.  Devices to be split
4993  * off may be listed, provided that no more than one device is specified
4994  * per top-level vdev mirror.  The newly split pool is left in an exported
4995  * state unless -R is specified.
4996  *
4997  * Restrictions: the top-level of the pool pool must only be made up of
4998  * mirrors; all devices in the pool must be healthy; no device may be
4999  * undergoing a resilvering operation.
5000  */
5001 int
5002 zpool_do_split(int argc, char **argv)
5003 {
5004         char *srcpool, *newpool, *propval;
5005         char *mntopts = NULL;
5006         splitflags_t flags;
5007         int c, ret = 0;
5008         zpool_handle_t *zhp;
5009         nvlist_t *config, *props = NULL;
5010
5011         flags.dryrun = B_FALSE;
5012         flags.import = B_FALSE;
5013         flags.name_flags = 0;
5014
5015         /* check options */
5016         while ((c = getopt(argc, argv, ":gLR:no:P")) != -1) {
5017                 switch (c) {
5018                 case 'g':
5019                         flags.name_flags |= VDEV_NAME_GUID;
5020                         break;
5021                 case 'L':
5022                         flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
5023                         break;
5024                 case 'R':
5025                         flags.import = B_TRUE;
5026                         if (add_prop_list(
5027                             zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
5028                             &props, B_TRUE) != 0) {
5029                                 nvlist_free(props);
5030                                 usage(B_FALSE);
5031                         }
5032                         break;
5033                 case 'n':
5034                         flags.dryrun = B_TRUE;
5035                         break;
5036                 case 'o':
5037                         if ((propval = strchr(optarg, '=')) != NULL) {
5038                                 *propval = '\0';
5039                                 propval++;
5040                                 if (add_prop_list(optarg, propval,
5041                                     &props, B_TRUE) != 0) {
5042                                         nvlist_free(props);
5043                                         usage(B_FALSE);
5044                                 }
5045                         } else {
5046                                 mntopts = optarg;
5047                         }
5048                         break;
5049                 case 'P':
5050                         flags.name_flags |= VDEV_NAME_PATH;
5051                         break;
5052                 case ':':
5053                         (void) fprintf(stderr, gettext("missing argument for "
5054                             "'%c' option\n"), optopt);
5055                         usage(B_FALSE);
5056                         break;
5057                 case '?':
5058                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5059                             optopt);
5060                         usage(B_FALSE);
5061                         break;
5062                 }
5063         }
5064
5065         if (!flags.import && mntopts != NULL) {
5066                 (void) fprintf(stderr, gettext("setting mntopts is only "
5067                     "valid when importing the pool\n"));
5068                 usage(B_FALSE);
5069         }
5070
5071         argc -= optind;
5072         argv += optind;
5073
5074         if (argc < 1) {
5075                 (void) fprintf(stderr, gettext("Missing pool name\n"));
5076                 usage(B_FALSE);
5077         }
5078         if (argc < 2) {
5079                 (void) fprintf(stderr, gettext("Missing new pool name\n"));
5080                 usage(B_FALSE);
5081         }
5082
5083         srcpool = argv[0];
5084         newpool = argv[1];
5085
5086         argc -= 2;
5087         argv += 2;
5088
5089         if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
5090                 nvlist_free(props);
5091                 return (1);
5092         }
5093
5094         config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
5095         if (config == NULL) {
5096                 ret = 1;
5097         } else {
5098                 if (flags.dryrun) {
5099                         (void) printf(gettext("would create '%s' with the "
5100                             "following layout:\n\n"), newpool);
5101                         print_vdev_tree(NULL, newpool, config, 0, B_FALSE,
5102                             flags.name_flags);
5103                 }
5104         }
5105
5106         zpool_close(zhp);
5107
5108         if (ret != 0 || flags.dryrun || !flags.import) {
5109                 nvlist_free(config);
5110                 nvlist_free(props);
5111                 return (ret);
5112         }
5113
5114         /*
5115          * The split was successful. Now we need to open the new
5116          * pool and import it.
5117          */
5118         if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
5119                 nvlist_free(config);
5120                 nvlist_free(props);
5121                 return (1);
5122         }
5123         if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
5124             zpool_enable_datasets(zhp, mntopts, 0) != 0) {
5125                 ret = 1;
5126                 (void) fprintf(stderr, gettext("Split was successful, but "
5127                     "the datasets could not all be mounted\n"));
5128                 (void) fprintf(stderr, gettext("Try doing '%s' with a "
5129                     "different altroot\n"), "zpool import");
5130         }
5131         zpool_close(zhp);
5132         nvlist_free(config);
5133         nvlist_free(props);
5134
5135         return (ret);
5136 }
5137
5138
5139
5140 /*
5141  * zpool online <pool> <device> ...
5142  */
5143 int
5144 zpool_do_online(int argc, char **argv)
5145 {
5146         int c, i;
5147         char *poolname;
5148         zpool_handle_t *zhp;
5149         int ret = 0;
5150         vdev_state_t newstate;
5151         int flags = 0;
5152
5153         /* check options */
5154         while ((c = getopt(argc, argv, "et")) != -1) {
5155                 switch (c) {
5156                 case 'e':
5157                         flags |= ZFS_ONLINE_EXPAND;
5158                         break;
5159                 case 't':
5160                 case '?':
5161                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5162                             optopt);
5163                         usage(B_FALSE);
5164                 }
5165         }
5166
5167         argc -= optind;
5168         argv += optind;
5169
5170         /* get pool name and check number of arguments */
5171         if (argc < 1) {
5172                 (void) fprintf(stderr, gettext("missing pool name\n"));
5173                 usage(B_FALSE);
5174         }
5175         if (argc < 2) {
5176                 (void) fprintf(stderr, gettext("missing device name\n"));
5177                 usage(B_FALSE);
5178         }
5179
5180         poolname = argv[0];
5181
5182         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5183                 return (1);
5184
5185         for (i = 1; i < argc; i++) {
5186                 if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
5187                         if (newstate != VDEV_STATE_HEALTHY) {
5188                                 (void) printf(gettext("warning: device '%s' "
5189                                     "onlined, but remains in faulted state\n"),
5190                                     argv[i]);
5191                                 if (newstate == VDEV_STATE_FAULTED)
5192                                         (void) printf(gettext("use 'zpool "
5193                                             "clear' to restore a faulted "
5194                                             "device\n"));
5195                                 else
5196                                         (void) printf(gettext("use 'zpool "
5197                                             "replace' to replace devices "
5198                                             "that are no longer present\n"));
5199                         }
5200                 } else {
5201                         ret = 1;
5202                 }
5203         }
5204
5205         zpool_close(zhp);
5206
5207         return (ret);
5208 }
5209
5210 /*
5211  * zpool offline [-ft] <pool> <device> ...
5212  *
5213  *      -f      Force the device into the offline state, even if doing
5214  *              so would appear to compromise pool availability.
5215  *              (not supported yet)
5216  *
5217  *      -t      Only take the device off-line temporarily.  The offline
5218  *              state will not be persistent across reboots.
5219  */
5220 /* ARGSUSED */
5221 int
5222 zpool_do_offline(int argc, char **argv)
5223 {
5224         int c, i;
5225         char *poolname;
5226         zpool_handle_t *zhp;
5227         int ret = 0;
5228         boolean_t istmp = B_FALSE;
5229
5230         /* check options */
5231         while ((c = getopt(argc, argv, "ft")) != -1) {
5232                 switch (c) {
5233                 case 't':
5234                         istmp = B_TRUE;
5235                         break;
5236                 case 'f':
5237                 case '?':
5238                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5239                             optopt);
5240                         usage(B_FALSE);
5241                 }
5242         }
5243
5244         argc -= optind;
5245         argv += optind;
5246
5247         /* get pool name and check number of arguments */
5248         if (argc < 1) {
5249                 (void) fprintf(stderr, gettext("missing pool name\n"));
5250                 usage(B_FALSE);
5251         }
5252         if (argc < 2) {
5253                 (void) fprintf(stderr, gettext("missing device name\n"));
5254                 usage(B_FALSE);
5255         }
5256
5257         poolname = argv[0];
5258
5259         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5260                 return (1);
5261
5262         for (i = 1; i < argc; i++) {
5263                 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
5264                         ret = 1;
5265         }
5266
5267         zpool_close(zhp);
5268
5269         return (ret);
5270 }
5271
5272 /*
5273  * zpool clear <pool> [device]
5274  *
5275  * Clear all errors associated with a pool or a particular device.
5276  */
5277 int
5278 zpool_do_clear(int argc, char **argv)
5279 {
5280         int c;
5281         int ret = 0;
5282         boolean_t dryrun = B_FALSE;
5283         boolean_t do_rewind = B_FALSE;
5284         boolean_t xtreme_rewind = B_FALSE;
5285         uint32_t rewind_policy = ZPOOL_NO_REWIND;
5286         nvlist_t *policy = NULL;
5287         zpool_handle_t *zhp;
5288         char *pool, *device;
5289
5290         /* check options */
5291         while ((c = getopt(argc, argv, "FnX")) != -1) {
5292                 switch (c) {
5293                 case 'F':
5294                         do_rewind = B_TRUE;
5295                         break;
5296                 case 'n':
5297                         dryrun = B_TRUE;
5298                         break;
5299                 case 'X':
5300                         xtreme_rewind = B_TRUE;
5301                         break;
5302                 case '?':
5303                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5304                             optopt);
5305                         usage(B_FALSE);
5306                 }
5307         }
5308
5309         argc -= optind;
5310         argv += optind;
5311
5312         if (argc < 1) {
5313                 (void) fprintf(stderr, gettext("missing pool name\n"));
5314                 usage(B_FALSE);
5315         }
5316
5317         if (argc > 2) {
5318                 (void) fprintf(stderr, gettext("too many arguments\n"));
5319                 usage(B_FALSE);
5320         }
5321
5322         if ((dryrun || xtreme_rewind) && !do_rewind) {
5323                 (void) fprintf(stderr,
5324                     gettext("-n or -X only meaningful with -F\n"));
5325                 usage(B_FALSE);
5326         }
5327         if (dryrun)
5328                 rewind_policy = ZPOOL_TRY_REWIND;
5329         else if (do_rewind)
5330                 rewind_policy = ZPOOL_DO_REWIND;
5331         if (xtreme_rewind)
5332                 rewind_policy |= ZPOOL_EXTREME_REWIND;
5333
5334         /* In future, further rewind policy choices can be passed along here */
5335         if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
5336             nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
5337                 return (1);
5338
5339         pool = argv[0];
5340         device = argc == 2 ? argv[1] : NULL;
5341
5342         if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
5343                 nvlist_free(policy);
5344                 return (1);
5345         }
5346
5347         if (zpool_clear(zhp, device, policy) != 0)
5348                 ret = 1;
5349
5350         zpool_close(zhp);
5351
5352         nvlist_free(policy);
5353
5354         return (ret);
5355 }
5356
5357 /*
5358  * zpool reguid <pool>
5359  */
5360 int
5361 zpool_do_reguid(int argc, char **argv)
5362 {
5363         int c;
5364         char *poolname;
5365         zpool_handle_t *zhp;
5366         int ret = 0;
5367
5368         /* check options */
5369         while ((c = getopt(argc, argv, "")) != -1) {
5370                 switch (c) {
5371                 case '?':
5372                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5373                             optopt);
5374                         usage(B_FALSE);
5375                 }
5376         }
5377
5378         argc -= optind;
5379         argv += optind;
5380
5381         /* get pool name and check number of arguments */
5382         if (argc < 1) {
5383                 (void) fprintf(stderr, gettext("missing pool name\n"));
5384                 usage(B_FALSE);
5385         }
5386
5387         if (argc > 1) {
5388                 (void) fprintf(stderr, gettext("too many arguments\n"));
5389                 usage(B_FALSE);
5390         }
5391
5392         poolname = argv[0];
5393         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5394                 return (1);
5395
5396         ret = zpool_reguid(zhp);
5397
5398         zpool_close(zhp);
5399         return (ret);
5400 }
5401
5402
5403 /*
5404  * zpool reopen <pool>
5405  *
5406  * Reopen the pool so that the kernel can update the sizes of all vdevs.
5407  */
5408 int
5409 zpool_do_reopen(int argc, char **argv)
5410 {
5411         int c;
5412         int ret = 0;
5413         zpool_handle_t *zhp;
5414         char *pool;
5415
5416         /* check options */
5417         while ((c = getopt(argc, argv, "")) != -1) {
5418                 switch (c) {
5419                 case '?':
5420                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5421                             optopt);
5422                         usage(B_FALSE);
5423                 }
5424         }
5425
5426         argc--;
5427         argv++;
5428
5429         if (argc < 1) {
5430                 (void) fprintf(stderr, gettext("missing pool name\n"));
5431                 usage(B_FALSE);
5432         }
5433
5434         if (argc > 1) {
5435                 (void) fprintf(stderr, gettext("too many arguments\n"));
5436                 usage(B_FALSE);
5437         }
5438
5439         pool = argv[0];
5440         if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL)
5441                 return (1);
5442
5443         ret = zpool_reopen(zhp);
5444         zpool_close(zhp);
5445         return (ret);
5446 }
5447
5448 typedef struct scrub_cbdata {
5449         int     cb_type;
5450         int     cb_argc;
5451         char    **cb_argv;
5452 } scrub_cbdata_t;
5453
5454 int
5455 scrub_callback(zpool_handle_t *zhp, void *data)
5456 {
5457         scrub_cbdata_t *cb = data;
5458         int err;
5459
5460         /*
5461          * Ignore faulted pools.
5462          */
5463         if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
5464                 (void) fprintf(stderr, gettext("cannot scrub '%s': pool is "
5465                     "currently unavailable\n"), zpool_get_name(zhp));
5466                 return (1);
5467         }
5468
5469         err = zpool_scan(zhp, cb->cb_type);
5470
5471         return (err != 0);
5472 }
5473
5474 /*
5475  * zpool scrub [-s] <pool> ...
5476  *
5477  *      -s      Stop.  Stops any in-progress scrub.
5478  */
5479 int
5480 zpool_do_scrub(int argc, char **argv)
5481 {
5482         int c;
5483         scrub_cbdata_t cb;
5484
5485         cb.cb_type = POOL_SCAN_SCRUB;
5486
5487         /* check options */
5488         while ((c = getopt(argc, argv, "s")) != -1) {
5489                 switch (c) {
5490                 case 's':
5491                         cb.cb_type = POOL_SCAN_NONE;
5492                         break;
5493                 case '?':
5494                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5495                             optopt);
5496                         usage(B_FALSE);
5497                 }
5498         }
5499
5500         cb.cb_argc = argc;
5501         cb.cb_argv = argv;
5502         argc -= optind;
5503         argv += optind;
5504
5505         if (argc < 1) {
5506                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5507                 usage(B_FALSE);
5508         }
5509
5510         return (for_each_pool(argc, argv, B_TRUE, NULL, scrub_callback, &cb));
5511 }
5512
5513 /*
5514  * Print out detailed scrub status.
5515  */
5516 void
5517 print_scan_status(pool_scan_stat_t *ps)
5518 {
5519         time_t start, end;
5520         uint64_t elapsed, mins_left, hours_left;
5521         uint64_t pass_exam, examined, total;
5522         uint_t rate;
5523         double fraction_done;
5524         char processed_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
5525
5526         (void) printf(gettext("  scan: "));
5527
5528         /* If there's never been a scan, there's not much to say. */
5529         if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
5530             ps->pss_func >= POOL_SCAN_FUNCS) {
5531                 (void) printf(gettext("none requested\n"));
5532                 return;
5533         }
5534
5535         start = ps->pss_start_time;
5536         end = ps->pss_end_time;
5537         zfs_nicenum(ps->pss_processed, processed_buf, sizeof (processed_buf));
5538
5539         assert(ps->pss_func == POOL_SCAN_SCRUB ||
5540             ps->pss_func == POOL_SCAN_RESILVER);
5541         /*
5542          * Scan is finished or canceled.
5543          */
5544         if (ps->pss_state == DSS_FINISHED) {
5545                 uint64_t minutes_taken = (end - start) / 60;
5546                 char *fmt = NULL;
5547
5548                 if (ps->pss_func == POOL_SCAN_SCRUB) {
5549                         fmt = gettext("scrub repaired %s in %lluh%um with "
5550                             "%llu errors on %s");
5551                 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5552                         fmt = gettext("resilvered %s in %lluh%um with "
5553                             "%llu errors on %s");
5554                 }
5555                 /* LINTED */
5556                 (void) printf(fmt, processed_buf,
5557                     (u_longlong_t)(minutes_taken / 60),
5558                     (uint_t)(minutes_taken % 60),
5559                     (u_longlong_t)ps->pss_errors,
5560                     ctime((time_t *)&end));
5561                 return;
5562         } else if (ps->pss_state == DSS_CANCELED) {
5563                 if (ps->pss_func == POOL_SCAN_SCRUB) {
5564                         (void) printf(gettext("scrub canceled on %s"),
5565                             ctime(&end));
5566                 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5567                         (void) printf(gettext("resilver canceled on %s"),
5568                             ctime(&end));
5569                 }
5570                 return;
5571         }
5572
5573         assert(ps->pss_state == DSS_SCANNING);
5574
5575         /*
5576          * Scan is in progress.
5577          */
5578         if (ps->pss_func == POOL_SCAN_SCRUB) {
5579                 (void) printf(gettext("scrub in progress since %s"),
5580                     ctime(&start));
5581         } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5582                 (void) printf(gettext("resilver in progress since %s"),
5583                     ctime(&start));
5584         }
5585
5586         examined = ps->pss_examined ? ps->pss_examined : 1;
5587         total = ps->pss_to_examine;
5588         fraction_done = (double)examined / total;
5589
5590         /* elapsed time for this pass */
5591         elapsed = time(NULL) - ps->pss_pass_start;
5592         elapsed = elapsed ? elapsed : 1;
5593         pass_exam = ps->pss_pass_exam ? ps->pss_pass_exam : 1;
5594         rate = pass_exam / elapsed;
5595         rate = rate ? rate : 1;
5596         mins_left = ((total - examined) / rate) / 60;
5597         hours_left = mins_left / 60;
5598
5599         zfs_nicenum(examined, examined_buf, sizeof (examined_buf));
5600         zfs_nicenum(total, total_buf, sizeof (total_buf));
5601         zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
5602
5603         /*
5604          * do not print estimated time if hours_left is more than 30 days
5605          */
5606         (void) printf(gettext("\t%s scanned out of %s at %s/s"),
5607             examined_buf, total_buf, rate_buf);
5608         if (hours_left < (30 * 24)) {
5609                 (void) printf(gettext(", %lluh%um to go\n"),
5610                     (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
5611         } else {
5612                 (void) printf(gettext(
5613                     ", (scan is slow, no estimated time)\n"));
5614         }
5615
5616         if (ps->pss_func == POOL_SCAN_RESILVER) {
5617                 (void) printf(gettext("\t%s resilvered, %.2f%% done\n"),
5618                     processed_buf, 100 * fraction_done);
5619         } else if (ps->pss_func == POOL_SCAN_SCRUB) {
5620                 (void) printf(gettext("\t%s repaired, %.2f%% done\n"),
5621                     processed_buf, 100 * fraction_done);
5622         }
5623 }
5624
5625 static void
5626 print_error_log(zpool_handle_t *zhp)
5627 {
5628         nvlist_t *nverrlist = NULL;
5629         nvpair_t *elem;
5630         char *pathname;
5631         size_t len = MAXPATHLEN * 2;
5632
5633         if (zpool_get_errlog(zhp, &nverrlist) != 0)
5634                 return;
5635
5636         (void) printf("errors: Permanent errors have been "
5637             "detected in the following files:\n\n");
5638
5639         pathname = safe_malloc(len);
5640         elem = NULL;
5641         while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
5642                 nvlist_t *nv;
5643                 uint64_t dsobj, obj;
5644
5645                 verify(nvpair_value_nvlist(elem, &nv) == 0);
5646                 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
5647                     &dsobj) == 0);
5648                 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
5649                     &obj) == 0);
5650                 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
5651                 (void) printf("%7s %s\n", "", pathname);
5652         }
5653         free(pathname);
5654         nvlist_free(nverrlist);
5655 }
5656
5657 static void
5658 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
5659     uint_t nspares)
5660 {
5661         uint_t i;
5662         char *name;
5663
5664         if (nspares == 0)
5665                 return;
5666
5667         (void) printf(gettext("\tspares\n"));
5668
5669         for (i = 0; i < nspares; i++) {
5670                 name = zpool_vdev_name(g_zfs, zhp, spares[i],
5671                     cb->cb_name_flags);
5672                 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE);
5673                 free(name);
5674         }
5675 }
5676
5677 static void
5678 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
5679     uint_t nl2cache)
5680 {
5681         uint_t i;
5682         char *name;
5683
5684         if (nl2cache == 0)
5685                 return;
5686
5687         (void) printf(gettext("\tcache\n"));
5688
5689         for (i = 0; i < nl2cache; i++) {
5690                 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
5691                     cb->cb_name_flags);
5692                 print_status_config(zhp, cb, name, l2cache[i], 2, B_FALSE);
5693                 free(name);
5694         }
5695 }
5696
5697 static void
5698 print_dedup_stats(nvlist_t *config)
5699 {
5700         ddt_histogram_t *ddh;
5701         ddt_stat_t *dds;
5702         ddt_object_t *ddo;
5703         uint_t c;
5704
5705         /*
5706          * If the pool was faulted then we may not have been able to
5707          * obtain the config. Otherwise, if we have anything in the dedup
5708          * table continue processing the stats.
5709          */
5710         if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
5711             (uint64_t **)&ddo, &c) != 0)
5712                 return;
5713
5714         (void) printf("\n");
5715         (void) printf(gettext(" dedup: "));
5716         if (ddo->ddo_count == 0) {
5717                 (void) printf(gettext("no DDT entries\n"));
5718                 return;
5719         }
5720
5721         (void) printf("DDT entries %llu, size %llu on disk, %llu in core\n",
5722             (u_longlong_t)ddo->ddo_count,
5723             (u_longlong_t)ddo->ddo_dspace,
5724             (u_longlong_t)ddo->ddo_mspace);
5725
5726         verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
5727             (uint64_t **)&dds, &c) == 0);
5728         verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
5729             (uint64_t **)&ddh, &c) == 0);
5730         zpool_dump_ddt(dds, ddh);
5731 }
5732
5733 /*
5734  * Display a summary of pool status.  Displays a summary such as:
5735  *
5736  *        pool: tank
5737  *      status: DEGRADED
5738  *      reason: One or more devices ...
5739  *         see: http://zfsonlinux.org/msg/ZFS-xxxx-01
5740  *      config:
5741  *              mirror          DEGRADED
5742  *                c1t0d0        OK
5743  *                c2t0d0        UNAVAIL
5744  *
5745  * When given the '-v' option, we print out the complete config.  If the '-e'
5746  * option is specified, then we print out error rate information as well.
5747  */
5748 int
5749 status_callback(zpool_handle_t *zhp, void *data)
5750 {
5751         status_cbdata_t *cbp = data;
5752         nvlist_t *config, *nvroot;
5753         char *msgid;
5754         zpool_status_t reason;
5755         zpool_errata_t errata;
5756         const char *health;
5757         uint_t c;
5758         vdev_stat_t *vs;
5759
5760         config = zpool_get_config(zhp, NULL);
5761         reason = zpool_get_status(zhp, &msgid, &errata);
5762
5763         cbp->cb_count++;
5764
5765         /*
5766          * If we were given 'zpool status -x', only report those pools with
5767          * problems.
5768          */
5769         if (cbp->cb_explain &&
5770             (reason == ZPOOL_STATUS_OK ||
5771             reason == ZPOOL_STATUS_VERSION_OLDER ||
5772             reason == ZPOOL_STATUS_FEAT_DISABLED)) {
5773                 if (!cbp->cb_allpools) {
5774                         (void) printf(gettext("pool '%s' is healthy\n"),
5775                             zpool_get_name(zhp));
5776                         if (cbp->cb_first)
5777                                 cbp->cb_first = B_FALSE;
5778                 }
5779                 return (0);
5780         }
5781
5782         if (cbp->cb_first)
5783                 cbp->cb_first = B_FALSE;
5784         else
5785                 (void) printf("\n");
5786
5787         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5788             &nvroot) == 0);
5789         verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
5790             (uint64_t **)&vs, &c) == 0);
5791         health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
5792
5793         (void) printf(gettext("  pool: %s\n"), zpool_get_name(zhp));
5794         (void) printf(gettext(" state: %s\n"), health);
5795
5796         switch (reason) {
5797         case ZPOOL_STATUS_MISSING_DEV_R:
5798                 (void) printf(gettext("status: One or more devices could not "
5799                     "be opened.  Sufficient replicas exist for\n\tthe pool to "
5800                     "continue functioning in a degraded state.\n"));
5801                 (void) printf(gettext("action: Attach the missing device and "
5802                     "online it using 'zpool online'.\n"));
5803                 break;
5804
5805         case ZPOOL_STATUS_MISSING_DEV_NR:
5806                 (void) printf(gettext("status: One or more devices could not "
5807                     "be opened.  There are insufficient\n\treplicas for the "
5808                     "pool to continue functioning.\n"));
5809                 (void) printf(gettext("action: Attach the missing device and "
5810                     "online it using 'zpool online'.\n"));
5811                 break;
5812
5813         case ZPOOL_STATUS_CORRUPT_LABEL_R:
5814                 (void) printf(gettext("status: One or more devices could not "
5815                     "be used because the label is missing or\n\tinvalid.  "
5816                     "Sufficient replicas exist for the pool to continue\n\t"
5817                     "functioning in a degraded state.\n"));
5818                 (void) printf(gettext("action: Replace the device using "
5819                     "'zpool replace'.\n"));
5820                 break;
5821
5822         case ZPOOL_STATUS_CORRUPT_LABEL_NR:
5823                 (void) printf(gettext("status: One or more devices could not "
5824                     "be used because the label is missing \n\tor invalid.  "
5825                     "There are insufficient replicas for the pool to "
5826                     "continue\n\tfunctioning.\n"));
5827                 zpool_explain_recover(zpool_get_handle(zhp),
5828                     zpool_get_name(zhp), reason, config);
5829                 break;
5830
5831         case ZPOOL_STATUS_FAILING_DEV:
5832                 (void) printf(gettext("status: One or more devices has "
5833                     "experienced an unrecoverable error.  An\n\tattempt was "
5834                     "made to correct the error.  Applications are "
5835                     "unaffected.\n"));
5836                 (void) printf(gettext("action: Determine if the device needs "
5837                     "to be replaced, and clear the errors\n\tusing "
5838                     "'zpool clear' or replace the device with 'zpool "
5839                     "replace'.\n"));
5840                 break;
5841
5842         case ZPOOL_STATUS_OFFLINE_DEV:
5843                 (void) printf(gettext("status: One or more devices has "
5844                     "been taken offline by the administrator.\n\tSufficient "
5845                     "replicas exist for the pool to continue functioning in "
5846                     "a\n\tdegraded state.\n"));
5847                 (void) printf(gettext("action: Online the device using "
5848                     "'zpool online' or replace the device with\n\t'zpool "
5849                     "replace'.\n"));
5850                 break;
5851
5852         case ZPOOL_STATUS_REMOVED_DEV:
5853                 (void) printf(gettext("status: One or more devices has "
5854                     "been removed by the administrator.\n\tSufficient "
5855                     "replicas exist for the pool to continue functioning in "
5856                     "a\n\tdegraded state.\n"));
5857                 (void) printf(gettext("action: Online the device using "
5858                     "'zpool online' or replace the device with\n\t'zpool "
5859                     "replace'.\n"));
5860                 break;
5861
5862         case ZPOOL_STATUS_RESILVERING:
5863                 (void) printf(gettext("status: One or more devices is "
5864                     "currently being resilvered.  The pool will\n\tcontinue "
5865                     "to function, possibly in a degraded state.\n"));
5866                 (void) printf(gettext("action: Wait for the resilver to "
5867                     "complete.\n"));
5868                 break;
5869
5870         case ZPOOL_STATUS_CORRUPT_DATA:
5871                 (void) printf(gettext("status: One or more devices has "
5872                     "experienced an error resulting in data\n\tcorruption.  "
5873                     "Applications may be affected.\n"));
5874                 (void) printf(gettext("action: Restore the file in question "
5875                     "if possible.  Otherwise restore the\n\tentire pool from "
5876                     "backup.\n"));
5877                 break;
5878
5879         case ZPOOL_STATUS_CORRUPT_POOL:
5880                 (void) printf(gettext("status: The pool metadata is corrupted "
5881                     "and the pool cannot be opened.\n"));
5882                 zpool_explain_recover(zpool_get_handle(zhp),
5883                     zpool_get_name(zhp), reason, config);
5884                 break;
5885
5886         case ZPOOL_STATUS_VERSION_OLDER:
5887                 (void) printf(gettext("status: The pool is formatted using a "
5888                     "legacy on-disk format.  The pool can\n\tstill be used, "
5889                     "but some features are unavailable.\n"));
5890                 (void) printf(gettext("action: Upgrade the pool using 'zpool "
5891                     "upgrade'.  Once this is done, the\n\tpool will no longer "
5892                     "be accessible on software that does not support\n\t"
5893                     "feature flags.\n"));
5894                 break;
5895
5896         case ZPOOL_STATUS_VERSION_NEWER:
5897                 (void) printf(gettext("status: The pool has been upgraded to a "
5898                     "newer, incompatible on-disk version.\n\tThe pool cannot "
5899                     "be accessed on this system.\n"));
5900                 (void) printf(gettext("action: Access the pool from a system "
5901                     "running more recent software, or\n\trestore the pool from "
5902                     "backup.\n"));
5903                 break;
5904
5905         case ZPOOL_STATUS_FEAT_DISABLED:
5906                 (void) printf(gettext("status: Some supported features are not "
5907                     "enabled on the pool. The pool can\n\tstill be used, but "
5908                     "some features are unavailable.\n"));
5909                 (void) printf(gettext("action: Enable all features using "
5910                     "'zpool upgrade'. Once this is done,\n\tthe pool may no "
5911                     "longer be accessible by software that does not support\n\t"
5912                     "the features. See zpool-features(5) for details.\n"));
5913                 break;
5914
5915         case ZPOOL_STATUS_UNSUP_FEAT_READ:
5916                 (void) printf(gettext("status: The pool cannot be accessed on "
5917                     "this system because it uses the\n\tfollowing feature(s) "
5918                     "not supported on this system:\n"));
5919                 zpool_print_unsup_feat(config);
5920                 (void) printf("\n");
5921                 (void) printf(gettext("action: Access the pool from a system "
5922                     "that supports the required feature(s),\n\tor restore the "
5923                     "pool from backup.\n"));
5924                 break;
5925
5926         case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
5927                 (void) printf(gettext("status: The pool can only be accessed "
5928                     "in read-only mode on this system. It\n\tcannot be "
5929                     "accessed in read-write mode because it uses the "
5930                     "following\n\tfeature(s) not supported on this system:\n"));
5931                 zpool_print_unsup_feat(config);
5932                 (void) printf("\n");
5933                 (void) printf(gettext("action: The pool cannot be accessed in "
5934                     "read-write mode. Import the pool with\n"
5935                     "\t\"-o readonly=on\", access the pool from a system that "
5936                     "supports the\n\trequired feature(s), or restore the "
5937                     "pool from backup.\n"));
5938                 break;
5939
5940         case ZPOOL_STATUS_FAULTED_DEV_R:
5941                 (void) printf(gettext("status: One or more devices are "
5942                     "faulted in response to persistent errors.\n\tSufficient "
5943                     "replicas exist for the pool to continue functioning "
5944                     "in a\n\tdegraded state.\n"));
5945                 (void) printf(gettext("action: Replace the faulted device, "
5946                     "or use 'zpool clear' to mark the device\n\trepaired.\n"));
5947                 break;
5948
5949         case ZPOOL_STATUS_FAULTED_DEV_NR:
5950                 (void) printf(gettext("status: One or more devices are "
5951                     "faulted in response to persistent errors.  There are "
5952                     "insufficient replicas for the pool to\n\tcontinue "
5953                     "functioning.\n"));
5954                 (void) printf(gettext("action: Destroy and re-create the pool "
5955                     "from a backup source.  Manually marking the device\n"
5956                     "\trepaired using 'zpool clear' may allow some data "
5957                     "to be recovered.\n"));
5958                 break;
5959
5960         case ZPOOL_STATUS_IO_FAILURE_WAIT:
5961         case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
5962                 (void) printf(gettext("status: One or more devices are "
5963                     "faulted in response to IO failures.\n"));
5964                 (void) printf(gettext("action: Make sure the affected devices "
5965                     "are connected, then run 'zpool clear'.\n"));
5966                 break;
5967
5968         case ZPOOL_STATUS_BAD_LOG:
5969                 (void) printf(gettext("status: An intent log record "
5970                     "could not be read.\n"
5971                     "\tWaiting for administrator intervention to fix the "
5972                     "faulted pool.\n"));
5973                 (void) printf(gettext("action: Either restore the affected "
5974                     "device(s) and run 'zpool online',\n"
5975                     "\tor ignore the intent log records by running "
5976                     "'zpool clear'.\n"));
5977                 break;
5978
5979         case ZPOOL_STATUS_HOSTID_MISMATCH:
5980                 (void) printf(gettext("status: Mismatch between pool hostid "
5981                     "and system hostid on imported pool.\n\tThis pool was "
5982                     "previously imported into a system with a different "
5983                     "hostid,\n\tand then was verbatim imported into this "
5984                     "system.\n"));
5985                 (void) printf(gettext("action: Export this pool on all systems "
5986                     "on which it is imported.\n"
5987                     "\tThen import it to correct the mismatch.\n"));
5988                 break;
5989
5990         case ZPOOL_STATUS_ERRATA:
5991                 (void) printf(gettext("status: Errata #%d detected.\n"),
5992                     errata);
5993
5994                 switch (errata) {
5995                 case ZPOOL_ERRATA_NONE:
5996                         break;
5997
5998                 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
5999                         (void) printf(gettext("action: To correct the issue "
6000                             "run 'zpool scrub'.\n"));
6001                         break;
6002
6003                 default:
6004                         /*
6005                          * All errata which allow the pool to be imported
6006                          * must contain an action message.
6007                          */
6008                         assert(0);
6009                 }
6010                 break;
6011
6012         default:
6013                 /*
6014                  * The remaining errors can't actually be generated, yet.
6015                  */
6016                 assert(reason == ZPOOL_STATUS_OK);
6017         }
6018
6019         if (msgid != NULL)
6020                 (void) printf(gettext("   see: http://zfsonlinux.org/msg/%s\n"),
6021                     msgid);
6022
6023         if (config != NULL) {
6024                 uint64_t nerr;
6025                 nvlist_t **spares, **l2cache;
6026                 uint_t nspares, nl2cache;
6027                 pool_scan_stat_t *ps = NULL;
6028
6029                 (void) nvlist_lookup_uint64_array(nvroot,
6030                     ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &c);
6031                 print_scan_status(ps);
6032
6033                 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
6034                     cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
6035                 if (cbp->cb_namewidth < 10)
6036                         cbp->cb_namewidth = 10;
6037
6038                 (void) printf(gettext("config:\n\n"));
6039                 (void) printf(gettext("\t%-*s  %-8s %5s %5s %5s\n"),
6040                     cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
6041                     "CKSUM");
6042                 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
6043                     B_FALSE);
6044
6045                 if (num_logs(nvroot) > 0)
6046                         print_logs(zhp, cbp, nvroot);
6047                 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
6048                     &l2cache, &nl2cache) == 0)
6049                         print_l2cache(zhp, cbp, l2cache, nl2cache);
6050
6051                 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
6052                     &spares, &nspares) == 0)
6053                         print_spares(zhp, cbp, spares, nspares);
6054
6055                 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
6056                     &nerr) == 0) {
6057                         nvlist_t *nverrlist = NULL;
6058
6059                         /*
6060                          * If the approximate error count is small, get a
6061                          * precise count by fetching the entire log and
6062                          * uniquifying the results.
6063                          */
6064                         if (nerr > 0 && nerr < 100 && !cbp->cb_verbose &&
6065                             zpool_get_errlog(zhp, &nverrlist) == 0) {
6066                                 nvpair_t *elem;
6067
6068                                 elem = NULL;
6069                                 nerr = 0;
6070                                 while ((elem = nvlist_next_nvpair(nverrlist,
6071                                     elem)) != NULL) {
6072                                         nerr++;
6073                                 }
6074                         }
6075                         nvlist_free(nverrlist);
6076
6077                         (void) printf("\n");
6078
6079                         if (nerr == 0)
6080                                 (void) printf(gettext("errors: No known data "
6081                                     "errors\n"));
6082                         else if (!cbp->cb_verbose)
6083                                 (void) printf(gettext("errors: %llu data "
6084                                     "errors, use '-v' for a list\n"),
6085                                     (u_longlong_t)nerr);
6086                         else
6087                                 print_error_log(zhp);
6088                 }
6089
6090                 if (cbp->cb_dedup_stats)
6091                         print_dedup_stats(config);
6092         } else {
6093                 (void) printf(gettext("config: The configuration cannot be "
6094                     "determined.\n"));
6095         }
6096
6097         return (0);
6098 }
6099
6100 /*
6101  * zpool status [-c CMD] [-gLPvx] [-T d|u] [pool] ... [interval [count]]
6102  *
6103  *      -c CMD  For each vdev, run command CMD
6104  *      -g      Display guid for individual vdev name.
6105  *      -L      Follow links when resolving vdev path name.
6106  *      -P      Display full path for vdev name.
6107  *      -v      Display complete error logs
6108  *      -x      Display only pools with potential problems
6109  *      -D      Display dedup status (undocumented)
6110  *      -T      Display a timestamp in date(1) or Unix format
6111  *
6112  * Describes the health status of all pools or some subset.
6113  */
6114 int
6115 zpool_do_status(int argc, char **argv)
6116 {
6117         int c;
6118         int ret;
6119         float interval = 0;
6120         unsigned long count = 0;
6121         status_cbdata_t cb = { 0 };
6122         char *cmd = NULL;
6123
6124         /* check options */
6125         while ((c = getopt(argc, argv, "c:gLPvxDT:")) != -1) {
6126                 switch (c) {
6127                 case 'c':
6128                         cmd = optarg;
6129                         break;
6130                 case 'g':
6131                         cb.cb_name_flags |= VDEV_NAME_GUID;
6132                         break;
6133                 case 'L':
6134                         cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6135                         break;
6136                 case 'P':
6137                         cb.cb_name_flags |= VDEV_NAME_PATH;
6138                         break;
6139                 case 'v':
6140                         cb.cb_verbose = B_TRUE;
6141                         break;
6142                 case 'x':
6143                         cb.cb_explain = B_TRUE;
6144                         break;
6145                 case 'D':
6146                         cb.cb_dedup_stats = B_TRUE;
6147                         break;
6148                 case 'T':
6149                         get_timestamp_arg(*optarg);
6150                         break;
6151                 case '?':
6152                         if (optopt == 'c') {
6153                                 fprintf(stderr,
6154                                     gettext("Missing CMD for -c\n"));
6155                         } else {
6156                                 fprintf(stderr,
6157                                     gettext("invalid option '%c'\n"), optopt);
6158                         }
6159                         usage(B_FALSE);
6160                 }
6161         }
6162
6163         argc -= optind;
6164         argv += optind;
6165
6166         get_interval_count(&argc, argv, &interval, &count);
6167
6168         if (argc == 0)
6169                 cb.cb_allpools = B_TRUE;
6170
6171         cb.cb_first = B_TRUE;
6172         cb.cb_print_status = B_TRUE;
6173
6174         for (;;) {
6175                 if (timestamp_fmt != NODATE)
6176                         print_timestamp(timestamp_fmt);
6177
6178                 if (cmd != NULL)
6179                         cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
6180                             NULL, NULL, 0, 0);
6181
6182                 ret = for_each_pool(argc, argv, B_TRUE, NULL,
6183                     status_callback, &cb);
6184
6185                 if (cb.vcdl != NULL)
6186                         free_vdev_cmd_data_list(cb.vcdl);
6187
6188                 if (argc == 0 && cb.cb_count == 0)
6189                         (void) fprintf(stderr, gettext("no pools available\n"));
6190                 else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
6191                         (void) printf(gettext("all pools are healthy\n"));
6192
6193                 if (ret != 0)
6194                         return (ret);
6195
6196                 if (interval == 0)
6197                         break;
6198
6199                 if (count != 0 && --count == 0)
6200                         break;
6201
6202                 (void) fsleep(interval);
6203         }
6204
6205         return (0);
6206 }
6207
6208 typedef struct upgrade_cbdata {
6209         int     cb_first;
6210         int     cb_argc;
6211         uint64_t cb_version;
6212         char    **cb_argv;
6213 } upgrade_cbdata_t;
6214
6215 static int
6216 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
6217 {
6218         int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
6219         int *count = (int *)unsupp_fs;
6220
6221         if (zfs_version > ZPL_VERSION) {
6222                 (void) printf(gettext("%s (v%d) is not supported by this "
6223                     "implementation of ZFS.\n"),
6224                     zfs_get_name(zhp), zfs_version);
6225                 (*count)++;
6226         }
6227
6228         zfs_iter_filesystems(zhp, check_unsupp_fs, unsupp_fs);
6229
6230         zfs_close(zhp);
6231
6232         return (0);
6233 }
6234
6235 static int
6236 upgrade_version(zpool_handle_t *zhp, uint64_t version)
6237 {
6238         int ret;
6239         nvlist_t *config;
6240         uint64_t oldversion;
6241         int unsupp_fs = 0;
6242
6243         config = zpool_get_config(zhp, NULL);
6244         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6245             &oldversion) == 0);
6246
6247         assert(SPA_VERSION_IS_SUPPORTED(oldversion));
6248         assert(oldversion < version);
6249
6250         ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
6251         if (ret != 0)
6252                 return (ret);
6253
6254         if (unsupp_fs) {
6255                 (void) fprintf(stderr, gettext("Upgrade not performed due "
6256                     "to %d unsupported filesystems (max v%d).\n"),
6257                     unsupp_fs, (int)ZPL_VERSION);
6258                 return (1);
6259         }
6260
6261         ret = zpool_upgrade(zhp, version);
6262         if (ret != 0)
6263                 return (ret);
6264
6265         if (version >= SPA_VERSION_FEATURES) {
6266                 (void) printf(gettext("Successfully upgraded "
6267                     "'%s' from version %llu to feature flags.\n"),
6268                     zpool_get_name(zhp), (u_longlong_t)oldversion);
6269         } else {
6270                 (void) printf(gettext("Successfully upgraded "
6271                     "'%s' from version %llu to version %llu.\n"),
6272                     zpool_get_name(zhp), (u_longlong_t)oldversion,
6273                     (u_longlong_t)version);
6274         }
6275
6276         return (0);
6277 }
6278
6279 static int
6280 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
6281 {
6282         int i, ret, count;
6283         boolean_t firstff = B_TRUE;
6284         nvlist_t *enabled = zpool_get_features(zhp);
6285
6286         count = 0;
6287         for (i = 0; i < SPA_FEATURES; i++) {
6288                 const char *fname = spa_feature_table[i].fi_uname;
6289                 const char *fguid = spa_feature_table[i].fi_guid;
6290                 if (!nvlist_exists(enabled, fguid)) {
6291                         char *propname;
6292                         verify(-1 != asprintf(&propname, "feature@%s", fname));
6293                         ret = zpool_set_prop(zhp, propname,
6294                             ZFS_FEATURE_ENABLED);
6295                         if (ret != 0) {
6296                                 free(propname);
6297                                 return (ret);
6298                         }
6299                         count++;
6300
6301                         if (firstff) {
6302                                 (void) printf(gettext("Enabled the "
6303                                     "following features on '%s':\n"),
6304                                     zpool_get_name(zhp));
6305                                 firstff = B_FALSE;
6306                         }
6307                         (void) printf(gettext("  %s\n"), fname);
6308                         free(propname);
6309                 }
6310         }
6311
6312         if (countp != NULL)
6313                 *countp = count;
6314         return (0);
6315 }
6316
6317 static int
6318 upgrade_cb(zpool_handle_t *zhp, void *arg)
6319 {
6320         upgrade_cbdata_t *cbp = arg;
6321         nvlist_t *config;
6322         uint64_t version;
6323         boolean_t printnl = B_FALSE;
6324         int ret;
6325
6326         config = zpool_get_config(zhp, NULL);
6327         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6328             &version) == 0);
6329
6330         assert(SPA_VERSION_IS_SUPPORTED(version));
6331
6332         if (version < cbp->cb_version) {
6333                 cbp->cb_first = B_FALSE;
6334                 ret = upgrade_version(zhp, cbp->cb_version);
6335                 if (ret != 0)
6336                         return (ret);
6337                 printnl = B_TRUE;
6338
6339                 /*
6340                  * If they did "zpool upgrade -a", then we could
6341                  * be doing ioctls to different pools.  We need
6342                  * to log this history once to each pool, and bypass
6343                  * the normal history logging that happens in main().
6344                  */
6345                 (void) zpool_log_history(g_zfs, history_str);
6346                 log_history = B_FALSE;
6347         }
6348
6349         if (cbp->cb_version >= SPA_VERSION_FEATURES) {
6350                 int count;
6351                 ret = upgrade_enable_all(zhp, &count);
6352                 if (ret != 0)
6353                         return (ret);
6354
6355                 if (count > 0) {
6356                         cbp->cb_first = B_FALSE;
6357                         printnl = B_TRUE;
6358                 }
6359         }
6360
6361         if (printnl) {
6362                 (void) printf(gettext("\n"));
6363         }
6364
6365         return (0);
6366 }
6367
6368 static int
6369 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
6370 {
6371         upgrade_cbdata_t *cbp = arg;
6372         nvlist_t *config;
6373         uint64_t version;
6374
6375         config = zpool_get_config(zhp, NULL);
6376         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6377             &version) == 0);
6378
6379         assert(SPA_VERSION_IS_SUPPORTED(version));
6380
6381         if (version < SPA_VERSION_FEATURES) {
6382                 if (cbp->cb_first) {
6383                         (void) printf(gettext("The following pools are "
6384                             "formatted with legacy version numbers and can\n"
6385                             "be upgraded to use feature flags.  After "
6386                             "being upgraded, these pools\nwill no "
6387                             "longer be accessible by software that does not "
6388                             "support feature\nflags.\n\n"));
6389                         (void) printf(gettext("VER  POOL\n"));
6390                         (void) printf(gettext("---  ------------\n"));
6391                         cbp->cb_first = B_FALSE;
6392                 }
6393
6394                 (void) printf("%2llu   %s\n", (u_longlong_t)version,
6395                     zpool_get_name(zhp));
6396         }
6397
6398         return (0);
6399 }
6400
6401 static int
6402 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
6403 {
6404         upgrade_cbdata_t *cbp = arg;
6405         nvlist_t *config;
6406         uint64_t version;
6407
6408         config = zpool_get_config(zhp, NULL);
6409         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6410             &version) == 0);
6411
6412         if (version >= SPA_VERSION_FEATURES) {
6413                 int i;
6414                 boolean_t poolfirst = B_TRUE;
6415                 nvlist_t *enabled = zpool_get_features(zhp);
6416
6417                 for (i = 0; i < SPA_FEATURES; i++) {
6418                         const char *fguid = spa_feature_table[i].fi_guid;
6419                         const char *fname = spa_feature_table[i].fi_uname;
6420                         if (!nvlist_exists(enabled, fguid)) {
6421                                 if (cbp->cb_first) {
6422                                         (void) printf(gettext("\nSome "
6423                                             "supported features are not "
6424                                             "enabled on the following pools. "
6425                                             "Once a\nfeature is enabled the "
6426                                             "pool may become incompatible with "
6427                                             "software\nthat does not support "
6428                                             "the feature. See "
6429                                             "zpool-features(5) for "
6430                                             "details.\n\n"));
6431                                         (void) printf(gettext("POOL  "
6432                                             "FEATURE\n"));
6433                                         (void) printf(gettext("------"
6434                                             "---------\n"));
6435                                         cbp->cb_first = B_FALSE;
6436                                 }
6437
6438                                 if (poolfirst) {
6439                                         (void) printf(gettext("%s\n"),
6440                                             zpool_get_name(zhp));
6441                                         poolfirst = B_FALSE;
6442                                 }
6443
6444                                 (void) printf(gettext("      %s\n"), fname);
6445                         }
6446                         /*
6447                          * If they did "zpool upgrade -a", then we could
6448                          * be doing ioctls to different pools.  We need
6449                          * to log this history once to each pool, and bypass
6450                          * the normal history logging that happens in main().
6451                          */
6452                         (void) zpool_log_history(g_zfs, history_str);
6453                         log_history = B_FALSE;
6454                 }
6455         }
6456
6457         return (0);
6458 }
6459
6460 /* ARGSUSED */
6461 static int
6462 upgrade_one(zpool_handle_t *zhp, void *data)
6463 {
6464         boolean_t printnl = B_FALSE;
6465         upgrade_cbdata_t *cbp = data;
6466         uint64_t cur_version;
6467         int ret;
6468
6469         if (strcmp("log", zpool_get_name(zhp)) == 0) {
6470                 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
6471                     "Pool 'log' must be renamed using export and import"
6472                     " to upgrade.\n"));
6473                 return (1);
6474         }
6475
6476         cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
6477         if (cur_version > cbp->cb_version) {
6478                 (void) printf(gettext("Pool '%s' is already formatted "
6479                     "using more current version '%llu'.\n\n"),
6480                     zpool_get_name(zhp), (u_longlong_t)cur_version);
6481                 return (0);
6482         }
6483
6484         if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
6485                 (void) printf(gettext("Pool '%s' is already formatted "
6486                     "using version %llu.\n\n"), zpool_get_name(zhp),
6487                     (u_longlong_t)cbp->cb_version);
6488                 return (0);
6489         }
6490
6491         if (cur_version != cbp->cb_version) {
6492                 printnl = B_TRUE;
6493                 ret = upgrade_version(zhp, cbp->cb_version);
6494                 if (ret != 0)
6495                         return (ret);
6496         }
6497
6498         if (cbp->cb_version >= SPA_VERSION_FEATURES) {
6499                 int count = 0;
6500                 ret = upgrade_enable_all(zhp, &count);
6501                 if (ret != 0)
6502                         return (ret);
6503
6504                 if (count != 0) {
6505                         printnl = B_TRUE;
6506                 } else if (cur_version == SPA_VERSION) {
6507                         (void) printf(gettext("Pool '%s' already has all "
6508                             "supported features enabled.\n"),
6509                             zpool_get_name(zhp));
6510                 }
6511         }
6512
6513         if (printnl) {
6514                 (void) printf(gettext("\n"));
6515         }
6516
6517         return (0);
6518 }
6519
6520 /*
6521  * zpool upgrade
6522  * zpool upgrade -v
6523  * zpool upgrade [-V version] <-a | pool ...>
6524  *
6525  * With no arguments, display downrev'd ZFS pool available for upgrade.
6526  * Individual pools can be upgraded by specifying the pool, and '-a' will
6527  * upgrade all pools.
6528  */
6529 int
6530 zpool_do_upgrade(int argc, char **argv)
6531 {
6532         int c;
6533         upgrade_cbdata_t cb = { 0 };
6534         int ret = 0;
6535         boolean_t showversions = B_FALSE;
6536         boolean_t upgradeall = B_FALSE;
6537         char *end;
6538
6539
6540         /* check options */
6541         while ((c = getopt(argc, argv, ":avV:")) != -1) {
6542                 switch (c) {
6543                 case 'a':
6544                         upgradeall = B_TRUE;
6545                         break;
6546                 case 'v':
6547                         showversions = B_TRUE;
6548                         break;
6549                 case 'V':
6550                         cb.cb_version = strtoll(optarg, &end, 10);
6551                         if (*end != '\0' ||
6552                             !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
6553                                 (void) fprintf(stderr,
6554                                     gettext("invalid version '%s'\n"), optarg);
6555                                 usage(B_FALSE);
6556                         }
6557                         break;
6558                 case ':':
6559                         (void) fprintf(stderr, gettext("missing argument for "
6560                             "'%c' option\n"), optopt);
6561                         usage(B_FALSE);
6562                         break;
6563                 case '?':
6564                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6565                             optopt);
6566                         usage(B_FALSE);
6567                 }
6568         }
6569
6570         cb.cb_argc = argc;
6571         cb.cb_argv = argv;
6572         argc -= optind;
6573         argv += optind;
6574
6575         if (cb.cb_version == 0) {
6576                 cb.cb_version = SPA_VERSION;
6577         } else if (!upgradeall && argc == 0) {
6578                 (void) fprintf(stderr, gettext("-V option is "
6579                     "incompatible with other arguments\n"));
6580                 usage(B_FALSE);
6581         }
6582
6583         if (showversions) {
6584                 if (upgradeall || argc != 0) {
6585                         (void) fprintf(stderr, gettext("-v option is "
6586                             "incompatible with other arguments\n"));
6587                         usage(B_FALSE);
6588                 }
6589         } else if (upgradeall) {
6590                 if (argc != 0) {
6591                         (void) fprintf(stderr, gettext("-a option should not "
6592                             "be used along with a pool name\n"));
6593                         usage(B_FALSE);
6594                 }
6595         }
6596
6597         (void) printf(gettext("This system supports ZFS pool feature "
6598             "flags.\n\n"));
6599         if (showversions) {
6600                 int i;
6601
6602                 (void) printf(gettext("The following features are "
6603                     "supported:\n\n"));
6604                 (void) printf(gettext("FEAT DESCRIPTION\n"));
6605                 (void) printf("----------------------------------------------"
6606                     "---------------\n");
6607                 for (i = 0; i < SPA_FEATURES; i++) {
6608                         zfeature_info_t *fi = &spa_feature_table[i];
6609                         const char *ro =
6610                             (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
6611                             " (read-only compatible)" : "";
6612
6613                         (void) printf("%-37s%s\n", fi->fi_uname, ro);
6614                         (void) printf("     %s\n", fi->fi_desc);
6615                 }
6616                 (void) printf("\n");
6617
6618                 (void) printf(gettext("The following legacy versions are also "
6619                     "supported:\n\n"));
6620                 (void) printf(gettext("VER  DESCRIPTION\n"));
6621                 (void) printf("---  -----------------------------------------"
6622                     "---------------\n");
6623                 (void) printf(gettext(" 1   Initial ZFS version\n"));
6624                 (void) printf(gettext(" 2   Ditto blocks "
6625                     "(replicated metadata)\n"));
6626                 (void) printf(gettext(" 3   Hot spares and double parity "
6627                     "RAID-Z\n"));
6628                 (void) printf(gettext(" 4   zpool history\n"));
6629                 (void) printf(gettext(" 5   Compression using the gzip "
6630                     "algorithm\n"));
6631                 (void) printf(gettext(" 6   bootfs pool property\n"));
6632                 (void) printf(gettext(" 7   Separate intent log devices\n"));
6633                 (void) printf(gettext(" 8   Delegated administration\n"));
6634                 (void) printf(gettext(" 9   refquota and refreservation "
6635                     "properties\n"));
6636                 (void) printf(gettext(" 10  Cache devices\n"));
6637                 (void) printf(gettext(" 11  Improved scrub performance\n"));
6638                 (void) printf(gettext(" 12  Snapshot properties\n"));
6639                 (void) printf(gettext(" 13  snapused property\n"));
6640                 (void) printf(gettext(" 14  passthrough-x aclinherit\n"));
6641                 (void) printf(gettext(" 15  user/group space accounting\n"));
6642                 (void) printf(gettext(" 16  stmf property support\n"));
6643                 (void) printf(gettext(" 17  Triple-parity RAID-Z\n"));
6644                 (void) printf(gettext(" 18  Snapshot user holds\n"));
6645                 (void) printf(gettext(" 19  Log device removal\n"));
6646                 (void) printf(gettext(" 20  Compression using zle "
6647                     "(zero-length encoding)\n"));
6648                 (void) printf(gettext(" 21  Deduplication\n"));
6649                 (void) printf(gettext(" 22  Received properties\n"));
6650                 (void) printf(gettext(" 23  Slim ZIL\n"));
6651                 (void) printf(gettext(" 24  System attributes\n"));
6652                 (void) printf(gettext(" 25  Improved scrub stats\n"));
6653                 (void) printf(gettext(" 26  Improved snapshot deletion "
6654                     "performance\n"));
6655                 (void) printf(gettext(" 27  Improved snapshot creation "
6656                     "performance\n"));
6657                 (void) printf(gettext(" 28  Multiple vdev replacements\n"));
6658                 (void) printf(gettext("\nFor more information on a particular "
6659                     "version, including supported releases,\n"));
6660                 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
6661         } else if (argc == 0 && upgradeall) {
6662                 cb.cb_first = B_TRUE;
6663                 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
6664                 if (ret == 0 && cb.cb_first) {
6665                         if (cb.cb_version == SPA_VERSION) {
6666                                 (void) printf(gettext("All pools are already "
6667                                     "formatted using feature flags.\n\n"));
6668                                 (void) printf(gettext("Every feature flags "
6669                                     "pool already has all supported features "
6670                                     "enabled.\n"));
6671                         } else {
6672                                 (void) printf(gettext("All pools are already "
6673                                     "formatted with version %llu or higher.\n"),
6674                                     (u_longlong_t)cb.cb_version);
6675                         }
6676                 }
6677         } else if (argc == 0) {
6678                 cb.cb_first = B_TRUE;
6679                 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
6680                 assert(ret == 0);
6681
6682                 if (cb.cb_first) {
6683                         (void) printf(gettext("All pools are formatted "
6684                             "using feature flags.\n\n"));
6685                 } else {
6686                         (void) printf(gettext("\nUse 'zpool upgrade -v' "
6687                             "for a list of available legacy versions.\n"));
6688                 }
6689
6690                 cb.cb_first = B_TRUE;
6691                 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
6692                 assert(ret == 0);
6693
6694                 if (cb.cb_first) {
6695                         (void) printf(gettext("Every feature flags pool has "
6696                             "all supported features enabled.\n"));
6697                 } else {
6698                         (void) printf(gettext("\n"));
6699                 }
6700         } else {
6701                 ret = for_each_pool(argc, argv, B_FALSE, NULL,
6702                     upgrade_one, &cb);
6703         }
6704
6705         return (ret);
6706 }
6707
6708 typedef struct hist_cbdata {
6709         boolean_t first;
6710         boolean_t longfmt;
6711         boolean_t internal;
6712 } hist_cbdata_t;
6713
6714 /*
6715  * Print out the command history for a specific pool.
6716  */
6717 static int
6718 get_history_one(zpool_handle_t *zhp, void *data)
6719 {
6720         nvlist_t *nvhis;
6721         nvlist_t **records;
6722         uint_t numrecords;
6723         int ret, i;
6724         hist_cbdata_t *cb = (hist_cbdata_t *)data;
6725
6726         cb->first = B_FALSE;
6727
6728         (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
6729
6730         if ((ret = zpool_get_history(zhp, &nvhis)) != 0)
6731                 return (ret);
6732
6733         verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
6734             &records, &numrecords) == 0);
6735         for (i = 0; i < numrecords; i++) {
6736                 nvlist_t *rec = records[i];
6737                 char tbuf[30] = "";
6738
6739                 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
6740                         time_t tsec;
6741                         struct tm t;
6742
6743                         tsec = fnvlist_lookup_uint64(records[i],
6744                             ZPOOL_HIST_TIME);
6745                         (void) localtime_r(&tsec, &t);
6746                         (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
6747                 }
6748
6749                 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
6750                         (void) printf("%s %s", tbuf,
6751                             fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
6752                 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
6753                         int ievent =
6754                             fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
6755                         if (!cb->internal)
6756                                 continue;
6757                         if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
6758                                 (void) printf("%s unrecognized record:\n",
6759                                     tbuf);
6760                                 dump_nvlist(rec, 4);
6761                                 continue;
6762                         }
6763                         (void) printf("%s [internal %s txg:%lld] %s", tbuf,
6764                             zfs_history_event_names[ievent],
6765                             (longlong_t)fnvlist_lookup_uint64(
6766                             rec, ZPOOL_HIST_TXG),
6767                             fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
6768                 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
6769                         if (!cb->internal)
6770                                 continue;
6771                         (void) printf("%s [txg:%lld] %s", tbuf,
6772                             (longlong_t)fnvlist_lookup_uint64(
6773                             rec, ZPOOL_HIST_TXG),
6774                             fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
6775                         if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
6776                                 (void) printf(" %s (%llu)",
6777                                     fnvlist_lookup_string(rec,
6778                                     ZPOOL_HIST_DSNAME),
6779                                     (u_longlong_t)fnvlist_lookup_uint64(rec,
6780                                     ZPOOL_HIST_DSID));
6781                         }
6782                         (void) printf(" %s", fnvlist_lookup_string(rec,
6783                             ZPOOL_HIST_INT_STR));
6784                 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
6785                         if (!cb->internal)
6786                                 continue;
6787                         (void) printf("%s ioctl %s\n", tbuf,
6788                             fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
6789                         if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
6790                                 (void) printf("    input:\n");
6791                                 dump_nvlist(fnvlist_lookup_nvlist(rec,
6792                                     ZPOOL_HIST_INPUT_NVL), 8);
6793                         }
6794                         if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
6795                                 (void) printf("    output:\n");
6796                                 dump_nvlist(fnvlist_lookup_nvlist(rec,
6797                                     ZPOOL_HIST_OUTPUT_NVL), 8);
6798                         }
6799                 } else {
6800                         if (!cb->internal)
6801                                 continue;
6802                         (void) printf("%s unrecognized record:\n", tbuf);
6803                         dump_nvlist(rec, 4);
6804                 }
6805
6806                 if (!cb->longfmt) {
6807                         (void) printf("\n");
6808                         continue;
6809                 }
6810                 (void) printf(" [");
6811                 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
6812                         uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
6813                         struct passwd *pwd = getpwuid(who);
6814                         (void) printf("user %d ", (int)who);
6815                         if (pwd != NULL)
6816                                 (void) printf("(%s) ", pwd->pw_name);
6817                 }
6818                 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
6819                         (void) printf("on %s",
6820                             fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
6821                 }
6822                 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
6823                         (void) printf(":%s",
6824                             fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
6825                 }
6826
6827                 (void) printf("]");
6828                 (void) printf("\n");
6829         }
6830         (void) printf("\n");
6831         nvlist_free(nvhis);
6832
6833         return (ret);
6834 }
6835
6836 /*
6837  * zpool history <pool>
6838  *
6839  * Displays the history of commands that modified pools.
6840  */
6841 int
6842 zpool_do_history(int argc, char **argv)
6843 {
6844         hist_cbdata_t cbdata = { 0 };
6845         int ret;
6846         int c;
6847
6848         cbdata.first = B_TRUE;
6849         /* check options */
6850         while ((c = getopt(argc, argv, "li")) != -1) {
6851                 switch (c) {
6852                 case 'l':
6853                         cbdata.longfmt = B_TRUE;
6854                         break;
6855                 case 'i':
6856                         cbdata.internal = B_TRUE;
6857                         break;
6858                 case '?':
6859                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6860                             optopt);
6861                         usage(B_FALSE);
6862                 }
6863         }
6864         argc -= optind;
6865         argv += optind;
6866
6867         ret = for_each_pool(argc, argv, B_FALSE,  NULL, get_history_one,
6868             &cbdata);
6869
6870         if (argc == 0 && cbdata.first == B_TRUE) {
6871                 (void) fprintf(stderr, gettext("no pools available\n"));
6872                 return (0);
6873         }
6874
6875         return (ret);
6876 }
6877
6878 typedef struct ev_opts {
6879         int verbose;
6880         int scripted;
6881         int follow;
6882         int clear;
6883 } ev_opts_t;
6884
6885 static void
6886 zpool_do_events_short(nvlist_t *nvl)
6887 {
6888         char ctime_str[26], str[32], *ptr;
6889         int64_t *tv;
6890         uint_t n;
6891
6892         verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
6893         memset(str, ' ', 32);
6894         (void) ctime_r((const time_t *)&tv[0], ctime_str);
6895         (void) strncpy(str, ctime_str+4,  6);           /* 'Jun 30' */
6896         (void) strncpy(str+7, ctime_str+20, 4);         /* '1993' */
6897         (void) strncpy(str+12, ctime_str+11, 8);        /* '21:49:08' */
6898         (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
6899         (void) printf(gettext("%s "), str);
6900
6901         verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
6902         (void) printf(gettext("%s\n"), ptr);
6903 }
6904
6905 static void
6906 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
6907 {
6908         nvpair_t *nvp;
6909
6910         for (nvp = nvlist_next_nvpair(nvl, NULL);
6911             nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
6912
6913                 data_type_t type = nvpair_type(nvp);
6914                 const char *name = nvpair_name(nvp);
6915
6916                 boolean_t b;
6917                 uint8_t i8;
6918                 uint16_t i16;
6919                 uint32_t i32;
6920                 uint64_t i64;
6921                 char *str;
6922                 nvlist_t *cnv;
6923
6924                 printf(gettext("%*s%s = "), depth, "", name);
6925
6926                 switch (type) {
6927                 case DATA_TYPE_BOOLEAN:
6928                         printf(gettext("%s"), "1");
6929                         break;
6930
6931                 case DATA_TYPE_BOOLEAN_VALUE:
6932                         (void) nvpair_value_boolean_value(nvp, &b);
6933                         printf(gettext("%s"), b ? "1" : "0");
6934                         break;
6935
6936                 case DATA_TYPE_BYTE:
6937                         (void) nvpair_value_byte(nvp, &i8);
6938                         printf(gettext("0x%x"), i8);
6939                         break;
6940
6941                 case DATA_TYPE_INT8:
6942                         (void) nvpair_value_int8(nvp, (void *)&i8);
6943                         printf(gettext("0x%x"), i8);
6944                         break;
6945
6946                 case DATA_TYPE_UINT8:
6947                         (void) nvpair_value_uint8(nvp, &i8);
6948                         printf(gettext("0x%x"), i8);
6949                         break;
6950
6951                 case DATA_TYPE_INT16:
6952                         (void) nvpair_value_int16(nvp, (void *)&i16);
6953                         printf(gettext("0x%x"), i16);
6954                         break;
6955
6956                 case DATA_TYPE_UINT16:
6957                         (void) nvpair_value_uint16(nvp, &i16);
6958                         printf(gettext("0x%x"), i16);
6959                         break;
6960
6961                 case DATA_TYPE_INT32:
6962                         (void) nvpair_value_int32(nvp, (void *)&i32);
6963                         printf(gettext("0x%x"), i32);
6964                         break;
6965
6966                 case DATA_TYPE_UINT32:
6967                         (void) nvpair_value_uint32(nvp, &i32);
6968                         printf(gettext("0x%x"), i32);
6969                         break;
6970
6971                 case DATA_TYPE_INT64:
6972                         (void) nvpair_value_int64(nvp, (void *)&i64);
6973                         printf(gettext("0x%llx"), (u_longlong_t)i64);
6974                         break;
6975
6976                 case DATA_TYPE_UINT64:
6977                         (void) nvpair_value_uint64(nvp, &i64);
6978                         /*
6979                          * translate vdev state values to readable
6980                          * strings to aide zpool events consumers
6981                          */
6982                         if (strcmp(name,
6983                             FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
6984                             strcmp(name,
6985                             FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
6986                                 printf(gettext("\"%s\" (0x%llx)"),
6987                                     zpool_state_to_name(i64, VDEV_AUX_NONE),
6988                                     (u_longlong_t)i64);
6989                         } else {
6990                                 printf(gettext("0x%llx"), (u_longlong_t)i64);
6991                         }
6992                         break;
6993
6994                 case DATA_TYPE_HRTIME:
6995                         (void) nvpair_value_hrtime(nvp, (void *)&i64);
6996                         printf(gettext("0x%llx"), (u_longlong_t)i64);
6997                         break;
6998
6999                 case DATA_TYPE_STRING:
7000                         (void) nvpair_value_string(nvp, &str);
7001                         printf(gettext("\"%s\""), str ? str : "<NULL>");
7002                         break;
7003
7004                 case DATA_TYPE_NVLIST:
7005                         printf(gettext("(embedded nvlist)\n"));
7006                         (void) nvpair_value_nvlist(nvp, &cnv);
7007                         zpool_do_events_nvprint(cnv, depth + 8);
7008                         printf(gettext("%*s(end %s)"), depth, "", name);
7009                         break;
7010
7011                 case DATA_TYPE_NVLIST_ARRAY: {
7012                         nvlist_t **val;
7013                         uint_t i, nelem;
7014
7015                         (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
7016                         printf(gettext("(%d embedded nvlists)\n"), nelem);
7017                         for (i = 0; i < nelem; i++) {
7018                                 printf(gettext("%*s%s[%d] = %s\n"),
7019                                     depth, "", name, i, "(embedded nvlist)");
7020                                 zpool_do_events_nvprint(val[i], depth + 8);
7021                                 printf(gettext("%*s(end %s[%i])\n"),
7022                                     depth, "", name, i);
7023                         }
7024                         printf(gettext("%*s(end %s)\n"), depth, "", name);
7025                         }
7026                         break;
7027
7028                 case DATA_TYPE_INT8_ARRAY: {
7029                         int8_t *val;
7030                         uint_t i, nelem;
7031
7032                         (void) nvpair_value_int8_array(nvp, &val, &nelem);
7033                         for (i = 0; i < nelem; i++)
7034                                 printf(gettext("0x%x "), val[i]);
7035
7036                         break;
7037                         }
7038
7039                 case DATA_TYPE_UINT8_ARRAY: {
7040                         uint8_t *val;
7041                         uint_t i, nelem;
7042
7043                         (void) nvpair_value_uint8_array(nvp, &val, &nelem);
7044                         for (i = 0; i < nelem; i++)
7045                                 printf(gettext("0x%x "), val[i]);
7046
7047                         break;
7048                         }
7049
7050                 case DATA_TYPE_INT16_ARRAY: {
7051                         int16_t *val;
7052                         uint_t i, nelem;
7053
7054                         (void) nvpair_value_int16_array(nvp, &val, &nelem);
7055                         for (i = 0; i < nelem; i++)
7056                                 printf(gettext("0x%x "), val[i]);
7057
7058                         break;
7059                         }
7060
7061                 case DATA_TYPE_UINT16_ARRAY: {
7062                         uint16_t *val;
7063                         uint_t i, nelem;
7064
7065                         (void) nvpair_value_uint16_array(nvp, &val, &nelem);
7066                         for (i = 0; i < nelem; i++)
7067                                 printf(gettext("0x%x "), val[i]);
7068
7069                         break;
7070                         }
7071
7072                 case DATA_TYPE_INT32_ARRAY: {
7073                         int32_t *val;
7074                         uint_t i, nelem;
7075
7076                         (void) nvpair_value_int32_array(nvp, &val, &nelem);
7077                         for (i = 0; i < nelem; i++)
7078                                 printf(gettext("0x%x "), val[i]);
7079
7080                         break;
7081                         }
7082
7083                 case DATA_TYPE_UINT32_ARRAY: {
7084                         uint32_t *val;
7085                         uint_t i, nelem;
7086
7087                         (void) nvpair_value_uint32_array(nvp, &val, &nelem);
7088                         for (i = 0; i < nelem; i++)
7089                                 printf(gettext("0x%x "), val[i]);
7090
7091                         break;
7092                         }
7093
7094                 case DATA_TYPE_INT64_ARRAY: {
7095                         int64_t *val;
7096                         uint_t i, nelem;
7097
7098                         (void) nvpair_value_int64_array(nvp, &val, &nelem);
7099                         for (i = 0; i < nelem; i++)
7100                                 printf(gettext("0x%llx "),
7101                                     (u_longlong_t)val[i]);
7102
7103                         break;
7104                         }
7105
7106                 case DATA_TYPE_UINT64_ARRAY: {
7107                         uint64_t *val;
7108                         uint_t i, nelem;
7109
7110                         (void) nvpair_value_uint64_array(nvp, &val, &nelem);
7111                         for (i = 0; i < nelem; i++)
7112                                 printf(gettext("0x%llx "),
7113                                     (u_longlong_t)val[i]);
7114
7115                         break;
7116                         }
7117
7118                 case DATA_TYPE_STRING_ARRAY: {
7119                         char **str;
7120                         uint_t i, nelem;
7121
7122                         (void) nvpair_value_string_array(nvp, &str, &nelem);
7123                         for (i = 0; i < nelem; i++)
7124                                 printf(gettext("\"%s\" "),
7125                                     str[i] ? str[i] : "<NULL>");
7126
7127                         break;
7128                         }
7129
7130                 case DATA_TYPE_BOOLEAN_ARRAY:
7131                 case DATA_TYPE_BYTE_ARRAY:
7132                 case DATA_TYPE_DOUBLE:
7133                 case DATA_TYPE_UNKNOWN:
7134                         printf(gettext("<unknown>"));
7135                         break;
7136                 }
7137
7138                 printf(gettext("\n"));
7139         }
7140 }
7141
7142 static int
7143 zpool_do_events_next(ev_opts_t *opts)
7144 {
7145         nvlist_t *nvl;
7146         int zevent_fd, ret, dropped;
7147
7148         zevent_fd = open(ZFS_DEV, O_RDWR);
7149         VERIFY(zevent_fd >= 0);
7150
7151         if (!opts->scripted)
7152                 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
7153
7154         while (1) {
7155                 ret = zpool_events_next(g_zfs, &nvl, &dropped,
7156                     (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
7157                 if (ret || nvl == NULL)
7158                         break;
7159
7160                 if (dropped > 0)
7161                         (void) printf(gettext("dropped %d events\n"), dropped);
7162
7163                 zpool_do_events_short(nvl);
7164
7165                 if (opts->verbose) {
7166                         zpool_do_events_nvprint(nvl, 8);
7167                         printf(gettext("\n"));
7168                 }
7169                 (void) fflush(stdout);
7170
7171                 nvlist_free(nvl);
7172         }
7173
7174         VERIFY(0 == close(zevent_fd));
7175
7176         return (ret);
7177 }
7178
7179 static int
7180 zpool_do_events_clear(ev_opts_t *opts)
7181 {
7182         int count, ret;
7183
7184         ret = zpool_events_clear(g_zfs, &count);
7185         if (!ret)
7186                 (void) printf(gettext("cleared %d events\n"), count);
7187
7188         return (ret);
7189 }
7190
7191 /*
7192  * zpool events [-vfc]
7193  *
7194  * Displays events logs by ZFS.
7195  */
7196 int
7197 zpool_do_events(int argc, char **argv)
7198 {
7199         ev_opts_t opts = { 0 };
7200         int ret;
7201         int c;
7202
7203         /* check options */
7204         while ((c = getopt(argc, argv, "vHfc")) != -1) {
7205                 switch (c) {
7206                 case 'v':
7207                         opts.verbose = 1;
7208                         break;
7209                 case 'H':
7210                         opts.scripted = 1;
7211                         break;
7212                 case 'f':
7213                         opts.follow = 1;
7214                         break;
7215                 case 'c':
7216                         opts.clear = 1;
7217                         break;
7218                 case '?':
7219                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7220                             optopt);
7221                         usage(B_FALSE);
7222                 }
7223         }
7224         argc -= optind;
7225         argv += optind;
7226
7227         if (opts.clear)
7228                 ret = zpool_do_events_clear(&opts);
7229         else
7230                 ret = zpool_do_events_next(&opts);
7231
7232         return (ret);
7233 }
7234
7235 static int
7236 get_callback(zpool_handle_t *zhp, void *data)
7237 {
7238         zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
7239         char value[MAXNAMELEN];
7240         zprop_source_t srctype;
7241         zprop_list_t *pl;
7242
7243         for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
7244
7245                 /*
7246                  * Skip the special fake placeholder. This will also skip
7247                  * over the name property when 'all' is specified.
7248                  */
7249                 if (pl->pl_prop == ZPOOL_PROP_NAME &&
7250                     pl == cbp->cb_proplist)
7251                         continue;
7252
7253                 if (pl->pl_prop == ZPROP_INVAL &&
7254                     (zpool_prop_feature(pl->pl_user_prop) ||
7255                     zpool_prop_unsupported(pl->pl_user_prop))) {
7256                         srctype = ZPROP_SRC_LOCAL;
7257
7258                         if (zpool_prop_get_feature(zhp, pl->pl_user_prop,
7259                             value, sizeof (value)) == 0) {
7260                                 zprop_print_one_property(zpool_get_name(zhp),
7261                                     cbp, pl->pl_user_prop, value, srctype,
7262                                     NULL, NULL);
7263                         }
7264                 } else {
7265                         if (zpool_get_prop(zhp, pl->pl_prop, value,
7266                             sizeof (value), &srctype, cbp->cb_literal) != 0)
7267                                 continue;
7268
7269                         zprop_print_one_property(zpool_get_name(zhp), cbp,
7270                             zpool_prop_to_name(pl->pl_prop), value, srctype,
7271                             NULL, NULL);
7272                 }
7273         }
7274         return (0);
7275 }
7276
7277 /*
7278  * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
7279  *
7280  *      -H      Scripted mode.  Don't display headers, and separate properties
7281  *              by a single tab.
7282  *      -o      List of columns to display.  Defaults to
7283  *              "name,property,value,source".
7284  *      -p      Display values in parsable (exact) format.
7285  *
7286  * Get properties of pools in the system. Output space statistics
7287  * for each one as well as other attributes.
7288  */
7289 int
7290 zpool_do_get(int argc, char **argv)
7291 {
7292         zprop_get_cbdata_t cb = { 0 };
7293         zprop_list_t fake_name = { 0 };
7294         int ret;
7295         int c, i;
7296         char *value;
7297
7298         cb.cb_first = B_TRUE;
7299
7300         /*
7301          * Set up default columns and sources.
7302          */
7303         cb.cb_sources = ZPROP_SRC_ALL;
7304         cb.cb_columns[0] = GET_COL_NAME;
7305         cb.cb_columns[1] = GET_COL_PROPERTY;
7306         cb.cb_columns[2] = GET_COL_VALUE;
7307         cb.cb_columns[3] = GET_COL_SOURCE;
7308         cb.cb_type = ZFS_TYPE_POOL;
7309
7310         /* check options */
7311         while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
7312                 switch (c) {
7313                 case 'p':
7314                         cb.cb_literal = B_TRUE;
7315                         break;
7316                 case 'H':
7317                         cb.cb_scripted = B_TRUE;
7318                         break;
7319                 case 'o':
7320                         bzero(&cb.cb_columns, sizeof (cb.cb_columns));
7321                         i = 0;
7322                         while (*optarg != '\0') {
7323                                 static char *col_subopts[] =
7324                                 { "name", "property", "value", "source",
7325                                 "all", NULL };
7326
7327                                 if (i == ZFS_GET_NCOLS) {
7328                                         (void) fprintf(stderr, gettext("too "
7329                                         "many fields given to -o "
7330                                         "option\n"));
7331                                         usage(B_FALSE);
7332                                 }
7333
7334                                 switch (getsubopt(&optarg, col_subopts,
7335                                     &value)) {
7336                                 case 0:
7337                                         cb.cb_columns[i++] = GET_COL_NAME;
7338                                         break;
7339                                 case 1:
7340                                         cb.cb_columns[i++] = GET_COL_PROPERTY;
7341                                         break;
7342                                 case 2:
7343                                         cb.cb_columns[i++] = GET_COL_VALUE;
7344                                         break;
7345                                 case 3:
7346                                         cb.cb_columns[i++] = GET_COL_SOURCE;
7347                                         break;
7348                                 case 4:
7349                                         if (i > 0) {
7350                                                 (void) fprintf(stderr,
7351                                                     gettext("\"all\" conflicts "
7352                                                     "with specific fields "
7353                                                     "given to -o option\n"));
7354                                                 usage(B_FALSE);
7355                                         }
7356                                         cb.cb_columns[0] = GET_COL_NAME;
7357                                         cb.cb_columns[1] = GET_COL_PROPERTY;
7358                                         cb.cb_columns[2] = GET_COL_VALUE;
7359                                         cb.cb_columns[3] = GET_COL_SOURCE;
7360                                         i = ZFS_GET_NCOLS;
7361                                         break;
7362                                 default:
7363                                         (void) fprintf(stderr,
7364                                             gettext("invalid column name "
7365                                             "'%s'\n"), value);
7366                                         usage(B_FALSE);
7367                                 }
7368                         }
7369                         break;
7370                 case '?':
7371                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7372                             optopt);
7373                         usage(B_FALSE);
7374                 }
7375         }
7376
7377         argc -= optind;
7378         argv += optind;
7379
7380         if (argc < 1) {
7381                 (void) fprintf(stderr, gettext("missing property "
7382                     "argument\n"));
7383                 usage(B_FALSE);
7384         }
7385
7386         if (zprop_get_list(g_zfs, argv[0], &cb.cb_proplist,
7387             ZFS_TYPE_POOL) != 0)
7388                 usage(B_FALSE);
7389
7390         argc--;
7391         argv++;
7392
7393         if (cb.cb_proplist != NULL) {
7394                 fake_name.pl_prop = ZPOOL_PROP_NAME;
7395                 fake_name.pl_width = strlen(gettext("NAME"));
7396                 fake_name.pl_next = cb.cb_proplist;
7397                 cb.cb_proplist = &fake_name;
7398         }
7399
7400         ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist,
7401             get_callback, &cb);
7402
7403         if (cb.cb_proplist == &fake_name)
7404                 zprop_free_list(fake_name.pl_next);
7405         else
7406                 zprop_free_list(cb.cb_proplist);
7407
7408         return (ret);
7409 }
7410
7411 typedef struct set_cbdata {
7412         char *cb_propname;
7413         char *cb_value;
7414         boolean_t cb_any_successful;
7415 } set_cbdata_t;
7416
7417 int
7418 set_callback(zpool_handle_t *zhp, void *data)
7419 {
7420         int error;
7421         set_cbdata_t *cb = (set_cbdata_t *)data;
7422
7423         error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
7424
7425         if (!error)
7426                 cb->cb_any_successful = B_TRUE;
7427
7428         return (error);
7429 }
7430
7431 int
7432 zpool_do_set(int argc, char **argv)
7433 {
7434         set_cbdata_t cb = { 0 };
7435         int error;
7436
7437         if (argc > 1 && argv[1][0] == '-') {
7438                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7439                     argv[1][1]);
7440                 usage(B_FALSE);
7441         }
7442
7443         if (argc < 2) {
7444                 (void) fprintf(stderr, gettext("missing property=value "
7445                     "argument\n"));
7446                 usage(B_FALSE);
7447         }
7448
7449         if (argc < 3) {
7450                 (void) fprintf(stderr, gettext("missing pool name\n"));
7451                 usage(B_FALSE);
7452         }
7453
7454         if (argc > 3) {
7455                 (void) fprintf(stderr, gettext("too many pool names\n"));
7456                 usage(B_FALSE);
7457         }
7458
7459         cb.cb_propname = argv[1];
7460         cb.cb_value = strchr(cb.cb_propname, '=');
7461         if (cb.cb_value == NULL) {
7462                 (void) fprintf(stderr, gettext("missing value in "
7463                     "property=value argument\n"));
7464                 usage(B_FALSE);
7465         }
7466
7467         *(cb.cb_value) = '\0';
7468         cb.cb_value++;
7469
7470         error = for_each_pool(argc - 2, argv + 2, B_TRUE, NULL,
7471             set_callback, &cb);
7472
7473         return (error);
7474 }
7475
7476 static int
7477 find_command_idx(char *command, int *idx)
7478 {
7479         int i;
7480
7481         for (i = 0; i < NCOMMAND; i++) {
7482                 if (command_table[i].name == NULL)
7483                         continue;
7484
7485                 if (strcmp(command, command_table[i].name) == 0) {
7486                         *idx = i;
7487                         return (0);
7488                 }
7489         }
7490         return (1);
7491 }
7492
7493 int
7494 main(int argc, char **argv)
7495 {
7496         int ret = 0;
7497         int i = 0;
7498         char *cmdname;
7499
7500         (void) setlocale(LC_ALL, "");
7501         (void) textdomain(TEXT_DOMAIN);
7502         srand(time(NULL));
7503
7504         dprintf_setup(&argc, argv);
7505
7506         opterr = 0;
7507
7508         /*
7509          * Make sure the user has specified some command.
7510          */
7511         if (argc < 2) {
7512                 (void) fprintf(stderr, gettext("missing command\n"));
7513                 usage(B_FALSE);
7514         }
7515
7516         cmdname = argv[1];
7517
7518         /*
7519          * Special case '-?'
7520          */
7521         if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
7522                 usage(B_TRUE);
7523
7524         if ((g_zfs = libzfs_init()) == NULL) {
7525                 (void) fprintf(stderr, "%s", libzfs_error_init(errno));
7526                 return (1);
7527         }
7528
7529         libzfs_print_on_error(g_zfs, B_TRUE);
7530
7531         zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
7532
7533         /*
7534          * Run the appropriate command.
7535          */
7536         if (find_command_idx(cmdname, &i) == 0) {
7537                 current_command = &command_table[i];
7538                 ret = command_table[i].func(argc - 1, argv + 1);
7539         } else if (strchr(cmdname, '=')) {
7540                 verify(find_command_idx("set", &i) == 0);
7541                 current_command = &command_table[i];
7542                 ret = command_table[i].func(argc, argv);
7543         } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
7544                 /*
7545                  * 'freeze' is a vile debugging abomination, so we treat
7546                  * it as such.
7547                  */
7548                 char buf[16384];
7549                 int fd = open(ZFS_DEV, O_RDWR);
7550                 (void) strlcpy((void *)buf, argv[2], sizeof (buf));
7551                 return (!!ioctl(fd, ZFS_IOC_POOL_FREEZE, buf));
7552         } else {
7553                 (void) fprintf(stderr, gettext("unrecognized "
7554                     "command '%s'\n"), cmdname);
7555                 usage(B_FALSE);
7556                 ret = 1;
7557         }
7558
7559         if (ret == 0 && log_history)
7560                 (void) zpool_log_history(g_zfs, history_str);
7561
7562         libzfs_fini(g_zfs);
7563
7564         /*
7565          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
7566          * for the purposes of running ::findleaks.
7567          */
7568         if (getenv("ZFS_ABORT") != NULL) {
7569                 (void) printf("dumping core by request\n");
7570                 abort();
7571         }
7572
7573         return (ret);
7574 }