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