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