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