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