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