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