1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * This file and its contents are supplied under the terms of the
4 * Common Development and Distribution License ("CDDL"), version 1.0.
5 * You may only use this file in accordance with the terms of version
6 * 1.0 of the CDDL.
7 *
8 * A full copy of the text of the CDDL should have accompanied this
9 * source. A copy of the CDDL is also available via the Internet at
10 * https://opensource.org/license/CDDL-1.0.
11 */
12
13 /*
14 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
15 * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
16 * Copyright (c) 2011, 2024 by Delphix. All rights reserved.
17 * Copyright (c) 2012 by Frederik Wessels. All rights reserved.
18 * Copyright (c) 2012 by Cyril Plisko. All rights reserved.
19 * Copyright (c) 2013 by Prasad Joshi (sTec). All rights reserved.
20 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
21 * Copyright (c) 2017 Datto Inc.
22 * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
23 * Copyright (c) 2017, Intel Corporation.
24 * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>
25 * Copyright (c) 2021, Colm Buckley <colm@tuatha.org>
26 * Copyright (c) 2021, 2023-2026, Klara, Inc.
27 * Copyright (c) 2021, 2025 Hewlett Packard Enterprise Development LP.
28 * Copyright (c) 2026, TrueNAS.
29 */
30
31 #include <assert.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <getopt.h>
37 #include <inttypes.h>
38 #include <libgen.h>
39 #include <libintl.h>
40 #include <locale.h>
41 #include <pthread.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <termios.h>
46 #include <time.h>
47 #include <unistd.h>
48 #include <pwd.h>
49 #include <zone.h>
50 #include <sys/wait.h>
51 #include <zfs_prop.h>
52 #include <sys/fs/zfs.h>
53 #include <sys/stat.h>
54 #include <sys/systeminfo.h>
55 #include <sys/fm/fs/zfs.h>
56 #include <sys/fm/util.h>
57 #include <sys/fm/protocol.h>
58 #include <sys/zfs_ioctl.h>
59 #include <sys/mount.h>
60 #include <sys/sysmacros.h>
61 #include <string.h>
62 #include <math.h>
63
64 #include <libzfs.h>
65 #include <libzutil.h>
66
67 #include "zpool_util.h"
68 #include "zfs_comutil.h"
69 #include "zfeature_common.h"
70 #include "zfs_valstr.h"
71
72 #include "statcommon.h"
73
74 libzfs_handle_t *g_zfs;
75
76 static int mount_tp_nthr = 512; /* tpool threads for multi-threaded mounting */
77
78 static int zpool_do_create(int, char **);
79 static int zpool_do_destroy(int, char **);
80
81 static int zpool_do_add(int, char **);
82 static int zpool_do_remove(int, char **);
83 static int zpool_do_labelclear(int, char **);
84
85 static int zpool_do_checkpoint(int, char **);
86 static int zpool_do_prefetch(int, char **);
87
88 static int zpool_do_list(int, char **);
89 static int zpool_do_iostat(int, char **);
90 static int zpool_do_status(int, char **);
91
92 static int zpool_do_online(int, char **);
93 static int zpool_do_offline(int, char **);
94 static int zpool_do_clear(int, char **);
95 static int zpool_do_reopen(int, char **);
96
97 static int zpool_do_reguid(int, char **);
98
99 static int zpool_do_attach(int, char **);
100 static int zpool_do_detach(int, char **);
101 static int zpool_do_replace(int, char **);
102 static int zpool_do_split(int, char **);
103
104 static int zpool_do_initialize(int, char **);
105 static int zpool_do_scrub(int, char **);
106 static int zpool_do_resilver(int, char **);
107 static int zpool_do_trim(int, char **);
108
109 static int zpool_do_import(int, char **);
110 static int zpool_do_export(int, char **);
111
112 static int zpool_do_upgrade(int, char **);
113
114 static int zpool_do_history(int, char **);
115 static int zpool_do_events(int, char **);
116
117 static int zpool_do_get(int, char **);
118 static int zpool_do_set(int, char **);
119
120 static int zpool_do_sync(int, char **);
121 static int zpool_do_condense(int, char **);
122
123 static int zpool_do_version(int, char **);
124
125 static int zpool_do_wait(int, char **);
126
127 static int zpool_do_ddt_prune(int, char **);
128
129 static int zpool_do_help(int argc, char **argv);
130
131 static zpool_compat_status_t zpool_do_load_compat(
132 const char *, boolean_t *);
133
134 enum zpool_options {
135 ZPOOL_OPTION_POWER = 1024,
136 ZPOOL_OPTION_ALLOW_INUSE,
137 ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH,
138 ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH,
139 ZPOOL_OPTION_POOL_KEY_GUID,
140 ZPOOL_OPTION_JSON_NUMS_AS_INT,
141 ZPOOL_OPTION_JSON_FLAT_VDEVS,
142 ZPOOL_OPTION_CONDENSE_LIST_TYPES
143 };
144
145 /*
146 * These libumem hooks provide a reasonable set of defaults for the allocator's
147 * debugging facilities.
148 */
149
150 #ifdef DEBUG
151 const char *
_umem_debug_init(void)152 _umem_debug_init(void)
153 {
154 return ("default,verbose"); /* $UMEM_DEBUG setting */
155 }
156
157 const char *
_umem_logging_init(void)158 _umem_logging_init(void)
159 {
160 return ("fail,contents"); /* $UMEM_LOGGING setting */
161 }
162 #endif
163
164 typedef enum {
165 HELP_ADD,
166 HELP_ATTACH,
167 HELP_CLEAR,
168 HELP_CREATE,
169 HELP_CHECKPOINT,
170 HELP_CONDENSE,
171 HELP_DDT_PRUNE,
172 HELP_DESTROY,
173 HELP_DETACH,
174 HELP_EXPORT,
175 HELP_HISTORY,
176 HELP_IMPORT,
177 HELP_IOSTAT,
178 HELP_LABELCLEAR,
179 HELP_LIST,
180 HELP_OFFLINE,
181 HELP_ONLINE,
182 HELP_PREFETCH,
183 HELP_REPLACE,
184 HELP_REMOVE,
185 HELP_INITIALIZE,
186 HELP_SCRUB,
187 HELP_RESILVER,
188 HELP_TRIM,
189 HELP_STATUS,
190 HELP_UPGRADE,
191 HELP_EVENTS,
192 HELP_GET,
193 HELP_SET,
194 HELP_SPLIT,
195 HELP_SYNC,
196 HELP_REGUID,
197 HELP_REOPEN,
198 HELP_VERSION,
199 HELP_WAIT
200 } zpool_help_t;
201
202
203 /*
204 * Flags for stats to display with "zpool iostats"
205 */
206 enum iostat_type {
207 IOS_DEFAULT = 0,
208 IOS_LATENCY = 1,
209 IOS_QUEUES = 2,
210 IOS_L_HISTO = 3,
211 IOS_RQ_HISTO = 4,
212 IOS_COUNT, /* always last element */
213 };
214
215 /* iostat_type entries as bitmasks */
216 #define IOS_DEFAULT_M (1ULL << IOS_DEFAULT)
217 #define IOS_LATENCY_M (1ULL << IOS_LATENCY)
218 #define IOS_QUEUES_M (1ULL << IOS_QUEUES)
219 #define IOS_L_HISTO_M (1ULL << IOS_L_HISTO)
220 #define IOS_RQ_HISTO_M (1ULL << IOS_RQ_HISTO)
221
222 /* Mask of all the histo bits */
223 #define IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
224
225 /*
226 * Lookup table for iostat flags to nvlist names. Basically a list
227 * of all the nvlists a flag requires. Also specifies the order in
228 * which data gets printed in zpool iostat.
229 */
230 static const char *vsx_type_to_nvlist[IOS_COUNT][15] = {
231 [IOS_L_HISTO] = {
232 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
233 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
234 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
235 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
236 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
237 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
238 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
239 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
240 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
241 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
242 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
243 NULL},
244 [IOS_LATENCY] = {
245 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
246 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
247 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
248 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
249 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
250 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
251 NULL},
252 [IOS_QUEUES] = {
253 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
254 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
255 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
256 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
257 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
258 ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
259 ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
260 NULL},
261 [IOS_RQ_HISTO] = {
262 ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
263 ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
264 ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
265 ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
266 ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
267 ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
268 ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
269 ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
270 ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
271 ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
272 ZPOOL_CONFIG_VDEV_IND_TRIM_HISTO,
273 ZPOOL_CONFIG_VDEV_AGG_TRIM_HISTO,
274 ZPOOL_CONFIG_VDEV_IND_REBUILD_HISTO,
275 ZPOOL_CONFIG_VDEV_AGG_REBUILD_HISTO,
276 NULL},
277 };
278
279 static const char *pool_scan_func_str[] = {
280 "NONE",
281 "SCRUB",
282 "RESILVER",
283 "ERRORSCRUB"
284 };
285
286 static const char *pool_scan_state_str[] = {
287 "NONE",
288 "SCANNING",
289 "FINISHED",
290 "CANCELED",
291 "ERRORSCRUBBING"
292 };
293
294 static const char *vdev_rebuild_state_str[] = {
295 "NONE",
296 "ACTIVE",
297 "CANCELED",
298 "COMPLETE"
299 };
300
301 static const char *checkpoint_state_str[] = {
302 "NONE",
303 "EXISTS",
304 "DISCARDING"
305 };
306
307 static const char *vdev_state_str[] = {
308 "UNKNOWN",
309 "CLOSED",
310 "OFFLINE",
311 "REMOVED",
312 "CANT_OPEN",
313 "FAULTED",
314 "DEGRADED",
315 "ONLINE"
316 };
317
318 static const char *vdev_aux_str[] = {
319 "NONE",
320 "OPEN_FAILED",
321 "CORRUPT_DATA",
322 "NO_REPLICAS",
323 "BAD_GUID_SUM",
324 "TOO_SMALL",
325 "BAD_LABEL",
326 "VERSION_NEWER",
327 "VERSION_OLDER",
328 "UNSUP_FEAT",
329 "SPARED",
330 "ERR_EXCEEDED",
331 "IO_FAILURE",
332 "BAD_LOG",
333 "EXTERNAL",
334 "SPLIT_POOL",
335 "BAD_ASHIFT",
336 "EXTERNAL_PERSIST",
337 "ACTIVE",
338 "CHILDREN_OFFLINE",
339 "ASHIFT_TOO_BIG"
340 };
341
342 static const char *vdev_init_state_str[] = {
343 "NONE",
344 "ACTIVE",
345 "CANCELED",
346 "SUSPENDED",
347 "COMPLETE"
348 };
349
350 static const char *vdev_trim_state_str[] = {
351 "NONE",
352 "ACTIVE",
353 "CANCELED",
354 "SUSPENDED",
355 "COMPLETE"
356 };
357
condense_unit(const char * type)358 static const char *condense_unit(const char *type) {
359 if (strcmp(type, POOL_CONDENSE_LOG_SPACEMAP) == 0)
360 return ("metaslabs");
361 #ifdef ZFS_DEBUG
362 if (strcmp(type, "debug") == 0)
363 return ("nits"); /* fundamental unit of debugging? ;) */
364 #endif
365 return ("items");
366 }
367
368 #define ZFS_NICE_TIMESTAMP 100
369
370 /*
371 * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
372 * Right now, only one histo bit is ever set at one time, so we can
373 * just do a highbit64(a)
374 */
375 #define IOS_HISTO_IDX(a) (highbit64(a & IOS_ANYHISTO_M) - 1)
376
377 typedef struct zpool_command {
378 const char *name;
379 int (*func)(int, char **);
380 zpool_help_t usage;
381 } zpool_command_t;
382
383 /*
384 * Master command table. Each ZFS command has a name, associated function, and
385 * usage message. The usage messages need to be internationalized, so we have
386 * to have a function to return the usage message based on a command index.
387 *
388 * These commands are organized according to how they are displayed in the usage
389 * message. An empty command (one with a NULL name) indicates an empty line in
390 * the generic usage message.
391 */
392 static zpool_command_t command_table[] = {
393 { "version", zpool_do_version, HELP_VERSION },
394 { NULL },
395 { "create", zpool_do_create, HELP_CREATE },
396 { "destroy", zpool_do_destroy, HELP_DESTROY },
397 { NULL },
398 { "add", zpool_do_add, HELP_ADD },
399 { "remove", zpool_do_remove, HELP_REMOVE },
400 { NULL },
401 { "labelclear", zpool_do_labelclear, HELP_LABELCLEAR },
402 { NULL },
403 { "checkpoint", zpool_do_checkpoint, HELP_CHECKPOINT },
404 { "prefetch", zpool_do_prefetch, HELP_PREFETCH },
405 { NULL },
406 { "list", zpool_do_list, HELP_LIST },
407 { "iostat", zpool_do_iostat, HELP_IOSTAT },
408 { "status", zpool_do_status, HELP_STATUS },
409 { NULL },
410 { "online", zpool_do_online, HELP_ONLINE },
411 { "offline", zpool_do_offline, HELP_OFFLINE },
412 { "clear", zpool_do_clear, HELP_CLEAR },
413 { "reopen", zpool_do_reopen, HELP_REOPEN },
414 { NULL },
415 { "attach", zpool_do_attach, HELP_ATTACH },
416 { "detach", zpool_do_detach, HELP_DETACH },
417 { "replace", zpool_do_replace, HELP_REPLACE },
418 { "split", zpool_do_split, HELP_SPLIT },
419 { NULL },
420 { "initialize", zpool_do_initialize, HELP_INITIALIZE },
421 { "resilver", zpool_do_resilver, HELP_RESILVER },
422 { "scrub", zpool_do_scrub, HELP_SCRUB },
423 { "trim", zpool_do_trim, HELP_TRIM },
424 { "condense", zpool_do_condense, HELP_CONDENSE },
425 { NULL },
426 { "import", zpool_do_import, HELP_IMPORT },
427 { "export", zpool_do_export, HELP_EXPORT },
428 { "upgrade", zpool_do_upgrade, HELP_UPGRADE },
429 { "reguid", zpool_do_reguid, HELP_REGUID },
430 { NULL },
431 { "history", zpool_do_history, HELP_HISTORY },
432 { "events", zpool_do_events, HELP_EVENTS },
433 { NULL },
434 { "get", zpool_do_get, HELP_GET },
435 { "set", zpool_do_set, HELP_SET },
436 { NULL },
437 { "sync", zpool_do_sync, HELP_SYNC },
438 { NULL },
439 { "wait", zpool_do_wait, HELP_WAIT },
440 { NULL },
441 { "ddtprune", zpool_do_ddt_prune, HELP_DDT_PRUNE },
442 };
443
444 #define NCOMMAND (ARRAY_SIZE(command_table))
445
446 #define VDEV_ALLOC_CLASS_LOGS "logs"
447
448 #define MAX_CMD_LEN 256
449
450 static zpool_command_t *current_command;
451 static zfs_type_t current_prop_type = (ZFS_TYPE_POOL | ZFS_TYPE_VDEV);
452 static char history_str[HIS_MAX_RECORD_LEN];
453 static boolean_t log_history = B_TRUE;
454 static uint_t timestamp_fmt = NODATE;
455
456 static const char *
get_usage(zpool_help_t idx)457 get_usage(zpool_help_t idx)
458 {
459 switch (idx) {
460 case HELP_ADD:
461 return (gettext("\tadd [-afgLnP] [-o property=value] "
462 "<pool> <vdev> ...\n"));
463 case HELP_ATTACH:
464 return (gettext("\tattach [-fsw] [-o property=value] "
465 "<pool> <vdev> <new-device>\n"));
466 case HELP_CLEAR:
467 return (gettext("\tclear [--power] <pool> [device]\n"));
468 case HELP_CREATE:
469 return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
470 "\t [-O file-system-property=value] ... \n"
471 "\t [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
472 case HELP_CHECKPOINT:
473 return (gettext("\tcheckpoint [-d [-w]] <pool> ...\n"));
474 case HELP_DESTROY:
475 return (gettext("\tdestroy [-f] <pool>\n"));
476 case HELP_DETACH:
477 return (gettext("\tdetach <pool> <device>\n"));
478 case HELP_EXPORT:
479 return (gettext("\texport [-af] <pool> ...\n"));
480 case HELP_HISTORY:
481 return (gettext("\thistory [-il] [<pool>] ...\n"));
482 case HELP_IMPORT:
483 return (gettext("\timport [-d dir] [-D]\n"
484 "\timport [-o mntopts] [-o property=value] ... \n"
485 "\t [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
486 "[-R root] [-F [-n]] -a\n"
487 "\timport [-o mntopts] [-o property=value] ... \n"
488 "\t [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
489 "[-R root] [-F [-n]]\n"
490 "\t [--rewind-to-checkpoint] <pool | id> [newpool]\n"));
491 case HELP_IOSTAT:
492 return (gettext("\tiostat [[[-c [script1,script2,...]"
493 "[-lq]]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
494 "\t [[pool ...]|[pool vdev ...]|[vdev ...]]"
495 " [[-n] interval [count]]\n"));
496 case HELP_LABELCLEAR:
497 return (gettext("\tlabelclear [-f] <vdev>\n"));
498 case HELP_LIST:
499 return (gettext("\tlist [-gHLpPv] [-o property[,...]] [-j "
500 "[--json-int, --json-pool-key-guid]] ...\n"
501 "\t [-T d|u] [pool] [interval [count]]\n"));
502 case HELP_PREFETCH:
503 return (gettext("\tprefetch [-t <type>] <pool>\n"));
504 case HELP_OFFLINE:
505 return (gettext("\toffline [--power]|[[-f][-t]] <pool> "
506 "<device> ...\n"));
507 case HELP_ONLINE:
508 return (gettext("\tonline [--power][-e] <pool> <device> "
509 "...\n"));
510 case HELP_REPLACE:
511 return (gettext("\treplace [-fsw] [-o property=value] "
512 "<pool> <device> [new-device]\n"));
513 case HELP_REMOVE:
514 return (gettext("\tremove [-npsw] <pool> <device> ...\n"));
515 case HELP_REOPEN:
516 return (gettext("\treopen [-n] <pool>\n"));
517 case HELP_INITIALIZE:
518 return (gettext("\tinitialize [-c | -s | -u] [-w] [-z] "
519 "<-a | <pool> [<device> ...]>\n"));
520 case HELP_SCRUB:
521 return (gettext("\tscrub [-e | -s | -p | -t | -C [-t] | "
522 "[-S date] [-E date] [-t]] [-w]\n"
523 "\t <-a | <pool> [<pool> ...]>\n"));
524 case HELP_RESILVER:
525 return (gettext("\tresilver <pool> ...\n"));
526 case HELP_TRIM:
527 return (gettext("\ttrim [-dw] [-r <rate>] [-c | -s] "
528 "<-a | <pool> [<device> ...]>\n"));
529 case HELP_STATUS:
530 return (gettext("\tstatus [-DdegiLPpstvx] "
531 "[-c script1[,script2,...]] ...\n"
532 "\t [-j|--json [--json-flat-vdevs] [--json-int] "
533 "[--json-pool-key-guid]] ...\n"
534 "\t [-T d|u] [--power] [pool] [interval [count]]\n"));
535 case HELP_UPGRADE:
536 return (gettext("\tupgrade\n"
537 "\tupgrade -v\n"
538 "\tupgrade [-V version] <-a | pool ...>\n"));
539 case HELP_EVENTS:
540 return (gettext("\tevents [-vHf [pool] | -c]\n"));
541 case HELP_GET:
542 return (gettext("\tget [-Hp] [-j [--json-int, "
543 "--json-pool-key-guid]] ...\n"
544 "\t [-o \"all\" | field[,...]] "
545 "<\"all\" | property[,...]> <pool> ...\n"));
546 case HELP_SET:
547 return (gettext("\tset <property=value> <pool>\n"
548 "\tset <vdev_property=value> <pool> <vdev>\n"));
549 case HELP_SPLIT:
550 return (gettext("\tsplit [-gLnPl] [-R altroot] [-o mntopts]\n"
551 "\t [-o property=value] <pool> <newpool> "
552 "[<device> ...]\n"));
553 case HELP_REGUID:
554 return (gettext("\treguid [-g guid] <pool>\n"));
555 case HELP_SYNC:
556 return (gettext("\tsync [pool] ...\n"));
557 case HELP_CONDENSE:
558 return (gettext("\tcondense [-t <type>] [-c | -w] "
559 "[-a | <pool> ...]\n"
560 "\tcondense --types\n"));
561 case HELP_VERSION:
562 return (gettext("\tversion [-j]\n"));
563 case HELP_WAIT:
564 return (gettext("\twait [-Hp] [-T d|u] [-t <activity>[,...]] "
565 "<pool> [interval]\n"));
566 case HELP_DDT_PRUNE:
567 return (gettext("\tddtprune -d|-p <amount> <pool>\n"));
568 default:
569 __builtin_unreachable();
570 }
571 }
572
573 /*
574 * Callback routine that will print out a pool property value.
575 */
576 static int
print_pool_prop_cb(int prop,void * cb)577 print_pool_prop_cb(int prop, void *cb)
578 {
579 FILE *fp = cb;
580
581 (void) fprintf(fp, "\t%-19s ", zpool_prop_to_name(prop));
582
583 if (zpool_prop_readonly(prop))
584 (void) fprintf(fp, " NO ");
585 else
586 (void) fprintf(fp, " YES ");
587
588 if (zpool_prop_values(prop) == NULL)
589 (void) fprintf(fp, "-\n");
590 else
591 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
592
593 return (ZPROP_CONT);
594 }
595
596 /*
597 * Callback routine that will print out a vdev property value.
598 */
599 static int
print_vdev_prop_cb(int prop,void * cb)600 print_vdev_prop_cb(int prop, void *cb)
601 {
602 FILE *fp = cb;
603
604 (void) fprintf(fp, "\t%-19s ", vdev_prop_to_name(prop));
605
606 if (vdev_prop_readonly(prop))
607 (void) fprintf(fp, " NO ");
608 else
609 (void) fprintf(fp, " YES ");
610
611 if (vdev_prop_values(prop) == NULL)
612 (void) fprintf(fp, "-\n");
613 else
614 (void) fprintf(fp, "%s\n", vdev_prop_values(prop));
615
616 return (ZPROP_CONT);
617 }
618
619 /*
620 * Given a leaf vdev name like 'L5' return its VDEV_CONFIG_PATH like
621 * '/dev/disk/by-vdev/L5'.
622 */
623 static const char *
vdev_name_to_path(zpool_handle_t * zhp,char * vdev)624 vdev_name_to_path(zpool_handle_t *zhp, char *vdev)
625 {
626 nvlist_t *vdev_nv = zpool_find_vdev(zhp, vdev, NULL, NULL, NULL);
627 if (vdev_nv == NULL) {
628 return (NULL);
629 }
630 return (fnvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH));
631 }
632
633 static int
zpool_power_on(zpool_handle_t * zhp,char * vdev)634 zpool_power_on(zpool_handle_t *zhp, char *vdev)
635 {
636 return (zpool_power(zhp, vdev, B_TRUE));
637 }
638
639 static int
zpool_power_on_and_disk_wait(zpool_handle_t * zhp,char * vdev)640 zpool_power_on_and_disk_wait(zpool_handle_t *zhp, char *vdev)
641 {
642 int rc;
643
644 rc = zpool_power_on(zhp, vdev);
645 if (rc != 0)
646 return (rc);
647
648 (void) zpool_disk_wait(vdev_name_to_path(zhp, vdev));
649
650 return (0);
651 }
652
653 static int
zpool_power_on_pool_and_wait_for_devices(zpool_handle_t * zhp)654 zpool_power_on_pool_and_wait_for_devices(zpool_handle_t *zhp)
655 {
656 nvlist_t *nv;
657 const char *path = NULL;
658 int rc;
659
660 /* Power up all the devices first */
661 FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
662 path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
663 if (path != NULL) {
664 rc = zpool_power_on(zhp, (char *)path);
665 if (rc != 0) {
666 return (rc);
667 }
668 }
669 }
670
671 /*
672 * Wait for their devices to show up. Since we powered them on
673 * at roughly the same time, they should all come online around
674 * the same time.
675 */
676 FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
677 path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
678 (void) zpool_disk_wait(path);
679 }
680
681 return (0);
682 }
683
684 static int
zpool_power_off(zpool_handle_t * zhp,char * vdev)685 zpool_power_off(zpool_handle_t *zhp, char *vdev)
686 {
687 return (zpool_power(zhp, vdev, B_FALSE));
688 }
689
690 /*
691 * Display usage message. If we're inside a command, display only the usage for
692 * that command. Otherwise, iterate over the entire command table and display
693 * a complete usage message.
694 */
695 static __attribute__((noreturn)) void
usage(boolean_t requested)696 usage(boolean_t requested)
697 {
698 FILE *fp = requested ? stdout : stderr;
699
700 if (current_command == NULL) {
701 int i;
702
703 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
704 (void) fprintf(fp,
705 gettext("where 'command' is one of the following:\n\n"));
706
707 for (i = 0; i < NCOMMAND; i++) {
708 if (command_table[i].name == NULL)
709 (void) fprintf(fp, "\n");
710 else
711 (void) fprintf(fp, "%s",
712 get_usage(command_table[i].usage));
713 }
714
715 (void) fprintf(fp,
716 gettext("\nFor further help on a command or topic, "
717 "run: %s\n"), "zpool help [<topic>]");
718 } else {
719 (void) fprintf(fp, gettext("usage:\n"));
720 (void) fprintf(fp, "%s", get_usage(current_command->usage));
721 }
722
723 if (current_command != NULL &&
724 current_prop_type != (ZFS_TYPE_POOL | ZFS_TYPE_VDEV) &&
725 ((strcmp(current_command->name, "set") == 0) ||
726 (strcmp(current_command->name, "get") == 0) ||
727 (strcmp(current_command->name, "list") == 0))) {
728
729 (void) fprintf(fp, "%s",
730 gettext("\nthe following properties are supported:\n"));
731
732 (void) fprintf(fp, "\n\t%-19s %s %s\n\n",
733 "PROPERTY", "EDIT", "VALUES");
734
735 /* Iterate over all properties */
736 if (current_prop_type == ZFS_TYPE_POOL) {
737 (void) zprop_iter(print_pool_prop_cb, fp, B_FALSE,
738 B_TRUE, current_prop_type);
739
740 (void) fprintf(fp, "\t%-19s ", "feature@...");
741 (void) fprintf(fp, "YES "
742 "disabled | enabled | active\n");
743
744 (void) fprintf(fp, gettext("\nThe feature@ properties "
745 "must be appended with a feature name.\n"
746 "See zpool-features(7).\n"));
747 } else if (current_prop_type == ZFS_TYPE_VDEV) {
748 (void) zprop_iter(print_vdev_prop_cb, fp, B_FALSE,
749 B_TRUE, current_prop_type);
750 }
751 }
752
753 /*
754 * See comments at end of main().
755 */
756 if (getenv("ZFS_ABORT") != NULL) {
757 (void) printf("dumping core by request\n");
758 abort();
759 }
760
761 exit(requested ? 0 : 2);
762 }
763
764 /*
765 * zpool initialize [-c | -s | -u] [-w] [-z] <-a | pool> [<vdev> ...]
766 * Initialize all unused blocks in the specified vdevs, or all vdevs in the pool
767 * if none specified.
768 *
769 * -a Use all pools.
770 * -c Cancel. Ends active initializing.
771 * -s Suspend. Initializing can then be restarted with no flags.
772 * -u Uninitialize. Clears initialization state.
773 * -w Wait. Blocks until initializing has completed.
774 */
775 int
zpool_do_initialize(int argc,char ** argv)776 zpool_do_initialize(int argc, char **argv)
777 {
778 int c;
779 char *poolname;
780 zpool_handle_t *zhp;
781 int err = 0;
782 boolean_t wait = B_FALSE;
783 boolean_t initialize_all = B_FALSE;
784 boolean_t zero = B_FALSE;
785
786 struct option long_options[] = {
787 {"cancel", no_argument, NULL, 'c'},
788 {"suspend", no_argument, NULL, 's'},
789 {"uninit", no_argument, NULL, 'u'},
790 {"wait", no_argument, NULL, 'w'},
791 {"all", no_argument, NULL, 'a'},
792 {"zero", no_argument, NULL, 'z'},
793 {0, 0, 0, 0}
794 };
795
796 pool_initialize_func_t cmd_type = POOL_INITIALIZE_START;
797 while ((c = getopt_long(argc, argv, "acsuwz", long_options,
798 NULL)) != -1) {
799 switch (c) {
800 case 'a':
801 initialize_all = B_TRUE;
802 break;
803 case 'z':
804 zero = B_TRUE;
805 break;
806 case 'c':
807 if (cmd_type != POOL_INITIALIZE_START &&
808 cmd_type != POOL_INITIALIZE_CANCEL) {
809 (void) fprintf(stderr, gettext("-c cannot be "
810 "combined with other options\n"));
811 usage(B_FALSE);
812 }
813 cmd_type = POOL_INITIALIZE_CANCEL;
814 break;
815 case 's':
816 if (cmd_type != POOL_INITIALIZE_START &&
817 cmd_type != POOL_INITIALIZE_SUSPEND) {
818 (void) fprintf(stderr, gettext("-s cannot be "
819 "combined with other options\n"));
820 usage(B_FALSE);
821 }
822 cmd_type = POOL_INITIALIZE_SUSPEND;
823 break;
824 case 'u':
825 if (cmd_type != POOL_INITIALIZE_START &&
826 cmd_type != POOL_INITIALIZE_UNINIT) {
827 (void) fprintf(stderr, gettext("-u cannot be "
828 "combined with other options\n"));
829 usage(B_FALSE);
830 }
831 cmd_type = POOL_INITIALIZE_UNINIT;
832 break;
833 case 'w':
834 wait = B_TRUE;
835 break;
836 case '?':
837 if (optopt != 0) {
838 (void) fprintf(stderr,
839 gettext("invalid option '%c'\n"), optopt);
840 } else {
841 (void) fprintf(stderr,
842 gettext("invalid option '%s'\n"),
843 argv[optind - 1]);
844 }
845 usage(B_FALSE);
846 }
847 }
848
849 argc -= optind;
850 argv += optind;
851
852 initialize_cbdata_t cbdata = {
853 .wait = wait,
854 .cmd_type = cmd_type,
855 .value = 0,
856 .value_provided = zero
857 };
858
859 if (initialize_all && argc > 0) {
860 (void) fprintf(stderr, gettext("-a cannot be combined with "
861 "individual pools or vdevs\n"));
862 usage(B_FALSE);
863 }
864
865 if (argc < 1 && !initialize_all) {
866 (void) fprintf(stderr, gettext("missing pool name argument\n"));
867 usage(B_FALSE);
868 }
869
870 if (wait && (cmd_type != POOL_INITIALIZE_START)) {
871 (void) fprintf(stderr, gettext("-w cannot be used with -c, -s"
872 "or -u\n"));
873 usage(B_FALSE);
874 }
875
876 if (zero && (cmd_type != POOL_INITIALIZE_START)) {
877 (void) fprintf(stderr, gettext("-z cannot be used with -c, -s "
878 "or -u\n"));
879 usage(B_FALSE);
880 }
881
882 if (argc == 0 && initialize_all) {
883 /* Initilize each pool recursively */
884 err = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
885 B_FALSE, zpool_initialize_one, &cbdata);
886 return (err);
887 } else if (argc == 1) {
888 /* no individual leaf vdevs specified, initialize the pool */
889 poolname = argv[0];
890 zhp = zpool_open(g_zfs, poolname);
891 if (zhp == NULL)
892 return (-1);
893 err = zpool_initialize_one(zhp, &cbdata);
894 } else {
895 /* individual leaf vdevs specified, initialize them */
896 poolname = argv[0];
897 zhp = zpool_open(g_zfs, poolname);
898 if (zhp == NULL)
899 return (-1);
900 nvlist_t *vdevs = fnvlist_alloc();
901 for (int i = 1; i < argc; i++) {
902 fnvlist_add_boolean(vdevs, argv[i]);
903 }
904 if (wait)
905 err = zpool_initialize_wait(zhp, cmd_type, vdevs,
906 cbdata.value, cbdata.value_provided);
907 else
908 err = zpool_initialize(zhp, cmd_type, vdevs,
909 cbdata.value, cbdata.value_provided);
910 fnvlist_free(vdevs);
911 }
912
913 zpool_close(zhp);
914
915 return (err);
916 }
917
918 /*
919 * print a pool vdev config for dry runs
920 */
921 static void
print_vdev_tree(zpool_handle_t * zhp,const char * name,nvlist_t * nv,int indent,const char * match,int name_flags)922 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
923 const char *match, int name_flags)
924 {
925 nvlist_t **child;
926 uint_t c, children;
927 char *vname;
928 boolean_t printed = B_FALSE;
929
930 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
931 &child, &children) != 0) {
932 if (name != NULL)
933 (void) printf("\t%*s%s\n", indent, "", name);
934 return;
935 }
936
937 for (c = 0; c < children; c++) {
938 uint64_t is_log = B_FALSE, is_hole = B_FALSE;
939 const char *class = "";
940
941 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
942 &is_hole);
943
944 if (is_hole == B_TRUE) {
945 continue;
946 }
947
948 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
949 &is_log);
950 if (is_log)
951 class = VDEV_ALLOC_BIAS_LOG;
952 (void) nvlist_lookup_string(child[c],
953 ZPOOL_CONFIG_ALLOCATION_BIAS, &class);
954 if (strcmp(match, class) != 0)
955 continue;
956
957 if (!printed && name != NULL) {
958 (void) printf("\t%*s%s\n", indent, "", name);
959 printed = B_TRUE;
960 }
961 vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
962 print_vdev_tree(zhp, vname, child[c], indent + 2, "",
963 name_flags);
964 free(vname);
965 }
966 }
967
968 /*
969 * Print the list of l2cache devices for dry runs.
970 */
971 static void
print_cache_list(nvlist_t * nv,int indent)972 print_cache_list(nvlist_t *nv, int indent)
973 {
974 nvlist_t **child;
975 uint_t c, children;
976
977 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
978 &child, &children) == 0 && children > 0) {
979 (void) printf("\t%*s%s\n", indent, "", "cache");
980 } else {
981 return;
982 }
983 for (c = 0; c < children; c++) {
984 char *vname;
985
986 vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
987 (void) printf("\t%*s%s\n", indent + 2, "", vname);
988 free(vname);
989 }
990 }
991
992 /*
993 * Print the list of spares for dry runs.
994 */
995 static void
print_spare_list(nvlist_t * nv,int indent)996 print_spare_list(nvlist_t *nv, int indent)
997 {
998 nvlist_t **child;
999 uint_t c, children;
1000
1001 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1002 &child, &children) == 0 && children > 0) {
1003 (void) printf("\t%*s%s\n", indent, "", "spares");
1004 } else {
1005 return;
1006 }
1007 for (c = 0; c < children; c++) {
1008 char *vname;
1009
1010 vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
1011 (void) printf("\t%*s%s\n", indent + 2, "", vname);
1012 free(vname);
1013 }
1014 }
1015
1016 typedef struct spare_cbdata {
1017 uint64_t cb_guid;
1018 zpool_handle_t *cb_zhp;
1019 } spare_cbdata_t;
1020
1021 static boolean_t
find_vdev(nvlist_t * nv,uint64_t search)1022 find_vdev(nvlist_t *nv, uint64_t search)
1023 {
1024 uint64_t guid;
1025 nvlist_t **child;
1026 uint_t c, children;
1027
1028 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1029 search == guid)
1030 return (B_TRUE);
1031
1032 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1033 &child, &children) == 0) {
1034 for (c = 0; c < children; c++)
1035 if (find_vdev(child[c], search))
1036 return (B_TRUE);
1037 }
1038
1039 return (B_FALSE);
1040 }
1041
1042 static int
find_spare(zpool_handle_t * zhp,void * data)1043 find_spare(zpool_handle_t *zhp, void *data)
1044 {
1045 spare_cbdata_t *cbp = data;
1046 nvlist_t *config, *nvroot;
1047
1048 config = zpool_get_config(zhp, NULL);
1049 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1050 &nvroot) == 0);
1051
1052 if (find_vdev(nvroot, cbp->cb_guid)) {
1053 cbp->cb_zhp = zhp;
1054 return (1);
1055 }
1056
1057 zpool_close(zhp);
1058 return (0);
1059 }
1060
1061 static void
nice_num_str_nvlist(nvlist_t * item,const char * key,uint64_t value,boolean_t literal,boolean_t as_int,int format)1062 nice_num_str_nvlist(nvlist_t *item, const char *key, uint64_t value,
1063 boolean_t literal, boolean_t as_int, int format)
1064 {
1065 char buf[256];
1066
1067 if (literal) {
1068 if (!as_int)
1069 (void) snprintf(buf, 256, "%llu", (u_longlong_t)value);
1070 } else {
1071 switch (format) {
1072 case ZFS_NICENUM_1024:
1073 zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_1024);
1074 break;
1075 case ZFS_NICENUM_BYTES:
1076 zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_BYTES);
1077 break;
1078 case ZFS_NICENUM_TIME:
1079 zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_TIME);
1080 break;
1081 case ZFS_NICE_TIMESTAMP:
1082 format_timestamp(value, buf, 256);
1083 break;
1084 default:
1085 fprintf(stderr, "Invalid number format");
1086 exit(1);
1087 }
1088 }
1089 if (as_int)
1090 fnvlist_add_uint64(item, key, value);
1091 else
1092 fnvlist_add_string(item, key, buf);
1093 }
1094
1095 /*
1096 * Generates an nvlist with output version for every command based on params.
1097 * Purpose of this is to add a version of JSON output, considering the schema
1098 * format might be updated for each command in future.
1099 *
1100 * Schema:
1101 *
1102 * "output_version": {
1103 * "command": string,
1104 * "vers_major": integer,
1105 * "vers_minor": integer,
1106 * }
1107 */
1108 static nvlist_t *
zpool_json_schema(int maj_v,int min_v)1109 zpool_json_schema(int maj_v, int min_v)
1110 {
1111 char cmd[MAX_CMD_LEN];
1112 nvlist_t *sch = fnvlist_alloc();
1113 nvlist_t *ov = fnvlist_alloc();
1114
1115 (void) snprintf(cmd, MAX_CMD_LEN, "zpool %s", current_command->name);
1116 fnvlist_add_string(ov, "command", cmd);
1117 fnvlist_add_uint32(ov, "vers_major", maj_v);
1118 fnvlist_add_uint32(ov, "vers_minor", min_v);
1119 fnvlist_add_nvlist(sch, "output_version", ov);
1120 fnvlist_free(ov);
1121 return (sch);
1122 }
1123
1124 static void
fill_pool_info(nvlist_t * list,zpool_handle_t * zhp,boolean_t addtype,boolean_t as_int)1125 fill_pool_info(nvlist_t *list, zpool_handle_t *zhp, boolean_t addtype,
1126 boolean_t as_int)
1127 {
1128 nvlist_t *config = zpool_get_config(zhp, NULL);
1129 uint64_t guid = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID);
1130 uint64_t txg = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG);
1131
1132 fnvlist_add_string(list, "name", zpool_get_name(zhp));
1133 if (addtype)
1134 fnvlist_add_string(list, "type", "POOL");
1135 fnvlist_add_string(list, "state", zpool_get_state_str(zhp));
1136 if (as_int) {
1137 if (guid)
1138 fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_GUID, guid);
1139 if (txg)
1140 fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_TXG, txg);
1141 fnvlist_add_uint64(list, "spa_version", SPA_VERSION);
1142 fnvlist_add_uint64(list, "zpl_version", ZPL_VERSION);
1143 } else {
1144 char value[ZFS_MAXPROPLEN];
1145 if (guid) {
1146 (void) snprintf(value, ZFS_MAXPROPLEN, "%llu",
1147 (u_longlong_t)guid);
1148 fnvlist_add_string(list, ZPOOL_CONFIG_POOL_GUID, value);
1149 }
1150 if (txg) {
1151 (void) snprintf(value, ZFS_MAXPROPLEN, "%llu",
1152 (u_longlong_t)txg);
1153 fnvlist_add_string(list, ZPOOL_CONFIG_POOL_TXG, value);
1154 }
1155 fnvlist_add_string(list, "spa_version", SPA_VERSION_STRING);
1156 fnvlist_add_string(list, "zpl_version", ZPL_VERSION_STRING);
1157 }
1158 }
1159
1160 static void
used_by_other(zpool_handle_t * zhp,nvlist_t * nvdev,nvlist_t * list)1161 used_by_other(zpool_handle_t *zhp, nvlist_t *nvdev, nvlist_t *list)
1162 {
1163 spare_cbdata_t spare_cb;
1164 verify(nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID,
1165 &spare_cb.cb_guid) == 0);
1166 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1167 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1168 zpool_get_name(zhp)) != 0) {
1169 fnvlist_add_string(list, "used_by",
1170 zpool_get_name(spare_cb.cb_zhp));
1171 }
1172 zpool_close(spare_cb.cb_zhp);
1173 }
1174 }
1175
1176 static void
fill_vdev_info(nvlist_t * list,zpool_handle_t * zhp,char * name,boolean_t addtype,boolean_t as_int)1177 fill_vdev_info(nvlist_t *list, zpool_handle_t *zhp, char *name,
1178 boolean_t addtype, boolean_t as_int)
1179 {
1180 boolean_t l2c = B_FALSE;
1181 const char *path, *phys, *devid, *bias = NULL;
1182 uint64_t hole = 0, log = 0, spare = 0;
1183 vdev_stat_t *vs;
1184 uint_t c;
1185 nvlist_t *nvdev;
1186 nvlist_t *nvdev_parent = NULL;
1187 char *_name;
1188
1189 if (strcmp(name, zpool_get_name(zhp)) != 0)
1190 _name = name;
1191 else
1192 _name = (char *)"root-0";
1193
1194 nvdev = zpool_find_vdev(zhp, _name, NULL, &l2c, NULL);
1195
1196 fnvlist_add_string(list, "name", name);
1197 if (addtype)
1198 fnvlist_add_string(list, "type", "VDEV");
1199 if (nvdev) {
1200 const char *type = fnvlist_lookup_string(nvdev,
1201 ZPOOL_CONFIG_TYPE);
1202 if (type)
1203 fnvlist_add_string(list, "vdev_type", type);
1204 uint64_t guid = fnvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID);
1205 if (guid) {
1206 if (as_int) {
1207 fnvlist_add_uint64(list, "guid", guid);
1208 } else {
1209 char buf[ZFS_MAXPROPLEN];
1210 (void) snprintf(buf, ZFS_MAXPROPLEN, "%llu",
1211 (u_longlong_t)guid);
1212 fnvlist_add_string(list, "guid", buf);
1213 }
1214 }
1215 if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PATH, &path) == 0)
1216 fnvlist_add_string(list, "path", path);
1217 if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PHYS_PATH,
1218 &phys) == 0)
1219 fnvlist_add_string(list, "phys_path", phys);
1220 if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_DEVID,
1221 &devid) == 0)
1222 fnvlist_add_string(list, "devid", devid);
1223 (void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_LOG, &log);
1224 (void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_SPARE,
1225 &spare);
1226 (void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_HOLE, &hole);
1227 if (hole)
1228 fnvlist_add_string(list, "class", VDEV_TYPE_HOLE);
1229 else if (l2c)
1230 fnvlist_add_string(list, "class", VDEV_TYPE_L2CACHE);
1231 else if (spare)
1232 fnvlist_add_string(list, "class", VDEV_TYPE_SPARE);
1233 else if (log)
1234 fnvlist_add_string(list, "class", VDEV_TYPE_LOG);
1235 else {
1236 (void) nvlist_lookup_string(nvdev,
1237 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
1238 if (bias != NULL)
1239 fnvlist_add_string(list, "class", bias);
1240 else {
1241 nvdev_parent = NULL;
1242 nvdev_parent = zpool_find_parent_vdev(zhp,
1243 _name, NULL, NULL, NULL);
1244
1245 /*
1246 * With a mirrored special device, the parent
1247 * "mirror" vdev will have
1248 * ZPOOL_CONFIG_ALLOCATION_BIAS set to "special"
1249 * not the leaf vdevs. If we're a leaf vdev
1250 * in that case we need to look at our parent
1251 * to see if they're "special" to know if we
1252 * are "special" too.
1253 */
1254 if (nvdev_parent) {
1255 (void) nvlist_lookup_string(
1256 nvdev_parent,
1257 ZPOOL_CONFIG_ALLOCATION_BIAS,
1258 &bias);
1259 }
1260 if (bias != NULL)
1261 fnvlist_add_string(list, "class", bias);
1262 else
1263 fnvlist_add_string(list, "class",
1264 "normal");
1265 }
1266 }
1267 if (nvlist_lookup_uint64_array(nvdev, ZPOOL_CONFIG_VDEV_STATS,
1268 (uint64_t **)&vs, &c) == 0) {
1269 fnvlist_add_string(list, "state",
1270 vdev_state_str[vs->vs_state]);
1271 }
1272 }
1273 }
1274
1275 static boolean_t
prop_list_contains_feature(nvlist_t * proplist)1276 prop_list_contains_feature(nvlist_t *proplist)
1277 {
1278 nvpair_t *nvp;
1279 for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
1280 nvp = nvlist_next_nvpair(proplist, nvp)) {
1281 if (zpool_prop_feature(nvpair_name(nvp)))
1282 return (B_TRUE);
1283 }
1284 return (B_FALSE);
1285 }
1286
1287 /*
1288 * Add a property pair (name, string-value) into a property nvlist.
1289 */
1290 static int
add_prop_list(const char * propname,const char * propval,nvlist_t ** props,boolean_t poolprop)1291 add_prop_list(const char *propname, const char *propval, nvlist_t **props,
1292 boolean_t poolprop)
1293 {
1294 zpool_prop_t prop = ZPOOL_PROP_INVAL;
1295 nvlist_t *proplist;
1296 const char *normnm;
1297 const char *strval;
1298
1299 if (*props == NULL &&
1300 nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
1301 (void) fprintf(stderr,
1302 gettext("internal error: out of memory\n"));
1303 return (1);
1304 }
1305
1306 proplist = *props;
1307
1308 if (poolprop) {
1309 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
1310 const char *cname =
1311 zpool_prop_to_name(ZPOOL_PROP_COMPATIBILITY);
1312
1313 if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
1314 (!zpool_prop_feature(propname) &&
1315 !zpool_prop_vdev(propname))) {
1316 (void) fprintf(stderr, gettext("property '%s' is "
1317 "not a valid pool or vdev property\n"), propname);
1318 return (2);
1319 }
1320
1321 /*
1322 * feature@ properties and version should not be specified
1323 * at the same time.
1324 */
1325 if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
1326 nvlist_exists(proplist, vname)) ||
1327 (prop == ZPOOL_PROP_VERSION &&
1328 prop_list_contains_feature(proplist))) {
1329 (void) fprintf(stderr, gettext("'feature@' and "
1330 "'version' properties cannot be specified "
1331 "together\n"));
1332 return (2);
1333 }
1334
1335 /*
1336 * if version is specified, only "legacy" compatibility
1337 * may be requested
1338 */
1339 if ((prop == ZPOOL_PROP_COMPATIBILITY &&
1340 strcmp(propval, ZPOOL_COMPAT_LEGACY) != 0 &&
1341 nvlist_exists(proplist, vname)) ||
1342 (prop == ZPOOL_PROP_VERSION &&
1343 nvlist_exists(proplist, cname) &&
1344 strcmp(fnvlist_lookup_string(proplist, cname),
1345 ZPOOL_COMPAT_LEGACY) != 0)) {
1346 (void) fprintf(stderr, gettext("when 'version' is "
1347 "specified, the 'compatibility' feature may only "
1348 "be set to '" ZPOOL_COMPAT_LEGACY "'\n"));
1349 return (2);
1350 }
1351
1352 if (zpool_prop_feature(propname) || zpool_prop_vdev(propname))
1353 normnm = propname;
1354 else
1355 normnm = zpool_prop_to_name(prop);
1356 } else {
1357 zfs_prop_t fsprop = zfs_name_to_prop(propname);
1358
1359 if (zfs_prop_valid_for_type(fsprop, ZFS_TYPE_FILESYSTEM,
1360 B_FALSE)) {
1361 normnm = zfs_prop_to_name(fsprop);
1362 } else if (zfs_prop_user(propname) ||
1363 zfs_prop_userquota(propname)) {
1364 normnm = propname;
1365 } else {
1366 (void) fprintf(stderr, gettext("property '%s' is "
1367 "not a valid filesystem property\n"), propname);
1368 return (2);
1369 }
1370 }
1371
1372 if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
1373 prop != ZPOOL_PROP_CACHEFILE) {
1374 (void) fprintf(stderr, gettext("property '%s' "
1375 "specified multiple times\n"), propname);
1376 return (2);
1377 }
1378
1379 if (nvlist_add_string(proplist, normnm, propval) != 0) {
1380 (void) fprintf(stderr, gettext("internal "
1381 "error: out of memory\n"));
1382 return (1);
1383 }
1384
1385 return (0);
1386 }
1387
1388 /*
1389 * Set a default property pair (name, string-value) in a property nvlist
1390 */
1391 static int
add_prop_list_default(const char * propname,const char * propval,nvlist_t ** props)1392 add_prop_list_default(const char *propname, const char *propval,
1393 nvlist_t **props)
1394 {
1395 const char *pval;
1396
1397 if (nvlist_lookup_string(*props, propname, &pval) == 0)
1398 return (0);
1399
1400 return (add_prop_list(propname, propval, props, B_TRUE));
1401 }
1402
1403 /*
1404 * zpool add [-afgLnP] [-o property=value] <pool> <vdev> ...
1405 *
1406 * -a Disable the ashift validation checks
1407 * -f Force addition of devices, even if they appear in use
1408 * -g Display guid for individual vdev name.
1409 * -L Follow links when resolving vdev path name.
1410 * -n Do not add the devices, but display the resulting layout if
1411 * they were to be added.
1412 * -o Set property=value.
1413 * -P Display full path for vdev name.
1414 *
1415 * Adds the given vdevs to 'pool'. As with create, the bulk of this work is
1416 * handled by make_root_vdev(), which constructs the nvlist needed to pass to
1417 * libzfs.
1418 */
1419 int
zpool_do_add(int argc,char ** argv)1420 zpool_do_add(int argc, char **argv)
1421 {
1422 boolean_t check_replication = B_TRUE;
1423 boolean_t check_inuse = B_TRUE;
1424 boolean_t dryrun = B_FALSE;
1425 boolean_t check_ashift = B_TRUE;
1426 boolean_t force = B_FALSE;
1427 int name_flags = 0;
1428 int c;
1429 nvlist_t *nvroot;
1430 char *poolname;
1431 int ret;
1432 zpool_handle_t *zhp;
1433 nvlist_t *config;
1434 nvlist_t *props = NULL;
1435 char *propval;
1436
1437 struct option long_options[] = {
1438 {"allow-in-use", no_argument, NULL, ZPOOL_OPTION_ALLOW_INUSE},
1439 {"allow-replication-mismatch", no_argument, NULL,
1440 ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH},
1441 {"allow-ashift-mismatch", no_argument, NULL,
1442 ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH},
1443 {0, 0, 0, 0}
1444 };
1445
1446 /* check options */
1447 while ((c = getopt_long(argc, argv, "fgLno:P", long_options, NULL))
1448 != -1) {
1449 switch (c) {
1450 case 'f':
1451 force = B_TRUE;
1452 break;
1453 case 'g':
1454 name_flags |= VDEV_NAME_GUID;
1455 break;
1456 case 'L':
1457 name_flags |= VDEV_NAME_FOLLOW_LINKS;
1458 break;
1459 case 'n':
1460 dryrun = B_TRUE;
1461 break;
1462 case 'o':
1463 if ((propval = strchr(optarg, '=')) == NULL) {
1464 (void) fprintf(stderr, gettext("missing "
1465 "'=' for -o option\n"));
1466 usage(B_FALSE);
1467 }
1468 *propval = '\0';
1469 propval++;
1470
1471 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
1472 (add_prop_list(optarg, propval, &props, B_TRUE)))
1473 usage(B_FALSE);
1474 break;
1475 case 'P':
1476 name_flags |= VDEV_NAME_PATH;
1477 break;
1478 case ZPOOL_OPTION_ALLOW_INUSE:
1479 check_inuse = B_FALSE;
1480 break;
1481 case ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH:
1482 check_replication = B_FALSE;
1483 break;
1484 case ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH:
1485 check_ashift = B_FALSE;
1486 break;
1487 case '?':
1488 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1489 optopt);
1490 usage(B_FALSE);
1491 }
1492 }
1493
1494 argc -= optind;
1495 argv += optind;
1496
1497 /* get pool name and check number of arguments */
1498 if (argc < 1) {
1499 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1500 usage(B_FALSE);
1501 }
1502 if (argc < 2) {
1503 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1504 usage(B_FALSE);
1505 }
1506
1507 if (force) {
1508 if (!check_inuse || !check_replication || !check_ashift) {
1509 (void) fprintf(stderr, gettext("'-f' option is not "
1510 "allowed with '--allow-replication-mismatch', "
1511 "'--allow-ashift-mismatch', or "
1512 "'--allow-in-use'\n"));
1513 usage(B_FALSE);
1514 }
1515 check_inuse = B_FALSE;
1516 check_replication = B_FALSE;
1517 check_ashift = B_FALSE;
1518 }
1519
1520 poolname = argv[0];
1521
1522 argc--;
1523 argv++;
1524
1525 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1526 return (1);
1527
1528 if ((config = zpool_get_config(zhp, NULL)) == NULL) {
1529 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
1530 poolname);
1531 zpool_close(zhp);
1532 return (1);
1533 }
1534
1535 /* unless manually specified use "ashift" pool property (if set) */
1536 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
1537 int intval;
1538 zprop_source_t src;
1539 char strval[ZPOOL_MAXPROPLEN];
1540
1541 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
1542 if (src != ZPROP_SRC_DEFAULT) {
1543 (void) sprintf(strval, "%" PRId32, intval);
1544 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
1545 &props, B_TRUE) == 0);
1546 }
1547 }
1548
1549 /* pass off to make_root_vdev for processing */
1550 nvroot = make_root_vdev(zhp, props, !check_inuse,
1551 check_replication, B_FALSE, dryrun, argc, argv);
1552 if (nvroot == NULL) {
1553 zpool_close(zhp);
1554 return (1);
1555 }
1556
1557 if (dryrun) {
1558 nvlist_t *poolnvroot;
1559 nvlist_t **l2child, **sparechild;
1560 uint_t l2children, sparechildren, c;
1561 char *vname;
1562 boolean_t hadcache = B_FALSE, hadspare = B_FALSE;
1563
1564 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1565 &poolnvroot) == 0);
1566
1567 (void) printf(gettext("would update '%s' to the following "
1568 "configuration:\n\n"), zpool_get_name(zhp));
1569
1570 /* print original main pool and new tree */
1571 print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
1572 name_flags | VDEV_NAME_TYPE_ID);
1573 print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
1574
1575 /* print other classes: 'dedup', 'special', and 'log' */
1576 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1577 print_vdev_tree(zhp, "dedup", poolnvroot, 0,
1578 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1579 print_vdev_tree(zhp, NULL, nvroot, 0,
1580 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1581 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1582 print_vdev_tree(zhp, "dedup", nvroot, 0,
1583 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1584 }
1585
1586 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1587 print_vdev_tree(zhp, "special", poolnvroot, 0,
1588 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1589 print_vdev_tree(zhp, NULL, nvroot, 0,
1590 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1591 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1592 print_vdev_tree(zhp, "special", nvroot, 0,
1593 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1594 }
1595
1596 if (num_logs(poolnvroot) > 0) {
1597 print_vdev_tree(zhp, "logs", poolnvroot, 0,
1598 VDEV_ALLOC_BIAS_LOG, name_flags);
1599 print_vdev_tree(zhp, NULL, nvroot, 0,
1600 VDEV_ALLOC_BIAS_LOG, name_flags);
1601 } else if (num_logs(nvroot) > 0) {
1602 print_vdev_tree(zhp, "logs", nvroot, 0,
1603 VDEV_ALLOC_BIAS_LOG, name_flags);
1604 }
1605
1606 /* Do the same for the caches */
1607 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
1608 &l2child, &l2children) == 0 && l2children) {
1609 hadcache = B_TRUE;
1610 (void) printf(gettext("\tcache\n"));
1611 for (c = 0; c < l2children; c++) {
1612 vname = zpool_vdev_name(g_zfs, NULL,
1613 l2child[c], name_flags);
1614 (void) printf("\t %s\n", vname);
1615 free(vname);
1616 }
1617 }
1618 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1619 &l2child, &l2children) == 0 && l2children) {
1620 if (!hadcache)
1621 (void) printf(gettext("\tcache\n"));
1622 for (c = 0; c < l2children; c++) {
1623 vname = zpool_vdev_name(g_zfs, NULL,
1624 l2child[c], name_flags);
1625 (void) printf("\t %s\n", vname);
1626 free(vname);
1627 }
1628 }
1629 /* And finally the spares */
1630 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_SPARES,
1631 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1632 hadspare = B_TRUE;
1633 (void) printf(gettext("\tspares\n"));
1634 for (c = 0; c < sparechildren; c++) {
1635 vname = zpool_vdev_name(g_zfs, NULL,
1636 sparechild[c], name_flags);
1637 (void) printf("\t %s\n", vname);
1638 free(vname);
1639 }
1640 }
1641 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1642 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1643 if (!hadspare)
1644 (void) printf(gettext("\tspares\n"));
1645 for (c = 0; c < sparechildren; c++) {
1646 vname = zpool_vdev_name(g_zfs, NULL,
1647 sparechild[c], name_flags);
1648 (void) printf("\t %s\n", vname);
1649 free(vname);
1650 }
1651 }
1652
1653 ret = 0;
1654 } else {
1655 ret = (zpool_add(zhp, nvroot, check_ashift) != 0);
1656 }
1657
1658 nvlist_free(props);
1659 nvlist_free(nvroot);
1660 zpool_close(zhp);
1661
1662 return (ret);
1663 }
1664
1665 /*
1666 * zpool remove [-npsw] <pool> <vdev> ...
1667 *
1668 * Removes the given vdev from the pool.
1669 */
1670 int
zpool_do_remove(int argc,char ** argv)1671 zpool_do_remove(int argc, char **argv)
1672 {
1673 char *poolname;
1674 int i, ret = 0;
1675 zpool_handle_t *zhp = NULL;
1676 boolean_t stop = B_FALSE;
1677 int c;
1678 boolean_t noop = B_FALSE;
1679 boolean_t parsable = B_FALSE;
1680 boolean_t wait = B_FALSE;
1681
1682 /* check options */
1683 while ((c = getopt(argc, argv, "npsw")) != -1) {
1684 switch (c) {
1685 case 'n':
1686 noop = B_TRUE;
1687 break;
1688 case 'p':
1689 parsable = B_TRUE;
1690 break;
1691 case 's':
1692 stop = B_TRUE;
1693 break;
1694 case 'w':
1695 wait = B_TRUE;
1696 break;
1697 case '?':
1698 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1699 optopt);
1700 usage(B_FALSE);
1701 }
1702 }
1703
1704 argc -= optind;
1705 argv += optind;
1706
1707 /* get pool name and check number of arguments */
1708 if (argc < 1) {
1709 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1710 usage(B_FALSE);
1711 }
1712
1713 poolname = argv[0];
1714
1715 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1716 return (1);
1717
1718 if (stop && noop) {
1719 zpool_close(zhp);
1720 (void) fprintf(stderr, gettext("stop request ignored\n"));
1721 return (0);
1722 }
1723
1724 if (stop) {
1725 if (argc > 1) {
1726 (void) fprintf(stderr, gettext("too many arguments\n"));
1727 usage(B_FALSE);
1728 }
1729 if (zpool_vdev_remove_cancel(zhp) != 0)
1730 ret = 1;
1731 if (wait) {
1732 (void) fprintf(stderr, gettext("invalid option "
1733 "combination: -w cannot be used with -s\n"));
1734 usage(B_FALSE);
1735 }
1736 } else {
1737 if (argc < 2) {
1738 (void) fprintf(stderr, gettext("missing device\n"));
1739 usage(B_FALSE);
1740 }
1741
1742 for (i = 1; i < argc; i++) {
1743 if (noop) {
1744 uint64_t size;
1745
1746 if (zpool_vdev_indirect_size(zhp, argv[i],
1747 &size) != 0) {
1748 ret = 1;
1749 break;
1750 }
1751 if (parsable) {
1752 (void) printf("%s %llu\n",
1753 argv[i], (unsigned long long)size);
1754 } else {
1755 char valstr[32];
1756 zfs_nicenum(size, valstr,
1757 sizeof (valstr));
1758 (void) printf("Memory that will be "
1759 "used after removing %s: %s\n",
1760 argv[i], valstr);
1761 }
1762 } else {
1763 if (zpool_vdev_remove(zhp, argv[i]) != 0)
1764 ret = 1;
1765 }
1766 }
1767
1768 if (ret == 0 && wait)
1769 ret = zpool_wait(zhp, ZPOOL_WAIT_REMOVE);
1770 }
1771 zpool_close(zhp);
1772
1773 return (ret);
1774 }
1775
1776 /*
1777 * Return 1 if a vdev is active (being used in a pool)
1778 * Return 0 if a vdev is inactive (offlined or faulted, or not in active pool)
1779 *
1780 * This is useful for checking if a disk in an active pool is offlined or
1781 * faulted.
1782 */
1783 static int
vdev_is_active(char * vdev_path)1784 vdev_is_active(char *vdev_path)
1785 {
1786 int fd;
1787 fd = open(vdev_path, O_EXCL);
1788 if (fd < 0) {
1789 return (1); /* cant open O_EXCL - disk is active */
1790 }
1791
1792 (void) close(fd);
1793 return (0); /* disk is inactive in the pool */
1794 }
1795
1796 /*
1797 * zpool labelclear [-f] <vdev>
1798 *
1799 * -f Force clearing the label for the vdevs which are members of
1800 * the exported or foreign pools.
1801 *
1802 * Verifies that the vdev is not active and zeros out the label information
1803 * on the device.
1804 */
1805 int
zpool_do_labelclear(int argc,char ** argv)1806 zpool_do_labelclear(int argc, char **argv)
1807 {
1808 char vdev[MAXPATHLEN];
1809 char *name = NULL;
1810 int c, fd, ret = 0;
1811 nvlist_t *config;
1812 pool_state_t state;
1813 boolean_t inuse = B_FALSE;
1814 boolean_t force = B_FALSE;
1815
1816 /* check options */
1817 while ((c = getopt(argc, argv, "f")) != -1) {
1818 switch (c) {
1819 case 'f':
1820 force = B_TRUE;
1821 break;
1822 default:
1823 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1824 optopt);
1825 usage(B_FALSE);
1826 }
1827 }
1828
1829 argc -= optind;
1830 argv += optind;
1831
1832 /* get vdev name */
1833 if (argc < 1) {
1834 (void) fprintf(stderr, gettext("missing vdev name\n"));
1835 usage(B_FALSE);
1836 }
1837 if (argc > 1) {
1838 (void) fprintf(stderr, gettext("too many arguments\n"));
1839 usage(B_FALSE);
1840 }
1841
1842 (void) strlcpy(vdev, argv[0], sizeof (vdev));
1843
1844 /*
1845 * If we cannot open an absolute path, we quit.
1846 * Otherwise if the provided vdev name doesn't point to a file,
1847 * try prepending expected disk paths and partition numbers.
1848 */
1849 if ((fd = open(vdev, O_RDWR)) < 0) {
1850 int error;
1851 if (vdev[0] == '/') {
1852 (void) fprintf(stderr, gettext("failed to open "
1853 "%s: %s\n"), vdev, strerror(errno));
1854 return (1);
1855 }
1856
1857 error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
1858 if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
1859 if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
1860 error = ENOENT;
1861 }
1862
1863 if (error || ((fd = open(vdev, O_RDWR)) < 0)) {
1864 if (errno == ENOENT) {
1865 (void) fprintf(stderr, gettext(
1866 "failed to find device %s, try "
1867 "specifying absolute path instead\n"),
1868 argv[0]);
1869 return (1);
1870 }
1871
1872 (void) fprintf(stderr, gettext("failed to open %s:"
1873 " %s\n"), vdev, strerror(errno));
1874 return (1);
1875 }
1876 }
1877
1878 /*
1879 * Flush all dirty pages for the block device. This should not be
1880 * fatal when the device does not support BLKFLSBUF as would be the
1881 * case for a file vdev.
1882 */
1883 if ((zfs_dev_flush(fd) != 0) && (errno != ENOTTY))
1884 (void) fprintf(stderr, gettext("failed to invalidate "
1885 "cache for %s: %s\n"), vdev, strerror(errno));
1886
1887 if (zpool_read_label(fd, &config, NULL) != 0) {
1888 (void) fprintf(stderr,
1889 gettext("failed to read label from %s\n"), vdev);
1890 ret = 1;
1891 goto errout;
1892 }
1893 nvlist_free(config);
1894
1895 ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1896 if (ret != 0) {
1897 (void) fprintf(stderr,
1898 gettext("failed to check state for %s\n"), vdev);
1899 ret = 1;
1900 goto errout;
1901 }
1902
1903 if (!inuse)
1904 goto wipe_label;
1905
1906 switch (state) {
1907 default:
1908 case POOL_STATE_ACTIVE:
1909 case POOL_STATE_SPARE:
1910 case POOL_STATE_L2CACHE:
1911 /*
1912 * We allow the user to call 'zpool offline -f'
1913 * on an offlined disk in an active pool. We can check if
1914 * the disk is online by calling vdev_is_active().
1915 */
1916 if (force && !vdev_is_active(vdev))
1917 break;
1918
1919 (void) fprintf(stderr, gettext(
1920 "%s is a member (%s) of pool \"%s\""),
1921 vdev, zpool_pool_state_to_name(state), name);
1922
1923 if (force) {
1924 (void) fprintf(stderr, gettext(
1925 ". Offline the disk first to clear its label."));
1926 }
1927 printf("\n");
1928 ret = 1;
1929 goto errout;
1930
1931 case POOL_STATE_EXPORTED:
1932 if (force)
1933 break;
1934 (void) fprintf(stderr, gettext(
1935 "use '-f' to override the following error:\n"
1936 "%s is a member of exported pool \"%s\"\n"),
1937 vdev, name);
1938 ret = 1;
1939 goto errout;
1940
1941 case POOL_STATE_POTENTIALLY_ACTIVE:
1942 if (force)
1943 break;
1944 (void) fprintf(stderr, gettext(
1945 "use '-f' to override the following error:\n"
1946 "%s is a member of potentially active pool \"%s\"\n"),
1947 vdev, name);
1948 ret = 1;
1949 goto errout;
1950
1951 case POOL_STATE_DESTROYED:
1952 /* inuse should never be set for a destroyed pool */
1953 assert(0);
1954 break;
1955 }
1956
1957 wipe_label:
1958 ret = zpool_clear_label(fd);
1959 if (ret != 0) {
1960 (void) fprintf(stderr,
1961 gettext("failed to clear label for %s\n"), vdev);
1962 }
1963
1964 errout:
1965 free(name);
1966 (void) close(fd);
1967
1968 return (ret);
1969 }
1970
1971 /*
1972 * zpool create [-fnd] [-o property=value] ...
1973 * [-O file-system-property=value] ...
1974 * [-R root] [-m mountpoint] <pool> <dev> ...
1975 *
1976 * -f Force creation, even if devices appear in use
1977 * -n Do not create the pool, but display the resulting layout if it
1978 * were to be created.
1979 * -R Create a pool under an alternate root
1980 * -m Set default mountpoint for the root dataset. By default it's
1981 * '/<pool>'
1982 * -o Set property=value.
1983 * -o Set feature@feature=enabled|disabled.
1984 * -d Don't automatically enable all supported pool features
1985 * (individual features can be enabled with -o).
1986 * -O Set fsproperty=value in the pool's root file system
1987 *
1988 * Creates the named pool according to the given vdev specification. The
1989 * bulk of the vdev processing is done in make_root_vdev() in zpool_vdev.c.
1990 * Once we get the nvlist back from make_root_vdev(), we either print out the
1991 * contents (if '-n' was specified), or pass it to libzfs to do the creation.
1992 */
1993 int
zpool_do_create(int argc,char ** argv)1994 zpool_do_create(int argc, char **argv)
1995 {
1996 boolean_t force = B_FALSE;
1997 boolean_t dryrun = B_FALSE;
1998 boolean_t enable_pool_features = B_TRUE;
1999
2000 int c;
2001 nvlist_t *nvroot = NULL;
2002 char *poolname;
2003 char *tname = NULL;
2004 int ret = 1;
2005 char *altroot = NULL;
2006 char *compat = NULL;
2007 char *mountpoint = NULL;
2008 nvlist_t *fsprops = NULL;
2009 nvlist_t *props = NULL;
2010 char *propval;
2011
2012 /* check options */
2013 while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
2014 switch (c) {
2015 case 'f':
2016 force = B_TRUE;
2017 break;
2018 case 'n':
2019 dryrun = B_TRUE;
2020 break;
2021 case 'd':
2022 enable_pool_features = B_FALSE;
2023 break;
2024 case 'R':
2025 altroot = optarg;
2026 if (add_prop_list(zpool_prop_to_name(
2027 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
2028 goto errout;
2029 if (add_prop_list_default(zpool_prop_to_name(
2030 ZPOOL_PROP_CACHEFILE), "none", &props))
2031 goto errout;
2032 break;
2033 case 'm':
2034 /* Equivalent to -O mountpoint=optarg */
2035 mountpoint = optarg;
2036 break;
2037 case 'o':
2038 if ((propval = strchr(optarg, '=')) == NULL) {
2039 (void) fprintf(stderr, gettext("missing "
2040 "'=' for -o option\n"));
2041 goto errout;
2042 }
2043 *propval = '\0';
2044 propval++;
2045
2046 if (add_prop_list(optarg, propval, &props, B_TRUE))
2047 goto errout;
2048
2049 /*
2050 * If the user is creating a pool that doesn't support
2051 * feature flags, don't enable any features.
2052 */
2053 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
2054 char *end;
2055 u_longlong_t ver;
2056
2057 ver = strtoull(propval, &end, 0);
2058 if (*end == '\0' &&
2059 ver < SPA_VERSION_FEATURES) {
2060 enable_pool_features = B_FALSE;
2061 }
2062 }
2063 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
2064 altroot = propval;
2065 if (zpool_name_to_prop(optarg) ==
2066 ZPOOL_PROP_COMPATIBILITY)
2067 compat = propval;
2068 break;
2069 case 'O':
2070 if ((propval = strchr(optarg, '=')) == NULL) {
2071 (void) fprintf(stderr, gettext("missing "
2072 "'=' for -O option\n"));
2073 goto errout;
2074 }
2075 *propval = '\0';
2076 propval++;
2077
2078 /*
2079 * Mountpoints are checked and then added later.
2080 * Uniquely among properties, they can be specified
2081 * more than once, to avoid conflict with -m.
2082 */
2083 if (0 == strcmp(optarg,
2084 zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
2085 mountpoint = propval;
2086 } else if (add_prop_list(optarg, propval, &fsprops,
2087 B_FALSE)) {
2088 goto errout;
2089 }
2090 break;
2091 case 't':
2092 /*
2093 * Sanity check temporary pool name.
2094 */
2095 if (strchr(optarg, '/') != NULL) {
2096 (void) fprintf(stderr, gettext("cannot create "
2097 "'%s': invalid character '/' in temporary "
2098 "name\n"), optarg);
2099 (void) fprintf(stderr, gettext("use 'zfs "
2100 "create' to create a dataset\n"));
2101 goto errout;
2102 }
2103
2104 if (add_prop_list(zpool_prop_to_name(
2105 ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
2106 goto errout;
2107 if (add_prop_list_default(zpool_prop_to_name(
2108 ZPOOL_PROP_CACHEFILE), "none", &props))
2109 goto errout;
2110 tname = optarg;
2111 break;
2112 case ':':
2113 (void) fprintf(stderr, gettext("missing argument for "
2114 "'%c' option\n"), optopt);
2115 goto badusage;
2116 case '?':
2117 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2118 optopt);
2119 goto badusage;
2120 }
2121 }
2122
2123 argc -= optind;
2124 argv += optind;
2125
2126 /* get pool name and check number of arguments */
2127 if (argc < 1) {
2128 (void) fprintf(stderr, gettext("missing pool name argument\n"));
2129 goto badusage;
2130 }
2131 if (argc < 2) {
2132 (void) fprintf(stderr, gettext("missing vdev specification\n"));
2133 goto badusage;
2134 }
2135
2136 poolname = argv[0];
2137
2138 /*
2139 * As a special case, check for use of '/' in the name, and direct the
2140 * user to use 'zfs create' instead.
2141 */
2142 if (strchr(poolname, '/') != NULL) {
2143 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
2144 "character '/' in pool name\n"), poolname);
2145 (void) fprintf(stderr, gettext("use 'zfs create' to "
2146 "create a dataset\n"));
2147 goto errout;
2148 }
2149
2150 /* pass off to make_root_vdev for bulk processing */
2151 nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
2152 argc - 1, argv + 1);
2153 if (nvroot == NULL)
2154 goto errout;
2155
2156 /* make_root_vdev() allows 0 toplevel children if there are spares */
2157 if (!zfs_allocatable_devs(nvroot)) {
2158 (void) fprintf(stderr, gettext("invalid vdev "
2159 "specification: at least one toplevel vdev must be "
2160 "specified\n"));
2161 goto errout;
2162 }
2163
2164 if (altroot != NULL && altroot[0] != '/') {
2165 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
2166 "must be an absolute path\n"), altroot);
2167 goto errout;
2168 }
2169
2170 /*
2171 * Check the validity of the mountpoint and direct the user to use the
2172 * '-m' mountpoint option if it looks like its in use.
2173 */
2174 if (mountpoint == NULL ||
2175 (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
2176 strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
2177 char buf[MAXPATHLEN];
2178 DIR *dirp;
2179
2180 if (mountpoint && mountpoint[0] != '/') {
2181 (void) fprintf(stderr, gettext("invalid mountpoint "
2182 "'%s': must be an absolute path, 'legacy', or "
2183 "'none'\n"), mountpoint);
2184 goto errout;
2185 }
2186
2187 if (mountpoint == NULL) {
2188 if (altroot != NULL)
2189 (void) snprintf(buf, sizeof (buf), "%s/%s",
2190 altroot, poolname);
2191 else
2192 (void) snprintf(buf, sizeof (buf), "/%s",
2193 poolname);
2194 } else {
2195 if (altroot != NULL)
2196 (void) snprintf(buf, sizeof (buf), "%s%s",
2197 altroot, mountpoint);
2198 else
2199 (void) snprintf(buf, sizeof (buf), "%s",
2200 mountpoint);
2201 }
2202
2203 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
2204 (void) fprintf(stderr, gettext("mountpoint '%s' : "
2205 "%s\n"), buf, strerror(errno));
2206 (void) fprintf(stderr, gettext("use '-m' "
2207 "option to provide a different default\n"));
2208 goto errout;
2209 } else if (dirp) {
2210 int count = 0;
2211
2212 while (count < 3 && readdir(dirp) != NULL)
2213 count++;
2214 (void) closedir(dirp);
2215
2216 if (count > 2) {
2217 (void) fprintf(stderr, gettext("mountpoint "
2218 "'%s' exists and is not empty\n"), buf);
2219 (void) fprintf(stderr, gettext("use '-m' "
2220 "option to provide a "
2221 "different default\n"));
2222 goto errout;
2223 }
2224 }
2225 }
2226
2227 /*
2228 * Now that the mountpoint's validity has been checked, ensure that
2229 * the property is set appropriately prior to creating the pool.
2230 */
2231 if (mountpoint != NULL) {
2232 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
2233 mountpoint, &fsprops, B_FALSE);
2234 if (ret != 0)
2235 goto errout;
2236 }
2237
2238 ret = 1;
2239 if (dryrun) {
2240 /*
2241 * For a dry run invocation, print out a basic message and run
2242 * through all the vdevs in the list and print out in an
2243 * appropriate hierarchy.
2244 */
2245 (void) printf(gettext("would create '%s' with the "
2246 "following layout:\n\n"), poolname);
2247
2248 print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
2249 print_vdev_tree(NULL, "dedup", nvroot, 0,
2250 VDEV_ALLOC_BIAS_DEDUP, 0);
2251 print_vdev_tree(NULL, "special", nvroot, 0,
2252 VDEV_ALLOC_BIAS_SPECIAL, 0);
2253 print_vdev_tree(NULL, "logs", nvroot, 0,
2254 VDEV_ALLOC_BIAS_LOG, 0);
2255 print_cache_list(nvroot, 0);
2256 print_spare_list(nvroot, 0);
2257
2258 ret = 0;
2259 } else {
2260 /*
2261 * Load in feature set.
2262 * Note: if compatibility property not given, we'll have
2263 * NULL, which means 'all features'.
2264 */
2265 boolean_t requested_features[SPA_FEATURES];
2266 if (zpool_do_load_compat(compat, requested_features) !=
2267 ZPOOL_COMPATIBILITY_OK)
2268 goto errout;
2269
2270 /*
2271 * props contains list of features to enable.
2272 * For each feature:
2273 * - remove it if feature@name=disabled
2274 * - leave it there if feature@name=enabled
2275 * - add it if:
2276 * - enable_pool_features (ie: no '-d' or '-o version')
2277 * - it's supported by the kernel module
2278 * - it's in the requested feature set
2279 * - warn if it's enabled but not in compat
2280 */
2281 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
2282 char propname[MAXPATHLEN];
2283 const char *propval;
2284 zfeature_info_t *feat = &spa_feature_table[i];
2285
2286 (void) snprintf(propname, sizeof (propname),
2287 "feature@%s", feat->fi_uname);
2288
2289 if (!nvlist_lookup_string(props, propname, &propval)) {
2290 if (strcmp(propval,
2291 ZFS_FEATURE_DISABLED) == 0) {
2292 (void) nvlist_remove_all(props,
2293 propname);
2294 } else if (strcmp(propval,
2295 ZFS_FEATURE_ENABLED) == 0 &&
2296 !requested_features[i]) {
2297 (void) fprintf(stderr, gettext(
2298 "Warning: feature \"%s\" enabled "
2299 "but is not in specified "
2300 "'compatibility' feature set.\n"),
2301 feat->fi_uname);
2302 }
2303 } else if (
2304 enable_pool_features &&
2305 feat->fi_zfs_mod_supported &&
2306 requested_features[i]) {
2307 ret = add_prop_list(propname,
2308 ZFS_FEATURE_ENABLED, &props, B_TRUE);
2309 if (ret != 0)
2310 goto errout;
2311 }
2312 }
2313
2314 ret = 1;
2315 if (zpool_create(g_zfs, poolname,
2316 nvroot, props, fsprops) == 0) {
2317 zfs_handle_t *pool = zfs_open(g_zfs,
2318 tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
2319 if (pool != NULL) {
2320 if (zfs_mount(pool, NULL, 0) == 0) {
2321 ret = zfs_share(pool, NULL);
2322 zfs_commit_shares(NULL);
2323 }
2324 zfs_close(pool);
2325 }
2326 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
2327 (void) fprintf(stderr, gettext("pool name may have "
2328 "been omitted\n"));
2329 }
2330 }
2331
2332 errout:
2333 nvlist_free(nvroot);
2334 nvlist_free(fsprops);
2335 nvlist_free(props);
2336 return (ret);
2337 badusage:
2338 nvlist_free(fsprops);
2339 nvlist_free(props);
2340 usage(B_FALSE);
2341 return (2);
2342 }
2343
2344 /*
2345 * zpool destroy <pool>
2346 *
2347 * -f Forcefully unmount any datasets
2348 *
2349 * Destroy the given pool. Automatically unmounts any datasets in the pool.
2350 */
2351 int
zpool_do_destroy(int argc,char ** argv)2352 zpool_do_destroy(int argc, char **argv)
2353 {
2354 boolean_t force = B_FALSE;
2355 int c;
2356 char *pool;
2357 zpool_handle_t *zhp;
2358 int ret;
2359
2360 /* check options */
2361 while ((c = getopt(argc, argv, "f")) != -1) {
2362 switch (c) {
2363 case 'f':
2364 force = B_TRUE;
2365 break;
2366 case '?':
2367 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2368 optopt);
2369 usage(B_FALSE);
2370 }
2371 }
2372
2373 argc -= optind;
2374 argv += optind;
2375
2376 /* check arguments */
2377 if (argc < 1) {
2378 (void) fprintf(stderr, gettext("missing pool argument\n"));
2379 usage(B_FALSE);
2380 }
2381 if (argc > 1) {
2382 (void) fprintf(stderr, gettext("too many arguments\n"));
2383 usage(B_FALSE);
2384 }
2385
2386 pool = argv[0];
2387
2388 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
2389 /*
2390 * As a special case, check for use of '/' in the name, and
2391 * direct the user to use 'zfs destroy' instead.
2392 */
2393 if (strchr(pool, '/') != NULL)
2394 (void) fprintf(stderr, gettext("use 'zfs destroy' to "
2395 "destroy a dataset\n"));
2396 return (1);
2397 }
2398
2399 if (zpool_disable_datasets(zhp, force) != 0) {
2400 (void) fprintf(stderr, gettext("could not destroy '%s': "
2401 "could not unmount datasets\n"), zpool_get_name(zhp));
2402 zpool_close(zhp);
2403 return (1);
2404 }
2405
2406 /* The history must be logged as part of the export */
2407 log_history = B_FALSE;
2408
2409 ret = (zpool_destroy(zhp, history_str) != 0);
2410
2411 zpool_close(zhp);
2412
2413 return (ret);
2414 }
2415
2416 typedef struct export_cbdata {
2417 taskq_t *taskq;
2418 pthread_mutex_t mnttab_lock;
2419 boolean_t force;
2420 boolean_t hardforce;
2421 int retval;
2422 } export_cbdata_t;
2423
2424
2425 typedef struct {
2426 char *aea_poolname;
2427 export_cbdata_t *aea_cbdata;
2428 } async_export_args_t;
2429
2430 /*
2431 * Export one pool
2432 */
2433 static int
zpool_export_one(zpool_handle_t * zhp,void * data)2434 zpool_export_one(zpool_handle_t *zhp, void *data)
2435 {
2436 export_cbdata_t *cb = data;
2437
2438 /*
2439 * zpool_disable_datasets() is not thread-safe for mnttab access.
2440 * So we serialize access here for 'zpool export -a' parallel case.
2441 */
2442 if (cb->taskq != NULL)
2443 (void) pthread_mutex_lock(&cb->mnttab_lock);
2444
2445 int retval = zpool_disable_datasets(zhp, cb->force);
2446
2447 if (cb->taskq != NULL)
2448 (void) pthread_mutex_unlock(&cb->mnttab_lock);
2449
2450 if (retval)
2451 return (1);
2452
2453 if (cb->hardforce) {
2454 if (zpool_export_force(zhp, history_str) != 0)
2455 return (1);
2456 } else if (zpool_export(zhp, cb->force, history_str) != 0) {
2457 return (1);
2458 }
2459
2460 return (0);
2461 }
2462
2463 /*
2464 * Asynchronous export request
2465 */
2466 static void
zpool_export_task(void * arg)2467 zpool_export_task(void *arg)
2468 {
2469 async_export_args_t *aea = arg;
2470
2471 zpool_handle_t *zhp = zpool_open(g_zfs, aea->aea_poolname);
2472 if (zhp != NULL) {
2473 int ret = zpool_export_one(zhp, aea->aea_cbdata);
2474 if (ret != 0)
2475 aea->aea_cbdata->retval = ret;
2476 zpool_close(zhp);
2477 } else {
2478 aea->aea_cbdata->retval = 1;
2479 }
2480
2481 free(aea->aea_poolname);
2482 free(aea);
2483 }
2484
2485 /*
2486 * Process an export request in parallel
2487 */
2488 static int
zpool_export_one_async(zpool_handle_t * zhp,void * data)2489 zpool_export_one_async(zpool_handle_t *zhp, void *data)
2490 {
2491 taskq_t *tq = ((export_cbdata_t *)data)->taskq;
2492 async_export_args_t *aea = safe_malloc(sizeof (async_export_args_t));
2493
2494 /* save pool name since zhp will go out of scope */
2495 aea->aea_poolname = strdup(zpool_get_name(zhp));
2496 aea->aea_cbdata = data;
2497
2498 /* ship off actual export to another thread */
2499 if (taskq_dispatch(tq, zpool_export_task, (void *)aea,
2500 TQ_SLEEP) == TASKQID_INVALID)
2501 return (errno); /* unlikely */
2502 else
2503 return (0);
2504 }
2505
2506 /*
2507 * zpool export [-f] <pool> ...
2508 *
2509 * -a Export all pools
2510 * -f Forcefully unmount datasets
2511 *
2512 * Export the given pools. By default, the command will attempt to cleanly
2513 * unmount any active datasets within the pool. If the '-f' flag is specified,
2514 * then the datasets will be forcefully unmounted.
2515 */
2516 int
zpool_do_export(int argc,char ** argv)2517 zpool_do_export(int argc, char **argv)
2518 {
2519 export_cbdata_t cb;
2520 boolean_t do_all = B_FALSE;
2521 boolean_t force = B_FALSE;
2522 boolean_t hardforce = B_FALSE;
2523 int c, ret;
2524
2525 /* check options */
2526 while ((c = getopt(argc, argv, "afF")) != -1) {
2527 switch (c) {
2528 case 'a':
2529 do_all = B_TRUE;
2530 break;
2531 case 'f':
2532 force = B_TRUE;
2533 break;
2534 case 'F':
2535 hardforce = B_TRUE;
2536 break;
2537 case '?':
2538 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2539 optopt);
2540 usage(B_FALSE);
2541 }
2542 }
2543
2544 cb.force = force;
2545 cb.hardforce = hardforce;
2546 cb.taskq = NULL;
2547 cb.retval = 0;
2548 argc -= optind;
2549 argv += optind;
2550
2551 /* The history will be logged as part of the export itself */
2552 log_history = B_FALSE;
2553
2554 if (do_all) {
2555 if (argc != 0) {
2556 (void) fprintf(stderr, gettext("too many arguments\n"));
2557 usage(B_FALSE);
2558 }
2559
2560 cb.taskq = taskq_create("zpool_export",
2561 5 * sysconf(_SC_NPROCESSORS_ONLN), minclsyspri, 1, INT_MAX,
2562 TASKQ_DYNAMIC);
2563 (void) pthread_mutex_init(&cb.mnttab_lock, NULL);
2564
2565 /* Asynchronously call zpool_export_one using thread pool */
2566 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2567 B_FALSE, zpool_export_one_async, &cb);
2568
2569 taskq_wait(cb.taskq);
2570 taskq_destroy(cb.taskq);
2571 (void) pthread_mutex_destroy(&cb.mnttab_lock);
2572
2573 return (ret | cb.retval);
2574 }
2575
2576 /* check arguments */
2577 if (argc < 1) {
2578 (void) fprintf(stderr, gettext("missing pool argument\n"));
2579 usage(B_FALSE);
2580 }
2581
2582 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2583 B_FALSE, zpool_export_one, &cb);
2584
2585 return (ret);
2586 }
2587
2588 /*
2589 * Given a vdev configuration, determine the maximum width needed for the device
2590 * name column.
2591 */
2592 static int
max_width(zpool_handle_t * zhp,nvlist_t * nv,int depth,int max,int name_flags)2593 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
2594 int name_flags)
2595 {
2596 static const char *const subtypes[] =
2597 {ZPOOL_CONFIG_SPARES, ZPOOL_CONFIG_L2CACHE, ZPOOL_CONFIG_CHILDREN};
2598
2599 char *name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
2600 max = MAX(strlen(name) + depth, max);
2601 free(name);
2602
2603 nvlist_t **child;
2604 uint_t children;
2605 for (size_t i = 0; i < ARRAY_SIZE(subtypes); ++i)
2606 if (nvlist_lookup_nvlist_array(nv, subtypes[i],
2607 &child, &children) == 0)
2608 for (uint_t c = 0; c < children; ++c)
2609 max = MAX(max_width(zhp, child[c], depth + 2,
2610 max, name_flags), max);
2611
2612 return (max);
2613 }
2614
2615 typedef struct status_cbdata {
2616 int cb_count;
2617 int cb_name_flags;
2618 int cb_namewidth;
2619 boolean_t cb_allpools;
2620 boolean_t cb_verbose;
2621 boolean_t cb_literal;
2622 boolean_t cb_explain;
2623 boolean_t cb_first;
2624 boolean_t cb_dedup_stats;
2625 boolean_t cb_print_unhealthy;
2626 boolean_t cb_print_status;
2627 boolean_t cb_print_slow_ios;
2628 boolean_t cb_print_dio_verify;
2629 boolean_t cb_print_vdev_init;
2630 boolean_t cb_print_vdev_trim;
2631 vdev_cmd_data_list_t *vcdl;
2632 boolean_t cb_print_power;
2633 boolean_t cb_json;
2634 boolean_t cb_flat_vdevs;
2635 nvlist_t *cb_jsobj;
2636 boolean_t cb_json_as_int;
2637 boolean_t cb_json_pool_key_guid;
2638 } status_cbdata_t;
2639
2640 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
2641 static boolean_t
is_blank_str(const char * str)2642 is_blank_str(const char *str)
2643 {
2644 for (; str != NULL && *str != '\0'; ++str)
2645 if (!isblank(*str))
2646 return (B_FALSE);
2647 return (B_TRUE);
2648 }
2649
2650 static void
zpool_nvlist_cmd(vdev_cmd_data_list_t * vcdl,const char * pool,const char * path,nvlist_t * item)2651 zpool_nvlist_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path,
2652 nvlist_t *item)
2653 {
2654 vdev_cmd_data_t *data;
2655 int i, j, k = 1;
2656 char tmp[256];
2657 const char *val;
2658
2659 for (i = 0; i < vcdl->count; i++) {
2660 if ((strcmp(vcdl->data[i].path, path) != 0) ||
2661 (strcmp(vcdl->data[i].pool, pool) != 0))
2662 continue;
2663
2664 data = &vcdl->data[i];
2665 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2666 val = NULL;
2667 for (int k = 0; k < data->cols_cnt; k++) {
2668 if (strcmp(data->cols[k],
2669 vcdl->uniq_cols[j]) == 0) {
2670 val = data->lines[k];
2671 break;
2672 }
2673 }
2674 if (val == NULL || is_blank_str(val))
2675 val = "-";
2676 fnvlist_add_string(item, vcdl->uniq_cols[j], val);
2677 }
2678
2679 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2680 if (data->lines[j]) {
2681 (void) snprintf(tmp, 256, "extra_%d", k++);
2682 fnvlist_add_string(item, tmp,
2683 data->lines[j]);
2684 }
2685 }
2686 break;
2687 }
2688 }
2689
2690 /* Print command output lines for specific vdev in a specific pool */
2691 static void
zpool_print_cmd(vdev_cmd_data_list_t * vcdl,const char * pool,const char * path)2692 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path)
2693 {
2694 vdev_cmd_data_t *data;
2695 int i, j;
2696 const char *val;
2697
2698 for (i = 0; i < vcdl->count; i++) {
2699 if ((strcmp(vcdl->data[i].path, path) != 0) ||
2700 (strcmp(vcdl->data[i].pool, pool) != 0)) {
2701 /* Not the vdev we're looking for */
2702 continue;
2703 }
2704
2705 data = &vcdl->data[i];
2706 /* Print out all the output values for this vdev */
2707 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2708 val = NULL;
2709 /* Does this vdev have values for this column? */
2710 for (int k = 0; k < data->cols_cnt; k++) {
2711 if (strcmp(data->cols[k],
2712 vcdl->uniq_cols[j]) == 0) {
2713 /* yes it does, record the value */
2714 val = data->lines[k];
2715 break;
2716 }
2717 }
2718 /*
2719 * Mark empty values with dashes to make output
2720 * awk-able.
2721 */
2722 if (val == NULL || is_blank_str(val))
2723 val = "-";
2724
2725 printf("%*s", vcdl->uniq_cols_width[j], val);
2726 if (j < vcdl->uniq_cols_cnt - 1)
2727 (void) fputs(" ", stdout);
2728 }
2729
2730 /* Print out any values that aren't in a column at the end */
2731 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2732 /* Did we have any columns? If so print a spacer. */
2733 if (vcdl->uniq_cols_cnt > 0)
2734 (void) fputs(" ", stdout);
2735
2736 val = data->lines[j];
2737 (void) fputs(val ?: "", stdout);
2738 }
2739 break;
2740 }
2741 }
2742
2743 /*
2744 * Print vdev initialization status for leaves
2745 */
2746 static void
print_status_initialize(vdev_stat_t * vs,boolean_t verbose)2747 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
2748 {
2749 if (verbose) {
2750 if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
2751 vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
2752 vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
2753 !vs->vs_scan_removing) {
2754 char zbuf[1024];
2755 char tbuf[256];
2756
2757 time_t t = vs->vs_initialize_action_time;
2758 int initialize_pct = 100;
2759 if (vs->vs_initialize_state !=
2760 VDEV_INITIALIZE_COMPLETE) {
2761 initialize_pct = (vs->vs_initialize_bytes_done *
2762 100 / (vs->vs_initialize_bytes_est + 1));
2763 }
2764
2765 (void) ctime_r(&t, tbuf);
2766 tbuf[24] = 0;
2767
2768 switch (vs->vs_initialize_state) {
2769 case VDEV_INITIALIZE_SUSPENDED:
2770 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2771 gettext("suspended, started at"), tbuf);
2772 break;
2773 case VDEV_INITIALIZE_ACTIVE:
2774 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2775 gettext("started at"), tbuf);
2776 break;
2777 case VDEV_INITIALIZE_COMPLETE:
2778 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2779 gettext("completed at"), tbuf);
2780 break;
2781 }
2782
2783 (void) printf(gettext(" (%d%% initialized%s)"),
2784 initialize_pct, zbuf);
2785 } else {
2786 (void) printf(gettext(" (uninitialized)"));
2787 }
2788 } else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
2789 (void) printf(gettext(" (initializing)"));
2790 }
2791 }
2792
2793 /*
2794 * Print vdev TRIM status for leaves
2795 */
2796 static void
print_status_trim(vdev_stat_t * vs,boolean_t verbose)2797 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
2798 {
2799 if (verbose) {
2800 if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
2801 vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
2802 vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
2803 !vs->vs_scan_removing) {
2804 char zbuf[1024];
2805 char tbuf[256];
2806
2807 time_t t = vs->vs_trim_action_time;
2808 int trim_pct = 100;
2809 if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
2810 trim_pct = (vs->vs_trim_bytes_done *
2811 100 / (vs->vs_trim_bytes_est + 1));
2812 }
2813
2814 (void) ctime_r(&t, tbuf);
2815 tbuf[24] = 0;
2816
2817 switch (vs->vs_trim_state) {
2818 case VDEV_TRIM_SUSPENDED:
2819 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2820 gettext("suspended, started at"), tbuf);
2821 break;
2822 case VDEV_TRIM_ACTIVE:
2823 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2824 gettext("started at"), tbuf);
2825 break;
2826 case VDEV_TRIM_COMPLETE:
2827 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2828 gettext("completed at"), tbuf);
2829 break;
2830 }
2831
2832 (void) printf(gettext(" (%d%% trimmed%s)"),
2833 trim_pct, zbuf);
2834 } else if (vs->vs_trim_notsup) {
2835 (void) printf(gettext(" (trim unsupported)"));
2836 } else {
2837 (void) printf(gettext(" (untrimmed)"));
2838 }
2839 } else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
2840 (void) printf(gettext(" (trimming)"));
2841 }
2842 }
2843
2844 /*
2845 * Return the color associated with a health string. This includes returning
2846 * NULL for no color change.
2847 */
2848 static const char *
health_str_to_color(const char * health)2849 health_str_to_color(const char *health)
2850 {
2851 if (strcmp(health, gettext("FAULTED")) == 0 ||
2852 strcmp(health, gettext("SUSPENDED")) == 0 ||
2853 strcmp(health, gettext("UNAVAIL")) == 0) {
2854 return (ANSI_RED);
2855 }
2856
2857 if (strcmp(health, gettext("OFFLINE")) == 0 ||
2858 strcmp(health, gettext("DEGRADED")) == 0 ||
2859 strcmp(health, gettext("REMOVED")) == 0) {
2860 return (ANSI_YELLOW);
2861 }
2862
2863 return (NULL);
2864 }
2865
2866 /*
2867 * Called for each leaf vdev. Returns 0 if the vdev is healthy.
2868 * A vdev is unhealthy if any of the following are true:
2869 * 1) there are read, write, or checksum errors,
2870 * 2) its state is not ONLINE, or
2871 * 3) slow IO reporting was requested (-s) and there are slow IOs.
2872 */
2873 static int
vdev_health_check_cb(void * hdl_data,nvlist_t * nv,void * data)2874 vdev_health_check_cb(void *hdl_data, nvlist_t *nv, void *data)
2875 {
2876 status_cbdata_t *cb = data;
2877 vdev_stat_t *vs;
2878 uint_t vsc;
2879 (void) hdl_data;
2880
2881 if (nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2882 (uint64_t **)&vs, &vsc) != 0)
2883 return (1);
2884
2885 if (vs->vs_checksum_errors || vs->vs_read_errors ||
2886 vs->vs_write_errors || vs->vs_state != VDEV_STATE_HEALTHY)
2887 return (1);
2888
2889 if (cb->cb_print_slow_ios && vs->vs_slow_ios)
2890 return (1);
2891
2892 return (0);
2893 }
2894
2895 /*
2896 * Print out configuration state as requested by status_callback.
2897 */
2898 static void
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)2899 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
2900 nvlist_t *nv, int depth, boolean_t isspare, vdev_rebuild_stat_t *vrs)
2901 {
2902 nvlist_t **child, *root;
2903 uint_t c, i, vsc, children;
2904 pool_scan_stat_t *ps = NULL;
2905 vdev_stat_t *vs;
2906 char rbuf[6], wbuf[6], cbuf[6], dbuf[6];
2907 char *vname;
2908 uint64_t notpresent;
2909 spare_cbdata_t spare_cb;
2910 const char *state;
2911 const char *type;
2912 const char *path = NULL;
2913 const char *rcolor = NULL, *wcolor = NULL, *ccolor = NULL,
2914 *scolor = NULL;
2915
2916 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2917 &child, &children) != 0)
2918 children = 0;
2919
2920 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2921 (uint64_t **)&vs, &vsc) == 0);
2922
2923 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2924
2925 if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2926 return;
2927
2928 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2929
2930 if (isspare) {
2931 /*
2932 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
2933 * online drives.
2934 */
2935 if (vs->vs_aux == VDEV_AUX_SPARED)
2936 state = gettext("INUSE");
2937 else if (vs->vs_state == VDEV_STATE_HEALTHY)
2938 state = gettext("AVAIL");
2939 }
2940
2941 /*
2942 * If '-e' is specified then top-level vdevs and their children
2943 * can be pruned if all of their leaves are healthy.
2944 */
2945 if (cb->cb_print_unhealthy && depth > 0 &&
2946 for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
2947 return;
2948 }
2949
2950 (void) printf_color(health_str_to_color(state),
2951 "\t%*s%-*s %-8s", depth, "", cb->cb_namewidth - depth,
2952 name, state);
2953
2954 if (!isspare) {
2955 if (vs->vs_read_errors)
2956 rcolor = ANSI_RED;
2957
2958 if (vs->vs_write_errors)
2959 wcolor = ANSI_RED;
2960
2961 if (vs->vs_checksum_errors)
2962 ccolor = ANSI_RED;
2963
2964 if (vs->vs_slow_ios)
2965 scolor = ANSI_BLUE;
2966
2967 if (cb->cb_literal) {
2968 (void) fputc(' ', stdout);
2969 (void) printf_color(rcolor, "%5llu",
2970 (u_longlong_t)vs->vs_read_errors);
2971 (void) fputc(' ', stdout);
2972 (void) printf_color(wcolor, "%5llu",
2973 (u_longlong_t)vs->vs_write_errors);
2974 (void) fputc(' ', stdout);
2975 (void) printf_color(ccolor, "%5llu",
2976 (u_longlong_t)vs->vs_checksum_errors);
2977 } else {
2978 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
2979 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
2980 zfs_nicenum(vs->vs_checksum_errors, cbuf,
2981 sizeof (cbuf));
2982 (void) fputc(' ', stdout);
2983 (void) printf_color(rcolor, "%5s", rbuf);
2984 (void) fputc(' ', stdout);
2985 (void) printf_color(wcolor, "%5s", wbuf);
2986 (void) fputc(' ', stdout);
2987 (void) printf_color(ccolor, "%5s", cbuf);
2988 }
2989 if (cb->cb_print_slow_ios) {
2990 if (children == 0) {
2991 /* Only leafs vdevs have slow IOs */
2992 zfs_nicenum(vs->vs_slow_ios, rbuf,
2993 sizeof (rbuf));
2994 } else {
2995 (void) snprintf(rbuf, sizeof (rbuf), "-");
2996 }
2997
2998 if (cb->cb_literal)
2999 (void) printf_color(scolor, " %5llu",
3000 (u_longlong_t)vs->vs_slow_ios);
3001 else
3002 (void) printf_color(scolor, " %5s", rbuf);
3003 }
3004 if (cb->cb_print_power) {
3005 if (children == 0) {
3006 /* Only leaf vdevs have physical slots */
3007 switch (zpool_power_current_state(zhp, (char *)
3008 fnvlist_lookup_string(nv,
3009 ZPOOL_CONFIG_PATH))) {
3010 case 0:
3011 (void) printf_color(ANSI_RED, " %5s",
3012 gettext("off"));
3013 break;
3014 case 1:
3015 printf(" %5s", gettext("on"));
3016 break;
3017 default:
3018 printf(" %5s", "-");
3019 }
3020 } else {
3021 printf(" %5s", "-");
3022 }
3023 }
3024 if (VDEV_STAT_VALID(vs_dio_verify_errors, vsc) &&
3025 cb->cb_print_dio_verify) {
3026 zfs_nicenum(vs->vs_dio_verify_errors, dbuf,
3027 sizeof (dbuf));
3028
3029 if (cb->cb_literal)
3030 printf(" %5llu",
3031 (u_longlong_t)vs->vs_dio_verify_errors);
3032 else
3033 printf(" %5s", dbuf);
3034 }
3035 }
3036
3037 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
3038 ¬present) == 0) {
3039 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
3040 (void) printf(" %s %s", gettext("was"), path);
3041 } else if (vs->vs_aux != 0) {
3042 (void) printf(" ");
3043 color_start(ANSI_RED);
3044 switch (vs->vs_aux) {
3045 case VDEV_AUX_OPEN_FAILED:
3046 (void) printf(gettext("cannot open"));
3047 break;
3048
3049 case VDEV_AUX_BAD_GUID_SUM:
3050 (void) printf(gettext("missing device"));
3051 break;
3052
3053 case VDEV_AUX_NO_REPLICAS:
3054 (void) printf(gettext("insufficient replicas"));
3055 break;
3056
3057 case VDEV_AUX_VERSION_NEWER:
3058 (void) printf(gettext("newer version"));
3059 break;
3060
3061 case VDEV_AUX_UNSUP_FEAT:
3062 (void) printf(gettext("unsupported feature(s)"));
3063 break;
3064
3065 case VDEV_AUX_ASHIFT_TOO_BIG:
3066 (void) printf(gettext("unsupported minimum blocksize"));
3067 break;
3068
3069 case VDEV_AUX_SPARED:
3070 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3071 &spare_cb.cb_guid) == 0);
3072 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
3073 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
3074 zpool_get_name(zhp)) == 0)
3075 (void) printf(gettext("currently in "
3076 "use"));
3077 else
3078 (void) printf(gettext("in use by "
3079 "pool '%s'"),
3080 zpool_get_name(spare_cb.cb_zhp));
3081 zpool_close(spare_cb.cb_zhp);
3082 } else {
3083 (void) printf(gettext("currently in use"));
3084 }
3085 break;
3086
3087 case VDEV_AUX_ERR_EXCEEDED:
3088 if (vs->vs_read_errors + vs->vs_write_errors +
3089 vs->vs_checksum_errors == 0 && children == 0 &&
3090 vs->vs_slow_ios > 0) {
3091 (void) printf(gettext("too many slow I/Os"));
3092 } else {
3093 (void) printf(gettext("too many errors"));
3094 }
3095 break;
3096
3097 case VDEV_AUX_IO_FAILURE:
3098 (void) printf(gettext("experienced I/O failures"));
3099 break;
3100
3101 case VDEV_AUX_BAD_LOG:
3102 (void) printf(gettext("bad intent log"));
3103 break;
3104
3105 case VDEV_AUX_EXTERNAL:
3106 (void) printf(gettext("external device fault"));
3107 break;
3108
3109 case VDEV_AUX_SPLIT_POOL:
3110 (void) printf(gettext("split into new pool"));
3111 break;
3112
3113 case VDEV_AUX_ACTIVE:
3114 (void) printf(gettext("currently in use"));
3115 break;
3116
3117 case VDEV_AUX_CHILDREN_OFFLINE:
3118 (void) printf(gettext("all children offline"));
3119 break;
3120
3121 case VDEV_AUX_BAD_LABEL:
3122 (void) printf(gettext("invalid label"));
3123 break;
3124
3125 default:
3126 (void) printf(gettext("corrupted data"));
3127 break;
3128 }
3129 color_end();
3130 } else if (children == 0 && !isspare &&
3131 getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
3132 VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
3133 vs->vs_configured_ashift < vs->vs_physical_ashift) {
3134 (void) printf(
3135 gettext(" block size: %dB configured, %dB native"),
3136 1 << vs->vs_configured_ashift, 1 << vs->vs_physical_ashift);
3137 }
3138
3139 if (vs->vs_scan_removing != 0) {
3140 (void) printf(gettext(" (removing)"));
3141 } else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
3142 (void) printf(gettext(" (non-allocating)"));
3143 }
3144
3145 /* The root vdev has the scrub/resilver stats */
3146 root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
3147 ZPOOL_CONFIG_VDEV_TREE);
3148 (void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
3149 (uint64_t **)&ps, &c);
3150
3151 /*
3152 * If you force fault a drive that's resilvering, its scan stats can
3153 * get frozen in time, giving the false impression that it's
3154 * being resilvered. That's why we check the state to see if the vdev
3155 * is healthy before reporting "resilvering" or "repairing".
3156 */
3157 if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0 &&
3158 vs->vs_state == VDEV_STATE_HEALTHY) {
3159 if (vs->vs_scan_processed != 0) {
3160 (void) printf(gettext(" (%s)"),
3161 (ps->pss_func == POOL_SCAN_RESILVER) ?
3162 "resilvering" : "repairing");
3163 } else if (vs->vs_resilver_deferred) {
3164 (void) printf(gettext(" (awaiting resilver)"));
3165 }
3166 }
3167
3168 /* The top-level vdevs have the rebuild stats */
3169 if (vrs != NULL && vrs->vrs_state == VDEV_REBUILD_ACTIVE &&
3170 children == 0 && vs->vs_state == VDEV_STATE_HEALTHY) {
3171 if (vs->vs_rebuild_processed != 0) {
3172 (void) printf(gettext(" (resilvering)"));
3173 }
3174 }
3175
3176 if (cb->vcdl != NULL) {
3177 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
3178 printf(" ");
3179 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
3180 }
3181 }
3182
3183 /* Display vdev initialization and trim status for leaves. */
3184 if (children == 0) {
3185 print_status_initialize(vs, cb->cb_print_vdev_init);
3186 print_status_trim(vs, cb->cb_print_vdev_trim);
3187 }
3188
3189 (void) printf("\n");
3190
3191 for (c = 0; c < children; c++) {
3192 uint64_t islog = B_FALSE, ishole = B_FALSE;
3193
3194 /* Don't print logs or holes here */
3195 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3196 &islog);
3197 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
3198 &ishole);
3199 if (islog || ishole)
3200 continue;
3201 /* Only print normal classes here */
3202 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3203 continue;
3204
3205 /* Provide vdev_rebuild_stats to children if available */
3206 if (vrs == NULL) {
3207 (void) nvlist_lookup_uint64_array(nv,
3208 ZPOOL_CONFIG_REBUILD_STATS,
3209 (uint64_t **)&vrs, &i);
3210 }
3211
3212 vname = zpool_vdev_name(g_zfs, zhp, child[c],
3213 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3214 print_status_config(zhp, cb, vname, child[c], depth + 2,
3215 isspare, vrs);
3216 free(vname);
3217 }
3218 }
3219
3220 /*
3221 * Print the configuration of an exported pool. Iterate over all vdevs in the
3222 * pool, printing out the name and status for each one.
3223 */
3224 static void
print_import_config(status_cbdata_t * cb,const char * name,nvlist_t * nv,int depth)3225 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
3226 int depth)
3227 {
3228 nvlist_t **child;
3229 uint_t c, children;
3230 vdev_stat_t *vs;
3231 const char *type;
3232 char *vname;
3233
3234 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
3235 if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
3236 strcmp(type, VDEV_TYPE_HOLE) == 0)
3237 return;
3238
3239 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
3240 (uint64_t **)&vs, &c) == 0);
3241
3242 (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
3243 (void) printf(" %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
3244
3245 if (vs->vs_aux != 0) {
3246 (void) printf(" ");
3247
3248 switch (vs->vs_aux) {
3249 case VDEV_AUX_OPEN_FAILED:
3250 (void) printf(gettext("cannot open"));
3251 break;
3252
3253 case VDEV_AUX_BAD_GUID_SUM:
3254 (void) printf(gettext("missing device"));
3255 break;
3256
3257 case VDEV_AUX_NO_REPLICAS:
3258 (void) printf(gettext("insufficient replicas"));
3259 break;
3260
3261 case VDEV_AUX_VERSION_NEWER:
3262 (void) printf(gettext("newer version"));
3263 break;
3264
3265 case VDEV_AUX_UNSUP_FEAT:
3266 (void) printf(gettext("unsupported feature(s)"));
3267 break;
3268
3269 case VDEV_AUX_ERR_EXCEEDED:
3270 (void) printf(gettext("too many errors"));
3271 break;
3272
3273 case VDEV_AUX_ACTIVE:
3274 (void) printf(gettext("currently in use"));
3275 break;
3276
3277 case VDEV_AUX_CHILDREN_OFFLINE:
3278 (void) printf(gettext("all children offline"));
3279 break;
3280
3281 case VDEV_AUX_BAD_LABEL:
3282 (void) printf(gettext("invalid label"));
3283 break;
3284
3285 default:
3286 (void) printf(gettext("corrupted data"));
3287 break;
3288 }
3289 }
3290 (void) printf("\n");
3291
3292 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
3293 &child, &children) != 0)
3294 return;
3295
3296 for (c = 0; c < children; c++) {
3297 uint64_t is_log = B_FALSE;
3298
3299 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3300 &is_log);
3301 if (is_log)
3302 continue;
3303 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3304 continue;
3305
3306 vname = zpool_vdev_name(g_zfs, NULL, child[c],
3307 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3308 print_import_config(cb, vname, child[c], depth + 2);
3309 free(vname);
3310 }
3311
3312 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
3313 &child, &children) == 0) {
3314 (void) printf(gettext("\tcache\n"));
3315 for (c = 0; c < children; c++) {
3316 vname = zpool_vdev_name(g_zfs, NULL, child[c],
3317 cb->cb_name_flags);
3318 (void) printf("\t %s\n", vname);
3319 free(vname);
3320 }
3321 }
3322
3323 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
3324 &child, &children) == 0) {
3325 (void) printf(gettext("\tspares\n"));
3326 for (c = 0; c < children; c++) {
3327 vname = zpool_vdev_name(g_zfs, NULL, child[c],
3328 cb->cb_name_flags);
3329 (void) printf("\t %s\n", vname);
3330 free(vname);
3331 }
3332 }
3333 }
3334
3335 /*
3336 * Print specialized class vdevs.
3337 *
3338 * These are recorded as top level vdevs in the main pool child array
3339 * but with "is_log" set to 1 or an "alloc_bias" string. We use either
3340 * print_status_config() or print_import_config() to print the top level
3341 * class vdevs then any of their children (eg mirrored slogs) are printed
3342 * recursively - which works because only the top level vdev is marked.
3343 */
3344 static void
print_class_vdevs(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,const char * class)3345 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
3346 const char *class)
3347 {
3348 uint_t c, children;
3349 nvlist_t **child;
3350 boolean_t printed = B_FALSE;
3351
3352 assert(zhp != NULL || !cb->cb_verbose);
3353
3354 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
3355 &children) != 0)
3356 return;
3357
3358 for (c = 0; c < children; c++) {
3359 uint64_t is_log = B_FALSE;
3360 const char *bias = NULL;
3361 const char *type = NULL;
3362
3363 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3364 &is_log);
3365
3366 if (is_log) {
3367 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
3368 } else {
3369 (void) nvlist_lookup_string(child[c],
3370 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
3371 (void) nvlist_lookup_string(child[c],
3372 ZPOOL_CONFIG_TYPE, &type);
3373 }
3374
3375 if (bias == NULL || strcmp(bias, class) != 0)
3376 continue;
3377 if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
3378 continue;
3379
3380 if (!printed) {
3381 (void) printf("\t%s\t\n", gettext(class));
3382 printed = B_TRUE;
3383 }
3384
3385 char *name = zpool_vdev_name(g_zfs, zhp, child[c],
3386 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3387 if (cb->cb_print_status)
3388 print_status_config(zhp, cb, name, child[c], 2,
3389 B_FALSE, NULL);
3390 else
3391 print_import_config(cb, name, child[c], 2);
3392 free(name);
3393 }
3394 }
3395
3396 /*
3397 * Display the status for the given pool.
3398 */
3399 static int
show_import(nvlist_t * config,boolean_t report_error)3400 show_import(nvlist_t *config, boolean_t report_error)
3401 {
3402 uint64_t pool_state;
3403 vdev_stat_t *vs;
3404 const char *name;
3405 uint64_t guid;
3406 uint64_t hostid = 0;
3407 const char *msgid;
3408 const char *hostname = "unknown";
3409 nvlist_t *nvroot, *nvinfo;
3410 zpool_status_t reason;
3411 zpool_errata_t errata;
3412 const char *health;
3413 uint_t vsc;
3414 const char *comment;
3415 const char *indent;
3416 char buf[2048];
3417 status_cbdata_t cb = { 0 };
3418
3419 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3420 &name) == 0);
3421 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3422 &guid) == 0);
3423 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3424 &pool_state) == 0);
3425 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3426 &nvroot) == 0);
3427
3428 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
3429 (uint64_t **)&vs, &vsc) == 0);
3430 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
3431
3432 reason = zpool_import_status(config, &msgid, &errata);
3433
3434 /*
3435 * If we're importing using a cachefile, then we won't report any
3436 * errors unless we are in the scan phase of the import.
3437 */
3438 if (reason != ZPOOL_STATUS_OK && !report_error)
3439 return (reason);
3440
3441 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0) {
3442 indent = " ";
3443 } else {
3444 comment = NULL;
3445 indent = "";
3446 }
3447
3448 (void) printf(gettext("%s pool: %s\n"), indent, name);
3449 (void) printf(gettext("%s id: %llu\n"), indent, (u_longlong_t)guid);
3450 (void) printf(gettext("%s state: %s"), indent, health);
3451 if (pool_state == POOL_STATE_DESTROYED)
3452 (void) printf(gettext(" (DESTROYED)"));
3453 (void) printf("\n");
3454
3455 if (reason != ZPOOL_STATUS_OK) {
3456 (void) printf("%s", indent);
3457 (void) printf_color(ANSI_BOLD, gettext("status: "));
3458 }
3459 switch (reason) {
3460 case ZPOOL_STATUS_MISSING_DEV_R:
3461 case ZPOOL_STATUS_MISSING_DEV_NR:
3462 case ZPOOL_STATUS_BAD_GUID_SUM:
3463 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3464 "are missing from the system.\n"));
3465 break;
3466
3467 case ZPOOL_STATUS_CORRUPT_LABEL_R:
3468 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
3469 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3470 "contains corrupted data.\n"));
3471 break;
3472
3473 case ZPOOL_STATUS_CORRUPT_DATA:
3474 (void) printf_color(ANSI_YELLOW, gettext("The pool data is "
3475 "corrupted.\n"));
3476 break;
3477
3478 case ZPOOL_STATUS_OFFLINE_DEV:
3479 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3480 "are offlined.\n"));
3481 break;
3482
3483 case ZPOOL_STATUS_CORRUPT_POOL:
3484 (void) printf_color(ANSI_YELLOW, gettext("The pool metadata is "
3485 "incomplete or corrupted.\n"));
3486 break;
3487
3488 case ZPOOL_STATUS_VERSION_OLDER:
3489 (void) printf_color(ANSI_YELLOW, gettext("The pool is "
3490 "formatted using a legacy on-disk version.\n"));
3491 break;
3492
3493 case ZPOOL_STATUS_VERSION_NEWER:
3494 (void) printf_color(ANSI_YELLOW, gettext("The pool is "
3495 "formatted using an incompatible version.\n"));
3496 break;
3497
3498 case ZPOOL_STATUS_FEAT_DISABLED:
3499 (void) printf_color(ANSI_YELLOW, gettext("Some supported "
3500 "features are not enabled on the pool.\n"
3501 "\t%s(Note that they may be intentionally disabled if the\n"
3502 "\t%s'compatibility' property is set.)\n"), indent, indent);
3503 break;
3504
3505 case ZPOOL_STATUS_COMPATIBILITY_ERR:
3506 (void) printf_color(ANSI_YELLOW, gettext("Error reading or "
3507 "parsing the file(s) indicated by the 'compatibility'\n"
3508 "\t%sproperty.\n"), indent);
3509 break;
3510
3511 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
3512 (void) printf_color(ANSI_YELLOW, gettext("One or more features "
3513 "are enabled on the pool despite not being\n"
3514 "\t%srequested by the 'compatibility' property.\n"),
3515 indent);
3516 break;
3517
3518 case ZPOOL_STATUS_UNSUP_FEAT_READ:
3519 (void) printf_color(ANSI_YELLOW, gettext("The pool uses the "
3520 "following feature(s) not supported on this system:\n"));
3521 color_start(ANSI_YELLOW);
3522 zpool_collect_unsup_feat(config, buf, 2048);
3523 (void) printf("%s", buf);
3524 color_end();
3525 break;
3526
3527 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3528 (void) printf_color(ANSI_YELLOW, gettext("The pool can only be "
3529 "accessed in read-only mode on this system. It\n"
3530 "\t%scannot be accessed in read-write mode because it uses "
3531 "the following\n"
3532 "\t%sfeature(s) not supported on this system:\n"),
3533 indent, indent);
3534 color_start(ANSI_YELLOW);
3535 zpool_collect_unsup_feat(config, buf, 2048);
3536 (void) printf("%s", buf);
3537 color_end();
3538 break;
3539
3540 case ZPOOL_STATUS_HOSTID_ACTIVE:
3541 (void) printf_color(ANSI_YELLOW, gettext("The pool is "
3542 "currently imported by another system.\n"));
3543 break;
3544
3545 case ZPOOL_STATUS_HOSTID_REQUIRED:
3546 (void) printf_color(ANSI_YELLOW, gettext("The pool has the "
3547 "multihost property on. It cannot\n"
3548 "\t%sbe safely imported when the system hostid is not "
3549 "set.\n"), indent);
3550 break;
3551
3552 case ZPOOL_STATUS_HOSTID_MISMATCH:
3553 (void) printf_color(ANSI_YELLOW, gettext("The pool was last "
3554 "accessed by another system.\n"));
3555 break;
3556
3557 case ZPOOL_STATUS_FAULTED_FDOM_R:
3558 (void) printf_color(ANSI_YELLOW, gettext("One or more failure "
3559 " domains are faulted.\n"));
3560 break;
3561
3562 case ZPOOL_STATUS_FAULTED_DEV_R:
3563 case ZPOOL_STATUS_FAULTED_DEV_NR:
3564 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3565 "are faulted.\n"));
3566 break;
3567
3568 case ZPOOL_STATUS_BAD_LOG:
3569 (void) printf_color(ANSI_YELLOW, gettext("An intent log record "
3570 "cannot be read.\n"));
3571 break;
3572
3573 case ZPOOL_STATUS_RESILVERING:
3574 case ZPOOL_STATUS_REBUILDING:
3575 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3576 "were being resilvered.\n"));
3577 break;
3578
3579 case ZPOOL_STATUS_ERRATA:
3580 (void) printf_color(ANSI_YELLOW,
3581 gettext("Errata #%d detected.\n"),
3582 errata);
3583 break;
3584
3585 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
3586 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3587 "are configured to use a non-native block size.\n"
3588 "\t%sExpect reduced performance.\n"), indent);
3589 break;
3590
3591 default:
3592 /*
3593 * No other status can be seen when importing pools.
3594 */
3595 assert(reason == ZPOOL_STATUS_OK);
3596 }
3597
3598 /*
3599 * Print out an action according to the overall state of the pool.
3600 */
3601 if (vs->vs_state != VDEV_STATE_HEALTHY ||
3602 reason != ZPOOL_STATUS_ERRATA || errata != ZPOOL_ERRATA_NONE) {
3603 (void) printf("%s", indent);
3604 (void) printf(gettext("action: "));
3605 }
3606 if (vs->vs_state == VDEV_STATE_HEALTHY) {
3607 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
3608 reason == ZPOOL_STATUS_FEAT_DISABLED) {
3609 (void) printf(gettext("The pool can be imported using "
3610 "its name or numeric identifier, though\n"
3611 "\t%ssome features will not be available without "
3612 "an explicit 'zpool upgrade'.\n"), indent);
3613 } else if (reason == ZPOOL_STATUS_COMPATIBILITY_ERR) {
3614 (void) printf(gettext("The pool can be imported using "
3615 "its name or numeric\n"
3616 "\t%sidentifier, though the file(s) indicated by "
3617 "its 'compatibility'\n"
3618 "\t%sproperty cannot be parsed at this time.\n"),
3619 indent, indent);
3620 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
3621 (void) printf(gettext("The pool can be imported using "
3622 "its name or numeric identifier and\n"
3623 "\t%sthe '-f' flag.\n"), indent);
3624 } else if (reason == ZPOOL_STATUS_ERRATA) {
3625 switch (errata) {
3626 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
3627 (void) printf(gettext("The pool can be "
3628 "imported using its name or numeric "
3629 "identifier,\n"
3630 "\t%showever there is a compatibility "
3631 "issue which should be corrected\n"
3632 "\t%sby running 'zpool scrub'\n"),
3633 indent, indent);
3634 break;
3635
3636 case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
3637 (void) printf(gettext("The pool cannot be "
3638 "imported with this version of ZFS due to\n"
3639 "\t%san active asynchronous destroy. "
3640 "Revert to an earlier version\n"
3641 "\t%sand allow the destroy to complete "
3642 "before updating.\n"), indent, indent);
3643 break;
3644
3645 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
3646 (void) printf(gettext("Existing encrypted "
3647 "datasets contain an on-disk "
3648 "incompatibility, which\n"
3649 "\t%sneeds to be corrected. Backup these "
3650 "datasets to new encrypted datasets\n"
3651 "\t%sand destroy the old ones.\n"),
3652 indent, indent);
3653 break;
3654
3655 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
3656 (void) printf(gettext("Existing encrypted "
3657 "snapshots and bookmarks contain an "
3658 "on-disk\n"
3659 "\t%sincompatibility. This may cause "
3660 "on-disk corruption if they are used\n"
3661 "\t%swith 'zfs recv'. To correct the "
3662 "issue, enable the bookmark_v2 feature.\n"
3663 "\t%sNo additional action is needed if "
3664 "there are no encrypted snapshots or\n"
3665 "\t%sbookmarks. If preserving the "
3666 "encrypted snapshots and bookmarks is\n"
3667 "\t%srequired, use a non-raw send to "
3668 "backup and restore them. Alternately,\n"
3669 "\t%sthey may be removed to resolve the "
3670 "incompatibility.\n"), indent, indent,
3671 indent, indent, indent, indent);
3672 break;
3673 default:
3674 /*
3675 * All errata must contain an action message.
3676 */
3677 assert(errata == ZPOOL_ERRATA_NONE);
3678 }
3679 } else {
3680 (void) printf(gettext("The pool can be imported using "
3681 "its name or numeric identifier.\n"));
3682 }
3683 } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
3684 (void) printf(gettext("The pool can be imported despite "
3685 "missing or damaged devices. The\n"
3686 "\t%sfault tolerance of the pool may be compromised if "
3687 "imported.\n"), indent);
3688 } else {
3689 switch (reason) {
3690 case ZPOOL_STATUS_VERSION_NEWER:
3691 (void) printf(gettext("The pool cannot be imported. "
3692 "Access the pool on a system running newer\n"
3693 "\t%ssoftware, or recreate the pool from "
3694 "backup.\n"), indent);
3695 break;
3696 case ZPOOL_STATUS_UNSUP_FEAT_READ:
3697 (void) printf(gettext("The pool cannot be imported. "
3698 "Access the pool on a system that supports\n"
3699 "\t%sthe required feature(s), or recreate the pool "
3700 "from backup.\n"), indent);
3701 break;
3702 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3703 (void) printf(gettext("The pool cannot be imported in "
3704 "read-write mode. Import the pool with\n"
3705 "\t%s'-o readonly=on', access the pool on a system "
3706 "that supports the\n"
3707 "\t%srequired feature(s), or recreate the pool "
3708 "from backup.\n"), indent, indent);
3709 break;
3710 case ZPOOL_STATUS_MISSING_DEV_R:
3711 case ZPOOL_STATUS_MISSING_DEV_NR:
3712 case ZPOOL_STATUS_BAD_GUID_SUM:
3713 (void) printf(gettext("The pool cannot be imported. "
3714 "Attach the missing\n"
3715 "\t%sdevices and try again.\n"), indent);
3716 break;
3717 case ZPOOL_STATUS_HOSTID_ACTIVE:
3718 VERIFY0(nvlist_lookup_nvlist(config,
3719 ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
3720
3721 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3722 hostname = fnvlist_lookup_string(nvinfo,
3723 ZPOOL_CONFIG_MMP_HOSTNAME);
3724
3725 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3726 hostid = fnvlist_lookup_uint64(nvinfo,
3727 ZPOOL_CONFIG_MMP_HOSTID);
3728
3729 (void) printf(gettext("The pool must be exported from "
3730 "%s (hostid=%"PRIx64")\n"
3731 "\t%sbefore it can be safely imported.\n"),
3732 hostname, hostid, indent);
3733 break;
3734 case ZPOOL_STATUS_HOSTID_REQUIRED:
3735 (void) printf(gettext("Set a unique system hostid with "
3736 "the zgenhostid(8) command.\n"));
3737 break;
3738 case ZPOOL_STATUS_CORRUPT_POOL:
3739 (void) printf(gettext("The pool cannot be imported due "
3740 "to missing or damaged devices. Ensure\n"
3741 "\t%sall devices are present and not in use by "
3742 "another subsystem.\n"), indent);
3743 break;
3744 default:
3745 (void) printf(gettext("The pool cannot be imported due "
3746 "to damaged devices or data.\n"));
3747 }
3748 }
3749
3750 /* Print the comment attached to the pool. */
3751 if (comment != NULL)
3752 (void) printf(gettext("comment: %s\n"), comment);
3753
3754 /*
3755 * If the state is "closed" or "can't open", and the aux state
3756 * is "corrupt data":
3757 */
3758 if ((vs->vs_state == VDEV_STATE_CLOSED ||
3759 vs->vs_state == VDEV_STATE_CANT_OPEN) &&
3760 vs->vs_aux == VDEV_AUX_CORRUPT_DATA) {
3761 if (pool_state == POOL_STATE_DESTROYED)
3762 (void) printf(gettext("\t%sThe pool was destroyed, "
3763 "but can be imported using the '-Df' flags.\n"),
3764 indent);
3765 else if (pool_state != POOL_STATE_EXPORTED)
3766 (void) printf(gettext("\t%sThe pool may be active on "
3767 "another system, but can be imported using\n"
3768 "\t%sthe '-f' flag.\n"), indent, indent);
3769 }
3770
3771 if (msgid != NULL) {
3772 (void) printf(gettext("%s see: "
3773 "https://openzfs.github.io/openzfs-docs/msg/%s\n"),
3774 indent, msgid);
3775 }
3776
3777 (void) printf(gettext("%sconfig:\n\n"), indent);
3778
3779 cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
3780 VDEV_NAME_TYPE_ID);
3781 if (cb.cb_namewidth < 10)
3782 cb.cb_namewidth = 10;
3783
3784 print_import_config(&cb, name, nvroot, 0);
3785
3786 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
3787 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
3788 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
3789
3790 if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
3791 (void) printf(gettext("\n\t%sAdditional devices are known to "
3792 "be part of this pool, though their\n"
3793 "\t%sexact configuration cannot be determined.\n"),
3794 indent, indent);
3795 }
3796 return (0);
3797 }
3798
3799 static boolean_t
zfs_force_import_required(nvlist_t * config)3800 zfs_force_import_required(nvlist_t *config)
3801 {
3802 uint64_t state;
3803 uint64_t hostid = 0;
3804 nvlist_t *nvinfo;
3805
3806 state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
3807 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3808
3809 /*
3810 * The hostid on LOAD_INFO comes from the MOS label via
3811 * spa_tryimport(). If its not there then we're likely talking to an
3812 * older kernel, so use the top one, which will be from the label
3813 * discovered in zpool_find_import(), or if a cachefile is in use, the
3814 * local hostid.
3815 */
3816 if (nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_HOSTID, &hostid) != 0)
3817 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
3818 &hostid);
3819
3820 if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
3821 return (B_TRUE);
3822
3823 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
3824 mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
3825 ZPOOL_CONFIG_MMP_STATE);
3826
3827 if (mmp_state != MMP_STATE_INACTIVE)
3828 return (B_TRUE);
3829 }
3830
3831 return (B_FALSE);
3832 }
3833
3834 /*
3835 * Perform the import for the given configuration. This passes the heavy
3836 * lifting off to zpool_import_props(), and then mounts the datasets contained
3837 * within the pool.
3838 */
3839 static int
do_import(nvlist_t * config,const char * newname,const char * mntopts,nvlist_t * props,int flags,uint_t mntthreads)3840 do_import(nvlist_t *config, const char *newname, const char *mntopts,
3841 nvlist_t *props, int flags, uint_t mntthreads)
3842 {
3843 int ret = 0;
3844 int ms_status = 0;
3845 zpool_handle_t *zhp;
3846 const char *name;
3847 uint64_t version;
3848
3849 name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
3850 version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3851
3852 if (!SPA_VERSION_IS_SUPPORTED(version)) {
3853 (void) fprintf(stderr, gettext("cannot import '%s': pool "
3854 "is formatted using an unsupported ZFS version\n"), name);
3855 return (1);
3856 } else if (zfs_force_import_required(config) &&
3857 !(flags & ZFS_IMPORT_ANY_HOST)) {
3858 mmp_state_t mmp_state = MMP_STATE_INACTIVE;
3859 nvlist_t *nvinfo;
3860
3861 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3862 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
3863 mmp_state = fnvlist_lookup_uint64(nvinfo,
3864 ZPOOL_CONFIG_MMP_STATE);
3865
3866 if (mmp_state == MMP_STATE_ACTIVE) {
3867 const char *hostname = "<unknown>";
3868 uint64_t hostid = 0;
3869
3870 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3871 hostname = fnvlist_lookup_string(nvinfo,
3872 ZPOOL_CONFIG_MMP_HOSTNAME);
3873
3874 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3875 hostid = fnvlist_lookup_uint64(nvinfo,
3876 ZPOOL_CONFIG_MMP_HOSTID);
3877
3878 (void) fprintf(stderr, gettext("cannot import '%s': "
3879 "pool is imported on %s (hostid: "
3880 "0x%"PRIx64")\nExport the pool on the other "
3881 "system, then run 'zpool import'.\n"),
3882 name, hostname, hostid);
3883 } else if (mmp_state == MMP_STATE_NO_HOSTID) {
3884 (void) fprintf(stderr, gettext("Cannot import '%s': "
3885 "pool has the multihost property on and the\n"
3886 "system's hostid is not set. Set a unique hostid "
3887 "with the zgenhostid(8) command.\n"), name);
3888 } else {
3889 const char *hostname = "<unknown>";
3890 time_t timestamp = 0;
3891 uint64_t hostid = 0;
3892
3893 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTNAME))
3894 hostname = fnvlist_lookup_string(nvinfo,
3895 ZPOOL_CONFIG_HOSTNAME);
3896 else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
3897 hostname = fnvlist_lookup_string(config,
3898 ZPOOL_CONFIG_HOSTNAME);
3899
3900 if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
3901 timestamp = fnvlist_lookup_uint64(config,
3902 ZPOOL_CONFIG_TIMESTAMP);
3903
3904 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTID))
3905 hostid = fnvlist_lookup_uint64(nvinfo,
3906 ZPOOL_CONFIG_HOSTID);
3907 else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
3908 hostid = fnvlist_lookup_uint64(config,
3909 ZPOOL_CONFIG_HOSTID);
3910
3911 (void) fprintf(stderr, gettext("cannot import '%s': "
3912 "pool was previously in use from another system.\n"
3913 "Last accessed by %s (hostid=%"PRIx64") at %s"
3914 "The pool can be imported, use 'zpool import -f' "
3915 "to import the pool.\n"), name, hostname,
3916 hostid, ctime(×tamp));
3917 }
3918
3919 if (getenv("ZFS_LOAD_INFO_DEBUG"))
3920 dump_nvlist(nvinfo, 4);
3921
3922 return (1);
3923 }
3924
3925 if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
3926 return (1);
3927
3928 if (newname != NULL)
3929 name = newname;
3930
3931 if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
3932 return (1);
3933
3934 /*
3935 * Loading keys is best effort. We don't want to return immediately
3936 * if it fails but we do want to give the error to the caller.
3937 */
3938 if (flags & ZFS_IMPORT_LOAD_KEYS &&
3939 zfs_crypto_attempt_load_keys(g_zfs, name) != 0)
3940 ret = 1;
3941
3942 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3943 !(flags & ZFS_IMPORT_ONLY)) {
3944 ms_status = zpool_enable_datasets(zhp, mntopts, 0, mntthreads);
3945 if (ms_status == EZFS_SHAREFAILED) {
3946 (void) fprintf(stderr, gettext("Import was "
3947 "successful, but unable to share some datasets\n"));
3948 } else if (ms_status == EZFS_MOUNTFAILED) {
3949 (void) fprintf(stderr, gettext("Import was "
3950 "successful, but unable to mount some datasets\n"));
3951 }
3952 }
3953
3954 zpool_close(zhp);
3955 return (ret);
3956 }
3957
3958 typedef struct import_parameters {
3959 nvlist_t *ip_config;
3960 const char *ip_mntopts;
3961 nvlist_t *ip_props;
3962 int ip_flags;
3963 uint_t ip_mntthreads;
3964 int *ip_err;
3965 } import_parameters_t;
3966
3967 static void
do_import_task(void * arg)3968 do_import_task(void *arg)
3969 {
3970 import_parameters_t *ip = arg;
3971 *ip->ip_err |= do_import(ip->ip_config, NULL, ip->ip_mntopts,
3972 ip->ip_props, ip->ip_flags, ip->ip_mntthreads);
3973 free(ip);
3974 }
3975
3976
3977 static int
import_pools(nvlist_t * pools,nvlist_t * props,char * mntopts,int flags,char * orig_name,char * new_name,importargs_t * import)3978 import_pools(nvlist_t *pools, nvlist_t *props, char *mntopts, int flags,
3979 char *orig_name, char *new_name, importargs_t *import)
3980 {
3981 nvlist_t *config = NULL;
3982 nvlist_t *found_config = NULL;
3983 uint64_t pool_state;
3984 boolean_t pool_specified = (import->poolname != NULL ||
3985 import->guid != 0);
3986 uint_t npools = 0;
3987
3988
3989 taskq_t *tq = NULL;
3990 if (import->do_all) {
3991 tq = taskq_create("zpool_import_all",
3992 5 * sysconf(_SC_NPROCESSORS_ONLN), minclsyspri, 1, INT_MAX,
3993 TASKQ_DYNAMIC);
3994 }
3995
3996 /*
3997 * At this point we have a list of import candidate configs. Even if
3998 * we were searching by pool name or guid, we still need to
3999 * post-process the list to deal with pool state and possible
4000 * duplicate names.
4001 */
4002 int err = 0;
4003 nvpair_t *elem = NULL;
4004 boolean_t first = B_TRUE;
4005 if (!pool_specified && import->do_all) {
4006 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL)
4007 npools++;
4008 }
4009 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
4010
4011 verify(nvpair_value_nvlist(elem, &config) == 0);
4012
4013 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4014 &pool_state) == 0);
4015 if (!import->do_destroyed &&
4016 pool_state == POOL_STATE_DESTROYED)
4017 continue;
4018 if (import->do_destroyed &&
4019 pool_state != POOL_STATE_DESTROYED)
4020 continue;
4021
4022 verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
4023 import->policy) == 0);
4024
4025 if (!pool_specified) {
4026 if (first)
4027 first = B_FALSE;
4028 else if (!import->do_all)
4029 (void) fputc('\n', stdout);
4030
4031 if (import->do_all) {
4032 import_parameters_t *ip = safe_malloc(
4033 sizeof (import_parameters_t));
4034
4035 ip->ip_config = config;
4036 ip->ip_mntopts = mntopts;
4037 ip->ip_props = props;
4038 ip->ip_flags = flags;
4039 ip->ip_mntthreads = mount_tp_nthr / npools;
4040 ip->ip_err = &err;
4041
4042 (void) taskq_dispatch(tq, do_import_task,
4043 (void *)ip, TQ_SLEEP);
4044 } else {
4045 /*
4046 * If we're importing from cachefile, then
4047 * we don't want to report errors until we
4048 * are in the scan phase of the import. If
4049 * we get an error, then we return that error
4050 * to invoke the scan phase.
4051 */
4052 if (import->cachefile && !import->scan)
4053 err = show_import(config, B_FALSE);
4054 else
4055 (void) show_import(config, B_TRUE);
4056 }
4057 } else if (import->poolname != NULL) {
4058 const char *name;
4059
4060 /*
4061 * We are searching for a pool based on name.
4062 */
4063 verify(nvlist_lookup_string(config,
4064 ZPOOL_CONFIG_POOL_NAME, &name) == 0);
4065
4066 if (strcmp(name, import->poolname) == 0) {
4067 if (found_config != NULL) {
4068 (void) fprintf(stderr, gettext(
4069 "cannot import '%s': more than "
4070 "one matching pool\n"),
4071 import->poolname);
4072 (void) fprintf(stderr, gettext(
4073 "import by numeric ID instead\n"));
4074 err = B_TRUE;
4075 }
4076 found_config = config;
4077 }
4078 } else {
4079 uint64_t guid;
4080
4081 /*
4082 * Search for a pool by guid.
4083 */
4084 verify(nvlist_lookup_uint64(config,
4085 ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
4086
4087 if (guid == import->guid)
4088 found_config = config;
4089 }
4090 }
4091 if (import->do_all) {
4092 taskq_wait(tq);
4093 taskq_destroy(tq);
4094 }
4095
4096 /*
4097 * If we were searching for a specific pool, verify that we found a
4098 * pool, and then do the import.
4099 */
4100 if (pool_specified && err == 0) {
4101 if (found_config == NULL) {
4102 (void) fprintf(stderr, gettext("cannot import '%s': "
4103 "no such pool available\n"), orig_name);
4104 err = B_TRUE;
4105 } else {
4106 err |= do_import(found_config, new_name,
4107 mntopts, props, flags, mount_tp_nthr);
4108 }
4109 }
4110
4111 /*
4112 * If we were just looking for pools, report an error if none were
4113 * found.
4114 */
4115 if (!pool_specified && first)
4116 (void) fprintf(stderr,
4117 gettext("no pools available to import\n"));
4118 return (err);
4119 }
4120
4121 typedef struct target_exists_args {
4122 const char *poolname;
4123 uint64_t poolguid;
4124 } target_exists_args_t;
4125
4126 static int
name_or_guid_exists(zpool_handle_t * zhp,void * data)4127 name_or_guid_exists(zpool_handle_t *zhp, void *data)
4128 {
4129 target_exists_args_t *args = data;
4130 nvlist_t *config = zpool_get_config(zhp, NULL);
4131 int found = 0;
4132
4133 if (config == NULL)
4134 return (0);
4135
4136 if (args->poolname != NULL) {
4137 const char *pool_name;
4138
4139 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4140 &pool_name) == 0);
4141 if (strcmp(pool_name, args->poolname) == 0)
4142 found = 1;
4143 } else {
4144 uint64_t pool_guid;
4145
4146 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4147 &pool_guid) == 0);
4148 if (pool_guid == args->poolguid)
4149 found = 1;
4150 }
4151 zpool_close(zhp);
4152
4153 return (found);
4154 }
4155 /*
4156 * zpool checkpoint <pool>
4157 * checkpoint --discard <pool>
4158 *
4159 * -d Discard the checkpoint from a checkpointed
4160 * --discard pool.
4161 *
4162 * -w Wait for discarding a checkpoint to complete.
4163 * --wait
4164 *
4165 * Checkpoints the specified pool, by taking a "snapshot" of its
4166 * current state. A pool can only have one checkpoint at a time.
4167 */
4168 int
zpool_do_checkpoint(int argc,char ** argv)4169 zpool_do_checkpoint(int argc, char **argv)
4170 {
4171 boolean_t discard, wait;
4172 char *pool;
4173 zpool_handle_t *zhp;
4174 int c, err;
4175
4176 struct option long_options[] = {
4177 {"discard", no_argument, NULL, 'd'},
4178 {"wait", no_argument, NULL, 'w'},
4179 {0, 0, 0, 0}
4180 };
4181
4182 discard = B_FALSE;
4183 wait = B_FALSE;
4184 while ((c = getopt_long(argc, argv, ":dw", long_options, NULL)) != -1) {
4185 switch (c) {
4186 case 'd':
4187 discard = B_TRUE;
4188 break;
4189 case 'w':
4190 wait = B_TRUE;
4191 break;
4192 case '?':
4193 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4194 optopt);
4195 usage(B_FALSE);
4196 }
4197 }
4198
4199 if (wait && !discard) {
4200 (void) fprintf(stderr, gettext("--wait only valid when "
4201 "--discard also specified\n"));
4202 usage(B_FALSE);
4203 }
4204
4205 argc -= optind;
4206 argv += optind;
4207
4208 if (argc < 1) {
4209 (void) fprintf(stderr, gettext("missing pool argument\n"));
4210 usage(B_FALSE);
4211 }
4212
4213 if (argc > 1) {
4214 (void) fprintf(stderr, gettext("too many arguments\n"));
4215 usage(B_FALSE);
4216 }
4217
4218 pool = argv[0];
4219
4220 if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
4221 /* As a special case, check for use of '/' in the name */
4222 if (strchr(pool, '/') != NULL)
4223 (void) fprintf(stderr, gettext("'zpool checkpoint' "
4224 "doesn't work on datasets. To save the state "
4225 "of a dataset from a specific point in time "
4226 "please use 'zfs snapshot'\n"));
4227 return (1);
4228 }
4229
4230 if (discard) {
4231 err = (zpool_discard_checkpoint(zhp) != 0);
4232 if (err == 0 && wait)
4233 err = zpool_wait(zhp, ZPOOL_WAIT_CKPT_DISCARD);
4234 } else {
4235 err = (zpool_checkpoint(zhp) != 0);
4236 }
4237
4238 zpool_close(zhp);
4239
4240 return (err);
4241 }
4242
4243 #define CHECKPOINT_OPT 1024
4244
4245 /*
4246 * zpool prefetch [-t <type>] <pool>
4247 *
4248 * Prefetchs a particular type of data in the specified pool.
4249 */
4250 int
zpool_do_prefetch(int argc,char ** argv)4251 zpool_do_prefetch(int argc, char **argv)
4252 {
4253 int c;
4254 char *poolname;
4255 char *typestr = NULL;
4256 zpool_prefetch_type_t type;
4257 zpool_handle_t *zhp;
4258 int err = 0;
4259
4260 while ((c = getopt(argc, argv, "t:")) != -1) {
4261 switch (c) {
4262 case 't':
4263 typestr = optarg;
4264 break;
4265 case ':':
4266 (void) fprintf(stderr, gettext("missing argument for "
4267 "'%c' option\n"), optopt);
4268 usage(B_FALSE);
4269 break;
4270 case '?':
4271 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4272 optopt);
4273 usage(B_FALSE);
4274 }
4275 }
4276 argc -= optind;
4277 argv += optind;
4278
4279 if (argc < 1) {
4280 (void) fprintf(stderr, gettext("missing pool name argument\n"));
4281 usage(B_FALSE);
4282 }
4283
4284 if (argc > 1) {
4285 (void) fprintf(stderr, gettext("too many arguments\n"));
4286 usage(B_FALSE);
4287 }
4288
4289 poolname = argv[0];
4290
4291 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
4292 return (1);
4293
4294 if (typestr == NULL) {
4295 /* Prefetch all types */
4296 err = zpool_prefetch(zhp, ZPOOL_PREFETCH_DDT);
4297 if (err == 0)
4298 err = zpool_prefetch(zhp, ZPOOL_PREFETCH_BRT);
4299 } else {
4300 if (strcmp(typestr, "ddt") == 0) {
4301 type = ZPOOL_PREFETCH_DDT;
4302 } else if (strcmp(typestr, "brt") == 0) {
4303 type = ZPOOL_PREFETCH_BRT;
4304 } else {
4305 (void) fprintf(stderr,
4306 gettext("unsupported prefetch type\n"));
4307 zpool_close(zhp);
4308 usage(B_FALSE);
4309 }
4310 err = zpool_prefetch(zhp, type);
4311 }
4312
4313 zpool_close(zhp);
4314
4315 return (err);
4316 }
4317
4318 /*
4319 * zpool import [-d dir] [-D]
4320 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4321 * [-d dir | -c cachefile | -s] [-f] -a
4322 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4323 * [-d dir | -c cachefile | -s] [-f] [-n] [-F] <pool | id>
4324 * [newpool]
4325 *
4326 * -c Read pool information from a cachefile instead of searching
4327 * devices. If importing from a cachefile config fails, then
4328 * fallback to searching for devices only in the directories that
4329 * exist in the cachefile.
4330 *
4331 * -d Scan in a specific directory, other than /dev/. More than
4332 * one directory can be specified using multiple '-d' options.
4333 *
4334 * -D Scan for previously destroyed pools or import all or only
4335 * specified destroyed pools.
4336 *
4337 * -R Temporarily import the pool, with all mountpoints relative to
4338 * the given root. The pool will remain exported when the machine
4339 * is rebooted.
4340 *
4341 * -V Import even in the presence of faulted vdevs. This is an
4342 * intentionally undocumented option for testing purposes, and
4343 * treats the pool configuration as complete, leaving any bad
4344 * vdevs in the FAULTED state. In other words, it does verbatim
4345 * import.
4346 *
4347 * -f Force import, even if it appears that the pool is active.
4348 *
4349 * -F Attempt rewind if necessary.
4350 *
4351 * -n See if rewind would work, but don't actually rewind.
4352 *
4353 * -N Import the pool but don't mount datasets.
4354 *
4355 * -T Specify a starting txg to use for import. This option is
4356 * intentionally undocumented option for testing purposes.
4357 *
4358 * -a Import all pools found.
4359 *
4360 * -l Load encryption keys while importing.
4361 *
4362 * -o Set property=value and/or temporary mount options (without '=').
4363 *
4364 * -s Scan using the default search path, the libblkid cache will
4365 * not be consulted.
4366 *
4367 * --rewind-to-checkpoint
4368 * Import the pool and revert back to the checkpoint.
4369 *
4370 * The import command scans for pools to import, and import pools based on pool
4371 * name and GUID. The pool can also be renamed as part of the import process.
4372 */
4373 int
zpool_do_import(int argc,char ** argv)4374 zpool_do_import(int argc, char **argv)
4375 {
4376 char **searchdirs = NULL;
4377 char *env, *envdup = NULL;
4378 int nsearch = 0;
4379 int c;
4380 int err = 0;
4381 nvlist_t *pools = NULL;
4382 boolean_t do_all = B_FALSE;
4383 boolean_t do_destroyed = B_FALSE;
4384 char *mntopts = NULL;
4385 uint64_t searchguid = 0;
4386 char *searchname = NULL;
4387 char *propval;
4388 nvlist_t *policy = NULL;
4389 nvlist_t *props = NULL;
4390 int flags = ZFS_IMPORT_NORMAL;
4391 uint32_t rewind_policy = ZPOOL_NO_REWIND;
4392 boolean_t dryrun = B_FALSE;
4393 boolean_t do_rewind = B_FALSE;
4394 boolean_t xtreme_rewind = B_FALSE;
4395 boolean_t do_scan = B_FALSE;
4396 boolean_t pool_exists = B_FALSE;
4397 uint64_t txg = -1ULL;
4398 char *cachefile = NULL;
4399 importargs_t idata = { 0 };
4400 char *endptr;
4401
4402 struct option long_options[] = {
4403 {"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
4404 {0, 0, 0, 0}
4405 };
4406
4407 /* check options */
4408 while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmnNo:R:stT:VX",
4409 long_options, NULL)) != -1) {
4410 switch (c) {
4411 case 'a':
4412 do_all = B_TRUE;
4413 break;
4414 case 'c':
4415 cachefile = optarg;
4416 break;
4417 case 'd':
4418 searchdirs = safe_realloc(searchdirs,
4419 (nsearch + 1) * sizeof (char *));
4420 searchdirs[nsearch++] = optarg;
4421 break;
4422 case 'D':
4423 do_destroyed = B_TRUE;
4424 break;
4425 case 'f':
4426 flags |= ZFS_IMPORT_ANY_HOST;
4427 break;
4428 case 'F':
4429 do_rewind = B_TRUE;
4430 break;
4431 case 'l':
4432 flags |= ZFS_IMPORT_LOAD_KEYS;
4433 break;
4434 case 'm':
4435 flags |= ZFS_IMPORT_MISSING_LOG;
4436 break;
4437 case 'n':
4438 dryrun = B_TRUE;
4439 break;
4440 case 'N':
4441 flags |= ZFS_IMPORT_ONLY;
4442 break;
4443 case 'o':
4444 if ((propval = strchr(optarg, '=')) != NULL) {
4445 *propval = '\0';
4446 propval++;
4447 if (add_prop_list(optarg, propval,
4448 &props, B_TRUE))
4449 goto error;
4450 } else {
4451 mntopts = optarg;
4452 }
4453 break;
4454 case 'R':
4455 if (add_prop_list(zpool_prop_to_name(
4456 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
4457 goto error;
4458 if (add_prop_list_default(zpool_prop_to_name(
4459 ZPOOL_PROP_CACHEFILE), "none", &props))
4460 goto error;
4461 break;
4462 case 's':
4463 do_scan = B_TRUE;
4464 break;
4465 case 't':
4466 flags |= ZFS_IMPORT_TEMP_NAME;
4467 if (add_prop_list_default(zpool_prop_to_name(
4468 ZPOOL_PROP_CACHEFILE), "none", &props))
4469 goto error;
4470 break;
4471
4472 case 'T':
4473 errno = 0;
4474 txg = strtoull(optarg, &endptr, 0);
4475 if (errno != 0 || *endptr != '\0') {
4476 (void) fprintf(stderr,
4477 gettext("invalid txg value\n"));
4478 usage(B_FALSE);
4479 }
4480 rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
4481 break;
4482 case 'V':
4483 flags |= ZFS_IMPORT_VERBATIM;
4484 break;
4485 case 'X':
4486 xtreme_rewind = B_TRUE;
4487 break;
4488 case CHECKPOINT_OPT:
4489 flags |= ZFS_IMPORT_CHECKPOINT;
4490 break;
4491 case ':':
4492 (void) fprintf(stderr, gettext("missing argument for "
4493 "'%c' option\n"), optopt);
4494 usage(B_FALSE);
4495 break;
4496 case '?':
4497 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4498 optopt);
4499 usage(B_FALSE);
4500 }
4501 }
4502
4503 argc -= optind;
4504 argv += optind;
4505
4506 if (cachefile && nsearch != 0) {
4507 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
4508 usage(B_FALSE);
4509 }
4510
4511 if (cachefile && do_scan) {
4512 (void) fprintf(stderr, gettext("-c is incompatible with -s\n"));
4513 usage(B_FALSE);
4514 }
4515
4516 if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
4517 (void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
4518 usage(B_FALSE);
4519 }
4520
4521 if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
4522 (void) fprintf(stderr, gettext("-l is only meaningful during "
4523 "an import\n"));
4524 usage(B_FALSE);
4525 }
4526
4527 if ((dryrun || xtreme_rewind) && !do_rewind) {
4528 (void) fprintf(stderr,
4529 gettext("-n or -X only meaningful with -F\n"));
4530 usage(B_FALSE);
4531 }
4532 if (dryrun)
4533 rewind_policy = ZPOOL_TRY_REWIND;
4534 else if (do_rewind)
4535 rewind_policy = ZPOOL_DO_REWIND;
4536 if (xtreme_rewind)
4537 rewind_policy |= ZPOOL_EXTREME_REWIND;
4538
4539 /* In the future, we can capture further policy and include it here */
4540 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
4541 nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
4542 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
4543 rewind_policy) != 0)
4544 goto error;
4545
4546 /* check argument count */
4547 if (do_all) {
4548 if (argc != 0) {
4549 (void) fprintf(stderr, gettext("too many arguments\n"));
4550 usage(B_FALSE);
4551 }
4552 } else {
4553 if (argc > 2) {
4554 (void) fprintf(stderr, gettext("too many arguments\n"));
4555 usage(B_FALSE);
4556 }
4557 }
4558
4559 /*
4560 * Check for the effective uid. We do this explicitly here because
4561 * otherwise any attempt to discover pools will silently fail.
4562 */
4563 if (argc == 0 && geteuid() != 0) {
4564 (void) fprintf(stderr, gettext("cannot "
4565 "discover pools: permission denied\n"));
4566
4567 free(searchdirs);
4568 nvlist_free(props);
4569 nvlist_free(policy);
4570 return (1);
4571 }
4572
4573 /*
4574 * Depending on the arguments given, we do one of the following:
4575 *
4576 * <none> Iterate through all pools and display information about
4577 * each one.
4578 *
4579 * -a Iterate through all pools and try to import each one.
4580 *
4581 * <id> Find the pool that corresponds to the given GUID/pool
4582 * name and import that one.
4583 *
4584 * -D Above options applies only to destroyed pools.
4585 */
4586 if (argc != 0) {
4587 char *endptr;
4588
4589 errno = 0;
4590 searchguid = strtoull(argv[0], &endptr, 10);
4591 if (errno != 0 || *endptr != '\0') {
4592 searchname = argv[0];
4593 searchguid = 0;
4594 }
4595
4596 /*
4597 * User specified a name or guid. Ensure it's unique.
4598 */
4599 target_exists_args_t search = {searchname, searchguid};
4600 pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
4601 }
4602
4603 /*
4604 * Check the environment for the preferred search path.
4605 */
4606 if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
4607 char *dir, *tmp = NULL;
4608
4609 envdup = strdup(env);
4610
4611 for (dir = strtok_r(envdup, ":", &tmp);
4612 dir != NULL;
4613 dir = strtok_r(NULL, ":", &tmp)) {
4614 searchdirs = safe_realloc(searchdirs,
4615 (nsearch + 1) * sizeof (char *));
4616 searchdirs[nsearch++] = dir;
4617 }
4618 }
4619
4620 idata.path = searchdirs;
4621 idata.paths = nsearch;
4622 idata.poolname = searchname;
4623 idata.guid = searchguid;
4624 idata.cachefile = cachefile;
4625 idata.scan = do_scan;
4626 idata.policy = policy;
4627 idata.do_destroyed = do_destroyed;
4628 idata.do_all = do_all;
4629
4630 libpc_handle_t lpch = {
4631 .lpc_lib_handle = g_zfs,
4632 .lpc_ops = &libzfs_config_ops,
4633 .lpc_printerr = B_TRUE
4634 };
4635 pools = zpool_search_import(&lpch, &idata);
4636
4637 if (pools != NULL && pool_exists &&
4638 (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
4639 (void) fprintf(stderr, gettext("cannot import '%s': "
4640 "a pool with that name already exists\n"),
4641 argv[0]);
4642 (void) fprintf(stderr, gettext("use the form '%s "
4643 "<pool | id> <newpool>' to give it a new name\n"),
4644 "zpool import");
4645 err = 1;
4646 } else if (pools == NULL && pool_exists) {
4647 (void) fprintf(stderr, gettext("cannot import '%s': "
4648 "a pool with that name is already created/imported,\n"),
4649 argv[0]);
4650 (void) fprintf(stderr, gettext("and no additional pools "
4651 "with that name were found\n"));
4652 err = 1;
4653 } else if (pools == NULL) {
4654 if (argc != 0) {
4655 (void) fprintf(stderr, gettext("cannot import '%s': "
4656 "no such pool available\n"), argv[0]);
4657 }
4658 err = 1;
4659 }
4660
4661 if (err == 1) {
4662 free(searchdirs);
4663 free(envdup);
4664 nvlist_free(policy);
4665 nvlist_free(pools);
4666 nvlist_free(props);
4667 return (1);
4668 }
4669
4670 err = import_pools(pools, props, mntopts, flags,
4671 argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL, &idata);
4672
4673 /*
4674 * If we're using the cachefile and we failed to import, then
4675 * fallback to scanning the directory for pools that match
4676 * those in the cachefile.
4677 */
4678 if (err != 0 && cachefile != NULL) {
4679 (void) printf(gettext("cachefile import failed, retrying\n"));
4680
4681 /*
4682 * We use the scan flag to gather the directories that exist
4683 * in the cachefile. If we need to fallback to searching for
4684 * the pool config, we will only search devices in these
4685 * directories.
4686 */
4687 idata.scan = B_TRUE;
4688 nvlist_free(pools);
4689 pools = zpool_search_import(&lpch, &idata);
4690
4691 err = import_pools(pools, props, mntopts, flags,
4692 argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL,
4693 &idata);
4694 }
4695
4696 error:
4697 nvlist_free(props);
4698 nvlist_free(pools);
4699 nvlist_free(policy);
4700 free(searchdirs);
4701 free(envdup);
4702
4703 return (err ? 1 : 0);
4704 }
4705
4706 /*
4707 * zpool sync [-f] [pool] ...
4708 *
4709 * -f (undocumented) force uberblock (and config including zpool cache file)
4710 * update.
4711 *
4712 * Sync the specified pool(s).
4713 * Without arguments "zpool sync" will sync all pools.
4714 * This command initiates TXG sync(s) and will return after the TXG(s) commit.
4715 *
4716 */
4717 static int
zpool_do_sync(int argc,char ** argv)4718 zpool_do_sync(int argc, char **argv)
4719 {
4720 int ret;
4721 boolean_t force = B_FALSE;
4722
4723 /* check options */
4724 while ((ret = getopt(argc, argv, "f")) != -1) {
4725 switch (ret) {
4726 case 'f':
4727 force = B_TRUE;
4728 break;
4729 case '?':
4730 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4731 optopt);
4732 usage(B_FALSE);
4733 }
4734 }
4735
4736 argc -= optind;
4737 argv += optind;
4738
4739 /* if argc == 0 we will execute zpool_sync_one on all pools */
4740 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
4741 B_FALSE, zpool_sync_one, &force);
4742
4743 return (ret);
4744 }
4745
4746 typedef struct iostat_cbdata {
4747 uint64_t cb_flags;
4748 int cb_namewidth;
4749 int cb_iteration;
4750 boolean_t cb_verbose;
4751 boolean_t cb_literal;
4752 boolean_t cb_scripted;
4753 zpool_list_t *cb_list;
4754 vdev_cmd_data_list_t *vcdl;
4755 vdev_cbdata_t cb_vdevs;
4756 } iostat_cbdata_t;
4757
4758 /* iostat labels */
4759 typedef struct name_and_columns {
4760 const char *name; /* Column name */
4761 unsigned int columns; /* Center name to this number of columns */
4762 } name_and_columns_t;
4763
4764 #define IOSTAT_MAX_LABELS 15 /* Max number of labels on one line */
4765
4766 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
4767 {
4768 [IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
4769 {NULL}},
4770 [IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4771 {"asyncq_wait", 2}, {"scrub", 1}, {"trim", 1}, {"rebuild", 1},
4772 {NULL}},
4773 [IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
4774 {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
4775 {"trimq_write", 2}, {"rebuildq_write", 2}, {NULL}},
4776 [IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4777 {"asyncq_wait", 2}, {NULL}},
4778 [IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
4779 {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
4780 {"trim", 2}, {"rebuild", 2}, {NULL}},
4781 };
4782
4783 /* Shorthand - if "columns" field not set, default to 1 column */
4784 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
4785 {
4786 [IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
4787 {"write"}, {NULL}},
4788 [IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4789 {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {"wait"},
4790 {NULL}},
4791 [IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
4792 {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
4793 {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
4794 [IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4795 {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {"rebuild"},
4796 {NULL}},
4797 [IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4798 {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4799 {"ind"}, {"agg"}, {NULL}},
4800 };
4801
4802 static const char *histo_to_title[] = {
4803 [IOS_L_HISTO] = "latency",
4804 [IOS_RQ_HISTO] = "req_size",
4805 };
4806
4807 /*
4808 * Return the number of labels in a null-terminated name_and_columns_t
4809 * array.
4810 *
4811 */
4812 static unsigned int
label_array_len(const name_and_columns_t * labels)4813 label_array_len(const name_and_columns_t *labels)
4814 {
4815 int i = 0;
4816
4817 while (labels[i].name)
4818 i++;
4819
4820 return (i);
4821 }
4822
4823 /*
4824 * Return the number of strings in a null-terminated string array.
4825 * For example:
4826 *
4827 * const char foo[] = {"bar", "baz", NULL}
4828 *
4829 * returns 2
4830 */
4831 static uint64_t
str_array_len(const char * array[])4832 str_array_len(const char *array[])
4833 {
4834 uint64_t i = 0;
4835 while (array[i])
4836 i++;
4837
4838 return (i);
4839 }
4840
4841
4842 /*
4843 * Return a default column width for default/latency/queue columns. This does
4844 * not include histograms, which have their columns autosized.
4845 */
4846 static unsigned int
default_column_width(iostat_cbdata_t * cb,enum iostat_type type)4847 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
4848 {
4849 unsigned long column_width = 5; /* Normal niceprint */
4850 static unsigned long widths[] = {
4851 /*
4852 * Choose some sane default column sizes for printing the
4853 * raw numbers.
4854 */
4855 [IOS_DEFAULT] = 15, /* 1PB capacity */
4856 [IOS_LATENCY] = 10, /* 1B ns = 10sec */
4857 [IOS_QUEUES] = 6, /* 1M queue entries */
4858 [IOS_L_HISTO] = 10, /* 1B ns = 10sec */
4859 [IOS_RQ_HISTO] = 6, /* 1M queue entries */
4860 };
4861
4862 if (cb->cb_literal)
4863 column_width = widths[type];
4864
4865 return (column_width);
4866 }
4867
4868 /*
4869 * Print the column labels, i.e:
4870 *
4871 * capacity operations bandwidth
4872 * alloc free read write read write ...
4873 *
4874 * If force_column_width is set, use it for the column width. If not set, use
4875 * the default column width.
4876 */
4877 static void
print_iostat_labels(iostat_cbdata_t * cb,unsigned int force_column_width,const name_and_columns_t labels[][IOSTAT_MAX_LABELS])4878 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
4879 const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
4880 {
4881 int i, idx, s;
4882 int text_start, rw_column_width, spaces_to_end;
4883 uint64_t flags = cb->cb_flags;
4884 uint64_t f;
4885 unsigned int column_width = force_column_width;
4886
4887 /* For each bit set in flags */
4888 for (f = flags; f; f &= ~(1ULL << idx)) {
4889 idx = lowbit64(f) - 1;
4890 if (!force_column_width)
4891 column_width = default_column_width(cb, idx);
4892 /* Print our top labels centered over "read write" label. */
4893 for (i = 0; i < label_array_len(labels[idx]); i++) {
4894 const char *name = labels[idx][i].name;
4895 /*
4896 * We treat labels[][].columns == 0 as shorthand
4897 * for one column. It makes writing out the label
4898 * tables more concise.
4899 */
4900 unsigned int columns = MAX(1, labels[idx][i].columns);
4901 unsigned int slen = strlen(name);
4902
4903 rw_column_width = (column_width * columns) +
4904 (2 * (columns - 1));
4905
4906 text_start = (int)((rw_column_width) / columns -
4907 slen / columns);
4908 if (text_start < 0)
4909 text_start = 0;
4910
4911 printf(" "); /* Two spaces between columns */
4912
4913 /* Space from beginning of column to label */
4914 for (s = 0; s < text_start; s++)
4915 printf(" ");
4916
4917 printf("%s", name);
4918
4919 /* Print space after label to end of column */
4920 spaces_to_end = rw_column_width - text_start - slen;
4921 if (spaces_to_end < 0)
4922 spaces_to_end = 0;
4923
4924 for (s = 0; s < spaces_to_end; s++)
4925 printf(" ");
4926 }
4927 }
4928 }
4929
4930
4931 /*
4932 * print_cmd_columns - Print custom column titles from -c
4933 *
4934 * If the user specified the "zpool status|iostat -c" then print their custom
4935 * column titles in the header. For example, print_cmd_columns() would print
4936 * the " col1 col2" part of this:
4937 *
4938 * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
4939 * ...
4940 * capacity operations bandwidth
4941 * pool alloc free read write read write col1 col2
4942 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4943 * mypool 269K 1008M 0 0 107 946
4944 * mirror 269K 1008M 0 0 107 946
4945 * sdb - - 0 0 102 473 val1 val2
4946 * sdc - - 0 0 5 473 val1 val2
4947 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4948 */
4949 static void
print_cmd_columns(vdev_cmd_data_list_t * vcdl,int use_dashes)4950 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
4951 {
4952 int i, j;
4953 vdev_cmd_data_t *data = &vcdl->data[0];
4954
4955 if (vcdl->count == 0 || data == NULL)
4956 return;
4957
4958 /*
4959 * Each vdev cmd should have the same column names unless the user did
4960 * something weird with their cmd. Just take the column names from the
4961 * first vdev and assume it works for all of them.
4962 */
4963 for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
4964 printf(" ");
4965 if (use_dashes) {
4966 for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
4967 printf("-");
4968 } else {
4969 (void) printf_color(ANSI_BOLD, "%*s",
4970 vcdl->uniq_cols_width[i],
4971 vcdl->uniq_cols[i]);
4972 }
4973 }
4974 }
4975
4976
4977 /*
4978 * Utility function to print out a line of dashes like:
4979 *
4980 * -------------------------------- ----- ----- ----- ----- -----
4981 *
4982 * ...or a dashed named-row line like:
4983 *
4984 * logs - - - - -
4985 *
4986 * @cb: iostat data
4987 *
4988 * @force_column_width If non-zero, use the value as the column width.
4989 * Otherwise use the default column widths.
4990 *
4991 * @name: Print a dashed named-row line starting
4992 * with @name. Otherwise, print a regular
4993 * dashed line.
4994 */
4995 static void
print_iostat_dashes(iostat_cbdata_t * cb,unsigned int force_column_width,const char * name)4996 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
4997 const char *name)
4998 {
4999 int i;
5000 unsigned int namewidth;
5001 uint64_t flags = cb->cb_flags;
5002 uint64_t f;
5003 int idx;
5004 const name_and_columns_t *labels;
5005 const char *title;
5006
5007
5008 if (cb->cb_flags & IOS_ANYHISTO_M) {
5009 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
5010 } else if (cb->cb_vdevs.cb_names_count) {
5011 title = "vdev";
5012 } else {
5013 title = "pool";
5014 }
5015
5016 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
5017 name ? strlen(name) : 0);
5018
5019
5020 if (name) {
5021 printf("%-*s", namewidth, name);
5022 } else {
5023 for (i = 0; i < namewidth; i++)
5024 (void) printf("-");
5025 }
5026
5027 /* For each bit in flags */
5028 for (f = flags; f; f &= ~(1ULL << idx)) {
5029 unsigned int column_width;
5030 idx = lowbit64(f) - 1;
5031 if (force_column_width)
5032 column_width = force_column_width;
5033 else
5034 column_width = default_column_width(cb, idx);
5035
5036 labels = iostat_bottom_labels[idx];
5037 for (i = 0; i < label_array_len(labels); i++) {
5038 if (name)
5039 printf(" %*s-", column_width - 1, " ");
5040 else
5041 printf(" %.*s", column_width,
5042 "--------------------");
5043 }
5044 }
5045 }
5046
5047
5048 static void
print_iostat_separator_impl(iostat_cbdata_t * cb,unsigned int force_column_width)5049 print_iostat_separator_impl(iostat_cbdata_t *cb,
5050 unsigned int force_column_width)
5051 {
5052 print_iostat_dashes(cb, force_column_width, NULL);
5053 }
5054
5055 static void
print_iostat_separator(iostat_cbdata_t * cb)5056 print_iostat_separator(iostat_cbdata_t *cb)
5057 {
5058 print_iostat_separator_impl(cb, 0);
5059 }
5060
5061 static void
print_iostat_header_impl(iostat_cbdata_t * cb,unsigned int force_column_width,const char * histo_vdev_name)5062 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
5063 const char *histo_vdev_name)
5064 {
5065 unsigned int namewidth;
5066 const char *title;
5067
5068 color_start(ANSI_BOLD);
5069
5070 if (cb->cb_flags & IOS_ANYHISTO_M) {
5071 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
5072 } else if (cb->cb_vdevs.cb_names_count) {
5073 title = "vdev";
5074 } else {
5075 title = "pool";
5076 }
5077
5078 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
5079 histo_vdev_name ? strlen(histo_vdev_name) : 0);
5080
5081 if (histo_vdev_name)
5082 printf("%-*s", namewidth, histo_vdev_name);
5083 else
5084 printf("%*s", namewidth, "");
5085
5086
5087 print_iostat_labels(cb, force_column_width, iostat_top_labels);
5088 printf("\n");
5089
5090 printf("%-*s", namewidth, title);
5091
5092 print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
5093 if (cb->vcdl != NULL)
5094 print_cmd_columns(cb->vcdl, 0);
5095
5096 printf("\n");
5097
5098 print_iostat_separator_impl(cb, force_column_width);
5099
5100 if (cb->vcdl != NULL)
5101 print_cmd_columns(cb->vcdl, 1);
5102
5103 color_end();
5104
5105 printf("\n");
5106 }
5107
5108 static void
print_iostat_header(iostat_cbdata_t * cb)5109 print_iostat_header(iostat_cbdata_t *cb)
5110 {
5111 print_iostat_header_impl(cb, 0, NULL);
5112 }
5113
5114 /*
5115 * Prints a size string (i.e. 120M) with the suffix ("M") colored
5116 * by order of magnitude. Uses column_size to add padding.
5117 */
5118 static void
print_stat_color(const char * statbuf,unsigned int column_size)5119 print_stat_color(const char *statbuf, unsigned int column_size)
5120 {
5121 (void) fputs(" ", stdout);
5122 size_t len = strlen(statbuf);
5123 while (len < column_size) {
5124 (void) fputc(' ', stdout);
5125 column_size--;
5126 }
5127 if (*statbuf == '0') {
5128 color_start(ANSI_GRAY);
5129 (void) fputc('0', stdout);
5130 } else {
5131 for (; *statbuf; statbuf++) {
5132 if (*statbuf == 'K') color_start(ANSI_GREEN);
5133 else if (*statbuf == 'M') color_start(ANSI_YELLOW);
5134 else if (*statbuf == 'G') color_start(ANSI_RED);
5135 else if (*statbuf == 'T') color_start(ANSI_BOLD_BLUE);
5136 else if (*statbuf == 'P') color_start(ANSI_MAGENTA);
5137 else if (*statbuf == 'E') color_start(ANSI_CYAN);
5138 (void) fputc(*statbuf, stdout);
5139 if (--column_size <= 0)
5140 break;
5141 }
5142 }
5143 color_end();
5144 }
5145
5146 /*
5147 * Display a single statistic.
5148 */
5149 static void
print_one_stat(uint64_t value,enum zfs_nicenum_format format,unsigned int column_size,boolean_t scripted)5150 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
5151 unsigned int column_size, boolean_t scripted)
5152 {
5153 char buf[64];
5154
5155 zfs_nicenum_format(value, buf, sizeof (buf), format);
5156
5157 if (scripted)
5158 printf("\t%s", buf);
5159 else
5160 print_stat_color(buf, column_size);
5161 }
5162
5163 /*
5164 * Calculate the default vdev stats
5165 *
5166 * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
5167 * stats into calcvs.
5168 */
5169 static void
calc_default_iostats(vdev_stat_t * oldvs,vdev_stat_t * newvs,vdev_stat_t * calcvs)5170 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
5171 vdev_stat_t *calcvs)
5172 {
5173 int i;
5174
5175 memcpy(calcvs, newvs, sizeof (*calcvs));
5176 for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
5177 calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
5178
5179 for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
5180 calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
5181 }
5182
5183 /*
5184 * Internal representation of the extended iostats data.
5185 *
5186 * The extended iostat stats are exported in nvlists as either uint64_t arrays
5187 * or single uint64_t's. We make both look like arrays to make them easier
5188 * to process. In order to make single uint64_t's look like arrays, we set
5189 * __data to the stat data, and then set *data = &__data with count = 1. Then,
5190 * we can just use *data and count.
5191 */
5192 struct stat_array {
5193 uint64_t *data;
5194 uint_t count; /* Number of entries in data[] */
5195 uint64_t __data; /* Only used when data is a single uint64_t */
5196 };
5197
5198 static uint64_t
stat_histo_max(struct stat_array * nva,unsigned int len)5199 stat_histo_max(struct stat_array *nva, unsigned int len)
5200 {
5201 uint64_t max = 0;
5202 int i;
5203 for (i = 0; i < len; i++)
5204 max = MAX(max, array64_max(nva[i].data, nva[i].count));
5205
5206 return (max);
5207 }
5208
5209 /*
5210 * Helper function to lookup a uint64_t array or uint64_t value and store its
5211 * data as a stat_array. If the nvpair is a single uint64_t value, then we make
5212 * it look like a one element array to make it easier to process.
5213 */
5214 static int
nvpair64_to_stat_array(nvlist_t * nvl,const char * name,struct stat_array * nva)5215 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
5216 struct stat_array *nva)
5217 {
5218 nvpair_t *tmp;
5219 int ret;
5220
5221 verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
5222 switch (nvpair_type(tmp)) {
5223 case DATA_TYPE_UINT64_ARRAY:
5224 ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
5225 break;
5226 case DATA_TYPE_UINT64:
5227 ret = nvpair_value_uint64(tmp, &nva->__data);
5228 nva->data = &nva->__data;
5229 nva->count = 1;
5230 break;
5231 default:
5232 /* Not a uint64_t */
5233 ret = EINVAL;
5234 break;
5235 }
5236
5237 return (ret);
5238 }
5239
5240 /*
5241 * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
5242 * subtract them, and return the results in a newly allocated stat_array.
5243 * You must free the returned array after you are done with it with
5244 * free_calc_stats().
5245 *
5246 * Additionally, you can set "oldnv" to NULL if you simply want the newnv
5247 * values.
5248 */
5249 static struct stat_array *
calc_and_alloc_stats_ex(const char ** names,unsigned int len,nvlist_t * oldnv,nvlist_t * newnv)5250 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
5251 nvlist_t *newnv)
5252 {
5253 nvlist_t *oldnvx = NULL, *newnvx;
5254 struct stat_array *oldnva, *newnva, *calcnva;
5255 int i, j;
5256 unsigned int alloc_size = (sizeof (struct stat_array)) * len;
5257
5258 /* Extract our extended stats nvlist from the main list */
5259 verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5260 &newnvx) == 0);
5261 if (oldnv) {
5262 verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5263 &oldnvx) == 0);
5264 }
5265
5266 newnva = safe_malloc(alloc_size);
5267 oldnva = safe_malloc(alloc_size);
5268 calcnva = safe_malloc(alloc_size);
5269
5270 for (j = 0; j < len; j++) {
5271 verify(nvpair64_to_stat_array(newnvx, names[j],
5272 &newnva[j]) == 0);
5273 calcnva[j].count = newnva[j].count;
5274 alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
5275 calcnva[j].data = safe_malloc(alloc_size);
5276 memcpy(calcnva[j].data, newnva[j].data, alloc_size);
5277
5278 if (oldnvx) {
5279 verify(nvpair64_to_stat_array(oldnvx, names[j],
5280 &oldnva[j]) == 0);
5281 for (i = 0; i < oldnva[j].count; i++)
5282 calcnva[j].data[i] -= oldnva[j].data[i];
5283 }
5284 }
5285 free(newnva);
5286 free(oldnva);
5287 return (calcnva);
5288 }
5289
5290 static void
free_calc_stats(struct stat_array * nva,unsigned int len)5291 free_calc_stats(struct stat_array *nva, unsigned int len)
5292 {
5293 int i;
5294 for (i = 0; i < len; i++)
5295 free(nva[i].data);
5296
5297 free(nva);
5298 }
5299
5300 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)5301 print_iostat_histo(struct stat_array *nva, unsigned int len,
5302 iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
5303 double scale)
5304 {
5305 int i, j;
5306 char buf[6];
5307 uint64_t val;
5308 enum zfs_nicenum_format format;
5309 unsigned int buckets;
5310 unsigned int start_bucket;
5311
5312 if (cb->cb_literal)
5313 format = ZFS_NICENUM_RAW;
5314 else
5315 format = ZFS_NICENUM_1024;
5316
5317 /* All these histos are the same size, so just use nva[0].count */
5318 buckets = nva[0].count;
5319
5320 if (cb->cb_flags & IOS_RQ_HISTO_M) {
5321 /* Start at 512 - req size should never be lower than this */
5322 start_bucket = 9;
5323 } else {
5324 start_bucket = 0;
5325 }
5326
5327 for (j = start_bucket; j < buckets; j++) {
5328 /* Print histogram bucket label */
5329 if (cb->cb_flags & IOS_L_HISTO_M) {
5330 /* Ending range of this bucket */
5331 val = (1UL << (j + 1)) - 1;
5332 zfs_nicetime(val, buf, sizeof (buf));
5333 } else {
5334 /* Request size (starting range of bucket) */
5335 val = (1UL << j);
5336 zfs_nicenum(val, buf, sizeof (buf));
5337 }
5338
5339 if (cb->cb_scripted)
5340 printf("%llu", (u_longlong_t)val);
5341 else
5342 printf("%-*s", namewidth, buf);
5343
5344 /* Print the values on the line */
5345 for (i = 0; i < len; i++) {
5346 print_one_stat(nva[i].data[j] * scale, format,
5347 column_width, cb->cb_scripted);
5348 }
5349 printf("\n");
5350 }
5351 }
5352
5353 static void
print_solid_separator(unsigned int length)5354 print_solid_separator(unsigned int length)
5355 {
5356 while (length--)
5357 printf("-");
5358 printf("\n");
5359 }
5360
5361 static void
print_iostat_histos(iostat_cbdata_t * cb,nvlist_t * oldnv,nvlist_t * newnv,double scale,const char * name)5362 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
5363 nvlist_t *newnv, double scale, const char *name)
5364 {
5365 unsigned int column_width;
5366 unsigned int namewidth;
5367 unsigned int entire_width;
5368 enum iostat_type type;
5369 struct stat_array *nva;
5370 const char **names;
5371 unsigned int names_len;
5372
5373 /* What type of histo are we? */
5374 type = IOS_HISTO_IDX(cb->cb_flags);
5375
5376 /* Get NULL-terminated array of nvlist names for our histo */
5377 names = vsx_type_to_nvlist[type];
5378 names_len = str_array_len(names); /* num of names */
5379
5380 nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
5381
5382 if (cb->cb_literal) {
5383 column_width = MAX(5,
5384 (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
5385 } else {
5386 column_width = 5;
5387 }
5388
5389 namewidth = MAX(cb->cb_namewidth,
5390 strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
5391
5392 /*
5393 * Calculate the entire line width of what we're printing. The
5394 * +2 is for the two spaces between columns:
5395 */
5396 /* read write */
5397 /* ----- ----- */
5398 /* |___| <---------- column_width */
5399 /* */
5400 /* |__________| <--- entire_width */
5401 /* */
5402 entire_width = namewidth + (column_width + 2) *
5403 label_array_len(iostat_bottom_labels[type]);
5404
5405 if (cb->cb_scripted)
5406 printf("%s\n", name);
5407 else
5408 print_iostat_header_impl(cb, column_width, name);
5409
5410 print_iostat_histo(nva, names_len, cb, column_width,
5411 namewidth, scale);
5412
5413 free_calc_stats(nva, names_len);
5414 if (!cb->cb_scripted)
5415 print_solid_separator(entire_width);
5416 }
5417
5418 /*
5419 * Calculate the average latency of a power-of-two latency histogram
5420 */
5421 static uint64_t
single_histo_average(uint64_t * histo,unsigned int buckets)5422 single_histo_average(uint64_t *histo, unsigned int buckets)
5423 {
5424 int i;
5425 uint64_t count = 0, total = 0;
5426
5427 for (i = 0; i < buckets; i++) {
5428 /*
5429 * Our buckets are power-of-two latency ranges. Use the
5430 * midpoint latency of each bucket to calculate the average.
5431 * For example:
5432 *
5433 * Bucket Midpoint
5434 * 8ns-15ns: 12ns
5435 * 16ns-31ns: 24ns
5436 * ...
5437 */
5438 if (histo[i] != 0) {
5439 total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
5440 count += histo[i];
5441 }
5442 }
5443
5444 /* Prevent divide by zero */
5445 return (count == 0 ? 0 : total / count);
5446 }
5447
5448 static void
print_iostat_queues(iostat_cbdata_t * cb,nvlist_t * newnv)5449 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *newnv)
5450 {
5451 const char *names[] = {
5452 ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
5453 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
5454 ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
5455 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
5456 ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
5457 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
5458 ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
5459 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
5460 ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
5461 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
5462 ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
5463 ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
5464 ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
5465 ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
5466 };
5467
5468 struct stat_array *nva;
5469
5470 unsigned int column_width = default_column_width(cb, IOS_QUEUES);
5471 enum zfs_nicenum_format format;
5472
5473 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
5474
5475 if (cb->cb_literal)
5476 format = ZFS_NICENUM_RAW;
5477 else
5478 format = ZFS_NICENUM_1024;
5479
5480 for (int i = 0; i < ARRAY_SIZE(names); i++) {
5481 uint64_t val = nva[i].data[0];
5482 print_one_stat(val, format, column_width, cb->cb_scripted);
5483 }
5484
5485 free_calc_stats(nva, ARRAY_SIZE(names));
5486 }
5487
5488 static void
print_iostat_latency(iostat_cbdata_t * cb,nvlist_t * oldnv,nvlist_t * newnv)5489 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
5490 nvlist_t *newnv)
5491 {
5492 int i;
5493 uint64_t val;
5494 const char *names[] = {
5495 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
5496 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
5497 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
5498 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
5499 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
5500 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
5501 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
5502 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
5503 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
5504 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
5505 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
5506 };
5507 struct stat_array *nva;
5508
5509 unsigned int column_width = default_column_width(cb, IOS_LATENCY);
5510 enum zfs_nicenum_format format;
5511
5512 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
5513
5514 if (cb->cb_literal)
5515 format = ZFS_NICENUM_RAWTIME;
5516 else
5517 format = ZFS_NICENUM_TIME;
5518
5519 /* Print our avg latencies on the line */
5520 for (i = 0; i < ARRAY_SIZE(names); i++) {
5521 /* Compute average latency for a latency histo */
5522 val = single_histo_average(nva[i].data, nva[i].count);
5523 print_one_stat(val, format, column_width, cb->cb_scripted);
5524 }
5525 free_calc_stats(nva, ARRAY_SIZE(names));
5526 }
5527
5528 /*
5529 * Print default statistics (capacity/operations/bandwidth)
5530 */
5531 static void
print_iostat_default(vdev_stat_t * vs,iostat_cbdata_t * cb,double scale)5532 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
5533 {
5534 unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
5535 enum zfs_nicenum_format format;
5536 char na; /* char to print for "not applicable" values */
5537
5538 if (cb->cb_literal) {
5539 format = ZFS_NICENUM_RAW;
5540 na = '0';
5541 } else {
5542 format = ZFS_NICENUM_1024;
5543 na = '-';
5544 }
5545
5546 /* only toplevel vdevs have capacity stats */
5547 if (vs->vs_space == 0) {
5548 if (cb->cb_scripted)
5549 printf("\t%c\t%c", na, na);
5550 else
5551 printf(" %*c %*c", column_width, na, column_width,
5552 na);
5553 } else {
5554 print_one_stat(vs->vs_alloc, format, column_width,
5555 cb->cb_scripted);
5556 print_one_stat(vs->vs_space - vs->vs_alloc, format,
5557 column_width, cb->cb_scripted);
5558 }
5559
5560 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
5561 format, column_width, cb->cb_scripted);
5562 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
5563 format, column_width, cb->cb_scripted);
5564 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
5565 format, column_width, cb->cb_scripted);
5566 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
5567 format, column_width, cb->cb_scripted);
5568 }
5569
5570 static const char *const class_name[] = {
5571 VDEV_ALLOC_BIAS_DEDUP,
5572 VDEV_ALLOC_BIAS_SPECIAL,
5573 VDEV_ALLOC_CLASS_LOGS
5574 };
5575
5576 /*
5577 * Print out all the statistics for the given vdev. This can either be the
5578 * toplevel configuration, or called recursively. If 'name' is NULL, then this
5579 * is a verbose output, and we don't want to display the toplevel pool stats.
5580 *
5581 * Returns the number of stat lines printed.
5582 */
5583 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)5584 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
5585 nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
5586 {
5587 nvlist_t **oldchild, **newchild;
5588 uint_t c, children, oldchildren;
5589 vdev_stat_t *oldvs, *newvs, *calcvs;
5590 vdev_stat_t zerovs = { 0 };
5591 char *vname;
5592 int i;
5593 int ret = 0;
5594 uint64_t tdelta;
5595 double scale;
5596
5597 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
5598 return (ret);
5599
5600 calcvs = safe_malloc(sizeof (*calcvs));
5601
5602 if (oldnv != NULL) {
5603 verify(nvlist_lookup_uint64_array(oldnv,
5604 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
5605 } else {
5606 oldvs = &zerovs;
5607 }
5608
5609 /* Do we only want to see a specific vdev? */
5610 for (i = 0; i < cb->cb_vdevs.cb_names_count; i++) {
5611 /* Yes we do. Is this the vdev? */
5612 if (strcmp(name, cb->cb_vdevs.cb_names[i]) == 0) {
5613 /*
5614 * This is our vdev. Since it is the only vdev we
5615 * will be displaying, make depth = 0 so that it
5616 * doesn't get indented.
5617 */
5618 depth = 0;
5619 break;
5620 }
5621 }
5622
5623 if (cb->cb_vdevs.cb_names_count && (i == cb->cb_vdevs.cb_names_count)) {
5624 /* Couldn't match the name */
5625 goto children;
5626 }
5627
5628
5629 verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
5630 (uint64_t **)&newvs, &c) == 0);
5631
5632 /*
5633 * Print the vdev name unless it's is a histogram. Histograms
5634 * display the vdev name in the header itself.
5635 */
5636 if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
5637 if (cb->cb_scripted) {
5638 printf("%s", name);
5639 } else {
5640 if (strlen(name) + depth > cb->cb_namewidth)
5641 (void) printf("%*s%s", depth, "", name);
5642 else
5643 (void) printf("%*s%s%*s", depth, "", name,
5644 (int)(cb->cb_namewidth - strlen(name) -
5645 depth), "");
5646 }
5647 }
5648
5649 /* Calculate our scaling factor */
5650 tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
5651 if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
5652 /*
5653 * If we specify printing histograms with no time interval, then
5654 * print the histogram numbers over the entire lifetime of the
5655 * vdev.
5656 */
5657 scale = 1;
5658 } else {
5659 if (tdelta == 0)
5660 scale = 1.0;
5661 else
5662 scale = (double)NANOSEC / tdelta;
5663 }
5664
5665 if (cb->cb_flags & IOS_DEFAULT_M) {
5666 calc_default_iostats(oldvs, newvs, calcvs);
5667 print_iostat_default(calcvs, cb, scale);
5668 }
5669 if (cb->cb_flags & IOS_LATENCY_M)
5670 print_iostat_latency(cb, oldnv, newnv);
5671 if (cb->cb_flags & IOS_QUEUES_M)
5672 print_iostat_queues(cb, newnv);
5673 if (cb->cb_flags & IOS_ANYHISTO_M) {
5674 printf("\n");
5675 print_iostat_histos(cb, oldnv, newnv, scale, name);
5676 }
5677
5678 if (cb->vcdl != NULL) {
5679 const char *path;
5680 if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
5681 &path) == 0) {
5682 printf(" ");
5683 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
5684 }
5685 }
5686
5687 if (!(cb->cb_flags & IOS_ANYHISTO_M))
5688 printf("\n");
5689
5690 ret++;
5691
5692 children:
5693
5694 free(calcvs);
5695
5696 if (!cb->cb_verbose)
5697 return (ret);
5698
5699 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
5700 &newchild, &children) != 0)
5701 return (ret);
5702
5703 if (oldnv) {
5704 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
5705 &oldchild, &oldchildren) != 0)
5706 return (ret);
5707
5708 children = MIN(oldchildren, children);
5709 }
5710
5711 /*
5712 * print normal top-level devices
5713 */
5714 for (c = 0; c < children; c++) {
5715 uint64_t ishole = B_FALSE, islog = B_FALSE;
5716
5717 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
5718 &ishole);
5719
5720 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
5721 &islog);
5722
5723 if (ishole || islog)
5724 continue;
5725
5726 if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
5727 continue;
5728
5729 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5730 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5731 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
5732 newchild[c], cb, depth + 2);
5733 free(vname);
5734 }
5735
5736 /*
5737 * print all other top-level devices
5738 */
5739 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
5740 boolean_t printed = B_FALSE;
5741
5742 for (c = 0; c < children; c++) {
5743 uint64_t islog = B_FALSE;
5744 const char *bias = NULL;
5745 const char *type = NULL;
5746
5747 (void) nvlist_lookup_uint64(newchild[c],
5748 ZPOOL_CONFIG_IS_LOG, &islog);
5749 if (islog) {
5750 bias = VDEV_ALLOC_CLASS_LOGS;
5751 } else {
5752 (void) nvlist_lookup_string(newchild[c],
5753 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
5754 (void) nvlist_lookup_string(newchild[c],
5755 ZPOOL_CONFIG_TYPE, &type);
5756 }
5757 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
5758 continue;
5759 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
5760 continue;
5761
5762 if (!printed) {
5763 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
5764 !cb->cb_scripted &&
5765 !cb->cb_vdevs.cb_names) {
5766 print_iostat_dashes(cb, 0,
5767 class_name[n]);
5768 }
5769 printf("\n");
5770 printed = B_TRUE;
5771 }
5772
5773 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5774 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5775 ret += print_vdev_stats(zhp, vname, oldnv ?
5776 oldchild[c] : NULL, newchild[c], cb, depth + 2);
5777 free(vname);
5778 }
5779 }
5780
5781 /*
5782 * Include level 2 ARC devices in iostat output
5783 */
5784 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
5785 &newchild, &children) != 0)
5786 return (ret);
5787
5788 if (oldnv) {
5789 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
5790 &oldchild, &oldchildren) != 0)
5791 return (ret);
5792
5793 children = MIN(oldchildren, children);
5794 }
5795
5796 if (children > 0) {
5797 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
5798 !cb->cb_vdevs.cb_names) {
5799 print_iostat_dashes(cb, 0, "cache");
5800 }
5801 printf("\n");
5802
5803 for (c = 0; c < children; c++) {
5804 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5805 cb->cb_vdevs.cb_name_flags);
5806 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
5807 : NULL, newchild[c], cb, depth + 2);
5808 free(vname);
5809 }
5810 }
5811
5812 return (ret);
5813 }
5814
5815 /*
5816 * Callback to print out the iostats for the given pool.
5817 */
5818 static int
print_iostat(zpool_handle_t * zhp,void * data)5819 print_iostat(zpool_handle_t *zhp, void *data)
5820 {
5821 iostat_cbdata_t *cb = data;
5822 nvlist_t *oldconfig, *newconfig;
5823 nvlist_t *oldnvroot, *newnvroot;
5824 int ret;
5825
5826 newconfig = zpool_get_config(zhp, &oldconfig);
5827
5828 if (cb->cb_iteration == 1)
5829 oldconfig = NULL;
5830
5831 verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
5832 &newnvroot) == 0);
5833
5834 if (oldconfig == NULL)
5835 oldnvroot = NULL;
5836 else
5837 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
5838 &oldnvroot) == 0);
5839
5840 ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
5841 cb, 0);
5842 if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
5843 !cb->cb_scripted && cb->cb_verbose &&
5844 !cb->cb_vdevs.cb_names_count) {
5845 print_iostat_separator(cb);
5846 if (cb->vcdl != NULL) {
5847 print_cmd_columns(cb->vcdl, 1);
5848 }
5849 printf("\n");
5850 }
5851
5852 return (ret);
5853 }
5854
5855 static int
get_columns(void)5856 get_columns(void)
5857 {
5858 struct winsize ws;
5859 int columns = 80;
5860 int error;
5861
5862 if (isatty(STDOUT_FILENO)) {
5863 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
5864 if (error == 0)
5865 columns = ws.ws_col;
5866 } else {
5867 columns = 999;
5868 }
5869
5870 return (columns);
5871 }
5872
5873 /*
5874 * Return the required length of the pool/vdev name column. The minimum
5875 * allowed width and output formatting flags must be provided.
5876 */
5877 static int
get_namewidth(zpool_handle_t * zhp,int min_width,int flags,boolean_t verbose)5878 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
5879 {
5880 nvlist_t *config, *nvroot;
5881 int width = min_width;
5882
5883 if ((config = zpool_get_config(zhp, NULL)) != NULL) {
5884 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5885 &nvroot) == 0);
5886 size_t poolname_len = strlen(zpool_get_name(zhp));
5887 if (verbose == B_FALSE) {
5888 width = MAX(poolname_len, min_width);
5889 } else {
5890 width = MAX(poolname_len,
5891 max_width(zhp, nvroot, 0, min_width, flags));
5892 }
5893 }
5894
5895 return (width);
5896 }
5897
5898 /*
5899 * Parse the input string, get the 'interval' and 'count' value if there is one.
5900 */
5901 static void
get_interval_count(int * argcp,char ** argv,float * iv,unsigned long * cnt)5902 get_interval_count(int *argcp, char **argv, float *iv,
5903 unsigned long *cnt)
5904 {
5905 float interval = 0;
5906 unsigned long count = 0;
5907 int argc = *argcp;
5908
5909 /*
5910 * Determine if the last argument is an integer or a pool name
5911 */
5912 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5913 char *end;
5914
5915 errno = 0;
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 * Ignore the last parameter
5926 */
5927 argc--;
5928 } else {
5929 /*
5930 * If this is not a valid number, just plow on. The
5931 * user will get a more informative error message later
5932 * on.
5933 */
5934 interval = 0;
5935 }
5936 }
5937
5938 /*
5939 * If the last argument is also an integer, then we have both a count
5940 * and an interval.
5941 */
5942 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5943 char *end;
5944
5945 errno = 0;
5946 count = interval;
5947 interval = strtof(argv[argc - 1], &end);
5948
5949 if (*end == '\0' && errno == 0) {
5950 if (interval == 0) {
5951 (void) fprintf(stderr, gettext(
5952 "interval cannot be zero\n"));
5953 usage(B_FALSE);
5954 }
5955
5956 /*
5957 * Ignore the last parameter
5958 */
5959 argc--;
5960 } else {
5961 interval = 0;
5962 }
5963 }
5964
5965 *iv = interval;
5966 *cnt = count;
5967 *argcp = argc;
5968 }
5969
5970 static void
get_timestamp_arg(char c)5971 get_timestamp_arg(char c)
5972 {
5973 if (c == 'u')
5974 timestamp_fmt = UDATE;
5975 else if (c == 'd')
5976 timestamp_fmt = DDATE;
5977 else
5978 usage(B_FALSE);
5979 }
5980
5981 /*
5982 * Return stat flags that are supported by all pools by both the module and
5983 * zpool iostat. "*data" should be initialized to all 0xFFs before running.
5984 * It will get ANDed down until only the flags that are supported on all pools
5985 * remain.
5986 */
5987 static int
get_stat_flags_cb(zpool_handle_t * zhp,void * data)5988 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
5989 {
5990 uint64_t *mask = data;
5991 nvlist_t *config, *nvroot, *nvx;
5992 uint64_t flags = 0;
5993 int i, j;
5994
5995 config = zpool_get_config(zhp, NULL);
5996 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5997 &nvroot) == 0);
5998
5999 /* Default stats are always supported, but for completeness.. */
6000 if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
6001 flags |= IOS_DEFAULT_M;
6002
6003 /* Get our extended stats nvlist from the main list */
6004 if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
6005 &nvx) != 0) {
6006 /*
6007 * No extended stats; they're probably running an older
6008 * module. No big deal, we support that too.
6009 */
6010 goto end;
6011 }
6012
6013 /* For each extended stat, make sure all its nvpairs are supported */
6014 for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
6015 if (!vsx_type_to_nvlist[j][0])
6016 continue;
6017
6018 /* Start off by assuming the flag is supported, then check */
6019 flags |= (1ULL << j);
6020 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
6021 if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
6022 /* flag isn't supported */
6023 flags = flags & ~(1ULL << j);
6024 break;
6025 }
6026 }
6027 }
6028 end:
6029 *mask = *mask & flags;
6030 return (0);
6031 }
6032
6033 /*
6034 * Return a bitmask of stats that are supported on all pools by both the module
6035 * and zpool iostat.
6036 */
6037 static uint64_t
get_stat_flags(zpool_list_t * list)6038 get_stat_flags(zpool_list_t *list)
6039 {
6040 uint64_t mask = -1;
6041
6042 /*
6043 * get_stat_flags_cb() will lop off bits from "mask" until only the
6044 * flags that are supported on all pools remain.
6045 */
6046 (void) pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
6047 return (mask);
6048 }
6049
6050 /*
6051 * Return 1 if cb_data->cb_names[0] is this vdev's name, 0 otherwise.
6052 */
6053 static int
is_vdev_cb(void * zhp_data,nvlist_t * nv,void * cb_data)6054 is_vdev_cb(void *zhp_data, nvlist_t *nv, void *cb_data)
6055 {
6056 uint64_t guid;
6057 vdev_cbdata_t *cb = cb_data;
6058 zpool_handle_t *zhp = zhp_data;
6059
6060 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
6061 return (0);
6062
6063 return (guid == zpool_vdev_path_to_guid(zhp, cb->cb_names[0]));
6064 }
6065
6066 /*
6067 * Returns 1 if cb_data->cb_names[0] is a vdev name, 0 otherwise.
6068 */
6069 static int
is_vdev(zpool_handle_t * zhp,void * cb_data)6070 is_vdev(zpool_handle_t *zhp, void *cb_data)
6071 {
6072 return (for_each_vdev(zhp, is_vdev_cb, cb_data));
6073 }
6074
6075 /*
6076 * Check if vdevs are in a pool
6077 *
6078 * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
6079 * return 0. If pool_name is NULL, then search all pools.
6080 */
6081 static int
are_vdevs_in_pool(int argc,char ** argv,char * pool_name,vdev_cbdata_t * cb)6082 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
6083 vdev_cbdata_t *cb)
6084 {
6085 char **tmp_name;
6086 int ret = 0;
6087 int i;
6088 int pool_count = 0;
6089
6090 if ((argc == 0) || !*argv)
6091 return (0);
6092
6093 if (pool_name)
6094 pool_count = 1;
6095
6096 /* Temporarily hijack cb_names for a second... */
6097 tmp_name = cb->cb_names;
6098
6099 /* Go though our list of prospective vdev names */
6100 for (i = 0; i < argc; i++) {
6101 cb->cb_names = argv + i;
6102
6103 /* Is this name a vdev in our pools? */
6104 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
6105 ZFS_TYPE_POOL, B_FALSE, is_vdev, cb);
6106 if (!ret) {
6107 /* No match */
6108 break;
6109 }
6110 }
6111
6112 cb->cb_names = tmp_name;
6113
6114 return (ret);
6115 }
6116
6117 static int
is_pool_cb(zpool_handle_t * zhp,void * data)6118 is_pool_cb(zpool_handle_t *zhp, void *data)
6119 {
6120 char *name = data;
6121 if (strcmp(name, zpool_get_name(zhp)) == 0)
6122 return (1);
6123
6124 return (0);
6125 }
6126
6127 /*
6128 * Do we have a pool named *name? If so, return 1, otherwise 0.
6129 */
6130 static int
is_pool(char * name)6131 is_pool(char *name)
6132 {
6133 return (for_each_pool(0, NULL, B_TRUE, NULL, ZFS_TYPE_POOL, B_FALSE,
6134 is_pool_cb, name));
6135 }
6136
6137 /* Are all our argv[] strings pool names? If so return 1, 0 otherwise. */
6138 static int
are_all_pools(int argc,char ** argv)6139 are_all_pools(int argc, char **argv)
6140 {
6141 if ((argc == 0) || !*argv)
6142 return (0);
6143
6144 while (--argc >= 0)
6145 if (!is_pool(argv[argc]))
6146 return (0);
6147
6148 return (1);
6149 }
6150
6151 /*
6152 * Helper function to print out vdev/pool names we can't resolve. Used for an
6153 * error message.
6154 */
6155 static void
error_list_unresolved_vdevs(int argc,char ** argv,char * pool_name,vdev_cbdata_t * cb)6156 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
6157 vdev_cbdata_t *cb)
6158 {
6159 int i;
6160 char *name;
6161 char *str;
6162 for (i = 0; i < argc; i++) {
6163 name = argv[i];
6164
6165 if (is_pool(name))
6166 str = gettext("pool");
6167 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
6168 str = gettext("vdev in this pool");
6169 else if (are_vdevs_in_pool(1, &name, NULL, cb))
6170 str = gettext("vdev in another pool");
6171 else
6172 str = gettext("unknown");
6173
6174 fprintf(stderr, "\t%s (%s)\n", name, str);
6175 }
6176 }
6177
6178 /*
6179 * Same as get_interval_count(), but with additional checks to not misinterpret
6180 * guids as interval/count values. Assumes VDEV_NAME_GUID is set in
6181 * cb.cb_vdevs.cb_name_flags.
6182 */
6183 static void
get_interval_count_filter_guids(int * argc,char ** argv,float * interval,unsigned long * count,iostat_cbdata_t * cb)6184 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
6185 unsigned long *count, iostat_cbdata_t *cb)
6186 {
6187 int argc_for_interval = 0;
6188
6189 /* Is the last arg an interval value? Or a guid? */
6190 if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL,
6191 &cb->cb_vdevs)) {
6192 /*
6193 * The last arg is not a guid, so it's probably an
6194 * interval value.
6195 */
6196 argc_for_interval++;
6197
6198 if (*argc >= 2 &&
6199 !are_vdevs_in_pool(1, &argv[*argc - 2], NULL,
6200 &cb->cb_vdevs)) {
6201 /*
6202 * The 2nd to last arg is not a guid, so it's probably
6203 * an interval value.
6204 */
6205 argc_for_interval++;
6206 }
6207 }
6208
6209 /* Point to our list of possible intervals */
6210 char **tmpargv = &argv[*argc - argc_for_interval];
6211
6212 *argc = *argc - argc_for_interval;
6213 get_interval_count(&argc_for_interval, tmpargv,
6214 interval, count);
6215 }
6216
6217 /*
6218 * Terminal height, in rows. Returns -1 if stdout is not connected to a TTY or
6219 * if we were unable to determine its size.
6220 */
6221 static int
terminal_height(void)6222 terminal_height(void)
6223 {
6224 struct winsize win;
6225
6226 if (isatty(STDOUT_FILENO) == 0)
6227 return (-1);
6228
6229 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_row > 0)
6230 return (win.ws_row);
6231
6232 return (-1);
6233 }
6234
6235 /*
6236 * Run one of the zpool status/iostat -c scripts with the help (-h) option and
6237 * print the result.
6238 *
6239 * name: Short name of the script ('iostat').
6240 * path: Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
6241 */
6242 static void
print_zpool_script_help(char * name,char * path)6243 print_zpool_script_help(char *name, char *path)
6244 {
6245 char *argv[] = {path, (char *)"-h", NULL};
6246 char **lines = NULL;
6247 int lines_cnt = 0;
6248 int rc;
6249
6250 rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
6251 &lines_cnt);
6252 if (rc != 0 || lines == NULL || lines_cnt <= 0) {
6253 if (lines != NULL)
6254 libzfs_free_str_array(lines, lines_cnt);
6255 return;
6256 }
6257
6258 for (int i = 0; i < lines_cnt; i++)
6259 if (!is_blank_str(lines[i]))
6260 printf(" %-14s %s\n", name, lines[i]);
6261
6262 libzfs_free_str_array(lines, lines_cnt);
6263 }
6264
6265 /*
6266 * Go though the zpool status/iostat -c scripts in the user's path, run their
6267 * help option (-h), and print out the results.
6268 */
6269 static void
print_zpool_dir_scripts(char * dirpath)6270 print_zpool_dir_scripts(char *dirpath)
6271 {
6272 DIR *dir;
6273 struct dirent *ent;
6274 char fullpath[MAXPATHLEN];
6275 struct stat dir_stat;
6276
6277 if ((dir = opendir(dirpath)) != NULL) {
6278 /* print all the files and directories within directory */
6279 while ((ent = readdir(dir)) != NULL) {
6280 if (snprintf(fullpath, sizeof (fullpath), "%s/%s",
6281 dirpath, ent->d_name) >= sizeof (fullpath)) {
6282 (void) fprintf(stderr,
6283 gettext("internal error: "
6284 "ZPOOL_SCRIPTS_PATH too large.\n"));
6285 exit(1);
6286 }
6287
6288 /* Print the scripts */
6289 if (stat(fullpath, &dir_stat) == 0)
6290 if (dir_stat.st_mode & S_IXUSR &&
6291 S_ISREG(dir_stat.st_mode))
6292 print_zpool_script_help(ent->d_name,
6293 fullpath);
6294 }
6295 (void) closedir(dir);
6296 }
6297 }
6298
6299 /*
6300 * Print out help text for all zpool status/iostat -c scripts.
6301 */
6302 static void
print_zpool_script_list(const char * subcommand)6303 print_zpool_script_list(const char *subcommand)
6304 {
6305 char *dir, *sp, *tmp;
6306
6307 printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
6308
6309 sp = zpool_get_cmd_search_path();
6310 if (sp == NULL)
6311 return;
6312
6313 for (dir = strtok_r(sp, ":", &tmp);
6314 dir != NULL;
6315 dir = strtok_r(NULL, ":", &tmp))
6316 print_zpool_dir_scripts(dir);
6317
6318 free(sp);
6319 }
6320
6321 /*
6322 * Set the minimum pool/vdev name column width. The width must be at least 10,
6323 * but may be as large as the column width - 42 so it still fits on one line.
6324 * NOTE: 42 is the width of the default capacity/operations/bandwidth output
6325 */
6326 static int
get_namewidth_iostat(zpool_handle_t * zhp,void * data)6327 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
6328 {
6329 iostat_cbdata_t *cb = data;
6330 int width, available_width;
6331
6332 /*
6333 * get_namewidth() returns the maximum width of any name in that column
6334 * for any pool/vdev/device line that will be output.
6335 */
6336 width = get_namewidth(zhp, cb->cb_namewidth,
6337 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
6338
6339 /*
6340 * The width we are calculating is the width of the header and also the
6341 * padding width for names that are less than maximum width. The stats
6342 * take up 42 characters, so the width available for names is:
6343 */
6344 available_width = get_columns() - 42;
6345
6346 /*
6347 * If the maximum width fits on a screen, then great! Make everything
6348 * line up by justifying all lines to the same width. If that max
6349 * width is larger than what's available, the name plus stats won't fit
6350 * on one line, and justifying to that width would cause every line to
6351 * wrap on the screen. We only want lines with long names to wrap.
6352 * Limit the padding to what won't wrap.
6353 */
6354 if (width > available_width)
6355 width = available_width;
6356
6357 /*
6358 * And regardless of whatever the screen width is (get_columns can
6359 * return 0 if the width is not known or less than 42 for a narrow
6360 * terminal) have the width be a minimum of 10.
6361 */
6362 if (width < 10)
6363 width = 10;
6364
6365 /* Save the calculated width */
6366 cb->cb_namewidth = width;
6367
6368 return (0);
6369 }
6370
6371 /*
6372 * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
6373 * [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
6374 * [interval [count]]
6375 *
6376 * -c CMD For each vdev, run command CMD
6377 * -g Display guid for individual vdev name.
6378 * -L Follow links when resolving vdev path name.
6379 * -P Display full path for vdev name.
6380 * -v Display statistics for individual vdevs
6381 * -h Display help
6382 * -p Display values in parsable (exact) format.
6383 * -H Scripted mode. Don't display headers, and separate properties
6384 * by a single tab.
6385 * -l Display average latency
6386 * -q Display queue depths
6387 * -w Display latency histograms
6388 * -r Display request size histogram
6389 * -T Display a timestamp in date(1) or Unix format
6390 * -n Only print headers once
6391 *
6392 * This command can be tricky because we want to be able to deal with pool
6393 * creation/destruction as well as vdev configuration changes. The bulk of this
6394 * processing is handled by the pool_list_* routines in zpool_iter.c. We rely
6395 * on pool_list_refresh() to detect the addition and removal of pools.
6396 * Configuration changes are all handled within libzfs.
6397 */
6398 int
zpool_do_iostat(int argc,char ** argv)6399 zpool_do_iostat(int argc, char **argv)
6400 {
6401 int c;
6402 int ret;
6403 float interval = 0;
6404 unsigned long count = 0;
6405 zpool_list_t *list;
6406 boolean_t verbose = B_FALSE;
6407 boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
6408 boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
6409 boolean_t omit_since_boot = B_FALSE;
6410 boolean_t guid = B_FALSE;
6411 boolean_t follow_links = B_FALSE;
6412 boolean_t full_name = B_FALSE;
6413 boolean_t headers_once = B_FALSE;
6414 iostat_cbdata_t cb = { 0 };
6415 char *cmd = NULL;
6416
6417 /* Used for printing error message */
6418 const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
6419 [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
6420
6421 uint64_t unsupported_flags;
6422
6423 /* check options */
6424 while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwnH")) != -1) {
6425 switch (c) {
6426 case 'c':
6427 if (cmd != NULL) {
6428 fprintf(stderr,
6429 gettext("Can't set -c flag twice\n"));
6430 exit(1);
6431 }
6432
6433 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
6434 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
6435 fprintf(stderr, gettext(
6436 "Can't run -c, disabled by "
6437 "ZPOOL_SCRIPTS_ENABLED.\n"));
6438 exit(1);
6439 }
6440
6441 if ((getuid() <= 0 || geteuid() <= 0) &&
6442 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
6443 fprintf(stderr, gettext(
6444 "Can't run -c with root privileges "
6445 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
6446 exit(1);
6447 }
6448 cmd = optarg;
6449 verbose = B_TRUE;
6450 break;
6451 case 'g':
6452 guid = B_TRUE;
6453 break;
6454 case 'L':
6455 follow_links = B_TRUE;
6456 break;
6457 case 'P':
6458 full_name = B_TRUE;
6459 break;
6460 case 'T':
6461 get_timestamp_arg(*optarg);
6462 break;
6463 case 'v':
6464 verbose = B_TRUE;
6465 break;
6466 case 'p':
6467 parsable = B_TRUE;
6468 break;
6469 case 'l':
6470 latency = B_TRUE;
6471 break;
6472 case 'q':
6473 queues = B_TRUE;
6474 break;
6475 case 'H':
6476 scripted = B_TRUE;
6477 break;
6478 case 'w':
6479 l_histo = B_TRUE;
6480 break;
6481 case 'r':
6482 rq_histo = B_TRUE;
6483 break;
6484 case 'y':
6485 omit_since_boot = B_TRUE;
6486 break;
6487 case 'n':
6488 headers_once = B_TRUE;
6489 break;
6490 case 'h':
6491 usage(B_FALSE);
6492 break;
6493 case '?':
6494 if (optopt == 'c') {
6495 print_zpool_script_list("iostat");
6496 exit(0);
6497 } else {
6498 fprintf(stderr,
6499 gettext("invalid option '%c'\n"), optopt);
6500 }
6501 usage(B_FALSE);
6502 }
6503 }
6504
6505 argc -= optind;
6506 argv += optind;
6507
6508 cb.cb_literal = parsable;
6509 cb.cb_scripted = scripted;
6510
6511 if (guid)
6512 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_GUID;
6513 if (follow_links)
6514 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6515 if (full_name)
6516 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_PATH;
6517 cb.cb_iteration = 0;
6518 cb.cb_namewidth = 0;
6519 cb.cb_verbose = verbose;
6520
6521 /* Get our interval and count values (if any) */
6522 if (guid) {
6523 get_interval_count_filter_guids(&argc, argv, &interval,
6524 &count, &cb);
6525 } else {
6526 get_interval_count(&argc, argv, &interval, &count);
6527 }
6528
6529 if (argc == 0) {
6530 /* No args, so just print the defaults. */
6531 } else if (are_all_pools(argc, argv)) {
6532 /* All the args are pool names */
6533 } else if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
6534 /* All the args are vdevs */
6535 cb.cb_vdevs.cb_names = argv;
6536 cb.cb_vdevs.cb_names_count = argc;
6537 argc = 0; /* No pools to process */
6538 } else if (are_all_pools(1, argv)) {
6539 /* The first arg is a pool name */
6540 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
6541 &cb.cb_vdevs)) {
6542 /* ...and the rest are vdev names */
6543 cb.cb_vdevs.cb_names = argv + 1;
6544 cb.cb_vdevs.cb_names_count = argc - 1;
6545 argc = 1; /* One pool to process */
6546 } else {
6547 fprintf(stderr, gettext("Expected either a list of "));
6548 fprintf(stderr, gettext("pools, or list of vdevs in"));
6549 fprintf(stderr, " \"%s\", ", argv[0]);
6550 fprintf(stderr, gettext("but got:\n"));
6551 error_list_unresolved_vdevs(argc - 1, argv + 1,
6552 argv[0], &cb.cb_vdevs);
6553 fprintf(stderr, "\n");
6554 usage(B_FALSE);
6555 }
6556 } else {
6557 /*
6558 * The args don't make sense. The first arg isn't a pool name,
6559 * nor are all the args vdevs.
6560 */
6561 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
6562 fprintf(stderr, "\n");
6563 return (1);
6564 }
6565
6566 if (cb.cb_vdevs.cb_names_count != 0) {
6567 /*
6568 * If user specified vdevs, it implies verbose.
6569 */
6570 cb.cb_verbose = B_TRUE;
6571 }
6572
6573 /*
6574 * Construct the list of all interesting pools.
6575 */
6576 ret = 0;
6577 if ((list = pool_list_get(argc, argv, NULL, ZFS_TYPE_POOL, parsable,
6578 &ret)) == NULL)
6579 return (1);
6580
6581 if (pool_list_count(list) == 0 && argc != 0) {
6582 pool_list_free(list);
6583 return (1);
6584 }
6585
6586 if (pool_list_count(list) == 0 && interval == 0) {
6587 pool_list_free(list);
6588 (void) fprintf(stderr, gettext("no pools available\n"));
6589 return (1);
6590 }
6591
6592 if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
6593 pool_list_free(list);
6594 (void) fprintf(stderr,
6595 gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
6596 usage(B_FALSE);
6597 }
6598
6599 if (l_histo && rq_histo) {
6600 pool_list_free(list);
6601 (void) fprintf(stderr,
6602 gettext("Only one of [-r|-w] can be passed at a time\n"));
6603 usage(B_FALSE);
6604 }
6605
6606 /*
6607 * Enter the main iostat loop.
6608 */
6609 cb.cb_list = list;
6610
6611 if (l_histo) {
6612 /*
6613 * Histograms tables look out of place when you try to display
6614 * them with the other stats, so make a rule that you can only
6615 * print histograms by themselves.
6616 */
6617 cb.cb_flags = IOS_L_HISTO_M;
6618 } else if (rq_histo) {
6619 cb.cb_flags = IOS_RQ_HISTO_M;
6620 } else {
6621 cb.cb_flags = IOS_DEFAULT_M;
6622 if (latency)
6623 cb.cb_flags |= IOS_LATENCY_M;
6624 if (queues)
6625 cb.cb_flags |= IOS_QUEUES_M;
6626 }
6627
6628 /*
6629 * See if the module supports all the stats we want to display.
6630 */
6631 unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
6632 if (unsupported_flags) {
6633 uint64_t f;
6634 int idx;
6635 fprintf(stderr,
6636 gettext("The loaded zfs module doesn't support:"));
6637
6638 /* for each bit set in unsupported_flags */
6639 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
6640 idx = lowbit64(f) - 1;
6641 fprintf(stderr, " -%c", flag_to_arg[idx]);
6642 }
6643
6644 fprintf(stderr, ". Try running a newer module.\n");
6645 pool_list_free(list);
6646
6647 return (1);
6648 }
6649
6650 int last_npools = 0;
6651 for (;;) {
6652 /*
6653 * Refresh all pools in list, adding or removing pools as
6654 * necessary.
6655 */
6656 int npools = pool_list_refresh(list);
6657 if (npools == 0) {
6658 (void) fprintf(stderr, gettext("no pools available\n"));
6659 } else {
6660 /*
6661 * If the list of pools has changed since last time
6662 * around, reset the iteration count to force the
6663 * header to be redisplayed.
6664 */
6665 if (last_npools != npools)
6666 cb.cb_iteration = 0;
6667
6668 /*
6669 * If this is the first iteration and -y was supplied
6670 * we skip any printing.
6671 */
6672 boolean_t skip = (omit_since_boot &&
6673 cb.cb_iteration == 0);
6674
6675 /*
6676 * Iterate over all pools to determine the maximum width
6677 * for the pool / device name column across all pools.
6678 */
6679 cb.cb_namewidth = 0;
6680 (void) pool_list_iter(list, B_FALSE,
6681 get_namewidth_iostat, &cb);
6682
6683 if (timestamp_fmt != NODATE)
6684 print_timestamp(timestamp_fmt);
6685
6686 if (cmd != NULL && cb.cb_verbose &&
6687 !(cb.cb_flags & IOS_ANYHISTO_M)) {
6688 cb.vcdl = all_pools_for_each_vdev_run(argc,
6689 argv, cmd, g_zfs, cb.cb_vdevs.cb_names,
6690 cb.cb_vdevs.cb_names_count,
6691 cb.cb_vdevs.cb_name_flags);
6692 } else {
6693 cb.vcdl = NULL;
6694 }
6695
6696
6697 /*
6698 * Check terminal size so we can print headers
6699 * even when terminal window has its height
6700 * changed.
6701 */
6702 int winheight = terminal_height();
6703 /*
6704 * Are we connected to TTY? If not, headers_once
6705 * should be true, to avoid breaking scripts.
6706 */
6707 if (winheight < 0)
6708 headers_once = B_TRUE;
6709
6710 /*
6711 * If it's the first time and we're not skipping it,
6712 * or either skip or verbose mode, print the header.
6713 *
6714 * The histogram code explicitly prints its header on
6715 * every vdev, so skip this for histograms.
6716 */
6717 if (((++cb.cb_iteration == 1 && !skip) ||
6718 (skip != verbose) ||
6719 (!headers_once &&
6720 (cb.cb_iteration % winheight) == 0)) &&
6721 (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
6722 !cb.cb_scripted)
6723 print_iostat_header(&cb);
6724
6725 if (skip) {
6726 (void) fflush(stdout);
6727 (void) fsleep(interval);
6728 last_npools = npools;
6729 continue;
6730 }
6731
6732 (void) pool_list_iter(list, B_FALSE, print_iostat, &cb);
6733
6734 /*
6735 * If there's more than one pool, and we're not in
6736 * verbose mode (which prints a separator for us),
6737 * then print a separator.
6738 *
6739 * In addition, if we're printing specific vdevs then
6740 * we also want an ending separator.
6741 */
6742 if (((npools > 1 && !verbose &&
6743 !(cb.cb_flags & IOS_ANYHISTO_M)) ||
6744 (!(cb.cb_flags & IOS_ANYHISTO_M) &&
6745 cb.cb_vdevs.cb_names_count)) &&
6746 !cb.cb_scripted) {
6747 print_iostat_separator(&cb);
6748 if (cb.vcdl != NULL)
6749 print_cmd_columns(cb.vcdl, 1);
6750 printf("\n");
6751 }
6752
6753 if (cb.vcdl != NULL)
6754 free_vdev_cmd_data_list(cb.vcdl);
6755
6756 }
6757
6758 if (interval == 0)
6759 break;
6760
6761 if (count != 0 && --count == 0)
6762 break;
6763
6764 (void) fflush(stdout);
6765 (void) fsleep(interval);
6766
6767 last_npools = npools;
6768 }
6769
6770 pool_list_free(list);
6771
6772 return (ret);
6773 }
6774
6775 typedef struct list_cbdata {
6776 boolean_t cb_verbose;
6777 int cb_name_flags;
6778 int cb_namewidth;
6779 boolean_t cb_json;
6780 boolean_t cb_scripted;
6781 zprop_list_t *cb_proplist;
6782 boolean_t cb_literal;
6783 nvlist_t *cb_jsobj;
6784 boolean_t cb_json_as_int;
6785 boolean_t cb_json_pool_key_guid;
6786 } list_cbdata_t;
6787
6788
6789 /*
6790 * Given a list of columns to display, print an appropriate line. If
6791 * `vdev_name` is not NULL, we print `vdev_name` followed by a line of dashes.
6792 * If `vdev_name` is NULL, we print a line of the headers.
6793 */
6794 static void
print_line(list_cbdata_t * cb,const char * vdev_name)6795 print_line(list_cbdata_t *cb, const char *vdev_name)
6796 {
6797 zprop_list_t *pl = cb->cb_proplist;
6798 char headerbuf[ZPOOL_MAXPROPLEN];
6799 const char *header;
6800 boolean_t first = B_TRUE;
6801 boolean_t right_justify;
6802 size_t width = 0;
6803
6804 boolean_t print_header = (vdev_name == NULL);
6805
6806 for (; pl != NULL; pl = pl->pl_next) {
6807 width = pl->pl_width;
6808 if (first && cb->cb_verbose) {
6809 /*
6810 * Reset the width to accommodate the verbose listing
6811 * of devices.
6812 */
6813 width = cb->cb_namewidth;
6814 }
6815
6816 if (!first)
6817 (void) fputs(" ", stdout);
6818
6819 if (print_header) {
6820 right_justify = B_FALSE;
6821 if (pl->pl_prop != ZPROP_USERPROP) {
6822 header = zpool_prop_column_name(pl->pl_prop);
6823 right_justify = zpool_prop_align_right(
6824 pl->pl_prop);
6825 } else {
6826 int i;
6827
6828 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
6829 headerbuf[i] = toupper(
6830 pl->pl_user_prop[i]);
6831 headerbuf[i] = '\0';
6832 header = headerbuf;
6833 }
6834
6835 }
6836 /*
6837 * If `print_header` is false, we want to print a line of
6838 * dashes.
6839 */
6840 else {
6841 if (first) {
6842 header = vdev_name;
6843 right_justify = B_FALSE;
6844 } else {
6845 header = "-";
6846 right_justify = B_TRUE;
6847 }
6848 }
6849
6850 if (pl->pl_next == NULL && !right_justify)
6851 (void) fputs(header, stdout);
6852 else if (right_justify)
6853 (void) printf("%*s", (int)width, header);
6854 else
6855 (void) printf("%-*s", (int)width, header);
6856
6857 if (first)
6858 first = B_FALSE;
6859 }
6860
6861 (void) fputc('\n', stdout);
6862 }
6863
6864 /*
6865 * Given a pool and a list of properties, print out all the properties according
6866 * to the described layout. Used by zpool_do_list().
6867 */
6868 static void
collect_pool(zpool_handle_t * zhp,list_cbdata_t * cb)6869 collect_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
6870 {
6871 zprop_list_t *pl = cb->cb_proplist;
6872 boolean_t first = B_TRUE;
6873 char property[ZPOOL_MAXPROPLEN];
6874 const char *propstr;
6875 boolean_t right_justify;
6876 size_t width;
6877 zprop_source_t sourcetype = ZPROP_SRC_NONE;
6878 nvlist_t *item, *d, *props;
6879 item = d = props = NULL;
6880
6881 if (cb->cb_json) {
6882 item = fnvlist_alloc();
6883 props = fnvlist_alloc();
6884 d = fnvlist_lookup_nvlist(cb->cb_jsobj, "pools");
6885 if (d == NULL) {
6886 fprintf(stderr, "pools obj not found.\n");
6887 exit(1);
6888 }
6889 fill_pool_info(item, zhp, B_TRUE, cb->cb_json_as_int);
6890 }
6891
6892 for (; pl != NULL; pl = pl->pl_next) {
6893
6894 width = pl->pl_width;
6895 if (first && cb->cb_verbose) {
6896 /*
6897 * Reset the width to accommodate the verbose listing
6898 * of devices.
6899 */
6900 width = cb->cb_namewidth;
6901 }
6902
6903 if (!cb->cb_json && !first) {
6904 if (cb->cb_scripted)
6905 (void) fputc('\t', stdout);
6906 else
6907 (void) fputs(" ", stdout);
6908 } else {
6909 first = B_FALSE;
6910 }
6911
6912 right_justify = B_FALSE;
6913 if (pl->pl_prop != ZPROP_USERPROP) {
6914 if (zpool_get_prop(zhp, pl->pl_prop, property,
6915 sizeof (property), &sourcetype,
6916 cb->cb_literal) != 0)
6917 propstr = "-";
6918 else
6919 propstr = property;
6920
6921 right_justify = zpool_prop_align_right(pl->pl_prop);
6922 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
6923 zpool_prop_unsupported(pl->pl_user_prop)) &&
6924 zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
6925 sizeof (property)) == 0) {
6926 propstr = property;
6927 sourcetype = ZPROP_SRC_LOCAL;
6928 } else if (zfs_prop_user(pl->pl_user_prop) &&
6929 zpool_get_userprop(zhp, pl->pl_user_prop, property,
6930 sizeof (property), &sourcetype) == 0) {
6931 propstr = property;
6932 } else {
6933 propstr = "-";
6934 }
6935
6936 if (cb->cb_json) {
6937 if (pl->pl_prop == ZPOOL_PROP_NAME)
6938 continue;
6939 const char *prop_name;
6940 if (pl->pl_prop != ZPROP_USERPROP)
6941 prop_name = zpool_prop_to_name(pl->pl_prop);
6942 else
6943 prop_name = pl->pl_user_prop;
6944 (void) zprop_nvlist_one_property(
6945 prop_name, propstr,
6946 sourcetype, NULL, NULL, props, cb->cb_json_as_int);
6947 } else {
6948 /*
6949 * If this is being called in scripted mode, or if this
6950 * is the last column and it is left-justified, don't
6951 * include a width format specifier.
6952 */
6953 if (cb->cb_scripted || (pl->pl_next == NULL &&
6954 !right_justify))
6955 (void) fputs(propstr, stdout);
6956 else if (right_justify)
6957 (void) printf("%*s", (int)width, propstr);
6958 else
6959 (void) printf("%-*s", (int)width, propstr);
6960 }
6961 }
6962
6963 if (cb->cb_json) {
6964 fnvlist_add_nvlist(item, "properties", props);
6965 if (cb->cb_json_pool_key_guid) {
6966 char pool_guid[256];
6967 uint64_t guid = fnvlist_lookup_uint64(
6968 zpool_get_config(zhp, NULL),
6969 ZPOOL_CONFIG_POOL_GUID);
6970 (void) snprintf(pool_guid, 256, "%llu",
6971 (u_longlong_t)guid);
6972 fnvlist_add_nvlist(d, pool_guid, item);
6973 } else {
6974 fnvlist_add_nvlist(d, zpool_get_name(zhp),
6975 item);
6976 }
6977 fnvlist_free(props);
6978 fnvlist_free(item);
6979 } else
6980 (void) fputc('\n', stdout);
6981 }
6982
6983 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)6984 collect_vdev_prop(zpool_prop_t prop, uint64_t value, const char *str,
6985 boolean_t scripted, boolean_t valid, enum zfs_nicenum_format format,
6986 boolean_t json, nvlist_t *nvl, boolean_t as_int)
6987 {
6988 char propval[64];
6989 boolean_t fixed;
6990 size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
6991
6992 switch (prop) {
6993 case ZPOOL_PROP_SIZE:
6994 case ZPOOL_PROP_NORMAL_SIZE:
6995 case ZPOOL_PROP_SPECIAL_SIZE:
6996 case ZPOOL_PROP_DEDUP_SIZE:
6997 case ZPOOL_PROP_LOG_SIZE:
6998 case ZPOOL_PROP_ELOG_SIZE:
6999 case ZPOOL_PROP_SELOG_SIZE:
7000 case ZPOOL_PROP_EXPANDSZ:
7001 case ZPOOL_PROP_NORMAL_EXPANDSZ:
7002 case ZPOOL_PROP_SPECIAL_EXPANDSZ:
7003 case ZPOOL_PROP_DEDUP_EXPANDSZ:
7004 case ZPOOL_PROP_LOG_EXPANDSZ:
7005 case ZPOOL_PROP_ELOG_EXPANDSZ:
7006 case ZPOOL_PROP_SELOG_EXPANDSZ:
7007 case ZPOOL_PROP_CHECKPOINT:
7008 case ZPOOL_PROP_DEDUPRATIO:
7009 case ZPOOL_PROP_DEDUPCACHED:
7010 if (value == 0)
7011 (void) strlcpy(propval, "-", sizeof (propval));
7012 else
7013 zfs_nicenum_format(value, propval, sizeof (propval),
7014 format);
7015 break;
7016 case ZPOOL_PROP_FRAGMENTATION:
7017 case ZPOOL_PROP_NORMAL_FRAGMENTATION:
7018 case ZPOOL_PROP_SPECIAL_FRAGMENTATION:
7019 case ZPOOL_PROP_DEDUP_FRAGMENTATION:
7020 case ZPOOL_PROP_LOG_FRAGMENTATION:
7021 case ZPOOL_PROP_ELOG_FRAGMENTATION:
7022 case ZPOOL_PROP_SELOG_FRAGMENTATION:
7023 if (value == ZFS_FRAG_INVALID) {
7024 (void) strlcpy(propval, "-", sizeof (propval));
7025 } else if (format == ZFS_NICENUM_RAW) {
7026 (void) snprintf(propval, sizeof (propval), "%llu",
7027 (unsigned long long)value);
7028 } else {
7029 (void) snprintf(propval, sizeof (propval), "%llu%%",
7030 (unsigned long long)value);
7031 }
7032 break;
7033 case ZPOOL_PROP_CAPACITY:
7034 case ZPOOL_PROP_NORMAL_CAPACITY:
7035 case ZPOOL_PROP_SPECIAL_CAPACITY:
7036 case ZPOOL_PROP_DEDUP_CAPACITY:
7037 case ZPOOL_PROP_LOG_CAPACITY:
7038 case ZPOOL_PROP_ELOG_CAPACITY:
7039 case ZPOOL_PROP_SELOG_CAPACITY:
7040 /* capacity value is in parts-per-10,000 (aka permyriad) */
7041 if (format == ZFS_NICENUM_RAW)
7042 (void) snprintf(propval, sizeof (propval), "%llu",
7043 (unsigned long long)value / 100);
7044 else
7045 (void) snprintf(propval, sizeof (propval),
7046 value < 1000 ? "%1.2f%%" : value < 10000 ?
7047 "%2.1f%%" : "%3.0f%%", value / 100.0);
7048 break;
7049 case ZPOOL_PROP_HEALTH:
7050 width = 8;
7051 (void) strlcpy(propval, str, sizeof (propval));
7052 break;
7053 default:
7054 zfs_nicenum_format(value, propval, sizeof (propval), format);
7055 }
7056
7057 if (!valid)
7058 (void) strlcpy(propval, "-", sizeof (propval));
7059
7060 if (json) {
7061 (void) zprop_nvlist_one_property(zpool_prop_to_name(prop),
7062 propval, ZPROP_SRC_NONE, NULL, NULL, nvl, as_int);
7063 } else {
7064 if (scripted)
7065 (void) printf("\t%s", propval);
7066 else
7067 (void) printf(" %*s", (int)width, propval);
7068 }
7069 }
7070
7071 /*
7072 * print static default line per vdev
7073 */
7074 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)7075 collect_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
7076 list_cbdata_t *cb, int depth, boolean_t isspare, nvlist_t *item)
7077 {
7078 nvlist_t **child;
7079 vdev_stat_t *vs;
7080 uint_t c, children = 0;
7081 char *vname;
7082 boolean_t scripted = cb->cb_scripted;
7083 uint64_t islog = B_FALSE;
7084 nvlist_t *props, *ent, *ch, *obj, *l2c, *sp;
7085 props = ent = ch = obj = sp = l2c = NULL;
7086
7087 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
7088 (uint64_t **)&vs, &c) == 0);
7089
7090 if (name != NULL) {
7091 boolean_t toplevel = (vs->vs_space != 0);
7092 uint64_t cap;
7093 enum zfs_nicenum_format format;
7094 const char *state;
7095
7096 if (cb->cb_literal)
7097 format = ZFS_NICENUM_RAW;
7098 else
7099 format = ZFS_NICENUM_1024;
7100
7101 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
7102 return;
7103
7104 if (cb->cb_json) {
7105 props = fnvlist_alloc();
7106 ent = fnvlist_alloc();
7107 fill_vdev_info(ent, zhp, (char *)name, B_FALSE,
7108 cb->cb_json_as_int);
7109 } else {
7110 if (scripted)
7111 (void) printf("\t%s", name);
7112 else if (strlen(name) + depth > cb->cb_namewidth)
7113 (void) printf("%*s%s", depth, "", name);
7114 else
7115 (void) printf("%*s%s%*s", depth, "", name,
7116 (int)(cb->cb_namewidth - strlen(name) -
7117 depth), "");
7118 }
7119
7120 /*
7121 * Print the properties for the individual vdevs. Some
7122 * properties are only applicable to toplevel vdevs. The
7123 * 'toplevel' boolean value is passed to the print_one_column()
7124 * to indicate that the value is valid.
7125 */
7126 for (zprop_list_t *pl = cb->cb_proplist; pl != NULL;
7127 pl = pl->pl_next) {
7128 switch (pl->pl_prop) {
7129 case ZPOOL_PROP_SIZE:
7130 if (VDEV_STAT_VALID(vs_pspace, c) &&
7131 vs->vs_pspace) {
7132 collect_vdev_prop(
7133 ZPOOL_PROP_SIZE, vs->vs_pspace,
7134 NULL, scripted, B_TRUE, format,
7135 cb->cb_json, props,
7136 cb->cb_json_as_int);
7137 } else {
7138 collect_vdev_prop(
7139 ZPOOL_PROP_SIZE, vs->vs_space, NULL,
7140 scripted, toplevel, format,
7141 cb->cb_json, props,
7142 cb->cb_json_as_int);
7143 }
7144 break;
7145 case ZPOOL_PROP_ALLOCATED:
7146 collect_vdev_prop(ZPOOL_PROP_ALLOCATED,
7147 vs->vs_alloc, NULL, scripted, toplevel,
7148 format, cb->cb_json, props,
7149 cb->cb_json_as_int);
7150 break;
7151
7152 case ZPOOL_PROP_FREE:
7153 collect_vdev_prop(ZPOOL_PROP_FREE,
7154 vs->vs_space - vs->vs_alloc, NULL, scripted,
7155 toplevel, format, cb->cb_json, props,
7156 cb->cb_json_as_int);
7157 break;
7158
7159 case ZPOOL_PROP_CHECKPOINT:
7160 collect_vdev_prop(ZPOOL_PROP_CHECKPOINT,
7161 vs->vs_checkpoint_space, NULL, scripted,
7162 toplevel, format, cb->cb_json, props,
7163 cb->cb_json_as_int);
7164 break;
7165
7166 case ZPOOL_PROP_EXPANDSZ:
7167 collect_vdev_prop(ZPOOL_PROP_EXPANDSZ,
7168 vs->vs_esize, NULL, scripted, B_TRUE,
7169 format, cb->cb_json, props,
7170 cb->cb_json_as_int);
7171 break;
7172
7173 case ZPOOL_PROP_FRAGMENTATION:
7174 collect_vdev_prop(
7175 ZPOOL_PROP_FRAGMENTATION,
7176 vs->vs_fragmentation, NULL, scripted,
7177 (vs->vs_fragmentation != ZFS_FRAG_INVALID &&
7178 toplevel),
7179 format, cb->cb_json, props,
7180 cb->cb_json_as_int);
7181 break;
7182
7183 case ZPOOL_PROP_CAPACITY:
7184 cap = (vs->vs_space == 0) ?
7185 0 : (vs->vs_alloc * 10000 / vs->vs_space);
7186 collect_vdev_prop(ZPOOL_PROP_CAPACITY, cap,
7187 NULL, scripted, toplevel, format,
7188 cb->cb_json, props, cb->cb_json_as_int);
7189 break;
7190
7191 case ZPOOL_PROP_HEALTH:
7192 state = zpool_state_to_name(vs->vs_state,
7193 vs->vs_aux);
7194 if (isspare) {
7195 if (vs->vs_aux == VDEV_AUX_SPARED)
7196 state = "INUSE";
7197 else if (vs->vs_state ==
7198 VDEV_STATE_HEALTHY)
7199 state = "AVAIL";
7200 }
7201 collect_vdev_prop(ZPOOL_PROP_HEALTH, 0, state,
7202 scripted, B_TRUE, format, cb->cb_json,
7203 props, cb->cb_json_as_int);
7204 break;
7205
7206 case ZPOOL_PROP_NAME:
7207 break;
7208
7209 default:
7210 collect_vdev_prop(pl->pl_prop, 0,
7211 NULL, scripted, B_FALSE, format,
7212 cb->cb_json, props, cb->cb_json_as_int);
7213
7214 }
7215
7216
7217 }
7218
7219 if (cb->cb_json) {
7220 fnvlist_add_nvlist(ent, "properties", props);
7221 fnvlist_free(props);
7222 } else
7223 (void) fputc('\n', stdout);
7224 }
7225
7226 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
7227 &child, &children) != 0) {
7228 if (cb->cb_json) {
7229 fnvlist_add_nvlist(item, name, ent);
7230 fnvlist_free(ent);
7231 }
7232 return;
7233 }
7234
7235 if (cb->cb_json) {
7236 ch = fnvlist_alloc();
7237 }
7238
7239 /* list the normal vdevs first */
7240 for (c = 0; c < children; c++) {
7241 uint64_t ishole = B_FALSE;
7242
7243 if (nvlist_lookup_uint64(child[c],
7244 ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
7245 continue;
7246
7247 if (nvlist_lookup_uint64(child[c],
7248 ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
7249 continue;
7250
7251 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
7252 continue;
7253
7254 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7255 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7256
7257 if (name == NULL || cb->cb_json != B_TRUE)
7258 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7259 B_FALSE, item);
7260 else if (cb->cb_json) {
7261 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7262 B_FALSE, ch);
7263 }
7264 free(vname);
7265 }
7266
7267 if (cb->cb_json) {
7268 if (!nvlist_empty(ch))
7269 fnvlist_add_nvlist(ent, "vdevs", ch);
7270 fnvlist_free(ch);
7271 }
7272
7273 /* list the classes: 'logs', 'dedup', and 'special' */
7274 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
7275 boolean_t printed = B_FALSE;
7276 if (cb->cb_json)
7277 obj = fnvlist_alloc();
7278 for (c = 0; c < children; c++) {
7279 const char *bias = NULL;
7280 const char *type = NULL;
7281
7282 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
7283 &islog) == 0 && islog) {
7284 bias = VDEV_ALLOC_CLASS_LOGS;
7285 } else {
7286 (void) nvlist_lookup_string(child[c],
7287 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
7288 (void) nvlist_lookup_string(child[c],
7289 ZPOOL_CONFIG_TYPE, &type);
7290 }
7291 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
7292 continue;
7293 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
7294 continue;
7295
7296 if (!printed && !cb->cb_json) {
7297 print_line(cb, class_name[n]);
7298 printed = B_TRUE;
7299 }
7300 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7301 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7302 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7303 B_FALSE, obj);
7304 free(vname);
7305 }
7306 if (cb->cb_json) {
7307 if (!nvlist_empty(obj))
7308 fnvlist_add_nvlist(item, class_name[n], obj);
7309 fnvlist_free(obj);
7310 }
7311 }
7312
7313 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
7314 &child, &children) == 0 && children > 0) {
7315 if (cb->cb_json) {
7316 l2c = fnvlist_alloc();
7317 } else {
7318 print_line(cb, "cache");
7319 }
7320 for (c = 0; c < children; c++) {
7321 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7322 cb->cb_name_flags);
7323 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7324 B_FALSE, l2c);
7325 free(vname);
7326 }
7327 if (cb->cb_json) {
7328 if (!nvlist_empty(l2c))
7329 fnvlist_add_nvlist(item, "l2cache", l2c);
7330 fnvlist_free(l2c);
7331 }
7332 }
7333
7334 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
7335 &children) == 0 && children > 0) {
7336 if (cb->cb_json) {
7337 sp = fnvlist_alloc();
7338 } else {
7339 print_line(cb, "spare");
7340 }
7341 for (c = 0; c < children; c++) {
7342 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7343 cb->cb_name_flags);
7344 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7345 B_TRUE, sp);
7346 free(vname);
7347 }
7348 if (cb->cb_json) {
7349 if (!nvlist_empty(sp))
7350 fnvlist_add_nvlist(item, "spares", sp);
7351 fnvlist_free(sp);
7352 }
7353 }
7354
7355 if (name != NULL && cb->cb_json) {
7356 fnvlist_add_nvlist(item, name, ent);
7357 fnvlist_free(ent);
7358 }
7359 }
7360
7361 /*
7362 * Generic callback function to list a pool.
7363 */
7364 static int
list_callback(zpool_handle_t * zhp,void * data)7365 list_callback(zpool_handle_t *zhp, void *data)
7366 {
7367 nvlist_t *p, *d, *nvdevs;
7368 uint64_t guid;
7369 char pool_guid[256];
7370 const char *pool_name = zpool_get_name(zhp);
7371 list_cbdata_t *cbp = data;
7372 p = d = nvdevs = NULL;
7373
7374 collect_pool(zhp, cbp);
7375
7376 if (cbp->cb_verbose) {
7377 nvlist_t *config, *nvroot;
7378 config = zpool_get_config(zhp, NULL);
7379 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
7380 &nvroot) == 0);
7381 if (cbp->cb_json) {
7382 d = fnvlist_lookup_nvlist(cbp->cb_jsobj,
7383 "pools");
7384 if (cbp->cb_json_pool_key_guid) {
7385 guid = fnvlist_lookup_uint64(config,
7386 ZPOOL_CONFIG_POOL_GUID);
7387 (void) snprintf(pool_guid, 256, "%llu",
7388 (u_longlong_t)guid);
7389 p = fnvlist_lookup_nvlist(d, pool_guid);
7390 } else {
7391 p = fnvlist_lookup_nvlist(d, pool_name);
7392 }
7393 nvdevs = fnvlist_alloc();
7394 }
7395 collect_list_stats(zhp, NULL, nvroot, cbp, 0, B_FALSE, nvdevs);
7396 if (cbp->cb_json) {
7397 fnvlist_add_nvlist(p, "vdevs", nvdevs);
7398 if (cbp->cb_json_pool_key_guid)
7399 fnvlist_add_nvlist(d, pool_guid, p);
7400 else
7401 fnvlist_add_nvlist(d, pool_name, p);
7402 fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
7403 fnvlist_free(nvdevs);
7404 }
7405 }
7406
7407 return (0);
7408 }
7409
7410 /*
7411 * Set the minimum pool/vdev name column width. The width must be at least 9,
7412 * but may be as large as needed.
7413 */
7414 static int
get_namewidth_list(zpool_handle_t * zhp,void * data)7415 get_namewidth_list(zpool_handle_t *zhp, void *data)
7416 {
7417 list_cbdata_t *cb = data;
7418 int width;
7419
7420 width = get_namewidth(zhp, cb->cb_namewidth,
7421 cb->cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
7422
7423 if (width < 9)
7424 width = 9;
7425
7426 cb->cb_namewidth = width;
7427
7428 return (0);
7429 }
7430
7431 /*
7432 * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
7433 *
7434 * -g Display guid for individual vdev name.
7435 * -H Scripted mode. Don't display headers, and separate properties
7436 * by a single tab.
7437 * -L Follow links when resolving vdev path name.
7438 * -o List of properties to display. Defaults to
7439 * "name,size,allocated,free,expandsize,fragmentation,capacity,"
7440 * "dedupratio,health,altroot"
7441 * -p Display values in parsable (exact) format.
7442 * -P Display full path for vdev name.
7443 * -T Display a timestamp in date(1) or Unix format
7444 * -j Display the output in JSON format
7445 * --json-int Display the numbers as integer instead of strings.
7446 * --json-pool-key-guid Set pool GUID as key for pool objects.
7447 *
7448 * List all pools in the system, whether or not they're healthy. Output space
7449 * statistics for each one, as well as health status summary.
7450 */
7451 int
zpool_do_list(int argc,char ** argv)7452 zpool_do_list(int argc, char **argv)
7453 {
7454 int c;
7455 int ret = 0;
7456 list_cbdata_t cb = { 0 };
7457 static char default_props[] =
7458 "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
7459 "capacity,dedupratio,health,altroot";
7460 char *props = default_props;
7461 float interval = 0;
7462 unsigned long count = 0;
7463 zpool_list_t *list;
7464 boolean_t first = B_TRUE;
7465 nvlist_t *data = NULL;
7466 current_prop_type = ZFS_TYPE_POOL;
7467
7468 struct option long_options[] = {
7469 {"json", no_argument, NULL, 'j'},
7470 {"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
7471 {"json-pool-key-guid", no_argument, NULL,
7472 ZPOOL_OPTION_POOL_KEY_GUID},
7473 {0, 0, 0, 0}
7474 };
7475
7476 /* check options */
7477 while ((c = getopt_long(argc, argv, ":gjHLo:pPT:v", long_options,
7478 NULL)) != -1) {
7479 switch (c) {
7480 case 'g':
7481 cb.cb_name_flags |= VDEV_NAME_GUID;
7482 break;
7483 case 'H':
7484 cb.cb_scripted = B_TRUE;
7485 break;
7486 case 'L':
7487 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
7488 break;
7489 case 'o':
7490 props = optarg;
7491 break;
7492 case 'P':
7493 cb.cb_name_flags |= VDEV_NAME_PATH;
7494 break;
7495 case 'p':
7496 cb.cb_literal = B_TRUE;
7497 break;
7498 case 'j':
7499 cb.cb_json = B_TRUE;
7500 break;
7501 case ZPOOL_OPTION_JSON_NUMS_AS_INT:
7502 cb.cb_json_as_int = B_TRUE;
7503 cb.cb_literal = B_TRUE;
7504 break;
7505 case ZPOOL_OPTION_POOL_KEY_GUID:
7506 cb.cb_json_pool_key_guid = B_TRUE;
7507 break;
7508 case 'T':
7509 get_timestamp_arg(*optarg);
7510 break;
7511 case 'v':
7512 cb.cb_verbose = B_TRUE;
7513 cb.cb_namewidth = 8; /* 8 until precalc is avail */
7514 break;
7515 case ':':
7516 (void) fprintf(stderr, gettext("missing argument for "
7517 "'%c' option\n"), optopt);
7518 usage(B_FALSE);
7519 break;
7520 case '?':
7521 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7522 optopt);
7523 usage(B_FALSE);
7524 }
7525 }
7526
7527 argc -= optind;
7528 argv += optind;
7529
7530 if (!cb.cb_json && cb.cb_json_as_int) {
7531 (void) fprintf(stderr, gettext("'--json-int' only works with"
7532 " '-j' option\n"));
7533 usage(B_FALSE);
7534 }
7535
7536 if (!cb.cb_json && cb.cb_json_pool_key_guid) {
7537 (void) fprintf(stderr, gettext("'json-pool-key-guid' only"
7538 " works with '-j' option\n"));
7539 usage(B_FALSE);
7540 }
7541
7542 get_interval_count(&argc, argv, &interval, &count);
7543
7544 if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
7545 usage(B_FALSE);
7546
7547 for (;;) {
7548 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
7549 ZFS_TYPE_POOL, cb.cb_literal, &ret)) == NULL)
7550 return (1);
7551
7552 if (pool_list_count(list) == 0)
7553 break;
7554
7555 if (cb.cb_json) {
7556 cb.cb_jsobj = zpool_json_schema(0, 1);
7557 data = fnvlist_alloc();
7558 fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
7559 fnvlist_free(data);
7560 }
7561
7562 cb.cb_namewidth = 0;
7563 (void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
7564
7565 if (timestamp_fmt != NODATE) {
7566 if (cb.cb_json) {
7567 if (cb.cb_json_as_int) {
7568 fnvlist_add_uint64(cb.cb_jsobj, "time",
7569 time(NULL));
7570 } else {
7571 char ts[128];
7572 get_timestamp(timestamp_fmt, ts, 128);
7573 fnvlist_add_string(cb.cb_jsobj, "time",
7574 ts);
7575 }
7576 } else
7577 print_timestamp(timestamp_fmt);
7578 }
7579
7580 if (!cb.cb_scripted && (first || cb.cb_verbose) &&
7581 !cb.cb_json) {
7582 print_line(&cb, NULL);
7583 first = B_FALSE;
7584 }
7585 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
7586
7587 if (ret == 0 && cb.cb_json)
7588 zcmd_print_json(cb.cb_jsobj);
7589 else if (ret != 0 && cb.cb_json)
7590 nvlist_free(cb.cb_jsobj);
7591
7592 if (interval == 0)
7593 break;
7594
7595 if (count != 0 && --count == 0)
7596 break;
7597
7598 pool_list_free(list);
7599
7600 (void) fflush(stdout);
7601 (void) fsleep(interval);
7602 }
7603
7604 if (argc == 0 && !cb.cb_scripted && !cb.cb_json &&
7605 pool_list_count(list) == 0) {
7606 (void) printf(gettext("no pools available\n"));
7607 ret = 0;
7608 }
7609
7610 pool_list_free(list);
7611 zprop_free_list(cb.cb_proplist);
7612 return (ret);
7613 }
7614
7615 static int
zpool_do_attach_or_replace(int argc,char ** argv,int replacing)7616 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
7617 {
7618 boolean_t force = B_FALSE;
7619 boolean_t rebuild = B_FALSE;
7620 boolean_t wait = B_FALSE;
7621 int c;
7622 nvlist_t *nvroot;
7623 char *poolname, *old_disk, *new_disk;
7624 zpool_handle_t *zhp;
7625 nvlist_t *props = NULL;
7626 char *propval;
7627 int ret;
7628
7629 /* check options */
7630 while ((c = getopt(argc, argv, "fo:sw")) != -1) {
7631 switch (c) {
7632 case 'f':
7633 force = B_TRUE;
7634 break;
7635 case 'o':
7636 if ((propval = strchr(optarg, '=')) == NULL) {
7637 (void) fprintf(stderr, gettext("missing "
7638 "'=' for -o option\n"));
7639 usage(B_FALSE);
7640 }
7641 *propval = '\0';
7642 propval++;
7643
7644 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
7645 (add_prop_list(optarg, propval, &props, B_TRUE)))
7646 usage(B_FALSE);
7647 break;
7648 case 's':
7649 rebuild = B_TRUE;
7650 break;
7651 case 'w':
7652 wait = B_TRUE;
7653 break;
7654 case '?':
7655 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7656 optopt);
7657 usage(B_FALSE);
7658 }
7659 }
7660
7661 argc -= optind;
7662 argv += optind;
7663
7664 /* get pool name and check number of arguments */
7665 if (argc < 1) {
7666 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7667 usage(B_FALSE);
7668 }
7669
7670 poolname = argv[0];
7671
7672 if (argc < 2) {
7673 (void) fprintf(stderr,
7674 gettext("missing <device> specification\n"));
7675 usage(B_FALSE);
7676 }
7677
7678 old_disk = argv[1];
7679
7680 if (argc < 3) {
7681 if (!replacing) {
7682 (void) fprintf(stderr,
7683 gettext("missing <new_device> specification\n"));
7684 usage(B_FALSE);
7685 }
7686 new_disk = old_disk;
7687 argc -= 1;
7688 argv += 1;
7689 } else {
7690 new_disk = argv[2];
7691 argc -= 2;
7692 argv += 2;
7693 }
7694
7695 if (argc > 1) {
7696 (void) fprintf(stderr, gettext("too many arguments\n"));
7697 usage(B_FALSE);
7698 }
7699
7700 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7701 nvlist_free(props);
7702 return (1);
7703 }
7704
7705 if (zpool_get_config(zhp, NULL) == NULL) {
7706 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
7707 poolname);
7708 zpool_close(zhp);
7709 nvlist_free(props);
7710 return (1);
7711 }
7712
7713 /* unless manually specified use "ashift" pool property (if set) */
7714 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
7715 int intval;
7716 zprop_source_t src;
7717 char strval[ZPOOL_MAXPROPLEN];
7718
7719 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
7720 if (src != ZPROP_SRC_DEFAULT) {
7721 (void) sprintf(strval, "%" PRId32, intval);
7722 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
7723 &props, B_TRUE) == 0);
7724 }
7725 }
7726
7727 nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
7728 argc, argv);
7729 if (nvroot == NULL) {
7730 zpool_close(zhp);
7731 nvlist_free(props);
7732 return (1);
7733 }
7734
7735 ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing,
7736 rebuild);
7737
7738 if (ret == 0 && wait) {
7739 zpool_wait_activity_t activity = ZPOOL_WAIT_RESILVER;
7740 char raidz_prefix[] = "raidz";
7741 if (replacing) {
7742 activity = ZPOOL_WAIT_REPLACE;
7743 } else if (strncmp(old_disk,
7744 raidz_prefix, strlen(raidz_prefix)) == 0) {
7745 activity = ZPOOL_WAIT_RAIDZ_EXPAND;
7746 }
7747 ret = zpool_wait(zhp, activity);
7748 }
7749
7750 nvlist_free(props);
7751 nvlist_free(nvroot);
7752 zpool_close(zhp);
7753
7754 return (ret);
7755 }
7756
7757 /*
7758 * zpool replace [-fsw] [-o property=value] <pool> <device> <new_device>
7759 *
7760 * -f Force attach, even if <new_device> appears to be in use.
7761 * -s Use sequential instead of healing reconstruction for resilver.
7762 * -o Set property=value.
7763 * -w Wait for replacing to complete before returning
7764 *
7765 * Replace <device> with <new_device>.
7766 */
7767 int
zpool_do_replace(int argc,char ** argv)7768 zpool_do_replace(int argc, char **argv)
7769 {
7770 return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
7771 }
7772
7773 /*
7774 * zpool attach [-fsw] [-o property=value] <pool> <vdev> <new_device>
7775 *
7776 * -f Force attach, even if <new_device> appears to be in use.
7777 * -s Use sequential instead of healing reconstruction for resilver.
7778 * -o Set property=value.
7779 * -w Wait for resilvering (mirror) or expansion (raidz) to complete
7780 * before returning.
7781 *
7782 * Attach <new_device> to a <vdev>, where the vdev can be of type
7783 * device, mirror or raidz. If <vdev> is not part of a mirror, then <vdev> will
7784 * be transformed into a mirror of <vdev> and <new_device>. When a mirror
7785 * is involved, <new_device> will begin life with a DTL of [0, now], and will
7786 * immediately begin to resilver itself. For the raidz case, a expansion will
7787 * commence and reflow the raidz data across all the disks including the
7788 * <new_device>.
7789 */
7790 int
zpool_do_attach(int argc,char ** argv)7791 zpool_do_attach(int argc, char **argv)
7792 {
7793 return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
7794 }
7795
7796 /*
7797 * zpool detach [-f] <pool> <device>
7798 *
7799 * -f Force detach of <device>, even if DTLs argue against it
7800 * (not supported yet)
7801 *
7802 * Detach a device from a mirror. The operation will be refused if <device>
7803 * is the last device in the mirror, or if the DTLs indicate that this device
7804 * has the only valid copy of some data.
7805 */
7806 int
zpool_do_detach(int argc,char ** argv)7807 zpool_do_detach(int argc, char **argv)
7808 {
7809 int c;
7810 char *poolname, *path;
7811 zpool_handle_t *zhp;
7812 int ret;
7813
7814 /* check options */
7815 while ((c = getopt(argc, argv, "")) != -1) {
7816 switch (c) {
7817 case '?':
7818 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7819 optopt);
7820 usage(B_FALSE);
7821 }
7822 }
7823
7824 argc -= optind;
7825 argv += optind;
7826
7827 /* get pool name and check number of arguments */
7828 if (argc < 1) {
7829 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7830 usage(B_FALSE);
7831 }
7832
7833 if (argc < 2) {
7834 (void) fprintf(stderr,
7835 gettext("missing <device> specification\n"));
7836 usage(B_FALSE);
7837 }
7838
7839 poolname = argv[0];
7840 path = argv[1];
7841
7842 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7843 return (1);
7844
7845 ret = zpool_vdev_detach(zhp, path);
7846
7847 zpool_close(zhp);
7848
7849 return (ret);
7850 }
7851
7852 /*
7853 * zpool split [-gLnP] [-o prop=val] ...
7854 * [-o mntopt] ...
7855 * [-R altroot] <pool> <newpool> [<device> ...]
7856 *
7857 * -g Display guid for individual vdev name.
7858 * -L Follow links when resolving vdev path name.
7859 * -n Do not split the pool, but display the resulting layout if
7860 * it were to be split.
7861 * -o Set property=value, or set mount options.
7862 * -P Display full path for vdev name.
7863 * -R Mount the split-off pool under an alternate root.
7864 * -l Load encryption keys while importing.
7865 *
7866 * Splits the named pool and gives it the new pool name. Devices to be split
7867 * off may be listed, provided that no more than one device is specified
7868 * per top-level vdev mirror. The newly split pool is left in an exported
7869 * state unless -R is specified.
7870 *
7871 * Restrictions: the top-level of the pool pool must only be made up of
7872 * mirrors; all devices in the pool must be healthy; no device may be
7873 * undergoing a resilvering operation.
7874 */
7875 int
zpool_do_split(int argc,char ** argv)7876 zpool_do_split(int argc, char **argv)
7877 {
7878 char *srcpool, *newpool, *propval;
7879 char *mntopts = NULL;
7880 splitflags_t flags;
7881 int c, ret = 0;
7882 int ms_status = 0;
7883 boolean_t loadkeys = B_FALSE;
7884 zpool_handle_t *zhp;
7885 nvlist_t *config, *props = NULL;
7886
7887 flags.dryrun = B_FALSE;
7888 flags.import = B_FALSE;
7889 flags.name_flags = 0;
7890
7891 /* check options */
7892 while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
7893 switch (c) {
7894 case 'g':
7895 flags.name_flags |= VDEV_NAME_GUID;
7896 break;
7897 case 'L':
7898 flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
7899 break;
7900 case 'R':
7901 flags.import = B_TRUE;
7902 if (add_prop_list(
7903 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
7904 &props, B_TRUE) != 0) {
7905 nvlist_free(props);
7906 usage(B_FALSE);
7907 }
7908 break;
7909 case 'l':
7910 loadkeys = B_TRUE;
7911 break;
7912 case 'n':
7913 flags.dryrun = B_TRUE;
7914 break;
7915 case 'o':
7916 if ((propval = strchr(optarg, '=')) != NULL) {
7917 *propval = '\0';
7918 propval++;
7919 if (add_prop_list(optarg, propval,
7920 &props, B_TRUE) != 0) {
7921 nvlist_free(props);
7922 usage(B_FALSE);
7923 }
7924 } else {
7925 mntopts = optarg;
7926 }
7927 break;
7928 case 'P':
7929 flags.name_flags |= VDEV_NAME_PATH;
7930 break;
7931 case ':':
7932 (void) fprintf(stderr, gettext("missing argument for "
7933 "'%c' option\n"), optopt);
7934 usage(B_FALSE);
7935 break;
7936 case '?':
7937 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7938 optopt);
7939 usage(B_FALSE);
7940 break;
7941 }
7942 }
7943
7944 if (!flags.import && mntopts != NULL) {
7945 (void) fprintf(stderr, gettext("setting mntopts is only "
7946 "valid when importing the pool\n"));
7947 usage(B_FALSE);
7948 }
7949
7950 if (!flags.import && loadkeys) {
7951 (void) fprintf(stderr, gettext("loading keys is only "
7952 "valid when importing the pool\n"));
7953 usage(B_FALSE);
7954 }
7955
7956 argc -= optind;
7957 argv += optind;
7958
7959 if (argc < 1) {
7960 (void) fprintf(stderr, gettext("Missing pool name\n"));
7961 usage(B_FALSE);
7962 }
7963 if (argc < 2) {
7964 (void) fprintf(stderr, gettext("Missing new pool name\n"));
7965 usage(B_FALSE);
7966 }
7967
7968 srcpool = argv[0];
7969 newpool = argv[1];
7970
7971 argc -= 2;
7972 argv += 2;
7973
7974 if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
7975 nvlist_free(props);
7976 return (1);
7977 }
7978
7979 config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
7980 if (config == NULL) {
7981 ret = 1;
7982 } else {
7983 if (flags.dryrun) {
7984 (void) printf(gettext("would create '%s' with the "
7985 "following layout:\n\n"), newpool);
7986 print_vdev_tree(NULL, newpool, config, 0, "",
7987 flags.name_flags);
7988 print_vdev_tree(NULL, "dedup", config, 0,
7989 VDEV_ALLOC_BIAS_DEDUP, 0);
7990 print_vdev_tree(NULL, "special", config, 0,
7991 VDEV_ALLOC_BIAS_SPECIAL, 0);
7992 }
7993 }
7994
7995 zpool_close(zhp);
7996
7997 if (ret != 0 || flags.dryrun || !flags.import) {
7998 nvlist_free(config);
7999 nvlist_free(props);
8000 return (ret);
8001 }
8002
8003 /*
8004 * The split was successful. Now we need to open the new
8005 * pool and import it.
8006 */
8007 if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
8008 nvlist_free(config);
8009 nvlist_free(props);
8010 return (1);
8011 }
8012
8013 if (loadkeys) {
8014 ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
8015 if (ret != 0)
8016 ret = 1;
8017 }
8018
8019 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL) {
8020 ms_status = zpool_enable_datasets(zhp, mntopts, 0,
8021 mount_tp_nthr);
8022 if (ms_status == EZFS_SHAREFAILED) {
8023 (void) fprintf(stderr, gettext("Split was successful, "
8024 "datasets are mounted but sharing of some datasets "
8025 "has failed\n"));
8026 } else if (ms_status == EZFS_MOUNTFAILED) {
8027 (void) fprintf(stderr, gettext("Split was successful"
8028 ", but some datasets could not be mounted\n"));
8029 (void) fprintf(stderr, gettext("Try doing '%s' with a "
8030 "different altroot\n"), "zpool import");
8031 }
8032 }
8033 zpool_close(zhp);
8034 nvlist_free(config);
8035 nvlist_free(props);
8036
8037 return (ret);
8038 }
8039
8040
8041 /*
8042 * zpool online [--power] <pool> <device> ...
8043 *
8044 * --power: Power on the enclosure slot to the drive (if possible)
8045 */
8046 int
zpool_do_online(int argc,char ** argv)8047 zpool_do_online(int argc, char **argv)
8048 {
8049 int c, i;
8050 char *poolname;
8051 zpool_handle_t *zhp;
8052 int ret = 0;
8053 vdev_state_t newstate;
8054 int flags = 0;
8055 boolean_t is_power_on = B_FALSE;
8056 struct option long_options[] = {
8057 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8058 {0, 0, 0, 0}
8059 };
8060
8061 /* check options */
8062 while ((c = getopt_long(argc, argv, "e", long_options, NULL)) != -1) {
8063 switch (c) {
8064 case 'e':
8065 flags |= ZFS_ONLINE_EXPAND;
8066 break;
8067 case ZPOOL_OPTION_POWER:
8068 is_power_on = B_TRUE;
8069 break;
8070 case '?':
8071 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8072 optopt);
8073 usage(B_FALSE);
8074 }
8075 }
8076
8077 if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8078 is_power_on = B_TRUE;
8079
8080 argc -= optind;
8081 argv += optind;
8082
8083 /* get pool name and check number of arguments */
8084 if (argc < 1) {
8085 (void) fprintf(stderr, gettext("missing pool name\n"));
8086 usage(B_FALSE);
8087 }
8088 if (argc < 2) {
8089 (void) fprintf(stderr, gettext("missing device name\n"));
8090 usage(B_FALSE);
8091 }
8092
8093 poolname = argv[0];
8094
8095 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8096 (void) fprintf(stderr, gettext("failed to open pool "
8097 "\"%s\"\n"), poolname);
8098 return (1);
8099 }
8100
8101 for (i = 1; i < argc; i++) {
8102 vdev_state_t oldstate;
8103 boolean_t avail_spare, l2cache;
8104 int rc;
8105
8106 if (is_power_on) {
8107 rc = zpool_power_on_and_disk_wait(zhp, argv[i]);
8108 if (rc == ENOTSUP) {
8109 (void) fprintf(stderr,
8110 gettext("Power control not supported\n"));
8111 }
8112 if (rc != 0)
8113 return (rc);
8114 }
8115
8116 nvlist_t *tgt = zpool_find_vdev(zhp, argv[i], &avail_spare,
8117 &l2cache, NULL);
8118 if (tgt == NULL) {
8119 ret = 1;
8120 (void) fprintf(stderr, gettext("couldn't find device "
8121 "\"%s\" in pool \"%s\"\n"), argv[i], poolname);
8122 continue;
8123 }
8124 uint_t vsc;
8125 oldstate = ((vdev_stat_t *)fnvlist_lookup_uint64_array(tgt,
8126 ZPOOL_CONFIG_VDEV_STATS, &vsc))->vs_state;
8127 if ((rc = zpool_vdev_online(zhp, argv[i], flags,
8128 &newstate)) == 0) {
8129 if (newstate != VDEV_STATE_HEALTHY) {
8130 (void) printf(gettext("warning: device '%s' "
8131 "onlined, but remains in faulted state\n"),
8132 argv[i]);
8133 if (newstate == VDEV_STATE_FAULTED)
8134 (void) printf(gettext("use 'zpool "
8135 "clear' to restore a faulted "
8136 "device\n"));
8137 else
8138 (void) printf(gettext("use 'zpool "
8139 "replace' to replace devices "
8140 "that are no longer present\n"));
8141 if ((flags & ZFS_ONLINE_EXPAND)) {
8142 (void) printf(gettext("%s: failed "
8143 "to expand usable space on "
8144 "unhealthy device '%s'\n"),
8145 (oldstate >= VDEV_STATE_DEGRADED ?
8146 "error" : "warning"), argv[i]);
8147 if (oldstate >= VDEV_STATE_DEGRADED) {
8148 ret = 1;
8149 break;
8150 }
8151 }
8152 }
8153 } else {
8154 (void) fprintf(stderr, gettext("Failed to online "
8155 "\"%s\" in pool \"%s\": %d\n"),
8156 argv[i], poolname, rc);
8157 ret = 1;
8158 }
8159 }
8160
8161 zpool_close(zhp);
8162
8163 return (ret);
8164 }
8165
8166 /*
8167 * zpool offline [-ft]|[--power] <pool> <device> ...
8168 *
8169 *
8170 * -f Force the device into a faulted state.
8171 *
8172 * -t Only take the device off-line temporarily. The offline/faulted
8173 * state will not be persistent across reboots.
8174 *
8175 * --power Power off the enclosure slot to the drive (if possible)
8176 */
8177 int
zpool_do_offline(int argc,char ** argv)8178 zpool_do_offline(int argc, char **argv)
8179 {
8180 int c, i;
8181 char *poolname;
8182 zpool_handle_t *zhp;
8183 int ret = 0;
8184 boolean_t istmp = B_FALSE;
8185 boolean_t fault = B_FALSE;
8186 boolean_t is_power_off = B_FALSE;
8187
8188 struct option long_options[] = {
8189 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8190 {0, 0, 0, 0}
8191 };
8192
8193 /* check options */
8194 while ((c = getopt_long(argc, argv, "ft", long_options, NULL)) != -1) {
8195 switch (c) {
8196 case 'f':
8197 fault = B_TRUE;
8198 break;
8199 case 't':
8200 istmp = B_TRUE;
8201 break;
8202 case ZPOOL_OPTION_POWER:
8203 is_power_off = B_TRUE;
8204 break;
8205 case '?':
8206 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8207 optopt);
8208 usage(B_FALSE);
8209 }
8210 }
8211
8212 if (is_power_off && fault) {
8213 (void) fprintf(stderr,
8214 gettext("-0 and -f cannot be used together\n"));
8215 usage(B_FALSE);
8216 }
8217
8218 if (is_power_off && istmp) {
8219 (void) fprintf(stderr,
8220 gettext("-0 and -t cannot be used together\n"));
8221 usage(B_FALSE);
8222 }
8223
8224 argc -= optind;
8225 argv += optind;
8226
8227 /* get pool name and check number of arguments */
8228 if (argc < 1) {
8229 (void) fprintf(stderr, gettext("missing pool name\n"));
8230 usage(B_FALSE);
8231 }
8232 if (argc < 2) {
8233 (void) fprintf(stderr, gettext("missing device name\n"));
8234 usage(B_FALSE);
8235 }
8236
8237 poolname = argv[0];
8238
8239 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8240 (void) fprintf(stderr, gettext("failed to open pool "
8241 "\"%s\"\n"), poolname);
8242 return (1);
8243 }
8244
8245 for (i = 1; i < argc; i++) {
8246 uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
8247 if (is_power_off) {
8248 /*
8249 * Note: we have to power off first, then set REMOVED,
8250 * or else zpool_vdev_set_removed_state() returns
8251 * EAGAIN.
8252 */
8253 ret = zpool_power_off(zhp, argv[i]);
8254 if (ret != 0) {
8255 (void) fprintf(stderr, "%s %s %d\n",
8256 gettext("unable to power off slot for"),
8257 argv[i], ret);
8258 }
8259 (void) zpool_vdev_set_removed_state(zhp, guid,
8260 VDEV_AUX_NONE);
8261
8262 } else if (fault) {
8263 vdev_aux_t aux;
8264 if (istmp == B_FALSE) {
8265 /* Force the fault to persist across imports */
8266 aux = VDEV_AUX_EXTERNAL_PERSIST;
8267 } else {
8268 aux = VDEV_AUX_EXTERNAL;
8269 }
8270
8271 if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
8272 ret = 1;
8273 } else {
8274 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
8275 ret = 1;
8276 }
8277 }
8278
8279 zpool_close(zhp);
8280
8281 return (ret);
8282 }
8283
8284 /*
8285 * zpool clear [--power] <pool> [device]
8286 *
8287 * Clear all errors associated with a pool or a particular device.
8288 */
8289 int
zpool_do_clear(int argc,char ** argv)8290 zpool_do_clear(int argc, char **argv)
8291 {
8292 int c;
8293 int ret = 0;
8294 boolean_t is_power_on = B_FALSE;
8295 nvlist_t *policy = NULL;
8296 zpool_handle_t *zhp;
8297 char *pool, *device;
8298
8299 struct option long_options[] = {
8300 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8301 {0, 0, 0, 0}
8302 };
8303
8304 /* check options */
8305 while ((c = getopt_long(argc, argv, "", long_options,
8306 NULL)) != -1) {
8307 switch (c) {
8308 case ZPOOL_OPTION_POWER:
8309 is_power_on = B_TRUE;
8310 break;
8311 case '?':
8312 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8313 optopt);
8314 usage(B_FALSE);
8315 }
8316 }
8317
8318 if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8319 is_power_on = B_TRUE;
8320
8321 argc -= optind;
8322 argv += optind;
8323
8324 if (argc < 1) {
8325 (void) fprintf(stderr, gettext("missing pool name\n"));
8326 usage(B_FALSE);
8327 }
8328
8329 if (argc > 2) {
8330 (void) fprintf(stderr, gettext("too many arguments\n"));
8331 usage(B_FALSE);
8332 }
8333
8334 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0)
8335 return (1);
8336
8337 pool = argv[0];
8338 device = argc == 2 ? argv[1] : NULL;
8339
8340 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
8341 nvlist_free(policy);
8342 return (1);
8343 }
8344
8345 if (is_power_on) {
8346 if (device == NULL) {
8347 (void) zpool_power_on_pool_and_wait_for_devices(zhp);
8348 } else {
8349 (void) zpool_power_on_and_disk_wait(zhp, device);
8350 }
8351 }
8352
8353 if (zpool_clear(zhp, device, policy) != 0)
8354 ret = 1;
8355
8356 zpool_close(zhp);
8357
8358 nvlist_free(policy);
8359
8360 return (ret);
8361 }
8362
8363 /*
8364 * zpool reguid [-g <guid>] <pool>
8365 */
8366 int
zpool_do_reguid(int argc,char ** argv)8367 zpool_do_reguid(int argc, char **argv)
8368 {
8369 uint64_t guid;
8370 uint64_t *guidp = NULL;
8371 int c;
8372 char *endptr;
8373 char *poolname;
8374 zpool_handle_t *zhp;
8375 int ret = 0;
8376
8377 /* check options */
8378 while ((c = getopt(argc, argv, "g:")) != -1) {
8379 switch (c) {
8380 case 'g':
8381 errno = 0;
8382 guid = strtoull(optarg, &endptr, 10);
8383 if (errno != 0 || *endptr != '\0') {
8384 (void) fprintf(stderr,
8385 gettext("invalid GUID: %s\n"), optarg);
8386 usage(B_FALSE);
8387 }
8388 guidp = &guid;
8389 break;
8390 case '?':
8391 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8392 optopt);
8393 usage(B_FALSE);
8394 }
8395 }
8396
8397 argc -= optind;
8398 argv += optind;
8399
8400 /* get pool name and check number of arguments */
8401 if (argc < 1) {
8402 (void) fprintf(stderr, gettext("missing pool name\n"));
8403 usage(B_FALSE);
8404 }
8405
8406 if (argc > 1) {
8407 (void) fprintf(stderr, gettext("too many arguments\n"));
8408 usage(B_FALSE);
8409 }
8410
8411 poolname = argv[0];
8412 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
8413 return (1);
8414
8415 ret = zpool_set_guid(zhp, guidp);
8416
8417 zpool_close(zhp);
8418 return (ret);
8419 }
8420
8421
8422 /*
8423 * zpool reopen <pool>
8424 *
8425 * Reopen the pool so that the kernel can update the sizes of all vdevs.
8426 */
8427 int
zpool_do_reopen(int argc,char ** argv)8428 zpool_do_reopen(int argc, char **argv)
8429 {
8430 int c;
8431 int ret = 0;
8432 boolean_t scrub_restart = B_TRUE;
8433
8434 /* check options */
8435 while ((c = getopt(argc, argv, "n")) != -1) {
8436 switch (c) {
8437 case 'n':
8438 scrub_restart = B_FALSE;
8439 break;
8440 case '?':
8441 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8442 optopt);
8443 usage(B_FALSE);
8444 }
8445 }
8446
8447 argc -= optind;
8448 argv += optind;
8449
8450 /* if argc == 0 we will execute zpool_reopen_one on all pools */
8451 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8452 B_FALSE, zpool_reopen_one, &scrub_restart);
8453
8454 return (ret);
8455 }
8456
8457 typedef struct scrub_cbdata {
8458 int cb_type;
8459 pool_scrub_cmd_t cb_scrub_cmd;
8460 pool_scrub_flags_t cb_scrub_flags;
8461 time_t cb_date_start;
8462 time_t cb_date_end;
8463 } scrub_cbdata_t;
8464
8465 static boolean_t
zpool_has_checkpoint(zpool_handle_t * zhp)8466 zpool_has_checkpoint(zpool_handle_t *zhp)
8467 {
8468 nvlist_t *config, *nvroot;
8469
8470 config = zpool_get_config(zhp, NULL);
8471
8472 if (config != NULL) {
8473 pool_checkpoint_stat_t *pcs = NULL;
8474 uint_t c;
8475
8476 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
8477 (void) nvlist_lookup_uint64_array(nvroot,
8478 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
8479
8480 if (pcs == NULL || pcs->pcs_state == CS_NONE)
8481 return (B_FALSE);
8482
8483 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
8484 pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
8485 return (B_TRUE);
8486 }
8487
8488 return (B_FALSE);
8489 }
8490
8491 static int
scrub_callback(zpool_handle_t * zhp,void * data)8492 scrub_callback(zpool_handle_t *zhp, void *data)
8493 {
8494 scrub_cbdata_t *cb = data;
8495 int err;
8496
8497 /*
8498 * Ignore faulted pools.
8499 */
8500 if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
8501 (void) fprintf(stderr, gettext("cannot scan '%s': pool is "
8502 "currently unavailable\n"), zpool_get_name(zhp));
8503 return (1);
8504 }
8505
8506 err = zpool_scan_range(zhp, cb->cb_type, cb->cb_scrub_cmd,
8507 cb->cb_scrub_flags, cb->cb_date_start, cb->cb_date_end);
8508 if (err == 0 && zpool_has_checkpoint(zhp) &&
8509 cb->cb_type == POOL_SCAN_SCRUB) {
8510 (void) printf(gettext("warning: will not scrub state that "
8511 "belongs to the checkpoint of pool '%s'\n"),
8512 zpool_get_name(zhp));
8513 }
8514
8515 return (err != 0);
8516 }
8517
8518 static int
wait_callback(zpool_handle_t * zhp,void * data)8519 wait_callback(zpool_handle_t *zhp, void *data)
8520 {
8521 zpool_wait_activity_t *act = data;
8522 return (zpool_wait(zhp, *act));
8523 }
8524
8525 static time_t
date_string_to_sec(const char * timestr,boolean_t rounding)8526 date_string_to_sec(const char *timestr, boolean_t rounding)
8527 {
8528 struct tm tm = {0};
8529 int adjustment = rounding ? 1 : 0;
8530
8531 /* Allow mktime to determine timezone. */
8532 tm.tm_isdst = -1;
8533
8534 if (strptime(timestr, "%Y-%m-%d %H:%M", &tm) == NULL) {
8535 if (strptime(timestr, "%Y-%m-%d", &tm) == NULL) {
8536 fprintf(stderr, gettext("Failed to parse the date.\n"));
8537 usage(B_FALSE);
8538 }
8539 adjustment *= 24 * 60 * 60;
8540 } else {
8541 adjustment *= 60;
8542 }
8543
8544 return (mktime(&tm) + adjustment);
8545 }
8546
8547 /*
8548 * zpool scrub [-e | -s | -p | -C | -E | -S | -t] [-w] [-a | <pool> ...]
8549 *
8550 * -a Scrub all pools.
8551 * -e Only scrub blocks in the error log.
8552 * -E End date of scrub.
8553 * -S Start date of scrub.
8554 * -s Stop. Stops any in-progress scrub.
8555 * -p Pause. Pause in-progress scrub.
8556 * -w Wait. Blocks until scrub has completed.
8557 * -t Decompress and decrypt (if key is loaded) scrubbed blocks.
8558 * -C Scrub from last saved txg.
8559 */
8560 int
zpool_do_scrub(int argc,char ** argv)8561 zpool_do_scrub(int argc, char **argv)
8562 {
8563 int c;
8564 scrub_cbdata_t cb;
8565 boolean_t wait = B_FALSE;
8566 int error;
8567
8568 cb.cb_type = POOL_SCAN_SCRUB;
8569 cb.cb_scrub_cmd = 0;
8570 cb.cb_scrub_flags = 0;
8571 cb.cb_date_start = cb.cb_date_end = 0;
8572
8573 boolean_t is_error_scrub = B_FALSE;
8574 boolean_t is_pause = B_FALSE;
8575 boolean_t is_stop = B_FALSE;
8576 boolean_t scrub_all = B_FALSE;
8577
8578 /* check options */
8579 while ((c = getopt(argc, argv, "aspweCE:S:t")) != -1) {
8580 switch (c) {
8581 case 'a':
8582 scrub_all = B_TRUE;
8583 break;
8584 case 'e':
8585 is_error_scrub = B_TRUE;
8586 break;
8587 case 't':
8588 cb.cb_scrub_flags |= POOL_SCRUB_THOROUGH;
8589 break;
8590 case 'E':
8591 /*
8592 * Round the date. It's better to scrub more data than
8593 * less. This also makes the date inclusive.
8594 */
8595 cb.cb_date_end = date_string_to_sec(optarg, B_TRUE);
8596 break;
8597 case 's':
8598 is_stop = B_TRUE;
8599 break;
8600 case 'S':
8601 cb.cb_date_start = date_string_to_sec(optarg, B_FALSE);
8602 break;
8603 case 'p':
8604 is_pause = B_TRUE;
8605 break;
8606 case 'w':
8607 wait = B_TRUE;
8608 break;
8609 case 'C':
8610 cb.cb_scrub_cmd |= POOL_SCRUB_FROM_LAST_TXG;
8611 break;
8612 case '?':
8613 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8614 optopt);
8615 usage(B_FALSE);
8616 }
8617 }
8618
8619 if (is_pause && is_stop) {
8620 (void) fprintf(stderr, gettext("invalid option "
8621 "combination: -s and -p are mutually exclusive\n"));
8622 usage(B_FALSE);
8623 } else if (is_error_scrub && is_pause) {
8624 (void) fprintf(stderr, gettext("invalid option "
8625 "combination: -e and -p are mutually exclusive\n"));
8626 usage(B_FALSE);
8627 } else if (is_error_scrub && is_stop) {
8628 (void) fprintf(stderr, gettext("invalid option "
8629 "combination: -e and -s are mutually exclusive\n"));
8630 usage(B_FALSE);
8631 } else if (is_error_scrub &&
8632 (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8633 (void) fprintf(stderr, gettext("invalid option "
8634 "combination: -e and -C are mutually exclusive\n"));
8635 usage(B_FALSE);
8636 } else if (is_error_scrub &&
8637 (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH)) {
8638 (void) fprintf(stderr, gettext("invalid option "
8639 "combination: -e and -t are mutually exclusive\n"));
8640 usage(B_FALSE);
8641 } else if (is_pause && (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8642 (void) fprintf(stderr, gettext("invalid option "
8643 "combination: -p and -C are mutually exclusive\n"));
8644 usage(B_FALSE);
8645 } else if (is_pause && (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH)) {
8646 (void) fprintf(stderr, gettext("invalid option "
8647 "combination: -p and -t are mutually exclusive\n"));
8648 usage(B_FALSE);
8649 } else if (is_stop && (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8650 (void) fprintf(stderr, gettext("invalid option "
8651 "combination: -s and -C are mutually exclusive\n"));
8652 usage(B_FALSE);
8653 } else if (is_stop && (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH)) {
8654 (void) fprintf(stderr, gettext("invalid option "
8655 "combination: -s and -t are mutually exclusive\n"));
8656 usage(B_FALSE);
8657 } else {
8658 if (is_error_scrub)
8659 cb.cb_type = POOL_SCAN_ERRORSCRUB;
8660
8661 if (is_pause) {
8662 cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
8663 } else if (is_stop) {
8664 cb.cb_type = POOL_SCAN_NONE;
8665 }
8666 }
8667
8668 boolean_t is_thorough =
8669 (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH) != 0;
8670 if ((cb.cb_date_start != 0 || cb.cb_date_end != 0) &&
8671 (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8672 (void) fprintf(stderr, gettext("invalid option "
8673 "combination: -C and -S/-E date are mutually "
8674 "exclusive\n"));
8675 usage(B_FALSE);
8676 } else if ((cb.cb_date_start != 0 || cb.cb_date_end != 0) &&
8677 (is_error_scrub || is_stop || is_pause ||
8678 (!is_thorough && cb.cb_scrub_cmd != POOL_SCRUB_NORMAL))) {
8679 (void) fprintf(stderr, gettext("invalid option "
8680 "combination: start/end date is available only "
8681 "with normal or thorough scrub\n"));
8682 usage(B_FALSE);
8683 }
8684
8685 if (cb.cb_date_start != 0 && cb.cb_date_end != 0 &&
8686 cb.cb_date_start > cb.cb_date_end) {
8687 (void) fprintf(stderr, gettext("invalid arguments: "
8688 "end date has to be later than start date\n"));
8689 usage(B_FALSE);
8690 }
8691
8692 if (wait && (cb.cb_type == POOL_SCAN_NONE ||
8693 cb.cb_scrub_cmd == POOL_SCRUB_PAUSE)) {
8694 (void) fprintf(stderr, gettext("invalid option combination: "
8695 "-w cannot be used with -p or -s\n"));
8696 usage(B_FALSE);
8697 }
8698
8699 argc -= optind;
8700 argv += optind;
8701
8702 if (argc < 1 && !scrub_all) {
8703 (void) fprintf(stderr, gettext("missing pool name argument\n"));
8704 usage(B_FALSE);
8705 }
8706
8707 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8708 B_FALSE, scrub_callback, &cb);
8709
8710 if (wait && !error) {
8711 zpool_wait_activity_t act = ZPOOL_WAIT_SCRUB;
8712 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8713 B_FALSE, wait_callback, &act);
8714 }
8715
8716 return (error);
8717 }
8718
8719 /*
8720 * zpool resilver <pool> ...
8721 *
8722 * Restarts any in-progress resilver
8723 */
8724 int
zpool_do_resilver(int argc,char ** argv)8725 zpool_do_resilver(int argc, char **argv)
8726 {
8727 int c;
8728 scrub_cbdata_t cb;
8729
8730 cb.cb_type = POOL_SCAN_RESILVER;
8731 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8732 cb.cb_scrub_flags = 0;
8733 cb.cb_date_start = cb.cb_date_end = 0;
8734
8735 /* check options */
8736 while ((c = getopt(argc, argv, "")) != -1) {
8737 switch (c) {
8738 case '?':
8739 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8740 optopt);
8741 usage(B_FALSE);
8742 }
8743 }
8744
8745 argc -= optind;
8746 argv += optind;
8747
8748 if (argc < 1) {
8749 (void) fprintf(stderr, gettext("missing pool name argument\n"));
8750 usage(B_FALSE);
8751 }
8752
8753 return (for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8754 B_FALSE, scrub_callback, &cb));
8755 }
8756
8757 /*
8758 * zpool trim [-d] [-r <rate>] [-c | -s] <-a | pool> [<device> ...]
8759 *
8760 * -a Trim all pools.
8761 * -c Cancel. Ends any in-progress trim.
8762 * -d Secure trim. Requires kernel and device support.
8763 * -r <rate> Sets the TRIM rate in bytes (per second). Supports
8764 * adding a multiplier suffix such as 'k' or 'm'.
8765 * -s Suspend. TRIM can then be restarted with no flags.
8766 * -w Wait. Blocks until trimming has completed.
8767 */
8768 int
zpool_do_trim(int argc,char ** argv)8769 zpool_do_trim(int argc, char **argv)
8770 {
8771 struct option long_options[] = {
8772 {"cancel", no_argument, NULL, 'c'},
8773 {"secure", no_argument, NULL, 'd'},
8774 {"rate", required_argument, NULL, 'r'},
8775 {"suspend", no_argument, NULL, 's'},
8776 {"wait", no_argument, NULL, 'w'},
8777 {"all", no_argument, NULL, 'a'},
8778 {0, 0, 0, 0}
8779 };
8780
8781 pool_trim_func_t cmd_type = POOL_TRIM_START;
8782 uint64_t rate = 0;
8783 boolean_t secure = B_FALSE;
8784 boolean_t wait = B_FALSE;
8785 boolean_t trimall = B_FALSE;
8786 int error;
8787
8788 int c;
8789 while ((c = getopt_long(argc, argv, "acdr:sw", long_options, NULL))
8790 != -1) {
8791 switch (c) {
8792 case 'a':
8793 trimall = B_TRUE;
8794 break;
8795 case 'c':
8796 if (cmd_type != POOL_TRIM_START &&
8797 cmd_type != POOL_TRIM_CANCEL) {
8798 (void) fprintf(stderr, gettext("-c cannot be "
8799 "combined with other options\n"));
8800 usage(B_FALSE);
8801 }
8802 cmd_type = POOL_TRIM_CANCEL;
8803 break;
8804 case 'd':
8805 if (cmd_type != POOL_TRIM_START) {
8806 (void) fprintf(stderr, gettext("-d cannot be "
8807 "combined with the -c or -s options\n"));
8808 usage(B_FALSE);
8809 }
8810 secure = B_TRUE;
8811 break;
8812 case 'r':
8813 if (cmd_type != POOL_TRIM_START) {
8814 (void) fprintf(stderr, gettext("-r cannot be "
8815 "combined with the -c or -s options\n"));
8816 usage(B_FALSE);
8817 }
8818 if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
8819 (void) fprintf(stderr, "%s: %s\n",
8820 gettext("invalid value for rate"),
8821 libzfs_error_description(g_zfs));
8822 usage(B_FALSE);
8823 }
8824 break;
8825 case 's':
8826 if (cmd_type != POOL_TRIM_START &&
8827 cmd_type != POOL_TRIM_SUSPEND) {
8828 (void) fprintf(stderr, gettext("-s cannot be "
8829 "combined with other options\n"));
8830 usage(B_FALSE);
8831 }
8832 cmd_type = POOL_TRIM_SUSPEND;
8833 break;
8834 case 'w':
8835 wait = B_TRUE;
8836 break;
8837 case '?':
8838 if (optopt != 0) {
8839 (void) fprintf(stderr,
8840 gettext("invalid option '%c'\n"), optopt);
8841 } else {
8842 (void) fprintf(stderr,
8843 gettext("invalid option '%s'\n"),
8844 argv[optind - 1]);
8845 }
8846 usage(B_FALSE);
8847 }
8848 }
8849
8850 argc -= optind;
8851 argv += optind;
8852
8853 trimflags_t trim_flags = {
8854 .secure = secure,
8855 .rate = rate,
8856 .wait = wait,
8857 };
8858
8859 trim_cbdata_t cbdata = {
8860 .trim_flags = trim_flags,
8861 .cmd_type = cmd_type
8862 };
8863
8864 if (argc < 1 && !trimall) {
8865 (void) fprintf(stderr, gettext("missing pool name argument\n"));
8866 usage(B_FALSE);
8867 }
8868
8869 if (wait && (cmd_type != POOL_TRIM_START)) {
8870 (void) fprintf(stderr, gettext("-w cannot be used with -c or "
8871 "-s options\n"));
8872 usage(B_FALSE);
8873 }
8874
8875 if (trimall && argc > 0) {
8876 (void) fprintf(stderr, gettext("-a cannot be combined with "
8877 "individual zpools or vdevs\n"));
8878 usage(B_FALSE);
8879 }
8880
8881 if (argc == 0 && trimall) {
8882 cbdata.trim_flags.fullpool = B_TRUE;
8883 /* Trim each pool recursively */
8884 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8885 B_FALSE, zpool_trim_one, &cbdata);
8886 } else if (argc == 1) {
8887 char *poolname = argv[0];
8888 zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8889 if (zhp == NULL)
8890 return (-1);
8891 /* no individual leaf vdevs specified, so add them all */
8892 error = zpool_trim_one(zhp, &cbdata);
8893 zpool_close(zhp);
8894 } else {
8895 char *poolname = argv[0];
8896 zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8897 if (zhp == NULL)
8898 return (-1);
8899 /* leaf vdevs specified, trim only those */
8900 cbdata.trim_flags.fullpool = B_FALSE;
8901 nvlist_t *vdevs = fnvlist_alloc();
8902 for (int i = 1; i < argc; i++) {
8903 fnvlist_add_boolean(vdevs, argv[i]);
8904 }
8905 error = zpool_trim(zhp, cbdata.cmd_type, vdevs,
8906 &cbdata.trim_flags);
8907 fnvlist_free(vdevs);
8908 zpool_close(zhp);
8909 }
8910
8911 return (error);
8912 }
8913
8914 static const char *condense_types[] = {
8915 POOL_CONDENSE_LOG_SPACEMAP,
8916 #ifdef ZFS_DEBUG
8917 "debug",
8918 #endif
8919 NULL,
8920 };
8921
8922 typedef struct {
8923 const char *cmd;
8924 const char *type;
8925 } condense_cb_t;
8926
8927 static int
condense_cb(zpool_handle_t * zhp,void * data)8928 condense_cb(zpool_handle_t *zhp, void *data)
8929 {
8930 condense_cb_t *cb = data;
8931 if (cb->type != NULL)
8932 return (zpool_condense(zhp, cb->cmd, cb->type));
8933
8934 int err = 0;
8935 for (uint_t i = 0; condense_types[i] != NULL; i++) {
8936 #ifdef ZFS_DEBUG
8937 /*
8938 * Skip the debug type when no type is specificed. This is
8939 * the "condense everything" mode, and people _do_ run debug
8940 * builds, and we don't want them to be accidentally running
8941 * the debug condense op.
8942 */
8943 if (strcmp(condense_types[i], "debug") == 0)
8944 continue;
8945 #endif
8946 err = zpool_condense(zhp, cb->cmd, condense_types[i]);
8947
8948 /*
8949 * Quietly ignore ENOTSUP, so we don't fail all condense types
8950 * just because one isn't supporte.d
8951 */
8952 if (err != 0 && err != ENOTSUP)
8953 break;
8954 }
8955
8956 return (err);
8957 }
8958
8959 /*
8960 * zpool condense [-t <type>] [-c | -w] [-a | <pool> ...]
8961 *
8962 * -t <type> What to condense.
8963 * -a Condense all pools.
8964 * -c Cancel. Ends any in-progress condense.
8965 * -w Wait. Blocks until condense has completed.
8966 *
8967 * Condense (flush, garbage-collect) the pool metadata on the specfied pools.
8968 */
8969 static int
zpool_do_condense(int argc,char ** argv)8970 zpool_do_condense(int argc, char **argv)
8971 {
8972 struct option long_options[] = {
8973 {"type", required_argument, NULL, 't'},
8974 {"all", no_argument, NULL, 'a'},
8975 {"cancel", no_argument, NULL, 'c'},
8976 {"wait", no_argument, NULL, 'w'},
8977 {"types", no_argument, NULL,
8978 ZPOOL_OPTION_CONDENSE_LIST_TYPES},
8979 {0, 0, 0, 0}
8980 };
8981
8982 condense_cb_t cb = {
8983 .cmd = "start",
8984 .type = NULL,
8985 };
8986
8987 boolean_t cancel = B_FALSE;
8988 boolean_t all_pools = B_FALSE;
8989 boolean_t wait = B_FALSE;
8990
8991 int c;
8992 while ((c = getopt_long(argc, argv, "at:cw", long_options, NULL))
8993 != -1) {
8994 switch (c) {
8995 case 'a':
8996 all_pools = B_TRUE;
8997 break;
8998 case 't': {
8999 for (uint_t i = 0; condense_types[i] != NULL; i++) {
9000 if (strcmp(condense_types[i], optarg) == 0) {
9001 cb.type = condense_types[i];
9002 break;
9003 }
9004 }
9005 if (cb.type == NULL) {
9006 (void) fprintf(stderr,
9007 gettext("invalid condense type '%s'\n"),
9008 optarg);
9009 usage(B_FALSE);
9010 }
9011 break;
9012 }
9013 case 'c':
9014 cb.cmd = "cancel";
9015 cancel = B_TRUE;
9016 break;
9017 case 'w':
9018 wait = B_TRUE;
9019 break;
9020 case ZPOOL_OPTION_CONDENSE_LIST_TYPES:
9021 for (uint_t i = 0; condense_types[i] != NULL; i++)
9022 printf("%s\n", condense_types[i]);
9023 return (0);
9024 case '?':
9025 if (optopt != 0) {
9026 (void) fprintf(stderr,
9027 gettext("invalid option '%c'\n"), optopt);
9028 } else {
9029 (void) fprintf(stderr,
9030 gettext("invalid option '%s'\n"),
9031 argv[optind - 1]);
9032 }
9033 usage(B_FALSE);
9034 }
9035 }
9036
9037 argc -= optind;
9038 argv += optind;
9039
9040 if (argc < 1 && !all_pools) {
9041 (void) fprintf(stderr, gettext("missing pool name argument\n"));
9042 usage(B_FALSE);
9043 return (-1);
9044 }
9045
9046 if (wait && cancel) {
9047 (void) fprintf(stderr, gettext("-w cannot be used with -c\n"));
9048 usage(B_FALSE);
9049 }
9050
9051 int error = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9052 B_FALSE, condense_cb, &cb);
9053
9054 if (wait && !error) {
9055 zpool_wait_activity_t act = ZPOOL_WAIT_CONDENSE;
9056 error = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9057 B_FALSE, wait_callback, &act);
9058 }
9059
9060 return (error);
9061 }
9062
9063
9064 /*
9065 * Converts a total number of seconds to a human readable string broken
9066 * down in to days/hours/minutes/seconds.
9067 */
9068 static void
secs_to_dhms(uint64_t total,char * buf)9069 secs_to_dhms(uint64_t total, char *buf)
9070 {
9071 uint64_t days = total / 60 / 60 / 24;
9072 uint64_t hours = (total / 60 / 60) % 24;
9073 uint64_t mins = (total / 60) % 60;
9074 uint64_t secs = (total % 60);
9075
9076 if (days > 0) {
9077 (void) sprintf(buf, "%llu days %02llu:%02llu:%02llu",
9078 (u_longlong_t)days, (u_longlong_t)hours,
9079 (u_longlong_t)mins, (u_longlong_t)secs);
9080 } else {
9081 (void) sprintf(buf, "%02llu:%02llu:%02llu",
9082 (u_longlong_t)hours, (u_longlong_t)mins,
9083 (u_longlong_t)secs);
9084 }
9085 }
9086
9087 /*
9088 * Print out detailed error scrub status.
9089 */
9090 static void
print_err_scrub_status(pool_scan_stat_t * ps)9091 print_err_scrub_status(pool_scan_stat_t *ps)
9092 {
9093 time_t start, end, pause;
9094 uint64_t total_secs_left;
9095 uint64_t secs_left, mins_left, hours_left, days_left;
9096 uint64_t examined, to_be_examined;
9097
9098 if (ps == NULL || ps->pss_error_scrub_func != POOL_SCAN_ERRORSCRUB) {
9099 return;
9100 }
9101
9102 (void) printf(gettext(" scrub: "));
9103
9104 start = ps->pss_error_scrub_start;
9105 end = ps->pss_error_scrub_end;
9106 pause = ps->pss_pass_error_scrub_pause;
9107 examined = ps->pss_error_scrub_examined;
9108 to_be_examined = ps->pss_error_scrub_to_be_examined;
9109
9110 assert(ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB);
9111
9112 if (ps->pss_error_scrub_state == DSS_FINISHED) {
9113 total_secs_left = end - start;
9114 days_left = total_secs_left / 60 / 60 / 24;
9115 hours_left = (total_secs_left / 60 / 60) % 24;
9116 mins_left = (total_secs_left / 60) % 60;
9117 secs_left = (total_secs_left % 60);
9118
9119 (void) printf(gettext("scrubbed %llu error blocks in %llu days "
9120 "%02llu:%02llu:%02llu on %s"), (u_longlong_t)examined,
9121 (u_longlong_t)days_left, (u_longlong_t)hours_left,
9122 (u_longlong_t)mins_left, (u_longlong_t)secs_left,
9123 ctime(&end));
9124
9125 return;
9126 } else if (ps->pss_error_scrub_state == DSS_CANCELED) {
9127 (void) printf(gettext("error scrub canceled on %s"),
9128 ctime(&end));
9129 return;
9130 }
9131 assert(ps->pss_error_scrub_state == DSS_ERRORSCRUBBING);
9132
9133 /* Error scrub is in progress. */
9134 if (pause == 0) {
9135 (void) printf(gettext("error scrub in progress since %s"),
9136 ctime(&start));
9137 } else {
9138 (void) printf(gettext("error scrub paused since %s"),
9139 ctime(&pause));
9140 (void) printf(gettext("\terror scrub started on %s"),
9141 ctime(&start));
9142 }
9143
9144 double fraction_done = (double)examined / (to_be_examined + examined);
9145 (void) printf(gettext("\t%.2f%% done, issued I/O for %llu error"
9146 " blocks"), 100 * fraction_done, (u_longlong_t)examined);
9147
9148 (void) printf("\n");
9149 }
9150
9151 /*
9152 * Print out detailed scrub status.
9153 */
9154 static void
print_scan_scrub_resilver_status(pool_scan_stat_t * ps,boolean_t is_thorough)9155 print_scan_scrub_resilver_status(pool_scan_stat_t *ps, boolean_t is_thorough)
9156 {
9157 time_t start, end, pause;
9158 uint64_t pass_scanned, scanned, pass_issued, issued, total_s, total_i;
9159 uint64_t elapsed, scan_rate, issue_rate;
9160 double fraction_done;
9161 char processed_buf[7], scanned_buf[7], issued_buf[7], total_s_buf[7];
9162 char total_i_buf[7], srate_buf[7], irate_buf[7], time_buf[32];
9163
9164 printf(" ");
9165 (void) printf_color(ANSI_BOLD, gettext("scan:"));
9166 printf(" ");
9167
9168 /* If there's never been a scan, there's not much to say. */
9169 if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
9170 ps->pss_func >= POOL_SCAN_FUNCS) {
9171 (void) printf(gettext("none requested\n"));
9172 return;
9173 }
9174
9175 start = ps->pss_start_time;
9176 end = ps->pss_end_time;
9177 pause = ps->pss_pass_scrub_pause;
9178
9179 zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
9180
9181 int is_resilver = ps->pss_func == POOL_SCAN_RESILVER;
9182 int is_scrub = ps->pss_func == POOL_SCAN_SCRUB;
9183 assert(is_resilver || is_scrub);
9184
9185 /* Scan is finished or canceled. */
9186 if (ps->pss_state == DSS_FINISHED) {
9187 secs_to_dhms(end - start, time_buf);
9188
9189 if (is_scrub) {
9190 if (is_thorough) {
9191 (void) printf(gettext("thorough scrub "
9192 "repaired %s in %s with %llu errors on %s"),
9193 processed_buf, time_buf,
9194 (u_longlong_t)ps->pss_errors, ctime(&end));
9195 } else {
9196 (void) printf(gettext("scrub repaired %s "
9197 "in %s with %llu errors on %s"),
9198 processed_buf, time_buf,
9199 (u_longlong_t)ps->pss_errors, ctime(&end));
9200 }
9201 } else if (is_resilver) {
9202 (void) printf(gettext("resilvered %s "
9203 "in %s with %llu errors on %s"), processed_buf,
9204 time_buf, (u_longlong_t)ps->pss_errors,
9205 ctime(&end));
9206 }
9207 return;
9208 } else if (ps->pss_state == DSS_CANCELED) {
9209 if (is_scrub) {
9210 if (is_thorough) {
9211 (void) printf(gettext("thorough scrub canceled "
9212 "on %s"), ctime(&end));
9213 } else {
9214 (void) printf(gettext("scrub canceled on %s"),
9215 ctime(&end));
9216 }
9217 } else if (is_resilver) {
9218 (void) printf(gettext("resilver canceled on %s"),
9219 ctime(&end));
9220 }
9221 return;
9222 }
9223
9224 assert(ps->pss_state == DSS_SCANNING);
9225
9226 /* Scan is in progress. Resilvers can't be paused. */
9227 if (is_scrub) {
9228 if (pause == 0) {
9229 if (is_thorough) {
9230 (void) printf(gettext("thorough scrub "
9231 "in progress since %s"), ctime(&start));
9232 } else {
9233 (void) printf(gettext("scrub in progress "
9234 "since %s"), ctime(&start));
9235 }
9236 } else {
9237 if (is_thorough) {
9238 (void) printf(gettext("thorough scrub paused "
9239 "since %s"), ctime(&pause));
9240 (void) printf(gettext("\tthorough scrub "
9241 "started on %s"), ctime(&start));
9242 } else {
9243 (void) printf(gettext("scrub paused since %s"),
9244 ctime(&pause));
9245 (void) printf(gettext("\tscrub started on %s"),
9246 ctime(&start));
9247 }
9248 }
9249 } else if (is_resilver) {
9250 (void) printf(gettext("resilver in progress since %s"),
9251 ctime(&start));
9252 }
9253
9254 scanned = ps->pss_examined;
9255 pass_scanned = ps->pss_pass_exam;
9256 issued = ps->pss_issued;
9257 pass_issued = ps->pss_pass_issued;
9258 total_s = ps->pss_to_examine;
9259 total_i = ps->pss_to_examine - ps->pss_skipped;
9260
9261 /* we are only done with a block once we have issued the IO for it */
9262 fraction_done = (double)issued / total_i;
9263
9264 /* elapsed time for this pass, rounding up to 1 if it's 0 */
9265 elapsed = time(NULL) - ps->pss_pass_start;
9266 elapsed -= ps->pss_pass_scrub_spent_paused;
9267 elapsed = (elapsed != 0) ? elapsed : 1;
9268
9269 scan_rate = pass_scanned / elapsed;
9270 issue_rate = pass_issued / elapsed;
9271
9272 /* format all of the numbers we will be reporting */
9273 zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
9274 zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
9275 zfs_nicebytes(total_s, total_s_buf, sizeof (total_s_buf));
9276 zfs_nicebytes(total_i, total_i_buf, sizeof (total_i_buf));
9277
9278 /* do not print estimated time if we have a paused scrub */
9279 (void) printf(gettext("\t%s / %s scanned"), scanned_buf, total_s_buf);
9280 if (pause == 0 && scan_rate > 0) {
9281 zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
9282 (void) printf(gettext(" at %s/s"), srate_buf);
9283 }
9284 (void) printf(gettext(", %s / %s issued"), issued_buf, total_i_buf);
9285 if (pause == 0 && issue_rate > 0) {
9286 zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
9287 (void) printf(gettext(" at %s/s"), irate_buf);
9288 }
9289 (void) printf(gettext("\n"));
9290
9291 if (is_resilver) {
9292 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
9293 processed_buf, 100 * fraction_done);
9294 } else if (is_scrub) {
9295 (void) printf(gettext("\t%s repaired, %.2f%% done"),
9296 processed_buf, 100 * fraction_done);
9297 }
9298
9299 if (pause == 0) {
9300 /*
9301 * Only provide an estimate iff:
9302 * 1) we haven't yet issued all we expected, and
9303 * 2) the issue rate exceeds 10 MB/s, and
9304 * 3) it's either:
9305 * a) a resilver which has started repairs, or
9306 * b) a scrub which has entered the issue phase.
9307 */
9308 if (total_i >= issued && issue_rate >= 10 * 1024 * 1024 &&
9309 ((is_resilver && ps->pss_processed > 0) ||
9310 (is_scrub && issued > 0))) {
9311 secs_to_dhms((total_i - issued) / issue_rate, time_buf);
9312 (void) printf(gettext(", %s to go\n"), time_buf);
9313 } else {
9314 (void) printf(gettext(", no estimated "
9315 "completion time\n"));
9316 }
9317 } else {
9318 (void) printf(gettext("\n"));
9319 }
9320 }
9321
9322 static void
print_rebuild_status_impl(vdev_rebuild_stat_t * vrs,uint_t c,char * vdev_name)9323 print_rebuild_status_impl(vdev_rebuild_stat_t *vrs, uint_t c, char *vdev_name)
9324 {
9325 if (vrs == NULL || vrs->vrs_state == VDEV_REBUILD_NONE)
9326 return;
9327
9328 printf(" ");
9329 (void) printf_color(ANSI_BOLD, gettext("scan:"));
9330 printf(" ");
9331
9332 uint64_t bytes_scanned = vrs->vrs_bytes_scanned;
9333 uint64_t bytes_issued = vrs->vrs_bytes_issued;
9334 uint64_t bytes_rebuilt = vrs->vrs_bytes_rebuilt;
9335 uint64_t bytes_est_s = vrs->vrs_bytes_est;
9336 uint64_t bytes_est_i = vrs->vrs_bytes_est;
9337 if (c > offsetof(vdev_rebuild_stat_t, vrs_pass_bytes_skipped) / 8)
9338 bytes_est_i -= vrs->vrs_pass_bytes_skipped;
9339 uint64_t scan_rate = (vrs->vrs_pass_bytes_scanned /
9340 (vrs->vrs_pass_time_ms + 1)) * 1000;
9341 uint64_t issue_rate = (vrs->vrs_pass_bytes_issued /
9342 (vrs->vrs_pass_time_ms + 1)) * 1000;
9343 double scan_pct = MIN((double)bytes_scanned * 100 /
9344 (bytes_est_s + 1), 100);
9345
9346 /* Format all of the numbers we will be reporting */
9347 char bytes_scanned_buf[7], bytes_issued_buf[7];
9348 char bytes_rebuilt_buf[7], bytes_est_s_buf[7], bytes_est_i_buf[7];
9349 char scan_rate_buf[7], issue_rate_buf[7], time_buf[32];
9350 zfs_nicebytes(bytes_scanned, bytes_scanned_buf,
9351 sizeof (bytes_scanned_buf));
9352 zfs_nicebytes(bytes_issued, bytes_issued_buf,
9353 sizeof (bytes_issued_buf));
9354 zfs_nicebytes(bytes_rebuilt, bytes_rebuilt_buf,
9355 sizeof (bytes_rebuilt_buf));
9356 zfs_nicebytes(bytes_est_s, bytes_est_s_buf, sizeof (bytes_est_s_buf));
9357 zfs_nicebytes(bytes_est_i, bytes_est_i_buf, sizeof (bytes_est_i_buf));
9358
9359 time_t start = vrs->vrs_start_time;
9360 time_t end = vrs->vrs_end_time;
9361
9362 /* Rebuild is finished or canceled. */
9363 if (vrs->vrs_state == VDEV_REBUILD_COMPLETE) {
9364 secs_to_dhms(vrs->vrs_scan_time_ms / 1000, time_buf);
9365 (void) printf(gettext("resilvered (%s) %s in %s "
9366 "with %llu errors on %s"), vdev_name, bytes_rebuilt_buf,
9367 time_buf, (u_longlong_t)vrs->vrs_errors, ctime(&end));
9368 return;
9369 } else if (vrs->vrs_state == VDEV_REBUILD_CANCELED) {
9370 (void) printf(gettext("resilver (%s) canceled on %s"),
9371 vdev_name, ctime(&end));
9372 return;
9373 } else if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9374 (void) printf(gettext("resilver (%s) in progress since %s"),
9375 vdev_name, ctime(&start));
9376 }
9377
9378 assert(vrs->vrs_state == VDEV_REBUILD_ACTIVE);
9379
9380 (void) printf(gettext("\t%s / %s scanned"), bytes_scanned_buf,
9381 bytes_est_s_buf);
9382 if (scan_rate > 0) {
9383 zfs_nicebytes(scan_rate, scan_rate_buf, sizeof (scan_rate_buf));
9384 (void) printf(gettext(" at %s/s"), scan_rate_buf);
9385 }
9386 (void) printf(gettext(", %s / %s issued"), bytes_issued_buf,
9387 bytes_est_i_buf);
9388 if (issue_rate > 0) {
9389 zfs_nicebytes(issue_rate, issue_rate_buf,
9390 sizeof (issue_rate_buf));
9391 (void) printf(gettext(" at %s/s"), issue_rate_buf);
9392 }
9393 (void) printf(gettext("\n"));
9394
9395 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
9396 bytes_rebuilt_buf, scan_pct);
9397
9398 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9399 if (bytes_est_s >= bytes_scanned &&
9400 scan_rate >= 10 * 1024 * 1024) {
9401 secs_to_dhms((bytes_est_s - bytes_scanned) / scan_rate,
9402 time_buf);
9403 (void) printf(gettext(", %s to go\n"), time_buf);
9404 } else {
9405 (void) printf(gettext(", no estimated "
9406 "completion time\n"));
9407 }
9408 } else {
9409 (void) printf(gettext("\n"));
9410 }
9411 }
9412
9413 /*
9414 * Print rebuild status for top-level vdevs.
9415 */
9416 static void
print_rebuild_status(zpool_handle_t * zhp,nvlist_t * nvroot)9417 print_rebuild_status(zpool_handle_t *zhp, nvlist_t *nvroot)
9418 {
9419 nvlist_t **child;
9420 uint_t children;
9421
9422 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9423 &child, &children) != 0)
9424 children = 0;
9425
9426 for (uint_t c = 0; c < children; c++) {
9427 vdev_rebuild_stat_t *vrs;
9428 uint_t i;
9429
9430 if (nvlist_lookup_uint64_array(child[c],
9431 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9432 char *name = zpool_vdev_name(g_zfs, zhp,
9433 child[c], VDEV_NAME_TYPE_ID);
9434 print_rebuild_status_impl(vrs, i, name);
9435 free(name);
9436 }
9437 }
9438 }
9439
9440 /*
9441 * As we don't scrub checkpointed blocks, we want to warn the user that we
9442 * skipped scanning some blocks if a checkpoint exists or existed at any
9443 * time during the scan. If a sequential instead of healing reconstruction
9444 * was performed then the blocks were reconstructed. However, their checksums
9445 * have not been verified so we still print the warning.
9446 */
9447 static void
print_checkpoint_scan_warning(pool_scan_stat_t * ps,pool_checkpoint_stat_t * pcs)9448 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
9449 {
9450 if (ps == NULL || pcs == NULL)
9451 return;
9452
9453 if (pcs->pcs_state == CS_NONE ||
9454 pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
9455 return;
9456
9457 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
9458
9459 if (ps->pss_state == DSS_NONE)
9460 return;
9461
9462 if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
9463 ps->pss_end_time < pcs->pcs_start_time)
9464 return;
9465
9466 if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
9467 (void) printf(gettext(" scan warning: skipped blocks "
9468 "that are only referenced by the checkpoint.\n"));
9469 } else {
9470 assert(ps->pss_state == DSS_SCANNING);
9471 (void) printf(gettext(" scan warning: skipping blocks "
9472 "that are only referenced by the checkpoint.\n"));
9473 }
9474 }
9475
9476 /*
9477 * Returns B_TRUE if there is an active rebuild in progress. Otherwise,
9478 * B_FALSE is returned and 'rebuild_end_time' is set to the end time for
9479 * the last completed (or cancelled) rebuild.
9480 */
9481 static boolean_t
check_rebuilding(nvlist_t * nvroot,uint64_t * rebuild_end_time)9482 check_rebuilding(nvlist_t *nvroot, uint64_t *rebuild_end_time)
9483 {
9484 nvlist_t **child;
9485 uint_t children;
9486 boolean_t rebuilding = B_FALSE;
9487 uint64_t end_time = 0;
9488
9489 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9490 &child, &children) != 0)
9491 children = 0;
9492
9493 for (uint_t c = 0; c < children; c++) {
9494 vdev_rebuild_stat_t *vrs;
9495 uint_t i;
9496
9497 if (nvlist_lookup_uint64_array(child[c],
9498 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9499
9500 if (vrs->vrs_end_time > end_time)
9501 end_time = vrs->vrs_end_time;
9502
9503 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9504 rebuilding = B_TRUE;
9505 end_time = 0;
9506 break;
9507 }
9508 }
9509 }
9510
9511 if (rebuild_end_time != NULL)
9512 *rebuild_end_time = end_time;
9513
9514 return (rebuilding);
9515 }
9516
9517 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)9518 vdev_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9519 int depth, boolean_t isspare, char *parent, nvlist_t *item)
9520 {
9521 nvlist_t *vds, **child, *ch = NULL;
9522 uint_t vsc, children;
9523 vdev_stat_t *vs;
9524 char *vname;
9525 uint64_t notpresent;
9526 const char *type, *path;
9527
9528 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
9529 &child, &children) != 0)
9530 children = 0;
9531 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
9532 (uint64_t **)&vs, &vsc) == 0);
9533 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
9534 if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9535 return;
9536
9537 if (cb->cb_print_unhealthy && depth > 0 &&
9538 for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
9539 return;
9540 }
9541 vname = zpool_vdev_name(g_zfs, zhp, nv,
9542 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9543 vds = fnvlist_alloc();
9544 fill_vdev_info(vds, zhp, vname, B_FALSE, cb->cb_json_as_int);
9545 if (cb->cb_flat_vdevs && parent != NULL) {
9546 fnvlist_add_string(vds, "parent", parent);
9547 }
9548
9549 if (isspare) {
9550 if (vs->vs_aux == VDEV_AUX_SPARED) {
9551 fnvlist_add_string(vds, "state", "INUSE");
9552 used_by_other(zhp, nv, vds);
9553 } else if (vs->vs_state == VDEV_STATE_HEALTHY)
9554 fnvlist_add_string(vds, "state", "AVAIL");
9555 } else {
9556 if (vs->vs_alloc) {
9557 nice_num_str_nvlist(vds, "alloc_space", vs->vs_alloc,
9558 cb->cb_literal, cb->cb_json_as_int,
9559 ZFS_NICENUM_BYTES);
9560 }
9561 if (vs->vs_space) {
9562 nice_num_str_nvlist(vds, "total_space", vs->vs_space,
9563 cb->cb_literal, cb->cb_json_as_int,
9564 ZFS_NICENUM_BYTES);
9565 }
9566 if (vs->vs_dspace) {
9567 nice_num_str_nvlist(vds, "def_space", vs->vs_dspace,
9568 cb->cb_literal, cb->cb_json_as_int,
9569 ZFS_NICENUM_BYTES);
9570 }
9571 if (vs->vs_rsize) {
9572 nice_num_str_nvlist(vds, "rep_dev_size", vs->vs_rsize,
9573 cb->cb_literal, cb->cb_json_as_int,
9574 ZFS_NICENUM_BYTES);
9575 }
9576 if (vs->vs_esize) {
9577 nice_num_str_nvlist(vds, "ex_dev_size", vs->vs_esize,
9578 cb->cb_literal, cb->cb_json_as_int,
9579 ZFS_NICENUM_BYTES);
9580 }
9581 if (vs->vs_self_healed) {
9582 nice_num_str_nvlist(vds, "self_healed",
9583 vs->vs_self_healed, cb->cb_literal,
9584 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9585 }
9586 if (vs->vs_pspace) {
9587 nice_num_str_nvlist(vds, "phys_space", vs->vs_pspace,
9588 cb->cb_literal, cb->cb_json_as_int,
9589 ZFS_NICENUM_BYTES);
9590 }
9591 nice_num_str_nvlist(vds, "read_errors", vs->vs_read_errors,
9592 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9593 nice_num_str_nvlist(vds, "write_errors", vs->vs_write_errors,
9594 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9595 nice_num_str_nvlist(vds, "checksum_errors",
9596 vs->vs_checksum_errors, cb->cb_literal,
9597 cb->cb_json_as_int, ZFS_NICENUM_1024);
9598 if (vs->vs_scan_processed) {
9599 nice_num_str_nvlist(vds, "scan_processed",
9600 vs->vs_scan_processed, cb->cb_literal,
9601 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9602 }
9603 if (vs->vs_checkpoint_space) {
9604 nice_num_str_nvlist(vds, "checkpoint_space",
9605 vs->vs_checkpoint_space, cb->cb_literal,
9606 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9607 }
9608 if (vs->vs_resilver_deferred) {
9609 nice_num_str_nvlist(vds, "resilver_deferred",
9610 vs->vs_resilver_deferred, B_TRUE,
9611 cb->cb_json_as_int, ZFS_NICENUM_1024);
9612 }
9613 if (children == 0) {
9614 nice_num_str_nvlist(vds, "slow_ios", vs->vs_slow_ios,
9615 cb->cb_literal, cb->cb_json_as_int,
9616 ZFS_NICENUM_1024);
9617 }
9618 if (cb->cb_print_power) {
9619 if (children == 0) {
9620 /* Only leaf vdevs have physical slots */
9621 switch (zpool_power_current_state(zhp, (char *)
9622 fnvlist_lookup_string(nv,
9623 ZPOOL_CONFIG_PATH))) {
9624 case 0:
9625 fnvlist_add_string(vds, "power_state",
9626 "off");
9627 break;
9628 case 1:
9629 fnvlist_add_string(vds, "power_state",
9630 "on");
9631 break;
9632 default:
9633 fnvlist_add_string(vds, "power_state",
9634 "-");
9635 }
9636 } else {
9637 fnvlist_add_string(vds, "power_state", "-");
9638 }
9639 }
9640 }
9641
9642 if (cb->cb_print_dio_verify) {
9643 nice_num_str_nvlist(vds, "dio_verify_errors",
9644 vs->vs_dio_verify_errors, cb->cb_literal,
9645 cb->cb_json_as_int, ZFS_NICENUM_1024);
9646 }
9647
9648 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
9649 ¬present) == 0) {
9650 nice_num_str_nvlist(vds, ZPOOL_CONFIG_NOT_PRESENT,
9651 1, B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9652 fnvlist_add_string(vds, "was",
9653 fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH));
9654 } else if (vs->vs_aux != VDEV_AUX_NONE) {
9655 fnvlist_add_string(vds, "aux", vdev_aux_str[vs->vs_aux]);
9656 } else if (children == 0 && !isspare &&
9657 getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
9658 VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
9659 vs->vs_configured_ashift < vs->vs_physical_ashift) {
9660 nice_num_str_nvlist(vds, "configured_ashift",
9661 vs->vs_configured_ashift, B_TRUE, cb->cb_json_as_int,
9662 ZFS_NICENUM_1024);
9663 nice_num_str_nvlist(vds, "physical_ashift",
9664 vs->vs_physical_ashift, B_TRUE, cb->cb_json_as_int,
9665 ZFS_NICENUM_1024);
9666 }
9667 if (vs->vs_scan_removing != 0) {
9668 nice_num_str_nvlist(vds, "removing", vs->vs_scan_removing,
9669 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9670 } else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
9671 nice_num_str_nvlist(vds, "noalloc", vs->vs_noalloc,
9672 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9673 }
9674
9675 if (cb->vcdl != NULL) {
9676 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
9677 zpool_nvlist_cmd(cb->vcdl, zpool_get_name(zhp),
9678 path, vds);
9679 }
9680 }
9681
9682 if (children == 0) {
9683 if (cb->cb_print_vdev_init) {
9684 if (vs->vs_initialize_state != 0) {
9685 uint64_t st = vs->vs_initialize_state;
9686 fnvlist_add_string(vds, "init_state",
9687 vdev_init_state_str[st]);
9688 nice_num_str_nvlist(vds, "initialized",
9689 vs->vs_initialize_bytes_done,
9690 cb->cb_literal, cb->cb_json_as_int,
9691 ZFS_NICENUM_BYTES);
9692 nice_num_str_nvlist(vds, "to_initialize",
9693 vs->vs_initialize_bytes_est,
9694 cb->cb_literal, cb->cb_json_as_int,
9695 ZFS_NICENUM_BYTES);
9696 nice_num_str_nvlist(vds, "init_time",
9697 vs->vs_initialize_action_time,
9698 cb->cb_literal, cb->cb_json_as_int,
9699 ZFS_NICE_TIMESTAMP);
9700 nice_num_str_nvlist(vds, "init_errors",
9701 vs->vs_initialize_errors,
9702 cb->cb_literal, cb->cb_json_as_int,
9703 ZFS_NICENUM_1024);
9704 } else {
9705 fnvlist_add_string(vds, "init_state",
9706 "UNINITIALIZED");
9707 }
9708 }
9709 if (cb->cb_print_vdev_trim) {
9710 if (vs->vs_trim_notsup == 0) {
9711 if (vs->vs_trim_state != 0) {
9712 uint64_t st = vs->vs_trim_state;
9713 fnvlist_add_string(vds, "trim_state",
9714 vdev_trim_state_str[st]);
9715 nice_num_str_nvlist(vds, "trimmed",
9716 vs->vs_trim_bytes_done,
9717 cb->cb_literal, cb->cb_json_as_int,
9718 ZFS_NICENUM_BYTES);
9719 nice_num_str_nvlist(vds, "to_trim",
9720 vs->vs_trim_bytes_est,
9721 cb->cb_literal, cb->cb_json_as_int,
9722 ZFS_NICENUM_BYTES);
9723 nice_num_str_nvlist(vds, "trim_time",
9724 vs->vs_trim_action_time,
9725 cb->cb_literal, cb->cb_json_as_int,
9726 ZFS_NICE_TIMESTAMP);
9727 nice_num_str_nvlist(vds, "trim_errors",
9728 vs->vs_trim_errors,
9729 cb->cb_literal, cb->cb_json_as_int,
9730 ZFS_NICENUM_1024);
9731 } else
9732 fnvlist_add_string(vds, "trim_state",
9733 "UNTRIMMED");
9734 }
9735 nice_num_str_nvlist(vds, "trim_notsup",
9736 vs->vs_trim_notsup, B_TRUE,
9737 cb->cb_json_as_int, ZFS_NICENUM_1024);
9738 }
9739 } else {
9740 ch = fnvlist_alloc();
9741 }
9742
9743 if (cb->cb_flat_vdevs && children == 0) {
9744 fnvlist_add_nvlist(item, vname, vds);
9745 }
9746
9747 for (int c = 0; c < children; c++) {
9748 uint64_t islog = B_FALSE, ishole = B_FALSE;
9749 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9750 &islog);
9751 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
9752 &ishole);
9753 if (islog || ishole)
9754 continue;
9755 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
9756 continue;
9757 if (cb->cb_flat_vdevs) {
9758 vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9759 vname, item);
9760 }
9761 vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9762 vname, ch);
9763 }
9764
9765 if (ch != NULL) {
9766 if (!nvlist_empty(ch))
9767 fnvlist_add_nvlist(vds, "vdevs", ch);
9768 fnvlist_free(ch);
9769 }
9770 fnvlist_add_nvlist(item, vname, vds);
9771 fnvlist_free(vds);
9772 free(vname);
9773 }
9774
9775 static void
class_vdevs_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,const char * class,nvlist_t * item)9776 class_vdevs_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9777 const char *class, nvlist_t *item)
9778 {
9779 uint_t c, children;
9780 nvlist_t **child;
9781 nvlist_t *class_obj = NULL;
9782
9783 if (!cb->cb_flat_vdevs)
9784 class_obj = fnvlist_alloc();
9785
9786 assert(zhp != NULL || !cb->cb_verbose);
9787
9788 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
9789 &children) != 0)
9790 return;
9791
9792 for (c = 0; c < children; c++) {
9793 uint64_t is_log = B_FALSE;
9794 const char *bias = NULL;
9795 const char *type = NULL;
9796 char *name = zpool_vdev_name(g_zfs, zhp, child[c],
9797 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9798
9799 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9800 &is_log);
9801
9802 if (is_log) {
9803 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
9804 } else {
9805 (void) nvlist_lookup_string(child[c],
9806 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
9807 (void) nvlist_lookup_string(child[c],
9808 ZPOOL_CONFIG_TYPE, &type);
9809 }
9810
9811 if (bias == NULL || strcmp(bias, class) != 0)
9812 continue;
9813 if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9814 continue;
9815
9816 if (cb->cb_flat_vdevs) {
9817 vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9818 NULL, item);
9819 } else {
9820 vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9821 NULL, class_obj);
9822 }
9823 free(name);
9824 }
9825 if (!cb->cb_flat_vdevs) {
9826 if (!nvlist_empty(class_obj))
9827 fnvlist_add_nvlist(item, class, class_obj);
9828 fnvlist_free(class_obj);
9829 }
9830 }
9831
9832 static void
l2cache_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,nvlist_t * item)9833 l2cache_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9834 nvlist_t *item)
9835 {
9836 nvlist_t *l2c = NULL, **l2cache;
9837 uint_t nl2cache;
9838 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
9839 &l2cache, &nl2cache) == 0) {
9840 if (nl2cache == 0)
9841 return;
9842 if (!cb->cb_flat_vdevs)
9843 l2c = fnvlist_alloc();
9844 for (int i = 0; i < nl2cache; i++) {
9845 if (cb->cb_flat_vdevs) {
9846 vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9847 B_FALSE, NULL, item);
9848 } else {
9849 vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9850 B_FALSE, NULL, l2c);
9851 }
9852 }
9853 }
9854 if (!cb->cb_flat_vdevs) {
9855 if (!nvlist_empty(l2c))
9856 fnvlist_add_nvlist(item, "l2cache", l2c);
9857 fnvlist_free(l2c);
9858 }
9859 }
9860
9861 static void
spares_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,nvlist_t * item)9862 spares_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9863 nvlist_t *item)
9864 {
9865 nvlist_t *sp = NULL, **spares;
9866 uint_t nspares;
9867 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
9868 &spares, &nspares) == 0) {
9869 if (nspares == 0)
9870 return;
9871 if (!cb->cb_flat_vdevs)
9872 sp = fnvlist_alloc();
9873 for (int i = 0; i < nspares; i++) {
9874 if (cb->cb_flat_vdevs) {
9875 vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9876 NULL, item);
9877 } else {
9878 vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9879 NULL, sp);
9880 }
9881 }
9882 }
9883 if (!cb->cb_flat_vdevs) {
9884 if (!nvlist_empty(sp))
9885 fnvlist_add_nvlist(item, "spares", sp);
9886 fnvlist_free(sp);
9887 }
9888 }
9889
9890 static void
errors_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * item)9891 errors_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9892 {
9893 uint64_t nerr;
9894 nvlist_t *config = zpool_get_config(zhp, NULL);
9895 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
9896 &nerr) == 0) {
9897 nice_num_str_nvlist(item, ZPOOL_CONFIG_ERRCOUNT, nerr,
9898 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9899 if (nerr != 0 && cb->cb_verbose) {
9900 nvlist_t *nverrlist = NULL;
9901 if (zpool_get_errlog(zhp, &nverrlist) == 0) {
9902 int i = 0;
9903 int count = 0;
9904 size_t len = MAXPATHLEN * 2;
9905 nvpair_t *elem = NULL;
9906
9907 for (nvpair_t *pair =
9908 nvlist_next_nvpair(nverrlist, NULL);
9909 pair != NULL;
9910 pair = nvlist_next_nvpair(nverrlist, pair))
9911 count++;
9912 char **errl = (char **)malloc(
9913 count * sizeof (char *));
9914
9915 while ((elem = nvlist_next_nvpair(nverrlist,
9916 elem)) != NULL) {
9917 nvlist_t *nv;
9918 uint64_t dsobj, obj;
9919
9920 verify(nvpair_value_nvlist(elem,
9921 &nv) == 0);
9922 verify(nvlist_lookup_uint64(nv,
9923 ZPOOL_ERR_DATASET, &dsobj) == 0);
9924 verify(nvlist_lookup_uint64(nv,
9925 ZPOOL_ERR_OBJECT, &obj) == 0);
9926 errl[i] = safe_malloc(len);
9927 zpool_obj_to_path(zhp, dsobj, obj,
9928 errl[i++], len);
9929 }
9930 nvlist_free(nverrlist);
9931 fnvlist_add_string_array(item, "errlist",
9932 (const char **)errl, count);
9933 for (int i = 0; i < count; ++i)
9934 free(errl[i]);
9935 free(errl);
9936 } else
9937 fnvlist_add_string(item, "errlist",
9938 strerror(errno));
9939 }
9940 }
9941 }
9942
9943 static void
ddt_stats_nvlist(ddt_stat_t * dds,status_cbdata_t * cb,nvlist_t * item)9944 ddt_stats_nvlist(ddt_stat_t *dds, status_cbdata_t *cb, nvlist_t *item)
9945 {
9946 nice_num_str_nvlist(item, "blocks", dds->dds_blocks,
9947 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9948 nice_num_str_nvlist(item, "logical_size", dds->dds_lsize,
9949 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9950 nice_num_str_nvlist(item, "physical_size", dds->dds_psize,
9951 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9952 nice_num_str_nvlist(item, "deflated_size", dds->dds_dsize,
9953 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9954 nice_num_str_nvlist(item, "ref_blocks", dds->dds_ref_blocks,
9955 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9956 nice_num_str_nvlist(item, "ref_lsize", dds->dds_ref_lsize,
9957 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9958 nice_num_str_nvlist(item, "ref_psize", dds->dds_ref_psize,
9959 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9960 nice_num_str_nvlist(item, "ref_dsize", dds->dds_ref_dsize,
9961 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9962 }
9963
9964 static void
dedup_stats_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * item)9965 dedup_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9966 {
9967 nvlist_t *config;
9968 if (cb->cb_dedup_stats) {
9969 ddt_histogram_t *ddh;
9970 ddt_stat_t *dds;
9971 ddt_object_t *ddo;
9972 nvlist_t *ddt_stat, *ddt_obj, *dedup;
9973 uint_t c;
9974 uint64_t cspace_prop;
9975
9976 config = zpool_get_config(zhp, NULL);
9977 if (nvlist_lookup_uint64_array(config,
9978 ZPOOL_CONFIG_DDT_OBJ_STATS, (uint64_t **)&ddo, &c) != 0)
9979 return;
9980
9981 dedup = fnvlist_alloc();
9982 ddt_obj = fnvlist_alloc();
9983 nice_num_str_nvlist(dedup, "obj_count", ddo->ddo_count,
9984 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9985 if (ddo->ddo_count == 0) {
9986 fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
9987 ddt_obj);
9988 fnvlist_add_nvlist(item, "dedup_stats", dedup);
9989 fnvlist_free(ddt_obj);
9990 fnvlist_free(dedup);
9991 return;
9992 } else {
9993 nice_num_str_nvlist(dedup, "dspace", ddo->ddo_dspace,
9994 cb->cb_literal, cb->cb_json_as_int,
9995 ZFS_NICENUM_1024);
9996 nice_num_str_nvlist(dedup, "mspace", ddo->ddo_mspace,
9997 cb->cb_literal, cb->cb_json_as_int,
9998 ZFS_NICENUM_1024);
9999 /*
10000 * Squash cached size into in-core size to handle race.
10001 * Only include cached size if it is available.
10002 */
10003 cspace_prop = zpool_get_prop_int(zhp,
10004 ZPOOL_PROP_DEDUPCACHED, NULL);
10005 cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
10006 nice_num_str_nvlist(dedup, "cspace", cspace_prop,
10007 cb->cb_literal, cb->cb_json_as_int,
10008 ZFS_NICENUM_1024);
10009 }
10010
10011 ddt_stat = fnvlist_alloc();
10012 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
10013 (uint64_t **)&dds, &c) == 0) {
10014 nvlist_t *total = fnvlist_alloc();
10015 if (dds->dds_blocks == 0)
10016 fnvlist_add_string(total, "blocks", "0");
10017 else
10018 ddt_stats_nvlist(dds, cb, total);
10019 fnvlist_add_nvlist(ddt_stat, "total", total);
10020 fnvlist_free(total);
10021 }
10022 if (nvlist_lookup_uint64_array(config,
10023 ZPOOL_CONFIG_DDT_HISTOGRAM, (uint64_t **)&ddh, &c) == 0) {
10024 nvlist_t *hist = fnvlist_alloc();
10025 nvlist_t *entry = NULL;
10026 char buf[16];
10027 for (int h = 0; h < 64; h++) {
10028 if (ddh->ddh_stat[h].dds_blocks != 0) {
10029 entry = fnvlist_alloc();
10030 ddt_stats_nvlist(&ddh->ddh_stat[h], cb,
10031 entry);
10032 (void) snprintf(buf, 16, "%d", h);
10033 fnvlist_add_nvlist(hist, buf, entry);
10034 fnvlist_free(entry);
10035 }
10036 }
10037 if (!nvlist_empty(hist))
10038 fnvlist_add_nvlist(ddt_stat, "histogram", hist);
10039 fnvlist_free(hist);
10040 }
10041
10042 if (!nvlist_empty(ddt_obj)) {
10043 fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
10044 ddt_obj);
10045 }
10046 fnvlist_free(ddt_obj);
10047 if (!nvlist_empty(ddt_stat)) {
10048 fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_STATS,
10049 ddt_stat);
10050 }
10051 fnvlist_free(ddt_stat);
10052 if (!nvlist_empty(dedup))
10053 fnvlist_add_nvlist(item, "dedup_stats", dedup);
10054 fnvlist_free(dedup);
10055 }
10056 }
10057
10058 static void
raidz_expand_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)10059 raidz_expand_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
10060 nvlist_t *nvroot, nvlist_t *item)
10061 {
10062 uint_t c;
10063 pool_raidz_expand_stat_t *pres = NULL;
10064 if (nvlist_lookup_uint64_array(nvroot,
10065 ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c) == 0) {
10066 nvlist_t **child;
10067 uint_t children;
10068 nvlist_t *nv = fnvlist_alloc();
10069 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10070 &child, &children) == 0);
10071 assert(pres->pres_expanding_vdev < children);
10072 char *name =
10073 zpool_vdev_name(g_zfs, zhp,
10074 child[pres->pres_expanding_vdev], 0);
10075 fill_vdev_info(nv, zhp, name, B_FALSE, cb->cb_json_as_int);
10076 fnvlist_add_string(nv, "state",
10077 pool_scan_state_str[pres->pres_state]);
10078 nice_num_str_nvlist(nv, "expanding_vdev",
10079 pres->pres_expanding_vdev, B_TRUE, cb->cb_json_as_int,
10080 ZFS_NICENUM_1024);
10081 nice_num_str_nvlist(nv, "start_time", pres->pres_start_time,
10082 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10083 nice_num_str_nvlist(nv, "end_time", pres->pres_end_time,
10084 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10085 nice_num_str_nvlist(nv, "to_reflow", pres->pres_to_reflow,
10086 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10087 nice_num_str_nvlist(nv, "reflowed", pres->pres_reflowed,
10088 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10089 nice_num_str_nvlist(nv, "waiting_for_resilver",
10090 pres->pres_waiting_for_resilver, B_TRUE,
10091 cb->cb_json_as_int, ZFS_NICENUM_1024);
10092 fnvlist_add_nvlist(item, ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, nv);
10093 fnvlist_free(nv);
10094 free(name);
10095 }
10096 }
10097
10098 static void
checkpoint_status_nvlist(nvlist_t * nvroot,status_cbdata_t * cb,nvlist_t * item)10099 checkpoint_status_nvlist(nvlist_t *nvroot, status_cbdata_t *cb,
10100 nvlist_t *item)
10101 {
10102 uint_t c;
10103 pool_checkpoint_stat_t *pcs = NULL;
10104 if (nvlist_lookup_uint64_array(nvroot,
10105 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c) == 0) {
10106 nvlist_t *nv = fnvlist_alloc();
10107 fnvlist_add_string(nv, "state",
10108 checkpoint_state_str[pcs->pcs_state]);
10109 nice_num_str_nvlist(nv, "start_time",
10110 pcs->pcs_start_time, cb->cb_literal, cb->cb_json_as_int,
10111 ZFS_NICE_TIMESTAMP);
10112 nice_num_str_nvlist(nv, "space",
10113 pcs->pcs_space, cb->cb_literal, cb->cb_json_as_int,
10114 ZFS_NICENUM_BYTES);
10115 fnvlist_add_nvlist(item, ZPOOL_CONFIG_CHECKPOINT_STATS, nv);
10116 fnvlist_free(nv);
10117 }
10118 }
10119
10120 static void
removal_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)10121 removal_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
10122 nvlist_t *nvroot, nvlist_t *item)
10123 {
10124 uint_t c;
10125 pool_removal_stat_t *prs = NULL;
10126 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_REMOVAL_STATS,
10127 (uint64_t **)&prs, &c) == 0) {
10128 if (prs->prs_state != DSS_NONE) {
10129 nvlist_t **child;
10130 uint_t children;
10131 verify(nvlist_lookup_nvlist_array(nvroot,
10132 ZPOOL_CONFIG_CHILDREN, &child, &children) == 0);
10133 assert(prs->prs_removing_vdev < children);
10134 char *vdev_name = zpool_vdev_name(g_zfs, zhp,
10135 child[prs->prs_removing_vdev], B_TRUE);
10136 nvlist_t *nv = fnvlist_alloc();
10137 fill_vdev_info(nv, zhp, vdev_name, B_FALSE,
10138 cb->cb_json_as_int);
10139 fnvlist_add_string(nv, "state",
10140 pool_scan_state_str[prs->prs_state]);
10141 nice_num_str_nvlist(nv, "removing_vdev",
10142 prs->prs_removing_vdev, B_TRUE, cb->cb_json_as_int,
10143 ZFS_NICENUM_1024);
10144 nice_num_str_nvlist(nv, "start_time",
10145 prs->prs_start_time, cb->cb_literal,
10146 cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10147 nice_num_str_nvlist(nv, "end_time", prs->prs_end_time,
10148 cb->cb_literal, cb->cb_json_as_int,
10149 ZFS_NICE_TIMESTAMP);
10150 nice_num_str_nvlist(nv, "to_copy", prs->prs_to_copy,
10151 cb->cb_literal, cb->cb_json_as_int,
10152 ZFS_NICENUM_BYTES);
10153 nice_num_str_nvlist(nv, "copied", prs->prs_copied,
10154 cb->cb_literal, cb->cb_json_as_int,
10155 ZFS_NICENUM_BYTES);
10156 nice_num_str_nvlist(nv, "mapping_memory",
10157 prs->prs_mapping_memory, cb->cb_literal,
10158 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10159 fnvlist_add_nvlist(item,
10160 ZPOOL_CONFIG_REMOVAL_STATS, nv);
10161 fnvlist_free(nv);
10162 free(vdev_name);
10163 }
10164 }
10165 }
10166
10167 static void
condense_status_nvlist(nvlist_t * nvroot,status_cbdata_t * cb,nvlist_t * item)10168 condense_status_nvlist(nvlist_t *nvroot, status_cbdata_t *cb, nvlist_t *item)
10169 {
10170 nvlist_t *cnv = NULL;
10171 nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_CONDENSE_STATS, &cnv);
10172 if (cnv == NULL)
10173 return;
10174
10175 nvlist_t *onv = fnvlist_alloc();
10176 for (nvpair_t *nvp = nvlist_next_nvpair(cnv, NULL);
10177 nvp != NULL; nvp = nvlist_next_nvpair(cnv, nvp)) {
10178 const char *type = nvpair_name(nvp);
10179 nvlist_t *tnv = fnvpair_value_nvlist(nvp);
10180
10181 uint64_t start_time = fnvlist_lookup_uint64(tnv, "start_time");
10182 if (start_time == 0)
10183 continue;
10184
10185 uint64_t end_time = fnvlist_lookup_uint64(tnv, "end_time");
10186 uint64_t processed = fnvlist_lookup_uint64(tnv, "processed");
10187 uint64_t total = fnvlist_lookup_uint64(tnv, "total");
10188
10189 nvlist_t *nv = fnvlist_alloc();
10190 nice_num_str_nvlist(nv, "start_time", start_time,
10191 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10192 if (end_time > 0)
10193 nice_num_str_nvlist(nv, "end_time", end_time,
10194 cb->cb_literal, cb->cb_json_as_int,
10195 ZFS_NICE_TIMESTAMP);
10196 nice_num_str_nvlist(nv, "processed", processed,
10197 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10198 nice_num_str_nvlist(nv, "total", total,
10199 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10200
10201 fnvlist_add_string(nv, "unit", condense_unit(type));
10202
10203 fnvlist_add_nvlist(onv, type, nv);
10204 fnvlist_free(nv);
10205 }
10206
10207 if (fnvlist_num_pairs(onv))
10208 fnvlist_add_nvlist(item, "condense", onv);
10209
10210 fnvlist_free(onv);
10211 }
10212
10213
10214 static void
scan_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)10215 scan_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
10216 nvlist_t *nvroot, nvlist_t *item)
10217 {
10218 pool_scan_stat_t *ps = NULL;
10219 uint_t c;
10220 nvlist_t *scan = fnvlist_alloc();
10221 nvlist_t **child;
10222 uint_t children;
10223
10224 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
10225 (uint64_t **)&ps, &c) == 0) {
10226 fnvlist_add_string(scan, "function",
10227 pool_scan_func_str[ps->pss_func]);
10228 fnvlist_add_string(scan, "state",
10229 pool_scan_state_str[ps->pss_state]);
10230 nice_num_str_nvlist(scan, "start_time", ps->pss_start_time,
10231 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10232 nice_num_str_nvlist(scan, "end_time", ps->pss_end_time,
10233 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10234 nice_num_str_nvlist(scan, "to_examine", ps->pss_to_examine,
10235 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10236 nice_num_str_nvlist(scan, "examined", ps->pss_examined,
10237 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10238 nice_num_str_nvlist(scan, "skipped", ps->pss_skipped,
10239 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10240 nice_num_str_nvlist(scan, "processed", ps->pss_processed,
10241 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10242 nice_num_str_nvlist(scan, "errors", ps->pss_errors,
10243 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10244 nice_num_str_nvlist(scan, "bytes_per_scan", ps->pss_pass_exam,
10245 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10246 nice_num_str_nvlist(scan, "pass_start", ps->pss_pass_start,
10247 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
10248 nice_num_str_nvlist(scan, "scrub_pause",
10249 ps->pss_pass_scrub_pause, cb->cb_literal,
10250 cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10251 nice_num_str_nvlist(scan, "scrub_spent_paused",
10252 ps->pss_pass_scrub_spent_paused,
10253 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
10254 nice_num_str_nvlist(scan, "issued_bytes_per_scan",
10255 ps->pss_pass_issued, cb->cb_literal,
10256 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10257 nice_num_str_nvlist(scan, "issued", ps->pss_issued,
10258 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10259 if (ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB &&
10260 ps->pss_error_scrub_start > ps->pss_start_time) {
10261 fnvlist_add_string(scan, "err_scrub_func",
10262 pool_scan_func_str[ps->pss_error_scrub_func]);
10263 fnvlist_add_string(scan, "err_scrub_state",
10264 pool_scan_state_str[ps->pss_error_scrub_state]);
10265 nice_num_str_nvlist(scan, "err_scrub_start_time",
10266 ps->pss_error_scrub_start,
10267 cb->cb_literal, cb->cb_json_as_int,
10268 ZFS_NICE_TIMESTAMP);
10269 nice_num_str_nvlist(scan, "err_scrub_end_time",
10270 ps->pss_error_scrub_end,
10271 cb->cb_literal, cb->cb_json_as_int,
10272 ZFS_NICE_TIMESTAMP);
10273 nice_num_str_nvlist(scan, "err_scrub_examined",
10274 ps->pss_error_scrub_examined,
10275 cb->cb_literal, cb->cb_json_as_int,
10276 ZFS_NICENUM_1024);
10277 nice_num_str_nvlist(scan, "err_scrub_to_examine",
10278 ps->pss_error_scrub_to_be_examined,
10279 cb->cb_literal, cb->cb_json_as_int,
10280 ZFS_NICENUM_1024);
10281 nice_num_str_nvlist(scan, "err_scrub_pause",
10282 ps->pss_pass_error_scrub_pause,
10283 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
10284 }
10285 }
10286
10287 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10288 &child, &children) == 0) {
10289 vdev_rebuild_stat_t *vrs;
10290 uint_t i;
10291 char *name;
10292 nvlist_t *nv;
10293 nvlist_t *rebuild = fnvlist_alloc();
10294 uint64_t st;
10295 for (uint_t c = 0; c < children; c++) {
10296 if (nvlist_lookup_uint64_array(child[c],
10297 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs,
10298 &i) == 0) {
10299 if (vrs->vrs_state != VDEV_REBUILD_NONE) {
10300 nv = fnvlist_alloc();
10301 name = zpool_vdev_name(g_zfs, zhp,
10302 child[c], VDEV_NAME_TYPE_ID);
10303 fill_vdev_info(nv, zhp, name, B_FALSE,
10304 cb->cb_json_as_int);
10305 st = vrs->vrs_state;
10306 fnvlist_add_string(nv, "state",
10307 vdev_rebuild_state_str[st]);
10308 nice_num_str_nvlist(nv, "start_time",
10309 vrs->vrs_start_time, cb->cb_literal,
10310 cb->cb_json_as_int,
10311 ZFS_NICE_TIMESTAMP);
10312 nice_num_str_nvlist(nv, "end_time",
10313 vrs->vrs_end_time, cb->cb_literal,
10314 cb->cb_json_as_int,
10315 ZFS_NICE_TIMESTAMP);
10316 nice_num_str_nvlist(nv, "scan_time",
10317 vrs->vrs_scan_time_ms * 1000000,
10318 cb->cb_literal, cb->cb_json_as_int,
10319 ZFS_NICENUM_TIME);
10320 nice_num_str_nvlist(nv, "scanned",
10321 vrs->vrs_bytes_scanned,
10322 cb->cb_literal, cb->cb_json_as_int,
10323 ZFS_NICENUM_BYTES);
10324 nice_num_str_nvlist(nv, "issued",
10325 vrs->vrs_bytes_issued,
10326 cb->cb_literal, cb->cb_json_as_int,
10327 ZFS_NICENUM_BYTES);
10328 nice_num_str_nvlist(nv, "rebuilt",
10329 vrs->vrs_bytes_rebuilt,
10330 cb->cb_literal, cb->cb_json_as_int,
10331 ZFS_NICENUM_BYTES);
10332 nice_num_str_nvlist(nv, "to_scan",
10333 vrs->vrs_bytes_est, cb->cb_literal,
10334 cb->cb_json_as_int,
10335 ZFS_NICENUM_BYTES);
10336 nice_num_str_nvlist(nv, "errors",
10337 vrs->vrs_errors, cb->cb_literal,
10338 cb->cb_json_as_int,
10339 ZFS_NICENUM_1024);
10340 nice_num_str_nvlist(nv, "pass_time",
10341 vrs->vrs_pass_time_ms * 1000000,
10342 cb->cb_literal, cb->cb_json_as_int,
10343 ZFS_NICENUM_TIME);
10344 nice_num_str_nvlist(nv, "pass_scanned",
10345 vrs->vrs_pass_bytes_scanned,
10346 cb->cb_literal, cb->cb_json_as_int,
10347 ZFS_NICENUM_BYTES);
10348 nice_num_str_nvlist(nv, "pass_issued",
10349 vrs->vrs_pass_bytes_issued,
10350 cb->cb_literal, cb->cb_json_as_int,
10351 ZFS_NICENUM_BYTES);
10352 nice_num_str_nvlist(nv, "pass_skipped",
10353 vrs->vrs_pass_bytes_skipped,
10354 cb->cb_literal, cb->cb_json_as_int,
10355 ZFS_NICENUM_BYTES);
10356 fnvlist_add_nvlist(rebuild, name, nv);
10357 free(name);
10358 }
10359 }
10360 }
10361 if (!nvlist_empty(rebuild))
10362 fnvlist_add_nvlist(scan, "rebuild_stats", rebuild);
10363 fnvlist_free(rebuild);
10364 }
10365
10366 if (!nvlist_empty(scan))
10367 fnvlist_add_nvlist(item, ZPOOL_CONFIG_SCAN_STATS, scan);
10368 fnvlist_free(scan);
10369 }
10370
10371 /*
10372 * Print the scan status.
10373 */
10374 static void
print_scan_status(zpool_handle_t * zhp,nvlist_t * nvroot)10375 print_scan_status(zpool_handle_t *zhp, nvlist_t *nvroot)
10376 {
10377 uint64_t rebuild_end_time = 0, resilver_end_time = 0;
10378 boolean_t have_resilver = B_FALSE, have_scrub = B_FALSE;
10379 boolean_t have_errorscrub = B_FALSE;
10380 boolean_t active_resilver = B_FALSE;
10381 pool_checkpoint_stat_t *pcs = NULL;
10382 pool_scan_stat_t *ps = NULL;
10383 uint_t c;
10384 boolean_t is_thorough = B_FALSE;
10385 time_t scrub_start = 0, errorscrub_start = 0;
10386
10387 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
10388 (uint64_t **)&ps, &c) == 0) {
10389 if (ps->pss_func == POOL_SCAN_RESILVER) {
10390 resilver_end_time = ps->pss_end_time;
10391 active_resilver = (ps->pss_state == DSS_SCANNING);
10392 }
10393
10394 have_resilver = (ps->pss_func == POOL_SCAN_RESILVER);
10395 have_scrub = (ps->pss_func == POOL_SCAN_SCRUB);
10396 scrub_start = ps->pss_start_time;
10397 if (POOL_SCAN_STAT_VALID(pss_pass_scrub_flags, c) &&
10398 (ps->pss_pass_scrub_flags & POOL_SCRUB_THOROUGH) != 0)
10399 is_thorough = B_TRUE;
10400 if (POOL_SCAN_STAT_VALID(pss_pass_error_scrub_pause, c)) {
10401 have_errorscrub = (ps->pss_error_scrub_func ==
10402 POOL_SCAN_ERRORSCRUB);
10403 errorscrub_start = ps->pss_error_scrub_start;
10404 }
10405 }
10406
10407 boolean_t active_rebuild = check_rebuilding(nvroot, &rebuild_end_time);
10408 boolean_t have_rebuild = (active_rebuild || (rebuild_end_time > 0));
10409
10410 /* Always print the scrub status when available. */
10411 if (have_scrub && scrub_start > errorscrub_start)
10412 print_scan_scrub_resilver_status(ps, is_thorough);
10413 else if (have_errorscrub && errorscrub_start >= scrub_start)
10414 print_err_scrub_status(ps);
10415
10416 /*
10417 * When there is an active resilver or rebuild print its status.
10418 * Otherwise print the status of the last resilver or rebuild.
10419 */
10420 if (active_resilver || (!active_rebuild && have_resilver &&
10421 resilver_end_time && resilver_end_time > rebuild_end_time)) {
10422 print_scan_scrub_resilver_status(ps, is_thorough);
10423 } else if (active_rebuild || (!active_resilver && have_rebuild &&
10424 rebuild_end_time && rebuild_end_time > resilver_end_time)) {
10425 print_rebuild_status(zhp, nvroot);
10426 }
10427
10428 (void) nvlist_lookup_uint64_array(nvroot,
10429 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
10430 print_checkpoint_scan_warning(ps, pcs);
10431 }
10432
10433 /*
10434 * Print out detailed removal status.
10435 */
10436 static void
print_removal_status(zpool_handle_t * zhp,pool_removal_stat_t * prs)10437 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
10438 {
10439 char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
10440 time_t start, end;
10441 nvlist_t *config, *nvroot;
10442 nvlist_t **child;
10443 uint_t children;
10444 char *vdev_name;
10445
10446 if (prs == NULL || prs->prs_state == DSS_NONE)
10447 return;
10448
10449 /*
10450 * Determine name of vdev.
10451 */
10452 config = zpool_get_config(zhp, NULL);
10453 nvroot = fnvlist_lookup_nvlist(config,
10454 ZPOOL_CONFIG_VDEV_TREE);
10455 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10456 &child, &children) == 0);
10457 assert(prs->prs_removing_vdev < children);
10458 vdev_name = zpool_vdev_name(g_zfs, zhp,
10459 child[prs->prs_removing_vdev], B_TRUE);
10460
10461 (void) printf_color(ANSI_BOLD, gettext("remove: "));
10462
10463 start = prs->prs_start_time;
10464 end = prs->prs_end_time;
10465 zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
10466
10467 /*
10468 * Removal is finished or canceled.
10469 */
10470 if (prs->prs_state == DSS_FINISHED) {
10471 uint64_t minutes_taken = (end - start) / 60;
10472
10473 (void) printf(gettext("Removal of vdev %llu copied %s "
10474 "in %lluh%um, completed on %s"),
10475 (longlong_t)prs->prs_removing_vdev,
10476 copied_buf,
10477 (u_longlong_t)(minutes_taken / 60),
10478 (uint_t)(minutes_taken % 60),
10479 ctime((time_t *)&end));
10480 } else if (prs->prs_state == DSS_CANCELED) {
10481 (void) printf(gettext("Removal of %s canceled on %s"),
10482 vdev_name, ctime(&end));
10483 } else {
10484 uint64_t copied, total, elapsed, rate, mins_left, hours_left;
10485 double fraction_done;
10486
10487 assert(prs->prs_state == DSS_SCANNING);
10488
10489 /*
10490 * Removal is in progress.
10491 */
10492 (void) printf(gettext(
10493 "Evacuation of %s in progress since %s"),
10494 vdev_name, ctime(&start));
10495
10496 copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
10497 total = prs->prs_to_copy;
10498 fraction_done = (double)copied / total;
10499
10500 /* elapsed time for this pass */
10501 elapsed = time(NULL) - prs->prs_start_time;
10502 elapsed = elapsed > 0 ? elapsed : 1;
10503 rate = copied / elapsed;
10504 rate = rate > 0 ? rate : 1;
10505 mins_left = ((total - copied) / rate) / 60;
10506 hours_left = mins_left / 60;
10507
10508 zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10509 zfs_nicenum(total, total_buf, sizeof (total_buf));
10510 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10511
10512 /*
10513 * do not print estimated time if hours_left is more than
10514 * 30 days
10515 */
10516 (void) printf(gettext(
10517 "\t%s copied out of %s at %s/s, %.2f%% done"),
10518 examined_buf, total_buf, rate_buf, 100 * fraction_done);
10519 if (hours_left < (30 * 24)) {
10520 (void) printf(gettext(", %lluh%um to go\n"),
10521 (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
10522 } else {
10523 (void) printf(gettext(
10524 ", (copy is slow, no estimated time)\n"));
10525 }
10526 }
10527 free(vdev_name);
10528
10529 if (prs->prs_mapping_memory > 0) {
10530 char mem_buf[7];
10531 zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
10532 (void) printf(gettext(
10533 "\t%s memory used for removed device mappings\n"),
10534 mem_buf);
10535 }
10536 }
10537
10538 /*
10539 * Print out detailed raidz expansion status.
10540 */
10541 static void
print_raidz_expand_status(zpool_handle_t * zhp,pool_raidz_expand_stat_t * pres)10542 print_raidz_expand_status(zpool_handle_t *zhp, pool_raidz_expand_stat_t *pres)
10543 {
10544 char copied_buf[7];
10545
10546 if (pres == NULL || pres->pres_state == DSS_NONE)
10547 return;
10548
10549 /*
10550 * Determine name of vdev.
10551 */
10552 nvlist_t *config = zpool_get_config(zhp, NULL);
10553 nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
10554 ZPOOL_CONFIG_VDEV_TREE);
10555 nvlist_t **child;
10556 uint_t children;
10557 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10558 &child, &children) == 0);
10559 assert(pres->pres_expanding_vdev < children);
10560
10561 (void) printf_color(ANSI_BOLD, gettext("expand: "));
10562
10563 time_t start = pres->pres_start_time;
10564 time_t end = pres->pres_end_time;
10565 char *vname =
10566 zpool_vdev_name(g_zfs, zhp, child[pres->pres_expanding_vdev], 0);
10567 zfs_nicenum(pres->pres_reflowed, copied_buf, sizeof (copied_buf));
10568
10569 /*
10570 * Expansion is finished or canceled.
10571 */
10572 if (pres->pres_state == DSS_FINISHED) {
10573 char time_buf[32];
10574 secs_to_dhms(end - start, time_buf);
10575
10576 (void) printf(gettext("expanded %s-%u copied %s in %s, "
10577 "on %s"), vname, (int)pres->pres_expanding_vdev,
10578 copied_buf, time_buf, ctime((time_t *)&end));
10579 } else {
10580 char examined_buf[7], total_buf[7], rate_buf[7];
10581 uint64_t copied, total, elapsed, rate, secs_left;
10582 double fraction_done;
10583
10584 assert(pres->pres_state == DSS_SCANNING);
10585
10586 /*
10587 * Expansion is in progress.
10588 */
10589 (void) printf(gettext(
10590 "expansion of %s-%u in progress since %s"),
10591 vname, (int)pres->pres_expanding_vdev, ctime(&start));
10592
10593 copied = pres->pres_reflowed > 0 ? pres->pres_reflowed : 1;
10594 total = pres->pres_to_reflow;
10595 fraction_done = (double)copied / total;
10596
10597 /* elapsed time for this pass */
10598 elapsed = time(NULL) - pres->pres_start_time;
10599 elapsed = elapsed > 0 ? elapsed : 1;
10600 rate = copied / elapsed;
10601 rate = rate > 0 ? rate : 1;
10602 secs_left = (total - copied) / rate;
10603
10604 zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10605 zfs_nicenum(total, total_buf, sizeof (total_buf));
10606 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10607
10608 /*
10609 * do not print estimated time if hours_left is more than
10610 * 30 days
10611 */
10612 (void) printf(gettext("\t%s / %s copied at %s/s, %.2f%% done"),
10613 examined_buf, total_buf, rate_buf, 100 * fraction_done);
10614 if (pres->pres_waiting_for_resilver) {
10615 (void) printf(gettext(", paused for resilver or "
10616 "clear\n"));
10617 } else if (secs_left < (30 * 24 * 3600)) {
10618 char time_buf[32];
10619 secs_to_dhms(secs_left, time_buf);
10620 (void) printf(gettext(", %s to go\n"), time_buf);
10621 } else {
10622 (void) printf(gettext(
10623 ", (copy is slow, no estimated time)\n"));
10624 }
10625 }
10626 free(vname);
10627 }
10628 static void
print_checkpoint_status(pool_checkpoint_stat_t * pcs)10629 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
10630 {
10631 time_t start;
10632 char space_buf[7];
10633
10634 if (pcs == NULL || pcs->pcs_state == CS_NONE)
10635 return;
10636
10637 (void) printf(gettext("checkpoint: "));
10638
10639 start = pcs->pcs_start_time;
10640 zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
10641
10642 if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
10643 char *date = ctime(&start);
10644
10645 /*
10646 * ctime() adds a newline at the end of the generated
10647 * string, thus the weird format specifier and the
10648 * strlen() call used to chop it off from the output.
10649 */
10650 (void) printf(gettext("created %.*s, consumes %s\n"),
10651 (int)(strlen(date) - 1), date, space_buf);
10652 return;
10653 }
10654
10655 assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
10656
10657 (void) printf(gettext("discarding, %s remaining.\n"),
10658 space_buf);
10659 }
10660
10661 static void
print_condense_status(nvlist_t * nv)10662 print_condense_status(nvlist_t *nv)
10663 {
10664 if (nv == NULL)
10665 return;
10666
10667 for (nvpair_t *nvp = nvlist_next_nvpair(nv, NULL);
10668 nvp != NULL; nvp = nvlist_next_nvpair(nv, nvp)) {
10669 const char *type = nvpair_name(nvp);
10670 nvlist_t *tnv = fnvpair_value_nvlist(nvp);
10671
10672 uint64_t start_time = fnvlist_lookup_uint64(tnv, "start_time");
10673 if (start_time == 0)
10674 continue;
10675
10676 uint64_t end_time = fnvlist_lookup_uint64(tnv, "end_time");
10677 uint64_t processed = fnvlist_lookup_uint64(tnv, "processed");
10678 uint64_t total = fnvlist_lookup_uint64(tnv, "total");
10679
10680 const char *units = condense_unit(type);
10681
10682 char cur[32], tot[32], elapsed[32];
10683 zfs_nicenum(processed, cur, sizeof (cur));
10684 zfs_nicenum(total, tot, sizeof (tot));
10685
10686 if (end_time == 0) {
10687 secs_to_dhms(time(NULL) - start_time, elapsed);
10688 (void) printf(gettext(
10689 "condense: %s: condensing, %s/%s %s done in %s\n"),
10690 type, cur, tot, units, elapsed);
10691 } else if (processed < total) {
10692 secs_to_dhms(end_time - start_time, elapsed);
10693 (void) printf(gettext(
10694 "condense: %s: cancelled, %s/%s %s done in %s\n"),
10695 type, cur, tot, units, elapsed);
10696 } else {
10697 secs_to_dhms(end_time - start_time, elapsed);
10698 (void) printf(gettext(
10699 "condense: %s: done, %s %s done in %s\n"),
10700 type, cur, units, elapsed);
10701 }
10702 }
10703 }
10704
10705 static void
print_error_log(zpool_handle_t * zhp)10706 print_error_log(zpool_handle_t *zhp)
10707 {
10708 nvlist_t *nverrlist = NULL;
10709 nvpair_t *elem;
10710 char *pathname;
10711 size_t len = MAXPATHLEN * 2;
10712
10713 if (zpool_get_errlog(zhp, &nverrlist) != 0)
10714 return;
10715
10716 (void) printf("errors: Permanent errors have been "
10717 "detected in the following files:\n\n");
10718
10719 pathname = safe_malloc(len);
10720 elem = NULL;
10721 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
10722 nvlist_t *nv;
10723 uint64_t dsobj, obj;
10724
10725 verify(nvpair_value_nvlist(elem, &nv) == 0);
10726 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
10727 &dsobj) == 0);
10728 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
10729 &obj) == 0);
10730 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
10731 (void) printf("%7s %s\n", "", pathname);
10732 }
10733 free(pathname);
10734 nvlist_free(nverrlist);
10735 }
10736
10737 static void
print_spares(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t ** spares,uint_t nspares)10738 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
10739 uint_t nspares)
10740 {
10741 uint_t i;
10742 char *name;
10743
10744 if (nspares == 0)
10745 return;
10746
10747 (void) printf(gettext("\tspares\n"));
10748
10749 for (i = 0; i < nspares; i++) {
10750 name = zpool_vdev_name(g_zfs, zhp, spares[i],
10751 cb->cb_name_flags);
10752 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE, NULL);
10753 free(name);
10754 }
10755 }
10756
10757 static void
print_l2cache(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t ** l2cache,uint_t nl2cache)10758 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
10759 uint_t nl2cache)
10760 {
10761 uint_t i;
10762 char *name;
10763
10764 if (nl2cache == 0)
10765 return;
10766
10767 (void) printf(gettext("\tcache\n"));
10768
10769 for (i = 0; i < nl2cache; i++) {
10770 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
10771 cb->cb_name_flags);
10772 print_status_config(zhp, cb, name, l2cache[i], 2,
10773 B_FALSE, NULL);
10774 free(name);
10775 }
10776 }
10777
10778 static void
print_dedup_stats(zpool_handle_t * zhp,nvlist_t * config,boolean_t literal)10779 print_dedup_stats(zpool_handle_t *zhp, nvlist_t *config, boolean_t literal)
10780 {
10781 ddt_histogram_t *ddh;
10782 ddt_stat_t *dds;
10783 ddt_object_t *ddo;
10784 uint_t c;
10785 /* Extra space provided for literal display */
10786 char dspace[32], mspace[32], cspace[32];
10787 uint64_t cspace_prop;
10788 enum zfs_nicenum_format format;
10789 zprop_source_t src;
10790
10791 /*
10792 * If the pool was faulted then we may not have been able to
10793 * obtain the config. Otherwise, if we have anything in the dedup
10794 * table continue processing the stats.
10795 */
10796 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
10797 (uint64_t **)&ddo, &c) != 0)
10798 return;
10799
10800 (void) printf("\n");
10801 (void) printf(gettext(" dedup: "));
10802 if (ddo->ddo_count == 0) {
10803 (void) printf(gettext("no DDT entries\n"));
10804 return;
10805 }
10806
10807 /*
10808 * Squash cached size into in-core size to handle race.
10809 * Only include cached size if it is available.
10810 */
10811 cspace_prop = zpool_get_prop_int(zhp, ZPOOL_PROP_DEDUPCACHED, &src);
10812 cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
10813 format = literal ? ZFS_NICENUM_RAW : ZFS_NICENUM_1024;
10814 zfs_nicenum_format(cspace_prop, cspace, sizeof (cspace), format);
10815 zfs_nicenum_format(ddo->ddo_dspace, dspace, sizeof (dspace), format);
10816 zfs_nicenum_format(ddo->ddo_mspace, mspace, sizeof (mspace), format);
10817 (void) printf("DDT entries %llu, size %s on disk, %s in core",
10818 (u_longlong_t)ddo->ddo_count,
10819 dspace,
10820 mspace);
10821 if (src != ZPROP_SRC_DEFAULT) {
10822 (void) printf(", %s cached (%.02f%%)",
10823 cspace,
10824 (double)cspace_prop / (double)ddo->ddo_mspace * 100.0);
10825 }
10826 (void) printf("\n");
10827
10828 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
10829 (uint64_t **)&dds, &c) == 0);
10830 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
10831 (uint64_t **)&ddh, &c) == 0);
10832 zpool_dump_ddt(dds, ddh, literal);
10833 }
10834
10835 #define ST_SIZE 4096
10836 #define AC_SIZE 2048
10837
10838 static void
print_status_reason(zpool_handle_t * zhp,status_cbdata_t * cbp,zpool_status_t reason,zpool_errata_t errata,nvlist_t * item)10839 print_status_reason(zpool_handle_t *zhp, status_cbdata_t *cbp,
10840 zpool_status_t reason, zpool_errata_t errata, nvlist_t *item)
10841 {
10842 char status[ST_SIZE];
10843 char action[AC_SIZE];
10844 memset(status, 0, ST_SIZE);
10845 memset(action, 0, AC_SIZE);
10846
10847 switch (reason) {
10848 case ZPOOL_STATUS_MISSING_DEV_R:
10849 (void) snprintf(status, ST_SIZE,
10850 gettext("One or more devices could "
10851 "not be opened. Sufficient replicas exist for\n\tthe pool "
10852 "to continue functioning in a degraded state.\n"));
10853 (void) snprintf(action, AC_SIZE,
10854 gettext("Attach the missing device "
10855 "and online it using 'zpool online'.\n"));
10856 break;
10857
10858 case ZPOOL_STATUS_MISSING_DEV_NR:
10859 (void) snprintf(status, ST_SIZE,
10860 gettext("One or more devices could "
10861 "not be opened. There are insufficient\n\treplicas for the"
10862 " pool to continue functioning.\n"));
10863 (void) snprintf(action, AC_SIZE,
10864 gettext("Attach the missing device "
10865 "and online it using 'zpool online'.\n"));
10866 break;
10867
10868 case ZPOOL_STATUS_CORRUPT_LABEL_R:
10869 (void) snprintf(status, ST_SIZE,
10870 gettext("One or more devices could "
10871 "not be used because the label is missing or\n\tinvalid. "
10872 "Sufficient replicas exist for the pool to continue\n\t"
10873 "functioning in a degraded state.\n"));
10874 (void) snprintf(action, AC_SIZE,
10875 gettext("Replace the device using 'zpool replace'.\n"));
10876 break;
10877
10878 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
10879 (void) snprintf(status, ST_SIZE,
10880 gettext("One or more devices could "
10881 "not be used because the label is missing \n\tor invalid. "
10882 "There are insufficient replicas for the pool to "
10883 "continue\n\tfunctioning.\n"));
10884 zpool_explain_recover(zpool_get_handle(zhp),
10885 zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
10886 action, AC_SIZE);
10887 break;
10888
10889 case ZPOOL_STATUS_FAILING_DEV:
10890 (void) snprintf(status, ST_SIZE,
10891 gettext("One or more devices has "
10892 "experienced an unrecoverable error. An\n\tattempt was "
10893 "made to correct the error. Applications are "
10894 "unaffected.\n"));
10895 (void) snprintf(action, AC_SIZE, gettext("Determine if the "
10896 "device needs to be replaced, and clear the errors\n\tusing"
10897 " 'zpool clear' or replace the device with 'zpool "
10898 "replace'.\n"));
10899 break;
10900
10901 case ZPOOL_STATUS_OFFLINE_DEV:
10902 (void) snprintf(status, ST_SIZE,
10903 gettext("One or more devices has "
10904 "been taken offline by the administrator.\n\tSufficient "
10905 "replicas exist for the pool to continue functioning in "
10906 "a\n\tdegraded state.\n"));
10907 (void) snprintf(action, AC_SIZE, gettext("Online the device "
10908 "using 'zpool online' or replace the device with\n\t'zpool "
10909 "replace'.\n"));
10910 break;
10911
10912 case ZPOOL_STATUS_REMOVED_DEV:
10913 (void) snprintf(status, ST_SIZE,
10914 gettext("One or more devices have "
10915 "been removed.\n\tSufficient replicas exist for the pool "
10916 "to continue functioning in a\n\tdegraded state.\n"));
10917 (void) snprintf(action, AC_SIZE, gettext("Online the device "
10918 "using zpool online' or replace the device with\n\t'zpool "
10919 "replace'.\n"));
10920 break;
10921
10922 case ZPOOL_STATUS_RESILVERING:
10923 case ZPOOL_STATUS_REBUILDING:
10924 (void) snprintf(status, ST_SIZE,
10925 gettext("One or more devices is "
10926 "currently being resilvered. The pool will\n\tcontinue "
10927 "to function, possibly in a degraded state.\n"));
10928 (void) snprintf(action, AC_SIZE,
10929 gettext("Wait for the resilver to complete.\n"));
10930 break;
10931
10932 case ZPOOL_STATUS_REBUILD_SCRUB:
10933 (void) snprintf(status, ST_SIZE,
10934 gettext("One or more devices have "
10935 "been sequentially resilvered, scrubbing\n\tthe pool "
10936 "is recommended.\n"));
10937 (void) snprintf(action, AC_SIZE, gettext("Use 'zpool scrub' to "
10938 "verify all data checksums.\n"));
10939 break;
10940
10941 case ZPOOL_STATUS_CORRUPT_DATA:
10942 (void) snprintf(status, ST_SIZE,
10943 gettext("One or more devices has "
10944 "experienced an error resulting in data\n\tcorruption. "
10945 "Applications may be affected.\n"));
10946 (void) snprintf(action, AC_SIZE,
10947 gettext("Restore the file in question"
10948 " if possible. Otherwise restore the\n\tentire pool from "
10949 "backup.\n"));
10950 break;
10951
10952 case ZPOOL_STATUS_CORRUPT_POOL:
10953 (void) snprintf(status, ST_SIZE, gettext("The pool metadata is "
10954 "incomplete or corrupted and the pool cannot be "
10955 "opened.\n"));
10956 zpool_explain_recover(zpool_get_handle(zhp),
10957 zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
10958 action, AC_SIZE);
10959 break;
10960
10961 case ZPOOL_STATUS_VERSION_OLDER:
10962 (void) snprintf(status, ST_SIZE,
10963 gettext("The pool is formatted using "
10964 "a legacy on-disk format. The pool can\n\tstill be used, "
10965 "but some features are unavailable.\n"));
10966 (void) snprintf(action, AC_SIZE,
10967 gettext("Upgrade the pool using "
10968 "'zpool upgrade'. Once this is done, the\n\tpool will no "
10969 "longer be accessible on software that does not support\n\t"
10970 "feature flags.\n"));
10971 break;
10972
10973 case ZPOOL_STATUS_VERSION_NEWER:
10974 (void) snprintf(status, ST_SIZE,
10975 gettext("The pool has been upgraded "
10976 "to a newer, incompatible on-disk version.\n\tThe pool "
10977 "cannot be accessed on this system.\n"));
10978 (void) snprintf(action, AC_SIZE,
10979 gettext("Access the pool from a "
10980 "system running more recent software, or\n\trestore the "
10981 "pool from backup.\n"));
10982 break;
10983
10984 case ZPOOL_STATUS_FEAT_DISABLED:
10985 (void) snprintf(status, ST_SIZE, gettext("Some supported and "
10986 "requested features are not enabled on the pool.\n\t"
10987 "The pool can still be used, but some features are "
10988 "unavailable.\n"));
10989 (void) snprintf(action, AC_SIZE,
10990 gettext("Enable all features using "
10991 "'zpool upgrade'. Once this is done,\n\tthe pool may no "
10992 "longer be accessible by software that does not support\n\t"
10993 "the features. See zpool-features(7) for details.\n"));
10994 break;
10995
10996 case ZPOOL_STATUS_COMPATIBILITY_ERR:
10997 (void) snprintf(status, ST_SIZE, gettext("This pool has a "
10998 "compatibility list specified, but it could not be\n\t"
10999 "read/parsed at this time. The pool can still be used, "
11000 "but this\n\tshould be investigated.\n"));
11001 (void) snprintf(action, AC_SIZE,
11002 gettext("Check the value of the "
11003 "'compatibility' property against the\n\t"
11004 "appropriate file in %s or %s.\n"),
11005 ZPOOL_SYSCONF_COMPAT_D, ZPOOL_DATA_COMPAT_D);
11006 break;
11007
11008 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
11009 (void) snprintf(status, ST_SIZE, gettext("One or more features "
11010 "are enabled on the pool despite not being\n\t"
11011 "requested by the 'compatibility' property.\n"));
11012 (void) snprintf(action, AC_SIZE, gettext("Consider setting "
11013 "'compatibility' to an appropriate value, or\n\t"
11014 "adding needed features to the relevant file in\n\t"
11015 "%s or %s.\n"),
11016 ZPOOL_SYSCONF_COMPAT_D, ZPOOL_DATA_COMPAT_D);
11017 break;
11018
11019 case ZPOOL_STATUS_UNSUP_FEAT_READ:
11020 (void) snprintf(status, ST_SIZE,
11021 gettext("The pool cannot be accessed "
11022 "on this system because it uses the\n\tfollowing feature(s)"
11023 " not supported on this system:\n"));
11024 zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
11025 1024);
11026 (void) snprintf(action, AC_SIZE,
11027 gettext("Access the pool from a "
11028 "system that supports the required feature(s),\n\tor "
11029 "restore the pool from backup.\n"));
11030 break;
11031
11032 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
11033 (void) snprintf(status, ST_SIZE, gettext("The pool can only be "
11034 "accessed in read-only mode on this system. It\n\tcannot be"
11035 " accessed in read-write mode because it uses the "
11036 "following\n\tfeature(s) not supported on this system:\n"));
11037 zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
11038 1024);
11039 (void) snprintf(action, AC_SIZE,
11040 gettext("The pool cannot be accessed "
11041 "in read-write mode. Import the pool with\n"
11042 "\t\"-o readonly=on\", access the pool from a system that "
11043 "supports the\n\trequired feature(s), or restore the "
11044 "pool from backup.\n"));
11045 break;
11046
11047 case ZPOOL_STATUS_FAULTED_DEV_R:
11048 (void) snprintf(status, ST_SIZE,
11049 gettext("One or more devices are "
11050 "faulted in response to persistent errors.\n\tSufficient "
11051 "replicas exist for the pool to continue functioning "
11052 "in a\n\tdegraded state.\n"));
11053 (void) snprintf(action, AC_SIZE,
11054 gettext("Replace the faulted device, "
11055 "or use 'zpool clear' to mark the device\n\trepaired.\n"));
11056 break;
11057
11058 case ZPOOL_STATUS_FAULTED_FDOM_R:
11059 (void) snprintf(status, ST_SIZE,
11060 gettext("One or more failure domains are faulted. "
11061 "The storage devices may be\n\tintact. Sufficient "
11062 "replicas exist for the pool to continue functioning\n\t"
11063 "in a degraded state.\n"));
11064 (void) snprintf(action, AC_SIZE,
11065 gettext("Replace the faulted domain device, "
11066 "or use 'zpool clear' to mark domain\n\tstorage devices "
11067 "repaired.\n"));
11068 break;
11069
11070 case ZPOOL_STATUS_FAULTED_DEV_NR:
11071 (void) snprintf(status, ST_SIZE,
11072 gettext("One or more devices are "
11073 "faulted in response to persistent errors. There are "
11074 "insufficient replicas for the pool to\n\tcontinue "
11075 "functioning.\n"));
11076 (void) snprintf(action, AC_SIZE,
11077 gettext("Destroy and re-create the "
11078 "pool from a backup source. Manually marking the device\n"
11079 "\trepaired using 'zpool clear' may allow some data "
11080 "to be recovered.\n"));
11081 break;
11082
11083 case ZPOOL_STATUS_IO_FAILURE_MMP:
11084 (void) snprintf(status, ST_SIZE,
11085 gettext("The pool is suspended "
11086 "because multihost writes failed or were delayed;\n\t"
11087 "another system could import the pool undetected.\n"));
11088 (void) snprintf(action, AC_SIZE,
11089 gettext("Make sure the pool's devices"
11090 " are connected, then reboot your system and\n\timport the "
11091 "pool or run 'zpool clear' to resume the pool.\n"));
11092 break;
11093
11094 case ZPOOL_STATUS_IO_FAILURE_WAIT:
11095 case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
11096 (void) snprintf(status, ST_SIZE,
11097 gettext("One or more devices are "
11098 "faulted in response to IO failures.\n"));
11099 (void) snprintf(action, AC_SIZE,
11100 gettext("Make sure the affected "
11101 "devices are connected, then run 'zpool clear'.\n"));
11102 break;
11103
11104 case ZPOOL_STATUS_BAD_LOG:
11105 (void) snprintf(status, ST_SIZE, gettext("An intent log record "
11106 "could not be read.\n"
11107 "\tWaiting for administrator intervention to fix the "
11108 "faulted pool.\n"));
11109 (void) snprintf(action, AC_SIZE,
11110 gettext("Either restore the affected "
11111 "device(s) and run 'zpool online',\n"
11112 "\tor ignore the intent log records by running "
11113 "'zpool clear'.\n"));
11114 break;
11115
11116 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
11117 (void) snprintf(status, ST_SIZE,
11118 gettext("One or more devices are "
11119 "configured to use a non-native block size.\n"
11120 "\tExpect reduced performance.\n"));
11121 (void) snprintf(action, AC_SIZE,
11122 gettext("Replace affected devices "
11123 "with devices that support the\n\tconfigured block size, "
11124 "or migrate data to a properly configured\n\tpool.\n"));
11125 break;
11126
11127 case ZPOOL_STATUS_HOSTID_MISMATCH:
11128 (void) snprintf(status, ST_SIZE,
11129 gettext("Mismatch between pool hostid"
11130 " and system hostid on imported pool.\n\tThis pool was "
11131 "previously imported into a system with a different "
11132 "hostid,\n\tand then was verbatim imported into this "
11133 "system.\n"));
11134 (void) snprintf(action, AC_SIZE,
11135 gettext("Export this pool on all "
11136 "systems on which it is imported.\n"
11137 "\tThen import it to correct the mismatch.\n"));
11138 break;
11139
11140 case ZPOOL_STATUS_ERRATA:
11141 (void) snprintf(status, ST_SIZE,
11142 gettext("Errata #%d detected.\n"), errata);
11143 switch (errata) {
11144 case ZPOOL_ERRATA_NONE:
11145 break;
11146
11147 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
11148 (void) snprintf(action, AC_SIZE,
11149 gettext("To correct the issue run "
11150 "'zpool scrub'.\n"));
11151 break;
11152
11153 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
11154 (void) strlcat(status, gettext("\tExisting encrypted "
11155 "datasets contain an on-disk incompatibility\n\t "
11156 "which needs to be corrected.\n"), ST_SIZE);
11157 (void) snprintf(action, AC_SIZE,
11158 gettext("To correct the issue"
11159 " backup existing encrypted datasets to new\n\t"
11160 "encrypted datasets and destroy the old ones. "
11161 "'zfs mount -o ro' can\n\tbe used to temporarily "
11162 "mount existing encrypted datasets readonly.\n"));
11163 break;
11164
11165 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
11166 (void) strlcat(status, gettext("\tExisting encrypted "
11167 "snapshots and bookmarks contain an on-disk\n\t"
11168 "incompatibility. This may cause on-disk "
11169 "corruption if they are used\n\twith "
11170 "'zfs recv'.\n"), ST_SIZE);
11171 (void) snprintf(action, AC_SIZE,
11172 gettext("To correct the"
11173 "issue, enable the bookmark_v2 feature. No "
11174 "additional\n\taction is needed if there are no "
11175 "encrypted snapshots or bookmarks.\n\tIf preserving"
11176 "the encrypted snapshots and bookmarks is required,"
11177 " use\n\ta non-raw send to backup and restore them."
11178 " Alternately, they may be\n\tremoved to resolve "
11179 "the incompatibility.\n"));
11180 break;
11181
11182 default:
11183 /*
11184 * All errata which allow the pool to be imported
11185 * must contain an action message.
11186 */
11187 assert(0);
11188 }
11189 break;
11190
11191 default:
11192 /*
11193 * The remaining errors can't actually be generated, yet.
11194 */
11195 assert(reason == ZPOOL_STATUS_OK);
11196 }
11197
11198 if (status[0] != 0) {
11199 if (cbp->cb_json)
11200 fnvlist_add_string(item, "status", status);
11201 else {
11202 (void) printf_color(ANSI_BOLD, gettext("status: "));
11203 (void) printf_color(ANSI_YELLOW, status);
11204 }
11205 }
11206
11207 if (action[0] != 0) {
11208 if (cbp->cb_json)
11209 fnvlist_add_string(item, "action", action);
11210 else {
11211 (void) printf_color(ANSI_BOLD, gettext("action: "));
11212 (void) printf_color(ANSI_YELLOW, action);
11213 }
11214 }
11215 }
11216
11217 static int
status_callback_json(zpool_handle_t * zhp,void * data)11218 status_callback_json(zpool_handle_t *zhp, void *data)
11219 {
11220 status_cbdata_t *cbp = data;
11221 nvlist_t *config, *nvroot;
11222 const char *msgid;
11223 char pool_guid[256];
11224 char msgbuf[256];
11225 uint64_t guid;
11226 zpool_status_t reason;
11227 zpool_errata_t errata;
11228 uint_t c;
11229 vdev_stat_t *vs;
11230 nvlist_t *item, *d, *load_info, *vds;
11231
11232 /* If dedup stats were requested, also fetch dedupcached. */
11233 if (cbp->cb_dedup_stats > 1)
11234 zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
11235 reason = zpool_get_status(zhp, &msgid, &errata);
11236 /*
11237 * If we were given 'zpool status -x', only report those pools with
11238 * problems.
11239 */
11240 if (cbp->cb_explain &&
11241 (reason == ZPOOL_STATUS_OK ||
11242 reason == ZPOOL_STATUS_VERSION_OLDER ||
11243 reason == ZPOOL_STATUS_FEAT_DISABLED ||
11244 reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
11245 reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
11246 return (0);
11247 }
11248
11249 d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
11250 item = fnvlist_alloc();
11251 vds = fnvlist_alloc();
11252 fill_pool_info(item, zhp, B_FALSE, cbp->cb_json_as_int);
11253 config = zpool_get_config(zhp, NULL);
11254
11255 if (config != NULL) {
11256 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
11257 verify(nvlist_lookup_uint64_array(nvroot,
11258 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &c) == 0);
11259 if (cbp->cb_json_pool_key_guid) {
11260 guid = fnvlist_lookup_uint64(config,
11261 ZPOOL_CONFIG_POOL_GUID);
11262 (void) snprintf(pool_guid, 256, "%llu",
11263 (u_longlong_t)guid);
11264 }
11265 cbp->cb_count++;
11266
11267 print_status_reason(zhp, cbp, reason, errata, item);
11268 if (msgid != NULL) {
11269 (void) snprintf(msgbuf, 256,
11270 "https://openzfs.github.io/openzfs-docs/msg/%s",
11271 msgid);
11272 fnvlist_add_string(item, "msgid", msgid);
11273 fnvlist_add_string(item, "moreinfo", msgbuf);
11274 }
11275
11276 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
11277 &load_info) == 0) {
11278 fnvlist_add_nvlist(item, ZPOOL_CONFIG_LOAD_INFO,
11279 load_info);
11280 }
11281
11282 scan_status_nvlist(zhp, cbp, nvroot, item);
11283 removal_status_nvlist(zhp, cbp, nvroot, item);
11284 checkpoint_status_nvlist(nvroot, cbp, item);
11285 condense_status_nvlist(nvroot, cbp, item);
11286 raidz_expand_status_nvlist(zhp, cbp, nvroot, item);
11287 vdev_stats_nvlist(zhp, cbp, nvroot, 0, B_FALSE, NULL, vds);
11288 if (cbp->cb_flat_vdevs) {
11289 class_vdevs_nvlist(zhp, cbp, nvroot,
11290 VDEV_ALLOC_BIAS_DEDUP, vds);
11291 class_vdevs_nvlist(zhp, cbp, nvroot,
11292 VDEV_ALLOC_BIAS_SPECIAL, vds);
11293 class_vdevs_nvlist(zhp, cbp, nvroot,
11294 VDEV_ALLOC_CLASS_LOGS, vds);
11295 l2cache_nvlist(zhp, cbp, nvroot, vds);
11296 spares_nvlist(zhp, cbp, nvroot, vds);
11297
11298 fnvlist_add_nvlist(item, "vdevs", vds);
11299 fnvlist_free(vds);
11300 } else {
11301 fnvlist_add_nvlist(item, "vdevs", vds);
11302 fnvlist_free(vds);
11303
11304 class_vdevs_nvlist(zhp, cbp, nvroot,
11305 VDEV_ALLOC_BIAS_DEDUP, item);
11306 class_vdevs_nvlist(zhp, cbp, nvroot,
11307 VDEV_ALLOC_BIAS_SPECIAL, item);
11308 class_vdevs_nvlist(zhp, cbp, nvroot,
11309 VDEV_ALLOC_CLASS_LOGS, item);
11310 l2cache_nvlist(zhp, cbp, nvroot, item);
11311 spares_nvlist(zhp, cbp, nvroot, item);
11312 }
11313 dedup_stats_nvlist(zhp, cbp, item);
11314 errors_nvlist(zhp, cbp, item);
11315 }
11316 if (cbp->cb_json_pool_key_guid) {
11317 fnvlist_add_nvlist(d, pool_guid, item);
11318 } else {
11319 fnvlist_add_nvlist(d, zpool_get_name(zhp),
11320 item);
11321 }
11322 fnvlist_free(item);
11323 return (0);
11324 }
11325
11326 /*
11327 * Display a summary of pool status. Displays a summary such as:
11328 *
11329 * pool: tank
11330 * status: DEGRADED
11331 * reason: One or more devices ...
11332 * see: https://openzfs.github.io/openzfs-docs/msg/ZFS-xxxx-01
11333 * config:
11334 * mirror DEGRADED
11335 * c1t0d0 OK
11336 * c2t0d0 UNAVAIL
11337 *
11338 * When given the '-v' option, we print out the complete config. If the '-e'
11339 * option is specified, then we print out error rate information as well.
11340 */
11341 static int
status_callback(zpool_handle_t * zhp,void * data)11342 status_callback(zpool_handle_t *zhp, void *data)
11343 {
11344 status_cbdata_t *cbp = data;
11345 nvlist_t *config, *nvroot;
11346 const char *msgid;
11347 zpool_status_t reason;
11348 zpool_errata_t errata;
11349 const char *health;
11350 uint_t c;
11351 vdev_stat_t *vs;
11352
11353 /* If dedup stats were requested, also fetch dedupcached. */
11354 if (cbp->cb_dedup_stats > 1)
11355 zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
11356
11357 config = zpool_get_config(zhp, NULL);
11358 reason = zpool_get_status(zhp, &msgid, &errata);
11359
11360 cbp->cb_count++;
11361
11362 /*
11363 * If we were given 'zpool status -x', only report those pools with
11364 * problems.
11365 */
11366 if (cbp->cb_explain &&
11367 (reason == ZPOOL_STATUS_OK ||
11368 reason == ZPOOL_STATUS_VERSION_OLDER ||
11369 reason == ZPOOL_STATUS_FEAT_DISABLED ||
11370 reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
11371 reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
11372 if (!cbp->cb_allpools) {
11373 (void) printf(gettext("pool '%s' is healthy\n"),
11374 zpool_get_name(zhp));
11375 if (cbp->cb_first)
11376 cbp->cb_first = B_FALSE;
11377 }
11378 return (0);
11379 }
11380
11381 if (cbp->cb_first)
11382 cbp->cb_first = B_FALSE;
11383 else
11384 (void) printf("\n");
11385
11386 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
11387 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
11388 (uint64_t **)&vs, &c) == 0);
11389
11390 health = zpool_get_state_str(zhp);
11391
11392 printf(" ");
11393 (void) printf_color(ANSI_BOLD, gettext("pool:"));
11394 printf(" %s\n", zpool_get_name(zhp));
11395 (void) fputc(' ', stdout);
11396 (void) printf_color(ANSI_BOLD, gettext("state: "));
11397
11398 (void) printf_color(health_str_to_color(health), "%s", health);
11399
11400 (void) fputc('\n', stdout);
11401 print_status_reason(zhp, cbp, reason, errata, NULL);
11402
11403 if (msgid != NULL) {
11404 printf(" ");
11405 (void) printf_color(ANSI_BOLD, gettext("see:"));
11406 printf(gettext(
11407 " https://openzfs.github.io/openzfs-docs/msg/%s\n"),
11408 msgid);
11409 }
11410
11411 if (config != NULL) {
11412 uint64_t nerr;
11413 nvlist_t **spares, **l2cache;
11414 uint_t nspares, nl2cache;
11415
11416 print_scan_status(zhp, nvroot);
11417
11418 pool_removal_stat_t *prs = NULL;
11419 (void) nvlist_lookup_uint64_array(nvroot,
11420 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
11421 print_removal_status(zhp, prs);
11422
11423 pool_checkpoint_stat_t *pcs = NULL;
11424 (void) nvlist_lookup_uint64_array(nvroot,
11425 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
11426 print_checkpoint_status(pcs);
11427
11428 pool_raidz_expand_stat_t *pres = NULL;
11429 (void) nvlist_lookup_uint64_array(nvroot,
11430 ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
11431 print_raidz_expand_status(zhp, pres);
11432
11433 nvlist_t *cnv = NULL;
11434 nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_CONDENSE_STATS, &cnv);
11435 print_condense_status(cnv);
11436
11437 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
11438 cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
11439 if (cbp->cb_namewidth < 10)
11440 cbp->cb_namewidth = 10;
11441
11442 color_start(ANSI_BOLD);
11443 (void) printf(gettext("config:\n\n"));
11444 (void) printf(gettext("\t%-*s %-8s %5s %5s %5s"),
11445 cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
11446 "CKSUM");
11447 color_end();
11448
11449 if (cbp->cb_print_slow_ios) {
11450 (void) printf_color(ANSI_BOLD, " %5s", gettext("SLOW"));
11451 }
11452
11453 if (cbp->cb_print_power) {
11454 (void) printf_color(ANSI_BOLD, " %5s",
11455 gettext("POWER"));
11456 }
11457
11458 if (cbp->cb_print_dio_verify) {
11459 (void) printf_color(ANSI_BOLD, " %5s", gettext("DIO"));
11460 }
11461
11462 if (cbp->vcdl != NULL)
11463 print_cmd_columns(cbp->vcdl, 0);
11464
11465 printf("\n");
11466
11467 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
11468 B_FALSE, NULL);
11469
11470 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
11471 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
11472 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
11473
11474 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
11475 &l2cache, &nl2cache) == 0)
11476 print_l2cache(zhp, cbp, l2cache, nl2cache);
11477
11478 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
11479 &spares, &nspares) == 0)
11480 print_spares(zhp, cbp, spares, nspares);
11481
11482 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
11483 &nerr) == 0) {
11484 (void) printf("\n");
11485 if (nerr == 0) {
11486 (void) printf(gettext(
11487 "errors: No known data errors\n"));
11488 } else if (!cbp->cb_verbose) {
11489 color_start(ANSI_RED);
11490 (void) printf(gettext("errors: %llu data "
11491 "errors, use '-v' for a list\n"),
11492 (u_longlong_t)nerr);
11493 color_end();
11494 } else {
11495 print_error_log(zhp);
11496 }
11497 }
11498
11499 if (cbp->cb_dedup_stats)
11500 print_dedup_stats(zhp, config, cbp->cb_literal);
11501 } else {
11502 (void) printf(gettext("config: The configuration cannot be "
11503 "determined.\n"));
11504 }
11505
11506 return (0);
11507 }
11508
11509 /*
11510 * zpool status [-dDegiLpPstvx] [-c [script1,script2,...]] ...
11511 * [-j|--json [--json-flat-vdevs] [--json-int] ...
11512 * [--json-pool-key-guid]] [--power] [-T d|u] ...
11513 * [pool] [interval [count]]
11514 *
11515 * -c CMD For each vdev, run command CMD
11516 * -D Display dedup status (undocumented)
11517 * -d Display Direct I/O write verify errors
11518 * -e Display only unhealthy vdevs
11519 * -g Display guid for individual vdev name.
11520 * -i Display vdev initialization status.
11521 * -j [...] Display output in JSON format
11522 * --json-flat-vdevs Display vdevs in flat hierarchy
11523 * --json-int Display numbers in integer format instead of string
11524 * --json-pool-key-guid Use pool GUID as key for pool objects
11525 * -L Follow links when resolving vdev path name.
11526 * -P Display full path for vdev name.
11527 * -p Display values in parsable (exact) format.
11528 * --power Display vdev enclosure slot power status
11529 * -s Display slow IOs column.
11530 * -T Display a timestamp in date(1) or Unix format
11531 * -t Display vdev TRIM status.
11532 * -v Display complete error logs
11533 * -x Display only pools with potential problems
11534 *
11535 * Describes the health status of all pools or some subset.
11536 */
11537 int
zpool_do_status(int argc,char ** argv)11538 zpool_do_status(int argc, char **argv)
11539 {
11540 int c;
11541 int ret;
11542 float interval = 0;
11543 unsigned long count = 0;
11544 status_cbdata_t cb = { 0 };
11545 nvlist_t *data;
11546 char *cmd = NULL;
11547
11548 struct option long_options[] = {
11549 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
11550 {"json", no_argument, NULL, 'j'},
11551 {"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
11552 {"json-flat-vdevs", no_argument, NULL,
11553 ZPOOL_OPTION_JSON_FLAT_VDEVS},
11554 {"json-pool-key-guid", no_argument, NULL,
11555 ZPOOL_OPTION_POOL_KEY_GUID},
11556 {0, 0, 0, 0}
11557 };
11558
11559 /* check options */
11560 while ((c = getopt_long(argc, argv, "c:jdDegiLpPstT:vx", long_options,
11561 NULL)) != -1) {
11562 switch (c) {
11563 case 'c':
11564 if (cmd != NULL) {
11565 fprintf(stderr,
11566 gettext("Can't set -c flag twice\n"));
11567 exit(1);
11568 }
11569
11570 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
11571 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
11572 fprintf(stderr, gettext(
11573 "Can't run -c, disabled by "
11574 "ZPOOL_SCRIPTS_ENABLED.\n"));
11575 exit(1);
11576 }
11577
11578 if ((getuid() <= 0 || geteuid() <= 0) &&
11579 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
11580 fprintf(stderr, gettext(
11581 "Can't run -c with root privileges "
11582 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
11583 exit(1);
11584 }
11585 cmd = optarg;
11586 break;
11587 case 'd':
11588 cb.cb_print_dio_verify = B_TRUE;
11589 break;
11590 case 'D':
11591 if (++cb.cb_dedup_stats > 2)
11592 cb.cb_dedup_stats = 2;
11593 break;
11594 case 'e':
11595 cb.cb_print_unhealthy = B_TRUE;
11596 break;
11597 case 'g':
11598 cb.cb_name_flags |= VDEV_NAME_GUID;
11599 break;
11600 case 'i':
11601 cb.cb_print_vdev_init = B_TRUE;
11602 break;
11603 case 'L':
11604 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
11605 break;
11606 case 'p':
11607 cb.cb_literal = B_TRUE;
11608 break;
11609 case 'P':
11610 cb.cb_name_flags |= VDEV_NAME_PATH;
11611 break;
11612 case 's':
11613 cb.cb_print_slow_ios = B_TRUE;
11614 break;
11615 case 't':
11616 cb.cb_print_vdev_trim = B_TRUE;
11617 break;
11618 case 'T':
11619 get_timestamp_arg(*optarg);
11620 break;
11621 case 'v':
11622 cb.cb_verbose = B_TRUE;
11623 break;
11624 case 'j':
11625 cb.cb_json = B_TRUE;
11626 break;
11627 case 'x':
11628 cb.cb_explain = B_TRUE;
11629 break;
11630 case ZPOOL_OPTION_POWER:
11631 cb.cb_print_power = B_TRUE;
11632 break;
11633 case ZPOOL_OPTION_JSON_FLAT_VDEVS:
11634 cb.cb_flat_vdevs = B_TRUE;
11635 break;
11636 case ZPOOL_OPTION_JSON_NUMS_AS_INT:
11637 cb.cb_json_as_int = B_TRUE;
11638 cb.cb_literal = B_TRUE;
11639 break;
11640 case ZPOOL_OPTION_POOL_KEY_GUID:
11641 cb.cb_json_pool_key_guid = B_TRUE;
11642 break;
11643 case '?':
11644 if (optopt == 'c') {
11645 print_zpool_script_list("status");
11646 exit(0);
11647 } else {
11648 fprintf(stderr,
11649 gettext("invalid option '%c'\n"), optopt);
11650 }
11651 usage(B_FALSE);
11652 }
11653 }
11654
11655 argc -= optind;
11656 argv += optind;
11657
11658 get_interval_count(&argc, argv, &interval, &count);
11659
11660 if (argc == 0)
11661 cb.cb_allpools = B_TRUE;
11662
11663 cb.cb_first = B_TRUE;
11664 cb.cb_print_status = B_TRUE;
11665
11666 if (cb.cb_flat_vdevs && !cb.cb_json) {
11667 fprintf(stderr, gettext("'--json-flat-vdevs' only works with"
11668 " '-j' option\n"));
11669 usage(B_FALSE);
11670 }
11671
11672 if (cb.cb_json_as_int && !cb.cb_json) {
11673 (void) fprintf(stderr, gettext("'--json-int' only works with"
11674 " '-j' option\n"));
11675 usage(B_FALSE);
11676 }
11677
11678 if (!cb.cb_json && cb.cb_json_pool_key_guid) {
11679 (void) fprintf(stderr, gettext("'json-pool-key-guid' only"
11680 " works with '-j' option\n"));
11681 usage(B_FALSE);
11682 }
11683
11684 for (;;) {
11685 if (cb.cb_json) {
11686 cb.cb_jsobj = zpool_json_schema(0, 1);
11687 data = fnvlist_alloc();
11688 fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
11689 fnvlist_free(data);
11690 }
11691
11692 if (timestamp_fmt != NODATE) {
11693 if (cb.cb_json) {
11694 if (cb.cb_json_as_int) {
11695 fnvlist_add_uint64(cb.cb_jsobj, "time",
11696 time(NULL));
11697 } else {
11698 char ts[128];
11699 get_timestamp(timestamp_fmt, ts, 128);
11700 fnvlist_add_string(cb.cb_jsobj, "time",
11701 ts);
11702 }
11703 } else
11704 print_timestamp(timestamp_fmt);
11705 }
11706
11707 if (cmd != NULL)
11708 cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
11709 NULL, NULL, 0, 0);
11710
11711 if (cb.cb_json) {
11712 ret = for_each_pool(argc, argv, B_TRUE, NULL,
11713 ZFS_TYPE_POOL, cb.cb_literal,
11714 status_callback_json, &cb);
11715 } else {
11716 ret = for_each_pool(argc, argv, B_TRUE, NULL,
11717 ZFS_TYPE_POOL, cb.cb_literal,
11718 status_callback, &cb);
11719 }
11720
11721 if (cb.vcdl != NULL)
11722 free_vdev_cmd_data_list(cb.vcdl);
11723
11724 if (cb.cb_json) {
11725 if (ret == 0)
11726 zcmd_print_json(cb.cb_jsobj);
11727 else
11728 nvlist_free(cb.cb_jsobj);
11729 } else {
11730 if (argc == 0 && cb.cb_count == 0) {
11731 (void) fprintf(stderr, "%s",
11732 gettext("no pools available\n"));
11733 } else if (cb.cb_explain && cb.cb_first &&
11734 cb.cb_allpools) {
11735 (void) printf("%s",
11736 gettext("all pools are healthy\n"));
11737 }
11738 }
11739
11740 if (ret != 0)
11741 return (ret);
11742
11743 if (interval == 0)
11744 break;
11745
11746 if (count != 0 && --count == 0)
11747 break;
11748
11749 (void) fflush(stdout);
11750 (void) fsleep(interval);
11751 }
11752
11753 return (0);
11754 }
11755
11756 typedef struct upgrade_cbdata {
11757 int cb_first;
11758 int cb_argc;
11759 uint64_t cb_version;
11760 char **cb_argv;
11761 } upgrade_cbdata_t;
11762
11763 static int
check_unsupp_fs(zfs_handle_t * zhp,void * unsupp_fs)11764 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
11765 {
11766 int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
11767 int *count = (int *)unsupp_fs;
11768
11769 if (zfs_version > ZPL_VERSION) {
11770 (void) printf(gettext("%s (v%d) is not supported by this "
11771 "implementation of ZFS.\n"),
11772 zfs_get_name(zhp), zfs_version);
11773 (*count)++;
11774 }
11775
11776 (void) zfs_iter_filesystems_v2(zhp, 0, check_unsupp_fs, unsupp_fs);
11777
11778 zfs_close(zhp);
11779
11780 return (0);
11781 }
11782
11783 static int
upgrade_version(zpool_handle_t * zhp,uint64_t version)11784 upgrade_version(zpool_handle_t *zhp, uint64_t version)
11785 {
11786 int ret;
11787 nvlist_t *config;
11788 uint64_t oldversion;
11789 int unsupp_fs = 0;
11790
11791 config = zpool_get_config(zhp, NULL);
11792 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11793 &oldversion) == 0);
11794
11795 char compat[ZFS_MAXPROPLEN];
11796 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11797 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11798 compat[0] = '\0';
11799
11800 assert(SPA_VERSION_IS_SUPPORTED(oldversion));
11801 assert(oldversion < version);
11802
11803 ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
11804 if (ret != 0)
11805 return (ret);
11806
11807 if (unsupp_fs) {
11808 (void) fprintf(stderr, gettext("Upgrade not performed due "
11809 "to %d unsupported filesystems (max v%d).\n"),
11810 unsupp_fs, (int)ZPL_VERSION);
11811 return (1);
11812 }
11813
11814 if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
11815 (void) fprintf(stderr, gettext("Upgrade not performed because "
11816 "'compatibility' property set to '"
11817 ZPOOL_COMPAT_LEGACY "'.\n"));
11818 return (1);
11819 }
11820
11821 ret = zpool_upgrade(zhp, version);
11822 if (ret != 0)
11823 return (ret);
11824
11825 if (version >= SPA_VERSION_FEATURES) {
11826 (void) printf(gettext("Successfully upgraded "
11827 "'%s' from version %llu to feature flags.\n"),
11828 zpool_get_name(zhp), (u_longlong_t)oldversion);
11829 } else {
11830 (void) printf(gettext("Successfully upgraded "
11831 "'%s' from version %llu to version %llu.\n"),
11832 zpool_get_name(zhp), (u_longlong_t)oldversion,
11833 (u_longlong_t)version);
11834 }
11835
11836 return (0);
11837 }
11838
11839 static int
upgrade_enable_all(zpool_handle_t * zhp,int * countp)11840 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
11841 {
11842 int i, ret, count;
11843 boolean_t firstff = B_TRUE;
11844 nvlist_t *enabled = zpool_get_features(zhp);
11845
11846 char compat[ZFS_MAXPROPLEN];
11847 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11848 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11849 compat[0] = '\0';
11850
11851 boolean_t requested_features[SPA_FEATURES];
11852 if (zpool_do_load_compat(compat, requested_features) !=
11853 ZPOOL_COMPATIBILITY_OK)
11854 return (-1);
11855
11856 count = 0;
11857 for (i = 0; i < SPA_FEATURES; i++) {
11858 const char *fname = spa_feature_table[i].fi_uname;
11859 const char *fguid = spa_feature_table[i].fi_guid;
11860
11861 if (!spa_feature_table[i].fi_zfs_mod_supported ||
11862 (spa_feature_table[i].fi_flags & ZFEATURE_FLAG_NO_UPGRADE))
11863 continue;
11864
11865 if (!nvlist_exists(enabled, fguid) && requested_features[i]) {
11866 char *propname;
11867 verify(-1 != asprintf(&propname, "feature@%s", fname));
11868 ret = zpool_set_prop(zhp, propname,
11869 ZFS_FEATURE_ENABLED);
11870 if (ret != 0) {
11871 free(propname);
11872 return (ret);
11873 }
11874 count++;
11875
11876 if (firstff) {
11877 (void) printf(gettext("Enabled the "
11878 "following features on '%s':\n"),
11879 zpool_get_name(zhp));
11880 firstff = B_FALSE;
11881 }
11882 (void) printf(gettext(" %s\n"), fname);
11883 free(propname);
11884 }
11885 }
11886
11887 if (countp != NULL)
11888 *countp = count;
11889 return (0);
11890 }
11891
11892 static int
upgrade_cb(zpool_handle_t * zhp,void * arg)11893 upgrade_cb(zpool_handle_t *zhp, void *arg)
11894 {
11895 upgrade_cbdata_t *cbp = arg;
11896 nvlist_t *config;
11897 uint64_t version;
11898 boolean_t modified_pool = B_FALSE;
11899 int ret;
11900
11901 config = zpool_get_config(zhp, NULL);
11902 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11903 &version) == 0);
11904
11905 assert(SPA_VERSION_IS_SUPPORTED(version));
11906
11907 if (version < cbp->cb_version) {
11908 cbp->cb_first = B_FALSE;
11909 ret = upgrade_version(zhp, cbp->cb_version);
11910 if (ret != 0)
11911 return (ret);
11912 modified_pool = B_TRUE;
11913
11914 /*
11915 * If they did "zpool upgrade -a", then we could
11916 * be doing ioctls to different pools. We need
11917 * to log this history once to each pool, and bypass
11918 * the normal history logging that happens in main().
11919 */
11920 (void) zpool_log_history(g_zfs, history_str);
11921 log_history = B_FALSE;
11922 }
11923
11924 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
11925 int count;
11926 ret = upgrade_enable_all(zhp, &count);
11927 if (ret != 0)
11928 return (ret);
11929
11930 if (count > 0) {
11931 cbp->cb_first = B_FALSE;
11932 modified_pool = B_TRUE;
11933 }
11934 }
11935
11936 if (modified_pool) {
11937 (void) printf("\n");
11938 (void) after_zpool_upgrade(zhp);
11939 }
11940
11941 return (0);
11942 }
11943
11944 static int
upgrade_list_older_cb(zpool_handle_t * zhp,void * arg)11945 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
11946 {
11947 upgrade_cbdata_t *cbp = arg;
11948 nvlist_t *config;
11949 uint64_t version;
11950
11951 config = zpool_get_config(zhp, NULL);
11952 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11953 &version) == 0);
11954
11955 assert(SPA_VERSION_IS_SUPPORTED(version));
11956
11957 if (version < SPA_VERSION_FEATURES) {
11958 if (cbp->cb_first) {
11959 (void) printf(gettext("The following pools are "
11960 "formatted with legacy version numbers and can\n"
11961 "be upgraded to use feature flags. After "
11962 "being upgraded, these pools\nwill no "
11963 "longer be accessible by software that does not "
11964 "support feature\nflags.\n\n"
11965 "Note that setting a pool's 'compatibility' "
11966 "feature to '" ZPOOL_COMPAT_LEGACY "' will\n"
11967 "inhibit upgrades.\n\n"));
11968 (void) printf(gettext("VER POOL\n"));
11969 (void) printf(gettext("--- ------------\n"));
11970 cbp->cb_first = B_FALSE;
11971 }
11972
11973 (void) printf("%2llu %s\n", (u_longlong_t)version,
11974 zpool_get_name(zhp));
11975 }
11976
11977 return (0);
11978 }
11979
11980 static int
upgrade_list_disabled_cb(zpool_handle_t * zhp,void * arg)11981 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
11982 {
11983 upgrade_cbdata_t *cbp = arg;
11984 nvlist_t *config;
11985 uint64_t version;
11986
11987 config = zpool_get_config(zhp, NULL);
11988 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11989 &version) == 0);
11990
11991 if (version >= SPA_VERSION_FEATURES) {
11992 int i;
11993 boolean_t poolfirst = B_TRUE;
11994 nvlist_t *enabled = zpool_get_features(zhp);
11995
11996 for (i = 0; i < SPA_FEATURES; i++) {
11997 const char *fguid = spa_feature_table[i].fi_guid;
11998 const char *fname = spa_feature_table[i].fi_uname;
11999
12000 if (!spa_feature_table[i].fi_zfs_mod_supported)
12001 continue;
12002
12003 if (!nvlist_exists(enabled, fguid)) {
12004 if (cbp->cb_first) {
12005 (void) printf(gettext("\nSome "
12006 "supported features are not "
12007 "enabled on the following pools. "
12008 "Once a\nfeature is enabled the "
12009 "pool may become incompatible with "
12010 "software\nthat does not support "
12011 "the feature. See "
12012 "zpool-features(7) for "
12013 "details.\n\n"
12014 "Note that the pool "
12015 "'compatibility' feature can be "
12016 "used to inhibit\nfeature "
12017 "upgrades.\n\n"
12018 "Features marked with (*) are not "
12019 "applied automatically on upgrade, "
12020 "and\nmust be applied explicitly "
12021 "with zpool-set(7).\n\n"));
12022 (void) printf(gettext("POOL "
12023 "FEATURE\n"));
12024 (void) printf(gettext("------"
12025 "---------\n"));
12026 cbp->cb_first = B_FALSE;
12027 }
12028
12029 if (poolfirst) {
12030 (void) printf(gettext("%s\n"),
12031 zpool_get_name(zhp));
12032 poolfirst = B_FALSE;
12033 }
12034
12035 (void) printf(gettext(" %s%s\n"), fname,
12036 spa_feature_table[i].fi_flags &
12037 ZFEATURE_FLAG_NO_UPGRADE ? "(*)" : "");
12038 }
12039 /*
12040 * If they did "zpool upgrade -a", then we could
12041 * be doing ioctls to different pools. We need
12042 * to log this history once to each pool, and bypass
12043 * the normal history logging that happens in main().
12044 */
12045 (void) zpool_log_history(g_zfs, history_str);
12046 log_history = B_FALSE;
12047 }
12048 }
12049
12050 return (0);
12051 }
12052
12053 static int
upgrade_one(zpool_handle_t * zhp,void * data)12054 upgrade_one(zpool_handle_t *zhp, void *data)
12055 {
12056 boolean_t modified_pool = B_FALSE;
12057 upgrade_cbdata_t *cbp = data;
12058 uint64_t cur_version;
12059 int ret;
12060
12061 if (strcmp("log", zpool_get_name(zhp)) == 0) {
12062 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
12063 "Pool 'log' must be renamed using export and import"
12064 " to upgrade.\n"));
12065 return (1);
12066 }
12067
12068 cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
12069 if (cur_version > cbp->cb_version) {
12070 (void) printf(gettext("Pool '%s' is already formatted "
12071 "using more current version '%llu'.\n\n"),
12072 zpool_get_name(zhp), (u_longlong_t)cur_version);
12073 return (0);
12074 }
12075
12076 if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
12077 (void) printf(gettext("Pool '%s' is already formatted "
12078 "using version %llu.\n\n"), zpool_get_name(zhp),
12079 (u_longlong_t)cbp->cb_version);
12080 return (0);
12081 }
12082
12083 if (cur_version != cbp->cb_version) {
12084 modified_pool = B_TRUE;
12085 ret = upgrade_version(zhp, cbp->cb_version);
12086 if (ret != 0)
12087 return (ret);
12088 }
12089
12090 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
12091 int count = 0;
12092 ret = upgrade_enable_all(zhp, &count);
12093 if (ret != 0)
12094 return (ret);
12095
12096 if (count != 0) {
12097 modified_pool = B_TRUE;
12098 } else if (cur_version == SPA_VERSION) {
12099 (void) printf(gettext("Pool '%s' already has all "
12100 "supported and requested features enabled.\n"),
12101 zpool_get_name(zhp));
12102 }
12103 }
12104
12105 if (modified_pool) {
12106 (void) printf("\n");
12107 (void) after_zpool_upgrade(zhp);
12108 }
12109
12110 return (0);
12111 }
12112
12113 /*
12114 * zpool upgrade
12115 * zpool upgrade -v
12116 * zpool upgrade [-V version] <-a | pool ...>
12117 *
12118 * With no arguments, display downrev'd ZFS pool available for upgrade.
12119 * Individual pools can be upgraded by specifying the pool, and '-a' will
12120 * upgrade all pools.
12121 */
12122 int
zpool_do_upgrade(int argc,char ** argv)12123 zpool_do_upgrade(int argc, char **argv)
12124 {
12125 int c;
12126 upgrade_cbdata_t cb = { 0 };
12127 int ret = 0;
12128 boolean_t showversions = B_FALSE;
12129 boolean_t upgradeall = B_FALSE;
12130 char *end;
12131
12132
12133 /* check options */
12134 while ((c = getopt(argc, argv, ":avV:")) != -1) {
12135 switch (c) {
12136 case 'a':
12137 upgradeall = B_TRUE;
12138 break;
12139 case 'v':
12140 showversions = B_TRUE;
12141 break;
12142 case 'V':
12143 cb.cb_version = strtoll(optarg, &end, 10);
12144 if (*end != '\0' ||
12145 !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
12146 (void) fprintf(stderr,
12147 gettext("invalid version '%s'\n"), optarg);
12148 usage(B_FALSE);
12149 }
12150 break;
12151 case ':':
12152 (void) fprintf(stderr, gettext("missing argument for "
12153 "'%c' option\n"), optopt);
12154 usage(B_FALSE);
12155 break;
12156 case '?':
12157 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
12158 optopt);
12159 usage(B_FALSE);
12160 }
12161 }
12162
12163 cb.cb_argc = argc;
12164 cb.cb_argv = argv;
12165 argc -= optind;
12166 argv += optind;
12167
12168 if (cb.cb_version == 0) {
12169 cb.cb_version = SPA_VERSION;
12170 } else if (!upgradeall && argc == 0) {
12171 (void) fprintf(stderr, gettext("-V option is "
12172 "incompatible with other arguments\n"));
12173 usage(B_FALSE);
12174 }
12175
12176 if (showversions) {
12177 if (upgradeall || argc != 0) {
12178 (void) fprintf(stderr, gettext("-v option is "
12179 "incompatible with other arguments\n"));
12180 usage(B_FALSE);
12181 }
12182 } else if (upgradeall) {
12183 if (argc != 0) {
12184 (void) fprintf(stderr, gettext("-a option should not "
12185 "be used along with a pool name\n"));
12186 usage(B_FALSE);
12187 }
12188 }
12189
12190 (void) printf("%s", gettext("This system supports ZFS pool feature "
12191 "flags.\n\n"));
12192 if (showversions) {
12193 int i;
12194
12195 (void) printf(gettext("The following features are "
12196 "supported:\n\n"));
12197 (void) printf(gettext("FEAT DESCRIPTION\n"));
12198 (void) printf("----------------------------------------------"
12199 "---------------\n");
12200 for (i = 0; i < SPA_FEATURES; i++) {
12201 zfeature_info_t *fi = &spa_feature_table[i];
12202 if (!fi->fi_zfs_mod_supported)
12203 continue;
12204 const char *ro =
12205 (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
12206 " (read-only compatible)" : "";
12207
12208 (void) printf("%-37s%s\n", fi->fi_uname, ro);
12209 (void) printf(" %s\n", fi->fi_desc);
12210 }
12211 (void) printf("\n");
12212
12213 (void) printf(gettext("The following legacy versions are also "
12214 "supported:\n\n"));
12215 (void) printf(gettext("VER DESCRIPTION\n"));
12216 (void) printf("--- -----------------------------------------"
12217 "---------------\n");
12218 (void) printf(gettext(" 1 Initial ZFS version\n"));
12219 (void) printf(gettext(" 2 Ditto blocks "
12220 "(replicated metadata)\n"));
12221 (void) printf(gettext(" 3 Hot spares and double parity "
12222 "RAID-Z\n"));
12223 (void) printf(gettext(" 4 zpool history\n"));
12224 (void) printf(gettext(" 5 Compression using the gzip "
12225 "algorithm\n"));
12226 (void) printf(gettext(" 6 bootfs pool property\n"));
12227 (void) printf(gettext(" 7 Separate intent log devices\n"));
12228 (void) printf(gettext(" 8 Delegated administration\n"));
12229 (void) printf(gettext(" 9 refquota and refreservation "
12230 "properties\n"));
12231 (void) printf(gettext(" 10 Cache devices\n"));
12232 (void) printf(gettext(" 11 Improved scrub performance\n"));
12233 (void) printf(gettext(" 12 Snapshot properties\n"));
12234 (void) printf(gettext(" 13 snapused property\n"));
12235 (void) printf(gettext(" 14 passthrough-x aclinherit\n"));
12236 (void) printf(gettext(" 15 user/group space accounting\n"));
12237 (void) printf(gettext(" 16 stmf property support\n"));
12238 (void) printf(gettext(" 17 Triple-parity RAID-Z\n"));
12239 (void) printf(gettext(" 18 Snapshot user holds\n"));
12240 (void) printf(gettext(" 19 Log device removal\n"));
12241 (void) printf(gettext(" 20 Compression using zle "
12242 "(zero-length encoding)\n"));
12243 (void) printf(gettext(" 21 Deduplication\n"));
12244 (void) printf(gettext(" 22 Received properties\n"));
12245 (void) printf(gettext(" 23 Slim ZIL\n"));
12246 (void) printf(gettext(" 24 System attributes\n"));
12247 (void) printf(gettext(" 25 Improved scrub stats\n"));
12248 (void) printf(gettext(" 26 Improved snapshot deletion "
12249 "performance\n"));
12250 (void) printf(gettext(" 27 Improved snapshot creation "
12251 "performance\n"));
12252 (void) printf(gettext(" 28 Multiple vdev replacements\n"));
12253 (void) printf(gettext("\nFor more information on a particular "
12254 "version, including supported releases,\n"));
12255 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
12256 } else if (argc == 0 && upgradeall) {
12257 cb.cb_first = B_TRUE;
12258 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
12259 if (ret == 0 && cb.cb_first) {
12260 if (cb.cb_version == SPA_VERSION) {
12261 (void) printf(gettext("All pools are already "
12262 "formatted using feature flags.\n\n"));
12263 (void) printf(gettext("Every feature flags "
12264 "pool already has all supported and "
12265 "requested features enabled.\n"));
12266 } else {
12267 (void) printf(gettext("All pools are already "
12268 "formatted with version %llu or higher.\n"),
12269 (u_longlong_t)cb.cb_version);
12270 }
12271 }
12272 } else if (argc == 0) {
12273 cb.cb_first = B_TRUE;
12274 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
12275 assert(ret == 0);
12276
12277 if (cb.cb_first) {
12278 (void) printf(gettext("All pools are formatted "
12279 "using feature flags.\n\n"));
12280 } else {
12281 (void) printf(gettext("\nUse 'zpool upgrade -v' "
12282 "for a list of available legacy versions.\n"));
12283 }
12284
12285 cb.cb_first = B_TRUE;
12286 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
12287 assert(ret == 0);
12288
12289 if (cb.cb_first) {
12290 (void) printf(gettext("Every feature flags pool has "
12291 "all supported and requested features enabled.\n"));
12292 } else {
12293 (void) printf(gettext("\n"));
12294 }
12295 } else {
12296 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
12297 B_FALSE, upgrade_one, &cb);
12298 }
12299
12300 return (ret);
12301 }
12302
12303 typedef struct hist_cbdata {
12304 boolean_t first;
12305 boolean_t longfmt;
12306 boolean_t internal;
12307 } hist_cbdata_t;
12308
12309 static void
print_history_records(nvlist_t * nvhis,hist_cbdata_t * cb)12310 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
12311 {
12312 nvlist_t **records;
12313 uint_t numrecords;
12314 int i;
12315
12316 verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
12317 &records, &numrecords) == 0);
12318 for (i = 0; i < numrecords; i++) {
12319 nvlist_t *rec = records[i];
12320 char tbuf[64] = "";
12321
12322 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
12323 time_t tsec;
12324 struct tm t;
12325
12326 tsec = fnvlist_lookup_uint64(records[i],
12327 ZPOOL_HIST_TIME);
12328 (void) localtime_r(&tsec, &t);
12329 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
12330 }
12331
12332 if (nvlist_exists(rec, ZPOOL_HIST_ELAPSED_NS)) {
12333 uint64_t elapsed_ns = fnvlist_lookup_int64(records[i],
12334 ZPOOL_HIST_ELAPSED_NS);
12335 (void) snprintf(tbuf + strlen(tbuf),
12336 sizeof (tbuf) - strlen(tbuf),
12337 " (%lldms)", (long long)elapsed_ns / 1000 / 1000);
12338 }
12339
12340 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
12341 (void) printf("%s %s", tbuf,
12342 fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
12343 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
12344 int ievent =
12345 fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
12346 if (!cb->internal)
12347 continue;
12348 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
12349 (void) printf("%s unrecognized record:\n",
12350 tbuf);
12351 dump_nvlist(rec, 4);
12352 continue;
12353 }
12354 (void) printf("%s [internal %s txg:%lld] %s", tbuf,
12355 zfs_history_event_names[ievent],
12356 (longlong_t)fnvlist_lookup_uint64(
12357 rec, ZPOOL_HIST_TXG),
12358 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
12359 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
12360 if (!cb->internal)
12361 continue;
12362 (void) printf("%s [txg:%lld] %s", tbuf,
12363 (longlong_t)fnvlist_lookup_uint64(
12364 rec, ZPOOL_HIST_TXG),
12365 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
12366 if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
12367 (void) printf(" %s (%llu)",
12368 fnvlist_lookup_string(rec,
12369 ZPOOL_HIST_DSNAME),
12370 (u_longlong_t)fnvlist_lookup_uint64(rec,
12371 ZPOOL_HIST_DSID));
12372 }
12373 (void) printf(" %s", fnvlist_lookup_string(rec,
12374 ZPOOL_HIST_INT_STR));
12375 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
12376 if (!cb->internal)
12377 continue;
12378 (void) printf("%s ioctl %s\n", tbuf,
12379 fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
12380 if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
12381 (void) printf(" input:\n");
12382 dump_nvlist(fnvlist_lookup_nvlist(rec,
12383 ZPOOL_HIST_INPUT_NVL), 8);
12384 }
12385 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
12386 (void) printf(" output:\n");
12387 dump_nvlist(fnvlist_lookup_nvlist(rec,
12388 ZPOOL_HIST_OUTPUT_NVL), 8);
12389 }
12390 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_SIZE)) {
12391 (void) printf(" output nvlist omitted; "
12392 "original size: %lldKB\n",
12393 (longlong_t)fnvlist_lookup_int64(rec,
12394 ZPOOL_HIST_OUTPUT_SIZE) / 1024);
12395 }
12396 if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
12397 (void) printf(" errno: %lld\n",
12398 (longlong_t)fnvlist_lookup_int64(rec,
12399 ZPOOL_HIST_ERRNO));
12400 }
12401 } else {
12402 if (!cb->internal)
12403 continue;
12404 (void) printf("%s unrecognized record:\n", tbuf);
12405 dump_nvlist(rec, 4);
12406 }
12407
12408 if (!cb->longfmt) {
12409 (void) printf("\n");
12410 continue;
12411 }
12412 (void) printf(" [");
12413 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
12414 uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
12415 struct passwd *pwd = getpwuid(who);
12416 (void) printf("user %d ", (int)who);
12417 if (pwd != NULL)
12418 (void) printf("(%s) ", pwd->pw_name);
12419 }
12420 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
12421 (void) printf("on %s",
12422 fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
12423 }
12424 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
12425 (void) printf(":%s",
12426 fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
12427 }
12428
12429 (void) printf("]");
12430 (void) printf("\n");
12431 }
12432 }
12433
12434 /*
12435 * Print out the command history for a specific pool.
12436 */
12437 static int
get_history_one(zpool_handle_t * zhp,void * data)12438 get_history_one(zpool_handle_t *zhp, void *data)
12439 {
12440 nvlist_t *nvhis;
12441 int ret;
12442 hist_cbdata_t *cb = (hist_cbdata_t *)data;
12443 uint64_t off = 0;
12444 boolean_t eof = B_FALSE;
12445
12446 cb->first = B_FALSE;
12447
12448 (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
12449
12450 while (!eof) {
12451 if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
12452 return (ret);
12453
12454 print_history_records(nvhis, cb);
12455 nvlist_free(nvhis);
12456 }
12457 (void) printf("\n");
12458
12459 return (ret);
12460 }
12461
12462 /*
12463 * zpool history <pool>
12464 *
12465 * Displays the history of commands that modified pools.
12466 */
12467 int
zpool_do_history(int argc,char ** argv)12468 zpool_do_history(int argc, char **argv)
12469 {
12470 hist_cbdata_t cbdata = { 0 };
12471 int ret;
12472 int c;
12473
12474 cbdata.first = B_TRUE;
12475 /* check options */
12476 while ((c = getopt(argc, argv, "li")) != -1) {
12477 switch (c) {
12478 case 'l':
12479 cbdata.longfmt = B_TRUE;
12480 break;
12481 case 'i':
12482 cbdata.internal = B_TRUE;
12483 break;
12484 case '?':
12485 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
12486 optopt);
12487 usage(B_FALSE);
12488 }
12489 }
12490 argc -= optind;
12491 argv += optind;
12492
12493 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
12494 B_FALSE, get_history_one, &cbdata);
12495
12496 if (argc == 0 && cbdata.first == B_TRUE) {
12497 (void) fprintf(stderr, gettext("no pools available\n"));
12498 return (0);
12499 }
12500
12501 return (ret);
12502 }
12503
12504 typedef struct ev_opts {
12505 int verbose;
12506 int scripted;
12507 int follow;
12508 int clear;
12509 char poolname[ZFS_MAX_DATASET_NAME_LEN];
12510 } ev_opts_t;
12511
12512 static void
zpool_do_events_short(nvlist_t * nvl,ev_opts_t * opts)12513 zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
12514 {
12515 char ctime_str[26], str[32];
12516 const char *ptr;
12517 int64_t *tv;
12518 uint_t n;
12519
12520 verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
12521 memset(str, ' ', 32);
12522 (void) ctime_r((const time_t *)&tv[0], ctime_str);
12523 (void) memcpy(str, ctime_str+4, 6); /* 'Jun 30' */
12524 (void) memcpy(str+7, ctime_str+20, 4); /* '1993' */
12525 (void) memcpy(str+12, ctime_str+11, 8); /* '21:49:08' */
12526 (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
12527 if (opts->scripted)
12528 (void) printf(gettext("%s\t"), str);
12529 else
12530 (void) printf(gettext("%s "), str);
12531
12532 verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
12533 (void) printf(gettext("%s\n"), ptr);
12534 }
12535
12536 static void
zpool_do_events_nvprint(nvlist_t * nvl,int depth)12537 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
12538 {
12539 nvpair_t *nvp;
12540 static char flagstr[256];
12541
12542 for (nvp = nvlist_next_nvpair(nvl, NULL);
12543 nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
12544
12545 data_type_t type = nvpair_type(nvp);
12546 const char *name = nvpair_name(nvp);
12547
12548 boolean_t b;
12549 uint8_t i8;
12550 uint16_t i16;
12551 uint32_t i32;
12552 uint64_t i64;
12553 const char *str;
12554 nvlist_t *cnv;
12555
12556 printf(gettext("%*s%s = "), depth, "", name);
12557
12558 switch (type) {
12559 case DATA_TYPE_BOOLEAN:
12560 printf(gettext("%s"), "1");
12561 break;
12562
12563 case DATA_TYPE_BOOLEAN_VALUE:
12564 (void) nvpair_value_boolean_value(nvp, &b);
12565 printf(gettext("%s"), b ? "1" : "0");
12566 break;
12567
12568 case DATA_TYPE_BYTE:
12569 (void) nvpair_value_byte(nvp, &i8);
12570 printf(gettext("0x%x"), i8);
12571 break;
12572
12573 case DATA_TYPE_INT8:
12574 (void) nvpair_value_int8(nvp, (void *)&i8);
12575 printf(gettext("0x%x"), i8);
12576 break;
12577
12578 case DATA_TYPE_UINT8:
12579 (void) nvpair_value_uint8(nvp, &i8);
12580 printf(gettext("0x%x"), i8);
12581 break;
12582
12583 case DATA_TYPE_INT16:
12584 (void) nvpair_value_int16(nvp, (void *)&i16);
12585 printf(gettext("0x%x"), i16);
12586 break;
12587
12588 case DATA_TYPE_UINT16:
12589 (void) nvpair_value_uint16(nvp, &i16);
12590 printf(gettext("0x%x"), i16);
12591 break;
12592
12593 case DATA_TYPE_INT32:
12594 (void) nvpair_value_int32(nvp, (void *)&i32);
12595 printf(gettext("0x%x"), i32);
12596 break;
12597
12598 case DATA_TYPE_UINT32:
12599 (void) nvpair_value_uint32(nvp, &i32);
12600 if (strcmp(name,
12601 FM_EREPORT_PAYLOAD_ZFS_ZIO_STAGE) == 0 ||
12602 strcmp(name,
12603 FM_EREPORT_PAYLOAD_ZFS_ZIO_PIPELINE) == 0) {
12604 (void) zfs_valstr_zio_stage(i32, flagstr,
12605 sizeof (flagstr));
12606 printf(gettext("0x%x [%s]"), i32, flagstr);
12607 } else if (strcmp(name,
12608 FM_EREPORT_PAYLOAD_ZFS_ZIO_TYPE) == 0) {
12609 (void) zfs_valstr_zio_type(i32, flagstr,
12610 sizeof (flagstr));
12611 printf(gettext("0x%x [%s]"), i32, flagstr);
12612 } else if (strcmp(name,
12613 FM_EREPORT_PAYLOAD_ZFS_ZIO_PRIORITY) == 0) {
12614 (void) zfs_valstr_zio_priority(i32, flagstr,
12615 sizeof (flagstr));
12616 printf(gettext("0x%x [%s]"), i32, flagstr);
12617 } else {
12618 printf(gettext("0x%x"), i32);
12619 }
12620 break;
12621
12622 case DATA_TYPE_INT64:
12623 (void) nvpair_value_int64(nvp, (void *)&i64);
12624 printf(gettext("0x%llx"), (u_longlong_t)i64);
12625 break;
12626
12627 case DATA_TYPE_UINT64:
12628 (void) nvpair_value_uint64(nvp, &i64);
12629 /*
12630 * translate vdev state values to readable
12631 * strings to aide zpool events consumers
12632 */
12633 if (strcmp(name,
12634 FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
12635 strcmp(name,
12636 FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
12637 printf(gettext("\"%s\" (0x%llx)"),
12638 zpool_state_to_name(i64, VDEV_AUX_NONE),
12639 (u_longlong_t)i64);
12640 } else if (strcmp(name,
12641 FM_EREPORT_PAYLOAD_ZFS_ZIO_FLAGS) == 0) {
12642 (void) zfs_valstr_zio_flag(i64, flagstr,
12643 sizeof (flagstr));
12644 printf(gettext("0x%llx [%s]"),
12645 (u_longlong_t)i64, flagstr);
12646 } else {
12647 printf(gettext("0x%llx"), (u_longlong_t)i64);
12648 }
12649 break;
12650
12651 case DATA_TYPE_HRTIME:
12652 (void) nvpair_value_hrtime(nvp, (void *)&i64);
12653 printf(gettext("0x%llx"), (u_longlong_t)i64);
12654 break;
12655
12656 case DATA_TYPE_STRING:
12657 (void) nvpair_value_string(nvp, &str);
12658 printf(gettext("\"%s\""), str ? str : "<NULL>");
12659 break;
12660
12661 case DATA_TYPE_NVLIST:
12662 printf(gettext("(embedded nvlist)\n"));
12663 (void) nvpair_value_nvlist(nvp, &cnv);
12664 zpool_do_events_nvprint(cnv, depth + 8);
12665 printf(gettext("%*s(end %s)"), depth, "", name);
12666 break;
12667
12668 case DATA_TYPE_NVLIST_ARRAY: {
12669 nvlist_t **val;
12670 uint_t i, nelem;
12671
12672 (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
12673 printf(gettext("(%d embedded nvlists)\n"), nelem);
12674 for (i = 0; i < nelem; i++) {
12675 printf(gettext("%*s%s[%d] = %s\n"),
12676 depth, "", name, i, "(embedded nvlist)");
12677 zpool_do_events_nvprint(val[i], depth + 8);
12678 printf(gettext("%*s(end %s[%i])\n"),
12679 depth, "", name, i);
12680 }
12681 printf(gettext("%*s(end %s)\n"), depth, "", name);
12682 }
12683 break;
12684
12685 case DATA_TYPE_INT8_ARRAY: {
12686 int8_t *val;
12687 uint_t i, nelem;
12688
12689 (void) nvpair_value_int8_array(nvp, &val, &nelem);
12690 for (i = 0; i < nelem; i++)
12691 printf(gettext("0x%x "), val[i]);
12692
12693 break;
12694 }
12695
12696 case DATA_TYPE_UINT8_ARRAY: {
12697 uint8_t *val;
12698 uint_t i, nelem;
12699
12700 (void) nvpair_value_uint8_array(nvp, &val, &nelem);
12701 for (i = 0; i < nelem; i++)
12702 printf(gettext("0x%x "), val[i]);
12703
12704 break;
12705 }
12706
12707 case DATA_TYPE_INT16_ARRAY: {
12708 int16_t *val;
12709 uint_t i, nelem;
12710
12711 (void) nvpair_value_int16_array(nvp, &val, &nelem);
12712 for (i = 0; i < nelem; i++)
12713 printf(gettext("0x%x "), val[i]);
12714
12715 break;
12716 }
12717
12718 case DATA_TYPE_UINT16_ARRAY: {
12719 uint16_t *val;
12720 uint_t i, nelem;
12721
12722 (void) nvpair_value_uint16_array(nvp, &val, &nelem);
12723 for (i = 0; i < nelem; i++)
12724 printf(gettext("0x%x "), val[i]);
12725
12726 break;
12727 }
12728
12729 case DATA_TYPE_INT32_ARRAY: {
12730 int32_t *val;
12731 uint_t i, nelem;
12732
12733 (void) nvpair_value_int32_array(nvp, &val, &nelem);
12734 for (i = 0; i < nelem; i++)
12735 printf(gettext("0x%x "), val[i]);
12736
12737 break;
12738 }
12739
12740 case DATA_TYPE_UINT32_ARRAY: {
12741 uint32_t *val;
12742 uint_t i, nelem;
12743
12744 (void) nvpair_value_uint32_array(nvp, &val, &nelem);
12745 for (i = 0; i < nelem; i++)
12746 printf(gettext("0x%x "), val[i]);
12747
12748 break;
12749 }
12750
12751 case DATA_TYPE_INT64_ARRAY: {
12752 int64_t *val;
12753 uint_t i, nelem;
12754
12755 (void) nvpair_value_int64_array(nvp, &val, &nelem);
12756 for (i = 0; i < nelem; i++)
12757 printf(gettext("0x%llx "),
12758 (u_longlong_t)val[i]);
12759
12760 break;
12761 }
12762
12763 case DATA_TYPE_UINT64_ARRAY: {
12764 uint64_t *val;
12765 uint_t i, nelem;
12766
12767 (void) nvpair_value_uint64_array(nvp, &val, &nelem);
12768 for (i = 0; i < nelem; i++)
12769 printf(gettext("0x%llx "),
12770 (u_longlong_t)val[i]);
12771
12772 break;
12773 }
12774
12775 case DATA_TYPE_STRING_ARRAY: {
12776 const char **str;
12777 uint_t i, nelem;
12778
12779 (void) nvpair_value_string_array(nvp, &str, &nelem);
12780 for (i = 0; i < nelem; i++)
12781 printf(gettext("\"%s\" "),
12782 str[i] ? str[i] : "<NULL>");
12783
12784 break;
12785 }
12786
12787 case DATA_TYPE_BOOLEAN_ARRAY:
12788 case DATA_TYPE_BYTE_ARRAY:
12789 case DATA_TYPE_DOUBLE:
12790 case DATA_TYPE_DONTCARE:
12791 case DATA_TYPE_UNKNOWN:
12792 printf(gettext("<unknown>"));
12793 break;
12794 }
12795
12796 printf(gettext("\n"));
12797 }
12798 }
12799
12800 static int
zpool_do_events_next(ev_opts_t * opts)12801 zpool_do_events_next(ev_opts_t *opts)
12802 {
12803 nvlist_t *nvl;
12804 int zevent_fd, ret, dropped;
12805 const char *pool;
12806
12807 zevent_fd = open(ZFS_DEV, O_RDWR);
12808 VERIFY(zevent_fd >= 0);
12809
12810 if (!opts->scripted)
12811 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
12812
12813 while (1) {
12814 ret = zpool_events_next(g_zfs, &nvl, &dropped,
12815 (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
12816 if (ret || nvl == NULL)
12817 break;
12818
12819 if (dropped > 0)
12820 (void) printf(gettext("dropped %d events\n"), dropped);
12821
12822 if (strlen(opts->poolname) > 0 &&
12823 nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
12824 strcmp(opts->poolname, pool) != 0)
12825 continue;
12826
12827 zpool_do_events_short(nvl, opts);
12828
12829 if (opts->verbose) {
12830 zpool_do_events_nvprint(nvl, 8);
12831 printf(gettext("\n"));
12832 }
12833 (void) fflush(stdout);
12834
12835 nvlist_free(nvl);
12836 }
12837
12838 VERIFY0(close(zevent_fd));
12839
12840 return (ret);
12841 }
12842
12843 static int
zpool_do_events_clear(void)12844 zpool_do_events_clear(void)
12845 {
12846 int count, ret;
12847
12848 ret = zpool_events_clear(g_zfs, &count);
12849 if (!ret)
12850 (void) printf(gettext("cleared %d events\n"), count);
12851
12852 return (ret);
12853 }
12854
12855 /*
12856 * zpool events [-vHf [pool] | -c]
12857 *
12858 * Displays events logs by ZFS.
12859 */
12860 int
zpool_do_events(int argc,char ** argv)12861 zpool_do_events(int argc, char **argv)
12862 {
12863 ev_opts_t opts = { 0 };
12864 int ret;
12865 int c;
12866
12867 /* check options */
12868 while ((c = getopt(argc, argv, "vHfc")) != -1) {
12869 switch (c) {
12870 case 'v':
12871 opts.verbose = 1;
12872 break;
12873 case 'H':
12874 opts.scripted = 1;
12875 break;
12876 case 'f':
12877 opts.follow = 1;
12878 break;
12879 case 'c':
12880 opts.clear = 1;
12881 break;
12882 case '?':
12883 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
12884 optopt);
12885 usage(B_FALSE);
12886 }
12887 }
12888 argc -= optind;
12889 argv += optind;
12890
12891 if (argc > 1) {
12892 (void) fprintf(stderr, gettext("too many arguments\n"));
12893 usage(B_FALSE);
12894 } else if (argc == 1) {
12895 (void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
12896 if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
12897 (void) fprintf(stderr,
12898 gettext("invalid pool name '%s'\n"), opts.poolname);
12899 usage(B_FALSE);
12900 }
12901 }
12902
12903 if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
12904 opts.clear) {
12905 (void) fprintf(stderr,
12906 gettext("invalid options combined with -c\n"));
12907 usage(B_FALSE);
12908 }
12909
12910 if (opts.clear)
12911 ret = zpool_do_events_clear();
12912 else
12913 ret = zpool_do_events_next(&opts);
12914
12915 return (ret);
12916 }
12917
12918 static int
get_callback_vdev(zpool_handle_t * zhp,char * vdevname,void * data)12919 get_callback_vdev(zpool_handle_t *zhp, char *vdevname, void *data)
12920 {
12921 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12922 char value[ZFS_MAXPROPLEN];
12923 zprop_source_t srctype;
12924 nvlist_t *props, *item, *d;
12925 props = item = d = NULL;
12926
12927 if (cbp->cb_json) {
12928 d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "vdevs");
12929 if (d == NULL) {
12930 fprintf(stderr, "vdevs obj not found.\n");
12931 exit(1);
12932 }
12933 props = fnvlist_alloc();
12934 }
12935
12936 for (zprop_list_t *pl = cbp->cb_proplist; pl != NULL;
12937 pl = pl->pl_next) {
12938 char *prop_name;
12939 /*
12940 * If the first property is pool name, it is a special
12941 * placeholder that we can skip. This will also skip
12942 * over the name property when 'all' is specified.
12943 */
12944 if (pl->pl_prop == ZPOOL_PROP_NAME &&
12945 pl == cbp->cb_proplist)
12946 continue;
12947
12948 if (pl->pl_prop == ZPROP_INVAL) {
12949 prop_name = pl->pl_user_prop;
12950 } else {
12951 prop_name = (char *)vdev_prop_to_name(pl->pl_prop);
12952 }
12953 if (zpool_get_vdev_prop(zhp, vdevname, pl->pl_prop,
12954 prop_name, value, sizeof (value), &srctype,
12955 cbp->cb_literal) == 0) {
12956 (void) zprop_collect_property(vdevname, cbp, prop_name,
12957 value, srctype, NULL, NULL, props);
12958 }
12959 }
12960
12961 if (cbp->cb_json) {
12962 if (!nvlist_empty(props)) {
12963 item = fnvlist_alloc();
12964 fill_vdev_info(item, zhp, vdevname, B_TRUE,
12965 cbp->cb_json_as_int);
12966 fnvlist_add_nvlist(item, "properties", props);
12967 fnvlist_add_nvlist(d, vdevname, item);
12968 fnvlist_add_nvlist(cbp->cb_jsobj, "vdevs", d);
12969 fnvlist_free(item);
12970 }
12971 fnvlist_free(props);
12972 }
12973
12974 return (0);
12975 }
12976
12977 static int
get_callback_vdev_cb(void * zhp_data,nvlist_t * nv,void * data)12978 get_callback_vdev_cb(void *zhp_data, nvlist_t *nv, void *data)
12979 {
12980 zpool_handle_t *zhp = zhp_data;
12981 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12982 char *vdevname;
12983 const char *type;
12984 int ret;
12985
12986 /*
12987 * zpool_vdev_name() transforms the root vdev name (i.e., root-0) to the
12988 * pool name for display purposes, which is not desired. Fallback to
12989 * zpool_vdev_name() when not dealing with the root vdev.
12990 */
12991 type = fnvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE);
12992 if (zhp != NULL && strcmp(type, "root") == 0)
12993 vdevname = strdup("root-0");
12994 else
12995 vdevname = zpool_vdev_name(g_zfs, zhp, nv,
12996 cbp->cb_vdevs.cb_name_flags);
12997
12998 (void) vdev_expand_proplist(zhp, vdevname, &cbp->cb_proplist);
12999
13000 ret = get_callback_vdev(zhp, vdevname, data);
13001
13002 free(vdevname);
13003
13004 return (ret);
13005 }
13006
13007 static int
get_callback(zpool_handle_t * zhp,void * data)13008 get_callback(zpool_handle_t *zhp, void *data)
13009 {
13010 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
13011 char value[ZFS_MAXPROPLEN];
13012 zprop_source_t srctype;
13013 zprop_list_t *pl;
13014 int vid;
13015 int err = 0;
13016 nvlist_t *props, *item, *d;
13017 props = item = d = NULL;
13018
13019 if (cbp->cb_type == ZFS_TYPE_VDEV) {
13020 if (cbp->cb_json) {
13021 nvlist_t *pool = fnvlist_alloc();
13022 fill_pool_info(pool, zhp, B_FALSE, cbp->cb_json_as_int);
13023 fnvlist_add_nvlist(cbp->cb_jsobj, "pool", pool);
13024 fnvlist_free(pool);
13025 }
13026
13027 if (strcmp(cbp->cb_vdevs.cb_names[0], "all-vdevs") == 0) {
13028 (void) for_each_vdev(zhp, get_callback_vdev_cb, data);
13029 } else {
13030 /* Adjust column widths for vdev properties */
13031 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
13032 vid++) {
13033 (void) vdev_expand_proplist(zhp,
13034 cbp->cb_vdevs.cb_names[vid],
13035 &cbp->cb_proplist);
13036 }
13037 /* Display the properties */
13038 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
13039 vid++) {
13040 (void) get_callback_vdev(zhp,
13041 cbp->cb_vdevs.cb_names[vid], data);
13042 }
13043 }
13044 } else {
13045 assert(cbp->cb_type == ZFS_TYPE_POOL);
13046 if (cbp->cb_json) {
13047 d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
13048 if (d == NULL) {
13049 fprintf(stderr, "pools obj not found.\n");
13050 exit(1);
13051 }
13052 props = fnvlist_alloc();
13053 }
13054 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
13055 /*
13056 * Skip the special fake placeholder. This will also
13057 * skip over the name property when 'all' is specified.
13058 */
13059 if (pl->pl_prop == ZPOOL_PROP_NAME &&
13060 pl == cbp->cb_proplist)
13061 continue;
13062
13063 if (pl->pl_prop == ZPROP_INVAL &&
13064 zfs_prop_user(pl->pl_user_prop)) {
13065 srctype = ZPROP_SRC_LOCAL;
13066
13067 if (zpool_get_userprop(zhp, pl->pl_user_prop,
13068 value, sizeof (value), &srctype) != 0)
13069 continue;
13070
13071 err = zprop_collect_property(
13072 zpool_get_name(zhp), cbp, pl->pl_user_prop,
13073 value, srctype, NULL, NULL, props);
13074 } else if (pl->pl_prop == ZPROP_INVAL &&
13075 (zpool_prop_feature(pl->pl_user_prop) ||
13076 zpool_prop_unsupported(pl->pl_user_prop))) {
13077 srctype = ZPROP_SRC_LOCAL;
13078
13079 if (zpool_prop_get_feature(zhp,
13080 pl->pl_user_prop, value,
13081 sizeof (value)) == 0) {
13082 err = zprop_collect_property(
13083 zpool_get_name(zhp), cbp,
13084 pl->pl_user_prop, value, srctype,
13085 NULL, NULL, props);
13086 }
13087 } else {
13088 if (zpool_get_prop(zhp, pl->pl_prop, value,
13089 sizeof (value), &srctype,
13090 cbp->cb_literal) != 0)
13091 continue;
13092
13093 err = zprop_collect_property(
13094 zpool_get_name(zhp), cbp,
13095 zpool_prop_to_name(pl->pl_prop),
13096 value, srctype, NULL, NULL, props);
13097 }
13098 if (err != 0)
13099 return (err);
13100 }
13101
13102 if (cbp->cb_json) {
13103 if (!nvlist_empty(props)) {
13104 item = fnvlist_alloc();
13105 fill_pool_info(item, zhp, B_TRUE,
13106 cbp->cb_json_as_int);
13107 fnvlist_add_nvlist(item, "properties", props);
13108 if (cbp->cb_json_pool_key_guid) {
13109 char buf[256];
13110 uint64_t guid = fnvlist_lookup_uint64(
13111 zpool_get_config(zhp, NULL),
13112 ZPOOL_CONFIG_POOL_GUID);
13113 (void) snprintf(buf, 256, "%llu",
13114 (u_longlong_t)guid);
13115 fnvlist_add_nvlist(d, buf, item);
13116 } else {
13117 const char *name = zpool_get_name(zhp);
13118 fnvlist_add_nvlist(d, name, item);
13119 }
13120 fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
13121 fnvlist_free(item);
13122 }
13123 fnvlist_free(props);
13124 }
13125 }
13126
13127 return (0);
13128 }
13129
13130 /*
13131 * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
13132 *
13133 * -H Scripted mode. Don't display headers, and separate properties
13134 * by a single tab.
13135 * -o List of columns to display. Defaults to
13136 * "name,property,value,source".
13137 * -p Display values in parsable (exact) format.
13138 * -j Display output in JSON format.
13139 * --json-int Display numbers as integers instead of strings.
13140 * --json-pool-key-guid Set pool GUID as key for pool objects.
13141 *
13142 * Get properties of pools in the system. Output space statistics
13143 * for each one as well as other attributes.
13144 */
13145 int
zpool_do_get(int argc,char ** argv)13146 zpool_do_get(int argc, char **argv)
13147 {
13148 zprop_get_cbdata_t cb = { 0 };
13149 zprop_list_t fake_name = { 0 };
13150 int ret;
13151 int c, i;
13152 char *propstr = NULL;
13153 char *vdev = NULL;
13154 nvlist_t *data = NULL;
13155
13156 cb.cb_first = B_TRUE;
13157
13158 /*
13159 * Set up default columns and sources.
13160 */
13161 cb.cb_sources = ZPROP_SRC_ALL;
13162 cb.cb_columns[0] = GET_COL_NAME;
13163 cb.cb_columns[1] = GET_COL_PROPERTY;
13164 cb.cb_columns[2] = GET_COL_VALUE;
13165 cb.cb_columns[3] = GET_COL_SOURCE;
13166 cb.cb_type = ZFS_TYPE_POOL;
13167 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
13168 current_prop_type = cb.cb_type;
13169
13170 struct option long_options[] = {
13171 {"json", no_argument, NULL, 'j'},
13172 {"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
13173 {"json-pool-key-guid", no_argument, NULL,
13174 ZPOOL_OPTION_POOL_KEY_GUID},
13175 {0, 0, 0, 0}
13176 };
13177
13178 /* check options */
13179 while ((c = getopt_long(argc, argv, ":jHpo:", long_options,
13180 NULL)) != -1) {
13181 switch (c) {
13182 case 'p':
13183 cb.cb_literal = B_TRUE;
13184 break;
13185 case 'H':
13186 cb.cb_scripted = B_TRUE;
13187 break;
13188 case 'j':
13189 cb.cb_json = B_TRUE;
13190 cb.cb_jsobj = zpool_json_schema(0, 1);
13191 data = fnvlist_alloc();
13192 break;
13193 case ZPOOL_OPTION_POOL_KEY_GUID:
13194 cb.cb_json_pool_key_guid = B_TRUE;
13195 break;
13196 case ZPOOL_OPTION_JSON_NUMS_AS_INT:
13197 cb.cb_json_as_int = B_TRUE;
13198 cb.cb_literal = B_TRUE;
13199 break;
13200 case 'o':
13201 memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
13202 i = 0;
13203
13204 for (char *tok; (tok = strsep(&optarg, ",")); ) {
13205 static const char *const col_opts[] =
13206 { "name", "property", "value", "source",
13207 "all" };
13208 static const zfs_get_column_t col_cols[] =
13209 { GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
13210 GET_COL_SOURCE };
13211
13212 if (i == ZFS_GET_NCOLS - 1) {
13213 (void) fprintf(stderr, gettext("too "
13214 "many fields given to -o "
13215 "option\n"));
13216 usage(B_FALSE);
13217 }
13218
13219 for (c = 0; c < ARRAY_SIZE(col_opts); ++c)
13220 if (strcmp(tok, col_opts[c]) == 0)
13221 goto found;
13222
13223 (void) fprintf(stderr,
13224 gettext("invalid column name '%s'\n"), tok);
13225 usage(B_FALSE);
13226
13227 found:
13228 if (c >= 4) {
13229 if (i > 0) {
13230 (void) fprintf(stderr,
13231 gettext("\"all\" conflicts "
13232 "with specific fields "
13233 "given to -o option\n"));
13234 usage(B_FALSE);
13235 }
13236
13237 memcpy(cb.cb_columns, col_cols,
13238 sizeof (col_cols));
13239 i = ZFS_GET_NCOLS - 1;
13240 } else
13241 cb.cb_columns[i++] = col_cols[c];
13242 }
13243 break;
13244 case '?':
13245 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
13246 optopt);
13247 usage(B_FALSE);
13248 }
13249 }
13250
13251 argc -= optind;
13252 argv += optind;
13253
13254 if (!cb.cb_json && cb.cb_json_as_int) {
13255 (void) fprintf(stderr, gettext("'--json-int' only works with"
13256 " '-j' option\n"));
13257 usage(B_FALSE);
13258 }
13259
13260 if (!cb.cb_json && cb.cb_json_pool_key_guid) {
13261 (void) fprintf(stderr, gettext("'json-pool-key-guid' only"
13262 " works with '-j' option\n"));
13263 usage(B_FALSE);
13264 }
13265
13266 if (argc < 1) {
13267 (void) fprintf(stderr, gettext("missing property "
13268 "argument\n"));
13269 usage(B_FALSE);
13270 }
13271
13272 /* Properties list is needed later by zprop_get_list() */
13273 propstr = argv[0];
13274
13275 argc--;
13276 argv++;
13277
13278 if (argc == 0) {
13279 /* No args, so just print the defaults. */
13280 } else if (are_all_pools(argc, argv)) {
13281 /* All the args are pool names */
13282 } else if (are_all_pools(1, argv)) {
13283 /* The first arg is a pool name */
13284 if ((argc == 2 && strcmp(argv[1], "all-vdevs") == 0) ||
13285 (argc == 2 && strcmp(argv[1], "root") == 0) ||
13286 are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
13287 &cb.cb_vdevs)) {
13288
13289 if (strcmp(argv[1], "root") == 0)
13290 vdev = strdup("root-0");
13291
13292 /* ... and the rest are vdev names */
13293 if (vdev == NULL)
13294 cb.cb_vdevs.cb_names = argv + 1;
13295 else
13296 cb.cb_vdevs.cb_names = &vdev;
13297
13298 cb.cb_vdevs.cb_names_count = argc - 1;
13299 cb.cb_type = ZFS_TYPE_VDEV;
13300 argc = 1; /* One pool to process */
13301 } else {
13302 if (cb.cb_json) {
13303 nvlist_free(cb.cb_jsobj);
13304 nvlist_free(data);
13305 }
13306 fprintf(stderr, gettext("Expected a list of vdevs in"
13307 " \"%s\", but got:\n"), argv[0]);
13308 error_list_unresolved_vdevs(argc - 1, argv + 1,
13309 argv[0], &cb.cb_vdevs);
13310 fprintf(stderr, "\n");
13311 usage(B_FALSE);
13312 }
13313 } else {
13314 if (cb.cb_json) {
13315 nvlist_free(cb.cb_jsobj);
13316 nvlist_free(data);
13317 }
13318 /*
13319 * The first arg isn't the name of a valid pool.
13320 */
13321 fprintf(stderr, gettext("Cannot get properties of %s: "
13322 "no such pool available.\n"), argv[0]);
13323 return (1);
13324 }
13325
13326 if (zprop_get_list(g_zfs, propstr, &cb.cb_proplist,
13327 cb.cb_type) != 0) {
13328 /* Use correct list of valid properties (pool or vdev) */
13329 current_prop_type = cb.cb_type;
13330 usage(B_FALSE);
13331 }
13332
13333 if (cb.cb_proplist != NULL) {
13334 fake_name.pl_prop = ZPOOL_PROP_NAME;
13335 fake_name.pl_width = strlen(gettext("NAME"));
13336 fake_name.pl_next = cb.cb_proplist;
13337 cb.cb_proplist = &fake_name;
13338 }
13339
13340 if (cb.cb_json) {
13341 if (cb.cb_type == ZFS_TYPE_VDEV)
13342 fnvlist_add_nvlist(cb.cb_jsobj, "vdevs", data);
13343 else
13344 fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
13345 fnvlist_free(data);
13346 }
13347
13348 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist, cb.cb_type,
13349 cb.cb_literal, get_callback, &cb);
13350
13351 if (ret == 0 && cb.cb_json)
13352 zcmd_print_json(cb.cb_jsobj);
13353 else if (ret != 0 && cb.cb_json)
13354 nvlist_free(cb.cb_jsobj);
13355
13356 if (cb.cb_proplist == &fake_name)
13357 zprop_free_list(fake_name.pl_next);
13358 else
13359 zprop_free_list(cb.cb_proplist);
13360
13361 if (vdev != NULL)
13362 free(vdev);
13363
13364 return (ret);
13365 }
13366
13367 typedef struct set_cbdata {
13368 char *cb_propname;
13369 char *cb_value;
13370 zfs_type_t cb_type;
13371 vdev_cbdata_t cb_vdevs;
13372 boolean_t cb_any_successful;
13373 } set_cbdata_t;
13374
13375 static int
set_pool_callback(zpool_handle_t * zhp,set_cbdata_t * cb)13376 set_pool_callback(zpool_handle_t *zhp, set_cbdata_t *cb)
13377 {
13378 int error;
13379
13380 /* Check if we have out-of-bounds features */
13381 if (strcmp(cb->cb_propname, ZPOOL_CONFIG_COMPATIBILITY) == 0) {
13382 boolean_t features[SPA_FEATURES];
13383 if (zpool_do_load_compat(cb->cb_value, features) !=
13384 ZPOOL_COMPATIBILITY_OK)
13385 return (-1);
13386
13387 nvlist_t *enabled = zpool_get_features(zhp);
13388 spa_feature_t i;
13389 for (i = 0; i < SPA_FEATURES; i++) {
13390 const char *fguid = spa_feature_table[i].fi_guid;
13391 if (nvlist_exists(enabled, fguid) && !features[i])
13392 break;
13393 }
13394 if (i < SPA_FEATURES)
13395 (void) fprintf(stderr, gettext("Warning: one or "
13396 "more features already enabled on pool '%s'\n"
13397 "are not present in this compatibility set.\n"),
13398 zpool_get_name(zhp));
13399 }
13400
13401 /* if we're setting a feature, check it's in compatibility set */
13402 if (zpool_prop_feature(cb->cb_propname) &&
13403 strcmp(cb->cb_value, ZFS_FEATURE_ENABLED) == 0) {
13404 char *fname = strchr(cb->cb_propname, '@') + 1;
13405 spa_feature_t f;
13406
13407 if (zfeature_lookup_name(fname, &f) == 0) {
13408 char compat[ZFS_MAXPROPLEN];
13409 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY,
13410 compat, ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
13411 compat[0] = '\0';
13412
13413 boolean_t features[SPA_FEATURES];
13414 if (zpool_do_load_compat(compat, features) !=
13415 ZPOOL_COMPATIBILITY_OK) {
13416 (void) fprintf(stderr, gettext("Error: "
13417 "cannot enable feature '%s' on pool '%s'\n"
13418 "because the pool's 'compatibility' "
13419 "property cannot be parsed.\n"),
13420 fname, zpool_get_name(zhp));
13421 return (-1);
13422 }
13423
13424 if (!features[f]) {
13425 (void) fprintf(stderr, gettext("Error: "
13426 "cannot enable feature '%s' on pool '%s'\n"
13427 "as it is not specified in this pool's "
13428 "current compatibility set.\n"
13429 "Consider setting 'compatibility' to a "
13430 "less restrictive set, or to 'off'.\n"),
13431 fname, zpool_get_name(zhp));
13432 return (-1);
13433 }
13434 }
13435 }
13436
13437 error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
13438
13439 return (error);
13440 }
13441
13442 static int
set_callback(zpool_handle_t * zhp,void * data)13443 set_callback(zpool_handle_t *zhp, void *data)
13444 {
13445 int error;
13446 set_cbdata_t *cb = (set_cbdata_t *)data;
13447
13448 if (cb->cb_type == ZFS_TYPE_VDEV) {
13449 error = zpool_set_vdev_prop(zhp, *cb->cb_vdevs.cb_names,
13450 cb->cb_propname, cb->cb_value);
13451 } else {
13452 assert(cb->cb_type == ZFS_TYPE_POOL);
13453 error = set_pool_callback(zhp, cb);
13454 }
13455
13456 cb->cb_any_successful = !error;
13457 return (error);
13458 }
13459
13460 int
zpool_do_set(int argc,char ** argv)13461 zpool_do_set(int argc, char **argv)
13462 {
13463 set_cbdata_t cb = { 0 };
13464 int error;
13465 char *vdev = NULL;
13466
13467 current_prop_type = ZFS_TYPE_POOL;
13468 if (argc > 1 && argv[1][0] == '-') {
13469 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
13470 argv[1][1]);
13471 usage(B_FALSE);
13472 }
13473
13474 if (argc < 2) {
13475 (void) fprintf(stderr, gettext("missing property=value "
13476 "argument\n"));
13477 usage(B_FALSE);
13478 }
13479
13480 if (argc < 3) {
13481 (void) fprintf(stderr, gettext("missing pool name\n"));
13482 usage(B_FALSE);
13483 }
13484
13485 if (argc > 4) {
13486 (void) fprintf(stderr, gettext("too many pool names\n"));
13487 usage(B_FALSE);
13488 }
13489
13490 cb.cb_propname = argv[1];
13491 cb.cb_type = ZFS_TYPE_POOL;
13492 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
13493 cb.cb_value = strchr(cb.cb_propname, '=');
13494 if (cb.cb_value == NULL) {
13495 (void) fprintf(stderr, gettext("missing value in "
13496 "property=value argument\n"));
13497 usage(B_FALSE);
13498 }
13499
13500 *(cb.cb_value) = '\0';
13501 cb.cb_value++;
13502 argc -= 2;
13503 argv += 2;
13504
13505 /* argv[0] is pool name */
13506 if (!is_pool(argv[0])) {
13507 (void) fprintf(stderr,
13508 gettext("cannot open '%s': is not a pool\n"), argv[0]);
13509 return (EINVAL);
13510 }
13511
13512 /* argv[1], when supplied, is vdev name */
13513 if (argc == 2) {
13514
13515 if (strcmp(argv[1], "root") == 0)
13516 vdev = strdup("root-0");
13517 else
13518 vdev = strdup(argv[1]);
13519
13520 if (!are_vdevs_in_pool(1, &vdev, argv[0], &cb.cb_vdevs)) {
13521 (void) fprintf(stderr, gettext(
13522 "cannot find '%s' in '%s': device not in pool\n"),
13523 vdev, argv[0]);
13524 free(vdev);
13525 return (EINVAL);
13526 }
13527 cb.cb_vdevs.cb_names = &vdev;
13528 cb.cb_vdevs.cb_names_count = 1;
13529 cb.cb_type = ZFS_TYPE_VDEV;
13530 }
13531
13532 error = for_each_pool(1, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
13533 B_FALSE, set_callback, &cb);
13534
13535 if (vdev != NULL)
13536 free(vdev);
13537
13538 return (error);
13539 }
13540
13541 /* Add up the total number of bytes left to initialize/trim across all vdevs */
13542 static uint64_t
vdev_activity_remaining(nvlist_t * nv,zpool_wait_activity_t activity)13543 vdev_activity_remaining(nvlist_t *nv, zpool_wait_activity_t activity)
13544 {
13545 uint64_t bytes_remaining;
13546 nvlist_t **child;
13547 uint_t c, children;
13548 vdev_stat_t *vs;
13549
13550 assert(activity == ZPOOL_WAIT_INITIALIZE ||
13551 activity == ZPOOL_WAIT_TRIM);
13552
13553 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
13554 (uint64_t **)&vs, &c) == 0);
13555
13556 if (activity == ZPOOL_WAIT_INITIALIZE &&
13557 vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE)
13558 bytes_remaining = vs->vs_initialize_bytes_est -
13559 vs->vs_initialize_bytes_done;
13560 else if (activity == ZPOOL_WAIT_TRIM &&
13561 vs->vs_trim_state == VDEV_TRIM_ACTIVE)
13562 bytes_remaining = vs->vs_trim_bytes_est -
13563 vs->vs_trim_bytes_done;
13564 else
13565 bytes_remaining = 0;
13566
13567 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13568 &child, &children) != 0)
13569 children = 0;
13570
13571 for (c = 0; c < children; c++)
13572 bytes_remaining += vdev_activity_remaining(child[c], activity);
13573
13574 return (bytes_remaining);
13575 }
13576
13577 /* Add up the total number of bytes left to rebuild across top-level vdevs */
13578 static uint64_t
vdev_activity_top_remaining(nvlist_t * nv)13579 vdev_activity_top_remaining(nvlist_t *nv)
13580 {
13581 uint64_t bytes_remaining = 0;
13582 nvlist_t **child;
13583 uint_t children;
13584 int error;
13585
13586 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13587 &child, &children) != 0)
13588 children = 0;
13589
13590 for (uint_t c = 0; c < children; c++) {
13591 vdev_rebuild_stat_t *vrs;
13592 uint_t i;
13593
13594 error = nvlist_lookup_uint64_array(child[c],
13595 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i);
13596 if (error == 0) {
13597 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
13598 bytes_remaining += (vrs->vrs_bytes_est -
13599 vrs->vrs_bytes_rebuilt);
13600 }
13601 }
13602 }
13603
13604 return (bytes_remaining);
13605 }
13606
13607 /* Whether any vdevs are 'spare' or 'replacing' vdevs */
13608 static boolean_t
vdev_any_spare_replacing(nvlist_t * nv)13609 vdev_any_spare_replacing(nvlist_t *nv)
13610 {
13611 nvlist_t **child;
13612 uint_t c, children;
13613 const char *vdev_type;
13614
13615 (void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &vdev_type);
13616
13617 if (strcmp(vdev_type, VDEV_TYPE_REPLACING) == 0 ||
13618 strcmp(vdev_type, VDEV_TYPE_SPARE) == 0 ||
13619 strcmp(vdev_type, VDEV_TYPE_DRAID_SPARE) == 0) {
13620 return (B_TRUE);
13621 }
13622
13623 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13624 &child, &children) != 0)
13625 children = 0;
13626
13627 for (c = 0; c < children; c++) {
13628 if (vdev_any_spare_replacing(child[c]))
13629 return (B_TRUE);
13630 }
13631
13632 return (B_FALSE);
13633 }
13634
13635 typedef struct wait_data {
13636 char *wd_poolname;
13637 boolean_t wd_scripted;
13638 boolean_t wd_exact;
13639 boolean_t wd_headers_once;
13640 boolean_t wd_should_exit;
13641 /* Which activities to wait for */
13642 boolean_t wd_enabled[ZPOOL_WAIT_NUM_ACTIVITIES];
13643 float wd_interval;
13644 pthread_cond_t wd_cv;
13645 pthread_mutex_t wd_mutex;
13646 } wait_data_t;
13647
13648 /*
13649 * Print to stdout a single line, containing one column for each activity that
13650 * we are waiting for specifying how many bytes of work are left for that
13651 * activity.
13652 */
13653 static void
print_wait_status_row(wait_data_t * wd,zpool_handle_t * zhp,int row)13654 print_wait_status_row(wait_data_t *wd, zpool_handle_t *zhp, int row)
13655 {
13656 nvlist_t *config, *nvroot;
13657 uint_t c;
13658 int i;
13659 pool_checkpoint_stat_t *pcs = NULL;
13660 pool_scan_stat_t *pss = NULL;
13661 pool_removal_stat_t *prs = NULL;
13662 pool_raidz_expand_stat_t *pres = NULL;
13663 nvlist_t *cnv = NULL;
13664 const char *const headers[] = {"DISCARD", "FREE", "INITIALIZE",
13665 "REPLACE", "REMOVE", "RESILVER", "SCRUB", "TRIM", "RAIDZ_EXPAND",
13666 "CONDENSE"};
13667 int col_widths[ZPOOL_WAIT_NUM_ACTIVITIES];
13668
13669 /* Calculate the width of each column */
13670 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13671 /*
13672 * Make sure we have enough space in the col for pretty-printed
13673 * numbers and for the column header, and then leave a couple
13674 * spaces between cols for readability.
13675 */
13676 col_widths[i] = MAX(strlen(headers[i]), 6) + 2;
13677 }
13678
13679 if (timestamp_fmt != NODATE)
13680 print_timestamp(timestamp_fmt);
13681
13682 /* Print header if appropriate */
13683 int term_height = terminal_height();
13684 boolean_t reprint_header = (!wd->wd_headers_once && term_height > 0 &&
13685 row % (term_height-1) == 0);
13686 if (!wd->wd_scripted && (row == 0 || reprint_header)) {
13687 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13688 if (wd->wd_enabled[i])
13689 (void) printf("%*s", col_widths[i], headers[i]);
13690 }
13691 (void) fputc('\n', stdout);
13692 }
13693
13694 /* Bytes of work remaining in each activity */
13695 int64_t bytes_rem[ZPOOL_WAIT_NUM_ACTIVITIES] = {0};
13696
13697 bytes_rem[ZPOOL_WAIT_FREE] =
13698 zpool_get_prop_int(zhp, ZPOOL_PROP_FREEING, NULL);
13699
13700 config = zpool_get_config(zhp, NULL);
13701 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
13702
13703 (void) nvlist_lookup_uint64_array(nvroot,
13704 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
13705 if (pcs != NULL && pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
13706 bytes_rem[ZPOOL_WAIT_CKPT_DISCARD] = pcs->pcs_space;
13707
13708 (void) nvlist_lookup_uint64_array(nvroot,
13709 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
13710 if (prs != NULL && prs->prs_state == DSS_SCANNING)
13711 bytes_rem[ZPOOL_WAIT_REMOVE] = prs->prs_to_copy -
13712 prs->prs_copied;
13713
13714 (void) nvlist_lookup_uint64_array(nvroot,
13715 ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&pss, &c);
13716 if (pss != NULL && pss->pss_state == DSS_SCANNING &&
13717 pss->pss_pass_scrub_pause == 0) {
13718 int64_t rem = pss->pss_to_examine - pss->pss_issued;
13719 if (pss->pss_func == POOL_SCAN_SCRUB)
13720 bytes_rem[ZPOOL_WAIT_SCRUB] = rem;
13721 else
13722 bytes_rem[ZPOOL_WAIT_RESILVER] = rem;
13723 } else if (check_rebuilding(nvroot, NULL)) {
13724 bytes_rem[ZPOOL_WAIT_RESILVER] =
13725 vdev_activity_top_remaining(nvroot);
13726 }
13727
13728 (void) nvlist_lookup_uint64_array(nvroot,
13729 ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
13730 if (pres != NULL && pres->pres_state == DSS_SCANNING) {
13731 int64_t rem = pres->pres_to_reflow - pres->pres_reflowed;
13732 bytes_rem[ZPOOL_WAIT_RAIDZ_EXPAND] = rem;
13733 }
13734
13735 /*
13736 * Count each outstanding condense item as a "byte". Its not true,
13737 * but its a counter, and it'll display nicely.
13738 */
13739 if (nvlist_lookup_nvlist(nvroot,
13740 ZPOOL_CONFIG_CONDENSE_STATS, &cnv) == 0) {
13741 for (nvpair_t *nvp = nvlist_next_nvpair(cnv, NULL);
13742 nvp != NULL; nvp = nvlist_next_nvpair(cnv, nvp)) {
13743 nvlist_t *tnv = fnvpair_value_nvlist(nvp);
13744 uint64_t total = fnvlist_lookup_uint64(tnv, "total");
13745 uint64_t processed =
13746 fnvlist_lookup_uint64(tnv, "processed");
13747 bytes_rem[ZPOOL_WAIT_CONDENSE] += (total - processed);
13748 }
13749 }
13750
13751 bytes_rem[ZPOOL_WAIT_INITIALIZE] =
13752 vdev_activity_remaining(nvroot, ZPOOL_WAIT_INITIALIZE);
13753 bytes_rem[ZPOOL_WAIT_TRIM] =
13754 vdev_activity_remaining(nvroot, ZPOOL_WAIT_TRIM);
13755
13756 /*
13757 * A replace finishes after resilvering finishes, so the amount of work
13758 * left for a replace is the same as for resilvering.
13759 *
13760 * It isn't quite correct to say that if we have any 'spare' or
13761 * 'replacing' vdevs and a resilver is happening, then a replace is in
13762 * progress, like we do here. When a hot spare is used, the faulted vdev
13763 * is not removed after the hot spare is resilvered, so parent 'spare'
13764 * vdev is not removed either. So we could have a 'spare' vdev, but be
13765 * resilvering for a different reason. However, we use it as a heuristic
13766 * because we don't have access to the DTLs, which could tell us whether
13767 * or not we have really finished resilvering a hot spare.
13768 */
13769 if (vdev_any_spare_replacing(nvroot))
13770 bytes_rem[ZPOOL_WAIT_REPLACE] = bytes_rem[ZPOOL_WAIT_RESILVER];
13771
13772 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13773 char buf[64];
13774 if (!wd->wd_enabled[i])
13775 continue;
13776
13777 if (wd->wd_exact) {
13778 (void) snprintf(buf, sizeof (buf), "%" PRIi64,
13779 bytes_rem[i]);
13780 } else {
13781 zfs_nicenum(bytes_rem[i], buf, sizeof (buf));
13782 }
13783
13784 if (wd->wd_scripted)
13785 (void) printf(i == 0 ? "%s" : "\t%s", buf);
13786 else
13787 (void) printf(" %*s", col_widths[i] - 1, buf);
13788 }
13789 (void) printf("\n");
13790 (void) fflush(stdout);
13791 }
13792
13793 static void *
wait_status_thread(void * arg)13794 wait_status_thread(void *arg)
13795 {
13796 wait_data_t *wd = (wait_data_t *)arg;
13797 zpool_handle_t *zhp;
13798
13799 if ((zhp = zpool_open(g_zfs, wd->wd_poolname)) == NULL)
13800 return (void *)(1);
13801
13802 for (int row = 0; ; row++) {
13803 boolean_t missing;
13804 struct timespec timeout;
13805 int ret = 0;
13806 (void) clock_gettime(CLOCK_REALTIME, &timeout);
13807
13808 if (zpool_refresh_stats(zhp, &missing) != 0 || missing ||
13809 zpool_props_refresh(zhp) != 0) {
13810 zpool_close(zhp);
13811 return (void *)(uintptr_t)(missing ? 0 : 1);
13812 }
13813
13814 print_wait_status_row(wd, zhp, row);
13815
13816 timeout.tv_sec += floor(wd->wd_interval);
13817 long nanos = timeout.tv_nsec +
13818 (wd->wd_interval - floor(wd->wd_interval)) * NANOSEC;
13819 if (nanos >= NANOSEC) {
13820 timeout.tv_sec++;
13821 timeout.tv_nsec = nanos - NANOSEC;
13822 } else {
13823 timeout.tv_nsec = nanos;
13824 }
13825 (void) pthread_mutex_lock(&wd->wd_mutex);
13826 if (!wd->wd_should_exit)
13827 ret = pthread_cond_timedwait(&wd->wd_cv, &wd->wd_mutex,
13828 &timeout);
13829 (void) pthread_mutex_unlock(&wd->wd_mutex);
13830 if (ret == 0) {
13831 break; /* signaled by main thread */
13832 } else if (ret != ETIMEDOUT) {
13833 (void) fprintf(stderr, gettext("pthread_cond_timedwait "
13834 "failed: %s\n"), strerror(ret));
13835 zpool_close(zhp);
13836 return (void *)(uintptr_t)(1);
13837 }
13838 }
13839
13840 zpool_close(zhp);
13841 return (void *)(0);
13842 }
13843
13844 int
zpool_do_wait(int argc,char ** argv)13845 zpool_do_wait(int argc, char **argv)
13846 {
13847 boolean_t verbose = B_FALSE;
13848 int c, i;
13849 unsigned long count;
13850 pthread_t status_thr;
13851 int error = 0;
13852 zpool_handle_t *zhp;
13853
13854 wait_data_t wd;
13855 wd.wd_scripted = B_FALSE;
13856 wd.wd_exact = B_FALSE;
13857 wd.wd_headers_once = B_FALSE;
13858 wd.wd_should_exit = B_FALSE;
13859
13860 (void) pthread_mutex_init(&wd.wd_mutex, NULL);
13861 (void) pthread_cond_init(&wd.wd_cv, NULL);
13862
13863 /* By default, wait for all types of activity. */
13864 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++)
13865 wd.wd_enabled[i] = B_TRUE;
13866
13867 while ((c = getopt(argc, argv, "HpT:t:")) != -1) {
13868 switch (c) {
13869 case 'H':
13870 wd.wd_scripted = B_TRUE;
13871 break;
13872 case 'n':
13873 wd.wd_headers_once = B_TRUE;
13874 break;
13875 case 'p':
13876 wd.wd_exact = B_TRUE;
13877 break;
13878 case 'T':
13879 get_timestamp_arg(*optarg);
13880 break;
13881 case 't':
13882 /* Reset activities array */
13883 memset(&wd.wd_enabled, 0, sizeof (wd.wd_enabled));
13884
13885 for (char *tok; (tok = strsep(&optarg, ",")); ) {
13886 static const char *const col_opts[] = {
13887 "discard", "free", "initialize", "replace",
13888 "remove", "resilver", "scrub", "trim",
13889 "raidz_expand", "condense" };
13890
13891 for (i = 0; i < ARRAY_SIZE(col_opts); ++i)
13892 if (strcmp(tok, col_opts[i]) == 0) {
13893 wd.wd_enabled[i] = B_TRUE;
13894 goto found;
13895 }
13896
13897 (void) fprintf(stderr,
13898 gettext("invalid activity '%s'\n"), tok);
13899 usage(B_FALSE);
13900 found:;
13901 }
13902 break;
13903 case '?':
13904 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
13905 optopt);
13906 usage(B_FALSE);
13907 }
13908 }
13909
13910 argc -= optind;
13911 argv += optind;
13912
13913 get_interval_count(&argc, argv, &wd.wd_interval, &count);
13914 if (count != 0) {
13915 /* This subcmd only accepts an interval, not a count */
13916 (void) fprintf(stderr, gettext("too many arguments\n"));
13917 usage(B_FALSE);
13918 }
13919
13920 if (wd.wd_interval != 0)
13921 verbose = B_TRUE;
13922
13923 if (argc < 1) {
13924 (void) fprintf(stderr, gettext("missing 'pool' argument\n"));
13925 usage(B_FALSE);
13926 }
13927 if (argc > 1) {
13928 (void) fprintf(stderr, gettext("too many arguments\n"));
13929 usage(B_FALSE);
13930 }
13931
13932 wd.wd_poolname = argv[0];
13933
13934 if ((zhp = zpool_open(g_zfs, wd.wd_poolname)) == NULL)
13935 return (1);
13936
13937 if (verbose) {
13938 /*
13939 * We use a separate thread for printing status updates because
13940 * the main thread will call lzc_wait(), which blocks as long
13941 * as an activity is in progress, which can be a long time.
13942 */
13943 if (pthread_create(&status_thr, NULL, wait_status_thread, &wd)
13944 != 0) {
13945 (void) fprintf(stderr, gettext("failed to create status"
13946 "thread: %s\n"), strerror(errno));
13947 zpool_close(zhp);
13948 return (1);
13949 }
13950 }
13951
13952 /*
13953 * Loop over all activities that we are supposed to wait for until none
13954 * of them are in progress. Note that this means we can end up waiting
13955 * for more activities to complete than just those that were in progress
13956 * when we began waiting; if an activity we are interested in begins
13957 * while we are waiting for another activity, we will wait for both to
13958 * complete before exiting.
13959 */
13960 for (;;) {
13961 boolean_t missing = B_FALSE;
13962 boolean_t any_waited = B_FALSE;
13963
13964 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13965 boolean_t waited;
13966
13967 if (!wd.wd_enabled[i])
13968 continue;
13969
13970 error = zpool_wait_status(zhp, i, &missing, &waited);
13971 if (error != 0 || missing)
13972 break;
13973
13974 any_waited = (any_waited || waited);
13975 }
13976
13977 if (error != 0 || missing || !any_waited)
13978 break;
13979 }
13980
13981 zpool_close(zhp);
13982
13983 if (verbose) {
13984 uintptr_t status;
13985 (void) pthread_mutex_lock(&wd.wd_mutex);
13986 wd.wd_should_exit = B_TRUE;
13987 (void) pthread_cond_signal(&wd.wd_cv);
13988 (void) pthread_mutex_unlock(&wd.wd_mutex);
13989 (void) pthread_join(status_thr, (void *)&status);
13990 if (status != 0)
13991 error = status;
13992 }
13993
13994 (void) pthread_mutex_destroy(&wd.wd_mutex);
13995 (void) pthread_cond_destroy(&wd.wd_cv);
13996 return (error);
13997 }
13998
13999 /*
14000 * zpool ddtprune -d|-p <amount> <pool>
14001 *
14002 * -d <days> Prune entries <days> old and older
14003 * -p <percent> Prune <percent> amount of entries
14004 *
14005 * Prune single reference entries from DDT to satisfy the amount specified.
14006 */
14007 int
zpool_do_ddt_prune(int argc,char ** argv)14008 zpool_do_ddt_prune(int argc, char **argv)
14009 {
14010 zpool_ddt_prune_unit_t unit = ZPOOL_DDT_PRUNE_NONE;
14011 uint64_t amount = 0;
14012 zpool_handle_t *zhp;
14013 char *endptr;
14014 int c;
14015
14016 while ((c = getopt(argc, argv, "d:p:")) != -1) {
14017 switch (c) {
14018 case 'd':
14019 if (unit == ZPOOL_DDT_PRUNE_PERCENTAGE) {
14020 (void) fprintf(stderr, gettext("-d cannot be "
14021 "combined with -p option\n"));
14022 usage(B_FALSE);
14023 }
14024 errno = 0;
14025 amount = strtoull(optarg, &endptr, 0);
14026 if (errno != 0 || *endptr != '\0' || amount == 0) {
14027 (void) fprintf(stderr,
14028 gettext("invalid days value\n"));
14029 usage(B_FALSE);
14030 }
14031 amount *= 86400; /* convert days to seconds */
14032 unit = ZPOOL_DDT_PRUNE_AGE;
14033 break;
14034 case 'p':
14035 if (unit == ZPOOL_DDT_PRUNE_AGE) {
14036 (void) fprintf(stderr, gettext("-p cannot be "
14037 "combined with -d option\n"));
14038 usage(B_FALSE);
14039 }
14040 errno = 0;
14041 amount = strtoull(optarg, &endptr, 0);
14042 if (errno != 0 || *endptr != '\0' ||
14043 amount == 0 || amount > 100) {
14044 (void) fprintf(stderr,
14045 gettext("invalid percentage value\n"));
14046 usage(B_FALSE);
14047 }
14048 unit = ZPOOL_DDT_PRUNE_PERCENTAGE;
14049 break;
14050 case '?':
14051 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
14052 optopt);
14053 usage(B_FALSE);
14054 }
14055 }
14056 argc -= optind;
14057 argv += optind;
14058
14059 if (unit == ZPOOL_DDT_PRUNE_NONE) {
14060 (void) fprintf(stderr,
14061 gettext("missing amount option (-d|-p <value>)\n"));
14062 usage(B_FALSE);
14063 } else if (argc < 1) {
14064 (void) fprintf(stderr, gettext("missing pool argument\n"));
14065 usage(B_FALSE);
14066 } else if (argc > 1) {
14067 (void) fprintf(stderr, gettext("too many arguments\n"));
14068 usage(B_FALSE);
14069 }
14070 zhp = zpool_open(g_zfs, argv[0]);
14071 if (zhp == NULL)
14072 return (-1);
14073
14074 int error = zpool_ddt_prune(zhp, unit, amount);
14075
14076 zpool_close(zhp);
14077
14078 return (error);
14079 }
14080
14081 static int
find_command_idx(const char * command,int * idx)14082 find_command_idx(const char *command, int *idx)
14083 {
14084 for (int i = 0; i < NCOMMAND; ++i) {
14085 if (command_table[i].name == NULL)
14086 continue;
14087
14088 if (strcmp(command, command_table[i].name) == 0) {
14089 *idx = i;
14090 return (0);
14091 }
14092 }
14093 return (1);
14094 }
14095
14096 /*
14097 * Display version message
14098 */
14099 static int
zpool_do_version(int argc,char ** argv)14100 zpool_do_version(int argc, char **argv)
14101 {
14102 int c;
14103 nvlist_t *jsobj = NULL, *zfs_ver = NULL;
14104 boolean_t json = B_FALSE;
14105
14106 struct option long_options[] = {
14107 {"json", no_argument, NULL, 'j'},
14108 };
14109
14110 while ((c = getopt_long(argc, argv, "j", long_options, NULL)) != -1) {
14111 switch (c) {
14112 case 'j':
14113 json = B_TRUE;
14114 jsobj = zpool_json_schema(0, 1);
14115 break;
14116 case '?':
14117 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
14118 optopt);
14119 usage(B_FALSE);
14120 }
14121 }
14122
14123 argc -= optind;
14124 if (argc != 0) {
14125 (void) fprintf(stderr, "too many arguments\n");
14126 usage(B_FALSE);
14127 }
14128
14129 if (json) {
14130 zfs_ver = zfs_version_nvlist();
14131 if (zfs_ver) {
14132 fnvlist_add_nvlist(jsobj, "zfs_version", zfs_ver);
14133 zcmd_print_json(jsobj);
14134 fnvlist_free(zfs_ver);
14135 return (0);
14136 } else
14137 return (-1);
14138 } else
14139 return (zfs_version_print() != 0);
14140 }
14141
14142 /* Display documentation */
14143 static int
zpool_do_help(int argc,char ** argv)14144 zpool_do_help(int argc, char **argv)
14145 {
14146 char page[MAXNAMELEN];
14147 if (argc < 3 || strcmp(argv[2], "zpool") == 0)
14148 (void) strcpy(page, "zpool");
14149 else if (strcmp(argv[2], "concepts") == 0 ||
14150 strcmp(argv[2], "props") == 0)
14151 (void) snprintf(page, sizeof (page), "zpool%s", argv[2]);
14152 else
14153 (void) snprintf(page, sizeof (page), "zpool-%s", argv[2]);
14154
14155 (void) execlp("man", "man", page, NULL);
14156
14157 fprintf(stderr, "couldn't run man program: %s\n", strerror(errno));
14158 return (-1);
14159 }
14160
14161 /*
14162 * Do zpool_load_compat() and print error message on failure
14163 */
14164 static zpool_compat_status_t
zpool_do_load_compat(const char * compat,boolean_t * list)14165 zpool_do_load_compat(const char *compat, boolean_t *list)
14166 {
14167 char report[1024];
14168
14169 zpool_compat_status_t ret;
14170
14171 ret = zpool_load_compat(compat, list, report, 1024);
14172 switch (ret) {
14173
14174 case ZPOOL_COMPATIBILITY_OK:
14175 break;
14176
14177 case ZPOOL_COMPATIBILITY_NOFILES:
14178 case ZPOOL_COMPATIBILITY_BADFILE:
14179 case ZPOOL_COMPATIBILITY_BADTOKEN:
14180 (void) fprintf(stderr, "Error: %s\n", report);
14181 break;
14182
14183 case ZPOOL_COMPATIBILITY_WARNTOKEN:
14184 (void) fprintf(stderr, "Warning: %s\n", report);
14185 ret = ZPOOL_COMPATIBILITY_OK;
14186 break;
14187 }
14188 return (ret);
14189 }
14190
14191 int
main(int argc,char ** argv)14192 main(int argc, char **argv)
14193 {
14194 int ret = 0;
14195 int i = 0;
14196 char *cmdname;
14197 char **newargv;
14198
14199 (void) setlocale(LC_ALL, "");
14200 (void) setlocale(LC_NUMERIC, "C");
14201 (void) textdomain(TEXT_DOMAIN);
14202 srand(time(NULL));
14203
14204 opterr = 0;
14205
14206 /*
14207 * Make sure the user has specified some command.
14208 */
14209 if (argc < 2) {
14210 (void) fprintf(stderr, gettext("missing command\n"));
14211 usage(B_FALSE);
14212 }
14213
14214 cmdname = argv[1];
14215
14216 /*
14217 * Special case '-?'
14218 */
14219 if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
14220 usage(B_TRUE);
14221
14222 /*
14223 * Special case '-V|--version'
14224 */
14225 if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
14226 return (zfs_version_print() != 0);
14227
14228 /*
14229 * Special case 'help'
14230 */
14231 if (strcmp(cmdname, "help") == 0)
14232 return (zpool_do_help(argc, argv));
14233
14234 /*
14235 * Special case '<subcommand> --help|-?'
14236 */
14237 if (argc >= 3 && (strcmp(argv[2], "--help") == 0 ||
14238 strcmp(argv[2], "-?") == 0)) {
14239 int idx;
14240 if (find_command_idx(cmdname, &idx) == 0) {
14241 current_command = &command_table[idx];
14242 usage(B_FALSE);
14243 }
14244 }
14245
14246 if ((g_zfs = libzfs_init()) == NULL) {
14247 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
14248 return (1);
14249 }
14250
14251 libzfs_print_on_error(g_zfs, B_TRUE);
14252
14253 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
14254
14255 /*
14256 * Many commands modify input strings for string parsing reasons.
14257 * We create a copy to protect the original argv.
14258 */
14259 newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
14260 for (i = 0; i < argc; i++)
14261 newargv[i] = strdup(argv[i]);
14262 newargv[argc] = NULL;
14263
14264 /*
14265 * Run the appropriate command.
14266 */
14267 if (find_command_idx(cmdname, &i) == 0) {
14268 current_command = &command_table[i];
14269 ret = command_table[i].func(argc - 1, newargv + 1);
14270 } else if (strchr(cmdname, '=')) {
14271 verify(find_command_idx("set", &i) == 0);
14272 current_command = &command_table[i];
14273 ret = command_table[i].func(argc, newargv);
14274 } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
14275 /*
14276 * 'freeze' is a vile debugging abomination, so we treat
14277 * it as such.
14278 */
14279 zfs_cmd_t zc = {"\0"};
14280
14281 (void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
14282 ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
14283 if (ret != 0) {
14284 (void) fprintf(stderr,
14285 gettext("failed to freeze pool: %d\n"), errno);
14286 ret = 1;
14287 }
14288
14289 log_history = 0;
14290 } else {
14291 (void) fprintf(stderr, gettext("unrecognized "
14292 "command '%s'\n"), cmdname);
14293 usage(B_FALSE);
14294 }
14295
14296 for (i = 0; i < argc; i++)
14297 free(newargv[i]);
14298 free(newargv);
14299
14300 if (ret == 0 && log_history)
14301 (void) zpool_log_history(g_zfs, history_str);
14302
14303 libzfs_fini(g_zfs);
14304
14305 /*
14306 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
14307 * for the purposes of running ::findleaks.
14308 */
14309 if (getenv("ZFS_ABORT") != NULL) {
14310 (void) printf("dumping core by request\n");
14311 abort();
14312 }
14313
14314 return (ret);
14315 }
14316