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