xref: /src/sys/contrib/openzfs/cmd/zpool/zpool_main.c (revision 80aae8a3f8aa70712930664572be9e6885dc0be7)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
26  * Copyright (c) 2011, 2024 by Delphix. All rights reserved.
27  * Copyright (c) 2012 by Frederik Wessels. All rights reserved.
28  * Copyright (c) 2012 by Cyril Plisko. All rights reserved.
29  * Copyright (c) 2013 by Prasad Joshi (sTec). All rights reserved.
30  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
31  * Copyright (c) 2017 Datto Inc.
32  * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
33  * Copyright (c) 2017, Intel Corporation.
34  * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>
35  * Copyright (c) 2021, Colm Buckley <colm@tuatha.org>
36  * Copyright (c) 2021, 2023, 2025, Klara, Inc.
37  * Copyright (c) 2021, 2025 Hewlett Packard Enterprise Development LP.
38  */
39 
40 #include <assert.h>
41 #include <ctype.h>
42 #include <dirent.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <getopt.h>
46 #include <inttypes.h>
47 #include <libgen.h>
48 #include <libintl.h>
49 #include <locale.h>
50 #include <pthread.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <termios.h>
55 #include <time.h>
56 #include <unistd.h>
57 #include <pwd.h>
58 #include <zone.h>
59 #include <sys/wait.h>
60 #include <zfs_prop.h>
61 #include <sys/fs/zfs.h>
62 #include <sys/stat.h>
63 #include <sys/systeminfo.h>
64 #include <sys/fm/fs/zfs.h>
65 #include <sys/fm/util.h>
66 #include <sys/fm/protocol.h>
67 #include <sys/zfs_ioctl.h>
68 #include <sys/mount.h>
69 #include <sys/sysmacros.h>
70 #include <string.h>
71 #include <math.h>
72 
73 #include <libzfs.h>
74 #include <libzutil.h>
75 
76 #include "zpool_util.h"
77 #include "zfs_comutil.h"
78 #include "zfeature_common.h"
79 #include "zfs_valstr.h"
80 
81 #include "statcommon.h"
82 
83 libzfs_handle_t *g_zfs;
84 
85 static int mount_tp_nthr = 512;  /* tpool threads for multi-threaded mounting */
86 
87 static int zpool_do_create(int, char **);
88 static int zpool_do_destroy(int, char **);
89 
90 static int zpool_do_add(int, char **);
91 static int zpool_do_remove(int, char **);
92 static int zpool_do_labelclear(int, char **);
93 
94 static int zpool_do_checkpoint(int, char **);
95 static int zpool_do_prefetch(int, char **);
96 
97 static int zpool_do_list(int, char **);
98 static int zpool_do_iostat(int, char **);
99 static int zpool_do_status(int, char **);
100 
101 static int zpool_do_online(int, char **);
102 static int zpool_do_offline(int, char **);
103 static int zpool_do_clear(int, char **);
104 static int zpool_do_reopen(int, char **);
105 
106 static int zpool_do_reguid(int, char **);
107 
108 static int zpool_do_attach(int, char **);
109 static int zpool_do_detach(int, char **);
110 static int zpool_do_replace(int, char **);
111 static int zpool_do_split(int, char **);
112 
113 static int zpool_do_initialize(int, char **);
114 static int zpool_do_scrub(int, char **);
115 static int zpool_do_resilver(int, char **);
116 static int zpool_do_trim(int, char **);
117 
118 static int zpool_do_import(int, char **);
119 static int zpool_do_export(int, char **);
120 
121 static int zpool_do_upgrade(int, char **);
122 
123 static int zpool_do_history(int, char **);
124 static int zpool_do_events(int, char **);
125 
126 static int zpool_do_get(int, char **);
127 static int zpool_do_set(int, char **);
128 
129 static int zpool_do_sync(int, char **);
130 
131 static int zpool_do_version(int, char **);
132 
133 static int zpool_do_wait(int, char **);
134 
135 static int zpool_do_ddt_prune(int, char **);
136 
137 static int zpool_do_help(int argc, char **argv);
138 
139 static zpool_compat_status_t zpool_do_load_compat(
140     const char *, boolean_t *);
141 
142 enum zpool_options {
143 	ZPOOL_OPTION_POWER = 1024,
144 	ZPOOL_OPTION_ALLOW_INUSE,
145 	ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH,
146 	ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH,
147 	ZPOOL_OPTION_POOL_KEY_GUID,
148 	ZPOOL_OPTION_JSON_NUMS_AS_INT,
149 	ZPOOL_OPTION_JSON_FLAT_VDEVS
150 };
151 
152 /*
153  * These libumem hooks provide a reasonable set of defaults for the allocator's
154  * debugging facilities.
155  */
156 
157 #ifdef DEBUG
158 const char *
_umem_debug_init(void)159 _umem_debug_init(void)
160 {
161 	return ("default,verbose"); /* $UMEM_DEBUG setting */
162 }
163 
164 const char *
_umem_logging_init(void)165 _umem_logging_init(void)
166 {
167 	return ("fail,contents"); /* $UMEM_LOGGING setting */
168 }
169 #endif
170 
171 typedef enum {
172 	HELP_ADD,
173 	HELP_ATTACH,
174 	HELP_CLEAR,
175 	HELP_CREATE,
176 	HELP_CHECKPOINT,
177 	HELP_DDT_PRUNE,
178 	HELP_DESTROY,
179 	HELP_DETACH,
180 	HELP_EXPORT,
181 	HELP_HISTORY,
182 	HELP_IMPORT,
183 	HELP_IOSTAT,
184 	HELP_LABELCLEAR,
185 	HELP_LIST,
186 	HELP_OFFLINE,
187 	HELP_ONLINE,
188 	HELP_PREFETCH,
189 	HELP_REPLACE,
190 	HELP_REMOVE,
191 	HELP_INITIALIZE,
192 	HELP_SCRUB,
193 	HELP_RESILVER,
194 	HELP_TRIM,
195 	HELP_STATUS,
196 	HELP_UPGRADE,
197 	HELP_EVENTS,
198 	HELP_GET,
199 	HELP_SET,
200 	HELP_SPLIT,
201 	HELP_SYNC,
202 	HELP_REGUID,
203 	HELP_REOPEN,
204 	HELP_VERSION,
205 	HELP_WAIT
206 } zpool_help_t;
207 
208 
209 /*
210  * Flags for stats to display with "zpool iostats"
211  */
212 enum iostat_type {
213 	IOS_DEFAULT = 0,
214 	IOS_LATENCY = 1,
215 	IOS_QUEUES = 2,
216 	IOS_L_HISTO = 3,
217 	IOS_RQ_HISTO = 4,
218 	IOS_COUNT,	/* always last element */
219 };
220 
221 /* iostat_type entries as bitmasks */
222 #define	IOS_DEFAULT_M	(1ULL << IOS_DEFAULT)
223 #define	IOS_LATENCY_M	(1ULL << IOS_LATENCY)
224 #define	IOS_QUEUES_M	(1ULL << IOS_QUEUES)
225 #define	IOS_L_HISTO_M	(1ULL << IOS_L_HISTO)
226 #define	IOS_RQ_HISTO_M	(1ULL << IOS_RQ_HISTO)
227 
228 /* Mask of all the histo bits */
229 #define	IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
230 
231 /*
232  * Lookup table for iostat flags to nvlist names.  Basically a list
233  * of all the nvlists a flag requires.  Also specifies the order in
234  * which data gets printed in zpool iostat.
235  */
236 static const char *vsx_type_to_nvlist[IOS_COUNT][15] = {
237 	[IOS_L_HISTO] = {
238 	    ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
239 	    ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
240 	    ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
241 	    ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
242 	    ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
243 	    ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
244 	    ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
245 	    ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
246 	    ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
247 	    ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
248 	    ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
249 	    NULL},
250 	[IOS_LATENCY] = {
251 	    ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
252 	    ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
253 	    ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
254 	    ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
255 	    ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
256 	    ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
257 	    NULL},
258 	[IOS_QUEUES] = {
259 	    ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
260 	    ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
261 	    ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
262 	    ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
263 	    ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
264 	    ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
265 	    ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
266 	    NULL},
267 	[IOS_RQ_HISTO] = {
268 	    ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
269 	    ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
270 	    ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
271 	    ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
272 	    ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
273 	    ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
274 	    ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
275 	    ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
276 	    ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
277 	    ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
278 	    ZPOOL_CONFIG_VDEV_IND_TRIM_HISTO,
279 	    ZPOOL_CONFIG_VDEV_AGG_TRIM_HISTO,
280 	    ZPOOL_CONFIG_VDEV_IND_REBUILD_HISTO,
281 	    ZPOOL_CONFIG_VDEV_AGG_REBUILD_HISTO,
282 	    NULL},
283 };
284 
285 static const char *pool_scan_func_str[] = {
286 	"NONE",
287 	"SCRUB",
288 	"RESILVER",
289 	"ERRORSCRUB"
290 };
291 
292 static const char *pool_scan_state_str[] = {
293 	"NONE",
294 	"SCANNING",
295 	"FINISHED",
296 	"CANCELED",
297 	"ERRORSCRUBBING"
298 };
299 
300 static const char *vdev_rebuild_state_str[] = {
301 	"NONE",
302 	"ACTIVE",
303 	"CANCELED",
304 	"COMPLETE"
305 };
306 
307 static const char *checkpoint_state_str[] = {
308 	"NONE",
309 	"EXISTS",
310 	"DISCARDING"
311 };
312 
313 static const char *vdev_state_str[] = {
314 	"UNKNOWN",
315 	"CLOSED",
316 	"OFFLINE",
317 	"REMOVED",
318 	"CANT_OPEN",
319 	"FAULTED",
320 	"DEGRADED",
321 	"ONLINE"
322 };
323 
324 static const char *vdev_aux_str[] = {
325 	"NONE",
326 	"OPEN_FAILED",
327 	"CORRUPT_DATA",
328 	"NO_REPLICAS",
329 	"BAD_GUID_SUM",
330 	"TOO_SMALL",
331 	"BAD_LABEL",
332 	"VERSION_NEWER",
333 	"VERSION_OLDER",
334 	"UNSUP_FEAT",
335 	"SPARED",
336 	"ERR_EXCEEDED",
337 	"IO_FAILURE",
338 	"BAD_LOG",
339 	"EXTERNAL",
340 	"SPLIT_POOL",
341 	"BAD_ASHIFT",
342 	"EXTERNAL_PERSIST",
343 	"ACTIVE",
344 	"CHILDREN_OFFLINE",
345 	"ASHIFT_TOO_BIG"
346 };
347 
348 static const char *vdev_init_state_str[] = {
349 	"NONE",
350 	"ACTIVE",
351 	"CANCELED",
352 	"SUSPENDED",
353 	"COMPLETE"
354 };
355 
356 static const char *vdev_trim_state_str[] = {
357 	"NONE",
358 	"ACTIVE",
359 	"CANCELED",
360 	"SUSPENDED",
361 	"COMPLETE"
362 };
363 
364 #define	ZFS_NICE_TIMESTAMP	100
365 
366 /*
367  * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
368  * Right now, only one histo bit is ever set at one time, so we can
369  * just do a highbit64(a)
370  */
371 #define	IOS_HISTO_IDX(a)	(highbit64(a & IOS_ANYHISTO_M) - 1)
372 
373 typedef struct zpool_command {
374 	const char	*name;
375 	int		(*func)(int, char **);
376 	zpool_help_t	usage;
377 } zpool_command_t;
378 
379 /*
380  * Master command table.  Each ZFS command has a name, associated function, and
381  * usage message.  The usage messages need to be internationalized, so we have
382  * to have a function to return the usage message based on a command index.
383  *
384  * These commands are organized according to how they are displayed in the usage
385  * message.  An empty command (one with a NULL name) indicates an empty line in
386  * the generic usage message.
387  */
388 static zpool_command_t command_table[] = {
389 	{ "version",	zpool_do_version,	HELP_VERSION		},
390 	{ NULL },
391 	{ "create",	zpool_do_create,	HELP_CREATE		},
392 	{ "destroy",	zpool_do_destroy,	HELP_DESTROY		},
393 	{ NULL },
394 	{ "add",	zpool_do_add,		HELP_ADD		},
395 	{ "remove",	zpool_do_remove,	HELP_REMOVE		},
396 	{ NULL },
397 	{ "labelclear",	zpool_do_labelclear,	HELP_LABELCLEAR		},
398 	{ NULL },
399 	{ "checkpoint",	zpool_do_checkpoint,	HELP_CHECKPOINT		},
400 	{ "prefetch",	zpool_do_prefetch,	HELP_PREFETCH		},
401 	{ NULL },
402 	{ "list",	zpool_do_list,		HELP_LIST		},
403 	{ "iostat",	zpool_do_iostat,	HELP_IOSTAT		},
404 	{ "status",	zpool_do_status,	HELP_STATUS		},
405 	{ NULL },
406 	{ "online",	zpool_do_online,	HELP_ONLINE		},
407 	{ "offline",	zpool_do_offline,	HELP_OFFLINE		},
408 	{ "clear",	zpool_do_clear,		HELP_CLEAR		},
409 	{ "reopen",	zpool_do_reopen,	HELP_REOPEN		},
410 	{ NULL },
411 	{ "attach",	zpool_do_attach,	HELP_ATTACH		},
412 	{ "detach",	zpool_do_detach,	HELP_DETACH		},
413 	{ "replace",	zpool_do_replace,	HELP_REPLACE		},
414 	{ "split",	zpool_do_split,		HELP_SPLIT		},
415 	{ NULL },
416 	{ "initialize",	zpool_do_initialize,	HELP_INITIALIZE		},
417 	{ "resilver",	zpool_do_resilver,	HELP_RESILVER		},
418 	{ "scrub",	zpool_do_scrub,		HELP_SCRUB		},
419 	{ "trim",	zpool_do_trim,		HELP_TRIM		},
420 	{ NULL },
421 	{ "import",	zpool_do_import,	HELP_IMPORT		},
422 	{ "export",	zpool_do_export,	HELP_EXPORT		},
423 	{ "upgrade",	zpool_do_upgrade,	HELP_UPGRADE		},
424 	{ "reguid",	zpool_do_reguid,	HELP_REGUID		},
425 	{ NULL },
426 	{ "history",	zpool_do_history,	HELP_HISTORY		},
427 	{ "events",	zpool_do_events,	HELP_EVENTS		},
428 	{ NULL },
429 	{ "get",	zpool_do_get,		HELP_GET		},
430 	{ "set",	zpool_do_set,		HELP_SET		},
431 	{ "sync",	zpool_do_sync,		HELP_SYNC		},
432 	{ NULL },
433 	{ "wait",	zpool_do_wait,		HELP_WAIT		},
434 	{ NULL },
435 	{ "ddtprune",	zpool_do_ddt_prune,	HELP_DDT_PRUNE		},
436 };
437 
438 #define	NCOMMAND	(ARRAY_SIZE(command_table))
439 
440 #define	VDEV_ALLOC_CLASS_LOGS	"logs"
441 
442 #define	MAX_CMD_LEN	256
443 
444 static zpool_command_t *current_command;
445 static zfs_type_t current_prop_type = (ZFS_TYPE_POOL | ZFS_TYPE_VDEV);
446 static char history_str[HIS_MAX_RECORD_LEN];
447 static boolean_t log_history = B_TRUE;
448 static uint_t timestamp_fmt = NODATE;
449 
450 static const char *
get_usage(zpool_help_t idx)451 get_usage(zpool_help_t idx)
452 {
453 	switch (idx) {
454 	case HELP_ADD:
455 		return (gettext("\tadd [-afgLnP] [-o property=value] "
456 		    "<pool> <vdev> ...\n"));
457 	case HELP_ATTACH:
458 		return (gettext("\tattach [-fsw] [-o property=value] "
459 		    "<pool> <vdev> <new-device>\n"));
460 	case HELP_CLEAR:
461 		return (gettext("\tclear [--power] <pool> [device]\n"));
462 	case HELP_CREATE:
463 		return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
464 		    "\t    [-O file-system-property=value] ... \n"
465 		    "\t    [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
466 	case HELP_CHECKPOINT:
467 		return (gettext("\tcheckpoint [-d [-w]] <pool> ...\n"));
468 	case HELP_DESTROY:
469 		return (gettext("\tdestroy [-f] <pool>\n"));
470 	case HELP_DETACH:
471 		return (gettext("\tdetach <pool> <device>\n"));
472 	case HELP_EXPORT:
473 		return (gettext("\texport [-af] <pool> ...\n"));
474 	case HELP_HISTORY:
475 		return (gettext("\thistory [-il] [<pool>] ...\n"));
476 	case HELP_IMPORT:
477 		return (gettext("\timport [-d dir] [-D]\n"
478 		    "\timport [-o mntopts] [-o property=value] ... \n"
479 		    "\t    [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
480 		    "[-R root] [-F [-n]] -a\n"
481 		    "\timport [-o mntopts] [-o property=value] ... \n"
482 		    "\t    [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
483 		    "[-R root] [-F [-n]]\n"
484 		    "\t    [--rewind-to-checkpoint] <pool | id> [newpool]\n"));
485 	case HELP_IOSTAT:
486 		return (gettext("\tiostat [[[-c [script1,script2,...]"
487 		    "[-lq]]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
488 		    "\t    [[pool ...]|[pool vdev ...]|[vdev ...]]"
489 		    " [[-n] interval [count]]\n"));
490 	case HELP_LABELCLEAR:
491 		return (gettext("\tlabelclear [-f] <vdev>\n"));
492 	case HELP_LIST:
493 		return (gettext("\tlist [-gHLpPv] [-o property[,...]] [-j "
494 		    "[--json-int, --json-pool-key-guid]] ...\n"
495 		    "\t    [-T d|u] [pool] [interval [count]]\n"));
496 	case HELP_PREFETCH:
497 		return (gettext("\tprefetch [-t <type>] <pool>\n"));
498 	case HELP_OFFLINE:
499 		return (gettext("\toffline [--power]|[[-f][-t]] <pool> "
500 		    "<device> ...\n"));
501 	case HELP_ONLINE:
502 		return (gettext("\tonline [--power][-e] <pool> <device> "
503 		    "...\n"));
504 	case HELP_REPLACE:
505 		return (gettext("\treplace [-fsw] [-o property=value] "
506 		    "<pool> <device> [new-device]\n"));
507 	case HELP_REMOVE:
508 		return (gettext("\tremove [-npsw] <pool> <device> ...\n"));
509 	case HELP_REOPEN:
510 		return (gettext("\treopen [-n] <pool>\n"));
511 	case HELP_INITIALIZE:
512 		return (gettext("\tinitialize [-c | -s | -u] [-w] <-a | <pool> "
513 		    "[<device> ...]>\n"));
514 	case HELP_SCRUB:
515 		return (gettext("\tscrub [-e | -s | -p | -C | -E | -S] [-w] "
516 		    "<-a | <pool> [<pool> ...]>\n"));
517 	case HELP_RESILVER:
518 		return (gettext("\tresilver <pool> ...\n"));
519 	case HELP_TRIM:
520 		return (gettext("\ttrim [-dw] [-r <rate>] [-c | -s] "
521 		    "<-a | <pool> [<device> ...]>\n"));
522 	case HELP_STATUS:
523 		return (gettext("\tstatus [-DdegiLPpstvx] "
524 		    "[-c script1[,script2,...]] ...\n"
525 		    "\t    [-j|--json [--json-flat-vdevs] [--json-int] "
526 		    "[--json-pool-key-guid]] ...\n"
527 		    "\t    [-T d|u] [--power] [pool] [interval [count]]\n"));
528 	case HELP_UPGRADE:
529 		return (gettext("\tupgrade\n"
530 		    "\tupgrade -v\n"
531 		    "\tupgrade [-V version] <-a | pool ...>\n"));
532 	case HELP_EVENTS:
533 		return (gettext("\tevents [-vHf [pool] | -c]\n"));
534 	case HELP_GET:
535 		return (gettext("\tget [-Hp] [-j [--json-int, "
536 		    "--json-pool-key-guid]] ...\n"
537 		    "\t    [-o \"all\" | field[,...]] "
538 		    "<\"all\" | property[,...]> <pool> ...\n"));
539 	case HELP_SET:
540 		return (gettext("\tset <property=value> <pool>\n"
541 		    "\tset <vdev_property=value> <pool> <vdev>\n"));
542 	case HELP_SPLIT:
543 		return (gettext("\tsplit [-gLnPl] [-R altroot] [-o mntopts]\n"
544 		    "\t    [-o property=value] <pool> <newpool> "
545 		    "[<device> ...]\n"));
546 	case HELP_REGUID:
547 		return (gettext("\treguid [-g guid] <pool>\n"));
548 	case HELP_SYNC:
549 		return (gettext("\tsync [pool] ...\n"));
550 	case HELP_VERSION:
551 		return (gettext("\tversion [-j]\n"));
552 	case HELP_WAIT:
553 		return (gettext("\twait [-Hp] [-T d|u] [-t <activity>[,...]] "
554 		    "<pool> [interval]\n"));
555 	case HELP_DDT_PRUNE:
556 		return (gettext("\tddtprune -d|-p <amount> <pool>\n"));
557 	default:
558 		__builtin_unreachable();
559 	}
560 }
561 
562 /*
563  * Callback routine that will print out a pool property value.
564  */
565 static int
print_pool_prop_cb(int prop,void * cb)566 print_pool_prop_cb(int prop, void *cb)
567 {
568 	FILE *fp = cb;
569 
570 	(void) fprintf(fp, "\t%-19s  ", zpool_prop_to_name(prop));
571 
572 	if (zpool_prop_readonly(prop))
573 		(void) fprintf(fp, "  NO   ");
574 	else
575 		(void) fprintf(fp, " YES   ");
576 
577 	if (zpool_prop_values(prop) == NULL)
578 		(void) fprintf(fp, "-\n");
579 	else
580 		(void) fprintf(fp, "%s\n", zpool_prop_values(prop));
581 
582 	return (ZPROP_CONT);
583 }
584 
585 /*
586  * Callback routine that will print out a vdev property value.
587  */
588 static int
print_vdev_prop_cb(int prop,void * cb)589 print_vdev_prop_cb(int prop, void *cb)
590 {
591 	FILE *fp = cb;
592 
593 	(void) fprintf(fp, "\t%-19s  ", vdev_prop_to_name(prop));
594 
595 	if (vdev_prop_readonly(prop))
596 		(void) fprintf(fp, "  NO   ");
597 	else
598 		(void) fprintf(fp, " YES   ");
599 
600 	if (vdev_prop_values(prop) == NULL)
601 		(void) fprintf(fp, "-\n");
602 	else
603 		(void) fprintf(fp, "%s\n", vdev_prop_values(prop));
604 
605 	return (ZPROP_CONT);
606 }
607 
608 /*
609  * Given a leaf vdev name like 'L5' return its VDEV_CONFIG_PATH like
610  * '/dev/disk/by-vdev/L5'.
611  */
612 static const char *
vdev_name_to_path(zpool_handle_t * zhp,char * vdev)613 vdev_name_to_path(zpool_handle_t *zhp, char *vdev)
614 {
615 	nvlist_t *vdev_nv = zpool_find_vdev(zhp, vdev, NULL, NULL, NULL);
616 	if (vdev_nv == NULL) {
617 		return (NULL);
618 	}
619 	return (fnvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH));
620 }
621 
622 static int
zpool_power_on(zpool_handle_t * zhp,char * vdev)623 zpool_power_on(zpool_handle_t *zhp, char *vdev)
624 {
625 	return (zpool_power(zhp, vdev, B_TRUE));
626 }
627 
628 static int
zpool_power_on_and_disk_wait(zpool_handle_t * zhp,char * vdev)629 zpool_power_on_and_disk_wait(zpool_handle_t *zhp, char *vdev)
630 {
631 	int rc;
632 
633 	rc = zpool_power_on(zhp, vdev);
634 	if (rc != 0)
635 		return (rc);
636 
637 	(void) zpool_disk_wait(vdev_name_to_path(zhp, vdev));
638 
639 	return (0);
640 }
641 
642 static int
zpool_power_on_pool_and_wait_for_devices(zpool_handle_t * zhp)643 zpool_power_on_pool_and_wait_for_devices(zpool_handle_t *zhp)
644 {
645 	nvlist_t *nv;
646 	const char *path = NULL;
647 	int rc;
648 
649 	/* Power up all the devices first */
650 	FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
651 		path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
652 		if (path != NULL) {
653 			rc = zpool_power_on(zhp, (char *)path);
654 			if (rc != 0) {
655 				return (rc);
656 			}
657 		}
658 	}
659 
660 	/*
661 	 * Wait for their devices to show up.  Since we powered them on
662 	 * at roughly the same time, they should all come online around
663 	 * the same time.
664 	 */
665 	FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
666 		path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
667 		(void) zpool_disk_wait(path);
668 	}
669 
670 	return (0);
671 }
672 
673 static int
zpool_power_off(zpool_handle_t * zhp,char * vdev)674 zpool_power_off(zpool_handle_t *zhp, char *vdev)
675 {
676 	return (zpool_power(zhp, vdev, B_FALSE));
677 }
678 
679 /*
680  * Display usage message.  If we're inside a command, display only the usage for
681  * that command.  Otherwise, iterate over the entire command table and display
682  * a complete usage message.
683  */
684 static __attribute__((noreturn)) void
usage(boolean_t requested)685 usage(boolean_t requested)
686 {
687 	FILE *fp = requested ? stdout : stderr;
688 
689 	if (current_command == NULL) {
690 		int i;
691 
692 		(void) fprintf(fp, gettext("usage: zpool command args ...\n"));
693 		(void) fprintf(fp,
694 		    gettext("where 'command' is one of the following:\n\n"));
695 
696 		for (i = 0; i < NCOMMAND; i++) {
697 			if (command_table[i].name == NULL)
698 				(void) fprintf(fp, "\n");
699 			else
700 				(void) fprintf(fp, "%s",
701 				    get_usage(command_table[i].usage));
702 		}
703 
704 		(void) fprintf(fp,
705 		    gettext("\nFor further help on a command or topic, "
706 		    "run: %s\n"), "zpool help [<topic>]");
707 	} else {
708 		(void) fprintf(fp, gettext("usage:\n"));
709 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
710 	}
711 
712 	if (current_command != NULL &&
713 	    current_prop_type != (ZFS_TYPE_POOL | ZFS_TYPE_VDEV) &&
714 	    ((strcmp(current_command->name, "set") == 0) ||
715 	    (strcmp(current_command->name, "get") == 0) ||
716 	    (strcmp(current_command->name, "list") == 0))) {
717 
718 		(void) fprintf(fp, "%s",
719 		    gettext("\nthe following properties are supported:\n"));
720 
721 		(void) fprintf(fp, "\n\t%-19s  %s   %s\n\n",
722 		    "PROPERTY", "EDIT", "VALUES");
723 
724 		/* Iterate over all properties */
725 		if (current_prop_type == ZFS_TYPE_POOL) {
726 			(void) zprop_iter(print_pool_prop_cb, fp, B_FALSE,
727 			    B_TRUE, current_prop_type);
728 
729 			(void) fprintf(fp, "\t%-19s   ", "feature@...");
730 			(void) fprintf(fp, "YES   "
731 			    "disabled | enabled | active\n");
732 
733 			(void) fprintf(fp, gettext("\nThe feature@ properties "
734 			    "must be appended with a feature name.\n"
735 			    "See zpool-features(7).\n"));
736 		} else if (current_prop_type == ZFS_TYPE_VDEV) {
737 			(void) zprop_iter(print_vdev_prop_cb, fp, B_FALSE,
738 			    B_TRUE, current_prop_type);
739 		}
740 	}
741 
742 	/*
743 	 * See comments at end of main().
744 	 */
745 	if (getenv("ZFS_ABORT") != NULL) {
746 		(void) printf("dumping core by request\n");
747 		abort();
748 	}
749 
750 	exit(requested ? 0 : 2);
751 }
752 
753 /*
754  * zpool initialize [-c | -s | -u] [-w] <-a | pool> [<vdev> ...]
755  * Initialize all unused blocks in the specified vdevs, or all vdevs in the pool
756  * if none specified.
757  *
758  *	-a	Use all pools.
759  *	-c	Cancel. Ends active initializing.
760  *	-s	Suspend. Initializing can then be restarted with no flags.
761  *	-u	Uninitialize. Clears initialization state.
762  *	-w	Wait. Blocks until initializing has completed.
763  */
764 int
zpool_do_initialize(int argc,char ** argv)765 zpool_do_initialize(int argc, char **argv)
766 {
767 	int c;
768 	char *poolname;
769 	zpool_handle_t *zhp;
770 	int err = 0;
771 	boolean_t wait = B_FALSE;
772 	boolean_t initialize_all = B_FALSE;
773 
774 	struct option long_options[] = {
775 		{"cancel",	no_argument,		NULL, 'c'},
776 		{"suspend",	no_argument,		NULL, 's'},
777 		{"uninit",	no_argument,		NULL, 'u'},
778 		{"wait",	no_argument,		NULL, 'w'},
779 		{"all",		no_argument,		NULL, 'a'},
780 		{0, 0, 0, 0}
781 	};
782 
783 	pool_initialize_func_t cmd_type = POOL_INITIALIZE_START;
784 	while ((c = getopt_long(argc, argv, "acsuw", long_options,
785 	    NULL)) != -1) {
786 		switch (c) {
787 		case 'a':
788 			initialize_all = B_TRUE;
789 			break;
790 		case 'c':
791 			if (cmd_type != POOL_INITIALIZE_START &&
792 			    cmd_type != POOL_INITIALIZE_CANCEL) {
793 				(void) fprintf(stderr, gettext("-c cannot be "
794 				    "combined with other options\n"));
795 				usage(B_FALSE);
796 			}
797 			cmd_type = POOL_INITIALIZE_CANCEL;
798 			break;
799 		case 's':
800 			if (cmd_type != POOL_INITIALIZE_START &&
801 			    cmd_type != POOL_INITIALIZE_SUSPEND) {
802 				(void) fprintf(stderr, gettext("-s cannot be "
803 				    "combined with other options\n"));
804 				usage(B_FALSE);
805 			}
806 			cmd_type = POOL_INITIALIZE_SUSPEND;
807 			break;
808 		case 'u':
809 			if (cmd_type != POOL_INITIALIZE_START &&
810 			    cmd_type != POOL_INITIALIZE_UNINIT) {
811 				(void) fprintf(stderr, gettext("-u cannot be "
812 				    "combined with other options\n"));
813 				usage(B_FALSE);
814 			}
815 			cmd_type = POOL_INITIALIZE_UNINIT;
816 			break;
817 		case 'w':
818 			wait = B_TRUE;
819 			break;
820 		case '?':
821 			if (optopt != 0) {
822 				(void) fprintf(stderr,
823 				    gettext("invalid option '%c'\n"), optopt);
824 			} else {
825 				(void) fprintf(stderr,
826 				    gettext("invalid option '%s'\n"),
827 				    argv[optind - 1]);
828 			}
829 			usage(B_FALSE);
830 		}
831 	}
832 
833 	argc -= optind;
834 	argv += optind;
835 
836 	initialize_cbdata_t cbdata = {
837 		.wait = wait,
838 		.cmd_type = cmd_type
839 	};
840 
841 	if (initialize_all && argc > 0) {
842 		(void) fprintf(stderr, gettext("-a cannot be combined with "
843 		    "individual pools or vdevs\n"));
844 		usage(B_FALSE);
845 	}
846 
847 	if (argc < 1 && !initialize_all) {
848 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
849 		usage(B_FALSE);
850 	}
851 
852 	if (wait && (cmd_type != POOL_INITIALIZE_START)) {
853 		(void) fprintf(stderr, gettext("-w cannot be used with -c, -s"
854 		    "or -u\n"));
855 		usage(B_FALSE);
856 	}
857 
858 	if (argc == 0 && initialize_all) {
859 		/* Initilize each pool recursively */
860 		err = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
861 		    B_FALSE, zpool_initialize_one, &cbdata);
862 		return (err);
863 	} else if (argc == 1) {
864 		/* no individual leaf vdevs specified, initialize the pool */
865 		poolname = argv[0];
866 		zhp = zpool_open(g_zfs, poolname);
867 		if (zhp == NULL)
868 			return (-1);
869 		err = zpool_initialize_one(zhp, &cbdata);
870 	} else {
871 		/* individual leaf vdevs specified, initialize them */
872 		poolname = argv[0];
873 		zhp = zpool_open(g_zfs, poolname);
874 		if (zhp == NULL)
875 			return (-1);
876 		nvlist_t *vdevs = fnvlist_alloc();
877 		for (int i = 1; i < argc; i++) {
878 			fnvlist_add_boolean(vdevs, argv[i]);
879 		}
880 		if (wait)
881 			err = zpool_initialize_wait(zhp, cmd_type, vdevs);
882 		else
883 			err = zpool_initialize(zhp, cmd_type, vdevs);
884 		fnvlist_free(vdevs);
885 	}
886 
887 	zpool_close(zhp);
888 
889 	return (err);
890 }
891 
892 /*
893  * print a pool vdev config for dry runs
894  */
895 static void
print_vdev_tree(zpool_handle_t * zhp,const char * name,nvlist_t * nv,int indent,const char * match,int name_flags)896 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
897     const char *match, int name_flags)
898 {
899 	nvlist_t **child;
900 	uint_t c, children;
901 	char *vname;
902 	boolean_t printed = B_FALSE;
903 
904 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
905 	    &child, &children) != 0) {
906 		if (name != NULL)
907 			(void) printf("\t%*s%s\n", indent, "", name);
908 		return;
909 	}
910 
911 	for (c = 0; c < children; c++) {
912 		uint64_t is_log = B_FALSE, is_hole = B_FALSE;
913 		const char *class = "";
914 
915 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
916 		    &is_hole);
917 
918 		if (is_hole == B_TRUE) {
919 			continue;
920 		}
921 
922 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
923 		    &is_log);
924 		if (is_log)
925 			class = VDEV_ALLOC_BIAS_LOG;
926 		(void) nvlist_lookup_string(child[c],
927 		    ZPOOL_CONFIG_ALLOCATION_BIAS, &class);
928 		if (strcmp(match, class) != 0)
929 			continue;
930 
931 		if (!printed && name != NULL) {
932 			(void) printf("\t%*s%s\n", indent, "", name);
933 			printed = B_TRUE;
934 		}
935 		vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
936 		print_vdev_tree(zhp, vname, child[c], indent + 2, "",
937 		    name_flags);
938 		free(vname);
939 	}
940 }
941 
942 /*
943  * Print the list of l2cache devices for dry runs.
944  */
945 static void
print_cache_list(nvlist_t * nv,int indent)946 print_cache_list(nvlist_t *nv, int indent)
947 {
948 	nvlist_t **child;
949 	uint_t c, children;
950 
951 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
952 	    &child, &children) == 0 && children > 0) {
953 		(void) printf("\t%*s%s\n", indent, "", "cache");
954 	} else {
955 		return;
956 	}
957 	for (c = 0; c < children; c++) {
958 		char *vname;
959 
960 		vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
961 		(void) printf("\t%*s%s\n", indent + 2, "", vname);
962 		free(vname);
963 	}
964 }
965 
966 /*
967  * Print the list of spares for dry runs.
968  */
969 static void
print_spare_list(nvlist_t * nv,int indent)970 print_spare_list(nvlist_t *nv, int indent)
971 {
972 	nvlist_t **child;
973 	uint_t c, children;
974 
975 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
976 	    &child, &children) == 0 && children > 0) {
977 		(void) printf("\t%*s%s\n", indent, "", "spares");
978 	} else {
979 		return;
980 	}
981 	for (c = 0; c < children; c++) {
982 		char *vname;
983 
984 		vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
985 		(void) printf("\t%*s%s\n", indent + 2, "", vname);
986 		free(vname);
987 	}
988 }
989 
990 typedef struct spare_cbdata {
991 	uint64_t	cb_guid;
992 	zpool_handle_t	*cb_zhp;
993 } spare_cbdata_t;
994 
995 static boolean_t
find_vdev(nvlist_t * nv,uint64_t search)996 find_vdev(nvlist_t *nv, uint64_t search)
997 {
998 	uint64_t guid;
999 	nvlist_t **child;
1000 	uint_t c, children;
1001 
1002 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1003 	    search == guid)
1004 		return (B_TRUE);
1005 
1006 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1007 	    &child, &children) == 0) {
1008 		for (c = 0; c < children; c++)
1009 			if (find_vdev(child[c], search))
1010 				return (B_TRUE);
1011 	}
1012 
1013 	return (B_FALSE);
1014 }
1015 
1016 static int
find_spare(zpool_handle_t * zhp,void * data)1017 find_spare(zpool_handle_t *zhp, void *data)
1018 {
1019 	spare_cbdata_t *cbp = data;
1020 	nvlist_t *config, *nvroot;
1021 
1022 	config = zpool_get_config(zhp, NULL);
1023 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1024 	    &nvroot) == 0);
1025 
1026 	if (find_vdev(nvroot, cbp->cb_guid)) {
1027 		cbp->cb_zhp = zhp;
1028 		return (1);
1029 	}
1030 
1031 	zpool_close(zhp);
1032 	return (0);
1033 }
1034 
1035 static void
nice_num_str_nvlist(nvlist_t * item,const char * key,uint64_t value,boolean_t literal,boolean_t as_int,int format)1036 nice_num_str_nvlist(nvlist_t *item, const char *key, uint64_t value,
1037     boolean_t literal, boolean_t as_int, int format)
1038 {
1039 	char buf[256];
1040 
1041 	if (literal) {
1042 		if (!as_int)
1043 			(void) snprintf(buf, 256, "%llu", (u_longlong_t)value);
1044 	} else {
1045 		switch (format) {
1046 		case ZFS_NICENUM_1024:
1047 			zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_1024);
1048 			break;
1049 		case ZFS_NICENUM_BYTES:
1050 			zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_BYTES);
1051 			break;
1052 		case ZFS_NICENUM_TIME:
1053 			zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_TIME);
1054 			break;
1055 		case ZFS_NICE_TIMESTAMP:
1056 			format_timestamp(value, buf, 256);
1057 			break;
1058 		default:
1059 			fprintf(stderr, "Invalid number format");
1060 			exit(1);
1061 		}
1062 	}
1063 	if (as_int)
1064 		fnvlist_add_uint64(item, key, value);
1065 	else
1066 		fnvlist_add_string(item, key, buf);
1067 }
1068 
1069 /*
1070  * Generates an nvlist with output version for every command based on params.
1071  * Purpose of this is to add a version of JSON output, considering the schema
1072  * format might be updated for each command in future.
1073  *
1074  * Schema:
1075  *
1076  * "output_version": {
1077  *    "command": string,
1078  *    "vers_major": integer,
1079  *    "vers_minor": integer,
1080  *  }
1081  */
1082 static nvlist_t *
zpool_json_schema(int maj_v,int min_v)1083 zpool_json_schema(int maj_v, int min_v)
1084 {
1085 	char cmd[MAX_CMD_LEN];
1086 	nvlist_t *sch = fnvlist_alloc();
1087 	nvlist_t *ov = fnvlist_alloc();
1088 
1089 	(void) snprintf(cmd, MAX_CMD_LEN, "zpool %s", current_command->name);
1090 	fnvlist_add_string(ov, "command", cmd);
1091 	fnvlist_add_uint32(ov, "vers_major", maj_v);
1092 	fnvlist_add_uint32(ov, "vers_minor", min_v);
1093 	fnvlist_add_nvlist(sch, "output_version", ov);
1094 	fnvlist_free(ov);
1095 	return (sch);
1096 }
1097 
1098 static void
fill_pool_info(nvlist_t * list,zpool_handle_t * zhp,boolean_t addtype,boolean_t as_int)1099 fill_pool_info(nvlist_t *list, zpool_handle_t *zhp, boolean_t addtype,
1100     boolean_t as_int)
1101 {
1102 	nvlist_t *config = zpool_get_config(zhp, NULL);
1103 	uint64_t guid = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID);
1104 	uint64_t txg = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG);
1105 
1106 	fnvlist_add_string(list, "name", zpool_get_name(zhp));
1107 	if (addtype)
1108 		fnvlist_add_string(list, "type", "POOL");
1109 	fnvlist_add_string(list, "state", zpool_get_state_str(zhp));
1110 	if (as_int) {
1111 		if (guid)
1112 			fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_GUID, guid);
1113 		if (txg)
1114 			fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_TXG, txg);
1115 		fnvlist_add_uint64(list, "spa_version", SPA_VERSION);
1116 		fnvlist_add_uint64(list, "zpl_version", ZPL_VERSION);
1117 	} else {
1118 		char value[ZFS_MAXPROPLEN];
1119 		if (guid) {
1120 			(void) snprintf(value, ZFS_MAXPROPLEN, "%llu",
1121 			    (u_longlong_t)guid);
1122 			fnvlist_add_string(list, ZPOOL_CONFIG_POOL_GUID, value);
1123 		}
1124 		if (txg) {
1125 			(void) snprintf(value, ZFS_MAXPROPLEN, "%llu",
1126 			    (u_longlong_t)txg);
1127 			fnvlist_add_string(list, ZPOOL_CONFIG_POOL_TXG, value);
1128 		}
1129 		fnvlist_add_string(list, "spa_version", SPA_VERSION_STRING);
1130 		fnvlist_add_string(list, "zpl_version", ZPL_VERSION_STRING);
1131 	}
1132 }
1133 
1134 static void
used_by_other(zpool_handle_t * zhp,nvlist_t * nvdev,nvlist_t * list)1135 used_by_other(zpool_handle_t *zhp, nvlist_t *nvdev, nvlist_t *list)
1136 {
1137 	spare_cbdata_t spare_cb;
1138 	verify(nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID,
1139 	    &spare_cb.cb_guid) == 0);
1140 	if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1141 		if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1142 		    zpool_get_name(zhp)) != 0) {
1143 			fnvlist_add_string(list, "used_by",
1144 			    zpool_get_name(spare_cb.cb_zhp));
1145 		}
1146 		zpool_close(spare_cb.cb_zhp);
1147 	}
1148 }
1149 
1150 static void
fill_vdev_info(nvlist_t * list,zpool_handle_t * zhp,char * name,boolean_t addtype,boolean_t as_int)1151 fill_vdev_info(nvlist_t *list, zpool_handle_t *zhp, char *name,
1152     boolean_t addtype, boolean_t as_int)
1153 {
1154 	boolean_t l2c = B_FALSE;
1155 	const char *path, *phys, *devid, *bias = NULL;
1156 	uint64_t hole = 0, log = 0, spare = 0;
1157 	vdev_stat_t *vs;
1158 	uint_t c;
1159 	nvlist_t *nvdev;
1160 	nvlist_t *nvdev_parent = NULL;
1161 	char *_name;
1162 
1163 	if (strcmp(name, zpool_get_name(zhp)) != 0)
1164 		_name = name;
1165 	else
1166 		_name = (char *)"root-0";
1167 
1168 	nvdev = zpool_find_vdev(zhp, _name, NULL, &l2c, NULL);
1169 
1170 	fnvlist_add_string(list, "name", name);
1171 	if (addtype)
1172 		fnvlist_add_string(list, "type", "VDEV");
1173 	if (nvdev) {
1174 		const char *type = fnvlist_lookup_string(nvdev,
1175 		    ZPOOL_CONFIG_TYPE);
1176 		if (type)
1177 			fnvlist_add_string(list, "vdev_type", type);
1178 		uint64_t guid = fnvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID);
1179 		if (guid) {
1180 			if (as_int) {
1181 				fnvlist_add_uint64(list, "guid", guid);
1182 			} else {
1183 				char buf[ZFS_MAXPROPLEN];
1184 				(void) snprintf(buf, ZFS_MAXPROPLEN, "%llu",
1185 				    (u_longlong_t)guid);
1186 				fnvlist_add_string(list, "guid", buf);
1187 			}
1188 		}
1189 		if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PATH, &path) == 0)
1190 			fnvlist_add_string(list, "path", path);
1191 		if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PHYS_PATH,
1192 		    &phys) == 0)
1193 			fnvlist_add_string(list, "phys_path", phys);
1194 		if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_DEVID,
1195 		    &devid) == 0)
1196 			fnvlist_add_string(list, "devid", devid);
1197 		(void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_LOG, &log);
1198 		(void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_SPARE,
1199 		    &spare);
1200 		(void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_HOLE, &hole);
1201 		if (hole)
1202 			fnvlist_add_string(list, "class", VDEV_TYPE_HOLE);
1203 		else if (l2c)
1204 			fnvlist_add_string(list, "class", VDEV_TYPE_L2CACHE);
1205 		else if (spare)
1206 			fnvlist_add_string(list, "class", VDEV_TYPE_SPARE);
1207 		else if (log)
1208 			fnvlist_add_string(list, "class", VDEV_TYPE_LOG);
1209 		else {
1210 			(void) nvlist_lookup_string(nvdev,
1211 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
1212 			if (bias != NULL)
1213 				fnvlist_add_string(list, "class", bias);
1214 			else {
1215 				nvdev_parent = NULL;
1216 				nvdev_parent = zpool_find_parent_vdev(zhp,
1217 				    _name, NULL, NULL, NULL);
1218 
1219 				/*
1220 				 * With a mirrored special device, the parent
1221 				 * "mirror" vdev will have
1222 				 * ZPOOL_CONFIG_ALLOCATION_BIAS set to "special"
1223 				 * not the leaf vdevs.  If we're a leaf vdev
1224 				 * in that case we need to look at our parent
1225 				 * to see if they're "special" to know if we
1226 				 * are "special" too.
1227 				 */
1228 				if (nvdev_parent) {
1229 					(void) nvlist_lookup_string(
1230 					    nvdev_parent,
1231 					    ZPOOL_CONFIG_ALLOCATION_BIAS,
1232 					    &bias);
1233 				}
1234 				if (bias != NULL)
1235 					fnvlist_add_string(list, "class", bias);
1236 				else
1237 					fnvlist_add_string(list, "class",
1238 					    "normal");
1239 			}
1240 		}
1241 		if (nvlist_lookup_uint64_array(nvdev, ZPOOL_CONFIG_VDEV_STATS,
1242 		    (uint64_t **)&vs, &c) == 0) {
1243 			fnvlist_add_string(list, "state",
1244 			    vdev_state_str[vs->vs_state]);
1245 		}
1246 	}
1247 }
1248 
1249 static boolean_t
prop_list_contains_feature(nvlist_t * proplist)1250 prop_list_contains_feature(nvlist_t *proplist)
1251 {
1252 	nvpair_t *nvp;
1253 	for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
1254 	    nvp = nvlist_next_nvpair(proplist, nvp)) {
1255 		if (zpool_prop_feature(nvpair_name(nvp)))
1256 			return (B_TRUE);
1257 	}
1258 	return (B_FALSE);
1259 }
1260 
1261 /*
1262  * Add a property pair (name, string-value) into a property nvlist.
1263  */
1264 static int
add_prop_list(const char * propname,const char * propval,nvlist_t ** props,boolean_t poolprop)1265 add_prop_list(const char *propname, const char *propval, nvlist_t **props,
1266     boolean_t poolprop)
1267 {
1268 	zpool_prop_t prop = ZPOOL_PROP_INVAL;
1269 	nvlist_t *proplist;
1270 	const char *normnm;
1271 	const char *strval;
1272 
1273 	if (*props == NULL &&
1274 	    nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
1275 		(void) fprintf(stderr,
1276 		    gettext("internal error: out of memory\n"));
1277 		return (1);
1278 	}
1279 
1280 	proplist = *props;
1281 
1282 	if (poolprop) {
1283 		const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
1284 		const char *cname =
1285 		    zpool_prop_to_name(ZPOOL_PROP_COMPATIBILITY);
1286 
1287 		if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
1288 		    (!zpool_prop_feature(propname) &&
1289 		    !zpool_prop_vdev(propname))) {
1290 			(void) fprintf(stderr, gettext("property '%s' is "
1291 			    "not a valid pool or vdev property\n"), propname);
1292 			return (2);
1293 		}
1294 
1295 		/*
1296 		 * feature@ properties and version should not be specified
1297 		 * at the same time.
1298 		 */
1299 		if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
1300 		    nvlist_exists(proplist, vname)) ||
1301 		    (prop == ZPOOL_PROP_VERSION &&
1302 		    prop_list_contains_feature(proplist))) {
1303 			(void) fprintf(stderr, gettext("'feature@' and "
1304 			    "'version' properties cannot be specified "
1305 			    "together\n"));
1306 			return (2);
1307 		}
1308 
1309 		/*
1310 		 * if version is specified, only "legacy" compatibility
1311 		 * may be requested
1312 		 */
1313 		if ((prop == ZPOOL_PROP_COMPATIBILITY &&
1314 		    strcmp(propval, ZPOOL_COMPAT_LEGACY) != 0 &&
1315 		    nvlist_exists(proplist, vname)) ||
1316 		    (prop == ZPOOL_PROP_VERSION &&
1317 		    nvlist_exists(proplist, cname) &&
1318 		    strcmp(fnvlist_lookup_string(proplist, cname),
1319 		    ZPOOL_COMPAT_LEGACY) != 0)) {
1320 			(void) fprintf(stderr, gettext("when 'version' is "
1321 			    "specified, the 'compatibility' feature may only "
1322 			    "be set to '" ZPOOL_COMPAT_LEGACY "'\n"));
1323 			return (2);
1324 		}
1325 
1326 		if (zpool_prop_feature(propname) || zpool_prop_vdev(propname))
1327 			normnm = propname;
1328 		else
1329 			normnm = zpool_prop_to_name(prop);
1330 	} else {
1331 		zfs_prop_t fsprop = zfs_name_to_prop(propname);
1332 
1333 		if (zfs_prop_valid_for_type(fsprop, ZFS_TYPE_FILESYSTEM,
1334 		    B_FALSE)) {
1335 			normnm = zfs_prop_to_name(fsprop);
1336 		} else if (zfs_prop_user(propname) ||
1337 		    zfs_prop_userquota(propname)) {
1338 			normnm = propname;
1339 		} else {
1340 			(void) fprintf(stderr, gettext("property '%s' is "
1341 			    "not a valid filesystem property\n"), propname);
1342 			return (2);
1343 		}
1344 	}
1345 
1346 	if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
1347 	    prop != ZPOOL_PROP_CACHEFILE) {
1348 		(void) fprintf(stderr, gettext("property '%s' "
1349 		    "specified multiple times\n"), propname);
1350 		return (2);
1351 	}
1352 
1353 	if (nvlist_add_string(proplist, normnm, propval) != 0) {
1354 		(void) fprintf(stderr, gettext("internal "
1355 		    "error: out of memory\n"));
1356 		return (1);
1357 	}
1358 
1359 	return (0);
1360 }
1361 
1362 /*
1363  * Set a default property pair (name, string-value) in a property nvlist
1364  */
1365 static int
add_prop_list_default(const char * propname,const char * propval,nvlist_t ** props)1366 add_prop_list_default(const char *propname, const char *propval,
1367     nvlist_t **props)
1368 {
1369 	const char *pval;
1370 
1371 	if (nvlist_lookup_string(*props, propname, &pval) == 0)
1372 		return (0);
1373 
1374 	return (add_prop_list(propname, propval, props, B_TRUE));
1375 }
1376 
1377 /*
1378  * zpool add [-afgLnP] [-o property=value] <pool> <vdev> ...
1379  *
1380  *	-a	Disable the ashift validation checks
1381  *	-f	Force addition of devices, even if they appear in use
1382  *	-g	Display guid for individual vdev name.
1383  *	-L	Follow links when resolving vdev path name.
1384  *	-n	Do not add the devices, but display the resulting layout if
1385  *		they were to be added.
1386  *	-o	Set property=value.
1387  *	-P	Display full path for vdev name.
1388  *
1389  * Adds the given vdevs to 'pool'.  As with create, the bulk of this work is
1390  * handled by make_root_vdev(), which constructs the nvlist needed to pass to
1391  * libzfs.
1392  */
1393 int
zpool_do_add(int argc,char ** argv)1394 zpool_do_add(int argc, char **argv)
1395 {
1396 	boolean_t check_replication = B_TRUE;
1397 	boolean_t check_inuse = B_TRUE;
1398 	boolean_t dryrun = B_FALSE;
1399 	boolean_t check_ashift = B_TRUE;
1400 	boolean_t force = B_FALSE;
1401 	int name_flags = 0;
1402 	int c;
1403 	nvlist_t *nvroot;
1404 	char *poolname;
1405 	int ret;
1406 	zpool_handle_t *zhp;
1407 	nvlist_t *config;
1408 	nvlist_t *props = NULL;
1409 	char *propval;
1410 
1411 	struct option long_options[] = {
1412 		{"allow-in-use", no_argument, NULL, ZPOOL_OPTION_ALLOW_INUSE},
1413 		{"allow-replication-mismatch", no_argument, NULL,
1414 		    ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH},
1415 		{"allow-ashift-mismatch", no_argument, NULL,
1416 		    ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH},
1417 		{0, 0, 0, 0}
1418 	};
1419 
1420 	/* check options */
1421 	while ((c = getopt_long(argc, argv, "fgLno:P", long_options, NULL))
1422 	    != -1) {
1423 		switch (c) {
1424 		case 'f':
1425 			force = B_TRUE;
1426 			break;
1427 		case 'g':
1428 			name_flags |= VDEV_NAME_GUID;
1429 			break;
1430 		case 'L':
1431 			name_flags |= VDEV_NAME_FOLLOW_LINKS;
1432 			break;
1433 		case 'n':
1434 			dryrun = B_TRUE;
1435 			break;
1436 		case 'o':
1437 			if ((propval = strchr(optarg, '=')) == NULL) {
1438 				(void) fprintf(stderr, gettext("missing "
1439 				    "'=' for -o option\n"));
1440 				usage(B_FALSE);
1441 			}
1442 			*propval = '\0';
1443 			propval++;
1444 
1445 			if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
1446 			    (add_prop_list(optarg, propval, &props, B_TRUE)))
1447 				usage(B_FALSE);
1448 			break;
1449 		case 'P':
1450 			name_flags |= VDEV_NAME_PATH;
1451 			break;
1452 		case ZPOOL_OPTION_ALLOW_INUSE:
1453 			check_inuse = B_FALSE;
1454 			break;
1455 		case ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH:
1456 			check_replication = B_FALSE;
1457 			break;
1458 		case ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH:
1459 			check_ashift = B_FALSE;
1460 			break;
1461 		case '?':
1462 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1463 			    optopt);
1464 			usage(B_FALSE);
1465 		}
1466 	}
1467 
1468 	argc -= optind;
1469 	argv += optind;
1470 
1471 	/* get pool name and check number of arguments */
1472 	if (argc < 1) {
1473 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
1474 		usage(B_FALSE);
1475 	}
1476 	if (argc < 2) {
1477 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
1478 		usage(B_FALSE);
1479 	}
1480 
1481 	if (force) {
1482 		if (!check_inuse || !check_replication || !check_ashift) {
1483 			(void) fprintf(stderr, gettext("'-f' option is not "
1484 			    "allowed with '--allow-replication-mismatch', "
1485 			    "'--allow-ashift-mismatch', or "
1486 			    "'--allow-in-use'\n"));
1487 			usage(B_FALSE);
1488 		}
1489 		check_inuse = B_FALSE;
1490 		check_replication = B_FALSE;
1491 		check_ashift = B_FALSE;
1492 	}
1493 
1494 	poolname = argv[0];
1495 
1496 	argc--;
1497 	argv++;
1498 
1499 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1500 		return (1);
1501 
1502 	if ((config = zpool_get_config(zhp, NULL)) == NULL) {
1503 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
1504 		    poolname);
1505 		zpool_close(zhp);
1506 		return (1);
1507 	}
1508 
1509 	/* unless manually specified use "ashift" pool property (if set) */
1510 	if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
1511 		int intval;
1512 		zprop_source_t src;
1513 		char strval[ZPOOL_MAXPROPLEN];
1514 
1515 		intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
1516 		if (src != ZPROP_SRC_DEFAULT) {
1517 			(void) sprintf(strval, "%" PRId32, intval);
1518 			verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
1519 			    &props, B_TRUE) == 0);
1520 		}
1521 	}
1522 
1523 	/* pass off to make_root_vdev for processing */
1524 	nvroot = make_root_vdev(zhp, props, !check_inuse,
1525 	    check_replication, B_FALSE, dryrun, argc, argv);
1526 	if (nvroot == NULL) {
1527 		zpool_close(zhp);
1528 		return (1);
1529 	}
1530 
1531 	if (dryrun) {
1532 		nvlist_t *poolnvroot;
1533 		nvlist_t **l2child, **sparechild;
1534 		uint_t l2children, sparechildren, c;
1535 		char *vname;
1536 		boolean_t hadcache = B_FALSE, hadspare = B_FALSE;
1537 
1538 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1539 		    &poolnvroot) == 0);
1540 
1541 		(void) printf(gettext("would update '%s' to the following "
1542 		    "configuration:\n\n"), zpool_get_name(zhp));
1543 
1544 		/* print original main pool and new tree */
1545 		print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
1546 		    name_flags | VDEV_NAME_TYPE_ID);
1547 		print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
1548 
1549 		/* print other classes: 'dedup', 'special', and 'log' */
1550 		if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1551 			print_vdev_tree(zhp, "dedup", poolnvroot, 0,
1552 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1553 			print_vdev_tree(zhp, NULL, nvroot, 0,
1554 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1555 		} else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1556 			print_vdev_tree(zhp, "dedup", nvroot, 0,
1557 			    VDEV_ALLOC_BIAS_DEDUP, name_flags);
1558 		}
1559 
1560 		if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1561 			print_vdev_tree(zhp, "special", poolnvroot, 0,
1562 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1563 			print_vdev_tree(zhp, NULL, nvroot, 0,
1564 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1565 		} else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1566 			print_vdev_tree(zhp, "special", nvroot, 0,
1567 			    VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1568 		}
1569 
1570 		if (num_logs(poolnvroot) > 0) {
1571 			print_vdev_tree(zhp, "logs", poolnvroot, 0,
1572 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1573 			print_vdev_tree(zhp, NULL, nvroot, 0,
1574 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1575 		} else if (num_logs(nvroot) > 0) {
1576 			print_vdev_tree(zhp, "logs", nvroot, 0,
1577 			    VDEV_ALLOC_BIAS_LOG, name_flags);
1578 		}
1579 
1580 		/* Do the same for the caches */
1581 		if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
1582 		    &l2child, &l2children) == 0 && l2children) {
1583 			hadcache = B_TRUE;
1584 			(void) printf(gettext("\tcache\n"));
1585 			for (c = 0; c < l2children; c++) {
1586 				vname = zpool_vdev_name(g_zfs, NULL,
1587 				    l2child[c], name_flags);
1588 				(void) printf("\t  %s\n", vname);
1589 				free(vname);
1590 			}
1591 		}
1592 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1593 		    &l2child, &l2children) == 0 && l2children) {
1594 			if (!hadcache)
1595 				(void) printf(gettext("\tcache\n"));
1596 			for (c = 0; c < l2children; c++) {
1597 				vname = zpool_vdev_name(g_zfs, NULL,
1598 				    l2child[c], name_flags);
1599 				(void) printf("\t  %s\n", vname);
1600 				free(vname);
1601 			}
1602 		}
1603 		/* And finally the spares */
1604 		if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_SPARES,
1605 		    &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1606 			hadspare = B_TRUE;
1607 			(void) printf(gettext("\tspares\n"));
1608 			for (c = 0; c < sparechildren; c++) {
1609 				vname = zpool_vdev_name(g_zfs, NULL,
1610 				    sparechild[c], name_flags);
1611 				(void) printf("\t  %s\n", vname);
1612 				free(vname);
1613 			}
1614 		}
1615 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1616 		    &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1617 			if (!hadspare)
1618 				(void) printf(gettext("\tspares\n"));
1619 			for (c = 0; c < sparechildren; c++) {
1620 				vname = zpool_vdev_name(g_zfs, NULL,
1621 				    sparechild[c], name_flags);
1622 				(void) printf("\t  %s\n", vname);
1623 				free(vname);
1624 			}
1625 		}
1626 
1627 		ret = 0;
1628 	} else {
1629 		ret = (zpool_add(zhp, nvroot, check_ashift) != 0);
1630 	}
1631 
1632 	nvlist_free(props);
1633 	nvlist_free(nvroot);
1634 	zpool_close(zhp);
1635 
1636 	return (ret);
1637 }
1638 
1639 /*
1640  * zpool remove [-npsw] <pool> <vdev> ...
1641  *
1642  * Removes the given vdev from the pool.
1643  */
1644 int
zpool_do_remove(int argc,char ** argv)1645 zpool_do_remove(int argc, char **argv)
1646 {
1647 	char *poolname;
1648 	int i, ret = 0;
1649 	zpool_handle_t *zhp = NULL;
1650 	boolean_t stop = B_FALSE;
1651 	int c;
1652 	boolean_t noop = B_FALSE;
1653 	boolean_t parsable = B_FALSE;
1654 	boolean_t wait = B_FALSE;
1655 
1656 	/* check options */
1657 	while ((c = getopt(argc, argv, "npsw")) != -1) {
1658 		switch (c) {
1659 		case 'n':
1660 			noop = B_TRUE;
1661 			break;
1662 		case 'p':
1663 			parsable = B_TRUE;
1664 			break;
1665 		case 's':
1666 			stop = B_TRUE;
1667 			break;
1668 		case 'w':
1669 			wait = B_TRUE;
1670 			break;
1671 		case '?':
1672 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1673 			    optopt);
1674 			usage(B_FALSE);
1675 		}
1676 	}
1677 
1678 	argc -= optind;
1679 	argv += optind;
1680 
1681 	/* get pool name and check number of arguments */
1682 	if (argc < 1) {
1683 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
1684 		usage(B_FALSE);
1685 	}
1686 
1687 	poolname = argv[0];
1688 
1689 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1690 		return (1);
1691 
1692 	if (stop && noop) {
1693 		zpool_close(zhp);
1694 		(void) fprintf(stderr, gettext("stop request ignored\n"));
1695 		return (0);
1696 	}
1697 
1698 	if (stop) {
1699 		if (argc > 1) {
1700 			(void) fprintf(stderr, gettext("too many arguments\n"));
1701 			usage(B_FALSE);
1702 		}
1703 		if (zpool_vdev_remove_cancel(zhp) != 0)
1704 			ret = 1;
1705 		if (wait) {
1706 			(void) fprintf(stderr, gettext("invalid option "
1707 			    "combination: -w cannot be used with -s\n"));
1708 			usage(B_FALSE);
1709 		}
1710 	} else {
1711 		if (argc < 2) {
1712 			(void) fprintf(stderr, gettext("missing device\n"));
1713 			usage(B_FALSE);
1714 		}
1715 
1716 		for (i = 1; i < argc; i++) {
1717 			if (noop) {
1718 				uint64_t size;
1719 
1720 				if (zpool_vdev_indirect_size(zhp, argv[i],
1721 				    &size) != 0) {
1722 					ret = 1;
1723 					break;
1724 				}
1725 				if (parsable) {
1726 					(void) printf("%s %llu\n",
1727 					    argv[i], (unsigned long long)size);
1728 				} else {
1729 					char valstr[32];
1730 					zfs_nicenum(size, valstr,
1731 					    sizeof (valstr));
1732 					(void) printf("Memory that will be "
1733 					    "used after removing %s: %s\n",
1734 					    argv[i], valstr);
1735 				}
1736 			} else {
1737 				if (zpool_vdev_remove(zhp, argv[i]) != 0)
1738 					ret = 1;
1739 			}
1740 		}
1741 
1742 		if (ret == 0 && wait)
1743 			ret = zpool_wait(zhp, ZPOOL_WAIT_REMOVE);
1744 	}
1745 	zpool_close(zhp);
1746 
1747 	return (ret);
1748 }
1749 
1750 /*
1751  * Return 1 if a vdev is active (being used in a pool)
1752  * Return 0 if a vdev is inactive (offlined or faulted, or not in active pool)
1753  *
1754  * This is useful for checking if a disk in an active pool is offlined or
1755  * faulted.
1756  */
1757 static int
vdev_is_active(char * vdev_path)1758 vdev_is_active(char *vdev_path)
1759 {
1760 	int fd;
1761 	fd = open(vdev_path, O_EXCL);
1762 	if (fd < 0) {
1763 		return (1);   /* cant open O_EXCL - disk is active */
1764 	}
1765 
1766 	(void) close(fd);
1767 	return (0);   /* disk is inactive in the pool */
1768 }
1769 
1770 /*
1771  * zpool labelclear [-f] <vdev>
1772  *
1773  *	-f	Force clearing the label for the vdevs which are members of
1774  *		the exported or foreign pools.
1775  *
1776  * Verifies that the vdev is not active and zeros out the label information
1777  * on the device.
1778  */
1779 int
zpool_do_labelclear(int argc,char ** argv)1780 zpool_do_labelclear(int argc, char **argv)
1781 {
1782 	char vdev[MAXPATHLEN];
1783 	char *name = NULL;
1784 	int c, fd, ret = 0;
1785 	nvlist_t *config;
1786 	pool_state_t state;
1787 	boolean_t inuse = B_FALSE;
1788 	boolean_t force = B_FALSE;
1789 
1790 	/* check options */
1791 	while ((c = getopt(argc, argv, "f")) != -1) {
1792 		switch (c) {
1793 		case 'f':
1794 			force = B_TRUE;
1795 			break;
1796 		default:
1797 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1798 			    optopt);
1799 			usage(B_FALSE);
1800 		}
1801 	}
1802 
1803 	argc -= optind;
1804 	argv += optind;
1805 
1806 	/* get vdev name */
1807 	if (argc < 1) {
1808 		(void) fprintf(stderr, gettext("missing vdev name\n"));
1809 		usage(B_FALSE);
1810 	}
1811 	if (argc > 1) {
1812 		(void) fprintf(stderr, gettext("too many arguments\n"));
1813 		usage(B_FALSE);
1814 	}
1815 
1816 	(void) strlcpy(vdev, argv[0], sizeof (vdev));
1817 
1818 	/*
1819 	 * If we cannot open an absolute path, we quit.
1820 	 * Otherwise if the provided vdev name doesn't point to a file,
1821 	 * try prepending expected disk paths and partition numbers.
1822 	 */
1823 	if ((fd = open(vdev, O_RDWR)) < 0) {
1824 		int error;
1825 		if (vdev[0] == '/') {
1826 			(void) fprintf(stderr, gettext("failed to open "
1827 			    "%s: %s\n"), vdev, strerror(errno));
1828 			return (1);
1829 		}
1830 
1831 		error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
1832 		if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
1833 			if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
1834 				error = ENOENT;
1835 		}
1836 
1837 		if (error || ((fd = open(vdev, O_RDWR)) < 0)) {
1838 			if (errno == ENOENT) {
1839 				(void) fprintf(stderr, gettext(
1840 				    "failed to find device %s, try "
1841 				    "specifying absolute path instead\n"),
1842 				    argv[0]);
1843 				return (1);
1844 			}
1845 
1846 			(void) fprintf(stderr, gettext("failed to open %s:"
1847 			    " %s\n"), vdev, strerror(errno));
1848 			return (1);
1849 		}
1850 	}
1851 
1852 	/*
1853 	 * Flush all dirty pages for the block device.  This should not be
1854 	 * fatal when the device does not support BLKFLSBUF as would be the
1855 	 * case for a file vdev.
1856 	 */
1857 	if ((zfs_dev_flush(fd) != 0) && (errno != ENOTTY))
1858 		(void) fprintf(stderr, gettext("failed to invalidate "
1859 		    "cache for %s: %s\n"), vdev, strerror(errno));
1860 
1861 	if (zpool_read_label(fd, &config, NULL) != 0) {
1862 		(void) fprintf(stderr,
1863 		    gettext("failed to read label from %s\n"), vdev);
1864 		ret = 1;
1865 		goto errout;
1866 	}
1867 	nvlist_free(config);
1868 
1869 	ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1870 	if (ret != 0) {
1871 		(void) fprintf(stderr,
1872 		    gettext("failed to check state for %s\n"), vdev);
1873 		ret = 1;
1874 		goto errout;
1875 	}
1876 
1877 	if (!inuse)
1878 		goto wipe_label;
1879 
1880 	switch (state) {
1881 	default:
1882 	case POOL_STATE_ACTIVE:
1883 	case POOL_STATE_SPARE:
1884 	case POOL_STATE_L2CACHE:
1885 		/*
1886 		 * We allow the user to call 'zpool offline -f'
1887 		 * on an offlined disk in an active pool. We can check if
1888 		 * the disk is online by calling vdev_is_active().
1889 		 */
1890 		if (force && !vdev_is_active(vdev))
1891 			break;
1892 
1893 		(void) fprintf(stderr, gettext(
1894 		    "%s is a member (%s) of pool \"%s\""),
1895 		    vdev, zpool_pool_state_to_name(state), name);
1896 
1897 		if (force) {
1898 			(void) fprintf(stderr, gettext(
1899 			    ". Offline the disk first to clear its label."));
1900 		}
1901 		printf("\n");
1902 		ret = 1;
1903 		goto errout;
1904 
1905 	case POOL_STATE_EXPORTED:
1906 		if (force)
1907 			break;
1908 		(void) fprintf(stderr, gettext(
1909 		    "use '-f' to override the following error:\n"
1910 		    "%s is a member of exported pool \"%s\"\n"),
1911 		    vdev, name);
1912 		ret = 1;
1913 		goto errout;
1914 
1915 	case POOL_STATE_POTENTIALLY_ACTIVE:
1916 		if (force)
1917 			break;
1918 		(void) fprintf(stderr, gettext(
1919 		    "use '-f' to override the following error:\n"
1920 		    "%s is a member of potentially active pool \"%s\"\n"),
1921 		    vdev, name);
1922 		ret = 1;
1923 		goto errout;
1924 
1925 	case POOL_STATE_DESTROYED:
1926 		/* inuse should never be set for a destroyed pool */
1927 		assert(0);
1928 		break;
1929 	}
1930 
1931 wipe_label:
1932 	ret = zpool_clear_label(fd);
1933 	if (ret != 0) {
1934 		(void) fprintf(stderr,
1935 		    gettext("failed to clear label for %s\n"), vdev);
1936 	}
1937 
1938 errout:
1939 	free(name);
1940 	(void) close(fd);
1941 
1942 	return (ret);
1943 }
1944 
1945 /*
1946  * zpool create [-fnd] [-o property=value] ...
1947  *		[-O file-system-property=value] ...
1948  *		[-R root] [-m mountpoint] <pool> <dev> ...
1949  *
1950  *	-f	Force creation, even if devices appear in use
1951  *	-n	Do not create the pool, but display the resulting layout if it
1952  *		were to be created.
1953  *      -R	Create a pool under an alternate root
1954  *      -m	Set default mountpoint for the root dataset.  By default it's
1955  *		'/<pool>'
1956  *	-o	Set property=value.
1957  *	-o	Set feature@feature=enabled|disabled.
1958  *	-d	Don't automatically enable all supported pool features
1959  *		(individual features can be enabled with -o).
1960  *	-O	Set fsproperty=value in the pool's root file system
1961  *
1962  * Creates the named pool according to the given vdev specification.  The
1963  * bulk of the vdev processing is done in make_root_vdev() in zpool_vdev.c.
1964  * Once we get the nvlist back from make_root_vdev(), we either print out the
1965  * contents (if '-n' was specified), or pass it to libzfs to do the creation.
1966  */
1967 int
zpool_do_create(int argc,char ** argv)1968 zpool_do_create(int argc, char **argv)
1969 {
1970 	boolean_t force = B_FALSE;
1971 	boolean_t dryrun = B_FALSE;
1972 	boolean_t enable_pool_features = B_TRUE;
1973 
1974 	int c;
1975 	nvlist_t *nvroot = NULL;
1976 	char *poolname;
1977 	char *tname = NULL;
1978 	int ret = 1;
1979 	char *altroot = NULL;
1980 	char *compat = NULL;
1981 	char *mountpoint = NULL;
1982 	nvlist_t *fsprops = NULL;
1983 	nvlist_t *props = NULL;
1984 	char *propval;
1985 
1986 	/* check options */
1987 	while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
1988 		switch (c) {
1989 		case 'f':
1990 			force = B_TRUE;
1991 			break;
1992 		case 'n':
1993 			dryrun = B_TRUE;
1994 			break;
1995 		case 'd':
1996 			enable_pool_features = B_FALSE;
1997 			break;
1998 		case 'R':
1999 			altroot = optarg;
2000 			if (add_prop_list(zpool_prop_to_name(
2001 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
2002 				goto errout;
2003 			if (add_prop_list_default(zpool_prop_to_name(
2004 			    ZPOOL_PROP_CACHEFILE), "none", &props))
2005 				goto errout;
2006 			break;
2007 		case 'm':
2008 			/* Equivalent to -O mountpoint=optarg */
2009 			mountpoint = optarg;
2010 			break;
2011 		case 'o':
2012 			if ((propval = strchr(optarg, '=')) == NULL) {
2013 				(void) fprintf(stderr, gettext("missing "
2014 				    "'=' for -o option\n"));
2015 				goto errout;
2016 			}
2017 			*propval = '\0';
2018 			propval++;
2019 
2020 			if (add_prop_list(optarg, propval, &props, B_TRUE))
2021 				goto errout;
2022 
2023 			/*
2024 			 * If the user is creating a pool that doesn't support
2025 			 * feature flags, don't enable any features.
2026 			 */
2027 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
2028 				char *end;
2029 				u_longlong_t ver;
2030 
2031 				ver = strtoull(propval, &end, 0);
2032 				if (*end == '\0' &&
2033 				    ver < SPA_VERSION_FEATURES) {
2034 					enable_pool_features = B_FALSE;
2035 				}
2036 			}
2037 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
2038 				altroot = propval;
2039 			if (zpool_name_to_prop(optarg) ==
2040 			    ZPOOL_PROP_COMPATIBILITY)
2041 				compat = propval;
2042 			break;
2043 		case 'O':
2044 			if ((propval = strchr(optarg, '=')) == NULL) {
2045 				(void) fprintf(stderr, gettext("missing "
2046 				    "'=' for -O option\n"));
2047 				goto errout;
2048 			}
2049 			*propval = '\0';
2050 			propval++;
2051 
2052 			/*
2053 			 * Mountpoints are checked and then added later.
2054 			 * Uniquely among properties, they can be specified
2055 			 * more than once, to avoid conflict with -m.
2056 			 */
2057 			if (0 == strcmp(optarg,
2058 			    zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
2059 				mountpoint = propval;
2060 			} else if (add_prop_list(optarg, propval, &fsprops,
2061 			    B_FALSE)) {
2062 				goto errout;
2063 			}
2064 			break;
2065 		case 't':
2066 			/*
2067 			 * Sanity check temporary pool name.
2068 			 */
2069 			if (strchr(optarg, '/') != NULL) {
2070 				(void) fprintf(stderr, gettext("cannot create "
2071 				    "'%s': invalid character '/' in temporary "
2072 				    "name\n"), optarg);
2073 				(void) fprintf(stderr, gettext("use 'zfs "
2074 				    "create' to create a dataset\n"));
2075 				goto errout;
2076 			}
2077 
2078 			if (add_prop_list(zpool_prop_to_name(
2079 			    ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
2080 				goto errout;
2081 			if (add_prop_list_default(zpool_prop_to_name(
2082 			    ZPOOL_PROP_CACHEFILE), "none", &props))
2083 				goto errout;
2084 			tname = optarg;
2085 			break;
2086 		case ':':
2087 			(void) fprintf(stderr, gettext("missing argument for "
2088 			    "'%c' option\n"), optopt);
2089 			goto badusage;
2090 		case '?':
2091 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2092 			    optopt);
2093 			goto badusage;
2094 		}
2095 	}
2096 
2097 	argc -= optind;
2098 	argv += optind;
2099 
2100 	/* get pool name and check number of arguments */
2101 	if (argc < 1) {
2102 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
2103 		goto badusage;
2104 	}
2105 	if (argc < 2) {
2106 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
2107 		goto badusage;
2108 	}
2109 
2110 	poolname = argv[0];
2111 
2112 	/*
2113 	 * As a special case, check for use of '/' in the name, and direct the
2114 	 * user to use 'zfs create' instead.
2115 	 */
2116 	if (strchr(poolname, '/') != NULL) {
2117 		(void) fprintf(stderr, gettext("cannot create '%s': invalid "
2118 		    "character '/' in pool name\n"), poolname);
2119 		(void) fprintf(stderr, gettext("use 'zfs create' to "
2120 		    "create a dataset\n"));
2121 		goto errout;
2122 	}
2123 
2124 	/* pass off to make_root_vdev for bulk processing */
2125 	nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
2126 	    argc - 1, argv + 1);
2127 	if (nvroot == NULL)
2128 		goto errout;
2129 
2130 	/* make_root_vdev() allows 0 toplevel children if there are spares */
2131 	if (!zfs_allocatable_devs(nvroot)) {
2132 		(void) fprintf(stderr, gettext("invalid vdev "
2133 		    "specification: at least one toplevel vdev must be "
2134 		    "specified\n"));
2135 		goto errout;
2136 	}
2137 
2138 	if (altroot != NULL && altroot[0] != '/') {
2139 		(void) fprintf(stderr, gettext("invalid alternate root '%s': "
2140 		    "must be an absolute path\n"), altroot);
2141 		goto errout;
2142 	}
2143 
2144 	/*
2145 	 * Check the validity of the mountpoint and direct the user to use the
2146 	 * '-m' mountpoint option if it looks like its in use.
2147 	 */
2148 	if (mountpoint == NULL ||
2149 	    (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
2150 	    strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
2151 		char buf[MAXPATHLEN];
2152 		DIR *dirp;
2153 
2154 		if (mountpoint && mountpoint[0] != '/') {
2155 			(void) fprintf(stderr, gettext("invalid mountpoint "
2156 			    "'%s': must be an absolute path, 'legacy', or "
2157 			    "'none'\n"), mountpoint);
2158 			goto errout;
2159 		}
2160 
2161 		if (mountpoint == NULL) {
2162 			if (altroot != NULL)
2163 				(void) snprintf(buf, sizeof (buf), "%s/%s",
2164 				    altroot, poolname);
2165 			else
2166 				(void) snprintf(buf, sizeof (buf), "/%s",
2167 				    poolname);
2168 		} else {
2169 			if (altroot != NULL)
2170 				(void) snprintf(buf, sizeof (buf), "%s%s",
2171 				    altroot, mountpoint);
2172 			else
2173 				(void) snprintf(buf, sizeof (buf), "%s",
2174 				    mountpoint);
2175 		}
2176 
2177 		if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
2178 			(void) fprintf(stderr, gettext("mountpoint '%s' : "
2179 			    "%s\n"), buf, strerror(errno));
2180 			(void) fprintf(stderr, gettext("use '-m' "
2181 			    "option to provide a different default\n"));
2182 			goto errout;
2183 		} else if (dirp) {
2184 			int count = 0;
2185 
2186 			while (count < 3 && readdir(dirp) != NULL)
2187 				count++;
2188 			(void) closedir(dirp);
2189 
2190 			if (count > 2) {
2191 				(void) fprintf(stderr, gettext("mountpoint "
2192 				    "'%s' exists and is not empty\n"), buf);
2193 				(void) fprintf(stderr, gettext("use '-m' "
2194 				    "option to provide a "
2195 				    "different default\n"));
2196 				goto errout;
2197 			}
2198 		}
2199 	}
2200 
2201 	/*
2202 	 * Now that the mountpoint's validity has been checked, ensure that
2203 	 * the property is set appropriately prior to creating the pool.
2204 	 */
2205 	if (mountpoint != NULL) {
2206 		ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
2207 		    mountpoint, &fsprops, B_FALSE);
2208 		if (ret != 0)
2209 			goto errout;
2210 	}
2211 
2212 	ret = 1;
2213 	if (dryrun) {
2214 		/*
2215 		 * For a dry run invocation, print out a basic message and run
2216 		 * through all the vdevs in the list and print out in an
2217 		 * appropriate hierarchy.
2218 		 */
2219 		(void) printf(gettext("would create '%s' with the "
2220 		    "following layout:\n\n"), poolname);
2221 
2222 		print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
2223 		print_vdev_tree(NULL, "dedup", nvroot, 0,
2224 		    VDEV_ALLOC_BIAS_DEDUP, 0);
2225 		print_vdev_tree(NULL, "special", nvroot, 0,
2226 		    VDEV_ALLOC_BIAS_SPECIAL, 0);
2227 		print_vdev_tree(NULL, "logs", nvroot, 0,
2228 		    VDEV_ALLOC_BIAS_LOG, 0);
2229 		print_cache_list(nvroot, 0);
2230 		print_spare_list(nvroot, 0);
2231 
2232 		ret = 0;
2233 	} else {
2234 		/*
2235 		 * Load in feature set.
2236 		 * Note: if compatibility property not given, we'll have
2237 		 * NULL, which means 'all features'.
2238 		 */
2239 		boolean_t requested_features[SPA_FEATURES];
2240 		if (zpool_do_load_compat(compat, requested_features) !=
2241 		    ZPOOL_COMPATIBILITY_OK)
2242 			goto errout;
2243 
2244 		/*
2245 		 * props contains list of features to enable.
2246 		 * For each feature:
2247 		 *  - remove it if feature@name=disabled
2248 		 *  - leave it there if feature@name=enabled
2249 		 *  - add it if:
2250 		 *    - enable_pool_features (ie: no '-d' or '-o version')
2251 		 *    - it's supported by the kernel module
2252 		 *    - it's in the requested feature set
2253 		 *  - warn if it's enabled but not in compat
2254 		 */
2255 		for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
2256 			char propname[MAXPATHLEN];
2257 			const char *propval;
2258 			zfeature_info_t *feat = &spa_feature_table[i];
2259 
2260 			(void) snprintf(propname, sizeof (propname),
2261 			    "feature@%s", feat->fi_uname);
2262 
2263 			if (!nvlist_lookup_string(props, propname, &propval)) {
2264 				if (strcmp(propval,
2265 				    ZFS_FEATURE_DISABLED) == 0) {
2266 					(void) nvlist_remove_all(props,
2267 					    propname);
2268 				} else if (strcmp(propval,
2269 				    ZFS_FEATURE_ENABLED) == 0 &&
2270 				    !requested_features[i]) {
2271 					(void) fprintf(stderr, gettext(
2272 					    "Warning: feature \"%s\" enabled "
2273 					    "but is not in specified "
2274 					    "'compatibility' feature set.\n"),
2275 					    feat->fi_uname);
2276 				}
2277 			} else if (
2278 			    enable_pool_features &&
2279 			    feat->fi_zfs_mod_supported &&
2280 			    requested_features[i]) {
2281 				ret = add_prop_list(propname,
2282 				    ZFS_FEATURE_ENABLED, &props, B_TRUE);
2283 				if (ret != 0)
2284 					goto errout;
2285 			}
2286 		}
2287 
2288 		ret = 1;
2289 		if (zpool_create(g_zfs, poolname,
2290 		    nvroot, props, fsprops) == 0) {
2291 			zfs_handle_t *pool = zfs_open(g_zfs,
2292 			    tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
2293 			if (pool != NULL) {
2294 				if (zfs_mount(pool, NULL, 0) == 0) {
2295 					ret = zfs_share(pool, NULL);
2296 					zfs_commit_shares(NULL);
2297 				}
2298 				zfs_close(pool);
2299 			}
2300 		} else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
2301 			(void) fprintf(stderr, gettext("pool name may have "
2302 			    "been omitted\n"));
2303 		}
2304 	}
2305 
2306 errout:
2307 	nvlist_free(nvroot);
2308 	nvlist_free(fsprops);
2309 	nvlist_free(props);
2310 	return (ret);
2311 badusage:
2312 	nvlist_free(fsprops);
2313 	nvlist_free(props);
2314 	usage(B_FALSE);
2315 	return (2);
2316 }
2317 
2318 /*
2319  * zpool destroy <pool>
2320  *
2321  * 	-f	Forcefully unmount any datasets
2322  *
2323  * Destroy the given pool.  Automatically unmounts any datasets in the pool.
2324  */
2325 int
zpool_do_destroy(int argc,char ** argv)2326 zpool_do_destroy(int argc, char **argv)
2327 {
2328 	boolean_t force = B_FALSE;
2329 	int c;
2330 	char *pool;
2331 	zpool_handle_t *zhp;
2332 	int ret;
2333 
2334 	/* check options */
2335 	while ((c = getopt(argc, argv, "f")) != -1) {
2336 		switch (c) {
2337 		case 'f':
2338 			force = B_TRUE;
2339 			break;
2340 		case '?':
2341 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2342 			    optopt);
2343 			usage(B_FALSE);
2344 		}
2345 	}
2346 
2347 	argc -= optind;
2348 	argv += optind;
2349 
2350 	/* check arguments */
2351 	if (argc < 1) {
2352 		(void) fprintf(stderr, gettext("missing pool argument\n"));
2353 		usage(B_FALSE);
2354 	}
2355 	if (argc > 1) {
2356 		(void) fprintf(stderr, gettext("too many arguments\n"));
2357 		usage(B_FALSE);
2358 	}
2359 
2360 	pool = argv[0];
2361 
2362 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
2363 		/*
2364 		 * As a special case, check for use of '/' in the name, and
2365 		 * direct the user to use 'zfs destroy' instead.
2366 		 */
2367 		if (strchr(pool, '/') != NULL)
2368 			(void) fprintf(stderr, gettext("use 'zfs destroy' to "
2369 			    "destroy a dataset\n"));
2370 		return (1);
2371 	}
2372 
2373 	if (zpool_disable_datasets(zhp, force) != 0) {
2374 		(void) fprintf(stderr, gettext("could not destroy '%s': "
2375 		    "could not unmount datasets\n"), zpool_get_name(zhp));
2376 		zpool_close(zhp);
2377 		return (1);
2378 	}
2379 
2380 	/* The history must be logged as part of the export */
2381 	log_history = B_FALSE;
2382 
2383 	ret = (zpool_destroy(zhp, history_str) != 0);
2384 
2385 	zpool_close(zhp);
2386 
2387 	return (ret);
2388 }
2389 
2390 typedef struct export_cbdata {
2391 	taskq_t *taskq;
2392 	pthread_mutex_t mnttab_lock;
2393 	boolean_t force;
2394 	boolean_t hardforce;
2395 	int retval;
2396 } export_cbdata_t;
2397 
2398 
2399 typedef struct {
2400 	char *aea_poolname;
2401 	export_cbdata_t	*aea_cbdata;
2402 } async_export_args_t;
2403 
2404 /*
2405  * Export one pool
2406  */
2407 static int
zpool_export_one(zpool_handle_t * zhp,void * data)2408 zpool_export_one(zpool_handle_t *zhp, void *data)
2409 {
2410 	export_cbdata_t *cb = data;
2411 
2412 	/*
2413 	 * zpool_disable_datasets() is not thread-safe for mnttab access.
2414 	 * So we serialize access here for 'zpool export -a' parallel case.
2415 	 */
2416 	if (cb->taskq != NULL)
2417 		(void) pthread_mutex_lock(&cb->mnttab_lock);
2418 
2419 	int retval = zpool_disable_datasets(zhp, cb->force);
2420 
2421 	if (cb->taskq != NULL)
2422 		(void) pthread_mutex_unlock(&cb->mnttab_lock);
2423 
2424 	if (retval)
2425 		return (1);
2426 
2427 	if (cb->hardforce) {
2428 		if (zpool_export_force(zhp, history_str) != 0)
2429 			return (1);
2430 	} else if (zpool_export(zhp, cb->force, history_str) != 0) {
2431 		return (1);
2432 	}
2433 
2434 	return (0);
2435 }
2436 
2437 /*
2438  * Asynchronous export request
2439  */
2440 static void
zpool_export_task(void * arg)2441 zpool_export_task(void *arg)
2442 {
2443 	async_export_args_t *aea = arg;
2444 
2445 	zpool_handle_t *zhp = zpool_open(g_zfs, aea->aea_poolname);
2446 	if (zhp != NULL) {
2447 		int ret = zpool_export_one(zhp, aea->aea_cbdata);
2448 		if (ret != 0)
2449 			aea->aea_cbdata->retval = ret;
2450 		zpool_close(zhp);
2451 	} else {
2452 		aea->aea_cbdata->retval = 1;
2453 	}
2454 
2455 	free(aea->aea_poolname);
2456 	free(aea);
2457 }
2458 
2459 /*
2460  * Process an export request in parallel
2461  */
2462 static int
zpool_export_one_async(zpool_handle_t * zhp,void * data)2463 zpool_export_one_async(zpool_handle_t *zhp, void *data)
2464 {
2465 	taskq_t *tq = ((export_cbdata_t *)data)->taskq;
2466 	async_export_args_t *aea = safe_malloc(sizeof (async_export_args_t));
2467 
2468 	/* save pool name since zhp will go out of scope */
2469 	aea->aea_poolname = strdup(zpool_get_name(zhp));
2470 	aea->aea_cbdata = data;
2471 
2472 	/* ship off actual export to another thread */
2473 	if (taskq_dispatch(tq, zpool_export_task, (void *)aea,
2474 	    TQ_SLEEP) == TASKQID_INVALID)
2475 		return (errno);	/* unlikely */
2476 	else
2477 		return (0);
2478 }
2479 
2480 /*
2481  * zpool export [-f] <pool> ...
2482  *
2483  *	-a	Export all pools
2484  *	-f	Forcefully unmount datasets
2485  *
2486  * Export the given pools.  By default, the command will attempt to cleanly
2487  * unmount any active datasets within the pool.  If the '-f' flag is specified,
2488  * then the datasets will be forcefully unmounted.
2489  */
2490 int
zpool_do_export(int argc,char ** argv)2491 zpool_do_export(int argc, char **argv)
2492 {
2493 	export_cbdata_t cb;
2494 	boolean_t do_all = B_FALSE;
2495 	boolean_t force = B_FALSE;
2496 	boolean_t hardforce = B_FALSE;
2497 	int c, ret;
2498 
2499 	/* check options */
2500 	while ((c = getopt(argc, argv, "afF")) != -1) {
2501 		switch (c) {
2502 		case 'a':
2503 			do_all = B_TRUE;
2504 			break;
2505 		case 'f':
2506 			force = B_TRUE;
2507 			break;
2508 		case 'F':
2509 			hardforce = B_TRUE;
2510 			break;
2511 		case '?':
2512 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2513 			    optopt);
2514 			usage(B_FALSE);
2515 		}
2516 	}
2517 
2518 	cb.force = force;
2519 	cb.hardforce = hardforce;
2520 	cb.taskq = NULL;
2521 	cb.retval = 0;
2522 	argc -= optind;
2523 	argv += optind;
2524 
2525 	/* The history will be logged as part of the export itself */
2526 	log_history = B_FALSE;
2527 
2528 	if (do_all) {
2529 		if (argc != 0) {
2530 			(void) fprintf(stderr, gettext("too many arguments\n"));
2531 			usage(B_FALSE);
2532 		}
2533 
2534 		cb.taskq = taskq_create("zpool_export",
2535 		    5 * sysconf(_SC_NPROCESSORS_ONLN), minclsyspri, 1, INT_MAX,
2536 		    TASKQ_DYNAMIC);
2537 		(void) pthread_mutex_init(&cb.mnttab_lock, NULL);
2538 
2539 		/* Asynchronously call zpool_export_one using thread pool */
2540 		ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2541 		    B_FALSE, zpool_export_one_async, &cb);
2542 
2543 		taskq_wait(cb.taskq);
2544 		taskq_destroy(cb.taskq);
2545 		(void) pthread_mutex_destroy(&cb.mnttab_lock);
2546 
2547 		return (ret | cb.retval);
2548 	}
2549 
2550 	/* check arguments */
2551 	if (argc < 1) {
2552 		(void) fprintf(stderr, gettext("missing pool argument\n"));
2553 		usage(B_FALSE);
2554 	}
2555 
2556 	ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2557 	    B_FALSE, zpool_export_one, &cb);
2558 
2559 	return (ret);
2560 }
2561 
2562 /*
2563  * Given a vdev configuration, determine the maximum width needed for the device
2564  * name column.
2565  */
2566 static int
max_width(zpool_handle_t * zhp,nvlist_t * nv,int depth,int max,int name_flags)2567 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
2568     int name_flags)
2569 {
2570 	static const char *const subtypes[] =
2571 	    {ZPOOL_CONFIG_SPARES, ZPOOL_CONFIG_L2CACHE, ZPOOL_CONFIG_CHILDREN};
2572 
2573 	char *name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
2574 	max = MAX(strlen(name) + depth, max);
2575 	free(name);
2576 
2577 	nvlist_t **child;
2578 	uint_t children;
2579 	for (size_t i = 0; i < ARRAY_SIZE(subtypes); ++i)
2580 		if (nvlist_lookup_nvlist_array(nv, subtypes[i],
2581 		    &child, &children) == 0)
2582 			for (uint_t c = 0; c < children; ++c)
2583 				max = MAX(max_width(zhp, child[c], depth + 2,
2584 				    max, name_flags), max);
2585 
2586 	return (max);
2587 }
2588 
2589 typedef struct status_cbdata {
2590 	int		cb_count;
2591 	int		cb_name_flags;
2592 	int		cb_namewidth;
2593 	boolean_t	cb_allpools;
2594 	boolean_t	cb_verbose;
2595 	boolean_t	cb_literal;
2596 	boolean_t	cb_explain;
2597 	boolean_t	cb_first;
2598 	boolean_t	cb_dedup_stats;
2599 	boolean_t	cb_print_unhealthy;
2600 	boolean_t	cb_print_status;
2601 	boolean_t	cb_print_slow_ios;
2602 	boolean_t	cb_print_dio_verify;
2603 	boolean_t	cb_print_vdev_init;
2604 	boolean_t	cb_print_vdev_trim;
2605 	vdev_cmd_data_list_t	*vcdl;
2606 	boolean_t	cb_print_power;
2607 	boolean_t	cb_json;
2608 	boolean_t	cb_flat_vdevs;
2609 	nvlist_t	*cb_jsobj;
2610 	boolean_t	cb_json_as_int;
2611 	boolean_t	cb_json_pool_key_guid;
2612 } status_cbdata_t;
2613 
2614 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
2615 static boolean_t
is_blank_str(const char * str)2616 is_blank_str(const char *str)
2617 {
2618 	for (; str != NULL && *str != '\0'; ++str)
2619 		if (!isblank(*str))
2620 			return (B_FALSE);
2621 	return (B_TRUE);
2622 }
2623 
2624 static void
zpool_nvlist_cmd(vdev_cmd_data_list_t * vcdl,const char * pool,const char * path,nvlist_t * item)2625 zpool_nvlist_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path,
2626     nvlist_t *item)
2627 {
2628 	vdev_cmd_data_t *data;
2629 	int i, j, k = 1;
2630 	char tmp[256];
2631 	const char *val;
2632 
2633 	for (i = 0; i < vcdl->count; i++) {
2634 		if ((strcmp(vcdl->data[i].path, path) != 0) ||
2635 		    (strcmp(vcdl->data[i].pool, pool) != 0))
2636 			continue;
2637 
2638 		data = &vcdl->data[i];
2639 		for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2640 			val = NULL;
2641 			for (int k = 0; k < data->cols_cnt; k++) {
2642 				if (strcmp(data->cols[k],
2643 				    vcdl->uniq_cols[j]) == 0) {
2644 					val = data->lines[k];
2645 					break;
2646 				}
2647 			}
2648 			if (val == NULL || is_blank_str(val))
2649 				val = "-";
2650 			fnvlist_add_string(item, vcdl->uniq_cols[j], val);
2651 		}
2652 
2653 		for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2654 			if (data->lines[j]) {
2655 				(void) snprintf(tmp, 256, "extra_%d", k++);
2656 				fnvlist_add_string(item, tmp,
2657 				    data->lines[j]);
2658 			}
2659 		}
2660 		break;
2661 	}
2662 }
2663 
2664 /* Print command output lines for specific vdev in a specific pool */
2665 static void
zpool_print_cmd(vdev_cmd_data_list_t * vcdl,const char * pool,const char * path)2666 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path)
2667 {
2668 	vdev_cmd_data_t *data;
2669 	int i, j;
2670 	const char *val;
2671 
2672 	for (i = 0; i < vcdl->count; i++) {
2673 		if ((strcmp(vcdl->data[i].path, path) != 0) ||
2674 		    (strcmp(vcdl->data[i].pool, pool) != 0)) {
2675 			/* Not the vdev we're looking for */
2676 			continue;
2677 		}
2678 
2679 		data = &vcdl->data[i];
2680 		/* Print out all the output values for this vdev */
2681 		for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2682 			val = NULL;
2683 			/* Does this vdev have values for this column? */
2684 			for (int k = 0; k < data->cols_cnt; k++) {
2685 				if (strcmp(data->cols[k],
2686 				    vcdl->uniq_cols[j]) == 0) {
2687 					/* yes it does, record the value */
2688 					val = data->lines[k];
2689 					break;
2690 				}
2691 			}
2692 			/*
2693 			 * Mark empty values with dashes to make output
2694 			 * awk-able.
2695 			 */
2696 			if (val == NULL || is_blank_str(val))
2697 				val = "-";
2698 
2699 			printf("%*s", vcdl->uniq_cols_width[j], val);
2700 			if (j < vcdl->uniq_cols_cnt - 1)
2701 				(void) fputs("  ", stdout);
2702 		}
2703 
2704 		/* Print out any values that aren't in a column at the end */
2705 		for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2706 			/* Did we have any columns?  If so print a spacer. */
2707 			if (vcdl->uniq_cols_cnt > 0)
2708 				(void) fputs("  ", stdout);
2709 
2710 			val = data->lines[j];
2711 			(void) fputs(val ?: "", stdout);
2712 		}
2713 		break;
2714 	}
2715 }
2716 
2717 /*
2718  * Print vdev initialization status for leaves
2719  */
2720 static void
print_status_initialize(vdev_stat_t * vs,boolean_t verbose)2721 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
2722 {
2723 	if (verbose) {
2724 		if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
2725 		    vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
2726 		    vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
2727 		    !vs->vs_scan_removing) {
2728 			char zbuf[1024];
2729 			char tbuf[256];
2730 
2731 			time_t t = vs->vs_initialize_action_time;
2732 			int initialize_pct = 100;
2733 			if (vs->vs_initialize_state !=
2734 			    VDEV_INITIALIZE_COMPLETE) {
2735 				initialize_pct = (vs->vs_initialize_bytes_done *
2736 				    100 / (vs->vs_initialize_bytes_est + 1));
2737 			}
2738 
2739 			(void) ctime_r(&t, tbuf);
2740 			tbuf[24] = 0;
2741 
2742 			switch (vs->vs_initialize_state) {
2743 			case VDEV_INITIALIZE_SUSPENDED:
2744 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2745 				    gettext("suspended, started at"), tbuf);
2746 				break;
2747 			case VDEV_INITIALIZE_ACTIVE:
2748 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2749 				    gettext("started at"), tbuf);
2750 				break;
2751 			case VDEV_INITIALIZE_COMPLETE:
2752 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2753 				    gettext("completed at"), tbuf);
2754 				break;
2755 			}
2756 
2757 			(void) printf(gettext("  (%d%% initialized%s)"),
2758 			    initialize_pct, zbuf);
2759 		} else {
2760 			(void) printf(gettext("  (uninitialized)"));
2761 		}
2762 	} else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
2763 		(void) printf(gettext("  (initializing)"));
2764 	}
2765 }
2766 
2767 /*
2768  * Print vdev TRIM status for leaves
2769  */
2770 static void
print_status_trim(vdev_stat_t * vs,boolean_t verbose)2771 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
2772 {
2773 	if (verbose) {
2774 		if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
2775 		    vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
2776 		    vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
2777 		    !vs->vs_scan_removing) {
2778 			char zbuf[1024];
2779 			char tbuf[256];
2780 
2781 			time_t t = vs->vs_trim_action_time;
2782 			int trim_pct = 100;
2783 			if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
2784 				trim_pct = (vs->vs_trim_bytes_done *
2785 				    100 / (vs->vs_trim_bytes_est + 1));
2786 			}
2787 
2788 			(void) ctime_r(&t, tbuf);
2789 			tbuf[24] = 0;
2790 
2791 			switch (vs->vs_trim_state) {
2792 			case VDEV_TRIM_SUSPENDED:
2793 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2794 				    gettext("suspended, started at"), tbuf);
2795 				break;
2796 			case VDEV_TRIM_ACTIVE:
2797 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2798 				    gettext("started at"), tbuf);
2799 				break;
2800 			case VDEV_TRIM_COMPLETE:
2801 				(void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2802 				    gettext("completed at"), tbuf);
2803 				break;
2804 			}
2805 
2806 			(void) printf(gettext("  (%d%% trimmed%s)"),
2807 			    trim_pct, zbuf);
2808 		} else if (vs->vs_trim_notsup) {
2809 			(void) printf(gettext("  (trim unsupported)"));
2810 		} else {
2811 			(void) printf(gettext("  (untrimmed)"));
2812 		}
2813 	} else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
2814 		(void) printf(gettext("  (trimming)"));
2815 	}
2816 }
2817 
2818 /*
2819  * Return the color associated with a health string.  This includes returning
2820  * NULL for no color change.
2821  */
2822 static const char *
health_str_to_color(const char * health)2823 health_str_to_color(const char *health)
2824 {
2825 	if (strcmp(health, gettext("FAULTED")) == 0 ||
2826 	    strcmp(health, gettext("SUSPENDED")) == 0 ||
2827 	    strcmp(health, gettext("UNAVAIL")) == 0) {
2828 		return (ANSI_RED);
2829 	}
2830 
2831 	if (strcmp(health, gettext("OFFLINE")) == 0 ||
2832 	    strcmp(health, gettext("DEGRADED")) == 0 ||
2833 	    strcmp(health, gettext("REMOVED")) == 0) {
2834 		return (ANSI_YELLOW);
2835 	}
2836 
2837 	return (NULL);
2838 }
2839 
2840 /*
2841  * Called for each leaf vdev.  Returns 0 if the vdev is healthy.
2842  * A vdev is unhealthy if any of the following are true:
2843  * 1) there are read, write, or checksum errors,
2844  * 2) its state is not ONLINE, or
2845  * 3) slow IO reporting was requested (-s) and there are slow IOs.
2846  */
2847 static int
vdev_health_check_cb(void * hdl_data,nvlist_t * nv,void * data)2848 vdev_health_check_cb(void *hdl_data, nvlist_t *nv, void *data)
2849 {
2850 	status_cbdata_t *cb = data;
2851 	vdev_stat_t *vs;
2852 	uint_t vsc;
2853 	(void) hdl_data;
2854 
2855 	if (nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2856 	    (uint64_t **)&vs, &vsc) != 0)
2857 		return (1);
2858 
2859 	if (vs->vs_checksum_errors || vs->vs_read_errors ||
2860 	    vs->vs_write_errors || vs->vs_state != VDEV_STATE_HEALTHY)
2861 		return (1);
2862 
2863 	if (cb->cb_print_slow_ios && vs->vs_slow_ios)
2864 		return (1);
2865 
2866 	return (0);
2867 }
2868 
2869 /*
2870  * Print out configuration state as requested by status_callback.
2871  */
2872 static void
print_status_config(zpool_handle_t * zhp,status_cbdata_t * cb,const char * name,nvlist_t * nv,int depth,boolean_t isspare,vdev_rebuild_stat_t * vrs)2873 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
2874     nvlist_t *nv, int depth, boolean_t isspare, vdev_rebuild_stat_t *vrs)
2875 {
2876 	nvlist_t **child, *root;
2877 	uint_t c, i, vsc, children;
2878 	pool_scan_stat_t *ps = NULL;
2879 	vdev_stat_t *vs;
2880 	char rbuf[6], wbuf[6], cbuf[6], dbuf[6];
2881 	char *vname;
2882 	uint64_t notpresent;
2883 	spare_cbdata_t spare_cb;
2884 	const char *state;
2885 	const char *type;
2886 	const char *path = NULL;
2887 	const char *rcolor = NULL, *wcolor = NULL, *ccolor = NULL,
2888 	    *scolor = NULL;
2889 
2890 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2891 	    &child, &children) != 0)
2892 		children = 0;
2893 
2894 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2895 	    (uint64_t **)&vs, &vsc) == 0);
2896 
2897 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2898 
2899 	if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2900 		return;
2901 
2902 	state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2903 
2904 	if (isspare) {
2905 		/*
2906 		 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
2907 		 * online drives.
2908 		 */
2909 		if (vs->vs_aux == VDEV_AUX_SPARED)
2910 			state = gettext("INUSE");
2911 		else if (vs->vs_state == VDEV_STATE_HEALTHY)
2912 			state = gettext("AVAIL");
2913 	}
2914 
2915 	/*
2916 	 * If '-e' is specified then top-level vdevs and their children
2917 	 * can be pruned if all of their leaves are healthy.
2918 	 */
2919 	if (cb->cb_print_unhealthy && depth > 0 &&
2920 	    for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
2921 		return;
2922 	}
2923 
2924 	(void) printf_color(health_str_to_color(state),
2925 	    "\t%*s%-*s  %-8s", depth, "", cb->cb_namewidth - depth,
2926 	    name, state);
2927 
2928 	if (!isspare) {
2929 		if (vs->vs_read_errors)
2930 			rcolor = ANSI_RED;
2931 
2932 		if (vs->vs_write_errors)
2933 			wcolor = ANSI_RED;
2934 
2935 		if (vs->vs_checksum_errors)
2936 			ccolor = ANSI_RED;
2937 
2938 		if (vs->vs_slow_ios)
2939 			scolor = ANSI_BLUE;
2940 
2941 		if (cb->cb_literal) {
2942 			(void) fputc(' ', stdout);
2943 			(void) printf_color(rcolor, "%5llu",
2944 			    (u_longlong_t)vs->vs_read_errors);
2945 			(void) fputc(' ', stdout);
2946 			(void) printf_color(wcolor, "%5llu",
2947 			    (u_longlong_t)vs->vs_write_errors);
2948 			(void) fputc(' ', stdout);
2949 			(void) printf_color(ccolor, "%5llu",
2950 			    (u_longlong_t)vs->vs_checksum_errors);
2951 		} else {
2952 			zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
2953 			zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
2954 			zfs_nicenum(vs->vs_checksum_errors, cbuf,
2955 			    sizeof (cbuf));
2956 			(void) fputc(' ', stdout);
2957 			(void) printf_color(rcolor, "%5s", rbuf);
2958 			(void) fputc(' ', stdout);
2959 			(void) printf_color(wcolor, "%5s", wbuf);
2960 			(void) fputc(' ', stdout);
2961 			(void) printf_color(ccolor, "%5s", cbuf);
2962 		}
2963 		if (cb->cb_print_slow_ios) {
2964 			if (children == 0)  {
2965 				/* Only leafs vdevs have slow IOs */
2966 				zfs_nicenum(vs->vs_slow_ios, rbuf,
2967 				    sizeof (rbuf));
2968 			} else {
2969 				(void) snprintf(rbuf, sizeof (rbuf), "-");
2970 			}
2971 
2972 			if (cb->cb_literal)
2973 				(void) printf_color(scolor, " %5llu",
2974 				    (u_longlong_t)vs->vs_slow_ios);
2975 			else
2976 				(void) printf_color(scolor, " %5s", rbuf);
2977 		}
2978 		if (cb->cb_print_power) {
2979 			if (children == 0)  {
2980 				/* Only leaf vdevs have physical slots */
2981 				switch (zpool_power_current_state(zhp, (char *)
2982 				    fnvlist_lookup_string(nv,
2983 				    ZPOOL_CONFIG_PATH))) {
2984 				case 0:
2985 					(void) printf_color(ANSI_RED, " %5s",
2986 					    gettext("off"));
2987 					break;
2988 				case 1:
2989 					printf(" %5s", gettext("on"));
2990 					break;
2991 				default:
2992 					printf(" %5s", "-");
2993 				}
2994 			} else {
2995 				printf(" %5s", "-");
2996 			}
2997 		}
2998 		if (VDEV_STAT_VALID(vs_dio_verify_errors, vsc) &&
2999 		    cb->cb_print_dio_verify) {
3000 			zfs_nicenum(vs->vs_dio_verify_errors, dbuf,
3001 			    sizeof (dbuf));
3002 
3003 			if (cb->cb_literal)
3004 				printf(" %5llu",
3005 				    (u_longlong_t)vs->vs_dio_verify_errors);
3006 			else
3007 				printf(" %5s", dbuf);
3008 		}
3009 	}
3010 
3011 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
3012 	    &notpresent) == 0) {
3013 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
3014 		(void) printf("  %s %s", gettext("was"), path);
3015 	} else if (vs->vs_aux != 0) {
3016 		(void) printf("  ");
3017 		color_start(ANSI_RED);
3018 		switch (vs->vs_aux) {
3019 		case VDEV_AUX_OPEN_FAILED:
3020 			(void) printf(gettext("cannot open"));
3021 			break;
3022 
3023 		case VDEV_AUX_BAD_GUID_SUM:
3024 			(void) printf(gettext("missing device"));
3025 			break;
3026 
3027 		case VDEV_AUX_NO_REPLICAS:
3028 			(void) printf(gettext("insufficient replicas"));
3029 			break;
3030 
3031 		case VDEV_AUX_VERSION_NEWER:
3032 			(void) printf(gettext("newer version"));
3033 			break;
3034 
3035 		case VDEV_AUX_UNSUP_FEAT:
3036 			(void) printf(gettext("unsupported feature(s)"));
3037 			break;
3038 
3039 		case VDEV_AUX_ASHIFT_TOO_BIG:
3040 			(void) printf(gettext("unsupported minimum blocksize"));
3041 			break;
3042 
3043 		case VDEV_AUX_SPARED:
3044 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3045 			    &spare_cb.cb_guid) == 0);
3046 			if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
3047 				if (strcmp(zpool_get_name(spare_cb.cb_zhp),
3048 				    zpool_get_name(zhp)) == 0)
3049 					(void) printf(gettext("currently in "
3050 					    "use"));
3051 				else
3052 					(void) printf(gettext("in use by "
3053 					    "pool '%s'"),
3054 					    zpool_get_name(spare_cb.cb_zhp));
3055 				zpool_close(spare_cb.cb_zhp);
3056 			} else {
3057 				(void) printf(gettext("currently in use"));
3058 			}
3059 			break;
3060 
3061 		case VDEV_AUX_ERR_EXCEEDED:
3062 			if (vs->vs_read_errors + vs->vs_write_errors +
3063 			    vs->vs_checksum_errors == 0 && children == 0 &&
3064 			    vs->vs_slow_ios > 0) {
3065 				(void) printf(gettext("too many slow I/Os"));
3066 			} else {
3067 				(void) printf(gettext("too many errors"));
3068 			}
3069 			break;
3070 
3071 		case VDEV_AUX_IO_FAILURE:
3072 			(void) printf(gettext("experienced I/O failures"));
3073 			break;
3074 
3075 		case VDEV_AUX_BAD_LOG:
3076 			(void) printf(gettext("bad intent log"));
3077 			break;
3078 
3079 		case VDEV_AUX_EXTERNAL:
3080 			(void) printf(gettext("external device fault"));
3081 			break;
3082 
3083 		case VDEV_AUX_SPLIT_POOL:
3084 			(void) printf(gettext("split into new pool"));
3085 			break;
3086 
3087 		case VDEV_AUX_ACTIVE:
3088 			(void) printf(gettext("currently in use"));
3089 			break;
3090 
3091 		case VDEV_AUX_CHILDREN_OFFLINE:
3092 			(void) printf(gettext("all children offline"));
3093 			break;
3094 
3095 		case VDEV_AUX_BAD_LABEL:
3096 			(void) printf(gettext("invalid label"));
3097 			break;
3098 
3099 		default:
3100 			(void) printf(gettext("corrupted data"));
3101 			break;
3102 		}
3103 		color_end();
3104 	} else if (children == 0 && !isspare &&
3105 	    getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
3106 	    VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
3107 	    vs->vs_configured_ashift < vs->vs_physical_ashift) {
3108 		(void) printf(
3109 		    gettext("  block size: %dB configured, %dB native"),
3110 		    1 << vs->vs_configured_ashift, 1 << vs->vs_physical_ashift);
3111 	}
3112 
3113 	if (vs->vs_scan_removing != 0) {
3114 		(void) printf(gettext("  (removing)"));
3115 	} else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
3116 		(void) printf(gettext("  (non-allocating)"));
3117 	}
3118 
3119 	/* The root vdev has the scrub/resilver stats */
3120 	root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
3121 	    ZPOOL_CONFIG_VDEV_TREE);
3122 	(void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
3123 	    (uint64_t **)&ps, &c);
3124 
3125 	/*
3126 	 * If you force fault a drive that's resilvering, its scan stats can
3127 	 * get frozen in time, giving the false impression that it's
3128 	 * being resilvered.  That's why we check the state to see if the vdev
3129 	 * is healthy before reporting "resilvering" or "repairing".
3130 	 */
3131 	if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0 &&
3132 	    vs->vs_state == VDEV_STATE_HEALTHY) {
3133 		if (vs->vs_scan_processed != 0) {
3134 			(void) printf(gettext("  (%s)"),
3135 			    (ps->pss_func == POOL_SCAN_RESILVER) ?
3136 			    "resilvering" : "repairing");
3137 		} else if (vs->vs_resilver_deferred) {
3138 			(void) printf(gettext("  (awaiting resilver)"));
3139 		}
3140 	}
3141 
3142 	/* The top-level vdevs have the rebuild stats */
3143 	if (vrs != NULL && vrs->vrs_state == VDEV_REBUILD_ACTIVE &&
3144 	    children == 0 && vs->vs_state == VDEV_STATE_HEALTHY) {
3145 		if (vs->vs_rebuild_processed != 0) {
3146 			(void) printf(gettext("  (resilvering)"));
3147 		}
3148 	}
3149 
3150 	if (cb->vcdl != NULL) {
3151 		if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
3152 			printf("  ");
3153 			zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
3154 		}
3155 	}
3156 
3157 	/* Display vdev initialization and trim status for leaves. */
3158 	if (children == 0) {
3159 		print_status_initialize(vs, cb->cb_print_vdev_init);
3160 		print_status_trim(vs, cb->cb_print_vdev_trim);
3161 	}
3162 
3163 	(void) printf("\n");
3164 
3165 	for (c = 0; c < children; c++) {
3166 		uint64_t islog = B_FALSE, ishole = B_FALSE;
3167 
3168 		/* Don't print logs or holes here */
3169 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3170 		    &islog);
3171 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
3172 		    &ishole);
3173 		if (islog || ishole)
3174 			continue;
3175 		/* Only print normal classes here */
3176 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3177 			continue;
3178 
3179 		/* Provide vdev_rebuild_stats to children if available */
3180 		if (vrs == NULL) {
3181 			(void) nvlist_lookup_uint64_array(nv,
3182 			    ZPOOL_CONFIG_REBUILD_STATS,
3183 			    (uint64_t **)&vrs, &i);
3184 		}
3185 
3186 		vname = zpool_vdev_name(g_zfs, zhp, child[c],
3187 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3188 		print_status_config(zhp, cb, vname, child[c], depth + 2,
3189 		    isspare, vrs);
3190 		free(vname);
3191 	}
3192 }
3193 
3194 /*
3195  * Print the configuration of an exported pool.  Iterate over all vdevs in the
3196  * pool, printing out the name and status for each one.
3197  */
3198 static void
print_import_config(status_cbdata_t * cb,const char * name,nvlist_t * nv,int depth)3199 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
3200     int depth)
3201 {
3202 	nvlist_t **child;
3203 	uint_t c, children;
3204 	vdev_stat_t *vs;
3205 	const char *type;
3206 	char *vname;
3207 
3208 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
3209 	if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
3210 	    strcmp(type, VDEV_TYPE_HOLE) == 0)
3211 		return;
3212 
3213 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
3214 	    (uint64_t **)&vs, &c) == 0);
3215 
3216 	(void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
3217 	(void) printf("  %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
3218 
3219 	if (vs->vs_aux != 0) {
3220 		(void) printf("  ");
3221 
3222 		switch (vs->vs_aux) {
3223 		case VDEV_AUX_OPEN_FAILED:
3224 			(void) printf(gettext("cannot open"));
3225 			break;
3226 
3227 		case VDEV_AUX_BAD_GUID_SUM:
3228 			(void) printf(gettext("missing device"));
3229 			break;
3230 
3231 		case VDEV_AUX_NO_REPLICAS:
3232 			(void) printf(gettext("insufficient replicas"));
3233 			break;
3234 
3235 		case VDEV_AUX_VERSION_NEWER:
3236 			(void) printf(gettext("newer version"));
3237 			break;
3238 
3239 		case VDEV_AUX_UNSUP_FEAT:
3240 			(void) printf(gettext("unsupported feature(s)"));
3241 			break;
3242 
3243 		case VDEV_AUX_ERR_EXCEEDED:
3244 			(void) printf(gettext("too many errors"));
3245 			break;
3246 
3247 		case VDEV_AUX_ACTIVE:
3248 			(void) printf(gettext("currently in use"));
3249 			break;
3250 
3251 		case VDEV_AUX_CHILDREN_OFFLINE:
3252 			(void) printf(gettext("all children offline"));
3253 			break;
3254 
3255 		case VDEV_AUX_BAD_LABEL:
3256 			(void) printf(gettext("invalid label"));
3257 			break;
3258 
3259 		default:
3260 			(void) printf(gettext("corrupted data"));
3261 			break;
3262 		}
3263 	}
3264 	(void) printf("\n");
3265 
3266 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
3267 	    &child, &children) != 0)
3268 		return;
3269 
3270 	for (c = 0; c < children; c++) {
3271 		uint64_t is_log = B_FALSE;
3272 
3273 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3274 		    &is_log);
3275 		if (is_log)
3276 			continue;
3277 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3278 			continue;
3279 
3280 		vname = zpool_vdev_name(g_zfs, NULL, child[c],
3281 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3282 		print_import_config(cb, vname, child[c], depth + 2);
3283 		free(vname);
3284 	}
3285 
3286 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
3287 	    &child, &children) == 0) {
3288 		(void) printf(gettext("\tcache\n"));
3289 		for (c = 0; c < children; c++) {
3290 			vname = zpool_vdev_name(g_zfs, NULL, child[c],
3291 			    cb->cb_name_flags);
3292 			(void) printf("\t  %s\n", vname);
3293 			free(vname);
3294 		}
3295 	}
3296 
3297 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
3298 	    &child, &children) == 0) {
3299 		(void) printf(gettext("\tspares\n"));
3300 		for (c = 0; c < children; c++) {
3301 			vname = zpool_vdev_name(g_zfs, NULL, child[c],
3302 			    cb->cb_name_flags);
3303 			(void) printf("\t  %s\n", vname);
3304 			free(vname);
3305 		}
3306 	}
3307 }
3308 
3309 /*
3310  * Print specialized class vdevs.
3311  *
3312  * These are recorded as top level vdevs in the main pool child array
3313  * but with "is_log" set to 1 or an "alloc_bias" string. We use either
3314  * print_status_config() or print_import_config() to print the top level
3315  * class vdevs then any of their children (eg mirrored slogs) are printed
3316  * recursively - which works because only the top level vdev is marked.
3317  */
3318 static void
print_class_vdevs(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,const char * class)3319 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
3320     const char *class)
3321 {
3322 	uint_t c, children;
3323 	nvlist_t **child;
3324 	boolean_t printed = B_FALSE;
3325 
3326 	assert(zhp != NULL || !cb->cb_verbose);
3327 
3328 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
3329 	    &children) != 0)
3330 		return;
3331 
3332 	for (c = 0; c < children; c++) {
3333 		uint64_t is_log = B_FALSE;
3334 		const char *bias = NULL;
3335 		const char *type = NULL;
3336 
3337 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3338 		    &is_log);
3339 
3340 		if (is_log) {
3341 			bias = (char *)VDEV_ALLOC_CLASS_LOGS;
3342 		} else {
3343 			(void) nvlist_lookup_string(child[c],
3344 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
3345 			(void) nvlist_lookup_string(child[c],
3346 			    ZPOOL_CONFIG_TYPE, &type);
3347 		}
3348 
3349 		if (bias == NULL || strcmp(bias, class) != 0)
3350 			continue;
3351 		if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
3352 			continue;
3353 
3354 		if (!printed) {
3355 			(void) printf("\t%s\t\n", gettext(class));
3356 			printed = B_TRUE;
3357 		}
3358 
3359 		char *name = zpool_vdev_name(g_zfs, zhp, child[c],
3360 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3361 		if (cb->cb_print_status)
3362 			print_status_config(zhp, cb, name, child[c], 2,
3363 			    B_FALSE, NULL);
3364 		else
3365 			print_import_config(cb, name, child[c], 2);
3366 		free(name);
3367 	}
3368 }
3369 
3370 /*
3371  * Display the status for the given pool.
3372  */
3373 static int
show_import(nvlist_t * config,boolean_t report_error)3374 show_import(nvlist_t *config, boolean_t report_error)
3375 {
3376 	uint64_t pool_state;
3377 	vdev_stat_t *vs;
3378 	const char *name;
3379 	uint64_t guid;
3380 	uint64_t hostid = 0;
3381 	const char *msgid;
3382 	const char *hostname = "unknown";
3383 	nvlist_t *nvroot, *nvinfo;
3384 	zpool_status_t reason;
3385 	zpool_errata_t errata;
3386 	const char *health;
3387 	uint_t vsc;
3388 	const char *comment;
3389 	const char *indent;
3390 	char buf[2048];
3391 	status_cbdata_t cb = { 0 };
3392 
3393 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3394 	    &name) == 0);
3395 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3396 	    &guid) == 0);
3397 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3398 	    &pool_state) == 0);
3399 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3400 	    &nvroot) == 0);
3401 
3402 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
3403 	    (uint64_t **)&vs, &vsc) == 0);
3404 	health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
3405 
3406 	reason = zpool_import_status(config, &msgid, &errata);
3407 
3408 	/*
3409 	 * If we're importing using a cachefile, then we won't report any
3410 	 * errors unless we are in the scan phase of the import.
3411 	 */
3412 	if (reason != ZPOOL_STATUS_OK && !report_error)
3413 		return (reason);
3414 
3415 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0) {
3416 		indent = " ";
3417 	} else {
3418 		comment = NULL;
3419 		indent = "";
3420 	}
3421 
3422 	(void) printf(gettext("%s  pool: %s\n"), indent, name);
3423 	(void) printf(gettext("%s    id: %llu\n"), indent, (u_longlong_t)guid);
3424 	(void) printf(gettext("%s state: %s"), indent, health);
3425 	if (pool_state == POOL_STATE_DESTROYED)
3426 		(void) printf(gettext(" (DESTROYED)"));
3427 	(void) printf("\n");
3428 
3429 	if (reason != ZPOOL_STATUS_OK) {
3430 		(void) printf("%s", indent);
3431 		(void) printf_color(ANSI_BOLD, gettext("status: "));
3432 	}
3433 	switch (reason) {
3434 	case ZPOOL_STATUS_MISSING_DEV_R:
3435 	case ZPOOL_STATUS_MISSING_DEV_NR:
3436 	case ZPOOL_STATUS_BAD_GUID_SUM:
3437 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3438 		    "are missing from the system.\n"));
3439 		break;
3440 
3441 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
3442 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
3443 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3444 		    "contains corrupted data.\n"));
3445 		break;
3446 
3447 	case ZPOOL_STATUS_CORRUPT_DATA:
3448 		(void) printf_color(ANSI_YELLOW, gettext("The pool data is "
3449 		    "corrupted.\n"));
3450 		break;
3451 
3452 	case ZPOOL_STATUS_OFFLINE_DEV:
3453 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3454 		    "are offlined.\n"));
3455 		break;
3456 
3457 	case ZPOOL_STATUS_CORRUPT_POOL:
3458 		(void) printf_color(ANSI_YELLOW, gettext("The pool metadata is "
3459 		    "incomplete or corrupted.\n"));
3460 		break;
3461 
3462 	case ZPOOL_STATUS_VERSION_OLDER:
3463 		(void) printf_color(ANSI_YELLOW, gettext("The pool is "
3464 		    "formatted using a legacy on-disk version.\n"));
3465 		break;
3466 
3467 	case ZPOOL_STATUS_VERSION_NEWER:
3468 		(void) printf_color(ANSI_YELLOW, gettext("The pool is "
3469 		    "formatted using an incompatible version.\n"));
3470 		break;
3471 
3472 	case ZPOOL_STATUS_FEAT_DISABLED:
3473 		(void) printf_color(ANSI_YELLOW, gettext("Some supported "
3474 		    "features are not enabled on the pool.\n"
3475 		    "\t%s(Note that they may be intentionally disabled if the\n"
3476 		    "\t%s'compatibility' property is set.)\n"), indent, indent);
3477 		break;
3478 
3479 	case ZPOOL_STATUS_COMPATIBILITY_ERR:
3480 		(void) printf_color(ANSI_YELLOW, gettext("Error reading or "
3481 		    "parsing the file(s) indicated by the 'compatibility'\n"
3482 		    "\t%sproperty.\n"), indent);
3483 		break;
3484 
3485 	case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
3486 		(void) printf_color(ANSI_YELLOW, gettext("One or more features "
3487 		    "are enabled on the pool despite not being\n"
3488 		    "\t%srequested by the 'compatibility' property.\n"),
3489 		    indent);
3490 		break;
3491 
3492 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
3493 		(void) printf_color(ANSI_YELLOW, gettext("The pool uses the "
3494 		    "following feature(s) not supported on this system:\n"));
3495 		color_start(ANSI_YELLOW);
3496 		zpool_collect_unsup_feat(config, buf, 2048);
3497 		(void) printf("%s", buf);
3498 		color_end();
3499 		break;
3500 
3501 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3502 		(void) printf_color(ANSI_YELLOW, gettext("The pool can only be "
3503 		    "accessed in read-only mode on this system. It\n"
3504 		    "\t%scannot be accessed in read-write mode because it uses "
3505 		    "the following\n"
3506 		    "\t%sfeature(s) not supported on this system:\n"),
3507 		    indent, indent);
3508 		color_start(ANSI_YELLOW);
3509 		zpool_collect_unsup_feat(config, buf, 2048);
3510 		(void) printf("%s", buf);
3511 		color_end();
3512 		break;
3513 
3514 	case ZPOOL_STATUS_HOSTID_ACTIVE:
3515 		(void) printf_color(ANSI_YELLOW, gettext("The pool is "
3516 		    "currently imported by another system.\n"));
3517 		break;
3518 
3519 	case ZPOOL_STATUS_HOSTID_REQUIRED:
3520 		(void) printf_color(ANSI_YELLOW, gettext("The pool has the "
3521 		    "multihost property on.  It cannot\n"
3522 		    "\t%sbe safely imported when the system hostid is not "
3523 		    "set.\n"), indent);
3524 		break;
3525 
3526 	case ZPOOL_STATUS_HOSTID_MISMATCH:
3527 		(void) printf_color(ANSI_YELLOW, gettext("The pool was last "
3528 		    "accessed by another system.\n"));
3529 		break;
3530 
3531 	case ZPOOL_STATUS_FAULTED_DEV_R:
3532 	case ZPOOL_STATUS_FAULTED_DEV_NR:
3533 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3534 		    "are faulted.\n"));
3535 		break;
3536 
3537 	case ZPOOL_STATUS_BAD_LOG:
3538 		(void) printf_color(ANSI_YELLOW, gettext("An intent log record "
3539 		    "cannot be read.\n"));
3540 		break;
3541 
3542 	case ZPOOL_STATUS_RESILVERING:
3543 	case ZPOOL_STATUS_REBUILDING:
3544 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3545 		    "were being resilvered.\n"));
3546 		break;
3547 
3548 	case ZPOOL_STATUS_ERRATA:
3549 		(void) printf_color(ANSI_YELLOW,
3550 		    gettext("Errata #%d detected.\n"),
3551 		    errata);
3552 		break;
3553 
3554 	case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
3555 		(void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3556 		    "are configured to use a non-native block size.\n"
3557 		    "\t%sExpect reduced performance.\n"), indent);
3558 		break;
3559 
3560 	default:
3561 		/*
3562 		 * No other status can be seen when importing pools.
3563 		 */
3564 		assert(reason == ZPOOL_STATUS_OK);
3565 	}
3566 
3567 	/*
3568 	 * Print out an action according to the overall state of the pool.
3569 	 */
3570 	if (vs->vs_state != VDEV_STATE_HEALTHY ||
3571 	    reason != ZPOOL_STATUS_ERRATA || errata != ZPOOL_ERRATA_NONE) {
3572 		(void) printf("%s", indent);
3573 		(void) printf(gettext("action: "));
3574 	}
3575 	if (vs->vs_state == VDEV_STATE_HEALTHY) {
3576 		if (reason == ZPOOL_STATUS_VERSION_OLDER ||
3577 		    reason == ZPOOL_STATUS_FEAT_DISABLED) {
3578 			(void) printf(gettext("The pool can be imported using "
3579 			    "its name or numeric identifier, though\n"
3580 			    "\t%ssome features will not be available without "
3581 			    "an explicit 'zpool upgrade'.\n"), indent);
3582 		} else if (reason == ZPOOL_STATUS_COMPATIBILITY_ERR) {
3583 			(void) printf(gettext("The pool can be imported using "
3584 			    "its name or numeric\n"
3585 			    "\t%sidentifier, though the file(s) indicated by "
3586 			    "its 'compatibility'\n"
3587 			    "\t%sproperty cannot be parsed at this time.\n"),
3588 			    indent, indent);
3589 		} else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
3590 			(void) printf(gettext("The pool can be imported using "
3591 			    "its name or numeric identifier and\n"
3592 			    "\t%sthe '-f' flag.\n"), indent);
3593 		} else if (reason == ZPOOL_STATUS_ERRATA) {
3594 			switch (errata) {
3595 			case ZPOOL_ERRATA_ZOL_2094_SCRUB:
3596 				(void) printf(gettext("The pool can be "
3597 				    "imported using its name or numeric "
3598 				    "identifier,\n"
3599 				    "\t%showever there is a compatibility "
3600 				    "issue which should be corrected\n"
3601 				    "\t%sby running 'zpool scrub'\n"),
3602 				    indent, indent);
3603 				break;
3604 
3605 			case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
3606 				(void) printf(gettext("The pool cannot be "
3607 				    "imported with this version of ZFS due to\n"
3608 				    "\t%san active asynchronous destroy. "
3609 				    "Revert to an earlier version\n"
3610 				    "\t%sand allow the destroy to complete "
3611 				    "before updating.\n"), indent, indent);
3612 				break;
3613 
3614 			case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
3615 				(void) printf(gettext("Existing encrypted "
3616 				    "datasets contain an on-disk "
3617 				    "incompatibility, which\n"
3618 				    "\t%sneeds to be corrected. Backup these "
3619 				    "datasets to new encrypted datasets\n"
3620 				    "\t%sand destroy the old ones.\n"),
3621 				    indent, indent);
3622 				break;
3623 
3624 			case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
3625 				(void) printf(gettext("Existing encrypted "
3626 				    "snapshots and bookmarks contain an "
3627 				    "on-disk\n"
3628 				    "\t%sincompatibility. This may cause "
3629 				    "on-disk corruption if they are used\n"
3630 				    "\t%swith 'zfs recv'. To correct the "
3631 				    "issue, enable the bookmark_v2 feature.\n"
3632 				    "\t%sNo additional action is needed if "
3633 				    "there are no encrypted snapshots or\n"
3634 				    "\t%sbookmarks. If preserving the "
3635 				    "encrypted snapshots and bookmarks is\n"
3636 				    "\t%srequired, use a non-raw send to "
3637 				    "backup and restore them. Alternately,\n"
3638 				    "\t%sthey may be removed to resolve the "
3639 				    "incompatibility.\n"), indent, indent,
3640 				    indent, indent, indent, indent);
3641 				break;
3642 			default:
3643 				/*
3644 				 * All errata must contain an action message.
3645 				 */
3646 				assert(errata == ZPOOL_ERRATA_NONE);
3647 			}
3648 		} else {
3649 			(void) printf(gettext("The pool can be imported using "
3650 			    "its name or numeric identifier.\n"));
3651 		}
3652 	} else if (vs->vs_state == VDEV_STATE_DEGRADED) {
3653 		(void) printf(gettext("The pool can be imported despite "
3654 		    "missing or damaged devices.  The\n"
3655 		    "\t%sfault tolerance of the pool may be compromised if "
3656 		    "imported.\n"), indent);
3657 	} else {
3658 		switch (reason) {
3659 		case ZPOOL_STATUS_VERSION_NEWER:
3660 			(void) printf(gettext("The pool cannot be imported.  "
3661 			    "Access the pool on a system running newer\n"
3662 			    "\t%ssoftware, or recreate the pool from "
3663 			    "backup.\n"), indent);
3664 			break;
3665 		case ZPOOL_STATUS_UNSUP_FEAT_READ:
3666 			(void) printf(gettext("The pool cannot be imported. "
3667 			    "Access the pool on a system that supports\n"
3668 			    "\t%sthe required feature(s), or recreate the pool "
3669 			    "from backup.\n"), indent);
3670 			break;
3671 		case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3672 			(void) printf(gettext("The pool cannot be imported in "
3673 			    "read-write mode. Import the pool with\n"
3674 			    "\t%s'-o readonly=on', access the pool on a system "
3675 			    "that supports the\n"
3676 			    "\t%srequired feature(s), or recreate the pool "
3677 			    "from backup.\n"), indent, indent);
3678 			break;
3679 		case ZPOOL_STATUS_MISSING_DEV_R:
3680 		case ZPOOL_STATUS_MISSING_DEV_NR:
3681 		case ZPOOL_STATUS_BAD_GUID_SUM:
3682 			(void) printf(gettext("The pool cannot be imported. "
3683 			    "Attach the missing\n"
3684 			    "\t%sdevices and try again.\n"), indent);
3685 			break;
3686 		case ZPOOL_STATUS_HOSTID_ACTIVE:
3687 			VERIFY0(nvlist_lookup_nvlist(config,
3688 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
3689 
3690 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3691 				hostname = fnvlist_lookup_string(nvinfo,
3692 				    ZPOOL_CONFIG_MMP_HOSTNAME);
3693 
3694 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3695 				hostid = fnvlist_lookup_uint64(nvinfo,
3696 				    ZPOOL_CONFIG_MMP_HOSTID);
3697 
3698 			(void) printf(gettext("The pool must be exported from "
3699 			    "%s (hostid=%"PRIx64")\n"
3700 			    "\t%sbefore it can be safely imported.\n"),
3701 			    hostname, hostid, indent);
3702 			break;
3703 		case ZPOOL_STATUS_HOSTID_REQUIRED:
3704 			(void) printf(gettext("Set a unique system hostid with "
3705 			    "the zgenhostid(8) command.\n"));
3706 			break;
3707 		case ZPOOL_STATUS_CORRUPT_POOL:
3708 			(void) printf(gettext("The pool cannot be imported due "
3709 			    "to missing or damaged devices.  Ensure\n"
3710 			    "\t%sall devices are present and not in use by "
3711 			    "another subsystem.\n"), indent);
3712 			break;
3713 		default:
3714 			(void) printf(gettext("The pool cannot be imported due "
3715 			    "to damaged devices or data.\n"));
3716 		}
3717 	}
3718 
3719 	/* Print the comment attached to the pool. */
3720 	if (comment != NULL)
3721 		(void) printf(gettext("comment: %s\n"), comment);
3722 
3723 	/*
3724 	 * If the state is "closed" or "can't open", and the aux state
3725 	 * is "corrupt data":
3726 	 */
3727 	if ((vs->vs_state == VDEV_STATE_CLOSED ||
3728 	    vs->vs_state == VDEV_STATE_CANT_OPEN) &&
3729 	    vs->vs_aux == VDEV_AUX_CORRUPT_DATA) {
3730 		if (pool_state == POOL_STATE_DESTROYED)
3731 			(void) printf(gettext("\t%sThe pool was destroyed, "
3732 			    "but can be imported using the '-Df' flags.\n"),
3733 			    indent);
3734 		else if (pool_state != POOL_STATE_EXPORTED)
3735 			(void) printf(gettext("\t%sThe pool may be active on "
3736 			    "another system, but can be imported using\n"
3737 			    "\t%sthe '-f' flag.\n"), indent, indent);
3738 	}
3739 
3740 	if (msgid != NULL) {
3741 		(void) printf(gettext("%s   see: "
3742 		    "https://openzfs.github.io/openzfs-docs/msg/%s\n"),
3743 		    indent, msgid);
3744 	}
3745 
3746 	(void) printf(gettext("%sconfig:\n\n"), indent);
3747 
3748 	cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
3749 	    VDEV_NAME_TYPE_ID);
3750 	if (cb.cb_namewidth < 10)
3751 		cb.cb_namewidth = 10;
3752 
3753 	print_import_config(&cb, name, nvroot, 0);
3754 
3755 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
3756 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
3757 	print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
3758 
3759 	if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
3760 		(void) printf(gettext("\n\t%sAdditional devices are known to "
3761 		    "be part of this pool, though their\n"
3762 		    "\t%sexact configuration cannot be determined.\n"),
3763 		    indent, indent);
3764 	}
3765 	return (0);
3766 }
3767 
3768 static boolean_t
zfs_force_import_required(nvlist_t * config)3769 zfs_force_import_required(nvlist_t *config)
3770 {
3771 	uint64_t state;
3772 	uint64_t hostid = 0;
3773 	nvlist_t *nvinfo;
3774 
3775 	state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
3776 	nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3777 
3778 	/*
3779 	 * The hostid on LOAD_INFO comes from the MOS label via
3780 	 * spa_tryimport(). If its not there then we're likely talking to an
3781 	 * older kernel, so use the top one, which will be from the label
3782 	 * discovered in zpool_find_import(), or if a cachefile is in use, the
3783 	 * local hostid.
3784 	 */
3785 	if (nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_HOSTID, &hostid) != 0)
3786 		(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
3787 		    &hostid);
3788 
3789 	if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
3790 		return (B_TRUE);
3791 
3792 	if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
3793 		mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
3794 		    ZPOOL_CONFIG_MMP_STATE);
3795 
3796 		if (mmp_state != MMP_STATE_INACTIVE)
3797 			return (B_TRUE);
3798 	}
3799 
3800 	return (B_FALSE);
3801 }
3802 
3803 /*
3804  * Perform the import for the given configuration.  This passes the heavy
3805  * lifting off to zpool_import_props(), and then mounts the datasets contained
3806  * within the pool.
3807  */
3808 static int
do_import(nvlist_t * config,const char * newname,const char * mntopts,nvlist_t * props,int flags,uint_t mntthreads)3809 do_import(nvlist_t *config, const char *newname, const char *mntopts,
3810     nvlist_t *props, int flags, uint_t mntthreads)
3811 {
3812 	int ret = 0;
3813 	int ms_status = 0;
3814 	zpool_handle_t *zhp;
3815 	const char *name;
3816 	uint64_t version;
3817 
3818 	name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
3819 	version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3820 
3821 	if (!SPA_VERSION_IS_SUPPORTED(version)) {
3822 		(void) fprintf(stderr, gettext("cannot import '%s': pool "
3823 		    "is formatted using an unsupported ZFS version\n"), name);
3824 		return (1);
3825 	} else if (zfs_force_import_required(config) &&
3826 	    !(flags & ZFS_IMPORT_ANY_HOST)) {
3827 		mmp_state_t mmp_state = MMP_STATE_INACTIVE;
3828 		nvlist_t *nvinfo;
3829 
3830 		nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3831 		if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
3832 			mmp_state = fnvlist_lookup_uint64(nvinfo,
3833 			    ZPOOL_CONFIG_MMP_STATE);
3834 
3835 		if (mmp_state == MMP_STATE_ACTIVE) {
3836 			const char *hostname = "<unknown>";
3837 			uint64_t hostid = 0;
3838 
3839 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3840 				hostname = fnvlist_lookup_string(nvinfo,
3841 				    ZPOOL_CONFIG_MMP_HOSTNAME);
3842 
3843 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3844 				hostid = fnvlist_lookup_uint64(nvinfo,
3845 				    ZPOOL_CONFIG_MMP_HOSTID);
3846 
3847 			(void) fprintf(stderr, gettext("cannot import '%s': "
3848 			    "pool is imported on %s (hostid: "
3849 			    "0x%"PRIx64")\nExport the pool on the other "
3850 			    "system, then run 'zpool import'.\n"),
3851 			    name, hostname, hostid);
3852 		} else if (mmp_state == MMP_STATE_NO_HOSTID) {
3853 			(void) fprintf(stderr, gettext("Cannot import '%s': "
3854 			    "pool has the multihost property on and the\n"
3855 			    "system's hostid is not set. Set a unique hostid "
3856 			    "with the zgenhostid(8) command.\n"), name);
3857 		} else {
3858 			const char *hostname = "<unknown>";
3859 			time_t timestamp = 0;
3860 			uint64_t hostid = 0;
3861 
3862 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTNAME))
3863 				hostname = fnvlist_lookup_string(nvinfo,
3864 				    ZPOOL_CONFIG_HOSTNAME);
3865 			else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
3866 				hostname = fnvlist_lookup_string(config,
3867 				    ZPOOL_CONFIG_HOSTNAME);
3868 
3869 			if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
3870 				timestamp = fnvlist_lookup_uint64(config,
3871 				    ZPOOL_CONFIG_TIMESTAMP);
3872 
3873 			if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTID))
3874 				hostid = fnvlist_lookup_uint64(nvinfo,
3875 				    ZPOOL_CONFIG_HOSTID);
3876 			else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
3877 				hostid = fnvlist_lookup_uint64(config,
3878 				    ZPOOL_CONFIG_HOSTID);
3879 
3880 			(void) fprintf(stderr, gettext("cannot import '%s': "
3881 			    "pool was previously in use from another system.\n"
3882 			    "Last accessed by %s (hostid=%"PRIx64") at %s"
3883 			    "The pool can be imported, use 'zpool import -f' "
3884 			    "to import the pool.\n"), name, hostname,
3885 			    hostid, ctime(&timestamp));
3886 		}
3887 
3888 		if (getenv("ZFS_LOAD_INFO_DEBUG"))
3889 			dump_nvlist(nvinfo, 4);
3890 
3891 		return (1);
3892 	}
3893 
3894 	if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
3895 		return (1);
3896 
3897 	if (newname != NULL)
3898 		name = newname;
3899 
3900 	if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
3901 		return (1);
3902 
3903 	/*
3904 	 * Loading keys is best effort. We don't want to return immediately
3905 	 * if it fails but we do want to give the error to the caller.
3906 	 */
3907 	if (flags & ZFS_IMPORT_LOAD_KEYS &&
3908 	    zfs_crypto_attempt_load_keys(g_zfs, name) != 0)
3909 			ret = 1;
3910 
3911 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3912 	    !(flags & ZFS_IMPORT_ONLY)) {
3913 		ms_status = zpool_enable_datasets(zhp, mntopts, 0, mntthreads);
3914 		if (ms_status == EZFS_SHAREFAILED) {
3915 			(void) fprintf(stderr, gettext("Import was "
3916 			    "successful, but unable to share some datasets\n"));
3917 		} else if (ms_status == EZFS_MOUNTFAILED) {
3918 			(void) fprintf(stderr, gettext("Import was "
3919 			    "successful, but unable to mount some datasets\n"));
3920 		}
3921 	}
3922 
3923 	zpool_close(zhp);
3924 	return (ret);
3925 }
3926 
3927 typedef struct import_parameters {
3928 	nvlist_t *ip_config;
3929 	const char *ip_mntopts;
3930 	nvlist_t *ip_props;
3931 	int ip_flags;
3932 	uint_t ip_mntthreads;
3933 	int *ip_err;
3934 } import_parameters_t;
3935 
3936 static void
do_import_task(void * arg)3937 do_import_task(void *arg)
3938 {
3939 	import_parameters_t *ip = arg;
3940 	*ip->ip_err |= do_import(ip->ip_config, NULL, ip->ip_mntopts,
3941 	    ip->ip_props, ip->ip_flags, ip->ip_mntthreads);
3942 	free(ip);
3943 }
3944 
3945 
3946 static int
import_pools(nvlist_t * pools,nvlist_t * props,char * mntopts,int flags,char * orig_name,char * new_name,importargs_t * import)3947 import_pools(nvlist_t *pools, nvlist_t *props, char *mntopts, int flags,
3948     char *orig_name, char *new_name, importargs_t *import)
3949 {
3950 	nvlist_t *config = NULL;
3951 	nvlist_t *found_config = NULL;
3952 	uint64_t pool_state;
3953 	boolean_t pool_specified = (import->poolname != NULL ||
3954 	    import->guid != 0);
3955 	uint_t npools = 0;
3956 
3957 
3958 	taskq_t *tq = NULL;
3959 	if (import->do_all) {
3960 		tq = taskq_create("zpool_import_all",
3961 		    5 * sysconf(_SC_NPROCESSORS_ONLN), minclsyspri, 1, INT_MAX,
3962 		    TASKQ_DYNAMIC);
3963 	}
3964 
3965 	/*
3966 	 * At this point we have a list of import candidate configs. Even if
3967 	 * we were searching by pool name or guid, we still need to
3968 	 * post-process the list to deal with pool state and possible
3969 	 * duplicate names.
3970 	 */
3971 	int err = 0;
3972 	nvpair_t *elem = NULL;
3973 	boolean_t first = B_TRUE;
3974 	if (!pool_specified && import->do_all) {
3975 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL)
3976 			npools++;
3977 	}
3978 	while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3979 
3980 		verify(nvpair_value_nvlist(elem, &config) == 0);
3981 
3982 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3983 		    &pool_state) == 0);
3984 		if (!import->do_destroyed &&
3985 		    pool_state == POOL_STATE_DESTROYED)
3986 			continue;
3987 		if (import->do_destroyed &&
3988 		    pool_state != POOL_STATE_DESTROYED)
3989 			continue;
3990 
3991 		verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
3992 		    import->policy) == 0);
3993 
3994 		if (!pool_specified) {
3995 			if (first)
3996 				first = B_FALSE;
3997 			else if (!import->do_all)
3998 				(void) fputc('\n', stdout);
3999 
4000 			if (import->do_all) {
4001 				import_parameters_t *ip = safe_malloc(
4002 				    sizeof (import_parameters_t));
4003 
4004 				ip->ip_config = config;
4005 				ip->ip_mntopts = mntopts;
4006 				ip->ip_props = props;
4007 				ip->ip_flags = flags;
4008 				ip->ip_mntthreads = mount_tp_nthr / npools;
4009 				ip->ip_err = &err;
4010 
4011 				(void) taskq_dispatch(tq, do_import_task,
4012 				    (void *)ip, TQ_SLEEP);
4013 			} else {
4014 				/*
4015 				 * If we're importing from cachefile, then
4016 				 * we don't want to report errors until we
4017 				 * are in the scan phase of the import. If
4018 				 * we get an error, then we return that error
4019 				 * to invoke the scan phase.
4020 				 */
4021 				if (import->cachefile && !import->scan)
4022 					err = show_import(config, B_FALSE);
4023 				else
4024 					(void) show_import(config, B_TRUE);
4025 			}
4026 		} else if (import->poolname != NULL) {
4027 			const char *name;
4028 
4029 			/*
4030 			 * We are searching for a pool based on name.
4031 			 */
4032 			verify(nvlist_lookup_string(config,
4033 			    ZPOOL_CONFIG_POOL_NAME, &name) == 0);
4034 
4035 			if (strcmp(name, import->poolname) == 0) {
4036 				if (found_config != NULL) {
4037 					(void) fprintf(stderr, gettext(
4038 					    "cannot import '%s': more than "
4039 					    "one matching pool\n"),
4040 					    import->poolname);
4041 					(void) fprintf(stderr, gettext(
4042 					    "import by numeric ID instead\n"));
4043 					err = B_TRUE;
4044 				}
4045 				found_config = config;
4046 			}
4047 		} else {
4048 			uint64_t guid;
4049 
4050 			/*
4051 			 * Search for a pool by guid.
4052 			 */
4053 			verify(nvlist_lookup_uint64(config,
4054 			    ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
4055 
4056 			if (guid == import->guid)
4057 				found_config = config;
4058 		}
4059 	}
4060 	if (import->do_all) {
4061 		taskq_wait(tq);
4062 		taskq_destroy(tq);
4063 	}
4064 
4065 	/*
4066 	 * If we were searching for a specific pool, verify that we found a
4067 	 * pool, and then do the import.
4068 	 */
4069 	if (pool_specified && err == 0) {
4070 		if (found_config == NULL) {
4071 			(void) fprintf(stderr, gettext("cannot import '%s': "
4072 			    "no such pool available\n"), orig_name);
4073 			err = B_TRUE;
4074 		} else {
4075 			err |= do_import(found_config, new_name,
4076 			    mntopts, props, flags, mount_tp_nthr);
4077 		}
4078 	}
4079 
4080 	/*
4081 	 * If we were just looking for pools, report an error if none were
4082 	 * found.
4083 	 */
4084 	if (!pool_specified && first)
4085 		(void) fprintf(stderr,
4086 		    gettext("no pools available to import\n"));
4087 	return (err);
4088 }
4089 
4090 typedef struct target_exists_args {
4091 	const char	*poolname;
4092 	uint64_t	poolguid;
4093 } target_exists_args_t;
4094 
4095 static int
name_or_guid_exists(zpool_handle_t * zhp,void * data)4096 name_or_guid_exists(zpool_handle_t *zhp, void *data)
4097 {
4098 	target_exists_args_t *args = data;
4099 	nvlist_t *config = zpool_get_config(zhp, NULL);
4100 	int found = 0;
4101 
4102 	if (config == NULL)
4103 		return (0);
4104 
4105 	if (args->poolname != NULL) {
4106 		const char *pool_name;
4107 
4108 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4109 		    &pool_name) == 0);
4110 		if (strcmp(pool_name, args->poolname) == 0)
4111 			found = 1;
4112 	} else {
4113 		uint64_t pool_guid;
4114 
4115 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4116 		    &pool_guid) == 0);
4117 		if (pool_guid == args->poolguid)
4118 			found = 1;
4119 	}
4120 	zpool_close(zhp);
4121 
4122 	return (found);
4123 }
4124 /*
4125  * zpool checkpoint <pool>
4126  *       checkpoint --discard <pool>
4127  *
4128  *       -d         Discard the checkpoint from a checkpointed
4129  *       --discard  pool.
4130  *
4131  *       -w         Wait for discarding a checkpoint to complete.
4132  *       --wait
4133  *
4134  * Checkpoints the specified pool, by taking a "snapshot" of its
4135  * current state. A pool can only have one checkpoint at a time.
4136  */
4137 int
zpool_do_checkpoint(int argc,char ** argv)4138 zpool_do_checkpoint(int argc, char **argv)
4139 {
4140 	boolean_t discard, wait;
4141 	char *pool;
4142 	zpool_handle_t *zhp;
4143 	int c, err;
4144 
4145 	struct option long_options[] = {
4146 		{"discard", no_argument, NULL, 'd'},
4147 		{"wait", no_argument, NULL, 'w'},
4148 		{0, 0, 0, 0}
4149 	};
4150 
4151 	discard = B_FALSE;
4152 	wait = B_FALSE;
4153 	while ((c = getopt_long(argc, argv, ":dw", long_options, NULL)) != -1) {
4154 		switch (c) {
4155 		case 'd':
4156 			discard = B_TRUE;
4157 			break;
4158 		case 'w':
4159 			wait = B_TRUE;
4160 			break;
4161 		case '?':
4162 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4163 			    optopt);
4164 			usage(B_FALSE);
4165 		}
4166 	}
4167 
4168 	if (wait && !discard) {
4169 		(void) fprintf(stderr, gettext("--wait only valid when "
4170 		    "--discard also specified\n"));
4171 		usage(B_FALSE);
4172 	}
4173 
4174 	argc -= optind;
4175 	argv += optind;
4176 
4177 	if (argc < 1) {
4178 		(void) fprintf(stderr, gettext("missing pool argument\n"));
4179 		usage(B_FALSE);
4180 	}
4181 
4182 	if (argc > 1) {
4183 		(void) fprintf(stderr, gettext("too many arguments\n"));
4184 		usage(B_FALSE);
4185 	}
4186 
4187 	pool = argv[0];
4188 
4189 	if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
4190 		/* As a special case, check for use of '/' in the name */
4191 		if (strchr(pool, '/') != NULL)
4192 			(void) fprintf(stderr, gettext("'zpool checkpoint' "
4193 			    "doesn't work on datasets. To save the state "
4194 			    "of a dataset from a specific point in time "
4195 			    "please use 'zfs snapshot'\n"));
4196 		return (1);
4197 	}
4198 
4199 	if (discard) {
4200 		err = (zpool_discard_checkpoint(zhp) != 0);
4201 		if (err == 0 && wait)
4202 			err = zpool_wait(zhp, ZPOOL_WAIT_CKPT_DISCARD);
4203 	} else {
4204 		err = (zpool_checkpoint(zhp) != 0);
4205 	}
4206 
4207 	zpool_close(zhp);
4208 
4209 	return (err);
4210 }
4211 
4212 #define	CHECKPOINT_OPT	1024
4213 
4214 /*
4215  * zpool prefetch [-t <type>] <pool>
4216  *
4217  * Prefetchs a particular type of data in the specified pool.
4218  */
4219 int
zpool_do_prefetch(int argc,char ** argv)4220 zpool_do_prefetch(int argc, char **argv)
4221 {
4222 	int c;
4223 	char *poolname;
4224 	char *typestr = NULL;
4225 	zpool_prefetch_type_t type;
4226 	zpool_handle_t *zhp;
4227 	int err = 0;
4228 
4229 	while ((c = getopt(argc, argv, "t:")) != -1) {
4230 		switch (c) {
4231 		case 't':
4232 			typestr = optarg;
4233 			break;
4234 		case ':':
4235 			(void) fprintf(stderr, gettext("missing argument for "
4236 			    "'%c' option\n"), optopt);
4237 			usage(B_FALSE);
4238 			break;
4239 		case '?':
4240 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4241 			    optopt);
4242 			usage(B_FALSE);
4243 		}
4244 	}
4245 	argc -= optind;
4246 	argv += optind;
4247 
4248 	if (argc < 1) {
4249 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
4250 		usage(B_FALSE);
4251 	}
4252 
4253 	if (argc > 1) {
4254 		(void) fprintf(stderr, gettext("too many arguments\n"));
4255 		usage(B_FALSE);
4256 	}
4257 
4258 	poolname = argv[0];
4259 
4260 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
4261 		return (1);
4262 
4263 	if (typestr == NULL) {
4264 		/* Prefetch all types */
4265 		err = zpool_prefetch(zhp, ZPOOL_PREFETCH_DDT);
4266 		if (err == 0)
4267 			err = zpool_prefetch(zhp, ZPOOL_PREFETCH_BRT);
4268 	} else {
4269 		if (strcmp(typestr, "ddt") == 0) {
4270 			type = ZPOOL_PREFETCH_DDT;
4271 		} else if (strcmp(typestr, "brt") == 0) {
4272 			type = ZPOOL_PREFETCH_BRT;
4273 		} else {
4274 			(void) fprintf(stderr,
4275 			    gettext("unsupported prefetch type\n"));
4276 			zpool_close(zhp);
4277 			usage(B_FALSE);
4278 		}
4279 		err = zpool_prefetch(zhp, type);
4280 	}
4281 
4282 	zpool_close(zhp);
4283 
4284 	return (err);
4285 }
4286 
4287 /*
4288  * zpool import [-d dir] [-D]
4289  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4290  *              [-d dir | -c cachefile | -s] [-f] -a
4291  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4292  *              [-d dir | -c cachefile | -s] [-f] [-n] [-F] <pool | id>
4293  *              [newpool]
4294  *
4295  *	-c	Read pool information from a cachefile instead of searching
4296  *		devices. If importing from a cachefile config fails, then
4297  *		fallback to searching for devices only in the directories that
4298  *		exist in the cachefile.
4299  *
4300  *	-d	Scan in a specific directory, other than /dev/.  More than
4301  *		one directory can be specified using multiple '-d' options.
4302  *
4303  *	-D	Scan for previously destroyed pools or import all or only
4304  *		specified destroyed pools.
4305  *
4306  *	-R	Temporarily import the pool, with all mountpoints relative to
4307  *		the given root.  The pool will remain exported when the machine
4308  *		is rebooted.
4309  *
4310  *	-V	Import even in the presence of faulted vdevs.  This is an
4311  *		intentionally undocumented option for testing purposes, and
4312  *		treats the pool configuration as complete, leaving any bad
4313  *		vdevs in the FAULTED state. In other words, it does verbatim
4314  *		import.
4315  *
4316  *	-f	Force import, even if it appears that the pool is active.
4317  *
4318  *	-F	Attempt rewind if necessary.
4319  *
4320  *	-n	See if rewind would work, but don't actually rewind.
4321  *
4322  *	-N	Import the pool but don't mount datasets.
4323  *
4324  *	-T	Specify a starting txg to use for import. This option is
4325  *		intentionally undocumented option for testing purposes.
4326  *
4327  *	-a	Import all pools found.
4328  *
4329  *	-l	Load encryption keys while importing.
4330  *
4331  *	-o	Set property=value and/or temporary mount options (without '=').
4332  *
4333  *	-s	Scan using the default search path, the libblkid cache will
4334  *		not be consulted.
4335  *
4336  *	--rewind-to-checkpoint
4337  *		Import the pool and revert back to the checkpoint.
4338  *
4339  * The import command scans for pools to import, and import pools based on pool
4340  * name and GUID.  The pool can also be renamed as part of the import process.
4341  */
4342 int
zpool_do_import(int argc,char ** argv)4343 zpool_do_import(int argc, char **argv)
4344 {
4345 	char **searchdirs = NULL;
4346 	char *env, *envdup = NULL;
4347 	int nsearch = 0;
4348 	int c;
4349 	int err = 0;
4350 	nvlist_t *pools = NULL;
4351 	boolean_t do_all = B_FALSE;
4352 	boolean_t do_destroyed = B_FALSE;
4353 	char *mntopts = NULL;
4354 	uint64_t searchguid = 0;
4355 	char *searchname = NULL;
4356 	char *propval;
4357 	nvlist_t *policy = NULL;
4358 	nvlist_t *props = NULL;
4359 	int flags = ZFS_IMPORT_NORMAL;
4360 	uint32_t rewind_policy = ZPOOL_NO_REWIND;
4361 	boolean_t dryrun = B_FALSE;
4362 	boolean_t do_rewind = B_FALSE;
4363 	boolean_t xtreme_rewind = B_FALSE;
4364 	boolean_t do_scan = B_FALSE;
4365 	boolean_t pool_exists = B_FALSE;
4366 	uint64_t txg = -1ULL;
4367 	char *cachefile = NULL;
4368 	importargs_t idata = { 0 };
4369 	char *endptr;
4370 
4371 	struct option long_options[] = {
4372 		{"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
4373 		{0, 0, 0, 0}
4374 	};
4375 
4376 	/* check options */
4377 	while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmnNo:R:stT:VX",
4378 	    long_options, NULL)) != -1) {
4379 		switch (c) {
4380 		case 'a':
4381 			do_all = B_TRUE;
4382 			break;
4383 		case 'c':
4384 			cachefile = optarg;
4385 			break;
4386 		case 'd':
4387 			searchdirs = safe_realloc(searchdirs,
4388 			    (nsearch + 1) * sizeof (char *));
4389 			searchdirs[nsearch++] = optarg;
4390 			break;
4391 		case 'D':
4392 			do_destroyed = B_TRUE;
4393 			break;
4394 		case 'f':
4395 			flags |= ZFS_IMPORT_ANY_HOST;
4396 			break;
4397 		case 'F':
4398 			do_rewind = B_TRUE;
4399 			break;
4400 		case 'l':
4401 			flags |= ZFS_IMPORT_LOAD_KEYS;
4402 			break;
4403 		case 'm':
4404 			flags |= ZFS_IMPORT_MISSING_LOG;
4405 			break;
4406 		case 'n':
4407 			dryrun = B_TRUE;
4408 			break;
4409 		case 'N':
4410 			flags |= ZFS_IMPORT_ONLY;
4411 			break;
4412 		case 'o':
4413 			if ((propval = strchr(optarg, '=')) != NULL) {
4414 				*propval = '\0';
4415 				propval++;
4416 				if (add_prop_list(optarg, propval,
4417 				    &props, B_TRUE))
4418 					goto error;
4419 			} else {
4420 				mntopts = optarg;
4421 			}
4422 			break;
4423 		case 'R':
4424 			if (add_prop_list(zpool_prop_to_name(
4425 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
4426 				goto error;
4427 			if (add_prop_list_default(zpool_prop_to_name(
4428 			    ZPOOL_PROP_CACHEFILE), "none", &props))
4429 				goto error;
4430 			break;
4431 		case 's':
4432 			do_scan = B_TRUE;
4433 			break;
4434 		case 't':
4435 			flags |= ZFS_IMPORT_TEMP_NAME;
4436 			if (add_prop_list_default(zpool_prop_to_name(
4437 			    ZPOOL_PROP_CACHEFILE), "none", &props))
4438 				goto error;
4439 			break;
4440 
4441 		case 'T':
4442 			errno = 0;
4443 			txg = strtoull(optarg, &endptr, 0);
4444 			if (errno != 0 || *endptr != '\0') {
4445 				(void) fprintf(stderr,
4446 				    gettext("invalid txg value\n"));
4447 				usage(B_FALSE);
4448 			}
4449 			rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
4450 			break;
4451 		case 'V':
4452 			flags |= ZFS_IMPORT_VERBATIM;
4453 			break;
4454 		case 'X':
4455 			xtreme_rewind = B_TRUE;
4456 			break;
4457 		case CHECKPOINT_OPT:
4458 			flags |= ZFS_IMPORT_CHECKPOINT;
4459 			break;
4460 		case ':':
4461 			(void) fprintf(stderr, gettext("missing argument for "
4462 			    "'%c' option\n"), optopt);
4463 			usage(B_FALSE);
4464 			break;
4465 		case '?':
4466 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4467 			    optopt);
4468 			usage(B_FALSE);
4469 		}
4470 	}
4471 
4472 	argc -= optind;
4473 	argv += optind;
4474 
4475 	if (cachefile && nsearch != 0) {
4476 		(void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
4477 		usage(B_FALSE);
4478 	}
4479 
4480 	if (cachefile && do_scan) {
4481 		(void) fprintf(stderr, gettext("-c is incompatible with -s\n"));
4482 		usage(B_FALSE);
4483 	}
4484 
4485 	if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
4486 		(void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
4487 		usage(B_FALSE);
4488 	}
4489 
4490 	if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
4491 		(void) fprintf(stderr, gettext("-l is only meaningful during "
4492 		    "an import\n"));
4493 		usage(B_FALSE);
4494 	}
4495 
4496 	if ((dryrun || xtreme_rewind) && !do_rewind) {
4497 		(void) fprintf(stderr,
4498 		    gettext("-n or -X only meaningful with -F\n"));
4499 		usage(B_FALSE);
4500 	}
4501 	if (dryrun)
4502 		rewind_policy = ZPOOL_TRY_REWIND;
4503 	else if (do_rewind)
4504 		rewind_policy = ZPOOL_DO_REWIND;
4505 	if (xtreme_rewind)
4506 		rewind_policy |= ZPOOL_EXTREME_REWIND;
4507 
4508 	/* In the future, we can capture further policy and include it here */
4509 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
4510 	    nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
4511 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
4512 	    rewind_policy) != 0)
4513 		goto error;
4514 
4515 	/* check argument count */
4516 	if (do_all) {
4517 		if (argc != 0) {
4518 			(void) fprintf(stderr, gettext("too many arguments\n"));
4519 			usage(B_FALSE);
4520 		}
4521 	} else {
4522 		if (argc > 2) {
4523 			(void) fprintf(stderr, gettext("too many arguments\n"));
4524 			usage(B_FALSE);
4525 		}
4526 	}
4527 
4528 	/*
4529 	 * Check for the effective uid.  We do this explicitly here because
4530 	 * otherwise any attempt to discover pools will silently fail.
4531 	 */
4532 	if (argc == 0 && geteuid() != 0) {
4533 		(void) fprintf(stderr, gettext("cannot "
4534 		    "discover pools: permission denied\n"));
4535 
4536 		free(searchdirs);
4537 		nvlist_free(props);
4538 		nvlist_free(policy);
4539 		return (1);
4540 	}
4541 
4542 	/*
4543 	 * Depending on the arguments given, we do one of the following:
4544 	 *
4545 	 *	<none>	Iterate through all pools and display information about
4546 	 *		each one.
4547 	 *
4548 	 *	-a	Iterate through all pools and try to import each one.
4549 	 *
4550 	 *	<id>	Find the pool that corresponds to the given GUID/pool
4551 	 *		name and import that one.
4552 	 *
4553 	 *	-D	Above options applies only to destroyed pools.
4554 	 */
4555 	if (argc != 0) {
4556 		char *endptr;
4557 
4558 		errno = 0;
4559 		searchguid = strtoull(argv[0], &endptr, 10);
4560 		if (errno != 0 || *endptr != '\0') {
4561 			searchname = argv[0];
4562 			searchguid = 0;
4563 		}
4564 
4565 		/*
4566 		 * User specified a name or guid.  Ensure it's unique.
4567 		 */
4568 		target_exists_args_t search = {searchname, searchguid};
4569 		pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
4570 	}
4571 
4572 	/*
4573 	 * Check the environment for the preferred search path.
4574 	 */
4575 	if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
4576 		char *dir, *tmp = NULL;
4577 
4578 		envdup = strdup(env);
4579 
4580 		for (dir = strtok_r(envdup, ":", &tmp);
4581 		    dir != NULL;
4582 		    dir = strtok_r(NULL, ":", &tmp)) {
4583 			searchdirs = safe_realloc(searchdirs,
4584 			    (nsearch + 1) * sizeof (char *));
4585 			searchdirs[nsearch++] = dir;
4586 		}
4587 	}
4588 
4589 	idata.path = searchdirs;
4590 	idata.paths = nsearch;
4591 	idata.poolname = searchname;
4592 	idata.guid = searchguid;
4593 	idata.cachefile = cachefile;
4594 	idata.scan = do_scan;
4595 	idata.policy = policy;
4596 	idata.do_destroyed = do_destroyed;
4597 	idata.do_all = do_all;
4598 
4599 	libpc_handle_t lpch = {
4600 		.lpc_lib_handle = g_zfs,
4601 		.lpc_ops = &libzfs_config_ops,
4602 		.lpc_printerr = B_TRUE
4603 	};
4604 	pools = zpool_search_import(&lpch, &idata);
4605 
4606 	if (pools != NULL && pool_exists &&
4607 	    (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
4608 		(void) fprintf(stderr, gettext("cannot import '%s': "
4609 		    "a pool with that name already exists\n"),
4610 		    argv[0]);
4611 		(void) fprintf(stderr, gettext("use the form '%s "
4612 		    "<pool | id> <newpool>' to give it a new name\n"),
4613 		    "zpool import");
4614 		err = 1;
4615 	} else if (pools == NULL && pool_exists) {
4616 		(void) fprintf(stderr, gettext("cannot import '%s': "
4617 		    "a pool with that name is already created/imported,\n"),
4618 		    argv[0]);
4619 		(void) fprintf(stderr, gettext("and no additional pools "
4620 		    "with that name were found\n"));
4621 		err = 1;
4622 	} else if (pools == NULL) {
4623 		if (argc != 0) {
4624 			(void) fprintf(stderr, gettext("cannot import '%s': "
4625 			    "no such pool available\n"), argv[0]);
4626 		}
4627 		err = 1;
4628 	}
4629 
4630 	if (err == 1) {
4631 		free(searchdirs);
4632 		free(envdup);
4633 		nvlist_free(policy);
4634 		nvlist_free(pools);
4635 		nvlist_free(props);
4636 		return (1);
4637 	}
4638 
4639 	err = import_pools(pools, props, mntopts, flags,
4640 	    argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL, &idata);
4641 
4642 	/*
4643 	 * If we're using the cachefile and we failed to import, then
4644 	 * fallback to scanning the directory for pools that match
4645 	 * those in the cachefile.
4646 	 */
4647 	if (err != 0 && cachefile != NULL) {
4648 		(void) printf(gettext("cachefile import failed, retrying\n"));
4649 
4650 		/*
4651 		 * We use the scan flag to gather the directories that exist
4652 		 * in the cachefile. If we need to fallback to searching for
4653 		 * the pool config, we will only search devices in these
4654 		 * directories.
4655 		 */
4656 		idata.scan = B_TRUE;
4657 		nvlist_free(pools);
4658 		pools = zpool_search_import(&lpch, &idata);
4659 
4660 		err = import_pools(pools, props, mntopts, flags,
4661 		    argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL,
4662 		    &idata);
4663 	}
4664 
4665 error:
4666 	nvlist_free(props);
4667 	nvlist_free(pools);
4668 	nvlist_free(policy);
4669 	free(searchdirs);
4670 	free(envdup);
4671 
4672 	return (err ? 1 : 0);
4673 }
4674 
4675 /*
4676  * zpool sync [-f] [pool] ...
4677  *
4678  * -f (undocumented) force uberblock (and config including zpool cache file)
4679  *    update.
4680  *
4681  * Sync the specified pool(s).
4682  * Without arguments "zpool sync" will sync all pools.
4683  * This command initiates TXG sync(s) and will return after the TXG(s) commit.
4684  *
4685  */
4686 static int
zpool_do_sync(int argc,char ** argv)4687 zpool_do_sync(int argc, char **argv)
4688 {
4689 	int ret;
4690 	boolean_t force = B_FALSE;
4691 
4692 	/* check options */
4693 	while ((ret  = getopt(argc, argv, "f")) != -1) {
4694 		switch (ret) {
4695 		case 'f':
4696 			force = B_TRUE;
4697 			break;
4698 		case '?':
4699 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4700 			    optopt);
4701 			usage(B_FALSE);
4702 		}
4703 	}
4704 
4705 	argc -= optind;
4706 	argv += optind;
4707 
4708 	/* if argc == 0 we will execute zpool_sync_one on all pools */
4709 	ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
4710 	    B_FALSE, zpool_sync_one, &force);
4711 
4712 	return (ret);
4713 }
4714 
4715 typedef struct iostat_cbdata {
4716 	uint64_t cb_flags;
4717 	int cb_namewidth;
4718 	int cb_iteration;
4719 	boolean_t cb_verbose;
4720 	boolean_t cb_literal;
4721 	boolean_t cb_scripted;
4722 	zpool_list_t *cb_list;
4723 	vdev_cmd_data_list_t *vcdl;
4724 	vdev_cbdata_t cb_vdevs;
4725 } iostat_cbdata_t;
4726 
4727 /*  iostat labels */
4728 typedef struct name_and_columns {
4729 	const char *name;	/* Column name */
4730 	unsigned int columns;	/* Center name to this number of columns */
4731 } name_and_columns_t;
4732 
4733 #define	IOSTAT_MAX_LABELS	15	/* Max number of labels on one line */
4734 
4735 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
4736 {
4737 	[IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
4738 	    {NULL}},
4739 	[IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4740 	    {"asyncq_wait", 2}, {"scrub", 1}, {"trim", 1}, {"rebuild", 1},
4741 	    {NULL}},
4742 	[IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
4743 	    {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
4744 	    {"trimq_write", 2}, {"rebuildq_write", 2}, {NULL}},
4745 	[IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4746 	    {"asyncq_wait", 2}, {NULL}},
4747 	[IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
4748 	    {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
4749 	    {"trim", 2}, {"rebuild", 2}, {NULL}},
4750 };
4751 
4752 /* Shorthand - if "columns" field not set, default to 1 column */
4753 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
4754 {
4755 	[IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
4756 	    {"write"}, {NULL}},
4757 	[IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4758 	    {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {"wait"},
4759 	    {NULL}},
4760 	[IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
4761 	    {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
4762 	    {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
4763 	[IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4764 	    {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {"rebuild"},
4765 	    {NULL}},
4766 	[IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4767 	    {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4768 	    {"ind"}, {"agg"}, {NULL}},
4769 };
4770 
4771 static const char *histo_to_title[] = {
4772 	[IOS_L_HISTO] = "latency",
4773 	[IOS_RQ_HISTO] = "req_size",
4774 };
4775 
4776 /*
4777  * Return the number of labels in a null-terminated name_and_columns_t
4778  * array.
4779  *
4780  */
4781 static unsigned int
label_array_len(const name_and_columns_t * labels)4782 label_array_len(const name_and_columns_t *labels)
4783 {
4784 	int i = 0;
4785 
4786 	while (labels[i].name)
4787 		i++;
4788 
4789 	return (i);
4790 }
4791 
4792 /*
4793  * Return the number of strings in a null-terminated string array.
4794  * For example:
4795  *
4796  *     const char foo[] = {"bar", "baz", NULL}
4797  *
4798  * returns 2
4799  */
4800 static uint64_t
str_array_len(const char * array[])4801 str_array_len(const char *array[])
4802 {
4803 	uint64_t i = 0;
4804 	while (array[i])
4805 		i++;
4806 
4807 	return (i);
4808 }
4809 
4810 
4811 /*
4812  * Return a default column width for default/latency/queue columns. This does
4813  * not include histograms, which have their columns autosized.
4814  */
4815 static unsigned int
default_column_width(iostat_cbdata_t * cb,enum iostat_type type)4816 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
4817 {
4818 	unsigned long column_width = 5; /* Normal niceprint */
4819 	static unsigned long widths[] = {
4820 		/*
4821 		 * Choose some sane default column sizes for printing the
4822 		 * raw numbers.
4823 		 */
4824 		[IOS_DEFAULT] = 15, /* 1PB capacity */
4825 		[IOS_LATENCY] = 10, /* 1B ns = 10sec */
4826 		[IOS_QUEUES] = 6,   /* 1M queue entries */
4827 		[IOS_L_HISTO] = 10, /* 1B ns = 10sec */
4828 		[IOS_RQ_HISTO] = 6, /* 1M queue entries */
4829 	};
4830 
4831 	if (cb->cb_literal)
4832 		column_width = widths[type];
4833 
4834 	return (column_width);
4835 }
4836 
4837 /*
4838  * Print the column labels, i.e:
4839  *
4840  *   capacity     operations     bandwidth
4841  * alloc   free   read  write   read  write  ...
4842  *
4843  * If force_column_width is set, use it for the column width.  If not set, use
4844  * the default column width.
4845  */
4846 static void
print_iostat_labels(iostat_cbdata_t * cb,unsigned int force_column_width,const name_and_columns_t labels[][IOSTAT_MAX_LABELS])4847 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
4848     const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
4849 {
4850 	int i, idx, s;
4851 	int text_start, rw_column_width, spaces_to_end;
4852 	uint64_t flags = cb->cb_flags;
4853 	uint64_t f;
4854 	unsigned int column_width = force_column_width;
4855 
4856 	/* For each bit set in flags */
4857 	for (f = flags; f; f &= ~(1ULL << idx)) {
4858 		idx = lowbit64(f) - 1;
4859 		if (!force_column_width)
4860 			column_width = default_column_width(cb, idx);
4861 		/* Print our top labels centered over "read  write" label. */
4862 		for (i = 0; i < label_array_len(labels[idx]); i++) {
4863 			const char *name = labels[idx][i].name;
4864 			/*
4865 			 * We treat labels[][].columns == 0 as shorthand
4866 			 * for one column.  It makes writing out the label
4867 			 * tables more concise.
4868 			 */
4869 			unsigned int columns = MAX(1, labels[idx][i].columns);
4870 			unsigned int slen = strlen(name);
4871 
4872 			rw_column_width = (column_width * columns) +
4873 			    (2 * (columns - 1));
4874 
4875 			text_start = (int)((rw_column_width) / columns -
4876 			    slen / columns);
4877 			if (text_start < 0)
4878 				text_start = 0;
4879 
4880 			printf("  ");	/* Two spaces between columns */
4881 
4882 			/* Space from beginning of column to label */
4883 			for (s = 0; s < text_start; s++)
4884 				printf(" ");
4885 
4886 			printf("%s", name);
4887 
4888 			/* Print space after label to end of column */
4889 			spaces_to_end = rw_column_width - text_start - slen;
4890 			if (spaces_to_end < 0)
4891 				spaces_to_end = 0;
4892 
4893 			for (s = 0; s < spaces_to_end; s++)
4894 				printf(" ");
4895 		}
4896 	}
4897 }
4898 
4899 
4900 /*
4901  * print_cmd_columns - Print custom column titles from -c
4902  *
4903  * If the user specified the "zpool status|iostat -c" then print their custom
4904  * column titles in the header.  For example, print_cmd_columns() would print
4905  * the "  col1  col2" part of this:
4906  *
4907  * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
4908  * ...
4909  *	      capacity     operations     bandwidth
4910  * pool        alloc   free   read  write   read  write  col1  col2
4911  * ----------  -----  -----  -----  -----  -----  -----  ----  ----
4912  * mypool       269K  1008M      0      0    107    946
4913  *   mirror     269K  1008M      0      0    107    946
4914  *     sdb         -      -      0      0    102    473  val1  val2
4915  *     sdc         -      -      0      0      5    473  val1  val2
4916  * ----------  -----  -----  -----  -----  -----  -----  ----  ----
4917  */
4918 static void
print_cmd_columns(vdev_cmd_data_list_t * vcdl,int use_dashes)4919 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
4920 {
4921 	int i, j;
4922 	vdev_cmd_data_t *data = &vcdl->data[0];
4923 
4924 	if (vcdl->count == 0 || data == NULL)
4925 		return;
4926 
4927 	/*
4928 	 * Each vdev cmd should have the same column names unless the user did
4929 	 * something weird with their cmd.  Just take the column names from the
4930 	 * first vdev and assume it works for all of them.
4931 	 */
4932 	for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
4933 		printf("  ");
4934 		if (use_dashes) {
4935 			for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
4936 				printf("-");
4937 		} else {
4938 			(void) printf_color(ANSI_BOLD, "%*s",
4939 			    vcdl->uniq_cols_width[i],
4940 			    vcdl->uniq_cols[i]);
4941 		}
4942 	}
4943 }
4944 
4945 
4946 /*
4947  * Utility function to print out a line of dashes like:
4948  *
4949  * 	--------------------------------  -----  -----  -----  -----  -----
4950  *
4951  * ...or a dashed named-row line like:
4952  *
4953  * 	logs                                  -      -      -      -      -
4954  *
4955  * @cb:				iostat data
4956  *
4957  * @force_column_width		If non-zero, use the value as the column width.
4958  * 				Otherwise use the default column widths.
4959  *
4960  * @name:			Print a dashed named-row line starting
4961  * 				with @name.  Otherwise, print a regular
4962  * 				dashed line.
4963  */
4964 static void
print_iostat_dashes(iostat_cbdata_t * cb,unsigned int force_column_width,const char * name)4965 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
4966     const char *name)
4967 {
4968 	int i;
4969 	unsigned int namewidth;
4970 	uint64_t flags = cb->cb_flags;
4971 	uint64_t f;
4972 	int idx;
4973 	const name_and_columns_t *labels;
4974 	const char *title;
4975 
4976 
4977 	if (cb->cb_flags & IOS_ANYHISTO_M) {
4978 		title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4979 	} else if (cb->cb_vdevs.cb_names_count) {
4980 		title = "vdev";
4981 	} else  {
4982 		title = "pool";
4983 	}
4984 
4985 	namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4986 	    name ? strlen(name) : 0);
4987 
4988 
4989 	if (name) {
4990 		printf("%-*s", namewidth, name);
4991 	} else {
4992 		for (i = 0; i < namewidth; i++)
4993 			(void) printf("-");
4994 	}
4995 
4996 	/* For each bit in flags */
4997 	for (f = flags; f; f &= ~(1ULL << idx)) {
4998 		unsigned int column_width;
4999 		idx = lowbit64(f) - 1;
5000 		if (force_column_width)
5001 			column_width = force_column_width;
5002 		else
5003 			column_width = default_column_width(cb, idx);
5004 
5005 		labels = iostat_bottom_labels[idx];
5006 		for (i = 0; i < label_array_len(labels); i++) {
5007 			if (name)
5008 				printf("  %*s-", column_width - 1, " ");
5009 			else
5010 				printf("  %.*s", column_width,
5011 				    "--------------------");
5012 		}
5013 	}
5014 }
5015 
5016 
5017 static void
print_iostat_separator_impl(iostat_cbdata_t * cb,unsigned int force_column_width)5018 print_iostat_separator_impl(iostat_cbdata_t *cb,
5019     unsigned int force_column_width)
5020 {
5021 	print_iostat_dashes(cb, force_column_width, NULL);
5022 }
5023 
5024 static void
print_iostat_separator(iostat_cbdata_t * cb)5025 print_iostat_separator(iostat_cbdata_t *cb)
5026 {
5027 	print_iostat_separator_impl(cb, 0);
5028 }
5029 
5030 static void
print_iostat_header_impl(iostat_cbdata_t * cb,unsigned int force_column_width,const char * histo_vdev_name)5031 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
5032     const char *histo_vdev_name)
5033 {
5034 	unsigned int namewidth;
5035 	const char *title;
5036 
5037 	color_start(ANSI_BOLD);
5038 
5039 	if (cb->cb_flags & IOS_ANYHISTO_M) {
5040 		title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
5041 	} else if (cb->cb_vdevs.cb_names_count) {
5042 		title = "vdev";
5043 	} else  {
5044 		title = "pool";
5045 	}
5046 
5047 	namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
5048 	    histo_vdev_name ? strlen(histo_vdev_name) : 0);
5049 
5050 	if (histo_vdev_name)
5051 		printf("%-*s", namewidth, histo_vdev_name);
5052 	else
5053 		printf("%*s", namewidth, "");
5054 
5055 
5056 	print_iostat_labels(cb, force_column_width, iostat_top_labels);
5057 	printf("\n");
5058 
5059 	printf("%-*s", namewidth, title);
5060 
5061 	print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
5062 	if (cb->vcdl != NULL)
5063 		print_cmd_columns(cb->vcdl, 0);
5064 
5065 	printf("\n");
5066 
5067 	print_iostat_separator_impl(cb, force_column_width);
5068 
5069 	if (cb->vcdl != NULL)
5070 		print_cmd_columns(cb->vcdl, 1);
5071 
5072 	color_end();
5073 
5074 	printf("\n");
5075 }
5076 
5077 static void
print_iostat_header(iostat_cbdata_t * cb)5078 print_iostat_header(iostat_cbdata_t *cb)
5079 {
5080 	print_iostat_header_impl(cb, 0, NULL);
5081 }
5082 
5083 /*
5084  * Prints a size string (i.e. 120M) with the suffix ("M") colored
5085  * by order of magnitude. Uses column_size to add padding.
5086  */
5087 static void
print_stat_color(const char * statbuf,unsigned int column_size)5088 print_stat_color(const char *statbuf, unsigned int column_size)
5089 {
5090 	(void) fputs("  ", stdout);
5091 	size_t len = strlen(statbuf);
5092 	while (len < column_size) {
5093 		(void) fputc(' ', stdout);
5094 		column_size--;
5095 	}
5096 	if (*statbuf == '0') {
5097 		color_start(ANSI_GRAY);
5098 		(void) fputc('0', stdout);
5099 	} else {
5100 		for (; *statbuf; statbuf++) {
5101 			if (*statbuf == 'K') color_start(ANSI_GREEN);
5102 			else if (*statbuf == 'M') color_start(ANSI_YELLOW);
5103 			else if (*statbuf == 'G') color_start(ANSI_RED);
5104 			else if (*statbuf == 'T') color_start(ANSI_BOLD_BLUE);
5105 			else if (*statbuf == 'P') color_start(ANSI_MAGENTA);
5106 			else if (*statbuf == 'E') color_start(ANSI_CYAN);
5107 			(void) fputc(*statbuf, stdout);
5108 			if (--column_size <= 0)
5109 				break;
5110 		}
5111 	}
5112 	color_end();
5113 }
5114 
5115 /*
5116  * Display a single statistic.
5117  */
5118 static void
print_one_stat(uint64_t value,enum zfs_nicenum_format format,unsigned int column_size,boolean_t scripted)5119 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
5120     unsigned int column_size, boolean_t scripted)
5121 {
5122 	char buf[64];
5123 
5124 	zfs_nicenum_format(value, buf, sizeof (buf), format);
5125 
5126 	if (scripted)
5127 		printf("\t%s", buf);
5128 	else
5129 		print_stat_color(buf, column_size);
5130 }
5131 
5132 /*
5133  * Calculate the default vdev stats
5134  *
5135  * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
5136  * stats into calcvs.
5137  */
5138 static void
calc_default_iostats(vdev_stat_t * oldvs,vdev_stat_t * newvs,vdev_stat_t * calcvs)5139 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
5140     vdev_stat_t *calcvs)
5141 {
5142 	int i;
5143 
5144 	memcpy(calcvs, newvs, sizeof (*calcvs));
5145 	for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
5146 		calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
5147 
5148 	for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
5149 		calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
5150 }
5151 
5152 /*
5153  * Internal representation of the extended iostats data.
5154  *
5155  * The extended iostat stats are exported in nvlists as either uint64_t arrays
5156  * or single uint64_t's.  We make both look like arrays to make them easier
5157  * to process.  In order to make single uint64_t's look like arrays, we set
5158  * __data to the stat data, and then set *data = &__data with count = 1.  Then,
5159  * we can just use *data and count.
5160  */
5161 struct stat_array {
5162 	uint64_t *data;
5163 	uint_t count;	/* Number of entries in data[] */
5164 	uint64_t __data; /* Only used when data is a single uint64_t */
5165 };
5166 
5167 static uint64_t
stat_histo_max(struct stat_array * nva,unsigned int len)5168 stat_histo_max(struct stat_array *nva, unsigned int len)
5169 {
5170 	uint64_t max = 0;
5171 	int i;
5172 	for (i = 0; i < len; i++)
5173 		max = MAX(max, array64_max(nva[i].data, nva[i].count));
5174 
5175 	return (max);
5176 }
5177 
5178 /*
5179  * Helper function to lookup a uint64_t array or uint64_t value and store its
5180  * data as a stat_array.  If the nvpair is a single uint64_t value, then we make
5181  * it look like a one element array to make it easier to process.
5182  */
5183 static int
nvpair64_to_stat_array(nvlist_t * nvl,const char * name,struct stat_array * nva)5184 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
5185     struct stat_array *nva)
5186 {
5187 	nvpair_t *tmp;
5188 	int ret;
5189 
5190 	verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
5191 	switch (nvpair_type(tmp)) {
5192 	case DATA_TYPE_UINT64_ARRAY:
5193 		ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
5194 		break;
5195 	case DATA_TYPE_UINT64:
5196 		ret = nvpair_value_uint64(tmp, &nva->__data);
5197 		nva->data = &nva->__data;
5198 		nva->count = 1;
5199 		break;
5200 	default:
5201 		/* Not a uint64_t */
5202 		ret = EINVAL;
5203 		break;
5204 	}
5205 
5206 	return (ret);
5207 }
5208 
5209 /*
5210  * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
5211  * subtract them, and return the results in a newly allocated stat_array.
5212  * You must free the returned array after you are done with it with
5213  * free_calc_stats().
5214  *
5215  * Additionally, you can set "oldnv" to NULL if you simply want the newnv
5216  * values.
5217  */
5218 static struct stat_array *
calc_and_alloc_stats_ex(const char ** names,unsigned int len,nvlist_t * oldnv,nvlist_t * newnv)5219 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
5220     nvlist_t *newnv)
5221 {
5222 	nvlist_t *oldnvx = NULL, *newnvx;
5223 	struct stat_array *oldnva, *newnva, *calcnva;
5224 	int i, j;
5225 	unsigned int alloc_size = (sizeof (struct stat_array)) * len;
5226 
5227 	/* Extract our extended stats nvlist from the main list */
5228 	verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5229 	    &newnvx) == 0);
5230 	if (oldnv) {
5231 		verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5232 		    &oldnvx) == 0);
5233 	}
5234 
5235 	newnva = safe_malloc(alloc_size);
5236 	oldnva = safe_malloc(alloc_size);
5237 	calcnva = safe_malloc(alloc_size);
5238 
5239 	for (j = 0; j < len; j++) {
5240 		verify(nvpair64_to_stat_array(newnvx, names[j],
5241 		    &newnva[j]) == 0);
5242 		calcnva[j].count = newnva[j].count;
5243 		alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
5244 		calcnva[j].data = safe_malloc(alloc_size);
5245 		memcpy(calcnva[j].data, newnva[j].data, alloc_size);
5246 
5247 		if (oldnvx) {
5248 			verify(nvpair64_to_stat_array(oldnvx, names[j],
5249 			    &oldnva[j]) == 0);
5250 			for (i = 0; i < oldnva[j].count; i++)
5251 				calcnva[j].data[i] -= oldnva[j].data[i];
5252 		}
5253 	}
5254 	free(newnva);
5255 	free(oldnva);
5256 	return (calcnva);
5257 }
5258 
5259 static void
free_calc_stats(struct stat_array * nva,unsigned int len)5260 free_calc_stats(struct stat_array *nva, unsigned int len)
5261 {
5262 	int i;
5263 	for (i = 0; i < len; i++)
5264 		free(nva[i].data);
5265 
5266 	free(nva);
5267 }
5268 
5269 static void
print_iostat_histo(struct stat_array * nva,unsigned int len,iostat_cbdata_t * cb,unsigned int column_width,unsigned int namewidth,double scale)5270 print_iostat_histo(struct stat_array *nva, unsigned int len,
5271     iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
5272     double scale)
5273 {
5274 	int i, j;
5275 	char buf[6];
5276 	uint64_t val;
5277 	enum zfs_nicenum_format format;
5278 	unsigned int buckets;
5279 	unsigned int start_bucket;
5280 
5281 	if (cb->cb_literal)
5282 		format = ZFS_NICENUM_RAW;
5283 	else
5284 		format = ZFS_NICENUM_1024;
5285 
5286 	/* All these histos are the same size, so just use nva[0].count */
5287 	buckets = nva[0].count;
5288 
5289 	if (cb->cb_flags & IOS_RQ_HISTO_M) {
5290 		/* Start at 512 - req size should never be lower than this */
5291 		start_bucket = 9;
5292 	} else {
5293 		start_bucket = 0;
5294 	}
5295 
5296 	for (j = start_bucket; j < buckets; j++) {
5297 		/* Print histogram bucket label */
5298 		if (cb->cb_flags & IOS_L_HISTO_M) {
5299 			/* Ending range of this bucket */
5300 			val = (1UL << (j + 1)) - 1;
5301 			zfs_nicetime(val, buf, sizeof (buf));
5302 		} else {
5303 			/* Request size (starting range of bucket) */
5304 			val = (1UL << j);
5305 			zfs_nicenum(val, buf, sizeof (buf));
5306 		}
5307 
5308 		if (cb->cb_scripted)
5309 			printf("%llu", (u_longlong_t)val);
5310 		else
5311 			printf("%-*s", namewidth, buf);
5312 
5313 		/* Print the values on the line */
5314 		for (i = 0; i < len; i++) {
5315 			print_one_stat(nva[i].data[j] * scale, format,
5316 			    column_width, cb->cb_scripted);
5317 		}
5318 		printf("\n");
5319 	}
5320 }
5321 
5322 static void
print_solid_separator(unsigned int length)5323 print_solid_separator(unsigned int length)
5324 {
5325 	while (length--)
5326 		printf("-");
5327 	printf("\n");
5328 }
5329 
5330 static void
print_iostat_histos(iostat_cbdata_t * cb,nvlist_t * oldnv,nvlist_t * newnv,double scale,const char * name)5331 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
5332     nvlist_t *newnv, double scale, const char *name)
5333 {
5334 	unsigned int column_width;
5335 	unsigned int namewidth;
5336 	unsigned int entire_width;
5337 	enum iostat_type type;
5338 	struct stat_array *nva;
5339 	const char **names;
5340 	unsigned int names_len;
5341 
5342 	/* What type of histo are we? */
5343 	type = IOS_HISTO_IDX(cb->cb_flags);
5344 
5345 	/* Get NULL-terminated array of nvlist names for our histo */
5346 	names = vsx_type_to_nvlist[type];
5347 	names_len = str_array_len(names); /* num of names */
5348 
5349 	nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
5350 
5351 	if (cb->cb_literal) {
5352 		column_width = MAX(5,
5353 		    (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
5354 	} else {
5355 		column_width = 5;
5356 	}
5357 
5358 	namewidth = MAX(cb->cb_namewidth,
5359 	    strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
5360 
5361 	/*
5362 	 * Calculate the entire line width of what we're printing.  The
5363 	 * +2 is for the two spaces between columns:
5364 	 */
5365 	/*	 read  write				*/
5366 	/*	-----  -----				*/
5367 	/*	|___|  <---------- column_width		*/
5368 	/*						*/
5369 	/*	|__________|  <--- entire_width		*/
5370 	/*						*/
5371 	entire_width = namewidth + (column_width + 2) *
5372 	    label_array_len(iostat_bottom_labels[type]);
5373 
5374 	if (cb->cb_scripted)
5375 		printf("%s\n", name);
5376 	else
5377 		print_iostat_header_impl(cb, column_width, name);
5378 
5379 	print_iostat_histo(nva, names_len, cb, column_width,
5380 	    namewidth, scale);
5381 
5382 	free_calc_stats(nva, names_len);
5383 	if (!cb->cb_scripted)
5384 		print_solid_separator(entire_width);
5385 }
5386 
5387 /*
5388  * Calculate the average latency of a power-of-two latency histogram
5389  */
5390 static uint64_t
single_histo_average(uint64_t * histo,unsigned int buckets)5391 single_histo_average(uint64_t *histo, unsigned int buckets)
5392 {
5393 	int i;
5394 	uint64_t count = 0, total = 0;
5395 
5396 	for (i = 0; i < buckets; i++) {
5397 		/*
5398 		 * Our buckets are power-of-two latency ranges.  Use the
5399 		 * midpoint latency of each bucket to calculate the average.
5400 		 * For example:
5401 		 *
5402 		 * Bucket          Midpoint
5403 		 * 8ns-15ns:       12ns
5404 		 * 16ns-31ns:      24ns
5405 		 * ...
5406 		 */
5407 		if (histo[i] != 0) {
5408 			total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
5409 			count += histo[i];
5410 		}
5411 	}
5412 
5413 	/* Prevent divide by zero */
5414 	return (count == 0 ? 0 : total / count);
5415 }
5416 
5417 static void
print_iostat_queues(iostat_cbdata_t * cb,nvlist_t * newnv)5418 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *newnv)
5419 {
5420 	const char *names[] = {
5421 		ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
5422 		ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
5423 		ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
5424 		ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
5425 		ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
5426 		ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
5427 		ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
5428 		ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
5429 		ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
5430 		ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
5431 		ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
5432 		ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
5433 		ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
5434 		ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
5435 	};
5436 
5437 	struct stat_array *nva;
5438 
5439 	unsigned int column_width = default_column_width(cb, IOS_QUEUES);
5440 	enum zfs_nicenum_format format;
5441 
5442 	nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
5443 
5444 	if (cb->cb_literal)
5445 		format = ZFS_NICENUM_RAW;
5446 	else
5447 		format = ZFS_NICENUM_1024;
5448 
5449 	for (int i = 0; i < ARRAY_SIZE(names); i++) {
5450 		uint64_t val = nva[i].data[0];
5451 		print_one_stat(val, format, column_width, cb->cb_scripted);
5452 	}
5453 
5454 	free_calc_stats(nva, ARRAY_SIZE(names));
5455 }
5456 
5457 static void
print_iostat_latency(iostat_cbdata_t * cb,nvlist_t * oldnv,nvlist_t * newnv)5458 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
5459     nvlist_t *newnv)
5460 {
5461 	int i;
5462 	uint64_t val;
5463 	const char *names[] = {
5464 		ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
5465 		ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
5466 		ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
5467 		ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
5468 		ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
5469 		ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
5470 		ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
5471 		ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
5472 		ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
5473 		ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
5474 		ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
5475 	};
5476 	struct stat_array *nva;
5477 
5478 	unsigned int column_width = default_column_width(cb, IOS_LATENCY);
5479 	enum zfs_nicenum_format format;
5480 
5481 	nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
5482 
5483 	if (cb->cb_literal)
5484 		format = ZFS_NICENUM_RAWTIME;
5485 	else
5486 		format = ZFS_NICENUM_TIME;
5487 
5488 	/* Print our avg latencies on the line */
5489 	for (i = 0; i < ARRAY_SIZE(names); i++) {
5490 		/* Compute average latency for a latency histo */
5491 		val = single_histo_average(nva[i].data, nva[i].count);
5492 		print_one_stat(val, format, column_width, cb->cb_scripted);
5493 	}
5494 	free_calc_stats(nva, ARRAY_SIZE(names));
5495 }
5496 
5497 /*
5498  * Print default statistics (capacity/operations/bandwidth)
5499  */
5500 static void
print_iostat_default(vdev_stat_t * vs,iostat_cbdata_t * cb,double scale)5501 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
5502 {
5503 	unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
5504 	enum zfs_nicenum_format format;
5505 	char na;	/* char to print for "not applicable" values */
5506 
5507 	if (cb->cb_literal) {
5508 		format = ZFS_NICENUM_RAW;
5509 		na = '0';
5510 	} else {
5511 		format = ZFS_NICENUM_1024;
5512 		na = '-';
5513 	}
5514 
5515 	/* only toplevel vdevs have capacity stats */
5516 	if (vs->vs_space == 0) {
5517 		if (cb->cb_scripted)
5518 			printf("\t%c\t%c", na, na);
5519 		else
5520 			printf("  %*c  %*c", column_width, na, column_width,
5521 			    na);
5522 	} else {
5523 		print_one_stat(vs->vs_alloc, format, column_width,
5524 		    cb->cb_scripted);
5525 		print_one_stat(vs->vs_space - vs->vs_alloc, format,
5526 		    column_width, cb->cb_scripted);
5527 	}
5528 
5529 	print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
5530 	    format, column_width, cb->cb_scripted);
5531 	print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
5532 	    format, column_width, cb->cb_scripted);
5533 	print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
5534 	    format, column_width, cb->cb_scripted);
5535 	print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
5536 	    format, column_width, cb->cb_scripted);
5537 }
5538 
5539 static const char *const class_name[] = {
5540 	VDEV_ALLOC_BIAS_DEDUP,
5541 	VDEV_ALLOC_BIAS_SPECIAL,
5542 	VDEV_ALLOC_CLASS_LOGS
5543 };
5544 
5545 /*
5546  * Print out all the statistics for the given vdev.  This can either be the
5547  * toplevel configuration, or called recursively.  If 'name' is NULL, then this
5548  * is a verbose output, and we don't want to display the toplevel pool stats.
5549  *
5550  * Returns the number of stat lines printed.
5551  */
5552 static unsigned int
print_vdev_stats(zpool_handle_t * zhp,const char * name,nvlist_t * oldnv,nvlist_t * newnv,iostat_cbdata_t * cb,int depth)5553 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
5554     nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
5555 {
5556 	nvlist_t **oldchild, **newchild;
5557 	uint_t c, children, oldchildren;
5558 	vdev_stat_t *oldvs, *newvs, *calcvs;
5559 	vdev_stat_t zerovs = { 0 };
5560 	char *vname;
5561 	int i;
5562 	int ret = 0;
5563 	uint64_t tdelta;
5564 	double scale;
5565 
5566 	if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
5567 		return (ret);
5568 
5569 	calcvs = safe_malloc(sizeof (*calcvs));
5570 
5571 	if (oldnv != NULL) {
5572 		verify(nvlist_lookup_uint64_array(oldnv,
5573 		    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
5574 	} else {
5575 		oldvs = &zerovs;
5576 	}
5577 
5578 	/* Do we only want to see a specific vdev? */
5579 	for (i = 0; i < cb->cb_vdevs.cb_names_count; i++) {
5580 		/* Yes we do.  Is this the vdev? */
5581 		if (strcmp(name, cb->cb_vdevs.cb_names[i]) == 0) {
5582 			/*
5583 			 * This is our vdev.  Since it is the only vdev we
5584 			 * will be displaying, make depth = 0 so that it
5585 			 * doesn't get indented.
5586 			 */
5587 			depth = 0;
5588 			break;
5589 		}
5590 	}
5591 
5592 	if (cb->cb_vdevs.cb_names_count && (i == cb->cb_vdevs.cb_names_count)) {
5593 		/* Couldn't match the name */
5594 		goto children;
5595 	}
5596 
5597 
5598 	verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
5599 	    (uint64_t **)&newvs, &c) == 0);
5600 
5601 	/*
5602 	 * Print the vdev name unless it's is a histogram.  Histograms
5603 	 * display the vdev name in the header itself.
5604 	 */
5605 	if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
5606 		if (cb->cb_scripted) {
5607 			printf("%s", name);
5608 		} else {
5609 			if (strlen(name) + depth > cb->cb_namewidth)
5610 				(void) printf("%*s%s", depth, "", name);
5611 			else
5612 				(void) printf("%*s%s%*s", depth, "", name,
5613 				    (int)(cb->cb_namewidth - strlen(name) -
5614 				    depth), "");
5615 		}
5616 	}
5617 
5618 	/* Calculate our scaling factor */
5619 	tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
5620 	if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
5621 		/*
5622 		 * If we specify printing histograms with no time interval, then
5623 		 * print the histogram numbers over the entire lifetime of the
5624 		 * vdev.
5625 		 */
5626 		scale = 1;
5627 	} else {
5628 		if (tdelta == 0)
5629 			scale = 1.0;
5630 		else
5631 			scale = (double)NANOSEC / tdelta;
5632 	}
5633 
5634 	if (cb->cb_flags & IOS_DEFAULT_M) {
5635 		calc_default_iostats(oldvs, newvs, calcvs);
5636 		print_iostat_default(calcvs, cb, scale);
5637 	}
5638 	if (cb->cb_flags & IOS_LATENCY_M)
5639 		print_iostat_latency(cb, oldnv, newnv);
5640 	if (cb->cb_flags & IOS_QUEUES_M)
5641 		print_iostat_queues(cb, newnv);
5642 	if (cb->cb_flags & IOS_ANYHISTO_M) {
5643 		printf("\n");
5644 		print_iostat_histos(cb, oldnv, newnv, scale, name);
5645 	}
5646 
5647 	if (cb->vcdl != NULL) {
5648 		const char *path;
5649 		if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
5650 		    &path) == 0) {
5651 			printf("  ");
5652 			zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
5653 		}
5654 	}
5655 
5656 	if (!(cb->cb_flags & IOS_ANYHISTO_M))
5657 		printf("\n");
5658 
5659 	ret++;
5660 
5661 children:
5662 
5663 	free(calcvs);
5664 
5665 	if (!cb->cb_verbose)
5666 		return (ret);
5667 
5668 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
5669 	    &newchild, &children) != 0)
5670 		return (ret);
5671 
5672 	if (oldnv) {
5673 		if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
5674 		    &oldchild, &oldchildren) != 0)
5675 			return (ret);
5676 
5677 		children = MIN(oldchildren, children);
5678 	}
5679 
5680 	/*
5681 	 * print normal top-level devices
5682 	 */
5683 	for (c = 0; c < children; c++) {
5684 		uint64_t ishole = B_FALSE, islog = B_FALSE;
5685 
5686 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
5687 		    &ishole);
5688 
5689 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
5690 		    &islog);
5691 
5692 		if (ishole || islog)
5693 			continue;
5694 
5695 		if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
5696 			continue;
5697 
5698 		vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5699 		    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5700 		ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
5701 		    newchild[c], cb, depth + 2);
5702 		free(vname);
5703 	}
5704 
5705 	/*
5706 	 * print all other top-level devices
5707 	 */
5708 	for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
5709 		boolean_t printed = B_FALSE;
5710 
5711 		for (c = 0; c < children; c++) {
5712 			uint64_t islog = B_FALSE;
5713 			const char *bias = NULL;
5714 			const char *type = NULL;
5715 
5716 			(void) nvlist_lookup_uint64(newchild[c],
5717 			    ZPOOL_CONFIG_IS_LOG, &islog);
5718 			if (islog) {
5719 				bias = VDEV_ALLOC_CLASS_LOGS;
5720 			} else {
5721 				(void) nvlist_lookup_string(newchild[c],
5722 				    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
5723 				(void) nvlist_lookup_string(newchild[c],
5724 				    ZPOOL_CONFIG_TYPE, &type);
5725 			}
5726 			if (bias == NULL || strcmp(bias, class_name[n]) != 0)
5727 				continue;
5728 			if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
5729 				continue;
5730 
5731 			if (!printed) {
5732 				if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
5733 				    !cb->cb_scripted &&
5734 				    !cb->cb_vdevs.cb_names) {
5735 					print_iostat_dashes(cb, 0,
5736 					    class_name[n]);
5737 				}
5738 				printf("\n");
5739 				printed = B_TRUE;
5740 			}
5741 
5742 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5743 			    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5744 			ret += print_vdev_stats(zhp, vname, oldnv ?
5745 			    oldchild[c] : NULL, newchild[c], cb, depth + 2);
5746 			free(vname);
5747 		}
5748 	}
5749 
5750 	/*
5751 	 * Include level 2 ARC devices in iostat output
5752 	 */
5753 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
5754 	    &newchild, &children) != 0)
5755 		return (ret);
5756 
5757 	if (oldnv) {
5758 		if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
5759 		    &oldchild, &oldchildren) != 0)
5760 			return (ret);
5761 
5762 		children = MIN(oldchildren, children);
5763 	}
5764 
5765 	if (children > 0) {
5766 		if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
5767 		    !cb->cb_vdevs.cb_names) {
5768 			print_iostat_dashes(cb, 0, "cache");
5769 		}
5770 		printf("\n");
5771 
5772 		for (c = 0; c < children; c++) {
5773 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5774 			    cb->cb_vdevs.cb_name_flags);
5775 			ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
5776 			    : NULL, newchild[c], cb, depth + 2);
5777 			free(vname);
5778 		}
5779 	}
5780 
5781 	return (ret);
5782 }
5783 
5784 /*
5785  * Callback to print out the iostats for the given pool.
5786  */
5787 static int
print_iostat(zpool_handle_t * zhp,void * data)5788 print_iostat(zpool_handle_t *zhp, void *data)
5789 {
5790 	iostat_cbdata_t *cb = data;
5791 	nvlist_t *oldconfig, *newconfig;
5792 	nvlist_t *oldnvroot, *newnvroot;
5793 	int ret;
5794 
5795 	newconfig = zpool_get_config(zhp, &oldconfig);
5796 
5797 	if (cb->cb_iteration == 1)
5798 		oldconfig = NULL;
5799 
5800 	verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
5801 	    &newnvroot) == 0);
5802 
5803 	if (oldconfig == NULL)
5804 		oldnvroot = NULL;
5805 	else
5806 		verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
5807 		    &oldnvroot) == 0);
5808 
5809 	ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
5810 	    cb, 0);
5811 	if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
5812 	    !cb->cb_scripted && cb->cb_verbose &&
5813 	    !cb->cb_vdevs.cb_names_count) {
5814 		print_iostat_separator(cb);
5815 		if (cb->vcdl != NULL) {
5816 			print_cmd_columns(cb->vcdl, 1);
5817 		}
5818 		printf("\n");
5819 	}
5820 
5821 	return (ret);
5822 }
5823 
5824 static int
get_columns(void)5825 get_columns(void)
5826 {
5827 	struct winsize ws;
5828 	int columns = 80;
5829 	int error;
5830 
5831 	if (isatty(STDOUT_FILENO)) {
5832 		error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
5833 		if (error == 0)
5834 			columns = ws.ws_col;
5835 	} else {
5836 		columns = 999;
5837 	}
5838 
5839 	return (columns);
5840 }
5841 
5842 /*
5843  * Return the required length of the pool/vdev name column.  The minimum
5844  * allowed width and output formatting flags must be provided.
5845  */
5846 static int
get_namewidth(zpool_handle_t * zhp,int min_width,int flags,boolean_t verbose)5847 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
5848 {
5849 	nvlist_t *config, *nvroot;
5850 	int width = min_width;
5851 
5852 	if ((config = zpool_get_config(zhp, NULL)) != NULL) {
5853 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5854 		    &nvroot) == 0);
5855 		size_t poolname_len = strlen(zpool_get_name(zhp));
5856 		if (verbose == B_FALSE) {
5857 			width = MAX(poolname_len, min_width);
5858 		} else {
5859 			width = MAX(poolname_len,
5860 			    max_width(zhp, nvroot, 0, min_width, flags));
5861 		}
5862 	}
5863 
5864 	return (width);
5865 }
5866 
5867 /*
5868  * Parse the input string, get the 'interval' and 'count' value if there is one.
5869  */
5870 static void
get_interval_count(int * argcp,char ** argv,float * iv,unsigned long * cnt)5871 get_interval_count(int *argcp, char **argv, float *iv,
5872     unsigned long *cnt)
5873 {
5874 	float interval = 0;
5875 	unsigned long count = 0;
5876 	int argc = *argcp;
5877 
5878 	/*
5879 	 * Determine if the last argument is an integer or a pool name
5880 	 */
5881 	if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5882 		char *end;
5883 
5884 		errno = 0;
5885 		interval = strtof(argv[argc - 1], &end);
5886 
5887 		if (*end == '\0' && errno == 0) {
5888 			if (interval == 0) {
5889 				(void) fprintf(stderr, gettext(
5890 				    "interval cannot be zero\n"));
5891 				usage(B_FALSE);
5892 			}
5893 			/*
5894 			 * Ignore the last parameter
5895 			 */
5896 			argc--;
5897 		} else {
5898 			/*
5899 			 * If this is not a valid number, just plow on.  The
5900 			 * user will get a more informative error message later
5901 			 * on.
5902 			 */
5903 			interval = 0;
5904 		}
5905 	}
5906 
5907 	/*
5908 	 * If the last argument is also an integer, then we have both a count
5909 	 * and an interval.
5910 	 */
5911 	if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5912 		char *end;
5913 
5914 		errno = 0;
5915 		count = interval;
5916 		interval = strtof(argv[argc - 1], &end);
5917 
5918 		if (*end == '\0' && errno == 0) {
5919 			if (interval == 0) {
5920 				(void) fprintf(stderr, gettext(
5921 				    "interval cannot be zero\n"));
5922 				usage(B_FALSE);
5923 			}
5924 
5925 			/*
5926 			 * Ignore the last parameter
5927 			 */
5928 			argc--;
5929 		} else {
5930 			interval = 0;
5931 		}
5932 	}
5933 
5934 	*iv = interval;
5935 	*cnt = count;
5936 	*argcp = argc;
5937 }
5938 
5939 static void
get_timestamp_arg(char c)5940 get_timestamp_arg(char c)
5941 {
5942 	if (c == 'u')
5943 		timestamp_fmt = UDATE;
5944 	else if (c == 'd')
5945 		timestamp_fmt = DDATE;
5946 	else
5947 		usage(B_FALSE);
5948 }
5949 
5950 /*
5951  * Return stat flags that are supported by all pools by both the module and
5952  * zpool iostat.  "*data" should be initialized to all 0xFFs before running.
5953  * It will get ANDed down until only the flags that are supported on all pools
5954  * remain.
5955  */
5956 static int
get_stat_flags_cb(zpool_handle_t * zhp,void * data)5957 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
5958 {
5959 	uint64_t *mask = data;
5960 	nvlist_t *config, *nvroot, *nvx;
5961 	uint64_t flags = 0;
5962 	int i, j;
5963 
5964 	config = zpool_get_config(zhp, NULL);
5965 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5966 	    &nvroot) == 0);
5967 
5968 	/* Default stats are always supported, but for completeness.. */
5969 	if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
5970 		flags |= IOS_DEFAULT_M;
5971 
5972 	/* Get our extended stats nvlist from the main list */
5973 	if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
5974 	    &nvx) != 0) {
5975 		/*
5976 		 * No extended stats; they're probably running an older
5977 		 * module.  No big deal, we support that too.
5978 		 */
5979 		goto end;
5980 	}
5981 
5982 	/* For each extended stat, make sure all its nvpairs are supported */
5983 	for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
5984 		if (!vsx_type_to_nvlist[j][0])
5985 			continue;
5986 
5987 		/* Start off by assuming the flag is supported, then check */
5988 		flags |= (1ULL << j);
5989 		for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
5990 			if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
5991 				/* flag isn't supported */
5992 				flags = flags & ~(1ULL  << j);
5993 				break;
5994 			}
5995 		}
5996 	}
5997 end:
5998 	*mask = *mask & flags;
5999 	return (0);
6000 }
6001 
6002 /*
6003  * Return a bitmask of stats that are supported on all pools by both the module
6004  * and zpool iostat.
6005  */
6006 static uint64_t
get_stat_flags(zpool_list_t * list)6007 get_stat_flags(zpool_list_t *list)
6008 {
6009 	uint64_t mask = -1;
6010 
6011 	/*
6012 	 * get_stat_flags_cb() will lop off bits from "mask" until only the
6013 	 * flags that are supported on all pools remain.
6014 	 */
6015 	(void) pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
6016 	return (mask);
6017 }
6018 
6019 /*
6020  * Return 1 if cb_data->cb_names[0] is this vdev's name, 0 otherwise.
6021  */
6022 static int
is_vdev_cb(void * zhp_data,nvlist_t * nv,void * cb_data)6023 is_vdev_cb(void *zhp_data, nvlist_t *nv, void *cb_data)
6024 {
6025 	uint64_t guid;
6026 	vdev_cbdata_t *cb = cb_data;
6027 	zpool_handle_t *zhp = zhp_data;
6028 
6029 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
6030 		return (0);
6031 
6032 	return (guid == zpool_vdev_path_to_guid(zhp, cb->cb_names[0]));
6033 }
6034 
6035 /*
6036  * Returns 1 if cb_data->cb_names[0] is a vdev name, 0 otherwise.
6037  */
6038 static int
is_vdev(zpool_handle_t * zhp,void * cb_data)6039 is_vdev(zpool_handle_t *zhp, void *cb_data)
6040 {
6041 	return (for_each_vdev(zhp, is_vdev_cb, cb_data));
6042 }
6043 
6044 /*
6045  * Check if vdevs are in a pool
6046  *
6047  * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
6048  * return 0.  If pool_name is NULL, then search all pools.
6049  */
6050 static int
are_vdevs_in_pool(int argc,char ** argv,char * pool_name,vdev_cbdata_t * cb)6051 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
6052     vdev_cbdata_t *cb)
6053 {
6054 	char **tmp_name;
6055 	int ret = 0;
6056 	int i;
6057 	int pool_count = 0;
6058 
6059 	if ((argc == 0) || !*argv)
6060 		return (0);
6061 
6062 	if (pool_name)
6063 		pool_count = 1;
6064 
6065 	/* Temporarily hijack cb_names for a second... */
6066 	tmp_name = cb->cb_names;
6067 
6068 	/* Go though our list of prospective vdev names */
6069 	for (i = 0; i < argc; i++) {
6070 		cb->cb_names = argv + i;
6071 
6072 		/* Is this name a vdev in our pools? */
6073 		ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
6074 		    ZFS_TYPE_POOL, B_FALSE, is_vdev, cb);
6075 		if (!ret) {
6076 			/* No match */
6077 			break;
6078 		}
6079 	}
6080 
6081 	cb->cb_names = tmp_name;
6082 
6083 	return (ret);
6084 }
6085 
6086 static int
is_pool_cb(zpool_handle_t * zhp,void * data)6087 is_pool_cb(zpool_handle_t *zhp, void *data)
6088 {
6089 	char *name = data;
6090 	if (strcmp(name, zpool_get_name(zhp)) == 0)
6091 		return (1);
6092 
6093 	return (0);
6094 }
6095 
6096 /*
6097  * Do we have a pool named *name?  If so, return 1, otherwise 0.
6098  */
6099 static int
is_pool(char * name)6100 is_pool(char *name)
6101 {
6102 	return (for_each_pool(0, NULL, B_TRUE, NULL, ZFS_TYPE_POOL, B_FALSE,
6103 	    is_pool_cb, name));
6104 }
6105 
6106 /* Are all our argv[] strings pool names?  If so return 1, 0 otherwise. */
6107 static int
are_all_pools(int argc,char ** argv)6108 are_all_pools(int argc, char **argv)
6109 {
6110 	if ((argc == 0) || !*argv)
6111 		return (0);
6112 
6113 	while (--argc >= 0)
6114 		if (!is_pool(argv[argc]))
6115 			return (0);
6116 
6117 	return (1);
6118 }
6119 
6120 /*
6121  * Helper function to print out vdev/pool names we can't resolve.  Used for an
6122  * error message.
6123  */
6124 static void
error_list_unresolved_vdevs(int argc,char ** argv,char * pool_name,vdev_cbdata_t * cb)6125 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
6126     vdev_cbdata_t *cb)
6127 {
6128 	int i;
6129 	char *name;
6130 	char *str;
6131 	for (i = 0; i < argc; i++) {
6132 		name = argv[i];
6133 
6134 		if (is_pool(name))
6135 			str = gettext("pool");
6136 		else if (are_vdevs_in_pool(1, &name, pool_name, cb))
6137 			str = gettext("vdev in this pool");
6138 		else if (are_vdevs_in_pool(1, &name, NULL, cb))
6139 			str = gettext("vdev in another pool");
6140 		else
6141 			str = gettext("unknown");
6142 
6143 		fprintf(stderr, "\t%s (%s)\n", name, str);
6144 	}
6145 }
6146 
6147 /*
6148  * Same as get_interval_count(), but with additional checks to not misinterpret
6149  * guids as interval/count values.  Assumes VDEV_NAME_GUID is set in
6150  * cb.cb_vdevs.cb_name_flags.
6151  */
6152 static void
get_interval_count_filter_guids(int * argc,char ** argv,float * interval,unsigned long * count,iostat_cbdata_t * cb)6153 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
6154     unsigned long *count, iostat_cbdata_t *cb)
6155 {
6156 	int argc_for_interval = 0;
6157 
6158 	/* Is the last arg an interval value?  Or a guid? */
6159 	if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL,
6160 	    &cb->cb_vdevs)) {
6161 		/*
6162 		 * The last arg is not a guid, so it's probably an
6163 		 * interval value.
6164 		 */
6165 		argc_for_interval++;
6166 
6167 		if (*argc >= 2 &&
6168 		    !are_vdevs_in_pool(1, &argv[*argc - 2], NULL,
6169 		    &cb->cb_vdevs)) {
6170 			/*
6171 			 * The 2nd to last arg is not a guid, so it's probably
6172 			 * an interval value.
6173 			 */
6174 			argc_for_interval++;
6175 		}
6176 	}
6177 
6178 	/* Point to our list of possible intervals */
6179 	char **tmpargv = &argv[*argc - argc_for_interval];
6180 
6181 	*argc = *argc - argc_for_interval;
6182 	get_interval_count(&argc_for_interval, tmpargv,
6183 	    interval, count);
6184 }
6185 
6186 /*
6187  * Terminal height, in rows. Returns -1 if stdout is not connected to a TTY or
6188  * if we were unable to determine its size.
6189  */
6190 static int
terminal_height(void)6191 terminal_height(void)
6192 {
6193 	struct winsize win;
6194 
6195 	if (isatty(STDOUT_FILENO) == 0)
6196 		return (-1);
6197 
6198 	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_row > 0)
6199 		return (win.ws_row);
6200 
6201 	return (-1);
6202 }
6203 
6204 /*
6205  * Run one of the zpool status/iostat -c scripts with the help (-h) option and
6206  * print the result.
6207  *
6208  * name:	Short name of the script ('iostat').
6209  * path:	Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
6210  */
6211 static void
print_zpool_script_help(char * name,char * path)6212 print_zpool_script_help(char *name, char *path)
6213 {
6214 	char *argv[] = {path, (char *)"-h", NULL};
6215 	char **lines = NULL;
6216 	int lines_cnt = 0;
6217 	int rc;
6218 
6219 	rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
6220 	    &lines_cnt);
6221 	if (rc != 0 || lines == NULL || lines_cnt <= 0) {
6222 		if (lines != NULL)
6223 			libzfs_free_str_array(lines, lines_cnt);
6224 		return;
6225 	}
6226 
6227 	for (int i = 0; i < lines_cnt; i++)
6228 		if (!is_blank_str(lines[i]))
6229 			printf("  %-14s  %s\n", name, lines[i]);
6230 
6231 	libzfs_free_str_array(lines, lines_cnt);
6232 }
6233 
6234 /*
6235  * Go though the zpool status/iostat -c scripts in the user's path, run their
6236  * help option (-h), and print out the results.
6237  */
6238 static void
print_zpool_dir_scripts(char * dirpath)6239 print_zpool_dir_scripts(char *dirpath)
6240 {
6241 	DIR *dir;
6242 	struct dirent *ent;
6243 	char fullpath[MAXPATHLEN];
6244 	struct stat dir_stat;
6245 
6246 	if ((dir = opendir(dirpath)) != NULL) {
6247 		/* print all the files and directories within directory */
6248 		while ((ent = readdir(dir)) != NULL) {
6249 			if (snprintf(fullpath, sizeof (fullpath), "%s/%s",
6250 			    dirpath, ent->d_name) >= sizeof (fullpath)) {
6251 				(void) fprintf(stderr,
6252 				    gettext("internal error: "
6253 				    "ZPOOL_SCRIPTS_PATH too large.\n"));
6254 				exit(1);
6255 			}
6256 
6257 			/* Print the scripts */
6258 			if (stat(fullpath, &dir_stat) == 0)
6259 				if (dir_stat.st_mode & S_IXUSR &&
6260 				    S_ISREG(dir_stat.st_mode))
6261 					print_zpool_script_help(ent->d_name,
6262 					    fullpath);
6263 		}
6264 		(void) closedir(dir);
6265 	}
6266 }
6267 
6268 /*
6269  * Print out help text for all zpool status/iostat -c scripts.
6270  */
6271 static void
print_zpool_script_list(const char * subcommand)6272 print_zpool_script_list(const char *subcommand)
6273 {
6274 	char *dir, *sp, *tmp;
6275 
6276 	printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
6277 
6278 	sp = zpool_get_cmd_search_path();
6279 	if (sp == NULL)
6280 		return;
6281 
6282 	for (dir = strtok_r(sp, ":", &tmp);
6283 	    dir != NULL;
6284 	    dir = strtok_r(NULL, ":", &tmp))
6285 		print_zpool_dir_scripts(dir);
6286 
6287 	free(sp);
6288 }
6289 
6290 /*
6291  * Set the minimum pool/vdev name column width.  The width must be at least 10,
6292  * but may be as large as the column width - 42 so it still fits on one line.
6293  * NOTE: 42 is the width of the default capacity/operations/bandwidth output
6294  */
6295 static int
get_namewidth_iostat(zpool_handle_t * zhp,void * data)6296 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
6297 {
6298 	iostat_cbdata_t *cb = data;
6299 	int width, available_width;
6300 
6301 	/*
6302 	 * get_namewidth() returns the maximum width of any name in that column
6303 	 * for any pool/vdev/device line that will be output.
6304 	 */
6305 	width = get_namewidth(zhp, cb->cb_namewidth,
6306 	    cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
6307 
6308 	/*
6309 	 * The width we are calculating is the width of the header and also the
6310 	 * padding width for names that are less than maximum width.  The stats
6311 	 * take up 42 characters, so the width available for names is:
6312 	 */
6313 	available_width = get_columns() - 42;
6314 
6315 	/*
6316 	 * If the maximum width fits on a screen, then great!  Make everything
6317 	 * line up by justifying all lines to the same width.  If that max
6318 	 * width is larger than what's available, the name plus stats won't fit
6319 	 * on one line, and justifying to that width would cause every line to
6320 	 * wrap on the screen.  We only want lines with long names to wrap.
6321 	 * Limit the padding to what won't wrap.
6322 	 */
6323 	if (width > available_width)
6324 		width = available_width;
6325 
6326 	/*
6327 	 * And regardless of whatever the screen width is (get_columns can
6328 	 * return 0 if the width is not known or less than 42 for a narrow
6329 	 * terminal) have the width be a minimum of 10.
6330 	 */
6331 	if (width < 10)
6332 		width = 10;
6333 
6334 	/* Save the calculated width */
6335 	cb->cb_namewidth = width;
6336 
6337 	return (0);
6338 }
6339 
6340 /*
6341  * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
6342  *              [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
6343  *              [interval [count]]
6344  *
6345  *	-c CMD  For each vdev, run command CMD
6346  *	-g	Display guid for individual vdev name.
6347  *	-L	Follow links when resolving vdev path name.
6348  *	-P	Display full path for vdev name.
6349  *	-v	Display statistics for individual vdevs
6350  *	-h	Display help
6351  *	-p	Display values in parsable (exact) format.
6352  *	-H	Scripted mode.  Don't display headers, and separate properties
6353  *		by a single tab.
6354  *	-l	Display average latency
6355  *	-q	Display queue depths
6356  *	-w	Display latency histograms
6357  *	-r	Display request size histogram
6358  *	-T	Display a timestamp in date(1) or Unix format
6359  *	-n	Only print headers once
6360  *
6361  * This command can be tricky because we want to be able to deal with pool
6362  * creation/destruction as well as vdev configuration changes.  The bulk of this
6363  * processing is handled by the pool_list_* routines in zpool_iter.c.  We rely
6364  * on pool_list_refresh() to detect the addition and removal of pools.
6365  * Configuration changes are all handled within libzfs.
6366  */
6367 int
zpool_do_iostat(int argc,char ** argv)6368 zpool_do_iostat(int argc, char **argv)
6369 {
6370 	int c;
6371 	int ret;
6372 	float interval = 0;
6373 	unsigned long count = 0;
6374 	zpool_list_t *list;
6375 	boolean_t verbose = B_FALSE;
6376 	boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
6377 	boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
6378 	boolean_t omit_since_boot = B_FALSE;
6379 	boolean_t guid = B_FALSE;
6380 	boolean_t follow_links = B_FALSE;
6381 	boolean_t full_name = B_FALSE;
6382 	boolean_t headers_once = B_FALSE;
6383 	iostat_cbdata_t cb = { 0 };
6384 	char *cmd = NULL;
6385 
6386 	/* Used for printing error message */
6387 	const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
6388 	    [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
6389 
6390 	uint64_t unsupported_flags;
6391 
6392 	/* check options */
6393 	while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwnH")) != -1) {
6394 		switch (c) {
6395 		case 'c':
6396 			if (cmd != NULL) {
6397 				fprintf(stderr,
6398 				    gettext("Can't set -c flag twice\n"));
6399 				exit(1);
6400 			}
6401 
6402 			if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
6403 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
6404 				fprintf(stderr, gettext(
6405 				    "Can't run -c, disabled by "
6406 				    "ZPOOL_SCRIPTS_ENABLED.\n"));
6407 				exit(1);
6408 			}
6409 
6410 			if ((getuid() <= 0 || geteuid() <= 0) &&
6411 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
6412 				fprintf(stderr, gettext(
6413 				    "Can't run -c with root privileges "
6414 				    "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
6415 				exit(1);
6416 			}
6417 			cmd = optarg;
6418 			verbose = B_TRUE;
6419 			break;
6420 		case 'g':
6421 			guid = B_TRUE;
6422 			break;
6423 		case 'L':
6424 			follow_links = B_TRUE;
6425 			break;
6426 		case 'P':
6427 			full_name = B_TRUE;
6428 			break;
6429 		case 'T':
6430 			get_timestamp_arg(*optarg);
6431 			break;
6432 		case 'v':
6433 			verbose = B_TRUE;
6434 			break;
6435 		case 'p':
6436 			parsable = B_TRUE;
6437 			break;
6438 		case 'l':
6439 			latency = B_TRUE;
6440 			break;
6441 		case 'q':
6442 			queues = B_TRUE;
6443 			break;
6444 		case 'H':
6445 			scripted = B_TRUE;
6446 			break;
6447 		case 'w':
6448 			l_histo = B_TRUE;
6449 			break;
6450 		case 'r':
6451 			rq_histo = B_TRUE;
6452 			break;
6453 		case 'y':
6454 			omit_since_boot = B_TRUE;
6455 			break;
6456 		case 'n':
6457 			headers_once = B_TRUE;
6458 			break;
6459 		case 'h':
6460 			usage(B_FALSE);
6461 			break;
6462 		case '?':
6463 			if (optopt == 'c') {
6464 				print_zpool_script_list("iostat");
6465 				exit(0);
6466 			} else {
6467 				fprintf(stderr,
6468 				    gettext("invalid option '%c'\n"), optopt);
6469 			}
6470 			usage(B_FALSE);
6471 		}
6472 	}
6473 
6474 	argc -= optind;
6475 	argv += optind;
6476 
6477 	cb.cb_literal = parsable;
6478 	cb.cb_scripted = scripted;
6479 
6480 	if (guid)
6481 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_GUID;
6482 	if (follow_links)
6483 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6484 	if (full_name)
6485 		cb.cb_vdevs.cb_name_flags |= VDEV_NAME_PATH;
6486 	cb.cb_iteration = 0;
6487 	cb.cb_namewidth = 0;
6488 	cb.cb_verbose = verbose;
6489 
6490 	/* Get our interval and count values (if any) */
6491 	if (guid) {
6492 		get_interval_count_filter_guids(&argc, argv, &interval,
6493 		    &count, &cb);
6494 	} else {
6495 		get_interval_count(&argc, argv, &interval, &count);
6496 	}
6497 
6498 	if (argc == 0) {
6499 		/* No args, so just print the defaults. */
6500 	} else if (are_all_pools(argc, argv)) {
6501 		/* All the args are pool names */
6502 	} else if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
6503 		/* All the args are vdevs */
6504 		cb.cb_vdevs.cb_names = argv;
6505 		cb.cb_vdevs.cb_names_count = argc;
6506 		argc = 0; /* No pools to process */
6507 	} else if (are_all_pools(1, argv)) {
6508 		/* The first arg is a pool name */
6509 		if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
6510 		    &cb.cb_vdevs)) {
6511 			/* ...and the rest are vdev names */
6512 			cb.cb_vdevs.cb_names = argv + 1;
6513 			cb.cb_vdevs.cb_names_count = argc - 1;
6514 			argc = 1; /* One pool to process */
6515 		} else {
6516 			fprintf(stderr, gettext("Expected either a list of "));
6517 			fprintf(stderr, gettext("pools, or list of vdevs in"));
6518 			fprintf(stderr, " \"%s\", ", argv[0]);
6519 			fprintf(stderr, gettext("but got:\n"));
6520 			error_list_unresolved_vdevs(argc - 1, argv + 1,
6521 			    argv[0], &cb.cb_vdevs);
6522 			fprintf(stderr, "\n");
6523 			usage(B_FALSE);
6524 		}
6525 	} else {
6526 		/*
6527 		 * The args don't make sense. The first arg isn't a pool name,
6528 		 * nor are all the args vdevs.
6529 		 */
6530 		fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
6531 		fprintf(stderr, "\n");
6532 		return (1);
6533 	}
6534 
6535 	if (cb.cb_vdevs.cb_names_count != 0) {
6536 		/*
6537 		 * If user specified vdevs, it implies verbose.
6538 		 */
6539 		cb.cb_verbose = B_TRUE;
6540 	}
6541 
6542 	/*
6543 	 * Construct the list of all interesting pools.
6544 	 */
6545 	ret = 0;
6546 	if ((list = pool_list_get(argc, argv, NULL, ZFS_TYPE_POOL, parsable,
6547 	    &ret)) == NULL)
6548 		return (1);
6549 
6550 	if (pool_list_count(list) == 0 && argc != 0) {
6551 		pool_list_free(list);
6552 		return (1);
6553 	}
6554 
6555 	if (pool_list_count(list) == 0 && interval == 0) {
6556 		pool_list_free(list);
6557 		(void) fprintf(stderr, gettext("no pools available\n"));
6558 		return (1);
6559 	}
6560 
6561 	if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
6562 		pool_list_free(list);
6563 		(void) fprintf(stderr,
6564 		    gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
6565 		usage(B_FALSE);
6566 	}
6567 
6568 	if (l_histo && rq_histo) {
6569 		pool_list_free(list);
6570 		(void) fprintf(stderr,
6571 		    gettext("Only one of [-r|-w] can be passed at a time\n"));
6572 		usage(B_FALSE);
6573 	}
6574 
6575 	/*
6576 	 * Enter the main iostat loop.
6577 	 */
6578 	cb.cb_list = list;
6579 
6580 	if (l_histo) {
6581 		/*
6582 		 * Histograms tables look out of place when you try to display
6583 		 * them with the other stats, so make a rule that you can only
6584 		 * print histograms by themselves.
6585 		 */
6586 		cb.cb_flags = IOS_L_HISTO_M;
6587 	} else if (rq_histo) {
6588 		cb.cb_flags = IOS_RQ_HISTO_M;
6589 	} else {
6590 		cb.cb_flags = IOS_DEFAULT_M;
6591 		if (latency)
6592 			cb.cb_flags |= IOS_LATENCY_M;
6593 		if (queues)
6594 			cb.cb_flags |= IOS_QUEUES_M;
6595 	}
6596 
6597 	/*
6598 	 * See if the module supports all the stats we want to display.
6599 	 */
6600 	unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
6601 	if (unsupported_flags) {
6602 		uint64_t f;
6603 		int idx;
6604 		fprintf(stderr,
6605 		    gettext("The loaded zfs module doesn't support:"));
6606 
6607 		/* for each bit set in unsupported_flags */
6608 		for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
6609 			idx = lowbit64(f) - 1;
6610 			fprintf(stderr, " -%c", flag_to_arg[idx]);
6611 		}
6612 
6613 		fprintf(stderr, ".  Try running a newer module.\n");
6614 		pool_list_free(list);
6615 
6616 		return (1);
6617 	}
6618 
6619 	int last_npools = 0;
6620 	for (;;) {
6621 		/*
6622 		 * Refresh all pools in list, adding or removing pools as
6623 		 * necessary.
6624 		 */
6625 		int npools = pool_list_refresh(list);
6626 		if (npools == 0) {
6627 			(void) fprintf(stderr, gettext("no pools available\n"));
6628 		} else {
6629 			/*
6630 			 * If the list of pools has changed since last time
6631 			 * around, reset the iteration count to force the
6632 			 * header to be redisplayed.
6633 			 */
6634 			if (last_npools != npools)
6635 				cb.cb_iteration = 0;
6636 
6637 			/*
6638 			 * If this is the first iteration and -y was supplied
6639 			 * we skip any printing.
6640 			 */
6641 			boolean_t skip = (omit_since_boot &&
6642 			    cb.cb_iteration == 0);
6643 
6644 			/*
6645 			 * Iterate over all pools to determine the maximum width
6646 			 * for the pool / device name column across all pools.
6647 			 */
6648 			cb.cb_namewidth = 0;
6649 			(void) pool_list_iter(list, B_FALSE,
6650 			    get_namewidth_iostat, &cb);
6651 
6652 			if (timestamp_fmt != NODATE)
6653 				print_timestamp(timestamp_fmt);
6654 
6655 			if (cmd != NULL && cb.cb_verbose &&
6656 			    !(cb.cb_flags & IOS_ANYHISTO_M)) {
6657 				cb.vcdl = all_pools_for_each_vdev_run(argc,
6658 				    argv, cmd, g_zfs, cb.cb_vdevs.cb_names,
6659 				    cb.cb_vdevs.cb_names_count,
6660 				    cb.cb_vdevs.cb_name_flags);
6661 			} else {
6662 				cb.vcdl = NULL;
6663 			}
6664 
6665 
6666 			/*
6667 			 * Check terminal size so we can print headers
6668 			 * even when terminal window has its height
6669 			 * changed.
6670 			 */
6671 			int winheight = terminal_height();
6672 			/*
6673 			 * Are we connected to TTY? If not, headers_once
6674 			 * should be true, to avoid breaking scripts.
6675 			 */
6676 			if (winheight < 0)
6677 				headers_once = B_TRUE;
6678 
6679 			/*
6680 			 * If it's the first time and we're not skipping it,
6681 			 * or either skip or verbose mode, print the header.
6682 			 *
6683 			 * The histogram code explicitly prints its header on
6684 			 * every vdev, so skip this for histograms.
6685 			 */
6686 			if (((++cb.cb_iteration == 1 && !skip) ||
6687 			    (skip != verbose) ||
6688 			    (!headers_once &&
6689 			    (cb.cb_iteration % winheight) == 0)) &&
6690 			    (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
6691 			    !cb.cb_scripted)
6692 				print_iostat_header(&cb);
6693 
6694 			if (skip) {
6695 				(void) fflush(stdout);
6696 				(void) fsleep(interval);
6697 				last_npools = npools;
6698 				continue;
6699 			}
6700 
6701 			(void) pool_list_iter(list, B_FALSE, print_iostat, &cb);
6702 
6703 			/*
6704 			 * If there's more than one pool, and we're not in
6705 			 * verbose mode (which prints a separator for us),
6706 			 * then print a separator.
6707 			 *
6708 			 * In addition, if we're printing specific vdevs then
6709 			 * we also want an ending separator.
6710 			 */
6711 			if (((npools > 1 && !verbose &&
6712 			    !(cb.cb_flags & IOS_ANYHISTO_M)) ||
6713 			    (!(cb.cb_flags & IOS_ANYHISTO_M) &&
6714 			    cb.cb_vdevs.cb_names_count)) &&
6715 			    !cb.cb_scripted) {
6716 				print_iostat_separator(&cb);
6717 				if (cb.vcdl != NULL)
6718 					print_cmd_columns(cb.vcdl, 1);
6719 				printf("\n");
6720 			}
6721 
6722 			if (cb.vcdl != NULL)
6723 				free_vdev_cmd_data_list(cb.vcdl);
6724 
6725 		}
6726 
6727 		if (interval == 0)
6728 			break;
6729 
6730 		if (count != 0 && --count == 0)
6731 			break;
6732 
6733 		(void) fflush(stdout);
6734 		(void) fsleep(interval);
6735 
6736 		last_npools = npools;
6737 	}
6738 
6739 	pool_list_free(list);
6740 
6741 	return (ret);
6742 }
6743 
6744 typedef struct list_cbdata {
6745 	boolean_t	cb_verbose;
6746 	int		cb_name_flags;
6747 	int		cb_namewidth;
6748 	boolean_t	cb_json;
6749 	boolean_t	cb_scripted;
6750 	zprop_list_t	*cb_proplist;
6751 	boolean_t	cb_literal;
6752 	nvlist_t	*cb_jsobj;
6753 	boolean_t	cb_json_as_int;
6754 	boolean_t	cb_json_pool_key_guid;
6755 } list_cbdata_t;
6756 
6757 
6758 /*
6759  * Given a list of columns to display, print an appropriate line. If
6760  * `vdev_name` is not NULL, we print `vdev_name` followed by a line of dashes.
6761  * If `vdev_name` is NULL, we print a line of the headers.
6762  */
6763 static void
print_line(list_cbdata_t * cb,const char * vdev_name)6764 print_line(list_cbdata_t *cb, const char *vdev_name)
6765 {
6766 	zprop_list_t *pl = cb->cb_proplist;
6767 	char headerbuf[ZPOOL_MAXPROPLEN];
6768 	const char *header;
6769 	boolean_t first = B_TRUE;
6770 	boolean_t right_justify;
6771 	size_t width = 0;
6772 
6773 	boolean_t print_header = (vdev_name == NULL);
6774 
6775 	for (; pl != NULL; pl = pl->pl_next) {
6776 		width = pl->pl_width;
6777 		if (first && cb->cb_verbose) {
6778 			/*
6779 			 * Reset the width to accommodate the verbose listing
6780 			 * of devices.
6781 			 */
6782 			width = cb->cb_namewidth;
6783 		}
6784 
6785 		if (!first)
6786 			(void) fputs("  ", stdout);
6787 
6788 		if (print_header) {
6789 			right_justify = B_FALSE;
6790 			if (pl->pl_prop != ZPROP_USERPROP) {
6791 				header = zpool_prop_column_name(pl->pl_prop);
6792 				right_justify = zpool_prop_align_right(
6793 				    pl->pl_prop);
6794 			} else {
6795 				int i;
6796 
6797 				for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
6798 					headerbuf[i] = toupper(
6799 					    pl->pl_user_prop[i]);
6800 				headerbuf[i] = '\0';
6801 				header = headerbuf;
6802 			}
6803 
6804 		}
6805 		/*
6806 		 * If `print_header` is false, we want to print a line of
6807 		 * dashes.
6808 		 */
6809 		else {
6810 			if (first) {
6811 				header = vdev_name;
6812 				right_justify = B_FALSE;
6813 			} else {
6814 				header = "-";
6815 				right_justify = B_TRUE;
6816 			}
6817 		}
6818 
6819 		if (pl->pl_next == NULL && !right_justify)
6820 			(void) fputs(header, stdout);
6821 		else if (right_justify)
6822 			(void) printf("%*s", (int)width, header);
6823 		else
6824 			(void) printf("%-*s", (int)width, header);
6825 
6826 		if (first)
6827 			first = B_FALSE;
6828 	}
6829 
6830 	(void) fputc('\n', stdout);
6831 }
6832 
6833 /*
6834  * Given a pool and a list of properties, print out all the properties according
6835  * to the described layout. Used by zpool_do_list().
6836  */
6837 static void
collect_pool(zpool_handle_t * zhp,list_cbdata_t * cb)6838 collect_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
6839 {
6840 	zprop_list_t *pl = cb->cb_proplist;
6841 	boolean_t first = B_TRUE;
6842 	char property[ZPOOL_MAXPROPLEN];
6843 	const char *propstr;
6844 	boolean_t right_justify;
6845 	size_t width;
6846 	zprop_source_t sourcetype = ZPROP_SRC_NONE;
6847 	nvlist_t *item, *d, *props;
6848 	item = d = props = NULL;
6849 
6850 	if (cb->cb_json) {
6851 		item = fnvlist_alloc();
6852 		props = fnvlist_alloc();
6853 		d = fnvlist_lookup_nvlist(cb->cb_jsobj, "pools");
6854 		if (d == NULL) {
6855 			fprintf(stderr, "pools obj not found.\n");
6856 			exit(1);
6857 		}
6858 		fill_pool_info(item, zhp, B_TRUE, cb->cb_json_as_int);
6859 	}
6860 
6861 	for (; pl != NULL; pl = pl->pl_next) {
6862 
6863 		width = pl->pl_width;
6864 		if (first && cb->cb_verbose) {
6865 			/*
6866 			 * Reset the width to accommodate the verbose listing
6867 			 * of devices.
6868 			 */
6869 			width = cb->cb_namewidth;
6870 		}
6871 
6872 		if (!cb->cb_json && !first) {
6873 			if (cb->cb_scripted)
6874 				(void) fputc('\t', stdout);
6875 			else
6876 				(void) fputs("  ", stdout);
6877 		} else {
6878 			first = B_FALSE;
6879 		}
6880 
6881 		right_justify = B_FALSE;
6882 		if (pl->pl_prop != ZPROP_USERPROP) {
6883 			if (zpool_get_prop(zhp, pl->pl_prop, property,
6884 			    sizeof (property), &sourcetype,
6885 			    cb->cb_literal) != 0)
6886 				propstr = "-";
6887 			else
6888 				propstr = property;
6889 
6890 			right_justify = zpool_prop_align_right(pl->pl_prop);
6891 		} else if ((zpool_prop_feature(pl->pl_user_prop) ||
6892 		    zpool_prop_unsupported(pl->pl_user_prop)) &&
6893 		    zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
6894 		    sizeof (property)) == 0) {
6895 			propstr = property;
6896 			sourcetype = ZPROP_SRC_LOCAL;
6897 		} else if (zfs_prop_user(pl->pl_user_prop) &&
6898 		    zpool_get_userprop(zhp, pl->pl_user_prop, property,
6899 		    sizeof (property), &sourcetype) == 0) {
6900 			propstr = property;
6901 		} else {
6902 			propstr = "-";
6903 		}
6904 
6905 		if (cb->cb_json) {
6906 			if (pl->pl_prop == ZPOOL_PROP_NAME)
6907 				continue;
6908 			const char *prop_name;
6909 			if (pl->pl_prop != ZPROP_USERPROP)
6910 				prop_name = zpool_prop_to_name(pl->pl_prop);
6911 			else
6912 				prop_name = pl->pl_user_prop;
6913 			(void) zprop_nvlist_one_property(
6914 			    prop_name, propstr,
6915 			    sourcetype, NULL, NULL, props, cb->cb_json_as_int);
6916 		} else {
6917 			/*
6918 			 * If this is being called in scripted mode, or if this
6919 			 * is the last column and it is left-justified, don't
6920 			 * include a width format specifier.
6921 			 */
6922 			if (cb->cb_scripted || (pl->pl_next == NULL &&
6923 			    !right_justify))
6924 				(void) fputs(propstr, stdout);
6925 			else if (right_justify)
6926 				(void) printf("%*s", (int)width, propstr);
6927 			else
6928 				(void) printf("%-*s", (int)width, propstr);
6929 		}
6930 	}
6931 
6932 	if (cb->cb_json) {
6933 		fnvlist_add_nvlist(item, "properties", props);
6934 		if (cb->cb_json_pool_key_guid) {
6935 			char pool_guid[256];
6936 			uint64_t guid = fnvlist_lookup_uint64(
6937 			    zpool_get_config(zhp, NULL),
6938 			    ZPOOL_CONFIG_POOL_GUID);
6939 			(void) snprintf(pool_guid, 256, "%llu",
6940 			    (u_longlong_t)guid);
6941 			fnvlist_add_nvlist(d, pool_guid, item);
6942 		} else {
6943 			fnvlist_add_nvlist(d, zpool_get_name(zhp),
6944 			    item);
6945 		}
6946 		fnvlist_free(props);
6947 		fnvlist_free(item);
6948 	} else
6949 		(void) fputc('\n', stdout);
6950 }
6951 
6952 static void
collect_vdev_prop(zpool_prop_t prop,uint64_t value,const char * str,boolean_t scripted,boolean_t valid,enum zfs_nicenum_format format,boolean_t json,nvlist_t * nvl,boolean_t as_int)6953 collect_vdev_prop(zpool_prop_t prop, uint64_t value, const char *str,
6954     boolean_t scripted, boolean_t valid, enum zfs_nicenum_format format,
6955     boolean_t json, nvlist_t *nvl, boolean_t as_int)
6956 {
6957 	char propval[64];
6958 	boolean_t fixed;
6959 	size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
6960 
6961 	switch (prop) {
6962 	case ZPOOL_PROP_SIZE:
6963 	case ZPOOL_PROP_NORMAL_SIZE:
6964 	case ZPOOL_PROP_SPECIAL_SIZE:
6965 	case ZPOOL_PROP_DEDUP_SIZE:
6966 	case ZPOOL_PROP_LOG_SIZE:
6967 	case ZPOOL_PROP_ELOG_SIZE:
6968 	case ZPOOL_PROP_SELOG_SIZE:
6969 	case ZPOOL_PROP_EXPANDSZ:
6970 	case ZPOOL_PROP_NORMAL_EXPANDSZ:
6971 	case ZPOOL_PROP_SPECIAL_EXPANDSZ:
6972 	case ZPOOL_PROP_DEDUP_EXPANDSZ:
6973 	case ZPOOL_PROP_LOG_EXPANDSZ:
6974 	case ZPOOL_PROP_ELOG_EXPANDSZ:
6975 	case ZPOOL_PROP_SELOG_EXPANDSZ:
6976 	case ZPOOL_PROP_CHECKPOINT:
6977 	case ZPOOL_PROP_DEDUPRATIO:
6978 	case ZPOOL_PROP_DEDUPCACHED:
6979 		if (value == 0)
6980 			(void) strlcpy(propval, "-", sizeof (propval));
6981 		else
6982 			zfs_nicenum_format(value, propval, sizeof (propval),
6983 			    format);
6984 		break;
6985 	case ZPOOL_PROP_FRAGMENTATION:
6986 	case ZPOOL_PROP_NORMAL_FRAGMENTATION:
6987 	case ZPOOL_PROP_SPECIAL_FRAGMENTATION:
6988 	case ZPOOL_PROP_DEDUP_FRAGMENTATION:
6989 	case ZPOOL_PROP_LOG_FRAGMENTATION:
6990 	case ZPOOL_PROP_ELOG_FRAGMENTATION:
6991 	case ZPOOL_PROP_SELOG_FRAGMENTATION:
6992 		if (value == ZFS_FRAG_INVALID) {
6993 			(void) strlcpy(propval, "-", sizeof (propval));
6994 		} else if (format == ZFS_NICENUM_RAW) {
6995 			(void) snprintf(propval, sizeof (propval), "%llu",
6996 			    (unsigned long long)value);
6997 		} else {
6998 			(void) snprintf(propval, sizeof (propval), "%llu%%",
6999 			    (unsigned long long)value);
7000 		}
7001 		break;
7002 	case ZPOOL_PROP_CAPACITY:
7003 	case ZPOOL_PROP_NORMAL_CAPACITY:
7004 	case ZPOOL_PROP_SPECIAL_CAPACITY:
7005 	case ZPOOL_PROP_DEDUP_CAPACITY:
7006 	case ZPOOL_PROP_LOG_CAPACITY:
7007 	case ZPOOL_PROP_ELOG_CAPACITY:
7008 	case ZPOOL_PROP_SELOG_CAPACITY:
7009 		/* capacity value is in parts-per-10,000 (aka permyriad) */
7010 		if (format == ZFS_NICENUM_RAW)
7011 			(void) snprintf(propval, sizeof (propval), "%llu",
7012 			    (unsigned long long)value / 100);
7013 		else
7014 			(void) snprintf(propval, sizeof (propval),
7015 			    value < 1000 ? "%1.2f%%" : value < 10000 ?
7016 			    "%2.1f%%" : "%3.0f%%", value / 100.0);
7017 		break;
7018 	case ZPOOL_PROP_HEALTH:
7019 		width = 8;
7020 		(void) strlcpy(propval, str, sizeof (propval));
7021 		break;
7022 	default:
7023 		zfs_nicenum_format(value, propval, sizeof (propval), format);
7024 	}
7025 
7026 	if (!valid)
7027 		(void) strlcpy(propval, "-", sizeof (propval));
7028 
7029 	if (json) {
7030 		(void) zprop_nvlist_one_property(zpool_prop_to_name(prop),
7031 		    propval, ZPROP_SRC_NONE, NULL, NULL, nvl, as_int);
7032 	} else {
7033 		if (scripted)
7034 			(void) printf("\t%s", propval);
7035 		else
7036 			(void) printf("  %*s", (int)width, propval);
7037 	}
7038 }
7039 
7040 /*
7041  * print static default line per vdev
7042  */
7043 static void
collect_list_stats(zpool_handle_t * zhp,const char * name,nvlist_t * nv,list_cbdata_t * cb,int depth,boolean_t isspare,nvlist_t * item)7044 collect_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
7045     list_cbdata_t *cb, int depth, boolean_t isspare, nvlist_t *item)
7046 {
7047 	nvlist_t **child;
7048 	vdev_stat_t *vs;
7049 	uint_t c, children = 0;
7050 	char *vname;
7051 	boolean_t scripted = cb->cb_scripted;
7052 	uint64_t islog = B_FALSE;
7053 	nvlist_t *props, *ent, *ch, *obj, *l2c, *sp;
7054 	props = ent = ch = obj = sp = l2c = NULL;
7055 
7056 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
7057 	    (uint64_t **)&vs, &c) == 0);
7058 
7059 	if (name != NULL) {
7060 		boolean_t toplevel = (vs->vs_space != 0);
7061 		uint64_t cap;
7062 		enum zfs_nicenum_format format;
7063 		const char *state;
7064 
7065 		if (cb->cb_literal)
7066 			format = ZFS_NICENUM_RAW;
7067 		else
7068 			format = ZFS_NICENUM_1024;
7069 
7070 		if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
7071 			return;
7072 
7073 		if (cb->cb_json) {
7074 			props = fnvlist_alloc();
7075 			ent = fnvlist_alloc();
7076 			fill_vdev_info(ent, zhp, (char *)name, B_FALSE,
7077 			    cb->cb_json_as_int);
7078 		} else {
7079 			if (scripted)
7080 				(void) printf("\t%s", name);
7081 			else if (strlen(name) + depth > cb->cb_namewidth)
7082 				(void) printf("%*s%s", depth, "", name);
7083 			else
7084 				(void) printf("%*s%s%*s", depth, "", name,
7085 				    (int)(cb->cb_namewidth - strlen(name) -
7086 				    depth), "");
7087 		}
7088 
7089 		/*
7090 		 * Print the properties for the individual vdevs. Some
7091 		 * properties are only applicable to toplevel vdevs. The
7092 		 * 'toplevel' boolean value is passed to the print_one_column()
7093 		 * to indicate that the value is valid.
7094 		 */
7095 		for (zprop_list_t *pl = cb->cb_proplist; pl != NULL;
7096 		    pl = pl->pl_next) {
7097 			switch (pl->pl_prop) {
7098 			case ZPOOL_PROP_SIZE:
7099 				if (VDEV_STAT_VALID(vs_pspace, c) &&
7100 				    vs->vs_pspace) {
7101 					collect_vdev_prop(
7102 					    ZPOOL_PROP_SIZE, vs->vs_pspace,
7103 					    NULL, scripted, B_TRUE, format,
7104 					    cb->cb_json, props,
7105 					    cb->cb_json_as_int);
7106 				} else {
7107 					collect_vdev_prop(
7108 					    ZPOOL_PROP_SIZE, vs->vs_space, NULL,
7109 					    scripted, toplevel, format,
7110 					    cb->cb_json, props,
7111 					    cb->cb_json_as_int);
7112 				}
7113 				break;
7114 			case ZPOOL_PROP_ALLOCATED:
7115 				collect_vdev_prop(ZPOOL_PROP_ALLOCATED,
7116 				    vs->vs_alloc, NULL, scripted, toplevel,
7117 				    format, cb->cb_json, props,
7118 				    cb->cb_json_as_int);
7119 				break;
7120 
7121 			case ZPOOL_PROP_FREE:
7122 				collect_vdev_prop(ZPOOL_PROP_FREE,
7123 				    vs->vs_space - vs->vs_alloc, NULL, scripted,
7124 				    toplevel, format, cb->cb_json, props,
7125 				    cb->cb_json_as_int);
7126 				break;
7127 
7128 			case ZPOOL_PROP_CHECKPOINT:
7129 				collect_vdev_prop(ZPOOL_PROP_CHECKPOINT,
7130 				    vs->vs_checkpoint_space, NULL, scripted,
7131 				    toplevel, format, cb->cb_json, props,
7132 				    cb->cb_json_as_int);
7133 				break;
7134 
7135 			case ZPOOL_PROP_EXPANDSZ:
7136 				collect_vdev_prop(ZPOOL_PROP_EXPANDSZ,
7137 				    vs->vs_esize, NULL, scripted, B_TRUE,
7138 				    format, cb->cb_json, props,
7139 				    cb->cb_json_as_int);
7140 				break;
7141 
7142 			case ZPOOL_PROP_FRAGMENTATION:
7143 				collect_vdev_prop(
7144 				    ZPOOL_PROP_FRAGMENTATION,
7145 				    vs->vs_fragmentation, NULL, scripted,
7146 				    (vs->vs_fragmentation != ZFS_FRAG_INVALID &&
7147 				    toplevel),
7148 				    format, cb->cb_json, props,
7149 				    cb->cb_json_as_int);
7150 				break;
7151 
7152 			case ZPOOL_PROP_CAPACITY:
7153 				cap = (vs->vs_space == 0) ?
7154 				    0 : (vs->vs_alloc * 10000 / vs->vs_space);
7155 				collect_vdev_prop(ZPOOL_PROP_CAPACITY, cap,
7156 				    NULL, scripted, toplevel, format,
7157 				    cb->cb_json, props, cb->cb_json_as_int);
7158 				break;
7159 
7160 			case ZPOOL_PROP_HEALTH:
7161 				state = zpool_state_to_name(vs->vs_state,
7162 				    vs->vs_aux);
7163 				if (isspare) {
7164 					if (vs->vs_aux == VDEV_AUX_SPARED)
7165 						state = "INUSE";
7166 					else if (vs->vs_state ==
7167 					    VDEV_STATE_HEALTHY)
7168 						state = "AVAIL";
7169 				}
7170 				collect_vdev_prop(ZPOOL_PROP_HEALTH, 0, state,
7171 				    scripted, B_TRUE, format, cb->cb_json,
7172 				    props, cb->cb_json_as_int);
7173 				break;
7174 
7175 			case ZPOOL_PROP_NAME:
7176 				break;
7177 
7178 			default:
7179 				collect_vdev_prop(pl->pl_prop, 0,
7180 				    NULL, scripted, B_FALSE, format,
7181 				    cb->cb_json, props, cb->cb_json_as_int);
7182 
7183 			}
7184 
7185 
7186 		}
7187 
7188 		if (cb->cb_json) {
7189 			fnvlist_add_nvlist(ent, "properties", props);
7190 			fnvlist_free(props);
7191 		} else
7192 			(void) fputc('\n', stdout);
7193 	}
7194 
7195 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
7196 	    &child, &children) != 0) {
7197 		if (cb->cb_json) {
7198 			fnvlist_add_nvlist(item, name, ent);
7199 			fnvlist_free(ent);
7200 		}
7201 		return;
7202 	}
7203 
7204 	if (cb->cb_json) {
7205 		ch = fnvlist_alloc();
7206 	}
7207 
7208 	/* list the normal vdevs first */
7209 	for (c = 0; c < children; c++) {
7210 		uint64_t ishole = B_FALSE;
7211 
7212 		if (nvlist_lookup_uint64(child[c],
7213 		    ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
7214 			continue;
7215 
7216 		if (nvlist_lookup_uint64(child[c],
7217 		    ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
7218 			continue;
7219 
7220 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
7221 			continue;
7222 
7223 		vname = zpool_vdev_name(g_zfs, zhp, child[c],
7224 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7225 
7226 		if (name == NULL || cb->cb_json != B_TRUE)
7227 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7228 			    B_FALSE, item);
7229 		else if (cb->cb_json) {
7230 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7231 			    B_FALSE, ch);
7232 		}
7233 		free(vname);
7234 	}
7235 
7236 	if (cb->cb_json) {
7237 		if (!nvlist_empty(ch))
7238 			fnvlist_add_nvlist(ent, "vdevs", ch);
7239 		fnvlist_free(ch);
7240 	}
7241 
7242 	/* list the classes: 'logs', 'dedup', and 'special' */
7243 	for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
7244 		boolean_t printed = B_FALSE;
7245 		if (cb->cb_json)
7246 			obj = fnvlist_alloc();
7247 		for (c = 0; c < children; c++) {
7248 			const char *bias = NULL;
7249 			const char *type = NULL;
7250 
7251 			if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
7252 			    &islog) == 0 && islog) {
7253 				bias = VDEV_ALLOC_CLASS_LOGS;
7254 			} else {
7255 				(void) nvlist_lookup_string(child[c],
7256 				    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
7257 				(void) nvlist_lookup_string(child[c],
7258 				    ZPOOL_CONFIG_TYPE, &type);
7259 			}
7260 			if (bias == NULL || strcmp(bias, class_name[n]) != 0)
7261 				continue;
7262 			if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
7263 				continue;
7264 
7265 			if (!printed && !cb->cb_json) {
7266 				print_line(cb, class_name[n]);
7267 				printed = B_TRUE;
7268 			}
7269 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
7270 			    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7271 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7272 			    B_FALSE, obj);
7273 			free(vname);
7274 		}
7275 		if (cb->cb_json) {
7276 			if (!nvlist_empty(obj))
7277 				fnvlist_add_nvlist(item, class_name[n], obj);
7278 			fnvlist_free(obj);
7279 		}
7280 	}
7281 
7282 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
7283 	    &child, &children) == 0 && children > 0) {
7284 		if (cb->cb_json) {
7285 			l2c = fnvlist_alloc();
7286 		} else {
7287 			print_line(cb, "cache");
7288 		}
7289 		for (c = 0; c < children; c++) {
7290 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
7291 			    cb->cb_name_flags);
7292 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7293 			    B_FALSE, l2c);
7294 			free(vname);
7295 		}
7296 		if (cb->cb_json) {
7297 			if (!nvlist_empty(l2c))
7298 				fnvlist_add_nvlist(item, "l2cache", l2c);
7299 			fnvlist_free(l2c);
7300 		}
7301 	}
7302 
7303 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
7304 	    &children) == 0 && children > 0) {
7305 		if (cb->cb_json) {
7306 			sp = fnvlist_alloc();
7307 		} else {
7308 			print_line(cb, "spare");
7309 		}
7310 		for (c = 0; c < children; c++) {
7311 			vname = zpool_vdev_name(g_zfs, zhp, child[c],
7312 			    cb->cb_name_flags);
7313 			collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7314 			    B_TRUE, sp);
7315 			free(vname);
7316 		}
7317 		if (cb->cb_json) {
7318 			if (!nvlist_empty(sp))
7319 				fnvlist_add_nvlist(item, "spares", sp);
7320 			fnvlist_free(sp);
7321 		}
7322 	}
7323 
7324 	if (name != NULL && cb->cb_json) {
7325 		fnvlist_add_nvlist(item, name, ent);
7326 		fnvlist_free(ent);
7327 	}
7328 }
7329 
7330 /*
7331  * Generic callback function to list a pool.
7332  */
7333 static int
list_callback(zpool_handle_t * zhp,void * data)7334 list_callback(zpool_handle_t *zhp, void *data)
7335 {
7336 	nvlist_t *p, *d, *nvdevs;
7337 	uint64_t guid;
7338 	char pool_guid[256];
7339 	const char *pool_name = zpool_get_name(zhp);
7340 	list_cbdata_t *cbp = data;
7341 	p = d = nvdevs = NULL;
7342 
7343 	collect_pool(zhp, cbp);
7344 
7345 	if (cbp->cb_verbose) {
7346 		nvlist_t *config, *nvroot;
7347 		config = zpool_get_config(zhp, NULL);
7348 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
7349 		    &nvroot) == 0);
7350 		if (cbp->cb_json) {
7351 			d = fnvlist_lookup_nvlist(cbp->cb_jsobj,
7352 			    "pools");
7353 			if (cbp->cb_json_pool_key_guid) {
7354 				guid = fnvlist_lookup_uint64(config,
7355 				    ZPOOL_CONFIG_POOL_GUID);
7356 				(void) snprintf(pool_guid, 256, "%llu",
7357 				    (u_longlong_t)guid);
7358 				p = fnvlist_lookup_nvlist(d, pool_guid);
7359 			} else {
7360 				p = fnvlist_lookup_nvlist(d, pool_name);
7361 			}
7362 			nvdevs = fnvlist_alloc();
7363 		}
7364 		collect_list_stats(zhp, NULL, nvroot, cbp, 0, B_FALSE, nvdevs);
7365 		if (cbp->cb_json) {
7366 			fnvlist_add_nvlist(p, "vdevs", nvdevs);
7367 			if (cbp->cb_json_pool_key_guid)
7368 				fnvlist_add_nvlist(d, pool_guid, p);
7369 			else
7370 				fnvlist_add_nvlist(d, pool_name, p);
7371 			fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
7372 			fnvlist_free(nvdevs);
7373 		}
7374 	}
7375 
7376 	return (0);
7377 }
7378 
7379 /*
7380  * Set the minimum pool/vdev name column width.  The width must be at least 9,
7381  * but may be as large as needed.
7382  */
7383 static int
get_namewidth_list(zpool_handle_t * zhp,void * data)7384 get_namewidth_list(zpool_handle_t *zhp, void *data)
7385 {
7386 	list_cbdata_t *cb = data;
7387 	int width;
7388 
7389 	width = get_namewidth(zhp, cb->cb_namewidth,
7390 	    cb->cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
7391 
7392 	if (width < 9)
7393 		width = 9;
7394 
7395 	cb->cb_namewidth = width;
7396 
7397 	return (0);
7398 }
7399 
7400 /*
7401  * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
7402  *
7403  *	-g	Display guid for individual vdev name.
7404  *	-H	Scripted mode.  Don't display headers, and separate properties
7405  *		by a single tab.
7406  *	-L	Follow links when resolving vdev path name.
7407  *	-o	List of properties to display.  Defaults to
7408  *		"name,size,allocated,free,expandsize,fragmentation,capacity,"
7409  *		"dedupratio,health,altroot"
7410  *	-p	Display values in parsable (exact) format.
7411  *	-P	Display full path for vdev name.
7412  *	-T	Display a timestamp in date(1) or Unix format
7413  *	-j	Display the output in JSON format
7414  *	--json-int	Display the numbers as integer instead of strings.
7415  *	--json-pool-key-guid  Set pool GUID as key for pool objects.
7416  *
7417  * List all pools in the system, whether or not they're healthy.  Output space
7418  * statistics for each one, as well as health status summary.
7419  */
7420 int
zpool_do_list(int argc,char ** argv)7421 zpool_do_list(int argc, char **argv)
7422 {
7423 	int c;
7424 	int ret = 0;
7425 	list_cbdata_t cb = { 0 };
7426 	static char default_props[] =
7427 	    "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
7428 	    "capacity,dedupratio,health,altroot";
7429 	char *props = default_props;
7430 	float interval = 0;
7431 	unsigned long count = 0;
7432 	zpool_list_t *list;
7433 	boolean_t first = B_TRUE;
7434 	nvlist_t *data = NULL;
7435 	current_prop_type = ZFS_TYPE_POOL;
7436 
7437 	struct option long_options[] = {
7438 		{"json", no_argument, NULL, 'j'},
7439 		{"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
7440 		{"json-pool-key-guid", no_argument, NULL,
7441 		    ZPOOL_OPTION_POOL_KEY_GUID},
7442 		{0, 0, 0, 0}
7443 	};
7444 
7445 	/* check options */
7446 	while ((c = getopt_long(argc, argv, ":gjHLo:pPT:v", long_options,
7447 	    NULL)) != -1) {
7448 		switch (c) {
7449 		case 'g':
7450 			cb.cb_name_flags |= VDEV_NAME_GUID;
7451 			break;
7452 		case 'H':
7453 			cb.cb_scripted = B_TRUE;
7454 			break;
7455 		case 'L':
7456 			cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
7457 			break;
7458 		case 'o':
7459 			props = optarg;
7460 			break;
7461 		case 'P':
7462 			cb.cb_name_flags |= VDEV_NAME_PATH;
7463 			break;
7464 		case 'p':
7465 			cb.cb_literal = B_TRUE;
7466 			break;
7467 		case 'j':
7468 			cb.cb_json = B_TRUE;
7469 			break;
7470 		case ZPOOL_OPTION_JSON_NUMS_AS_INT:
7471 			cb.cb_json_as_int = B_TRUE;
7472 			cb.cb_literal = B_TRUE;
7473 			break;
7474 		case ZPOOL_OPTION_POOL_KEY_GUID:
7475 			cb.cb_json_pool_key_guid = B_TRUE;
7476 			break;
7477 		case 'T':
7478 			get_timestamp_arg(*optarg);
7479 			break;
7480 		case 'v':
7481 			cb.cb_verbose = B_TRUE;
7482 			cb.cb_namewidth = 8;	/* 8 until precalc is avail */
7483 			break;
7484 		case ':':
7485 			(void) fprintf(stderr, gettext("missing argument for "
7486 			    "'%c' option\n"), optopt);
7487 			usage(B_FALSE);
7488 			break;
7489 		case '?':
7490 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7491 			    optopt);
7492 			usage(B_FALSE);
7493 		}
7494 	}
7495 
7496 	argc -= optind;
7497 	argv += optind;
7498 
7499 	if (!cb.cb_json && cb.cb_json_as_int) {
7500 		(void) fprintf(stderr, gettext("'--json-int' only works with"
7501 		    " '-j' option\n"));
7502 		usage(B_FALSE);
7503 	}
7504 
7505 	if (!cb.cb_json && cb.cb_json_pool_key_guid) {
7506 		(void) fprintf(stderr, gettext("'json-pool-key-guid' only"
7507 		    " works with '-j' option\n"));
7508 		usage(B_FALSE);
7509 	}
7510 
7511 	get_interval_count(&argc, argv, &interval, &count);
7512 
7513 	if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
7514 		usage(B_FALSE);
7515 
7516 	for (;;) {
7517 		if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
7518 		    ZFS_TYPE_POOL, cb.cb_literal, &ret)) == NULL)
7519 			return (1);
7520 
7521 		if (pool_list_count(list) == 0)
7522 			break;
7523 
7524 		if (cb.cb_json) {
7525 			cb.cb_jsobj = zpool_json_schema(0, 1);
7526 			data = fnvlist_alloc();
7527 			fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
7528 			fnvlist_free(data);
7529 		}
7530 
7531 		cb.cb_namewidth = 0;
7532 		(void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
7533 
7534 		if (timestamp_fmt != NODATE) {
7535 			if (cb.cb_json) {
7536 				if (cb.cb_json_as_int) {
7537 					fnvlist_add_uint64(cb.cb_jsobj, "time",
7538 					    time(NULL));
7539 				} else {
7540 					char ts[128];
7541 					get_timestamp(timestamp_fmt, ts, 128);
7542 					fnvlist_add_string(cb.cb_jsobj, "time",
7543 					    ts);
7544 				}
7545 			} else
7546 				print_timestamp(timestamp_fmt);
7547 		}
7548 
7549 		if (!cb.cb_scripted && (first || cb.cb_verbose) &&
7550 		    !cb.cb_json) {
7551 			print_line(&cb, NULL);
7552 			first = B_FALSE;
7553 		}
7554 		ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
7555 
7556 		if (ret == 0 && cb.cb_json)
7557 			zcmd_print_json(cb.cb_jsobj);
7558 		else if (ret != 0 && cb.cb_json)
7559 			nvlist_free(cb.cb_jsobj);
7560 
7561 		if (interval == 0)
7562 			break;
7563 
7564 		if (count != 0 && --count == 0)
7565 			break;
7566 
7567 		pool_list_free(list);
7568 
7569 		(void) fflush(stdout);
7570 		(void) fsleep(interval);
7571 	}
7572 
7573 	if (argc == 0 && !cb.cb_scripted && !cb.cb_json &&
7574 	    pool_list_count(list) == 0) {
7575 		(void) printf(gettext("no pools available\n"));
7576 		ret = 0;
7577 	}
7578 
7579 	pool_list_free(list);
7580 	zprop_free_list(cb.cb_proplist);
7581 	return (ret);
7582 }
7583 
7584 static int
zpool_do_attach_or_replace(int argc,char ** argv,int replacing)7585 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
7586 {
7587 	boolean_t force = B_FALSE;
7588 	boolean_t rebuild = B_FALSE;
7589 	boolean_t wait = B_FALSE;
7590 	int c;
7591 	nvlist_t *nvroot;
7592 	char *poolname, *old_disk, *new_disk;
7593 	zpool_handle_t *zhp;
7594 	nvlist_t *props = NULL;
7595 	char *propval;
7596 	int ret;
7597 
7598 	/* check options */
7599 	while ((c = getopt(argc, argv, "fo:sw")) != -1) {
7600 		switch (c) {
7601 		case 'f':
7602 			force = B_TRUE;
7603 			break;
7604 		case 'o':
7605 			if ((propval = strchr(optarg, '=')) == NULL) {
7606 				(void) fprintf(stderr, gettext("missing "
7607 				    "'=' for -o option\n"));
7608 				usage(B_FALSE);
7609 			}
7610 			*propval = '\0';
7611 			propval++;
7612 
7613 			if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
7614 			    (add_prop_list(optarg, propval, &props, B_TRUE)))
7615 				usage(B_FALSE);
7616 			break;
7617 		case 's':
7618 			rebuild = B_TRUE;
7619 			break;
7620 		case 'w':
7621 			wait = B_TRUE;
7622 			break;
7623 		case '?':
7624 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7625 			    optopt);
7626 			usage(B_FALSE);
7627 		}
7628 	}
7629 
7630 	argc -= optind;
7631 	argv += optind;
7632 
7633 	/* get pool name and check number of arguments */
7634 	if (argc < 1) {
7635 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
7636 		usage(B_FALSE);
7637 	}
7638 
7639 	poolname = argv[0];
7640 
7641 	if (argc < 2) {
7642 		(void) fprintf(stderr,
7643 		    gettext("missing <device> specification\n"));
7644 		usage(B_FALSE);
7645 	}
7646 
7647 	old_disk = argv[1];
7648 
7649 	if (argc < 3) {
7650 		if (!replacing) {
7651 			(void) fprintf(stderr,
7652 			    gettext("missing <new_device> specification\n"));
7653 			usage(B_FALSE);
7654 		}
7655 		new_disk = old_disk;
7656 		argc -= 1;
7657 		argv += 1;
7658 	} else {
7659 		new_disk = argv[2];
7660 		argc -= 2;
7661 		argv += 2;
7662 	}
7663 
7664 	if (argc > 1) {
7665 		(void) fprintf(stderr, gettext("too many arguments\n"));
7666 		usage(B_FALSE);
7667 	}
7668 
7669 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7670 		nvlist_free(props);
7671 		return (1);
7672 	}
7673 
7674 	if (zpool_get_config(zhp, NULL) == NULL) {
7675 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
7676 		    poolname);
7677 		zpool_close(zhp);
7678 		nvlist_free(props);
7679 		return (1);
7680 	}
7681 
7682 	/* unless manually specified use "ashift" pool property (if set) */
7683 	if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
7684 		int intval;
7685 		zprop_source_t src;
7686 		char strval[ZPOOL_MAXPROPLEN];
7687 
7688 		intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
7689 		if (src != ZPROP_SRC_DEFAULT) {
7690 			(void) sprintf(strval, "%" PRId32, intval);
7691 			verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
7692 			    &props, B_TRUE) == 0);
7693 		}
7694 	}
7695 
7696 	nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
7697 	    argc, argv);
7698 	if (nvroot == NULL) {
7699 		zpool_close(zhp);
7700 		nvlist_free(props);
7701 		return (1);
7702 	}
7703 
7704 	ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing,
7705 	    rebuild);
7706 
7707 	if (ret == 0 && wait) {
7708 		zpool_wait_activity_t activity = ZPOOL_WAIT_RESILVER;
7709 		char raidz_prefix[] = "raidz";
7710 		if (replacing) {
7711 			activity = ZPOOL_WAIT_REPLACE;
7712 		} else if (strncmp(old_disk,
7713 		    raidz_prefix, strlen(raidz_prefix)) == 0) {
7714 			activity = ZPOOL_WAIT_RAIDZ_EXPAND;
7715 		}
7716 		ret = zpool_wait(zhp, activity);
7717 	}
7718 
7719 	nvlist_free(props);
7720 	nvlist_free(nvroot);
7721 	zpool_close(zhp);
7722 
7723 	return (ret);
7724 }
7725 
7726 /*
7727  * zpool replace [-fsw] [-o property=value] <pool> <device> <new_device>
7728  *
7729  *	-f	Force attach, even if <new_device> appears to be in use.
7730  *	-s	Use sequential instead of healing reconstruction for resilver.
7731  *	-o	Set property=value.
7732  *	-w	Wait for replacing to complete before returning
7733  *
7734  * Replace <device> with <new_device>.
7735  */
7736 int
zpool_do_replace(int argc,char ** argv)7737 zpool_do_replace(int argc, char **argv)
7738 {
7739 	return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
7740 }
7741 
7742 /*
7743  * zpool attach [-fsw] [-o property=value] <pool> <vdev> <new_device>
7744  *
7745  *	-f	Force attach, even if <new_device> appears to be in use.
7746  *	-s	Use sequential instead of healing reconstruction for resilver.
7747  *	-o	Set property=value.
7748  *	-w	Wait for resilvering (mirror) or expansion (raidz) to complete
7749  *		before returning.
7750  *
7751  * Attach <new_device> to a <vdev>, where the vdev can be of type
7752  * device, mirror or raidz. If <vdev> is not part of a mirror, then <vdev> will
7753  * be transformed into a mirror of <vdev> and <new_device>. When a mirror
7754  * is involved, <new_device> will begin life with a DTL of [0, now], and will
7755  * immediately begin to resilver itself. For the raidz case, a expansion will
7756  * commence and reflow the raidz data across all the disks including the
7757  * <new_device>.
7758  */
7759 int
zpool_do_attach(int argc,char ** argv)7760 zpool_do_attach(int argc, char **argv)
7761 {
7762 	return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
7763 }
7764 
7765 /*
7766  * zpool detach [-f] <pool> <device>
7767  *
7768  *	-f	Force detach of <device>, even if DTLs argue against it
7769  *		(not supported yet)
7770  *
7771  * Detach a device from a mirror.  The operation will be refused if <device>
7772  * is the last device in the mirror, or if the DTLs indicate that this device
7773  * has the only valid copy of some data.
7774  */
7775 int
zpool_do_detach(int argc,char ** argv)7776 zpool_do_detach(int argc, char **argv)
7777 {
7778 	int c;
7779 	char *poolname, *path;
7780 	zpool_handle_t *zhp;
7781 	int ret;
7782 
7783 	/* check options */
7784 	while ((c = getopt(argc, argv, "")) != -1) {
7785 		switch (c) {
7786 		case '?':
7787 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7788 			    optopt);
7789 			usage(B_FALSE);
7790 		}
7791 	}
7792 
7793 	argc -= optind;
7794 	argv += optind;
7795 
7796 	/* get pool name and check number of arguments */
7797 	if (argc < 1) {
7798 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
7799 		usage(B_FALSE);
7800 	}
7801 
7802 	if (argc < 2) {
7803 		(void) fprintf(stderr,
7804 		    gettext("missing <device> specification\n"));
7805 		usage(B_FALSE);
7806 	}
7807 
7808 	poolname = argv[0];
7809 	path = argv[1];
7810 
7811 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7812 		return (1);
7813 
7814 	ret = zpool_vdev_detach(zhp, path);
7815 
7816 	zpool_close(zhp);
7817 
7818 	return (ret);
7819 }
7820 
7821 /*
7822  * zpool split [-gLnP] [-o prop=val] ...
7823  *		[-o mntopt] ...
7824  *		[-R altroot] <pool> <newpool> [<device> ...]
7825  *
7826  *	-g      Display guid for individual vdev name.
7827  *	-L	Follow links when resolving vdev path name.
7828  *	-n	Do not split the pool, but display the resulting layout if
7829  *		it were to be split.
7830  *	-o	Set property=value, or set mount options.
7831  *	-P	Display full path for vdev name.
7832  *	-R	Mount the split-off pool under an alternate root.
7833  *	-l	Load encryption keys while importing.
7834  *
7835  * Splits the named pool and gives it the new pool name.  Devices to be split
7836  * off may be listed, provided that no more than one device is specified
7837  * per top-level vdev mirror.  The newly split pool is left in an exported
7838  * state unless -R is specified.
7839  *
7840  * Restrictions: the top-level of the pool pool must only be made up of
7841  * mirrors; all devices in the pool must be healthy; no device may be
7842  * undergoing a resilvering operation.
7843  */
7844 int
zpool_do_split(int argc,char ** argv)7845 zpool_do_split(int argc, char **argv)
7846 {
7847 	char *srcpool, *newpool, *propval;
7848 	char *mntopts = NULL;
7849 	splitflags_t flags;
7850 	int c, ret = 0;
7851 	int ms_status = 0;
7852 	boolean_t loadkeys = B_FALSE;
7853 	zpool_handle_t *zhp;
7854 	nvlist_t *config, *props = NULL;
7855 
7856 	flags.dryrun = B_FALSE;
7857 	flags.import = B_FALSE;
7858 	flags.name_flags = 0;
7859 
7860 	/* check options */
7861 	while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
7862 		switch (c) {
7863 		case 'g':
7864 			flags.name_flags |= VDEV_NAME_GUID;
7865 			break;
7866 		case 'L':
7867 			flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
7868 			break;
7869 		case 'R':
7870 			flags.import = B_TRUE;
7871 			if (add_prop_list(
7872 			    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
7873 			    &props, B_TRUE) != 0) {
7874 				nvlist_free(props);
7875 				usage(B_FALSE);
7876 			}
7877 			break;
7878 		case 'l':
7879 			loadkeys = B_TRUE;
7880 			break;
7881 		case 'n':
7882 			flags.dryrun = B_TRUE;
7883 			break;
7884 		case 'o':
7885 			if ((propval = strchr(optarg, '=')) != NULL) {
7886 				*propval = '\0';
7887 				propval++;
7888 				if (add_prop_list(optarg, propval,
7889 				    &props, B_TRUE) != 0) {
7890 					nvlist_free(props);
7891 					usage(B_FALSE);
7892 				}
7893 			} else {
7894 				mntopts = optarg;
7895 			}
7896 			break;
7897 		case 'P':
7898 			flags.name_flags |= VDEV_NAME_PATH;
7899 			break;
7900 		case ':':
7901 			(void) fprintf(stderr, gettext("missing argument for "
7902 			    "'%c' option\n"), optopt);
7903 			usage(B_FALSE);
7904 			break;
7905 		case '?':
7906 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7907 			    optopt);
7908 			usage(B_FALSE);
7909 			break;
7910 		}
7911 	}
7912 
7913 	if (!flags.import && mntopts != NULL) {
7914 		(void) fprintf(stderr, gettext("setting mntopts is only "
7915 		    "valid when importing the pool\n"));
7916 		usage(B_FALSE);
7917 	}
7918 
7919 	if (!flags.import && loadkeys) {
7920 		(void) fprintf(stderr, gettext("loading keys is only "
7921 		    "valid when importing the pool\n"));
7922 		usage(B_FALSE);
7923 	}
7924 
7925 	argc -= optind;
7926 	argv += optind;
7927 
7928 	if (argc < 1) {
7929 		(void) fprintf(stderr, gettext("Missing pool name\n"));
7930 		usage(B_FALSE);
7931 	}
7932 	if (argc < 2) {
7933 		(void) fprintf(stderr, gettext("Missing new pool name\n"));
7934 		usage(B_FALSE);
7935 	}
7936 
7937 	srcpool = argv[0];
7938 	newpool = argv[1];
7939 
7940 	argc -= 2;
7941 	argv += 2;
7942 
7943 	if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
7944 		nvlist_free(props);
7945 		return (1);
7946 	}
7947 
7948 	config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
7949 	if (config == NULL) {
7950 		ret = 1;
7951 	} else {
7952 		if (flags.dryrun) {
7953 			(void) printf(gettext("would create '%s' with the "
7954 			    "following layout:\n\n"), newpool);
7955 			print_vdev_tree(NULL, newpool, config, 0, "",
7956 			    flags.name_flags);
7957 			print_vdev_tree(NULL, "dedup", config, 0,
7958 			    VDEV_ALLOC_BIAS_DEDUP, 0);
7959 			print_vdev_tree(NULL, "special", config, 0,
7960 			    VDEV_ALLOC_BIAS_SPECIAL, 0);
7961 		}
7962 	}
7963 
7964 	zpool_close(zhp);
7965 
7966 	if (ret != 0 || flags.dryrun || !flags.import) {
7967 		nvlist_free(config);
7968 		nvlist_free(props);
7969 		return (ret);
7970 	}
7971 
7972 	/*
7973 	 * The split was successful. Now we need to open the new
7974 	 * pool and import it.
7975 	 */
7976 	if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
7977 		nvlist_free(config);
7978 		nvlist_free(props);
7979 		return (1);
7980 	}
7981 
7982 	if (loadkeys) {
7983 		ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
7984 		if (ret != 0)
7985 			ret = 1;
7986 	}
7987 
7988 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL) {
7989 		ms_status = zpool_enable_datasets(zhp, mntopts, 0,
7990 		    mount_tp_nthr);
7991 		if (ms_status == EZFS_SHAREFAILED) {
7992 			(void) fprintf(stderr, gettext("Split was successful, "
7993 			    "datasets are mounted but sharing of some datasets "
7994 			    "has failed\n"));
7995 		} else if (ms_status == EZFS_MOUNTFAILED) {
7996 			(void) fprintf(stderr, gettext("Split was successful"
7997 			    ", but some datasets could not be mounted\n"));
7998 			(void) fprintf(stderr, gettext("Try doing '%s' with a "
7999 			    "different altroot\n"), "zpool import");
8000 		}
8001 	}
8002 	zpool_close(zhp);
8003 	nvlist_free(config);
8004 	nvlist_free(props);
8005 
8006 	return (ret);
8007 }
8008 
8009 
8010 /*
8011  * zpool online [--power] <pool> <device> ...
8012  *
8013  * --power: Power on the enclosure slot to the drive (if possible)
8014  */
8015 int
zpool_do_online(int argc,char ** argv)8016 zpool_do_online(int argc, char **argv)
8017 {
8018 	int c, i;
8019 	char *poolname;
8020 	zpool_handle_t *zhp;
8021 	int ret = 0;
8022 	vdev_state_t newstate;
8023 	int flags = 0;
8024 	boolean_t is_power_on = B_FALSE;
8025 	struct option long_options[] = {
8026 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8027 		{0, 0, 0, 0}
8028 	};
8029 
8030 	/* check options */
8031 	while ((c = getopt_long(argc, argv, "e", long_options, NULL)) != -1) {
8032 		switch (c) {
8033 		case 'e':
8034 			flags |= ZFS_ONLINE_EXPAND;
8035 			break;
8036 		case ZPOOL_OPTION_POWER:
8037 			is_power_on = B_TRUE;
8038 			break;
8039 		case '?':
8040 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8041 			    optopt);
8042 			usage(B_FALSE);
8043 		}
8044 	}
8045 
8046 	if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8047 		is_power_on = B_TRUE;
8048 
8049 	argc -= optind;
8050 	argv += optind;
8051 
8052 	/* get pool name and check number of arguments */
8053 	if (argc < 1) {
8054 		(void) fprintf(stderr, gettext("missing pool name\n"));
8055 		usage(B_FALSE);
8056 	}
8057 	if (argc < 2) {
8058 		(void) fprintf(stderr, gettext("missing device name\n"));
8059 		usage(B_FALSE);
8060 	}
8061 
8062 	poolname = argv[0];
8063 
8064 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8065 		(void) fprintf(stderr, gettext("failed to open pool "
8066 		    "\"%s\""), poolname);
8067 		return (1);
8068 	}
8069 
8070 	for (i = 1; i < argc; i++) {
8071 		vdev_state_t oldstate;
8072 		boolean_t avail_spare, l2cache;
8073 		int rc;
8074 
8075 		if (is_power_on) {
8076 			rc = zpool_power_on_and_disk_wait(zhp, argv[i]);
8077 			if (rc == ENOTSUP) {
8078 				(void) fprintf(stderr,
8079 				    gettext("Power control not supported\n"));
8080 			}
8081 			if (rc != 0)
8082 				return (rc);
8083 		}
8084 
8085 		nvlist_t *tgt = zpool_find_vdev(zhp, argv[i], &avail_spare,
8086 		    &l2cache, NULL);
8087 		if (tgt == NULL) {
8088 			ret = 1;
8089 			(void) fprintf(stderr, gettext("couldn't find device "
8090 			"\"%s\" in pool \"%s\"\n"), argv[i], poolname);
8091 			continue;
8092 		}
8093 		uint_t vsc;
8094 		oldstate = ((vdev_stat_t *)fnvlist_lookup_uint64_array(tgt,
8095 		    ZPOOL_CONFIG_VDEV_STATS, &vsc))->vs_state;
8096 		if ((rc = zpool_vdev_online(zhp, argv[i], flags,
8097 		    &newstate)) == 0) {
8098 			if (newstate != VDEV_STATE_HEALTHY) {
8099 				(void) printf(gettext("warning: device '%s' "
8100 				    "onlined, but remains in faulted state\n"),
8101 				    argv[i]);
8102 				if (newstate == VDEV_STATE_FAULTED)
8103 					(void) printf(gettext("use 'zpool "
8104 					    "clear' to restore a faulted "
8105 					    "device\n"));
8106 				else
8107 					(void) printf(gettext("use 'zpool "
8108 					    "replace' to replace devices "
8109 					    "that are no longer present\n"));
8110 				if ((flags & ZFS_ONLINE_EXPAND)) {
8111 					(void) printf(gettext("%s: failed "
8112 					    "to expand usable space on "
8113 					    "unhealthy device '%s'\n"),
8114 					    (oldstate >= VDEV_STATE_DEGRADED ?
8115 					    "error" : "warning"), argv[i]);
8116 					if (oldstate >= VDEV_STATE_DEGRADED) {
8117 						ret = 1;
8118 						break;
8119 					}
8120 				}
8121 			}
8122 		} else {
8123 			(void) fprintf(stderr, gettext("Failed to online "
8124 			    "\"%s\" in pool \"%s\": %d\n"),
8125 			    argv[i], poolname, rc);
8126 			ret = 1;
8127 		}
8128 	}
8129 
8130 	zpool_close(zhp);
8131 
8132 	return (ret);
8133 }
8134 
8135 /*
8136  * zpool offline [-ft]|[--power] <pool> <device> ...
8137  *
8138  *
8139  *	-f	Force the device into a faulted state.
8140  *
8141  *	-t	Only take the device off-line temporarily.  The offline/faulted
8142  *		state will not be persistent across reboots.
8143  *
8144  *	--power Power off the enclosure slot to the drive (if possible)
8145  */
8146 int
zpool_do_offline(int argc,char ** argv)8147 zpool_do_offline(int argc, char **argv)
8148 {
8149 	int c, i;
8150 	char *poolname;
8151 	zpool_handle_t *zhp;
8152 	int ret = 0;
8153 	boolean_t istmp = B_FALSE;
8154 	boolean_t fault = B_FALSE;
8155 	boolean_t is_power_off = B_FALSE;
8156 
8157 	struct option long_options[] = {
8158 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8159 		{0, 0, 0, 0}
8160 	};
8161 
8162 	/* check options */
8163 	while ((c = getopt_long(argc, argv, "ft", long_options, NULL)) != -1) {
8164 		switch (c) {
8165 		case 'f':
8166 			fault = B_TRUE;
8167 			break;
8168 		case 't':
8169 			istmp = B_TRUE;
8170 			break;
8171 		case ZPOOL_OPTION_POWER:
8172 			is_power_off = B_TRUE;
8173 			break;
8174 		case '?':
8175 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8176 			    optopt);
8177 			usage(B_FALSE);
8178 		}
8179 	}
8180 
8181 	if (is_power_off && fault) {
8182 		(void) fprintf(stderr,
8183 		    gettext("-0 and -f cannot be used together\n"));
8184 		usage(B_FALSE);
8185 	}
8186 
8187 	if (is_power_off && istmp) {
8188 		(void) fprintf(stderr,
8189 		    gettext("-0 and -t cannot be used together\n"));
8190 		usage(B_FALSE);
8191 	}
8192 
8193 	argc -= optind;
8194 	argv += optind;
8195 
8196 	/* get pool name and check number of arguments */
8197 	if (argc < 1) {
8198 		(void) fprintf(stderr, gettext("missing pool name\n"));
8199 		usage(B_FALSE);
8200 	}
8201 	if (argc < 2) {
8202 		(void) fprintf(stderr, gettext("missing device name\n"));
8203 		usage(B_FALSE);
8204 	}
8205 
8206 	poolname = argv[0];
8207 
8208 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8209 		(void) fprintf(stderr, gettext("failed to open pool "
8210 		    "\"%s\""), poolname);
8211 		return (1);
8212 	}
8213 
8214 	for (i = 1; i < argc; i++) {
8215 		uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
8216 		if (is_power_off) {
8217 			/*
8218 			 * Note: we have to power off first, then set REMOVED,
8219 			 * or else zpool_vdev_set_removed_state() returns
8220 			 * EAGAIN.
8221 			 */
8222 			ret = zpool_power_off(zhp, argv[i]);
8223 			if (ret != 0) {
8224 				(void) fprintf(stderr, "%s %s %d\n",
8225 				    gettext("unable to power off slot for"),
8226 				    argv[i], ret);
8227 			}
8228 			(void) zpool_vdev_set_removed_state(zhp, guid,
8229 			    VDEV_AUX_NONE);
8230 
8231 		} else if (fault) {
8232 			vdev_aux_t aux;
8233 			if (istmp == B_FALSE) {
8234 				/* Force the fault to persist across imports */
8235 				aux = VDEV_AUX_EXTERNAL_PERSIST;
8236 			} else {
8237 				aux = VDEV_AUX_EXTERNAL;
8238 			}
8239 
8240 			if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
8241 				ret = 1;
8242 		} else {
8243 			if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
8244 				ret = 1;
8245 		}
8246 	}
8247 
8248 	zpool_close(zhp);
8249 
8250 	return (ret);
8251 }
8252 
8253 /*
8254  * zpool clear [--power] <pool> [device]
8255  *
8256  * Clear all errors associated with a pool or a particular device.
8257  */
8258 int
zpool_do_clear(int argc,char ** argv)8259 zpool_do_clear(int argc, char **argv)
8260 {
8261 	int c;
8262 	int ret = 0;
8263 	boolean_t is_power_on = B_FALSE;
8264 	nvlist_t *policy = NULL;
8265 	zpool_handle_t *zhp;
8266 	char *pool, *device;
8267 
8268 	struct option long_options[] = {
8269 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8270 		{0, 0, 0, 0}
8271 	};
8272 
8273 	/* check options */
8274 	while ((c = getopt_long(argc, argv, "", long_options,
8275 	    NULL)) != -1) {
8276 		switch (c) {
8277 		case ZPOOL_OPTION_POWER:
8278 			is_power_on = B_TRUE;
8279 			break;
8280 		case '?':
8281 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8282 			    optopt);
8283 			usage(B_FALSE);
8284 		}
8285 	}
8286 
8287 	if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8288 		is_power_on = B_TRUE;
8289 
8290 	argc -= optind;
8291 	argv += optind;
8292 
8293 	if (argc < 1) {
8294 		(void) fprintf(stderr, gettext("missing pool name\n"));
8295 		usage(B_FALSE);
8296 	}
8297 
8298 	if (argc > 2) {
8299 		(void) fprintf(stderr, gettext("too many arguments\n"));
8300 		usage(B_FALSE);
8301 	}
8302 
8303 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0)
8304 		return (1);
8305 
8306 	pool = argv[0];
8307 	device = argc == 2 ? argv[1] : NULL;
8308 
8309 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
8310 		nvlist_free(policy);
8311 		return (1);
8312 	}
8313 
8314 	if (is_power_on) {
8315 		if (device == NULL) {
8316 			(void) zpool_power_on_pool_and_wait_for_devices(zhp);
8317 		} else {
8318 			(void) zpool_power_on_and_disk_wait(zhp, device);
8319 		}
8320 	}
8321 
8322 	if (zpool_clear(zhp, device, policy) != 0)
8323 		ret = 1;
8324 
8325 	zpool_close(zhp);
8326 
8327 	nvlist_free(policy);
8328 
8329 	return (ret);
8330 }
8331 
8332 /*
8333  * zpool reguid [-g <guid>] <pool>
8334  */
8335 int
zpool_do_reguid(int argc,char ** argv)8336 zpool_do_reguid(int argc, char **argv)
8337 {
8338 	uint64_t guid;
8339 	uint64_t *guidp = NULL;
8340 	int c;
8341 	char *endptr;
8342 	char *poolname;
8343 	zpool_handle_t *zhp;
8344 	int ret = 0;
8345 
8346 	/* check options */
8347 	while ((c = getopt(argc, argv, "g:")) != -1) {
8348 		switch (c) {
8349 		case 'g':
8350 			errno = 0;
8351 			guid = strtoull(optarg, &endptr, 10);
8352 			if (errno != 0 || *endptr != '\0') {
8353 				(void) fprintf(stderr,
8354 				    gettext("invalid GUID: %s\n"), optarg);
8355 				usage(B_FALSE);
8356 			}
8357 			guidp = &guid;
8358 			break;
8359 		case '?':
8360 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8361 			    optopt);
8362 			usage(B_FALSE);
8363 		}
8364 	}
8365 
8366 	argc -= optind;
8367 	argv += optind;
8368 
8369 	/* get pool name and check number of arguments */
8370 	if (argc < 1) {
8371 		(void) fprintf(stderr, gettext("missing pool name\n"));
8372 		usage(B_FALSE);
8373 	}
8374 
8375 	if (argc > 1) {
8376 		(void) fprintf(stderr, gettext("too many arguments\n"));
8377 		usage(B_FALSE);
8378 	}
8379 
8380 	poolname = argv[0];
8381 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
8382 		return (1);
8383 
8384 	ret = zpool_set_guid(zhp, guidp);
8385 
8386 	zpool_close(zhp);
8387 	return (ret);
8388 }
8389 
8390 
8391 /*
8392  * zpool reopen <pool>
8393  *
8394  * Reopen the pool so that the kernel can update the sizes of all vdevs.
8395  */
8396 int
zpool_do_reopen(int argc,char ** argv)8397 zpool_do_reopen(int argc, char **argv)
8398 {
8399 	int c;
8400 	int ret = 0;
8401 	boolean_t scrub_restart = B_TRUE;
8402 
8403 	/* check options */
8404 	while ((c = getopt(argc, argv, "n")) != -1) {
8405 		switch (c) {
8406 		case 'n':
8407 			scrub_restart = B_FALSE;
8408 			break;
8409 		case '?':
8410 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8411 			    optopt);
8412 			usage(B_FALSE);
8413 		}
8414 	}
8415 
8416 	argc -= optind;
8417 	argv += optind;
8418 
8419 	/* if argc == 0 we will execute zpool_reopen_one on all pools */
8420 	ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8421 	    B_FALSE, zpool_reopen_one, &scrub_restart);
8422 
8423 	return (ret);
8424 }
8425 
8426 typedef struct scrub_cbdata {
8427 	int	cb_type;
8428 	pool_scrub_cmd_t cb_scrub_cmd;
8429 	time_t	cb_date_start;
8430 	time_t	cb_date_end;
8431 } scrub_cbdata_t;
8432 
8433 static boolean_t
zpool_has_checkpoint(zpool_handle_t * zhp)8434 zpool_has_checkpoint(zpool_handle_t *zhp)
8435 {
8436 	nvlist_t *config, *nvroot;
8437 
8438 	config = zpool_get_config(zhp, NULL);
8439 
8440 	if (config != NULL) {
8441 		pool_checkpoint_stat_t *pcs = NULL;
8442 		uint_t c;
8443 
8444 		nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
8445 		(void) nvlist_lookup_uint64_array(nvroot,
8446 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
8447 
8448 		if (pcs == NULL || pcs->pcs_state == CS_NONE)
8449 			return (B_FALSE);
8450 
8451 		assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
8452 		    pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
8453 		return (B_TRUE);
8454 	}
8455 
8456 	return (B_FALSE);
8457 }
8458 
8459 static int
scrub_callback(zpool_handle_t * zhp,void * data)8460 scrub_callback(zpool_handle_t *zhp, void *data)
8461 {
8462 	scrub_cbdata_t *cb = data;
8463 	int err;
8464 
8465 	/*
8466 	 * Ignore faulted pools.
8467 	 */
8468 	if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
8469 		(void) fprintf(stderr, gettext("cannot scan '%s': pool is "
8470 		    "currently unavailable\n"), zpool_get_name(zhp));
8471 		return (1);
8472 	}
8473 
8474 	err = zpool_scan_range(zhp, cb->cb_type, cb->cb_scrub_cmd,
8475 	    cb->cb_date_start, cb->cb_date_end);
8476 	if (err == 0 && zpool_has_checkpoint(zhp) &&
8477 	    cb->cb_type == POOL_SCAN_SCRUB) {
8478 		(void) printf(gettext("warning: will not scrub state that "
8479 		    "belongs to the checkpoint of pool '%s'\n"),
8480 		    zpool_get_name(zhp));
8481 	}
8482 
8483 	return (err != 0);
8484 }
8485 
8486 static int
wait_callback(zpool_handle_t * zhp,void * data)8487 wait_callback(zpool_handle_t *zhp, void *data)
8488 {
8489 	zpool_wait_activity_t *act = data;
8490 	return (zpool_wait(zhp, *act));
8491 }
8492 
8493 static time_t
date_string_to_sec(const char * timestr,boolean_t rounding)8494 date_string_to_sec(const char *timestr, boolean_t rounding)
8495 {
8496 	struct tm tm = {0};
8497 	int adjustment = rounding ? 1 : 0;
8498 
8499 	/* Allow mktime to determine timezone. */
8500 	tm.tm_isdst = -1;
8501 
8502 	if (strptime(timestr, "%Y-%m-%d %H:%M", &tm) == NULL) {
8503 		if (strptime(timestr, "%Y-%m-%d", &tm) == NULL) {
8504 			fprintf(stderr, gettext("Failed to parse the date.\n"));
8505 			usage(B_FALSE);
8506 		}
8507 		adjustment *= 24 * 60 * 60;
8508 	} else {
8509 		adjustment *= 60;
8510 	}
8511 
8512 	return (mktime(&tm) + adjustment);
8513 }
8514 
8515 /*
8516  * zpool scrub [-e | -s | -p | -C | -E | -S] [-w] [-a | <pool> ...]
8517  *
8518  *	-a	Scrub all pools.
8519  *	-e	Only scrub blocks in the error log.
8520  *	-E	End date of scrub.
8521  *	-S	Start date of scrub.
8522  *	-s	Stop.  Stops any in-progress scrub.
8523  *	-p	Pause. Pause in-progress scrub.
8524  *	-w	Wait.  Blocks until scrub has completed.
8525  *	-C	Scrub from last saved txg.
8526  */
8527 int
zpool_do_scrub(int argc,char ** argv)8528 zpool_do_scrub(int argc, char **argv)
8529 {
8530 	int c;
8531 	scrub_cbdata_t cb;
8532 	boolean_t wait = B_FALSE;
8533 	int error;
8534 
8535 	cb.cb_type = POOL_SCAN_SCRUB;
8536 	cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8537 	cb.cb_date_start = cb.cb_date_end = 0;
8538 
8539 	boolean_t is_error_scrub = B_FALSE;
8540 	boolean_t is_pause = B_FALSE;
8541 	boolean_t is_stop = B_FALSE;
8542 	boolean_t is_txg_continue = B_FALSE;
8543 	boolean_t scrub_all = B_FALSE;
8544 
8545 	/* check options */
8546 	while ((c = getopt(argc, argv, "aspweCE:S:")) != -1) {
8547 		switch (c) {
8548 		case 'a':
8549 			scrub_all = B_TRUE;
8550 			break;
8551 		case 'e':
8552 			is_error_scrub = B_TRUE;
8553 			break;
8554 		case 'E':
8555 			/*
8556 			 * Round the date. It's better to scrub more data than
8557 			 * less. This also makes the date inclusive.
8558 			 */
8559 			cb.cb_date_end = date_string_to_sec(optarg, B_TRUE);
8560 			break;
8561 		case 's':
8562 			is_stop = B_TRUE;
8563 			break;
8564 		case 'S':
8565 			cb.cb_date_start = date_string_to_sec(optarg, B_FALSE);
8566 			break;
8567 		case 'p':
8568 			is_pause = B_TRUE;
8569 			break;
8570 		case 'w':
8571 			wait = B_TRUE;
8572 			break;
8573 		case 'C':
8574 			is_txg_continue = B_TRUE;
8575 			break;
8576 		case '?':
8577 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8578 			    optopt);
8579 			usage(B_FALSE);
8580 		}
8581 	}
8582 
8583 	if (is_pause && is_stop) {
8584 		(void) fprintf(stderr, gettext("invalid option "
8585 		    "combination: -s and -p are mutually exclusive\n"));
8586 		usage(B_FALSE);
8587 	} else if (is_pause && is_txg_continue) {
8588 		(void) fprintf(stderr, gettext("invalid option "
8589 		    "combination: -p and -C are mutually exclusive\n"));
8590 		usage(B_FALSE);
8591 	} else if (is_stop && is_txg_continue) {
8592 		(void) fprintf(stderr, gettext("invalid option "
8593 		    "combination: -s and -C are mutually exclusive\n"));
8594 		usage(B_FALSE);
8595 	} else if (is_error_scrub && is_txg_continue) {
8596 		(void) fprintf(stderr, gettext("invalid option "
8597 		    "combination: -e and -C are mutually exclusive\n"));
8598 		usage(B_FALSE);
8599 	} else {
8600 		if (is_error_scrub)
8601 			cb.cb_type = POOL_SCAN_ERRORSCRUB;
8602 
8603 		if (is_pause) {
8604 			cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
8605 		} else if (is_stop) {
8606 			cb.cb_type = POOL_SCAN_NONE;
8607 		} else if (is_txg_continue) {
8608 			cb.cb_scrub_cmd = POOL_SCRUB_FROM_LAST_TXG;
8609 		} else {
8610 			cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8611 		}
8612 	}
8613 
8614 	if ((cb.cb_date_start != 0 || cb.cb_date_end != 0) &&
8615 	    cb.cb_scrub_cmd != POOL_SCRUB_NORMAL) {
8616 		(void) fprintf(stderr, gettext("invalid option combination: "
8617 		    "start/end date is available only with normal scrub\n"));
8618 		usage(B_FALSE);
8619 	}
8620 	if (cb.cb_date_start != 0 && cb.cb_date_end != 0 &&
8621 	    cb.cb_date_start > cb.cb_date_end) {
8622 		(void) fprintf(stderr, gettext("invalid arguments: "
8623 		    "end date has to be later than start date\n"));
8624 		usage(B_FALSE);
8625 	}
8626 
8627 	if (wait && (cb.cb_type == POOL_SCAN_NONE ||
8628 	    cb.cb_scrub_cmd == POOL_SCRUB_PAUSE)) {
8629 		(void) fprintf(stderr, gettext("invalid option combination: "
8630 		    "-w cannot be used with -p or -s\n"));
8631 		usage(B_FALSE);
8632 	}
8633 
8634 	argc -= optind;
8635 	argv += optind;
8636 
8637 	if (argc < 1 && !scrub_all) {
8638 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
8639 		usage(B_FALSE);
8640 	}
8641 
8642 	error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8643 	    B_FALSE, scrub_callback, &cb);
8644 
8645 	if (wait && !error) {
8646 		zpool_wait_activity_t act = ZPOOL_WAIT_SCRUB;
8647 		error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8648 		    B_FALSE, wait_callback, &act);
8649 	}
8650 
8651 	return (error);
8652 }
8653 
8654 /*
8655  * zpool resilver <pool> ...
8656  *
8657  *	Restarts any in-progress resilver
8658  */
8659 int
zpool_do_resilver(int argc,char ** argv)8660 zpool_do_resilver(int argc, char **argv)
8661 {
8662 	int c;
8663 	scrub_cbdata_t cb;
8664 
8665 	cb.cb_type = POOL_SCAN_RESILVER;
8666 	cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8667 	cb.cb_date_start = cb.cb_date_end = 0;
8668 
8669 	/* check options */
8670 	while ((c = getopt(argc, argv, "")) != -1) {
8671 		switch (c) {
8672 		case '?':
8673 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8674 			    optopt);
8675 			usage(B_FALSE);
8676 		}
8677 	}
8678 
8679 	argc -= optind;
8680 	argv += optind;
8681 
8682 	if (argc < 1) {
8683 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
8684 		usage(B_FALSE);
8685 	}
8686 
8687 	return (for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8688 	    B_FALSE, scrub_callback, &cb));
8689 }
8690 
8691 /*
8692  * zpool trim [-d] [-r <rate>] [-c | -s] <-a | pool> [<device> ...]
8693  *
8694  *	-a		Trim all pools.
8695  *	-c		Cancel. Ends any in-progress trim.
8696  *	-d		Secure trim.  Requires kernel and device support.
8697  *	-r <rate>	Sets the TRIM rate in bytes (per second). Supports
8698  *			adding a multiplier suffix such as 'k' or 'm'.
8699  *	-s		Suspend. TRIM can then be restarted with no flags.
8700  *	-w		Wait. Blocks until trimming has completed.
8701  */
8702 int
zpool_do_trim(int argc,char ** argv)8703 zpool_do_trim(int argc, char **argv)
8704 {
8705 	struct option long_options[] = {
8706 		{"cancel",	no_argument,		NULL,	'c'},
8707 		{"secure",	no_argument,		NULL,	'd'},
8708 		{"rate",	required_argument,	NULL,	'r'},
8709 		{"suspend",	no_argument,		NULL,	's'},
8710 		{"wait",	no_argument,		NULL,	'w'},
8711 		{"all",		no_argument,		NULL,	'a'},
8712 		{0, 0, 0, 0}
8713 	};
8714 
8715 	pool_trim_func_t cmd_type = POOL_TRIM_START;
8716 	uint64_t rate = 0;
8717 	boolean_t secure = B_FALSE;
8718 	boolean_t wait = B_FALSE;
8719 	boolean_t trimall = B_FALSE;
8720 	int error;
8721 
8722 	int c;
8723 	while ((c = getopt_long(argc, argv, "acdr:sw", long_options, NULL))
8724 	    != -1) {
8725 		switch (c) {
8726 		case 'a':
8727 			trimall = B_TRUE;
8728 			break;
8729 		case 'c':
8730 			if (cmd_type != POOL_TRIM_START &&
8731 			    cmd_type != POOL_TRIM_CANCEL) {
8732 				(void) fprintf(stderr, gettext("-c cannot be "
8733 				    "combined with other options\n"));
8734 				usage(B_FALSE);
8735 			}
8736 			cmd_type = POOL_TRIM_CANCEL;
8737 			break;
8738 		case 'd':
8739 			if (cmd_type != POOL_TRIM_START) {
8740 				(void) fprintf(stderr, gettext("-d cannot be "
8741 				    "combined with the -c or -s options\n"));
8742 				usage(B_FALSE);
8743 			}
8744 			secure = B_TRUE;
8745 			break;
8746 		case 'r':
8747 			if (cmd_type != POOL_TRIM_START) {
8748 				(void) fprintf(stderr, gettext("-r cannot be "
8749 				    "combined with the -c or -s options\n"));
8750 				usage(B_FALSE);
8751 			}
8752 			if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
8753 				(void) fprintf(stderr, "%s: %s\n",
8754 				    gettext("invalid value for rate"),
8755 				    libzfs_error_description(g_zfs));
8756 				usage(B_FALSE);
8757 			}
8758 			break;
8759 		case 's':
8760 			if (cmd_type != POOL_TRIM_START &&
8761 			    cmd_type != POOL_TRIM_SUSPEND) {
8762 				(void) fprintf(stderr, gettext("-s cannot be "
8763 				    "combined with other options\n"));
8764 				usage(B_FALSE);
8765 			}
8766 			cmd_type = POOL_TRIM_SUSPEND;
8767 			break;
8768 		case 'w':
8769 			wait = B_TRUE;
8770 			break;
8771 		case '?':
8772 			if (optopt != 0) {
8773 				(void) fprintf(stderr,
8774 				    gettext("invalid option '%c'\n"), optopt);
8775 			} else {
8776 				(void) fprintf(stderr,
8777 				    gettext("invalid option '%s'\n"),
8778 				    argv[optind - 1]);
8779 			}
8780 			usage(B_FALSE);
8781 		}
8782 	}
8783 
8784 	argc -= optind;
8785 	argv += optind;
8786 
8787 	trimflags_t trim_flags = {
8788 		.secure = secure,
8789 		.rate = rate,
8790 		.wait = wait,
8791 	};
8792 
8793 	trim_cbdata_t cbdata = {
8794 		.trim_flags = trim_flags,
8795 		.cmd_type = cmd_type
8796 	};
8797 
8798 	if (argc < 1 && !trimall) {
8799 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
8800 		usage(B_FALSE);
8801 	}
8802 
8803 	if (wait && (cmd_type != POOL_TRIM_START)) {
8804 		(void) fprintf(stderr, gettext("-w cannot be used with -c or "
8805 		    "-s options\n"));
8806 		usage(B_FALSE);
8807 	}
8808 
8809 	if (trimall && argc > 0) {
8810 		(void) fprintf(stderr, gettext("-a cannot be combined with "
8811 		    "individual zpools or vdevs\n"));
8812 		usage(B_FALSE);
8813 	}
8814 
8815 	if (argc == 0 && trimall) {
8816 		cbdata.trim_flags.fullpool = B_TRUE;
8817 		/* Trim each pool recursively */
8818 		error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8819 		    B_FALSE, zpool_trim_one, &cbdata);
8820 	} else if (argc == 1) {
8821 		char *poolname = argv[0];
8822 		zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8823 		if (zhp == NULL)
8824 			return (-1);
8825 		/* no individual leaf vdevs specified, so add them all */
8826 		error = zpool_trim_one(zhp, &cbdata);
8827 		zpool_close(zhp);
8828 	} else {
8829 		char *poolname = argv[0];
8830 		zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8831 		if (zhp == NULL)
8832 			return (-1);
8833 		/* leaf vdevs specified, trim only those */
8834 		cbdata.trim_flags.fullpool = B_FALSE;
8835 		nvlist_t *vdevs = fnvlist_alloc();
8836 		for (int i = 1; i < argc; i++) {
8837 			fnvlist_add_boolean(vdevs, argv[i]);
8838 		}
8839 		error = zpool_trim(zhp, cbdata.cmd_type, vdevs,
8840 		    &cbdata.trim_flags);
8841 		fnvlist_free(vdevs);
8842 		zpool_close(zhp);
8843 	}
8844 
8845 	return (error);
8846 }
8847 
8848 /*
8849  * Converts a total number of seconds to a human readable string broken
8850  * down in to days/hours/minutes/seconds.
8851  */
8852 static void
secs_to_dhms(uint64_t total,char * buf)8853 secs_to_dhms(uint64_t total, char *buf)
8854 {
8855 	uint64_t days = total / 60 / 60 / 24;
8856 	uint64_t hours = (total / 60 / 60) % 24;
8857 	uint64_t mins = (total / 60) % 60;
8858 	uint64_t secs = (total % 60);
8859 
8860 	if (days > 0) {
8861 		(void) sprintf(buf, "%llu days %02llu:%02llu:%02llu",
8862 		    (u_longlong_t)days, (u_longlong_t)hours,
8863 		    (u_longlong_t)mins, (u_longlong_t)secs);
8864 	} else {
8865 		(void) sprintf(buf, "%02llu:%02llu:%02llu",
8866 		    (u_longlong_t)hours, (u_longlong_t)mins,
8867 		    (u_longlong_t)secs);
8868 	}
8869 }
8870 
8871 /*
8872  * Print out detailed error scrub status.
8873  */
8874 static void
print_err_scrub_status(pool_scan_stat_t * ps)8875 print_err_scrub_status(pool_scan_stat_t *ps)
8876 {
8877 	time_t start, end, pause;
8878 	uint64_t total_secs_left;
8879 	uint64_t secs_left, mins_left, hours_left, days_left;
8880 	uint64_t examined, to_be_examined;
8881 
8882 	if (ps == NULL || ps->pss_error_scrub_func != POOL_SCAN_ERRORSCRUB) {
8883 		return;
8884 	}
8885 
8886 	(void) printf(gettext(" scrub: "));
8887 
8888 	start = ps->pss_error_scrub_start;
8889 	end = ps->pss_error_scrub_end;
8890 	pause = ps->pss_pass_error_scrub_pause;
8891 	examined = ps->pss_error_scrub_examined;
8892 	to_be_examined = ps->pss_error_scrub_to_be_examined;
8893 
8894 	assert(ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB);
8895 
8896 	if (ps->pss_error_scrub_state == DSS_FINISHED) {
8897 		total_secs_left = end - start;
8898 		days_left = total_secs_left / 60 / 60 / 24;
8899 		hours_left = (total_secs_left / 60 / 60) % 24;
8900 		mins_left = (total_secs_left / 60) % 60;
8901 		secs_left = (total_secs_left % 60);
8902 
8903 		(void) printf(gettext("scrubbed %llu error blocks in %llu days "
8904 		    "%02llu:%02llu:%02llu on %s"), (u_longlong_t)examined,
8905 		    (u_longlong_t)days_left, (u_longlong_t)hours_left,
8906 		    (u_longlong_t)mins_left, (u_longlong_t)secs_left,
8907 		    ctime(&end));
8908 
8909 		return;
8910 	} else if (ps->pss_error_scrub_state == DSS_CANCELED) {
8911 		(void) printf(gettext("error scrub canceled on %s"),
8912 		    ctime(&end));
8913 		return;
8914 	}
8915 	assert(ps->pss_error_scrub_state == DSS_ERRORSCRUBBING);
8916 
8917 	/* Error scrub is in progress. */
8918 	if (pause == 0) {
8919 		(void) printf(gettext("error scrub in progress since %s"),
8920 		    ctime(&start));
8921 	} else {
8922 		(void) printf(gettext("error scrub paused since %s"),
8923 		    ctime(&pause));
8924 		(void) printf(gettext("\terror scrub started on %s"),
8925 		    ctime(&start));
8926 	}
8927 
8928 	double fraction_done = (double)examined / (to_be_examined + examined);
8929 	(void) printf(gettext("\t%.2f%% done, issued I/O for %llu error"
8930 	    " blocks"), 100 * fraction_done, (u_longlong_t)examined);
8931 
8932 	(void) printf("\n");
8933 }
8934 
8935 /*
8936  * Print out detailed scrub status.
8937  */
8938 static void
print_scan_scrub_resilver_status(pool_scan_stat_t * ps)8939 print_scan_scrub_resilver_status(pool_scan_stat_t *ps)
8940 {
8941 	time_t start, end, pause;
8942 	uint64_t pass_scanned, scanned, pass_issued, issued, total_s, total_i;
8943 	uint64_t elapsed, scan_rate, issue_rate;
8944 	double fraction_done;
8945 	char processed_buf[7], scanned_buf[7], issued_buf[7], total_s_buf[7];
8946 	char total_i_buf[7], srate_buf[7], irate_buf[7], time_buf[32];
8947 
8948 	printf("  ");
8949 	(void) printf_color(ANSI_BOLD, gettext("scan:"));
8950 	printf(" ");
8951 
8952 	/* If there's never been a scan, there's not much to say. */
8953 	if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
8954 	    ps->pss_func >= POOL_SCAN_FUNCS) {
8955 		(void) printf(gettext("none requested\n"));
8956 		return;
8957 	}
8958 
8959 	start = ps->pss_start_time;
8960 	end = ps->pss_end_time;
8961 	pause = ps->pss_pass_scrub_pause;
8962 
8963 	zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
8964 
8965 	int is_resilver = ps->pss_func == POOL_SCAN_RESILVER;
8966 	int is_scrub = ps->pss_func == POOL_SCAN_SCRUB;
8967 	assert(is_resilver || is_scrub);
8968 
8969 	/* Scan is finished or canceled. */
8970 	if (ps->pss_state == DSS_FINISHED) {
8971 		secs_to_dhms(end - start, time_buf);
8972 
8973 		if (is_scrub) {
8974 			(void) printf(gettext("scrub repaired %s "
8975 			    "in %s with %llu errors on %s"), processed_buf,
8976 			    time_buf, (u_longlong_t)ps->pss_errors,
8977 			    ctime(&end));
8978 		} else if (is_resilver) {
8979 			(void) printf(gettext("resilvered %s "
8980 			    "in %s with %llu errors on %s"), processed_buf,
8981 			    time_buf, (u_longlong_t)ps->pss_errors,
8982 			    ctime(&end));
8983 		}
8984 		return;
8985 	} else if (ps->pss_state == DSS_CANCELED) {
8986 		if (is_scrub) {
8987 			(void) printf(gettext("scrub canceled on %s"),
8988 			    ctime(&end));
8989 		} else if (is_resilver) {
8990 			(void) printf(gettext("resilver canceled on %s"),
8991 			    ctime(&end));
8992 		}
8993 		return;
8994 	}
8995 
8996 	assert(ps->pss_state == DSS_SCANNING);
8997 
8998 	/* Scan is in progress. Resilvers can't be paused. */
8999 	if (is_scrub) {
9000 		if (pause == 0) {
9001 			(void) printf(gettext("scrub in progress since %s"),
9002 			    ctime(&start));
9003 		} else {
9004 			(void) printf(gettext("scrub paused since %s"),
9005 			    ctime(&pause));
9006 			(void) printf(gettext("\tscrub started on %s"),
9007 			    ctime(&start));
9008 		}
9009 	} else if (is_resilver) {
9010 		(void) printf(gettext("resilver in progress since %s"),
9011 		    ctime(&start));
9012 	}
9013 
9014 	scanned = ps->pss_examined;
9015 	pass_scanned = ps->pss_pass_exam;
9016 	issued = ps->pss_issued;
9017 	pass_issued = ps->pss_pass_issued;
9018 	total_s = ps->pss_to_examine;
9019 	total_i = ps->pss_to_examine - ps->pss_skipped;
9020 
9021 	/* we are only done with a block once we have issued the IO for it */
9022 	fraction_done = (double)issued / total_i;
9023 
9024 	/* elapsed time for this pass, rounding up to 1 if it's 0 */
9025 	elapsed = time(NULL) - ps->pss_pass_start;
9026 	elapsed -= ps->pss_pass_scrub_spent_paused;
9027 	elapsed = (elapsed != 0) ? elapsed : 1;
9028 
9029 	scan_rate = pass_scanned / elapsed;
9030 	issue_rate = pass_issued / elapsed;
9031 
9032 	/* format all of the numbers we will be reporting */
9033 	zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
9034 	zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
9035 	zfs_nicebytes(total_s, total_s_buf, sizeof (total_s_buf));
9036 	zfs_nicebytes(total_i, total_i_buf, sizeof (total_i_buf));
9037 
9038 	/* do not print estimated time if we have a paused scrub */
9039 	(void) printf(gettext("\t%s / %s scanned"), scanned_buf, total_s_buf);
9040 	if (pause == 0 && scan_rate > 0) {
9041 		zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
9042 		(void) printf(gettext(" at %s/s"), srate_buf);
9043 	}
9044 	(void) printf(gettext(", %s / %s issued"), issued_buf, total_i_buf);
9045 	if (pause == 0 && issue_rate > 0) {
9046 		zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
9047 		(void) printf(gettext(" at %s/s"), irate_buf);
9048 	}
9049 	(void) printf(gettext("\n"));
9050 
9051 	if (is_resilver) {
9052 		(void) printf(gettext("\t%s resilvered, %.2f%% done"),
9053 		    processed_buf, 100 * fraction_done);
9054 	} else if (is_scrub) {
9055 		(void) printf(gettext("\t%s repaired, %.2f%% done"),
9056 		    processed_buf, 100 * fraction_done);
9057 	}
9058 
9059 	if (pause == 0) {
9060 		/*
9061 		 * Only provide an estimate iff:
9062 		 * 1) we haven't yet issued all we expected, and
9063 		 * 2) the issue rate exceeds 10 MB/s, and
9064 		 * 3) it's either:
9065 		 *    a) a resilver which has started repairs, or
9066 		 *    b) a scrub which has entered the issue phase.
9067 		 */
9068 		if (total_i >= issued && issue_rate >= 10 * 1024 * 1024 &&
9069 		    ((is_resilver && ps->pss_processed > 0) ||
9070 		    (is_scrub && issued > 0))) {
9071 			secs_to_dhms((total_i - issued) / issue_rate, time_buf);
9072 			(void) printf(gettext(", %s to go\n"), time_buf);
9073 		} else {
9074 			(void) printf(gettext(", no estimated "
9075 			    "completion time\n"));
9076 		}
9077 	} else {
9078 		(void) printf(gettext("\n"));
9079 	}
9080 }
9081 
9082 static void
print_rebuild_status_impl(vdev_rebuild_stat_t * vrs,uint_t c,char * vdev_name)9083 print_rebuild_status_impl(vdev_rebuild_stat_t *vrs, uint_t c, char *vdev_name)
9084 {
9085 	if (vrs == NULL || vrs->vrs_state == VDEV_REBUILD_NONE)
9086 		return;
9087 
9088 	printf("  ");
9089 	(void) printf_color(ANSI_BOLD, gettext("scan:"));
9090 	printf(" ");
9091 
9092 	uint64_t bytes_scanned = vrs->vrs_bytes_scanned;
9093 	uint64_t bytes_issued = vrs->vrs_bytes_issued;
9094 	uint64_t bytes_rebuilt = vrs->vrs_bytes_rebuilt;
9095 	uint64_t bytes_est_s = vrs->vrs_bytes_est;
9096 	uint64_t bytes_est_i = vrs->vrs_bytes_est;
9097 	if (c > offsetof(vdev_rebuild_stat_t, vrs_pass_bytes_skipped) / 8)
9098 		bytes_est_i -= vrs->vrs_pass_bytes_skipped;
9099 	uint64_t scan_rate = (vrs->vrs_pass_bytes_scanned /
9100 	    (vrs->vrs_pass_time_ms + 1)) * 1000;
9101 	uint64_t issue_rate = (vrs->vrs_pass_bytes_issued /
9102 	    (vrs->vrs_pass_time_ms + 1)) * 1000;
9103 	double scan_pct = MIN((double)bytes_scanned * 100 /
9104 	    (bytes_est_s + 1), 100);
9105 
9106 	/* Format all of the numbers we will be reporting */
9107 	char bytes_scanned_buf[7], bytes_issued_buf[7];
9108 	char bytes_rebuilt_buf[7], bytes_est_s_buf[7], bytes_est_i_buf[7];
9109 	char scan_rate_buf[7], issue_rate_buf[7], time_buf[32];
9110 	zfs_nicebytes(bytes_scanned, bytes_scanned_buf,
9111 	    sizeof (bytes_scanned_buf));
9112 	zfs_nicebytes(bytes_issued, bytes_issued_buf,
9113 	    sizeof (bytes_issued_buf));
9114 	zfs_nicebytes(bytes_rebuilt, bytes_rebuilt_buf,
9115 	    sizeof (bytes_rebuilt_buf));
9116 	zfs_nicebytes(bytes_est_s, bytes_est_s_buf, sizeof (bytes_est_s_buf));
9117 	zfs_nicebytes(bytes_est_i, bytes_est_i_buf, sizeof (bytes_est_i_buf));
9118 
9119 	time_t start = vrs->vrs_start_time;
9120 	time_t end = vrs->vrs_end_time;
9121 
9122 	/* Rebuild is finished or canceled. */
9123 	if (vrs->vrs_state == VDEV_REBUILD_COMPLETE) {
9124 		secs_to_dhms(vrs->vrs_scan_time_ms / 1000, time_buf);
9125 		(void) printf(gettext("resilvered (%s) %s in %s "
9126 		    "with %llu errors on %s"), vdev_name, bytes_rebuilt_buf,
9127 		    time_buf, (u_longlong_t)vrs->vrs_errors, ctime(&end));
9128 		return;
9129 	} else if (vrs->vrs_state == VDEV_REBUILD_CANCELED) {
9130 		(void) printf(gettext("resilver (%s) canceled on %s"),
9131 		    vdev_name, ctime(&end));
9132 		return;
9133 	} else if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9134 		(void) printf(gettext("resilver (%s) in progress since %s"),
9135 		    vdev_name, ctime(&start));
9136 	}
9137 
9138 	assert(vrs->vrs_state == VDEV_REBUILD_ACTIVE);
9139 
9140 	(void) printf(gettext("\t%s / %s scanned"), bytes_scanned_buf,
9141 	    bytes_est_s_buf);
9142 	if (scan_rate > 0) {
9143 		zfs_nicebytes(scan_rate, scan_rate_buf, sizeof (scan_rate_buf));
9144 		(void) printf(gettext(" at %s/s"), scan_rate_buf);
9145 	}
9146 	(void) printf(gettext(", %s / %s issued"), bytes_issued_buf,
9147 	    bytes_est_i_buf);
9148 	if (issue_rate > 0) {
9149 		zfs_nicebytes(issue_rate, issue_rate_buf,
9150 		    sizeof (issue_rate_buf));
9151 		(void) printf(gettext(" at %s/s"), issue_rate_buf);
9152 	}
9153 	(void) printf(gettext("\n"));
9154 
9155 	(void) printf(gettext("\t%s resilvered, %.2f%% done"),
9156 	    bytes_rebuilt_buf, scan_pct);
9157 
9158 	if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9159 		if (bytes_est_s >= bytes_scanned &&
9160 		    scan_rate >= 10 * 1024 * 1024) {
9161 			secs_to_dhms((bytes_est_s - bytes_scanned) / scan_rate,
9162 			    time_buf);
9163 			(void) printf(gettext(", %s to go\n"), time_buf);
9164 		} else {
9165 			(void) printf(gettext(", no estimated "
9166 			    "completion time\n"));
9167 		}
9168 	} else {
9169 		(void) printf(gettext("\n"));
9170 	}
9171 }
9172 
9173 /*
9174  * Print rebuild status for top-level vdevs.
9175  */
9176 static void
print_rebuild_status(zpool_handle_t * zhp,nvlist_t * nvroot)9177 print_rebuild_status(zpool_handle_t *zhp, nvlist_t *nvroot)
9178 {
9179 	nvlist_t **child;
9180 	uint_t children;
9181 
9182 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9183 	    &child, &children) != 0)
9184 		children = 0;
9185 
9186 	for (uint_t c = 0; c < children; c++) {
9187 		vdev_rebuild_stat_t *vrs;
9188 		uint_t i;
9189 
9190 		if (nvlist_lookup_uint64_array(child[c],
9191 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9192 			char *name = zpool_vdev_name(g_zfs, zhp,
9193 			    child[c], VDEV_NAME_TYPE_ID);
9194 			print_rebuild_status_impl(vrs, i, name);
9195 			free(name);
9196 		}
9197 	}
9198 }
9199 
9200 /*
9201  * As we don't scrub checkpointed blocks, we want to warn the user that we
9202  * skipped scanning some blocks if a checkpoint exists or existed at any
9203  * time during the scan.  If a sequential instead of healing reconstruction
9204  * was performed then the blocks were reconstructed.  However, their checksums
9205  * have not been verified so we still print the warning.
9206  */
9207 static void
print_checkpoint_scan_warning(pool_scan_stat_t * ps,pool_checkpoint_stat_t * pcs)9208 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
9209 {
9210 	if (ps == NULL || pcs == NULL)
9211 		return;
9212 
9213 	if (pcs->pcs_state == CS_NONE ||
9214 	    pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
9215 		return;
9216 
9217 	assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
9218 
9219 	if (ps->pss_state == DSS_NONE)
9220 		return;
9221 
9222 	if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
9223 	    ps->pss_end_time < pcs->pcs_start_time)
9224 		return;
9225 
9226 	if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
9227 		(void) printf(gettext("    scan warning: skipped blocks "
9228 		    "that are only referenced by the checkpoint.\n"));
9229 	} else {
9230 		assert(ps->pss_state == DSS_SCANNING);
9231 		(void) printf(gettext("    scan warning: skipping blocks "
9232 		    "that are only referenced by the checkpoint.\n"));
9233 	}
9234 }
9235 
9236 /*
9237  * Returns B_TRUE if there is an active rebuild in progress.  Otherwise,
9238  * B_FALSE is returned and 'rebuild_end_time' is set to the end time for
9239  * the last completed (or cancelled) rebuild.
9240  */
9241 static boolean_t
check_rebuilding(nvlist_t * nvroot,uint64_t * rebuild_end_time)9242 check_rebuilding(nvlist_t *nvroot, uint64_t *rebuild_end_time)
9243 {
9244 	nvlist_t **child;
9245 	uint_t children;
9246 	boolean_t rebuilding = B_FALSE;
9247 	uint64_t end_time = 0;
9248 
9249 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9250 	    &child, &children) != 0)
9251 		children = 0;
9252 
9253 	for (uint_t c = 0; c < children; c++) {
9254 		vdev_rebuild_stat_t *vrs;
9255 		uint_t i;
9256 
9257 		if (nvlist_lookup_uint64_array(child[c],
9258 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9259 
9260 			if (vrs->vrs_end_time > end_time)
9261 				end_time = vrs->vrs_end_time;
9262 
9263 			if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9264 				rebuilding = B_TRUE;
9265 				end_time = 0;
9266 				break;
9267 			}
9268 		}
9269 	}
9270 
9271 	if (rebuild_end_time != NULL)
9272 		*rebuild_end_time = end_time;
9273 
9274 	return (rebuilding);
9275 }
9276 
9277 static void
vdev_stats_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,int depth,boolean_t isspare,char * parent,nvlist_t * item)9278 vdev_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9279     int depth, boolean_t isspare, char *parent, nvlist_t *item)
9280 {
9281 	nvlist_t *vds, **child, *ch = NULL;
9282 	uint_t vsc, children;
9283 	vdev_stat_t *vs;
9284 	char *vname;
9285 	uint64_t notpresent;
9286 	const char *type, *path;
9287 
9288 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
9289 	    &child, &children) != 0)
9290 		children = 0;
9291 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
9292 	    (uint64_t **)&vs, &vsc) == 0);
9293 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
9294 	if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9295 		return;
9296 
9297 	if (cb->cb_print_unhealthy && depth > 0 &&
9298 	    for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
9299 		return;
9300 	}
9301 	vname = zpool_vdev_name(g_zfs, zhp, nv,
9302 	    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9303 	vds = fnvlist_alloc();
9304 	fill_vdev_info(vds, zhp, vname, B_FALSE, cb->cb_json_as_int);
9305 	if (cb->cb_flat_vdevs && parent != NULL) {
9306 		fnvlist_add_string(vds, "parent", parent);
9307 	}
9308 
9309 	if (isspare) {
9310 		if (vs->vs_aux == VDEV_AUX_SPARED) {
9311 			fnvlist_add_string(vds, "state", "INUSE");
9312 			used_by_other(zhp, nv, vds);
9313 		} else if (vs->vs_state == VDEV_STATE_HEALTHY)
9314 			fnvlist_add_string(vds, "state", "AVAIL");
9315 	} else {
9316 		if (vs->vs_alloc) {
9317 			nice_num_str_nvlist(vds, "alloc_space", vs->vs_alloc,
9318 			    cb->cb_literal, cb->cb_json_as_int,
9319 			    ZFS_NICENUM_BYTES);
9320 		}
9321 		if (vs->vs_space) {
9322 			nice_num_str_nvlist(vds, "total_space", vs->vs_space,
9323 			    cb->cb_literal, cb->cb_json_as_int,
9324 			    ZFS_NICENUM_BYTES);
9325 		}
9326 		if (vs->vs_dspace) {
9327 			nice_num_str_nvlist(vds, "def_space", vs->vs_dspace,
9328 			    cb->cb_literal, cb->cb_json_as_int,
9329 			    ZFS_NICENUM_BYTES);
9330 		}
9331 		if (vs->vs_rsize) {
9332 			nice_num_str_nvlist(vds, "rep_dev_size", vs->vs_rsize,
9333 			    cb->cb_literal, cb->cb_json_as_int,
9334 			    ZFS_NICENUM_BYTES);
9335 		}
9336 		if (vs->vs_esize) {
9337 			nice_num_str_nvlist(vds, "ex_dev_size", vs->vs_esize,
9338 			    cb->cb_literal, cb->cb_json_as_int,
9339 			    ZFS_NICENUM_BYTES);
9340 		}
9341 		if (vs->vs_self_healed) {
9342 			nice_num_str_nvlist(vds, "self_healed",
9343 			    vs->vs_self_healed, cb->cb_literal,
9344 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9345 		}
9346 		if (vs->vs_pspace) {
9347 			nice_num_str_nvlist(vds, "phys_space", vs->vs_pspace,
9348 			    cb->cb_literal, cb->cb_json_as_int,
9349 			    ZFS_NICENUM_BYTES);
9350 		}
9351 		nice_num_str_nvlist(vds, "read_errors", vs->vs_read_errors,
9352 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9353 		nice_num_str_nvlist(vds, "write_errors", vs->vs_write_errors,
9354 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9355 		nice_num_str_nvlist(vds, "checksum_errors",
9356 		    vs->vs_checksum_errors, cb->cb_literal,
9357 		    cb->cb_json_as_int, ZFS_NICENUM_1024);
9358 		if (vs->vs_scan_processed) {
9359 			nice_num_str_nvlist(vds, "scan_processed",
9360 			    vs->vs_scan_processed, cb->cb_literal,
9361 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9362 		}
9363 		if (vs->vs_checkpoint_space) {
9364 			nice_num_str_nvlist(vds, "checkpoint_space",
9365 			    vs->vs_checkpoint_space, cb->cb_literal,
9366 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9367 		}
9368 		if (vs->vs_resilver_deferred) {
9369 			nice_num_str_nvlist(vds, "resilver_deferred",
9370 			    vs->vs_resilver_deferred, B_TRUE,
9371 			    cb->cb_json_as_int, ZFS_NICENUM_1024);
9372 		}
9373 		if (children == 0) {
9374 			nice_num_str_nvlist(vds, "slow_ios", vs->vs_slow_ios,
9375 			    cb->cb_literal, cb->cb_json_as_int,
9376 			    ZFS_NICENUM_1024);
9377 		}
9378 		if (cb->cb_print_power) {
9379 			if (children == 0)  {
9380 				/* Only leaf vdevs have physical slots */
9381 				switch (zpool_power_current_state(zhp, (char *)
9382 				    fnvlist_lookup_string(nv,
9383 				    ZPOOL_CONFIG_PATH))) {
9384 				case 0:
9385 					fnvlist_add_string(vds, "power_state",
9386 					    "off");
9387 					break;
9388 				case 1:
9389 					fnvlist_add_string(vds, "power_state",
9390 					    "on");
9391 					break;
9392 				default:
9393 					fnvlist_add_string(vds, "power_state",
9394 					    "-");
9395 				}
9396 			} else {
9397 				fnvlist_add_string(vds, "power_state", "-");
9398 			}
9399 		}
9400 	}
9401 
9402 	if (cb->cb_print_dio_verify) {
9403 		nice_num_str_nvlist(vds, "dio_verify_errors",
9404 		    vs->vs_dio_verify_errors, cb->cb_literal,
9405 		    cb->cb_json_as_int, ZFS_NICENUM_1024);
9406 	}
9407 
9408 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
9409 	    &notpresent) == 0) {
9410 		nice_num_str_nvlist(vds, ZPOOL_CONFIG_NOT_PRESENT,
9411 		    1, B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9412 		fnvlist_add_string(vds, "was",
9413 		    fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH));
9414 	} else if (vs->vs_aux != VDEV_AUX_NONE) {
9415 		fnvlist_add_string(vds, "aux", vdev_aux_str[vs->vs_aux]);
9416 	} else if (children == 0 && !isspare &&
9417 	    getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
9418 	    VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
9419 	    vs->vs_configured_ashift < vs->vs_physical_ashift) {
9420 		nice_num_str_nvlist(vds, "configured_ashift",
9421 		    vs->vs_configured_ashift, B_TRUE, cb->cb_json_as_int,
9422 		    ZFS_NICENUM_1024);
9423 		nice_num_str_nvlist(vds, "physical_ashift",
9424 		    vs->vs_physical_ashift, B_TRUE, cb->cb_json_as_int,
9425 		    ZFS_NICENUM_1024);
9426 	}
9427 	if (vs->vs_scan_removing != 0) {
9428 		nice_num_str_nvlist(vds, "removing", vs->vs_scan_removing,
9429 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9430 	} else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
9431 		nice_num_str_nvlist(vds, "noalloc", vs->vs_noalloc,
9432 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9433 	}
9434 
9435 	if (cb->vcdl != NULL) {
9436 		if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
9437 			zpool_nvlist_cmd(cb->vcdl, zpool_get_name(zhp),
9438 			    path, vds);
9439 		}
9440 	}
9441 
9442 	if (children == 0) {
9443 		if (cb->cb_print_vdev_init) {
9444 			if (vs->vs_initialize_state != 0) {
9445 				uint64_t st = vs->vs_initialize_state;
9446 				fnvlist_add_string(vds, "init_state",
9447 				    vdev_init_state_str[st]);
9448 				nice_num_str_nvlist(vds, "initialized",
9449 				    vs->vs_initialize_bytes_done,
9450 				    cb->cb_literal, cb->cb_json_as_int,
9451 				    ZFS_NICENUM_BYTES);
9452 				nice_num_str_nvlist(vds, "to_initialize",
9453 				    vs->vs_initialize_bytes_est,
9454 				    cb->cb_literal, cb->cb_json_as_int,
9455 				    ZFS_NICENUM_BYTES);
9456 				nice_num_str_nvlist(vds, "init_time",
9457 				    vs->vs_initialize_action_time,
9458 				    cb->cb_literal, cb->cb_json_as_int,
9459 				    ZFS_NICE_TIMESTAMP);
9460 				nice_num_str_nvlist(vds, "init_errors",
9461 				    vs->vs_initialize_errors,
9462 				    cb->cb_literal, cb->cb_json_as_int,
9463 				    ZFS_NICENUM_1024);
9464 			} else {
9465 				fnvlist_add_string(vds, "init_state",
9466 				    "UNINITIALIZED");
9467 			}
9468 		}
9469 		if (cb->cb_print_vdev_trim) {
9470 			if (vs->vs_trim_notsup == 0) {
9471 					if (vs->vs_trim_state != 0) {
9472 					uint64_t st = vs->vs_trim_state;
9473 					fnvlist_add_string(vds, "trim_state",
9474 					    vdev_trim_state_str[st]);
9475 					nice_num_str_nvlist(vds, "trimmed",
9476 					    vs->vs_trim_bytes_done,
9477 					    cb->cb_literal, cb->cb_json_as_int,
9478 					    ZFS_NICENUM_BYTES);
9479 					nice_num_str_nvlist(vds, "to_trim",
9480 					    vs->vs_trim_bytes_est,
9481 					    cb->cb_literal, cb->cb_json_as_int,
9482 					    ZFS_NICENUM_BYTES);
9483 					nice_num_str_nvlist(vds, "trim_time",
9484 					    vs->vs_trim_action_time,
9485 					    cb->cb_literal, cb->cb_json_as_int,
9486 					    ZFS_NICE_TIMESTAMP);
9487 					nice_num_str_nvlist(vds, "trim_errors",
9488 					    vs->vs_trim_errors,
9489 					    cb->cb_literal, cb->cb_json_as_int,
9490 					    ZFS_NICENUM_1024);
9491 				} else
9492 					fnvlist_add_string(vds, "trim_state",
9493 					    "UNTRIMMED");
9494 			}
9495 			nice_num_str_nvlist(vds, "trim_notsup",
9496 			    vs->vs_trim_notsup, B_TRUE,
9497 			    cb->cb_json_as_int, ZFS_NICENUM_1024);
9498 		}
9499 	} else {
9500 		ch = fnvlist_alloc();
9501 	}
9502 
9503 	if (cb->cb_flat_vdevs && children == 0) {
9504 		fnvlist_add_nvlist(item, vname, vds);
9505 	}
9506 
9507 	for (int c = 0; c < children; c++) {
9508 		uint64_t islog = B_FALSE, ishole = B_FALSE;
9509 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9510 		    &islog);
9511 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
9512 		    &ishole);
9513 		if (islog || ishole)
9514 			continue;
9515 		if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
9516 			continue;
9517 		if (cb->cb_flat_vdevs) {
9518 			vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9519 			    vname, item);
9520 		}
9521 		vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9522 		    vname, ch);
9523 	}
9524 
9525 	if (ch != NULL) {
9526 		if (!nvlist_empty(ch))
9527 			fnvlist_add_nvlist(vds, "vdevs", ch);
9528 		fnvlist_free(ch);
9529 	}
9530 	fnvlist_add_nvlist(item, vname, vds);
9531 	fnvlist_free(vds);
9532 	free(vname);
9533 }
9534 
9535 static void
class_vdevs_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,const char * class,nvlist_t * item)9536 class_vdevs_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9537     const char *class, nvlist_t *item)
9538 {
9539 	uint_t c, children;
9540 	nvlist_t **child;
9541 	nvlist_t *class_obj = NULL;
9542 
9543 	if (!cb->cb_flat_vdevs)
9544 		class_obj = fnvlist_alloc();
9545 
9546 	assert(zhp != NULL || !cb->cb_verbose);
9547 
9548 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
9549 	    &children) != 0)
9550 		return;
9551 
9552 	for (c = 0; c < children; c++) {
9553 		uint64_t is_log = B_FALSE;
9554 		const char *bias = NULL;
9555 		const char *type = NULL;
9556 		char *name = zpool_vdev_name(g_zfs, zhp, child[c],
9557 		    cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9558 
9559 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9560 		    &is_log);
9561 
9562 		if (is_log) {
9563 			bias = (char *)VDEV_ALLOC_CLASS_LOGS;
9564 		} else {
9565 			(void) nvlist_lookup_string(child[c],
9566 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
9567 			(void) nvlist_lookup_string(child[c],
9568 			    ZPOOL_CONFIG_TYPE, &type);
9569 		}
9570 
9571 		if (bias == NULL || strcmp(bias, class) != 0)
9572 			continue;
9573 		if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9574 			continue;
9575 
9576 		if (cb->cb_flat_vdevs) {
9577 			vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9578 			    NULL, item);
9579 		} else {
9580 			vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9581 			    NULL, class_obj);
9582 		}
9583 		free(name);
9584 	}
9585 	if (!cb->cb_flat_vdevs) {
9586 		if (!nvlist_empty(class_obj))
9587 			fnvlist_add_nvlist(item, class, class_obj);
9588 		fnvlist_free(class_obj);
9589 	}
9590 }
9591 
9592 static void
l2cache_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,nvlist_t * item)9593 l2cache_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9594     nvlist_t *item)
9595 {
9596 	nvlist_t *l2c = NULL, **l2cache;
9597 	uint_t nl2cache;
9598 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
9599 	    &l2cache, &nl2cache) == 0) {
9600 		if (nl2cache == 0)
9601 			return;
9602 		if (!cb->cb_flat_vdevs)
9603 			l2c = fnvlist_alloc();
9604 		for (int i = 0; i < nl2cache; i++) {
9605 			if (cb->cb_flat_vdevs) {
9606 				vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9607 				    B_FALSE, NULL, item);
9608 			} else {
9609 				vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9610 				    B_FALSE, NULL, l2c);
9611 			}
9612 		}
9613 	}
9614 	if (!cb->cb_flat_vdevs) {
9615 		if (!nvlist_empty(l2c))
9616 			fnvlist_add_nvlist(item, "l2cache", l2c);
9617 		fnvlist_free(l2c);
9618 	}
9619 }
9620 
9621 static void
spares_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,nvlist_t * item)9622 spares_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9623     nvlist_t *item)
9624 {
9625 	nvlist_t *sp = NULL, **spares;
9626 	uint_t nspares;
9627 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
9628 	    &spares, &nspares) == 0) {
9629 		if (nspares == 0)
9630 			return;
9631 		if (!cb->cb_flat_vdevs)
9632 			sp = fnvlist_alloc();
9633 		for (int i = 0; i < nspares; i++) {
9634 			if (cb->cb_flat_vdevs) {
9635 				vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9636 				    NULL, item);
9637 			} else {
9638 				vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9639 				    NULL, sp);
9640 			}
9641 		}
9642 	}
9643 	if (!cb->cb_flat_vdevs) {
9644 		if (!nvlist_empty(sp))
9645 			fnvlist_add_nvlist(item, "spares", sp);
9646 		fnvlist_free(sp);
9647 	}
9648 }
9649 
9650 static void
errors_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * item)9651 errors_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9652 {
9653 	uint64_t nerr;
9654 	nvlist_t *config = zpool_get_config(zhp, NULL);
9655 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
9656 	    &nerr) == 0) {
9657 		nice_num_str_nvlist(item, ZPOOL_CONFIG_ERRCOUNT, nerr,
9658 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9659 		if (nerr != 0 && cb->cb_verbose) {
9660 			nvlist_t *nverrlist = NULL;
9661 			if (zpool_get_errlog(zhp, &nverrlist) == 0) {
9662 				int i = 0;
9663 				int count = 0;
9664 				size_t len = MAXPATHLEN * 2;
9665 				nvpair_t *elem = NULL;
9666 
9667 				for (nvpair_t *pair =
9668 				    nvlist_next_nvpair(nverrlist, NULL);
9669 				    pair != NULL;
9670 				    pair = nvlist_next_nvpair(nverrlist, pair))
9671 					count++;
9672 				char **errl = (char **)malloc(
9673 				    count * sizeof (char *));
9674 
9675 				while ((elem = nvlist_next_nvpair(nverrlist,
9676 				    elem)) != NULL) {
9677 					nvlist_t *nv;
9678 					uint64_t dsobj, obj;
9679 
9680 					verify(nvpair_value_nvlist(elem,
9681 					    &nv) == 0);
9682 					verify(nvlist_lookup_uint64(nv,
9683 					    ZPOOL_ERR_DATASET, &dsobj) == 0);
9684 					verify(nvlist_lookup_uint64(nv,
9685 					    ZPOOL_ERR_OBJECT, &obj) == 0);
9686 					errl[i] = safe_malloc(len);
9687 					zpool_obj_to_path(zhp, dsobj, obj,
9688 					    errl[i++], len);
9689 				}
9690 				nvlist_free(nverrlist);
9691 				fnvlist_add_string_array(item, "errlist",
9692 				    (const char **)errl, count);
9693 				for (int i = 0; i < count; ++i)
9694 					free(errl[i]);
9695 				free(errl);
9696 			} else
9697 				fnvlist_add_string(item, "errlist",
9698 				    strerror(errno));
9699 		}
9700 	}
9701 }
9702 
9703 static void
ddt_stats_nvlist(ddt_stat_t * dds,status_cbdata_t * cb,nvlist_t * item)9704 ddt_stats_nvlist(ddt_stat_t *dds, status_cbdata_t *cb, nvlist_t *item)
9705 {
9706 	nice_num_str_nvlist(item, "blocks", dds->dds_blocks,
9707 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9708 	nice_num_str_nvlist(item, "logical_size", dds->dds_lsize,
9709 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9710 	nice_num_str_nvlist(item, "physical_size", dds->dds_psize,
9711 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9712 	nice_num_str_nvlist(item, "deflated_size", dds->dds_dsize,
9713 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9714 	nice_num_str_nvlist(item, "ref_blocks", dds->dds_ref_blocks,
9715 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9716 	nice_num_str_nvlist(item, "ref_lsize", dds->dds_ref_lsize,
9717 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9718 	nice_num_str_nvlist(item, "ref_psize", dds->dds_ref_psize,
9719 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9720 	nice_num_str_nvlist(item, "ref_dsize", dds->dds_ref_dsize,
9721 	    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9722 }
9723 
9724 static void
dedup_stats_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * item)9725 dedup_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9726 {
9727 	nvlist_t *config;
9728 	if (cb->cb_dedup_stats) {
9729 		ddt_histogram_t *ddh;
9730 		ddt_stat_t *dds;
9731 		ddt_object_t *ddo;
9732 		nvlist_t *ddt_stat, *ddt_obj, *dedup;
9733 		uint_t c;
9734 		uint64_t cspace_prop;
9735 
9736 		config = zpool_get_config(zhp, NULL);
9737 		if (nvlist_lookup_uint64_array(config,
9738 		    ZPOOL_CONFIG_DDT_OBJ_STATS, (uint64_t **)&ddo, &c) != 0)
9739 			return;
9740 
9741 		dedup = fnvlist_alloc();
9742 		ddt_obj = fnvlist_alloc();
9743 		nice_num_str_nvlist(dedup, "obj_count", ddo->ddo_count,
9744 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9745 		if (ddo->ddo_count == 0) {
9746 			fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
9747 			    ddt_obj);
9748 			fnvlist_add_nvlist(item, "dedup_stats", dedup);
9749 			fnvlist_free(ddt_obj);
9750 			fnvlist_free(dedup);
9751 			return;
9752 		} else {
9753 			nice_num_str_nvlist(dedup, "dspace", ddo->ddo_dspace,
9754 			    cb->cb_literal, cb->cb_json_as_int,
9755 			    ZFS_NICENUM_1024);
9756 			nice_num_str_nvlist(dedup, "mspace", ddo->ddo_mspace,
9757 			    cb->cb_literal, cb->cb_json_as_int,
9758 			    ZFS_NICENUM_1024);
9759 			/*
9760 			 * Squash cached size into in-core size to handle race.
9761 			 * Only include cached size if it is available.
9762 			 */
9763 			cspace_prop = zpool_get_prop_int(zhp,
9764 			    ZPOOL_PROP_DEDUPCACHED, NULL);
9765 			cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
9766 			nice_num_str_nvlist(dedup, "cspace", cspace_prop,
9767 			    cb->cb_literal, cb->cb_json_as_int,
9768 			    ZFS_NICENUM_1024);
9769 		}
9770 
9771 		ddt_stat = fnvlist_alloc();
9772 		if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
9773 		    (uint64_t **)&dds, &c) == 0) {
9774 			nvlist_t *total = fnvlist_alloc();
9775 			if (dds->dds_blocks == 0)
9776 				fnvlist_add_string(total, "blocks", "0");
9777 			else
9778 				ddt_stats_nvlist(dds, cb, total);
9779 			fnvlist_add_nvlist(ddt_stat, "total", total);
9780 			fnvlist_free(total);
9781 		}
9782 		if (nvlist_lookup_uint64_array(config,
9783 		    ZPOOL_CONFIG_DDT_HISTOGRAM, (uint64_t **)&ddh, &c) == 0) {
9784 			nvlist_t *hist = fnvlist_alloc();
9785 			nvlist_t *entry = NULL;
9786 			char buf[16];
9787 			for (int h = 0; h < 64; h++) {
9788 				if (ddh->ddh_stat[h].dds_blocks != 0) {
9789 					entry = fnvlist_alloc();
9790 					ddt_stats_nvlist(&ddh->ddh_stat[h], cb,
9791 					    entry);
9792 					(void) snprintf(buf, 16, "%d", h);
9793 					fnvlist_add_nvlist(hist, buf, entry);
9794 					fnvlist_free(entry);
9795 				}
9796 			}
9797 			if (!nvlist_empty(hist))
9798 				fnvlist_add_nvlist(ddt_stat, "histogram", hist);
9799 			fnvlist_free(hist);
9800 		}
9801 
9802 		if (!nvlist_empty(ddt_obj)) {
9803 			fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
9804 			    ddt_obj);
9805 		}
9806 		fnvlist_free(ddt_obj);
9807 		if (!nvlist_empty(ddt_stat)) {
9808 			fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_STATS,
9809 			    ddt_stat);
9810 		}
9811 		fnvlist_free(ddt_stat);
9812 		if (!nvlist_empty(dedup))
9813 			fnvlist_add_nvlist(item, "dedup_stats", dedup);
9814 		fnvlist_free(dedup);
9815 	}
9816 }
9817 
9818 static void
raidz_expand_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)9819 raidz_expand_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
9820     nvlist_t *nvroot, nvlist_t *item)
9821 {
9822 	uint_t c;
9823 	pool_raidz_expand_stat_t *pres = NULL;
9824 	if (nvlist_lookup_uint64_array(nvroot,
9825 	    ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c) == 0) {
9826 		nvlist_t **child;
9827 		uint_t children;
9828 		nvlist_t *nv = fnvlist_alloc();
9829 		verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9830 		    &child, &children) == 0);
9831 		assert(pres->pres_expanding_vdev < children);
9832 		char *name =
9833 		    zpool_vdev_name(g_zfs, zhp,
9834 		    child[pres->pres_expanding_vdev], 0);
9835 		fill_vdev_info(nv, zhp, name, B_FALSE, cb->cb_json_as_int);
9836 		fnvlist_add_string(nv, "state",
9837 		    pool_scan_state_str[pres->pres_state]);
9838 		nice_num_str_nvlist(nv, "expanding_vdev",
9839 		    pres->pres_expanding_vdev, B_TRUE, cb->cb_json_as_int,
9840 		    ZFS_NICENUM_1024);
9841 		nice_num_str_nvlist(nv, "start_time", pres->pres_start_time,
9842 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9843 		nice_num_str_nvlist(nv, "end_time", pres->pres_end_time,
9844 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9845 		nice_num_str_nvlist(nv, "to_reflow", pres->pres_to_reflow,
9846 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9847 		nice_num_str_nvlist(nv, "reflowed", pres->pres_reflowed,
9848 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9849 		nice_num_str_nvlist(nv, "waiting_for_resilver",
9850 		    pres->pres_waiting_for_resilver, B_TRUE,
9851 		    cb->cb_json_as_int, ZFS_NICENUM_1024);
9852 		fnvlist_add_nvlist(item, ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, nv);
9853 		fnvlist_free(nv);
9854 		free(name);
9855 	}
9856 }
9857 
9858 static void
checkpoint_status_nvlist(nvlist_t * nvroot,status_cbdata_t * cb,nvlist_t * item)9859 checkpoint_status_nvlist(nvlist_t *nvroot, status_cbdata_t *cb,
9860     nvlist_t *item)
9861 {
9862 	uint_t c;
9863 	pool_checkpoint_stat_t *pcs = NULL;
9864 	if (nvlist_lookup_uint64_array(nvroot,
9865 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c) == 0) {
9866 		nvlist_t *nv = fnvlist_alloc();
9867 		fnvlist_add_string(nv, "state",
9868 		    checkpoint_state_str[pcs->pcs_state]);
9869 		nice_num_str_nvlist(nv, "start_time",
9870 		    pcs->pcs_start_time, cb->cb_literal, cb->cb_json_as_int,
9871 		    ZFS_NICE_TIMESTAMP);
9872 		nice_num_str_nvlist(nv, "space",
9873 		    pcs->pcs_space, cb->cb_literal, cb->cb_json_as_int,
9874 		    ZFS_NICENUM_BYTES);
9875 		fnvlist_add_nvlist(item, ZPOOL_CONFIG_CHECKPOINT_STATS, nv);
9876 		fnvlist_free(nv);
9877 	}
9878 }
9879 
9880 static void
removal_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)9881 removal_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
9882     nvlist_t *nvroot, nvlist_t *item)
9883 {
9884 	uint_t c;
9885 	pool_removal_stat_t *prs = NULL;
9886 	if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_REMOVAL_STATS,
9887 	    (uint64_t **)&prs, &c) == 0) {
9888 		if (prs->prs_state != DSS_NONE) {
9889 			nvlist_t **child;
9890 			uint_t children;
9891 			verify(nvlist_lookup_nvlist_array(nvroot,
9892 			    ZPOOL_CONFIG_CHILDREN, &child, &children) == 0);
9893 			assert(prs->prs_removing_vdev < children);
9894 			char *vdev_name = zpool_vdev_name(g_zfs, zhp,
9895 			    child[prs->prs_removing_vdev], B_TRUE);
9896 			nvlist_t *nv = fnvlist_alloc();
9897 			fill_vdev_info(nv, zhp, vdev_name, B_FALSE,
9898 			    cb->cb_json_as_int);
9899 			fnvlist_add_string(nv, "state",
9900 			    pool_scan_state_str[prs->prs_state]);
9901 			nice_num_str_nvlist(nv, "removing_vdev",
9902 			    prs->prs_removing_vdev, B_TRUE, cb->cb_json_as_int,
9903 			    ZFS_NICENUM_1024);
9904 			nice_num_str_nvlist(nv, "start_time",
9905 			    prs->prs_start_time, cb->cb_literal,
9906 			    cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9907 			nice_num_str_nvlist(nv, "end_time", prs->prs_end_time,
9908 			    cb->cb_literal, cb->cb_json_as_int,
9909 			    ZFS_NICE_TIMESTAMP);
9910 			nice_num_str_nvlist(nv, "to_copy", prs->prs_to_copy,
9911 			    cb->cb_literal, cb->cb_json_as_int,
9912 			    ZFS_NICENUM_BYTES);
9913 			nice_num_str_nvlist(nv, "copied", prs->prs_copied,
9914 			    cb->cb_literal, cb->cb_json_as_int,
9915 			    ZFS_NICENUM_BYTES);
9916 			nice_num_str_nvlist(nv, "mapping_memory",
9917 			    prs->prs_mapping_memory, cb->cb_literal,
9918 			    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9919 			fnvlist_add_nvlist(item,
9920 			    ZPOOL_CONFIG_REMOVAL_STATS, nv);
9921 			fnvlist_free(nv);
9922 			free(vdev_name);
9923 		}
9924 	}
9925 }
9926 
9927 static void
scan_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)9928 scan_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
9929     nvlist_t *nvroot, nvlist_t *item)
9930 {
9931 	pool_scan_stat_t *ps = NULL;
9932 	uint_t c;
9933 	nvlist_t *scan = fnvlist_alloc();
9934 	nvlist_t **child;
9935 	uint_t children;
9936 
9937 	if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
9938 	    (uint64_t **)&ps, &c) == 0) {
9939 		fnvlist_add_string(scan, "function",
9940 		    pool_scan_func_str[ps->pss_func]);
9941 		fnvlist_add_string(scan, "state",
9942 		    pool_scan_state_str[ps->pss_state]);
9943 		nice_num_str_nvlist(scan, "start_time", ps->pss_start_time,
9944 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9945 		nice_num_str_nvlist(scan, "end_time", ps->pss_end_time,
9946 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9947 		nice_num_str_nvlist(scan, "to_examine", ps->pss_to_examine,
9948 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9949 		nice_num_str_nvlist(scan, "examined", ps->pss_examined,
9950 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9951 		nice_num_str_nvlist(scan, "skipped", ps->pss_skipped,
9952 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9953 		nice_num_str_nvlist(scan, "processed", ps->pss_processed,
9954 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9955 		nice_num_str_nvlist(scan, "errors", ps->pss_errors,
9956 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9957 		nice_num_str_nvlist(scan, "bytes_per_scan", ps->pss_pass_exam,
9958 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9959 		nice_num_str_nvlist(scan, "pass_start", ps->pss_pass_start,
9960 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9961 		nice_num_str_nvlist(scan, "scrub_pause",
9962 		    ps->pss_pass_scrub_pause, cb->cb_literal,
9963 		    cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9964 		nice_num_str_nvlist(scan, "scrub_spent_paused",
9965 		    ps->pss_pass_scrub_spent_paused,
9966 		    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9967 		nice_num_str_nvlist(scan, "issued_bytes_per_scan",
9968 		    ps->pss_pass_issued, cb->cb_literal,
9969 		    cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9970 		nice_num_str_nvlist(scan, "issued", ps->pss_issued,
9971 		    cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9972 		if (ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB &&
9973 		    ps->pss_error_scrub_start > ps->pss_start_time) {
9974 			fnvlist_add_string(scan, "err_scrub_func",
9975 			    pool_scan_func_str[ps->pss_error_scrub_func]);
9976 			fnvlist_add_string(scan, "err_scrub_state",
9977 			    pool_scan_state_str[ps->pss_error_scrub_state]);
9978 			nice_num_str_nvlist(scan, "err_scrub_start_time",
9979 			    ps->pss_error_scrub_start,
9980 			    cb->cb_literal, cb->cb_json_as_int,
9981 			    ZFS_NICE_TIMESTAMP);
9982 			nice_num_str_nvlist(scan, "err_scrub_end_time",
9983 			    ps->pss_error_scrub_end,
9984 			    cb->cb_literal, cb->cb_json_as_int,
9985 			    ZFS_NICE_TIMESTAMP);
9986 			nice_num_str_nvlist(scan, "err_scrub_examined",
9987 			    ps->pss_error_scrub_examined,
9988 			    cb->cb_literal, cb->cb_json_as_int,
9989 			    ZFS_NICENUM_1024);
9990 			nice_num_str_nvlist(scan, "err_scrub_to_examine",
9991 			    ps->pss_error_scrub_to_be_examined,
9992 			    cb->cb_literal, cb->cb_json_as_int,
9993 			    ZFS_NICENUM_1024);
9994 			nice_num_str_nvlist(scan, "err_scrub_pause",
9995 			    ps->pss_pass_error_scrub_pause,
9996 			    B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9997 		}
9998 	}
9999 
10000 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10001 	    &child, &children) == 0) {
10002 		vdev_rebuild_stat_t *vrs;
10003 		uint_t i;
10004 		char *name;
10005 		nvlist_t *nv;
10006 		nvlist_t *rebuild = fnvlist_alloc();
10007 		uint64_t st;
10008 		for (uint_t c = 0; c < children; c++) {
10009 			if (nvlist_lookup_uint64_array(child[c],
10010 			    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs,
10011 			    &i) == 0) {
10012 				if (vrs->vrs_state != VDEV_REBUILD_NONE) {
10013 					nv = fnvlist_alloc();
10014 					name = zpool_vdev_name(g_zfs, zhp,
10015 					    child[c], VDEV_NAME_TYPE_ID);
10016 					fill_vdev_info(nv, zhp, name, B_FALSE,
10017 					    cb->cb_json_as_int);
10018 					st = vrs->vrs_state;
10019 					fnvlist_add_string(nv, "state",
10020 					    vdev_rebuild_state_str[st]);
10021 					nice_num_str_nvlist(nv, "start_time",
10022 					    vrs->vrs_start_time, cb->cb_literal,
10023 					    cb->cb_json_as_int,
10024 					    ZFS_NICE_TIMESTAMP);
10025 					nice_num_str_nvlist(nv, "end_time",
10026 					    vrs->vrs_end_time, cb->cb_literal,
10027 					    cb->cb_json_as_int,
10028 					    ZFS_NICE_TIMESTAMP);
10029 					nice_num_str_nvlist(nv, "scan_time",
10030 					    vrs->vrs_scan_time_ms * 1000000,
10031 					    cb->cb_literal, cb->cb_json_as_int,
10032 					    ZFS_NICENUM_TIME);
10033 					nice_num_str_nvlist(nv, "scanned",
10034 					    vrs->vrs_bytes_scanned,
10035 					    cb->cb_literal, cb->cb_json_as_int,
10036 					    ZFS_NICENUM_BYTES);
10037 					nice_num_str_nvlist(nv, "issued",
10038 					    vrs->vrs_bytes_issued,
10039 					    cb->cb_literal, cb->cb_json_as_int,
10040 					    ZFS_NICENUM_BYTES);
10041 					nice_num_str_nvlist(nv, "rebuilt",
10042 					    vrs->vrs_bytes_rebuilt,
10043 					    cb->cb_literal, cb->cb_json_as_int,
10044 					    ZFS_NICENUM_BYTES);
10045 					nice_num_str_nvlist(nv, "to_scan",
10046 					    vrs->vrs_bytes_est, cb->cb_literal,
10047 					    cb->cb_json_as_int,
10048 					    ZFS_NICENUM_BYTES);
10049 					nice_num_str_nvlist(nv, "errors",
10050 					    vrs->vrs_errors, cb->cb_literal,
10051 					    cb->cb_json_as_int,
10052 					    ZFS_NICENUM_1024);
10053 					nice_num_str_nvlist(nv, "pass_time",
10054 					    vrs->vrs_pass_time_ms * 1000000,
10055 					    cb->cb_literal, cb->cb_json_as_int,
10056 					    ZFS_NICENUM_TIME);
10057 					nice_num_str_nvlist(nv, "pass_scanned",
10058 					    vrs->vrs_pass_bytes_scanned,
10059 					    cb->cb_literal, cb->cb_json_as_int,
10060 					    ZFS_NICENUM_BYTES);
10061 					nice_num_str_nvlist(nv, "pass_issued",
10062 					    vrs->vrs_pass_bytes_issued,
10063 					    cb->cb_literal, cb->cb_json_as_int,
10064 					    ZFS_NICENUM_BYTES);
10065 					nice_num_str_nvlist(nv, "pass_skipped",
10066 					    vrs->vrs_pass_bytes_skipped,
10067 					    cb->cb_literal, cb->cb_json_as_int,
10068 					    ZFS_NICENUM_BYTES);
10069 					fnvlist_add_nvlist(rebuild, name, nv);
10070 					free(name);
10071 				}
10072 			}
10073 		}
10074 		if (!nvlist_empty(rebuild))
10075 			fnvlist_add_nvlist(scan, "rebuild_stats", rebuild);
10076 		fnvlist_free(rebuild);
10077 	}
10078 
10079 	if (!nvlist_empty(scan))
10080 		fnvlist_add_nvlist(item, ZPOOL_CONFIG_SCAN_STATS, scan);
10081 	fnvlist_free(scan);
10082 }
10083 
10084 /*
10085  * Print the scan status.
10086  */
10087 static void
print_scan_status(zpool_handle_t * zhp,nvlist_t * nvroot)10088 print_scan_status(zpool_handle_t *zhp, nvlist_t *nvroot)
10089 {
10090 	uint64_t rebuild_end_time = 0, resilver_end_time = 0;
10091 	boolean_t have_resilver = B_FALSE, have_scrub = B_FALSE;
10092 	boolean_t have_errorscrub = B_FALSE;
10093 	boolean_t active_resilver = B_FALSE;
10094 	pool_checkpoint_stat_t *pcs = NULL;
10095 	pool_scan_stat_t *ps = NULL;
10096 	uint_t c;
10097 	time_t scrub_start = 0, errorscrub_start = 0;
10098 
10099 	if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
10100 	    (uint64_t **)&ps, &c) == 0) {
10101 		if (ps->pss_func == POOL_SCAN_RESILVER) {
10102 			resilver_end_time = ps->pss_end_time;
10103 			active_resilver = (ps->pss_state == DSS_SCANNING);
10104 		}
10105 
10106 		have_resilver = (ps->pss_func == POOL_SCAN_RESILVER);
10107 		have_scrub = (ps->pss_func == POOL_SCAN_SCRUB);
10108 		scrub_start = ps->pss_start_time;
10109 		if (c > offsetof(pool_scan_stat_t,
10110 		    pss_pass_error_scrub_pause) / 8) {
10111 			have_errorscrub = (ps->pss_error_scrub_func ==
10112 			    POOL_SCAN_ERRORSCRUB);
10113 			errorscrub_start = ps->pss_error_scrub_start;
10114 		}
10115 	}
10116 
10117 	boolean_t active_rebuild = check_rebuilding(nvroot, &rebuild_end_time);
10118 	boolean_t have_rebuild = (active_rebuild || (rebuild_end_time > 0));
10119 
10120 	/* Always print the scrub status when available. */
10121 	if (have_scrub && scrub_start > errorscrub_start)
10122 		print_scan_scrub_resilver_status(ps);
10123 	else if (have_errorscrub && errorscrub_start >= scrub_start)
10124 		print_err_scrub_status(ps);
10125 
10126 	/*
10127 	 * When there is an active resilver or rebuild print its status.
10128 	 * Otherwise print the status of the last resilver or rebuild.
10129 	 */
10130 	if (active_resilver || (!active_rebuild && have_resilver &&
10131 	    resilver_end_time && resilver_end_time > rebuild_end_time)) {
10132 		print_scan_scrub_resilver_status(ps);
10133 	} else if (active_rebuild || (!active_resilver && have_rebuild &&
10134 	    rebuild_end_time && rebuild_end_time > resilver_end_time)) {
10135 		print_rebuild_status(zhp, nvroot);
10136 	}
10137 
10138 	(void) nvlist_lookup_uint64_array(nvroot,
10139 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
10140 	print_checkpoint_scan_warning(ps, pcs);
10141 }
10142 
10143 /*
10144  * Print out detailed removal status.
10145  */
10146 static void
print_removal_status(zpool_handle_t * zhp,pool_removal_stat_t * prs)10147 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
10148 {
10149 	char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
10150 	time_t start, end;
10151 	nvlist_t *config, *nvroot;
10152 	nvlist_t **child;
10153 	uint_t children;
10154 	char *vdev_name;
10155 
10156 	if (prs == NULL || prs->prs_state == DSS_NONE)
10157 		return;
10158 
10159 	/*
10160 	 * Determine name of vdev.
10161 	 */
10162 	config = zpool_get_config(zhp, NULL);
10163 	nvroot = fnvlist_lookup_nvlist(config,
10164 	    ZPOOL_CONFIG_VDEV_TREE);
10165 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10166 	    &child, &children) == 0);
10167 	assert(prs->prs_removing_vdev < children);
10168 	vdev_name = zpool_vdev_name(g_zfs, zhp,
10169 	    child[prs->prs_removing_vdev], B_TRUE);
10170 
10171 	(void) printf_color(ANSI_BOLD, gettext("remove: "));
10172 
10173 	start = prs->prs_start_time;
10174 	end = prs->prs_end_time;
10175 	zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
10176 
10177 	/*
10178 	 * Removal is finished or canceled.
10179 	 */
10180 	if (prs->prs_state == DSS_FINISHED) {
10181 		uint64_t minutes_taken = (end - start) / 60;
10182 
10183 		(void) printf(gettext("Removal of vdev %llu copied %s "
10184 		    "in %lluh%um, completed on %s"),
10185 		    (longlong_t)prs->prs_removing_vdev,
10186 		    copied_buf,
10187 		    (u_longlong_t)(minutes_taken / 60),
10188 		    (uint_t)(minutes_taken % 60),
10189 		    ctime((time_t *)&end));
10190 	} else if (prs->prs_state == DSS_CANCELED) {
10191 		(void) printf(gettext("Removal of %s canceled on %s"),
10192 		    vdev_name, ctime(&end));
10193 	} else {
10194 		uint64_t copied, total, elapsed, rate, mins_left, hours_left;
10195 		double fraction_done;
10196 
10197 		assert(prs->prs_state == DSS_SCANNING);
10198 
10199 		/*
10200 		 * Removal is in progress.
10201 		 */
10202 		(void) printf(gettext(
10203 		    "Evacuation of %s in progress since %s"),
10204 		    vdev_name, ctime(&start));
10205 
10206 		copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
10207 		total = prs->prs_to_copy;
10208 		fraction_done = (double)copied / total;
10209 
10210 		/* elapsed time for this pass */
10211 		elapsed = time(NULL) - prs->prs_start_time;
10212 		elapsed = elapsed > 0 ? elapsed : 1;
10213 		rate = copied / elapsed;
10214 		rate = rate > 0 ? rate : 1;
10215 		mins_left = ((total - copied) / rate) / 60;
10216 		hours_left = mins_left / 60;
10217 
10218 		zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10219 		zfs_nicenum(total, total_buf, sizeof (total_buf));
10220 		zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10221 
10222 		/*
10223 		 * do not print estimated time if hours_left is more than
10224 		 * 30 days
10225 		 */
10226 		(void) printf(gettext(
10227 		    "\t%s copied out of %s at %s/s, %.2f%% done"),
10228 		    examined_buf, total_buf, rate_buf, 100 * fraction_done);
10229 		if (hours_left < (30 * 24)) {
10230 			(void) printf(gettext(", %lluh%um to go\n"),
10231 			    (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
10232 		} else {
10233 			(void) printf(gettext(
10234 			    ", (copy is slow, no estimated time)\n"));
10235 		}
10236 	}
10237 	free(vdev_name);
10238 
10239 	if (prs->prs_mapping_memory > 0) {
10240 		char mem_buf[7];
10241 		zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
10242 		(void) printf(gettext(
10243 		    "\t%s memory used for removed device mappings\n"),
10244 		    mem_buf);
10245 	}
10246 }
10247 
10248 /*
10249  * Print out detailed raidz expansion status.
10250  */
10251 static void
print_raidz_expand_status(zpool_handle_t * zhp,pool_raidz_expand_stat_t * pres)10252 print_raidz_expand_status(zpool_handle_t *zhp, pool_raidz_expand_stat_t *pres)
10253 {
10254 	char copied_buf[7];
10255 
10256 	if (pres == NULL || pres->pres_state == DSS_NONE)
10257 		return;
10258 
10259 	/*
10260 	 * Determine name of vdev.
10261 	 */
10262 	nvlist_t *config = zpool_get_config(zhp, NULL);
10263 	nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
10264 	    ZPOOL_CONFIG_VDEV_TREE);
10265 	nvlist_t **child;
10266 	uint_t children;
10267 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10268 	    &child, &children) == 0);
10269 	assert(pres->pres_expanding_vdev < children);
10270 
10271 	(void) printf_color(ANSI_BOLD, gettext("expand: "));
10272 
10273 	time_t start = pres->pres_start_time;
10274 	time_t end = pres->pres_end_time;
10275 	char *vname =
10276 	    zpool_vdev_name(g_zfs, zhp, child[pres->pres_expanding_vdev], 0);
10277 	zfs_nicenum(pres->pres_reflowed, copied_buf, sizeof (copied_buf));
10278 
10279 	/*
10280 	 * Expansion is finished or canceled.
10281 	 */
10282 	if (pres->pres_state == DSS_FINISHED) {
10283 		char time_buf[32];
10284 		secs_to_dhms(end - start, time_buf);
10285 
10286 		(void) printf(gettext("expanded %s-%u copied %s in %s, "
10287 		    "on %s"), vname, (int)pres->pres_expanding_vdev,
10288 		    copied_buf, time_buf, ctime((time_t *)&end));
10289 	} else {
10290 		char examined_buf[7], total_buf[7], rate_buf[7];
10291 		uint64_t copied, total, elapsed, rate, secs_left;
10292 		double fraction_done;
10293 
10294 		assert(pres->pres_state == DSS_SCANNING);
10295 
10296 		/*
10297 		 * Expansion is in progress.
10298 		 */
10299 		(void) printf(gettext(
10300 		    "expansion of %s-%u in progress since %s"),
10301 		    vname, (int)pres->pres_expanding_vdev, ctime(&start));
10302 
10303 		copied = pres->pres_reflowed > 0 ? pres->pres_reflowed : 1;
10304 		total = pres->pres_to_reflow;
10305 		fraction_done = (double)copied / total;
10306 
10307 		/* elapsed time for this pass */
10308 		elapsed = time(NULL) - pres->pres_start_time;
10309 		elapsed = elapsed > 0 ? elapsed : 1;
10310 		rate = copied / elapsed;
10311 		rate = rate > 0 ? rate : 1;
10312 		secs_left = (total - copied) / rate;
10313 
10314 		zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10315 		zfs_nicenum(total, total_buf, sizeof (total_buf));
10316 		zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10317 
10318 		/*
10319 		 * do not print estimated time if hours_left is more than
10320 		 * 30 days
10321 		 */
10322 		(void) printf(gettext("\t%s / %s copied at %s/s, %.2f%% done"),
10323 		    examined_buf, total_buf, rate_buf, 100 * fraction_done);
10324 		if (pres->pres_waiting_for_resilver) {
10325 			(void) printf(gettext(", paused for resilver or "
10326 			    "clear\n"));
10327 		} else if (secs_left < (30 * 24 * 3600)) {
10328 			char time_buf[32];
10329 			secs_to_dhms(secs_left, time_buf);
10330 			(void) printf(gettext(", %s to go\n"), time_buf);
10331 		} else {
10332 			(void) printf(gettext(
10333 			    ", (copy is slow, no estimated time)\n"));
10334 		}
10335 	}
10336 	free(vname);
10337 }
10338 static void
print_checkpoint_status(pool_checkpoint_stat_t * pcs)10339 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
10340 {
10341 	time_t start;
10342 	char space_buf[7];
10343 
10344 	if (pcs == NULL || pcs->pcs_state == CS_NONE)
10345 		return;
10346 
10347 	(void) printf(gettext("checkpoint: "));
10348 
10349 	start = pcs->pcs_start_time;
10350 	zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
10351 
10352 	if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
10353 		char *date = ctime(&start);
10354 
10355 		/*
10356 		 * ctime() adds a newline at the end of the generated
10357 		 * string, thus the weird format specifier and the
10358 		 * strlen() call used to chop it off from the output.
10359 		 */
10360 		(void) printf(gettext("created %.*s, consumes %s\n"),
10361 		    (int)(strlen(date) - 1), date, space_buf);
10362 		return;
10363 	}
10364 
10365 	assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
10366 
10367 	(void) printf(gettext("discarding, %s remaining.\n"),
10368 	    space_buf);
10369 }
10370 
10371 static void
print_error_log(zpool_handle_t * zhp)10372 print_error_log(zpool_handle_t *zhp)
10373 {
10374 	nvlist_t *nverrlist = NULL;
10375 	nvpair_t *elem;
10376 	char *pathname;
10377 	size_t len = MAXPATHLEN * 2;
10378 
10379 	if (zpool_get_errlog(zhp, &nverrlist) != 0)
10380 		return;
10381 
10382 	(void) printf("errors: Permanent errors have been "
10383 	    "detected in the following files:\n\n");
10384 
10385 	pathname = safe_malloc(len);
10386 	elem = NULL;
10387 	while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
10388 		nvlist_t *nv;
10389 		uint64_t dsobj, obj;
10390 
10391 		verify(nvpair_value_nvlist(elem, &nv) == 0);
10392 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
10393 		    &dsobj) == 0);
10394 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
10395 		    &obj) == 0);
10396 		zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
10397 		(void) printf("%7s %s\n", "", pathname);
10398 	}
10399 	free(pathname);
10400 	nvlist_free(nverrlist);
10401 }
10402 
10403 static void
print_spares(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t ** spares,uint_t nspares)10404 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
10405     uint_t nspares)
10406 {
10407 	uint_t i;
10408 	char *name;
10409 
10410 	if (nspares == 0)
10411 		return;
10412 
10413 	(void) printf(gettext("\tspares\n"));
10414 
10415 	for (i = 0; i < nspares; i++) {
10416 		name = zpool_vdev_name(g_zfs, zhp, spares[i],
10417 		    cb->cb_name_flags);
10418 		print_status_config(zhp, cb, name, spares[i], 2, B_TRUE, NULL);
10419 		free(name);
10420 	}
10421 }
10422 
10423 static void
print_l2cache(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t ** l2cache,uint_t nl2cache)10424 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
10425     uint_t nl2cache)
10426 {
10427 	uint_t i;
10428 	char *name;
10429 
10430 	if (nl2cache == 0)
10431 		return;
10432 
10433 	(void) printf(gettext("\tcache\n"));
10434 
10435 	for (i = 0; i < nl2cache; i++) {
10436 		name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
10437 		    cb->cb_name_flags);
10438 		print_status_config(zhp, cb, name, l2cache[i], 2,
10439 		    B_FALSE, NULL);
10440 		free(name);
10441 	}
10442 }
10443 
10444 static void
print_dedup_stats(zpool_handle_t * zhp,nvlist_t * config,boolean_t literal)10445 print_dedup_stats(zpool_handle_t *zhp, nvlist_t *config, boolean_t literal)
10446 {
10447 	ddt_histogram_t *ddh;
10448 	ddt_stat_t *dds;
10449 	ddt_object_t *ddo;
10450 	uint_t c;
10451 	/* Extra space provided for literal display */
10452 	char dspace[32], mspace[32], cspace[32];
10453 	uint64_t cspace_prop;
10454 	enum zfs_nicenum_format format;
10455 	zprop_source_t src;
10456 
10457 	/*
10458 	 * If the pool was faulted then we may not have been able to
10459 	 * obtain the config. Otherwise, if we have anything in the dedup
10460 	 * table continue processing the stats.
10461 	 */
10462 	if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
10463 	    (uint64_t **)&ddo, &c) != 0)
10464 		return;
10465 
10466 	(void) printf("\n");
10467 	(void) printf(gettext(" dedup: "));
10468 	if (ddo->ddo_count == 0) {
10469 		(void) printf(gettext("no DDT entries\n"));
10470 		return;
10471 	}
10472 
10473 	/*
10474 	 * Squash cached size into in-core size to handle race.
10475 	 * Only include cached size if it is available.
10476 	 */
10477 	cspace_prop = zpool_get_prop_int(zhp, ZPOOL_PROP_DEDUPCACHED, &src);
10478 	cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
10479 	format = literal ? ZFS_NICENUM_RAW : ZFS_NICENUM_1024;
10480 	zfs_nicenum_format(cspace_prop, cspace, sizeof (cspace), format);
10481 	zfs_nicenum_format(ddo->ddo_dspace, dspace, sizeof (dspace), format);
10482 	zfs_nicenum_format(ddo->ddo_mspace, mspace, sizeof (mspace), format);
10483 	(void) printf("DDT entries %llu, size %s on disk, %s in core",
10484 	    (u_longlong_t)ddo->ddo_count,
10485 	    dspace,
10486 	    mspace);
10487 	if (src != ZPROP_SRC_DEFAULT) {
10488 		(void) printf(", %s cached (%.02f%%)",
10489 		    cspace,
10490 		    (double)cspace_prop / (double)ddo->ddo_mspace * 100.0);
10491 	}
10492 	(void) printf("\n");
10493 
10494 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
10495 	    (uint64_t **)&dds, &c) == 0);
10496 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
10497 	    (uint64_t **)&ddh, &c) == 0);
10498 	zpool_dump_ddt(dds, ddh, literal);
10499 }
10500 
10501 #define	ST_SIZE	4096
10502 #define	AC_SIZE	2048
10503 
10504 static void
print_status_reason(zpool_handle_t * zhp,status_cbdata_t * cbp,zpool_status_t reason,zpool_errata_t errata,nvlist_t * item)10505 print_status_reason(zpool_handle_t *zhp, status_cbdata_t *cbp,
10506     zpool_status_t reason, zpool_errata_t errata, nvlist_t *item)
10507 {
10508 	char status[ST_SIZE];
10509 	char action[AC_SIZE];
10510 	memset(status, 0, ST_SIZE);
10511 	memset(action, 0, AC_SIZE);
10512 
10513 	switch (reason) {
10514 	case ZPOOL_STATUS_MISSING_DEV_R:
10515 		(void) snprintf(status, ST_SIZE,
10516 		    gettext("One or more devices could "
10517 		    "not be opened.  Sufficient replicas exist for\n\tthe pool "
10518 		    "to continue functioning in a degraded state.\n"));
10519 		(void) snprintf(action, AC_SIZE,
10520 		    gettext("Attach the missing device "
10521 		    "and online it using 'zpool online'.\n"));
10522 		break;
10523 
10524 	case ZPOOL_STATUS_MISSING_DEV_NR:
10525 		(void) snprintf(status, ST_SIZE,
10526 		    gettext("One or more devices could "
10527 		    "not be opened.  There are insufficient\n\treplicas for the"
10528 		    " pool to continue functioning.\n"));
10529 		(void) snprintf(action, AC_SIZE,
10530 		    gettext("Attach the missing device "
10531 		    "and online it using 'zpool online'.\n"));
10532 		break;
10533 
10534 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
10535 		(void) snprintf(status, ST_SIZE,
10536 		    gettext("One or more devices could "
10537 		    "not be used because the label is missing or\n\tinvalid.  "
10538 		    "Sufficient replicas exist for the pool to continue\n\t"
10539 		    "functioning in a degraded state.\n"));
10540 		(void) snprintf(action, AC_SIZE,
10541 		    gettext("Replace the device using 'zpool replace'.\n"));
10542 		break;
10543 
10544 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
10545 		(void) snprintf(status, ST_SIZE,
10546 		    gettext("One or more devices could "
10547 		    "not be used because the label is missing \n\tor invalid.  "
10548 		    "There are insufficient replicas for the pool to "
10549 		    "continue\n\tfunctioning.\n"));
10550 		zpool_explain_recover(zpool_get_handle(zhp),
10551 		    zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
10552 		    action, AC_SIZE);
10553 		break;
10554 
10555 	case ZPOOL_STATUS_FAILING_DEV:
10556 		(void) snprintf(status, ST_SIZE,
10557 		    gettext("One or more devices has "
10558 		    "experienced an unrecoverable error.  An\n\tattempt was "
10559 		    "made to correct the error.  Applications are "
10560 		    "unaffected.\n"));
10561 		(void) snprintf(action, AC_SIZE, gettext("Determine if the "
10562 		    "device needs to be replaced, and clear the errors\n\tusing"
10563 		    " 'zpool clear' or replace the device with 'zpool "
10564 		    "replace'.\n"));
10565 		break;
10566 
10567 	case ZPOOL_STATUS_OFFLINE_DEV:
10568 		(void) snprintf(status, ST_SIZE,
10569 		    gettext("One or more devices has "
10570 		    "been taken offline by the administrator.\n\tSufficient "
10571 		    "replicas exist for the pool to continue functioning in "
10572 		    "a\n\tdegraded state.\n"));
10573 		(void) snprintf(action, AC_SIZE, gettext("Online the device "
10574 		    "using 'zpool online' or replace the device with\n\t'zpool "
10575 		    "replace'.\n"));
10576 		break;
10577 
10578 	case ZPOOL_STATUS_REMOVED_DEV:
10579 		(void) snprintf(status, ST_SIZE,
10580 		    gettext("One or more devices have "
10581 		    "been removed.\n\tSufficient replicas exist for the pool "
10582 		    "to continue functioning in a\n\tdegraded state.\n"));
10583 		(void) snprintf(action, AC_SIZE, gettext("Online the device "
10584 		    "using zpool online' or replace the device with\n\t'zpool "
10585 		    "replace'.\n"));
10586 		break;
10587 
10588 	case ZPOOL_STATUS_RESILVERING:
10589 	case ZPOOL_STATUS_REBUILDING:
10590 		(void) snprintf(status, ST_SIZE,
10591 		    gettext("One or more devices is "
10592 		    "currently being resilvered.  The pool will\n\tcontinue "
10593 		    "to function, possibly in a degraded state.\n"));
10594 		(void) snprintf(action, AC_SIZE,
10595 		    gettext("Wait for the resilver to complete.\n"));
10596 		break;
10597 
10598 	case ZPOOL_STATUS_REBUILD_SCRUB:
10599 		(void) snprintf(status, ST_SIZE,
10600 		    gettext("One or more devices have "
10601 		    "been sequentially resilvered, scrubbing\n\tthe pool "
10602 		    "is recommended.\n"));
10603 		(void) snprintf(action, AC_SIZE, gettext("Use 'zpool scrub' to "
10604 		    "verify all data checksums.\n"));
10605 		break;
10606 
10607 	case ZPOOL_STATUS_CORRUPT_DATA:
10608 		(void) snprintf(status, ST_SIZE,
10609 		    gettext("One or more devices has "
10610 		    "experienced an error resulting in data\n\tcorruption.  "
10611 		    "Applications may be affected.\n"));
10612 		(void) snprintf(action, AC_SIZE,
10613 		    gettext("Restore the file in question"
10614 		    " if possible.  Otherwise restore the\n\tentire pool from "
10615 		    "backup.\n"));
10616 		break;
10617 
10618 	case ZPOOL_STATUS_CORRUPT_POOL:
10619 		(void) snprintf(status, ST_SIZE, gettext("The pool metadata is "
10620 		    "incomplete or corrupted and the pool cannot be "
10621 		    "opened.\n"));
10622 		zpool_explain_recover(zpool_get_handle(zhp),
10623 		    zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
10624 		    action, AC_SIZE);
10625 		break;
10626 
10627 	case ZPOOL_STATUS_VERSION_OLDER:
10628 		(void) snprintf(status, ST_SIZE,
10629 		    gettext("The pool is formatted using "
10630 		    "a legacy on-disk format.  The pool can\n\tstill be used, "
10631 		    "but some features are unavailable.\n"));
10632 		(void) snprintf(action, AC_SIZE,
10633 		    gettext("Upgrade the pool using "
10634 		    "'zpool upgrade'.  Once this is done, the\n\tpool will no "
10635 		    "longer be accessible on software that does not support\n\t"
10636 		    "feature flags.\n"));
10637 		break;
10638 
10639 	case ZPOOL_STATUS_VERSION_NEWER:
10640 		(void) snprintf(status, ST_SIZE,
10641 		    gettext("The pool has been upgraded "
10642 		    "to a newer, incompatible on-disk version.\n\tThe pool "
10643 		    "cannot be accessed on this system.\n"));
10644 		(void) snprintf(action, AC_SIZE,
10645 		    gettext("Access the pool from a "
10646 		    "system running more recent software, or\n\trestore the "
10647 		    "pool from backup.\n"));
10648 		break;
10649 
10650 	case ZPOOL_STATUS_FEAT_DISABLED:
10651 		(void) snprintf(status, ST_SIZE, gettext("Some supported and "
10652 		    "requested features are not enabled on the pool.\n\t"
10653 		    "The pool can still be used, but some features are "
10654 		    "unavailable.\n"));
10655 		(void) snprintf(action, AC_SIZE,
10656 		    gettext("Enable all features using "
10657 		    "'zpool upgrade'. Once this is done,\n\tthe pool may no "
10658 		    "longer be accessible by software that does not support\n\t"
10659 		    "the features. See zpool-features(7) for details.\n"));
10660 		break;
10661 
10662 	case ZPOOL_STATUS_COMPATIBILITY_ERR:
10663 		(void) snprintf(status, ST_SIZE, gettext("This pool has a "
10664 		    "compatibility list specified, but it could not be\n\t"
10665 		    "read/parsed at this time. The pool can still be used, "
10666 		    "but this\n\tshould be investigated.\n"));
10667 		(void) snprintf(action, AC_SIZE,
10668 		    gettext("Check the value of the "
10669 		    "'compatibility' property against the\n\t"
10670 		    "appropriate file in " ZPOOL_SYSCONF_COMPAT_D " or "
10671 		    ZPOOL_DATA_COMPAT_D ".\n"));
10672 		break;
10673 
10674 	case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
10675 		(void) snprintf(status, ST_SIZE, gettext("One or more features "
10676 		    "are enabled on the pool despite not being\n\t"
10677 		    "requested by the 'compatibility' property.\n"));
10678 		(void) snprintf(action, AC_SIZE, gettext("Consider setting "
10679 		    "'compatibility' to an appropriate value, or\n\t"
10680 		    "adding needed features to the relevant file in\n\t"
10681 		    ZPOOL_SYSCONF_COMPAT_D " or " ZPOOL_DATA_COMPAT_D ".\n"));
10682 		break;
10683 
10684 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
10685 		(void) snprintf(status, ST_SIZE,
10686 		    gettext("The pool cannot be accessed "
10687 		    "on this system because it uses the\n\tfollowing feature(s)"
10688 		    " not supported on this system:\n"));
10689 		zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
10690 		    1024);
10691 		(void) snprintf(action, AC_SIZE,
10692 		    gettext("Access the pool from a "
10693 		    "system that supports the required feature(s),\n\tor "
10694 		    "restore the pool from backup.\n"));
10695 		break;
10696 
10697 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
10698 		(void) snprintf(status, ST_SIZE, gettext("The pool can only be "
10699 		    "accessed in read-only mode on this system. It\n\tcannot be"
10700 		    " accessed in read-write mode because it uses the "
10701 		    "following\n\tfeature(s) not supported on this system:\n"));
10702 		zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
10703 		    1024);
10704 		(void) snprintf(action, AC_SIZE,
10705 		    gettext("The pool cannot be accessed "
10706 		    "in read-write mode. Import the pool with\n"
10707 		    "\t\"-o readonly=on\", access the pool from a system that "
10708 		    "supports the\n\trequired feature(s), or restore the "
10709 		    "pool from backup.\n"));
10710 		break;
10711 
10712 	case ZPOOL_STATUS_FAULTED_DEV_R:
10713 		(void) snprintf(status, ST_SIZE,
10714 		    gettext("One or more devices are "
10715 		    "faulted in response to persistent errors.\n\tSufficient "
10716 		    "replicas exist for the pool to continue functioning "
10717 		    "in a\n\tdegraded state.\n"));
10718 		(void) snprintf(action, AC_SIZE,
10719 		    gettext("Replace the faulted device, "
10720 		    "or use 'zpool clear' to mark the device\n\trepaired.\n"));
10721 		break;
10722 
10723 	case ZPOOL_STATUS_FAULTED_DEV_NR:
10724 		(void) snprintf(status, ST_SIZE,
10725 		    gettext("One or more devices are "
10726 		    "faulted in response to persistent errors.  There are "
10727 		    "insufficient replicas for the pool to\n\tcontinue "
10728 		    "functioning.\n"));
10729 		(void) snprintf(action, AC_SIZE,
10730 		    gettext("Destroy and re-create the "
10731 		    "pool from a backup source.  Manually marking the device\n"
10732 		    "\trepaired using 'zpool clear' may allow some data "
10733 		    "to be recovered.\n"));
10734 		break;
10735 
10736 	case ZPOOL_STATUS_IO_FAILURE_MMP:
10737 		(void) snprintf(status, ST_SIZE,
10738 		    gettext("The pool is suspended "
10739 		    "because multihost writes failed or were delayed;\n\t"
10740 		    "another system could import the pool undetected.\n"));
10741 		(void) snprintf(action, AC_SIZE,
10742 		    gettext("Make sure the pool's devices"
10743 		    " are connected, then reboot your system and\n\timport the "
10744 		    "pool or run 'zpool clear' to resume the pool.\n"));
10745 		break;
10746 
10747 	case ZPOOL_STATUS_IO_FAILURE_WAIT:
10748 	case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
10749 		(void) snprintf(status, ST_SIZE,
10750 		    gettext("One or more devices are "
10751 		    "faulted in response to IO failures.\n"));
10752 		(void) snprintf(action, AC_SIZE,
10753 		    gettext("Make sure the affected "
10754 		    "devices are connected, then run 'zpool clear'.\n"));
10755 		break;
10756 
10757 	case ZPOOL_STATUS_BAD_LOG:
10758 		(void) snprintf(status, ST_SIZE, gettext("An intent log record "
10759 		    "could not be read.\n"
10760 		    "\tWaiting for administrator intervention to fix the "
10761 		    "faulted pool.\n"));
10762 		(void) snprintf(action, AC_SIZE,
10763 		    gettext("Either restore the affected "
10764 		    "device(s) and run 'zpool online',\n"
10765 		    "\tor ignore the intent log records by running "
10766 		    "'zpool clear'.\n"));
10767 		break;
10768 
10769 	case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
10770 		(void) snprintf(status, ST_SIZE,
10771 		    gettext("One or more devices are "
10772 		    "configured to use a non-native block size.\n"
10773 		    "\tExpect reduced performance.\n"));
10774 		(void) snprintf(action, AC_SIZE,
10775 		    gettext("Replace affected devices "
10776 		    "with devices that support the\n\tconfigured block size, "
10777 		    "or migrate data to a properly configured\n\tpool.\n"));
10778 		break;
10779 
10780 	case ZPOOL_STATUS_HOSTID_MISMATCH:
10781 		(void) snprintf(status, ST_SIZE,
10782 		    gettext("Mismatch between pool hostid"
10783 		    " and system hostid on imported pool.\n\tThis pool was "
10784 		    "previously imported into a system with a different "
10785 		    "hostid,\n\tand then was verbatim imported into this "
10786 		    "system.\n"));
10787 		(void) snprintf(action, AC_SIZE,
10788 		    gettext("Export this pool on all "
10789 		    "systems on which it is imported.\n"
10790 		    "\tThen import it to correct the mismatch.\n"));
10791 		break;
10792 
10793 	case ZPOOL_STATUS_ERRATA:
10794 		(void) snprintf(status, ST_SIZE,
10795 		    gettext("Errata #%d detected.\n"), errata);
10796 		switch (errata) {
10797 		case ZPOOL_ERRATA_NONE:
10798 			break;
10799 
10800 		case ZPOOL_ERRATA_ZOL_2094_SCRUB:
10801 			(void) snprintf(action, AC_SIZE,
10802 			    gettext("To correct the issue run "
10803 			    "'zpool scrub'.\n"));
10804 			break;
10805 
10806 		case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
10807 			(void) strlcat(status, gettext("\tExisting encrypted "
10808 			    "datasets contain an on-disk incompatibility\n\t "
10809 			    "which needs to be corrected.\n"), ST_SIZE);
10810 			(void) snprintf(action, AC_SIZE,
10811 			    gettext("To correct the issue"
10812 			    " backup existing encrypted datasets to new\n\t"
10813 			    "encrypted datasets and destroy the old ones. "
10814 			    "'zfs mount -o ro' can\n\tbe used to temporarily "
10815 			    "mount existing encrypted datasets readonly.\n"));
10816 			break;
10817 
10818 		case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
10819 			(void) strlcat(status, gettext("\tExisting encrypted "
10820 			    "snapshots and bookmarks contain an on-disk\n\t"
10821 			    "incompatibility. This may cause on-disk "
10822 			    "corruption if they are used\n\twith "
10823 			    "'zfs recv'.\n"), ST_SIZE);
10824 			(void) snprintf(action, AC_SIZE,
10825 			    gettext("To correct the"
10826 			    "issue, enable the bookmark_v2 feature. No "
10827 			    "additional\n\taction is needed if there are no "
10828 			    "encrypted snapshots or bookmarks.\n\tIf preserving"
10829 			    "the encrypted snapshots and bookmarks is required,"
10830 			    " use\n\ta non-raw send to backup and restore them."
10831 			    " Alternately, they may be\n\tremoved to resolve "
10832 			    "the incompatibility.\n"));
10833 			break;
10834 
10835 		default:
10836 			/*
10837 			 * All errata which allow the pool to be imported
10838 			 * must contain an action message.
10839 			 */
10840 			assert(0);
10841 		}
10842 		break;
10843 
10844 	default:
10845 		/*
10846 		 * The remaining errors can't actually be generated, yet.
10847 		 */
10848 		assert(reason == ZPOOL_STATUS_OK);
10849 	}
10850 
10851 	if (status[0] != 0) {
10852 		if (cbp->cb_json)
10853 			fnvlist_add_string(item, "status", status);
10854 		else {
10855 			(void) printf_color(ANSI_BOLD, gettext("status: "));
10856 			(void) printf_color(ANSI_YELLOW, status);
10857 		}
10858 	}
10859 
10860 	if (action[0] != 0) {
10861 		if (cbp->cb_json)
10862 			fnvlist_add_string(item, "action", action);
10863 		else {
10864 			(void) printf_color(ANSI_BOLD, gettext("action: "));
10865 			(void) printf_color(ANSI_YELLOW, action);
10866 		}
10867 	}
10868 }
10869 
10870 static int
status_callback_json(zpool_handle_t * zhp,void * data)10871 status_callback_json(zpool_handle_t *zhp, void *data)
10872 {
10873 	status_cbdata_t *cbp = data;
10874 	nvlist_t *config, *nvroot;
10875 	const char *msgid;
10876 	char pool_guid[256];
10877 	char msgbuf[256];
10878 	uint64_t guid;
10879 	zpool_status_t reason;
10880 	zpool_errata_t errata;
10881 	uint_t c;
10882 	vdev_stat_t *vs;
10883 	nvlist_t *item, *d, *load_info, *vds;
10884 
10885 	/* If dedup stats were requested, also fetch dedupcached. */
10886 	if (cbp->cb_dedup_stats > 1)
10887 		zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
10888 	reason = zpool_get_status(zhp, &msgid, &errata);
10889 	/*
10890 	 * If we were given 'zpool status -x', only report those pools with
10891 	 * problems.
10892 	 */
10893 	if (cbp->cb_explain &&
10894 	    (reason == ZPOOL_STATUS_OK ||
10895 	    reason == ZPOOL_STATUS_VERSION_OLDER ||
10896 	    reason == ZPOOL_STATUS_FEAT_DISABLED ||
10897 	    reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
10898 	    reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
10899 		return (0);
10900 	}
10901 
10902 	d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
10903 	item = fnvlist_alloc();
10904 	vds = fnvlist_alloc();
10905 	fill_pool_info(item, zhp, B_FALSE, cbp->cb_json_as_int);
10906 	config = zpool_get_config(zhp, NULL);
10907 
10908 	if (config != NULL) {
10909 		nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
10910 		verify(nvlist_lookup_uint64_array(nvroot,
10911 		    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &c) == 0);
10912 		if (cbp->cb_json_pool_key_guid) {
10913 			guid = fnvlist_lookup_uint64(config,
10914 			    ZPOOL_CONFIG_POOL_GUID);
10915 			(void) snprintf(pool_guid, 256, "%llu",
10916 			    (u_longlong_t)guid);
10917 		}
10918 		cbp->cb_count++;
10919 
10920 		print_status_reason(zhp, cbp, reason, errata, item);
10921 		if (msgid != NULL) {
10922 			(void) snprintf(msgbuf, 256,
10923 			    "https://openzfs.github.io/openzfs-docs/msg/%s",
10924 			    msgid);
10925 			fnvlist_add_string(item, "msgid", msgid);
10926 			fnvlist_add_string(item, "moreinfo", msgbuf);
10927 		}
10928 
10929 		if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
10930 		    &load_info) == 0) {
10931 			fnvlist_add_nvlist(item, ZPOOL_CONFIG_LOAD_INFO,
10932 			    load_info);
10933 		}
10934 
10935 		scan_status_nvlist(zhp, cbp, nvroot, item);
10936 		removal_status_nvlist(zhp, cbp, nvroot, item);
10937 		checkpoint_status_nvlist(nvroot, cbp, item);
10938 		raidz_expand_status_nvlist(zhp, cbp, nvroot, item);
10939 		vdev_stats_nvlist(zhp, cbp, nvroot, 0, B_FALSE, NULL, vds);
10940 		if (cbp->cb_flat_vdevs) {
10941 			class_vdevs_nvlist(zhp, cbp, nvroot,
10942 			    VDEV_ALLOC_BIAS_DEDUP, vds);
10943 			class_vdevs_nvlist(zhp, cbp, nvroot,
10944 			    VDEV_ALLOC_BIAS_SPECIAL, vds);
10945 			class_vdevs_nvlist(zhp, cbp, nvroot,
10946 			    VDEV_ALLOC_CLASS_LOGS, vds);
10947 			l2cache_nvlist(zhp, cbp, nvroot, vds);
10948 			spares_nvlist(zhp, cbp, nvroot, vds);
10949 
10950 			fnvlist_add_nvlist(item, "vdevs", vds);
10951 			fnvlist_free(vds);
10952 		} else {
10953 			fnvlist_add_nvlist(item, "vdevs", vds);
10954 			fnvlist_free(vds);
10955 
10956 			class_vdevs_nvlist(zhp, cbp, nvroot,
10957 			    VDEV_ALLOC_BIAS_DEDUP, item);
10958 			class_vdevs_nvlist(zhp, cbp, nvroot,
10959 			    VDEV_ALLOC_BIAS_SPECIAL, item);
10960 			class_vdevs_nvlist(zhp, cbp, nvroot,
10961 			    VDEV_ALLOC_CLASS_LOGS, item);
10962 			l2cache_nvlist(zhp, cbp, nvroot, item);
10963 			spares_nvlist(zhp, cbp, nvroot, item);
10964 		}
10965 		dedup_stats_nvlist(zhp, cbp, item);
10966 		errors_nvlist(zhp, cbp, item);
10967 	}
10968 	if (cbp->cb_json_pool_key_guid) {
10969 		fnvlist_add_nvlist(d, pool_guid, item);
10970 	} else {
10971 		fnvlist_add_nvlist(d, zpool_get_name(zhp),
10972 		    item);
10973 	}
10974 	fnvlist_free(item);
10975 	return (0);
10976 }
10977 
10978 /*
10979  * Display a summary of pool status.  Displays a summary such as:
10980  *
10981  *        pool: tank
10982  *	status: DEGRADED
10983  *	reason: One or more devices ...
10984  *         see: https://openzfs.github.io/openzfs-docs/msg/ZFS-xxxx-01
10985  *	config:
10986  *		mirror		DEGRADED
10987  *                c1t0d0	OK
10988  *                c2t0d0	UNAVAIL
10989  *
10990  * When given the '-v' option, we print out the complete config.  If the '-e'
10991  * option is specified, then we print out error rate information as well.
10992  */
10993 static int
status_callback(zpool_handle_t * zhp,void * data)10994 status_callback(zpool_handle_t *zhp, void *data)
10995 {
10996 	status_cbdata_t *cbp = data;
10997 	nvlist_t *config, *nvroot;
10998 	const char *msgid;
10999 	zpool_status_t reason;
11000 	zpool_errata_t errata;
11001 	const char *health;
11002 	uint_t c;
11003 	vdev_stat_t *vs;
11004 
11005 	/* If dedup stats were requested, also fetch dedupcached. */
11006 	if (cbp->cb_dedup_stats > 1)
11007 		zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
11008 
11009 	config = zpool_get_config(zhp, NULL);
11010 	reason = zpool_get_status(zhp, &msgid, &errata);
11011 
11012 	cbp->cb_count++;
11013 
11014 	/*
11015 	 * If we were given 'zpool status -x', only report those pools with
11016 	 * problems.
11017 	 */
11018 	if (cbp->cb_explain &&
11019 	    (reason == ZPOOL_STATUS_OK ||
11020 	    reason == ZPOOL_STATUS_VERSION_OLDER ||
11021 	    reason == ZPOOL_STATUS_FEAT_DISABLED ||
11022 	    reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
11023 	    reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
11024 		if (!cbp->cb_allpools) {
11025 			(void) printf(gettext("pool '%s' is healthy\n"),
11026 			    zpool_get_name(zhp));
11027 			if (cbp->cb_first)
11028 				cbp->cb_first = B_FALSE;
11029 		}
11030 		return (0);
11031 	}
11032 
11033 	if (cbp->cb_first)
11034 		cbp->cb_first = B_FALSE;
11035 	else
11036 		(void) printf("\n");
11037 
11038 	nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
11039 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
11040 	    (uint64_t **)&vs, &c) == 0);
11041 
11042 	health = zpool_get_state_str(zhp);
11043 
11044 	printf("  ");
11045 	(void) printf_color(ANSI_BOLD, gettext("pool:"));
11046 	printf(" %s\n", zpool_get_name(zhp));
11047 	(void) fputc(' ', stdout);
11048 	(void) printf_color(ANSI_BOLD, gettext("state: "));
11049 
11050 	(void) printf_color(health_str_to_color(health), "%s", health);
11051 
11052 	(void) fputc('\n', stdout);
11053 	print_status_reason(zhp, cbp, reason, errata, NULL);
11054 
11055 	if (msgid != NULL) {
11056 		printf("   ");
11057 		(void) printf_color(ANSI_BOLD, gettext("see:"));
11058 		printf(gettext(
11059 		    " https://openzfs.github.io/openzfs-docs/msg/%s\n"),
11060 		    msgid);
11061 	}
11062 
11063 	if (config != NULL) {
11064 		uint64_t nerr;
11065 		nvlist_t **spares, **l2cache;
11066 		uint_t nspares, nl2cache;
11067 
11068 		print_scan_status(zhp, nvroot);
11069 
11070 		pool_removal_stat_t *prs = NULL;
11071 		(void) nvlist_lookup_uint64_array(nvroot,
11072 		    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
11073 		print_removal_status(zhp, prs);
11074 
11075 		pool_checkpoint_stat_t *pcs = NULL;
11076 		(void) nvlist_lookup_uint64_array(nvroot,
11077 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
11078 		print_checkpoint_status(pcs);
11079 
11080 		pool_raidz_expand_stat_t *pres = NULL;
11081 		(void) nvlist_lookup_uint64_array(nvroot,
11082 		    ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
11083 		print_raidz_expand_status(zhp, pres);
11084 
11085 		cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
11086 		    cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
11087 		if (cbp->cb_namewidth < 10)
11088 			cbp->cb_namewidth = 10;
11089 
11090 		color_start(ANSI_BOLD);
11091 		(void) printf(gettext("config:\n\n"));
11092 		(void) printf(gettext("\t%-*s  %-8s %5s %5s %5s"),
11093 		    cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
11094 		    "CKSUM");
11095 		color_end();
11096 
11097 		if (cbp->cb_print_slow_ios) {
11098 			(void) printf_color(ANSI_BOLD, " %5s", gettext("SLOW"));
11099 		}
11100 
11101 		if (cbp->cb_print_power) {
11102 			(void) printf_color(ANSI_BOLD, " %5s",
11103 			    gettext("POWER"));
11104 		}
11105 
11106 		if (cbp->cb_print_dio_verify) {
11107 			(void) printf_color(ANSI_BOLD, " %5s", gettext("DIO"));
11108 		}
11109 
11110 		if (cbp->vcdl != NULL)
11111 			print_cmd_columns(cbp->vcdl, 0);
11112 
11113 		printf("\n");
11114 
11115 		print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
11116 		    B_FALSE, NULL);
11117 
11118 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
11119 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
11120 		print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
11121 
11122 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
11123 		    &l2cache, &nl2cache) == 0)
11124 			print_l2cache(zhp, cbp, l2cache, nl2cache);
11125 
11126 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
11127 		    &spares, &nspares) == 0)
11128 			print_spares(zhp, cbp, spares, nspares);
11129 
11130 		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
11131 		    &nerr) == 0) {
11132 			(void) printf("\n");
11133 			if (nerr == 0) {
11134 				(void) printf(gettext(
11135 				    "errors: No known data errors\n"));
11136 			} else if (!cbp->cb_verbose) {
11137 				color_start(ANSI_RED);
11138 				(void) printf(gettext("errors: %llu data "
11139 				    "errors, use '-v' for a list\n"),
11140 				    (u_longlong_t)nerr);
11141 				color_end();
11142 			} else {
11143 				print_error_log(zhp);
11144 			}
11145 		}
11146 
11147 		if (cbp->cb_dedup_stats)
11148 			print_dedup_stats(zhp, config, cbp->cb_literal);
11149 	} else {
11150 		(void) printf(gettext("config: The configuration cannot be "
11151 		    "determined.\n"));
11152 	}
11153 
11154 	return (0);
11155 }
11156 
11157 /*
11158  * zpool status [-dDegiLpPstvx] [-c [script1,script2,...]] ...
11159  * 				[-j|--json [--json-flat-vdevs] [--json-int] ...
11160  * 				[--json-pool-key-guid]] [--power] [-T d|u] ...
11161  * 				[pool] [interval [count]]
11162  *
11163  *	-c CMD	For each vdev, run command CMD
11164  *	-D	Display dedup status (undocumented)
11165  *	-d	Display Direct I/O write verify errors
11166  *	-e	Display only unhealthy vdevs
11167  *	-g	Display guid for individual vdev name.
11168  *	-i	Display vdev initialization status.
11169  *	-j [...]	Display output in JSON format
11170  *	   --json-flat-vdevs Display vdevs in flat hierarchy
11171  *	   --json-int Display numbers in integer format instead of string
11172  *	   --json-pool-key-guid Use pool GUID as key for pool objects
11173  *	-L	Follow links when resolving vdev path name.
11174  *	-P	Display full path for vdev name.
11175  *	-p	Display values in parsable (exact) format.
11176  *	--power	Display vdev enclosure slot power status
11177  *	-s	Display slow IOs column.
11178  *	-T	Display a timestamp in date(1) or Unix format
11179  *	-t	Display vdev TRIM status.
11180  *	-v	Display complete error logs
11181  *	-x	Display only pools with potential problems
11182  *
11183  * Describes the health status of all pools or some subset.
11184  */
11185 int
zpool_do_status(int argc,char ** argv)11186 zpool_do_status(int argc, char **argv)
11187 {
11188 	int c;
11189 	int ret;
11190 	float interval = 0;
11191 	unsigned long count = 0;
11192 	status_cbdata_t cb = { 0 };
11193 	nvlist_t *data;
11194 	char *cmd = NULL;
11195 
11196 	struct option long_options[] = {
11197 		{"power", no_argument, NULL, ZPOOL_OPTION_POWER},
11198 		{"json", no_argument, NULL, 'j'},
11199 		{"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
11200 		{"json-flat-vdevs", no_argument, NULL,
11201 		    ZPOOL_OPTION_JSON_FLAT_VDEVS},
11202 		{"json-pool-key-guid", no_argument, NULL,
11203 		    ZPOOL_OPTION_POOL_KEY_GUID},
11204 		{0, 0, 0, 0}
11205 	};
11206 
11207 	/* check options */
11208 	while ((c = getopt_long(argc, argv, "c:jdDegiLpPstT:vx", long_options,
11209 	    NULL)) != -1) {
11210 		switch (c) {
11211 		case 'c':
11212 			if (cmd != NULL) {
11213 				fprintf(stderr,
11214 				    gettext("Can't set -c flag twice\n"));
11215 				exit(1);
11216 			}
11217 
11218 			if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
11219 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
11220 				fprintf(stderr, gettext(
11221 				    "Can't run -c, disabled by "
11222 				    "ZPOOL_SCRIPTS_ENABLED.\n"));
11223 				exit(1);
11224 			}
11225 
11226 			if ((getuid() <= 0 || geteuid() <= 0) &&
11227 			    !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
11228 				fprintf(stderr, gettext(
11229 				    "Can't run -c with root privileges "
11230 				    "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
11231 				exit(1);
11232 			}
11233 			cmd = optarg;
11234 			break;
11235 		case 'd':
11236 			cb.cb_print_dio_verify = B_TRUE;
11237 			break;
11238 		case 'D':
11239 			if (++cb.cb_dedup_stats  > 2)
11240 				cb.cb_dedup_stats = 2;
11241 			break;
11242 		case 'e':
11243 			cb.cb_print_unhealthy = B_TRUE;
11244 			break;
11245 		case 'g':
11246 			cb.cb_name_flags |= VDEV_NAME_GUID;
11247 			break;
11248 		case 'i':
11249 			cb.cb_print_vdev_init = B_TRUE;
11250 			break;
11251 		case 'L':
11252 			cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
11253 			break;
11254 		case 'p':
11255 			cb.cb_literal = B_TRUE;
11256 			break;
11257 		case 'P':
11258 			cb.cb_name_flags |= VDEV_NAME_PATH;
11259 			break;
11260 		case 's':
11261 			cb.cb_print_slow_ios = B_TRUE;
11262 			break;
11263 		case 't':
11264 			cb.cb_print_vdev_trim = B_TRUE;
11265 			break;
11266 		case 'T':
11267 			get_timestamp_arg(*optarg);
11268 			break;
11269 		case 'v':
11270 			cb.cb_verbose = B_TRUE;
11271 			break;
11272 		case 'j':
11273 			cb.cb_json = B_TRUE;
11274 			break;
11275 		case 'x':
11276 			cb.cb_explain = B_TRUE;
11277 			break;
11278 		case ZPOOL_OPTION_POWER:
11279 			cb.cb_print_power = B_TRUE;
11280 			break;
11281 		case ZPOOL_OPTION_JSON_FLAT_VDEVS:
11282 			cb.cb_flat_vdevs = B_TRUE;
11283 			break;
11284 		case ZPOOL_OPTION_JSON_NUMS_AS_INT:
11285 			cb.cb_json_as_int = B_TRUE;
11286 			cb.cb_literal = B_TRUE;
11287 			break;
11288 		case ZPOOL_OPTION_POOL_KEY_GUID:
11289 			cb.cb_json_pool_key_guid = B_TRUE;
11290 			break;
11291 		case '?':
11292 			if (optopt == 'c') {
11293 				print_zpool_script_list("status");
11294 				exit(0);
11295 			} else {
11296 				fprintf(stderr,
11297 				    gettext("invalid option '%c'\n"), optopt);
11298 			}
11299 			usage(B_FALSE);
11300 		}
11301 	}
11302 
11303 	argc -= optind;
11304 	argv += optind;
11305 
11306 	get_interval_count(&argc, argv, &interval, &count);
11307 
11308 	if (argc == 0)
11309 		cb.cb_allpools = B_TRUE;
11310 
11311 	cb.cb_first = B_TRUE;
11312 	cb.cb_print_status = B_TRUE;
11313 
11314 	if (cb.cb_flat_vdevs && !cb.cb_json) {
11315 		fprintf(stderr, gettext("'--json-flat-vdevs' only works with"
11316 		    " '-j' option\n"));
11317 		usage(B_FALSE);
11318 	}
11319 
11320 	if (cb.cb_json_as_int && !cb.cb_json) {
11321 		(void) fprintf(stderr, gettext("'--json-int' only works with"
11322 		    " '-j' option\n"));
11323 		usage(B_FALSE);
11324 	}
11325 
11326 	if (!cb.cb_json && cb.cb_json_pool_key_guid) {
11327 		(void) fprintf(stderr, gettext("'json-pool-key-guid' only"
11328 		    " works with '-j' option\n"));
11329 		usage(B_FALSE);
11330 	}
11331 
11332 	for (;;) {
11333 		if (cb.cb_json) {
11334 			cb.cb_jsobj = zpool_json_schema(0, 1);
11335 			data = fnvlist_alloc();
11336 			fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
11337 			fnvlist_free(data);
11338 		}
11339 
11340 		if (timestamp_fmt != NODATE) {
11341 			if (cb.cb_json) {
11342 				if (cb.cb_json_as_int) {
11343 					fnvlist_add_uint64(cb.cb_jsobj, "time",
11344 					    time(NULL));
11345 				} else {
11346 					char ts[128];
11347 					get_timestamp(timestamp_fmt, ts, 128);
11348 					fnvlist_add_string(cb.cb_jsobj, "time",
11349 					    ts);
11350 				}
11351 			} else
11352 				print_timestamp(timestamp_fmt);
11353 		}
11354 
11355 		if (cmd != NULL)
11356 			cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
11357 			    NULL, NULL, 0, 0);
11358 
11359 		if (cb.cb_json) {
11360 			ret = for_each_pool(argc, argv, B_TRUE, NULL,
11361 			    ZFS_TYPE_POOL, cb.cb_literal,
11362 			    status_callback_json, &cb);
11363 		} else {
11364 			ret = for_each_pool(argc, argv, B_TRUE, NULL,
11365 			    ZFS_TYPE_POOL, cb.cb_literal,
11366 			    status_callback, &cb);
11367 		}
11368 
11369 		if (cb.vcdl != NULL)
11370 			free_vdev_cmd_data_list(cb.vcdl);
11371 
11372 		if (cb.cb_json) {
11373 			if (ret == 0)
11374 				zcmd_print_json(cb.cb_jsobj);
11375 			else
11376 				nvlist_free(cb.cb_jsobj);
11377 		} else {
11378 			if (argc == 0 && cb.cb_count == 0) {
11379 				(void) fprintf(stderr, "%s",
11380 				    gettext("no pools available\n"));
11381 			} else if (cb.cb_explain && cb.cb_first &&
11382 			    cb.cb_allpools) {
11383 				(void) printf("%s",
11384 				    gettext("all pools are healthy\n"));
11385 			}
11386 		}
11387 
11388 		if (ret != 0)
11389 			return (ret);
11390 
11391 		if (interval == 0)
11392 			break;
11393 
11394 		if (count != 0 && --count == 0)
11395 			break;
11396 
11397 		(void) fflush(stdout);
11398 		(void) fsleep(interval);
11399 	}
11400 
11401 	return (0);
11402 }
11403 
11404 typedef struct upgrade_cbdata {
11405 	int	cb_first;
11406 	int	cb_argc;
11407 	uint64_t cb_version;
11408 	char	**cb_argv;
11409 } upgrade_cbdata_t;
11410 
11411 static int
check_unsupp_fs(zfs_handle_t * zhp,void * unsupp_fs)11412 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
11413 {
11414 	int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
11415 	int *count = (int *)unsupp_fs;
11416 
11417 	if (zfs_version > ZPL_VERSION) {
11418 		(void) printf(gettext("%s (v%d) is not supported by this "
11419 		    "implementation of ZFS.\n"),
11420 		    zfs_get_name(zhp), zfs_version);
11421 		(*count)++;
11422 	}
11423 
11424 	(void) zfs_iter_filesystems_v2(zhp, 0, check_unsupp_fs, unsupp_fs);
11425 
11426 	zfs_close(zhp);
11427 
11428 	return (0);
11429 }
11430 
11431 static int
upgrade_version(zpool_handle_t * zhp,uint64_t version)11432 upgrade_version(zpool_handle_t *zhp, uint64_t version)
11433 {
11434 	int ret;
11435 	nvlist_t *config;
11436 	uint64_t oldversion;
11437 	int unsupp_fs = 0;
11438 
11439 	config = zpool_get_config(zhp, NULL);
11440 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11441 	    &oldversion) == 0);
11442 
11443 	char compat[ZFS_MAXPROPLEN];
11444 	if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11445 	    ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11446 		compat[0] = '\0';
11447 
11448 	assert(SPA_VERSION_IS_SUPPORTED(oldversion));
11449 	assert(oldversion < version);
11450 
11451 	ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
11452 	if (ret != 0)
11453 		return (ret);
11454 
11455 	if (unsupp_fs) {
11456 		(void) fprintf(stderr, gettext("Upgrade not performed due "
11457 		    "to %d unsupported filesystems (max v%d).\n"),
11458 		    unsupp_fs, (int)ZPL_VERSION);
11459 		return (1);
11460 	}
11461 
11462 	if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
11463 		(void) fprintf(stderr, gettext("Upgrade not performed because "
11464 		    "'compatibility' property set to '"
11465 		    ZPOOL_COMPAT_LEGACY "'.\n"));
11466 		return (1);
11467 	}
11468 
11469 	ret = zpool_upgrade(zhp, version);
11470 	if (ret != 0)
11471 		return (ret);
11472 
11473 	if (version >= SPA_VERSION_FEATURES) {
11474 		(void) printf(gettext("Successfully upgraded "
11475 		    "'%s' from version %llu to feature flags.\n"),
11476 		    zpool_get_name(zhp), (u_longlong_t)oldversion);
11477 	} else {
11478 		(void) printf(gettext("Successfully upgraded "
11479 		    "'%s' from version %llu to version %llu.\n"),
11480 		    zpool_get_name(zhp), (u_longlong_t)oldversion,
11481 		    (u_longlong_t)version);
11482 	}
11483 
11484 	return (0);
11485 }
11486 
11487 static int
upgrade_enable_all(zpool_handle_t * zhp,int * countp)11488 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
11489 {
11490 	int i, ret, count;
11491 	boolean_t firstff = B_TRUE;
11492 	nvlist_t *enabled = zpool_get_features(zhp);
11493 
11494 	char compat[ZFS_MAXPROPLEN];
11495 	if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11496 	    ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11497 		compat[0] = '\0';
11498 
11499 	boolean_t requested_features[SPA_FEATURES];
11500 	if (zpool_do_load_compat(compat, requested_features) !=
11501 	    ZPOOL_COMPATIBILITY_OK)
11502 		return (-1);
11503 
11504 	count = 0;
11505 	for (i = 0; i < SPA_FEATURES; i++) {
11506 		const char *fname = spa_feature_table[i].fi_uname;
11507 		const char *fguid = spa_feature_table[i].fi_guid;
11508 
11509 		if (!spa_feature_table[i].fi_zfs_mod_supported ||
11510 		    (spa_feature_table[i].fi_flags & ZFEATURE_FLAG_NO_UPGRADE))
11511 			continue;
11512 
11513 		if (!nvlist_exists(enabled, fguid) && requested_features[i]) {
11514 			char *propname;
11515 			verify(-1 != asprintf(&propname, "feature@%s", fname));
11516 			ret = zpool_set_prop(zhp, propname,
11517 			    ZFS_FEATURE_ENABLED);
11518 			if (ret != 0) {
11519 				free(propname);
11520 				return (ret);
11521 			}
11522 			count++;
11523 
11524 			if (firstff) {
11525 				(void) printf(gettext("Enabled the "
11526 				    "following features on '%s':\n"),
11527 				    zpool_get_name(zhp));
11528 				firstff = B_FALSE;
11529 			}
11530 			(void) printf(gettext("  %s\n"), fname);
11531 			free(propname);
11532 		}
11533 	}
11534 
11535 	if (countp != NULL)
11536 		*countp = count;
11537 	return (0);
11538 }
11539 
11540 static int
upgrade_cb(zpool_handle_t * zhp,void * arg)11541 upgrade_cb(zpool_handle_t *zhp, void *arg)
11542 {
11543 	upgrade_cbdata_t *cbp = arg;
11544 	nvlist_t *config;
11545 	uint64_t version;
11546 	boolean_t modified_pool = B_FALSE;
11547 	int ret;
11548 
11549 	config = zpool_get_config(zhp, NULL);
11550 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11551 	    &version) == 0);
11552 
11553 	assert(SPA_VERSION_IS_SUPPORTED(version));
11554 
11555 	if (version < cbp->cb_version) {
11556 		cbp->cb_first = B_FALSE;
11557 		ret = upgrade_version(zhp, cbp->cb_version);
11558 		if (ret != 0)
11559 			return (ret);
11560 		modified_pool = B_TRUE;
11561 
11562 		/*
11563 		 * If they did "zpool upgrade -a", then we could
11564 		 * be doing ioctls to different pools.  We need
11565 		 * to log this history once to each pool, and bypass
11566 		 * the normal history logging that happens in main().
11567 		 */
11568 		(void) zpool_log_history(g_zfs, history_str);
11569 		log_history = B_FALSE;
11570 	}
11571 
11572 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
11573 		int count;
11574 		ret = upgrade_enable_all(zhp, &count);
11575 		if (ret != 0)
11576 			return (ret);
11577 
11578 		if (count > 0) {
11579 			cbp->cb_first = B_FALSE;
11580 			modified_pool = B_TRUE;
11581 		}
11582 	}
11583 
11584 	if (modified_pool) {
11585 		(void) printf("\n");
11586 		(void) after_zpool_upgrade(zhp);
11587 	}
11588 
11589 	return (0);
11590 }
11591 
11592 static int
upgrade_list_older_cb(zpool_handle_t * zhp,void * arg)11593 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
11594 {
11595 	upgrade_cbdata_t *cbp = arg;
11596 	nvlist_t *config;
11597 	uint64_t version;
11598 
11599 	config = zpool_get_config(zhp, NULL);
11600 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11601 	    &version) == 0);
11602 
11603 	assert(SPA_VERSION_IS_SUPPORTED(version));
11604 
11605 	if (version < SPA_VERSION_FEATURES) {
11606 		if (cbp->cb_first) {
11607 			(void) printf(gettext("The following pools are "
11608 			    "formatted with legacy version numbers and can\n"
11609 			    "be upgraded to use feature flags.  After "
11610 			    "being upgraded, these pools\nwill no "
11611 			    "longer be accessible by software that does not "
11612 			    "support feature\nflags.\n\n"
11613 			    "Note that setting a pool's 'compatibility' "
11614 			    "feature to '" ZPOOL_COMPAT_LEGACY "' will\n"
11615 			    "inhibit upgrades.\n\n"));
11616 			(void) printf(gettext("VER  POOL\n"));
11617 			(void) printf(gettext("---  ------------\n"));
11618 			cbp->cb_first = B_FALSE;
11619 		}
11620 
11621 		(void) printf("%2llu   %s\n", (u_longlong_t)version,
11622 		    zpool_get_name(zhp));
11623 	}
11624 
11625 	return (0);
11626 }
11627 
11628 static int
upgrade_list_disabled_cb(zpool_handle_t * zhp,void * arg)11629 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
11630 {
11631 	upgrade_cbdata_t *cbp = arg;
11632 	nvlist_t *config;
11633 	uint64_t version;
11634 
11635 	config = zpool_get_config(zhp, NULL);
11636 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11637 	    &version) == 0);
11638 
11639 	if (version >= SPA_VERSION_FEATURES) {
11640 		int i;
11641 		boolean_t poolfirst = B_TRUE;
11642 		nvlist_t *enabled = zpool_get_features(zhp);
11643 
11644 		for (i = 0; i < SPA_FEATURES; i++) {
11645 			const char *fguid = spa_feature_table[i].fi_guid;
11646 			const char *fname = spa_feature_table[i].fi_uname;
11647 
11648 			if (!spa_feature_table[i].fi_zfs_mod_supported)
11649 				continue;
11650 
11651 			if (!nvlist_exists(enabled, fguid)) {
11652 				if (cbp->cb_first) {
11653 					(void) printf(gettext("\nSome "
11654 					    "supported features are not "
11655 					    "enabled on the following pools. "
11656 					    "Once a\nfeature is enabled the "
11657 					    "pool may become incompatible with "
11658 					    "software\nthat does not support "
11659 					    "the feature. See "
11660 					    "zpool-features(7) for "
11661 					    "details.\n\n"
11662 					    "Note that the pool "
11663 					    "'compatibility' feature can be "
11664 					    "used to inhibit\nfeature "
11665 					    "upgrades.\n\n"
11666 					    "Features marked with (*) are not "
11667 					    "applied automatically on upgrade, "
11668 					    "and\nmust be applied explicitly "
11669 					    "with zpool-set(7).\n\n"));
11670 					(void) printf(gettext("POOL  "
11671 					    "FEATURE\n"));
11672 					(void) printf(gettext("------"
11673 					    "---------\n"));
11674 					cbp->cb_first = B_FALSE;
11675 				}
11676 
11677 				if (poolfirst) {
11678 					(void) printf(gettext("%s\n"),
11679 					    zpool_get_name(zhp));
11680 					poolfirst = B_FALSE;
11681 				}
11682 
11683 				(void) printf(gettext("      %s%s\n"), fname,
11684 				    spa_feature_table[i].fi_flags &
11685 				    ZFEATURE_FLAG_NO_UPGRADE ? "(*)" : "");
11686 			}
11687 			/*
11688 			 * If they did "zpool upgrade -a", then we could
11689 			 * be doing ioctls to different pools.  We need
11690 			 * to log this history once to each pool, and bypass
11691 			 * the normal history logging that happens in main().
11692 			 */
11693 			(void) zpool_log_history(g_zfs, history_str);
11694 			log_history = B_FALSE;
11695 		}
11696 	}
11697 
11698 	return (0);
11699 }
11700 
11701 static int
upgrade_one(zpool_handle_t * zhp,void * data)11702 upgrade_one(zpool_handle_t *zhp, void *data)
11703 {
11704 	boolean_t modified_pool = B_FALSE;
11705 	upgrade_cbdata_t *cbp = data;
11706 	uint64_t cur_version;
11707 	int ret;
11708 
11709 	if (strcmp("log", zpool_get_name(zhp)) == 0) {
11710 		(void) fprintf(stderr, gettext("'log' is now a reserved word\n"
11711 		    "Pool 'log' must be renamed using export and import"
11712 		    " to upgrade.\n"));
11713 		return (1);
11714 	}
11715 
11716 	cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
11717 	if (cur_version > cbp->cb_version) {
11718 		(void) printf(gettext("Pool '%s' is already formatted "
11719 		    "using more current version '%llu'.\n\n"),
11720 		    zpool_get_name(zhp), (u_longlong_t)cur_version);
11721 		return (0);
11722 	}
11723 
11724 	if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
11725 		(void) printf(gettext("Pool '%s' is already formatted "
11726 		    "using version %llu.\n\n"), zpool_get_name(zhp),
11727 		    (u_longlong_t)cbp->cb_version);
11728 		return (0);
11729 	}
11730 
11731 	if (cur_version != cbp->cb_version) {
11732 		modified_pool = B_TRUE;
11733 		ret = upgrade_version(zhp, cbp->cb_version);
11734 		if (ret != 0)
11735 			return (ret);
11736 	}
11737 
11738 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
11739 		int count = 0;
11740 		ret = upgrade_enable_all(zhp, &count);
11741 		if (ret != 0)
11742 			return (ret);
11743 
11744 		if (count != 0) {
11745 			modified_pool = B_TRUE;
11746 		} else if (cur_version == SPA_VERSION) {
11747 			(void) printf(gettext("Pool '%s' already has all "
11748 			    "supported and requested features enabled.\n"),
11749 			    zpool_get_name(zhp));
11750 		}
11751 	}
11752 
11753 	if (modified_pool) {
11754 		(void) printf("\n");
11755 		(void) after_zpool_upgrade(zhp);
11756 	}
11757 
11758 	return (0);
11759 }
11760 
11761 /*
11762  * zpool upgrade
11763  * zpool upgrade -v
11764  * zpool upgrade [-V version] <-a | pool ...>
11765  *
11766  * With no arguments, display downrev'd ZFS pool available for upgrade.
11767  * Individual pools can be upgraded by specifying the pool, and '-a' will
11768  * upgrade all pools.
11769  */
11770 int
zpool_do_upgrade(int argc,char ** argv)11771 zpool_do_upgrade(int argc, char **argv)
11772 {
11773 	int c;
11774 	upgrade_cbdata_t cb = { 0 };
11775 	int ret = 0;
11776 	boolean_t showversions = B_FALSE;
11777 	boolean_t upgradeall = B_FALSE;
11778 	char *end;
11779 
11780 
11781 	/* check options */
11782 	while ((c = getopt(argc, argv, ":avV:")) != -1) {
11783 		switch (c) {
11784 		case 'a':
11785 			upgradeall = B_TRUE;
11786 			break;
11787 		case 'v':
11788 			showversions = B_TRUE;
11789 			break;
11790 		case 'V':
11791 			cb.cb_version = strtoll(optarg, &end, 10);
11792 			if (*end != '\0' ||
11793 			    !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
11794 				(void) fprintf(stderr,
11795 				    gettext("invalid version '%s'\n"), optarg);
11796 				usage(B_FALSE);
11797 			}
11798 			break;
11799 		case ':':
11800 			(void) fprintf(stderr, gettext("missing argument for "
11801 			    "'%c' option\n"), optopt);
11802 			usage(B_FALSE);
11803 			break;
11804 		case '?':
11805 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
11806 			    optopt);
11807 			usage(B_FALSE);
11808 		}
11809 	}
11810 
11811 	cb.cb_argc = argc;
11812 	cb.cb_argv = argv;
11813 	argc -= optind;
11814 	argv += optind;
11815 
11816 	if (cb.cb_version == 0) {
11817 		cb.cb_version = SPA_VERSION;
11818 	} else if (!upgradeall && argc == 0) {
11819 		(void) fprintf(stderr, gettext("-V option is "
11820 		    "incompatible with other arguments\n"));
11821 		usage(B_FALSE);
11822 	}
11823 
11824 	if (showversions) {
11825 		if (upgradeall || argc != 0) {
11826 			(void) fprintf(stderr, gettext("-v option is "
11827 			    "incompatible with other arguments\n"));
11828 			usage(B_FALSE);
11829 		}
11830 	} else if (upgradeall) {
11831 		if (argc != 0) {
11832 			(void) fprintf(stderr, gettext("-a option should not "
11833 			    "be used along with a pool name\n"));
11834 			usage(B_FALSE);
11835 		}
11836 	}
11837 
11838 	(void) printf("%s", gettext("This system supports ZFS pool feature "
11839 	    "flags.\n\n"));
11840 	if (showversions) {
11841 		int i;
11842 
11843 		(void) printf(gettext("The following features are "
11844 		    "supported:\n\n"));
11845 		(void) printf(gettext("FEAT DESCRIPTION\n"));
11846 		(void) printf("----------------------------------------------"
11847 		    "---------------\n");
11848 		for (i = 0; i < SPA_FEATURES; i++) {
11849 			zfeature_info_t *fi = &spa_feature_table[i];
11850 			if (!fi->fi_zfs_mod_supported)
11851 				continue;
11852 			const char *ro =
11853 			    (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
11854 			    " (read-only compatible)" : "";
11855 
11856 			(void) printf("%-37s%s\n", fi->fi_uname, ro);
11857 			(void) printf("     %s\n", fi->fi_desc);
11858 		}
11859 		(void) printf("\n");
11860 
11861 		(void) printf(gettext("The following legacy versions are also "
11862 		    "supported:\n\n"));
11863 		(void) printf(gettext("VER  DESCRIPTION\n"));
11864 		(void) printf("---  -----------------------------------------"
11865 		    "---------------\n");
11866 		(void) printf(gettext(" 1   Initial ZFS version\n"));
11867 		(void) printf(gettext(" 2   Ditto blocks "
11868 		    "(replicated metadata)\n"));
11869 		(void) printf(gettext(" 3   Hot spares and double parity "
11870 		    "RAID-Z\n"));
11871 		(void) printf(gettext(" 4   zpool history\n"));
11872 		(void) printf(gettext(" 5   Compression using the gzip "
11873 		    "algorithm\n"));
11874 		(void) printf(gettext(" 6   bootfs pool property\n"));
11875 		(void) printf(gettext(" 7   Separate intent log devices\n"));
11876 		(void) printf(gettext(" 8   Delegated administration\n"));
11877 		(void) printf(gettext(" 9   refquota and refreservation "
11878 		    "properties\n"));
11879 		(void) printf(gettext(" 10  Cache devices\n"));
11880 		(void) printf(gettext(" 11  Improved scrub performance\n"));
11881 		(void) printf(gettext(" 12  Snapshot properties\n"));
11882 		(void) printf(gettext(" 13  snapused property\n"));
11883 		(void) printf(gettext(" 14  passthrough-x aclinherit\n"));
11884 		(void) printf(gettext(" 15  user/group space accounting\n"));
11885 		(void) printf(gettext(" 16  stmf property support\n"));
11886 		(void) printf(gettext(" 17  Triple-parity RAID-Z\n"));
11887 		(void) printf(gettext(" 18  Snapshot user holds\n"));
11888 		(void) printf(gettext(" 19  Log device removal\n"));
11889 		(void) printf(gettext(" 20  Compression using zle "
11890 		    "(zero-length encoding)\n"));
11891 		(void) printf(gettext(" 21  Deduplication\n"));
11892 		(void) printf(gettext(" 22  Received properties\n"));
11893 		(void) printf(gettext(" 23  Slim ZIL\n"));
11894 		(void) printf(gettext(" 24  System attributes\n"));
11895 		(void) printf(gettext(" 25  Improved scrub stats\n"));
11896 		(void) printf(gettext(" 26  Improved snapshot deletion "
11897 		    "performance\n"));
11898 		(void) printf(gettext(" 27  Improved snapshot creation "
11899 		    "performance\n"));
11900 		(void) printf(gettext(" 28  Multiple vdev replacements\n"));
11901 		(void) printf(gettext("\nFor more information on a particular "
11902 		    "version, including supported releases,\n"));
11903 		(void) printf(gettext("see the ZFS Administration Guide.\n\n"));
11904 	} else if (argc == 0 && upgradeall) {
11905 		cb.cb_first = B_TRUE;
11906 		ret = zpool_iter(g_zfs, upgrade_cb, &cb);
11907 		if (ret == 0 && cb.cb_first) {
11908 			if (cb.cb_version == SPA_VERSION) {
11909 				(void) printf(gettext("All pools are already "
11910 				    "formatted using feature flags.\n\n"));
11911 				(void) printf(gettext("Every feature flags "
11912 				    "pool already has all supported and "
11913 				    "requested features enabled.\n"));
11914 			} else {
11915 				(void) printf(gettext("All pools are already "
11916 				    "formatted with version %llu or higher.\n"),
11917 				    (u_longlong_t)cb.cb_version);
11918 			}
11919 		}
11920 	} else if (argc == 0) {
11921 		cb.cb_first = B_TRUE;
11922 		ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
11923 		assert(ret == 0);
11924 
11925 		if (cb.cb_first) {
11926 			(void) printf(gettext("All pools are formatted "
11927 			    "using feature flags.\n\n"));
11928 		} else {
11929 			(void) printf(gettext("\nUse 'zpool upgrade -v' "
11930 			    "for a list of available legacy versions.\n"));
11931 		}
11932 
11933 		cb.cb_first = B_TRUE;
11934 		ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
11935 		assert(ret == 0);
11936 
11937 		if (cb.cb_first) {
11938 			(void) printf(gettext("Every feature flags pool has "
11939 			    "all supported and requested features enabled.\n"));
11940 		} else {
11941 			(void) printf(gettext("\n"));
11942 		}
11943 	} else {
11944 		ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
11945 		    B_FALSE, upgrade_one, &cb);
11946 	}
11947 
11948 	return (ret);
11949 }
11950 
11951 typedef struct hist_cbdata {
11952 	boolean_t first;
11953 	boolean_t longfmt;
11954 	boolean_t internal;
11955 } hist_cbdata_t;
11956 
11957 static void
print_history_records(nvlist_t * nvhis,hist_cbdata_t * cb)11958 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
11959 {
11960 	nvlist_t **records;
11961 	uint_t numrecords;
11962 	int i;
11963 
11964 	verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
11965 	    &records, &numrecords) == 0);
11966 	for (i = 0; i < numrecords; i++) {
11967 		nvlist_t *rec = records[i];
11968 		char tbuf[64] = "";
11969 
11970 		if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
11971 			time_t tsec;
11972 			struct tm t;
11973 
11974 			tsec = fnvlist_lookup_uint64(records[i],
11975 			    ZPOOL_HIST_TIME);
11976 			(void) localtime_r(&tsec, &t);
11977 			(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
11978 		}
11979 
11980 		if (nvlist_exists(rec, ZPOOL_HIST_ELAPSED_NS)) {
11981 			uint64_t elapsed_ns = fnvlist_lookup_int64(records[i],
11982 			    ZPOOL_HIST_ELAPSED_NS);
11983 			(void) snprintf(tbuf + strlen(tbuf),
11984 			    sizeof (tbuf) - strlen(tbuf),
11985 			    " (%lldms)", (long long)elapsed_ns / 1000 / 1000);
11986 		}
11987 
11988 		if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
11989 			(void) printf("%s %s", tbuf,
11990 			    fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
11991 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
11992 			int ievent =
11993 			    fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
11994 			if (!cb->internal)
11995 				continue;
11996 			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
11997 				(void) printf("%s unrecognized record:\n",
11998 				    tbuf);
11999 				dump_nvlist(rec, 4);
12000 				continue;
12001 			}
12002 			(void) printf("%s [internal %s txg:%lld] %s", tbuf,
12003 			    zfs_history_event_names[ievent],
12004 			    (longlong_t)fnvlist_lookup_uint64(
12005 			    rec, ZPOOL_HIST_TXG),
12006 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
12007 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
12008 			if (!cb->internal)
12009 				continue;
12010 			(void) printf("%s [txg:%lld] %s", tbuf,
12011 			    (longlong_t)fnvlist_lookup_uint64(
12012 			    rec, ZPOOL_HIST_TXG),
12013 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
12014 			if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
12015 				(void) printf(" %s (%llu)",
12016 				    fnvlist_lookup_string(rec,
12017 				    ZPOOL_HIST_DSNAME),
12018 				    (u_longlong_t)fnvlist_lookup_uint64(rec,
12019 				    ZPOOL_HIST_DSID));
12020 			}
12021 			(void) printf(" %s", fnvlist_lookup_string(rec,
12022 			    ZPOOL_HIST_INT_STR));
12023 		} else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
12024 			if (!cb->internal)
12025 				continue;
12026 			(void) printf("%s ioctl %s\n", tbuf,
12027 			    fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
12028 			if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
12029 				(void) printf("    input:\n");
12030 				dump_nvlist(fnvlist_lookup_nvlist(rec,
12031 				    ZPOOL_HIST_INPUT_NVL), 8);
12032 			}
12033 			if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
12034 				(void) printf("    output:\n");
12035 				dump_nvlist(fnvlist_lookup_nvlist(rec,
12036 				    ZPOOL_HIST_OUTPUT_NVL), 8);
12037 			}
12038 			if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_SIZE)) {
12039 				(void) printf("    output nvlist omitted; "
12040 				    "original size: %lldKB\n",
12041 				    (longlong_t)fnvlist_lookup_int64(rec,
12042 				    ZPOOL_HIST_OUTPUT_SIZE) / 1024);
12043 			}
12044 			if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
12045 				(void) printf("    errno: %lld\n",
12046 				    (longlong_t)fnvlist_lookup_int64(rec,
12047 				    ZPOOL_HIST_ERRNO));
12048 			}
12049 		} else {
12050 			if (!cb->internal)
12051 				continue;
12052 			(void) printf("%s unrecognized record:\n", tbuf);
12053 			dump_nvlist(rec, 4);
12054 		}
12055 
12056 		if (!cb->longfmt) {
12057 			(void) printf("\n");
12058 			continue;
12059 		}
12060 		(void) printf(" [");
12061 		if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
12062 			uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
12063 			struct passwd *pwd = getpwuid(who);
12064 			(void) printf("user %d ", (int)who);
12065 			if (pwd != NULL)
12066 				(void) printf("(%s) ", pwd->pw_name);
12067 		}
12068 		if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
12069 			(void) printf("on %s",
12070 			    fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
12071 		}
12072 		if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
12073 			(void) printf(":%s",
12074 			    fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
12075 		}
12076 
12077 		(void) printf("]");
12078 		(void) printf("\n");
12079 	}
12080 }
12081 
12082 /*
12083  * Print out the command history for a specific pool.
12084  */
12085 static int
get_history_one(zpool_handle_t * zhp,void * data)12086 get_history_one(zpool_handle_t *zhp, void *data)
12087 {
12088 	nvlist_t *nvhis;
12089 	int ret;
12090 	hist_cbdata_t *cb = (hist_cbdata_t *)data;
12091 	uint64_t off = 0;
12092 	boolean_t eof = B_FALSE;
12093 
12094 	cb->first = B_FALSE;
12095 
12096 	(void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
12097 
12098 	while (!eof) {
12099 		if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
12100 			return (ret);
12101 
12102 		print_history_records(nvhis, cb);
12103 		nvlist_free(nvhis);
12104 	}
12105 	(void) printf("\n");
12106 
12107 	return (ret);
12108 }
12109 
12110 /*
12111  * zpool history <pool>
12112  *
12113  * Displays the history of commands that modified pools.
12114  */
12115 int
zpool_do_history(int argc,char ** argv)12116 zpool_do_history(int argc, char **argv)
12117 {
12118 	hist_cbdata_t cbdata = { 0 };
12119 	int ret;
12120 	int c;
12121 
12122 	cbdata.first = B_TRUE;
12123 	/* check options */
12124 	while ((c = getopt(argc, argv, "li")) != -1) {
12125 		switch (c) {
12126 		case 'l':
12127 			cbdata.longfmt = B_TRUE;
12128 			break;
12129 		case 'i':
12130 			cbdata.internal = B_TRUE;
12131 			break;
12132 		case '?':
12133 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
12134 			    optopt);
12135 			usage(B_FALSE);
12136 		}
12137 	}
12138 	argc -= optind;
12139 	argv += optind;
12140 
12141 	ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
12142 	    B_FALSE, get_history_one, &cbdata);
12143 
12144 	if (argc == 0 && cbdata.first == B_TRUE) {
12145 		(void) fprintf(stderr, gettext("no pools available\n"));
12146 		return (0);
12147 	}
12148 
12149 	return (ret);
12150 }
12151 
12152 typedef struct ev_opts {
12153 	int verbose;
12154 	int scripted;
12155 	int follow;
12156 	int clear;
12157 	char poolname[ZFS_MAX_DATASET_NAME_LEN];
12158 } ev_opts_t;
12159 
12160 static void
zpool_do_events_short(nvlist_t * nvl,ev_opts_t * opts)12161 zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
12162 {
12163 	char ctime_str[26], str[32];
12164 	const char *ptr;
12165 	int64_t *tv;
12166 	uint_t n;
12167 
12168 	verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
12169 	memset(str, ' ', 32);
12170 	(void) ctime_r((const time_t *)&tv[0], ctime_str);
12171 	(void) memcpy(str, ctime_str+4,  6);		/* 'Jun 30' */
12172 	(void) memcpy(str+7, ctime_str+20, 4);		/* '1993' */
12173 	(void) memcpy(str+12, ctime_str+11, 8);		/* '21:49:08' */
12174 	(void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
12175 	if (opts->scripted)
12176 		(void) printf(gettext("%s\t"), str);
12177 	else
12178 		(void) printf(gettext("%s "), str);
12179 
12180 	verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
12181 	(void) printf(gettext("%s\n"), ptr);
12182 }
12183 
12184 static void
zpool_do_events_nvprint(nvlist_t * nvl,int depth)12185 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
12186 {
12187 	nvpair_t *nvp;
12188 	static char flagstr[256];
12189 
12190 	for (nvp = nvlist_next_nvpair(nvl, NULL);
12191 	    nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
12192 
12193 		data_type_t type = nvpair_type(nvp);
12194 		const char *name = nvpair_name(nvp);
12195 
12196 		boolean_t b;
12197 		uint8_t i8;
12198 		uint16_t i16;
12199 		uint32_t i32;
12200 		uint64_t i64;
12201 		const char *str;
12202 		nvlist_t *cnv;
12203 
12204 		printf(gettext("%*s%s = "), depth, "", name);
12205 
12206 		switch (type) {
12207 		case DATA_TYPE_BOOLEAN:
12208 			printf(gettext("%s"), "1");
12209 			break;
12210 
12211 		case DATA_TYPE_BOOLEAN_VALUE:
12212 			(void) nvpair_value_boolean_value(nvp, &b);
12213 			printf(gettext("%s"), b ? "1" : "0");
12214 			break;
12215 
12216 		case DATA_TYPE_BYTE:
12217 			(void) nvpair_value_byte(nvp, &i8);
12218 			printf(gettext("0x%x"), i8);
12219 			break;
12220 
12221 		case DATA_TYPE_INT8:
12222 			(void) nvpair_value_int8(nvp, (void *)&i8);
12223 			printf(gettext("0x%x"), i8);
12224 			break;
12225 
12226 		case DATA_TYPE_UINT8:
12227 			(void) nvpair_value_uint8(nvp, &i8);
12228 			printf(gettext("0x%x"), i8);
12229 			break;
12230 
12231 		case DATA_TYPE_INT16:
12232 			(void) nvpair_value_int16(nvp, (void *)&i16);
12233 			printf(gettext("0x%x"), i16);
12234 			break;
12235 
12236 		case DATA_TYPE_UINT16:
12237 			(void) nvpair_value_uint16(nvp, &i16);
12238 			printf(gettext("0x%x"), i16);
12239 			break;
12240 
12241 		case DATA_TYPE_INT32:
12242 			(void) nvpair_value_int32(nvp, (void *)&i32);
12243 			printf(gettext("0x%x"), i32);
12244 			break;
12245 
12246 		case DATA_TYPE_UINT32:
12247 			(void) nvpair_value_uint32(nvp, &i32);
12248 			if (strcmp(name,
12249 			    FM_EREPORT_PAYLOAD_ZFS_ZIO_STAGE) == 0 ||
12250 			    strcmp(name,
12251 			    FM_EREPORT_PAYLOAD_ZFS_ZIO_PIPELINE) == 0) {
12252 				(void) zfs_valstr_zio_stage(i32, flagstr,
12253 				    sizeof (flagstr));
12254 				printf(gettext("0x%x [%s]"), i32, flagstr);
12255 			} else if (strcmp(name,
12256 			    FM_EREPORT_PAYLOAD_ZFS_ZIO_TYPE) == 0) {
12257 				(void) zfs_valstr_zio_type(i32, flagstr,
12258 				    sizeof (flagstr));
12259 				printf(gettext("0x%x [%s]"), i32, flagstr);
12260 			} else if (strcmp(name,
12261 			    FM_EREPORT_PAYLOAD_ZFS_ZIO_PRIORITY) == 0) {
12262 				(void) zfs_valstr_zio_priority(i32, flagstr,
12263 				    sizeof (flagstr));
12264 				printf(gettext("0x%x [%s]"), i32, flagstr);
12265 			} else {
12266 				printf(gettext("0x%x"), i32);
12267 			}
12268 			break;
12269 
12270 		case DATA_TYPE_INT64:
12271 			(void) nvpair_value_int64(nvp, (void *)&i64);
12272 			printf(gettext("0x%llx"), (u_longlong_t)i64);
12273 			break;
12274 
12275 		case DATA_TYPE_UINT64:
12276 			(void) nvpair_value_uint64(nvp, &i64);
12277 			/*
12278 			 * translate vdev state values to readable
12279 			 * strings to aide zpool events consumers
12280 			 */
12281 			if (strcmp(name,
12282 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
12283 			    strcmp(name,
12284 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
12285 				printf(gettext("\"%s\" (0x%llx)"),
12286 				    zpool_state_to_name(i64, VDEV_AUX_NONE),
12287 				    (u_longlong_t)i64);
12288 			} else if (strcmp(name,
12289 			    FM_EREPORT_PAYLOAD_ZFS_ZIO_FLAGS) == 0) {
12290 				(void) zfs_valstr_zio_flag(i64, flagstr,
12291 				    sizeof (flagstr));
12292 				printf(gettext("0x%llx [%s]"),
12293 				    (u_longlong_t)i64, flagstr);
12294 			} else {
12295 				printf(gettext("0x%llx"), (u_longlong_t)i64);
12296 			}
12297 			break;
12298 
12299 		case DATA_TYPE_HRTIME:
12300 			(void) nvpair_value_hrtime(nvp, (void *)&i64);
12301 			printf(gettext("0x%llx"), (u_longlong_t)i64);
12302 			break;
12303 
12304 		case DATA_TYPE_STRING:
12305 			(void) nvpair_value_string(nvp, &str);
12306 			printf(gettext("\"%s\""), str ? str : "<NULL>");
12307 			break;
12308 
12309 		case DATA_TYPE_NVLIST:
12310 			printf(gettext("(embedded nvlist)\n"));
12311 			(void) nvpair_value_nvlist(nvp, &cnv);
12312 			zpool_do_events_nvprint(cnv, depth + 8);
12313 			printf(gettext("%*s(end %s)"), depth, "", name);
12314 			break;
12315 
12316 		case DATA_TYPE_NVLIST_ARRAY: {
12317 			nvlist_t **val;
12318 			uint_t i, nelem;
12319 
12320 			(void) nvpair_value_nvlist_array(nvp, &val, &nelem);
12321 			printf(gettext("(%d embedded nvlists)\n"), nelem);
12322 			for (i = 0; i < nelem; i++) {
12323 				printf(gettext("%*s%s[%d] = %s\n"),
12324 				    depth, "", name, i, "(embedded nvlist)");
12325 				zpool_do_events_nvprint(val[i], depth + 8);
12326 				printf(gettext("%*s(end %s[%i])\n"),
12327 				    depth, "", name, i);
12328 			}
12329 			printf(gettext("%*s(end %s)\n"), depth, "", name);
12330 			}
12331 			break;
12332 
12333 		case DATA_TYPE_INT8_ARRAY: {
12334 			int8_t *val;
12335 			uint_t i, nelem;
12336 
12337 			(void) nvpair_value_int8_array(nvp, &val, &nelem);
12338 			for (i = 0; i < nelem; i++)
12339 				printf(gettext("0x%x "), val[i]);
12340 
12341 			break;
12342 			}
12343 
12344 		case DATA_TYPE_UINT8_ARRAY: {
12345 			uint8_t *val;
12346 			uint_t i, nelem;
12347 
12348 			(void) nvpair_value_uint8_array(nvp, &val, &nelem);
12349 			for (i = 0; i < nelem; i++)
12350 				printf(gettext("0x%x "), val[i]);
12351 
12352 			break;
12353 			}
12354 
12355 		case DATA_TYPE_INT16_ARRAY: {
12356 			int16_t *val;
12357 			uint_t i, nelem;
12358 
12359 			(void) nvpair_value_int16_array(nvp, &val, &nelem);
12360 			for (i = 0; i < nelem; i++)
12361 				printf(gettext("0x%x "), val[i]);
12362 
12363 			break;
12364 			}
12365 
12366 		case DATA_TYPE_UINT16_ARRAY: {
12367 			uint16_t *val;
12368 			uint_t i, nelem;
12369 
12370 			(void) nvpair_value_uint16_array(nvp, &val, &nelem);
12371 			for (i = 0; i < nelem; i++)
12372 				printf(gettext("0x%x "), val[i]);
12373 
12374 			break;
12375 			}
12376 
12377 		case DATA_TYPE_INT32_ARRAY: {
12378 			int32_t *val;
12379 			uint_t i, nelem;
12380 
12381 			(void) nvpair_value_int32_array(nvp, &val, &nelem);
12382 			for (i = 0; i < nelem; i++)
12383 				printf(gettext("0x%x "), val[i]);
12384 
12385 			break;
12386 			}
12387 
12388 		case DATA_TYPE_UINT32_ARRAY: {
12389 			uint32_t *val;
12390 			uint_t i, nelem;
12391 
12392 			(void) nvpair_value_uint32_array(nvp, &val, &nelem);
12393 			for (i = 0; i < nelem; i++)
12394 				printf(gettext("0x%x "), val[i]);
12395 
12396 			break;
12397 			}
12398 
12399 		case DATA_TYPE_INT64_ARRAY: {
12400 			int64_t *val;
12401 			uint_t i, nelem;
12402 
12403 			(void) nvpair_value_int64_array(nvp, &val, &nelem);
12404 			for (i = 0; i < nelem; i++)
12405 				printf(gettext("0x%llx "),
12406 				    (u_longlong_t)val[i]);
12407 
12408 			break;
12409 			}
12410 
12411 		case DATA_TYPE_UINT64_ARRAY: {
12412 			uint64_t *val;
12413 			uint_t i, nelem;
12414 
12415 			(void) nvpair_value_uint64_array(nvp, &val, &nelem);
12416 			for (i = 0; i < nelem; i++)
12417 				printf(gettext("0x%llx "),
12418 				    (u_longlong_t)val[i]);
12419 
12420 			break;
12421 			}
12422 
12423 		case DATA_TYPE_STRING_ARRAY: {
12424 			const char **str;
12425 			uint_t i, nelem;
12426 
12427 			(void) nvpair_value_string_array(nvp, &str, &nelem);
12428 			for (i = 0; i < nelem; i++)
12429 				printf(gettext("\"%s\" "),
12430 				    str[i] ? str[i] : "<NULL>");
12431 
12432 			break;
12433 			}
12434 
12435 		case DATA_TYPE_BOOLEAN_ARRAY:
12436 		case DATA_TYPE_BYTE_ARRAY:
12437 		case DATA_TYPE_DOUBLE:
12438 		case DATA_TYPE_DONTCARE:
12439 		case DATA_TYPE_UNKNOWN:
12440 			printf(gettext("<unknown>"));
12441 			break;
12442 		}
12443 
12444 		printf(gettext("\n"));
12445 	}
12446 }
12447 
12448 static int
zpool_do_events_next(ev_opts_t * opts)12449 zpool_do_events_next(ev_opts_t *opts)
12450 {
12451 	nvlist_t *nvl;
12452 	int zevent_fd, ret, dropped;
12453 	const char *pool;
12454 
12455 	zevent_fd = open(ZFS_DEV, O_RDWR);
12456 	VERIFY(zevent_fd >= 0);
12457 
12458 	if (!opts->scripted)
12459 		(void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
12460 
12461 	while (1) {
12462 		ret = zpool_events_next(g_zfs, &nvl, &dropped,
12463 		    (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
12464 		if (ret || nvl == NULL)
12465 			break;
12466 
12467 		if (dropped > 0)
12468 			(void) printf(gettext("dropped %d events\n"), dropped);
12469 
12470 		if (strlen(opts->poolname) > 0 &&
12471 		    nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
12472 		    strcmp(opts->poolname, pool) != 0)
12473 			continue;
12474 
12475 		zpool_do_events_short(nvl, opts);
12476 
12477 		if (opts->verbose) {
12478 			zpool_do_events_nvprint(nvl, 8);
12479 			printf(gettext("\n"));
12480 		}
12481 		(void) fflush(stdout);
12482 
12483 		nvlist_free(nvl);
12484 	}
12485 
12486 	VERIFY0(close(zevent_fd));
12487 
12488 	return (ret);
12489 }
12490 
12491 static int
zpool_do_events_clear(void)12492 zpool_do_events_clear(void)
12493 {
12494 	int count, ret;
12495 
12496 	ret = zpool_events_clear(g_zfs, &count);
12497 	if (!ret)
12498 		(void) printf(gettext("cleared %d events\n"), count);
12499 
12500 	return (ret);
12501 }
12502 
12503 /*
12504  * zpool events [-vHf [pool] | -c]
12505  *
12506  * Displays events logs by ZFS.
12507  */
12508 int
zpool_do_events(int argc,char ** argv)12509 zpool_do_events(int argc, char **argv)
12510 {
12511 	ev_opts_t opts = { 0 };
12512 	int ret;
12513 	int c;
12514 
12515 	/* check options */
12516 	while ((c = getopt(argc, argv, "vHfc")) != -1) {
12517 		switch (c) {
12518 		case 'v':
12519 			opts.verbose = 1;
12520 			break;
12521 		case 'H':
12522 			opts.scripted = 1;
12523 			break;
12524 		case 'f':
12525 			opts.follow = 1;
12526 			break;
12527 		case 'c':
12528 			opts.clear = 1;
12529 			break;
12530 		case '?':
12531 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
12532 			    optopt);
12533 			usage(B_FALSE);
12534 		}
12535 	}
12536 	argc -= optind;
12537 	argv += optind;
12538 
12539 	if (argc > 1) {
12540 		(void) fprintf(stderr, gettext("too many arguments\n"));
12541 		usage(B_FALSE);
12542 	} else if (argc == 1) {
12543 		(void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
12544 		if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
12545 			(void) fprintf(stderr,
12546 			    gettext("invalid pool name '%s'\n"), opts.poolname);
12547 			usage(B_FALSE);
12548 		}
12549 	}
12550 
12551 	if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
12552 	    opts.clear) {
12553 		(void) fprintf(stderr,
12554 		    gettext("invalid options combined with -c\n"));
12555 		usage(B_FALSE);
12556 	}
12557 
12558 	if (opts.clear)
12559 		ret = zpool_do_events_clear();
12560 	else
12561 		ret = zpool_do_events_next(&opts);
12562 
12563 	return (ret);
12564 }
12565 
12566 static int
get_callback_vdev(zpool_handle_t * zhp,char * vdevname,void * data)12567 get_callback_vdev(zpool_handle_t *zhp, char *vdevname, void *data)
12568 {
12569 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12570 	char value[ZFS_MAXPROPLEN];
12571 	zprop_source_t srctype;
12572 	nvlist_t *props, *item, *d;
12573 	props = item = d = NULL;
12574 
12575 	if (cbp->cb_json) {
12576 		d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "vdevs");
12577 		if (d == NULL) {
12578 			fprintf(stderr, "vdevs obj not found.\n");
12579 			exit(1);
12580 		}
12581 		props = fnvlist_alloc();
12582 	}
12583 
12584 	for (zprop_list_t *pl = cbp->cb_proplist; pl != NULL;
12585 	    pl = pl->pl_next) {
12586 		char *prop_name;
12587 		/*
12588 		 * If the first property is pool name, it is a special
12589 		 * placeholder that we can skip. This will also skip
12590 		 * over the name property when 'all' is specified.
12591 		 */
12592 		if (pl->pl_prop == ZPOOL_PROP_NAME &&
12593 		    pl == cbp->cb_proplist)
12594 			continue;
12595 
12596 		if (pl->pl_prop == ZPROP_INVAL) {
12597 			prop_name = pl->pl_user_prop;
12598 		} else {
12599 			prop_name = (char *)vdev_prop_to_name(pl->pl_prop);
12600 		}
12601 		if (zpool_get_vdev_prop(zhp, vdevname, pl->pl_prop,
12602 		    prop_name, value, sizeof (value), &srctype,
12603 		    cbp->cb_literal) == 0) {
12604 			(void) zprop_collect_property(vdevname, cbp, prop_name,
12605 			    value, srctype, NULL, NULL, props);
12606 		}
12607 	}
12608 
12609 	if (cbp->cb_json) {
12610 		if (!nvlist_empty(props)) {
12611 			item = fnvlist_alloc();
12612 			fill_vdev_info(item, zhp, vdevname, B_TRUE,
12613 			    cbp->cb_json_as_int);
12614 			fnvlist_add_nvlist(item, "properties", props);
12615 			fnvlist_add_nvlist(d, vdevname, item);
12616 			fnvlist_add_nvlist(cbp->cb_jsobj, "vdevs", d);
12617 			fnvlist_free(item);
12618 		}
12619 		fnvlist_free(props);
12620 	}
12621 
12622 	return (0);
12623 }
12624 
12625 static int
get_callback_vdev_cb(void * zhp_data,nvlist_t * nv,void * data)12626 get_callback_vdev_cb(void *zhp_data, nvlist_t *nv, void *data)
12627 {
12628 	zpool_handle_t *zhp = zhp_data;
12629 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12630 	char *vdevname;
12631 	const char *type;
12632 	int ret;
12633 
12634 	/*
12635 	 * zpool_vdev_name() transforms the root vdev name (i.e., root-0) to the
12636 	 * pool name for display purposes, which is not desired. Fallback to
12637 	 * zpool_vdev_name() when not dealing with the root vdev.
12638 	 */
12639 	type = fnvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE);
12640 	if (zhp != NULL && strcmp(type, "root") == 0)
12641 		vdevname = strdup("root-0");
12642 	else
12643 		vdevname = zpool_vdev_name(g_zfs, zhp, nv,
12644 		    cbp->cb_vdevs.cb_name_flags);
12645 
12646 	(void) vdev_expand_proplist(zhp, vdevname, &cbp->cb_proplist);
12647 
12648 	ret = get_callback_vdev(zhp, vdevname, data);
12649 
12650 	free(vdevname);
12651 
12652 	return (ret);
12653 }
12654 
12655 static int
get_callback(zpool_handle_t * zhp,void * data)12656 get_callback(zpool_handle_t *zhp, void *data)
12657 {
12658 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12659 	char value[ZFS_MAXPROPLEN];
12660 	zprop_source_t srctype;
12661 	zprop_list_t *pl;
12662 	int vid;
12663 	int err = 0;
12664 	nvlist_t *props, *item, *d;
12665 	props = item = d = NULL;
12666 
12667 	if (cbp->cb_type == ZFS_TYPE_VDEV) {
12668 		if (cbp->cb_json) {
12669 			nvlist_t *pool = fnvlist_alloc();
12670 			fill_pool_info(pool, zhp, B_FALSE, cbp->cb_json_as_int);
12671 			fnvlist_add_nvlist(cbp->cb_jsobj, "pool", pool);
12672 			fnvlist_free(pool);
12673 		}
12674 
12675 		if (strcmp(cbp->cb_vdevs.cb_names[0], "all-vdevs") == 0) {
12676 			(void) for_each_vdev(zhp, get_callback_vdev_cb, data);
12677 		} else {
12678 			/* Adjust column widths for vdev properties */
12679 			for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
12680 			    vid++) {
12681 				(void) vdev_expand_proplist(zhp,
12682 				    cbp->cb_vdevs.cb_names[vid],
12683 				    &cbp->cb_proplist);
12684 			}
12685 			/* Display the properties */
12686 			for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
12687 			    vid++) {
12688 				(void) get_callback_vdev(zhp,
12689 				    cbp->cb_vdevs.cb_names[vid], data);
12690 			}
12691 		}
12692 	} else {
12693 		assert(cbp->cb_type == ZFS_TYPE_POOL);
12694 		if (cbp->cb_json) {
12695 			d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
12696 			if (d == NULL) {
12697 				fprintf(stderr, "pools obj not found.\n");
12698 				exit(1);
12699 			}
12700 			props = fnvlist_alloc();
12701 		}
12702 		for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
12703 			/*
12704 			 * Skip the special fake placeholder. This will also
12705 			 * skip over the name property when 'all' is specified.
12706 			 */
12707 			if (pl->pl_prop == ZPOOL_PROP_NAME &&
12708 			    pl == cbp->cb_proplist)
12709 				continue;
12710 
12711 			if (pl->pl_prop == ZPROP_INVAL &&
12712 			    zfs_prop_user(pl->pl_user_prop)) {
12713 				srctype = ZPROP_SRC_LOCAL;
12714 
12715 				if (zpool_get_userprop(zhp, pl->pl_user_prop,
12716 				    value, sizeof (value), &srctype) != 0)
12717 					continue;
12718 
12719 				err = zprop_collect_property(
12720 				    zpool_get_name(zhp), cbp, pl->pl_user_prop,
12721 				    value, srctype, NULL, NULL, props);
12722 			} else if (pl->pl_prop == ZPROP_INVAL &&
12723 			    (zpool_prop_feature(pl->pl_user_prop) ||
12724 			    zpool_prop_unsupported(pl->pl_user_prop))) {
12725 				srctype = ZPROP_SRC_LOCAL;
12726 
12727 				if (zpool_prop_get_feature(zhp,
12728 				    pl->pl_user_prop, value,
12729 				    sizeof (value)) == 0) {
12730 					err = zprop_collect_property(
12731 					    zpool_get_name(zhp), cbp,
12732 					    pl->pl_user_prop, value, srctype,
12733 					    NULL, NULL, props);
12734 				}
12735 			} else {
12736 				if (zpool_get_prop(zhp, pl->pl_prop, value,
12737 				    sizeof (value), &srctype,
12738 				    cbp->cb_literal) != 0)
12739 					continue;
12740 
12741 				err = zprop_collect_property(
12742 				    zpool_get_name(zhp), cbp,
12743 				    zpool_prop_to_name(pl->pl_prop),
12744 				    value, srctype, NULL, NULL, props);
12745 			}
12746 			if (err != 0)
12747 				return (err);
12748 		}
12749 
12750 		if (cbp->cb_json) {
12751 			if (!nvlist_empty(props)) {
12752 				item = fnvlist_alloc();
12753 				fill_pool_info(item, zhp, B_TRUE,
12754 				    cbp->cb_json_as_int);
12755 				fnvlist_add_nvlist(item, "properties", props);
12756 				if (cbp->cb_json_pool_key_guid) {
12757 					char buf[256];
12758 					uint64_t guid = fnvlist_lookup_uint64(
12759 					    zpool_get_config(zhp, NULL),
12760 					    ZPOOL_CONFIG_POOL_GUID);
12761 					(void) snprintf(buf, 256, "%llu",
12762 					    (u_longlong_t)guid);
12763 					fnvlist_add_nvlist(d, buf, item);
12764 				} else {
12765 					const char *name = zpool_get_name(zhp);
12766 					fnvlist_add_nvlist(d, name, item);
12767 				}
12768 				fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
12769 				fnvlist_free(item);
12770 			}
12771 			fnvlist_free(props);
12772 		}
12773 	}
12774 
12775 	return (0);
12776 }
12777 
12778 /*
12779  * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
12780  *
12781  *	-H	Scripted mode.  Don't display headers, and separate properties
12782  *		by a single tab.
12783  *	-o	List of columns to display.  Defaults to
12784  *		"name,property,value,source".
12785  * 	-p	Display values in parsable (exact) format.
12786  * 	-j	Display output in JSON format.
12787  * 	--json-int	Display numbers as integers instead of strings.
12788  * 	--json-pool-key-guid	Set pool GUID as key for pool objects.
12789  *
12790  * Get properties of pools in the system. Output space statistics
12791  * for each one as well as other attributes.
12792  */
12793 int
zpool_do_get(int argc,char ** argv)12794 zpool_do_get(int argc, char **argv)
12795 {
12796 	zprop_get_cbdata_t cb = { 0 };
12797 	zprop_list_t fake_name = { 0 };
12798 	int ret;
12799 	int c, i;
12800 	char *propstr = NULL;
12801 	char *vdev = NULL;
12802 	nvlist_t *data = NULL;
12803 
12804 	cb.cb_first = B_TRUE;
12805 
12806 	/*
12807 	 * Set up default columns and sources.
12808 	 */
12809 	cb.cb_sources = ZPROP_SRC_ALL;
12810 	cb.cb_columns[0] = GET_COL_NAME;
12811 	cb.cb_columns[1] = GET_COL_PROPERTY;
12812 	cb.cb_columns[2] = GET_COL_VALUE;
12813 	cb.cb_columns[3] = GET_COL_SOURCE;
12814 	cb.cb_type = ZFS_TYPE_POOL;
12815 	cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
12816 	current_prop_type = cb.cb_type;
12817 
12818 	struct option long_options[] = {
12819 		{"json", no_argument, NULL, 'j'},
12820 		{"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
12821 		{"json-pool-key-guid", no_argument, NULL,
12822 		    ZPOOL_OPTION_POOL_KEY_GUID},
12823 		{0, 0, 0, 0}
12824 	};
12825 
12826 	/* check options */
12827 	while ((c = getopt_long(argc, argv, ":jHpo:", long_options,
12828 	    NULL)) != -1) {
12829 		switch (c) {
12830 		case 'p':
12831 			cb.cb_literal = B_TRUE;
12832 			break;
12833 		case 'H':
12834 			cb.cb_scripted = B_TRUE;
12835 			break;
12836 		case 'j':
12837 			cb.cb_json = B_TRUE;
12838 			cb.cb_jsobj = zpool_json_schema(0, 1);
12839 			data = fnvlist_alloc();
12840 			break;
12841 		case ZPOOL_OPTION_POOL_KEY_GUID:
12842 			cb.cb_json_pool_key_guid = B_TRUE;
12843 			break;
12844 		case ZPOOL_OPTION_JSON_NUMS_AS_INT:
12845 			cb.cb_json_as_int = B_TRUE;
12846 			cb.cb_literal = B_TRUE;
12847 			break;
12848 		case 'o':
12849 			memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
12850 			i = 0;
12851 
12852 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
12853 				static const char *const col_opts[] =
12854 				{ "name", "property", "value", "source",
12855 				    "all" };
12856 				static const zfs_get_column_t col_cols[] =
12857 				{ GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
12858 				    GET_COL_SOURCE };
12859 
12860 				if (i == ZFS_GET_NCOLS - 1) {
12861 					(void) fprintf(stderr, gettext("too "
12862 					"many fields given to -o "
12863 					"option\n"));
12864 					usage(B_FALSE);
12865 				}
12866 
12867 				for (c = 0; c < ARRAY_SIZE(col_opts); ++c)
12868 					if (strcmp(tok, col_opts[c]) == 0)
12869 						goto found;
12870 
12871 				(void) fprintf(stderr,
12872 				    gettext("invalid column name '%s'\n"), tok);
12873 				usage(B_FALSE);
12874 
12875 found:
12876 				if (c >= 4) {
12877 					if (i > 0) {
12878 						(void) fprintf(stderr,
12879 						    gettext("\"all\" conflicts "
12880 						    "with specific fields "
12881 						    "given to -o option\n"));
12882 						usage(B_FALSE);
12883 					}
12884 
12885 					memcpy(cb.cb_columns, col_cols,
12886 					    sizeof (col_cols));
12887 					i = ZFS_GET_NCOLS - 1;
12888 				} else
12889 					cb.cb_columns[i++] = col_cols[c];
12890 			}
12891 			break;
12892 		case '?':
12893 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
12894 			    optopt);
12895 			usage(B_FALSE);
12896 		}
12897 	}
12898 
12899 	argc -= optind;
12900 	argv += optind;
12901 
12902 	if (!cb.cb_json && cb.cb_json_as_int) {
12903 		(void) fprintf(stderr, gettext("'--json-int' only works with"
12904 		    " '-j' option\n"));
12905 		usage(B_FALSE);
12906 	}
12907 
12908 	if (!cb.cb_json && cb.cb_json_pool_key_guid) {
12909 		(void) fprintf(stderr, gettext("'json-pool-key-guid' only"
12910 		    " works with '-j' option\n"));
12911 		usage(B_FALSE);
12912 	}
12913 
12914 	if (argc < 1) {
12915 		(void) fprintf(stderr, gettext("missing property "
12916 		    "argument\n"));
12917 		usage(B_FALSE);
12918 	}
12919 
12920 	/* Properties list is needed later by zprop_get_list() */
12921 	propstr = argv[0];
12922 
12923 	argc--;
12924 	argv++;
12925 
12926 	if (argc == 0) {
12927 		/* No args, so just print the defaults. */
12928 	} else if (are_all_pools(argc, argv)) {
12929 		/* All the args are pool names */
12930 	} else if (are_all_pools(1, argv)) {
12931 		/* The first arg is a pool name */
12932 		if ((argc == 2 && strcmp(argv[1], "all-vdevs") == 0) ||
12933 		    (argc == 2 && strcmp(argv[1], "root") == 0) ||
12934 		    are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
12935 		    &cb.cb_vdevs)) {
12936 
12937 			if (strcmp(argv[1], "root") == 0)
12938 				vdev = strdup("root-0");
12939 
12940 			/* ... and the rest are vdev names */
12941 			if (vdev == NULL)
12942 				cb.cb_vdevs.cb_names = argv + 1;
12943 			else
12944 				cb.cb_vdevs.cb_names = &vdev;
12945 
12946 			cb.cb_vdevs.cb_names_count = argc - 1;
12947 			cb.cb_type = ZFS_TYPE_VDEV;
12948 			argc = 1; /* One pool to process */
12949 		} else {
12950 			if (cb.cb_json) {
12951 				nvlist_free(cb.cb_jsobj);
12952 				nvlist_free(data);
12953 			}
12954 			fprintf(stderr, gettext("Expected a list of vdevs in"
12955 			    " \"%s\", but got:\n"), argv[0]);
12956 			error_list_unresolved_vdevs(argc - 1, argv + 1,
12957 			    argv[0], &cb.cb_vdevs);
12958 			fprintf(stderr, "\n");
12959 			usage(B_FALSE);
12960 		}
12961 	} else {
12962 		if (cb.cb_json) {
12963 			nvlist_free(cb.cb_jsobj);
12964 			nvlist_free(data);
12965 		}
12966 		/*
12967 		 * The first arg isn't the name of a valid pool.
12968 		 */
12969 		fprintf(stderr, gettext("Cannot get properties of %s: "
12970 		    "no such pool available.\n"), argv[0]);
12971 		return (1);
12972 	}
12973 
12974 	if (zprop_get_list(g_zfs, propstr, &cb.cb_proplist,
12975 	    cb.cb_type) != 0) {
12976 		/* Use correct list of valid properties (pool or vdev) */
12977 		current_prop_type = cb.cb_type;
12978 		usage(B_FALSE);
12979 	}
12980 
12981 	if (cb.cb_proplist != NULL) {
12982 		fake_name.pl_prop = ZPOOL_PROP_NAME;
12983 		fake_name.pl_width = strlen(gettext("NAME"));
12984 		fake_name.pl_next = cb.cb_proplist;
12985 		cb.cb_proplist = &fake_name;
12986 	}
12987 
12988 	if (cb.cb_json) {
12989 		if (cb.cb_type == ZFS_TYPE_VDEV)
12990 			fnvlist_add_nvlist(cb.cb_jsobj, "vdevs", data);
12991 		else
12992 			fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
12993 		fnvlist_free(data);
12994 	}
12995 
12996 	ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist, cb.cb_type,
12997 	    cb.cb_literal, get_callback, &cb);
12998 
12999 	if (ret == 0 && cb.cb_json)
13000 		zcmd_print_json(cb.cb_jsobj);
13001 	else if (ret != 0 && cb.cb_json)
13002 		nvlist_free(cb.cb_jsobj);
13003 
13004 	if (cb.cb_proplist == &fake_name)
13005 		zprop_free_list(fake_name.pl_next);
13006 	else
13007 		zprop_free_list(cb.cb_proplist);
13008 
13009 	if (vdev != NULL)
13010 		free(vdev);
13011 
13012 	return (ret);
13013 }
13014 
13015 typedef struct set_cbdata {
13016 	char *cb_propname;
13017 	char *cb_value;
13018 	zfs_type_t cb_type;
13019 	vdev_cbdata_t cb_vdevs;
13020 	boolean_t cb_any_successful;
13021 } set_cbdata_t;
13022 
13023 static int
set_pool_callback(zpool_handle_t * zhp,set_cbdata_t * cb)13024 set_pool_callback(zpool_handle_t *zhp, set_cbdata_t *cb)
13025 {
13026 	int error;
13027 
13028 	/* Check if we have out-of-bounds features */
13029 	if (strcmp(cb->cb_propname, ZPOOL_CONFIG_COMPATIBILITY) == 0) {
13030 		boolean_t features[SPA_FEATURES];
13031 		if (zpool_do_load_compat(cb->cb_value, features) !=
13032 		    ZPOOL_COMPATIBILITY_OK)
13033 			return (-1);
13034 
13035 		nvlist_t *enabled = zpool_get_features(zhp);
13036 		spa_feature_t i;
13037 		for (i = 0; i < SPA_FEATURES; i++) {
13038 			const char *fguid = spa_feature_table[i].fi_guid;
13039 			if (nvlist_exists(enabled, fguid) && !features[i])
13040 				break;
13041 		}
13042 		if (i < SPA_FEATURES)
13043 			(void) fprintf(stderr, gettext("Warning: one or "
13044 			    "more features already enabled on pool '%s'\n"
13045 			    "are not present in this compatibility set.\n"),
13046 			    zpool_get_name(zhp));
13047 	}
13048 
13049 	/* if we're setting a feature, check it's in compatibility set */
13050 	if (zpool_prop_feature(cb->cb_propname) &&
13051 	    strcmp(cb->cb_value, ZFS_FEATURE_ENABLED) == 0) {
13052 		char *fname = strchr(cb->cb_propname, '@') + 1;
13053 		spa_feature_t f;
13054 
13055 		if (zfeature_lookup_name(fname, &f) == 0) {
13056 			char compat[ZFS_MAXPROPLEN];
13057 			if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY,
13058 			    compat, ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
13059 				compat[0] = '\0';
13060 
13061 			boolean_t features[SPA_FEATURES];
13062 			if (zpool_do_load_compat(compat, features) !=
13063 			    ZPOOL_COMPATIBILITY_OK) {
13064 				(void) fprintf(stderr, gettext("Error: "
13065 				    "cannot enable feature '%s' on pool '%s'\n"
13066 				    "because the pool's 'compatibility' "
13067 				    "property cannot be parsed.\n"),
13068 				    fname, zpool_get_name(zhp));
13069 				return (-1);
13070 			}
13071 
13072 			if (!features[f]) {
13073 				(void) fprintf(stderr, gettext("Error: "
13074 				    "cannot enable feature '%s' on pool '%s'\n"
13075 				    "as it is not specified in this pool's "
13076 				    "current compatibility set.\n"
13077 				    "Consider setting 'compatibility' to a "
13078 				    "less restrictive set, or to 'off'.\n"),
13079 				    fname, zpool_get_name(zhp));
13080 				return (-1);
13081 			}
13082 		}
13083 	}
13084 
13085 	error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
13086 
13087 	return (error);
13088 }
13089 
13090 static int
set_callback(zpool_handle_t * zhp,void * data)13091 set_callback(zpool_handle_t *zhp, void *data)
13092 {
13093 	int error;
13094 	set_cbdata_t *cb = (set_cbdata_t *)data;
13095 
13096 	if (cb->cb_type == ZFS_TYPE_VDEV) {
13097 		error = zpool_set_vdev_prop(zhp, *cb->cb_vdevs.cb_names,
13098 		    cb->cb_propname, cb->cb_value);
13099 	} else {
13100 		assert(cb->cb_type == ZFS_TYPE_POOL);
13101 		error = set_pool_callback(zhp, cb);
13102 	}
13103 
13104 	cb->cb_any_successful = !error;
13105 	return (error);
13106 }
13107 
13108 int
zpool_do_set(int argc,char ** argv)13109 zpool_do_set(int argc, char **argv)
13110 {
13111 	set_cbdata_t cb = { 0 };
13112 	int error;
13113 	char *vdev = NULL;
13114 
13115 	current_prop_type = ZFS_TYPE_POOL;
13116 	if (argc > 1 && argv[1][0] == '-') {
13117 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
13118 		    argv[1][1]);
13119 		usage(B_FALSE);
13120 	}
13121 
13122 	if (argc < 2) {
13123 		(void) fprintf(stderr, gettext("missing property=value "
13124 		    "argument\n"));
13125 		usage(B_FALSE);
13126 	}
13127 
13128 	if (argc < 3) {
13129 		(void) fprintf(stderr, gettext("missing pool name\n"));
13130 		usage(B_FALSE);
13131 	}
13132 
13133 	if (argc > 4) {
13134 		(void) fprintf(stderr, gettext("too many pool names\n"));
13135 		usage(B_FALSE);
13136 	}
13137 
13138 	cb.cb_propname = argv[1];
13139 	cb.cb_type = ZFS_TYPE_POOL;
13140 	cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
13141 	cb.cb_value = strchr(cb.cb_propname, '=');
13142 	if (cb.cb_value == NULL) {
13143 		(void) fprintf(stderr, gettext("missing value in "
13144 		    "property=value argument\n"));
13145 		usage(B_FALSE);
13146 	}
13147 
13148 	*(cb.cb_value) = '\0';
13149 	cb.cb_value++;
13150 	argc -= 2;
13151 	argv += 2;
13152 
13153 	/* argv[0] is pool name */
13154 	if (!is_pool(argv[0])) {
13155 		(void) fprintf(stderr,
13156 		    gettext("cannot open '%s': is not a pool\n"), argv[0]);
13157 		return (EINVAL);
13158 	}
13159 
13160 	/* argv[1], when supplied, is vdev name */
13161 	if (argc == 2) {
13162 
13163 		if (strcmp(argv[1], "root") == 0)
13164 			vdev = strdup("root-0");
13165 		else
13166 			vdev = strdup(argv[1]);
13167 
13168 		if (!are_vdevs_in_pool(1, &vdev, argv[0], &cb.cb_vdevs)) {
13169 			(void) fprintf(stderr, gettext(
13170 			    "cannot find '%s' in '%s': device not in pool\n"),
13171 			    vdev, argv[0]);
13172 			free(vdev);
13173 			return (EINVAL);
13174 		}
13175 		cb.cb_vdevs.cb_names = &vdev;
13176 		cb.cb_vdevs.cb_names_count = 1;
13177 		cb.cb_type = ZFS_TYPE_VDEV;
13178 	}
13179 
13180 	error = for_each_pool(1, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
13181 	    B_FALSE, set_callback, &cb);
13182 
13183 	if (vdev != NULL)
13184 		free(vdev);
13185 
13186 	return (error);
13187 }
13188 
13189 /* Add up the total number of bytes left to initialize/trim across all vdevs */
13190 static uint64_t
vdev_activity_remaining(nvlist_t * nv,zpool_wait_activity_t activity)13191 vdev_activity_remaining(nvlist_t *nv, zpool_wait_activity_t activity)
13192 {
13193 	uint64_t bytes_remaining;
13194 	nvlist_t **child;
13195 	uint_t c, children;
13196 	vdev_stat_t *vs;
13197 
13198 	assert(activity == ZPOOL_WAIT_INITIALIZE ||
13199 	    activity == ZPOOL_WAIT_TRIM);
13200 
13201 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
13202 	    (uint64_t **)&vs, &c) == 0);
13203 
13204 	if (activity == ZPOOL_WAIT_INITIALIZE &&
13205 	    vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE)
13206 		bytes_remaining = vs->vs_initialize_bytes_est -
13207 		    vs->vs_initialize_bytes_done;
13208 	else if (activity == ZPOOL_WAIT_TRIM &&
13209 	    vs->vs_trim_state == VDEV_TRIM_ACTIVE)
13210 		bytes_remaining = vs->vs_trim_bytes_est -
13211 		    vs->vs_trim_bytes_done;
13212 	else
13213 		bytes_remaining = 0;
13214 
13215 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13216 	    &child, &children) != 0)
13217 		children = 0;
13218 
13219 	for (c = 0; c < children; c++)
13220 		bytes_remaining += vdev_activity_remaining(child[c], activity);
13221 
13222 	return (bytes_remaining);
13223 }
13224 
13225 /* Add up the total number of bytes left to rebuild across top-level vdevs */
13226 static uint64_t
vdev_activity_top_remaining(nvlist_t * nv)13227 vdev_activity_top_remaining(nvlist_t *nv)
13228 {
13229 	uint64_t bytes_remaining = 0;
13230 	nvlist_t **child;
13231 	uint_t children;
13232 	int error;
13233 
13234 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13235 	    &child, &children) != 0)
13236 		children = 0;
13237 
13238 	for (uint_t c = 0; c < children; c++) {
13239 		vdev_rebuild_stat_t *vrs;
13240 		uint_t i;
13241 
13242 		error = nvlist_lookup_uint64_array(child[c],
13243 		    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i);
13244 		if (error == 0) {
13245 			if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
13246 				bytes_remaining += (vrs->vrs_bytes_est -
13247 				    vrs->vrs_bytes_rebuilt);
13248 			}
13249 		}
13250 	}
13251 
13252 	return (bytes_remaining);
13253 }
13254 
13255 /* Whether any vdevs are 'spare' or 'replacing' vdevs */
13256 static boolean_t
vdev_any_spare_replacing(nvlist_t * nv)13257 vdev_any_spare_replacing(nvlist_t *nv)
13258 {
13259 	nvlist_t **child;
13260 	uint_t c, children;
13261 	const char *vdev_type;
13262 
13263 	(void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &vdev_type);
13264 
13265 	if (strcmp(vdev_type, VDEV_TYPE_REPLACING) == 0 ||
13266 	    strcmp(vdev_type, VDEV_TYPE_SPARE) == 0 ||
13267 	    strcmp(vdev_type, VDEV_TYPE_DRAID_SPARE) == 0) {
13268 		return (B_TRUE);
13269 	}
13270 
13271 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13272 	    &child, &children) != 0)
13273 		children = 0;
13274 
13275 	for (c = 0; c < children; c++) {
13276 		if (vdev_any_spare_replacing(child[c]))
13277 			return (B_TRUE);
13278 	}
13279 
13280 	return (B_FALSE);
13281 }
13282 
13283 typedef struct wait_data {
13284 	char *wd_poolname;
13285 	boolean_t wd_scripted;
13286 	boolean_t wd_exact;
13287 	boolean_t wd_headers_once;
13288 	boolean_t wd_should_exit;
13289 	/* Which activities to wait for */
13290 	boolean_t wd_enabled[ZPOOL_WAIT_NUM_ACTIVITIES];
13291 	float wd_interval;
13292 	pthread_cond_t wd_cv;
13293 	pthread_mutex_t wd_mutex;
13294 } wait_data_t;
13295 
13296 /*
13297  * Print to stdout a single line, containing one column for each activity that
13298  * we are waiting for specifying how many bytes of work are left for that
13299  * activity.
13300  */
13301 static void
print_wait_status_row(wait_data_t * wd,zpool_handle_t * zhp,int row)13302 print_wait_status_row(wait_data_t *wd, zpool_handle_t *zhp, int row)
13303 {
13304 	nvlist_t *config, *nvroot;
13305 	uint_t c;
13306 	int i;
13307 	pool_checkpoint_stat_t *pcs = NULL;
13308 	pool_scan_stat_t *pss = NULL;
13309 	pool_removal_stat_t *prs = NULL;
13310 	pool_raidz_expand_stat_t *pres = NULL;
13311 	const char *const headers[] = {"DISCARD", "FREE", "INITIALIZE",
13312 	    "REPLACE", "REMOVE", "RESILVER", "SCRUB", "TRIM", "RAIDZ_EXPAND"};
13313 	int col_widths[ZPOOL_WAIT_NUM_ACTIVITIES];
13314 
13315 	/* Calculate the width of each column */
13316 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13317 		/*
13318 		 * Make sure we have enough space in the col for pretty-printed
13319 		 * numbers and for the column header, and then leave a couple
13320 		 * spaces between cols for readability.
13321 		 */
13322 		col_widths[i] = MAX(strlen(headers[i]), 6) + 2;
13323 	}
13324 
13325 	if (timestamp_fmt != NODATE)
13326 		print_timestamp(timestamp_fmt);
13327 
13328 	/* Print header if appropriate */
13329 	int term_height = terminal_height();
13330 	boolean_t reprint_header = (!wd->wd_headers_once && term_height > 0 &&
13331 	    row % (term_height-1) == 0);
13332 	if (!wd->wd_scripted && (row == 0 || reprint_header)) {
13333 		for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13334 			if (wd->wd_enabled[i])
13335 				(void) printf("%*s", col_widths[i], headers[i]);
13336 		}
13337 		(void) fputc('\n', stdout);
13338 	}
13339 
13340 	/* Bytes of work remaining in each activity */
13341 	int64_t bytes_rem[ZPOOL_WAIT_NUM_ACTIVITIES] = {0};
13342 
13343 	bytes_rem[ZPOOL_WAIT_FREE] =
13344 	    zpool_get_prop_int(zhp, ZPOOL_PROP_FREEING, NULL);
13345 
13346 	config = zpool_get_config(zhp, NULL);
13347 	nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
13348 
13349 	(void) nvlist_lookup_uint64_array(nvroot,
13350 	    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
13351 	if (pcs != NULL && pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
13352 		bytes_rem[ZPOOL_WAIT_CKPT_DISCARD] = pcs->pcs_space;
13353 
13354 	(void) nvlist_lookup_uint64_array(nvroot,
13355 	    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
13356 	if (prs != NULL && prs->prs_state == DSS_SCANNING)
13357 		bytes_rem[ZPOOL_WAIT_REMOVE] = prs->prs_to_copy -
13358 		    prs->prs_copied;
13359 
13360 	(void) nvlist_lookup_uint64_array(nvroot,
13361 	    ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&pss, &c);
13362 	if (pss != NULL && pss->pss_state == DSS_SCANNING &&
13363 	    pss->pss_pass_scrub_pause == 0) {
13364 		int64_t rem = pss->pss_to_examine - pss->pss_issued;
13365 		if (pss->pss_func == POOL_SCAN_SCRUB)
13366 			bytes_rem[ZPOOL_WAIT_SCRUB] = rem;
13367 		else
13368 			bytes_rem[ZPOOL_WAIT_RESILVER] = rem;
13369 	} else if (check_rebuilding(nvroot, NULL)) {
13370 		bytes_rem[ZPOOL_WAIT_RESILVER] =
13371 		    vdev_activity_top_remaining(nvroot);
13372 	}
13373 
13374 	(void) nvlist_lookup_uint64_array(nvroot,
13375 	    ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
13376 	if (pres != NULL && pres->pres_state == DSS_SCANNING) {
13377 		int64_t rem = pres->pres_to_reflow - pres->pres_reflowed;
13378 		bytes_rem[ZPOOL_WAIT_RAIDZ_EXPAND] = rem;
13379 	}
13380 
13381 	bytes_rem[ZPOOL_WAIT_INITIALIZE] =
13382 	    vdev_activity_remaining(nvroot, ZPOOL_WAIT_INITIALIZE);
13383 	bytes_rem[ZPOOL_WAIT_TRIM] =
13384 	    vdev_activity_remaining(nvroot, ZPOOL_WAIT_TRIM);
13385 
13386 	/*
13387 	 * A replace finishes after resilvering finishes, so the amount of work
13388 	 * left for a replace is the same as for resilvering.
13389 	 *
13390 	 * It isn't quite correct to say that if we have any 'spare' or
13391 	 * 'replacing' vdevs and a resilver is happening, then a replace is in
13392 	 * progress, like we do here. When a hot spare is used, the faulted vdev
13393 	 * is not removed after the hot spare is resilvered, so parent 'spare'
13394 	 * vdev is not removed either. So we could have a 'spare' vdev, but be
13395 	 * resilvering for a different reason. However, we use it as a heuristic
13396 	 * because we don't have access to the DTLs, which could tell us whether
13397 	 * or not we have really finished resilvering a hot spare.
13398 	 */
13399 	if (vdev_any_spare_replacing(nvroot))
13400 		bytes_rem[ZPOOL_WAIT_REPLACE] =  bytes_rem[ZPOOL_WAIT_RESILVER];
13401 
13402 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13403 		char buf[64];
13404 		if (!wd->wd_enabled[i])
13405 			continue;
13406 
13407 		if (wd->wd_exact) {
13408 			(void) snprintf(buf, sizeof (buf), "%" PRIi64,
13409 			    bytes_rem[i]);
13410 		} else {
13411 			zfs_nicenum(bytes_rem[i], buf, sizeof (buf));
13412 		}
13413 
13414 		if (wd->wd_scripted)
13415 			(void) printf(i == 0 ? "%s" : "\t%s", buf);
13416 		else
13417 			(void) printf(" %*s", col_widths[i] - 1, buf);
13418 	}
13419 	(void) printf("\n");
13420 	(void) fflush(stdout);
13421 }
13422 
13423 static void *
wait_status_thread(void * arg)13424 wait_status_thread(void *arg)
13425 {
13426 	wait_data_t *wd = (wait_data_t *)arg;
13427 	zpool_handle_t *zhp;
13428 
13429 	if ((zhp = zpool_open(g_zfs, wd->wd_poolname)) == NULL)
13430 		return (void *)(1);
13431 
13432 	for (int row = 0; ; row++) {
13433 		boolean_t missing;
13434 		struct timespec timeout;
13435 		int ret = 0;
13436 		(void) clock_gettime(CLOCK_REALTIME, &timeout);
13437 
13438 		if (zpool_refresh_stats(zhp, &missing) != 0 || missing ||
13439 		    zpool_props_refresh(zhp) != 0) {
13440 			zpool_close(zhp);
13441 			return (void *)(uintptr_t)(missing ? 0 : 1);
13442 		}
13443 
13444 		print_wait_status_row(wd, zhp, row);
13445 
13446 		timeout.tv_sec += floor(wd->wd_interval);
13447 		long nanos = timeout.tv_nsec +
13448 		    (wd->wd_interval - floor(wd->wd_interval)) * NANOSEC;
13449 		if (nanos >= NANOSEC) {
13450 			timeout.tv_sec++;
13451 			timeout.tv_nsec = nanos - NANOSEC;
13452 		} else {
13453 			timeout.tv_nsec = nanos;
13454 		}
13455 		(void) pthread_mutex_lock(&wd->wd_mutex);
13456 		if (!wd->wd_should_exit)
13457 			ret = pthread_cond_timedwait(&wd->wd_cv, &wd->wd_mutex,
13458 			    &timeout);
13459 		(void) pthread_mutex_unlock(&wd->wd_mutex);
13460 		if (ret == 0) {
13461 			break; /* signaled by main thread */
13462 		} else if (ret != ETIMEDOUT) {
13463 			(void) fprintf(stderr, gettext("pthread_cond_timedwait "
13464 			    "failed: %s\n"), strerror(ret));
13465 			zpool_close(zhp);
13466 			return (void *)(uintptr_t)(1);
13467 		}
13468 	}
13469 
13470 	zpool_close(zhp);
13471 	return (void *)(0);
13472 }
13473 
13474 int
zpool_do_wait(int argc,char ** argv)13475 zpool_do_wait(int argc, char **argv)
13476 {
13477 	boolean_t verbose = B_FALSE;
13478 	int c, i;
13479 	unsigned long count;
13480 	pthread_t status_thr;
13481 	int error = 0;
13482 	zpool_handle_t *zhp;
13483 
13484 	wait_data_t wd;
13485 	wd.wd_scripted = B_FALSE;
13486 	wd.wd_exact = B_FALSE;
13487 	wd.wd_headers_once = B_FALSE;
13488 	wd.wd_should_exit = B_FALSE;
13489 
13490 	(void) pthread_mutex_init(&wd.wd_mutex, NULL);
13491 	(void) pthread_cond_init(&wd.wd_cv, NULL);
13492 
13493 	/* By default, wait for all types of activity. */
13494 	for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++)
13495 		wd.wd_enabled[i] = B_TRUE;
13496 
13497 	while ((c = getopt(argc, argv, "HpT:t:")) != -1) {
13498 		switch (c) {
13499 		case 'H':
13500 			wd.wd_scripted = B_TRUE;
13501 			break;
13502 		case 'n':
13503 			wd.wd_headers_once = B_TRUE;
13504 			break;
13505 		case 'p':
13506 			wd.wd_exact = B_TRUE;
13507 			break;
13508 		case 'T':
13509 			get_timestamp_arg(*optarg);
13510 			break;
13511 		case 't':
13512 			/* Reset activities array */
13513 			memset(&wd.wd_enabled, 0, sizeof (wd.wd_enabled));
13514 
13515 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
13516 				static const char *const col_opts[] = {
13517 				    "discard", "free", "initialize", "replace",
13518 				    "remove", "resilver", "scrub", "trim",
13519 				    "raidz_expand" };
13520 
13521 				for (i = 0; i < ARRAY_SIZE(col_opts); ++i)
13522 					if (strcmp(tok, col_opts[i]) == 0) {
13523 						wd.wd_enabled[i] = B_TRUE;
13524 						goto found;
13525 					}
13526 
13527 				(void) fprintf(stderr,
13528 				    gettext("invalid activity '%s'\n"), tok);
13529 				usage(B_FALSE);
13530 found:;
13531 			}
13532 			break;
13533 		case '?':
13534 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
13535 			    optopt);
13536 			usage(B_FALSE);
13537 		}
13538 	}
13539 
13540 	argc -= optind;
13541 	argv += optind;
13542 
13543 	get_interval_count(&argc, argv, &wd.wd_interval, &count);
13544 	if (count != 0) {
13545 		/* This subcmd only accepts an interval, not a count */
13546 		(void) fprintf(stderr, gettext("too many arguments\n"));
13547 		usage(B_FALSE);
13548 	}
13549 
13550 	if (wd.wd_interval != 0)
13551 		verbose = B_TRUE;
13552 
13553 	if (argc < 1) {
13554 		(void) fprintf(stderr, gettext("missing 'pool' argument\n"));
13555 		usage(B_FALSE);
13556 	}
13557 	if (argc > 1) {
13558 		(void) fprintf(stderr, gettext("too many arguments\n"));
13559 		usage(B_FALSE);
13560 	}
13561 
13562 	wd.wd_poolname = argv[0];
13563 
13564 	if ((zhp = zpool_open(g_zfs, wd.wd_poolname)) == NULL)
13565 		return (1);
13566 
13567 	if (verbose) {
13568 		/*
13569 		 * We use a separate thread for printing status updates because
13570 		 * the main thread will call lzc_wait(), which blocks as long
13571 		 * as an activity is in progress, which can be a long time.
13572 		 */
13573 		if (pthread_create(&status_thr, NULL, wait_status_thread, &wd)
13574 		    != 0) {
13575 			(void) fprintf(stderr, gettext("failed to create status"
13576 			    "thread: %s\n"), strerror(errno));
13577 			zpool_close(zhp);
13578 			return (1);
13579 		}
13580 	}
13581 
13582 	/*
13583 	 * Loop over all activities that we are supposed to wait for until none
13584 	 * of them are in progress. Note that this means we can end up waiting
13585 	 * for more activities to complete than just those that were in progress
13586 	 * when we began waiting; if an activity we are interested in begins
13587 	 * while we are waiting for another activity, we will wait for both to
13588 	 * complete before exiting.
13589 	 */
13590 	for (;;) {
13591 		boolean_t missing = B_FALSE;
13592 		boolean_t any_waited = B_FALSE;
13593 
13594 		for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13595 			boolean_t waited;
13596 
13597 			if (!wd.wd_enabled[i])
13598 				continue;
13599 
13600 			error = zpool_wait_status(zhp, i, &missing, &waited);
13601 			if (error != 0 || missing)
13602 				break;
13603 
13604 			any_waited = (any_waited || waited);
13605 		}
13606 
13607 		if (error != 0 || missing || !any_waited)
13608 			break;
13609 	}
13610 
13611 	zpool_close(zhp);
13612 
13613 	if (verbose) {
13614 		uintptr_t status;
13615 		(void) pthread_mutex_lock(&wd.wd_mutex);
13616 		wd.wd_should_exit = B_TRUE;
13617 		(void) pthread_cond_signal(&wd.wd_cv);
13618 		(void) pthread_mutex_unlock(&wd.wd_mutex);
13619 		(void) pthread_join(status_thr, (void *)&status);
13620 		if (status != 0)
13621 			error = status;
13622 	}
13623 
13624 	(void) pthread_mutex_destroy(&wd.wd_mutex);
13625 	(void) pthread_cond_destroy(&wd.wd_cv);
13626 	return (error);
13627 }
13628 
13629 /*
13630  * zpool ddtprune -d|-p <amount> <pool>
13631  *
13632  *       -d <days>	Prune entries <days> old and older
13633  *       -p <percent>	Prune <percent> amount of entries
13634  *
13635  * Prune single reference entries from DDT to satisfy the amount specified.
13636  */
13637 int
zpool_do_ddt_prune(int argc,char ** argv)13638 zpool_do_ddt_prune(int argc, char **argv)
13639 {
13640 	zpool_ddt_prune_unit_t unit = ZPOOL_DDT_PRUNE_NONE;
13641 	uint64_t amount = 0;
13642 	zpool_handle_t *zhp;
13643 	char *endptr;
13644 	int c;
13645 
13646 	while ((c = getopt(argc, argv, "d:p:")) != -1) {
13647 		switch (c) {
13648 		case 'd':
13649 			if (unit == ZPOOL_DDT_PRUNE_PERCENTAGE) {
13650 				(void) fprintf(stderr, gettext("-d cannot be "
13651 				    "combined with -p option\n"));
13652 				usage(B_FALSE);
13653 			}
13654 			errno = 0;
13655 			amount = strtoull(optarg, &endptr, 0);
13656 			if (errno != 0 || *endptr != '\0' || amount == 0) {
13657 				(void) fprintf(stderr,
13658 				    gettext("invalid days value\n"));
13659 				usage(B_FALSE);
13660 			}
13661 			amount *= 86400;	/* convert days to seconds */
13662 			unit = ZPOOL_DDT_PRUNE_AGE;
13663 			break;
13664 		case 'p':
13665 			if (unit == ZPOOL_DDT_PRUNE_AGE) {
13666 				(void) fprintf(stderr, gettext("-p cannot be "
13667 				    "combined with -d option\n"));
13668 				usage(B_FALSE);
13669 			}
13670 			errno = 0;
13671 			amount = strtoull(optarg, &endptr, 0);
13672 			if (errno != 0 || *endptr != '\0' ||
13673 			    amount == 0 || amount > 100) {
13674 				(void) fprintf(stderr,
13675 				    gettext("invalid percentage value\n"));
13676 				usage(B_FALSE);
13677 			}
13678 			unit = ZPOOL_DDT_PRUNE_PERCENTAGE;
13679 			break;
13680 		case '?':
13681 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
13682 			    optopt);
13683 			usage(B_FALSE);
13684 		}
13685 	}
13686 	argc -= optind;
13687 	argv += optind;
13688 
13689 	if (unit == ZPOOL_DDT_PRUNE_NONE) {
13690 		(void) fprintf(stderr,
13691 		    gettext("missing amount option (-d|-p <value>)\n"));
13692 		usage(B_FALSE);
13693 	} else if (argc < 1) {
13694 		(void) fprintf(stderr, gettext("missing pool argument\n"));
13695 		usage(B_FALSE);
13696 	} else if (argc > 1) {
13697 		(void) fprintf(stderr, gettext("too many arguments\n"));
13698 		usage(B_FALSE);
13699 	}
13700 	zhp = zpool_open(g_zfs, argv[0]);
13701 	if (zhp == NULL)
13702 		return (-1);
13703 
13704 	int error = zpool_ddt_prune(zhp, unit, amount);
13705 
13706 	zpool_close(zhp);
13707 
13708 	return (error);
13709 }
13710 
13711 static int
find_command_idx(const char * command,int * idx)13712 find_command_idx(const char *command, int *idx)
13713 {
13714 	for (int i = 0; i < NCOMMAND; ++i) {
13715 		if (command_table[i].name == NULL)
13716 			continue;
13717 
13718 		if (strcmp(command, command_table[i].name) == 0) {
13719 			*idx = i;
13720 			return (0);
13721 		}
13722 	}
13723 	return (1);
13724 }
13725 
13726 /*
13727  * Display version message
13728  */
13729 static int
zpool_do_version(int argc,char ** argv)13730 zpool_do_version(int argc, char **argv)
13731 {
13732 	int c;
13733 	nvlist_t *jsobj = NULL, *zfs_ver = NULL;
13734 	boolean_t json = B_FALSE;
13735 
13736 	struct option long_options[] = {
13737 		{"json", no_argument, NULL, 'j'},
13738 	};
13739 
13740 	while ((c = getopt_long(argc, argv, "j", long_options, NULL)) != -1) {
13741 		switch (c) {
13742 		case 'j':
13743 			json = B_TRUE;
13744 			jsobj = zpool_json_schema(0, 1);
13745 			break;
13746 		case '?':
13747 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
13748 			    optopt);
13749 			usage(B_FALSE);
13750 		}
13751 	}
13752 
13753 	argc -= optind;
13754 	if (argc != 0) {
13755 		(void) fprintf(stderr, "too many arguments\n");
13756 		usage(B_FALSE);
13757 	}
13758 
13759 	if (json) {
13760 		zfs_ver = zfs_version_nvlist();
13761 		if (zfs_ver) {
13762 			fnvlist_add_nvlist(jsobj, "zfs_version", zfs_ver);
13763 			zcmd_print_json(jsobj);
13764 			fnvlist_free(zfs_ver);
13765 			return (0);
13766 		} else
13767 			return (-1);
13768 	} else
13769 		return (zfs_version_print() != 0);
13770 }
13771 
13772 /* Display documentation */
13773 static int
zpool_do_help(int argc,char ** argv)13774 zpool_do_help(int argc, char **argv)
13775 {
13776 	char page[MAXNAMELEN];
13777 	if (argc < 3 || strcmp(argv[2], "zpool") == 0)
13778 		(void) strcpy(page, "zpool");
13779 	else if (strcmp(argv[2], "concepts") == 0 ||
13780 	    strcmp(argv[2], "props") == 0)
13781 		(void) snprintf(page, sizeof (page), "zpool%s", argv[2]);
13782 	else
13783 		(void) snprintf(page, sizeof (page), "zpool-%s", argv[2]);
13784 
13785 	(void) execlp("man", "man", page, NULL);
13786 
13787 	fprintf(stderr, "couldn't run man program: %s\n", strerror(errno));
13788 	return (-1);
13789 }
13790 
13791 /*
13792  * Do zpool_load_compat() and print error message on failure
13793  */
13794 static zpool_compat_status_t
zpool_do_load_compat(const char * compat,boolean_t * list)13795 zpool_do_load_compat(const char *compat, boolean_t *list)
13796 {
13797 	char report[1024];
13798 
13799 	zpool_compat_status_t ret;
13800 
13801 	ret = zpool_load_compat(compat, list, report, 1024);
13802 	switch (ret) {
13803 
13804 	case ZPOOL_COMPATIBILITY_OK:
13805 		break;
13806 
13807 	case ZPOOL_COMPATIBILITY_NOFILES:
13808 	case ZPOOL_COMPATIBILITY_BADFILE:
13809 	case ZPOOL_COMPATIBILITY_BADTOKEN:
13810 		(void) fprintf(stderr, "Error: %s\n", report);
13811 		break;
13812 
13813 	case ZPOOL_COMPATIBILITY_WARNTOKEN:
13814 		(void) fprintf(stderr, "Warning: %s\n", report);
13815 		ret = ZPOOL_COMPATIBILITY_OK;
13816 		break;
13817 	}
13818 	return (ret);
13819 }
13820 
13821 int
main(int argc,char ** argv)13822 main(int argc, char **argv)
13823 {
13824 	int ret = 0;
13825 	int i = 0;
13826 	char *cmdname;
13827 	char **newargv;
13828 
13829 	(void) setlocale(LC_ALL, "");
13830 	(void) setlocale(LC_NUMERIC, "C");
13831 	(void) textdomain(TEXT_DOMAIN);
13832 	srand(time(NULL));
13833 
13834 	opterr = 0;
13835 
13836 	/*
13837 	 * Make sure the user has specified some command.
13838 	 */
13839 	if (argc < 2) {
13840 		(void) fprintf(stderr, gettext("missing command\n"));
13841 		usage(B_FALSE);
13842 	}
13843 
13844 	cmdname = argv[1];
13845 
13846 	/*
13847 	 * Special case '-?'
13848 	 */
13849 	if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
13850 		usage(B_TRUE);
13851 
13852 	/*
13853 	 * Special case '-V|--version'
13854 	 */
13855 	if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
13856 		return (zfs_version_print() != 0);
13857 
13858 	/*
13859 	 * Special case 'help'
13860 	 */
13861 	if (strcmp(cmdname, "help") == 0)
13862 		return (zpool_do_help(argc, argv));
13863 
13864 	if ((g_zfs = libzfs_init()) == NULL) {
13865 		(void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
13866 		return (1);
13867 	}
13868 
13869 	libzfs_print_on_error(g_zfs, B_TRUE);
13870 
13871 	zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
13872 
13873 	/*
13874 	 * Many commands modify input strings for string parsing reasons.
13875 	 * We create a copy to protect the original argv.
13876 	 */
13877 	newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
13878 	for (i = 0; i < argc; i++)
13879 		newargv[i] = strdup(argv[i]);
13880 	newargv[argc] = NULL;
13881 
13882 	/*
13883 	 * Run the appropriate command.
13884 	 */
13885 	if (find_command_idx(cmdname, &i) == 0) {
13886 		current_command = &command_table[i];
13887 		ret = command_table[i].func(argc - 1, newargv + 1);
13888 	} else if (strchr(cmdname, '=')) {
13889 		verify(find_command_idx("set", &i) == 0);
13890 		current_command = &command_table[i];
13891 		ret = command_table[i].func(argc, newargv);
13892 	} else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
13893 		/*
13894 		 * 'freeze' is a vile debugging abomination, so we treat
13895 		 * it as such.
13896 		 */
13897 		zfs_cmd_t zc = {"\0"};
13898 
13899 		(void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
13900 		ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
13901 		if (ret != 0) {
13902 			(void) fprintf(stderr,
13903 			gettext("failed to freeze pool: %d\n"), errno);
13904 			ret = 1;
13905 		}
13906 
13907 		log_history = 0;
13908 	} else {
13909 		(void) fprintf(stderr, gettext("unrecognized "
13910 		    "command '%s'\n"), cmdname);
13911 		usage(B_FALSE);
13912 	}
13913 
13914 	for (i = 0; i < argc; i++)
13915 		free(newargv[i]);
13916 	free(newargv);
13917 
13918 	if (ret == 0 && log_history)
13919 		(void) zpool_log_history(g_zfs, history_str);
13920 
13921 	libzfs_fini(g_zfs);
13922 
13923 	/*
13924 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
13925 	 * for the purposes of running ::findleaks.
13926 	 */
13927 	if (getenv("ZFS_ABORT") != NULL) {
13928 		(void) printf("dumping core by request\n");
13929 		abort();
13930 	}
13931 
13932 	return (ret);
13933 }
13934