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