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