xref: /illumos-gate/usr/src/cmd/zpool/zpool_main.c (revision e43afc9605f99023dbdb4a7b5309de87e6016db6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2012 by Frederik Wessels. All rights reserved.
26  * Copyright (c) 2013 by Prasad Joshi (sTec). All rights reserved.
27  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
28  * Copyright 2016 Nexenta Systems, Inc.
29  * Copyright (c) 2017 Datto Inc.
30  * Copyright (c) 2017, Intel Corporation.
31  * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>
32  * Copyright 2020 Joyent, Inc.
33  * Copyright (c) 2012 by Cyril Plisko. All rights reserved.
34  * Copyright 2019 OmniOS Community Edition (OmniOSce) Association.
35  */
36 
37 #include <assert.h>
38 #include <ctype.h>
39 #include <dirent.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <getopt.h>
43 #include <libgen.h>
44 #include <libintl.h>
45 #include <libuutil.h>
46 #include <locale.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <strings.h>
51 #include <unistd.h>
52 #include <priv.h>
53 #include <pwd.h>
54 #include <zone.h>
55 #include <zfs_prop.h>
56 #include <sys/fs/zfs.h>
57 #include <sys/stat.h>
58 #include <sys/debug.h>
59 #include <math.h>
60 #include <sys/sysmacros.h>
61 #include <sys/termios.h>
62 
63 #include <libzfs.h>
64 #include <libzutil.h>
65 
66 #include "zpool_util.h"
67 #include "zfs_comutil.h"
68 #include "zfeature_common.h"
69 
70 #include "statcommon.h"
71 
72 libzfs_handle_t *g_zfs;
73 
74 static int zpool_do_create(int, char **);
75 static int zpool_do_destroy(int, char **);
76 
77 static int zpool_do_add(int, char **);
78 static int zpool_do_remove(int, char **);
79 static int zpool_do_labelclear(int, char **);
80 
81 static int zpool_do_checkpoint(int, char **);
82 
83 static int zpool_do_list(int, char **);
84 static int zpool_do_iostat(int, char **);
85 static int zpool_do_status(int, char **);
86 
87 static int zpool_do_online(int, char **);
88 static int zpool_do_offline(int, char **);
89 static int zpool_do_clear(int, char **);
90 static int zpool_do_reopen(int, char **);
91 
92 static int zpool_do_reguid(int, char **);
93 
94 static int zpool_do_attach(int, char **);
95 static int zpool_do_detach(int, char **);
96 static int zpool_do_replace(int, char **);
97 static int zpool_do_split(int, char **);
98 
99 static int zpool_do_initialize(int, char **);
100 static int zpool_do_scrub(int, char **);
101 static int zpool_do_resilver(int, char **);
102 static int zpool_do_trim(int, char **);
103 
104 static int zpool_do_import(int, char **);
105 static int zpool_do_export(int, char **);
106 
107 static int zpool_do_upgrade(int, char **);
108 
109 static int zpool_do_history(int, char **);
110 
111 static int zpool_do_get(int, char **);
112 static int zpool_do_set(int, char **);
113 
114 static int zpool_do_sync(int, char **);
115 
116 /*
117  * These libumem hooks provide a reasonable set of defaults for the allocator's
118  * debugging facilities.
119  */
120 
121 #ifdef DEBUG
122 const char *
123 _umem_debug_init(void)
124 {
125 	return ("default,verbose"); /* $UMEM_DEBUG setting */
126 }
127 
128 const char *
129 _umem_logging_init(void)
130 {
131 	return ("fail,contents"); /* $UMEM_LOGGING setting */
132 }
133 #endif
134 
135 typedef enum {
136 	HELP_ADD,
137 	HELP_ATTACH,
138 	HELP_CLEAR,
139 	HELP_CREATE,
140 	HELP_CHECKPOINT,
141 	HELP_DESTROY,
142 	HELP_DETACH,
143 	HELP_EXPORT,
144 	HELP_HISTORY,
145 	HELP_IMPORT,
146 	HELP_IOSTAT,
147 	HELP_LABELCLEAR,
148 	HELP_LIST,
149 	HELP_OFFLINE,
150 	HELP_ONLINE,
151 	HELP_REPLACE,
152 	HELP_REMOVE,
153 	HELP_INITIALIZE,
154 	HELP_SCRUB,
155 	HELP_RESILVER,
156 	HELP_TRIM,
157 	HELP_STATUS,
158 	HELP_UPGRADE,
159 	HELP_GET,
160 	HELP_SET,
161 	HELP_SPLIT,
162 	HELP_SYNC,
163 	HELP_REGUID,
164 	HELP_REOPEN
165 } zpool_help_t;
166 
167 
168 /*
169  * Flags for stats to display with "zpool iostats"
170  */
171 enum iostat_type {
172 	IOS_DEFAULT = 0,
173 	IOS_LATENCY = 1,
174 	IOS_QUEUES = 2,
175 	IOS_L_HISTO = 3,
176 	IOS_RQ_HISTO = 4,
177 	IOS_COUNT,	/* always last element */
178 };
179 
180 /* iostat_type entries as bitmasks */
181 #define	IOS_DEFAULT_M	(1ULL << IOS_DEFAULT)
182 #define	IOS_LATENCY_M	(1ULL << IOS_LATENCY)
183 #define	IOS_QUEUES_M	(1ULL << IOS_QUEUES)
184 #define	IOS_L_HISTO_M	(1ULL << IOS_L_HISTO)
185 #define	IOS_RQ_HISTO_M	(1ULL << IOS_RQ_HISTO)
186 
187 /* Mask of all the histo bits */
188 #define	IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
189 
190 /*
191  * Lookup table for iostat flags to nvlist names.  Basically a list
192  * of all the nvlists a flag requires.  Also specifies the order in
193  * which data gets printed in zpool iostat.
194  */
195 static const char *vsx_type_to_nvlist[IOS_COUNT][13] = {
196 	[IOS_L_HISTO] = {
197 	    ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
198 	    ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
199 	    ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
200 	    ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
201 	    ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
202 	    ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
203 	    ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
204 	    ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
205 	    ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
206 	    ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
207 	    NULL},
208 	[IOS_LATENCY] = {
209 	    ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
210 	    ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
211 	    ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
212 	    ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
213 	    ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
214 	    NULL},
215 	[IOS_QUEUES] = {
216 	    ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
217 	    ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
218 	    ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
219 	    ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
220 	    ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
221 	    ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
222 	    NULL},
223 	[IOS_RQ_HISTO] = {
224 	    ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
225 	    ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
226 	    ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
227 	    ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
228 	    ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
229 	    ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
230 	    ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
231 	    ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
232 	    ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
233 	    ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
234 	    ZPOOL_CONFIG_VDEV_IND_TRIM_HISTO,
235 	    ZPOOL_CONFIG_VDEV_AGG_TRIM_HISTO,
236 	    NULL},
237 };
238 
239 
240 /*
241  * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
242  * Right now, only one histo bit is ever set at one time, so we can
243  * just do a highbit64(a)
244  */
245 #define	IOS_HISTO_IDX(a)	(highbit64(a & IOS_ANYHISTO_M) - 1)
246 
247 typedef struct zpool_command {
248 	const char	*name;
249 	int		(*func)(int, char **);
250 	zpool_help_t	usage;
251 } zpool_command_t;
252 
253 /*
254  * Master command table.  Each ZFS command has a name, associated function, and
255  * usage message.  The usage messages need to be internationalized, so we have
256  * to have a function to return the usage message based on a command index.
257  *
258  * These commands are organized according to how they are displayed in the usage
259  * message.  An empty command (one with a NULL name) indicates an empty line in
260  * the generic usage message.
261  */
262 static zpool_command_t command_table[] = {
263 	{ "create",	zpool_do_create,	HELP_CREATE		},
264 	{ "destroy",	zpool_do_destroy,	HELP_DESTROY		},
265 	{ NULL },
266 	{ "add",	zpool_do_add,		HELP_ADD		},
267 	{ "remove",	zpool_do_remove,	HELP_REMOVE		},
268 	{ NULL },
269 	{ "labelclear",	zpool_do_labelclear,	HELP_LABELCLEAR		},
270 	{ NULL },
271 	{ "checkpoint",	zpool_do_checkpoint,	HELP_CHECKPOINT		},
272 	{ NULL },
273 	{ "list",	zpool_do_list,		HELP_LIST		},
274 	{ "iostat",	zpool_do_iostat,	HELP_IOSTAT		},
275 	{ "status",	zpool_do_status,	HELP_STATUS		},
276 	{ NULL },
277 	{ "online",	zpool_do_online,	HELP_ONLINE		},
278 	{ "offline",	zpool_do_offline,	HELP_OFFLINE		},
279 	{ "clear",	zpool_do_clear,		HELP_CLEAR		},
280 	{ "reopen",	zpool_do_reopen,	HELP_REOPEN		},
281 	{ NULL },
282 	{ "attach",	zpool_do_attach,	HELP_ATTACH		},
283 	{ "detach",	zpool_do_detach,	HELP_DETACH		},
284 	{ "replace",	zpool_do_replace,	HELP_REPLACE		},
285 	{ "split",	zpool_do_split,		HELP_SPLIT		},
286 	{ NULL },
287 	{ "initialize",	zpool_do_initialize,	HELP_INITIALIZE		},
288 	{ "resilver",	zpool_do_resilver,	HELP_RESILVER		},
289 	{ "scrub",	zpool_do_scrub,		HELP_SCRUB		},
290 	{ "trim",	zpool_do_trim,		HELP_TRIM		},
291 	{ NULL },
292 	{ "import",	zpool_do_import,	HELP_IMPORT		},
293 	{ "export",	zpool_do_export,	HELP_EXPORT		},
294 	{ "upgrade",	zpool_do_upgrade,	HELP_UPGRADE		},
295 	{ "reguid",	zpool_do_reguid,	HELP_REGUID		},
296 	{ NULL },
297 	{ "history",	zpool_do_history,	HELP_HISTORY		},
298 	{ "get",	zpool_do_get,		HELP_GET		},
299 	{ "set",	zpool_do_set,		HELP_SET		},
300 	{ "sync",	zpool_do_sync,		HELP_SYNC		},
301 };
302 
303 #define	NCOMMAND	(ARRAY_SIZE(command_table))
304 
305 #define	VDEV_ALLOC_CLASS_LOGS	"logs"
306 
307 static zpool_command_t *current_command;
308 static char history_str[HIS_MAX_RECORD_LEN];
309 static boolean_t log_history = B_TRUE;
310 static uint_t timestamp_fmt = NODATE;
311 
312 static const char *
313 get_usage(zpool_help_t idx)
314 {
315 	switch (idx) {
316 	case HELP_ADD:
317 		return (gettext("\tadd [-fgLnP] [-o property=value] "
318 		    "<pool> <vdev> ...\n"));
319 	case HELP_ATTACH:
320 		return (gettext("\tattach [-f] [-o property=value] "
321 		    "<pool> <device> <new-device>\n"));
322 	case HELP_CLEAR:
323 		return (gettext("\tclear [-nF] <pool> [device]\n"));
324 	case HELP_CREATE:
325 		return (gettext("\tcreate [-fnd] [-B] "
326 		    "[-o property=value] ... \n"
327 		    "\t    [-O file-system-property=value] ...\n"
328 		    "\t    [-m mountpoint] [-R root] [-t tempname] "
329 		    "<pool> <vdev> ...\n"));
330 	case HELP_CHECKPOINT:
331 		return (gettext("\tcheckpoint [--discard] <pool> ...\n"));
332 	case HELP_DESTROY:
333 		return (gettext("\tdestroy [-f] <pool>\n"));
334 	case HELP_DETACH:
335 		return (gettext("\tdetach <pool> <device>\n"));
336 	case HELP_EXPORT:
337 		return (gettext("\texport [-f] <pool> ...\n"));
338 	case HELP_HISTORY:
339 		return (gettext("\thistory [-il] [<pool>] ...\n"));
340 	case HELP_IMPORT:
341 		return (gettext("\timport [-d dir] [-D]\n"
342 		    "\timport [-d dir | -c cachefile] [-F [-n]] [-l] "
343 		    "<pool | id>\n"
344 		    "\timport [-o mntopts] [-o property=value] ... \n"
345 		    "\t    [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
346 		    "[-R root] [-F [-n]] -a\n"
347 		    "\timport [-o mntopts] [-o property=value] ... \n"
348 		    "\t    [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
349 		    "[-R root] [-F [-n]] [-t]\n"
350 		    "\t    [--rewind-to-checkpoint] <pool | id> [newpool]\n"));
351 	case HELP_IOSTAT:
352 		return (gettext("\tiostat "
353 		    "[[-lq]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
354 		    "\t    [[pool] ...]|[pool vdev ...]|[vdev ...]]"
355 		    " [[-n] interval [count]]\n"));
356 	case HELP_LABELCLEAR:
357 		return (gettext("\tlabelclear [-f] <vdev>\n"));
358 	case HELP_LIST:
359 		return (gettext("\tlist [-gHLpPv] [-o property[,...]] "
360 		    "[-T d|u] [pool] ... [interval [count]]\n"));
361 	case HELP_OFFLINE:
362 		return (gettext("\toffline [-t] <pool> <device> ...\n"));
363 	case HELP_ONLINE:
364 		return (gettext("\tonline <pool> <device> ...\n"));
365 	case HELP_REPLACE:
366 		return (gettext("\treplace [-f] <pool> <device> "
367 		    "[new-device]\n"));
368 	case HELP_REMOVE:
369 		return (gettext("\tremove [-nps] <pool> <device> ...\n"));
370 	case HELP_REOPEN:
371 		return (gettext("\treopen <pool>\n"));
372 	case HELP_INITIALIZE:
373 		return (gettext("\tinitialize [-c | -s] <pool> "
374 		    "[<device> ...]\n"));
375 	case HELP_SCRUB:
376 		return (gettext("\tscrub [-s | -p] <pool> ...\n"));
377 	case HELP_RESILVER:
378 		return (gettext("\tresilver <pool> ...\n"));
379 	case HELP_TRIM:
380 		return (gettext("\ttrim [-d] [-r <rate>] [-c | -s] <pool> "
381 		    "[<device> ...]\n"));
382 	case HELP_STATUS:
383 		return (gettext("\tstatus "
384 		    "[-igLpPsvxD] [-T d|u] [pool] ... "
385 		    "[interval [count]]\n"));
386 	case HELP_UPGRADE:
387 		return (gettext("\tupgrade\n"
388 		    "\tupgrade -v\n"
389 		    "\tupgrade [-V version] <-a | pool ...>\n"));
390 	case HELP_GET:
391 		return (gettext("\tget [-Hp] [-o \"all\" | field[,...]] "
392 		    "<\"all\" | property[,...]> <pool> ...\n"));
393 	case HELP_SET:
394 		return (gettext("\tset <property=value> <pool> \n"));
395 	case HELP_SPLIT:
396 		return (gettext("\tsplit [-gLlnP] [-R altroot] [-o mntopts]\n"
397 		    "\t    [-o property=value] <pool> <newpool> "
398 		    "[<device> ...]\n"));
399 	case HELP_REGUID:
400 		return (gettext("\treguid <pool>\n"));
401 	case HELP_SYNC:
402 		return (gettext("\tsync [pool] ...\n"));
403 	}
404 
405 	abort();
406 	/* NOTREACHED */
407 }
408 
409 static void
410 zpool_collect_leaves(zpool_handle_t *zhp, nvlist_t *nvroot, nvlist_t *res)
411 {
412 	uint_t children = 0;
413 	nvlist_t **child;
414 	uint_t i;
415 
416 	(void) nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
417 	    &child, &children);
418 
419 	if (children == 0) {
420 		char *path = zpool_vdev_name(g_zfs, zhp, nvroot, 0);
421 
422 		if (strcmp(path, VDEV_TYPE_INDIRECT) != 0)
423 			fnvlist_add_boolean(res, path);
424 
425 		free(path);
426 		return;
427 	}
428 
429 	for (i = 0; i < children; i++) {
430 		zpool_collect_leaves(zhp, child[i], res);
431 	}
432 }
433 
434 /*
435  * Callback routine that will print out a pool property value.
436  */
437 static int
438 print_prop_cb(int prop, void *cb)
439 {
440 	FILE *fp = cb;
441 
442 	(void) fprintf(fp, "\t%-19s  ", zpool_prop_to_name(prop));
443 
444 	if (zpool_prop_readonly(prop))
445 		(void) fprintf(fp, "  NO   ");
446 	else
447 		(void) fprintf(fp, " YES   ");
448 
449 	if (zpool_prop_values(prop) == NULL)
450 		(void) fprintf(fp, "-\n");
451 	else
452 		(void) fprintf(fp, "%s\n", zpool_prop_values(prop));
453 
454 	return (ZPROP_CONT);
455 }
456 
457 /*
458  * Display usage message.  If we're inside a command, display only the usage for
459  * that command.  Otherwise, iterate over the entire command table and display
460  * a complete usage message.
461  */
462 void
463 usage(boolean_t requested)
464 {
465 	FILE *fp = requested ? stdout : stderr;
466 
467 	if (current_command == NULL) {
468 		int i;
469 
470 		(void) fprintf(fp, gettext("usage: zpool command args ...\n"));
471 		(void) fprintf(fp,
472 		    gettext("where 'command' is one of the following:\n\n"));
473 
474 		for (i = 0; i < NCOMMAND; i++) {
475 			if (command_table[i].name == NULL)
476 				(void) fprintf(fp, "\n");
477 			else
478 				(void) fprintf(fp, "%s",
479 				    get_usage(command_table[i].usage));
480 		}
481 	} else {
482 		(void) fprintf(fp, gettext("usage:\n"));
483 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
484 	}
485 
486 	if (current_command != NULL &&
487 	    ((strcmp(current_command->name, "set") == 0) ||
488 	    (strcmp(current_command->name, "get") == 0) ||
489 	    (strcmp(current_command->name, "list") == 0))) {
490 
491 		(void) fprintf(fp,
492 		    gettext("\nthe following properties are supported:\n"));
493 
494 		(void) fprintf(fp, "\n\t%-19s  %s   %s\n\n",
495 		    "PROPERTY", "EDIT", "VALUES");
496 
497 		/* Iterate over all properties */
498 		(void) zprop_iter(print_prop_cb, fp, B_FALSE, B_TRUE,
499 		    ZFS_TYPE_POOL);
500 
501 		(void) fprintf(fp, "\t%-19s   ", "feature@...");
502 		(void) fprintf(fp, "YES   disabled | enabled | active\n");
503 
504 		(void) fprintf(fp, gettext("\nThe feature@ properties must be "
505 		    "appended with a feature name.\nSee zpool-features(5).\n"));
506 	}
507 
508 	/*
509 	 * See comments at end of main().
510 	 */
511 	if (getenv("ZFS_ABORT") != NULL) {
512 		(void) printf("dumping core by request\n");
513 		abort();
514 	}
515 
516 	exit(requested ? 0 : 2);
517 }
518 
519 /*
520  * print a pool vdev config for dry runs
521  */
522 static void
523 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
524     const char *match, int name_flags)
525 {
526 	nvlist_t **child;
527 	uint_t c, children;
528 	char *vname;
529 	boolean_t printed = B_FALSE;
530 
531 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
532 	    &child, &children) != 0) {
533 		if (name != NULL)
534 			(void) printf("\t%*s%s\n", indent, "", name);
535 		return;
536 	}
537 
538 	for (c = 0; c < children; c++) {
539 		uint64_t is_log = B_FALSE;
540 		char *class = "";
541 
542 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
543 		    &is_log);
544 		if (is_log)
545 			class = VDEV_ALLOC_BIAS_LOG;
546 		(void) nvlist_lookup_string(child[c],
547 		    ZPOOL_CONFIG_ALLOCATION_BIAS, &class);
548 		if (strcmp(match, class) != 0)
549 			continue;
550 
551 		if (!printed && name != NULL) {
552 			(void) printf("\t%*s%s\n", indent, "", name);
553 			printed = B_TRUE;
554 		}
555 		vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
556 		print_vdev_tree(zhp, vname, child[c], indent + 2, "",
557 		    name_flags);
558 		free(vname);
559 	}
560 }
561 
562 static boolean_t
563 prop_list_contains_feature(nvlist_t *proplist)
564 {
565 	nvpair_t *nvp;
566 	for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
567 	    nvp = nvlist_next_nvpair(proplist, nvp)) {
568 		if (zpool_prop_feature(nvpair_name(nvp)))
569 			return (B_TRUE);
570 	}
571 	return (B_FALSE);
572 }
573 
574 /*
575  * Add a property pair (name, string-value) into a property nvlist.
576  */
577 static int
578 add_prop_list(const char *propname, char *propval, nvlist_t **props,
579     boolean_t poolprop)
580 {
581 	zpool_prop_t prop = ZPOOL_PROP_INVAL;
582 	zfs_prop_t fprop;
583 	nvlist_t *proplist;
584 	const char *normnm;
585 	char *strval;
586 
587 	if (*props == NULL &&
588 	    nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
589 		(void) fprintf(stderr,
590 		    gettext("internal error: out of memory\n"));
591 		return (1);
592 	}
593 
594 	proplist = *props;
595 
596 	if (poolprop) {
597 		const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
598 
599 		if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
600 		    !zpool_prop_feature(propname)) {
601 			(void) fprintf(stderr, gettext("property '%s' is "
602 			    "not a valid pool property\n"), propname);
603 			return (2);
604 		}
605 
606 		/*
607 		 * feature@ properties and version should not be specified
608 		 * at the same time.
609 		 */
610 		if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
611 		    nvlist_exists(proplist, vname)) ||
612 		    (prop == ZPOOL_PROP_VERSION &&
613 		    prop_list_contains_feature(proplist))) {
614 			(void) fprintf(stderr, gettext("'feature@' and "
615 			    "'version' properties cannot be specified "
616 			    "together\n"));
617 			return (2);
618 		}
619 
620 
621 		if (zpool_prop_feature(propname))
622 			normnm = propname;
623 		else
624 			normnm = zpool_prop_to_name(prop);
625 	} else {
626 		if ((fprop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
627 			normnm = zfs_prop_to_name(fprop);
628 		} else {
629 			normnm = propname;
630 		}
631 	}
632 
633 	if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
634 	    prop != ZPOOL_PROP_CACHEFILE) {
635 		(void) fprintf(stderr, gettext("property '%s' "
636 		    "specified multiple times\n"), propname);
637 		return (2);
638 	}
639 
640 	if (nvlist_add_string(proplist, normnm, propval) != 0) {
641 		(void) fprintf(stderr, gettext("internal "
642 		    "error: out of memory\n"));
643 		return (1);
644 	}
645 
646 	return (0);
647 }
648 
649 /*
650  * Set a default property pair (name, string-value) in a property nvlist
651  */
652 static int
653 add_prop_list_default(const char *propname, char *propval, nvlist_t **props,
654     boolean_t poolprop)
655 {
656 	char *pval;
657 
658 	if (nvlist_lookup_string(*props, propname, &pval) == 0)
659 		return (0);
660 
661 	return (add_prop_list(propname, propval, props, poolprop));
662 }
663 
664 /*
665  * zpool add [-fgLnP] [-o property=value] <pool> <vdev> ...
666  *
667  *	-f	Force addition of devices, even if they appear in use
668  *	-g	Display guid for individual vdev name.
669  *	-L	Follow links when resolving vdev path name.
670  *	-n	Do not add the devices, but display the resulting layout if
671  *		they were to be added.
672  *	-P	Display full path for vdev name.
673  *	-o	Set property=value.
674  *
675  * Adds the given vdevs to 'pool'.  As with create, the bulk of this work is
676  * handled by get_vdev_spec(), which constructs the nvlist needed to pass to
677  * libzfs.
678  */
679 int
680 zpool_do_add(int argc, char **argv)
681 {
682 	boolean_t force = B_FALSE;
683 	boolean_t dryrun = B_FALSE;
684 	int name_flags = 0;
685 	int c;
686 	nvlist_t *nvroot;
687 	char *poolname;
688 	zpool_boot_label_t boot_type;
689 	uint64_t boot_size;
690 	int ret;
691 	zpool_handle_t *zhp;
692 	nvlist_t *config;
693 	nvlist_t *props = NULL;
694 	char *propval;
695 
696 	/* check options */
697 	while ((c = getopt(argc, argv, "fgLnPo:")) != -1) {
698 		switch (c) {
699 		case 'f':
700 			force = B_TRUE;
701 			break;
702 		case 'g':
703 			name_flags |= VDEV_NAME_GUID;
704 			break;
705 		case 'L':
706 			name_flags |= VDEV_NAME_FOLLOW_LINKS;
707 			break;
708 		case 'n':
709 			dryrun = B_TRUE;
710 			break;
711 		case 'P':
712 			name_flags |= VDEV_NAME_PATH;
713 			break;
714 		case 'o':
715 			if ((propval = strchr(optarg, '=')) == NULL) {
716 				(void) fprintf(stderr, gettext("missing "
717 				    "'=' for -o option\n"));
718 				usage(B_FALSE);
719 			}
720 			*propval = '\0';
721 			propval++;
722 
723 			if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
724 			    (add_prop_list(optarg, propval, &props, B_TRUE)))
725 				usage(B_FALSE);
726 			break;
727 		case '?':
728 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
729 			    optopt);
730 			usage(B_FALSE);
731 		}
732 	}
733 
734 	argc -= optind;
735 	argv += optind;
736 
737 	/* get pool name and check number of arguments */
738 	if (argc < 1) {
739 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
740 		usage(B_FALSE);
741 	}
742 	if (argc < 2) {
743 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
744 		usage(B_FALSE);
745 	}
746 
747 	poolname = argv[0];
748 
749 	argc--;
750 	argv++;
751 
752 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
753 		return (1);
754 
755 	if ((config = zpool_get_config(zhp, NULL)) == NULL) {
756 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
757 		    poolname);
758 		zpool_close(zhp);
759 		return (1);
760 	}
761 
762 	if (zpool_is_bootable(zhp))
763 		boot_type = ZPOOL_COPY_BOOT_LABEL;
764 	else
765 		boot_type = ZPOOL_NO_BOOT_LABEL;
766 
767 	/* unless manually specified use "ashift" pool property (if set) */
768 	if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
769 		int intval;
770 		zprop_source_t src;
771 		char strval[ZPOOL_MAXPROPLEN];
772 
773 		intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
774 		if (src != ZPROP_SRC_DEFAULT) {
775 			(void) sprintf(strval, "%" PRId32, intval);
776 			verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
777 			    &props, B_TRUE) == 0);
778 		}
779 	}
780 
781 	/* pass off to get_vdev_spec for processing */
782 	boot_size = zpool_get_prop_int(zhp, ZPOOL_PROP_BOOTSIZE, NULL);
783 	nvroot = make_root_vdev(zhp, props, force, !force, B_FALSE, dryrun,
784 	    boot_type, boot_size, argc, argv);
785 	if (nvroot == NULL) {
786 		zpool_close(zhp);
787 		return (1);
788 	}
789 
790 	if (dryrun) {
791 		nvlist_t *poolnvroot;
792 
793 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
794 		    &poolnvroot) == 0);
795 
796 		(void) printf(gettext("would update '%s' to the following "
797 		    "configuration:\n"), zpool_get_name(zhp));
798 
799 		/* print original main pool and new tree */
800 		print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
801 		    name_flags | VDEV_NAME_TYPE_ID);
802 		print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
803 
804 		/* print other classes: 'dedup', 'special', and 'log' */
805 		print_vdev_tree(zhp, "dedup", poolnvroot, 0,
806 		    VDEV_ALLOC_BIAS_DEDUP, name_flags);
807 		print_vdev_tree(zhp, NULL, nvroot, 0, VDEV_ALLOC_BIAS_DEDUP,
808 		    name_flags);
809 
810 		print_vdev_tree(zhp, "special", poolnvroot, 0,
811 		    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
812 		print_vdev_tree(zhp, NULL, nvroot, 0, VDEV_ALLOC_BIAS_SPECIAL,
813 		    name_flags);
814 
815 		print_vdev_tree(zhp, "logs", poolnvroot, 0, VDEV_ALLOC_BIAS_LOG,
816 		    name_flags);
817 		print_vdev_tree(zhp, NULL, nvroot, 0, VDEV_ALLOC_BIAS_LOG,
818 		    name_flags);
819 
820 		ret = 0;
821 	} else {
822 		ret = (zpool_add(zhp, nvroot) != 0);
823 	}
824 
825 	nvlist_free(props);
826 	nvlist_free(nvroot);
827 	zpool_close(zhp);
828 
829 	return (ret);
830 }
831 
832 /*
833  * zpool remove  <pool> <vdev> ...
834  *
835  * Removes the given vdev from the pool.
836  */
837 int
838 zpool_do_remove(int argc, char **argv)
839 {
840 	char *poolname;
841 	int i, ret = 0;
842 	zpool_handle_t *zhp;
843 	boolean_t stop = B_FALSE;
844 	boolean_t noop = B_FALSE;
845 	boolean_t parsable = B_FALSE;
846 	char c;
847 
848 	/* check options */
849 	while ((c = getopt(argc, argv, "nps")) != -1) {
850 		switch (c) {
851 		case 'n':
852 			noop = B_TRUE;
853 			break;
854 		case 'p':
855 			parsable = B_TRUE;
856 			break;
857 		case 's':
858 			stop = B_TRUE;
859 			break;
860 		case '?':
861 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
862 			    optopt);
863 			usage(B_FALSE);
864 		}
865 	}
866 
867 	argc -= optind;
868 	argv += optind;
869 
870 	/* get pool name and check number of arguments */
871 	if (argc < 1) {
872 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
873 		usage(B_FALSE);
874 	}
875 
876 	poolname = argv[0];
877 
878 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
879 		return (1);
880 
881 	if (stop && noop) {
882 		(void) fprintf(stderr, gettext("stop request ignored\n"));
883 		return (0);
884 	}
885 
886 	if (stop) {
887 		if (argc > 1) {
888 			(void) fprintf(stderr, gettext("too many arguments\n"));
889 			usage(B_FALSE);
890 		}
891 		if (zpool_vdev_remove_cancel(zhp) != 0)
892 			ret = 1;
893 	} else {
894 		if (argc < 2) {
895 			(void) fprintf(stderr, gettext("missing device\n"));
896 			usage(B_FALSE);
897 		}
898 
899 		for (i = 1; i < argc; i++) {
900 			if (noop) {
901 				uint64_t size;
902 
903 				if (zpool_vdev_indirect_size(zhp, argv[i],
904 				    &size) != 0) {
905 					ret = 1;
906 					break;
907 				}
908 				if (parsable) {
909 					(void) printf("%s %llu\n",
910 					    argv[i], size);
911 				} else {
912 					char valstr[32];
913 					zfs_nicenum(size, valstr,
914 					    sizeof (valstr));
915 					(void) printf("Memory that will be "
916 					    "used after removing %s: %s\n",
917 					    argv[i], valstr);
918 				}
919 			} else {
920 				if (zpool_vdev_remove(zhp, argv[i]) != 0)
921 					ret = 1;
922 			}
923 		}
924 	}
925 
926 	return (ret);
927 }
928 
929 /*
930  * zpool labelclear [-f] <vdev>
931  *
932  *	-f	Force clearing the label for the vdevs which are members of
933  *		the exported or foreign pools.
934  *
935  * Verifies that the vdev is not active and zeros out the label information
936  * on the device.
937  */
938 int
939 zpool_do_labelclear(int argc, char **argv)
940 {
941 	char vdev[MAXPATHLEN];
942 	char *name = NULL;
943 	struct stat st;
944 	int c, fd, ret = 0;
945 	nvlist_t *config;
946 	pool_state_t state;
947 	boolean_t inuse = B_FALSE;
948 	boolean_t force = B_FALSE;
949 
950 	/* check options */
951 	while ((c = getopt(argc, argv, "f")) != -1) {
952 		switch (c) {
953 		case 'f':
954 			force = B_TRUE;
955 			break;
956 		default:
957 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
958 			    optopt);
959 			usage(B_FALSE);
960 		}
961 	}
962 
963 	argc -= optind;
964 	argv += optind;
965 
966 	/* get vdev name */
967 	if (argc < 1) {
968 		(void) fprintf(stderr, gettext("missing vdev name\n"));
969 		usage(B_FALSE);
970 	}
971 	if (argc > 1) {
972 		(void) fprintf(stderr, gettext("too many arguments\n"));
973 		usage(B_FALSE);
974 	}
975 
976 	/*
977 	 * Check if we were given absolute path and use it as is.
978 	 * Otherwise if the provided vdev name doesn't point to a file,
979 	 * try prepending dsk path and appending s0.
980 	 */
981 	(void) strlcpy(vdev, argv[0], sizeof (vdev));
982 	if (vdev[0] != '/' && stat(vdev, &st) != 0) {
983 		char *s;
984 
985 		(void) snprintf(vdev, sizeof (vdev), "%s/%s",
986 		    ZFS_DISK_ROOT, argv[0]);
987 		if ((s = strrchr(argv[0], 's')) == NULL ||
988 		    !isdigit(*(s + 1)))
989 			(void) strlcat(vdev, "s0", sizeof (vdev));
990 		if (stat(vdev, &st) != 0) {
991 			(void) fprintf(stderr, gettext(
992 			    "failed to find device %s, try specifying absolute "
993 			    "path instead\n"), argv[0]);
994 			return (1);
995 		}
996 	}
997 
998 	if ((fd = open(vdev, O_RDWR)) < 0) {
999 		(void) fprintf(stderr, gettext("failed to open %s: %s\n"),
1000 		    vdev, strerror(errno));
1001 		return (1);
1002 	}
1003 
1004 	if (zpool_read_label(fd, &config, NULL) != 0) {
1005 		(void) fprintf(stderr,
1006 		    gettext("failed to read label from %s\n"), vdev);
1007 		return (1);
1008 	}
1009 	nvlist_free(config);
1010 
1011 	ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1012 	if (ret != 0) {
1013 		(void) fprintf(stderr,
1014 		    gettext("failed to check state for %s\n"), vdev);
1015 		return (1);
1016 	}
1017 
1018 	if (!inuse)
1019 		goto wipe_label;
1020 
1021 	switch (state) {
1022 	default:
1023 	case POOL_STATE_ACTIVE:
1024 	case POOL_STATE_SPARE:
1025 	case POOL_STATE_L2CACHE:
1026 		(void) fprintf(stderr, gettext(
1027 		    "%s is a member (%s) of pool \"%s\"\n"),
1028 		    vdev, zpool_pool_state_to_name(state), name);
1029 		ret = 1;
1030 		goto errout;
1031 
1032 	case POOL_STATE_EXPORTED:
1033 		if (force)
1034 			break;
1035 		(void) fprintf(stderr, gettext(
1036 		    "use '-f' to override the following error:\n"
1037 		    "%s is a member of exported pool \"%s\"\n"),
1038 		    vdev, name);
1039 		ret = 1;
1040 		goto errout;
1041 
1042 	case POOL_STATE_POTENTIALLY_ACTIVE:
1043 		if (force)
1044 			break;
1045 		(void) fprintf(stderr, gettext(
1046 		    "use '-f' to override the following error:\n"
1047 		    "%s is a member of potentially active pool \"%s\"\n"),
1048 		    vdev, name);
1049 		ret = 1;
1050 		goto errout;
1051 
1052 	case POOL_STATE_DESTROYED:
1053 		/* inuse should never be set for a destroyed pool */
1054 		assert(0);
1055 		break;
1056 	}
1057 
1058 wipe_label:
1059 	ret = zpool_clear_label(fd);
1060 	if (ret != 0) {
1061 		(void) fprintf(stderr,
1062 		    gettext("failed to clear label for %s\n"), vdev);
1063 	}
1064 
1065 errout:
1066 	free(name);
1067 	(void) close(fd);
1068 
1069 	return (ret);
1070 }
1071 
1072 /*
1073  * zpool create [-fnd] [-B] [-o property=value] ...
1074  *		[-O file-system-property=value] ...
1075  *		[-R root] [-m mountpoint] [-t tempname] <pool> <dev> ...
1076  *
1077  *	-B	Create boot partition.
1078  *	-f	Force creation, even if devices appear in use
1079  *	-n	Do not create the pool, but display the resulting layout if it
1080  *		were to be created.
1081  *	-R	Create a pool under an alternate root
1082  *	-m	Set default mountpoint for the root dataset.  By default it's
1083  *		'/<pool>'
1084  *	-t	Use the temporary name until the pool is exported.
1085  *	-o	Set property=value.
1086  *	-o	Set feature@feature=enabled|disabled.
1087  *	-d	Don't automatically enable all supported pool features
1088  *		(individual features can be enabled with -o).
1089  *	-O	Set fsproperty=value in the pool's root file system
1090  *
1091  * Creates the named pool according to the given vdev specification.  The
1092  * bulk of the vdev processing is done in get_vdev_spec() in zpool_vdev.c.  Once
1093  * we get the nvlist back from get_vdev_spec(), we either print out the contents
1094  * (if '-n' was specified), or pass it to libzfs to do the creation.
1095  */
1096 
1097 #define	SYSTEM256	(256 * 1024 * 1024)
1098 int
1099 zpool_do_create(int argc, char **argv)
1100 {
1101 	boolean_t force = B_FALSE;
1102 	boolean_t dryrun = B_FALSE;
1103 	boolean_t enable_all_pool_feat = B_TRUE;
1104 	zpool_boot_label_t boot_type = ZPOOL_NO_BOOT_LABEL;
1105 	uint64_t boot_size = 0;
1106 	int c;
1107 	nvlist_t *nvroot = NULL;
1108 	char *poolname;
1109 	char *tname = NULL;
1110 	int ret = 1;
1111 	char *altroot = NULL;
1112 	char *mountpoint = NULL;
1113 	nvlist_t *fsprops = NULL;
1114 	nvlist_t *props = NULL;
1115 	char *propval;
1116 
1117 	/* check options */
1118 	while ((c = getopt(argc, argv, ":fndBR:m:o:O:t:")) != -1) {
1119 		switch (c) {
1120 		case 'f':
1121 			force = B_TRUE;
1122 			break;
1123 		case 'n':
1124 			dryrun = B_TRUE;
1125 			break;
1126 		case 'd':
1127 			enable_all_pool_feat = B_FALSE;
1128 			break;
1129 		case 'B':
1130 			/*
1131 			 * We should create the system partition.
1132 			 * Also make sure the size is set.
1133 			 */
1134 			boot_type = ZPOOL_CREATE_BOOT_LABEL;
1135 			if (boot_size == 0)
1136 				boot_size = SYSTEM256;
1137 			break;
1138 		case 'R':
1139 			altroot = optarg;
1140 			if (add_prop_list(zpool_prop_to_name(
1141 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
1142 				goto errout;
1143 			if (add_prop_list_default(zpool_prop_to_name(
1144 			    ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1145 				goto errout;
1146 			break;
1147 		case 'm':
1148 			/* Equivalent to -O mountpoint=optarg */
1149 			mountpoint = optarg;
1150 			break;
1151 		case 'o':
1152 			if ((propval = strchr(optarg, '=')) == NULL) {
1153 				(void) fprintf(stderr, gettext("missing "
1154 				    "'=' for -o option\n"));
1155 				goto errout;
1156 			}
1157 			*propval = '\0';
1158 			propval++;
1159 
1160 			if (add_prop_list(optarg, propval, &props, B_TRUE))
1161 				goto errout;
1162 
1163 			/*
1164 			 * Get bootsize value for make_root_vdev().
1165 			 */
1166 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_BOOTSIZE) {
1167 				if (zfs_nicestrtonum(g_zfs, propval,
1168 				    &boot_size) < 0 || boot_size == 0) {
1169 					(void) fprintf(stderr,
1170 					    gettext("bad boot partition size "
1171 					    "'%s': %s\n"),  propval,
1172 					    libzfs_error_description(g_zfs));
1173 					goto errout;
1174 				}
1175 			}
1176 
1177 			/*
1178 			 * If the user is creating a pool that doesn't support
1179 			 * feature flags, don't enable any features.
1180 			 */
1181 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
1182 				char *end;
1183 				u_longlong_t ver;
1184 
1185 				ver = strtoull(propval, &end, 10);
1186 				if (*end == '\0' &&
1187 				    ver < SPA_VERSION_FEATURES) {
1188 					enable_all_pool_feat = B_FALSE;
1189 				}
1190 			}
1191 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
1192 				altroot = propval;
1193 			break;
1194 		case 'O':
1195 			if ((propval = strchr(optarg, '=')) == NULL) {
1196 				(void) fprintf(stderr, gettext("missing "
1197 				    "'=' for -O option\n"));
1198 				goto errout;
1199 			}
1200 			*propval = '\0';
1201 			propval++;
1202 
1203 			/*
1204 			 * Mountpoints are checked and then added later.
1205 			 * Uniquely among properties, they can be specified
1206 			 * more than once, to avoid conflict with -m.
1207 			 */
1208 			if (0 == strcmp(optarg,
1209 			    zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
1210 				mountpoint = propval;
1211 			} else if (add_prop_list(optarg, propval, &fsprops,
1212 			    B_FALSE)) {
1213 				goto errout;
1214 			}
1215 			break;
1216 		case 't':
1217 			/*
1218 			 * Sanity check temporary pool name.
1219 			 */
1220 			if (strchr(optarg, '/') != NULL) {
1221 				(void) fprintf(stderr, gettext("cannot create "
1222 				    "'%s': invalid character '/' in temporary "
1223 				    "name\n"), optarg);
1224 				(void) fprintf(stderr, gettext("use 'zfs "
1225 				    "create' to create a dataset\n"));
1226 				goto errout;
1227 			}
1228 
1229 			if (add_prop_list(zpool_prop_to_name(
1230 			    ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
1231 				goto errout;
1232 			if (add_prop_list_default(zpool_prop_to_name(
1233 			    ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1234 				goto errout;
1235 			tname = optarg;
1236 			break;
1237 		case ':':
1238 			(void) fprintf(stderr, gettext("missing argument for "
1239 			    "'%c' option\n"), optopt);
1240 			goto badusage;
1241 		case '?':
1242 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1243 			    optopt);
1244 			goto badusage;
1245 		}
1246 	}
1247 
1248 	argc -= optind;
1249 	argv += optind;
1250 
1251 	/* get pool name and check number of arguments */
1252 	if (argc < 1) {
1253 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
1254 		goto badusage;
1255 	}
1256 	if (argc < 2) {
1257 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
1258 		goto badusage;
1259 	}
1260 
1261 	poolname = argv[0];
1262 
1263 	/*
1264 	 * As a special case, check for use of '/' in the name, and direct the
1265 	 * user to use 'zfs create' instead.
1266 	 */
1267 	if (strchr(poolname, '/') != NULL) {
1268 		(void) fprintf(stderr, gettext("cannot create '%s': invalid "
1269 		    "character '/' in pool name\n"), poolname);
1270 		(void) fprintf(stderr, gettext("use 'zfs create' to "
1271 		    "create a dataset\n"));
1272 		goto errout;
1273 	}
1274 
1275 	/*
1276 	 * Make sure the bootsize is set when ZPOOL_CREATE_BOOT_LABEL is used,
1277 	 * and not set otherwise.
1278 	 */
1279 	if (boot_type == ZPOOL_CREATE_BOOT_LABEL) {
1280 		const char *propname;
1281 		char *strptr, *buf = NULL;
1282 		int rv;
1283 
1284 		propname = zpool_prop_to_name(ZPOOL_PROP_BOOTSIZE);
1285 		if (nvlist_lookup_string(props, propname, &strptr) != 0) {
1286 			(void) asprintf(&buf, "%" PRIu64, boot_size);
1287 			if (buf == NULL) {
1288 				(void) fprintf(stderr,
1289 				    gettext("internal error: out of memory\n"));
1290 				goto errout;
1291 			}
1292 			rv = add_prop_list(propname, buf, &props, B_TRUE);
1293 			free(buf);
1294 			if (rv != 0)
1295 				goto errout;
1296 		}
1297 	} else {
1298 		const char *propname;
1299 		char *strptr;
1300 
1301 		propname = zpool_prop_to_name(ZPOOL_PROP_BOOTSIZE);
1302 		if (nvlist_lookup_string(props, propname, &strptr) == 0) {
1303 			(void) fprintf(stderr, gettext("error: setting boot "
1304 			    "partition size requires option '-B'\n"));
1305 			goto errout;
1306 		}
1307 	}
1308 
1309 	/* pass off to get_vdev_spec for bulk processing */
1310 	nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
1311 	    boot_type, boot_size, argc - 1, argv + 1);
1312 	if (nvroot == NULL)
1313 		goto errout;
1314 
1315 	/* make_root_vdev() allows 0 toplevel children if there are spares */
1316 	if (!zfs_allocatable_devs(nvroot)) {
1317 		(void) fprintf(stderr, gettext("invalid vdev "
1318 		    "specification: at least one toplevel vdev must be "
1319 		    "specified\n"));
1320 		goto errout;
1321 	}
1322 
1323 	if (altroot != NULL && altroot[0] != '/') {
1324 		(void) fprintf(stderr, gettext("invalid alternate root '%s': "
1325 		    "must be an absolute path\n"), altroot);
1326 		goto errout;
1327 	}
1328 
1329 	/*
1330 	 * Check the validity of the mountpoint and direct the user to use the
1331 	 * '-m' mountpoint option if it looks like its in use.
1332 	 */
1333 	if (mountpoint == NULL ||
1334 	    (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
1335 	    strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
1336 		char buf[MAXPATHLEN];
1337 		DIR *dirp;
1338 
1339 		if (mountpoint && mountpoint[0] != '/') {
1340 			(void) fprintf(stderr, gettext("invalid mountpoint "
1341 			    "'%s': must be an absolute path, 'legacy', or "
1342 			    "'none'\n"), mountpoint);
1343 			goto errout;
1344 		}
1345 
1346 		if (mountpoint == NULL) {
1347 			if (altroot != NULL)
1348 				(void) snprintf(buf, sizeof (buf), "%s/%s",
1349 				    altroot, poolname);
1350 			else
1351 				(void) snprintf(buf, sizeof (buf), "/%s",
1352 				    poolname);
1353 		} else {
1354 			if (altroot != NULL)
1355 				(void) snprintf(buf, sizeof (buf), "%s%s",
1356 				    altroot, mountpoint);
1357 			else
1358 				(void) snprintf(buf, sizeof (buf), "%s",
1359 				    mountpoint);
1360 		}
1361 
1362 		if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
1363 			(void) fprintf(stderr, gettext("mountpoint '%s' : "
1364 			    "%s\n"), buf, strerror(errno));
1365 			(void) fprintf(stderr, gettext("use '-m' "
1366 			    "option to provide a different default\n"));
1367 			goto errout;
1368 		} else if (dirp) {
1369 			int count = 0;
1370 
1371 			while (count < 3 && readdir(dirp) != NULL)
1372 				count++;
1373 			(void) closedir(dirp);
1374 
1375 			if (count > 2) {
1376 				(void) fprintf(stderr, gettext("mountpoint "
1377 				    "'%s' exists and is not empty\n"), buf);
1378 				(void) fprintf(stderr, gettext("use '-m' "
1379 				    "option to provide a "
1380 				    "different default\n"));
1381 				goto errout;
1382 			}
1383 		}
1384 	}
1385 
1386 	/*
1387 	 * Now that the mountpoint's validity has been checked, ensure that
1388 	 * the property is set appropriately prior to creating the pool.
1389 	 */
1390 	if (mountpoint != NULL) {
1391 		ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
1392 		    mountpoint, &fsprops, B_FALSE);
1393 		if (ret != 0)
1394 			goto errout;
1395 	}
1396 
1397 	ret = 1;
1398 	if (dryrun) {
1399 		/*
1400 		 * For a dry run invocation, print out a basic message and run
1401 		 * through all the vdevs in the list and print out in an
1402 		 * appropriate hierarchy.
1403 		 */
1404 		(void) printf(gettext("would create '%s' with the "
1405 		    "following layout:\n\n"), poolname);
1406 
1407 		print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
1408 		print_vdev_tree(NULL, "dedup", nvroot, 0,
1409 		    VDEV_ALLOC_BIAS_DEDUP, 0);
1410 		print_vdev_tree(NULL, "special", nvroot, 0,
1411 		    VDEV_ALLOC_BIAS_SPECIAL, 0);
1412 		print_vdev_tree(NULL, "logs", nvroot, 0,
1413 		    VDEV_ALLOC_BIAS_LOG, 0);
1414 
1415 		ret = 0;
1416 	} else {
1417 		/*
1418 		 * Hand off to libzfs.
1419 		 */
1420 
1421 		spa_feature_t i;
1422 		for (i = 0; i < SPA_FEATURES; i++) {
1423 			char propname[MAXPATHLEN];
1424 			char *propval;
1425 			zfeature_info_t *feat = &spa_feature_table[i];
1426 			(void) snprintf(propname, sizeof (propname),
1427 			    "feature@%s", feat->fi_uname);
1428 
1429 			/*
1430 			 * Only features contained in props will be enabled:
1431 			 * remove from the nvlist every ZFS_FEATURE_DISABLED
1432 			 * value and add every missing ZFS_FEATURE_ENABLED if
1433 			 * enable_all_pool_feat is set.
1434 			 */
1435 			if (!nvlist_lookup_string(props, propname, &propval)) {
1436 				if (strcmp(propval, ZFS_FEATURE_DISABLED) == 0)
1437 					(void) nvlist_remove_all(props,
1438 					    propname);
1439 			} else if (enable_all_pool_feat) {
1440 				ret = add_prop_list(propname,
1441 				    ZFS_FEATURE_ENABLED, &props, B_TRUE);
1442 				if (ret != 0)
1443 					goto errout;
1444 			}
1445 		}
1446 
1447 		ret = 1;
1448 		if (zpool_create(g_zfs, poolname,
1449 		    nvroot, props, fsprops) == 0) {
1450 			zfs_handle_t *pool = zfs_open(g_zfs,
1451 			    tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
1452 			if (pool != NULL) {
1453 				if (zfs_mount(pool, NULL, 0) == 0)
1454 					ret = zfs_shareall(pool);
1455 				zfs_close(pool);
1456 			}
1457 		} else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
1458 			(void) fprintf(stderr, gettext("pool name may have "
1459 			    "been omitted\n"));
1460 		}
1461 	}
1462 
1463 errout:
1464 	nvlist_free(nvroot);
1465 	nvlist_free(fsprops);
1466 	nvlist_free(props);
1467 	return (ret);
1468 badusage:
1469 	nvlist_free(fsprops);
1470 	nvlist_free(props);
1471 	usage(B_FALSE);
1472 	return (2);
1473 }
1474 
1475 /*
1476  * zpool destroy <pool>
1477  *
1478  *	-f	Forcefully unmount any datasets
1479  *
1480  * Destroy the given pool.  Automatically unmounts any datasets in the pool.
1481  */
1482 int
1483 zpool_do_destroy(int argc, char **argv)
1484 {
1485 	boolean_t force = B_FALSE;
1486 	int c;
1487 	char *pool;
1488 	zpool_handle_t *zhp;
1489 	int ret;
1490 
1491 	/* check options */
1492 	while ((c = getopt(argc, argv, "f")) != -1) {
1493 		switch (c) {
1494 		case 'f':
1495 			force = B_TRUE;
1496 			break;
1497 		case '?':
1498 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1499 			    optopt);
1500 			usage(B_FALSE);
1501 		}
1502 	}
1503 
1504 	argc -= optind;
1505 	argv += optind;
1506 
1507 	/* check arguments */
1508 	if (argc < 1) {
1509 		(void) fprintf(stderr, gettext("missing pool argument\n"));
1510 		usage(B_FALSE);
1511 	}
1512 	if (argc > 1) {
1513 		(void) fprintf(stderr, gettext("too many arguments\n"));
1514 		usage(B_FALSE);
1515 	}
1516 
1517 	pool = argv[0];
1518 
1519 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
1520 		/*
1521 		 * As a special case, check for use of '/' in the name, and
1522 		 * direct the user to use 'zfs destroy' instead.
1523 		 */
1524 		if (strchr(pool, '/') != NULL)
1525 			(void) fprintf(stderr, gettext("use 'zfs destroy' to "
1526 			    "destroy a dataset\n"));
1527 		return (1);
1528 	}
1529 
1530 	if (zpool_disable_datasets(zhp, force) != 0) {
1531 		(void) fprintf(stderr, gettext("could not destroy '%s': "
1532 		    "could not unmount datasets\n"), zpool_get_name(zhp));
1533 		return (1);
1534 	}
1535 
1536 	/* The history must be logged as part of the export */
1537 	log_history = B_FALSE;
1538 
1539 	ret = (zpool_destroy(zhp, history_str) != 0);
1540 
1541 	zpool_close(zhp);
1542 
1543 	return (ret);
1544 }
1545 
1546 /*
1547  * zpool export [-f] <pool> ...
1548  *
1549  *	-f	Forcefully unmount datasets
1550  *
1551  * Export the given pools.  By default, the command will attempt to cleanly
1552  * unmount any active datasets within the pool.  If the '-f' flag is specified,
1553  * then the datasets will be forcefully unmounted.
1554  */
1555 int
1556 zpool_do_export(int argc, char **argv)
1557 {
1558 	boolean_t force = B_FALSE;
1559 	boolean_t hardforce = B_FALSE;
1560 	int c;
1561 	zpool_handle_t *zhp;
1562 	int ret;
1563 	int i;
1564 
1565 	/* check options */
1566 	while ((c = getopt(argc, argv, "fF")) != -1) {
1567 		switch (c) {
1568 		case 'f':
1569 			force = B_TRUE;
1570 			break;
1571 		case 'F':
1572 			hardforce = B_TRUE;
1573 			break;
1574 		case '?':
1575 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1576 			    optopt);
1577 			usage(B_FALSE);
1578 		}
1579 	}
1580 
1581 	argc -= optind;
1582 	argv += optind;
1583 
1584 	/* check arguments */
1585 	if (argc < 1) {
1586 		(void) fprintf(stderr, gettext("missing pool argument\n"));
1587 		usage(B_FALSE);
1588 	}
1589 
1590 	ret = 0;
1591 	for (i = 0; i < argc; i++) {
1592 		if ((zhp = zpool_open_canfail(g_zfs, argv[i])) == NULL) {
1593 			ret = 1;
1594 			continue;
1595 		}
1596 
1597 		if (zpool_disable_datasets(zhp, force) != 0) {
1598 			ret = 1;
1599 			zpool_close(zhp);
1600 			continue;
1601 		}
1602 
1603 		/* The history must be logged as part of the export */
1604 		log_history = B_FALSE;
1605 
1606 		if (hardforce) {
1607 			if (zpool_export_force(zhp, history_str) != 0)
1608 				ret = 1;
1609 		} else if (zpool_export(zhp, force, history_str) != 0) {
1610 			ret = 1;
1611 		}
1612 
1613 		zpool_close(zhp);
1614 	}
1615 
1616 	return (ret);
1617 }
1618 
1619 /*
1620  * Given a vdev configuration, determine the maximum width needed for the device
1621  * name column.
1622  */
1623 static int
1624 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
1625     int name_flags)
1626 {
1627 	char *name;
1628 	nvlist_t **child;
1629 	uint_t c, children;
1630 	int ret;
1631 
1632 	name = zpool_vdev_name(g_zfs, zhp, nv, name_flags | VDEV_NAME_TYPE_ID);
1633 	if (strlen(name) + depth > max)
1634 		max = strlen(name) + depth;
1635 
1636 	free(name);
1637 
1638 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1639 	    &child, &children) == 0) {
1640 		for (c = 0; c < children; c++)
1641 			if ((ret = max_width(zhp, child[c], depth + 2,
1642 			    max, name_flags)) > max)
1643 				max = ret;
1644 	}
1645 
1646 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1647 	    &child, &children) == 0) {
1648 		for (c = 0; c < children; c++)
1649 			if ((ret = max_width(zhp, child[c], depth + 2,
1650 			    max, name_flags)) > max)
1651 				max = ret;
1652 	}
1653 
1654 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1655 	    &child, &children) == 0) {
1656 		for (c = 0; c < children; c++)
1657 			if ((ret = max_width(zhp, child[c], depth + 2,
1658 			    max, name_flags)) > max)
1659 				max = ret;
1660 	}
1661 
1662 	return (max);
1663 }
1664 
1665 typedef struct spare_cbdata {
1666 	uint64_t	cb_guid;
1667 	zpool_handle_t	*cb_zhp;
1668 } spare_cbdata_t;
1669 
1670 static boolean_t
1671 find_vdev(nvlist_t *nv, uint64_t search)
1672 {
1673 	uint64_t guid;
1674 	nvlist_t **child;
1675 	uint_t c, children;
1676 
1677 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1678 	    search == guid)
1679 		return (B_TRUE);
1680 
1681 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1682 	    &child, &children) == 0) {
1683 		for (c = 0; c < children; c++)
1684 			if (find_vdev(child[c], search))
1685 				return (B_TRUE);
1686 	}
1687 
1688 	return (B_FALSE);
1689 }
1690 
1691 static int
1692 find_spare(zpool_handle_t *zhp, void *data)
1693 {
1694 	spare_cbdata_t *cbp = data;
1695 	nvlist_t *config, *nvroot;
1696 
1697 	config = zpool_get_config(zhp, NULL);
1698 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1699 	    &nvroot) == 0);
1700 
1701 	if (find_vdev(nvroot, cbp->cb_guid)) {
1702 		cbp->cb_zhp = zhp;
1703 		return (1);
1704 	}
1705 
1706 	zpool_close(zhp);
1707 	return (0);
1708 }
1709 
1710 typedef struct status_cbdata {
1711 	int		cb_count;
1712 	int		cb_name_flags;
1713 	int		cb_namewidth;
1714 	boolean_t	cb_allpools;
1715 	boolean_t	cb_verbose;
1716 	boolean_t	cb_literal;
1717 	boolean_t	cb_explain;
1718 	boolean_t	cb_first;
1719 	boolean_t	cb_dedup_stats;
1720 	boolean_t	cb_print_status;
1721 	boolean_t	cb_print_slow_ios;
1722 	boolean_t	cb_print_vdev_init;
1723 	boolean_t	cb_print_vdev_trim;
1724 } status_cbdata_t;
1725 
1726 /*
1727  * Print vdev initialization status for leaves
1728  */
1729 static void
1730 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
1731 {
1732 	if (verbose) {
1733 		if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
1734 		    vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
1735 		    vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
1736 		    !vs->vs_scan_removing) {
1737 			char zbuf[1024];
1738 			char tbuf[256];
1739 			struct tm zaction_ts;
1740 
1741 			time_t t = vs->vs_initialize_action_time;
1742 			int initialize_pct = 100;
1743 			if (vs->vs_initialize_state !=
1744 			    VDEV_INITIALIZE_COMPLETE) {
1745 				initialize_pct = (vs->vs_initialize_bytes_done *
1746 				    100 / (vs->vs_initialize_bytes_est + 1));
1747 			}
1748 
1749 			(void) localtime_r(&t, &zaction_ts);
1750 			(void) strftime(tbuf, sizeof (tbuf), "%c", &zaction_ts);
1751 
1752 			switch (vs->vs_initialize_state) {
1753 			case VDEV_INITIALIZE_SUSPENDED:
1754 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
1755 				    gettext("suspended, started at"), tbuf);
1756 				break;
1757 			case VDEV_INITIALIZE_ACTIVE:
1758 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
1759 				    gettext("started at"), tbuf);
1760 				break;
1761 			case VDEV_INITIALIZE_COMPLETE:
1762 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
1763 				    gettext("completed at"), tbuf);
1764 				break;
1765 			}
1766 
1767 			(void) printf(gettext("  (%d%% initialized%s)"),
1768 			    initialize_pct, zbuf);
1769 		} else {
1770 			(void) printf(gettext("  (uninitialized)"));
1771 		}
1772 	} else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
1773 		(void) printf(gettext("  (initializing)"));
1774 	}
1775 }
1776 
1777 /*
1778  * Print vdev TRIM status for leaves
1779  */
1780 static void
1781 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
1782 {
1783 	if (verbose) {
1784 		if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
1785 		    vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
1786 		    vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
1787 		    !vs->vs_scan_removing) {
1788 			char zbuf[1024];
1789 			char tbuf[256];
1790 			struct tm zaction_ts;
1791 
1792 			time_t t = vs->vs_trim_action_time;
1793 			int trim_pct = 100;
1794 			if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
1795 				trim_pct = (vs->vs_trim_bytes_done *
1796 				    100 / (vs->vs_trim_bytes_est + 1));
1797 			}
1798 
1799 			(void) localtime_r(&t, &zaction_ts);
1800 			(void) strftime(tbuf, sizeof (tbuf), "%c", &zaction_ts);
1801 
1802 			switch (vs->vs_trim_state) {
1803 			case VDEV_TRIM_SUSPENDED:
1804 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
1805 				    gettext("suspended, started at"), tbuf);
1806 				break;
1807 			case VDEV_TRIM_ACTIVE:
1808 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
1809 				    gettext("started at"), tbuf);
1810 				break;
1811 			case VDEV_TRIM_COMPLETE:
1812 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
1813 				    gettext("completed at"), tbuf);
1814 				break;
1815 			}
1816 
1817 			(void) printf(gettext("  (%d%% trimmed%s)"),
1818 			    trim_pct, zbuf);
1819 		} else if (vs->vs_trim_notsup) {
1820 			(void) printf(gettext("  (trim unsupported)"));
1821 		} else {
1822 			(void) printf(gettext("  (untrimmed)"));
1823 		}
1824 	} else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
1825 		(void) printf(gettext("  (trimming)"));
1826 	}
1827 }
1828 
1829 /*
1830  * Print out configuration state as requested by status_callback.
1831  */
1832 static void
1833 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
1834     nvlist_t *nv, int depth, boolean_t isspare)
1835 {
1836 	nvlist_t **child, *root;
1837 	uint_t c, children;
1838 	pool_scan_stat_t *ps = NULL;
1839 	vdev_stat_t *vs;
1840 	char rbuf[6], wbuf[6], cbuf[6];
1841 	char *vname;
1842 	uint64_t notpresent;
1843 	spare_cbdata_t spare_cb;
1844 	const char *state;
1845 	char *type;
1846 
1847 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1848 	    &child, &children) != 0)
1849 		children = 0;
1850 
1851 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1852 	    (uint64_t **)&vs, &c) == 0);
1853 
1854 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1855 
1856 	if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
1857 		return;
1858 
1859 	state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1860 	if (isspare) {
1861 		/*
1862 		 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
1863 		 * online drives.
1864 		 */
1865 		if (vs->vs_aux == VDEV_AUX_SPARED)
1866 			state = "INUSE";
1867 		else if (vs->vs_state == VDEV_STATE_HEALTHY)
1868 			state = "AVAIL";
1869 	}
1870 
1871 	(void) printf("\t%*s%-*s  %-8s", depth, "", cb->cb_namewidth - depth,
1872 	    name, state);
1873 
1874 	if (!isspare) {
1875 		if (cb->cb_literal) {
1876 			printf(" %5llu %5llu %5llu",
1877 			    (u_longlong_t)vs->vs_read_errors,
1878 			    (u_longlong_t)vs->vs_write_errors,
1879 			    (u_longlong_t)vs->vs_checksum_errors);
1880 		} else {
1881 			zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
1882 			zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
1883 			zfs_nicenum(vs->vs_checksum_errors, cbuf,
1884 			    sizeof (cbuf));
1885 			printf(" %5s %5s %5s", rbuf, wbuf, cbuf);
1886 		}
1887 
1888 		if (cb->cb_print_slow_ios) {
1889 			if (children == 0)  {
1890 				/* Only leafs vdevs have slow IOs */
1891 				zfs_nicenum(vs->vs_slow_ios, rbuf,
1892 				    sizeof (rbuf));
1893 			} else {
1894 				(void) snprintf(rbuf, sizeof (rbuf), "-");
1895 			}
1896 
1897 			if (cb->cb_literal)
1898 				printf(" %5llu", (u_longlong_t)vs->vs_slow_ios);
1899 			else
1900 				printf(" %5s", rbuf);
1901 		}
1902 
1903 	}
1904 
1905 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
1906 	    &notpresent) == 0) {
1907 		char *path;
1908 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
1909 		(void) printf("  was %s", path);
1910 	} else if (vs->vs_aux != 0) {
1911 		(void) printf("  ");
1912 
1913 		switch (vs->vs_aux) {
1914 		case VDEV_AUX_OPEN_FAILED:
1915 			(void) printf(gettext("cannot open"));
1916 			break;
1917 
1918 		case VDEV_AUX_BAD_GUID_SUM:
1919 			(void) printf(gettext("missing device"));
1920 			break;
1921 
1922 		case VDEV_AUX_NO_REPLICAS:
1923 			(void) printf(gettext("insufficient replicas"));
1924 			break;
1925 
1926 		case VDEV_AUX_VERSION_NEWER:
1927 			(void) printf(gettext("newer version"));
1928 			break;
1929 
1930 		case VDEV_AUX_UNSUP_FEAT:
1931 			(void) printf(gettext("unsupported feature(s)"));
1932 			break;
1933 
1934 		case VDEV_AUX_SPARED:
1935 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
1936 			    &spare_cb.cb_guid) == 0);
1937 			if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1938 				if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1939 				    zpool_get_name(zhp)) == 0)
1940 					(void) printf(gettext("currently in "
1941 					    "use"));
1942 				else
1943 					(void) printf(gettext("in use by "
1944 					    "pool '%s'"),
1945 					    zpool_get_name(spare_cb.cb_zhp));
1946 				zpool_close(spare_cb.cb_zhp);
1947 			} else {
1948 				(void) printf(gettext("currently in use"));
1949 			}
1950 			break;
1951 
1952 		case VDEV_AUX_ERR_EXCEEDED:
1953 			(void) printf(gettext("too many errors"));
1954 			break;
1955 
1956 		case VDEV_AUX_IO_FAILURE:
1957 			(void) printf(gettext("experienced I/O failures"));
1958 			break;
1959 
1960 		case VDEV_AUX_BAD_LOG:
1961 			(void) printf(gettext("bad intent log"));
1962 			break;
1963 
1964 		case VDEV_AUX_EXTERNAL:
1965 			(void) printf(gettext("external device fault"));
1966 			break;
1967 
1968 		case VDEV_AUX_SPLIT_POOL:
1969 			(void) printf(gettext("split into new pool"));
1970 			break;
1971 
1972 		case VDEV_AUX_ACTIVE:
1973 			(void) printf(gettext("currently in use"));
1974 			break;
1975 
1976 		case VDEV_AUX_CHILDREN_OFFLINE:
1977 			(void) printf(gettext("all children offline"));
1978 			break;
1979 
1980 		default:
1981 			(void) printf(gettext("corrupted data"));
1982 			break;
1983 		}
1984 	}
1985 
1986 	/* The root vdev has the scrub/resilver stats */
1987 	root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
1988 	    ZPOOL_CONFIG_VDEV_TREE);
1989 	(void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
1990 	    (uint64_t **)&ps, &c);
1991 
1992 	if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0) {
1993 		if (vs->vs_scan_processed != 0) {
1994 			(void) printf(gettext("  (%s)"),
1995 			    (ps->pss_func == POOL_SCAN_RESILVER) ?
1996 			    "resilvering" : "repairing");
1997 		} else if (vs->vs_resilver_deferred) {
1998 			(void) printf(gettext("  (awaiting resilver)"));
1999 		}
2000 	}
2001 
2002 	/* Display vdev initialization and trim status for leaves */
2003 	if (children == 0) {
2004 		print_status_initialize(vs, cb->cb_print_vdev_init);
2005 		print_status_trim(vs, cb->cb_print_vdev_trim);
2006 	}
2007 
2008 	(void) printf("\n");
2009 
2010 	for (c = 0; c < children; c++) {
2011 		uint64_t islog = B_FALSE, ishole = B_FALSE;
2012 
2013 		/* Don't print logs or holes here */
2014 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2015 		    &islog);
2016 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
2017 		    &ishole);
2018 		if (islog || ishole)
2019 			continue;
2020 		/* Only print normal classes here */
2021 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
2022 			continue;
2023 
2024 		vname = zpool_vdev_name(g_zfs, zhp, child[c],
2025 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2026 
2027 		print_status_config(zhp, cb, vname, child[c], depth + 2,
2028 		    isspare);
2029 		free(vname);
2030 	}
2031 }
2032 
2033 /*
2034  * Print the configuration of an exported pool.  Iterate over all vdevs in the
2035  * pool, printing out the name and status for each one.
2036  */
2037 static void
2038 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
2039     int depth)
2040 {
2041 	nvlist_t **child;
2042 	uint_t c, children;
2043 	vdev_stat_t *vs;
2044 	char *type, *vname;
2045 
2046 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2047 	if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
2048 	    strcmp(type, VDEV_TYPE_HOLE) == 0)
2049 		return;
2050 
2051 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2052 	    (uint64_t **)&vs, &c) == 0);
2053 
2054 	(void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
2055 	(void) printf("  %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
2056 
2057 	if (vs->vs_aux != 0) {
2058 		(void) printf("  ");
2059 
2060 		switch (vs->vs_aux) {
2061 		case VDEV_AUX_OPEN_FAILED:
2062 			(void) printf(gettext("cannot open"));
2063 			break;
2064 
2065 		case VDEV_AUX_BAD_GUID_SUM:
2066 			(void) printf(gettext("missing device"));
2067 			break;
2068 
2069 		case VDEV_AUX_NO_REPLICAS:
2070 			(void) printf(gettext("insufficient replicas"));
2071 			break;
2072 
2073 		case VDEV_AUX_VERSION_NEWER:
2074 			(void) printf(gettext("newer version"));
2075 			break;
2076 
2077 		case VDEV_AUX_UNSUP_FEAT:
2078 			(void) printf(gettext("unsupported feature(s)"));
2079 			break;
2080 
2081 		case VDEV_AUX_ERR_EXCEEDED:
2082 			(void) printf(gettext("too many errors"));
2083 			break;
2084 
2085 		case VDEV_AUX_ACTIVE:
2086 			(void) printf(gettext("currently in use"));
2087 			break;
2088 
2089 		case VDEV_AUX_CHILDREN_OFFLINE:
2090 			(void) printf(gettext("all children offline"));
2091 			break;
2092 
2093 		default:
2094 			(void) printf(gettext("corrupted data"));
2095 			break;
2096 		}
2097 	}
2098 	(void) printf("\n");
2099 
2100 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2101 	    &child, &children) != 0)
2102 		return;
2103 
2104 	for (c = 0; c < children; c++) {
2105 		uint64_t is_log = B_FALSE;
2106 
2107 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2108 		    &is_log);
2109 		if (is_log)
2110 			continue;
2111 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
2112 			continue;
2113 
2114 		vname = zpool_vdev_name(g_zfs, NULL, child[c],
2115 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2116 		print_import_config(cb, vname, child[c], depth + 2);
2117 		free(vname);
2118 	}
2119 
2120 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2121 	    &child, &children) == 0) {
2122 		(void) printf(gettext("\tcache\n"));
2123 		for (c = 0; c < children; c++) {
2124 			vname = zpool_vdev_name(g_zfs, NULL, child[c],
2125 			    cb->cb_name_flags);
2126 			(void) printf("\t  %s\n", vname);
2127 			free(vname);
2128 		}
2129 	}
2130 
2131 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2132 	    &child, &children) == 0) {
2133 		(void) printf(gettext("\tspares\n"));
2134 		for (c = 0; c < children; c++) {
2135 			vname = zpool_vdev_name(g_zfs, NULL, child[c],
2136 			    cb->cb_name_flags);
2137 			(void) printf("\t  %s\n", vname);
2138 			free(vname);
2139 		}
2140 	}
2141 }
2142 
2143 /*
2144  * Print specialized class vdevs.
2145  *
2146  * These are recorded as top level vdevs in the main pool child array
2147  * but with "is_log" set to 1 or an "alloc_bias" string. We use either
2148  * print_status_config() or print_import_config() to print the top level
2149  * class vdevs then any of their children (eg mirrored slogs) are printed
2150  * recursively - which works because only the top level vdev is marked.
2151  */
2152 static void
2153 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
2154     const char *class)
2155 {
2156 	uint_t c, children;
2157 	nvlist_t **child;
2158 	boolean_t printed = B_FALSE;
2159 
2160 	assert(zhp != NULL || !cb->cb_verbose);
2161 
2162 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
2163 	    &children) != 0)
2164 		return;
2165 
2166 	for (c = 0; c < children; c++) {
2167 		uint64_t is_log = B_FALSE;
2168 		char *bias = NULL;
2169 		char *type = NULL;
2170 
2171 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2172 		    &is_log);
2173 
2174 		if (is_log) {
2175 			bias = VDEV_ALLOC_CLASS_LOGS;
2176 		} else {
2177 			(void) nvlist_lookup_string(child[c],
2178 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
2179 			(void) nvlist_lookup_string(child[c],
2180 			    ZPOOL_CONFIG_TYPE, &type);
2181 		}
2182 
2183 		if (bias == NULL || strcmp(bias, class) != 0)
2184 			continue;
2185 		if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2186 			continue;
2187 
2188 		if (!printed) {
2189 			(void) printf("\t%s\t\n", gettext(class));
2190 			printed = B_TRUE;
2191 		}
2192 
2193 		char *name = zpool_vdev_name(g_zfs, zhp, child[c],
2194 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2195 		if (cb->cb_print_status)
2196 			print_status_config(zhp, cb, name, child[c], 2,
2197 			    B_FALSE);
2198 		else
2199 			print_import_config(cb, name, child[c], 2);
2200 		free(name);
2201 	}
2202 }
2203 
2204 /*
2205  * Display the status for the given pool.
2206  */
2207 static void
2208 show_import(nvlist_t *config)
2209 {
2210 	uint64_t pool_state;
2211 	vdev_stat_t *vs;
2212 	char *name;
2213 	uint64_t guid;
2214 	uint64_t hostid = 0;
2215 	char *msgid;
2216 	char *hostname = "unknown";
2217 	nvlist_t *nvroot, *nvinfo;
2218 	int reason;
2219 	zpool_errata_t errata;
2220 	const char *health;
2221 	uint_t vsc;
2222 	char *comment;
2223 	status_cbdata_t cb = { 0 };
2224 
2225 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2226 	    &name) == 0);
2227 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
2228 	    &guid) == 0);
2229 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2230 	    &pool_state) == 0);
2231 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2232 	    &nvroot) == 0);
2233 
2234 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
2235 	    (uint64_t **)&vs, &vsc) == 0);
2236 	health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2237 
2238 	reason = zpool_import_status(config, &msgid, &errata);
2239 
2240 	(void) printf(gettext("   pool: %s\n"), name);
2241 	(void) printf(gettext("     id: %llu\n"), (u_longlong_t)guid);
2242 	(void) printf(gettext("  state: %s"), health);
2243 	if (pool_state == POOL_STATE_DESTROYED)
2244 		(void) printf(gettext(" (DESTROYED)"));
2245 	(void) printf("\n");
2246 
2247 	switch (reason) {
2248 	case ZPOOL_STATUS_MISSING_DEV_R:
2249 	case ZPOOL_STATUS_MISSING_DEV_NR:
2250 	case ZPOOL_STATUS_BAD_GUID_SUM:
2251 		(void) printf(gettext(" status: One or more devices are "
2252 		    "missing from the system.\n"));
2253 		break;
2254 
2255 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
2256 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
2257 		(void) printf(gettext(" status: One or more devices contains "
2258 		    "corrupted data.\n"));
2259 		break;
2260 
2261 	case ZPOOL_STATUS_CORRUPT_DATA:
2262 		(void) printf(
2263 		    gettext(" status: The pool data is corrupted.\n"));
2264 		break;
2265 
2266 	case ZPOOL_STATUS_OFFLINE_DEV:
2267 		(void) printf(gettext(" status: One or more devices "
2268 		    "are offlined.\n"));
2269 		break;
2270 
2271 	case ZPOOL_STATUS_CORRUPT_POOL:
2272 		(void) printf(gettext(" status: The pool metadata is "
2273 		    "corrupted.\n"));
2274 		break;
2275 
2276 	case ZPOOL_STATUS_VERSION_OLDER:
2277 		(void) printf(gettext(" status: The pool is formatted using a "
2278 		    "legacy on-disk version.\n"));
2279 		break;
2280 
2281 	case ZPOOL_STATUS_VERSION_NEWER:
2282 		(void) printf(gettext(" status: The pool is formatted using an "
2283 		    "incompatible version.\n"));
2284 		break;
2285 
2286 	case ZPOOL_STATUS_FEAT_DISABLED:
2287 		(void) printf(gettext(" status: Some supported features are "
2288 		    "not enabled on the pool.\n"));
2289 		break;
2290 
2291 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
2292 		(void) printf(gettext("status: The pool uses the following "
2293 		    "feature(s) not supported on this system:\n"));
2294 		zpool_print_unsup_feat(config);
2295 		break;
2296 
2297 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2298 		(void) printf(gettext("status: The pool can only be accessed "
2299 		    "in read-only mode on this system. It\n\tcannot be "
2300 		    "accessed in read-write mode because it uses the "
2301 		    "following\n\tfeature(s) not supported on this system:\n"));
2302 		zpool_print_unsup_feat(config);
2303 		break;
2304 
2305 	case ZPOOL_STATUS_HOSTID_ACTIVE:
2306 		(void) printf(gettext(" status: The pool is currently "
2307 		    "imported by another system.\n"));
2308 		break;
2309 
2310 	case ZPOOL_STATUS_HOSTID_REQUIRED:
2311 		(void) printf(gettext(" status: The pool has the "
2312 		    "multihost property on.  It cannot\n\tbe safely imported "
2313 		    "when the system hostid is not set.\n"));
2314 		break;
2315 
2316 	case ZPOOL_STATUS_HOSTID_MISMATCH:
2317 		(void) printf(gettext(" status: The pool was last accessed by "
2318 		    "another system.\n"));
2319 		break;
2320 
2321 	case ZPOOL_STATUS_FAULTED_DEV_R:
2322 	case ZPOOL_STATUS_FAULTED_DEV_NR:
2323 		(void) printf(gettext(" status: One or more devices are "
2324 		    "faulted.\n"));
2325 		break;
2326 
2327 	case ZPOOL_STATUS_BAD_LOG:
2328 		(void) printf(gettext(" status: An intent log record cannot be "
2329 		    "read.\n"));
2330 		break;
2331 
2332 	case ZPOOL_STATUS_RESILVERING:
2333 		(void) printf(gettext(" status: One or more devices were being "
2334 		    "resilvered.\n"));
2335 		break;
2336 
2337 	case ZPOOL_STATUS_ERRATA:
2338 		(void) printf(gettext(" status: Errata #%d detected.\n"),
2339 		    errata);
2340 		break;
2341 
2342 	default:
2343 		/*
2344 		 * No other status can be seen when importing pools.
2345 		 */
2346 		assert(reason == ZPOOL_STATUS_OK);
2347 	}
2348 
2349 	/*
2350 	 * Print out an action according to the overall state of the pool.
2351 	 */
2352 	if (vs->vs_state == VDEV_STATE_HEALTHY) {
2353 		if (reason == ZPOOL_STATUS_VERSION_OLDER ||
2354 		    reason == ZPOOL_STATUS_FEAT_DISABLED) {
2355 			(void) printf(gettext(" action: The pool can be "
2356 			    "imported using its name or numeric identifier, "
2357 			    "though\n\tsome features will not be available "
2358 			    "without an explicit 'zpool upgrade'.\n"));
2359 		} else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
2360 			(void) printf(gettext(" action: The pool can be "
2361 			    "imported using its name or numeric "
2362 			    "identifier and\n\tthe '-f' flag.\n"));
2363 		} else if (reason == ZPOOL_STATUS_ERRATA) {
2364 			switch (errata) {
2365 			case ZPOOL_ERRATA_NONE:
2366 				break;
2367 
2368 			case ZPOOL_ERRATA_ZOL_2094_SCRUB:
2369 				(void) printf(gettext(" action: The pool can "
2370 				    "be imported using its name or numeric "
2371 				    "identifier,\n\thowever there is a compat"
2372 				    "ibility issue which should be corrected"
2373 				    "\n\tby running 'zpool scrub'\n"));
2374 				break;
2375 
2376 			case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
2377 				(void) printf(gettext(" action: The pool can"
2378 				    "not be imported with this version of ZFS "
2379 				    "due to\n\tan active asynchronous destroy. "
2380 				    "Revert to an earlier version\n\tand "
2381 				    "allow the destroy to complete before "
2382 				    "updating.\n"));
2383 				break;
2384 
2385 			case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
2386 				(void) printf(gettext(" action: Existing "
2387 				    "encrypted datasets contain an on-disk "
2388 				    "incompatibility, which\n\tneeds to be "
2389 				    "corrected. Backup these datasets to new "
2390 				    "encrypted datasets\n\tand destroy the "
2391 				    "old ones.\n"));
2392 				break;
2393 			case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
2394 				(void) printf(gettext(" action: Any existing "
2395 				    "encrypted datasets contain an on-disk "
2396 				    "incompatibility which\n\tmay cause "
2397 				    "on-disk corruption with 'zfs recv' and "
2398 				    "which needs to be\n\tcorrected. Enable "
2399 				    "the bookmark_v2 feature and backup "
2400 				    "these datasets to new encrypted "
2401 				    "datasets and\n\tdestroy the old ones. "
2402 				    "If this pool does not contain any "
2403 				    "encrypted datasets, simply enable\n\t"
2404 				    "the bookmark_v2 feature.\n"));
2405 				break;
2406 			default:
2407 				/*
2408 				 * All errata must contain an action message.
2409 				 */
2410 				assert(0);
2411 			}
2412 		} else {
2413 			(void) printf(gettext(" action: The pool can be "
2414 			    "imported using its name or numeric "
2415 			    "identifier.\n"));
2416 		}
2417 	} else if (vs->vs_state == VDEV_STATE_DEGRADED) {
2418 		(void) printf(gettext(" action: The pool can be imported "
2419 		    "despite missing or damaged devices.  The\n\tfault "
2420 		    "tolerance of the pool may be compromised if imported.\n"));
2421 	} else {
2422 		switch (reason) {
2423 		case ZPOOL_STATUS_VERSION_NEWER:
2424 			(void) printf(gettext(" action: The pool cannot be "
2425 			    "imported.  Access the pool on a system running "
2426 			    "newer\n\tsoftware, or recreate the pool from "
2427 			    "backup.\n"));
2428 			break;
2429 		case ZPOOL_STATUS_UNSUP_FEAT_READ:
2430 			(void) printf(gettext("action: The pool cannot be "
2431 			    "imported. Access the pool on a system that "
2432 			    "supports\n\tthe required feature(s), or recreate "
2433 			    "the pool from backup.\n"));
2434 			break;
2435 		case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2436 			(void) printf(gettext("action: The pool cannot be "
2437 			    "imported in read-write mode. Import the pool "
2438 			    "with\n"
2439 			    "\t\"-o readonly=on\", access the pool on a system "
2440 			    "that supports the\n\trequired feature(s), or "
2441 			    "recreate the pool from backup.\n"));
2442 			break;
2443 		case ZPOOL_STATUS_MISSING_DEV_R:
2444 		case ZPOOL_STATUS_MISSING_DEV_NR:
2445 		case ZPOOL_STATUS_BAD_GUID_SUM:
2446 			(void) printf(gettext(" action: The pool cannot be "
2447 			    "imported. Attach the missing\n\tdevices and try "
2448 			    "again.\n"));
2449 			break;
2450 		case ZPOOL_STATUS_HOSTID_ACTIVE:
2451 			VERIFY0(nvlist_lookup_nvlist(config,
2452 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
2453 
2454 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
2455 				hostname = fnvlist_lookup_string(nvinfo,
2456 				    ZPOOL_CONFIG_MMP_HOSTNAME);
2457 
2458 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
2459 				hostid = fnvlist_lookup_uint64(nvinfo,
2460 				    ZPOOL_CONFIG_MMP_HOSTID);
2461 
2462 			(void) printf(gettext(" action: The pool must be "
2463 			    "exported from %s (hostid=%lx)\n\tbefore it "
2464 			    "can be safely imported.\n"), hostname,
2465 			    (unsigned long) hostid);
2466 			break;
2467 		case ZPOOL_STATUS_HOSTID_REQUIRED:
2468 			(void) printf(gettext(" action: Check the SMF "
2469 			    "svc:/system/hostid service.\n"));
2470 			break;
2471 		default:
2472 			(void) printf(gettext(" action: The pool cannot be "
2473 			    "imported due to damaged devices or data.\n"));
2474 		}
2475 	}
2476 
2477 	/* Print the comment attached to the pool. */
2478 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2479 		(void) printf(gettext("comment: %s\n"), comment);
2480 
2481 	/*
2482 	 * If the state is "closed" or "can't open", and the aux state
2483 	 * is "corrupt data":
2484 	 */
2485 	if (((vs->vs_state == VDEV_STATE_CLOSED) ||
2486 	    (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
2487 	    (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
2488 		if (pool_state == POOL_STATE_DESTROYED)
2489 			(void) printf(gettext("\tThe pool was destroyed, "
2490 			    "but can be imported using the '-Df' flags.\n"));
2491 		else if (pool_state != POOL_STATE_EXPORTED)
2492 			(void) printf(gettext("\tThe pool may be active on "
2493 			    "another system, but can be imported using\n\t"
2494 			    "the '-f' flag.\n"));
2495 	}
2496 
2497 	if (msgid != NULL)
2498 		(void) printf(gettext("   see: http://illumos.org/msg/%s\n"),
2499 		    msgid);
2500 
2501 	(void) printf(gettext(" config:\n\n"));
2502 
2503 	cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
2504 	    VDEV_NAME_TYPE_ID);
2505 	if (cb.cb_namewidth < 10)
2506 		cb.cb_namewidth = 10;
2507 
2508 	print_import_config(&cb, name, nvroot, 0);
2509 
2510 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
2511 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
2512 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
2513 
2514 	if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
2515 		(void) printf(gettext("\n\tAdditional devices are known to "
2516 		    "be part of this pool, though their\n\texact "
2517 		    "configuration cannot be determined.\n"));
2518 	}
2519 }
2520 
2521 static boolean_t
2522 zfs_force_import_required(nvlist_t *config)
2523 {
2524 	uint64_t state;
2525 	uint64_t hostid = 0;
2526 	nvlist_t *nvinfo;
2527 
2528 	state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
2529 	(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID, &hostid);
2530 
2531 	if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
2532 		return (B_TRUE);
2533 
2534 	nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2535 	if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
2536 		mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
2537 		    ZPOOL_CONFIG_MMP_STATE);
2538 
2539 		if (mmp_state != MMP_STATE_INACTIVE)
2540 			return (B_TRUE);
2541 	}
2542 
2543 	return (B_FALSE);
2544 }
2545 
2546 /*
2547  * Perform the import for the given configuration.  This passes the heavy
2548  * lifting off to zpool_import_props(), and then mounts the datasets contained
2549  * within the pool.
2550  */
2551 static int
2552 do_import(nvlist_t *config, const char *newname, const char *mntopts,
2553     nvlist_t *props, int flags)
2554 {
2555 	int ret = 0;
2556 	zpool_handle_t *zhp;
2557 	char *name;
2558 	uint64_t version;
2559 
2560 	name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
2561 	version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
2562 
2563 	if (!SPA_VERSION_IS_SUPPORTED(version)) {
2564 		(void) fprintf(stderr, gettext("cannot import '%s': pool "
2565 		    "is formatted using an unsupported ZFS version\n"), name);
2566 		return (1);
2567 	} else if (zfs_force_import_required(config) &&
2568 	    !(flags & ZFS_IMPORT_ANY_HOST)) {
2569 		mmp_state_t mmp_state = MMP_STATE_INACTIVE;
2570 		nvlist_t *nvinfo;
2571 
2572 		nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2573 		if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
2574 			mmp_state = fnvlist_lookup_uint64(nvinfo,
2575 			    ZPOOL_CONFIG_MMP_STATE);
2576 
2577 		if (mmp_state == MMP_STATE_ACTIVE) {
2578 			char *hostname = "<unknown>";
2579 			uint64_t hostid = 0;
2580 
2581 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
2582 				hostname = fnvlist_lookup_string(nvinfo,
2583 				    ZPOOL_CONFIG_MMP_HOSTNAME);
2584 
2585 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
2586 				hostid = fnvlist_lookup_uint64(nvinfo,
2587 				    ZPOOL_CONFIG_MMP_HOSTID);
2588 
2589 			(void) fprintf(stderr, gettext("cannot import '%s': "
2590 			    "pool is imported on %s (hostid: "
2591 			    "0x%lx)\nExport the pool on the other system, "
2592 			    "then run 'zpool import'.\n"),
2593 			    name, hostname, (unsigned long) hostid);
2594 		} else if (mmp_state == MMP_STATE_NO_HOSTID) {
2595 			(void) fprintf(stderr, gettext("Cannot import '%s': "
2596 			    "pool has the multihost property on and the\n"
2597 			    "system's hostid is not set.\n"), name);
2598 		} else {
2599 			char *hostname = "<unknown>";
2600 			uint64_t timestamp = 0;
2601 			uint64_t hostid = 0;
2602 
2603 			if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
2604 				hostname = fnvlist_lookup_string(config,
2605 				    ZPOOL_CONFIG_HOSTNAME);
2606 
2607 			if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
2608 				timestamp = fnvlist_lookup_uint64(config,
2609 				    ZPOOL_CONFIG_TIMESTAMP);
2610 
2611 			if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
2612 				hostid = fnvlist_lookup_uint64(config,
2613 				    ZPOOL_CONFIG_HOSTID);
2614 
2615 			(void) fprintf(stderr, gettext("cannot import '%s': "
2616 			    "pool was previously in use from another system.\n"
2617 			    "Last accessed by %s (hostid=%lx) at %s"
2618 			    "The pool can be imported, use 'zpool import -f' "
2619 			    "to import the pool.\n"), name, hostname,
2620 			    (unsigned long)hostid, ctime((time_t *)&timestamp));
2621 
2622 		}
2623 
2624 		return (1);
2625 	}
2626 
2627 	if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
2628 		return (1);
2629 
2630 	if (newname != NULL)
2631 		name = (char *)newname;
2632 
2633 	if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
2634 		return (1);
2635 
2636 	/*
2637 	 * Loading keys is best effort. We don't want to return immediately
2638 	 * if it fails but we do want to give the error to the caller.
2639 	 */
2640 	if (flags & ZFS_IMPORT_LOAD_KEYS) {
2641 		ret = zfs_crypto_attempt_load_keys(g_zfs, name);
2642 		if (ret != 0)
2643 			ret = 1;
2644 	}
2645 
2646 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
2647 	    !(flags & ZFS_IMPORT_ONLY) &&
2648 	    zpool_enable_datasets(zhp, mntopts, 0) != 0) {
2649 		zpool_close(zhp);
2650 		return (1);
2651 	}
2652 
2653 	zpool_close(zhp);
2654 	return (ret);
2655 }
2656 
2657 typedef struct target_exists_args {
2658 	const char	*poolname;
2659 	uint64_t	poolguid;
2660 } target_exists_args_t;
2661 
2662 static int
2663 name_or_guid_exists(zpool_handle_t *zhp, void *data)
2664 {
2665 	target_exists_args_t *args = data;
2666 	nvlist_t *config = zpool_get_config(zhp, NULL);
2667 	int found = 0;
2668 
2669 	if (config == NULL)
2670 		return (0);
2671 
2672 	if (args->poolname != NULL) {
2673 		char *pool_name;
2674 
2675 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2676 		    &pool_name) == 0);
2677 		if (strcmp(pool_name, args->poolname) == 0)
2678 			found = 1;
2679 	} else {
2680 		uint64_t pool_guid;
2681 
2682 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
2683 		    &pool_guid) == 0);
2684 		if (pool_guid == args->poolguid)
2685 			found = 1;
2686 	}
2687 	zpool_close(zhp);
2688 
2689 	return (found);
2690 }
2691 /*
2692  * zpool checkpoint <pool>
2693  *       checkpoint --discard <pool>
2694  *
2695  *	-d	Discard the checkpoint from a checkpointed
2696  *	--discard  pool.
2697  *
2698  * Checkpoints the specified pool, by taking a "snapshot" of its
2699  * current state. A pool can only have one checkpoint at a time.
2700  */
2701 int
2702 zpool_do_checkpoint(int argc, char **argv)
2703 {
2704 	boolean_t discard;
2705 	char *pool;
2706 	zpool_handle_t *zhp;
2707 	int c, err;
2708 
2709 	struct option long_options[] = {
2710 		{"discard", no_argument, NULL, 'd'},
2711 		{0, 0, 0, 0}
2712 	};
2713 
2714 	discard = B_FALSE;
2715 	while ((c = getopt_long(argc, argv, ":d", long_options, NULL)) != -1) {
2716 		switch (c) {
2717 		case 'd':
2718 			discard = B_TRUE;
2719 			break;
2720 		case '?':
2721 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2722 			    optopt);
2723 			usage(B_FALSE);
2724 		}
2725 	}
2726 
2727 	argc -= optind;
2728 	argv += optind;
2729 
2730 	if (argc < 1) {
2731 		(void) fprintf(stderr, gettext("missing pool argument\n"));
2732 		usage(B_FALSE);
2733 	}
2734 
2735 	if (argc > 1) {
2736 		(void) fprintf(stderr, gettext("too many arguments\n"));
2737 		usage(B_FALSE);
2738 	}
2739 
2740 	pool = argv[0];
2741 
2742 	if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
2743 		/* As a special case, check for use of '/' in the name */
2744 		if (strchr(pool, '/') != NULL)
2745 			(void) fprintf(stderr, gettext("'zpool checkpoint' "
2746 			    "doesn't work on datasets. To save the state "
2747 			    "of a dataset from a specific point in time "
2748 			    "please use 'zfs snapshot'\n"));
2749 		return (1);
2750 	}
2751 
2752 	if (discard)
2753 		err = (zpool_discard_checkpoint(zhp) != 0);
2754 	else
2755 		err = (zpool_checkpoint(zhp) != 0);
2756 
2757 	zpool_close(zhp);
2758 
2759 	return (err);
2760 }
2761 
2762 #define	CHECKPOINT_OPT	1024
2763 
2764 /*
2765  * zpool import [-d dir] [-D]
2766  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
2767  *              [-d dir | -c cachefile] [-f] -a
2768  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
2769  *              [-d dir | -c cachefile] [-f] [-n] [-F] [-t]
2770  *              <pool | id> [newpool]
2771  *
2772  *	-c	Read pool information from a cachefile instead of searching
2773  *		devices.
2774  *
2775  *	-d	Scan in a specific directory, other than /dev/dsk.  More than
2776  *		one directory can be specified using multiple '-d' options.
2777  *
2778  *	-D	Scan for previously destroyed pools or import all or only
2779  *		specified destroyed pools.
2780  *
2781  *	-R	Temporarily import the pool, with all mountpoints relative to
2782  *		the given root.  The pool will remain exported when the machine
2783  *		is rebooted.
2784  *
2785  *	-V	Import even in the presence of faulted vdevs.  This is an
2786  *		intentionally undocumented option for testing purposes, and
2787  *		treats the pool configuration as complete, leaving any bad
2788  *		vdevs in the FAULTED state. In other words, it does verbatim
2789  *		import.
2790  *
2791  *	-f	Force import, even if it appears that the pool is active.
2792  *
2793  *	-F	Attempt rewind if necessary.
2794  *
2795  *	-n	See if rewind would work, but don't actually rewind.
2796  *
2797  *	-N	Import the pool but don't mount datasets.
2798  *
2799  *	-t	Use newpool as a temporary pool name instead of renaming
2800  *		the pool.
2801  *
2802  *	-T	Specify a starting txg to use for import. This option is
2803  *		intentionally undocumented option for testing purposes.
2804  *
2805  *	-a	Import all pools found.
2806  *
2807  *	-o	Set property=value and/or temporary mount options (without '=').
2808  *  -l	Load encryption keys while importing.
2809  *
2810  *	--rewind-to-checkpoint
2811  *		Import the pool and revert back to the checkpoint.
2812  *
2813  * The import command scans for pools to import, and import pools based on pool
2814  * name and GUID.  The pool can also be renamed as part of the import process.
2815  */
2816 int
2817 zpool_do_import(int argc, char **argv)
2818 {
2819 	char **searchdirs = NULL;
2820 	int nsearch = 0;
2821 	int c;
2822 	int err = 0;
2823 	nvlist_t *pools = NULL;
2824 	boolean_t do_all = B_FALSE;
2825 	boolean_t do_destroyed = B_FALSE;
2826 	char *mntopts = NULL;
2827 	nvpair_t *elem;
2828 	nvlist_t *config;
2829 	uint64_t searchguid = 0;
2830 	char *searchname = NULL;
2831 	char *propval;
2832 	nvlist_t *found_config;
2833 	nvlist_t *policy = NULL;
2834 	nvlist_t *props = NULL;
2835 	boolean_t first;
2836 	int flags = ZFS_IMPORT_NORMAL;
2837 	uint32_t rewind_policy = ZPOOL_NO_REWIND;
2838 	boolean_t dryrun = B_FALSE;
2839 	boolean_t do_rewind = B_FALSE;
2840 	boolean_t xtreme_rewind = B_FALSE;
2841 	boolean_t pool_exists = B_FALSE;
2842 	uint64_t pool_state, txg = -1ULL;
2843 	char *cachefile = NULL;
2844 	importargs_t idata = { 0 };
2845 	char *endptr;
2846 
2847 
2848 	struct option long_options[] = {
2849 		{"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
2850 		{0, 0, 0, 0}
2851 	};
2852 
2853 	/* check options */
2854 	while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmnNo:rR:tT:VX",
2855 	    long_options, NULL)) != -1) {
2856 		switch (c) {
2857 		case 'a':
2858 			do_all = B_TRUE;
2859 			break;
2860 		case 'c':
2861 			cachefile = optarg;
2862 			break;
2863 		case 'd':
2864 			if (searchdirs == NULL) {
2865 				searchdirs = safe_malloc(sizeof (char *));
2866 			} else {
2867 				char **tmp = safe_malloc((nsearch + 1) *
2868 				    sizeof (char *));
2869 				bcopy(searchdirs, tmp, nsearch *
2870 				    sizeof (char *));
2871 				free(searchdirs);
2872 				searchdirs = tmp;
2873 			}
2874 			searchdirs[nsearch++] = optarg;
2875 			break;
2876 		case 'D':
2877 			do_destroyed = B_TRUE;
2878 			break;
2879 		case 'f':
2880 			flags |= ZFS_IMPORT_ANY_HOST;
2881 			break;
2882 		case 'F':
2883 			do_rewind = B_TRUE;
2884 			break;
2885 		case 'l':
2886 			flags |= ZFS_IMPORT_LOAD_KEYS;
2887 			break;
2888 		case 'm':
2889 			flags |= ZFS_IMPORT_MISSING_LOG;
2890 			break;
2891 		case 'n':
2892 			dryrun = B_TRUE;
2893 			break;
2894 		case 'N':
2895 			flags |= ZFS_IMPORT_ONLY;
2896 			break;
2897 		case 'o':
2898 			if ((propval = strchr(optarg, '=')) != NULL) {
2899 				*propval = '\0';
2900 				propval++;
2901 				if (add_prop_list(optarg, propval,
2902 				    &props, B_TRUE))
2903 					goto error;
2904 			} else {
2905 				mntopts = optarg;
2906 			}
2907 			break;
2908 		case 'R':
2909 			if (add_prop_list(zpool_prop_to_name(
2910 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
2911 				goto error;
2912 			if (add_prop_list_default(zpool_prop_to_name(
2913 			    ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
2914 				goto error;
2915 			break;
2916 		case 't':
2917 			flags |= ZFS_IMPORT_TEMP_NAME;
2918 			if (add_prop_list_default(zpool_prop_to_name(
2919 			    ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
2920 				goto error;
2921 			break;
2922 		case 'T':
2923 			errno = 0;
2924 			txg = strtoull(optarg, &endptr, 0);
2925 			if (errno != 0 || *endptr != '\0') {
2926 				(void) fprintf(stderr,
2927 				    gettext("invalid txg value\n"));
2928 				usage(B_FALSE);
2929 			}
2930 			rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
2931 			break;
2932 		case 'V':
2933 			flags |= ZFS_IMPORT_VERBATIM;
2934 			break;
2935 		case 'X':
2936 			xtreme_rewind = B_TRUE;
2937 			break;
2938 		case CHECKPOINT_OPT:
2939 			flags |= ZFS_IMPORT_CHECKPOINT;
2940 			break;
2941 		case ':':
2942 			(void) fprintf(stderr, gettext("missing argument for "
2943 			    "'%c' option\n"), optopt);
2944 			usage(B_FALSE);
2945 			break;
2946 		case '?':
2947 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2948 			    optopt);
2949 			usage(B_FALSE);
2950 		}
2951 	}
2952 
2953 	argc -= optind;
2954 	argv += optind;
2955 
2956 	if (cachefile && nsearch != 0) {
2957 		(void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
2958 		usage(B_FALSE);
2959 	}
2960 
2961 	if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
2962 		(void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
2963 		usage(B_FALSE);
2964 	}
2965 
2966 	if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
2967 		(void) fprintf(stderr, gettext("-l is only meaningful during "
2968 		    "an import\n"));
2969 		usage(B_FALSE);
2970 	}
2971 
2972 	if ((dryrun || xtreme_rewind) && !do_rewind) {
2973 		(void) fprintf(stderr,
2974 		    gettext("-n or -X only meaningful with -F\n"));
2975 		usage(B_FALSE);
2976 	}
2977 	if (dryrun)
2978 		rewind_policy = ZPOOL_TRY_REWIND;
2979 	else if (do_rewind)
2980 		rewind_policy = ZPOOL_DO_REWIND;
2981 	if (xtreme_rewind)
2982 		rewind_policy |= ZPOOL_EXTREME_REWIND;
2983 
2984 	/* In the future, we can capture further policy and include it here */
2985 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
2986 	    nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
2987 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
2988 	    rewind_policy) != 0)
2989 		goto error;
2990 
2991 	if (searchdirs == NULL) {
2992 		searchdirs = safe_malloc(sizeof (char *));
2993 		searchdirs[0] = ZFS_DISK_ROOT;
2994 		nsearch = 1;
2995 	}
2996 
2997 	/* check argument count */
2998 	if (do_all) {
2999 		if (argc != 0) {
3000 			(void) fprintf(stderr, gettext("too many arguments\n"));
3001 			usage(B_FALSE);
3002 		}
3003 	} else {
3004 		if (argc > 2) {
3005 			(void) fprintf(stderr, gettext("too many arguments\n"));
3006 			usage(B_FALSE);
3007 		}
3008 
3009 		/*
3010 		 * Check for the SYS_CONFIG privilege.  We do this explicitly
3011 		 * here because otherwise any attempt to discover pools will
3012 		 * silently fail.
3013 		 */
3014 		if (argc == 0 && !priv_ineffect(PRIV_SYS_CONFIG)) {
3015 			(void) fprintf(stderr, gettext("cannot "
3016 			    "discover pools: permission denied\n"));
3017 			free(searchdirs);
3018 			nvlist_free(policy);
3019 			return (1);
3020 		}
3021 	}
3022 
3023 	/*
3024 	 * Depending on the arguments given, we do one of the following:
3025 	 *
3026 	 *	<none>	Iterate through all pools and display information about
3027 	 *		each one.
3028 	 *
3029 	 *	-a	Iterate through all pools and try to import each one.
3030 	 *
3031 	 *	<id>	Find the pool that corresponds to the given GUID/pool
3032 	 *		name and import that one.
3033 	 *
3034 	 *	-D	Above options applies only to destroyed pools.
3035 	 */
3036 	if (argc != 0) {
3037 		char *endptr;
3038 
3039 		errno = 0;
3040 		searchguid = strtoull(argv[0], &endptr, 10);
3041 		if (errno != 0 || *endptr != '\0') {
3042 			searchname = argv[0];
3043 			searchguid = 0;
3044 		}
3045 		found_config = NULL;
3046 
3047 		/*
3048 		 * User specified a name or guid.  Ensure it's unique.
3049 		 */
3050 		target_exists_args_t search = {searchname, searchguid};
3051 		pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
3052 	}
3053 
3054 	idata.path = searchdirs;
3055 	idata.paths = nsearch;
3056 	idata.poolname = searchname;
3057 	idata.guid = searchguid;
3058 	idata.cachefile = cachefile;
3059 	idata.policy = policy;
3060 
3061 	pools = zpool_search_import(g_zfs, &idata, &libzfs_config_ops);
3062 
3063 	if (pools != NULL && pool_exists &&
3064 	    (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
3065 		(void) fprintf(stderr, gettext("cannot import '%s': "
3066 		    "a pool with that name already exists\n"),
3067 		    argv[0]);
3068 		(void) fprintf(stderr, gettext("use the form 'zpool import "
3069 		    "[-t] <pool | id> <newpool>' to give it a new temporary "
3070 		    "or permanent name\n"));
3071 		err = 1;
3072 	} else if (pools == NULL && pool_exists) {
3073 		(void) fprintf(stderr, gettext("cannot import '%s': "
3074 		    "a pool with that name is already created/imported,\n"),
3075 		    argv[0]);
3076 		(void) fprintf(stderr, gettext("and no additional pools "
3077 		    "with that name were found\n"));
3078 		err = 1;
3079 	} else if (pools == NULL) {
3080 		if (argc != 0) {
3081 			(void) fprintf(stderr, gettext("cannot import '%s': "
3082 			    "no such pool available\n"), argv[0]);
3083 		}
3084 		err = 1;
3085 	}
3086 
3087 	if (err == 1) {
3088 		free(searchdirs);
3089 		nvlist_free(policy);
3090 		return (1);
3091 	}
3092 
3093 	/*
3094 	 * At this point we have a list of import candidate configs. Even if
3095 	 * we were searching by pool name or guid, we still need to
3096 	 * post-process the list to deal with pool state and possible
3097 	 * duplicate names.
3098 	 */
3099 	err = 0;
3100 	elem = NULL;
3101 	first = B_TRUE;
3102 	while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3103 
3104 		verify(nvpair_value_nvlist(elem, &config) == 0);
3105 
3106 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3107 		    &pool_state) == 0);
3108 		if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
3109 			continue;
3110 		if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
3111 			continue;
3112 
3113 		verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
3114 		    policy) == 0);
3115 
3116 		if (argc == 0) {
3117 			if (first)
3118 				first = B_FALSE;
3119 			else if (!do_all)
3120 				(void) printf("\n");
3121 
3122 			if (do_all) {
3123 				err |= do_import(config, NULL, mntopts,
3124 				    props, flags);
3125 			} else {
3126 				show_import(config);
3127 			}
3128 		} else if (searchname != NULL) {
3129 			char *name;
3130 
3131 			/*
3132 			 * We are searching for a pool based on name.
3133 			 */
3134 			verify(nvlist_lookup_string(config,
3135 			    ZPOOL_CONFIG_POOL_NAME, &name) == 0);
3136 
3137 			if (strcmp(name, searchname) == 0) {
3138 				if (found_config != NULL) {
3139 					(void) fprintf(stderr, gettext(
3140 					    "cannot import '%s': more than "
3141 					    "one matching pool\n"), searchname);
3142 					(void) fprintf(stderr, gettext(
3143 					    "import by numeric ID instead\n"));
3144 					err = B_TRUE;
3145 				}
3146 				found_config = config;
3147 			}
3148 		} else {
3149 			uint64_t guid;
3150 
3151 			/*
3152 			 * Search for a pool by guid.
3153 			 */
3154 			verify(nvlist_lookup_uint64(config,
3155 			    ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
3156 
3157 			if (guid == searchguid)
3158 				found_config = config;
3159 		}
3160 	}
3161 
3162 	/*
3163 	 * If we were searching for a specific pool, verify that we found a
3164 	 * pool, and then do the import.
3165 	 */
3166 	if (argc != 0 && err == 0) {
3167 		if (found_config == NULL) {
3168 			(void) fprintf(stderr, gettext("cannot import '%s': "
3169 			    "no such pool available\n"), argv[0]);
3170 			err = B_TRUE;
3171 		} else {
3172 			err |= do_import(found_config, argc == 1 ? NULL :
3173 			    argv[1], mntopts, props, flags);
3174 		}
3175 	}
3176 
3177 	/*
3178 	 * If we were just looking for pools, report an error if none were
3179 	 * found.
3180 	 */
3181 	if (argc == 0 && first)
3182 		(void) fprintf(stderr,
3183 		    gettext("no pools available to import\n"));
3184 
3185 error:
3186 	nvlist_free(props);
3187 	nvlist_free(pools);
3188 	nvlist_free(policy);
3189 	free(searchdirs);
3190 
3191 	return (err ? 1 : 0);
3192 }
3193 
3194 /*
3195  * zpool sync [-f] [pool] ...
3196  *
3197  * -f (undocumented) force uberblock (and config including zpool cache file)
3198  *    update.
3199  *
3200  * Sync the specified pool(s).
3201  * Without arguments "zpool sync" will sync all pools.
3202  * This command initiates TXG sync(s) and will return after the TXG(s) commit.
3203  *
3204  */
3205 static int
3206 zpool_do_sync(int argc, char **argv)
3207 {
3208 	int ret;
3209 	boolean_t force = B_FALSE;
3210 
3211 	/* check options */
3212 	while ((ret  = getopt(argc, argv, "f")) != -1) {
3213 		switch (ret) {
3214 		case 'f':
3215 			force = B_TRUE;
3216 			break;
3217 		case '?':
3218 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3219 			    optopt);
3220 			usage(B_FALSE);
3221 		}
3222 	}
3223 
3224 	argc -= optind;
3225 	argv += optind;
3226 
3227 	/* if argc == 0 we will execute zpool_sync_one on all pools */
3228 	ret = for_each_pool(argc, argv, B_FALSE, NULL, zpool_sync_one, &force);
3229 
3230 	return (ret);
3231 }
3232 
3233 typedef struct iostat_cbdata {
3234 	uint64_t cb_flags;
3235 	int cb_name_flags;
3236 	int cb_namewidth;
3237 	int cb_iteration;
3238 	char **cb_vdev_names; /* Only show these vdevs */
3239 	unsigned int cb_vdev_names_count;
3240 	boolean_t cb_verbose;
3241 	boolean_t cb_literal;
3242 	boolean_t cb_scripted;
3243 	zpool_list_t *cb_list;
3244 } iostat_cbdata_t;
3245 
3246 /*  iostat labels */
3247 typedef struct name_and_columns {
3248 	const char *name;	/* Column name */
3249 	unsigned int columns;	/* Center name to this number of columns */
3250 } name_and_columns_t;
3251 
3252 #define	IOSTAT_MAX_LABELS	13	/* Max number of labels on one line */
3253 
3254 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
3255 {
3256 	[IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
3257 	    {NULL}},
3258 	[IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
3259 	    {"asyncq_wait", 2}, {"scrub"}, {"trim", 1}, {NULL}},
3260 	[IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
3261 	    {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
3262 	    {"trimq_write", 2}, {NULL}},
3263 	[IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
3264 	    {"asyncq_wait", 2}, {NULL}},
3265 	[IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
3266 	    {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
3267 	    {"trim", 2}, {NULL}},
3268 
3269 };
3270 
3271 /* Shorthand - if "columns" field not set, default to 1 column */
3272 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
3273 {
3274 	[IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
3275 	    {"write"}, {NULL}},
3276 	[IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
3277 	    {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {NULL}},
3278 	[IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
3279 	    {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
3280 	    {"pend"}, {"activ"}, {NULL}},
3281 	[IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
3282 	    {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {NULL}},
3283 	[IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
3284 	    {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"}, {NULL}},
3285 };
3286 
3287 static const char *histo_to_title[] = {
3288 	[IOS_L_HISTO] = "latency",
3289 	[IOS_RQ_HISTO] = "req_size",
3290 };
3291 
3292 /*
3293  * Return the number of labels in a null-terminated name_and_columns_t
3294  * array.
3295  *
3296  */
3297 static unsigned int
3298 label_array_len(const name_and_columns_t *labels)
3299 {
3300 	int i = 0;
3301 
3302 	while (labels[i].name)
3303 		i++;
3304 
3305 	return (i);
3306 }
3307 
3308 /*
3309  * Return the number of strings in a null-terminated string array.
3310  * For example:
3311  *
3312  *     const char foo[] = {"bar", "baz", NULL}
3313  *
3314  * returns 2
3315  */
3316 static uint64_t
3317 str_array_len(const char *array[])
3318 {
3319 	uint64_t i = 0;
3320 	while (array[i])
3321 		i++;
3322 
3323 	return (i);
3324 }
3325 
3326 
3327 /*
3328  * Return a default column width for default/latency/queue columns. This does
3329  * not include histograms, which have their columns autosized.
3330  */
3331 static unsigned int
3332 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
3333 {
3334 	unsigned long column_width = 5; /* Normal niceprint */
3335 	static unsigned long widths[] = {
3336 		/*
3337 		 * Choose some sane default column sizes for printing the
3338 		 * raw numbers.
3339 		 */
3340 		[IOS_DEFAULT] = 15, /* 1PB capacity */
3341 		[IOS_LATENCY] = 10, /* 1B ns = 10sec */
3342 		[IOS_QUEUES] = 6,   /* 1M queue entries */
3343 		[IOS_L_HISTO] = 10, /* 1B ns = 10sec */
3344 		[IOS_RQ_HISTO] = 6, /* 1M queue entries */
3345 	};
3346 
3347 	if (cb->cb_literal)
3348 		column_width = widths[type];
3349 
3350 	return (column_width);
3351 }
3352 
3353 /*
3354  * Print the column labels, i.e:
3355  *
3356  *   capacity     operations     bandwidth
3357  * alloc   free   read  write   read  write  ...
3358  *
3359  * If force_column_width is set, use it for the column width.  If not set, use
3360  * the default column width.
3361  */
3362 void
3363 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
3364     const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
3365 {
3366 	int i, idx, s;
3367 	int text_start, rw_column_width, spaces_to_end;
3368 	uint64_t flags = cb->cb_flags;
3369 	uint64_t f;
3370 	unsigned int column_width = force_column_width;
3371 
3372 	/* For each bit set in flags */
3373 	for (f = flags; f; f &= ~(1ULL << idx)) {
3374 		idx = lowbit64(f) - 1;
3375 		if (!force_column_width)
3376 			column_width = default_column_width(cb, idx);
3377 		/* Print our top labels centered over "read  write" label. */
3378 		for (i = 0; i < label_array_len(labels[idx]); i++) {
3379 			const char *name = labels[idx][i].name;
3380 			/*
3381 			 * We treat labels[][].columns == 0 as shorthand
3382 			 * for one column.  It makes writing out the label
3383 			 * tables more concise.
3384 			 */
3385 			unsigned int columns = MAX(1, labels[idx][i].columns);
3386 			unsigned int slen = strlen(name);
3387 
3388 			rw_column_width = (column_width * columns) +
3389 			    (2 * (columns - 1));
3390 
3391 			text_start = (int)((rw_column_width) / columns -
3392 			    slen / columns);
3393 			if (text_start < 0)
3394 				text_start = 0;
3395 
3396 			printf("  ");	/* Two spaces between columns */
3397 
3398 			/* Space from beginning of column to label */
3399 			for (s = 0; s < text_start; s++)
3400 				printf(" ");
3401 
3402 			printf("%s", name);
3403 
3404 			/* Print space after label to end of column */
3405 			spaces_to_end = rw_column_width - text_start - slen;
3406 			if (spaces_to_end < 0)
3407 				spaces_to_end = 0;
3408 
3409 			for (s = 0; s < spaces_to_end; s++)
3410 				printf(" ");
3411 		}
3412 	}
3413 }
3414 
3415 /*
3416  * Utility function to print out a line of dashes like:
3417  *
3418  *	--------------------------------  -----  -----  -----  -----  -----
3419  *
3420  * ...or a dashed named-row line like:
3421  *
3422  *	logs                                  -      -      -      -      -
3423  *
3424  * @cb:				iostat data
3425  *
3426  * @force_column_width		If non-zero, use the value as the column width.
3427  *				Otherwise use the default column widths.
3428  *
3429  * @name:			Print a dashed named-row line starting
3430  *				with @name.  Otherwise, print a regular
3431  *				dashed line.
3432  */
3433 static void
3434 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
3435     const char *name)
3436 {
3437 	int i;
3438 	unsigned int namewidth;
3439 	uint64_t flags = cb->cb_flags;
3440 	uint64_t f;
3441 	int idx;
3442 	const name_and_columns_t *labels;
3443 	const char *title;
3444 
3445 
3446 	if (cb->cb_flags & IOS_ANYHISTO_M) {
3447 		title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
3448 	} else if (cb->cb_vdev_names_count) {
3449 		title = "vdev";
3450 	} else  {
3451 		title = "pool";
3452 	}
3453 
3454 	namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
3455 	    name ? strlen(name) : 0);
3456 
3457 
3458 	if (name) {
3459 		printf("%-*s", namewidth, name);
3460 	} else {
3461 		for (i = 0; i < namewidth; i++)
3462 			(void) printf("-");
3463 	}
3464 
3465 	/* For each bit in flags */
3466 	for (f = flags; f; f &= ~(1ULL << idx)) {
3467 		unsigned int column_width;
3468 		idx = lowbit64(f) - 1;
3469 		if (force_column_width)
3470 			column_width = force_column_width;
3471 		else
3472 			column_width = default_column_width(cb, idx);
3473 
3474 		labels = iostat_bottom_labels[idx];
3475 		for (i = 0; i < label_array_len(labels); i++) {
3476 			if (name)
3477 				printf("  %*s-", column_width - 1, " ");
3478 			else
3479 				printf("  %.*s", column_width,
3480 				    "--------------------");
3481 		}
3482 	}
3483 }
3484 
3485 
3486 static void
3487 print_iostat_separator_impl(iostat_cbdata_t *cb,
3488     unsigned int force_column_width)
3489 {
3490 	print_iostat_dashes(cb, force_column_width, NULL);
3491 }
3492 
3493 static void
3494 print_iostat_separator(iostat_cbdata_t *cb)
3495 {
3496 	print_iostat_separator_impl(cb, 0);
3497 }
3498 
3499 static void
3500 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
3501     const char *histo_vdev_name)
3502 {
3503 	unsigned int namewidth;
3504 	const char *title;
3505 
3506 	if (cb->cb_flags & IOS_ANYHISTO_M) {
3507 		title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
3508 	} else if (cb->cb_vdev_names_count) {
3509 		title = "vdev";
3510 	} else  {
3511 		title = "pool";
3512 	}
3513 
3514 	namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
3515 	    histo_vdev_name ? strlen(histo_vdev_name) : 0);
3516 
3517 	if (histo_vdev_name)
3518 		printf("%-*s", namewidth, histo_vdev_name);
3519 	else
3520 		printf("%*s", namewidth, "");
3521 
3522 
3523 	print_iostat_labels(cb, force_column_width, iostat_top_labels);
3524 	printf("\n");
3525 
3526 	printf("%-*s", namewidth, title);
3527 
3528 	print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
3529 
3530 	printf("\n");
3531 
3532 	print_iostat_separator_impl(cb, force_column_width);
3533 
3534 	printf("\n");
3535 }
3536 
3537 static void
3538 print_iostat_header(iostat_cbdata_t *cb)
3539 {
3540 	print_iostat_header_impl(cb, 0, NULL);
3541 }
3542 
3543 /*
3544  * Display a single statistic.
3545  */
3546 static void
3547 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
3548     unsigned int column_size, boolean_t scripted)
3549 {
3550 	char buf[64];
3551 
3552 	zfs_nicenum_format(value, buf, sizeof (buf), format);
3553 
3554 	if (scripted)
3555 		printf("\t%s", buf);
3556 	else
3557 		printf("  %*s", column_size, buf);
3558 }
3559 
3560 /*
3561  * Calculate the default vdev stats
3562  *
3563  * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
3564  * stats into calcvs.
3565  */
3566 static void
3567 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
3568     vdev_stat_t *calcvs)
3569 {
3570 	int i;
3571 
3572 	memcpy(calcvs, newvs, sizeof (*calcvs));
3573 	for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
3574 		calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
3575 
3576 	for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
3577 		calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
3578 }
3579 
3580 /*
3581  * Internal representation of the extended iostats data.
3582  *
3583  * The extended iostat stats are exported in nvlists as either uint64_t arrays
3584  * or single uint64_t's.  We make both look like arrays to make them easier
3585  * to process.  In order to make single uint64_t's look like arrays, we set
3586  * __data to the stat data, and then set *data = &__data with count = 1.  Then,
3587  * we can just use *data and count.
3588  */
3589 struct stat_array {
3590 	uint64_t *data;
3591 	uint_t count;	/* Number of entries in data[] */
3592 	uint64_t __data; /* Only used when data is a single uint64_t */
3593 };
3594 
3595 static uint64_t
3596 stat_histo_max(struct stat_array *nva, unsigned int len)
3597 {
3598 	uint64_t max = 0;
3599 	int i;
3600 	for (i = 0; i < len; i++)
3601 		max = MAX(max, array64_max(nva[i].data, nva[i].count));
3602 
3603 	return (max);
3604 }
3605 
3606 /*
3607  * Helper function to lookup a uint64_t array or uint64_t value and store its
3608  * data as a stat_array.  If the nvpair is a single uint64_t value, then we make
3609  * it look like a one element array to make it easier to process.
3610  */
3611 static int
3612 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
3613     struct stat_array *nva)
3614 {
3615 	nvpair_t *tmp;
3616 	int ret;
3617 
3618 	verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
3619 	switch (nvpair_type(tmp)) {
3620 	case DATA_TYPE_UINT64_ARRAY:
3621 		ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
3622 		break;
3623 	case DATA_TYPE_UINT64:
3624 		ret = nvpair_value_uint64(tmp, &nva->__data);
3625 		nva->data = &nva->__data;
3626 		nva->count = 1;
3627 		break;
3628 	default:
3629 		/* Not a uint64_t */
3630 		ret = EINVAL;
3631 		break;
3632 	}
3633 
3634 	return (ret);
3635 }
3636 
3637 /*
3638  * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
3639  * subtract them, and return the results in a newly allocated stat_array.
3640  * You must free the returned array after you are done with it with
3641  * free_calc_stats().
3642  *
3643  * Additionally, you can set "oldnv" to NULL if you simply want the newnv
3644  * values.
3645  */
3646 static struct stat_array *
3647 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
3648     nvlist_t *newnv)
3649 {
3650 	nvlist_t *oldnvx = NULL, *newnvx;
3651 	struct stat_array *oldnva, *newnva, *calcnva;
3652 	int i, j;
3653 	unsigned int alloc_size = (sizeof (struct stat_array)) * len;
3654 
3655 	/* Extract our extended stats nvlist from the main list */
3656 	verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
3657 	    &newnvx) == 0);
3658 	if (oldnv) {
3659 		verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
3660 		    &oldnvx) == 0);
3661 	}
3662 
3663 	newnva = safe_malloc(alloc_size);
3664 	oldnva = safe_malloc(alloc_size);
3665 	calcnva = safe_malloc(alloc_size);
3666 
3667 	for (j = 0; j < len; j++) {
3668 		verify(nvpair64_to_stat_array(newnvx, names[j],
3669 		    &newnva[j]) == 0);
3670 		calcnva[j].count = newnva[j].count;
3671 		alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
3672 		calcnva[j].data = safe_malloc(alloc_size);
3673 		memcpy(calcnva[j].data, newnva[j].data, alloc_size);
3674 
3675 		if (oldnvx) {
3676 			verify(nvpair64_to_stat_array(oldnvx, names[j],
3677 			    &oldnva[j]) == 0);
3678 			for (i = 0; i < oldnva[j].count; i++)
3679 				calcnva[j].data[i] -= oldnva[j].data[i];
3680 		}
3681 	}
3682 	free(newnva);
3683 	free(oldnva);
3684 	return (calcnva);
3685 }
3686 
3687 static void
3688 free_calc_stats(struct stat_array *nva, unsigned int len)
3689 {
3690 	int i;
3691 	for (i = 0; i < len; i++)
3692 		free(nva[i].data);
3693 
3694 	free(nva);
3695 }
3696 
3697 static void
3698 print_iostat_histo(struct stat_array *nva, unsigned int len,
3699     iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
3700     double scale)
3701 {
3702 	int i, j;
3703 	char buf[6];
3704 	uint64_t val;
3705 	enum zfs_nicenum_format format;
3706 	unsigned int buckets;
3707 	unsigned int start_bucket;
3708 
3709 	if (cb->cb_literal)
3710 		format = ZFS_NICENUM_RAW;
3711 	else
3712 		format = ZFS_NICENUM_1024;
3713 
3714 	/* All these histos are the same size, so just use nva[0].count */
3715 	buckets = nva[0].count;
3716 
3717 	if (cb->cb_flags & IOS_RQ_HISTO_M) {
3718 		/* Start at 512 - req size should never be lower than this */
3719 		start_bucket = 9;
3720 	} else {
3721 		start_bucket = 0;
3722 	}
3723 
3724 	for (j = start_bucket; j < buckets; j++) {
3725 		/* Print histogram bucket label */
3726 		if (cb->cb_flags & IOS_L_HISTO_M) {
3727 			/* Ending range of this bucket */
3728 			val = (1ULL << (j + 1)) - 1;
3729 			zfs_nicetime(val, buf, sizeof (buf));
3730 		} else {
3731 			/* Request size (starting range of bucket) */
3732 			val = (1UL << j);
3733 			zfs_nicenum(val, buf, sizeof (buf));
3734 		}
3735 
3736 		if (cb->cb_scripted)
3737 			printf("%llu", (u_longlong_t)val);
3738 		else
3739 			printf("%-*s", namewidth, buf);
3740 
3741 		/* Print the values on the line */
3742 		for (i = 0; i < len; i++) {
3743 			print_one_stat(nva[i].data[j] * scale, format,
3744 			    column_width, cb->cb_scripted);
3745 		}
3746 		printf("\n");
3747 	}
3748 }
3749 
3750 static void
3751 print_solid_separator(unsigned int length)
3752 {
3753 	while (length--)
3754 		printf("-");
3755 	printf("\n");
3756 }
3757 
3758 static void
3759 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
3760     nvlist_t *newnv, double scale, const char *name)
3761 {
3762 	unsigned int column_width;
3763 	unsigned int namewidth;
3764 	unsigned int entire_width;
3765 	enum iostat_type type;
3766 	struct stat_array *nva;
3767 	const char **names;
3768 	unsigned int names_len;
3769 
3770 	/* What type of histo are we? */
3771 	type = IOS_HISTO_IDX(cb->cb_flags);
3772 
3773 	/* Get NULL-terminated array of nvlist names for our histo */
3774 	names = vsx_type_to_nvlist[type];
3775 	names_len = str_array_len(names); /* num of names */
3776 
3777 	nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
3778 
3779 	if (cb->cb_literal) {
3780 		column_width = MAX(5,
3781 		    (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
3782 	} else {
3783 		column_width = 5;
3784 	}
3785 
3786 	namewidth = MAX(cb->cb_namewidth,
3787 	    strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
3788 
3789 	/*
3790 	 * Calculate the entire line width of what we're printing.  The
3791 	 * +2 is for the two spaces between columns:
3792 	 */
3793 	/*	 read  write				*/
3794 	/*	-----  -----				*/
3795 	/*	|___|  <---------- column_width		*/
3796 	/*						*/
3797 	/*	|__________|  <--- entire_width		*/
3798 	/*						*/
3799 	entire_width = namewidth + (column_width + 2) *
3800 	    label_array_len(iostat_bottom_labels[type]);
3801 
3802 	if (cb->cb_scripted)
3803 		printf("%s\n", name);
3804 	else
3805 		print_iostat_header_impl(cb, column_width, name);
3806 
3807 	print_iostat_histo(nva, names_len, cb, column_width,
3808 	    namewidth, scale);
3809 
3810 	free_calc_stats(nva, names_len);
3811 	if (!cb->cb_scripted)
3812 		print_solid_separator(entire_width);
3813 }
3814 
3815 /*
3816  * Calculate the average latency of a power-of-two latency histogram
3817  */
3818 static uint64_t
3819 single_histo_average(uint64_t *histo, unsigned int buckets)
3820 {
3821 	int i;
3822 	uint64_t count = 0, total = 0;
3823 
3824 	for (i = 0; i < buckets; i++) {
3825 		/*
3826 		 * Our buckets are power-of-two latency ranges.  Use the
3827 		 * midpoint latency of each bucket to calculate the average.
3828 		 * For example:
3829 		 *
3830 		 * Bucket	Midpoint
3831 		 * 8ns-15ns:	12ns
3832 		 * 16ns-31ns:	24ns
3833 		 * ...
3834 		 */
3835 		if (histo[i] != 0) {
3836 			total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
3837 			count += histo[i];
3838 		}
3839 	}
3840 
3841 	/* Prevent divide by zero */
3842 	return (count == 0 ? 0 : total / count);
3843 }
3844 
3845 static void
3846 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *oldnv,
3847     nvlist_t *newnv)
3848 {
3849 	int i;
3850 	uint64_t val;
3851 	const char *names[] = {
3852 		ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
3853 		ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
3854 		ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
3855 		ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
3856 		ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
3857 		ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
3858 		ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
3859 		ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
3860 		ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
3861 		ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
3862 		ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
3863 		ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
3864 	};
3865 
3866 	struct stat_array *nva;
3867 
3868 	unsigned int column_width = default_column_width(cb, IOS_QUEUES);
3869 	enum zfs_nicenum_format format;
3870 
3871 	nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
3872 
3873 	if (cb->cb_literal)
3874 		format = ZFS_NICENUM_RAW;
3875 	else
3876 		format = ZFS_NICENUM_1024;
3877 
3878 	for (i = 0; i < ARRAY_SIZE(names); i++) {
3879 		val = nva[i].data[0];
3880 		print_one_stat(val, format, column_width, cb->cb_scripted);
3881 	}
3882 
3883 	free_calc_stats(nva, ARRAY_SIZE(names));
3884 }
3885 
3886 static void
3887 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
3888     nvlist_t *newnv)
3889 {
3890 	int i;
3891 	uint64_t val;
3892 	const char *names[] = {
3893 		ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
3894 		ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
3895 		ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
3896 		ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
3897 		ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
3898 		ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
3899 		ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
3900 		ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
3901 		ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
3902 		ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
3903 	};
3904 	struct stat_array *nva;
3905 
3906 	unsigned int column_width = default_column_width(cb, IOS_LATENCY);
3907 	enum zfs_nicenum_format format;
3908 
3909 	nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
3910 
3911 	if (cb->cb_literal)
3912 		format = ZFS_NICENUM_RAWTIME;
3913 	else
3914 		format = ZFS_NICENUM_TIME;
3915 
3916 	/* Print our avg latencies on the line */
3917 	for (i = 0; i < ARRAY_SIZE(names); i++) {
3918 		/* Compute average latency for a latency histo */
3919 		val = single_histo_average(nva[i].data, nva[i].count);
3920 		print_one_stat(val, format, column_width, cb->cb_scripted);
3921 	}
3922 	free_calc_stats(nva, ARRAY_SIZE(names));
3923 }
3924 
3925 /*
3926  * Print default statistics (capacity/operations/bandwidth)
3927  */
3928 static void
3929 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
3930 {
3931 	unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
3932 	enum zfs_nicenum_format format;
3933 	char na;	/* char to print for "not applicable" values */
3934 
3935 	if (cb->cb_literal) {
3936 		format = ZFS_NICENUM_RAW;
3937 		na = '0';
3938 	} else {
3939 		format = ZFS_NICENUM_1024;
3940 		na = '-';
3941 	}
3942 
3943 	/* only toplevel vdevs have capacity stats */
3944 	if (vs->vs_space == 0) {
3945 		if (cb->cb_scripted)
3946 			printf("\t%c\t%c", na, na);
3947 		else
3948 			printf("  %*c  %*c", column_width, na, column_width,
3949 			    na);
3950 	} else {
3951 		print_one_stat(vs->vs_alloc, format, column_width,
3952 		    cb->cb_scripted);
3953 		print_one_stat(vs->vs_space - vs->vs_alloc, format,
3954 		    column_width, cb->cb_scripted);
3955 	}
3956 
3957 	print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
3958 	    format, column_width, cb->cb_scripted);
3959 	print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
3960 	    format, column_width, cb->cb_scripted);
3961 	print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
3962 	    format, column_width, cb->cb_scripted);
3963 	print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
3964 	    format, column_width, cb->cb_scripted);
3965 }
3966 
3967 static const char *class_name[] = {
3968 	VDEV_ALLOC_BIAS_DEDUP,
3969 	VDEV_ALLOC_BIAS_SPECIAL,
3970 	VDEV_ALLOC_CLASS_LOGS
3971 };
3972 
3973 /*
3974  * Print out all the statistics for the given vdev.  This can either be the
3975  * toplevel configuration, or called recursively.  If 'name' is NULL, then this
3976  * is a verbose output, and we don't want to display the toplevel pool stats.
3977  *
3978  * Returns the number of stat lines printed.
3979  */
3980 unsigned int
3981 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
3982     nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
3983 {
3984 	nvlist_t **oldchild, **newchild;
3985 	uint_t c, children, oldchildren;
3986 	vdev_stat_t *oldvs, *newvs, *calcvs;
3987 	vdev_stat_t zerovs = { 0 };
3988 	char *vname;
3989 	int i;
3990 	int ret = 0;
3991 	uint64_t tdelta;
3992 	double scale;
3993 
3994 	if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
3995 		return (0);
3996 
3997 	calcvs = safe_malloc(sizeof (*calcvs));
3998 
3999 	if (oldnv != NULL) {
4000 		verify(nvlist_lookup_uint64_array(oldnv,
4001 		    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
4002 	} else {
4003 		oldvs = &zerovs;
4004 	}
4005 
4006 	/* Do we only want to see a specific vdev? */
4007 	for (i = 0; i < cb->cb_vdev_names_count; i++) {
4008 		/* Yes we do.  Is this the vdev? */
4009 		if (strcmp(name, cb->cb_vdev_names[i]) == 0) {
4010 			/*
4011 			 * This is our vdev.  Since it is the only vdev we
4012 			 * will be displaying, make depth = 0 so that it
4013 			 * doesn't get indented.
4014 			 */
4015 			depth = 0;
4016 			break;
4017 		}
4018 	}
4019 
4020 	if (cb->cb_vdev_names_count && (i == cb->cb_vdev_names_count)) {
4021 		/* Couldn't match the name */
4022 		goto children;
4023 	}
4024 
4025 
4026 	verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
4027 	    (uint64_t **)&newvs, &c) == 0);
4028 
4029 	/*
4030 	 * Print the vdev name unless it's is a histogram.  Histograms
4031 	 * display the vdev name in the header itself.
4032 	 */
4033 	if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
4034 		if (cb->cb_scripted) {
4035 			printf("%s", name);
4036 		} else {
4037 			if (strlen(name) + depth > cb->cb_namewidth)
4038 				(void) printf("%*s%s", depth, "", name);
4039 			else
4040 				(void) printf("%*s%s%*s", depth, "", name,
4041 				    (int)(cb->cb_namewidth - strlen(name) -
4042 				    depth), "");
4043 		}
4044 	}
4045 
4046 	/* Calculate our scaling factor */
4047 	tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
4048 	if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
4049 		/*
4050 		 * If we specify printing histograms with no time interval, then
4051 		 * print the histogram numbers over the entire lifetime of the
4052 		 * vdev.
4053 		 */
4054 		scale = 1;
4055 	} else {
4056 		if (tdelta == 0)
4057 			scale = 1.0;
4058 		else
4059 			scale = (double)NANOSEC / tdelta;
4060 	}
4061 
4062 	if (cb->cb_flags & IOS_DEFAULT_M) {
4063 		calc_default_iostats(oldvs, newvs, calcvs);
4064 		print_iostat_default(calcvs, cb, scale);
4065 	}
4066 	if (cb->cb_flags & IOS_LATENCY_M)
4067 		print_iostat_latency(cb, oldnv, newnv);
4068 	if (cb->cb_flags & IOS_QUEUES_M)
4069 		print_iostat_queues(cb, oldnv, newnv);
4070 	if (cb->cb_flags & IOS_ANYHISTO_M) {
4071 		printf("\n");
4072 		print_iostat_histos(cb, oldnv, newnv, scale, name);
4073 	}
4074 
4075 	if (!(cb->cb_flags & IOS_ANYHISTO_M))
4076 		printf("\n");
4077 
4078 	ret++;
4079 
4080 children:
4081 
4082 	free(calcvs);
4083 
4084 	if (!cb->cb_verbose)
4085 		return (ret);
4086 
4087 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
4088 	    &newchild, &children) != 0)
4089 		return (ret);
4090 
4091 	if (oldnv) {
4092 		if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
4093 		    &oldchild, &oldchildren) != 0)
4094 			return (ret);
4095 
4096 		children = MIN(oldchildren, children);
4097 	}
4098 
4099 	/*
4100 	 * print normal top-level devices
4101 	 */
4102 	for (c = 0; c < children; c++) {
4103 		uint64_t ishole = B_FALSE, islog = B_FALSE;
4104 
4105 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
4106 		    &ishole);
4107 
4108 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
4109 		    &islog);
4110 
4111 		if (ishole || islog)
4112 			continue;
4113 
4114 		if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
4115 			continue;
4116 
4117 		vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4118 		    cb->cb_name_flags);
4119 		ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
4120 		    newchild[c], cb, depth + 2);
4121 		free(vname);
4122 	}
4123 
4124 	/*
4125 	 * print all other top-level devices
4126 	 */
4127 	for (uint_t n = 0; n < 3; n++) {
4128 		boolean_t printed = B_FALSE;
4129 
4130 		for (c = 0; c < children; c++) {
4131 			uint64_t islog = B_FALSE;
4132 			char *bias = NULL;
4133 			char *type = NULL;
4134 
4135 			(void) nvlist_lookup_uint64(newchild[c],
4136 			    ZPOOL_CONFIG_IS_LOG, &islog);
4137 			if (islog) {
4138 				bias = VDEV_ALLOC_CLASS_LOGS;
4139 			} else {
4140 				(void) nvlist_lookup_string(newchild[c],
4141 				    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
4142 				(void) nvlist_lookup_string(newchild[c],
4143 				    ZPOOL_CONFIG_TYPE, &type);
4144 			}
4145 			if (bias == NULL || strcmp(bias, class_name[n]) != 0)
4146 				continue;
4147 			if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
4148 				continue;
4149 
4150 			if (!printed) {
4151 				if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
4152 				    !cb->cb_scripted && !cb->cb_vdev_names) {
4153 					print_iostat_dashes(cb, 0,
4154 					    class_name[n]);
4155 				}
4156 				printf("\n");
4157 				printed = B_TRUE;
4158 			}
4159 
4160 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4161 			    cb->cb_name_flags);
4162 			ret += print_vdev_stats(zhp, vname, oldnv ?
4163 			    oldchild[c] : NULL, newchild[c], cb, depth + 2);
4164 			free(vname);
4165 		}
4166 
4167 	}
4168 
4169 	/*
4170 	 * Include level 2 ARC devices in iostat output
4171 	 */
4172 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
4173 	    &newchild, &children) != 0)
4174 		return (ret);
4175 
4176 	if (oldnv) {
4177 		if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
4178 		    &oldchild, &oldchildren) != 0)
4179 			return (ret);
4180 
4181 		children = MIN(oldchildren, children);
4182 	}
4183 
4184 	if (children > 0) {
4185 		if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
4186 		    !cb->cb_vdev_names) {
4187 			print_iostat_dashes(cb, 0, "cache");
4188 		}
4189 		printf("\n");
4190 
4191 		for (c = 0; c < children; c++) {
4192 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4193 			    cb->cb_name_flags);
4194 			ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
4195 			    : NULL, newchild[c], cb, depth + 2);
4196 			free(vname);
4197 		}
4198 	}
4199 
4200 	return (ret);
4201 }
4202 
4203 static int
4204 refresh_iostat(zpool_handle_t *zhp, void *data)
4205 {
4206 	iostat_cbdata_t *cb = data;
4207 	boolean_t missing;
4208 
4209 	/*
4210 	 * If the pool has disappeared, remove it from the list and continue.
4211 	 */
4212 	if (zpool_refresh_stats(zhp, &missing) != 0)
4213 		return (-1);
4214 
4215 	if (missing)
4216 		pool_list_remove(cb->cb_list, zhp);
4217 
4218 	return (0);
4219 }
4220 
4221 /*
4222  * Callback to print out the iostats for the given pool.
4223  */
4224 int
4225 print_iostat(zpool_handle_t *zhp, void *data)
4226 {
4227 	iostat_cbdata_t *cb = data;
4228 	nvlist_t *oldconfig, *newconfig;
4229 	nvlist_t *oldnvroot, *newnvroot;
4230 	int ret;
4231 
4232 	newconfig = zpool_get_config(zhp, &oldconfig);
4233 
4234 	if (cb->cb_iteration == 1)
4235 		oldconfig = NULL;
4236 
4237 	verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
4238 	    &newnvroot) == 0);
4239 
4240 	if (oldconfig == NULL)
4241 		oldnvroot = NULL;
4242 	else
4243 		verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
4244 		    &oldnvroot) == 0);
4245 
4246 	ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
4247 	    cb, 0);
4248 	if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
4249 	    !cb->cb_scripted && cb->cb_verbose && !cb->cb_vdev_names_count) {
4250 		print_iostat_separator(cb);
4251 		printf("\n");
4252 	}
4253 
4254 	return (ret);
4255 }
4256 
4257 static int
4258 get_columns(void)
4259 {
4260 	struct winsize ws;
4261 	int columns = 80;
4262 	int error;
4263 
4264 	if (isatty(STDOUT_FILENO)) {
4265 		error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
4266 		if (error == 0)
4267 			columns = ws.ws_col;
4268 	} else {
4269 		columns = 999;
4270 	}
4271 
4272 	return (columns);
4273 }
4274 
4275 /*
4276  * Return the required length of the pool/vdev name column.  The minimum
4277  * allowed width and output formatting flags must be provided.
4278  */
4279 static int
4280 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
4281 {
4282 	nvlist_t *config, *nvroot;
4283 	int width = min_width;
4284 
4285 	if ((config = zpool_get_config(zhp, NULL)) != NULL) {
4286 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4287 		    &nvroot) == 0);
4288 		unsigned int poolname_len = strlen(zpool_get_name(zhp));
4289 		if (verbose == B_FALSE) {
4290 			width = MAX(poolname_len, min_width);
4291 		} else {
4292 			width = MAX(poolname_len,
4293 			    max_width(zhp, nvroot, 0, min_width, flags));
4294 		}
4295 	}
4296 
4297 	return (width);
4298 }
4299 
4300 /*
4301  * Parse the input string, get the 'interval' and 'count' value if there is one.
4302  */
4303 static void
4304 get_interval_count(int *argcp, char **argv, float *iv,
4305     unsigned long *cnt)
4306 {
4307 	float interval = 0;
4308 	unsigned long count = 0;
4309 	int argc = *argcp, errno;
4310 
4311 	/*
4312 	 * Determine if the last argument is an integer or a pool name
4313 	 */
4314 	if (argc > 0 && isnumber(argv[argc - 1])) {
4315 		char *end;
4316 
4317 		errno = 0;
4318 		interval = strtof(argv[argc - 1], &end);
4319 
4320 		if (*end == '\0' && errno == 0) {
4321 			if (interval == 0) {
4322 				(void) fprintf(stderr, gettext("interval "
4323 				    "cannot be zero\n"));
4324 				usage(B_FALSE);
4325 			}
4326 			/*
4327 			 * Ignore the last parameter
4328 			 */
4329 			argc--;
4330 		} else {
4331 			/*
4332 			 * If this is not a valid number, just plow on.  The
4333 			 * user will get a more informative error message later
4334 			 * on.
4335 			 */
4336 			interval = 0;
4337 		}
4338 	}
4339 
4340 	/*
4341 	 * If the last argument is also an integer, then we have both a count
4342 	 * and an interval.
4343 	 */
4344 	if (argc > 0 && isnumber(argv[argc - 1])) {
4345 		char *end;
4346 
4347 		errno = 0;
4348 		count = interval;
4349 		interval = strtof(argv[argc - 1], &end);
4350 
4351 		if (*end == '\0' && errno == 0) {
4352 			if (interval == 0) {
4353 				(void) fprintf(stderr, gettext("interval "
4354 				    "cannot be zero\n"));
4355 				usage(B_FALSE);
4356 			}
4357 
4358 			/*
4359 			 * Ignore the last parameter
4360 			 */
4361 			argc--;
4362 		} else {
4363 			interval = 0;
4364 		}
4365 	}
4366 
4367 	*iv = interval;
4368 	*cnt = count;
4369 	*argcp = argc;
4370 }
4371 
4372 static void
4373 get_timestamp_arg(char c)
4374 {
4375 	if (c == 'u')
4376 		timestamp_fmt = UDATE;
4377 	else if (c == 'd')
4378 		timestamp_fmt = DDATE;
4379 	else
4380 		usage(B_FALSE);
4381 }
4382 
4383 /*
4384  * Return stat flags that are supported by all pools by both the module and
4385  * zpool iostat.  "*data" should be initialized to all 0xFFs before running.
4386  * It will get ANDed down until only the flags that are supported on all pools
4387  * remain.
4388  */
4389 static int
4390 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
4391 {
4392 	uint64_t *mask = data;
4393 	nvlist_t *config, *nvroot, *nvx;
4394 	uint64_t flags = 0;
4395 	int i, j;
4396 
4397 	config = zpool_get_config(zhp, NULL);
4398 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4399 	    &nvroot) == 0);
4400 
4401 	/* Default stats are always supported, but for completeness.. */
4402 	if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
4403 		flags |= IOS_DEFAULT_M;
4404 
4405 	/* Get our extended stats nvlist from the main list */
4406 	if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
4407 	    &nvx) != 0) {
4408 		/*
4409 		 * No extended stats; they're probably running an older
4410 		 * module.  No big deal, we support that too.
4411 		 */
4412 		goto end;
4413 	}
4414 
4415 	/* For each extended stat, make sure all its nvpairs are supported */
4416 	for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
4417 		if (!vsx_type_to_nvlist[j][0])
4418 			continue;
4419 
4420 		/* Start off by assuming the flag is supported, then check */
4421 		flags |= (1ULL << j);
4422 		for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
4423 			if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
4424 				/* flag isn't supported */
4425 				flags = flags & ~(1ULL  << j);
4426 				break;
4427 			}
4428 		}
4429 	}
4430 end:
4431 	*mask = *mask & flags;
4432 	return (0);
4433 }
4434 
4435 /*
4436  * Return a bitmask of stats that are supported on all pools by both the module
4437  * and zpool iostat.
4438  */
4439 static uint64_t
4440 get_stat_flags(zpool_list_t *list)
4441 {
4442 	uint64_t mask = -1;
4443 
4444 	/*
4445 	 * get_stat_flags_cb() will lop off bits from "mask" until only the
4446 	 * flags that are supported on all pools remain.
4447 	 */
4448 	(void) pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
4449 	return (mask);
4450 }
4451 
4452 /*
4453  * Return 1 if cb_data->cb_vdev_names[0] is this vdev's name, 0 otherwise.
4454  */
4455 static int
4456 is_vdev_cb(zpool_handle_t *zhp, nvlist_t *nv, void *cb_data)
4457 {
4458 	iostat_cbdata_t *cb = cb_data;
4459 	char *name;
4460 
4461 	name = zpool_vdev_name(g_zfs, zhp, nv, cb->cb_name_flags);
4462 
4463 	if (strcmp(name, cb->cb_vdev_names[0]) == 0)
4464 		return (1); /* match */
4465 
4466 	return (0);
4467 }
4468 
4469 /*
4470  * Returns 1 if cb_data->cb_vdev_names[0] is a vdev name, 0 otherwise.
4471  */
4472 static int
4473 is_vdev(zpool_handle_t *zhp, void *cb_data)
4474 {
4475 	return (for_each_vdev(zhp, is_vdev_cb, cb_data));
4476 }
4477 
4478 /*
4479  * Check if vdevs are in a pool
4480  *
4481  * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
4482  * return 0.  If pool_name is NULL, then search all pools.
4483  */
4484 static int
4485 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
4486     iostat_cbdata_t *cb)
4487 {
4488 	char **tmp_name;
4489 	int ret = 0;
4490 	int i;
4491 	int pool_count = 0;
4492 
4493 	if ((argc == 0) || !*argv)
4494 		return (0);
4495 
4496 	if (pool_name)
4497 		pool_count = 1;
4498 
4499 	/* Temporarily hijack cb_vdev_names for a second... */
4500 	tmp_name = cb->cb_vdev_names;
4501 
4502 	/* Go though our list of prospective vdev names */
4503 	for (i = 0; i < argc; i++) {
4504 		cb->cb_vdev_names = argv + i;
4505 
4506 		/* Is this name a vdev in our pools? */
4507 		ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
4508 		    is_vdev, cb);
4509 		if (!ret) {
4510 			/* No match */
4511 			break;
4512 		}
4513 	}
4514 
4515 	cb->cb_vdev_names = tmp_name;
4516 
4517 	return (ret);
4518 }
4519 
4520 static int
4521 is_pool_cb(zpool_handle_t *zhp, void *data)
4522 {
4523 	char *name = data;
4524 	if (strcmp(name, zpool_get_name(zhp)) == 0)
4525 		return (1);
4526 
4527 	return (0);
4528 }
4529 
4530 /*
4531  * Do we have a pool named *name?  If so, return 1, otherwise 0.
4532  */
4533 static int
4534 is_pool(char *name)
4535 {
4536 	return (for_each_pool(0, NULL, B_TRUE, NULL,  is_pool_cb, name));
4537 }
4538 
4539 /* Are all our argv[] strings pool names?  If so return 1, 0 otherwise. */
4540 static int
4541 are_all_pools(int argc, char **argv)
4542 {
4543 	if ((argc == 0) || !*argv)
4544 		return (0);
4545 
4546 	while (--argc >= 0)
4547 		if (!is_pool(argv[argc]))
4548 			return (0);
4549 
4550 	return (1);
4551 }
4552 
4553 /*
4554  * Helper function to print out vdev/pool names we can't resolve.  Used for an
4555  * error message.
4556  */
4557 static void
4558 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
4559     iostat_cbdata_t *cb)
4560 {
4561 	int i;
4562 	char *name;
4563 	char *str;
4564 	for (i = 0; i < argc; i++) {
4565 		name = argv[i];
4566 
4567 		if (is_pool(name))
4568 			str = gettext("pool");
4569 		else if (are_vdevs_in_pool(1, &name, pool_name, cb))
4570 			str = gettext("vdev in this pool");
4571 		else if (are_vdevs_in_pool(1, &name, NULL, cb))
4572 			str = gettext("vdev in another pool");
4573 		else
4574 			str = gettext("unknown");
4575 
4576 		fprintf(stderr, "\t%s (%s)\n", name, str);
4577 	}
4578 }
4579 
4580 /*
4581  * Same as get_interval_count(), but with additional checks to not misinterpret
4582  * guids as interval/count values.  Assumes VDEV_NAME_GUID is set in
4583  * cb.cb_name_flags.
4584  */
4585 static void
4586 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
4587     unsigned long *count, iostat_cbdata_t *cb)
4588 {
4589 	char **tmpargv = argv;
4590 	int argc_for_interval = 0;
4591 
4592 	/* Is the last arg an interval value?  Or a guid? */
4593 	if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL, cb)) {
4594 		/*
4595 		 * The last arg is not a guid, so it's probably an
4596 		 * interval value.
4597 		 */
4598 		argc_for_interval++;
4599 
4600 		if (*argc >= 2 &&
4601 		    !are_vdevs_in_pool(1, &argv[*argc - 2], NULL, cb)) {
4602 			/*
4603 			 * The 2nd to last arg is not a guid, so it's probably
4604 			 * an interval value.
4605 			 */
4606 			argc_for_interval++;
4607 		}
4608 	}
4609 
4610 	/* Point to our list of possible intervals */
4611 	tmpargv = &argv[*argc - argc_for_interval];
4612 
4613 	*argc = *argc - argc_for_interval;
4614 	get_interval_count(&argc_for_interval, tmpargv,
4615 	    interval, count);
4616 }
4617 
4618 /*
4619  * Floating point sleep().  Allows you to pass in a floating point value for
4620  * seconds.
4621  */
4622 static void
4623 fsleep(float sec)
4624 {
4625 	struct timespec req;
4626 	req.tv_sec = floor(sec);
4627 	req.tv_nsec = (sec - (float)req.tv_sec) * NANOSEC;
4628 	(void) nanosleep(&req, NULL);
4629 }
4630 
4631 /*
4632  * Set the minimum pool/vdev name column width.  The width must be at least 10,
4633  * but may be as large as the column width - 42 so it still fits on one line.
4634  */
4635 static int
4636 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
4637 {
4638 	iostat_cbdata_t *cb = data;
4639 	int width, columns;
4640 
4641 	width = get_namewidth(zhp, cb->cb_namewidth, cb->cb_name_flags,
4642 	    cb->cb_verbose);
4643 	columns = get_columns();
4644 
4645 	if (width < 10)
4646 		width = 10;
4647 	if (width > columns - 42)
4648 		width = columns - 42;
4649 
4650 	cb->cb_namewidth = width;
4651 
4652 	return (0);
4653 }
4654 
4655 /*
4656  * zpool iostat [-ghHLpPvy] [[-lq]|[-r|-w]] [-n name] [-T d|u]
4657  *		[[ pool ...]|[pool vdev ...]|[vdev ...]]
4658  *		[interval [count]]
4659  *
4660  *	-g	Display guid for individual vdev name.
4661  *	-L	Follow links when resolving vdev path name.
4662  *	-P	Display full path for vdev name.
4663  *	-v	Display statistics for individual vdevs
4664  *	-h	Display help
4665  *	-p	Display values in parsable (exact) format.
4666  *	-H	Scripted mode.  Don't display headers, and separate properties
4667  *		by a single tab.
4668  *	-l	Display average latency
4669  *	-q	Display queue depths
4670  *	-w	Display latency histograms
4671  *	-r	Display request size histogram
4672  *	-T	Display a timestamp in date(1) or Unix format
4673  *	-n	Only print headers once
4674  *
4675  * This command can be tricky because we want to be able to deal with pool
4676  * creation/destruction as well as vdev configuration changes.  The bulk of this
4677  * processing is handled by the pool_list_* routines in zpool_iter.c.  We rely
4678  * on pool_list_update() to detect the addition of new pools.  Configuration
4679  * changes are all handled within libzfs.
4680  */
4681 int
4682 zpool_do_iostat(int argc, char **argv)
4683 {
4684 	int c;
4685 	int ret;
4686 	int npools;
4687 	float interval = 0;
4688 	unsigned long count = 0;
4689 	int winheight = 24;
4690 	struct winsize win;
4691 	zpool_list_t *list;
4692 	boolean_t verbose = B_FALSE;
4693 	boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
4694 	boolean_t queues = B_FALSE, parseable = B_FALSE, scripted = B_FALSE;
4695 	boolean_t omit_since_boot = B_FALSE;
4696 	boolean_t guid = B_FALSE;
4697 	boolean_t follow_links = B_FALSE;
4698 	boolean_t full_name = B_FALSE;
4699 	boolean_t headers_once = B_FALSE;
4700 	iostat_cbdata_t cb = { 0 };
4701 
4702 	/* Used for printing error message */
4703 	const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
4704 	    [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
4705 
4706 	uint64_t unsupported_flags;
4707 
4708 	/* check options */
4709 	while ((c = getopt(argc, argv, "gLPT:vyhplqrwnH")) != -1) {
4710 		switch (c) {
4711 		case 'g':
4712 			guid = B_TRUE;
4713 			break;
4714 		case 'L':
4715 			follow_links = B_TRUE;
4716 			break;
4717 		case 'P':
4718 			full_name = B_TRUE;
4719 			break;
4720 		case 'T':
4721 			get_timestamp_arg(*optarg);
4722 			break;
4723 		case 'v':
4724 			verbose = B_TRUE;
4725 			break;
4726 		case 'p':
4727 			parseable = B_TRUE;
4728 			break;
4729 		case 'l':
4730 			latency = B_TRUE;
4731 			break;
4732 		case 'q':
4733 			queues = B_TRUE;
4734 			break;
4735 		case 'H':
4736 			scripted = B_TRUE;
4737 			break;
4738 		case 'w':
4739 			l_histo = B_TRUE;
4740 			break;
4741 		case 'r':
4742 			rq_histo = B_TRUE;
4743 			break;
4744 		case 'y':
4745 			omit_since_boot = B_TRUE;
4746 			break;
4747 		case 'n':
4748 			headers_once = B_TRUE;
4749 			break;
4750 		case 'h':
4751 			usage(B_FALSE);
4752 			break;
4753 		case '?':
4754 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4755 			    optopt);
4756 			usage(B_FALSE);
4757 		}
4758 	}
4759 
4760 	argc -= optind;
4761 	argv += optind;
4762 
4763 	cb.cb_literal = parseable;
4764 	cb.cb_scripted = scripted;
4765 
4766 	if (guid)
4767 		cb.cb_name_flags |= VDEV_NAME_GUID;
4768 	if (follow_links)
4769 		cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
4770 	if (full_name)
4771 		cb.cb_name_flags |= VDEV_NAME_PATH;
4772 	cb.cb_iteration = 0;
4773 	cb.cb_namewidth = 0;
4774 	cb.cb_verbose = verbose;
4775 
4776 	/* Get our interval and count values (if any) */
4777 	if (guid) {
4778 		get_interval_count_filter_guids(&argc, argv, &interval,
4779 		    &count, &cb);
4780 	} else {
4781 		get_interval_count(&argc, argv, &interval, &count);
4782 	}
4783 
4784 	if (argc == 0) {
4785 		/* No args, so just print the defaults. */
4786 	} else if (are_all_pools(argc, argv)) {
4787 		/* All the args are pool names */
4788 	} else if (are_vdevs_in_pool(argc, argv, NULL, &cb)) {
4789 		/* All the args are vdevs */
4790 		cb.cb_vdev_names = argv;
4791 		cb.cb_vdev_names_count = argc;
4792 		argc = 0; /* No pools to process */
4793 	} else if (are_all_pools(1, argv)) {
4794 		/* The first arg is a pool name */
4795 		if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0], &cb)) {
4796 			/* ...and the rest are vdev names */
4797 			cb.cb_vdev_names = argv + 1;
4798 			cb.cb_vdev_names_count = argc - 1;
4799 			argc = 1; /* One pool to process */
4800 		} else {
4801 			fprintf(stderr, gettext("Expected either a list of "));
4802 			fprintf(stderr, gettext("pools, or list of vdevs in"));
4803 			fprintf(stderr, " \"%s\", ", argv[0]);
4804 			fprintf(stderr, gettext("but got:\n"));
4805 			error_list_unresolved_vdevs(argc - 1, argv + 1,
4806 			    argv[0], &cb);
4807 			fprintf(stderr, "\n");
4808 			usage(B_FALSE);
4809 			return (1);
4810 		}
4811 	} else {
4812 		/*
4813 		 * The args don't make sense. The first arg isn't a pool name,
4814 		 * nor are all the args vdevs.
4815 		 */
4816 		fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
4817 		fprintf(stderr, "\n");
4818 		return (1);
4819 	}
4820 
4821 	if (cb.cb_vdev_names_count != 0) {
4822 		/*
4823 		 * If user specified vdevs, it implies verbose.
4824 		 */
4825 		cb.cb_verbose = B_TRUE;
4826 	}
4827 
4828 	/*
4829 	 * Construct the list of all interesting pools.
4830 	 */
4831 	ret = 0;
4832 	if ((list = pool_list_get(argc, argv, NULL, &ret)) == NULL)
4833 		return (1);
4834 
4835 	if (pool_list_count(list) == 0 && argc != 0) {
4836 		pool_list_free(list);
4837 		return (1);
4838 	}
4839 
4840 	if (pool_list_count(list) == 0 && interval == 0) {
4841 		pool_list_free(list);
4842 		(void) fprintf(stderr, gettext("no pools available\n"));
4843 		return (1);
4844 	}
4845 
4846 	if ((l_histo || rq_histo) && (queues || latency)) {
4847 		pool_list_free(list);
4848 		(void) fprintf(stderr,
4849 		    gettext("[-r|-w] isn't allowed with [-q|-l]\n"));
4850 		usage(B_FALSE);
4851 		return (1);
4852 	}
4853 
4854 	if (l_histo && rq_histo) {
4855 		pool_list_free(list);
4856 		(void) fprintf(stderr,
4857 		    gettext("Only one of [-r|-w] can be passed at a time\n"));
4858 		usage(B_FALSE);
4859 		return (1);
4860 	}
4861 
4862 	/*
4863 	 * Enter the main iostat loop.
4864 	 */
4865 	cb.cb_list = list;
4866 
4867 	if (l_histo) {
4868 		/*
4869 		 * Histograms tables look out of place when you try to display
4870 		 * them with the other stats, so make a rule that you can only
4871 		 * print histograms by themselves.
4872 		 */
4873 		cb.cb_flags = IOS_L_HISTO_M;
4874 	} else if (rq_histo) {
4875 		cb.cb_flags = IOS_RQ_HISTO_M;
4876 	} else {
4877 		cb.cb_flags = IOS_DEFAULT_M;
4878 		if (latency)
4879 			cb.cb_flags |= IOS_LATENCY_M;
4880 		if (queues)
4881 			cb.cb_flags |= IOS_QUEUES_M;
4882 	}
4883 
4884 	/*
4885 	 * See if the module supports all the stats we want to display.
4886 	 */
4887 	unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
4888 	if (unsupported_flags) {
4889 		uint64_t f;
4890 		int idx;
4891 		fprintf(stderr,
4892 		    gettext("The loaded zfs module doesn't support:"));
4893 
4894 		/* for each bit set in unsupported_flags */
4895 		for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
4896 			idx = lowbit64(f) - 1;
4897 			fprintf(stderr, " -%c", flag_to_arg[idx]);
4898 		}
4899 
4900 		fprintf(stderr, ".  Try running a newer module.\n"),
4901 		    pool_list_free(list);
4902 
4903 		return (1);
4904 	}
4905 
4906 	for (;;) {
4907 		if ((npools = pool_list_count(list)) == 0)
4908 			(void) fprintf(stderr, gettext("no pools available\n"));
4909 		else {
4910 			/*
4911 			 * If this is the first iteration and -y was supplied
4912 			 * we skip any printing.
4913 			 */
4914 			boolean_t skip = (omit_since_boot &&
4915 			    cb.cb_iteration == 0);
4916 
4917 			/*
4918 			 * Refresh all statistics.  This is done as an
4919 			 * explicit step before calculating the maximum name
4920 			 * width, so that any configuration changes are
4921 			 * properly accounted for.
4922 			 */
4923 			(void) pool_list_iter(list, B_FALSE, refresh_iostat,
4924 			    &cb);
4925 
4926 			/*
4927 			 * Iterate over all pools to determine the maximum width
4928 			 * for the pool / device name column across all pools.
4929 			 */
4930 			cb.cb_namewidth = 0;
4931 			(void) pool_list_iter(list, B_FALSE,
4932 			    get_namewidth_iostat, &cb);
4933 
4934 			if (timestamp_fmt != NODATE)
4935 				print_timestamp(timestamp_fmt);
4936 
4937 			/*
4938 			 * Check terminal size so we can print headers
4939 			 * even when terminal window has its height
4940 			 * changed.
4941 			 */
4942 			if (headers_once == B_FALSE) {
4943 				if (ioctl(1, TIOCGWINSZ, &win) != -1) {
4944 					if (win.ws_row <= 0) {
4945 						headers_once = B_TRUE;
4946 					} else {
4947 						winheight = win.ws_row;
4948 					}
4949 				}
4950 			}
4951 			/*
4952 			 * Are we connected to TTY? If not, headers_once
4953 			 * should be true, to avoid breaking scripts.
4954 			 */
4955 			if (isatty(fileno(stdout)) == 0)
4956 				headers_once = B_TRUE;
4957 
4958 			/*
4959 			 * If it's the first time and we're not skipping it,
4960 			 * or either skip or verbose mode, print the header.
4961 			 *
4962 			 * The histogram code explicitly prints its header on
4963 			 * every vdev, so skip this for histograms.
4964 			 */
4965 			if (((++cb.cb_iteration == 1 && !skip) ||
4966 			    (skip != verbose) ||
4967 			    (!headers_once &&
4968 			    (cb.cb_iteration % winheight) == 0)) &&
4969 			    (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
4970 			    !cb.cb_scripted)
4971 				print_iostat_header(&cb);
4972 
4973 			if (skip) {
4974 				(void) fsleep(interval);
4975 				continue;
4976 			}
4977 
4978 			(void) pool_list_iter(list, B_FALSE, print_iostat, &cb);
4979 
4980 			/*
4981 			 * If there's more than one pool, and we're not in
4982 			 * verbose mode (which prints a separator for us),
4983 			 * then print a separator.
4984 			 *
4985 			 * In addition, if we're printing specific vdevs then
4986 			 * we also want an ending separator.
4987 			 */
4988 			if (((npools > 1 && !verbose &&
4989 			    !(cb.cb_flags & IOS_ANYHISTO_M)) ||
4990 			    (!(cb.cb_flags & IOS_ANYHISTO_M) &&
4991 			    cb.cb_vdev_names_count)) &&
4992 			    !cb.cb_scripted) {
4993 				print_iostat_separator(&cb);
4994 				printf("\n");
4995 			}
4996 		}
4997 
4998 		/*
4999 		 * Flush the output so that redirection to a file isn't buffered
5000 		 * indefinitely.
5001 		 */
5002 		(void) fflush(stdout);
5003 
5004 		if (interval == 0)
5005 			break;
5006 
5007 		if (count != 0 && --count == 0)
5008 			break;
5009 
5010 		(void) fsleep(interval);
5011 	}
5012 
5013 	pool_list_free(list);
5014 
5015 	return (ret);
5016 }
5017 
5018 typedef struct list_cbdata {
5019 	boolean_t	cb_verbose;
5020 	int		cb_name_flags;
5021 	int		cb_namewidth;
5022 	boolean_t	cb_scripted;
5023 	zprop_list_t	*cb_proplist;
5024 	boolean_t	cb_literal;
5025 } list_cbdata_t;
5026 
5027 
5028 /*
5029  * Given a list of columns to display, output appropriate headers for each one.
5030  */
5031 static void
5032 print_header(list_cbdata_t *cb)
5033 {
5034 	zprop_list_t *pl = cb->cb_proplist;
5035 	char headerbuf[ZPOOL_MAXPROPLEN];
5036 	const char *header;
5037 	boolean_t first = B_TRUE;
5038 	boolean_t right_justify;
5039 	size_t width = 0;
5040 
5041 	for (; pl != NULL; pl = pl->pl_next) {
5042 		width = pl->pl_width;
5043 		if (first && cb->cb_verbose) {
5044 			/*
5045 			 * Reset the width to accommodate the verbose listing
5046 			 * of devices.
5047 			 */
5048 			width = cb->cb_namewidth;
5049 		}
5050 
5051 		if (!first)
5052 			(void) printf("  ");
5053 		else
5054 			first = B_FALSE;
5055 
5056 		right_justify = B_FALSE;
5057 		if (pl->pl_prop != ZPROP_INVAL) {
5058 			header = zpool_prop_column_name(pl->pl_prop);
5059 			right_justify = zpool_prop_align_right(pl->pl_prop);
5060 		} else {
5061 			int i;
5062 
5063 			for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
5064 				headerbuf[i] = toupper(pl->pl_user_prop[i]);
5065 			headerbuf[i] = '\0';
5066 			header = headerbuf;
5067 		}
5068 
5069 		if (pl->pl_next == NULL && !right_justify)
5070 			(void) printf("%s", header);
5071 		else if (right_justify)
5072 			(void) printf("%*s", width, header);
5073 		else
5074 			(void) printf("%-*s", width, header);
5075 
5076 	}
5077 
5078 	(void) printf("\n");
5079 }
5080 
5081 /*
5082  * Given a pool and a list of properties, print out all the properties according
5083  * to the described layout. Used by zpool_do_list().
5084  */
5085 static void
5086 print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
5087 {
5088 	zprop_list_t *pl = cb->cb_proplist;
5089 	boolean_t first = B_TRUE;
5090 	char property[ZPOOL_MAXPROPLEN];
5091 	char *propstr;
5092 	boolean_t right_justify;
5093 	size_t width;
5094 
5095 	for (; pl != NULL; pl = pl->pl_next) {
5096 
5097 		width = pl->pl_width;
5098 		if (first && cb->cb_verbose) {
5099 			/*
5100 			 * Reset the width to accommodate the verbose listing
5101 			 * of devices.
5102 			 */
5103 			width = cb->cb_namewidth;
5104 		}
5105 
5106 		if (!first) {
5107 			if (cb->cb_scripted)
5108 				(void) printf("\t");
5109 			else
5110 				(void) printf("  ");
5111 		} else {
5112 			first = B_FALSE;
5113 		}
5114 
5115 		right_justify = B_FALSE;
5116 		if (pl->pl_prop != ZPROP_INVAL) {
5117 			if (zpool_get_prop(zhp, pl->pl_prop, property,
5118 			    sizeof (property), NULL, cb->cb_literal) != 0)
5119 				propstr = "-";
5120 			else
5121 				propstr = property;
5122 
5123 			right_justify = zpool_prop_align_right(pl->pl_prop);
5124 		} else if ((zpool_prop_feature(pl->pl_user_prop) ||
5125 		    zpool_prop_unsupported(pl->pl_user_prop)) &&
5126 		    zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
5127 		    sizeof (property)) == 0) {
5128 			propstr = property;
5129 		} else {
5130 			propstr = "-";
5131 		}
5132 
5133 
5134 		/*
5135 		 * If this is being called in scripted mode, or if this is the
5136 		 * last column and it is left-justified, don't include a width
5137 		 * format specifier.
5138 		 */
5139 		if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
5140 			(void) printf("%s", propstr);
5141 		else if (right_justify)
5142 			(void) printf("%*s", width, propstr);
5143 		else
5144 			(void) printf("%-*s", width, propstr);
5145 	}
5146 
5147 	(void) printf("\n");
5148 }
5149 
5150 static void
5151 print_one_column(zpool_prop_t prop, uint64_t value, boolean_t scripted,
5152     boolean_t valid, enum zfs_nicenum_format format)
5153 {
5154 	char propval[64];
5155 	boolean_t fixed;
5156 	size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
5157 
5158 	switch (prop) {
5159 	case ZPOOL_PROP_EXPANDSZ:
5160 	case ZPOOL_PROP_CHECKPOINT:
5161 		if (value == 0)
5162 			(void) strlcpy(propval, "-", sizeof (propval));
5163 		else
5164 			zfs_nicenum_format(value, propval, sizeof (propval),
5165 			    format);
5166 		break;
5167 	case ZPOOL_PROP_FRAGMENTATION:
5168 		if (value == ZFS_FRAG_INVALID) {
5169 			(void) strlcpy(propval, "-", sizeof (propval));
5170 		} else if (format == ZFS_NICENUM_RAW) {
5171 			(void) snprintf(propval, sizeof (propval), "%llu",
5172 			    (unsigned long long)value);
5173 		} else {
5174 			(void) snprintf(propval, sizeof (propval), "%llu%%",
5175 			    (unsigned long long)value);
5176 		}
5177 		break;
5178 	case ZPOOL_PROP_CAPACITY:
5179 		if (format == ZFS_NICENUM_RAW)
5180 			(void) snprintf(propval, sizeof (propval), "%llu",
5181 			    (unsigned long long)value / 100);
5182 
5183 		else
5184 			(void) snprintf(propval, sizeof (propval),
5185 			    value < 1000 ? "%1.2f%%" : value < 10000 ?
5186 			    "%2.1f%%" : "%3.0f%%", value / 100.0);
5187 		break;
5188 	default:
5189 		zfs_nicenum_format(value, propval, sizeof (propval), format);
5190 	}
5191 
5192 	if (!valid)
5193 		(void) strlcpy(propval, "-", sizeof (propval));
5194 
5195 	if (scripted)
5196 		(void) printf("\t%s", propval);
5197 	else
5198 		(void) printf("  %*s", width, propval);
5199 }
5200 
5201 /*
5202  * print static default line per vdev
5203  */
5204 void
5205 print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
5206     list_cbdata_t *cb, int depth)
5207 {
5208 	nvlist_t **child;
5209 	vdev_stat_t *vs;
5210 	uint_t c, children;
5211 	char *vname;
5212 	boolean_t scripted = cb->cb_scripted;
5213 	uint64_t islog = B_FALSE;
5214 	char *dashes = "%-*s      -      -      -         -      -      -\n";
5215 
5216 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
5217 	    (uint64_t **)&vs, &c) == 0);
5218 
5219 	if (name != NULL) {
5220 		boolean_t toplevel = (vs->vs_space != 0);
5221 		uint64_t cap;
5222 		enum zfs_nicenum_format format;
5223 
5224 		if (cb->cb_literal)
5225 			format = ZFS_NICENUM_RAW;
5226 		else
5227 			format = ZFS_NICENUM_1024;
5228 
5229 		if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
5230 			return;
5231 
5232 		if (scripted)
5233 			(void) printf("\t%s", name);
5234 		else if (strlen(name) + depth > cb->cb_namewidth)
5235 			(void) printf("%*s%s", depth, "", name);
5236 		else
5237 			(void) printf("%*s%s%*s", depth, "", name,
5238 			    (int)(cb->cb_namewidth - strlen(name) - depth), "");
5239 
5240 		/*
5241 		 * Print the properties for the individual vdevs. Some
5242 		 * properties are only applicable to toplevel vdevs. The
5243 		 * 'toplevel' boolean value is passed to the print_one_column()
5244 		 * to indicate that the value is valid.
5245 		 */
5246 		print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, scripted,
5247 		    toplevel, format);
5248 		print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, scripted,
5249 		    toplevel, format);
5250 		print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
5251 		    scripted, toplevel, format);
5252 		print_one_column(ZPOOL_PROP_CHECKPOINT,
5253 		    vs->vs_checkpoint_space, scripted, toplevel, format);
5254 		print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, scripted,
5255 		    B_TRUE, format);
5256 		print_one_column(ZPOOL_PROP_FRAGMENTATION,
5257 		    vs->vs_fragmentation, scripted,
5258 		    (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
5259 		    format);
5260 		cap = (vs->vs_space == 0) ? 0 :
5261 		    (vs->vs_alloc * 10000 / vs->vs_space);
5262 		print_one_column(ZPOOL_PROP_CAPACITY, cap, scripted, toplevel,
5263 		    format);
5264 		(void) printf("\n");
5265 	}
5266 
5267 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
5268 	    &child, &children) != 0)
5269 		return;
5270 
5271 	/* list the normal vdevs first */
5272 	for (c = 0; c < children; c++) {
5273 		uint64_t ishole = B_FALSE;
5274 
5275 		if (nvlist_lookup_uint64(child[c],
5276 		    ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
5277 			continue;
5278 
5279 		if (nvlist_lookup_uint64(child[c],
5280 		    ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
5281 			continue;
5282 
5283 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
5284 			continue;
5285 
5286 		vname = zpool_vdev_name(g_zfs, zhp, child[c],
5287 		    cb->cb_name_flags);
5288 		print_list_stats(zhp, vname, child[c], cb, depth + 2);
5289 		free(vname);
5290 	}
5291 
5292 	/* list the classes: 'logs', 'dedup', and 'special' */
5293 	for (uint_t n = 0; n < 3; n++) {
5294 		boolean_t printed = B_FALSE;
5295 
5296 		for (c = 0; c < children; c++) {
5297 			char *bias = NULL;
5298 			char *type = NULL;
5299 
5300 			if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
5301 			    &islog) == 0 && islog) {
5302 				bias = VDEV_ALLOC_CLASS_LOGS;
5303 			} else {
5304 				(void) nvlist_lookup_string(child[c],
5305 				    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
5306 				(void) nvlist_lookup_string(child[c],
5307 				    ZPOOL_CONFIG_TYPE, &type);
5308 			}
5309 			if (bias == NULL || strcmp(bias, class_name[n]) != 0)
5310 				continue;
5311 			if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
5312 				continue;
5313 
5314 			if (!printed) {
5315 				/* LINTED E_SEC_PRINTF_VAR_FMT */
5316 				(void) printf(dashes, cb->cb_namewidth,
5317 				    class_name[n]);
5318 				printed = B_TRUE;
5319 			}
5320 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
5321 			    cb->cb_name_flags);
5322 			print_list_stats(zhp, vname, child[c], cb, depth + 2);
5323 			free(vname);
5324 		}
5325 	}
5326 
5327 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
5328 	    &child, &children) == 0 && children > 0) {
5329 		/* LINTED E_SEC_PRINTF_VAR_FMT */
5330 		(void) printf(dashes, cb->cb_namewidth, "cache");
5331 		for (c = 0; c < children; c++) {
5332 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
5333 			    cb->cb_name_flags);
5334 			print_list_stats(zhp, vname, child[c], cb, depth + 2);
5335 			free(vname);
5336 		}
5337 	}
5338 
5339 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
5340 	    &children) == 0 && children > 0) {
5341 		/* LINTED E_SEC_PRINTF_VAR_FMT */
5342 		(void) printf(dashes, cb->cb_namewidth, "spare");
5343 		for (c = 0; c < children; c++) {
5344 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
5345 			    cb->cb_name_flags);
5346 			print_list_stats(zhp, vname, child[c], cb, depth + 2);
5347 			free(vname);
5348 		}
5349 	}
5350 }
5351 
5352 /*
5353  * Generic callback function to list a pool.
5354  */
5355 int
5356 list_callback(zpool_handle_t *zhp, void *data)
5357 {
5358 	list_cbdata_t *cbp = data;
5359 	nvlist_t *config;
5360 	nvlist_t *nvroot;
5361 
5362 	config = zpool_get_config(zhp, NULL);
5363 
5364 	if (cbp->cb_verbose) {
5365 		config = zpool_get_config(zhp, NULL);
5366 
5367 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5368 		    &nvroot) == 0);
5369 	}
5370 
5371 	if (cbp->cb_verbose)
5372 		cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
5373 		    cbp->cb_name_flags);
5374 
5375 	print_pool(zhp, cbp);
5376 
5377 	if (cbp->cb_verbose)
5378 		print_list_stats(zhp, NULL, nvroot, cbp, 0);
5379 
5380 	return (0);
5381 }
5382 
5383 /*
5384  * Set the minimum pool/vdev name column width.  The width must be at least 9,
5385  * but may be as large as needed.
5386  */
5387 static int
5388 get_namewidth_list(zpool_handle_t *zhp, void *data)
5389 {
5390 	list_cbdata_t *cb = data;
5391 	int width;
5392 
5393 	width = get_namewidth(zhp, cb->cb_namewidth, cb->cb_name_flags,
5394 	    cb->cb_verbose);
5395 
5396 	if (width < 9)
5397 		width = 9;
5398 
5399 	cb->cb_namewidth = width;
5400 
5401 	return (0);
5402 }
5403 
5404 /*
5405  * zpool list [-gHLP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
5406  *
5407  *	-g	Display guid for individual vdev name.
5408  *	-H	Scripted mode.  Don't display headers, and separate properties
5409  *		by a single tab.
5410  *	-L	Follow links when resolving vdev path name.
5411  *	-o	List of properties to display.  Defaults to
5412  *		"name,size,allocated,free,expandsize,fragmentation,capacity,"
5413  *		"dedupratio,health,altroot"
5414  *	-p	Diplay values in parsable (exact) format.
5415  *	-P	Display full path for vdev name.
5416  *	-T	Display a timestamp in date(1) or Unix format
5417  *
5418  * List all pools in the system, whether or not they're healthy.  Output space
5419  * statistics for each one, as well as health status summary.
5420  */
5421 int
5422 zpool_do_list(int argc, char **argv)
5423 {
5424 	int c;
5425 	int ret;
5426 	list_cbdata_t cb = { 0 };
5427 	static char default_props[] =
5428 	    "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
5429 	    "capacity,dedupratio,health,altroot";
5430 	char *props = default_props;
5431 	float interval = 0;
5432 	unsigned long count = 0;
5433 	zpool_list_t *list;
5434 	boolean_t first = B_TRUE;
5435 
5436 	/* check options */
5437 	while ((c = getopt(argc, argv, ":gHLo:pPT:v")) != -1) {
5438 		switch (c) {
5439 		case 'g':
5440 			cb.cb_name_flags |= VDEV_NAME_GUID;
5441 			break;
5442 		case 'H':
5443 			cb.cb_scripted = B_TRUE;
5444 			break;
5445 		case 'L':
5446 			cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
5447 			break;
5448 		case 'o':
5449 			props = optarg;
5450 			break;
5451 		case 'P':
5452 			cb.cb_name_flags |= VDEV_NAME_PATH;
5453 			break;
5454 		case 'p':
5455 			cb.cb_literal = B_TRUE;
5456 			break;
5457 		case 'T':
5458 			get_timestamp_arg(*optarg);
5459 			break;
5460 		case 'v':
5461 			cb.cb_verbose = B_TRUE;
5462 			cb.cb_namewidth = 8;	/* 8 until precalc is avail */
5463 			break;
5464 		case ':':
5465 			(void) fprintf(stderr, gettext("missing argument for "
5466 			    "'%c' option\n"), optopt);
5467 			usage(B_FALSE);
5468 			break;
5469 		case '?':
5470 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5471 			    optopt);
5472 			usage(B_FALSE);
5473 		}
5474 	}
5475 
5476 	argc -= optind;
5477 	argv += optind;
5478 
5479 	get_interval_count(&argc, argv, &interval, &count);
5480 
5481 	if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
5482 		usage(B_FALSE);
5483 
5484 	for (;;) {
5485 		if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
5486 		    &ret)) == NULL)
5487 			return (1);
5488 
5489 		if (pool_list_count(list) == 0)
5490 			break;
5491 
5492 		cb.cb_namewidth = 0;
5493 		(void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
5494 
5495 		if (timestamp_fmt != NODATE)
5496 			print_timestamp(timestamp_fmt);
5497 
5498 		if (!cb.cb_scripted && (first || cb.cb_verbose)) {
5499 			print_header(&cb);
5500 			first = B_FALSE;
5501 		}
5502 		ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
5503 
5504 		if (interval == 0)
5505 			break;
5506 
5507 		if (count != 0 && --count == 0)
5508 			break;
5509 
5510 		pool_list_free(list);
5511 		(void) fsleep(interval);
5512 	}
5513 
5514 	if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
5515 		(void) printf(gettext("no pools available\n"));
5516 		ret = 0;
5517 	}
5518 
5519 	pool_list_free(list);
5520 	zprop_free_list(cb.cb_proplist);
5521 	return (ret);
5522 }
5523 
5524 static int
5525 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
5526 {
5527 	boolean_t force = B_FALSE;
5528 	int c;
5529 	nvlist_t *nvroot;
5530 	char *poolname, *old_disk, *new_disk;
5531 	zpool_handle_t *zhp;
5532 	zpool_boot_label_t boot_type;
5533 	uint64_t boot_size;
5534 	nvlist_t *props = NULL;
5535 	char *propval;
5536 	int ret;
5537 
5538 	/* check options */
5539 	while ((c = getopt(argc, argv, "fo:")) != -1) {
5540 		switch (c) {
5541 		case 'f':
5542 			force = B_TRUE;
5543 			break;
5544 		case 'o':
5545 			if ((propval = strchr(optarg, '=')) == NULL) {
5546 				(void) fprintf(stderr, gettext("missing "
5547 				    "'=' for -o option\n"));
5548 				usage(B_FALSE);
5549 			}
5550 			*propval = '\0';
5551 			propval++;
5552 
5553 			if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
5554 			    (add_prop_list(optarg, propval, &props, B_TRUE)))
5555 				usage(B_FALSE);
5556 			break;
5557 		case '?':
5558 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5559 			    optopt);
5560 			usage(B_FALSE);
5561 		}
5562 	}
5563 
5564 	argc -= optind;
5565 	argv += optind;
5566 
5567 	/* get pool name and check number of arguments */
5568 	if (argc < 1) {
5569 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
5570 		usage(B_FALSE);
5571 	}
5572 
5573 	poolname = argv[0];
5574 
5575 	if (argc < 2) {
5576 		(void) fprintf(stderr,
5577 		    gettext("missing <device> specification\n"));
5578 		usage(B_FALSE);
5579 	}
5580 
5581 	old_disk = argv[1];
5582 
5583 	if (argc < 3) {
5584 		if (!replacing) {
5585 			(void) fprintf(stderr,
5586 			    gettext("missing <new_device> specification\n"));
5587 			usage(B_FALSE);
5588 		}
5589 		new_disk = old_disk;
5590 		argc -= 1;
5591 		argv += 1;
5592 	} else {
5593 		new_disk = argv[2];
5594 		argc -= 2;
5595 		argv += 2;
5596 	}
5597 
5598 	if (argc > 1) {
5599 		(void) fprintf(stderr, gettext("too many arguments\n"));
5600 		usage(B_FALSE);
5601 	}
5602 
5603 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5604 		return (1);
5605 
5606 	if (zpool_get_config(zhp, NULL) == NULL) {
5607 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
5608 		    poolname);
5609 		zpool_close(zhp);
5610 		return (1);
5611 	}
5612 
5613 	if (zpool_is_bootable(zhp))
5614 		boot_type = ZPOOL_COPY_BOOT_LABEL;
5615 	else
5616 		boot_type = ZPOOL_NO_BOOT_LABEL;
5617 
5618 	boot_size = zpool_get_prop_int(zhp, ZPOOL_PROP_BOOTSIZE, NULL);
5619 
5620 	/* unless manually specified use "ashift" pool property (if set) */
5621 	if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
5622 		int intval;
5623 		zprop_source_t src;
5624 		char strval[ZPOOL_MAXPROPLEN];
5625 
5626 		intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
5627 		if (src != ZPROP_SRC_DEFAULT) {
5628 			(void) sprintf(strval, "%" PRId32, intval);
5629 			verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
5630 			    &props, B_TRUE) == 0);
5631 		}
5632 	}
5633 
5634 	nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
5635 	    boot_type, boot_size, argc, argv);
5636 	if (nvroot == NULL) {
5637 		zpool_close(zhp);
5638 		return (1);
5639 	}
5640 
5641 	ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing);
5642 
5643 	nvlist_free(nvroot);
5644 	zpool_close(zhp);
5645 
5646 	return (ret);
5647 }
5648 
5649 /*
5650  * zpool replace [-f] <pool> <device> <new_device>
5651  *
5652  *	-f	Force attach, even if <new_device> appears to be in use.
5653  *
5654  * Replace <device> with <new_device>.
5655  */
5656 /* ARGSUSED */
5657 int
5658 zpool_do_replace(int argc, char **argv)
5659 {
5660 	return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
5661 }
5662 
5663 /*
5664  * zpool attach [-f] [-o property=value] <pool> <device> <new_device>
5665  *
5666  *	-f	Force attach, even if <new_device> appears to be in use.
5667  *	-o	Set property=value.
5668  *
5669  * Attach <new_device> to the mirror containing <device>.  If <device> is not
5670  * part of a mirror, then <device> will be transformed into a mirror of
5671  * <device> and <new_device>.  In either case, <new_device> will begin life
5672  * with a DTL of [0, now], and will immediately begin to resilver itself.
5673  */
5674 int
5675 zpool_do_attach(int argc, char **argv)
5676 {
5677 	return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
5678 }
5679 
5680 /*
5681  * zpool detach [-f] <pool> <device>
5682  *
5683  *	-f	Force detach of <device>, even if DTLs argue against it
5684  *		(not supported yet)
5685  *
5686  * Detach a device from a mirror.  The operation will be refused if <device>
5687  * is the last device in the mirror, or if the DTLs indicate that this device
5688  * has the only valid copy of some data.
5689  */
5690 /* ARGSUSED */
5691 int
5692 zpool_do_detach(int argc, char **argv)
5693 {
5694 	int c;
5695 	char *poolname, *path;
5696 	zpool_handle_t *zhp;
5697 	int ret;
5698 
5699 	/* check options */
5700 	while ((c = getopt(argc, argv, "f")) != -1) {
5701 		switch (c) {
5702 		case 'f':
5703 		case '?':
5704 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5705 			    optopt);
5706 			usage(B_FALSE);
5707 		}
5708 	}
5709 
5710 	argc -= optind;
5711 	argv += optind;
5712 
5713 	/* get pool name and check number of arguments */
5714 	if (argc < 1) {
5715 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
5716 		usage(B_FALSE);
5717 	}
5718 
5719 	if (argc < 2) {
5720 		(void) fprintf(stderr,
5721 		    gettext("missing <device> specification\n"));
5722 		usage(B_FALSE);
5723 	}
5724 
5725 	poolname = argv[0];
5726 	path = argv[1];
5727 
5728 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5729 		return (1);
5730 
5731 	ret = zpool_vdev_detach(zhp, path);
5732 
5733 	zpool_close(zhp);
5734 
5735 	return (ret);
5736 }
5737 
5738 /*
5739  * zpool split [-gLnP] [-o prop=val] ...
5740  *		[-o mntopt] ...
5741  *		[-R altroot] <pool> <newpool> [<device> ...]
5742  *
5743  *	-g      Display guid for individual vdev name.
5744  *	-L	Follow links when resolving vdev path name.
5745  *	-n	Do not split the pool, but display the resulting layout if
5746  *		it were to be split.
5747  *	-o	Set property=value, or set mount options.
5748  *	-P	Display full path for vdev name.
5749  *	-R	Mount the split-off pool under an alternate root.
5750  *	-l	Load encryption keys while importing.
5751  *
5752  * Splits the named pool and gives it the new pool name.  Devices to be split
5753  * off may be listed, provided that no more than one device is specified
5754  * per top-level vdev mirror.  The newly split pool is left in an exported
5755  * state unless -R is specified.
5756  *
5757  * Restrictions: the top-level of the pool pool must only be made up of
5758  * mirrors; all devices in the pool must be healthy; no device may be
5759  * undergoing a resilvering operation.
5760  */
5761 int
5762 zpool_do_split(int argc, char **argv)
5763 {
5764 	char *srcpool, *newpool, *propval;
5765 	char *mntopts = NULL;
5766 	splitflags_t flags;
5767 	int c, ret = 0;
5768 	boolean_t loadkeys = B_FALSE;
5769 	zpool_handle_t *zhp;
5770 	nvlist_t *config, *props = NULL;
5771 
5772 	flags.dryrun = B_FALSE;
5773 	flags.import = B_FALSE;
5774 	flags.name_flags = 0;
5775 
5776 	/* check options */
5777 	while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
5778 		switch (c) {
5779 		case 'g':
5780 			flags.name_flags |= VDEV_NAME_GUID;
5781 			break;
5782 		case 'L':
5783 			flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
5784 			break;
5785 		case 'R':
5786 			flags.import = B_TRUE;
5787 			if (add_prop_list(
5788 			    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
5789 			    &props, B_TRUE) != 0) {
5790 				nvlist_free(props);
5791 				usage(B_FALSE);
5792 			}
5793 			break;
5794 		case 'l':
5795 			loadkeys = B_TRUE;
5796 			break;
5797 		case 'n':
5798 			flags.dryrun = B_TRUE;
5799 			break;
5800 		case 'o':
5801 			if ((propval = strchr(optarg, '=')) != NULL) {
5802 				*propval = '\0';
5803 				propval++;
5804 				if (add_prop_list(optarg, propval,
5805 				    &props, B_TRUE) != 0) {
5806 					nvlist_free(props);
5807 					usage(B_FALSE);
5808 				}
5809 			} else {
5810 				mntopts = optarg;
5811 			}
5812 			break;
5813 		case 'P':
5814 			flags.name_flags |= VDEV_NAME_PATH;
5815 			break;
5816 		case ':':
5817 			(void) fprintf(stderr, gettext("missing argument for "
5818 			    "'%c' option\n"), optopt);
5819 			usage(B_FALSE);
5820 			break;
5821 		case '?':
5822 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5823 			    optopt);
5824 			usage(B_FALSE);
5825 			break;
5826 		}
5827 	}
5828 
5829 	if (!flags.import && mntopts != NULL) {
5830 		(void) fprintf(stderr, gettext("setting mntopts is only "
5831 		    "valid when importing the pool\n"));
5832 		usage(B_FALSE);
5833 	}
5834 
5835 	if (!flags.import && loadkeys) {
5836 		(void) fprintf(stderr, gettext("loading keys is only "
5837 		    "valid when importing the pool\n"));
5838 		usage(B_FALSE);
5839 	}
5840 
5841 	argc -= optind;
5842 	argv += optind;
5843 
5844 	if (argc < 1) {
5845 		(void) fprintf(stderr, gettext("Missing pool name\n"));
5846 		usage(B_FALSE);
5847 	}
5848 	if (argc < 2) {
5849 		(void) fprintf(stderr, gettext("Missing new pool name\n"));
5850 		usage(B_FALSE);
5851 	}
5852 
5853 	srcpool = argv[0];
5854 	newpool = argv[1];
5855 
5856 	argc -= 2;
5857 	argv += 2;
5858 
5859 	if ((zhp = zpool_open(g_zfs, srcpool)) == NULL)
5860 		return (1);
5861 
5862 	config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
5863 	if (config == NULL) {
5864 		ret = 1;
5865 	} else {
5866 		if (flags.dryrun) {
5867 			(void) printf(gettext("would create '%s' with the "
5868 			    "following layout:\n\n"), newpool);
5869 			print_vdev_tree(NULL, newpool, config, 0, "",
5870 			    flags.name_flags);
5871 		}
5872 		nvlist_free(config);
5873 	}
5874 
5875 	zpool_close(zhp);
5876 
5877 	if (ret != 0 || flags.dryrun || !flags.import)
5878 		return (ret);
5879 
5880 	/*
5881 	 * The split was successful. Now we need to open the new
5882 	 * pool and import it.
5883 	 */
5884 	if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL)
5885 		return (1);
5886 
5887 	if (loadkeys) {
5888 		ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
5889 		if (ret != 0)
5890 			ret = 1;
5891 	}
5892 
5893 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
5894 	    zpool_enable_datasets(zhp, mntopts, 0) != 0) {
5895 		ret = 1;
5896 		(void) fprintf(stderr, gettext("Split was successful, but "
5897 		    "the datasets could not all be mounted\n"));
5898 		(void) fprintf(stderr, gettext("Try doing '%s' with a "
5899 		    "different altroot\n"), "zpool import");
5900 	}
5901 	zpool_close(zhp);
5902 
5903 	return (ret);
5904 }
5905 
5906 
5907 
5908 /*
5909  * zpool online <pool> <device> ...
5910  */
5911 int
5912 zpool_do_online(int argc, char **argv)
5913 {
5914 	int c, i;
5915 	char *poolname;
5916 	zpool_handle_t *zhp;
5917 	int ret = 0;
5918 	vdev_state_t newstate;
5919 	int flags = 0;
5920 
5921 	/* check options */
5922 	while ((c = getopt(argc, argv, "et")) != -1) {
5923 		switch (c) {
5924 		case 'e':
5925 			flags |= ZFS_ONLINE_EXPAND;
5926 			break;
5927 		case 't':
5928 		case '?':
5929 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5930 			    optopt);
5931 			usage(B_FALSE);
5932 		}
5933 	}
5934 
5935 	argc -= optind;
5936 	argv += optind;
5937 
5938 	/* get pool name and check number of arguments */
5939 	if (argc < 1) {
5940 		(void) fprintf(stderr, gettext("missing pool name\n"));
5941 		usage(B_FALSE);
5942 	}
5943 	if (argc < 2) {
5944 		(void) fprintf(stderr, gettext("missing device name\n"));
5945 		usage(B_FALSE);
5946 	}
5947 
5948 	poolname = argv[0];
5949 
5950 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5951 		return (1);
5952 
5953 	for (i = 1; i < argc; i++) {
5954 		if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
5955 			if (newstate != VDEV_STATE_HEALTHY) {
5956 				(void) printf(gettext("warning: device '%s' "
5957 				    "onlined, but remains in faulted state\n"),
5958 				    argv[i]);
5959 				if (newstate == VDEV_STATE_FAULTED)
5960 					(void) printf(gettext("use 'zpool "
5961 					    "clear' to restore a faulted "
5962 					    "device\n"));
5963 				else
5964 					(void) printf(gettext("use 'zpool "
5965 					    "replace' to replace devices "
5966 					    "that are no longer present\n"));
5967 			}
5968 		} else {
5969 			ret = 1;
5970 		}
5971 	}
5972 
5973 	zpool_close(zhp);
5974 
5975 	return (ret);
5976 }
5977 
5978 /*
5979  * zpool offline [-ft] <pool> <device> ...
5980  *
5981  *	-f	Force the device into the offline state, even if doing
5982  *		so would appear to compromise pool availability.
5983  *		(not supported yet)
5984  *
5985  *	-t	Only take the device off-line temporarily.  The offline
5986  *		state will not be persistent across reboots.
5987  */
5988 /* ARGSUSED */
5989 int
5990 zpool_do_offline(int argc, char **argv)
5991 {
5992 	int c, i;
5993 	char *poolname;
5994 	zpool_handle_t *zhp;
5995 	int ret = 0;
5996 	boolean_t istmp = B_FALSE;
5997 
5998 	/* check options */
5999 	while ((c = getopt(argc, argv, "ft")) != -1) {
6000 		switch (c) {
6001 		case 't':
6002 			istmp = B_TRUE;
6003 			break;
6004 		case 'f':
6005 		case '?':
6006 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6007 			    optopt);
6008 			usage(B_FALSE);
6009 		}
6010 	}
6011 
6012 	argc -= optind;
6013 	argv += optind;
6014 
6015 	/* get pool name and check number of arguments */
6016 	if (argc < 1) {
6017 		(void) fprintf(stderr, gettext("missing pool name\n"));
6018 		usage(B_FALSE);
6019 	}
6020 	if (argc < 2) {
6021 		(void) fprintf(stderr, gettext("missing device name\n"));
6022 		usage(B_FALSE);
6023 	}
6024 
6025 	poolname = argv[0];
6026 
6027 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6028 		return (1);
6029 
6030 	for (i = 1; i < argc; i++) {
6031 		if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
6032 			ret = 1;
6033 	}
6034 
6035 	zpool_close(zhp);
6036 
6037 	return (ret);
6038 }
6039 
6040 /*
6041  * zpool clear <pool> [device]
6042  *
6043  * Clear all errors associated with a pool or a particular device.
6044  */
6045 int
6046 zpool_do_clear(int argc, char **argv)
6047 {
6048 	int c;
6049 	int ret = 0;
6050 	boolean_t dryrun = B_FALSE;
6051 	boolean_t do_rewind = B_FALSE;
6052 	boolean_t xtreme_rewind = B_FALSE;
6053 	uint32_t rewind_policy = ZPOOL_NO_REWIND;
6054 	nvlist_t *policy = NULL;
6055 	zpool_handle_t *zhp;
6056 	char *pool, *device;
6057 
6058 	/* check options */
6059 	while ((c = getopt(argc, argv, "FnX")) != -1) {
6060 		switch (c) {
6061 		case 'F':
6062 			do_rewind = B_TRUE;
6063 			break;
6064 		case 'n':
6065 			dryrun = B_TRUE;
6066 			break;
6067 		case 'X':
6068 			xtreme_rewind = B_TRUE;
6069 			break;
6070 		case '?':
6071 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6072 			    optopt);
6073 			usage(B_FALSE);
6074 		}
6075 	}
6076 
6077 	argc -= optind;
6078 	argv += optind;
6079 
6080 	if (argc < 1) {
6081 		(void) fprintf(stderr, gettext("missing pool name\n"));
6082 		usage(B_FALSE);
6083 	}
6084 
6085 	if (argc > 2) {
6086 		(void) fprintf(stderr, gettext("too many arguments\n"));
6087 		usage(B_FALSE);
6088 	}
6089 
6090 	if ((dryrun || xtreme_rewind) && !do_rewind) {
6091 		(void) fprintf(stderr,
6092 		    gettext("-n or -X only meaningful with -F\n"));
6093 		usage(B_FALSE);
6094 	}
6095 	if (dryrun)
6096 		rewind_policy = ZPOOL_TRY_REWIND;
6097 	else if (do_rewind)
6098 		rewind_policy = ZPOOL_DO_REWIND;
6099 	if (xtreme_rewind)
6100 		rewind_policy |= ZPOOL_EXTREME_REWIND;
6101 
6102 	/* In future, further rewind policy choices can be passed along here */
6103 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
6104 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
6105 	    rewind_policy) != 0) {
6106 		return (1);
6107 	}
6108 
6109 	pool = argv[0];
6110 	device = argc == 2 ? argv[1] : NULL;
6111 
6112 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
6113 		nvlist_free(policy);
6114 		return (1);
6115 	}
6116 
6117 	if (zpool_clear(zhp, device, policy) != 0)
6118 		ret = 1;
6119 
6120 	zpool_close(zhp);
6121 
6122 	nvlist_free(policy);
6123 
6124 	return (ret);
6125 }
6126 
6127 /*
6128  * zpool reguid <pool>
6129  */
6130 int
6131 zpool_do_reguid(int argc, char **argv)
6132 {
6133 	int c;
6134 	char *poolname;
6135 	zpool_handle_t *zhp;
6136 	int ret = 0;
6137 
6138 	/* check options */
6139 	while ((c = getopt(argc, argv, "")) != -1) {
6140 		switch (c) {
6141 		case '?':
6142 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6143 			    optopt);
6144 			usage(B_FALSE);
6145 		}
6146 	}
6147 
6148 	argc -= optind;
6149 	argv += optind;
6150 
6151 	/* get pool name and check number of arguments */
6152 	if (argc < 1) {
6153 		(void) fprintf(stderr, gettext("missing pool name\n"));
6154 		usage(B_FALSE);
6155 	}
6156 
6157 	if (argc > 1) {
6158 		(void) fprintf(stderr, gettext("too many arguments\n"));
6159 		usage(B_FALSE);
6160 	}
6161 
6162 	poolname = argv[0];
6163 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6164 		return (1);
6165 
6166 	ret = zpool_reguid(zhp);
6167 
6168 	zpool_close(zhp);
6169 	return (ret);
6170 }
6171 
6172 
6173 /*
6174  * zpool reopen <pool>
6175  *
6176  * Reopen the pool so that the kernel can update the sizes of all vdevs.
6177  */
6178 int
6179 zpool_do_reopen(int argc, char **argv)
6180 {
6181 	int c;
6182 	int ret = 0;
6183 	zpool_handle_t *zhp;
6184 	char *pool;
6185 
6186 	/* check options */
6187 	while ((c = getopt(argc, argv, "")) != -1) {
6188 		switch (c) {
6189 		case '?':
6190 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6191 			    optopt);
6192 			usage(B_FALSE);
6193 		}
6194 	}
6195 
6196 	argc--;
6197 	argv++;
6198 
6199 	if (argc < 1) {
6200 		(void) fprintf(stderr, gettext("missing pool name\n"));
6201 		usage(B_FALSE);
6202 	}
6203 
6204 	if (argc > 1) {
6205 		(void) fprintf(stderr, gettext("too many arguments\n"));
6206 		usage(B_FALSE);
6207 	}
6208 
6209 	pool = argv[0];
6210 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL)
6211 		return (1);
6212 
6213 	ret = zpool_reopen(zhp);
6214 	zpool_close(zhp);
6215 	return (ret);
6216 }
6217 
6218 typedef struct scrub_cbdata {
6219 	int	cb_type;
6220 	int	cb_argc;
6221 	char	**cb_argv;
6222 	pool_scrub_cmd_t cb_scrub_cmd;
6223 } scrub_cbdata_t;
6224 
6225 static boolean_t
6226 zpool_has_checkpoint(zpool_handle_t *zhp)
6227 {
6228 	nvlist_t *config, *nvroot;
6229 
6230 	config = zpool_get_config(zhp, NULL);
6231 
6232 	if (config != NULL) {
6233 		pool_checkpoint_stat_t *pcs = NULL;
6234 		uint_t c;
6235 
6236 		nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
6237 		(void) nvlist_lookup_uint64_array(nvroot,
6238 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
6239 
6240 		if (pcs == NULL || pcs->pcs_state == CS_NONE)
6241 			return (B_FALSE);
6242 
6243 		assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
6244 		    pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
6245 		return (B_TRUE);
6246 	}
6247 
6248 	return (B_FALSE);
6249 }
6250 
6251 int
6252 scrub_callback(zpool_handle_t *zhp, void *data)
6253 {
6254 	scrub_cbdata_t *cb = data;
6255 	int err;
6256 
6257 	/*
6258 	 * Ignore faulted pools.
6259 	 */
6260 	if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
6261 		(void) fprintf(stderr, gettext("cannot scan '%s': pool is "
6262 		    "currently unavailable\n"), zpool_get_name(zhp));
6263 		return (1);
6264 	}
6265 
6266 	err = zpool_scan(zhp, cb->cb_type, cb->cb_scrub_cmd);
6267 
6268 	if (err == 0 && zpool_has_checkpoint(zhp) &&
6269 	    cb->cb_type == POOL_SCAN_SCRUB) {
6270 		(void) printf(gettext("warning: will not scrub state that "
6271 		    "belongs to the checkpoint of pool '%s'\n"),
6272 		    zpool_get_name(zhp));
6273 	}
6274 
6275 	return (err != 0);
6276 }
6277 
6278 /*
6279  * zpool scrub [-s | -p] <pool> ...
6280  *
6281  *	-s	Stop.  Stops any in-progress scrub.
6282  *	-p	Pause. Pause in-progress scrub.
6283  */
6284 int
6285 zpool_do_scrub(int argc, char **argv)
6286 {
6287 	int c;
6288 	scrub_cbdata_t cb;
6289 
6290 	cb.cb_type = POOL_SCAN_SCRUB;
6291 	cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
6292 
6293 	/* check options */
6294 	while ((c = getopt(argc, argv, "sp")) != -1) {
6295 		switch (c) {
6296 		case 's':
6297 			cb.cb_type = POOL_SCAN_NONE;
6298 			break;
6299 		case 'p':
6300 			cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
6301 			break;
6302 		case '?':
6303 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6304 			    optopt);
6305 			usage(B_FALSE);
6306 		}
6307 	}
6308 
6309 	if (cb.cb_type == POOL_SCAN_NONE &&
6310 	    cb.cb_scrub_cmd == POOL_SCRUB_PAUSE) {
6311 		(void) fprintf(stderr, gettext("invalid option combination: "
6312 		    "-s and -p are mutually exclusive\n"));
6313 		usage(B_FALSE);
6314 	}
6315 
6316 	cb.cb_argc = argc;
6317 	cb.cb_argv = argv;
6318 	argc -= optind;
6319 	argv += optind;
6320 
6321 	if (argc < 1) {
6322 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
6323 		usage(B_FALSE);
6324 	}
6325 
6326 	return (for_each_pool(argc, argv, B_TRUE, NULL, scrub_callback, &cb));
6327 }
6328 
6329 /*
6330  * zpool resilver <pool> ...
6331  *
6332  *	Restarts any in-progress resilver
6333  */
6334 int
6335 zpool_do_resilver(int argc, char **argv)
6336 {
6337 	int c;
6338 	scrub_cbdata_t cb;
6339 
6340 	cb.cb_type = POOL_SCAN_RESILVER;
6341 	cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
6342 	cb.cb_argc = argc;
6343 	cb.cb_argv = argv;
6344 
6345 	/* check options */
6346 	while ((c = getopt(argc, argv, "")) != -1) {
6347 		switch (c) {
6348 		case '?':
6349 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6350 			    optopt);
6351 			usage(B_FALSE);
6352 		}
6353 	}
6354 
6355 	argc -= optind;
6356 	argv += optind;
6357 
6358 	if (argc < 1) {
6359 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
6360 		usage(B_FALSE);
6361 	}
6362 
6363 	return (for_each_pool(argc, argv, B_TRUE, NULL, scrub_callback, &cb));
6364 }
6365 
6366 /*
6367  * zpool trim [-d] [-r <rate>] [-c | -s] <pool> [<device> ...]
6368  *
6369  *	-c		Cancel. Ends any in-progress trim.
6370  *	-d		Secure trim.  Requires kernel and device support.
6371  *	-r <rate>	Sets the TRIM rate in bytes (per second). Supports
6372  *			adding a multiplier suffix such as 'k' or 'm'.
6373  *	-s		Suspend. TRIM can then be restarted with no flags.
6374  */
6375 int
6376 zpool_do_trim(int argc, char **argv)
6377 {
6378 	struct option long_options[] = {
6379 		{"cancel",	no_argument,		NULL,	'c'},
6380 		{"secure",	no_argument,		NULL,	'd'},
6381 		{"rate",	required_argument,	NULL,	'r'},
6382 		{"suspend",	no_argument,		NULL,	's'},
6383 		{0, 0, 0, 0}
6384 	};
6385 
6386 	pool_trim_func_t cmd_type = POOL_TRIM_START;
6387 	uint64_t rate = 0;
6388 	boolean_t secure = B_FALSE;
6389 
6390 	int c;
6391 	while ((c = getopt_long(argc, argv, "cdr:s", long_options, NULL))
6392 	    != -1) {
6393 		switch (c) {
6394 		case 'c':
6395 			if (cmd_type != POOL_TRIM_START &&
6396 			    cmd_type != POOL_TRIM_CANCEL) {
6397 				(void) fprintf(stderr, gettext("-c cannot be "
6398 				    "combined with other options\n"));
6399 				usage(B_FALSE);
6400 			}
6401 			cmd_type = POOL_TRIM_CANCEL;
6402 			break;
6403 		case 'd':
6404 			if (cmd_type != POOL_TRIM_START) {
6405 				(void) fprintf(stderr, gettext("-d cannot be "
6406 				    "combined with the -c or -s options\n"));
6407 				usage(B_FALSE);
6408 			}
6409 			secure = B_TRUE;
6410 			break;
6411 		case 'r':
6412 			if (cmd_type != POOL_TRIM_START) {
6413 				(void) fprintf(stderr, gettext("-r cannot be "
6414 				    "combined with the -c or -s options\n"));
6415 				usage(B_FALSE);
6416 			}
6417 			if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
6418 				(void) fprintf(stderr, "%s: %s\n",
6419 				    gettext("invalid value for rate"),
6420 				    libzfs_error_description(g_zfs));
6421 				usage(B_FALSE);
6422 			}
6423 			break;
6424 		case 's':
6425 			if (cmd_type != POOL_TRIM_START &&
6426 			    cmd_type != POOL_TRIM_SUSPEND) {
6427 				(void) fprintf(stderr, gettext("-s cannot be "
6428 				    "combined with other options\n"));
6429 				usage(B_FALSE);
6430 			}
6431 			cmd_type = POOL_TRIM_SUSPEND;
6432 			break;
6433 		case '?':
6434 			if (optopt != 0) {
6435 				(void) fprintf(stderr,
6436 				    gettext("invalid option '%c'\n"), optopt);
6437 			} else {
6438 				(void) fprintf(stderr,
6439 				    gettext("invalid option '%s'\n"),
6440 				    argv[optind - 1]);
6441 			}
6442 			usage(B_FALSE);
6443 		}
6444 	}
6445 
6446 	argc -= optind;
6447 	argv += optind;
6448 
6449 	if (argc < 1) {
6450 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
6451 		usage(B_FALSE);
6452 		return (-1);
6453 	}
6454 
6455 	char *poolname = argv[0];
6456 	zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
6457 	if (zhp == NULL)
6458 		return (-1);
6459 
6460 	trimflags_t trim_flags = {
6461 		.secure = secure,
6462 		.rate = rate,
6463 	};
6464 
6465 	nvlist_t *vdevs = fnvlist_alloc();
6466 	if (argc == 1) {
6467 		/* no individual leaf vdevs specified, so add them all */
6468 		nvlist_t *config = zpool_get_config(zhp, NULL);
6469 		nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
6470 		    ZPOOL_CONFIG_VDEV_TREE);
6471 		zpool_collect_leaves(zhp, nvroot, vdevs);
6472 		trim_flags.fullpool = B_TRUE;
6473 	} else {
6474 		trim_flags.fullpool = B_FALSE;
6475 		for (int i = 1; i < argc; i++) {
6476 			fnvlist_add_boolean(vdevs, argv[i]);
6477 		}
6478 	}
6479 
6480 	int error = zpool_trim(zhp, cmd_type, vdevs, &trim_flags);
6481 
6482 	fnvlist_free(vdevs);
6483 	zpool_close(zhp);
6484 
6485 	return (error);
6486 }
6487 
6488 /*
6489  * zpool initialize [-c | -s] <pool> [<vdev> ...]
6490  * Initialize all unused blocks in the specified vdevs, or all vdevs in the pool
6491  * if none specified.
6492  *
6493  *	-c	Cancel. Ends active initializing.
6494  *	-s	Suspend. Initializing can then be restarted with no flags.
6495  */
6496 int
6497 zpool_do_initialize(int argc, char **argv)
6498 {
6499 	int c;
6500 	char *poolname;
6501 	zpool_handle_t *zhp;
6502 	nvlist_t *vdevs;
6503 	int err = 0;
6504 
6505 	struct option long_options[] = {
6506 		{"cancel",	no_argument,		NULL, 'c'},
6507 		{"suspend",	no_argument,		NULL, 's'},
6508 		{0, 0, 0, 0}
6509 	};
6510 
6511 	pool_initialize_func_t cmd_type = POOL_INITIALIZE_START;
6512 	while ((c = getopt_long(argc, argv, "cs", long_options, NULL)) != -1) {
6513 		switch (c) {
6514 		case 'c':
6515 			if (cmd_type != POOL_INITIALIZE_START &&
6516 			    cmd_type != POOL_INITIALIZE_CANCEL) {
6517 				(void) fprintf(stderr, gettext("-c cannot be "
6518 				    "combined with other options\n"));
6519 				usage(B_FALSE);
6520 			}
6521 			cmd_type = POOL_INITIALIZE_CANCEL;
6522 			break;
6523 		case 's':
6524 			if (cmd_type != POOL_INITIALIZE_START &&
6525 			    cmd_type != POOL_INITIALIZE_SUSPEND) {
6526 				(void) fprintf(stderr, gettext("-s cannot be "
6527 				    "combined with other options\n"));
6528 				usage(B_FALSE);
6529 			}
6530 			cmd_type = POOL_INITIALIZE_SUSPEND;
6531 			break;
6532 		case '?':
6533 			if (optopt != 0) {
6534 				(void) fprintf(stderr,
6535 				    gettext("invalid option '%c'\n"), optopt);
6536 			} else {
6537 				(void) fprintf(stderr,
6538 				    gettext("invalid option '%s'\n"),
6539 				    argv[optind - 1]);
6540 			}
6541 			usage(B_FALSE);
6542 		}
6543 	}
6544 
6545 	argc -= optind;
6546 	argv += optind;
6547 
6548 	if (argc < 1) {
6549 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
6550 		usage(B_FALSE);
6551 		return (-1);
6552 	}
6553 
6554 	poolname = argv[0];
6555 	zhp = zpool_open(g_zfs, poolname);
6556 	if (zhp == NULL)
6557 		return (-1);
6558 
6559 	vdevs = fnvlist_alloc();
6560 	if (argc == 1) {
6561 		/* no individual leaf vdevs specified, so add them all */
6562 		nvlist_t *config = zpool_get_config(zhp, NULL);
6563 		nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
6564 		    ZPOOL_CONFIG_VDEV_TREE);
6565 		zpool_collect_leaves(zhp, nvroot, vdevs);
6566 	} else {
6567 		for (int i = 1; i < argc; i++) {
6568 			fnvlist_add_boolean(vdevs, argv[i]);
6569 		}
6570 	}
6571 
6572 	err = zpool_initialize(zhp, cmd_type, vdevs);
6573 
6574 	fnvlist_free(vdevs);
6575 	zpool_close(zhp);
6576 
6577 	return (err);
6578 }
6579 
6580 /*
6581  * Print out detailed scrub status.
6582  */
6583 static void
6584 print_scan_status(pool_scan_stat_t *ps)
6585 {
6586 	time_t start, end, pause;
6587 	uint64_t total_secs_left;
6588 	uint64_t elapsed, secs_left, mins_left, hours_left, days_left;
6589 	uint64_t pass_scanned, scanned, pass_issued, issued, total;
6590 	uint_t scan_rate, issue_rate;
6591 	double fraction_done;
6592 	char processed_buf[7], scanned_buf[7], issued_buf[7], total_buf[7];
6593 	char srate_buf[7], irate_buf[7];
6594 
6595 	(void) printf(gettext("  scan: "));
6596 
6597 	/* If there's never been a scan, there's not much to say. */
6598 	if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
6599 	    ps->pss_func >= POOL_SCAN_FUNCS) {
6600 		(void) printf(gettext("none requested\n"));
6601 		return;
6602 	}
6603 
6604 	start = ps->pss_start_time;
6605 	end = ps->pss_end_time;
6606 	pause = ps->pss_pass_scrub_pause;
6607 
6608 	zfs_nicenum(ps->pss_processed, processed_buf, sizeof (processed_buf));
6609 
6610 	assert(ps->pss_func == POOL_SCAN_SCRUB ||
6611 	    ps->pss_func == POOL_SCAN_RESILVER);
6612 
6613 	/*
6614 	 * Scan is finished or canceled.
6615 	 */
6616 	if (ps->pss_state == DSS_FINISHED) {
6617 		total_secs_left = end - start;
6618 		days_left = total_secs_left / 60 / 60 / 24;
6619 		hours_left = (total_secs_left / 60 / 60) % 24;
6620 		mins_left = (total_secs_left / 60) % 60;
6621 		secs_left = (total_secs_left % 60);
6622 
6623 		if (ps->pss_func == POOL_SCAN_SCRUB) {
6624 			(void) printf(gettext("scrub repaired %s "
6625 			    "in %llu days %02llu:%02llu:%02llu "
6626 			    "with %llu errors on %s"), processed_buf,
6627 			    (u_longlong_t)days_left, (u_longlong_t)hours_left,
6628 			    (u_longlong_t)mins_left, (u_longlong_t)secs_left,
6629 			    (u_longlong_t)ps->pss_errors, ctime(&end));
6630 		} else if (ps->pss_func == POOL_SCAN_RESILVER) {
6631 			(void) printf(gettext("resilvered %s "
6632 			    "in %llu days %02llu:%02llu:%02llu "
6633 			    "with %llu errors on %s"), processed_buf,
6634 			    (u_longlong_t)days_left, (u_longlong_t)hours_left,
6635 			    (u_longlong_t)mins_left, (u_longlong_t)secs_left,
6636 			    (u_longlong_t)ps->pss_errors, ctime(&end));
6637 		}
6638 		return;
6639 	} else if (ps->pss_state == DSS_CANCELED) {
6640 		if (ps->pss_func == POOL_SCAN_SCRUB) {
6641 			(void) printf(gettext("scrub canceled on %s"),
6642 			    ctime(&end));
6643 		} else if (ps->pss_func == POOL_SCAN_RESILVER) {
6644 			(void) printf(gettext("resilver canceled on %s"),
6645 			    ctime(&end));
6646 		}
6647 		return;
6648 	}
6649 
6650 	assert(ps->pss_state == DSS_SCANNING);
6651 
6652 	/* Scan is in progress. Resilvers can't be paused. */
6653 	if (ps->pss_func == POOL_SCAN_SCRUB) {
6654 		if (pause == 0) {
6655 			(void) printf(gettext("scrub in progress since %s"),
6656 			    ctime(&start));
6657 		} else {
6658 			(void) printf(gettext("scrub paused since %s"),
6659 			    ctime(&pause));
6660 			(void) printf(gettext("\tscrub started on %s"),
6661 			    ctime(&start));
6662 		}
6663 	} else if (ps->pss_func == POOL_SCAN_RESILVER) {
6664 		(void) printf(gettext("resilver in progress since %s"),
6665 		    ctime(&start));
6666 	}
6667 
6668 	scanned = ps->pss_examined;
6669 	pass_scanned = ps->pss_pass_exam;
6670 	issued = ps->pss_issued;
6671 	pass_issued = ps->pss_pass_issued;
6672 	total = ps->pss_to_examine;
6673 
6674 	/* we are only done with a block once we have issued the IO for it  */
6675 	fraction_done = (double)issued / total;
6676 
6677 	/* elapsed time for this pass, rounding up to 1 if it's 0 */
6678 	elapsed = time(NULL) - ps->pss_pass_start;
6679 	elapsed -= ps->pss_pass_scrub_spent_paused;
6680 	elapsed = (elapsed != 0) ? elapsed : 1;
6681 
6682 	scan_rate = pass_scanned / elapsed;
6683 	issue_rate = pass_issued / elapsed;
6684 	total_secs_left = (issue_rate != 0 && total >= issued) ?
6685 	    ((total - issued) / issue_rate) : UINT64_MAX;
6686 
6687 	days_left = total_secs_left / 60 / 60 / 24;
6688 	hours_left = (total_secs_left / 60 / 60) % 24;
6689 	mins_left = (total_secs_left / 60) % 60;
6690 	secs_left = (total_secs_left % 60);
6691 
6692 	/* format all of the numbers we will be reporting */
6693 	zfs_nicenum(scanned, scanned_buf, sizeof (scanned_buf));
6694 	zfs_nicenum(issued, issued_buf, sizeof (issued_buf));
6695 	zfs_nicenum(total, total_buf, sizeof (total_buf));
6696 	zfs_nicenum(scan_rate, srate_buf, sizeof (srate_buf));
6697 	zfs_nicenum(issue_rate, irate_buf, sizeof (irate_buf));
6698 
6699 	/* do not print estimated time if we have a paused scrub */
6700 	if (pause == 0) {
6701 		(void) printf(gettext("\t%s scanned at %s/s, "
6702 		    "%s issued at %s/s, %s total\n"),
6703 		    scanned_buf, srate_buf, issued_buf, irate_buf, total_buf);
6704 	} else {
6705 		(void) printf(gettext("\t%s scanned, %s issued, %s total\n"),
6706 		    scanned_buf, issued_buf, total_buf);
6707 	}
6708 
6709 	if (ps->pss_func == POOL_SCAN_RESILVER) {
6710 		(void) printf(gettext("\t%s resilvered, %.2f%% done"),
6711 		    processed_buf, 100 * fraction_done);
6712 	} else if (ps->pss_func == POOL_SCAN_SCRUB) {
6713 		(void) printf(gettext("\t%s repaired, %.2f%% done"),
6714 		    processed_buf, 100 * fraction_done);
6715 	}
6716 
6717 	if (pause == 0) {
6718 		if (total_secs_left != UINT64_MAX &&
6719 		    issue_rate >= 10 * 1024 * 1024) {
6720 			(void) printf(gettext(", %llu days "
6721 			    "%02llu:%02llu:%02llu to go\n"),
6722 			    (u_longlong_t)days_left, (u_longlong_t)hours_left,
6723 			    (u_longlong_t)mins_left, (u_longlong_t)secs_left);
6724 		} else {
6725 			(void) printf(gettext(", no estimated "
6726 			    "completion time\n"));
6727 		}
6728 	} else {
6729 		(void) printf(gettext("\n"));
6730 	}
6731 }
6732 
6733 /*
6734  * As we don't scrub checkpointed blocks, we want to warn the
6735  * user that we skipped scanning some blocks if a checkpoint exists
6736  * or existed at any time during the scan.
6737  */
6738 static void
6739 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
6740 {
6741 	if (ps == NULL || pcs == NULL)
6742 		return;
6743 
6744 	if (pcs->pcs_state == CS_NONE ||
6745 	    pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
6746 		return;
6747 
6748 	assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
6749 
6750 	if (ps->pss_state == DSS_NONE)
6751 		return;
6752 
6753 	if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
6754 	    ps->pss_end_time < pcs->pcs_start_time)
6755 		return;
6756 
6757 	if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
6758 		(void) printf(gettext("    scan warning: skipped blocks "
6759 		    "that are only referenced by the checkpoint.\n"));
6760 	} else {
6761 		assert(ps->pss_state == DSS_SCANNING);
6762 		(void) printf(gettext("    scan warning: skipping blocks "
6763 		    "that are only referenced by the checkpoint.\n"));
6764 	}
6765 }
6766 
6767 /*
6768  * Print out detailed removal status.
6769  */
6770 static void
6771 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
6772 {
6773 	char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
6774 	time_t start, end;
6775 	nvlist_t *config, *nvroot;
6776 	nvlist_t **child;
6777 	uint_t children;
6778 	char *vdev_name;
6779 
6780 	if (prs == NULL || prs->prs_state == DSS_NONE)
6781 		return;
6782 
6783 	/*
6784 	 * Determine name of vdev.
6785 	 */
6786 	config = zpool_get_config(zhp, NULL);
6787 	nvroot = fnvlist_lookup_nvlist(config,
6788 	    ZPOOL_CONFIG_VDEV_TREE);
6789 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
6790 	    &child, &children) == 0);
6791 	assert(prs->prs_removing_vdev < children);
6792 	vdev_name = zpool_vdev_name(g_zfs, zhp,
6793 	    child[prs->prs_removing_vdev], B_TRUE);
6794 
6795 	(void) printf(gettext("remove: "));
6796 
6797 	start = prs->prs_start_time;
6798 	end = prs->prs_end_time;
6799 	zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
6800 
6801 	/*
6802 	 * Removal is finished or canceled.
6803 	 */
6804 	if (prs->prs_state == DSS_FINISHED) {
6805 		uint64_t minutes_taken = (end - start) / 60;
6806 
6807 		(void) printf(gettext("Removal of vdev %llu copied %s "
6808 		    "in %lluh%um, completed on %s"),
6809 		    (longlong_t)prs->prs_removing_vdev,
6810 		    copied_buf,
6811 		    (u_longlong_t)(minutes_taken / 60),
6812 		    (uint_t)(minutes_taken % 60),
6813 		    ctime((time_t *)&end));
6814 	} else if (prs->prs_state == DSS_CANCELED) {
6815 		(void) printf(gettext("Removal of %s canceled on %s"),
6816 		    vdev_name, ctime(&end));
6817 	} else {
6818 		uint64_t copied, total, elapsed, mins_left, hours_left;
6819 		double fraction_done;
6820 		uint_t rate;
6821 
6822 		assert(prs->prs_state == DSS_SCANNING);
6823 
6824 		/*
6825 		 * Removal is in progress.
6826 		 */
6827 		(void) printf(gettext(
6828 		    "Evacuation of %s in progress since %s"),
6829 		    vdev_name, ctime(&start));
6830 
6831 		copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
6832 		total = prs->prs_to_copy;
6833 		fraction_done = (double)copied / total;
6834 
6835 		/* elapsed time for this pass */
6836 		elapsed = time(NULL) - prs->prs_start_time;
6837 		elapsed = elapsed > 0 ? elapsed : 1;
6838 		rate = copied / elapsed;
6839 		rate = rate > 0 ? rate : 1;
6840 		mins_left = ((total - copied) / rate) / 60;
6841 		hours_left = mins_left / 60;
6842 
6843 		zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
6844 		zfs_nicenum(total, total_buf, sizeof (total_buf));
6845 		zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
6846 
6847 		/*
6848 		 * do not print estimated time if hours_left is more than
6849 		 * 30 days
6850 		 */
6851 		(void) printf(gettext("    %s copied out of %s at %s/s, "
6852 		    "%.2f%% done"),
6853 		    examined_buf, total_buf, rate_buf, 100 * fraction_done);
6854 		if (hours_left < (30 * 24)) {
6855 			(void) printf(gettext(", %lluh%um to go\n"),
6856 			    (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
6857 		} else {
6858 			(void) printf(gettext(
6859 			    ", (copy is slow, no estimated time)\n"));
6860 		}
6861 	}
6862 
6863 	if (prs->prs_mapping_memory > 0) {
6864 		char mem_buf[7];
6865 		zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
6866 		(void) printf(gettext("    %s memory used for "
6867 		    "removed device mappings\n"),
6868 		    mem_buf);
6869 	}
6870 }
6871 
6872 static void
6873 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
6874 {
6875 	time_t start;
6876 	char space_buf[7];
6877 
6878 	if (pcs == NULL || pcs->pcs_state == CS_NONE)
6879 		return;
6880 
6881 	(void) printf(gettext("checkpoint: "));
6882 
6883 	start = pcs->pcs_start_time;
6884 	zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
6885 
6886 	if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
6887 		char *date = ctime(&start);
6888 
6889 		/*
6890 		 * ctime() adds a newline at the end of the generated
6891 		 * string, thus the weird format specifier and the
6892 		 * strlen() call used to chop it off from the output.
6893 		 */
6894 		(void) printf(gettext("created %.*s, consumes %s\n"),
6895 		    strlen(date) - 1, date, space_buf);
6896 		return;
6897 	}
6898 
6899 	assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
6900 
6901 	(void) printf(gettext("discarding, %s remaining.\n"),
6902 	    space_buf);
6903 }
6904 
6905 static void
6906 print_error_log(zpool_handle_t *zhp)
6907 {
6908 	nvlist_t *nverrlist = NULL;
6909 	nvpair_t *elem;
6910 	char *pathname;
6911 	size_t len = MAXPATHLEN * 2;
6912 
6913 	if (zpool_get_errlog(zhp, &nverrlist) != 0) {
6914 		(void) printf("errors: List of errors unavailable "
6915 		    "(insufficient privileges)\n");
6916 		return;
6917 	}
6918 
6919 	(void) printf("errors: Permanent errors have been "
6920 	    "detected in the following files:\n\n");
6921 
6922 	pathname = safe_malloc(len);
6923 	elem = NULL;
6924 	while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
6925 		nvlist_t *nv;
6926 		uint64_t dsobj, obj;
6927 
6928 		verify(nvpair_value_nvlist(elem, &nv) == 0);
6929 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
6930 		    &dsobj) == 0);
6931 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
6932 		    &obj) == 0);
6933 		zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
6934 		(void) printf("%7s %s\n", "", pathname);
6935 	}
6936 	free(pathname);
6937 	nvlist_free(nverrlist);
6938 }
6939 
6940 static void
6941 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
6942     uint_t nspares)
6943 {
6944 	uint_t i;
6945 	char *name;
6946 
6947 	if (nspares == 0)
6948 		return;
6949 
6950 	(void) printf(gettext("\tspares\n"));
6951 
6952 	for (i = 0; i < nspares; i++) {
6953 		name = zpool_vdev_name(g_zfs, zhp, spares[i],
6954 		    cb->cb_name_flags);
6955 		print_status_config(zhp, cb, name, spares[i], 2, B_TRUE);
6956 		free(name);
6957 	}
6958 }
6959 
6960 static void
6961 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
6962     uint_t nl2cache)
6963 {
6964 	uint_t i;
6965 	char *name;
6966 
6967 	if (nl2cache == 0)
6968 		return;
6969 
6970 	(void) printf(gettext("\tcache\n"));
6971 
6972 	for (i = 0; i < nl2cache; i++) {
6973 		name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
6974 		    cb->cb_name_flags);
6975 		print_status_config(zhp, cb, name, l2cache[i], 2, B_FALSE);
6976 		free(name);
6977 	}
6978 }
6979 
6980 static void
6981 print_dedup_stats(nvlist_t *config)
6982 {
6983 	ddt_histogram_t *ddh;
6984 	ddt_stat_t *dds;
6985 	ddt_object_t *ddo;
6986 	uint_t c;
6987 
6988 	/*
6989 	 * If the pool was faulted then we may not have been able to
6990 	 * obtain the config. Otherwise, if we have anything in the dedup
6991 	 * table continue processing the stats.
6992 	 */
6993 	if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
6994 	    (uint64_t **)&ddo, &c) != 0)
6995 		return;
6996 
6997 	(void) printf("\n");
6998 	(void) printf(gettext(" dedup: "));
6999 	if (ddo->ddo_count == 0) {
7000 		(void) printf(gettext("no DDT entries\n"));
7001 		return;
7002 	}
7003 
7004 	(void) printf("DDT entries %llu, size %llu on disk, %llu in core\n",
7005 	    (u_longlong_t)ddo->ddo_count,
7006 	    (u_longlong_t)ddo->ddo_dspace,
7007 	    (u_longlong_t)ddo->ddo_mspace);
7008 
7009 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
7010 	    (uint64_t **)&dds, &c) == 0);
7011 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
7012 	    (uint64_t **)&ddh, &c) == 0);
7013 	zpool_dump_ddt(dds, ddh);
7014 }
7015 
7016 /*
7017  * Display a summary of pool status.  Displays a summary such as:
7018  *
7019  *        pool: tank
7020  *	status: DEGRADED
7021  *	reason: One or more devices ...
7022  *         see: http://illumos.org/msg/ZFS-xxxx-01
7023  *	config:
7024  *		mirror		DEGRADED
7025  *                c1t0d0	OK
7026  *                c2t0d0	UNAVAIL
7027  *
7028  * When given the '-v' option, we print out the complete config.  If the '-e'
7029  * option is specified, then we print out error rate information as well.
7030  */
7031 int
7032 status_callback(zpool_handle_t *zhp, void *data)
7033 {
7034 	status_cbdata_t *cbp = data;
7035 	nvlist_t *config, *nvroot;
7036 	char *msgid;
7037 	int reason;
7038 	zpool_errata_t errata;
7039 	const char *health;
7040 	uint_t c;
7041 	vdev_stat_t *vs;
7042 
7043 	config = zpool_get_config(zhp, NULL);
7044 	reason = zpool_get_status(zhp, &msgid, &errata);
7045 
7046 	cbp->cb_count++;
7047 
7048 	/*
7049 	 * If we were given 'zpool status -x', only report those pools with
7050 	 * problems.
7051 	 */
7052 	if (cbp->cb_explain &&
7053 	    (reason == ZPOOL_STATUS_OK ||
7054 	    reason == ZPOOL_STATUS_VERSION_OLDER ||
7055 	    reason == ZPOOL_STATUS_FEAT_DISABLED)) {
7056 		if (!cbp->cb_allpools) {
7057 			(void) printf(gettext("pool '%s' is healthy\n"),
7058 			    zpool_get_name(zhp));
7059 			if (cbp->cb_first)
7060 				cbp->cb_first = B_FALSE;
7061 		}
7062 		return (0);
7063 	}
7064 
7065 	if (cbp->cb_first)
7066 		cbp->cb_first = B_FALSE;
7067 	else
7068 		(void) printf("\n");
7069 
7070 	nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
7071 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
7072 	    (uint64_t **)&vs, &c) == 0);
7073 	health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
7074 
7075 	(void) printf(gettext("  pool: %s\n"), zpool_get_name(zhp));
7076 	(void) printf(gettext(" state: %s\n"), health);
7077 
7078 	switch (reason) {
7079 	case ZPOOL_STATUS_MISSING_DEV_R:
7080 		(void) printf(gettext("status: One or more devices could not "
7081 		    "be opened.  Sufficient replicas exist for\n\tthe pool to "
7082 		    "continue functioning in a degraded state.\n"));
7083 		(void) printf(gettext("action: Attach the missing device and "
7084 		    "online it using 'zpool online'.\n"));
7085 		break;
7086 
7087 	case ZPOOL_STATUS_MISSING_DEV_NR:
7088 		(void) printf(gettext("status: One or more devices could not "
7089 		    "be opened.  There are insufficient\n\treplicas for the "
7090 		    "pool to continue functioning.\n"));
7091 		(void) printf(gettext("action: Attach the missing device and "
7092 		    "online it using 'zpool online'.\n"));
7093 		break;
7094 
7095 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
7096 		(void) printf(gettext("status: One or more devices could not "
7097 		    "be used because the label is missing or\n\tinvalid.  "
7098 		    "Sufficient replicas exist for the pool to continue\n\t"
7099 		    "functioning in a degraded state.\n"));
7100 		(void) printf(gettext("action: Replace the device using "
7101 		    "'zpool replace'.\n"));
7102 		break;
7103 
7104 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
7105 		(void) printf(gettext("status: One or more devices could not "
7106 		    "be used because the label is missing \n\tor invalid.  "
7107 		    "There are insufficient replicas for the pool to "
7108 		    "continue\n\tfunctioning.\n"));
7109 		zpool_explain_recover(zpool_get_handle(zhp),
7110 		    zpool_get_name(zhp), reason, config);
7111 		break;
7112 
7113 	case ZPOOL_STATUS_FAILING_DEV:
7114 		(void) printf(gettext("status: One or more devices has "
7115 		    "experienced an unrecoverable error.  An\n\tattempt was "
7116 		    "made to correct the error.  Applications are "
7117 		    "unaffected.\n"));
7118 		(void) printf(gettext("action: Determine if the device needs "
7119 		    "to be replaced, and clear the errors\n\tusing "
7120 		    "'zpool clear' or replace the device with 'zpool "
7121 		    "replace'.\n"));
7122 		break;
7123 
7124 	case ZPOOL_STATUS_OFFLINE_DEV:
7125 		(void) printf(gettext("status: One or more devices has "
7126 		    "been taken offline by the administrator.\n\tSufficient "
7127 		    "replicas exist for the pool to continue functioning in "
7128 		    "a\n\tdegraded state.\n"));
7129 		(void) printf(gettext("action: Online the device using "
7130 		    "'zpool online' or replace the device with\n\t'zpool "
7131 		    "replace'.\n"));
7132 		break;
7133 
7134 	case ZPOOL_STATUS_REMOVED_DEV:
7135 		(void) printf(gettext("status: One or more devices has "
7136 		    "been removed by the administrator.\n\tSufficient "
7137 		    "replicas exist for the pool to continue functioning in "
7138 		    "a\n\tdegraded state.\n"));
7139 		(void) printf(gettext("action: Online the device using "
7140 		    "'zpool online' or replace the device with\n\t'zpool "
7141 		    "replace'.\n"));
7142 		break;
7143 
7144 	case ZPOOL_STATUS_RESILVERING:
7145 		(void) printf(gettext("status: One or more devices is "
7146 		    "currently being resilvered.  The pool will\n\tcontinue "
7147 		    "to function, possibly in a degraded state.\n"));
7148 		(void) printf(gettext("action: Wait for the resilver to "
7149 		    "complete.\n"));
7150 		break;
7151 
7152 	case ZPOOL_STATUS_CORRUPT_DATA:
7153 		(void) printf(gettext("status: One or more devices has "
7154 		    "experienced an error resulting in data\n\tcorruption.  "
7155 		    "Applications may be affected.\n"));
7156 		(void) printf(gettext("action: Restore the file in question "
7157 		    "if possible.  Otherwise restore the\n\tentire pool from "
7158 		    "backup.\n"));
7159 		break;
7160 
7161 	case ZPOOL_STATUS_CORRUPT_POOL:
7162 		(void) printf(gettext("status: The pool metadata is corrupted "
7163 		    "and the pool cannot be opened.\n"));
7164 		zpool_explain_recover(zpool_get_handle(zhp),
7165 		    zpool_get_name(zhp), reason, config);
7166 		break;
7167 
7168 	case ZPOOL_STATUS_VERSION_OLDER:
7169 		(void) printf(gettext("status: The pool is formatted using a "
7170 		    "legacy on-disk format.  The pool can\n\tstill be used, "
7171 		    "but some features are unavailable.\n"));
7172 		(void) printf(gettext("action: Upgrade the pool using 'zpool "
7173 		    "upgrade'.  Once this is done, the\n\tpool will no longer "
7174 		    "be accessible on software that does not support feature\n"
7175 		    "\tflags.\n"));
7176 		break;
7177 
7178 	case ZPOOL_STATUS_VERSION_NEWER:
7179 		(void) printf(gettext("status: The pool has been upgraded to a "
7180 		    "newer, incompatible on-disk version.\n\tThe pool cannot "
7181 		    "be accessed on this system.\n"));
7182 		(void) printf(gettext("action: Access the pool from a system "
7183 		    "running more recent software, or\n\trestore the pool from "
7184 		    "backup.\n"));
7185 		break;
7186 
7187 	case ZPOOL_STATUS_FEAT_DISABLED:
7188 		(void) printf(gettext("status: Some supported features are not "
7189 		    "enabled on the pool. The pool can\n\tstill be used, but "
7190 		    "some features are unavailable.\n"));
7191 		(void) printf(gettext("action: Enable all features using "
7192 		    "'zpool upgrade'. Once this is done,\n\tthe pool may no "
7193 		    "longer be accessible by software that does not support\n\t"
7194 		    "the features. See zpool-features(5) for details.\n"));
7195 		break;
7196 
7197 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
7198 		(void) printf(gettext("status: The pool cannot be accessed on "
7199 		    "this system because it uses the\n\tfollowing feature(s) "
7200 		    "not supported on this system:\n"));
7201 		zpool_print_unsup_feat(config);
7202 		(void) printf("\n");
7203 		(void) printf(gettext("action: Access the pool from a system "
7204 		    "that supports the required feature(s),\n\tor restore the "
7205 		    "pool from backup.\n"));
7206 		break;
7207 
7208 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
7209 		(void) printf(gettext("status: The pool can only be accessed "
7210 		    "in read-only mode on this system. It\n\tcannot be "
7211 		    "accessed in read-write mode because it uses the "
7212 		    "following\n\tfeature(s) not supported on this system:\n"));
7213 		zpool_print_unsup_feat(config);
7214 		(void) printf("\n");
7215 		(void) printf(gettext("action: The pool cannot be accessed in "
7216 		    "read-write mode. Import the pool with\n"
7217 		    "\t\"-o readonly=on\", access the pool from a system that "
7218 		    "supports the\n\trequired feature(s), or restore the "
7219 		    "pool from backup.\n"));
7220 		break;
7221 
7222 	case ZPOOL_STATUS_FAULTED_DEV_R:
7223 		(void) printf(gettext("status: One or more devices are "
7224 		    "faulted in response to persistent errors.\n\tSufficient "
7225 		    "replicas exist for the pool to continue functioning "
7226 		    "in a\n\tdegraded state.\n"));
7227 		(void) printf(gettext("action: Replace the faulted device, "
7228 		    "or use 'zpool clear' to mark the device\n\trepaired.\n"));
7229 		break;
7230 
7231 	case ZPOOL_STATUS_FAULTED_DEV_NR:
7232 		(void) printf(gettext("status: One or more devices are "
7233 		    "faulted in response to persistent errors.  There are "
7234 		    "insufficient replicas for the pool to\n\tcontinue "
7235 		    "functioning.\n"));
7236 		(void) printf(gettext("action: Destroy and re-create the pool "
7237 		    "from a backup source.  Manually marking the device\n"
7238 		    "\trepaired using 'zpool clear' may allow some data "
7239 		    "to be recovered.\n"));
7240 		break;
7241 
7242 	case ZPOOL_STATUS_IO_FAILURE_MMP:
7243 		(void) printf(gettext("status: The pool is suspended because "
7244 		    "multihost writes failed or were delayed;\n\tanother "
7245 		    "system could import the pool undetected.\n"));
7246 		(void) printf(gettext("action: Make sure the pool's devices "
7247 		    "are connected, then reboot your system and\n\timport the "
7248 		    "pool.\n"));
7249 		break;
7250 
7251 	case ZPOOL_STATUS_IO_FAILURE_WAIT:
7252 	case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
7253 		(void) printf(gettext("status: One or more devices are "
7254 		    "faulted in response to IO failures.\n"));
7255 		(void) printf(gettext("action: Make sure the affected devices "
7256 		    "are connected, then run 'zpool clear'.\n"));
7257 		break;
7258 
7259 	case ZPOOL_STATUS_BAD_LOG:
7260 		(void) printf(gettext("status: An intent log record "
7261 		    "could not be read.\n"
7262 		    "\tWaiting for adminstrator intervention to fix the "
7263 		    "faulted pool.\n"));
7264 		(void) printf(gettext("action: Either restore the affected "
7265 		    "device(s) and run 'zpool online',\n"
7266 		    "\tor ignore the intent log records by running "
7267 		    "'zpool clear'.\n"));
7268 		break;
7269 
7270 	case ZPOOL_STATUS_ERRATA:
7271 		(void) printf(gettext("status: Errata #%d detected.\n"),
7272 		    errata);
7273 
7274 		switch (errata) {
7275 		case ZPOOL_ERRATA_NONE:
7276 			break;
7277 
7278 		case ZPOOL_ERRATA_ZOL_2094_SCRUB:
7279 			(void) printf(gettext("action: To correct the issue "
7280 			    "run 'zpool scrub'.\n"));
7281 			break;
7282 
7283 		case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
7284 			(void) printf(gettext("\tExisting encrypted datasets "
7285 			    "contain an on-disk incompatibility\n\twhich "
7286 			    "needs to be corrected.\n"));
7287 			(void) printf(gettext("action: To correct the issue "
7288 			    "backup existing encrypted datasets to new\n\t"
7289 			    "encrypted datasets and destroy the old ones. "
7290 			    "'zfs mount -o ro' can\n\tbe used to temporarily "
7291 			    "mount existing encrypted datasets readonly.\n"));
7292 			break;
7293 
7294 		case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
7295 			(void) printf(gettext("\tExisting encrypted datasets "
7296 			    "contain an on-disk incompatibility\n\twhich "
7297 			    "needs to be corrected.\n"));
7298 			(void) printf(gettext("action: To correct the issue "
7299 			    "enable the bookmark_v2 feature and "
7300 			    "backup\n\tany existing encrypted datasets to "
7301 			    "new encrypted datasets and\n\tdestroy the old "
7302 			    "ones. If this pool does not contain any\n\t"
7303 			    "encrypted datasets, simply enable the "
7304 			    "bookmark_v2 feature\n"));
7305 			break;
7306 
7307 		default:
7308 			/*
7309 			 * All errata which allow the pool to be imported
7310 			 * must contain an action message.
7311 			 */
7312 			assert(0);
7313 		}
7314 		break;
7315 
7316 	default:
7317 		/*
7318 		 * The remaining errors can't actually be generated, yet.
7319 		 */
7320 		assert(reason == ZPOOL_STATUS_OK);
7321 	}
7322 
7323 	if (msgid != NULL)
7324 		(void) printf(gettext("   see: http://illumos.org/msg/%s\n"),
7325 		    msgid);
7326 
7327 	if (config != NULL) {
7328 		uint64_t nerr;
7329 		nvlist_t **spares, **l2cache;
7330 		uint_t nspares, nl2cache;
7331 		pool_checkpoint_stat_t *pcs = NULL;
7332 		pool_scan_stat_t *ps = NULL;
7333 		pool_removal_stat_t *prs = NULL;
7334 
7335 		(void) nvlist_lookup_uint64_array(nvroot,
7336 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
7337 		(void) nvlist_lookup_uint64_array(nvroot,
7338 		    ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &c);
7339 		(void) nvlist_lookup_uint64_array(nvroot,
7340 		    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
7341 
7342 		print_scan_status(ps);
7343 		print_checkpoint_scan_warning(ps, pcs);
7344 		print_removal_status(zhp, prs);
7345 		print_checkpoint_status(pcs);
7346 
7347 		cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
7348 		    cbp->cb_name_flags);
7349 		if (cbp->cb_namewidth < 10)
7350 			cbp->cb_namewidth = 10;
7351 
7352 		(void) printf(gettext("config:\n\n"));
7353 		(void) printf(gettext("\t%-*s  %-8s %5s %5s %5s\n"),
7354 		    cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
7355 		    "CKSUM");
7356 
7357 		if (cbp->cb_print_slow_ios)
7358 			(void) printf(" %5s", gettext("SLOW"));
7359 
7360 		print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
7361 		    B_FALSE);
7362 
7363 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
7364 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
7365 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
7366 
7367 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
7368 		    &l2cache, &nl2cache) == 0)
7369 			print_l2cache(zhp, cbp, l2cache, nl2cache);
7370 
7371 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
7372 		    &spares, &nspares) == 0)
7373 			print_spares(zhp, cbp, spares, nspares);
7374 
7375 		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
7376 		    &nerr) == 0) {
7377 			nvlist_t *nverrlist = NULL;
7378 
7379 			/*
7380 			 * If the approximate error count is small, get a
7381 			 * precise count by fetching the entire log and
7382 			 * uniquifying the results.
7383 			 */
7384 			if (nerr > 0 && nerr < 100 && !cbp->cb_verbose &&
7385 			    zpool_get_errlog(zhp, &nverrlist) == 0) {
7386 				nvpair_t *elem;
7387 
7388 				elem = NULL;
7389 				nerr = 0;
7390 				while ((elem = nvlist_next_nvpair(nverrlist,
7391 				    elem)) != NULL) {
7392 					nerr++;
7393 				}
7394 			}
7395 			nvlist_free(nverrlist);
7396 
7397 			(void) printf("\n");
7398 
7399 			if (nerr == 0)
7400 				(void) printf(gettext("errors: No known data "
7401 				    "errors\n"));
7402 			else if (!cbp->cb_verbose)
7403 				(void) printf(gettext("errors: %llu data "
7404 				    "errors, use '-v' for a list\n"),
7405 				    (u_longlong_t)nerr);
7406 			else
7407 				print_error_log(zhp);
7408 		}
7409 
7410 		if (cbp->cb_dedup_stats)
7411 			print_dedup_stats(config);
7412 	} else {
7413 		(void) printf(gettext("config: The configuration cannot be "
7414 		    "determined.\n"));
7415 	}
7416 
7417 	return (0);
7418 }
7419 
7420 /*
7421  * zpool status [-igLpPstvx] [-T d|u] [pool] ... [interval [count]]
7422  *
7423  *	-i	Display vdev initialization status.
7424  *	-g	Display guid for individual vdev name.
7425  *	-L	Follow links when resolving vdev path name.
7426  *	-p	Display values in parsable (exact) format.
7427  *	-P	Display full path for vdev name.
7428  *	-s	Display slow IOs column.
7429  *	-v	Display complete error logs
7430  *	-x	Display only pools with potential problems
7431  *	-D	Display dedup status (undocumented)
7432  *	-t	Display vdev TRIM status.
7433  *	-T	Display a timestamp in date(1) or Unix format
7434  *
7435  * Describes the health status of all pools or some subset.
7436  */
7437 int
7438 zpool_do_status(int argc, char **argv)
7439 {
7440 	int c;
7441 	int ret;
7442 	float interval = 0;
7443 	unsigned long count = 0;
7444 	status_cbdata_t cb = { 0 };
7445 
7446 	/* check options */
7447 	while ((c = getopt(argc, argv, "igLpPsvxDtT:")) != -1) {
7448 		switch (c) {
7449 		case 'i':
7450 			cb.cb_print_vdev_init = B_TRUE;
7451 			break;
7452 		case 'g':
7453 			cb.cb_name_flags |= VDEV_NAME_GUID;
7454 			break;
7455 		case 'L':
7456 			cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
7457 			break;
7458 		case 'p':
7459 			cb.cb_literal = B_TRUE;
7460 			break;
7461 		case 'P':
7462 			cb.cb_name_flags |= VDEV_NAME_PATH;
7463 			break;
7464 		case 's':
7465 			cb.cb_print_slow_ios = B_TRUE;
7466 			break;
7467 		case 'v':
7468 			cb.cb_verbose = B_TRUE;
7469 			break;
7470 		case 'x':
7471 			cb.cb_explain = B_TRUE;
7472 			break;
7473 		case 'D':
7474 			cb.cb_dedup_stats = B_TRUE;
7475 			break;
7476 		case 't':
7477 			cb.cb_print_vdev_trim = B_TRUE;
7478 			break;
7479 		case 'T':
7480 			get_timestamp_arg(*optarg);
7481 			break;
7482 		case '?':
7483 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7484 			    optopt);
7485 			usage(B_FALSE);
7486 		}
7487 	}
7488 
7489 	argc -= optind;
7490 	argv += optind;
7491 
7492 	get_interval_count(&argc, argv, &interval, &count);
7493 
7494 	if (argc == 0)
7495 		cb.cb_allpools = B_TRUE;
7496 
7497 	cb.cb_first = B_TRUE;
7498 	cb.cb_print_status = B_TRUE;
7499 
7500 	for (;;) {
7501 		if (timestamp_fmt != NODATE)
7502 			print_timestamp(timestamp_fmt);
7503 
7504 		ret = for_each_pool(argc, argv, B_TRUE, NULL,
7505 		    status_callback, &cb);
7506 
7507 		if (argc == 0 && cb.cb_count == 0)
7508 			(void) printf(gettext("no pools available\n"));
7509 		else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
7510 			(void) printf(gettext("all pools are healthy\n"));
7511 
7512 		if (ret != 0)
7513 			return (ret);
7514 
7515 		if (interval == 0)
7516 			break;
7517 
7518 		if (count != 0 && --count == 0)
7519 			break;
7520 
7521 		(void) fsleep(interval);
7522 	}
7523 
7524 	return (0);
7525 }
7526 
7527 typedef struct upgrade_cbdata {
7528 	int	cb_first;
7529 	int	cb_argc;
7530 	uint64_t cb_version;
7531 	char	**cb_argv;
7532 } upgrade_cbdata_t;
7533 
7534 static int
7535 upgrade_version(zpool_handle_t *zhp, uint64_t version)
7536 {
7537 	int ret;
7538 	nvlist_t *config;
7539 	uint64_t oldversion;
7540 
7541 	config = zpool_get_config(zhp, NULL);
7542 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
7543 	    &oldversion) == 0);
7544 
7545 	assert(SPA_VERSION_IS_SUPPORTED(oldversion));
7546 	assert(oldversion < version);
7547 
7548 	ret = zpool_upgrade(zhp, version);
7549 	if (ret != 0)
7550 		return (ret);
7551 
7552 	if (version >= SPA_VERSION_FEATURES) {
7553 		(void) printf(gettext("Successfully upgraded "
7554 		    "'%s' from version %llu to feature flags.\n"),
7555 		    zpool_get_name(zhp), oldversion);
7556 	} else {
7557 		(void) printf(gettext("Successfully upgraded "
7558 		    "'%s' from version %llu to version %llu.\n"),
7559 		    zpool_get_name(zhp), oldversion, version);
7560 	}
7561 
7562 	return (0);
7563 }
7564 
7565 static int
7566 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
7567 {
7568 	int i, ret, count;
7569 	boolean_t firstff = B_TRUE;
7570 	nvlist_t *enabled = zpool_get_features(zhp);
7571 
7572 	count = 0;
7573 	for (i = 0; i < SPA_FEATURES; i++) {
7574 		const char *fname = spa_feature_table[i].fi_uname;
7575 		const char *fguid = spa_feature_table[i].fi_guid;
7576 		if (!nvlist_exists(enabled, fguid)) {
7577 			char *propname;
7578 			verify(-1 != asprintf(&propname, "feature@%s", fname));
7579 			ret = zpool_set_prop(zhp, propname,
7580 			    ZFS_FEATURE_ENABLED);
7581 			if (ret != 0) {
7582 				free(propname);
7583 				return (ret);
7584 			}
7585 			count++;
7586 
7587 			if (firstff) {
7588 				(void) printf(gettext("Enabled the "
7589 				    "following features on '%s':\n"),
7590 				    zpool_get_name(zhp));
7591 				firstff = B_FALSE;
7592 			}
7593 			(void) printf(gettext("  %s\n"), fname);
7594 			free(propname);
7595 		}
7596 	}
7597 
7598 	if (countp != NULL)
7599 		*countp = count;
7600 	return (0);
7601 }
7602 
7603 static int
7604 upgrade_cb(zpool_handle_t *zhp, void *arg)
7605 {
7606 	upgrade_cbdata_t *cbp = arg;
7607 	nvlist_t *config;
7608 	uint64_t version;
7609 	boolean_t printnl = B_FALSE;
7610 	int ret;
7611 
7612 	config = zpool_get_config(zhp, NULL);
7613 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
7614 	    &version) == 0);
7615 
7616 	assert(SPA_VERSION_IS_SUPPORTED(version));
7617 
7618 	if (version < cbp->cb_version) {
7619 		cbp->cb_first = B_FALSE;
7620 		ret = upgrade_version(zhp, cbp->cb_version);
7621 		if (ret != 0)
7622 			return (ret);
7623 		printnl = B_TRUE;
7624 
7625 		/*
7626 		 * If they did "zpool upgrade -a", then we could
7627 		 * be doing ioctls to different pools.  We need
7628 		 * to log this history once to each pool, and bypass
7629 		 * the normal history logging that happens in main().
7630 		 */
7631 		(void) zpool_log_history(g_zfs, history_str);
7632 		log_history = B_FALSE;
7633 	}
7634 
7635 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
7636 		int count;
7637 		ret = upgrade_enable_all(zhp, &count);
7638 		if (ret != 0)
7639 			return (ret);
7640 
7641 		if (count > 0) {
7642 			cbp->cb_first = B_FALSE;
7643 			printnl = B_TRUE;
7644 		}
7645 	}
7646 
7647 	if (printnl) {
7648 		(void) printf(gettext("\n"));
7649 	}
7650 
7651 	return (0);
7652 }
7653 
7654 static int
7655 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
7656 {
7657 	upgrade_cbdata_t *cbp = arg;
7658 	nvlist_t *config;
7659 	uint64_t version;
7660 
7661 	config = zpool_get_config(zhp, NULL);
7662 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
7663 	    &version) == 0);
7664 
7665 	assert(SPA_VERSION_IS_SUPPORTED(version));
7666 
7667 	if (version < SPA_VERSION_FEATURES) {
7668 		if (cbp->cb_first) {
7669 			(void) printf(gettext("The following pools are "
7670 			    "formatted with legacy version numbers and can\n"
7671 			    "be upgraded to use feature flags.  After "
7672 			    "being upgraded, these pools\nwill no "
7673 			    "longer be accessible by software that does not "
7674 			    "support feature\nflags.\n\n"));
7675 			(void) printf(gettext("VER  POOL\n"));
7676 			(void) printf(gettext("---  ------------\n"));
7677 			cbp->cb_first = B_FALSE;
7678 		}
7679 
7680 		(void) printf("%2llu   %s\n", (u_longlong_t)version,
7681 		    zpool_get_name(zhp));
7682 	}
7683 
7684 	return (0);
7685 }
7686 
7687 static int
7688 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
7689 {
7690 	upgrade_cbdata_t *cbp = arg;
7691 	nvlist_t *config;
7692 	uint64_t version;
7693 
7694 	config = zpool_get_config(zhp, NULL);
7695 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
7696 	    &version) == 0);
7697 
7698 	if (version >= SPA_VERSION_FEATURES) {
7699 		int i;
7700 		boolean_t poolfirst = B_TRUE;
7701 		nvlist_t *enabled = zpool_get_features(zhp);
7702 
7703 		for (i = 0; i < SPA_FEATURES; i++) {
7704 			const char *fguid = spa_feature_table[i].fi_guid;
7705 			const char *fname = spa_feature_table[i].fi_uname;
7706 			if (!nvlist_exists(enabled, fguid)) {
7707 				if (cbp->cb_first) {
7708 					(void) printf(gettext("\nSome "
7709 					    "supported features are not "
7710 					    "enabled on the following pools. "
7711 					    "Once a\nfeature is enabled the "
7712 					    "pool may become incompatible with "
7713 					    "software\nthat does not support "
7714 					    "the feature. See "
7715 					    "zpool-features(5) for "
7716 					    "details.\n\n"));
7717 					(void) printf(gettext("POOL  "
7718 					    "FEATURE\n"));
7719 					(void) printf(gettext("------"
7720 					    "---------\n"));
7721 					cbp->cb_first = B_FALSE;
7722 				}
7723 
7724 				if (poolfirst) {
7725 					(void) printf(gettext("%s\n"),
7726 					    zpool_get_name(zhp));
7727 					poolfirst = B_FALSE;
7728 				}
7729 
7730 				(void) printf(gettext("      %s\n"), fname);
7731 			}
7732 		}
7733 	}
7734 
7735 	return (0);
7736 }
7737 
7738 /* ARGSUSED */
7739 static int
7740 upgrade_one(zpool_handle_t *zhp, void *data)
7741 {
7742 	boolean_t printnl = B_FALSE;
7743 	upgrade_cbdata_t *cbp = data;
7744 	uint64_t cur_version;
7745 	int ret;
7746 
7747 	if (strcmp("log", zpool_get_name(zhp)) == 0) {
7748 		(void) printf(gettext("'log' is now a reserved word\n"
7749 		    "Pool 'log' must be renamed using export and import"
7750 		    " to upgrade.\n"));
7751 		return (1);
7752 	}
7753 
7754 	cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
7755 	if (cur_version > cbp->cb_version) {
7756 		(void) printf(gettext("Pool '%s' is already formatted "
7757 		    "using more current version '%llu'.\n\n"),
7758 		    zpool_get_name(zhp), cur_version);
7759 		return (0);
7760 	}
7761 
7762 	if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
7763 		(void) printf(gettext("Pool '%s' is already formatted "
7764 		    "using version %llu.\n\n"), zpool_get_name(zhp),
7765 		    cbp->cb_version);
7766 		return (0);
7767 	}
7768 
7769 	if (cur_version != cbp->cb_version) {
7770 		printnl = B_TRUE;
7771 		ret = upgrade_version(zhp, cbp->cb_version);
7772 		if (ret != 0)
7773 			return (ret);
7774 	}
7775 
7776 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
7777 		int count = 0;
7778 		ret = upgrade_enable_all(zhp, &count);
7779 		if (ret != 0)
7780 			return (ret);
7781 
7782 		if (count != 0) {
7783 			printnl = B_TRUE;
7784 		} else if (cur_version == SPA_VERSION) {
7785 			(void) printf(gettext("Pool '%s' already has all "
7786 			    "supported features enabled.\n"),
7787 			    zpool_get_name(zhp));
7788 		}
7789 	}
7790 
7791 	if (printnl) {
7792 		(void) printf(gettext("\n"));
7793 	}
7794 
7795 	return (0);
7796 }
7797 
7798 /*
7799  * zpool upgrade
7800  * zpool upgrade -v
7801  * zpool upgrade [-V version] <-a | pool ...>
7802  *
7803  * With no arguments, display downrev'd ZFS pool available for upgrade.
7804  * Individual pools can be upgraded by specifying the pool, and '-a' will
7805  * upgrade all pools.
7806  */
7807 int
7808 zpool_do_upgrade(int argc, char **argv)
7809 {
7810 	int c;
7811 	upgrade_cbdata_t cb = { 0 };
7812 	int ret = 0;
7813 	boolean_t showversions = B_FALSE;
7814 	boolean_t upgradeall = B_FALSE;
7815 	char *end;
7816 
7817 
7818 	/* check options */
7819 	while ((c = getopt(argc, argv, ":avV:")) != -1) {
7820 		switch (c) {
7821 		case 'a':
7822 			upgradeall = B_TRUE;
7823 			break;
7824 		case 'v':
7825 			showversions = B_TRUE;
7826 			break;
7827 		case 'V':
7828 			cb.cb_version = strtoll(optarg, &end, 10);
7829 			if (*end != '\0' ||
7830 			    !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
7831 				(void) fprintf(stderr,
7832 				    gettext("invalid version '%s'\n"), optarg);
7833 				usage(B_FALSE);
7834 			}
7835 			break;
7836 		case ':':
7837 			(void) fprintf(stderr, gettext("missing argument for "
7838 			    "'%c' option\n"), optopt);
7839 			usage(B_FALSE);
7840 			break;
7841 		case '?':
7842 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7843 			    optopt);
7844 			usage(B_FALSE);
7845 		}
7846 	}
7847 
7848 	cb.cb_argc = argc;
7849 	cb.cb_argv = argv;
7850 	argc -= optind;
7851 	argv += optind;
7852 
7853 	if (cb.cb_version == 0) {
7854 		cb.cb_version = SPA_VERSION;
7855 	} else if (!upgradeall && argc == 0) {
7856 		(void) fprintf(stderr, gettext("-V option is "
7857 		    "incompatible with other arguments\n"));
7858 		usage(B_FALSE);
7859 	}
7860 
7861 	if (showversions) {
7862 		if (upgradeall || argc != 0) {
7863 			(void) fprintf(stderr, gettext("-v option is "
7864 			    "incompatible with other arguments\n"));
7865 			usage(B_FALSE);
7866 		}
7867 	} else if (upgradeall) {
7868 		if (argc != 0) {
7869 			(void) fprintf(stderr, gettext("-a option should not "
7870 			    "be used along with a pool name\n"));
7871 			usage(B_FALSE);
7872 		}
7873 	}
7874 
7875 	(void) printf(gettext("This system supports ZFS pool feature "
7876 	    "flags.\n\n"));
7877 	if (showversions) {
7878 		int i;
7879 
7880 		(void) printf(gettext("The following features are "
7881 		    "supported:\n\n"));
7882 		(void) printf(gettext("FEAT DESCRIPTION\n"));
7883 		(void) printf("----------------------------------------------"
7884 		    "---------------\n");
7885 		for (i = 0; i < SPA_FEATURES; i++) {
7886 			zfeature_info_t *fi = &spa_feature_table[i];
7887 			const char *ro =
7888 			    (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
7889 			    " (read-only compatible)" : "";
7890 
7891 			(void) printf("%-37s%s\n", fi->fi_uname, ro);
7892 			(void) printf("     %s\n", fi->fi_desc);
7893 		}
7894 		(void) printf("\n");
7895 
7896 		(void) printf(gettext("The following legacy versions are also "
7897 		    "supported:\n\n"));
7898 		(void) printf(gettext("VER  DESCRIPTION\n"));
7899 		(void) printf("---  -----------------------------------------"
7900 		    "---------------\n");
7901 		(void) printf(gettext(" 1   Initial ZFS version\n"));
7902 		(void) printf(gettext(" 2   Ditto blocks "
7903 		    "(replicated metadata)\n"));
7904 		(void) printf(gettext(" 3   Hot spares and double parity "
7905 		    "RAID-Z\n"));
7906 		(void) printf(gettext(" 4   zpool history\n"));
7907 		(void) printf(gettext(" 5   Compression using the gzip "
7908 		    "algorithm\n"));
7909 		(void) printf(gettext(" 6   bootfs pool property\n"));
7910 		(void) printf(gettext(" 7   Separate intent log devices\n"));
7911 		(void) printf(gettext(" 8   Delegated administration\n"));
7912 		(void) printf(gettext(" 9   refquota and refreservation "
7913 		    "properties\n"));
7914 		(void) printf(gettext(" 10  Cache devices\n"));
7915 		(void) printf(gettext(" 11  Improved scrub performance\n"));
7916 		(void) printf(gettext(" 12  Snapshot properties\n"));
7917 		(void) printf(gettext(" 13  snapused property\n"));
7918 		(void) printf(gettext(" 14  passthrough-x aclinherit\n"));
7919 		(void) printf(gettext(" 15  user/group space accounting\n"));
7920 		(void) printf(gettext(" 16  stmf property support\n"));
7921 		(void) printf(gettext(" 17  Triple-parity RAID-Z\n"));
7922 		(void) printf(gettext(" 18  Snapshot user holds\n"));
7923 		(void) printf(gettext(" 19  Log device removal\n"));
7924 		(void) printf(gettext(" 20  Compression using zle "
7925 		    "(zero-length encoding)\n"));
7926 		(void) printf(gettext(" 21  Deduplication\n"));
7927 		(void) printf(gettext(" 22  Received properties\n"));
7928 		(void) printf(gettext(" 23  Slim ZIL\n"));
7929 		(void) printf(gettext(" 24  System attributes\n"));
7930 		(void) printf(gettext(" 25  Improved scrub stats\n"));
7931 		(void) printf(gettext(" 26  Improved snapshot deletion "
7932 		    "performance\n"));
7933 		(void) printf(gettext(" 27  Improved snapshot creation "
7934 		    "performance\n"));
7935 		(void) printf(gettext(" 28  Multiple vdev replacements\n"));
7936 		(void) printf(gettext("\nFor more information on a particular "
7937 		    "version, including supported releases,\n"));
7938 		(void) printf(gettext("see the ZFS Administration Guide.\n\n"));
7939 	} else if (argc == 0 && upgradeall) {
7940 		cb.cb_first = B_TRUE;
7941 		ret = zpool_iter(g_zfs, upgrade_cb, &cb);
7942 		if (ret == 0 && cb.cb_first) {
7943 			if (cb.cb_version == SPA_VERSION) {
7944 				(void) printf(gettext("All pools are already "
7945 				    "formatted using feature flags.\n\n"));
7946 				(void) printf(gettext("Every feature flags "
7947 				    "pool already has all supported features "
7948 				    "enabled.\n"));
7949 			} else {
7950 				(void) printf(gettext("All pools are already "
7951 				    "formatted with version %llu or higher.\n"),
7952 				    cb.cb_version);
7953 			}
7954 		}
7955 	} else if (argc == 0) {
7956 		cb.cb_first = B_TRUE;
7957 		ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
7958 		assert(ret == 0);
7959 
7960 		if (cb.cb_first) {
7961 			(void) printf(gettext("All pools are formatted "
7962 			    "using feature flags.\n\n"));
7963 		} else {
7964 			(void) printf(gettext("\nUse 'zpool upgrade -v' "
7965 			    "for a list of available legacy versions.\n"));
7966 		}
7967 
7968 		cb.cb_first = B_TRUE;
7969 		ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
7970 		assert(ret == 0);
7971 
7972 		if (cb.cb_first) {
7973 			(void) printf(gettext("Every feature flags pool has "
7974 			    "all supported features enabled.\n"));
7975 		} else {
7976 			(void) printf(gettext("\n"));
7977 		}
7978 	} else {
7979 		ret = for_each_pool(argc, argv, B_FALSE, NULL,
7980 		    upgrade_one, &cb);
7981 	}
7982 
7983 	return (ret);
7984 }
7985 
7986 typedef struct hist_cbdata {
7987 	boolean_t first;
7988 	boolean_t longfmt;
7989 	boolean_t internal;
7990 } hist_cbdata_t;
7991 
7992 static void
7993 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
7994 {
7995 	nvlist_t **records;
7996 	uint_t numrecords;
7997 	int i;
7998 
7999 	verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
8000 	    &records, &numrecords) == 0);
8001 	for (i = 0; i < numrecords; i++) {
8002 		nvlist_t *rec = records[i];
8003 		char tbuf[30] = "";
8004 
8005 		if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
8006 			time_t tsec;
8007 			struct tm t;
8008 
8009 			tsec = fnvlist_lookup_uint64(records[i],
8010 			    ZPOOL_HIST_TIME);
8011 			(void) localtime_r(&tsec, &t);
8012 			(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
8013 		}
8014 
8015 		if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
8016 			(void) printf("%s %s", tbuf,
8017 			    fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
8018 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
8019 			int ievent =
8020 			    fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
8021 			if (!cb->internal)
8022 				continue;
8023 			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
8024 				(void) printf("%s unrecognized record:\n",
8025 				    tbuf);
8026 				dump_nvlist(rec, 4);
8027 				continue;
8028 			}
8029 			(void) printf("%s [internal %s txg:%lld] %s", tbuf,
8030 			    zfs_history_event_names[ievent],
8031 			    fnvlist_lookup_uint64(rec, ZPOOL_HIST_TXG),
8032 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
8033 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
8034 			if (!cb->internal)
8035 				continue;
8036 			(void) printf("%s [txg:%lld] %s", tbuf,
8037 			    fnvlist_lookup_uint64(rec, ZPOOL_HIST_TXG),
8038 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
8039 			if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
8040 				(void) printf(" %s (%llu)",
8041 				    fnvlist_lookup_string(rec,
8042 				    ZPOOL_HIST_DSNAME),
8043 				    fnvlist_lookup_uint64(rec,
8044 				    ZPOOL_HIST_DSID));
8045 			}
8046 			(void) printf(" %s", fnvlist_lookup_string(rec,
8047 			    ZPOOL_HIST_INT_STR));
8048 		} else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
8049 			if (!cb->internal)
8050 				continue;
8051 			(void) printf("%s ioctl %s\n", tbuf,
8052 			    fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
8053 			if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
8054 				(void) printf("    input:\n");
8055 				dump_nvlist(fnvlist_lookup_nvlist(rec,
8056 				    ZPOOL_HIST_INPUT_NVL), 8);
8057 			}
8058 			if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
8059 				(void) printf("    output:\n");
8060 				dump_nvlist(fnvlist_lookup_nvlist(rec,
8061 				    ZPOOL_HIST_OUTPUT_NVL), 8);
8062 			}
8063 			if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
8064 				(void) printf("    errno: %lld\n",
8065 				    fnvlist_lookup_int64(rec,
8066 				    ZPOOL_HIST_ERRNO));
8067 			}
8068 		} else {
8069 			if (!cb->internal)
8070 				continue;
8071 			(void) printf("%s unrecognized record:\n", tbuf);
8072 			dump_nvlist(rec, 4);
8073 		}
8074 
8075 		if (!cb->longfmt) {
8076 			(void) printf("\n");
8077 			continue;
8078 		}
8079 		(void) printf(" [");
8080 		if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
8081 			uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
8082 			struct passwd *pwd = getpwuid(who);
8083 			(void) printf("user %d ", (int)who);
8084 			if (pwd != NULL)
8085 				(void) printf("(%s) ", pwd->pw_name);
8086 		}
8087 		if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
8088 			(void) printf("on %s",
8089 			    fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
8090 		}
8091 		if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
8092 			(void) printf(":%s",
8093 			    fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
8094 		}
8095 		(void) printf("]");
8096 		(void) printf("\n");
8097 	}
8098 }
8099 
8100 /*
8101  * Print out the command history for a specific pool.
8102  */
8103 static int
8104 get_history_one(zpool_handle_t *zhp, void *data)
8105 {
8106 	nvlist_t *nvhis;
8107 	int ret;
8108 	hist_cbdata_t *cb = (hist_cbdata_t *)data;
8109 	uint64_t off = 0;
8110 	boolean_t eof = B_FALSE;
8111 
8112 	cb->first = B_FALSE;
8113 
8114 	(void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
8115 
8116 	while (!eof) {
8117 		if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
8118 			return (ret);
8119 
8120 		print_history_records(nvhis, cb);
8121 		nvlist_free(nvhis);
8122 	}
8123 	(void) printf("\n");
8124 
8125 	return (ret);
8126 }
8127 
8128 /*
8129  * zpool history <pool>
8130  *
8131  * Displays the history of commands that modified pools.
8132  */
8133 int
8134 zpool_do_history(int argc, char **argv)
8135 {
8136 	hist_cbdata_t cbdata = { 0 };
8137 	int ret;
8138 	int c;
8139 
8140 	cbdata.first = B_TRUE;
8141 	/* check options */
8142 	while ((c = getopt(argc, argv, "li")) != -1) {
8143 		switch (c) {
8144 		case 'l':
8145 			cbdata.longfmt = B_TRUE;
8146 			break;
8147 		case 'i':
8148 			cbdata.internal = B_TRUE;
8149 			break;
8150 		case '?':
8151 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8152 			    optopt);
8153 			usage(B_FALSE);
8154 		}
8155 	}
8156 	argc -= optind;
8157 	argv += optind;
8158 
8159 	ret = for_each_pool(argc, argv, B_FALSE,  NULL, get_history_one,
8160 	    &cbdata);
8161 
8162 	if (argc == 0 && cbdata.first == B_TRUE) {
8163 		(void) printf(gettext("no pools available\n"));
8164 		return (0);
8165 	}
8166 
8167 	return (ret);
8168 }
8169 
8170 static int
8171 get_callback(zpool_handle_t *zhp, void *data)
8172 {
8173 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
8174 	char value[MAXNAMELEN];
8175 	zprop_source_t srctype;
8176 	zprop_list_t *pl;
8177 
8178 	for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
8179 
8180 		/*
8181 		 * Skip the special fake placeholder. This will also skip
8182 		 * over the name property when 'all' is specified.
8183 		 */
8184 		if (pl->pl_prop == ZPOOL_PROP_NAME &&
8185 		    pl == cbp->cb_proplist)
8186 			continue;
8187 
8188 		if (pl->pl_prop == ZPROP_INVAL &&
8189 		    (zpool_prop_feature(pl->pl_user_prop) ||
8190 		    zpool_prop_unsupported(pl->pl_user_prop))) {
8191 			srctype = ZPROP_SRC_LOCAL;
8192 
8193 			if (zpool_prop_get_feature(zhp, pl->pl_user_prop,
8194 			    value, sizeof (value)) == 0) {
8195 				zprop_print_one_property(zpool_get_name(zhp),
8196 				    cbp, pl->pl_user_prop, value, srctype,
8197 				    NULL, NULL);
8198 			}
8199 		} else {
8200 			if (zpool_get_prop(zhp, pl->pl_prop, value,
8201 			    sizeof (value), &srctype, cbp->cb_literal) != 0)
8202 				continue;
8203 
8204 			zprop_print_one_property(zpool_get_name(zhp), cbp,
8205 			    zpool_prop_to_name(pl->pl_prop), value, srctype,
8206 			    NULL, NULL);
8207 		}
8208 	}
8209 	return (0);
8210 }
8211 
8212 /*
8213  * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
8214  *
8215  *	-H	Scripted mode.  Don't display headers, and separate properties
8216  *		by a single tab.
8217  *	-o	List of columns to display.  Defaults to
8218  *		"name,property,value,source".
8219  *	-p	Diplay values in parsable (exact) format.
8220  *
8221  * Get properties of pools in the system. Output space statistics
8222  * for each one as well as other attributes.
8223  */
8224 int
8225 zpool_do_get(int argc, char **argv)
8226 {
8227 	zprop_get_cbdata_t cb = { 0 };
8228 	zprop_list_t fake_name = { 0 };
8229 	int ret;
8230 	int c, i;
8231 	char *value;
8232 
8233 	cb.cb_first = B_TRUE;
8234 
8235 	/*
8236 	 * Set up default columns and sources.
8237 	 */
8238 	cb.cb_sources = ZPROP_SRC_ALL;
8239 	cb.cb_columns[0] = GET_COL_NAME;
8240 	cb.cb_columns[1] = GET_COL_PROPERTY;
8241 	cb.cb_columns[2] = GET_COL_VALUE;
8242 	cb.cb_columns[3] = GET_COL_SOURCE;
8243 	cb.cb_type = ZFS_TYPE_POOL;
8244 
8245 	/* check options */
8246 	while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
8247 		switch (c) {
8248 		case 'p':
8249 			cb.cb_literal = B_TRUE;
8250 			break;
8251 		case 'H':
8252 			cb.cb_scripted = B_TRUE;
8253 			break;
8254 		case 'o':
8255 			bzero(&cb.cb_columns, sizeof (cb.cb_columns));
8256 			i = 0;
8257 			while (*optarg != '\0') {
8258 				static char *col_subopts[] =
8259 				{ "name", "property", "value", "source",
8260 				"all", NULL };
8261 
8262 				if (i == ZFS_GET_NCOLS) {
8263 					(void) fprintf(stderr, gettext("too "
8264 					"many fields given to -o "
8265 					"option\n"));
8266 					usage(B_FALSE);
8267 				}
8268 
8269 				switch (getsubopt(&optarg, col_subopts,
8270 				    &value)) {
8271 				case 0:
8272 					cb.cb_columns[i++] = GET_COL_NAME;
8273 					break;
8274 				case 1:
8275 					cb.cb_columns[i++] = GET_COL_PROPERTY;
8276 					break;
8277 				case 2:
8278 					cb.cb_columns[i++] = GET_COL_VALUE;
8279 					break;
8280 				case 3:
8281 					cb.cb_columns[i++] = GET_COL_SOURCE;
8282 					break;
8283 				case 4:
8284 					if (i > 0) {
8285 						(void) fprintf(stderr,
8286 						    gettext("\"all\" conflicts "
8287 						    "with specific fields "
8288 						    "given to -o option\n"));
8289 						usage(B_FALSE);
8290 					}
8291 					cb.cb_columns[0] = GET_COL_NAME;
8292 					cb.cb_columns[1] = GET_COL_PROPERTY;
8293 					cb.cb_columns[2] = GET_COL_VALUE;
8294 					cb.cb_columns[3] = GET_COL_SOURCE;
8295 					i = ZFS_GET_NCOLS;
8296 					break;
8297 				default:
8298 					(void) fprintf(stderr,
8299 					    gettext("invalid column name "
8300 					    "'%s'\n"), value);
8301 					usage(B_FALSE);
8302 				}
8303 			}
8304 			break;
8305 		case '?':
8306 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8307 			    optopt);
8308 			usage(B_FALSE);
8309 		}
8310 	}
8311 
8312 	argc -= optind;
8313 	argv += optind;
8314 
8315 	if (argc < 1) {
8316 		(void) fprintf(stderr, gettext("missing property "
8317 		    "argument\n"));
8318 		usage(B_FALSE);
8319 	}
8320 
8321 	if (zprop_get_list(g_zfs, argv[0], &cb.cb_proplist,
8322 	    ZFS_TYPE_POOL) != 0)
8323 		usage(B_FALSE);
8324 
8325 	argc--;
8326 	argv++;
8327 
8328 	if (cb.cb_proplist != NULL) {
8329 		fake_name.pl_prop = ZPOOL_PROP_NAME;
8330 		fake_name.pl_width = strlen(gettext("NAME"));
8331 		fake_name.pl_next = cb.cb_proplist;
8332 		cb.cb_proplist = &fake_name;
8333 	}
8334 
8335 	ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist,
8336 	    get_callback, &cb);
8337 
8338 	if (cb.cb_proplist == &fake_name)
8339 		zprop_free_list(fake_name.pl_next);
8340 	else
8341 		zprop_free_list(cb.cb_proplist);
8342 
8343 	return (ret);
8344 }
8345 
8346 typedef struct set_cbdata {
8347 	char *cb_propname;
8348 	char *cb_value;
8349 	boolean_t cb_any_successful;
8350 } set_cbdata_t;
8351 
8352 int
8353 set_callback(zpool_handle_t *zhp, void *data)
8354 {
8355 	int error;
8356 	set_cbdata_t *cb = (set_cbdata_t *)data;
8357 
8358 	error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
8359 
8360 	if (!error)
8361 		cb->cb_any_successful = B_TRUE;
8362 
8363 	return (error);
8364 }
8365 
8366 int
8367 zpool_do_set(int argc, char **argv)
8368 {
8369 	set_cbdata_t cb = { 0 };
8370 	int error;
8371 
8372 	if (argc > 1 && argv[1][0] == '-') {
8373 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8374 		    argv[1][1]);
8375 		usage(B_FALSE);
8376 	}
8377 
8378 	if (argc < 2) {
8379 		(void) fprintf(stderr, gettext("missing property=value "
8380 		    "argument\n"));
8381 		usage(B_FALSE);
8382 	}
8383 
8384 	if (argc < 3) {
8385 		(void) fprintf(stderr, gettext("missing pool name\n"));
8386 		usage(B_FALSE);
8387 	}
8388 
8389 	if (argc > 3) {
8390 		(void) fprintf(stderr, gettext("too many pool names\n"));
8391 		usage(B_FALSE);
8392 	}
8393 
8394 	cb.cb_propname = argv[1];
8395 	cb.cb_value = strchr(cb.cb_propname, '=');
8396 	if (cb.cb_value == NULL) {
8397 		(void) fprintf(stderr, gettext("missing value in "
8398 		    "property=value argument\n"));
8399 		usage(B_FALSE);
8400 	}
8401 
8402 	*(cb.cb_value) = '\0';
8403 	cb.cb_value++;
8404 
8405 	error = for_each_pool(argc - 2, argv + 2, B_TRUE, NULL,
8406 	    set_callback, &cb);
8407 
8408 	return (error);
8409 }
8410 
8411 static int
8412 find_command_idx(char *command, int *idx)
8413 {
8414 	int i;
8415 
8416 	for (i = 0; i < NCOMMAND; i++) {
8417 		if (command_table[i].name == NULL)
8418 			continue;
8419 
8420 		if (strcmp(command, command_table[i].name) == 0) {
8421 			*idx = i;
8422 			return (0);
8423 		}
8424 	}
8425 	return (1);
8426 }
8427 
8428 int
8429 main(int argc, char **argv)
8430 {
8431 	int ret = 0;
8432 	int i;
8433 	char *cmdname;
8434 
8435 	(void) setlocale(LC_ALL, "");
8436 	(void) textdomain(TEXT_DOMAIN);
8437 
8438 	if ((g_zfs = libzfs_init()) == NULL) {
8439 		(void) fprintf(stderr, gettext("internal error: failed to "
8440 		    "initialize ZFS library\n"));
8441 		return (1);
8442 	}
8443 
8444 	libzfs_print_on_error(g_zfs, B_TRUE);
8445 
8446 	opterr = 0;
8447 
8448 	/*
8449 	 * Make sure the user has specified some command.
8450 	 */
8451 	if (argc < 2) {
8452 		(void) fprintf(stderr, gettext("missing command\n"));
8453 		usage(B_FALSE);
8454 	}
8455 
8456 	cmdname = argv[1];
8457 
8458 	/*
8459 	 * Special case '-?'
8460 	 */
8461 	if (strcmp(cmdname, "-?") == 0)
8462 		usage(B_TRUE);
8463 
8464 	zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
8465 
8466 	/*
8467 	 * Run the appropriate command.
8468 	 */
8469 	if (find_command_idx(cmdname, &i) == 0) {
8470 		current_command = &command_table[i];
8471 		ret = command_table[i].func(argc - 1, argv + 1);
8472 	} else if (strchr(cmdname, '=')) {
8473 		verify(find_command_idx("set", &i) == 0);
8474 		current_command = &command_table[i];
8475 		ret = command_table[i].func(argc, argv);
8476 	} else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
8477 		/*
8478 		 * 'freeze' is a vile debugging abomination, so we treat
8479 		 * it as such.
8480 		 */
8481 		char buf[16384];
8482 		int fd = open(ZFS_DEV, O_RDWR);
8483 		(void) strcpy((void *)buf, argv[2]);
8484 		return (!!ioctl(fd, ZFS_IOC_POOL_FREEZE, buf));
8485 	} else {
8486 		(void) fprintf(stderr, gettext("unrecognized "
8487 		    "command '%s'\n"), cmdname);
8488 		usage(B_FALSE);
8489 	}
8490 
8491 	if (ret == 0 && log_history)
8492 		(void) zpool_log_history(g_zfs, history_str);
8493 
8494 	libzfs_fini(g_zfs);
8495 
8496 	/*
8497 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
8498 	 * for the purposes of running ::findleaks.
8499 	 */
8500 	if (getenv("ZFS_ABORT") != NULL) {
8501 		(void) printf("dumping core by request\n");
8502 		abort();
8503 	}
8504 
8505 	return (ret);
8506 }
8507