xref: /freebsd/sys/contrib/openzfs/cmd/zpool/zpool_main.c (revision 9729f076e4d93c5a37e78d427bfe0f1ab99bbcc6)
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 https://opensource.org/licenses/CDDL-1.0.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
25  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
26  * Copyright (c) 2012 by Frederik Wessels. All rights reserved.
27  * Copyright (c) 2012 by Cyril Plisko. All rights reserved.
28  * Copyright (c) 2013 by Prasad Joshi (sTec). All rights reserved.
29  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
30  * Copyright (c) 2017 Datto Inc.
31  * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
32  * Copyright (c) 2017, Intel Corporation.
33  * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>
34  * Copyright (c) 2021, Colm Buckley <colm@tuatha.org>
35  * Copyright (c) 2021, Klara Inc.
36  * Copyright [2021] Hewlett Packard Enterprise Development LP
37  */
38 
39 #include <assert.h>
40 #include <ctype.h>
41 #include <dirent.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <getopt.h>
45 #include <libgen.h>
46 #include <libintl.h>
47 #include <libuutil.h>
48 #include <locale.h>
49 #include <pthread.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <time.h>
54 #include <unistd.h>
55 #include <pwd.h>
56 #include <zone.h>
57 #include <sys/wait.h>
58 #include <zfs_prop.h>
59 #include <sys/fs/zfs.h>
60 #include <sys/stat.h>
61 #include <sys/systeminfo.h>
62 #include <sys/fm/fs/zfs.h>
63 #include <sys/fm/util.h>
64 #include <sys/fm/protocol.h>
65 #include <sys/zfs_ioctl.h>
66 #include <sys/mount.h>
67 #include <sys/sysmacros.h>
68 
69 #include <math.h>
70 
71 #include <libzfs.h>
72 #include <libzutil.h>
73 
74 #include "zpool_util.h"
75 #include "zfs_comutil.h"
76 #include "zfeature_common.h"
77 
78 #include "statcommon.h"
79 
80 libzfs_handle_t *g_zfs;
81 
82 static int zpool_do_create(int, char **);
83 static int zpool_do_destroy(int, char **);
84 
85 static int zpool_do_add(int, char **);
86 static int zpool_do_remove(int, char **);
87 static int zpool_do_labelclear(int, char **);
88 
89 static int zpool_do_checkpoint(int, char **);
90 
91 static int zpool_do_list(int, char **);
92 static int zpool_do_iostat(int, char **);
93 static int zpool_do_status(int, char **);
94 
95 static int zpool_do_online(int, char **);
96 static int zpool_do_offline(int, char **);
97 static int zpool_do_clear(int, char **);
98 static int zpool_do_reopen(int, char **);
99 
100 static int zpool_do_reguid(int, char **);
101 
102 static int zpool_do_attach(int, char **);
103 static int zpool_do_detach(int, char **);
104 static int zpool_do_replace(int, char **);
105 static int zpool_do_split(int, char **);
106 
107 static int zpool_do_initialize(int, char **);
108 static int zpool_do_scrub(int, char **);
109 static int zpool_do_resilver(int, char **);
110 static int zpool_do_trim(int, char **);
111 
112 static int zpool_do_import(int, char **);
113 static int zpool_do_export(int, char **);
114 
115 static int zpool_do_upgrade(int, char **);
116 
117 static int zpool_do_history(int, char **);
118 static int zpool_do_events(int, char **);
119 
120 static int zpool_do_get(int, char **);
121 static int zpool_do_set(int, char **);
122 
123 static int zpool_do_sync(int, char **);
124 
125 static int zpool_do_version(int, char **);
126 
127 static int zpool_do_wait(int, char **);
128 
129 static zpool_compat_status_t zpool_do_load_compat(
130     const char *, boolean_t *);
131 
132 /*
133  * These libumem hooks provide a reasonable set of defaults for the allocator's
134  * debugging facilities.
135  */
136 
137 #ifdef DEBUG
138 const char *
139 _umem_debug_init(void)
140 {
141 	return ("default,verbose"); /* $UMEM_DEBUG setting */
142 }
143 
144 const char *
145 _umem_logging_init(void)
146 {
147 	return ("fail,contents"); /* $UMEM_LOGGING setting */
148 }
149 #endif
150 
151 typedef enum {
152 	HELP_ADD,
153 	HELP_ATTACH,
154 	HELP_CLEAR,
155 	HELP_CREATE,
156 	HELP_CHECKPOINT,
157 	HELP_DESTROY,
158 	HELP_DETACH,
159 	HELP_EXPORT,
160 	HELP_HISTORY,
161 	HELP_IMPORT,
162 	HELP_IOSTAT,
163 	HELP_LABELCLEAR,
164 	HELP_LIST,
165 	HELP_OFFLINE,
166 	HELP_ONLINE,
167 	HELP_REPLACE,
168 	HELP_REMOVE,
169 	HELP_INITIALIZE,
170 	HELP_SCRUB,
171 	HELP_RESILVER,
172 	HELP_TRIM,
173 	HELP_STATUS,
174 	HELP_UPGRADE,
175 	HELP_EVENTS,
176 	HELP_GET,
177 	HELP_SET,
178 	HELP_SPLIT,
179 	HELP_SYNC,
180 	HELP_REGUID,
181 	HELP_REOPEN,
182 	HELP_VERSION,
183 	HELP_WAIT
184 } zpool_help_t;
185 
186 
187 /*
188  * Flags for stats to display with "zpool iostats"
189  */
190 enum iostat_type {
191 	IOS_DEFAULT = 0,
192 	IOS_LATENCY = 1,
193 	IOS_QUEUES = 2,
194 	IOS_L_HISTO = 3,
195 	IOS_RQ_HISTO = 4,
196 	IOS_COUNT,	/* always last element */
197 };
198 
199 /* iostat_type entries as bitmasks */
200 #define	IOS_DEFAULT_M	(1ULL << IOS_DEFAULT)
201 #define	IOS_LATENCY_M	(1ULL << IOS_LATENCY)
202 #define	IOS_QUEUES_M	(1ULL << IOS_QUEUES)
203 #define	IOS_L_HISTO_M	(1ULL << IOS_L_HISTO)
204 #define	IOS_RQ_HISTO_M	(1ULL << IOS_RQ_HISTO)
205 
206 /* Mask of all the histo bits */
207 #define	IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
208 
209 /*
210  * Lookup table for iostat flags to nvlist names.  Basically a list
211  * of all the nvlists a flag requires.  Also specifies the order in
212  * which data gets printed in zpool iostat.
213  */
214 static const char *vsx_type_to_nvlist[IOS_COUNT][15] = {
215 	[IOS_L_HISTO] = {
216 	    ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
217 	    ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
218 	    ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
219 	    ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
220 	    ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
221 	    ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
222 	    ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
223 	    ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
224 	    ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
225 	    ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
226 	    ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
227 	    NULL},
228 	[IOS_LATENCY] = {
229 	    ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
230 	    ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
231 	    ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
232 	    ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
233 	    ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
234 	    ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
235 	    NULL},
236 	[IOS_QUEUES] = {
237 	    ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
238 	    ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
239 	    ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
240 	    ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
241 	    ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
242 	    ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
243 	    ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
244 	    NULL},
245 	[IOS_RQ_HISTO] = {
246 	    ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
247 	    ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
248 	    ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
249 	    ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
250 	    ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
251 	    ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
252 	    ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
253 	    ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
254 	    ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
255 	    ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
256 	    ZPOOL_CONFIG_VDEV_IND_TRIM_HISTO,
257 	    ZPOOL_CONFIG_VDEV_AGG_TRIM_HISTO,
258 	    ZPOOL_CONFIG_VDEV_IND_REBUILD_HISTO,
259 	    ZPOOL_CONFIG_VDEV_AGG_REBUILD_HISTO,
260 	    NULL},
261 };
262 
263 
264 /*
265  * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
266  * Right now, only one histo bit is ever set at one time, so we can
267  * just do a highbit64(a)
268  */
269 #define	IOS_HISTO_IDX(a)	(highbit64(a & IOS_ANYHISTO_M) - 1)
270 
271 typedef struct zpool_command {
272 	const char	*name;
273 	int		(*func)(int, char **);
274 	zpool_help_t	usage;
275 } zpool_command_t;
276 
277 /*
278  * Master command table.  Each ZFS command has a name, associated function, and
279  * usage message.  The usage messages need to be internationalized, so we have
280  * to have a function to return the usage message based on a command index.
281  *
282  * These commands are organized according to how they are displayed in the usage
283  * message.  An empty command (one with a NULL name) indicates an empty line in
284  * the generic usage message.
285  */
286 static zpool_command_t command_table[] = {
287 	{ "version",	zpool_do_version,	HELP_VERSION		},
288 	{ NULL },
289 	{ "create",	zpool_do_create,	HELP_CREATE		},
290 	{ "destroy",	zpool_do_destroy,	HELP_DESTROY		},
291 	{ NULL },
292 	{ "add",	zpool_do_add,		HELP_ADD		},
293 	{ "remove",	zpool_do_remove,	HELP_REMOVE		},
294 	{ NULL },
295 	{ "labelclear",	zpool_do_labelclear,	HELP_LABELCLEAR		},
296 	{ NULL },
297 	{ "checkpoint",	zpool_do_checkpoint,	HELP_CHECKPOINT		},
298 	{ NULL },
299 	{ "list",	zpool_do_list,		HELP_LIST		},
300 	{ "iostat",	zpool_do_iostat,	HELP_IOSTAT		},
301 	{ "status",	zpool_do_status,	HELP_STATUS		},
302 	{ NULL },
303 	{ "online",	zpool_do_online,	HELP_ONLINE		},
304 	{ "offline",	zpool_do_offline,	HELP_OFFLINE		},
305 	{ "clear",	zpool_do_clear,		HELP_CLEAR		},
306 	{ "reopen",	zpool_do_reopen,	HELP_REOPEN		},
307 	{ NULL },
308 	{ "attach",	zpool_do_attach,	HELP_ATTACH		},
309 	{ "detach",	zpool_do_detach,	HELP_DETACH		},
310 	{ "replace",	zpool_do_replace,	HELP_REPLACE		},
311 	{ "split",	zpool_do_split,		HELP_SPLIT		},
312 	{ NULL },
313 	{ "initialize",	zpool_do_initialize,	HELP_INITIALIZE		},
314 	{ "resilver",	zpool_do_resilver,	HELP_RESILVER		},
315 	{ "scrub",	zpool_do_scrub,		HELP_SCRUB		},
316 	{ "trim",	zpool_do_trim,		HELP_TRIM		},
317 	{ NULL },
318 	{ "import",	zpool_do_import,	HELP_IMPORT		},
319 	{ "export",	zpool_do_export,	HELP_EXPORT		},
320 	{ "upgrade",	zpool_do_upgrade,	HELP_UPGRADE		},
321 	{ "reguid",	zpool_do_reguid,	HELP_REGUID		},
322 	{ NULL },
323 	{ "history",	zpool_do_history,	HELP_HISTORY		},
324 	{ "events",	zpool_do_events,	HELP_EVENTS		},
325 	{ NULL },
326 	{ "get",	zpool_do_get,		HELP_GET		},
327 	{ "set",	zpool_do_set,		HELP_SET		},
328 	{ "sync",	zpool_do_sync,		HELP_SYNC		},
329 	{ NULL },
330 	{ "wait",	zpool_do_wait,		HELP_WAIT		},
331 };
332 
333 #define	NCOMMAND	(ARRAY_SIZE(command_table))
334 
335 #define	VDEV_ALLOC_CLASS_LOGS	"logs"
336 
337 static zpool_command_t *current_command;
338 static zfs_type_t current_prop_type = (ZFS_TYPE_POOL | ZFS_TYPE_VDEV);
339 static char history_str[HIS_MAX_RECORD_LEN];
340 static boolean_t log_history = B_TRUE;
341 static uint_t timestamp_fmt = NODATE;
342 
343 static const char *
344 get_usage(zpool_help_t idx)
345 {
346 	switch (idx) {
347 	case HELP_ADD:
348 		return (gettext("\tadd [-fgLnP] [-o property=value] "
349 		    "<pool> <vdev> ...\n"));
350 	case HELP_ATTACH:
351 		return (gettext("\tattach [-fsw] [-o property=value] "
352 		    "<pool> <device> <new-device>\n"));
353 	case HELP_CLEAR:
354 		return (gettext("\tclear [-nF] <pool> [device]\n"));
355 	case HELP_CREATE:
356 		return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
357 		    "\t    [-O file-system-property=value] ... \n"
358 		    "\t    [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
359 	case HELP_CHECKPOINT:
360 		return (gettext("\tcheckpoint [-d [-w]] <pool> ...\n"));
361 	case HELP_DESTROY:
362 		return (gettext("\tdestroy [-f] <pool>\n"));
363 	case HELP_DETACH:
364 		return (gettext("\tdetach <pool> <device>\n"));
365 	case HELP_EXPORT:
366 		return (gettext("\texport [-af] <pool> ...\n"));
367 	case HELP_HISTORY:
368 		return (gettext("\thistory [-il] [<pool>] ...\n"));
369 	case HELP_IMPORT:
370 		return (gettext("\timport [-d dir] [-D]\n"
371 		    "\timport [-o mntopts] [-o property=value] ... \n"
372 		    "\t    [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
373 		    "[-R root] [-F [-n]] -a\n"
374 		    "\timport [-o mntopts] [-o property=value] ... \n"
375 		    "\t    [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
376 		    "[-R root] [-F [-n]]\n"
377 		    "\t    [--rewind-to-checkpoint] <pool | id> [newpool]\n"));
378 	case HELP_IOSTAT:
379 		return (gettext("\tiostat [[[-c [script1,script2,...]"
380 		    "[-lq]]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
381 		    "\t    [[pool ...]|[pool vdev ...]|[vdev ...]]"
382 		    " [[-n] interval [count]]\n"));
383 	case HELP_LABELCLEAR:
384 		return (gettext("\tlabelclear [-f] <vdev>\n"));
385 	case HELP_LIST:
386 		return (gettext("\tlist [-gHLpPv] [-o property[,...]] "
387 		    "[-T d|u] [pool] ... \n"
388 		    "\t    [interval [count]]\n"));
389 	case HELP_OFFLINE:
390 		return (gettext("\toffline [-f] [-t] <pool> <device> ...\n"));
391 	case HELP_ONLINE:
392 		return (gettext("\tonline [-e] <pool> <device> ...\n"));
393 	case HELP_REPLACE:
394 		return (gettext("\treplace [-fsw] [-o property=value] "
395 		    "<pool> <device> [new-device]\n"));
396 	case HELP_REMOVE:
397 		return (gettext("\tremove [-npsw] <pool> <device> ...\n"));
398 	case HELP_REOPEN:
399 		return (gettext("\treopen [-n] <pool>\n"));
400 	case HELP_INITIALIZE:
401 		return (gettext("\tinitialize [-c | -s] [-w] <pool> "
402 		    "[<device> ...]\n"));
403 	case HELP_SCRUB:
404 		return (gettext("\tscrub [-s | -p] [-w] <pool> ...\n"));
405 	case HELP_RESILVER:
406 		return (gettext("\tresilver <pool> ...\n"));
407 	case HELP_TRIM:
408 		return (gettext("\ttrim [-dw] [-r <rate>] [-c | -s] <pool> "
409 		    "[<device> ...]\n"));
410 	case HELP_STATUS:
411 		return (gettext("\tstatus [-c [script1,script2,...]] "
412 		    "[-igLpPstvxD]  [-T d|u] [pool] ... \n"
413 		    "\t    [interval [count]]\n"));
414 	case HELP_UPGRADE:
415 		return (gettext("\tupgrade\n"
416 		    "\tupgrade -v\n"
417 		    "\tupgrade [-V version] <-a | pool ...>\n"));
418 	case HELP_EVENTS:
419 		return (gettext("\tevents [-vHf [pool] | -c]\n"));
420 	case HELP_GET:
421 		return (gettext("\tget [-Hp] [-o \"all\" | field[,...]] "
422 		    "<\"all\" | property[,...]> <pool> ...\n"));
423 	case HELP_SET:
424 		return (gettext("\tset <property=value> <pool> \n"));
425 	case HELP_SPLIT:
426 		return (gettext("\tsplit [-gLnPl] [-R altroot] [-o mntopts]\n"
427 		    "\t    [-o property=value] <pool> <newpool> "
428 		    "[<device> ...]\n"));
429 	case HELP_REGUID:
430 		return (gettext("\treguid <pool>\n"));
431 	case HELP_SYNC:
432 		return (gettext("\tsync [pool] ...\n"));
433 	case HELP_VERSION:
434 		return (gettext("\tversion\n"));
435 	case HELP_WAIT:
436 		return (gettext("\twait [-Hp] [-T d|u] [-t <activity>[,...]] "
437 		    "<pool> [interval]\n"));
438 	default:
439 		__builtin_unreachable();
440 	}
441 }
442 
443 static void
444 zpool_collect_leaves(zpool_handle_t *zhp, nvlist_t *nvroot, nvlist_t *res)
445 {
446 	uint_t children = 0;
447 	nvlist_t **child;
448 	uint_t i;
449 
450 	(void) nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
451 	    &child, &children);
452 
453 	if (children == 0) {
454 		char *path = zpool_vdev_name(g_zfs, zhp, nvroot,
455 		    VDEV_NAME_PATH);
456 
457 		if (strcmp(path, VDEV_TYPE_INDIRECT) != 0 &&
458 		    strcmp(path, VDEV_TYPE_HOLE) != 0)
459 			fnvlist_add_boolean(res, path);
460 
461 		free(path);
462 		return;
463 	}
464 
465 	for (i = 0; i < children; i++) {
466 		zpool_collect_leaves(zhp, child[i], res);
467 	}
468 }
469 
470 /*
471  * Callback routine that will print out a pool property value.
472  */
473 static int
474 print_pool_prop_cb(int prop, void *cb)
475 {
476 	FILE *fp = cb;
477 
478 	(void) fprintf(fp, "\t%-19s  ", zpool_prop_to_name(prop));
479 
480 	if (zpool_prop_readonly(prop))
481 		(void) fprintf(fp, "  NO   ");
482 	else
483 		(void) fprintf(fp, " YES   ");
484 
485 	if (zpool_prop_values(prop) == NULL)
486 		(void) fprintf(fp, "-\n");
487 	else
488 		(void) fprintf(fp, "%s\n", zpool_prop_values(prop));
489 
490 	return (ZPROP_CONT);
491 }
492 
493 /*
494  * Callback routine that will print out a vdev property value.
495  */
496 static int
497 print_vdev_prop_cb(int prop, void *cb)
498 {
499 	FILE *fp = cb;
500 
501 	(void) fprintf(fp, "\t%-19s  ", vdev_prop_to_name(prop));
502 
503 	if (vdev_prop_readonly(prop))
504 		(void) fprintf(fp, "  NO   ");
505 	else
506 		(void) fprintf(fp, " YES   ");
507 
508 	if (vdev_prop_values(prop) == NULL)
509 		(void) fprintf(fp, "-\n");
510 	else
511 		(void) fprintf(fp, "%s\n", vdev_prop_values(prop));
512 
513 	return (ZPROP_CONT);
514 }
515 
516 /*
517  * Display usage message.  If we're inside a command, display only the usage for
518  * that command.  Otherwise, iterate over the entire command table and display
519  * a complete usage message.
520  */
521 static __attribute__((noreturn)) void
522 usage(boolean_t requested)
523 {
524 	FILE *fp = requested ? stdout : stderr;
525 
526 	if (current_command == NULL) {
527 		int i;
528 
529 		(void) fprintf(fp, gettext("usage: zpool command args ...\n"));
530 		(void) fprintf(fp,
531 		    gettext("where 'command' is one of the following:\n\n"));
532 
533 		for (i = 0; i < NCOMMAND; i++) {
534 			if (command_table[i].name == NULL)
535 				(void) fprintf(fp, "\n");
536 			else
537 				(void) fprintf(fp, "%s",
538 				    get_usage(command_table[i].usage));
539 		}
540 	} else {
541 		(void) fprintf(fp, gettext("usage:\n"));
542 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
543 	}
544 
545 	if (current_command != NULL &&
546 	    current_prop_type != (ZFS_TYPE_POOL | ZFS_TYPE_VDEV) &&
547 	    ((strcmp(current_command->name, "set") == 0) ||
548 	    (strcmp(current_command->name, "get") == 0) ||
549 	    (strcmp(current_command->name, "list") == 0))) {
550 
551 		(void) fprintf(fp,
552 		    gettext("\nthe following properties are supported:\n"));
553 
554 		(void) fprintf(fp, "\n\t%-19s  %s   %s\n\n",
555 		    "PROPERTY", "EDIT", "VALUES");
556 
557 		/* Iterate over all properties */
558 		if (current_prop_type == ZFS_TYPE_POOL) {
559 			(void) zprop_iter(print_pool_prop_cb, fp, B_FALSE,
560 			    B_TRUE, current_prop_type);
561 
562 			(void) fprintf(fp, "\t%-19s   ", "feature@...");
563 			(void) fprintf(fp, "YES   "
564 			    "disabled | enabled | active\n");
565 
566 			(void) fprintf(fp, gettext("\nThe feature@ properties "
567 			    "must be appended with a feature name.\n"
568 			    "See zpool-features(7).\n"));
569 		} else if (current_prop_type == ZFS_TYPE_VDEV) {
570 			(void) zprop_iter(print_vdev_prop_cb, fp, B_FALSE,
571 			    B_TRUE, current_prop_type);
572 		}
573 	}
574 
575 	/*
576 	 * See comments at end of main().
577 	 */
578 	if (getenv("ZFS_ABORT") != NULL) {
579 		(void) printf("dumping core by request\n");
580 		abort();
581 	}
582 
583 	exit(requested ? 0 : 2);
584 }
585 
586 /*
587  * zpool initialize [-c | -s] [-w] <pool> [<vdev> ...]
588  * Initialize all unused blocks in the specified vdevs, or all vdevs in the pool
589  * if none specified.
590  *
591  *	-c	Cancel. Ends active initializing.
592  *	-s	Suspend. Initializing can then be restarted with no flags.
593  *	-w	Wait. Blocks until initializing has completed.
594  */
595 int
596 zpool_do_initialize(int argc, char **argv)
597 {
598 	int c;
599 	char *poolname;
600 	zpool_handle_t *zhp;
601 	nvlist_t *vdevs;
602 	int err = 0;
603 	boolean_t wait = B_FALSE;
604 
605 	struct option long_options[] = {
606 		{"cancel",	no_argument,		NULL, 'c'},
607 		{"suspend",	no_argument,		NULL, 's'},
608 		{"wait",	no_argument,		NULL, 'w'},
609 		{0, 0, 0, 0}
610 	};
611 
612 	pool_initialize_func_t cmd_type = POOL_INITIALIZE_START;
613 	while ((c = getopt_long(argc, argv, "csw", long_options, NULL)) != -1) {
614 		switch (c) {
615 		case 'c':
616 			if (cmd_type != POOL_INITIALIZE_START &&
617 			    cmd_type != POOL_INITIALIZE_CANCEL) {
618 				(void) fprintf(stderr, gettext("-c cannot be "
619 				    "combined with other options\n"));
620 				usage(B_FALSE);
621 			}
622 			cmd_type = POOL_INITIALIZE_CANCEL;
623 			break;
624 		case 's':
625 			if (cmd_type != POOL_INITIALIZE_START &&
626 			    cmd_type != POOL_INITIALIZE_SUSPEND) {
627 				(void) fprintf(stderr, gettext("-s cannot be "
628 				    "combined with other options\n"));
629 				usage(B_FALSE);
630 			}
631 			cmd_type = POOL_INITIALIZE_SUSPEND;
632 			break;
633 		case 'w':
634 			wait = B_TRUE;
635 			break;
636 		case '?':
637 			if (optopt != 0) {
638 				(void) fprintf(stderr,
639 				    gettext("invalid option '%c'\n"), optopt);
640 			} else {
641 				(void) fprintf(stderr,
642 				    gettext("invalid option '%s'\n"),
643 				    argv[optind - 1]);
644 			}
645 			usage(B_FALSE);
646 		}
647 	}
648 
649 	argc -= optind;
650 	argv += optind;
651 
652 	if (argc < 1) {
653 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
654 		usage(B_FALSE);
655 		return (-1);
656 	}
657 
658 	if (wait && (cmd_type != POOL_INITIALIZE_START)) {
659 		(void) fprintf(stderr, gettext("-w cannot be used with -c or "
660 		    "-s\n"));
661 		usage(B_FALSE);
662 	}
663 
664 	poolname = argv[0];
665 	zhp = zpool_open(g_zfs, poolname);
666 	if (zhp == NULL)
667 		return (-1);
668 
669 	vdevs = fnvlist_alloc();
670 	if (argc == 1) {
671 		/* no individual leaf vdevs specified, so add them all */
672 		nvlist_t *config = zpool_get_config(zhp, NULL);
673 		nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
674 		    ZPOOL_CONFIG_VDEV_TREE);
675 		zpool_collect_leaves(zhp, nvroot, vdevs);
676 	} else {
677 		for (int i = 1; i < argc; i++) {
678 			fnvlist_add_boolean(vdevs, argv[i]);
679 		}
680 	}
681 
682 	if (wait)
683 		err = zpool_initialize_wait(zhp, cmd_type, vdevs);
684 	else
685 		err = zpool_initialize(zhp, cmd_type, vdevs);
686 
687 	fnvlist_free(vdevs);
688 	zpool_close(zhp);
689 
690 	return (err);
691 }
692 
693 /*
694  * print a pool vdev config for dry runs
695  */
696 static void
697 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
698     const char *match, int name_flags)
699 {
700 	nvlist_t **child;
701 	uint_t c, children;
702 	char *vname;
703 	boolean_t printed = B_FALSE;
704 
705 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
706 	    &child, &children) != 0) {
707 		if (name != NULL)
708 			(void) printf("\t%*s%s\n", indent, "", name);
709 		return;
710 	}
711 
712 	for (c = 0; c < children; c++) {
713 		uint64_t is_log = B_FALSE, is_hole = B_FALSE;
714 		char *class = (char *)"";
715 
716 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
717 		    &is_hole);
718 
719 		if (is_hole == B_TRUE) {
720 			continue;
721 		}
722 
723 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
724 		    &is_log);
725 		if (is_log)
726 			class = (char *)VDEV_ALLOC_BIAS_LOG;
727 		(void) nvlist_lookup_string(child[c],
728 		    ZPOOL_CONFIG_ALLOCATION_BIAS, &class);
729 		if (strcmp(match, class) != 0)
730 			continue;
731 
732 		if (!printed && name != NULL) {
733 			(void) printf("\t%*s%s\n", indent, "", name);
734 			printed = B_TRUE;
735 		}
736 		vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
737 		print_vdev_tree(zhp, vname, child[c], indent + 2, "",
738 		    name_flags);
739 		free(vname);
740 	}
741 }
742 
743 /*
744  * Print the list of l2cache devices for dry runs.
745  */
746 static void
747 print_cache_list(nvlist_t *nv, int indent)
748 {
749 	nvlist_t **child;
750 	uint_t c, children;
751 
752 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
753 	    &child, &children) == 0 && children > 0) {
754 		(void) printf("\t%*s%s\n", indent, "", "cache");
755 	} else {
756 		return;
757 	}
758 	for (c = 0; c < children; c++) {
759 		char *vname;
760 
761 		vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
762 		(void) printf("\t%*s%s\n", indent + 2, "", vname);
763 		free(vname);
764 	}
765 }
766 
767 /*
768  * Print the list of spares for dry runs.
769  */
770 static void
771 print_spare_list(nvlist_t *nv, int indent)
772 {
773 	nvlist_t **child;
774 	uint_t c, children;
775 
776 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
777 	    &child, &children) == 0 && children > 0) {
778 		(void) printf("\t%*s%s\n", indent, "", "spares");
779 	} else {
780 		return;
781 	}
782 	for (c = 0; c < children; c++) {
783 		char *vname;
784 
785 		vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
786 		(void) printf("\t%*s%s\n", indent + 2, "", vname);
787 		free(vname);
788 	}
789 }
790 
791 static boolean_t
792 prop_list_contains_feature(nvlist_t *proplist)
793 {
794 	nvpair_t *nvp;
795 	for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
796 	    nvp = nvlist_next_nvpair(proplist, nvp)) {
797 		if (zpool_prop_feature(nvpair_name(nvp)))
798 			return (B_TRUE);
799 	}
800 	return (B_FALSE);
801 }
802 
803 /*
804  * Add a property pair (name, string-value) into a property nvlist.
805  */
806 static int
807 add_prop_list(const char *propname, const char *propval, nvlist_t **props,
808     boolean_t poolprop)
809 {
810 	zpool_prop_t prop = ZPOOL_PROP_INVAL;
811 	nvlist_t *proplist;
812 	const char *normnm;
813 	char *strval;
814 
815 	if (*props == NULL &&
816 	    nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
817 		(void) fprintf(stderr,
818 		    gettext("internal error: out of memory\n"));
819 		return (1);
820 	}
821 
822 	proplist = *props;
823 
824 	if (poolprop) {
825 		const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
826 		const char *cname =
827 		    zpool_prop_to_name(ZPOOL_PROP_COMPATIBILITY);
828 
829 		if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
830 		    (!zpool_prop_feature(propname) &&
831 		    !zpool_prop_vdev(propname))) {
832 			(void) fprintf(stderr, gettext("property '%s' is "
833 			    "not a valid pool or vdev property\n"), propname);
834 			return (2);
835 		}
836 
837 		/*
838 		 * feature@ properties and version should not be specified
839 		 * at the same time.
840 		 */
841 		if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
842 		    nvlist_exists(proplist, vname)) ||
843 		    (prop == ZPOOL_PROP_VERSION &&
844 		    prop_list_contains_feature(proplist))) {
845 			(void) fprintf(stderr, gettext("'feature@' and "
846 			    "'version' properties cannot be specified "
847 			    "together\n"));
848 			return (2);
849 		}
850 
851 		/*
852 		 * if version is specified, only "legacy" compatibility
853 		 * may be requested
854 		 */
855 		if ((prop == ZPOOL_PROP_COMPATIBILITY &&
856 		    strcmp(propval, ZPOOL_COMPAT_LEGACY) != 0 &&
857 		    nvlist_exists(proplist, vname)) ||
858 		    (prop == ZPOOL_PROP_VERSION &&
859 		    nvlist_exists(proplist, cname) &&
860 		    strcmp(fnvlist_lookup_string(proplist, cname),
861 		    ZPOOL_COMPAT_LEGACY) != 0)) {
862 			(void) fprintf(stderr, gettext("when 'version' is "
863 			    "specified, the 'compatibility' feature may only "
864 			    "be set to '" ZPOOL_COMPAT_LEGACY "'\n"));
865 			return (2);
866 		}
867 
868 		if (zpool_prop_feature(propname) || zpool_prop_vdev(propname))
869 			normnm = propname;
870 		else
871 			normnm = zpool_prop_to_name(prop);
872 	} else {
873 		zfs_prop_t fsprop = zfs_name_to_prop(propname);
874 
875 		if (zfs_prop_valid_for_type(fsprop, ZFS_TYPE_FILESYSTEM,
876 		    B_FALSE)) {
877 			normnm = zfs_prop_to_name(fsprop);
878 		} else if (zfs_prop_user(propname) ||
879 		    zfs_prop_userquota(propname)) {
880 			normnm = propname;
881 		} else {
882 			(void) fprintf(stderr, gettext("property '%s' is "
883 			    "not a valid filesystem property\n"), propname);
884 			return (2);
885 		}
886 	}
887 
888 	if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
889 	    prop != ZPOOL_PROP_CACHEFILE) {
890 		(void) fprintf(stderr, gettext("property '%s' "
891 		    "specified multiple times\n"), propname);
892 		return (2);
893 	}
894 
895 	if (nvlist_add_string(proplist, normnm, propval) != 0) {
896 		(void) fprintf(stderr, gettext("internal "
897 		    "error: out of memory\n"));
898 		return (1);
899 	}
900 
901 	return (0);
902 }
903 
904 /*
905  * Set a default property pair (name, string-value) in a property nvlist
906  */
907 static int
908 add_prop_list_default(const char *propname, const char *propval,
909     nvlist_t **props)
910 {
911 	char *pval;
912 
913 	if (nvlist_lookup_string(*props, propname, &pval) == 0)
914 		return (0);
915 
916 	return (add_prop_list(propname, propval, props, B_TRUE));
917 }
918 
919 /*
920  * zpool add [-fgLnP] [-o property=value] <pool> <vdev> ...
921  *
922  *	-f	Force addition of devices, even if they appear in use
923  *	-g	Display guid for individual vdev name.
924  *	-L	Follow links when resolving vdev path name.
925  *	-n	Do not add the devices, but display the resulting layout if
926  *		they were to be added.
927  *	-o	Set property=value.
928  *	-P	Display full path for vdev name.
929  *
930  * Adds the given vdevs to 'pool'.  As with create, the bulk of this work is
931  * handled by make_root_vdev(), which constructs the nvlist needed to pass to
932  * libzfs.
933  */
934 int
935 zpool_do_add(int argc, char **argv)
936 {
937 	boolean_t force = B_FALSE;
938 	boolean_t dryrun = B_FALSE;
939 	int name_flags = 0;
940 	int c;
941 	nvlist_t *nvroot;
942 	char *poolname;
943 	int ret;
944 	zpool_handle_t *zhp;
945 	nvlist_t *config;
946 	nvlist_t *props = NULL;
947 	char *propval;
948 
949 	/* check options */
950 	while ((c = getopt(argc, argv, "fgLno:P")) != -1) {
951 		switch (c) {
952 		case 'f':
953 			force = B_TRUE;
954 			break;
955 		case 'g':
956 			name_flags |= VDEV_NAME_GUID;
957 			break;
958 		case 'L':
959 			name_flags |= VDEV_NAME_FOLLOW_LINKS;
960 			break;
961 		case 'n':
962 			dryrun = B_TRUE;
963 			break;
964 		case 'o':
965 			if ((propval = strchr(optarg, '=')) == NULL) {
966 				(void) fprintf(stderr, gettext("missing "
967 				    "'=' for -o option\n"));
968 				usage(B_FALSE);
969 			}
970 			*propval = '\0';
971 			propval++;
972 
973 			if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
974 			    (add_prop_list(optarg, propval, &props, B_TRUE)))
975 				usage(B_FALSE);
976 			break;
977 		case 'P':
978 			name_flags |= VDEV_NAME_PATH;
979 			break;
980 		case '?':
981 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
982 			    optopt);
983 			usage(B_FALSE);
984 		}
985 	}
986 
987 	argc -= optind;
988 	argv += optind;
989 
990 	/* get pool name and check number of arguments */
991 	if (argc < 1) {
992 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
993 		usage(B_FALSE);
994 	}
995 	if (argc < 2) {
996 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
997 		usage(B_FALSE);
998 	}
999 
1000 	poolname = argv[0];
1001 
1002 	argc--;
1003 	argv++;
1004 
1005 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1006 		return (1);
1007 
1008 	if ((config = zpool_get_config(zhp, NULL)) == NULL) {
1009 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
1010 		    poolname);
1011 		zpool_close(zhp);
1012 		return (1);
1013 	}
1014 
1015 	/* unless manually specified use "ashift" pool property (if set) */
1016 	if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
1017 		int intval;
1018 		zprop_source_t src;
1019 		char strval[ZPOOL_MAXPROPLEN];
1020 
1021 		intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
1022 		if (src != ZPROP_SRC_DEFAULT) {
1023 			(void) sprintf(strval, "%" PRId32, intval);
1024 			verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
1025 			    &props, B_TRUE) == 0);
1026 		}
1027 	}
1028 
1029 	/* pass off to make_root_vdev for processing */
1030 	nvroot = make_root_vdev(zhp, props, force, !force, B_FALSE, dryrun,
1031 	    argc, argv);
1032 	if (nvroot == NULL) {
1033 		zpool_close(zhp);
1034 		return (1);
1035 	}
1036 
1037 	if (dryrun) {
1038 		nvlist_t *poolnvroot;
1039 		nvlist_t **l2child, **sparechild;
1040 		uint_t l2children, sparechildren, c;
1041 		char *vname;
1042 		boolean_t hadcache = B_FALSE, hadspare = B_FALSE;
1043 
1044 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1045 		    &poolnvroot) == 0);
1046 
1047 		(void) printf(gettext("would update '%s' to the following "
1048 		    "configuration:\n\n"), zpool_get_name(zhp));
1049 
1050 		/* print original main pool and new tree */
1051 		print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
1052 		    name_flags | VDEV_NAME_TYPE_ID);
1053 		print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
1054 
1055 		/* print other classes: 'dedup', 'special', and 'log' */
1056 		if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1057 			print_vdev_tree(zhp, "dedup", poolnvroot, 0,
1058 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1059 			print_vdev_tree(zhp, NULL, nvroot, 0,
1060 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1061 		} else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1062 			print_vdev_tree(zhp, "dedup", nvroot, 0,
1063 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1064 		}
1065 
1066 		if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1067 			print_vdev_tree(zhp, "special", poolnvroot, 0,
1068 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1069 			print_vdev_tree(zhp, NULL, nvroot, 0,
1070 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1071 		} else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1072 			print_vdev_tree(zhp, "special", nvroot, 0,
1073 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1074 		}
1075 
1076 		if (num_logs(poolnvroot) > 0) {
1077 			print_vdev_tree(zhp, "logs", poolnvroot, 0,
1078 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1079 			print_vdev_tree(zhp, NULL, nvroot, 0,
1080 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1081 		} else if (num_logs(nvroot) > 0) {
1082 			print_vdev_tree(zhp, "logs", nvroot, 0,
1083 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1084 		}
1085 
1086 		/* Do the same for the caches */
1087 		if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
1088 		    &l2child, &l2children) == 0 && l2children) {
1089 			hadcache = B_TRUE;
1090 			(void) printf(gettext("\tcache\n"));
1091 			for (c = 0; c < l2children; c++) {
1092 				vname = zpool_vdev_name(g_zfs, NULL,
1093 				    l2child[c], name_flags);
1094 				(void) printf("\t  %s\n", vname);
1095 				free(vname);
1096 			}
1097 		}
1098 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1099 		    &l2child, &l2children) == 0 && l2children) {
1100 			if (!hadcache)
1101 				(void) printf(gettext("\tcache\n"));
1102 			for (c = 0; c < l2children; c++) {
1103 				vname = zpool_vdev_name(g_zfs, NULL,
1104 				    l2child[c], name_flags);
1105 				(void) printf("\t  %s\n", vname);
1106 				free(vname);
1107 			}
1108 		}
1109 		/* And finally the spares */
1110 		if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_SPARES,
1111 		    &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1112 			hadspare = B_TRUE;
1113 			(void) printf(gettext("\tspares\n"));
1114 			for (c = 0; c < sparechildren; c++) {
1115 				vname = zpool_vdev_name(g_zfs, NULL,
1116 				    sparechild[c], name_flags);
1117 				(void) printf("\t  %s\n", vname);
1118 				free(vname);
1119 			}
1120 		}
1121 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1122 		    &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1123 			if (!hadspare)
1124 				(void) printf(gettext("\tspares\n"));
1125 			for (c = 0; c < sparechildren; c++) {
1126 				vname = zpool_vdev_name(g_zfs, NULL,
1127 				    sparechild[c], name_flags);
1128 				(void) printf("\t  %s\n", vname);
1129 				free(vname);
1130 			}
1131 		}
1132 
1133 		ret = 0;
1134 	} else {
1135 		ret = (zpool_add(zhp, nvroot) != 0);
1136 	}
1137 
1138 	nvlist_free(props);
1139 	nvlist_free(nvroot);
1140 	zpool_close(zhp);
1141 
1142 	return (ret);
1143 }
1144 
1145 /*
1146  * zpool remove [-npsw] <pool> <vdev> ...
1147  *
1148  * Removes the given vdev from the pool.
1149  */
1150 int
1151 zpool_do_remove(int argc, char **argv)
1152 {
1153 	char *poolname;
1154 	int i, ret = 0;
1155 	zpool_handle_t *zhp = NULL;
1156 	boolean_t stop = B_FALSE;
1157 	int c;
1158 	boolean_t noop = B_FALSE;
1159 	boolean_t parsable = B_FALSE;
1160 	boolean_t wait = B_FALSE;
1161 
1162 	/* check options */
1163 	while ((c = getopt(argc, argv, "npsw")) != -1) {
1164 		switch (c) {
1165 		case 'n':
1166 			noop = B_TRUE;
1167 			break;
1168 		case 'p':
1169 			parsable = B_TRUE;
1170 			break;
1171 		case 's':
1172 			stop = B_TRUE;
1173 			break;
1174 		case 'w':
1175 			wait = B_TRUE;
1176 			break;
1177 		case '?':
1178 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1179 			    optopt);
1180 			usage(B_FALSE);
1181 		}
1182 	}
1183 
1184 	argc -= optind;
1185 	argv += optind;
1186 
1187 	/* get pool name and check number of arguments */
1188 	if (argc < 1) {
1189 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
1190 		usage(B_FALSE);
1191 	}
1192 
1193 	poolname = argv[0];
1194 
1195 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1196 		return (1);
1197 
1198 	if (stop && noop) {
1199 		zpool_close(zhp);
1200 		(void) fprintf(stderr, gettext("stop request ignored\n"));
1201 		return (0);
1202 	}
1203 
1204 	if (stop) {
1205 		if (argc > 1) {
1206 			(void) fprintf(stderr, gettext("too many arguments\n"));
1207 			usage(B_FALSE);
1208 		}
1209 		if (zpool_vdev_remove_cancel(zhp) != 0)
1210 			ret = 1;
1211 		if (wait) {
1212 			(void) fprintf(stderr, gettext("invalid option "
1213 			    "combination: -w cannot be used with -s\n"));
1214 			usage(B_FALSE);
1215 		}
1216 	} else {
1217 		if (argc < 2) {
1218 			(void) fprintf(stderr, gettext("missing device\n"));
1219 			usage(B_FALSE);
1220 		}
1221 
1222 		for (i = 1; i < argc; i++) {
1223 			if (noop) {
1224 				uint64_t size;
1225 
1226 				if (zpool_vdev_indirect_size(zhp, argv[i],
1227 				    &size) != 0) {
1228 					ret = 1;
1229 					break;
1230 				}
1231 				if (parsable) {
1232 					(void) printf("%s %llu\n",
1233 					    argv[i], (unsigned long long)size);
1234 				} else {
1235 					char valstr[32];
1236 					zfs_nicenum(size, valstr,
1237 					    sizeof (valstr));
1238 					(void) printf("Memory that will be "
1239 					    "used after removing %s: %s\n",
1240 					    argv[i], valstr);
1241 				}
1242 			} else {
1243 				if (zpool_vdev_remove(zhp, argv[i]) != 0)
1244 					ret = 1;
1245 			}
1246 		}
1247 
1248 		if (ret == 0 && wait)
1249 			ret = zpool_wait(zhp, ZPOOL_WAIT_REMOVE);
1250 	}
1251 	zpool_close(zhp);
1252 
1253 	return (ret);
1254 }
1255 
1256 /*
1257  * Return 1 if a vdev is active (being used in a pool)
1258  * Return 0 if a vdev is inactive (offlined or faulted, or not in active pool)
1259  *
1260  * This is useful for checking if a disk in an active pool is offlined or
1261  * faulted.
1262  */
1263 static int
1264 vdev_is_active(char *vdev_path)
1265 {
1266 	int fd;
1267 	fd = open(vdev_path, O_EXCL);
1268 	if (fd < 0) {
1269 		return (1);   /* cant open O_EXCL - disk is active */
1270 	}
1271 
1272 	close(fd);
1273 	return (0);   /* disk is inactive in the pool */
1274 }
1275 
1276 /*
1277  * zpool labelclear [-f] <vdev>
1278  *
1279  *	-f	Force clearing the label for the vdevs which are members of
1280  *		the exported or foreign pools.
1281  *
1282  * Verifies that the vdev is not active and zeros out the label information
1283  * on the device.
1284  */
1285 int
1286 zpool_do_labelclear(int argc, char **argv)
1287 {
1288 	char vdev[MAXPATHLEN];
1289 	char *name = NULL;
1290 	struct stat st;
1291 	int c, fd = -1, ret = 0;
1292 	nvlist_t *config;
1293 	pool_state_t state;
1294 	boolean_t inuse = B_FALSE;
1295 	boolean_t force = B_FALSE;
1296 
1297 	/* check options */
1298 	while ((c = getopt(argc, argv, "f")) != -1) {
1299 		switch (c) {
1300 		case 'f':
1301 			force = B_TRUE;
1302 			break;
1303 		default:
1304 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1305 			    optopt);
1306 			usage(B_FALSE);
1307 		}
1308 	}
1309 
1310 	argc -= optind;
1311 	argv += optind;
1312 
1313 	/* get vdev name */
1314 	if (argc < 1) {
1315 		(void) fprintf(stderr, gettext("missing vdev name\n"));
1316 		usage(B_FALSE);
1317 	}
1318 	if (argc > 1) {
1319 		(void) fprintf(stderr, gettext("too many arguments\n"));
1320 		usage(B_FALSE);
1321 	}
1322 
1323 	/*
1324 	 * Check if we were given absolute path and use it as is.
1325 	 * Otherwise if the provided vdev name doesn't point to a file,
1326 	 * try prepending expected disk paths and partition numbers.
1327 	 */
1328 	(void) strlcpy(vdev, argv[0], sizeof (vdev));
1329 	if (vdev[0] != '/' && stat(vdev, &st) != 0) {
1330 		int error;
1331 
1332 		error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
1333 		if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
1334 			if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
1335 				error = ENOENT;
1336 		}
1337 
1338 		if (error || (stat(vdev, &st) != 0)) {
1339 			(void) fprintf(stderr, gettext(
1340 			    "failed to find device %s, try specifying absolute "
1341 			    "path instead\n"), argv[0]);
1342 			return (1);
1343 		}
1344 	}
1345 
1346 	if ((fd = open(vdev, O_RDWR)) < 0) {
1347 		(void) fprintf(stderr, gettext("failed to open %s: %s\n"),
1348 		    vdev, strerror(errno));
1349 		return (1);
1350 	}
1351 
1352 	/*
1353 	 * Flush all dirty pages for the block device.  This should not be
1354 	 * fatal when the device does not support BLKFLSBUF as would be the
1355 	 * case for a file vdev.
1356 	 */
1357 	if ((zfs_dev_flush(fd) != 0) && (errno != ENOTTY))
1358 		(void) fprintf(stderr, gettext("failed to invalidate "
1359 		    "cache for %s: %s\n"), vdev, strerror(errno));
1360 
1361 	if (zpool_read_label(fd, &config, NULL) != 0) {
1362 		(void) fprintf(stderr,
1363 		    gettext("failed to read label from %s\n"), vdev);
1364 		ret = 1;
1365 		goto errout;
1366 	}
1367 	nvlist_free(config);
1368 
1369 	ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1370 	if (ret != 0) {
1371 		(void) fprintf(stderr,
1372 		    gettext("failed to check state for %s\n"), vdev);
1373 		ret = 1;
1374 		goto errout;
1375 	}
1376 
1377 	if (!inuse)
1378 		goto wipe_label;
1379 
1380 	switch (state) {
1381 	default:
1382 	case POOL_STATE_ACTIVE:
1383 	case POOL_STATE_SPARE:
1384 	case POOL_STATE_L2CACHE:
1385 		/*
1386 		 * We allow the user to call 'zpool offline -f'
1387 		 * on an offlined disk in an active pool. We can check if
1388 		 * the disk is online by calling vdev_is_active().
1389 		 */
1390 		if (force && !vdev_is_active(vdev))
1391 			break;
1392 
1393 		(void) fprintf(stderr, gettext(
1394 		    "%s is a member (%s) of pool \"%s\""),
1395 		    vdev, zpool_pool_state_to_name(state), name);
1396 
1397 		if (force) {
1398 			(void) fprintf(stderr, gettext(
1399 			    ". Offline the disk first to clear its label."));
1400 		}
1401 		printf("\n");
1402 		ret = 1;
1403 		goto errout;
1404 
1405 	case POOL_STATE_EXPORTED:
1406 		if (force)
1407 			break;
1408 		(void) fprintf(stderr, gettext(
1409 		    "use '-f' to override the following error:\n"
1410 		    "%s is a member of exported pool \"%s\"\n"),
1411 		    vdev, name);
1412 		ret = 1;
1413 		goto errout;
1414 
1415 	case POOL_STATE_POTENTIALLY_ACTIVE:
1416 		if (force)
1417 			break;
1418 		(void) fprintf(stderr, gettext(
1419 		    "use '-f' to override the following error:\n"
1420 		    "%s is a member of potentially active pool \"%s\"\n"),
1421 		    vdev, name);
1422 		ret = 1;
1423 		goto errout;
1424 
1425 	case POOL_STATE_DESTROYED:
1426 		/* inuse should never be set for a destroyed pool */
1427 		assert(0);
1428 		break;
1429 	}
1430 
1431 wipe_label:
1432 	ret = zpool_clear_label(fd);
1433 	if (ret != 0) {
1434 		(void) fprintf(stderr,
1435 		    gettext("failed to clear label for %s\n"), vdev);
1436 	}
1437 
1438 errout:
1439 	free(name);
1440 	(void) close(fd);
1441 
1442 	return (ret);
1443 }
1444 
1445 /*
1446  * zpool create [-fnd] [-o property=value] ...
1447  *		[-O file-system-property=value] ...
1448  *		[-R root] [-m mountpoint] <pool> <dev> ...
1449  *
1450  *	-f	Force creation, even if devices appear in use
1451  *	-n	Do not create the pool, but display the resulting layout if it
1452  *		were to be created.
1453  *      -R	Create a pool under an alternate root
1454  *      -m	Set default mountpoint for the root dataset.  By default it's
1455  *		'/<pool>'
1456  *	-o	Set property=value.
1457  *	-o	Set feature@feature=enabled|disabled.
1458  *	-d	Don't automatically enable all supported pool features
1459  *		(individual features can be enabled with -o).
1460  *	-O	Set fsproperty=value in the pool's root file system
1461  *
1462  * Creates the named pool according to the given vdev specification.  The
1463  * bulk of the vdev processing is done in make_root_vdev() in zpool_vdev.c.
1464  * Once we get the nvlist back from make_root_vdev(), we either print out the
1465  * contents (if '-n' was specified), or pass it to libzfs to do the creation.
1466  */
1467 int
1468 zpool_do_create(int argc, char **argv)
1469 {
1470 	boolean_t force = B_FALSE;
1471 	boolean_t dryrun = B_FALSE;
1472 	boolean_t enable_pool_features = B_TRUE;
1473 
1474 	int c;
1475 	nvlist_t *nvroot = NULL;
1476 	char *poolname;
1477 	char *tname = NULL;
1478 	int ret = 1;
1479 	char *altroot = NULL;
1480 	char *compat = NULL;
1481 	char *mountpoint = NULL;
1482 	nvlist_t *fsprops = NULL;
1483 	nvlist_t *props = NULL;
1484 	char *propval;
1485 
1486 	/* check options */
1487 	while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
1488 		switch (c) {
1489 		case 'f':
1490 			force = B_TRUE;
1491 			break;
1492 		case 'n':
1493 			dryrun = B_TRUE;
1494 			break;
1495 		case 'd':
1496 			enable_pool_features = B_FALSE;
1497 			break;
1498 		case 'R':
1499 			altroot = optarg;
1500 			if (add_prop_list(zpool_prop_to_name(
1501 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
1502 				goto errout;
1503 			if (add_prop_list_default(zpool_prop_to_name(
1504 			    ZPOOL_PROP_CACHEFILE), "none", &props))
1505 				goto errout;
1506 			break;
1507 		case 'm':
1508 			/* Equivalent to -O mountpoint=optarg */
1509 			mountpoint = optarg;
1510 			break;
1511 		case 'o':
1512 			if ((propval = strchr(optarg, '=')) == NULL) {
1513 				(void) fprintf(stderr, gettext("missing "
1514 				    "'=' for -o option\n"));
1515 				goto errout;
1516 			}
1517 			*propval = '\0';
1518 			propval++;
1519 
1520 			if (add_prop_list(optarg, propval, &props, B_TRUE))
1521 				goto errout;
1522 
1523 			/*
1524 			 * If the user is creating a pool that doesn't support
1525 			 * feature flags, don't enable any features.
1526 			 */
1527 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
1528 				char *end;
1529 				u_longlong_t ver;
1530 
1531 				ver = strtoull(propval, &end, 10);
1532 				if (*end == '\0' &&
1533 				    ver < SPA_VERSION_FEATURES) {
1534 					enable_pool_features = B_FALSE;
1535 				}
1536 			}
1537 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
1538 				altroot = propval;
1539 			if (zpool_name_to_prop(optarg) ==
1540 			    ZPOOL_PROP_COMPATIBILITY)
1541 				compat = propval;
1542 			break;
1543 		case 'O':
1544 			if ((propval = strchr(optarg, '=')) == NULL) {
1545 				(void) fprintf(stderr, gettext("missing "
1546 				    "'=' for -O option\n"));
1547 				goto errout;
1548 			}
1549 			*propval = '\0';
1550 			propval++;
1551 
1552 			/*
1553 			 * Mountpoints are checked and then added later.
1554 			 * Uniquely among properties, they can be specified
1555 			 * more than once, to avoid conflict with -m.
1556 			 */
1557 			if (0 == strcmp(optarg,
1558 			    zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
1559 				mountpoint = propval;
1560 			} else if (add_prop_list(optarg, propval, &fsprops,
1561 			    B_FALSE)) {
1562 				goto errout;
1563 			}
1564 			break;
1565 		case 't':
1566 			/*
1567 			 * Sanity check temporary pool name.
1568 			 */
1569 			if (strchr(optarg, '/') != NULL) {
1570 				(void) fprintf(stderr, gettext("cannot create "
1571 				    "'%s': invalid character '/' in temporary "
1572 				    "name\n"), optarg);
1573 				(void) fprintf(stderr, gettext("use 'zfs "
1574 				    "create' to create a dataset\n"));
1575 				goto errout;
1576 			}
1577 
1578 			if (add_prop_list(zpool_prop_to_name(
1579 			    ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
1580 				goto errout;
1581 			if (add_prop_list_default(zpool_prop_to_name(
1582 			    ZPOOL_PROP_CACHEFILE), "none", &props))
1583 				goto errout;
1584 			tname = optarg;
1585 			break;
1586 		case ':':
1587 			(void) fprintf(stderr, gettext("missing argument for "
1588 			    "'%c' option\n"), optopt);
1589 			goto badusage;
1590 		case '?':
1591 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1592 			    optopt);
1593 			goto badusage;
1594 		}
1595 	}
1596 
1597 	argc -= optind;
1598 	argv += optind;
1599 
1600 	/* get pool name and check number of arguments */
1601 	if (argc < 1) {
1602 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
1603 		goto badusage;
1604 	}
1605 	if (argc < 2) {
1606 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
1607 		goto badusage;
1608 	}
1609 
1610 	poolname = argv[0];
1611 
1612 	/*
1613 	 * As a special case, check for use of '/' in the name, and direct the
1614 	 * user to use 'zfs create' instead.
1615 	 */
1616 	if (strchr(poolname, '/') != NULL) {
1617 		(void) fprintf(stderr, gettext("cannot create '%s': invalid "
1618 		    "character '/' in pool name\n"), poolname);
1619 		(void) fprintf(stderr, gettext("use 'zfs create' to "
1620 		    "create a dataset\n"));
1621 		goto errout;
1622 	}
1623 
1624 	/* pass off to make_root_vdev for bulk processing */
1625 	nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
1626 	    argc - 1, argv + 1);
1627 	if (nvroot == NULL)
1628 		goto errout;
1629 
1630 	/* make_root_vdev() allows 0 toplevel children if there are spares */
1631 	if (!zfs_allocatable_devs(nvroot)) {
1632 		(void) fprintf(stderr, gettext("invalid vdev "
1633 		    "specification: at least one toplevel vdev must be "
1634 		    "specified\n"));
1635 		goto errout;
1636 	}
1637 
1638 	if (altroot != NULL && altroot[0] != '/') {
1639 		(void) fprintf(stderr, gettext("invalid alternate root '%s': "
1640 		    "must be an absolute path\n"), altroot);
1641 		goto errout;
1642 	}
1643 
1644 	/*
1645 	 * Check the validity of the mountpoint and direct the user to use the
1646 	 * '-m' mountpoint option if it looks like its in use.
1647 	 */
1648 	if (mountpoint == NULL ||
1649 	    (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
1650 	    strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
1651 		char buf[MAXPATHLEN];
1652 		DIR *dirp;
1653 
1654 		if (mountpoint && mountpoint[0] != '/') {
1655 			(void) fprintf(stderr, gettext("invalid mountpoint "
1656 			    "'%s': must be an absolute path, 'legacy', or "
1657 			    "'none'\n"), mountpoint);
1658 			goto errout;
1659 		}
1660 
1661 		if (mountpoint == NULL) {
1662 			if (altroot != NULL)
1663 				(void) snprintf(buf, sizeof (buf), "%s/%s",
1664 				    altroot, poolname);
1665 			else
1666 				(void) snprintf(buf, sizeof (buf), "/%s",
1667 				    poolname);
1668 		} else {
1669 			if (altroot != NULL)
1670 				(void) snprintf(buf, sizeof (buf), "%s%s",
1671 				    altroot, mountpoint);
1672 			else
1673 				(void) snprintf(buf, sizeof (buf), "%s",
1674 				    mountpoint);
1675 		}
1676 
1677 		if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
1678 			(void) fprintf(stderr, gettext("mountpoint '%s' : "
1679 			    "%s\n"), buf, strerror(errno));
1680 			(void) fprintf(stderr, gettext("use '-m' "
1681 			    "option to provide a different default\n"));
1682 			goto errout;
1683 		} else if (dirp) {
1684 			int count = 0;
1685 
1686 			while (count < 3 && readdir(dirp) != NULL)
1687 				count++;
1688 			(void) closedir(dirp);
1689 
1690 			if (count > 2) {
1691 				(void) fprintf(stderr, gettext("mountpoint "
1692 				    "'%s' exists and is not empty\n"), buf);
1693 				(void) fprintf(stderr, gettext("use '-m' "
1694 				    "option to provide a "
1695 				    "different default\n"));
1696 				goto errout;
1697 			}
1698 		}
1699 	}
1700 
1701 	/*
1702 	 * Now that the mountpoint's validity has been checked, ensure that
1703 	 * the property is set appropriately prior to creating the pool.
1704 	 */
1705 	if (mountpoint != NULL) {
1706 		ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
1707 		    mountpoint, &fsprops, B_FALSE);
1708 		if (ret != 0)
1709 			goto errout;
1710 	}
1711 
1712 	ret = 1;
1713 	if (dryrun) {
1714 		/*
1715 		 * For a dry run invocation, print out a basic message and run
1716 		 * through all the vdevs in the list and print out in an
1717 		 * appropriate hierarchy.
1718 		 */
1719 		(void) printf(gettext("would create '%s' with the "
1720 		    "following layout:\n\n"), poolname);
1721 
1722 		print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
1723 		print_vdev_tree(NULL, "dedup", nvroot, 0,
1724 		    VDEV_ALLOC_BIAS_DEDUP, 0);
1725 		print_vdev_tree(NULL, "special", nvroot, 0,
1726 		    VDEV_ALLOC_BIAS_SPECIAL, 0);
1727 		print_vdev_tree(NULL, "logs", nvroot, 0,
1728 		    VDEV_ALLOC_BIAS_LOG, 0);
1729 		print_cache_list(nvroot, 0);
1730 		print_spare_list(nvroot, 0);
1731 
1732 		ret = 0;
1733 	} else {
1734 		/*
1735 		 * Load in feature set.
1736 		 * Note: if compatibility property not given, we'll have
1737 		 * NULL, which means 'all features'.
1738 		 */
1739 		boolean_t requested_features[SPA_FEATURES];
1740 		if (zpool_do_load_compat(compat, requested_features) !=
1741 		    ZPOOL_COMPATIBILITY_OK)
1742 			goto errout;
1743 
1744 		/*
1745 		 * props contains list of features to enable.
1746 		 * For each feature:
1747 		 *  - remove it if feature@name=disabled
1748 		 *  - leave it there if feature@name=enabled
1749 		 *  - add it if:
1750 		 *    - enable_pool_features (ie: no '-d' or '-o version')
1751 		 *    - it's supported by the kernel module
1752 		 *    - it's in the requested feature set
1753 		 *  - warn if it's enabled but not in compat
1754 		 */
1755 		for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
1756 			char propname[MAXPATHLEN];
1757 			char *propval;
1758 			zfeature_info_t *feat = &spa_feature_table[i];
1759 
1760 			(void) snprintf(propname, sizeof (propname),
1761 			    "feature@%s", feat->fi_uname);
1762 
1763 			if (!nvlist_lookup_string(props, propname, &propval)) {
1764 				if (strcmp(propval,
1765 				    ZFS_FEATURE_DISABLED) == 0) {
1766 					(void) nvlist_remove_all(props,
1767 					    propname);
1768 				} else if (strcmp(propval,
1769 				    ZFS_FEATURE_ENABLED) == 0 &&
1770 				    !requested_features[i]) {
1771 					(void) fprintf(stderr, gettext(
1772 					    "Warning: feature \"%s\" enabled "
1773 					    "but is not in specified "
1774 					    "'compatibility' feature set.\n"),
1775 					    feat->fi_uname);
1776 				}
1777 			} else if (
1778 			    enable_pool_features &&
1779 			    feat->fi_zfs_mod_supported &&
1780 			    requested_features[i]) {
1781 				ret = add_prop_list(propname,
1782 				    ZFS_FEATURE_ENABLED, &props, B_TRUE);
1783 				if (ret != 0)
1784 					goto errout;
1785 			}
1786 		}
1787 
1788 		ret = 1;
1789 		if (zpool_create(g_zfs, poolname,
1790 		    nvroot, props, fsprops) == 0) {
1791 			zfs_handle_t *pool = zfs_open(g_zfs,
1792 			    tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
1793 			if (pool != NULL) {
1794 				if (zfs_mount(pool, NULL, 0) == 0) {
1795 					ret = zfs_share(pool, NULL);
1796 					zfs_commit_shares(NULL);
1797 				}
1798 				zfs_close(pool);
1799 			}
1800 		} else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
1801 			(void) fprintf(stderr, gettext("pool name may have "
1802 			    "been omitted\n"));
1803 		}
1804 	}
1805 
1806 errout:
1807 	nvlist_free(nvroot);
1808 	nvlist_free(fsprops);
1809 	nvlist_free(props);
1810 	return (ret);
1811 badusage:
1812 	nvlist_free(fsprops);
1813 	nvlist_free(props);
1814 	usage(B_FALSE);
1815 	return (2);
1816 }
1817 
1818 /*
1819  * zpool destroy <pool>
1820  *
1821  * 	-f	Forcefully unmount any datasets
1822  *
1823  * Destroy the given pool.  Automatically unmounts any datasets in the pool.
1824  */
1825 int
1826 zpool_do_destroy(int argc, char **argv)
1827 {
1828 	boolean_t force = B_FALSE;
1829 	int c;
1830 	char *pool;
1831 	zpool_handle_t *zhp;
1832 	int ret;
1833 
1834 	/* check options */
1835 	while ((c = getopt(argc, argv, "f")) != -1) {
1836 		switch (c) {
1837 		case 'f':
1838 			force = B_TRUE;
1839 			break;
1840 		case '?':
1841 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1842 			    optopt);
1843 			usage(B_FALSE);
1844 		}
1845 	}
1846 
1847 	argc -= optind;
1848 	argv += optind;
1849 
1850 	/* check arguments */
1851 	if (argc < 1) {
1852 		(void) fprintf(stderr, gettext("missing pool argument\n"));
1853 		usage(B_FALSE);
1854 	}
1855 	if (argc > 1) {
1856 		(void) fprintf(stderr, gettext("too many arguments\n"));
1857 		usage(B_FALSE);
1858 	}
1859 
1860 	pool = argv[0];
1861 
1862 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
1863 		/*
1864 		 * As a special case, check for use of '/' in the name, and
1865 		 * direct the user to use 'zfs destroy' instead.
1866 		 */
1867 		if (strchr(pool, '/') != NULL)
1868 			(void) fprintf(stderr, gettext("use 'zfs destroy' to "
1869 			    "destroy a dataset\n"));
1870 		return (1);
1871 	}
1872 
1873 	if (zpool_disable_datasets(zhp, force) != 0) {
1874 		(void) fprintf(stderr, gettext("could not destroy '%s': "
1875 		    "could not unmount datasets\n"), zpool_get_name(zhp));
1876 		zpool_close(zhp);
1877 		return (1);
1878 	}
1879 
1880 	/* The history must be logged as part of the export */
1881 	log_history = B_FALSE;
1882 
1883 	ret = (zpool_destroy(zhp, history_str) != 0);
1884 
1885 	zpool_close(zhp);
1886 
1887 	return (ret);
1888 }
1889 
1890 typedef struct export_cbdata {
1891 	boolean_t force;
1892 	boolean_t hardforce;
1893 } export_cbdata_t;
1894 
1895 /*
1896  * Export one pool
1897  */
1898 static int
1899 zpool_export_one(zpool_handle_t *zhp, void *data)
1900 {
1901 	export_cbdata_t *cb = data;
1902 
1903 	if (zpool_disable_datasets(zhp, cb->force) != 0)
1904 		return (1);
1905 
1906 	/* The history must be logged as part of the export */
1907 	log_history = B_FALSE;
1908 
1909 	if (cb->hardforce) {
1910 		if (zpool_export_force(zhp, history_str) != 0)
1911 			return (1);
1912 	} else if (zpool_export(zhp, cb->force, history_str) != 0) {
1913 		return (1);
1914 	}
1915 
1916 	return (0);
1917 }
1918 
1919 /*
1920  * zpool export [-f] <pool> ...
1921  *
1922  *	-a	Export all pools
1923  *	-f	Forcefully unmount datasets
1924  *
1925  * Export the given pools.  By default, the command will attempt to cleanly
1926  * unmount any active datasets within the pool.  If the '-f' flag is specified,
1927  * then the datasets will be forcefully unmounted.
1928  */
1929 int
1930 zpool_do_export(int argc, char **argv)
1931 {
1932 	export_cbdata_t cb;
1933 	boolean_t do_all = B_FALSE;
1934 	boolean_t force = B_FALSE;
1935 	boolean_t hardforce = B_FALSE;
1936 	int c, ret;
1937 
1938 	/* check options */
1939 	while ((c = getopt(argc, argv, "afF")) != -1) {
1940 		switch (c) {
1941 		case 'a':
1942 			do_all = B_TRUE;
1943 			break;
1944 		case 'f':
1945 			force = B_TRUE;
1946 			break;
1947 		case 'F':
1948 			hardforce = B_TRUE;
1949 			break;
1950 		case '?':
1951 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1952 			    optopt);
1953 			usage(B_FALSE);
1954 		}
1955 	}
1956 
1957 	cb.force = force;
1958 	cb.hardforce = hardforce;
1959 	argc -= optind;
1960 	argv += optind;
1961 
1962 	if (do_all) {
1963 		if (argc != 0) {
1964 			(void) fprintf(stderr, gettext("too many arguments\n"));
1965 			usage(B_FALSE);
1966 		}
1967 
1968 		return (for_each_pool(argc, argv, B_TRUE, NULL,
1969 		    ZFS_TYPE_POOL, B_FALSE, zpool_export_one, &cb));
1970 	}
1971 
1972 	/* check arguments */
1973 	if (argc < 1) {
1974 		(void) fprintf(stderr, gettext("missing pool argument\n"));
1975 		usage(B_FALSE);
1976 	}
1977 
1978 	ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
1979 	    B_FALSE, zpool_export_one, &cb);
1980 
1981 	return (ret);
1982 }
1983 
1984 /*
1985  * Given a vdev configuration, determine the maximum width needed for the device
1986  * name column.
1987  */
1988 static int
1989 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
1990     int name_flags)
1991 {
1992 	static const char *const subtypes[] =
1993 	    {ZPOOL_CONFIG_SPARES, ZPOOL_CONFIG_L2CACHE, ZPOOL_CONFIG_CHILDREN};
1994 
1995 	char *name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
1996 	max = MAX(strlen(name) + depth, max);
1997 	free(name);
1998 
1999 	nvlist_t **child;
2000 	uint_t children;
2001 	for (size_t i = 0; i < ARRAY_SIZE(subtypes); ++i)
2002 		if (nvlist_lookup_nvlist_array(nv, subtypes[i],
2003 		    &child, &children) == 0)
2004 			for (uint_t c = 0; c < children; ++c)
2005 				max = MAX(max_width(zhp, child[c], depth + 2,
2006 				    max, name_flags), max);
2007 
2008 	return (max);
2009 }
2010 
2011 typedef struct spare_cbdata {
2012 	uint64_t	cb_guid;
2013 	zpool_handle_t	*cb_zhp;
2014 } spare_cbdata_t;
2015 
2016 static boolean_t
2017 find_vdev(nvlist_t *nv, uint64_t search)
2018 {
2019 	uint64_t guid;
2020 	nvlist_t **child;
2021 	uint_t c, children;
2022 
2023 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
2024 	    search == guid)
2025 		return (B_TRUE);
2026 
2027 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2028 	    &child, &children) == 0) {
2029 		for (c = 0; c < children; c++)
2030 			if (find_vdev(child[c], search))
2031 				return (B_TRUE);
2032 	}
2033 
2034 	return (B_FALSE);
2035 }
2036 
2037 static int
2038 find_spare(zpool_handle_t *zhp, void *data)
2039 {
2040 	spare_cbdata_t *cbp = data;
2041 	nvlist_t *config, *nvroot;
2042 
2043 	config = zpool_get_config(zhp, NULL);
2044 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2045 	    &nvroot) == 0);
2046 
2047 	if (find_vdev(nvroot, cbp->cb_guid)) {
2048 		cbp->cb_zhp = zhp;
2049 		return (1);
2050 	}
2051 
2052 	zpool_close(zhp);
2053 	return (0);
2054 }
2055 
2056 typedef struct status_cbdata {
2057 	int		cb_count;
2058 	int		cb_name_flags;
2059 	int		cb_namewidth;
2060 	boolean_t	cb_allpools;
2061 	boolean_t	cb_verbose;
2062 	boolean_t	cb_literal;
2063 	boolean_t	cb_explain;
2064 	boolean_t	cb_first;
2065 	boolean_t	cb_dedup_stats;
2066 	boolean_t	cb_print_status;
2067 	boolean_t	cb_print_slow_ios;
2068 	boolean_t	cb_print_vdev_init;
2069 	boolean_t	cb_print_vdev_trim;
2070 	vdev_cmd_data_list_t	*vcdl;
2071 } status_cbdata_t;
2072 
2073 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
2074 static boolean_t
2075 is_blank_str(const char *str)
2076 {
2077 	for (; str != NULL && *str != '\0'; ++str)
2078 		if (!isblank(*str))
2079 			return (B_FALSE);
2080 	return (B_TRUE);
2081 }
2082 
2083 /* Print command output lines for specific vdev in a specific pool */
2084 static void
2085 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, char *path)
2086 {
2087 	vdev_cmd_data_t *data;
2088 	int i, j;
2089 	const char *val;
2090 
2091 	for (i = 0; i < vcdl->count; i++) {
2092 		if ((strcmp(vcdl->data[i].path, path) != 0) ||
2093 		    (strcmp(vcdl->data[i].pool, pool) != 0)) {
2094 			/* Not the vdev we're looking for */
2095 			continue;
2096 		}
2097 
2098 		data = &vcdl->data[i];
2099 		/* Print out all the output values for this vdev */
2100 		for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2101 			val = NULL;
2102 			/* Does this vdev have values for this column? */
2103 			for (int k = 0; k < data->cols_cnt; k++) {
2104 				if (strcmp(data->cols[k],
2105 				    vcdl->uniq_cols[j]) == 0) {
2106 					/* yes it does, record the value */
2107 					val = data->lines[k];
2108 					break;
2109 				}
2110 			}
2111 			/*
2112 			 * Mark empty values with dashes to make output
2113 			 * awk-able.
2114 			 */
2115 			if (val == NULL || is_blank_str(val))
2116 				val = "-";
2117 
2118 			printf("%*s", vcdl->uniq_cols_width[j], val);
2119 			if (j < vcdl->uniq_cols_cnt - 1)
2120 				fputs("  ", stdout);
2121 		}
2122 
2123 		/* Print out any values that aren't in a column at the end */
2124 		for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2125 			/* Did we have any columns?  If so print a spacer. */
2126 			if (vcdl->uniq_cols_cnt > 0)
2127 				fputs("  ", stdout);
2128 
2129 			val = data->lines[j];
2130 			fputs(val ?: "", stdout);
2131 		}
2132 		break;
2133 	}
2134 }
2135 
2136 /*
2137  * Print vdev initialization status for leaves
2138  */
2139 static void
2140 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
2141 {
2142 	if (verbose) {
2143 		if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
2144 		    vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
2145 		    vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
2146 		    !vs->vs_scan_removing) {
2147 			char zbuf[1024];
2148 			char tbuf[256];
2149 			struct tm zaction_ts;
2150 
2151 			time_t t = vs->vs_initialize_action_time;
2152 			int initialize_pct = 100;
2153 			if (vs->vs_initialize_state !=
2154 			    VDEV_INITIALIZE_COMPLETE) {
2155 				initialize_pct = (vs->vs_initialize_bytes_done *
2156 				    100 / (vs->vs_initialize_bytes_est + 1));
2157 			}
2158 
2159 			(void) localtime_r(&t, &zaction_ts);
2160 			(void) strftime(tbuf, sizeof (tbuf), "%c", &zaction_ts);
2161 
2162 			switch (vs->vs_initialize_state) {
2163 			case VDEV_INITIALIZE_SUSPENDED:
2164 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2165 				    gettext("suspended, started at"), tbuf);
2166 				break;
2167 			case VDEV_INITIALIZE_ACTIVE:
2168 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2169 				    gettext("started at"), tbuf);
2170 				break;
2171 			case VDEV_INITIALIZE_COMPLETE:
2172 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2173 				    gettext("completed at"), tbuf);
2174 				break;
2175 			}
2176 
2177 			(void) printf(gettext("  (%d%% initialized%s)"),
2178 			    initialize_pct, zbuf);
2179 		} else {
2180 			(void) printf(gettext("  (uninitialized)"));
2181 		}
2182 	} else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
2183 		(void) printf(gettext("  (initializing)"));
2184 	}
2185 }
2186 
2187 /*
2188  * Print vdev TRIM status for leaves
2189  */
2190 static void
2191 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
2192 {
2193 	if (verbose) {
2194 		if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
2195 		    vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
2196 		    vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
2197 		    !vs->vs_scan_removing) {
2198 			char zbuf[1024];
2199 			char tbuf[256];
2200 			struct tm zaction_ts;
2201 
2202 			time_t t = vs->vs_trim_action_time;
2203 			int trim_pct = 100;
2204 			if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
2205 				trim_pct = (vs->vs_trim_bytes_done *
2206 				    100 / (vs->vs_trim_bytes_est + 1));
2207 			}
2208 
2209 			(void) localtime_r(&t, &zaction_ts);
2210 			(void) strftime(tbuf, sizeof (tbuf), "%c", &zaction_ts);
2211 
2212 			switch (vs->vs_trim_state) {
2213 			case VDEV_TRIM_SUSPENDED:
2214 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2215 				    gettext("suspended, started at"), tbuf);
2216 				break;
2217 			case VDEV_TRIM_ACTIVE:
2218 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2219 				    gettext("started at"), tbuf);
2220 				break;
2221 			case VDEV_TRIM_COMPLETE:
2222 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2223 				    gettext("completed at"), tbuf);
2224 				break;
2225 			}
2226 
2227 			(void) printf(gettext("  (%d%% trimmed%s)"),
2228 			    trim_pct, zbuf);
2229 		} else if (vs->vs_trim_notsup) {
2230 			(void) printf(gettext("  (trim unsupported)"));
2231 		} else {
2232 			(void) printf(gettext("  (untrimmed)"));
2233 		}
2234 	} else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
2235 		(void) printf(gettext("  (trimming)"));
2236 	}
2237 }
2238 
2239 /*
2240  * Return the color associated with a health string.  This includes returning
2241  * NULL for no color change.
2242  */
2243 static const char *
2244 health_str_to_color(const char *health)
2245 {
2246 	if (strcmp(health, gettext("FAULTED")) == 0 ||
2247 	    strcmp(health, gettext("SUSPENDED")) == 0 ||
2248 	    strcmp(health, gettext("UNAVAIL")) == 0) {
2249 		return (ANSI_RED);
2250 	}
2251 
2252 	if (strcmp(health, gettext("OFFLINE")) == 0 ||
2253 	    strcmp(health, gettext("DEGRADED")) == 0 ||
2254 	    strcmp(health, gettext("REMOVED")) == 0) {
2255 		return (ANSI_YELLOW);
2256 	}
2257 
2258 	return (NULL);
2259 }
2260 
2261 /*
2262  * Print out configuration state as requested by status_callback.
2263  */
2264 static void
2265 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
2266     nvlist_t *nv, int depth, boolean_t isspare, vdev_rebuild_stat_t *vrs)
2267 {
2268 	nvlist_t **child, *root;
2269 	uint_t c, i, vsc, children;
2270 	pool_scan_stat_t *ps = NULL;
2271 	vdev_stat_t *vs;
2272 	char rbuf[6], wbuf[6], cbuf[6];
2273 	char *vname;
2274 	uint64_t notpresent;
2275 	spare_cbdata_t spare_cb;
2276 	const char *state;
2277 	char *type;
2278 	char *path = NULL;
2279 	const char *rcolor = NULL, *wcolor = NULL, *ccolor = NULL;
2280 
2281 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2282 	    &child, &children) != 0)
2283 		children = 0;
2284 
2285 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2286 	    (uint64_t **)&vs, &vsc) == 0);
2287 
2288 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2289 
2290 	if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2291 		return;
2292 
2293 	state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2294 
2295 	if (isspare) {
2296 		/*
2297 		 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
2298 		 * online drives.
2299 		 */
2300 		if (vs->vs_aux == VDEV_AUX_SPARED)
2301 			state = gettext("INUSE");
2302 		else if (vs->vs_state == VDEV_STATE_HEALTHY)
2303 			state = gettext("AVAIL");
2304 	}
2305 
2306 	printf_color(health_str_to_color(state),
2307 	    "\t%*s%-*s  %-8s", depth, "", cb->cb_namewidth - depth,
2308 	    name, state);
2309 
2310 	if (!isspare) {
2311 		if (vs->vs_read_errors)
2312 			rcolor = ANSI_RED;
2313 
2314 		if (vs->vs_write_errors)
2315 			wcolor = ANSI_RED;
2316 
2317 		if (vs->vs_checksum_errors)
2318 			ccolor = ANSI_RED;
2319 
2320 		if (cb->cb_literal) {
2321 			fputc(' ', stdout);
2322 			printf_color(rcolor, "%5llu",
2323 			    (u_longlong_t)vs->vs_read_errors);
2324 			fputc(' ', stdout);
2325 			printf_color(wcolor, "%5llu",
2326 			    (u_longlong_t)vs->vs_write_errors);
2327 			fputc(' ', stdout);
2328 			printf_color(ccolor, "%5llu",
2329 			    (u_longlong_t)vs->vs_checksum_errors);
2330 		} else {
2331 			zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
2332 			zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
2333 			zfs_nicenum(vs->vs_checksum_errors, cbuf,
2334 			    sizeof (cbuf));
2335 			fputc(' ', stdout);
2336 			printf_color(rcolor, "%5s", rbuf);
2337 			fputc(' ', stdout);
2338 			printf_color(wcolor, "%5s", wbuf);
2339 			fputc(' ', stdout);
2340 			printf_color(ccolor, "%5s", cbuf);
2341 		}
2342 		if (cb->cb_print_slow_ios) {
2343 			if (children == 0)  {
2344 				/* Only leafs vdevs have slow IOs */
2345 				zfs_nicenum(vs->vs_slow_ios, rbuf,
2346 				    sizeof (rbuf));
2347 			} else {
2348 				snprintf(rbuf, sizeof (rbuf), "-");
2349 			}
2350 
2351 			if (cb->cb_literal)
2352 				printf(" %5llu", (u_longlong_t)vs->vs_slow_ios);
2353 			else
2354 				printf(" %5s", rbuf);
2355 		}
2356 	}
2357 
2358 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
2359 	    &notpresent) == 0) {
2360 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
2361 		(void) printf("  %s %s", gettext("was"), path);
2362 	} else if (vs->vs_aux != 0) {
2363 		(void) printf("  ");
2364 		color_start(ANSI_RED);
2365 		switch (vs->vs_aux) {
2366 		case VDEV_AUX_OPEN_FAILED:
2367 			(void) printf(gettext("cannot open"));
2368 			break;
2369 
2370 		case VDEV_AUX_BAD_GUID_SUM:
2371 			(void) printf(gettext("missing device"));
2372 			break;
2373 
2374 		case VDEV_AUX_NO_REPLICAS:
2375 			(void) printf(gettext("insufficient replicas"));
2376 			break;
2377 
2378 		case VDEV_AUX_VERSION_NEWER:
2379 			(void) printf(gettext("newer version"));
2380 			break;
2381 
2382 		case VDEV_AUX_UNSUP_FEAT:
2383 			(void) printf(gettext("unsupported feature(s)"));
2384 			break;
2385 
2386 		case VDEV_AUX_ASHIFT_TOO_BIG:
2387 			(void) printf(gettext("unsupported minimum blocksize"));
2388 			break;
2389 
2390 		case VDEV_AUX_SPARED:
2391 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
2392 			    &spare_cb.cb_guid) == 0);
2393 			if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
2394 				if (strcmp(zpool_get_name(spare_cb.cb_zhp),
2395 				    zpool_get_name(zhp)) == 0)
2396 					(void) printf(gettext("currently in "
2397 					    "use"));
2398 				else
2399 					(void) printf(gettext("in use by "
2400 					    "pool '%s'"),
2401 					    zpool_get_name(spare_cb.cb_zhp));
2402 				zpool_close(spare_cb.cb_zhp);
2403 			} else {
2404 				(void) printf(gettext("currently in use"));
2405 			}
2406 			break;
2407 
2408 		case VDEV_AUX_ERR_EXCEEDED:
2409 			(void) printf(gettext("too many errors"));
2410 			break;
2411 
2412 		case VDEV_AUX_IO_FAILURE:
2413 			(void) printf(gettext("experienced I/O failures"));
2414 			break;
2415 
2416 		case VDEV_AUX_BAD_LOG:
2417 			(void) printf(gettext("bad intent log"));
2418 			break;
2419 
2420 		case VDEV_AUX_EXTERNAL:
2421 			(void) printf(gettext("external device fault"));
2422 			break;
2423 
2424 		case VDEV_AUX_SPLIT_POOL:
2425 			(void) printf(gettext("split into new pool"));
2426 			break;
2427 
2428 		case VDEV_AUX_ACTIVE:
2429 			(void) printf(gettext("currently in use"));
2430 			break;
2431 
2432 		case VDEV_AUX_CHILDREN_OFFLINE:
2433 			(void) printf(gettext("all children offline"));
2434 			break;
2435 
2436 		case VDEV_AUX_BAD_LABEL:
2437 			(void) printf(gettext("invalid label"));
2438 			break;
2439 
2440 		default:
2441 			(void) printf(gettext("corrupted data"));
2442 			break;
2443 		}
2444 		color_end();
2445 	} else if (children == 0 && !isspare &&
2446 	    getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
2447 	    VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
2448 	    vs->vs_configured_ashift < vs->vs_physical_ashift) {
2449 		(void) printf(
2450 		    gettext("  block size: %dB configured, %dB native"),
2451 		    1 << vs->vs_configured_ashift, 1 << vs->vs_physical_ashift);
2452 	}
2453 
2454 	if (vs->vs_scan_removing != 0) {
2455 		(void) printf(gettext("  (removing)"));
2456 	} else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
2457 		(void) printf(gettext("  (non-allocating)"));
2458 	}
2459 
2460 	/* The root vdev has the scrub/resilver stats */
2461 	root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
2462 	    ZPOOL_CONFIG_VDEV_TREE);
2463 	(void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
2464 	    (uint64_t **)&ps, &c);
2465 
2466 	/*
2467 	 * If you force fault a drive that's resilvering, its scan stats can
2468 	 * get frozen in time, giving the false impression that it's
2469 	 * being resilvered.  That's why we check the state to see if the vdev
2470 	 * is healthy before reporting "resilvering" or "repairing".
2471 	 */
2472 	if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0 &&
2473 	    vs->vs_state == VDEV_STATE_HEALTHY) {
2474 		if (vs->vs_scan_processed != 0) {
2475 			(void) printf(gettext("  (%s)"),
2476 			    (ps->pss_func == POOL_SCAN_RESILVER) ?
2477 			    "resilvering" : "repairing");
2478 		} else if (vs->vs_resilver_deferred) {
2479 			(void) printf(gettext("  (awaiting resilver)"));
2480 		}
2481 	}
2482 
2483 	/* The top-level vdevs have the rebuild stats */
2484 	if (vrs != NULL && vrs->vrs_state == VDEV_REBUILD_ACTIVE &&
2485 	    children == 0 && vs->vs_state == VDEV_STATE_HEALTHY) {
2486 		if (vs->vs_rebuild_processed != 0) {
2487 			(void) printf(gettext("  (resilvering)"));
2488 		}
2489 	}
2490 
2491 	if (cb->vcdl != NULL) {
2492 		if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
2493 			printf("  ");
2494 			zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
2495 		}
2496 	}
2497 
2498 	/* Display vdev initialization and trim status for leaves. */
2499 	if (children == 0) {
2500 		print_status_initialize(vs, cb->cb_print_vdev_init);
2501 		print_status_trim(vs, cb->cb_print_vdev_trim);
2502 	}
2503 
2504 	(void) printf("\n");
2505 
2506 	for (c = 0; c < children; c++) {
2507 		uint64_t islog = B_FALSE, ishole = B_FALSE;
2508 
2509 		/* Don't print logs or holes here */
2510 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2511 		    &islog);
2512 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
2513 		    &ishole);
2514 		if (islog || ishole)
2515 			continue;
2516 		/* Only print normal classes here */
2517 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
2518 			continue;
2519 
2520 		/* Provide vdev_rebuild_stats to children if available */
2521 		if (vrs == NULL) {
2522 			(void) nvlist_lookup_uint64_array(nv,
2523 			    ZPOOL_CONFIG_REBUILD_STATS,
2524 			    (uint64_t **)&vrs, &i);
2525 		}
2526 
2527 		vname = zpool_vdev_name(g_zfs, zhp, child[c],
2528 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2529 		print_status_config(zhp, cb, vname, child[c], depth + 2,
2530 		    isspare, vrs);
2531 		free(vname);
2532 	}
2533 }
2534 
2535 /*
2536  * Print the configuration of an exported pool.  Iterate over all vdevs in the
2537  * pool, printing out the name and status for each one.
2538  */
2539 static void
2540 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
2541     int depth)
2542 {
2543 	nvlist_t **child;
2544 	uint_t c, children;
2545 	vdev_stat_t *vs;
2546 	char *type, *vname;
2547 
2548 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2549 	if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
2550 	    strcmp(type, VDEV_TYPE_HOLE) == 0)
2551 		return;
2552 
2553 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2554 	    (uint64_t **)&vs, &c) == 0);
2555 
2556 	(void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
2557 	(void) printf("  %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
2558 
2559 	if (vs->vs_aux != 0) {
2560 		(void) printf("  ");
2561 
2562 		switch (vs->vs_aux) {
2563 		case VDEV_AUX_OPEN_FAILED:
2564 			(void) printf(gettext("cannot open"));
2565 			break;
2566 
2567 		case VDEV_AUX_BAD_GUID_SUM:
2568 			(void) printf(gettext("missing device"));
2569 			break;
2570 
2571 		case VDEV_AUX_NO_REPLICAS:
2572 			(void) printf(gettext("insufficient replicas"));
2573 			break;
2574 
2575 		case VDEV_AUX_VERSION_NEWER:
2576 			(void) printf(gettext("newer version"));
2577 			break;
2578 
2579 		case VDEV_AUX_UNSUP_FEAT:
2580 			(void) printf(gettext("unsupported feature(s)"));
2581 			break;
2582 
2583 		case VDEV_AUX_ERR_EXCEEDED:
2584 			(void) printf(gettext("too many errors"));
2585 			break;
2586 
2587 		case VDEV_AUX_ACTIVE:
2588 			(void) printf(gettext("currently in use"));
2589 			break;
2590 
2591 		case VDEV_AUX_CHILDREN_OFFLINE:
2592 			(void) printf(gettext("all children offline"));
2593 			break;
2594 
2595 		case VDEV_AUX_BAD_LABEL:
2596 			(void) printf(gettext("invalid label"));
2597 			break;
2598 
2599 		default:
2600 			(void) printf(gettext("corrupted data"));
2601 			break;
2602 		}
2603 	}
2604 	(void) printf("\n");
2605 
2606 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2607 	    &child, &children) != 0)
2608 		return;
2609 
2610 	for (c = 0; c < children; c++) {
2611 		uint64_t is_log = B_FALSE;
2612 
2613 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2614 		    &is_log);
2615 		if (is_log)
2616 			continue;
2617 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
2618 			continue;
2619 
2620 		vname = zpool_vdev_name(g_zfs, NULL, child[c],
2621 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2622 		print_import_config(cb, vname, child[c], depth + 2);
2623 		free(vname);
2624 	}
2625 
2626 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2627 	    &child, &children) == 0) {
2628 		(void) printf(gettext("\tcache\n"));
2629 		for (c = 0; c < children; c++) {
2630 			vname = zpool_vdev_name(g_zfs, NULL, child[c],
2631 			    cb->cb_name_flags);
2632 			(void) printf("\t  %s\n", vname);
2633 			free(vname);
2634 		}
2635 	}
2636 
2637 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2638 	    &child, &children) == 0) {
2639 		(void) printf(gettext("\tspares\n"));
2640 		for (c = 0; c < children; c++) {
2641 			vname = zpool_vdev_name(g_zfs, NULL, child[c],
2642 			    cb->cb_name_flags);
2643 			(void) printf("\t  %s\n", vname);
2644 			free(vname);
2645 		}
2646 	}
2647 }
2648 
2649 /*
2650  * Print specialized class vdevs.
2651  *
2652  * These are recorded as top level vdevs in the main pool child array
2653  * but with "is_log" set to 1 or an "alloc_bias" string. We use either
2654  * print_status_config() or print_import_config() to print the top level
2655  * class vdevs then any of their children (eg mirrored slogs) are printed
2656  * recursively - which works because only the top level vdev is marked.
2657  */
2658 static void
2659 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
2660     const char *class)
2661 {
2662 	uint_t c, children;
2663 	nvlist_t **child;
2664 	boolean_t printed = B_FALSE;
2665 
2666 	assert(zhp != NULL || !cb->cb_verbose);
2667 
2668 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
2669 	    &children) != 0)
2670 		return;
2671 
2672 	for (c = 0; c < children; c++) {
2673 		uint64_t is_log = B_FALSE;
2674 		char *bias = NULL;
2675 		char *type = NULL;
2676 
2677 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2678 		    &is_log);
2679 
2680 		if (is_log) {
2681 			bias = (char *)VDEV_ALLOC_CLASS_LOGS;
2682 		} else {
2683 			(void) nvlist_lookup_string(child[c],
2684 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
2685 			(void) nvlist_lookup_string(child[c],
2686 			    ZPOOL_CONFIG_TYPE, &type);
2687 		}
2688 
2689 		if (bias == NULL || strcmp(bias, class) != 0)
2690 			continue;
2691 		if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2692 			continue;
2693 
2694 		if (!printed) {
2695 			(void) printf("\t%s\t\n", gettext(class));
2696 			printed = B_TRUE;
2697 		}
2698 
2699 		char *name = zpool_vdev_name(g_zfs, zhp, child[c],
2700 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2701 		if (cb->cb_print_status)
2702 			print_status_config(zhp, cb, name, child[c], 2,
2703 			    B_FALSE, NULL);
2704 		else
2705 			print_import_config(cb, name, child[c], 2);
2706 		free(name);
2707 	}
2708 }
2709 
2710 /*
2711  * Display the status for the given pool.
2712  */
2713 static int
2714 show_import(nvlist_t *config, boolean_t report_error)
2715 {
2716 	uint64_t pool_state;
2717 	vdev_stat_t *vs;
2718 	char *name;
2719 	uint64_t guid;
2720 	uint64_t hostid = 0;
2721 	const char *msgid;
2722 	const char *hostname = "unknown";
2723 	nvlist_t *nvroot, *nvinfo;
2724 	zpool_status_t reason;
2725 	zpool_errata_t errata;
2726 	const char *health;
2727 	uint_t vsc;
2728 	char *comment;
2729 	status_cbdata_t cb = { 0 };
2730 
2731 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2732 	    &name) == 0);
2733 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
2734 	    &guid) == 0);
2735 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2736 	    &pool_state) == 0);
2737 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2738 	    &nvroot) == 0);
2739 
2740 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
2741 	    (uint64_t **)&vs, &vsc) == 0);
2742 	health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2743 
2744 	reason = zpool_import_status(config, &msgid, &errata);
2745 
2746 	/*
2747 	 * If we're importing using a cachefile, then we won't report any
2748 	 * errors unless we are in the scan phase of the import.
2749 	 */
2750 	if (reason != ZPOOL_STATUS_OK && !report_error)
2751 		return (reason);
2752 
2753 	(void) printf(gettext("   pool: %s\n"), name);
2754 	(void) printf(gettext("     id: %llu\n"), (u_longlong_t)guid);
2755 	(void) printf(gettext("  state: %s"), health);
2756 	if (pool_state == POOL_STATE_DESTROYED)
2757 		(void) printf(gettext(" (DESTROYED)"));
2758 	(void) printf("\n");
2759 
2760 	switch (reason) {
2761 	case ZPOOL_STATUS_MISSING_DEV_R:
2762 	case ZPOOL_STATUS_MISSING_DEV_NR:
2763 	case ZPOOL_STATUS_BAD_GUID_SUM:
2764 		printf_color(ANSI_BOLD, gettext("status: "));
2765 		printf_color(ANSI_YELLOW, gettext("One or more devices are "
2766 		    "missing from the system.\n"));
2767 		break;
2768 
2769 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
2770 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
2771 		printf_color(ANSI_BOLD, gettext("status: "));
2772 		printf_color(ANSI_YELLOW, gettext("One or more devices contains"
2773 		    " corrupted data.\n"));
2774 		break;
2775 
2776 	case ZPOOL_STATUS_CORRUPT_DATA:
2777 		(void) printf(
2778 		    gettext(" status: The pool data is corrupted.\n"));
2779 		break;
2780 
2781 	case ZPOOL_STATUS_OFFLINE_DEV:
2782 		printf_color(ANSI_BOLD, gettext("status: "));
2783 		printf_color(ANSI_YELLOW, gettext("One or more devices "
2784 		    "are offlined.\n"));
2785 		break;
2786 
2787 	case ZPOOL_STATUS_CORRUPT_POOL:
2788 		printf_color(ANSI_BOLD, gettext("status: "));
2789 		printf_color(ANSI_YELLOW, gettext("The pool metadata is "
2790 		    "corrupted.\n"));
2791 		break;
2792 
2793 	case ZPOOL_STATUS_VERSION_OLDER:
2794 		printf_color(ANSI_BOLD, gettext("status: "));
2795 		printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
2796 		    "a legacy on-disk version.\n"));
2797 		break;
2798 
2799 	case ZPOOL_STATUS_VERSION_NEWER:
2800 		printf_color(ANSI_BOLD, gettext("status: "));
2801 		printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
2802 		    "an incompatible version.\n"));
2803 		break;
2804 
2805 	case ZPOOL_STATUS_FEAT_DISABLED:
2806 		printf_color(ANSI_BOLD, gettext("status: "));
2807 		printf_color(ANSI_YELLOW, gettext("Some supported "
2808 		    "features are not enabled on the pool.\n\t"
2809 		    "(Note that they may be intentionally disabled "
2810 		    "if the\n\t'compatibility' property is set.)\n"));
2811 		break;
2812 
2813 	case ZPOOL_STATUS_COMPATIBILITY_ERR:
2814 		printf_color(ANSI_BOLD, gettext("status: "));
2815 		printf_color(ANSI_YELLOW, gettext("Error reading or parsing "
2816 		    "the file(s) indicated by the 'compatibility'\n"
2817 		    "property.\n"));
2818 		break;
2819 
2820 	case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
2821 		printf_color(ANSI_BOLD, gettext("status: "));
2822 		printf_color(ANSI_YELLOW, gettext("One or more features "
2823 		    "are enabled on the pool despite not being\n"
2824 		    "requested by the 'compatibility' property.\n"));
2825 		break;
2826 
2827 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
2828 		printf_color(ANSI_BOLD, gettext("status: "));
2829 		printf_color(ANSI_YELLOW, gettext("The pool uses the following "
2830 		    "feature(s) not supported on this system:\n"));
2831 		color_start(ANSI_YELLOW);
2832 		zpool_print_unsup_feat(config);
2833 		color_end();
2834 		break;
2835 
2836 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2837 		printf_color(ANSI_BOLD, gettext("status: "));
2838 		printf_color(ANSI_YELLOW, gettext("The pool can only be "
2839 		    "accessed in read-only mode on this system. It\n\tcannot be"
2840 		    " accessed in read-write mode because it uses the "
2841 		    "following\n\tfeature(s) not supported on this system:\n"));
2842 		color_start(ANSI_YELLOW);
2843 		zpool_print_unsup_feat(config);
2844 		color_end();
2845 		break;
2846 
2847 	case ZPOOL_STATUS_HOSTID_ACTIVE:
2848 		printf_color(ANSI_BOLD, gettext("status: "));
2849 		printf_color(ANSI_YELLOW, gettext("The pool is currently "
2850 		    "imported by another system.\n"));
2851 		break;
2852 
2853 	case ZPOOL_STATUS_HOSTID_REQUIRED:
2854 		printf_color(ANSI_BOLD, gettext("status: "));
2855 		printf_color(ANSI_YELLOW, gettext("The pool has the "
2856 		    "multihost property on.  It cannot\n\tbe safely imported "
2857 		    "when the system hostid is not set.\n"));
2858 		break;
2859 
2860 	case ZPOOL_STATUS_HOSTID_MISMATCH:
2861 		printf_color(ANSI_BOLD, gettext("status: "));
2862 		printf_color(ANSI_YELLOW, gettext("The pool was last accessed "
2863 		    "by another system.\n"));
2864 		break;
2865 
2866 	case ZPOOL_STATUS_FAULTED_DEV_R:
2867 	case ZPOOL_STATUS_FAULTED_DEV_NR:
2868 		printf_color(ANSI_BOLD, gettext("status: "));
2869 		printf_color(ANSI_YELLOW, gettext("One or more devices are "
2870 		    "faulted.\n"));
2871 		break;
2872 
2873 	case ZPOOL_STATUS_BAD_LOG:
2874 		printf_color(ANSI_BOLD, gettext("status: "));
2875 		printf_color(ANSI_YELLOW, gettext("An intent log record cannot "
2876 		    "be read.\n"));
2877 		break;
2878 
2879 	case ZPOOL_STATUS_RESILVERING:
2880 	case ZPOOL_STATUS_REBUILDING:
2881 		printf_color(ANSI_BOLD, gettext("status: "));
2882 		printf_color(ANSI_YELLOW, gettext("One or more devices were "
2883 		    "being resilvered.\n"));
2884 		break;
2885 
2886 	case ZPOOL_STATUS_ERRATA:
2887 		printf_color(ANSI_BOLD, gettext("status: "));
2888 		printf_color(ANSI_YELLOW, gettext("Errata #%d detected.\n"),
2889 		    errata);
2890 		break;
2891 
2892 	case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
2893 		printf_color(ANSI_BOLD, gettext("status: "));
2894 		printf_color(ANSI_YELLOW, gettext("One or more devices are "
2895 		    "configured to use a non-native block size.\n"
2896 		    "\tExpect reduced performance.\n"));
2897 		break;
2898 
2899 	default:
2900 		/*
2901 		 * No other status can be seen when importing pools.
2902 		 */
2903 		assert(reason == ZPOOL_STATUS_OK);
2904 	}
2905 
2906 	/*
2907 	 * Print out an action according to the overall state of the pool.
2908 	 */
2909 	if (vs->vs_state == VDEV_STATE_HEALTHY) {
2910 		if (reason == ZPOOL_STATUS_VERSION_OLDER ||
2911 		    reason == ZPOOL_STATUS_FEAT_DISABLED) {
2912 			(void) printf(gettext(" action: The pool can be "
2913 			    "imported using its name or numeric identifier, "
2914 			    "though\n\tsome features will not be available "
2915 			    "without an explicit 'zpool upgrade'.\n"));
2916 		} else if (reason == ZPOOL_STATUS_COMPATIBILITY_ERR) {
2917 			(void) printf(gettext(" action: The pool can be "
2918 			    "imported using its name or numeric\n\tidentifier, "
2919 			    "though the file(s) indicated by its "
2920 			    "'compatibility'\n\tproperty cannot be parsed at "
2921 			    "this time.\n"));
2922 		} else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
2923 			(void) printf(gettext(" action: The pool can be "
2924 			    "imported using its name or numeric "
2925 			    "identifier and\n\tthe '-f' flag.\n"));
2926 		} else if (reason == ZPOOL_STATUS_ERRATA) {
2927 			switch (errata) {
2928 			case ZPOOL_ERRATA_NONE:
2929 				break;
2930 
2931 			case ZPOOL_ERRATA_ZOL_2094_SCRUB:
2932 				(void) printf(gettext(" action: The pool can "
2933 				    "be imported using its name or numeric "
2934 				    "identifier,\n\thowever there is a compat"
2935 				    "ibility issue which should be corrected"
2936 				    "\n\tby running 'zpool scrub'\n"));
2937 				break;
2938 
2939 			case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
2940 				(void) printf(gettext(" action: The pool can"
2941 				    "not be imported with this version of ZFS "
2942 				    "due to\n\tan active asynchronous destroy. "
2943 				    "Revert to an earlier version\n\tand "
2944 				    "allow the destroy to complete before "
2945 				    "updating.\n"));
2946 				break;
2947 
2948 			case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
2949 				(void) printf(gettext(" action: Existing "
2950 				    "encrypted datasets contain an on-disk "
2951 				    "incompatibility, which\n\tneeds to be "
2952 				    "corrected. Backup these datasets to new "
2953 				    "encrypted datasets\n\tand destroy the "
2954 				    "old ones.\n"));
2955 				break;
2956 
2957 			case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
2958 				(void) printf(gettext(" action: Existing "
2959 				    "encrypted snapshots and bookmarks contain "
2960 				    "an on-disk\n\tincompatibility. This may "
2961 				    "cause on-disk corruption if they are used"
2962 				    "\n\twith 'zfs recv'. To correct the "
2963 				    "issue, enable the bookmark_v2 feature.\n\t"
2964 				    "No additional action is needed if there "
2965 				    "are no encrypted snapshots or\n\t"
2966 				    "bookmarks. If preserving the encrypted "
2967 				    "snapshots and bookmarks is\n\trequired, "
2968 				    "use a non-raw send to backup and restore "
2969 				    "them. Alternately,\n\tthey may be removed"
2970 				    " to resolve the incompatibility.\n"));
2971 				break;
2972 			default:
2973 				/*
2974 				 * All errata must contain an action message.
2975 				 */
2976 				assert(0);
2977 			}
2978 		} else {
2979 			(void) printf(gettext(" action: The pool can be "
2980 			    "imported using its name or numeric "
2981 			    "identifier.\n"));
2982 		}
2983 	} else if (vs->vs_state == VDEV_STATE_DEGRADED) {
2984 		(void) printf(gettext(" action: The pool can be imported "
2985 		    "despite missing or damaged devices.  The\n\tfault "
2986 		    "tolerance of the pool may be compromised if imported.\n"));
2987 	} else {
2988 		switch (reason) {
2989 		case ZPOOL_STATUS_VERSION_NEWER:
2990 			(void) printf(gettext(" action: The pool cannot be "
2991 			    "imported.  Access the pool on a system running "
2992 			    "newer\n\tsoftware, or recreate the pool from "
2993 			    "backup.\n"));
2994 			break;
2995 		case ZPOOL_STATUS_UNSUP_FEAT_READ:
2996 			printf_color(ANSI_BOLD, gettext("action: "));
2997 			printf_color(ANSI_YELLOW, gettext("The pool cannot be "
2998 			    "imported. Access the pool on a system that "
2999 			    "supports\n\tthe required feature(s), or recreate "
3000 			    "the pool from backup.\n"));
3001 			break;
3002 		case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3003 			printf_color(ANSI_BOLD, gettext("action: "));
3004 			printf_color(ANSI_YELLOW, gettext("The pool cannot be "
3005 			    "imported in read-write mode. Import the pool "
3006 			    "with\n"
3007 			    "\t\"-o readonly=on\", access the pool on a system "
3008 			    "that supports the\n\trequired feature(s), or "
3009 			    "recreate the pool from backup.\n"));
3010 			break;
3011 		case ZPOOL_STATUS_MISSING_DEV_R:
3012 		case ZPOOL_STATUS_MISSING_DEV_NR:
3013 		case ZPOOL_STATUS_BAD_GUID_SUM:
3014 			(void) printf(gettext(" action: The pool cannot be "
3015 			    "imported. Attach the missing\n\tdevices and try "
3016 			    "again.\n"));
3017 			break;
3018 		case ZPOOL_STATUS_HOSTID_ACTIVE:
3019 			VERIFY0(nvlist_lookup_nvlist(config,
3020 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
3021 
3022 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3023 				hostname = fnvlist_lookup_string(nvinfo,
3024 				    ZPOOL_CONFIG_MMP_HOSTNAME);
3025 
3026 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3027 				hostid = fnvlist_lookup_uint64(nvinfo,
3028 				    ZPOOL_CONFIG_MMP_HOSTID);
3029 
3030 			(void) printf(gettext(" action: The pool must be "
3031 			    "exported from %s (hostid=%"PRIx64")\n\tbefore it "
3032 			    "can be safely imported.\n"), hostname, hostid);
3033 			break;
3034 		case ZPOOL_STATUS_HOSTID_REQUIRED:
3035 			(void) printf(gettext(" action: Set a unique system "
3036 			    "hostid with the zgenhostid(8) command.\n"));
3037 			break;
3038 		default:
3039 			(void) printf(gettext(" action: The pool cannot be "
3040 			    "imported due to damaged devices or data.\n"));
3041 		}
3042 	}
3043 
3044 	/* Print the comment attached to the pool. */
3045 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
3046 		(void) printf(gettext("comment: %s\n"), comment);
3047 
3048 	/*
3049 	 * If the state is "closed" or "can't open", and the aux state
3050 	 * is "corrupt data":
3051 	 */
3052 	if (((vs->vs_state == VDEV_STATE_CLOSED) ||
3053 	    (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
3054 	    (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
3055 		if (pool_state == POOL_STATE_DESTROYED)
3056 			(void) printf(gettext("\tThe pool was destroyed, "
3057 			    "but can be imported using the '-Df' flags.\n"));
3058 		else if (pool_state != POOL_STATE_EXPORTED)
3059 			(void) printf(gettext("\tThe pool may be active on "
3060 			    "another system, but can be imported using\n\t"
3061 			    "the '-f' flag.\n"));
3062 	}
3063 
3064 	if (msgid != NULL) {
3065 		(void) printf(gettext(
3066 		    "   see: https://openzfs.github.io/openzfs-docs/msg/%s\n"),
3067 		    msgid);
3068 	}
3069 
3070 	(void) printf(gettext(" config:\n\n"));
3071 
3072 	cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
3073 	    VDEV_NAME_TYPE_ID);
3074 	if (cb.cb_namewidth < 10)
3075 		cb.cb_namewidth = 10;
3076 
3077 	print_import_config(&cb, name, nvroot, 0);
3078 
3079 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
3080 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
3081 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
3082 
3083 	if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
3084 		(void) printf(gettext("\n\tAdditional devices are known to "
3085 		    "be part of this pool, though their\n\texact "
3086 		    "configuration cannot be determined.\n"));
3087 	}
3088 	return (0);
3089 }
3090 
3091 static boolean_t
3092 zfs_force_import_required(nvlist_t *config)
3093 {
3094 	uint64_t state;
3095 	uint64_t hostid = 0;
3096 	nvlist_t *nvinfo;
3097 
3098 	state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
3099 	(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID, &hostid);
3100 
3101 	if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
3102 		return (B_TRUE);
3103 
3104 	nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3105 	if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
3106 		mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
3107 		    ZPOOL_CONFIG_MMP_STATE);
3108 
3109 		if (mmp_state != MMP_STATE_INACTIVE)
3110 			return (B_TRUE);
3111 	}
3112 
3113 	return (B_FALSE);
3114 }
3115 
3116 /*
3117  * Perform the import for the given configuration.  This passes the heavy
3118  * lifting off to zpool_import_props(), and then mounts the datasets contained
3119  * within the pool.
3120  */
3121 static int
3122 do_import(nvlist_t *config, const char *newname, const char *mntopts,
3123     nvlist_t *props, int flags)
3124 {
3125 	int ret = 0;
3126 	zpool_handle_t *zhp;
3127 	const char *name;
3128 	uint64_t version;
3129 
3130 	name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
3131 	version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3132 
3133 	if (!SPA_VERSION_IS_SUPPORTED(version)) {
3134 		(void) fprintf(stderr, gettext("cannot import '%s': pool "
3135 		    "is formatted using an unsupported ZFS version\n"), name);
3136 		return (1);
3137 	} else if (zfs_force_import_required(config) &&
3138 	    !(flags & ZFS_IMPORT_ANY_HOST)) {
3139 		mmp_state_t mmp_state = MMP_STATE_INACTIVE;
3140 		nvlist_t *nvinfo;
3141 
3142 		nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3143 		if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
3144 			mmp_state = fnvlist_lookup_uint64(nvinfo,
3145 			    ZPOOL_CONFIG_MMP_STATE);
3146 
3147 		if (mmp_state == MMP_STATE_ACTIVE) {
3148 			const char *hostname = "<unknown>";
3149 			uint64_t hostid = 0;
3150 
3151 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3152 				hostname = fnvlist_lookup_string(nvinfo,
3153 				    ZPOOL_CONFIG_MMP_HOSTNAME);
3154 
3155 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3156 				hostid = fnvlist_lookup_uint64(nvinfo,
3157 				    ZPOOL_CONFIG_MMP_HOSTID);
3158 
3159 			(void) fprintf(stderr, gettext("cannot import '%s': "
3160 			    "pool is imported on %s (hostid: "
3161 			    "0x%"PRIx64")\nExport the pool on the other "
3162 			    "system, then run 'zpool import'.\n"),
3163 			    name, hostname, hostid);
3164 		} else if (mmp_state == MMP_STATE_NO_HOSTID) {
3165 			(void) fprintf(stderr, gettext("Cannot import '%s': "
3166 			    "pool has the multihost property on and the\n"
3167 			    "system's hostid is not set. Set a unique hostid "
3168 			    "with the zgenhostid(8) command.\n"), name);
3169 		} else {
3170 			const char *hostname = "<unknown>";
3171 			time_t timestamp = 0;
3172 			uint64_t hostid = 0;
3173 
3174 			if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
3175 				hostname = fnvlist_lookup_string(config,
3176 				    ZPOOL_CONFIG_HOSTNAME);
3177 
3178 			if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
3179 				timestamp = fnvlist_lookup_uint64(config,
3180 				    ZPOOL_CONFIG_TIMESTAMP);
3181 
3182 			if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
3183 				hostid = fnvlist_lookup_uint64(config,
3184 				    ZPOOL_CONFIG_HOSTID);
3185 
3186 			(void) fprintf(stderr, gettext("cannot import '%s': "
3187 			    "pool was previously in use from another system.\n"
3188 			    "Last accessed by %s (hostid=%"PRIx64") at %s"
3189 			    "The pool can be imported, use 'zpool import -f' "
3190 			    "to import the pool.\n"), name, hostname,
3191 			    hostid, ctime(&timestamp));
3192 		}
3193 
3194 		return (1);
3195 	}
3196 
3197 	if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
3198 		return (1);
3199 
3200 	if (newname != NULL)
3201 		name = newname;
3202 
3203 	if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
3204 		return (1);
3205 
3206 	/*
3207 	 * Loading keys is best effort. We don't want to return immediately
3208 	 * if it fails but we do want to give the error to the caller.
3209 	 */
3210 	if (flags & ZFS_IMPORT_LOAD_KEYS &&
3211 	    zfs_crypto_attempt_load_keys(g_zfs, name) != 0)
3212 			ret = 1;
3213 
3214 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3215 	    !(flags & ZFS_IMPORT_ONLY) &&
3216 	    zpool_enable_datasets(zhp, mntopts, 0) != 0) {
3217 		zpool_close(zhp);
3218 		return (1);
3219 	}
3220 
3221 	zpool_close(zhp);
3222 	return (ret);
3223 }
3224 
3225 static int
3226 import_pools(nvlist_t *pools, nvlist_t *props, char *mntopts, int flags,
3227     char *orig_name, char *new_name,
3228     boolean_t do_destroyed, boolean_t pool_specified, boolean_t do_all,
3229     importargs_t *import)
3230 {
3231 	nvlist_t *config = NULL;
3232 	nvlist_t *found_config = NULL;
3233 	uint64_t pool_state;
3234 
3235 	/*
3236 	 * At this point we have a list of import candidate configs. Even if
3237 	 * we were searching by pool name or guid, we still need to
3238 	 * post-process the list to deal with pool state and possible
3239 	 * duplicate names.
3240 	 */
3241 	int err = 0;
3242 	nvpair_t *elem = NULL;
3243 	boolean_t first = B_TRUE;
3244 	while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3245 
3246 		verify(nvpair_value_nvlist(elem, &config) == 0);
3247 
3248 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3249 		    &pool_state) == 0);
3250 		if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
3251 			continue;
3252 		if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
3253 			continue;
3254 
3255 		verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
3256 		    import->policy) == 0);
3257 
3258 		if (!pool_specified) {
3259 			if (first)
3260 				first = B_FALSE;
3261 			else if (!do_all)
3262 				(void) fputc('\n', stdout);
3263 
3264 			if (do_all) {
3265 				err |= do_import(config, NULL, mntopts,
3266 				    props, flags);
3267 			} else {
3268 				/*
3269 				 * If we're importing from cachefile, then
3270 				 * we don't want to report errors until we
3271 				 * are in the scan phase of the import. If
3272 				 * we get an error, then we return that error
3273 				 * to invoke the scan phase.
3274 				 */
3275 				if (import->cachefile && !import->scan)
3276 					err = show_import(config, B_FALSE);
3277 				else
3278 					(void) show_import(config, B_TRUE);
3279 			}
3280 		} else if (import->poolname != NULL) {
3281 			char *name;
3282 
3283 			/*
3284 			 * We are searching for a pool based on name.
3285 			 */
3286 			verify(nvlist_lookup_string(config,
3287 			    ZPOOL_CONFIG_POOL_NAME, &name) == 0);
3288 
3289 			if (strcmp(name, import->poolname) == 0) {
3290 				if (found_config != NULL) {
3291 					(void) fprintf(stderr, gettext(
3292 					    "cannot import '%s': more than "
3293 					    "one matching pool\n"),
3294 					    import->poolname);
3295 					(void) fprintf(stderr, gettext(
3296 					    "import by numeric ID instead\n"));
3297 					err = B_TRUE;
3298 				}
3299 				found_config = config;
3300 			}
3301 		} else {
3302 			uint64_t guid;
3303 
3304 			/*
3305 			 * Search for a pool by guid.
3306 			 */
3307 			verify(nvlist_lookup_uint64(config,
3308 			    ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
3309 
3310 			if (guid == import->guid)
3311 				found_config = config;
3312 		}
3313 	}
3314 
3315 	/*
3316 	 * If we were searching for a specific pool, verify that we found a
3317 	 * pool, and then do the import.
3318 	 */
3319 	if (pool_specified && err == 0) {
3320 		if (found_config == NULL) {
3321 			(void) fprintf(stderr, gettext("cannot import '%s': "
3322 			    "no such pool available\n"), orig_name);
3323 			err = B_TRUE;
3324 		} else {
3325 			err |= do_import(found_config, new_name,
3326 			    mntopts, props, flags);
3327 		}
3328 	}
3329 
3330 	/*
3331 	 * If we were just looking for pools, report an error if none were
3332 	 * found.
3333 	 */
3334 	if (!pool_specified && first)
3335 		(void) fprintf(stderr,
3336 		    gettext("no pools available to import\n"));
3337 	return (err);
3338 }
3339 
3340 typedef struct target_exists_args {
3341 	const char	*poolname;
3342 	uint64_t	poolguid;
3343 } target_exists_args_t;
3344 
3345 static int
3346 name_or_guid_exists(zpool_handle_t *zhp, void *data)
3347 {
3348 	target_exists_args_t *args = data;
3349 	nvlist_t *config = zpool_get_config(zhp, NULL);
3350 	int found = 0;
3351 
3352 	if (config == NULL)
3353 		return (0);
3354 
3355 	if (args->poolname != NULL) {
3356 		char *pool_name;
3357 
3358 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3359 		    &pool_name) == 0);
3360 		if (strcmp(pool_name, args->poolname) == 0)
3361 			found = 1;
3362 	} else {
3363 		uint64_t pool_guid;
3364 
3365 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3366 		    &pool_guid) == 0);
3367 		if (pool_guid == args->poolguid)
3368 			found = 1;
3369 	}
3370 	zpool_close(zhp);
3371 
3372 	return (found);
3373 }
3374 /*
3375  * zpool checkpoint <pool>
3376  *       checkpoint --discard <pool>
3377  *
3378  *       -d         Discard the checkpoint from a checkpointed
3379  *       --discard  pool.
3380  *
3381  *       -w         Wait for discarding a checkpoint to complete.
3382  *       --wait
3383  *
3384  * Checkpoints the specified pool, by taking a "snapshot" of its
3385  * current state. A pool can only have one checkpoint at a time.
3386  */
3387 int
3388 zpool_do_checkpoint(int argc, char **argv)
3389 {
3390 	boolean_t discard, wait;
3391 	char *pool;
3392 	zpool_handle_t *zhp;
3393 	int c, err;
3394 
3395 	struct option long_options[] = {
3396 		{"discard", no_argument, NULL, 'd'},
3397 		{"wait", no_argument, NULL, 'w'},
3398 		{0, 0, 0, 0}
3399 	};
3400 
3401 	discard = B_FALSE;
3402 	wait = B_FALSE;
3403 	while ((c = getopt_long(argc, argv, ":dw", long_options, NULL)) != -1) {
3404 		switch (c) {
3405 		case 'd':
3406 			discard = B_TRUE;
3407 			break;
3408 		case 'w':
3409 			wait = B_TRUE;
3410 			break;
3411 		case '?':
3412 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3413 			    optopt);
3414 			usage(B_FALSE);
3415 		}
3416 	}
3417 
3418 	if (wait && !discard) {
3419 		(void) fprintf(stderr, gettext("--wait only valid when "
3420 		    "--discard also specified\n"));
3421 		usage(B_FALSE);
3422 	}
3423 
3424 	argc -= optind;
3425 	argv += optind;
3426 
3427 	if (argc < 1) {
3428 		(void) fprintf(stderr, gettext("missing pool argument\n"));
3429 		usage(B_FALSE);
3430 	}
3431 
3432 	if (argc > 1) {
3433 		(void) fprintf(stderr, gettext("too many arguments\n"));
3434 		usage(B_FALSE);
3435 	}
3436 
3437 	pool = argv[0];
3438 
3439 	if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
3440 		/* As a special case, check for use of '/' in the name */
3441 		if (strchr(pool, '/') != NULL)
3442 			(void) fprintf(stderr, gettext("'zpool checkpoint' "
3443 			    "doesn't work on datasets. To save the state "
3444 			    "of a dataset from a specific point in time "
3445 			    "please use 'zfs snapshot'\n"));
3446 		return (1);
3447 	}
3448 
3449 	if (discard) {
3450 		err = (zpool_discard_checkpoint(zhp) != 0);
3451 		if (err == 0 && wait)
3452 			err = zpool_wait(zhp, ZPOOL_WAIT_CKPT_DISCARD);
3453 	} else {
3454 		err = (zpool_checkpoint(zhp) != 0);
3455 	}
3456 
3457 	zpool_close(zhp);
3458 
3459 	return (err);
3460 }
3461 
3462 #define	CHECKPOINT_OPT	1024
3463 
3464 /*
3465  * zpool import [-d dir] [-D]
3466  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
3467  *              [-d dir | -c cachefile | -s] [-f] -a
3468  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
3469  *              [-d dir | -c cachefile | -s] [-f] [-n] [-F] <pool | id>
3470  *              [newpool]
3471  *
3472  *	-c	Read pool information from a cachefile instead of searching
3473  *		devices. If importing from a cachefile config fails, then
3474  *		fallback to searching for devices only in the directories that
3475  *		exist in the cachefile.
3476  *
3477  *	-d	Scan in a specific directory, other than /dev/.  More than
3478  *		one directory can be specified using multiple '-d' options.
3479  *
3480  *	-D	Scan for previously destroyed pools or import all or only
3481  *		specified destroyed pools.
3482  *
3483  *	-R	Temporarily import the pool, with all mountpoints relative to
3484  *		the given root.  The pool will remain exported when the machine
3485  *		is rebooted.
3486  *
3487  *	-V	Import even in the presence of faulted vdevs.  This is an
3488  *		intentionally undocumented option for testing purposes, and
3489  *		treats the pool configuration as complete, leaving any bad
3490  *		vdevs in the FAULTED state. In other words, it does verbatim
3491  *		import.
3492  *
3493  *	-f	Force import, even if it appears that the pool is active.
3494  *
3495  *	-F	Attempt rewind if necessary.
3496  *
3497  *	-n	See if rewind would work, but don't actually rewind.
3498  *
3499  *	-N	Import the pool but don't mount datasets.
3500  *
3501  *	-T	Specify a starting txg to use for import. This option is
3502  *		intentionally undocumented option for testing purposes.
3503  *
3504  *	-a	Import all pools found.
3505  *
3506  *	-l	Load encryption keys while importing.
3507  *
3508  *	-o	Set property=value and/or temporary mount options (without '=').
3509  *
3510  *	-s	Scan using the default search path, the libblkid cache will
3511  *		not be consulted.
3512  *
3513  *	--rewind-to-checkpoint
3514  *		Import the pool and revert back to the checkpoint.
3515  *
3516  * The import command scans for pools to import, and import pools based on pool
3517  * name and GUID.  The pool can also be renamed as part of the import process.
3518  */
3519 int
3520 zpool_do_import(int argc, char **argv)
3521 {
3522 	char **searchdirs = NULL;
3523 	char *env, *envdup = NULL;
3524 	int nsearch = 0;
3525 	int c;
3526 	int err = 0;
3527 	nvlist_t *pools = NULL;
3528 	boolean_t do_all = B_FALSE;
3529 	boolean_t do_destroyed = B_FALSE;
3530 	char *mntopts = NULL;
3531 	uint64_t searchguid = 0;
3532 	char *searchname = NULL;
3533 	char *propval;
3534 	nvlist_t *policy = NULL;
3535 	nvlist_t *props = NULL;
3536 	int flags = ZFS_IMPORT_NORMAL;
3537 	uint32_t rewind_policy = ZPOOL_NO_REWIND;
3538 	boolean_t dryrun = B_FALSE;
3539 	boolean_t do_rewind = B_FALSE;
3540 	boolean_t xtreme_rewind = B_FALSE;
3541 	boolean_t do_scan = B_FALSE;
3542 	boolean_t pool_exists = B_FALSE;
3543 	boolean_t pool_specified = B_FALSE;
3544 	uint64_t txg = -1ULL;
3545 	char *cachefile = NULL;
3546 	importargs_t idata = { 0 };
3547 	char *endptr;
3548 
3549 	struct option long_options[] = {
3550 		{"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
3551 		{0, 0, 0, 0}
3552 	};
3553 
3554 	/* check options */
3555 	while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmnNo:R:stT:VX",
3556 	    long_options, NULL)) != -1) {
3557 		switch (c) {
3558 		case 'a':
3559 			do_all = B_TRUE;
3560 			break;
3561 		case 'c':
3562 			cachefile = optarg;
3563 			break;
3564 		case 'd':
3565 			searchdirs = safe_realloc(searchdirs,
3566 			    (nsearch + 1) * sizeof (char *));
3567 			searchdirs[nsearch++] = optarg;
3568 			break;
3569 		case 'D':
3570 			do_destroyed = B_TRUE;
3571 			break;
3572 		case 'f':
3573 			flags |= ZFS_IMPORT_ANY_HOST;
3574 			break;
3575 		case 'F':
3576 			do_rewind = B_TRUE;
3577 			break;
3578 		case 'l':
3579 			flags |= ZFS_IMPORT_LOAD_KEYS;
3580 			break;
3581 		case 'm':
3582 			flags |= ZFS_IMPORT_MISSING_LOG;
3583 			break;
3584 		case 'n':
3585 			dryrun = B_TRUE;
3586 			break;
3587 		case 'N':
3588 			flags |= ZFS_IMPORT_ONLY;
3589 			break;
3590 		case 'o':
3591 			if ((propval = strchr(optarg, '=')) != NULL) {
3592 				*propval = '\0';
3593 				propval++;
3594 				if (add_prop_list(optarg, propval,
3595 				    &props, B_TRUE))
3596 					goto error;
3597 			} else {
3598 				mntopts = optarg;
3599 			}
3600 			break;
3601 		case 'R':
3602 			if (add_prop_list(zpool_prop_to_name(
3603 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
3604 				goto error;
3605 			if (add_prop_list_default(zpool_prop_to_name(
3606 			    ZPOOL_PROP_CACHEFILE), "none", &props))
3607 				goto error;
3608 			break;
3609 		case 's':
3610 			do_scan = B_TRUE;
3611 			break;
3612 		case 't':
3613 			flags |= ZFS_IMPORT_TEMP_NAME;
3614 			if (add_prop_list_default(zpool_prop_to_name(
3615 			    ZPOOL_PROP_CACHEFILE), "none", &props))
3616 				goto error;
3617 			break;
3618 
3619 		case 'T':
3620 			errno = 0;
3621 			txg = strtoull(optarg, &endptr, 0);
3622 			if (errno != 0 || *endptr != '\0') {
3623 				(void) fprintf(stderr,
3624 				    gettext("invalid txg value\n"));
3625 				usage(B_FALSE);
3626 			}
3627 			rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
3628 			break;
3629 		case 'V':
3630 			flags |= ZFS_IMPORT_VERBATIM;
3631 			break;
3632 		case 'X':
3633 			xtreme_rewind = B_TRUE;
3634 			break;
3635 		case CHECKPOINT_OPT:
3636 			flags |= ZFS_IMPORT_CHECKPOINT;
3637 			break;
3638 		case ':':
3639 			(void) fprintf(stderr, gettext("missing argument for "
3640 			    "'%c' option\n"), optopt);
3641 			usage(B_FALSE);
3642 			break;
3643 		case '?':
3644 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3645 			    optopt);
3646 			usage(B_FALSE);
3647 		}
3648 	}
3649 
3650 	argc -= optind;
3651 	argv += optind;
3652 
3653 	if (cachefile && nsearch != 0) {
3654 		(void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
3655 		usage(B_FALSE);
3656 	}
3657 
3658 	if (cachefile && do_scan) {
3659 		(void) fprintf(stderr, gettext("-c is incompatible with -s\n"));
3660 		usage(B_FALSE);
3661 	}
3662 
3663 	if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
3664 		(void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
3665 		usage(B_FALSE);
3666 	}
3667 
3668 	if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
3669 		(void) fprintf(stderr, gettext("-l is only meaningful during "
3670 		    "an import\n"));
3671 		usage(B_FALSE);
3672 	}
3673 
3674 	if ((dryrun || xtreme_rewind) && !do_rewind) {
3675 		(void) fprintf(stderr,
3676 		    gettext("-n or -X only meaningful with -F\n"));
3677 		usage(B_FALSE);
3678 	}
3679 	if (dryrun)
3680 		rewind_policy = ZPOOL_TRY_REWIND;
3681 	else if (do_rewind)
3682 		rewind_policy = ZPOOL_DO_REWIND;
3683 	if (xtreme_rewind)
3684 		rewind_policy |= ZPOOL_EXTREME_REWIND;
3685 
3686 	/* In the future, we can capture further policy and include it here */
3687 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
3688 	    nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
3689 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
3690 	    rewind_policy) != 0)
3691 		goto error;
3692 
3693 	/* check argument count */
3694 	if (do_all) {
3695 		if (argc != 0) {
3696 			(void) fprintf(stderr, gettext("too many arguments\n"));
3697 			usage(B_FALSE);
3698 		}
3699 	} else {
3700 		if (argc > 2) {
3701 			(void) fprintf(stderr, gettext("too many arguments\n"));
3702 			usage(B_FALSE);
3703 		}
3704 	}
3705 
3706 	/*
3707 	 * Check for the effective uid.  We do this explicitly here because
3708 	 * otherwise any attempt to discover pools will silently fail.
3709 	 */
3710 	if (argc == 0 && geteuid() != 0) {
3711 		(void) fprintf(stderr, gettext("cannot "
3712 		    "discover pools: permission denied\n"));
3713 
3714 		free(searchdirs);
3715 		nvlist_free(props);
3716 		nvlist_free(policy);
3717 		return (1);
3718 	}
3719 
3720 	/*
3721 	 * Depending on the arguments given, we do one of the following:
3722 	 *
3723 	 *	<none>	Iterate through all pools and display information about
3724 	 *		each one.
3725 	 *
3726 	 *	-a	Iterate through all pools and try to import each one.
3727 	 *
3728 	 *	<id>	Find the pool that corresponds to the given GUID/pool
3729 	 *		name and import that one.
3730 	 *
3731 	 *	-D	Above options applies only to destroyed pools.
3732 	 */
3733 	if (argc != 0) {
3734 		char *endptr;
3735 
3736 		errno = 0;
3737 		searchguid = strtoull(argv[0], &endptr, 10);
3738 		if (errno != 0 || *endptr != '\0') {
3739 			searchname = argv[0];
3740 			searchguid = 0;
3741 		}
3742 		pool_specified = B_TRUE;
3743 
3744 		/*
3745 		 * User specified a name or guid.  Ensure it's unique.
3746 		 */
3747 		target_exists_args_t search = {searchname, searchguid};
3748 		pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
3749 	}
3750 
3751 	/*
3752 	 * Check the environment for the preferred search path.
3753 	 */
3754 	if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
3755 		char *dir, *tmp = NULL;
3756 
3757 		envdup = strdup(env);
3758 
3759 		for (dir = strtok_r(envdup, ":", &tmp);
3760 		    dir != NULL;
3761 		    dir = strtok_r(NULL, ":", &tmp)) {
3762 			searchdirs = safe_realloc(searchdirs,
3763 			    (nsearch + 1) * sizeof (char *));
3764 			searchdirs[nsearch++] = dir;
3765 		}
3766 	}
3767 
3768 	idata.path = searchdirs;
3769 	idata.paths = nsearch;
3770 	idata.poolname = searchname;
3771 	idata.guid = searchguid;
3772 	idata.cachefile = cachefile;
3773 	idata.scan = do_scan;
3774 	idata.policy = policy;
3775 
3776 	pools = zpool_search_import(g_zfs, &idata, &libzfs_config_ops);
3777 
3778 	if (pools != NULL && pool_exists &&
3779 	    (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
3780 		(void) fprintf(stderr, gettext("cannot import '%s': "
3781 		    "a pool with that name already exists\n"),
3782 		    argv[0]);
3783 		(void) fprintf(stderr, gettext("use the form '%s "
3784 		    "<pool | id> <newpool>' to give it a new name\n"),
3785 		    "zpool import");
3786 		err = 1;
3787 	} else if (pools == NULL && pool_exists) {
3788 		(void) fprintf(stderr, gettext("cannot import '%s': "
3789 		    "a pool with that name is already created/imported,\n"),
3790 		    argv[0]);
3791 		(void) fprintf(stderr, gettext("and no additional pools "
3792 		    "with that name were found\n"));
3793 		err = 1;
3794 	} else if (pools == NULL) {
3795 		if (argc != 0) {
3796 			(void) fprintf(stderr, gettext("cannot import '%s': "
3797 			    "no such pool available\n"), argv[0]);
3798 		}
3799 		err = 1;
3800 	}
3801 
3802 	if (err == 1) {
3803 		free(searchdirs);
3804 		free(envdup);
3805 		nvlist_free(policy);
3806 		nvlist_free(pools);
3807 		nvlist_free(props);
3808 		return (1);
3809 	}
3810 
3811 	err = import_pools(pools, props, mntopts, flags,
3812 	    argc >= 1 ? argv[0] : NULL,
3813 	    argc >= 2 ? argv[1] : NULL,
3814 	    do_destroyed, pool_specified, do_all, &idata);
3815 
3816 	/*
3817 	 * If we're using the cachefile and we failed to import, then
3818 	 * fallback to scanning the directory for pools that match
3819 	 * those in the cachefile.
3820 	 */
3821 	if (err != 0 && cachefile != NULL) {
3822 		(void) printf(gettext("cachefile import failed, retrying\n"));
3823 
3824 		/*
3825 		 * We use the scan flag to gather the directories that exist
3826 		 * in the cachefile. If we need to fallback to searching for
3827 		 * the pool config, we will only search devices in these
3828 		 * directories.
3829 		 */
3830 		idata.scan = B_TRUE;
3831 		nvlist_free(pools);
3832 		pools = zpool_search_import(g_zfs, &idata, &libzfs_config_ops);
3833 
3834 		err = import_pools(pools, props, mntopts, flags,
3835 		    argc >= 1 ? argv[0] : NULL,
3836 		    argc >= 2 ? argv[1] : NULL,
3837 		    do_destroyed, pool_specified, do_all, &idata);
3838 	}
3839 
3840 error:
3841 	nvlist_free(props);
3842 	nvlist_free(pools);
3843 	nvlist_free(policy);
3844 	free(searchdirs);
3845 	free(envdup);
3846 
3847 	return (err ? 1 : 0);
3848 }
3849 
3850 /*
3851  * zpool sync [-f] [pool] ...
3852  *
3853  * -f (undocumented) force uberblock (and config including zpool cache file)
3854  *    update.
3855  *
3856  * Sync the specified pool(s).
3857  * Without arguments "zpool sync" will sync all pools.
3858  * This command initiates TXG sync(s) and will return after the TXG(s) commit.
3859  *
3860  */
3861 static int
3862 zpool_do_sync(int argc, char **argv)
3863 {
3864 	int ret;
3865 	boolean_t force = B_FALSE;
3866 
3867 	/* check options */
3868 	while ((ret  = getopt(argc, argv, "f")) != -1) {
3869 		switch (ret) {
3870 		case 'f':
3871 			force = B_TRUE;
3872 			break;
3873 		case '?':
3874 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3875 			    optopt);
3876 			usage(B_FALSE);
3877 		}
3878 	}
3879 
3880 	argc -= optind;
3881 	argv += optind;
3882 
3883 	/* if argc == 0 we will execute zpool_sync_one on all pools */
3884 	ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
3885 	    B_FALSE, zpool_sync_one, &force);
3886 
3887 	return (ret);
3888 }
3889 
3890 typedef struct iostat_cbdata {
3891 	uint64_t cb_flags;
3892 	int cb_namewidth;
3893 	int cb_iteration;
3894 	boolean_t cb_verbose;
3895 	boolean_t cb_literal;
3896 	boolean_t cb_scripted;
3897 	zpool_list_t *cb_list;
3898 	vdev_cmd_data_list_t *vcdl;
3899 	vdev_cbdata_t cb_vdevs;
3900 } iostat_cbdata_t;
3901 
3902 /*  iostat labels */
3903 typedef struct name_and_columns {
3904 	const char *name;	/* Column name */
3905 	unsigned int columns;	/* Center name to this number of columns */
3906 } name_and_columns_t;
3907 
3908 #define	IOSTAT_MAX_LABELS	15	/* Max number of labels on one line */
3909 
3910 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
3911 {
3912 	[IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
3913 	    {NULL}},
3914 	[IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
3915 	    {"asyncq_wait", 2}, {"scrub", 1}, {"trim", 1}, {"rebuild", 1},
3916 	    {NULL}},
3917 	[IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
3918 	    {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
3919 	    {"trimq_write", 2}, {"rebuildq_write", 2}, {NULL}},
3920 	[IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
3921 	    {"asyncq_wait", 2}, {NULL}},
3922 	[IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
3923 	    {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
3924 	    {"trim", 2}, {"rebuild", 2}, {NULL}},
3925 };
3926 
3927 /* Shorthand - if "columns" field not set, default to 1 column */
3928 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
3929 {
3930 	[IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
3931 	    {"write"}, {NULL}},
3932 	[IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
3933 	    {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {"wait"},
3934 	    {NULL}},
3935 	[IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
3936 	    {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
3937 	    {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
3938 	[IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
3939 	    {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {"rebuild"},
3940 	    {NULL}},
3941 	[IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
3942 	    {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
3943 	    {"ind"}, {"agg"}, {NULL}},
3944 };
3945 
3946 static const char *histo_to_title[] = {
3947 	[IOS_L_HISTO] = "latency",
3948 	[IOS_RQ_HISTO] = "req_size",
3949 };
3950 
3951 /*
3952  * Return the number of labels in a null-terminated name_and_columns_t
3953  * array.
3954  *
3955  */
3956 static unsigned int
3957 label_array_len(const name_and_columns_t *labels)
3958 {
3959 	int i = 0;
3960 
3961 	while (labels[i].name)
3962 		i++;
3963 
3964 	return (i);
3965 }
3966 
3967 /*
3968  * Return the number of strings in a null-terminated string array.
3969  * For example:
3970  *
3971  *     const char foo[] = {"bar", "baz", NULL}
3972  *
3973  * returns 2
3974  */
3975 static uint64_t
3976 str_array_len(const char *array[])
3977 {
3978 	uint64_t i = 0;
3979 	while (array[i])
3980 		i++;
3981 
3982 	return (i);
3983 }
3984 
3985 
3986 /*
3987  * Return a default column width for default/latency/queue columns. This does
3988  * not include histograms, which have their columns autosized.
3989  */
3990 static unsigned int
3991 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
3992 {
3993 	unsigned long column_width = 5; /* Normal niceprint */
3994 	static unsigned long widths[] = {
3995 		/*
3996 		 * Choose some sane default column sizes for printing the
3997 		 * raw numbers.
3998 		 */
3999 		[IOS_DEFAULT] = 15, /* 1PB capacity */
4000 		[IOS_LATENCY] = 10, /* 1B ns = 10sec */
4001 		[IOS_QUEUES] = 6,   /* 1M queue entries */
4002 		[IOS_L_HISTO] = 10, /* 1B ns = 10sec */
4003 		[IOS_RQ_HISTO] = 6, /* 1M queue entries */
4004 	};
4005 
4006 	if (cb->cb_literal)
4007 		column_width = widths[type];
4008 
4009 	return (column_width);
4010 }
4011 
4012 /*
4013  * Print the column labels, i.e:
4014  *
4015  *   capacity     operations     bandwidth
4016  * alloc   free   read  write   read  write  ...
4017  *
4018  * If force_column_width is set, use it for the column width.  If not set, use
4019  * the default column width.
4020  */
4021 static void
4022 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
4023     const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
4024 {
4025 	int i, idx, s;
4026 	int text_start, rw_column_width, spaces_to_end;
4027 	uint64_t flags = cb->cb_flags;
4028 	uint64_t f;
4029 	unsigned int column_width = force_column_width;
4030 
4031 	/* For each bit set in flags */
4032 	for (f = flags; f; f &= ~(1ULL << idx)) {
4033 		idx = lowbit64(f) - 1;
4034 		if (!force_column_width)
4035 			column_width = default_column_width(cb, idx);
4036 		/* Print our top labels centered over "read  write" label. */
4037 		for (i = 0; i < label_array_len(labels[idx]); i++) {
4038 			const char *name = labels[idx][i].name;
4039 			/*
4040 			 * We treat labels[][].columns == 0 as shorthand
4041 			 * for one column.  It makes writing out the label
4042 			 * tables more concise.
4043 			 */
4044 			unsigned int columns = MAX(1, labels[idx][i].columns);
4045 			unsigned int slen = strlen(name);
4046 
4047 			rw_column_width = (column_width * columns) +
4048 			    (2 * (columns - 1));
4049 
4050 			text_start = (int)((rw_column_width) / columns -
4051 			    slen / columns);
4052 			if (text_start < 0)
4053 				text_start = 0;
4054 
4055 			printf("  ");	/* Two spaces between columns */
4056 
4057 			/* Space from beginning of column to label */
4058 			for (s = 0; s < text_start; s++)
4059 				printf(" ");
4060 
4061 			printf("%s", name);
4062 
4063 			/* Print space after label to end of column */
4064 			spaces_to_end = rw_column_width - text_start - slen;
4065 			if (spaces_to_end < 0)
4066 				spaces_to_end = 0;
4067 
4068 			for (s = 0; s < spaces_to_end; s++)
4069 				printf(" ");
4070 		}
4071 	}
4072 }
4073 
4074 
4075 /*
4076  * print_cmd_columns - Print custom column titles from -c
4077  *
4078  * If the user specified the "zpool status|iostat -c" then print their custom
4079  * column titles in the header.  For example, print_cmd_columns() would print
4080  * the "  col1  col2" part of this:
4081  *
4082  * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
4083  * ...
4084  *	      capacity     operations     bandwidth
4085  * pool        alloc   free   read  write   read  write  col1  col2
4086  * ----------  -----  -----  -----  -----  -----  -----  ----  ----
4087  * mypool       269K  1008M      0      0    107    946
4088  *   mirror     269K  1008M      0      0    107    946
4089  *     sdb         -      -      0      0    102    473  val1  val2
4090  *     sdc         -      -      0      0      5    473  val1  val2
4091  * ----------  -----  -----  -----  -----  -----  -----  ----  ----
4092  */
4093 static void
4094 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
4095 {
4096 	int i, j;
4097 	vdev_cmd_data_t *data = &vcdl->data[0];
4098 
4099 	if (vcdl->count == 0 || data == NULL)
4100 		return;
4101 
4102 	/*
4103 	 * Each vdev cmd should have the same column names unless the user did
4104 	 * something weird with their cmd.  Just take the column names from the
4105 	 * first vdev and assume it works for all of them.
4106 	 */
4107 	for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
4108 		printf("  ");
4109 		if (use_dashes) {
4110 			for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
4111 				printf("-");
4112 		} else {
4113 			printf_color(ANSI_BOLD, "%*s", vcdl->uniq_cols_width[i],
4114 			    vcdl->uniq_cols[i]);
4115 		}
4116 	}
4117 }
4118 
4119 
4120 /*
4121  * Utility function to print out a line of dashes like:
4122  *
4123  * 	--------------------------------  -----  -----  -----  -----  -----
4124  *
4125  * ...or a dashed named-row line like:
4126  *
4127  * 	logs                                  -      -      -      -      -
4128  *
4129  * @cb:				iostat data
4130  *
4131  * @force_column_width		If non-zero, use the value as the column width.
4132  * 				Otherwise use the default column widths.
4133  *
4134  * @name:			Print a dashed named-row line starting
4135  * 				with @name.  Otherwise, print a regular
4136  * 				dashed line.
4137  */
4138 static void
4139 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
4140     const char *name)
4141 {
4142 	int i;
4143 	unsigned int namewidth;
4144 	uint64_t flags = cb->cb_flags;
4145 	uint64_t f;
4146 	int idx;
4147 	const name_and_columns_t *labels;
4148 	const char *title;
4149 
4150 
4151 	if (cb->cb_flags & IOS_ANYHISTO_M) {
4152 		title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4153 	} else if (cb->cb_vdevs.cb_names_count) {
4154 		title = "vdev";
4155 	} else  {
4156 		title = "pool";
4157 	}
4158 
4159 	namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4160 	    name ? strlen(name) : 0);
4161 
4162 
4163 	if (name) {
4164 		printf("%-*s", namewidth, name);
4165 	} else {
4166 		for (i = 0; i < namewidth; i++)
4167 			(void) printf("-");
4168 	}
4169 
4170 	/* For each bit in flags */
4171 	for (f = flags; f; f &= ~(1ULL << idx)) {
4172 		unsigned int column_width;
4173 		idx = lowbit64(f) - 1;
4174 		if (force_column_width)
4175 			column_width = force_column_width;
4176 		else
4177 			column_width = default_column_width(cb, idx);
4178 
4179 		labels = iostat_bottom_labels[idx];
4180 		for (i = 0; i < label_array_len(labels); i++) {
4181 			if (name)
4182 				printf("  %*s-", column_width - 1, " ");
4183 			else
4184 				printf("  %.*s", column_width,
4185 				    "--------------------");
4186 		}
4187 	}
4188 }
4189 
4190 
4191 static void
4192 print_iostat_separator_impl(iostat_cbdata_t *cb,
4193     unsigned int force_column_width)
4194 {
4195 	print_iostat_dashes(cb, force_column_width, NULL);
4196 }
4197 
4198 static void
4199 print_iostat_separator(iostat_cbdata_t *cb)
4200 {
4201 	print_iostat_separator_impl(cb, 0);
4202 }
4203 
4204 static void
4205 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
4206     const char *histo_vdev_name)
4207 {
4208 	unsigned int namewidth;
4209 	const char *title;
4210 
4211 	if (cb->cb_flags & IOS_ANYHISTO_M) {
4212 		title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4213 	} else if (cb->cb_vdevs.cb_names_count) {
4214 		title = "vdev";
4215 	} else  {
4216 		title = "pool";
4217 	}
4218 
4219 	namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4220 	    histo_vdev_name ? strlen(histo_vdev_name) : 0);
4221 
4222 	if (histo_vdev_name)
4223 		printf("%-*s", namewidth, histo_vdev_name);
4224 	else
4225 		printf("%*s", namewidth, "");
4226 
4227 
4228 	print_iostat_labels(cb, force_column_width, iostat_top_labels);
4229 	printf("\n");
4230 
4231 	printf("%-*s", namewidth, title);
4232 
4233 	print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
4234 	if (cb->vcdl != NULL)
4235 		print_cmd_columns(cb->vcdl, 0);
4236 
4237 	printf("\n");
4238 
4239 	print_iostat_separator_impl(cb, force_column_width);
4240 
4241 	if (cb->vcdl != NULL)
4242 		print_cmd_columns(cb->vcdl, 1);
4243 
4244 	printf("\n");
4245 }
4246 
4247 static void
4248 print_iostat_header(iostat_cbdata_t *cb)
4249 {
4250 	print_iostat_header_impl(cb, 0, NULL);
4251 }
4252 
4253 
4254 /*
4255  * Display a single statistic.
4256  */
4257 static void
4258 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
4259     unsigned int column_size, boolean_t scripted)
4260 {
4261 	char buf[64];
4262 
4263 	zfs_nicenum_format(value, buf, sizeof (buf), format);
4264 
4265 	if (scripted)
4266 		printf("\t%s", buf);
4267 	else
4268 		printf("  %*s", column_size, buf);
4269 }
4270 
4271 /*
4272  * Calculate the default vdev stats
4273  *
4274  * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
4275  * stats into calcvs.
4276  */
4277 static void
4278 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
4279     vdev_stat_t *calcvs)
4280 {
4281 	int i;
4282 
4283 	memcpy(calcvs, newvs, sizeof (*calcvs));
4284 	for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
4285 		calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
4286 
4287 	for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
4288 		calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
4289 }
4290 
4291 /*
4292  * Internal representation of the extended iostats data.
4293  *
4294  * The extended iostat stats are exported in nvlists as either uint64_t arrays
4295  * or single uint64_t's.  We make both look like arrays to make them easier
4296  * to process.  In order to make single uint64_t's look like arrays, we set
4297  * __data to the stat data, and then set *data = &__data with count = 1.  Then,
4298  * we can just use *data and count.
4299  */
4300 struct stat_array {
4301 	uint64_t *data;
4302 	uint_t count;	/* Number of entries in data[] */
4303 	uint64_t __data; /* Only used when data is a single uint64_t */
4304 };
4305 
4306 static uint64_t
4307 stat_histo_max(struct stat_array *nva, unsigned int len)
4308 {
4309 	uint64_t max = 0;
4310 	int i;
4311 	for (i = 0; i < len; i++)
4312 		max = MAX(max, array64_max(nva[i].data, nva[i].count));
4313 
4314 	return (max);
4315 }
4316 
4317 /*
4318  * Helper function to lookup a uint64_t array or uint64_t value and store its
4319  * data as a stat_array.  If the nvpair is a single uint64_t value, then we make
4320  * it look like a one element array to make it easier to process.
4321  */
4322 static int
4323 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
4324     struct stat_array *nva)
4325 {
4326 	nvpair_t *tmp;
4327 	int ret;
4328 
4329 	verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
4330 	switch (nvpair_type(tmp)) {
4331 	case DATA_TYPE_UINT64_ARRAY:
4332 		ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
4333 		break;
4334 	case DATA_TYPE_UINT64:
4335 		ret = nvpair_value_uint64(tmp, &nva->__data);
4336 		nva->data = &nva->__data;
4337 		nva->count = 1;
4338 		break;
4339 	default:
4340 		/* Not a uint64_t */
4341 		ret = EINVAL;
4342 		break;
4343 	}
4344 
4345 	return (ret);
4346 }
4347 
4348 /*
4349  * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
4350  * subtract them, and return the results in a newly allocated stat_array.
4351  * You must free the returned array after you are done with it with
4352  * free_calc_stats().
4353  *
4354  * Additionally, you can set "oldnv" to NULL if you simply want the newnv
4355  * values.
4356  */
4357 static struct stat_array *
4358 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
4359     nvlist_t *newnv)
4360 {
4361 	nvlist_t *oldnvx = NULL, *newnvx;
4362 	struct stat_array *oldnva, *newnva, *calcnva;
4363 	int i, j;
4364 	unsigned int alloc_size = (sizeof (struct stat_array)) * len;
4365 
4366 	/* Extract our extended stats nvlist from the main list */
4367 	verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
4368 	    &newnvx) == 0);
4369 	if (oldnv) {
4370 		verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
4371 		    &oldnvx) == 0);
4372 	}
4373 
4374 	newnva = safe_malloc(alloc_size);
4375 	oldnva = safe_malloc(alloc_size);
4376 	calcnva = safe_malloc(alloc_size);
4377 
4378 	for (j = 0; j < len; j++) {
4379 		verify(nvpair64_to_stat_array(newnvx, names[j],
4380 		    &newnva[j]) == 0);
4381 		calcnva[j].count = newnva[j].count;
4382 		alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
4383 		calcnva[j].data = safe_malloc(alloc_size);
4384 		memcpy(calcnva[j].data, newnva[j].data, alloc_size);
4385 
4386 		if (oldnvx) {
4387 			verify(nvpair64_to_stat_array(oldnvx, names[j],
4388 			    &oldnva[j]) == 0);
4389 			for (i = 0; i < oldnva[j].count; i++)
4390 				calcnva[j].data[i] -= oldnva[j].data[i];
4391 		}
4392 	}
4393 	free(newnva);
4394 	free(oldnva);
4395 	return (calcnva);
4396 }
4397 
4398 static void
4399 free_calc_stats(struct stat_array *nva, unsigned int len)
4400 {
4401 	int i;
4402 	for (i = 0; i < len; i++)
4403 		free(nva[i].data);
4404 
4405 	free(nva);
4406 }
4407 
4408 static void
4409 print_iostat_histo(struct stat_array *nva, unsigned int len,
4410     iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
4411     double scale)
4412 {
4413 	int i, j;
4414 	char buf[6];
4415 	uint64_t val;
4416 	enum zfs_nicenum_format format;
4417 	unsigned int buckets;
4418 	unsigned int start_bucket;
4419 
4420 	if (cb->cb_literal)
4421 		format = ZFS_NICENUM_RAW;
4422 	else
4423 		format = ZFS_NICENUM_1024;
4424 
4425 	/* All these histos are the same size, so just use nva[0].count */
4426 	buckets = nva[0].count;
4427 
4428 	if (cb->cb_flags & IOS_RQ_HISTO_M) {
4429 		/* Start at 512 - req size should never be lower than this */
4430 		start_bucket = 9;
4431 	} else {
4432 		start_bucket = 0;
4433 	}
4434 
4435 	for (j = start_bucket; j < buckets; j++) {
4436 		/* Print histogram bucket label */
4437 		if (cb->cb_flags & IOS_L_HISTO_M) {
4438 			/* Ending range of this bucket */
4439 			val = (1UL << (j + 1)) - 1;
4440 			zfs_nicetime(val, buf, sizeof (buf));
4441 		} else {
4442 			/* Request size (starting range of bucket) */
4443 			val = (1UL << j);
4444 			zfs_nicenum(val, buf, sizeof (buf));
4445 		}
4446 
4447 		if (cb->cb_scripted)
4448 			printf("%llu", (u_longlong_t)val);
4449 		else
4450 			printf("%-*s", namewidth, buf);
4451 
4452 		/* Print the values on the line */
4453 		for (i = 0; i < len; i++) {
4454 			print_one_stat(nva[i].data[j] * scale, format,
4455 			    column_width, cb->cb_scripted);
4456 		}
4457 		printf("\n");
4458 	}
4459 }
4460 
4461 static void
4462 print_solid_separator(unsigned int length)
4463 {
4464 	while (length--)
4465 		printf("-");
4466 	printf("\n");
4467 }
4468 
4469 static void
4470 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
4471     nvlist_t *newnv, double scale, const char *name)
4472 {
4473 	unsigned int column_width;
4474 	unsigned int namewidth;
4475 	unsigned int entire_width;
4476 	enum iostat_type type;
4477 	struct stat_array *nva;
4478 	const char **names;
4479 	unsigned int names_len;
4480 
4481 	/* What type of histo are we? */
4482 	type = IOS_HISTO_IDX(cb->cb_flags);
4483 
4484 	/* Get NULL-terminated array of nvlist names for our histo */
4485 	names = vsx_type_to_nvlist[type];
4486 	names_len = str_array_len(names); /* num of names */
4487 
4488 	nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
4489 
4490 	if (cb->cb_literal) {
4491 		column_width = MAX(5,
4492 		    (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
4493 	} else {
4494 		column_width = 5;
4495 	}
4496 
4497 	namewidth = MAX(cb->cb_namewidth,
4498 	    strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
4499 
4500 	/*
4501 	 * Calculate the entire line width of what we're printing.  The
4502 	 * +2 is for the two spaces between columns:
4503 	 */
4504 	/*	 read  write				*/
4505 	/*	-----  -----				*/
4506 	/*	|___|  <---------- column_width		*/
4507 	/*						*/
4508 	/*	|__________|  <--- entire_width		*/
4509 	/*						*/
4510 	entire_width = namewidth + (column_width + 2) *
4511 	    label_array_len(iostat_bottom_labels[type]);
4512 
4513 	if (cb->cb_scripted)
4514 		printf("%s\n", name);
4515 	else
4516 		print_iostat_header_impl(cb, column_width, name);
4517 
4518 	print_iostat_histo(nva, names_len, cb, column_width,
4519 	    namewidth, scale);
4520 
4521 	free_calc_stats(nva, names_len);
4522 	if (!cb->cb_scripted)
4523 		print_solid_separator(entire_width);
4524 }
4525 
4526 /*
4527  * Calculate the average latency of a power-of-two latency histogram
4528  */
4529 static uint64_t
4530 single_histo_average(uint64_t *histo, unsigned int buckets)
4531 {
4532 	int i;
4533 	uint64_t count = 0, total = 0;
4534 
4535 	for (i = 0; i < buckets; i++) {
4536 		/*
4537 		 * Our buckets are power-of-two latency ranges.  Use the
4538 		 * midpoint latency of each bucket to calculate the average.
4539 		 * For example:
4540 		 *
4541 		 * Bucket          Midpoint
4542 		 * 8ns-15ns:       12ns
4543 		 * 16ns-31ns:      24ns
4544 		 * ...
4545 		 */
4546 		if (histo[i] != 0) {
4547 			total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
4548 			count += histo[i];
4549 		}
4550 	}
4551 
4552 	/* Prevent divide by zero */
4553 	return (count == 0 ? 0 : total / count);
4554 }
4555 
4556 static void
4557 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *newnv)
4558 {
4559 	const char *names[] = {
4560 		ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
4561 		ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
4562 		ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
4563 		ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
4564 		ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
4565 		ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
4566 		ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
4567 		ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
4568 		ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
4569 		ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
4570 		ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
4571 		ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
4572 		ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
4573 		ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
4574 	};
4575 
4576 	struct stat_array *nva;
4577 
4578 	unsigned int column_width = default_column_width(cb, IOS_QUEUES);
4579 	enum zfs_nicenum_format format;
4580 
4581 	nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
4582 
4583 	if (cb->cb_literal)
4584 		format = ZFS_NICENUM_RAW;
4585 	else
4586 		format = ZFS_NICENUM_1024;
4587 
4588 	for (int i = 0; i < ARRAY_SIZE(names); i++) {
4589 		uint64_t val = nva[i].data[0];
4590 		print_one_stat(val, format, column_width, cb->cb_scripted);
4591 	}
4592 
4593 	free_calc_stats(nva, ARRAY_SIZE(names));
4594 }
4595 
4596 static void
4597 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
4598     nvlist_t *newnv)
4599 {
4600 	int i;
4601 	uint64_t val;
4602 	const char *names[] = {
4603 		ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
4604 		ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
4605 		ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
4606 		ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
4607 		ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
4608 		ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
4609 		ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
4610 		ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
4611 		ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
4612 		ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
4613 		ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
4614 	};
4615 	struct stat_array *nva;
4616 
4617 	unsigned int column_width = default_column_width(cb, IOS_LATENCY);
4618 	enum zfs_nicenum_format format;
4619 
4620 	nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
4621 
4622 	if (cb->cb_literal)
4623 		format = ZFS_NICENUM_RAWTIME;
4624 	else
4625 		format = ZFS_NICENUM_TIME;
4626 
4627 	/* Print our avg latencies on the line */
4628 	for (i = 0; i < ARRAY_SIZE(names); i++) {
4629 		/* Compute average latency for a latency histo */
4630 		val = single_histo_average(nva[i].data, nva[i].count);
4631 		print_one_stat(val, format, column_width, cb->cb_scripted);
4632 	}
4633 	free_calc_stats(nva, ARRAY_SIZE(names));
4634 }
4635 
4636 /*
4637  * Print default statistics (capacity/operations/bandwidth)
4638  */
4639 static void
4640 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
4641 {
4642 	unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
4643 	enum zfs_nicenum_format format;
4644 	char na;	/* char to print for "not applicable" values */
4645 
4646 	if (cb->cb_literal) {
4647 		format = ZFS_NICENUM_RAW;
4648 		na = '0';
4649 	} else {
4650 		format = ZFS_NICENUM_1024;
4651 		na = '-';
4652 	}
4653 
4654 	/* only toplevel vdevs have capacity stats */
4655 	if (vs->vs_space == 0) {
4656 		if (cb->cb_scripted)
4657 			printf("\t%c\t%c", na, na);
4658 		else
4659 			printf("  %*c  %*c", column_width, na, column_width,
4660 			    na);
4661 	} else {
4662 		print_one_stat(vs->vs_alloc, format, column_width,
4663 		    cb->cb_scripted);
4664 		print_one_stat(vs->vs_space - vs->vs_alloc, format,
4665 		    column_width, cb->cb_scripted);
4666 	}
4667 
4668 	print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
4669 	    format, column_width, cb->cb_scripted);
4670 	print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
4671 	    format, column_width, cb->cb_scripted);
4672 	print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
4673 	    format, column_width, cb->cb_scripted);
4674 	print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
4675 	    format, column_width, cb->cb_scripted);
4676 }
4677 
4678 static const char *const class_name[] = {
4679 	VDEV_ALLOC_BIAS_DEDUP,
4680 	VDEV_ALLOC_BIAS_SPECIAL,
4681 	VDEV_ALLOC_CLASS_LOGS
4682 };
4683 
4684 /*
4685  * Print out all the statistics for the given vdev.  This can either be the
4686  * toplevel configuration, or called recursively.  If 'name' is NULL, then this
4687  * is a verbose output, and we don't want to display the toplevel pool stats.
4688  *
4689  * Returns the number of stat lines printed.
4690  */
4691 static unsigned int
4692 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
4693     nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
4694 {
4695 	nvlist_t **oldchild, **newchild;
4696 	uint_t c, children, oldchildren;
4697 	vdev_stat_t *oldvs, *newvs, *calcvs;
4698 	vdev_stat_t zerovs = { 0 };
4699 	char *vname;
4700 	int i;
4701 	int ret = 0;
4702 	uint64_t tdelta;
4703 	double scale;
4704 
4705 	if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
4706 		return (ret);
4707 
4708 	calcvs = safe_malloc(sizeof (*calcvs));
4709 
4710 	if (oldnv != NULL) {
4711 		verify(nvlist_lookup_uint64_array(oldnv,
4712 		    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
4713 	} else {
4714 		oldvs = &zerovs;
4715 	}
4716 
4717 	/* Do we only want to see a specific vdev? */
4718 	for (i = 0; i < cb->cb_vdevs.cb_names_count; i++) {
4719 		/* Yes we do.  Is this the vdev? */
4720 		if (strcmp(name, cb->cb_vdevs.cb_names[i]) == 0) {
4721 			/*
4722 			 * This is our vdev.  Since it is the only vdev we
4723 			 * will be displaying, make depth = 0 so that it
4724 			 * doesn't get indented.
4725 			 */
4726 			depth = 0;
4727 			break;
4728 		}
4729 	}
4730 
4731 	if (cb->cb_vdevs.cb_names_count && (i == cb->cb_vdevs.cb_names_count)) {
4732 		/* Couldn't match the name */
4733 		goto children;
4734 	}
4735 
4736 
4737 	verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
4738 	    (uint64_t **)&newvs, &c) == 0);
4739 
4740 	/*
4741 	 * Print the vdev name unless it's is a histogram.  Histograms
4742 	 * display the vdev name in the header itself.
4743 	 */
4744 	if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
4745 		if (cb->cb_scripted) {
4746 			printf("%s", name);
4747 		} else {
4748 			if (strlen(name) + depth > cb->cb_namewidth)
4749 				(void) printf("%*s%s", depth, "", name);
4750 			else
4751 				(void) printf("%*s%s%*s", depth, "", name,
4752 				    (int)(cb->cb_namewidth - strlen(name) -
4753 				    depth), "");
4754 		}
4755 	}
4756 
4757 	/* Calculate our scaling factor */
4758 	tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
4759 	if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
4760 		/*
4761 		 * If we specify printing histograms with no time interval, then
4762 		 * print the histogram numbers over the entire lifetime of the
4763 		 * vdev.
4764 		 */
4765 		scale = 1;
4766 	} else {
4767 		if (tdelta == 0)
4768 			scale = 1.0;
4769 		else
4770 			scale = (double)NANOSEC / tdelta;
4771 	}
4772 
4773 	if (cb->cb_flags & IOS_DEFAULT_M) {
4774 		calc_default_iostats(oldvs, newvs, calcvs);
4775 		print_iostat_default(calcvs, cb, scale);
4776 	}
4777 	if (cb->cb_flags & IOS_LATENCY_M)
4778 		print_iostat_latency(cb, oldnv, newnv);
4779 	if (cb->cb_flags & IOS_QUEUES_M)
4780 		print_iostat_queues(cb, newnv);
4781 	if (cb->cb_flags & IOS_ANYHISTO_M) {
4782 		printf("\n");
4783 		print_iostat_histos(cb, oldnv, newnv, scale, name);
4784 	}
4785 
4786 	if (cb->vcdl != NULL) {
4787 		char *path;
4788 		if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
4789 		    &path) == 0) {
4790 			printf("  ");
4791 			zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
4792 		}
4793 	}
4794 
4795 	if (!(cb->cb_flags & IOS_ANYHISTO_M))
4796 		printf("\n");
4797 
4798 	ret++;
4799 
4800 children:
4801 
4802 	free(calcvs);
4803 
4804 	if (!cb->cb_verbose)
4805 		return (ret);
4806 
4807 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
4808 	    &newchild, &children) != 0)
4809 		return (ret);
4810 
4811 	if (oldnv) {
4812 		if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
4813 		    &oldchild, &oldchildren) != 0)
4814 			return (ret);
4815 
4816 		children = MIN(oldchildren, children);
4817 	}
4818 
4819 	/*
4820 	 * print normal top-level devices
4821 	 */
4822 	for (c = 0; c < children; c++) {
4823 		uint64_t ishole = B_FALSE, islog = B_FALSE;
4824 
4825 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
4826 		    &ishole);
4827 
4828 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
4829 		    &islog);
4830 
4831 		if (ishole || islog)
4832 			continue;
4833 
4834 		if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
4835 			continue;
4836 
4837 		vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4838 		    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
4839 		ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
4840 		    newchild[c], cb, depth + 2);
4841 		free(vname);
4842 	}
4843 
4844 	/*
4845 	 * print all other top-level devices
4846 	 */
4847 	for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
4848 		boolean_t printed = B_FALSE;
4849 
4850 		for (c = 0; c < children; c++) {
4851 			uint64_t islog = B_FALSE;
4852 			char *bias = NULL;
4853 			char *type = NULL;
4854 
4855 			(void) nvlist_lookup_uint64(newchild[c],
4856 			    ZPOOL_CONFIG_IS_LOG, &islog);
4857 			if (islog) {
4858 				bias = (char *)VDEV_ALLOC_CLASS_LOGS;
4859 			} else {
4860 				(void) nvlist_lookup_string(newchild[c],
4861 				    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
4862 				(void) nvlist_lookup_string(newchild[c],
4863 				    ZPOOL_CONFIG_TYPE, &type);
4864 			}
4865 			if (bias == NULL || strcmp(bias, class_name[n]) != 0)
4866 				continue;
4867 			if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
4868 				continue;
4869 
4870 			if (!printed) {
4871 				if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
4872 				    !cb->cb_scripted &&
4873 				    !cb->cb_vdevs.cb_names) {
4874 					print_iostat_dashes(cb, 0,
4875 					    class_name[n]);
4876 				}
4877 				printf("\n");
4878 				printed = B_TRUE;
4879 			}
4880 
4881 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4882 			    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
4883 			ret += print_vdev_stats(zhp, vname, oldnv ?
4884 			    oldchild[c] : NULL, newchild[c], cb, depth + 2);
4885 			free(vname);
4886 		}
4887 	}
4888 
4889 	/*
4890 	 * Include level 2 ARC devices in iostat output
4891 	 */
4892 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
4893 	    &newchild, &children) != 0)
4894 		return (ret);
4895 
4896 	if (oldnv) {
4897 		if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
4898 		    &oldchild, &oldchildren) != 0)
4899 			return (ret);
4900 
4901 		children = MIN(oldchildren, children);
4902 	}
4903 
4904 	if (children > 0) {
4905 		if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
4906 		    !cb->cb_vdevs.cb_names) {
4907 			print_iostat_dashes(cb, 0, "cache");
4908 		}
4909 		printf("\n");
4910 
4911 		for (c = 0; c < children; c++) {
4912 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4913 			    cb->cb_vdevs.cb_name_flags);
4914 			ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
4915 			    : NULL, newchild[c], cb, depth + 2);
4916 			free(vname);
4917 		}
4918 	}
4919 
4920 	return (ret);
4921 }
4922 
4923 static int
4924 refresh_iostat(zpool_handle_t *zhp, void *data)
4925 {
4926 	iostat_cbdata_t *cb = data;
4927 	boolean_t missing;
4928 
4929 	/*
4930 	 * If the pool has disappeared, remove it from the list and continue.
4931 	 */
4932 	if (zpool_refresh_stats(zhp, &missing) != 0)
4933 		return (-1);
4934 
4935 	if (missing)
4936 		pool_list_remove(cb->cb_list, zhp);
4937 
4938 	return (0);
4939 }
4940 
4941 /*
4942  * Callback to print out the iostats for the given pool.
4943  */
4944 static int
4945 print_iostat(zpool_handle_t *zhp, void *data)
4946 {
4947 	iostat_cbdata_t *cb = data;
4948 	nvlist_t *oldconfig, *newconfig;
4949 	nvlist_t *oldnvroot, *newnvroot;
4950 	int ret;
4951 
4952 	newconfig = zpool_get_config(zhp, &oldconfig);
4953 
4954 	if (cb->cb_iteration == 1)
4955 		oldconfig = NULL;
4956 
4957 	verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
4958 	    &newnvroot) == 0);
4959 
4960 	if (oldconfig == NULL)
4961 		oldnvroot = NULL;
4962 	else
4963 		verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
4964 		    &oldnvroot) == 0);
4965 
4966 	ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
4967 	    cb, 0);
4968 	if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
4969 	    !cb->cb_scripted && cb->cb_verbose &&
4970 	    !cb->cb_vdevs.cb_names_count) {
4971 		print_iostat_separator(cb);
4972 		if (cb->vcdl != NULL) {
4973 			print_cmd_columns(cb->vcdl, 1);
4974 		}
4975 		printf("\n");
4976 	}
4977 
4978 	return (ret);
4979 }
4980 
4981 static int
4982 get_columns(void)
4983 {
4984 	struct winsize ws;
4985 	int columns = 80;
4986 	int error;
4987 
4988 	if (isatty(STDOUT_FILENO)) {
4989 		error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
4990 		if (error == 0)
4991 			columns = ws.ws_col;
4992 	} else {
4993 		columns = 999;
4994 	}
4995 
4996 	return (columns);
4997 }
4998 
4999 /*
5000  * Return the required length of the pool/vdev name column.  The minimum
5001  * allowed width and output formatting flags must be provided.
5002  */
5003 static int
5004 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
5005 {
5006 	nvlist_t *config, *nvroot;
5007 	int width = min_width;
5008 
5009 	if ((config = zpool_get_config(zhp, NULL)) != NULL) {
5010 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5011 		    &nvroot) == 0);
5012 		size_t poolname_len = strlen(zpool_get_name(zhp));
5013 		if (verbose == B_FALSE) {
5014 			width = MAX(poolname_len, min_width);
5015 		} else {
5016 			width = MAX(poolname_len,
5017 			    max_width(zhp, nvroot, 0, min_width, flags));
5018 		}
5019 	}
5020 
5021 	return (width);
5022 }
5023 
5024 /*
5025  * Parse the input string, get the 'interval' and 'count' value if there is one.
5026  */
5027 static void
5028 get_interval_count(int *argcp, char **argv, float *iv,
5029     unsigned long *cnt)
5030 {
5031 	float interval = 0;
5032 	unsigned long count = 0;
5033 	int argc = *argcp;
5034 
5035 	/*
5036 	 * Determine if the last argument is an integer or a pool name
5037 	 */
5038 	if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5039 		char *end;
5040 
5041 		errno = 0;
5042 		interval = strtof(argv[argc - 1], &end);
5043 
5044 		if (*end == '\0' && errno == 0) {
5045 			if (interval == 0) {
5046 				(void) fprintf(stderr, gettext(
5047 				    "interval cannot be zero\n"));
5048 				usage(B_FALSE);
5049 			}
5050 			/*
5051 			 * Ignore the last parameter
5052 			 */
5053 			argc--;
5054 		} else {
5055 			/*
5056 			 * If this is not a valid number, just plow on.  The
5057 			 * user will get a more informative error message later
5058 			 * on.
5059 			 */
5060 			interval = 0;
5061 		}
5062 	}
5063 
5064 	/*
5065 	 * If the last argument is also an integer, then we have both a count
5066 	 * and an interval.
5067 	 */
5068 	if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5069 		char *end;
5070 
5071 		errno = 0;
5072 		count = interval;
5073 		interval = strtof(argv[argc - 1], &end);
5074 
5075 		if (*end == '\0' && errno == 0) {
5076 			if (interval == 0) {
5077 				(void) fprintf(stderr, gettext(
5078 				    "interval cannot be zero\n"));
5079 				usage(B_FALSE);
5080 			}
5081 
5082 			/*
5083 			 * Ignore the last parameter
5084 			 */
5085 			argc--;
5086 		} else {
5087 			interval = 0;
5088 		}
5089 	}
5090 
5091 	*iv = interval;
5092 	*cnt = count;
5093 	*argcp = argc;
5094 }
5095 
5096 static void
5097 get_timestamp_arg(char c)
5098 {
5099 	if (c == 'u')
5100 		timestamp_fmt = UDATE;
5101 	else if (c == 'd')
5102 		timestamp_fmt = DDATE;
5103 	else
5104 		usage(B_FALSE);
5105 }
5106 
5107 /*
5108  * Return stat flags that are supported by all pools by both the module and
5109  * zpool iostat.  "*data" should be initialized to all 0xFFs before running.
5110  * It will get ANDed down until only the flags that are supported on all pools
5111  * remain.
5112  */
5113 static int
5114 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
5115 {
5116 	uint64_t *mask = data;
5117 	nvlist_t *config, *nvroot, *nvx;
5118 	uint64_t flags = 0;
5119 	int i, j;
5120 
5121 	config = zpool_get_config(zhp, NULL);
5122 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5123 	    &nvroot) == 0);
5124 
5125 	/* Default stats are always supported, but for completeness.. */
5126 	if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
5127 		flags |= IOS_DEFAULT_M;
5128 
5129 	/* Get our extended stats nvlist from the main list */
5130 	if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
5131 	    &nvx) != 0) {
5132 		/*
5133 		 * No extended stats; they're probably running an older
5134 		 * module.  No big deal, we support that too.
5135 		 */
5136 		goto end;
5137 	}
5138 
5139 	/* For each extended stat, make sure all its nvpairs are supported */
5140 	for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
5141 		if (!vsx_type_to_nvlist[j][0])
5142 			continue;
5143 
5144 		/* Start off by assuming the flag is supported, then check */
5145 		flags |= (1ULL << j);
5146 		for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
5147 			if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
5148 				/* flag isn't supported */
5149 				flags = flags & ~(1ULL  << j);
5150 				break;
5151 			}
5152 		}
5153 	}
5154 end:
5155 	*mask = *mask & flags;
5156 	return (0);
5157 }
5158 
5159 /*
5160  * Return a bitmask of stats that are supported on all pools by both the module
5161  * and zpool iostat.
5162  */
5163 static uint64_t
5164 get_stat_flags(zpool_list_t *list)
5165 {
5166 	uint64_t mask = -1;
5167 
5168 	/*
5169 	 * get_stat_flags_cb() will lop off bits from "mask" until only the
5170 	 * flags that are supported on all pools remain.
5171 	 */
5172 	pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
5173 	return (mask);
5174 }
5175 
5176 /*
5177  * Return 1 if cb_data->cb_names[0] is this vdev's name, 0 otherwise.
5178  */
5179 static int
5180 is_vdev_cb(void *zhp_data, nvlist_t *nv, void *cb_data)
5181 {
5182 	vdev_cbdata_t *cb = cb_data;
5183 	char *name = NULL;
5184 	int ret = 1; /* assume match */
5185 	zpool_handle_t *zhp = zhp_data;
5186 
5187 	name = zpool_vdev_name(g_zfs, zhp, nv, cb->cb_name_flags);
5188 
5189 	if (strcmp(name, cb->cb_names[0])) {
5190 		free(name);
5191 		name = zpool_vdev_name(g_zfs, zhp, nv, VDEV_NAME_GUID);
5192 		ret = (strcmp(name, cb->cb_names[0]) == 0);
5193 	}
5194 	free(name);
5195 
5196 	return (ret);
5197 }
5198 
5199 /*
5200  * Returns 1 if cb_data->cb_names[0] is a vdev name, 0 otherwise.
5201  */
5202 static int
5203 is_vdev(zpool_handle_t *zhp, void *cb_data)
5204 {
5205 	return (for_each_vdev(zhp, is_vdev_cb, cb_data));
5206 }
5207 
5208 /*
5209  * Check if vdevs are in a pool
5210  *
5211  * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
5212  * return 0.  If pool_name is NULL, then search all pools.
5213  */
5214 static int
5215 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
5216     vdev_cbdata_t *cb)
5217 {
5218 	char **tmp_name;
5219 	int ret = 0;
5220 	int i;
5221 	int pool_count = 0;
5222 
5223 	if ((argc == 0) || !*argv)
5224 		return (0);
5225 
5226 	if (pool_name)
5227 		pool_count = 1;
5228 
5229 	/* Temporarily hijack cb_names for a second... */
5230 	tmp_name = cb->cb_names;
5231 
5232 	/* Go though our list of prospective vdev names */
5233 	for (i = 0; i < argc; i++) {
5234 		cb->cb_names = argv + i;
5235 
5236 		/* Is this name a vdev in our pools? */
5237 		ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
5238 		    ZFS_TYPE_POOL, B_FALSE, is_vdev, cb);
5239 		if (!ret) {
5240 			/* No match */
5241 			break;
5242 		}
5243 	}
5244 
5245 	cb->cb_names = tmp_name;
5246 
5247 	return (ret);
5248 }
5249 
5250 static int
5251 is_pool_cb(zpool_handle_t *zhp, void *data)
5252 {
5253 	char *name = data;
5254 	if (strcmp(name, zpool_get_name(zhp)) == 0)
5255 		return (1);
5256 
5257 	return (0);
5258 }
5259 
5260 /*
5261  * Do we have a pool named *name?  If so, return 1, otherwise 0.
5262  */
5263 static int
5264 is_pool(char *name)
5265 {
5266 	return (for_each_pool(0, NULL, B_TRUE, NULL, ZFS_TYPE_POOL, B_FALSE,
5267 	    is_pool_cb, name));
5268 }
5269 
5270 /* Are all our argv[] strings pool names?  If so return 1, 0 otherwise. */
5271 static int
5272 are_all_pools(int argc, char **argv)
5273 {
5274 	if ((argc == 0) || !*argv)
5275 		return (0);
5276 
5277 	while (--argc >= 0)
5278 		if (!is_pool(argv[argc]))
5279 			return (0);
5280 
5281 	return (1);
5282 }
5283 
5284 /*
5285  * Helper function to print out vdev/pool names we can't resolve.  Used for an
5286  * error message.
5287  */
5288 static void
5289 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
5290     vdev_cbdata_t *cb)
5291 {
5292 	int i;
5293 	char *name;
5294 	char *str;
5295 	for (i = 0; i < argc; i++) {
5296 		name = argv[i];
5297 
5298 		if (is_pool(name))
5299 			str = gettext("pool");
5300 		else if (are_vdevs_in_pool(1, &name, pool_name, cb))
5301 			str = gettext("vdev in this pool");
5302 		else if (are_vdevs_in_pool(1, &name, NULL, cb))
5303 			str = gettext("vdev in another pool");
5304 		else
5305 			str = gettext("unknown");
5306 
5307 		fprintf(stderr, "\t%s (%s)\n", name, str);
5308 	}
5309 }
5310 
5311 /*
5312  * Same as get_interval_count(), but with additional checks to not misinterpret
5313  * guids as interval/count values.  Assumes VDEV_NAME_GUID is set in
5314  * cb.cb_vdevs.cb_name_flags.
5315  */
5316 static void
5317 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
5318     unsigned long *count, iostat_cbdata_t *cb)
5319 {
5320 	char **tmpargv = argv;
5321 	int argc_for_interval = 0;
5322 
5323 	/* Is the last arg an interval value?  Or a guid? */
5324 	if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL,
5325 	    &cb->cb_vdevs)) {
5326 		/*
5327 		 * The last arg is not a guid, so it's probably an
5328 		 * interval value.
5329 		 */
5330 		argc_for_interval++;
5331 
5332 		if (*argc >= 2 &&
5333 		    !are_vdevs_in_pool(1, &argv[*argc - 2], NULL,
5334 		    &cb->cb_vdevs)) {
5335 			/*
5336 			 * The 2nd to last arg is not a guid, so it's probably
5337 			 * an interval value.
5338 			 */
5339 			argc_for_interval++;
5340 		}
5341 	}
5342 
5343 	/* Point to our list of possible intervals */
5344 	tmpargv = &argv[*argc - argc_for_interval];
5345 
5346 	*argc = *argc - argc_for_interval;
5347 	get_interval_count(&argc_for_interval, tmpargv,
5348 	    interval, count);
5349 }
5350 
5351 /*
5352  * Floating point sleep().  Allows you to pass in a floating point value for
5353  * seconds.
5354  */
5355 static void
5356 fsleep(float sec)
5357 {
5358 	struct timespec req;
5359 	req.tv_sec = floor(sec);
5360 	req.tv_nsec = (sec - (float)req.tv_sec) * NANOSEC;
5361 	nanosleep(&req, NULL);
5362 }
5363 
5364 /*
5365  * Terminal height, in rows. Returns -1 if stdout is not connected to a TTY or
5366  * if we were unable to determine its size.
5367  */
5368 static int
5369 terminal_height(void)
5370 {
5371 	struct winsize win;
5372 
5373 	if (isatty(STDOUT_FILENO) == 0)
5374 		return (-1);
5375 
5376 	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_row > 0)
5377 		return (win.ws_row);
5378 
5379 	return (-1);
5380 }
5381 
5382 /*
5383  * Run one of the zpool status/iostat -c scripts with the help (-h) option and
5384  * print the result.
5385  *
5386  * name:	Short name of the script ('iostat').
5387  * path:	Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
5388  */
5389 static void
5390 print_zpool_script_help(char *name, char *path)
5391 {
5392 	char *argv[] = {path, (char *)"-h", NULL};
5393 	char **lines = NULL;
5394 	int lines_cnt = 0;
5395 	int rc;
5396 
5397 	rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
5398 	    &lines_cnt);
5399 	if (rc != 0 || lines == NULL || lines_cnt <= 0) {
5400 		if (lines != NULL)
5401 			libzfs_free_str_array(lines, lines_cnt);
5402 		return;
5403 	}
5404 
5405 	for (int i = 0; i < lines_cnt; i++)
5406 		if (!is_blank_str(lines[i]))
5407 			printf("  %-14s  %s\n", name, lines[i]);
5408 
5409 	libzfs_free_str_array(lines, lines_cnt);
5410 }
5411 
5412 /*
5413  * Go though the zpool status/iostat -c scripts in the user's path, run their
5414  * help option (-h), and print out the results.
5415  */
5416 static void
5417 print_zpool_dir_scripts(char *dirpath)
5418 {
5419 	DIR *dir;
5420 	struct dirent *ent;
5421 	char fullpath[MAXPATHLEN];
5422 	struct stat dir_stat;
5423 
5424 	if ((dir = opendir(dirpath)) != NULL) {
5425 		/* print all the files and directories within directory */
5426 		while ((ent = readdir(dir)) != NULL) {
5427 			sprintf(fullpath, "%s/%s", dirpath, ent->d_name);
5428 
5429 			/* Print the scripts */
5430 			if (stat(fullpath, &dir_stat) == 0)
5431 				if (dir_stat.st_mode & S_IXUSR &&
5432 				    S_ISREG(dir_stat.st_mode))
5433 					print_zpool_script_help(ent->d_name,
5434 					    fullpath);
5435 		}
5436 		closedir(dir);
5437 	}
5438 }
5439 
5440 /*
5441  * Print out help text for all zpool status/iostat -c scripts.
5442  */
5443 static void
5444 print_zpool_script_list(const char *subcommand)
5445 {
5446 	char *dir, *sp, *tmp;
5447 
5448 	printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
5449 
5450 	sp = zpool_get_cmd_search_path();
5451 	if (sp == NULL)
5452 		return;
5453 
5454 	for (dir = strtok_r(sp, ":", &tmp);
5455 	    dir != NULL;
5456 	    dir = strtok_r(NULL, ":", &tmp))
5457 		print_zpool_dir_scripts(dir);
5458 
5459 	free(sp);
5460 }
5461 
5462 /*
5463  * Set the minimum pool/vdev name column width.  The width must be at least 10,
5464  * but may be as large as the column width - 42 so it still fits on one line.
5465  * NOTE: 42 is the width of the default capacity/operations/bandwidth output
5466  */
5467 static int
5468 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
5469 {
5470 	iostat_cbdata_t *cb = data;
5471 	int width, available_width;
5472 
5473 	/*
5474 	 * get_namewidth() returns the maximum width of any name in that column
5475 	 * for any pool/vdev/device line that will be output.
5476 	 */
5477 	width = get_namewidth(zhp, cb->cb_namewidth,
5478 	    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
5479 
5480 	/*
5481 	 * The width we are calculating is the width of the header and also the
5482 	 * padding width for names that are less than maximum width.  The stats
5483 	 * take up 42 characters, so the width available for names is:
5484 	 */
5485 	available_width = get_columns() - 42;
5486 
5487 	/*
5488 	 * If the maximum width fits on a screen, then great!  Make everything
5489 	 * line up by justifying all lines to the same width.  If that max
5490 	 * width is larger than what's available, the name plus stats won't fit
5491 	 * on one line, and justifying to that width would cause every line to
5492 	 * wrap on the screen.  We only want lines with long names to wrap.
5493 	 * Limit the padding to what won't wrap.
5494 	 */
5495 	if (width > available_width)
5496 		width = available_width;
5497 
5498 	/*
5499 	 * And regardless of whatever the screen width is (get_columns can
5500 	 * return 0 if the width is not known or less than 42 for a narrow
5501 	 * terminal) have the width be a minimum of 10.
5502 	 */
5503 	if (width < 10)
5504 		width = 10;
5505 
5506 	/* Save the calculated width */
5507 	cb->cb_namewidth = width;
5508 
5509 	return (0);
5510 }
5511 
5512 /*
5513  * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
5514  *              [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
5515  *              [interval [count]]
5516  *
5517  *	-c CMD  For each vdev, run command CMD
5518  *	-g	Display guid for individual vdev name.
5519  *	-L	Follow links when resolving vdev path name.
5520  *	-P	Display full path for vdev name.
5521  *	-v	Display statistics for individual vdevs
5522  *	-h	Display help
5523  *	-p	Display values in parsable (exact) format.
5524  *	-H	Scripted mode.  Don't display headers, and separate properties
5525  *		by a single tab.
5526  *	-l	Display average latency
5527  *	-q	Display queue depths
5528  *	-w	Display latency histograms
5529  *	-r	Display request size histogram
5530  *	-T	Display a timestamp in date(1) or Unix format
5531  *	-n	Only print headers once
5532  *
5533  * This command can be tricky because we want to be able to deal with pool
5534  * creation/destruction as well as vdev configuration changes.  The bulk of this
5535  * processing is handled by the pool_list_* routines in zpool_iter.c.  We rely
5536  * on pool_list_update() to detect the addition of new pools.  Configuration
5537  * changes are all handled within libzfs.
5538  */
5539 int
5540 zpool_do_iostat(int argc, char **argv)
5541 {
5542 	int c;
5543 	int ret;
5544 	int npools;
5545 	float interval = 0;
5546 	unsigned long count = 0;
5547 	int winheight = 24;
5548 	zpool_list_t *list;
5549 	boolean_t verbose = B_FALSE;
5550 	boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
5551 	boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
5552 	boolean_t omit_since_boot = B_FALSE;
5553 	boolean_t guid = B_FALSE;
5554 	boolean_t follow_links = B_FALSE;
5555 	boolean_t full_name = B_FALSE;
5556 	boolean_t headers_once = B_FALSE;
5557 	iostat_cbdata_t cb = { 0 };
5558 	char *cmd = NULL;
5559 
5560 	/* Used for printing error message */
5561 	const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
5562 	    [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
5563 
5564 	uint64_t unsupported_flags;
5565 
5566 	/* check options */
5567 	while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwnH")) != -1) {
5568 		switch (c) {
5569 		case 'c':
5570 			if (cmd != NULL) {
5571 				fprintf(stderr,
5572 				    gettext("Can't set -c flag twice\n"));
5573 				exit(1);
5574 			}
5575 
5576 			if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
5577 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
5578 				fprintf(stderr, gettext(
5579 				    "Can't run -c, disabled by "
5580 				    "ZPOOL_SCRIPTS_ENABLED.\n"));
5581 				exit(1);
5582 			}
5583 
5584 			if ((getuid() <= 0 || geteuid() <= 0) &&
5585 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
5586 				fprintf(stderr, gettext(
5587 				    "Can't run -c with root privileges "
5588 				    "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
5589 				exit(1);
5590 			}
5591 			cmd = optarg;
5592 			verbose = B_TRUE;
5593 			break;
5594 		case 'g':
5595 			guid = B_TRUE;
5596 			break;
5597 		case 'L':
5598 			follow_links = B_TRUE;
5599 			break;
5600 		case 'P':
5601 			full_name = B_TRUE;
5602 			break;
5603 		case 'T':
5604 			get_timestamp_arg(*optarg);
5605 			break;
5606 		case 'v':
5607 			verbose = B_TRUE;
5608 			break;
5609 		case 'p':
5610 			parsable = B_TRUE;
5611 			break;
5612 		case 'l':
5613 			latency = B_TRUE;
5614 			break;
5615 		case 'q':
5616 			queues = B_TRUE;
5617 			break;
5618 		case 'H':
5619 			scripted = B_TRUE;
5620 			break;
5621 		case 'w':
5622 			l_histo = B_TRUE;
5623 			break;
5624 		case 'r':
5625 			rq_histo = B_TRUE;
5626 			break;
5627 		case 'y':
5628 			omit_since_boot = B_TRUE;
5629 			break;
5630 		case 'n':
5631 			headers_once = B_TRUE;
5632 			break;
5633 		case 'h':
5634 			usage(B_FALSE);
5635 			break;
5636 		case '?':
5637 			if (optopt == 'c') {
5638 				print_zpool_script_list("iostat");
5639 				exit(0);
5640 			} else {
5641 				fprintf(stderr,
5642 				    gettext("invalid option '%c'\n"), optopt);
5643 			}
5644 			usage(B_FALSE);
5645 		}
5646 	}
5647 
5648 	argc -= optind;
5649 	argv += optind;
5650 
5651 	cb.cb_literal = parsable;
5652 	cb.cb_scripted = scripted;
5653 
5654 	if (guid)
5655 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_GUID;
5656 	if (follow_links)
5657 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
5658 	if (full_name)
5659 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_PATH;
5660 	cb.cb_iteration = 0;
5661 	cb.cb_namewidth = 0;
5662 	cb.cb_verbose = verbose;
5663 
5664 	/* Get our interval and count values (if any) */
5665 	if (guid) {
5666 		get_interval_count_filter_guids(&argc, argv, &interval,
5667 		    &count, &cb);
5668 	} else {
5669 		get_interval_count(&argc, argv, &interval, &count);
5670 	}
5671 
5672 	if (argc == 0) {
5673 		/* No args, so just print the defaults. */
5674 	} else if (are_all_pools(argc, argv)) {
5675 		/* All the args are pool names */
5676 	} else if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
5677 		/* All the args are vdevs */
5678 		cb.cb_vdevs.cb_names = argv;
5679 		cb.cb_vdevs.cb_names_count = argc;
5680 		argc = 0; /* No pools to process */
5681 	} else if (are_all_pools(1, argv)) {
5682 		/* The first arg is a pool name */
5683 		if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
5684 		    &cb.cb_vdevs)) {
5685 			/* ...and the rest are vdev names */
5686 			cb.cb_vdevs.cb_names = argv + 1;
5687 			cb.cb_vdevs.cb_names_count = argc - 1;
5688 			argc = 1; /* One pool to process */
5689 		} else {
5690 			fprintf(stderr, gettext("Expected either a list of "));
5691 			fprintf(stderr, gettext("pools, or list of vdevs in"));
5692 			fprintf(stderr, " \"%s\", ", argv[0]);
5693 			fprintf(stderr, gettext("but got:\n"));
5694 			error_list_unresolved_vdevs(argc - 1, argv + 1,
5695 			    argv[0], &cb.cb_vdevs);
5696 			fprintf(stderr, "\n");
5697 			usage(B_FALSE);
5698 			return (1);
5699 		}
5700 	} else {
5701 		/*
5702 		 * The args don't make sense. The first arg isn't a pool name,
5703 		 * nor are all the args vdevs.
5704 		 */
5705 		fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
5706 		fprintf(stderr, "\n");
5707 		return (1);
5708 	}
5709 
5710 	if (cb.cb_vdevs.cb_names_count != 0) {
5711 		/*
5712 		 * If user specified vdevs, it implies verbose.
5713 		 */
5714 		cb.cb_verbose = B_TRUE;
5715 	}
5716 
5717 	/*
5718 	 * Construct the list of all interesting pools.
5719 	 */
5720 	ret = 0;
5721 	if ((list = pool_list_get(argc, argv, NULL, ZFS_TYPE_POOL, parsable,
5722 	    &ret)) == NULL)
5723 		return (1);
5724 
5725 	if (pool_list_count(list) == 0 && argc != 0) {
5726 		pool_list_free(list);
5727 		return (1);
5728 	}
5729 
5730 	if (pool_list_count(list) == 0 && interval == 0) {
5731 		pool_list_free(list);
5732 		(void) fprintf(stderr, gettext("no pools available\n"));
5733 		return (1);
5734 	}
5735 
5736 	if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
5737 		pool_list_free(list);
5738 		(void) fprintf(stderr,
5739 		    gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
5740 		usage(B_FALSE);
5741 		return (1);
5742 	}
5743 
5744 	if (l_histo && rq_histo) {
5745 		pool_list_free(list);
5746 		(void) fprintf(stderr,
5747 		    gettext("Only one of [-r|-w] can be passed at a time\n"));
5748 		usage(B_FALSE);
5749 		return (1);
5750 	}
5751 
5752 	/*
5753 	 * Enter the main iostat loop.
5754 	 */
5755 	cb.cb_list = list;
5756 
5757 	if (l_histo) {
5758 		/*
5759 		 * Histograms tables look out of place when you try to display
5760 		 * them with the other stats, so make a rule that you can only
5761 		 * print histograms by themselves.
5762 		 */
5763 		cb.cb_flags = IOS_L_HISTO_M;
5764 	} else if (rq_histo) {
5765 		cb.cb_flags = IOS_RQ_HISTO_M;
5766 	} else {
5767 		cb.cb_flags = IOS_DEFAULT_M;
5768 		if (latency)
5769 			cb.cb_flags |= IOS_LATENCY_M;
5770 		if (queues)
5771 			cb.cb_flags |= IOS_QUEUES_M;
5772 	}
5773 
5774 	/*
5775 	 * See if the module supports all the stats we want to display.
5776 	 */
5777 	unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
5778 	if (unsupported_flags) {
5779 		uint64_t f;
5780 		int idx;
5781 		fprintf(stderr,
5782 		    gettext("The loaded zfs module doesn't support:"));
5783 
5784 		/* for each bit set in unsupported_flags */
5785 		for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
5786 			idx = lowbit64(f) - 1;
5787 			fprintf(stderr, " -%c", flag_to_arg[idx]);
5788 		}
5789 
5790 		fprintf(stderr, ".  Try running a newer module.\n");
5791 		pool_list_free(list);
5792 
5793 		return (1);
5794 	}
5795 
5796 	for (;;) {
5797 		if ((npools = pool_list_count(list)) == 0)
5798 			(void) fprintf(stderr, gettext("no pools available\n"));
5799 		else {
5800 			/*
5801 			 * If this is the first iteration and -y was supplied
5802 			 * we skip any printing.
5803 			 */
5804 			boolean_t skip = (omit_since_boot &&
5805 			    cb.cb_iteration == 0);
5806 
5807 			/*
5808 			 * Refresh all statistics.  This is done as an
5809 			 * explicit step before calculating the maximum name
5810 			 * width, so that any * configuration changes are
5811 			 * properly accounted for.
5812 			 */
5813 			(void) pool_list_iter(list, B_FALSE, refresh_iostat,
5814 			    &cb);
5815 
5816 			/*
5817 			 * Iterate over all pools to determine the maximum width
5818 			 * for the pool / device name column across all pools.
5819 			 */
5820 			cb.cb_namewidth = 0;
5821 			(void) pool_list_iter(list, B_FALSE,
5822 			    get_namewidth_iostat, &cb);
5823 
5824 			if (timestamp_fmt != NODATE)
5825 				print_timestamp(timestamp_fmt);
5826 
5827 			if (cmd != NULL && cb.cb_verbose &&
5828 			    !(cb.cb_flags & IOS_ANYHISTO_M)) {
5829 				cb.vcdl = all_pools_for_each_vdev_run(argc,
5830 				    argv, cmd, g_zfs, cb.cb_vdevs.cb_names,
5831 				    cb.cb_vdevs.cb_names_count,
5832 				    cb.cb_vdevs.cb_name_flags);
5833 			} else {
5834 				cb.vcdl = NULL;
5835 			}
5836 
5837 
5838 			/*
5839 			 * Check terminal size so we can print headers
5840 			 * even when terminal window has its height
5841 			 * changed.
5842 			 */
5843 			winheight = terminal_height();
5844 			/*
5845 			 * Are we connected to TTY? If not, headers_once
5846 			 * should be true, to avoid breaking scripts.
5847 			 */
5848 			if (winheight < 0)
5849 				headers_once = B_TRUE;
5850 
5851 			/*
5852 			 * If it's the first time and we're not skipping it,
5853 			 * or either skip or verbose mode, print the header.
5854 			 *
5855 			 * The histogram code explicitly prints its header on
5856 			 * every vdev, so skip this for histograms.
5857 			 */
5858 			if (((++cb.cb_iteration == 1 && !skip) ||
5859 			    (skip != verbose) ||
5860 			    (!headers_once &&
5861 			    (cb.cb_iteration % winheight) == 0)) &&
5862 			    (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
5863 			    !cb.cb_scripted)
5864 				print_iostat_header(&cb);
5865 
5866 			if (skip) {
5867 				(void) fsleep(interval);
5868 				continue;
5869 			}
5870 
5871 			pool_list_iter(list, B_FALSE, print_iostat, &cb);
5872 
5873 			/*
5874 			 * If there's more than one pool, and we're not in
5875 			 * verbose mode (which prints a separator for us),
5876 			 * then print a separator.
5877 			 *
5878 			 * In addition, if we're printing specific vdevs then
5879 			 * we also want an ending separator.
5880 			 */
5881 			if (((npools > 1 && !verbose &&
5882 			    !(cb.cb_flags & IOS_ANYHISTO_M)) ||
5883 			    (!(cb.cb_flags & IOS_ANYHISTO_M) &&
5884 			    cb.cb_vdevs.cb_names_count)) &&
5885 			    !cb.cb_scripted) {
5886 				print_iostat_separator(&cb);
5887 				if (cb.vcdl != NULL)
5888 					print_cmd_columns(cb.vcdl, 1);
5889 				printf("\n");
5890 			}
5891 
5892 			if (cb.vcdl != NULL)
5893 				free_vdev_cmd_data_list(cb.vcdl);
5894 
5895 		}
5896 
5897 		/*
5898 		 * Flush the output so that redirection to a file isn't buffered
5899 		 * indefinitely.
5900 		 */
5901 		(void) fflush(stdout);
5902 
5903 		if (interval == 0)
5904 			break;
5905 
5906 		if (count != 0 && --count == 0)
5907 			break;
5908 
5909 		(void) fsleep(interval);
5910 	}
5911 
5912 	pool_list_free(list);
5913 
5914 	return (ret);
5915 }
5916 
5917 typedef struct list_cbdata {
5918 	boolean_t	cb_verbose;
5919 	int		cb_name_flags;
5920 	int		cb_namewidth;
5921 	boolean_t	cb_scripted;
5922 	zprop_list_t	*cb_proplist;
5923 	boolean_t	cb_literal;
5924 } list_cbdata_t;
5925 
5926 
5927 /*
5928  * Given a list of columns to display, output appropriate headers for each one.
5929  */
5930 static void
5931 print_header(list_cbdata_t *cb)
5932 {
5933 	zprop_list_t *pl = cb->cb_proplist;
5934 	char headerbuf[ZPOOL_MAXPROPLEN];
5935 	const char *header;
5936 	boolean_t first = B_TRUE;
5937 	boolean_t right_justify;
5938 	size_t width = 0;
5939 
5940 	for (; pl != NULL; pl = pl->pl_next) {
5941 		width = pl->pl_width;
5942 		if (first && cb->cb_verbose) {
5943 			/*
5944 			 * Reset the width to accommodate the verbose listing
5945 			 * of devices.
5946 			 */
5947 			width = cb->cb_namewidth;
5948 		}
5949 
5950 		if (!first)
5951 			(void) fputs("  ", stdout);
5952 		else
5953 			first = B_FALSE;
5954 
5955 		right_justify = B_FALSE;
5956 		if (pl->pl_prop != ZPROP_USERPROP) {
5957 			header = zpool_prop_column_name(pl->pl_prop);
5958 			right_justify = zpool_prop_align_right(pl->pl_prop);
5959 		} else {
5960 			int i;
5961 
5962 			for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
5963 				headerbuf[i] = toupper(pl->pl_user_prop[i]);
5964 			headerbuf[i] = '\0';
5965 			header = headerbuf;
5966 		}
5967 
5968 		if (pl->pl_next == NULL && !right_justify)
5969 			(void) fputs(header, stdout);
5970 		else if (right_justify)
5971 			(void) printf("%*s", (int)width, header);
5972 		else
5973 			(void) printf("%-*s", (int)width, header);
5974 	}
5975 
5976 	(void) fputc('\n', stdout);
5977 }
5978 
5979 /*
5980  * Given a pool and a list of properties, print out all the properties according
5981  * to the described layout. Used by zpool_do_list().
5982  */
5983 static void
5984 print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
5985 {
5986 	zprop_list_t *pl = cb->cb_proplist;
5987 	boolean_t first = B_TRUE;
5988 	char property[ZPOOL_MAXPROPLEN];
5989 	const char *propstr;
5990 	boolean_t right_justify;
5991 	size_t width;
5992 
5993 	for (; pl != NULL; pl = pl->pl_next) {
5994 
5995 		width = pl->pl_width;
5996 		if (first && cb->cb_verbose) {
5997 			/*
5998 			 * Reset the width to accommodate the verbose listing
5999 			 * of devices.
6000 			 */
6001 			width = cb->cb_namewidth;
6002 		}
6003 
6004 		if (!first) {
6005 			if (cb->cb_scripted)
6006 				(void) fputc('\t', stdout);
6007 			else
6008 				(void) fputs("  ", stdout);
6009 		} else {
6010 			first = B_FALSE;
6011 		}
6012 
6013 		right_justify = B_FALSE;
6014 		if (pl->pl_prop != ZPROP_USERPROP) {
6015 			if (zpool_get_prop(zhp, pl->pl_prop, property,
6016 			    sizeof (property), NULL, cb->cb_literal) != 0)
6017 				propstr = "-";
6018 			else
6019 				propstr = property;
6020 
6021 			right_justify = zpool_prop_align_right(pl->pl_prop);
6022 		} else if ((zpool_prop_feature(pl->pl_user_prop) ||
6023 		    zpool_prop_unsupported(pl->pl_user_prop)) &&
6024 		    zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
6025 		    sizeof (property)) == 0) {
6026 			propstr = property;
6027 		} else {
6028 			propstr = "-";
6029 		}
6030 
6031 
6032 		/*
6033 		 * If this is being called in scripted mode, or if this is the
6034 		 * last column and it is left-justified, don't include a width
6035 		 * format specifier.
6036 		 */
6037 		if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
6038 			(void) fputs(propstr, stdout);
6039 		else if (right_justify)
6040 			(void) printf("%*s", (int)width, propstr);
6041 		else
6042 			(void) printf("%-*s", (int)width, propstr);
6043 	}
6044 
6045 	(void) fputc('\n', stdout);
6046 }
6047 
6048 static void
6049 print_one_column(zpool_prop_t prop, uint64_t value, const char *str,
6050     boolean_t scripted, boolean_t valid, enum zfs_nicenum_format format)
6051 {
6052 	char propval[64];
6053 	boolean_t fixed;
6054 	size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
6055 
6056 	switch (prop) {
6057 	case ZPOOL_PROP_SIZE:
6058 	case ZPOOL_PROP_EXPANDSZ:
6059 	case ZPOOL_PROP_CHECKPOINT:
6060 	case ZPOOL_PROP_DEDUPRATIO:
6061 		if (value == 0)
6062 			(void) strlcpy(propval, "-", sizeof (propval));
6063 		else
6064 			zfs_nicenum_format(value, propval, sizeof (propval),
6065 			    format);
6066 		break;
6067 	case ZPOOL_PROP_FRAGMENTATION:
6068 		if (value == ZFS_FRAG_INVALID) {
6069 			(void) strlcpy(propval, "-", sizeof (propval));
6070 		} else if (format == ZFS_NICENUM_RAW) {
6071 			(void) snprintf(propval, sizeof (propval), "%llu",
6072 			    (unsigned long long)value);
6073 		} else {
6074 			(void) snprintf(propval, sizeof (propval), "%llu%%",
6075 			    (unsigned long long)value);
6076 		}
6077 		break;
6078 	case ZPOOL_PROP_CAPACITY:
6079 		/* capacity value is in parts-per-10,000 (aka permyriad) */
6080 		if (format == ZFS_NICENUM_RAW)
6081 			(void) snprintf(propval, sizeof (propval), "%llu",
6082 			    (unsigned long long)value / 100);
6083 		else
6084 			(void) snprintf(propval, sizeof (propval),
6085 			    value < 1000 ? "%1.2f%%" : value < 10000 ?
6086 			    "%2.1f%%" : "%3.0f%%", value / 100.0);
6087 		break;
6088 	case ZPOOL_PROP_HEALTH:
6089 		width = 8;
6090 		(void) strlcpy(propval, str, sizeof (propval));
6091 		break;
6092 	default:
6093 		zfs_nicenum_format(value, propval, sizeof (propval), format);
6094 	}
6095 
6096 	if (!valid)
6097 		(void) strlcpy(propval, "-", sizeof (propval));
6098 
6099 	if (scripted)
6100 		(void) printf("\t%s", propval);
6101 	else
6102 		(void) printf("  %*s", (int)width, propval);
6103 }
6104 
6105 /*
6106  * print static default line per vdev
6107  * not compatible with '-o' <proplist> option
6108  */
6109 static void
6110 print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
6111     list_cbdata_t *cb, int depth, boolean_t isspare)
6112 {
6113 	nvlist_t **child;
6114 	vdev_stat_t *vs;
6115 	uint_t c, children;
6116 	char *vname;
6117 	boolean_t scripted = cb->cb_scripted;
6118 	uint64_t islog = B_FALSE;
6119 	const char *dashes = "%-*s      -      -      -        -         "
6120 	    "-      -      -      -         -\n";
6121 
6122 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
6123 	    (uint64_t **)&vs, &c) == 0);
6124 
6125 	if (name != NULL) {
6126 		boolean_t toplevel = (vs->vs_space != 0);
6127 		uint64_t cap;
6128 		enum zfs_nicenum_format format;
6129 		const char *state;
6130 
6131 		if (cb->cb_literal)
6132 			format = ZFS_NICENUM_RAW;
6133 		else
6134 			format = ZFS_NICENUM_1024;
6135 
6136 		if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
6137 			return;
6138 
6139 		if (scripted)
6140 			(void) printf("\t%s", name);
6141 		else if (strlen(name) + depth > cb->cb_namewidth)
6142 			(void) printf("%*s%s", depth, "", name);
6143 		else
6144 			(void) printf("%*s%s%*s", depth, "", name,
6145 			    (int)(cb->cb_namewidth - strlen(name) - depth), "");
6146 
6147 		/*
6148 		 * Print the properties for the individual vdevs. Some
6149 		 * properties are only applicable to toplevel vdevs. The
6150 		 * 'toplevel' boolean value is passed to the print_one_column()
6151 		 * to indicate that the value is valid.
6152 		 */
6153 		if (VDEV_STAT_VALID(vs_pspace, c) && vs->vs_pspace)
6154 			print_one_column(ZPOOL_PROP_SIZE, vs->vs_pspace, NULL,
6155 			    scripted, B_TRUE, format);
6156 		else
6157 			print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, NULL,
6158 			    scripted, toplevel, format);
6159 		print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, NULL,
6160 		    scripted, toplevel, format);
6161 		print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
6162 		    NULL, scripted, toplevel, format);
6163 		print_one_column(ZPOOL_PROP_CHECKPOINT,
6164 		    vs->vs_checkpoint_space, NULL, scripted, toplevel, format);
6165 		print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, NULL,
6166 		    scripted, B_TRUE, format);
6167 		print_one_column(ZPOOL_PROP_FRAGMENTATION,
6168 		    vs->vs_fragmentation, NULL, scripted,
6169 		    (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
6170 		    format);
6171 		cap = (vs->vs_space == 0) ? 0 :
6172 		    (vs->vs_alloc * 10000 / vs->vs_space);
6173 		print_one_column(ZPOOL_PROP_CAPACITY, cap, NULL,
6174 		    scripted, toplevel, format);
6175 		print_one_column(ZPOOL_PROP_DEDUPRATIO, 0, NULL,
6176 		    scripted, toplevel, format);
6177 		state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
6178 		if (isspare) {
6179 			if (vs->vs_aux == VDEV_AUX_SPARED)
6180 				state = "INUSE";
6181 			else if (vs->vs_state == VDEV_STATE_HEALTHY)
6182 				state = "AVAIL";
6183 		}
6184 		print_one_column(ZPOOL_PROP_HEALTH, 0, state, scripted,
6185 		    B_TRUE, format);
6186 		(void) fputc('\n', stdout);
6187 	}
6188 
6189 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
6190 	    &child, &children) != 0)
6191 		return;
6192 
6193 	/* list the normal vdevs first */
6194 	for (c = 0; c < children; c++) {
6195 		uint64_t ishole = B_FALSE;
6196 
6197 		if (nvlist_lookup_uint64(child[c],
6198 		    ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
6199 			continue;
6200 
6201 		if (nvlist_lookup_uint64(child[c],
6202 		    ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
6203 			continue;
6204 
6205 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
6206 			continue;
6207 
6208 		vname = zpool_vdev_name(g_zfs, zhp, child[c],
6209 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
6210 		print_list_stats(zhp, vname, child[c], cb, depth + 2, B_FALSE);
6211 		free(vname);
6212 	}
6213 
6214 	/* list the classes: 'logs', 'dedup', and 'special' */
6215 	for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
6216 		boolean_t printed = B_FALSE;
6217 
6218 		for (c = 0; c < children; c++) {
6219 			char *bias = NULL;
6220 			char *type = NULL;
6221 
6222 			if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
6223 			    &islog) == 0 && islog) {
6224 				bias = (char *)VDEV_ALLOC_CLASS_LOGS;
6225 			} else {
6226 				(void) nvlist_lookup_string(child[c],
6227 				    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
6228 				(void) nvlist_lookup_string(child[c],
6229 				    ZPOOL_CONFIG_TYPE, &type);
6230 			}
6231 			if (bias == NULL || strcmp(bias, class_name[n]) != 0)
6232 				continue;
6233 			if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
6234 				continue;
6235 
6236 			if (!printed) {
6237 				/* LINTED E_SEC_PRINTF_VAR_FMT */
6238 				(void) printf(dashes, cb->cb_namewidth,
6239 				    class_name[n]);
6240 				printed = B_TRUE;
6241 			}
6242 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
6243 			    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
6244 			print_list_stats(zhp, vname, child[c], cb, depth + 2,
6245 			    B_FALSE);
6246 			free(vname);
6247 		}
6248 	}
6249 
6250 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
6251 	    &child, &children) == 0 && children > 0) {
6252 		/* LINTED E_SEC_PRINTF_VAR_FMT */
6253 		(void) printf(dashes, cb->cb_namewidth, "cache");
6254 		for (c = 0; c < children; c++) {
6255 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
6256 			    cb->cb_name_flags);
6257 			print_list_stats(zhp, vname, child[c], cb, depth + 2,
6258 			    B_FALSE);
6259 			free(vname);
6260 		}
6261 	}
6262 
6263 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
6264 	    &children) == 0 && children > 0) {
6265 		/* LINTED E_SEC_PRINTF_VAR_FMT */
6266 		(void) printf(dashes, cb->cb_namewidth, "spare");
6267 		for (c = 0; c < children; c++) {
6268 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
6269 			    cb->cb_name_flags);
6270 			print_list_stats(zhp, vname, child[c], cb, depth + 2,
6271 			    B_TRUE);
6272 			free(vname);
6273 		}
6274 	}
6275 }
6276 
6277 /*
6278  * Generic callback function to list a pool.
6279  */
6280 static int
6281 list_callback(zpool_handle_t *zhp, void *data)
6282 {
6283 	list_cbdata_t *cbp = data;
6284 
6285 	print_pool(zhp, cbp);
6286 
6287 	if (cbp->cb_verbose) {
6288 		nvlist_t *config, *nvroot;
6289 
6290 		config = zpool_get_config(zhp, NULL);
6291 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
6292 		    &nvroot) == 0);
6293 		print_list_stats(zhp, NULL, nvroot, cbp, 0, B_FALSE);
6294 	}
6295 
6296 	return (0);
6297 }
6298 
6299 /*
6300  * Set the minimum pool/vdev name column width.  The width must be at least 9,
6301  * but may be as large as needed.
6302  */
6303 static int
6304 get_namewidth_list(zpool_handle_t *zhp, void *data)
6305 {
6306 	list_cbdata_t *cb = data;
6307 	int width;
6308 
6309 	width = get_namewidth(zhp, cb->cb_namewidth,
6310 	    cb->cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
6311 
6312 	if (width < 9)
6313 		width = 9;
6314 
6315 	cb->cb_namewidth = width;
6316 
6317 	return (0);
6318 }
6319 
6320 /*
6321  * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
6322  *
6323  *	-g	Display guid for individual vdev name.
6324  *	-H	Scripted mode.  Don't display headers, and separate properties
6325  *		by a single tab.
6326  *	-L	Follow links when resolving vdev path name.
6327  *	-o	List of properties to display.  Defaults to
6328  *		"name,size,allocated,free,expandsize,fragmentation,capacity,"
6329  *		"dedupratio,health,altroot"
6330  *	-p	Display values in parsable (exact) format.
6331  *	-P	Display full path for vdev name.
6332  *	-T	Display a timestamp in date(1) or Unix format
6333  *
6334  * List all pools in the system, whether or not they're healthy.  Output space
6335  * statistics for each one, as well as health status summary.
6336  */
6337 int
6338 zpool_do_list(int argc, char **argv)
6339 {
6340 	int c;
6341 	int ret = 0;
6342 	list_cbdata_t cb = { 0 };
6343 	static char default_props[] =
6344 	    "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
6345 	    "capacity,dedupratio,health,altroot";
6346 	char *props = default_props;
6347 	float interval = 0;
6348 	unsigned long count = 0;
6349 	zpool_list_t *list;
6350 	boolean_t first = B_TRUE;
6351 	current_prop_type = ZFS_TYPE_POOL;
6352 
6353 	/* check options */
6354 	while ((c = getopt(argc, argv, ":gHLo:pPT:v")) != -1) {
6355 		switch (c) {
6356 		case 'g':
6357 			cb.cb_name_flags |= VDEV_NAME_GUID;
6358 			break;
6359 		case 'H':
6360 			cb.cb_scripted = B_TRUE;
6361 			break;
6362 		case 'L':
6363 			cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6364 			break;
6365 		case 'o':
6366 			props = optarg;
6367 			break;
6368 		case 'P':
6369 			cb.cb_name_flags |= VDEV_NAME_PATH;
6370 			break;
6371 		case 'p':
6372 			cb.cb_literal = B_TRUE;
6373 			break;
6374 		case 'T':
6375 			get_timestamp_arg(*optarg);
6376 			break;
6377 		case 'v':
6378 			cb.cb_verbose = B_TRUE;
6379 			cb.cb_namewidth = 8;	/* 8 until precalc is avail */
6380 			break;
6381 		case ':':
6382 			(void) fprintf(stderr, gettext("missing argument for "
6383 			    "'%c' option\n"), optopt);
6384 			usage(B_FALSE);
6385 			break;
6386 		case '?':
6387 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6388 			    optopt);
6389 			usage(B_FALSE);
6390 		}
6391 	}
6392 
6393 	argc -= optind;
6394 	argv += optind;
6395 
6396 	get_interval_count(&argc, argv, &interval, &count);
6397 
6398 	if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
6399 		usage(B_FALSE);
6400 
6401 	for (;;) {
6402 		if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
6403 		    ZFS_TYPE_POOL, cb.cb_literal, &ret)) == NULL)
6404 			return (1);
6405 
6406 		if (pool_list_count(list) == 0)
6407 			break;
6408 
6409 		cb.cb_namewidth = 0;
6410 		(void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
6411 
6412 		if (timestamp_fmt != NODATE)
6413 			print_timestamp(timestamp_fmt);
6414 
6415 		if (!cb.cb_scripted && (first || cb.cb_verbose)) {
6416 			print_header(&cb);
6417 			first = B_FALSE;
6418 		}
6419 		ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
6420 
6421 		if (interval == 0)
6422 			break;
6423 
6424 		if (count != 0 && --count == 0)
6425 			break;
6426 
6427 		pool_list_free(list);
6428 		(void) fsleep(interval);
6429 	}
6430 
6431 	if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
6432 		(void) printf(gettext("no pools available\n"));
6433 		ret = 0;
6434 	}
6435 
6436 	pool_list_free(list);
6437 	zprop_free_list(cb.cb_proplist);
6438 	return (ret);
6439 }
6440 
6441 static int
6442 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
6443 {
6444 	boolean_t force = B_FALSE;
6445 	boolean_t rebuild = B_FALSE;
6446 	boolean_t wait = B_FALSE;
6447 	int c;
6448 	nvlist_t *nvroot;
6449 	char *poolname, *old_disk, *new_disk;
6450 	zpool_handle_t *zhp;
6451 	nvlist_t *props = NULL;
6452 	char *propval;
6453 	int ret;
6454 
6455 	/* check options */
6456 	while ((c = getopt(argc, argv, "fo:sw")) != -1) {
6457 		switch (c) {
6458 		case 'f':
6459 			force = B_TRUE;
6460 			break;
6461 		case 'o':
6462 			if ((propval = strchr(optarg, '=')) == NULL) {
6463 				(void) fprintf(stderr, gettext("missing "
6464 				    "'=' for -o option\n"));
6465 				usage(B_FALSE);
6466 			}
6467 			*propval = '\0';
6468 			propval++;
6469 
6470 			if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
6471 			    (add_prop_list(optarg, propval, &props, B_TRUE)))
6472 				usage(B_FALSE);
6473 			break;
6474 		case 's':
6475 			rebuild = B_TRUE;
6476 			break;
6477 		case 'w':
6478 			wait = B_TRUE;
6479 			break;
6480 		case '?':
6481 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6482 			    optopt);
6483 			usage(B_FALSE);
6484 		}
6485 	}
6486 
6487 	argc -= optind;
6488 	argv += optind;
6489 
6490 	/* get pool name and check number of arguments */
6491 	if (argc < 1) {
6492 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
6493 		usage(B_FALSE);
6494 	}
6495 
6496 	poolname = argv[0];
6497 
6498 	if (argc < 2) {
6499 		(void) fprintf(stderr,
6500 		    gettext("missing <device> specification\n"));
6501 		usage(B_FALSE);
6502 	}
6503 
6504 	old_disk = argv[1];
6505 
6506 	if (argc < 3) {
6507 		if (!replacing) {
6508 			(void) fprintf(stderr,
6509 			    gettext("missing <new_device> specification\n"));
6510 			usage(B_FALSE);
6511 		}
6512 		new_disk = old_disk;
6513 		argc -= 1;
6514 		argv += 1;
6515 	} else {
6516 		new_disk = argv[2];
6517 		argc -= 2;
6518 		argv += 2;
6519 	}
6520 
6521 	if (argc > 1) {
6522 		(void) fprintf(stderr, gettext("too many arguments\n"));
6523 		usage(B_FALSE);
6524 	}
6525 
6526 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
6527 		nvlist_free(props);
6528 		return (1);
6529 	}
6530 
6531 	if (zpool_get_config(zhp, NULL) == NULL) {
6532 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
6533 		    poolname);
6534 		zpool_close(zhp);
6535 		nvlist_free(props);
6536 		return (1);
6537 	}
6538 
6539 	/* unless manually specified use "ashift" pool property (if set) */
6540 	if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
6541 		int intval;
6542 		zprop_source_t src;
6543 		char strval[ZPOOL_MAXPROPLEN];
6544 
6545 		intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
6546 		if (src != ZPROP_SRC_DEFAULT) {
6547 			(void) sprintf(strval, "%" PRId32, intval);
6548 			verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
6549 			    &props, B_TRUE) == 0);
6550 		}
6551 	}
6552 
6553 	nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
6554 	    argc, argv);
6555 	if (nvroot == NULL) {
6556 		zpool_close(zhp);
6557 		nvlist_free(props);
6558 		return (1);
6559 	}
6560 
6561 	ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing,
6562 	    rebuild);
6563 
6564 	if (ret == 0 && wait)
6565 		ret = zpool_wait(zhp,
6566 		    replacing ? ZPOOL_WAIT_REPLACE : ZPOOL_WAIT_RESILVER);
6567 
6568 	nvlist_free(props);
6569 	nvlist_free(nvroot);
6570 	zpool_close(zhp);
6571 
6572 	return (ret);
6573 }
6574 
6575 /*
6576  * zpool replace [-fsw] [-o property=value] <pool> <device> <new_device>
6577  *
6578  *	-f	Force attach, even if <new_device> appears to be in use.
6579  *	-s	Use sequential instead of healing reconstruction for resilver.
6580  *	-o	Set property=value.
6581  *	-w	Wait for replacing to complete before returning
6582  *
6583  * Replace <device> with <new_device>.
6584  */
6585 int
6586 zpool_do_replace(int argc, char **argv)
6587 {
6588 	return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
6589 }
6590 
6591 /*
6592  * zpool attach [-fsw] [-o property=value] <pool> <device> <new_device>
6593  *
6594  *	-f	Force attach, even if <new_device> appears to be in use.
6595  *	-s	Use sequential instead of healing reconstruction for resilver.
6596  *	-o	Set property=value.
6597  *	-w	Wait for resilvering to complete before returning
6598  *
6599  * Attach <new_device> to the mirror containing <device>.  If <device> is not
6600  * part of a mirror, then <device> will be transformed into a mirror of
6601  * <device> and <new_device>.  In either case, <new_device> will begin life
6602  * with a DTL of [0, now], and will immediately begin to resilver itself.
6603  */
6604 int
6605 zpool_do_attach(int argc, char **argv)
6606 {
6607 	return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
6608 }
6609 
6610 /*
6611  * zpool detach [-f] <pool> <device>
6612  *
6613  *	-f	Force detach of <device>, even if DTLs argue against it
6614  *		(not supported yet)
6615  *
6616  * Detach a device from a mirror.  The operation will be refused if <device>
6617  * is the last device in the mirror, or if the DTLs indicate that this device
6618  * has the only valid copy of some data.
6619  */
6620 int
6621 zpool_do_detach(int argc, char **argv)
6622 {
6623 	int c;
6624 	char *poolname, *path;
6625 	zpool_handle_t *zhp;
6626 	int ret;
6627 
6628 	/* check options */
6629 	while ((c = getopt(argc, argv, "")) != -1) {
6630 		switch (c) {
6631 		case '?':
6632 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6633 			    optopt);
6634 			usage(B_FALSE);
6635 		}
6636 	}
6637 
6638 	argc -= optind;
6639 	argv += optind;
6640 
6641 	/* get pool name and check number of arguments */
6642 	if (argc < 1) {
6643 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
6644 		usage(B_FALSE);
6645 	}
6646 
6647 	if (argc < 2) {
6648 		(void) fprintf(stderr,
6649 		    gettext("missing <device> specification\n"));
6650 		usage(B_FALSE);
6651 	}
6652 
6653 	poolname = argv[0];
6654 	path = argv[1];
6655 
6656 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6657 		return (1);
6658 
6659 	ret = zpool_vdev_detach(zhp, path);
6660 
6661 	zpool_close(zhp);
6662 
6663 	return (ret);
6664 }
6665 
6666 /*
6667  * zpool split [-gLnP] [-o prop=val] ...
6668  *		[-o mntopt] ...
6669  *		[-R altroot] <pool> <newpool> [<device> ...]
6670  *
6671  *	-g      Display guid for individual vdev name.
6672  *	-L	Follow links when resolving vdev path name.
6673  *	-n	Do not split the pool, but display the resulting layout if
6674  *		it were to be split.
6675  *	-o	Set property=value, or set mount options.
6676  *	-P	Display full path for vdev name.
6677  *	-R	Mount the split-off pool under an alternate root.
6678  *	-l	Load encryption keys while importing.
6679  *
6680  * Splits the named pool and gives it the new pool name.  Devices to be split
6681  * off may be listed, provided that no more than one device is specified
6682  * per top-level vdev mirror.  The newly split pool is left in an exported
6683  * state unless -R is specified.
6684  *
6685  * Restrictions: the top-level of the pool pool must only be made up of
6686  * mirrors; all devices in the pool must be healthy; no device may be
6687  * undergoing a resilvering operation.
6688  */
6689 int
6690 zpool_do_split(int argc, char **argv)
6691 {
6692 	char *srcpool, *newpool, *propval;
6693 	char *mntopts = NULL;
6694 	splitflags_t flags;
6695 	int c, ret = 0;
6696 	boolean_t loadkeys = B_FALSE;
6697 	zpool_handle_t *zhp;
6698 	nvlist_t *config, *props = NULL;
6699 
6700 	flags.dryrun = B_FALSE;
6701 	flags.import = B_FALSE;
6702 	flags.name_flags = 0;
6703 
6704 	/* check options */
6705 	while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
6706 		switch (c) {
6707 		case 'g':
6708 			flags.name_flags |= VDEV_NAME_GUID;
6709 			break;
6710 		case 'L':
6711 			flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
6712 			break;
6713 		case 'R':
6714 			flags.import = B_TRUE;
6715 			if (add_prop_list(
6716 			    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
6717 			    &props, B_TRUE) != 0) {
6718 				nvlist_free(props);
6719 				usage(B_FALSE);
6720 			}
6721 			break;
6722 		case 'l':
6723 			loadkeys = B_TRUE;
6724 			break;
6725 		case 'n':
6726 			flags.dryrun = B_TRUE;
6727 			break;
6728 		case 'o':
6729 			if ((propval = strchr(optarg, '=')) != NULL) {
6730 				*propval = '\0';
6731 				propval++;
6732 				if (add_prop_list(optarg, propval,
6733 				    &props, B_TRUE) != 0) {
6734 					nvlist_free(props);
6735 					usage(B_FALSE);
6736 				}
6737 			} else {
6738 				mntopts = optarg;
6739 			}
6740 			break;
6741 		case 'P':
6742 			flags.name_flags |= VDEV_NAME_PATH;
6743 			break;
6744 		case ':':
6745 			(void) fprintf(stderr, gettext("missing argument for "
6746 			    "'%c' option\n"), optopt);
6747 			usage(B_FALSE);
6748 			break;
6749 		case '?':
6750 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6751 			    optopt);
6752 			usage(B_FALSE);
6753 			break;
6754 		}
6755 	}
6756 
6757 	if (!flags.import && mntopts != NULL) {
6758 		(void) fprintf(stderr, gettext("setting mntopts is only "
6759 		    "valid when importing the pool\n"));
6760 		usage(B_FALSE);
6761 	}
6762 
6763 	if (!flags.import && loadkeys) {
6764 		(void) fprintf(stderr, gettext("loading keys is only "
6765 		    "valid when importing the pool\n"));
6766 		usage(B_FALSE);
6767 	}
6768 
6769 	argc -= optind;
6770 	argv += optind;
6771 
6772 	if (argc < 1) {
6773 		(void) fprintf(stderr, gettext("Missing pool name\n"));
6774 		usage(B_FALSE);
6775 	}
6776 	if (argc < 2) {
6777 		(void) fprintf(stderr, gettext("Missing new pool name\n"));
6778 		usage(B_FALSE);
6779 	}
6780 
6781 	srcpool = argv[0];
6782 	newpool = argv[1];
6783 
6784 	argc -= 2;
6785 	argv += 2;
6786 
6787 	if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
6788 		nvlist_free(props);
6789 		return (1);
6790 	}
6791 
6792 	config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
6793 	if (config == NULL) {
6794 		ret = 1;
6795 	} else {
6796 		if (flags.dryrun) {
6797 			(void) printf(gettext("would create '%s' with the "
6798 			    "following layout:\n\n"), newpool);
6799 			print_vdev_tree(NULL, newpool, config, 0, "",
6800 			    flags.name_flags);
6801 			print_vdev_tree(NULL, "dedup", config, 0,
6802 			    VDEV_ALLOC_BIAS_DEDUP, 0);
6803 			print_vdev_tree(NULL, "special", config, 0,
6804 			    VDEV_ALLOC_BIAS_SPECIAL, 0);
6805 		}
6806 	}
6807 
6808 	zpool_close(zhp);
6809 
6810 	if (ret != 0 || flags.dryrun || !flags.import) {
6811 		nvlist_free(config);
6812 		nvlist_free(props);
6813 		return (ret);
6814 	}
6815 
6816 	/*
6817 	 * The split was successful. Now we need to open the new
6818 	 * pool and import it.
6819 	 */
6820 	if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
6821 		nvlist_free(config);
6822 		nvlist_free(props);
6823 		return (1);
6824 	}
6825 
6826 	if (loadkeys) {
6827 		ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
6828 		if (ret != 0)
6829 			ret = 1;
6830 	}
6831 
6832 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
6833 	    zpool_enable_datasets(zhp, mntopts, 0) != 0) {
6834 		ret = 1;
6835 		(void) fprintf(stderr, gettext("Split was successful, but "
6836 		    "the datasets could not all be mounted\n"));
6837 		(void) fprintf(stderr, gettext("Try doing '%s' with a "
6838 		    "different altroot\n"), "zpool import");
6839 	}
6840 	zpool_close(zhp);
6841 	nvlist_free(config);
6842 	nvlist_free(props);
6843 
6844 	return (ret);
6845 }
6846 
6847 
6848 
6849 /*
6850  * zpool online <pool> <device> ...
6851  */
6852 int
6853 zpool_do_online(int argc, char **argv)
6854 {
6855 	int c, i;
6856 	char *poolname;
6857 	zpool_handle_t *zhp;
6858 	int ret = 0;
6859 	vdev_state_t newstate;
6860 	int flags = 0;
6861 
6862 	/* check options */
6863 	while ((c = getopt(argc, argv, "e")) != -1) {
6864 		switch (c) {
6865 		case 'e':
6866 			flags |= ZFS_ONLINE_EXPAND;
6867 			break;
6868 		case '?':
6869 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6870 			    optopt);
6871 			usage(B_FALSE);
6872 		}
6873 	}
6874 
6875 	argc -= optind;
6876 	argv += optind;
6877 
6878 	/* get pool name and check number of arguments */
6879 	if (argc < 1) {
6880 		(void) fprintf(stderr, gettext("missing pool name\n"));
6881 		usage(B_FALSE);
6882 	}
6883 	if (argc < 2) {
6884 		(void) fprintf(stderr, gettext("missing device name\n"));
6885 		usage(B_FALSE);
6886 	}
6887 
6888 	poolname = argv[0];
6889 
6890 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6891 		return (1);
6892 
6893 	for (i = 1; i < argc; i++) {
6894 		if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
6895 			if (newstate != VDEV_STATE_HEALTHY) {
6896 				(void) printf(gettext("warning: device '%s' "
6897 				    "onlined, but remains in faulted state\n"),
6898 				    argv[i]);
6899 				if (newstate == VDEV_STATE_FAULTED)
6900 					(void) printf(gettext("use 'zpool "
6901 					    "clear' to restore a faulted "
6902 					    "device\n"));
6903 				else
6904 					(void) printf(gettext("use 'zpool "
6905 					    "replace' to replace devices "
6906 					    "that are no longer present\n"));
6907 			}
6908 		} else {
6909 			ret = 1;
6910 		}
6911 	}
6912 
6913 	zpool_close(zhp);
6914 
6915 	return (ret);
6916 }
6917 
6918 /*
6919  * zpool offline [-ft] <pool> <device> ...
6920  *
6921  *	-f	Force the device into a faulted state.
6922  *
6923  *	-t	Only take the device off-line temporarily.  The offline/faulted
6924  *		state will not be persistent across reboots.
6925  */
6926 int
6927 zpool_do_offline(int argc, char **argv)
6928 {
6929 	int c, i;
6930 	char *poolname;
6931 	zpool_handle_t *zhp;
6932 	int ret = 0;
6933 	boolean_t istmp = B_FALSE;
6934 	boolean_t fault = B_FALSE;
6935 
6936 	/* check options */
6937 	while ((c = getopt(argc, argv, "ft")) != -1) {
6938 		switch (c) {
6939 		case 'f':
6940 			fault = B_TRUE;
6941 			break;
6942 		case 't':
6943 			istmp = B_TRUE;
6944 			break;
6945 		case '?':
6946 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6947 			    optopt);
6948 			usage(B_FALSE);
6949 		}
6950 	}
6951 
6952 	argc -= optind;
6953 	argv += optind;
6954 
6955 	/* get pool name and check number of arguments */
6956 	if (argc < 1) {
6957 		(void) fprintf(stderr, gettext("missing pool name\n"));
6958 		usage(B_FALSE);
6959 	}
6960 	if (argc < 2) {
6961 		(void) fprintf(stderr, gettext("missing device name\n"));
6962 		usage(B_FALSE);
6963 	}
6964 
6965 	poolname = argv[0];
6966 
6967 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6968 		return (1);
6969 
6970 	for (i = 1; i < argc; i++) {
6971 		if (fault) {
6972 			uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
6973 			vdev_aux_t aux;
6974 			if (istmp == B_FALSE) {
6975 				/* Force the fault to persist across imports */
6976 				aux = VDEV_AUX_EXTERNAL_PERSIST;
6977 			} else {
6978 				aux = VDEV_AUX_EXTERNAL;
6979 			}
6980 
6981 			if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
6982 				ret = 1;
6983 		} else {
6984 			if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
6985 				ret = 1;
6986 		}
6987 	}
6988 
6989 	zpool_close(zhp);
6990 
6991 	return (ret);
6992 }
6993 
6994 /*
6995  * zpool clear <pool> [device]
6996  *
6997  * Clear all errors associated with a pool or a particular device.
6998  */
6999 int
7000 zpool_do_clear(int argc, char **argv)
7001 {
7002 	int c;
7003 	int ret = 0;
7004 	boolean_t dryrun = B_FALSE;
7005 	boolean_t do_rewind = B_FALSE;
7006 	boolean_t xtreme_rewind = B_FALSE;
7007 	uint32_t rewind_policy = ZPOOL_NO_REWIND;
7008 	nvlist_t *policy = NULL;
7009 	zpool_handle_t *zhp;
7010 	char *pool, *device;
7011 
7012 	/* check options */
7013 	while ((c = getopt(argc, argv, "FnX")) != -1) {
7014 		switch (c) {
7015 		case 'F':
7016 			do_rewind = B_TRUE;
7017 			break;
7018 		case 'n':
7019 			dryrun = B_TRUE;
7020 			break;
7021 		case 'X':
7022 			xtreme_rewind = B_TRUE;
7023 			break;
7024 		case '?':
7025 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7026 			    optopt);
7027 			usage(B_FALSE);
7028 		}
7029 	}
7030 
7031 	argc -= optind;
7032 	argv += optind;
7033 
7034 	if (argc < 1) {
7035 		(void) fprintf(stderr, gettext("missing pool name\n"));
7036 		usage(B_FALSE);
7037 	}
7038 
7039 	if (argc > 2) {
7040 		(void) fprintf(stderr, gettext("too many arguments\n"));
7041 		usage(B_FALSE);
7042 	}
7043 
7044 	if ((dryrun || xtreme_rewind) && !do_rewind) {
7045 		(void) fprintf(stderr,
7046 		    gettext("-n or -X only meaningful with -F\n"));
7047 		usage(B_FALSE);
7048 	}
7049 	if (dryrun)
7050 		rewind_policy = ZPOOL_TRY_REWIND;
7051 	else if (do_rewind)
7052 		rewind_policy = ZPOOL_DO_REWIND;
7053 	if (xtreme_rewind)
7054 		rewind_policy |= ZPOOL_EXTREME_REWIND;
7055 
7056 	/* In future, further rewind policy choices can be passed along here */
7057 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
7058 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
7059 	    rewind_policy) != 0) {
7060 		return (1);
7061 	}
7062 
7063 	pool = argv[0];
7064 	device = argc == 2 ? argv[1] : NULL;
7065 
7066 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
7067 		nvlist_free(policy);
7068 		return (1);
7069 	}
7070 
7071 	if (zpool_clear(zhp, device, policy) != 0)
7072 		ret = 1;
7073 
7074 	zpool_close(zhp);
7075 
7076 	nvlist_free(policy);
7077 
7078 	return (ret);
7079 }
7080 
7081 /*
7082  * zpool reguid <pool>
7083  */
7084 int
7085 zpool_do_reguid(int argc, char **argv)
7086 {
7087 	int c;
7088 	char *poolname;
7089 	zpool_handle_t *zhp;
7090 	int ret = 0;
7091 
7092 	/* check options */
7093 	while ((c = getopt(argc, argv, "")) != -1) {
7094 		switch (c) {
7095 		case '?':
7096 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7097 			    optopt);
7098 			usage(B_FALSE);
7099 		}
7100 	}
7101 
7102 	argc -= optind;
7103 	argv += optind;
7104 
7105 	/* get pool name and check number of arguments */
7106 	if (argc < 1) {
7107 		(void) fprintf(stderr, gettext("missing pool name\n"));
7108 		usage(B_FALSE);
7109 	}
7110 
7111 	if (argc > 1) {
7112 		(void) fprintf(stderr, gettext("too many arguments\n"));
7113 		usage(B_FALSE);
7114 	}
7115 
7116 	poolname = argv[0];
7117 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7118 		return (1);
7119 
7120 	ret = zpool_reguid(zhp);
7121 
7122 	zpool_close(zhp);
7123 	return (ret);
7124 }
7125 
7126 
7127 /*
7128  * zpool reopen <pool>
7129  *
7130  * Reopen the pool so that the kernel can update the sizes of all vdevs.
7131  */
7132 int
7133 zpool_do_reopen(int argc, char **argv)
7134 {
7135 	int c;
7136 	int ret = 0;
7137 	boolean_t scrub_restart = B_TRUE;
7138 
7139 	/* check options */
7140 	while ((c = getopt(argc, argv, "n")) != -1) {
7141 		switch (c) {
7142 		case 'n':
7143 			scrub_restart = B_FALSE;
7144 			break;
7145 		case '?':
7146 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7147 			    optopt);
7148 			usage(B_FALSE);
7149 		}
7150 	}
7151 
7152 	argc -= optind;
7153 	argv += optind;
7154 
7155 	/* if argc == 0 we will execute zpool_reopen_one on all pools */
7156 	ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7157 	    B_FALSE, zpool_reopen_one, &scrub_restart);
7158 
7159 	return (ret);
7160 }
7161 
7162 typedef struct scrub_cbdata {
7163 	int	cb_type;
7164 	pool_scrub_cmd_t cb_scrub_cmd;
7165 } scrub_cbdata_t;
7166 
7167 static boolean_t
7168 zpool_has_checkpoint(zpool_handle_t *zhp)
7169 {
7170 	nvlist_t *config, *nvroot;
7171 
7172 	config = zpool_get_config(zhp, NULL);
7173 
7174 	if (config != NULL) {
7175 		pool_checkpoint_stat_t *pcs = NULL;
7176 		uint_t c;
7177 
7178 		nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
7179 		(void) nvlist_lookup_uint64_array(nvroot,
7180 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
7181 
7182 		if (pcs == NULL || pcs->pcs_state == CS_NONE)
7183 			return (B_FALSE);
7184 
7185 		assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
7186 		    pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
7187 		return (B_TRUE);
7188 	}
7189 
7190 	return (B_FALSE);
7191 }
7192 
7193 static int
7194 scrub_callback(zpool_handle_t *zhp, void *data)
7195 {
7196 	scrub_cbdata_t *cb = data;
7197 	int err;
7198 
7199 	/*
7200 	 * Ignore faulted pools.
7201 	 */
7202 	if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
7203 		(void) fprintf(stderr, gettext("cannot scan '%s': pool is "
7204 		    "currently unavailable\n"), zpool_get_name(zhp));
7205 		return (1);
7206 	}
7207 
7208 	err = zpool_scan(zhp, cb->cb_type, cb->cb_scrub_cmd);
7209 
7210 	if (err == 0 && zpool_has_checkpoint(zhp) &&
7211 	    cb->cb_type == POOL_SCAN_SCRUB) {
7212 		(void) printf(gettext("warning: will not scrub state that "
7213 		    "belongs to the checkpoint of pool '%s'\n"),
7214 		    zpool_get_name(zhp));
7215 	}
7216 
7217 	return (err != 0);
7218 }
7219 
7220 static int
7221 wait_callback(zpool_handle_t *zhp, void *data)
7222 {
7223 	zpool_wait_activity_t *act = data;
7224 	return (zpool_wait(zhp, *act));
7225 }
7226 
7227 /*
7228  * zpool scrub [-s | -p] [-w] <pool> ...
7229  *
7230  *	-s	Stop.  Stops any in-progress scrub.
7231  *	-p	Pause. Pause in-progress scrub.
7232  *	-w	Wait.  Blocks until scrub has completed.
7233  */
7234 int
7235 zpool_do_scrub(int argc, char **argv)
7236 {
7237 	int c;
7238 	scrub_cbdata_t cb;
7239 	boolean_t wait = B_FALSE;
7240 	int error;
7241 
7242 	cb.cb_type = POOL_SCAN_SCRUB;
7243 	cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
7244 
7245 	/* check options */
7246 	while ((c = getopt(argc, argv, "spw")) != -1) {
7247 		switch (c) {
7248 		case 's':
7249 			cb.cb_type = POOL_SCAN_NONE;
7250 			break;
7251 		case 'p':
7252 			cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
7253 			break;
7254 		case 'w':
7255 			wait = B_TRUE;
7256 			break;
7257 		case '?':
7258 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7259 			    optopt);
7260 			usage(B_FALSE);
7261 		}
7262 	}
7263 
7264 	if (cb.cb_type == POOL_SCAN_NONE &&
7265 	    cb.cb_scrub_cmd == POOL_SCRUB_PAUSE) {
7266 		(void) fprintf(stderr, gettext("invalid option combination: "
7267 		    "-s and -p are mutually exclusive\n"));
7268 		usage(B_FALSE);
7269 	}
7270 
7271 	if (wait && (cb.cb_type == POOL_SCAN_NONE ||
7272 	    cb.cb_scrub_cmd == POOL_SCRUB_PAUSE)) {
7273 		(void) fprintf(stderr, gettext("invalid option combination: "
7274 		    "-w cannot be used with -p or -s\n"));
7275 		usage(B_FALSE);
7276 	}
7277 
7278 	argc -= optind;
7279 	argv += optind;
7280 
7281 	if (argc < 1) {
7282 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
7283 		usage(B_FALSE);
7284 	}
7285 
7286 	error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7287 	    B_FALSE, scrub_callback, &cb);
7288 
7289 	if (wait && !error) {
7290 		zpool_wait_activity_t act = ZPOOL_WAIT_SCRUB;
7291 		error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7292 		    B_FALSE, wait_callback, &act);
7293 	}
7294 
7295 	return (error);
7296 }
7297 
7298 /*
7299  * zpool resilver <pool> ...
7300  *
7301  *	Restarts any in-progress resilver
7302  */
7303 int
7304 zpool_do_resilver(int argc, char **argv)
7305 {
7306 	int c;
7307 	scrub_cbdata_t cb;
7308 
7309 	cb.cb_type = POOL_SCAN_RESILVER;
7310 	cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
7311 
7312 	/* check options */
7313 	while ((c = getopt(argc, argv, "")) != -1) {
7314 		switch (c) {
7315 		case '?':
7316 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7317 			    optopt);
7318 			usage(B_FALSE);
7319 		}
7320 	}
7321 
7322 	argc -= optind;
7323 	argv += optind;
7324 
7325 	if (argc < 1) {
7326 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
7327 		usage(B_FALSE);
7328 	}
7329 
7330 	return (for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7331 	    B_FALSE, scrub_callback, &cb));
7332 }
7333 
7334 /*
7335  * zpool trim [-d] [-r <rate>] [-c | -s] <pool> [<device> ...]
7336  *
7337  *	-c		Cancel. Ends any in-progress trim.
7338  *	-d		Secure trim.  Requires kernel and device support.
7339  *	-r <rate>	Sets the TRIM rate in bytes (per second). Supports
7340  *			adding a multiplier suffix such as 'k' or 'm'.
7341  *	-s		Suspend. TRIM can then be restarted with no flags.
7342  *	-w		Wait. Blocks until trimming has completed.
7343  */
7344 int
7345 zpool_do_trim(int argc, char **argv)
7346 {
7347 	struct option long_options[] = {
7348 		{"cancel",	no_argument,		NULL,	'c'},
7349 		{"secure",	no_argument,		NULL,	'd'},
7350 		{"rate",	required_argument,	NULL,	'r'},
7351 		{"suspend",	no_argument,		NULL,	's'},
7352 		{"wait",	no_argument,		NULL,	'w'},
7353 		{0, 0, 0, 0}
7354 	};
7355 
7356 	pool_trim_func_t cmd_type = POOL_TRIM_START;
7357 	uint64_t rate = 0;
7358 	boolean_t secure = B_FALSE;
7359 	boolean_t wait = B_FALSE;
7360 
7361 	int c;
7362 	while ((c = getopt_long(argc, argv, "cdr:sw", long_options, NULL))
7363 	    != -1) {
7364 		switch (c) {
7365 		case 'c':
7366 			if (cmd_type != POOL_TRIM_START &&
7367 			    cmd_type != POOL_TRIM_CANCEL) {
7368 				(void) fprintf(stderr, gettext("-c cannot be "
7369 				    "combined with other options\n"));
7370 				usage(B_FALSE);
7371 			}
7372 			cmd_type = POOL_TRIM_CANCEL;
7373 			break;
7374 		case 'd':
7375 			if (cmd_type != POOL_TRIM_START) {
7376 				(void) fprintf(stderr, gettext("-d cannot be "
7377 				    "combined with the -c or -s options\n"));
7378 				usage(B_FALSE);
7379 			}
7380 			secure = B_TRUE;
7381 			break;
7382 		case 'r':
7383 			if (cmd_type != POOL_TRIM_START) {
7384 				(void) fprintf(stderr, gettext("-r cannot be "
7385 				    "combined with the -c or -s options\n"));
7386 				usage(B_FALSE);
7387 			}
7388 			if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
7389 				(void) fprintf(stderr, "%s: %s\n",
7390 				    gettext("invalid value for rate"),
7391 				    libzfs_error_description(g_zfs));
7392 				usage(B_FALSE);
7393 			}
7394 			break;
7395 		case 's':
7396 			if (cmd_type != POOL_TRIM_START &&
7397 			    cmd_type != POOL_TRIM_SUSPEND) {
7398 				(void) fprintf(stderr, gettext("-s cannot be "
7399 				    "combined with other options\n"));
7400 				usage(B_FALSE);
7401 			}
7402 			cmd_type = POOL_TRIM_SUSPEND;
7403 			break;
7404 		case 'w':
7405 			wait = B_TRUE;
7406 			break;
7407 		case '?':
7408 			if (optopt != 0) {
7409 				(void) fprintf(stderr,
7410 				    gettext("invalid option '%c'\n"), optopt);
7411 			} else {
7412 				(void) fprintf(stderr,
7413 				    gettext("invalid option '%s'\n"),
7414 				    argv[optind - 1]);
7415 			}
7416 			usage(B_FALSE);
7417 		}
7418 	}
7419 
7420 	argc -= optind;
7421 	argv += optind;
7422 
7423 	if (argc < 1) {
7424 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
7425 		usage(B_FALSE);
7426 		return (-1);
7427 	}
7428 
7429 	if (wait && (cmd_type != POOL_TRIM_START)) {
7430 		(void) fprintf(stderr, gettext("-w cannot be used with -c or "
7431 		    "-s\n"));
7432 		usage(B_FALSE);
7433 	}
7434 
7435 	char *poolname = argv[0];
7436 	zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
7437 	if (zhp == NULL)
7438 		return (-1);
7439 
7440 	trimflags_t trim_flags = {
7441 		.secure = secure,
7442 		.rate = rate,
7443 		.wait = wait,
7444 	};
7445 
7446 	nvlist_t *vdevs = fnvlist_alloc();
7447 	if (argc == 1) {
7448 		/* no individual leaf vdevs specified, so add them all */
7449 		nvlist_t *config = zpool_get_config(zhp, NULL);
7450 		nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
7451 		    ZPOOL_CONFIG_VDEV_TREE);
7452 		zpool_collect_leaves(zhp, nvroot, vdevs);
7453 		trim_flags.fullpool = B_TRUE;
7454 	} else {
7455 		trim_flags.fullpool = B_FALSE;
7456 		for (int i = 1; i < argc; i++) {
7457 			fnvlist_add_boolean(vdevs, argv[i]);
7458 		}
7459 	}
7460 
7461 	int error = zpool_trim(zhp, cmd_type, vdevs, &trim_flags);
7462 
7463 	fnvlist_free(vdevs);
7464 	zpool_close(zhp);
7465 
7466 	return (error);
7467 }
7468 
7469 /*
7470  * Converts a total number of seconds to a human readable string broken
7471  * down in to days/hours/minutes/seconds.
7472  */
7473 static void
7474 secs_to_dhms(uint64_t total, char *buf)
7475 {
7476 	uint64_t days = total / 60 / 60 / 24;
7477 	uint64_t hours = (total / 60 / 60) % 24;
7478 	uint64_t mins = (total / 60) % 60;
7479 	uint64_t secs = (total % 60);
7480 
7481 	if (days > 0) {
7482 		(void) sprintf(buf, "%llu days %02llu:%02llu:%02llu",
7483 		    (u_longlong_t)days, (u_longlong_t)hours,
7484 		    (u_longlong_t)mins, (u_longlong_t)secs);
7485 	} else {
7486 		(void) sprintf(buf, "%02llu:%02llu:%02llu",
7487 		    (u_longlong_t)hours, (u_longlong_t)mins,
7488 		    (u_longlong_t)secs);
7489 	}
7490 }
7491 
7492 /*
7493  * Print out detailed scrub status.
7494  */
7495 static void
7496 print_scan_scrub_resilver_status(pool_scan_stat_t *ps)
7497 {
7498 	time_t start, end, pause;
7499 	uint64_t pass_scanned, scanned, pass_issued, issued, total;
7500 	uint64_t elapsed, scan_rate, issue_rate;
7501 	double fraction_done;
7502 	char processed_buf[7], scanned_buf[7], issued_buf[7], total_buf[7];
7503 	char srate_buf[7], irate_buf[7], time_buf[32];
7504 
7505 	printf("  ");
7506 	printf_color(ANSI_BOLD, gettext("scan:"));
7507 	printf(" ");
7508 
7509 	/* If there's never been a scan, there's not much to say. */
7510 	if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
7511 	    ps->pss_func >= POOL_SCAN_FUNCS) {
7512 		(void) printf(gettext("none requested\n"));
7513 		return;
7514 	}
7515 
7516 	start = ps->pss_start_time;
7517 	end = ps->pss_end_time;
7518 	pause = ps->pss_pass_scrub_pause;
7519 
7520 	zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
7521 
7522 	assert(ps->pss_func == POOL_SCAN_SCRUB ||
7523 	    ps->pss_func == POOL_SCAN_RESILVER);
7524 
7525 	/* Scan is finished or canceled. */
7526 	if (ps->pss_state == DSS_FINISHED) {
7527 		secs_to_dhms(end - start, time_buf);
7528 
7529 		if (ps->pss_func == POOL_SCAN_SCRUB) {
7530 			(void) printf(gettext("scrub repaired %s "
7531 			    "in %s with %llu errors on %s"), processed_buf,
7532 			    time_buf, (u_longlong_t)ps->pss_errors,
7533 			    ctime(&end));
7534 		} else if (ps->pss_func == POOL_SCAN_RESILVER) {
7535 			(void) printf(gettext("resilvered %s "
7536 			    "in %s with %llu errors on %s"), processed_buf,
7537 			    time_buf, (u_longlong_t)ps->pss_errors,
7538 			    ctime(&end));
7539 		}
7540 		return;
7541 	} else if (ps->pss_state == DSS_CANCELED) {
7542 		if (ps->pss_func == POOL_SCAN_SCRUB) {
7543 			(void) printf(gettext("scrub canceled on %s"),
7544 			    ctime(&end));
7545 		} else if (ps->pss_func == POOL_SCAN_RESILVER) {
7546 			(void) printf(gettext("resilver canceled on %s"),
7547 			    ctime(&end));
7548 		}
7549 		return;
7550 	}
7551 
7552 	assert(ps->pss_state == DSS_SCANNING);
7553 
7554 	/* Scan is in progress. Resilvers can't be paused. */
7555 	if (ps->pss_func == POOL_SCAN_SCRUB) {
7556 		if (pause == 0) {
7557 			(void) printf(gettext("scrub in progress since %s"),
7558 			    ctime(&start));
7559 		} else {
7560 			(void) printf(gettext("scrub paused since %s"),
7561 			    ctime(&pause));
7562 			(void) printf(gettext("\tscrub started on %s"),
7563 			    ctime(&start));
7564 		}
7565 	} else if (ps->pss_func == POOL_SCAN_RESILVER) {
7566 		(void) printf(gettext("resilver in progress since %s"),
7567 		    ctime(&start));
7568 	}
7569 
7570 	scanned = ps->pss_examined;
7571 	pass_scanned = ps->pss_pass_exam;
7572 	issued = ps->pss_issued;
7573 	pass_issued = ps->pss_pass_issued;
7574 	total = ps->pss_to_examine;
7575 
7576 	/* we are only done with a block once we have issued the IO for it */
7577 	fraction_done = (double)issued / total;
7578 
7579 	/* elapsed time for this pass, rounding up to 1 if it's 0 */
7580 	elapsed = time(NULL) - ps->pss_pass_start;
7581 	elapsed -= ps->pss_pass_scrub_spent_paused;
7582 	elapsed = (elapsed != 0) ? elapsed : 1;
7583 
7584 	scan_rate = pass_scanned / elapsed;
7585 	issue_rate = pass_issued / elapsed;
7586 	uint64_t total_secs_left = (issue_rate != 0 && total >= issued) ?
7587 	    ((total - issued) / issue_rate) : UINT64_MAX;
7588 	secs_to_dhms(total_secs_left, time_buf);
7589 
7590 	/* format all of the numbers we will be reporting */
7591 	zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
7592 	zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
7593 	zfs_nicebytes(total, total_buf, sizeof (total_buf));
7594 	zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
7595 	zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
7596 
7597 	/* do not print estimated time if we have a paused scrub */
7598 	if (pause == 0) {
7599 		(void) printf(gettext("\t%s scanned at %s/s, "
7600 		    "%s issued at %s/s, %s total\n"),
7601 		    scanned_buf, srate_buf, issued_buf, irate_buf, total_buf);
7602 	} else {
7603 		(void) printf(gettext("\t%s scanned, %s issued, %s total\n"),
7604 		    scanned_buf, issued_buf, total_buf);
7605 	}
7606 
7607 	if (ps->pss_func == POOL_SCAN_RESILVER) {
7608 		(void) printf(gettext("\t%s resilvered, %.2f%% done"),
7609 		    processed_buf, 100 * fraction_done);
7610 	} else if (ps->pss_func == POOL_SCAN_SCRUB) {
7611 		(void) printf(gettext("\t%s repaired, %.2f%% done"),
7612 		    processed_buf, 100 * fraction_done);
7613 	}
7614 
7615 	if (pause == 0) {
7616 		if (total_secs_left != UINT64_MAX &&
7617 		    issue_rate >= 10 * 1024 * 1024) {
7618 			(void) printf(gettext(", %s to go\n"), time_buf);
7619 		} else {
7620 			(void) printf(gettext(", no estimated "
7621 			    "completion time\n"));
7622 		}
7623 	} else {
7624 		(void) printf(gettext("\n"));
7625 	}
7626 }
7627 
7628 static void
7629 print_rebuild_status_impl(vdev_rebuild_stat_t *vrs, char *vdev_name)
7630 {
7631 	if (vrs == NULL || vrs->vrs_state == VDEV_REBUILD_NONE)
7632 		return;
7633 
7634 	printf("  ");
7635 	printf_color(ANSI_BOLD, gettext("scan:"));
7636 	printf(" ");
7637 
7638 	uint64_t bytes_scanned = vrs->vrs_bytes_scanned;
7639 	uint64_t bytes_issued = vrs->vrs_bytes_issued;
7640 	uint64_t bytes_rebuilt = vrs->vrs_bytes_rebuilt;
7641 	uint64_t bytes_est = vrs->vrs_bytes_est;
7642 	uint64_t scan_rate = (vrs->vrs_pass_bytes_scanned /
7643 	    (vrs->vrs_pass_time_ms + 1)) * 1000;
7644 	uint64_t issue_rate = (vrs->vrs_pass_bytes_issued /
7645 	    (vrs->vrs_pass_time_ms + 1)) * 1000;
7646 	double scan_pct = MIN((double)bytes_scanned * 100 /
7647 	    (bytes_est + 1), 100);
7648 
7649 	/* Format all of the numbers we will be reporting */
7650 	char bytes_scanned_buf[7], bytes_issued_buf[7];
7651 	char bytes_rebuilt_buf[7], bytes_est_buf[7];
7652 	char scan_rate_buf[7], issue_rate_buf[7], time_buf[32];
7653 	zfs_nicebytes(bytes_scanned, bytes_scanned_buf,
7654 	    sizeof (bytes_scanned_buf));
7655 	zfs_nicebytes(bytes_issued, bytes_issued_buf,
7656 	    sizeof (bytes_issued_buf));
7657 	zfs_nicebytes(bytes_rebuilt, bytes_rebuilt_buf,
7658 	    sizeof (bytes_rebuilt_buf));
7659 	zfs_nicebytes(bytes_est, bytes_est_buf, sizeof (bytes_est_buf));
7660 	zfs_nicebytes(scan_rate, scan_rate_buf, sizeof (scan_rate_buf));
7661 	zfs_nicebytes(issue_rate, issue_rate_buf, sizeof (issue_rate_buf));
7662 
7663 	time_t start = vrs->vrs_start_time;
7664 	time_t end = vrs->vrs_end_time;
7665 
7666 	/* Rebuild is finished or canceled. */
7667 	if (vrs->vrs_state == VDEV_REBUILD_COMPLETE) {
7668 		secs_to_dhms(vrs->vrs_scan_time_ms / 1000, time_buf);
7669 		(void) printf(gettext("resilvered (%s) %s in %s "
7670 		    "with %llu errors on %s"), vdev_name, bytes_rebuilt_buf,
7671 		    time_buf, (u_longlong_t)vrs->vrs_errors, ctime(&end));
7672 		return;
7673 	} else if (vrs->vrs_state == VDEV_REBUILD_CANCELED) {
7674 		(void) printf(gettext("resilver (%s) canceled on %s"),
7675 		    vdev_name, ctime(&end));
7676 		return;
7677 	} else if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
7678 		(void) printf(gettext("resilver (%s) in progress since %s"),
7679 		    vdev_name, ctime(&start));
7680 	}
7681 
7682 	assert(vrs->vrs_state == VDEV_REBUILD_ACTIVE);
7683 
7684 	secs_to_dhms(MAX((int64_t)bytes_est - (int64_t)bytes_scanned, 0) /
7685 	    MAX(scan_rate, 1), time_buf);
7686 
7687 	(void) printf(gettext("\t%s scanned at %s/s, %s issued %s/s, "
7688 	    "%s total\n"), bytes_scanned_buf, scan_rate_buf,
7689 	    bytes_issued_buf, issue_rate_buf, bytes_est_buf);
7690 	(void) printf(gettext("\t%s resilvered, %.2f%% done"),
7691 	    bytes_rebuilt_buf, scan_pct);
7692 
7693 	if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
7694 		if (scan_rate >= 10 * 1024 * 1024) {
7695 			(void) printf(gettext(", %s to go\n"), time_buf);
7696 		} else {
7697 			(void) printf(gettext(", no estimated "
7698 			    "completion time\n"));
7699 		}
7700 	} else {
7701 		(void) printf(gettext("\n"));
7702 	}
7703 }
7704 
7705 /*
7706  * Print rebuild status for top-level vdevs.
7707  */
7708 static void
7709 print_rebuild_status(zpool_handle_t *zhp, nvlist_t *nvroot)
7710 {
7711 	nvlist_t **child;
7712 	uint_t children;
7713 
7714 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
7715 	    &child, &children) != 0)
7716 		children = 0;
7717 
7718 	for (uint_t c = 0; c < children; c++) {
7719 		vdev_rebuild_stat_t *vrs;
7720 		uint_t i;
7721 
7722 		if (nvlist_lookup_uint64_array(child[c],
7723 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
7724 			char *name = zpool_vdev_name(g_zfs, zhp,
7725 			    child[c], VDEV_NAME_TYPE_ID);
7726 			print_rebuild_status_impl(vrs, name);
7727 			free(name);
7728 		}
7729 	}
7730 }
7731 
7732 /*
7733  * As we don't scrub checkpointed blocks, we want to warn the user that we
7734  * skipped scanning some blocks if a checkpoint exists or existed at any
7735  * time during the scan.  If a sequential instead of healing reconstruction
7736  * was performed then the blocks were reconstructed.  However, their checksums
7737  * have not been verified so we still print the warning.
7738  */
7739 static void
7740 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
7741 {
7742 	if (ps == NULL || pcs == NULL)
7743 		return;
7744 
7745 	if (pcs->pcs_state == CS_NONE ||
7746 	    pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
7747 		return;
7748 
7749 	assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
7750 
7751 	if (ps->pss_state == DSS_NONE)
7752 		return;
7753 
7754 	if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
7755 	    ps->pss_end_time < pcs->pcs_start_time)
7756 		return;
7757 
7758 	if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
7759 		(void) printf(gettext("    scan warning: skipped blocks "
7760 		    "that are only referenced by the checkpoint.\n"));
7761 	} else {
7762 		assert(ps->pss_state == DSS_SCANNING);
7763 		(void) printf(gettext("    scan warning: skipping blocks "
7764 		    "that are only referenced by the checkpoint.\n"));
7765 	}
7766 }
7767 
7768 /*
7769  * Returns B_TRUE if there is an active rebuild in progress.  Otherwise,
7770  * B_FALSE is returned and 'rebuild_end_time' is set to the end time for
7771  * the last completed (or cancelled) rebuild.
7772  */
7773 static boolean_t
7774 check_rebuilding(nvlist_t *nvroot, uint64_t *rebuild_end_time)
7775 {
7776 	nvlist_t **child;
7777 	uint_t children;
7778 	boolean_t rebuilding = B_FALSE;
7779 	uint64_t end_time = 0;
7780 
7781 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
7782 	    &child, &children) != 0)
7783 		children = 0;
7784 
7785 	for (uint_t c = 0; c < children; c++) {
7786 		vdev_rebuild_stat_t *vrs;
7787 		uint_t i;
7788 
7789 		if (nvlist_lookup_uint64_array(child[c],
7790 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
7791 
7792 			if (vrs->vrs_end_time > end_time)
7793 				end_time = vrs->vrs_end_time;
7794 
7795 			if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
7796 				rebuilding = B_TRUE;
7797 				end_time = 0;
7798 				break;
7799 			}
7800 		}
7801 	}
7802 
7803 	if (rebuild_end_time != NULL)
7804 		*rebuild_end_time = end_time;
7805 
7806 	return (rebuilding);
7807 }
7808 
7809 /*
7810  * Print the scan status.
7811  */
7812 static void
7813 print_scan_status(zpool_handle_t *zhp, nvlist_t *nvroot)
7814 {
7815 	uint64_t rebuild_end_time = 0, resilver_end_time = 0;
7816 	boolean_t have_resilver = B_FALSE, have_scrub = B_FALSE;
7817 	boolean_t active_resilver = B_FALSE;
7818 	pool_checkpoint_stat_t *pcs = NULL;
7819 	pool_scan_stat_t *ps = NULL;
7820 	uint_t c;
7821 
7822 	if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
7823 	    (uint64_t **)&ps, &c) == 0) {
7824 		if (ps->pss_func == POOL_SCAN_RESILVER) {
7825 			resilver_end_time = ps->pss_end_time;
7826 			active_resilver = (ps->pss_state == DSS_SCANNING);
7827 		}
7828 
7829 		have_resilver = (ps->pss_func == POOL_SCAN_RESILVER);
7830 		have_scrub = (ps->pss_func == POOL_SCAN_SCRUB);
7831 	}
7832 
7833 	boolean_t active_rebuild = check_rebuilding(nvroot, &rebuild_end_time);
7834 	boolean_t have_rebuild = (active_rebuild || (rebuild_end_time > 0));
7835 
7836 	/* Always print the scrub status when available. */
7837 	if (have_scrub)
7838 		print_scan_scrub_resilver_status(ps);
7839 
7840 	/*
7841 	 * When there is an active resilver or rebuild print its status.
7842 	 * Otherwise print the status of the last resilver or rebuild.
7843 	 */
7844 	if (active_resilver || (!active_rebuild && have_resilver &&
7845 	    resilver_end_time && resilver_end_time > rebuild_end_time)) {
7846 		print_scan_scrub_resilver_status(ps);
7847 	} else if (active_rebuild || (!active_resilver && have_rebuild &&
7848 	    rebuild_end_time && rebuild_end_time > resilver_end_time)) {
7849 		print_rebuild_status(zhp, nvroot);
7850 	}
7851 
7852 	(void) nvlist_lookup_uint64_array(nvroot,
7853 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
7854 	print_checkpoint_scan_warning(ps, pcs);
7855 }
7856 
7857 /*
7858  * Print out detailed removal status.
7859  */
7860 static void
7861 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
7862 {
7863 	char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
7864 	time_t start, end;
7865 	nvlist_t *config, *nvroot;
7866 	nvlist_t **child;
7867 	uint_t children;
7868 	char *vdev_name;
7869 
7870 	if (prs == NULL || prs->prs_state == DSS_NONE)
7871 		return;
7872 
7873 	/*
7874 	 * Determine name of vdev.
7875 	 */
7876 	config = zpool_get_config(zhp, NULL);
7877 	nvroot = fnvlist_lookup_nvlist(config,
7878 	    ZPOOL_CONFIG_VDEV_TREE);
7879 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
7880 	    &child, &children) == 0);
7881 	assert(prs->prs_removing_vdev < children);
7882 	vdev_name = zpool_vdev_name(g_zfs, zhp,
7883 	    child[prs->prs_removing_vdev], B_TRUE);
7884 
7885 	printf_color(ANSI_BOLD, gettext("remove: "));
7886 
7887 	start = prs->prs_start_time;
7888 	end = prs->prs_end_time;
7889 	zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
7890 
7891 	/*
7892 	 * Removal is finished or canceled.
7893 	 */
7894 	if (prs->prs_state == DSS_FINISHED) {
7895 		uint64_t minutes_taken = (end - start) / 60;
7896 
7897 		(void) printf(gettext("Removal of vdev %llu copied %s "
7898 		    "in %lluh%um, completed on %s"),
7899 		    (longlong_t)prs->prs_removing_vdev,
7900 		    copied_buf,
7901 		    (u_longlong_t)(minutes_taken / 60),
7902 		    (uint_t)(minutes_taken % 60),
7903 		    ctime((time_t *)&end));
7904 	} else if (prs->prs_state == DSS_CANCELED) {
7905 		(void) printf(gettext("Removal of %s canceled on %s"),
7906 		    vdev_name, ctime(&end));
7907 	} else {
7908 		uint64_t copied, total, elapsed, mins_left, hours_left;
7909 		double fraction_done;
7910 		uint_t rate;
7911 
7912 		assert(prs->prs_state == DSS_SCANNING);
7913 
7914 		/*
7915 		 * Removal is in progress.
7916 		 */
7917 		(void) printf(gettext(
7918 		    "Evacuation of %s in progress since %s"),
7919 		    vdev_name, ctime(&start));
7920 
7921 		copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
7922 		total = prs->prs_to_copy;
7923 		fraction_done = (double)copied / total;
7924 
7925 		/* elapsed time for this pass */
7926 		elapsed = time(NULL) - prs->prs_start_time;
7927 		elapsed = elapsed > 0 ? elapsed : 1;
7928 		rate = copied / elapsed;
7929 		rate = rate > 0 ? rate : 1;
7930 		mins_left = ((total - copied) / rate) / 60;
7931 		hours_left = mins_left / 60;
7932 
7933 		zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
7934 		zfs_nicenum(total, total_buf, sizeof (total_buf));
7935 		zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
7936 
7937 		/*
7938 		 * do not print estimated time if hours_left is more than
7939 		 * 30 days
7940 		 */
7941 		(void) printf(gettext(
7942 		    "\t%s copied out of %s at %s/s, %.2f%% done"),
7943 		    examined_buf, total_buf, rate_buf, 100 * fraction_done);
7944 		if (hours_left < (30 * 24)) {
7945 			(void) printf(gettext(", %lluh%um to go\n"),
7946 			    (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
7947 		} else {
7948 			(void) printf(gettext(
7949 			    ", (copy is slow, no estimated time)\n"));
7950 		}
7951 	}
7952 	free(vdev_name);
7953 
7954 	if (prs->prs_mapping_memory > 0) {
7955 		char mem_buf[7];
7956 		zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
7957 		(void) printf(gettext(
7958 		    "\t%s memory used for removed device mappings\n"),
7959 		    mem_buf);
7960 	}
7961 }
7962 
7963 static void
7964 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
7965 {
7966 	time_t start;
7967 	char space_buf[7];
7968 
7969 	if (pcs == NULL || pcs->pcs_state == CS_NONE)
7970 		return;
7971 
7972 	(void) printf(gettext("checkpoint: "));
7973 
7974 	start = pcs->pcs_start_time;
7975 	zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
7976 
7977 	if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
7978 		char *date = ctime(&start);
7979 
7980 		/*
7981 		 * ctime() adds a newline at the end of the generated
7982 		 * string, thus the weird format specifier and the
7983 		 * strlen() call used to chop it off from the output.
7984 		 */
7985 		(void) printf(gettext("created %.*s, consumes %s\n"),
7986 		    (int)(strlen(date) - 1), date, space_buf);
7987 		return;
7988 	}
7989 
7990 	assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
7991 
7992 	(void) printf(gettext("discarding, %s remaining.\n"),
7993 	    space_buf);
7994 }
7995 
7996 static void
7997 print_error_log(zpool_handle_t *zhp)
7998 {
7999 	nvlist_t *nverrlist = NULL;
8000 	nvpair_t *elem;
8001 	char *pathname;
8002 	size_t len = MAXPATHLEN * 2;
8003 
8004 	if (zpool_get_errlog(zhp, &nverrlist) != 0)
8005 		return;
8006 
8007 	(void) printf("errors: Permanent errors have been "
8008 	    "detected in the following files:\n\n");
8009 
8010 	pathname = safe_malloc(len);
8011 	elem = NULL;
8012 	while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
8013 		nvlist_t *nv;
8014 		uint64_t dsobj, obj;
8015 
8016 		verify(nvpair_value_nvlist(elem, &nv) == 0);
8017 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
8018 		    &dsobj) == 0);
8019 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
8020 		    &obj) == 0);
8021 		zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
8022 		(void) printf("%7s %s\n", "", pathname);
8023 	}
8024 	free(pathname);
8025 	nvlist_free(nverrlist);
8026 }
8027 
8028 static void
8029 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
8030     uint_t nspares)
8031 {
8032 	uint_t i;
8033 	char *name;
8034 
8035 	if (nspares == 0)
8036 		return;
8037 
8038 	(void) printf(gettext("\tspares\n"));
8039 
8040 	for (i = 0; i < nspares; i++) {
8041 		name = zpool_vdev_name(g_zfs, zhp, spares[i],
8042 		    cb->cb_name_flags);
8043 		print_status_config(zhp, cb, name, spares[i], 2, B_TRUE, NULL);
8044 		free(name);
8045 	}
8046 }
8047 
8048 static void
8049 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
8050     uint_t nl2cache)
8051 {
8052 	uint_t i;
8053 	char *name;
8054 
8055 	if (nl2cache == 0)
8056 		return;
8057 
8058 	(void) printf(gettext("\tcache\n"));
8059 
8060 	for (i = 0; i < nl2cache; i++) {
8061 		name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
8062 		    cb->cb_name_flags);
8063 		print_status_config(zhp, cb, name, l2cache[i], 2,
8064 		    B_FALSE, NULL);
8065 		free(name);
8066 	}
8067 }
8068 
8069 static void
8070 print_dedup_stats(nvlist_t *config)
8071 {
8072 	ddt_histogram_t *ddh;
8073 	ddt_stat_t *dds;
8074 	ddt_object_t *ddo;
8075 	uint_t c;
8076 	char dspace[6], mspace[6];
8077 
8078 	/*
8079 	 * If the pool was faulted then we may not have been able to
8080 	 * obtain the config. Otherwise, if we have anything in the dedup
8081 	 * table continue processing the stats.
8082 	 */
8083 	if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
8084 	    (uint64_t **)&ddo, &c) != 0)
8085 		return;
8086 
8087 	(void) printf("\n");
8088 	(void) printf(gettext(" dedup: "));
8089 	if (ddo->ddo_count == 0) {
8090 		(void) printf(gettext("no DDT entries\n"));
8091 		return;
8092 	}
8093 
8094 	zfs_nicebytes(ddo->ddo_dspace, dspace, sizeof (dspace));
8095 	zfs_nicebytes(ddo->ddo_mspace, mspace, sizeof (mspace));
8096 	(void) printf("DDT entries %llu, size %s on disk, %s in core\n",
8097 	    (u_longlong_t)ddo->ddo_count,
8098 	    dspace,
8099 	    mspace);
8100 
8101 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
8102 	    (uint64_t **)&dds, &c) == 0);
8103 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
8104 	    (uint64_t **)&ddh, &c) == 0);
8105 	zpool_dump_ddt(dds, ddh);
8106 }
8107 
8108 /*
8109  * Display a summary of pool status.  Displays a summary such as:
8110  *
8111  *        pool: tank
8112  *	status: DEGRADED
8113  *	reason: One or more devices ...
8114  *         see: https://openzfs.github.io/openzfs-docs/msg/ZFS-xxxx-01
8115  *	config:
8116  *		mirror		DEGRADED
8117  *                c1t0d0	OK
8118  *                c2t0d0	UNAVAIL
8119  *
8120  * When given the '-v' option, we print out the complete config.  If the '-e'
8121  * option is specified, then we print out error rate information as well.
8122  */
8123 static int
8124 status_callback(zpool_handle_t *zhp, void *data)
8125 {
8126 	status_cbdata_t *cbp = data;
8127 	nvlist_t *config, *nvroot;
8128 	const char *msgid;
8129 	zpool_status_t reason;
8130 	zpool_errata_t errata;
8131 	const char *health;
8132 	uint_t c;
8133 	vdev_stat_t *vs;
8134 
8135 	config = zpool_get_config(zhp, NULL);
8136 	reason = zpool_get_status(zhp, &msgid, &errata);
8137 
8138 	cbp->cb_count++;
8139 
8140 	/*
8141 	 * If we were given 'zpool status -x', only report those pools with
8142 	 * problems.
8143 	 */
8144 	if (cbp->cb_explain &&
8145 	    (reason == ZPOOL_STATUS_OK ||
8146 	    reason == ZPOOL_STATUS_VERSION_OLDER ||
8147 	    reason == ZPOOL_STATUS_FEAT_DISABLED ||
8148 	    reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
8149 	    reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
8150 		if (!cbp->cb_allpools) {
8151 			(void) printf(gettext("pool '%s' is healthy\n"),
8152 			    zpool_get_name(zhp));
8153 			if (cbp->cb_first)
8154 				cbp->cb_first = B_FALSE;
8155 		}
8156 		return (0);
8157 	}
8158 
8159 	if (cbp->cb_first)
8160 		cbp->cb_first = B_FALSE;
8161 	else
8162 		(void) printf("\n");
8163 
8164 	nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
8165 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
8166 	    (uint64_t **)&vs, &c) == 0);
8167 
8168 	health = zpool_get_state_str(zhp);
8169 
8170 	printf("  ");
8171 	printf_color(ANSI_BOLD, gettext("pool:"));
8172 	printf(" %s\n", zpool_get_name(zhp));
8173 	fputc(' ', stdout);
8174 	printf_color(ANSI_BOLD, gettext("state: "));
8175 
8176 	printf_color(health_str_to_color(health), "%s", health);
8177 
8178 	fputc('\n', stdout);
8179 
8180 	switch (reason) {
8181 	case ZPOOL_STATUS_MISSING_DEV_R:
8182 		printf_color(ANSI_BOLD, gettext("status: "));
8183 		printf_color(ANSI_YELLOW, gettext("One or more devices could "
8184 		    "not be opened.  Sufficient replicas exist for\n\tthe pool "
8185 		    "to continue functioning in a degraded state.\n"));
8186 		printf_color(ANSI_BOLD, gettext("action: "));
8187 		printf_color(ANSI_YELLOW, gettext("Attach the missing device "
8188 		    "and online it using 'zpool online'.\n"));
8189 		break;
8190 
8191 	case ZPOOL_STATUS_MISSING_DEV_NR:
8192 		printf_color(ANSI_BOLD, gettext("status: "));
8193 		printf_color(ANSI_YELLOW, gettext("One or more devices could "
8194 		    "not be opened.  There are insufficient\n\treplicas for the"
8195 		    " pool to continue functioning.\n"));
8196 		printf_color(ANSI_BOLD, gettext("action: "));
8197 		printf_color(ANSI_YELLOW, gettext("Attach the missing device "
8198 		    "and online it using 'zpool online'.\n"));
8199 		break;
8200 
8201 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
8202 		printf_color(ANSI_BOLD, gettext("status: "));
8203 		printf_color(ANSI_YELLOW, gettext("One or more devices could "
8204 		    "not be used because the label is missing or\n\tinvalid.  "
8205 		    "Sufficient replicas exist for the pool to continue\n\t"
8206 		    "functioning in a degraded state.\n"));
8207 		printf_color(ANSI_BOLD, gettext("action: "));
8208 		printf_color(ANSI_YELLOW, gettext("Replace the device using "
8209 		    "'zpool replace'.\n"));
8210 		break;
8211 
8212 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
8213 		printf_color(ANSI_BOLD, gettext("status: "));
8214 		printf_color(ANSI_YELLOW, gettext("One or more devices could "
8215 		    "not be used because the label is missing \n\tor invalid.  "
8216 		    "There are insufficient replicas for the pool to "
8217 		    "continue\n\tfunctioning.\n"));
8218 		zpool_explain_recover(zpool_get_handle(zhp),
8219 		    zpool_get_name(zhp), reason, config);
8220 		break;
8221 
8222 	case ZPOOL_STATUS_FAILING_DEV:
8223 		printf_color(ANSI_BOLD, gettext("status: "));
8224 		printf_color(ANSI_YELLOW, gettext("One or more devices has "
8225 		    "experienced an unrecoverable error.  An\n\tattempt was "
8226 		    "made to correct the error.  Applications are "
8227 		    "unaffected.\n"));
8228 		printf_color(ANSI_BOLD, gettext("action: "));
8229 			printf_color(ANSI_YELLOW, gettext("Determine if the "
8230 		    "device needs to be replaced, and clear the errors\n\tusing"
8231 		    " 'zpool clear' or replace the device with 'zpool "
8232 		    "replace'.\n"));
8233 		break;
8234 
8235 	case ZPOOL_STATUS_OFFLINE_DEV:
8236 		printf_color(ANSI_BOLD, gettext("status: "));
8237 		printf_color(ANSI_YELLOW, gettext("One or more devices has "
8238 		    "been taken offline by the administrator.\n\tSufficient "
8239 		    "replicas exist for the pool to continue functioning in "
8240 		    "a\n\tdegraded state.\n"));
8241 		printf_color(ANSI_BOLD, gettext("action: "));
8242 		printf_color(ANSI_YELLOW, gettext("Online the device "
8243 		    "using 'zpool online' or replace the device with\n\t'zpool "
8244 		    "replace'.\n"));
8245 		break;
8246 
8247 	case ZPOOL_STATUS_REMOVED_DEV:
8248 		printf_color(ANSI_BOLD, gettext("status: "));
8249 		printf_color(ANSI_YELLOW, gettext("One or more devices has "
8250 		    "been removed by the administrator.\n\tSufficient "
8251 		    "replicas exist for the pool to continue functioning in "
8252 		    "a\n\tdegraded state.\n"));
8253 		printf_color(ANSI_BOLD, gettext("action: "));
8254 		printf_color(ANSI_YELLOW, gettext("Online the device "
8255 		    "using zpool online' or replace the device with\n\t'zpool "
8256 		    "replace'.\n"));
8257 		break;
8258 
8259 	case ZPOOL_STATUS_RESILVERING:
8260 	case ZPOOL_STATUS_REBUILDING:
8261 		printf_color(ANSI_BOLD, gettext("status: "));
8262 		printf_color(ANSI_YELLOW, gettext("One or more devices is "
8263 		    "currently being resilvered.  The pool will\n\tcontinue "
8264 		    "to function, possibly in a degraded state.\n"));
8265 		printf_color(ANSI_BOLD, gettext("action: "));
8266 		printf_color(ANSI_YELLOW, gettext("Wait for the resilver to "
8267 		    "complete.\n"));
8268 		break;
8269 
8270 	case ZPOOL_STATUS_REBUILD_SCRUB:
8271 		printf_color(ANSI_BOLD, gettext("status: "));
8272 		printf_color(ANSI_YELLOW, gettext("One or more devices have "
8273 		    "been sequentially resilvered, scrubbing\n\tthe pool "
8274 		    "is recommended.\n"));
8275 		printf_color(ANSI_BOLD, gettext("action: "));
8276 		printf_color(ANSI_YELLOW, gettext("Use 'zpool scrub' to "
8277 		    "verify all data checksums.\n"));
8278 		break;
8279 
8280 	case ZPOOL_STATUS_CORRUPT_DATA:
8281 		printf_color(ANSI_BOLD, gettext("status: "));
8282 		printf_color(ANSI_YELLOW, gettext("One or more devices has "
8283 		    "experienced an error resulting in data\n\tcorruption.  "
8284 		    "Applications may be affected.\n"));
8285 		printf_color(ANSI_BOLD, gettext("action: "));
8286 		printf_color(ANSI_YELLOW, gettext("Restore the file in question"
8287 		    " if possible.  Otherwise restore the\n\tentire pool from "
8288 		    "backup.\n"));
8289 		break;
8290 
8291 	case ZPOOL_STATUS_CORRUPT_POOL:
8292 		printf_color(ANSI_BOLD, gettext("status: "));
8293 		printf_color(ANSI_YELLOW, gettext("The pool metadata is "
8294 		    "corrupted and the pool cannot be opened.\n"));
8295 		zpool_explain_recover(zpool_get_handle(zhp),
8296 		    zpool_get_name(zhp), reason, config);
8297 		break;
8298 
8299 	case ZPOOL_STATUS_VERSION_OLDER:
8300 		printf_color(ANSI_BOLD, gettext("status: "));
8301 		printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
8302 		    "a legacy on-disk format.  The pool can\n\tstill be used, "
8303 		    "but some features are unavailable.\n"));
8304 		printf_color(ANSI_BOLD, gettext("action: "));
8305 		printf_color(ANSI_YELLOW, gettext("Upgrade the pool using "
8306 		    "'zpool upgrade'.  Once this is done, the\n\tpool will no "
8307 		    "longer be accessible on software that does not support\n\t"
8308 		    "feature flags.\n"));
8309 		break;
8310 
8311 	case ZPOOL_STATUS_VERSION_NEWER:
8312 		printf_color(ANSI_BOLD, gettext("status: "));
8313 		printf_color(ANSI_YELLOW, gettext("The pool has been upgraded "
8314 		    "to a newer, incompatible on-disk version.\n\tThe pool "
8315 		    "cannot be accessed on this system.\n"));
8316 		printf_color(ANSI_BOLD, gettext("action: "));
8317 		printf_color(ANSI_YELLOW, gettext("Access the pool from a "
8318 		    "system running more recent software, or\n\trestore the "
8319 		    "pool from backup.\n"));
8320 		break;
8321 
8322 	case ZPOOL_STATUS_FEAT_DISABLED:
8323 		printf_color(ANSI_BOLD, gettext("status: "));
8324 		printf_color(ANSI_YELLOW, gettext("Some supported and "
8325 		    "requested features are not enabled on the pool.\n\t"
8326 		    "The pool can still be used, but some features are "
8327 		    "unavailable.\n"));
8328 		printf_color(ANSI_BOLD, gettext("action: "));
8329 		printf_color(ANSI_YELLOW, gettext("Enable all features using "
8330 		    "'zpool upgrade'. Once this is done,\n\tthe pool may no "
8331 		    "longer be accessible by software that does not support\n\t"
8332 		    "the features. See zpool-features(7) for details.\n"));
8333 		break;
8334 
8335 	case ZPOOL_STATUS_COMPATIBILITY_ERR:
8336 		printf_color(ANSI_BOLD, gettext("status: "));
8337 		printf_color(ANSI_YELLOW, gettext("This pool has a "
8338 		    "compatibility list specified, but it could not be\n\t"
8339 		    "read/parsed at this time. The pool can still be used, "
8340 		    "but this\n\tshould be investigated.\n"));
8341 		printf_color(ANSI_BOLD, gettext("action: "));
8342 		printf_color(ANSI_YELLOW, gettext("Check the value of the "
8343 		    "'compatibility' property against the\n\t"
8344 		    "appropriate file in " ZPOOL_SYSCONF_COMPAT_D " or "
8345 		    ZPOOL_DATA_COMPAT_D ".\n"));
8346 		break;
8347 
8348 	case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
8349 		printf_color(ANSI_BOLD, gettext("status: "));
8350 		printf_color(ANSI_YELLOW, gettext("One or more features "
8351 		    "are enabled on the pool despite not being\n\t"
8352 		    "requested by the 'compatibility' property.\n"));
8353 		printf_color(ANSI_BOLD, gettext("action: "));
8354 		printf_color(ANSI_YELLOW, gettext("Consider setting "
8355 		    "'compatibility' to an appropriate value, or\n\t"
8356 		    "adding needed features to the relevant file in\n\t"
8357 		    ZPOOL_SYSCONF_COMPAT_D " or " ZPOOL_DATA_COMPAT_D ".\n"));
8358 		break;
8359 
8360 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
8361 		printf_color(ANSI_BOLD, gettext("status: "));
8362 		printf_color(ANSI_YELLOW, gettext("The pool cannot be accessed "
8363 		    "on this system because it uses the\n\tfollowing feature(s)"
8364 		    " not supported on this system:\n"));
8365 		zpool_print_unsup_feat(config);
8366 		(void) printf("\n");
8367 		printf_color(ANSI_BOLD, gettext("action: "));
8368 		printf_color(ANSI_YELLOW, gettext("Access the pool from a "
8369 		    "system that supports the required feature(s),\n\tor "
8370 		    "restore the pool from backup.\n"));
8371 		break;
8372 
8373 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
8374 		printf_color(ANSI_BOLD, gettext("status: "));
8375 		printf_color(ANSI_YELLOW, gettext("The pool can only be "
8376 		    "accessed in read-only mode on this system. It\n\tcannot be"
8377 		    " accessed in read-write mode because it uses the "
8378 		    "following\n\tfeature(s) not supported on this system:\n"));
8379 		zpool_print_unsup_feat(config);
8380 		(void) printf("\n");
8381 		printf_color(ANSI_BOLD, gettext("action: "));
8382 		printf_color(ANSI_YELLOW, gettext("The pool cannot be accessed "
8383 		    "in read-write mode. Import the pool with\n"
8384 		    "\t\"-o readonly=on\", access the pool from a system that "
8385 		    "supports the\n\trequired feature(s), or restore the "
8386 		    "pool from backup.\n"));
8387 		break;
8388 
8389 	case ZPOOL_STATUS_FAULTED_DEV_R:
8390 		printf_color(ANSI_BOLD, gettext("status: "));
8391 		printf_color(ANSI_YELLOW, gettext("One or more devices are "
8392 		    "faulted in response to persistent errors.\n\tSufficient "
8393 		    "replicas exist for the pool to continue functioning "
8394 		    "in a\n\tdegraded state.\n"));
8395 		printf_color(ANSI_BOLD, gettext("action: "));
8396 		printf_color(ANSI_YELLOW, gettext("Replace the faulted device, "
8397 		    "or use 'zpool clear' to mark the device\n\trepaired.\n"));
8398 		break;
8399 
8400 	case ZPOOL_STATUS_FAULTED_DEV_NR:
8401 		printf_color(ANSI_BOLD, gettext("status: "));
8402 		printf_color(ANSI_YELLOW, gettext("One or more devices are "
8403 		    "faulted in response to persistent errors.  There are "
8404 		    "insufficient replicas for the pool to\n\tcontinue "
8405 		    "functioning.\n"));
8406 		printf_color(ANSI_BOLD, gettext("action: "));
8407 		printf_color(ANSI_YELLOW, gettext("Destroy and re-create the "
8408 		    "pool from a backup source.  Manually marking the device\n"
8409 		    "\trepaired using 'zpool clear' may allow some data "
8410 		    "to be recovered.\n"));
8411 		break;
8412 
8413 	case ZPOOL_STATUS_IO_FAILURE_MMP:
8414 		printf_color(ANSI_BOLD, gettext("status: "));
8415 		printf_color(ANSI_YELLOW, gettext("The pool is suspended "
8416 		    "because multihost writes failed or were delayed;\n\t"
8417 		    "another system could import the pool undetected.\n"));
8418 		printf_color(ANSI_BOLD, gettext("action: "));
8419 		printf_color(ANSI_YELLOW, gettext("Make sure the pool's devices"
8420 		    " are connected, then reboot your system and\n\timport the "
8421 		    "pool.\n"));
8422 		break;
8423 
8424 	case ZPOOL_STATUS_IO_FAILURE_WAIT:
8425 	case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
8426 		printf_color(ANSI_BOLD, gettext("status: "));
8427 		printf_color(ANSI_YELLOW, gettext("One or more devices are "
8428 		    "faulted in response to IO failures.\n"));
8429 		printf_color(ANSI_BOLD, gettext("action: "));
8430 		printf_color(ANSI_YELLOW, gettext("Make sure the affected "
8431 		    "devices are connected, then run 'zpool clear'.\n"));
8432 		break;
8433 
8434 	case ZPOOL_STATUS_BAD_LOG:
8435 		printf_color(ANSI_BOLD, gettext("status: "));
8436 		printf_color(ANSI_YELLOW, gettext("An intent log record "
8437 		    "could not be read.\n"
8438 		    "\tWaiting for administrator intervention to fix the "
8439 		    "faulted pool.\n"));
8440 		printf_color(ANSI_BOLD, gettext("action: "));
8441 		printf_color(ANSI_YELLOW, gettext("Either restore the affected "
8442 		    "device(s) and run 'zpool online',\n"
8443 		    "\tor ignore the intent log records by running "
8444 		    "'zpool clear'.\n"));
8445 		break;
8446 
8447 	case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
8448 		(void) printf(gettext("status: One or more devices are "
8449 		    "configured to use a non-native block size.\n"
8450 		    "\tExpect reduced performance.\n"));
8451 		(void) printf(gettext("action: Replace affected devices with "
8452 		    "devices that support the\n\tconfigured block size, or "
8453 		    "migrate data to a properly configured\n\tpool.\n"));
8454 		break;
8455 
8456 	case ZPOOL_STATUS_HOSTID_MISMATCH:
8457 		printf_color(ANSI_BOLD, gettext("status: "));
8458 		printf_color(ANSI_YELLOW, gettext("Mismatch between pool hostid"
8459 		    " and system hostid on imported pool.\n\tThis pool was "
8460 		    "previously imported into a system with a different "
8461 		    "hostid,\n\tand then was verbatim imported into this "
8462 		    "system.\n"));
8463 		printf_color(ANSI_BOLD, gettext("action: "));
8464 		printf_color(ANSI_YELLOW, gettext("Export this pool on all "
8465 		    "systems on which it is imported.\n"
8466 		    "\tThen import it to correct the mismatch.\n"));
8467 		break;
8468 
8469 	case ZPOOL_STATUS_ERRATA:
8470 		printf_color(ANSI_BOLD, gettext("status: "));
8471 		printf_color(ANSI_YELLOW, gettext("Errata #%d detected.\n"),
8472 		    errata);
8473 
8474 		switch (errata) {
8475 		case ZPOOL_ERRATA_NONE:
8476 			break;
8477 
8478 		case ZPOOL_ERRATA_ZOL_2094_SCRUB:
8479 			printf_color(ANSI_BOLD, gettext("action: "));
8480 			printf_color(ANSI_YELLOW, gettext("To correct the issue"
8481 			    " run 'zpool scrub'.\n"));
8482 			break;
8483 
8484 		case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
8485 			(void) printf(gettext("\tExisting encrypted datasets "
8486 			    "contain an on-disk incompatibility\n\twhich "
8487 			    "needs to be corrected.\n"));
8488 			printf_color(ANSI_BOLD, gettext("action: "));
8489 			printf_color(ANSI_YELLOW, gettext("To correct the issue"
8490 			    " backup existing encrypted datasets to new\n\t"
8491 			    "encrypted datasets and destroy the old ones. "
8492 			    "'zfs mount -o ro' can\n\tbe used to temporarily "
8493 			    "mount existing encrypted datasets readonly.\n"));
8494 			break;
8495 
8496 		case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
8497 			(void) printf(gettext("\tExisting encrypted snapshots "
8498 			    "and bookmarks contain an on-disk\n\tincompat"
8499 			    "ibility. This may cause on-disk corruption if "
8500 			    "they are used\n\twith 'zfs recv'.\n"));
8501 			printf_color(ANSI_BOLD, gettext("action: "));
8502 			printf_color(ANSI_YELLOW, gettext("To correct the"
8503 			    "issue, enable the bookmark_v2 feature. No "
8504 			    "additional\n\taction is needed if there are no "
8505 			    "encrypted snapshots or bookmarks.\n\tIf preserving"
8506 			    "the encrypted snapshots and bookmarks is required,"
8507 			    " use\n\ta non-raw send to backup and restore them."
8508 			    " Alternately, they may be\n\tremoved to resolve "
8509 			    "the incompatibility.\n"));
8510 			break;
8511 
8512 		default:
8513 			/*
8514 			 * All errata which allow the pool to be imported
8515 			 * must contain an action message.
8516 			 */
8517 			assert(0);
8518 		}
8519 		break;
8520 
8521 	default:
8522 		/*
8523 		 * The remaining errors can't actually be generated, yet.
8524 		 */
8525 		assert(reason == ZPOOL_STATUS_OK);
8526 	}
8527 
8528 	if (msgid != NULL) {
8529 		printf("   ");
8530 		printf_color(ANSI_BOLD, gettext("see:"));
8531 		printf(gettext(
8532 		    " https://openzfs.github.io/openzfs-docs/msg/%s\n"),
8533 		    msgid);
8534 	}
8535 
8536 	if (config != NULL) {
8537 		uint64_t nerr;
8538 		nvlist_t **spares, **l2cache;
8539 		uint_t nspares, nl2cache;
8540 		pool_checkpoint_stat_t *pcs = NULL;
8541 		pool_removal_stat_t *prs = NULL;
8542 
8543 		print_scan_status(zhp, nvroot);
8544 
8545 		(void) nvlist_lookup_uint64_array(nvroot,
8546 		    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
8547 		print_removal_status(zhp, prs);
8548 
8549 		(void) nvlist_lookup_uint64_array(nvroot,
8550 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
8551 		print_checkpoint_status(pcs);
8552 
8553 		cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
8554 		    cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
8555 		if (cbp->cb_namewidth < 10)
8556 			cbp->cb_namewidth = 10;
8557 
8558 		color_start(ANSI_BOLD);
8559 		(void) printf(gettext("config:\n\n"));
8560 		(void) printf(gettext("\t%-*s  %-8s %5s %5s %5s"),
8561 		    cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
8562 		    "CKSUM");
8563 		color_end();
8564 
8565 		if (cbp->cb_print_slow_ios) {
8566 			printf_color(ANSI_BOLD, " %5s", gettext("SLOW"));
8567 		}
8568 
8569 		if (cbp->vcdl != NULL)
8570 			print_cmd_columns(cbp->vcdl, 0);
8571 
8572 		printf("\n");
8573 
8574 		print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
8575 		    B_FALSE, NULL);
8576 
8577 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
8578 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
8579 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
8580 
8581 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
8582 		    &l2cache, &nl2cache) == 0)
8583 			print_l2cache(zhp, cbp, l2cache, nl2cache);
8584 
8585 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
8586 		    &spares, &nspares) == 0)
8587 			print_spares(zhp, cbp, spares, nspares);
8588 
8589 		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
8590 		    &nerr) == 0) {
8591 			nvlist_t *nverrlist = NULL;
8592 
8593 			/*
8594 			 * If the approximate error count is small, get a
8595 			 * precise count by fetching the entire log and
8596 			 * uniquifying the results.
8597 			 */
8598 			if (nerr > 0 && nerr < 100 && !cbp->cb_verbose &&
8599 			    zpool_get_errlog(zhp, &nverrlist) == 0) {
8600 				nvpair_t *elem;
8601 
8602 				elem = NULL;
8603 				nerr = 0;
8604 				while ((elem = nvlist_next_nvpair(nverrlist,
8605 				    elem)) != NULL) {
8606 					nerr++;
8607 				}
8608 			}
8609 			nvlist_free(nverrlist);
8610 
8611 			(void) printf("\n");
8612 
8613 			if (nerr == 0)
8614 				(void) printf(gettext("errors: No known data "
8615 				    "errors\n"));
8616 			else if (!cbp->cb_verbose)
8617 				(void) printf(gettext("errors: %llu data "
8618 				    "errors, use '-v' for a list\n"),
8619 				    (u_longlong_t)nerr);
8620 			else
8621 				print_error_log(zhp);
8622 		}
8623 
8624 		if (cbp->cb_dedup_stats)
8625 			print_dedup_stats(config);
8626 	} else {
8627 		(void) printf(gettext("config: The configuration cannot be "
8628 		    "determined.\n"));
8629 	}
8630 
8631 	return (0);
8632 }
8633 
8634 /*
8635  * zpool status [-c [script1,script2,...]] [-igLpPstvx] [-T d|u] [pool] ...
8636  *              [interval [count]]
8637  *
8638  *	-c CMD	For each vdev, run command CMD
8639  *	-i	Display vdev initialization status.
8640  *	-g	Display guid for individual vdev name.
8641  *	-L	Follow links when resolving vdev path name.
8642  *	-p	Display values in parsable (exact) format.
8643  *	-P	Display full path for vdev name.
8644  *	-s	Display slow IOs column.
8645  *	-v	Display complete error logs
8646  *	-x	Display only pools with potential problems
8647  *	-D	Display dedup status (undocumented)
8648  *	-t	Display vdev TRIM status.
8649  *	-T	Display a timestamp in date(1) or Unix format
8650  *
8651  * Describes the health status of all pools or some subset.
8652  */
8653 int
8654 zpool_do_status(int argc, char **argv)
8655 {
8656 	int c;
8657 	int ret;
8658 	float interval = 0;
8659 	unsigned long count = 0;
8660 	status_cbdata_t cb = { 0 };
8661 	char *cmd = NULL;
8662 
8663 	/* check options */
8664 	while ((c = getopt(argc, argv, "c:igLpPsvxDtT:")) != -1) {
8665 		switch (c) {
8666 		case 'c':
8667 			if (cmd != NULL) {
8668 				fprintf(stderr,
8669 				    gettext("Can't set -c flag twice\n"));
8670 				exit(1);
8671 			}
8672 
8673 			if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
8674 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
8675 				fprintf(stderr, gettext(
8676 				    "Can't run -c, disabled by "
8677 				    "ZPOOL_SCRIPTS_ENABLED.\n"));
8678 				exit(1);
8679 			}
8680 
8681 			if ((getuid() <= 0 || geteuid() <= 0) &&
8682 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
8683 				fprintf(stderr, gettext(
8684 				    "Can't run -c with root privileges "
8685 				    "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
8686 				exit(1);
8687 			}
8688 			cmd = optarg;
8689 			break;
8690 		case 'i':
8691 			cb.cb_print_vdev_init = B_TRUE;
8692 			break;
8693 		case 'g':
8694 			cb.cb_name_flags |= VDEV_NAME_GUID;
8695 			break;
8696 		case 'L':
8697 			cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
8698 			break;
8699 		case 'p':
8700 			cb.cb_literal = B_TRUE;
8701 			break;
8702 		case 'P':
8703 			cb.cb_name_flags |= VDEV_NAME_PATH;
8704 			break;
8705 		case 's':
8706 			cb.cb_print_slow_ios = B_TRUE;
8707 			break;
8708 		case 'v':
8709 			cb.cb_verbose = B_TRUE;
8710 			break;
8711 		case 'x':
8712 			cb.cb_explain = B_TRUE;
8713 			break;
8714 		case 'D':
8715 			cb.cb_dedup_stats = B_TRUE;
8716 			break;
8717 		case 't':
8718 			cb.cb_print_vdev_trim = B_TRUE;
8719 			break;
8720 		case 'T':
8721 			get_timestamp_arg(*optarg);
8722 			break;
8723 		case '?':
8724 			if (optopt == 'c') {
8725 				print_zpool_script_list("status");
8726 				exit(0);
8727 			} else {
8728 				fprintf(stderr,
8729 				    gettext("invalid option '%c'\n"), optopt);
8730 			}
8731 			usage(B_FALSE);
8732 		}
8733 	}
8734 
8735 	argc -= optind;
8736 	argv += optind;
8737 
8738 	get_interval_count(&argc, argv, &interval, &count);
8739 
8740 	if (argc == 0)
8741 		cb.cb_allpools = B_TRUE;
8742 
8743 	cb.cb_first = B_TRUE;
8744 	cb.cb_print_status = B_TRUE;
8745 
8746 	for (;;) {
8747 		if (timestamp_fmt != NODATE)
8748 			print_timestamp(timestamp_fmt);
8749 
8750 		if (cmd != NULL)
8751 			cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
8752 			    NULL, NULL, 0, 0);
8753 
8754 		ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8755 		    cb.cb_literal, status_callback, &cb);
8756 
8757 		if (cb.vcdl != NULL)
8758 			free_vdev_cmd_data_list(cb.vcdl);
8759 
8760 		if (argc == 0 && cb.cb_count == 0)
8761 			(void) fprintf(stderr, gettext("no pools available\n"));
8762 		else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
8763 			(void) printf(gettext("all pools are healthy\n"));
8764 
8765 		if (ret != 0)
8766 			return (ret);
8767 
8768 		if (interval == 0)
8769 			break;
8770 
8771 		if (count != 0 && --count == 0)
8772 			break;
8773 
8774 		(void) fsleep(interval);
8775 	}
8776 
8777 	return (0);
8778 }
8779 
8780 typedef struct upgrade_cbdata {
8781 	int	cb_first;
8782 	int	cb_argc;
8783 	uint64_t cb_version;
8784 	char	**cb_argv;
8785 } upgrade_cbdata_t;
8786 
8787 static int
8788 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
8789 {
8790 	int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
8791 	int *count = (int *)unsupp_fs;
8792 
8793 	if (zfs_version > ZPL_VERSION) {
8794 		(void) printf(gettext("%s (v%d) is not supported by this "
8795 		    "implementation of ZFS.\n"),
8796 		    zfs_get_name(zhp), zfs_version);
8797 		(*count)++;
8798 	}
8799 
8800 	zfs_iter_filesystems(zhp, check_unsupp_fs, unsupp_fs);
8801 
8802 	zfs_close(zhp);
8803 
8804 	return (0);
8805 }
8806 
8807 static int
8808 upgrade_version(zpool_handle_t *zhp, uint64_t version)
8809 {
8810 	int ret;
8811 	nvlist_t *config;
8812 	uint64_t oldversion;
8813 	int unsupp_fs = 0;
8814 
8815 	config = zpool_get_config(zhp, NULL);
8816 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
8817 	    &oldversion) == 0);
8818 
8819 	char compat[ZFS_MAXPROPLEN];
8820 	if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
8821 	    ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
8822 		compat[0] = '\0';
8823 
8824 	assert(SPA_VERSION_IS_SUPPORTED(oldversion));
8825 	assert(oldversion < version);
8826 
8827 	ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
8828 	if (ret != 0)
8829 		return (ret);
8830 
8831 	if (unsupp_fs) {
8832 		(void) fprintf(stderr, gettext("Upgrade not performed due "
8833 		    "to %d unsupported filesystems (max v%d).\n"),
8834 		    unsupp_fs, (int)ZPL_VERSION);
8835 		return (1);
8836 	}
8837 
8838 	if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
8839 		(void) fprintf(stderr, gettext("Upgrade not performed because "
8840 		    "'compatibility' property set to '"
8841 		    ZPOOL_COMPAT_LEGACY "'.\n"));
8842 		return (1);
8843 	}
8844 
8845 	ret = zpool_upgrade(zhp, version);
8846 	if (ret != 0)
8847 		return (ret);
8848 
8849 	if (version >= SPA_VERSION_FEATURES) {
8850 		(void) printf(gettext("Successfully upgraded "
8851 		    "'%s' from version %llu to feature flags.\n"),
8852 		    zpool_get_name(zhp), (u_longlong_t)oldversion);
8853 	} else {
8854 		(void) printf(gettext("Successfully upgraded "
8855 		    "'%s' from version %llu to version %llu.\n"),
8856 		    zpool_get_name(zhp), (u_longlong_t)oldversion,
8857 		    (u_longlong_t)version);
8858 	}
8859 
8860 	return (0);
8861 }
8862 
8863 static int
8864 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
8865 {
8866 	int i, ret, count;
8867 	boolean_t firstff = B_TRUE;
8868 	nvlist_t *enabled = zpool_get_features(zhp);
8869 
8870 	char compat[ZFS_MAXPROPLEN];
8871 	if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
8872 	    ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
8873 		compat[0] = '\0';
8874 
8875 	boolean_t requested_features[SPA_FEATURES];
8876 	if (zpool_do_load_compat(compat, requested_features) !=
8877 	    ZPOOL_COMPATIBILITY_OK)
8878 		return (-1);
8879 
8880 	count = 0;
8881 	for (i = 0; i < SPA_FEATURES; i++) {
8882 		const char *fname = spa_feature_table[i].fi_uname;
8883 		const char *fguid = spa_feature_table[i].fi_guid;
8884 
8885 		if (!spa_feature_table[i].fi_zfs_mod_supported)
8886 			continue;
8887 
8888 		if (!nvlist_exists(enabled, fguid) && requested_features[i]) {
8889 			char *propname;
8890 			verify(-1 != asprintf(&propname, "feature@%s", fname));
8891 			ret = zpool_set_prop(zhp, propname,
8892 			    ZFS_FEATURE_ENABLED);
8893 			if (ret != 0) {
8894 				free(propname);
8895 				return (ret);
8896 			}
8897 			count++;
8898 
8899 			if (firstff) {
8900 				(void) printf(gettext("Enabled the "
8901 				    "following features on '%s':\n"),
8902 				    zpool_get_name(zhp));
8903 				firstff = B_FALSE;
8904 			}
8905 			(void) printf(gettext("  %s\n"), fname);
8906 			free(propname);
8907 		}
8908 	}
8909 
8910 	if (countp != NULL)
8911 		*countp = count;
8912 	return (0);
8913 }
8914 
8915 static int
8916 upgrade_cb(zpool_handle_t *zhp, void *arg)
8917 {
8918 	upgrade_cbdata_t *cbp = arg;
8919 	nvlist_t *config;
8920 	uint64_t version;
8921 	boolean_t modified_pool = B_FALSE;
8922 	int ret;
8923 
8924 	config = zpool_get_config(zhp, NULL);
8925 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
8926 	    &version) == 0);
8927 
8928 	assert(SPA_VERSION_IS_SUPPORTED(version));
8929 
8930 	if (version < cbp->cb_version) {
8931 		cbp->cb_first = B_FALSE;
8932 		ret = upgrade_version(zhp, cbp->cb_version);
8933 		if (ret != 0)
8934 			return (ret);
8935 		modified_pool = B_TRUE;
8936 
8937 		/*
8938 		 * If they did "zpool upgrade -a", then we could
8939 		 * be doing ioctls to different pools.  We need
8940 		 * to log this history once to each pool, and bypass
8941 		 * the normal history logging that happens in main().
8942 		 */
8943 		(void) zpool_log_history(g_zfs, history_str);
8944 		log_history = B_FALSE;
8945 	}
8946 
8947 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
8948 		int count;
8949 		ret = upgrade_enable_all(zhp, &count);
8950 		if (ret != 0)
8951 			return (ret);
8952 
8953 		if (count > 0) {
8954 			cbp->cb_first = B_FALSE;
8955 			modified_pool = B_TRUE;
8956 		}
8957 	}
8958 
8959 	if (modified_pool) {
8960 		(void) printf("\n");
8961 		(void) after_zpool_upgrade(zhp);
8962 	}
8963 
8964 	return (0);
8965 }
8966 
8967 static int
8968 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
8969 {
8970 	upgrade_cbdata_t *cbp = arg;
8971 	nvlist_t *config;
8972 	uint64_t version;
8973 
8974 	config = zpool_get_config(zhp, NULL);
8975 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
8976 	    &version) == 0);
8977 
8978 	assert(SPA_VERSION_IS_SUPPORTED(version));
8979 
8980 	if (version < SPA_VERSION_FEATURES) {
8981 		if (cbp->cb_first) {
8982 			(void) printf(gettext("The following pools are "
8983 			    "formatted with legacy version numbers and can\n"
8984 			    "be upgraded to use feature flags.  After "
8985 			    "being upgraded, these pools\nwill no "
8986 			    "longer be accessible by software that does not "
8987 			    "support feature\nflags.\n\n"
8988 			    "Note that setting a pool's 'compatibility' "
8989 			    "feature to '" ZPOOL_COMPAT_LEGACY "' will\n"
8990 			    "inhibit upgrades.\n\n"));
8991 			(void) printf(gettext("VER  POOL\n"));
8992 			(void) printf(gettext("---  ------------\n"));
8993 			cbp->cb_first = B_FALSE;
8994 		}
8995 
8996 		(void) printf("%2llu   %s\n", (u_longlong_t)version,
8997 		    zpool_get_name(zhp));
8998 	}
8999 
9000 	return (0);
9001 }
9002 
9003 static int
9004 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
9005 {
9006 	upgrade_cbdata_t *cbp = arg;
9007 	nvlist_t *config;
9008 	uint64_t version;
9009 
9010 	config = zpool_get_config(zhp, NULL);
9011 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
9012 	    &version) == 0);
9013 
9014 	if (version >= SPA_VERSION_FEATURES) {
9015 		int i;
9016 		boolean_t poolfirst = B_TRUE;
9017 		nvlist_t *enabled = zpool_get_features(zhp);
9018 
9019 		for (i = 0; i < SPA_FEATURES; i++) {
9020 			const char *fguid = spa_feature_table[i].fi_guid;
9021 			const char *fname = spa_feature_table[i].fi_uname;
9022 
9023 			if (!spa_feature_table[i].fi_zfs_mod_supported)
9024 				continue;
9025 
9026 			if (!nvlist_exists(enabled, fguid)) {
9027 				if (cbp->cb_first) {
9028 					(void) printf(gettext("\nSome "
9029 					    "supported features are not "
9030 					    "enabled on the following pools. "
9031 					    "Once a\nfeature is enabled the "
9032 					    "pool may become incompatible with "
9033 					    "software\nthat does not support "
9034 					    "the feature. See "
9035 					    "zpool-features(7) for "
9036 					    "details.\n\n"
9037 					    "Note that the pool "
9038 					    "'compatibility' feature can be "
9039 					    "used to inhibit\nfeature "
9040 					    "upgrades.\n\n"));
9041 					(void) printf(gettext("POOL  "
9042 					    "FEATURE\n"));
9043 					(void) printf(gettext("------"
9044 					    "---------\n"));
9045 					cbp->cb_first = B_FALSE;
9046 				}
9047 
9048 				if (poolfirst) {
9049 					(void) printf(gettext("%s\n"),
9050 					    zpool_get_name(zhp));
9051 					poolfirst = B_FALSE;
9052 				}
9053 
9054 				(void) printf(gettext("      %s\n"), fname);
9055 			}
9056 			/*
9057 			 * If they did "zpool upgrade -a", then we could
9058 			 * be doing ioctls to different pools.  We need
9059 			 * to log this history once to each pool, and bypass
9060 			 * the normal history logging that happens in main().
9061 			 */
9062 			(void) zpool_log_history(g_zfs, history_str);
9063 			log_history = B_FALSE;
9064 		}
9065 	}
9066 
9067 	return (0);
9068 }
9069 
9070 static int
9071 upgrade_one(zpool_handle_t *zhp, void *data)
9072 {
9073 	boolean_t modified_pool = B_FALSE;
9074 	upgrade_cbdata_t *cbp = data;
9075 	uint64_t cur_version;
9076 	int ret;
9077 
9078 	if (strcmp("log", zpool_get_name(zhp)) == 0) {
9079 		(void) fprintf(stderr, gettext("'log' is now a reserved word\n"
9080 		    "Pool 'log' must be renamed using export and import"
9081 		    " to upgrade.\n"));
9082 		return (1);
9083 	}
9084 
9085 	cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
9086 	if (cur_version > cbp->cb_version) {
9087 		(void) printf(gettext("Pool '%s' is already formatted "
9088 		    "using more current version '%llu'.\n\n"),
9089 		    zpool_get_name(zhp), (u_longlong_t)cur_version);
9090 		return (0);
9091 	}
9092 
9093 	if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
9094 		(void) printf(gettext("Pool '%s' is already formatted "
9095 		    "using version %llu.\n\n"), zpool_get_name(zhp),
9096 		    (u_longlong_t)cbp->cb_version);
9097 		return (0);
9098 	}
9099 
9100 	if (cur_version != cbp->cb_version) {
9101 		modified_pool = B_TRUE;
9102 		ret = upgrade_version(zhp, cbp->cb_version);
9103 		if (ret != 0)
9104 			return (ret);
9105 	}
9106 
9107 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
9108 		int count = 0;
9109 		ret = upgrade_enable_all(zhp, &count);
9110 		if (ret != 0)
9111 			return (ret);
9112 
9113 		if (count != 0) {
9114 			modified_pool = B_TRUE;
9115 		} else if (cur_version == SPA_VERSION) {
9116 			(void) printf(gettext("Pool '%s' already has all "
9117 			    "supported and requested features enabled.\n"),
9118 			    zpool_get_name(zhp));
9119 		}
9120 	}
9121 
9122 	if (modified_pool) {
9123 		(void) printf("\n");
9124 		(void) after_zpool_upgrade(zhp);
9125 	}
9126 
9127 	return (0);
9128 }
9129 
9130 /*
9131  * zpool upgrade
9132  * zpool upgrade -v
9133  * zpool upgrade [-V version] <-a | pool ...>
9134  *
9135  * With no arguments, display downrev'd ZFS pool available for upgrade.
9136  * Individual pools can be upgraded by specifying the pool, and '-a' will
9137  * upgrade all pools.
9138  */
9139 int
9140 zpool_do_upgrade(int argc, char **argv)
9141 {
9142 	int c;
9143 	upgrade_cbdata_t cb = { 0 };
9144 	int ret = 0;
9145 	boolean_t showversions = B_FALSE;
9146 	boolean_t upgradeall = B_FALSE;
9147 	char *end;
9148 
9149 
9150 	/* check options */
9151 	while ((c = getopt(argc, argv, ":avV:")) != -1) {
9152 		switch (c) {
9153 		case 'a':
9154 			upgradeall = B_TRUE;
9155 			break;
9156 		case 'v':
9157 			showversions = B_TRUE;
9158 			break;
9159 		case 'V':
9160 			cb.cb_version = strtoll(optarg, &end, 10);
9161 			if (*end != '\0' ||
9162 			    !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
9163 				(void) fprintf(stderr,
9164 				    gettext("invalid version '%s'\n"), optarg);
9165 				usage(B_FALSE);
9166 			}
9167 			break;
9168 		case ':':
9169 			(void) fprintf(stderr, gettext("missing argument for "
9170 			    "'%c' option\n"), optopt);
9171 			usage(B_FALSE);
9172 			break;
9173 		case '?':
9174 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
9175 			    optopt);
9176 			usage(B_FALSE);
9177 		}
9178 	}
9179 
9180 	cb.cb_argc = argc;
9181 	cb.cb_argv = argv;
9182 	argc -= optind;
9183 	argv += optind;
9184 
9185 	if (cb.cb_version == 0) {
9186 		cb.cb_version = SPA_VERSION;
9187 	} else if (!upgradeall && argc == 0) {
9188 		(void) fprintf(stderr, gettext("-V option is "
9189 		    "incompatible with other arguments\n"));
9190 		usage(B_FALSE);
9191 	}
9192 
9193 	if (showversions) {
9194 		if (upgradeall || argc != 0) {
9195 			(void) fprintf(stderr, gettext("-v option is "
9196 			    "incompatible with other arguments\n"));
9197 			usage(B_FALSE);
9198 		}
9199 	} else if (upgradeall) {
9200 		if (argc != 0) {
9201 			(void) fprintf(stderr, gettext("-a option should not "
9202 			    "be used along with a pool name\n"));
9203 			usage(B_FALSE);
9204 		}
9205 	}
9206 
9207 	(void) printf("%s", gettext("This system supports ZFS pool feature "
9208 	    "flags.\n\n"));
9209 	if (showversions) {
9210 		int i;
9211 
9212 		(void) printf(gettext("The following features are "
9213 		    "supported:\n\n"));
9214 		(void) printf(gettext("FEAT DESCRIPTION\n"));
9215 		(void) printf("----------------------------------------------"
9216 		    "---------------\n");
9217 		for (i = 0; i < SPA_FEATURES; i++) {
9218 			zfeature_info_t *fi = &spa_feature_table[i];
9219 			if (!fi->fi_zfs_mod_supported)
9220 				continue;
9221 			const char *ro =
9222 			    (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
9223 			    " (read-only compatible)" : "";
9224 
9225 			(void) printf("%-37s%s\n", fi->fi_uname, ro);
9226 			(void) printf("     %s\n", fi->fi_desc);
9227 		}
9228 		(void) printf("\n");
9229 
9230 		(void) printf(gettext("The following legacy versions are also "
9231 		    "supported:\n\n"));
9232 		(void) printf(gettext("VER  DESCRIPTION\n"));
9233 		(void) printf("---  -----------------------------------------"
9234 		    "---------------\n");
9235 		(void) printf(gettext(" 1   Initial ZFS version\n"));
9236 		(void) printf(gettext(" 2   Ditto blocks "
9237 		    "(replicated metadata)\n"));
9238 		(void) printf(gettext(" 3   Hot spares and double parity "
9239 		    "RAID-Z\n"));
9240 		(void) printf(gettext(" 4   zpool history\n"));
9241 		(void) printf(gettext(" 5   Compression using the gzip "
9242 		    "algorithm\n"));
9243 		(void) printf(gettext(" 6   bootfs pool property\n"));
9244 		(void) printf(gettext(" 7   Separate intent log devices\n"));
9245 		(void) printf(gettext(" 8   Delegated administration\n"));
9246 		(void) printf(gettext(" 9   refquota and refreservation "
9247 		    "properties\n"));
9248 		(void) printf(gettext(" 10  Cache devices\n"));
9249 		(void) printf(gettext(" 11  Improved scrub performance\n"));
9250 		(void) printf(gettext(" 12  Snapshot properties\n"));
9251 		(void) printf(gettext(" 13  snapused property\n"));
9252 		(void) printf(gettext(" 14  passthrough-x aclinherit\n"));
9253 		(void) printf(gettext(" 15  user/group space accounting\n"));
9254 		(void) printf(gettext(" 16  stmf property support\n"));
9255 		(void) printf(gettext(" 17  Triple-parity RAID-Z\n"));
9256 		(void) printf(gettext(" 18  Snapshot user holds\n"));
9257 		(void) printf(gettext(" 19  Log device removal\n"));
9258 		(void) printf(gettext(" 20  Compression using zle "
9259 		    "(zero-length encoding)\n"));
9260 		(void) printf(gettext(" 21  Deduplication\n"));
9261 		(void) printf(gettext(" 22  Received properties\n"));
9262 		(void) printf(gettext(" 23  Slim ZIL\n"));
9263 		(void) printf(gettext(" 24  System attributes\n"));
9264 		(void) printf(gettext(" 25  Improved scrub stats\n"));
9265 		(void) printf(gettext(" 26  Improved snapshot deletion "
9266 		    "performance\n"));
9267 		(void) printf(gettext(" 27  Improved snapshot creation "
9268 		    "performance\n"));
9269 		(void) printf(gettext(" 28  Multiple vdev replacements\n"));
9270 		(void) printf(gettext("\nFor more information on a particular "
9271 		    "version, including supported releases,\n"));
9272 		(void) printf(gettext("see the ZFS Administration Guide.\n\n"));
9273 	} else if (argc == 0 && upgradeall) {
9274 		cb.cb_first = B_TRUE;
9275 		ret = zpool_iter(g_zfs, upgrade_cb, &cb);
9276 		if (ret == 0 && cb.cb_first) {
9277 			if (cb.cb_version == SPA_VERSION) {
9278 				(void) printf(gettext("All pools are already "
9279 				    "formatted using feature flags.\n\n"));
9280 				(void) printf(gettext("Every feature flags "
9281 				    "pool already has all supported and "
9282 				    "requested features enabled.\n"));
9283 			} else {
9284 				(void) printf(gettext("All pools are already "
9285 				    "formatted with version %llu or higher.\n"),
9286 				    (u_longlong_t)cb.cb_version);
9287 			}
9288 		}
9289 	} else if (argc == 0) {
9290 		cb.cb_first = B_TRUE;
9291 		ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
9292 		assert(ret == 0);
9293 
9294 		if (cb.cb_first) {
9295 			(void) printf(gettext("All pools are formatted "
9296 			    "using feature flags.\n\n"));
9297 		} else {
9298 			(void) printf(gettext("\nUse 'zpool upgrade -v' "
9299 			    "for a list of available legacy versions.\n"));
9300 		}
9301 
9302 		cb.cb_first = B_TRUE;
9303 		ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
9304 		assert(ret == 0);
9305 
9306 		if (cb.cb_first) {
9307 			(void) printf(gettext("Every feature flags pool has "
9308 			    "all supported and requested features enabled.\n"));
9309 		} else {
9310 			(void) printf(gettext("\n"));
9311 		}
9312 	} else {
9313 		ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9314 		    B_FALSE, upgrade_one, &cb);
9315 	}
9316 
9317 	return (ret);
9318 }
9319 
9320 typedef struct hist_cbdata {
9321 	boolean_t first;
9322 	boolean_t longfmt;
9323 	boolean_t internal;
9324 } hist_cbdata_t;
9325 
9326 static void
9327 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
9328 {
9329 	nvlist_t **records;
9330 	uint_t numrecords;
9331 	int i;
9332 
9333 	verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
9334 	    &records, &numrecords) == 0);
9335 	for (i = 0; i < numrecords; i++) {
9336 		nvlist_t *rec = records[i];
9337 		char tbuf[64] = "";
9338 
9339 		if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
9340 			time_t tsec;
9341 			struct tm t;
9342 
9343 			tsec = fnvlist_lookup_uint64(records[i],
9344 			    ZPOOL_HIST_TIME);
9345 			(void) localtime_r(&tsec, &t);
9346 			(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
9347 		}
9348 
9349 		if (nvlist_exists(rec, ZPOOL_HIST_ELAPSED_NS)) {
9350 			uint64_t elapsed_ns = fnvlist_lookup_int64(records[i],
9351 			    ZPOOL_HIST_ELAPSED_NS);
9352 			(void) snprintf(tbuf + strlen(tbuf),
9353 			    sizeof (tbuf) - strlen(tbuf),
9354 			    " (%lldms)", (long long)elapsed_ns / 1000 / 1000);
9355 		}
9356 
9357 		if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
9358 			(void) printf("%s %s", tbuf,
9359 			    fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
9360 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
9361 			int ievent =
9362 			    fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
9363 			if (!cb->internal)
9364 				continue;
9365 			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
9366 				(void) printf("%s unrecognized record:\n",
9367 				    tbuf);
9368 				dump_nvlist(rec, 4);
9369 				continue;
9370 			}
9371 			(void) printf("%s [internal %s txg:%lld] %s", tbuf,
9372 			    zfs_history_event_names[ievent],
9373 			    (longlong_t)fnvlist_lookup_uint64(
9374 			    rec, ZPOOL_HIST_TXG),
9375 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
9376 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
9377 			if (!cb->internal)
9378 				continue;
9379 			(void) printf("%s [txg:%lld] %s", tbuf,
9380 			    (longlong_t)fnvlist_lookup_uint64(
9381 			    rec, ZPOOL_HIST_TXG),
9382 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
9383 			if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
9384 				(void) printf(" %s (%llu)",
9385 				    fnvlist_lookup_string(rec,
9386 				    ZPOOL_HIST_DSNAME),
9387 				    (u_longlong_t)fnvlist_lookup_uint64(rec,
9388 				    ZPOOL_HIST_DSID));
9389 			}
9390 			(void) printf(" %s", fnvlist_lookup_string(rec,
9391 			    ZPOOL_HIST_INT_STR));
9392 		} else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
9393 			if (!cb->internal)
9394 				continue;
9395 			(void) printf("%s ioctl %s\n", tbuf,
9396 			    fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
9397 			if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
9398 				(void) printf("    input:\n");
9399 				dump_nvlist(fnvlist_lookup_nvlist(rec,
9400 				    ZPOOL_HIST_INPUT_NVL), 8);
9401 			}
9402 			if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
9403 				(void) printf("    output:\n");
9404 				dump_nvlist(fnvlist_lookup_nvlist(rec,
9405 				    ZPOOL_HIST_OUTPUT_NVL), 8);
9406 			}
9407 			if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_SIZE)) {
9408 				(void) printf("    output nvlist omitted; "
9409 				    "original size: %lldKB\n",
9410 				    (longlong_t)fnvlist_lookup_int64(rec,
9411 				    ZPOOL_HIST_OUTPUT_SIZE) / 1024);
9412 			}
9413 			if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
9414 				(void) printf("    errno: %lld\n",
9415 				    (longlong_t)fnvlist_lookup_int64(rec,
9416 				    ZPOOL_HIST_ERRNO));
9417 			}
9418 		} else {
9419 			if (!cb->internal)
9420 				continue;
9421 			(void) printf("%s unrecognized record:\n", tbuf);
9422 			dump_nvlist(rec, 4);
9423 		}
9424 
9425 		if (!cb->longfmt) {
9426 			(void) printf("\n");
9427 			continue;
9428 		}
9429 		(void) printf(" [");
9430 		if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
9431 			uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
9432 			struct passwd *pwd = getpwuid(who);
9433 			(void) printf("user %d ", (int)who);
9434 			if (pwd != NULL)
9435 				(void) printf("(%s) ", pwd->pw_name);
9436 		}
9437 		if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
9438 			(void) printf("on %s",
9439 			    fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
9440 		}
9441 		if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
9442 			(void) printf(":%s",
9443 			    fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
9444 		}
9445 
9446 		(void) printf("]");
9447 		(void) printf("\n");
9448 	}
9449 }
9450 
9451 /*
9452  * Print out the command history for a specific pool.
9453  */
9454 static int
9455 get_history_one(zpool_handle_t *zhp, void *data)
9456 {
9457 	nvlist_t *nvhis;
9458 	int ret;
9459 	hist_cbdata_t *cb = (hist_cbdata_t *)data;
9460 	uint64_t off = 0;
9461 	boolean_t eof = B_FALSE;
9462 
9463 	cb->first = B_FALSE;
9464 
9465 	(void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
9466 
9467 	while (!eof) {
9468 		if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
9469 			return (ret);
9470 
9471 		print_history_records(nvhis, cb);
9472 		nvlist_free(nvhis);
9473 	}
9474 	(void) printf("\n");
9475 
9476 	return (ret);
9477 }
9478 
9479 /*
9480  * zpool history <pool>
9481  *
9482  * Displays the history of commands that modified pools.
9483  */
9484 int
9485 zpool_do_history(int argc, char **argv)
9486 {
9487 	hist_cbdata_t cbdata = { 0 };
9488 	int ret;
9489 	int c;
9490 
9491 	cbdata.first = B_TRUE;
9492 	/* check options */
9493 	while ((c = getopt(argc, argv, "li")) != -1) {
9494 		switch (c) {
9495 		case 'l':
9496 			cbdata.longfmt = B_TRUE;
9497 			break;
9498 		case 'i':
9499 			cbdata.internal = B_TRUE;
9500 			break;
9501 		case '?':
9502 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
9503 			    optopt);
9504 			usage(B_FALSE);
9505 		}
9506 	}
9507 	argc -= optind;
9508 	argv += optind;
9509 
9510 	ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9511 	    B_FALSE, get_history_one, &cbdata);
9512 
9513 	if (argc == 0 && cbdata.first == B_TRUE) {
9514 		(void) fprintf(stderr, gettext("no pools available\n"));
9515 		return (0);
9516 	}
9517 
9518 	return (ret);
9519 }
9520 
9521 typedef struct ev_opts {
9522 	int verbose;
9523 	int scripted;
9524 	int follow;
9525 	int clear;
9526 	char poolname[ZFS_MAX_DATASET_NAME_LEN];
9527 } ev_opts_t;
9528 
9529 static void
9530 zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
9531 {
9532 	char ctime_str[26], str[32], *ptr;
9533 	int64_t *tv;
9534 	uint_t n;
9535 
9536 	verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
9537 	memset(str, ' ', 32);
9538 	(void) ctime_r((const time_t *)&tv[0], ctime_str);
9539 	(void) memcpy(str, ctime_str+4,  6);		/* 'Jun 30' */
9540 	(void) memcpy(str+7, ctime_str+20, 4);		/* '1993' */
9541 	(void) memcpy(str+12, ctime_str+11, 8);		/* '21:49:08' */
9542 	(void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
9543 	if (opts->scripted)
9544 		(void) printf(gettext("%s\t"), str);
9545 	else
9546 		(void) printf(gettext("%s "), str);
9547 
9548 	verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
9549 	(void) printf(gettext("%s\n"), ptr);
9550 }
9551 
9552 static void
9553 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
9554 {
9555 	nvpair_t *nvp;
9556 
9557 	for (nvp = nvlist_next_nvpair(nvl, NULL);
9558 	    nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
9559 
9560 		data_type_t type = nvpair_type(nvp);
9561 		const char *name = nvpair_name(nvp);
9562 
9563 		boolean_t b;
9564 		uint8_t i8;
9565 		uint16_t i16;
9566 		uint32_t i32;
9567 		uint64_t i64;
9568 		char *str;
9569 		nvlist_t *cnv;
9570 
9571 		printf(gettext("%*s%s = "), depth, "", name);
9572 
9573 		switch (type) {
9574 		case DATA_TYPE_BOOLEAN:
9575 			printf(gettext("%s"), "1");
9576 			break;
9577 
9578 		case DATA_TYPE_BOOLEAN_VALUE:
9579 			(void) nvpair_value_boolean_value(nvp, &b);
9580 			printf(gettext("%s"), b ? "1" : "0");
9581 			break;
9582 
9583 		case DATA_TYPE_BYTE:
9584 			(void) nvpair_value_byte(nvp, &i8);
9585 			printf(gettext("0x%x"), i8);
9586 			break;
9587 
9588 		case DATA_TYPE_INT8:
9589 			(void) nvpair_value_int8(nvp, (void *)&i8);
9590 			printf(gettext("0x%x"), i8);
9591 			break;
9592 
9593 		case DATA_TYPE_UINT8:
9594 			(void) nvpair_value_uint8(nvp, &i8);
9595 			printf(gettext("0x%x"), i8);
9596 			break;
9597 
9598 		case DATA_TYPE_INT16:
9599 			(void) nvpair_value_int16(nvp, (void *)&i16);
9600 			printf(gettext("0x%x"), i16);
9601 			break;
9602 
9603 		case DATA_TYPE_UINT16:
9604 			(void) nvpair_value_uint16(nvp, &i16);
9605 			printf(gettext("0x%x"), i16);
9606 			break;
9607 
9608 		case DATA_TYPE_INT32:
9609 			(void) nvpair_value_int32(nvp, (void *)&i32);
9610 			printf(gettext("0x%x"), i32);
9611 			break;
9612 
9613 		case DATA_TYPE_UINT32:
9614 			(void) nvpair_value_uint32(nvp, &i32);
9615 			printf(gettext("0x%x"), i32);
9616 			break;
9617 
9618 		case DATA_TYPE_INT64:
9619 			(void) nvpair_value_int64(nvp, (void *)&i64);
9620 			printf(gettext("0x%llx"), (u_longlong_t)i64);
9621 			break;
9622 
9623 		case DATA_TYPE_UINT64:
9624 			(void) nvpair_value_uint64(nvp, &i64);
9625 			/*
9626 			 * translate vdev state values to readable
9627 			 * strings to aide zpool events consumers
9628 			 */
9629 			if (strcmp(name,
9630 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
9631 			    strcmp(name,
9632 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
9633 				printf(gettext("\"%s\" (0x%llx)"),
9634 				    zpool_state_to_name(i64, VDEV_AUX_NONE),
9635 				    (u_longlong_t)i64);
9636 			} else {
9637 				printf(gettext("0x%llx"), (u_longlong_t)i64);
9638 			}
9639 			break;
9640 
9641 		case DATA_TYPE_HRTIME:
9642 			(void) nvpair_value_hrtime(nvp, (void *)&i64);
9643 			printf(gettext("0x%llx"), (u_longlong_t)i64);
9644 			break;
9645 
9646 		case DATA_TYPE_STRING:
9647 			(void) nvpair_value_string(nvp, &str);
9648 			printf(gettext("\"%s\""), str ? str : "<NULL>");
9649 			break;
9650 
9651 		case DATA_TYPE_NVLIST:
9652 			printf(gettext("(embedded nvlist)\n"));
9653 			(void) nvpair_value_nvlist(nvp, &cnv);
9654 			zpool_do_events_nvprint(cnv, depth + 8);
9655 			printf(gettext("%*s(end %s)"), depth, "", name);
9656 			break;
9657 
9658 		case DATA_TYPE_NVLIST_ARRAY: {
9659 			nvlist_t **val;
9660 			uint_t i, nelem;
9661 
9662 			(void) nvpair_value_nvlist_array(nvp, &val, &nelem);
9663 			printf(gettext("(%d embedded nvlists)\n"), nelem);
9664 			for (i = 0; i < nelem; i++) {
9665 				printf(gettext("%*s%s[%d] = %s\n"),
9666 				    depth, "", name, i, "(embedded nvlist)");
9667 				zpool_do_events_nvprint(val[i], depth + 8);
9668 				printf(gettext("%*s(end %s[%i])\n"),
9669 				    depth, "", name, i);
9670 			}
9671 			printf(gettext("%*s(end %s)\n"), depth, "", name);
9672 			}
9673 			break;
9674 
9675 		case DATA_TYPE_INT8_ARRAY: {
9676 			int8_t *val;
9677 			uint_t i, nelem;
9678 
9679 			(void) nvpair_value_int8_array(nvp, &val, &nelem);
9680 			for (i = 0; i < nelem; i++)
9681 				printf(gettext("0x%x "), val[i]);
9682 
9683 			break;
9684 			}
9685 
9686 		case DATA_TYPE_UINT8_ARRAY: {
9687 			uint8_t *val;
9688 			uint_t i, nelem;
9689 
9690 			(void) nvpair_value_uint8_array(nvp, &val, &nelem);
9691 			for (i = 0; i < nelem; i++)
9692 				printf(gettext("0x%x "), val[i]);
9693 
9694 			break;
9695 			}
9696 
9697 		case DATA_TYPE_INT16_ARRAY: {
9698 			int16_t *val;
9699 			uint_t i, nelem;
9700 
9701 			(void) nvpair_value_int16_array(nvp, &val, &nelem);
9702 			for (i = 0; i < nelem; i++)
9703 				printf(gettext("0x%x "), val[i]);
9704 
9705 			break;
9706 			}
9707 
9708 		case DATA_TYPE_UINT16_ARRAY: {
9709 			uint16_t *val;
9710 			uint_t i, nelem;
9711 
9712 			(void) nvpair_value_uint16_array(nvp, &val, &nelem);
9713 			for (i = 0; i < nelem; i++)
9714 				printf(gettext("0x%x "), val[i]);
9715 
9716 			break;
9717 			}
9718 
9719 		case DATA_TYPE_INT32_ARRAY: {
9720 			int32_t *val;
9721 			uint_t i, nelem;
9722 
9723 			(void) nvpair_value_int32_array(nvp, &val, &nelem);
9724 			for (i = 0; i < nelem; i++)
9725 				printf(gettext("0x%x "), val[i]);
9726 
9727 			break;
9728 			}
9729 
9730 		case DATA_TYPE_UINT32_ARRAY: {
9731 			uint32_t *val;
9732 			uint_t i, nelem;
9733 
9734 			(void) nvpair_value_uint32_array(nvp, &val, &nelem);
9735 			for (i = 0; i < nelem; i++)
9736 				printf(gettext("0x%x "), val[i]);
9737 
9738 			break;
9739 			}
9740 
9741 		case DATA_TYPE_INT64_ARRAY: {
9742 			int64_t *val;
9743 			uint_t i, nelem;
9744 
9745 			(void) nvpair_value_int64_array(nvp, &val, &nelem);
9746 			for (i = 0; i < nelem; i++)
9747 				printf(gettext("0x%llx "),
9748 				    (u_longlong_t)val[i]);
9749 
9750 			break;
9751 			}
9752 
9753 		case DATA_TYPE_UINT64_ARRAY: {
9754 			uint64_t *val;
9755 			uint_t i, nelem;
9756 
9757 			(void) nvpair_value_uint64_array(nvp, &val, &nelem);
9758 			for (i = 0; i < nelem; i++)
9759 				printf(gettext("0x%llx "),
9760 				    (u_longlong_t)val[i]);
9761 
9762 			break;
9763 			}
9764 
9765 		case DATA_TYPE_STRING_ARRAY: {
9766 			char **str;
9767 			uint_t i, nelem;
9768 
9769 			(void) nvpair_value_string_array(nvp, &str, &nelem);
9770 			for (i = 0; i < nelem; i++)
9771 				printf(gettext("\"%s\" "),
9772 				    str[i] ? str[i] : "<NULL>");
9773 
9774 			break;
9775 			}
9776 
9777 		case DATA_TYPE_BOOLEAN_ARRAY:
9778 		case DATA_TYPE_BYTE_ARRAY:
9779 		case DATA_TYPE_DOUBLE:
9780 		case DATA_TYPE_DONTCARE:
9781 		case DATA_TYPE_UNKNOWN:
9782 			printf(gettext("<unknown>"));
9783 			break;
9784 		}
9785 
9786 		printf(gettext("\n"));
9787 	}
9788 }
9789 
9790 static int
9791 zpool_do_events_next(ev_opts_t *opts)
9792 {
9793 	nvlist_t *nvl;
9794 	int zevent_fd, ret, dropped;
9795 	char *pool;
9796 
9797 	zevent_fd = open(ZFS_DEV, O_RDWR);
9798 	VERIFY(zevent_fd >= 0);
9799 
9800 	if (!opts->scripted)
9801 		(void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
9802 
9803 	while (1) {
9804 		ret = zpool_events_next(g_zfs, &nvl, &dropped,
9805 		    (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
9806 		if (ret || nvl == NULL)
9807 			break;
9808 
9809 		if (dropped > 0)
9810 			(void) printf(gettext("dropped %d events\n"), dropped);
9811 
9812 		if (strlen(opts->poolname) > 0 &&
9813 		    nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
9814 		    strcmp(opts->poolname, pool) != 0)
9815 			continue;
9816 
9817 		zpool_do_events_short(nvl, opts);
9818 
9819 		if (opts->verbose) {
9820 			zpool_do_events_nvprint(nvl, 8);
9821 			printf(gettext("\n"));
9822 		}
9823 		(void) fflush(stdout);
9824 
9825 		nvlist_free(nvl);
9826 	}
9827 
9828 	VERIFY(0 == close(zevent_fd));
9829 
9830 	return (ret);
9831 }
9832 
9833 static int
9834 zpool_do_events_clear(void)
9835 {
9836 	int count, ret;
9837 
9838 	ret = zpool_events_clear(g_zfs, &count);
9839 	if (!ret)
9840 		(void) printf(gettext("cleared %d events\n"), count);
9841 
9842 	return (ret);
9843 }
9844 
9845 /*
9846  * zpool events [-vHf [pool] | -c]
9847  *
9848  * Displays events logs by ZFS.
9849  */
9850 int
9851 zpool_do_events(int argc, char **argv)
9852 {
9853 	ev_opts_t opts = { 0 };
9854 	int ret;
9855 	int c;
9856 
9857 	/* check options */
9858 	while ((c = getopt(argc, argv, "vHfc")) != -1) {
9859 		switch (c) {
9860 		case 'v':
9861 			opts.verbose = 1;
9862 			break;
9863 		case 'H':
9864 			opts.scripted = 1;
9865 			break;
9866 		case 'f':
9867 			opts.follow = 1;
9868 			break;
9869 		case 'c':
9870 			opts.clear = 1;
9871 			break;
9872 		case '?':
9873 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
9874 			    optopt);
9875 			usage(B_FALSE);
9876 		}
9877 	}
9878 	argc -= optind;
9879 	argv += optind;
9880 
9881 	if (argc > 1) {
9882 		(void) fprintf(stderr, gettext("too many arguments\n"));
9883 		usage(B_FALSE);
9884 	} else if (argc == 1) {
9885 		(void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
9886 		if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
9887 			(void) fprintf(stderr,
9888 			    gettext("invalid pool name '%s'\n"), opts.poolname);
9889 			usage(B_FALSE);
9890 		}
9891 	}
9892 
9893 	if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
9894 	    opts.clear) {
9895 		(void) fprintf(stderr,
9896 		    gettext("invalid options combined with -c\n"));
9897 		usage(B_FALSE);
9898 	}
9899 
9900 	if (opts.clear)
9901 		ret = zpool_do_events_clear();
9902 	else
9903 		ret = zpool_do_events_next(&opts);
9904 
9905 	return (ret);
9906 }
9907 
9908 static int
9909 get_callback_vdev(zpool_handle_t *zhp, char *vdevname, void *data)
9910 {
9911 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
9912 	char value[ZFS_MAXPROPLEN];
9913 	zprop_source_t srctype;
9914 
9915 	for (zprop_list_t *pl = cbp->cb_proplist; pl != NULL;
9916 	    pl = pl->pl_next) {
9917 		char *prop_name;
9918 		/*
9919 		 * If the first property is pool name, it is a special
9920 		 * placeholder that we can skip. This will also skip
9921 		 * over the name property when 'all' is specified.
9922 		 */
9923 		if (pl->pl_prop == ZPOOL_PROP_NAME &&
9924 		    pl == cbp->cb_proplist)
9925 			continue;
9926 
9927 		if (pl->pl_prop == ZPROP_INVAL) {
9928 			prop_name = pl->pl_user_prop;
9929 		} else {
9930 			prop_name = (char *)vdev_prop_to_name(pl->pl_prop);
9931 		}
9932 		if (zpool_get_vdev_prop(zhp, vdevname, pl->pl_prop,
9933 		    prop_name, value, sizeof (value), &srctype,
9934 		    cbp->cb_literal) == 0) {
9935 			zprop_print_one_property(vdevname, cbp, prop_name,
9936 			    value, srctype, NULL, NULL);
9937 		}
9938 	}
9939 
9940 	return (0);
9941 }
9942 
9943 static int
9944 get_callback_vdev_width_cb(void *zhp_data, nvlist_t *nv, void *data)
9945 {
9946 	zpool_handle_t *zhp = zhp_data;
9947 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
9948 	char *vdevname = zpool_vdev_name(g_zfs, zhp, nv,
9949 	    cbp->cb_vdevs.cb_name_flags);
9950 	int ret;
9951 
9952 	/* Adjust the column widths for the vdev properties */
9953 	ret = vdev_expand_proplist(zhp, vdevname, &cbp->cb_proplist);
9954 
9955 	return (ret);
9956 }
9957 
9958 static int
9959 get_callback_vdev_cb(void *zhp_data, nvlist_t *nv, void *data)
9960 {
9961 	zpool_handle_t *zhp = zhp_data;
9962 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
9963 	char *vdevname = zpool_vdev_name(g_zfs, zhp, nv,
9964 	    cbp->cb_vdevs.cb_name_flags);
9965 	int ret;
9966 
9967 	/* Display the properties */
9968 	ret = get_callback_vdev(zhp, vdevname, data);
9969 
9970 	return (ret);
9971 }
9972 
9973 static int
9974 get_callback(zpool_handle_t *zhp, void *data)
9975 {
9976 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
9977 	char value[MAXNAMELEN];
9978 	zprop_source_t srctype;
9979 	zprop_list_t *pl;
9980 	int vid;
9981 
9982 	if (cbp->cb_type == ZFS_TYPE_VDEV) {
9983 		if (strcmp(cbp->cb_vdevs.cb_names[0], "all-vdevs") == 0) {
9984 			for_each_vdev(zhp, get_callback_vdev_width_cb, data);
9985 			for_each_vdev(zhp, get_callback_vdev_cb, data);
9986 		} else {
9987 			/* Adjust column widths for vdev properties */
9988 			for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
9989 			    vid++) {
9990 				vdev_expand_proplist(zhp,
9991 				    cbp->cb_vdevs.cb_names[vid],
9992 				    &cbp->cb_proplist);
9993 			}
9994 			/* Display the properties */
9995 			for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
9996 			    vid++) {
9997 				get_callback_vdev(zhp,
9998 				    cbp->cb_vdevs.cb_names[vid], data);
9999 			}
10000 		}
10001 	} else {
10002 		assert(cbp->cb_type == ZFS_TYPE_POOL);
10003 		for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
10004 			/*
10005 			 * Skip the special fake placeholder. This will also
10006 			 * skip over the name property when 'all' is specified.
10007 			 */
10008 			if (pl->pl_prop == ZPOOL_PROP_NAME &&
10009 			    pl == cbp->cb_proplist)
10010 				continue;
10011 
10012 			if (pl->pl_prop == ZPROP_INVAL &&
10013 			    (zpool_prop_feature(pl->pl_user_prop) ||
10014 			    zpool_prop_unsupported(pl->pl_user_prop))) {
10015 				srctype = ZPROP_SRC_LOCAL;
10016 
10017 				if (zpool_prop_get_feature(zhp,
10018 				    pl->pl_user_prop, value,
10019 				    sizeof (value)) == 0) {
10020 					zprop_print_one_property(
10021 					    zpool_get_name(zhp), cbp,
10022 					    pl->pl_user_prop, value, srctype,
10023 					    NULL, NULL);
10024 				}
10025 			} else {
10026 				if (zpool_get_prop(zhp, pl->pl_prop, value,
10027 				    sizeof (value), &srctype,
10028 				    cbp->cb_literal) != 0)
10029 					continue;
10030 
10031 				zprop_print_one_property(zpool_get_name(zhp),
10032 				    cbp, zpool_prop_to_name(pl->pl_prop),
10033 				    value, srctype, NULL, NULL);
10034 			}
10035 		}
10036 	}
10037 
10038 	return (0);
10039 }
10040 
10041 /*
10042  * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
10043  *
10044  *	-H	Scripted mode.  Don't display headers, and separate properties
10045  *		by a single tab.
10046  *	-o	List of columns to display.  Defaults to
10047  *		"name,property,value,source".
10048  * 	-p	Display values in parsable (exact) format.
10049  *
10050  * Get properties of pools in the system. Output space statistics
10051  * for each one as well as other attributes.
10052  */
10053 int
10054 zpool_do_get(int argc, char **argv)
10055 {
10056 	zprop_get_cbdata_t cb = { 0 };
10057 	zprop_list_t fake_name = { 0 };
10058 	int ret;
10059 	int c, i;
10060 	char *propstr = NULL;
10061 
10062 	cb.cb_first = B_TRUE;
10063 
10064 	/*
10065 	 * Set up default columns and sources.
10066 	 */
10067 	cb.cb_sources = ZPROP_SRC_ALL;
10068 	cb.cb_columns[0] = GET_COL_NAME;
10069 	cb.cb_columns[1] = GET_COL_PROPERTY;
10070 	cb.cb_columns[2] = GET_COL_VALUE;
10071 	cb.cb_columns[3] = GET_COL_SOURCE;
10072 	cb.cb_type = ZFS_TYPE_POOL;
10073 	cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
10074 	current_prop_type = cb.cb_type;
10075 
10076 	/* check options */
10077 	while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
10078 		switch (c) {
10079 		case 'p':
10080 			cb.cb_literal = B_TRUE;
10081 			break;
10082 		case 'H':
10083 			cb.cb_scripted = B_TRUE;
10084 			break;
10085 		case 'o':
10086 			memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
10087 			i = 0;
10088 
10089 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
10090 				static const char *const col_opts[] =
10091 				{ "name", "property", "value", "source",
10092 				    "all" };
10093 				static const zfs_get_column_t col_cols[] =
10094 				{ GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
10095 				    GET_COL_SOURCE };
10096 
10097 				if (i == ZFS_GET_NCOLS - 1) {
10098 					(void) fprintf(stderr, gettext("too "
10099 					"many fields given to -o "
10100 					"option\n"));
10101 					usage(B_FALSE);
10102 				}
10103 
10104 				for (c = 0; c < ARRAY_SIZE(col_opts); ++c)
10105 					if (strcmp(tok, col_opts[c]) == 0)
10106 						goto found;
10107 
10108 				(void) fprintf(stderr,
10109 				    gettext("invalid column name '%s'\n"), tok);
10110 				usage(B_FALSE);
10111 
10112 found:
10113 				if (c >= 4) {
10114 					if (i > 0) {
10115 						(void) fprintf(stderr,
10116 						    gettext("\"all\" conflicts "
10117 						    "with specific fields "
10118 						    "given to -o option\n"));
10119 						usage(B_FALSE);
10120 					}
10121 
10122 					memcpy(cb.cb_columns, col_cols,
10123 					    sizeof (col_cols));
10124 					i = ZFS_GET_NCOLS - 1;
10125 				} else
10126 					cb.cb_columns[i++] = col_cols[c];
10127 			}
10128 			break;
10129 		case '?':
10130 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
10131 			    optopt);
10132 			usage(B_FALSE);
10133 		}
10134 	}
10135 
10136 	argc -= optind;
10137 	argv += optind;
10138 
10139 	if (argc < 1) {
10140 		(void) fprintf(stderr, gettext("missing property "
10141 		    "argument\n"));
10142 		usage(B_FALSE);
10143 	}
10144 
10145 	/* Properties list is needed later by zprop_get_list() */
10146 	propstr = argv[0];
10147 
10148 	argc--;
10149 	argv++;
10150 
10151 	if (argc == 0) {
10152 		/* No args, so just print the defaults. */
10153 	} else if (are_all_pools(argc, argv)) {
10154 		/* All the args are pool names */
10155 	} else if (are_all_pools(1, argv)) {
10156 		/* The first arg is a pool name */
10157 		if ((argc == 2 && strcmp(argv[1], "all-vdevs") == 0) ||
10158 		    are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
10159 		    &cb.cb_vdevs)) {
10160 			/* ... and the rest are vdev names */
10161 			cb.cb_vdevs.cb_names = argv + 1;
10162 			cb.cb_vdevs.cb_names_count = argc - 1;
10163 			cb.cb_type = ZFS_TYPE_VDEV;
10164 			argc = 1; /* One pool to process */
10165 		} else {
10166 			fprintf(stderr, gettext("Expected a list of vdevs in"
10167 			    " \"%s\", but got:\n"), argv[0]);
10168 			error_list_unresolved_vdevs(argc - 1, argv + 1,
10169 			    argv[0], &cb.cb_vdevs);
10170 			fprintf(stderr, "\n");
10171 			usage(B_FALSE);
10172 			return (1);
10173 		}
10174 	} else {
10175 		/*
10176 		 * The first arg isn't a pool name,
10177 		 */
10178 		fprintf(stderr, gettext("missing pool name.\n"));
10179 		fprintf(stderr, "\n");
10180 		usage(B_FALSE);
10181 		return (1);
10182 	}
10183 
10184 	if (zprop_get_list(g_zfs, propstr, &cb.cb_proplist,
10185 	    cb.cb_type) != 0) {
10186 		/* Use correct list of valid properties (pool or vdev) */
10187 		current_prop_type = cb.cb_type;
10188 		usage(B_FALSE);
10189 	}
10190 
10191 	if (cb.cb_proplist != NULL) {
10192 		fake_name.pl_prop = ZPOOL_PROP_NAME;
10193 		fake_name.pl_width = strlen(gettext("NAME"));
10194 		fake_name.pl_next = cb.cb_proplist;
10195 		cb.cb_proplist = &fake_name;
10196 	}
10197 
10198 	ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist, cb.cb_type,
10199 	    cb.cb_literal, get_callback, &cb);
10200 
10201 	if (cb.cb_proplist == &fake_name)
10202 		zprop_free_list(fake_name.pl_next);
10203 	else
10204 		zprop_free_list(cb.cb_proplist);
10205 
10206 	return (ret);
10207 }
10208 
10209 typedef struct set_cbdata {
10210 	char *cb_propname;
10211 	char *cb_value;
10212 	zfs_type_t cb_type;
10213 	vdev_cbdata_t cb_vdevs;
10214 	boolean_t cb_any_successful;
10215 } set_cbdata_t;
10216 
10217 static int
10218 set_pool_callback(zpool_handle_t *zhp, set_cbdata_t *cb)
10219 {
10220 	int error;
10221 
10222 	/* Check if we have out-of-bounds features */
10223 	if (strcmp(cb->cb_propname, ZPOOL_CONFIG_COMPATIBILITY) == 0) {
10224 		boolean_t features[SPA_FEATURES];
10225 		if (zpool_do_load_compat(cb->cb_value, features) !=
10226 		    ZPOOL_COMPATIBILITY_OK)
10227 			return (-1);
10228 
10229 		nvlist_t *enabled = zpool_get_features(zhp);
10230 		spa_feature_t i;
10231 		for (i = 0; i < SPA_FEATURES; i++) {
10232 			const char *fguid = spa_feature_table[i].fi_guid;
10233 			if (nvlist_exists(enabled, fguid) && !features[i])
10234 				break;
10235 		}
10236 		if (i < SPA_FEATURES)
10237 			(void) fprintf(stderr, gettext("Warning: one or "
10238 			    "more features already enabled on pool '%s'\n"
10239 			    "are not present in this compatibility set.\n"),
10240 			    zpool_get_name(zhp));
10241 	}
10242 
10243 	/* if we're setting a feature, check it's in compatibility set */
10244 	if (zpool_prop_feature(cb->cb_propname) &&
10245 	    strcmp(cb->cb_value, ZFS_FEATURE_ENABLED) == 0) {
10246 		char *fname = strchr(cb->cb_propname, '@') + 1;
10247 		spa_feature_t f;
10248 
10249 		if (zfeature_lookup_name(fname, &f) == 0) {
10250 			char compat[ZFS_MAXPROPLEN];
10251 			if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY,
10252 			    compat, ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
10253 				compat[0] = '\0';
10254 
10255 			boolean_t features[SPA_FEATURES];
10256 			if (zpool_do_load_compat(compat, features) !=
10257 			    ZPOOL_COMPATIBILITY_OK) {
10258 				(void) fprintf(stderr, gettext("Error: "
10259 				    "cannot enable feature '%s' on pool '%s'\n"
10260 				    "because the pool's 'compatibility' "
10261 				    "property cannot be parsed.\n"),
10262 				    fname, zpool_get_name(zhp));
10263 				return (-1);
10264 			}
10265 
10266 			if (!features[f]) {
10267 				(void) fprintf(stderr, gettext("Error: "
10268 				    "cannot enable feature '%s' on pool '%s'\n"
10269 				    "as it is not specified in this pool's "
10270 				    "current compatibility set.\n"
10271 				    "Consider setting 'compatibility' to a "
10272 				    "less restrictive set, or to 'off'.\n"),
10273 				    fname, zpool_get_name(zhp));
10274 				return (-1);
10275 			}
10276 		}
10277 	}
10278 
10279 	error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
10280 
10281 	return (error);
10282 }
10283 
10284 static int
10285 set_callback(zpool_handle_t *zhp, void *data)
10286 {
10287 	int error;
10288 	set_cbdata_t *cb = (set_cbdata_t *)data;
10289 
10290 	if (cb->cb_type == ZFS_TYPE_VDEV) {
10291 		error = zpool_set_vdev_prop(zhp, *cb->cb_vdevs.cb_names,
10292 		    cb->cb_propname, cb->cb_value);
10293 	} else {
10294 		assert(cb->cb_type == ZFS_TYPE_POOL);
10295 		error = set_pool_callback(zhp, cb);
10296 	}
10297 
10298 	cb->cb_any_successful = !error;
10299 	return (error);
10300 }
10301 
10302 int
10303 zpool_do_set(int argc, char **argv)
10304 {
10305 	set_cbdata_t cb = { 0 };
10306 	int error;
10307 
10308 	current_prop_type = ZFS_TYPE_POOL;
10309 	if (argc > 1 && argv[1][0] == '-') {
10310 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
10311 		    argv[1][1]);
10312 		usage(B_FALSE);
10313 	}
10314 
10315 	if (argc < 2) {
10316 		(void) fprintf(stderr, gettext("missing property=value "
10317 		    "argument\n"));
10318 		usage(B_FALSE);
10319 	}
10320 
10321 	if (argc < 3) {
10322 		(void) fprintf(stderr, gettext("missing pool name\n"));
10323 		usage(B_FALSE);
10324 	}
10325 
10326 	if (argc > 4) {
10327 		(void) fprintf(stderr, gettext("too many pool names\n"));
10328 		usage(B_FALSE);
10329 	}
10330 
10331 	cb.cb_propname = argv[1];
10332 	cb.cb_type = ZFS_TYPE_POOL;
10333 	cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
10334 	cb.cb_value = strchr(cb.cb_propname, '=');
10335 	if (cb.cb_value == NULL) {
10336 		(void) fprintf(stderr, gettext("missing value in "
10337 		    "property=value argument\n"));
10338 		usage(B_FALSE);
10339 	}
10340 
10341 	*(cb.cb_value) = '\0';
10342 	cb.cb_value++;
10343 	argc -= 2;
10344 	argv += 2;
10345 
10346 	if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
10347 		/* Argument is a vdev */
10348 		cb.cb_vdevs.cb_names = argv;
10349 		cb.cb_vdevs.cb_names_count = 1;
10350 		cb.cb_type = ZFS_TYPE_VDEV;
10351 		argc = 0; /* No pools to process */
10352 	} else if (are_all_pools(1, argv)) {
10353 		/* The first arg is a pool name */
10354 		if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
10355 		    &cb.cb_vdevs)) {
10356 			/* 2nd argument is a vdev */
10357 			cb.cb_vdevs.cb_names = argv + 1;
10358 			cb.cb_vdevs.cb_names_count = 1;
10359 			cb.cb_type = ZFS_TYPE_VDEV;
10360 			argc = 1; /* One pool to process */
10361 		} else if (argc > 1) {
10362 			(void) fprintf(stderr,
10363 			    gettext("too many pool names\n"));
10364 			usage(B_FALSE);
10365 		}
10366 	}
10367 
10368 	error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
10369 	    B_FALSE, set_callback, &cb);
10370 
10371 	return (error);
10372 }
10373 
10374 /* Add up the total number of bytes left to initialize/trim across all vdevs */
10375 static uint64_t
10376 vdev_activity_remaining(nvlist_t *nv, zpool_wait_activity_t activity)
10377 {
10378 	uint64_t bytes_remaining;
10379 	nvlist_t **child;
10380 	uint_t c, children;
10381 	vdev_stat_t *vs;
10382 
10383 	assert(activity == ZPOOL_WAIT_INITIALIZE ||
10384 	    activity == ZPOOL_WAIT_TRIM);
10385 
10386 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
10387 	    (uint64_t **)&vs, &c) == 0);
10388 
10389 	if (activity == ZPOOL_WAIT_INITIALIZE &&
10390 	    vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE)
10391 		bytes_remaining = vs->vs_initialize_bytes_est -
10392 		    vs->vs_initialize_bytes_done;
10393 	else if (activity == ZPOOL_WAIT_TRIM &&
10394 	    vs->vs_trim_state == VDEV_TRIM_ACTIVE)
10395 		bytes_remaining = vs->vs_trim_bytes_est -
10396 		    vs->vs_trim_bytes_done;
10397 	else
10398 		bytes_remaining = 0;
10399 
10400 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10401 	    &child, &children) != 0)
10402 		children = 0;
10403 
10404 	for (c = 0; c < children; c++)
10405 		bytes_remaining += vdev_activity_remaining(child[c], activity);
10406 
10407 	return (bytes_remaining);
10408 }
10409 
10410 /* Add up the total number of bytes left to rebuild across top-level vdevs */
10411 static uint64_t
10412 vdev_activity_top_remaining(nvlist_t *nv)
10413 {
10414 	uint64_t bytes_remaining = 0;
10415 	nvlist_t **child;
10416 	uint_t children;
10417 	int error;
10418 
10419 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10420 	    &child, &children) != 0)
10421 		children = 0;
10422 
10423 	for (uint_t c = 0; c < children; c++) {
10424 		vdev_rebuild_stat_t *vrs;
10425 		uint_t i;
10426 
10427 		error = nvlist_lookup_uint64_array(child[c],
10428 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i);
10429 		if (error == 0) {
10430 			if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
10431 				bytes_remaining += (vrs->vrs_bytes_est -
10432 				    vrs->vrs_bytes_rebuilt);
10433 			}
10434 		}
10435 	}
10436 
10437 	return (bytes_remaining);
10438 }
10439 
10440 /* Whether any vdevs are 'spare' or 'replacing' vdevs */
10441 static boolean_t
10442 vdev_any_spare_replacing(nvlist_t *nv)
10443 {
10444 	nvlist_t **child;
10445 	uint_t c, children;
10446 	char *vdev_type;
10447 
10448 	(void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &vdev_type);
10449 
10450 	if (strcmp(vdev_type, VDEV_TYPE_REPLACING) == 0 ||
10451 	    strcmp(vdev_type, VDEV_TYPE_SPARE) == 0 ||
10452 	    strcmp(vdev_type, VDEV_TYPE_DRAID_SPARE) == 0) {
10453 		return (B_TRUE);
10454 	}
10455 
10456 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10457 	    &child, &children) != 0)
10458 		children = 0;
10459 
10460 	for (c = 0; c < children; c++) {
10461 		if (vdev_any_spare_replacing(child[c]))
10462 			return (B_TRUE);
10463 	}
10464 
10465 	return (B_FALSE);
10466 }
10467 
10468 typedef struct wait_data {
10469 	char *wd_poolname;
10470 	boolean_t wd_scripted;
10471 	boolean_t wd_exact;
10472 	boolean_t wd_headers_once;
10473 	boolean_t wd_should_exit;
10474 	/* Which activities to wait for */
10475 	boolean_t wd_enabled[ZPOOL_WAIT_NUM_ACTIVITIES];
10476 	float wd_interval;
10477 	pthread_cond_t wd_cv;
10478 	pthread_mutex_t wd_mutex;
10479 } wait_data_t;
10480 
10481 /*
10482  * Print to stdout a single line, containing one column for each activity that
10483  * we are waiting for specifying how many bytes of work are left for that
10484  * activity.
10485  */
10486 static void
10487 print_wait_status_row(wait_data_t *wd, zpool_handle_t *zhp, int row)
10488 {
10489 	nvlist_t *config, *nvroot;
10490 	uint_t c;
10491 	int i;
10492 	pool_checkpoint_stat_t *pcs = NULL;
10493 	pool_scan_stat_t *pss = NULL;
10494 	pool_removal_stat_t *prs = NULL;
10495 	const char *const headers[] = {"DISCARD", "FREE", "INITIALIZE",
10496 	    "REPLACE", "REMOVE", "RESILVER", "SCRUB", "TRIM"};
10497 	int col_widths[ZPOOL_WAIT_NUM_ACTIVITIES];
10498 
10499 	/* Calculate the width of each column */
10500 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10501 		/*
10502 		 * Make sure we have enough space in the col for pretty-printed
10503 		 * numbers and for the column header, and then leave a couple
10504 		 * spaces between cols for readability.
10505 		 */
10506 		col_widths[i] = MAX(strlen(headers[i]), 6) + 2;
10507 	}
10508 
10509 	/* Print header if appropriate */
10510 	int term_height = terminal_height();
10511 	boolean_t reprint_header = (!wd->wd_headers_once && term_height > 0 &&
10512 	    row % (term_height-1) == 0);
10513 	if (!wd->wd_scripted && (row == 0 || reprint_header)) {
10514 		for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10515 			if (wd->wd_enabled[i])
10516 				(void) printf("%*s", col_widths[i], headers[i]);
10517 		}
10518 		(void) fputc('\n', stdout);
10519 	}
10520 
10521 	/* Bytes of work remaining in each activity */
10522 	int64_t bytes_rem[ZPOOL_WAIT_NUM_ACTIVITIES] = {0};
10523 
10524 	bytes_rem[ZPOOL_WAIT_FREE] =
10525 	    zpool_get_prop_int(zhp, ZPOOL_PROP_FREEING, NULL);
10526 
10527 	config = zpool_get_config(zhp, NULL);
10528 	nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
10529 
10530 	(void) nvlist_lookup_uint64_array(nvroot,
10531 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
10532 	if (pcs != NULL && pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
10533 		bytes_rem[ZPOOL_WAIT_CKPT_DISCARD] = pcs->pcs_space;
10534 
10535 	(void) nvlist_lookup_uint64_array(nvroot,
10536 	    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
10537 	if (prs != NULL && prs->prs_state == DSS_SCANNING)
10538 		bytes_rem[ZPOOL_WAIT_REMOVE] = prs->prs_to_copy -
10539 		    prs->prs_copied;
10540 
10541 	(void) nvlist_lookup_uint64_array(nvroot,
10542 	    ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&pss, &c);
10543 	if (pss != NULL && pss->pss_state == DSS_SCANNING &&
10544 	    pss->pss_pass_scrub_pause == 0) {
10545 		int64_t rem = pss->pss_to_examine - pss->pss_issued;
10546 		if (pss->pss_func == POOL_SCAN_SCRUB)
10547 			bytes_rem[ZPOOL_WAIT_SCRUB] = rem;
10548 		else
10549 			bytes_rem[ZPOOL_WAIT_RESILVER] = rem;
10550 	} else if (check_rebuilding(nvroot, NULL)) {
10551 		bytes_rem[ZPOOL_WAIT_RESILVER] =
10552 		    vdev_activity_top_remaining(nvroot);
10553 	}
10554 
10555 	bytes_rem[ZPOOL_WAIT_INITIALIZE] =
10556 	    vdev_activity_remaining(nvroot, ZPOOL_WAIT_INITIALIZE);
10557 	bytes_rem[ZPOOL_WAIT_TRIM] =
10558 	    vdev_activity_remaining(nvroot, ZPOOL_WAIT_TRIM);
10559 
10560 	/*
10561 	 * A replace finishes after resilvering finishes, so the amount of work
10562 	 * left for a replace is the same as for resilvering.
10563 	 *
10564 	 * It isn't quite correct to say that if we have any 'spare' or
10565 	 * 'replacing' vdevs and a resilver is happening, then a replace is in
10566 	 * progress, like we do here. When a hot spare is used, the faulted vdev
10567 	 * is not removed after the hot spare is resilvered, so parent 'spare'
10568 	 * vdev is not removed either. So we could have a 'spare' vdev, but be
10569 	 * resilvering for a different reason. However, we use it as a heuristic
10570 	 * because we don't have access to the DTLs, which could tell us whether
10571 	 * or not we have really finished resilvering a hot spare.
10572 	 */
10573 	if (vdev_any_spare_replacing(nvroot))
10574 		bytes_rem[ZPOOL_WAIT_REPLACE] =  bytes_rem[ZPOOL_WAIT_RESILVER];
10575 
10576 	if (timestamp_fmt != NODATE)
10577 		print_timestamp(timestamp_fmt);
10578 
10579 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10580 		char buf[64];
10581 		if (!wd->wd_enabled[i])
10582 			continue;
10583 
10584 		if (wd->wd_exact)
10585 			(void) snprintf(buf, sizeof (buf), "%" PRIi64,
10586 			    bytes_rem[i]);
10587 		else
10588 			zfs_nicenum(bytes_rem[i], buf, sizeof (buf));
10589 
10590 		if (wd->wd_scripted)
10591 			(void) printf(i == 0 ? "%s" : "\t%s", buf);
10592 		else
10593 			(void) printf(" %*s", col_widths[i] - 1, buf);
10594 	}
10595 	(void) printf("\n");
10596 	(void) fflush(stdout);
10597 }
10598 
10599 static void *
10600 wait_status_thread(void *arg)
10601 {
10602 	wait_data_t *wd = (wait_data_t *)arg;
10603 	zpool_handle_t *zhp;
10604 
10605 	if ((zhp = zpool_open(g_zfs, wd->wd_poolname)) == NULL)
10606 		return (void *)(1);
10607 
10608 	for (int row = 0; ; row++) {
10609 		boolean_t missing;
10610 		struct timespec timeout;
10611 		int ret = 0;
10612 		(void) clock_gettime(CLOCK_REALTIME, &timeout);
10613 
10614 		if (zpool_refresh_stats(zhp, &missing) != 0 || missing ||
10615 		    zpool_props_refresh(zhp) != 0) {
10616 			zpool_close(zhp);
10617 			return (void *)(uintptr_t)(missing ? 0 : 1);
10618 		}
10619 
10620 		print_wait_status_row(wd, zhp, row);
10621 
10622 		timeout.tv_sec += floor(wd->wd_interval);
10623 		long nanos = timeout.tv_nsec +
10624 		    (wd->wd_interval - floor(wd->wd_interval)) * NANOSEC;
10625 		if (nanos >= NANOSEC) {
10626 			timeout.tv_sec++;
10627 			timeout.tv_nsec = nanos - NANOSEC;
10628 		} else {
10629 			timeout.tv_nsec = nanos;
10630 		}
10631 		pthread_mutex_lock(&wd->wd_mutex);
10632 		if (!wd->wd_should_exit)
10633 			ret = pthread_cond_timedwait(&wd->wd_cv, &wd->wd_mutex,
10634 			    &timeout);
10635 		pthread_mutex_unlock(&wd->wd_mutex);
10636 		if (ret == 0) {
10637 			break; /* signaled by main thread */
10638 		} else if (ret != ETIMEDOUT) {
10639 			(void) fprintf(stderr, gettext("pthread_cond_timedwait "
10640 			    "failed: %s\n"), strerror(ret));
10641 			zpool_close(zhp);
10642 			return (void *)(uintptr_t)(1);
10643 		}
10644 	}
10645 
10646 	zpool_close(zhp);
10647 	return (void *)(0);
10648 }
10649 
10650 int
10651 zpool_do_wait(int argc, char **argv)
10652 {
10653 	boolean_t verbose = B_FALSE;
10654 	int c, i;
10655 	unsigned long count;
10656 	pthread_t status_thr;
10657 	int error = 0;
10658 	zpool_handle_t *zhp;
10659 
10660 	wait_data_t wd;
10661 	wd.wd_scripted = B_FALSE;
10662 	wd.wd_exact = B_FALSE;
10663 	wd.wd_headers_once = B_FALSE;
10664 	wd.wd_should_exit = B_FALSE;
10665 
10666 	pthread_mutex_init(&wd.wd_mutex, NULL);
10667 	pthread_cond_init(&wd.wd_cv, NULL);
10668 
10669 	/* By default, wait for all types of activity. */
10670 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++)
10671 		wd.wd_enabled[i] = B_TRUE;
10672 
10673 	while ((c = getopt(argc, argv, "HpT:t:")) != -1) {
10674 		switch (c) {
10675 		case 'H':
10676 			wd.wd_scripted = B_TRUE;
10677 			break;
10678 		case 'n':
10679 			wd.wd_headers_once = B_TRUE;
10680 			break;
10681 		case 'p':
10682 			wd.wd_exact = B_TRUE;
10683 			break;
10684 		case 'T':
10685 			get_timestamp_arg(*optarg);
10686 			break;
10687 		case 't':
10688 			/* Reset activities array */
10689 			memset(&wd.wd_enabled, 0, sizeof (wd.wd_enabled));
10690 
10691 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
10692 				static const char *const col_opts[] = {
10693 				    "discard", "free", "initialize", "replace",
10694 				    "remove", "resilver", "scrub", "trim" };
10695 
10696 				for (i = 0; i < ARRAY_SIZE(col_opts); ++i)
10697 					if (strcmp(tok, col_opts[i]) == 0) {
10698 						wd.wd_enabled[i] = B_TRUE;
10699 						goto found;
10700 					}
10701 
10702 				(void) fprintf(stderr,
10703 				    gettext("invalid activity '%s'\n"), tok);
10704 				usage(B_FALSE);
10705 found:;
10706 			}
10707 			break;
10708 		case '?':
10709 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
10710 			    optopt);
10711 			usage(B_FALSE);
10712 		}
10713 	}
10714 
10715 	argc -= optind;
10716 	argv += optind;
10717 
10718 	get_interval_count(&argc, argv, &wd.wd_interval, &count);
10719 	if (count != 0) {
10720 		/* This subcmd only accepts an interval, not a count */
10721 		(void) fprintf(stderr, gettext("too many arguments\n"));
10722 		usage(B_FALSE);
10723 	}
10724 
10725 	if (wd.wd_interval != 0)
10726 		verbose = B_TRUE;
10727 
10728 	if (argc < 1) {
10729 		(void) fprintf(stderr, gettext("missing 'pool' argument\n"));
10730 		usage(B_FALSE);
10731 	}
10732 	if (argc > 1) {
10733 		(void) fprintf(stderr, gettext("too many arguments\n"));
10734 		usage(B_FALSE);
10735 	}
10736 
10737 	wd.wd_poolname = argv[0];
10738 
10739 	if ((zhp = zpool_open(g_zfs, wd.wd_poolname)) == NULL)
10740 		return (1);
10741 
10742 	if (verbose) {
10743 		/*
10744 		 * We use a separate thread for printing status updates because
10745 		 * the main thread will call lzc_wait(), which blocks as long
10746 		 * as an activity is in progress, which can be a long time.
10747 		 */
10748 		if (pthread_create(&status_thr, NULL, wait_status_thread, &wd)
10749 		    != 0) {
10750 			(void) fprintf(stderr, gettext("failed to create status"
10751 			    "thread: %s\n"), strerror(errno));
10752 			zpool_close(zhp);
10753 			return (1);
10754 		}
10755 	}
10756 
10757 	/*
10758 	 * Loop over all activities that we are supposed to wait for until none
10759 	 * of them are in progress. Note that this means we can end up waiting
10760 	 * for more activities to complete than just those that were in progress
10761 	 * when we began waiting; if an activity we are interested in begins
10762 	 * while we are waiting for another activity, we will wait for both to
10763 	 * complete before exiting.
10764 	 */
10765 	for (;;) {
10766 		boolean_t missing = B_FALSE;
10767 		boolean_t any_waited = B_FALSE;
10768 
10769 		for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10770 			boolean_t waited;
10771 
10772 			if (!wd.wd_enabled[i])
10773 				continue;
10774 
10775 			error = zpool_wait_status(zhp, i, &missing, &waited);
10776 			if (error != 0 || missing)
10777 				break;
10778 
10779 			any_waited = (any_waited || waited);
10780 		}
10781 
10782 		if (error != 0 || missing || !any_waited)
10783 			break;
10784 	}
10785 
10786 	zpool_close(zhp);
10787 
10788 	if (verbose) {
10789 		uintptr_t status;
10790 		pthread_mutex_lock(&wd.wd_mutex);
10791 		wd.wd_should_exit = B_TRUE;
10792 		pthread_cond_signal(&wd.wd_cv);
10793 		pthread_mutex_unlock(&wd.wd_mutex);
10794 		(void) pthread_join(status_thr, (void *)&status);
10795 		if (status != 0)
10796 			error = status;
10797 	}
10798 
10799 	pthread_mutex_destroy(&wd.wd_mutex);
10800 	pthread_cond_destroy(&wd.wd_cv);
10801 	return (error);
10802 }
10803 
10804 static int
10805 find_command_idx(const char *command, int *idx)
10806 {
10807 	for (int i = 0; i < NCOMMAND; ++i) {
10808 		if (command_table[i].name == NULL)
10809 			continue;
10810 
10811 		if (strcmp(command, command_table[i].name) == 0) {
10812 			*idx = i;
10813 			return (0);
10814 		}
10815 	}
10816 	return (1);
10817 }
10818 
10819 /*
10820  * Display version message
10821  */
10822 static int
10823 zpool_do_version(int argc, char **argv)
10824 {
10825 	(void) argc, (void) argv;
10826 	return (zfs_version_print() != 0);
10827 }
10828 
10829 /*
10830  * Do zpool_load_compat() and print error message on failure
10831  */
10832 static zpool_compat_status_t
10833 zpool_do_load_compat(const char *compat, boolean_t *list)
10834 {
10835 	char report[1024];
10836 
10837 	zpool_compat_status_t ret;
10838 
10839 	ret = zpool_load_compat(compat, list, report, 1024);
10840 	switch (ret) {
10841 
10842 	case ZPOOL_COMPATIBILITY_OK:
10843 		break;
10844 
10845 	case ZPOOL_COMPATIBILITY_NOFILES:
10846 	case ZPOOL_COMPATIBILITY_BADFILE:
10847 	case ZPOOL_COMPATIBILITY_BADTOKEN:
10848 		(void) fprintf(stderr, "Error: %s\n", report);
10849 		break;
10850 
10851 	case ZPOOL_COMPATIBILITY_WARNTOKEN:
10852 		(void) fprintf(stderr, "Warning: %s\n", report);
10853 		ret = ZPOOL_COMPATIBILITY_OK;
10854 		break;
10855 	}
10856 	return (ret);
10857 }
10858 
10859 int
10860 main(int argc, char **argv)
10861 {
10862 	int ret = 0;
10863 	int i = 0;
10864 	char *cmdname;
10865 	char **newargv;
10866 
10867 	(void) setlocale(LC_ALL, "");
10868 	(void) setlocale(LC_NUMERIC, "C");
10869 	(void) textdomain(TEXT_DOMAIN);
10870 	srand(time(NULL));
10871 
10872 	opterr = 0;
10873 
10874 	/*
10875 	 * Make sure the user has specified some command.
10876 	 */
10877 	if (argc < 2) {
10878 		(void) fprintf(stderr, gettext("missing command\n"));
10879 		usage(B_FALSE);
10880 	}
10881 
10882 	cmdname = argv[1];
10883 
10884 	/*
10885 	 * Special case '-?'
10886 	 */
10887 	if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
10888 		usage(B_TRUE);
10889 
10890 	/*
10891 	 * Special case '-V|--version'
10892 	 */
10893 	if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
10894 		return (zpool_do_version(argc, argv));
10895 
10896 	if ((g_zfs = libzfs_init()) == NULL) {
10897 		(void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
10898 		return (1);
10899 	}
10900 
10901 	libzfs_print_on_error(g_zfs, B_TRUE);
10902 
10903 	zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
10904 
10905 	/*
10906 	 * Many commands modify input strings for string parsing reasons.
10907 	 * We create a copy to protect the original argv.
10908 	 */
10909 	newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
10910 	for (i = 0; i < argc; i++)
10911 		newargv[i] = strdup(argv[i]);
10912 	newargv[argc] = NULL;
10913 
10914 	/*
10915 	 * Run the appropriate command.
10916 	 */
10917 	if (find_command_idx(cmdname, &i) == 0) {
10918 		current_command = &command_table[i];
10919 		ret = command_table[i].func(argc - 1, newargv + 1);
10920 	} else if (strchr(cmdname, '=')) {
10921 		verify(find_command_idx("set", &i) == 0);
10922 		current_command = &command_table[i];
10923 		ret = command_table[i].func(argc, newargv);
10924 	} else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
10925 		/*
10926 		 * 'freeze' is a vile debugging abomination, so we treat
10927 		 * it as such.
10928 		 */
10929 		zfs_cmd_t zc = {"\0"};
10930 
10931 		(void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
10932 		ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
10933 		if (ret != 0) {
10934 			(void) fprintf(stderr,
10935 			gettext("failed to freeze pool: %d\n"), errno);
10936 			ret = 1;
10937 		}
10938 
10939 		log_history = 0;
10940 	} else {
10941 		(void) fprintf(stderr, gettext("unrecognized "
10942 		    "command '%s'\n"), cmdname);
10943 		usage(B_FALSE);
10944 		ret = 1;
10945 	}
10946 
10947 	for (i = 0; i < argc; i++)
10948 		free(newargv[i]);
10949 	free(newargv);
10950 
10951 	if (ret == 0 && log_history)
10952 		(void) zpool_log_history(g_zfs, history_str);
10953 
10954 	libzfs_fini(g_zfs);
10955 
10956 	/*
10957 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
10958 	 * for the purposes of running ::findleaks.
10959 	 */
10960 	if (getenv("ZFS_ABORT") != NULL) {
10961 		(void) printf("dumping core by request\n");
10962 		abort();
10963 	}
10964 
10965 	return (ret);
10966 }
10967