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