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