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