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