xref: /freebsd/sys/contrib/openzfs/cmd/zpool/zpool_main.c (revision 2f10ffc003be396f3fc23cd2888023896560252b)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 
13 /*
14  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
15  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
16  * Copyright (c) 2011, 2024 by Delphix. All rights reserved.
17  * Copyright (c) 2012 by Frederik Wessels. All rights reserved.
18  * Copyright (c) 2012 by Cyril Plisko. All rights reserved.
19  * Copyright (c) 2013 by Prasad Joshi (sTec). All rights reserved.
20  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
21  * Copyright (c) 2017 Datto Inc.
22  * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
23  * Copyright (c) 2017, Intel Corporation.
24  * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>
25  * Copyright (c) 2021, Colm Buckley <colm@tuatha.org>
26  * Copyright (c) 2021, 2023-2026, Klara, Inc.
27  * Copyright (c) 2021, 2025 Hewlett Packard Enterprise Development LP.
28  * Copyright (c) 2026, TrueNAS.
29  */
30 
31 #include <assert.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <getopt.h>
37 #include <inttypes.h>
38 #include <libgen.h>
39 #include <libintl.h>
40 #include <locale.h>
41 #include <pthread.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <termios.h>
46 #include <time.h>
47 #include <unistd.h>
48 #include <pwd.h>
49 #include <zone.h>
50 #include <sys/wait.h>
51 #include <zfs_prop.h>
52 #include <sys/fs/zfs.h>
53 #include <sys/stat.h>
54 #include <sys/systeminfo.h>
55 #include <sys/fm/fs/zfs.h>
56 #include <sys/fm/util.h>
57 #include <sys/fm/protocol.h>
58 #include <sys/zfs_ioctl.h>
59 #include <sys/mount.h>
60 #include <sys/sysmacros.h>
61 #include <string.h>
62 #include <math.h>
63 
64 #include <libzfs.h>
65 #include <libzutil.h>
66 
67 #include "zpool_util.h"
68 #include "zfs_comutil.h"
69 #include "zfeature_common.h"
70 #include "zfs_valstr.h"
71 
72 #include "statcommon.h"
73 
74 libzfs_handle_t *g_zfs;
75 
76 static int mount_tp_nthr = 512;  /* tpool threads for multi-threaded mounting */
77 
78 static int zpool_do_create(int, char **);
79 static int zpool_do_destroy(int, char **);
80 
81 static int zpool_do_add(int, char **);
82 static int zpool_do_remove(int, char **);
83 static int zpool_do_labelclear(int, char **);
84 
85 static int zpool_do_checkpoint(int, char **);
86 static int zpool_do_prefetch(int, char **);
87 
88 static int zpool_do_list(int, char **);
89 static int zpool_do_iostat(int, char **);
90 static int zpool_do_status(int, char **);
91 
92 static int zpool_do_online(int, char **);
93 static int zpool_do_offline(int, char **);
94 static int zpool_do_clear(int, char **);
95 static int zpool_do_reopen(int, char **);
96 
97 static int zpool_do_reguid(int, char **);
98 
99 static int zpool_do_attach(int, char **);
100 static int zpool_do_detach(int, char **);
101 static int zpool_do_replace(int, char **);
102 static int zpool_do_split(int, char **);
103 
104 static int zpool_do_initialize(int, char **);
105 static int zpool_do_scrub(int, char **);
106 static int zpool_do_resilver(int, char **);
107 static int zpool_do_trim(int, char **);
108 
109 static int zpool_do_import(int, char **);
110 static int zpool_do_export(int, char **);
111 
112 static int zpool_do_upgrade(int, char **);
113 
114 static int zpool_do_history(int, char **);
115 static int zpool_do_events(int, char **);
116 
117 static int zpool_do_get(int, char **);
118 static int zpool_do_set(int, char **);
119 
120 static int zpool_do_sync(int, char **);
121 static int zpool_do_condense(int, char **);
122 
123 static int zpool_do_version(int, char **);
124 
125 static int zpool_do_wait(int, char **);
126 
127 static int zpool_do_ddt_prune(int, char **);
128 
129 static int zpool_do_help(int argc, char **argv);
130 
131 static zpool_compat_status_t zpool_do_load_compat(
132     const char *, boolean_t *);
133 
134 enum zpool_options {
135 	ZPOOL_OPTION_POWER = 1024,
136 	ZPOOL_OPTION_ALLOW_INUSE,
137 	ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH,
138 	ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH,
139 	ZPOOL_OPTION_POOL_KEY_GUID,
140 	ZPOOL_OPTION_JSON_NUMS_AS_INT,
141 	ZPOOL_OPTION_JSON_FLAT_VDEVS,
142 	ZPOOL_OPTION_CONDENSE_LIST_TYPES
143 };
144 
145 /*
146  * These libumem hooks provide a reasonable set of defaults for the allocator's
147  * debugging facilities.
148  */
149 
150 #ifdef DEBUG
151 const char *
152 _umem_debug_init(void)
153 {
154 	return ("default,verbose"); /* $UMEM_DEBUG setting */
155 }
156 
157 const char *
158 _umem_logging_init(void)
159 {
160 	return ("fail,contents"); /* $UMEM_LOGGING setting */
161 }
162 #endif
163 
164 typedef enum {
165 	HELP_ADD,
166 	HELP_ATTACH,
167 	HELP_CLEAR,
168 	HELP_CREATE,
169 	HELP_CHECKPOINT,
170 	HELP_CONDENSE,
171 	HELP_DDT_PRUNE,
172 	HELP_DESTROY,
173 	HELP_DETACH,
174 	HELP_EXPORT,
175 	HELP_HISTORY,
176 	HELP_IMPORT,
177 	HELP_IOSTAT,
178 	HELP_LABELCLEAR,
179 	HELP_LIST,
180 	HELP_OFFLINE,
181 	HELP_ONLINE,
182 	HELP_PREFETCH,
183 	HELP_REPLACE,
184 	HELP_REMOVE,
185 	HELP_INITIALIZE,
186 	HELP_SCRUB,
187 	HELP_RESILVER,
188 	HELP_TRIM,
189 	HELP_STATUS,
190 	HELP_UPGRADE,
191 	HELP_EVENTS,
192 	HELP_GET,
193 	HELP_SET,
194 	HELP_SPLIT,
195 	HELP_SYNC,
196 	HELP_REGUID,
197 	HELP_REOPEN,
198 	HELP_VERSION,
199 	HELP_WAIT
200 } zpool_help_t;
201 
202 
203 /*
204  * Flags for stats to display with "zpool iostats"
205  */
206 enum iostat_type {
207 	IOS_DEFAULT = 0,
208 	IOS_LATENCY = 1,
209 	IOS_QUEUES = 2,
210 	IOS_L_HISTO = 3,
211 	IOS_RQ_HISTO = 4,
212 	IOS_COUNT,	/* always last element */
213 };
214 
215 /* iostat_type entries as bitmasks */
216 #define	IOS_DEFAULT_M	(1ULL << IOS_DEFAULT)
217 #define	IOS_LATENCY_M	(1ULL << IOS_LATENCY)
218 #define	IOS_QUEUES_M	(1ULL << IOS_QUEUES)
219 #define	IOS_L_HISTO_M	(1ULL << IOS_L_HISTO)
220 #define	IOS_RQ_HISTO_M	(1ULL << IOS_RQ_HISTO)
221 
222 /* Mask of all the histo bits */
223 #define	IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
224 
225 /*
226  * Lookup table for iostat flags to nvlist names.  Basically a list
227  * of all the nvlists a flag requires.  Also specifies the order in
228  * which data gets printed in zpool iostat.
229  */
230 static const char *vsx_type_to_nvlist[IOS_COUNT][15] = {
231 	[IOS_L_HISTO] = {
232 	    ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
233 	    ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
234 	    ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
235 	    ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
236 	    ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
237 	    ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
238 	    ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
239 	    ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
240 	    ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
241 	    ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
242 	    ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
243 	    NULL},
244 	[IOS_LATENCY] = {
245 	    ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
246 	    ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
247 	    ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
248 	    ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
249 	    ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
250 	    ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
251 	    NULL},
252 	[IOS_QUEUES] = {
253 	    ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
254 	    ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
255 	    ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
256 	    ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
257 	    ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
258 	    ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
259 	    ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
260 	    NULL},
261 	[IOS_RQ_HISTO] = {
262 	    ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
263 	    ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
264 	    ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
265 	    ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
266 	    ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
267 	    ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
268 	    ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
269 	    ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
270 	    ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
271 	    ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
272 	    ZPOOL_CONFIG_VDEV_IND_TRIM_HISTO,
273 	    ZPOOL_CONFIG_VDEV_AGG_TRIM_HISTO,
274 	    ZPOOL_CONFIG_VDEV_IND_REBUILD_HISTO,
275 	    ZPOOL_CONFIG_VDEV_AGG_REBUILD_HISTO,
276 	    NULL},
277 };
278 
279 static const char *pool_scan_func_str[] = {
280 	"NONE",
281 	"SCRUB",
282 	"RESILVER",
283 	"ERRORSCRUB"
284 };
285 
286 static const char *pool_scan_state_str[] = {
287 	"NONE",
288 	"SCANNING",
289 	"FINISHED",
290 	"CANCELED",
291 	"ERRORSCRUBBING"
292 };
293 
294 static const char *vdev_rebuild_state_str[] = {
295 	"NONE",
296 	"ACTIVE",
297 	"CANCELED",
298 	"COMPLETE"
299 };
300 
301 static const char *checkpoint_state_str[] = {
302 	"NONE",
303 	"EXISTS",
304 	"DISCARDING"
305 };
306 
307 static const char *vdev_state_str[] = {
308 	"UNKNOWN",
309 	"CLOSED",
310 	"OFFLINE",
311 	"REMOVED",
312 	"CANT_OPEN",
313 	"FAULTED",
314 	"DEGRADED",
315 	"ONLINE"
316 };
317 
318 static const char *vdev_aux_str[] = {
319 	"NONE",
320 	"OPEN_FAILED",
321 	"CORRUPT_DATA",
322 	"NO_REPLICAS",
323 	"BAD_GUID_SUM",
324 	"TOO_SMALL",
325 	"BAD_LABEL",
326 	"VERSION_NEWER",
327 	"VERSION_OLDER",
328 	"UNSUP_FEAT",
329 	"SPARED",
330 	"ERR_EXCEEDED",
331 	"IO_FAILURE",
332 	"BAD_LOG",
333 	"EXTERNAL",
334 	"SPLIT_POOL",
335 	"BAD_ASHIFT",
336 	"EXTERNAL_PERSIST",
337 	"ACTIVE",
338 	"CHILDREN_OFFLINE",
339 	"ASHIFT_TOO_BIG"
340 };
341 
342 static const char *vdev_init_state_str[] = {
343 	"NONE",
344 	"ACTIVE",
345 	"CANCELED",
346 	"SUSPENDED",
347 	"COMPLETE"
348 };
349 
350 static const char *vdev_trim_state_str[] = {
351 	"NONE",
352 	"ACTIVE",
353 	"CANCELED",
354 	"SUSPENDED",
355 	"COMPLETE"
356 };
357 
358 static const char *condense_unit(const char *type) {
359 	if (strcmp(type, POOL_CONDENSE_LOG_SPACEMAP) == 0)
360 		return ("metaslabs");
361 #ifdef ZFS_DEBUG
362 	if (strcmp(type, "debug") == 0)
363 		return ("nits");	/* fundamental unit of debugging? ;) */
364 #endif
365 	return ("items");
366 }
367 
368 #define	ZFS_NICE_TIMESTAMP	100
369 
370 /*
371  * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
372  * Right now, only one histo bit is ever set at one time, so we can
373  * just do a highbit64(a)
374  */
375 #define	IOS_HISTO_IDX(a)	(highbit64(a & IOS_ANYHISTO_M) - 1)
376 
377 typedef struct zpool_command {
378 	const char	*name;
379 	int		(*func)(int, char **);
380 	zpool_help_t	usage;
381 } zpool_command_t;
382 
383 /*
384  * Master command table.  Each ZFS command has a name, associated function, and
385  * usage message.  The usage messages need to be internationalized, so we have
386  * to have a function to return the usage message based on a command index.
387  *
388  * These commands are organized according to how they are displayed in the usage
389  * message.  An empty command (one with a NULL name) indicates an empty line in
390  * the generic usage message.
391  */
392 static zpool_command_t command_table[] = {
393 	{ "version",	zpool_do_version,	HELP_VERSION		},
394 	{ NULL },
395 	{ "create",	zpool_do_create,	HELP_CREATE		},
396 	{ "destroy",	zpool_do_destroy,	HELP_DESTROY		},
397 	{ NULL },
398 	{ "add",	zpool_do_add,		HELP_ADD		},
399 	{ "remove",	zpool_do_remove,	HELP_REMOVE		},
400 	{ NULL },
401 	{ "labelclear",	zpool_do_labelclear,	HELP_LABELCLEAR		},
402 	{ NULL },
403 	{ "checkpoint",	zpool_do_checkpoint,	HELP_CHECKPOINT		},
404 	{ "prefetch",	zpool_do_prefetch,	HELP_PREFETCH		},
405 	{ NULL },
406 	{ "list",	zpool_do_list,		HELP_LIST		},
407 	{ "iostat",	zpool_do_iostat,	HELP_IOSTAT		},
408 	{ "status",	zpool_do_status,	HELP_STATUS		},
409 	{ NULL },
410 	{ "online",	zpool_do_online,	HELP_ONLINE		},
411 	{ "offline",	zpool_do_offline,	HELP_OFFLINE		},
412 	{ "clear",	zpool_do_clear,		HELP_CLEAR		},
413 	{ "reopen",	zpool_do_reopen,	HELP_REOPEN		},
414 	{ NULL },
415 	{ "attach",	zpool_do_attach,	HELP_ATTACH		},
416 	{ "detach",	zpool_do_detach,	HELP_DETACH		},
417 	{ "replace",	zpool_do_replace,	HELP_REPLACE		},
418 	{ "split",	zpool_do_split,		HELP_SPLIT		},
419 	{ NULL },
420 	{ "initialize",	zpool_do_initialize,	HELP_INITIALIZE		},
421 	{ "resilver",	zpool_do_resilver,	HELP_RESILVER		},
422 	{ "scrub",	zpool_do_scrub,		HELP_SCRUB		},
423 	{ "trim",	zpool_do_trim,		HELP_TRIM		},
424 	{ "condense",	zpool_do_condense,	HELP_CONDENSE		},
425 	{ NULL },
426 	{ "import",	zpool_do_import,	HELP_IMPORT		},
427 	{ "export",	zpool_do_export,	HELP_EXPORT		},
428 	{ "upgrade",	zpool_do_upgrade,	HELP_UPGRADE		},
429 	{ "reguid",	zpool_do_reguid,	HELP_REGUID		},
430 	{ NULL },
431 	{ "history",	zpool_do_history,	HELP_HISTORY		},
432 	{ "events",	zpool_do_events,	HELP_EVENTS		},
433 	{ NULL },
434 	{ "get",	zpool_do_get,		HELP_GET		},
435 	{ "set",	zpool_do_set,		HELP_SET		},
436 	{ NULL },
437 	{ "sync",	zpool_do_sync,		HELP_SYNC		},
438 	{ NULL },
439 	{ "wait",	zpool_do_wait,		HELP_WAIT		},
440 	{ NULL },
441 	{ "ddtprune",	zpool_do_ddt_prune,	HELP_DDT_PRUNE		},
442 };
443 
444 #define	NCOMMAND	(ARRAY_SIZE(command_table))
445 
446 #define	VDEV_ALLOC_CLASS_LOGS	"logs"
447 
448 #define	MAX_CMD_LEN	256
449 
450 static zpool_command_t *current_command;
451 static zfs_type_t current_prop_type = (ZFS_TYPE_POOL | ZFS_TYPE_VDEV);
452 static char history_str[HIS_MAX_RECORD_LEN];
453 static boolean_t log_history = B_TRUE;
454 static uint_t timestamp_fmt = NODATE;
455 
456 static const char *
457 get_usage(zpool_help_t idx)
458 {
459 	switch (idx) {
460 	case HELP_ADD:
461 		return (gettext("\tadd [-afgLnP] [-o property=value] "
462 		    "<pool> <vdev> ...\n"));
463 	case HELP_ATTACH:
464 		return (gettext("\tattach [-fsw] [-o property=value] "
465 		    "<pool> <vdev> <new-device>\n"));
466 	case HELP_CLEAR:
467 		return (gettext("\tclear [--power] <pool> [device]\n"));
468 	case HELP_CREATE:
469 		return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
470 		    "\t    [-O file-system-property=value] ... \n"
471 		    "\t    [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
472 	case HELP_CHECKPOINT:
473 		return (gettext("\tcheckpoint [-d [-w]] <pool> ...\n"));
474 	case HELP_DESTROY:
475 		return (gettext("\tdestroy [-f] <pool>\n"));
476 	case HELP_DETACH:
477 		return (gettext("\tdetach <pool> <device>\n"));
478 	case HELP_EXPORT:
479 		return (gettext("\texport [-af] <pool> ...\n"));
480 	case HELP_HISTORY:
481 		return (gettext("\thistory [-il] [<pool>] ...\n"));
482 	case HELP_IMPORT:
483 		return (gettext("\timport [-d dir] [-D]\n"
484 		    "\timport [-o mntopts] [-o property=value] ... \n"
485 		    "\t    [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
486 		    "[-R root] [-F [-n]] -a\n"
487 		    "\timport [-o mntopts] [-o property=value] ... \n"
488 		    "\t    [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
489 		    "[-R root] [-F [-n]]\n"
490 		    "\t    [--rewind-to-checkpoint] <pool | id> [newpool]\n"));
491 	case HELP_IOSTAT:
492 		return (gettext("\tiostat [[[-c [script1,script2,...]"
493 		    "[-lq]]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
494 		    "\t    [[pool ...]|[pool vdev ...]|[vdev ...]]"
495 		    " [[-n] interval [count]]\n"));
496 	case HELP_LABELCLEAR:
497 		return (gettext("\tlabelclear [-f] <vdev>\n"));
498 	case HELP_LIST:
499 		return (gettext("\tlist [-gHLpPv] [-o property[,...]] [-j "
500 		    "[--json-int, --json-pool-key-guid]] ...\n"
501 		    "\t    [-T d|u] [pool] [interval [count]]\n"));
502 	case HELP_PREFETCH:
503 		return (gettext("\tprefetch [-t <type>] <pool>\n"));
504 	case HELP_OFFLINE:
505 		return (gettext("\toffline [--power]|[[-f][-t]] <pool> "
506 		    "<device> ...\n"));
507 	case HELP_ONLINE:
508 		return (gettext("\tonline [--power][-e] <pool> <device> "
509 		    "...\n"));
510 	case HELP_REPLACE:
511 		return (gettext("\treplace [-fsw] [-o property=value] "
512 		    "<pool> <device> [new-device]\n"));
513 	case HELP_REMOVE:
514 		return (gettext("\tremove [-npsw] <pool> <device> ...\n"));
515 	case HELP_REOPEN:
516 		return (gettext("\treopen [-n] <pool>\n"));
517 	case HELP_INITIALIZE:
518 		return (gettext("\tinitialize [-c | -s | -u] [-w] [-z] "
519 		    "<-a | <pool> [<device> ...]>\n"));
520 	case HELP_SCRUB:
521 		return (gettext("\tscrub [-e | -s | -p | -t | -C [-t] | "
522 		    "[-S date] [-E date] [-t]] [-w]\n"
523 		    "\t    <-a | <pool> [<pool> ...]>\n"));
524 	case HELP_RESILVER:
525 		return (gettext("\tresilver <pool> ...\n"));
526 	case HELP_TRIM:
527 		return (gettext("\ttrim [-dw] [-r <rate>] [-c | -s] "
528 		    "<-a | <pool> [<device> ...]>\n"));
529 	case HELP_STATUS:
530 		return (gettext("\tstatus [-DdegiLPpstvx] "
531 		    "[-c script1[,script2,...]] ...\n"
532 		    "\t    [-j|--json [--json-flat-vdevs] [--json-int] "
533 		    "[--json-pool-key-guid]] ...\n"
534 		    "\t    [-T d|u] [--power] [pool] [interval [count]]\n"));
535 	case HELP_UPGRADE:
536 		return (gettext("\tupgrade\n"
537 		    "\tupgrade -v\n"
538 		    "\tupgrade [-V version] <-a | pool ...>\n"));
539 	case HELP_EVENTS:
540 		return (gettext("\tevents [-vHf [pool] | -c]\n"));
541 	case HELP_GET:
542 		return (gettext("\tget [-Hp] [-j [--json-int, "
543 		    "--json-pool-key-guid]] ...\n"
544 		    "\t    [-o \"all\" | field[,...]] "
545 		    "<\"all\" | property[,...]> <pool> ...\n"));
546 	case HELP_SET:
547 		return (gettext("\tset <property=value> <pool>\n"
548 		    "\tset <vdev_property=value> <pool> <vdev>\n"));
549 	case HELP_SPLIT:
550 		return (gettext("\tsplit [-gLnPl] [-R altroot] [-o mntopts]\n"
551 		    "\t    [-o property=value] <pool> <newpool> "
552 		    "[<device> ...]\n"));
553 	case HELP_REGUID:
554 		return (gettext("\treguid [-g guid] <pool>\n"));
555 	case HELP_SYNC:
556 		return (gettext("\tsync [pool] ...\n"));
557 	case HELP_CONDENSE:
558 		return (gettext("\tcondense [-t <type>] [-c | -w] "
559 		    "[-a | <pool> ...]\n"
560 		    "\tcondense --types\n"));
561 	case HELP_VERSION:
562 		return (gettext("\tversion [-j]\n"));
563 	case HELP_WAIT:
564 		return (gettext("\twait [-Hp] [-T d|u] [-t <activity>[,...]] "
565 		    "<pool> [interval]\n"));
566 	case HELP_DDT_PRUNE:
567 		return (gettext("\tddtprune -d|-p <amount> <pool>\n"));
568 	default:
569 		__builtin_unreachable();
570 	}
571 }
572 
573 /*
574  * Callback routine that will print out a pool property value.
575  */
576 static int
577 print_pool_prop_cb(int prop, void *cb)
578 {
579 	FILE *fp = cb;
580 
581 	(void) fprintf(fp, "\t%-19s  ", zpool_prop_to_name(prop));
582 
583 	if (zpool_prop_readonly(prop))
584 		(void) fprintf(fp, "  NO   ");
585 	else
586 		(void) fprintf(fp, " YES   ");
587 
588 	if (zpool_prop_values(prop) == NULL)
589 		(void) fprintf(fp, "-\n");
590 	else
591 		(void) fprintf(fp, "%s\n", zpool_prop_values(prop));
592 
593 	return (ZPROP_CONT);
594 }
595 
596 /*
597  * Callback routine that will print out a vdev property value.
598  */
599 static int
600 print_vdev_prop_cb(int prop, void *cb)
601 {
602 	FILE *fp = cb;
603 
604 	(void) fprintf(fp, "\t%-19s  ", vdev_prop_to_name(prop));
605 
606 	if (vdev_prop_readonly(prop))
607 		(void) fprintf(fp, "  NO   ");
608 	else
609 		(void) fprintf(fp, " YES   ");
610 
611 	if (vdev_prop_values(prop) == NULL)
612 		(void) fprintf(fp, "-\n");
613 	else
614 		(void) fprintf(fp, "%s\n", vdev_prop_values(prop));
615 
616 	return (ZPROP_CONT);
617 }
618 
619 /*
620  * Given a leaf vdev name like 'L5' return its VDEV_CONFIG_PATH like
621  * '/dev/disk/by-vdev/L5'.
622  */
623 static const char *
624 vdev_name_to_path(zpool_handle_t *zhp, char *vdev)
625 {
626 	nvlist_t *vdev_nv = zpool_find_vdev(zhp, vdev, NULL, NULL, NULL);
627 	if (vdev_nv == NULL) {
628 		return (NULL);
629 	}
630 	return (fnvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH));
631 }
632 
633 static int
634 zpool_power_on(zpool_handle_t *zhp, char *vdev)
635 {
636 	return (zpool_power(zhp, vdev, B_TRUE));
637 }
638 
639 static int
640 zpool_power_on_and_disk_wait(zpool_handle_t *zhp, char *vdev)
641 {
642 	int rc;
643 
644 	rc = zpool_power_on(zhp, vdev);
645 	if (rc != 0)
646 		return (rc);
647 
648 	(void) zpool_disk_wait(vdev_name_to_path(zhp, vdev));
649 
650 	return (0);
651 }
652 
653 static int
654 zpool_power_on_pool_and_wait_for_devices(zpool_handle_t *zhp)
655 {
656 	nvlist_t *nv;
657 	const char *path = NULL;
658 	int rc;
659 
660 	/* Power up all the devices first */
661 	FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
662 		path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
663 		if (path != NULL) {
664 			rc = zpool_power_on(zhp, (char *)path);
665 			if (rc != 0) {
666 				return (rc);
667 			}
668 		}
669 	}
670 
671 	/*
672 	 * Wait for their devices to show up.  Since we powered them on
673 	 * at roughly the same time, they should all come online around
674 	 * the same time.
675 	 */
676 	FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
677 		path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
678 		(void) zpool_disk_wait(path);
679 	}
680 
681 	return (0);
682 }
683 
684 static int
685 zpool_power_off(zpool_handle_t *zhp, char *vdev)
686 {
687 	return (zpool_power(zhp, vdev, B_FALSE));
688 }
689 
690 /*
691  * Display usage message.  If we're inside a command, display only the usage for
692  * that command.  Otherwise, iterate over the entire command table and display
693  * a complete usage message.
694  */
695 static __attribute__((noreturn)) void
696 usage(boolean_t requested)
697 {
698 	FILE *fp = requested ? stdout : stderr;
699 
700 	if (current_command == NULL) {
701 		int i;
702 
703 		(void) fprintf(fp, gettext("usage: zpool command args ...\n"));
704 		(void) fprintf(fp,
705 		    gettext("where 'command' is one of the following:\n\n"));
706 
707 		for (i = 0; i < NCOMMAND; i++) {
708 			if (command_table[i].name == NULL)
709 				(void) fprintf(fp, "\n");
710 			else
711 				(void) fprintf(fp, "%s",
712 				    get_usage(command_table[i].usage));
713 		}
714 
715 		(void) fprintf(fp,
716 		    gettext("\nFor further help on a command or topic, "
717 		    "run: %s\n"), "zpool help [<topic>]");
718 	} else {
719 		(void) fprintf(fp, gettext("usage:\n"));
720 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
721 	}
722 
723 	if (current_command != NULL &&
724 	    current_prop_type != (ZFS_TYPE_POOL | ZFS_TYPE_VDEV) &&
725 	    ((strcmp(current_command->name, "set") == 0) ||
726 	    (strcmp(current_command->name, "get") == 0) ||
727 	    (strcmp(current_command->name, "list") == 0))) {
728 
729 		(void) fprintf(fp, "%s",
730 		    gettext("\nthe following properties are supported:\n"));
731 
732 		(void) fprintf(fp, "\n\t%-19s  %s   %s\n\n",
733 		    "PROPERTY", "EDIT", "VALUES");
734 
735 		/* Iterate over all properties */
736 		if (current_prop_type == ZFS_TYPE_POOL) {
737 			(void) zprop_iter(print_pool_prop_cb, fp, B_FALSE,
738 			    B_TRUE, current_prop_type);
739 
740 			(void) fprintf(fp, "\t%-19s   ", "feature@...");
741 			(void) fprintf(fp, "YES   "
742 			    "disabled | enabled | active\n");
743 
744 			(void) fprintf(fp, gettext("\nThe feature@ properties "
745 			    "must be appended with a feature name.\n"
746 			    "See zpool-features(7).\n"));
747 		} else if (current_prop_type == ZFS_TYPE_VDEV) {
748 			(void) zprop_iter(print_vdev_prop_cb, fp, B_FALSE,
749 			    B_TRUE, current_prop_type);
750 		}
751 	}
752 
753 	/*
754 	 * See comments at end of main().
755 	 */
756 	if (getenv("ZFS_ABORT") != NULL) {
757 		(void) printf("dumping core by request\n");
758 		abort();
759 	}
760 
761 	exit(requested ? 0 : 2);
762 }
763 
764 /*
765  * zpool initialize [-c | -s | -u] [-w] [-z] <-a | pool> [<vdev> ...]
766  * Initialize all unused blocks in the specified vdevs, or all vdevs in the pool
767  * if none specified.
768  *
769  *	-a	Use all pools.
770  *	-c	Cancel. Ends active initializing.
771  *	-s	Suspend. Initializing can then be restarted with no flags.
772  *	-u	Uninitialize. Clears initialization state.
773  *	-w	Wait. Blocks until initializing has completed.
774  */
775 int
776 zpool_do_initialize(int argc, char **argv)
777 {
778 	int c;
779 	char *poolname;
780 	zpool_handle_t *zhp;
781 	int err = 0;
782 	boolean_t wait = B_FALSE;
783 	boolean_t initialize_all = B_FALSE;
784 	boolean_t zero = B_FALSE;
785 
786 	struct option long_options[] = {
787 		{"cancel",	no_argument,		NULL, 'c'},
788 		{"suspend",	no_argument,		NULL, 's'},
789 		{"uninit",	no_argument,		NULL, 'u'},
790 		{"wait",	no_argument,		NULL, 'w'},
791 		{"all",		no_argument,		NULL, 'a'},
792 		{"zero",	no_argument,		NULL, 'z'},
793 		{0, 0, 0, 0}
794 	};
795 
796 	pool_initialize_func_t cmd_type = POOL_INITIALIZE_START;
797 	while ((c = getopt_long(argc, argv, "acsuwz", long_options,
798 	    NULL)) != -1) {
799 		switch (c) {
800 		case 'a':
801 			initialize_all = B_TRUE;
802 			break;
803 		case 'z':
804 			zero = B_TRUE;
805 			break;
806 		case 'c':
807 			if (cmd_type != POOL_INITIALIZE_START &&
808 			    cmd_type != POOL_INITIALIZE_CANCEL) {
809 				(void) fprintf(stderr, gettext("-c cannot be "
810 				    "combined with other options\n"));
811 				usage(B_FALSE);
812 			}
813 			cmd_type = POOL_INITIALIZE_CANCEL;
814 			break;
815 		case 's':
816 			if (cmd_type != POOL_INITIALIZE_START &&
817 			    cmd_type != POOL_INITIALIZE_SUSPEND) {
818 				(void) fprintf(stderr, gettext("-s cannot be "
819 				    "combined with other options\n"));
820 				usage(B_FALSE);
821 			}
822 			cmd_type = POOL_INITIALIZE_SUSPEND;
823 			break;
824 		case 'u':
825 			if (cmd_type != POOL_INITIALIZE_START &&
826 			    cmd_type != POOL_INITIALIZE_UNINIT) {
827 				(void) fprintf(stderr, gettext("-u cannot be "
828 				    "combined with other options\n"));
829 				usage(B_FALSE);
830 			}
831 			cmd_type = POOL_INITIALIZE_UNINIT;
832 			break;
833 		case 'w':
834 			wait = B_TRUE;
835 			break;
836 		case '?':
837 			if (optopt != 0) {
838 				(void) fprintf(stderr,
839 				    gettext("invalid option '%c'\n"), optopt);
840 			} else {
841 				(void) fprintf(stderr,
842 				    gettext("invalid option '%s'\n"),
843 				    argv[optind - 1]);
844 			}
845 			usage(B_FALSE);
846 		}
847 	}
848 
849 	argc -= optind;
850 	argv += optind;
851 
852 	initialize_cbdata_t cbdata = {
853 		.wait = wait,
854 		.cmd_type = cmd_type,
855 		.value = 0,
856 		.value_provided = zero
857 	};
858 
859 	if (initialize_all && argc > 0) {
860 		(void) fprintf(stderr, gettext("-a cannot be combined with "
861 		    "individual pools or vdevs\n"));
862 		usage(B_FALSE);
863 	}
864 
865 	if (argc < 1 && !initialize_all) {
866 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
867 		usage(B_FALSE);
868 	}
869 
870 	if (wait && (cmd_type != POOL_INITIALIZE_START)) {
871 		(void) fprintf(stderr, gettext("-w cannot be used with -c, -s"
872 		    "or -u\n"));
873 		usage(B_FALSE);
874 	}
875 
876 	if (zero && (cmd_type != POOL_INITIALIZE_START)) {
877 		(void) fprintf(stderr, gettext("-z cannot be used with -c, -s "
878 		    "or -u\n"));
879 		usage(B_FALSE);
880 	}
881 
882 	if (argc == 0 && initialize_all) {
883 		/* Initilize each pool recursively */
884 		err = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
885 		    B_FALSE, zpool_initialize_one, &cbdata);
886 		return (err);
887 	} else if (argc == 1) {
888 		/* no individual leaf vdevs specified, initialize the pool */
889 		poolname = argv[0];
890 		zhp = zpool_open(g_zfs, poolname);
891 		if (zhp == NULL)
892 			return (-1);
893 		err = zpool_initialize_one(zhp, &cbdata);
894 	} else {
895 		/* individual leaf vdevs specified, initialize them */
896 		poolname = argv[0];
897 		zhp = zpool_open(g_zfs, poolname);
898 		if (zhp == NULL)
899 			return (-1);
900 		nvlist_t *vdevs = fnvlist_alloc();
901 		for (int i = 1; i < argc; i++) {
902 			fnvlist_add_boolean(vdevs, argv[i]);
903 		}
904 		if (wait)
905 			err = zpool_initialize_wait(zhp, cmd_type, vdevs,
906 			    cbdata.value, cbdata.value_provided);
907 		else
908 			err = zpool_initialize(zhp, cmd_type, vdevs,
909 			    cbdata.value, cbdata.value_provided);
910 		fnvlist_free(vdevs);
911 	}
912 
913 	zpool_close(zhp);
914 
915 	return (err);
916 }
917 
918 /*
919  * print a pool vdev config for dry runs
920  */
921 static void
922 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
923     const char *match, int name_flags)
924 {
925 	nvlist_t **child;
926 	uint_t c, children;
927 	char *vname;
928 	boolean_t printed = B_FALSE;
929 
930 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
931 	    &child, &children) != 0) {
932 		if (name != NULL)
933 			(void) printf("\t%*s%s\n", indent, "", name);
934 		return;
935 	}
936 
937 	for (c = 0; c < children; c++) {
938 		uint64_t is_log = B_FALSE, is_hole = B_FALSE;
939 		const char *class = "";
940 
941 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
942 		    &is_hole);
943 
944 		if (is_hole == B_TRUE) {
945 			continue;
946 		}
947 
948 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
949 		    &is_log);
950 		if (is_log)
951 			class = VDEV_ALLOC_BIAS_LOG;
952 		(void) nvlist_lookup_string(child[c],
953 		    ZPOOL_CONFIG_ALLOCATION_BIAS, &class);
954 		if (strcmp(match, class) != 0)
955 			continue;
956 
957 		if (!printed && name != NULL) {
958 			(void) printf("\t%*s%s\n", indent, "", name);
959 			printed = B_TRUE;
960 		}
961 		vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
962 		print_vdev_tree(zhp, vname, child[c], indent + 2, "",
963 		    name_flags);
964 		free(vname);
965 	}
966 }
967 
968 /*
969  * Print the list of l2cache devices for dry runs.
970  */
971 static void
972 print_cache_list(nvlist_t *nv, int indent)
973 {
974 	nvlist_t **child;
975 	uint_t c, children;
976 
977 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
978 	    &child, &children) == 0 && children > 0) {
979 		(void) printf("\t%*s%s\n", indent, "", "cache");
980 	} else {
981 		return;
982 	}
983 	for (c = 0; c < children; c++) {
984 		char *vname;
985 
986 		vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
987 		(void) printf("\t%*s%s\n", indent + 2, "", vname);
988 		free(vname);
989 	}
990 }
991 
992 /*
993  * Print the list of spares for dry runs.
994  */
995 static void
996 print_spare_list(nvlist_t *nv, int indent)
997 {
998 	nvlist_t **child;
999 	uint_t c, children;
1000 
1001 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1002 	    &child, &children) == 0 && children > 0) {
1003 		(void) printf("\t%*s%s\n", indent, "", "spares");
1004 	} else {
1005 		return;
1006 	}
1007 	for (c = 0; c < children; c++) {
1008 		char *vname;
1009 
1010 		vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
1011 		(void) printf("\t%*s%s\n", indent + 2, "", vname);
1012 		free(vname);
1013 	}
1014 }
1015 
1016 typedef struct spare_cbdata {
1017 	uint64_t	cb_guid;
1018 	zpool_handle_t	*cb_zhp;
1019 } spare_cbdata_t;
1020 
1021 static boolean_t
1022 find_vdev(nvlist_t *nv, uint64_t search)
1023 {
1024 	uint64_t guid;
1025 	nvlist_t **child;
1026 	uint_t c, children;
1027 
1028 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1029 	    search == guid)
1030 		return (B_TRUE);
1031 
1032 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1033 	    &child, &children) == 0) {
1034 		for (c = 0; c < children; c++)
1035 			if (find_vdev(child[c], search))
1036 				return (B_TRUE);
1037 	}
1038 
1039 	return (B_FALSE);
1040 }
1041 
1042 static int
1043 find_spare(zpool_handle_t *zhp, void *data)
1044 {
1045 	spare_cbdata_t *cbp = data;
1046 	nvlist_t *config, *nvroot;
1047 
1048 	config = zpool_get_config(zhp, NULL);
1049 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1050 	    &nvroot) == 0);
1051 
1052 	if (find_vdev(nvroot, cbp->cb_guid)) {
1053 		cbp->cb_zhp = zhp;
1054 		return (1);
1055 	}
1056 
1057 	zpool_close(zhp);
1058 	return (0);
1059 }
1060 
1061 static void
1062 nice_num_str_nvlist(nvlist_t *item, const char *key, uint64_t value,
1063     boolean_t literal, boolean_t as_int, int format)
1064 {
1065 	char buf[256];
1066 
1067 	if (literal) {
1068 		if (!as_int)
1069 			(void) snprintf(buf, 256, "%llu", (u_longlong_t)value);
1070 	} else {
1071 		switch (format) {
1072 		case ZFS_NICENUM_1024:
1073 			zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_1024);
1074 			break;
1075 		case ZFS_NICENUM_BYTES:
1076 			zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_BYTES);
1077 			break;
1078 		case ZFS_NICENUM_TIME:
1079 			zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_TIME);
1080 			break;
1081 		case ZFS_NICE_TIMESTAMP:
1082 			format_timestamp(value, buf, 256);
1083 			break;
1084 		default:
1085 			fprintf(stderr, "Invalid number format");
1086 			exit(1);
1087 		}
1088 	}
1089 	if (as_int)
1090 		fnvlist_add_uint64(item, key, value);
1091 	else
1092 		fnvlist_add_string(item, key, buf);
1093 }
1094 
1095 /*
1096  * Generates an nvlist with output version for every command based on params.
1097  * Purpose of this is to add a version of JSON output, considering the schema
1098  * format might be updated for each command in future.
1099  *
1100  * Schema:
1101  *
1102  * "output_version": {
1103  *    "command": string,
1104  *    "vers_major": integer,
1105  *    "vers_minor": integer,
1106  *  }
1107  */
1108 static nvlist_t *
1109 zpool_json_schema(int maj_v, int min_v)
1110 {
1111 	char cmd[MAX_CMD_LEN];
1112 	nvlist_t *sch = fnvlist_alloc();
1113 	nvlist_t *ov = fnvlist_alloc();
1114 
1115 	(void) snprintf(cmd, MAX_CMD_LEN, "zpool %s", current_command->name);
1116 	fnvlist_add_string(ov, "command", cmd);
1117 	fnvlist_add_uint32(ov, "vers_major", maj_v);
1118 	fnvlist_add_uint32(ov, "vers_minor", min_v);
1119 	fnvlist_add_nvlist(sch, "output_version", ov);
1120 	fnvlist_free(ov);
1121 	return (sch);
1122 }
1123 
1124 static void
1125 fill_pool_info(nvlist_t *list, zpool_handle_t *zhp, boolean_t addtype,
1126     boolean_t as_int)
1127 {
1128 	nvlist_t *config = zpool_get_config(zhp, NULL);
1129 	uint64_t guid = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID);
1130 	uint64_t txg = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG);
1131 
1132 	fnvlist_add_string(list, "name", zpool_get_name(zhp));
1133 	if (addtype)
1134 		fnvlist_add_string(list, "type", "POOL");
1135 	fnvlist_add_string(list, "state", zpool_get_state_str(zhp));
1136 	if (as_int) {
1137 		if (guid)
1138 			fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_GUID, guid);
1139 		if (txg)
1140 			fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_TXG, txg);
1141 		fnvlist_add_uint64(list, "spa_version", SPA_VERSION);
1142 		fnvlist_add_uint64(list, "zpl_version", ZPL_VERSION);
1143 	} else {
1144 		char value[ZFS_MAXPROPLEN];
1145 		if (guid) {
1146 			(void) snprintf(value, ZFS_MAXPROPLEN, "%llu",
1147 			    (u_longlong_t)guid);
1148 			fnvlist_add_string(list, ZPOOL_CONFIG_POOL_GUID, value);
1149 		}
1150 		if (txg) {
1151 			(void) snprintf(value, ZFS_MAXPROPLEN, "%llu",
1152 			    (u_longlong_t)txg);
1153 			fnvlist_add_string(list, ZPOOL_CONFIG_POOL_TXG, value);
1154 		}
1155 		fnvlist_add_string(list, "spa_version", SPA_VERSION_STRING);
1156 		fnvlist_add_string(list, "zpl_version", ZPL_VERSION_STRING);
1157 	}
1158 }
1159 
1160 static void
1161 used_by_other(zpool_handle_t *zhp, nvlist_t *nvdev, nvlist_t *list)
1162 {
1163 	spare_cbdata_t spare_cb;
1164 	verify(nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID,
1165 	    &spare_cb.cb_guid) == 0);
1166 	if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1167 		if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1168 		    zpool_get_name(zhp)) != 0) {
1169 			fnvlist_add_string(list, "used_by",
1170 			    zpool_get_name(spare_cb.cb_zhp));
1171 		}
1172 		zpool_close(spare_cb.cb_zhp);
1173 	}
1174 }
1175 
1176 static void
1177 fill_vdev_info(nvlist_t *list, zpool_handle_t *zhp, char *name,
1178     boolean_t addtype, boolean_t as_int)
1179 {
1180 	boolean_t l2c = B_FALSE;
1181 	const char *path, *phys, *devid, *bias = NULL;
1182 	uint64_t hole = 0, log = 0, spare = 0;
1183 	vdev_stat_t *vs;
1184 	uint_t c;
1185 	nvlist_t *nvdev;
1186 	nvlist_t *nvdev_parent = NULL;
1187 	char *_name;
1188 
1189 	if (strcmp(name, zpool_get_name(zhp)) != 0)
1190 		_name = name;
1191 	else
1192 		_name = (char *)"root-0";
1193 
1194 	nvdev = zpool_find_vdev(zhp, _name, NULL, &l2c, NULL);
1195 
1196 	fnvlist_add_string(list, "name", name);
1197 	if (addtype)
1198 		fnvlist_add_string(list, "type", "VDEV");
1199 	if (nvdev) {
1200 		const char *type = fnvlist_lookup_string(nvdev,
1201 		    ZPOOL_CONFIG_TYPE);
1202 		if (type)
1203 			fnvlist_add_string(list, "vdev_type", type);
1204 		uint64_t guid = fnvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID);
1205 		if (guid) {
1206 			if (as_int) {
1207 				fnvlist_add_uint64(list, "guid", guid);
1208 			} else {
1209 				char buf[ZFS_MAXPROPLEN];
1210 				(void) snprintf(buf, ZFS_MAXPROPLEN, "%llu",
1211 				    (u_longlong_t)guid);
1212 				fnvlist_add_string(list, "guid", buf);
1213 			}
1214 		}
1215 		if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PATH, &path) == 0)
1216 			fnvlist_add_string(list, "path", path);
1217 		if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PHYS_PATH,
1218 		    &phys) == 0)
1219 			fnvlist_add_string(list, "phys_path", phys);
1220 		if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_DEVID,
1221 		    &devid) == 0)
1222 			fnvlist_add_string(list, "devid", devid);
1223 		(void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_LOG, &log);
1224 		(void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_SPARE,
1225 		    &spare);
1226 		(void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_HOLE, &hole);
1227 		if (hole)
1228 			fnvlist_add_string(list, "class", VDEV_TYPE_HOLE);
1229 		else if (l2c)
1230 			fnvlist_add_string(list, "class", VDEV_TYPE_L2CACHE);
1231 		else if (spare)
1232 			fnvlist_add_string(list, "class", VDEV_TYPE_SPARE);
1233 		else if (log)
1234 			fnvlist_add_string(list, "class", VDEV_TYPE_LOG);
1235 		else {
1236 			(void) nvlist_lookup_string(nvdev,
1237 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
1238 			if (bias != NULL)
1239 				fnvlist_add_string(list, "class", bias);
1240 			else {
1241 				nvdev_parent = NULL;
1242 				nvdev_parent = zpool_find_parent_vdev(zhp,
1243 				    _name, NULL, NULL, NULL);
1244 
1245 				/*
1246 				 * With a mirrored special device, the parent
1247 				 * "mirror" vdev will have
1248 				 * ZPOOL_CONFIG_ALLOCATION_BIAS set to "special"
1249 				 * not the leaf vdevs.  If we're a leaf vdev
1250 				 * in that case we need to look at our parent
1251 				 * to see if they're "special" to know if we
1252 				 * are "special" too.
1253 				 */
1254 				if (nvdev_parent) {
1255 					(void) nvlist_lookup_string(
1256 					    nvdev_parent,
1257 					    ZPOOL_CONFIG_ALLOCATION_BIAS,
1258 					    &bias);
1259 				}
1260 				if (bias != NULL)
1261 					fnvlist_add_string(list, "class", bias);
1262 				else
1263 					fnvlist_add_string(list, "class",
1264 					    "normal");
1265 			}
1266 		}
1267 		if (nvlist_lookup_uint64_array(nvdev, ZPOOL_CONFIG_VDEV_STATS,
1268 		    (uint64_t **)&vs, &c) == 0) {
1269 			fnvlist_add_string(list, "state",
1270 			    vdev_state_str[vs->vs_state]);
1271 		}
1272 	}
1273 }
1274 
1275 static boolean_t
1276 prop_list_contains_feature(nvlist_t *proplist)
1277 {
1278 	nvpair_t *nvp;
1279 	for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
1280 	    nvp = nvlist_next_nvpair(proplist, nvp)) {
1281 		if (zpool_prop_feature(nvpair_name(nvp)))
1282 			return (B_TRUE);
1283 	}
1284 	return (B_FALSE);
1285 }
1286 
1287 /*
1288  * Add a property pair (name, string-value) into a property nvlist.
1289  */
1290 static int
1291 add_prop_list(const char *propname, const char *propval, nvlist_t **props,
1292     boolean_t poolprop)
1293 {
1294 	zpool_prop_t prop = ZPOOL_PROP_INVAL;
1295 	nvlist_t *proplist;
1296 	const char *normnm;
1297 	const char *strval;
1298 
1299 	if (*props == NULL &&
1300 	    nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
1301 		(void) fprintf(stderr,
1302 		    gettext("internal error: out of memory\n"));
1303 		return (1);
1304 	}
1305 
1306 	proplist = *props;
1307 
1308 	if (poolprop) {
1309 		const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
1310 		const char *cname =
1311 		    zpool_prop_to_name(ZPOOL_PROP_COMPATIBILITY);
1312 
1313 		if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
1314 		    (!zpool_prop_feature(propname) &&
1315 		    !zpool_prop_vdev(propname))) {
1316 			(void) fprintf(stderr, gettext("property '%s' is "
1317 			    "not a valid pool or vdev property\n"), propname);
1318 			return (2);
1319 		}
1320 
1321 		/*
1322 		 * feature@ properties and version should not be specified
1323 		 * at the same time.
1324 		 */
1325 		if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
1326 		    nvlist_exists(proplist, vname)) ||
1327 		    (prop == ZPOOL_PROP_VERSION &&
1328 		    prop_list_contains_feature(proplist))) {
1329 			(void) fprintf(stderr, gettext("'feature@' and "
1330 			    "'version' properties cannot be specified "
1331 			    "together\n"));
1332 			return (2);
1333 		}
1334 
1335 		/*
1336 		 * if version is specified, only "legacy" compatibility
1337 		 * may be requested
1338 		 */
1339 		if ((prop == ZPOOL_PROP_COMPATIBILITY &&
1340 		    strcmp(propval, ZPOOL_COMPAT_LEGACY) != 0 &&
1341 		    nvlist_exists(proplist, vname)) ||
1342 		    (prop == ZPOOL_PROP_VERSION &&
1343 		    nvlist_exists(proplist, cname) &&
1344 		    strcmp(fnvlist_lookup_string(proplist, cname),
1345 		    ZPOOL_COMPAT_LEGACY) != 0)) {
1346 			(void) fprintf(stderr, gettext("when 'version' is "
1347 			    "specified, the 'compatibility' feature may only "
1348 			    "be set to '" ZPOOL_COMPAT_LEGACY "'\n"));
1349 			return (2);
1350 		}
1351 
1352 		if (zpool_prop_feature(propname) || zpool_prop_vdev(propname))
1353 			normnm = propname;
1354 		else
1355 			normnm = zpool_prop_to_name(prop);
1356 	} else {
1357 		zfs_prop_t fsprop = zfs_name_to_prop(propname);
1358 
1359 		if (zfs_prop_valid_for_type(fsprop, ZFS_TYPE_FILESYSTEM,
1360 		    B_FALSE)) {
1361 			normnm = zfs_prop_to_name(fsprop);
1362 		} else if (zfs_prop_user(propname) ||
1363 		    zfs_prop_userquota(propname)) {
1364 			normnm = propname;
1365 		} else {
1366 			(void) fprintf(stderr, gettext("property '%s' is "
1367 			    "not a valid filesystem property\n"), propname);
1368 			return (2);
1369 		}
1370 	}
1371 
1372 	if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
1373 	    prop != ZPOOL_PROP_CACHEFILE) {
1374 		(void) fprintf(stderr, gettext("property '%s' "
1375 		    "specified multiple times\n"), propname);
1376 		return (2);
1377 	}
1378 
1379 	if (nvlist_add_string(proplist, normnm, propval) != 0) {
1380 		(void) fprintf(stderr, gettext("internal "
1381 		    "error: out of memory\n"));
1382 		return (1);
1383 	}
1384 
1385 	return (0);
1386 }
1387 
1388 /*
1389  * Set a default property pair (name, string-value) in a property nvlist
1390  */
1391 static int
1392 add_prop_list_default(const char *propname, const char *propval,
1393     nvlist_t **props)
1394 {
1395 	const char *pval;
1396 
1397 	if (nvlist_lookup_string(*props, propname, &pval) == 0)
1398 		return (0);
1399 
1400 	return (add_prop_list(propname, propval, props, B_TRUE));
1401 }
1402 
1403 /*
1404  * zpool add [-afgLnP] [-o property=value] <pool> <vdev> ...
1405  *
1406  *	-a	Disable the ashift validation checks
1407  *	-f	Force addition of devices, even if they appear in use
1408  *	-g	Display guid for individual vdev name.
1409  *	-L	Follow links when resolving vdev path name.
1410  *	-n	Do not add the devices, but display the resulting layout if
1411  *		they were to be added.
1412  *	-o	Set property=value.
1413  *	-P	Display full path for vdev name.
1414  *
1415  * Adds the given vdevs to 'pool'.  As with create, the bulk of this work is
1416  * handled by make_root_vdev(), which constructs the nvlist needed to pass to
1417  * libzfs.
1418  */
1419 int
1420 zpool_do_add(int argc, char **argv)
1421 {
1422 	boolean_t check_replication = B_TRUE;
1423 	boolean_t check_inuse = B_TRUE;
1424 	boolean_t dryrun = B_FALSE;
1425 	boolean_t check_ashift = B_TRUE;
1426 	boolean_t force = B_FALSE;
1427 	int name_flags = 0;
1428 	int c;
1429 	nvlist_t *nvroot;
1430 	char *poolname;
1431 	int ret;
1432 	zpool_handle_t *zhp;
1433 	nvlist_t *config;
1434 	nvlist_t *props = NULL;
1435 	char *propval;
1436 
1437 	struct option long_options[] = {
1438 		{"allow-in-use", no_argument, NULL, ZPOOL_OPTION_ALLOW_INUSE},
1439 		{"allow-replication-mismatch", no_argument, NULL,
1440 		    ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH},
1441 		{"allow-ashift-mismatch", no_argument, NULL,
1442 		    ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH},
1443 		{0, 0, 0, 0}
1444 	};
1445 
1446 	/* check options */
1447 	while ((c = getopt_long(argc, argv, "fgLno:P", long_options, NULL))
1448 	    != -1) {
1449 		switch (c) {
1450 		case 'f':
1451 			force = B_TRUE;
1452 			break;
1453 		case 'g':
1454 			name_flags |= VDEV_NAME_GUID;
1455 			break;
1456 		case 'L':
1457 			name_flags |= VDEV_NAME_FOLLOW_LINKS;
1458 			break;
1459 		case 'n':
1460 			dryrun = B_TRUE;
1461 			break;
1462 		case 'o':
1463 			if ((propval = strchr(optarg, '=')) == NULL) {
1464 				(void) fprintf(stderr, gettext("missing "
1465 				    "'=' for -o option\n"));
1466 				usage(B_FALSE);
1467 			}
1468 			*propval = '\0';
1469 			propval++;
1470 
1471 			if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
1472 			    (add_prop_list(optarg, propval, &props, B_TRUE)))
1473 				usage(B_FALSE);
1474 			break;
1475 		case 'P':
1476 			name_flags |= VDEV_NAME_PATH;
1477 			break;
1478 		case ZPOOL_OPTION_ALLOW_INUSE:
1479 			check_inuse = B_FALSE;
1480 			break;
1481 		case ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH:
1482 			check_replication = B_FALSE;
1483 			break;
1484 		case ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH:
1485 			check_ashift = B_FALSE;
1486 			break;
1487 		case '?':
1488 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1489 			    optopt);
1490 			usage(B_FALSE);
1491 		}
1492 	}
1493 
1494 	argc -= optind;
1495 	argv += optind;
1496 
1497 	/* get pool name and check number of arguments */
1498 	if (argc < 1) {
1499 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
1500 		usage(B_FALSE);
1501 	}
1502 	if (argc < 2) {
1503 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
1504 		usage(B_FALSE);
1505 	}
1506 
1507 	if (force) {
1508 		if (!check_inuse || !check_replication || !check_ashift) {
1509 			(void) fprintf(stderr, gettext("'-f' option is not "
1510 			    "allowed with '--allow-replication-mismatch', "
1511 			    "'--allow-ashift-mismatch', or "
1512 			    "'--allow-in-use'\n"));
1513 			usage(B_FALSE);
1514 		}
1515 		check_inuse = B_FALSE;
1516 		check_replication = B_FALSE;
1517 		check_ashift = B_FALSE;
1518 	}
1519 
1520 	poolname = argv[0];
1521 
1522 	argc--;
1523 	argv++;
1524 
1525 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1526 		return (1);
1527 
1528 	if ((config = zpool_get_config(zhp, NULL)) == NULL) {
1529 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
1530 		    poolname);
1531 		zpool_close(zhp);
1532 		return (1);
1533 	}
1534 
1535 	/* unless manually specified use "ashift" pool property (if set) */
1536 	if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
1537 		int intval;
1538 		zprop_source_t src;
1539 		char strval[ZPOOL_MAXPROPLEN];
1540 
1541 		intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
1542 		if (src != ZPROP_SRC_DEFAULT) {
1543 			(void) sprintf(strval, "%" PRId32, intval);
1544 			verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
1545 			    &props, B_TRUE) == 0);
1546 		}
1547 	}
1548 
1549 	/* pass off to make_root_vdev for processing */
1550 	nvroot = make_root_vdev(zhp, props, !check_inuse,
1551 	    check_replication, B_FALSE, dryrun, argc, argv);
1552 	if (nvroot == NULL) {
1553 		zpool_close(zhp);
1554 		return (1);
1555 	}
1556 
1557 	if (dryrun) {
1558 		nvlist_t *poolnvroot;
1559 		nvlist_t **l2child, **sparechild;
1560 		uint_t l2children, sparechildren, c;
1561 		char *vname;
1562 		boolean_t hadcache = B_FALSE, hadspare = B_FALSE;
1563 
1564 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1565 		    &poolnvroot) == 0);
1566 
1567 		(void) printf(gettext("would update '%s' to the following "
1568 		    "configuration:\n\n"), zpool_get_name(zhp));
1569 
1570 		/* print original main pool and new tree */
1571 		print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
1572 		    name_flags | VDEV_NAME_TYPE_ID);
1573 		print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
1574 
1575 		/* print other classes: 'dedup', 'special', and 'log' */
1576 		if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1577 			print_vdev_tree(zhp, "dedup", poolnvroot, 0,
1578 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1579 			print_vdev_tree(zhp, NULL, nvroot, 0,
1580 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1581 		} else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1582 			print_vdev_tree(zhp, "dedup", nvroot, 0,
1583 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1584 		}
1585 
1586 		if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1587 			print_vdev_tree(zhp, "special", poolnvroot, 0,
1588 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1589 			print_vdev_tree(zhp, NULL, nvroot, 0,
1590 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1591 		} else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1592 			print_vdev_tree(zhp, "special", nvroot, 0,
1593 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1594 		}
1595 
1596 		if (num_logs(poolnvroot) > 0) {
1597 			print_vdev_tree(zhp, "logs", poolnvroot, 0,
1598 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1599 			print_vdev_tree(zhp, NULL, nvroot, 0,
1600 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1601 		} else if (num_logs(nvroot) > 0) {
1602 			print_vdev_tree(zhp, "logs", nvroot, 0,
1603 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1604 		}
1605 
1606 		/* Do the same for the caches */
1607 		if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
1608 		    &l2child, &l2children) == 0 && l2children) {
1609 			hadcache = B_TRUE;
1610 			(void) printf(gettext("\tcache\n"));
1611 			for (c = 0; c < l2children; c++) {
1612 				vname = zpool_vdev_name(g_zfs, NULL,
1613 				    l2child[c], name_flags);
1614 				(void) printf("\t  %s\n", vname);
1615 				free(vname);
1616 			}
1617 		}
1618 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1619 		    &l2child, &l2children) == 0 && l2children) {
1620 			if (!hadcache)
1621 				(void) printf(gettext("\tcache\n"));
1622 			for (c = 0; c < l2children; c++) {
1623 				vname = zpool_vdev_name(g_zfs, NULL,
1624 				    l2child[c], name_flags);
1625 				(void) printf("\t  %s\n", vname);
1626 				free(vname);
1627 			}
1628 		}
1629 		/* And finally the spares */
1630 		if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_SPARES,
1631 		    &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1632 			hadspare = B_TRUE;
1633 			(void) printf(gettext("\tspares\n"));
1634 			for (c = 0; c < sparechildren; c++) {
1635 				vname = zpool_vdev_name(g_zfs, NULL,
1636 				    sparechild[c], name_flags);
1637 				(void) printf("\t  %s\n", vname);
1638 				free(vname);
1639 			}
1640 		}
1641 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1642 		    &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1643 			if (!hadspare)
1644 				(void) printf(gettext("\tspares\n"));
1645 			for (c = 0; c < sparechildren; c++) {
1646 				vname = zpool_vdev_name(g_zfs, NULL,
1647 				    sparechild[c], name_flags);
1648 				(void) printf("\t  %s\n", vname);
1649 				free(vname);
1650 			}
1651 		}
1652 
1653 		ret = 0;
1654 	} else {
1655 		ret = (zpool_add(zhp, nvroot, check_ashift) != 0);
1656 	}
1657 
1658 	nvlist_free(props);
1659 	nvlist_free(nvroot);
1660 	zpool_close(zhp);
1661 
1662 	return (ret);
1663 }
1664 
1665 /*
1666  * zpool remove [-npsw] <pool> <vdev> ...
1667  *
1668  * Removes the given vdev from the pool.
1669  */
1670 int
1671 zpool_do_remove(int argc, char **argv)
1672 {
1673 	char *poolname;
1674 	int i, ret = 0;
1675 	zpool_handle_t *zhp = NULL;
1676 	boolean_t stop = B_FALSE;
1677 	int c;
1678 	boolean_t noop = B_FALSE;
1679 	boolean_t parsable = B_FALSE;
1680 	boolean_t wait = B_FALSE;
1681 
1682 	/* check options */
1683 	while ((c = getopt(argc, argv, "npsw")) != -1) {
1684 		switch (c) {
1685 		case 'n':
1686 			noop = B_TRUE;
1687 			break;
1688 		case 'p':
1689 			parsable = B_TRUE;
1690 			break;
1691 		case 's':
1692 			stop = B_TRUE;
1693 			break;
1694 		case 'w':
1695 			wait = B_TRUE;
1696 			break;
1697 		case '?':
1698 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1699 			    optopt);
1700 			usage(B_FALSE);
1701 		}
1702 	}
1703 
1704 	argc -= optind;
1705 	argv += optind;
1706 
1707 	/* get pool name and check number of arguments */
1708 	if (argc < 1) {
1709 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
1710 		usage(B_FALSE);
1711 	}
1712 
1713 	poolname = argv[0];
1714 
1715 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1716 		return (1);
1717 
1718 	if (stop && noop) {
1719 		zpool_close(zhp);
1720 		(void) fprintf(stderr, gettext("stop request ignored\n"));
1721 		return (0);
1722 	}
1723 
1724 	if (stop) {
1725 		if (argc > 1) {
1726 			(void) fprintf(stderr, gettext("too many arguments\n"));
1727 			usage(B_FALSE);
1728 		}
1729 		if (zpool_vdev_remove_cancel(zhp) != 0)
1730 			ret = 1;
1731 		if (wait) {
1732 			(void) fprintf(stderr, gettext("invalid option "
1733 			    "combination: -w cannot be used with -s\n"));
1734 			usage(B_FALSE);
1735 		}
1736 	} else {
1737 		if (argc < 2) {
1738 			(void) fprintf(stderr, gettext("missing device\n"));
1739 			usage(B_FALSE);
1740 		}
1741 
1742 		for (i = 1; i < argc; i++) {
1743 			if (noop) {
1744 				uint64_t size;
1745 
1746 				if (zpool_vdev_indirect_size(zhp, argv[i],
1747 				    &size) != 0) {
1748 					ret = 1;
1749 					break;
1750 				}
1751 				if (parsable) {
1752 					(void) printf("%s %llu\n",
1753 					    argv[i], (unsigned long long)size);
1754 				} else {
1755 					char valstr[32];
1756 					zfs_nicenum(size, valstr,
1757 					    sizeof (valstr));
1758 					(void) printf("Memory that will be "
1759 					    "used after removing %s: %s\n",
1760 					    argv[i], valstr);
1761 				}
1762 			} else {
1763 				if (zpool_vdev_remove(zhp, argv[i]) != 0)
1764 					ret = 1;
1765 			}
1766 		}
1767 
1768 		if (ret == 0 && wait)
1769 			ret = zpool_wait(zhp, ZPOOL_WAIT_REMOVE);
1770 	}
1771 	zpool_close(zhp);
1772 
1773 	return (ret);
1774 }
1775 
1776 /*
1777  * Return 1 if a vdev is active (being used in a pool)
1778  * Return 0 if a vdev is inactive (offlined or faulted, or not in active pool)
1779  *
1780  * This is useful for checking if a disk in an active pool is offlined or
1781  * faulted.
1782  */
1783 static int
1784 vdev_is_active(char *vdev_path)
1785 {
1786 	int fd;
1787 	fd = open(vdev_path, O_EXCL);
1788 	if (fd < 0) {
1789 		return (1);   /* cant open O_EXCL - disk is active */
1790 	}
1791 
1792 	(void) close(fd);
1793 	return (0);   /* disk is inactive in the pool */
1794 }
1795 
1796 /*
1797  * zpool labelclear [-f] <vdev>
1798  *
1799  *	-f	Force clearing the label for the vdevs which are members of
1800  *		the exported or foreign pools.
1801  *
1802  * Verifies that the vdev is not active and zeros out the label information
1803  * on the device.
1804  */
1805 int
1806 zpool_do_labelclear(int argc, char **argv)
1807 {
1808 	char vdev[MAXPATHLEN];
1809 	char *name = NULL;
1810 	int c, fd, ret = 0;
1811 	nvlist_t *config;
1812 	pool_state_t state;
1813 	boolean_t inuse = B_FALSE;
1814 	boolean_t force = B_FALSE;
1815 
1816 	/* check options */
1817 	while ((c = getopt(argc, argv, "f")) != -1) {
1818 		switch (c) {
1819 		case 'f':
1820 			force = B_TRUE;
1821 			break;
1822 		default:
1823 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1824 			    optopt);
1825 			usage(B_FALSE);
1826 		}
1827 	}
1828 
1829 	argc -= optind;
1830 	argv += optind;
1831 
1832 	/* get vdev name */
1833 	if (argc < 1) {
1834 		(void) fprintf(stderr, gettext("missing vdev name\n"));
1835 		usage(B_FALSE);
1836 	}
1837 	if (argc > 1) {
1838 		(void) fprintf(stderr, gettext("too many arguments\n"));
1839 		usage(B_FALSE);
1840 	}
1841 
1842 	(void) strlcpy(vdev, argv[0], sizeof (vdev));
1843 
1844 	/*
1845 	 * If we cannot open an absolute path, we quit.
1846 	 * Otherwise if the provided vdev name doesn't point to a file,
1847 	 * try prepending expected disk paths and partition numbers.
1848 	 */
1849 	if ((fd = open(vdev, O_RDWR)) < 0) {
1850 		int error;
1851 		if (vdev[0] == '/') {
1852 			(void) fprintf(stderr, gettext("failed to open "
1853 			    "%s: %s\n"), vdev, strerror(errno));
1854 			return (1);
1855 		}
1856 
1857 		error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
1858 		if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
1859 			if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
1860 				error = ENOENT;
1861 		}
1862 
1863 		if (error || ((fd = open(vdev, O_RDWR)) < 0)) {
1864 			if (errno == ENOENT) {
1865 				(void) fprintf(stderr, gettext(
1866 				    "failed to find device %s, try "
1867 				    "specifying absolute path instead\n"),
1868 				    argv[0]);
1869 				return (1);
1870 			}
1871 
1872 			(void) fprintf(stderr, gettext("failed to open %s:"
1873 			    " %s\n"), vdev, strerror(errno));
1874 			return (1);
1875 		}
1876 	}
1877 
1878 	/*
1879 	 * Flush all dirty pages for the block device.  This should not be
1880 	 * fatal when the device does not support BLKFLSBUF as would be the
1881 	 * case for a file vdev.
1882 	 */
1883 	if ((zfs_dev_flush(fd) != 0) && (errno != ENOTTY))
1884 		(void) fprintf(stderr, gettext("failed to invalidate "
1885 		    "cache for %s: %s\n"), vdev, strerror(errno));
1886 
1887 	if (zpool_read_label(fd, &config, NULL) != 0) {
1888 		(void) fprintf(stderr,
1889 		    gettext("failed to read label from %s\n"), vdev);
1890 		ret = 1;
1891 		goto errout;
1892 	}
1893 	nvlist_free(config);
1894 
1895 	ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1896 	if (ret != 0) {
1897 		(void) fprintf(stderr,
1898 		    gettext("failed to check state for %s\n"), vdev);
1899 		ret = 1;
1900 		goto errout;
1901 	}
1902 
1903 	if (!inuse)
1904 		goto wipe_label;
1905 
1906 	switch (state) {
1907 	default:
1908 	case POOL_STATE_ACTIVE:
1909 	case POOL_STATE_SPARE:
1910 	case POOL_STATE_L2CACHE:
1911 		/*
1912 		 * We allow the user to call 'zpool offline -f'
1913 		 * on an offlined disk in an active pool. We can check if
1914 		 * the disk is online by calling vdev_is_active().
1915 		 */
1916 		if (force && !vdev_is_active(vdev))
1917 			break;
1918 
1919 		(void) fprintf(stderr, gettext(
1920 		    "%s is a member (%s) of pool \"%s\""),
1921 		    vdev, zpool_pool_state_to_name(state), name);
1922 
1923 		if (force) {
1924 			(void) fprintf(stderr, gettext(
1925 			    ". Offline the disk first to clear its label."));
1926 		}
1927 		printf("\n");
1928 		ret = 1;
1929 		goto errout;
1930 
1931 	case POOL_STATE_EXPORTED:
1932 		if (force)
1933 			break;
1934 		(void) fprintf(stderr, gettext(
1935 		    "use '-f' to override the following error:\n"
1936 		    "%s is a member of exported pool \"%s\"\n"),
1937 		    vdev, name);
1938 		ret = 1;
1939 		goto errout;
1940 
1941 	case POOL_STATE_POTENTIALLY_ACTIVE:
1942 		if (force)
1943 			break;
1944 		(void) fprintf(stderr, gettext(
1945 		    "use '-f' to override the following error:\n"
1946 		    "%s is a member of potentially active pool \"%s\"\n"),
1947 		    vdev, name);
1948 		ret = 1;
1949 		goto errout;
1950 
1951 	case POOL_STATE_DESTROYED:
1952 		/* inuse should never be set for a destroyed pool */
1953 		assert(0);
1954 		break;
1955 	}
1956 
1957 wipe_label:
1958 	ret = zpool_clear_label(fd);
1959 	if (ret != 0) {
1960 		(void) fprintf(stderr,
1961 		    gettext("failed to clear label for %s\n"), vdev);
1962 	}
1963 
1964 errout:
1965 	free(name);
1966 	(void) close(fd);
1967 
1968 	return (ret);
1969 }
1970 
1971 /*
1972  * zpool create [-fnd] [-o property=value] ...
1973  *		[-O file-system-property=value] ...
1974  *		[-R root] [-m mountpoint] <pool> <dev> ...
1975  *
1976  *	-f	Force creation, even if devices appear in use
1977  *	-n	Do not create the pool, but display the resulting layout if it
1978  *		were to be created.
1979  *      -R	Create a pool under an alternate root
1980  *      -m	Set default mountpoint for the root dataset.  By default it's
1981  *		'/<pool>'
1982  *	-o	Set property=value.
1983  *	-o	Set feature@feature=enabled|disabled.
1984  *	-d	Don't automatically enable all supported pool features
1985  *		(individual features can be enabled with -o).
1986  *	-O	Set fsproperty=value in the pool's root file system
1987  *
1988  * Creates the named pool according to the given vdev specification.  The
1989  * bulk of the vdev processing is done in make_root_vdev() in zpool_vdev.c.
1990  * Once we get the nvlist back from make_root_vdev(), we either print out the
1991  * contents (if '-n' was specified), or pass it to libzfs to do the creation.
1992  */
1993 int
1994 zpool_do_create(int argc, char **argv)
1995 {
1996 	boolean_t force = B_FALSE;
1997 	boolean_t dryrun = B_FALSE;
1998 	boolean_t enable_pool_features = B_TRUE;
1999 
2000 	int c;
2001 	nvlist_t *nvroot = NULL;
2002 	char *poolname;
2003 	char *tname = NULL;
2004 	int ret = 1;
2005 	char *altroot = NULL;
2006 	char *compat = NULL;
2007 	char *mountpoint = NULL;
2008 	nvlist_t *fsprops = NULL;
2009 	nvlist_t *props = NULL;
2010 	char *propval;
2011 
2012 	/* check options */
2013 	while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
2014 		switch (c) {
2015 		case 'f':
2016 			force = B_TRUE;
2017 			break;
2018 		case 'n':
2019 			dryrun = B_TRUE;
2020 			break;
2021 		case 'd':
2022 			enable_pool_features = B_FALSE;
2023 			break;
2024 		case 'R':
2025 			altroot = optarg;
2026 			if (add_prop_list(zpool_prop_to_name(
2027 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
2028 				goto errout;
2029 			if (add_prop_list_default(zpool_prop_to_name(
2030 			    ZPOOL_PROP_CACHEFILE), "none", &props))
2031 				goto errout;
2032 			break;
2033 		case 'm':
2034 			/* Equivalent to -O mountpoint=optarg */
2035 			mountpoint = optarg;
2036 			break;
2037 		case 'o':
2038 			if ((propval = strchr(optarg, '=')) == NULL) {
2039 				(void) fprintf(stderr, gettext("missing "
2040 				    "'=' for -o option\n"));
2041 				goto errout;
2042 			}
2043 			*propval = '\0';
2044 			propval++;
2045 
2046 			if (add_prop_list(optarg, propval, &props, B_TRUE))
2047 				goto errout;
2048 
2049 			/*
2050 			 * If the user is creating a pool that doesn't support
2051 			 * feature flags, don't enable any features.
2052 			 */
2053 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
2054 				char *end;
2055 				u_longlong_t ver;
2056 
2057 				ver = strtoull(propval, &end, 0);
2058 				if (*end == '\0' &&
2059 				    ver < SPA_VERSION_FEATURES) {
2060 					enable_pool_features = B_FALSE;
2061 				}
2062 			}
2063 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
2064 				altroot = propval;
2065 			if (zpool_name_to_prop(optarg) ==
2066 			    ZPOOL_PROP_COMPATIBILITY)
2067 				compat = propval;
2068 			break;
2069 		case 'O':
2070 			if ((propval = strchr(optarg, '=')) == NULL) {
2071 				(void) fprintf(stderr, gettext("missing "
2072 				    "'=' for -O option\n"));
2073 				goto errout;
2074 			}
2075 			*propval = '\0';
2076 			propval++;
2077 
2078 			/*
2079 			 * Mountpoints are checked and then added later.
2080 			 * Uniquely among properties, they can be specified
2081 			 * more than once, to avoid conflict with -m.
2082 			 */
2083 			if (0 == strcmp(optarg,
2084 			    zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
2085 				mountpoint = propval;
2086 			} else if (add_prop_list(optarg, propval, &fsprops,
2087 			    B_FALSE)) {
2088 				goto errout;
2089 			}
2090 			break;
2091 		case 't':
2092 			/*
2093 			 * Sanity check temporary pool name.
2094 			 */
2095 			if (strchr(optarg, '/') != NULL) {
2096 				(void) fprintf(stderr, gettext("cannot create "
2097 				    "'%s': invalid character '/' in temporary "
2098 				    "name\n"), optarg);
2099 				(void) fprintf(stderr, gettext("use 'zfs "
2100 				    "create' to create a dataset\n"));
2101 				goto errout;
2102 			}
2103 
2104 			if (add_prop_list(zpool_prop_to_name(
2105 			    ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
2106 				goto errout;
2107 			if (add_prop_list_default(zpool_prop_to_name(
2108 			    ZPOOL_PROP_CACHEFILE), "none", &props))
2109 				goto errout;
2110 			tname = optarg;
2111 			break;
2112 		case ':':
2113 			(void) fprintf(stderr, gettext("missing argument for "
2114 			    "'%c' option\n"), optopt);
2115 			goto badusage;
2116 		case '?':
2117 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2118 			    optopt);
2119 			goto badusage;
2120 		}
2121 	}
2122 
2123 	argc -= optind;
2124 	argv += optind;
2125 
2126 	/* get pool name and check number of arguments */
2127 	if (argc < 1) {
2128 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
2129 		goto badusage;
2130 	}
2131 	if (argc < 2) {
2132 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
2133 		goto badusage;
2134 	}
2135 
2136 	poolname = argv[0];
2137 
2138 	/*
2139 	 * As a special case, check for use of '/' in the name, and direct the
2140 	 * user to use 'zfs create' instead.
2141 	 */
2142 	if (strchr(poolname, '/') != NULL) {
2143 		(void) fprintf(stderr, gettext("cannot create '%s': invalid "
2144 		    "character '/' in pool name\n"), poolname);
2145 		(void) fprintf(stderr, gettext("use 'zfs create' to "
2146 		    "create a dataset\n"));
2147 		goto errout;
2148 	}
2149 
2150 	/* pass off to make_root_vdev for bulk processing */
2151 	nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
2152 	    argc - 1, argv + 1);
2153 	if (nvroot == NULL)
2154 		goto errout;
2155 
2156 	/* make_root_vdev() allows 0 toplevel children if there are spares */
2157 	if (!zfs_allocatable_devs(nvroot)) {
2158 		(void) fprintf(stderr, gettext("invalid vdev "
2159 		    "specification: at least one toplevel vdev must be "
2160 		    "specified\n"));
2161 		goto errout;
2162 	}
2163 
2164 	if (altroot != NULL && altroot[0] != '/') {
2165 		(void) fprintf(stderr, gettext("invalid alternate root '%s': "
2166 		    "must be an absolute path\n"), altroot);
2167 		goto errout;
2168 	}
2169 
2170 	/*
2171 	 * Check the validity of the mountpoint and direct the user to use the
2172 	 * '-m' mountpoint option if it looks like its in use.
2173 	 */
2174 	if (mountpoint == NULL ||
2175 	    (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
2176 	    strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
2177 		char buf[MAXPATHLEN];
2178 		DIR *dirp;
2179 
2180 		if (mountpoint && mountpoint[0] != '/') {
2181 			(void) fprintf(stderr, gettext("invalid mountpoint "
2182 			    "'%s': must be an absolute path, 'legacy', or "
2183 			    "'none'\n"), mountpoint);
2184 			goto errout;
2185 		}
2186 
2187 		if (mountpoint == NULL) {
2188 			if (altroot != NULL)
2189 				(void) snprintf(buf, sizeof (buf), "%s/%s",
2190 				    altroot, poolname);
2191 			else
2192 				(void) snprintf(buf, sizeof (buf), "/%s",
2193 				    poolname);
2194 		} else {
2195 			if (altroot != NULL)
2196 				(void) snprintf(buf, sizeof (buf), "%s%s",
2197 				    altroot, mountpoint);
2198 			else
2199 				(void) snprintf(buf, sizeof (buf), "%s",
2200 				    mountpoint);
2201 		}
2202 
2203 		if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
2204 			(void) fprintf(stderr, gettext("mountpoint '%s' : "
2205 			    "%s\n"), buf, strerror(errno));
2206 			(void) fprintf(stderr, gettext("use '-m' "
2207 			    "option to provide a different default\n"));
2208 			goto errout;
2209 		} else if (dirp) {
2210 			int count = 0;
2211 
2212 			while (count < 3 && readdir(dirp) != NULL)
2213 				count++;
2214 			(void) closedir(dirp);
2215 
2216 			if (count > 2) {
2217 				(void) fprintf(stderr, gettext("mountpoint "
2218 				    "'%s' exists and is not empty\n"), buf);
2219 				(void) fprintf(stderr, gettext("use '-m' "
2220 				    "option to provide a "
2221 				    "different default\n"));
2222 				goto errout;
2223 			}
2224 		}
2225 	}
2226 
2227 	/*
2228 	 * Now that the mountpoint's validity has been checked, ensure that
2229 	 * the property is set appropriately prior to creating the pool.
2230 	 */
2231 	if (mountpoint != NULL) {
2232 		ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
2233 		    mountpoint, &fsprops, B_FALSE);
2234 		if (ret != 0)
2235 			goto errout;
2236 	}
2237 
2238 	ret = 1;
2239 	if (dryrun) {
2240 		/*
2241 		 * For a dry run invocation, print out a basic message and run
2242 		 * through all the vdevs in the list and print out in an
2243 		 * appropriate hierarchy.
2244 		 */
2245 		(void) printf(gettext("would create '%s' with the "
2246 		    "following layout:\n\n"), poolname);
2247 
2248 		print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
2249 		print_vdev_tree(NULL, "dedup", nvroot, 0,
2250 		    VDEV_ALLOC_BIAS_DEDUP, 0);
2251 		print_vdev_tree(NULL, "special", nvroot, 0,
2252 		    VDEV_ALLOC_BIAS_SPECIAL, 0);
2253 		print_vdev_tree(NULL, "logs", nvroot, 0,
2254 		    VDEV_ALLOC_BIAS_LOG, 0);
2255 		print_cache_list(nvroot, 0);
2256 		print_spare_list(nvroot, 0);
2257 
2258 		ret = 0;
2259 	} else {
2260 		/*
2261 		 * Load in feature set.
2262 		 * Note: if compatibility property not given, we'll have
2263 		 * NULL, which means 'all features'.
2264 		 */
2265 		boolean_t requested_features[SPA_FEATURES];
2266 		if (zpool_do_load_compat(compat, requested_features) !=
2267 		    ZPOOL_COMPATIBILITY_OK)
2268 			goto errout;
2269 
2270 		/*
2271 		 * props contains list of features to enable.
2272 		 * For each feature:
2273 		 *  - remove it if feature@name=disabled
2274 		 *  - leave it there if feature@name=enabled
2275 		 *  - add it if:
2276 		 *    - enable_pool_features (ie: no '-d' or '-o version')
2277 		 *    - it's supported by the kernel module
2278 		 *    - it's in the requested feature set
2279 		 *  - warn if it's enabled but not in compat
2280 		 */
2281 		for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
2282 			char propname[MAXPATHLEN];
2283 			const char *propval;
2284 			zfeature_info_t *feat = &spa_feature_table[i];
2285 
2286 			(void) snprintf(propname, sizeof (propname),
2287 			    "feature@%s", feat->fi_uname);
2288 
2289 			if (!nvlist_lookup_string(props, propname, &propval)) {
2290 				if (strcmp(propval,
2291 				    ZFS_FEATURE_DISABLED) == 0) {
2292 					(void) nvlist_remove_all(props,
2293 					    propname);
2294 				} else if (strcmp(propval,
2295 				    ZFS_FEATURE_ENABLED) == 0 &&
2296 				    !requested_features[i]) {
2297 					(void) fprintf(stderr, gettext(
2298 					    "Warning: feature \"%s\" enabled "
2299 					    "but is not in specified "
2300 					    "'compatibility' feature set.\n"),
2301 					    feat->fi_uname);
2302 				}
2303 			} else if (
2304 			    enable_pool_features &&
2305 			    feat->fi_zfs_mod_supported &&
2306 			    requested_features[i]) {
2307 				ret = add_prop_list(propname,
2308 				    ZFS_FEATURE_ENABLED, &props, B_TRUE);
2309 				if (ret != 0)
2310 					goto errout;
2311 			}
2312 		}
2313 
2314 		ret = 1;
2315 		if (zpool_create(g_zfs, poolname,
2316 		    nvroot, props, fsprops) == 0) {
2317 			zfs_handle_t *pool = zfs_open(g_zfs,
2318 			    tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
2319 			if (pool != NULL) {
2320 				if (zfs_mount(pool, NULL, 0) == 0) {
2321 					ret = zfs_share(pool, NULL);
2322 					zfs_commit_shares(NULL);
2323 				}
2324 				zfs_close(pool);
2325 			}
2326 		} else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
2327 			(void) fprintf(stderr, gettext("pool name may have "
2328 			    "been omitted\n"));
2329 		}
2330 	}
2331 
2332 errout:
2333 	nvlist_free(nvroot);
2334 	nvlist_free(fsprops);
2335 	nvlist_free(props);
2336 	return (ret);
2337 badusage:
2338 	nvlist_free(fsprops);
2339 	nvlist_free(props);
2340 	usage(B_FALSE);
2341 	return (2);
2342 }
2343 
2344 /*
2345  * zpool destroy <pool>
2346  *
2347  * 	-f	Forcefully unmount any datasets
2348  *
2349  * Destroy the given pool.  Automatically unmounts any datasets in the pool.
2350  */
2351 int
2352 zpool_do_destroy(int argc, char **argv)
2353 {
2354 	boolean_t force = B_FALSE;
2355 	int c;
2356 	char *pool;
2357 	zpool_handle_t *zhp;
2358 	int ret;
2359 
2360 	/* check options */
2361 	while ((c = getopt(argc, argv, "f")) != -1) {
2362 		switch (c) {
2363 		case 'f':
2364 			force = B_TRUE;
2365 			break;
2366 		case '?':
2367 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2368 			    optopt);
2369 			usage(B_FALSE);
2370 		}
2371 	}
2372 
2373 	argc -= optind;
2374 	argv += optind;
2375 
2376 	/* check arguments */
2377 	if (argc < 1) {
2378 		(void) fprintf(stderr, gettext("missing pool argument\n"));
2379 		usage(B_FALSE);
2380 	}
2381 	if (argc > 1) {
2382 		(void) fprintf(stderr, gettext("too many arguments\n"));
2383 		usage(B_FALSE);
2384 	}
2385 
2386 	pool = argv[0];
2387 
2388 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
2389 		/*
2390 		 * As a special case, check for use of '/' in the name, and
2391 		 * direct the user to use 'zfs destroy' instead.
2392 		 */
2393 		if (strchr(pool, '/') != NULL)
2394 			(void) fprintf(stderr, gettext("use 'zfs destroy' to "
2395 			    "destroy a dataset\n"));
2396 		return (1);
2397 	}
2398 
2399 	if (zpool_disable_datasets(zhp, force) != 0) {
2400 		(void) fprintf(stderr, gettext("could not destroy '%s': "
2401 		    "could not unmount datasets\n"), zpool_get_name(zhp));
2402 		zpool_close(zhp);
2403 		return (1);
2404 	}
2405 
2406 	/* The history must be logged as part of the export */
2407 	log_history = B_FALSE;
2408 
2409 	ret = (zpool_destroy(zhp, history_str) != 0);
2410 
2411 	zpool_close(zhp);
2412 
2413 	return (ret);
2414 }
2415 
2416 typedef struct export_cbdata {
2417 	taskq_t *taskq;
2418 	pthread_mutex_t mnttab_lock;
2419 	boolean_t force;
2420 	boolean_t hardforce;
2421 	int retval;
2422 } export_cbdata_t;
2423 
2424 
2425 typedef struct {
2426 	char *aea_poolname;
2427 	export_cbdata_t	*aea_cbdata;
2428 } async_export_args_t;
2429 
2430 /*
2431  * Export one pool
2432  */
2433 static int
2434 zpool_export_one(zpool_handle_t *zhp, void *data)
2435 {
2436 	export_cbdata_t *cb = data;
2437 
2438 	/*
2439 	 * zpool_disable_datasets() is not thread-safe for mnttab access.
2440 	 * So we serialize access here for 'zpool export -a' parallel case.
2441 	 */
2442 	if (cb->taskq != NULL)
2443 		(void) pthread_mutex_lock(&cb->mnttab_lock);
2444 
2445 	int retval = zpool_disable_datasets(zhp, cb->force);
2446 
2447 	if (cb->taskq != NULL)
2448 		(void) pthread_mutex_unlock(&cb->mnttab_lock);
2449 
2450 	if (retval)
2451 		return (1);
2452 
2453 	if (cb->hardforce) {
2454 		if (zpool_export_force(zhp, history_str) != 0)
2455 			return (1);
2456 	} else if (zpool_export(zhp, cb->force, history_str) != 0) {
2457 		return (1);
2458 	}
2459 
2460 	return (0);
2461 }
2462 
2463 /*
2464  * Asynchronous export request
2465  */
2466 static void
2467 zpool_export_task(void *arg)
2468 {
2469 	async_export_args_t *aea = arg;
2470 
2471 	zpool_handle_t *zhp = zpool_open(g_zfs, aea->aea_poolname);
2472 	if (zhp != NULL) {
2473 		int ret = zpool_export_one(zhp, aea->aea_cbdata);
2474 		if (ret != 0)
2475 			aea->aea_cbdata->retval = ret;
2476 		zpool_close(zhp);
2477 	} else {
2478 		aea->aea_cbdata->retval = 1;
2479 	}
2480 
2481 	free(aea->aea_poolname);
2482 	free(aea);
2483 }
2484 
2485 /*
2486  * Process an export request in parallel
2487  */
2488 static int
2489 zpool_export_one_async(zpool_handle_t *zhp, void *data)
2490 {
2491 	taskq_t *tq = ((export_cbdata_t *)data)->taskq;
2492 	async_export_args_t *aea = safe_malloc(sizeof (async_export_args_t));
2493 
2494 	/* save pool name since zhp will go out of scope */
2495 	aea->aea_poolname = strdup(zpool_get_name(zhp));
2496 	aea->aea_cbdata = data;
2497 
2498 	/* ship off actual export to another thread */
2499 	if (taskq_dispatch(tq, zpool_export_task, (void *)aea,
2500 	    TQ_SLEEP) == TASKQID_INVALID)
2501 		return (errno);	/* unlikely */
2502 	else
2503 		return (0);
2504 }
2505 
2506 /*
2507  * zpool export [-f] <pool> ...
2508  *
2509  *	-a	Export all pools
2510  *	-f	Forcefully unmount datasets
2511  *
2512  * Export the given pools.  By default, the command will attempt to cleanly
2513  * unmount any active datasets within the pool.  If the '-f' flag is specified,
2514  * then the datasets will be forcefully unmounted.
2515  */
2516 int
2517 zpool_do_export(int argc, char **argv)
2518 {
2519 	export_cbdata_t cb;
2520 	boolean_t do_all = B_FALSE;
2521 	boolean_t force = B_FALSE;
2522 	boolean_t hardforce = B_FALSE;
2523 	int c, ret;
2524 
2525 	/* check options */
2526 	while ((c = getopt(argc, argv, "afF")) != -1) {
2527 		switch (c) {
2528 		case 'a':
2529 			do_all = B_TRUE;
2530 			break;
2531 		case 'f':
2532 			force = B_TRUE;
2533 			break;
2534 		case 'F':
2535 			hardforce = B_TRUE;
2536 			break;
2537 		case '?':
2538 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2539 			    optopt);
2540 			usage(B_FALSE);
2541 		}
2542 	}
2543 
2544 	cb.force = force;
2545 	cb.hardforce = hardforce;
2546 	cb.taskq = NULL;
2547 	cb.retval = 0;
2548 	argc -= optind;
2549 	argv += optind;
2550 
2551 	/* The history will be logged as part of the export itself */
2552 	log_history = B_FALSE;
2553 
2554 	if (do_all) {
2555 		if (argc != 0) {
2556 			(void) fprintf(stderr, gettext("too many arguments\n"));
2557 			usage(B_FALSE);
2558 		}
2559 
2560 		cb.taskq = taskq_create("zpool_export",
2561 		    5 * sysconf(_SC_NPROCESSORS_ONLN), minclsyspri, 1, INT_MAX,
2562 		    TASKQ_DYNAMIC);
2563 		(void) pthread_mutex_init(&cb.mnttab_lock, NULL);
2564 
2565 		/* Asynchronously call zpool_export_one using thread pool */
2566 		ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2567 		    B_FALSE, zpool_export_one_async, &cb);
2568 
2569 		taskq_wait(cb.taskq);
2570 		taskq_destroy(cb.taskq);
2571 		(void) pthread_mutex_destroy(&cb.mnttab_lock);
2572 
2573 		return (ret | cb.retval);
2574 	}
2575 
2576 	/* check arguments */
2577 	if (argc < 1) {
2578 		(void) fprintf(stderr, gettext("missing pool argument\n"));
2579 		usage(B_FALSE);
2580 	}
2581 
2582 	ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2583 	    B_FALSE, zpool_export_one, &cb);
2584 
2585 	return (ret);
2586 }
2587 
2588 /*
2589  * Given a vdev configuration, determine the maximum width needed for the device
2590  * name column.
2591  */
2592 static int
2593 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
2594     int name_flags)
2595 {
2596 	static const char *const subtypes[] =
2597 	    {ZPOOL_CONFIG_SPARES, ZPOOL_CONFIG_L2CACHE, ZPOOL_CONFIG_CHILDREN};
2598 
2599 	char *name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
2600 	max = MAX(strlen(name) + depth, max);
2601 	free(name);
2602 
2603 	nvlist_t **child;
2604 	uint_t children;
2605 	for (size_t i = 0; i < ARRAY_SIZE(subtypes); ++i)
2606 		if (nvlist_lookup_nvlist_array(nv, subtypes[i],
2607 		    &child, &children) == 0)
2608 			for (uint_t c = 0; c < children; ++c)
2609 				max = MAX(max_width(zhp, child[c], depth + 2,
2610 				    max, name_flags), max);
2611 
2612 	return (max);
2613 }
2614 
2615 typedef struct status_cbdata {
2616 	int		cb_count;
2617 	int		cb_name_flags;
2618 	int		cb_namewidth;
2619 	boolean_t	cb_allpools;
2620 	boolean_t	cb_verbose;
2621 	boolean_t	cb_literal;
2622 	boolean_t	cb_explain;
2623 	boolean_t	cb_first;
2624 	boolean_t	cb_dedup_stats;
2625 	boolean_t	cb_print_unhealthy;
2626 	boolean_t	cb_print_status;
2627 	boolean_t	cb_print_slow_ios;
2628 	boolean_t	cb_print_dio_verify;
2629 	boolean_t	cb_print_vdev_init;
2630 	boolean_t	cb_print_vdev_trim;
2631 	vdev_cmd_data_list_t	*vcdl;
2632 	boolean_t	cb_print_power;
2633 	boolean_t	cb_json;
2634 	boolean_t	cb_flat_vdevs;
2635 	nvlist_t	*cb_jsobj;
2636 	boolean_t	cb_json_as_int;
2637 	boolean_t	cb_json_pool_key_guid;
2638 } status_cbdata_t;
2639 
2640 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
2641 static boolean_t
2642 is_blank_str(const char *str)
2643 {
2644 	for (; str != NULL && *str != '\0'; ++str)
2645 		if (!isblank(*str))
2646 			return (B_FALSE);
2647 	return (B_TRUE);
2648 }
2649 
2650 static void
2651 zpool_nvlist_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path,
2652     nvlist_t *item)
2653 {
2654 	vdev_cmd_data_t *data;
2655 	int i, j, k = 1;
2656 	char tmp[256];
2657 	const char *val;
2658 
2659 	for (i = 0; i < vcdl->count; i++) {
2660 		if ((strcmp(vcdl->data[i].path, path) != 0) ||
2661 		    (strcmp(vcdl->data[i].pool, pool) != 0))
2662 			continue;
2663 
2664 		data = &vcdl->data[i];
2665 		for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2666 			val = NULL;
2667 			for (int k = 0; k < data->cols_cnt; k++) {
2668 				if (strcmp(data->cols[k],
2669 				    vcdl->uniq_cols[j]) == 0) {
2670 					val = data->lines[k];
2671 					break;
2672 				}
2673 			}
2674 			if (val == NULL || is_blank_str(val))
2675 				val = "-";
2676 			fnvlist_add_string(item, vcdl->uniq_cols[j], val);
2677 		}
2678 
2679 		for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2680 			if (data->lines[j]) {
2681 				(void) snprintf(tmp, 256, "extra_%d", k++);
2682 				fnvlist_add_string(item, tmp,
2683 				    data->lines[j]);
2684 			}
2685 		}
2686 		break;
2687 	}
2688 }
2689 
2690 /* Print command output lines for specific vdev in a specific pool */
2691 static void
2692 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path)
2693 {
2694 	vdev_cmd_data_t *data;
2695 	int i, j;
2696 	const char *val;
2697 
2698 	for (i = 0; i < vcdl->count; i++) {
2699 		if ((strcmp(vcdl->data[i].path, path) != 0) ||
2700 		    (strcmp(vcdl->data[i].pool, pool) != 0)) {
2701 			/* Not the vdev we're looking for */
2702 			continue;
2703 		}
2704 
2705 		data = &vcdl->data[i];
2706 		/* Print out all the output values for this vdev */
2707 		for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2708 			val = NULL;
2709 			/* Does this vdev have values for this column? */
2710 			for (int k = 0; k < data->cols_cnt; k++) {
2711 				if (strcmp(data->cols[k],
2712 				    vcdl->uniq_cols[j]) == 0) {
2713 					/* yes it does, record the value */
2714 					val = data->lines[k];
2715 					break;
2716 				}
2717 			}
2718 			/*
2719 			 * Mark empty values with dashes to make output
2720 			 * awk-able.
2721 			 */
2722 			if (val == NULL || is_blank_str(val))
2723 				val = "-";
2724 
2725 			printf("%*s", vcdl->uniq_cols_width[j], val);
2726 			if (j < vcdl->uniq_cols_cnt - 1)
2727 				(void) fputs("  ", stdout);
2728 		}
2729 
2730 		/* Print out any values that aren't in a column at the end */
2731 		for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2732 			/* Did we have any columns?  If so print a spacer. */
2733 			if (vcdl->uniq_cols_cnt > 0)
2734 				(void) fputs("  ", stdout);
2735 
2736 			val = data->lines[j];
2737 			(void) fputs(val ?: "", stdout);
2738 		}
2739 		break;
2740 	}
2741 }
2742 
2743 /*
2744  * Print vdev initialization status for leaves
2745  */
2746 static void
2747 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
2748 {
2749 	if (verbose) {
2750 		if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
2751 		    vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
2752 		    vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
2753 		    !vs->vs_scan_removing) {
2754 			char zbuf[1024];
2755 			char tbuf[256];
2756 
2757 			time_t t = vs->vs_initialize_action_time;
2758 			int initialize_pct = 100;
2759 			if (vs->vs_initialize_state !=
2760 			    VDEV_INITIALIZE_COMPLETE) {
2761 				initialize_pct = (vs->vs_initialize_bytes_done *
2762 				    100 / (vs->vs_initialize_bytes_est + 1));
2763 			}
2764 
2765 			(void) ctime_r(&t, tbuf);
2766 			tbuf[24] = 0;
2767 
2768 			switch (vs->vs_initialize_state) {
2769 			case VDEV_INITIALIZE_SUSPENDED:
2770 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2771 				    gettext("suspended, started at"), tbuf);
2772 				break;
2773 			case VDEV_INITIALIZE_ACTIVE:
2774 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2775 				    gettext("started at"), tbuf);
2776 				break;
2777 			case VDEV_INITIALIZE_COMPLETE:
2778 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2779 				    gettext("completed at"), tbuf);
2780 				break;
2781 			}
2782 
2783 			(void) printf(gettext("  (%d%% initialized%s)"),
2784 			    initialize_pct, zbuf);
2785 		} else {
2786 			(void) printf(gettext("  (uninitialized)"));
2787 		}
2788 	} else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
2789 		(void) printf(gettext("  (initializing)"));
2790 	}
2791 }
2792 
2793 /*
2794  * Print vdev TRIM status for leaves
2795  */
2796 static void
2797 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
2798 {
2799 	if (verbose) {
2800 		if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
2801 		    vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
2802 		    vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
2803 		    !vs->vs_scan_removing) {
2804 			char zbuf[1024];
2805 			char tbuf[256];
2806 
2807 			time_t t = vs->vs_trim_action_time;
2808 			int trim_pct = 100;
2809 			if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
2810 				trim_pct = (vs->vs_trim_bytes_done *
2811 				    100 / (vs->vs_trim_bytes_est + 1));
2812 			}
2813 
2814 			(void) ctime_r(&t, tbuf);
2815 			tbuf[24] = 0;
2816 
2817 			switch (vs->vs_trim_state) {
2818 			case VDEV_TRIM_SUSPENDED:
2819 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2820 				    gettext("suspended, started at"), tbuf);
2821 				break;
2822 			case VDEV_TRIM_ACTIVE:
2823 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2824 				    gettext("started at"), tbuf);
2825 				break;
2826 			case VDEV_TRIM_COMPLETE:
2827 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2828 				    gettext("completed at"), tbuf);
2829 				break;
2830 			}
2831 
2832 			(void) printf(gettext("  (%d%% trimmed%s)"),
2833 			    trim_pct, zbuf);
2834 		} else if (vs->vs_trim_notsup) {
2835 			(void) printf(gettext("  (trim unsupported)"));
2836 		} else {
2837 			(void) printf(gettext("  (untrimmed)"));
2838 		}
2839 	} else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
2840 		(void) printf(gettext("  (trimming)"));
2841 	}
2842 }
2843 
2844 /*
2845  * Return the color associated with a health string.  This includes returning
2846  * NULL for no color change.
2847  */
2848 static const char *
2849 health_str_to_color(const char *health)
2850 {
2851 	if (strcmp(health, gettext("FAULTED")) == 0 ||
2852 	    strcmp(health, gettext("SUSPENDED")) == 0 ||
2853 	    strcmp(health, gettext("UNAVAIL")) == 0) {
2854 		return (ANSI_RED);
2855 	}
2856 
2857 	if (strcmp(health, gettext("OFFLINE")) == 0 ||
2858 	    strcmp(health, gettext("DEGRADED")) == 0 ||
2859 	    strcmp(health, gettext("REMOVED")) == 0) {
2860 		return (ANSI_YELLOW);
2861 	}
2862 
2863 	return (NULL);
2864 }
2865 
2866 /*
2867  * Called for each leaf vdev.  Returns 0 if the vdev is healthy.
2868  * A vdev is unhealthy if any of the following are true:
2869  * 1) there are read, write, or checksum errors,
2870  * 2) its state is not ONLINE, or
2871  * 3) slow IO reporting was requested (-s) and there are slow IOs.
2872  */
2873 static int
2874 vdev_health_check_cb(void *hdl_data, nvlist_t *nv, void *data)
2875 {
2876 	status_cbdata_t *cb = data;
2877 	vdev_stat_t *vs;
2878 	uint_t vsc;
2879 	(void) hdl_data;
2880 
2881 	if (nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2882 	    (uint64_t **)&vs, &vsc) != 0)
2883 		return (1);
2884 
2885 	if (vs->vs_checksum_errors || vs->vs_read_errors ||
2886 	    vs->vs_write_errors || vs->vs_state != VDEV_STATE_HEALTHY)
2887 		return (1);
2888 
2889 	if (cb->cb_print_slow_ios && vs->vs_slow_ios)
2890 		return (1);
2891 
2892 	return (0);
2893 }
2894 
2895 /*
2896  * Print out configuration state as requested by status_callback.
2897  */
2898 static void
2899 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
2900     nvlist_t *nv, int depth, boolean_t isspare, vdev_rebuild_stat_t *vrs)
2901 {
2902 	nvlist_t **child, *root;
2903 	uint_t c, i, vsc, children;
2904 	pool_scan_stat_t *ps = NULL;
2905 	vdev_stat_t *vs;
2906 	char rbuf[6], wbuf[6], cbuf[6], dbuf[6];
2907 	char *vname;
2908 	uint64_t notpresent;
2909 	spare_cbdata_t spare_cb;
2910 	const char *state;
2911 	const char *type;
2912 	const char *path = NULL;
2913 	const char *rcolor = NULL, *wcolor = NULL, *ccolor = NULL,
2914 	    *scolor = NULL;
2915 
2916 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2917 	    &child, &children) != 0)
2918 		children = 0;
2919 
2920 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2921 	    (uint64_t **)&vs, &vsc) == 0);
2922 
2923 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2924 
2925 	if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2926 		return;
2927 
2928 	state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2929 
2930 	if (isspare) {
2931 		/*
2932 		 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
2933 		 * online drives.
2934 		 */
2935 		if (vs->vs_aux == VDEV_AUX_SPARED)
2936 			state = gettext("INUSE");
2937 		else if (vs->vs_state == VDEV_STATE_HEALTHY)
2938 			state = gettext("AVAIL");
2939 	}
2940 
2941 	/*
2942 	 * If '-e' is specified then top-level vdevs and their children
2943 	 * can be pruned if all of their leaves are healthy.
2944 	 */
2945 	if (cb->cb_print_unhealthy && depth > 0 &&
2946 	    for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
2947 		return;
2948 	}
2949 
2950 	(void) printf_color(health_str_to_color(state),
2951 	    "\t%*s%-*s  %-8s", depth, "", cb->cb_namewidth - depth,
2952 	    name, state);
2953 
2954 	if (!isspare) {
2955 		if (vs->vs_read_errors)
2956 			rcolor = ANSI_RED;
2957 
2958 		if (vs->vs_write_errors)
2959 			wcolor = ANSI_RED;
2960 
2961 		if (vs->vs_checksum_errors)
2962 			ccolor = ANSI_RED;
2963 
2964 		if (vs->vs_slow_ios)
2965 			scolor = ANSI_BLUE;
2966 
2967 		if (cb->cb_literal) {
2968 			(void) fputc(' ', stdout);
2969 			(void) printf_color(rcolor, "%5llu",
2970 			    (u_longlong_t)vs->vs_read_errors);
2971 			(void) fputc(' ', stdout);
2972 			(void) printf_color(wcolor, "%5llu",
2973 			    (u_longlong_t)vs->vs_write_errors);
2974 			(void) fputc(' ', stdout);
2975 			(void) printf_color(ccolor, "%5llu",
2976 			    (u_longlong_t)vs->vs_checksum_errors);
2977 		} else {
2978 			zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
2979 			zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
2980 			zfs_nicenum(vs->vs_checksum_errors, cbuf,
2981 			    sizeof (cbuf));
2982 			(void) fputc(' ', stdout);
2983 			(void) printf_color(rcolor, "%5s", rbuf);
2984 			(void) fputc(' ', stdout);
2985 			(void) printf_color(wcolor, "%5s", wbuf);
2986 			(void) fputc(' ', stdout);
2987 			(void) printf_color(ccolor, "%5s", cbuf);
2988 		}
2989 		if (cb->cb_print_slow_ios) {
2990 			if (children == 0)  {
2991 				/* Only leafs vdevs have slow IOs */
2992 				zfs_nicenum(vs->vs_slow_ios, rbuf,
2993 				    sizeof (rbuf));
2994 			} else {
2995 				(void) snprintf(rbuf, sizeof (rbuf), "-");
2996 			}
2997 
2998 			if (cb->cb_literal)
2999 				(void) printf_color(scolor, " %5llu",
3000 				    (u_longlong_t)vs->vs_slow_ios);
3001 			else
3002 				(void) printf_color(scolor, " %5s", rbuf);
3003 		}
3004 		if (cb->cb_print_power) {
3005 			if (children == 0)  {
3006 				/* Only leaf vdevs have physical slots */
3007 				switch (zpool_power_current_state(zhp, (char *)
3008 				    fnvlist_lookup_string(nv,
3009 				    ZPOOL_CONFIG_PATH))) {
3010 				case 0:
3011 					(void) printf_color(ANSI_RED, " %5s",
3012 					    gettext("off"));
3013 					break;
3014 				case 1:
3015 					printf(" %5s", gettext("on"));
3016 					break;
3017 				default:
3018 					printf(" %5s", "-");
3019 				}
3020 			} else {
3021 				printf(" %5s", "-");
3022 			}
3023 		}
3024 		if (VDEV_STAT_VALID(vs_dio_verify_errors, vsc) &&
3025 		    cb->cb_print_dio_verify) {
3026 			zfs_nicenum(vs->vs_dio_verify_errors, dbuf,
3027 			    sizeof (dbuf));
3028 
3029 			if (cb->cb_literal)
3030 				printf(" %5llu",
3031 				    (u_longlong_t)vs->vs_dio_verify_errors);
3032 			else
3033 				printf(" %5s", dbuf);
3034 		}
3035 	}
3036 
3037 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
3038 	    &notpresent) == 0) {
3039 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
3040 		(void) printf("  %s %s", gettext("was"), path);
3041 	} else if (vs->vs_aux != 0) {
3042 		(void) printf("  ");
3043 		color_start(ANSI_RED);
3044 		switch (vs->vs_aux) {
3045 		case VDEV_AUX_OPEN_FAILED:
3046 			(void) printf(gettext("cannot open"));
3047 			break;
3048 
3049 		case VDEV_AUX_BAD_GUID_SUM:
3050 			(void) printf(gettext("missing device"));
3051 			break;
3052 
3053 		case VDEV_AUX_NO_REPLICAS:
3054 			(void) printf(gettext("insufficient replicas"));
3055 			break;
3056 
3057 		case VDEV_AUX_VERSION_NEWER:
3058 			(void) printf(gettext("newer version"));
3059 			break;
3060 
3061 		case VDEV_AUX_UNSUP_FEAT:
3062 			(void) printf(gettext("unsupported feature(s)"));
3063 			break;
3064 
3065 		case VDEV_AUX_ASHIFT_TOO_BIG:
3066 			(void) printf(gettext("unsupported minimum blocksize"));
3067 			break;
3068 
3069 		case VDEV_AUX_SPARED:
3070 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3071 			    &spare_cb.cb_guid) == 0);
3072 			if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
3073 				if (strcmp(zpool_get_name(spare_cb.cb_zhp),
3074 				    zpool_get_name(zhp)) == 0)
3075 					(void) printf(gettext("currently in "
3076 					    "use"));
3077 				else
3078 					(void) printf(gettext("in use by "
3079 					    "pool '%s'"),
3080 					    zpool_get_name(spare_cb.cb_zhp));
3081 				zpool_close(spare_cb.cb_zhp);
3082 			} else {
3083 				(void) printf(gettext("currently in use"));
3084 			}
3085 			break;
3086 
3087 		case VDEV_AUX_ERR_EXCEEDED:
3088 			if (vs->vs_read_errors + vs->vs_write_errors +
3089 			    vs->vs_checksum_errors == 0 && children == 0 &&
3090 			    vs->vs_slow_ios > 0) {
3091 				(void) printf(gettext("too many slow I/Os"));
3092 			} else {
3093 				(void) printf(gettext("too many errors"));
3094 			}
3095 			break;
3096 
3097 		case VDEV_AUX_IO_FAILURE:
3098 			(void) printf(gettext("experienced I/O failures"));
3099 			break;
3100 
3101 		case VDEV_AUX_BAD_LOG:
3102 			(void) printf(gettext("bad intent log"));
3103 			break;
3104 
3105 		case VDEV_AUX_EXTERNAL:
3106 			(void) printf(gettext("external device fault"));
3107 			break;
3108 
3109 		case VDEV_AUX_SPLIT_POOL:
3110 			(void) printf(gettext("split into new pool"));
3111 			break;
3112 
3113 		case VDEV_AUX_ACTIVE:
3114 			(void) printf(gettext("currently in use"));
3115 			break;
3116 
3117 		case VDEV_AUX_CHILDREN_OFFLINE:
3118 			(void) printf(gettext("all children offline"));
3119 			break;
3120 
3121 		case VDEV_AUX_BAD_LABEL:
3122 			(void) printf(gettext("invalid label"));
3123 			break;
3124 
3125 		default:
3126 			(void) printf(gettext("corrupted data"));
3127 			break;
3128 		}
3129 		color_end();
3130 	} else if (children == 0 && !isspare &&
3131 	    getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
3132 	    VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
3133 	    vs->vs_configured_ashift < vs->vs_physical_ashift) {
3134 		(void) printf(
3135 		    gettext("  block size: %dB configured, %dB native"),
3136 		    1 << vs->vs_configured_ashift, 1 << vs->vs_physical_ashift);
3137 	}
3138 
3139 	if (vs->vs_scan_removing != 0) {
3140 		(void) printf(gettext("  (removing)"));
3141 	} else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
3142 		(void) printf(gettext("  (non-allocating)"));
3143 	}
3144 
3145 	/* The root vdev has the scrub/resilver stats */
3146 	root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
3147 	    ZPOOL_CONFIG_VDEV_TREE);
3148 	(void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
3149 	    (uint64_t **)&ps, &c);
3150 
3151 	/*
3152 	 * If you force fault a drive that's resilvering, its scan stats can
3153 	 * get frozen in time, giving the false impression that it's
3154 	 * being resilvered.  That's why we check the state to see if the vdev
3155 	 * is healthy before reporting "resilvering" or "repairing".
3156 	 */
3157 	if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0 &&
3158 	    vs->vs_state == VDEV_STATE_HEALTHY) {
3159 		if (vs->vs_scan_processed != 0) {
3160 			(void) printf(gettext("  (%s)"),
3161 			    (ps->pss_func == POOL_SCAN_RESILVER) ?
3162 			    "resilvering" : "repairing");
3163 		} else if (vs->vs_resilver_deferred) {
3164 			(void) printf(gettext("  (awaiting resilver)"));
3165 		}
3166 	}
3167 
3168 	/* The top-level vdevs have the rebuild stats */
3169 	if (vrs != NULL && vrs->vrs_state == VDEV_REBUILD_ACTIVE &&
3170 	    children == 0 && vs->vs_state == VDEV_STATE_HEALTHY) {
3171 		if (vs->vs_rebuild_processed != 0) {
3172 			(void) printf(gettext("  (resilvering)"));
3173 		}
3174 	}
3175 
3176 	if (cb->vcdl != NULL) {
3177 		if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
3178 			printf("  ");
3179 			zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
3180 		}
3181 	}
3182 
3183 	/* Display vdev initialization and trim status for leaves. */
3184 	if (children == 0) {
3185 		print_status_initialize(vs, cb->cb_print_vdev_init);
3186 		print_status_trim(vs, cb->cb_print_vdev_trim);
3187 	}
3188 
3189 	(void) printf("\n");
3190 
3191 	for (c = 0; c < children; c++) {
3192 		uint64_t islog = B_FALSE, ishole = B_FALSE;
3193 
3194 		/* Don't print logs or holes here */
3195 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3196 		    &islog);
3197 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
3198 		    &ishole);
3199 		if (islog || ishole)
3200 			continue;
3201 		/* Only print normal classes here */
3202 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3203 			continue;
3204 
3205 		/* Provide vdev_rebuild_stats to children if available */
3206 		if (vrs == NULL) {
3207 			(void) nvlist_lookup_uint64_array(nv,
3208 			    ZPOOL_CONFIG_REBUILD_STATS,
3209 			    (uint64_t **)&vrs, &i);
3210 		}
3211 
3212 		vname = zpool_vdev_name(g_zfs, zhp, child[c],
3213 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3214 		print_status_config(zhp, cb, vname, child[c], depth + 2,
3215 		    isspare, vrs);
3216 		free(vname);
3217 	}
3218 }
3219 
3220 /*
3221  * Print the configuration of an exported pool.  Iterate over all vdevs in the
3222  * pool, printing out the name and status for each one.
3223  */
3224 static void
3225 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
3226     int depth)
3227 {
3228 	nvlist_t **child;
3229 	uint_t c, children;
3230 	vdev_stat_t *vs;
3231 	const char *type;
3232 	char *vname;
3233 
3234 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
3235 	if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
3236 	    strcmp(type, VDEV_TYPE_HOLE) == 0)
3237 		return;
3238 
3239 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
3240 	    (uint64_t **)&vs, &c) == 0);
3241 
3242 	(void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
3243 	(void) printf("  %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
3244 
3245 	if (vs->vs_aux != 0) {
3246 		(void) printf("  ");
3247 
3248 		switch (vs->vs_aux) {
3249 		case VDEV_AUX_OPEN_FAILED:
3250 			(void) printf(gettext("cannot open"));
3251 			break;
3252 
3253 		case VDEV_AUX_BAD_GUID_SUM:
3254 			(void) printf(gettext("missing device"));
3255 			break;
3256 
3257 		case VDEV_AUX_NO_REPLICAS:
3258 			(void) printf(gettext("insufficient replicas"));
3259 			break;
3260 
3261 		case VDEV_AUX_VERSION_NEWER:
3262 			(void) printf(gettext("newer version"));
3263 			break;
3264 
3265 		case VDEV_AUX_UNSUP_FEAT:
3266 			(void) printf(gettext("unsupported feature(s)"));
3267 			break;
3268 
3269 		case VDEV_AUX_ERR_EXCEEDED:
3270 			(void) printf(gettext("too many errors"));
3271 			break;
3272 
3273 		case VDEV_AUX_ACTIVE:
3274 			(void) printf(gettext("currently in use"));
3275 			break;
3276 
3277 		case VDEV_AUX_CHILDREN_OFFLINE:
3278 			(void) printf(gettext("all children offline"));
3279 			break;
3280 
3281 		case VDEV_AUX_BAD_LABEL:
3282 			(void) printf(gettext("invalid label"));
3283 			break;
3284 
3285 		default:
3286 			(void) printf(gettext("corrupted data"));
3287 			break;
3288 		}
3289 	}
3290 	(void) printf("\n");
3291 
3292 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
3293 	    &child, &children) != 0)
3294 		return;
3295 
3296 	for (c = 0; c < children; c++) {
3297 		uint64_t is_log = B_FALSE;
3298 
3299 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3300 		    &is_log);
3301 		if (is_log)
3302 			continue;
3303 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3304 			continue;
3305 
3306 		vname = zpool_vdev_name(g_zfs, NULL, child[c],
3307 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3308 		print_import_config(cb, vname, child[c], depth + 2);
3309 		free(vname);
3310 	}
3311 
3312 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
3313 	    &child, &children) == 0) {
3314 		(void) printf(gettext("\tcache\n"));
3315 		for (c = 0; c < children; c++) {
3316 			vname = zpool_vdev_name(g_zfs, NULL, child[c],
3317 			    cb->cb_name_flags);
3318 			(void) printf("\t  %s\n", vname);
3319 			free(vname);
3320 		}
3321 	}
3322 
3323 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
3324 	    &child, &children) == 0) {
3325 		(void) printf(gettext("\tspares\n"));
3326 		for (c = 0; c < children; c++) {
3327 			vname = zpool_vdev_name(g_zfs, NULL, child[c],
3328 			    cb->cb_name_flags);
3329 			(void) printf("\t  %s\n", vname);
3330 			free(vname);
3331 		}
3332 	}
3333 }
3334 
3335 /*
3336  * Print specialized class vdevs.
3337  *
3338  * These are recorded as top level vdevs in the main pool child array
3339  * but with "is_log" set to 1 or an "alloc_bias" string. We use either
3340  * print_status_config() or print_import_config() to print the top level
3341  * class vdevs then any of their children (eg mirrored slogs) are printed
3342  * recursively - which works because only the top level vdev is marked.
3343  */
3344 static void
3345 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
3346     const char *class)
3347 {
3348 	uint_t c, children;
3349 	nvlist_t **child;
3350 	boolean_t printed = B_FALSE;
3351 
3352 	assert(zhp != NULL || !cb->cb_verbose);
3353 
3354 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
3355 	    &children) != 0)
3356 		return;
3357 
3358 	for (c = 0; c < children; c++) {
3359 		uint64_t is_log = B_FALSE;
3360 		const char *bias = NULL;
3361 		const char *type = NULL;
3362 
3363 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3364 		    &is_log);
3365 
3366 		if (is_log) {
3367 			bias = (char *)VDEV_ALLOC_CLASS_LOGS;
3368 		} else {
3369 			(void) nvlist_lookup_string(child[c],
3370 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
3371 			(void) nvlist_lookup_string(child[c],
3372 			    ZPOOL_CONFIG_TYPE, &type);
3373 		}
3374 
3375 		if (bias == NULL || strcmp(bias, class) != 0)
3376 			continue;
3377 		if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
3378 			continue;
3379 
3380 		if (!printed) {
3381 			(void) printf("\t%s\t\n", gettext(class));
3382 			printed = B_TRUE;
3383 		}
3384 
3385 		char *name = zpool_vdev_name(g_zfs, zhp, child[c],
3386 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3387 		if (cb->cb_print_status)
3388 			print_status_config(zhp, cb, name, child[c], 2,
3389 			    B_FALSE, NULL);
3390 		else
3391 			print_import_config(cb, name, child[c], 2);
3392 		free(name);
3393 	}
3394 }
3395 
3396 /*
3397  * Display the status for the given pool.
3398  */
3399 static int
3400 show_import(nvlist_t *config, boolean_t report_error)
3401 {
3402 	uint64_t pool_state;
3403 	vdev_stat_t *vs;
3404 	const char *name;
3405 	uint64_t guid;
3406 	uint64_t hostid = 0;
3407 	const char *msgid;
3408 	const char *hostname = "unknown";
3409 	nvlist_t *nvroot, *nvinfo;
3410 	zpool_status_t reason;
3411 	zpool_errata_t errata;
3412 	const char *health;
3413 	uint_t vsc;
3414 	const char *comment;
3415 	const char *indent;
3416 	char buf[2048];
3417 	status_cbdata_t cb = { 0 };
3418 
3419 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3420 	    &name) == 0);
3421 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3422 	    &guid) == 0);
3423 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3424 	    &pool_state) == 0);
3425 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3426 	    &nvroot) == 0);
3427 
3428 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
3429 	    (uint64_t **)&vs, &vsc) == 0);
3430 	health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
3431 
3432 	reason = zpool_import_status(config, &msgid, &errata);
3433 
3434 	/*
3435 	 * If we're importing using a cachefile, then we won't report any
3436 	 * errors unless we are in the scan phase of the import.
3437 	 */
3438 	if (reason != ZPOOL_STATUS_OK && !report_error)
3439 		return (reason);
3440 
3441 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0) {
3442 		indent = " ";
3443 	} else {
3444 		comment = NULL;
3445 		indent = "";
3446 	}
3447 
3448 	(void) printf(gettext("%s  pool: %s\n"), indent, name);
3449 	(void) printf(gettext("%s    id: %llu\n"), indent, (u_longlong_t)guid);
3450 	(void) printf(gettext("%s state: %s"), indent, health);
3451 	if (pool_state == POOL_STATE_DESTROYED)
3452 		(void) printf(gettext(" (DESTROYED)"));
3453 	(void) printf("\n");
3454 
3455 	if (reason != ZPOOL_STATUS_OK) {
3456 		(void) printf("%s", indent);
3457 		(void) printf_color(ANSI_BOLD, gettext("status: "));
3458 	}
3459 	switch (reason) {
3460 	case ZPOOL_STATUS_MISSING_DEV_R:
3461 	case ZPOOL_STATUS_MISSING_DEV_NR:
3462 	case ZPOOL_STATUS_BAD_GUID_SUM:
3463 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3464 		    "are missing from the system.\n"));
3465 		break;
3466 
3467 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
3468 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
3469 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3470 		    "contains corrupted data.\n"));
3471 		break;
3472 
3473 	case ZPOOL_STATUS_CORRUPT_DATA:
3474 		(void) printf_color(ANSI_YELLOW, gettext("The pool data is "
3475 		    "corrupted.\n"));
3476 		break;
3477 
3478 	case ZPOOL_STATUS_OFFLINE_DEV:
3479 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3480 		    "are offlined.\n"));
3481 		break;
3482 
3483 	case ZPOOL_STATUS_CORRUPT_POOL:
3484 		(void) printf_color(ANSI_YELLOW, gettext("The pool metadata is "
3485 		    "incomplete or corrupted.\n"));
3486 		break;
3487 
3488 	case ZPOOL_STATUS_VERSION_OLDER:
3489 		(void) printf_color(ANSI_YELLOW, gettext("The pool is "
3490 		    "formatted using a legacy on-disk version.\n"));
3491 		break;
3492 
3493 	case ZPOOL_STATUS_VERSION_NEWER:
3494 		(void) printf_color(ANSI_YELLOW, gettext("The pool is "
3495 		    "formatted using an incompatible version.\n"));
3496 		break;
3497 
3498 	case ZPOOL_STATUS_FEAT_DISABLED:
3499 		(void) printf_color(ANSI_YELLOW, gettext("Some supported "
3500 		    "features are not enabled on the pool.\n"
3501 		    "\t%s(Note that they may be intentionally disabled if the\n"
3502 		    "\t%s'compatibility' property is set.)\n"), indent, indent);
3503 		break;
3504 
3505 	case ZPOOL_STATUS_COMPATIBILITY_ERR:
3506 		(void) printf_color(ANSI_YELLOW, gettext("Error reading or "
3507 		    "parsing the file(s) indicated by the 'compatibility'\n"
3508 		    "\t%sproperty.\n"), indent);
3509 		break;
3510 
3511 	case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
3512 		(void) printf_color(ANSI_YELLOW, gettext("One or more features "
3513 		    "are enabled on the pool despite not being\n"
3514 		    "\t%srequested by the 'compatibility' property.\n"),
3515 		    indent);
3516 		break;
3517 
3518 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
3519 		(void) printf_color(ANSI_YELLOW, gettext("The pool uses the "
3520 		    "following feature(s) not supported on this system:\n"));
3521 		color_start(ANSI_YELLOW);
3522 		zpool_collect_unsup_feat(config, buf, 2048);
3523 		(void) printf("%s", buf);
3524 		color_end();
3525 		break;
3526 
3527 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3528 		(void) printf_color(ANSI_YELLOW, gettext("The pool can only be "
3529 		    "accessed in read-only mode on this system. It\n"
3530 		    "\t%scannot be accessed in read-write mode because it uses "
3531 		    "the following\n"
3532 		    "\t%sfeature(s) not supported on this system:\n"),
3533 		    indent, indent);
3534 		color_start(ANSI_YELLOW);
3535 		zpool_collect_unsup_feat(config, buf, 2048);
3536 		(void) printf("%s", buf);
3537 		color_end();
3538 		break;
3539 
3540 	case ZPOOL_STATUS_HOSTID_ACTIVE:
3541 		(void) printf_color(ANSI_YELLOW, gettext("The pool is "
3542 		    "currently imported by another system.\n"));
3543 		break;
3544 
3545 	case ZPOOL_STATUS_HOSTID_REQUIRED:
3546 		(void) printf_color(ANSI_YELLOW, gettext("The pool has the "
3547 		    "multihost property on.  It cannot\n"
3548 		    "\t%sbe safely imported when the system hostid is not "
3549 		    "set.\n"), indent);
3550 		break;
3551 
3552 	case ZPOOL_STATUS_HOSTID_MISMATCH:
3553 		(void) printf_color(ANSI_YELLOW, gettext("The pool was last "
3554 		    "accessed by another system.\n"));
3555 		break;
3556 
3557 	case ZPOOL_STATUS_FAULTED_FDOM_R:
3558 		(void) printf_color(ANSI_YELLOW, gettext("One or more failure "
3559 		    " domains are faulted.\n"));
3560 		break;
3561 
3562 	case ZPOOL_STATUS_FAULTED_DEV_R:
3563 	case ZPOOL_STATUS_FAULTED_DEV_NR:
3564 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3565 		    "are faulted.\n"));
3566 		break;
3567 
3568 	case ZPOOL_STATUS_BAD_LOG:
3569 		(void) printf_color(ANSI_YELLOW, gettext("An intent log record "
3570 		    "cannot be read.\n"));
3571 		break;
3572 
3573 	case ZPOOL_STATUS_RESILVERING:
3574 	case ZPOOL_STATUS_REBUILDING:
3575 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3576 		    "were being resilvered.\n"));
3577 		break;
3578 
3579 	case ZPOOL_STATUS_ERRATA:
3580 		(void) printf_color(ANSI_YELLOW,
3581 		    gettext("Errata #%d detected.\n"),
3582 		    errata);
3583 		break;
3584 
3585 	case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
3586 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3587 		    "are configured to use a non-native block size.\n"
3588 		    "\t%sExpect reduced performance.\n"), indent);
3589 		break;
3590 
3591 	default:
3592 		/*
3593 		 * No other status can be seen when importing pools.
3594 		 */
3595 		assert(reason == ZPOOL_STATUS_OK);
3596 	}
3597 
3598 	/*
3599 	 * Print out an action according to the overall state of the pool.
3600 	 */
3601 	if (vs->vs_state != VDEV_STATE_HEALTHY ||
3602 	    reason != ZPOOL_STATUS_ERRATA || errata != ZPOOL_ERRATA_NONE) {
3603 		(void) printf("%s", indent);
3604 		(void) printf(gettext("action: "));
3605 	}
3606 	if (vs->vs_state == VDEV_STATE_HEALTHY) {
3607 		if (reason == ZPOOL_STATUS_VERSION_OLDER ||
3608 		    reason == ZPOOL_STATUS_FEAT_DISABLED) {
3609 			(void) printf(gettext("The pool can be imported using "
3610 			    "its name or numeric identifier, though\n"
3611 			    "\t%ssome features will not be available without "
3612 			    "an explicit 'zpool upgrade'.\n"), indent);
3613 		} else if (reason == ZPOOL_STATUS_COMPATIBILITY_ERR) {
3614 			(void) printf(gettext("The pool can be imported using "
3615 			    "its name or numeric\n"
3616 			    "\t%sidentifier, though the file(s) indicated by "
3617 			    "its 'compatibility'\n"
3618 			    "\t%sproperty cannot be parsed at this time.\n"),
3619 			    indent, indent);
3620 		} else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
3621 			(void) printf(gettext("The pool can be imported using "
3622 			    "its name or numeric identifier and\n"
3623 			    "\t%sthe '-f' flag.\n"), indent);
3624 		} else if (reason == ZPOOL_STATUS_ERRATA) {
3625 			switch (errata) {
3626 			case ZPOOL_ERRATA_ZOL_2094_SCRUB:
3627 				(void) printf(gettext("The pool can be "
3628 				    "imported using its name or numeric "
3629 				    "identifier,\n"
3630 				    "\t%showever there is a compatibility "
3631 				    "issue which should be corrected\n"
3632 				    "\t%sby running 'zpool scrub'\n"),
3633 				    indent, indent);
3634 				break;
3635 
3636 			case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
3637 				(void) printf(gettext("The pool cannot be "
3638 				    "imported with this version of ZFS due to\n"
3639 				    "\t%san active asynchronous destroy. "
3640 				    "Revert to an earlier version\n"
3641 				    "\t%sand allow the destroy to complete "
3642 				    "before updating.\n"), indent, indent);
3643 				break;
3644 
3645 			case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
3646 				(void) printf(gettext("Existing encrypted "
3647 				    "datasets contain an on-disk "
3648 				    "incompatibility, which\n"
3649 				    "\t%sneeds to be corrected. Backup these "
3650 				    "datasets to new encrypted datasets\n"
3651 				    "\t%sand destroy the old ones.\n"),
3652 				    indent, indent);
3653 				break;
3654 
3655 			case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
3656 				(void) printf(gettext("Existing encrypted "
3657 				    "snapshots and bookmarks contain an "
3658 				    "on-disk\n"
3659 				    "\t%sincompatibility. This may cause "
3660 				    "on-disk corruption if they are used\n"
3661 				    "\t%swith 'zfs recv'. To correct the "
3662 				    "issue, enable the bookmark_v2 feature.\n"
3663 				    "\t%sNo additional action is needed if "
3664 				    "there are no encrypted snapshots or\n"
3665 				    "\t%sbookmarks. If preserving the "
3666 				    "encrypted snapshots and bookmarks is\n"
3667 				    "\t%srequired, use a non-raw send to "
3668 				    "backup and restore them. Alternately,\n"
3669 				    "\t%sthey may be removed to resolve the "
3670 				    "incompatibility.\n"), indent, indent,
3671 				    indent, indent, indent, indent);
3672 				break;
3673 			default:
3674 				/*
3675 				 * All errata must contain an action message.
3676 				 */
3677 				assert(errata == ZPOOL_ERRATA_NONE);
3678 			}
3679 		} else {
3680 			(void) printf(gettext("The pool can be imported using "
3681 			    "its name or numeric identifier.\n"));
3682 		}
3683 	} else if (vs->vs_state == VDEV_STATE_DEGRADED) {
3684 		(void) printf(gettext("The pool can be imported despite "
3685 		    "missing or damaged devices.  The\n"
3686 		    "\t%sfault tolerance of the pool may be compromised if "
3687 		    "imported.\n"), indent);
3688 	} else {
3689 		switch (reason) {
3690 		case ZPOOL_STATUS_VERSION_NEWER:
3691 			(void) printf(gettext("The pool cannot be imported.  "
3692 			    "Access the pool on a system running newer\n"
3693 			    "\t%ssoftware, or recreate the pool from "
3694 			    "backup.\n"), indent);
3695 			break;
3696 		case ZPOOL_STATUS_UNSUP_FEAT_READ:
3697 			(void) printf(gettext("The pool cannot be imported. "
3698 			    "Access the pool on a system that supports\n"
3699 			    "\t%sthe required feature(s), or recreate the pool "
3700 			    "from backup.\n"), indent);
3701 			break;
3702 		case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3703 			(void) printf(gettext("The pool cannot be imported in "
3704 			    "read-write mode. Import the pool with\n"
3705 			    "\t%s'-o readonly=on', access the pool on a system "
3706 			    "that supports the\n"
3707 			    "\t%srequired feature(s), or recreate the pool "
3708 			    "from backup.\n"), indent, indent);
3709 			break;
3710 		case ZPOOL_STATUS_MISSING_DEV_R:
3711 		case ZPOOL_STATUS_MISSING_DEV_NR:
3712 		case ZPOOL_STATUS_BAD_GUID_SUM:
3713 			(void) printf(gettext("The pool cannot be imported. "
3714 			    "Attach the missing\n"
3715 			    "\t%sdevices and try again.\n"), indent);
3716 			break;
3717 		case ZPOOL_STATUS_HOSTID_ACTIVE:
3718 			VERIFY0(nvlist_lookup_nvlist(config,
3719 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
3720 
3721 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3722 				hostname = fnvlist_lookup_string(nvinfo,
3723 				    ZPOOL_CONFIG_MMP_HOSTNAME);
3724 
3725 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3726 				hostid = fnvlist_lookup_uint64(nvinfo,
3727 				    ZPOOL_CONFIG_MMP_HOSTID);
3728 
3729 			(void) printf(gettext("The pool must be exported from "
3730 			    "%s (hostid=%"PRIx64")\n"
3731 			    "\t%sbefore it can be safely imported.\n"),
3732 			    hostname, hostid, indent);
3733 			break;
3734 		case ZPOOL_STATUS_HOSTID_REQUIRED:
3735 			(void) printf(gettext("Set a unique system hostid with "
3736 			    "the zgenhostid(8) command.\n"));
3737 			break;
3738 		case ZPOOL_STATUS_CORRUPT_POOL:
3739 			(void) printf(gettext("The pool cannot be imported due "
3740 			    "to missing or damaged devices.  Ensure\n"
3741 			    "\t%sall devices are present and not in use by "
3742 			    "another subsystem.\n"), indent);
3743 			break;
3744 		default:
3745 			(void) printf(gettext("The pool cannot be imported due "
3746 			    "to damaged devices or data.\n"));
3747 		}
3748 	}
3749 
3750 	/* Print the comment attached to the pool. */
3751 	if (comment != NULL)
3752 		(void) printf(gettext("comment: %s\n"), comment);
3753 
3754 	/*
3755 	 * If the state is "closed" or "can't open", and the aux state
3756 	 * is "corrupt data":
3757 	 */
3758 	if ((vs->vs_state == VDEV_STATE_CLOSED ||
3759 	    vs->vs_state == VDEV_STATE_CANT_OPEN) &&
3760 	    vs->vs_aux == VDEV_AUX_CORRUPT_DATA) {
3761 		if (pool_state == POOL_STATE_DESTROYED)
3762 			(void) printf(gettext("\t%sThe pool was destroyed, "
3763 			    "but can be imported using the '-Df' flags.\n"),
3764 			    indent);
3765 		else if (pool_state != POOL_STATE_EXPORTED)
3766 			(void) printf(gettext("\t%sThe pool may be active on "
3767 			    "another system, but can be imported using\n"
3768 			    "\t%sthe '-f' flag.\n"), indent, indent);
3769 	}
3770 
3771 	if (msgid != NULL) {
3772 		(void) printf(gettext("%s   see: "
3773 		    "https://openzfs.github.io/openzfs-docs/msg/%s\n"),
3774 		    indent, msgid);
3775 	}
3776 
3777 	(void) printf(gettext("%sconfig:\n\n"), indent);
3778 
3779 	cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
3780 	    VDEV_NAME_TYPE_ID);
3781 	if (cb.cb_namewidth < 10)
3782 		cb.cb_namewidth = 10;
3783 
3784 	print_import_config(&cb, name, nvroot, 0);
3785 
3786 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
3787 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
3788 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
3789 
3790 	if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
3791 		(void) printf(gettext("\n\t%sAdditional devices are known to "
3792 		    "be part of this pool, though their\n"
3793 		    "\t%sexact configuration cannot be determined.\n"),
3794 		    indent, indent);
3795 	}
3796 	return (0);
3797 }
3798 
3799 static boolean_t
3800 zfs_force_import_required(nvlist_t *config)
3801 {
3802 	uint64_t state;
3803 	uint64_t hostid = 0;
3804 	nvlist_t *nvinfo;
3805 
3806 	state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
3807 	nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3808 
3809 	/*
3810 	 * The hostid on LOAD_INFO comes from the MOS label via
3811 	 * spa_tryimport(). If its not there then we're likely talking to an
3812 	 * older kernel, so use the top one, which will be from the label
3813 	 * discovered in zpool_find_import(), or if a cachefile is in use, the
3814 	 * local hostid.
3815 	 */
3816 	if (nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_HOSTID, &hostid) != 0)
3817 		(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
3818 		    &hostid);
3819 
3820 	if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
3821 		return (B_TRUE);
3822 
3823 	if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
3824 		mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
3825 		    ZPOOL_CONFIG_MMP_STATE);
3826 
3827 		if (mmp_state != MMP_STATE_INACTIVE)
3828 			return (B_TRUE);
3829 	}
3830 
3831 	return (B_FALSE);
3832 }
3833 
3834 /*
3835  * Perform the import for the given configuration.  This passes the heavy
3836  * lifting off to zpool_import_props(), and then mounts the datasets contained
3837  * within the pool.
3838  */
3839 static int
3840 do_import(nvlist_t *config, const char *newname, const char *mntopts,
3841     nvlist_t *props, int flags, uint_t mntthreads)
3842 {
3843 	int ret = 0;
3844 	int ms_status = 0;
3845 	zpool_handle_t *zhp;
3846 	const char *name;
3847 	uint64_t version;
3848 
3849 	name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
3850 	version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3851 
3852 	if (!SPA_VERSION_IS_SUPPORTED(version)) {
3853 		(void) fprintf(stderr, gettext("cannot import '%s': pool "
3854 		    "is formatted using an unsupported ZFS version\n"), name);
3855 		return (1);
3856 	} else if (zfs_force_import_required(config) &&
3857 	    !(flags & ZFS_IMPORT_ANY_HOST)) {
3858 		mmp_state_t mmp_state = MMP_STATE_INACTIVE;
3859 		nvlist_t *nvinfo;
3860 
3861 		nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3862 		if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
3863 			mmp_state = fnvlist_lookup_uint64(nvinfo,
3864 			    ZPOOL_CONFIG_MMP_STATE);
3865 
3866 		if (mmp_state == MMP_STATE_ACTIVE) {
3867 			const char *hostname = "<unknown>";
3868 			uint64_t hostid = 0;
3869 
3870 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3871 				hostname = fnvlist_lookup_string(nvinfo,
3872 				    ZPOOL_CONFIG_MMP_HOSTNAME);
3873 
3874 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3875 				hostid = fnvlist_lookup_uint64(nvinfo,
3876 				    ZPOOL_CONFIG_MMP_HOSTID);
3877 
3878 			(void) fprintf(stderr, gettext("cannot import '%s': "
3879 			    "pool is imported on %s (hostid: "
3880 			    "0x%"PRIx64")\nExport the pool on the other "
3881 			    "system, then run 'zpool import'.\n"),
3882 			    name, hostname, hostid);
3883 		} else if (mmp_state == MMP_STATE_NO_HOSTID) {
3884 			(void) fprintf(stderr, gettext("Cannot import '%s': "
3885 			    "pool has the multihost property on and the\n"
3886 			    "system's hostid is not set. Set a unique hostid "
3887 			    "with the zgenhostid(8) command.\n"), name);
3888 		} else {
3889 			const char *hostname = "<unknown>";
3890 			time_t timestamp = 0;
3891 			uint64_t hostid = 0;
3892 
3893 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTNAME))
3894 				hostname = fnvlist_lookup_string(nvinfo,
3895 				    ZPOOL_CONFIG_HOSTNAME);
3896 			else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
3897 				hostname = fnvlist_lookup_string(config,
3898 				    ZPOOL_CONFIG_HOSTNAME);
3899 
3900 			if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
3901 				timestamp = fnvlist_lookup_uint64(config,
3902 				    ZPOOL_CONFIG_TIMESTAMP);
3903 
3904 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTID))
3905 				hostid = fnvlist_lookup_uint64(nvinfo,
3906 				    ZPOOL_CONFIG_HOSTID);
3907 			else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
3908 				hostid = fnvlist_lookup_uint64(config,
3909 				    ZPOOL_CONFIG_HOSTID);
3910 
3911 			(void) fprintf(stderr, gettext("cannot import '%s': "
3912 			    "pool was previously in use from another system.\n"
3913 			    "Last accessed by %s (hostid=%"PRIx64") at %s"
3914 			    "The pool can be imported, use 'zpool import -f' "
3915 			    "to import the pool.\n"), name, hostname,
3916 			    hostid, ctime(&timestamp));
3917 		}
3918 
3919 		if (getenv("ZFS_LOAD_INFO_DEBUG"))
3920 			dump_nvlist(nvinfo, 4);
3921 
3922 		return (1);
3923 	}
3924 
3925 	if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
3926 		return (1);
3927 
3928 	if (newname != NULL)
3929 		name = newname;
3930 
3931 	if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
3932 		return (1);
3933 
3934 	/*
3935 	 * Loading keys is best effort. We don't want to return immediately
3936 	 * if it fails but we do want to give the error to the caller.
3937 	 */
3938 	if (flags & ZFS_IMPORT_LOAD_KEYS &&
3939 	    zfs_crypto_attempt_load_keys(g_zfs, name) != 0)
3940 			ret = 1;
3941 
3942 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3943 	    !(flags & ZFS_IMPORT_ONLY)) {
3944 		ms_status = zpool_enable_datasets(zhp, mntopts, 0, mntthreads);
3945 		if (ms_status == EZFS_SHAREFAILED) {
3946 			(void) fprintf(stderr, gettext("Import was "
3947 			    "successful, but unable to share some datasets\n"));
3948 		} else if (ms_status == EZFS_MOUNTFAILED) {
3949 			(void) fprintf(stderr, gettext("Import was "
3950 			    "successful, but unable to mount some datasets\n"));
3951 		}
3952 	}
3953 
3954 	zpool_close(zhp);
3955 	return (ret);
3956 }
3957 
3958 typedef struct import_parameters {
3959 	nvlist_t *ip_config;
3960 	const char *ip_mntopts;
3961 	nvlist_t *ip_props;
3962 	int ip_flags;
3963 	uint_t ip_mntthreads;
3964 	int *ip_err;
3965 } import_parameters_t;
3966 
3967 static void
3968 do_import_task(void *arg)
3969 {
3970 	import_parameters_t *ip = arg;
3971 	*ip->ip_err |= do_import(ip->ip_config, NULL, ip->ip_mntopts,
3972 	    ip->ip_props, ip->ip_flags, ip->ip_mntthreads);
3973 	free(ip);
3974 }
3975 
3976 
3977 static int
3978 import_pools(nvlist_t *pools, nvlist_t *props, char *mntopts, int flags,
3979     char *orig_name, char *new_name, importargs_t *import)
3980 {
3981 	nvlist_t *config = NULL;
3982 	nvlist_t *found_config = NULL;
3983 	uint64_t pool_state;
3984 	boolean_t pool_specified = (import->poolname != NULL ||
3985 	    import->guid != 0);
3986 	uint_t npools = 0;
3987 
3988 
3989 	taskq_t *tq = NULL;
3990 	if (import->do_all) {
3991 		tq = taskq_create("zpool_import_all",
3992 		    5 * sysconf(_SC_NPROCESSORS_ONLN), minclsyspri, 1, INT_MAX,
3993 		    TASKQ_DYNAMIC);
3994 	}
3995 
3996 	/*
3997 	 * At this point we have a list of import candidate configs. Even if
3998 	 * we were searching by pool name or guid, we still need to
3999 	 * post-process the list to deal with pool state and possible
4000 	 * duplicate names.
4001 	 */
4002 	int err = 0;
4003 	nvpair_t *elem = NULL;
4004 	boolean_t first = B_TRUE;
4005 	if (!pool_specified && import->do_all) {
4006 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL)
4007 			npools++;
4008 	}
4009 	while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
4010 
4011 		verify(nvpair_value_nvlist(elem, &config) == 0);
4012 
4013 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4014 		    &pool_state) == 0);
4015 		if (!import->do_destroyed &&
4016 		    pool_state == POOL_STATE_DESTROYED)
4017 			continue;
4018 		if (import->do_destroyed &&
4019 		    pool_state != POOL_STATE_DESTROYED)
4020 			continue;
4021 
4022 		verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
4023 		    import->policy) == 0);
4024 
4025 		if (!pool_specified) {
4026 			if (first)
4027 				first = B_FALSE;
4028 			else if (!import->do_all)
4029 				(void) fputc('\n', stdout);
4030 
4031 			if (import->do_all) {
4032 				import_parameters_t *ip = safe_malloc(
4033 				    sizeof (import_parameters_t));
4034 
4035 				ip->ip_config = config;
4036 				ip->ip_mntopts = mntopts;
4037 				ip->ip_props = props;
4038 				ip->ip_flags = flags;
4039 				ip->ip_mntthreads = mount_tp_nthr / npools;
4040 				ip->ip_err = &err;
4041 
4042 				(void) taskq_dispatch(tq, do_import_task,
4043 				    (void *)ip, TQ_SLEEP);
4044 			} else {
4045 				/*
4046 				 * If we're importing from cachefile, then
4047 				 * we don't want to report errors until we
4048 				 * are in the scan phase of the import. If
4049 				 * we get an error, then we return that error
4050 				 * to invoke the scan phase.
4051 				 */
4052 				if (import->cachefile && !import->scan)
4053 					err = show_import(config, B_FALSE);
4054 				else
4055 					(void) show_import(config, B_TRUE);
4056 			}
4057 		} else if (import->poolname != NULL) {
4058 			const char *name;
4059 
4060 			/*
4061 			 * We are searching for a pool based on name.
4062 			 */
4063 			verify(nvlist_lookup_string(config,
4064 			    ZPOOL_CONFIG_POOL_NAME, &name) == 0);
4065 
4066 			if (strcmp(name, import->poolname) == 0) {
4067 				if (found_config != NULL) {
4068 					(void) fprintf(stderr, gettext(
4069 					    "cannot import '%s': more than "
4070 					    "one matching pool\n"),
4071 					    import->poolname);
4072 					(void) fprintf(stderr, gettext(
4073 					    "import by numeric ID instead\n"));
4074 					err = B_TRUE;
4075 				}
4076 				found_config = config;
4077 			}
4078 		} else {
4079 			uint64_t guid;
4080 
4081 			/*
4082 			 * Search for a pool by guid.
4083 			 */
4084 			verify(nvlist_lookup_uint64(config,
4085 			    ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
4086 
4087 			if (guid == import->guid)
4088 				found_config = config;
4089 		}
4090 	}
4091 	if (import->do_all) {
4092 		taskq_wait(tq);
4093 		taskq_destroy(tq);
4094 	}
4095 
4096 	/*
4097 	 * If we were searching for a specific pool, verify that we found a
4098 	 * pool, and then do the import.
4099 	 */
4100 	if (pool_specified && err == 0) {
4101 		if (found_config == NULL) {
4102 			(void) fprintf(stderr, gettext("cannot import '%s': "
4103 			    "no such pool available\n"), orig_name);
4104 			err = B_TRUE;
4105 		} else {
4106 			err |= do_import(found_config, new_name,
4107 			    mntopts, props, flags, mount_tp_nthr);
4108 		}
4109 	}
4110 
4111 	/*
4112 	 * If we were just looking for pools, report an error if none were
4113 	 * found.
4114 	 */
4115 	if (!pool_specified && first)
4116 		(void) fprintf(stderr,
4117 		    gettext("no pools available to import\n"));
4118 	return (err);
4119 }
4120 
4121 typedef struct target_exists_args {
4122 	const char	*poolname;
4123 	uint64_t	poolguid;
4124 } target_exists_args_t;
4125 
4126 static int
4127 name_or_guid_exists(zpool_handle_t *zhp, void *data)
4128 {
4129 	target_exists_args_t *args = data;
4130 	nvlist_t *config = zpool_get_config(zhp, NULL);
4131 	int found = 0;
4132 
4133 	if (config == NULL)
4134 		return (0);
4135 
4136 	if (args->poolname != NULL) {
4137 		const char *pool_name;
4138 
4139 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4140 		    &pool_name) == 0);
4141 		if (strcmp(pool_name, args->poolname) == 0)
4142 			found = 1;
4143 	} else {
4144 		uint64_t pool_guid;
4145 
4146 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4147 		    &pool_guid) == 0);
4148 		if (pool_guid == args->poolguid)
4149 			found = 1;
4150 	}
4151 	zpool_close(zhp);
4152 
4153 	return (found);
4154 }
4155 /*
4156  * zpool checkpoint <pool>
4157  *       checkpoint --discard <pool>
4158  *
4159  *       -d         Discard the checkpoint from a checkpointed
4160  *       --discard  pool.
4161  *
4162  *       -w         Wait for discarding a checkpoint to complete.
4163  *       --wait
4164  *
4165  * Checkpoints the specified pool, by taking a "snapshot" of its
4166  * current state. A pool can only have one checkpoint at a time.
4167  */
4168 int
4169 zpool_do_checkpoint(int argc, char **argv)
4170 {
4171 	boolean_t discard, wait;
4172 	char *pool;
4173 	zpool_handle_t *zhp;
4174 	int c, err;
4175 
4176 	struct option long_options[] = {
4177 		{"discard", no_argument, NULL, 'd'},
4178 		{"wait", no_argument, NULL, 'w'},
4179 		{0, 0, 0, 0}
4180 	};
4181 
4182 	discard = B_FALSE;
4183 	wait = B_FALSE;
4184 	while ((c = getopt_long(argc, argv, ":dw", long_options, NULL)) != -1) {
4185 		switch (c) {
4186 		case 'd':
4187 			discard = B_TRUE;
4188 			break;
4189 		case 'w':
4190 			wait = B_TRUE;
4191 			break;
4192 		case '?':
4193 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4194 			    optopt);
4195 			usage(B_FALSE);
4196 		}
4197 	}
4198 
4199 	if (wait && !discard) {
4200 		(void) fprintf(stderr, gettext("--wait only valid when "
4201 		    "--discard also specified\n"));
4202 		usage(B_FALSE);
4203 	}
4204 
4205 	argc -= optind;
4206 	argv += optind;
4207 
4208 	if (argc < 1) {
4209 		(void) fprintf(stderr, gettext("missing pool argument\n"));
4210 		usage(B_FALSE);
4211 	}
4212 
4213 	if (argc > 1) {
4214 		(void) fprintf(stderr, gettext("too many arguments\n"));
4215 		usage(B_FALSE);
4216 	}
4217 
4218 	pool = argv[0];
4219 
4220 	if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
4221 		/* As a special case, check for use of '/' in the name */
4222 		if (strchr(pool, '/') != NULL)
4223 			(void) fprintf(stderr, gettext("'zpool checkpoint' "
4224 			    "doesn't work on datasets. To save the state "
4225 			    "of a dataset from a specific point in time "
4226 			    "please use 'zfs snapshot'\n"));
4227 		return (1);
4228 	}
4229 
4230 	if (discard) {
4231 		err = (zpool_discard_checkpoint(zhp) != 0);
4232 		if (err == 0 && wait)
4233 			err = zpool_wait(zhp, ZPOOL_WAIT_CKPT_DISCARD);
4234 	} else {
4235 		err = (zpool_checkpoint(zhp) != 0);
4236 	}
4237 
4238 	zpool_close(zhp);
4239 
4240 	return (err);
4241 }
4242 
4243 #define	CHECKPOINT_OPT	1024
4244 
4245 /*
4246  * zpool prefetch [-t <type>] <pool>
4247  *
4248  * Prefetchs a particular type of data in the specified pool.
4249  */
4250 int
4251 zpool_do_prefetch(int argc, char **argv)
4252 {
4253 	int c;
4254 	char *poolname;
4255 	char *typestr = NULL;
4256 	zpool_prefetch_type_t type;
4257 	zpool_handle_t *zhp;
4258 	int err = 0;
4259 
4260 	while ((c = getopt(argc, argv, "t:")) != -1) {
4261 		switch (c) {
4262 		case 't':
4263 			typestr = optarg;
4264 			break;
4265 		case ':':
4266 			(void) fprintf(stderr, gettext("missing argument for "
4267 			    "'%c' option\n"), optopt);
4268 			usage(B_FALSE);
4269 			break;
4270 		case '?':
4271 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4272 			    optopt);
4273 			usage(B_FALSE);
4274 		}
4275 	}
4276 	argc -= optind;
4277 	argv += optind;
4278 
4279 	if (argc < 1) {
4280 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
4281 		usage(B_FALSE);
4282 	}
4283 
4284 	if (argc > 1) {
4285 		(void) fprintf(stderr, gettext("too many arguments\n"));
4286 		usage(B_FALSE);
4287 	}
4288 
4289 	poolname = argv[0];
4290 
4291 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
4292 		return (1);
4293 
4294 	if (typestr == NULL) {
4295 		/* Prefetch all types */
4296 		err = zpool_prefetch(zhp, ZPOOL_PREFETCH_DDT);
4297 		if (err == 0)
4298 			err = zpool_prefetch(zhp, ZPOOL_PREFETCH_BRT);
4299 	} else {
4300 		if (strcmp(typestr, "ddt") == 0) {
4301 			type = ZPOOL_PREFETCH_DDT;
4302 		} else if (strcmp(typestr, "brt") == 0) {
4303 			type = ZPOOL_PREFETCH_BRT;
4304 		} else {
4305 			(void) fprintf(stderr,
4306 			    gettext("unsupported prefetch type\n"));
4307 			zpool_close(zhp);
4308 			usage(B_FALSE);
4309 		}
4310 		err = zpool_prefetch(zhp, type);
4311 	}
4312 
4313 	zpool_close(zhp);
4314 
4315 	return (err);
4316 }
4317 
4318 /*
4319  * zpool import [-d dir] [-D]
4320  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4321  *              [-d dir | -c cachefile | -s] [-f] -a
4322  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4323  *              [-d dir | -c cachefile | -s] [-f] [-n] [-F] <pool | id>
4324  *              [newpool]
4325  *
4326  *	-c	Read pool information from a cachefile instead of searching
4327  *		devices. If importing from a cachefile config fails, then
4328  *		fallback to searching for devices only in the directories that
4329  *		exist in the cachefile.
4330  *
4331  *	-d	Scan in a specific directory, other than /dev/.  More than
4332  *		one directory can be specified using multiple '-d' options.
4333  *
4334  *	-D	Scan for previously destroyed pools or import all or only
4335  *		specified destroyed pools.
4336  *
4337  *	-R	Temporarily import the pool, with all mountpoints relative to
4338  *		the given root.  The pool will remain exported when the machine
4339  *		is rebooted.
4340  *
4341  *	-V	Import even in the presence of faulted vdevs.  This is an
4342  *		intentionally undocumented option for testing purposes, and
4343  *		treats the pool configuration as complete, leaving any bad
4344  *		vdevs in the FAULTED state. In other words, it does verbatim
4345  *		import.
4346  *
4347  *	-f	Force import, even if it appears that the pool is active.
4348  *
4349  *	-F	Attempt rewind if necessary.
4350  *
4351  *	-M	Tolerate meta-data read errors that are not critical for the
4352  *		pool operation.
4353  *
4354  *	-n	See if rewind would work, but don't actually rewind.
4355  *
4356  *	-N	Import the pool but don't mount datasets.
4357  *
4358  *	-T	Specify a starting txg to use for import. This option is
4359  *		intentionally undocumented option for testing purposes.
4360  *
4361  *	-a	Import all pools found.
4362  *
4363  *	-l	Load encryption keys while importing.
4364  *
4365  *	-o	Set property=value and/or temporary mount options (without '=').
4366  *
4367  *	-s	Scan using the default search path, the libblkid cache will
4368  *		not be consulted.
4369  *
4370  *	--rewind-to-checkpoint
4371  *		Import the pool and revert back to the checkpoint.
4372  *
4373  * The import command scans for pools to import, and import pools based on pool
4374  * name and GUID.  The pool can also be renamed as part of the import process.
4375  */
4376 int
4377 zpool_do_import(int argc, char **argv)
4378 {
4379 	char **searchdirs = NULL;
4380 	char *env, *envdup = NULL;
4381 	int nsearch = 0;
4382 	int c;
4383 	int err = 0;
4384 	nvlist_t *pools = NULL;
4385 	boolean_t do_all = B_FALSE;
4386 	boolean_t do_destroyed = B_FALSE;
4387 	char *mntopts = NULL;
4388 	uint64_t searchguid = 0;
4389 	char *searchname = NULL;
4390 	char *propval;
4391 	nvlist_t *policy = NULL;
4392 	nvlist_t *props = NULL;
4393 	int flags = ZFS_IMPORT_NORMAL;
4394 	uint32_t rewind_policy = ZPOOL_NO_REWIND;
4395 	boolean_t dryrun = B_FALSE;
4396 	boolean_t do_rewind = B_FALSE;
4397 	boolean_t xtreme_rewind = B_FALSE;
4398 	boolean_t relax_meta = B_FALSE;
4399 	boolean_t do_scan = B_FALSE;
4400 	boolean_t pool_exists = B_FALSE;
4401 	uint64_t txg = -1ULL;
4402 	char *cachefile = NULL;
4403 	importargs_t idata = { 0 };
4404 	char *endptr;
4405 
4406 	struct option long_options[] = {
4407 		{"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
4408 		{0, 0, 0, 0}
4409 	};
4410 
4411 	/* check options */
4412 	while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmMnNo:R:stT:VX",
4413 	    long_options, NULL)) != -1) {
4414 		switch (c) {
4415 		case 'a':
4416 			do_all = B_TRUE;
4417 			break;
4418 		case 'c':
4419 			cachefile = optarg;
4420 			break;
4421 		case 'd':
4422 			searchdirs = safe_realloc(searchdirs,
4423 			    (nsearch + 1) * sizeof (char *));
4424 			searchdirs[nsearch++] = optarg;
4425 			break;
4426 		case 'D':
4427 			do_destroyed = B_TRUE;
4428 			break;
4429 		case 'f':
4430 			flags |= ZFS_IMPORT_ANY_HOST;
4431 			break;
4432 		case 'F':
4433 			do_rewind = B_TRUE;
4434 			break;
4435 		case 'l':
4436 			flags |= ZFS_IMPORT_LOAD_KEYS;
4437 			break;
4438 		case 'm':
4439 			flags |= ZFS_IMPORT_MISSING_LOG;
4440 			break;
4441 		case 'M':
4442 			relax_meta = B_TRUE;
4443 			break;
4444 		case 'n':
4445 			dryrun = B_TRUE;
4446 			break;
4447 		case 'N':
4448 			flags |= ZFS_IMPORT_ONLY;
4449 			break;
4450 		case 'o':
4451 			if ((propval = strchr(optarg, '=')) != NULL) {
4452 				*propval = '\0';
4453 				propval++;
4454 				if (add_prop_list(optarg, propval,
4455 				    &props, B_TRUE))
4456 					goto error;
4457 			} else {
4458 				mntopts = optarg;
4459 			}
4460 			break;
4461 		case 'R':
4462 			if (add_prop_list(zpool_prop_to_name(
4463 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
4464 				goto error;
4465 			if (add_prop_list_default(zpool_prop_to_name(
4466 			    ZPOOL_PROP_CACHEFILE), "none", &props))
4467 				goto error;
4468 			break;
4469 		case 's':
4470 			do_scan = B_TRUE;
4471 			break;
4472 		case 't':
4473 			flags |= ZFS_IMPORT_TEMP_NAME;
4474 			if (add_prop_list_default(zpool_prop_to_name(
4475 			    ZPOOL_PROP_CACHEFILE), "none", &props))
4476 				goto error;
4477 			break;
4478 
4479 		case 'T':
4480 			errno = 0;
4481 			txg = strtoull(optarg, &endptr, 0);
4482 			if (errno != 0 || *endptr != '\0') {
4483 				(void) fprintf(stderr,
4484 				    gettext("invalid txg value\n"));
4485 				usage(B_FALSE);
4486 			}
4487 			/* Rollback to a specific txg implies -FX. */
4488 			do_rewind = B_TRUE;
4489 			xtreme_rewind = B_TRUE;
4490 			break;
4491 		case 'V':
4492 			flags |= ZFS_IMPORT_VERBATIM;
4493 			break;
4494 		case 'X':
4495 			xtreme_rewind = B_TRUE;
4496 			break;
4497 		case CHECKPOINT_OPT:
4498 			flags |= ZFS_IMPORT_CHECKPOINT;
4499 			break;
4500 		case ':':
4501 			(void) fprintf(stderr, gettext("missing argument for "
4502 			    "'%c' option\n"), optopt);
4503 			usage(B_FALSE);
4504 			break;
4505 		case '?':
4506 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4507 			    optopt);
4508 			usage(B_FALSE);
4509 		}
4510 	}
4511 
4512 	argc -= optind;
4513 	argv += optind;
4514 
4515 	if (cachefile && nsearch != 0) {
4516 		(void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
4517 		usage(B_FALSE);
4518 	}
4519 
4520 	if (cachefile && do_scan) {
4521 		(void) fprintf(stderr, gettext("-c is incompatible with -s\n"));
4522 		usage(B_FALSE);
4523 	}
4524 
4525 	if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
4526 		(void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
4527 		usage(B_FALSE);
4528 	}
4529 
4530 	if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
4531 		(void) fprintf(stderr, gettext("-l is only meaningful during "
4532 		    "an import\n"));
4533 		usage(B_FALSE);
4534 	}
4535 
4536 	if ((dryrun || xtreme_rewind) && !do_rewind) {
4537 		(void) fprintf(stderr,
4538 		    gettext("-n or -X only meaningful with -F\n"));
4539 		usage(B_FALSE);
4540 	}
4541 	if (dryrun)
4542 		rewind_policy = ZPOOL_TRY_REWIND;
4543 	else if (do_rewind)
4544 		rewind_policy = ZPOOL_DO_REWIND;
4545 	if (xtreme_rewind)
4546 		rewind_policy |= ZPOOL_EXTREME_REWIND;
4547 
4548 	/* In the future, we can capture further policy and include it here */
4549 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
4550 	    nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
4551 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
4552 	    rewind_policy) != 0 ||
4553 	    nvlist_add_boolean_value(policy, ZPOOL_LOAD_RELAX_META,
4554 	    relax_meta) != 0)
4555 		goto error;
4556 
4557 	/* check argument count */
4558 	if (do_all) {
4559 		if (argc != 0) {
4560 			(void) fprintf(stderr, gettext("too many arguments\n"));
4561 			usage(B_FALSE);
4562 		}
4563 	} else {
4564 		if (argc > 2) {
4565 			(void) fprintf(stderr, gettext("too many arguments\n"));
4566 			usage(B_FALSE);
4567 		}
4568 	}
4569 
4570 	/*
4571 	 * Check for the effective uid.  We do this explicitly here because
4572 	 * otherwise any attempt to discover pools will silently fail.
4573 	 */
4574 	if (argc == 0 && geteuid() != 0) {
4575 		(void) fprintf(stderr, gettext("cannot "
4576 		    "discover pools: permission denied\n"));
4577 
4578 		free(searchdirs);
4579 		nvlist_free(props);
4580 		nvlist_free(policy);
4581 		return (1);
4582 	}
4583 
4584 	/*
4585 	 * Depending on the arguments given, we do one of the following:
4586 	 *
4587 	 *	<none>	Iterate through all pools and display information about
4588 	 *		each one.
4589 	 *
4590 	 *	-a	Iterate through all pools and try to import each one.
4591 	 *
4592 	 *	<id>	Find the pool that corresponds to the given GUID/pool
4593 	 *		name and import that one.
4594 	 *
4595 	 *	-D	Above options applies only to destroyed pools.
4596 	 */
4597 	if (argc != 0) {
4598 		char *endptr;
4599 
4600 		errno = 0;
4601 		searchguid = strtoull(argv[0], &endptr, 10);
4602 		if (errno != 0 || *endptr != '\0') {
4603 			searchname = argv[0];
4604 			searchguid = 0;
4605 		}
4606 
4607 		/*
4608 		 * User specified a name or guid.  Ensure it's unique.
4609 		 */
4610 		target_exists_args_t search = {searchname, searchguid};
4611 		pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
4612 	}
4613 
4614 	/*
4615 	 * Check the environment for the preferred search path.
4616 	 */
4617 	if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
4618 		char *dir, *tmp = NULL;
4619 
4620 		envdup = strdup(env);
4621 
4622 		for (dir = strtok_r(envdup, ":", &tmp);
4623 		    dir != NULL;
4624 		    dir = strtok_r(NULL, ":", &tmp)) {
4625 			searchdirs = safe_realloc(searchdirs,
4626 			    (nsearch + 1) * sizeof (char *));
4627 			searchdirs[nsearch++] = dir;
4628 		}
4629 	}
4630 
4631 	idata.path = searchdirs;
4632 	idata.paths = nsearch;
4633 	idata.poolname = searchname;
4634 	idata.guid = searchguid;
4635 	idata.cachefile = cachefile;
4636 	idata.scan = do_scan;
4637 	idata.policy = policy;
4638 	idata.do_destroyed = do_destroyed;
4639 	idata.do_all = do_all;
4640 
4641 	libpc_handle_t lpch = {
4642 		.lpc_lib_handle = g_zfs,
4643 		.lpc_ops = &libzfs_config_ops,
4644 		.lpc_printerr = B_TRUE
4645 	};
4646 	pools = zpool_search_import(&lpch, &idata);
4647 
4648 	if (pools != NULL && pool_exists &&
4649 	    (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
4650 		(void) fprintf(stderr, gettext("cannot import '%s': "
4651 		    "a pool with that name already exists\n"),
4652 		    argv[0]);
4653 		(void) fprintf(stderr, gettext("use the form '%s "
4654 		    "<pool | id> <newpool>' to give it a new name\n"),
4655 		    "zpool import");
4656 		err = 1;
4657 	} else if (pools == NULL && pool_exists) {
4658 		(void) fprintf(stderr, gettext("cannot import '%s': "
4659 		    "a pool with that name is already created/imported,\n"),
4660 		    argv[0]);
4661 		(void) fprintf(stderr, gettext("and no additional pools "
4662 		    "with that name were found\n"));
4663 		err = 1;
4664 	} else if (pools == NULL) {
4665 		if (argc != 0) {
4666 			(void) fprintf(stderr, gettext("cannot import '%s': "
4667 			    "no such pool available\n"), argv[0]);
4668 		}
4669 		err = 1;
4670 	}
4671 
4672 	if (err == 1) {
4673 		free(searchdirs);
4674 		free(envdup);
4675 		nvlist_free(policy);
4676 		nvlist_free(pools);
4677 		nvlist_free(props);
4678 		return (1);
4679 	}
4680 
4681 	err = import_pools(pools, props, mntopts, flags,
4682 	    argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL, &idata);
4683 
4684 	/*
4685 	 * If we're using the cachefile and we failed to import, then
4686 	 * fallback to scanning the directory for pools that match
4687 	 * those in the cachefile.
4688 	 */
4689 	if (err != 0 && cachefile != NULL) {
4690 		(void) printf(gettext("cachefile import failed, retrying\n"));
4691 
4692 		/*
4693 		 * We use the scan flag to gather the directories that exist
4694 		 * in the cachefile. If we need to fallback to searching for
4695 		 * the pool config, we will only search devices in these
4696 		 * directories.
4697 		 */
4698 		idata.scan = B_TRUE;
4699 		nvlist_free(pools);
4700 		pools = zpool_search_import(&lpch, &idata);
4701 
4702 		err = import_pools(pools, props, mntopts, flags,
4703 		    argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL,
4704 		    &idata);
4705 	}
4706 
4707 error:
4708 	nvlist_free(props);
4709 	nvlist_free(pools);
4710 	nvlist_free(policy);
4711 	free(searchdirs);
4712 	free(envdup);
4713 
4714 	return (err ? 1 : 0);
4715 }
4716 
4717 /*
4718  * zpool sync [-f] [pool] ...
4719  *
4720  * -f (undocumented) force uberblock (and config including zpool cache file)
4721  *    update.
4722  *
4723  * Sync the specified pool(s).
4724  * Without arguments "zpool sync" will sync all pools.
4725  * This command initiates TXG sync(s) and will return after the TXG(s) commit.
4726  *
4727  */
4728 static int
4729 zpool_do_sync(int argc, char **argv)
4730 {
4731 	int ret;
4732 	boolean_t force = B_FALSE;
4733 
4734 	/* check options */
4735 	while ((ret  = getopt(argc, argv, "f")) != -1) {
4736 		switch (ret) {
4737 		case 'f':
4738 			force = B_TRUE;
4739 			break;
4740 		case '?':
4741 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4742 			    optopt);
4743 			usage(B_FALSE);
4744 		}
4745 	}
4746 
4747 	argc -= optind;
4748 	argv += optind;
4749 
4750 	/* if argc == 0 we will execute zpool_sync_one on all pools */
4751 	ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
4752 	    B_FALSE, zpool_sync_one, &force);
4753 
4754 	return (ret);
4755 }
4756 
4757 typedef struct iostat_cbdata {
4758 	uint64_t cb_flags;
4759 	int cb_namewidth;
4760 	int cb_iteration;
4761 	boolean_t cb_verbose;
4762 	boolean_t cb_literal;
4763 	boolean_t cb_scripted;
4764 	zpool_list_t *cb_list;
4765 	vdev_cmd_data_list_t *vcdl;
4766 	vdev_cbdata_t cb_vdevs;
4767 } iostat_cbdata_t;
4768 
4769 /*  iostat labels */
4770 typedef struct name_and_columns {
4771 	const char *name;	/* Column name */
4772 	unsigned int columns;	/* Center name to this number of columns */
4773 } name_and_columns_t;
4774 
4775 #define	IOSTAT_MAX_LABELS	15	/* Max number of labels on one line */
4776 
4777 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
4778 {
4779 	[IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
4780 	    {NULL}},
4781 	[IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4782 	    {"asyncq_wait", 2}, {"scrub", 1}, {"trim", 1}, {"rebuild", 1},
4783 	    {NULL}},
4784 	[IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
4785 	    {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
4786 	    {"trimq_write", 2}, {"rebuildq_write", 2}, {NULL}},
4787 	[IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4788 	    {"asyncq_wait", 2}, {NULL}},
4789 	[IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
4790 	    {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
4791 	    {"trim", 2}, {"rebuild", 2}, {NULL}},
4792 };
4793 
4794 /* Shorthand - if "columns" field not set, default to 1 column */
4795 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
4796 {
4797 	[IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
4798 	    {"write"}, {NULL}},
4799 	[IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4800 	    {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {"wait"},
4801 	    {NULL}},
4802 	[IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
4803 	    {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
4804 	    {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
4805 	[IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4806 	    {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {"rebuild"},
4807 	    {NULL}},
4808 	[IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4809 	    {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4810 	    {"ind"}, {"agg"}, {NULL}},
4811 };
4812 
4813 static const char *histo_to_title[] = {
4814 	[IOS_L_HISTO] = "latency",
4815 	[IOS_RQ_HISTO] = "req_size",
4816 };
4817 
4818 /*
4819  * Return the number of labels in a null-terminated name_and_columns_t
4820  * array.
4821  *
4822  */
4823 static unsigned int
4824 label_array_len(const name_and_columns_t *labels)
4825 {
4826 	int i = 0;
4827 
4828 	while (labels[i].name)
4829 		i++;
4830 
4831 	return (i);
4832 }
4833 
4834 /*
4835  * Return the number of strings in a null-terminated string array.
4836  * For example:
4837  *
4838  *     const char foo[] = {"bar", "baz", NULL}
4839  *
4840  * returns 2
4841  */
4842 static uint64_t
4843 str_array_len(const char *array[])
4844 {
4845 	uint64_t i = 0;
4846 	while (array[i])
4847 		i++;
4848 
4849 	return (i);
4850 }
4851 
4852 
4853 /*
4854  * Return a default column width for default/latency/queue columns. This does
4855  * not include histograms, which have their columns autosized.
4856  */
4857 static unsigned int
4858 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
4859 {
4860 	unsigned long column_width = 5; /* Normal niceprint */
4861 	static unsigned long widths[] = {
4862 		/*
4863 		 * Choose some sane default column sizes for printing the
4864 		 * raw numbers.
4865 		 */
4866 		[IOS_DEFAULT] = 15, /* 1PB capacity */
4867 		[IOS_LATENCY] = 10, /* 1B ns = 10sec */
4868 		[IOS_QUEUES] = 6,   /* 1M queue entries */
4869 		[IOS_L_HISTO] = 10, /* 1B ns = 10sec */
4870 		[IOS_RQ_HISTO] = 6, /* 1M queue entries */
4871 	};
4872 
4873 	if (cb->cb_literal)
4874 		column_width = widths[type];
4875 
4876 	return (column_width);
4877 }
4878 
4879 /*
4880  * Print the column labels, i.e:
4881  *
4882  *   capacity     operations     bandwidth
4883  * alloc   free   read  write   read  write  ...
4884  *
4885  * If force_column_width is set, use it for the column width.  If not set, use
4886  * the default column width.
4887  */
4888 static void
4889 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
4890     const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
4891 {
4892 	int i, idx, s;
4893 	int text_start, rw_column_width, spaces_to_end;
4894 	uint64_t flags = cb->cb_flags;
4895 	uint64_t f;
4896 	unsigned int column_width = force_column_width;
4897 
4898 	/* For each bit set in flags */
4899 	for (f = flags; f; f &= ~(1ULL << idx)) {
4900 		idx = lowbit64(f) - 1;
4901 		if (!force_column_width)
4902 			column_width = default_column_width(cb, idx);
4903 		/* Print our top labels centered over "read  write" label. */
4904 		for (i = 0; i < label_array_len(labels[idx]); i++) {
4905 			const char *name = labels[idx][i].name;
4906 			/*
4907 			 * We treat labels[][].columns == 0 as shorthand
4908 			 * for one column.  It makes writing out the label
4909 			 * tables more concise.
4910 			 */
4911 			unsigned int columns = MAX(1, labels[idx][i].columns);
4912 			unsigned int slen = strlen(name);
4913 
4914 			rw_column_width = (column_width * columns) +
4915 			    (2 * (columns - 1));
4916 
4917 			text_start = (int)((rw_column_width) / columns -
4918 			    slen / columns);
4919 			if (text_start < 0)
4920 				text_start = 0;
4921 
4922 			printf("  ");	/* Two spaces between columns */
4923 
4924 			/* Space from beginning of column to label */
4925 			for (s = 0; s < text_start; s++)
4926 				printf(" ");
4927 
4928 			printf("%s", name);
4929 
4930 			/* Print space after label to end of column */
4931 			spaces_to_end = rw_column_width - text_start - slen;
4932 			if (spaces_to_end < 0)
4933 				spaces_to_end = 0;
4934 
4935 			for (s = 0; s < spaces_to_end; s++)
4936 				printf(" ");
4937 		}
4938 	}
4939 }
4940 
4941 
4942 /*
4943  * print_cmd_columns - Print custom column titles from -c
4944  *
4945  * If the user specified the "zpool status|iostat -c" then print their custom
4946  * column titles in the header.  For example, print_cmd_columns() would print
4947  * the "  col1  col2" part of this:
4948  *
4949  * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
4950  * ...
4951  *	      capacity     operations     bandwidth
4952  * pool        alloc   free   read  write   read  write  col1  col2
4953  * ----------  -----  -----  -----  -----  -----  -----  ----  ----
4954  * mypool       269K  1008M      0      0    107    946
4955  *   mirror     269K  1008M      0      0    107    946
4956  *     sdb         -      -      0      0    102    473  val1  val2
4957  *     sdc         -      -      0      0      5    473  val1  val2
4958  * ----------  -----  -----  -----  -----  -----  -----  ----  ----
4959  */
4960 static void
4961 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
4962 {
4963 	int i, j;
4964 	vdev_cmd_data_t *data = &vcdl->data[0];
4965 
4966 	if (vcdl->count == 0 || data == NULL)
4967 		return;
4968 
4969 	/*
4970 	 * Each vdev cmd should have the same column names unless the user did
4971 	 * something weird with their cmd.  Just take the column names from the
4972 	 * first vdev and assume it works for all of them.
4973 	 */
4974 	for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
4975 		printf("  ");
4976 		if (use_dashes) {
4977 			for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
4978 				printf("-");
4979 		} else {
4980 			(void) printf_color(ANSI_BOLD, "%*s",
4981 			    vcdl->uniq_cols_width[i],
4982 			    vcdl->uniq_cols[i]);
4983 		}
4984 	}
4985 }
4986 
4987 
4988 /*
4989  * Utility function to print out a line of dashes like:
4990  *
4991  * 	--------------------------------  -----  -----  -----  -----  -----
4992  *
4993  * ...or a dashed named-row line like:
4994  *
4995  * 	logs                                  -      -      -      -      -
4996  *
4997  * @cb:				iostat data
4998  *
4999  * @force_column_width		If non-zero, use the value as the column width.
5000  * 				Otherwise use the default column widths.
5001  *
5002  * @name:			Print a dashed named-row line starting
5003  * 				with @name.  Otherwise, print a regular
5004  * 				dashed line.
5005  */
5006 static void
5007 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
5008     const char *name)
5009 {
5010 	int i;
5011 	unsigned int namewidth;
5012 	uint64_t flags = cb->cb_flags;
5013 	uint64_t f;
5014 	int idx;
5015 	const name_and_columns_t *labels;
5016 	const char *title;
5017 
5018 
5019 	if (cb->cb_flags & IOS_ANYHISTO_M) {
5020 		title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
5021 	} else if (cb->cb_vdevs.cb_names_count) {
5022 		title = "vdev";
5023 	} else  {
5024 		title = "pool";
5025 	}
5026 
5027 	namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
5028 	    name ? strlen(name) : 0);
5029 
5030 
5031 	if (name) {
5032 		printf("%-*s", namewidth, name);
5033 	} else {
5034 		for (i = 0; i < namewidth; i++)
5035 			(void) printf("-");
5036 	}
5037 
5038 	/* For each bit in flags */
5039 	for (f = flags; f; f &= ~(1ULL << idx)) {
5040 		unsigned int column_width;
5041 		idx = lowbit64(f) - 1;
5042 		if (force_column_width)
5043 			column_width = force_column_width;
5044 		else
5045 			column_width = default_column_width(cb, idx);
5046 
5047 		labels = iostat_bottom_labels[idx];
5048 		for (i = 0; i < label_array_len(labels); i++) {
5049 			if (name)
5050 				printf("  %*s-", column_width - 1, " ");
5051 			else
5052 				printf("  %.*s", column_width,
5053 				    "--------------------");
5054 		}
5055 	}
5056 }
5057 
5058 
5059 static void
5060 print_iostat_separator_impl(iostat_cbdata_t *cb,
5061     unsigned int force_column_width)
5062 {
5063 	print_iostat_dashes(cb, force_column_width, NULL);
5064 }
5065 
5066 static void
5067 print_iostat_separator(iostat_cbdata_t *cb)
5068 {
5069 	print_iostat_separator_impl(cb, 0);
5070 }
5071 
5072 static void
5073 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
5074     const char *histo_vdev_name)
5075 {
5076 	unsigned int namewidth;
5077 	const char *title;
5078 
5079 	color_start(ANSI_BOLD);
5080 
5081 	if (cb->cb_flags & IOS_ANYHISTO_M) {
5082 		title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
5083 	} else if (cb->cb_vdevs.cb_names_count) {
5084 		title = "vdev";
5085 	} else  {
5086 		title = "pool";
5087 	}
5088 
5089 	namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
5090 	    histo_vdev_name ? strlen(histo_vdev_name) : 0);
5091 
5092 	if (histo_vdev_name)
5093 		printf("%-*s", namewidth, histo_vdev_name);
5094 	else
5095 		printf("%*s", namewidth, "");
5096 
5097 
5098 	print_iostat_labels(cb, force_column_width, iostat_top_labels);
5099 	printf("\n");
5100 
5101 	printf("%-*s", namewidth, title);
5102 
5103 	print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
5104 	if (cb->vcdl != NULL)
5105 		print_cmd_columns(cb->vcdl, 0);
5106 
5107 	printf("\n");
5108 
5109 	print_iostat_separator_impl(cb, force_column_width);
5110 
5111 	if (cb->vcdl != NULL)
5112 		print_cmd_columns(cb->vcdl, 1);
5113 
5114 	color_end();
5115 
5116 	printf("\n");
5117 }
5118 
5119 static void
5120 print_iostat_header(iostat_cbdata_t *cb)
5121 {
5122 	print_iostat_header_impl(cb, 0, NULL);
5123 }
5124 
5125 /*
5126  * Prints a size string (i.e. 120M) with the suffix ("M") colored
5127  * by order of magnitude. Uses column_size to add padding.
5128  */
5129 static void
5130 print_stat_color(const char *statbuf, unsigned int column_size)
5131 {
5132 	(void) fputs("  ", stdout);
5133 	size_t len = strlen(statbuf);
5134 	while (len < column_size) {
5135 		(void) fputc(' ', stdout);
5136 		column_size--;
5137 	}
5138 	if (*statbuf == '0') {
5139 		color_start(ANSI_GRAY);
5140 		(void) fputc('0', stdout);
5141 	} else {
5142 		for (; *statbuf; statbuf++) {
5143 			if (*statbuf == 'K') color_start(ANSI_GREEN);
5144 			else if (*statbuf == 'M') color_start(ANSI_YELLOW);
5145 			else if (*statbuf == 'G') color_start(ANSI_RED);
5146 			else if (*statbuf == 'T') color_start(ANSI_BOLD_BLUE);
5147 			else if (*statbuf == 'P') color_start(ANSI_MAGENTA);
5148 			else if (*statbuf == 'E') color_start(ANSI_CYAN);
5149 			(void) fputc(*statbuf, stdout);
5150 			if (--column_size <= 0)
5151 				break;
5152 		}
5153 	}
5154 	color_end();
5155 }
5156 
5157 /*
5158  * Display a single statistic.
5159  */
5160 static void
5161 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
5162     unsigned int column_size, boolean_t scripted)
5163 {
5164 	char buf[64];
5165 
5166 	zfs_nicenum_format(value, buf, sizeof (buf), format);
5167 
5168 	if (scripted)
5169 		printf("\t%s", buf);
5170 	else
5171 		print_stat_color(buf, column_size);
5172 }
5173 
5174 /*
5175  * Calculate the default vdev stats
5176  *
5177  * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
5178  * stats into calcvs.
5179  */
5180 static void
5181 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
5182     vdev_stat_t *calcvs)
5183 {
5184 	int i;
5185 
5186 	memcpy(calcvs, newvs, sizeof (*calcvs));
5187 	for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
5188 		calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
5189 
5190 	for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
5191 		calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
5192 }
5193 
5194 /*
5195  * Internal representation of the extended iostats data.
5196  *
5197  * The extended iostat stats are exported in nvlists as either uint64_t arrays
5198  * or single uint64_t's.  We make both look like arrays to make them easier
5199  * to process.  In order to make single uint64_t's look like arrays, we set
5200  * __data to the stat data, and then set *data = &__data with count = 1.  Then,
5201  * we can just use *data and count.
5202  */
5203 struct stat_array {
5204 	uint64_t *data;
5205 	uint_t count;	/* Number of entries in data[] */
5206 	uint64_t __data; /* Only used when data is a single uint64_t */
5207 };
5208 
5209 static uint64_t
5210 stat_histo_max(struct stat_array *nva, unsigned int len)
5211 {
5212 	uint64_t max = 0;
5213 	int i;
5214 	for (i = 0; i < len; i++)
5215 		max = MAX(max, array64_max(nva[i].data, nva[i].count));
5216 
5217 	return (max);
5218 }
5219 
5220 /*
5221  * Helper function to lookup a uint64_t array or uint64_t value and store its
5222  * data as a stat_array.  If the nvpair is a single uint64_t value, then we make
5223  * it look like a one element array to make it easier to process.
5224  */
5225 static int
5226 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
5227     struct stat_array *nva)
5228 {
5229 	nvpair_t *tmp;
5230 	int ret;
5231 
5232 	verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
5233 	switch (nvpair_type(tmp)) {
5234 	case DATA_TYPE_UINT64_ARRAY:
5235 		ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
5236 		break;
5237 	case DATA_TYPE_UINT64:
5238 		ret = nvpair_value_uint64(tmp, &nva->__data);
5239 		nva->data = &nva->__data;
5240 		nva->count = 1;
5241 		break;
5242 	default:
5243 		/* Not a uint64_t */
5244 		ret = EINVAL;
5245 		break;
5246 	}
5247 
5248 	return (ret);
5249 }
5250 
5251 /*
5252  * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
5253  * subtract them, and return the results in a newly allocated stat_array.
5254  * You must free the returned array after you are done with it with
5255  * free_calc_stats().
5256  *
5257  * Additionally, you can set "oldnv" to NULL if you simply want the newnv
5258  * values.
5259  */
5260 static struct stat_array *
5261 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
5262     nvlist_t *newnv)
5263 {
5264 	nvlist_t *oldnvx = NULL, *newnvx;
5265 	struct stat_array *oldnva, *newnva, *calcnva;
5266 	int i, j;
5267 	unsigned int alloc_size = (sizeof (struct stat_array)) * len;
5268 
5269 	/* Extract our extended stats nvlist from the main list */
5270 	verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5271 	    &newnvx) == 0);
5272 	if (oldnv) {
5273 		verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5274 		    &oldnvx) == 0);
5275 	}
5276 
5277 	newnva = safe_malloc(alloc_size);
5278 	oldnva = safe_malloc(alloc_size);
5279 	calcnva = safe_malloc(alloc_size);
5280 
5281 	for (j = 0; j < len; j++) {
5282 		verify(nvpair64_to_stat_array(newnvx, names[j],
5283 		    &newnva[j]) == 0);
5284 		calcnva[j].count = newnva[j].count;
5285 		alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
5286 		calcnva[j].data = safe_malloc(alloc_size);
5287 		memcpy(calcnva[j].data, newnva[j].data, alloc_size);
5288 
5289 		if (oldnvx) {
5290 			verify(nvpair64_to_stat_array(oldnvx, names[j],
5291 			    &oldnva[j]) == 0);
5292 			for (i = 0; i < oldnva[j].count; i++)
5293 				calcnva[j].data[i] -= oldnva[j].data[i];
5294 		}
5295 	}
5296 	free(newnva);
5297 	free(oldnva);
5298 	return (calcnva);
5299 }
5300 
5301 static void
5302 free_calc_stats(struct stat_array *nva, unsigned int len)
5303 {
5304 	int i;
5305 	for (i = 0; i < len; i++)
5306 		free(nva[i].data);
5307 
5308 	free(nva);
5309 }
5310 
5311 static void
5312 print_iostat_histo(struct stat_array *nva, unsigned int len,
5313     iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
5314     double scale)
5315 {
5316 	int i, j;
5317 	char buf[6];
5318 	uint64_t val;
5319 	enum zfs_nicenum_format format;
5320 	unsigned int buckets;
5321 	unsigned int start_bucket;
5322 
5323 	if (cb->cb_literal)
5324 		format = ZFS_NICENUM_RAW;
5325 	else
5326 		format = ZFS_NICENUM_1024;
5327 
5328 	/* All these histos are the same size, so just use nva[0].count */
5329 	buckets = nva[0].count;
5330 
5331 	if (cb->cb_flags & IOS_RQ_HISTO_M) {
5332 		/* Start at 512 - req size should never be lower than this */
5333 		start_bucket = 9;
5334 	} else {
5335 		start_bucket = 0;
5336 	}
5337 
5338 	for (j = start_bucket; j < buckets; j++) {
5339 		/* Print histogram bucket label */
5340 		if (cb->cb_flags & IOS_L_HISTO_M) {
5341 			/* Ending range of this bucket */
5342 			val = (1UL << (j + 1)) - 1;
5343 			zfs_nicetime(val, buf, sizeof (buf));
5344 		} else {
5345 			/* Request size (starting range of bucket) */
5346 			val = (1UL << j);
5347 			zfs_nicenum(val, buf, sizeof (buf));
5348 		}
5349 
5350 		if (cb->cb_scripted)
5351 			printf("%llu", (u_longlong_t)val);
5352 		else
5353 			printf("%-*s", namewidth, buf);
5354 
5355 		/* Print the values on the line */
5356 		for (i = 0; i < len; i++) {
5357 			print_one_stat(nva[i].data[j] * scale, format,
5358 			    column_width, cb->cb_scripted);
5359 		}
5360 		printf("\n");
5361 	}
5362 }
5363 
5364 static void
5365 print_solid_separator(unsigned int length)
5366 {
5367 	while (length--)
5368 		printf("-");
5369 	printf("\n");
5370 }
5371 
5372 static void
5373 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
5374     nvlist_t *newnv, double scale, const char *name)
5375 {
5376 	unsigned int column_width;
5377 	unsigned int namewidth;
5378 	unsigned int entire_width;
5379 	enum iostat_type type;
5380 	struct stat_array *nva;
5381 	const char **names;
5382 	unsigned int names_len;
5383 
5384 	/* What type of histo are we? */
5385 	type = IOS_HISTO_IDX(cb->cb_flags);
5386 
5387 	/* Get NULL-terminated array of nvlist names for our histo */
5388 	names = vsx_type_to_nvlist[type];
5389 	names_len = str_array_len(names); /* num of names */
5390 
5391 	nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
5392 
5393 	if (cb->cb_literal) {
5394 		column_width = MAX(5,
5395 		    (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
5396 	} else {
5397 		column_width = 5;
5398 	}
5399 
5400 	namewidth = MAX(cb->cb_namewidth,
5401 	    strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
5402 
5403 	/*
5404 	 * Calculate the entire line width of what we're printing.  The
5405 	 * +2 is for the two spaces between columns:
5406 	 */
5407 	/*	 read  write				*/
5408 	/*	-----  -----				*/
5409 	/*	|___|  <---------- column_width		*/
5410 	/*						*/
5411 	/*	|__________|  <--- entire_width		*/
5412 	/*						*/
5413 	entire_width = namewidth + (column_width + 2) *
5414 	    label_array_len(iostat_bottom_labels[type]);
5415 
5416 	if (cb->cb_scripted)
5417 		printf("%s\n", name);
5418 	else
5419 		print_iostat_header_impl(cb, column_width, name);
5420 
5421 	print_iostat_histo(nva, names_len, cb, column_width,
5422 	    namewidth, scale);
5423 
5424 	free_calc_stats(nva, names_len);
5425 	if (!cb->cb_scripted)
5426 		print_solid_separator(entire_width);
5427 }
5428 
5429 /*
5430  * Calculate the average latency of a power-of-two latency histogram
5431  */
5432 static uint64_t
5433 single_histo_average(uint64_t *histo, unsigned int buckets)
5434 {
5435 	int i;
5436 	uint64_t count = 0, total = 0;
5437 
5438 	for (i = 0; i < buckets; i++) {
5439 		/*
5440 		 * Our buckets are power-of-two latency ranges.  Use the
5441 		 * midpoint latency of each bucket to calculate the average.
5442 		 * For example:
5443 		 *
5444 		 * Bucket          Midpoint
5445 		 * 8ns-15ns:       12ns
5446 		 * 16ns-31ns:      24ns
5447 		 * ...
5448 		 */
5449 		if (histo[i] != 0) {
5450 			total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
5451 			count += histo[i];
5452 		}
5453 	}
5454 
5455 	/* Prevent divide by zero */
5456 	return (count == 0 ? 0 : total / count);
5457 }
5458 
5459 static void
5460 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *newnv)
5461 {
5462 	const char *names[] = {
5463 		ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
5464 		ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
5465 		ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
5466 		ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
5467 		ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
5468 		ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
5469 		ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
5470 		ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
5471 		ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
5472 		ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
5473 		ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
5474 		ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
5475 		ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
5476 		ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
5477 	};
5478 
5479 	struct stat_array *nva;
5480 
5481 	unsigned int column_width = default_column_width(cb, IOS_QUEUES);
5482 	enum zfs_nicenum_format format;
5483 
5484 	nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
5485 
5486 	if (cb->cb_literal)
5487 		format = ZFS_NICENUM_RAW;
5488 	else
5489 		format = ZFS_NICENUM_1024;
5490 
5491 	for (int i = 0; i < ARRAY_SIZE(names); i++) {
5492 		uint64_t val = nva[i].data[0];
5493 		print_one_stat(val, format, column_width, cb->cb_scripted);
5494 	}
5495 
5496 	free_calc_stats(nva, ARRAY_SIZE(names));
5497 }
5498 
5499 static void
5500 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
5501     nvlist_t *newnv)
5502 {
5503 	int i;
5504 	uint64_t val;
5505 	const char *names[] = {
5506 		ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
5507 		ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
5508 		ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
5509 		ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
5510 		ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
5511 		ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
5512 		ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
5513 		ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
5514 		ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
5515 		ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
5516 		ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
5517 	};
5518 	struct stat_array *nva;
5519 
5520 	unsigned int column_width = default_column_width(cb, IOS_LATENCY);
5521 	enum zfs_nicenum_format format;
5522 
5523 	nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
5524 
5525 	if (cb->cb_literal)
5526 		format = ZFS_NICENUM_RAWTIME;
5527 	else
5528 		format = ZFS_NICENUM_TIME;
5529 
5530 	/* Print our avg latencies on the line */
5531 	for (i = 0; i < ARRAY_SIZE(names); i++) {
5532 		/* Compute average latency for a latency histo */
5533 		val = single_histo_average(nva[i].data, nva[i].count);
5534 		print_one_stat(val, format, column_width, cb->cb_scripted);
5535 	}
5536 	free_calc_stats(nva, ARRAY_SIZE(names));
5537 }
5538 
5539 /*
5540  * Print default statistics (capacity/operations/bandwidth)
5541  */
5542 static void
5543 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
5544 {
5545 	unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
5546 	enum zfs_nicenum_format format;
5547 	char na;	/* char to print for "not applicable" values */
5548 
5549 	if (cb->cb_literal) {
5550 		format = ZFS_NICENUM_RAW;
5551 		na = '0';
5552 	} else {
5553 		format = ZFS_NICENUM_1024;
5554 		na = '-';
5555 	}
5556 
5557 	/* only toplevel vdevs have capacity stats */
5558 	if (vs->vs_space == 0) {
5559 		if (cb->cb_scripted)
5560 			printf("\t%c\t%c", na, na);
5561 		else
5562 			printf("  %*c  %*c", column_width, na, column_width,
5563 			    na);
5564 	} else {
5565 		print_one_stat(vs->vs_alloc, format, column_width,
5566 		    cb->cb_scripted);
5567 		print_one_stat(vs->vs_space - vs->vs_alloc, format,
5568 		    column_width, cb->cb_scripted);
5569 	}
5570 
5571 	print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
5572 	    format, column_width, cb->cb_scripted);
5573 	print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
5574 	    format, column_width, cb->cb_scripted);
5575 	print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
5576 	    format, column_width, cb->cb_scripted);
5577 	print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
5578 	    format, column_width, cb->cb_scripted);
5579 }
5580 
5581 static const char *const class_name[] = {
5582 	VDEV_ALLOC_BIAS_DEDUP,
5583 	VDEV_ALLOC_BIAS_SPECIAL,
5584 	VDEV_ALLOC_CLASS_LOGS
5585 };
5586 
5587 /*
5588  * Print out all the statistics for the given vdev.  This can either be the
5589  * toplevel configuration, or called recursively.  If 'name' is NULL, then this
5590  * is a verbose output, and we don't want to display the toplevel pool stats.
5591  *
5592  * Returns the number of stat lines printed.
5593  */
5594 static unsigned int
5595 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
5596     nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
5597 {
5598 	nvlist_t **oldchild, **newchild;
5599 	uint_t c, children, oldchildren;
5600 	vdev_stat_t *oldvs, *newvs, *calcvs;
5601 	vdev_stat_t zerovs = { 0 };
5602 	char *vname;
5603 	int i;
5604 	int ret = 0;
5605 	uint64_t tdelta;
5606 	double scale;
5607 
5608 	if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
5609 		return (ret);
5610 
5611 	calcvs = safe_malloc(sizeof (*calcvs));
5612 
5613 	if (oldnv != NULL) {
5614 		verify(nvlist_lookup_uint64_array(oldnv,
5615 		    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
5616 	} else {
5617 		oldvs = &zerovs;
5618 	}
5619 
5620 	/* Do we only want to see a specific vdev? */
5621 	for (i = 0; i < cb->cb_vdevs.cb_names_count; i++) {
5622 		/* Yes we do.  Is this the vdev? */
5623 		if (strcmp(name, cb->cb_vdevs.cb_names[i]) == 0) {
5624 			/*
5625 			 * This is our vdev.  Since it is the only vdev we
5626 			 * will be displaying, make depth = 0 so that it
5627 			 * doesn't get indented.
5628 			 */
5629 			depth = 0;
5630 			break;
5631 		}
5632 	}
5633 
5634 	if (cb->cb_vdevs.cb_names_count && (i == cb->cb_vdevs.cb_names_count)) {
5635 		/* Couldn't match the name */
5636 		goto children;
5637 	}
5638 
5639 
5640 	verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
5641 	    (uint64_t **)&newvs, &c) == 0);
5642 
5643 	/*
5644 	 * Print the vdev name unless it's is a histogram.  Histograms
5645 	 * display the vdev name in the header itself.
5646 	 */
5647 	if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
5648 		if (cb->cb_scripted) {
5649 			printf("%s", name);
5650 		} else {
5651 			if (strlen(name) + depth > cb->cb_namewidth)
5652 				(void) printf("%*s%s", depth, "", name);
5653 			else
5654 				(void) printf("%*s%s%*s", depth, "", name,
5655 				    (int)(cb->cb_namewidth - strlen(name) -
5656 				    depth), "");
5657 		}
5658 	}
5659 
5660 	/* Calculate our scaling factor */
5661 	tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
5662 	if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
5663 		/*
5664 		 * If we specify printing histograms with no time interval, then
5665 		 * print the histogram numbers over the entire lifetime of the
5666 		 * vdev.
5667 		 */
5668 		scale = 1;
5669 	} else {
5670 		if (tdelta == 0)
5671 			scale = 1.0;
5672 		else
5673 			scale = (double)NANOSEC / tdelta;
5674 	}
5675 
5676 	if (cb->cb_flags & IOS_DEFAULT_M) {
5677 		calc_default_iostats(oldvs, newvs, calcvs);
5678 		print_iostat_default(calcvs, cb, scale);
5679 	}
5680 	if (cb->cb_flags & IOS_LATENCY_M)
5681 		print_iostat_latency(cb, oldnv, newnv);
5682 	if (cb->cb_flags & IOS_QUEUES_M)
5683 		print_iostat_queues(cb, newnv);
5684 	if (cb->cb_flags & IOS_ANYHISTO_M) {
5685 		printf("\n");
5686 		print_iostat_histos(cb, oldnv, newnv, scale, name);
5687 	}
5688 
5689 	if (cb->vcdl != NULL) {
5690 		const char *path;
5691 		if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
5692 		    &path) == 0) {
5693 			printf("  ");
5694 			zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
5695 		}
5696 	}
5697 
5698 	if (!(cb->cb_flags & IOS_ANYHISTO_M))
5699 		printf("\n");
5700 
5701 	ret++;
5702 
5703 children:
5704 
5705 	free(calcvs);
5706 
5707 	if (!cb->cb_verbose)
5708 		return (ret);
5709 
5710 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
5711 	    &newchild, &children) != 0)
5712 		return (ret);
5713 
5714 	if (oldnv) {
5715 		if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
5716 		    &oldchild, &oldchildren) != 0)
5717 			return (ret);
5718 
5719 		children = MIN(oldchildren, children);
5720 	}
5721 
5722 	/*
5723 	 * print normal top-level devices
5724 	 */
5725 	for (c = 0; c < children; c++) {
5726 		uint64_t ishole = B_FALSE, islog = B_FALSE;
5727 
5728 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
5729 		    &ishole);
5730 
5731 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
5732 		    &islog);
5733 
5734 		if (ishole || islog)
5735 			continue;
5736 
5737 		if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
5738 			continue;
5739 
5740 		vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5741 		    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5742 		ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
5743 		    newchild[c], cb, depth + 2);
5744 		free(vname);
5745 	}
5746 
5747 	/*
5748 	 * print all other top-level devices
5749 	 */
5750 	for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
5751 		boolean_t printed = B_FALSE;
5752 
5753 		for (c = 0; c < children; c++) {
5754 			uint64_t islog = B_FALSE;
5755 			const char *bias = NULL;
5756 			const char *type = NULL;
5757 
5758 			(void) nvlist_lookup_uint64(newchild[c],
5759 			    ZPOOL_CONFIG_IS_LOG, &islog);
5760 			if (islog) {
5761 				bias = VDEV_ALLOC_CLASS_LOGS;
5762 			} else {
5763 				(void) nvlist_lookup_string(newchild[c],
5764 				    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
5765 				(void) nvlist_lookup_string(newchild[c],
5766 				    ZPOOL_CONFIG_TYPE, &type);
5767 			}
5768 			if (bias == NULL || strcmp(bias, class_name[n]) != 0)
5769 				continue;
5770 			if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
5771 				continue;
5772 
5773 			if (!printed) {
5774 				if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
5775 				    !cb->cb_scripted &&
5776 				    !cb->cb_vdevs.cb_names) {
5777 					print_iostat_dashes(cb, 0,
5778 					    class_name[n]);
5779 				}
5780 				printf("\n");
5781 				printed = B_TRUE;
5782 			}
5783 
5784 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5785 			    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5786 			ret += print_vdev_stats(zhp, vname, oldnv ?
5787 			    oldchild[c] : NULL, newchild[c], cb, depth + 2);
5788 			free(vname);
5789 		}
5790 	}
5791 
5792 	/*
5793 	 * Include level 2 ARC devices in iostat output
5794 	 */
5795 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
5796 	    &newchild, &children) != 0)
5797 		return (ret);
5798 
5799 	if (oldnv) {
5800 		if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
5801 		    &oldchild, &oldchildren) != 0)
5802 			return (ret);
5803 
5804 		children = MIN(oldchildren, children);
5805 	}
5806 
5807 	if (children > 0) {
5808 		if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
5809 		    !cb->cb_vdevs.cb_names) {
5810 			print_iostat_dashes(cb, 0, "cache");
5811 		}
5812 		printf("\n");
5813 
5814 		for (c = 0; c < children; c++) {
5815 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5816 			    cb->cb_vdevs.cb_name_flags);
5817 			ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
5818 			    : NULL, newchild[c], cb, depth + 2);
5819 			free(vname);
5820 		}
5821 	}
5822 
5823 	return (ret);
5824 }
5825 
5826 /*
5827  * Callback to print out the iostats for the given pool.
5828  */
5829 static int
5830 print_iostat(zpool_handle_t *zhp, void *data)
5831 {
5832 	iostat_cbdata_t *cb = data;
5833 	nvlist_t *oldconfig, *newconfig;
5834 	nvlist_t *oldnvroot, *newnvroot;
5835 	int ret;
5836 
5837 	newconfig = zpool_get_config(zhp, &oldconfig);
5838 
5839 	if (cb->cb_iteration == 1)
5840 		oldconfig = NULL;
5841 
5842 	verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
5843 	    &newnvroot) == 0);
5844 
5845 	if (oldconfig == NULL)
5846 		oldnvroot = NULL;
5847 	else
5848 		verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
5849 		    &oldnvroot) == 0);
5850 
5851 	ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
5852 	    cb, 0);
5853 	if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
5854 	    !cb->cb_scripted && cb->cb_verbose &&
5855 	    !cb->cb_vdevs.cb_names_count) {
5856 		print_iostat_separator(cb);
5857 		if (cb->vcdl != NULL) {
5858 			print_cmd_columns(cb->vcdl, 1);
5859 		}
5860 		printf("\n");
5861 	}
5862 
5863 	return (ret);
5864 }
5865 
5866 static int
5867 get_columns(void)
5868 {
5869 	struct winsize ws;
5870 	int columns = 80;
5871 	int error;
5872 
5873 	if (isatty(STDOUT_FILENO)) {
5874 		error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
5875 		if (error == 0 && ws.ws_col > 0)
5876 			columns = ws.ws_col;
5877 	} else {
5878 		columns = 999;
5879 	}
5880 
5881 	return (columns);
5882 }
5883 
5884 /*
5885  * Return the required length of the pool/vdev name column.  The minimum
5886  * allowed width and output formatting flags must be provided.
5887  */
5888 static int
5889 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
5890 {
5891 	nvlist_t *config, *nvroot;
5892 	int width = min_width;
5893 
5894 	if ((config = zpool_get_config(zhp, NULL)) != NULL) {
5895 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5896 		    &nvroot) == 0);
5897 		size_t poolname_len = strlen(zpool_get_name(zhp));
5898 		if (verbose == B_FALSE) {
5899 			width = MAX(poolname_len, min_width);
5900 		} else {
5901 			width = MAX(poolname_len,
5902 			    max_width(zhp, nvroot, 0, min_width, flags));
5903 		}
5904 	}
5905 
5906 	return (width);
5907 }
5908 
5909 /*
5910  * Parse the input string, get the 'interval' and 'count' value if there is one.
5911  */
5912 static void
5913 get_interval_count(int *argcp, char **argv, float *iv,
5914     unsigned long *cnt)
5915 {
5916 	float interval = 0;
5917 	unsigned long count = 0;
5918 	int argc = *argcp;
5919 
5920 	/*
5921 	 * Determine if the last argument is an integer or a pool name
5922 	 */
5923 	if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5924 		char *end;
5925 
5926 		errno = 0;
5927 		interval = strtof(argv[argc - 1], &end);
5928 
5929 		if (*end == '\0' && errno == 0) {
5930 			if (interval == 0) {
5931 				(void) fprintf(stderr, gettext(
5932 				    "interval cannot be zero\n"));
5933 				usage(B_FALSE);
5934 			}
5935 			/*
5936 			 * Ignore the last parameter
5937 			 */
5938 			argc--;
5939 		} else {
5940 			/*
5941 			 * If this is not a valid number, just plow on.  The
5942 			 * user will get a more informative error message later
5943 			 * on.
5944 			 */
5945 			interval = 0;
5946 		}
5947 	}
5948 
5949 	/*
5950 	 * If the last argument is also an integer, then we have both a count
5951 	 * and an interval.
5952 	 */
5953 	if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5954 		char *end;
5955 
5956 		errno = 0;
5957 		count = interval;
5958 		interval = strtof(argv[argc - 1], &end);
5959 
5960 		if (*end == '\0' && errno == 0) {
5961 			if (interval == 0) {
5962 				(void) fprintf(stderr, gettext(
5963 				    "interval cannot be zero\n"));
5964 				usage(B_FALSE);
5965 			}
5966 
5967 			/*
5968 			 * Ignore the last parameter
5969 			 */
5970 			argc--;
5971 		} else {
5972 			interval = 0;
5973 		}
5974 	}
5975 
5976 	*iv = interval;
5977 	*cnt = count;
5978 	*argcp = argc;
5979 }
5980 
5981 static void
5982 get_timestamp_arg(char c)
5983 {
5984 	if (c == 'u')
5985 		timestamp_fmt = UDATE;
5986 	else if (c == 'd')
5987 		timestamp_fmt = DDATE;
5988 	else
5989 		usage(B_FALSE);
5990 }
5991 
5992 /*
5993  * Return stat flags that are supported by all pools by both the module and
5994  * zpool iostat.  "*data" should be initialized to all 0xFFs before running.
5995  * It will get ANDed down until only the flags that are supported on all pools
5996  * remain.
5997  */
5998 static int
5999 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
6000 {
6001 	uint64_t *mask = data;
6002 	nvlist_t *config, *nvroot, *nvx;
6003 	uint64_t flags = 0;
6004 	int i, j;
6005 
6006 	config = zpool_get_config(zhp, NULL);
6007 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
6008 	    &nvroot) == 0);
6009 
6010 	/* Default stats are always supported, but for completeness.. */
6011 	if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
6012 		flags |= IOS_DEFAULT_M;
6013 
6014 	/* Get our extended stats nvlist from the main list */
6015 	if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
6016 	    &nvx) != 0) {
6017 		/*
6018 		 * No extended stats; they're probably running an older
6019 		 * module.  No big deal, we support that too.
6020 		 */
6021 		goto end;
6022 	}
6023 
6024 	/* For each extended stat, make sure all its nvpairs are supported */
6025 	for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
6026 		if (!vsx_type_to_nvlist[j][0])
6027 			continue;
6028 
6029 		/* Start off by assuming the flag is supported, then check */
6030 		flags |= (1ULL << j);
6031 		for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
6032 			if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
6033 				/* flag isn't supported */
6034 				flags = flags & ~(1ULL  << j);
6035 				break;
6036 			}
6037 		}
6038 	}
6039 end:
6040 	*mask = *mask & flags;
6041 	return (0);
6042 }
6043 
6044 /*
6045  * Return a bitmask of stats that are supported on all pools by both the module
6046  * and zpool iostat.
6047  */
6048 static uint64_t
6049 get_stat_flags(zpool_list_t *list)
6050 {
6051 	uint64_t mask = -1;
6052 
6053 	/*
6054 	 * get_stat_flags_cb() will lop off bits from "mask" until only the
6055 	 * flags that are supported on all pools remain.
6056 	 */
6057 	(void) pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
6058 	return (mask);
6059 }
6060 
6061 /*
6062  * Return 1 if cb_data->cb_names[0] is this vdev's name, 0 otherwise.
6063  */
6064 static int
6065 is_vdev_cb(void *zhp_data, nvlist_t *nv, void *cb_data)
6066 {
6067 	uint64_t guid;
6068 	vdev_cbdata_t *cb = cb_data;
6069 	zpool_handle_t *zhp = zhp_data;
6070 
6071 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
6072 		return (0);
6073 
6074 	return (guid == zpool_vdev_path_to_guid(zhp, cb->cb_names[0]));
6075 }
6076 
6077 /*
6078  * Returns 1 if cb_data->cb_names[0] is a vdev name, 0 otherwise.
6079  */
6080 static int
6081 is_vdev(zpool_handle_t *zhp, void *cb_data)
6082 {
6083 	return (for_each_vdev(zhp, is_vdev_cb, cb_data));
6084 }
6085 
6086 /*
6087  * Check if vdevs are in a pool
6088  *
6089  * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
6090  * return 0.  If pool_name is NULL, then search all pools.
6091  */
6092 static int
6093 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
6094     vdev_cbdata_t *cb)
6095 {
6096 	char **tmp_name;
6097 	int ret = 0;
6098 	int i;
6099 	int pool_count = 0;
6100 
6101 	if ((argc == 0) || !*argv)
6102 		return (0);
6103 
6104 	if (pool_name)
6105 		pool_count = 1;
6106 
6107 	/* Temporarily hijack cb_names for a second... */
6108 	tmp_name = cb->cb_names;
6109 
6110 	/* Go though our list of prospective vdev names */
6111 	for (i = 0; i < argc; i++) {
6112 		cb->cb_names = argv + i;
6113 
6114 		/* Is this name a vdev in our pools? */
6115 		ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
6116 		    ZFS_TYPE_POOL, B_FALSE, is_vdev, cb);
6117 		if (!ret) {
6118 			/* No match */
6119 			break;
6120 		}
6121 	}
6122 
6123 	cb->cb_names = tmp_name;
6124 
6125 	return (ret);
6126 }
6127 
6128 static int
6129 is_pool_cb(zpool_handle_t *zhp, void *data)
6130 {
6131 	char *name = data;
6132 	if (strcmp(name, zpool_get_name(zhp)) == 0)
6133 		return (1);
6134 
6135 	return (0);
6136 }
6137 
6138 /*
6139  * Do we have a pool named *name?  If so, return 1, otherwise 0.
6140  */
6141 static int
6142 is_pool(char *name)
6143 {
6144 	return (for_each_pool(0, NULL, B_TRUE, NULL, ZFS_TYPE_POOL, B_FALSE,
6145 	    is_pool_cb, name));
6146 }
6147 
6148 /* Are all our argv[] strings pool names?  If so return 1, 0 otherwise. */
6149 static int
6150 are_all_pools(int argc, char **argv)
6151 {
6152 	if ((argc == 0) || !*argv)
6153 		return (0);
6154 
6155 	while (--argc >= 0)
6156 		if (!is_pool(argv[argc]))
6157 			return (0);
6158 
6159 	return (1);
6160 }
6161 
6162 /*
6163  * Helper function to print out vdev/pool names we can't resolve.  Used for an
6164  * error message.
6165  */
6166 static void
6167 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
6168     vdev_cbdata_t *cb)
6169 {
6170 	int i;
6171 	char *name;
6172 	char *str;
6173 	for (i = 0; i < argc; i++) {
6174 		name = argv[i];
6175 
6176 		if (is_pool(name))
6177 			str = gettext("pool");
6178 		else if (are_vdevs_in_pool(1, &name, pool_name, cb))
6179 			str = gettext("vdev in this pool");
6180 		else if (are_vdevs_in_pool(1, &name, NULL, cb))
6181 			str = gettext("vdev in another pool");
6182 		else
6183 			str = gettext("unknown");
6184 
6185 		fprintf(stderr, "\t%s (%s)\n", name, str);
6186 	}
6187 }
6188 
6189 /*
6190  * Same as get_interval_count(), but with additional checks to not misinterpret
6191  * guids as interval/count values.  Assumes VDEV_NAME_GUID is set in
6192  * cb.cb_vdevs.cb_name_flags.
6193  */
6194 static void
6195 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
6196     unsigned long *count, iostat_cbdata_t *cb)
6197 {
6198 	int argc_for_interval = 0;
6199 
6200 	/* Is the last arg an interval value?  Or a guid? */
6201 	if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL,
6202 	    &cb->cb_vdevs)) {
6203 		/*
6204 		 * The last arg is not a guid, so it's probably an
6205 		 * interval value.
6206 		 */
6207 		argc_for_interval++;
6208 
6209 		if (*argc >= 2 &&
6210 		    !are_vdevs_in_pool(1, &argv[*argc - 2], NULL,
6211 		    &cb->cb_vdevs)) {
6212 			/*
6213 			 * The 2nd to last arg is not a guid, so it's probably
6214 			 * an interval value.
6215 			 */
6216 			argc_for_interval++;
6217 		}
6218 	}
6219 
6220 	/* Point to our list of possible intervals */
6221 	char **tmpargv = &argv[*argc - argc_for_interval];
6222 
6223 	*argc = *argc - argc_for_interval;
6224 	get_interval_count(&argc_for_interval, tmpargv,
6225 	    interval, count);
6226 }
6227 
6228 /*
6229  * Terminal height, in rows. Returns -1 if stdout is not connected to a TTY or
6230  * if we were unable to determine its size.
6231  */
6232 static int
6233 terminal_height(void)
6234 {
6235 	struct winsize win;
6236 
6237 	if (isatty(STDOUT_FILENO) == 0)
6238 		return (-1);
6239 
6240 	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_row > 0)
6241 		return (win.ws_row);
6242 
6243 	return (-1);
6244 }
6245 
6246 /*
6247  * Run one of the zpool status/iostat -c scripts with the help (-h) option and
6248  * print the result.
6249  *
6250  * name:	Short name of the script ('iostat').
6251  * path:	Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
6252  */
6253 static void
6254 print_zpool_script_help(char *name, char *path)
6255 {
6256 	char *argv[] = {path, (char *)"-h", NULL};
6257 	char **lines = NULL;
6258 	int lines_cnt = 0;
6259 	int rc;
6260 
6261 	rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
6262 	    &lines_cnt);
6263 	if (rc != 0 || lines == NULL || lines_cnt <= 0) {
6264 		if (lines != NULL)
6265 			libzfs_free_str_array(lines, lines_cnt);
6266 		return;
6267 	}
6268 
6269 	for (int i = 0; i < lines_cnt; i++)
6270 		if (!is_blank_str(lines[i]))
6271 			printf("  %-14s  %s\n", name, lines[i]);
6272 
6273 	libzfs_free_str_array(lines, lines_cnt);
6274 }
6275 
6276 /*
6277  * Go though the zpool status/iostat -c scripts in the user's path, run their
6278  * help option (-h), and print out the results.
6279  */
6280 static void
6281 print_zpool_dir_scripts(char *dirpath)
6282 {
6283 	DIR *dir;
6284 	struct dirent *ent;
6285 	char fullpath[MAXPATHLEN];
6286 	struct stat dir_stat;
6287 
6288 	if ((dir = opendir(dirpath)) != NULL) {
6289 		/* print all the files and directories within directory */
6290 		while ((ent = readdir(dir)) != NULL) {
6291 			if (snprintf(fullpath, sizeof (fullpath), "%s/%s",
6292 			    dirpath, ent->d_name) >= sizeof (fullpath)) {
6293 				(void) fprintf(stderr,
6294 				    gettext("internal error: "
6295 				    "ZPOOL_SCRIPTS_PATH too large.\n"));
6296 				exit(1);
6297 			}
6298 
6299 			/* Print the scripts */
6300 			if (stat(fullpath, &dir_stat) == 0)
6301 				if (dir_stat.st_mode & S_IXUSR &&
6302 				    S_ISREG(dir_stat.st_mode))
6303 					print_zpool_script_help(ent->d_name,
6304 					    fullpath);
6305 		}
6306 		(void) closedir(dir);
6307 	}
6308 }
6309 
6310 /*
6311  * Print out help text for all zpool status/iostat -c scripts.
6312  */
6313 static void
6314 print_zpool_script_list(const char *subcommand)
6315 {
6316 	char *dir, *sp, *tmp;
6317 
6318 	printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
6319 
6320 	sp = zpool_get_cmd_search_path();
6321 	if (sp == NULL)
6322 		return;
6323 
6324 	for (dir = strtok_r(sp, ":", &tmp);
6325 	    dir != NULL;
6326 	    dir = strtok_r(NULL, ":", &tmp))
6327 		print_zpool_dir_scripts(dir);
6328 
6329 	free(sp);
6330 }
6331 
6332 /*
6333  * Set the minimum pool/vdev name column width.  The width must be at least 10,
6334  * but may be as large as the column width - 42 so it still fits on one line.
6335  * NOTE: 42 is the width of the default capacity/operations/bandwidth output
6336  */
6337 static int
6338 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
6339 {
6340 	iostat_cbdata_t *cb = data;
6341 	int width, available_width;
6342 
6343 	/*
6344 	 * get_namewidth() returns the maximum width of any name in that column
6345 	 * for any pool/vdev/device line that will be output.
6346 	 */
6347 	width = get_namewidth(zhp, cb->cb_namewidth,
6348 	    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
6349 
6350 	/*
6351 	 * The width we are calculating is the width of the header and also the
6352 	 * padding width for names that are less than maximum width.  The stats
6353 	 * take up 42 characters, so the width available for names is:
6354 	 */
6355 	available_width = get_columns() - 42;
6356 
6357 	/*
6358 	 * If the maximum width fits on a screen, then great!  Make everything
6359 	 * line up by justifying all lines to the same width.  If that max
6360 	 * width is larger than what's available, the name plus stats won't fit
6361 	 * on one line, and justifying to that width would cause every line to
6362 	 * wrap on the screen.  We only want lines with long names to wrap.
6363 	 * Limit the padding to what won't wrap.
6364 	 */
6365 	if (width > available_width)
6366 		width = available_width;
6367 
6368 	/*
6369 	 * And regardless of whatever the screen width is (get_columns can
6370 	 * return 0 if the width is not known or less than 42 for a narrow
6371 	 * terminal) have the width be a minimum of 10.
6372 	 */
6373 	if (width < 10)
6374 		width = 10;
6375 
6376 	/* Save the calculated width */
6377 	cb->cb_namewidth = width;
6378 
6379 	return (0);
6380 }
6381 
6382 /*
6383  * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
6384  *              [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
6385  *              [interval [count]]
6386  *
6387  *	-c CMD  For each vdev, run command CMD
6388  *	-g	Display guid for individual vdev name.
6389  *	-L	Follow links when resolving vdev path name.
6390  *	-P	Display full path for vdev name.
6391  *	-v	Display statistics for individual vdevs
6392  *	-h	Display help
6393  *	-p	Display values in parsable (exact) format.
6394  *	-H	Scripted mode.  Don't display headers, and separate properties
6395  *		by a single tab.
6396  *	-l	Display average latency
6397  *	-q	Display queue depths
6398  *	-w	Display latency histograms
6399  *	-r	Display request size histogram
6400  *	-T	Display a timestamp in date(1) or Unix format
6401  *	-n	Only print headers once
6402  *
6403  * This command can be tricky because we want to be able to deal with pool
6404  * creation/destruction as well as vdev configuration changes.  The bulk of this
6405  * processing is handled by the pool_list_* routines in zpool_iter.c.  We rely
6406  * on pool_list_refresh() to detect the addition and removal of pools.
6407  * Configuration changes are all handled within libzfs.
6408  */
6409 int
6410 zpool_do_iostat(int argc, char **argv)
6411 {
6412 	int c;
6413 	int ret;
6414 	float interval = 0;
6415 	unsigned long count = 0;
6416 	zpool_list_t *list;
6417 	boolean_t verbose = B_FALSE;
6418 	boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
6419 	boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
6420 	boolean_t omit_since_boot = B_FALSE;
6421 	boolean_t guid = B_FALSE;
6422 	boolean_t follow_links = B_FALSE;
6423 	boolean_t full_name = B_FALSE;
6424 	boolean_t headers_once = B_FALSE;
6425 	iostat_cbdata_t cb = { 0 };
6426 	char *cmd = NULL;
6427 
6428 	/* Used for printing error message */
6429 	const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
6430 	    [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
6431 
6432 	uint64_t unsupported_flags;
6433 
6434 	/* check options */
6435 	while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwnH")) != -1) {
6436 		switch (c) {
6437 		case 'c':
6438 			if (cmd != NULL) {
6439 				fprintf(stderr,
6440 				    gettext("Can't set -c flag twice\n"));
6441 				exit(1);
6442 			}
6443 
6444 			if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
6445 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
6446 				fprintf(stderr, gettext(
6447 				    "Can't run -c, disabled by "
6448 				    "ZPOOL_SCRIPTS_ENABLED.\n"));
6449 				exit(1);
6450 			}
6451 
6452 			if ((getuid() <= 0 || geteuid() <= 0) &&
6453 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
6454 				fprintf(stderr, gettext(
6455 				    "Can't run -c with root privileges "
6456 				    "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
6457 				exit(1);
6458 			}
6459 			cmd = optarg;
6460 			verbose = B_TRUE;
6461 			break;
6462 		case 'g':
6463 			guid = B_TRUE;
6464 			break;
6465 		case 'L':
6466 			follow_links = B_TRUE;
6467 			break;
6468 		case 'P':
6469 			full_name = B_TRUE;
6470 			break;
6471 		case 'T':
6472 			get_timestamp_arg(*optarg);
6473 			break;
6474 		case 'v':
6475 			verbose = B_TRUE;
6476 			break;
6477 		case 'p':
6478 			parsable = B_TRUE;
6479 			break;
6480 		case 'l':
6481 			latency = B_TRUE;
6482 			break;
6483 		case 'q':
6484 			queues = B_TRUE;
6485 			break;
6486 		case 'H':
6487 			scripted = B_TRUE;
6488 			break;
6489 		case 'w':
6490 			l_histo = B_TRUE;
6491 			break;
6492 		case 'r':
6493 			rq_histo = B_TRUE;
6494 			break;
6495 		case 'y':
6496 			omit_since_boot = B_TRUE;
6497 			break;
6498 		case 'n':
6499 			headers_once = B_TRUE;
6500 			break;
6501 		case 'h':
6502 			usage(B_FALSE);
6503 			break;
6504 		case '?':
6505 			if (optopt == 'c') {
6506 				print_zpool_script_list("iostat");
6507 				exit(0);
6508 			} else {
6509 				fprintf(stderr,
6510 				    gettext("invalid option '%c'\n"), optopt);
6511 			}
6512 			usage(B_FALSE);
6513 		}
6514 	}
6515 
6516 	argc -= optind;
6517 	argv += optind;
6518 
6519 	cb.cb_literal = parsable;
6520 	cb.cb_scripted = scripted;
6521 
6522 	if (guid)
6523 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_GUID;
6524 	if (follow_links)
6525 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6526 	if (full_name)
6527 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_PATH;
6528 	cb.cb_iteration = 0;
6529 	cb.cb_namewidth = 0;
6530 	cb.cb_verbose = verbose;
6531 
6532 	/* Get our interval and count values (if any) */
6533 	if (guid) {
6534 		get_interval_count_filter_guids(&argc, argv, &interval,
6535 		    &count, &cb);
6536 	} else {
6537 		get_interval_count(&argc, argv, &interval, &count);
6538 	}
6539 
6540 	if (argc == 0) {
6541 		/* No args, so just print the defaults. */
6542 	} else if (are_all_pools(argc, argv)) {
6543 		/* All the args are pool names */
6544 	} else if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
6545 		/* All the args are vdevs */
6546 		cb.cb_vdevs.cb_names = argv;
6547 		cb.cb_vdevs.cb_names_count = argc;
6548 		argc = 0; /* No pools to process */
6549 	} else if (are_all_pools(1, argv)) {
6550 		/* The first arg is a pool name */
6551 		if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
6552 		    &cb.cb_vdevs)) {
6553 			/* ...and the rest are vdev names */
6554 			cb.cb_vdevs.cb_names = argv + 1;
6555 			cb.cb_vdevs.cb_names_count = argc - 1;
6556 			argc = 1; /* One pool to process */
6557 		} else {
6558 			fprintf(stderr, gettext("Expected either a list of "));
6559 			fprintf(stderr, gettext("pools, or list of vdevs in"));
6560 			fprintf(stderr, " \"%s\", ", argv[0]);
6561 			fprintf(stderr, gettext("but got:\n"));
6562 			error_list_unresolved_vdevs(argc - 1, argv + 1,
6563 			    argv[0], &cb.cb_vdevs);
6564 			fprintf(stderr, "\n");
6565 			usage(B_FALSE);
6566 		}
6567 	} else {
6568 		/*
6569 		 * The args don't make sense. The first arg isn't a pool name,
6570 		 * nor are all the args vdevs.
6571 		 */
6572 		fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
6573 		fprintf(stderr, "\n");
6574 		return (1);
6575 	}
6576 
6577 	if (cb.cb_vdevs.cb_names_count != 0) {
6578 		/*
6579 		 * If user specified vdevs, it implies verbose.
6580 		 */
6581 		cb.cb_verbose = B_TRUE;
6582 	}
6583 
6584 	/*
6585 	 * Construct the list of all interesting pools.
6586 	 */
6587 	ret = 0;
6588 	if ((list = pool_list_get(argc, argv, NULL, ZFS_TYPE_POOL, parsable,
6589 	    &ret)) == NULL)
6590 		return (1);
6591 
6592 	if (pool_list_count(list) == 0 && argc != 0) {
6593 		pool_list_free(list);
6594 		return (1);
6595 	}
6596 
6597 	if (pool_list_count(list) == 0 && interval == 0) {
6598 		pool_list_free(list);
6599 		(void) fprintf(stderr, gettext("no pools available\n"));
6600 		return (1);
6601 	}
6602 
6603 	if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
6604 		pool_list_free(list);
6605 		(void) fprintf(stderr,
6606 		    gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
6607 		usage(B_FALSE);
6608 	}
6609 
6610 	if (l_histo && rq_histo) {
6611 		pool_list_free(list);
6612 		(void) fprintf(stderr,
6613 		    gettext("Only one of [-r|-w] can be passed at a time\n"));
6614 		usage(B_FALSE);
6615 	}
6616 
6617 	/*
6618 	 * Enter the main iostat loop.
6619 	 */
6620 	cb.cb_list = list;
6621 
6622 	if (l_histo) {
6623 		/*
6624 		 * Histograms tables look out of place when you try to display
6625 		 * them with the other stats, so make a rule that you can only
6626 		 * print histograms by themselves.
6627 		 */
6628 		cb.cb_flags = IOS_L_HISTO_M;
6629 	} else if (rq_histo) {
6630 		cb.cb_flags = IOS_RQ_HISTO_M;
6631 	} else {
6632 		cb.cb_flags = IOS_DEFAULT_M;
6633 		if (latency)
6634 			cb.cb_flags |= IOS_LATENCY_M;
6635 		if (queues)
6636 			cb.cb_flags |= IOS_QUEUES_M;
6637 	}
6638 
6639 	/*
6640 	 * See if the module supports all the stats we want to display.
6641 	 */
6642 	unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
6643 	if (unsupported_flags) {
6644 		uint64_t f;
6645 		int idx;
6646 		fprintf(stderr,
6647 		    gettext("The loaded zfs module doesn't support:"));
6648 
6649 		/* for each bit set in unsupported_flags */
6650 		for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
6651 			idx = lowbit64(f) - 1;
6652 			fprintf(stderr, " -%c", flag_to_arg[idx]);
6653 		}
6654 
6655 		fprintf(stderr, ".  Try running a newer module.\n");
6656 		pool_list_free(list);
6657 
6658 		return (1);
6659 	}
6660 
6661 	int last_npools = 0;
6662 	for (;;) {
6663 		/*
6664 		 * Refresh all pools in list, adding or removing pools as
6665 		 * necessary.
6666 		 */
6667 		int npools = pool_list_refresh(list);
6668 		if (npools == 0) {
6669 			(void) fprintf(stderr, gettext("no pools available\n"));
6670 		} else {
6671 			/*
6672 			 * If the list of pools has changed since last time
6673 			 * around, reset the iteration count to force the
6674 			 * header to be redisplayed.
6675 			 */
6676 			if (last_npools != npools)
6677 				cb.cb_iteration = 0;
6678 
6679 			/*
6680 			 * If this is the first iteration and -y was supplied
6681 			 * we skip any printing.
6682 			 */
6683 			boolean_t skip = (omit_since_boot &&
6684 			    cb.cb_iteration == 0);
6685 
6686 			/*
6687 			 * Iterate over all pools to determine the maximum width
6688 			 * for the pool / device name column across all pools.
6689 			 */
6690 			cb.cb_namewidth = 0;
6691 			(void) pool_list_iter(list, B_FALSE,
6692 			    get_namewidth_iostat, &cb);
6693 
6694 			if (timestamp_fmt != NODATE)
6695 				print_timestamp(timestamp_fmt);
6696 
6697 			if (cmd != NULL && cb.cb_verbose &&
6698 			    !(cb.cb_flags & IOS_ANYHISTO_M)) {
6699 				cb.vcdl = all_pools_for_each_vdev_run(argc,
6700 				    argv, cmd, g_zfs, cb.cb_vdevs.cb_names,
6701 				    cb.cb_vdevs.cb_names_count,
6702 				    cb.cb_vdevs.cb_name_flags);
6703 			} else {
6704 				cb.vcdl = NULL;
6705 			}
6706 
6707 
6708 			/*
6709 			 * Check terminal size so we can print headers
6710 			 * even when terminal window has its height
6711 			 * changed.
6712 			 */
6713 			int winheight = terminal_height();
6714 			/*
6715 			 * Are we connected to TTY? If not, headers_once
6716 			 * should be true, to avoid breaking scripts.
6717 			 */
6718 			if (winheight < 0)
6719 				headers_once = B_TRUE;
6720 
6721 			/*
6722 			 * If it's the first time and we're not skipping it,
6723 			 * or either skip or verbose mode, print the header.
6724 			 *
6725 			 * The histogram code explicitly prints its header on
6726 			 * every vdev, so skip this for histograms.
6727 			 */
6728 			if (((++cb.cb_iteration == 1 && !skip) ||
6729 			    (skip != verbose) ||
6730 			    (!headers_once &&
6731 			    (cb.cb_iteration % winheight) == 0)) &&
6732 			    (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
6733 			    !cb.cb_scripted)
6734 				print_iostat_header(&cb);
6735 
6736 			if (skip) {
6737 				(void) fflush(stdout);
6738 				(void) fsleep(interval);
6739 				last_npools = npools;
6740 				continue;
6741 			}
6742 
6743 			(void) pool_list_iter(list, B_FALSE, print_iostat, &cb);
6744 
6745 			/*
6746 			 * If there's more than one pool, and we're not in
6747 			 * verbose mode (which prints a separator for us),
6748 			 * then print a separator.
6749 			 *
6750 			 * In addition, if we're printing specific vdevs then
6751 			 * we also want an ending separator.
6752 			 */
6753 			if (((npools > 1 && !verbose &&
6754 			    !(cb.cb_flags & IOS_ANYHISTO_M)) ||
6755 			    (!(cb.cb_flags & IOS_ANYHISTO_M) &&
6756 			    cb.cb_vdevs.cb_names_count)) &&
6757 			    !cb.cb_scripted) {
6758 				print_iostat_separator(&cb);
6759 				if (cb.vcdl != NULL)
6760 					print_cmd_columns(cb.vcdl, 1);
6761 				printf("\n");
6762 			}
6763 
6764 			if (cb.vcdl != NULL)
6765 				free_vdev_cmd_data_list(cb.vcdl);
6766 
6767 		}
6768 
6769 		if (interval == 0)
6770 			break;
6771 
6772 		if (count != 0 && --count == 0)
6773 			break;
6774 
6775 		(void) fflush(stdout);
6776 		(void) fsleep(interval);
6777 
6778 		last_npools = npools;
6779 	}
6780 
6781 	pool_list_free(list);
6782 
6783 	return (ret);
6784 }
6785 
6786 typedef struct list_cbdata {
6787 	boolean_t	cb_verbose;
6788 	int		cb_name_flags;
6789 	int		cb_namewidth;
6790 	boolean_t	cb_json;
6791 	boolean_t	cb_scripted;
6792 	zprop_list_t	*cb_proplist;
6793 	boolean_t	cb_literal;
6794 	nvlist_t	*cb_jsobj;
6795 	boolean_t	cb_json_as_int;
6796 	boolean_t	cb_json_pool_key_guid;
6797 } list_cbdata_t;
6798 
6799 
6800 /*
6801  * Given a list of columns to display, print an appropriate line. If
6802  * `vdev_name` is not NULL, we print `vdev_name` followed by a line of dashes.
6803  * If `vdev_name` is NULL, we print a line of the headers.
6804  */
6805 static void
6806 print_line(list_cbdata_t *cb, const char *vdev_name)
6807 {
6808 	zprop_list_t *pl = cb->cb_proplist;
6809 	char headerbuf[ZPOOL_MAXPROPLEN];
6810 	const char *header;
6811 	boolean_t first = B_TRUE;
6812 	boolean_t right_justify;
6813 	size_t width = 0;
6814 
6815 	boolean_t print_header = (vdev_name == NULL);
6816 
6817 	for (; pl != NULL; pl = pl->pl_next) {
6818 		width = pl->pl_width;
6819 		if (first && cb->cb_verbose) {
6820 			/*
6821 			 * Reset the width to accommodate the verbose listing
6822 			 * of devices.
6823 			 */
6824 			width = cb->cb_namewidth;
6825 		}
6826 
6827 		if (!first)
6828 			(void) fputs("  ", stdout);
6829 
6830 		if (print_header) {
6831 			right_justify = B_FALSE;
6832 			if (pl->pl_prop != ZPROP_USERPROP) {
6833 				header = zpool_prop_column_name(pl->pl_prop);
6834 				right_justify = zpool_prop_align_right(
6835 				    pl->pl_prop);
6836 			} else {
6837 				int i;
6838 
6839 				for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
6840 					headerbuf[i] = toupper(
6841 					    pl->pl_user_prop[i]);
6842 				headerbuf[i] = '\0';
6843 				header = headerbuf;
6844 			}
6845 
6846 		}
6847 		/*
6848 		 * If `print_header` is false, we want to print a line of
6849 		 * dashes.
6850 		 */
6851 		else {
6852 			if (first) {
6853 				header = vdev_name;
6854 				right_justify = B_FALSE;
6855 			} else {
6856 				header = "-";
6857 				right_justify = B_TRUE;
6858 			}
6859 		}
6860 
6861 		if (pl->pl_next == NULL && !right_justify)
6862 			(void) fputs(header, stdout);
6863 		else if (right_justify)
6864 			(void) printf("%*s", (int)width, header);
6865 		else
6866 			(void) printf("%-*s", (int)width, header);
6867 
6868 		if (first)
6869 			first = B_FALSE;
6870 	}
6871 
6872 	(void) fputc('\n', stdout);
6873 }
6874 
6875 /*
6876  * Given a pool and a list of properties, print out all the properties according
6877  * to the described layout. Used by zpool_do_list().
6878  */
6879 static void
6880 collect_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
6881 {
6882 	zprop_list_t *pl = cb->cb_proplist;
6883 	boolean_t first = B_TRUE;
6884 	char property[ZPOOL_MAXPROPLEN];
6885 	const char *propstr;
6886 	boolean_t right_justify;
6887 	size_t width;
6888 	zprop_source_t sourcetype = ZPROP_SRC_NONE;
6889 	nvlist_t *item, *d, *props;
6890 	item = d = props = NULL;
6891 
6892 	if (cb->cb_json) {
6893 		item = fnvlist_alloc();
6894 		props = fnvlist_alloc();
6895 		d = fnvlist_lookup_nvlist(cb->cb_jsobj, "pools");
6896 		if (d == NULL) {
6897 			fprintf(stderr, "pools obj not found.\n");
6898 			exit(1);
6899 		}
6900 		fill_pool_info(item, zhp, B_TRUE, cb->cb_json_as_int);
6901 	}
6902 
6903 	for (; pl != NULL; pl = pl->pl_next) {
6904 
6905 		width = pl->pl_width;
6906 		if (first && cb->cb_verbose) {
6907 			/*
6908 			 * Reset the width to accommodate the verbose listing
6909 			 * of devices.
6910 			 */
6911 			width = cb->cb_namewidth;
6912 		}
6913 
6914 		if (!cb->cb_json && !first) {
6915 			if (cb->cb_scripted)
6916 				(void) fputc('\t', stdout);
6917 			else
6918 				(void) fputs("  ", stdout);
6919 		} else {
6920 			first = B_FALSE;
6921 		}
6922 
6923 		right_justify = B_FALSE;
6924 		if (pl->pl_prop != ZPROP_USERPROP) {
6925 			if (zpool_get_prop(zhp, pl->pl_prop, property,
6926 			    sizeof (property), &sourcetype,
6927 			    cb->cb_literal) != 0)
6928 				propstr = "-";
6929 			else
6930 				propstr = property;
6931 
6932 			right_justify = zpool_prop_align_right(pl->pl_prop);
6933 		} else if ((zpool_prop_feature(pl->pl_user_prop) ||
6934 		    zpool_prop_unsupported(pl->pl_user_prop)) &&
6935 		    zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
6936 		    sizeof (property)) == 0) {
6937 			propstr = property;
6938 			sourcetype = ZPROP_SRC_LOCAL;
6939 		} else if (zfs_prop_user(pl->pl_user_prop) &&
6940 		    zpool_get_userprop(zhp, pl->pl_user_prop, property,
6941 		    sizeof (property), &sourcetype) == 0) {
6942 			propstr = property;
6943 		} else {
6944 			propstr = "-";
6945 		}
6946 
6947 		if (cb->cb_json) {
6948 			if (pl->pl_prop == ZPOOL_PROP_NAME)
6949 				continue;
6950 			const char *prop_name;
6951 			if (pl->pl_prop != ZPROP_USERPROP)
6952 				prop_name = zpool_prop_to_name(pl->pl_prop);
6953 			else
6954 				prop_name = pl->pl_user_prop;
6955 			(void) zprop_nvlist_one_property(
6956 			    prop_name, propstr,
6957 			    sourcetype, NULL, NULL, props, cb->cb_json_as_int);
6958 		} else {
6959 			/*
6960 			 * If this is being called in scripted mode, or if this
6961 			 * is the last column and it is left-justified, don't
6962 			 * include a width format specifier.
6963 			 */
6964 			if (cb->cb_scripted || (pl->pl_next == NULL &&
6965 			    !right_justify))
6966 				(void) fputs(propstr, stdout);
6967 			else if (right_justify)
6968 				(void) printf("%*s", (int)width, propstr);
6969 			else
6970 				(void) printf("%-*s", (int)width, propstr);
6971 		}
6972 	}
6973 
6974 	if (cb->cb_json) {
6975 		fnvlist_add_nvlist(item, "properties", props);
6976 		if (cb->cb_json_pool_key_guid) {
6977 			char pool_guid[256];
6978 			uint64_t guid = fnvlist_lookup_uint64(
6979 			    zpool_get_config(zhp, NULL),
6980 			    ZPOOL_CONFIG_POOL_GUID);
6981 			(void) snprintf(pool_guid, 256, "%llu",
6982 			    (u_longlong_t)guid);
6983 			fnvlist_add_nvlist(d, pool_guid, item);
6984 		} else {
6985 			fnvlist_add_nvlist(d, zpool_get_name(zhp),
6986 			    item);
6987 		}
6988 		fnvlist_free(props);
6989 		fnvlist_free(item);
6990 	} else
6991 		(void) fputc('\n', stdout);
6992 }
6993 
6994 static void
6995 collect_vdev_prop(zpool_prop_t prop, uint64_t value, const char *str,
6996     boolean_t scripted, boolean_t valid, enum zfs_nicenum_format format,
6997     boolean_t json, nvlist_t *nvl, boolean_t as_int)
6998 {
6999 	char propval[64];
7000 	boolean_t fixed;
7001 	size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
7002 
7003 	switch (prop) {
7004 	case ZPOOL_PROP_SIZE:
7005 	case ZPOOL_PROP_NORMAL_SIZE:
7006 	case ZPOOL_PROP_SPECIAL_SIZE:
7007 	case ZPOOL_PROP_DEDUP_SIZE:
7008 	case ZPOOL_PROP_LOG_SIZE:
7009 	case ZPOOL_PROP_ELOG_SIZE:
7010 	case ZPOOL_PROP_SELOG_SIZE:
7011 	case ZPOOL_PROP_EXPANDSZ:
7012 	case ZPOOL_PROP_NORMAL_EXPANDSZ:
7013 	case ZPOOL_PROP_SPECIAL_EXPANDSZ:
7014 	case ZPOOL_PROP_DEDUP_EXPANDSZ:
7015 	case ZPOOL_PROP_LOG_EXPANDSZ:
7016 	case ZPOOL_PROP_ELOG_EXPANDSZ:
7017 	case ZPOOL_PROP_SELOG_EXPANDSZ:
7018 	case ZPOOL_PROP_CHECKPOINT:
7019 	case ZPOOL_PROP_DEDUPRATIO:
7020 	case ZPOOL_PROP_DEDUPCACHED:
7021 		if (value == 0)
7022 			(void) strlcpy(propval, "-", sizeof (propval));
7023 		else
7024 			zfs_nicenum_format(value, propval, sizeof (propval),
7025 			    format);
7026 		break;
7027 	case ZPOOL_PROP_FRAGMENTATION:
7028 	case ZPOOL_PROP_NORMAL_FRAGMENTATION:
7029 	case ZPOOL_PROP_SPECIAL_FRAGMENTATION:
7030 	case ZPOOL_PROP_DEDUP_FRAGMENTATION:
7031 	case ZPOOL_PROP_LOG_FRAGMENTATION:
7032 	case ZPOOL_PROP_ELOG_FRAGMENTATION:
7033 	case ZPOOL_PROP_SELOG_FRAGMENTATION:
7034 		if (value == ZFS_FRAG_INVALID) {
7035 			(void) strlcpy(propval, "-", sizeof (propval));
7036 		} else if (format == ZFS_NICENUM_RAW) {
7037 			(void) snprintf(propval, sizeof (propval), "%llu",
7038 			    (unsigned long long)value);
7039 		} else {
7040 			(void) snprintf(propval, sizeof (propval), "%llu%%",
7041 			    (unsigned long long)value);
7042 		}
7043 		break;
7044 	case ZPOOL_PROP_CAPACITY:
7045 	case ZPOOL_PROP_NORMAL_CAPACITY:
7046 	case ZPOOL_PROP_SPECIAL_CAPACITY:
7047 	case ZPOOL_PROP_DEDUP_CAPACITY:
7048 	case ZPOOL_PROP_LOG_CAPACITY:
7049 	case ZPOOL_PROP_ELOG_CAPACITY:
7050 	case ZPOOL_PROP_SELOG_CAPACITY:
7051 		/* capacity value is in parts-per-10,000 (aka permyriad) */
7052 		if (format == ZFS_NICENUM_RAW)
7053 			(void) snprintf(propval, sizeof (propval), "%llu",
7054 			    (unsigned long long)value / 100);
7055 		else
7056 			(void) snprintf(propval, sizeof (propval),
7057 			    value < 1000 ? "%1.2f%%" : value < 10000 ?
7058 			    "%2.1f%%" : "%3.0f%%", value / 100.0);
7059 		break;
7060 	case ZPOOL_PROP_HEALTH:
7061 		width = 8;
7062 		(void) strlcpy(propval, str, sizeof (propval));
7063 		break;
7064 	default:
7065 		zfs_nicenum_format(value, propval, sizeof (propval), format);
7066 	}
7067 
7068 	if (!valid)
7069 		(void) strlcpy(propval, "-", sizeof (propval));
7070 
7071 	if (json) {
7072 		(void) zprop_nvlist_one_property(zpool_prop_to_name(prop),
7073 		    propval, ZPROP_SRC_NONE, NULL, NULL, nvl, as_int);
7074 	} else {
7075 		if (scripted)
7076 			(void) printf("\t%s", propval);
7077 		else
7078 			(void) printf("  %*s", (int)width, propval);
7079 	}
7080 }
7081 
7082 /*
7083  * print static default line per vdev
7084  */
7085 static void
7086 collect_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
7087     list_cbdata_t *cb, int depth, boolean_t isspare, nvlist_t *item)
7088 {
7089 	nvlist_t **child;
7090 	vdev_stat_t *vs;
7091 	uint_t c, children = 0;
7092 	char *vname;
7093 	boolean_t scripted = cb->cb_scripted;
7094 	uint64_t islog = B_FALSE;
7095 	nvlist_t *props, *ent, *ch, *obj, *l2c, *sp;
7096 	props = ent = ch = obj = sp = l2c = NULL;
7097 
7098 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
7099 	    (uint64_t **)&vs, &c) == 0);
7100 
7101 	if (name != NULL) {
7102 		boolean_t toplevel = (vs->vs_space != 0);
7103 		uint64_t cap;
7104 		enum zfs_nicenum_format format;
7105 		const char *state;
7106 
7107 		if (cb->cb_literal)
7108 			format = ZFS_NICENUM_RAW;
7109 		else
7110 			format = ZFS_NICENUM_1024;
7111 
7112 		if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
7113 			return;
7114 
7115 		if (cb->cb_json) {
7116 			props = fnvlist_alloc();
7117 			ent = fnvlist_alloc();
7118 			fill_vdev_info(ent, zhp, (char *)name, B_FALSE,
7119 			    cb->cb_json_as_int);
7120 		} else {
7121 			if (scripted)
7122 				(void) printf("\t%s", name);
7123 			else if (strlen(name) + depth > cb->cb_namewidth)
7124 				(void) printf("%*s%s", depth, "", name);
7125 			else
7126 				(void) printf("%*s%s%*s", depth, "", name,
7127 				    (int)(cb->cb_namewidth - strlen(name) -
7128 				    depth), "");
7129 		}
7130 
7131 		/*
7132 		 * Print the properties for the individual vdevs. Some
7133 		 * properties are only applicable to toplevel vdevs. The
7134 		 * 'toplevel' boolean value is passed to the print_one_column()
7135 		 * to indicate that the value is valid.
7136 		 */
7137 		for (zprop_list_t *pl = cb->cb_proplist; pl != NULL;
7138 		    pl = pl->pl_next) {
7139 			switch (pl->pl_prop) {
7140 			case ZPOOL_PROP_SIZE:
7141 				if (VDEV_STAT_VALID(vs_pspace, c) &&
7142 				    vs->vs_pspace) {
7143 					collect_vdev_prop(
7144 					    ZPOOL_PROP_SIZE, vs->vs_pspace,
7145 					    NULL, scripted, B_TRUE, format,
7146 					    cb->cb_json, props,
7147 					    cb->cb_json_as_int);
7148 				} else {
7149 					collect_vdev_prop(
7150 					    ZPOOL_PROP_SIZE, vs->vs_space, NULL,
7151 					    scripted, toplevel, format,
7152 					    cb->cb_json, props,
7153 					    cb->cb_json_as_int);
7154 				}
7155 				break;
7156 			case ZPOOL_PROP_ALLOCATED:
7157 				collect_vdev_prop(ZPOOL_PROP_ALLOCATED,
7158 				    vs->vs_alloc, NULL, scripted, toplevel,
7159 				    format, cb->cb_json, props,
7160 				    cb->cb_json_as_int);
7161 				break;
7162 
7163 			case ZPOOL_PROP_FREE:
7164 				collect_vdev_prop(ZPOOL_PROP_FREE,
7165 				    vs->vs_space - vs->vs_alloc, NULL, scripted,
7166 				    toplevel, format, cb->cb_json, props,
7167 				    cb->cb_json_as_int);
7168 				break;
7169 
7170 			case ZPOOL_PROP_CHECKPOINT:
7171 				collect_vdev_prop(ZPOOL_PROP_CHECKPOINT,
7172 				    vs->vs_checkpoint_space, NULL, scripted,
7173 				    toplevel, format, cb->cb_json, props,
7174 				    cb->cb_json_as_int);
7175 				break;
7176 
7177 			case ZPOOL_PROP_EXPANDSZ:
7178 				collect_vdev_prop(ZPOOL_PROP_EXPANDSZ,
7179 				    vs->vs_esize, NULL, scripted, B_TRUE,
7180 				    format, cb->cb_json, props,
7181 				    cb->cb_json_as_int);
7182 				break;
7183 
7184 			case ZPOOL_PROP_FRAGMENTATION:
7185 				collect_vdev_prop(
7186 				    ZPOOL_PROP_FRAGMENTATION,
7187 				    vs->vs_fragmentation, NULL, scripted,
7188 				    (vs->vs_fragmentation != ZFS_FRAG_INVALID &&
7189 				    toplevel),
7190 				    format, cb->cb_json, props,
7191 				    cb->cb_json_as_int);
7192 				break;
7193 
7194 			case ZPOOL_PROP_CAPACITY:
7195 				cap = (vs->vs_space == 0) ?
7196 				    0 : (vs->vs_alloc * 10000 / vs->vs_space);
7197 				collect_vdev_prop(ZPOOL_PROP_CAPACITY, cap,
7198 				    NULL, scripted, toplevel, format,
7199 				    cb->cb_json, props, cb->cb_json_as_int);
7200 				break;
7201 
7202 			case ZPOOL_PROP_HEALTH:
7203 				state = zpool_state_to_name(vs->vs_state,
7204 				    vs->vs_aux);
7205 				if (isspare) {
7206 					if (vs->vs_aux == VDEV_AUX_SPARED)
7207 						state = "INUSE";
7208 					else if (vs->vs_state ==
7209 					    VDEV_STATE_HEALTHY)
7210 						state = "AVAIL";
7211 				}
7212 				collect_vdev_prop(ZPOOL_PROP_HEALTH, 0, state,
7213 				    scripted, B_TRUE, format, cb->cb_json,
7214 				    props, cb->cb_json_as_int);
7215 				break;
7216 
7217 			case ZPOOL_PROP_NAME:
7218 				break;
7219 
7220 			default:
7221 				collect_vdev_prop(pl->pl_prop, 0,
7222 				    NULL, scripted, B_FALSE, format,
7223 				    cb->cb_json, props, cb->cb_json_as_int);
7224 
7225 			}
7226 
7227 
7228 		}
7229 
7230 		if (cb->cb_json) {
7231 			fnvlist_add_nvlist(ent, "properties", props);
7232 			fnvlist_free(props);
7233 		} else
7234 			(void) fputc('\n', stdout);
7235 	}
7236 
7237 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
7238 	    &child, &children) != 0) {
7239 		if (cb->cb_json) {
7240 			fnvlist_add_nvlist(item, name, ent);
7241 			fnvlist_free(ent);
7242 		}
7243 		return;
7244 	}
7245 
7246 	if (cb->cb_json) {
7247 		ch = fnvlist_alloc();
7248 	}
7249 
7250 	/* list the normal vdevs first */
7251 	for (c = 0; c < children; c++) {
7252 		uint64_t ishole = B_FALSE;
7253 
7254 		if (nvlist_lookup_uint64(child[c],
7255 		    ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
7256 			continue;
7257 
7258 		if (nvlist_lookup_uint64(child[c],
7259 		    ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
7260 			continue;
7261 
7262 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
7263 			continue;
7264 
7265 		vname = zpool_vdev_name(g_zfs, zhp, child[c],
7266 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7267 
7268 		if (name == NULL || cb->cb_json != B_TRUE)
7269 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7270 			    B_FALSE, item);
7271 		else if (cb->cb_json) {
7272 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7273 			    B_FALSE, ch);
7274 		}
7275 		free(vname);
7276 	}
7277 
7278 	if (cb->cb_json) {
7279 		if (!nvlist_empty(ch))
7280 			fnvlist_add_nvlist(ent, "vdevs", ch);
7281 		fnvlist_free(ch);
7282 	}
7283 
7284 	/* list the classes: 'logs', 'dedup', and 'special' */
7285 	for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
7286 		boolean_t printed = B_FALSE;
7287 		if (cb->cb_json)
7288 			obj = fnvlist_alloc();
7289 		for (c = 0; c < children; c++) {
7290 			const char *bias = NULL;
7291 			const char *type = NULL;
7292 
7293 			if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
7294 			    &islog) == 0 && islog) {
7295 				bias = VDEV_ALLOC_CLASS_LOGS;
7296 			} else {
7297 				(void) nvlist_lookup_string(child[c],
7298 				    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
7299 				(void) nvlist_lookup_string(child[c],
7300 				    ZPOOL_CONFIG_TYPE, &type);
7301 			}
7302 			if (bias == NULL || strcmp(bias, class_name[n]) != 0)
7303 				continue;
7304 			if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
7305 				continue;
7306 
7307 			if (!printed && !cb->cb_json) {
7308 				print_line(cb, class_name[n]);
7309 				printed = B_TRUE;
7310 			}
7311 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
7312 			    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7313 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7314 			    B_FALSE, obj);
7315 			free(vname);
7316 		}
7317 		if (cb->cb_json) {
7318 			if (!nvlist_empty(obj))
7319 				fnvlist_add_nvlist(item, class_name[n], obj);
7320 			fnvlist_free(obj);
7321 		}
7322 	}
7323 
7324 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
7325 	    &child, &children) == 0 && children > 0) {
7326 		if (cb->cb_json) {
7327 			l2c = fnvlist_alloc();
7328 		} else {
7329 			print_line(cb, "cache");
7330 		}
7331 		for (c = 0; c < children; c++) {
7332 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
7333 			    cb->cb_name_flags);
7334 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7335 			    B_FALSE, l2c);
7336 			free(vname);
7337 		}
7338 		if (cb->cb_json) {
7339 			if (!nvlist_empty(l2c))
7340 				fnvlist_add_nvlist(item, "l2cache", l2c);
7341 			fnvlist_free(l2c);
7342 		}
7343 	}
7344 
7345 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
7346 	    &children) == 0 && children > 0) {
7347 		if (cb->cb_json) {
7348 			sp = fnvlist_alloc();
7349 		} else {
7350 			print_line(cb, "spare");
7351 		}
7352 		for (c = 0; c < children; c++) {
7353 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
7354 			    cb->cb_name_flags);
7355 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7356 			    B_TRUE, sp);
7357 			free(vname);
7358 		}
7359 		if (cb->cb_json) {
7360 			if (!nvlist_empty(sp))
7361 				fnvlist_add_nvlist(item, "spares", sp);
7362 			fnvlist_free(sp);
7363 		}
7364 	}
7365 
7366 	if (name != NULL && cb->cb_json) {
7367 		fnvlist_add_nvlist(item, name, ent);
7368 		fnvlist_free(ent);
7369 	}
7370 }
7371 
7372 /*
7373  * Generic callback function to list a pool.
7374  */
7375 static int
7376 list_callback(zpool_handle_t *zhp, void *data)
7377 {
7378 	nvlist_t *p, *d, *nvdevs;
7379 	uint64_t guid;
7380 	char pool_guid[256];
7381 	const char *pool_name = zpool_get_name(zhp);
7382 	list_cbdata_t *cbp = data;
7383 	p = d = nvdevs = NULL;
7384 
7385 	collect_pool(zhp, cbp);
7386 
7387 	if (cbp->cb_verbose) {
7388 		nvlist_t *config, *nvroot;
7389 		config = zpool_get_config(zhp, NULL);
7390 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
7391 		    &nvroot) == 0);
7392 		if (cbp->cb_json) {
7393 			d = fnvlist_lookup_nvlist(cbp->cb_jsobj,
7394 			    "pools");
7395 			if (cbp->cb_json_pool_key_guid) {
7396 				guid = fnvlist_lookup_uint64(config,
7397 				    ZPOOL_CONFIG_POOL_GUID);
7398 				(void) snprintf(pool_guid, 256, "%llu",
7399 				    (u_longlong_t)guid);
7400 				p = fnvlist_lookup_nvlist(d, pool_guid);
7401 			} else {
7402 				p = fnvlist_lookup_nvlist(d, pool_name);
7403 			}
7404 			nvdevs = fnvlist_alloc();
7405 		}
7406 		collect_list_stats(zhp, NULL, nvroot, cbp, 0, B_FALSE, nvdevs);
7407 		if (cbp->cb_json) {
7408 			fnvlist_add_nvlist(p, "vdevs", nvdevs);
7409 			if (cbp->cb_json_pool_key_guid)
7410 				fnvlist_add_nvlist(d, pool_guid, p);
7411 			else
7412 				fnvlist_add_nvlist(d, pool_name, p);
7413 			fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
7414 			fnvlist_free(nvdevs);
7415 		}
7416 	}
7417 
7418 	return (0);
7419 }
7420 
7421 /*
7422  * Set the minimum pool/vdev name column width.  The width must be at least 9,
7423  * but may be as large as needed.
7424  */
7425 static int
7426 get_namewidth_list(zpool_handle_t *zhp, void *data)
7427 {
7428 	list_cbdata_t *cb = data;
7429 	int width;
7430 
7431 	width = get_namewidth(zhp, cb->cb_namewidth,
7432 	    cb->cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
7433 
7434 	if (width < 9)
7435 		width = 9;
7436 
7437 	cb->cb_namewidth = width;
7438 
7439 	return (0);
7440 }
7441 
7442 /*
7443  * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
7444  *
7445  *	-g	Display guid for individual vdev name.
7446  *	-H	Scripted mode.  Don't display headers, and separate properties
7447  *		by a single tab.
7448  *	-L	Follow links when resolving vdev path name.
7449  *	-o	List of properties to display.  Defaults to
7450  *		"name,size,allocated,free,expandsize,fragmentation,capacity,"
7451  *		"dedupratio,health,altroot"
7452  *	-p	Display values in parsable (exact) format.
7453  *	-P	Display full path for vdev name.
7454  *	-T	Display a timestamp in date(1) or Unix format
7455  *	-j	Display the output in JSON format
7456  *	--json-int	Display the numbers as integer instead of strings.
7457  *	--json-pool-key-guid  Set pool GUID as key for pool objects.
7458  *
7459  * List all pools in the system, whether or not they're healthy.  Output space
7460  * statistics for each one, as well as health status summary.
7461  */
7462 int
7463 zpool_do_list(int argc, char **argv)
7464 {
7465 	int c;
7466 	int ret = 0;
7467 	list_cbdata_t cb = { 0 };
7468 	static char default_props[] =
7469 	    "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
7470 	    "capacity,dedupratio,health,altroot";
7471 	char *props = default_props;
7472 	float interval = 0;
7473 	unsigned long count = 0;
7474 	zpool_list_t *list;
7475 	boolean_t first = B_TRUE;
7476 	nvlist_t *data = NULL;
7477 	current_prop_type = ZFS_TYPE_POOL;
7478 
7479 	struct option long_options[] = {
7480 		{"json", no_argument, NULL, 'j'},
7481 		{"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
7482 		{"json-pool-key-guid", no_argument, NULL,
7483 		    ZPOOL_OPTION_POOL_KEY_GUID},
7484 		{0, 0, 0, 0}
7485 	};
7486 
7487 	/* check options */
7488 	while ((c = getopt_long(argc, argv, ":gjHLo:pPT:v", long_options,
7489 	    NULL)) != -1) {
7490 		switch (c) {
7491 		case 'g':
7492 			cb.cb_name_flags |= VDEV_NAME_GUID;
7493 			break;
7494 		case 'H':
7495 			cb.cb_scripted = B_TRUE;
7496 			break;
7497 		case 'L':
7498 			cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
7499 			break;
7500 		case 'o':
7501 			props = optarg;
7502 			break;
7503 		case 'P':
7504 			cb.cb_name_flags |= VDEV_NAME_PATH;
7505 			break;
7506 		case 'p':
7507 			cb.cb_literal = B_TRUE;
7508 			break;
7509 		case 'j':
7510 			cb.cb_json = B_TRUE;
7511 			break;
7512 		case ZPOOL_OPTION_JSON_NUMS_AS_INT:
7513 			cb.cb_json_as_int = B_TRUE;
7514 			cb.cb_literal = B_TRUE;
7515 			break;
7516 		case ZPOOL_OPTION_POOL_KEY_GUID:
7517 			cb.cb_json_pool_key_guid = B_TRUE;
7518 			break;
7519 		case 'T':
7520 			get_timestamp_arg(*optarg);
7521 			break;
7522 		case 'v':
7523 			cb.cb_verbose = B_TRUE;
7524 			cb.cb_namewidth = 8;	/* 8 until precalc is avail */
7525 			break;
7526 		case ':':
7527 			(void) fprintf(stderr, gettext("missing argument for "
7528 			    "'%c' option\n"), optopt);
7529 			usage(B_FALSE);
7530 			break;
7531 		case '?':
7532 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7533 			    optopt);
7534 			usage(B_FALSE);
7535 		}
7536 	}
7537 
7538 	argc -= optind;
7539 	argv += optind;
7540 
7541 	if (!cb.cb_json && cb.cb_json_as_int) {
7542 		(void) fprintf(stderr, gettext("'--json-int' only works with"
7543 		    " '-j' option\n"));
7544 		usage(B_FALSE);
7545 	}
7546 
7547 	if (!cb.cb_json && cb.cb_json_pool_key_guid) {
7548 		(void) fprintf(stderr, gettext("'json-pool-key-guid' only"
7549 		    " works with '-j' option\n"));
7550 		usage(B_FALSE);
7551 	}
7552 
7553 	get_interval_count(&argc, argv, &interval, &count);
7554 
7555 	if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
7556 		usage(B_FALSE);
7557 
7558 	for (;;) {
7559 		if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
7560 		    ZFS_TYPE_POOL, cb.cb_literal, &ret)) == NULL)
7561 			return (1);
7562 
7563 		if (pool_list_count(list) == 0)
7564 			break;
7565 
7566 		if (cb.cb_json) {
7567 			cb.cb_jsobj = zpool_json_schema(0, 1);
7568 			data = fnvlist_alloc();
7569 			fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
7570 			fnvlist_free(data);
7571 		}
7572 
7573 		cb.cb_namewidth = 0;
7574 		(void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
7575 
7576 		if (timestamp_fmt != NODATE) {
7577 			if (cb.cb_json) {
7578 				if (cb.cb_json_as_int) {
7579 					fnvlist_add_uint64(cb.cb_jsobj, "time",
7580 					    time(NULL));
7581 				} else {
7582 					char ts[128];
7583 					get_timestamp(timestamp_fmt, ts, 128);
7584 					fnvlist_add_string(cb.cb_jsobj, "time",
7585 					    ts);
7586 				}
7587 			} else
7588 				print_timestamp(timestamp_fmt);
7589 		}
7590 
7591 		if (!cb.cb_scripted && (first || cb.cb_verbose) &&
7592 		    !cb.cb_json) {
7593 			print_line(&cb, NULL);
7594 			first = B_FALSE;
7595 		}
7596 		ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
7597 
7598 		if (ret == 0 && cb.cb_json)
7599 			zcmd_print_json(cb.cb_jsobj);
7600 		else if (ret != 0 && cb.cb_json)
7601 			nvlist_free(cb.cb_jsobj);
7602 
7603 		if (interval == 0)
7604 			break;
7605 
7606 		if (count != 0 && --count == 0)
7607 			break;
7608 
7609 		pool_list_free(list);
7610 
7611 		(void) fflush(stdout);
7612 		(void) fsleep(interval);
7613 	}
7614 
7615 	if (argc == 0 && !cb.cb_scripted && !cb.cb_json &&
7616 	    pool_list_count(list) == 0) {
7617 		(void) printf(gettext("no pools available\n"));
7618 		ret = 0;
7619 	}
7620 
7621 	pool_list_free(list);
7622 	zprop_free_list(cb.cb_proplist);
7623 	return (ret);
7624 }
7625 
7626 static int
7627 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
7628 {
7629 	boolean_t force = B_FALSE;
7630 	boolean_t rebuild = B_FALSE;
7631 	boolean_t wait = B_FALSE;
7632 	int c;
7633 	nvlist_t *nvroot;
7634 	char *poolname, *old_disk, *new_disk;
7635 	zpool_handle_t *zhp;
7636 	nvlist_t *props = NULL;
7637 	char *propval;
7638 	int ret;
7639 
7640 	/* check options */
7641 	while ((c = getopt(argc, argv, "fo:sw")) != -1) {
7642 		switch (c) {
7643 		case 'f':
7644 			force = B_TRUE;
7645 			break;
7646 		case 'o':
7647 			if ((propval = strchr(optarg, '=')) == NULL) {
7648 				(void) fprintf(stderr, gettext("missing "
7649 				    "'=' for -o option\n"));
7650 				usage(B_FALSE);
7651 			}
7652 			*propval = '\0';
7653 			propval++;
7654 
7655 			if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
7656 			    (add_prop_list(optarg, propval, &props, B_TRUE)))
7657 				usage(B_FALSE);
7658 			break;
7659 		case 's':
7660 			rebuild = B_TRUE;
7661 			break;
7662 		case 'w':
7663 			wait = B_TRUE;
7664 			break;
7665 		case '?':
7666 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7667 			    optopt);
7668 			usage(B_FALSE);
7669 		}
7670 	}
7671 
7672 	argc -= optind;
7673 	argv += optind;
7674 
7675 	/* get pool name and check number of arguments */
7676 	if (argc < 1) {
7677 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
7678 		usage(B_FALSE);
7679 	}
7680 
7681 	poolname = argv[0];
7682 
7683 	if (argc < 2) {
7684 		(void) fprintf(stderr,
7685 		    gettext("missing <device> specification\n"));
7686 		usage(B_FALSE);
7687 	}
7688 
7689 	old_disk = argv[1];
7690 
7691 	if (argc < 3) {
7692 		if (!replacing) {
7693 			(void) fprintf(stderr,
7694 			    gettext("missing <new_device> specification\n"));
7695 			usage(B_FALSE);
7696 		}
7697 		new_disk = old_disk;
7698 		argc -= 1;
7699 		argv += 1;
7700 	} else {
7701 		new_disk = argv[2];
7702 		argc -= 2;
7703 		argv += 2;
7704 	}
7705 
7706 	if (argc > 1) {
7707 		(void) fprintf(stderr, gettext("too many arguments\n"));
7708 		usage(B_FALSE);
7709 	}
7710 
7711 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7712 		nvlist_free(props);
7713 		return (1);
7714 	}
7715 
7716 	if (zpool_get_config(zhp, NULL) == NULL) {
7717 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
7718 		    poolname);
7719 		zpool_close(zhp);
7720 		nvlist_free(props);
7721 		return (1);
7722 	}
7723 
7724 	/* unless manually specified use "ashift" pool property (if set) */
7725 	if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
7726 		int intval;
7727 		zprop_source_t src;
7728 		char strval[ZPOOL_MAXPROPLEN];
7729 
7730 		intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
7731 		if (src != ZPROP_SRC_DEFAULT) {
7732 			(void) sprintf(strval, "%" PRId32, intval);
7733 			verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
7734 			    &props, B_TRUE) == 0);
7735 		}
7736 	}
7737 
7738 	nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
7739 	    argc, argv);
7740 	if (nvroot == NULL) {
7741 		zpool_close(zhp);
7742 		nvlist_free(props);
7743 		return (1);
7744 	}
7745 
7746 	ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing,
7747 	    rebuild);
7748 
7749 	if (ret == 0 && wait) {
7750 		zpool_wait_activity_t activity = ZPOOL_WAIT_RESILVER;
7751 		char raidz_prefix[] = "raidz";
7752 		if (replacing) {
7753 			activity = ZPOOL_WAIT_REPLACE;
7754 		} else if (strncmp(old_disk,
7755 		    raidz_prefix, strlen(raidz_prefix)) == 0) {
7756 			activity = ZPOOL_WAIT_RAIDZ_EXPAND;
7757 		}
7758 		ret = zpool_wait(zhp, activity);
7759 	}
7760 
7761 	nvlist_free(props);
7762 	nvlist_free(nvroot);
7763 	zpool_close(zhp);
7764 
7765 	return (ret);
7766 }
7767 
7768 /*
7769  * zpool replace [-fsw] [-o property=value] <pool> <device> <new_device>
7770  *
7771  *	-f	Force attach, even if <new_device> appears to be in use.
7772  *	-s	Use sequential instead of healing reconstruction for resilver.
7773  *	-o	Set property=value.
7774  *	-w	Wait for replacing to complete before returning
7775  *
7776  * Replace <device> with <new_device>.
7777  */
7778 int
7779 zpool_do_replace(int argc, char **argv)
7780 {
7781 	return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
7782 }
7783 
7784 /*
7785  * zpool attach [-fsw] [-o property=value] <pool> <vdev> <new_device>
7786  *
7787  *	-f	Force attach, even if <new_device> appears to be in use.
7788  *	-s	Use sequential instead of healing reconstruction for resilver.
7789  *	-o	Set property=value.
7790  *	-w	Wait for resilvering (mirror) or expansion (raidz) to complete
7791  *		before returning.
7792  *
7793  * Attach <new_device> to a <vdev>, where the vdev can be of type
7794  * device, mirror or raidz. If <vdev> is not part of a mirror, then <vdev> will
7795  * be transformed into a mirror of <vdev> and <new_device>. When a mirror
7796  * is involved, <new_device> will begin life with a DTL of [0, now], and will
7797  * immediately begin to resilver itself. For the raidz case, a expansion will
7798  * commence and reflow the raidz data across all the disks including the
7799  * <new_device>.
7800  */
7801 int
7802 zpool_do_attach(int argc, char **argv)
7803 {
7804 	return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
7805 }
7806 
7807 /*
7808  * zpool detach [-f] <pool> <device>
7809  *
7810  *	-f	Force detach of <device>, even if DTLs argue against it
7811  *		(not supported yet)
7812  *
7813  * Detach a device from a mirror.  The operation will be refused if <device>
7814  * is the last device in the mirror, or if the DTLs indicate that this device
7815  * has the only valid copy of some data.
7816  */
7817 int
7818 zpool_do_detach(int argc, char **argv)
7819 {
7820 	int c;
7821 	char *poolname, *path;
7822 	zpool_handle_t *zhp;
7823 	int ret;
7824 
7825 	/* check options */
7826 	while ((c = getopt(argc, argv, "")) != -1) {
7827 		switch (c) {
7828 		case '?':
7829 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7830 			    optopt);
7831 			usage(B_FALSE);
7832 		}
7833 	}
7834 
7835 	argc -= optind;
7836 	argv += optind;
7837 
7838 	/* get pool name and check number of arguments */
7839 	if (argc < 1) {
7840 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
7841 		usage(B_FALSE);
7842 	}
7843 
7844 	if (argc < 2) {
7845 		(void) fprintf(stderr,
7846 		    gettext("missing <device> specification\n"));
7847 		usage(B_FALSE);
7848 	}
7849 
7850 	poolname = argv[0];
7851 	path = argv[1];
7852 
7853 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7854 		return (1);
7855 
7856 	ret = zpool_vdev_detach(zhp, path);
7857 
7858 	zpool_close(zhp);
7859 
7860 	return (ret);
7861 }
7862 
7863 /*
7864  * zpool split [-gLnP] [-o prop=val] ...
7865  *		[-o mntopt] ...
7866  *		[-R altroot] <pool> <newpool> [<device> ...]
7867  *
7868  *	-g      Display guid for individual vdev name.
7869  *	-L	Follow links when resolving vdev path name.
7870  *	-n	Do not split the pool, but display the resulting layout if
7871  *		it were to be split.
7872  *	-o	Set property=value, or set mount options.
7873  *	-P	Display full path for vdev name.
7874  *	-R	Mount the split-off pool under an alternate root.
7875  *	-l	Load encryption keys while importing.
7876  *
7877  * Splits the named pool and gives it the new pool name.  Devices to be split
7878  * off may be listed, provided that no more than one device is specified
7879  * per top-level vdev mirror.  The newly split pool is left in an exported
7880  * state unless -R is specified.
7881  *
7882  * Restrictions: the top-level of the pool pool must only be made up of
7883  * mirrors; all devices in the pool must be healthy; no device may be
7884  * undergoing a resilvering operation.
7885  */
7886 int
7887 zpool_do_split(int argc, char **argv)
7888 {
7889 	char *srcpool, *newpool, *propval;
7890 	char *mntopts = NULL;
7891 	splitflags_t flags;
7892 	int c, ret = 0;
7893 	int ms_status = 0;
7894 	boolean_t loadkeys = B_FALSE;
7895 	zpool_handle_t *zhp;
7896 	nvlist_t *config, *props = NULL;
7897 
7898 	flags.dryrun = B_FALSE;
7899 	flags.import = B_FALSE;
7900 	flags.name_flags = 0;
7901 
7902 	/* check options */
7903 	while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
7904 		switch (c) {
7905 		case 'g':
7906 			flags.name_flags |= VDEV_NAME_GUID;
7907 			break;
7908 		case 'L':
7909 			flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
7910 			break;
7911 		case 'R':
7912 			flags.import = B_TRUE;
7913 			if (add_prop_list(
7914 			    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
7915 			    &props, B_TRUE) != 0) {
7916 				nvlist_free(props);
7917 				usage(B_FALSE);
7918 			}
7919 			break;
7920 		case 'l':
7921 			loadkeys = B_TRUE;
7922 			break;
7923 		case 'n':
7924 			flags.dryrun = B_TRUE;
7925 			break;
7926 		case 'o':
7927 			if ((propval = strchr(optarg, '=')) != NULL) {
7928 				*propval = '\0';
7929 				propval++;
7930 				if (add_prop_list(optarg, propval,
7931 				    &props, B_TRUE) != 0) {
7932 					nvlist_free(props);
7933 					usage(B_FALSE);
7934 				}
7935 			} else {
7936 				mntopts = optarg;
7937 			}
7938 			break;
7939 		case 'P':
7940 			flags.name_flags |= VDEV_NAME_PATH;
7941 			break;
7942 		case ':':
7943 			(void) fprintf(stderr, gettext("missing argument for "
7944 			    "'%c' option\n"), optopt);
7945 			usage(B_FALSE);
7946 			break;
7947 		case '?':
7948 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7949 			    optopt);
7950 			usage(B_FALSE);
7951 			break;
7952 		}
7953 	}
7954 
7955 	if (!flags.import && mntopts != NULL) {
7956 		(void) fprintf(stderr, gettext("setting mntopts is only "
7957 		    "valid when importing the pool\n"));
7958 		usage(B_FALSE);
7959 	}
7960 
7961 	if (!flags.import && loadkeys) {
7962 		(void) fprintf(stderr, gettext("loading keys is only "
7963 		    "valid when importing the pool\n"));
7964 		usage(B_FALSE);
7965 	}
7966 
7967 	argc -= optind;
7968 	argv += optind;
7969 
7970 	if (argc < 1) {
7971 		(void) fprintf(stderr, gettext("Missing pool name\n"));
7972 		usage(B_FALSE);
7973 	}
7974 	if (argc < 2) {
7975 		(void) fprintf(stderr, gettext("Missing new pool name\n"));
7976 		usage(B_FALSE);
7977 	}
7978 
7979 	srcpool = argv[0];
7980 	newpool = argv[1];
7981 
7982 	argc -= 2;
7983 	argv += 2;
7984 
7985 	if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
7986 		nvlist_free(props);
7987 		return (1);
7988 	}
7989 
7990 	config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
7991 	if (config == NULL) {
7992 		ret = 1;
7993 	} else {
7994 		if (flags.dryrun) {
7995 			(void) printf(gettext("would create '%s' with the "
7996 			    "following layout:\n\n"), newpool);
7997 			print_vdev_tree(NULL, newpool, config, 0, "",
7998 			    flags.name_flags);
7999 			print_vdev_tree(NULL, "dedup", config, 0,
8000 			    VDEV_ALLOC_BIAS_DEDUP, 0);
8001 			print_vdev_tree(NULL, "special", config, 0,
8002 			    VDEV_ALLOC_BIAS_SPECIAL, 0);
8003 		}
8004 	}
8005 
8006 	zpool_close(zhp);
8007 
8008 	if (ret != 0 || flags.dryrun || !flags.import) {
8009 		nvlist_free(config);
8010 		nvlist_free(props);
8011 		return (ret);
8012 	}
8013 
8014 	/*
8015 	 * The split was successful. Now we need to open the new
8016 	 * pool and import it.
8017 	 */
8018 	if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
8019 		nvlist_free(config);
8020 		nvlist_free(props);
8021 		return (1);
8022 	}
8023 
8024 	if (loadkeys) {
8025 		ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
8026 		if (ret != 0)
8027 			ret = 1;
8028 	}
8029 
8030 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL) {
8031 		ms_status = zpool_enable_datasets(zhp, mntopts, 0,
8032 		    mount_tp_nthr);
8033 		if (ms_status == EZFS_SHAREFAILED) {
8034 			(void) fprintf(stderr, gettext("Split was successful, "
8035 			    "datasets are mounted but sharing of some datasets "
8036 			    "has failed\n"));
8037 		} else if (ms_status == EZFS_MOUNTFAILED) {
8038 			(void) fprintf(stderr, gettext("Split was successful"
8039 			    ", but some datasets could not be mounted\n"));
8040 			(void) fprintf(stderr, gettext("Try doing '%s' with a "
8041 			    "different altroot\n"), "zpool import");
8042 		}
8043 	}
8044 	zpool_close(zhp);
8045 	nvlist_free(config);
8046 	nvlist_free(props);
8047 
8048 	return (ret);
8049 }
8050 
8051 
8052 /*
8053  * zpool online [--power] <pool> <device> ...
8054  *
8055  * --power: Power on the enclosure slot to the drive (if possible)
8056  */
8057 int
8058 zpool_do_online(int argc, char **argv)
8059 {
8060 	int c, i;
8061 	char *poolname;
8062 	zpool_handle_t *zhp;
8063 	int ret = 0;
8064 	vdev_state_t newstate;
8065 	int flags = 0;
8066 	boolean_t is_power_on = B_FALSE;
8067 	struct option long_options[] = {
8068 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8069 		{0, 0, 0, 0}
8070 	};
8071 
8072 	/* check options */
8073 	while ((c = getopt_long(argc, argv, "e", long_options, NULL)) != -1) {
8074 		switch (c) {
8075 		case 'e':
8076 			flags |= ZFS_ONLINE_EXPAND;
8077 			break;
8078 		case ZPOOL_OPTION_POWER:
8079 			is_power_on = B_TRUE;
8080 			break;
8081 		case '?':
8082 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8083 			    optopt);
8084 			usage(B_FALSE);
8085 		}
8086 	}
8087 
8088 	if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8089 		is_power_on = B_TRUE;
8090 
8091 	argc -= optind;
8092 	argv += optind;
8093 
8094 	/* get pool name and check number of arguments */
8095 	if (argc < 1) {
8096 		(void) fprintf(stderr, gettext("missing pool name\n"));
8097 		usage(B_FALSE);
8098 	}
8099 	if (argc < 2) {
8100 		(void) fprintf(stderr, gettext("missing device name\n"));
8101 		usage(B_FALSE);
8102 	}
8103 
8104 	poolname = argv[0];
8105 
8106 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8107 		(void) fprintf(stderr, gettext("failed to open pool "
8108 		    "\"%s\"\n"), poolname);
8109 		return (1);
8110 	}
8111 
8112 	for (i = 1; i < argc; i++) {
8113 		vdev_state_t oldstate;
8114 		boolean_t avail_spare, l2cache;
8115 		int rc;
8116 
8117 		if (is_power_on) {
8118 			rc = zpool_power_on_and_disk_wait(zhp, argv[i]);
8119 			if (rc == ENOTSUP) {
8120 				(void) fprintf(stderr,
8121 				    gettext("Power control not supported\n"));
8122 			}
8123 			if (rc != 0)
8124 				return (rc);
8125 		}
8126 
8127 		nvlist_t *tgt = zpool_find_vdev(zhp, argv[i], &avail_spare,
8128 		    &l2cache, NULL);
8129 		if (tgt == NULL) {
8130 			ret = 1;
8131 			(void) fprintf(stderr, gettext("couldn't find device "
8132 			"\"%s\" in pool \"%s\"\n"), argv[i], poolname);
8133 			continue;
8134 		}
8135 		uint_t vsc;
8136 		oldstate = ((vdev_stat_t *)fnvlist_lookup_uint64_array(tgt,
8137 		    ZPOOL_CONFIG_VDEV_STATS, &vsc))->vs_state;
8138 		if ((rc = zpool_vdev_online(zhp, argv[i], flags,
8139 		    &newstate)) == 0) {
8140 			if (newstate != VDEV_STATE_HEALTHY) {
8141 				(void) printf(gettext("warning: device '%s' "
8142 				    "onlined, but remains in faulted state\n"),
8143 				    argv[i]);
8144 				if (newstate == VDEV_STATE_FAULTED)
8145 					(void) printf(gettext("use 'zpool "
8146 					    "clear' to restore a faulted "
8147 					    "device\n"));
8148 				else
8149 					(void) printf(gettext("use 'zpool "
8150 					    "replace' to replace devices "
8151 					    "that are no longer present\n"));
8152 				if ((flags & ZFS_ONLINE_EXPAND)) {
8153 					(void) printf(gettext("%s: failed "
8154 					    "to expand usable space on "
8155 					    "unhealthy device '%s'\n"),
8156 					    (oldstate >= VDEV_STATE_DEGRADED ?
8157 					    "error" : "warning"), argv[i]);
8158 					if (oldstate >= VDEV_STATE_DEGRADED) {
8159 						ret = 1;
8160 						break;
8161 					}
8162 				}
8163 			}
8164 		} else {
8165 			(void) fprintf(stderr, gettext("Failed to online "
8166 			    "\"%s\" in pool \"%s\": %d\n"),
8167 			    argv[i], poolname, rc);
8168 			ret = 1;
8169 		}
8170 	}
8171 
8172 	zpool_close(zhp);
8173 
8174 	return (ret);
8175 }
8176 
8177 /*
8178  * zpool offline [-ft]|[--power] <pool> <device> ...
8179  *
8180  *
8181  *	-f	Force the device into a faulted state.
8182  *
8183  *	-t	Only take the device off-line temporarily.  The offline/faulted
8184  *		state will not be persistent across reboots.
8185  *
8186  *	--power Power off the enclosure slot to the drive (if possible)
8187  */
8188 int
8189 zpool_do_offline(int argc, char **argv)
8190 {
8191 	int c, i;
8192 	char *poolname;
8193 	zpool_handle_t *zhp;
8194 	int ret = 0;
8195 	boolean_t istmp = B_FALSE;
8196 	boolean_t fault = B_FALSE;
8197 	boolean_t is_power_off = B_FALSE;
8198 
8199 	struct option long_options[] = {
8200 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8201 		{0, 0, 0, 0}
8202 	};
8203 
8204 	/* check options */
8205 	while ((c = getopt_long(argc, argv, "ft", long_options, NULL)) != -1) {
8206 		switch (c) {
8207 		case 'f':
8208 			fault = B_TRUE;
8209 			break;
8210 		case 't':
8211 			istmp = B_TRUE;
8212 			break;
8213 		case ZPOOL_OPTION_POWER:
8214 			is_power_off = B_TRUE;
8215 			break;
8216 		case '?':
8217 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8218 			    optopt);
8219 			usage(B_FALSE);
8220 		}
8221 	}
8222 
8223 	if (is_power_off && fault) {
8224 		(void) fprintf(stderr,
8225 		    gettext("-0 and -f cannot be used together\n"));
8226 		usage(B_FALSE);
8227 	}
8228 
8229 	if (is_power_off && istmp) {
8230 		(void) fprintf(stderr,
8231 		    gettext("-0 and -t cannot be used together\n"));
8232 		usage(B_FALSE);
8233 	}
8234 
8235 	argc -= optind;
8236 	argv += optind;
8237 
8238 	/* get pool name and check number of arguments */
8239 	if (argc < 1) {
8240 		(void) fprintf(stderr, gettext("missing pool name\n"));
8241 		usage(B_FALSE);
8242 	}
8243 	if (argc < 2) {
8244 		(void) fprintf(stderr, gettext("missing device name\n"));
8245 		usage(B_FALSE);
8246 	}
8247 
8248 	poolname = argv[0];
8249 
8250 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8251 		(void) fprintf(stderr, gettext("failed to open pool "
8252 		    "\"%s\"\n"), poolname);
8253 		return (1);
8254 	}
8255 
8256 	for (i = 1; i < argc; i++) {
8257 		uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
8258 		if (is_power_off) {
8259 			/*
8260 			 * Note: we have to power off first, then set REMOVED,
8261 			 * or else zpool_vdev_set_removed_state() returns
8262 			 * EAGAIN.
8263 			 */
8264 			ret = zpool_power_off(zhp, argv[i]);
8265 			if (ret != 0) {
8266 				(void) fprintf(stderr, "%s %s %d\n",
8267 				    gettext("unable to power off slot for"),
8268 				    argv[i], ret);
8269 			}
8270 			(void) zpool_vdev_set_removed_state(zhp, guid,
8271 			    VDEV_AUX_NONE);
8272 
8273 		} else if (fault) {
8274 			vdev_aux_t aux;
8275 			if (istmp == B_FALSE) {
8276 				/* Force the fault to persist across imports */
8277 				aux = VDEV_AUX_EXTERNAL_PERSIST;
8278 			} else {
8279 				aux = VDEV_AUX_EXTERNAL;
8280 			}
8281 
8282 			if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
8283 				ret = 1;
8284 		} else {
8285 			if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
8286 				ret = 1;
8287 		}
8288 	}
8289 
8290 	zpool_close(zhp);
8291 
8292 	return (ret);
8293 }
8294 
8295 /*
8296  * zpool clear [--power] <pool> [device]
8297  *
8298  * Clear all errors associated with a pool or a particular device.
8299  */
8300 int
8301 zpool_do_clear(int argc, char **argv)
8302 {
8303 	int c;
8304 	int ret = 0;
8305 	boolean_t is_power_on = B_FALSE;
8306 	nvlist_t *policy = NULL;
8307 	zpool_handle_t *zhp;
8308 	char *pool, *device;
8309 
8310 	struct option long_options[] = {
8311 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8312 		{0, 0, 0, 0}
8313 	};
8314 
8315 	/* check options */
8316 	while ((c = getopt_long(argc, argv, "", long_options,
8317 	    NULL)) != -1) {
8318 		switch (c) {
8319 		case ZPOOL_OPTION_POWER:
8320 			is_power_on = B_TRUE;
8321 			break;
8322 		case '?':
8323 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8324 			    optopt);
8325 			usage(B_FALSE);
8326 		}
8327 	}
8328 
8329 	if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8330 		is_power_on = B_TRUE;
8331 
8332 	argc -= optind;
8333 	argv += optind;
8334 
8335 	if (argc < 1) {
8336 		(void) fprintf(stderr, gettext("missing pool name\n"));
8337 		usage(B_FALSE);
8338 	}
8339 
8340 	if (argc > 2) {
8341 		(void) fprintf(stderr, gettext("too many arguments\n"));
8342 		usage(B_FALSE);
8343 	}
8344 
8345 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0)
8346 		return (1);
8347 
8348 	pool = argv[0];
8349 	device = argc == 2 ? argv[1] : NULL;
8350 
8351 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
8352 		nvlist_free(policy);
8353 		return (1);
8354 	}
8355 
8356 	if (is_power_on) {
8357 		if (device == NULL) {
8358 			(void) zpool_power_on_pool_and_wait_for_devices(zhp);
8359 		} else {
8360 			(void) zpool_power_on_and_disk_wait(zhp, device);
8361 		}
8362 	}
8363 
8364 	if (zpool_clear(zhp, device, policy) != 0)
8365 		ret = 1;
8366 
8367 	zpool_close(zhp);
8368 
8369 	nvlist_free(policy);
8370 
8371 	return (ret);
8372 }
8373 
8374 /*
8375  * zpool reguid [-g <guid>] <pool>
8376  */
8377 int
8378 zpool_do_reguid(int argc, char **argv)
8379 {
8380 	uint64_t guid;
8381 	uint64_t *guidp = NULL;
8382 	int c;
8383 	char *endptr;
8384 	char *poolname;
8385 	zpool_handle_t *zhp;
8386 	int ret = 0;
8387 
8388 	/* check options */
8389 	while ((c = getopt(argc, argv, "g:")) != -1) {
8390 		switch (c) {
8391 		case 'g':
8392 			errno = 0;
8393 			guid = strtoull(optarg, &endptr, 10);
8394 			if (errno != 0 || *endptr != '\0') {
8395 				(void) fprintf(stderr,
8396 				    gettext("invalid GUID: %s\n"), optarg);
8397 				usage(B_FALSE);
8398 			}
8399 			guidp = &guid;
8400 			break;
8401 		case '?':
8402 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8403 			    optopt);
8404 			usage(B_FALSE);
8405 		}
8406 	}
8407 
8408 	argc -= optind;
8409 	argv += optind;
8410 
8411 	/* get pool name and check number of arguments */
8412 	if (argc < 1) {
8413 		(void) fprintf(stderr, gettext("missing pool name\n"));
8414 		usage(B_FALSE);
8415 	}
8416 
8417 	if (argc > 1) {
8418 		(void) fprintf(stderr, gettext("too many arguments\n"));
8419 		usage(B_FALSE);
8420 	}
8421 
8422 	poolname = argv[0];
8423 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
8424 		return (1);
8425 
8426 	ret = zpool_set_guid(zhp, guidp);
8427 
8428 	zpool_close(zhp);
8429 	return (ret);
8430 }
8431 
8432 
8433 /*
8434  * zpool reopen <pool>
8435  *
8436  * Reopen the pool so that the kernel can update the sizes of all vdevs.
8437  */
8438 int
8439 zpool_do_reopen(int argc, char **argv)
8440 {
8441 	int c;
8442 	int ret = 0;
8443 	boolean_t scrub_restart = B_TRUE;
8444 
8445 	/* check options */
8446 	while ((c = getopt(argc, argv, "n")) != -1) {
8447 		switch (c) {
8448 		case 'n':
8449 			scrub_restart = B_FALSE;
8450 			break;
8451 		case '?':
8452 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8453 			    optopt);
8454 			usage(B_FALSE);
8455 		}
8456 	}
8457 
8458 	argc -= optind;
8459 	argv += optind;
8460 
8461 	/* if argc == 0 we will execute zpool_reopen_one on all pools */
8462 	ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8463 	    B_FALSE, zpool_reopen_one, &scrub_restart);
8464 
8465 	return (ret);
8466 }
8467 
8468 typedef struct scrub_cbdata {
8469 	int	cb_type;
8470 	pool_scrub_cmd_t cb_scrub_cmd;
8471 	pool_scrub_flags_t cb_scrub_flags;
8472 	time_t	cb_date_start;
8473 	time_t	cb_date_end;
8474 } scrub_cbdata_t;
8475 
8476 static boolean_t
8477 zpool_has_checkpoint(zpool_handle_t *zhp)
8478 {
8479 	nvlist_t *config, *nvroot;
8480 
8481 	config = zpool_get_config(zhp, NULL);
8482 
8483 	if (config != NULL) {
8484 		pool_checkpoint_stat_t *pcs = NULL;
8485 		uint_t c;
8486 
8487 		nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
8488 		(void) nvlist_lookup_uint64_array(nvroot,
8489 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
8490 
8491 		if (pcs == NULL || pcs->pcs_state == CS_NONE)
8492 			return (B_FALSE);
8493 
8494 		assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
8495 		    pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
8496 		return (B_TRUE);
8497 	}
8498 
8499 	return (B_FALSE);
8500 }
8501 
8502 static int
8503 scrub_callback(zpool_handle_t *zhp, void *data)
8504 {
8505 	scrub_cbdata_t *cb = data;
8506 	int err;
8507 
8508 	/*
8509 	 * Ignore faulted pools.
8510 	 */
8511 	if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
8512 		(void) fprintf(stderr, gettext("cannot scan '%s': pool is "
8513 		    "currently unavailable\n"), zpool_get_name(zhp));
8514 		return (1);
8515 	}
8516 
8517 	err = zpool_scan_range(zhp, cb->cb_type, cb->cb_scrub_cmd,
8518 	    cb->cb_scrub_flags, cb->cb_date_start, cb->cb_date_end);
8519 	if (err == 0 && zpool_has_checkpoint(zhp) &&
8520 	    cb->cb_type == POOL_SCAN_SCRUB) {
8521 		(void) printf(gettext("warning: will not scrub state that "
8522 		    "belongs to the checkpoint of pool '%s'\n"),
8523 		    zpool_get_name(zhp));
8524 	}
8525 
8526 	return (err != 0);
8527 }
8528 
8529 static int
8530 wait_callback(zpool_handle_t *zhp, void *data)
8531 {
8532 	zpool_wait_activity_t *act = data;
8533 	return (zpool_wait(zhp, *act));
8534 }
8535 
8536 static time_t
8537 date_string_to_sec(const char *timestr, boolean_t rounding)
8538 {
8539 	struct tm tm = {0};
8540 	int adjustment = rounding ? 1 : 0;
8541 
8542 	/* Allow mktime to determine timezone. */
8543 	tm.tm_isdst = -1;
8544 
8545 	if (strptime(timestr, "%Y-%m-%d %H:%M", &tm) == NULL) {
8546 		if (strptime(timestr, "%Y-%m-%d", &tm) == NULL) {
8547 			fprintf(stderr, gettext("Failed to parse the date.\n"));
8548 			usage(B_FALSE);
8549 		}
8550 		adjustment *= 24 * 60 * 60;
8551 	} else {
8552 		adjustment *= 60;
8553 	}
8554 
8555 	return (mktime(&tm) + adjustment);
8556 }
8557 
8558 /*
8559  * zpool scrub [-e | -s | -p | -C | -E | -S | -t] [-w] [-a | <pool> ...]
8560  *
8561  *	-a	Scrub all pools.
8562  *	-e	Only scrub blocks in the error log.
8563  *	-E	End date of scrub.
8564  *	-S	Start date of scrub.
8565  *	-s	Stop.  Stops any in-progress scrub.
8566  *	-p	Pause. Pause in-progress scrub.
8567  *	-w	Wait.  Blocks until scrub has completed.
8568  *	-t	Decompress and decrypt (if key is loaded) scrubbed blocks.
8569  *	-C	Scrub from last saved txg.
8570  */
8571 int
8572 zpool_do_scrub(int argc, char **argv)
8573 {
8574 	int c;
8575 	scrub_cbdata_t cb;
8576 	boolean_t wait = B_FALSE;
8577 	int error;
8578 
8579 	cb.cb_type = POOL_SCAN_SCRUB;
8580 	cb.cb_scrub_cmd = 0;
8581 	cb.cb_scrub_flags = 0;
8582 	cb.cb_date_start = cb.cb_date_end = 0;
8583 
8584 	boolean_t is_error_scrub = B_FALSE;
8585 	boolean_t is_pause = B_FALSE;
8586 	boolean_t is_stop = B_FALSE;
8587 	boolean_t scrub_all = B_FALSE;
8588 
8589 	/* check options */
8590 	while ((c = getopt(argc, argv, "aspweCE:S:t")) != -1) {
8591 		switch (c) {
8592 		case 'a':
8593 			scrub_all = B_TRUE;
8594 			break;
8595 		case 'e':
8596 			is_error_scrub = B_TRUE;
8597 			break;
8598 		case 't':
8599 			cb.cb_scrub_flags |= POOL_SCRUB_THOROUGH;
8600 			break;
8601 		case 'E':
8602 			/*
8603 			 * Round the date. It's better to scrub more data than
8604 			 * less. This also makes the date inclusive.
8605 			 */
8606 			cb.cb_date_end = date_string_to_sec(optarg, B_TRUE);
8607 			break;
8608 		case 's':
8609 			is_stop = B_TRUE;
8610 			break;
8611 		case 'S':
8612 			cb.cb_date_start = date_string_to_sec(optarg, B_FALSE);
8613 			break;
8614 		case 'p':
8615 			is_pause = B_TRUE;
8616 			break;
8617 		case 'w':
8618 			wait = B_TRUE;
8619 			break;
8620 		case 'C':
8621 			cb.cb_scrub_cmd |= POOL_SCRUB_FROM_LAST_TXG;
8622 			break;
8623 		case '?':
8624 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8625 			    optopt);
8626 			usage(B_FALSE);
8627 		}
8628 	}
8629 
8630 	if (is_pause && is_stop) {
8631 		(void) fprintf(stderr, gettext("invalid option "
8632 		    "combination: -s and -p are mutually exclusive\n"));
8633 		usage(B_FALSE);
8634 	} else if (is_error_scrub && is_pause) {
8635 		(void) fprintf(stderr, gettext("invalid option "
8636 		    "combination: -e and -p are mutually exclusive\n"));
8637 		usage(B_FALSE);
8638 	} else if (is_error_scrub && is_stop) {
8639 		(void) fprintf(stderr, gettext("invalid option "
8640 		    "combination: -e and -s are mutually exclusive\n"));
8641 		usage(B_FALSE);
8642 	} else if (is_error_scrub &&
8643 	    (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8644 		(void) fprintf(stderr, gettext("invalid option "
8645 		    "combination: -e and -C are mutually exclusive\n"));
8646 		usage(B_FALSE);
8647 	} else if (is_error_scrub &&
8648 	    (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH)) {
8649 		(void) fprintf(stderr, gettext("invalid option "
8650 		    "combination: -e and -t are mutually exclusive\n"));
8651 		usage(B_FALSE);
8652 	} else if (is_pause && (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8653 		(void) fprintf(stderr, gettext("invalid option "
8654 		    "combination: -p and -C are mutually exclusive\n"));
8655 		usage(B_FALSE);
8656 	} else if (is_pause && (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH)) {
8657 		(void) fprintf(stderr, gettext("invalid option "
8658 		    "combination: -p and -t are mutually exclusive\n"));
8659 		usage(B_FALSE);
8660 	} else if (is_stop && (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8661 		(void) fprintf(stderr, gettext("invalid option "
8662 		    "combination: -s and -C are mutually exclusive\n"));
8663 		usage(B_FALSE);
8664 	} else if (is_stop && (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH)) {
8665 		(void) fprintf(stderr, gettext("invalid option "
8666 		    "combination: -s and -t are mutually exclusive\n"));
8667 		usage(B_FALSE);
8668 	} else {
8669 		if (is_error_scrub)
8670 			cb.cb_type = POOL_SCAN_ERRORSCRUB;
8671 
8672 		if (is_pause) {
8673 			cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
8674 		} else if (is_stop) {
8675 			cb.cb_type = POOL_SCAN_NONE;
8676 		}
8677 	}
8678 
8679 	boolean_t is_thorough =
8680 	    (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH) != 0;
8681 	if ((cb.cb_date_start != 0 || cb.cb_date_end != 0) &&
8682 	    (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8683 		(void) fprintf(stderr, gettext("invalid option "
8684 		    "combination: -C and -S/-E date are mutually "
8685 		    "exclusive\n"));
8686 		usage(B_FALSE);
8687 	} else if ((cb.cb_date_start != 0 || cb.cb_date_end != 0) &&
8688 	    (is_error_scrub || is_stop || is_pause ||
8689 	    (!is_thorough && cb.cb_scrub_cmd != POOL_SCRUB_NORMAL))) {
8690 		(void) fprintf(stderr, gettext("invalid option "
8691 		    "combination: start/end date is available only "
8692 		    "with normal or thorough scrub\n"));
8693 		usage(B_FALSE);
8694 	}
8695 
8696 	if (cb.cb_date_start != 0 && cb.cb_date_end != 0 &&
8697 	    cb.cb_date_start > cb.cb_date_end) {
8698 		(void) fprintf(stderr, gettext("invalid arguments: "
8699 		    "end date has to be later than start date\n"));
8700 		usage(B_FALSE);
8701 	}
8702 
8703 	if (wait && (cb.cb_type == POOL_SCAN_NONE ||
8704 	    cb.cb_scrub_cmd == POOL_SCRUB_PAUSE)) {
8705 		(void) fprintf(stderr, gettext("invalid option combination: "
8706 		    "-w cannot be used with -p or -s\n"));
8707 		usage(B_FALSE);
8708 	}
8709 
8710 	argc -= optind;
8711 	argv += optind;
8712 
8713 	if (argc < 1 && !scrub_all) {
8714 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
8715 		usage(B_FALSE);
8716 	}
8717 
8718 	error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8719 	    B_FALSE, scrub_callback, &cb);
8720 
8721 	if (wait && !error) {
8722 		zpool_wait_activity_t act = ZPOOL_WAIT_SCRUB;
8723 		error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8724 		    B_FALSE, wait_callback, &act);
8725 	}
8726 
8727 	return (error);
8728 }
8729 
8730 /*
8731  * zpool resilver <pool> ...
8732  *
8733  *	Restarts any in-progress resilver
8734  */
8735 int
8736 zpool_do_resilver(int argc, char **argv)
8737 {
8738 	int c;
8739 	scrub_cbdata_t cb;
8740 
8741 	cb.cb_type = POOL_SCAN_RESILVER;
8742 	cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8743 	cb.cb_scrub_flags = 0;
8744 	cb.cb_date_start = cb.cb_date_end = 0;
8745 
8746 	/* check options */
8747 	while ((c = getopt(argc, argv, "")) != -1) {
8748 		switch (c) {
8749 		case '?':
8750 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8751 			    optopt);
8752 			usage(B_FALSE);
8753 		}
8754 	}
8755 
8756 	argc -= optind;
8757 	argv += optind;
8758 
8759 	if (argc < 1) {
8760 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
8761 		usage(B_FALSE);
8762 	}
8763 
8764 	return (for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8765 	    B_FALSE, scrub_callback, &cb));
8766 }
8767 
8768 /*
8769  * zpool trim [-d] [-r <rate>] [-c | -s] <-a | pool> [<device> ...]
8770  *
8771  *	-a		Trim all pools.
8772  *	-c		Cancel. Ends any in-progress trim.
8773  *	-d		Secure trim.  Requires kernel and device support.
8774  *	-r <rate>	Sets the TRIM rate in bytes (per second). Supports
8775  *			adding a multiplier suffix such as 'k' or 'm'.
8776  *	-s		Suspend. TRIM can then be restarted with no flags.
8777  *	-w		Wait. Blocks until trimming has completed.
8778  */
8779 int
8780 zpool_do_trim(int argc, char **argv)
8781 {
8782 	struct option long_options[] = {
8783 		{"cancel",	no_argument,		NULL,	'c'},
8784 		{"secure",	no_argument,		NULL,	'd'},
8785 		{"rate",	required_argument,	NULL,	'r'},
8786 		{"suspend",	no_argument,		NULL,	's'},
8787 		{"wait",	no_argument,		NULL,	'w'},
8788 		{"all",		no_argument,		NULL,	'a'},
8789 		{0, 0, 0, 0}
8790 	};
8791 
8792 	pool_trim_func_t cmd_type = POOL_TRIM_START;
8793 	uint64_t rate = 0;
8794 	boolean_t secure = B_FALSE;
8795 	boolean_t wait = B_FALSE;
8796 	boolean_t trimall = B_FALSE;
8797 	int error;
8798 
8799 	int c;
8800 	while ((c = getopt_long(argc, argv, "acdr:sw", long_options, NULL))
8801 	    != -1) {
8802 		switch (c) {
8803 		case 'a':
8804 			trimall = B_TRUE;
8805 			break;
8806 		case 'c':
8807 			if (cmd_type != POOL_TRIM_START &&
8808 			    cmd_type != POOL_TRIM_CANCEL) {
8809 				(void) fprintf(stderr, gettext("-c cannot be "
8810 				    "combined with other options\n"));
8811 				usage(B_FALSE);
8812 			}
8813 			cmd_type = POOL_TRIM_CANCEL;
8814 			break;
8815 		case 'd':
8816 			if (cmd_type != POOL_TRIM_START) {
8817 				(void) fprintf(stderr, gettext("-d cannot be "
8818 				    "combined with the -c or -s options\n"));
8819 				usage(B_FALSE);
8820 			}
8821 			secure = B_TRUE;
8822 			break;
8823 		case 'r':
8824 			if (cmd_type != POOL_TRIM_START) {
8825 				(void) fprintf(stderr, gettext("-r cannot be "
8826 				    "combined with the -c or -s options\n"));
8827 				usage(B_FALSE);
8828 			}
8829 			if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
8830 				(void) fprintf(stderr, "%s: %s\n",
8831 				    gettext("invalid value for rate"),
8832 				    libzfs_error_description(g_zfs));
8833 				usage(B_FALSE);
8834 			}
8835 			break;
8836 		case 's':
8837 			if (cmd_type != POOL_TRIM_START &&
8838 			    cmd_type != POOL_TRIM_SUSPEND) {
8839 				(void) fprintf(stderr, gettext("-s cannot be "
8840 				    "combined with other options\n"));
8841 				usage(B_FALSE);
8842 			}
8843 			cmd_type = POOL_TRIM_SUSPEND;
8844 			break;
8845 		case 'w':
8846 			wait = B_TRUE;
8847 			break;
8848 		case '?':
8849 			if (optopt != 0) {
8850 				(void) fprintf(stderr,
8851 				    gettext("invalid option '%c'\n"), optopt);
8852 			} else {
8853 				(void) fprintf(stderr,
8854 				    gettext("invalid option '%s'\n"),
8855 				    argv[optind - 1]);
8856 			}
8857 			usage(B_FALSE);
8858 		}
8859 	}
8860 
8861 	argc -= optind;
8862 	argv += optind;
8863 
8864 	trimflags_t trim_flags = {
8865 		.secure = secure,
8866 		.rate = rate,
8867 		.wait = wait,
8868 	};
8869 
8870 	trim_cbdata_t cbdata = {
8871 		.trim_flags = trim_flags,
8872 		.cmd_type = cmd_type
8873 	};
8874 
8875 	if (argc < 1 && !trimall) {
8876 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
8877 		usage(B_FALSE);
8878 	}
8879 
8880 	if (wait && (cmd_type != POOL_TRIM_START)) {
8881 		(void) fprintf(stderr, gettext("-w cannot be used with -c or "
8882 		    "-s options\n"));
8883 		usage(B_FALSE);
8884 	}
8885 
8886 	if (trimall && argc > 0) {
8887 		(void) fprintf(stderr, gettext("-a cannot be combined with "
8888 		    "individual zpools or vdevs\n"));
8889 		usage(B_FALSE);
8890 	}
8891 
8892 	if (argc == 0 && trimall) {
8893 		cbdata.trim_flags.fullpool = B_TRUE;
8894 		/* Trim each pool recursively */
8895 		error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8896 		    B_FALSE, zpool_trim_one, &cbdata);
8897 	} else if (argc == 1) {
8898 		char *poolname = argv[0];
8899 		zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8900 		if (zhp == NULL)
8901 			return (-1);
8902 		/* no individual leaf vdevs specified, so add them all */
8903 		error = zpool_trim_one(zhp, &cbdata);
8904 		zpool_close(zhp);
8905 	} else {
8906 		char *poolname = argv[0];
8907 		zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8908 		if (zhp == NULL)
8909 			return (-1);
8910 		/* leaf vdevs specified, trim only those */
8911 		cbdata.trim_flags.fullpool = B_FALSE;
8912 		nvlist_t *vdevs = fnvlist_alloc();
8913 		for (int i = 1; i < argc; i++) {
8914 			fnvlist_add_boolean(vdevs, argv[i]);
8915 		}
8916 		error = zpool_trim(zhp, cbdata.cmd_type, vdevs,
8917 		    &cbdata.trim_flags);
8918 		fnvlist_free(vdevs);
8919 		zpool_close(zhp);
8920 	}
8921 
8922 	return (error);
8923 }
8924 
8925 static const char *condense_types[] = {
8926 	POOL_CONDENSE_LOG_SPACEMAP,
8927 #ifdef ZFS_DEBUG
8928 	"debug",
8929 #endif
8930 	NULL,
8931 };
8932 
8933 typedef struct {
8934 	const char *cmd;
8935 	const char *type;
8936 } condense_cb_t;
8937 
8938 static int
8939 condense_cb(zpool_handle_t *zhp, void *data)
8940 {
8941 	condense_cb_t *cb = data;
8942 	if (cb->type != NULL)
8943 		return (zpool_condense(zhp, cb->cmd, cb->type));
8944 
8945 	int err = 0;
8946 	for (uint_t i = 0; condense_types[i] != NULL; i++) {
8947 #ifdef ZFS_DEBUG
8948 		/*
8949 		 * Skip the debug type when no type is specificed. This is
8950 		 * the "condense everything" mode, and people _do_ run debug
8951 		 * builds, and we don't want them to be accidentally running
8952 		 * the debug condense op.
8953 		 */
8954 		if (strcmp(condense_types[i], "debug") == 0)
8955 			continue;
8956 #endif
8957 		err = zpool_condense(zhp, cb->cmd, condense_types[i]);
8958 
8959 		/*
8960 		 * Quietly ignore ENOTSUP, so we don't fail all condense types
8961 		 * just because one isn't supporte.d
8962 		 */
8963 		if (err != 0 && err != ENOTSUP)
8964 			break;
8965 	}
8966 
8967 	return (err);
8968 }
8969 
8970 /*
8971  * zpool condense [-t <type>] [-c | -w] [-a | <pool> ...]
8972  *
8973  *	-t <type>	What to condense.
8974  *	-a		Condense all pools.
8975  *	-c		Cancel. Ends any in-progress condense.
8976  *	-w		Wait. Blocks until condense has completed.
8977  *
8978  * Condense (flush, garbage-collect) the pool metadata on the specfied pools.
8979  */
8980 static int
8981 zpool_do_condense(int argc, char **argv)
8982 {
8983 	struct option long_options[] = {
8984 		{"type",	required_argument,	NULL,	't'},
8985 		{"all",		no_argument,		NULL,	'a'},
8986 		{"cancel",	no_argument,		NULL,	'c'},
8987 		{"wait",	no_argument,		NULL,	'w'},
8988 		{"types",	no_argument,		NULL,
8989 		    ZPOOL_OPTION_CONDENSE_LIST_TYPES},
8990 		{0, 0, 0, 0}
8991 	};
8992 
8993 	condense_cb_t cb = {
8994 		.cmd = "start",
8995 		.type = NULL,
8996 	};
8997 
8998 	boolean_t cancel = B_FALSE;
8999 	boolean_t all_pools = B_FALSE;
9000 	boolean_t wait = B_FALSE;
9001 
9002 	int c;
9003 	while ((c = getopt_long(argc, argv, "at:cw", long_options, NULL))
9004 	    != -1) {
9005 		switch (c) {
9006 		case 'a':
9007 			all_pools = B_TRUE;
9008 			break;
9009 		case 't': {
9010 			for (uint_t i = 0; condense_types[i] != NULL; i++) {
9011 				if (strcmp(condense_types[i], optarg) == 0) {
9012 					cb.type = condense_types[i];
9013 					break;
9014 				}
9015 			}
9016 			if (cb.type == NULL) {
9017 				(void) fprintf(stderr,
9018 				    gettext("invalid condense type '%s'\n"),
9019 				    optarg);
9020 				usage(B_FALSE);
9021 			}
9022 			break;
9023 		}
9024 		case 'c':
9025 			cb.cmd = "cancel";
9026 			cancel = B_TRUE;
9027 			break;
9028 		case 'w':
9029 			wait = B_TRUE;
9030 			break;
9031 		case ZPOOL_OPTION_CONDENSE_LIST_TYPES:
9032 			for (uint_t i = 0; condense_types[i] != NULL; i++)
9033 				printf("%s\n", condense_types[i]);
9034 			return (0);
9035 		case '?':
9036 			if (optopt != 0) {
9037 				(void) fprintf(stderr,
9038 				    gettext("invalid option '%c'\n"), optopt);
9039 			} else {
9040 				(void) fprintf(stderr,
9041 				    gettext("invalid option '%s'\n"),
9042 				    argv[optind - 1]);
9043 			}
9044 			usage(B_FALSE);
9045 		}
9046 	}
9047 
9048 	argc -= optind;
9049 	argv += optind;
9050 
9051 	if (argc < 1 && !all_pools) {
9052 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
9053 		usage(B_FALSE);
9054 		return (-1);
9055 	}
9056 
9057 	if (wait && cancel) {
9058 		(void) fprintf(stderr, gettext("-w cannot be used with -c\n"));
9059 		usage(B_FALSE);
9060 	}
9061 
9062 	int error = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9063 	    B_FALSE, condense_cb, &cb);
9064 
9065 	if (wait && !error) {
9066 		zpool_wait_activity_t act = ZPOOL_WAIT_CONDENSE;
9067 		error = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9068 		    B_FALSE, wait_callback, &act);
9069 	}
9070 
9071 	return (error);
9072 }
9073 
9074 
9075 /*
9076  * Converts a total number of seconds to a human readable string broken
9077  * down in to days/hours/minutes/seconds.
9078  */
9079 static void
9080 secs_to_dhms(uint64_t total, char *buf)
9081 {
9082 	uint64_t days = total / 60 / 60 / 24;
9083 	uint64_t hours = (total / 60 / 60) % 24;
9084 	uint64_t mins = (total / 60) % 60;
9085 	uint64_t secs = (total % 60);
9086 
9087 	if (days > 0) {
9088 		(void) sprintf(buf, "%llu days %02llu:%02llu:%02llu",
9089 		    (u_longlong_t)days, (u_longlong_t)hours,
9090 		    (u_longlong_t)mins, (u_longlong_t)secs);
9091 	} else {
9092 		(void) sprintf(buf, "%02llu:%02llu:%02llu",
9093 		    (u_longlong_t)hours, (u_longlong_t)mins,
9094 		    (u_longlong_t)secs);
9095 	}
9096 }
9097 
9098 /*
9099  * Print out detailed error scrub status.
9100  */
9101 static void
9102 print_err_scrub_status(pool_scan_stat_t *ps)
9103 {
9104 	time_t start, end, pause;
9105 	uint64_t total_secs_left;
9106 	uint64_t secs_left, mins_left, hours_left, days_left;
9107 	uint64_t examined, to_be_examined;
9108 
9109 	if (ps == NULL || ps->pss_error_scrub_func != POOL_SCAN_ERRORSCRUB) {
9110 		return;
9111 	}
9112 
9113 	(void) printf(gettext(" scrub: "));
9114 
9115 	start = ps->pss_error_scrub_start;
9116 	end = ps->pss_error_scrub_end;
9117 	pause = ps->pss_pass_error_scrub_pause;
9118 	examined = ps->pss_error_scrub_examined;
9119 	to_be_examined = ps->pss_error_scrub_to_be_examined;
9120 
9121 	assert(ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB);
9122 
9123 	if (ps->pss_error_scrub_state == DSS_FINISHED) {
9124 		total_secs_left = end - start;
9125 		days_left = total_secs_left / 60 / 60 / 24;
9126 		hours_left = (total_secs_left / 60 / 60) % 24;
9127 		mins_left = (total_secs_left / 60) % 60;
9128 		secs_left = (total_secs_left % 60);
9129 
9130 		(void) printf(gettext("scrubbed %llu error blocks in %llu days "
9131 		    "%02llu:%02llu:%02llu on %s"), (u_longlong_t)examined,
9132 		    (u_longlong_t)days_left, (u_longlong_t)hours_left,
9133 		    (u_longlong_t)mins_left, (u_longlong_t)secs_left,
9134 		    ctime(&end));
9135 
9136 		return;
9137 	} else if (ps->pss_error_scrub_state == DSS_CANCELED) {
9138 		(void) printf(gettext("error scrub canceled on %s"),
9139 		    ctime(&end));
9140 		return;
9141 	}
9142 	assert(ps->pss_error_scrub_state == DSS_ERRORSCRUBBING);
9143 
9144 	/* Error scrub is in progress. */
9145 	if (pause == 0) {
9146 		(void) printf(gettext("error scrub in progress since %s"),
9147 		    ctime(&start));
9148 	} else {
9149 		(void) printf(gettext("error scrub paused since %s"),
9150 		    ctime(&pause));
9151 		(void) printf(gettext("\terror scrub started on %s"),
9152 		    ctime(&start));
9153 	}
9154 
9155 	double fraction_done = (double)examined / (to_be_examined + examined);
9156 	(void) printf(gettext("\t%.2f%% done, issued I/O for %llu error"
9157 	    " blocks"), 100 * fraction_done, (u_longlong_t)examined);
9158 
9159 	(void) printf("\n");
9160 }
9161 
9162 /*
9163  * Print out detailed scrub status.
9164  */
9165 static void
9166 print_scan_scrub_resilver_status(pool_scan_stat_t *ps, boolean_t is_thorough)
9167 {
9168 	time_t start, end, pause;
9169 	uint64_t pass_scanned, scanned, pass_issued, issued, total_s, total_i;
9170 	uint64_t elapsed, scan_rate, issue_rate;
9171 	double fraction_done;
9172 	char processed_buf[7], scanned_buf[7], issued_buf[7], total_s_buf[7];
9173 	char total_i_buf[7], srate_buf[7], irate_buf[7], time_buf[32];
9174 
9175 	printf("  ");
9176 	(void) printf_color(ANSI_BOLD, gettext("scan:"));
9177 	printf(" ");
9178 
9179 	/* If there's never been a scan, there's not much to say. */
9180 	if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
9181 	    ps->pss_func >= POOL_SCAN_FUNCS) {
9182 		(void) printf(gettext("none requested\n"));
9183 		return;
9184 	}
9185 
9186 	start = ps->pss_start_time;
9187 	end = ps->pss_end_time;
9188 	pause = ps->pss_pass_scrub_pause;
9189 
9190 	zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
9191 
9192 	int is_resilver = ps->pss_func == POOL_SCAN_RESILVER;
9193 	int is_scrub = ps->pss_func == POOL_SCAN_SCRUB;
9194 	assert(is_resilver || is_scrub);
9195 
9196 	/* Scan is finished or canceled. */
9197 	if (ps->pss_state == DSS_FINISHED) {
9198 		secs_to_dhms(end - start, time_buf);
9199 
9200 		if (is_scrub) {
9201 			if (is_thorough) {
9202 				(void) printf(gettext("thorough scrub "
9203 				    "repaired %s in %s with %llu errors on %s"),
9204 				    processed_buf, time_buf,
9205 				    (u_longlong_t)ps->pss_errors, ctime(&end));
9206 			} else {
9207 				(void) printf(gettext("scrub repaired %s "
9208 				    "in %s with %llu errors on %s"),
9209 				    processed_buf, time_buf,
9210 				    (u_longlong_t)ps->pss_errors, ctime(&end));
9211 			}
9212 		} else if (is_resilver) {
9213 			(void) printf(gettext("resilvered %s "
9214 			    "in %s with %llu errors on %s"), processed_buf,
9215 			    time_buf, (u_longlong_t)ps->pss_errors,
9216 			    ctime(&end));
9217 		}
9218 		return;
9219 	} else if (ps->pss_state == DSS_CANCELED) {
9220 		if (is_scrub) {
9221 			if (is_thorough) {
9222 				(void) printf(gettext("thorough scrub canceled "
9223 				    "on %s"), ctime(&end));
9224 			} else {
9225 				(void) printf(gettext("scrub canceled on %s"),
9226 				    ctime(&end));
9227 			}
9228 		} else if (is_resilver) {
9229 			(void) printf(gettext("resilver canceled on %s"),
9230 			    ctime(&end));
9231 		}
9232 		return;
9233 	}
9234 
9235 	assert(ps->pss_state == DSS_SCANNING);
9236 
9237 	/* Scan is in progress. Resilvers can't be paused. */
9238 	if (is_scrub) {
9239 		if (pause == 0) {
9240 			if (is_thorough) {
9241 				(void) printf(gettext("thorough scrub "
9242 				    "in progress since %s"), ctime(&start));
9243 			} else {
9244 				(void) printf(gettext("scrub in progress "
9245 				    "since %s"), ctime(&start));
9246 			}
9247 		} else {
9248 			if (is_thorough) {
9249 				(void) printf(gettext("thorough scrub paused "
9250 				    "since %s"), ctime(&pause));
9251 				(void) printf(gettext("\tthorough scrub "
9252 				    "started on %s"), ctime(&start));
9253 			} else {
9254 				(void) printf(gettext("scrub paused since %s"),
9255 				    ctime(&pause));
9256 				(void) printf(gettext("\tscrub started on %s"),
9257 				    ctime(&start));
9258 			}
9259 		}
9260 	} else if (is_resilver) {
9261 		(void) printf(gettext("resilver in progress since %s"),
9262 		    ctime(&start));
9263 	}
9264 
9265 	scanned = ps->pss_examined;
9266 	pass_scanned = ps->pss_pass_exam;
9267 	issued = ps->pss_issued;
9268 	pass_issued = ps->pss_pass_issued;
9269 	total_s = ps->pss_to_examine;
9270 	total_i = ps->pss_to_examine - ps->pss_skipped;
9271 
9272 	/* we are only done with a block once we have issued the IO for it */
9273 	fraction_done = (double)issued / total_i;
9274 
9275 	/* elapsed time for this pass, rounding up to 1 if it's 0 */
9276 	elapsed = time(NULL) - ps->pss_pass_start;
9277 	elapsed -= ps->pss_pass_scrub_spent_paused;
9278 	elapsed = (elapsed != 0) ? elapsed : 1;
9279 
9280 	scan_rate = pass_scanned / elapsed;
9281 	issue_rate = pass_issued / elapsed;
9282 
9283 	/* format all of the numbers we will be reporting */
9284 	zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
9285 	zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
9286 	zfs_nicebytes(total_s, total_s_buf, sizeof (total_s_buf));
9287 	zfs_nicebytes(total_i, total_i_buf, sizeof (total_i_buf));
9288 
9289 	/* do not print estimated time if we have a paused scrub */
9290 	(void) printf(gettext("\t%s / %s scanned"), scanned_buf, total_s_buf);
9291 	if (pause == 0 && scan_rate > 0) {
9292 		zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
9293 		(void) printf(gettext(" at %s/s"), srate_buf);
9294 	}
9295 	(void) printf(gettext(", %s / %s issued"), issued_buf, total_i_buf);
9296 	if (pause == 0 && issue_rate > 0) {
9297 		zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
9298 		(void) printf(gettext(" at %s/s"), irate_buf);
9299 	}
9300 	(void) printf(gettext("\n"));
9301 
9302 	if (is_resilver) {
9303 		(void) printf(gettext("\t%s resilvered, %.2f%% done"),
9304 		    processed_buf, 100 * fraction_done);
9305 	} else if (is_scrub) {
9306 		(void) printf(gettext("\t%s repaired, %.2f%% done"),
9307 		    processed_buf, 100 * fraction_done);
9308 	}
9309 
9310 	if (pause == 0) {
9311 		/*
9312 		 * Only provide an estimate iff:
9313 		 * 1) we haven't yet issued all we expected, and
9314 		 * 2) the issue rate exceeds 10 MB/s, and
9315 		 * 3) it's either:
9316 		 *    a) a resilver which has started repairs, or
9317 		 *    b) a scrub which has entered the issue phase.
9318 		 */
9319 		if (total_i >= issued && issue_rate >= 10 * 1024 * 1024 &&
9320 		    ((is_resilver && ps->pss_processed > 0) ||
9321 		    (is_scrub && issued > 0))) {
9322 			secs_to_dhms((total_i - issued) / issue_rate, time_buf);
9323 			(void) printf(gettext(", %s to go\n"), time_buf);
9324 		} else {
9325 			(void) printf(gettext(", no estimated "
9326 			    "completion time\n"));
9327 		}
9328 	} else {
9329 		(void) printf(gettext("\n"));
9330 	}
9331 }
9332 
9333 static void
9334 print_rebuild_status_impl(vdev_rebuild_stat_t *vrs, uint_t c, char *vdev_name)
9335 {
9336 	if (vrs == NULL || vrs->vrs_state == VDEV_REBUILD_NONE)
9337 		return;
9338 
9339 	printf("  ");
9340 	(void) printf_color(ANSI_BOLD, gettext("scan:"));
9341 	printf(" ");
9342 
9343 	uint64_t bytes_scanned = vrs->vrs_bytes_scanned;
9344 	uint64_t bytes_issued = vrs->vrs_bytes_issued;
9345 	uint64_t bytes_rebuilt = vrs->vrs_bytes_rebuilt;
9346 	uint64_t bytes_est_s = vrs->vrs_bytes_est;
9347 	uint64_t bytes_est_i = vrs->vrs_bytes_est;
9348 	if (c > offsetof(vdev_rebuild_stat_t, vrs_pass_bytes_skipped) / 8)
9349 		bytes_est_i -= vrs->vrs_pass_bytes_skipped;
9350 	uint64_t scan_rate = (vrs->vrs_pass_bytes_scanned /
9351 	    (vrs->vrs_pass_time_ms + 1)) * 1000;
9352 	uint64_t issue_rate = (vrs->vrs_pass_bytes_issued /
9353 	    (vrs->vrs_pass_time_ms + 1)) * 1000;
9354 	double scan_pct = MIN((double)bytes_scanned * 100 /
9355 	    (bytes_est_s + 1), 100);
9356 
9357 	/* Format all of the numbers we will be reporting */
9358 	char bytes_scanned_buf[7], bytes_issued_buf[7];
9359 	char bytes_rebuilt_buf[7], bytes_est_s_buf[7], bytes_est_i_buf[7];
9360 	char scan_rate_buf[7], issue_rate_buf[7], time_buf[32];
9361 	zfs_nicebytes(bytes_scanned, bytes_scanned_buf,
9362 	    sizeof (bytes_scanned_buf));
9363 	zfs_nicebytes(bytes_issued, bytes_issued_buf,
9364 	    sizeof (bytes_issued_buf));
9365 	zfs_nicebytes(bytes_rebuilt, bytes_rebuilt_buf,
9366 	    sizeof (bytes_rebuilt_buf));
9367 	zfs_nicebytes(bytes_est_s, bytes_est_s_buf, sizeof (bytes_est_s_buf));
9368 	zfs_nicebytes(bytes_est_i, bytes_est_i_buf, sizeof (bytes_est_i_buf));
9369 
9370 	time_t start = vrs->vrs_start_time;
9371 	time_t end = vrs->vrs_end_time;
9372 
9373 	/* Rebuild is finished or canceled. */
9374 	if (vrs->vrs_state == VDEV_REBUILD_COMPLETE) {
9375 		secs_to_dhms(vrs->vrs_scan_time_ms / 1000, time_buf);
9376 		(void) printf(gettext("resilvered (%s) %s in %s "
9377 		    "with %llu errors on %s"), vdev_name, bytes_rebuilt_buf,
9378 		    time_buf, (u_longlong_t)vrs->vrs_errors, ctime(&end));
9379 		return;
9380 	} else if (vrs->vrs_state == VDEV_REBUILD_CANCELED) {
9381 		(void) printf(gettext("resilver (%s) canceled on %s"),
9382 		    vdev_name, ctime(&end));
9383 		return;
9384 	} else if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9385 		(void) printf(gettext("resilver (%s) in progress since %s"),
9386 		    vdev_name, ctime(&start));
9387 	}
9388 
9389 	assert(vrs->vrs_state == VDEV_REBUILD_ACTIVE);
9390 
9391 	(void) printf(gettext("\t%s / %s scanned"), bytes_scanned_buf,
9392 	    bytes_est_s_buf);
9393 	if (scan_rate > 0) {
9394 		zfs_nicebytes(scan_rate, scan_rate_buf, sizeof (scan_rate_buf));
9395 		(void) printf(gettext(" at %s/s"), scan_rate_buf);
9396 	}
9397 	(void) printf(gettext(", %s / %s issued"), bytes_issued_buf,
9398 	    bytes_est_i_buf);
9399 	if (issue_rate > 0) {
9400 		zfs_nicebytes(issue_rate, issue_rate_buf,
9401 		    sizeof (issue_rate_buf));
9402 		(void) printf(gettext(" at %s/s"), issue_rate_buf);
9403 	}
9404 	(void) printf(gettext("\n"));
9405 
9406 	(void) printf(gettext("\t%s resilvered, %.2f%% done"),
9407 	    bytes_rebuilt_buf, scan_pct);
9408 
9409 	if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9410 		if (bytes_est_s >= bytes_scanned &&
9411 		    scan_rate >= 10 * 1024 * 1024) {
9412 			secs_to_dhms((bytes_est_s - bytes_scanned) / scan_rate,
9413 			    time_buf);
9414 			(void) printf(gettext(", %s to go\n"), time_buf);
9415 		} else {
9416 			(void) printf(gettext(", no estimated "
9417 			    "completion time\n"));
9418 		}
9419 	} else {
9420 		(void) printf(gettext("\n"));
9421 	}
9422 }
9423 
9424 /*
9425  * Print rebuild status for top-level vdevs.
9426  */
9427 static void
9428 print_rebuild_status(zpool_handle_t *zhp, nvlist_t *nvroot)
9429 {
9430 	nvlist_t **child;
9431 	uint_t children;
9432 
9433 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9434 	    &child, &children) != 0)
9435 		children = 0;
9436 
9437 	for (uint_t c = 0; c < children; c++) {
9438 		vdev_rebuild_stat_t *vrs;
9439 		uint_t i;
9440 
9441 		if (nvlist_lookup_uint64_array(child[c],
9442 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9443 			char *name = zpool_vdev_name(g_zfs, zhp,
9444 			    child[c], VDEV_NAME_TYPE_ID);
9445 			print_rebuild_status_impl(vrs, i, name);
9446 			free(name);
9447 		}
9448 	}
9449 }
9450 
9451 /*
9452  * As we don't scrub checkpointed blocks, we want to warn the user that we
9453  * skipped scanning some blocks if a checkpoint exists or existed at any
9454  * time during the scan.  If a sequential instead of healing reconstruction
9455  * was performed then the blocks were reconstructed.  However, their checksums
9456  * have not been verified so we still print the warning.
9457  */
9458 static void
9459 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
9460 {
9461 	if (ps == NULL || pcs == NULL)
9462 		return;
9463 
9464 	if (pcs->pcs_state == CS_NONE ||
9465 	    pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
9466 		return;
9467 
9468 	assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
9469 
9470 	if (ps->pss_state == DSS_NONE)
9471 		return;
9472 
9473 	if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
9474 	    ps->pss_end_time < pcs->pcs_start_time)
9475 		return;
9476 
9477 	if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
9478 		(void) printf(gettext("    scan warning: skipped blocks "
9479 		    "that are only referenced by the checkpoint.\n"));
9480 	} else {
9481 		assert(ps->pss_state == DSS_SCANNING);
9482 		(void) printf(gettext("    scan warning: skipping blocks "
9483 		    "that are only referenced by the checkpoint.\n"));
9484 	}
9485 }
9486 
9487 /*
9488  * Returns B_TRUE if there is an active rebuild in progress.  Otherwise,
9489  * B_FALSE is returned and 'rebuild_end_time' is set to the end time for
9490  * the last completed (or cancelled) rebuild.
9491  */
9492 static boolean_t
9493 check_rebuilding(nvlist_t *nvroot, uint64_t *rebuild_end_time)
9494 {
9495 	nvlist_t **child;
9496 	uint_t children;
9497 	boolean_t rebuilding = B_FALSE;
9498 	uint64_t end_time = 0;
9499 
9500 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9501 	    &child, &children) != 0)
9502 		children = 0;
9503 
9504 	for (uint_t c = 0; c < children; c++) {
9505 		vdev_rebuild_stat_t *vrs;
9506 		uint_t i;
9507 
9508 		if (nvlist_lookup_uint64_array(child[c],
9509 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9510 
9511 			if (vrs->vrs_end_time > end_time)
9512 				end_time = vrs->vrs_end_time;
9513 
9514 			if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9515 				rebuilding = B_TRUE;
9516 				end_time = 0;
9517 				break;
9518 			}
9519 		}
9520 	}
9521 
9522 	if (rebuild_end_time != NULL)
9523 		*rebuild_end_time = end_time;
9524 
9525 	return (rebuilding);
9526 }
9527 
9528 static void
9529 vdev_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9530     int depth, boolean_t isspare, char *parent, nvlist_t *item)
9531 {
9532 	nvlist_t *vds, **child, *ch = NULL;
9533 	uint_t vsc, children;
9534 	vdev_stat_t *vs;
9535 	char *vname;
9536 	uint64_t notpresent;
9537 	const char *type, *path;
9538 
9539 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
9540 	    &child, &children) != 0)
9541 		children = 0;
9542 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
9543 	    (uint64_t **)&vs, &vsc) == 0);
9544 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
9545 	if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9546 		return;
9547 
9548 	if (cb->cb_print_unhealthy && depth > 0 &&
9549 	    for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
9550 		return;
9551 	}
9552 	vname = zpool_vdev_name(g_zfs, zhp, nv,
9553 	    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9554 	vds = fnvlist_alloc();
9555 	fill_vdev_info(vds, zhp, vname, B_FALSE, cb->cb_json_as_int);
9556 	if (cb->cb_flat_vdevs && parent != NULL) {
9557 		fnvlist_add_string(vds, "parent", parent);
9558 	}
9559 
9560 	if (isspare) {
9561 		if (vs->vs_aux == VDEV_AUX_SPARED) {
9562 			fnvlist_add_string(vds, "state", "INUSE");
9563 			used_by_other(zhp, nv, vds);
9564 		} else if (vs->vs_state == VDEV_STATE_HEALTHY)
9565 			fnvlist_add_string(vds, "state", "AVAIL");
9566 	} else {
9567 		if (vs->vs_alloc) {
9568 			nice_num_str_nvlist(vds, "alloc_space", vs->vs_alloc,
9569 			    cb->cb_literal, cb->cb_json_as_int,
9570 			    ZFS_NICENUM_BYTES);
9571 		}
9572 		if (vs->vs_space) {
9573 			nice_num_str_nvlist(vds, "total_space", vs->vs_space,
9574 			    cb->cb_literal, cb->cb_json_as_int,
9575 			    ZFS_NICENUM_BYTES);
9576 		}
9577 		if (vs->vs_dspace) {
9578 			nice_num_str_nvlist(vds, "def_space", vs->vs_dspace,
9579 			    cb->cb_literal, cb->cb_json_as_int,
9580 			    ZFS_NICENUM_BYTES);
9581 		}
9582 		if (vs->vs_rsize) {
9583 			nice_num_str_nvlist(vds, "rep_dev_size", vs->vs_rsize,
9584 			    cb->cb_literal, cb->cb_json_as_int,
9585 			    ZFS_NICENUM_BYTES);
9586 		}
9587 		if (vs->vs_esize) {
9588 			nice_num_str_nvlist(vds, "ex_dev_size", vs->vs_esize,
9589 			    cb->cb_literal, cb->cb_json_as_int,
9590 			    ZFS_NICENUM_BYTES);
9591 		}
9592 		if (vs->vs_self_healed) {
9593 			nice_num_str_nvlist(vds, "self_healed",
9594 			    vs->vs_self_healed, cb->cb_literal,
9595 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9596 		}
9597 		if (vs->vs_pspace) {
9598 			nice_num_str_nvlist(vds, "phys_space", vs->vs_pspace,
9599 			    cb->cb_literal, cb->cb_json_as_int,
9600 			    ZFS_NICENUM_BYTES);
9601 		}
9602 		nice_num_str_nvlist(vds, "read_errors", vs->vs_read_errors,
9603 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9604 		nice_num_str_nvlist(vds, "write_errors", vs->vs_write_errors,
9605 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9606 		nice_num_str_nvlist(vds, "checksum_errors",
9607 		    vs->vs_checksum_errors, cb->cb_literal,
9608 		    cb->cb_json_as_int, ZFS_NICENUM_1024);
9609 		if (vs->vs_scan_processed) {
9610 			nice_num_str_nvlist(vds, "scan_processed",
9611 			    vs->vs_scan_processed, cb->cb_literal,
9612 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9613 		}
9614 		if (vs->vs_checkpoint_space) {
9615 			nice_num_str_nvlist(vds, "checkpoint_space",
9616 			    vs->vs_checkpoint_space, cb->cb_literal,
9617 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9618 		}
9619 		if (vs->vs_resilver_deferred) {
9620 			nice_num_str_nvlist(vds, "resilver_deferred",
9621 			    vs->vs_resilver_deferred, B_TRUE,
9622 			    cb->cb_json_as_int, ZFS_NICENUM_1024);
9623 		}
9624 		if (children == 0) {
9625 			nice_num_str_nvlist(vds, "slow_ios", vs->vs_slow_ios,
9626 			    cb->cb_literal, cb->cb_json_as_int,
9627 			    ZFS_NICENUM_1024);
9628 		}
9629 		if (cb->cb_print_power) {
9630 			if (children == 0)  {
9631 				/* Only leaf vdevs have physical slots */
9632 				switch (zpool_power_current_state(zhp, (char *)
9633 				    fnvlist_lookup_string(nv,
9634 				    ZPOOL_CONFIG_PATH))) {
9635 				case 0:
9636 					fnvlist_add_string(vds, "power_state",
9637 					    "off");
9638 					break;
9639 				case 1:
9640 					fnvlist_add_string(vds, "power_state",
9641 					    "on");
9642 					break;
9643 				default:
9644 					fnvlist_add_string(vds, "power_state",
9645 					    "-");
9646 				}
9647 			} else {
9648 				fnvlist_add_string(vds, "power_state", "-");
9649 			}
9650 		}
9651 	}
9652 
9653 	if (cb->cb_print_dio_verify) {
9654 		nice_num_str_nvlist(vds, "dio_verify_errors",
9655 		    vs->vs_dio_verify_errors, cb->cb_literal,
9656 		    cb->cb_json_as_int, ZFS_NICENUM_1024);
9657 	}
9658 
9659 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
9660 	    &notpresent) == 0) {
9661 		nice_num_str_nvlist(vds, ZPOOL_CONFIG_NOT_PRESENT,
9662 		    1, B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9663 		fnvlist_add_string(vds, "was",
9664 		    fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH));
9665 	} else if (vs->vs_aux != VDEV_AUX_NONE) {
9666 		fnvlist_add_string(vds, "aux", vdev_aux_str[vs->vs_aux]);
9667 	} else if (children == 0 && !isspare &&
9668 	    getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
9669 	    VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
9670 	    vs->vs_configured_ashift < vs->vs_physical_ashift) {
9671 		nice_num_str_nvlist(vds, "configured_ashift",
9672 		    vs->vs_configured_ashift, B_TRUE, cb->cb_json_as_int,
9673 		    ZFS_NICENUM_1024);
9674 		nice_num_str_nvlist(vds, "physical_ashift",
9675 		    vs->vs_physical_ashift, B_TRUE, cb->cb_json_as_int,
9676 		    ZFS_NICENUM_1024);
9677 	}
9678 	if (vs->vs_scan_removing != 0) {
9679 		nice_num_str_nvlist(vds, "removing", vs->vs_scan_removing,
9680 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9681 	} else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
9682 		nice_num_str_nvlist(vds, "noalloc", vs->vs_noalloc,
9683 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9684 	}
9685 
9686 	if (cb->vcdl != NULL) {
9687 		if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
9688 			zpool_nvlist_cmd(cb->vcdl, zpool_get_name(zhp),
9689 			    path, vds);
9690 		}
9691 	}
9692 
9693 	if (children == 0) {
9694 		if (cb->cb_print_vdev_init) {
9695 			if (vs->vs_initialize_state != 0) {
9696 				uint64_t st = vs->vs_initialize_state;
9697 				fnvlist_add_string(vds, "init_state",
9698 				    vdev_init_state_str[st]);
9699 				nice_num_str_nvlist(vds, "initialized",
9700 				    vs->vs_initialize_bytes_done,
9701 				    cb->cb_literal, cb->cb_json_as_int,
9702 				    ZFS_NICENUM_BYTES);
9703 				nice_num_str_nvlist(vds, "to_initialize",
9704 				    vs->vs_initialize_bytes_est,
9705 				    cb->cb_literal, cb->cb_json_as_int,
9706 				    ZFS_NICENUM_BYTES);
9707 				nice_num_str_nvlist(vds, "init_time",
9708 				    vs->vs_initialize_action_time,
9709 				    cb->cb_literal, cb->cb_json_as_int,
9710 				    ZFS_NICE_TIMESTAMP);
9711 				nice_num_str_nvlist(vds, "init_errors",
9712 				    vs->vs_initialize_errors,
9713 				    cb->cb_literal, cb->cb_json_as_int,
9714 				    ZFS_NICENUM_1024);
9715 			} else {
9716 				fnvlist_add_string(vds, "init_state",
9717 				    "UNINITIALIZED");
9718 			}
9719 		}
9720 		if (cb->cb_print_vdev_trim) {
9721 			if (vs->vs_trim_notsup == 0) {
9722 					if (vs->vs_trim_state != 0) {
9723 					uint64_t st = vs->vs_trim_state;
9724 					fnvlist_add_string(vds, "trim_state",
9725 					    vdev_trim_state_str[st]);
9726 					nice_num_str_nvlist(vds, "trimmed",
9727 					    vs->vs_trim_bytes_done,
9728 					    cb->cb_literal, cb->cb_json_as_int,
9729 					    ZFS_NICENUM_BYTES);
9730 					nice_num_str_nvlist(vds, "to_trim",
9731 					    vs->vs_trim_bytes_est,
9732 					    cb->cb_literal, cb->cb_json_as_int,
9733 					    ZFS_NICENUM_BYTES);
9734 					nice_num_str_nvlist(vds, "trim_time",
9735 					    vs->vs_trim_action_time,
9736 					    cb->cb_literal, cb->cb_json_as_int,
9737 					    ZFS_NICE_TIMESTAMP);
9738 					nice_num_str_nvlist(vds, "trim_errors",
9739 					    vs->vs_trim_errors,
9740 					    cb->cb_literal, cb->cb_json_as_int,
9741 					    ZFS_NICENUM_1024);
9742 				} else
9743 					fnvlist_add_string(vds, "trim_state",
9744 					    "UNTRIMMED");
9745 			}
9746 			nice_num_str_nvlist(vds, "trim_notsup",
9747 			    vs->vs_trim_notsup, B_TRUE,
9748 			    cb->cb_json_as_int, ZFS_NICENUM_1024);
9749 		}
9750 	} else {
9751 		ch = fnvlist_alloc();
9752 	}
9753 
9754 	if (cb->cb_flat_vdevs && children == 0) {
9755 		fnvlist_add_nvlist(item, vname, vds);
9756 	}
9757 
9758 	for (int c = 0; c < children; c++) {
9759 		uint64_t islog = B_FALSE, ishole = B_FALSE;
9760 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9761 		    &islog);
9762 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
9763 		    &ishole);
9764 		if (islog || ishole)
9765 			continue;
9766 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
9767 			continue;
9768 		if (cb->cb_flat_vdevs) {
9769 			vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9770 			    vname, item);
9771 		}
9772 		vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9773 		    vname, ch);
9774 	}
9775 
9776 	if (ch != NULL) {
9777 		if (!nvlist_empty(ch))
9778 			fnvlist_add_nvlist(vds, "vdevs", ch);
9779 		fnvlist_free(ch);
9780 	}
9781 	fnvlist_add_nvlist(item, vname, vds);
9782 	fnvlist_free(vds);
9783 	free(vname);
9784 }
9785 
9786 static void
9787 class_vdevs_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9788     const char *class, nvlist_t *item)
9789 {
9790 	uint_t c, children;
9791 	nvlist_t **child;
9792 	nvlist_t *class_obj = NULL;
9793 
9794 	if (!cb->cb_flat_vdevs)
9795 		class_obj = fnvlist_alloc();
9796 
9797 	assert(zhp != NULL || !cb->cb_verbose);
9798 
9799 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
9800 	    &children) != 0)
9801 		return;
9802 
9803 	for (c = 0; c < children; c++) {
9804 		uint64_t is_log = B_FALSE;
9805 		const char *bias = NULL;
9806 		const char *type = NULL;
9807 		char *name = zpool_vdev_name(g_zfs, zhp, child[c],
9808 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9809 
9810 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9811 		    &is_log);
9812 
9813 		if (is_log) {
9814 			bias = (char *)VDEV_ALLOC_CLASS_LOGS;
9815 		} else {
9816 			(void) nvlist_lookup_string(child[c],
9817 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
9818 			(void) nvlist_lookup_string(child[c],
9819 			    ZPOOL_CONFIG_TYPE, &type);
9820 		}
9821 
9822 		if (bias == NULL || strcmp(bias, class) != 0)
9823 			continue;
9824 		if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9825 			continue;
9826 
9827 		if (cb->cb_flat_vdevs) {
9828 			vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9829 			    NULL, item);
9830 		} else {
9831 			vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9832 			    NULL, class_obj);
9833 		}
9834 		free(name);
9835 	}
9836 	if (!cb->cb_flat_vdevs) {
9837 		if (!nvlist_empty(class_obj))
9838 			fnvlist_add_nvlist(item, class, class_obj);
9839 		fnvlist_free(class_obj);
9840 	}
9841 }
9842 
9843 static void
9844 l2cache_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9845     nvlist_t *item)
9846 {
9847 	nvlist_t *l2c = NULL, **l2cache;
9848 	uint_t nl2cache;
9849 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
9850 	    &l2cache, &nl2cache) == 0) {
9851 		if (nl2cache == 0)
9852 			return;
9853 		if (!cb->cb_flat_vdevs)
9854 			l2c = fnvlist_alloc();
9855 		for (int i = 0; i < nl2cache; i++) {
9856 			if (cb->cb_flat_vdevs) {
9857 				vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9858 				    B_FALSE, NULL, item);
9859 			} else {
9860 				vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9861 				    B_FALSE, NULL, l2c);
9862 			}
9863 		}
9864 	}
9865 	if (!cb->cb_flat_vdevs) {
9866 		if (!nvlist_empty(l2c))
9867 			fnvlist_add_nvlist(item, "l2cache", l2c);
9868 		fnvlist_free(l2c);
9869 	}
9870 }
9871 
9872 static void
9873 spares_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9874     nvlist_t *item)
9875 {
9876 	nvlist_t *sp = NULL, **spares;
9877 	uint_t nspares;
9878 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
9879 	    &spares, &nspares) == 0) {
9880 		if (nspares == 0)
9881 			return;
9882 		if (!cb->cb_flat_vdevs)
9883 			sp = fnvlist_alloc();
9884 		for (int i = 0; i < nspares; i++) {
9885 			if (cb->cb_flat_vdevs) {
9886 				vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9887 				    NULL, item);
9888 			} else {
9889 				vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9890 				    NULL, sp);
9891 			}
9892 		}
9893 	}
9894 	if (!cb->cb_flat_vdevs) {
9895 		if (!nvlist_empty(sp))
9896 			fnvlist_add_nvlist(item, "spares", sp);
9897 		fnvlist_free(sp);
9898 	}
9899 }
9900 
9901 static void
9902 errors_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9903 {
9904 	uint64_t nerr;
9905 	nvlist_t *config = zpool_get_config(zhp, NULL);
9906 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
9907 	    &nerr) == 0) {
9908 		nice_num_str_nvlist(item, ZPOOL_CONFIG_ERRCOUNT, nerr,
9909 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9910 		if (nerr != 0 && cb->cb_verbose) {
9911 			nvlist_t *nverrlist = NULL;
9912 			if (zpool_get_errlog(zhp, &nverrlist) == 0) {
9913 				int i = 0;
9914 				int count = 0;
9915 				size_t len = MAXPATHLEN * 2;
9916 				nvpair_t *elem = NULL;
9917 
9918 				for (nvpair_t *pair =
9919 				    nvlist_next_nvpair(nverrlist, NULL);
9920 				    pair != NULL;
9921 				    pair = nvlist_next_nvpair(nverrlist, pair))
9922 					count++;
9923 				char **errl = (char **)malloc(
9924 				    count * sizeof (char *));
9925 
9926 				while ((elem = nvlist_next_nvpair(nverrlist,
9927 				    elem)) != NULL) {
9928 					nvlist_t *nv;
9929 					uint64_t dsobj, obj;
9930 
9931 					verify(nvpair_value_nvlist(elem,
9932 					    &nv) == 0);
9933 					verify(nvlist_lookup_uint64(nv,
9934 					    ZPOOL_ERR_DATASET, &dsobj) == 0);
9935 					verify(nvlist_lookup_uint64(nv,
9936 					    ZPOOL_ERR_OBJECT, &obj) == 0);
9937 					errl[i] = safe_malloc(len);
9938 					zpool_obj_to_path(zhp, dsobj, obj,
9939 					    errl[i++], len);
9940 				}
9941 				nvlist_free(nverrlist);
9942 				fnvlist_add_string_array(item, "errlist",
9943 				    (const char **)errl, count);
9944 				for (int i = 0; i < count; ++i)
9945 					free(errl[i]);
9946 				free(errl);
9947 			} else
9948 				fnvlist_add_string(item, "errlist",
9949 				    strerror(errno));
9950 		}
9951 	}
9952 }
9953 
9954 static void
9955 ddt_stats_nvlist(ddt_stat_t *dds, status_cbdata_t *cb, nvlist_t *item)
9956 {
9957 	nice_num_str_nvlist(item, "blocks", dds->dds_blocks,
9958 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9959 	nice_num_str_nvlist(item, "logical_size", dds->dds_lsize,
9960 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9961 	nice_num_str_nvlist(item, "physical_size", dds->dds_psize,
9962 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9963 	nice_num_str_nvlist(item, "deflated_size", dds->dds_dsize,
9964 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9965 	nice_num_str_nvlist(item, "ref_blocks", dds->dds_ref_blocks,
9966 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9967 	nice_num_str_nvlist(item, "ref_lsize", dds->dds_ref_lsize,
9968 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9969 	nice_num_str_nvlist(item, "ref_psize", dds->dds_ref_psize,
9970 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9971 	nice_num_str_nvlist(item, "ref_dsize", dds->dds_ref_dsize,
9972 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9973 }
9974 
9975 static void
9976 dedup_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9977 {
9978 	nvlist_t *config;
9979 	if (cb->cb_dedup_stats) {
9980 		ddt_histogram_t *ddh;
9981 		ddt_stat_t *dds;
9982 		ddt_object_t *ddo;
9983 		nvlist_t *ddt_stat, *ddt_obj, *dedup;
9984 		uint_t c;
9985 		uint64_t cspace_prop;
9986 
9987 		config = zpool_get_config(zhp, NULL);
9988 		if (nvlist_lookup_uint64_array(config,
9989 		    ZPOOL_CONFIG_DDT_OBJ_STATS, (uint64_t **)&ddo, &c) != 0)
9990 			return;
9991 
9992 		dedup = fnvlist_alloc();
9993 		ddt_obj = fnvlist_alloc();
9994 		nice_num_str_nvlist(dedup, "obj_count", ddo->ddo_count,
9995 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9996 		if (ddo->ddo_count == 0) {
9997 			fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
9998 			    ddt_obj);
9999 			fnvlist_add_nvlist(item, "dedup_stats", dedup);
10000 			fnvlist_free(ddt_obj);
10001 			fnvlist_free(dedup);
10002 			return;
10003 		} else {
10004 			nice_num_str_nvlist(dedup, "dspace", ddo->ddo_dspace,
10005 			    cb->cb_literal, cb->cb_json_as_int,
10006 			    ZFS_NICENUM_1024);
10007 			nice_num_str_nvlist(dedup, "mspace", ddo->ddo_mspace,
10008 			    cb->cb_literal, cb->cb_json_as_int,
10009 			    ZFS_NICENUM_1024);
10010 			/*
10011 			 * Squash cached size into in-core size to handle race.
10012 			 * Only include cached size if it is available.
10013 			 */
10014 			cspace_prop = zpool_get_prop_int(zhp,
10015 			    ZPOOL_PROP_DEDUPCACHED, NULL);
10016 			cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
10017 			nice_num_str_nvlist(dedup, "cspace", cspace_prop,
10018 			    cb->cb_literal, cb->cb_json_as_int,
10019 			    ZFS_NICENUM_1024);
10020 		}
10021 
10022 		ddt_stat = fnvlist_alloc();
10023 		if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
10024 		    (uint64_t **)&dds, &c) == 0) {
10025 			nvlist_t *total = fnvlist_alloc();
10026 			if (dds->dds_blocks == 0)
10027 				fnvlist_add_string(total, "blocks", "0");
10028 			else
10029 				ddt_stats_nvlist(dds, cb, total);
10030 			fnvlist_add_nvlist(ddt_stat, "total", total);
10031 			fnvlist_free(total);
10032 		}
10033 		if (nvlist_lookup_uint64_array(config,
10034 		    ZPOOL_CONFIG_DDT_HISTOGRAM, (uint64_t **)&ddh, &c) == 0) {
10035 			nvlist_t *hist = fnvlist_alloc();
10036 			nvlist_t *entry = NULL;
10037 			char buf[16];
10038 			for (int h = 0; h < 64; h++) {
10039 				if (ddh->ddh_stat[h].dds_blocks != 0) {
10040 					entry = fnvlist_alloc();
10041 					ddt_stats_nvlist(&ddh->ddh_stat[h], cb,
10042 					    entry);
10043 					(void) snprintf(buf, 16, "%d", h);
10044 					fnvlist_add_nvlist(hist, buf, entry);
10045 					fnvlist_free(entry);
10046 				}
10047 			}
10048 			if (!nvlist_empty(hist))
10049 				fnvlist_add_nvlist(ddt_stat, "histogram", hist);
10050 			fnvlist_free(hist);
10051 		}
10052 
10053 		if (!nvlist_empty(ddt_obj)) {
10054 			fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
10055 			    ddt_obj);
10056 		}
10057 		fnvlist_free(ddt_obj);
10058 		if (!nvlist_empty(ddt_stat)) {
10059 			fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_STATS,
10060 			    ddt_stat);
10061 		}
10062 		fnvlist_free(ddt_stat);
10063 		if (!nvlist_empty(dedup))
10064 			fnvlist_add_nvlist(item, "dedup_stats", dedup);
10065 		fnvlist_free(dedup);
10066 	}
10067 }
10068 
10069 static void
10070 raidz_expand_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
10071     nvlist_t *nvroot, nvlist_t *item)
10072 {
10073 	uint_t c;
10074 	pool_raidz_expand_stat_t *pres = NULL;
10075 	if (nvlist_lookup_uint64_array(nvroot,
10076 	    ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c) == 0) {
10077 		nvlist_t **child;
10078 		uint_t children;
10079 		nvlist_t *nv = fnvlist_alloc();
10080 		verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10081 		    &child, &children) == 0);
10082 		assert(pres->pres_expanding_vdev < children);
10083 		char *name =
10084 		    zpool_vdev_name(g_zfs, zhp,
10085 		    child[pres->pres_expanding_vdev], 0);
10086 		fill_vdev_info(nv, zhp, name, B_FALSE, cb->cb_json_as_int);
10087 		fnvlist_add_string(nv, "state",
10088 		    pool_scan_state_str[pres->pres_state]);
10089 		nice_num_str_nvlist(nv, "expanding_vdev",
10090 		    pres->pres_expanding_vdev, B_TRUE, cb->cb_json_as_int,
10091 		    ZFS_NICENUM_1024);
10092 		nice_num_str_nvlist(nv, "start_time", pres->pres_start_time,
10093 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10094 		nice_num_str_nvlist(nv, "end_time", pres->pres_end_time,
10095 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10096 		nice_num_str_nvlist(nv, "to_reflow", pres->pres_to_reflow,
10097 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10098 		nice_num_str_nvlist(nv, "reflowed", pres->pres_reflowed,
10099 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10100 		nice_num_str_nvlist(nv, "waiting_for_resilver",
10101 		    pres->pres_waiting_for_resilver, B_TRUE,
10102 		    cb->cb_json_as_int, ZFS_NICENUM_1024);
10103 		fnvlist_add_nvlist(item, ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, nv);
10104 		fnvlist_free(nv);
10105 		free(name);
10106 	}
10107 }
10108 
10109 static void
10110 checkpoint_status_nvlist(nvlist_t *nvroot, status_cbdata_t *cb,
10111     nvlist_t *item)
10112 {
10113 	uint_t c;
10114 	pool_checkpoint_stat_t *pcs = NULL;
10115 	if (nvlist_lookup_uint64_array(nvroot,
10116 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c) == 0) {
10117 		nvlist_t *nv = fnvlist_alloc();
10118 		fnvlist_add_string(nv, "state",
10119 		    checkpoint_state_str[pcs->pcs_state]);
10120 		nice_num_str_nvlist(nv, "start_time",
10121 		    pcs->pcs_start_time, cb->cb_literal, cb->cb_json_as_int,
10122 		    ZFS_NICE_TIMESTAMP);
10123 		nice_num_str_nvlist(nv, "space",
10124 		    pcs->pcs_space, cb->cb_literal, cb->cb_json_as_int,
10125 		    ZFS_NICENUM_BYTES);
10126 		fnvlist_add_nvlist(item, ZPOOL_CONFIG_CHECKPOINT_STATS, nv);
10127 		fnvlist_free(nv);
10128 	}
10129 }
10130 
10131 static void
10132 removal_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
10133     nvlist_t *nvroot, nvlist_t *item)
10134 {
10135 	uint_t c;
10136 	pool_removal_stat_t *prs = NULL;
10137 	if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_REMOVAL_STATS,
10138 	    (uint64_t **)&prs, &c) == 0) {
10139 		if (prs->prs_state != DSS_NONE) {
10140 			nvlist_t **child;
10141 			uint_t children;
10142 			verify(nvlist_lookup_nvlist_array(nvroot,
10143 			    ZPOOL_CONFIG_CHILDREN, &child, &children) == 0);
10144 			assert(prs->prs_removing_vdev < children);
10145 			char *vdev_name = zpool_vdev_name(g_zfs, zhp,
10146 			    child[prs->prs_removing_vdev], B_TRUE);
10147 			nvlist_t *nv = fnvlist_alloc();
10148 			fill_vdev_info(nv, zhp, vdev_name, B_FALSE,
10149 			    cb->cb_json_as_int);
10150 			fnvlist_add_string(nv, "state",
10151 			    pool_scan_state_str[prs->prs_state]);
10152 			nice_num_str_nvlist(nv, "removing_vdev",
10153 			    prs->prs_removing_vdev, B_TRUE, cb->cb_json_as_int,
10154 			    ZFS_NICENUM_1024);
10155 			nice_num_str_nvlist(nv, "start_time",
10156 			    prs->prs_start_time, cb->cb_literal,
10157 			    cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10158 			nice_num_str_nvlist(nv, "end_time", prs->prs_end_time,
10159 			    cb->cb_literal, cb->cb_json_as_int,
10160 			    ZFS_NICE_TIMESTAMP);
10161 			nice_num_str_nvlist(nv, "to_copy", prs->prs_to_copy,
10162 			    cb->cb_literal, cb->cb_json_as_int,
10163 			    ZFS_NICENUM_BYTES);
10164 			nice_num_str_nvlist(nv, "copied", prs->prs_copied,
10165 			    cb->cb_literal, cb->cb_json_as_int,
10166 			    ZFS_NICENUM_BYTES);
10167 			nice_num_str_nvlist(nv, "mapping_memory",
10168 			    prs->prs_mapping_memory, cb->cb_literal,
10169 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10170 			fnvlist_add_nvlist(item,
10171 			    ZPOOL_CONFIG_REMOVAL_STATS, nv);
10172 			fnvlist_free(nv);
10173 			free(vdev_name);
10174 		}
10175 	}
10176 }
10177 
10178 static void
10179 condense_status_nvlist(nvlist_t *nvroot, status_cbdata_t *cb, nvlist_t *item)
10180 {
10181 	nvlist_t *cnv = NULL;
10182 	nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_CONDENSE_STATS, &cnv);
10183 	if (cnv == NULL)
10184 		return;
10185 
10186 	nvlist_t *onv = fnvlist_alloc();
10187 	for (nvpair_t *nvp = nvlist_next_nvpair(cnv, NULL);
10188 	    nvp != NULL; nvp = nvlist_next_nvpair(cnv, nvp)) {
10189 		const char *type = nvpair_name(nvp);
10190 		nvlist_t *tnv = fnvpair_value_nvlist(nvp);
10191 
10192 		uint64_t start_time = fnvlist_lookup_uint64(tnv, "start_time");
10193 		if (start_time == 0)
10194 			continue;
10195 
10196 		uint64_t end_time = fnvlist_lookup_uint64(tnv, "end_time");
10197 		uint64_t processed = fnvlist_lookup_uint64(tnv, "processed");
10198 		uint64_t total = fnvlist_lookup_uint64(tnv, "total");
10199 
10200 		nvlist_t *nv = fnvlist_alloc();
10201 		nice_num_str_nvlist(nv, "start_time", start_time,
10202 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10203 		if (end_time > 0)
10204 			nice_num_str_nvlist(nv, "end_time", end_time,
10205 			    cb->cb_literal, cb->cb_json_as_int,
10206 			    ZFS_NICE_TIMESTAMP);
10207 		nice_num_str_nvlist(nv, "processed", processed,
10208 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10209 		nice_num_str_nvlist(nv, "total", total,
10210 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10211 
10212 		fnvlist_add_string(nv, "unit", condense_unit(type));
10213 
10214 		fnvlist_add_nvlist(onv, type, nv);
10215 		fnvlist_free(nv);
10216 	}
10217 
10218 	if (fnvlist_num_pairs(onv))
10219 		fnvlist_add_nvlist(item, "condense", onv);
10220 
10221 	fnvlist_free(onv);
10222 }
10223 
10224 
10225 static void
10226 scan_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
10227     nvlist_t *nvroot, nvlist_t *item)
10228 {
10229 	pool_scan_stat_t *ps = NULL;
10230 	uint_t c;
10231 	nvlist_t *scan = fnvlist_alloc();
10232 	nvlist_t **child;
10233 	uint_t children;
10234 
10235 	if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
10236 	    (uint64_t **)&ps, &c) == 0) {
10237 		fnvlist_add_string(scan, "function",
10238 		    pool_scan_func_str[ps->pss_func]);
10239 		fnvlist_add_string(scan, "state",
10240 		    pool_scan_state_str[ps->pss_state]);
10241 		nice_num_str_nvlist(scan, "start_time", ps->pss_start_time,
10242 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10243 		nice_num_str_nvlist(scan, "end_time", ps->pss_end_time,
10244 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10245 		nice_num_str_nvlist(scan, "to_examine", ps->pss_to_examine,
10246 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10247 		nice_num_str_nvlist(scan, "examined", ps->pss_examined,
10248 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10249 		nice_num_str_nvlist(scan, "skipped", ps->pss_skipped,
10250 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10251 		nice_num_str_nvlist(scan, "processed", ps->pss_processed,
10252 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10253 		nice_num_str_nvlist(scan, "errors", ps->pss_errors,
10254 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10255 		nice_num_str_nvlist(scan, "bytes_per_scan", ps->pss_pass_exam,
10256 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10257 		nice_num_str_nvlist(scan, "pass_start", ps->pss_pass_start,
10258 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
10259 		nice_num_str_nvlist(scan, "scrub_pause",
10260 		    ps->pss_pass_scrub_pause, cb->cb_literal,
10261 		    cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10262 		nice_num_str_nvlist(scan, "scrub_spent_paused",
10263 		    ps->pss_pass_scrub_spent_paused,
10264 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
10265 		nice_num_str_nvlist(scan, "issued_bytes_per_scan",
10266 		    ps->pss_pass_issued, cb->cb_literal,
10267 		    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10268 		nice_num_str_nvlist(scan, "issued", ps->pss_issued,
10269 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10270 		if (ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB &&
10271 		    ps->pss_error_scrub_start > ps->pss_start_time) {
10272 			fnvlist_add_string(scan, "err_scrub_func",
10273 			    pool_scan_func_str[ps->pss_error_scrub_func]);
10274 			fnvlist_add_string(scan, "err_scrub_state",
10275 			    pool_scan_state_str[ps->pss_error_scrub_state]);
10276 			nice_num_str_nvlist(scan, "err_scrub_start_time",
10277 			    ps->pss_error_scrub_start,
10278 			    cb->cb_literal, cb->cb_json_as_int,
10279 			    ZFS_NICE_TIMESTAMP);
10280 			nice_num_str_nvlist(scan, "err_scrub_end_time",
10281 			    ps->pss_error_scrub_end,
10282 			    cb->cb_literal, cb->cb_json_as_int,
10283 			    ZFS_NICE_TIMESTAMP);
10284 			nice_num_str_nvlist(scan, "err_scrub_examined",
10285 			    ps->pss_error_scrub_examined,
10286 			    cb->cb_literal, cb->cb_json_as_int,
10287 			    ZFS_NICENUM_1024);
10288 			nice_num_str_nvlist(scan, "err_scrub_to_examine",
10289 			    ps->pss_error_scrub_to_be_examined,
10290 			    cb->cb_literal, cb->cb_json_as_int,
10291 			    ZFS_NICENUM_1024);
10292 			nice_num_str_nvlist(scan, "err_scrub_pause",
10293 			    ps->pss_pass_error_scrub_pause,
10294 			    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
10295 		}
10296 	}
10297 
10298 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10299 	    &child, &children) == 0) {
10300 		vdev_rebuild_stat_t *vrs;
10301 		uint_t i;
10302 		char *name;
10303 		nvlist_t *nv;
10304 		nvlist_t *rebuild = fnvlist_alloc();
10305 		uint64_t st;
10306 		for (uint_t c = 0; c < children; c++) {
10307 			if (nvlist_lookup_uint64_array(child[c],
10308 			    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs,
10309 			    &i) == 0) {
10310 				if (vrs->vrs_state != VDEV_REBUILD_NONE) {
10311 					nv = fnvlist_alloc();
10312 					name = zpool_vdev_name(g_zfs, zhp,
10313 					    child[c], VDEV_NAME_TYPE_ID);
10314 					fill_vdev_info(nv, zhp, name, B_FALSE,
10315 					    cb->cb_json_as_int);
10316 					st = vrs->vrs_state;
10317 					fnvlist_add_string(nv, "state",
10318 					    vdev_rebuild_state_str[st]);
10319 					nice_num_str_nvlist(nv, "start_time",
10320 					    vrs->vrs_start_time, cb->cb_literal,
10321 					    cb->cb_json_as_int,
10322 					    ZFS_NICE_TIMESTAMP);
10323 					nice_num_str_nvlist(nv, "end_time",
10324 					    vrs->vrs_end_time, cb->cb_literal,
10325 					    cb->cb_json_as_int,
10326 					    ZFS_NICE_TIMESTAMP);
10327 					nice_num_str_nvlist(nv, "scan_time",
10328 					    vrs->vrs_scan_time_ms * 1000000,
10329 					    cb->cb_literal, cb->cb_json_as_int,
10330 					    ZFS_NICENUM_TIME);
10331 					nice_num_str_nvlist(nv, "scanned",
10332 					    vrs->vrs_bytes_scanned,
10333 					    cb->cb_literal, cb->cb_json_as_int,
10334 					    ZFS_NICENUM_BYTES);
10335 					nice_num_str_nvlist(nv, "issued",
10336 					    vrs->vrs_bytes_issued,
10337 					    cb->cb_literal, cb->cb_json_as_int,
10338 					    ZFS_NICENUM_BYTES);
10339 					nice_num_str_nvlist(nv, "rebuilt",
10340 					    vrs->vrs_bytes_rebuilt,
10341 					    cb->cb_literal, cb->cb_json_as_int,
10342 					    ZFS_NICENUM_BYTES);
10343 					nice_num_str_nvlist(nv, "to_scan",
10344 					    vrs->vrs_bytes_est, cb->cb_literal,
10345 					    cb->cb_json_as_int,
10346 					    ZFS_NICENUM_BYTES);
10347 					nice_num_str_nvlist(nv, "errors",
10348 					    vrs->vrs_errors, cb->cb_literal,
10349 					    cb->cb_json_as_int,
10350 					    ZFS_NICENUM_1024);
10351 					nice_num_str_nvlist(nv, "pass_time",
10352 					    vrs->vrs_pass_time_ms * 1000000,
10353 					    cb->cb_literal, cb->cb_json_as_int,
10354 					    ZFS_NICENUM_TIME);
10355 					nice_num_str_nvlist(nv, "pass_scanned",
10356 					    vrs->vrs_pass_bytes_scanned,
10357 					    cb->cb_literal, cb->cb_json_as_int,
10358 					    ZFS_NICENUM_BYTES);
10359 					nice_num_str_nvlist(nv, "pass_issued",
10360 					    vrs->vrs_pass_bytes_issued,
10361 					    cb->cb_literal, cb->cb_json_as_int,
10362 					    ZFS_NICENUM_BYTES);
10363 					nice_num_str_nvlist(nv, "pass_skipped",
10364 					    vrs->vrs_pass_bytes_skipped,
10365 					    cb->cb_literal, cb->cb_json_as_int,
10366 					    ZFS_NICENUM_BYTES);
10367 					fnvlist_add_nvlist(rebuild, name, nv);
10368 					free(name);
10369 				}
10370 			}
10371 		}
10372 		if (!nvlist_empty(rebuild))
10373 			fnvlist_add_nvlist(scan, "rebuild_stats", rebuild);
10374 		fnvlist_free(rebuild);
10375 	}
10376 
10377 	if (!nvlist_empty(scan))
10378 		fnvlist_add_nvlist(item, ZPOOL_CONFIG_SCAN_STATS, scan);
10379 	fnvlist_free(scan);
10380 }
10381 
10382 /*
10383  * Print the scan status.
10384  */
10385 static void
10386 print_scan_status(zpool_handle_t *zhp, nvlist_t *nvroot)
10387 {
10388 	uint64_t rebuild_end_time = 0, resilver_end_time = 0;
10389 	boolean_t have_resilver = B_FALSE, have_scrub = B_FALSE;
10390 	boolean_t have_errorscrub = B_FALSE;
10391 	boolean_t active_resilver = B_FALSE;
10392 	pool_checkpoint_stat_t *pcs = NULL;
10393 	pool_scan_stat_t *ps = NULL;
10394 	uint_t c;
10395 	boolean_t is_thorough = B_FALSE;
10396 	time_t scrub_start = 0, errorscrub_start = 0;
10397 
10398 	if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
10399 	    (uint64_t **)&ps, &c) == 0) {
10400 		if (ps->pss_func == POOL_SCAN_RESILVER) {
10401 			resilver_end_time = ps->pss_end_time;
10402 			active_resilver = (ps->pss_state == DSS_SCANNING);
10403 		}
10404 
10405 		have_resilver = (ps->pss_func == POOL_SCAN_RESILVER);
10406 		have_scrub = (ps->pss_func == POOL_SCAN_SCRUB);
10407 		scrub_start = ps->pss_start_time;
10408 		if (POOL_SCAN_STAT_VALID(pss_pass_scrub_flags, c) &&
10409 		    (ps->pss_pass_scrub_flags & POOL_SCRUB_THOROUGH) != 0)
10410 			is_thorough = B_TRUE;
10411 		if (POOL_SCAN_STAT_VALID(pss_pass_error_scrub_pause, c)) {
10412 			have_errorscrub = (ps->pss_error_scrub_func ==
10413 			    POOL_SCAN_ERRORSCRUB);
10414 			errorscrub_start = ps->pss_error_scrub_start;
10415 		}
10416 	}
10417 
10418 	boolean_t active_rebuild = check_rebuilding(nvroot, &rebuild_end_time);
10419 	boolean_t have_rebuild = (active_rebuild || (rebuild_end_time > 0));
10420 
10421 	/* Always print the scrub status when available. */
10422 	if (have_scrub && scrub_start > errorscrub_start)
10423 		print_scan_scrub_resilver_status(ps, is_thorough);
10424 	else if (have_errorscrub && errorscrub_start >= scrub_start)
10425 		print_err_scrub_status(ps);
10426 
10427 	/*
10428 	 * When there is an active resilver or rebuild print its status.
10429 	 * Otherwise print the status of the last resilver or rebuild.
10430 	 */
10431 	if (active_resilver || (!active_rebuild && have_resilver &&
10432 	    resilver_end_time && resilver_end_time > rebuild_end_time)) {
10433 		print_scan_scrub_resilver_status(ps, is_thorough);
10434 	} else if (active_rebuild || (!active_resilver && have_rebuild &&
10435 	    rebuild_end_time && rebuild_end_time > resilver_end_time)) {
10436 		print_rebuild_status(zhp, nvroot);
10437 	}
10438 
10439 	(void) nvlist_lookup_uint64_array(nvroot,
10440 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
10441 	print_checkpoint_scan_warning(ps, pcs);
10442 }
10443 
10444 /*
10445  * Print out detailed removal status.
10446  */
10447 static void
10448 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
10449 {
10450 	char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
10451 	time_t start, end;
10452 	nvlist_t *config, *nvroot;
10453 	nvlist_t **child;
10454 	uint_t children;
10455 	char *vdev_name;
10456 
10457 	if (prs == NULL || prs->prs_state == DSS_NONE)
10458 		return;
10459 
10460 	/*
10461 	 * Determine name of vdev.
10462 	 */
10463 	config = zpool_get_config(zhp, NULL);
10464 	nvroot = fnvlist_lookup_nvlist(config,
10465 	    ZPOOL_CONFIG_VDEV_TREE);
10466 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10467 	    &child, &children) == 0);
10468 	assert(prs->prs_removing_vdev < children);
10469 	vdev_name = zpool_vdev_name(g_zfs, zhp,
10470 	    child[prs->prs_removing_vdev], B_TRUE);
10471 
10472 	(void) printf_color(ANSI_BOLD, gettext("remove: "));
10473 
10474 	start = prs->prs_start_time;
10475 	end = prs->prs_end_time;
10476 	zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
10477 
10478 	/*
10479 	 * Removal is finished or canceled.
10480 	 */
10481 	if (prs->prs_state == DSS_FINISHED) {
10482 		uint64_t minutes_taken = (end - start) / 60;
10483 
10484 		(void) printf(gettext("Removal of vdev %llu copied %s "
10485 		    "in %lluh%um, completed on %s"),
10486 		    (longlong_t)prs->prs_removing_vdev,
10487 		    copied_buf,
10488 		    (u_longlong_t)(minutes_taken / 60),
10489 		    (uint_t)(minutes_taken % 60),
10490 		    ctime((time_t *)&end));
10491 	} else if (prs->prs_state == DSS_CANCELED) {
10492 		(void) printf(gettext("Removal of %s canceled on %s"),
10493 		    vdev_name, ctime(&end));
10494 	} else {
10495 		uint64_t copied, total, elapsed, rate, mins_left, hours_left;
10496 		double fraction_done;
10497 
10498 		assert(prs->prs_state == DSS_SCANNING);
10499 
10500 		/*
10501 		 * Removal is in progress.
10502 		 */
10503 		(void) printf(gettext(
10504 		    "Evacuation of %s in progress since %s"),
10505 		    vdev_name, ctime(&start));
10506 
10507 		copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
10508 		total = prs->prs_to_copy;
10509 		fraction_done = (double)copied / total;
10510 
10511 		/* elapsed time for this pass */
10512 		elapsed = time(NULL) - prs->prs_start_time;
10513 		elapsed = elapsed > 0 ? elapsed : 1;
10514 		rate = copied / elapsed;
10515 		rate = rate > 0 ? rate : 1;
10516 		mins_left = ((total - copied) / rate) / 60;
10517 		hours_left = mins_left / 60;
10518 
10519 		zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10520 		zfs_nicenum(total, total_buf, sizeof (total_buf));
10521 		zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10522 
10523 		/*
10524 		 * do not print estimated time if hours_left is more than
10525 		 * 30 days
10526 		 */
10527 		(void) printf(gettext(
10528 		    "\t%s copied out of %s at %s/s, %.2f%% done"),
10529 		    examined_buf, total_buf, rate_buf, 100 * fraction_done);
10530 		if (hours_left < (30 * 24)) {
10531 			(void) printf(gettext(", %lluh%um to go\n"),
10532 			    (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
10533 		} else {
10534 			(void) printf(gettext(
10535 			    ", (copy is slow, no estimated time)\n"));
10536 		}
10537 	}
10538 	free(vdev_name);
10539 
10540 	if (prs->prs_mapping_memory > 0) {
10541 		char mem_buf[7];
10542 		zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
10543 		(void) printf(gettext(
10544 		    "\t%s memory used for removed device mappings\n"),
10545 		    mem_buf);
10546 	}
10547 }
10548 
10549 /*
10550  * Print out detailed raidz expansion status.
10551  */
10552 static void
10553 print_raidz_expand_status(zpool_handle_t *zhp, pool_raidz_expand_stat_t *pres)
10554 {
10555 	char copied_buf[7];
10556 
10557 	if (pres == NULL || pres->pres_state == DSS_NONE)
10558 		return;
10559 
10560 	/*
10561 	 * Determine name of vdev.
10562 	 */
10563 	nvlist_t *config = zpool_get_config(zhp, NULL);
10564 	nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
10565 	    ZPOOL_CONFIG_VDEV_TREE);
10566 	nvlist_t **child;
10567 	uint_t children;
10568 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10569 	    &child, &children) == 0);
10570 	assert(pres->pres_expanding_vdev < children);
10571 
10572 	(void) printf_color(ANSI_BOLD, gettext("expand: "));
10573 
10574 	time_t start = pres->pres_start_time;
10575 	time_t end = pres->pres_end_time;
10576 	char *vname =
10577 	    zpool_vdev_name(g_zfs, zhp, child[pres->pres_expanding_vdev], 0);
10578 	zfs_nicenum(pres->pres_reflowed, copied_buf, sizeof (copied_buf));
10579 
10580 	/*
10581 	 * Expansion is finished or canceled.
10582 	 */
10583 	if (pres->pres_state == DSS_FINISHED) {
10584 		char time_buf[32];
10585 		secs_to_dhms(end - start, time_buf);
10586 
10587 		(void) printf(gettext("expanded %s-%u copied %s in %s, "
10588 		    "on %s"), vname, (int)pres->pres_expanding_vdev,
10589 		    copied_buf, time_buf, ctime((time_t *)&end));
10590 	} else {
10591 		char examined_buf[7], total_buf[7], rate_buf[7];
10592 		uint64_t copied, total, elapsed, rate, secs_left;
10593 		double fraction_done;
10594 
10595 		assert(pres->pres_state == DSS_SCANNING);
10596 
10597 		/*
10598 		 * Expansion is in progress.
10599 		 */
10600 		(void) printf(gettext(
10601 		    "expansion of %s-%u in progress since %s"),
10602 		    vname, (int)pres->pres_expanding_vdev, ctime(&start));
10603 
10604 		copied = pres->pres_reflowed > 0 ? pres->pres_reflowed : 1;
10605 		total = pres->pres_to_reflow;
10606 		fraction_done = (double)copied / total;
10607 
10608 		/* elapsed time for this pass */
10609 		elapsed = time(NULL) - pres->pres_start_time;
10610 		elapsed = elapsed > 0 ? elapsed : 1;
10611 		rate = copied / elapsed;
10612 		rate = rate > 0 ? rate : 1;
10613 		secs_left = (total - copied) / rate;
10614 
10615 		zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10616 		zfs_nicenum(total, total_buf, sizeof (total_buf));
10617 		zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10618 
10619 		/*
10620 		 * do not print estimated time if hours_left is more than
10621 		 * 30 days
10622 		 */
10623 		(void) printf(gettext("\t%s / %s copied at %s/s, %.2f%% done"),
10624 		    examined_buf, total_buf, rate_buf, 100 * fraction_done);
10625 		if (pres->pres_waiting_for_resilver) {
10626 			(void) printf(gettext(", paused for resilver or "
10627 			    "clear\n"));
10628 		} else if (secs_left < (30 * 24 * 3600)) {
10629 			char time_buf[32];
10630 			secs_to_dhms(secs_left, time_buf);
10631 			(void) printf(gettext(", %s to go\n"), time_buf);
10632 		} else {
10633 			(void) printf(gettext(
10634 			    ", (copy is slow, no estimated time)\n"));
10635 		}
10636 	}
10637 	free(vname);
10638 }
10639 static void
10640 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
10641 {
10642 	time_t start;
10643 	char space_buf[7];
10644 
10645 	if (pcs == NULL || pcs->pcs_state == CS_NONE)
10646 		return;
10647 
10648 	(void) printf(gettext("checkpoint: "));
10649 
10650 	start = pcs->pcs_start_time;
10651 	zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
10652 
10653 	if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
10654 		char *date = ctime(&start);
10655 
10656 		/*
10657 		 * ctime() adds a newline at the end of the generated
10658 		 * string, thus the weird format specifier and the
10659 		 * strlen() call used to chop it off from the output.
10660 		 */
10661 		(void) printf(gettext("created %.*s, consumes %s\n"),
10662 		    (int)(strlen(date) - 1), date, space_buf);
10663 		return;
10664 	}
10665 
10666 	assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
10667 
10668 	(void) printf(gettext("discarding, %s remaining.\n"),
10669 	    space_buf);
10670 }
10671 
10672 static void
10673 print_condense_status(nvlist_t *nv)
10674 {
10675 	if (nv == NULL)
10676 		return;
10677 
10678 	for (nvpair_t *nvp = nvlist_next_nvpair(nv, NULL);
10679 	    nvp != NULL; nvp = nvlist_next_nvpair(nv, nvp)) {
10680 		const char *type = nvpair_name(nvp);
10681 		nvlist_t *tnv = fnvpair_value_nvlist(nvp);
10682 
10683 		uint64_t start_time = fnvlist_lookup_uint64(tnv, "start_time");
10684 		if (start_time == 0)
10685 			continue;
10686 
10687 		uint64_t end_time = fnvlist_lookup_uint64(tnv, "end_time");
10688 		uint64_t processed = fnvlist_lookup_uint64(tnv, "processed");
10689 		uint64_t total = fnvlist_lookup_uint64(tnv, "total");
10690 
10691 		const char *units = condense_unit(type);
10692 
10693 		char cur[32], tot[32], elapsed[32];
10694 		zfs_nicenum(processed, cur, sizeof (cur));
10695 		zfs_nicenum(total, tot, sizeof (tot));
10696 
10697 		if (end_time == 0) {
10698 			secs_to_dhms(time(NULL) - start_time, elapsed);
10699 			(void) printf(gettext(
10700 			    "condense: %s: condensing, %s/%s %s done in %s\n"),
10701 			    type, cur, tot, units, elapsed);
10702 		} else if (processed < total) {
10703 			secs_to_dhms(end_time - start_time, elapsed);
10704 			(void) printf(gettext(
10705 			    "condense: %s: cancelled, %s/%s %s done in %s\n"),
10706 			    type, cur, tot, units, elapsed);
10707 		} else {
10708 			secs_to_dhms(end_time - start_time, elapsed);
10709 			(void) printf(gettext(
10710 			    "condense: %s: done, %s %s done in %s\n"),
10711 			    type, cur, units, elapsed);
10712 		}
10713 	}
10714 }
10715 
10716 static void
10717 print_error_log(zpool_handle_t *zhp)
10718 {
10719 	nvlist_t *nverrlist = NULL;
10720 	nvpair_t *elem;
10721 	char *pathname;
10722 	size_t len = MAXPATHLEN * 2;
10723 
10724 	if (zpool_get_errlog(zhp, &nverrlist) != 0)
10725 		return;
10726 
10727 	(void) printf("errors: Permanent errors have been "
10728 	    "detected in the following files:\n\n");
10729 
10730 	pathname = safe_malloc(len);
10731 	elem = NULL;
10732 	while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
10733 		nvlist_t *nv;
10734 		uint64_t dsobj, obj;
10735 
10736 		verify(nvpair_value_nvlist(elem, &nv) == 0);
10737 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
10738 		    &dsobj) == 0);
10739 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
10740 		    &obj) == 0);
10741 		zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
10742 		(void) printf("%7s %s\n", "", pathname);
10743 	}
10744 	free(pathname);
10745 	nvlist_free(nverrlist);
10746 }
10747 
10748 static void
10749 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
10750     uint_t nspares)
10751 {
10752 	uint_t i;
10753 	char *name;
10754 
10755 	if (nspares == 0)
10756 		return;
10757 
10758 	(void) printf(gettext("\tspares\n"));
10759 
10760 	for (i = 0; i < nspares; i++) {
10761 		name = zpool_vdev_name(g_zfs, zhp, spares[i],
10762 		    cb->cb_name_flags);
10763 		print_status_config(zhp, cb, name, spares[i], 2, B_TRUE, NULL);
10764 		free(name);
10765 	}
10766 }
10767 
10768 static void
10769 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
10770     uint_t nl2cache)
10771 {
10772 	uint_t i;
10773 	char *name;
10774 
10775 	if (nl2cache == 0)
10776 		return;
10777 
10778 	(void) printf(gettext("\tcache\n"));
10779 
10780 	for (i = 0; i < nl2cache; i++) {
10781 		name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
10782 		    cb->cb_name_flags);
10783 		print_status_config(zhp, cb, name, l2cache[i], 2,
10784 		    B_FALSE, NULL);
10785 		free(name);
10786 	}
10787 }
10788 
10789 static void
10790 print_dedup_stats(zpool_handle_t *zhp, nvlist_t *config, boolean_t literal)
10791 {
10792 	ddt_histogram_t *ddh;
10793 	ddt_stat_t *dds;
10794 	ddt_object_t *ddo;
10795 	uint_t c;
10796 	/* Extra space provided for literal display */
10797 	char dspace[32], mspace[32], cspace[32];
10798 	uint64_t cspace_prop;
10799 	enum zfs_nicenum_format format;
10800 	zprop_source_t src;
10801 
10802 	/*
10803 	 * If the pool was faulted then we may not have been able to
10804 	 * obtain the config. Otherwise, if we have anything in the dedup
10805 	 * table continue processing the stats.
10806 	 */
10807 	if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
10808 	    (uint64_t **)&ddo, &c) != 0)
10809 		return;
10810 
10811 	(void) printf("\n");
10812 	(void) printf(gettext(" dedup: "));
10813 	if (ddo->ddo_count == 0) {
10814 		(void) printf(gettext("no DDT entries\n"));
10815 		return;
10816 	}
10817 
10818 	/*
10819 	 * Squash cached size into in-core size to handle race.
10820 	 * Only include cached size if it is available.
10821 	 */
10822 	cspace_prop = zpool_get_prop_int(zhp, ZPOOL_PROP_DEDUPCACHED, &src);
10823 	cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
10824 	format = literal ? ZFS_NICENUM_RAW : ZFS_NICENUM_1024;
10825 	zfs_nicenum_format(cspace_prop, cspace, sizeof (cspace), format);
10826 	zfs_nicenum_format(ddo->ddo_dspace, dspace, sizeof (dspace), format);
10827 	zfs_nicenum_format(ddo->ddo_mspace, mspace, sizeof (mspace), format);
10828 	(void) printf("DDT entries %llu, size %s on disk, %s in core",
10829 	    (u_longlong_t)ddo->ddo_count,
10830 	    dspace,
10831 	    mspace);
10832 	if (src != ZPROP_SRC_DEFAULT) {
10833 		(void) printf(", %s cached (%.02f%%)",
10834 		    cspace,
10835 		    (double)cspace_prop / (double)ddo->ddo_mspace * 100.0);
10836 	}
10837 	(void) printf("\n");
10838 
10839 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
10840 	    (uint64_t **)&dds, &c) == 0);
10841 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
10842 	    (uint64_t **)&ddh, &c) == 0);
10843 	zpool_dump_ddt(dds, ddh, literal);
10844 }
10845 
10846 #define	ST_SIZE	4096
10847 #define	AC_SIZE	2048
10848 
10849 static void
10850 print_status_reason(zpool_handle_t *zhp, status_cbdata_t *cbp,
10851     zpool_status_t reason, zpool_errata_t errata, nvlist_t *item)
10852 {
10853 	char status[ST_SIZE];
10854 	char action[AC_SIZE];
10855 	memset(status, 0, ST_SIZE);
10856 	memset(action, 0, AC_SIZE);
10857 
10858 	switch (reason) {
10859 	case ZPOOL_STATUS_MISSING_DEV_R:
10860 		(void) snprintf(status, ST_SIZE,
10861 		    gettext("One or more devices could "
10862 		    "not be opened.  Sufficient replicas exist for\n\tthe pool "
10863 		    "to continue functioning in a degraded state.\n"));
10864 		(void) snprintf(action, AC_SIZE,
10865 		    gettext("Attach the missing device "
10866 		    "and online it using 'zpool online'.\n"));
10867 		break;
10868 
10869 	case ZPOOL_STATUS_MISSING_DEV_NR:
10870 		(void) snprintf(status, ST_SIZE,
10871 		    gettext("One or more devices could "
10872 		    "not be opened.  There are insufficient\n\treplicas for the"
10873 		    " pool to continue functioning.\n"));
10874 		(void) snprintf(action, AC_SIZE,
10875 		    gettext("Attach the missing device "
10876 		    "and online it using 'zpool online'.\n"));
10877 		break;
10878 
10879 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
10880 		(void) snprintf(status, ST_SIZE,
10881 		    gettext("One or more devices could "
10882 		    "not be used because the label is missing or\n\tinvalid.  "
10883 		    "Sufficient replicas exist for the pool to continue\n\t"
10884 		    "functioning in a degraded state.\n"));
10885 		(void) snprintf(action, AC_SIZE,
10886 		    gettext("Replace the device using 'zpool replace'.\n"));
10887 		break;
10888 
10889 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
10890 		(void) snprintf(status, ST_SIZE,
10891 		    gettext("One or more devices could "
10892 		    "not be used because the label is missing \n\tor invalid.  "
10893 		    "There are insufficient replicas for the pool to "
10894 		    "continue\n\tfunctioning.\n"));
10895 		zpool_explain_recover(zpool_get_handle(zhp),
10896 		    zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
10897 		    action, AC_SIZE);
10898 		break;
10899 
10900 	case ZPOOL_STATUS_FAILING_DEV:
10901 		(void) snprintf(status, ST_SIZE,
10902 		    gettext("One or more devices has "
10903 		    "experienced an unrecoverable error.  An\n\tattempt was "
10904 		    "made to correct the error.  Applications are "
10905 		    "unaffected.\n"));
10906 		(void) snprintf(action, AC_SIZE, gettext("Determine if the "
10907 		    "device needs to be replaced, and clear the errors\n\tusing"
10908 		    " 'zpool clear' or replace the device with 'zpool "
10909 		    "replace'.\n"));
10910 		break;
10911 
10912 	case ZPOOL_STATUS_OFFLINE_DEV:
10913 		(void) snprintf(status, ST_SIZE,
10914 		    gettext("One or more devices has "
10915 		    "been taken offline by the administrator.\n\tSufficient "
10916 		    "replicas exist for the pool to continue functioning in "
10917 		    "a\n\tdegraded state.\n"));
10918 		(void) snprintf(action, AC_SIZE, gettext("Online the device "
10919 		    "using 'zpool online' or replace the device with\n\t'zpool "
10920 		    "replace'.\n"));
10921 		break;
10922 
10923 	case ZPOOL_STATUS_REMOVED_DEV:
10924 		(void) snprintf(status, ST_SIZE,
10925 		    gettext("One or more devices have "
10926 		    "been removed.\n\tSufficient replicas exist for the pool "
10927 		    "to continue functioning in a\n\tdegraded state.\n"));
10928 		(void) snprintf(action, AC_SIZE, gettext("Online the device "
10929 		    "using zpool online' or replace the device with\n\t'zpool "
10930 		    "replace'.\n"));
10931 		break;
10932 
10933 	case ZPOOL_STATUS_RESILVERING:
10934 	case ZPOOL_STATUS_REBUILDING:
10935 		(void) snprintf(status, ST_SIZE,
10936 		    gettext("One or more devices is "
10937 		    "currently being resilvered.  The pool will\n\tcontinue "
10938 		    "to function, possibly in a degraded state.\n"));
10939 		(void) snprintf(action, AC_SIZE,
10940 		    gettext("Wait for the resilver to complete.\n"));
10941 		break;
10942 
10943 	case ZPOOL_STATUS_REBUILD_SCRUB:
10944 		(void) snprintf(status, ST_SIZE,
10945 		    gettext("One or more devices have "
10946 		    "been sequentially resilvered, scrubbing\n\tthe pool "
10947 		    "is recommended.\n"));
10948 		(void) snprintf(action, AC_SIZE, gettext("Use 'zpool scrub' to "
10949 		    "verify all data checksums.\n"));
10950 		break;
10951 
10952 	case ZPOOL_STATUS_CORRUPT_DATA:
10953 		(void) snprintf(status, ST_SIZE,
10954 		    gettext("One or more devices has "
10955 		    "experienced an error resulting in data\n\tcorruption.  "
10956 		    "Applications may be affected.\n"));
10957 		(void) snprintf(action, AC_SIZE,
10958 		    gettext("Restore the file in question"
10959 		    " if possible.  Otherwise restore the\n\tentire pool from "
10960 		    "backup.\n"));
10961 		break;
10962 
10963 	case ZPOOL_STATUS_CORRUPT_POOL:
10964 		(void) snprintf(status, ST_SIZE, gettext("The pool metadata is "
10965 		    "incomplete or corrupted and the pool cannot be "
10966 		    "opened.\n"));
10967 		zpool_explain_recover(zpool_get_handle(zhp),
10968 		    zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
10969 		    action, AC_SIZE);
10970 		break;
10971 
10972 	case ZPOOL_STATUS_VERSION_OLDER:
10973 		(void) snprintf(status, ST_SIZE,
10974 		    gettext("The pool is formatted using "
10975 		    "a legacy on-disk format.  The pool can\n\tstill be used, "
10976 		    "but some features are unavailable.\n"));
10977 		(void) snprintf(action, AC_SIZE,
10978 		    gettext("Upgrade the pool using "
10979 		    "'zpool upgrade'.  Once this is done, the\n\tpool will no "
10980 		    "longer be accessible on software that does not support\n\t"
10981 		    "feature flags.\n"));
10982 		break;
10983 
10984 	case ZPOOL_STATUS_VERSION_NEWER:
10985 		(void) snprintf(status, ST_SIZE,
10986 		    gettext("The pool has been upgraded "
10987 		    "to a newer, incompatible on-disk version.\n\tThe pool "
10988 		    "cannot be accessed on this system.\n"));
10989 		(void) snprintf(action, AC_SIZE,
10990 		    gettext("Access the pool from a "
10991 		    "system running more recent software, or\n\trestore the "
10992 		    "pool from backup.\n"));
10993 		break;
10994 
10995 	case ZPOOL_STATUS_FEAT_DISABLED:
10996 		(void) snprintf(status, ST_SIZE, gettext("Some supported and "
10997 		    "requested features are not enabled on the pool.\n\t"
10998 		    "The pool can still be used, but some features are "
10999 		    "unavailable.\n"));
11000 		(void) snprintf(action, AC_SIZE,
11001 		    gettext("Enable all features using "
11002 		    "'zpool upgrade'. Once this is done,\n\tthe pool may no "
11003 		    "longer be accessible by software that does not support\n\t"
11004 		    "the features. See zpool-features(7) for details.\n"));
11005 		break;
11006 
11007 	case ZPOOL_STATUS_COMPATIBILITY_ERR:
11008 		(void) snprintf(status, ST_SIZE, gettext("This pool has a "
11009 		    "compatibility list specified, but it could not be\n\t"
11010 		    "read/parsed at this time. The pool can still be used, "
11011 		    "but this\n\tshould be investigated.\n"));
11012 		(void) snprintf(action, AC_SIZE,
11013 		    gettext("Check the value of the "
11014 		    "'compatibility' property against the\n\t"
11015 		    "appropriate file in %s or %s.\n"),
11016 		    ZPOOL_SYSCONF_COMPAT_D, ZPOOL_DATA_COMPAT_D);
11017 		break;
11018 
11019 	case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
11020 		(void) snprintf(status, ST_SIZE, gettext("One or more features "
11021 		    "are enabled on the pool despite not being\n\t"
11022 		    "requested by the 'compatibility' property.\n"));
11023 		(void) snprintf(action, AC_SIZE, gettext("Consider setting "
11024 		    "'compatibility' to an appropriate value, or\n\t"
11025 		    "adding needed features to the relevant file in\n\t"
11026 		    "%s or %s.\n"),
11027 		    ZPOOL_SYSCONF_COMPAT_D, ZPOOL_DATA_COMPAT_D);
11028 		break;
11029 
11030 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
11031 		(void) snprintf(status, ST_SIZE,
11032 		    gettext("The pool cannot be accessed "
11033 		    "on this system because it uses the\n\tfollowing feature(s)"
11034 		    " not supported on this system:\n"));
11035 		zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
11036 		    1024);
11037 		(void) snprintf(action, AC_SIZE,
11038 		    gettext("Access the pool from a "
11039 		    "system that supports the required feature(s),\n\tor "
11040 		    "restore the pool from backup.\n"));
11041 		break;
11042 
11043 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
11044 		(void) snprintf(status, ST_SIZE, gettext("The pool can only be "
11045 		    "accessed in read-only mode on this system. It\n\tcannot be"
11046 		    " accessed in read-write mode because it uses the "
11047 		    "following\n\tfeature(s) not supported on this system:\n"));
11048 		zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
11049 		    1024);
11050 		(void) snprintf(action, AC_SIZE,
11051 		    gettext("The pool cannot be accessed "
11052 		    "in read-write mode. Import the pool with\n"
11053 		    "\t\"-o readonly=on\", access the pool from a system that "
11054 		    "supports the\n\trequired feature(s), or restore the "
11055 		    "pool from backup.\n"));
11056 		break;
11057 
11058 	case ZPOOL_STATUS_FAULTED_DEV_R:
11059 		(void) snprintf(status, ST_SIZE,
11060 		    gettext("One or more devices are "
11061 		    "faulted in response to persistent errors.\n\tSufficient "
11062 		    "replicas exist for the pool to continue functioning "
11063 		    "in a\n\tdegraded state.\n"));
11064 		(void) snprintf(action, AC_SIZE,
11065 		    gettext("Replace the faulted device, "
11066 		    "or use 'zpool clear' to mark the device\n\trepaired.\n"));
11067 		break;
11068 
11069 	case ZPOOL_STATUS_FAULTED_FDOM_R:
11070 		(void) snprintf(status, ST_SIZE,
11071 		    gettext("One or more failure domains are faulted. "
11072 		    "The storage devices may be\n\tintact. Sufficient "
11073 		    "replicas exist for the pool to continue functioning\n\t"
11074 		    "in a degraded state.\n"));
11075 		(void) snprintf(action, AC_SIZE,
11076 		    gettext("Replace the faulted domain device, "
11077 		    "or use 'zpool clear' to mark domain\n\tstorage devices "
11078 		    "repaired.\n"));
11079 		break;
11080 
11081 	case ZPOOL_STATUS_FAULTED_DEV_NR:
11082 		(void) snprintf(status, ST_SIZE,
11083 		    gettext("One or more devices are "
11084 		    "faulted in response to persistent errors.  There are "
11085 		    "insufficient replicas for the pool to\n\tcontinue "
11086 		    "functioning.\n"));
11087 		(void) snprintf(action, AC_SIZE,
11088 		    gettext("Destroy and re-create the "
11089 		    "pool from a backup source.  Manually marking the device\n"
11090 		    "\trepaired using 'zpool clear' may allow some data "
11091 		    "to be recovered.\n"));
11092 		break;
11093 
11094 	case ZPOOL_STATUS_IO_FAILURE_MMP:
11095 		(void) snprintf(status, ST_SIZE,
11096 		    gettext("The pool is suspended "
11097 		    "because multihost writes failed or were delayed;\n\t"
11098 		    "another system could import the pool undetected.\n"));
11099 		(void) snprintf(action, AC_SIZE,
11100 		    gettext("Make sure the pool's devices"
11101 		    " are connected, then reboot your system and\n\timport the "
11102 		    "pool or run 'zpool clear' to resume the pool.\n"));
11103 		break;
11104 
11105 	case ZPOOL_STATUS_IO_FAILURE_WAIT:
11106 	case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
11107 		(void) snprintf(status, ST_SIZE,
11108 		    gettext("One or more devices are "
11109 		    "faulted in response to IO failures.\n"));
11110 		(void) snprintf(action, AC_SIZE,
11111 		    gettext("Make sure the affected "
11112 		    "devices are connected, then run 'zpool clear'.\n"));
11113 		break;
11114 
11115 	case ZPOOL_STATUS_BAD_LOG:
11116 		(void) snprintf(status, ST_SIZE, gettext("An intent log record "
11117 		    "could not be read.\n"
11118 		    "\tWaiting for administrator intervention to fix the "
11119 		    "faulted pool.\n"));
11120 		(void) snprintf(action, AC_SIZE,
11121 		    gettext("Either restore the affected "
11122 		    "device(s) and run 'zpool online',\n"
11123 		    "\tor ignore the intent log records by running "
11124 		    "'zpool clear'.\n"));
11125 		break;
11126 
11127 	case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
11128 		(void) snprintf(status, ST_SIZE,
11129 		    gettext("One or more devices are "
11130 		    "configured to use a non-native block size.\n"
11131 		    "\tExpect reduced performance.\n"));
11132 		(void) snprintf(action, AC_SIZE,
11133 		    gettext("Replace affected devices "
11134 		    "with devices that support the\n\tconfigured block size, "
11135 		    "or migrate data to a properly configured\n\tpool.\n"));
11136 		break;
11137 
11138 	case ZPOOL_STATUS_HOSTID_MISMATCH:
11139 		(void) snprintf(status, ST_SIZE,
11140 		    gettext("Mismatch between pool hostid"
11141 		    " and system hostid on imported pool.\n\tThis pool was "
11142 		    "previously imported into a system with a different "
11143 		    "hostid,\n\tand then was verbatim imported into this "
11144 		    "system.\n"));
11145 		(void) snprintf(action, AC_SIZE,
11146 		    gettext("Export this pool on all "
11147 		    "systems on which it is imported.\n"
11148 		    "\tThen import it to correct the mismatch.\n"));
11149 		break;
11150 
11151 	case ZPOOL_STATUS_ERRATA:
11152 		(void) snprintf(status, ST_SIZE,
11153 		    gettext("Errata #%d detected.\n"), errata);
11154 		switch (errata) {
11155 		case ZPOOL_ERRATA_NONE:
11156 			break;
11157 
11158 		case ZPOOL_ERRATA_ZOL_2094_SCRUB:
11159 			(void) snprintf(action, AC_SIZE,
11160 			    gettext("To correct the issue run "
11161 			    "'zpool scrub'.\n"));
11162 			break;
11163 
11164 		case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
11165 			(void) strlcat(status, gettext("\tExisting encrypted "
11166 			    "datasets contain an on-disk incompatibility\n\t "
11167 			    "which needs to be corrected.\n"), ST_SIZE);
11168 			(void) snprintf(action, AC_SIZE,
11169 			    gettext("To correct the issue"
11170 			    " backup existing encrypted datasets to new\n\t"
11171 			    "encrypted datasets and destroy the old ones. "
11172 			    "'zfs mount -o ro' can\n\tbe used to temporarily "
11173 			    "mount existing encrypted datasets readonly.\n"));
11174 			break;
11175 
11176 		case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
11177 			(void) strlcat(status, gettext("\tExisting encrypted "
11178 			    "snapshots and bookmarks contain an on-disk\n\t"
11179 			    "incompatibility. This may cause on-disk "
11180 			    "corruption if they are used\n\twith "
11181 			    "'zfs recv'.\n"), ST_SIZE);
11182 			(void) snprintf(action, AC_SIZE,
11183 			    gettext("To correct the"
11184 			    "issue, enable the bookmark_v2 feature. No "
11185 			    "additional\n\taction is needed if there are no "
11186 			    "encrypted snapshots or bookmarks.\n\tIf preserving"
11187 			    "the encrypted snapshots and bookmarks is required,"
11188 			    " use\n\ta non-raw send to backup and restore them."
11189 			    " Alternately, they may be\n\tremoved to resolve "
11190 			    "the incompatibility.\n"));
11191 			break;
11192 
11193 		default:
11194 			/*
11195 			 * All errata which allow the pool to be imported
11196 			 * must contain an action message.
11197 			 */
11198 			assert(0);
11199 		}
11200 		break;
11201 
11202 	default:
11203 		/*
11204 		 * The remaining errors can't actually be generated, yet.
11205 		 */
11206 		assert(reason == ZPOOL_STATUS_OK);
11207 	}
11208 
11209 	if (status[0] != 0) {
11210 		if (cbp->cb_json)
11211 			fnvlist_add_string(item, "status", status);
11212 		else {
11213 			(void) printf_color(ANSI_BOLD, gettext("status: "));
11214 			(void) printf_color(ANSI_YELLOW, status);
11215 		}
11216 	}
11217 
11218 	if (action[0] != 0) {
11219 		if (cbp->cb_json)
11220 			fnvlist_add_string(item, "action", action);
11221 		else {
11222 			(void) printf_color(ANSI_BOLD, gettext("action: "));
11223 			(void) printf_color(ANSI_YELLOW, action);
11224 		}
11225 	}
11226 }
11227 
11228 static int
11229 status_callback_json(zpool_handle_t *zhp, void *data)
11230 {
11231 	status_cbdata_t *cbp = data;
11232 	nvlist_t *config, *nvroot;
11233 	const char *msgid;
11234 	char pool_guid[256];
11235 	char msgbuf[256];
11236 	uint64_t guid;
11237 	zpool_status_t reason;
11238 	zpool_errata_t errata;
11239 	uint_t c;
11240 	vdev_stat_t *vs;
11241 	nvlist_t *item, *d, *load_info, *vds;
11242 
11243 	/* If dedup stats were requested, also fetch dedupcached. */
11244 	if (cbp->cb_dedup_stats > 1)
11245 		zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
11246 	reason = zpool_get_status(zhp, &msgid, &errata);
11247 	/*
11248 	 * If we were given 'zpool status -x', only report those pools with
11249 	 * problems.
11250 	 */
11251 	if (cbp->cb_explain &&
11252 	    (reason == ZPOOL_STATUS_OK ||
11253 	    reason == ZPOOL_STATUS_VERSION_OLDER ||
11254 	    reason == ZPOOL_STATUS_FEAT_DISABLED ||
11255 	    reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
11256 	    reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
11257 		return (0);
11258 	}
11259 
11260 	d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
11261 	item = fnvlist_alloc();
11262 	vds = fnvlist_alloc();
11263 	fill_pool_info(item, zhp, B_FALSE, cbp->cb_json_as_int);
11264 	config = zpool_get_config(zhp, NULL);
11265 
11266 	if (config != NULL) {
11267 		nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
11268 		verify(nvlist_lookup_uint64_array(nvroot,
11269 		    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &c) == 0);
11270 		if (cbp->cb_json_pool_key_guid) {
11271 			guid = fnvlist_lookup_uint64(config,
11272 			    ZPOOL_CONFIG_POOL_GUID);
11273 			(void) snprintf(pool_guid, 256, "%llu",
11274 			    (u_longlong_t)guid);
11275 		}
11276 		cbp->cb_count++;
11277 
11278 		print_status_reason(zhp, cbp, reason, errata, item);
11279 		if (msgid != NULL) {
11280 			(void) snprintf(msgbuf, 256,
11281 			    "https://openzfs.github.io/openzfs-docs/msg/%s",
11282 			    msgid);
11283 			fnvlist_add_string(item, "msgid", msgid);
11284 			fnvlist_add_string(item, "moreinfo", msgbuf);
11285 		}
11286 
11287 		if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
11288 		    &load_info) == 0) {
11289 			fnvlist_add_nvlist(item, ZPOOL_CONFIG_LOAD_INFO,
11290 			    load_info);
11291 		}
11292 
11293 		scan_status_nvlist(zhp, cbp, nvroot, item);
11294 		removal_status_nvlist(zhp, cbp, nvroot, item);
11295 		checkpoint_status_nvlist(nvroot, cbp, item);
11296 		condense_status_nvlist(nvroot, cbp, item);
11297 		raidz_expand_status_nvlist(zhp, cbp, nvroot, item);
11298 		vdev_stats_nvlist(zhp, cbp, nvroot, 0, B_FALSE, NULL, vds);
11299 		if (cbp->cb_flat_vdevs) {
11300 			class_vdevs_nvlist(zhp, cbp, nvroot,
11301 			    VDEV_ALLOC_BIAS_DEDUP, vds);
11302 			class_vdevs_nvlist(zhp, cbp, nvroot,
11303 			    VDEV_ALLOC_BIAS_SPECIAL, vds);
11304 			class_vdevs_nvlist(zhp, cbp, nvroot,
11305 			    VDEV_ALLOC_CLASS_LOGS, vds);
11306 			l2cache_nvlist(zhp, cbp, nvroot, vds);
11307 			spares_nvlist(zhp, cbp, nvroot, vds);
11308 
11309 			fnvlist_add_nvlist(item, "vdevs", vds);
11310 			fnvlist_free(vds);
11311 		} else {
11312 			fnvlist_add_nvlist(item, "vdevs", vds);
11313 			fnvlist_free(vds);
11314 
11315 			class_vdevs_nvlist(zhp, cbp, nvroot,
11316 			    VDEV_ALLOC_BIAS_DEDUP, item);
11317 			class_vdevs_nvlist(zhp, cbp, nvroot,
11318 			    VDEV_ALLOC_BIAS_SPECIAL, item);
11319 			class_vdevs_nvlist(zhp, cbp, nvroot,
11320 			    VDEV_ALLOC_CLASS_LOGS, item);
11321 			l2cache_nvlist(zhp, cbp, nvroot, item);
11322 			spares_nvlist(zhp, cbp, nvroot, item);
11323 		}
11324 		dedup_stats_nvlist(zhp, cbp, item);
11325 		errors_nvlist(zhp, cbp, item);
11326 	}
11327 	if (cbp->cb_json_pool_key_guid) {
11328 		fnvlist_add_nvlist(d, pool_guid, item);
11329 	} else {
11330 		fnvlist_add_nvlist(d, zpool_get_name(zhp),
11331 		    item);
11332 	}
11333 	fnvlist_free(item);
11334 	return (0);
11335 }
11336 
11337 /*
11338  * Display a summary of pool status.  Displays a summary such as:
11339  *
11340  *        pool: tank
11341  *	status: DEGRADED
11342  *	reason: One or more devices ...
11343  *         see: https://openzfs.github.io/openzfs-docs/msg/ZFS-xxxx-01
11344  *	config:
11345  *		mirror		DEGRADED
11346  *                c1t0d0	OK
11347  *                c2t0d0	UNAVAIL
11348  *
11349  * When given the '-v' option, we print out the complete config.  If the '-e'
11350  * option is specified, then we print out error rate information as well.
11351  */
11352 static int
11353 status_callback(zpool_handle_t *zhp, void *data)
11354 {
11355 	status_cbdata_t *cbp = data;
11356 	nvlist_t *config, *nvroot;
11357 	const char *msgid;
11358 	zpool_status_t reason;
11359 	zpool_errata_t errata;
11360 	const char *health;
11361 	uint_t c;
11362 	vdev_stat_t *vs;
11363 
11364 	/* If dedup stats were requested, also fetch dedupcached. */
11365 	if (cbp->cb_dedup_stats > 1)
11366 		zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
11367 
11368 	config = zpool_get_config(zhp, NULL);
11369 	reason = zpool_get_status(zhp, &msgid, &errata);
11370 
11371 	cbp->cb_count++;
11372 
11373 	/*
11374 	 * If we were given 'zpool status -x', only report those pools with
11375 	 * problems.
11376 	 */
11377 	if (cbp->cb_explain &&
11378 	    (reason == ZPOOL_STATUS_OK ||
11379 	    reason == ZPOOL_STATUS_VERSION_OLDER ||
11380 	    reason == ZPOOL_STATUS_FEAT_DISABLED ||
11381 	    reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
11382 	    reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
11383 		if (!cbp->cb_allpools) {
11384 			(void) printf(gettext("pool '%s' is healthy\n"),
11385 			    zpool_get_name(zhp));
11386 			if (cbp->cb_first)
11387 				cbp->cb_first = B_FALSE;
11388 		}
11389 		return (0);
11390 	}
11391 
11392 	if (cbp->cb_first)
11393 		cbp->cb_first = B_FALSE;
11394 	else
11395 		(void) printf("\n");
11396 
11397 	nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
11398 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
11399 	    (uint64_t **)&vs, &c) == 0);
11400 
11401 	health = zpool_get_state_str(zhp);
11402 
11403 	printf("  ");
11404 	(void) printf_color(ANSI_BOLD, gettext("pool:"));
11405 	printf(" %s\n", zpool_get_name(zhp));
11406 	(void) fputc(' ', stdout);
11407 	(void) printf_color(ANSI_BOLD, gettext("state: "));
11408 
11409 	(void) printf_color(health_str_to_color(health), "%s", health);
11410 
11411 	(void) fputc('\n', stdout);
11412 	print_status_reason(zhp, cbp, reason, errata, NULL);
11413 
11414 	if (msgid != NULL) {
11415 		printf("   ");
11416 		(void) printf_color(ANSI_BOLD, gettext("see:"));
11417 		printf(gettext(
11418 		    " https://openzfs.github.io/openzfs-docs/msg/%s\n"),
11419 		    msgid);
11420 	}
11421 
11422 	if (config != NULL) {
11423 		uint64_t nerr;
11424 		nvlist_t **spares, **l2cache;
11425 		uint_t nspares, nl2cache;
11426 
11427 		print_scan_status(zhp, nvroot);
11428 
11429 		pool_removal_stat_t *prs = NULL;
11430 		(void) nvlist_lookup_uint64_array(nvroot,
11431 		    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
11432 		print_removal_status(zhp, prs);
11433 
11434 		pool_checkpoint_stat_t *pcs = NULL;
11435 		(void) nvlist_lookup_uint64_array(nvroot,
11436 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
11437 		print_checkpoint_status(pcs);
11438 
11439 		pool_raidz_expand_stat_t *pres = NULL;
11440 		(void) nvlist_lookup_uint64_array(nvroot,
11441 		    ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
11442 		print_raidz_expand_status(zhp, pres);
11443 
11444 		nvlist_t *cnv = NULL;
11445 		nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_CONDENSE_STATS, &cnv);
11446 		print_condense_status(cnv);
11447 
11448 		cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
11449 		    cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
11450 		if (cbp->cb_namewidth < 10)
11451 			cbp->cb_namewidth = 10;
11452 
11453 		color_start(ANSI_BOLD);
11454 		(void) printf(gettext("config:\n\n"));
11455 		(void) printf(gettext("\t%-*s  %-8s %5s %5s %5s"),
11456 		    cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
11457 		    "CKSUM");
11458 		color_end();
11459 
11460 		if (cbp->cb_print_slow_ios) {
11461 			(void) printf_color(ANSI_BOLD, " %5s", gettext("SLOW"));
11462 		}
11463 
11464 		if (cbp->cb_print_power) {
11465 			(void) printf_color(ANSI_BOLD, " %5s",
11466 			    gettext("POWER"));
11467 		}
11468 
11469 		if (cbp->cb_print_dio_verify) {
11470 			(void) printf_color(ANSI_BOLD, " %5s", gettext("DIO"));
11471 		}
11472 
11473 		if (cbp->vcdl != NULL)
11474 			print_cmd_columns(cbp->vcdl, 0);
11475 
11476 		printf("\n");
11477 
11478 		print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
11479 		    B_FALSE, NULL);
11480 
11481 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
11482 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
11483 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
11484 
11485 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
11486 		    &l2cache, &nl2cache) == 0)
11487 			print_l2cache(zhp, cbp, l2cache, nl2cache);
11488 
11489 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
11490 		    &spares, &nspares) == 0)
11491 			print_spares(zhp, cbp, spares, nspares);
11492 
11493 		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
11494 		    &nerr) == 0) {
11495 			(void) printf("\n");
11496 			if (nerr == 0) {
11497 				(void) printf(gettext(
11498 				    "errors: No known data errors\n"));
11499 			} else if (!cbp->cb_verbose) {
11500 				color_start(ANSI_RED);
11501 				(void) printf(gettext("errors: %llu data "
11502 				    "errors, use '-v' for a list\n"),
11503 				    (u_longlong_t)nerr);
11504 				color_end();
11505 			} else {
11506 				print_error_log(zhp);
11507 			}
11508 		}
11509 
11510 		if (cbp->cb_dedup_stats)
11511 			print_dedup_stats(zhp, config, cbp->cb_literal);
11512 	} else {
11513 		(void) printf(gettext("config: The configuration cannot be "
11514 		    "determined.\n"));
11515 	}
11516 
11517 	return (0);
11518 }
11519 
11520 /*
11521  * zpool status [-dDegiLpPstvx] [-c [script1,script2,...]] ...
11522  * 				[-j|--json [--json-flat-vdevs] [--json-int] ...
11523  * 				[--json-pool-key-guid]] [--power] [-T d|u] ...
11524  * 				[pool] [interval [count]]
11525  *
11526  *	-c CMD	For each vdev, run command CMD
11527  *	-D	Display dedup status (undocumented)
11528  *	-d	Display Direct I/O write verify errors
11529  *	-e	Display only unhealthy vdevs
11530  *	-g	Display guid for individual vdev name.
11531  *	-i	Display vdev initialization status.
11532  *	-j [...]	Display output in JSON format
11533  *	   --json-flat-vdevs Display vdevs in flat hierarchy
11534  *	   --json-int Display numbers in integer format instead of string
11535  *	   --json-pool-key-guid Use pool GUID as key for pool objects
11536  *	-L	Follow links when resolving vdev path name.
11537  *	-P	Display full path for vdev name.
11538  *	-p	Display values in parsable (exact) format.
11539  *	--power	Display vdev enclosure slot power status
11540  *	-s	Display slow IOs column.
11541  *	-T	Display a timestamp in date(1) or Unix format
11542  *	-t	Display vdev TRIM status.
11543  *	-v	Display complete error logs
11544  *	-x	Display only pools with potential problems
11545  *
11546  * Describes the health status of all pools or some subset.
11547  */
11548 int
11549 zpool_do_status(int argc, char **argv)
11550 {
11551 	int c;
11552 	int ret;
11553 	float interval = 0;
11554 	unsigned long count = 0;
11555 	status_cbdata_t cb = { 0 };
11556 	nvlist_t *data;
11557 	char *cmd = NULL;
11558 
11559 	struct option long_options[] = {
11560 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
11561 		{"json", no_argument, NULL, 'j'},
11562 		{"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
11563 		{"json-flat-vdevs", no_argument, NULL,
11564 		    ZPOOL_OPTION_JSON_FLAT_VDEVS},
11565 		{"json-pool-key-guid", no_argument, NULL,
11566 		    ZPOOL_OPTION_POOL_KEY_GUID},
11567 		{0, 0, 0, 0}
11568 	};
11569 
11570 	/* check options */
11571 	while ((c = getopt_long(argc, argv, "c:jdDegiLpPstT:vx", long_options,
11572 	    NULL)) != -1) {
11573 		switch (c) {
11574 		case 'c':
11575 			if (cmd != NULL) {
11576 				fprintf(stderr,
11577 				    gettext("Can't set -c flag twice\n"));
11578 				exit(1);
11579 			}
11580 
11581 			if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
11582 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
11583 				fprintf(stderr, gettext(
11584 				    "Can't run -c, disabled by "
11585 				    "ZPOOL_SCRIPTS_ENABLED.\n"));
11586 				exit(1);
11587 			}
11588 
11589 			if ((getuid() <= 0 || geteuid() <= 0) &&
11590 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
11591 				fprintf(stderr, gettext(
11592 				    "Can't run -c with root privileges "
11593 				    "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
11594 				exit(1);
11595 			}
11596 			cmd = optarg;
11597 			break;
11598 		case 'd':
11599 			cb.cb_print_dio_verify = B_TRUE;
11600 			break;
11601 		case 'D':
11602 			if (++cb.cb_dedup_stats  > 2)
11603 				cb.cb_dedup_stats = 2;
11604 			break;
11605 		case 'e':
11606 			cb.cb_print_unhealthy = B_TRUE;
11607 			break;
11608 		case 'g':
11609 			cb.cb_name_flags |= VDEV_NAME_GUID;
11610 			break;
11611 		case 'i':
11612 			cb.cb_print_vdev_init = B_TRUE;
11613 			break;
11614 		case 'L':
11615 			cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
11616 			break;
11617 		case 'p':
11618 			cb.cb_literal = B_TRUE;
11619 			break;
11620 		case 'P':
11621 			cb.cb_name_flags |= VDEV_NAME_PATH;
11622 			break;
11623 		case 's':
11624 			cb.cb_print_slow_ios = B_TRUE;
11625 			break;
11626 		case 't':
11627 			cb.cb_print_vdev_trim = B_TRUE;
11628 			break;
11629 		case 'T':
11630 			get_timestamp_arg(*optarg);
11631 			break;
11632 		case 'v':
11633 			cb.cb_verbose = B_TRUE;
11634 			break;
11635 		case 'j':
11636 			cb.cb_json = B_TRUE;
11637 			break;
11638 		case 'x':
11639 			cb.cb_explain = B_TRUE;
11640 			break;
11641 		case ZPOOL_OPTION_POWER:
11642 			cb.cb_print_power = B_TRUE;
11643 			break;
11644 		case ZPOOL_OPTION_JSON_FLAT_VDEVS:
11645 			cb.cb_flat_vdevs = B_TRUE;
11646 			break;
11647 		case ZPOOL_OPTION_JSON_NUMS_AS_INT:
11648 			cb.cb_json_as_int = B_TRUE;
11649 			cb.cb_literal = B_TRUE;
11650 			break;
11651 		case ZPOOL_OPTION_POOL_KEY_GUID:
11652 			cb.cb_json_pool_key_guid = B_TRUE;
11653 			break;
11654 		case '?':
11655 			if (optopt == 'c') {
11656 				print_zpool_script_list("status");
11657 				exit(0);
11658 			} else {
11659 				fprintf(stderr,
11660 				    gettext("invalid option '%c'\n"), optopt);
11661 			}
11662 			usage(B_FALSE);
11663 		}
11664 	}
11665 
11666 	argc -= optind;
11667 	argv += optind;
11668 
11669 	get_interval_count(&argc, argv, &interval, &count);
11670 
11671 	if (argc == 0)
11672 		cb.cb_allpools = B_TRUE;
11673 
11674 	cb.cb_first = B_TRUE;
11675 	cb.cb_print_status = B_TRUE;
11676 
11677 	if (cb.cb_flat_vdevs && !cb.cb_json) {
11678 		fprintf(stderr, gettext("'--json-flat-vdevs' only works with"
11679 		    " '-j' option\n"));
11680 		usage(B_FALSE);
11681 	}
11682 
11683 	if (cb.cb_json_as_int && !cb.cb_json) {
11684 		(void) fprintf(stderr, gettext("'--json-int' only works with"
11685 		    " '-j' option\n"));
11686 		usage(B_FALSE);
11687 	}
11688 
11689 	if (!cb.cb_json && cb.cb_json_pool_key_guid) {
11690 		(void) fprintf(stderr, gettext("'json-pool-key-guid' only"
11691 		    " works with '-j' option\n"));
11692 		usage(B_FALSE);
11693 	}
11694 
11695 	for (;;) {
11696 		if (cb.cb_json) {
11697 			cb.cb_jsobj = zpool_json_schema(0, 1);
11698 			data = fnvlist_alloc();
11699 			fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
11700 			fnvlist_free(data);
11701 		}
11702 
11703 		if (timestamp_fmt != NODATE) {
11704 			if (cb.cb_json) {
11705 				if (cb.cb_json_as_int) {
11706 					fnvlist_add_uint64(cb.cb_jsobj, "time",
11707 					    time(NULL));
11708 				} else {
11709 					char ts[128];
11710 					get_timestamp(timestamp_fmt, ts, 128);
11711 					fnvlist_add_string(cb.cb_jsobj, "time",
11712 					    ts);
11713 				}
11714 			} else
11715 				print_timestamp(timestamp_fmt);
11716 		}
11717 
11718 		if (cmd != NULL)
11719 			cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
11720 			    NULL, NULL, 0, 0);
11721 
11722 		if (cb.cb_json) {
11723 			ret = for_each_pool(argc, argv, B_TRUE, NULL,
11724 			    ZFS_TYPE_POOL, cb.cb_literal,
11725 			    status_callback_json, &cb);
11726 		} else {
11727 			ret = for_each_pool(argc, argv, B_TRUE, NULL,
11728 			    ZFS_TYPE_POOL, cb.cb_literal,
11729 			    status_callback, &cb);
11730 		}
11731 
11732 		if (cb.vcdl != NULL)
11733 			free_vdev_cmd_data_list(cb.vcdl);
11734 
11735 		if (cb.cb_json) {
11736 			if (ret == 0)
11737 				zcmd_print_json(cb.cb_jsobj);
11738 			else
11739 				nvlist_free(cb.cb_jsobj);
11740 		} else {
11741 			if (argc == 0 && cb.cb_count == 0) {
11742 				(void) fprintf(stderr, "%s",
11743 				    gettext("no pools available\n"));
11744 			} else if (cb.cb_explain && cb.cb_first &&
11745 			    cb.cb_allpools) {
11746 				(void) printf("%s",
11747 				    gettext("all pools are healthy\n"));
11748 			}
11749 		}
11750 
11751 		if (ret != 0)
11752 			return (ret);
11753 
11754 		if (interval == 0)
11755 			break;
11756 
11757 		if (count != 0 && --count == 0)
11758 			break;
11759 
11760 		(void) fflush(stdout);
11761 		(void) fsleep(interval);
11762 	}
11763 
11764 	return (0);
11765 }
11766 
11767 typedef struct upgrade_cbdata {
11768 	int	cb_first;
11769 	int	cb_argc;
11770 	uint64_t cb_version;
11771 	char	**cb_argv;
11772 } upgrade_cbdata_t;
11773 
11774 static int
11775 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
11776 {
11777 	int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
11778 	int *count = (int *)unsupp_fs;
11779 
11780 	if (zfs_version > ZPL_VERSION) {
11781 		(void) printf(gettext("%s (v%d) is not supported by this "
11782 		    "implementation of ZFS.\n"),
11783 		    zfs_get_name(zhp), zfs_version);
11784 		(*count)++;
11785 	}
11786 
11787 	(void) zfs_iter_filesystems_v2(zhp, 0, check_unsupp_fs, unsupp_fs);
11788 
11789 	zfs_close(zhp);
11790 
11791 	return (0);
11792 }
11793 
11794 static int
11795 upgrade_version(zpool_handle_t *zhp, uint64_t version)
11796 {
11797 	int ret;
11798 	nvlist_t *config;
11799 	uint64_t oldversion;
11800 	int unsupp_fs = 0;
11801 
11802 	config = zpool_get_config(zhp, NULL);
11803 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11804 	    &oldversion) == 0);
11805 
11806 	char compat[ZFS_MAXPROPLEN];
11807 	if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11808 	    ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11809 		compat[0] = '\0';
11810 
11811 	assert(SPA_VERSION_IS_SUPPORTED(oldversion));
11812 	assert(oldversion < version);
11813 
11814 	ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
11815 	if (ret != 0)
11816 		return (ret);
11817 
11818 	if (unsupp_fs) {
11819 		(void) fprintf(stderr, gettext("Upgrade not performed due "
11820 		    "to %d unsupported filesystems (max v%d).\n"),
11821 		    unsupp_fs, (int)ZPL_VERSION);
11822 		return (1);
11823 	}
11824 
11825 	if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
11826 		(void) fprintf(stderr, gettext("Upgrade not performed because "
11827 		    "'compatibility' property set to '"
11828 		    ZPOOL_COMPAT_LEGACY "'.\n"));
11829 		return (1);
11830 	}
11831 
11832 	ret = zpool_upgrade(zhp, version);
11833 	if (ret != 0)
11834 		return (ret);
11835 
11836 	if (version >= SPA_VERSION_FEATURES) {
11837 		(void) printf(gettext("Successfully upgraded "
11838 		    "'%s' from version %llu to feature flags.\n"),
11839 		    zpool_get_name(zhp), (u_longlong_t)oldversion);
11840 	} else {
11841 		(void) printf(gettext("Successfully upgraded "
11842 		    "'%s' from version %llu to version %llu.\n"),
11843 		    zpool_get_name(zhp), (u_longlong_t)oldversion,
11844 		    (u_longlong_t)version);
11845 	}
11846 
11847 	return (0);
11848 }
11849 
11850 static int
11851 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
11852 {
11853 	int i, ret, count;
11854 	boolean_t firstff = B_TRUE;
11855 	nvlist_t *enabled = zpool_get_features(zhp);
11856 
11857 	char compat[ZFS_MAXPROPLEN];
11858 	if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11859 	    ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11860 		compat[0] = '\0';
11861 
11862 	boolean_t requested_features[SPA_FEATURES];
11863 	if (zpool_do_load_compat(compat, requested_features) !=
11864 	    ZPOOL_COMPATIBILITY_OK)
11865 		return (-1);
11866 
11867 	count = 0;
11868 	for (i = 0; i < SPA_FEATURES; i++) {
11869 		const char *fname = spa_feature_table[i].fi_uname;
11870 		const char *fguid = spa_feature_table[i].fi_guid;
11871 
11872 		if (!spa_feature_table[i].fi_zfs_mod_supported ||
11873 		    (spa_feature_table[i].fi_flags & ZFEATURE_FLAG_NO_UPGRADE))
11874 			continue;
11875 
11876 		if (!nvlist_exists(enabled, fguid) && requested_features[i]) {
11877 			char *propname;
11878 			verify(-1 != asprintf(&propname, "feature@%s", fname));
11879 			ret = zpool_set_prop(zhp, propname,
11880 			    ZFS_FEATURE_ENABLED);
11881 			if (ret != 0) {
11882 				free(propname);
11883 				return (ret);
11884 			}
11885 			count++;
11886 
11887 			if (firstff) {
11888 				(void) printf(gettext("Enabled the "
11889 				    "following features on '%s':\n"),
11890 				    zpool_get_name(zhp));
11891 				firstff = B_FALSE;
11892 			}
11893 			(void) printf(gettext("  %s\n"), fname);
11894 			free(propname);
11895 		}
11896 	}
11897 
11898 	if (countp != NULL)
11899 		*countp = count;
11900 	return (0);
11901 }
11902 
11903 static int
11904 upgrade_cb(zpool_handle_t *zhp, void *arg)
11905 {
11906 	upgrade_cbdata_t *cbp = arg;
11907 	nvlist_t *config;
11908 	uint64_t version;
11909 	boolean_t modified_pool = B_FALSE;
11910 	int ret;
11911 
11912 	config = zpool_get_config(zhp, NULL);
11913 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11914 	    &version) == 0);
11915 
11916 	assert(SPA_VERSION_IS_SUPPORTED(version));
11917 
11918 	if (version < cbp->cb_version) {
11919 		cbp->cb_first = B_FALSE;
11920 		ret = upgrade_version(zhp, cbp->cb_version);
11921 		if (ret != 0)
11922 			return (ret);
11923 		modified_pool = B_TRUE;
11924 
11925 		/*
11926 		 * If they did "zpool upgrade -a", then we could
11927 		 * be doing ioctls to different pools.  We need
11928 		 * to log this history once to each pool, and bypass
11929 		 * the normal history logging that happens in main().
11930 		 */
11931 		(void) zpool_log_history(g_zfs, history_str);
11932 		log_history = B_FALSE;
11933 	}
11934 
11935 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
11936 		int count;
11937 		ret = upgrade_enable_all(zhp, &count);
11938 		if (ret != 0)
11939 			return (ret);
11940 
11941 		if (count > 0) {
11942 			cbp->cb_first = B_FALSE;
11943 			modified_pool = B_TRUE;
11944 		}
11945 	}
11946 
11947 	if (modified_pool) {
11948 		(void) printf("\n");
11949 		(void) after_zpool_upgrade(zhp);
11950 	}
11951 
11952 	return (0);
11953 }
11954 
11955 static int
11956 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
11957 {
11958 	upgrade_cbdata_t *cbp = arg;
11959 	nvlist_t *config;
11960 	uint64_t version;
11961 
11962 	config = zpool_get_config(zhp, NULL);
11963 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11964 	    &version) == 0);
11965 
11966 	assert(SPA_VERSION_IS_SUPPORTED(version));
11967 
11968 	if (version < SPA_VERSION_FEATURES) {
11969 		if (cbp->cb_first) {
11970 			(void) printf(gettext("The following pools are "
11971 			    "formatted with legacy version numbers and can\n"
11972 			    "be upgraded to use feature flags.  After "
11973 			    "being upgraded, these pools\nwill no "
11974 			    "longer be accessible by software that does not "
11975 			    "support feature\nflags.\n\n"
11976 			    "Note that setting a pool's 'compatibility' "
11977 			    "feature to '" ZPOOL_COMPAT_LEGACY "' will\n"
11978 			    "inhibit upgrades.\n\n"));
11979 			(void) printf(gettext("VER  POOL\n"));
11980 			(void) printf(gettext("---  ------------\n"));
11981 			cbp->cb_first = B_FALSE;
11982 		}
11983 
11984 		(void) printf("%2llu   %s\n", (u_longlong_t)version,
11985 		    zpool_get_name(zhp));
11986 	}
11987 
11988 	return (0);
11989 }
11990 
11991 static int
11992 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
11993 {
11994 	upgrade_cbdata_t *cbp = arg;
11995 	nvlist_t *config;
11996 	uint64_t version;
11997 
11998 	config = zpool_get_config(zhp, NULL);
11999 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
12000 	    &version) == 0);
12001 
12002 	if (version >= SPA_VERSION_FEATURES) {
12003 		int i;
12004 		boolean_t poolfirst = B_TRUE;
12005 		nvlist_t *enabled = zpool_get_features(zhp);
12006 
12007 		for (i = 0; i < SPA_FEATURES; i++) {
12008 			const char *fguid = spa_feature_table[i].fi_guid;
12009 			const char *fname = spa_feature_table[i].fi_uname;
12010 
12011 			if (!spa_feature_table[i].fi_zfs_mod_supported)
12012 				continue;
12013 
12014 			if (!nvlist_exists(enabled, fguid)) {
12015 				if (cbp->cb_first) {
12016 					(void) printf(gettext("\nSome "
12017 					    "supported features are not "
12018 					    "enabled on the following pools. "
12019 					    "Once a\nfeature is enabled the "
12020 					    "pool may become incompatible with "
12021 					    "software\nthat does not support "
12022 					    "the feature. See "
12023 					    "zpool-features(7) for "
12024 					    "details.\n\n"
12025 					    "Note that the pool "
12026 					    "'compatibility' feature can be "
12027 					    "used to inhibit\nfeature "
12028 					    "upgrades.\n\n"
12029 					    "Features marked with (*) are not "
12030 					    "applied automatically on upgrade, "
12031 					    "and\nmust be applied explicitly "
12032 					    "with zpool-set(7).\n\n"));
12033 					(void) printf(gettext("POOL  "
12034 					    "FEATURE\n"));
12035 					(void) printf(gettext("------"
12036 					    "---------\n"));
12037 					cbp->cb_first = B_FALSE;
12038 				}
12039 
12040 				if (poolfirst) {
12041 					(void) printf(gettext("%s\n"),
12042 					    zpool_get_name(zhp));
12043 					poolfirst = B_FALSE;
12044 				}
12045 
12046 				(void) printf(gettext("      %s%s\n"), fname,
12047 				    spa_feature_table[i].fi_flags &
12048 				    ZFEATURE_FLAG_NO_UPGRADE ? "(*)" : "");
12049 			}
12050 			/*
12051 			 * If they did "zpool upgrade -a", then we could
12052 			 * be doing ioctls to different pools.  We need
12053 			 * to log this history once to each pool, and bypass
12054 			 * the normal history logging that happens in main().
12055 			 */
12056 			(void) zpool_log_history(g_zfs, history_str);
12057 			log_history = B_FALSE;
12058 		}
12059 	}
12060 
12061 	return (0);
12062 }
12063 
12064 static int
12065 upgrade_one(zpool_handle_t *zhp, void *data)
12066 {
12067 	boolean_t modified_pool = B_FALSE;
12068 	upgrade_cbdata_t *cbp = data;
12069 	uint64_t cur_version;
12070 	int ret;
12071 
12072 	if (strcmp("log", zpool_get_name(zhp)) == 0) {
12073 		(void) fprintf(stderr, gettext("'log' is now a reserved word\n"
12074 		    "Pool 'log' must be renamed using export and import"
12075 		    " to upgrade.\n"));
12076 		return (1);
12077 	}
12078 
12079 	cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
12080 	if (cur_version > cbp->cb_version) {
12081 		(void) printf(gettext("Pool '%s' is already formatted "
12082 		    "using more current version '%llu'.\n\n"),
12083 		    zpool_get_name(zhp), (u_longlong_t)cur_version);
12084 		return (0);
12085 	}
12086 
12087 	if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
12088 		(void) printf(gettext("Pool '%s' is already formatted "
12089 		    "using version %llu.\n\n"), zpool_get_name(zhp),
12090 		    (u_longlong_t)cbp->cb_version);
12091 		return (0);
12092 	}
12093 
12094 	if (cur_version != cbp->cb_version) {
12095 		modified_pool = B_TRUE;
12096 		ret = upgrade_version(zhp, cbp->cb_version);
12097 		if (ret != 0)
12098 			return (ret);
12099 	}
12100 
12101 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
12102 		int count = 0;
12103 		ret = upgrade_enable_all(zhp, &count);
12104 		if (ret != 0)
12105 			return (ret);
12106 
12107 		if (count != 0) {
12108 			modified_pool = B_TRUE;
12109 		} else if (cur_version == SPA_VERSION) {
12110 			(void) printf(gettext("Pool '%s' already has all "
12111 			    "supported and requested features enabled.\n"),
12112 			    zpool_get_name(zhp));
12113 		}
12114 	}
12115 
12116 	if (modified_pool) {
12117 		(void) printf("\n");
12118 		(void) after_zpool_upgrade(zhp);
12119 	}
12120 
12121 	return (0);
12122 }
12123 
12124 /*
12125  * zpool upgrade
12126  * zpool upgrade -v
12127  * zpool upgrade [-V version] <-a | pool ...>
12128  *
12129  * With no arguments, display downrev'd ZFS pool available for upgrade.
12130  * Individual pools can be upgraded by specifying the pool, and '-a' will
12131  * upgrade all pools.
12132  */
12133 int
12134 zpool_do_upgrade(int argc, char **argv)
12135 {
12136 	int c;
12137 	upgrade_cbdata_t cb = { 0 };
12138 	int ret = 0;
12139 	boolean_t showversions = B_FALSE;
12140 	boolean_t upgradeall = B_FALSE;
12141 	char *end;
12142 
12143 
12144 	/* check options */
12145 	while ((c = getopt(argc, argv, ":avV:")) != -1) {
12146 		switch (c) {
12147 		case 'a':
12148 			upgradeall = B_TRUE;
12149 			break;
12150 		case 'v':
12151 			showversions = B_TRUE;
12152 			break;
12153 		case 'V':
12154 			cb.cb_version = strtoll(optarg, &end, 10);
12155 			if (*end != '\0' ||
12156 			    !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
12157 				(void) fprintf(stderr,
12158 				    gettext("invalid version '%s'\n"), optarg);
12159 				usage(B_FALSE);
12160 			}
12161 			break;
12162 		case ':':
12163 			(void) fprintf(stderr, gettext("missing argument for "
12164 			    "'%c' option\n"), optopt);
12165 			usage(B_FALSE);
12166 			break;
12167 		case '?':
12168 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
12169 			    optopt);
12170 			usage(B_FALSE);
12171 		}
12172 	}
12173 
12174 	cb.cb_argc = argc;
12175 	cb.cb_argv = argv;
12176 	argc -= optind;
12177 	argv += optind;
12178 
12179 	if (cb.cb_version == 0) {
12180 		cb.cb_version = SPA_VERSION;
12181 	} else if (!upgradeall && argc == 0) {
12182 		(void) fprintf(stderr, gettext("-V option is "
12183 		    "incompatible with other arguments\n"));
12184 		usage(B_FALSE);
12185 	}
12186 
12187 	if (showversions) {
12188 		if (upgradeall || argc != 0) {
12189 			(void) fprintf(stderr, gettext("-v option is "
12190 			    "incompatible with other arguments\n"));
12191 			usage(B_FALSE);
12192 		}
12193 	} else if (upgradeall) {
12194 		if (argc != 0) {
12195 			(void) fprintf(stderr, gettext("-a option should not "
12196 			    "be used along with a pool name\n"));
12197 			usage(B_FALSE);
12198 		}
12199 	}
12200 
12201 	(void) printf("%s", gettext("This system supports ZFS pool feature "
12202 	    "flags.\n\n"));
12203 	if (showversions) {
12204 		int i;
12205 
12206 		(void) printf(gettext("The following features are "
12207 		    "supported:\n\n"));
12208 		(void) printf(gettext("FEAT DESCRIPTION\n"));
12209 		(void) printf("----------------------------------------------"
12210 		    "---------------\n");
12211 		for (i = 0; i < SPA_FEATURES; i++) {
12212 			zfeature_info_t *fi = &spa_feature_table[i];
12213 			if (!fi->fi_zfs_mod_supported)
12214 				continue;
12215 			const char *ro =
12216 			    (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
12217 			    " (read-only compatible)" : "";
12218 
12219 			(void) printf("%-37s%s\n", fi->fi_uname, ro);
12220 			(void) printf("     %s\n", fi->fi_desc);
12221 		}
12222 		(void) printf("\n");
12223 
12224 		(void) printf(gettext("The following legacy versions are also "
12225 		    "supported:\n\n"));
12226 		(void) printf(gettext("VER  DESCRIPTION\n"));
12227 		(void) printf("---  -----------------------------------------"
12228 		    "---------------\n");
12229 		(void) printf(gettext(" 1   Initial ZFS version\n"));
12230 		(void) printf(gettext(" 2   Ditto blocks "
12231 		    "(replicated metadata)\n"));
12232 		(void) printf(gettext(" 3   Hot spares and double parity "
12233 		    "RAID-Z\n"));
12234 		(void) printf(gettext(" 4   zpool history\n"));
12235 		(void) printf(gettext(" 5   Compression using the gzip "
12236 		    "algorithm\n"));
12237 		(void) printf(gettext(" 6   bootfs pool property\n"));
12238 		(void) printf(gettext(" 7   Separate intent log devices\n"));
12239 		(void) printf(gettext(" 8   Delegated administration\n"));
12240 		(void) printf(gettext(" 9   refquota and refreservation "
12241 		    "properties\n"));
12242 		(void) printf(gettext(" 10  Cache devices\n"));
12243 		(void) printf(gettext(" 11  Improved scrub performance\n"));
12244 		(void) printf(gettext(" 12  Snapshot properties\n"));
12245 		(void) printf(gettext(" 13  snapused property\n"));
12246 		(void) printf(gettext(" 14  passthrough-x aclinherit\n"));
12247 		(void) printf(gettext(" 15  user/group space accounting\n"));
12248 		(void) printf(gettext(" 16  stmf property support\n"));
12249 		(void) printf(gettext(" 17  Triple-parity RAID-Z\n"));
12250 		(void) printf(gettext(" 18  Snapshot user holds\n"));
12251 		(void) printf(gettext(" 19  Log device removal\n"));
12252 		(void) printf(gettext(" 20  Compression using zle "
12253 		    "(zero-length encoding)\n"));
12254 		(void) printf(gettext(" 21  Deduplication\n"));
12255 		(void) printf(gettext(" 22  Received properties\n"));
12256 		(void) printf(gettext(" 23  Slim ZIL\n"));
12257 		(void) printf(gettext(" 24  System attributes\n"));
12258 		(void) printf(gettext(" 25  Improved scrub stats\n"));
12259 		(void) printf(gettext(" 26  Improved snapshot deletion "
12260 		    "performance\n"));
12261 		(void) printf(gettext(" 27  Improved snapshot creation "
12262 		    "performance\n"));
12263 		(void) printf(gettext(" 28  Multiple vdev replacements\n"));
12264 		(void) printf(gettext("\nFor more information on a particular "
12265 		    "version, including supported releases,\n"));
12266 		(void) printf(gettext("see the ZFS Administration Guide.\n\n"));
12267 	} else if (argc == 0 && upgradeall) {
12268 		cb.cb_first = B_TRUE;
12269 		ret = zpool_iter(g_zfs, upgrade_cb, &cb);
12270 		if (ret == 0 && cb.cb_first) {
12271 			if (cb.cb_version == SPA_VERSION) {
12272 				(void) printf(gettext("All pools are already "
12273 				    "formatted using feature flags.\n\n"));
12274 				(void) printf(gettext("Every feature flags "
12275 				    "pool already has all supported and "
12276 				    "requested features enabled.\n"));
12277 			} else {
12278 				(void) printf(gettext("All pools are already "
12279 				    "formatted with version %llu or higher.\n"),
12280 				    (u_longlong_t)cb.cb_version);
12281 			}
12282 		}
12283 	} else if (argc == 0) {
12284 		cb.cb_first = B_TRUE;
12285 		ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
12286 		assert(ret == 0);
12287 
12288 		if (cb.cb_first) {
12289 			(void) printf(gettext("All pools are formatted "
12290 			    "using feature flags.\n\n"));
12291 		} else {
12292 			(void) printf(gettext("\nUse 'zpool upgrade -v' "
12293 			    "for a list of available legacy versions.\n"));
12294 		}
12295 
12296 		cb.cb_first = B_TRUE;
12297 		ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
12298 		assert(ret == 0);
12299 
12300 		if (cb.cb_first) {
12301 			(void) printf(gettext("Every feature flags pool has "
12302 			    "all supported and requested features enabled.\n"));
12303 		} else {
12304 			(void) printf(gettext("\n"));
12305 		}
12306 	} else {
12307 		ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
12308 		    B_FALSE, upgrade_one, &cb);
12309 	}
12310 
12311 	return (ret);
12312 }
12313 
12314 typedef struct hist_cbdata {
12315 	boolean_t first;
12316 	boolean_t longfmt;
12317 	boolean_t internal;
12318 } hist_cbdata_t;
12319 
12320 static void
12321 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
12322 {
12323 	nvlist_t **records;
12324 	uint_t numrecords;
12325 	int i;
12326 
12327 	verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
12328 	    &records, &numrecords) == 0);
12329 	for (i = 0; i < numrecords; i++) {
12330 		nvlist_t *rec = records[i];
12331 		char tbuf[64] = "";
12332 
12333 		if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
12334 			time_t tsec;
12335 			struct tm t;
12336 
12337 			tsec = fnvlist_lookup_uint64(records[i],
12338 			    ZPOOL_HIST_TIME);
12339 			(void) localtime_r(&tsec, &t);
12340 			(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
12341 		}
12342 
12343 		if (nvlist_exists(rec, ZPOOL_HIST_ELAPSED_NS)) {
12344 			uint64_t elapsed_ns = fnvlist_lookup_int64(records[i],
12345 			    ZPOOL_HIST_ELAPSED_NS);
12346 			(void) snprintf(tbuf + strlen(tbuf),
12347 			    sizeof (tbuf) - strlen(tbuf),
12348 			    " (%lldms)", (long long)elapsed_ns / 1000 / 1000);
12349 		}
12350 
12351 		if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
12352 			(void) printf("%s %s", tbuf,
12353 			    fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
12354 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
12355 			int ievent =
12356 			    fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
12357 			if (!cb->internal)
12358 				continue;
12359 			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
12360 				(void) printf("%s unrecognized record:\n",
12361 				    tbuf);
12362 				dump_nvlist(rec, 4);
12363 				continue;
12364 			}
12365 			(void) printf("%s [internal %s txg:%lld] %s", tbuf,
12366 			    zfs_history_event_names[ievent],
12367 			    (longlong_t)fnvlist_lookup_uint64(
12368 			    rec, ZPOOL_HIST_TXG),
12369 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
12370 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
12371 			if (!cb->internal)
12372 				continue;
12373 			(void) printf("%s [txg:%lld] %s", tbuf,
12374 			    (longlong_t)fnvlist_lookup_uint64(
12375 			    rec, ZPOOL_HIST_TXG),
12376 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
12377 			if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
12378 				(void) printf(" %s (%llu)",
12379 				    fnvlist_lookup_string(rec,
12380 				    ZPOOL_HIST_DSNAME),
12381 				    (u_longlong_t)fnvlist_lookup_uint64(rec,
12382 				    ZPOOL_HIST_DSID));
12383 			}
12384 			(void) printf(" %s", fnvlist_lookup_string(rec,
12385 			    ZPOOL_HIST_INT_STR));
12386 		} else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
12387 			if (!cb->internal)
12388 				continue;
12389 			(void) printf("%s ioctl %s\n", tbuf,
12390 			    fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
12391 			if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
12392 				(void) printf("    input:\n");
12393 				dump_nvlist(fnvlist_lookup_nvlist(rec,
12394 				    ZPOOL_HIST_INPUT_NVL), 8);
12395 			}
12396 			if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
12397 				(void) printf("    output:\n");
12398 				dump_nvlist(fnvlist_lookup_nvlist(rec,
12399 				    ZPOOL_HIST_OUTPUT_NVL), 8);
12400 			}
12401 			if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_SIZE)) {
12402 				(void) printf("    output nvlist omitted; "
12403 				    "original size: %lldKB\n",
12404 				    (longlong_t)fnvlist_lookup_int64(rec,
12405 				    ZPOOL_HIST_OUTPUT_SIZE) / 1024);
12406 			}
12407 			if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
12408 				(void) printf("    errno: %lld\n",
12409 				    (longlong_t)fnvlist_lookup_int64(rec,
12410 				    ZPOOL_HIST_ERRNO));
12411 			}
12412 		} else {
12413 			if (!cb->internal)
12414 				continue;
12415 			(void) printf("%s unrecognized record:\n", tbuf);
12416 			dump_nvlist(rec, 4);
12417 		}
12418 
12419 		if (!cb->longfmt) {
12420 			(void) printf("\n");
12421 			continue;
12422 		}
12423 		(void) printf(" [");
12424 		if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
12425 			uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
12426 			struct passwd *pwd = getpwuid(who);
12427 			(void) printf("user %d ", (int)who);
12428 			if (pwd != NULL)
12429 				(void) printf("(%s) ", pwd->pw_name);
12430 		}
12431 		if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
12432 			(void) printf("on %s",
12433 			    fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
12434 		}
12435 		if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
12436 			(void) printf(":%s",
12437 			    fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
12438 		}
12439 
12440 		(void) printf("]");
12441 		(void) printf("\n");
12442 	}
12443 }
12444 
12445 /*
12446  * Print out the command history for a specific pool.
12447  */
12448 static int
12449 get_history_one(zpool_handle_t *zhp, void *data)
12450 {
12451 	nvlist_t *nvhis;
12452 	int ret;
12453 	hist_cbdata_t *cb = (hist_cbdata_t *)data;
12454 	uint64_t off = 0;
12455 	boolean_t eof = B_FALSE;
12456 
12457 	cb->first = B_FALSE;
12458 
12459 	(void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
12460 
12461 	while (!eof) {
12462 		if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
12463 			return (ret);
12464 
12465 		print_history_records(nvhis, cb);
12466 		nvlist_free(nvhis);
12467 	}
12468 	(void) printf("\n");
12469 
12470 	return (ret);
12471 }
12472 
12473 /*
12474  * zpool history <pool>
12475  *
12476  * Displays the history of commands that modified pools.
12477  */
12478 int
12479 zpool_do_history(int argc, char **argv)
12480 {
12481 	hist_cbdata_t cbdata = { 0 };
12482 	int ret;
12483 	int c;
12484 
12485 	cbdata.first = B_TRUE;
12486 	/* check options */
12487 	while ((c = getopt(argc, argv, "li")) != -1) {
12488 		switch (c) {
12489 		case 'l':
12490 			cbdata.longfmt = B_TRUE;
12491 			break;
12492 		case 'i':
12493 			cbdata.internal = B_TRUE;
12494 			break;
12495 		case '?':
12496 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
12497 			    optopt);
12498 			usage(B_FALSE);
12499 		}
12500 	}
12501 	argc -= optind;
12502 	argv += optind;
12503 
12504 	ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
12505 	    B_FALSE, get_history_one, &cbdata);
12506 
12507 	if (argc == 0 && cbdata.first == B_TRUE) {
12508 		(void) fprintf(stderr, gettext("no pools available\n"));
12509 		return (0);
12510 	}
12511 
12512 	return (ret);
12513 }
12514 
12515 typedef struct ev_opts {
12516 	int verbose;
12517 	int scripted;
12518 	int follow;
12519 	int clear;
12520 	char poolname[ZFS_MAX_DATASET_NAME_LEN];
12521 } ev_opts_t;
12522 
12523 static void
12524 zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
12525 {
12526 	char ctime_str[26], str[32];
12527 	const char *ptr;
12528 	int64_t *tv;
12529 	uint_t n;
12530 
12531 	verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
12532 	memset(str, ' ', 32);
12533 	(void) ctime_r((const time_t *)&tv[0], ctime_str);
12534 	(void) memcpy(str, ctime_str+4,  6);		/* 'Jun 30' */
12535 	(void) memcpy(str+7, ctime_str+20, 4);		/* '1993' */
12536 	(void) memcpy(str+12, ctime_str+11, 8);		/* '21:49:08' */
12537 	(void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
12538 	if (opts->scripted)
12539 		(void) printf(gettext("%s\t"), str);
12540 	else
12541 		(void) printf(gettext("%s "), str);
12542 
12543 	verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
12544 	(void) printf(gettext("%s\n"), ptr);
12545 }
12546 
12547 static void
12548 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
12549 {
12550 	nvpair_t *nvp;
12551 	static char flagstr[256];
12552 
12553 	for (nvp = nvlist_next_nvpair(nvl, NULL);
12554 	    nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
12555 
12556 		data_type_t type = nvpair_type(nvp);
12557 		const char *name = nvpair_name(nvp);
12558 
12559 		boolean_t b;
12560 		uint8_t i8;
12561 		uint16_t i16;
12562 		uint32_t i32;
12563 		uint64_t i64;
12564 		const char *str;
12565 		nvlist_t *cnv;
12566 
12567 		printf(gettext("%*s%s = "), depth, "", name);
12568 
12569 		switch (type) {
12570 		case DATA_TYPE_BOOLEAN:
12571 			printf(gettext("%s"), "1");
12572 			break;
12573 
12574 		case DATA_TYPE_BOOLEAN_VALUE:
12575 			(void) nvpair_value_boolean_value(nvp, &b);
12576 			printf(gettext("%s"), b ? "1" : "0");
12577 			break;
12578 
12579 		case DATA_TYPE_BYTE:
12580 			(void) nvpair_value_byte(nvp, &i8);
12581 			printf(gettext("0x%x"), i8);
12582 			break;
12583 
12584 		case DATA_TYPE_INT8:
12585 			(void) nvpair_value_int8(nvp, (void *)&i8);
12586 			printf(gettext("0x%x"), i8);
12587 			break;
12588 
12589 		case DATA_TYPE_UINT8:
12590 			(void) nvpair_value_uint8(nvp, &i8);
12591 			printf(gettext("0x%x"), i8);
12592 			break;
12593 
12594 		case DATA_TYPE_INT16:
12595 			(void) nvpair_value_int16(nvp, (void *)&i16);
12596 			printf(gettext("0x%x"), i16);
12597 			break;
12598 
12599 		case DATA_TYPE_UINT16:
12600 			(void) nvpair_value_uint16(nvp, &i16);
12601 			printf(gettext("0x%x"), i16);
12602 			break;
12603 
12604 		case DATA_TYPE_INT32:
12605 			(void) nvpair_value_int32(nvp, (void *)&i32);
12606 			printf(gettext("0x%x"), i32);
12607 			break;
12608 
12609 		case DATA_TYPE_UINT32:
12610 			(void) nvpair_value_uint32(nvp, &i32);
12611 			if (strcmp(name,
12612 			    FM_EREPORT_PAYLOAD_ZFS_ZIO_STAGE) == 0 ||
12613 			    strcmp(name,
12614 			    FM_EREPORT_PAYLOAD_ZFS_ZIO_PIPELINE) == 0) {
12615 				(void) zfs_valstr_zio_stage(i32, flagstr,
12616 				    sizeof (flagstr));
12617 				printf(gettext("0x%x [%s]"), i32, flagstr);
12618 			} else if (strcmp(name,
12619 			    FM_EREPORT_PAYLOAD_ZFS_ZIO_TYPE) == 0) {
12620 				(void) zfs_valstr_zio_type(i32, flagstr,
12621 				    sizeof (flagstr));
12622 				printf(gettext("0x%x [%s]"), i32, flagstr);
12623 			} else if (strcmp(name,
12624 			    FM_EREPORT_PAYLOAD_ZFS_ZIO_PRIORITY) == 0) {
12625 				(void) zfs_valstr_zio_priority(i32, flagstr,
12626 				    sizeof (flagstr));
12627 				printf(gettext("0x%x [%s]"), i32, flagstr);
12628 			} else {
12629 				printf(gettext("0x%x"), i32);
12630 			}
12631 			break;
12632 
12633 		case DATA_TYPE_INT64:
12634 			(void) nvpair_value_int64(nvp, (void *)&i64);
12635 			printf(gettext("0x%llx"), (u_longlong_t)i64);
12636 			break;
12637 
12638 		case DATA_TYPE_UINT64:
12639 			(void) nvpair_value_uint64(nvp, &i64);
12640 			/*
12641 			 * translate vdev state values to readable
12642 			 * strings to aide zpool events consumers
12643 			 */
12644 			if (strcmp(name,
12645 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
12646 			    strcmp(name,
12647 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
12648 				printf(gettext("\"%s\" (0x%llx)"),
12649 				    zpool_state_to_name(i64, VDEV_AUX_NONE),
12650 				    (u_longlong_t)i64);
12651 			} else if (strcmp(name,
12652 			    FM_EREPORT_PAYLOAD_ZFS_ZIO_FLAGS) == 0) {
12653 				(void) zfs_valstr_zio_flag(i64, flagstr,
12654 				    sizeof (flagstr));
12655 				printf(gettext("0x%llx [%s]"),
12656 				    (u_longlong_t)i64, flagstr);
12657 			} else {
12658 				printf(gettext("0x%llx"), (u_longlong_t)i64);
12659 			}
12660 			break;
12661 
12662 		case DATA_TYPE_HRTIME:
12663 			(void) nvpair_value_hrtime(nvp, (void *)&i64);
12664 			printf(gettext("0x%llx"), (u_longlong_t)i64);
12665 			break;
12666 
12667 		case DATA_TYPE_STRING:
12668 			(void) nvpair_value_string(nvp, &str);
12669 			printf(gettext("\"%s\""), str ? str : "<NULL>");
12670 			break;
12671 
12672 		case DATA_TYPE_NVLIST:
12673 			printf(gettext("(embedded nvlist)\n"));
12674 			(void) nvpair_value_nvlist(nvp, &cnv);
12675 			zpool_do_events_nvprint(cnv, depth + 8);
12676 			printf(gettext("%*s(end %s)"), depth, "", name);
12677 			break;
12678 
12679 		case DATA_TYPE_NVLIST_ARRAY: {
12680 			nvlist_t **val;
12681 			uint_t i, nelem;
12682 
12683 			(void) nvpair_value_nvlist_array(nvp, &val, &nelem);
12684 			printf(gettext("(%d embedded nvlists)\n"), nelem);
12685 			for (i = 0; i < nelem; i++) {
12686 				printf(gettext("%*s%s[%d] = %s\n"),
12687 				    depth, "", name, i, "(embedded nvlist)");
12688 				zpool_do_events_nvprint(val[i], depth + 8);
12689 				printf(gettext("%*s(end %s[%i])\n"),
12690 				    depth, "", name, i);
12691 			}
12692 			printf(gettext("%*s(end %s)\n"), depth, "", name);
12693 			}
12694 			break;
12695 
12696 		case DATA_TYPE_INT8_ARRAY: {
12697 			int8_t *val;
12698 			uint_t i, nelem;
12699 
12700 			(void) nvpair_value_int8_array(nvp, &val, &nelem);
12701 			for (i = 0; i < nelem; i++)
12702 				printf(gettext("0x%x "), val[i]);
12703 
12704 			break;
12705 			}
12706 
12707 		case DATA_TYPE_UINT8_ARRAY: {
12708 			uint8_t *val;
12709 			uint_t i, nelem;
12710 
12711 			(void) nvpair_value_uint8_array(nvp, &val, &nelem);
12712 			for (i = 0; i < nelem; i++)
12713 				printf(gettext("0x%x "), val[i]);
12714 
12715 			break;
12716 			}
12717 
12718 		case DATA_TYPE_INT16_ARRAY: {
12719 			int16_t *val;
12720 			uint_t i, nelem;
12721 
12722 			(void) nvpair_value_int16_array(nvp, &val, &nelem);
12723 			for (i = 0; i < nelem; i++)
12724 				printf(gettext("0x%x "), val[i]);
12725 
12726 			break;
12727 			}
12728 
12729 		case DATA_TYPE_UINT16_ARRAY: {
12730 			uint16_t *val;
12731 			uint_t i, nelem;
12732 
12733 			(void) nvpair_value_uint16_array(nvp, &val, &nelem);
12734 			for (i = 0; i < nelem; i++)
12735 				printf(gettext("0x%x "), val[i]);
12736 
12737 			break;
12738 			}
12739 
12740 		case DATA_TYPE_INT32_ARRAY: {
12741 			int32_t *val;
12742 			uint_t i, nelem;
12743 
12744 			(void) nvpair_value_int32_array(nvp, &val, &nelem);
12745 			for (i = 0; i < nelem; i++)
12746 				printf(gettext("0x%x "), val[i]);
12747 
12748 			break;
12749 			}
12750 
12751 		case DATA_TYPE_UINT32_ARRAY: {
12752 			uint32_t *val;
12753 			uint_t i, nelem;
12754 
12755 			(void) nvpair_value_uint32_array(nvp, &val, &nelem);
12756 			for (i = 0; i < nelem; i++)
12757 				printf(gettext("0x%x "), val[i]);
12758 
12759 			break;
12760 			}
12761 
12762 		case DATA_TYPE_INT64_ARRAY: {
12763 			int64_t *val;
12764 			uint_t i, nelem;
12765 
12766 			(void) nvpair_value_int64_array(nvp, &val, &nelem);
12767 			for (i = 0; i < nelem; i++)
12768 				printf(gettext("0x%llx "),
12769 				    (u_longlong_t)val[i]);
12770 
12771 			break;
12772 			}
12773 
12774 		case DATA_TYPE_UINT64_ARRAY: {
12775 			uint64_t *val;
12776 			uint_t i, nelem;
12777 
12778 			(void) nvpair_value_uint64_array(nvp, &val, &nelem);
12779 			for (i = 0; i < nelem; i++)
12780 				printf(gettext("0x%llx "),
12781 				    (u_longlong_t)val[i]);
12782 
12783 			break;
12784 			}
12785 
12786 		case DATA_TYPE_STRING_ARRAY: {
12787 			const char **str;
12788 			uint_t i, nelem;
12789 
12790 			(void) nvpair_value_string_array(nvp, &str, &nelem);
12791 			for (i = 0; i < nelem; i++)
12792 				printf(gettext("\"%s\" "),
12793 				    str[i] ? str[i] : "<NULL>");
12794 
12795 			break;
12796 			}
12797 
12798 		case DATA_TYPE_BOOLEAN_ARRAY:
12799 		case DATA_TYPE_BYTE_ARRAY:
12800 		case DATA_TYPE_DOUBLE:
12801 		case DATA_TYPE_DONTCARE:
12802 		case DATA_TYPE_UNKNOWN:
12803 			printf(gettext("<unknown>"));
12804 			break;
12805 		}
12806 
12807 		printf(gettext("\n"));
12808 	}
12809 }
12810 
12811 static int
12812 zpool_do_events_next(ev_opts_t *opts)
12813 {
12814 	nvlist_t *nvl;
12815 	int zevent_fd, ret, dropped;
12816 	const char *pool;
12817 
12818 	zevent_fd = open(ZFS_DEV, O_RDWR);
12819 	VERIFY(zevent_fd >= 0);
12820 
12821 	if (!opts->scripted)
12822 		(void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
12823 
12824 	while (1) {
12825 		ret = zpool_events_next(g_zfs, &nvl, &dropped,
12826 		    (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
12827 		if (ret || nvl == NULL)
12828 			break;
12829 
12830 		if (dropped > 0)
12831 			(void) printf(gettext("dropped %d events\n"), dropped);
12832 
12833 		if (strlen(opts->poolname) > 0 &&
12834 		    nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
12835 		    strcmp(opts->poolname, pool) != 0)
12836 			continue;
12837 
12838 		zpool_do_events_short(nvl, opts);
12839 
12840 		if (opts->verbose) {
12841 			zpool_do_events_nvprint(nvl, 8);
12842 			printf(gettext("\n"));
12843 		}
12844 		(void) fflush(stdout);
12845 
12846 		nvlist_free(nvl);
12847 	}
12848 
12849 	VERIFY0(close(zevent_fd));
12850 
12851 	return (ret);
12852 }
12853 
12854 static int
12855 zpool_do_events_clear(void)
12856 {
12857 	int count, ret;
12858 
12859 	ret = zpool_events_clear(g_zfs, &count);
12860 	if (!ret)
12861 		(void) printf(gettext("cleared %d events\n"), count);
12862 
12863 	return (ret);
12864 }
12865 
12866 /*
12867  * zpool events [-vHf [pool] | -c]
12868  *
12869  * Displays events logs by ZFS.
12870  */
12871 int
12872 zpool_do_events(int argc, char **argv)
12873 {
12874 	ev_opts_t opts = { 0 };
12875 	int ret;
12876 	int c;
12877 
12878 	/* check options */
12879 	while ((c = getopt(argc, argv, "vHfc")) != -1) {
12880 		switch (c) {
12881 		case 'v':
12882 			opts.verbose = 1;
12883 			break;
12884 		case 'H':
12885 			opts.scripted = 1;
12886 			break;
12887 		case 'f':
12888 			opts.follow = 1;
12889 			break;
12890 		case 'c':
12891 			opts.clear = 1;
12892 			break;
12893 		case '?':
12894 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
12895 			    optopt);
12896 			usage(B_FALSE);
12897 		}
12898 	}
12899 	argc -= optind;
12900 	argv += optind;
12901 
12902 	if (argc > 1) {
12903 		(void) fprintf(stderr, gettext("too many arguments\n"));
12904 		usage(B_FALSE);
12905 	} else if (argc == 1) {
12906 		(void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
12907 		if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
12908 			(void) fprintf(stderr,
12909 			    gettext("invalid pool name '%s'\n"), opts.poolname);
12910 			usage(B_FALSE);
12911 		}
12912 	}
12913 
12914 	if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
12915 	    opts.clear) {
12916 		(void) fprintf(stderr,
12917 		    gettext("invalid options combined with -c\n"));
12918 		usage(B_FALSE);
12919 	}
12920 
12921 	if (opts.clear)
12922 		ret = zpool_do_events_clear();
12923 	else
12924 		ret = zpool_do_events_next(&opts);
12925 
12926 	return (ret);
12927 }
12928 
12929 static int
12930 get_callback_vdev(zpool_handle_t *zhp, char *vdevname, void *data)
12931 {
12932 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12933 	char value[ZFS_MAXPROPLEN];
12934 	zprop_source_t srctype;
12935 	nvlist_t *props, *item, *d;
12936 	props = item = d = NULL;
12937 
12938 	if (cbp->cb_json) {
12939 		d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "vdevs");
12940 		if (d == NULL) {
12941 			fprintf(stderr, "vdevs obj not found.\n");
12942 			exit(1);
12943 		}
12944 		props = fnvlist_alloc();
12945 	}
12946 
12947 	for (zprop_list_t *pl = cbp->cb_proplist; pl != NULL;
12948 	    pl = pl->pl_next) {
12949 		char *prop_name;
12950 		/*
12951 		 * If the first property is pool name, it is a special
12952 		 * placeholder that we can skip. This will also skip
12953 		 * over the name property when 'all' is specified.
12954 		 */
12955 		if (pl->pl_prop == ZPOOL_PROP_NAME &&
12956 		    pl == cbp->cb_proplist)
12957 			continue;
12958 
12959 		if (pl->pl_prop == ZPROP_INVAL) {
12960 			prop_name = pl->pl_user_prop;
12961 		} else {
12962 			prop_name = (char *)vdev_prop_to_name(pl->pl_prop);
12963 		}
12964 		if (zpool_get_vdev_prop(zhp, vdevname, pl->pl_prop,
12965 		    prop_name, value, sizeof (value), &srctype,
12966 		    cbp->cb_literal) == 0) {
12967 			(void) zprop_collect_property(vdevname, cbp, prop_name,
12968 			    value, srctype, NULL, NULL, props);
12969 		}
12970 	}
12971 
12972 	if (cbp->cb_json) {
12973 		if (!nvlist_empty(props)) {
12974 			item = fnvlist_alloc();
12975 			fill_vdev_info(item, zhp, vdevname, B_TRUE,
12976 			    cbp->cb_json_as_int);
12977 			fnvlist_add_nvlist(item, "properties", props);
12978 			fnvlist_add_nvlist(d, vdevname, item);
12979 			fnvlist_add_nvlist(cbp->cb_jsobj, "vdevs", d);
12980 			fnvlist_free(item);
12981 		}
12982 		fnvlist_free(props);
12983 	}
12984 
12985 	return (0);
12986 }
12987 
12988 static int
12989 get_callback_vdev_cb(void *zhp_data, nvlist_t *nv, void *data)
12990 {
12991 	zpool_handle_t *zhp = zhp_data;
12992 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12993 	char *vdevname;
12994 	const char *type;
12995 	int ret;
12996 
12997 	/*
12998 	 * zpool_vdev_name() transforms the root vdev name (i.e., root-0) to the
12999 	 * pool name for display purposes, which is not desired. Fallback to
13000 	 * zpool_vdev_name() when not dealing with the root vdev.
13001 	 */
13002 	type = fnvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE);
13003 	if (zhp != NULL && strcmp(type, "root") == 0)
13004 		vdevname = strdup("root-0");
13005 	else
13006 		vdevname = zpool_vdev_name(g_zfs, zhp, nv,
13007 		    cbp->cb_vdevs.cb_name_flags);
13008 
13009 	(void) vdev_expand_proplist(zhp, vdevname, &cbp->cb_proplist);
13010 
13011 	ret = get_callback_vdev(zhp, vdevname, data);
13012 
13013 	free(vdevname);
13014 
13015 	return (ret);
13016 }
13017 
13018 static int
13019 get_callback(zpool_handle_t *zhp, void *data)
13020 {
13021 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
13022 	char value[ZFS_MAXPROPLEN];
13023 	zprop_source_t srctype;
13024 	zprop_list_t *pl;
13025 	int vid;
13026 	int err = 0;
13027 	nvlist_t *props, *item, *d;
13028 	props = item = d = NULL;
13029 
13030 	if (cbp->cb_type == ZFS_TYPE_VDEV) {
13031 		if (cbp->cb_json) {
13032 			nvlist_t *pool = fnvlist_alloc();
13033 			fill_pool_info(pool, zhp, B_FALSE, cbp->cb_json_as_int);
13034 			fnvlist_add_nvlist(cbp->cb_jsobj, "pool", pool);
13035 			fnvlist_free(pool);
13036 		}
13037 
13038 		if (strcmp(cbp->cb_vdevs.cb_names[0], "all-vdevs") == 0) {
13039 			(void) for_each_vdev(zhp, get_callback_vdev_cb, data);
13040 		} else {
13041 			/* Adjust column widths for vdev properties */
13042 			for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
13043 			    vid++) {
13044 				(void) vdev_expand_proplist(zhp,
13045 				    cbp->cb_vdevs.cb_names[vid],
13046 				    &cbp->cb_proplist);
13047 			}
13048 			/* Display the properties */
13049 			for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
13050 			    vid++) {
13051 				(void) get_callback_vdev(zhp,
13052 				    cbp->cb_vdevs.cb_names[vid], data);
13053 			}
13054 		}
13055 	} else {
13056 		assert(cbp->cb_type == ZFS_TYPE_POOL);
13057 		if (cbp->cb_json) {
13058 			d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
13059 			if (d == NULL) {
13060 				fprintf(stderr, "pools obj not found.\n");
13061 				exit(1);
13062 			}
13063 			props = fnvlist_alloc();
13064 		}
13065 		for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
13066 			/*
13067 			 * Skip the special fake placeholder. This will also
13068 			 * skip over the name property when 'all' is specified.
13069 			 */
13070 			if (pl->pl_prop == ZPOOL_PROP_NAME &&
13071 			    pl == cbp->cb_proplist)
13072 				continue;
13073 
13074 			if (pl->pl_prop == ZPROP_INVAL &&
13075 			    zfs_prop_user(pl->pl_user_prop)) {
13076 				srctype = ZPROP_SRC_LOCAL;
13077 
13078 				if (zpool_get_userprop(zhp, pl->pl_user_prop,
13079 				    value, sizeof (value), &srctype) != 0)
13080 					continue;
13081 
13082 				err = zprop_collect_property(
13083 				    zpool_get_name(zhp), cbp, pl->pl_user_prop,
13084 				    value, srctype, NULL, NULL, props);
13085 			} else if (pl->pl_prop == ZPROP_INVAL &&
13086 			    (zpool_prop_feature(pl->pl_user_prop) ||
13087 			    zpool_prop_unsupported(pl->pl_user_prop))) {
13088 				srctype = ZPROP_SRC_LOCAL;
13089 
13090 				if (zpool_prop_get_feature(zhp,
13091 				    pl->pl_user_prop, value,
13092 				    sizeof (value)) == 0) {
13093 					err = zprop_collect_property(
13094 					    zpool_get_name(zhp), cbp,
13095 					    pl->pl_user_prop, value, srctype,
13096 					    NULL, NULL, props);
13097 				}
13098 			} else {
13099 				if (zpool_get_prop(zhp, pl->pl_prop, value,
13100 				    sizeof (value), &srctype,
13101 				    cbp->cb_literal) != 0)
13102 					continue;
13103 
13104 				err = zprop_collect_property(
13105 				    zpool_get_name(zhp), cbp,
13106 				    zpool_prop_to_name(pl->pl_prop),
13107 				    value, srctype, NULL, NULL, props);
13108 			}
13109 			if (err != 0)
13110 				return (err);
13111 		}
13112 
13113 		if (cbp->cb_json) {
13114 			if (!nvlist_empty(props)) {
13115 				item = fnvlist_alloc();
13116 				fill_pool_info(item, zhp, B_TRUE,
13117 				    cbp->cb_json_as_int);
13118 				fnvlist_add_nvlist(item, "properties", props);
13119 				if (cbp->cb_json_pool_key_guid) {
13120 					char buf[256];
13121 					uint64_t guid = fnvlist_lookup_uint64(
13122 					    zpool_get_config(zhp, NULL),
13123 					    ZPOOL_CONFIG_POOL_GUID);
13124 					(void) snprintf(buf, 256, "%llu",
13125 					    (u_longlong_t)guid);
13126 					fnvlist_add_nvlist(d, buf, item);
13127 				} else {
13128 					const char *name = zpool_get_name(zhp);
13129 					fnvlist_add_nvlist(d, name, item);
13130 				}
13131 				fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
13132 				fnvlist_free(item);
13133 			}
13134 			fnvlist_free(props);
13135 		}
13136 	}
13137 
13138 	return (0);
13139 }
13140 
13141 /*
13142  * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
13143  *
13144  *	-H	Scripted mode.  Don't display headers, and separate properties
13145  *		by a single tab.
13146  *	-o	List of columns to display.  Defaults to
13147  *		"name,property,value,source".
13148  * 	-p	Display values in parsable (exact) format.
13149  * 	-j	Display output in JSON format.
13150  * 	--json-int	Display numbers as integers instead of strings.
13151  * 	--json-pool-key-guid	Set pool GUID as key for pool objects.
13152  *
13153  * Get properties of pools in the system. Output space statistics
13154  * for each one as well as other attributes.
13155  */
13156 int
13157 zpool_do_get(int argc, char **argv)
13158 {
13159 	zprop_get_cbdata_t cb = { 0 };
13160 	zprop_list_t fake_name = { 0 };
13161 	int ret;
13162 	int c, i;
13163 	char *propstr = NULL;
13164 	char *vdev = NULL;
13165 	nvlist_t *data = NULL;
13166 
13167 	cb.cb_first = B_TRUE;
13168 
13169 	/*
13170 	 * Set up default columns and sources.
13171 	 */
13172 	cb.cb_sources = ZPROP_SRC_ALL;
13173 	cb.cb_columns[0] = GET_COL_NAME;
13174 	cb.cb_columns[1] = GET_COL_PROPERTY;
13175 	cb.cb_columns[2] = GET_COL_VALUE;
13176 	cb.cb_columns[3] = GET_COL_SOURCE;
13177 	cb.cb_type = ZFS_TYPE_POOL;
13178 	cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
13179 	current_prop_type = cb.cb_type;
13180 
13181 	struct option long_options[] = {
13182 		{"json", no_argument, NULL, 'j'},
13183 		{"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
13184 		{"json-pool-key-guid", no_argument, NULL,
13185 		    ZPOOL_OPTION_POOL_KEY_GUID},
13186 		{0, 0, 0, 0}
13187 	};
13188 
13189 	/* check options */
13190 	while ((c = getopt_long(argc, argv, ":jHpo:", long_options,
13191 	    NULL)) != -1) {
13192 		switch (c) {
13193 		case 'p':
13194 			cb.cb_literal = B_TRUE;
13195 			break;
13196 		case 'H':
13197 			cb.cb_scripted = B_TRUE;
13198 			break;
13199 		case 'j':
13200 			cb.cb_json = B_TRUE;
13201 			cb.cb_jsobj = zpool_json_schema(0, 1);
13202 			data = fnvlist_alloc();
13203 			break;
13204 		case ZPOOL_OPTION_POOL_KEY_GUID:
13205 			cb.cb_json_pool_key_guid = B_TRUE;
13206 			break;
13207 		case ZPOOL_OPTION_JSON_NUMS_AS_INT:
13208 			cb.cb_json_as_int = B_TRUE;
13209 			cb.cb_literal = B_TRUE;
13210 			break;
13211 		case 'o':
13212 			memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
13213 			i = 0;
13214 
13215 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
13216 				static const char *const col_opts[] =
13217 				{ "name", "property", "value", "source",
13218 				    "all" };
13219 				static const zfs_get_column_t col_cols[] =
13220 				{ GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
13221 				    GET_COL_SOURCE };
13222 
13223 				if (i == ZFS_GET_NCOLS - 1) {
13224 					(void) fprintf(stderr, gettext("too "
13225 					"many fields given to -o "
13226 					"option\n"));
13227 					usage(B_FALSE);
13228 				}
13229 
13230 				for (c = 0; c < ARRAY_SIZE(col_opts); ++c)
13231 					if (strcmp(tok, col_opts[c]) == 0)
13232 						goto found;
13233 
13234 				(void) fprintf(stderr,
13235 				    gettext("invalid column name '%s'\n"), tok);
13236 				usage(B_FALSE);
13237 
13238 found:
13239 				if (c >= 4) {
13240 					if (i > 0) {
13241 						(void) fprintf(stderr,
13242 						    gettext("\"all\" conflicts "
13243 						    "with specific fields "
13244 						    "given to -o option\n"));
13245 						usage(B_FALSE);
13246 					}
13247 
13248 					memcpy(cb.cb_columns, col_cols,
13249 					    sizeof (col_cols));
13250 					i = ZFS_GET_NCOLS - 1;
13251 				} else
13252 					cb.cb_columns[i++] = col_cols[c];
13253 			}
13254 			break;
13255 		case '?':
13256 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
13257 			    optopt);
13258 			usage(B_FALSE);
13259 		}
13260 	}
13261 
13262 	argc -= optind;
13263 	argv += optind;
13264 
13265 	if (!cb.cb_json && cb.cb_json_as_int) {
13266 		(void) fprintf(stderr, gettext("'--json-int' only works with"
13267 		    " '-j' option\n"));
13268 		usage(B_FALSE);
13269 	}
13270 
13271 	if (!cb.cb_json && cb.cb_json_pool_key_guid) {
13272 		(void) fprintf(stderr, gettext("'json-pool-key-guid' only"
13273 		    " works with '-j' option\n"));
13274 		usage(B_FALSE);
13275 	}
13276 
13277 	if (argc < 1) {
13278 		(void) fprintf(stderr, gettext("missing property "
13279 		    "argument\n"));
13280 		usage(B_FALSE);
13281 	}
13282 
13283 	/* Properties list is needed later by zprop_get_list() */
13284 	propstr = argv[0];
13285 
13286 	argc--;
13287 	argv++;
13288 
13289 	if (argc == 0) {
13290 		/* No args, so just print the defaults. */
13291 	} else if (are_all_pools(argc, argv)) {
13292 		/* All the args are pool names */
13293 	} else if (are_all_pools(1, argv)) {
13294 		/* The first arg is a pool name */
13295 		if ((argc == 2 && strcmp(argv[1], "all-vdevs") == 0) ||
13296 		    (argc == 2 && strcmp(argv[1], "root") == 0) ||
13297 		    are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
13298 		    &cb.cb_vdevs)) {
13299 
13300 			if (strcmp(argv[1], "root") == 0)
13301 				vdev = strdup("root-0");
13302 
13303 			/* ... and the rest are vdev names */
13304 			if (vdev == NULL)
13305 				cb.cb_vdevs.cb_names = argv + 1;
13306 			else
13307 				cb.cb_vdevs.cb_names = &vdev;
13308 
13309 			cb.cb_vdevs.cb_names_count = argc - 1;
13310 			cb.cb_type = ZFS_TYPE_VDEV;
13311 			argc = 1; /* One pool to process */
13312 		} else {
13313 			if (cb.cb_json) {
13314 				nvlist_free(cb.cb_jsobj);
13315 				nvlist_free(data);
13316 			}
13317 			fprintf(stderr, gettext("Expected a list of vdevs in"
13318 			    " \"%s\", but got:\n"), argv[0]);
13319 			error_list_unresolved_vdevs(argc - 1, argv + 1,
13320 			    argv[0], &cb.cb_vdevs);
13321 			fprintf(stderr, "\n");
13322 			usage(B_FALSE);
13323 		}
13324 	} else {
13325 		if (cb.cb_json) {
13326 			nvlist_free(cb.cb_jsobj);
13327 			nvlist_free(data);
13328 		}
13329 		/*
13330 		 * The first arg isn't the name of a valid pool.
13331 		 */
13332 		fprintf(stderr, gettext("Cannot get properties of %s: "
13333 		    "no such pool available.\n"), argv[0]);
13334 		return (1);
13335 	}
13336 
13337 	if (zprop_get_list(g_zfs, propstr, &cb.cb_proplist,
13338 	    cb.cb_type) != 0) {
13339 		/* Use correct list of valid properties (pool or vdev) */
13340 		current_prop_type = cb.cb_type;
13341 		usage(B_FALSE);
13342 	}
13343 
13344 	if (cb.cb_proplist != NULL) {
13345 		fake_name.pl_prop = ZPOOL_PROP_NAME;
13346 		fake_name.pl_width = strlen(gettext("NAME"));
13347 		fake_name.pl_next = cb.cb_proplist;
13348 		cb.cb_proplist = &fake_name;
13349 	}
13350 
13351 	if (cb.cb_json) {
13352 		if (cb.cb_type == ZFS_TYPE_VDEV)
13353 			fnvlist_add_nvlist(cb.cb_jsobj, "vdevs", data);
13354 		else
13355 			fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
13356 		fnvlist_free(data);
13357 	}
13358 
13359 	ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist, cb.cb_type,
13360 	    cb.cb_literal, get_callback, &cb);
13361 
13362 	if (ret == 0 && cb.cb_json)
13363 		zcmd_print_json(cb.cb_jsobj);
13364 	else if (ret != 0 && cb.cb_json)
13365 		nvlist_free(cb.cb_jsobj);
13366 
13367 	if (cb.cb_proplist == &fake_name)
13368 		zprop_free_list(fake_name.pl_next);
13369 	else
13370 		zprop_free_list(cb.cb_proplist);
13371 
13372 	if (vdev != NULL)
13373 		free(vdev);
13374 
13375 	return (ret);
13376 }
13377 
13378 typedef struct set_cbdata {
13379 	char *cb_propname;
13380 	char *cb_value;
13381 	zfs_type_t cb_type;
13382 	vdev_cbdata_t cb_vdevs;
13383 	boolean_t cb_any_successful;
13384 } set_cbdata_t;
13385 
13386 static int
13387 set_pool_callback(zpool_handle_t *zhp, set_cbdata_t *cb)
13388 {
13389 	int error;
13390 
13391 	/* Check if we have out-of-bounds features */
13392 	if (strcmp(cb->cb_propname, ZPOOL_CONFIG_COMPATIBILITY) == 0) {
13393 		boolean_t features[SPA_FEATURES];
13394 		if (zpool_do_load_compat(cb->cb_value, features) !=
13395 		    ZPOOL_COMPATIBILITY_OK)
13396 			return (-1);
13397 
13398 		nvlist_t *enabled = zpool_get_features(zhp);
13399 		spa_feature_t i;
13400 		for (i = 0; i < SPA_FEATURES; i++) {
13401 			const char *fguid = spa_feature_table[i].fi_guid;
13402 			if (nvlist_exists(enabled, fguid) && !features[i])
13403 				break;
13404 		}
13405 		if (i < SPA_FEATURES)
13406 			(void) fprintf(stderr, gettext("Warning: one or "
13407 			    "more features already enabled on pool '%s'\n"
13408 			    "are not present in this compatibility set.\n"),
13409 			    zpool_get_name(zhp));
13410 	}
13411 
13412 	/* if we're setting a feature, check it's in compatibility set */
13413 	if (zpool_prop_feature(cb->cb_propname) &&
13414 	    strcmp(cb->cb_value, ZFS_FEATURE_ENABLED) == 0) {
13415 		char *fname = strchr(cb->cb_propname, '@') + 1;
13416 		spa_feature_t f;
13417 
13418 		if (zfeature_lookup_name(fname, &f) == 0) {
13419 			char compat[ZFS_MAXPROPLEN];
13420 			if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY,
13421 			    compat, ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
13422 				compat[0] = '\0';
13423 
13424 			boolean_t features[SPA_FEATURES];
13425 			if (zpool_do_load_compat(compat, features) !=
13426 			    ZPOOL_COMPATIBILITY_OK) {
13427 				(void) fprintf(stderr, gettext("Error: "
13428 				    "cannot enable feature '%s' on pool '%s'\n"
13429 				    "because the pool's 'compatibility' "
13430 				    "property cannot be parsed.\n"),
13431 				    fname, zpool_get_name(zhp));
13432 				return (-1);
13433 			}
13434 
13435 			if (!features[f]) {
13436 				(void) fprintf(stderr, gettext("Error: "
13437 				    "cannot enable feature '%s' on pool '%s'\n"
13438 				    "as it is not specified in this pool's "
13439 				    "current compatibility set.\n"
13440 				    "Consider setting 'compatibility' to a "
13441 				    "less restrictive set, or to 'off'.\n"),
13442 				    fname, zpool_get_name(zhp));
13443 				return (-1);
13444 			}
13445 		}
13446 	}
13447 
13448 	error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
13449 
13450 	return (error);
13451 }
13452 
13453 static int
13454 set_callback(zpool_handle_t *zhp, void *data)
13455 {
13456 	int error;
13457 	set_cbdata_t *cb = (set_cbdata_t *)data;
13458 
13459 	if (cb->cb_type == ZFS_TYPE_VDEV) {
13460 		error = zpool_set_vdev_prop(zhp, *cb->cb_vdevs.cb_names,
13461 		    cb->cb_propname, cb->cb_value);
13462 	} else {
13463 		assert(cb->cb_type == ZFS_TYPE_POOL);
13464 		error = set_pool_callback(zhp, cb);
13465 	}
13466 
13467 	cb->cb_any_successful = !error;
13468 	return (error);
13469 }
13470 
13471 int
13472 zpool_do_set(int argc, char **argv)
13473 {
13474 	set_cbdata_t cb = { 0 };
13475 	int error;
13476 	char *vdev = NULL;
13477 
13478 	current_prop_type = ZFS_TYPE_POOL;
13479 	if (argc > 1 && argv[1][0] == '-') {
13480 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
13481 		    argv[1][1]);
13482 		usage(B_FALSE);
13483 	}
13484 
13485 	if (argc < 2) {
13486 		(void) fprintf(stderr, gettext("missing property=value "
13487 		    "argument\n"));
13488 		usage(B_FALSE);
13489 	}
13490 
13491 	if (argc < 3) {
13492 		(void) fprintf(stderr, gettext("missing pool name\n"));
13493 		usage(B_FALSE);
13494 	}
13495 
13496 	if (argc > 4) {
13497 		(void) fprintf(stderr, gettext("too many pool names\n"));
13498 		usage(B_FALSE);
13499 	}
13500 
13501 	cb.cb_propname = argv[1];
13502 	cb.cb_type = ZFS_TYPE_POOL;
13503 	cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
13504 	cb.cb_value = strchr(cb.cb_propname, '=');
13505 	if (cb.cb_value == NULL) {
13506 		(void) fprintf(stderr, gettext("missing value in "
13507 		    "property=value argument\n"));
13508 		usage(B_FALSE);
13509 	}
13510 
13511 	*(cb.cb_value) = '\0';
13512 	cb.cb_value++;
13513 	argc -= 2;
13514 	argv += 2;
13515 
13516 	/* argv[0] is pool name */
13517 	if (!is_pool(argv[0])) {
13518 		(void) fprintf(stderr,
13519 		    gettext("cannot open '%s': is not a pool\n"), argv[0]);
13520 		return (EINVAL);
13521 	}
13522 
13523 	/* argv[1], when supplied, is vdev name */
13524 	if (argc == 2) {
13525 
13526 		if (strcmp(argv[1], "root") == 0)
13527 			vdev = strdup("root-0");
13528 		else
13529 			vdev = strdup(argv[1]);
13530 
13531 		if (!are_vdevs_in_pool(1, &vdev, argv[0], &cb.cb_vdevs)) {
13532 			(void) fprintf(stderr, gettext(
13533 			    "cannot find '%s' in '%s': device not in pool\n"),
13534 			    vdev, argv[0]);
13535 			free(vdev);
13536 			return (EINVAL);
13537 		}
13538 		cb.cb_vdevs.cb_names = &vdev;
13539 		cb.cb_vdevs.cb_names_count = 1;
13540 		cb.cb_type = ZFS_TYPE_VDEV;
13541 	}
13542 
13543 	error = for_each_pool(1, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
13544 	    B_FALSE, set_callback, &cb);
13545 
13546 	if (vdev != NULL)
13547 		free(vdev);
13548 
13549 	return (error);
13550 }
13551 
13552 /* Add up the total number of bytes left to initialize/trim across all vdevs */
13553 static uint64_t
13554 vdev_activity_remaining(nvlist_t *nv, zpool_wait_activity_t activity)
13555 {
13556 	uint64_t bytes_remaining;
13557 	nvlist_t **child;
13558 	uint_t c, children;
13559 	vdev_stat_t *vs;
13560 
13561 	assert(activity == ZPOOL_WAIT_INITIALIZE ||
13562 	    activity == ZPOOL_WAIT_TRIM);
13563 
13564 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
13565 	    (uint64_t **)&vs, &c) == 0);
13566 
13567 	if (activity == ZPOOL_WAIT_INITIALIZE &&
13568 	    vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE)
13569 		bytes_remaining = vs->vs_initialize_bytes_est -
13570 		    vs->vs_initialize_bytes_done;
13571 	else if (activity == ZPOOL_WAIT_TRIM &&
13572 	    vs->vs_trim_state == VDEV_TRIM_ACTIVE)
13573 		bytes_remaining = vs->vs_trim_bytes_est -
13574 		    vs->vs_trim_bytes_done;
13575 	else
13576 		bytes_remaining = 0;
13577 
13578 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13579 	    &child, &children) != 0)
13580 		children = 0;
13581 
13582 	for (c = 0; c < children; c++)
13583 		bytes_remaining += vdev_activity_remaining(child[c], activity);
13584 
13585 	return (bytes_remaining);
13586 }
13587 
13588 /* Add up the total number of bytes left to rebuild across top-level vdevs */
13589 static uint64_t
13590 vdev_activity_top_remaining(nvlist_t *nv)
13591 {
13592 	uint64_t bytes_remaining = 0;
13593 	nvlist_t **child;
13594 	uint_t children;
13595 	int error;
13596 
13597 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13598 	    &child, &children) != 0)
13599 		children = 0;
13600 
13601 	for (uint_t c = 0; c < children; c++) {
13602 		vdev_rebuild_stat_t *vrs;
13603 		uint_t i;
13604 
13605 		error = nvlist_lookup_uint64_array(child[c],
13606 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i);
13607 		if (error == 0) {
13608 			if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
13609 				bytes_remaining += (vrs->vrs_bytes_est -
13610 				    vrs->vrs_bytes_rebuilt);
13611 			}
13612 		}
13613 	}
13614 
13615 	return (bytes_remaining);
13616 }
13617 
13618 /* Whether any vdevs are 'spare' or 'replacing' vdevs */
13619 static boolean_t
13620 vdev_any_spare_replacing(nvlist_t *nv)
13621 {
13622 	nvlist_t **child;
13623 	uint_t c, children;
13624 	const char *vdev_type;
13625 
13626 	(void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &vdev_type);
13627 
13628 	if (strcmp(vdev_type, VDEV_TYPE_REPLACING) == 0 ||
13629 	    strcmp(vdev_type, VDEV_TYPE_SPARE) == 0 ||
13630 	    strcmp(vdev_type, VDEV_TYPE_DRAID_SPARE) == 0) {
13631 		return (B_TRUE);
13632 	}
13633 
13634 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13635 	    &child, &children) != 0)
13636 		children = 0;
13637 
13638 	for (c = 0; c < children; c++) {
13639 		if (vdev_any_spare_replacing(child[c]))
13640 			return (B_TRUE);
13641 	}
13642 
13643 	return (B_FALSE);
13644 }
13645 
13646 typedef struct wait_data {
13647 	char *wd_poolname;
13648 	boolean_t wd_scripted;
13649 	boolean_t wd_exact;
13650 	boolean_t wd_headers_once;
13651 	boolean_t wd_should_exit;
13652 	/* Which activities to wait for */
13653 	boolean_t wd_enabled[ZPOOL_WAIT_NUM_ACTIVITIES];
13654 	float wd_interval;
13655 	pthread_cond_t wd_cv;
13656 	pthread_mutex_t wd_mutex;
13657 } wait_data_t;
13658 
13659 /*
13660  * Print to stdout a single line, containing one column for each activity that
13661  * we are waiting for specifying how many bytes of work are left for that
13662  * activity.
13663  */
13664 static void
13665 print_wait_status_row(wait_data_t *wd, zpool_handle_t *zhp, int row)
13666 {
13667 	nvlist_t *config, *nvroot;
13668 	uint_t c;
13669 	int i;
13670 	pool_checkpoint_stat_t *pcs = NULL;
13671 	pool_scan_stat_t *pss = NULL;
13672 	pool_removal_stat_t *prs = NULL;
13673 	pool_raidz_expand_stat_t *pres = NULL;
13674 	nvlist_t *cnv = NULL;
13675 	const char *const headers[] = {"DISCARD", "FREE", "INITIALIZE",
13676 	    "REPLACE", "REMOVE", "RESILVER", "SCRUB", "TRIM", "RAIDZ_EXPAND",
13677 	    "CONDENSE"};
13678 	int col_widths[ZPOOL_WAIT_NUM_ACTIVITIES];
13679 
13680 	/* Calculate the width of each column */
13681 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13682 		/*
13683 		 * Make sure we have enough space in the col for pretty-printed
13684 		 * numbers and for the column header, and then leave a couple
13685 		 * spaces between cols for readability.
13686 		 */
13687 		col_widths[i] = MAX(strlen(headers[i]), 6) + 2;
13688 	}
13689 
13690 	if (timestamp_fmt != NODATE)
13691 		print_timestamp(timestamp_fmt);
13692 
13693 	/* Print header if appropriate */
13694 	int term_height = terminal_height();
13695 	boolean_t reprint_header = (!wd->wd_headers_once && term_height > 0 &&
13696 	    row % (term_height-1) == 0);
13697 	if (!wd->wd_scripted && (row == 0 || reprint_header)) {
13698 		for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13699 			if (wd->wd_enabled[i])
13700 				(void) printf("%*s", col_widths[i], headers[i]);
13701 		}
13702 		(void) fputc('\n', stdout);
13703 	}
13704 
13705 	/* Bytes of work remaining in each activity */
13706 	int64_t bytes_rem[ZPOOL_WAIT_NUM_ACTIVITIES] = {0};
13707 
13708 	bytes_rem[ZPOOL_WAIT_FREE] =
13709 	    zpool_get_prop_int(zhp, ZPOOL_PROP_FREEING, NULL);
13710 
13711 	config = zpool_get_config(zhp, NULL);
13712 	nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
13713 
13714 	(void) nvlist_lookup_uint64_array(nvroot,
13715 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
13716 	if (pcs != NULL && pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
13717 		bytes_rem[ZPOOL_WAIT_CKPT_DISCARD] = pcs->pcs_space;
13718 
13719 	(void) nvlist_lookup_uint64_array(nvroot,
13720 	    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
13721 	if (prs != NULL && prs->prs_state == DSS_SCANNING)
13722 		bytes_rem[ZPOOL_WAIT_REMOVE] = prs->prs_to_copy -
13723 		    prs->prs_copied;
13724 
13725 	(void) nvlist_lookup_uint64_array(nvroot,
13726 	    ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&pss, &c);
13727 	if (pss != NULL && pss->pss_state == DSS_SCANNING &&
13728 	    pss->pss_pass_scrub_pause == 0) {
13729 		int64_t rem = pss->pss_to_examine - pss->pss_issued;
13730 		if (pss->pss_func == POOL_SCAN_SCRUB)
13731 			bytes_rem[ZPOOL_WAIT_SCRUB] = rem;
13732 		else
13733 			bytes_rem[ZPOOL_WAIT_RESILVER] = rem;
13734 	} else if (check_rebuilding(nvroot, NULL)) {
13735 		bytes_rem[ZPOOL_WAIT_RESILVER] =
13736 		    vdev_activity_top_remaining(nvroot);
13737 	}
13738 
13739 	(void) nvlist_lookup_uint64_array(nvroot,
13740 	    ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
13741 	if (pres != NULL && pres->pres_state == DSS_SCANNING) {
13742 		int64_t rem = pres->pres_to_reflow - pres->pres_reflowed;
13743 		bytes_rem[ZPOOL_WAIT_RAIDZ_EXPAND] = rem;
13744 	}
13745 
13746 	/*
13747 	 * Count each outstanding condense item as a "byte". Its not true,
13748 	 * but its a counter, and it'll display nicely.
13749 	 */
13750 	if (nvlist_lookup_nvlist(nvroot,
13751 	    ZPOOL_CONFIG_CONDENSE_STATS, &cnv) == 0) {
13752 		for (nvpair_t *nvp = nvlist_next_nvpair(cnv, NULL);
13753 		    nvp != NULL; nvp = nvlist_next_nvpair(cnv, nvp)) {
13754 			nvlist_t *tnv = fnvpair_value_nvlist(nvp);
13755 			uint64_t total = fnvlist_lookup_uint64(tnv, "total");
13756 			uint64_t processed =
13757 			    fnvlist_lookup_uint64(tnv, "processed");
13758 			bytes_rem[ZPOOL_WAIT_CONDENSE] += (total - processed);
13759 		}
13760 	}
13761 
13762 	bytes_rem[ZPOOL_WAIT_INITIALIZE] =
13763 	    vdev_activity_remaining(nvroot, ZPOOL_WAIT_INITIALIZE);
13764 	bytes_rem[ZPOOL_WAIT_TRIM] =
13765 	    vdev_activity_remaining(nvroot, ZPOOL_WAIT_TRIM);
13766 
13767 	/*
13768 	 * A replace finishes after resilvering finishes, so the amount of work
13769 	 * left for a replace is the same as for resilvering.
13770 	 *
13771 	 * It isn't quite correct to say that if we have any 'spare' or
13772 	 * 'replacing' vdevs and a resilver is happening, then a replace is in
13773 	 * progress, like we do here. When a hot spare is used, the faulted vdev
13774 	 * is not removed after the hot spare is resilvered, so parent 'spare'
13775 	 * vdev is not removed either. So we could have a 'spare' vdev, but be
13776 	 * resilvering for a different reason. However, we use it as a heuristic
13777 	 * because we don't have access to the DTLs, which could tell us whether
13778 	 * or not we have really finished resilvering a hot spare.
13779 	 */
13780 	if (vdev_any_spare_replacing(nvroot))
13781 		bytes_rem[ZPOOL_WAIT_REPLACE] =  bytes_rem[ZPOOL_WAIT_RESILVER];
13782 
13783 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13784 		char buf[64];
13785 		if (!wd->wd_enabled[i])
13786 			continue;
13787 
13788 		if (wd->wd_exact) {
13789 			(void) snprintf(buf, sizeof (buf), "%" PRIi64,
13790 			    bytes_rem[i]);
13791 		} else {
13792 			zfs_nicenum(bytes_rem[i], buf, sizeof (buf));
13793 		}
13794 
13795 		if (wd->wd_scripted)
13796 			(void) printf(i == 0 ? "%s" : "\t%s", buf);
13797 		else
13798 			(void) printf(" %*s", col_widths[i] - 1, buf);
13799 	}
13800 	(void) printf("\n");
13801 	(void) fflush(stdout);
13802 }
13803 
13804 static void *
13805 wait_status_thread(void *arg)
13806 {
13807 	wait_data_t *wd = (wait_data_t *)arg;
13808 	zpool_handle_t *zhp;
13809 
13810 	if ((zhp = zpool_open(g_zfs, wd->wd_poolname)) == NULL)
13811 		return (void *)(1);
13812 
13813 	for (int row = 0; ; row++) {
13814 		boolean_t missing;
13815 		struct timespec timeout;
13816 		int ret = 0;
13817 		(void) clock_gettime(CLOCK_REALTIME, &timeout);
13818 
13819 		if (zpool_refresh_stats(zhp, &missing) != 0 || missing ||
13820 		    zpool_props_refresh(zhp) != 0) {
13821 			zpool_close(zhp);
13822 			return (void *)(uintptr_t)(missing ? 0 : 1);
13823 		}
13824 
13825 		print_wait_status_row(wd, zhp, row);
13826 
13827 		timeout.tv_sec += floor(wd->wd_interval);
13828 		long nanos = timeout.tv_nsec +
13829 		    (wd->wd_interval - floor(wd->wd_interval)) * NANOSEC;
13830 		if (nanos >= NANOSEC) {
13831 			timeout.tv_sec++;
13832 			timeout.tv_nsec = nanos - NANOSEC;
13833 		} else {
13834 			timeout.tv_nsec = nanos;
13835 		}
13836 		(void) pthread_mutex_lock(&wd->wd_mutex);
13837 		if (!wd->wd_should_exit)
13838 			ret = pthread_cond_timedwait(&wd->wd_cv, &wd->wd_mutex,
13839 			    &timeout);
13840 		(void) pthread_mutex_unlock(&wd->wd_mutex);
13841 		if (ret == 0) {
13842 			break; /* signaled by main thread */
13843 		} else if (ret != ETIMEDOUT) {
13844 			(void) fprintf(stderr, gettext("pthread_cond_timedwait "
13845 			    "failed: %s\n"), strerror(ret));
13846 			zpool_close(zhp);
13847 			return (void *)(uintptr_t)(1);
13848 		}
13849 	}
13850 
13851 	zpool_close(zhp);
13852 	return (void *)(0);
13853 }
13854 
13855 int
13856 zpool_do_wait(int argc, char **argv)
13857 {
13858 	boolean_t verbose = B_FALSE;
13859 	int c, i;
13860 	unsigned long count;
13861 	pthread_t status_thr;
13862 	int error = 0;
13863 	zpool_handle_t *zhp;
13864 
13865 	wait_data_t wd;
13866 	wd.wd_scripted = B_FALSE;
13867 	wd.wd_exact = B_FALSE;
13868 	wd.wd_headers_once = B_FALSE;
13869 	wd.wd_should_exit = B_FALSE;
13870 
13871 	(void) pthread_mutex_init(&wd.wd_mutex, NULL);
13872 	(void) pthread_cond_init(&wd.wd_cv, NULL);
13873 
13874 	/* By default, wait for all types of activity. */
13875 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++)
13876 		wd.wd_enabled[i] = B_TRUE;
13877 
13878 	while ((c = getopt(argc, argv, "HpT:t:")) != -1) {
13879 		switch (c) {
13880 		case 'H':
13881 			wd.wd_scripted = B_TRUE;
13882 			break;
13883 		case 'n':
13884 			wd.wd_headers_once = B_TRUE;
13885 			break;
13886 		case 'p':
13887 			wd.wd_exact = B_TRUE;
13888 			break;
13889 		case 'T':
13890 			get_timestamp_arg(*optarg);
13891 			break;
13892 		case 't':
13893 			/* Reset activities array */
13894 			memset(&wd.wd_enabled, 0, sizeof (wd.wd_enabled));
13895 
13896 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
13897 				static const char *const col_opts[] = {
13898 				    "discard", "free", "initialize", "replace",
13899 				    "remove", "resilver", "scrub", "trim",
13900 				    "raidz_expand", "condense" };
13901 
13902 				for (i = 0; i < ARRAY_SIZE(col_opts); ++i)
13903 					if (strcmp(tok, col_opts[i]) == 0) {
13904 						wd.wd_enabled[i] = B_TRUE;
13905 						goto found;
13906 					}
13907 
13908 				(void) fprintf(stderr,
13909 				    gettext("invalid activity '%s'\n"), tok);
13910 				usage(B_FALSE);
13911 found:;
13912 			}
13913 			break;
13914 		case '?':
13915 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
13916 			    optopt);
13917 			usage(B_FALSE);
13918 		}
13919 	}
13920 
13921 	argc -= optind;
13922 	argv += optind;
13923 
13924 	get_interval_count(&argc, argv, &wd.wd_interval, &count);
13925 	if (count != 0) {
13926 		/* This subcmd only accepts an interval, not a count */
13927 		(void) fprintf(stderr, gettext("too many arguments\n"));
13928 		usage(B_FALSE);
13929 	}
13930 
13931 	if (wd.wd_interval != 0)
13932 		verbose = B_TRUE;
13933 
13934 	if (argc < 1) {
13935 		(void) fprintf(stderr, gettext("missing 'pool' argument\n"));
13936 		usage(B_FALSE);
13937 	}
13938 	if (argc > 1) {
13939 		(void) fprintf(stderr, gettext("too many arguments\n"));
13940 		usage(B_FALSE);
13941 	}
13942 
13943 	wd.wd_poolname = argv[0];
13944 
13945 	if ((zhp = zpool_open(g_zfs, wd.wd_poolname)) == NULL)
13946 		return (1);
13947 
13948 	if (verbose) {
13949 		/*
13950 		 * We use a separate thread for printing status updates because
13951 		 * the main thread will call lzc_wait(), which blocks as long
13952 		 * as an activity is in progress, which can be a long time.
13953 		 */
13954 		if (pthread_create(&status_thr, NULL, wait_status_thread, &wd)
13955 		    != 0) {
13956 			(void) fprintf(stderr, gettext("failed to create status"
13957 			    "thread: %s\n"), strerror(errno));
13958 			zpool_close(zhp);
13959 			return (1);
13960 		}
13961 	}
13962 
13963 	/*
13964 	 * Loop over all activities that we are supposed to wait for until none
13965 	 * of them are in progress. Note that this means we can end up waiting
13966 	 * for more activities to complete than just those that were in progress
13967 	 * when we began waiting; if an activity we are interested in begins
13968 	 * while we are waiting for another activity, we will wait for both to
13969 	 * complete before exiting.
13970 	 */
13971 	for (;;) {
13972 		boolean_t missing = B_FALSE;
13973 		boolean_t any_waited = B_FALSE;
13974 
13975 		for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13976 			boolean_t waited;
13977 
13978 			if (!wd.wd_enabled[i])
13979 				continue;
13980 
13981 			error = zpool_wait_status(zhp, i, &missing, &waited);
13982 			if (error != 0 || missing)
13983 				break;
13984 
13985 			any_waited = (any_waited || waited);
13986 		}
13987 
13988 		if (error != 0 || missing || !any_waited)
13989 			break;
13990 	}
13991 
13992 	zpool_close(zhp);
13993 
13994 	if (verbose) {
13995 		uintptr_t status;
13996 		(void) pthread_mutex_lock(&wd.wd_mutex);
13997 		wd.wd_should_exit = B_TRUE;
13998 		(void) pthread_cond_signal(&wd.wd_cv);
13999 		(void) pthread_mutex_unlock(&wd.wd_mutex);
14000 		(void) pthread_join(status_thr, (void *)&status);
14001 		if (status != 0)
14002 			error = status;
14003 	}
14004 
14005 	(void) pthread_mutex_destroy(&wd.wd_mutex);
14006 	(void) pthread_cond_destroy(&wd.wd_cv);
14007 	return (error);
14008 }
14009 
14010 /*
14011  * zpool ddtprune -d|-p <amount> <pool>
14012  *
14013  *       -d <days>	Prune entries <days> old and older
14014  *       -p <percent>	Prune <percent> amount of entries
14015  *
14016  * Prune single reference entries from DDT to satisfy the amount specified.
14017  */
14018 int
14019 zpool_do_ddt_prune(int argc, char **argv)
14020 {
14021 	zpool_ddt_prune_unit_t unit = ZPOOL_DDT_PRUNE_NONE;
14022 	uint64_t amount = 0;
14023 	zpool_handle_t *zhp;
14024 	char *endptr;
14025 	int c;
14026 
14027 	while ((c = getopt(argc, argv, "d:p:")) != -1) {
14028 		switch (c) {
14029 		case 'd':
14030 			if (unit == ZPOOL_DDT_PRUNE_PERCENTAGE) {
14031 				(void) fprintf(stderr, gettext("-d cannot be "
14032 				    "combined with -p option\n"));
14033 				usage(B_FALSE);
14034 			}
14035 			errno = 0;
14036 			amount = strtoull(optarg, &endptr, 0);
14037 			if (errno != 0 || *endptr != '\0' || amount == 0) {
14038 				(void) fprintf(stderr,
14039 				    gettext("invalid days value\n"));
14040 				usage(B_FALSE);
14041 			}
14042 			amount *= 86400;	/* convert days to seconds */
14043 			unit = ZPOOL_DDT_PRUNE_AGE;
14044 			break;
14045 		case 'p':
14046 			if (unit == ZPOOL_DDT_PRUNE_AGE) {
14047 				(void) fprintf(stderr, gettext("-p cannot be "
14048 				    "combined with -d option\n"));
14049 				usage(B_FALSE);
14050 			}
14051 			errno = 0;
14052 			amount = strtoull(optarg, &endptr, 0);
14053 			if (errno != 0 || *endptr != '\0' ||
14054 			    amount == 0 || amount > 100) {
14055 				(void) fprintf(stderr,
14056 				    gettext("invalid percentage value\n"));
14057 				usage(B_FALSE);
14058 			}
14059 			unit = ZPOOL_DDT_PRUNE_PERCENTAGE;
14060 			break;
14061 		case '?':
14062 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
14063 			    optopt);
14064 			usage(B_FALSE);
14065 		}
14066 	}
14067 	argc -= optind;
14068 	argv += optind;
14069 
14070 	if (unit == ZPOOL_DDT_PRUNE_NONE) {
14071 		(void) fprintf(stderr,
14072 		    gettext("missing amount option (-d|-p <value>)\n"));
14073 		usage(B_FALSE);
14074 	} else if (argc < 1) {
14075 		(void) fprintf(stderr, gettext("missing pool argument\n"));
14076 		usage(B_FALSE);
14077 	} else if (argc > 1) {
14078 		(void) fprintf(stderr, gettext("too many arguments\n"));
14079 		usage(B_FALSE);
14080 	}
14081 	zhp = zpool_open(g_zfs, argv[0]);
14082 	if (zhp == NULL)
14083 		return (-1);
14084 
14085 	int error = zpool_ddt_prune(zhp, unit, amount);
14086 
14087 	zpool_close(zhp);
14088 
14089 	return (error);
14090 }
14091 
14092 static int
14093 find_command_idx(const char *command, int *idx)
14094 {
14095 	for (int i = 0; i < NCOMMAND; ++i) {
14096 		if (command_table[i].name == NULL)
14097 			continue;
14098 
14099 		if (strcmp(command, command_table[i].name) == 0) {
14100 			*idx = i;
14101 			return (0);
14102 		}
14103 	}
14104 	return (1);
14105 }
14106 
14107 /*
14108  * Display version message
14109  */
14110 static int
14111 zpool_do_version(int argc, char **argv)
14112 {
14113 	int c;
14114 	nvlist_t *jsobj = NULL, *zfs_ver = NULL;
14115 	boolean_t json = B_FALSE;
14116 
14117 	struct option long_options[] = {
14118 		{"json", no_argument, NULL, 'j'},
14119 	};
14120 
14121 	while ((c = getopt_long(argc, argv, "j", long_options, NULL)) != -1) {
14122 		switch (c) {
14123 		case 'j':
14124 			json = B_TRUE;
14125 			jsobj = zpool_json_schema(0, 1);
14126 			break;
14127 		case '?':
14128 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
14129 			    optopt);
14130 			usage(B_FALSE);
14131 		}
14132 	}
14133 
14134 	argc -= optind;
14135 	if (argc != 0) {
14136 		(void) fprintf(stderr, "too many arguments\n");
14137 		usage(B_FALSE);
14138 	}
14139 
14140 	if (json) {
14141 		zfs_ver = zfs_version_nvlist();
14142 		if (zfs_ver) {
14143 			fnvlist_add_nvlist(jsobj, "zfs_version", zfs_ver);
14144 			zcmd_print_json(jsobj);
14145 			fnvlist_free(zfs_ver);
14146 			return (0);
14147 		} else
14148 			return (-1);
14149 	} else
14150 		return (zfs_version_print() != 0);
14151 }
14152 
14153 /* Display documentation */
14154 static int
14155 zpool_do_help(int argc, char **argv)
14156 {
14157 	char page[MAXNAMELEN];
14158 	if (argc < 3 || strcmp(argv[2], "zpool") == 0)
14159 		(void) strcpy(page, "zpool");
14160 	else if (strcmp(argv[2], "concepts") == 0 ||
14161 	    strcmp(argv[2], "props") == 0)
14162 		(void) snprintf(page, sizeof (page), "zpool%s", argv[2]);
14163 	else
14164 		(void) snprintf(page, sizeof (page), "zpool-%s", argv[2]);
14165 
14166 	(void) execlp("man", "man", page, NULL);
14167 
14168 	fprintf(stderr, "couldn't run man program: %s\n", strerror(errno));
14169 	return (-1);
14170 }
14171 
14172 /*
14173  * Do zpool_load_compat() and print error message on failure
14174  */
14175 static zpool_compat_status_t
14176 zpool_do_load_compat(const char *compat, boolean_t *list)
14177 {
14178 	char report[1024];
14179 
14180 	zpool_compat_status_t ret;
14181 
14182 	ret = zpool_load_compat(compat, list, report, 1024);
14183 	switch (ret) {
14184 
14185 	case ZPOOL_COMPATIBILITY_OK:
14186 		break;
14187 
14188 	case ZPOOL_COMPATIBILITY_NOFILES:
14189 	case ZPOOL_COMPATIBILITY_BADFILE:
14190 	case ZPOOL_COMPATIBILITY_BADTOKEN:
14191 		(void) fprintf(stderr, "Error: %s\n", report);
14192 		break;
14193 
14194 	case ZPOOL_COMPATIBILITY_WARNTOKEN:
14195 		(void) fprintf(stderr, "Warning: %s\n", report);
14196 		ret = ZPOOL_COMPATIBILITY_OK;
14197 		break;
14198 	}
14199 	return (ret);
14200 }
14201 
14202 int
14203 main(int argc, char **argv)
14204 {
14205 	int ret = 0;
14206 	int i = 0;
14207 	char *cmdname;
14208 	char **newargv;
14209 
14210 	(void) setlocale(LC_ALL, "");
14211 	(void) setlocale(LC_NUMERIC, "C");
14212 	(void) textdomain(TEXT_DOMAIN);
14213 	srand(time(NULL));
14214 
14215 	opterr = 0;
14216 
14217 	/*
14218 	 * Make sure the user has specified some command.
14219 	 */
14220 	if (argc < 2) {
14221 		(void) fprintf(stderr, gettext("missing command\n"));
14222 		usage(B_FALSE);
14223 	}
14224 
14225 	cmdname = argv[1];
14226 
14227 	/*
14228 	 * Special case '-?'
14229 	 */
14230 	if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
14231 		usage(B_TRUE);
14232 
14233 	/*
14234 	 * Special case '-V|--version'
14235 	 */
14236 	if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
14237 		return (zfs_version_print() != 0);
14238 
14239 	/*
14240 	 * Special case 'help'
14241 	 */
14242 	if (strcmp(cmdname, "help") == 0)
14243 		return (zpool_do_help(argc, argv));
14244 
14245 	/*
14246 	 * Special case '<subcommand> --help|-?'
14247 	 */
14248 	if (argc >= 3 && (strcmp(argv[2], "--help") == 0 ||
14249 	    strcmp(argv[2], "-?") == 0)) {
14250 		int idx;
14251 		if (find_command_idx(cmdname, &idx) == 0) {
14252 			current_command = &command_table[idx];
14253 			usage(B_FALSE);
14254 		}
14255 	}
14256 
14257 	if ((g_zfs = libzfs_init()) == NULL) {
14258 		(void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
14259 		return (1);
14260 	}
14261 
14262 	libzfs_print_on_error(g_zfs, B_TRUE);
14263 
14264 	zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
14265 
14266 	/*
14267 	 * Many commands modify input strings for string parsing reasons.
14268 	 * We create a copy to protect the original argv.
14269 	 */
14270 	newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
14271 	for (i = 0; i < argc; i++)
14272 		newargv[i] = strdup(argv[i]);
14273 	newargv[argc] = NULL;
14274 
14275 	/*
14276 	 * Run the appropriate command.
14277 	 */
14278 	if (find_command_idx(cmdname, &i) == 0) {
14279 		current_command = &command_table[i];
14280 		ret = command_table[i].func(argc - 1, newargv + 1);
14281 	} else if (strchr(cmdname, '=')) {
14282 		verify(find_command_idx("set", &i) == 0);
14283 		current_command = &command_table[i];
14284 		ret = command_table[i].func(argc, newargv);
14285 	} else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
14286 		/*
14287 		 * 'freeze' is a vile debugging abomination, so we treat
14288 		 * it as such.
14289 		 */
14290 		zfs_cmd_t zc = {"\0"};
14291 
14292 		(void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
14293 		ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
14294 		if (ret != 0) {
14295 			(void) fprintf(stderr,
14296 			gettext("failed to freeze pool: %d\n"), errno);
14297 			ret = 1;
14298 		}
14299 
14300 		log_history = 0;
14301 	} else {
14302 		(void) fprintf(stderr, gettext("unrecognized "
14303 		    "command '%s'\n"), cmdname);
14304 		usage(B_FALSE);
14305 	}
14306 
14307 	for (i = 0; i < argc; i++)
14308 		free(newargv[i]);
14309 	free(newargv);
14310 
14311 	if (ret == 0 && log_history)
14312 		(void) zpool_log_history(g_zfs, history_str);
14313 
14314 	libzfs_fini(g_zfs);
14315 
14316 	/*
14317 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
14318 	 * for the purposes of running ::findleaks.
14319 	 */
14320 	if (getenv("ZFS_ABORT") != NULL) {
14321 		(void) printf("dumping core by request\n");
14322 		abort();
14323 	}
14324 
14325 	return (ret);
14326 }
14327