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