Illumos #3064: usr/src/cmd/zpool/zpool_main.c misspells "successful"
[zfs.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 by Delphix. All rights reserved.
26  * Copyright (c) 2012 by Frederik Wessels. All rights reserved.
27  */
28
29 #include <assert.h>
30 #include <ctype.h>
31 #include <dirent.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <libgen.h>
35 #include <libintl.h>
36 #include <libuutil.h>
37 #include <locale.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <strings.h>
42 #include <unistd.h>
43 #include <priv.h>
44 #include <pwd.h>
45 #include <zone.h>
46 #include <sys/fs/zfs.h>
47 #include <sys/stat.h>
48 #include <sys/fm/util.h>
49 #include <sys/fm/protocol.h>
50
51 #include <libzfs.h>
52
53 #include "zpool_util.h"
54 #include "zfs_comutil.h"
55
56 #include "statcommon.h"
57
58 static int zpool_do_create(int, char **);
59 static int zpool_do_destroy(int, char **);
60
61 static int zpool_do_add(int, char **);
62 static int zpool_do_remove(int, char **);
63
64 static int zpool_do_list(int, char **);
65 static int zpool_do_iostat(int, char **);
66 static int zpool_do_status(int, char **);
67
68 static int zpool_do_online(int, char **);
69 static int zpool_do_offline(int, char **);
70 static int zpool_do_clear(int, char **);
71
72 static int zpool_do_reguid(int, char **);
73
74 static int zpool_do_attach(int, char **);
75 static int zpool_do_detach(int, char **);
76 static int zpool_do_replace(int, char **);
77 static int zpool_do_split(int, char **);
78
79 static int zpool_do_scrub(int, char **);
80
81 static int zpool_do_import(int, char **);
82 static int zpool_do_export(int, char **);
83
84 static int zpool_do_upgrade(int, char **);
85
86 static int zpool_do_history(int, char **);
87 static int zpool_do_events(int, char **);
88
89 static int zpool_do_get(int, char **);
90 static int zpool_do_set(int, char **);
91
92 /*
93  * These libumem hooks provide a reasonable set of defaults for the allocator's
94  * debugging facilities.
95  */
96
97 #ifdef DEBUG
98 const char *
99 _umem_debug_init(void)
100 {
101         return ("default,verbose"); /* $UMEM_DEBUG setting */
102 }
103
104 const char *
105 _umem_logging_init(void)
106 {
107         return ("fail,contents"); /* $UMEM_LOGGING setting */
108 }
109 #endif
110
111 typedef enum {
112         HELP_ADD,
113         HELP_ATTACH,
114         HELP_CLEAR,
115         HELP_CREATE,
116         HELP_DESTROY,
117         HELP_DETACH,
118         HELP_EXPORT,
119         HELP_HISTORY,
120         HELP_IMPORT,
121         HELP_IOSTAT,
122         HELP_LIST,
123         HELP_OFFLINE,
124         HELP_ONLINE,
125         HELP_REPLACE,
126         HELP_REMOVE,
127         HELP_SCRUB,
128         HELP_STATUS,
129         HELP_UPGRADE,
130         HELP_EVENTS,
131         HELP_GET,
132         HELP_SET,
133         HELP_SPLIT,
134         HELP_REGUID
135 } zpool_help_t;
136
137
138 typedef struct zpool_command {
139         const char      *name;
140         int             (*func)(int, char **);
141         zpool_help_t    usage;
142 } zpool_command_t;
143
144 /*
145  * Master command table.  Each ZFS command has a name, associated function, and
146  * usage message.  The usage messages need to be internationalized, so we have
147  * to have a function to return the usage message based on a command index.
148  *
149  * These commands are organized according to how they are displayed in the usage
150  * message.  An empty command (one with a NULL name) indicates an empty line in
151  * the generic usage message.
152  */
153 static zpool_command_t command_table[] = {
154         { "create",     zpool_do_create,        HELP_CREATE             },
155         { "destroy",    zpool_do_destroy,       HELP_DESTROY            },
156         { NULL },
157         { "add",        zpool_do_add,           HELP_ADD                },
158         { "remove",     zpool_do_remove,        HELP_REMOVE             },
159         { NULL },
160         { "list",       zpool_do_list,          HELP_LIST               },
161         { "iostat",     zpool_do_iostat,        HELP_IOSTAT             },
162         { "status",     zpool_do_status,        HELP_STATUS             },
163         { NULL },
164         { "online",     zpool_do_online,        HELP_ONLINE             },
165         { "offline",    zpool_do_offline,       HELP_OFFLINE            },
166         { "clear",      zpool_do_clear,         HELP_CLEAR              },
167         { NULL },
168         { "attach",     zpool_do_attach,        HELP_ATTACH             },
169         { "detach",     zpool_do_detach,        HELP_DETACH             },
170         { "replace",    zpool_do_replace,       HELP_REPLACE            },
171         { "split",      zpool_do_split,         HELP_SPLIT              },
172         { NULL },
173         { "scrub",      zpool_do_scrub,         HELP_SCRUB              },
174         { NULL },
175         { "import",     zpool_do_import,        HELP_IMPORT             },
176         { "export",     zpool_do_export,        HELP_EXPORT             },
177         { "upgrade",    zpool_do_upgrade,       HELP_UPGRADE            },
178         { "reguid",     zpool_do_reguid,        HELP_REGUID             },
179         { NULL },
180         { "history",    zpool_do_history,       HELP_HISTORY            },
181         { "events",     zpool_do_events,        HELP_EVENTS             },
182         { NULL },
183         { "get",        zpool_do_get,           HELP_GET                },
184         { "set",        zpool_do_set,           HELP_SET                },
185 };
186
187 #define NCOMMAND        (sizeof (command_table) / sizeof (command_table[0]))
188
189 zpool_command_t *current_command;
190 static char history_str[HIS_MAX_RECORD_LEN];
191
192 static uint_t timestamp_fmt = NODATE;
193
194 static const char *
195 get_usage(zpool_help_t idx) {
196         switch (idx) {
197         case HELP_ADD:
198                 return (gettext("\tadd [-fn] <pool> <vdev> ...\n"));
199         case HELP_ATTACH:
200                 return (gettext("\tattach [-f] <pool> <device> "
201                     "<new-device>\n"));
202         case HELP_CLEAR:
203                 return (gettext("\tclear [-nF] <pool> [device]\n"));
204         case HELP_CREATE:
205                 return (gettext("\tcreate [-fn] [-o property=value] ... \n"
206                     "\t    [-O file-system-property=value] ... \n"
207                     "\t    [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
208         case HELP_DESTROY:
209                 return (gettext("\tdestroy [-f] <pool>\n"));
210         case HELP_DETACH:
211                 return (gettext("\tdetach <pool> <device>\n"));
212         case HELP_EXPORT:
213                 return (gettext("\texport [-f] <pool> ...\n"));
214         case HELP_HISTORY:
215                 return (gettext("\thistory [-il] [<pool>] ...\n"));
216         case HELP_IMPORT:
217                 return (gettext("\timport [-d dir] [-D]\n"
218                     "\timport [-d dir | -c cachefile] [-F [-n]] <pool | id>\n"
219                     "\timport [-o mntopts] [-o property=value] ... \n"
220                     "\t    [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
221                     "[-R root] [-F [-n]] -a\n"
222                     "\timport [-o mntopts] [-o property=value] ... \n"
223                     "\t    [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
224                     "[-R root] [-F [-n]]\n"
225                     "\t    <pool | id> [newpool]\n"));
226         case HELP_IOSTAT:
227                 return (gettext("\tiostat [-v] [-T d|u] [pool] ... [interval "
228                     "[count]]\n"));
229         case HELP_LIST:
230                 return (gettext("\tlist [-H] [-o property[,...]] "
231                     "[-T d|u] [pool] ... [interval [count]]\n"));
232         case HELP_OFFLINE:
233                 return (gettext("\toffline [-t] <pool> <device> ...\n"));
234         case HELP_ONLINE:
235                 return (gettext("\tonline <pool> <device> ...\n"));
236         case HELP_REPLACE:
237                 return (gettext("\treplace [-f] <pool> <device> "
238                     "[new-device]\n"));
239         case HELP_REMOVE:
240                 return (gettext("\tremove <pool> <device> ...\n"));
241         case HELP_SCRUB:
242                 return (gettext("\tscrub [-s] <pool> ...\n"));
243         case HELP_STATUS:
244                 return (gettext("\tstatus [-vx] [-T d|u] [pool] ... [interval "
245                     "[count]]\n"));
246         case HELP_UPGRADE:
247                 return (gettext("\tupgrade\n"
248                     "\tupgrade -v\n"
249                     "\tupgrade [-V version] <-a | pool ...>\n"));
250         case HELP_EVENTS:
251                 return (gettext("\tevents [-vHfc]\n"));
252         case HELP_GET:
253                 return (gettext("\tget <\"all\" | property[,...]> "
254                     "<pool> ...\n"));
255         case HELP_SET:
256                 return (gettext("\tset <property=value> <pool> \n"));
257         case HELP_SPLIT:
258                 return (gettext("\tsplit [-n] [-R altroot] [-o mntopts]\n"
259                     "\t    [-o property=value] <pool> <newpool> "
260                     "[<device> ...]\n"));
261         case HELP_REGUID:
262                 return (gettext("\treguid <pool>\n"));
263         }
264
265         abort();
266         /* NOTREACHED */
267 }
268
269
270 /*
271  * Callback routine that will print out a pool property value.
272  */
273 static int
274 print_prop_cb(int prop, void *cb)
275 {
276         FILE *fp = cb;
277
278         (void) fprintf(fp, "\t%-15s  ", zpool_prop_to_name(prop));
279
280         if (zpool_prop_readonly(prop))
281                 (void) fprintf(fp, "  NO   ");
282         else
283                 (void) fprintf(fp, " YES   ");
284
285         if (zpool_prop_values(prop) == NULL)
286                 (void) fprintf(fp, "-\n");
287         else
288                 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
289
290         return (ZPROP_CONT);
291 }
292
293 /*
294  * Display usage message.  If we're inside a command, display only the usage for
295  * that command.  Otherwise, iterate over the entire command table and display
296  * a complete usage message.
297  */
298 void
299 usage(boolean_t requested)
300 {
301         FILE *fp = requested ? stdout : stderr;
302
303         if (current_command == NULL) {
304                 int i;
305
306                 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
307                 (void) fprintf(fp,
308                     gettext("where 'command' is one of the following:\n\n"));
309
310                 for (i = 0; i < NCOMMAND; i++) {
311                         if (command_table[i].name == NULL)
312                                 (void) fprintf(fp, "\n");
313                         else
314                                 (void) fprintf(fp, "%s",
315                                     get_usage(command_table[i].usage));
316                 }
317         } else {
318                 (void) fprintf(fp, gettext("usage:\n"));
319                 (void) fprintf(fp, "%s", get_usage(current_command->usage));
320         }
321
322         if (current_command != NULL &&
323             ((strcmp(current_command->name, "set") == 0) ||
324             (strcmp(current_command->name, "get") == 0) ||
325             (strcmp(current_command->name, "list") == 0))) {
326
327                 (void) fprintf(fp,
328                     gettext("\nthe following properties are supported:\n"));
329
330                 (void) fprintf(fp, "\n\t%-15s  %s   %s\n\n",
331                     "PROPERTY", "EDIT", "VALUES");
332
333                 /* Iterate over all properties */
334                 (void) zprop_iter(print_prop_cb, fp, B_FALSE, B_TRUE,
335                     ZFS_TYPE_POOL);
336         }
337
338         /*
339          * See comments at end of main().
340          */
341         if (getenv("ZFS_ABORT") != NULL) {
342                 (void) printf("dumping core by request\n");
343                 abort();
344         }
345
346         exit(requested ? 0 : 2);
347 }
348
349 void
350 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
351     boolean_t print_logs)
352 {
353         nvlist_t **child;
354         uint_t c, children;
355         char *vname;
356
357         if (name != NULL)
358                 (void) printf("\t%*s%s\n", indent, "", name);
359
360         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
361             &child, &children) != 0)
362                 return;
363
364         for (c = 0; c < children; c++) {
365                 uint64_t is_log = B_FALSE;
366
367                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
368                     &is_log);
369                 if ((is_log && !print_logs) || (!is_log && print_logs))
370                         continue;
371
372                 vname = zpool_vdev_name(g_zfs, zhp, child[c], B_FALSE);
373                 print_vdev_tree(zhp, vname, child[c], indent + 2,
374                     B_FALSE);
375                 free(vname);
376         }
377 }
378
379 /*
380  * Add a property pair (name, string-value) into a property nvlist.
381  */
382 static int
383 add_prop_list(const char *propname, char *propval, nvlist_t **props,
384     boolean_t poolprop)
385 {
386         zpool_prop_t prop = ZPROP_INVAL;
387         zfs_prop_t fprop;
388         nvlist_t *proplist;
389         const char *normnm;
390         char *strval;
391
392         if (*props == NULL &&
393             nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
394                 (void) fprintf(stderr,
395                     gettext("internal error: out of memory\n"));
396                 return (1);
397         }
398
399         proplist = *props;
400
401         if (poolprop) {
402                 if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL) {
403                         (void) fprintf(stderr, gettext("property '%s' is "
404                             "not a valid pool property\n"), propname);
405                         return (2);
406                 }
407                 normnm = zpool_prop_to_name(prop);
408         } else {
409                 if ((fprop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
410                         normnm = zfs_prop_to_name(fprop);
411                 } else {
412                         normnm = propname;
413                 }
414         }
415
416         if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
417             prop != ZPOOL_PROP_CACHEFILE) {
418                 (void) fprintf(stderr, gettext("property '%s' "
419                     "specified multiple times\n"), propname);
420                 return (2);
421         }
422
423         if (nvlist_add_string(proplist, normnm, propval) != 0) {
424                 (void) fprintf(stderr, gettext("internal "
425                     "error: out of memory\n"));
426                 return (1);
427         }
428
429         return (0);
430 }
431
432 /*
433  * zpool add [-fn] <pool> <vdev> ...
434  *
435  *      -f      Force addition of devices, even if they appear in use
436  *      -n      Do not add the devices, but display the resulting layout if
437  *              they were to be added.
438  *
439  * Adds the given vdevs to 'pool'.  As with create, the bulk of this work is
440  * handled by get_vdev_spec(), which constructs the nvlist needed to pass to
441  * libzfs.
442  */
443 int
444 zpool_do_add(int argc, char **argv)
445 {
446         boolean_t force = B_FALSE;
447         boolean_t dryrun = B_FALSE;
448         int c;
449         nvlist_t *nvroot;
450         char *poolname;
451         int ret;
452         zpool_handle_t *zhp;
453         nvlist_t *config;
454
455         /* check options */
456         while ((c = getopt(argc, argv, "fn")) != -1) {
457                 switch (c) {
458                 case 'f':
459                         force = B_TRUE;
460                         break;
461                 case 'n':
462                         dryrun = B_TRUE;
463                         break;
464                 case '?':
465                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
466                             optopt);
467                         usage(B_FALSE);
468                 }
469         }
470
471         argc -= optind;
472         argv += optind;
473
474         /* get pool name and check number of arguments */
475         if (argc < 1) {
476                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
477                 usage(B_FALSE);
478         }
479         if (argc < 2) {
480                 (void) fprintf(stderr, gettext("missing vdev specification\n"));
481                 usage(B_FALSE);
482         }
483
484         poolname = argv[0];
485
486         argc--;
487         argv++;
488
489         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
490                 return (1);
491
492         if ((config = zpool_get_config(zhp, NULL)) == NULL) {
493                 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
494                     poolname);
495                 zpool_close(zhp);
496                 return (1);
497         }
498
499         /* pass off to get_vdev_spec for processing */
500         nvroot = make_root_vdev(zhp, NULL, force, !force, B_FALSE, dryrun,
501             argc, argv);
502         if (nvroot == NULL) {
503                 zpool_close(zhp);
504                 return (1);
505         }
506
507         if (dryrun) {
508                 nvlist_t *poolnvroot;
509
510                 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
511                     &poolnvroot) == 0);
512
513                 (void) printf(gettext("would update '%s' to the following "
514                     "configuration:\n"), zpool_get_name(zhp));
515
516                 /* print original main pool and new tree */
517                 print_vdev_tree(zhp, poolname, poolnvroot, 0, B_FALSE);
518                 print_vdev_tree(zhp, NULL, nvroot, 0, B_FALSE);
519
520                 /* Do the same for the logs */
521                 if (num_logs(poolnvroot) > 0) {
522                         print_vdev_tree(zhp, "logs", poolnvroot, 0, B_TRUE);
523                         print_vdev_tree(zhp, NULL, nvroot, 0, B_TRUE);
524                 } else if (num_logs(nvroot) > 0) {
525                         print_vdev_tree(zhp, "logs", nvroot, 0, B_TRUE);
526                 }
527
528                 ret = 0;
529         } else {
530                 ret = (zpool_add(zhp, nvroot) != 0);
531         }
532
533         nvlist_free(nvroot);
534         zpool_close(zhp);
535
536         return (ret);
537 }
538
539 /*
540  * zpool remove  <pool> <vdev> ...
541  *
542  * Removes the given vdev from the pool.  Currently, this supports removing
543  * spares, cache, and log devices from the pool.
544  */
545 int
546 zpool_do_remove(int argc, char **argv)
547 {
548         char *poolname;
549         int i, ret = 0;
550         zpool_handle_t *zhp;
551
552         argc--;
553         argv++;
554
555         /* get pool name and check number of arguments */
556         if (argc < 1) {
557                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
558                 usage(B_FALSE);
559         }
560         if (argc < 2) {
561                 (void) fprintf(stderr, gettext("missing device\n"));
562                 usage(B_FALSE);
563         }
564
565         poolname = argv[0];
566
567         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
568                 return (1);
569
570         for (i = 1; i < argc; i++) {
571                 if (zpool_vdev_remove(zhp, argv[i]) != 0)
572                         ret = 1;
573         }
574
575         return (ret);
576 }
577
578 /*
579  * zpool create [-fn] [-o property=value] ...
580  *              [-O file-system-property=value] ...
581  *              [-R root] [-m mountpoint] <pool> <dev> ...
582  *
583  *      -f      Force creation, even if devices appear in use
584  *      -n      Do not create the pool, but display the resulting layout if it
585  *              were to be created.
586  *      -R      Create a pool under an alternate root
587  *      -m      Set default mountpoint for the root dataset.  By default it's
588  *              '/<pool>'
589  *      -o      Set property=value.
590  *      -O      Set fsproperty=value in the pool's root file system
591  *
592  * Creates the named pool according to the given vdev specification.  The
593  * bulk of the vdev processing is done in get_vdev_spec() in zpool_vdev.c.  Once
594  * we get the nvlist back from get_vdev_spec(), we either print out the contents
595  * (if '-n' was specified), or pass it to libzfs to do the creation.
596  */
597 int
598 zpool_do_create(int argc, char **argv)
599 {
600         boolean_t force = B_FALSE;
601         boolean_t dryrun = B_FALSE;
602         int c;
603         nvlist_t *nvroot = NULL;
604         char *poolname;
605         int ret = 1;
606         char *altroot = NULL;
607         char *mountpoint = NULL;
608         nvlist_t *fsprops = NULL;
609         nvlist_t *props = NULL;
610         char *propval;
611
612         /* check options */
613         while ((c = getopt(argc, argv, ":fnR:m:o:O:")) != -1) {
614                 switch (c) {
615                 case 'f':
616                         force = B_TRUE;
617                         break;
618                 case 'n':
619                         dryrun = B_TRUE;
620                         break;
621                 case 'R':
622                         altroot = optarg;
623                         if (add_prop_list(zpool_prop_to_name(
624                             ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
625                                 goto errout;
626                         if (nvlist_lookup_string(props,
627                             zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
628                             &propval) == 0)
629                                 break;
630                         if (add_prop_list(zpool_prop_to_name(
631                             ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
632                                 goto errout;
633                         break;
634                 case 'm':
635                         mountpoint = optarg;
636                         break;
637                 case 'o':
638                         if ((propval = strchr(optarg, '=')) == NULL) {
639                                 (void) fprintf(stderr, gettext("missing "
640                                     "'=' for -o option\n"));
641                                 goto errout;
642                         }
643                         *propval = '\0';
644                         propval++;
645
646                         if (add_prop_list(optarg, propval, &props, B_TRUE))
647                                 goto errout;
648                         break;
649                 case 'O':
650                         if ((propval = strchr(optarg, '=')) == NULL) {
651                                 (void) fprintf(stderr, gettext("missing "
652                                     "'=' for -O option\n"));
653                                 goto errout;
654                         }
655                         *propval = '\0';
656                         propval++;
657
658                         if (add_prop_list(optarg, propval, &fsprops, B_FALSE))
659                                 goto errout;
660                         break;
661                 case ':':
662                         (void) fprintf(stderr, gettext("missing argument for "
663                             "'%c' option\n"), optopt);
664                         goto badusage;
665                 case '?':
666                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
667                             optopt);
668                         goto badusage;
669                 }
670         }
671
672         argc -= optind;
673         argv += optind;
674
675         /* get pool name and check number of arguments */
676         if (argc < 1) {
677                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
678                 goto badusage;
679         }
680         if (argc < 2) {
681                 (void) fprintf(stderr, gettext("missing vdev specification\n"));
682                 goto badusage;
683         }
684
685         poolname = argv[0];
686
687         /*
688          * As a special case, check for use of '/' in the name, and direct the
689          * user to use 'zfs create' instead.
690          */
691         if (strchr(poolname, '/') != NULL) {
692                 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
693                     "character '/' in pool name\n"), poolname);
694                 (void) fprintf(stderr, gettext("use 'zfs create' to "
695                     "create a dataset\n"));
696                 goto errout;
697         }
698
699         /* pass off to get_vdev_spec for bulk processing */
700         nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
701             argc - 1, argv + 1);
702         if (nvroot == NULL)
703                 goto errout;
704
705         /* make_root_vdev() allows 0 toplevel children if there are spares */
706         if (!zfs_allocatable_devs(nvroot)) {
707                 (void) fprintf(stderr, gettext("invalid vdev "
708                     "specification: at least one toplevel vdev must be "
709                     "specified\n"));
710                 goto errout;
711         }
712
713
714         if (altroot != NULL && altroot[0] != '/') {
715                 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
716                     "must be an absolute path\n"), altroot);
717                 goto errout;
718         }
719
720         /*
721          * Check the validity of the mountpoint and direct the user to use the
722          * '-m' mountpoint option if it looks like its in use.
723          */
724         if (mountpoint == NULL ||
725             (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
726             strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
727                 char buf[MAXPATHLEN];
728                 DIR *dirp;
729
730                 if (mountpoint && mountpoint[0] != '/') {
731                         (void) fprintf(stderr, gettext("invalid mountpoint "
732                             "'%s': must be an absolute path, 'legacy', or "
733                             "'none'\n"), mountpoint);
734                         goto errout;
735                 }
736
737                 if (mountpoint == NULL) {
738                         if (altroot != NULL)
739                                 (void) snprintf(buf, sizeof (buf), "%s/%s",
740                                     altroot, poolname);
741                         else
742                                 (void) snprintf(buf, sizeof (buf), "/%s",
743                                     poolname);
744                 } else {
745                         if (altroot != NULL)
746                                 (void) snprintf(buf, sizeof (buf), "%s%s",
747                                     altroot, mountpoint);
748                         else
749                                 (void) snprintf(buf, sizeof (buf), "%s",
750                                     mountpoint);
751                 }
752
753                 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
754                         (void) fprintf(stderr, gettext("mountpoint '%s' : "
755                             "%s\n"), buf, strerror(errno));
756                         (void) fprintf(stderr, gettext("use '-m' "
757                             "option to provide a different default\n"));
758                         goto errout;
759                 } else if (dirp) {
760                         int count = 0;
761
762                         while (count < 3 && readdir(dirp) != NULL)
763                                 count++;
764                         (void) closedir(dirp);
765
766                         if (count > 2) {
767                                 (void) fprintf(stderr, gettext("mountpoint "
768                                     "'%s' exists and is not empty\n"), buf);
769                                 (void) fprintf(stderr, gettext("use '-m' "
770                                     "option to provide a "
771                                     "different default\n"));
772                                 goto errout;
773                         }
774                 }
775         }
776
777         if (dryrun) {
778                 /*
779                  * For a dry run invocation, print out a basic message and run
780                  * through all the vdevs in the list and print out in an
781                  * appropriate hierarchy.
782                  */
783                 (void) printf(gettext("would create '%s' with the "
784                     "following layout:\n\n"), poolname);
785
786                 print_vdev_tree(NULL, poolname, nvroot, 0, B_FALSE);
787                 if (num_logs(nvroot) > 0)
788                         print_vdev_tree(NULL, "logs", nvroot, 0, B_TRUE);
789
790                 ret = 0;
791         } else {
792                 /*
793                  * Hand off to libzfs.
794                  */
795                 if (zpool_create(g_zfs, poolname,
796                     nvroot, props, fsprops) == 0) {
797                         zfs_handle_t *pool = zfs_open(g_zfs, poolname,
798                             ZFS_TYPE_FILESYSTEM);
799                         if (pool != NULL) {
800                                 if (mountpoint != NULL)
801                                         verify(zfs_prop_set(pool,
802                                             zfs_prop_to_name(
803                                             ZFS_PROP_MOUNTPOINT),
804                                             mountpoint) == 0);
805                                 if (zfs_mount(pool, NULL, 0) == 0)
806                                         ret = zfs_shareall(pool);
807                                 zfs_close(pool);
808                         }
809                 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
810                         (void) fprintf(stderr, gettext("pool name may have "
811                             "been omitted\n"));
812                 }
813         }
814
815 errout:
816         nvlist_free(nvroot);
817         nvlist_free(fsprops);
818         nvlist_free(props);
819         return (ret);
820 badusage:
821         nvlist_free(fsprops);
822         nvlist_free(props);
823         usage(B_FALSE);
824         return (2);
825 }
826
827 /*
828  * zpool destroy <pool>
829  *
830  *      -f      Forcefully unmount any datasets
831  *
832  * Destroy the given pool.  Automatically unmounts any datasets in the pool.
833  */
834 int
835 zpool_do_destroy(int argc, char **argv)
836 {
837         boolean_t force = B_FALSE;
838         int c;
839         char *pool;
840         zpool_handle_t *zhp;
841         int ret;
842
843         /* check options */
844         while ((c = getopt(argc, argv, "f")) != -1) {
845                 switch (c) {
846                 case 'f':
847                         force = B_TRUE;
848                         break;
849                 case '?':
850                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
851                             optopt);
852                         usage(B_FALSE);
853                 }
854         }
855
856         argc -= optind;
857         argv += optind;
858
859         /* check arguments */
860         if (argc < 1) {
861                 (void) fprintf(stderr, gettext("missing pool argument\n"));
862                 usage(B_FALSE);
863         }
864         if (argc > 1) {
865                 (void) fprintf(stderr, gettext("too many arguments\n"));
866                 usage(B_FALSE);
867         }
868
869         pool = argv[0];
870
871         if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
872                 /*
873                  * As a special case, check for use of '/' in the name, and
874                  * direct the user to use 'zfs destroy' instead.
875                  */
876                 if (strchr(pool, '/') != NULL)
877                         (void) fprintf(stderr, gettext("use 'zfs destroy' to "
878                             "destroy a dataset\n"));
879                 return (1);
880         }
881
882         if (zpool_disable_datasets(zhp, force) != 0) {
883                 (void) fprintf(stderr, gettext("could not destroy '%s': "
884                     "could not unmount datasets\n"), zpool_get_name(zhp));
885                 return (1);
886         }
887
888         ret = (zpool_destroy(zhp) != 0);
889
890         zpool_close(zhp);
891
892         return (ret);
893 }
894
895 /*
896  * zpool export [-f] <pool> ...
897  *
898  *      -f      Forcefully unmount datasets
899  *
900  * Export the given pools.  By default, the command will attempt to cleanly
901  * unmount any active datasets within the pool.  If the '-f' flag is specified,
902  * then the datasets will be forcefully unmounted.
903  */
904 int
905 zpool_do_export(int argc, char **argv)
906 {
907         boolean_t force = B_FALSE;
908         boolean_t hardforce = B_FALSE;
909         int c;
910         zpool_handle_t *zhp;
911         int ret;
912         int i;
913
914         /* check options */
915         while ((c = getopt(argc, argv, "fF")) != -1) {
916                 switch (c) {
917                 case 'f':
918                         force = B_TRUE;
919                         break;
920                 case 'F':
921                         hardforce = B_TRUE;
922                         break;
923                 case '?':
924                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
925                             optopt);
926                         usage(B_FALSE);
927                 }
928         }
929
930         argc -= optind;
931         argv += optind;
932
933         /* check arguments */
934         if (argc < 1) {
935                 (void) fprintf(stderr, gettext("missing pool argument\n"));
936                 usage(B_FALSE);
937         }
938
939         ret = 0;
940         for (i = 0; i < argc; i++) {
941                 if ((zhp = zpool_open_canfail(g_zfs, argv[i])) == NULL) {
942                         ret = 1;
943                         continue;
944                 }
945
946                 if (zpool_disable_datasets(zhp, force) != 0) {
947                         ret = 1;
948                         zpool_close(zhp);
949                         continue;
950                 }
951
952                 if (hardforce) {
953                         if (zpool_export_force(zhp) != 0)
954                                 ret = 1;
955                 } else if (zpool_export(zhp, force) != 0) {
956                         ret = 1;
957                 }
958
959                 zpool_close(zhp);
960         }
961
962         return (ret);
963 }
964
965 /*
966  * Given a vdev configuration, determine the maximum width needed for the device
967  * name column.
968  */
969 static int
970 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max)
971 {
972         char *name = zpool_vdev_name(g_zfs, zhp, nv, B_TRUE);
973         nvlist_t **child;
974         uint_t c, children;
975         int ret;
976
977         if (strlen(name) + depth > max)
978                 max = strlen(name) + depth;
979
980         free(name);
981
982         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
983             &child, &children) == 0) {
984                 for (c = 0; c < children; c++)
985                         if ((ret = max_width(zhp, child[c], depth + 2,
986                             max)) > max)
987                                 max = ret;
988         }
989
990         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
991             &child, &children) == 0) {
992                 for (c = 0; c < children; c++)
993                         if ((ret = max_width(zhp, child[c], depth + 2,
994                             max)) > max)
995                                 max = ret;
996         }
997
998         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
999             &child, &children) == 0) {
1000                 for (c = 0; c < children; c++)
1001                         if ((ret = max_width(zhp, child[c], depth + 2,
1002                             max)) > max)
1003                                 max = ret;
1004         }
1005
1006
1007         return (max);
1008 }
1009
1010 typedef struct spare_cbdata {
1011         uint64_t        cb_guid;
1012         zpool_handle_t  *cb_zhp;
1013 } spare_cbdata_t;
1014
1015 static boolean_t
1016 find_vdev(nvlist_t *nv, uint64_t search)
1017 {
1018         uint64_t guid;
1019         nvlist_t **child;
1020         uint_t c, children;
1021
1022         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1023             search == guid)
1024                 return (B_TRUE);
1025
1026         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1027             &child, &children) == 0) {
1028                 for (c = 0; c < children; c++)
1029                         if (find_vdev(child[c], search))
1030                                 return (B_TRUE);
1031         }
1032
1033         return (B_FALSE);
1034 }
1035
1036 static int
1037 find_spare(zpool_handle_t *zhp, void *data)
1038 {
1039         spare_cbdata_t *cbp = data;
1040         nvlist_t *config, *nvroot;
1041
1042         config = zpool_get_config(zhp, NULL);
1043         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1044             &nvroot) == 0);
1045
1046         if (find_vdev(nvroot, cbp->cb_guid)) {
1047                 cbp->cb_zhp = zhp;
1048                 return (1);
1049         }
1050
1051         zpool_close(zhp);
1052         return (0);
1053 }
1054
1055 /*
1056  * Print out configuration state as requested by status_callback.
1057  */
1058 void
1059 print_status_config(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
1060     int namewidth, int depth, boolean_t isspare)
1061 {
1062         nvlist_t **child;
1063         uint_t c, children;
1064         pool_scan_stat_t *ps = NULL;
1065         vdev_stat_t *vs;
1066         char rbuf[6], wbuf[6], cbuf[6];
1067         char *vname;
1068         uint64_t notpresent;
1069         spare_cbdata_t cb;
1070         char *state;
1071
1072         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1073             &child, &children) != 0)
1074                 children = 0;
1075
1076         verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1077             (uint64_t **)&vs, &c) == 0);
1078
1079         state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1080         if (isspare) {
1081                 /*
1082                  * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
1083                  * online drives.
1084                  */
1085                 if (vs->vs_aux == VDEV_AUX_SPARED)
1086                         state = "INUSE";
1087                 else if (vs->vs_state == VDEV_STATE_HEALTHY)
1088                         state = "AVAIL";
1089         }
1090
1091         (void) printf("\t%*s%-*s  %-8s", depth, "", namewidth - depth,
1092             name, state);
1093
1094         if (!isspare) {
1095                 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
1096                 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
1097                 zfs_nicenum(vs->vs_checksum_errors, cbuf, sizeof (cbuf));
1098                 (void) printf(" %5s %5s %5s", rbuf, wbuf, cbuf);
1099         }
1100
1101         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
1102             &notpresent) == 0) {
1103                 char *path;
1104                 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
1105                 (void) printf("  was %s", path);
1106         } else if (vs->vs_aux != 0) {
1107                 (void) printf("  ");
1108
1109                 switch (vs->vs_aux) {
1110                 case VDEV_AUX_OPEN_FAILED:
1111                         (void) printf(gettext("cannot open"));
1112                         break;
1113
1114                 case VDEV_AUX_BAD_GUID_SUM:
1115                         (void) printf(gettext("missing device"));
1116                         break;
1117
1118                 case VDEV_AUX_NO_REPLICAS:
1119                         (void) printf(gettext("insufficient replicas"));
1120                         break;
1121
1122                 case VDEV_AUX_VERSION_NEWER:
1123                         (void) printf(gettext("newer version"));
1124                         break;
1125
1126                 case VDEV_AUX_SPARED:
1127                         verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
1128                             &cb.cb_guid) == 0);
1129                         if (zpool_iter(g_zfs, find_spare, &cb) == 1) {
1130                                 if (strcmp(zpool_get_name(cb.cb_zhp),
1131                                     zpool_get_name(zhp)) == 0)
1132                                         (void) printf(gettext("currently in "
1133                                             "use"));
1134                                 else
1135                                         (void) printf(gettext("in use by "
1136                                             "pool '%s'"),
1137                                             zpool_get_name(cb.cb_zhp));
1138                                 zpool_close(cb.cb_zhp);
1139                         } else {
1140                                 (void) printf(gettext("currently in use"));
1141                         }
1142                         break;
1143
1144                 case VDEV_AUX_ERR_EXCEEDED:
1145                         (void) printf(gettext("too many errors"));
1146                         break;
1147
1148                 case VDEV_AUX_IO_FAILURE:
1149                         (void) printf(gettext("experienced I/O failures"));
1150                         break;
1151
1152                 case VDEV_AUX_BAD_LOG:
1153                         (void) printf(gettext("bad intent log"));
1154                         break;
1155
1156                 case VDEV_AUX_EXTERNAL:
1157                         (void) printf(gettext("external device fault"));
1158                         break;
1159
1160                 case VDEV_AUX_SPLIT_POOL:
1161                         (void) printf(gettext("split into new pool"));
1162                         break;
1163
1164                 default:
1165                         (void) printf(gettext("corrupted data"));
1166                         break;
1167                 }
1168         }
1169
1170         (void) nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_SCAN_STATS,
1171             (uint64_t **)&ps, &c);
1172
1173         if (ps && ps->pss_state == DSS_SCANNING &&
1174             vs->vs_scan_processed != 0 && children == 0) {
1175                 (void) printf(gettext("  (%s)"),
1176                     (ps->pss_func == POOL_SCAN_RESILVER) ?
1177                     "resilvering" : "repairing");
1178         }
1179
1180         (void) printf("\n");
1181
1182         for (c = 0; c < children; c++) {
1183                 uint64_t islog = B_FALSE, ishole = B_FALSE;
1184
1185                 /* Don't print logs or holes here */
1186                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1187                     &islog);
1188                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
1189                     &ishole);
1190                 if (islog || ishole)
1191                         continue;
1192                 vname = zpool_vdev_name(g_zfs, zhp, child[c], B_TRUE);
1193                 print_status_config(zhp, vname, child[c],
1194                     namewidth, depth + 2, isspare);
1195                 free(vname);
1196         }
1197 }
1198
1199
1200 /*
1201  * Print the configuration of an exported pool.  Iterate over all vdevs in the
1202  * pool, printing out the name and status for each one.
1203  */
1204 void
1205 print_import_config(const char *name, nvlist_t *nv, int namewidth, int depth)
1206 {
1207         nvlist_t **child;
1208         uint_t c, children;
1209         vdev_stat_t *vs;
1210         char *type, *vname;
1211
1212         verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1213         if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
1214             strcmp(type, VDEV_TYPE_HOLE) == 0)
1215                 return;
1216
1217         verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1218             (uint64_t **)&vs, &c) == 0);
1219
1220         (void) printf("\t%*s%-*s", depth, "", namewidth - depth, name);
1221         (void) printf("  %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
1222
1223         if (vs->vs_aux != 0) {
1224                 (void) printf("  ");
1225
1226                 switch (vs->vs_aux) {
1227                 case VDEV_AUX_OPEN_FAILED:
1228                         (void) printf(gettext("cannot open"));
1229                         break;
1230
1231                 case VDEV_AUX_BAD_GUID_SUM:
1232                         (void) printf(gettext("missing device"));
1233                         break;
1234
1235                 case VDEV_AUX_NO_REPLICAS:
1236                         (void) printf(gettext("insufficient replicas"));
1237                         break;
1238
1239                 case VDEV_AUX_VERSION_NEWER:
1240                         (void) printf(gettext("newer version"));
1241                         break;
1242
1243                 case VDEV_AUX_ERR_EXCEEDED:
1244                         (void) printf(gettext("too many errors"));
1245                         break;
1246
1247                 default:
1248                         (void) printf(gettext("corrupted data"));
1249                         break;
1250                 }
1251         }
1252         (void) printf("\n");
1253
1254         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1255             &child, &children) != 0)
1256                 return;
1257
1258         for (c = 0; c < children; c++) {
1259                 uint64_t is_log = B_FALSE;
1260
1261                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1262                     &is_log);
1263                 if (is_log)
1264                         continue;
1265
1266                 vname = zpool_vdev_name(g_zfs, NULL, child[c], B_TRUE);
1267                 print_import_config(vname, child[c], namewidth, depth + 2);
1268                 free(vname);
1269         }
1270
1271         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1272             &child, &children) == 0) {
1273                 (void) printf(gettext("\tcache\n"));
1274                 for (c = 0; c < children; c++) {
1275                         vname = zpool_vdev_name(g_zfs, NULL, child[c], B_FALSE);
1276                         (void) printf("\t  %s\n", vname);
1277                         free(vname);
1278                 }
1279         }
1280
1281         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1282             &child, &children) == 0) {
1283                 (void) printf(gettext("\tspares\n"));
1284                 for (c = 0; c < children; c++) {
1285                         vname = zpool_vdev_name(g_zfs, NULL, child[c], B_FALSE);
1286                         (void) printf("\t  %s\n", vname);
1287                         free(vname);
1288                 }
1289         }
1290 }
1291
1292 /*
1293  * Print log vdevs.
1294  * Logs are recorded as top level vdevs in the main pool child array
1295  * but with "is_log" set to 1. We use either print_status_config() or
1296  * print_import_config() to print the top level logs then any log
1297  * children (eg mirrored slogs) are printed recursively - which
1298  * works because only the top level vdev is marked "is_log"
1299  */
1300 static void
1301 print_logs(zpool_handle_t *zhp, nvlist_t *nv, int namewidth, boolean_t verbose)
1302 {
1303         uint_t c, children;
1304         nvlist_t **child;
1305
1306         if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
1307             &children) != 0)
1308                 return;
1309
1310         (void) printf(gettext("\tlogs\n"));
1311
1312         for (c = 0; c < children; c++) {
1313                 uint64_t is_log = B_FALSE;
1314                 char *name;
1315
1316                 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1317                     &is_log);
1318                 if (!is_log)
1319                         continue;
1320                 name = zpool_vdev_name(g_zfs, zhp, child[c], B_TRUE);
1321                 if (verbose)
1322                         print_status_config(zhp, name, child[c], namewidth,
1323                             2, B_FALSE);
1324                 else
1325                         print_import_config(name, child[c], namewidth, 2);
1326                 free(name);
1327         }
1328 }
1329
1330 /*
1331  * Display the status for the given pool.
1332  */
1333 static void
1334 show_import(nvlist_t *config)
1335 {
1336         uint64_t pool_state;
1337         vdev_stat_t *vs;
1338         char *name;
1339         uint64_t guid;
1340         char *msgid;
1341         nvlist_t *nvroot;
1342         int reason;
1343         const char *health;
1344         uint_t vsc;
1345         int namewidth;
1346         char *comment;
1347
1348         verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1349             &name) == 0);
1350         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1351             &guid) == 0);
1352         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
1353             &pool_state) == 0);
1354         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1355             &nvroot) == 0);
1356
1357         verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
1358             (uint64_t **)&vs, &vsc) == 0);
1359         health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1360
1361         reason = zpool_import_status(config, &msgid);
1362
1363         (void) printf(gettext("   pool: %s\n"), name);
1364         (void) printf(gettext("     id: %llu\n"), (u_longlong_t)guid);
1365         (void) printf(gettext("  state: %s"), health);
1366         if (pool_state == POOL_STATE_DESTROYED)
1367                 (void) printf(gettext(" (DESTROYED)"));
1368         (void) printf("\n");
1369
1370         switch (reason) {
1371         case ZPOOL_STATUS_MISSING_DEV_R:
1372         case ZPOOL_STATUS_MISSING_DEV_NR:
1373         case ZPOOL_STATUS_BAD_GUID_SUM:
1374                 (void) printf(gettext(" status: One or more devices are "
1375                     "missing from the system.\n"));
1376                 break;
1377
1378         case ZPOOL_STATUS_CORRUPT_LABEL_R:
1379         case ZPOOL_STATUS_CORRUPT_LABEL_NR:
1380                 (void) printf(gettext(" status: One or more devices contains "
1381                     "corrupted data.\n"));
1382                 break;
1383
1384         case ZPOOL_STATUS_CORRUPT_DATA:
1385                 (void) printf(
1386                     gettext(" status: The pool data is corrupted.\n"));
1387                 break;
1388
1389         case ZPOOL_STATUS_OFFLINE_DEV:
1390                 (void) printf(gettext(" status: One or more devices "
1391                     "are offlined.\n"));
1392                 break;
1393
1394         case ZPOOL_STATUS_CORRUPT_POOL:
1395                 (void) printf(gettext(" status: The pool metadata is "
1396                     "corrupted.\n"));
1397                 break;
1398
1399         case ZPOOL_STATUS_VERSION_OLDER:
1400                 (void) printf(gettext(" status: The pool is formatted using an "
1401                     "older on-disk version.\n"));
1402                 break;
1403
1404         case ZPOOL_STATUS_VERSION_NEWER:
1405                 (void) printf(gettext(" status: The pool is formatted using an "
1406                     "incompatible version.\n"));
1407                 break;
1408
1409         case ZPOOL_STATUS_HOSTID_MISMATCH:
1410                 (void) printf(gettext(" status: The pool was last accessed by "
1411                     "another system.\n"));
1412                 break;
1413
1414         case ZPOOL_STATUS_FAULTED_DEV_R:
1415         case ZPOOL_STATUS_FAULTED_DEV_NR:
1416                 (void) printf(gettext(" status: One or more devices are "
1417                     "faulted.\n"));
1418                 break;
1419
1420         case ZPOOL_STATUS_BAD_LOG:
1421                 (void) printf(gettext(" status: An intent log record cannot be "
1422                     "read.\n"));
1423                 break;
1424
1425         case ZPOOL_STATUS_RESILVERING:
1426                 (void) printf(gettext(" status: One or more devices were being "
1427                     "resilvered.\n"));
1428                 break;
1429
1430         default:
1431                 /*
1432                  * No other status can be seen when importing pools.
1433                  */
1434                 assert(reason == ZPOOL_STATUS_OK);
1435         }
1436
1437         /*
1438          * Print out an action according to the overall state of the pool.
1439          */
1440         if (vs->vs_state == VDEV_STATE_HEALTHY) {
1441                 if (reason == ZPOOL_STATUS_VERSION_OLDER)
1442                         (void) printf(gettext(" action: The pool can be "
1443                             "imported using its name or numeric identifier, "
1444                             "though\n\tsome features will not be available "
1445                             "without an explicit 'zpool upgrade'.\n"));
1446                 else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH)
1447                         (void) printf(gettext(" action: The pool can be "
1448                             "imported using its name or numeric "
1449                             "identifier and\n\tthe '-f' flag.\n"));
1450                 else
1451                         (void) printf(gettext(" action: The pool can be "
1452                             "imported using its name or numeric "
1453                             "identifier.\n"));
1454         } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
1455                 (void) printf(gettext(" action: The pool can be imported "
1456                     "despite missing or damaged devices.  The\n\tfault "
1457                     "tolerance of the pool may be compromised if imported.\n"));
1458         } else {
1459                 switch (reason) {
1460                 case ZPOOL_STATUS_VERSION_NEWER:
1461                         (void) printf(gettext(" action: The pool cannot be "
1462                             "imported.  Access the pool on a system running "
1463                             "newer\n\tsoftware, or recreate the pool from "
1464                             "backup.\n"));
1465                         break;
1466                 case ZPOOL_STATUS_MISSING_DEV_R:
1467                 case ZPOOL_STATUS_MISSING_DEV_NR:
1468                 case ZPOOL_STATUS_BAD_GUID_SUM:
1469                         (void) printf(gettext(" action: The pool cannot be "
1470                             "imported. Attach the missing\n\tdevices and try "
1471                             "again.\n"));
1472                         break;
1473                 default:
1474                         (void) printf(gettext(" action: The pool cannot be "
1475                             "imported due to damaged devices or data.\n"));
1476                 }
1477         }
1478
1479         /* Print the comment attached to the pool. */
1480         if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
1481                 (void) printf(gettext("comment: %s\n"), comment);
1482
1483         /*
1484          * If the state is "closed" or "can't open", and the aux state
1485          * is "corrupt data":
1486          */
1487         if (((vs->vs_state == VDEV_STATE_CLOSED) ||
1488             (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
1489             (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
1490                 if (pool_state == POOL_STATE_DESTROYED)
1491                         (void) printf(gettext("\tThe pool was destroyed, "
1492                             "but can be imported using the '-Df' flags.\n"));
1493                 else if (pool_state != POOL_STATE_EXPORTED)
1494                         (void) printf(gettext("\tThe pool may be active on "
1495                             "another system, but can be imported using\n\t"
1496                             "the '-f' flag.\n"));
1497         }
1498
1499         if (msgid != NULL)
1500                 (void) printf(gettext("   see: http://zfsonlinux.org/msg/%s\n"),
1501                     msgid);
1502
1503         (void) printf(gettext(" config:\n\n"));
1504
1505         namewidth = max_width(NULL, nvroot, 0, 0);
1506         if (namewidth < 10)
1507                 namewidth = 10;
1508
1509         print_import_config(name, nvroot, namewidth, 0);
1510         if (num_logs(nvroot) > 0)
1511                 print_logs(NULL, nvroot, namewidth, B_FALSE);
1512
1513         if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
1514                 (void) printf(gettext("\n\tAdditional devices are known to "
1515                     "be part of this pool, though their\n\texact "
1516                     "configuration cannot be determined.\n"));
1517         }
1518 }
1519
1520 /*
1521  * Perform the import for the given configuration.  This passes the heavy
1522  * lifting off to zpool_import_props(), and then mounts the datasets contained
1523  * within the pool.
1524  */
1525 static int
1526 do_import(nvlist_t *config, const char *newname, const char *mntopts,
1527     nvlist_t *props, int flags)
1528 {
1529         zpool_handle_t *zhp;
1530         char *name;
1531         uint64_t state;
1532         uint64_t version;
1533
1534         verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1535             &name) == 0);
1536
1537         verify(nvlist_lookup_uint64(config,
1538             ZPOOL_CONFIG_POOL_STATE, &state) == 0);
1539         verify(nvlist_lookup_uint64(config,
1540             ZPOOL_CONFIG_VERSION, &version) == 0);
1541         if (version > SPA_VERSION) {
1542                 (void) fprintf(stderr, gettext("cannot import '%s': pool "
1543                     "is formatted using a newer ZFS version\n"), name);
1544                 return (1);
1545         } else if (state != POOL_STATE_EXPORTED &&
1546             !(flags & ZFS_IMPORT_ANY_HOST)) {
1547                 uint64_t hostid;
1548
1549                 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
1550                     &hostid) == 0) {
1551                         unsigned long system_hostid = gethostid() & 0xffffffff;
1552
1553                         if ((unsigned long)hostid != system_hostid) {
1554                                 char *hostname;
1555                                 uint64_t timestamp;
1556                                 time_t t;
1557
1558                                 verify(nvlist_lookup_string(config,
1559                                     ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
1560                                 verify(nvlist_lookup_uint64(config,
1561                                     ZPOOL_CONFIG_TIMESTAMP, &timestamp) == 0);
1562                                 t = timestamp;
1563                                 (void) fprintf(stderr, gettext("cannot import "
1564                                     "'%s': pool may be in use from other "
1565                                     "system, it was last accessed by %s "
1566                                     "(hostid: 0x%lx) on %s"), name, hostname,
1567                                     (unsigned long)hostid,
1568                                     asctime(localtime(&t)));
1569                                 (void) fprintf(stderr, gettext("use '-f' to "
1570                                     "import anyway\n"));
1571                                 return (1);
1572                         }
1573                 } else {
1574                         (void) fprintf(stderr, gettext("cannot import '%s': "
1575                             "pool may be in use from other system\n"), name);
1576                         (void) fprintf(stderr, gettext("use '-f' to import "
1577                             "anyway\n"));
1578                         return (1);
1579                 }
1580         }
1581
1582         if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
1583                 return (1);
1584
1585         if (newname != NULL)
1586                 name = (char *)newname;
1587
1588         if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
1589                 return (1);
1590
1591         if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
1592             !(flags & ZFS_IMPORT_ONLY) &&
1593             zpool_enable_datasets(zhp, mntopts, 0) != 0) {
1594                 zpool_close(zhp);
1595                 return (1);
1596         }
1597
1598         zpool_close(zhp);
1599         return (0);
1600 }
1601
1602 /*
1603  * zpool import [-d dir] [-D]
1604  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D]
1605  *              [-d dir | -c cachefile] [-f] -a
1606  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D]
1607  *              [-d dir | -c cachefile] [-f] [-n] [-F] <pool | id> [newpool]
1608  *
1609  *       -c     Read pool information from a cachefile instead of searching
1610  *              devices.
1611  *
1612  *       -d     Scan in a specific directory, other than /dev/.  More than
1613  *              one directory can be specified using multiple '-d' options.
1614  *
1615  *       -D     Scan for previously destroyed pools or import all or only
1616  *              specified destroyed pools.
1617  *
1618  *       -R     Temporarily import the pool, with all mountpoints relative to
1619  *              the given root.  The pool will remain exported when the machine
1620  *              is rebooted.
1621  *
1622  *       -V     Import even in the presence of faulted vdevs.  This is an
1623  *              intentionally undocumented option for testing purposes, and
1624  *              treats the pool configuration as complete, leaving any bad
1625  *              vdevs in the FAULTED state. In other words, it does verbatim
1626  *              import.
1627  *
1628  *       -f     Force import, even if it appears that the pool is active.
1629  *
1630  *       -F     Attempt rewind if necessary.
1631  *
1632  *       -n     See if rewind would work, but don't actually rewind.
1633  *
1634  *       -N     Import the pool but don't mount datasets.
1635  *
1636  *       -T     Specify a starting txg to use for import. This option is
1637  *              intentionally undocumented option for testing purposes.
1638  *
1639  *       -a     Import all pools found.
1640  *
1641  *       -o     Set property=value and/or temporary mount options (without '=').
1642  *
1643  * The import command scans for pools to import, and import pools based on pool
1644  * name and GUID.  The pool can also be renamed as part of the import process.
1645  */
1646 int
1647 zpool_do_import(int argc, char **argv)
1648 {
1649         char **searchdirs = NULL;
1650         int nsearch = 0;
1651         int c;
1652         int err = 0;
1653         nvlist_t *pools = NULL;
1654         boolean_t do_all = B_FALSE;
1655         boolean_t do_destroyed = B_FALSE;
1656         char *mntopts = NULL;
1657         nvpair_t *elem;
1658         nvlist_t *config;
1659         uint64_t searchguid = 0;
1660         char *searchname = NULL;
1661         char *propval;
1662         nvlist_t *found_config;
1663         nvlist_t *policy = NULL;
1664         nvlist_t *props = NULL;
1665         boolean_t first;
1666         int flags = ZFS_IMPORT_NORMAL;
1667         uint32_t rewind_policy = ZPOOL_NO_REWIND;
1668         boolean_t dryrun = B_FALSE;
1669         boolean_t do_rewind = B_FALSE;
1670         boolean_t xtreme_rewind = B_FALSE;
1671         uint64_t pool_state, txg = -1ULL;
1672         char *cachefile = NULL;
1673         importargs_t idata = { 0 };
1674         char *endptr;
1675
1676         /* check options */
1677         while ((c = getopt(argc, argv, ":aCc:d:DEfFmnNo:rR:T:VX")) != -1) {
1678                 switch (c) {
1679                 case 'a':
1680                         do_all = B_TRUE;
1681                         break;
1682                 case 'c':
1683                         cachefile = optarg;
1684                         break;
1685                 case 'd':
1686                         if (searchdirs == NULL) {
1687                                 searchdirs = safe_malloc(sizeof (char *));
1688                         } else {
1689                                 char **tmp = safe_malloc((nsearch + 1) *
1690                                     sizeof (char *));
1691                                 bcopy(searchdirs, tmp, nsearch *
1692                                     sizeof (char *));
1693                                 free(searchdirs);
1694                                 searchdirs = tmp;
1695                         }
1696                         searchdirs[nsearch++] = optarg;
1697                         break;
1698                 case 'D':
1699                         do_destroyed = B_TRUE;
1700                         break;
1701                 case 'f':
1702                         flags |= ZFS_IMPORT_ANY_HOST;
1703                         break;
1704                 case 'F':
1705                         do_rewind = B_TRUE;
1706                         break;
1707                 case 'm':
1708                         flags |= ZFS_IMPORT_MISSING_LOG;
1709                         break;
1710                 case 'n':
1711                         dryrun = B_TRUE;
1712                         break;
1713                 case 'N':
1714                         flags |= ZFS_IMPORT_ONLY;
1715                         break;
1716                 case 'o':
1717                         if ((propval = strchr(optarg, '=')) != NULL) {
1718                                 *propval = '\0';
1719                                 propval++;
1720                                 if (add_prop_list(optarg, propval,
1721                                     &props, B_TRUE))
1722                                         goto error;
1723                         } else {
1724                                 mntopts = optarg;
1725                         }
1726                         break;
1727                 case 'R':
1728                         if (add_prop_list(zpool_prop_to_name(
1729                             ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
1730                                 goto error;
1731                         if (nvlist_lookup_string(props,
1732                             zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
1733                             &propval) == 0)
1734                                 break;
1735                         if (add_prop_list(zpool_prop_to_name(
1736                             ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1737                                 goto error;
1738                         break;
1739                 case 'T':
1740                         errno = 0;
1741                         txg = strtoull(optarg, &endptr, 10);
1742                         if (errno != 0 || *endptr != '\0') {
1743                                 (void) fprintf(stderr,
1744                                     gettext("invalid txg value\n"));
1745                                 usage(B_FALSE);
1746                         }
1747                         rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
1748                         break;
1749                 case 'V':
1750                         flags |= ZFS_IMPORT_VERBATIM;
1751                         break;
1752                 case 'X':
1753                         xtreme_rewind = B_TRUE;
1754                         break;
1755                 case ':':
1756                         (void) fprintf(stderr, gettext("missing argument for "
1757                             "'%c' option\n"), optopt);
1758                         usage(B_FALSE);
1759                         break;
1760                 case '?':
1761                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1762                             optopt);
1763                         usage(B_FALSE);
1764                 }
1765         }
1766
1767         argc -= optind;
1768         argv += optind;
1769
1770         if (cachefile && nsearch != 0) {
1771                 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
1772                 usage(B_FALSE);
1773         }
1774
1775         if ((dryrun || xtreme_rewind) && !do_rewind) {
1776                 (void) fprintf(stderr,
1777                     gettext("-n or -X only meaningful with -F\n"));
1778                 usage(B_FALSE);
1779         }
1780         if (dryrun)
1781                 rewind_policy = ZPOOL_TRY_REWIND;
1782         else if (do_rewind)
1783                 rewind_policy = ZPOOL_DO_REWIND;
1784         if (xtreme_rewind)
1785                 rewind_policy |= ZPOOL_EXTREME_REWIND;
1786
1787         /* In the future, we can capture further policy and include it here */
1788         if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
1789             nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, txg) != 0 ||
1790             nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
1791                 goto error;
1792
1793         /* check argument count */
1794         if (do_all) {
1795                 if (argc != 0) {
1796                         (void) fprintf(stderr, gettext("too many arguments\n"));
1797                         usage(B_FALSE);
1798                 }
1799         } else {
1800                 if (argc > 2) {
1801                         (void) fprintf(stderr, gettext("too many arguments\n"));
1802                         usage(B_FALSE);
1803                 }
1804
1805                 /*
1806                  * Check for the SYS_CONFIG privilege.  We do this explicitly
1807                  * here because otherwise any attempt to discover pools will
1808                  * silently fail.
1809                  */
1810                 if (argc == 0 && !priv_ineffect(PRIV_SYS_CONFIG)) {
1811                         (void) fprintf(stderr, gettext("cannot "
1812                             "discover pools: permission denied\n"));
1813                         if (searchdirs != NULL)
1814                                 free(searchdirs);
1815
1816                         nvlist_free(policy);
1817                         return (1);
1818                 }
1819         }
1820
1821         /*
1822          * Depending on the arguments given, we do one of the following:
1823          *
1824          *      <none>  Iterate through all pools and display information about
1825          *              each one.
1826          *
1827          *      -a      Iterate through all pools and try to import each one.
1828          *
1829          *      <id>    Find the pool that corresponds to the given GUID/pool
1830          *              name and import that one.
1831          *
1832          *      -D      Above options applies only to destroyed pools.
1833          */
1834         if (argc != 0) {
1835                 char *endptr;
1836
1837                 errno = 0;
1838                 searchguid = strtoull(argv[0], &endptr, 10);
1839                 if (errno != 0 || *endptr != '\0')
1840                         searchname = argv[0];
1841                 found_config = NULL;
1842
1843                 /*
1844                  * User specified a name or guid.  Ensure it's unique.
1845                  */
1846                 idata.unique = B_TRUE;
1847         }
1848
1849
1850         idata.path = searchdirs;
1851         idata.paths = nsearch;
1852         idata.poolname = searchname;
1853         idata.guid = searchguid;
1854         idata.cachefile = cachefile;
1855
1856         pools = zpool_search_import(g_zfs, &idata);
1857
1858         if (pools != NULL && idata.exists &&
1859             (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
1860                 (void) fprintf(stderr, gettext("cannot import '%s': "
1861                     "a pool with that name already exists\n"),
1862                     argv[0]);
1863                 (void) fprintf(stderr, gettext("use the form '%s "
1864                     "<pool | id> <newpool>' to give it a new name\n"),
1865                     "zpool import");
1866                 err = 1;
1867         } else if (pools == NULL && idata.exists) {
1868                 (void) fprintf(stderr, gettext("cannot import '%s': "
1869                     "a pool with that name is already created/imported,\n"),
1870                     argv[0]);
1871                 (void) fprintf(stderr, gettext("and no additional pools "
1872                     "with that name were found\n"));
1873                 err = 1;
1874         } else if (pools == NULL) {
1875                 if (argc != 0) {
1876                         (void) fprintf(stderr, gettext("cannot import '%s': "
1877                             "no such pool available\n"), argv[0]);
1878                 }
1879                 err = 1;
1880         }
1881
1882         if (err == 1) {
1883                 if (searchdirs != NULL)
1884                         free(searchdirs);
1885                 nvlist_free(policy);
1886                 return (1);
1887         }
1888
1889         /*
1890          * At this point we have a list of import candidate configs. Even if
1891          * we were searching by pool name or guid, we still need to
1892          * post-process the list to deal with pool state and possible
1893          * duplicate names.
1894          */
1895         err = 0;
1896         elem = NULL;
1897         first = B_TRUE;
1898         while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
1899
1900                 verify(nvpair_value_nvlist(elem, &config) == 0);
1901
1902                 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
1903                     &pool_state) == 0);
1904                 if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
1905                         continue;
1906                 if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
1907                         continue;
1908
1909                 verify(nvlist_add_nvlist(config, ZPOOL_REWIND_POLICY,
1910                     policy) == 0);
1911
1912                 if (argc == 0) {
1913                         if (first)
1914                                 first = B_FALSE;
1915                         else if (!do_all)
1916                                 (void) printf("\n");
1917
1918                         if (do_all) {
1919                                 err |= do_import(config, NULL, mntopts,
1920                                     props, flags);
1921                         } else {
1922                                 show_import(config);
1923                         }
1924                 } else if (searchname != NULL) {
1925                         char *name;
1926
1927                         /*
1928                          * We are searching for a pool based on name.
1929                          */
1930                         verify(nvlist_lookup_string(config,
1931                             ZPOOL_CONFIG_POOL_NAME, &name) == 0);
1932
1933                         if (strcmp(name, searchname) == 0) {
1934                                 if (found_config != NULL) {
1935                                         (void) fprintf(stderr, gettext(
1936                                             "cannot import '%s': more than "
1937                                             "one matching pool\n"), searchname);
1938                                         (void) fprintf(stderr, gettext(
1939                                             "import by numeric ID instead\n"));
1940                                         err = B_TRUE;
1941                                 }
1942                                 found_config = config;
1943                         }
1944                 } else {
1945                         uint64_t guid;
1946
1947                         /*
1948                          * Search for a pool by guid.
1949                          */
1950                         verify(nvlist_lookup_uint64(config,
1951                             ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
1952
1953                         if (guid == searchguid)
1954                                 found_config = config;
1955                 }
1956         }
1957
1958         /*
1959          * If we were searching for a specific pool, verify that we found a
1960          * pool, and then do the import.
1961          */
1962         if (argc != 0 && err == 0) {
1963                 if (found_config == NULL) {
1964                         (void) fprintf(stderr, gettext("cannot import '%s': "
1965                             "no such pool available\n"), argv[0]);
1966                         err = B_TRUE;
1967                 } else {
1968                         err |= do_import(found_config, argc == 1 ? NULL :
1969                             argv[1], mntopts, props, flags);
1970                 }
1971         }
1972
1973         /*
1974          * If we were just looking for pools, report an error if none were
1975          * found.
1976          */
1977         if (argc == 0 && first)
1978                 (void) fprintf(stderr,
1979                     gettext("no pools available to import\n"));
1980
1981 error:
1982         nvlist_free(props);
1983         nvlist_free(pools);
1984         nvlist_free(policy);
1985         if (searchdirs != NULL)
1986                 free(searchdirs);
1987
1988         return (err ? 1 : 0);
1989 }
1990
1991 typedef struct iostat_cbdata {
1992         zpool_list_t *cb_list;
1993         int cb_verbose;
1994         int cb_iteration;
1995         int cb_namewidth;
1996 } iostat_cbdata_t;
1997
1998 static void
1999 print_iostat_separator(iostat_cbdata_t *cb)
2000 {
2001         int i = 0;
2002
2003         for (i = 0; i < cb->cb_namewidth; i++)
2004                 (void) printf("-");
2005         (void) printf("  -----  -----  -----  -----  -----  -----\n");
2006 }
2007
2008 static void
2009 print_iostat_header(iostat_cbdata_t *cb)
2010 {
2011         (void) printf("%*s     capacity     operations    bandwidth\n",
2012             cb->cb_namewidth, "");
2013         (void) printf("%-*s  alloc   free   read  write   read  write\n",
2014             cb->cb_namewidth, "pool");
2015         print_iostat_separator(cb);
2016 }
2017
2018 /*
2019  * Display a single statistic.
2020  */
2021 static void
2022 print_one_stat(uint64_t value)
2023 {
2024         char buf[64];
2025
2026         zfs_nicenum(value, buf, sizeof (buf));
2027         (void) printf("  %5s", buf);
2028 }
2029
2030 /*
2031  * Print out all the statistics for the given vdev.  This can either be the
2032  * toplevel configuration, or called recursively.  If 'name' is NULL, then this
2033  * is a verbose output, and we don't want to display the toplevel pool stats.
2034  */
2035 void
2036 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
2037     nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
2038 {
2039         nvlist_t **oldchild, **newchild;
2040         uint_t c, children;
2041         vdev_stat_t *oldvs, *newvs;
2042         vdev_stat_t zerovs = { 0 };
2043         uint64_t tdelta;
2044         double scale;
2045         char *vname;
2046
2047         if (oldnv != NULL) {
2048                 verify(nvlist_lookup_uint64_array(oldnv,
2049                     ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
2050         } else {
2051                 oldvs = &zerovs;
2052         }
2053
2054         verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
2055             (uint64_t **)&newvs, &c) == 0);
2056
2057         if (strlen(name) + depth > cb->cb_namewidth)
2058                 (void) printf("%*s%s", depth, "", name);
2059         else
2060                 (void) printf("%*s%s%*s", depth, "", name,
2061                     (int)(cb->cb_namewidth - strlen(name) - depth), "");
2062
2063         tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
2064
2065         if (tdelta == 0)
2066                 scale = 1.0;
2067         else
2068                 scale = (double)NANOSEC / tdelta;
2069
2070         /* only toplevel vdevs have capacity stats */
2071         if (newvs->vs_space == 0) {
2072                 (void) printf("      -      -");
2073         } else {
2074                 print_one_stat(newvs->vs_alloc);
2075                 print_one_stat(newvs->vs_space - newvs->vs_alloc);
2076         }
2077
2078         print_one_stat((uint64_t)(scale * (newvs->vs_ops[ZIO_TYPE_READ] -
2079             oldvs->vs_ops[ZIO_TYPE_READ])));
2080
2081         print_one_stat((uint64_t)(scale * (newvs->vs_ops[ZIO_TYPE_WRITE] -
2082             oldvs->vs_ops[ZIO_TYPE_WRITE])));
2083
2084         print_one_stat((uint64_t)(scale * (newvs->vs_bytes[ZIO_TYPE_READ] -
2085             oldvs->vs_bytes[ZIO_TYPE_READ])));
2086
2087         print_one_stat((uint64_t)(scale * (newvs->vs_bytes[ZIO_TYPE_WRITE] -
2088             oldvs->vs_bytes[ZIO_TYPE_WRITE])));
2089
2090         (void) printf("\n");
2091
2092         if (!cb->cb_verbose)
2093                 return;
2094
2095         if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
2096             &newchild, &children) != 0)
2097                 return;
2098
2099         if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
2100             &oldchild, &c) != 0)
2101                 return;
2102
2103         for (c = 0; c < children; c++) {
2104                 uint64_t ishole = B_FALSE, islog = B_FALSE;
2105
2106                 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
2107                     &ishole);
2108
2109                 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
2110                     &islog);
2111
2112                 if (ishole || islog)
2113                         continue;
2114
2115                 vname = zpool_vdev_name(g_zfs, zhp, newchild[c], B_FALSE);
2116                 print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
2117                     newchild[c], cb, depth + 2);
2118                 free(vname);
2119         }
2120
2121         /*
2122          * Log device section
2123          */
2124
2125         if (num_logs(newnv) > 0) {
2126                 (void) printf("%-*s      -      -      -      -      -      "
2127                     "-\n", cb->cb_namewidth, "logs");
2128
2129                 for (c = 0; c < children; c++) {
2130                         uint64_t islog = B_FALSE;
2131                         (void) nvlist_lookup_uint64(newchild[c],
2132                             ZPOOL_CONFIG_IS_LOG, &islog);
2133
2134                         if (islog) {
2135                                 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
2136                                     B_FALSE);
2137                                 print_vdev_stats(zhp, vname, oldnv ?
2138                                     oldchild[c] : NULL, newchild[c],
2139                                     cb, depth + 2);
2140                                 free(vname);
2141                         }
2142                 }
2143
2144         }
2145
2146         /*
2147          * Include level 2 ARC devices in iostat output
2148          */
2149         if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
2150             &newchild, &children) != 0)
2151                 return;
2152
2153         if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
2154             &oldchild, &c) != 0)
2155                 return;
2156
2157         if (children > 0) {
2158                 (void) printf("%-*s      -      -      -      -      -      "
2159                     "-\n", cb->cb_namewidth, "cache");
2160                 for (c = 0; c < children; c++) {
2161                         vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
2162                             B_FALSE);
2163                         print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
2164                             newchild[c], cb, depth + 2);
2165                         free(vname);
2166                 }
2167         }
2168 }
2169
2170 static int
2171 refresh_iostat(zpool_handle_t *zhp, void *data)
2172 {
2173         iostat_cbdata_t *cb = data;
2174         boolean_t missing;
2175
2176         /*
2177          * If the pool has disappeared, remove it from the list and continue.
2178          */
2179         if (zpool_refresh_stats(zhp, &missing) != 0)
2180                 return (-1);
2181
2182         if (missing)
2183                 pool_list_remove(cb->cb_list, zhp);
2184
2185         return (0);
2186 }
2187
2188 /*
2189  * Callback to print out the iostats for the given pool.
2190  */
2191 int
2192 print_iostat(zpool_handle_t *zhp, void *data)
2193 {
2194         iostat_cbdata_t *cb = data;
2195         nvlist_t *oldconfig, *newconfig;
2196         nvlist_t *oldnvroot, *newnvroot;
2197
2198         newconfig = zpool_get_config(zhp, &oldconfig);
2199
2200         if (cb->cb_iteration == 1)
2201                 oldconfig = NULL;
2202
2203         verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
2204             &newnvroot) == 0);
2205
2206         if (oldconfig == NULL)
2207                 oldnvroot = NULL;
2208         else
2209                 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
2210                     &oldnvroot) == 0);
2211
2212         /*
2213          * Print out the statistics for the pool.
2214          */
2215         print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot, cb, 0);
2216
2217         if (cb->cb_verbose)
2218                 print_iostat_separator(cb);
2219
2220         return (0);
2221 }
2222
2223 static int
2224 get_columns(void)
2225 {
2226         struct winsize ws;
2227         int columns = 80;
2228         int error;
2229
2230         if (isatty(STDOUT_FILENO)) {
2231                 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
2232                 if (error == 0)
2233                         columns = ws.ws_col;
2234         } else {
2235                 columns = 999;
2236         }
2237
2238         return columns;
2239 }
2240
2241 int
2242 get_namewidth(zpool_handle_t *zhp, void *data)
2243 {
2244         iostat_cbdata_t *cb = data;
2245         nvlist_t *config, *nvroot;
2246         int columns;
2247
2248         if ((config = zpool_get_config(zhp, NULL)) != NULL) {
2249                 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2250                     &nvroot) == 0);
2251                 if (!cb->cb_verbose)
2252                         cb->cb_namewidth = strlen(zpool_get_name(zhp));
2253                 else
2254                         cb->cb_namewidth = max_width(zhp, nvroot, 0,
2255                             cb->cb_namewidth);
2256         }
2257
2258         /*
2259          * The width must be at least 10, but may be as large as the
2260          * column width - 42 so that we can still fit in one line.
2261          */
2262         columns = get_columns();
2263
2264         if (cb->cb_namewidth < 10)
2265                 cb->cb_namewidth = 10;
2266         if (cb->cb_namewidth > columns - 42)
2267                 cb->cb_namewidth = columns - 42;
2268
2269         return (0);
2270 }
2271
2272 /*
2273  * Parse the input string, get the 'interval' and 'count' value if there is one.
2274  */
2275 static void
2276 get_interval_count(int *argcp, char **argv, unsigned long *iv,
2277     unsigned long *cnt)
2278 {
2279         unsigned long interval = 0, count = 0;
2280         int argc = *argcp;
2281
2282         /*
2283          * Determine if the last argument is an integer or a pool name
2284          */
2285         if (argc > 0 && isdigit(argv[argc - 1][0])) {
2286                 char *end;
2287
2288                 errno = 0;
2289                 interval = strtoul(argv[argc - 1], &end, 10);
2290
2291                 if (*end == '\0' && errno == 0) {
2292                         if (interval == 0) {
2293                                 (void) fprintf(stderr, gettext("interval "
2294                                     "cannot be zero\n"));
2295                                 usage(B_FALSE);
2296                         }
2297                         /*
2298                          * Ignore the last parameter
2299                          */
2300                         argc--;
2301                 } else {
2302                         /*
2303                          * If this is not a valid number, just plow on.  The
2304                          * user will get a more informative error message later
2305                          * on.
2306                          */
2307                         interval = 0;
2308                 }
2309         }
2310
2311         /*
2312          * If the last argument is also an integer, then we have both a count
2313          * and an interval.
2314          */
2315         if (argc > 0 && isdigit(argv[argc - 1][0])) {
2316                 char *end;
2317
2318                 errno = 0;
2319                 count = interval;
2320                 interval = strtoul(argv[argc - 1], &end, 10);
2321
2322                 if (*end == '\0' && errno == 0) {
2323                         if (interval == 0) {
2324                                 (void) fprintf(stderr, gettext("interval "
2325                                     "cannot be zero\n"));
2326                                 usage(B_FALSE);
2327                         }
2328
2329                         /*
2330                          * Ignore the last parameter
2331                          */
2332                         argc--;
2333                 } else {
2334                         interval = 0;
2335                 }
2336         }
2337
2338         *iv = interval;
2339         *cnt = count;
2340         *argcp = argc;
2341 }
2342
2343 static void
2344 get_timestamp_arg(char c)
2345 {
2346         if (c == 'u')
2347                 timestamp_fmt = UDATE;
2348         else if (c == 'd')
2349                 timestamp_fmt = DDATE;
2350         else
2351                 usage(B_FALSE);
2352 }
2353
2354 /*
2355  * zpool iostat [-v] [-T d|u] [pool] ... [interval [count]]
2356  *
2357  *      -v      Display statistics for individual vdevs
2358  *      -T      Display a timestamp in date(1) or Unix format
2359  *
2360  * This command can be tricky because we want to be able to deal with pool
2361  * creation/destruction as well as vdev configuration changes.  The bulk of this
2362  * processing is handled by the pool_list_* routines in zpool_iter.c.  We rely
2363  * on pool_list_update() to detect the addition of new pools.  Configuration
2364  * changes are all handled within libzfs.
2365  */
2366 int
2367 zpool_do_iostat(int argc, char **argv)
2368 {
2369         int c;
2370         int ret;
2371         int npools;
2372         unsigned long interval = 0, count = 0;
2373         zpool_list_t *list;
2374         boolean_t verbose = B_FALSE;
2375         iostat_cbdata_t cb;
2376
2377         /* check options */
2378         while ((c = getopt(argc, argv, "T:v")) != -1) {
2379                 switch (c) {
2380                 case 'T':
2381                         get_timestamp_arg(*optarg);
2382                         break;
2383                 case 'v':
2384                         verbose = B_TRUE;
2385                         break;
2386                 case '?':
2387                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2388                             optopt);
2389                         usage(B_FALSE);
2390                 }
2391         }
2392
2393         argc -= optind;
2394         argv += optind;
2395
2396         get_interval_count(&argc, argv, &interval, &count);
2397
2398         /*
2399          * Construct the list of all interesting pools.
2400          */
2401         ret = 0;
2402         if ((list = pool_list_get(argc, argv, NULL, &ret)) == NULL)
2403                 return (1);
2404
2405         if (pool_list_count(list) == 0 && argc != 0) {
2406                 pool_list_free(list);
2407                 return (1);
2408         }
2409
2410         if (pool_list_count(list) == 0 && interval == 0) {
2411                 pool_list_free(list);
2412                 (void) fprintf(stderr, gettext("no pools available\n"));
2413                 return (1);
2414         }
2415
2416         /*
2417          * Enter the main iostat loop.
2418          */
2419         cb.cb_list = list;
2420         cb.cb_verbose = verbose;
2421         cb.cb_iteration = 0;
2422         cb.cb_namewidth = 0;
2423
2424         for (;;) {
2425                 pool_list_update(list);
2426
2427                 if ((npools = pool_list_count(list)) == 0)
2428                         (void) fprintf(stderr, gettext("no pools available\n"));
2429                 else {
2430                         /*
2431                          * Refresh all statistics.  This is done as an
2432                          * explicit step before calculating the maximum name
2433                          * width, so that any * configuration changes are
2434                          * properly accounted for.
2435                          */
2436                         (void) pool_list_iter(list, B_FALSE, refresh_iostat,
2437                                 &cb);
2438
2439                         /*
2440                          * Iterate over all pools to determine the maximum width
2441                          * for the pool / device name column across all pools.
2442                          */
2443                         cb.cb_namewidth = 0;
2444                         (void) pool_list_iter(list, B_FALSE, get_namewidth,
2445                                 &cb);
2446
2447                         if (timestamp_fmt != NODATE)
2448                                 print_timestamp(timestamp_fmt);
2449
2450                         /*
2451                          * If it's the first time, or verbose mode, print the
2452                          * header.
2453                          */
2454                         if (++cb.cb_iteration == 1 || verbose)
2455                                 print_iostat_header(&cb);
2456
2457                         (void) pool_list_iter(list, B_FALSE, print_iostat, &cb);
2458
2459                         /*
2460                          * If there's more than one pool, and we're not in
2461                          * verbose mode (which prints a separator for us),
2462                          * then print a separator.
2463                          */
2464                         if (npools > 1 && !verbose)
2465                                 print_iostat_separator(&cb);
2466
2467                         if (verbose)
2468                                 (void) printf("\n");
2469                 }
2470
2471                 /*
2472                  * Flush the output so that redirection to a file isn't buffered
2473                  * indefinitely.
2474                  */
2475                 (void) fflush(stdout);
2476
2477                 if (interval == 0)
2478                         break;
2479
2480                 if (count != 0 && --count == 0)
2481                         break;
2482
2483                 (void) sleep(interval);
2484         }
2485
2486         pool_list_free(list);
2487
2488         return (ret);
2489 }
2490
2491 typedef struct list_cbdata {
2492         boolean_t       cb_scripted;
2493         boolean_t       cb_first;
2494         zprop_list_t    *cb_proplist;
2495 } list_cbdata_t;
2496
2497 /*
2498  * Given a list of columns to display, output appropriate headers for each one.
2499  */
2500 static void
2501 print_header(zprop_list_t *pl)
2502 {
2503         const char *header;
2504         boolean_t first = B_TRUE;
2505         boolean_t right_justify;
2506
2507         for (; pl != NULL; pl = pl->pl_next) {
2508                 if (pl->pl_prop == ZPROP_INVAL)
2509                         continue;
2510
2511                 if (!first)
2512                         (void) printf("  ");
2513                 else
2514                         first = B_FALSE;
2515
2516                 header = zpool_prop_column_name(pl->pl_prop);
2517                 right_justify = zpool_prop_align_right(pl->pl_prop);
2518
2519                 if (pl->pl_next == NULL && !right_justify)
2520                         (void) printf("%s", header);
2521                 else if (right_justify)
2522                         (void) printf("%*s", (int)pl->pl_width, header);
2523                 else
2524                         (void) printf("%-*s", (int)pl->pl_width, header);
2525         }
2526
2527         (void) printf("\n");
2528 }
2529
2530 /*
2531  * Given a pool and a list of properties, print out all the properties according
2532  * to the described layout.
2533  */
2534 static void
2535 print_pool(zpool_handle_t *zhp, zprop_list_t *pl, int scripted)
2536 {
2537         boolean_t first = B_TRUE;
2538         char property[ZPOOL_MAXPROPLEN];
2539         char *propstr;
2540         boolean_t right_justify;
2541         int width;
2542
2543         for (; pl != NULL; pl = pl->pl_next) {
2544                 if (!first) {
2545                         if (scripted)
2546                                 (void) printf("\t");
2547                         else
2548                                 (void) printf("  ");
2549                 } else {
2550                         first = B_FALSE;
2551                 }
2552
2553                 right_justify = B_FALSE;
2554                 if (pl->pl_prop != ZPROP_INVAL) {
2555                         if (zpool_get_prop(zhp, pl->pl_prop, property,
2556                             sizeof (property), NULL) != 0)
2557                                 propstr = "-";
2558                         else
2559                                 propstr = property;
2560
2561                         right_justify = zpool_prop_align_right(pl->pl_prop);
2562                 } else {
2563                         propstr = "-";
2564                 }
2565
2566                 width = pl->pl_width;
2567
2568                 /*
2569                  * If this is being called in scripted mode, or if this is the
2570                  * last column and it is left-justified, don't include a width
2571                  * format specifier.
2572                  */
2573                 if (scripted || (pl->pl_next == NULL && !right_justify))
2574                         (void) printf("%s", propstr);
2575                 else if (right_justify)
2576                         (void) printf("%*s", width, propstr);
2577                 else
2578                         (void) printf("%-*s", width, propstr);
2579         }
2580
2581         (void) printf("\n");
2582 }
2583
2584 /*
2585  * Generic callback function to list a pool.
2586  */
2587 int
2588 list_callback(zpool_handle_t *zhp, void *data)
2589 {
2590         list_cbdata_t *cbp = data;
2591
2592         if (cbp->cb_first) {
2593                 if (!cbp->cb_scripted)
2594                         print_header(cbp->cb_proplist);
2595                 cbp->cb_first = B_FALSE;
2596         }
2597
2598         print_pool(zhp, cbp->cb_proplist, cbp->cb_scripted);
2599
2600         return (0);
2601 }
2602
2603 /*
2604  * zpool list [-H] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
2605  *
2606  *      -H      Scripted mode.  Don't display headers, and separate properties
2607  *              by a single tab.
2608  *      -o      List of properties to display.  Defaults to
2609  *              "name,size,allocated,free,capacity,health,altroot"
2610  *      -T      Display a timestamp in date(1) or Unix format
2611  *
2612  * List all pools in the system, whether or not they're healthy.  Output space
2613  * statistics for each one, as well as health status summary.
2614  */
2615 int
2616 zpool_do_list(int argc, char **argv)
2617 {
2618         int c;
2619         int ret;
2620         list_cbdata_t cb = { 0 };
2621         static char default_props[] =
2622             "name,size,allocated,free,capacity,dedupratio,health,altroot";
2623         char *props = default_props;
2624         unsigned long interval = 0, count = 0;
2625
2626         /* check options */
2627         while ((c = getopt(argc, argv, ":Ho:T:")) != -1) {
2628                 switch (c) {
2629                 case 'H':
2630                         cb.cb_scripted = B_TRUE;
2631                         break;
2632                 case 'o':
2633                         props = optarg;
2634                         break;
2635                 case 'T':
2636                         get_timestamp_arg(*optarg);
2637                         break;
2638                 case ':':
2639                         (void) fprintf(stderr, gettext("missing argument for "
2640                             "'%c' option\n"), optopt);
2641                         usage(B_FALSE);
2642                         break;
2643                 case '?':
2644                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2645                             optopt);
2646                         usage(B_FALSE);
2647                 }
2648         }
2649
2650         argc -= optind;
2651         argv += optind;
2652
2653         get_interval_count(&argc, argv, &interval, &count);
2654
2655         if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
2656                 usage(B_FALSE);
2657
2658         cb.cb_first = B_TRUE;
2659
2660         for (;;) {
2661
2662                 if (timestamp_fmt != NODATE)
2663                         print_timestamp(timestamp_fmt);
2664
2665                 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist,
2666                     list_callback, &cb);
2667
2668                 if (argc == 0 && cb.cb_first)
2669                         (void) fprintf(stderr, gettext("no pools available\n"));
2670                 else if (argc && cb.cb_first) {
2671                         /* cannot open the given pool */
2672                         zprop_free_list(cb.cb_proplist);
2673                         return (1);
2674                 }
2675
2676                 if (interval == 0)
2677                         break;
2678
2679                 if (count != 0 && --count == 0)
2680                         break;
2681
2682                 (void) sleep(interval);
2683         }
2684
2685         zprop_free_list(cb.cb_proplist);
2686         return (ret);
2687 }
2688
2689 static int
2690 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
2691 {
2692         boolean_t force = B_FALSE;
2693         int c;
2694         nvlist_t *nvroot;
2695         char *poolname, *old_disk, *new_disk;
2696         zpool_handle_t *zhp;
2697         int ret;
2698
2699         /* check options */
2700         while ((c = getopt(argc, argv, "f")) != -1) {
2701                 switch (c) {
2702                 case 'f':
2703                         force = B_TRUE;
2704                         break;
2705                 case '?':
2706                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2707                             optopt);
2708                         usage(B_FALSE);
2709                 }
2710         }
2711
2712         argc -= optind;
2713         argv += optind;
2714
2715         /* get pool name and check number of arguments */
2716         if (argc < 1) {
2717                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
2718                 usage(B_FALSE);
2719         }
2720
2721         poolname = argv[0];
2722
2723         if (argc < 2) {
2724                 (void) fprintf(stderr,
2725                     gettext("missing <device> specification\n"));
2726                 usage(B_FALSE);
2727         }
2728
2729         old_disk = argv[1];
2730
2731         if (argc < 3) {
2732                 if (!replacing) {
2733                         (void) fprintf(stderr,
2734                             gettext("missing <new_device> specification\n"));
2735                         usage(B_FALSE);
2736                 }
2737                 new_disk = old_disk;
2738                 argc -= 1;
2739                 argv += 1;
2740         } else {
2741                 new_disk = argv[2];
2742                 argc -= 2;
2743                 argv += 2;
2744         }
2745
2746         if (argc > 1) {
2747                 (void) fprintf(stderr, gettext("too many arguments\n"));
2748                 usage(B_FALSE);
2749         }
2750
2751         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
2752                 return (1);
2753
2754         if (zpool_get_config(zhp, NULL) == NULL) {
2755                 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
2756                     poolname);
2757                 zpool_close(zhp);
2758                 return (1);
2759         }
2760
2761         nvroot = make_root_vdev(zhp, NULL, force, B_FALSE, replacing, B_FALSE,
2762             argc, argv);
2763         if (nvroot == NULL) {
2764                 zpool_close(zhp);
2765                 return (1);
2766         }
2767
2768         ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing);
2769
2770         nvlist_free(nvroot);
2771         zpool_close(zhp);
2772
2773         return (ret);
2774 }
2775
2776 /*
2777  * zpool replace [-f] <pool> <device> <new_device>
2778  *
2779  *      -f      Force attach, even if <new_device> appears to be in use.
2780  *
2781  * Replace <device> with <new_device>.
2782  */
2783 /* ARGSUSED */
2784 int
2785 zpool_do_replace(int argc, char **argv)
2786 {
2787         return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
2788 }
2789
2790 /*
2791  * zpool attach [-f] <pool> <device> <new_device>
2792  *
2793  *      -f      Force attach, even if <new_device> appears to be in use.
2794  *
2795  * Attach <new_device> to the mirror containing <device>.  If <device> is not
2796  * part of a mirror, then <device> will be transformed into a mirror of
2797  * <device> and <new_device>.  In either case, <new_device> will begin life
2798  * with a DTL of [0, now], and will immediately begin to resilver itself.
2799  */
2800 int
2801 zpool_do_attach(int argc, char **argv)
2802 {
2803         return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
2804 }
2805
2806 /*
2807  * zpool detach [-f] <pool> <device>
2808  *
2809  *      -f      Force detach of <device>, even if DTLs argue against it
2810  *              (not supported yet)
2811  *
2812  * Detach a device from a mirror.  The operation will be refused if <device>
2813  * is the last device in the mirror, or if the DTLs indicate that this device
2814  * has the only valid copy of some data.
2815  */
2816 /* ARGSUSED */
2817 int
2818 zpool_do_detach(int argc, char **argv)
2819 {
2820         int c;
2821         char *poolname, *path;
2822         zpool_handle_t *zhp;
2823         int ret;
2824
2825         /* check options */
2826         while ((c = getopt(argc, argv, "f")) != -1) {
2827                 switch (c) {
2828                 case 'f':
2829                 case '?':
2830                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2831                             optopt);
2832                         usage(B_FALSE);
2833                 }
2834         }
2835
2836         argc -= optind;
2837         argv += optind;
2838
2839         /* get pool name and check number of arguments */
2840         if (argc < 1) {
2841                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
2842                 usage(B_FALSE);
2843         }
2844
2845         if (argc < 2) {
2846                 (void) fprintf(stderr,
2847                     gettext("missing <device> specification\n"));
2848                 usage(B_FALSE);
2849         }
2850
2851         poolname = argv[0];
2852         path = argv[1];
2853
2854         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
2855                 return (1);
2856
2857         ret = zpool_vdev_detach(zhp, path);
2858
2859         zpool_close(zhp);
2860
2861         return (ret);
2862 }
2863
2864 /*
2865  * zpool split [-n] [-o prop=val] ...
2866  *              [-o mntopt] ...
2867  *              [-R altroot] <pool> <newpool> [<device> ...]
2868  *
2869  *      -n      Do not split the pool, but display the resulting layout if
2870  *              it were to be split.
2871  *      -o      Set property=value, or set mount options.
2872  *      -R      Mount the split-off pool under an alternate root.
2873  *
2874  * Splits the named pool and gives it the new pool name.  Devices to be split
2875  * off may be listed, provided that no more than one device is specified
2876  * per top-level vdev mirror.  The newly split pool is left in an exported
2877  * state unless -R is specified.
2878  *
2879  * Restrictions: the top-level of the pool pool must only be made up of
2880  * mirrors; all devices in the pool must be healthy; no device may be
2881  * undergoing a resilvering operation.
2882  */
2883 int
2884 zpool_do_split(int argc, char **argv)
2885 {
2886         char *srcpool, *newpool, *propval;
2887         char *mntopts = NULL;
2888         splitflags_t flags;
2889         int c, ret = 0;
2890         zpool_handle_t *zhp;
2891         nvlist_t *config, *props = NULL;
2892
2893         flags.dryrun = B_FALSE;
2894         flags.import = B_FALSE;
2895
2896         /* check options */
2897         while ((c = getopt(argc, argv, ":R:no:")) != -1) {
2898                 switch (c) {
2899                 case 'R':
2900                         flags.import = B_TRUE;
2901                         if (add_prop_list(
2902                             zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
2903                             &props, B_TRUE) != 0) {
2904                                 if (props)
2905                                         nvlist_free(props);
2906                                 usage(B_FALSE);
2907                         }
2908                         break;
2909                 case 'n':
2910                         flags.dryrun = B_TRUE;
2911                         break;
2912                 case 'o':
2913                         if ((propval = strchr(optarg, '=')) != NULL) {
2914                                 *propval = '\0';
2915                                 propval++;
2916                                 if (add_prop_list(optarg, propval,
2917                                     &props, B_TRUE) != 0) {
2918                                         if (props)
2919                                                 nvlist_free(props);
2920                                         usage(B_FALSE);
2921                                 }
2922                         } else {
2923                                 mntopts = optarg;
2924                         }
2925                         break;
2926                 case ':':
2927                         (void) fprintf(stderr, gettext("missing argument for "
2928                             "'%c' option\n"), optopt);
2929                         usage(B_FALSE);
2930                         break;
2931                 case '?':
2932                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2933                             optopt);
2934                         usage(B_FALSE);
2935                         break;
2936                 }
2937         }
2938
2939         if (!flags.import && mntopts != NULL) {
2940                 (void) fprintf(stderr, gettext("setting mntopts is only "
2941                     "valid when importing the pool\n"));
2942                 usage(B_FALSE);
2943         }
2944
2945         argc -= optind;
2946         argv += optind;
2947
2948         if (argc < 1) {
2949                 (void) fprintf(stderr, gettext("Missing pool name\n"));
2950                 usage(B_FALSE);
2951         }
2952         if (argc < 2) {
2953                 (void) fprintf(stderr, gettext("Missing new pool name\n"));
2954                 usage(B_FALSE);
2955         }
2956
2957         srcpool = argv[0];
2958         newpool = argv[1];
2959
2960         argc -= 2;
2961         argv += 2;
2962
2963         if ((zhp = zpool_open(g_zfs, srcpool)) == NULL)
2964                 return (1);
2965
2966         config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
2967         if (config == NULL) {
2968                 ret = 1;
2969         } else {
2970                 if (flags.dryrun) {
2971                         (void) printf(gettext("would create '%s' with the "
2972                             "following layout:\n\n"), newpool);
2973                         print_vdev_tree(NULL, newpool, config, 0, B_FALSE);
2974                 }
2975                 nvlist_free(config);
2976         }
2977
2978         zpool_close(zhp);
2979
2980         if (ret != 0 || flags.dryrun || !flags.import)
2981                 return (ret);
2982
2983         /*
2984          * The split was successful. Now we need to open the new
2985          * pool and import it.
2986          */
2987         if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL)
2988                 return (1);
2989         if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
2990             zpool_enable_datasets(zhp, mntopts, 0) != 0) {
2991                 ret = 1;
2992                 (void) fprintf(stderr, gettext("Split was successful, but "
2993                     "the datasets could not all be mounted\n"));
2994                 (void) fprintf(stderr, gettext("Try doing '%s' with a "
2995                     "different altroot\n"), "zpool import");
2996         }
2997         zpool_close(zhp);
2998
2999         return (ret);
3000 }
3001
3002
3003
3004 /*
3005  * zpool online <pool> <device> ...
3006  */
3007 int
3008 zpool_do_online(int argc, char **argv)
3009 {
3010         int c, i;
3011         char *poolname;
3012         zpool_handle_t *zhp;
3013         int ret = 0;
3014         vdev_state_t newstate;
3015         int flags = 0;
3016
3017         /* check options */
3018         while ((c = getopt(argc, argv, "et")) != -1) {
3019                 switch (c) {
3020                 case 'e':
3021                         flags |= ZFS_ONLINE_EXPAND;
3022                         break;
3023                 case 't':
3024                 case '?':
3025                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3026                             optopt);
3027                         usage(B_FALSE);
3028                 }
3029         }
3030
3031         argc -= optind;
3032         argv += optind;
3033
3034         /* get pool name and check number of arguments */
3035         if (argc < 1) {
3036                 (void) fprintf(stderr, gettext("missing pool name\n"));
3037                 usage(B_FALSE);
3038         }
3039         if (argc < 2) {
3040                 (void) fprintf(stderr, gettext("missing device name\n"));
3041                 usage(B_FALSE);
3042         }
3043
3044         poolname = argv[0];
3045
3046         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
3047                 return (1);
3048
3049         for (i = 1; i < argc; i++) {
3050                 if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
3051                         if (newstate != VDEV_STATE_HEALTHY) {
3052                                 (void) printf(gettext("warning: device '%s' "
3053                                     "onlined, but remains in faulted state\n"),
3054                                     argv[i]);
3055                                 if (newstate == VDEV_STATE_FAULTED)
3056                                         (void) printf(gettext("use 'zpool "
3057                                             "clear' to restore a faulted "
3058                                             "device\n"));
3059                                 else
3060                                         (void) printf(gettext("use 'zpool "
3061                                             "replace' to replace devices "
3062                                             "that are no longer present\n"));
3063                         }
3064                 } else {
3065                         ret = 1;
3066                 }
3067         }
3068
3069         zpool_close(zhp);
3070
3071         return (ret);
3072 }
3073
3074 /*
3075  * zpool offline [-ft] <pool> <device> ...
3076  *
3077  *      -f      Force the device into the offline state, even if doing
3078  *              so would appear to compromise pool availability.
3079  *              (not supported yet)
3080  *
3081  *      -t      Only take the device off-line temporarily.  The offline
3082  *              state will not be persistent across reboots.
3083  */
3084 /* ARGSUSED */
3085 int
3086 zpool_do_offline(int argc, char **argv)
3087 {
3088         int c, i;
3089         char *poolname;
3090         zpool_handle_t *zhp;
3091         int ret = 0;
3092         boolean_t istmp = B_FALSE;
3093
3094         /* check options */
3095         while ((c = getopt(argc, argv, "ft")) != -1) {
3096                 switch (c) {
3097                 case 't':
3098                         istmp = B_TRUE;
3099                         break;
3100                 case 'f':
3101                 case '?':
3102                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3103                             optopt);
3104                         usage(B_FALSE);
3105                 }
3106         }
3107
3108         argc -= optind;
3109         argv += optind;
3110
3111         /* get pool name and check number of arguments */
3112         if (argc < 1) {
3113                 (void) fprintf(stderr, gettext("missing pool name\n"));
3114                 usage(B_FALSE);
3115         }
3116         if (argc < 2) {
3117                 (void) fprintf(stderr, gettext("missing device name\n"));
3118                 usage(B_FALSE);
3119         }
3120
3121         poolname = argv[0];
3122
3123         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
3124                 return (1);
3125
3126         for (i = 1; i < argc; i++) {
3127                 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
3128                         ret = 1;
3129         }
3130
3131         zpool_close(zhp);
3132
3133         return (ret);
3134 }
3135
3136 /*
3137  * zpool clear <pool> [device]
3138  *
3139  * Clear all errors associated with a pool or a particular device.
3140  */
3141 int
3142 zpool_do_clear(int argc, char **argv)
3143 {
3144         int c;
3145         int ret = 0;
3146         boolean_t dryrun = B_FALSE;
3147         boolean_t do_rewind = B_FALSE;
3148         boolean_t xtreme_rewind = B_FALSE;
3149         uint32_t rewind_policy = ZPOOL_NO_REWIND;
3150         nvlist_t *policy = NULL;
3151         zpool_handle_t *zhp;
3152         char *pool, *device;
3153
3154         /* check options */
3155         while ((c = getopt(argc, argv, "FnX")) != -1) {
3156                 switch (c) {
3157                 case 'F':
3158                         do_rewind = B_TRUE;
3159                         break;
3160                 case 'n':
3161                         dryrun = B_TRUE;
3162                         break;
3163                 case 'X':
3164                         xtreme_rewind = B_TRUE;
3165                         break;
3166                 case '?':
3167                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3168                             optopt);
3169                         usage(B_FALSE);
3170                 }
3171         }
3172
3173         argc -= optind;
3174         argv += optind;
3175
3176         if (argc < 1) {
3177                 (void) fprintf(stderr, gettext("missing pool name\n"));
3178                 usage(B_FALSE);
3179         }
3180
3181         if (argc > 2) {
3182                 (void) fprintf(stderr, gettext("too many arguments\n"));
3183                 usage(B_FALSE);
3184         }
3185
3186         if ((dryrun || xtreme_rewind) && !do_rewind) {
3187                 (void) fprintf(stderr,
3188                     gettext("-n or -X only meaningful with -F\n"));
3189                 usage(B_FALSE);
3190         }
3191         if (dryrun)
3192                 rewind_policy = ZPOOL_TRY_REWIND;
3193         else if (do_rewind)
3194                 rewind_policy = ZPOOL_DO_REWIND;
3195         if (xtreme_rewind)
3196                 rewind_policy |= ZPOOL_EXTREME_REWIND;
3197
3198         /* In future, further rewind policy choices can be passed along here */
3199         if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
3200             nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
3201                 return (1);
3202
3203         pool = argv[0];
3204         device = argc == 2 ? argv[1] : NULL;
3205
3206         if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
3207                 nvlist_free(policy);
3208                 return (1);
3209         }
3210
3211         if (zpool_clear(zhp, device, policy) != 0)
3212                 ret = 1;
3213
3214         zpool_close(zhp);
3215
3216         nvlist_free(policy);
3217
3218         return (ret);
3219 }
3220
3221 /*
3222  * zpool reguid <pool>
3223  */
3224 int
3225 zpool_do_reguid(int argc, char **argv)
3226 {
3227         int c;
3228         char *poolname;
3229         zpool_handle_t *zhp;
3230         int ret = 0;
3231
3232         /* check options */
3233         while ((c = getopt(argc, argv, "")) != -1) {
3234                 switch (c) {
3235                 case '?':
3236                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3237                             optopt);
3238                         usage(B_FALSE);
3239                 }
3240         }
3241
3242         argc -= optind;
3243         argv += optind;
3244
3245         /* get pool name and check number of arguments */
3246         if (argc < 1) {
3247                 (void) fprintf(stderr, gettext("missing pool name\n"));
3248                 usage(B_FALSE);
3249         }
3250
3251         if (argc > 1) {
3252                 (void) fprintf(stderr, gettext("too many arguments\n"));
3253                 usage(B_FALSE);
3254         }
3255
3256         poolname = argv[0];
3257         if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
3258                 return (1);
3259
3260         ret = zpool_reguid(zhp);
3261
3262         zpool_close(zhp);
3263         return (ret);
3264 }
3265
3266
3267 typedef struct scrub_cbdata {
3268         int     cb_type;
3269         int     cb_argc;
3270         char    **cb_argv;
3271 } scrub_cbdata_t;
3272
3273 int
3274 scrub_callback(zpool_handle_t *zhp, void *data)
3275 {
3276         scrub_cbdata_t *cb = data;
3277         int err;
3278
3279         /*
3280          * Ignore faulted pools.
3281          */
3282         if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
3283                 (void) fprintf(stderr, gettext("cannot scrub '%s': pool is "
3284                     "currently unavailable\n"), zpool_get_name(zhp));
3285                 return (1);
3286         }
3287
3288         err = zpool_scan(zhp, cb->cb_type);
3289
3290         return (err != 0);
3291 }
3292
3293 /*
3294  * zpool scrub [-s] <pool> ...
3295  *
3296  *      -s      Stop.  Stops any in-progress scrub.
3297  */
3298 int
3299 zpool_do_scrub(int argc, char **argv)
3300 {
3301         int c;
3302         scrub_cbdata_t cb;
3303
3304         cb.cb_type = POOL_SCAN_SCRUB;
3305
3306         /* check options */
3307         while ((c = getopt(argc, argv, "s")) != -1) {
3308                 switch (c) {
3309                 case 's':
3310                         cb.cb_type = POOL_SCAN_NONE;
3311                         break;
3312                 case '?':
3313                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3314                             optopt);
3315                         usage(B_FALSE);
3316                 }
3317         }
3318
3319         cb.cb_argc = argc;
3320         cb.cb_argv = argv;
3321         argc -= optind;
3322         argv += optind;
3323
3324         if (argc < 1) {
3325                 (void) fprintf(stderr, gettext("missing pool name argument\n"));
3326                 usage(B_FALSE);
3327         }
3328
3329         return (for_each_pool(argc, argv, B_TRUE, NULL, scrub_callback, &cb));
3330 }
3331
3332 typedef struct status_cbdata {
3333         int             cb_count;
3334         boolean_t       cb_allpools;
3335         boolean_t       cb_verbose;
3336         boolean_t       cb_explain;
3337         boolean_t       cb_first;
3338         boolean_t       cb_dedup_stats;
3339 } status_cbdata_t;
3340
3341 /*
3342  * Print out detailed scrub status.
3343  */
3344 void
3345 print_scan_status(pool_scan_stat_t *ps)
3346 {
3347         time_t start, end;
3348         uint64_t elapsed, mins_left, hours_left;
3349         uint64_t pass_exam, examined, total;
3350         uint_t rate;
3351         double fraction_done;
3352         char processed_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
3353
3354         (void) printf(gettext(" scan: "));
3355
3356         /* If there's never been a scan, there's not much to say. */
3357         if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
3358             ps->pss_func >= POOL_SCAN_FUNCS) {
3359                 (void) printf(gettext("none requested\n"));
3360                 return;
3361         }
3362
3363         start = ps->pss_start_time;
3364         end = ps->pss_end_time;
3365         zfs_nicenum(ps->pss_processed, processed_buf, sizeof (processed_buf));
3366
3367         assert(ps->pss_func == POOL_SCAN_SCRUB ||
3368             ps->pss_func == POOL_SCAN_RESILVER);
3369         /*
3370          * Scan is finished or canceled.
3371          */
3372         if (ps->pss_state == DSS_FINISHED) {
3373                 uint64_t minutes_taken = (end - start) / 60;
3374                 char *fmt = NULL;
3375
3376                 if (ps->pss_func == POOL_SCAN_SCRUB) {
3377                         fmt = gettext("scrub repaired %s in %lluh%um with "
3378                             "%llu errors on %s");
3379                 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
3380                         fmt = gettext("resilvered %s in %lluh%um with "
3381                             "%llu errors on %s");
3382                 }
3383                 /* LINTED */
3384                 (void) printf(fmt, processed_buf,
3385                     (u_longlong_t)(minutes_taken / 60),
3386                     (uint_t)(minutes_taken % 60),
3387                     (u_longlong_t)ps->pss_errors,
3388                     ctime((time_t *)&end));
3389                 return;
3390         } else if (ps->pss_state == DSS_CANCELED) {
3391                 if (ps->pss_func == POOL_SCAN_SCRUB) {
3392                         (void) printf(gettext("scrub canceled on %s"),
3393                             ctime(&end));
3394                 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
3395                         (void) printf(gettext("resilver canceled on %s"),
3396                             ctime(&end));
3397                 }
3398                 return;
3399         }
3400
3401         assert(ps->pss_state == DSS_SCANNING);
3402
3403         /*
3404          * Scan is in progress.
3405          */
3406         if (ps->pss_func == POOL_SCAN_SCRUB) {
3407                 (void) printf(gettext("scrub in progress since %s"),
3408                     ctime(&start));
3409         } else if (ps->pss_func == POOL_SCAN_RESILVER) {
3410                 (void) printf(gettext("resilver in progress since %s"),
3411                     ctime(&start));
3412         }
3413
3414         examined = ps->pss_examined ? ps->pss_examined : 1;
3415         total = ps->pss_to_examine;
3416         fraction_done = (double)examined / total;
3417
3418         /* elapsed time for this pass */
3419         elapsed = time(NULL) - ps->pss_pass_start;
3420         elapsed = elapsed ? elapsed : 1;
3421         pass_exam = ps->pss_pass_exam ? ps->pss_pass_exam : 1;
3422         rate = pass_exam / elapsed;
3423         rate = rate ? rate : 1;
3424         mins_left = ((total - examined) / rate) / 60;
3425         hours_left = mins_left / 60;
3426
3427         zfs_nicenum(examined, examined_buf, sizeof (examined_buf));
3428         zfs_nicenum(total, total_buf, sizeof (total_buf));
3429         zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
3430
3431         /*
3432          * do not print estimated time if hours_left is more than 30 days
3433          */
3434         (void) printf(gettext("    %s scanned out of %s at %s/s"),
3435             examined_buf, total_buf, rate_buf);
3436         if (hours_left < (30 * 24)) {
3437                 (void) printf(gettext(", %lluh%um to go\n"),
3438                     (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
3439         } else {
3440                 (void) printf(gettext(
3441                     ", (scan is slow, no estimated time)\n"));
3442         }
3443
3444         if (ps->pss_func == POOL_SCAN_RESILVER) {
3445                 (void) printf(gettext("    %s resilvered, %.2f%% done\n"),
3446                     processed_buf, 100 * fraction_done);
3447         } else if (ps->pss_func == POOL_SCAN_SCRUB) {
3448                 (void) printf(gettext("    %s repaired, %.2f%% done\n"),
3449                     processed_buf, 100 * fraction_done);
3450         }
3451 }
3452
3453 static void
3454 print_error_log(zpool_handle_t *zhp)
3455 {
3456         nvlist_t *nverrlist = NULL;
3457         nvpair_t *elem;
3458         char *pathname;
3459         size_t len = MAXPATHLEN * 2;
3460
3461         if (zpool_get_errlog(zhp, &nverrlist) != 0) {
3462                 (void) printf("errors: List of errors unavailable "
3463                     "(insufficient privileges)\n");
3464                 return;
3465         }
3466
3467         (void) printf("errors: Permanent errors have been "
3468             "detected in the following files:\n\n");
3469
3470         pathname = safe_malloc(len);
3471         elem = NULL;
3472         while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
3473                 nvlist_t *nv;
3474                 uint64_t dsobj, obj;
3475
3476                 verify(nvpair_value_nvlist(elem, &nv) == 0);
3477                 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
3478                     &dsobj) == 0);
3479                 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
3480                     &obj) == 0);
3481                 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
3482                 (void) printf("%7s %s\n", "", pathname);
3483         }
3484         free(pathname);
3485         nvlist_free(nverrlist);
3486 }
3487
3488 static void
3489 print_spares(zpool_handle_t *zhp, nvlist_t **spares, uint_t nspares,
3490     int namewidth)
3491 {
3492         uint_t i;
3493         char *name;
3494
3495         if (nspares == 0)
3496                 return;
3497
3498         (void) printf(gettext("\tspares\n"));
3499
3500         for (i = 0; i < nspares; i++) {
3501                 name = zpool_vdev_name(g_zfs, zhp, spares[i], B_FALSE);
3502                 print_status_config(zhp, name, spares[i],
3503                     namewidth, 2, B_TRUE);
3504                 free(name);
3505         }
3506 }
3507
3508 static void
3509 print_l2cache(zpool_handle_t *zhp, nvlist_t **l2cache, uint_t nl2cache,
3510     int namewidth)
3511 {
3512         uint_t i;
3513         char *name;
3514
3515         if (nl2cache == 0)
3516                 return;
3517
3518         (void) printf(gettext("\tcache\n"));
3519
3520         for (i = 0; i < nl2cache; i++) {
3521                 name = zpool_vdev_name(g_zfs, zhp, l2cache[i], B_FALSE);
3522                 print_status_config(zhp, name, l2cache[i],
3523                     namewidth, 2, B_FALSE);
3524                 free(name);
3525         }
3526 }
3527
3528 static void
3529 print_dedup_stats(nvlist_t *config)
3530 {
3531         ddt_histogram_t *ddh;
3532         ddt_stat_t *dds;
3533         ddt_object_t *ddo;
3534         uint_t c;
3535
3536         /*
3537          * If the pool was faulted then we may not have been able to
3538          * obtain the config. Otherwise, if have anything in the dedup
3539          * table continue processing the stats.
3540          */
3541         if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
3542             (uint64_t **)&ddo, &c) != 0 || ddo->ddo_count == 0)
3543                 return;
3544
3545         (void) printf("\n");
3546         (void) printf("DDT entries %llu, size %llu on disk, %llu in core\n",
3547             (u_longlong_t)ddo->ddo_count,
3548             (u_longlong_t)ddo->ddo_dspace,
3549             (u_longlong_t)ddo->ddo_mspace);
3550
3551         verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
3552             (uint64_t **)&dds, &c) == 0);
3553         verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
3554             (uint64_t **)&ddh, &c) == 0);
3555         zpool_dump_ddt(dds, ddh);
3556 }
3557
3558 /*
3559  * Display a summary of pool status.  Displays a summary such as:
3560  *
3561  *        pool: tank
3562  *      status: DEGRADED
3563  *      reason: One or more devices ...
3564  *         see: http://zfsonlinux.org/msg/ZFS-xxxx-01
3565  *      config:
3566  *              mirror          DEGRADED
3567  *                c1t0d0        OK
3568  *                c2t0d0        UNAVAIL
3569  *
3570  * When given the '-v' option, we print out the complete config.  If the '-e'
3571  * option is specified, then we print out error rate information as well.
3572  */
3573 int
3574 status_callback(zpool_handle_t *zhp, void *data)
3575 {
3576         status_cbdata_t *cbp = data;
3577         nvlist_t *config, *nvroot;
3578         char *msgid;
3579         int reason;
3580         const char *health;
3581         uint_t c;
3582         vdev_stat_t *vs;
3583
3584         config = zpool_get_config(zhp, NULL);
3585         reason = zpool_get_status(zhp, &msgid);
3586
3587         cbp->cb_count++;
3588
3589         /*
3590          * If we were given 'zpool status -x', only report those pools with
3591          * problems.
3592          */
3593         if (reason == ZPOOL_STATUS_OK && cbp->cb_explain) {
3594                 if (!cbp->cb_allpools) {
3595                         (void) printf(gettext("pool '%s' is healthy\n"),
3596                             zpool_get_name(zhp));
3597                         if (cbp->cb_first)
3598                                 cbp->cb_first = B_FALSE;
3599                 }
3600                 return (0);
3601         }
3602
3603         if (cbp->cb_first)
3604                 cbp->cb_first = B_FALSE;
3605         else
3606                 (void) printf("\n");
3607
3608         verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3609             &nvroot) == 0);
3610         verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
3611             (uint64_t **)&vs, &c) == 0);
3612         health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
3613
3614         (void) printf(gettext("  pool: %s\n"), zpool_get_name(zhp));
3615         (void) printf(gettext(" state: %s\n"), health);
3616
3617         switch (reason) {
3618         case ZPOOL_STATUS_MISSING_DEV_R:
3619                 (void) printf(gettext("status: One or more devices could not "
3620                     "be opened.  Sufficient replicas exist for\n\tthe pool to "
3621                     "continue functioning in a degraded state.\n"));
3622                 (void) printf(gettext("action: Attach the missing device and "
3623                     "online it using 'zpool online'.\n"));
3624                 break;
3625
3626         case ZPOOL_STATUS_MISSING_DEV_NR:
3627                 (void) printf(gettext("status: One or more devices could not "
3628                     "be opened.  There are insufficient\n\treplicas for the "
3629                     "pool to continue functioning.\n"));
3630                 (void) printf(gettext("action: Attach the missing device and "
3631                     "online it using 'zpool online'.\n"));
3632                 break;
3633
3634         case ZPOOL_STATUS_CORRUPT_LABEL_R:
3635                 (void) printf(gettext("status: One or more devices could not "
3636                     "be used because the label is missing or\n\tinvalid.  "
3637                     "Sufficient replicas exist for the pool to continue\n\t"
3638                     "functioning in a degraded state.\n"));
3639                 (void) printf(gettext("action: Replace the device using "
3640                     "'zpool replace'.\n"));
3641                 break;
3642
3643         case ZPOOL_STATUS_CORRUPT_LABEL_NR:
3644                 (void) printf(gettext("status: One or more devices could not "
3645                     "be used because the label is missing \n\tor invalid.  "
3646                     "There are insufficient replicas for the pool to "
3647                     "continue\n\tfunctioning.\n"));
3648                 zpool_explain_recover(zpool_get_handle(zhp),
3649                     zpool_get_name(zhp), reason, config);
3650                 break;
3651
3652         case ZPOOL_STATUS_FAILING_DEV:
3653                 (void) printf(gettext("status: One or more devices has "
3654                     "experienced an unrecoverable error.  An\n\tattempt was "
3655                     "made to correct the error.  Applications are "
3656                     "unaffected.\n"));
3657                 (void) printf(gettext("action: Determine if the device needs "
3658                     "to be replaced, and clear the errors\n\tusing "
3659                     "'zpool clear' or replace the device with 'zpool "
3660                     "replace'.\n"));
3661                 break;
3662
3663         case ZPOOL_STATUS_OFFLINE_DEV:
3664                 (void) printf(gettext("status: One or more devices has "
3665                     "been taken offline by the administrator.\n\tSufficient "
3666                     "replicas exist for the pool to continue functioning in "
3667                     "a\n\tdegraded state.\n"));
3668                 (void) printf(gettext("action: Online the device using "
3669                     "'zpool online' or replace the device with\n\t'zpool "
3670                     "replace'.\n"));
3671                 break;
3672
3673         case ZPOOL_STATUS_REMOVED_DEV:
3674                 (void) printf(gettext("status: One or more devices has "
3675                     "been removed by the administrator.\n\tSufficient "
3676                     "replicas exist for the pool to continue functioning in "
3677                     "a\n\tdegraded state.\n"));
3678                 (void) printf(gettext("action: Online the device using "
3679                     "'zpool online' or replace the device with\n\t'zpool "
3680                     "replace'.\n"));
3681                 break;
3682
3683         case ZPOOL_STATUS_RESILVERING:
3684                 (void) printf(gettext("status: One or more devices is "
3685                     "currently being resilvered.  The pool will\n\tcontinue "
3686                     "to function, possibly in a degraded state.\n"));
3687                 (void) printf(gettext("action: Wait for the resilver to "
3688                     "complete.\n"));
3689                 break;
3690
3691         case ZPOOL_STATUS_CORRUPT_DATA:
3692                 (void) printf(gettext("status: One or more devices has "
3693                     "experienced an error resulting in data\n\tcorruption.  "
3694                     "Applications may be affected.\n"));
3695                 (void) printf(gettext("action: Restore the file in question "
3696                     "if possible.  Otherwise restore the\n\tentire pool from "
3697                     "backup.\n"));
3698                 break;
3699
3700         case ZPOOL_STATUS_CORRUPT_POOL:
3701                 (void) printf(gettext("status: The pool metadata is corrupted "
3702                     "and the pool cannot be opened.\n"));
3703                 zpool_explain_recover(zpool_get_handle(zhp),
3704                     zpool_get_name(zhp), reason, config);
3705                 break;
3706
3707         case ZPOOL_STATUS_VERSION_OLDER:
3708                 (void) printf(gettext("status: The pool is formatted using an "
3709                     "older on-disk format.  The pool can\n\tstill be used, but "
3710                     "some features are unavailable.\n"));
3711                 (void) printf(gettext("action: Upgrade the pool using 'zpool "
3712                     "upgrade'.  Once this is done, the\n\tpool will no longer "
3713                     "be accessible on older software versions.\n"));
3714                 break;
3715
3716         case ZPOOL_STATUS_VERSION_NEWER:
3717                 (void) printf(gettext("status: The pool has been upgraded to a "
3718                     "newer, incompatible on-disk version.\n\tThe pool cannot "
3719                     "be accessed on this system.\n"));
3720                 (void) printf(gettext("action: Access the pool from a system "
3721                     "running more recent software, or\n\trestore the pool from "
3722                     "backup.\n"));
3723                 break;
3724
3725         case ZPOOL_STATUS_FAULTED_DEV_R:
3726                 (void) printf(gettext("status: One or more devices are "
3727                     "faulted in response to persistent errors.\n\tSufficient "
3728                     "replicas exist for the pool to continue functioning "
3729                     "in a\n\tdegraded state.\n"));
3730                 (void) printf(gettext("action: Replace the faulted device, "
3731                     "or use 'zpool clear' to mark the device\n\trepaired.\n"));
3732                 break;
3733
3734         case ZPOOL_STATUS_FAULTED_DEV_NR:
3735                 (void) printf(gettext("status: One or more devices are "
3736                     "faulted in response to persistent errors.  There are "
3737                     "insufficient replicas for the pool to\n\tcontinue "
3738                     "functioning.\n"));
3739                 (void) printf(gettext("action: Destroy and re-create the pool "
3740                     "from a backup source.  Manually marking the device\n"
3741                     "\trepaired using 'zpool clear' may allow some data "
3742                     "to be recovered.\n"));
3743                 break;
3744
3745         case ZPOOL_STATUS_IO_FAILURE_WAIT:
3746         case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
3747                 (void) printf(gettext("status: One or more devices are "
3748                     "faulted in response to IO failures.\n"));
3749                 (void) printf(gettext("action: Make sure the affected devices "
3750                     "are connected, then run 'zpool clear'.\n"));
3751                 break;
3752
3753         case ZPOOL_STATUS_BAD_LOG:
3754                 (void) printf(gettext("status: An intent log record "
3755                     "could not be read.\n"
3756                     "\tWaiting for adminstrator intervention to fix the "
3757                     "faulted pool.\n"));
3758                 (void) printf(gettext("action: Either restore the affected "
3759                     "device(s) and run 'zpool online',\n"
3760                     "\tor ignore the intent log records by running "
3761                     "'zpool clear'.\n"));
3762                 break;
3763
3764         default:
3765                 /*
3766                  * The remaining errors can't actually be generated, yet.
3767                  */
3768                 assert(reason == ZPOOL_STATUS_OK);
3769         }
3770
3771         if (msgid != NULL)
3772                 (void) printf(gettext("   see: http://zfsonlinux.org/msg/%s\n"),
3773                     msgid);
3774
3775         if (config != NULL) {
3776                 int namewidth;
3777                 uint64_t nerr;
3778                 nvlist_t **spares, **l2cache;
3779                 uint_t nspares, nl2cache;
3780                 pool_scan_stat_t *ps = NULL;
3781
3782                 (void) nvlist_lookup_uint64_array(nvroot,
3783                     ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &c);
3784                 print_scan_status(ps);
3785
3786                 namewidth = max_width(zhp, nvroot, 0, 0);
3787                 if (namewidth < 10)
3788                         namewidth = 10;
3789
3790                 (void) printf(gettext("config:\n\n"));
3791                 (void) printf(gettext("\t%-*s  %-8s %5s %5s %5s\n"), namewidth,
3792                     "NAME", "STATE", "READ", "WRITE", "CKSUM");
3793                 print_status_config(zhp, zpool_get_name(zhp), nvroot,
3794                     namewidth, 0, B_FALSE);
3795
3796                 if (num_logs(nvroot) > 0)
3797                         print_logs(zhp, nvroot, namewidth, B_TRUE);
3798                 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
3799                     &l2cache, &nl2cache) == 0)
3800                         print_l2cache(zhp, l2cache, nl2cache, namewidth);
3801
3802                 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
3803                     &spares, &nspares) == 0)
3804                         print_spares(zhp, spares, nspares, namewidth);
3805
3806                 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
3807                     &nerr) == 0) {
3808                         nvlist_t *nverrlist = NULL;
3809
3810                         /*
3811                          * If the approximate error count is small, get a
3812                          * precise count by fetching the entire log and
3813                          * uniquifying the results.
3814                          */
3815                         if (nerr > 0 && nerr < 100 && !cbp->cb_verbose &&
3816                             zpool_get_errlog(zhp, &nverrlist) == 0) {
3817                                 nvpair_t *elem;
3818
3819                                 elem = NULL;
3820                                 nerr = 0;
3821                                 while ((elem = nvlist_next_nvpair(nverrlist,
3822                                     elem)) != NULL) {
3823                                         nerr++;
3824                                 }
3825                         }
3826                         nvlist_free(nverrlist);
3827
3828                         (void) printf("\n");
3829
3830                         if (nerr == 0)
3831                                 (void) printf(gettext("errors: No known data "
3832                                     "errors\n"));
3833                         else if (!cbp->cb_verbose)
3834                                 (void) printf(gettext("errors: %llu data "
3835                                     "errors, use '-v' for a list\n"),
3836                                     (u_longlong_t)nerr);
3837                         else
3838                                 print_error_log(zhp);
3839                 }
3840
3841                 if (cbp->cb_dedup_stats)
3842                         print_dedup_stats(config);
3843         } else {
3844                 (void) printf(gettext("config: The configuration cannot be "
3845                     "determined.\n"));
3846         }
3847
3848         return (0);
3849 }
3850
3851 /*
3852  * zpool status [-vx] [-T d|u] [pool] ... [interval [count]]
3853  *
3854  *      -v      Display complete error logs
3855  *      -x      Display only pools with potential problems
3856  *      -D      Display dedup status (undocumented)
3857  *      -T      Display a timestamp in date(1) or Unix format
3858  *
3859  * Describes the health status of all pools or some subset.
3860  */
3861 int
3862 zpool_do_status(int argc, char **argv)
3863 {
3864         int c;
3865         int ret;
3866         unsigned long interval = 0, count = 0;
3867         status_cbdata_t cb = { 0 };
3868
3869         /* check options */
3870         while ((c = getopt(argc, argv, "vxDT:")) != -1) {
3871                 switch (c) {
3872                 case 'v':
3873                         cb.cb_verbose = B_TRUE;
3874                         break;
3875                 case 'x':
3876                         cb.cb_explain = B_TRUE;
3877                         break;
3878                 case 'D':
3879                         cb.cb_dedup_stats = B_TRUE;
3880                         break;
3881                 case 'T':
3882                         get_timestamp_arg(*optarg);
3883                         break;
3884                 case '?':
3885                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3886                             optopt);
3887                         usage(B_FALSE);
3888                 }
3889         }
3890
3891         argc -= optind;
3892         argv += optind;
3893
3894         get_interval_count(&argc, argv, &interval, &count);
3895
3896         if (argc == 0)
3897                 cb.cb_allpools = B_TRUE;
3898
3899         cb.cb_first = B_TRUE;
3900
3901         for (;;) {
3902                 if (timestamp_fmt != NODATE)
3903                         print_timestamp(timestamp_fmt);
3904
3905                 ret = for_each_pool(argc, argv, B_TRUE, NULL,
3906                     status_callback, &cb);
3907
3908                 if (argc == 0 && cb.cb_count == 0)
3909                         (void) fprintf(stderr, gettext("no pools available\n"));
3910                 else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
3911                         (void) printf(gettext("all pools are healthy\n"));
3912
3913                 if (ret != 0)
3914                         return (ret);
3915
3916                 if (interval == 0)
3917                         break;
3918
3919                 if (count != 0 && --count == 0)
3920                         break;
3921
3922                 (void) sleep(interval);
3923         }
3924
3925         return (0);
3926 }
3927
3928 typedef struct upgrade_cbdata {
3929         int     cb_all;
3930         int     cb_first;
3931         int     cb_newer;
3932         int     cb_argc;
3933         uint64_t cb_version;
3934         char    **cb_argv;
3935 } upgrade_cbdata_t;
3936
3937 static int
3938 upgrade_cb(zpool_handle_t *zhp, void *arg)
3939 {
3940         upgrade_cbdata_t *cbp = arg;
3941         nvlist_t *config;
3942         uint64_t version;
3943         int ret = 0;
3944
3945         config = zpool_get_config(zhp, NULL);
3946         verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
3947             &version) == 0);
3948
3949         if (!cbp->cb_newer && version < SPA_VERSION) {
3950                 if (!cbp->cb_all) {
3951                         if (cbp->cb_first) {
3952                                 (void) printf(gettext("The following pools are "
3953                                     "out of date, and can be upgraded.  After "
3954                                     "being\nupgraded, these pools will no "
3955                                     "longer be accessible by older software "
3956                                     "versions.\n\n"));
3957                                 (void) printf(gettext("VER  POOL\n"));
3958                                 (void) printf(gettext("---  ------------\n"));
3959                                 cbp->cb_first = B_FALSE;
3960                         }
3961
3962                         (void) printf("%2llu   %s\n", (u_longlong_t)version,
3963                             zpool_get_name(zhp));
3964                 } else {
3965                         cbp->cb_first = B_FALSE;
3966                         ret = zpool_upgrade(zhp, cbp->cb_version);
3967                         if (!ret) {
3968                                 (void) printf(gettext("Successfully upgraded "
3969                                     "'%s'\n\n"), zpool_get_name(zhp));
3970                         }
3971                 }
3972         } else if (cbp->cb_newer && version > SPA_VERSION) {
3973                 assert(!cbp->cb_all);
3974
3975                 if (cbp->cb_first) {
3976                         (void) printf(gettext("The following pools are "
3977                             "formatted using a newer software version and\n"
3978                             "cannot be accessed on the current system.\n\n"));
3979                         (void) printf(gettext("VER  POOL\n"));
3980                         (void) printf(gettext("---  ------------\n"));
3981                         cbp->cb_first = B_FALSE;
3982                 }
3983
3984                 (void) printf("%2llu   %s\n", (u_longlong_t)version,
3985                     zpool_get_name(zhp));
3986         }
3987
3988         zpool_close(zhp);
3989         return (ret);
3990 }
3991
3992 /* ARGSUSED */
3993 static int
3994 upgrade_one(zpool_handle_t *zhp, void *data)
3995 {
3996         upgrade_cbdata_t *cbp = data;
3997         uint64_t cur_version;
3998         int ret;
3999
4000         if (strcmp("log", zpool_get_name(zhp)) == 0) {
4001                 (void) printf(gettext("'log' is now a reserved word\n"
4002                     "Pool 'log' must be renamed using export and import"
4003                     " to upgrade.\n"));
4004                 return (1);
4005         }
4006
4007         cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
4008         if (cur_version > cbp->cb_version) {
4009                 (void) printf(gettext("Pool '%s' is already formatted "
4010                     "using more current version '%llu'.\n"),
4011                     zpool_get_name(zhp), (u_longlong_t) cur_version);
4012                 return (0);
4013         }
4014         if (cur_version == cbp->cb_version) {
4015                 (void) printf(gettext("Pool '%s' is already formatted "
4016                     "using the current version.\n"), zpool_get_name(zhp));
4017                 return (0);
4018         }
4019
4020         ret = zpool_upgrade(zhp, cbp->cb_version);
4021
4022         if (!ret) {
4023                 (void) printf(gettext("Successfully upgraded '%s' "
4024                     "from version %llu to version %llu\n\n"),
4025                     zpool_get_name(zhp), (u_longlong_t)cur_version,
4026                     (u_longlong_t)cbp->cb_version);
4027         }
4028
4029         return (ret != 0);
4030 }
4031
4032 /*
4033  * zpool upgrade
4034  * zpool upgrade -v
4035  * zpool upgrade [-V version] <-a | pool ...>
4036  *
4037  * With no arguments, display downrev'd ZFS pool available for upgrade.
4038  * Individual pools can be upgraded by specifying the pool, and '-a' will
4039  * upgrade all pools.
4040  */
4041 int
4042 zpool_do_upgrade(int argc, char **argv)
4043 {
4044         int c;
4045         upgrade_cbdata_t cb = { 0 };
4046         int ret = 0;
4047         boolean_t showversions = B_FALSE;
4048         char *end;
4049
4050
4051         /* check options */
4052         while ((c = getopt(argc, argv, ":avV:")) != -1) {
4053                 switch (c) {
4054                 case 'a':
4055                         cb.cb_all = B_TRUE;
4056                         break;
4057                 case 'v':
4058                         showversions = B_TRUE;
4059                         break;
4060                 case 'V':
4061                         cb.cb_version = strtoll(optarg, &end, 10);
4062                         if (*end != '\0' || cb.cb_version > SPA_VERSION ||
4063                             cb.cb_version < SPA_VERSION_1) {
4064                                 (void) fprintf(stderr,
4065                                     gettext("invalid version '%s'\n"), optarg);
4066                                 usage(B_FALSE);
4067                         }
4068                         break;
4069                 case ':':
4070                         (void) fprintf(stderr, gettext("missing argument for "
4071                             "'%c' option\n"), optopt);
4072                         usage(B_FALSE);
4073                         break;
4074                 case '?':
4075                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4076                             optopt);
4077                         usage(B_FALSE);
4078                 }
4079         }
4080
4081         cb.cb_argc = argc;
4082         cb.cb_argv = argv;
4083         argc -= optind;
4084         argv += optind;
4085
4086         if (cb.cb_version == 0) {
4087                 cb.cb_version = SPA_VERSION;
4088         } else if (!cb.cb_all && argc == 0) {
4089                 (void) fprintf(stderr, gettext("-V option is "
4090                     "incompatible with other arguments\n"));
4091                 usage(B_FALSE);
4092         }
4093
4094         if (showversions) {
4095                 if (cb.cb_all || argc != 0) {
4096                         (void) fprintf(stderr, gettext("-v option is "
4097                             "incompatible with other arguments\n"));
4098                         usage(B_FALSE);
4099                 }
4100         } else if (cb.cb_all) {
4101                 if (argc != 0) {
4102                         (void) fprintf(stderr, gettext("-a option should not "
4103                             "be used along with a pool name\n"));
4104                         usage(B_FALSE);
4105                 }
4106         }
4107
4108         (void) printf(gettext("This system is currently running "
4109             "ZFS pool version %llu.\n\n"), SPA_VERSION);
4110         cb.cb_first = B_TRUE;
4111         if (showversions) {
4112                 (void) printf(gettext("The following versions are "
4113                     "supported:\n\n"));
4114                 (void) printf(gettext("VER  DESCRIPTION\n"));
4115                 (void) printf("---  -----------------------------------------"
4116                     "---------------\n");
4117                 (void) printf(gettext(" 1   Initial ZFS version\n"));
4118                 (void) printf(gettext(" 2   Ditto blocks "
4119                     "(replicated metadata)\n"));
4120                 (void) printf(gettext(" 3   Hot spares and double parity "
4121                     "RAID-Z\n"));
4122                 (void) printf(gettext(" 4   zpool history\n"));
4123                 (void) printf(gettext(" 5   Compression using the gzip "
4124                     "algorithm\n"));
4125                 (void) printf(gettext(" 6   bootfs pool property\n"));
4126                 (void) printf(gettext(" 7   Separate intent log devices\n"));
4127                 (void) printf(gettext(" 8   Delegated administration\n"));
4128                 (void) printf(gettext(" 9   refquota and refreservation "
4129                     "properties\n"));
4130                 (void) printf(gettext(" 10  Cache devices\n"));
4131                 (void) printf(gettext(" 11  Improved scrub performance\n"));
4132                 (void) printf(gettext(" 12  Snapshot properties\n"));
4133                 (void) printf(gettext(" 13  snapused property\n"));
4134                 (void) printf(gettext(" 14  passthrough-x aclinherit\n"));
4135                 (void) printf(gettext(" 15  user/group space accounting\n"));
4136                 (void) printf(gettext(" 16  stmf property support\n"));
4137                 (void) printf(gettext(" 17  Triple-parity RAID-Z\n"));
4138                 (void) printf(gettext(" 18  Snapshot user holds\n"));
4139                 (void) printf(gettext(" 19  Log device removal\n"));
4140                 (void) printf(gettext(" 20  Compression using zle "
4141                     "(zero-length encoding)\n"));
4142                 (void) printf(gettext(" 21  Deduplication\n"));
4143                 (void) printf(gettext(" 22  Received properties\n"));
4144                 (void) printf(gettext(" 23  Slim ZIL\n"));
4145                 (void) printf(gettext(" 24  System attributes\n"));
4146                 (void) printf(gettext(" 25  Improved scrub stats\n"));
4147                 (void) printf(gettext(" 26  Improved snapshot deletion "
4148                     "performance\n"));
4149                 (void) printf(gettext(" 27  Improved snapshot creation "
4150                     "performance\n"));
4151                 (void) printf(gettext(" 28  Multiple vdev replacements\n"));
4152                 (void) printf(gettext("\nFor more information on a particular "
4153                     "version, including supported releases,\n"));
4154                 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
4155         } else if (argc == 0) {
4156                 int notfound;
4157
4158                 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
4159                 notfound = cb.cb_first;
4160
4161                 if (!cb.cb_all && ret == 0) {
4162                         if (!cb.cb_first)
4163                                 (void) printf("\n");
4164                         cb.cb_first = B_TRUE;
4165                         cb.cb_newer = B_TRUE;
4166                         ret = zpool_iter(g_zfs, upgrade_cb, &cb);
4167                         if (!cb.cb_first) {
4168                                 notfound = B_FALSE;
4169                                 (void) printf("\n");
4170                         }
4171                 }
4172
4173                 if (ret == 0) {
4174                         if (notfound)
4175                                 (void) printf(gettext("All pools are formatted "
4176                                     "using this version.\n"));
4177                         else if (!cb.cb_all)
4178                                 (void) printf(gettext("Use 'zpool upgrade -v' "
4179                                     "for a list of available versions and "
4180                                     "their associated\nfeatures.\n"));
4181                 }
4182         } else {
4183                 ret = for_each_pool(argc, argv, B_FALSE, NULL,
4184                     upgrade_one, &cb);
4185         }
4186
4187         return (ret);
4188 }
4189
4190 typedef struct hist_cbdata {
4191         boolean_t first;
4192         int longfmt;
4193         int internal;
4194 } hist_cbdata_t;
4195
4196 /*
4197  * Print out the command history for a specific pool.
4198  */
4199 static int
4200 get_history_one(zpool_handle_t *zhp, void *data)
4201 {
4202         nvlist_t *nvhis;
4203         nvlist_t **records;
4204         uint_t numrecords;
4205         char *cmdstr;
4206         char *pathstr;
4207         uint64_t dst_time;
4208         time_t tsec;
4209         struct tm t;
4210         char tbuf[30];
4211         int ret, i;
4212         uint64_t who;
4213         struct passwd *pwd;
4214         char *hostname;
4215         char *zonename;
4216         char internalstr[MAXPATHLEN];
4217         hist_cbdata_t *cb = (hist_cbdata_t *)data;
4218         uint64_t txg;
4219         uint64_t ievent;
4220
4221         cb->first = B_FALSE;
4222
4223         (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
4224
4225         if ((ret = zpool_get_history(zhp, &nvhis)) != 0)
4226                 return (ret);
4227
4228         verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
4229             &records, &numrecords) == 0);
4230         for (i = 0; i < numrecords; i++) {
4231                 if (nvlist_lookup_uint64(records[i], ZPOOL_HIST_TIME,
4232                     &dst_time) != 0)
4233                         continue;
4234
4235                 /* is it an internal event or a standard event? */
4236                 if (nvlist_lookup_string(records[i], ZPOOL_HIST_CMD,
4237                     &cmdstr) != 0) {
4238                         if (cb->internal == 0)
4239                                 continue;
4240
4241                         if (nvlist_lookup_uint64(records[i],
4242                             ZPOOL_HIST_INT_EVENT, &ievent) != 0)
4243                                 continue;
4244                         verify(nvlist_lookup_uint64(records[i],
4245                             ZPOOL_HIST_TXG, &txg) == 0);
4246                         verify(nvlist_lookup_string(records[i],
4247                             ZPOOL_HIST_INT_STR, &pathstr) == 0);
4248                         if (ievent >= LOG_END)
4249                                 continue;
4250                         (void) snprintf(internalstr,
4251                             sizeof (internalstr),
4252                             "[internal %s txg:%llu] %s",
4253                             zfs_history_event_names[ievent], (u_longlong_t)txg,
4254                             pathstr);
4255                         cmdstr = internalstr;
4256                 }
4257                 tsec = dst_time;
4258                 (void) localtime_r(&tsec, &t);
4259                 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
4260                 (void) printf("%s %s", tbuf, cmdstr);
4261
4262                 if (!cb->longfmt) {
4263                         (void) printf("\n");
4264                         continue;
4265                 }
4266                 (void) printf(" [");
4267                 if (nvlist_lookup_uint64(records[i],
4268                     ZPOOL_HIST_WHO, &who) == 0) {
4269                         pwd = getpwuid((uid_t)who);
4270                         if (pwd)
4271                                 (void) printf("user %s on",
4272                                     pwd->pw_name);
4273                         else
4274                                 (void) printf("user %d on",
4275                                     (int)who);
4276                 } else {
4277                         (void) printf(gettext("no info]\n"));
4278                         continue;
4279                 }
4280                 if (nvlist_lookup_string(records[i],
4281                     ZPOOL_HIST_HOST, &hostname) == 0) {
4282                         (void) printf(" %s", hostname);
4283                 }
4284                 if (nvlist_lookup_string(records[i],
4285                     ZPOOL_HIST_ZONE, &zonename) == 0) {
4286                         (void) printf(":%s", zonename);
4287                 }
4288
4289                 (void) printf("]");
4290                 (void) printf("\n");
4291         }
4292         (void) printf("\n");
4293         nvlist_free(nvhis);
4294
4295         return (ret);
4296 }
4297
4298 /*
4299  * zpool history <pool>
4300  *
4301  * Displays the history of commands that modified pools.
4302  */
4303
4304
4305 int
4306 zpool_do_history(int argc, char **argv)
4307 {
4308         hist_cbdata_t cbdata = { 0 };
4309         int ret;
4310         int c;
4311
4312         cbdata.first = B_TRUE;
4313         /* check options */
4314         while ((c = getopt(argc, argv, "li")) != -1) {
4315                 switch (c) {
4316                 case 'l':
4317                         cbdata.longfmt = 1;
4318                         break;
4319                 case 'i':
4320                         cbdata.internal = 1;
4321                         break;
4322                 case '?':
4323                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4324                             optopt);
4325                         usage(B_FALSE);
4326                 }
4327         }
4328         argc -= optind;
4329         argv += optind;
4330
4331         ret = for_each_pool(argc, argv, B_FALSE,  NULL, get_history_one,
4332             &cbdata);
4333
4334         if (argc == 0 && cbdata.first == B_TRUE) {
4335                 (void) fprintf(stderr, gettext("no pools available\n"));
4336                 return (0);
4337         }
4338
4339         return (ret);
4340 }
4341
4342 typedef struct ev_opts {
4343         int verbose;
4344         int scripted;
4345         int follow;
4346         int clear;
4347 } ev_opts_t;
4348
4349 static void
4350 zpool_do_events_short(nvlist_t *nvl)
4351 {
4352         char ctime_str[26], str[32], *ptr;
4353         int64_t *tv;
4354         uint_t n;
4355
4356         verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
4357         memset(str, ' ', 32);
4358         (void) ctime_r((const time_t *)&tv[0], ctime_str);
4359         (void) strncpy(str,    ctime_str+4,  6);             /* 'Jun 30'     */
4360         (void) strncpy(str+7,  ctime_str+20, 4);             /* '1993'       */
4361         (void) strncpy(str+12, ctime_str+11, 8);             /* '21:49:08'   */
4362         (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]);/* '.123456789' */
4363         (void) printf(gettext("%s "), str);
4364
4365         verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
4366         (void) printf(gettext("%s\n"), ptr);
4367 }
4368
4369 static void
4370 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
4371 {
4372         nvpair_t *nvp;
4373
4374         for (nvp = nvlist_next_nvpair(nvl, NULL);
4375             nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
4376
4377                 data_type_t type = nvpair_type(nvp);
4378                 const char *name = nvpair_name(nvp);
4379
4380                 boolean_t b;
4381                 uint8_t i8;
4382                 uint16_t i16;
4383                 uint32_t i32;
4384                 uint64_t i64;
4385                 char *str;
4386                 nvlist_t *cnv;
4387
4388                 printf(gettext("%*s%s = "), depth, "", name);
4389
4390                 switch (type) {
4391                 case DATA_TYPE_BOOLEAN:
4392                         printf(gettext("%s"), "1");
4393                         break;
4394
4395                 case DATA_TYPE_BOOLEAN_VALUE:
4396                         (void) nvpair_value_boolean_value(nvp, &b);
4397                         printf(gettext("%s"), b ? "1" : "0");
4398                         break;
4399
4400                 case DATA_TYPE_BYTE:
4401                         (void) nvpair_value_byte(nvp, &i8);
4402                         printf(gettext("0x%x"), i8);
4403                         break;
4404
4405                 case DATA_TYPE_INT8:
4406                         (void) nvpair_value_int8(nvp, (void *)&i8);
4407                         printf(gettext("0x%x"), i8);
4408                         break;
4409
4410                 case DATA_TYPE_UINT8:
4411                         (void) nvpair_value_uint8(nvp, &i8);
4412                         printf(gettext("0x%x"), i8);
4413                         break;
4414
4415                 case DATA_TYPE_INT16:
4416                         (void) nvpair_value_int16(nvp, (void *)&i16);
4417                         printf(gettext("0x%x"), i16);
4418                         break;
4419
4420                 case DATA_TYPE_UINT16:
4421                         (void) nvpair_value_uint16(nvp, &i16);
4422                         printf(gettext("0x%x"), i16);
4423                         break;
4424
4425                 case DATA_TYPE_INT32:
4426                         (void) nvpair_value_int32(nvp, (void *)&i32);
4427                         printf(gettext("0x%x"), i32);
4428                         break;
4429
4430                 case DATA_TYPE_UINT32:
4431                         (void) nvpair_value_uint32(nvp, &i32);
4432                         printf(gettext("0x%x"), i32);
4433                         break;
4434
4435                 case DATA_TYPE_INT64:
4436                         (void) nvpair_value_int64(nvp, (void *)&i64);
4437                         printf(gettext("0x%llx"), (u_longlong_t)i64);
4438                         break;
4439
4440                 case DATA_TYPE_UINT64:
4441                         (void) nvpair_value_uint64(nvp, &i64);
4442                         printf(gettext("0x%llx"), (u_longlong_t)i64);
4443                         break;
4444
4445                 case DATA_TYPE_HRTIME:
4446                         (void) nvpair_value_hrtime(nvp, (void *)&i64);
4447                         printf(gettext("0x%llx"), (u_longlong_t)i64);
4448                         break;
4449
4450                 case DATA_TYPE_STRING:
4451                         (void) nvpair_value_string(nvp, &str);
4452                         printf(gettext("\"%s\""), str ? str : "<NULL>");
4453                         break;
4454
4455                 case DATA_TYPE_NVLIST:
4456                         printf(gettext("(embedded nvlist)\n"));
4457                         (void) nvpair_value_nvlist(nvp, &cnv);
4458                         zpool_do_events_nvprint(cnv, depth + 8);
4459                         printf(gettext("%*s(end %s)"), depth, "", name);
4460                         break;
4461
4462                 case DATA_TYPE_NVLIST_ARRAY: {
4463                         nvlist_t **val;
4464                         uint_t i, nelem;
4465
4466                         (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
4467                         printf(gettext("(%d embedded nvlists)\n"), nelem);
4468                         for (i = 0; i < nelem; i++) {
4469                                 printf(gettext("%*s%s[%d] = %s\n"),
4470                                        depth, "", name, i, "(embedded nvlist)");
4471                                 zpool_do_events_nvprint(val[i], depth + 8);
4472                                 printf(gettext("%*s(end %s[%i])\n"),
4473                                        depth, "", name, i);
4474                         }
4475                         printf(gettext("%*s(end %s)\n"), depth, "", name);
4476                         }
4477                         break;
4478
4479                 case DATA_TYPE_INT8_ARRAY: {
4480                         int8_t *val;
4481                         uint_t i, nelem;
4482
4483                         (void) nvpair_value_int8_array(nvp, &val, &nelem);
4484                         for (i = 0; i < nelem; i++)
4485                                 printf(gettext("0x%x "), val[i]);
4486
4487                         break;
4488                         }
4489
4490                 case DATA_TYPE_UINT8_ARRAY: {
4491                         uint8_t *val;
4492                         uint_t i, nelem;
4493
4494                         (void) nvpair_value_uint8_array(nvp, &val, &nelem);
4495                         for (i = 0; i < nelem; i++)
4496                                 printf(gettext("0x%x "), val[i]);
4497
4498                         break;
4499                         }
4500
4501                 case DATA_TYPE_INT16_ARRAY: {
4502                         int16_t *val;
4503                         uint_t i, nelem;
4504
4505                         (void) nvpair_value_int16_array(nvp, &val, &nelem);
4506                         for (i = 0; i < nelem; i++)
4507                                 printf(gettext("0x%x "), val[i]);
4508
4509                         break;
4510                         }
4511
4512                 case DATA_TYPE_UINT16_ARRAY: {
4513                         uint16_t *val;
4514                         uint_t i, nelem;
4515
4516                         (void) nvpair_value_uint16_array(nvp, &val, &nelem);
4517                         for (i = 0; i < nelem; i++)
4518                                 printf(gettext("0x%x "), val[i]);
4519
4520                         break;
4521                         }
4522
4523                 case DATA_TYPE_INT32_ARRAY: {
4524                         int32_t *val;
4525                         uint_t i, nelem;
4526
4527                         (void) nvpair_value_int32_array(nvp, &val, &nelem);
4528                         for (i = 0; i < nelem; i++)
4529                                 printf(gettext("0x%x "), val[i]);
4530
4531                         break;
4532                         }
4533
4534                 case DATA_TYPE_UINT32_ARRAY: {
4535                         uint32_t *val;
4536                         uint_t i, nelem;
4537
4538                         (void) nvpair_value_uint32_array(nvp, &val, &nelem);
4539                         for (i = 0; i < nelem; i++)
4540                                 printf(gettext("0x%x "), val[i]);
4541
4542                         break;
4543                         }
4544
4545                 case DATA_TYPE_INT64_ARRAY: {
4546                         int64_t *val;
4547                         uint_t i, nelem;
4548
4549                         (void) nvpair_value_int64_array(nvp, &val, &nelem);
4550                         for (i = 0; i < nelem; i++)
4551                                 printf(gettext("0x%llx "), (u_longlong_t)val[i]);
4552
4553                         break;
4554                         }
4555
4556                 case DATA_TYPE_UINT64_ARRAY: {
4557                         uint64_t *val;
4558                         uint_t i, nelem;
4559
4560                         (void) nvpair_value_uint64_array(nvp, &val, &nelem);
4561                         for (i = 0; i < nelem; i++)
4562                                 printf(gettext("0x%llx "), (u_longlong_t)val[i]);
4563
4564                         break;
4565                         }
4566
4567                 case DATA_TYPE_STRING_ARRAY:
4568                 case DATA_TYPE_BOOLEAN_ARRAY:
4569                 case DATA_TYPE_BYTE_ARRAY:
4570                 case DATA_TYPE_DOUBLE:
4571                 case DATA_TYPE_UNKNOWN:
4572                         printf(gettext("<unknown>"));
4573                         break;
4574                 }
4575
4576                 printf(gettext("\n"));
4577         }
4578 }
4579
4580 static int
4581 zpool_do_events_next(ev_opts_t *opts)
4582 {
4583         nvlist_t *nvl;
4584         int cleanup_fd, ret, dropped;
4585
4586         cleanup_fd = open(ZFS_DEV, O_RDWR);
4587         VERIFY(cleanup_fd >= 0);
4588
4589         if (!opts->scripted)
4590                 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
4591
4592         while (1) {
4593                 ret = zpool_events_next(g_zfs, &nvl, &dropped,
4594                     !!opts->follow, cleanup_fd);
4595                 if (ret || nvl == NULL)
4596                         break;
4597
4598                 if (dropped > 0)
4599                         (void) printf(gettext("dropped %d events\n"), dropped);
4600
4601                 zpool_do_events_short(nvl);
4602
4603                 if (opts->verbose) {
4604                         zpool_do_events_nvprint(nvl, 8);
4605                         printf(gettext("\n"));
4606                 }
4607
4608                 nvlist_free(nvl);
4609         }
4610
4611         VERIFY(0 == close(cleanup_fd));
4612
4613         return (ret);
4614 }
4615
4616 static int
4617 zpool_do_events_clear(ev_opts_t *opts)
4618 {
4619         int count, ret;
4620
4621         ret = zpool_events_clear(g_zfs, &count);
4622         if (!ret)
4623                 (void) printf(gettext("cleared %d events\n"), count);
4624
4625         return (ret);
4626 }
4627
4628 /*
4629  * zpool events [-vfc]
4630  *
4631  * Displays events logs by ZFS.
4632  */
4633 int
4634 zpool_do_events(int argc, char **argv)
4635 {
4636         ev_opts_t opts = { 0 };
4637         int ret;
4638         int c;
4639
4640         /* check options */
4641         while ((c = getopt(argc, argv, "vHfc")) != -1) {
4642                 switch (c) {
4643                 case 'v':
4644                         opts.verbose = 1;
4645                         break;
4646                 case 'H':
4647                         opts.scripted = 1;
4648                         break;
4649                 case 'f':
4650                         opts.follow = 1;
4651                         break;
4652                 case 'c':
4653                         opts.clear = 1;
4654                         break;
4655                 case '?':
4656                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4657                             optopt);
4658                         usage(B_FALSE);
4659                 }
4660         }
4661         argc -= optind;
4662         argv += optind;
4663
4664         if (opts.clear)
4665                 ret = zpool_do_events_clear(&opts);
4666         else
4667                 ret = zpool_do_events_next(&opts);
4668
4669         return ret;
4670 }
4671
4672 static int
4673 get_callback(zpool_handle_t *zhp, void *data)
4674 {
4675         zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
4676         char value[MAXNAMELEN];
4677         zprop_source_t srctype;
4678         zprop_list_t *pl;
4679
4680         for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
4681
4682                 /*
4683                  * Skip the special fake placeholder. This will also skip
4684                  * over the name property when 'all' is specified.
4685                  */
4686                 if (pl->pl_prop == ZPOOL_PROP_NAME &&
4687                     pl == cbp->cb_proplist)
4688                         continue;
4689
4690                 if (zpool_get_prop(zhp, pl->pl_prop,
4691                     value, sizeof (value), &srctype) != 0)
4692                         continue;
4693
4694                 zprop_print_one_property(zpool_get_name(zhp), cbp,
4695                     zpool_prop_to_name(pl->pl_prop), value, srctype, NULL,
4696                     NULL);
4697         }
4698         return (0);
4699 }
4700
4701 int
4702 zpool_do_get(int argc, char **argv)
4703 {
4704         zprop_get_cbdata_t cb = { 0 };
4705         zprop_list_t fake_name = { 0 };
4706         int ret;
4707
4708         if (argc < 3)
4709                 usage(B_FALSE);
4710
4711         cb.cb_first = B_TRUE;
4712         cb.cb_sources = ZPROP_SRC_ALL;
4713         cb.cb_columns[0] = GET_COL_NAME;
4714         cb.cb_columns[1] = GET_COL_PROPERTY;
4715         cb.cb_columns[2] = GET_COL_VALUE;
4716         cb.cb_columns[3] = GET_COL_SOURCE;
4717         cb.cb_type = ZFS_TYPE_POOL;
4718
4719         if (zprop_get_list(g_zfs, argv[1],  &cb.cb_proplist,
4720             ZFS_TYPE_POOL) != 0)
4721                 usage(B_FALSE);
4722
4723         if (cb.cb_proplist != NULL) {
4724                 fake_name.pl_prop = ZPOOL_PROP_NAME;
4725                 fake_name.pl_width = strlen(gettext("NAME"));
4726                 fake_name.pl_next = cb.cb_proplist;
4727                 cb.cb_proplist = &fake_name;
4728         }
4729
4730         ret = for_each_pool(argc - 2, argv + 2, B_TRUE, &cb.cb_proplist,
4731             get_callback, &cb);
4732
4733         if (cb.cb_proplist == &fake_name)
4734                 zprop_free_list(fake_name.pl_next);
4735         else
4736                 zprop_free_list(cb.cb_proplist);
4737
4738         return (ret);
4739 }
4740
4741 typedef struct set_cbdata {
4742         char *cb_propname;
4743         char *cb_value;
4744         boolean_t cb_any_successful;
4745 } set_cbdata_t;
4746
4747 int
4748 set_callback(zpool_handle_t *zhp, void *data)
4749 {
4750         int error;
4751         set_cbdata_t *cb = (set_cbdata_t *)data;
4752
4753         error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
4754
4755         if (!error)
4756                 cb->cb_any_successful = B_TRUE;
4757
4758         return (error);
4759 }
4760
4761 int
4762 zpool_do_set(int argc, char **argv)
4763 {
4764         set_cbdata_t cb = { 0 };
4765         int error;
4766
4767         if (argc > 1 && argv[1][0] == '-') {
4768                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4769                     argv[1][1]);
4770                 usage(B_FALSE);
4771         }
4772
4773         if (argc < 2) {
4774                 (void) fprintf(stderr, gettext("missing property=value "
4775                     "argument\n"));
4776                 usage(B_FALSE);
4777         }
4778
4779         if (argc < 3) {
4780                 (void) fprintf(stderr, gettext("missing pool name\n"));
4781                 usage(B_FALSE);
4782         }
4783
4784         if (argc > 3) {
4785                 (void) fprintf(stderr, gettext("too many pool names\n"));
4786                 usage(B_FALSE);
4787         }
4788
4789         cb.cb_propname = argv[1];
4790         cb.cb_value = strchr(cb.cb_propname, '=');
4791         if (cb.cb_value == NULL) {
4792                 (void) fprintf(stderr, gettext("missing value in "
4793                     "property=value argument\n"));
4794                 usage(B_FALSE);
4795         }
4796
4797         *(cb.cb_value) = '\0';
4798         cb.cb_value++;
4799
4800         error = for_each_pool(argc - 2, argv + 2, B_TRUE, NULL,
4801             set_callback, &cb);
4802
4803         return (error);
4804 }
4805
4806 static int
4807 find_command_idx(char *command, int *idx)
4808 {
4809         int i;
4810
4811         for (i = 0; i < NCOMMAND; i++) {
4812                 if (command_table[i].name == NULL)
4813                         continue;
4814
4815                 if (strcmp(command, command_table[i].name) == 0) {
4816                         *idx = i;
4817                         return (0);
4818                 }
4819         }
4820         return (1);
4821 }
4822
4823 int
4824 main(int argc, char **argv)
4825 {
4826         int ret;
4827         int i = 0;
4828         char *cmdname;
4829
4830         (void) setlocale(LC_ALL, "");
4831         (void) textdomain(TEXT_DOMAIN);
4832
4833         opterr = 0;
4834
4835         /*
4836          * Make sure the user has specified some command.
4837          */
4838         if (argc < 2) {
4839                 (void) fprintf(stderr, gettext("missing command\n"));
4840                 usage(B_FALSE);
4841         }
4842
4843         cmdname = argv[1];
4844
4845         /*
4846          * Special case '-?'
4847          */
4848         if ((strcmp(cmdname, "-?") == 0) ||
4849              strcmp(cmdname, "--help") == 0)
4850                 usage(B_TRUE);
4851
4852         if ((g_zfs = libzfs_init()) == NULL)
4853                 return (1);
4854
4855         libzfs_print_on_error(g_zfs, B_TRUE);
4856
4857         zpool_set_history_str("zpool", argc, argv, history_str);
4858         verify(zpool_stage_history(g_zfs, history_str) == 0);
4859
4860         /*
4861          * Run the appropriate command.
4862          */
4863         if (find_command_idx(cmdname, &i) == 0) {
4864                 current_command = &command_table[i];
4865                 ret = command_table[i].func(argc - 1, argv + 1);
4866         } else if (strchr(cmdname, '=')) {
4867                 verify(find_command_idx("set", &i) == 0);
4868                 current_command = &command_table[i];
4869                 ret = command_table[i].func(argc, argv);
4870         } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
4871                 /*
4872                  * 'freeze' is a vile debugging abomination, so we treat
4873                  * it as such.
4874                  */
4875                 char buf[16384];
4876                 int fd = open(ZFS_DEV, O_RDWR);
4877                 (void) strcpy((void *)buf, argv[2]);
4878                 return (!!ioctl(fd, ZFS_IOC_POOL_FREEZE, buf));
4879         } else {
4880                 (void) fprintf(stderr, gettext("unrecognized "
4881                     "command '%s'\n"), cmdname);
4882                 usage(B_FALSE);
4883                 ret = 1;
4884         }
4885
4886         libzfs_fini(g_zfs);
4887
4888         /*
4889          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
4890          * for the purposes of running ::findleaks.
4891          */
4892         if (getenv("ZFS_ABORT") != NULL) {
4893                 (void) printf("dumping core by request\n");
4894                 abort();
4895         }
4896
4897         return (ret);
4898 }