xref: /freebsd/sys/contrib/openzfs/cmd/zpool/zpool_main.c (revision f5ce3f4ef562ea9fc4d8f9c13c268f48a5bacba7)
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, 2024 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, 2023, 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 <thread_pool.h>
54 #include <time.h>
55 #include <unistd.h>
56 #include <pwd.h>
57 #include <zone.h>
58 #include <sys/wait.h>
59 #include <zfs_prop.h>
60 #include <sys/fs/zfs.h>
61 #include <sys/stat.h>
62 #include <sys/systeminfo.h>
63 #include <sys/fm/fs/zfs.h>
64 #include <sys/fm/util.h>
65 #include <sys/fm/protocol.h>
66 #include <sys/zfs_ioctl.h>
67 #include <sys/mount.h>
68 #include <sys/sysmacros.h>
69 #include <string.h>
70 #include <math.h>
71 
72 #include <libzfs.h>
73 #include <libzutil.h>
74 
75 #include "zpool_util.h"
76 #include "zfs_comutil.h"
77 #include "zfeature_common.h"
78 
79 #include "statcommon.h"
80 
81 libzfs_handle_t *g_zfs;
82 
83 static int mount_tp_nthr = 512;  /* tpool threads for multi-threaded mounting */
84 
85 static int zpool_do_create(int, char **);
86 static int zpool_do_destroy(int, char **);
87 
88 static int zpool_do_add(int, char **);
89 static int zpool_do_remove(int, char **);
90 static int zpool_do_labelclear(int, char **);
91 
92 static int zpool_do_checkpoint(int, char **);
93 static int zpool_do_prefetch(int, char **);
94 
95 static int zpool_do_list(int, char **);
96 static int zpool_do_iostat(int, char **);
97 static int zpool_do_status(int, char **);
98 
99 static int zpool_do_online(int, char **);
100 static int zpool_do_offline(int, char **);
101 static int zpool_do_clear(int, char **);
102 static int zpool_do_reopen(int, char **);
103 
104 static int zpool_do_reguid(int, char **);
105 
106 static int zpool_do_attach(int, char **);
107 static int zpool_do_detach(int, char **);
108 static int zpool_do_replace(int, char **);
109 static int zpool_do_split(int, char **);
110 
111 static int zpool_do_initialize(int, char **);
112 static int zpool_do_scrub(int, char **);
113 static int zpool_do_resilver(int, char **);
114 static int zpool_do_trim(int, char **);
115 
116 static int zpool_do_import(int, char **);
117 static int zpool_do_export(int, char **);
118 
119 static int zpool_do_upgrade(int, char **);
120 
121 static int zpool_do_history(int, char **);
122 static int zpool_do_events(int, char **);
123 
124 static int zpool_do_get(int, char **);
125 static int zpool_do_set(int, char **);
126 
127 static int zpool_do_sync(int, char **);
128 
129 static int zpool_do_version(int, char **);
130 
131 static int zpool_do_wait(int, char **);
132 
133 static int zpool_do_help(int argc, char **argv);
134 
135 static zpool_compat_status_t zpool_do_load_compat(
136     const char *, boolean_t *);
137 
138 enum zpool_options {
139 	ZPOOL_OPTION_POWER = 1024,
140 	ZPOOL_OPTION_ALLOW_INUSE,
141 	ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH,
142 	ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH,
143 	ZPOOL_OPTION_POOL_KEY_GUID,
144 	ZPOOL_OPTION_JSON_NUMS_AS_INT,
145 	ZPOOL_OPTION_JSON_FLAT_VDEVS
146 };
147 
148 /*
149  * These libumem hooks provide a reasonable set of defaults for the allocator's
150  * debugging facilities.
151  */
152 
153 #ifdef DEBUG
154 const char *
155 _umem_debug_init(void)
156 {
157 	return ("default,verbose"); /* $UMEM_DEBUG setting */
158 }
159 
160 const char *
161 _umem_logging_init(void)
162 {
163 	return ("fail,contents"); /* $UMEM_LOGGING setting */
164 }
165 #endif
166 
167 typedef enum {
168 	HELP_ADD,
169 	HELP_ATTACH,
170 	HELP_CLEAR,
171 	HELP_CREATE,
172 	HELP_CHECKPOINT,
173 	HELP_DESTROY,
174 	HELP_DETACH,
175 	HELP_EXPORT,
176 	HELP_HISTORY,
177 	HELP_IMPORT,
178 	HELP_IOSTAT,
179 	HELP_LABELCLEAR,
180 	HELP_LIST,
181 	HELP_OFFLINE,
182 	HELP_ONLINE,
183 	HELP_PREFETCH,
184 	HELP_REPLACE,
185 	HELP_REMOVE,
186 	HELP_INITIALIZE,
187 	HELP_SCRUB,
188 	HELP_RESILVER,
189 	HELP_TRIM,
190 	HELP_STATUS,
191 	HELP_UPGRADE,
192 	HELP_EVENTS,
193 	HELP_GET,
194 	HELP_SET,
195 	HELP_SPLIT,
196 	HELP_SYNC,
197 	HELP_REGUID,
198 	HELP_REOPEN,
199 	HELP_VERSION,
200 	HELP_WAIT
201 } zpool_help_t;
202 
203 
204 /*
205  * Flags for stats to display with "zpool iostats"
206  */
207 enum iostat_type {
208 	IOS_DEFAULT = 0,
209 	IOS_LATENCY = 1,
210 	IOS_QUEUES = 2,
211 	IOS_L_HISTO = 3,
212 	IOS_RQ_HISTO = 4,
213 	IOS_COUNT,	/* always last element */
214 };
215 
216 /* iostat_type entries as bitmasks */
217 #define	IOS_DEFAULT_M	(1ULL << IOS_DEFAULT)
218 #define	IOS_LATENCY_M	(1ULL << IOS_LATENCY)
219 #define	IOS_QUEUES_M	(1ULL << IOS_QUEUES)
220 #define	IOS_L_HISTO_M	(1ULL << IOS_L_HISTO)
221 #define	IOS_RQ_HISTO_M	(1ULL << IOS_RQ_HISTO)
222 
223 /* Mask of all the histo bits */
224 #define	IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
225 
226 /*
227  * Lookup table for iostat flags to nvlist names.  Basically a list
228  * of all the nvlists a flag requires.  Also specifies the order in
229  * which data gets printed in zpool iostat.
230  */
231 static const char *vsx_type_to_nvlist[IOS_COUNT][15] = {
232 	[IOS_L_HISTO] = {
233 	    ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
234 	    ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
235 	    ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
236 	    ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
237 	    ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
238 	    ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
239 	    ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
240 	    ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
241 	    ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
242 	    ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
243 	    ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
244 	    NULL},
245 	[IOS_LATENCY] = {
246 	    ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
247 	    ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
248 	    ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
249 	    ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
250 	    ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
251 	    ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
252 	    NULL},
253 	[IOS_QUEUES] = {
254 	    ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
255 	    ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
256 	    ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
257 	    ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
258 	    ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
259 	    ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
260 	    ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
261 	    NULL},
262 	[IOS_RQ_HISTO] = {
263 	    ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
264 	    ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
265 	    ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
266 	    ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
267 	    ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
268 	    ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
269 	    ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
270 	    ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
271 	    ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
272 	    ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
273 	    ZPOOL_CONFIG_VDEV_IND_TRIM_HISTO,
274 	    ZPOOL_CONFIG_VDEV_AGG_TRIM_HISTO,
275 	    ZPOOL_CONFIG_VDEV_IND_REBUILD_HISTO,
276 	    ZPOOL_CONFIG_VDEV_AGG_REBUILD_HISTO,
277 	    NULL},
278 };
279 
280 static const char *pool_scan_func_str[] = {
281 	"NONE",
282 	"SCRUB",
283 	"RESILVER",
284 	"ERRORSCRUB"
285 };
286 
287 static const char *pool_scan_state_str[] = {
288 	"NONE",
289 	"SCANNING",
290 	"FINISHED",
291 	"CANCELED",
292 	"ERRORSCRUBBING"
293 };
294 
295 static const char *vdev_rebuild_state_str[] = {
296 	"NONE",
297 	"ACTIVE",
298 	"CANCELED",
299 	"COMPLETE"
300 };
301 
302 static const char *checkpoint_state_str[] = {
303 	"NONE",
304 	"EXISTS",
305 	"DISCARDING"
306 };
307 
308 static const char *vdev_state_str[] = {
309 	"UNKNOWN",
310 	"CLOSED",
311 	"OFFLINE",
312 	"REMOVED",
313 	"CANT_OPEN",
314 	"FAULTED",
315 	"DEGRADED",
316 	"ONLINE"
317 };
318 
319 static const char *vdev_aux_str[] = {
320 	"NONE",
321 	"OPEN_FAILED",
322 	"CORRUPT_DATA",
323 	"NO_REPLICAS",
324 	"BAD_GUID_SUM",
325 	"TOO_SMALL",
326 	"BAD_LABEL",
327 	"VERSION_NEWER",
328 	"VERSION_OLDER",
329 	"UNSUP_FEAT",
330 	"SPARED",
331 	"ERR_EXCEEDED",
332 	"IO_FAILURE",
333 	"BAD_LOG",
334 	"EXTERNAL",
335 	"SPLIT_POOL",
336 	"BAD_ASHIFT",
337 	"EXTERNAL_PERSIST",
338 	"ACTIVE",
339 	"CHILDREN_OFFLINE",
340 	"ASHIFT_TOO_BIG"
341 };
342 
343 static const char *vdev_init_state_str[] = {
344 	"NONE",
345 	"ACTIVE",
346 	"CANCELED",
347 	"SUSPENDED",
348 	"COMPLETE"
349 };
350 
351 static const char *vdev_trim_state_str[] = {
352 	"NONE",
353 	"ACTIVE",
354 	"CANCELED",
355 	"SUSPENDED",
356 	"COMPLETE"
357 };
358 
359 #define	ZFS_NICE_TIMESTAMP	100
360 
361 /*
362  * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
363  * Right now, only one histo bit is ever set at one time, so we can
364  * just do a highbit64(a)
365  */
366 #define	IOS_HISTO_IDX(a)	(highbit64(a & IOS_ANYHISTO_M) - 1)
367 
368 typedef struct zpool_command {
369 	const char	*name;
370 	int		(*func)(int, char **);
371 	zpool_help_t	usage;
372 } zpool_command_t;
373 
374 /*
375  * Master command table.  Each ZFS command has a name, associated function, and
376  * usage message.  The usage messages need to be internationalized, so we have
377  * to have a function to return the usage message based on a command index.
378  *
379  * These commands are organized according to how they are displayed in the usage
380  * message.  An empty command (one with a NULL name) indicates an empty line in
381  * the generic usage message.
382  */
383 static zpool_command_t command_table[] = {
384 	{ "version",	zpool_do_version,	HELP_VERSION		},
385 	{ NULL },
386 	{ "create",	zpool_do_create,	HELP_CREATE		},
387 	{ "destroy",	zpool_do_destroy,	HELP_DESTROY		},
388 	{ NULL },
389 	{ "add",	zpool_do_add,		HELP_ADD		},
390 	{ "remove",	zpool_do_remove,	HELP_REMOVE		},
391 	{ NULL },
392 	{ "labelclear",	zpool_do_labelclear,	HELP_LABELCLEAR		},
393 	{ NULL },
394 	{ "checkpoint",	zpool_do_checkpoint,	HELP_CHECKPOINT		},
395 	{ "prefetch",	zpool_do_prefetch,	HELP_PREFETCH		},
396 	{ NULL },
397 	{ "list",	zpool_do_list,		HELP_LIST		},
398 	{ "iostat",	zpool_do_iostat,	HELP_IOSTAT		},
399 	{ "status",	zpool_do_status,	HELP_STATUS		},
400 	{ NULL },
401 	{ "online",	zpool_do_online,	HELP_ONLINE		},
402 	{ "offline",	zpool_do_offline,	HELP_OFFLINE		},
403 	{ "clear",	zpool_do_clear,		HELP_CLEAR		},
404 	{ "reopen",	zpool_do_reopen,	HELP_REOPEN		},
405 	{ NULL },
406 	{ "attach",	zpool_do_attach,	HELP_ATTACH		},
407 	{ "detach",	zpool_do_detach,	HELP_DETACH		},
408 	{ "replace",	zpool_do_replace,	HELP_REPLACE		},
409 	{ "split",	zpool_do_split,		HELP_SPLIT		},
410 	{ NULL },
411 	{ "initialize",	zpool_do_initialize,	HELP_INITIALIZE		},
412 	{ "resilver",	zpool_do_resilver,	HELP_RESILVER		},
413 	{ "scrub",	zpool_do_scrub,		HELP_SCRUB		},
414 	{ "trim",	zpool_do_trim,		HELP_TRIM		},
415 	{ NULL },
416 	{ "import",	zpool_do_import,	HELP_IMPORT		},
417 	{ "export",	zpool_do_export,	HELP_EXPORT		},
418 	{ "upgrade",	zpool_do_upgrade,	HELP_UPGRADE		},
419 	{ "reguid",	zpool_do_reguid,	HELP_REGUID		},
420 	{ NULL },
421 	{ "history",	zpool_do_history,	HELP_HISTORY		},
422 	{ "events",	zpool_do_events,	HELP_EVENTS		},
423 	{ NULL },
424 	{ "get",	zpool_do_get,		HELP_GET		},
425 	{ "set",	zpool_do_set,		HELP_SET		},
426 	{ "sync",	zpool_do_sync,		HELP_SYNC		},
427 	{ NULL },
428 	{ "wait",	zpool_do_wait,		HELP_WAIT		},
429 };
430 
431 #define	NCOMMAND	(ARRAY_SIZE(command_table))
432 
433 #define	VDEV_ALLOC_CLASS_LOGS	"logs"
434 
435 #define	MAX_CMD_LEN	256
436 
437 static zpool_command_t *current_command;
438 static zfs_type_t current_prop_type = (ZFS_TYPE_POOL | ZFS_TYPE_VDEV);
439 static char history_str[HIS_MAX_RECORD_LEN];
440 static boolean_t log_history = B_TRUE;
441 static uint_t timestamp_fmt = NODATE;
442 
443 static const char *
444 get_usage(zpool_help_t idx)
445 {
446 	switch (idx) {
447 	case HELP_ADD:
448 		return (gettext("\tadd [-afgLnP] [-o property=value] "
449 		    "<pool> <vdev> ...\n"));
450 	case HELP_ATTACH:
451 		return (gettext("\tattach [-fsw] [-o property=value] "
452 		    "<pool> <device> <new-device>\n"));
453 	case HELP_CLEAR:
454 		return (gettext("\tclear [[--power]|[-nF]] <pool> [device]\n"));
455 	case HELP_CREATE:
456 		return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
457 		    "\t    [-O file-system-property=value] ... \n"
458 		    "\t    [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
459 	case HELP_CHECKPOINT:
460 		return (gettext("\tcheckpoint [-d [-w]] <pool> ...\n"));
461 	case HELP_DESTROY:
462 		return (gettext("\tdestroy [-f] <pool>\n"));
463 	case HELP_DETACH:
464 		return (gettext("\tdetach <pool> <device>\n"));
465 	case HELP_EXPORT:
466 		return (gettext("\texport [-af] <pool> ...\n"));
467 	case HELP_HISTORY:
468 		return (gettext("\thistory [-il] [<pool>] ...\n"));
469 	case HELP_IMPORT:
470 		return (gettext("\timport [-d dir] [-D]\n"
471 		    "\timport [-o mntopts] [-o property=value] ... \n"
472 		    "\t    [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
473 		    "[-R root] [-F [-n]] -a\n"
474 		    "\timport [-o mntopts] [-o property=value] ... \n"
475 		    "\t    [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
476 		    "[-R root] [-F [-n]]\n"
477 		    "\t    [--rewind-to-checkpoint] <pool | id> [newpool]\n"));
478 	case HELP_IOSTAT:
479 		return (gettext("\tiostat [[[-c [script1,script2,...]"
480 		    "[-lq]]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
481 		    "\t    [[pool ...]|[pool vdev ...]|[vdev ...]]"
482 		    " [[-n] interval [count]]\n"));
483 	case HELP_LABELCLEAR:
484 		return (gettext("\tlabelclear [-f] <vdev>\n"));
485 	case HELP_LIST:
486 		return (gettext("\tlist [-gHLpPv] [-o property[,...]] [-j "
487 		    "[--json-int, --json-pool-key-guid]] ...\n"
488 		    "\t    [-T d|u] [pool] [interval [count]]\n"));
489 	case HELP_PREFETCH:
490 		return (gettext("\tprefetch -t <type> [<type opts>] <pool>\n"
491 		    "\t    -t ddt <pool>\n"));
492 	case HELP_OFFLINE:
493 		return (gettext("\toffline [--power]|[[-f][-t]] <pool> "
494 		    "<device> ...\n"));
495 	case HELP_ONLINE:
496 		return (gettext("\tonline [--power][-e] <pool> <device> "
497 		    "...\n"));
498 	case HELP_REPLACE:
499 		return (gettext("\treplace [-fsw] [-o property=value] "
500 		    "<pool> <device> [new-device]\n"));
501 	case HELP_REMOVE:
502 		return (gettext("\tremove [-npsw] <pool> <device> ...\n"));
503 	case HELP_REOPEN:
504 		return (gettext("\treopen [-n] <pool>\n"));
505 	case HELP_INITIALIZE:
506 		return (gettext("\tinitialize [-c | -s | -u] [-w] <pool> "
507 		    "[<device> ...]\n"));
508 	case HELP_SCRUB:
509 		return (gettext("\tscrub [-s | -p] [-w] [-e] <pool> ...\n"));
510 	case HELP_RESILVER:
511 		return (gettext("\tresilver <pool> ...\n"));
512 	case HELP_TRIM:
513 		return (gettext("\ttrim [-dw] [-r <rate>] [-c | -s] <pool> "
514 		    "[<device> ...]\n"));
515 	case HELP_STATUS:
516 		return (gettext("\tstatus [--power] [-j [--json-int, "
517 		    "--json-flat-vdevs, ...\n"
518 		    "\t    --json-pool-key-guid]] [-c [script1,script2,...]] "
519 		    "[-DegiLpPstvx] ...\n"
520 		    "\t    [-T d|u] [pool] [interval [count]]\n"));
521 	case HELP_UPGRADE:
522 		return (gettext("\tupgrade\n"
523 		    "\tupgrade -v\n"
524 		    "\tupgrade [-V version] <-a | pool ...>\n"));
525 	case HELP_EVENTS:
526 		return (gettext("\tevents [-vHf [pool] | -c]\n"));
527 	case HELP_GET:
528 		return (gettext("\tget [-Hp] [-j [--json-int, "
529 		    "--json-pool-key-guid]] ...\n"
530 		    "\t    [-o \"all\" | field[,...]] "
531 		    "<\"all\" | property[,...]> <pool> ...\n"));
532 	case HELP_SET:
533 		return (gettext("\tset <property=value> <pool>\n"
534 		    "\tset <vdev_property=value> <pool> <vdev>\n"));
535 	case HELP_SPLIT:
536 		return (gettext("\tsplit [-gLnPl] [-R altroot] [-o mntopts]\n"
537 		    "\t    [-o property=value] <pool> <newpool> "
538 		    "[<device> ...]\n"));
539 	case HELP_REGUID:
540 		return (gettext("\treguid <pool>\n"));
541 	case HELP_SYNC:
542 		return (gettext("\tsync [pool] ...\n"));
543 	case HELP_VERSION:
544 		return (gettext("\tversion [-j]\n"));
545 	case HELP_WAIT:
546 		return (gettext("\twait [-Hp] [-T d|u] [-t <activity>[,...]] "
547 		    "<pool> [interval]\n"));
548 	default:
549 		__builtin_unreachable();
550 	}
551 }
552 
553 static void
554 zpool_collect_leaves(zpool_handle_t *zhp, nvlist_t *nvroot, nvlist_t *res)
555 {
556 	uint_t children = 0;
557 	nvlist_t **child;
558 	uint_t i;
559 
560 	(void) nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
561 	    &child, &children);
562 
563 	if (children == 0) {
564 		char *path = zpool_vdev_name(g_zfs, zhp, nvroot,
565 		    VDEV_NAME_PATH);
566 
567 		if (strcmp(path, VDEV_TYPE_INDIRECT) != 0 &&
568 		    strcmp(path, VDEV_TYPE_HOLE) != 0)
569 			fnvlist_add_boolean(res, path);
570 
571 		free(path);
572 		return;
573 	}
574 
575 	for (i = 0; i < children; i++) {
576 		zpool_collect_leaves(zhp, child[i], res);
577 	}
578 }
579 
580 /*
581  * Callback routine that will print out a pool property value.
582  */
583 static int
584 print_pool_prop_cb(int prop, void *cb)
585 {
586 	FILE *fp = cb;
587 
588 	(void) fprintf(fp, "\t%-19s  ", zpool_prop_to_name(prop));
589 
590 	if (zpool_prop_readonly(prop))
591 		(void) fprintf(fp, "  NO   ");
592 	else
593 		(void) fprintf(fp, " YES   ");
594 
595 	if (zpool_prop_values(prop) == NULL)
596 		(void) fprintf(fp, "-\n");
597 	else
598 		(void) fprintf(fp, "%s\n", zpool_prop_values(prop));
599 
600 	return (ZPROP_CONT);
601 }
602 
603 /*
604  * Callback routine that will print out a vdev property value.
605  */
606 static int
607 print_vdev_prop_cb(int prop, void *cb)
608 {
609 	FILE *fp = cb;
610 
611 	(void) fprintf(fp, "\t%-19s  ", vdev_prop_to_name(prop));
612 
613 	if (vdev_prop_readonly(prop))
614 		(void) fprintf(fp, "  NO   ");
615 	else
616 		(void) fprintf(fp, " YES   ");
617 
618 	if (vdev_prop_values(prop) == NULL)
619 		(void) fprintf(fp, "-\n");
620 	else
621 		(void) fprintf(fp, "%s\n", vdev_prop_values(prop));
622 
623 	return (ZPROP_CONT);
624 }
625 
626 /*
627  * Given a leaf vdev name like 'L5' return its VDEV_CONFIG_PATH like
628  * '/dev/disk/by-vdev/L5'.
629  */
630 static const char *
631 vdev_name_to_path(zpool_handle_t *zhp, char *vdev)
632 {
633 	nvlist_t *vdev_nv = zpool_find_vdev(zhp, vdev, NULL, NULL, NULL);
634 	if (vdev_nv == NULL) {
635 		return (NULL);
636 	}
637 	return (fnvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH));
638 }
639 
640 static int
641 zpool_power_on(zpool_handle_t *zhp, char *vdev)
642 {
643 	return (zpool_power(zhp, vdev, B_TRUE));
644 }
645 
646 static int
647 zpool_power_on_and_disk_wait(zpool_handle_t *zhp, char *vdev)
648 {
649 	int rc;
650 
651 	rc = zpool_power_on(zhp, vdev);
652 	if (rc != 0)
653 		return (rc);
654 
655 	zpool_disk_wait(vdev_name_to_path(zhp, vdev));
656 
657 	return (0);
658 }
659 
660 static int
661 zpool_power_on_pool_and_wait_for_devices(zpool_handle_t *zhp)
662 {
663 	nvlist_t *nv;
664 	const char *path = NULL;
665 	int rc;
666 
667 	/* Power up all the devices first */
668 	FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
669 		path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
670 		if (path != NULL) {
671 			rc = zpool_power_on(zhp, (char *)path);
672 			if (rc != 0) {
673 				return (rc);
674 			}
675 		}
676 	}
677 
678 	/*
679 	 * Wait for their devices to show up.  Since we powered them on
680 	 * at roughly the same time, they should all come online around
681 	 * the same time.
682 	 */
683 	FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
684 		path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
685 		zpool_disk_wait(path);
686 	}
687 
688 	return (0);
689 }
690 
691 static int
692 zpool_power_off(zpool_handle_t *zhp, char *vdev)
693 {
694 	return (zpool_power(zhp, vdev, B_FALSE));
695 }
696 
697 /*
698  * Display usage message.  If we're inside a command, display only the usage for
699  * that command.  Otherwise, iterate over the entire command table and display
700  * a complete usage message.
701  */
702 static __attribute__((noreturn)) void
703 usage(boolean_t requested)
704 {
705 	FILE *fp = requested ? stdout : stderr;
706 
707 	if (current_command == NULL) {
708 		int i;
709 
710 		(void) fprintf(fp, gettext("usage: zpool command args ...\n"));
711 		(void) fprintf(fp,
712 		    gettext("where 'command' is one of the following:\n\n"));
713 
714 		for (i = 0; i < NCOMMAND; i++) {
715 			if (command_table[i].name == NULL)
716 				(void) fprintf(fp, "\n");
717 			else
718 				(void) fprintf(fp, "%s",
719 				    get_usage(command_table[i].usage));
720 		}
721 
722 		(void) fprintf(fp,
723 		    gettext("\nFor further help on a command or topic, "
724 		    "run: %s\n"), "zpool help [<topic>]");
725 	} else {
726 		(void) fprintf(fp, gettext("usage:\n"));
727 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
728 	}
729 
730 	if (current_command != NULL &&
731 	    current_prop_type != (ZFS_TYPE_POOL | ZFS_TYPE_VDEV) &&
732 	    ((strcmp(current_command->name, "set") == 0) ||
733 	    (strcmp(current_command->name, "get") == 0) ||
734 	    (strcmp(current_command->name, "list") == 0))) {
735 
736 		(void) fprintf(fp, "%s",
737 		    gettext("\nthe following properties are supported:\n"));
738 
739 		(void) fprintf(fp, "\n\t%-19s  %s   %s\n\n",
740 		    "PROPERTY", "EDIT", "VALUES");
741 
742 		/* Iterate over all properties */
743 		if (current_prop_type == ZFS_TYPE_POOL) {
744 			(void) zprop_iter(print_pool_prop_cb, fp, B_FALSE,
745 			    B_TRUE, current_prop_type);
746 
747 			(void) fprintf(fp, "\t%-19s   ", "feature@...");
748 			(void) fprintf(fp, "YES   "
749 			    "disabled | enabled | active\n");
750 
751 			(void) fprintf(fp, gettext("\nThe feature@ properties "
752 			    "must be appended with a feature name.\n"
753 			    "See zpool-features(7).\n"));
754 		} else if (current_prop_type == ZFS_TYPE_VDEV) {
755 			(void) zprop_iter(print_vdev_prop_cb, fp, B_FALSE,
756 			    B_TRUE, current_prop_type);
757 		}
758 	}
759 
760 	/*
761 	 * See comments at end of main().
762 	 */
763 	if (getenv("ZFS_ABORT") != NULL) {
764 		(void) printf("dumping core by request\n");
765 		abort();
766 	}
767 
768 	exit(requested ? 0 : 2);
769 }
770 
771 /*
772  * zpool initialize [-c | -s | -u] [-w] <pool> [<vdev> ...]
773  * Initialize all unused blocks in the specified vdevs, or all vdevs in the pool
774  * if none specified.
775  *
776  *	-c	Cancel. Ends active initializing.
777  *	-s	Suspend. Initializing can then be restarted with no flags.
778  *	-u	Uninitialize. Clears initialization state.
779  *	-w	Wait. Blocks until initializing has completed.
780  */
781 int
782 zpool_do_initialize(int argc, char **argv)
783 {
784 	int c;
785 	char *poolname;
786 	zpool_handle_t *zhp;
787 	nvlist_t *vdevs;
788 	int err = 0;
789 	boolean_t wait = B_FALSE;
790 
791 	struct option long_options[] = {
792 		{"cancel",	no_argument,		NULL, 'c'},
793 		{"suspend",	no_argument,		NULL, 's'},
794 		{"uninit",	no_argument,		NULL, 'u'},
795 		{"wait",	no_argument,		NULL, 'w'},
796 		{0, 0, 0, 0}
797 	};
798 
799 	pool_initialize_func_t cmd_type = POOL_INITIALIZE_START;
800 	while ((c = getopt_long(argc, argv, "csuw", long_options,
801 	    NULL)) != -1) {
802 		switch (c) {
803 		case 'c':
804 			if (cmd_type != POOL_INITIALIZE_START &&
805 			    cmd_type != POOL_INITIALIZE_CANCEL) {
806 				(void) fprintf(stderr, gettext("-c cannot be "
807 				    "combined with other options\n"));
808 				usage(B_FALSE);
809 			}
810 			cmd_type = POOL_INITIALIZE_CANCEL;
811 			break;
812 		case 's':
813 			if (cmd_type != POOL_INITIALIZE_START &&
814 			    cmd_type != POOL_INITIALIZE_SUSPEND) {
815 				(void) fprintf(stderr, gettext("-s cannot be "
816 				    "combined with other options\n"));
817 				usage(B_FALSE);
818 			}
819 			cmd_type = POOL_INITIALIZE_SUSPEND;
820 			break;
821 		case 'u':
822 			if (cmd_type != POOL_INITIALIZE_START &&
823 			    cmd_type != POOL_INITIALIZE_UNINIT) {
824 				(void) fprintf(stderr, gettext("-u cannot be "
825 				    "combined with other options\n"));
826 				usage(B_FALSE);
827 			}
828 			cmd_type = POOL_INITIALIZE_UNINIT;
829 			break;
830 		case 'w':
831 			wait = B_TRUE;
832 			break;
833 		case '?':
834 			if (optopt != 0) {
835 				(void) fprintf(stderr,
836 				    gettext("invalid option '%c'\n"), optopt);
837 			} else {
838 				(void) fprintf(stderr,
839 				    gettext("invalid option '%s'\n"),
840 				    argv[optind - 1]);
841 			}
842 			usage(B_FALSE);
843 		}
844 	}
845 
846 	argc -= optind;
847 	argv += optind;
848 
849 	if (argc < 1) {
850 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
851 		usage(B_FALSE);
852 		return (-1);
853 	}
854 
855 	if (wait && (cmd_type != POOL_INITIALIZE_START)) {
856 		(void) fprintf(stderr, gettext("-w cannot be used with -c, -s"
857 		    "or -u\n"));
858 		usage(B_FALSE);
859 	}
860 
861 	poolname = argv[0];
862 	zhp = zpool_open(g_zfs, poolname);
863 	if (zhp == NULL)
864 		return (-1);
865 
866 	vdevs = fnvlist_alloc();
867 	if (argc == 1) {
868 		/* no individual leaf vdevs specified, so add them all */
869 		nvlist_t *config = zpool_get_config(zhp, NULL);
870 		nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
871 		    ZPOOL_CONFIG_VDEV_TREE);
872 		zpool_collect_leaves(zhp, nvroot, vdevs);
873 	} else {
874 		for (int i = 1; i < argc; i++) {
875 			fnvlist_add_boolean(vdevs, argv[i]);
876 		}
877 	}
878 
879 	if (wait)
880 		err = zpool_initialize_wait(zhp, cmd_type, vdevs);
881 	else
882 		err = zpool_initialize(zhp, cmd_type, vdevs);
883 
884 	fnvlist_free(vdevs);
885 	zpool_close(zhp);
886 
887 	return (err);
888 }
889 
890 /*
891  * print a pool vdev config for dry runs
892  */
893 static void
894 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
895     const char *match, int name_flags)
896 {
897 	nvlist_t **child;
898 	uint_t c, children;
899 	char *vname;
900 	boolean_t printed = B_FALSE;
901 
902 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
903 	    &child, &children) != 0) {
904 		if (name != NULL)
905 			(void) printf("\t%*s%s\n", indent, "", name);
906 		return;
907 	}
908 
909 	for (c = 0; c < children; c++) {
910 		uint64_t is_log = B_FALSE, is_hole = B_FALSE;
911 		const char *class = "";
912 
913 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
914 		    &is_hole);
915 
916 		if (is_hole == B_TRUE) {
917 			continue;
918 		}
919 
920 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
921 		    &is_log);
922 		if (is_log)
923 			class = VDEV_ALLOC_BIAS_LOG;
924 		(void) nvlist_lookup_string(child[c],
925 		    ZPOOL_CONFIG_ALLOCATION_BIAS, &class);
926 		if (strcmp(match, class) != 0)
927 			continue;
928 
929 		if (!printed && name != NULL) {
930 			(void) printf("\t%*s%s\n", indent, "", name);
931 			printed = B_TRUE;
932 		}
933 		vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
934 		print_vdev_tree(zhp, vname, child[c], indent + 2, "",
935 		    name_flags);
936 		free(vname);
937 	}
938 }
939 
940 /*
941  * Print the list of l2cache devices for dry runs.
942  */
943 static void
944 print_cache_list(nvlist_t *nv, int indent)
945 {
946 	nvlist_t **child;
947 	uint_t c, children;
948 
949 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
950 	    &child, &children) == 0 && children > 0) {
951 		(void) printf("\t%*s%s\n", indent, "", "cache");
952 	} else {
953 		return;
954 	}
955 	for (c = 0; c < children; c++) {
956 		char *vname;
957 
958 		vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
959 		(void) printf("\t%*s%s\n", indent + 2, "", vname);
960 		free(vname);
961 	}
962 }
963 
964 /*
965  * Print the list of spares for dry runs.
966  */
967 static void
968 print_spare_list(nvlist_t *nv, int indent)
969 {
970 	nvlist_t **child;
971 	uint_t c, children;
972 
973 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
974 	    &child, &children) == 0 && children > 0) {
975 		(void) printf("\t%*s%s\n", indent, "", "spares");
976 	} else {
977 		return;
978 	}
979 	for (c = 0; c < children; c++) {
980 		char *vname;
981 
982 		vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
983 		(void) printf("\t%*s%s\n", indent + 2, "", vname);
984 		free(vname);
985 	}
986 }
987 
988 typedef struct spare_cbdata {
989 	uint64_t	cb_guid;
990 	zpool_handle_t	*cb_zhp;
991 } spare_cbdata_t;
992 
993 static boolean_t
994 find_vdev(nvlist_t *nv, uint64_t search)
995 {
996 	uint64_t guid;
997 	nvlist_t **child;
998 	uint_t c, children;
999 
1000 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1001 	    search == guid)
1002 		return (B_TRUE);
1003 
1004 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1005 	    &child, &children) == 0) {
1006 		for (c = 0; c < children; c++)
1007 			if (find_vdev(child[c], search))
1008 				return (B_TRUE);
1009 	}
1010 
1011 	return (B_FALSE);
1012 }
1013 
1014 static int
1015 find_spare(zpool_handle_t *zhp, void *data)
1016 {
1017 	spare_cbdata_t *cbp = data;
1018 	nvlist_t *config, *nvroot;
1019 
1020 	config = zpool_get_config(zhp, NULL);
1021 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1022 	    &nvroot) == 0);
1023 
1024 	if (find_vdev(nvroot, cbp->cb_guid)) {
1025 		cbp->cb_zhp = zhp;
1026 		return (1);
1027 	}
1028 
1029 	zpool_close(zhp);
1030 	return (0);
1031 }
1032 
1033 static void
1034 nice_num_str_nvlist(nvlist_t *item, const char *key, uint64_t value,
1035     boolean_t literal, boolean_t as_int, int format)
1036 {
1037 	char buf[256];
1038 	if (literal) {
1039 		if (!as_int)
1040 			snprintf(buf, 256, "%llu", (u_longlong_t)value);
1041 	} else {
1042 		switch (format) {
1043 		case ZFS_NICENUM_1024:
1044 			zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_1024);
1045 			break;
1046 		case ZFS_NICENUM_BYTES:
1047 			zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_BYTES);
1048 			break;
1049 		case ZFS_NICENUM_TIME:
1050 			zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_TIME);
1051 			break;
1052 		case ZFS_NICE_TIMESTAMP:
1053 			format_timestamp(value, buf, 256);
1054 			break;
1055 		default:
1056 			fprintf(stderr, "Invalid number format");
1057 			exit(1);
1058 		}
1059 	}
1060 	if (as_int)
1061 		fnvlist_add_uint64(item, key, value);
1062 	else
1063 		fnvlist_add_string(item, key, buf);
1064 }
1065 
1066 /*
1067  * Generates an nvlist with output version for every command based on params.
1068  * Purpose of this is to add a version of JSON output, considering the schema
1069  * format might be updated for each command in future.
1070  *
1071  * Schema:
1072  *
1073  * "output_version": {
1074  *    "command": string,
1075  *    "vers_major": integer,
1076  *    "vers_minor": integer,
1077  *  }
1078  */
1079 static nvlist_t *
1080 zpool_json_schema(int maj_v, int min_v)
1081 {
1082 	char cmd[MAX_CMD_LEN];
1083 	nvlist_t *sch = fnvlist_alloc();
1084 	nvlist_t *ov = fnvlist_alloc();
1085 
1086 	snprintf(cmd, MAX_CMD_LEN, "zpool %s", current_command->name);
1087 	fnvlist_add_string(ov, "command", cmd);
1088 	fnvlist_add_uint32(ov, "vers_major", maj_v);
1089 	fnvlist_add_uint32(ov, "vers_minor", min_v);
1090 	fnvlist_add_nvlist(sch, "output_version", ov);
1091 	fnvlist_free(ov);
1092 	return (sch);
1093 }
1094 
1095 static void
1096 fill_pool_info(nvlist_t *list, zpool_handle_t *zhp, boolean_t addtype,
1097     boolean_t as_int)
1098 {
1099 	nvlist_t *config = zpool_get_config(zhp, NULL);
1100 	uint64_t guid = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID);
1101 	uint64_t txg = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG);
1102 
1103 	fnvlist_add_string(list, "name", zpool_get_name(zhp));
1104 	if (addtype)
1105 		fnvlist_add_string(list, "type", "POOL");
1106 	fnvlist_add_string(list, "state", zpool_get_state_str(zhp));
1107 	if (as_int) {
1108 		if (guid)
1109 			fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_GUID, guid);
1110 		if (txg)
1111 			fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_TXG, txg);
1112 		fnvlist_add_uint64(list, "spa_version", SPA_VERSION);
1113 		fnvlist_add_uint64(list, "zpl_version", ZPL_VERSION);
1114 	} else {
1115 		char value[ZFS_MAXPROPLEN];
1116 		if (guid) {
1117 			snprintf(value, ZFS_MAXPROPLEN, "%llu",
1118 			    (u_longlong_t)guid);
1119 			fnvlist_add_string(list, ZPOOL_CONFIG_POOL_GUID, value);
1120 		}
1121 		if (txg) {
1122 			snprintf(value, ZFS_MAXPROPLEN, "%llu",
1123 			    (u_longlong_t)txg);
1124 			fnvlist_add_string(list, ZPOOL_CONFIG_POOL_TXG, value);
1125 		}
1126 		fnvlist_add_string(list, "spa_version", SPA_VERSION_STRING);
1127 		fnvlist_add_string(list, "zpl_version", ZPL_VERSION_STRING);
1128 	}
1129 }
1130 
1131 static void
1132 used_by_other(zpool_handle_t *zhp, nvlist_t *nvdev, nvlist_t *list)
1133 {
1134 	spare_cbdata_t spare_cb;
1135 	verify(nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID,
1136 	    &spare_cb.cb_guid) == 0);
1137 	if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1138 		if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1139 		    zpool_get_name(zhp)) != 0) {
1140 			fnvlist_add_string(list, "used_by",
1141 			    zpool_get_name(spare_cb.cb_zhp));
1142 		}
1143 		zpool_close(spare_cb.cb_zhp);
1144 	}
1145 }
1146 
1147 static void
1148 fill_vdev_info(nvlist_t *list, zpool_handle_t *zhp, char *name,
1149     boolean_t addtype, boolean_t as_int)
1150 {
1151 	boolean_t l2c = B_FALSE;
1152 	const char *path, *phys, *devid, *bias = NULL;
1153 	uint64_t hole = 0, log = 0, spare = 0;
1154 	vdev_stat_t *vs;
1155 	uint_t c;
1156 	nvlist_t *nvdev;
1157 	nvlist_t *nvdev_parent = NULL;
1158 	char *_name;
1159 
1160 	if (strcmp(name, zpool_get_name(zhp)) != 0)
1161 		_name = name;
1162 	else
1163 		_name = (char *)"root-0";
1164 
1165 	nvdev = zpool_find_vdev(zhp, _name, NULL, &l2c, NULL);
1166 
1167 	fnvlist_add_string(list, "name", name);
1168 	if (addtype)
1169 		fnvlist_add_string(list, "type", "VDEV");
1170 	if (nvdev) {
1171 		const char *type = fnvlist_lookup_string(nvdev,
1172 		    ZPOOL_CONFIG_TYPE);
1173 		if (type)
1174 			fnvlist_add_string(list, "vdev_type", type);
1175 		uint64_t guid = fnvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID);
1176 		if (guid) {
1177 			if (as_int) {
1178 				fnvlist_add_uint64(list, "guid", guid);
1179 			} else {
1180 				char buf[ZFS_MAXPROPLEN];
1181 				snprintf(buf, ZFS_MAXPROPLEN, "%llu",
1182 				    (u_longlong_t)guid);
1183 				fnvlist_add_string(list, "guid", buf);
1184 			}
1185 		}
1186 		if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PATH, &path) == 0)
1187 			fnvlist_add_string(list, "path", path);
1188 		if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PHYS_PATH,
1189 		    &phys) == 0)
1190 			fnvlist_add_string(list, "phys_path", phys);
1191 		if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_DEVID,
1192 		    &devid) == 0)
1193 			fnvlist_add_string(list, "devid", devid);
1194 		(void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_LOG, &log);
1195 		(void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_SPARE,
1196 		    &spare);
1197 		(void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_HOLE, &hole);
1198 		if (hole)
1199 			fnvlist_add_string(list, "class", VDEV_TYPE_HOLE);
1200 		else if (l2c)
1201 			fnvlist_add_string(list, "class", VDEV_TYPE_L2CACHE);
1202 		else if (spare)
1203 			fnvlist_add_string(list, "class", VDEV_TYPE_SPARE);
1204 		else if (log)
1205 			fnvlist_add_string(list, "class", VDEV_TYPE_LOG);
1206 		else {
1207 			(void) nvlist_lookup_string(nvdev,
1208 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
1209 			if (bias != NULL)
1210 				fnvlist_add_string(list, "class", bias);
1211 			else {
1212 				nvdev_parent = NULL;
1213 				nvdev_parent = zpool_find_parent_vdev(zhp,
1214 				    _name, NULL, NULL, NULL);
1215 
1216 				/*
1217 				 * With a mirrored special device, the parent
1218 				 * "mirror" vdev will have
1219 				 * ZPOOL_CONFIG_ALLOCATION_BIAS set to "special"
1220 				 * not the leaf vdevs.  If we're a leaf vdev
1221 				 * in that case we need to look at our parent
1222 				 * to see if they're "special" to know if we
1223 				 * are "special" too.
1224 				 */
1225 				if (nvdev_parent) {
1226 					(void) nvlist_lookup_string(
1227 					    nvdev_parent,
1228 					    ZPOOL_CONFIG_ALLOCATION_BIAS,
1229 					    &bias);
1230 				}
1231 				if (bias != NULL)
1232 					fnvlist_add_string(list, "class", bias);
1233 				else
1234 					fnvlist_add_string(list, "class",
1235 					    "normal");
1236 			}
1237 		}
1238 		if (nvlist_lookup_uint64_array(nvdev, ZPOOL_CONFIG_VDEV_STATS,
1239 		    (uint64_t **)&vs, &c) == 0) {
1240 			fnvlist_add_string(list, "state",
1241 			    vdev_state_str[vs->vs_state]);
1242 		}
1243 	}
1244 }
1245 
1246 static boolean_t
1247 prop_list_contains_feature(nvlist_t *proplist)
1248 {
1249 	nvpair_t *nvp;
1250 	for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
1251 	    nvp = nvlist_next_nvpair(proplist, nvp)) {
1252 		if (zpool_prop_feature(nvpair_name(nvp)))
1253 			return (B_TRUE);
1254 	}
1255 	return (B_FALSE);
1256 }
1257 
1258 /*
1259  * Add a property pair (name, string-value) into a property nvlist.
1260  */
1261 static int
1262 add_prop_list(const char *propname, const char *propval, nvlist_t **props,
1263     boolean_t poolprop)
1264 {
1265 	zpool_prop_t prop = ZPOOL_PROP_INVAL;
1266 	nvlist_t *proplist;
1267 	const char *normnm;
1268 	const char *strval;
1269 
1270 	if (*props == NULL &&
1271 	    nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
1272 		(void) fprintf(stderr,
1273 		    gettext("internal error: out of memory\n"));
1274 		return (1);
1275 	}
1276 
1277 	proplist = *props;
1278 
1279 	if (poolprop) {
1280 		const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
1281 		const char *cname =
1282 		    zpool_prop_to_name(ZPOOL_PROP_COMPATIBILITY);
1283 
1284 		if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
1285 		    (!zpool_prop_feature(propname) &&
1286 		    !zpool_prop_vdev(propname))) {
1287 			(void) fprintf(stderr, gettext("property '%s' is "
1288 			    "not a valid pool or vdev property\n"), propname);
1289 			return (2);
1290 		}
1291 
1292 		/*
1293 		 * feature@ properties and version should not be specified
1294 		 * at the same time.
1295 		 */
1296 		if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
1297 		    nvlist_exists(proplist, vname)) ||
1298 		    (prop == ZPOOL_PROP_VERSION &&
1299 		    prop_list_contains_feature(proplist))) {
1300 			(void) fprintf(stderr, gettext("'feature@' and "
1301 			    "'version' properties cannot be specified "
1302 			    "together\n"));
1303 			return (2);
1304 		}
1305 
1306 		/*
1307 		 * if version is specified, only "legacy" compatibility
1308 		 * may be requested
1309 		 */
1310 		if ((prop == ZPOOL_PROP_COMPATIBILITY &&
1311 		    strcmp(propval, ZPOOL_COMPAT_LEGACY) != 0 &&
1312 		    nvlist_exists(proplist, vname)) ||
1313 		    (prop == ZPOOL_PROP_VERSION &&
1314 		    nvlist_exists(proplist, cname) &&
1315 		    strcmp(fnvlist_lookup_string(proplist, cname),
1316 		    ZPOOL_COMPAT_LEGACY) != 0)) {
1317 			(void) fprintf(stderr, gettext("when 'version' is "
1318 			    "specified, the 'compatibility' feature may only "
1319 			    "be set to '" ZPOOL_COMPAT_LEGACY "'\n"));
1320 			return (2);
1321 		}
1322 
1323 		if (zpool_prop_feature(propname) || zpool_prop_vdev(propname))
1324 			normnm = propname;
1325 		else
1326 			normnm = zpool_prop_to_name(prop);
1327 	} else {
1328 		zfs_prop_t fsprop = zfs_name_to_prop(propname);
1329 
1330 		if (zfs_prop_valid_for_type(fsprop, ZFS_TYPE_FILESYSTEM,
1331 		    B_FALSE)) {
1332 			normnm = zfs_prop_to_name(fsprop);
1333 		} else if (zfs_prop_user(propname) ||
1334 		    zfs_prop_userquota(propname)) {
1335 			normnm = propname;
1336 		} else {
1337 			(void) fprintf(stderr, gettext("property '%s' is "
1338 			    "not a valid filesystem property\n"), propname);
1339 			return (2);
1340 		}
1341 	}
1342 
1343 	if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
1344 	    prop != ZPOOL_PROP_CACHEFILE) {
1345 		(void) fprintf(stderr, gettext("property '%s' "
1346 		    "specified multiple times\n"), propname);
1347 		return (2);
1348 	}
1349 
1350 	if (nvlist_add_string(proplist, normnm, propval) != 0) {
1351 		(void) fprintf(stderr, gettext("internal "
1352 		    "error: out of memory\n"));
1353 		return (1);
1354 	}
1355 
1356 	return (0);
1357 }
1358 
1359 /*
1360  * Set a default property pair (name, string-value) in a property nvlist
1361  */
1362 static int
1363 add_prop_list_default(const char *propname, const char *propval,
1364     nvlist_t **props)
1365 {
1366 	const char *pval;
1367 
1368 	if (nvlist_lookup_string(*props, propname, &pval) == 0)
1369 		return (0);
1370 
1371 	return (add_prop_list(propname, propval, props, B_TRUE));
1372 }
1373 
1374 /*
1375  * zpool add [-afgLnP] [-o property=value] <pool> <vdev> ...
1376  *
1377  *	-a	Disable the ashift validation checks
1378  *	-f	Force addition of devices, even if they appear in use
1379  *	-g	Display guid for individual vdev name.
1380  *	-L	Follow links when resolving vdev path name.
1381  *	-n	Do not add the devices, but display the resulting layout if
1382  *		they were to be added.
1383  *	-o	Set property=value.
1384  *	-P	Display full path for vdev name.
1385  *
1386  * Adds the given vdevs to 'pool'.  As with create, the bulk of this work is
1387  * handled by make_root_vdev(), which constructs the nvlist needed to pass to
1388  * libzfs.
1389  */
1390 int
1391 zpool_do_add(int argc, char **argv)
1392 {
1393 	boolean_t check_replication = B_TRUE;
1394 	boolean_t check_inuse = B_TRUE;
1395 	boolean_t dryrun = B_FALSE;
1396 	boolean_t check_ashift = B_TRUE;
1397 	boolean_t force = B_FALSE;
1398 	int name_flags = 0;
1399 	int c;
1400 	nvlist_t *nvroot;
1401 	char *poolname;
1402 	int ret;
1403 	zpool_handle_t *zhp;
1404 	nvlist_t *config;
1405 	nvlist_t *props = NULL;
1406 	char *propval;
1407 
1408 	struct option long_options[] = {
1409 		{"allow-in-use", no_argument, NULL, ZPOOL_OPTION_ALLOW_INUSE},
1410 		{"allow-replication-mismatch", no_argument, NULL,
1411 		    ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH},
1412 		{"allow-ashift-mismatch", no_argument, NULL,
1413 		    ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH},
1414 		{0, 0, 0, 0}
1415 	};
1416 
1417 	/* check options */
1418 	while ((c = getopt_long(argc, argv, "fgLno:P", long_options, NULL))
1419 	    != -1) {
1420 		switch (c) {
1421 		case 'f':
1422 			force = B_TRUE;
1423 			break;
1424 		case 'g':
1425 			name_flags |= VDEV_NAME_GUID;
1426 			break;
1427 		case 'L':
1428 			name_flags |= VDEV_NAME_FOLLOW_LINKS;
1429 			break;
1430 		case 'n':
1431 			dryrun = B_TRUE;
1432 			break;
1433 		case 'o':
1434 			if ((propval = strchr(optarg, '=')) == NULL) {
1435 				(void) fprintf(stderr, gettext("missing "
1436 				    "'=' for -o option\n"));
1437 				usage(B_FALSE);
1438 			}
1439 			*propval = '\0';
1440 			propval++;
1441 
1442 			if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
1443 			    (add_prop_list(optarg, propval, &props, B_TRUE)))
1444 				usage(B_FALSE);
1445 			break;
1446 		case 'P':
1447 			name_flags |= VDEV_NAME_PATH;
1448 			break;
1449 		case ZPOOL_OPTION_ALLOW_INUSE:
1450 			check_inuse = B_FALSE;
1451 			break;
1452 		case ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH:
1453 			check_replication = B_FALSE;
1454 			break;
1455 		case ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH:
1456 			check_ashift = B_FALSE;
1457 			break;
1458 		case '?':
1459 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1460 			    optopt);
1461 			usage(B_FALSE);
1462 		}
1463 	}
1464 
1465 	argc -= optind;
1466 	argv += optind;
1467 
1468 	/* get pool name and check number of arguments */
1469 	if (argc < 1) {
1470 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
1471 		usage(B_FALSE);
1472 	}
1473 	if (argc < 2) {
1474 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
1475 		usage(B_FALSE);
1476 	}
1477 
1478 	if (force) {
1479 		if (!check_inuse || !check_replication || !check_ashift) {
1480 			(void) fprintf(stderr, gettext("'-f' option is not "
1481 			    "allowed with '--allow-replication-mismatch', "
1482 			    "'--allow-ashift-mismatch', or "
1483 			    "'--allow-in-use'\n"));
1484 			usage(B_FALSE);
1485 		}
1486 		check_inuse = B_FALSE;
1487 		check_replication = B_FALSE;
1488 		check_ashift = B_FALSE;
1489 	}
1490 
1491 	poolname = argv[0];
1492 
1493 	argc--;
1494 	argv++;
1495 
1496 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1497 		return (1);
1498 
1499 	if ((config = zpool_get_config(zhp, NULL)) == NULL) {
1500 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
1501 		    poolname);
1502 		zpool_close(zhp);
1503 		return (1);
1504 	}
1505 
1506 	/* unless manually specified use "ashift" pool property (if set) */
1507 	if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
1508 		int intval;
1509 		zprop_source_t src;
1510 		char strval[ZPOOL_MAXPROPLEN];
1511 
1512 		intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
1513 		if (src != ZPROP_SRC_DEFAULT) {
1514 			(void) sprintf(strval, "%" PRId32, intval);
1515 			verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
1516 			    &props, B_TRUE) == 0);
1517 		}
1518 	}
1519 
1520 	/* pass off to make_root_vdev for processing */
1521 	nvroot = make_root_vdev(zhp, props, !check_inuse,
1522 	    check_replication, B_FALSE, dryrun, argc, argv);
1523 	if (nvroot == NULL) {
1524 		zpool_close(zhp);
1525 		return (1);
1526 	}
1527 
1528 	if (dryrun) {
1529 		nvlist_t *poolnvroot;
1530 		nvlist_t **l2child, **sparechild;
1531 		uint_t l2children, sparechildren, c;
1532 		char *vname;
1533 		boolean_t hadcache = B_FALSE, hadspare = B_FALSE;
1534 
1535 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1536 		    &poolnvroot) == 0);
1537 
1538 		(void) printf(gettext("would update '%s' to the following "
1539 		    "configuration:\n\n"), zpool_get_name(zhp));
1540 
1541 		/* print original main pool and new tree */
1542 		print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
1543 		    name_flags | VDEV_NAME_TYPE_ID);
1544 		print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
1545 
1546 		/* print other classes: 'dedup', 'special', and 'log' */
1547 		if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1548 			print_vdev_tree(zhp, "dedup", poolnvroot, 0,
1549 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1550 			print_vdev_tree(zhp, NULL, nvroot, 0,
1551 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1552 		} else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1553 			print_vdev_tree(zhp, "dedup", nvroot, 0,
1554 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1555 		}
1556 
1557 		if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1558 			print_vdev_tree(zhp, "special", poolnvroot, 0,
1559 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1560 			print_vdev_tree(zhp, NULL, nvroot, 0,
1561 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1562 		} else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1563 			print_vdev_tree(zhp, "special", nvroot, 0,
1564 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1565 		}
1566 
1567 		if (num_logs(poolnvroot) > 0) {
1568 			print_vdev_tree(zhp, "logs", poolnvroot, 0,
1569 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1570 			print_vdev_tree(zhp, NULL, nvroot, 0,
1571 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1572 		} else if (num_logs(nvroot) > 0) {
1573 			print_vdev_tree(zhp, "logs", nvroot, 0,
1574 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1575 		}
1576 
1577 		/* Do the same for the caches */
1578 		if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
1579 		    &l2child, &l2children) == 0 && l2children) {
1580 			hadcache = B_TRUE;
1581 			(void) printf(gettext("\tcache\n"));
1582 			for (c = 0; c < l2children; c++) {
1583 				vname = zpool_vdev_name(g_zfs, NULL,
1584 				    l2child[c], name_flags);
1585 				(void) printf("\t  %s\n", vname);
1586 				free(vname);
1587 			}
1588 		}
1589 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1590 		    &l2child, &l2children) == 0 && l2children) {
1591 			if (!hadcache)
1592 				(void) printf(gettext("\tcache\n"));
1593 			for (c = 0; c < l2children; c++) {
1594 				vname = zpool_vdev_name(g_zfs, NULL,
1595 				    l2child[c], name_flags);
1596 				(void) printf("\t  %s\n", vname);
1597 				free(vname);
1598 			}
1599 		}
1600 		/* And finally the spares */
1601 		if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_SPARES,
1602 		    &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1603 			hadspare = B_TRUE;
1604 			(void) printf(gettext("\tspares\n"));
1605 			for (c = 0; c < sparechildren; c++) {
1606 				vname = zpool_vdev_name(g_zfs, NULL,
1607 				    sparechild[c], name_flags);
1608 				(void) printf("\t  %s\n", vname);
1609 				free(vname);
1610 			}
1611 		}
1612 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1613 		    &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1614 			if (!hadspare)
1615 				(void) printf(gettext("\tspares\n"));
1616 			for (c = 0; c < sparechildren; c++) {
1617 				vname = zpool_vdev_name(g_zfs, NULL,
1618 				    sparechild[c], name_flags);
1619 				(void) printf("\t  %s\n", vname);
1620 				free(vname);
1621 			}
1622 		}
1623 
1624 		ret = 0;
1625 	} else {
1626 		ret = (zpool_add(zhp, nvroot, check_ashift) != 0);
1627 	}
1628 
1629 	nvlist_free(props);
1630 	nvlist_free(nvroot);
1631 	zpool_close(zhp);
1632 
1633 	return (ret);
1634 }
1635 
1636 /*
1637  * zpool remove [-npsw] <pool> <vdev> ...
1638  *
1639  * Removes the given vdev from the pool.
1640  */
1641 int
1642 zpool_do_remove(int argc, char **argv)
1643 {
1644 	char *poolname;
1645 	int i, ret = 0;
1646 	zpool_handle_t *zhp = NULL;
1647 	boolean_t stop = B_FALSE;
1648 	int c;
1649 	boolean_t noop = B_FALSE;
1650 	boolean_t parsable = B_FALSE;
1651 	boolean_t wait = B_FALSE;
1652 
1653 	/* check options */
1654 	while ((c = getopt(argc, argv, "npsw")) != -1) {
1655 		switch (c) {
1656 		case 'n':
1657 			noop = B_TRUE;
1658 			break;
1659 		case 'p':
1660 			parsable = B_TRUE;
1661 			break;
1662 		case 's':
1663 			stop = B_TRUE;
1664 			break;
1665 		case 'w':
1666 			wait = B_TRUE;
1667 			break;
1668 		case '?':
1669 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1670 			    optopt);
1671 			usage(B_FALSE);
1672 		}
1673 	}
1674 
1675 	argc -= optind;
1676 	argv += optind;
1677 
1678 	/* get pool name and check number of arguments */
1679 	if (argc < 1) {
1680 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
1681 		usage(B_FALSE);
1682 	}
1683 
1684 	poolname = argv[0];
1685 
1686 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1687 		return (1);
1688 
1689 	if (stop && noop) {
1690 		zpool_close(zhp);
1691 		(void) fprintf(stderr, gettext("stop request ignored\n"));
1692 		return (0);
1693 	}
1694 
1695 	if (stop) {
1696 		if (argc > 1) {
1697 			(void) fprintf(stderr, gettext("too many arguments\n"));
1698 			usage(B_FALSE);
1699 		}
1700 		if (zpool_vdev_remove_cancel(zhp) != 0)
1701 			ret = 1;
1702 		if (wait) {
1703 			(void) fprintf(stderr, gettext("invalid option "
1704 			    "combination: -w cannot be used with -s\n"));
1705 			usage(B_FALSE);
1706 		}
1707 	} else {
1708 		if (argc < 2) {
1709 			(void) fprintf(stderr, gettext("missing device\n"));
1710 			usage(B_FALSE);
1711 		}
1712 
1713 		for (i = 1; i < argc; i++) {
1714 			if (noop) {
1715 				uint64_t size;
1716 
1717 				if (zpool_vdev_indirect_size(zhp, argv[i],
1718 				    &size) != 0) {
1719 					ret = 1;
1720 					break;
1721 				}
1722 				if (parsable) {
1723 					(void) printf("%s %llu\n",
1724 					    argv[i], (unsigned long long)size);
1725 				} else {
1726 					char valstr[32];
1727 					zfs_nicenum(size, valstr,
1728 					    sizeof (valstr));
1729 					(void) printf("Memory that will be "
1730 					    "used after removing %s: %s\n",
1731 					    argv[i], valstr);
1732 				}
1733 			} else {
1734 				if (zpool_vdev_remove(zhp, argv[i]) != 0)
1735 					ret = 1;
1736 			}
1737 		}
1738 
1739 		if (ret == 0 && wait)
1740 			ret = zpool_wait(zhp, ZPOOL_WAIT_REMOVE);
1741 	}
1742 	zpool_close(zhp);
1743 
1744 	return (ret);
1745 }
1746 
1747 /*
1748  * Return 1 if a vdev is active (being used in a pool)
1749  * Return 0 if a vdev is inactive (offlined or faulted, or not in active pool)
1750  *
1751  * This is useful for checking if a disk in an active pool is offlined or
1752  * faulted.
1753  */
1754 static int
1755 vdev_is_active(char *vdev_path)
1756 {
1757 	int fd;
1758 	fd = open(vdev_path, O_EXCL);
1759 	if (fd < 0) {
1760 		return (1);   /* cant open O_EXCL - disk is active */
1761 	}
1762 
1763 	close(fd);
1764 	return (0);   /* disk is inactive in the pool */
1765 }
1766 
1767 /*
1768  * zpool labelclear [-f] <vdev>
1769  *
1770  *	-f	Force clearing the label for the vdevs which are members of
1771  *		the exported or foreign pools.
1772  *
1773  * Verifies that the vdev is not active and zeros out the label information
1774  * on the device.
1775  */
1776 int
1777 zpool_do_labelclear(int argc, char **argv)
1778 {
1779 	char vdev[MAXPATHLEN];
1780 	char *name = NULL;
1781 	int c, fd = -1, ret = 0;
1782 	nvlist_t *config;
1783 	pool_state_t state;
1784 	boolean_t inuse = B_FALSE;
1785 	boolean_t force = B_FALSE;
1786 
1787 	/* check options */
1788 	while ((c = getopt(argc, argv, "f")) != -1) {
1789 		switch (c) {
1790 		case 'f':
1791 			force = B_TRUE;
1792 			break;
1793 		default:
1794 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1795 			    optopt);
1796 			usage(B_FALSE);
1797 		}
1798 	}
1799 
1800 	argc -= optind;
1801 	argv += optind;
1802 
1803 	/* get vdev name */
1804 	if (argc < 1) {
1805 		(void) fprintf(stderr, gettext("missing vdev name\n"));
1806 		usage(B_FALSE);
1807 	}
1808 	if (argc > 1) {
1809 		(void) fprintf(stderr, gettext("too many arguments\n"));
1810 		usage(B_FALSE);
1811 	}
1812 
1813 	(void) strlcpy(vdev, argv[0], sizeof (vdev));
1814 
1815 	/*
1816 	 * If we cannot open an absolute path, we quit.
1817 	 * Otherwise if the provided vdev name doesn't point to a file,
1818 	 * try prepending expected disk paths and partition numbers.
1819 	 */
1820 	if ((fd = open(vdev, O_RDWR)) < 0) {
1821 		int error;
1822 		if (vdev[0] == '/') {
1823 			(void) fprintf(stderr, gettext("failed to open "
1824 			    "%s: %s\n"), vdev, strerror(errno));
1825 			return (1);
1826 		}
1827 
1828 		error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
1829 		if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
1830 			if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
1831 				error = ENOENT;
1832 		}
1833 
1834 		if (error || ((fd = open(vdev, O_RDWR)) < 0)) {
1835 			if (errno == ENOENT) {
1836 				(void) fprintf(stderr, gettext(
1837 				    "failed to find device %s, try "
1838 				    "specifying absolute path instead\n"),
1839 				    argv[0]);
1840 				return (1);
1841 			}
1842 
1843 			(void) fprintf(stderr, gettext("failed to open %s:"
1844 			    " %s\n"), vdev, strerror(errno));
1845 			return (1);
1846 		}
1847 	}
1848 
1849 	/*
1850 	 * Flush all dirty pages for the block device.  This should not be
1851 	 * fatal when the device does not support BLKFLSBUF as would be the
1852 	 * case for a file vdev.
1853 	 */
1854 	if ((zfs_dev_flush(fd) != 0) && (errno != ENOTTY))
1855 		(void) fprintf(stderr, gettext("failed to invalidate "
1856 		    "cache for %s: %s\n"), vdev, strerror(errno));
1857 
1858 	if (zpool_read_label(fd, &config, NULL) != 0) {
1859 		(void) fprintf(stderr,
1860 		    gettext("failed to read label from %s\n"), vdev);
1861 		ret = 1;
1862 		goto errout;
1863 	}
1864 	nvlist_free(config);
1865 
1866 	ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1867 	if (ret != 0) {
1868 		(void) fprintf(stderr,
1869 		    gettext("failed to check state for %s\n"), vdev);
1870 		ret = 1;
1871 		goto errout;
1872 	}
1873 
1874 	if (!inuse)
1875 		goto wipe_label;
1876 
1877 	switch (state) {
1878 	default:
1879 	case POOL_STATE_ACTIVE:
1880 	case POOL_STATE_SPARE:
1881 	case POOL_STATE_L2CACHE:
1882 		/*
1883 		 * We allow the user to call 'zpool offline -f'
1884 		 * on an offlined disk in an active pool. We can check if
1885 		 * the disk is online by calling vdev_is_active().
1886 		 */
1887 		if (force && !vdev_is_active(vdev))
1888 			break;
1889 
1890 		(void) fprintf(stderr, gettext(
1891 		    "%s is a member (%s) of pool \"%s\""),
1892 		    vdev, zpool_pool_state_to_name(state), name);
1893 
1894 		if (force) {
1895 			(void) fprintf(stderr, gettext(
1896 			    ". Offline the disk first to clear its label."));
1897 		}
1898 		printf("\n");
1899 		ret = 1;
1900 		goto errout;
1901 
1902 	case POOL_STATE_EXPORTED:
1903 		if (force)
1904 			break;
1905 		(void) fprintf(stderr, gettext(
1906 		    "use '-f' to override the following error:\n"
1907 		    "%s is a member of exported pool \"%s\"\n"),
1908 		    vdev, name);
1909 		ret = 1;
1910 		goto errout;
1911 
1912 	case POOL_STATE_POTENTIALLY_ACTIVE:
1913 		if (force)
1914 			break;
1915 		(void) fprintf(stderr, gettext(
1916 		    "use '-f' to override the following error:\n"
1917 		    "%s is a member of potentially active pool \"%s\"\n"),
1918 		    vdev, name);
1919 		ret = 1;
1920 		goto errout;
1921 
1922 	case POOL_STATE_DESTROYED:
1923 		/* inuse should never be set for a destroyed pool */
1924 		assert(0);
1925 		break;
1926 	}
1927 
1928 wipe_label:
1929 	ret = zpool_clear_label(fd);
1930 	if (ret != 0) {
1931 		(void) fprintf(stderr,
1932 		    gettext("failed to clear label for %s\n"), vdev);
1933 	}
1934 
1935 errout:
1936 	free(name);
1937 	(void) close(fd);
1938 
1939 	return (ret);
1940 }
1941 
1942 /*
1943  * zpool create [-fnd] [-o property=value] ...
1944  *		[-O file-system-property=value] ...
1945  *		[-R root] [-m mountpoint] <pool> <dev> ...
1946  *
1947  *	-f	Force creation, even if devices appear in use
1948  *	-n	Do not create the pool, but display the resulting layout if it
1949  *		were to be created.
1950  *      -R	Create a pool under an alternate root
1951  *      -m	Set default mountpoint for the root dataset.  By default it's
1952  *		'/<pool>'
1953  *	-o	Set property=value.
1954  *	-o	Set feature@feature=enabled|disabled.
1955  *	-d	Don't automatically enable all supported pool features
1956  *		(individual features can be enabled with -o).
1957  *	-O	Set fsproperty=value in the pool's root file system
1958  *
1959  * Creates the named pool according to the given vdev specification.  The
1960  * bulk of the vdev processing is done in make_root_vdev() in zpool_vdev.c.
1961  * Once we get the nvlist back from make_root_vdev(), we either print out the
1962  * contents (if '-n' was specified), or pass it to libzfs to do the creation.
1963  */
1964 int
1965 zpool_do_create(int argc, char **argv)
1966 {
1967 	boolean_t force = B_FALSE;
1968 	boolean_t dryrun = B_FALSE;
1969 	boolean_t enable_pool_features = B_TRUE;
1970 
1971 	int c;
1972 	nvlist_t *nvroot = NULL;
1973 	char *poolname;
1974 	char *tname = NULL;
1975 	int ret = 1;
1976 	char *altroot = NULL;
1977 	char *compat = NULL;
1978 	char *mountpoint = NULL;
1979 	nvlist_t *fsprops = NULL;
1980 	nvlist_t *props = NULL;
1981 	char *propval;
1982 
1983 	/* check options */
1984 	while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
1985 		switch (c) {
1986 		case 'f':
1987 			force = B_TRUE;
1988 			break;
1989 		case 'n':
1990 			dryrun = B_TRUE;
1991 			break;
1992 		case 'd':
1993 			enable_pool_features = B_FALSE;
1994 			break;
1995 		case 'R':
1996 			altroot = optarg;
1997 			if (add_prop_list(zpool_prop_to_name(
1998 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
1999 				goto errout;
2000 			if (add_prop_list_default(zpool_prop_to_name(
2001 			    ZPOOL_PROP_CACHEFILE), "none", &props))
2002 				goto errout;
2003 			break;
2004 		case 'm':
2005 			/* Equivalent to -O mountpoint=optarg */
2006 			mountpoint = optarg;
2007 			break;
2008 		case 'o':
2009 			if ((propval = strchr(optarg, '=')) == NULL) {
2010 				(void) fprintf(stderr, gettext("missing "
2011 				    "'=' for -o option\n"));
2012 				goto errout;
2013 			}
2014 			*propval = '\0';
2015 			propval++;
2016 
2017 			if (add_prop_list(optarg, propval, &props, B_TRUE))
2018 				goto errout;
2019 
2020 			/*
2021 			 * If the user is creating a pool that doesn't support
2022 			 * feature flags, don't enable any features.
2023 			 */
2024 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
2025 				char *end;
2026 				u_longlong_t ver;
2027 
2028 				ver = strtoull(propval, &end, 10);
2029 				if (*end == '\0' &&
2030 				    ver < SPA_VERSION_FEATURES) {
2031 					enable_pool_features = B_FALSE;
2032 				}
2033 			}
2034 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
2035 				altroot = propval;
2036 			if (zpool_name_to_prop(optarg) ==
2037 			    ZPOOL_PROP_COMPATIBILITY)
2038 				compat = propval;
2039 			break;
2040 		case 'O':
2041 			if ((propval = strchr(optarg, '=')) == NULL) {
2042 				(void) fprintf(stderr, gettext("missing "
2043 				    "'=' for -O option\n"));
2044 				goto errout;
2045 			}
2046 			*propval = '\0';
2047 			propval++;
2048 
2049 			/*
2050 			 * Mountpoints are checked and then added later.
2051 			 * Uniquely among properties, they can be specified
2052 			 * more than once, to avoid conflict with -m.
2053 			 */
2054 			if (0 == strcmp(optarg,
2055 			    zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
2056 				mountpoint = propval;
2057 			} else if (add_prop_list(optarg, propval, &fsprops,
2058 			    B_FALSE)) {
2059 				goto errout;
2060 			}
2061 			break;
2062 		case 't':
2063 			/*
2064 			 * Sanity check temporary pool name.
2065 			 */
2066 			if (strchr(optarg, '/') != NULL) {
2067 				(void) fprintf(stderr, gettext("cannot create "
2068 				    "'%s': invalid character '/' in temporary "
2069 				    "name\n"), optarg);
2070 				(void) fprintf(stderr, gettext("use 'zfs "
2071 				    "create' to create a dataset\n"));
2072 				goto errout;
2073 			}
2074 
2075 			if (add_prop_list(zpool_prop_to_name(
2076 			    ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
2077 				goto errout;
2078 			if (add_prop_list_default(zpool_prop_to_name(
2079 			    ZPOOL_PROP_CACHEFILE), "none", &props))
2080 				goto errout;
2081 			tname = optarg;
2082 			break;
2083 		case ':':
2084 			(void) fprintf(stderr, gettext("missing argument for "
2085 			    "'%c' option\n"), optopt);
2086 			goto badusage;
2087 		case '?':
2088 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2089 			    optopt);
2090 			goto badusage;
2091 		}
2092 	}
2093 
2094 	argc -= optind;
2095 	argv += optind;
2096 
2097 	/* get pool name and check number of arguments */
2098 	if (argc < 1) {
2099 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
2100 		goto badusage;
2101 	}
2102 	if (argc < 2) {
2103 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
2104 		goto badusage;
2105 	}
2106 
2107 	poolname = argv[0];
2108 
2109 	/*
2110 	 * As a special case, check for use of '/' in the name, and direct the
2111 	 * user to use 'zfs create' instead.
2112 	 */
2113 	if (strchr(poolname, '/') != NULL) {
2114 		(void) fprintf(stderr, gettext("cannot create '%s': invalid "
2115 		    "character '/' in pool name\n"), poolname);
2116 		(void) fprintf(stderr, gettext("use 'zfs create' to "
2117 		    "create a dataset\n"));
2118 		goto errout;
2119 	}
2120 
2121 	/* pass off to make_root_vdev for bulk processing */
2122 	nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
2123 	    argc - 1, argv + 1);
2124 	if (nvroot == NULL)
2125 		goto errout;
2126 
2127 	/* make_root_vdev() allows 0 toplevel children if there are spares */
2128 	if (!zfs_allocatable_devs(nvroot)) {
2129 		(void) fprintf(stderr, gettext("invalid vdev "
2130 		    "specification: at least one toplevel vdev must be "
2131 		    "specified\n"));
2132 		goto errout;
2133 	}
2134 
2135 	if (altroot != NULL && altroot[0] != '/') {
2136 		(void) fprintf(stderr, gettext("invalid alternate root '%s': "
2137 		    "must be an absolute path\n"), altroot);
2138 		goto errout;
2139 	}
2140 
2141 	/*
2142 	 * Check the validity of the mountpoint and direct the user to use the
2143 	 * '-m' mountpoint option if it looks like its in use.
2144 	 */
2145 	if (mountpoint == NULL ||
2146 	    (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
2147 	    strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
2148 		char buf[MAXPATHLEN];
2149 		DIR *dirp;
2150 
2151 		if (mountpoint && mountpoint[0] != '/') {
2152 			(void) fprintf(stderr, gettext("invalid mountpoint "
2153 			    "'%s': must be an absolute path, 'legacy', or "
2154 			    "'none'\n"), mountpoint);
2155 			goto errout;
2156 		}
2157 
2158 		if (mountpoint == NULL) {
2159 			if (altroot != NULL)
2160 				(void) snprintf(buf, sizeof (buf), "%s/%s",
2161 				    altroot, poolname);
2162 			else
2163 				(void) snprintf(buf, sizeof (buf), "/%s",
2164 				    poolname);
2165 		} else {
2166 			if (altroot != NULL)
2167 				(void) snprintf(buf, sizeof (buf), "%s%s",
2168 				    altroot, mountpoint);
2169 			else
2170 				(void) snprintf(buf, sizeof (buf), "%s",
2171 				    mountpoint);
2172 		}
2173 
2174 		if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
2175 			(void) fprintf(stderr, gettext("mountpoint '%s' : "
2176 			    "%s\n"), buf, strerror(errno));
2177 			(void) fprintf(stderr, gettext("use '-m' "
2178 			    "option to provide a different default\n"));
2179 			goto errout;
2180 		} else if (dirp) {
2181 			int count = 0;
2182 
2183 			while (count < 3 && readdir(dirp) != NULL)
2184 				count++;
2185 			(void) closedir(dirp);
2186 
2187 			if (count > 2) {
2188 				(void) fprintf(stderr, gettext("mountpoint "
2189 				    "'%s' exists and is not empty\n"), buf);
2190 				(void) fprintf(stderr, gettext("use '-m' "
2191 				    "option to provide a "
2192 				    "different default\n"));
2193 				goto errout;
2194 			}
2195 		}
2196 	}
2197 
2198 	/*
2199 	 * Now that the mountpoint's validity has been checked, ensure that
2200 	 * the property is set appropriately prior to creating the pool.
2201 	 */
2202 	if (mountpoint != NULL) {
2203 		ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
2204 		    mountpoint, &fsprops, B_FALSE);
2205 		if (ret != 0)
2206 			goto errout;
2207 	}
2208 
2209 	ret = 1;
2210 	if (dryrun) {
2211 		/*
2212 		 * For a dry run invocation, print out a basic message and run
2213 		 * through all the vdevs in the list and print out in an
2214 		 * appropriate hierarchy.
2215 		 */
2216 		(void) printf(gettext("would create '%s' with the "
2217 		    "following layout:\n\n"), poolname);
2218 
2219 		print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
2220 		print_vdev_tree(NULL, "dedup", nvroot, 0,
2221 		    VDEV_ALLOC_BIAS_DEDUP, 0);
2222 		print_vdev_tree(NULL, "special", nvroot, 0,
2223 		    VDEV_ALLOC_BIAS_SPECIAL, 0);
2224 		print_vdev_tree(NULL, "logs", nvroot, 0,
2225 		    VDEV_ALLOC_BIAS_LOG, 0);
2226 		print_cache_list(nvroot, 0);
2227 		print_spare_list(nvroot, 0);
2228 
2229 		ret = 0;
2230 	} else {
2231 		/*
2232 		 * Load in feature set.
2233 		 * Note: if compatibility property not given, we'll have
2234 		 * NULL, which means 'all features'.
2235 		 */
2236 		boolean_t requested_features[SPA_FEATURES];
2237 		if (zpool_do_load_compat(compat, requested_features) !=
2238 		    ZPOOL_COMPATIBILITY_OK)
2239 			goto errout;
2240 
2241 		/*
2242 		 * props contains list of features to enable.
2243 		 * For each feature:
2244 		 *  - remove it if feature@name=disabled
2245 		 *  - leave it there if feature@name=enabled
2246 		 *  - add it if:
2247 		 *    - enable_pool_features (ie: no '-d' or '-o version')
2248 		 *    - it's supported by the kernel module
2249 		 *    - it's in the requested feature set
2250 		 *  - warn if it's enabled but not in compat
2251 		 */
2252 		for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
2253 			char propname[MAXPATHLEN];
2254 			const char *propval;
2255 			zfeature_info_t *feat = &spa_feature_table[i];
2256 
2257 			(void) snprintf(propname, sizeof (propname),
2258 			    "feature@%s", feat->fi_uname);
2259 
2260 			if (!nvlist_lookup_string(props, propname, &propval)) {
2261 				if (strcmp(propval,
2262 				    ZFS_FEATURE_DISABLED) == 0) {
2263 					(void) nvlist_remove_all(props,
2264 					    propname);
2265 				} else if (strcmp(propval,
2266 				    ZFS_FEATURE_ENABLED) == 0 &&
2267 				    !requested_features[i]) {
2268 					(void) fprintf(stderr, gettext(
2269 					    "Warning: feature \"%s\" enabled "
2270 					    "but is not in specified "
2271 					    "'compatibility' feature set.\n"),
2272 					    feat->fi_uname);
2273 				}
2274 			} else if (
2275 			    enable_pool_features &&
2276 			    feat->fi_zfs_mod_supported &&
2277 			    requested_features[i]) {
2278 				ret = add_prop_list(propname,
2279 				    ZFS_FEATURE_ENABLED, &props, B_TRUE);
2280 				if (ret != 0)
2281 					goto errout;
2282 			}
2283 		}
2284 
2285 		ret = 1;
2286 		if (zpool_create(g_zfs, poolname,
2287 		    nvroot, props, fsprops) == 0) {
2288 			zfs_handle_t *pool = zfs_open(g_zfs,
2289 			    tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
2290 			if (pool != NULL) {
2291 				if (zfs_mount(pool, NULL, 0) == 0) {
2292 					ret = zfs_share(pool, NULL);
2293 					zfs_commit_shares(NULL);
2294 				}
2295 				zfs_close(pool);
2296 			}
2297 		} else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
2298 			(void) fprintf(stderr, gettext("pool name may have "
2299 			    "been omitted\n"));
2300 		}
2301 	}
2302 
2303 errout:
2304 	nvlist_free(nvroot);
2305 	nvlist_free(fsprops);
2306 	nvlist_free(props);
2307 	return (ret);
2308 badusage:
2309 	nvlist_free(fsprops);
2310 	nvlist_free(props);
2311 	usage(B_FALSE);
2312 	return (2);
2313 }
2314 
2315 /*
2316  * zpool destroy <pool>
2317  *
2318  * 	-f	Forcefully unmount any datasets
2319  *
2320  * Destroy the given pool.  Automatically unmounts any datasets in the pool.
2321  */
2322 int
2323 zpool_do_destroy(int argc, char **argv)
2324 {
2325 	boolean_t force = B_FALSE;
2326 	int c;
2327 	char *pool;
2328 	zpool_handle_t *zhp;
2329 	int ret;
2330 
2331 	/* check options */
2332 	while ((c = getopt(argc, argv, "f")) != -1) {
2333 		switch (c) {
2334 		case 'f':
2335 			force = B_TRUE;
2336 			break;
2337 		case '?':
2338 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2339 			    optopt);
2340 			usage(B_FALSE);
2341 		}
2342 	}
2343 
2344 	argc -= optind;
2345 	argv += optind;
2346 
2347 	/* check arguments */
2348 	if (argc < 1) {
2349 		(void) fprintf(stderr, gettext("missing pool argument\n"));
2350 		usage(B_FALSE);
2351 	}
2352 	if (argc > 1) {
2353 		(void) fprintf(stderr, gettext("too many arguments\n"));
2354 		usage(B_FALSE);
2355 	}
2356 
2357 	pool = argv[0];
2358 
2359 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
2360 		/*
2361 		 * As a special case, check for use of '/' in the name, and
2362 		 * direct the user to use 'zfs destroy' instead.
2363 		 */
2364 		if (strchr(pool, '/') != NULL)
2365 			(void) fprintf(stderr, gettext("use 'zfs destroy' to "
2366 			    "destroy a dataset\n"));
2367 		return (1);
2368 	}
2369 
2370 	if (zpool_disable_datasets(zhp, force) != 0) {
2371 		(void) fprintf(stderr, gettext("could not destroy '%s': "
2372 		    "could not unmount datasets\n"), zpool_get_name(zhp));
2373 		zpool_close(zhp);
2374 		return (1);
2375 	}
2376 
2377 	/* The history must be logged as part of the export */
2378 	log_history = B_FALSE;
2379 
2380 	ret = (zpool_destroy(zhp, history_str) != 0);
2381 
2382 	zpool_close(zhp);
2383 
2384 	return (ret);
2385 }
2386 
2387 typedef struct export_cbdata {
2388 	tpool_t *tpool;
2389 	pthread_mutex_t mnttab_lock;
2390 	boolean_t force;
2391 	boolean_t hardforce;
2392 	int retval;
2393 } export_cbdata_t;
2394 
2395 
2396 typedef struct {
2397 	char *aea_poolname;
2398 	export_cbdata_t	*aea_cbdata;
2399 } async_export_args_t;
2400 
2401 /*
2402  * Export one pool
2403  */
2404 static int
2405 zpool_export_one(zpool_handle_t *zhp, void *data)
2406 {
2407 	export_cbdata_t *cb = data;
2408 
2409 	/*
2410 	 * zpool_disable_datasets() is not thread-safe for mnttab access.
2411 	 * So we serialize access here for 'zpool export -a' parallel case.
2412 	 */
2413 	if (cb->tpool != NULL)
2414 		pthread_mutex_lock(&cb->mnttab_lock);
2415 
2416 	int retval = zpool_disable_datasets(zhp, cb->force);
2417 
2418 	if (cb->tpool != NULL)
2419 		pthread_mutex_unlock(&cb->mnttab_lock);
2420 
2421 	if (retval)
2422 		return (1);
2423 
2424 	if (cb->hardforce) {
2425 		if (zpool_export_force(zhp, history_str) != 0)
2426 			return (1);
2427 	} else if (zpool_export(zhp, cb->force, history_str) != 0) {
2428 		return (1);
2429 	}
2430 
2431 	return (0);
2432 }
2433 
2434 /*
2435  * Asynchronous export request
2436  */
2437 static void
2438 zpool_export_task(void *arg)
2439 {
2440 	async_export_args_t *aea = arg;
2441 
2442 	zpool_handle_t *zhp = zpool_open(g_zfs, aea->aea_poolname);
2443 	if (zhp != NULL) {
2444 		int ret = zpool_export_one(zhp, aea->aea_cbdata);
2445 		if (ret != 0)
2446 			aea->aea_cbdata->retval = ret;
2447 		zpool_close(zhp);
2448 	} else {
2449 		aea->aea_cbdata->retval = 1;
2450 	}
2451 
2452 	free(aea->aea_poolname);
2453 	free(aea);
2454 }
2455 
2456 /*
2457  * Process an export request in parallel
2458  */
2459 static int
2460 zpool_export_one_async(zpool_handle_t *zhp, void *data)
2461 {
2462 	tpool_t *tpool = ((export_cbdata_t *)data)->tpool;
2463 	async_export_args_t *aea = safe_malloc(sizeof (async_export_args_t));
2464 
2465 	/* save pool name since zhp will go out of scope */
2466 	aea->aea_poolname = strdup(zpool_get_name(zhp));
2467 	aea->aea_cbdata = data;
2468 
2469 	/* ship off actual export to another thread */
2470 	if (tpool_dispatch(tpool, zpool_export_task, (void *)aea) != 0)
2471 		return (errno);	/* unlikely */
2472 	else
2473 		return (0);
2474 }
2475 
2476 /*
2477  * zpool export [-f] <pool> ...
2478  *
2479  *	-a	Export all pools
2480  *	-f	Forcefully unmount datasets
2481  *
2482  * Export the given pools.  By default, the command will attempt to cleanly
2483  * unmount any active datasets within the pool.  If the '-f' flag is specified,
2484  * then the datasets will be forcefully unmounted.
2485  */
2486 int
2487 zpool_do_export(int argc, char **argv)
2488 {
2489 	export_cbdata_t cb;
2490 	boolean_t do_all = B_FALSE;
2491 	boolean_t force = B_FALSE;
2492 	boolean_t hardforce = B_FALSE;
2493 	int c, ret;
2494 
2495 	/* check options */
2496 	while ((c = getopt(argc, argv, "afF")) != -1) {
2497 		switch (c) {
2498 		case 'a':
2499 			do_all = B_TRUE;
2500 			break;
2501 		case 'f':
2502 			force = B_TRUE;
2503 			break;
2504 		case 'F':
2505 			hardforce = B_TRUE;
2506 			break;
2507 		case '?':
2508 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2509 			    optopt);
2510 			usage(B_FALSE);
2511 		}
2512 	}
2513 
2514 	cb.force = force;
2515 	cb.hardforce = hardforce;
2516 	cb.tpool = NULL;
2517 	cb.retval = 0;
2518 	argc -= optind;
2519 	argv += optind;
2520 
2521 	/* The history will be logged as part of the export itself */
2522 	log_history = B_FALSE;
2523 
2524 	if (do_all) {
2525 		if (argc != 0) {
2526 			(void) fprintf(stderr, gettext("too many arguments\n"));
2527 			usage(B_FALSE);
2528 		}
2529 
2530 		cb.tpool = tpool_create(1, 5 * sysconf(_SC_NPROCESSORS_ONLN),
2531 		    0, NULL);
2532 		pthread_mutex_init(&cb.mnttab_lock, NULL);
2533 
2534 		/* Asynchronously call zpool_export_one using thread pool */
2535 		ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2536 		    B_FALSE, zpool_export_one_async, &cb);
2537 
2538 		tpool_wait(cb.tpool);
2539 		tpool_destroy(cb.tpool);
2540 		(void) pthread_mutex_destroy(&cb.mnttab_lock);
2541 
2542 		return (ret | cb.retval);
2543 	}
2544 
2545 	/* check arguments */
2546 	if (argc < 1) {
2547 		(void) fprintf(stderr, gettext("missing pool argument\n"));
2548 		usage(B_FALSE);
2549 	}
2550 
2551 	ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2552 	    B_FALSE, zpool_export_one, &cb);
2553 
2554 	return (ret);
2555 }
2556 
2557 /*
2558  * Given a vdev configuration, determine the maximum width needed for the device
2559  * name column.
2560  */
2561 static int
2562 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
2563     int name_flags)
2564 {
2565 	static const char *const subtypes[] =
2566 	    {ZPOOL_CONFIG_SPARES, ZPOOL_CONFIG_L2CACHE, ZPOOL_CONFIG_CHILDREN};
2567 
2568 	char *name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
2569 	max = MAX(strlen(name) + depth, max);
2570 	free(name);
2571 
2572 	nvlist_t **child;
2573 	uint_t children;
2574 	for (size_t i = 0; i < ARRAY_SIZE(subtypes); ++i)
2575 		if (nvlist_lookup_nvlist_array(nv, subtypes[i],
2576 		    &child, &children) == 0)
2577 			for (uint_t c = 0; c < children; ++c)
2578 				max = MAX(max_width(zhp, child[c], depth + 2,
2579 				    max, name_flags), max);
2580 
2581 	return (max);
2582 }
2583 
2584 typedef struct status_cbdata {
2585 	int		cb_count;
2586 	int		cb_name_flags;
2587 	int		cb_namewidth;
2588 	boolean_t	cb_allpools;
2589 	boolean_t	cb_verbose;
2590 	boolean_t	cb_literal;
2591 	boolean_t	cb_explain;
2592 	boolean_t	cb_first;
2593 	boolean_t	cb_dedup_stats;
2594 	boolean_t	cb_print_unhealthy;
2595 	boolean_t	cb_print_status;
2596 	boolean_t	cb_print_slow_ios;
2597 	boolean_t	cb_print_vdev_init;
2598 	boolean_t	cb_print_vdev_trim;
2599 	vdev_cmd_data_list_t	*vcdl;
2600 	boolean_t	cb_print_power;
2601 	boolean_t	cb_json;
2602 	boolean_t	cb_flat_vdevs;
2603 	nvlist_t	*cb_jsobj;
2604 	boolean_t	cb_json_as_int;
2605 	boolean_t	cb_json_pool_key_guid;
2606 } status_cbdata_t;
2607 
2608 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
2609 static boolean_t
2610 is_blank_str(const char *str)
2611 {
2612 	for (; str != NULL && *str != '\0'; ++str)
2613 		if (!isblank(*str))
2614 			return (B_FALSE);
2615 	return (B_TRUE);
2616 }
2617 
2618 static void
2619 zpool_nvlist_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path,
2620     nvlist_t *item)
2621 {
2622 	vdev_cmd_data_t *data;
2623 	int i, j, k = 1;
2624 	char tmp[256];
2625 	const char *val;
2626 
2627 	for (i = 0; i < vcdl->count; i++) {
2628 		if ((strcmp(vcdl->data[i].path, path) != 0) ||
2629 		    (strcmp(vcdl->data[i].pool, pool) != 0))
2630 			continue;
2631 
2632 		data = &vcdl->data[i];
2633 		for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2634 			val = NULL;
2635 			for (int k = 0; k < data->cols_cnt; k++) {
2636 				if (strcmp(data->cols[k],
2637 				    vcdl->uniq_cols[j]) == 0) {
2638 					val = data->lines[k];
2639 					break;
2640 				}
2641 			}
2642 			if (val == NULL || is_blank_str(val))
2643 				val = "-";
2644 			fnvlist_add_string(item, vcdl->uniq_cols[j], val);
2645 		}
2646 
2647 		for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2648 			if (data->lines[j]) {
2649 				snprintf(tmp, 256, "extra_%d", k++);
2650 				fnvlist_add_string(item, tmp,
2651 				    data->lines[j]);
2652 			}
2653 		}
2654 		break;
2655 	}
2656 }
2657 
2658 /* Print command output lines for specific vdev in a specific pool */
2659 static void
2660 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path)
2661 {
2662 	vdev_cmd_data_t *data;
2663 	int i, j;
2664 	const char *val;
2665 
2666 	for (i = 0; i < vcdl->count; i++) {
2667 		if ((strcmp(vcdl->data[i].path, path) != 0) ||
2668 		    (strcmp(vcdl->data[i].pool, pool) != 0)) {
2669 			/* Not the vdev we're looking for */
2670 			continue;
2671 		}
2672 
2673 		data = &vcdl->data[i];
2674 		/* Print out all the output values for this vdev */
2675 		for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2676 			val = NULL;
2677 			/* Does this vdev have values for this column? */
2678 			for (int k = 0; k < data->cols_cnt; k++) {
2679 				if (strcmp(data->cols[k],
2680 				    vcdl->uniq_cols[j]) == 0) {
2681 					/* yes it does, record the value */
2682 					val = data->lines[k];
2683 					break;
2684 				}
2685 			}
2686 			/*
2687 			 * Mark empty values with dashes to make output
2688 			 * awk-able.
2689 			 */
2690 			if (val == NULL || is_blank_str(val))
2691 				val = "-";
2692 
2693 			printf("%*s", vcdl->uniq_cols_width[j], val);
2694 			if (j < vcdl->uniq_cols_cnt - 1)
2695 				fputs("  ", stdout);
2696 		}
2697 
2698 		/* Print out any values that aren't in a column at the end */
2699 		for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2700 			/* Did we have any columns?  If so print a spacer. */
2701 			if (vcdl->uniq_cols_cnt > 0)
2702 				fputs("  ", stdout);
2703 
2704 			val = data->lines[j];
2705 			fputs(val ?: "", stdout);
2706 		}
2707 		break;
2708 	}
2709 }
2710 
2711 /*
2712  * Print vdev initialization status for leaves
2713  */
2714 static void
2715 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
2716 {
2717 	if (verbose) {
2718 		if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
2719 		    vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
2720 		    vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
2721 		    !vs->vs_scan_removing) {
2722 			char zbuf[1024];
2723 			char tbuf[256];
2724 
2725 			time_t t = vs->vs_initialize_action_time;
2726 			int initialize_pct = 100;
2727 			if (vs->vs_initialize_state !=
2728 			    VDEV_INITIALIZE_COMPLETE) {
2729 				initialize_pct = (vs->vs_initialize_bytes_done *
2730 				    100 / (vs->vs_initialize_bytes_est + 1));
2731 			}
2732 
2733 			(void) ctime_r(&t, tbuf);
2734 			tbuf[24] = 0;
2735 
2736 			switch (vs->vs_initialize_state) {
2737 			case VDEV_INITIALIZE_SUSPENDED:
2738 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2739 				    gettext("suspended, started at"), tbuf);
2740 				break;
2741 			case VDEV_INITIALIZE_ACTIVE:
2742 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2743 				    gettext("started at"), tbuf);
2744 				break;
2745 			case VDEV_INITIALIZE_COMPLETE:
2746 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2747 				    gettext("completed at"), tbuf);
2748 				break;
2749 			}
2750 
2751 			(void) printf(gettext("  (%d%% initialized%s)"),
2752 			    initialize_pct, zbuf);
2753 		} else {
2754 			(void) printf(gettext("  (uninitialized)"));
2755 		}
2756 	} else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
2757 		(void) printf(gettext("  (initializing)"));
2758 	}
2759 }
2760 
2761 /*
2762  * Print vdev TRIM status for leaves
2763  */
2764 static void
2765 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
2766 {
2767 	if (verbose) {
2768 		if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
2769 		    vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
2770 		    vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
2771 		    !vs->vs_scan_removing) {
2772 			char zbuf[1024];
2773 			char tbuf[256];
2774 
2775 			time_t t = vs->vs_trim_action_time;
2776 			int trim_pct = 100;
2777 			if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
2778 				trim_pct = (vs->vs_trim_bytes_done *
2779 				    100 / (vs->vs_trim_bytes_est + 1));
2780 			}
2781 
2782 			(void) ctime_r(&t, tbuf);
2783 			tbuf[24] = 0;
2784 
2785 			switch (vs->vs_trim_state) {
2786 			case VDEV_TRIM_SUSPENDED:
2787 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2788 				    gettext("suspended, started at"), tbuf);
2789 				break;
2790 			case VDEV_TRIM_ACTIVE:
2791 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2792 				    gettext("started at"), tbuf);
2793 				break;
2794 			case VDEV_TRIM_COMPLETE:
2795 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2796 				    gettext("completed at"), tbuf);
2797 				break;
2798 			}
2799 
2800 			(void) printf(gettext("  (%d%% trimmed%s)"),
2801 			    trim_pct, zbuf);
2802 		} else if (vs->vs_trim_notsup) {
2803 			(void) printf(gettext("  (trim unsupported)"));
2804 		} else {
2805 			(void) printf(gettext("  (untrimmed)"));
2806 		}
2807 	} else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
2808 		(void) printf(gettext("  (trimming)"));
2809 	}
2810 }
2811 
2812 /*
2813  * Return the color associated with a health string.  This includes returning
2814  * NULL for no color change.
2815  */
2816 static const char *
2817 health_str_to_color(const char *health)
2818 {
2819 	if (strcmp(health, gettext("FAULTED")) == 0 ||
2820 	    strcmp(health, gettext("SUSPENDED")) == 0 ||
2821 	    strcmp(health, gettext("UNAVAIL")) == 0) {
2822 		return (ANSI_RED);
2823 	}
2824 
2825 	if (strcmp(health, gettext("OFFLINE")) == 0 ||
2826 	    strcmp(health, gettext("DEGRADED")) == 0 ||
2827 	    strcmp(health, gettext("REMOVED")) == 0) {
2828 		return (ANSI_YELLOW);
2829 	}
2830 
2831 	return (NULL);
2832 }
2833 
2834 /*
2835  * Called for each leaf vdev.  Returns 0 if the vdev is healthy.
2836  * A vdev is unhealthy if any of the following are true:
2837  * 1) there are read, write, or checksum errors,
2838  * 2) its state is not ONLINE, or
2839  * 3) slow IO reporting was requested (-s) and there are slow IOs.
2840  */
2841 static int
2842 vdev_health_check_cb(void *hdl_data, nvlist_t *nv, void *data)
2843 {
2844 	status_cbdata_t *cb = data;
2845 	vdev_stat_t *vs;
2846 	uint_t vsc;
2847 	(void) hdl_data;
2848 
2849 	if (nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2850 	    (uint64_t **)&vs, &vsc) != 0)
2851 		return (1);
2852 
2853 	if (vs->vs_checksum_errors || vs->vs_read_errors ||
2854 	    vs->vs_write_errors || vs->vs_state != VDEV_STATE_HEALTHY)
2855 		return (1);
2856 
2857 	if (cb->cb_print_slow_ios && vs->vs_slow_ios)
2858 		return (1);
2859 
2860 	return (0);
2861 }
2862 
2863 /*
2864  * Print out configuration state as requested by status_callback.
2865  */
2866 static void
2867 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
2868     nvlist_t *nv, int depth, boolean_t isspare, vdev_rebuild_stat_t *vrs)
2869 {
2870 	nvlist_t **child, *root;
2871 	uint_t c, i, vsc, children;
2872 	pool_scan_stat_t *ps = NULL;
2873 	vdev_stat_t *vs;
2874 	char rbuf[6], wbuf[6], cbuf[6];
2875 	char *vname;
2876 	uint64_t notpresent;
2877 	spare_cbdata_t spare_cb;
2878 	const char *state;
2879 	const char *type;
2880 	const char *path = NULL;
2881 	const char *rcolor = NULL, *wcolor = NULL, *ccolor = NULL,
2882 	    *scolor = NULL;
2883 
2884 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2885 	    &child, &children) != 0)
2886 		children = 0;
2887 
2888 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2889 	    (uint64_t **)&vs, &vsc) == 0);
2890 
2891 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2892 
2893 	if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2894 		return;
2895 
2896 	state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2897 
2898 	if (isspare) {
2899 		/*
2900 		 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
2901 		 * online drives.
2902 		 */
2903 		if (vs->vs_aux == VDEV_AUX_SPARED)
2904 			state = gettext("INUSE");
2905 		else if (vs->vs_state == VDEV_STATE_HEALTHY)
2906 			state = gettext("AVAIL");
2907 	}
2908 
2909 	/*
2910 	 * If '-e' is specified then top-level vdevs and their children
2911 	 * can be pruned if all of their leaves are healthy.
2912 	 */
2913 	if (cb->cb_print_unhealthy && depth > 0 &&
2914 	    for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
2915 		return;
2916 	}
2917 
2918 	printf_color(health_str_to_color(state),
2919 	    "\t%*s%-*s  %-8s", depth, "", cb->cb_namewidth - depth,
2920 	    name, state);
2921 
2922 	if (!isspare) {
2923 		if (vs->vs_read_errors)
2924 			rcolor = ANSI_RED;
2925 
2926 		if (vs->vs_write_errors)
2927 			wcolor = ANSI_RED;
2928 
2929 		if (vs->vs_checksum_errors)
2930 			ccolor = ANSI_RED;
2931 
2932 		if (vs->vs_slow_ios)
2933 			scolor = ANSI_BLUE;
2934 
2935 		if (cb->cb_literal) {
2936 			fputc(' ', stdout);
2937 			printf_color(rcolor, "%5llu",
2938 			    (u_longlong_t)vs->vs_read_errors);
2939 			fputc(' ', stdout);
2940 			printf_color(wcolor, "%5llu",
2941 			    (u_longlong_t)vs->vs_write_errors);
2942 			fputc(' ', stdout);
2943 			printf_color(ccolor, "%5llu",
2944 			    (u_longlong_t)vs->vs_checksum_errors);
2945 		} else {
2946 			zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
2947 			zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
2948 			zfs_nicenum(vs->vs_checksum_errors, cbuf,
2949 			    sizeof (cbuf));
2950 			fputc(' ', stdout);
2951 			printf_color(rcolor, "%5s", rbuf);
2952 			fputc(' ', stdout);
2953 			printf_color(wcolor, "%5s", wbuf);
2954 			fputc(' ', stdout);
2955 			printf_color(ccolor, "%5s", cbuf);
2956 		}
2957 		if (cb->cb_print_slow_ios) {
2958 			if (children == 0)  {
2959 				/* Only leafs vdevs have slow IOs */
2960 				zfs_nicenum(vs->vs_slow_ios, rbuf,
2961 				    sizeof (rbuf));
2962 			} else {
2963 				snprintf(rbuf, sizeof (rbuf), "-");
2964 			}
2965 
2966 			if (cb->cb_literal)
2967 				printf_color(scolor, " %5llu",
2968 				    (u_longlong_t)vs->vs_slow_ios);
2969 			else
2970 				printf_color(scolor, " %5s", rbuf);
2971 		}
2972 		if (cb->cb_print_power) {
2973 			if (children == 0)  {
2974 				/* Only leaf vdevs have physical slots */
2975 				switch (zpool_power_current_state(zhp, (char *)
2976 				    fnvlist_lookup_string(nv,
2977 				    ZPOOL_CONFIG_PATH))) {
2978 				case 0:
2979 					printf_color(ANSI_RED, " %5s",
2980 					    gettext("off"));
2981 					break;
2982 				case 1:
2983 					printf(" %5s", gettext("on"));
2984 					break;
2985 				default:
2986 					printf(" %5s", "-");
2987 				}
2988 			} else {
2989 				printf(" %5s", "-");
2990 			}
2991 		}
2992 	}
2993 
2994 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
2995 	    &notpresent) == 0) {
2996 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
2997 		(void) printf("  %s %s", gettext("was"), path);
2998 	} else if (vs->vs_aux != 0) {
2999 		(void) printf("  ");
3000 		color_start(ANSI_RED);
3001 		switch (vs->vs_aux) {
3002 		case VDEV_AUX_OPEN_FAILED:
3003 			(void) printf(gettext("cannot open"));
3004 			break;
3005 
3006 		case VDEV_AUX_BAD_GUID_SUM:
3007 			(void) printf(gettext("missing device"));
3008 			break;
3009 
3010 		case VDEV_AUX_NO_REPLICAS:
3011 			(void) printf(gettext("insufficient replicas"));
3012 			break;
3013 
3014 		case VDEV_AUX_VERSION_NEWER:
3015 			(void) printf(gettext("newer version"));
3016 			break;
3017 
3018 		case VDEV_AUX_UNSUP_FEAT:
3019 			(void) printf(gettext("unsupported feature(s)"));
3020 			break;
3021 
3022 		case VDEV_AUX_ASHIFT_TOO_BIG:
3023 			(void) printf(gettext("unsupported minimum blocksize"));
3024 			break;
3025 
3026 		case VDEV_AUX_SPARED:
3027 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3028 			    &spare_cb.cb_guid) == 0);
3029 			if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
3030 				if (strcmp(zpool_get_name(spare_cb.cb_zhp),
3031 				    zpool_get_name(zhp)) == 0)
3032 					(void) printf(gettext("currently in "
3033 					    "use"));
3034 				else
3035 					(void) printf(gettext("in use by "
3036 					    "pool '%s'"),
3037 					    zpool_get_name(spare_cb.cb_zhp));
3038 				zpool_close(spare_cb.cb_zhp);
3039 			} else {
3040 				(void) printf(gettext("currently in use"));
3041 			}
3042 			break;
3043 
3044 		case VDEV_AUX_ERR_EXCEEDED:
3045 			if (vs->vs_read_errors + vs->vs_write_errors +
3046 			    vs->vs_checksum_errors == 0 && children == 0 &&
3047 			    vs->vs_slow_ios > 0) {
3048 				(void) printf(gettext("too many slow I/Os"));
3049 			} else {
3050 				(void) printf(gettext("too many errors"));
3051 			}
3052 			break;
3053 
3054 		case VDEV_AUX_IO_FAILURE:
3055 			(void) printf(gettext("experienced I/O failures"));
3056 			break;
3057 
3058 		case VDEV_AUX_BAD_LOG:
3059 			(void) printf(gettext("bad intent log"));
3060 			break;
3061 
3062 		case VDEV_AUX_EXTERNAL:
3063 			(void) printf(gettext("external device fault"));
3064 			break;
3065 
3066 		case VDEV_AUX_SPLIT_POOL:
3067 			(void) printf(gettext("split into new pool"));
3068 			break;
3069 
3070 		case VDEV_AUX_ACTIVE:
3071 			(void) printf(gettext("currently in use"));
3072 			break;
3073 
3074 		case VDEV_AUX_CHILDREN_OFFLINE:
3075 			(void) printf(gettext("all children offline"));
3076 			break;
3077 
3078 		case VDEV_AUX_BAD_LABEL:
3079 			(void) printf(gettext("invalid label"));
3080 			break;
3081 
3082 		default:
3083 			(void) printf(gettext("corrupted data"));
3084 			break;
3085 		}
3086 		color_end();
3087 	} else if (children == 0 && !isspare &&
3088 	    getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
3089 	    VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
3090 	    vs->vs_configured_ashift < vs->vs_physical_ashift) {
3091 		(void) printf(
3092 		    gettext("  block size: %dB configured, %dB native"),
3093 		    1 << vs->vs_configured_ashift, 1 << vs->vs_physical_ashift);
3094 	}
3095 
3096 	if (vs->vs_scan_removing != 0) {
3097 		(void) printf(gettext("  (removing)"));
3098 	} else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
3099 		(void) printf(gettext("  (non-allocating)"));
3100 	}
3101 
3102 	/* The root vdev has the scrub/resilver stats */
3103 	root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
3104 	    ZPOOL_CONFIG_VDEV_TREE);
3105 	(void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
3106 	    (uint64_t **)&ps, &c);
3107 
3108 	/*
3109 	 * If you force fault a drive that's resilvering, its scan stats can
3110 	 * get frozen in time, giving the false impression that it's
3111 	 * being resilvered.  That's why we check the state to see if the vdev
3112 	 * is healthy before reporting "resilvering" or "repairing".
3113 	 */
3114 	if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0 &&
3115 	    vs->vs_state == VDEV_STATE_HEALTHY) {
3116 		if (vs->vs_scan_processed != 0) {
3117 			(void) printf(gettext("  (%s)"),
3118 			    (ps->pss_func == POOL_SCAN_RESILVER) ?
3119 			    "resilvering" : "repairing");
3120 		} else if (vs->vs_resilver_deferred) {
3121 			(void) printf(gettext("  (awaiting resilver)"));
3122 		}
3123 	}
3124 
3125 	/* The top-level vdevs have the rebuild stats */
3126 	if (vrs != NULL && vrs->vrs_state == VDEV_REBUILD_ACTIVE &&
3127 	    children == 0 && vs->vs_state == VDEV_STATE_HEALTHY) {
3128 		if (vs->vs_rebuild_processed != 0) {
3129 			(void) printf(gettext("  (resilvering)"));
3130 		}
3131 	}
3132 
3133 	if (cb->vcdl != NULL) {
3134 		if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
3135 			printf("  ");
3136 			zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
3137 		}
3138 	}
3139 
3140 	/* Display vdev initialization and trim status for leaves. */
3141 	if (children == 0) {
3142 		print_status_initialize(vs, cb->cb_print_vdev_init);
3143 		print_status_trim(vs, cb->cb_print_vdev_trim);
3144 	}
3145 
3146 	(void) printf("\n");
3147 
3148 	for (c = 0; c < children; c++) {
3149 		uint64_t islog = B_FALSE, ishole = B_FALSE;
3150 
3151 		/* Don't print logs or holes here */
3152 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3153 		    &islog);
3154 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
3155 		    &ishole);
3156 		if (islog || ishole)
3157 			continue;
3158 		/* Only print normal classes here */
3159 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3160 			continue;
3161 
3162 		/* Provide vdev_rebuild_stats to children if available */
3163 		if (vrs == NULL) {
3164 			(void) nvlist_lookup_uint64_array(nv,
3165 			    ZPOOL_CONFIG_REBUILD_STATS,
3166 			    (uint64_t **)&vrs, &i);
3167 		}
3168 
3169 		vname = zpool_vdev_name(g_zfs, zhp, child[c],
3170 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3171 		print_status_config(zhp, cb, vname, child[c], depth + 2,
3172 		    isspare, vrs);
3173 		free(vname);
3174 	}
3175 }
3176 
3177 /*
3178  * Print the configuration of an exported pool.  Iterate over all vdevs in the
3179  * pool, printing out the name and status for each one.
3180  */
3181 static void
3182 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
3183     int depth)
3184 {
3185 	nvlist_t **child;
3186 	uint_t c, children;
3187 	vdev_stat_t *vs;
3188 	const char *type;
3189 	char *vname;
3190 
3191 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
3192 	if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
3193 	    strcmp(type, VDEV_TYPE_HOLE) == 0)
3194 		return;
3195 
3196 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
3197 	    (uint64_t **)&vs, &c) == 0);
3198 
3199 	(void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
3200 	(void) printf("  %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
3201 
3202 	if (vs->vs_aux != 0) {
3203 		(void) printf("  ");
3204 
3205 		switch (vs->vs_aux) {
3206 		case VDEV_AUX_OPEN_FAILED:
3207 			(void) printf(gettext("cannot open"));
3208 			break;
3209 
3210 		case VDEV_AUX_BAD_GUID_SUM:
3211 			(void) printf(gettext("missing device"));
3212 			break;
3213 
3214 		case VDEV_AUX_NO_REPLICAS:
3215 			(void) printf(gettext("insufficient replicas"));
3216 			break;
3217 
3218 		case VDEV_AUX_VERSION_NEWER:
3219 			(void) printf(gettext("newer version"));
3220 			break;
3221 
3222 		case VDEV_AUX_UNSUP_FEAT:
3223 			(void) printf(gettext("unsupported feature(s)"));
3224 			break;
3225 
3226 		case VDEV_AUX_ERR_EXCEEDED:
3227 			(void) printf(gettext("too many errors"));
3228 			break;
3229 
3230 		case VDEV_AUX_ACTIVE:
3231 			(void) printf(gettext("currently in use"));
3232 			break;
3233 
3234 		case VDEV_AUX_CHILDREN_OFFLINE:
3235 			(void) printf(gettext("all children offline"));
3236 			break;
3237 
3238 		case VDEV_AUX_BAD_LABEL:
3239 			(void) printf(gettext("invalid label"));
3240 			break;
3241 
3242 		default:
3243 			(void) printf(gettext("corrupted data"));
3244 			break;
3245 		}
3246 	}
3247 	(void) printf("\n");
3248 
3249 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
3250 	    &child, &children) != 0)
3251 		return;
3252 
3253 	for (c = 0; c < children; c++) {
3254 		uint64_t is_log = B_FALSE;
3255 
3256 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3257 		    &is_log);
3258 		if (is_log)
3259 			continue;
3260 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3261 			continue;
3262 
3263 		vname = zpool_vdev_name(g_zfs, NULL, child[c],
3264 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3265 		print_import_config(cb, vname, child[c], depth + 2);
3266 		free(vname);
3267 	}
3268 
3269 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
3270 	    &child, &children) == 0) {
3271 		(void) printf(gettext("\tcache\n"));
3272 		for (c = 0; c < children; c++) {
3273 			vname = zpool_vdev_name(g_zfs, NULL, child[c],
3274 			    cb->cb_name_flags);
3275 			(void) printf("\t  %s\n", vname);
3276 			free(vname);
3277 		}
3278 	}
3279 
3280 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
3281 	    &child, &children) == 0) {
3282 		(void) printf(gettext("\tspares\n"));
3283 		for (c = 0; c < children; c++) {
3284 			vname = zpool_vdev_name(g_zfs, NULL, child[c],
3285 			    cb->cb_name_flags);
3286 			(void) printf("\t  %s\n", vname);
3287 			free(vname);
3288 		}
3289 	}
3290 }
3291 
3292 /*
3293  * Print specialized class vdevs.
3294  *
3295  * These are recorded as top level vdevs in the main pool child array
3296  * but with "is_log" set to 1 or an "alloc_bias" string. We use either
3297  * print_status_config() or print_import_config() to print the top level
3298  * class vdevs then any of their children (eg mirrored slogs) are printed
3299  * recursively - which works because only the top level vdev is marked.
3300  */
3301 static void
3302 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
3303     const char *class)
3304 {
3305 	uint_t c, children;
3306 	nvlist_t **child;
3307 	boolean_t printed = B_FALSE;
3308 
3309 	assert(zhp != NULL || !cb->cb_verbose);
3310 
3311 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
3312 	    &children) != 0)
3313 		return;
3314 
3315 	for (c = 0; c < children; c++) {
3316 		uint64_t is_log = B_FALSE;
3317 		const char *bias = NULL;
3318 		const char *type = NULL;
3319 
3320 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3321 		    &is_log);
3322 
3323 		if (is_log) {
3324 			bias = (char *)VDEV_ALLOC_CLASS_LOGS;
3325 		} else {
3326 			(void) nvlist_lookup_string(child[c],
3327 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
3328 			(void) nvlist_lookup_string(child[c],
3329 			    ZPOOL_CONFIG_TYPE, &type);
3330 		}
3331 
3332 		if (bias == NULL || strcmp(bias, class) != 0)
3333 			continue;
3334 		if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
3335 			continue;
3336 
3337 		if (!printed) {
3338 			(void) printf("\t%s\t\n", gettext(class));
3339 			printed = B_TRUE;
3340 		}
3341 
3342 		char *name = zpool_vdev_name(g_zfs, zhp, child[c],
3343 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3344 		if (cb->cb_print_status)
3345 			print_status_config(zhp, cb, name, child[c], 2,
3346 			    B_FALSE, NULL);
3347 		else
3348 			print_import_config(cb, name, child[c], 2);
3349 		free(name);
3350 	}
3351 }
3352 
3353 /*
3354  * Display the status for the given pool.
3355  */
3356 static int
3357 show_import(nvlist_t *config, boolean_t report_error)
3358 {
3359 	uint64_t pool_state;
3360 	vdev_stat_t *vs;
3361 	const char *name;
3362 	uint64_t guid;
3363 	uint64_t hostid = 0;
3364 	const char *msgid;
3365 	const char *hostname = "unknown";
3366 	nvlist_t *nvroot, *nvinfo;
3367 	zpool_status_t reason;
3368 	zpool_errata_t errata;
3369 	const char *health;
3370 	uint_t vsc;
3371 	const char *comment;
3372 	const char *indent;
3373 	char buf[2048];
3374 	status_cbdata_t cb = { 0 };
3375 
3376 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3377 	    &name) == 0);
3378 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3379 	    &guid) == 0);
3380 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3381 	    &pool_state) == 0);
3382 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3383 	    &nvroot) == 0);
3384 
3385 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
3386 	    (uint64_t **)&vs, &vsc) == 0);
3387 	health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
3388 
3389 	reason = zpool_import_status(config, &msgid, &errata);
3390 
3391 	/*
3392 	 * If we're importing using a cachefile, then we won't report any
3393 	 * errors unless we are in the scan phase of the import.
3394 	 */
3395 	if (reason != ZPOOL_STATUS_OK && !report_error)
3396 		return (reason);
3397 
3398 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0) {
3399 		indent = " ";
3400 	} else {
3401 		comment = NULL;
3402 		indent = "";
3403 	}
3404 
3405 	(void) printf(gettext("%s  pool: %s\n"), indent, name);
3406 	(void) printf(gettext("%s    id: %llu\n"), indent, (u_longlong_t)guid);
3407 	(void) printf(gettext("%s state: %s"), indent, health);
3408 	if (pool_state == POOL_STATE_DESTROYED)
3409 		(void) printf(gettext(" (DESTROYED)"));
3410 	(void) printf("\n");
3411 
3412 	if (reason != ZPOOL_STATUS_OK) {
3413 		(void) printf("%s", indent);
3414 		printf_color(ANSI_BOLD, gettext("status: "));
3415 	}
3416 	switch (reason) {
3417 	case ZPOOL_STATUS_MISSING_DEV_R:
3418 	case ZPOOL_STATUS_MISSING_DEV_NR:
3419 	case ZPOOL_STATUS_BAD_GUID_SUM:
3420 		printf_color(ANSI_YELLOW, gettext("One or more devices are "
3421 		    "missing from the system.\n"));
3422 		break;
3423 
3424 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
3425 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
3426 		printf_color(ANSI_YELLOW, gettext("One or more devices "
3427 		    "contains corrupted data.\n"));
3428 		break;
3429 
3430 	case ZPOOL_STATUS_CORRUPT_DATA:
3431 		printf_color(ANSI_YELLOW, gettext("The pool data is "
3432 		    "corrupted.\n"));
3433 		break;
3434 
3435 	case ZPOOL_STATUS_OFFLINE_DEV:
3436 		printf_color(ANSI_YELLOW, gettext("One or more devices "
3437 		    "are offlined.\n"));
3438 		break;
3439 
3440 	case ZPOOL_STATUS_CORRUPT_POOL:
3441 		printf_color(ANSI_YELLOW, gettext("The pool metadata is "
3442 		    "corrupted.\n"));
3443 		break;
3444 
3445 	case ZPOOL_STATUS_VERSION_OLDER:
3446 		printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
3447 		    "a legacy on-disk version.\n"));
3448 		break;
3449 
3450 	case ZPOOL_STATUS_VERSION_NEWER:
3451 		printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
3452 		    "an incompatible version.\n"));
3453 		break;
3454 
3455 	case ZPOOL_STATUS_FEAT_DISABLED:
3456 		printf_color(ANSI_YELLOW, gettext("Some supported "
3457 		    "features are not enabled on the pool.\n"
3458 		    "\t%s(Note that they may be intentionally disabled if the\n"
3459 		    "\t%s'compatibility' property is set.)\n"), indent, indent);
3460 		break;
3461 
3462 	case ZPOOL_STATUS_COMPATIBILITY_ERR:
3463 		printf_color(ANSI_YELLOW, gettext("Error reading or parsing "
3464 		    "the file(s) indicated by the 'compatibility'\n"
3465 		    "\t%sproperty.\n"), indent);
3466 		break;
3467 
3468 	case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
3469 		printf_color(ANSI_YELLOW, gettext("One or more features "
3470 		    "are enabled on the pool despite not being\n"
3471 		    "\t%srequested by the 'compatibility' property.\n"),
3472 		    indent);
3473 		break;
3474 
3475 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
3476 		printf_color(ANSI_YELLOW, gettext("The pool uses the following "
3477 		    "feature(s) not supported on this system:\n"));
3478 		color_start(ANSI_YELLOW);
3479 		zpool_collect_unsup_feat(config, buf, 2048);
3480 		(void) printf("%s", buf);
3481 		color_end();
3482 		break;
3483 
3484 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3485 		printf_color(ANSI_YELLOW, gettext("The pool can only be "
3486 		    "accessed in read-only mode on this system. It\n"
3487 		    "\t%scannot be accessed in read-write mode because it uses "
3488 		    "the following\n"
3489 		    "\t%sfeature(s) not supported on this system:\n"),
3490 		    indent, indent);
3491 		color_start(ANSI_YELLOW);
3492 		zpool_collect_unsup_feat(config, buf, 2048);
3493 		(void) printf("%s", buf);
3494 		color_end();
3495 		break;
3496 
3497 	case ZPOOL_STATUS_HOSTID_ACTIVE:
3498 		printf_color(ANSI_YELLOW, gettext("The pool is currently "
3499 		    "imported by another system.\n"));
3500 		break;
3501 
3502 	case ZPOOL_STATUS_HOSTID_REQUIRED:
3503 		printf_color(ANSI_YELLOW, gettext("The pool has the "
3504 		    "multihost property on.  It cannot\n"
3505 		    "\t%sbe safely imported when the system hostid is not "
3506 		    "set.\n"), indent);
3507 		break;
3508 
3509 	case ZPOOL_STATUS_HOSTID_MISMATCH:
3510 		printf_color(ANSI_YELLOW, gettext("The pool was last accessed "
3511 		    "by another system.\n"));
3512 		break;
3513 
3514 	case ZPOOL_STATUS_FAULTED_DEV_R:
3515 	case ZPOOL_STATUS_FAULTED_DEV_NR:
3516 		printf_color(ANSI_YELLOW, gettext("One or more devices are "
3517 		    "faulted.\n"));
3518 		break;
3519 
3520 	case ZPOOL_STATUS_BAD_LOG:
3521 		printf_color(ANSI_YELLOW, gettext("An intent log record cannot "
3522 		    "be read.\n"));
3523 		break;
3524 
3525 	case ZPOOL_STATUS_RESILVERING:
3526 	case ZPOOL_STATUS_REBUILDING:
3527 		printf_color(ANSI_YELLOW, gettext("One or more devices were "
3528 		    "being resilvered.\n"));
3529 		break;
3530 
3531 	case ZPOOL_STATUS_ERRATA:
3532 		printf_color(ANSI_YELLOW, gettext("Errata #%d detected.\n"),
3533 		    errata);
3534 		break;
3535 
3536 	case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
3537 		printf_color(ANSI_YELLOW, gettext("One or more devices are "
3538 		    "configured to use a non-native block size.\n"
3539 		    "\t%sExpect reduced performance.\n"), indent);
3540 		break;
3541 
3542 	default:
3543 		/*
3544 		 * No other status can be seen when importing pools.
3545 		 */
3546 		assert(reason == ZPOOL_STATUS_OK);
3547 	}
3548 
3549 	/*
3550 	 * Print out an action according to the overall state of the pool.
3551 	 */
3552 	if (vs->vs_state != VDEV_STATE_HEALTHY ||
3553 	    reason != ZPOOL_STATUS_ERRATA || errata != ZPOOL_ERRATA_NONE) {
3554 		(void) printf("%s", indent);
3555 		(void) printf(gettext("action: "));
3556 	}
3557 	if (vs->vs_state == VDEV_STATE_HEALTHY) {
3558 		if (reason == ZPOOL_STATUS_VERSION_OLDER ||
3559 		    reason == ZPOOL_STATUS_FEAT_DISABLED) {
3560 			(void) printf(gettext("The pool can be imported using "
3561 			    "its name or numeric identifier, though\n"
3562 			    "\t%ssome features will not be available without "
3563 			    "an explicit 'zpool upgrade'.\n"), indent);
3564 		} else if (reason == ZPOOL_STATUS_COMPATIBILITY_ERR) {
3565 			(void) printf(gettext("The pool can be imported using "
3566 			    "its name or numeric\n"
3567 			    "\t%sidentifier, though the file(s) indicated by "
3568 			    "its 'compatibility'\n"
3569 			    "\t%sproperty cannot be parsed at this time.\n"),
3570 			    indent, indent);
3571 		} else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
3572 			(void) printf(gettext("The pool can be imported using "
3573 			    "its name or numeric identifier and\n"
3574 			    "\t%sthe '-f' flag.\n"), indent);
3575 		} else if (reason == ZPOOL_STATUS_ERRATA) {
3576 			switch (errata) {
3577 			case ZPOOL_ERRATA_ZOL_2094_SCRUB:
3578 				(void) printf(gettext("The pool can be "
3579 				    "imported using its name or numeric "
3580 				    "identifier,\n"
3581 				    "\t%showever there is a compatibility "
3582 				    "issue which should be corrected\n"
3583 				    "\t%sby running 'zpool scrub'\n"),
3584 				    indent, indent);
3585 				break;
3586 
3587 			case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
3588 				(void) printf(gettext("The pool cannot be "
3589 				    "imported with this version of ZFS due to\n"
3590 				    "\t%san active asynchronous destroy. "
3591 				    "Revert to an earlier version\n"
3592 				    "\t%sand allow the destroy to complete "
3593 				    "before updating.\n"), indent, indent);
3594 				break;
3595 
3596 			case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
3597 				(void) printf(gettext("Existing encrypted "
3598 				    "datasets contain an on-disk "
3599 				    "incompatibility, which\n"
3600 				    "\t%sneeds to be corrected. Backup these "
3601 				    "datasets to new encrypted datasets\n"
3602 				    "\t%sand destroy the old ones.\n"),
3603 				    indent, indent);
3604 				break;
3605 
3606 			case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
3607 				(void) printf(gettext("Existing encrypted "
3608 				    "snapshots and bookmarks contain an "
3609 				    "on-disk\n"
3610 				    "\t%sincompatibility. This may cause "
3611 				    "on-disk corruption if they are used\n"
3612 				    "\t%swith 'zfs recv'. To correct the "
3613 				    "issue, enable the bookmark_v2 feature.\n"
3614 				    "\t%sNo additional action is needed if "
3615 				    "there are no encrypted snapshots or\n"
3616 				    "\t%sbookmarks. If preserving the "
3617 				    "encrypted snapshots and bookmarks is\n"
3618 				    "\t%srequired, use a non-raw send to "
3619 				    "backup and restore them. Alternately,\n"
3620 				    "\t%sthey may be removed to resolve the "
3621 				    "incompatibility.\n"), indent, indent,
3622 				    indent, indent, indent, indent);
3623 				break;
3624 			default:
3625 				/*
3626 				 * All errata must contain an action message.
3627 				 */
3628 				assert(errata == ZPOOL_ERRATA_NONE);
3629 			}
3630 		} else {
3631 			(void) printf(gettext("The pool can be imported using "
3632 			    "its name or numeric identifier.\n"));
3633 		}
3634 	} else if (vs->vs_state == VDEV_STATE_DEGRADED) {
3635 		(void) printf(gettext("The pool can be imported despite "
3636 		    "missing or damaged devices.  The\n"
3637 		    "\t%sfault tolerance of the pool may be compromised if "
3638 		    "imported.\n"), indent);
3639 	} else {
3640 		switch (reason) {
3641 		case ZPOOL_STATUS_VERSION_NEWER:
3642 			(void) printf(gettext("The pool cannot be imported.  "
3643 			    "Access the pool on a system running newer\n"
3644 			    "\t%ssoftware, or recreate the pool from "
3645 			    "backup.\n"), indent);
3646 			break;
3647 		case ZPOOL_STATUS_UNSUP_FEAT_READ:
3648 			(void) printf(gettext("The pool cannot be imported. "
3649 			    "Access the pool on a system that supports\n"
3650 			    "\t%sthe required feature(s), or recreate the pool "
3651 			    "from backup.\n"), indent);
3652 			break;
3653 		case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3654 			(void) printf(gettext("The pool cannot be imported in "
3655 			    "read-write mode. Import the pool with\n"
3656 			    "\t%s'-o readonly=on', access the pool on a system "
3657 			    "that supports the\n"
3658 			    "\t%srequired feature(s), or recreate the pool "
3659 			    "from backup.\n"), indent, indent);
3660 			break;
3661 		case ZPOOL_STATUS_MISSING_DEV_R:
3662 		case ZPOOL_STATUS_MISSING_DEV_NR:
3663 		case ZPOOL_STATUS_BAD_GUID_SUM:
3664 			(void) printf(gettext("The pool cannot be imported. "
3665 			    "Attach the missing\n"
3666 			    "\t%sdevices and try again.\n"), indent);
3667 			break;
3668 		case ZPOOL_STATUS_HOSTID_ACTIVE:
3669 			VERIFY0(nvlist_lookup_nvlist(config,
3670 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
3671 
3672 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3673 				hostname = fnvlist_lookup_string(nvinfo,
3674 				    ZPOOL_CONFIG_MMP_HOSTNAME);
3675 
3676 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3677 				hostid = fnvlist_lookup_uint64(nvinfo,
3678 				    ZPOOL_CONFIG_MMP_HOSTID);
3679 
3680 			(void) printf(gettext("The pool must be exported from "
3681 			    "%s (hostid=%"PRIx64")\n"
3682 			    "\t%sbefore it can be safely imported.\n"),
3683 			    hostname, hostid, indent);
3684 			break;
3685 		case ZPOOL_STATUS_HOSTID_REQUIRED:
3686 			(void) printf(gettext("Set a unique system hostid with "
3687 			    "the zgenhostid(8) command.\n"));
3688 			break;
3689 		default:
3690 			(void) printf(gettext("The pool cannot be imported due "
3691 			    "to damaged devices or data.\n"));
3692 		}
3693 	}
3694 
3695 	/* Print the comment attached to the pool. */
3696 	if (comment != NULL)
3697 		(void) printf(gettext("comment: %s\n"), comment);
3698 
3699 	/*
3700 	 * If the state is "closed" or "can't open", and the aux state
3701 	 * is "corrupt data":
3702 	 */
3703 	if ((vs->vs_state == VDEV_STATE_CLOSED ||
3704 	    vs->vs_state == VDEV_STATE_CANT_OPEN) &&
3705 	    vs->vs_aux == VDEV_AUX_CORRUPT_DATA) {
3706 		if (pool_state == POOL_STATE_DESTROYED)
3707 			(void) printf(gettext("\t%sThe pool was destroyed, "
3708 			    "but can be imported using the '-Df' flags.\n"),
3709 			    indent);
3710 		else if (pool_state != POOL_STATE_EXPORTED)
3711 			(void) printf(gettext("\t%sThe pool may be active on "
3712 			    "another system, but can be imported using\n"
3713 			    "\t%sthe '-f' flag.\n"), indent, indent);
3714 	}
3715 
3716 	if (msgid != NULL) {
3717 		(void) printf(gettext("%s   see: "
3718 		    "https://openzfs.github.io/openzfs-docs/msg/%s\n"),
3719 		    indent, msgid);
3720 	}
3721 
3722 	(void) printf(gettext("%sconfig:\n\n"), indent);
3723 
3724 	cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
3725 	    VDEV_NAME_TYPE_ID);
3726 	if (cb.cb_namewidth < 10)
3727 		cb.cb_namewidth = 10;
3728 
3729 	print_import_config(&cb, name, nvroot, 0);
3730 
3731 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
3732 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
3733 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
3734 
3735 	if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
3736 		(void) printf(gettext("\n\t%sAdditional devices are known to "
3737 		    "be part of this pool, though their\n"
3738 		    "\t%sexact configuration cannot be determined.\n"),
3739 		    indent, indent);
3740 	}
3741 	return (0);
3742 }
3743 
3744 static boolean_t
3745 zfs_force_import_required(nvlist_t *config)
3746 {
3747 	uint64_t state;
3748 	uint64_t hostid = 0;
3749 	nvlist_t *nvinfo;
3750 
3751 	state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
3752 	nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3753 
3754 	/*
3755 	 * The hostid on LOAD_INFO comes from the MOS label via
3756 	 * spa_tryimport(). If its not there then we're likely talking to an
3757 	 * older kernel, so use the top one, which will be from the label
3758 	 * discovered in zpool_find_import(), or if a cachefile is in use, the
3759 	 * local hostid.
3760 	 */
3761 	if (nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_HOSTID, &hostid) != 0)
3762 		(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
3763 		    &hostid);
3764 
3765 	if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
3766 		return (B_TRUE);
3767 
3768 	if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
3769 		mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
3770 		    ZPOOL_CONFIG_MMP_STATE);
3771 
3772 		if (mmp_state != MMP_STATE_INACTIVE)
3773 			return (B_TRUE);
3774 	}
3775 
3776 	return (B_FALSE);
3777 }
3778 
3779 /*
3780  * Perform the import for the given configuration.  This passes the heavy
3781  * lifting off to zpool_import_props(), and then mounts the datasets contained
3782  * within the pool.
3783  */
3784 static int
3785 do_import(nvlist_t *config, const char *newname, const char *mntopts,
3786     nvlist_t *props, int flags, uint_t mntthreads)
3787 {
3788 	int ret = 0;
3789 	int ms_status = 0;
3790 	zpool_handle_t *zhp;
3791 	const char *name;
3792 	uint64_t version;
3793 
3794 	name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
3795 	version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3796 
3797 	if (!SPA_VERSION_IS_SUPPORTED(version)) {
3798 		(void) fprintf(stderr, gettext("cannot import '%s': pool "
3799 		    "is formatted using an unsupported ZFS version\n"), name);
3800 		return (1);
3801 	} else if (zfs_force_import_required(config) &&
3802 	    !(flags & ZFS_IMPORT_ANY_HOST)) {
3803 		mmp_state_t mmp_state = MMP_STATE_INACTIVE;
3804 		nvlist_t *nvinfo;
3805 
3806 		nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3807 		if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
3808 			mmp_state = fnvlist_lookup_uint64(nvinfo,
3809 			    ZPOOL_CONFIG_MMP_STATE);
3810 
3811 		if (mmp_state == MMP_STATE_ACTIVE) {
3812 			const char *hostname = "<unknown>";
3813 			uint64_t hostid = 0;
3814 
3815 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3816 				hostname = fnvlist_lookup_string(nvinfo,
3817 				    ZPOOL_CONFIG_MMP_HOSTNAME);
3818 
3819 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3820 				hostid = fnvlist_lookup_uint64(nvinfo,
3821 				    ZPOOL_CONFIG_MMP_HOSTID);
3822 
3823 			(void) fprintf(stderr, gettext("cannot import '%s': "
3824 			    "pool is imported on %s (hostid: "
3825 			    "0x%"PRIx64")\nExport the pool on the other "
3826 			    "system, then run 'zpool import'.\n"),
3827 			    name, hostname, hostid);
3828 		} else if (mmp_state == MMP_STATE_NO_HOSTID) {
3829 			(void) fprintf(stderr, gettext("Cannot import '%s': "
3830 			    "pool has the multihost property on and the\n"
3831 			    "system's hostid is not set. Set a unique hostid "
3832 			    "with the zgenhostid(8) command.\n"), name);
3833 		} else {
3834 			const char *hostname = "<unknown>";
3835 			time_t timestamp = 0;
3836 			uint64_t hostid = 0;
3837 
3838 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTNAME))
3839 				hostname = fnvlist_lookup_string(nvinfo,
3840 				    ZPOOL_CONFIG_HOSTNAME);
3841 			else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
3842 				hostname = fnvlist_lookup_string(config,
3843 				    ZPOOL_CONFIG_HOSTNAME);
3844 
3845 			if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
3846 				timestamp = fnvlist_lookup_uint64(config,
3847 				    ZPOOL_CONFIG_TIMESTAMP);
3848 
3849 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTID))
3850 				hostid = fnvlist_lookup_uint64(nvinfo,
3851 				    ZPOOL_CONFIG_HOSTID);
3852 			else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
3853 				hostid = fnvlist_lookup_uint64(config,
3854 				    ZPOOL_CONFIG_HOSTID);
3855 
3856 			(void) fprintf(stderr, gettext("cannot import '%s': "
3857 			    "pool was previously in use from another system.\n"
3858 			    "Last accessed by %s (hostid=%"PRIx64") at %s"
3859 			    "The pool can be imported, use 'zpool import -f' "
3860 			    "to import the pool.\n"), name, hostname,
3861 			    hostid, ctime(&timestamp));
3862 		}
3863 
3864 		return (1);
3865 	}
3866 
3867 	if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
3868 		return (1);
3869 
3870 	if (newname != NULL)
3871 		name = newname;
3872 
3873 	if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
3874 		return (1);
3875 
3876 	/*
3877 	 * Loading keys is best effort. We don't want to return immediately
3878 	 * if it fails but we do want to give the error to the caller.
3879 	 */
3880 	if (flags & ZFS_IMPORT_LOAD_KEYS &&
3881 	    zfs_crypto_attempt_load_keys(g_zfs, name) != 0)
3882 			ret = 1;
3883 
3884 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3885 	    !(flags & ZFS_IMPORT_ONLY)) {
3886 		ms_status = zpool_enable_datasets(zhp, mntopts, 0, mntthreads);
3887 		if (ms_status == EZFS_SHAREFAILED) {
3888 			(void) fprintf(stderr, gettext("Import was "
3889 			    "successful, but unable to share some datasets\n"));
3890 		} else if (ms_status == EZFS_MOUNTFAILED) {
3891 			(void) fprintf(stderr, gettext("Import was "
3892 			    "successful, but unable to mount some datasets\n"));
3893 		}
3894 	}
3895 
3896 	zpool_close(zhp);
3897 	return (ret);
3898 }
3899 
3900 typedef struct import_parameters {
3901 	nvlist_t *ip_config;
3902 	const char *ip_mntopts;
3903 	nvlist_t *ip_props;
3904 	int ip_flags;
3905 	uint_t ip_mntthreads;
3906 	int *ip_err;
3907 } import_parameters_t;
3908 
3909 static void
3910 do_import_task(void *arg)
3911 {
3912 	import_parameters_t *ip = arg;
3913 	*ip->ip_err |= do_import(ip->ip_config, NULL, ip->ip_mntopts,
3914 	    ip->ip_props, ip->ip_flags, ip->ip_mntthreads);
3915 	free(ip);
3916 }
3917 
3918 
3919 static int
3920 import_pools(nvlist_t *pools, nvlist_t *props, char *mntopts, int flags,
3921     char *orig_name, char *new_name, importargs_t *import)
3922 {
3923 	nvlist_t *config = NULL;
3924 	nvlist_t *found_config = NULL;
3925 	uint64_t pool_state;
3926 	boolean_t pool_specified = (import->poolname != NULL ||
3927 	    import->guid != 0);
3928 	uint_t npools = 0;
3929 
3930 
3931 	tpool_t *tp = NULL;
3932 	if (import->do_all) {
3933 		tp = tpool_create(1, 5 * sysconf(_SC_NPROCESSORS_ONLN),
3934 		    0, NULL);
3935 	}
3936 
3937 	/*
3938 	 * At this point we have a list of import candidate configs. Even if
3939 	 * we were searching by pool name or guid, we still need to
3940 	 * post-process the list to deal with pool state and possible
3941 	 * duplicate names.
3942 	 */
3943 	int err = 0;
3944 	nvpair_t *elem = NULL;
3945 	boolean_t first = B_TRUE;
3946 	if (!pool_specified && import->do_all) {
3947 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL)
3948 			npools++;
3949 	}
3950 	while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3951 
3952 		verify(nvpair_value_nvlist(elem, &config) == 0);
3953 
3954 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3955 		    &pool_state) == 0);
3956 		if (!import->do_destroyed &&
3957 		    pool_state == POOL_STATE_DESTROYED)
3958 			continue;
3959 		if (import->do_destroyed &&
3960 		    pool_state != POOL_STATE_DESTROYED)
3961 			continue;
3962 
3963 		verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
3964 		    import->policy) == 0);
3965 
3966 		if (!pool_specified) {
3967 			if (first)
3968 				first = B_FALSE;
3969 			else if (!import->do_all)
3970 				(void) fputc('\n', stdout);
3971 
3972 			if (import->do_all) {
3973 				import_parameters_t *ip = safe_malloc(
3974 				    sizeof (import_parameters_t));
3975 
3976 				ip->ip_config = config;
3977 				ip->ip_mntopts = mntopts;
3978 				ip->ip_props = props;
3979 				ip->ip_flags = flags;
3980 				ip->ip_mntthreads = mount_tp_nthr / npools;
3981 				ip->ip_err = &err;
3982 
3983 				(void) tpool_dispatch(tp, do_import_task,
3984 				    (void *)ip);
3985 			} else {
3986 				/*
3987 				 * If we're importing from cachefile, then
3988 				 * we don't want to report errors until we
3989 				 * are in the scan phase of the import. If
3990 				 * we get an error, then we return that error
3991 				 * to invoke the scan phase.
3992 				 */
3993 				if (import->cachefile && !import->scan)
3994 					err = show_import(config, B_FALSE);
3995 				else
3996 					(void) show_import(config, B_TRUE);
3997 			}
3998 		} else if (import->poolname != NULL) {
3999 			const char *name;
4000 
4001 			/*
4002 			 * We are searching for a pool based on name.
4003 			 */
4004 			verify(nvlist_lookup_string(config,
4005 			    ZPOOL_CONFIG_POOL_NAME, &name) == 0);
4006 
4007 			if (strcmp(name, import->poolname) == 0) {
4008 				if (found_config != NULL) {
4009 					(void) fprintf(stderr, gettext(
4010 					    "cannot import '%s': more than "
4011 					    "one matching pool\n"),
4012 					    import->poolname);
4013 					(void) fprintf(stderr, gettext(
4014 					    "import by numeric ID instead\n"));
4015 					err = B_TRUE;
4016 				}
4017 				found_config = config;
4018 			}
4019 		} else {
4020 			uint64_t guid;
4021 
4022 			/*
4023 			 * Search for a pool by guid.
4024 			 */
4025 			verify(nvlist_lookup_uint64(config,
4026 			    ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
4027 
4028 			if (guid == import->guid)
4029 				found_config = config;
4030 		}
4031 	}
4032 	if (import->do_all) {
4033 		tpool_wait(tp);
4034 		tpool_destroy(tp);
4035 	}
4036 
4037 	/*
4038 	 * If we were searching for a specific pool, verify that we found a
4039 	 * pool, and then do the import.
4040 	 */
4041 	if (pool_specified && err == 0) {
4042 		if (found_config == NULL) {
4043 			(void) fprintf(stderr, gettext("cannot import '%s': "
4044 			    "no such pool available\n"), orig_name);
4045 			err = B_TRUE;
4046 		} else {
4047 			err |= do_import(found_config, new_name,
4048 			    mntopts, props, flags, mount_tp_nthr);
4049 		}
4050 	}
4051 
4052 	/*
4053 	 * If we were just looking for pools, report an error if none were
4054 	 * found.
4055 	 */
4056 	if (!pool_specified && first)
4057 		(void) fprintf(stderr,
4058 		    gettext("no pools available to import\n"));
4059 	return (err);
4060 }
4061 
4062 typedef struct target_exists_args {
4063 	const char	*poolname;
4064 	uint64_t	poolguid;
4065 } target_exists_args_t;
4066 
4067 static int
4068 name_or_guid_exists(zpool_handle_t *zhp, void *data)
4069 {
4070 	target_exists_args_t *args = data;
4071 	nvlist_t *config = zpool_get_config(zhp, NULL);
4072 	int found = 0;
4073 
4074 	if (config == NULL)
4075 		return (0);
4076 
4077 	if (args->poolname != NULL) {
4078 		const char *pool_name;
4079 
4080 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4081 		    &pool_name) == 0);
4082 		if (strcmp(pool_name, args->poolname) == 0)
4083 			found = 1;
4084 	} else {
4085 		uint64_t pool_guid;
4086 
4087 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4088 		    &pool_guid) == 0);
4089 		if (pool_guid == args->poolguid)
4090 			found = 1;
4091 	}
4092 	zpool_close(zhp);
4093 
4094 	return (found);
4095 }
4096 /*
4097  * zpool checkpoint <pool>
4098  *       checkpoint --discard <pool>
4099  *
4100  *       -d         Discard the checkpoint from a checkpointed
4101  *       --discard  pool.
4102  *
4103  *       -w         Wait for discarding a checkpoint to complete.
4104  *       --wait
4105  *
4106  * Checkpoints the specified pool, by taking a "snapshot" of its
4107  * current state. A pool can only have one checkpoint at a time.
4108  */
4109 int
4110 zpool_do_checkpoint(int argc, char **argv)
4111 {
4112 	boolean_t discard, wait;
4113 	char *pool;
4114 	zpool_handle_t *zhp;
4115 	int c, err;
4116 
4117 	struct option long_options[] = {
4118 		{"discard", no_argument, NULL, 'd'},
4119 		{"wait", no_argument, NULL, 'w'},
4120 		{0, 0, 0, 0}
4121 	};
4122 
4123 	discard = B_FALSE;
4124 	wait = B_FALSE;
4125 	while ((c = getopt_long(argc, argv, ":dw", long_options, NULL)) != -1) {
4126 		switch (c) {
4127 		case 'd':
4128 			discard = B_TRUE;
4129 			break;
4130 		case 'w':
4131 			wait = B_TRUE;
4132 			break;
4133 		case '?':
4134 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4135 			    optopt);
4136 			usage(B_FALSE);
4137 		}
4138 	}
4139 
4140 	if (wait && !discard) {
4141 		(void) fprintf(stderr, gettext("--wait only valid when "
4142 		    "--discard also specified\n"));
4143 		usage(B_FALSE);
4144 	}
4145 
4146 	argc -= optind;
4147 	argv += optind;
4148 
4149 	if (argc < 1) {
4150 		(void) fprintf(stderr, gettext("missing pool argument\n"));
4151 		usage(B_FALSE);
4152 	}
4153 
4154 	if (argc > 1) {
4155 		(void) fprintf(stderr, gettext("too many arguments\n"));
4156 		usage(B_FALSE);
4157 	}
4158 
4159 	pool = argv[0];
4160 
4161 	if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
4162 		/* As a special case, check for use of '/' in the name */
4163 		if (strchr(pool, '/') != NULL)
4164 			(void) fprintf(stderr, gettext("'zpool checkpoint' "
4165 			    "doesn't work on datasets. To save the state "
4166 			    "of a dataset from a specific point in time "
4167 			    "please use 'zfs snapshot'\n"));
4168 		return (1);
4169 	}
4170 
4171 	if (discard) {
4172 		err = (zpool_discard_checkpoint(zhp) != 0);
4173 		if (err == 0 && wait)
4174 			err = zpool_wait(zhp, ZPOOL_WAIT_CKPT_DISCARD);
4175 	} else {
4176 		err = (zpool_checkpoint(zhp) != 0);
4177 	}
4178 
4179 	zpool_close(zhp);
4180 
4181 	return (err);
4182 }
4183 
4184 #define	CHECKPOINT_OPT	1024
4185 
4186 /*
4187  * zpool prefetch <type> [<type opts>] <pool>
4188  *
4189  * Prefetchs a particular type of data in the specified pool.
4190  */
4191 int
4192 zpool_do_prefetch(int argc, char **argv)
4193 {
4194 	int c;
4195 	char *poolname;
4196 	char *typestr = NULL;
4197 	zpool_prefetch_type_t type;
4198 	zpool_handle_t *zhp;
4199 	int err = 0;
4200 
4201 	while ((c = getopt(argc, argv, "t:")) != -1) {
4202 		switch (c) {
4203 		case 't':
4204 			typestr = optarg;
4205 			break;
4206 		case ':':
4207 			(void) fprintf(stderr, gettext("missing argument for "
4208 			    "'%c' option\n"), optopt);
4209 			usage(B_FALSE);
4210 			break;
4211 		case '?':
4212 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4213 			    optopt);
4214 			usage(B_FALSE);
4215 		}
4216 	}
4217 	argc -= optind;
4218 	argv += optind;
4219 
4220 	if (argc < 1) {
4221 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
4222 		usage(B_FALSE);
4223 	}
4224 
4225 	if (argc > 1) {
4226 		(void) fprintf(stderr, gettext("too many arguments\n"));
4227 		usage(B_FALSE);
4228 	}
4229 
4230 	poolname = argv[0];
4231 
4232 	argc--;
4233 	argv++;
4234 
4235 	if (strcmp(typestr, "ddt") == 0) {
4236 		type = ZPOOL_PREFETCH_DDT;
4237 	} else {
4238 		(void) fprintf(stderr, gettext("unsupported prefetch type\n"));
4239 		usage(B_FALSE);
4240 	}
4241 
4242 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
4243 		return (1);
4244 
4245 	err = zpool_prefetch(zhp, type);
4246 
4247 	zpool_close(zhp);
4248 
4249 	return (err);
4250 }
4251 
4252 /*
4253  * zpool import [-d dir] [-D]
4254  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4255  *              [-d dir | -c cachefile | -s] [-f] -a
4256  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4257  *              [-d dir | -c cachefile | -s] [-f] [-n] [-F] <pool | id>
4258  *              [newpool]
4259  *
4260  *	-c	Read pool information from a cachefile instead of searching
4261  *		devices. If importing from a cachefile config fails, then
4262  *		fallback to searching for devices only in the directories that
4263  *		exist in the cachefile.
4264  *
4265  *	-d	Scan in a specific directory, other than /dev/.  More than
4266  *		one directory can be specified using multiple '-d' options.
4267  *
4268  *	-D	Scan for previously destroyed pools or import all or only
4269  *		specified destroyed pools.
4270  *
4271  *	-R	Temporarily import the pool, with all mountpoints relative to
4272  *		the given root.  The pool will remain exported when the machine
4273  *		is rebooted.
4274  *
4275  *	-V	Import even in the presence of faulted vdevs.  This is an
4276  *		intentionally undocumented option for testing purposes, and
4277  *		treats the pool configuration as complete, leaving any bad
4278  *		vdevs in the FAULTED state. In other words, it does verbatim
4279  *		import.
4280  *
4281  *	-f	Force import, even if it appears that the pool is active.
4282  *
4283  *	-F	Attempt rewind if necessary.
4284  *
4285  *	-n	See if rewind would work, but don't actually rewind.
4286  *
4287  *	-N	Import the pool but don't mount datasets.
4288  *
4289  *	-T	Specify a starting txg to use for import. This option is
4290  *		intentionally undocumented option for testing purposes.
4291  *
4292  *	-a	Import all pools found.
4293  *
4294  *	-l	Load encryption keys while importing.
4295  *
4296  *	-o	Set property=value and/or temporary mount options (without '=').
4297  *
4298  *	-s	Scan using the default search path, the libblkid cache will
4299  *		not be consulted.
4300  *
4301  *	--rewind-to-checkpoint
4302  *		Import the pool and revert back to the checkpoint.
4303  *
4304  * The import command scans for pools to import, and import pools based on pool
4305  * name and GUID.  The pool can also be renamed as part of the import process.
4306  */
4307 int
4308 zpool_do_import(int argc, char **argv)
4309 {
4310 	char **searchdirs = NULL;
4311 	char *env, *envdup = NULL;
4312 	int nsearch = 0;
4313 	int c;
4314 	int err = 0;
4315 	nvlist_t *pools = NULL;
4316 	boolean_t do_all = B_FALSE;
4317 	boolean_t do_destroyed = B_FALSE;
4318 	char *mntopts = NULL;
4319 	uint64_t searchguid = 0;
4320 	char *searchname = NULL;
4321 	char *propval;
4322 	nvlist_t *policy = NULL;
4323 	nvlist_t *props = NULL;
4324 	int flags = ZFS_IMPORT_NORMAL;
4325 	uint32_t rewind_policy = ZPOOL_NO_REWIND;
4326 	boolean_t dryrun = B_FALSE;
4327 	boolean_t do_rewind = B_FALSE;
4328 	boolean_t xtreme_rewind = B_FALSE;
4329 	boolean_t do_scan = B_FALSE;
4330 	boolean_t pool_exists = B_FALSE;
4331 	uint64_t txg = -1ULL;
4332 	char *cachefile = NULL;
4333 	importargs_t idata = { 0 };
4334 	char *endptr;
4335 
4336 	struct option long_options[] = {
4337 		{"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
4338 		{0, 0, 0, 0}
4339 	};
4340 
4341 	/* check options */
4342 	while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmnNo:R:stT:VX",
4343 	    long_options, NULL)) != -1) {
4344 		switch (c) {
4345 		case 'a':
4346 			do_all = B_TRUE;
4347 			break;
4348 		case 'c':
4349 			cachefile = optarg;
4350 			break;
4351 		case 'd':
4352 			searchdirs = safe_realloc(searchdirs,
4353 			    (nsearch + 1) * sizeof (char *));
4354 			searchdirs[nsearch++] = optarg;
4355 			break;
4356 		case 'D':
4357 			do_destroyed = B_TRUE;
4358 			break;
4359 		case 'f':
4360 			flags |= ZFS_IMPORT_ANY_HOST;
4361 			break;
4362 		case 'F':
4363 			do_rewind = B_TRUE;
4364 			break;
4365 		case 'l':
4366 			flags |= ZFS_IMPORT_LOAD_KEYS;
4367 			break;
4368 		case 'm':
4369 			flags |= ZFS_IMPORT_MISSING_LOG;
4370 			break;
4371 		case 'n':
4372 			dryrun = B_TRUE;
4373 			break;
4374 		case 'N':
4375 			flags |= ZFS_IMPORT_ONLY;
4376 			break;
4377 		case 'o':
4378 			if ((propval = strchr(optarg, '=')) != NULL) {
4379 				*propval = '\0';
4380 				propval++;
4381 				if (add_prop_list(optarg, propval,
4382 				    &props, B_TRUE))
4383 					goto error;
4384 			} else {
4385 				mntopts = optarg;
4386 			}
4387 			break;
4388 		case 'R':
4389 			if (add_prop_list(zpool_prop_to_name(
4390 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
4391 				goto error;
4392 			if (add_prop_list_default(zpool_prop_to_name(
4393 			    ZPOOL_PROP_CACHEFILE), "none", &props))
4394 				goto error;
4395 			break;
4396 		case 's':
4397 			do_scan = B_TRUE;
4398 			break;
4399 		case 't':
4400 			flags |= ZFS_IMPORT_TEMP_NAME;
4401 			if (add_prop_list_default(zpool_prop_to_name(
4402 			    ZPOOL_PROP_CACHEFILE), "none", &props))
4403 				goto error;
4404 			break;
4405 
4406 		case 'T':
4407 			errno = 0;
4408 			txg = strtoull(optarg, &endptr, 0);
4409 			if (errno != 0 || *endptr != '\0') {
4410 				(void) fprintf(stderr,
4411 				    gettext("invalid txg value\n"));
4412 				usage(B_FALSE);
4413 			}
4414 			rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
4415 			break;
4416 		case 'V':
4417 			flags |= ZFS_IMPORT_VERBATIM;
4418 			break;
4419 		case 'X':
4420 			xtreme_rewind = B_TRUE;
4421 			break;
4422 		case CHECKPOINT_OPT:
4423 			flags |= ZFS_IMPORT_CHECKPOINT;
4424 			break;
4425 		case ':':
4426 			(void) fprintf(stderr, gettext("missing argument for "
4427 			    "'%c' option\n"), optopt);
4428 			usage(B_FALSE);
4429 			break;
4430 		case '?':
4431 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4432 			    optopt);
4433 			usage(B_FALSE);
4434 		}
4435 	}
4436 
4437 	argc -= optind;
4438 	argv += optind;
4439 
4440 	if (cachefile && nsearch != 0) {
4441 		(void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
4442 		usage(B_FALSE);
4443 	}
4444 
4445 	if (cachefile && do_scan) {
4446 		(void) fprintf(stderr, gettext("-c is incompatible with -s\n"));
4447 		usage(B_FALSE);
4448 	}
4449 
4450 	if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
4451 		(void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
4452 		usage(B_FALSE);
4453 	}
4454 
4455 	if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
4456 		(void) fprintf(stderr, gettext("-l is only meaningful during "
4457 		    "an import\n"));
4458 		usage(B_FALSE);
4459 	}
4460 
4461 	if ((dryrun || xtreme_rewind) && !do_rewind) {
4462 		(void) fprintf(stderr,
4463 		    gettext("-n or -X only meaningful with -F\n"));
4464 		usage(B_FALSE);
4465 	}
4466 	if (dryrun)
4467 		rewind_policy = ZPOOL_TRY_REWIND;
4468 	else if (do_rewind)
4469 		rewind_policy = ZPOOL_DO_REWIND;
4470 	if (xtreme_rewind)
4471 		rewind_policy |= ZPOOL_EXTREME_REWIND;
4472 
4473 	/* In the future, we can capture further policy and include it here */
4474 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
4475 	    nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
4476 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
4477 	    rewind_policy) != 0)
4478 		goto error;
4479 
4480 	/* check argument count */
4481 	if (do_all) {
4482 		if (argc != 0) {
4483 			(void) fprintf(stderr, gettext("too many arguments\n"));
4484 			usage(B_FALSE);
4485 		}
4486 	} else {
4487 		if (argc > 2) {
4488 			(void) fprintf(stderr, gettext("too many arguments\n"));
4489 			usage(B_FALSE);
4490 		}
4491 	}
4492 
4493 	/*
4494 	 * Check for the effective uid.  We do this explicitly here because
4495 	 * otherwise any attempt to discover pools will silently fail.
4496 	 */
4497 	if (argc == 0 && geteuid() != 0) {
4498 		(void) fprintf(stderr, gettext("cannot "
4499 		    "discover pools: permission denied\n"));
4500 
4501 		free(searchdirs);
4502 		nvlist_free(props);
4503 		nvlist_free(policy);
4504 		return (1);
4505 	}
4506 
4507 	/*
4508 	 * Depending on the arguments given, we do one of the following:
4509 	 *
4510 	 *	<none>	Iterate through all pools and display information about
4511 	 *		each one.
4512 	 *
4513 	 *	-a	Iterate through all pools and try to import each one.
4514 	 *
4515 	 *	<id>	Find the pool that corresponds to the given GUID/pool
4516 	 *		name and import that one.
4517 	 *
4518 	 *	-D	Above options applies only to destroyed pools.
4519 	 */
4520 	if (argc != 0) {
4521 		char *endptr;
4522 
4523 		errno = 0;
4524 		searchguid = strtoull(argv[0], &endptr, 10);
4525 		if (errno != 0 || *endptr != '\0') {
4526 			searchname = argv[0];
4527 			searchguid = 0;
4528 		}
4529 
4530 		/*
4531 		 * User specified a name or guid.  Ensure it's unique.
4532 		 */
4533 		target_exists_args_t search = {searchname, searchguid};
4534 		pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
4535 	}
4536 
4537 	/*
4538 	 * Check the environment for the preferred search path.
4539 	 */
4540 	if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
4541 		char *dir, *tmp = NULL;
4542 
4543 		envdup = strdup(env);
4544 
4545 		for (dir = strtok_r(envdup, ":", &tmp);
4546 		    dir != NULL;
4547 		    dir = strtok_r(NULL, ":", &tmp)) {
4548 			searchdirs = safe_realloc(searchdirs,
4549 			    (nsearch + 1) * sizeof (char *));
4550 			searchdirs[nsearch++] = dir;
4551 		}
4552 	}
4553 
4554 	idata.path = searchdirs;
4555 	idata.paths = nsearch;
4556 	idata.poolname = searchname;
4557 	idata.guid = searchguid;
4558 	idata.cachefile = cachefile;
4559 	idata.scan = do_scan;
4560 	idata.policy = policy;
4561 	idata.do_destroyed = do_destroyed;
4562 	idata.do_all = do_all;
4563 
4564 	libpc_handle_t lpch = {
4565 		.lpc_lib_handle = g_zfs,
4566 		.lpc_ops = &libzfs_config_ops,
4567 		.lpc_printerr = B_TRUE
4568 	};
4569 	pools = zpool_search_import(&lpch, &idata);
4570 
4571 	if (pools != NULL && pool_exists &&
4572 	    (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
4573 		(void) fprintf(stderr, gettext("cannot import '%s': "
4574 		    "a pool with that name already exists\n"),
4575 		    argv[0]);
4576 		(void) fprintf(stderr, gettext("use the form '%s "
4577 		    "<pool | id> <newpool>' to give it a new name\n"),
4578 		    "zpool import");
4579 		err = 1;
4580 	} else if (pools == NULL && pool_exists) {
4581 		(void) fprintf(stderr, gettext("cannot import '%s': "
4582 		    "a pool with that name is already created/imported,\n"),
4583 		    argv[0]);
4584 		(void) fprintf(stderr, gettext("and no additional pools "
4585 		    "with that name were found\n"));
4586 		err = 1;
4587 	} else if (pools == NULL) {
4588 		if (argc != 0) {
4589 			(void) fprintf(stderr, gettext("cannot import '%s': "
4590 			    "no such pool available\n"), argv[0]);
4591 		}
4592 		err = 1;
4593 	}
4594 
4595 	if (err == 1) {
4596 		free(searchdirs);
4597 		free(envdup);
4598 		nvlist_free(policy);
4599 		nvlist_free(pools);
4600 		nvlist_free(props);
4601 		return (1);
4602 	}
4603 
4604 	err = import_pools(pools, props, mntopts, flags,
4605 	    argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL, &idata);
4606 
4607 	/*
4608 	 * If we're using the cachefile and we failed to import, then
4609 	 * fallback to scanning the directory for pools that match
4610 	 * those in the cachefile.
4611 	 */
4612 	if (err != 0 && cachefile != NULL) {
4613 		(void) printf(gettext("cachefile import failed, retrying\n"));
4614 
4615 		/*
4616 		 * We use the scan flag to gather the directories that exist
4617 		 * in the cachefile. If we need to fallback to searching for
4618 		 * the pool config, we will only search devices in these
4619 		 * directories.
4620 		 */
4621 		idata.scan = B_TRUE;
4622 		nvlist_free(pools);
4623 		pools = zpool_search_import(&lpch, &idata);
4624 
4625 		err = import_pools(pools, props, mntopts, flags,
4626 		    argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL,
4627 		    &idata);
4628 	}
4629 
4630 error:
4631 	nvlist_free(props);
4632 	nvlist_free(pools);
4633 	nvlist_free(policy);
4634 	free(searchdirs);
4635 	free(envdup);
4636 
4637 	return (err ? 1 : 0);
4638 }
4639 
4640 /*
4641  * zpool sync [-f] [pool] ...
4642  *
4643  * -f (undocumented) force uberblock (and config including zpool cache file)
4644  *    update.
4645  *
4646  * Sync the specified pool(s).
4647  * Without arguments "zpool sync" will sync all pools.
4648  * This command initiates TXG sync(s) and will return after the TXG(s) commit.
4649  *
4650  */
4651 static int
4652 zpool_do_sync(int argc, char **argv)
4653 {
4654 	int ret;
4655 	boolean_t force = B_FALSE;
4656 
4657 	/* check options */
4658 	while ((ret  = getopt(argc, argv, "f")) != -1) {
4659 		switch (ret) {
4660 		case 'f':
4661 			force = B_TRUE;
4662 			break;
4663 		case '?':
4664 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4665 			    optopt);
4666 			usage(B_FALSE);
4667 		}
4668 	}
4669 
4670 	argc -= optind;
4671 	argv += optind;
4672 
4673 	/* if argc == 0 we will execute zpool_sync_one on all pools */
4674 	ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
4675 	    B_FALSE, zpool_sync_one, &force);
4676 
4677 	return (ret);
4678 }
4679 
4680 typedef struct iostat_cbdata {
4681 	uint64_t cb_flags;
4682 	int cb_namewidth;
4683 	int cb_iteration;
4684 	boolean_t cb_verbose;
4685 	boolean_t cb_literal;
4686 	boolean_t cb_scripted;
4687 	zpool_list_t *cb_list;
4688 	vdev_cmd_data_list_t *vcdl;
4689 	vdev_cbdata_t cb_vdevs;
4690 } iostat_cbdata_t;
4691 
4692 /*  iostat labels */
4693 typedef struct name_and_columns {
4694 	const char *name;	/* Column name */
4695 	unsigned int columns;	/* Center name to this number of columns */
4696 } name_and_columns_t;
4697 
4698 #define	IOSTAT_MAX_LABELS	15	/* Max number of labels on one line */
4699 
4700 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
4701 {
4702 	[IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
4703 	    {NULL}},
4704 	[IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4705 	    {"asyncq_wait", 2}, {"scrub", 1}, {"trim", 1}, {"rebuild", 1},
4706 	    {NULL}},
4707 	[IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
4708 	    {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
4709 	    {"trimq_write", 2}, {"rebuildq_write", 2}, {NULL}},
4710 	[IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4711 	    {"asyncq_wait", 2}, {NULL}},
4712 	[IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
4713 	    {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
4714 	    {"trim", 2}, {"rebuild", 2}, {NULL}},
4715 };
4716 
4717 /* Shorthand - if "columns" field not set, default to 1 column */
4718 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
4719 {
4720 	[IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
4721 	    {"write"}, {NULL}},
4722 	[IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4723 	    {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {"wait"},
4724 	    {NULL}},
4725 	[IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
4726 	    {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
4727 	    {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
4728 	[IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4729 	    {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {"rebuild"},
4730 	    {NULL}},
4731 	[IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4732 	    {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4733 	    {"ind"}, {"agg"}, {NULL}},
4734 };
4735 
4736 static const char *histo_to_title[] = {
4737 	[IOS_L_HISTO] = "latency",
4738 	[IOS_RQ_HISTO] = "req_size",
4739 };
4740 
4741 /*
4742  * Return the number of labels in a null-terminated name_and_columns_t
4743  * array.
4744  *
4745  */
4746 static unsigned int
4747 label_array_len(const name_and_columns_t *labels)
4748 {
4749 	int i = 0;
4750 
4751 	while (labels[i].name)
4752 		i++;
4753 
4754 	return (i);
4755 }
4756 
4757 /*
4758  * Return the number of strings in a null-terminated string array.
4759  * For example:
4760  *
4761  *     const char foo[] = {"bar", "baz", NULL}
4762  *
4763  * returns 2
4764  */
4765 static uint64_t
4766 str_array_len(const char *array[])
4767 {
4768 	uint64_t i = 0;
4769 	while (array[i])
4770 		i++;
4771 
4772 	return (i);
4773 }
4774 
4775 
4776 /*
4777  * Return a default column width for default/latency/queue columns. This does
4778  * not include histograms, which have their columns autosized.
4779  */
4780 static unsigned int
4781 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
4782 {
4783 	unsigned long column_width = 5; /* Normal niceprint */
4784 	static unsigned long widths[] = {
4785 		/*
4786 		 * Choose some sane default column sizes for printing the
4787 		 * raw numbers.
4788 		 */
4789 		[IOS_DEFAULT] = 15, /* 1PB capacity */
4790 		[IOS_LATENCY] = 10, /* 1B ns = 10sec */
4791 		[IOS_QUEUES] = 6,   /* 1M queue entries */
4792 		[IOS_L_HISTO] = 10, /* 1B ns = 10sec */
4793 		[IOS_RQ_HISTO] = 6, /* 1M queue entries */
4794 	};
4795 
4796 	if (cb->cb_literal)
4797 		column_width = widths[type];
4798 
4799 	return (column_width);
4800 }
4801 
4802 /*
4803  * Print the column labels, i.e:
4804  *
4805  *   capacity     operations     bandwidth
4806  * alloc   free   read  write   read  write  ...
4807  *
4808  * If force_column_width is set, use it for the column width.  If not set, use
4809  * the default column width.
4810  */
4811 static void
4812 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
4813     const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
4814 {
4815 	int i, idx, s;
4816 	int text_start, rw_column_width, spaces_to_end;
4817 	uint64_t flags = cb->cb_flags;
4818 	uint64_t f;
4819 	unsigned int column_width = force_column_width;
4820 
4821 	/* For each bit set in flags */
4822 	for (f = flags; f; f &= ~(1ULL << idx)) {
4823 		idx = lowbit64(f) - 1;
4824 		if (!force_column_width)
4825 			column_width = default_column_width(cb, idx);
4826 		/* Print our top labels centered over "read  write" label. */
4827 		for (i = 0; i < label_array_len(labels[idx]); i++) {
4828 			const char *name = labels[idx][i].name;
4829 			/*
4830 			 * We treat labels[][].columns == 0 as shorthand
4831 			 * for one column.  It makes writing out the label
4832 			 * tables more concise.
4833 			 */
4834 			unsigned int columns = MAX(1, labels[idx][i].columns);
4835 			unsigned int slen = strlen(name);
4836 
4837 			rw_column_width = (column_width * columns) +
4838 			    (2 * (columns - 1));
4839 
4840 			text_start = (int)((rw_column_width) / columns -
4841 			    slen / columns);
4842 			if (text_start < 0)
4843 				text_start = 0;
4844 
4845 			printf("  ");	/* Two spaces between columns */
4846 
4847 			/* Space from beginning of column to label */
4848 			for (s = 0; s < text_start; s++)
4849 				printf(" ");
4850 
4851 			printf("%s", name);
4852 
4853 			/* Print space after label to end of column */
4854 			spaces_to_end = rw_column_width - text_start - slen;
4855 			if (spaces_to_end < 0)
4856 				spaces_to_end = 0;
4857 
4858 			for (s = 0; s < spaces_to_end; s++)
4859 				printf(" ");
4860 		}
4861 	}
4862 }
4863 
4864 
4865 /*
4866  * print_cmd_columns - Print custom column titles from -c
4867  *
4868  * If the user specified the "zpool status|iostat -c" then print their custom
4869  * column titles in the header.  For example, print_cmd_columns() would print
4870  * the "  col1  col2" part of this:
4871  *
4872  * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
4873  * ...
4874  *	      capacity     operations     bandwidth
4875  * pool        alloc   free   read  write   read  write  col1  col2
4876  * ----------  -----  -----  -----  -----  -----  -----  ----  ----
4877  * mypool       269K  1008M      0      0    107    946
4878  *   mirror     269K  1008M      0      0    107    946
4879  *     sdb         -      -      0      0    102    473  val1  val2
4880  *     sdc         -      -      0      0      5    473  val1  val2
4881  * ----------  -----  -----  -----  -----  -----  -----  ----  ----
4882  */
4883 static void
4884 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
4885 {
4886 	int i, j;
4887 	vdev_cmd_data_t *data = &vcdl->data[0];
4888 
4889 	if (vcdl->count == 0 || data == NULL)
4890 		return;
4891 
4892 	/*
4893 	 * Each vdev cmd should have the same column names unless the user did
4894 	 * something weird with their cmd.  Just take the column names from the
4895 	 * first vdev and assume it works for all of them.
4896 	 */
4897 	for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
4898 		printf("  ");
4899 		if (use_dashes) {
4900 			for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
4901 				printf("-");
4902 		} else {
4903 			printf_color(ANSI_BOLD, "%*s", vcdl->uniq_cols_width[i],
4904 			    vcdl->uniq_cols[i]);
4905 		}
4906 	}
4907 }
4908 
4909 
4910 /*
4911  * Utility function to print out a line of dashes like:
4912  *
4913  * 	--------------------------------  -----  -----  -----  -----  -----
4914  *
4915  * ...or a dashed named-row line like:
4916  *
4917  * 	logs                                  -      -      -      -      -
4918  *
4919  * @cb:				iostat data
4920  *
4921  * @force_column_width		If non-zero, use the value as the column width.
4922  * 				Otherwise use the default column widths.
4923  *
4924  * @name:			Print a dashed named-row line starting
4925  * 				with @name.  Otherwise, print a regular
4926  * 				dashed line.
4927  */
4928 static void
4929 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
4930     const char *name)
4931 {
4932 	int i;
4933 	unsigned int namewidth;
4934 	uint64_t flags = cb->cb_flags;
4935 	uint64_t f;
4936 	int idx;
4937 	const name_and_columns_t *labels;
4938 	const char *title;
4939 
4940 
4941 	if (cb->cb_flags & IOS_ANYHISTO_M) {
4942 		title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4943 	} else if (cb->cb_vdevs.cb_names_count) {
4944 		title = "vdev";
4945 	} else  {
4946 		title = "pool";
4947 	}
4948 
4949 	namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4950 	    name ? strlen(name) : 0);
4951 
4952 
4953 	if (name) {
4954 		printf("%-*s", namewidth, name);
4955 	} else {
4956 		for (i = 0; i < namewidth; i++)
4957 			(void) printf("-");
4958 	}
4959 
4960 	/* For each bit in flags */
4961 	for (f = flags; f; f &= ~(1ULL << idx)) {
4962 		unsigned int column_width;
4963 		idx = lowbit64(f) - 1;
4964 		if (force_column_width)
4965 			column_width = force_column_width;
4966 		else
4967 			column_width = default_column_width(cb, idx);
4968 
4969 		labels = iostat_bottom_labels[idx];
4970 		for (i = 0; i < label_array_len(labels); i++) {
4971 			if (name)
4972 				printf("  %*s-", column_width - 1, " ");
4973 			else
4974 				printf("  %.*s", column_width,
4975 				    "--------------------");
4976 		}
4977 	}
4978 }
4979 
4980 
4981 static void
4982 print_iostat_separator_impl(iostat_cbdata_t *cb,
4983     unsigned int force_column_width)
4984 {
4985 	print_iostat_dashes(cb, force_column_width, NULL);
4986 }
4987 
4988 static void
4989 print_iostat_separator(iostat_cbdata_t *cb)
4990 {
4991 	print_iostat_separator_impl(cb, 0);
4992 }
4993 
4994 static void
4995 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
4996     const char *histo_vdev_name)
4997 {
4998 	unsigned int namewidth;
4999 	const char *title;
5000 
5001 	color_start(ANSI_BOLD);
5002 
5003 	if (cb->cb_flags & IOS_ANYHISTO_M) {
5004 		title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
5005 	} else if (cb->cb_vdevs.cb_names_count) {
5006 		title = "vdev";
5007 	} else  {
5008 		title = "pool";
5009 	}
5010 
5011 	namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
5012 	    histo_vdev_name ? strlen(histo_vdev_name) : 0);
5013 
5014 	if (histo_vdev_name)
5015 		printf("%-*s", namewidth, histo_vdev_name);
5016 	else
5017 		printf("%*s", namewidth, "");
5018 
5019 
5020 	print_iostat_labels(cb, force_column_width, iostat_top_labels);
5021 	printf("\n");
5022 
5023 	printf("%-*s", namewidth, title);
5024 
5025 	print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
5026 	if (cb->vcdl != NULL)
5027 		print_cmd_columns(cb->vcdl, 0);
5028 
5029 	printf("\n");
5030 
5031 	print_iostat_separator_impl(cb, force_column_width);
5032 
5033 	if (cb->vcdl != NULL)
5034 		print_cmd_columns(cb->vcdl, 1);
5035 
5036 	color_end();
5037 
5038 	printf("\n");
5039 }
5040 
5041 static void
5042 print_iostat_header(iostat_cbdata_t *cb)
5043 {
5044 	print_iostat_header_impl(cb, 0, NULL);
5045 }
5046 
5047 /*
5048  * Prints a size string (i.e. 120M) with the suffix ("M") colored
5049  * by order of magnitude. Uses column_size to add padding.
5050  */
5051 static void
5052 print_stat_color(const char *statbuf, unsigned int column_size)
5053 {
5054 	fputs("  ", stdout);
5055 	size_t len = strlen(statbuf);
5056 	while (len < column_size) {
5057 		fputc(' ', stdout);
5058 		column_size--;
5059 	}
5060 	if (*statbuf == '0') {
5061 		color_start(ANSI_GRAY);
5062 		fputc('0', stdout);
5063 	} else {
5064 		for (; *statbuf; statbuf++) {
5065 			if (*statbuf == 'K') color_start(ANSI_GREEN);
5066 			else if (*statbuf == 'M') color_start(ANSI_YELLOW);
5067 			else if (*statbuf == 'G') color_start(ANSI_RED);
5068 			else if (*statbuf == 'T') color_start(ANSI_BOLD_BLUE);
5069 			else if (*statbuf == 'P') color_start(ANSI_MAGENTA);
5070 			else if (*statbuf == 'E') color_start(ANSI_CYAN);
5071 			fputc(*statbuf, stdout);
5072 			if (--column_size <= 0)
5073 				break;
5074 		}
5075 	}
5076 	color_end();
5077 }
5078 
5079 /*
5080  * Display a single statistic.
5081  */
5082 static void
5083 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
5084     unsigned int column_size, boolean_t scripted)
5085 {
5086 	char buf[64];
5087 
5088 	zfs_nicenum_format(value, buf, sizeof (buf), format);
5089 
5090 	if (scripted)
5091 		printf("\t%s", buf);
5092 	else
5093 		print_stat_color(buf, column_size);
5094 }
5095 
5096 /*
5097  * Calculate the default vdev stats
5098  *
5099  * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
5100  * stats into calcvs.
5101  */
5102 static void
5103 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
5104     vdev_stat_t *calcvs)
5105 {
5106 	int i;
5107 
5108 	memcpy(calcvs, newvs, sizeof (*calcvs));
5109 	for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
5110 		calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
5111 
5112 	for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
5113 		calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
5114 }
5115 
5116 /*
5117  * Internal representation of the extended iostats data.
5118  *
5119  * The extended iostat stats are exported in nvlists as either uint64_t arrays
5120  * or single uint64_t's.  We make both look like arrays to make them easier
5121  * to process.  In order to make single uint64_t's look like arrays, we set
5122  * __data to the stat data, and then set *data = &__data with count = 1.  Then,
5123  * we can just use *data and count.
5124  */
5125 struct stat_array {
5126 	uint64_t *data;
5127 	uint_t count;	/* Number of entries in data[] */
5128 	uint64_t __data; /* Only used when data is a single uint64_t */
5129 };
5130 
5131 static uint64_t
5132 stat_histo_max(struct stat_array *nva, unsigned int len)
5133 {
5134 	uint64_t max = 0;
5135 	int i;
5136 	for (i = 0; i < len; i++)
5137 		max = MAX(max, array64_max(nva[i].data, nva[i].count));
5138 
5139 	return (max);
5140 }
5141 
5142 /*
5143  * Helper function to lookup a uint64_t array or uint64_t value and store its
5144  * data as a stat_array.  If the nvpair is a single uint64_t value, then we make
5145  * it look like a one element array to make it easier to process.
5146  */
5147 static int
5148 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
5149     struct stat_array *nva)
5150 {
5151 	nvpair_t *tmp;
5152 	int ret;
5153 
5154 	verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
5155 	switch (nvpair_type(tmp)) {
5156 	case DATA_TYPE_UINT64_ARRAY:
5157 		ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
5158 		break;
5159 	case DATA_TYPE_UINT64:
5160 		ret = nvpair_value_uint64(tmp, &nva->__data);
5161 		nva->data = &nva->__data;
5162 		nva->count = 1;
5163 		break;
5164 	default:
5165 		/* Not a uint64_t */
5166 		ret = EINVAL;
5167 		break;
5168 	}
5169 
5170 	return (ret);
5171 }
5172 
5173 /*
5174  * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
5175  * subtract them, and return the results in a newly allocated stat_array.
5176  * You must free the returned array after you are done with it with
5177  * free_calc_stats().
5178  *
5179  * Additionally, you can set "oldnv" to NULL if you simply want the newnv
5180  * values.
5181  */
5182 static struct stat_array *
5183 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
5184     nvlist_t *newnv)
5185 {
5186 	nvlist_t *oldnvx = NULL, *newnvx;
5187 	struct stat_array *oldnva, *newnva, *calcnva;
5188 	int i, j;
5189 	unsigned int alloc_size = (sizeof (struct stat_array)) * len;
5190 
5191 	/* Extract our extended stats nvlist from the main list */
5192 	verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5193 	    &newnvx) == 0);
5194 	if (oldnv) {
5195 		verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5196 		    &oldnvx) == 0);
5197 	}
5198 
5199 	newnva = safe_malloc(alloc_size);
5200 	oldnva = safe_malloc(alloc_size);
5201 	calcnva = safe_malloc(alloc_size);
5202 
5203 	for (j = 0; j < len; j++) {
5204 		verify(nvpair64_to_stat_array(newnvx, names[j],
5205 		    &newnva[j]) == 0);
5206 		calcnva[j].count = newnva[j].count;
5207 		alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
5208 		calcnva[j].data = safe_malloc(alloc_size);
5209 		memcpy(calcnva[j].data, newnva[j].data, alloc_size);
5210 
5211 		if (oldnvx) {
5212 			verify(nvpair64_to_stat_array(oldnvx, names[j],
5213 			    &oldnva[j]) == 0);
5214 			for (i = 0; i < oldnva[j].count; i++)
5215 				calcnva[j].data[i] -= oldnva[j].data[i];
5216 		}
5217 	}
5218 	free(newnva);
5219 	free(oldnva);
5220 	return (calcnva);
5221 }
5222 
5223 static void
5224 free_calc_stats(struct stat_array *nva, unsigned int len)
5225 {
5226 	int i;
5227 	for (i = 0; i < len; i++)
5228 		free(nva[i].data);
5229 
5230 	free(nva);
5231 }
5232 
5233 static void
5234 print_iostat_histo(struct stat_array *nva, unsigned int len,
5235     iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
5236     double scale)
5237 {
5238 	int i, j;
5239 	char buf[6];
5240 	uint64_t val;
5241 	enum zfs_nicenum_format format;
5242 	unsigned int buckets;
5243 	unsigned int start_bucket;
5244 
5245 	if (cb->cb_literal)
5246 		format = ZFS_NICENUM_RAW;
5247 	else
5248 		format = ZFS_NICENUM_1024;
5249 
5250 	/* All these histos are the same size, so just use nva[0].count */
5251 	buckets = nva[0].count;
5252 
5253 	if (cb->cb_flags & IOS_RQ_HISTO_M) {
5254 		/* Start at 512 - req size should never be lower than this */
5255 		start_bucket = 9;
5256 	} else {
5257 		start_bucket = 0;
5258 	}
5259 
5260 	for (j = start_bucket; j < buckets; j++) {
5261 		/* Print histogram bucket label */
5262 		if (cb->cb_flags & IOS_L_HISTO_M) {
5263 			/* Ending range of this bucket */
5264 			val = (1UL << (j + 1)) - 1;
5265 			zfs_nicetime(val, buf, sizeof (buf));
5266 		} else {
5267 			/* Request size (starting range of bucket) */
5268 			val = (1UL << j);
5269 			zfs_nicenum(val, buf, sizeof (buf));
5270 		}
5271 
5272 		if (cb->cb_scripted)
5273 			printf("%llu", (u_longlong_t)val);
5274 		else
5275 			printf("%-*s", namewidth, buf);
5276 
5277 		/* Print the values on the line */
5278 		for (i = 0; i < len; i++) {
5279 			print_one_stat(nva[i].data[j] * scale, format,
5280 			    column_width, cb->cb_scripted);
5281 		}
5282 		printf("\n");
5283 	}
5284 }
5285 
5286 static void
5287 print_solid_separator(unsigned int length)
5288 {
5289 	while (length--)
5290 		printf("-");
5291 	printf("\n");
5292 }
5293 
5294 static void
5295 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
5296     nvlist_t *newnv, double scale, const char *name)
5297 {
5298 	unsigned int column_width;
5299 	unsigned int namewidth;
5300 	unsigned int entire_width;
5301 	enum iostat_type type;
5302 	struct stat_array *nva;
5303 	const char **names;
5304 	unsigned int names_len;
5305 
5306 	/* What type of histo are we? */
5307 	type = IOS_HISTO_IDX(cb->cb_flags);
5308 
5309 	/* Get NULL-terminated array of nvlist names for our histo */
5310 	names = vsx_type_to_nvlist[type];
5311 	names_len = str_array_len(names); /* num of names */
5312 
5313 	nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
5314 
5315 	if (cb->cb_literal) {
5316 		column_width = MAX(5,
5317 		    (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
5318 	} else {
5319 		column_width = 5;
5320 	}
5321 
5322 	namewidth = MAX(cb->cb_namewidth,
5323 	    strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
5324 
5325 	/*
5326 	 * Calculate the entire line width of what we're printing.  The
5327 	 * +2 is for the two spaces between columns:
5328 	 */
5329 	/*	 read  write				*/
5330 	/*	-----  -----				*/
5331 	/*	|___|  <---------- column_width		*/
5332 	/*						*/
5333 	/*	|__________|  <--- entire_width		*/
5334 	/*						*/
5335 	entire_width = namewidth + (column_width + 2) *
5336 	    label_array_len(iostat_bottom_labels[type]);
5337 
5338 	if (cb->cb_scripted)
5339 		printf("%s\n", name);
5340 	else
5341 		print_iostat_header_impl(cb, column_width, name);
5342 
5343 	print_iostat_histo(nva, names_len, cb, column_width,
5344 	    namewidth, scale);
5345 
5346 	free_calc_stats(nva, names_len);
5347 	if (!cb->cb_scripted)
5348 		print_solid_separator(entire_width);
5349 }
5350 
5351 /*
5352  * Calculate the average latency of a power-of-two latency histogram
5353  */
5354 static uint64_t
5355 single_histo_average(uint64_t *histo, unsigned int buckets)
5356 {
5357 	int i;
5358 	uint64_t count = 0, total = 0;
5359 
5360 	for (i = 0; i < buckets; i++) {
5361 		/*
5362 		 * Our buckets are power-of-two latency ranges.  Use the
5363 		 * midpoint latency of each bucket to calculate the average.
5364 		 * For example:
5365 		 *
5366 		 * Bucket          Midpoint
5367 		 * 8ns-15ns:       12ns
5368 		 * 16ns-31ns:      24ns
5369 		 * ...
5370 		 */
5371 		if (histo[i] != 0) {
5372 			total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
5373 			count += histo[i];
5374 		}
5375 	}
5376 
5377 	/* Prevent divide by zero */
5378 	return (count == 0 ? 0 : total / count);
5379 }
5380 
5381 static void
5382 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *newnv)
5383 {
5384 	const char *names[] = {
5385 		ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
5386 		ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
5387 		ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
5388 		ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
5389 		ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
5390 		ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
5391 		ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
5392 		ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
5393 		ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
5394 		ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
5395 		ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
5396 		ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
5397 		ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
5398 		ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
5399 	};
5400 
5401 	struct stat_array *nva;
5402 
5403 	unsigned int column_width = default_column_width(cb, IOS_QUEUES);
5404 	enum zfs_nicenum_format format;
5405 
5406 	nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
5407 
5408 	if (cb->cb_literal)
5409 		format = ZFS_NICENUM_RAW;
5410 	else
5411 		format = ZFS_NICENUM_1024;
5412 
5413 	for (int i = 0; i < ARRAY_SIZE(names); i++) {
5414 		uint64_t val = nva[i].data[0];
5415 		print_one_stat(val, format, column_width, cb->cb_scripted);
5416 	}
5417 
5418 	free_calc_stats(nva, ARRAY_SIZE(names));
5419 }
5420 
5421 static void
5422 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
5423     nvlist_t *newnv)
5424 {
5425 	int i;
5426 	uint64_t val;
5427 	const char *names[] = {
5428 		ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
5429 		ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
5430 		ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
5431 		ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
5432 		ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
5433 		ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
5434 		ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
5435 		ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
5436 		ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
5437 		ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
5438 		ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
5439 	};
5440 	struct stat_array *nva;
5441 
5442 	unsigned int column_width = default_column_width(cb, IOS_LATENCY);
5443 	enum zfs_nicenum_format format;
5444 
5445 	nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
5446 
5447 	if (cb->cb_literal)
5448 		format = ZFS_NICENUM_RAWTIME;
5449 	else
5450 		format = ZFS_NICENUM_TIME;
5451 
5452 	/* Print our avg latencies on the line */
5453 	for (i = 0; i < ARRAY_SIZE(names); i++) {
5454 		/* Compute average latency for a latency histo */
5455 		val = single_histo_average(nva[i].data, nva[i].count);
5456 		print_one_stat(val, format, column_width, cb->cb_scripted);
5457 	}
5458 	free_calc_stats(nva, ARRAY_SIZE(names));
5459 }
5460 
5461 /*
5462  * Print default statistics (capacity/operations/bandwidth)
5463  */
5464 static void
5465 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
5466 {
5467 	unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
5468 	enum zfs_nicenum_format format;
5469 	char na;	/* char to print for "not applicable" values */
5470 
5471 	if (cb->cb_literal) {
5472 		format = ZFS_NICENUM_RAW;
5473 		na = '0';
5474 	} else {
5475 		format = ZFS_NICENUM_1024;
5476 		na = '-';
5477 	}
5478 
5479 	/* only toplevel vdevs have capacity stats */
5480 	if (vs->vs_space == 0) {
5481 		if (cb->cb_scripted)
5482 			printf("\t%c\t%c", na, na);
5483 		else
5484 			printf("  %*c  %*c", column_width, na, column_width,
5485 			    na);
5486 	} else {
5487 		print_one_stat(vs->vs_alloc, format, column_width,
5488 		    cb->cb_scripted);
5489 		print_one_stat(vs->vs_space - vs->vs_alloc, format,
5490 		    column_width, cb->cb_scripted);
5491 	}
5492 
5493 	print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
5494 	    format, column_width, cb->cb_scripted);
5495 	print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
5496 	    format, column_width, cb->cb_scripted);
5497 	print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
5498 	    format, column_width, cb->cb_scripted);
5499 	print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
5500 	    format, column_width, cb->cb_scripted);
5501 }
5502 
5503 static const char *const class_name[] = {
5504 	VDEV_ALLOC_BIAS_DEDUP,
5505 	VDEV_ALLOC_BIAS_SPECIAL,
5506 	VDEV_ALLOC_CLASS_LOGS
5507 };
5508 
5509 /*
5510  * Print out all the statistics for the given vdev.  This can either be the
5511  * toplevel configuration, or called recursively.  If 'name' is NULL, then this
5512  * is a verbose output, and we don't want to display the toplevel pool stats.
5513  *
5514  * Returns the number of stat lines printed.
5515  */
5516 static unsigned int
5517 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
5518     nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
5519 {
5520 	nvlist_t **oldchild, **newchild;
5521 	uint_t c, children, oldchildren;
5522 	vdev_stat_t *oldvs, *newvs, *calcvs;
5523 	vdev_stat_t zerovs = { 0 };
5524 	char *vname;
5525 	int i;
5526 	int ret = 0;
5527 	uint64_t tdelta;
5528 	double scale;
5529 
5530 	if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
5531 		return (ret);
5532 
5533 	calcvs = safe_malloc(sizeof (*calcvs));
5534 
5535 	if (oldnv != NULL) {
5536 		verify(nvlist_lookup_uint64_array(oldnv,
5537 		    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
5538 	} else {
5539 		oldvs = &zerovs;
5540 	}
5541 
5542 	/* Do we only want to see a specific vdev? */
5543 	for (i = 0; i < cb->cb_vdevs.cb_names_count; i++) {
5544 		/* Yes we do.  Is this the vdev? */
5545 		if (strcmp(name, cb->cb_vdevs.cb_names[i]) == 0) {
5546 			/*
5547 			 * This is our vdev.  Since it is the only vdev we
5548 			 * will be displaying, make depth = 0 so that it
5549 			 * doesn't get indented.
5550 			 */
5551 			depth = 0;
5552 			break;
5553 		}
5554 	}
5555 
5556 	if (cb->cb_vdevs.cb_names_count && (i == cb->cb_vdevs.cb_names_count)) {
5557 		/* Couldn't match the name */
5558 		goto children;
5559 	}
5560 
5561 
5562 	verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
5563 	    (uint64_t **)&newvs, &c) == 0);
5564 
5565 	/*
5566 	 * Print the vdev name unless it's is a histogram.  Histograms
5567 	 * display the vdev name in the header itself.
5568 	 */
5569 	if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
5570 		if (cb->cb_scripted) {
5571 			printf("%s", name);
5572 		} else {
5573 			if (strlen(name) + depth > cb->cb_namewidth)
5574 				(void) printf("%*s%s", depth, "", name);
5575 			else
5576 				(void) printf("%*s%s%*s", depth, "", name,
5577 				    (int)(cb->cb_namewidth - strlen(name) -
5578 				    depth), "");
5579 		}
5580 	}
5581 
5582 	/* Calculate our scaling factor */
5583 	tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
5584 	if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
5585 		/*
5586 		 * If we specify printing histograms with no time interval, then
5587 		 * print the histogram numbers over the entire lifetime of the
5588 		 * vdev.
5589 		 */
5590 		scale = 1;
5591 	} else {
5592 		if (tdelta == 0)
5593 			scale = 1.0;
5594 		else
5595 			scale = (double)NANOSEC / tdelta;
5596 	}
5597 
5598 	if (cb->cb_flags & IOS_DEFAULT_M) {
5599 		calc_default_iostats(oldvs, newvs, calcvs);
5600 		print_iostat_default(calcvs, cb, scale);
5601 	}
5602 	if (cb->cb_flags & IOS_LATENCY_M)
5603 		print_iostat_latency(cb, oldnv, newnv);
5604 	if (cb->cb_flags & IOS_QUEUES_M)
5605 		print_iostat_queues(cb, newnv);
5606 	if (cb->cb_flags & IOS_ANYHISTO_M) {
5607 		printf("\n");
5608 		print_iostat_histos(cb, oldnv, newnv, scale, name);
5609 	}
5610 
5611 	if (cb->vcdl != NULL) {
5612 		const char *path;
5613 		if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
5614 		    &path) == 0) {
5615 			printf("  ");
5616 			zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
5617 		}
5618 	}
5619 
5620 	if (!(cb->cb_flags & IOS_ANYHISTO_M))
5621 		printf("\n");
5622 
5623 	ret++;
5624 
5625 children:
5626 
5627 	free(calcvs);
5628 
5629 	if (!cb->cb_verbose)
5630 		return (ret);
5631 
5632 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
5633 	    &newchild, &children) != 0)
5634 		return (ret);
5635 
5636 	if (oldnv) {
5637 		if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
5638 		    &oldchild, &oldchildren) != 0)
5639 			return (ret);
5640 
5641 		children = MIN(oldchildren, children);
5642 	}
5643 
5644 	/*
5645 	 * print normal top-level devices
5646 	 */
5647 	for (c = 0; c < children; c++) {
5648 		uint64_t ishole = B_FALSE, islog = B_FALSE;
5649 
5650 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
5651 		    &ishole);
5652 
5653 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
5654 		    &islog);
5655 
5656 		if (ishole || islog)
5657 			continue;
5658 
5659 		if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
5660 			continue;
5661 
5662 		vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5663 		    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5664 		ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
5665 		    newchild[c], cb, depth + 2);
5666 		free(vname);
5667 	}
5668 
5669 	/*
5670 	 * print all other top-level devices
5671 	 */
5672 	for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
5673 		boolean_t printed = B_FALSE;
5674 
5675 		for (c = 0; c < children; c++) {
5676 			uint64_t islog = B_FALSE;
5677 			const char *bias = NULL;
5678 			const char *type = NULL;
5679 
5680 			(void) nvlist_lookup_uint64(newchild[c],
5681 			    ZPOOL_CONFIG_IS_LOG, &islog);
5682 			if (islog) {
5683 				bias = VDEV_ALLOC_CLASS_LOGS;
5684 			} else {
5685 				(void) nvlist_lookup_string(newchild[c],
5686 				    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
5687 				(void) nvlist_lookup_string(newchild[c],
5688 				    ZPOOL_CONFIG_TYPE, &type);
5689 			}
5690 			if (bias == NULL || strcmp(bias, class_name[n]) != 0)
5691 				continue;
5692 			if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
5693 				continue;
5694 
5695 			if (!printed) {
5696 				if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
5697 				    !cb->cb_scripted &&
5698 				    !cb->cb_vdevs.cb_names) {
5699 					print_iostat_dashes(cb, 0,
5700 					    class_name[n]);
5701 				}
5702 				printf("\n");
5703 				printed = B_TRUE;
5704 			}
5705 
5706 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5707 			    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5708 			ret += print_vdev_stats(zhp, vname, oldnv ?
5709 			    oldchild[c] : NULL, newchild[c], cb, depth + 2);
5710 			free(vname);
5711 		}
5712 	}
5713 
5714 	/*
5715 	 * Include level 2 ARC devices in iostat output
5716 	 */
5717 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
5718 	    &newchild, &children) != 0)
5719 		return (ret);
5720 
5721 	if (oldnv) {
5722 		if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
5723 		    &oldchild, &oldchildren) != 0)
5724 			return (ret);
5725 
5726 		children = MIN(oldchildren, children);
5727 	}
5728 
5729 	if (children > 0) {
5730 		if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
5731 		    !cb->cb_vdevs.cb_names) {
5732 			print_iostat_dashes(cb, 0, "cache");
5733 		}
5734 		printf("\n");
5735 
5736 		for (c = 0; c < children; c++) {
5737 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5738 			    cb->cb_vdevs.cb_name_flags);
5739 			ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
5740 			    : NULL, newchild[c], cb, depth + 2);
5741 			free(vname);
5742 		}
5743 	}
5744 
5745 	return (ret);
5746 }
5747 
5748 static int
5749 refresh_iostat(zpool_handle_t *zhp, void *data)
5750 {
5751 	iostat_cbdata_t *cb = data;
5752 	boolean_t missing;
5753 
5754 	/*
5755 	 * If the pool has disappeared, remove it from the list and continue.
5756 	 */
5757 	if (zpool_refresh_stats(zhp, &missing) != 0)
5758 		return (-1);
5759 
5760 	if (missing)
5761 		pool_list_remove(cb->cb_list, zhp);
5762 
5763 	return (0);
5764 }
5765 
5766 /*
5767  * Callback to print out the iostats for the given pool.
5768  */
5769 static int
5770 print_iostat(zpool_handle_t *zhp, void *data)
5771 {
5772 	iostat_cbdata_t *cb = data;
5773 	nvlist_t *oldconfig, *newconfig;
5774 	nvlist_t *oldnvroot, *newnvroot;
5775 	int ret;
5776 
5777 	newconfig = zpool_get_config(zhp, &oldconfig);
5778 
5779 	if (cb->cb_iteration == 1)
5780 		oldconfig = NULL;
5781 
5782 	verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
5783 	    &newnvroot) == 0);
5784 
5785 	if (oldconfig == NULL)
5786 		oldnvroot = NULL;
5787 	else
5788 		verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
5789 		    &oldnvroot) == 0);
5790 
5791 	ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
5792 	    cb, 0);
5793 	if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
5794 	    !cb->cb_scripted && cb->cb_verbose &&
5795 	    !cb->cb_vdevs.cb_names_count) {
5796 		print_iostat_separator(cb);
5797 		if (cb->vcdl != NULL) {
5798 			print_cmd_columns(cb->vcdl, 1);
5799 		}
5800 		printf("\n");
5801 	}
5802 
5803 	return (ret);
5804 }
5805 
5806 static int
5807 get_columns(void)
5808 {
5809 	struct winsize ws;
5810 	int columns = 80;
5811 	int error;
5812 
5813 	if (isatty(STDOUT_FILENO)) {
5814 		error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
5815 		if (error == 0)
5816 			columns = ws.ws_col;
5817 	} else {
5818 		columns = 999;
5819 	}
5820 
5821 	return (columns);
5822 }
5823 
5824 /*
5825  * Return the required length of the pool/vdev name column.  The minimum
5826  * allowed width and output formatting flags must be provided.
5827  */
5828 static int
5829 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
5830 {
5831 	nvlist_t *config, *nvroot;
5832 	int width = min_width;
5833 
5834 	if ((config = zpool_get_config(zhp, NULL)) != NULL) {
5835 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5836 		    &nvroot) == 0);
5837 		size_t poolname_len = strlen(zpool_get_name(zhp));
5838 		if (verbose == B_FALSE) {
5839 			width = MAX(poolname_len, min_width);
5840 		} else {
5841 			width = MAX(poolname_len,
5842 			    max_width(zhp, nvroot, 0, min_width, flags));
5843 		}
5844 	}
5845 
5846 	return (width);
5847 }
5848 
5849 /*
5850  * Parse the input string, get the 'interval' and 'count' value if there is one.
5851  */
5852 static void
5853 get_interval_count(int *argcp, char **argv, float *iv,
5854     unsigned long *cnt)
5855 {
5856 	float interval = 0;
5857 	unsigned long count = 0;
5858 	int argc = *argcp;
5859 
5860 	/*
5861 	 * Determine if the last argument is an integer or a pool name
5862 	 */
5863 	if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5864 		char *end;
5865 
5866 		errno = 0;
5867 		interval = strtof(argv[argc - 1], &end);
5868 
5869 		if (*end == '\0' && errno == 0) {
5870 			if (interval == 0) {
5871 				(void) fprintf(stderr, gettext(
5872 				    "interval cannot be zero\n"));
5873 				usage(B_FALSE);
5874 			}
5875 			/*
5876 			 * Ignore the last parameter
5877 			 */
5878 			argc--;
5879 		} else {
5880 			/*
5881 			 * If this is not a valid number, just plow on.  The
5882 			 * user will get a more informative error message later
5883 			 * on.
5884 			 */
5885 			interval = 0;
5886 		}
5887 	}
5888 
5889 	/*
5890 	 * If the last argument is also an integer, then we have both a count
5891 	 * and an interval.
5892 	 */
5893 	if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5894 		char *end;
5895 
5896 		errno = 0;
5897 		count = interval;
5898 		interval = strtof(argv[argc - 1], &end);
5899 
5900 		if (*end == '\0' && errno == 0) {
5901 			if (interval == 0) {
5902 				(void) fprintf(stderr, gettext(
5903 				    "interval cannot be zero\n"));
5904 				usage(B_FALSE);
5905 			}
5906 
5907 			/*
5908 			 * Ignore the last parameter
5909 			 */
5910 			argc--;
5911 		} else {
5912 			interval = 0;
5913 		}
5914 	}
5915 
5916 	*iv = interval;
5917 	*cnt = count;
5918 	*argcp = argc;
5919 }
5920 
5921 static void
5922 get_timestamp_arg(char c)
5923 {
5924 	if (c == 'u')
5925 		timestamp_fmt = UDATE;
5926 	else if (c == 'd')
5927 		timestamp_fmt = DDATE;
5928 	else
5929 		usage(B_FALSE);
5930 }
5931 
5932 /*
5933  * Return stat flags that are supported by all pools by both the module and
5934  * zpool iostat.  "*data" should be initialized to all 0xFFs before running.
5935  * It will get ANDed down until only the flags that are supported on all pools
5936  * remain.
5937  */
5938 static int
5939 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
5940 {
5941 	uint64_t *mask = data;
5942 	nvlist_t *config, *nvroot, *nvx;
5943 	uint64_t flags = 0;
5944 	int i, j;
5945 
5946 	config = zpool_get_config(zhp, NULL);
5947 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5948 	    &nvroot) == 0);
5949 
5950 	/* Default stats are always supported, but for completeness.. */
5951 	if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
5952 		flags |= IOS_DEFAULT_M;
5953 
5954 	/* Get our extended stats nvlist from the main list */
5955 	if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
5956 	    &nvx) != 0) {
5957 		/*
5958 		 * No extended stats; they're probably running an older
5959 		 * module.  No big deal, we support that too.
5960 		 */
5961 		goto end;
5962 	}
5963 
5964 	/* For each extended stat, make sure all its nvpairs are supported */
5965 	for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
5966 		if (!vsx_type_to_nvlist[j][0])
5967 			continue;
5968 
5969 		/* Start off by assuming the flag is supported, then check */
5970 		flags |= (1ULL << j);
5971 		for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
5972 			if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
5973 				/* flag isn't supported */
5974 				flags = flags & ~(1ULL  << j);
5975 				break;
5976 			}
5977 		}
5978 	}
5979 end:
5980 	*mask = *mask & flags;
5981 	return (0);
5982 }
5983 
5984 /*
5985  * Return a bitmask of stats that are supported on all pools by both the module
5986  * and zpool iostat.
5987  */
5988 static uint64_t
5989 get_stat_flags(zpool_list_t *list)
5990 {
5991 	uint64_t mask = -1;
5992 
5993 	/*
5994 	 * get_stat_flags_cb() will lop off bits from "mask" until only the
5995 	 * flags that are supported on all pools remain.
5996 	 */
5997 	pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
5998 	return (mask);
5999 }
6000 
6001 /*
6002  * Return 1 if cb_data->cb_names[0] is this vdev's name, 0 otherwise.
6003  */
6004 static int
6005 is_vdev_cb(void *zhp_data, nvlist_t *nv, void *cb_data)
6006 {
6007 	uint64_t guid;
6008 	vdev_cbdata_t *cb = cb_data;
6009 	zpool_handle_t *zhp = zhp_data;
6010 
6011 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
6012 		return (0);
6013 
6014 	return (guid == zpool_vdev_path_to_guid(zhp, cb->cb_names[0]));
6015 }
6016 
6017 /*
6018  * Returns 1 if cb_data->cb_names[0] is a vdev name, 0 otherwise.
6019  */
6020 static int
6021 is_vdev(zpool_handle_t *zhp, void *cb_data)
6022 {
6023 	return (for_each_vdev(zhp, is_vdev_cb, cb_data));
6024 }
6025 
6026 /*
6027  * Check if vdevs are in a pool
6028  *
6029  * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
6030  * return 0.  If pool_name is NULL, then search all pools.
6031  */
6032 static int
6033 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
6034     vdev_cbdata_t *cb)
6035 {
6036 	char **tmp_name;
6037 	int ret = 0;
6038 	int i;
6039 	int pool_count = 0;
6040 
6041 	if ((argc == 0) || !*argv)
6042 		return (0);
6043 
6044 	if (pool_name)
6045 		pool_count = 1;
6046 
6047 	/* Temporarily hijack cb_names for a second... */
6048 	tmp_name = cb->cb_names;
6049 
6050 	/* Go though our list of prospective vdev names */
6051 	for (i = 0; i < argc; i++) {
6052 		cb->cb_names = argv + i;
6053 
6054 		/* Is this name a vdev in our pools? */
6055 		ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
6056 		    ZFS_TYPE_POOL, B_FALSE, is_vdev, cb);
6057 		if (!ret) {
6058 			/* No match */
6059 			break;
6060 		}
6061 	}
6062 
6063 	cb->cb_names = tmp_name;
6064 
6065 	return (ret);
6066 }
6067 
6068 static int
6069 is_pool_cb(zpool_handle_t *zhp, void *data)
6070 {
6071 	char *name = data;
6072 	if (strcmp(name, zpool_get_name(zhp)) == 0)
6073 		return (1);
6074 
6075 	return (0);
6076 }
6077 
6078 /*
6079  * Do we have a pool named *name?  If so, return 1, otherwise 0.
6080  */
6081 static int
6082 is_pool(char *name)
6083 {
6084 	return (for_each_pool(0, NULL, B_TRUE, NULL, ZFS_TYPE_POOL, B_FALSE,
6085 	    is_pool_cb, name));
6086 }
6087 
6088 /* Are all our argv[] strings pool names?  If so return 1, 0 otherwise. */
6089 static int
6090 are_all_pools(int argc, char **argv)
6091 {
6092 	if ((argc == 0) || !*argv)
6093 		return (0);
6094 
6095 	while (--argc >= 0)
6096 		if (!is_pool(argv[argc]))
6097 			return (0);
6098 
6099 	return (1);
6100 }
6101 
6102 /*
6103  * Helper function to print out vdev/pool names we can't resolve.  Used for an
6104  * error message.
6105  */
6106 static void
6107 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
6108     vdev_cbdata_t *cb)
6109 {
6110 	int i;
6111 	char *name;
6112 	char *str;
6113 	for (i = 0; i < argc; i++) {
6114 		name = argv[i];
6115 
6116 		if (is_pool(name))
6117 			str = gettext("pool");
6118 		else if (are_vdevs_in_pool(1, &name, pool_name, cb))
6119 			str = gettext("vdev in this pool");
6120 		else if (are_vdevs_in_pool(1, &name, NULL, cb))
6121 			str = gettext("vdev in another pool");
6122 		else
6123 			str = gettext("unknown");
6124 
6125 		fprintf(stderr, "\t%s (%s)\n", name, str);
6126 	}
6127 }
6128 
6129 /*
6130  * Same as get_interval_count(), but with additional checks to not misinterpret
6131  * guids as interval/count values.  Assumes VDEV_NAME_GUID is set in
6132  * cb.cb_vdevs.cb_name_flags.
6133  */
6134 static void
6135 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
6136     unsigned long *count, iostat_cbdata_t *cb)
6137 {
6138 	char **tmpargv = argv;
6139 	int argc_for_interval = 0;
6140 
6141 	/* Is the last arg an interval value?  Or a guid? */
6142 	if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL,
6143 	    &cb->cb_vdevs)) {
6144 		/*
6145 		 * The last arg is not a guid, so it's probably an
6146 		 * interval value.
6147 		 */
6148 		argc_for_interval++;
6149 
6150 		if (*argc >= 2 &&
6151 		    !are_vdevs_in_pool(1, &argv[*argc - 2], NULL,
6152 		    &cb->cb_vdevs)) {
6153 			/*
6154 			 * The 2nd to last arg is not a guid, so it's probably
6155 			 * an interval value.
6156 			 */
6157 			argc_for_interval++;
6158 		}
6159 	}
6160 
6161 	/* Point to our list of possible intervals */
6162 	tmpargv = &argv[*argc - argc_for_interval];
6163 
6164 	*argc = *argc - argc_for_interval;
6165 	get_interval_count(&argc_for_interval, tmpargv,
6166 	    interval, count);
6167 }
6168 
6169 /*
6170  * Terminal height, in rows. Returns -1 if stdout is not connected to a TTY or
6171  * if we were unable to determine its size.
6172  */
6173 static int
6174 terminal_height(void)
6175 {
6176 	struct winsize win;
6177 
6178 	if (isatty(STDOUT_FILENO) == 0)
6179 		return (-1);
6180 
6181 	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_row > 0)
6182 		return (win.ws_row);
6183 
6184 	return (-1);
6185 }
6186 
6187 /*
6188  * Run one of the zpool status/iostat -c scripts with the help (-h) option and
6189  * print the result.
6190  *
6191  * name:	Short name of the script ('iostat').
6192  * path:	Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
6193  */
6194 static void
6195 print_zpool_script_help(char *name, char *path)
6196 {
6197 	char *argv[] = {path, (char *)"-h", NULL};
6198 	char **lines = NULL;
6199 	int lines_cnt = 0;
6200 	int rc;
6201 
6202 	rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
6203 	    &lines_cnt);
6204 	if (rc != 0 || lines == NULL || lines_cnt <= 0) {
6205 		if (lines != NULL)
6206 			libzfs_free_str_array(lines, lines_cnt);
6207 		return;
6208 	}
6209 
6210 	for (int i = 0; i < lines_cnt; i++)
6211 		if (!is_blank_str(lines[i]))
6212 			printf("  %-14s  %s\n", name, lines[i]);
6213 
6214 	libzfs_free_str_array(lines, lines_cnt);
6215 }
6216 
6217 /*
6218  * Go though the zpool status/iostat -c scripts in the user's path, run their
6219  * help option (-h), and print out the results.
6220  */
6221 static void
6222 print_zpool_dir_scripts(char *dirpath)
6223 {
6224 	DIR *dir;
6225 	struct dirent *ent;
6226 	char fullpath[MAXPATHLEN];
6227 	struct stat dir_stat;
6228 
6229 	if ((dir = opendir(dirpath)) != NULL) {
6230 		/* print all the files and directories within directory */
6231 		while ((ent = readdir(dir)) != NULL) {
6232 			if (snprintf(fullpath, sizeof (fullpath), "%s/%s",
6233 			    dirpath, ent->d_name) >= sizeof (fullpath)) {
6234 				(void) fprintf(stderr,
6235 				    gettext("internal error: "
6236 				    "ZPOOL_SCRIPTS_PATH too large.\n"));
6237 				exit(1);
6238 			}
6239 
6240 			/* Print the scripts */
6241 			if (stat(fullpath, &dir_stat) == 0)
6242 				if (dir_stat.st_mode & S_IXUSR &&
6243 				    S_ISREG(dir_stat.st_mode))
6244 					print_zpool_script_help(ent->d_name,
6245 					    fullpath);
6246 		}
6247 		closedir(dir);
6248 	}
6249 }
6250 
6251 /*
6252  * Print out help text for all zpool status/iostat -c scripts.
6253  */
6254 static void
6255 print_zpool_script_list(const char *subcommand)
6256 {
6257 	char *dir, *sp, *tmp;
6258 
6259 	printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
6260 
6261 	sp = zpool_get_cmd_search_path();
6262 	if (sp == NULL)
6263 		return;
6264 
6265 	for (dir = strtok_r(sp, ":", &tmp);
6266 	    dir != NULL;
6267 	    dir = strtok_r(NULL, ":", &tmp))
6268 		print_zpool_dir_scripts(dir);
6269 
6270 	free(sp);
6271 }
6272 
6273 /*
6274  * Set the minimum pool/vdev name column width.  The width must be at least 10,
6275  * but may be as large as the column width - 42 so it still fits on one line.
6276  * NOTE: 42 is the width of the default capacity/operations/bandwidth output
6277  */
6278 static int
6279 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
6280 {
6281 	iostat_cbdata_t *cb = data;
6282 	int width, available_width;
6283 
6284 	/*
6285 	 * get_namewidth() returns the maximum width of any name in that column
6286 	 * for any pool/vdev/device line that will be output.
6287 	 */
6288 	width = get_namewidth(zhp, cb->cb_namewidth,
6289 	    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
6290 
6291 	/*
6292 	 * The width we are calculating is the width of the header and also the
6293 	 * padding width for names that are less than maximum width.  The stats
6294 	 * take up 42 characters, so the width available for names is:
6295 	 */
6296 	available_width = get_columns() - 42;
6297 
6298 	/*
6299 	 * If the maximum width fits on a screen, then great!  Make everything
6300 	 * line up by justifying all lines to the same width.  If that max
6301 	 * width is larger than what's available, the name plus stats won't fit
6302 	 * on one line, and justifying to that width would cause every line to
6303 	 * wrap on the screen.  We only want lines with long names to wrap.
6304 	 * Limit the padding to what won't wrap.
6305 	 */
6306 	if (width > available_width)
6307 		width = available_width;
6308 
6309 	/*
6310 	 * And regardless of whatever the screen width is (get_columns can
6311 	 * return 0 if the width is not known or less than 42 for a narrow
6312 	 * terminal) have the width be a minimum of 10.
6313 	 */
6314 	if (width < 10)
6315 		width = 10;
6316 
6317 	/* Save the calculated width */
6318 	cb->cb_namewidth = width;
6319 
6320 	return (0);
6321 }
6322 
6323 /*
6324  * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
6325  *              [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
6326  *              [interval [count]]
6327  *
6328  *	-c CMD  For each vdev, run command CMD
6329  *	-g	Display guid for individual vdev name.
6330  *	-L	Follow links when resolving vdev path name.
6331  *	-P	Display full path for vdev name.
6332  *	-v	Display statistics for individual vdevs
6333  *	-h	Display help
6334  *	-p	Display values in parsable (exact) format.
6335  *	-H	Scripted mode.  Don't display headers, and separate properties
6336  *		by a single tab.
6337  *	-l	Display average latency
6338  *	-q	Display queue depths
6339  *	-w	Display latency histograms
6340  *	-r	Display request size histogram
6341  *	-T	Display a timestamp in date(1) or Unix format
6342  *	-n	Only print headers once
6343  *
6344  * This command can be tricky because we want to be able to deal with pool
6345  * creation/destruction as well as vdev configuration changes.  The bulk of this
6346  * processing is handled by the pool_list_* routines in zpool_iter.c.  We rely
6347  * on pool_list_update() to detect the addition of new pools.  Configuration
6348  * changes are all handled within libzfs.
6349  */
6350 int
6351 zpool_do_iostat(int argc, char **argv)
6352 {
6353 	int c;
6354 	int ret;
6355 	int npools;
6356 	float interval = 0;
6357 	unsigned long count = 0;
6358 	int winheight = 24;
6359 	zpool_list_t *list;
6360 	boolean_t verbose = B_FALSE;
6361 	boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
6362 	boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
6363 	boolean_t omit_since_boot = B_FALSE;
6364 	boolean_t guid = B_FALSE;
6365 	boolean_t follow_links = B_FALSE;
6366 	boolean_t full_name = B_FALSE;
6367 	boolean_t headers_once = B_FALSE;
6368 	iostat_cbdata_t cb = { 0 };
6369 	char *cmd = NULL;
6370 
6371 	/* Used for printing error message */
6372 	const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
6373 	    [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
6374 
6375 	uint64_t unsupported_flags;
6376 
6377 	/* check options */
6378 	while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwnH")) != -1) {
6379 		switch (c) {
6380 		case 'c':
6381 			if (cmd != NULL) {
6382 				fprintf(stderr,
6383 				    gettext("Can't set -c flag twice\n"));
6384 				exit(1);
6385 			}
6386 
6387 			if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
6388 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
6389 				fprintf(stderr, gettext(
6390 				    "Can't run -c, disabled by "
6391 				    "ZPOOL_SCRIPTS_ENABLED.\n"));
6392 				exit(1);
6393 			}
6394 
6395 			if ((getuid() <= 0 || geteuid() <= 0) &&
6396 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
6397 				fprintf(stderr, gettext(
6398 				    "Can't run -c with root privileges "
6399 				    "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
6400 				exit(1);
6401 			}
6402 			cmd = optarg;
6403 			verbose = B_TRUE;
6404 			break;
6405 		case 'g':
6406 			guid = B_TRUE;
6407 			break;
6408 		case 'L':
6409 			follow_links = B_TRUE;
6410 			break;
6411 		case 'P':
6412 			full_name = B_TRUE;
6413 			break;
6414 		case 'T':
6415 			get_timestamp_arg(*optarg);
6416 			break;
6417 		case 'v':
6418 			verbose = B_TRUE;
6419 			break;
6420 		case 'p':
6421 			parsable = B_TRUE;
6422 			break;
6423 		case 'l':
6424 			latency = B_TRUE;
6425 			break;
6426 		case 'q':
6427 			queues = B_TRUE;
6428 			break;
6429 		case 'H':
6430 			scripted = B_TRUE;
6431 			break;
6432 		case 'w':
6433 			l_histo = B_TRUE;
6434 			break;
6435 		case 'r':
6436 			rq_histo = B_TRUE;
6437 			break;
6438 		case 'y':
6439 			omit_since_boot = B_TRUE;
6440 			break;
6441 		case 'n':
6442 			headers_once = B_TRUE;
6443 			break;
6444 		case 'h':
6445 			usage(B_FALSE);
6446 			break;
6447 		case '?':
6448 			if (optopt == 'c') {
6449 				print_zpool_script_list("iostat");
6450 				exit(0);
6451 			} else {
6452 				fprintf(stderr,
6453 				    gettext("invalid option '%c'\n"), optopt);
6454 			}
6455 			usage(B_FALSE);
6456 		}
6457 	}
6458 
6459 	argc -= optind;
6460 	argv += optind;
6461 
6462 	cb.cb_literal = parsable;
6463 	cb.cb_scripted = scripted;
6464 
6465 	if (guid)
6466 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_GUID;
6467 	if (follow_links)
6468 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6469 	if (full_name)
6470 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_PATH;
6471 	cb.cb_iteration = 0;
6472 	cb.cb_namewidth = 0;
6473 	cb.cb_verbose = verbose;
6474 
6475 	/* Get our interval and count values (if any) */
6476 	if (guid) {
6477 		get_interval_count_filter_guids(&argc, argv, &interval,
6478 		    &count, &cb);
6479 	} else {
6480 		get_interval_count(&argc, argv, &interval, &count);
6481 	}
6482 
6483 	if (argc == 0) {
6484 		/* No args, so just print the defaults. */
6485 	} else if (are_all_pools(argc, argv)) {
6486 		/* All the args are pool names */
6487 	} else if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
6488 		/* All the args are vdevs */
6489 		cb.cb_vdevs.cb_names = argv;
6490 		cb.cb_vdevs.cb_names_count = argc;
6491 		argc = 0; /* No pools to process */
6492 	} else if (are_all_pools(1, argv)) {
6493 		/* The first arg is a pool name */
6494 		if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
6495 		    &cb.cb_vdevs)) {
6496 			/* ...and the rest are vdev names */
6497 			cb.cb_vdevs.cb_names = argv + 1;
6498 			cb.cb_vdevs.cb_names_count = argc - 1;
6499 			argc = 1; /* One pool to process */
6500 		} else {
6501 			fprintf(stderr, gettext("Expected either a list of "));
6502 			fprintf(stderr, gettext("pools, or list of vdevs in"));
6503 			fprintf(stderr, " \"%s\", ", argv[0]);
6504 			fprintf(stderr, gettext("but got:\n"));
6505 			error_list_unresolved_vdevs(argc - 1, argv + 1,
6506 			    argv[0], &cb.cb_vdevs);
6507 			fprintf(stderr, "\n");
6508 			usage(B_FALSE);
6509 			return (1);
6510 		}
6511 	} else {
6512 		/*
6513 		 * The args don't make sense. The first arg isn't a pool name,
6514 		 * nor are all the args vdevs.
6515 		 */
6516 		fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
6517 		fprintf(stderr, "\n");
6518 		return (1);
6519 	}
6520 
6521 	if (cb.cb_vdevs.cb_names_count != 0) {
6522 		/*
6523 		 * If user specified vdevs, it implies verbose.
6524 		 */
6525 		cb.cb_verbose = B_TRUE;
6526 	}
6527 
6528 	/*
6529 	 * Construct the list of all interesting pools.
6530 	 */
6531 	ret = 0;
6532 	if ((list = pool_list_get(argc, argv, NULL, ZFS_TYPE_POOL, parsable,
6533 	    &ret)) == NULL)
6534 		return (1);
6535 
6536 	if (pool_list_count(list) == 0 && argc != 0) {
6537 		pool_list_free(list);
6538 		return (1);
6539 	}
6540 
6541 	if (pool_list_count(list) == 0 && interval == 0) {
6542 		pool_list_free(list);
6543 		(void) fprintf(stderr, gettext("no pools available\n"));
6544 		return (1);
6545 	}
6546 
6547 	if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
6548 		pool_list_free(list);
6549 		(void) fprintf(stderr,
6550 		    gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
6551 		usage(B_FALSE);
6552 		return (1);
6553 	}
6554 
6555 	if (l_histo && rq_histo) {
6556 		pool_list_free(list);
6557 		(void) fprintf(stderr,
6558 		    gettext("Only one of [-r|-w] can be passed at a time\n"));
6559 		usage(B_FALSE);
6560 		return (1);
6561 	}
6562 
6563 	/*
6564 	 * Enter the main iostat loop.
6565 	 */
6566 	cb.cb_list = list;
6567 
6568 	if (l_histo) {
6569 		/*
6570 		 * Histograms tables look out of place when you try to display
6571 		 * them with the other stats, so make a rule that you can only
6572 		 * print histograms by themselves.
6573 		 */
6574 		cb.cb_flags = IOS_L_HISTO_M;
6575 	} else if (rq_histo) {
6576 		cb.cb_flags = IOS_RQ_HISTO_M;
6577 	} else {
6578 		cb.cb_flags = IOS_DEFAULT_M;
6579 		if (latency)
6580 			cb.cb_flags |= IOS_LATENCY_M;
6581 		if (queues)
6582 			cb.cb_flags |= IOS_QUEUES_M;
6583 	}
6584 
6585 	/*
6586 	 * See if the module supports all the stats we want to display.
6587 	 */
6588 	unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
6589 	if (unsupported_flags) {
6590 		uint64_t f;
6591 		int idx;
6592 		fprintf(stderr,
6593 		    gettext("The loaded zfs module doesn't support:"));
6594 
6595 		/* for each bit set in unsupported_flags */
6596 		for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
6597 			idx = lowbit64(f) - 1;
6598 			fprintf(stderr, " -%c", flag_to_arg[idx]);
6599 		}
6600 
6601 		fprintf(stderr, ".  Try running a newer module.\n");
6602 		pool_list_free(list);
6603 
6604 		return (1);
6605 	}
6606 
6607 	for (;;) {
6608 		if ((npools = pool_list_count(list)) == 0)
6609 			(void) fprintf(stderr, gettext("no pools available\n"));
6610 		else {
6611 			/*
6612 			 * If this is the first iteration and -y was supplied
6613 			 * we skip any printing.
6614 			 */
6615 			boolean_t skip = (omit_since_boot &&
6616 			    cb.cb_iteration == 0);
6617 
6618 			/*
6619 			 * Refresh all statistics.  This is done as an
6620 			 * explicit step before calculating the maximum name
6621 			 * width, so that any * configuration changes are
6622 			 * properly accounted for.
6623 			 */
6624 			(void) pool_list_iter(list, B_FALSE, refresh_iostat,
6625 			    &cb);
6626 
6627 			/*
6628 			 * Iterate over all pools to determine the maximum width
6629 			 * for the pool / device name column across all pools.
6630 			 */
6631 			cb.cb_namewidth = 0;
6632 			(void) pool_list_iter(list, B_FALSE,
6633 			    get_namewidth_iostat, &cb);
6634 
6635 			if (timestamp_fmt != NODATE)
6636 				print_timestamp(timestamp_fmt);
6637 
6638 			if (cmd != NULL && cb.cb_verbose &&
6639 			    !(cb.cb_flags & IOS_ANYHISTO_M)) {
6640 				cb.vcdl = all_pools_for_each_vdev_run(argc,
6641 				    argv, cmd, g_zfs, cb.cb_vdevs.cb_names,
6642 				    cb.cb_vdevs.cb_names_count,
6643 				    cb.cb_vdevs.cb_name_flags);
6644 			} else {
6645 				cb.vcdl = NULL;
6646 			}
6647 
6648 
6649 			/*
6650 			 * Check terminal size so we can print headers
6651 			 * even when terminal window has its height
6652 			 * changed.
6653 			 */
6654 			winheight = terminal_height();
6655 			/*
6656 			 * Are we connected to TTY? If not, headers_once
6657 			 * should be true, to avoid breaking scripts.
6658 			 */
6659 			if (winheight < 0)
6660 				headers_once = B_TRUE;
6661 
6662 			/*
6663 			 * If it's the first time and we're not skipping it,
6664 			 * or either skip or verbose mode, print the header.
6665 			 *
6666 			 * The histogram code explicitly prints its header on
6667 			 * every vdev, so skip this for histograms.
6668 			 */
6669 			if (((++cb.cb_iteration == 1 && !skip) ||
6670 			    (skip != verbose) ||
6671 			    (!headers_once &&
6672 			    (cb.cb_iteration % winheight) == 0)) &&
6673 			    (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
6674 			    !cb.cb_scripted)
6675 				print_iostat_header(&cb);
6676 
6677 			if (skip) {
6678 				(void) fflush(stdout);
6679 				(void) fsleep(interval);
6680 				continue;
6681 			}
6682 
6683 			pool_list_iter(list, B_FALSE, print_iostat, &cb);
6684 
6685 			/*
6686 			 * If there's more than one pool, and we're not in
6687 			 * verbose mode (which prints a separator for us),
6688 			 * then print a separator.
6689 			 *
6690 			 * In addition, if we're printing specific vdevs then
6691 			 * we also want an ending separator.
6692 			 */
6693 			if (((npools > 1 && !verbose &&
6694 			    !(cb.cb_flags & IOS_ANYHISTO_M)) ||
6695 			    (!(cb.cb_flags & IOS_ANYHISTO_M) &&
6696 			    cb.cb_vdevs.cb_names_count)) &&
6697 			    !cb.cb_scripted) {
6698 				print_iostat_separator(&cb);
6699 				if (cb.vcdl != NULL)
6700 					print_cmd_columns(cb.vcdl, 1);
6701 				printf("\n");
6702 			}
6703 
6704 			if (cb.vcdl != NULL)
6705 				free_vdev_cmd_data_list(cb.vcdl);
6706 
6707 		}
6708 
6709 		if (interval == 0)
6710 			break;
6711 
6712 		if (count != 0 && --count == 0)
6713 			break;
6714 
6715 		(void) fflush(stdout);
6716 		(void) fsleep(interval);
6717 	}
6718 
6719 	pool_list_free(list);
6720 
6721 	return (ret);
6722 }
6723 
6724 typedef struct list_cbdata {
6725 	boolean_t	cb_verbose;
6726 	int		cb_name_flags;
6727 	int		cb_namewidth;
6728 	boolean_t	cb_json;
6729 	boolean_t	cb_scripted;
6730 	zprop_list_t	*cb_proplist;
6731 	boolean_t	cb_literal;
6732 	nvlist_t	*cb_jsobj;
6733 	boolean_t	cb_json_as_int;
6734 	boolean_t	cb_json_pool_key_guid;
6735 } list_cbdata_t;
6736 
6737 
6738 /*
6739  * Given a list of columns to display, output appropriate headers for each one.
6740  */
6741 static void
6742 print_header(list_cbdata_t *cb)
6743 {
6744 	zprop_list_t *pl = cb->cb_proplist;
6745 	char headerbuf[ZPOOL_MAXPROPLEN];
6746 	const char *header;
6747 	boolean_t first = B_TRUE;
6748 	boolean_t right_justify;
6749 	size_t width = 0;
6750 
6751 	for (; pl != NULL; pl = pl->pl_next) {
6752 		width = pl->pl_width;
6753 		if (first && cb->cb_verbose) {
6754 			/*
6755 			 * Reset the width to accommodate the verbose listing
6756 			 * of devices.
6757 			 */
6758 			width = cb->cb_namewidth;
6759 		}
6760 
6761 		if (!first)
6762 			(void) fputs("  ", stdout);
6763 		else
6764 			first = B_FALSE;
6765 
6766 		right_justify = B_FALSE;
6767 		if (pl->pl_prop != ZPROP_USERPROP) {
6768 			header = zpool_prop_column_name(pl->pl_prop);
6769 			right_justify = zpool_prop_align_right(pl->pl_prop);
6770 		} else {
6771 			int i;
6772 
6773 			for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
6774 				headerbuf[i] = toupper(pl->pl_user_prop[i]);
6775 			headerbuf[i] = '\0';
6776 			header = headerbuf;
6777 		}
6778 
6779 		if (pl->pl_next == NULL && !right_justify)
6780 			(void) fputs(header, stdout);
6781 		else if (right_justify)
6782 			(void) printf("%*s", (int)width, header);
6783 		else
6784 			(void) printf("%-*s", (int)width, header);
6785 	}
6786 
6787 	(void) fputc('\n', stdout);
6788 }
6789 
6790 /*
6791  * Given a pool and a list of properties, print out all the properties according
6792  * to the described layout. Used by zpool_do_list().
6793  */
6794 static void
6795 collect_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
6796 {
6797 	zprop_list_t *pl = cb->cb_proplist;
6798 	boolean_t first = B_TRUE;
6799 	char property[ZPOOL_MAXPROPLEN];
6800 	const char *propstr;
6801 	boolean_t right_justify;
6802 	size_t width;
6803 	zprop_source_t sourcetype = ZPROP_SRC_NONE;
6804 	nvlist_t *item, *d, *props;
6805 	item = d = props = NULL;
6806 
6807 	if (cb->cb_json) {
6808 		item = fnvlist_alloc();
6809 		props = fnvlist_alloc();
6810 		d = fnvlist_lookup_nvlist(cb->cb_jsobj, "pools");
6811 		if (d == NULL) {
6812 			fprintf(stderr, "pools obj not found.\n");
6813 			exit(1);
6814 		}
6815 		fill_pool_info(item, zhp, B_TRUE, cb->cb_json_as_int);
6816 	}
6817 
6818 	for (; pl != NULL; pl = pl->pl_next) {
6819 
6820 		width = pl->pl_width;
6821 		if (first && cb->cb_verbose) {
6822 			/*
6823 			 * Reset the width to accommodate the verbose listing
6824 			 * of devices.
6825 			 */
6826 			width = cb->cb_namewidth;
6827 		}
6828 
6829 		if (!cb->cb_json && !first) {
6830 			if (cb->cb_scripted)
6831 				(void) fputc('\t', stdout);
6832 			else
6833 				(void) fputs("  ", stdout);
6834 		} else {
6835 			first = B_FALSE;
6836 		}
6837 
6838 		right_justify = B_FALSE;
6839 		if (pl->pl_prop != ZPROP_USERPROP) {
6840 			if (zpool_get_prop(zhp, pl->pl_prop, property,
6841 			    sizeof (property), &sourcetype,
6842 			    cb->cb_literal) != 0)
6843 				propstr = "-";
6844 			else
6845 				propstr = property;
6846 
6847 			right_justify = zpool_prop_align_right(pl->pl_prop);
6848 		} else if ((zpool_prop_feature(pl->pl_user_prop) ||
6849 		    zpool_prop_unsupported(pl->pl_user_prop)) &&
6850 		    zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
6851 		    sizeof (property)) == 0) {
6852 			propstr = property;
6853 			sourcetype = ZPROP_SRC_LOCAL;
6854 		} else if (zfs_prop_user(pl->pl_user_prop) &&
6855 		    zpool_get_userprop(zhp, pl->pl_user_prop, property,
6856 		    sizeof (property), &sourcetype) == 0) {
6857 			propstr = property;
6858 		} else {
6859 			propstr = "-";
6860 		}
6861 
6862 		if (cb->cb_json) {
6863 			if (pl->pl_prop == ZPOOL_PROP_NAME)
6864 				continue;
6865 			(void) zprop_nvlist_one_property(
6866 			    zpool_prop_to_name(pl->pl_prop), propstr,
6867 			    sourcetype, NULL, NULL, props, cb->cb_json_as_int);
6868 		} else {
6869 			/*
6870 			 * If this is being called in scripted mode, or if this
6871 			 * is the last column and it is left-justified, don't
6872 			 * include a width format specifier.
6873 			 */
6874 			if (cb->cb_scripted || (pl->pl_next == NULL &&
6875 			    !right_justify))
6876 				(void) fputs(propstr, stdout);
6877 			else if (right_justify)
6878 				(void) printf("%*s", (int)width, propstr);
6879 			else
6880 				(void) printf("%-*s", (int)width, propstr);
6881 		}
6882 	}
6883 
6884 	if (cb->cb_json) {
6885 		fnvlist_add_nvlist(item, "properties", props);
6886 		if (cb->cb_json_pool_key_guid) {
6887 			char pool_guid[256];
6888 			uint64_t guid = fnvlist_lookup_uint64(
6889 			    zpool_get_config(zhp, NULL),
6890 			    ZPOOL_CONFIG_POOL_GUID);
6891 			snprintf(pool_guid, 256, "%llu",
6892 			    (u_longlong_t)guid);
6893 			fnvlist_add_nvlist(d, pool_guid, item);
6894 		} else {
6895 			fnvlist_add_nvlist(d, zpool_get_name(zhp),
6896 			    item);
6897 		}
6898 		fnvlist_free(props);
6899 		fnvlist_free(item);
6900 	} else
6901 		(void) fputc('\n', stdout);
6902 }
6903 
6904 static void
6905 collect_vdev_prop(zpool_prop_t prop, uint64_t value, const char *str,
6906     boolean_t scripted, boolean_t valid, enum zfs_nicenum_format format,
6907     boolean_t json, nvlist_t *nvl, boolean_t as_int)
6908 {
6909 	char propval[64];
6910 	boolean_t fixed;
6911 	size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
6912 
6913 	switch (prop) {
6914 	case ZPOOL_PROP_SIZE:
6915 	case ZPOOL_PROP_EXPANDSZ:
6916 	case ZPOOL_PROP_CHECKPOINT:
6917 	case ZPOOL_PROP_DEDUPRATIO:
6918 	case ZPOOL_PROP_DEDUPCACHED:
6919 		if (value == 0)
6920 			(void) strlcpy(propval, "-", sizeof (propval));
6921 		else
6922 			zfs_nicenum_format(value, propval, sizeof (propval),
6923 			    format);
6924 		break;
6925 	case ZPOOL_PROP_FRAGMENTATION:
6926 		if (value == ZFS_FRAG_INVALID) {
6927 			(void) strlcpy(propval, "-", sizeof (propval));
6928 		} else if (format == ZFS_NICENUM_RAW) {
6929 			(void) snprintf(propval, sizeof (propval), "%llu",
6930 			    (unsigned long long)value);
6931 		} else {
6932 			(void) snprintf(propval, sizeof (propval), "%llu%%",
6933 			    (unsigned long long)value);
6934 		}
6935 		break;
6936 	case ZPOOL_PROP_CAPACITY:
6937 		/* capacity value is in parts-per-10,000 (aka permyriad) */
6938 		if (format == ZFS_NICENUM_RAW)
6939 			(void) snprintf(propval, sizeof (propval), "%llu",
6940 			    (unsigned long long)value / 100);
6941 		else
6942 			(void) snprintf(propval, sizeof (propval),
6943 			    value < 1000 ? "%1.2f%%" : value < 10000 ?
6944 			    "%2.1f%%" : "%3.0f%%", value / 100.0);
6945 		break;
6946 	case ZPOOL_PROP_HEALTH:
6947 		width = 8;
6948 		(void) strlcpy(propval, str, sizeof (propval));
6949 		break;
6950 	default:
6951 		zfs_nicenum_format(value, propval, sizeof (propval), format);
6952 	}
6953 
6954 	if (!valid)
6955 		(void) strlcpy(propval, "-", sizeof (propval));
6956 
6957 	if (json) {
6958 		zprop_nvlist_one_property(zpool_prop_to_name(prop), propval,
6959 		    ZPROP_SRC_NONE, NULL, NULL, nvl, as_int);
6960 	} else {
6961 		if (scripted)
6962 			(void) printf("\t%s", propval);
6963 		else
6964 			(void) printf("  %*s", (int)width, propval);
6965 	}
6966 }
6967 
6968 /*
6969  * print static default line per vdev
6970  * not compatible with '-o' <proplist> option
6971  */
6972 static void
6973 collect_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
6974     list_cbdata_t *cb, int depth, boolean_t isspare, nvlist_t *item)
6975 {
6976 	nvlist_t **child;
6977 	vdev_stat_t *vs;
6978 	uint_t c, children = 0;
6979 	char *vname;
6980 	boolean_t scripted = cb->cb_scripted;
6981 	uint64_t islog = B_FALSE;
6982 	nvlist_t *props, *ent, *ch, *obj, *l2c, *sp;
6983 	props = ent = ch = obj = sp = l2c = NULL;
6984 	const char *dashes = "%-*s      -      -      -        -         "
6985 	    "-      -      -      -         -\n";
6986 
6987 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
6988 	    (uint64_t **)&vs, &c) == 0);
6989 
6990 	if (name != NULL) {
6991 		boolean_t toplevel = (vs->vs_space != 0);
6992 		uint64_t cap;
6993 		enum zfs_nicenum_format format;
6994 		const char *state;
6995 
6996 		if (cb->cb_literal)
6997 			format = ZFS_NICENUM_RAW;
6998 		else
6999 			format = ZFS_NICENUM_1024;
7000 
7001 		if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
7002 			return;
7003 
7004 		if (cb->cb_json) {
7005 			props = fnvlist_alloc();
7006 			ent = fnvlist_alloc();
7007 			fill_vdev_info(ent, zhp, (char *)name, B_FALSE,
7008 			    cb->cb_json_as_int);
7009 		} else {
7010 			if (scripted)
7011 				(void) printf("\t%s", name);
7012 			else if (strlen(name) + depth > cb->cb_namewidth)
7013 				(void) printf("%*s%s", depth, "", name);
7014 			else
7015 				(void) printf("%*s%s%*s", depth, "", name,
7016 				    (int)(cb->cb_namewidth - strlen(name) -
7017 				    depth), "");
7018 		}
7019 
7020 		/*
7021 		 * Print the properties for the individual vdevs. Some
7022 		 * properties are only applicable to toplevel vdevs. The
7023 		 * 'toplevel' boolean value is passed to the print_one_column()
7024 		 * to indicate that the value is valid.
7025 		 */
7026 		if (VDEV_STAT_VALID(vs_pspace, c) && vs->vs_pspace) {
7027 			collect_vdev_prop(ZPOOL_PROP_SIZE, vs->vs_pspace, NULL,
7028 			    scripted, B_TRUE, format, cb->cb_json, props,
7029 			    cb->cb_json_as_int);
7030 		} else {
7031 			collect_vdev_prop(ZPOOL_PROP_SIZE, vs->vs_space, NULL,
7032 			    scripted, toplevel, format, cb->cb_json, props,
7033 			    cb->cb_json_as_int);
7034 		}
7035 		collect_vdev_prop(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, NULL,
7036 		    scripted, toplevel, format, cb->cb_json, props,
7037 		    cb->cb_json_as_int);
7038 		collect_vdev_prop(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
7039 		    NULL, scripted, toplevel, format, cb->cb_json, props,
7040 		    cb->cb_json_as_int);
7041 		collect_vdev_prop(ZPOOL_PROP_CHECKPOINT,
7042 		    vs->vs_checkpoint_space, NULL, scripted, toplevel, format,
7043 		    cb->cb_json, props, cb->cb_json_as_int);
7044 		collect_vdev_prop(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, NULL,
7045 		    scripted, B_TRUE, format, cb->cb_json, props,
7046 		    cb->cb_json_as_int);
7047 		collect_vdev_prop(ZPOOL_PROP_FRAGMENTATION,
7048 		    vs->vs_fragmentation, NULL, scripted,
7049 		    (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
7050 		    format, cb->cb_json, props, cb->cb_json_as_int);
7051 		cap = (vs->vs_space == 0) ? 0 :
7052 		    (vs->vs_alloc * 10000 / vs->vs_space);
7053 		collect_vdev_prop(ZPOOL_PROP_CAPACITY, cap, NULL,
7054 		    scripted, toplevel, format, cb->cb_json, props,
7055 		    cb->cb_json_as_int);
7056 		collect_vdev_prop(ZPOOL_PROP_DEDUPRATIO, 0, NULL,
7057 		    scripted, toplevel, format, cb->cb_json, props,
7058 		    cb->cb_json_as_int);
7059 		state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
7060 		if (isspare) {
7061 			if (vs->vs_aux == VDEV_AUX_SPARED)
7062 				state = "INUSE";
7063 			else if (vs->vs_state == VDEV_STATE_HEALTHY)
7064 				state = "AVAIL";
7065 		}
7066 		collect_vdev_prop(ZPOOL_PROP_HEALTH, 0, state, scripted,
7067 		    B_TRUE, format, cb->cb_json, props, cb->cb_json_as_int);
7068 
7069 		if (cb->cb_json) {
7070 			fnvlist_add_nvlist(ent, "properties", props);
7071 			fnvlist_free(props);
7072 		} else
7073 			(void) fputc('\n', stdout);
7074 	}
7075 
7076 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
7077 	    &child, &children) != 0) {
7078 		if (cb->cb_json) {
7079 			fnvlist_add_nvlist(item, name, ent);
7080 			fnvlist_free(ent);
7081 		}
7082 		return;
7083 	}
7084 
7085 	if (cb->cb_json) {
7086 		ch = fnvlist_alloc();
7087 	}
7088 
7089 	/* list the normal vdevs first */
7090 	for (c = 0; c < children; c++) {
7091 		uint64_t ishole = B_FALSE;
7092 
7093 		if (nvlist_lookup_uint64(child[c],
7094 		    ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
7095 			continue;
7096 
7097 		if (nvlist_lookup_uint64(child[c],
7098 		    ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
7099 			continue;
7100 
7101 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
7102 			continue;
7103 
7104 		vname = zpool_vdev_name(g_zfs, zhp, child[c],
7105 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7106 
7107 		if (name == NULL || cb->cb_json != B_TRUE)
7108 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7109 			    B_FALSE, item);
7110 		else if (cb->cb_json) {
7111 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7112 			    B_FALSE, ch);
7113 		}
7114 		free(vname);
7115 	}
7116 
7117 	if (cb->cb_json) {
7118 		if (!nvlist_empty(ch))
7119 			fnvlist_add_nvlist(ent, "vdevs", ch);
7120 		fnvlist_free(ch);
7121 	}
7122 
7123 	/* list the classes: 'logs', 'dedup', and 'special' */
7124 	for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
7125 		boolean_t printed = B_FALSE;
7126 		if (cb->cb_json)
7127 			obj = fnvlist_alloc();
7128 		for (c = 0; c < children; c++) {
7129 			const char *bias = NULL;
7130 			const char *type = NULL;
7131 
7132 			if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
7133 			    &islog) == 0 && islog) {
7134 				bias = VDEV_ALLOC_CLASS_LOGS;
7135 			} else {
7136 				(void) nvlist_lookup_string(child[c],
7137 				    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
7138 				(void) nvlist_lookup_string(child[c],
7139 				    ZPOOL_CONFIG_TYPE, &type);
7140 			}
7141 			if (bias == NULL || strcmp(bias, class_name[n]) != 0)
7142 				continue;
7143 			if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
7144 				continue;
7145 
7146 			if (!printed && !cb->cb_json) {
7147 				/* LINTED E_SEC_PRINTF_VAR_FMT */
7148 				(void) printf(dashes, cb->cb_namewidth,
7149 				    class_name[n]);
7150 				printed = B_TRUE;
7151 			}
7152 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
7153 			    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7154 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7155 			    B_FALSE, obj);
7156 			free(vname);
7157 		}
7158 		if (cb->cb_json) {
7159 			if (!nvlist_empty(obj))
7160 				fnvlist_add_nvlist(item, class_name[n], obj);
7161 			fnvlist_free(obj);
7162 		}
7163 	}
7164 
7165 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
7166 	    &child, &children) == 0 && children > 0) {
7167 		if (cb->cb_json) {
7168 			l2c = fnvlist_alloc();
7169 		} else {
7170 			/* LINTED E_SEC_PRINTF_VAR_FMT */
7171 			(void) printf(dashes, cb->cb_namewidth, "cache");
7172 		}
7173 		for (c = 0; c < children; c++) {
7174 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
7175 			    cb->cb_name_flags);
7176 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7177 			    B_FALSE, l2c);
7178 			free(vname);
7179 		}
7180 		if (cb->cb_json) {
7181 			if (!nvlist_empty(l2c))
7182 				fnvlist_add_nvlist(item, "l2cache", l2c);
7183 			fnvlist_free(l2c);
7184 		}
7185 	}
7186 
7187 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
7188 	    &children) == 0 && children > 0) {
7189 		if (cb->cb_json) {
7190 			sp = fnvlist_alloc();
7191 		} else {
7192 			/* LINTED E_SEC_PRINTF_VAR_FMT */
7193 			(void) printf(dashes, cb->cb_namewidth, "spare");
7194 		}
7195 		for (c = 0; c < children; c++) {
7196 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
7197 			    cb->cb_name_flags);
7198 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7199 			    B_TRUE, sp);
7200 			free(vname);
7201 		}
7202 		if (cb->cb_json) {
7203 			if (!nvlist_empty(sp))
7204 				fnvlist_add_nvlist(item, "spares", sp);
7205 			fnvlist_free(sp);
7206 		}
7207 	}
7208 
7209 	if (name != NULL && cb->cb_json) {
7210 		fnvlist_add_nvlist(item, name, ent);
7211 		fnvlist_free(ent);
7212 	}
7213 }
7214 
7215 /*
7216  * Generic callback function to list a pool.
7217  */
7218 static int
7219 list_callback(zpool_handle_t *zhp, void *data)
7220 {
7221 	nvlist_t *p, *d, *nvdevs;
7222 	uint64_t guid;
7223 	char pool_guid[256];
7224 	const char *pool_name = zpool_get_name(zhp);
7225 	list_cbdata_t *cbp = data;
7226 	p = d = nvdevs = NULL;
7227 
7228 	collect_pool(zhp, cbp);
7229 
7230 	if (cbp->cb_verbose) {
7231 		nvlist_t *config, *nvroot;
7232 		config = zpool_get_config(zhp, NULL);
7233 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
7234 		    &nvroot) == 0);
7235 		if (cbp->cb_json) {
7236 			d = fnvlist_lookup_nvlist(cbp->cb_jsobj,
7237 			    "pools");
7238 			if (cbp->cb_json_pool_key_guid) {
7239 				guid = fnvlist_lookup_uint64(config,
7240 				    ZPOOL_CONFIG_POOL_GUID);
7241 				snprintf(pool_guid, 256, "%llu",
7242 				    (u_longlong_t)guid);
7243 				p = fnvlist_lookup_nvlist(d, pool_guid);
7244 			} else {
7245 				p = fnvlist_lookup_nvlist(d, pool_name);
7246 			}
7247 			nvdevs = fnvlist_alloc();
7248 		}
7249 		collect_list_stats(zhp, NULL, nvroot, cbp, 0, B_FALSE, nvdevs);
7250 		if (cbp->cb_json) {
7251 			fnvlist_add_nvlist(p, "vdevs", nvdevs);
7252 			if (cbp->cb_json_pool_key_guid)
7253 				fnvlist_add_nvlist(d, pool_guid, p);
7254 			else
7255 				fnvlist_add_nvlist(d, pool_name, p);
7256 			fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
7257 			fnvlist_free(nvdevs);
7258 		}
7259 	}
7260 
7261 	return (0);
7262 }
7263 
7264 /*
7265  * Set the minimum pool/vdev name column width.  The width must be at least 9,
7266  * but may be as large as needed.
7267  */
7268 static int
7269 get_namewidth_list(zpool_handle_t *zhp, void *data)
7270 {
7271 	list_cbdata_t *cb = data;
7272 	int width;
7273 
7274 	width = get_namewidth(zhp, cb->cb_namewidth,
7275 	    cb->cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
7276 
7277 	if (width < 9)
7278 		width = 9;
7279 
7280 	cb->cb_namewidth = width;
7281 
7282 	return (0);
7283 }
7284 
7285 /*
7286  * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
7287  *
7288  *	-g	Display guid for individual vdev name.
7289  *	-H	Scripted mode.  Don't display headers, and separate properties
7290  *		by a single tab.
7291  *	-L	Follow links when resolving vdev path name.
7292  *	-o	List of properties to display.  Defaults to
7293  *		"name,size,allocated,free,expandsize,fragmentation,capacity,"
7294  *		"dedupratio,health,altroot"
7295  *	-p	Display values in parsable (exact) format.
7296  *	-P	Display full path for vdev name.
7297  *	-T	Display a timestamp in date(1) or Unix format
7298  *	-j	Display the output in JSON format
7299  *	--json-int	Display the numbers as integer instead of strings.
7300  *	--json-pool-key-guid  Set pool GUID as key for pool objects.
7301  *
7302  * List all pools in the system, whether or not they're healthy.  Output space
7303  * statistics for each one, as well as health status summary.
7304  */
7305 int
7306 zpool_do_list(int argc, char **argv)
7307 {
7308 	int c;
7309 	int ret = 0;
7310 	list_cbdata_t cb = { 0 };
7311 	static char default_props[] =
7312 	    "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
7313 	    "capacity,dedupratio,health,altroot";
7314 	char *props = default_props;
7315 	float interval = 0;
7316 	unsigned long count = 0;
7317 	zpool_list_t *list;
7318 	boolean_t first = B_TRUE;
7319 	nvlist_t *data = NULL;
7320 	current_prop_type = ZFS_TYPE_POOL;
7321 
7322 	struct option long_options[] = {
7323 		{"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
7324 		{"json-pool-key-guid", no_argument, NULL,
7325 		    ZPOOL_OPTION_POOL_KEY_GUID},
7326 		{0, 0, 0, 0}
7327 	};
7328 
7329 	/* check options */
7330 	while ((c = getopt_long(argc, argv, ":gjHLo:pPT:v", long_options,
7331 	    NULL)) != -1) {
7332 		switch (c) {
7333 		case 'g':
7334 			cb.cb_name_flags |= VDEV_NAME_GUID;
7335 			break;
7336 		case 'H':
7337 			cb.cb_scripted = B_TRUE;
7338 			break;
7339 		case 'L':
7340 			cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
7341 			break;
7342 		case 'o':
7343 			props = optarg;
7344 			break;
7345 		case 'P':
7346 			cb.cb_name_flags |= VDEV_NAME_PATH;
7347 			break;
7348 		case 'p':
7349 			cb.cb_literal = B_TRUE;
7350 			break;
7351 		case 'j':
7352 			cb.cb_json = B_TRUE;
7353 			break;
7354 		case ZPOOL_OPTION_JSON_NUMS_AS_INT:
7355 			cb.cb_json_as_int = B_TRUE;
7356 			cb.cb_literal = B_TRUE;
7357 			break;
7358 		case ZPOOL_OPTION_POOL_KEY_GUID:
7359 			cb.cb_json_pool_key_guid = B_TRUE;
7360 			break;
7361 		case 'T':
7362 			get_timestamp_arg(*optarg);
7363 			break;
7364 		case 'v':
7365 			cb.cb_verbose = B_TRUE;
7366 			cb.cb_namewidth = 8;	/* 8 until precalc is avail */
7367 			break;
7368 		case ':':
7369 			(void) fprintf(stderr, gettext("missing argument for "
7370 			    "'%c' option\n"), optopt);
7371 			usage(B_FALSE);
7372 			break;
7373 		case '?':
7374 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7375 			    optopt);
7376 			usage(B_FALSE);
7377 		}
7378 	}
7379 
7380 	argc -= optind;
7381 	argv += optind;
7382 
7383 	if (!cb.cb_json && cb.cb_json_as_int) {
7384 		(void) fprintf(stderr, gettext("'--json-int' only works with"
7385 		    " '-j' option\n"));
7386 		usage(B_FALSE);
7387 	}
7388 
7389 	if (!cb.cb_json && cb.cb_json_pool_key_guid) {
7390 		(void) fprintf(stderr, gettext("'json-pool-key-guid' only"
7391 		    " works with '-j' option\n"));
7392 		usage(B_FALSE);
7393 	}
7394 
7395 	get_interval_count(&argc, argv, &interval, &count);
7396 
7397 	if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
7398 		usage(B_FALSE);
7399 
7400 	for (;;) {
7401 		if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
7402 		    ZFS_TYPE_POOL, cb.cb_literal, &ret)) == NULL)
7403 			return (1);
7404 
7405 		if (pool_list_count(list) == 0)
7406 			break;
7407 
7408 		if (cb.cb_json) {
7409 			cb.cb_jsobj = zpool_json_schema(0, 1);
7410 			data = fnvlist_alloc();
7411 			fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
7412 			fnvlist_free(data);
7413 		}
7414 
7415 		cb.cb_namewidth = 0;
7416 		(void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
7417 
7418 		if (timestamp_fmt != NODATE) {
7419 			if (cb.cb_json) {
7420 				if (cb.cb_json_as_int) {
7421 					fnvlist_add_uint64(cb.cb_jsobj, "time",
7422 					    time(NULL));
7423 				} else {
7424 					char ts[128];
7425 					get_timestamp(timestamp_fmt, ts, 128);
7426 					fnvlist_add_string(cb.cb_jsobj, "time",
7427 					    ts);
7428 				}
7429 			} else
7430 				print_timestamp(timestamp_fmt);
7431 		}
7432 
7433 		if (!cb.cb_scripted && (first || cb.cb_verbose) &&
7434 		    !cb.cb_json) {
7435 			print_header(&cb);
7436 			first = B_FALSE;
7437 		}
7438 		ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
7439 
7440 		if (ret == 0 && cb.cb_json)
7441 			zcmd_print_json(cb.cb_jsobj);
7442 		else if (ret != 0 && cb.cb_json)
7443 			nvlist_free(cb.cb_jsobj);
7444 
7445 		if (interval == 0)
7446 			break;
7447 
7448 		if (count != 0 && --count == 0)
7449 			break;
7450 
7451 		pool_list_free(list);
7452 
7453 		(void) fflush(stdout);
7454 		(void) fsleep(interval);
7455 	}
7456 
7457 	if (argc == 0 && !cb.cb_scripted && !cb.cb_json &&
7458 	    pool_list_count(list) == 0) {
7459 		(void) printf(gettext("no pools available\n"));
7460 		ret = 0;
7461 	}
7462 
7463 	pool_list_free(list);
7464 	zprop_free_list(cb.cb_proplist);
7465 	return (ret);
7466 }
7467 
7468 static int
7469 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
7470 {
7471 	boolean_t force = B_FALSE;
7472 	boolean_t rebuild = B_FALSE;
7473 	boolean_t wait = B_FALSE;
7474 	int c;
7475 	nvlist_t *nvroot;
7476 	char *poolname, *old_disk, *new_disk;
7477 	zpool_handle_t *zhp;
7478 	nvlist_t *props = NULL;
7479 	char *propval;
7480 	int ret;
7481 
7482 	/* check options */
7483 	while ((c = getopt(argc, argv, "fo:sw")) != -1) {
7484 		switch (c) {
7485 		case 'f':
7486 			force = B_TRUE;
7487 			break;
7488 		case 'o':
7489 			if ((propval = strchr(optarg, '=')) == NULL) {
7490 				(void) fprintf(stderr, gettext("missing "
7491 				    "'=' for -o option\n"));
7492 				usage(B_FALSE);
7493 			}
7494 			*propval = '\0';
7495 			propval++;
7496 
7497 			if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
7498 			    (add_prop_list(optarg, propval, &props, B_TRUE)))
7499 				usage(B_FALSE);
7500 			break;
7501 		case 's':
7502 			rebuild = B_TRUE;
7503 			break;
7504 		case 'w':
7505 			wait = B_TRUE;
7506 			break;
7507 		case '?':
7508 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7509 			    optopt);
7510 			usage(B_FALSE);
7511 		}
7512 	}
7513 
7514 	argc -= optind;
7515 	argv += optind;
7516 
7517 	/* get pool name and check number of arguments */
7518 	if (argc < 1) {
7519 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
7520 		usage(B_FALSE);
7521 	}
7522 
7523 	poolname = argv[0];
7524 
7525 	if (argc < 2) {
7526 		(void) fprintf(stderr,
7527 		    gettext("missing <device> specification\n"));
7528 		usage(B_FALSE);
7529 	}
7530 
7531 	old_disk = argv[1];
7532 
7533 	if (argc < 3) {
7534 		if (!replacing) {
7535 			(void) fprintf(stderr,
7536 			    gettext("missing <new_device> specification\n"));
7537 			usage(B_FALSE);
7538 		}
7539 		new_disk = old_disk;
7540 		argc -= 1;
7541 		argv += 1;
7542 	} else {
7543 		new_disk = argv[2];
7544 		argc -= 2;
7545 		argv += 2;
7546 	}
7547 
7548 	if (argc > 1) {
7549 		(void) fprintf(stderr, gettext("too many arguments\n"));
7550 		usage(B_FALSE);
7551 	}
7552 
7553 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7554 		nvlist_free(props);
7555 		return (1);
7556 	}
7557 
7558 	if (zpool_get_config(zhp, NULL) == NULL) {
7559 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
7560 		    poolname);
7561 		zpool_close(zhp);
7562 		nvlist_free(props);
7563 		return (1);
7564 	}
7565 
7566 	/* unless manually specified use "ashift" pool property (if set) */
7567 	if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
7568 		int intval;
7569 		zprop_source_t src;
7570 		char strval[ZPOOL_MAXPROPLEN];
7571 
7572 		intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
7573 		if (src != ZPROP_SRC_DEFAULT) {
7574 			(void) sprintf(strval, "%" PRId32, intval);
7575 			verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
7576 			    &props, B_TRUE) == 0);
7577 		}
7578 	}
7579 
7580 	nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
7581 	    argc, argv);
7582 	if (nvroot == NULL) {
7583 		zpool_close(zhp);
7584 		nvlist_free(props);
7585 		return (1);
7586 	}
7587 
7588 	ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing,
7589 	    rebuild);
7590 
7591 	if (ret == 0 && wait) {
7592 		zpool_wait_activity_t activity = ZPOOL_WAIT_RESILVER;
7593 		char raidz_prefix[] = "raidz";
7594 		if (replacing) {
7595 			activity = ZPOOL_WAIT_REPLACE;
7596 		} else if (strncmp(old_disk,
7597 		    raidz_prefix, strlen(raidz_prefix)) == 0) {
7598 			activity = ZPOOL_WAIT_RAIDZ_EXPAND;
7599 		}
7600 		ret = zpool_wait(zhp, activity);
7601 	}
7602 
7603 	nvlist_free(props);
7604 	nvlist_free(nvroot);
7605 	zpool_close(zhp);
7606 
7607 	return (ret);
7608 }
7609 
7610 /*
7611  * zpool replace [-fsw] [-o property=value] <pool> <device> <new_device>
7612  *
7613  *	-f	Force attach, even if <new_device> appears to be in use.
7614  *	-s	Use sequential instead of healing reconstruction for resilver.
7615  *	-o	Set property=value.
7616  *	-w	Wait for replacing to complete before returning
7617  *
7618  * Replace <device> with <new_device>.
7619  */
7620 int
7621 zpool_do_replace(int argc, char **argv)
7622 {
7623 	return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
7624 }
7625 
7626 /*
7627  * zpool attach [-fsw] [-o property=value] <pool> <device>|<vdev> <new_device>
7628  *
7629  *	-f	Force attach, even if <new_device> appears to be in use.
7630  *	-s	Use sequential instead of healing reconstruction for resilver.
7631  *	-o	Set property=value.
7632  *	-w	Wait for resilvering (mirror) or expansion (raidz) to complete
7633  *		before returning.
7634  *
7635  * Attach <new_device> to a <device> or <vdev>, where the vdev can be of type
7636  * mirror or raidz. If <device> is not part of a mirror, then <device> will
7637  * be transformed into a mirror of <device> and <new_device>. When a mirror
7638  * is involved, <new_device> will begin life with a DTL of [0, now], and will
7639  * immediately begin to resilver itself. For the raidz case, a expansion will
7640  * commence and reflow the raidz data across all the disks including the
7641  * <new_device>.
7642  */
7643 int
7644 zpool_do_attach(int argc, char **argv)
7645 {
7646 	return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
7647 }
7648 
7649 /*
7650  * zpool detach [-f] <pool> <device>
7651  *
7652  *	-f	Force detach of <device>, even if DTLs argue against it
7653  *		(not supported yet)
7654  *
7655  * Detach a device from a mirror.  The operation will be refused if <device>
7656  * is the last device in the mirror, or if the DTLs indicate that this device
7657  * has the only valid copy of some data.
7658  */
7659 int
7660 zpool_do_detach(int argc, char **argv)
7661 {
7662 	int c;
7663 	char *poolname, *path;
7664 	zpool_handle_t *zhp;
7665 	int ret;
7666 
7667 	/* check options */
7668 	while ((c = getopt(argc, argv, "")) != -1) {
7669 		switch (c) {
7670 		case '?':
7671 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7672 			    optopt);
7673 			usage(B_FALSE);
7674 		}
7675 	}
7676 
7677 	argc -= optind;
7678 	argv += optind;
7679 
7680 	/* get pool name and check number of arguments */
7681 	if (argc < 1) {
7682 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
7683 		usage(B_FALSE);
7684 	}
7685 
7686 	if (argc < 2) {
7687 		(void) fprintf(stderr,
7688 		    gettext("missing <device> specification\n"));
7689 		usage(B_FALSE);
7690 	}
7691 
7692 	poolname = argv[0];
7693 	path = argv[1];
7694 
7695 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7696 		return (1);
7697 
7698 	ret = zpool_vdev_detach(zhp, path);
7699 
7700 	zpool_close(zhp);
7701 
7702 	return (ret);
7703 }
7704 
7705 /*
7706  * zpool split [-gLnP] [-o prop=val] ...
7707  *		[-o mntopt] ...
7708  *		[-R altroot] <pool> <newpool> [<device> ...]
7709  *
7710  *	-g      Display guid for individual vdev name.
7711  *	-L	Follow links when resolving vdev path name.
7712  *	-n	Do not split the pool, but display the resulting layout if
7713  *		it were to be split.
7714  *	-o	Set property=value, or set mount options.
7715  *	-P	Display full path for vdev name.
7716  *	-R	Mount the split-off pool under an alternate root.
7717  *	-l	Load encryption keys while importing.
7718  *
7719  * Splits the named pool and gives it the new pool name.  Devices to be split
7720  * off may be listed, provided that no more than one device is specified
7721  * per top-level vdev mirror.  The newly split pool is left in an exported
7722  * state unless -R is specified.
7723  *
7724  * Restrictions: the top-level of the pool pool must only be made up of
7725  * mirrors; all devices in the pool must be healthy; no device may be
7726  * undergoing a resilvering operation.
7727  */
7728 int
7729 zpool_do_split(int argc, char **argv)
7730 {
7731 	char *srcpool, *newpool, *propval;
7732 	char *mntopts = NULL;
7733 	splitflags_t flags;
7734 	int c, ret = 0;
7735 	int ms_status = 0;
7736 	boolean_t loadkeys = B_FALSE;
7737 	zpool_handle_t *zhp;
7738 	nvlist_t *config, *props = NULL;
7739 
7740 	flags.dryrun = B_FALSE;
7741 	flags.import = B_FALSE;
7742 	flags.name_flags = 0;
7743 
7744 	/* check options */
7745 	while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
7746 		switch (c) {
7747 		case 'g':
7748 			flags.name_flags |= VDEV_NAME_GUID;
7749 			break;
7750 		case 'L':
7751 			flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
7752 			break;
7753 		case 'R':
7754 			flags.import = B_TRUE;
7755 			if (add_prop_list(
7756 			    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
7757 			    &props, B_TRUE) != 0) {
7758 				nvlist_free(props);
7759 				usage(B_FALSE);
7760 			}
7761 			break;
7762 		case 'l':
7763 			loadkeys = B_TRUE;
7764 			break;
7765 		case 'n':
7766 			flags.dryrun = B_TRUE;
7767 			break;
7768 		case 'o':
7769 			if ((propval = strchr(optarg, '=')) != NULL) {
7770 				*propval = '\0';
7771 				propval++;
7772 				if (add_prop_list(optarg, propval,
7773 				    &props, B_TRUE) != 0) {
7774 					nvlist_free(props);
7775 					usage(B_FALSE);
7776 				}
7777 			} else {
7778 				mntopts = optarg;
7779 			}
7780 			break;
7781 		case 'P':
7782 			flags.name_flags |= VDEV_NAME_PATH;
7783 			break;
7784 		case ':':
7785 			(void) fprintf(stderr, gettext("missing argument for "
7786 			    "'%c' option\n"), optopt);
7787 			usage(B_FALSE);
7788 			break;
7789 		case '?':
7790 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7791 			    optopt);
7792 			usage(B_FALSE);
7793 			break;
7794 		}
7795 	}
7796 
7797 	if (!flags.import && mntopts != NULL) {
7798 		(void) fprintf(stderr, gettext("setting mntopts is only "
7799 		    "valid when importing the pool\n"));
7800 		usage(B_FALSE);
7801 	}
7802 
7803 	if (!flags.import && loadkeys) {
7804 		(void) fprintf(stderr, gettext("loading keys is only "
7805 		    "valid when importing the pool\n"));
7806 		usage(B_FALSE);
7807 	}
7808 
7809 	argc -= optind;
7810 	argv += optind;
7811 
7812 	if (argc < 1) {
7813 		(void) fprintf(stderr, gettext("Missing pool name\n"));
7814 		usage(B_FALSE);
7815 	}
7816 	if (argc < 2) {
7817 		(void) fprintf(stderr, gettext("Missing new pool name\n"));
7818 		usage(B_FALSE);
7819 	}
7820 
7821 	srcpool = argv[0];
7822 	newpool = argv[1];
7823 
7824 	argc -= 2;
7825 	argv += 2;
7826 
7827 	if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
7828 		nvlist_free(props);
7829 		return (1);
7830 	}
7831 
7832 	config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
7833 	if (config == NULL) {
7834 		ret = 1;
7835 	} else {
7836 		if (flags.dryrun) {
7837 			(void) printf(gettext("would create '%s' with the "
7838 			    "following layout:\n\n"), newpool);
7839 			print_vdev_tree(NULL, newpool, config, 0, "",
7840 			    flags.name_flags);
7841 			print_vdev_tree(NULL, "dedup", config, 0,
7842 			    VDEV_ALLOC_BIAS_DEDUP, 0);
7843 			print_vdev_tree(NULL, "special", config, 0,
7844 			    VDEV_ALLOC_BIAS_SPECIAL, 0);
7845 		}
7846 	}
7847 
7848 	zpool_close(zhp);
7849 
7850 	if (ret != 0 || flags.dryrun || !flags.import) {
7851 		nvlist_free(config);
7852 		nvlist_free(props);
7853 		return (ret);
7854 	}
7855 
7856 	/*
7857 	 * The split was successful. Now we need to open the new
7858 	 * pool and import it.
7859 	 */
7860 	if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
7861 		nvlist_free(config);
7862 		nvlist_free(props);
7863 		return (1);
7864 	}
7865 
7866 	if (loadkeys) {
7867 		ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
7868 		if (ret != 0)
7869 			ret = 1;
7870 	}
7871 
7872 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL) {
7873 		ms_status = zpool_enable_datasets(zhp, mntopts, 0,
7874 		    mount_tp_nthr);
7875 		if (ms_status == EZFS_SHAREFAILED) {
7876 			(void) fprintf(stderr, gettext("Split was successful, "
7877 			    "datasets are mounted but sharing of some datasets "
7878 			    "has failed\n"));
7879 		} else if (ms_status == EZFS_MOUNTFAILED) {
7880 			(void) fprintf(stderr, gettext("Split was successful"
7881 			    ", but some datasets could not be mounted\n"));
7882 			(void) fprintf(stderr, gettext("Try doing '%s' with a "
7883 			    "different altroot\n"), "zpool import");
7884 		}
7885 	}
7886 	zpool_close(zhp);
7887 	nvlist_free(config);
7888 	nvlist_free(props);
7889 
7890 	return (ret);
7891 }
7892 
7893 
7894 /*
7895  * zpool online [--power] <pool> <device> ...
7896  *
7897  * --power: Power on the enclosure slot to the drive (if possible)
7898  */
7899 int
7900 zpool_do_online(int argc, char **argv)
7901 {
7902 	int c, i;
7903 	char *poolname;
7904 	zpool_handle_t *zhp;
7905 	int ret = 0;
7906 	vdev_state_t newstate;
7907 	int flags = 0;
7908 	boolean_t is_power_on = B_FALSE;
7909 	struct option long_options[] = {
7910 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
7911 		{0, 0, 0, 0}
7912 	};
7913 
7914 	/* check options */
7915 	while ((c = getopt_long(argc, argv, "e", long_options, NULL)) != -1) {
7916 		switch (c) {
7917 		case 'e':
7918 			flags |= ZFS_ONLINE_EXPAND;
7919 			break;
7920 		case ZPOOL_OPTION_POWER:
7921 			is_power_on = B_TRUE;
7922 			break;
7923 		case '?':
7924 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7925 			    optopt);
7926 			usage(B_FALSE);
7927 		}
7928 	}
7929 
7930 	if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
7931 		is_power_on = B_TRUE;
7932 
7933 	argc -= optind;
7934 	argv += optind;
7935 
7936 	/* get pool name and check number of arguments */
7937 	if (argc < 1) {
7938 		(void) fprintf(stderr, gettext("missing pool name\n"));
7939 		usage(B_FALSE);
7940 	}
7941 	if (argc < 2) {
7942 		(void) fprintf(stderr, gettext("missing device name\n"));
7943 		usage(B_FALSE);
7944 	}
7945 
7946 	poolname = argv[0];
7947 
7948 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7949 		return (1);
7950 
7951 	for (i = 1; i < argc; i++) {
7952 		vdev_state_t oldstate;
7953 		boolean_t avail_spare, l2cache;
7954 		int rc;
7955 
7956 		if (is_power_on) {
7957 			rc = zpool_power_on_and_disk_wait(zhp, argv[i]);
7958 			if (rc == ENOTSUP) {
7959 				(void) fprintf(stderr,
7960 				    gettext("Power control not supported\n"));
7961 			}
7962 			if (rc != 0)
7963 				return (rc);
7964 		}
7965 
7966 		nvlist_t *tgt = zpool_find_vdev(zhp, argv[i], &avail_spare,
7967 		    &l2cache, NULL);
7968 		if (tgt == NULL) {
7969 			ret = 1;
7970 			continue;
7971 		}
7972 		uint_t vsc;
7973 		oldstate = ((vdev_stat_t *)fnvlist_lookup_uint64_array(tgt,
7974 		    ZPOOL_CONFIG_VDEV_STATS, &vsc))->vs_state;
7975 		if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
7976 			if (newstate != VDEV_STATE_HEALTHY) {
7977 				(void) printf(gettext("warning: device '%s' "
7978 				    "onlined, but remains in faulted state\n"),
7979 				    argv[i]);
7980 				if (newstate == VDEV_STATE_FAULTED)
7981 					(void) printf(gettext("use 'zpool "
7982 					    "clear' to restore a faulted "
7983 					    "device\n"));
7984 				else
7985 					(void) printf(gettext("use 'zpool "
7986 					    "replace' to replace devices "
7987 					    "that are no longer present\n"));
7988 				if ((flags & ZFS_ONLINE_EXPAND)) {
7989 					(void) printf(gettext("%s: failed "
7990 					    "to expand usable space on "
7991 					    "unhealthy device '%s'\n"),
7992 					    (oldstate >= VDEV_STATE_DEGRADED ?
7993 					    "error" : "warning"), argv[i]);
7994 					if (oldstate >= VDEV_STATE_DEGRADED) {
7995 						ret = 1;
7996 						break;
7997 					}
7998 				}
7999 			}
8000 		} else {
8001 			ret = 1;
8002 		}
8003 	}
8004 
8005 	zpool_close(zhp);
8006 
8007 	return (ret);
8008 }
8009 
8010 /*
8011  * zpool offline [-ft]|[--power] <pool> <device> ...
8012  *
8013  *
8014  *	-f	Force the device into a faulted state.
8015  *
8016  *	-t	Only take the device off-line temporarily.  The offline/faulted
8017  *		state will not be persistent across reboots.
8018  *
8019  *	--power Power off the enclosure slot to the drive (if possible)
8020  */
8021 int
8022 zpool_do_offline(int argc, char **argv)
8023 {
8024 	int c, i;
8025 	char *poolname;
8026 	zpool_handle_t *zhp;
8027 	int ret = 0;
8028 	boolean_t istmp = B_FALSE;
8029 	boolean_t fault = B_FALSE;
8030 	boolean_t is_power_off = B_FALSE;
8031 
8032 	struct option long_options[] = {
8033 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8034 		{0, 0, 0, 0}
8035 	};
8036 
8037 	/* check options */
8038 	while ((c = getopt_long(argc, argv, "ft", long_options, NULL)) != -1) {
8039 		switch (c) {
8040 		case 'f':
8041 			fault = B_TRUE;
8042 			break;
8043 		case 't':
8044 			istmp = B_TRUE;
8045 			break;
8046 		case ZPOOL_OPTION_POWER:
8047 			is_power_off = B_TRUE;
8048 			break;
8049 		case '?':
8050 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8051 			    optopt);
8052 			usage(B_FALSE);
8053 		}
8054 	}
8055 
8056 	if (is_power_off && fault) {
8057 		(void) fprintf(stderr,
8058 		    gettext("-0 and -f cannot be used together\n"));
8059 		usage(B_FALSE);
8060 		return (1);
8061 	}
8062 
8063 	if (is_power_off && istmp) {
8064 		(void) fprintf(stderr,
8065 		    gettext("-0 and -t cannot be used together\n"));
8066 		usage(B_FALSE);
8067 		return (1);
8068 	}
8069 
8070 	argc -= optind;
8071 	argv += optind;
8072 
8073 	/* get pool name and check number of arguments */
8074 	if (argc < 1) {
8075 		(void) fprintf(stderr, gettext("missing pool name\n"));
8076 		usage(B_FALSE);
8077 	}
8078 	if (argc < 2) {
8079 		(void) fprintf(stderr, gettext("missing device name\n"));
8080 		usage(B_FALSE);
8081 	}
8082 
8083 	poolname = argv[0];
8084 
8085 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
8086 		return (1);
8087 
8088 	for (i = 1; i < argc; i++) {
8089 		uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
8090 		if (is_power_off) {
8091 			/*
8092 			 * Note: we have to power off first, then set REMOVED,
8093 			 * or else zpool_vdev_set_removed_state() returns
8094 			 * EAGAIN.
8095 			 */
8096 			ret = zpool_power_off(zhp, argv[i]);
8097 			if (ret != 0) {
8098 				(void) fprintf(stderr, "%s %s %d\n",
8099 				    gettext("unable to power off slot for"),
8100 				    argv[i], ret);
8101 			}
8102 			zpool_vdev_set_removed_state(zhp, guid, VDEV_AUX_NONE);
8103 
8104 		} else if (fault) {
8105 			vdev_aux_t aux;
8106 			if (istmp == B_FALSE) {
8107 				/* Force the fault to persist across imports */
8108 				aux = VDEV_AUX_EXTERNAL_PERSIST;
8109 			} else {
8110 				aux = VDEV_AUX_EXTERNAL;
8111 			}
8112 
8113 			if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
8114 				ret = 1;
8115 		} else {
8116 			if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
8117 				ret = 1;
8118 		}
8119 	}
8120 
8121 	zpool_close(zhp);
8122 
8123 	return (ret);
8124 }
8125 
8126 /*
8127  * zpool clear [-nF]|[--power] <pool> [device]
8128  *
8129  * Clear all errors associated with a pool or a particular device.
8130  */
8131 int
8132 zpool_do_clear(int argc, char **argv)
8133 {
8134 	int c;
8135 	int ret = 0;
8136 	boolean_t dryrun = B_FALSE;
8137 	boolean_t do_rewind = B_FALSE;
8138 	boolean_t xtreme_rewind = B_FALSE;
8139 	boolean_t is_power_on = B_FALSE;
8140 	uint32_t rewind_policy = ZPOOL_NO_REWIND;
8141 	nvlist_t *policy = NULL;
8142 	zpool_handle_t *zhp;
8143 	char *pool, *device;
8144 
8145 	struct option long_options[] = {
8146 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8147 		{0, 0, 0, 0}
8148 	};
8149 
8150 	/* check options */
8151 	while ((c = getopt_long(argc, argv, "FnX", long_options,
8152 	    NULL)) != -1) {
8153 		switch (c) {
8154 		case 'F':
8155 			do_rewind = B_TRUE;
8156 			break;
8157 		case 'n':
8158 			dryrun = B_TRUE;
8159 			break;
8160 		case 'X':
8161 			xtreme_rewind = B_TRUE;
8162 			break;
8163 		case ZPOOL_OPTION_POWER:
8164 			is_power_on = B_TRUE;
8165 			break;
8166 		case '?':
8167 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8168 			    optopt);
8169 			usage(B_FALSE);
8170 		}
8171 	}
8172 
8173 	if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8174 		is_power_on = B_TRUE;
8175 
8176 	argc -= optind;
8177 	argv += optind;
8178 
8179 	if (argc < 1) {
8180 		(void) fprintf(stderr, gettext("missing pool name\n"));
8181 		usage(B_FALSE);
8182 	}
8183 
8184 	if (argc > 2) {
8185 		(void) fprintf(stderr, gettext("too many arguments\n"));
8186 		usage(B_FALSE);
8187 	}
8188 
8189 	if ((dryrun || xtreme_rewind) && !do_rewind) {
8190 		(void) fprintf(stderr,
8191 		    gettext("-n or -X only meaningful with -F\n"));
8192 		usage(B_FALSE);
8193 	}
8194 	if (dryrun)
8195 		rewind_policy = ZPOOL_TRY_REWIND;
8196 	else if (do_rewind)
8197 		rewind_policy = ZPOOL_DO_REWIND;
8198 	if (xtreme_rewind)
8199 		rewind_policy |= ZPOOL_EXTREME_REWIND;
8200 
8201 	/* In future, further rewind policy choices can be passed along here */
8202 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
8203 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
8204 	    rewind_policy) != 0) {
8205 		return (1);
8206 	}
8207 
8208 	pool = argv[0];
8209 	device = argc == 2 ? argv[1] : NULL;
8210 
8211 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
8212 		nvlist_free(policy);
8213 		return (1);
8214 	}
8215 
8216 	if (is_power_on) {
8217 		if (device == NULL) {
8218 			zpool_power_on_pool_and_wait_for_devices(zhp);
8219 		} else {
8220 			zpool_power_on_and_disk_wait(zhp, device);
8221 		}
8222 	}
8223 
8224 	if (zpool_clear(zhp, device, policy) != 0)
8225 		ret = 1;
8226 
8227 	zpool_close(zhp);
8228 
8229 	nvlist_free(policy);
8230 
8231 	return (ret);
8232 }
8233 
8234 /*
8235  * zpool reguid <pool>
8236  */
8237 int
8238 zpool_do_reguid(int argc, char **argv)
8239 {
8240 	int c;
8241 	char *poolname;
8242 	zpool_handle_t *zhp;
8243 	int ret = 0;
8244 
8245 	/* check options */
8246 	while ((c = getopt(argc, argv, "")) != -1) {
8247 		switch (c) {
8248 		case '?':
8249 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8250 			    optopt);
8251 			usage(B_FALSE);
8252 		}
8253 	}
8254 
8255 	argc -= optind;
8256 	argv += optind;
8257 
8258 	/* get pool name and check number of arguments */
8259 	if (argc < 1) {
8260 		(void) fprintf(stderr, gettext("missing pool name\n"));
8261 		usage(B_FALSE);
8262 	}
8263 
8264 	if (argc > 1) {
8265 		(void) fprintf(stderr, gettext("too many arguments\n"));
8266 		usage(B_FALSE);
8267 	}
8268 
8269 	poolname = argv[0];
8270 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
8271 		return (1);
8272 
8273 	ret = zpool_reguid(zhp);
8274 
8275 	zpool_close(zhp);
8276 	return (ret);
8277 }
8278 
8279 
8280 /*
8281  * zpool reopen <pool>
8282  *
8283  * Reopen the pool so that the kernel can update the sizes of all vdevs.
8284  */
8285 int
8286 zpool_do_reopen(int argc, char **argv)
8287 {
8288 	int c;
8289 	int ret = 0;
8290 	boolean_t scrub_restart = B_TRUE;
8291 
8292 	/* check options */
8293 	while ((c = getopt(argc, argv, "n")) != -1) {
8294 		switch (c) {
8295 		case 'n':
8296 			scrub_restart = B_FALSE;
8297 			break;
8298 		case '?':
8299 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8300 			    optopt);
8301 			usage(B_FALSE);
8302 		}
8303 	}
8304 
8305 	argc -= optind;
8306 	argv += optind;
8307 
8308 	/* if argc == 0 we will execute zpool_reopen_one on all pools */
8309 	ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8310 	    B_FALSE, zpool_reopen_one, &scrub_restart);
8311 
8312 	return (ret);
8313 }
8314 
8315 typedef struct scrub_cbdata {
8316 	int	cb_type;
8317 	pool_scrub_cmd_t cb_scrub_cmd;
8318 } scrub_cbdata_t;
8319 
8320 static boolean_t
8321 zpool_has_checkpoint(zpool_handle_t *zhp)
8322 {
8323 	nvlist_t *config, *nvroot;
8324 
8325 	config = zpool_get_config(zhp, NULL);
8326 
8327 	if (config != NULL) {
8328 		pool_checkpoint_stat_t *pcs = NULL;
8329 		uint_t c;
8330 
8331 		nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
8332 		(void) nvlist_lookup_uint64_array(nvroot,
8333 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
8334 
8335 		if (pcs == NULL || pcs->pcs_state == CS_NONE)
8336 			return (B_FALSE);
8337 
8338 		assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
8339 		    pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
8340 		return (B_TRUE);
8341 	}
8342 
8343 	return (B_FALSE);
8344 }
8345 
8346 static int
8347 scrub_callback(zpool_handle_t *zhp, void *data)
8348 {
8349 	scrub_cbdata_t *cb = data;
8350 	int err;
8351 
8352 	/*
8353 	 * Ignore faulted pools.
8354 	 */
8355 	if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
8356 		(void) fprintf(stderr, gettext("cannot scan '%s': pool is "
8357 		    "currently unavailable\n"), zpool_get_name(zhp));
8358 		return (1);
8359 	}
8360 
8361 	err = zpool_scan(zhp, cb->cb_type, cb->cb_scrub_cmd);
8362 
8363 	if (err == 0 && zpool_has_checkpoint(zhp) &&
8364 	    cb->cb_type == POOL_SCAN_SCRUB) {
8365 		(void) printf(gettext("warning: will not scrub state that "
8366 		    "belongs to the checkpoint of pool '%s'\n"),
8367 		    zpool_get_name(zhp));
8368 	}
8369 
8370 	return (err != 0);
8371 }
8372 
8373 static int
8374 wait_callback(zpool_handle_t *zhp, void *data)
8375 {
8376 	zpool_wait_activity_t *act = data;
8377 	return (zpool_wait(zhp, *act));
8378 }
8379 
8380 /*
8381  * zpool scrub [-s | -p] [-w] [-e] <pool> ...
8382  *
8383  *	-e	Only scrub blocks in the error log.
8384  *	-s	Stop.  Stops any in-progress scrub.
8385  *	-p	Pause. Pause in-progress scrub.
8386  *	-w	Wait.  Blocks until scrub has completed.
8387  */
8388 int
8389 zpool_do_scrub(int argc, char **argv)
8390 {
8391 	int c;
8392 	scrub_cbdata_t cb;
8393 	boolean_t wait = B_FALSE;
8394 	int error;
8395 
8396 	cb.cb_type = POOL_SCAN_SCRUB;
8397 	cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8398 
8399 	boolean_t is_error_scrub = B_FALSE;
8400 	boolean_t is_pause = B_FALSE;
8401 	boolean_t is_stop = B_FALSE;
8402 
8403 	/* check options */
8404 	while ((c = getopt(argc, argv, "spwe")) != -1) {
8405 		switch (c) {
8406 		case 'e':
8407 			is_error_scrub = B_TRUE;
8408 			break;
8409 		case 's':
8410 			is_stop = B_TRUE;
8411 			break;
8412 		case 'p':
8413 			is_pause = B_TRUE;
8414 			break;
8415 		case 'w':
8416 			wait = B_TRUE;
8417 			break;
8418 		case '?':
8419 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8420 			    optopt);
8421 			usage(B_FALSE);
8422 		}
8423 	}
8424 
8425 	if (is_pause && is_stop) {
8426 		(void) fprintf(stderr, gettext("invalid option "
8427 		    "combination :-s and -p are mutually exclusive\n"));
8428 		usage(B_FALSE);
8429 	} else {
8430 		if (is_error_scrub)
8431 			cb.cb_type = POOL_SCAN_ERRORSCRUB;
8432 
8433 		if (is_pause) {
8434 			cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
8435 		} else if (is_stop) {
8436 			cb.cb_type = POOL_SCAN_NONE;
8437 		} else {
8438 			cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8439 		}
8440 	}
8441 
8442 	if (wait && (cb.cb_type == POOL_SCAN_NONE ||
8443 	    cb.cb_scrub_cmd == POOL_SCRUB_PAUSE)) {
8444 		(void) fprintf(stderr, gettext("invalid option combination: "
8445 		    "-w cannot be used with -p or -s\n"));
8446 		usage(B_FALSE);
8447 	}
8448 
8449 	argc -= optind;
8450 	argv += optind;
8451 
8452 	if (argc < 1) {
8453 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
8454 		usage(B_FALSE);
8455 	}
8456 
8457 	error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8458 	    B_FALSE, scrub_callback, &cb);
8459 
8460 	if (wait && !error) {
8461 		zpool_wait_activity_t act = ZPOOL_WAIT_SCRUB;
8462 		error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8463 		    B_FALSE, wait_callback, &act);
8464 	}
8465 
8466 	return (error);
8467 }
8468 
8469 /*
8470  * zpool resilver <pool> ...
8471  *
8472  *	Restarts any in-progress resilver
8473  */
8474 int
8475 zpool_do_resilver(int argc, char **argv)
8476 {
8477 	int c;
8478 	scrub_cbdata_t cb;
8479 
8480 	cb.cb_type = POOL_SCAN_RESILVER;
8481 	cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8482 
8483 	/* check options */
8484 	while ((c = getopt(argc, argv, "")) != -1) {
8485 		switch (c) {
8486 		case '?':
8487 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8488 			    optopt);
8489 			usage(B_FALSE);
8490 		}
8491 	}
8492 
8493 	argc -= optind;
8494 	argv += optind;
8495 
8496 	if (argc < 1) {
8497 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
8498 		usage(B_FALSE);
8499 	}
8500 
8501 	return (for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8502 	    B_FALSE, scrub_callback, &cb));
8503 }
8504 
8505 /*
8506  * zpool trim [-d] [-r <rate>] [-c | -s] <pool> [<device> ...]
8507  *
8508  *	-c		Cancel. Ends any in-progress trim.
8509  *	-d		Secure trim.  Requires kernel and device support.
8510  *	-r <rate>	Sets the TRIM rate in bytes (per second). Supports
8511  *			adding a multiplier suffix such as 'k' or 'm'.
8512  *	-s		Suspend. TRIM can then be restarted with no flags.
8513  *	-w		Wait. Blocks until trimming has completed.
8514  */
8515 int
8516 zpool_do_trim(int argc, char **argv)
8517 {
8518 	struct option long_options[] = {
8519 		{"cancel",	no_argument,		NULL,	'c'},
8520 		{"secure",	no_argument,		NULL,	'd'},
8521 		{"rate",	required_argument,	NULL,	'r'},
8522 		{"suspend",	no_argument,		NULL,	's'},
8523 		{"wait",	no_argument,		NULL,	'w'},
8524 		{0, 0, 0, 0}
8525 	};
8526 
8527 	pool_trim_func_t cmd_type = POOL_TRIM_START;
8528 	uint64_t rate = 0;
8529 	boolean_t secure = B_FALSE;
8530 	boolean_t wait = B_FALSE;
8531 
8532 	int c;
8533 	while ((c = getopt_long(argc, argv, "cdr:sw", long_options, NULL))
8534 	    != -1) {
8535 		switch (c) {
8536 		case 'c':
8537 			if (cmd_type != POOL_TRIM_START &&
8538 			    cmd_type != POOL_TRIM_CANCEL) {
8539 				(void) fprintf(stderr, gettext("-c cannot be "
8540 				    "combined with other options\n"));
8541 				usage(B_FALSE);
8542 			}
8543 			cmd_type = POOL_TRIM_CANCEL;
8544 			break;
8545 		case 'd':
8546 			if (cmd_type != POOL_TRIM_START) {
8547 				(void) fprintf(stderr, gettext("-d cannot be "
8548 				    "combined with the -c or -s options\n"));
8549 				usage(B_FALSE);
8550 			}
8551 			secure = B_TRUE;
8552 			break;
8553 		case 'r':
8554 			if (cmd_type != POOL_TRIM_START) {
8555 				(void) fprintf(stderr, gettext("-r cannot be "
8556 				    "combined with the -c or -s options\n"));
8557 				usage(B_FALSE);
8558 			}
8559 			if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
8560 				(void) fprintf(stderr, "%s: %s\n",
8561 				    gettext("invalid value for rate"),
8562 				    libzfs_error_description(g_zfs));
8563 				usage(B_FALSE);
8564 			}
8565 			break;
8566 		case 's':
8567 			if (cmd_type != POOL_TRIM_START &&
8568 			    cmd_type != POOL_TRIM_SUSPEND) {
8569 				(void) fprintf(stderr, gettext("-s cannot be "
8570 				    "combined with other options\n"));
8571 				usage(B_FALSE);
8572 			}
8573 			cmd_type = POOL_TRIM_SUSPEND;
8574 			break;
8575 		case 'w':
8576 			wait = B_TRUE;
8577 			break;
8578 		case '?':
8579 			if (optopt != 0) {
8580 				(void) fprintf(stderr,
8581 				    gettext("invalid option '%c'\n"), optopt);
8582 			} else {
8583 				(void) fprintf(stderr,
8584 				    gettext("invalid option '%s'\n"),
8585 				    argv[optind - 1]);
8586 			}
8587 			usage(B_FALSE);
8588 		}
8589 	}
8590 
8591 	argc -= optind;
8592 	argv += optind;
8593 
8594 	if (argc < 1) {
8595 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
8596 		usage(B_FALSE);
8597 		return (-1);
8598 	}
8599 
8600 	if (wait && (cmd_type != POOL_TRIM_START)) {
8601 		(void) fprintf(stderr, gettext("-w cannot be used with -c or "
8602 		    "-s\n"));
8603 		usage(B_FALSE);
8604 	}
8605 
8606 	char *poolname = argv[0];
8607 	zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8608 	if (zhp == NULL)
8609 		return (-1);
8610 
8611 	trimflags_t trim_flags = {
8612 		.secure = secure,
8613 		.rate = rate,
8614 		.wait = wait,
8615 	};
8616 
8617 	nvlist_t *vdevs = fnvlist_alloc();
8618 	if (argc == 1) {
8619 		/* no individual leaf vdevs specified, so add them all */
8620 		nvlist_t *config = zpool_get_config(zhp, NULL);
8621 		nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
8622 		    ZPOOL_CONFIG_VDEV_TREE);
8623 		zpool_collect_leaves(zhp, nvroot, vdevs);
8624 		trim_flags.fullpool = B_TRUE;
8625 	} else {
8626 		trim_flags.fullpool = B_FALSE;
8627 		for (int i = 1; i < argc; i++) {
8628 			fnvlist_add_boolean(vdevs, argv[i]);
8629 		}
8630 	}
8631 
8632 	int error = zpool_trim(zhp, cmd_type, vdevs, &trim_flags);
8633 
8634 	fnvlist_free(vdevs);
8635 	zpool_close(zhp);
8636 
8637 	return (error);
8638 }
8639 
8640 /*
8641  * Converts a total number of seconds to a human readable string broken
8642  * down in to days/hours/minutes/seconds.
8643  */
8644 static void
8645 secs_to_dhms(uint64_t total, char *buf)
8646 {
8647 	uint64_t days = total / 60 / 60 / 24;
8648 	uint64_t hours = (total / 60 / 60) % 24;
8649 	uint64_t mins = (total / 60) % 60;
8650 	uint64_t secs = (total % 60);
8651 
8652 	if (days > 0) {
8653 		(void) sprintf(buf, "%llu days %02llu:%02llu:%02llu",
8654 		    (u_longlong_t)days, (u_longlong_t)hours,
8655 		    (u_longlong_t)mins, (u_longlong_t)secs);
8656 	} else {
8657 		(void) sprintf(buf, "%02llu:%02llu:%02llu",
8658 		    (u_longlong_t)hours, (u_longlong_t)mins,
8659 		    (u_longlong_t)secs);
8660 	}
8661 }
8662 
8663 /*
8664  * Print out detailed error scrub status.
8665  */
8666 static void
8667 print_err_scrub_status(pool_scan_stat_t *ps)
8668 {
8669 	time_t start, end, pause;
8670 	uint64_t total_secs_left;
8671 	uint64_t secs_left, mins_left, hours_left, days_left;
8672 	uint64_t examined, to_be_examined;
8673 
8674 	if (ps == NULL || ps->pss_error_scrub_func != POOL_SCAN_ERRORSCRUB) {
8675 		return;
8676 	}
8677 
8678 	(void) printf(gettext(" scrub: "));
8679 
8680 	start = ps->pss_error_scrub_start;
8681 	end = ps->pss_error_scrub_end;
8682 	pause = ps->pss_pass_error_scrub_pause;
8683 	examined = ps->pss_error_scrub_examined;
8684 	to_be_examined = ps->pss_error_scrub_to_be_examined;
8685 
8686 	assert(ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB);
8687 
8688 	if (ps->pss_error_scrub_state == DSS_FINISHED) {
8689 		total_secs_left = end - start;
8690 		days_left = total_secs_left / 60 / 60 / 24;
8691 		hours_left = (total_secs_left / 60 / 60) % 24;
8692 		mins_left = (total_secs_left / 60) % 60;
8693 		secs_left = (total_secs_left % 60);
8694 
8695 		(void) printf(gettext("scrubbed %llu error blocks in %llu days "
8696 		    "%02llu:%02llu:%02llu on %s"), (u_longlong_t)examined,
8697 		    (u_longlong_t)days_left, (u_longlong_t)hours_left,
8698 		    (u_longlong_t)mins_left, (u_longlong_t)secs_left,
8699 		    ctime(&end));
8700 
8701 		return;
8702 	} else if (ps->pss_error_scrub_state == DSS_CANCELED) {
8703 		(void) printf(gettext("error scrub canceled on %s"),
8704 		    ctime(&end));
8705 		return;
8706 	}
8707 	assert(ps->pss_error_scrub_state == DSS_ERRORSCRUBBING);
8708 
8709 	/* Error scrub is in progress. */
8710 	if (pause == 0) {
8711 		(void) printf(gettext("error scrub in progress since %s"),
8712 		    ctime(&start));
8713 	} else {
8714 		(void) printf(gettext("error scrub paused since %s"),
8715 		    ctime(&pause));
8716 		(void) printf(gettext("\terror scrub started on %s"),
8717 		    ctime(&start));
8718 	}
8719 
8720 	double fraction_done = (double)examined / (to_be_examined + examined);
8721 	(void) printf(gettext("\t%.2f%% done, issued I/O for %llu error"
8722 	    " blocks"), 100 * fraction_done, (u_longlong_t)examined);
8723 
8724 	(void) printf("\n");
8725 }
8726 
8727 /*
8728  * Print out detailed scrub status.
8729  */
8730 static void
8731 print_scan_scrub_resilver_status(pool_scan_stat_t *ps)
8732 {
8733 	time_t start, end, pause;
8734 	uint64_t pass_scanned, scanned, pass_issued, issued, total_s, total_i;
8735 	uint64_t elapsed, scan_rate, issue_rate;
8736 	double fraction_done;
8737 	char processed_buf[7], scanned_buf[7], issued_buf[7], total_s_buf[7];
8738 	char total_i_buf[7], srate_buf[7], irate_buf[7], time_buf[32];
8739 
8740 	printf("  ");
8741 	printf_color(ANSI_BOLD, gettext("scan:"));
8742 	printf(" ");
8743 
8744 	/* If there's never been a scan, there's not much to say. */
8745 	if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
8746 	    ps->pss_func >= POOL_SCAN_FUNCS) {
8747 		(void) printf(gettext("none requested\n"));
8748 		return;
8749 	}
8750 
8751 	start = ps->pss_start_time;
8752 	end = ps->pss_end_time;
8753 	pause = ps->pss_pass_scrub_pause;
8754 
8755 	zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
8756 
8757 	int is_resilver = ps->pss_func == POOL_SCAN_RESILVER;
8758 	int is_scrub = ps->pss_func == POOL_SCAN_SCRUB;
8759 	assert(is_resilver || is_scrub);
8760 
8761 	/* Scan is finished or canceled. */
8762 	if (ps->pss_state == DSS_FINISHED) {
8763 		secs_to_dhms(end - start, time_buf);
8764 
8765 		if (is_scrub) {
8766 			(void) printf(gettext("scrub repaired %s "
8767 			    "in %s with %llu errors on %s"), processed_buf,
8768 			    time_buf, (u_longlong_t)ps->pss_errors,
8769 			    ctime(&end));
8770 		} else if (is_resilver) {
8771 			(void) printf(gettext("resilvered %s "
8772 			    "in %s with %llu errors on %s"), processed_buf,
8773 			    time_buf, (u_longlong_t)ps->pss_errors,
8774 			    ctime(&end));
8775 		}
8776 		return;
8777 	} else if (ps->pss_state == DSS_CANCELED) {
8778 		if (is_scrub) {
8779 			(void) printf(gettext("scrub canceled on %s"),
8780 			    ctime(&end));
8781 		} else if (is_resilver) {
8782 			(void) printf(gettext("resilver canceled on %s"),
8783 			    ctime(&end));
8784 		}
8785 		return;
8786 	}
8787 
8788 	assert(ps->pss_state == DSS_SCANNING);
8789 
8790 	/* Scan is in progress. Resilvers can't be paused. */
8791 	if (is_scrub) {
8792 		if (pause == 0) {
8793 			(void) printf(gettext("scrub in progress since %s"),
8794 			    ctime(&start));
8795 		} else {
8796 			(void) printf(gettext("scrub paused since %s"),
8797 			    ctime(&pause));
8798 			(void) printf(gettext("\tscrub started on %s"),
8799 			    ctime(&start));
8800 		}
8801 	} else if (is_resilver) {
8802 		(void) printf(gettext("resilver in progress since %s"),
8803 		    ctime(&start));
8804 	}
8805 
8806 	scanned = ps->pss_examined;
8807 	pass_scanned = ps->pss_pass_exam;
8808 	issued = ps->pss_issued;
8809 	pass_issued = ps->pss_pass_issued;
8810 	total_s = ps->pss_to_examine;
8811 	total_i = ps->pss_to_examine - ps->pss_skipped;
8812 
8813 	/* we are only done with a block once we have issued the IO for it */
8814 	fraction_done = (double)issued / total_i;
8815 
8816 	/* elapsed time for this pass, rounding up to 1 if it's 0 */
8817 	elapsed = time(NULL) - ps->pss_pass_start;
8818 	elapsed -= ps->pss_pass_scrub_spent_paused;
8819 	elapsed = (elapsed != 0) ? elapsed : 1;
8820 
8821 	scan_rate = pass_scanned / elapsed;
8822 	issue_rate = pass_issued / elapsed;
8823 
8824 	/* format all of the numbers we will be reporting */
8825 	zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
8826 	zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
8827 	zfs_nicebytes(total_s, total_s_buf, sizeof (total_s_buf));
8828 	zfs_nicebytes(total_i, total_i_buf, sizeof (total_i_buf));
8829 
8830 	/* do not print estimated time if we have a paused scrub */
8831 	(void) printf(gettext("\t%s / %s scanned"), scanned_buf, total_s_buf);
8832 	if (pause == 0 && scan_rate > 0) {
8833 		zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
8834 		(void) printf(gettext(" at %s/s"), srate_buf);
8835 	}
8836 	(void) printf(gettext(", %s / %s issued"), issued_buf, total_i_buf);
8837 	if (pause == 0 && issue_rate > 0) {
8838 		zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
8839 		(void) printf(gettext(" at %s/s"), irate_buf);
8840 	}
8841 	(void) printf(gettext("\n"));
8842 
8843 	if (is_resilver) {
8844 		(void) printf(gettext("\t%s resilvered, %.2f%% done"),
8845 		    processed_buf, 100 * fraction_done);
8846 	} else if (is_scrub) {
8847 		(void) printf(gettext("\t%s repaired, %.2f%% done"),
8848 		    processed_buf, 100 * fraction_done);
8849 	}
8850 
8851 	if (pause == 0) {
8852 		/*
8853 		 * Only provide an estimate iff:
8854 		 * 1) we haven't yet issued all we expected, and
8855 		 * 2) the issue rate exceeds 10 MB/s, and
8856 		 * 3) it's either:
8857 		 *    a) a resilver which has started repairs, or
8858 		 *    b) a scrub which has entered the issue phase.
8859 		 */
8860 		if (total_i >= issued && issue_rate >= 10 * 1024 * 1024 &&
8861 		    ((is_resilver && ps->pss_processed > 0) ||
8862 		    (is_scrub && issued > 0))) {
8863 			secs_to_dhms((total_i - issued) / issue_rate, time_buf);
8864 			(void) printf(gettext(", %s to go\n"), time_buf);
8865 		} else {
8866 			(void) printf(gettext(", no estimated "
8867 			    "completion time\n"));
8868 		}
8869 	} else {
8870 		(void) printf(gettext("\n"));
8871 	}
8872 }
8873 
8874 static void
8875 print_rebuild_status_impl(vdev_rebuild_stat_t *vrs, uint_t c, char *vdev_name)
8876 {
8877 	if (vrs == NULL || vrs->vrs_state == VDEV_REBUILD_NONE)
8878 		return;
8879 
8880 	printf("  ");
8881 	printf_color(ANSI_BOLD, gettext("scan:"));
8882 	printf(" ");
8883 
8884 	uint64_t bytes_scanned = vrs->vrs_bytes_scanned;
8885 	uint64_t bytes_issued = vrs->vrs_bytes_issued;
8886 	uint64_t bytes_rebuilt = vrs->vrs_bytes_rebuilt;
8887 	uint64_t bytes_est_s = vrs->vrs_bytes_est;
8888 	uint64_t bytes_est_i = vrs->vrs_bytes_est;
8889 	if (c > offsetof(vdev_rebuild_stat_t, vrs_pass_bytes_skipped) / 8)
8890 		bytes_est_i -= vrs->vrs_pass_bytes_skipped;
8891 	uint64_t scan_rate = (vrs->vrs_pass_bytes_scanned /
8892 	    (vrs->vrs_pass_time_ms + 1)) * 1000;
8893 	uint64_t issue_rate = (vrs->vrs_pass_bytes_issued /
8894 	    (vrs->vrs_pass_time_ms + 1)) * 1000;
8895 	double scan_pct = MIN((double)bytes_scanned * 100 /
8896 	    (bytes_est_s + 1), 100);
8897 
8898 	/* Format all of the numbers we will be reporting */
8899 	char bytes_scanned_buf[7], bytes_issued_buf[7];
8900 	char bytes_rebuilt_buf[7], bytes_est_s_buf[7], bytes_est_i_buf[7];
8901 	char scan_rate_buf[7], issue_rate_buf[7], time_buf[32];
8902 	zfs_nicebytes(bytes_scanned, bytes_scanned_buf,
8903 	    sizeof (bytes_scanned_buf));
8904 	zfs_nicebytes(bytes_issued, bytes_issued_buf,
8905 	    sizeof (bytes_issued_buf));
8906 	zfs_nicebytes(bytes_rebuilt, bytes_rebuilt_buf,
8907 	    sizeof (bytes_rebuilt_buf));
8908 	zfs_nicebytes(bytes_est_s, bytes_est_s_buf, sizeof (bytes_est_s_buf));
8909 	zfs_nicebytes(bytes_est_i, bytes_est_i_buf, sizeof (bytes_est_i_buf));
8910 
8911 	time_t start = vrs->vrs_start_time;
8912 	time_t end = vrs->vrs_end_time;
8913 
8914 	/* Rebuild is finished or canceled. */
8915 	if (vrs->vrs_state == VDEV_REBUILD_COMPLETE) {
8916 		secs_to_dhms(vrs->vrs_scan_time_ms / 1000, time_buf);
8917 		(void) printf(gettext("resilvered (%s) %s in %s "
8918 		    "with %llu errors on %s"), vdev_name, bytes_rebuilt_buf,
8919 		    time_buf, (u_longlong_t)vrs->vrs_errors, ctime(&end));
8920 		return;
8921 	} else if (vrs->vrs_state == VDEV_REBUILD_CANCELED) {
8922 		(void) printf(gettext("resilver (%s) canceled on %s"),
8923 		    vdev_name, ctime(&end));
8924 		return;
8925 	} else if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
8926 		(void) printf(gettext("resilver (%s) in progress since %s"),
8927 		    vdev_name, ctime(&start));
8928 	}
8929 
8930 	assert(vrs->vrs_state == VDEV_REBUILD_ACTIVE);
8931 
8932 	(void) printf(gettext("\t%s / %s scanned"), bytes_scanned_buf,
8933 	    bytes_est_s_buf);
8934 	if (scan_rate > 0) {
8935 		zfs_nicebytes(scan_rate, scan_rate_buf, sizeof (scan_rate_buf));
8936 		(void) printf(gettext(" at %s/s"), scan_rate_buf);
8937 	}
8938 	(void) printf(gettext(", %s / %s issued"), bytes_issued_buf,
8939 	    bytes_est_i_buf);
8940 	if (issue_rate > 0) {
8941 		zfs_nicebytes(issue_rate, issue_rate_buf,
8942 		    sizeof (issue_rate_buf));
8943 		(void) printf(gettext(" at %s/s"), issue_rate_buf);
8944 	}
8945 	(void) printf(gettext("\n"));
8946 
8947 	(void) printf(gettext("\t%s resilvered, %.2f%% done"),
8948 	    bytes_rebuilt_buf, scan_pct);
8949 
8950 	if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
8951 		if (bytes_est_s >= bytes_scanned &&
8952 		    scan_rate >= 10 * 1024 * 1024) {
8953 			secs_to_dhms((bytes_est_s - bytes_scanned) / scan_rate,
8954 			    time_buf);
8955 			(void) printf(gettext(", %s to go\n"), time_buf);
8956 		} else {
8957 			(void) printf(gettext(", no estimated "
8958 			    "completion time\n"));
8959 		}
8960 	} else {
8961 		(void) printf(gettext("\n"));
8962 	}
8963 }
8964 
8965 /*
8966  * Print rebuild status for top-level vdevs.
8967  */
8968 static void
8969 print_rebuild_status(zpool_handle_t *zhp, nvlist_t *nvroot)
8970 {
8971 	nvlist_t **child;
8972 	uint_t children;
8973 
8974 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
8975 	    &child, &children) != 0)
8976 		children = 0;
8977 
8978 	for (uint_t c = 0; c < children; c++) {
8979 		vdev_rebuild_stat_t *vrs;
8980 		uint_t i;
8981 
8982 		if (nvlist_lookup_uint64_array(child[c],
8983 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
8984 			char *name = zpool_vdev_name(g_zfs, zhp,
8985 			    child[c], VDEV_NAME_TYPE_ID);
8986 			print_rebuild_status_impl(vrs, i, name);
8987 			free(name);
8988 		}
8989 	}
8990 }
8991 
8992 /*
8993  * As we don't scrub checkpointed blocks, we want to warn the user that we
8994  * skipped scanning some blocks if a checkpoint exists or existed at any
8995  * time during the scan.  If a sequential instead of healing reconstruction
8996  * was performed then the blocks were reconstructed.  However, their checksums
8997  * have not been verified so we still print the warning.
8998  */
8999 static void
9000 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
9001 {
9002 	if (ps == NULL || pcs == NULL)
9003 		return;
9004 
9005 	if (pcs->pcs_state == CS_NONE ||
9006 	    pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
9007 		return;
9008 
9009 	assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
9010 
9011 	if (ps->pss_state == DSS_NONE)
9012 		return;
9013 
9014 	if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
9015 	    ps->pss_end_time < pcs->pcs_start_time)
9016 		return;
9017 
9018 	if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
9019 		(void) printf(gettext("    scan warning: skipped blocks "
9020 		    "that are only referenced by the checkpoint.\n"));
9021 	} else {
9022 		assert(ps->pss_state == DSS_SCANNING);
9023 		(void) printf(gettext("    scan warning: skipping blocks "
9024 		    "that are only referenced by the checkpoint.\n"));
9025 	}
9026 }
9027 
9028 /*
9029  * Returns B_TRUE if there is an active rebuild in progress.  Otherwise,
9030  * B_FALSE is returned and 'rebuild_end_time' is set to the end time for
9031  * the last completed (or cancelled) rebuild.
9032  */
9033 static boolean_t
9034 check_rebuilding(nvlist_t *nvroot, uint64_t *rebuild_end_time)
9035 {
9036 	nvlist_t **child;
9037 	uint_t children;
9038 	boolean_t rebuilding = B_FALSE;
9039 	uint64_t end_time = 0;
9040 
9041 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9042 	    &child, &children) != 0)
9043 		children = 0;
9044 
9045 	for (uint_t c = 0; c < children; c++) {
9046 		vdev_rebuild_stat_t *vrs;
9047 		uint_t i;
9048 
9049 		if (nvlist_lookup_uint64_array(child[c],
9050 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9051 
9052 			if (vrs->vrs_end_time > end_time)
9053 				end_time = vrs->vrs_end_time;
9054 
9055 			if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9056 				rebuilding = B_TRUE;
9057 				end_time = 0;
9058 				break;
9059 			}
9060 		}
9061 	}
9062 
9063 	if (rebuild_end_time != NULL)
9064 		*rebuild_end_time = end_time;
9065 
9066 	return (rebuilding);
9067 }
9068 
9069 static void
9070 vdev_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9071     int depth, boolean_t isspare, char *parent, nvlist_t *item)
9072 {
9073 	nvlist_t *vds, **child, *ch = NULL;
9074 	uint_t vsc, children;
9075 	vdev_stat_t *vs;
9076 	char *vname;
9077 	uint64_t notpresent;
9078 	const char *type, *path;
9079 
9080 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
9081 	    &child, &children) != 0)
9082 		children = 0;
9083 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
9084 	    (uint64_t **)&vs, &vsc) == 0);
9085 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
9086 	if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9087 		return;
9088 
9089 	if (cb->cb_print_unhealthy && depth > 0 &&
9090 	    for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
9091 		return;
9092 	}
9093 	vname = zpool_vdev_name(g_zfs, zhp, nv,
9094 	    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9095 	vds = fnvlist_alloc();
9096 	fill_vdev_info(vds, zhp, vname, B_FALSE, cb->cb_json_as_int);
9097 	if (cb->cb_flat_vdevs && parent != NULL) {
9098 		fnvlist_add_string(vds, "parent", parent);
9099 	}
9100 
9101 	if (isspare) {
9102 		if (vs->vs_aux == VDEV_AUX_SPARED) {
9103 			fnvlist_add_string(vds, "state", "INUSE");
9104 			used_by_other(zhp, nv, vds);
9105 		} else if (vs->vs_state == VDEV_STATE_HEALTHY)
9106 			fnvlist_add_string(vds, "state", "AVAIL");
9107 	} else {
9108 		if (vs->vs_alloc) {
9109 			nice_num_str_nvlist(vds, "alloc_space", vs->vs_alloc,
9110 			    cb->cb_literal, cb->cb_json_as_int,
9111 			    ZFS_NICENUM_BYTES);
9112 		}
9113 		if (vs->vs_space) {
9114 			nice_num_str_nvlist(vds, "total_space", vs->vs_space,
9115 			    cb->cb_literal, cb->cb_json_as_int,
9116 			    ZFS_NICENUM_BYTES);
9117 		}
9118 		if (vs->vs_dspace) {
9119 			nice_num_str_nvlist(vds, "def_space", vs->vs_dspace,
9120 			    cb->cb_literal, cb->cb_json_as_int,
9121 			    ZFS_NICENUM_BYTES);
9122 		}
9123 		if (vs->vs_rsize) {
9124 			nice_num_str_nvlist(vds, "rep_dev_size", vs->vs_rsize,
9125 			    cb->cb_literal, cb->cb_json_as_int,
9126 			    ZFS_NICENUM_BYTES);
9127 		}
9128 		if (vs->vs_esize) {
9129 			nice_num_str_nvlist(vds, "ex_dev_size", vs->vs_esize,
9130 			    cb->cb_literal, cb->cb_json_as_int,
9131 			    ZFS_NICENUM_BYTES);
9132 		}
9133 		if (vs->vs_self_healed) {
9134 			nice_num_str_nvlist(vds, "self_healed",
9135 			    vs->vs_self_healed, cb->cb_literal,
9136 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9137 		}
9138 		if (vs->vs_pspace) {
9139 			nice_num_str_nvlist(vds, "phys_space", vs->vs_pspace,
9140 			    cb->cb_literal, cb->cb_json_as_int,
9141 			    ZFS_NICENUM_BYTES);
9142 		}
9143 		nice_num_str_nvlist(vds, "read_errors", vs->vs_read_errors,
9144 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9145 		nice_num_str_nvlist(vds, "write_errors", vs->vs_write_errors,
9146 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9147 		nice_num_str_nvlist(vds, "checksum_errors",
9148 		    vs->vs_checksum_errors, cb->cb_literal,
9149 		    cb->cb_json_as_int, ZFS_NICENUM_1024);
9150 		if (vs->vs_scan_processed) {
9151 			nice_num_str_nvlist(vds, "scan_processed",
9152 			    vs->vs_scan_processed, cb->cb_literal,
9153 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9154 		}
9155 		if (vs->vs_checkpoint_space) {
9156 			nice_num_str_nvlist(vds, "checkpoint_space",
9157 			    vs->vs_checkpoint_space, cb->cb_literal,
9158 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9159 		}
9160 		if (vs->vs_resilver_deferred) {
9161 			nice_num_str_nvlist(vds, "resilver_deferred",
9162 			    vs->vs_resilver_deferred, B_TRUE,
9163 			    cb->cb_json_as_int, ZFS_NICENUM_1024);
9164 		}
9165 		if (children == 0) {
9166 			nice_num_str_nvlist(vds, "slow_ios", vs->vs_slow_ios,
9167 			    cb->cb_literal, cb->cb_json_as_int,
9168 			    ZFS_NICENUM_1024);
9169 		}
9170 		if (cb->cb_print_power) {
9171 			if (children == 0)  {
9172 				/* Only leaf vdevs have physical slots */
9173 				switch (zpool_power_current_state(zhp, (char *)
9174 				    fnvlist_lookup_string(nv,
9175 				    ZPOOL_CONFIG_PATH))) {
9176 				case 0:
9177 					fnvlist_add_string(vds, "power_state",
9178 					    "off");
9179 					break;
9180 				case 1:
9181 					fnvlist_add_string(vds, "power_state",
9182 					    "on");
9183 					break;
9184 				default:
9185 					fnvlist_add_string(vds, "power_state",
9186 					    "-");
9187 				}
9188 			} else {
9189 				fnvlist_add_string(vds, "power_state", "-");
9190 			}
9191 		}
9192 	}
9193 
9194 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
9195 	    &notpresent) == 0) {
9196 		nice_num_str_nvlist(vds, ZPOOL_CONFIG_NOT_PRESENT,
9197 		    1, B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9198 		fnvlist_add_string(vds, "was",
9199 		    fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH));
9200 	} else if (vs->vs_aux != VDEV_AUX_NONE) {
9201 		fnvlist_add_string(vds, "aux", vdev_aux_str[vs->vs_aux]);
9202 	} else if (children == 0 && !isspare &&
9203 	    getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
9204 	    VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
9205 	    vs->vs_configured_ashift < vs->vs_physical_ashift) {
9206 		nice_num_str_nvlist(vds, "configured_ashift",
9207 		    vs->vs_configured_ashift, B_TRUE, cb->cb_json_as_int,
9208 		    ZFS_NICENUM_1024);
9209 		nice_num_str_nvlist(vds, "physical_ashift",
9210 		    vs->vs_physical_ashift, B_TRUE, cb->cb_json_as_int,
9211 		    ZFS_NICENUM_1024);
9212 	}
9213 	if (vs->vs_scan_removing != 0) {
9214 		nice_num_str_nvlist(vds, "removing", vs->vs_scan_removing,
9215 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9216 	} else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
9217 		nice_num_str_nvlist(vds, "noalloc", vs->vs_noalloc,
9218 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9219 	}
9220 
9221 	if (cb->vcdl != NULL) {
9222 		if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
9223 			zpool_nvlist_cmd(cb->vcdl, zpool_get_name(zhp),
9224 			    path, vds);
9225 		}
9226 	}
9227 
9228 	if (children == 0) {
9229 		if (cb->cb_print_vdev_init) {
9230 			if (vs->vs_initialize_state != 0) {
9231 				uint64_t st = vs->vs_initialize_state;
9232 				fnvlist_add_string(vds, "init_state",
9233 				    vdev_init_state_str[st]);
9234 				nice_num_str_nvlist(vds, "initialized",
9235 				    vs->vs_initialize_bytes_done,
9236 				    cb->cb_literal, cb->cb_json_as_int,
9237 				    ZFS_NICENUM_BYTES);
9238 				nice_num_str_nvlist(vds, "to_initialize",
9239 				    vs->vs_initialize_bytes_est,
9240 				    cb->cb_literal, cb->cb_json_as_int,
9241 				    ZFS_NICENUM_BYTES);
9242 				nice_num_str_nvlist(vds, "init_time",
9243 				    vs->vs_initialize_action_time,
9244 				    cb->cb_literal, cb->cb_json_as_int,
9245 				    ZFS_NICE_TIMESTAMP);
9246 				nice_num_str_nvlist(vds, "init_errors",
9247 				    vs->vs_initialize_errors,
9248 				    cb->cb_literal, cb->cb_json_as_int,
9249 				    ZFS_NICENUM_1024);
9250 			} else {
9251 				fnvlist_add_string(vds, "init_state",
9252 				    "UNINITIALIZED");
9253 			}
9254 		}
9255 		if (cb->cb_print_vdev_trim) {
9256 			if (vs->vs_trim_notsup == 0) {
9257 					if (vs->vs_trim_state != 0) {
9258 					uint64_t st = vs->vs_trim_state;
9259 					fnvlist_add_string(vds, "trim_state",
9260 					    vdev_trim_state_str[st]);
9261 					nice_num_str_nvlist(vds, "trimmed",
9262 					    vs->vs_trim_bytes_done,
9263 					    cb->cb_literal, cb->cb_json_as_int,
9264 					    ZFS_NICENUM_BYTES);
9265 					nice_num_str_nvlist(vds, "to_trim",
9266 					    vs->vs_trim_bytes_est,
9267 					    cb->cb_literal, cb->cb_json_as_int,
9268 					    ZFS_NICENUM_BYTES);
9269 					nice_num_str_nvlist(vds, "trim_time",
9270 					    vs->vs_trim_action_time,
9271 					    cb->cb_literal, cb->cb_json_as_int,
9272 					    ZFS_NICE_TIMESTAMP);
9273 					nice_num_str_nvlist(vds, "trim_errors",
9274 					    vs->vs_trim_errors,
9275 					    cb->cb_literal, cb->cb_json_as_int,
9276 					    ZFS_NICENUM_1024);
9277 				} else
9278 					fnvlist_add_string(vds, "trim_state",
9279 					    "UNTRIMMED");
9280 			}
9281 			nice_num_str_nvlist(vds, "trim_notsup",
9282 			    vs->vs_trim_notsup, B_TRUE,
9283 			    cb->cb_json_as_int, ZFS_NICENUM_1024);
9284 		}
9285 	} else {
9286 		ch = fnvlist_alloc();
9287 	}
9288 
9289 	if (cb->cb_flat_vdevs && children == 0) {
9290 		fnvlist_add_nvlist(item, vname, vds);
9291 	}
9292 
9293 	for (int c = 0; c < children; c++) {
9294 		uint64_t islog = B_FALSE, ishole = B_FALSE;
9295 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9296 		    &islog);
9297 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
9298 		    &ishole);
9299 		if (islog || ishole)
9300 			continue;
9301 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
9302 			continue;
9303 		if (cb->cb_flat_vdevs) {
9304 			vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9305 			    vname, item);
9306 		}
9307 		vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9308 		    vname, ch);
9309 	}
9310 
9311 	if (ch != NULL) {
9312 		if (!nvlist_empty(ch))
9313 			fnvlist_add_nvlist(vds, "vdevs", ch);
9314 		fnvlist_free(ch);
9315 	}
9316 	fnvlist_add_nvlist(item, vname, vds);
9317 	fnvlist_free(vds);
9318 	free(vname);
9319 }
9320 
9321 static void
9322 class_vdevs_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9323     const char *class, nvlist_t *item)
9324 {
9325 	uint_t c, children;
9326 	nvlist_t **child;
9327 	nvlist_t *class_obj = NULL;
9328 
9329 	if (!cb->cb_flat_vdevs)
9330 		class_obj = fnvlist_alloc();
9331 
9332 	assert(zhp != NULL || !cb->cb_verbose);
9333 
9334 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
9335 	    &children) != 0)
9336 		return;
9337 
9338 	for (c = 0; c < children; c++) {
9339 		uint64_t is_log = B_FALSE;
9340 		const char *bias = NULL;
9341 		const char *type = NULL;
9342 		char *name = zpool_vdev_name(g_zfs, zhp, child[c],
9343 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9344 
9345 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9346 		    &is_log);
9347 
9348 		if (is_log) {
9349 			bias = (char *)VDEV_ALLOC_CLASS_LOGS;
9350 		} else {
9351 			(void) nvlist_lookup_string(child[c],
9352 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
9353 			(void) nvlist_lookup_string(child[c],
9354 			    ZPOOL_CONFIG_TYPE, &type);
9355 		}
9356 
9357 		if (bias == NULL || strcmp(bias, class) != 0)
9358 			continue;
9359 		if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9360 			continue;
9361 
9362 		if (cb->cb_flat_vdevs) {
9363 			vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9364 			    NULL, item);
9365 		} else {
9366 			vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9367 			    NULL, class_obj);
9368 		}
9369 		free(name);
9370 	}
9371 	if (!cb->cb_flat_vdevs) {
9372 		if (!nvlist_empty(class_obj))
9373 			fnvlist_add_nvlist(item, class, class_obj);
9374 		fnvlist_free(class_obj);
9375 	}
9376 }
9377 
9378 static void
9379 l2cache_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9380     nvlist_t *item)
9381 {
9382 	nvlist_t *l2c = NULL, **l2cache;
9383 	uint_t nl2cache;
9384 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
9385 	    &l2cache, &nl2cache) == 0) {
9386 		if (nl2cache == 0)
9387 			return;
9388 		if (!cb->cb_flat_vdevs)
9389 			l2c = fnvlist_alloc();
9390 		for (int i = 0; i < nl2cache; i++) {
9391 			if (cb->cb_flat_vdevs) {
9392 				vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9393 				    B_FALSE, NULL, item);
9394 			} else {
9395 				vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9396 				    B_FALSE, NULL, l2c);
9397 			}
9398 		}
9399 	}
9400 	if (!cb->cb_flat_vdevs) {
9401 		if (!nvlist_empty(l2c))
9402 			fnvlist_add_nvlist(item, "l2cache", l2c);
9403 		fnvlist_free(l2c);
9404 	}
9405 }
9406 
9407 static void
9408 spares_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9409     nvlist_t *item)
9410 {
9411 	nvlist_t *sp = NULL, **spares;
9412 	uint_t nspares;
9413 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
9414 	    &spares, &nspares) == 0) {
9415 		if (nspares == 0)
9416 			return;
9417 		if (!cb->cb_flat_vdevs)
9418 			sp = fnvlist_alloc();
9419 		for (int i = 0; i < nspares; i++) {
9420 			if (cb->cb_flat_vdevs) {
9421 				vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9422 				    NULL, item);
9423 			} else {
9424 				vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9425 				    NULL, sp);
9426 			}
9427 		}
9428 	}
9429 	if (!cb->cb_flat_vdevs) {
9430 		if (!nvlist_empty(sp))
9431 			fnvlist_add_nvlist(item, "spares", sp);
9432 		fnvlist_free(sp);
9433 	}
9434 }
9435 
9436 static void
9437 errors_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9438 {
9439 	uint64_t nerr;
9440 	nvlist_t *config = zpool_get_config(zhp, NULL);
9441 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
9442 	    &nerr) == 0) {
9443 		nice_num_str_nvlist(item, ZPOOL_CONFIG_ERRCOUNT, nerr,
9444 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9445 		if (nerr != 0 && cb->cb_verbose) {
9446 			nvlist_t *nverrlist = NULL;
9447 			if (zpool_get_errlog(zhp, &nverrlist) == 0) {
9448 				int i = 0;
9449 				int count = 0;
9450 				size_t len = MAXPATHLEN * 2;
9451 				nvpair_t *elem = NULL;
9452 
9453 				for (nvpair_t *pair =
9454 				    nvlist_next_nvpair(nverrlist, NULL);
9455 				    pair != NULL;
9456 				    pair = nvlist_next_nvpair(nverrlist, pair))
9457 					count++;
9458 				char **errl = (char **)malloc(
9459 				    count * sizeof (char *));
9460 
9461 				while ((elem = nvlist_next_nvpair(nverrlist,
9462 				    elem)) != NULL) {
9463 					nvlist_t *nv;
9464 					uint64_t dsobj, obj;
9465 
9466 					verify(nvpair_value_nvlist(elem,
9467 					    &nv) == 0);
9468 					verify(nvlist_lookup_uint64(nv,
9469 					    ZPOOL_ERR_DATASET, &dsobj) == 0);
9470 					verify(nvlist_lookup_uint64(nv,
9471 					    ZPOOL_ERR_OBJECT, &obj) == 0);
9472 					errl[i] = safe_malloc(len);
9473 					zpool_obj_to_path(zhp, dsobj, obj,
9474 					    errl[i++], len);
9475 				}
9476 				nvlist_free(nverrlist);
9477 				fnvlist_add_string_array(item, "errlist",
9478 				    (const char **)errl, count);
9479 				for (int i = 0; i < count; ++i)
9480 					free(errl[i]);
9481 				free(errl);
9482 			} else
9483 				fnvlist_add_string(item, "errlist",
9484 				    strerror(errno));
9485 		}
9486 	}
9487 }
9488 
9489 static void
9490 ddt_stats_nvlist(ddt_stat_t *dds, status_cbdata_t *cb, nvlist_t *item)
9491 {
9492 	nice_num_str_nvlist(item, "blocks", dds->dds_blocks,
9493 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9494 	nice_num_str_nvlist(item, "logical_size", dds->dds_lsize,
9495 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9496 	nice_num_str_nvlist(item, "physical_size", dds->dds_psize,
9497 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9498 	nice_num_str_nvlist(item, "deflated_size", dds->dds_dsize,
9499 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9500 	nice_num_str_nvlist(item, "ref_blocks", dds->dds_ref_blocks,
9501 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9502 	nice_num_str_nvlist(item, "ref_lsize", dds->dds_ref_lsize,
9503 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9504 	nice_num_str_nvlist(item, "ref_psize", dds->dds_ref_psize,
9505 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9506 	nice_num_str_nvlist(item, "ref_dsize", dds->dds_ref_dsize,
9507 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9508 }
9509 
9510 static void
9511 dedup_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9512 {
9513 	nvlist_t *config;
9514 	if (cb->cb_dedup_stats) {
9515 		ddt_histogram_t *ddh;
9516 		ddt_stat_t *dds;
9517 		ddt_object_t *ddo;
9518 		nvlist_t *ddt_stat, *ddt_obj, *dedup;
9519 		uint_t c;
9520 		uint64_t cspace_prop;
9521 
9522 		config = zpool_get_config(zhp, NULL);
9523 		if (nvlist_lookup_uint64_array(config,
9524 		    ZPOOL_CONFIG_DDT_OBJ_STATS, (uint64_t **)&ddo, &c) != 0)
9525 			return;
9526 
9527 		dedup = fnvlist_alloc();
9528 		ddt_obj = fnvlist_alloc();
9529 		nice_num_str_nvlist(dedup, "obj_count", ddo->ddo_count,
9530 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9531 		if (ddo->ddo_count == 0) {
9532 			fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
9533 			    ddt_obj);
9534 			fnvlist_add_nvlist(item, "dedup_stats", dedup);
9535 			fnvlist_free(ddt_obj);
9536 			fnvlist_free(dedup);
9537 			return;
9538 		} else {
9539 			nice_num_str_nvlist(dedup, "dspace", ddo->ddo_dspace,
9540 			    cb->cb_literal, cb->cb_json_as_int,
9541 			    ZFS_NICENUM_1024);
9542 			nice_num_str_nvlist(dedup, "mspace", ddo->ddo_mspace,
9543 			    cb->cb_literal, cb->cb_json_as_int,
9544 			    ZFS_NICENUM_1024);
9545 			/*
9546 			 * Squash cached size into in-core size to handle race.
9547 			 * Only include cached size if it is available.
9548 			 */
9549 			cspace_prop = zpool_get_prop_int(zhp,
9550 			    ZPOOL_PROP_DEDUPCACHED, NULL);
9551 			cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
9552 			nice_num_str_nvlist(dedup, "cspace", cspace_prop,
9553 			    cb->cb_literal, cb->cb_json_as_int,
9554 			    ZFS_NICENUM_1024);
9555 		}
9556 
9557 		ddt_stat = fnvlist_alloc();
9558 		if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
9559 		    (uint64_t **)&dds, &c) == 0) {
9560 			nvlist_t *total = fnvlist_alloc();
9561 			if (dds->dds_blocks == 0)
9562 				fnvlist_add_string(total, "blocks", "0");
9563 			else
9564 				ddt_stats_nvlist(dds, cb, total);
9565 			fnvlist_add_nvlist(ddt_stat, "total", total);
9566 			fnvlist_free(total);
9567 		}
9568 		if (nvlist_lookup_uint64_array(config,
9569 		    ZPOOL_CONFIG_DDT_HISTOGRAM, (uint64_t **)&ddh, &c) == 0) {
9570 			nvlist_t *hist = fnvlist_alloc();
9571 			nvlist_t *entry = NULL;
9572 			char buf[16];
9573 			for (int h = 0; h < 64; h++) {
9574 				if (ddh->ddh_stat[h].dds_blocks != 0) {
9575 					entry = fnvlist_alloc();
9576 					ddt_stats_nvlist(&ddh->ddh_stat[h], cb,
9577 					    entry);
9578 					snprintf(buf, 16, "%d", h);
9579 					fnvlist_add_nvlist(hist, buf, entry);
9580 					fnvlist_free(entry);
9581 				}
9582 			}
9583 			if (!nvlist_empty(hist))
9584 				fnvlist_add_nvlist(ddt_stat, "histogram", hist);
9585 			fnvlist_free(hist);
9586 		}
9587 
9588 		if (!nvlist_empty(ddt_obj)) {
9589 			fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
9590 			    ddt_obj);
9591 		}
9592 		fnvlist_free(ddt_obj);
9593 		if (!nvlist_empty(ddt_stat)) {
9594 			fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_STATS,
9595 			    ddt_stat);
9596 		}
9597 		fnvlist_free(ddt_stat);
9598 		if (!nvlist_empty(dedup))
9599 			fnvlist_add_nvlist(item, "dedup_stats", dedup);
9600 		fnvlist_free(dedup);
9601 	}
9602 }
9603 
9604 static void
9605 raidz_expand_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
9606     nvlist_t *nvroot, nvlist_t *item)
9607 {
9608 	uint_t c;
9609 	pool_raidz_expand_stat_t *pres = NULL;
9610 	if (nvlist_lookup_uint64_array(nvroot,
9611 	    ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c) == 0) {
9612 		nvlist_t **child;
9613 		uint_t children;
9614 		nvlist_t *nv = fnvlist_alloc();
9615 		verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9616 		    &child, &children) == 0);
9617 		assert(pres->pres_expanding_vdev < children);
9618 		char *name =
9619 		    zpool_vdev_name(g_zfs, zhp,
9620 		    child[pres->pres_expanding_vdev], 0);
9621 		fill_vdev_info(nv, zhp, name, B_FALSE, cb->cb_json_as_int);
9622 		fnvlist_add_string(nv, "state",
9623 		    pool_scan_state_str[pres->pres_state]);
9624 		nice_num_str_nvlist(nv, "expanding_vdev",
9625 		    pres->pres_expanding_vdev, B_TRUE, cb->cb_json_as_int,
9626 		    ZFS_NICENUM_1024);
9627 		nice_num_str_nvlist(nv, "start_time", pres->pres_start_time,
9628 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9629 		nice_num_str_nvlist(nv, "end_time", pres->pres_end_time,
9630 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9631 		nice_num_str_nvlist(nv, "to_reflow", pres->pres_to_reflow,
9632 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9633 		nice_num_str_nvlist(nv, "reflowed", pres->pres_reflowed,
9634 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9635 		nice_num_str_nvlist(nv, "waiting_for_resilver",
9636 		    pres->pres_waiting_for_resilver, B_TRUE,
9637 		    cb->cb_json_as_int, ZFS_NICENUM_1024);
9638 		fnvlist_add_nvlist(item, ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, nv);
9639 		fnvlist_free(nv);
9640 		free(name);
9641 	}
9642 }
9643 
9644 static void
9645 checkpoint_status_nvlist(nvlist_t *nvroot, status_cbdata_t *cb,
9646     nvlist_t *item)
9647 {
9648 	uint_t c;
9649 	pool_checkpoint_stat_t *pcs = NULL;
9650 	if (nvlist_lookup_uint64_array(nvroot,
9651 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c) == 0) {
9652 		nvlist_t *nv = fnvlist_alloc();
9653 		fnvlist_add_string(nv, "state",
9654 		    checkpoint_state_str[pcs->pcs_state]);
9655 		nice_num_str_nvlist(nv, "start_time",
9656 		    pcs->pcs_start_time, cb->cb_literal, cb->cb_json_as_int,
9657 		    ZFS_NICE_TIMESTAMP);
9658 		nice_num_str_nvlist(nv, "space",
9659 		    pcs->pcs_space, cb->cb_literal, cb->cb_json_as_int,
9660 		    ZFS_NICENUM_BYTES);
9661 		fnvlist_add_nvlist(item, ZPOOL_CONFIG_CHECKPOINT_STATS, nv);
9662 		fnvlist_free(nv);
9663 	}
9664 }
9665 
9666 static void
9667 removal_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
9668     nvlist_t *nvroot, nvlist_t *item)
9669 {
9670 	uint_t c;
9671 	pool_removal_stat_t *prs = NULL;
9672 	if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_REMOVAL_STATS,
9673 	    (uint64_t **)&prs, &c) == 0) {
9674 		if (prs->prs_state != DSS_NONE) {
9675 			nvlist_t **child;
9676 			uint_t children;
9677 			verify(nvlist_lookup_nvlist_array(nvroot,
9678 			    ZPOOL_CONFIG_CHILDREN, &child, &children) == 0);
9679 			assert(prs->prs_removing_vdev < children);
9680 			char *vdev_name = zpool_vdev_name(g_zfs, zhp,
9681 			    child[prs->prs_removing_vdev], B_TRUE);
9682 			nvlist_t *nv = fnvlist_alloc();
9683 			fill_vdev_info(nv, zhp, vdev_name, B_FALSE,
9684 			    cb->cb_json_as_int);
9685 			fnvlist_add_string(nv, "state",
9686 			    pool_scan_state_str[prs->prs_state]);
9687 			nice_num_str_nvlist(nv, "removing_vdev",
9688 			    prs->prs_removing_vdev, B_TRUE, cb->cb_json_as_int,
9689 			    ZFS_NICENUM_1024);
9690 			nice_num_str_nvlist(nv, "start_time",
9691 			    prs->prs_start_time, cb->cb_literal,
9692 			    cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9693 			nice_num_str_nvlist(nv, "end_time", prs->prs_end_time,
9694 			    cb->cb_literal, cb->cb_json_as_int,
9695 			    ZFS_NICE_TIMESTAMP);
9696 			nice_num_str_nvlist(nv, "to_copy", prs->prs_to_copy,
9697 			    cb->cb_literal, cb->cb_json_as_int,
9698 			    ZFS_NICENUM_BYTES);
9699 			nice_num_str_nvlist(nv, "copied", prs->prs_copied,
9700 			    cb->cb_literal, cb->cb_json_as_int,
9701 			    ZFS_NICENUM_BYTES);
9702 			nice_num_str_nvlist(nv, "mapping_memory",
9703 			    prs->prs_mapping_memory, cb->cb_literal,
9704 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9705 			fnvlist_add_nvlist(item,
9706 			    ZPOOL_CONFIG_REMOVAL_STATS, nv);
9707 			fnvlist_free(nv);
9708 			free(vdev_name);
9709 		}
9710 	}
9711 }
9712 
9713 static void
9714 scan_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
9715     nvlist_t *nvroot, nvlist_t *item)
9716 {
9717 	pool_scan_stat_t *ps = NULL;
9718 	uint_t c;
9719 	nvlist_t *scan = fnvlist_alloc();
9720 	nvlist_t **child;
9721 	uint_t children;
9722 
9723 	if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
9724 	    (uint64_t **)&ps, &c) == 0) {
9725 		fnvlist_add_string(scan, "function",
9726 		    pool_scan_func_str[ps->pss_func]);
9727 		fnvlist_add_string(scan, "state",
9728 		    pool_scan_state_str[ps->pss_state]);
9729 		nice_num_str_nvlist(scan, "start_time", ps->pss_start_time,
9730 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9731 		nice_num_str_nvlist(scan, "end_time", ps->pss_end_time,
9732 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9733 		nice_num_str_nvlist(scan, "to_examine", ps->pss_to_examine,
9734 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9735 		nice_num_str_nvlist(scan, "examined", ps->pss_examined,
9736 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9737 		nice_num_str_nvlist(scan, "skipped", ps->pss_skipped,
9738 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9739 		nice_num_str_nvlist(scan, "processed", ps->pss_processed,
9740 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9741 		nice_num_str_nvlist(scan, "errors", ps->pss_errors,
9742 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9743 		nice_num_str_nvlist(scan, "bytes_per_scan", ps->pss_pass_exam,
9744 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9745 		nice_num_str_nvlist(scan, "pass_start", ps->pss_pass_start,
9746 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9747 		nice_num_str_nvlist(scan, "scrub_pause",
9748 		    ps->pss_pass_scrub_pause, cb->cb_literal,
9749 		    cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9750 		nice_num_str_nvlist(scan, "scrub_spent_paused",
9751 		    ps->pss_pass_scrub_spent_paused,
9752 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9753 		nice_num_str_nvlist(scan, "issued_bytes_per_scan",
9754 		    ps->pss_pass_issued, cb->cb_literal,
9755 		    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9756 		nice_num_str_nvlist(scan, "issued", ps->pss_issued,
9757 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9758 		if (ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB &&
9759 		    ps->pss_error_scrub_start > ps->pss_start_time) {
9760 			fnvlist_add_string(scan, "err_scrub_func",
9761 			    pool_scan_func_str[ps->pss_error_scrub_func]);
9762 			fnvlist_add_string(scan, "err_scrub_state",
9763 			    pool_scan_state_str[ps->pss_error_scrub_state]);
9764 			nice_num_str_nvlist(scan, "err_scrub_start_time",
9765 			    ps->pss_error_scrub_start,
9766 			    cb->cb_literal, cb->cb_json_as_int,
9767 			    ZFS_NICE_TIMESTAMP);
9768 			nice_num_str_nvlist(scan, "err_scrub_end_time",
9769 			    ps->pss_error_scrub_end,
9770 			    cb->cb_literal, cb->cb_json_as_int,
9771 			    ZFS_NICE_TIMESTAMP);
9772 			nice_num_str_nvlist(scan, "err_scrub_examined",
9773 			    ps->pss_error_scrub_examined,
9774 			    cb->cb_literal, cb->cb_json_as_int,
9775 			    ZFS_NICENUM_1024);
9776 			nice_num_str_nvlist(scan, "err_scrub_to_examine",
9777 			    ps->pss_error_scrub_to_be_examined,
9778 			    cb->cb_literal, cb->cb_json_as_int,
9779 			    ZFS_NICENUM_1024);
9780 			nice_num_str_nvlist(scan, "err_scrub_pause",
9781 			    ps->pss_pass_error_scrub_pause,
9782 			    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9783 		}
9784 	}
9785 
9786 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9787 	    &child, &children) == 0) {
9788 		vdev_rebuild_stat_t *vrs;
9789 		uint_t i;
9790 		char *name;
9791 		nvlist_t *nv;
9792 		nvlist_t *rebuild = fnvlist_alloc();
9793 		uint64_t st;
9794 		for (uint_t c = 0; c < children; c++) {
9795 			if (nvlist_lookup_uint64_array(child[c],
9796 			    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs,
9797 			    &i) == 0) {
9798 				if (vrs->vrs_state != VDEV_REBUILD_NONE) {
9799 					nv = fnvlist_alloc();
9800 					name = zpool_vdev_name(g_zfs, zhp,
9801 					    child[c], VDEV_NAME_TYPE_ID);
9802 					fill_vdev_info(nv, zhp, name, B_FALSE,
9803 					    cb->cb_json_as_int);
9804 					st = vrs->vrs_state;
9805 					fnvlist_add_string(nv, "state",
9806 					    vdev_rebuild_state_str[st]);
9807 					nice_num_str_nvlist(nv, "start_time",
9808 					    vrs->vrs_start_time, cb->cb_literal,
9809 					    cb->cb_json_as_int,
9810 					    ZFS_NICE_TIMESTAMP);
9811 					nice_num_str_nvlist(nv, "end_time",
9812 					    vrs->vrs_end_time, cb->cb_literal,
9813 					    cb->cb_json_as_int,
9814 					    ZFS_NICE_TIMESTAMP);
9815 					nice_num_str_nvlist(nv, "scan_time",
9816 					    vrs->vrs_scan_time_ms * 1000000,
9817 					    cb->cb_literal, cb->cb_json_as_int,
9818 					    ZFS_NICENUM_TIME);
9819 					nice_num_str_nvlist(nv, "scanned",
9820 					    vrs->vrs_bytes_scanned,
9821 					    cb->cb_literal, cb->cb_json_as_int,
9822 					    ZFS_NICENUM_BYTES);
9823 					nice_num_str_nvlist(nv, "issued",
9824 					    vrs->vrs_bytes_issued,
9825 					    cb->cb_literal, cb->cb_json_as_int,
9826 					    ZFS_NICENUM_BYTES);
9827 					nice_num_str_nvlist(nv, "rebuilt",
9828 					    vrs->vrs_bytes_rebuilt,
9829 					    cb->cb_literal, cb->cb_json_as_int,
9830 					    ZFS_NICENUM_BYTES);
9831 					nice_num_str_nvlist(nv, "to_scan",
9832 					    vrs->vrs_bytes_est, cb->cb_literal,
9833 					    cb->cb_json_as_int,
9834 					    ZFS_NICENUM_BYTES);
9835 					nice_num_str_nvlist(nv, "errors",
9836 					    vrs->vrs_errors, cb->cb_literal,
9837 					    cb->cb_json_as_int,
9838 					    ZFS_NICENUM_1024);
9839 					nice_num_str_nvlist(nv, "pass_time",
9840 					    vrs->vrs_pass_time_ms * 1000000,
9841 					    cb->cb_literal, cb->cb_json_as_int,
9842 					    ZFS_NICENUM_TIME);
9843 					nice_num_str_nvlist(nv, "pass_scanned",
9844 					    vrs->vrs_pass_bytes_scanned,
9845 					    cb->cb_literal, cb->cb_json_as_int,
9846 					    ZFS_NICENUM_BYTES);
9847 					nice_num_str_nvlist(nv, "pass_issued",
9848 					    vrs->vrs_pass_bytes_issued,
9849 					    cb->cb_literal, cb->cb_json_as_int,
9850 					    ZFS_NICENUM_BYTES);
9851 					nice_num_str_nvlist(nv, "pass_skipped",
9852 					    vrs->vrs_pass_bytes_skipped,
9853 					    cb->cb_literal, cb->cb_json_as_int,
9854 					    ZFS_NICENUM_BYTES);
9855 					fnvlist_add_nvlist(rebuild, name, nv);
9856 					free(name);
9857 				}
9858 			}
9859 		}
9860 		if (!nvlist_empty(rebuild))
9861 			fnvlist_add_nvlist(scan, "rebuild_stats", rebuild);
9862 		fnvlist_free(rebuild);
9863 	}
9864 
9865 	if (!nvlist_empty(scan))
9866 		fnvlist_add_nvlist(item, ZPOOL_CONFIG_SCAN_STATS, scan);
9867 	fnvlist_free(scan);
9868 }
9869 
9870 /*
9871  * Print the scan status.
9872  */
9873 static void
9874 print_scan_status(zpool_handle_t *zhp, nvlist_t *nvroot)
9875 {
9876 	uint64_t rebuild_end_time = 0, resilver_end_time = 0;
9877 	boolean_t have_resilver = B_FALSE, have_scrub = B_FALSE;
9878 	boolean_t have_errorscrub = B_FALSE;
9879 	boolean_t active_resilver = B_FALSE;
9880 	pool_checkpoint_stat_t *pcs = NULL;
9881 	pool_scan_stat_t *ps = NULL;
9882 	uint_t c;
9883 	time_t scrub_start = 0, errorscrub_start = 0;
9884 
9885 	if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
9886 	    (uint64_t **)&ps, &c) == 0) {
9887 		if (ps->pss_func == POOL_SCAN_RESILVER) {
9888 			resilver_end_time = ps->pss_end_time;
9889 			active_resilver = (ps->pss_state == DSS_SCANNING);
9890 		}
9891 
9892 		have_resilver = (ps->pss_func == POOL_SCAN_RESILVER);
9893 		have_scrub = (ps->pss_func == POOL_SCAN_SCRUB);
9894 		scrub_start = ps->pss_start_time;
9895 		if (c > offsetof(pool_scan_stat_t,
9896 		    pss_pass_error_scrub_pause) / 8) {
9897 			have_errorscrub = (ps->pss_error_scrub_func ==
9898 			    POOL_SCAN_ERRORSCRUB);
9899 			errorscrub_start = ps->pss_error_scrub_start;
9900 		}
9901 	}
9902 
9903 	boolean_t active_rebuild = check_rebuilding(nvroot, &rebuild_end_time);
9904 	boolean_t have_rebuild = (active_rebuild || (rebuild_end_time > 0));
9905 
9906 	/* Always print the scrub status when available. */
9907 	if (have_scrub && scrub_start > errorscrub_start)
9908 		print_scan_scrub_resilver_status(ps);
9909 	else if (have_errorscrub && errorscrub_start >= scrub_start)
9910 		print_err_scrub_status(ps);
9911 
9912 	/*
9913 	 * When there is an active resilver or rebuild print its status.
9914 	 * Otherwise print the status of the last resilver or rebuild.
9915 	 */
9916 	if (active_resilver || (!active_rebuild && have_resilver &&
9917 	    resilver_end_time && resilver_end_time > rebuild_end_time)) {
9918 		print_scan_scrub_resilver_status(ps);
9919 	} else if (active_rebuild || (!active_resilver && have_rebuild &&
9920 	    rebuild_end_time && rebuild_end_time > resilver_end_time)) {
9921 		print_rebuild_status(zhp, nvroot);
9922 	}
9923 
9924 	(void) nvlist_lookup_uint64_array(nvroot,
9925 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
9926 	print_checkpoint_scan_warning(ps, pcs);
9927 }
9928 
9929 /*
9930  * Print out detailed removal status.
9931  */
9932 static void
9933 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
9934 {
9935 	char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
9936 	time_t start, end;
9937 	nvlist_t *config, *nvroot;
9938 	nvlist_t **child;
9939 	uint_t children;
9940 	char *vdev_name;
9941 
9942 	if (prs == NULL || prs->prs_state == DSS_NONE)
9943 		return;
9944 
9945 	/*
9946 	 * Determine name of vdev.
9947 	 */
9948 	config = zpool_get_config(zhp, NULL);
9949 	nvroot = fnvlist_lookup_nvlist(config,
9950 	    ZPOOL_CONFIG_VDEV_TREE);
9951 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9952 	    &child, &children) == 0);
9953 	assert(prs->prs_removing_vdev < children);
9954 	vdev_name = zpool_vdev_name(g_zfs, zhp,
9955 	    child[prs->prs_removing_vdev], B_TRUE);
9956 
9957 	printf_color(ANSI_BOLD, gettext("remove: "));
9958 
9959 	start = prs->prs_start_time;
9960 	end = prs->prs_end_time;
9961 	zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
9962 
9963 	/*
9964 	 * Removal is finished or canceled.
9965 	 */
9966 	if (prs->prs_state == DSS_FINISHED) {
9967 		uint64_t minutes_taken = (end - start) / 60;
9968 
9969 		(void) printf(gettext("Removal of vdev %llu copied %s "
9970 		    "in %lluh%um, completed on %s"),
9971 		    (longlong_t)prs->prs_removing_vdev,
9972 		    copied_buf,
9973 		    (u_longlong_t)(minutes_taken / 60),
9974 		    (uint_t)(minutes_taken % 60),
9975 		    ctime((time_t *)&end));
9976 	} else if (prs->prs_state == DSS_CANCELED) {
9977 		(void) printf(gettext("Removal of %s canceled on %s"),
9978 		    vdev_name, ctime(&end));
9979 	} else {
9980 		uint64_t copied, total, elapsed, mins_left, hours_left;
9981 		double fraction_done;
9982 		uint_t rate;
9983 
9984 		assert(prs->prs_state == DSS_SCANNING);
9985 
9986 		/*
9987 		 * Removal is in progress.
9988 		 */
9989 		(void) printf(gettext(
9990 		    "Evacuation of %s in progress since %s"),
9991 		    vdev_name, ctime(&start));
9992 
9993 		copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
9994 		total = prs->prs_to_copy;
9995 		fraction_done = (double)copied / total;
9996 
9997 		/* elapsed time for this pass */
9998 		elapsed = time(NULL) - prs->prs_start_time;
9999 		elapsed = elapsed > 0 ? elapsed : 1;
10000 		rate = copied / elapsed;
10001 		rate = rate > 0 ? rate : 1;
10002 		mins_left = ((total - copied) / rate) / 60;
10003 		hours_left = mins_left / 60;
10004 
10005 		zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10006 		zfs_nicenum(total, total_buf, sizeof (total_buf));
10007 		zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10008 
10009 		/*
10010 		 * do not print estimated time if hours_left is more than
10011 		 * 30 days
10012 		 */
10013 		(void) printf(gettext(
10014 		    "\t%s copied out of %s at %s/s, %.2f%% done"),
10015 		    examined_buf, total_buf, rate_buf, 100 * fraction_done);
10016 		if (hours_left < (30 * 24)) {
10017 			(void) printf(gettext(", %lluh%um to go\n"),
10018 			    (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
10019 		} else {
10020 			(void) printf(gettext(
10021 			    ", (copy is slow, no estimated time)\n"));
10022 		}
10023 	}
10024 	free(vdev_name);
10025 
10026 	if (prs->prs_mapping_memory > 0) {
10027 		char mem_buf[7];
10028 		zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
10029 		(void) printf(gettext(
10030 		    "\t%s memory used for removed device mappings\n"),
10031 		    mem_buf);
10032 	}
10033 }
10034 
10035 /*
10036  * Print out detailed raidz expansion status.
10037  */
10038 static void
10039 print_raidz_expand_status(zpool_handle_t *zhp, pool_raidz_expand_stat_t *pres)
10040 {
10041 	char copied_buf[7];
10042 
10043 	if (pres == NULL || pres->pres_state == DSS_NONE)
10044 		return;
10045 
10046 	/*
10047 	 * Determine name of vdev.
10048 	 */
10049 	nvlist_t *config = zpool_get_config(zhp, NULL);
10050 	nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
10051 	    ZPOOL_CONFIG_VDEV_TREE);
10052 	nvlist_t **child;
10053 	uint_t children;
10054 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10055 	    &child, &children) == 0);
10056 	assert(pres->pres_expanding_vdev < children);
10057 
10058 	printf_color(ANSI_BOLD, gettext("expand: "));
10059 
10060 	time_t start = pres->pres_start_time;
10061 	time_t end = pres->pres_end_time;
10062 	char *vname =
10063 	    zpool_vdev_name(g_zfs, zhp, child[pres->pres_expanding_vdev], 0);
10064 	zfs_nicenum(pres->pres_reflowed, copied_buf, sizeof (copied_buf));
10065 
10066 	/*
10067 	 * Expansion is finished or canceled.
10068 	 */
10069 	if (pres->pres_state == DSS_FINISHED) {
10070 		char time_buf[32];
10071 		secs_to_dhms(end - start, time_buf);
10072 
10073 		(void) printf(gettext("expanded %s-%u copied %s in %s, "
10074 		    "on %s"), vname, (int)pres->pres_expanding_vdev,
10075 		    copied_buf, time_buf, ctime((time_t *)&end));
10076 	} else {
10077 		char examined_buf[7], total_buf[7], rate_buf[7];
10078 		uint64_t copied, total, elapsed, secs_left;
10079 		double fraction_done;
10080 		uint_t rate;
10081 
10082 		assert(pres->pres_state == DSS_SCANNING);
10083 
10084 		/*
10085 		 * Expansion is in progress.
10086 		 */
10087 		(void) printf(gettext(
10088 		    "expansion of %s-%u in progress since %s"),
10089 		    vname, (int)pres->pres_expanding_vdev, ctime(&start));
10090 
10091 		copied = pres->pres_reflowed > 0 ? pres->pres_reflowed : 1;
10092 		total = pres->pres_to_reflow;
10093 		fraction_done = (double)copied / total;
10094 
10095 		/* elapsed time for this pass */
10096 		elapsed = time(NULL) - pres->pres_start_time;
10097 		elapsed = elapsed > 0 ? elapsed : 1;
10098 		rate = copied / elapsed;
10099 		rate = rate > 0 ? rate : 1;
10100 		secs_left = (total - copied) / rate;
10101 
10102 		zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10103 		zfs_nicenum(total, total_buf, sizeof (total_buf));
10104 		zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10105 
10106 		/*
10107 		 * do not print estimated time if hours_left is more than
10108 		 * 30 days
10109 		 */
10110 		(void) printf(gettext("\t%s / %s copied at %s/s, %.2f%% done"),
10111 		    examined_buf, total_buf, rate_buf, 100 * fraction_done);
10112 		if (pres->pres_waiting_for_resilver) {
10113 			(void) printf(gettext(", paused for resilver or "
10114 			    "clear\n"));
10115 		} else if (secs_left < (30 * 24 * 3600)) {
10116 			char time_buf[32];
10117 			secs_to_dhms(secs_left, time_buf);
10118 			(void) printf(gettext(", %s to go\n"), time_buf);
10119 		} else {
10120 			(void) printf(gettext(
10121 			    ", (copy is slow, no estimated time)\n"));
10122 		}
10123 	}
10124 	free(vname);
10125 }
10126 static void
10127 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
10128 {
10129 	time_t start;
10130 	char space_buf[7];
10131 
10132 	if (pcs == NULL || pcs->pcs_state == CS_NONE)
10133 		return;
10134 
10135 	(void) printf(gettext("checkpoint: "));
10136 
10137 	start = pcs->pcs_start_time;
10138 	zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
10139 
10140 	if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
10141 		char *date = ctime(&start);
10142 
10143 		/*
10144 		 * ctime() adds a newline at the end of the generated
10145 		 * string, thus the weird format specifier and the
10146 		 * strlen() call used to chop it off from the output.
10147 		 */
10148 		(void) printf(gettext("created %.*s, consumes %s\n"),
10149 		    (int)(strlen(date) - 1), date, space_buf);
10150 		return;
10151 	}
10152 
10153 	assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
10154 
10155 	(void) printf(gettext("discarding, %s remaining.\n"),
10156 	    space_buf);
10157 }
10158 
10159 static void
10160 print_error_log(zpool_handle_t *zhp)
10161 {
10162 	nvlist_t *nverrlist = NULL;
10163 	nvpair_t *elem;
10164 	char *pathname;
10165 	size_t len = MAXPATHLEN * 2;
10166 
10167 	if (zpool_get_errlog(zhp, &nverrlist) != 0)
10168 		return;
10169 
10170 	(void) printf("errors: Permanent errors have been "
10171 	    "detected in the following files:\n\n");
10172 
10173 	pathname = safe_malloc(len);
10174 	elem = NULL;
10175 	while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
10176 		nvlist_t *nv;
10177 		uint64_t dsobj, obj;
10178 
10179 		verify(nvpair_value_nvlist(elem, &nv) == 0);
10180 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
10181 		    &dsobj) == 0);
10182 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
10183 		    &obj) == 0);
10184 		zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
10185 		(void) printf("%7s %s\n", "", pathname);
10186 	}
10187 	free(pathname);
10188 	nvlist_free(nverrlist);
10189 }
10190 
10191 static void
10192 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
10193     uint_t nspares)
10194 {
10195 	uint_t i;
10196 	char *name;
10197 
10198 	if (nspares == 0)
10199 		return;
10200 
10201 	(void) printf(gettext("\tspares\n"));
10202 
10203 	for (i = 0; i < nspares; i++) {
10204 		name = zpool_vdev_name(g_zfs, zhp, spares[i],
10205 		    cb->cb_name_flags);
10206 		print_status_config(zhp, cb, name, spares[i], 2, B_TRUE, NULL);
10207 		free(name);
10208 	}
10209 }
10210 
10211 static void
10212 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
10213     uint_t nl2cache)
10214 {
10215 	uint_t i;
10216 	char *name;
10217 
10218 	if (nl2cache == 0)
10219 		return;
10220 
10221 	(void) printf(gettext("\tcache\n"));
10222 
10223 	for (i = 0; i < nl2cache; i++) {
10224 		name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
10225 		    cb->cb_name_flags);
10226 		print_status_config(zhp, cb, name, l2cache[i], 2,
10227 		    B_FALSE, NULL);
10228 		free(name);
10229 	}
10230 }
10231 
10232 static void
10233 print_dedup_stats(zpool_handle_t *zhp, nvlist_t *config, boolean_t literal)
10234 {
10235 	ddt_histogram_t *ddh;
10236 	ddt_stat_t *dds;
10237 	ddt_object_t *ddo;
10238 	uint_t c;
10239 	/* Extra space provided for literal display */
10240 	char dspace[32], mspace[32], cspace[32];
10241 	uint64_t cspace_prop;
10242 	enum zfs_nicenum_format format;
10243 	zprop_source_t src;
10244 
10245 	/*
10246 	 * If the pool was faulted then we may not have been able to
10247 	 * obtain the config. Otherwise, if we have anything in the dedup
10248 	 * table continue processing the stats.
10249 	 */
10250 	if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
10251 	    (uint64_t **)&ddo, &c) != 0)
10252 		return;
10253 
10254 	(void) printf("\n");
10255 	(void) printf(gettext(" dedup: "));
10256 	if (ddo->ddo_count == 0) {
10257 		(void) printf(gettext("no DDT entries\n"));
10258 		return;
10259 	}
10260 
10261 	/*
10262 	 * Squash cached size into in-core size to handle race.
10263 	 * Only include cached size if it is available.
10264 	 */
10265 	cspace_prop = zpool_get_prop_int(zhp, ZPOOL_PROP_DEDUPCACHED, &src);
10266 	cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
10267 	format = literal ? ZFS_NICENUM_RAW : ZFS_NICENUM_1024;
10268 	zfs_nicenum_format(cspace_prop, cspace, sizeof (cspace), format);
10269 	zfs_nicenum_format(ddo->ddo_dspace, dspace, sizeof (dspace), format);
10270 	zfs_nicenum_format(ddo->ddo_mspace, mspace, sizeof (mspace), format);
10271 	(void) printf("DDT entries %llu, size %s on disk, %s in core",
10272 	    (u_longlong_t)ddo->ddo_count,
10273 	    dspace,
10274 	    mspace);
10275 	if (src != ZPROP_SRC_DEFAULT) {
10276 		(void) printf(", %s cached (%.02f%%)",
10277 		    cspace,
10278 		    (double)cspace_prop / (double)ddo->ddo_mspace * 100.0);
10279 	}
10280 	(void) printf("\n");
10281 
10282 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
10283 	    (uint64_t **)&dds, &c) == 0);
10284 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
10285 	    (uint64_t **)&ddh, &c) == 0);
10286 	zpool_dump_ddt(dds, ddh);
10287 }
10288 
10289 #define	ST_SIZE	4096
10290 #define	AC_SIZE	2048
10291 
10292 static void
10293 print_status_reason(zpool_handle_t *zhp, status_cbdata_t *cbp,
10294     zpool_status_t reason, zpool_errata_t errata, nvlist_t *item)
10295 {
10296 	char status[ST_SIZE];
10297 	char action[AC_SIZE];
10298 	memset(status, 0, ST_SIZE);
10299 	memset(action, 0, AC_SIZE);
10300 
10301 	switch (reason) {
10302 	case ZPOOL_STATUS_MISSING_DEV_R:
10303 		snprintf(status, ST_SIZE, gettext("One or more devices could "
10304 		    "not be opened.  Sufficient replicas exist for\n\tthe pool "
10305 		    "to continue functioning in a degraded state.\n"));
10306 		snprintf(action, AC_SIZE, gettext("Attach the missing device "
10307 		    "and online it using 'zpool online'.\n"));
10308 		break;
10309 
10310 	case ZPOOL_STATUS_MISSING_DEV_NR:
10311 		snprintf(status, ST_SIZE, gettext("One or more devices could "
10312 		    "not be opened.  There are insufficient\n\treplicas for the"
10313 		    " pool to continue functioning.\n"));
10314 		snprintf(action, AC_SIZE, gettext("Attach the missing device "
10315 		    "and online it using 'zpool online'.\n"));
10316 		break;
10317 
10318 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
10319 		snprintf(status, ST_SIZE, gettext("One or more devices could "
10320 		    "not be used because the label is missing or\n\tinvalid.  "
10321 		    "Sufficient replicas exist for the pool to continue\n\t"
10322 		    "functioning in a degraded state.\n"));
10323 		snprintf(action, AC_SIZE, gettext("Replace the device using "
10324 		    "'zpool replace'.\n"));
10325 		break;
10326 
10327 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
10328 		snprintf(status, ST_SIZE, gettext("One or more devices could "
10329 		    "not be used because the label is missing \n\tor invalid.  "
10330 		    "There are insufficient replicas for the pool to "
10331 		    "continue\n\tfunctioning.\n"));
10332 		zpool_explain_recover(zpool_get_handle(zhp),
10333 		    zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
10334 		    action, AC_SIZE);
10335 		break;
10336 
10337 	case ZPOOL_STATUS_FAILING_DEV:
10338 		snprintf(status, ST_SIZE, gettext("One or more devices has "
10339 		    "experienced an unrecoverable error.  An\n\tattempt was "
10340 		    "made to correct the error.  Applications are "
10341 		    "unaffected.\n"));
10342 		snprintf(action, AC_SIZE, gettext("Determine if the "
10343 		    "device needs to be replaced, and clear the errors\n\tusing"
10344 		    " 'zpool clear' or replace the device with 'zpool "
10345 		    "replace'.\n"));
10346 		break;
10347 
10348 	case ZPOOL_STATUS_OFFLINE_DEV:
10349 		snprintf(status, ST_SIZE, gettext("One or more devices has "
10350 		    "been taken offline by the administrator.\n\tSufficient "
10351 		    "replicas exist for the pool to continue functioning in "
10352 		    "a\n\tdegraded state.\n"));
10353 		snprintf(action, AC_SIZE, gettext("Online the device "
10354 		    "using 'zpool online' or replace the device with\n\t'zpool "
10355 		    "replace'.\n"));
10356 		break;
10357 
10358 	case ZPOOL_STATUS_REMOVED_DEV:
10359 		snprintf(status, ST_SIZE, gettext("One or more devices has "
10360 		    "been removed by the administrator.\n\tSufficient "
10361 		    "replicas exist for the pool to continue functioning in "
10362 		    "a\n\tdegraded state.\n"));
10363 		snprintf(action, AC_SIZE, gettext("Online the device "
10364 		    "using zpool online' or replace the device with\n\t'zpool "
10365 		    "replace'.\n"));
10366 		break;
10367 
10368 	case ZPOOL_STATUS_RESILVERING:
10369 	case ZPOOL_STATUS_REBUILDING:
10370 		snprintf(status, ST_SIZE, gettext("One or more devices is "
10371 		    "currently being resilvered.  The pool will\n\tcontinue "
10372 		    "to function, possibly in a degraded state.\n"));
10373 		snprintf(action, AC_SIZE, gettext("Wait for the resilver to "
10374 		    "complete.\n"));
10375 		break;
10376 
10377 	case ZPOOL_STATUS_REBUILD_SCRUB:
10378 		snprintf(status, ST_SIZE, gettext("One or more devices have "
10379 		    "been sequentially resilvered, scrubbing\n\tthe pool "
10380 		    "is recommended.\n"));
10381 		snprintf(action, AC_SIZE, gettext("Use 'zpool scrub' to "
10382 		    "verify all data checksums.\n"));
10383 		break;
10384 
10385 	case ZPOOL_STATUS_CORRUPT_DATA:
10386 		snprintf(status, ST_SIZE, gettext("One or more devices has "
10387 		    "experienced an error resulting in data\n\tcorruption.  "
10388 		    "Applications may be affected.\n"));
10389 		snprintf(action, AC_SIZE, gettext("Restore the file in question"
10390 		    " if possible.  Otherwise restore the\n\tentire pool from "
10391 		    "backup.\n"));
10392 		break;
10393 
10394 	case ZPOOL_STATUS_CORRUPT_POOL:
10395 		snprintf(status, ST_SIZE, gettext("The pool metadata is "
10396 		    "corrupted and the pool cannot be opened.\n"));
10397 		zpool_explain_recover(zpool_get_handle(zhp),
10398 		    zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
10399 		    action, AC_SIZE);
10400 		break;
10401 
10402 	case ZPOOL_STATUS_VERSION_OLDER:
10403 		snprintf(status, ST_SIZE, gettext("The pool is formatted using "
10404 		    "a legacy on-disk format.  The pool can\n\tstill be used, "
10405 		    "but some features are unavailable.\n"));
10406 		snprintf(action, AC_SIZE, gettext("Upgrade the pool using "
10407 		    "'zpool upgrade'.  Once this is done, the\n\tpool will no "
10408 		    "longer be accessible on software that does not support\n\t"
10409 		    "feature flags.\n"));
10410 		break;
10411 
10412 	case ZPOOL_STATUS_VERSION_NEWER:
10413 		snprintf(status, ST_SIZE, gettext("The pool has been upgraded "
10414 		    "to a newer, incompatible on-disk version.\n\tThe pool "
10415 		    "cannot be accessed on this system.\n"));
10416 		snprintf(action, AC_SIZE, gettext("Access the pool from a "
10417 		    "system running more recent software, or\n\trestore the "
10418 		    "pool from backup.\n"));
10419 		break;
10420 
10421 	case ZPOOL_STATUS_FEAT_DISABLED:
10422 		snprintf(status, ST_SIZE, gettext("Some supported and "
10423 		    "requested features are not enabled on the pool.\n\t"
10424 		    "The pool can still be used, but some features are "
10425 		    "unavailable.\n"));
10426 		snprintf(action, AC_SIZE, gettext("Enable all features using "
10427 		    "'zpool upgrade'. Once this is done,\n\tthe pool may no "
10428 		    "longer be accessible by software that does not support\n\t"
10429 		    "the features. See zpool-features(7) for details.\n"));
10430 		break;
10431 
10432 	case ZPOOL_STATUS_COMPATIBILITY_ERR:
10433 		snprintf(status, ST_SIZE, gettext("This pool has a "
10434 		    "compatibility list specified, but it could not be\n\t"
10435 		    "read/parsed at this time. The pool can still be used, "
10436 		    "but this\n\tshould be investigated.\n"));
10437 		snprintf(action, AC_SIZE, gettext("Check the value of the "
10438 		    "'compatibility' property against the\n\t"
10439 		    "appropriate file in " ZPOOL_SYSCONF_COMPAT_D " or "
10440 		    ZPOOL_DATA_COMPAT_D ".\n"));
10441 		break;
10442 
10443 	case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
10444 		snprintf(status, ST_SIZE, gettext("One or more features "
10445 		    "are enabled on the pool despite not being\n\t"
10446 		    "requested by the 'compatibility' property.\n"));
10447 		snprintf(action, AC_SIZE, gettext("Consider setting "
10448 		    "'compatibility' to an appropriate value, or\n\t"
10449 		    "adding needed features to the relevant file in\n\t"
10450 		    ZPOOL_SYSCONF_COMPAT_D " or " ZPOOL_DATA_COMPAT_D ".\n"));
10451 		break;
10452 
10453 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
10454 		snprintf(status, ST_SIZE, gettext("The pool cannot be accessed "
10455 		    "on this system because it uses the\n\tfollowing feature(s)"
10456 		    " not supported on this system:\n"));
10457 		zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
10458 		    1024);
10459 		snprintf(action, AC_SIZE, gettext("Access the pool from a "
10460 		    "system that supports the required feature(s),\n\tor "
10461 		    "restore the pool from backup.\n"));
10462 		break;
10463 
10464 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
10465 		snprintf(status, ST_SIZE, gettext("The pool can only be "
10466 		    "accessed in read-only mode on this system. It\n\tcannot be"
10467 		    " accessed in read-write mode because it uses the "
10468 		    "following\n\tfeature(s) not supported on this system:\n"));
10469 		zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
10470 		    1024);
10471 		snprintf(action, AC_SIZE, gettext("The pool cannot be accessed "
10472 		    "in read-write mode. Import the pool with\n"
10473 		    "\t\"-o readonly=on\", access the pool from a system that "
10474 		    "supports the\n\trequired feature(s), or restore the "
10475 		    "pool from backup.\n"));
10476 		break;
10477 
10478 	case ZPOOL_STATUS_FAULTED_DEV_R:
10479 		snprintf(status, ST_SIZE, gettext("One or more devices are "
10480 		    "faulted in response to persistent errors.\n\tSufficient "
10481 		    "replicas exist for the pool to continue functioning "
10482 		    "in a\n\tdegraded state.\n"));
10483 		snprintf(action, AC_SIZE, gettext("Replace the faulted device, "
10484 		    "or use 'zpool clear' to mark the device\n\trepaired.\n"));
10485 		break;
10486 
10487 	case ZPOOL_STATUS_FAULTED_DEV_NR:
10488 		snprintf(status, ST_SIZE, gettext("One or more devices are "
10489 		    "faulted in response to persistent errors.  There are "
10490 		    "insufficient replicas for the pool to\n\tcontinue "
10491 		    "functioning.\n"));
10492 		snprintf(action, AC_SIZE, gettext("Destroy and re-create the "
10493 		    "pool from a backup source.  Manually marking the device\n"
10494 		    "\trepaired using 'zpool clear' may allow some data "
10495 		    "to be recovered.\n"));
10496 		break;
10497 
10498 	case ZPOOL_STATUS_IO_FAILURE_MMP:
10499 		snprintf(status, ST_SIZE, gettext("The pool is suspended "
10500 		    "because multihost writes failed or were delayed;\n\t"
10501 		    "another system could import the pool undetected.\n"));
10502 		snprintf(action, AC_SIZE, gettext("Make sure the pool's devices"
10503 		    " are connected, then reboot your system and\n\timport the "
10504 		    "pool or run 'zpool clear' to resume the pool.\n"));
10505 		break;
10506 
10507 	case ZPOOL_STATUS_IO_FAILURE_WAIT:
10508 	case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
10509 		snprintf(status, ST_SIZE, gettext("One or more devices are "
10510 		    "faulted in response to IO failures.\n"));
10511 		snprintf(action, AC_SIZE, gettext("Make sure the affected "
10512 		    "devices are connected, then run 'zpool clear'.\n"));
10513 		break;
10514 
10515 	case ZPOOL_STATUS_BAD_LOG:
10516 		snprintf(status, ST_SIZE, gettext("An intent log record "
10517 		    "could not be read.\n"
10518 		    "\tWaiting for administrator intervention to fix the "
10519 		    "faulted pool.\n"));
10520 		snprintf(action, AC_SIZE, gettext("Either restore the affected "
10521 		    "device(s) and run 'zpool online',\n"
10522 		    "\tor ignore the intent log records by running "
10523 		    "'zpool clear'.\n"));
10524 		break;
10525 
10526 	case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
10527 		snprintf(status, ST_SIZE, gettext("One or more devices are "
10528 		    "configured to use a non-native block size.\n"
10529 		    "\tExpect reduced performance.\n"));
10530 		snprintf(action, AC_SIZE, gettext("Replace affected devices "
10531 		    "with devices that support the\n\tconfigured block size, "
10532 		    "or migrate data to a properly configured\n\tpool.\n"));
10533 		break;
10534 
10535 	case ZPOOL_STATUS_HOSTID_MISMATCH:
10536 		snprintf(status, ST_SIZE, gettext("Mismatch between pool hostid"
10537 		    " and system hostid on imported pool.\n\tThis pool was "
10538 		    "previously imported into a system with a different "
10539 		    "hostid,\n\tand then was verbatim imported into this "
10540 		    "system.\n"));
10541 		snprintf(action, AC_SIZE, gettext("Export this pool on all "
10542 		    "systems on which it is imported.\n"
10543 		    "\tThen import it to correct the mismatch.\n"));
10544 		break;
10545 
10546 	case ZPOOL_STATUS_ERRATA:
10547 		snprintf(status, ST_SIZE, gettext("Errata #%d detected.\n"),
10548 		    errata);
10549 		switch (errata) {
10550 		case ZPOOL_ERRATA_NONE:
10551 			break;
10552 
10553 		case ZPOOL_ERRATA_ZOL_2094_SCRUB:
10554 			snprintf(action, AC_SIZE, gettext("To correct the issue"
10555 			    " run 'zpool scrub'.\n"));
10556 			break;
10557 
10558 		case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
10559 			(void) strlcat(status, gettext("\tExisting encrypted "
10560 			    "datasets contain an on-disk incompatibility\n\t "
10561 			    "which needs to be corrected.\n"), ST_SIZE);
10562 			snprintf(action, AC_SIZE, gettext("To correct the issue"
10563 			    " backup existing encrypted datasets to new\n\t"
10564 			    "encrypted datasets and destroy the old ones. "
10565 			    "'zfs mount -o ro' can\n\tbe used to temporarily "
10566 			    "mount existing encrypted datasets readonly.\n"));
10567 			break;
10568 
10569 		case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
10570 			(void) strlcat(status, gettext("\tExisting encrypted "
10571 			    "snapshots and bookmarks contain an on-disk\n\t"
10572 			    "incompatibility. This may cause on-disk "
10573 			    "corruption if they are used\n\twith "
10574 			    "'zfs recv'.\n"), ST_SIZE);
10575 			snprintf(action, AC_SIZE, gettext("To correct the"
10576 			    "issue, enable the bookmark_v2 feature. No "
10577 			    "additional\n\taction is needed if there are no "
10578 			    "encrypted snapshots or bookmarks.\n\tIf preserving"
10579 			    "the encrypted snapshots and bookmarks is required,"
10580 			    " use\n\ta non-raw send to backup and restore them."
10581 			    " Alternately, they may be\n\tremoved to resolve "
10582 			    "the incompatibility.\n"));
10583 			break;
10584 
10585 		default:
10586 			/*
10587 			 * All errata which allow the pool to be imported
10588 			 * must contain an action message.
10589 			 */
10590 			assert(0);
10591 		}
10592 		break;
10593 
10594 	default:
10595 		/*
10596 		 * The remaining errors can't actually be generated, yet.
10597 		 */
10598 		assert(reason == ZPOOL_STATUS_OK);
10599 	}
10600 
10601 	if (status[0] != 0) {
10602 		if (cbp->cb_json)
10603 			fnvlist_add_string(item, "status", status);
10604 		else {
10605 			printf_color(ANSI_BOLD, gettext("status: "));
10606 			printf_color(ANSI_YELLOW, status);
10607 		}
10608 	}
10609 
10610 	if (action[0] != 0) {
10611 		if (cbp->cb_json)
10612 			fnvlist_add_string(item, "action", action);
10613 		else {
10614 			printf_color(ANSI_BOLD, gettext("action: "));
10615 			printf_color(ANSI_YELLOW, action);
10616 		}
10617 	}
10618 }
10619 
10620 static int
10621 status_callback_json(zpool_handle_t *zhp, void *data)
10622 {
10623 	status_cbdata_t *cbp = data;
10624 	nvlist_t *config, *nvroot;
10625 	const char *msgid;
10626 	char pool_guid[256];
10627 	char msgbuf[256];
10628 	uint64_t guid;
10629 	zpool_status_t reason;
10630 	zpool_errata_t errata;
10631 	uint_t c;
10632 	vdev_stat_t *vs;
10633 	nvlist_t *item, *d, *load_info, *vds;
10634 	item = d = NULL;
10635 
10636 	/* If dedup stats were requested, also fetch dedupcached. */
10637 	if (cbp->cb_dedup_stats > 1)
10638 		zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
10639 	reason = zpool_get_status(zhp, &msgid, &errata);
10640 	/*
10641 	 * If we were given 'zpool status -x', only report those pools with
10642 	 * problems.
10643 	 */
10644 	if (cbp->cb_explain &&
10645 	    (reason == ZPOOL_STATUS_OK ||
10646 	    reason == ZPOOL_STATUS_VERSION_OLDER ||
10647 	    reason == ZPOOL_STATUS_FEAT_DISABLED ||
10648 	    reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
10649 	    reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
10650 		return (0);
10651 	}
10652 
10653 	d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
10654 	item = fnvlist_alloc();
10655 	vds = fnvlist_alloc();
10656 	fill_pool_info(item, zhp, B_FALSE, cbp->cb_json_as_int);
10657 	config = zpool_get_config(zhp, NULL);
10658 
10659 	if (config != NULL) {
10660 		nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
10661 		verify(nvlist_lookup_uint64_array(nvroot,
10662 		    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &c) == 0);
10663 		if (cbp->cb_json_pool_key_guid) {
10664 			guid = fnvlist_lookup_uint64(config,
10665 			    ZPOOL_CONFIG_POOL_GUID);
10666 			snprintf(pool_guid, 256, "%llu", (u_longlong_t)guid);
10667 		}
10668 		cbp->cb_count++;
10669 
10670 		print_status_reason(zhp, cbp, reason, errata, item);
10671 		if (msgid != NULL) {
10672 			snprintf(msgbuf, 256,
10673 			    "https://openzfs.github.io/openzfs-docs/msg/%s",
10674 			    msgid);
10675 			fnvlist_add_string(item, "msgid", msgid);
10676 			fnvlist_add_string(item, "moreinfo", msgbuf);
10677 		}
10678 
10679 		if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
10680 		    &load_info) == 0) {
10681 			fnvlist_add_nvlist(item, ZPOOL_CONFIG_LOAD_INFO,
10682 			    load_info);
10683 		}
10684 
10685 		scan_status_nvlist(zhp, cbp, nvroot, item);
10686 		removal_status_nvlist(zhp, cbp, nvroot, item);
10687 		checkpoint_status_nvlist(nvroot, cbp, item);
10688 		raidz_expand_status_nvlist(zhp, cbp, nvroot, item);
10689 		vdev_stats_nvlist(zhp, cbp, nvroot, 0, B_FALSE, NULL, vds);
10690 		if (cbp->cb_flat_vdevs) {
10691 			class_vdevs_nvlist(zhp, cbp, nvroot,
10692 			    VDEV_ALLOC_BIAS_DEDUP, vds);
10693 			class_vdevs_nvlist(zhp, cbp, nvroot,
10694 			    VDEV_ALLOC_BIAS_SPECIAL, vds);
10695 			class_vdevs_nvlist(zhp, cbp, nvroot,
10696 			    VDEV_ALLOC_CLASS_LOGS, vds);
10697 			l2cache_nvlist(zhp, cbp, nvroot, vds);
10698 			spares_nvlist(zhp, cbp, nvroot, vds);
10699 
10700 			fnvlist_add_nvlist(item, "vdevs", vds);
10701 			fnvlist_free(vds);
10702 		} else {
10703 			fnvlist_add_nvlist(item, "vdevs", vds);
10704 			fnvlist_free(vds);
10705 
10706 			class_vdevs_nvlist(zhp, cbp, nvroot,
10707 			    VDEV_ALLOC_BIAS_DEDUP, item);
10708 			class_vdevs_nvlist(zhp, cbp, nvroot,
10709 			    VDEV_ALLOC_BIAS_SPECIAL, item);
10710 			class_vdevs_nvlist(zhp, cbp, nvroot,
10711 			    VDEV_ALLOC_CLASS_LOGS, item);
10712 			l2cache_nvlist(zhp, cbp, nvroot, item);
10713 			spares_nvlist(zhp, cbp, nvroot, item);
10714 		}
10715 		dedup_stats_nvlist(zhp, cbp, item);
10716 		errors_nvlist(zhp, cbp, item);
10717 	}
10718 	if (cbp->cb_json_pool_key_guid) {
10719 		fnvlist_add_nvlist(d, pool_guid, item);
10720 	} else {
10721 		fnvlist_add_nvlist(d, zpool_get_name(zhp),
10722 		    item);
10723 	}
10724 	fnvlist_free(item);
10725 	return (0);
10726 }
10727 
10728 /*
10729  * Display a summary of pool status.  Displays a summary such as:
10730  *
10731  *        pool: tank
10732  *	status: DEGRADED
10733  *	reason: One or more devices ...
10734  *         see: https://openzfs.github.io/openzfs-docs/msg/ZFS-xxxx-01
10735  *	config:
10736  *		mirror		DEGRADED
10737  *                c1t0d0	OK
10738  *                c2t0d0	UNAVAIL
10739  *
10740  * When given the '-v' option, we print out the complete config.  If the '-e'
10741  * option is specified, then we print out error rate information as well.
10742  */
10743 static int
10744 status_callback(zpool_handle_t *zhp, void *data)
10745 {
10746 	status_cbdata_t *cbp = data;
10747 	nvlist_t *config, *nvroot;
10748 	const char *msgid;
10749 	zpool_status_t reason;
10750 	zpool_errata_t errata;
10751 	const char *health;
10752 	uint_t c;
10753 	vdev_stat_t *vs;
10754 
10755 	/* If dedup stats were requested, also fetch dedupcached. */
10756 	if (cbp->cb_dedup_stats > 1)
10757 		zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
10758 
10759 	config = zpool_get_config(zhp, NULL);
10760 	reason = zpool_get_status(zhp, &msgid, &errata);
10761 
10762 	cbp->cb_count++;
10763 
10764 	/*
10765 	 * If we were given 'zpool status -x', only report those pools with
10766 	 * problems.
10767 	 */
10768 	if (cbp->cb_explain &&
10769 	    (reason == ZPOOL_STATUS_OK ||
10770 	    reason == ZPOOL_STATUS_VERSION_OLDER ||
10771 	    reason == ZPOOL_STATUS_FEAT_DISABLED ||
10772 	    reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
10773 	    reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
10774 		if (!cbp->cb_allpools) {
10775 			(void) printf(gettext("pool '%s' is healthy\n"),
10776 			    zpool_get_name(zhp));
10777 			if (cbp->cb_first)
10778 				cbp->cb_first = B_FALSE;
10779 		}
10780 		return (0);
10781 	}
10782 
10783 	if (cbp->cb_first)
10784 		cbp->cb_first = B_FALSE;
10785 	else
10786 		(void) printf("\n");
10787 
10788 	nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
10789 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
10790 	    (uint64_t **)&vs, &c) == 0);
10791 
10792 	health = zpool_get_state_str(zhp);
10793 
10794 	printf("  ");
10795 	printf_color(ANSI_BOLD, gettext("pool:"));
10796 	printf(" %s\n", zpool_get_name(zhp));
10797 	fputc(' ', stdout);
10798 	printf_color(ANSI_BOLD, gettext("state: "));
10799 
10800 	printf_color(health_str_to_color(health), "%s", health);
10801 
10802 	fputc('\n', stdout);
10803 	print_status_reason(zhp, cbp, reason, errata, NULL);
10804 
10805 	if (msgid != NULL) {
10806 		printf("   ");
10807 		printf_color(ANSI_BOLD, gettext("see:"));
10808 		printf(gettext(
10809 		    " https://openzfs.github.io/openzfs-docs/msg/%s\n"),
10810 		    msgid);
10811 	}
10812 
10813 	if (config != NULL) {
10814 		uint64_t nerr;
10815 		nvlist_t **spares, **l2cache;
10816 		uint_t nspares, nl2cache;
10817 
10818 		print_scan_status(zhp, nvroot);
10819 
10820 		pool_removal_stat_t *prs = NULL;
10821 		(void) nvlist_lookup_uint64_array(nvroot,
10822 		    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
10823 		print_removal_status(zhp, prs);
10824 
10825 		pool_checkpoint_stat_t *pcs = NULL;
10826 		(void) nvlist_lookup_uint64_array(nvroot,
10827 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
10828 		print_checkpoint_status(pcs);
10829 
10830 		pool_raidz_expand_stat_t *pres = NULL;
10831 		(void) nvlist_lookup_uint64_array(nvroot,
10832 		    ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
10833 		print_raidz_expand_status(zhp, pres);
10834 
10835 		cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
10836 		    cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
10837 		if (cbp->cb_namewidth < 10)
10838 			cbp->cb_namewidth = 10;
10839 
10840 		color_start(ANSI_BOLD);
10841 		(void) printf(gettext("config:\n\n"));
10842 		(void) printf(gettext("\t%-*s  %-8s %5s %5s %5s"),
10843 		    cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
10844 		    "CKSUM");
10845 		color_end();
10846 
10847 		if (cbp->cb_print_slow_ios) {
10848 			printf_color(ANSI_BOLD, " %5s", gettext("SLOW"));
10849 		}
10850 
10851 		if (cbp->cb_print_power) {
10852 			printf_color(ANSI_BOLD, " %5s", gettext("POWER"));
10853 		}
10854 
10855 		if (cbp->vcdl != NULL)
10856 			print_cmd_columns(cbp->vcdl, 0);
10857 
10858 		printf("\n");
10859 
10860 		print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
10861 		    B_FALSE, NULL);
10862 
10863 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
10864 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
10865 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
10866 
10867 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
10868 		    &l2cache, &nl2cache) == 0)
10869 			print_l2cache(zhp, cbp, l2cache, nl2cache);
10870 
10871 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
10872 		    &spares, &nspares) == 0)
10873 			print_spares(zhp, cbp, spares, nspares);
10874 
10875 		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
10876 		    &nerr) == 0) {
10877 			(void) printf("\n");
10878 			if (nerr == 0) {
10879 				(void) printf(gettext(
10880 				    "errors: No known data errors\n"));
10881 			} else if (!cbp->cb_verbose) {
10882 				color_start(ANSI_RED);
10883 				(void) printf(gettext("errors: %llu data "
10884 				    "errors, use '-v' for a list\n"),
10885 				    (u_longlong_t)nerr);
10886 				color_end();
10887 			} else {
10888 				print_error_log(zhp);
10889 			}
10890 		}
10891 
10892 		if (cbp->cb_dedup_stats)
10893 			print_dedup_stats(zhp, config, cbp->cb_literal);
10894 	} else {
10895 		(void) printf(gettext("config: The configuration cannot be "
10896 		    "determined.\n"));
10897 	}
10898 
10899 	return (0);
10900 }
10901 
10902 /*
10903  * zpool status [-c [script1,script2,...]] [-DegiLpPstvx] [--power] [-T d|u] ...
10904  *              [pool] [interval [count]]
10905  *
10906  *	-c CMD	For each vdev, run command CMD
10907  *	-D	Display dedup status (undocumented)
10908  *	-e	Display only unhealthy vdevs
10909  *	-g	Display guid for individual vdev name.
10910  *	-i	Display vdev initialization status.
10911  *	-L	Follow links when resolving vdev path name.
10912  *	-p	Display values in parsable (exact) format.
10913  *	-P	Display full path for vdev name.
10914  *	-s	Display slow IOs column.
10915  *	-t	Display vdev TRIM status.
10916  *	-T	Display a timestamp in date(1) or Unix format
10917  *	-v	Display complete error logs
10918  *	-x	Display only pools with potential problems
10919  *	-j	Display output in JSON format
10920  *	--power	Display vdev enclosure slot power status
10921  *	--json-int Display numbers in inteeger format instead of string
10922  *	--json-flat-vdevs Display vdevs in flat hierarchy
10923  *	--json-pool-key-guid Use pool GUID as key for pool objects
10924  *
10925  * Describes the health status of all pools or some subset.
10926  */
10927 int
10928 zpool_do_status(int argc, char **argv)
10929 {
10930 	int c;
10931 	int ret;
10932 	float interval = 0;
10933 	unsigned long count = 0;
10934 	status_cbdata_t cb = { 0 };
10935 	nvlist_t *data;
10936 	char *cmd = NULL;
10937 
10938 	struct option long_options[] = {
10939 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
10940 		{"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
10941 		{"json-flat-vdevs", no_argument, NULL,
10942 		    ZPOOL_OPTION_JSON_FLAT_VDEVS},
10943 		{"json-pool-key-guid", no_argument, NULL,
10944 		    ZPOOL_OPTION_POOL_KEY_GUID},
10945 		{0, 0, 0, 0}
10946 	};
10947 
10948 	/* check options */
10949 	while ((c = getopt_long(argc, argv, "c:jDegiLpPstT:vx", long_options,
10950 	    NULL)) != -1) {
10951 		switch (c) {
10952 		case 'c':
10953 			if (cmd != NULL) {
10954 				fprintf(stderr,
10955 				    gettext("Can't set -c flag twice\n"));
10956 				exit(1);
10957 			}
10958 
10959 			if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
10960 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
10961 				fprintf(stderr, gettext(
10962 				    "Can't run -c, disabled by "
10963 				    "ZPOOL_SCRIPTS_ENABLED.\n"));
10964 				exit(1);
10965 			}
10966 
10967 			if ((getuid() <= 0 || geteuid() <= 0) &&
10968 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
10969 				fprintf(stderr, gettext(
10970 				    "Can't run -c with root privileges "
10971 				    "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
10972 				exit(1);
10973 			}
10974 			cmd = optarg;
10975 			break;
10976 		case 'D':
10977 			if (++cb.cb_dedup_stats  > 2)
10978 				cb.cb_dedup_stats = 2;
10979 			break;
10980 		case 'e':
10981 			cb.cb_print_unhealthy = B_TRUE;
10982 			break;
10983 		case 'g':
10984 			cb.cb_name_flags |= VDEV_NAME_GUID;
10985 			break;
10986 		case 'i':
10987 			cb.cb_print_vdev_init = B_TRUE;
10988 			break;
10989 		case 'L':
10990 			cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
10991 			break;
10992 		case 'p':
10993 			cb.cb_literal = B_TRUE;
10994 			break;
10995 		case 'P':
10996 			cb.cb_name_flags |= VDEV_NAME_PATH;
10997 			break;
10998 		case 's':
10999 			cb.cb_print_slow_ios = B_TRUE;
11000 			break;
11001 		case 't':
11002 			cb.cb_print_vdev_trim = B_TRUE;
11003 			break;
11004 		case 'T':
11005 			get_timestamp_arg(*optarg);
11006 			break;
11007 		case 'v':
11008 			cb.cb_verbose = B_TRUE;
11009 			break;
11010 		case 'j':
11011 			cb.cb_json = B_TRUE;
11012 			break;
11013 		case 'x':
11014 			cb.cb_explain = B_TRUE;
11015 			break;
11016 		case ZPOOL_OPTION_POWER:
11017 			cb.cb_print_power = B_TRUE;
11018 			break;
11019 		case ZPOOL_OPTION_JSON_FLAT_VDEVS:
11020 			cb.cb_flat_vdevs = B_TRUE;
11021 			break;
11022 		case ZPOOL_OPTION_JSON_NUMS_AS_INT:
11023 			cb.cb_json_as_int = B_TRUE;
11024 			cb.cb_literal = B_TRUE;
11025 			break;
11026 		case ZPOOL_OPTION_POOL_KEY_GUID:
11027 			cb.cb_json_pool_key_guid = B_TRUE;
11028 			break;
11029 		case '?':
11030 			if (optopt == 'c') {
11031 				print_zpool_script_list("status");
11032 				exit(0);
11033 			} else {
11034 				fprintf(stderr,
11035 				    gettext("invalid option '%c'\n"), optopt);
11036 			}
11037 			usage(B_FALSE);
11038 		}
11039 	}
11040 
11041 	argc -= optind;
11042 	argv += optind;
11043 
11044 	get_interval_count(&argc, argv, &interval, &count);
11045 
11046 	if (argc == 0)
11047 		cb.cb_allpools = B_TRUE;
11048 
11049 	cb.cb_first = B_TRUE;
11050 	cb.cb_print_status = B_TRUE;
11051 
11052 	if (cb.cb_flat_vdevs && !cb.cb_json) {
11053 		fprintf(stderr, gettext("'--json-flat-vdevs' only works with"
11054 		    " '-j' option\n"));
11055 		usage(B_FALSE);
11056 	}
11057 
11058 	if (cb.cb_json_as_int && !cb.cb_json) {
11059 		(void) fprintf(stderr, gettext("'--json-int' only works with"
11060 		    " '-j' option\n"));
11061 		usage(B_FALSE);
11062 	}
11063 
11064 	if (!cb.cb_json && cb.cb_json_pool_key_guid) {
11065 		(void) fprintf(stderr, gettext("'json-pool-key-guid' only"
11066 		    " works with '-j' option\n"));
11067 		usage(B_FALSE);
11068 	}
11069 
11070 	for (;;) {
11071 		if (cb.cb_json) {
11072 			cb.cb_jsobj = zpool_json_schema(0, 1);
11073 			data = fnvlist_alloc();
11074 			fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
11075 			fnvlist_free(data);
11076 		}
11077 
11078 		if (timestamp_fmt != NODATE) {
11079 			if (cb.cb_json) {
11080 				if (cb.cb_json_as_int) {
11081 					fnvlist_add_uint64(cb.cb_jsobj, "time",
11082 					    time(NULL));
11083 				} else {
11084 					char ts[128];
11085 					get_timestamp(timestamp_fmt, ts, 128);
11086 					fnvlist_add_string(cb.cb_jsobj, "time",
11087 					    ts);
11088 				}
11089 			} else
11090 				print_timestamp(timestamp_fmt);
11091 		}
11092 
11093 		if (cmd != NULL)
11094 			cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
11095 			    NULL, NULL, 0, 0);
11096 
11097 		if (cb.cb_json) {
11098 			ret = for_each_pool(argc, argv, B_TRUE, NULL,
11099 			    ZFS_TYPE_POOL, cb.cb_literal,
11100 			    status_callback_json, &cb);
11101 		} else {
11102 			ret = for_each_pool(argc, argv, B_TRUE, NULL,
11103 			    ZFS_TYPE_POOL, cb.cb_literal,
11104 			    status_callback, &cb);
11105 		}
11106 
11107 		if (cb.vcdl != NULL)
11108 			free_vdev_cmd_data_list(cb.vcdl);
11109 
11110 		if (cb.cb_json) {
11111 			if (ret == 0)
11112 				zcmd_print_json(cb.cb_jsobj);
11113 			else
11114 				nvlist_free(cb.cb_jsobj);
11115 		} else {
11116 			if (argc == 0 && cb.cb_count == 0) {
11117 				(void) fprintf(stderr, "%s",
11118 				    gettext("no pools available\n"));
11119 			} else if (cb.cb_explain && cb.cb_first &&
11120 			    cb.cb_allpools) {
11121 				(void) printf("%s",
11122 				    gettext("all pools are healthy\n"));
11123 			}
11124 		}
11125 
11126 		if (ret != 0)
11127 			return (ret);
11128 
11129 		if (interval == 0)
11130 			break;
11131 
11132 		if (count != 0 && --count == 0)
11133 			break;
11134 
11135 		(void) fflush(stdout);
11136 		(void) fsleep(interval);
11137 	}
11138 
11139 	return (0);
11140 }
11141 
11142 typedef struct upgrade_cbdata {
11143 	int	cb_first;
11144 	int	cb_argc;
11145 	uint64_t cb_version;
11146 	char	**cb_argv;
11147 } upgrade_cbdata_t;
11148 
11149 static int
11150 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
11151 {
11152 	int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
11153 	int *count = (int *)unsupp_fs;
11154 
11155 	if (zfs_version > ZPL_VERSION) {
11156 		(void) printf(gettext("%s (v%d) is not supported by this "
11157 		    "implementation of ZFS.\n"),
11158 		    zfs_get_name(zhp), zfs_version);
11159 		(*count)++;
11160 	}
11161 
11162 	zfs_iter_filesystems_v2(zhp, 0, check_unsupp_fs, unsupp_fs);
11163 
11164 	zfs_close(zhp);
11165 
11166 	return (0);
11167 }
11168 
11169 static int
11170 upgrade_version(zpool_handle_t *zhp, uint64_t version)
11171 {
11172 	int ret;
11173 	nvlist_t *config;
11174 	uint64_t oldversion;
11175 	int unsupp_fs = 0;
11176 
11177 	config = zpool_get_config(zhp, NULL);
11178 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11179 	    &oldversion) == 0);
11180 
11181 	char compat[ZFS_MAXPROPLEN];
11182 	if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11183 	    ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11184 		compat[0] = '\0';
11185 
11186 	assert(SPA_VERSION_IS_SUPPORTED(oldversion));
11187 	assert(oldversion < version);
11188 
11189 	ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
11190 	if (ret != 0)
11191 		return (ret);
11192 
11193 	if (unsupp_fs) {
11194 		(void) fprintf(stderr, gettext("Upgrade not performed due "
11195 		    "to %d unsupported filesystems (max v%d).\n"),
11196 		    unsupp_fs, (int)ZPL_VERSION);
11197 		return (1);
11198 	}
11199 
11200 	if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
11201 		(void) fprintf(stderr, gettext("Upgrade not performed because "
11202 		    "'compatibility' property set to '"
11203 		    ZPOOL_COMPAT_LEGACY "'.\n"));
11204 		return (1);
11205 	}
11206 
11207 	ret = zpool_upgrade(zhp, version);
11208 	if (ret != 0)
11209 		return (ret);
11210 
11211 	if (version >= SPA_VERSION_FEATURES) {
11212 		(void) printf(gettext("Successfully upgraded "
11213 		    "'%s' from version %llu to feature flags.\n"),
11214 		    zpool_get_name(zhp), (u_longlong_t)oldversion);
11215 	} else {
11216 		(void) printf(gettext("Successfully upgraded "
11217 		    "'%s' from version %llu to version %llu.\n"),
11218 		    zpool_get_name(zhp), (u_longlong_t)oldversion,
11219 		    (u_longlong_t)version);
11220 	}
11221 
11222 	return (0);
11223 }
11224 
11225 static int
11226 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
11227 {
11228 	int i, ret, count;
11229 	boolean_t firstff = B_TRUE;
11230 	nvlist_t *enabled = zpool_get_features(zhp);
11231 
11232 	char compat[ZFS_MAXPROPLEN];
11233 	if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11234 	    ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11235 		compat[0] = '\0';
11236 
11237 	boolean_t requested_features[SPA_FEATURES];
11238 	if (zpool_do_load_compat(compat, requested_features) !=
11239 	    ZPOOL_COMPATIBILITY_OK)
11240 		return (-1);
11241 
11242 	count = 0;
11243 	for (i = 0; i < SPA_FEATURES; i++) {
11244 		const char *fname = spa_feature_table[i].fi_uname;
11245 		const char *fguid = spa_feature_table[i].fi_guid;
11246 
11247 		if (!spa_feature_table[i].fi_zfs_mod_supported)
11248 			continue;
11249 
11250 		if (!nvlist_exists(enabled, fguid) && requested_features[i]) {
11251 			char *propname;
11252 			verify(-1 != asprintf(&propname, "feature@%s", fname));
11253 			ret = zpool_set_prop(zhp, propname,
11254 			    ZFS_FEATURE_ENABLED);
11255 			if (ret != 0) {
11256 				free(propname);
11257 				return (ret);
11258 			}
11259 			count++;
11260 
11261 			if (firstff) {
11262 				(void) printf(gettext("Enabled the "
11263 				    "following features on '%s':\n"),
11264 				    zpool_get_name(zhp));
11265 				firstff = B_FALSE;
11266 			}
11267 			(void) printf(gettext("  %s\n"), fname);
11268 			free(propname);
11269 		}
11270 	}
11271 
11272 	if (countp != NULL)
11273 		*countp = count;
11274 	return (0);
11275 }
11276 
11277 static int
11278 upgrade_cb(zpool_handle_t *zhp, void *arg)
11279 {
11280 	upgrade_cbdata_t *cbp = arg;
11281 	nvlist_t *config;
11282 	uint64_t version;
11283 	boolean_t modified_pool = B_FALSE;
11284 	int ret;
11285 
11286 	config = zpool_get_config(zhp, NULL);
11287 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11288 	    &version) == 0);
11289 
11290 	assert(SPA_VERSION_IS_SUPPORTED(version));
11291 
11292 	if (version < cbp->cb_version) {
11293 		cbp->cb_first = B_FALSE;
11294 		ret = upgrade_version(zhp, cbp->cb_version);
11295 		if (ret != 0)
11296 			return (ret);
11297 		modified_pool = B_TRUE;
11298 
11299 		/*
11300 		 * If they did "zpool upgrade -a", then we could
11301 		 * be doing ioctls to different pools.  We need
11302 		 * to log this history once to each pool, and bypass
11303 		 * the normal history logging that happens in main().
11304 		 */
11305 		(void) zpool_log_history(g_zfs, history_str);
11306 		log_history = B_FALSE;
11307 	}
11308 
11309 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
11310 		int count;
11311 		ret = upgrade_enable_all(zhp, &count);
11312 		if (ret != 0)
11313 			return (ret);
11314 
11315 		if (count > 0) {
11316 			cbp->cb_first = B_FALSE;
11317 			modified_pool = B_TRUE;
11318 		}
11319 	}
11320 
11321 	if (modified_pool) {
11322 		(void) printf("\n");
11323 		(void) after_zpool_upgrade(zhp);
11324 	}
11325 
11326 	return (0);
11327 }
11328 
11329 static int
11330 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
11331 {
11332 	upgrade_cbdata_t *cbp = arg;
11333 	nvlist_t *config;
11334 	uint64_t version;
11335 
11336 	config = zpool_get_config(zhp, NULL);
11337 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11338 	    &version) == 0);
11339 
11340 	assert(SPA_VERSION_IS_SUPPORTED(version));
11341 
11342 	if (version < SPA_VERSION_FEATURES) {
11343 		if (cbp->cb_first) {
11344 			(void) printf(gettext("The following pools are "
11345 			    "formatted with legacy version numbers and can\n"
11346 			    "be upgraded to use feature flags.  After "
11347 			    "being upgraded, these pools\nwill no "
11348 			    "longer be accessible by software that does not "
11349 			    "support feature\nflags.\n\n"
11350 			    "Note that setting a pool's 'compatibility' "
11351 			    "feature to '" ZPOOL_COMPAT_LEGACY "' will\n"
11352 			    "inhibit upgrades.\n\n"));
11353 			(void) printf(gettext("VER  POOL\n"));
11354 			(void) printf(gettext("---  ------------\n"));
11355 			cbp->cb_first = B_FALSE;
11356 		}
11357 
11358 		(void) printf("%2llu   %s\n", (u_longlong_t)version,
11359 		    zpool_get_name(zhp));
11360 	}
11361 
11362 	return (0);
11363 }
11364 
11365 static int
11366 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
11367 {
11368 	upgrade_cbdata_t *cbp = arg;
11369 	nvlist_t *config;
11370 	uint64_t version;
11371 
11372 	config = zpool_get_config(zhp, NULL);
11373 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11374 	    &version) == 0);
11375 
11376 	if (version >= SPA_VERSION_FEATURES) {
11377 		int i;
11378 		boolean_t poolfirst = B_TRUE;
11379 		nvlist_t *enabled = zpool_get_features(zhp);
11380 
11381 		for (i = 0; i < SPA_FEATURES; i++) {
11382 			const char *fguid = spa_feature_table[i].fi_guid;
11383 			const char *fname = spa_feature_table[i].fi_uname;
11384 
11385 			if (!spa_feature_table[i].fi_zfs_mod_supported)
11386 				continue;
11387 
11388 			if (!nvlist_exists(enabled, fguid)) {
11389 				if (cbp->cb_first) {
11390 					(void) printf(gettext("\nSome "
11391 					    "supported features are not "
11392 					    "enabled on the following pools. "
11393 					    "Once a\nfeature is enabled the "
11394 					    "pool may become incompatible with "
11395 					    "software\nthat does not support "
11396 					    "the feature. See "
11397 					    "zpool-features(7) for "
11398 					    "details.\n\n"
11399 					    "Note that the pool "
11400 					    "'compatibility' feature can be "
11401 					    "used to inhibit\nfeature "
11402 					    "upgrades.\n\n"));
11403 					(void) printf(gettext("POOL  "
11404 					    "FEATURE\n"));
11405 					(void) printf(gettext("------"
11406 					    "---------\n"));
11407 					cbp->cb_first = B_FALSE;
11408 				}
11409 
11410 				if (poolfirst) {
11411 					(void) printf(gettext("%s\n"),
11412 					    zpool_get_name(zhp));
11413 					poolfirst = B_FALSE;
11414 				}
11415 
11416 				(void) printf(gettext("      %s\n"), fname);
11417 			}
11418 			/*
11419 			 * If they did "zpool upgrade -a", then we could
11420 			 * be doing ioctls to different pools.  We need
11421 			 * to log this history once to each pool, and bypass
11422 			 * the normal history logging that happens in main().
11423 			 */
11424 			(void) zpool_log_history(g_zfs, history_str);
11425 			log_history = B_FALSE;
11426 		}
11427 	}
11428 
11429 	return (0);
11430 }
11431 
11432 static int
11433 upgrade_one(zpool_handle_t *zhp, void *data)
11434 {
11435 	boolean_t modified_pool = B_FALSE;
11436 	upgrade_cbdata_t *cbp = data;
11437 	uint64_t cur_version;
11438 	int ret;
11439 
11440 	if (strcmp("log", zpool_get_name(zhp)) == 0) {
11441 		(void) fprintf(stderr, gettext("'log' is now a reserved word\n"
11442 		    "Pool 'log' must be renamed using export and import"
11443 		    " to upgrade.\n"));
11444 		return (1);
11445 	}
11446 
11447 	cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
11448 	if (cur_version > cbp->cb_version) {
11449 		(void) printf(gettext("Pool '%s' is already formatted "
11450 		    "using more current version '%llu'.\n\n"),
11451 		    zpool_get_name(zhp), (u_longlong_t)cur_version);
11452 		return (0);
11453 	}
11454 
11455 	if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
11456 		(void) printf(gettext("Pool '%s' is already formatted "
11457 		    "using version %llu.\n\n"), zpool_get_name(zhp),
11458 		    (u_longlong_t)cbp->cb_version);
11459 		return (0);
11460 	}
11461 
11462 	if (cur_version != cbp->cb_version) {
11463 		modified_pool = B_TRUE;
11464 		ret = upgrade_version(zhp, cbp->cb_version);
11465 		if (ret != 0)
11466 			return (ret);
11467 	}
11468 
11469 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
11470 		int count = 0;
11471 		ret = upgrade_enable_all(zhp, &count);
11472 		if (ret != 0)
11473 			return (ret);
11474 
11475 		if (count != 0) {
11476 			modified_pool = B_TRUE;
11477 		} else if (cur_version == SPA_VERSION) {
11478 			(void) printf(gettext("Pool '%s' already has all "
11479 			    "supported and requested features enabled.\n"),
11480 			    zpool_get_name(zhp));
11481 		}
11482 	}
11483 
11484 	if (modified_pool) {
11485 		(void) printf("\n");
11486 		(void) after_zpool_upgrade(zhp);
11487 	}
11488 
11489 	return (0);
11490 }
11491 
11492 /*
11493  * zpool upgrade
11494  * zpool upgrade -v
11495  * zpool upgrade [-V version] <-a | pool ...>
11496  *
11497  * With no arguments, display downrev'd ZFS pool available for upgrade.
11498  * Individual pools can be upgraded by specifying the pool, and '-a' will
11499  * upgrade all pools.
11500  */
11501 int
11502 zpool_do_upgrade(int argc, char **argv)
11503 {
11504 	int c;
11505 	upgrade_cbdata_t cb = { 0 };
11506 	int ret = 0;
11507 	boolean_t showversions = B_FALSE;
11508 	boolean_t upgradeall = B_FALSE;
11509 	char *end;
11510 
11511 
11512 	/* check options */
11513 	while ((c = getopt(argc, argv, ":avV:")) != -1) {
11514 		switch (c) {
11515 		case 'a':
11516 			upgradeall = B_TRUE;
11517 			break;
11518 		case 'v':
11519 			showversions = B_TRUE;
11520 			break;
11521 		case 'V':
11522 			cb.cb_version = strtoll(optarg, &end, 10);
11523 			if (*end != '\0' ||
11524 			    !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
11525 				(void) fprintf(stderr,
11526 				    gettext("invalid version '%s'\n"), optarg);
11527 				usage(B_FALSE);
11528 			}
11529 			break;
11530 		case ':':
11531 			(void) fprintf(stderr, gettext("missing argument for "
11532 			    "'%c' option\n"), optopt);
11533 			usage(B_FALSE);
11534 			break;
11535 		case '?':
11536 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
11537 			    optopt);
11538 			usage(B_FALSE);
11539 		}
11540 	}
11541 
11542 	cb.cb_argc = argc;
11543 	cb.cb_argv = argv;
11544 	argc -= optind;
11545 	argv += optind;
11546 
11547 	if (cb.cb_version == 0) {
11548 		cb.cb_version = SPA_VERSION;
11549 	} else if (!upgradeall && argc == 0) {
11550 		(void) fprintf(stderr, gettext("-V option is "
11551 		    "incompatible with other arguments\n"));
11552 		usage(B_FALSE);
11553 	}
11554 
11555 	if (showversions) {
11556 		if (upgradeall || argc != 0) {
11557 			(void) fprintf(stderr, gettext("-v option is "
11558 			    "incompatible with other arguments\n"));
11559 			usage(B_FALSE);
11560 		}
11561 	} else if (upgradeall) {
11562 		if (argc != 0) {
11563 			(void) fprintf(stderr, gettext("-a option should not "
11564 			    "be used along with a pool name\n"));
11565 			usage(B_FALSE);
11566 		}
11567 	}
11568 
11569 	(void) printf("%s", gettext("This system supports ZFS pool feature "
11570 	    "flags.\n\n"));
11571 	if (showversions) {
11572 		int i;
11573 
11574 		(void) printf(gettext("The following features are "
11575 		    "supported:\n\n"));
11576 		(void) printf(gettext("FEAT DESCRIPTION\n"));
11577 		(void) printf("----------------------------------------------"
11578 		    "---------------\n");
11579 		for (i = 0; i < SPA_FEATURES; i++) {
11580 			zfeature_info_t *fi = &spa_feature_table[i];
11581 			if (!fi->fi_zfs_mod_supported)
11582 				continue;
11583 			const char *ro =
11584 			    (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
11585 			    " (read-only compatible)" : "";
11586 
11587 			(void) printf("%-37s%s\n", fi->fi_uname, ro);
11588 			(void) printf("     %s\n", fi->fi_desc);
11589 		}
11590 		(void) printf("\n");
11591 
11592 		(void) printf(gettext("The following legacy versions are also "
11593 		    "supported:\n\n"));
11594 		(void) printf(gettext("VER  DESCRIPTION\n"));
11595 		(void) printf("---  -----------------------------------------"
11596 		    "---------------\n");
11597 		(void) printf(gettext(" 1   Initial ZFS version\n"));
11598 		(void) printf(gettext(" 2   Ditto blocks "
11599 		    "(replicated metadata)\n"));
11600 		(void) printf(gettext(" 3   Hot spares and double parity "
11601 		    "RAID-Z\n"));
11602 		(void) printf(gettext(" 4   zpool history\n"));
11603 		(void) printf(gettext(" 5   Compression using the gzip "
11604 		    "algorithm\n"));
11605 		(void) printf(gettext(" 6   bootfs pool property\n"));
11606 		(void) printf(gettext(" 7   Separate intent log devices\n"));
11607 		(void) printf(gettext(" 8   Delegated administration\n"));
11608 		(void) printf(gettext(" 9   refquota and refreservation "
11609 		    "properties\n"));
11610 		(void) printf(gettext(" 10  Cache devices\n"));
11611 		(void) printf(gettext(" 11  Improved scrub performance\n"));
11612 		(void) printf(gettext(" 12  Snapshot properties\n"));
11613 		(void) printf(gettext(" 13  snapused property\n"));
11614 		(void) printf(gettext(" 14  passthrough-x aclinherit\n"));
11615 		(void) printf(gettext(" 15  user/group space accounting\n"));
11616 		(void) printf(gettext(" 16  stmf property support\n"));
11617 		(void) printf(gettext(" 17  Triple-parity RAID-Z\n"));
11618 		(void) printf(gettext(" 18  Snapshot user holds\n"));
11619 		(void) printf(gettext(" 19  Log device removal\n"));
11620 		(void) printf(gettext(" 20  Compression using zle "
11621 		    "(zero-length encoding)\n"));
11622 		(void) printf(gettext(" 21  Deduplication\n"));
11623 		(void) printf(gettext(" 22  Received properties\n"));
11624 		(void) printf(gettext(" 23  Slim ZIL\n"));
11625 		(void) printf(gettext(" 24  System attributes\n"));
11626 		(void) printf(gettext(" 25  Improved scrub stats\n"));
11627 		(void) printf(gettext(" 26  Improved snapshot deletion "
11628 		    "performance\n"));
11629 		(void) printf(gettext(" 27  Improved snapshot creation "
11630 		    "performance\n"));
11631 		(void) printf(gettext(" 28  Multiple vdev replacements\n"));
11632 		(void) printf(gettext("\nFor more information on a particular "
11633 		    "version, including supported releases,\n"));
11634 		(void) printf(gettext("see the ZFS Administration Guide.\n\n"));
11635 	} else if (argc == 0 && upgradeall) {
11636 		cb.cb_first = B_TRUE;
11637 		ret = zpool_iter(g_zfs, upgrade_cb, &cb);
11638 		if (ret == 0 && cb.cb_first) {
11639 			if (cb.cb_version == SPA_VERSION) {
11640 				(void) printf(gettext("All pools are already "
11641 				    "formatted using feature flags.\n\n"));
11642 				(void) printf(gettext("Every feature flags "
11643 				    "pool already has all supported and "
11644 				    "requested features enabled.\n"));
11645 			} else {
11646 				(void) printf(gettext("All pools are already "
11647 				    "formatted with version %llu or higher.\n"),
11648 				    (u_longlong_t)cb.cb_version);
11649 			}
11650 		}
11651 	} else if (argc == 0) {
11652 		cb.cb_first = B_TRUE;
11653 		ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
11654 		assert(ret == 0);
11655 
11656 		if (cb.cb_first) {
11657 			(void) printf(gettext("All pools are formatted "
11658 			    "using feature flags.\n\n"));
11659 		} else {
11660 			(void) printf(gettext("\nUse 'zpool upgrade -v' "
11661 			    "for a list of available legacy versions.\n"));
11662 		}
11663 
11664 		cb.cb_first = B_TRUE;
11665 		ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
11666 		assert(ret == 0);
11667 
11668 		if (cb.cb_first) {
11669 			(void) printf(gettext("Every feature flags pool has "
11670 			    "all supported and requested features enabled.\n"));
11671 		} else {
11672 			(void) printf(gettext("\n"));
11673 		}
11674 	} else {
11675 		ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
11676 		    B_FALSE, upgrade_one, &cb);
11677 	}
11678 
11679 	return (ret);
11680 }
11681 
11682 typedef struct hist_cbdata {
11683 	boolean_t first;
11684 	boolean_t longfmt;
11685 	boolean_t internal;
11686 } hist_cbdata_t;
11687 
11688 static void
11689 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
11690 {
11691 	nvlist_t **records;
11692 	uint_t numrecords;
11693 	int i;
11694 
11695 	verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
11696 	    &records, &numrecords) == 0);
11697 	for (i = 0; i < numrecords; i++) {
11698 		nvlist_t *rec = records[i];
11699 		char tbuf[64] = "";
11700 
11701 		if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
11702 			time_t tsec;
11703 			struct tm t;
11704 
11705 			tsec = fnvlist_lookup_uint64(records[i],
11706 			    ZPOOL_HIST_TIME);
11707 			(void) localtime_r(&tsec, &t);
11708 			(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
11709 		}
11710 
11711 		if (nvlist_exists(rec, ZPOOL_HIST_ELAPSED_NS)) {
11712 			uint64_t elapsed_ns = fnvlist_lookup_int64(records[i],
11713 			    ZPOOL_HIST_ELAPSED_NS);
11714 			(void) snprintf(tbuf + strlen(tbuf),
11715 			    sizeof (tbuf) - strlen(tbuf),
11716 			    " (%lldms)", (long long)elapsed_ns / 1000 / 1000);
11717 		}
11718 
11719 		if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
11720 			(void) printf("%s %s", tbuf,
11721 			    fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
11722 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
11723 			int ievent =
11724 			    fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
11725 			if (!cb->internal)
11726 				continue;
11727 			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
11728 				(void) printf("%s unrecognized record:\n",
11729 				    tbuf);
11730 				dump_nvlist(rec, 4);
11731 				continue;
11732 			}
11733 			(void) printf("%s [internal %s txg:%lld] %s", tbuf,
11734 			    zfs_history_event_names[ievent],
11735 			    (longlong_t)fnvlist_lookup_uint64(
11736 			    rec, ZPOOL_HIST_TXG),
11737 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
11738 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
11739 			if (!cb->internal)
11740 				continue;
11741 			(void) printf("%s [txg:%lld] %s", tbuf,
11742 			    (longlong_t)fnvlist_lookup_uint64(
11743 			    rec, ZPOOL_HIST_TXG),
11744 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
11745 			if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
11746 				(void) printf(" %s (%llu)",
11747 				    fnvlist_lookup_string(rec,
11748 				    ZPOOL_HIST_DSNAME),
11749 				    (u_longlong_t)fnvlist_lookup_uint64(rec,
11750 				    ZPOOL_HIST_DSID));
11751 			}
11752 			(void) printf(" %s", fnvlist_lookup_string(rec,
11753 			    ZPOOL_HIST_INT_STR));
11754 		} else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
11755 			if (!cb->internal)
11756 				continue;
11757 			(void) printf("%s ioctl %s\n", tbuf,
11758 			    fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
11759 			if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
11760 				(void) printf("    input:\n");
11761 				dump_nvlist(fnvlist_lookup_nvlist(rec,
11762 				    ZPOOL_HIST_INPUT_NVL), 8);
11763 			}
11764 			if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
11765 				(void) printf("    output:\n");
11766 				dump_nvlist(fnvlist_lookup_nvlist(rec,
11767 				    ZPOOL_HIST_OUTPUT_NVL), 8);
11768 			}
11769 			if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_SIZE)) {
11770 				(void) printf("    output nvlist omitted; "
11771 				    "original size: %lldKB\n",
11772 				    (longlong_t)fnvlist_lookup_int64(rec,
11773 				    ZPOOL_HIST_OUTPUT_SIZE) / 1024);
11774 			}
11775 			if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
11776 				(void) printf("    errno: %lld\n",
11777 				    (longlong_t)fnvlist_lookup_int64(rec,
11778 				    ZPOOL_HIST_ERRNO));
11779 			}
11780 		} else {
11781 			if (!cb->internal)
11782 				continue;
11783 			(void) printf("%s unrecognized record:\n", tbuf);
11784 			dump_nvlist(rec, 4);
11785 		}
11786 
11787 		if (!cb->longfmt) {
11788 			(void) printf("\n");
11789 			continue;
11790 		}
11791 		(void) printf(" [");
11792 		if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
11793 			uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
11794 			struct passwd *pwd = getpwuid(who);
11795 			(void) printf("user %d ", (int)who);
11796 			if (pwd != NULL)
11797 				(void) printf("(%s) ", pwd->pw_name);
11798 		}
11799 		if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
11800 			(void) printf("on %s",
11801 			    fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
11802 		}
11803 		if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
11804 			(void) printf(":%s",
11805 			    fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
11806 		}
11807 
11808 		(void) printf("]");
11809 		(void) printf("\n");
11810 	}
11811 }
11812 
11813 /*
11814  * Print out the command history for a specific pool.
11815  */
11816 static int
11817 get_history_one(zpool_handle_t *zhp, void *data)
11818 {
11819 	nvlist_t *nvhis;
11820 	int ret;
11821 	hist_cbdata_t *cb = (hist_cbdata_t *)data;
11822 	uint64_t off = 0;
11823 	boolean_t eof = B_FALSE;
11824 
11825 	cb->first = B_FALSE;
11826 
11827 	(void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
11828 
11829 	while (!eof) {
11830 		if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
11831 			return (ret);
11832 
11833 		print_history_records(nvhis, cb);
11834 		nvlist_free(nvhis);
11835 	}
11836 	(void) printf("\n");
11837 
11838 	return (ret);
11839 }
11840 
11841 /*
11842  * zpool history <pool>
11843  *
11844  * Displays the history of commands that modified pools.
11845  */
11846 int
11847 zpool_do_history(int argc, char **argv)
11848 {
11849 	hist_cbdata_t cbdata = { 0 };
11850 	int ret;
11851 	int c;
11852 
11853 	cbdata.first = B_TRUE;
11854 	/* check options */
11855 	while ((c = getopt(argc, argv, "li")) != -1) {
11856 		switch (c) {
11857 		case 'l':
11858 			cbdata.longfmt = B_TRUE;
11859 			break;
11860 		case 'i':
11861 			cbdata.internal = B_TRUE;
11862 			break;
11863 		case '?':
11864 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
11865 			    optopt);
11866 			usage(B_FALSE);
11867 		}
11868 	}
11869 	argc -= optind;
11870 	argv += optind;
11871 
11872 	ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
11873 	    B_FALSE, get_history_one, &cbdata);
11874 
11875 	if (argc == 0 && cbdata.first == B_TRUE) {
11876 		(void) fprintf(stderr, gettext("no pools available\n"));
11877 		return (0);
11878 	}
11879 
11880 	return (ret);
11881 }
11882 
11883 typedef struct ev_opts {
11884 	int verbose;
11885 	int scripted;
11886 	int follow;
11887 	int clear;
11888 	char poolname[ZFS_MAX_DATASET_NAME_LEN];
11889 } ev_opts_t;
11890 
11891 static void
11892 zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
11893 {
11894 	char ctime_str[26], str[32];
11895 	const char *ptr;
11896 	int64_t *tv;
11897 	uint_t n;
11898 
11899 	verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
11900 	memset(str, ' ', 32);
11901 	(void) ctime_r((const time_t *)&tv[0], ctime_str);
11902 	(void) memcpy(str, ctime_str+4,  6);		/* 'Jun 30' */
11903 	(void) memcpy(str+7, ctime_str+20, 4);		/* '1993' */
11904 	(void) memcpy(str+12, ctime_str+11, 8);		/* '21:49:08' */
11905 	(void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
11906 	if (opts->scripted)
11907 		(void) printf(gettext("%s\t"), str);
11908 	else
11909 		(void) printf(gettext("%s "), str);
11910 
11911 	verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
11912 	(void) printf(gettext("%s\n"), ptr);
11913 }
11914 
11915 static void
11916 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
11917 {
11918 	nvpair_t *nvp;
11919 
11920 	for (nvp = nvlist_next_nvpair(nvl, NULL);
11921 	    nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
11922 
11923 		data_type_t type = nvpair_type(nvp);
11924 		const char *name = nvpair_name(nvp);
11925 
11926 		boolean_t b;
11927 		uint8_t i8;
11928 		uint16_t i16;
11929 		uint32_t i32;
11930 		uint64_t i64;
11931 		const char *str;
11932 		nvlist_t *cnv;
11933 
11934 		printf(gettext("%*s%s = "), depth, "", name);
11935 
11936 		switch (type) {
11937 		case DATA_TYPE_BOOLEAN:
11938 			printf(gettext("%s"), "1");
11939 			break;
11940 
11941 		case DATA_TYPE_BOOLEAN_VALUE:
11942 			(void) nvpair_value_boolean_value(nvp, &b);
11943 			printf(gettext("%s"), b ? "1" : "0");
11944 			break;
11945 
11946 		case DATA_TYPE_BYTE:
11947 			(void) nvpair_value_byte(nvp, &i8);
11948 			printf(gettext("0x%x"), i8);
11949 			break;
11950 
11951 		case DATA_TYPE_INT8:
11952 			(void) nvpair_value_int8(nvp, (void *)&i8);
11953 			printf(gettext("0x%x"), i8);
11954 			break;
11955 
11956 		case DATA_TYPE_UINT8:
11957 			(void) nvpair_value_uint8(nvp, &i8);
11958 			printf(gettext("0x%x"), i8);
11959 			break;
11960 
11961 		case DATA_TYPE_INT16:
11962 			(void) nvpair_value_int16(nvp, (void *)&i16);
11963 			printf(gettext("0x%x"), i16);
11964 			break;
11965 
11966 		case DATA_TYPE_UINT16:
11967 			(void) nvpair_value_uint16(nvp, &i16);
11968 			printf(gettext("0x%x"), i16);
11969 			break;
11970 
11971 		case DATA_TYPE_INT32:
11972 			(void) nvpair_value_int32(nvp, (void *)&i32);
11973 			printf(gettext("0x%x"), i32);
11974 			break;
11975 
11976 		case DATA_TYPE_UINT32:
11977 			(void) nvpair_value_uint32(nvp, &i32);
11978 			printf(gettext("0x%x"), i32);
11979 			break;
11980 
11981 		case DATA_TYPE_INT64:
11982 			(void) nvpair_value_int64(nvp, (void *)&i64);
11983 			printf(gettext("0x%llx"), (u_longlong_t)i64);
11984 			break;
11985 
11986 		case DATA_TYPE_UINT64:
11987 			(void) nvpair_value_uint64(nvp, &i64);
11988 			/*
11989 			 * translate vdev state values to readable
11990 			 * strings to aide zpool events consumers
11991 			 */
11992 			if (strcmp(name,
11993 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
11994 			    strcmp(name,
11995 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
11996 				printf(gettext("\"%s\" (0x%llx)"),
11997 				    zpool_state_to_name(i64, VDEV_AUX_NONE),
11998 				    (u_longlong_t)i64);
11999 			} else {
12000 				printf(gettext("0x%llx"), (u_longlong_t)i64);
12001 			}
12002 			break;
12003 
12004 		case DATA_TYPE_HRTIME:
12005 			(void) nvpair_value_hrtime(nvp, (void *)&i64);
12006 			printf(gettext("0x%llx"), (u_longlong_t)i64);
12007 			break;
12008 
12009 		case DATA_TYPE_STRING:
12010 			(void) nvpair_value_string(nvp, &str);
12011 			printf(gettext("\"%s\""), str ? str : "<NULL>");
12012 			break;
12013 
12014 		case DATA_TYPE_NVLIST:
12015 			printf(gettext("(embedded nvlist)\n"));
12016 			(void) nvpair_value_nvlist(nvp, &cnv);
12017 			zpool_do_events_nvprint(cnv, depth + 8);
12018 			printf(gettext("%*s(end %s)"), depth, "", name);
12019 			break;
12020 
12021 		case DATA_TYPE_NVLIST_ARRAY: {
12022 			nvlist_t **val;
12023 			uint_t i, nelem;
12024 
12025 			(void) nvpair_value_nvlist_array(nvp, &val, &nelem);
12026 			printf(gettext("(%d embedded nvlists)\n"), nelem);
12027 			for (i = 0; i < nelem; i++) {
12028 				printf(gettext("%*s%s[%d] = %s\n"),
12029 				    depth, "", name, i, "(embedded nvlist)");
12030 				zpool_do_events_nvprint(val[i], depth + 8);
12031 				printf(gettext("%*s(end %s[%i])\n"),
12032 				    depth, "", name, i);
12033 			}
12034 			printf(gettext("%*s(end %s)\n"), depth, "", name);
12035 			}
12036 			break;
12037 
12038 		case DATA_TYPE_INT8_ARRAY: {
12039 			int8_t *val;
12040 			uint_t i, nelem;
12041 
12042 			(void) nvpair_value_int8_array(nvp, &val, &nelem);
12043 			for (i = 0; i < nelem; i++)
12044 				printf(gettext("0x%x "), val[i]);
12045 
12046 			break;
12047 			}
12048 
12049 		case DATA_TYPE_UINT8_ARRAY: {
12050 			uint8_t *val;
12051 			uint_t i, nelem;
12052 
12053 			(void) nvpair_value_uint8_array(nvp, &val, &nelem);
12054 			for (i = 0; i < nelem; i++)
12055 				printf(gettext("0x%x "), val[i]);
12056 
12057 			break;
12058 			}
12059 
12060 		case DATA_TYPE_INT16_ARRAY: {
12061 			int16_t *val;
12062 			uint_t i, nelem;
12063 
12064 			(void) nvpair_value_int16_array(nvp, &val, &nelem);
12065 			for (i = 0; i < nelem; i++)
12066 				printf(gettext("0x%x "), val[i]);
12067 
12068 			break;
12069 			}
12070 
12071 		case DATA_TYPE_UINT16_ARRAY: {
12072 			uint16_t *val;
12073 			uint_t i, nelem;
12074 
12075 			(void) nvpair_value_uint16_array(nvp, &val, &nelem);
12076 			for (i = 0; i < nelem; i++)
12077 				printf(gettext("0x%x "), val[i]);
12078 
12079 			break;
12080 			}
12081 
12082 		case DATA_TYPE_INT32_ARRAY: {
12083 			int32_t *val;
12084 			uint_t i, nelem;
12085 
12086 			(void) nvpair_value_int32_array(nvp, &val, &nelem);
12087 			for (i = 0; i < nelem; i++)
12088 				printf(gettext("0x%x "), val[i]);
12089 
12090 			break;
12091 			}
12092 
12093 		case DATA_TYPE_UINT32_ARRAY: {
12094 			uint32_t *val;
12095 			uint_t i, nelem;
12096 
12097 			(void) nvpair_value_uint32_array(nvp, &val, &nelem);
12098 			for (i = 0; i < nelem; i++)
12099 				printf(gettext("0x%x "), val[i]);
12100 
12101 			break;
12102 			}
12103 
12104 		case DATA_TYPE_INT64_ARRAY: {
12105 			int64_t *val;
12106 			uint_t i, nelem;
12107 
12108 			(void) nvpair_value_int64_array(nvp, &val, &nelem);
12109 			for (i = 0; i < nelem; i++)
12110 				printf(gettext("0x%llx "),
12111 				    (u_longlong_t)val[i]);
12112 
12113 			break;
12114 			}
12115 
12116 		case DATA_TYPE_UINT64_ARRAY: {
12117 			uint64_t *val;
12118 			uint_t i, nelem;
12119 
12120 			(void) nvpair_value_uint64_array(nvp, &val, &nelem);
12121 			for (i = 0; i < nelem; i++)
12122 				printf(gettext("0x%llx "),
12123 				    (u_longlong_t)val[i]);
12124 
12125 			break;
12126 			}
12127 
12128 		case DATA_TYPE_STRING_ARRAY: {
12129 			const char **str;
12130 			uint_t i, nelem;
12131 
12132 			(void) nvpair_value_string_array(nvp, &str, &nelem);
12133 			for (i = 0; i < nelem; i++)
12134 				printf(gettext("\"%s\" "),
12135 				    str[i] ? str[i] : "<NULL>");
12136 
12137 			break;
12138 			}
12139 
12140 		case DATA_TYPE_BOOLEAN_ARRAY:
12141 		case DATA_TYPE_BYTE_ARRAY:
12142 		case DATA_TYPE_DOUBLE:
12143 		case DATA_TYPE_DONTCARE:
12144 		case DATA_TYPE_UNKNOWN:
12145 			printf(gettext("<unknown>"));
12146 			break;
12147 		}
12148 
12149 		printf(gettext("\n"));
12150 	}
12151 }
12152 
12153 static int
12154 zpool_do_events_next(ev_opts_t *opts)
12155 {
12156 	nvlist_t *nvl;
12157 	int zevent_fd, ret, dropped;
12158 	const char *pool;
12159 
12160 	zevent_fd = open(ZFS_DEV, O_RDWR);
12161 	VERIFY(zevent_fd >= 0);
12162 
12163 	if (!opts->scripted)
12164 		(void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
12165 
12166 	while (1) {
12167 		ret = zpool_events_next(g_zfs, &nvl, &dropped,
12168 		    (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
12169 		if (ret || nvl == NULL)
12170 			break;
12171 
12172 		if (dropped > 0)
12173 			(void) printf(gettext("dropped %d events\n"), dropped);
12174 
12175 		if (strlen(opts->poolname) > 0 &&
12176 		    nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
12177 		    strcmp(opts->poolname, pool) != 0)
12178 			continue;
12179 
12180 		zpool_do_events_short(nvl, opts);
12181 
12182 		if (opts->verbose) {
12183 			zpool_do_events_nvprint(nvl, 8);
12184 			printf(gettext("\n"));
12185 		}
12186 		(void) fflush(stdout);
12187 
12188 		nvlist_free(nvl);
12189 	}
12190 
12191 	VERIFY(0 == close(zevent_fd));
12192 
12193 	return (ret);
12194 }
12195 
12196 static int
12197 zpool_do_events_clear(void)
12198 {
12199 	int count, ret;
12200 
12201 	ret = zpool_events_clear(g_zfs, &count);
12202 	if (!ret)
12203 		(void) printf(gettext("cleared %d events\n"), count);
12204 
12205 	return (ret);
12206 }
12207 
12208 /*
12209  * zpool events [-vHf [pool] | -c]
12210  *
12211  * Displays events logs by ZFS.
12212  */
12213 int
12214 zpool_do_events(int argc, char **argv)
12215 {
12216 	ev_opts_t opts = { 0 };
12217 	int ret;
12218 	int c;
12219 
12220 	/* check options */
12221 	while ((c = getopt(argc, argv, "vHfc")) != -1) {
12222 		switch (c) {
12223 		case 'v':
12224 			opts.verbose = 1;
12225 			break;
12226 		case 'H':
12227 			opts.scripted = 1;
12228 			break;
12229 		case 'f':
12230 			opts.follow = 1;
12231 			break;
12232 		case 'c':
12233 			opts.clear = 1;
12234 			break;
12235 		case '?':
12236 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
12237 			    optopt);
12238 			usage(B_FALSE);
12239 		}
12240 	}
12241 	argc -= optind;
12242 	argv += optind;
12243 
12244 	if (argc > 1) {
12245 		(void) fprintf(stderr, gettext("too many arguments\n"));
12246 		usage(B_FALSE);
12247 	} else if (argc == 1) {
12248 		(void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
12249 		if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
12250 			(void) fprintf(stderr,
12251 			    gettext("invalid pool name '%s'\n"), opts.poolname);
12252 			usage(B_FALSE);
12253 		}
12254 	}
12255 
12256 	if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
12257 	    opts.clear) {
12258 		(void) fprintf(stderr,
12259 		    gettext("invalid options combined with -c\n"));
12260 		usage(B_FALSE);
12261 	}
12262 
12263 	if (opts.clear)
12264 		ret = zpool_do_events_clear();
12265 	else
12266 		ret = zpool_do_events_next(&opts);
12267 
12268 	return (ret);
12269 }
12270 
12271 static int
12272 get_callback_vdev(zpool_handle_t *zhp, char *vdevname, void *data)
12273 {
12274 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12275 	char value[ZFS_MAXPROPLEN];
12276 	zprop_source_t srctype;
12277 	nvlist_t *props, *item, *d;
12278 	props = item = d = NULL;
12279 
12280 	if (cbp->cb_json) {
12281 		d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "vdevs");
12282 		if (d == NULL) {
12283 			fprintf(stderr, "vdevs obj not found.\n");
12284 			exit(1);
12285 		}
12286 		props = fnvlist_alloc();
12287 	}
12288 
12289 	for (zprop_list_t *pl = cbp->cb_proplist; pl != NULL;
12290 	    pl = pl->pl_next) {
12291 		char *prop_name;
12292 		/*
12293 		 * If the first property is pool name, it is a special
12294 		 * placeholder that we can skip. This will also skip
12295 		 * over the name property when 'all' is specified.
12296 		 */
12297 		if (pl->pl_prop == ZPOOL_PROP_NAME &&
12298 		    pl == cbp->cb_proplist)
12299 			continue;
12300 
12301 		if (pl->pl_prop == ZPROP_INVAL) {
12302 			prop_name = pl->pl_user_prop;
12303 		} else {
12304 			prop_name = (char *)vdev_prop_to_name(pl->pl_prop);
12305 		}
12306 		if (zpool_get_vdev_prop(zhp, vdevname, pl->pl_prop,
12307 		    prop_name, value, sizeof (value), &srctype,
12308 		    cbp->cb_literal) == 0) {
12309 			zprop_collect_property(vdevname, cbp, prop_name,
12310 			    value, srctype, NULL, NULL, props);
12311 		}
12312 	}
12313 
12314 	if (cbp->cb_json) {
12315 		if (!nvlist_empty(props)) {
12316 			item = fnvlist_alloc();
12317 			fill_vdev_info(item, zhp, vdevname, B_TRUE,
12318 			    cbp->cb_json_as_int);
12319 			fnvlist_add_nvlist(item, "properties", props);
12320 			fnvlist_add_nvlist(d, vdevname, item);
12321 			fnvlist_add_nvlist(cbp->cb_jsobj, "vdevs", d);
12322 			fnvlist_free(item);
12323 		}
12324 		fnvlist_free(props);
12325 	}
12326 
12327 	return (0);
12328 }
12329 
12330 static int
12331 get_callback_vdev_cb(void *zhp_data, nvlist_t *nv, void *data)
12332 {
12333 	zpool_handle_t *zhp = zhp_data;
12334 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12335 	char *vdevname;
12336 	const char *type;
12337 	int ret;
12338 
12339 	/*
12340 	 * zpool_vdev_name() transforms the root vdev name (i.e., root-0) to the
12341 	 * pool name for display purposes, which is not desired. Fallback to
12342 	 * zpool_vdev_name() when not dealing with the root vdev.
12343 	 */
12344 	type = fnvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE);
12345 	if (zhp != NULL && strcmp(type, "root") == 0)
12346 		vdevname = strdup("root-0");
12347 	else
12348 		vdevname = zpool_vdev_name(g_zfs, zhp, nv,
12349 		    cbp->cb_vdevs.cb_name_flags);
12350 
12351 	(void) vdev_expand_proplist(zhp, vdevname, &cbp->cb_proplist);
12352 
12353 	ret = get_callback_vdev(zhp, vdevname, data);
12354 
12355 	free(vdevname);
12356 
12357 	return (ret);
12358 }
12359 
12360 static int
12361 get_callback(zpool_handle_t *zhp, void *data)
12362 {
12363 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12364 	char value[ZFS_MAXPROPLEN];
12365 	zprop_source_t srctype;
12366 	zprop_list_t *pl;
12367 	int vid;
12368 	int err = 0;
12369 	nvlist_t *props, *item, *d;
12370 	props = item = d = NULL;
12371 
12372 	if (cbp->cb_type == ZFS_TYPE_VDEV) {
12373 		if (cbp->cb_json) {
12374 			nvlist_t *pool = fnvlist_alloc();
12375 			fill_pool_info(pool, zhp, B_FALSE, cbp->cb_json_as_int);
12376 			fnvlist_add_nvlist(cbp->cb_jsobj, "pool", pool);
12377 			fnvlist_free(pool);
12378 		}
12379 
12380 		if (strcmp(cbp->cb_vdevs.cb_names[0], "all-vdevs") == 0) {
12381 			for_each_vdev(zhp, get_callback_vdev_cb, data);
12382 		} else {
12383 			/* Adjust column widths for vdev properties */
12384 			for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
12385 			    vid++) {
12386 				vdev_expand_proplist(zhp,
12387 				    cbp->cb_vdevs.cb_names[vid],
12388 				    &cbp->cb_proplist);
12389 			}
12390 			/* Display the properties */
12391 			for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
12392 			    vid++) {
12393 				get_callback_vdev(zhp,
12394 				    cbp->cb_vdevs.cb_names[vid], data);
12395 			}
12396 		}
12397 	} else {
12398 		assert(cbp->cb_type == ZFS_TYPE_POOL);
12399 		if (cbp->cb_json) {
12400 			d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
12401 			if (d == NULL) {
12402 				fprintf(stderr, "pools obj not found.\n");
12403 				exit(1);
12404 			}
12405 			props = fnvlist_alloc();
12406 		}
12407 		for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
12408 			/*
12409 			 * Skip the special fake placeholder. This will also
12410 			 * skip over the name property when 'all' is specified.
12411 			 */
12412 			if (pl->pl_prop == ZPOOL_PROP_NAME &&
12413 			    pl == cbp->cb_proplist)
12414 				continue;
12415 
12416 			if (pl->pl_prop == ZPROP_INVAL &&
12417 			    zfs_prop_user(pl->pl_user_prop)) {
12418 				srctype = ZPROP_SRC_LOCAL;
12419 
12420 				if (zpool_get_userprop(zhp, pl->pl_user_prop,
12421 				    value, sizeof (value), &srctype) != 0)
12422 					continue;
12423 
12424 				err = zprop_collect_property(
12425 				    zpool_get_name(zhp), cbp, pl->pl_user_prop,
12426 				    value, srctype, NULL, NULL, props);
12427 			} else if (pl->pl_prop == ZPROP_INVAL &&
12428 			    (zpool_prop_feature(pl->pl_user_prop) ||
12429 			    zpool_prop_unsupported(pl->pl_user_prop))) {
12430 				srctype = ZPROP_SRC_LOCAL;
12431 
12432 				if (zpool_prop_get_feature(zhp,
12433 				    pl->pl_user_prop, value,
12434 				    sizeof (value)) == 0) {
12435 					err = zprop_collect_property(
12436 					    zpool_get_name(zhp), cbp,
12437 					    pl->pl_user_prop, value, srctype,
12438 					    NULL, NULL, props);
12439 				}
12440 			} else {
12441 				if (zpool_get_prop(zhp, pl->pl_prop, value,
12442 				    sizeof (value), &srctype,
12443 				    cbp->cb_literal) != 0)
12444 					continue;
12445 
12446 				err = zprop_collect_property(
12447 				    zpool_get_name(zhp), cbp,
12448 				    zpool_prop_to_name(pl->pl_prop),
12449 				    value, srctype, NULL, NULL, props);
12450 			}
12451 			if (err != 0)
12452 				return (err);
12453 		}
12454 
12455 		if (cbp->cb_json) {
12456 			if (!nvlist_empty(props)) {
12457 				item = fnvlist_alloc();
12458 				fill_pool_info(item, zhp, B_TRUE,
12459 				    cbp->cb_json_as_int);
12460 				fnvlist_add_nvlist(item, "properties", props);
12461 				if (cbp->cb_json_pool_key_guid) {
12462 					char buf[256];
12463 					uint64_t guid = fnvlist_lookup_uint64(
12464 					    zpool_get_config(zhp, NULL),
12465 					    ZPOOL_CONFIG_POOL_GUID);
12466 					snprintf(buf, 256, "%llu",
12467 					    (u_longlong_t)guid);
12468 					fnvlist_add_nvlist(d, buf, item);
12469 				} else {
12470 					const char *name = zpool_get_name(zhp);
12471 					fnvlist_add_nvlist(d, name, item);
12472 				}
12473 				fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
12474 				fnvlist_free(item);
12475 			}
12476 			fnvlist_free(props);
12477 		}
12478 	}
12479 
12480 	return (0);
12481 }
12482 
12483 /*
12484  * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
12485  *
12486  *	-H	Scripted mode.  Don't display headers, and separate properties
12487  *		by a single tab.
12488  *	-o	List of columns to display.  Defaults to
12489  *		"name,property,value,source".
12490  * 	-p	Display values in parsable (exact) format.
12491  * 	-j	Display output in JSON format.
12492  * 	--json-int	Display numbers as integers instead of strings.
12493  * 	--json-pool-key-guid	Set pool GUID as key for pool objects.
12494  *
12495  * Get properties of pools in the system. Output space statistics
12496  * for each one as well as other attributes.
12497  */
12498 int
12499 zpool_do_get(int argc, char **argv)
12500 {
12501 	zprop_get_cbdata_t cb = { 0 };
12502 	zprop_list_t fake_name = { 0 };
12503 	int ret;
12504 	int c, i;
12505 	char *propstr = NULL;
12506 	char *vdev = NULL;
12507 	nvlist_t *data = NULL;
12508 
12509 	cb.cb_first = B_TRUE;
12510 
12511 	/*
12512 	 * Set up default columns and sources.
12513 	 */
12514 	cb.cb_sources = ZPROP_SRC_ALL;
12515 	cb.cb_columns[0] = GET_COL_NAME;
12516 	cb.cb_columns[1] = GET_COL_PROPERTY;
12517 	cb.cb_columns[2] = GET_COL_VALUE;
12518 	cb.cb_columns[3] = GET_COL_SOURCE;
12519 	cb.cb_type = ZFS_TYPE_POOL;
12520 	cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
12521 	current_prop_type = cb.cb_type;
12522 
12523 	struct option long_options[] = {
12524 		{"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
12525 		{"json-pool-key-guid", no_argument, NULL,
12526 		    ZPOOL_OPTION_POOL_KEY_GUID},
12527 		{0, 0, 0, 0}
12528 	};
12529 
12530 	/* check options */
12531 	while ((c = getopt_long(argc, argv, ":jHpo:", long_options,
12532 	    NULL)) != -1) {
12533 		switch (c) {
12534 		case 'p':
12535 			cb.cb_literal = B_TRUE;
12536 			break;
12537 		case 'H':
12538 			cb.cb_scripted = B_TRUE;
12539 			break;
12540 		case 'j':
12541 			cb.cb_json = B_TRUE;
12542 			cb.cb_jsobj = zpool_json_schema(0, 1);
12543 			data = fnvlist_alloc();
12544 			break;
12545 		case ZPOOL_OPTION_POOL_KEY_GUID:
12546 			cb.cb_json_pool_key_guid = B_TRUE;
12547 			break;
12548 		case ZPOOL_OPTION_JSON_NUMS_AS_INT:
12549 			cb.cb_json_as_int = B_TRUE;
12550 			cb.cb_literal = B_TRUE;
12551 			break;
12552 		case 'o':
12553 			memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
12554 			i = 0;
12555 
12556 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
12557 				static const char *const col_opts[] =
12558 				{ "name", "property", "value", "source",
12559 				    "all" };
12560 				static const zfs_get_column_t col_cols[] =
12561 				{ GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
12562 				    GET_COL_SOURCE };
12563 
12564 				if (i == ZFS_GET_NCOLS - 1) {
12565 					(void) fprintf(stderr, gettext("too "
12566 					"many fields given to -o "
12567 					"option\n"));
12568 					usage(B_FALSE);
12569 				}
12570 
12571 				for (c = 0; c < ARRAY_SIZE(col_opts); ++c)
12572 					if (strcmp(tok, col_opts[c]) == 0)
12573 						goto found;
12574 
12575 				(void) fprintf(stderr,
12576 				    gettext("invalid column name '%s'\n"), tok);
12577 				usage(B_FALSE);
12578 
12579 found:
12580 				if (c >= 4) {
12581 					if (i > 0) {
12582 						(void) fprintf(stderr,
12583 						    gettext("\"all\" conflicts "
12584 						    "with specific fields "
12585 						    "given to -o option\n"));
12586 						usage(B_FALSE);
12587 					}
12588 
12589 					memcpy(cb.cb_columns, col_cols,
12590 					    sizeof (col_cols));
12591 					i = ZFS_GET_NCOLS - 1;
12592 				} else
12593 					cb.cb_columns[i++] = col_cols[c];
12594 			}
12595 			break;
12596 		case '?':
12597 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
12598 			    optopt);
12599 			usage(B_FALSE);
12600 		}
12601 	}
12602 
12603 	argc -= optind;
12604 	argv += optind;
12605 
12606 	if (!cb.cb_json && cb.cb_json_as_int) {
12607 		(void) fprintf(stderr, gettext("'--json-int' only works with"
12608 		    " '-j' option\n"));
12609 		usage(B_FALSE);
12610 	}
12611 
12612 	if (!cb.cb_json && cb.cb_json_pool_key_guid) {
12613 		(void) fprintf(stderr, gettext("'json-pool-key-guid' only"
12614 		    " works with '-j' option\n"));
12615 		usage(B_FALSE);
12616 	}
12617 
12618 	if (argc < 1) {
12619 		(void) fprintf(stderr, gettext("missing property "
12620 		    "argument\n"));
12621 		usage(B_FALSE);
12622 	}
12623 
12624 	/* Properties list is needed later by zprop_get_list() */
12625 	propstr = argv[0];
12626 
12627 	argc--;
12628 	argv++;
12629 
12630 	if (argc == 0) {
12631 		/* No args, so just print the defaults. */
12632 	} else if (are_all_pools(argc, argv)) {
12633 		/* All the args are pool names */
12634 	} else if (are_all_pools(1, argv)) {
12635 		/* The first arg is a pool name */
12636 		if ((argc == 2 && strcmp(argv[1], "all-vdevs") == 0) ||
12637 		    (argc == 2 && strcmp(argv[1], "root") == 0) ||
12638 		    are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
12639 		    &cb.cb_vdevs)) {
12640 
12641 			if (strcmp(argv[1], "root") == 0)
12642 				vdev = strdup("root-0");
12643 			else
12644 				vdev = strdup(argv[1]);
12645 
12646 			/* ... and the rest are vdev names */
12647 			cb.cb_vdevs.cb_names = &vdev;
12648 			cb.cb_vdevs.cb_names_count = argc - 1;
12649 			cb.cb_type = ZFS_TYPE_VDEV;
12650 			argc = 1; /* One pool to process */
12651 		} else {
12652 			if (cb.cb_json) {
12653 				nvlist_free(cb.cb_jsobj);
12654 				nvlist_free(data);
12655 			}
12656 			fprintf(stderr, gettext("Expected a list of vdevs in"
12657 			    " \"%s\", but got:\n"), argv[0]);
12658 			error_list_unresolved_vdevs(argc - 1, argv + 1,
12659 			    argv[0], &cb.cb_vdevs);
12660 			fprintf(stderr, "\n");
12661 			usage(B_FALSE);
12662 			return (1);
12663 		}
12664 	} else {
12665 		if (cb.cb_json) {
12666 			nvlist_free(cb.cb_jsobj);
12667 			nvlist_free(data);
12668 		}
12669 		/*
12670 		 * The first arg isn't the name of a valid pool.
12671 		 */
12672 		fprintf(stderr, gettext("Cannot get properties of %s: "
12673 		    "no such pool available.\n"), argv[0]);
12674 		return (1);
12675 	}
12676 
12677 	if (zprop_get_list(g_zfs, propstr, &cb.cb_proplist,
12678 	    cb.cb_type) != 0) {
12679 		/* Use correct list of valid properties (pool or vdev) */
12680 		current_prop_type = cb.cb_type;
12681 		usage(B_FALSE);
12682 	}
12683 
12684 	if (cb.cb_proplist != NULL) {
12685 		fake_name.pl_prop = ZPOOL_PROP_NAME;
12686 		fake_name.pl_width = strlen(gettext("NAME"));
12687 		fake_name.pl_next = cb.cb_proplist;
12688 		cb.cb_proplist = &fake_name;
12689 	}
12690 
12691 	if (cb.cb_json) {
12692 		if (cb.cb_type == ZFS_TYPE_VDEV)
12693 			fnvlist_add_nvlist(cb.cb_jsobj, "vdevs", data);
12694 		else
12695 			fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
12696 		fnvlist_free(data);
12697 	}
12698 
12699 	ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist, cb.cb_type,
12700 	    cb.cb_literal, get_callback, &cb);
12701 
12702 	if (ret == 0 && cb.cb_json)
12703 		zcmd_print_json(cb.cb_jsobj);
12704 	else if (ret != 0 && cb.cb_json)
12705 		nvlist_free(cb.cb_jsobj);
12706 
12707 	if (cb.cb_proplist == &fake_name)
12708 		zprop_free_list(fake_name.pl_next);
12709 	else
12710 		zprop_free_list(cb.cb_proplist);
12711 
12712 	if (vdev != NULL)
12713 		free(vdev);
12714 
12715 	return (ret);
12716 }
12717 
12718 typedef struct set_cbdata {
12719 	char *cb_propname;
12720 	char *cb_value;
12721 	zfs_type_t cb_type;
12722 	vdev_cbdata_t cb_vdevs;
12723 	boolean_t cb_any_successful;
12724 } set_cbdata_t;
12725 
12726 static int
12727 set_pool_callback(zpool_handle_t *zhp, set_cbdata_t *cb)
12728 {
12729 	int error;
12730 
12731 	/* Check if we have out-of-bounds features */
12732 	if (strcmp(cb->cb_propname, ZPOOL_CONFIG_COMPATIBILITY) == 0) {
12733 		boolean_t features[SPA_FEATURES];
12734 		if (zpool_do_load_compat(cb->cb_value, features) !=
12735 		    ZPOOL_COMPATIBILITY_OK)
12736 			return (-1);
12737 
12738 		nvlist_t *enabled = zpool_get_features(zhp);
12739 		spa_feature_t i;
12740 		for (i = 0; i < SPA_FEATURES; i++) {
12741 			const char *fguid = spa_feature_table[i].fi_guid;
12742 			if (nvlist_exists(enabled, fguid) && !features[i])
12743 				break;
12744 		}
12745 		if (i < SPA_FEATURES)
12746 			(void) fprintf(stderr, gettext("Warning: one or "
12747 			    "more features already enabled on pool '%s'\n"
12748 			    "are not present in this compatibility set.\n"),
12749 			    zpool_get_name(zhp));
12750 	}
12751 
12752 	/* if we're setting a feature, check it's in compatibility set */
12753 	if (zpool_prop_feature(cb->cb_propname) &&
12754 	    strcmp(cb->cb_value, ZFS_FEATURE_ENABLED) == 0) {
12755 		char *fname = strchr(cb->cb_propname, '@') + 1;
12756 		spa_feature_t f;
12757 
12758 		if (zfeature_lookup_name(fname, &f) == 0) {
12759 			char compat[ZFS_MAXPROPLEN];
12760 			if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY,
12761 			    compat, ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
12762 				compat[0] = '\0';
12763 
12764 			boolean_t features[SPA_FEATURES];
12765 			if (zpool_do_load_compat(compat, features) !=
12766 			    ZPOOL_COMPATIBILITY_OK) {
12767 				(void) fprintf(stderr, gettext("Error: "
12768 				    "cannot enable feature '%s' on pool '%s'\n"
12769 				    "because the pool's 'compatibility' "
12770 				    "property cannot be parsed.\n"),
12771 				    fname, zpool_get_name(zhp));
12772 				return (-1);
12773 			}
12774 
12775 			if (!features[f]) {
12776 				(void) fprintf(stderr, gettext("Error: "
12777 				    "cannot enable feature '%s' on pool '%s'\n"
12778 				    "as it is not specified in this pool's "
12779 				    "current compatibility set.\n"
12780 				    "Consider setting 'compatibility' to a "
12781 				    "less restrictive set, or to 'off'.\n"),
12782 				    fname, zpool_get_name(zhp));
12783 				return (-1);
12784 			}
12785 		}
12786 	}
12787 
12788 	error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
12789 
12790 	return (error);
12791 }
12792 
12793 static int
12794 set_callback(zpool_handle_t *zhp, void *data)
12795 {
12796 	int error;
12797 	set_cbdata_t *cb = (set_cbdata_t *)data;
12798 
12799 	if (cb->cb_type == ZFS_TYPE_VDEV) {
12800 		error = zpool_set_vdev_prop(zhp, *cb->cb_vdevs.cb_names,
12801 		    cb->cb_propname, cb->cb_value);
12802 	} else {
12803 		assert(cb->cb_type == ZFS_TYPE_POOL);
12804 		error = set_pool_callback(zhp, cb);
12805 	}
12806 
12807 	cb->cb_any_successful = !error;
12808 	return (error);
12809 }
12810 
12811 int
12812 zpool_do_set(int argc, char **argv)
12813 {
12814 	set_cbdata_t cb = { 0 };
12815 	int error;
12816 	char *vdev = NULL;
12817 
12818 	current_prop_type = ZFS_TYPE_POOL;
12819 	if (argc > 1 && argv[1][0] == '-') {
12820 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
12821 		    argv[1][1]);
12822 		usage(B_FALSE);
12823 	}
12824 
12825 	if (argc < 2) {
12826 		(void) fprintf(stderr, gettext("missing property=value "
12827 		    "argument\n"));
12828 		usage(B_FALSE);
12829 	}
12830 
12831 	if (argc < 3) {
12832 		(void) fprintf(stderr, gettext("missing pool name\n"));
12833 		usage(B_FALSE);
12834 	}
12835 
12836 	if (argc > 4) {
12837 		(void) fprintf(stderr, gettext("too many pool names\n"));
12838 		usage(B_FALSE);
12839 	}
12840 
12841 	cb.cb_propname = argv[1];
12842 	cb.cb_type = ZFS_TYPE_POOL;
12843 	cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
12844 	cb.cb_value = strchr(cb.cb_propname, '=');
12845 	if (cb.cb_value == NULL) {
12846 		(void) fprintf(stderr, gettext("missing value in "
12847 		    "property=value argument\n"));
12848 		usage(B_FALSE);
12849 	}
12850 
12851 	*(cb.cb_value) = '\0';
12852 	cb.cb_value++;
12853 	argc -= 2;
12854 	argv += 2;
12855 
12856 	/* argv[0] is pool name */
12857 	if (!is_pool(argv[0])) {
12858 		(void) fprintf(stderr,
12859 		    gettext("cannot open '%s': is not a pool\n"), argv[0]);
12860 		return (EINVAL);
12861 	}
12862 
12863 	/* argv[1], when supplied, is vdev name */
12864 	if (argc == 2) {
12865 
12866 		if (strcmp(argv[1], "root") == 0)
12867 			vdev = strdup("root-0");
12868 		else
12869 			vdev = strdup(argv[1]);
12870 
12871 		if (!are_vdevs_in_pool(1, &vdev, argv[0], &cb.cb_vdevs)) {
12872 			(void) fprintf(stderr, gettext(
12873 			    "cannot find '%s' in '%s': device not in pool\n"),
12874 			    vdev, argv[0]);
12875 			free(vdev);
12876 			return (EINVAL);
12877 		}
12878 		cb.cb_vdevs.cb_names = &vdev;
12879 		cb.cb_vdevs.cb_names_count = 1;
12880 		cb.cb_type = ZFS_TYPE_VDEV;
12881 	}
12882 
12883 	error = for_each_pool(1, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
12884 	    B_FALSE, set_callback, &cb);
12885 
12886 	if (vdev != NULL)
12887 		free(vdev);
12888 
12889 	return (error);
12890 }
12891 
12892 /* Add up the total number of bytes left to initialize/trim across all vdevs */
12893 static uint64_t
12894 vdev_activity_remaining(nvlist_t *nv, zpool_wait_activity_t activity)
12895 {
12896 	uint64_t bytes_remaining;
12897 	nvlist_t **child;
12898 	uint_t c, children;
12899 	vdev_stat_t *vs;
12900 
12901 	assert(activity == ZPOOL_WAIT_INITIALIZE ||
12902 	    activity == ZPOOL_WAIT_TRIM);
12903 
12904 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
12905 	    (uint64_t **)&vs, &c) == 0);
12906 
12907 	if (activity == ZPOOL_WAIT_INITIALIZE &&
12908 	    vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE)
12909 		bytes_remaining = vs->vs_initialize_bytes_est -
12910 		    vs->vs_initialize_bytes_done;
12911 	else if (activity == ZPOOL_WAIT_TRIM &&
12912 	    vs->vs_trim_state == VDEV_TRIM_ACTIVE)
12913 		bytes_remaining = vs->vs_trim_bytes_est -
12914 		    vs->vs_trim_bytes_done;
12915 	else
12916 		bytes_remaining = 0;
12917 
12918 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
12919 	    &child, &children) != 0)
12920 		children = 0;
12921 
12922 	for (c = 0; c < children; c++)
12923 		bytes_remaining += vdev_activity_remaining(child[c], activity);
12924 
12925 	return (bytes_remaining);
12926 }
12927 
12928 /* Add up the total number of bytes left to rebuild across top-level vdevs */
12929 static uint64_t
12930 vdev_activity_top_remaining(nvlist_t *nv)
12931 {
12932 	uint64_t bytes_remaining = 0;
12933 	nvlist_t **child;
12934 	uint_t children;
12935 	int error;
12936 
12937 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
12938 	    &child, &children) != 0)
12939 		children = 0;
12940 
12941 	for (uint_t c = 0; c < children; c++) {
12942 		vdev_rebuild_stat_t *vrs;
12943 		uint_t i;
12944 
12945 		error = nvlist_lookup_uint64_array(child[c],
12946 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i);
12947 		if (error == 0) {
12948 			if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
12949 				bytes_remaining += (vrs->vrs_bytes_est -
12950 				    vrs->vrs_bytes_rebuilt);
12951 			}
12952 		}
12953 	}
12954 
12955 	return (bytes_remaining);
12956 }
12957 
12958 /* Whether any vdevs are 'spare' or 'replacing' vdevs */
12959 static boolean_t
12960 vdev_any_spare_replacing(nvlist_t *nv)
12961 {
12962 	nvlist_t **child;
12963 	uint_t c, children;
12964 	const char *vdev_type;
12965 
12966 	(void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &vdev_type);
12967 
12968 	if (strcmp(vdev_type, VDEV_TYPE_REPLACING) == 0 ||
12969 	    strcmp(vdev_type, VDEV_TYPE_SPARE) == 0 ||
12970 	    strcmp(vdev_type, VDEV_TYPE_DRAID_SPARE) == 0) {
12971 		return (B_TRUE);
12972 	}
12973 
12974 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
12975 	    &child, &children) != 0)
12976 		children = 0;
12977 
12978 	for (c = 0; c < children; c++) {
12979 		if (vdev_any_spare_replacing(child[c]))
12980 			return (B_TRUE);
12981 	}
12982 
12983 	return (B_FALSE);
12984 }
12985 
12986 typedef struct wait_data {
12987 	char *wd_poolname;
12988 	boolean_t wd_scripted;
12989 	boolean_t wd_exact;
12990 	boolean_t wd_headers_once;
12991 	boolean_t wd_should_exit;
12992 	/* Which activities to wait for */
12993 	boolean_t wd_enabled[ZPOOL_WAIT_NUM_ACTIVITIES];
12994 	float wd_interval;
12995 	pthread_cond_t wd_cv;
12996 	pthread_mutex_t wd_mutex;
12997 } wait_data_t;
12998 
12999 /*
13000  * Print to stdout a single line, containing one column for each activity that
13001  * we are waiting for specifying how many bytes of work are left for that
13002  * activity.
13003  */
13004 static void
13005 print_wait_status_row(wait_data_t *wd, zpool_handle_t *zhp, int row)
13006 {
13007 	nvlist_t *config, *nvroot;
13008 	uint_t c;
13009 	int i;
13010 	pool_checkpoint_stat_t *pcs = NULL;
13011 	pool_scan_stat_t *pss = NULL;
13012 	pool_removal_stat_t *prs = NULL;
13013 	pool_raidz_expand_stat_t *pres = NULL;
13014 	const char *const headers[] = {"DISCARD", "FREE", "INITIALIZE",
13015 	    "REPLACE", "REMOVE", "RESILVER", "SCRUB", "TRIM", "RAIDZ_EXPAND"};
13016 	int col_widths[ZPOOL_WAIT_NUM_ACTIVITIES];
13017 
13018 	/* Calculate the width of each column */
13019 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13020 		/*
13021 		 * Make sure we have enough space in the col for pretty-printed
13022 		 * numbers and for the column header, and then leave a couple
13023 		 * spaces between cols for readability.
13024 		 */
13025 		col_widths[i] = MAX(strlen(headers[i]), 6) + 2;
13026 	}
13027 
13028 	if (timestamp_fmt != NODATE)
13029 		print_timestamp(timestamp_fmt);
13030 
13031 	/* Print header if appropriate */
13032 	int term_height = terminal_height();
13033 	boolean_t reprint_header = (!wd->wd_headers_once && term_height > 0 &&
13034 	    row % (term_height-1) == 0);
13035 	if (!wd->wd_scripted && (row == 0 || reprint_header)) {
13036 		for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13037 			if (wd->wd_enabled[i])
13038 				(void) printf("%*s", col_widths[i], headers[i]);
13039 		}
13040 		(void) fputc('\n', stdout);
13041 	}
13042 
13043 	/* Bytes of work remaining in each activity */
13044 	int64_t bytes_rem[ZPOOL_WAIT_NUM_ACTIVITIES] = {0};
13045 
13046 	bytes_rem[ZPOOL_WAIT_FREE] =
13047 	    zpool_get_prop_int(zhp, ZPOOL_PROP_FREEING, NULL);
13048 
13049 	config = zpool_get_config(zhp, NULL);
13050 	nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
13051 
13052 	(void) nvlist_lookup_uint64_array(nvroot,
13053 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
13054 	if (pcs != NULL && pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
13055 		bytes_rem[ZPOOL_WAIT_CKPT_DISCARD] = pcs->pcs_space;
13056 
13057 	(void) nvlist_lookup_uint64_array(nvroot,
13058 	    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
13059 	if (prs != NULL && prs->prs_state == DSS_SCANNING)
13060 		bytes_rem[ZPOOL_WAIT_REMOVE] = prs->prs_to_copy -
13061 		    prs->prs_copied;
13062 
13063 	(void) nvlist_lookup_uint64_array(nvroot,
13064 	    ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&pss, &c);
13065 	if (pss != NULL && pss->pss_state == DSS_SCANNING &&
13066 	    pss->pss_pass_scrub_pause == 0) {
13067 		int64_t rem = pss->pss_to_examine - pss->pss_issued;
13068 		if (pss->pss_func == POOL_SCAN_SCRUB)
13069 			bytes_rem[ZPOOL_WAIT_SCRUB] = rem;
13070 		else
13071 			bytes_rem[ZPOOL_WAIT_RESILVER] = rem;
13072 	} else if (check_rebuilding(nvroot, NULL)) {
13073 		bytes_rem[ZPOOL_WAIT_RESILVER] =
13074 		    vdev_activity_top_remaining(nvroot);
13075 	}
13076 
13077 	(void) nvlist_lookup_uint64_array(nvroot,
13078 	    ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
13079 	if (pres != NULL && pres->pres_state == DSS_SCANNING) {
13080 		int64_t rem = pres->pres_to_reflow - pres->pres_reflowed;
13081 		bytes_rem[ZPOOL_WAIT_RAIDZ_EXPAND] = rem;
13082 	}
13083 
13084 	bytes_rem[ZPOOL_WAIT_INITIALIZE] =
13085 	    vdev_activity_remaining(nvroot, ZPOOL_WAIT_INITIALIZE);
13086 	bytes_rem[ZPOOL_WAIT_TRIM] =
13087 	    vdev_activity_remaining(nvroot, ZPOOL_WAIT_TRIM);
13088 
13089 	/*
13090 	 * A replace finishes after resilvering finishes, so the amount of work
13091 	 * left for a replace is the same as for resilvering.
13092 	 *
13093 	 * It isn't quite correct to say that if we have any 'spare' or
13094 	 * 'replacing' vdevs and a resilver is happening, then a replace is in
13095 	 * progress, like we do here. When a hot spare is used, the faulted vdev
13096 	 * is not removed after the hot spare is resilvered, so parent 'spare'
13097 	 * vdev is not removed either. So we could have a 'spare' vdev, but be
13098 	 * resilvering for a different reason. However, we use it as a heuristic
13099 	 * because we don't have access to the DTLs, which could tell us whether
13100 	 * or not we have really finished resilvering a hot spare.
13101 	 */
13102 	if (vdev_any_spare_replacing(nvroot))
13103 		bytes_rem[ZPOOL_WAIT_REPLACE] =  bytes_rem[ZPOOL_WAIT_RESILVER];
13104 
13105 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13106 		char buf[64];
13107 		if (!wd->wd_enabled[i])
13108 			continue;
13109 
13110 		if (wd->wd_exact) {
13111 			(void) snprintf(buf, sizeof (buf), "%" PRIi64,
13112 			    bytes_rem[i]);
13113 		} else {
13114 			zfs_nicenum(bytes_rem[i], buf, sizeof (buf));
13115 		}
13116 
13117 		if (wd->wd_scripted)
13118 			(void) printf(i == 0 ? "%s" : "\t%s", buf);
13119 		else
13120 			(void) printf(" %*s", col_widths[i] - 1, buf);
13121 	}
13122 	(void) printf("\n");
13123 	(void) fflush(stdout);
13124 }
13125 
13126 static void *
13127 wait_status_thread(void *arg)
13128 {
13129 	wait_data_t *wd = (wait_data_t *)arg;
13130 	zpool_handle_t *zhp;
13131 
13132 	if ((zhp = zpool_open(g_zfs, wd->wd_poolname)) == NULL)
13133 		return (void *)(1);
13134 
13135 	for (int row = 0; ; row++) {
13136 		boolean_t missing;
13137 		struct timespec timeout;
13138 		int ret = 0;
13139 		(void) clock_gettime(CLOCK_REALTIME, &timeout);
13140 
13141 		if (zpool_refresh_stats(zhp, &missing) != 0 || missing ||
13142 		    zpool_props_refresh(zhp) != 0) {
13143 			zpool_close(zhp);
13144 			return (void *)(uintptr_t)(missing ? 0 : 1);
13145 		}
13146 
13147 		print_wait_status_row(wd, zhp, row);
13148 
13149 		timeout.tv_sec += floor(wd->wd_interval);
13150 		long nanos = timeout.tv_nsec +
13151 		    (wd->wd_interval - floor(wd->wd_interval)) * NANOSEC;
13152 		if (nanos >= NANOSEC) {
13153 			timeout.tv_sec++;
13154 			timeout.tv_nsec = nanos - NANOSEC;
13155 		} else {
13156 			timeout.tv_nsec = nanos;
13157 		}
13158 		pthread_mutex_lock(&wd->wd_mutex);
13159 		if (!wd->wd_should_exit)
13160 			ret = pthread_cond_timedwait(&wd->wd_cv, &wd->wd_mutex,
13161 			    &timeout);
13162 		pthread_mutex_unlock(&wd->wd_mutex);
13163 		if (ret == 0) {
13164 			break; /* signaled by main thread */
13165 		} else if (ret != ETIMEDOUT) {
13166 			(void) fprintf(stderr, gettext("pthread_cond_timedwait "
13167 			    "failed: %s\n"), strerror(ret));
13168 			zpool_close(zhp);
13169 			return (void *)(uintptr_t)(1);
13170 		}
13171 	}
13172 
13173 	zpool_close(zhp);
13174 	return (void *)(0);
13175 }
13176 
13177 int
13178 zpool_do_wait(int argc, char **argv)
13179 {
13180 	boolean_t verbose = B_FALSE;
13181 	int c, i;
13182 	unsigned long count;
13183 	pthread_t status_thr;
13184 	int error = 0;
13185 	zpool_handle_t *zhp;
13186 
13187 	wait_data_t wd;
13188 	wd.wd_scripted = B_FALSE;
13189 	wd.wd_exact = B_FALSE;
13190 	wd.wd_headers_once = B_FALSE;
13191 	wd.wd_should_exit = B_FALSE;
13192 
13193 	pthread_mutex_init(&wd.wd_mutex, NULL);
13194 	pthread_cond_init(&wd.wd_cv, NULL);
13195 
13196 	/* By default, wait for all types of activity. */
13197 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++)
13198 		wd.wd_enabled[i] = B_TRUE;
13199 
13200 	while ((c = getopt(argc, argv, "HpT:t:")) != -1) {
13201 		switch (c) {
13202 		case 'H':
13203 			wd.wd_scripted = B_TRUE;
13204 			break;
13205 		case 'n':
13206 			wd.wd_headers_once = B_TRUE;
13207 			break;
13208 		case 'p':
13209 			wd.wd_exact = B_TRUE;
13210 			break;
13211 		case 'T':
13212 			get_timestamp_arg(*optarg);
13213 			break;
13214 		case 't':
13215 			/* Reset activities array */
13216 			memset(&wd.wd_enabled, 0, sizeof (wd.wd_enabled));
13217 
13218 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
13219 				static const char *const col_opts[] = {
13220 				    "discard", "free", "initialize", "replace",
13221 				    "remove", "resilver", "scrub", "trim",
13222 				    "raidz_expand" };
13223 
13224 				for (i = 0; i < ARRAY_SIZE(col_opts); ++i)
13225 					if (strcmp(tok, col_opts[i]) == 0) {
13226 						wd.wd_enabled[i] = B_TRUE;
13227 						goto found;
13228 					}
13229 
13230 				(void) fprintf(stderr,
13231 				    gettext("invalid activity '%s'\n"), tok);
13232 				usage(B_FALSE);
13233 found:;
13234 			}
13235 			break;
13236 		case '?':
13237 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
13238 			    optopt);
13239 			usage(B_FALSE);
13240 		}
13241 	}
13242 
13243 	argc -= optind;
13244 	argv += optind;
13245 
13246 	get_interval_count(&argc, argv, &wd.wd_interval, &count);
13247 	if (count != 0) {
13248 		/* This subcmd only accepts an interval, not a count */
13249 		(void) fprintf(stderr, gettext("too many arguments\n"));
13250 		usage(B_FALSE);
13251 	}
13252 
13253 	if (wd.wd_interval != 0)
13254 		verbose = B_TRUE;
13255 
13256 	if (argc < 1) {
13257 		(void) fprintf(stderr, gettext("missing 'pool' argument\n"));
13258 		usage(B_FALSE);
13259 	}
13260 	if (argc > 1) {
13261 		(void) fprintf(stderr, gettext("too many arguments\n"));
13262 		usage(B_FALSE);
13263 	}
13264 
13265 	wd.wd_poolname = argv[0];
13266 
13267 	if ((zhp = zpool_open(g_zfs, wd.wd_poolname)) == NULL)
13268 		return (1);
13269 
13270 	if (verbose) {
13271 		/*
13272 		 * We use a separate thread for printing status updates because
13273 		 * the main thread will call lzc_wait(), which blocks as long
13274 		 * as an activity is in progress, which can be a long time.
13275 		 */
13276 		if (pthread_create(&status_thr, NULL, wait_status_thread, &wd)
13277 		    != 0) {
13278 			(void) fprintf(stderr, gettext("failed to create status"
13279 			    "thread: %s\n"), strerror(errno));
13280 			zpool_close(zhp);
13281 			return (1);
13282 		}
13283 	}
13284 
13285 	/*
13286 	 * Loop over all activities that we are supposed to wait for until none
13287 	 * of them are in progress. Note that this means we can end up waiting
13288 	 * for more activities to complete than just those that were in progress
13289 	 * when we began waiting; if an activity we are interested in begins
13290 	 * while we are waiting for another activity, we will wait for both to
13291 	 * complete before exiting.
13292 	 */
13293 	for (;;) {
13294 		boolean_t missing = B_FALSE;
13295 		boolean_t any_waited = B_FALSE;
13296 
13297 		for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13298 			boolean_t waited;
13299 
13300 			if (!wd.wd_enabled[i])
13301 				continue;
13302 
13303 			error = zpool_wait_status(zhp, i, &missing, &waited);
13304 			if (error != 0 || missing)
13305 				break;
13306 
13307 			any_waited = (any_waited || waited);
13308 		}
13309 
13310 		if (error != 0 || missing || !any_waited)
13311 			break;
13312 	}
13313 
13314 	zpool_close(zhp);
13315 
13316 	if (verbose) {
13317 		uintptr_t status;
13318 		pthread_mutex_lock(&wd.wd_mutex);
13319 		wd.wd_should_exit = B_TRUE;
13320 		pthread_cond_signal(&wd.wd_cv);
13321 		pthread_mutex_unlock(&wd.wd_mutex);
13322 		(void) pthread_join(status_thr, (void *)&status);
13323 		if (status != 0)
13324 			error = status;
13325 	}
13326 
13327 	pthread_mutex_destroy(&wd.wd_mutex);
13328 	pthread_cond_destroy(&wd.wd_cv);
13329 	return (error);
13330 }
13331 
13332 static int
13333 find_command_idx(const char *command, int *idx)
13334 {
13335 	for (int i = 0; i < NCOMMAND; ++i) {
13336 		if (command_table[i].name == NULL)
13337 			continue;
13338 
13339 		if (strcmp(command, command_table[i].name) == 0) {
13340 			*idx = i;
13341 			return (0);
13342 		}
13343 	}
13344 	return (1);
13345 }
13346 
13347 /*
13348  * Display version message
13349  */
13350 static int
13351 zpool_do_version(int argc, char **argv)
13352 {
13353 	int c;
13354 	nvlist_t *jsobj = NULL, *zfs_ver = NULL;
13355 	boolean_t json = B_FALSE;
13356 	while ((c = getopt(argc, argv, "j")) != -1) {
13357 		switch (c) {
13358 		case 'j':
13359 			json = B_TRUE;
13360 			jsobj = zpool_json_schema(0, 1);
13361 			break;
13362 		case '?':
13363 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
13364 			    optopt);
13365 			usage(B_FALSE);
13366 		}
13367 	}
13368 
13369 	argc -= optind;
13370 	if (argc != 0) {
13371 		(void) fprintf(stderr, "too many arguments\n");
13372 		usage(B_FALSE);
13373 	}
13374 
13375 	if (json) {
13376 		zfs_ver = zfs_version_nvlist();
13377 		if (zfs_ver) {
13378 			fnvlist_add_nvlist(jsobj, "zfs_version", zfs_ver);
13379 			zcmd_print_json(jsobj);
13380 			fnvlist_free(zfs_ver);
13381 			return (0);
13382 		} else
13383 			return (-1);
13384 	} else
13385 		return (zfs_version_print() != 0);
13386 }
13387 
13388 /* Display documentation */
13389 static int
13390 zpool_do_help(int argc, char **argv)
13391 {
13392 	char page[MAXNAMELEN];
13393 	if (argc < 3 || strcmp(argv[2], "zpool") == 0)
13394 		strcpy(page, "zpool");
13395 	else if (strcmp(argv[2], "concepts") == 0 ||
13396 	    strcmp(argv[2], "props") == 0)
13397 		snprintf(page, sizeof (page), "zpool%s", argv[2]);
13398 	else
13399 		snprintf(page, sizeof (page), "zpool-%s", argv[2]);
13400 
13401 	execlp("man", "man", page, NULL);
13402 
13403 	fprintf(stderr, "couldn't run man program: %s", strerror(errno));
13404 	return (-1);
13405 }
13406 
13407 /*
13408  * Do zpool_load_compat() and print error message on failure
13409  */
13410 static zpool_compat_status_t
13411 zpool_do_load_compat(const char *compat, boolean_t *list)
13412 {
13413 	char report[1024];
13414 
13415 	zpool_compat_status_t ret;
13416 
13417 	ret = zpool_load_compat(compat, list, report, 1024);
13418 	switch (ret) {
13419 
13420 	case ZPOOL_COMPATIBILITY_OK:
13421 		break;
13422 
13423 	case ZPOOL_COMPATIBILITY_NOFILES:
13424 	case ZPOOL_COMPATIBILITY_BADFILE:
13425 	case ZPOOL_COMPATIBILITY_BADTOKEN:
13426 		(void) fprintf(stderr, "Error: %s\n", report);
13427 		break;
13428 
13429 	case ZPOOL_COMPATIBILITY_WARNTOKEN:
13430 		(void) fprintf(stderr, "Warning: %s\n", report);
13431 		ret = ZPOOL_COMPATIBILITY_OK;
13432 		break;
13433 	}
13434 	return (ret);
13435 }
13436 
13437 int
13438 main(int argc, char **argv)
13439 {
13440 	int ret = 0;
13441 	int i = 0;
13442 	char *cmdname;
13443 	char **newargv;
13444 
13445 	(void) setlocale(LC_ALL, "");
13446 	(void) setlocale(LC_NUMERIC, "C");
13447 	(void) textdomain(TEXT_DOMAIN);
13448 	srand(time(NULL));
13449 
13450 	opterr = 0;
13451 
13452 	/*
13453 	 * Make sure the user has specified some command.
13454 	 */
13455 	if (argc < 2) {
13456 		(void) fprintf(stderr, gettext("missing command\n"));
13457 		usage(B_FALSE);
13458 	}
13459 
13460 	cmdname = argv[1];
13461 
13462 	/*
13463 	 * Special case '-?'
13464 	 */
13465 	if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
13466 		usage(B_TRUE);
13467 
13468 	/*
13469 	 * Special case '-V|--version'
13470 	 */
13471 	if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
13472 		return (zpool_do_version(argc, argv));
13473 
13474 	/*
13475 	 * Special case 'help'
13476 	 */
13477 	if (strcmp(cmdname, "help") == 0)
13478 		return (zpool_do_help(argc, argv));
13479 
13480 	if ((g_zfs = libzfs_init()) == NULL) {
13481 		(void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
13482 		return (1);
13483 	}
13484 
13485 	libzfs_print_on_error(g_zfs, B_TRUE);
13486 
13487 	zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
13488 
13489 	/*
13490 	 * Many commands modify input strings for string parsing reasons.
13491 	 * We create a copy to protect the original argv.
13492 	 */
13493 	newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
13494 	for (i = 0; i < argc; i++)
13495 		newargv[i] = strdup(argv[i]);
13496 	newargv[argc] = NULL;
13497 
13498 	/*
13499 	 * Run the appropriate command.
13500 	 */
13501 	if (find_command_idx(cmdname, &i) == 0) {
13502 		current_command = &command_table[i];
13503 		ret = command_table[i].func(argc - 1, newargv + 1);
13504 	} else if (strchr(cmdname, '=')) {
13505 		verify(find_command_idx("set", &i) == 0);
13506 		current_command = &command_table[i];
13507 		ret = command_table[i].func(argc, newargv);
13508 	} else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
13509 		/*
13510 		 * 'freeze' is a vile debugging abomination, so we treat
13511 		 * it as such.
13512 		 */
13513 		zfs_cmd_t zc = {"\0"};
13514 
13515 		(void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
13516 		ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
13517 		if (ret != 0) {
13518 			(void) fprintf(stderr,
13519 			gettext("failed to freeze pool: %d\n"), errno);
13520 			ret = 1;
13521 		}
13522 
13523 		log_history = 0;
13524 	} else {
13525 		(void) fprintf(stderr, gettext("unrecognized "
13526 		    "command '%s'\n"), cmdname);
13527 		usage(B_FALSE);
13528 		ret = 1;
13529 	}
13530 
13531 	for (i = 0; i < argc; i++)
13532 		free(newargv[i]);
13533 	free(newargv);
13534 
13535 	if (ret == 0 && log_history)
13536 		(void) zpool_log_history(g_zfs, history_str);
13537 
13538 	libzfs_fini(g_zfs);
13539 
13540 	/*
13541 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
13542 	 * for the purposes of running ::findleaks.
13543 	 */
13544 	if (getenv("ZFS_ABORT") != NULL) {
13545 		(void) printf("dumping core by request\n");
13546 		abort();
13547 	}
13548 
13549 	return (ret);
13550 }
13551