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 [-DdegiLPpstx] [-v|-vv] "
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_RAW:
1079 zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_RAW);
1080 break;
1081 case ZFS_NICENUM_TIME:
1082 zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_TIME);
1083 break;
1084 case ZFS_NICE_TIMESTAMP:
1085 format_timestamp(value, buf, 256);
1086 break;
1087 default:
1088 fprintf(stderr, "Invalid number format");
1089 exit(1);
1090 }
1091 }
1092 if (as_int)
1093 fnvlist_add_uint64(item, key, value);
1094 else
1095 fnvlist_add_string(item, key, buf);
1096 }
1097
1098 /*
1099 * Generates an nvlist with output version for every command based on params.
1100 * Purpose of this is to add a version of JSON output, considering the schema
1101 * format might be updated for each command in future.
1102 *
1103 * Schema:
1104 *
1105 * "output_version": {
1106 * "command": string,
1107 * "vers_major": integer,
1108 * "vers_minor": integer,
1109 * }
1110 */
1111 static nvlist_t *
zpool_json_schema(int maj_v,int min_v)1112 zpool_json_schema(int maj_v, int min_v)
1113 {
1114 char cmd[MAX_CMD_LEN];
1115 nvlist_t *sch = fnvlist_alloc();
1116 nvlist_t *ov = fnvlist_alloc();
1117
1118 (void) snprintf(cmd, MAX_CMD_LEN, "zpool %s", current_command->name);
1119 fnvlist_add_string(ov, "command", cmd);
1120 fnvlist_add_uint32(ov, "vers_major", maj_v);
1121 fnvlist_add_uint32(ov, "vers_minor", min_v);
1122 fnvlist_add_nvlist(sch, "output_version", ov);
1123 fnvlist_free(ov);
1124 return (sch);
1125 }
1126
1127 static void
fill_pool_info(nvlist_t * list,zpool_handle_t * zhp,boolean_t addtype,boolean_t as_int)1128 fill_pool_info(nvlist_t *list, zpool_handle_t *zhp, boolean_t addtype,
1129 boolean_t as_int)
1130 {
1131 nvlist_t *config = zpool_get_config(zhp, NULL);
1132 uint64_t guid = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID);
1133 uint64_t txg = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG);
1134
1135 fnvlist_add_string(list, "name", zpool_get_name(zhp));
1136 if (addtype)
1137 fnvlist_add_string(list, "type", "POOL");
1138 fnvlist_add_string(list, "state", zpool_get_state_str(zhp));
1139 if (as_int) {
1140 if (guid)
1141 fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_GUID, guid);
1142 if (txg)
1143 fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_TXG, txg);
1144 fnvlist_add_uint64(list, "spa_version", SPA_VERSION);
1145 fnvlist_add_uint64(list, "zpl_version", ZPL_VERSION);
1146 } else {
1147 char value[ZFS_MAXPROPLEN];
1148 if (guid) {
1149 (void) snprintf(value, ZFS_MAXPROPLEN, "%llu",
1150 (u_longlong_t)guid);
1151 fnvlist_add_string(list, ZPOOL_CONFIG_POOL_GUID, value);
1152 }
1153 if (txg) {
1154 (void) snprintf(value, ZFS_MAXPROPLEN, "%llu",
1155 (u_longlong_t)txg);
1156 fnvlist_add_string(list, ZPOOL_CONFIG_POOL_TXG, value);
1157 }
1158 fnvlist_add_string(list, "spa_version", SPA_VERSION_STRING);
1159 fnvlist_add_string(list, "zpl_version", ZPL_VERSION_STRING);
1160 }
1161 }
1162
1163 static void
used_by_other(zpool_handle_t * zhp,nvlist_t * nvdev,nvlist_t * list)1164 used_by_other(zpool_handle_t *zhp, nvlist_t *nvdev, nvlist_t *list)
1165 {
1166 spare_cbdata_t spare_cb;
1167 verify(nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID,
1168 &spare_cb.cb_guid) == 0);
1169 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1170 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1171 zpool_get_name(zhp)) != 0) {
1172 fnvlist_add_string(list, "used_by",
1173 zpool_get_name(spare_cb.cb_zhp));
1174 }
1175 zpool_close(spare_cb.cb_zhp);
1176 }
1177 }
1178
1179 static void
fill_vdev_info(nvlist_t * list,zpool_handle_t * zhp,char * name,boolean_t addtype,boolean_t as_int)1180 fill_vdev_info(nvlist_t *list, zpool_handle_t *zhp, char *name,
1181 boolean_t addtype, boolean_t as_int)
1182 {
1183 boolean_t l2c = B_FALSE;
1184 const char *path, *phys, *devid, *bias = NULL;
1185 uint64_t hole = 0, log = 0, spare = 0;
1186 vdev_stat_t *vs;
1187 uint_t c;
1188 nvlist_t *nvdev;
1189 nvlist_t *nvdev_parent = NULL;
1190 char *_name;
1191
1192 if (strcmp(name, zpool_get_name(zhp)) != 0)
1193 _name = name;
1194 else
1195 _name = (char *)"root-0";
1196
1197 nvdev = zpool_find_vdev(zhp, _name, NULL, &l2c, NULL);
1198
1199 fnvlist_add_string(list, "name", name);
1200 if (addtype)
1201 fnvlist_add_string(list, "type", "VDEV");
1202 if (nvdev) {
1203 const char *type = fnvlist_lookup_string(nvdev,
1204 ZPOOL_CONFIG_TYPE);
1205 if (type)
1206 fnvlist_add_string(list, "vdev_type", type);
1207 uint64_t guid = fnvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID);
1208 if (guid) {
1209 if (as_int) {
1210 fnvlist_add_uint64(list, "guid", guid);
1211 } else {
1212 char buf[ZFS_MAXPROPLEN];
1213 (void) snprintf(buf, ZFS_MAXPROPLEN, "%llu",
1214 (u_longlong_t)guid);
1215 fnvlist_add_string(list, "guid", buf);
1216 }
1217 }
1218 if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PATH, &path) == 0)
1219 fnvlist_add_string(list, "path", path);
1220 if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PHYS_PATH,
1221 &phys) == 0)
1222 fnvlist_add_string(list, "phys_path", phys);
1223 if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_DEVID,
1224 &devid) == 0)
1225 fnvlist_add_string(list, "devid", devid);
1226 (void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_LOG, &log);
1227 (void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_SPARE,
1228 &spare);
1229 (void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_HOLE, &hole);
1230 if (hole)
1231 fnvlist_add_string(list, "class", VDEV_TYPE_HOLE);
1232 else if (l2c)
1233 fnvlist_add_string(list, "class", VDEV_TYPE_L2CACHE);
1234 else if (spare)
1235 fnvlist_add_string(list, "class", VDEV_TYPE_SPARE);
1236 else if (log)
1237 fnvlist_add_string(list, "class", VDEV_TYPE_LOG);
1238 else {
1239 (void) nvlist_lookup_string(nvdev,
1240 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
1241 if (bias != NULL)
1242 fnvlist_add_string(list, "class", bias);
1243 else {
1244 nvdev_parent = NULL;
1245 nvdev_parent = zpool_find_parent_vdev(zhp,
1246 _name, NULL, NULL, NULL);
1247
1248 /*
1249 * With a mirrored special device, the parent
1250 * "mirror" vdev will have
1251 * ZPOOL_CONFIG_ALLOCATION_BIAS set to "special"
1252 * not the leaf vdevs. If we're a leaf vdev
1253 * in that case we need to look at our parent
1254 * to see if they're "special" to know if we
1255 * are "special" too.
1256 */
1257 if (nvdev_parent) {
1258 (void) nvlist_lookup_string(
1259 nvdev_parent,
1260 ZPOOL_CONFIG_ALLOCATION_BIAS,
1261 &bias);
1262 }
1263 if (bias != NULL)
1264 fnvlist_add_string(list, "class", bias);
1265 else
1266 fnvlist_add_string(list, "class",
1267 "normal");
1268 }
1269 }
1270 if (nvlist_lookup_uint64_array(nvdev, ZPOOL_CONFIG_VDEV_STATS,
1271 (uint64_t **)&vs, &c) == 0) {
1272 fnvlist_add_string(list, "state",
1273 vdev_state_str[vs->vs_state]);
1274 }
1275 }
1276 }
1277
1278 static boolean_t
prop_list_contains_feature(nvlist_t * proplist)1279 prop_list_contains_feature(nvlist_t *proplist)
1280 {
1281 nvpair_t *nvp;
1282 for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
1283 nvp = nvlist_next_nvpair(proplist, nvp)) {
1284 if (zpool_prop_feature(nvpair_name(nvp)))
1285 return (B_TRUE);
1286 }
1287 return (B_FALSE);
1288 }
1289
1290 /*
1291 * Add a property pair (name, string-value) into a property nvlist.
1292 */
1293 static int
add_prop_list(const char * propname,const char * propval,nvlist_t ** props,boolean_t poolprop)1294 add_prop_list(const char *propname, const char *propval, nvlist_t **props,
1295 boolean_t poolprop)
1296 {
1297 zpool_prop_t prop = ZPOOL_PROP_INVAL;
1298 nvlist_t *proplist;
1299 const char *normnm;
1300 const char *strval;
1301
1302 if (*props == NULL &&
1303 nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
1304 (void) fprintf(stderr,
1305 gettext("internal error: out of memory\n"));
1306 return (1);
1307 }
1308
1309 proplist = *props;
1310
1311 if (poolprop) {
1312 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
1313 const char *cname =
1314 zpool_prop_to_name(ZPOOL_PROP_COMPATIBILITY);
1315
1316 if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
1317 (!zpool_prop_feature(propname) &&
1318 !zpool_prop_vdev(propname))) {
1319 (void) fprintf(stderr, gettext("property '%s' is "
1320 "not a valid pool or vdev property\n"), propname);
1321 return (2);
1322 }
1323
1324 /*
1325 * feature@ properties and version should not be specified
1326 * at the same time.
1327 */
1328 if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
1329 nvlist_exists(proplist, vname)) ||
1330 (prop == ZPOOL_PROP_VERSION &&
1331 prop_list_contains_feature(proplist))) {
1332 (void) fprintf(stderr, gettext("'feature@' and "
1333 "'version' properties cannot be specified "
1334 "together\n"));
1335 return (2);
1336 }
1337
1338 /*
1339 * if version is specified, only "legacy" compatibility
1340 * may be requested
1341 */
1342 if ((prop == ZPOOL_PROP_COMPATIBILITY &&
1343 strcmp(propval, ZPOOL_COMPAT_LEGACY) != 0 &&
1344 nvlist_exists(proplist, vname)) ||
1345 (prop == ZPOOL_PROP_VERSION &&
1346 nvlist_exists(proplist, cname) &&
1347 strcmp(fnvlist_lookup_string(proplist, cname),
1348 ZPOOL_COMPAT_LEGACY) != 0)) {
1349 (void) fprintf(stderr, gettext("when 'version' is "
1350 "specified, the 'compatibility' feature may only "
1351 "be set to '" ZPOOL_COMPAT_LEGACY "'\n"));
1352 return (2);
1353 }
1354
1355 if (zpool_prop_feature(propname) || zpool_prop_vdev(propname))
1356 normnm = propname;
1357 else
1358 normnm = zpool_prop_to_name(prop);
1359 } else {
1360 zfs_prop_t fsprop = zfs_name_to_prop(propname);
1361
1362 if (zfs_prop_valid_for_type(fsprop, ZFS_TYPE_FILESYSTEM,
1363 B_FALSE)) {
1364 normnm = zfs_prop_to_name(fsprop);
1365 } else if (zfs_prop_user(propname) ||
1366 zfs_prop_userquota(propname)) {
1367 normnm = propname;
1368 } else {
1369 (void) fprintf(stderr, gettext("property '%s' is "
1370 "not a valid filesystem property\n"), propname);
1371 return (2);
1372 }
1373 }
1374
1375 if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
1376 prop != ZPOOL_PROP_CACHEFILE) {
1377 (void) fprintf(stderr, gettext("property '%s' "
1378 "specified multiple times\n"), propname);
1379 return (2);
1380 }
1381
1382 if (nvlist_add_string(proplist, normnm, propval) != 0) {
1383 (void) fprintf(stderr, gettext("internal "
1384 "error: out of memory\n"));
1385 return (1);
1386 }
1387
1388 return (0);
1389 }
1390
1391 /*
1392 * Set a default property pair (name, string-value) in a property nvlist
1393 */
1394 static int
add_prop_list_default(const char * propname,const char * propval,nvlist_t ** props)1395 add_prop_list_default(const char *propname, const char *propval,
1396 nvlist_t **props)
1397 {
1398 const char *pval;
1399
1400 if (nvlist_lookup_string(*props, propname, &pval) == 0)
1401 return (0);
1402
1403 return (add_prop_list(propname, propval, props, B_TRUE));
1404 }
1405
1406 /*
1407 * zpool add [-afgLnP] [-o property=value] <pool> <vdev> ...
1408 *
1409 * -a Disable the ashift validation checks
1410 * -f Force addition of devices, even if they appear in use
1411 * -g Display guid for individual vdev name.
1412 * -L Follow links when resolving vdev path name.
1413 * -n Do not add the devices, but display the resulting layout if
1414 * they were to be added.
1415 * -o Set property=value.
1416 * -P Display full path for vdev name.
1417 *
1418 * Adds the given vdevs to 'pool'. As with create, the bulk of this work is
1419 * handled by make_root_vdev(), which constructs the nvlist needed to pass to
1420 * libzfs.
1421 */
1422 int
zpool_do_add(int argc,char ** argv)1423 zpool_do_add(int argc, char **argv)
1424 {
1425 boolean_t check_replication = B_TRUE;
1426 boolean_t check_inuse = B_TRUE;
1427 boolean_t dryrun = B_FALSE;
1428 boolean_t check_ashift = B_TRUE;
1429 boolean_t force = B_FALSE;
1430 int name_flags = 0;
1431 int c;
1432 nvlist_t *nvroot;
1433 char *poolname;
1434 int ret;
1435 zpool_handle_t *zhp;
1436 nvlist_t *config;
1437 nvlist_t *props = NULL;
1438 char *propval;
1439
1440 struct option long_options[] = {
1441 {"allow-in-use", no_argument, NULL, ZPOOL_OPTION_ALLOW_INUSE},
1442 {"allow-replication-mismatch", no_argument, NULL,
1443 ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH},
1444 {"allow-ashift-mismatch", no_argument, NULL,
1445 ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH},
1446 {0, 0, 0, 0}
1447 };
1448
1449 /* check options */
1450 while ((c = getopt_long(argc, argv, "fgLno:P", long_options, NULL))
1451 != -1) {
1452 switch (c) {
1453 case 'f':
1454 force = B_TRUE;
1455 break;
1456 case 'g':
1457 name_flags |= VDEV_NAME_GUID;
1458 break;
1459 case 'L':
1460 name_flags |= VDEV_NAME_FOLLOW_LINKS;
1461 break;
1462 case 'n':
1463 dryrun = B_TRUE;
1464 break;
1465 case 'o':
1466 if ((propval = strchr(optarg, '=')) == NULL) {
1467 (void) fprintf(stderr, gettext("missing "
1468 "'=' for -o option\n"));
1469 usage(B_FALSE);
1470 }
1471 *propval = '\0';
1472 propval++;
1473
1474 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
1475 (add_prop_list(optarg, propval, &props, B_TRUE)))
1476 usage(B_FALSE);
1477 break;
1478 case 'P':
1479 name_flags |= VDEV_NAME_PATH;
1480 break;
1481 case ZPOOL_OPTION_ALLOW_INUSE:
1482 check_inuse = B_FALSE;
1483 break;
1484 case ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH:
1485 check_replication = B_FALSE;
1486 break;
1487 case ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH:
1488 check_ashift = B_FALSE;
1489 break;
1490 case '?':
1491 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1492 optopt);
1493 usage(B_FALSE);
1494 }
1495 }
1496
1497 argc -= optind;
1498 argv += optind;
1499
1500 /* get pool name and check number of arguments */
1501 if (argc < 1) {
1502 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1503 usage(B_FALSE);
1504 }
1505 if (argc < 2) {
1506 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1507 usage(B_FALSE);
1508 }
1509
1510 if (force) {
1511 if (!check_inuse || !check_replication || !check_ashift) {
1512 (void) fprintf(stderr, gettext("'-f' option is not "
1513 "allowed with '--allow-replication-mismatch', "
1514 "'--allow-ashift-mismatch', or "
1515 "'--allow-in-use'\n"));
1516 usage(B_FALSE);
1517 }
1518 check_inuse = B_FALSE;
1519 check_replication = B_FALSE;
1520 check_ashift = B_FALSE;
1521 }
1522
1523 poolname = argv[0];
1524
1525 argc--;
1526 argv++;
1527
1528 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1529 return (1);
1530
1531 if ((config = zpool_get_config(zhp, NULL)) == NULL) {
1532 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
1533 poolname);
1534 zpool_close(zhp);
1535 return (1);
1536 }
1537
1538 /* unless manually specified use "ashift" pool property (if set) */
1539 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
1540 int intval;
1541 zprop_source_t src;
1542 char strval[ZPOOL_MAXPROPLEN];
1543
1544 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
1545 if (src != ZPROP_SRC_DEFAULT) {
1546 (void) sprintf(strval, "%" PRId32, intval);
1547 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
1548 &props, B_TRUE) == 0);
1549 }
1550 }
1551
1552 /* pass off to make_root_vdev for processing */
1553 nvroot = make_root_vdev(zhp, props, !check_inuse,
1554 check_replication, B_FALSE, dryrun, argc, argv);
1555 if (nvroot == NULL) {
1556 zpool_close(zhp);
1557 return (1);
1558 }
1559
1560 if (dryrun) {
1561 nvlist_t *poolnvroot;
1562 nvlist_t **l2child, **sparechild;
1563 uint_t l2children, sparechildren, c;
1564 char *vname;
1565 boolean_t hadcache = B_FALSE, hadspare = B_FALSE;
1566
1567 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1568 &poolnvroot) == 0);
1569
1570 (void) printf(gettext("would update '%s' to the following "
1571 "configuration:\n\n"), zpool_get_name(zhp));
1572
1573 /* print original main pool and new tree */
1574 print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
1575 name_flags | VDEV_NAME_TYPE_ID);
1576 print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
1577
1578 /* print other classes: 'dedup', 'special', and 'log' */
1579 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1580 print_vdev_tree(zhp, "dedup", poolnvroot, 0,
1581 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1582 print_vdev_tree(zhp, NULL, nvroot, 0,
1583 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1584 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1585 print_vdev_tree(zhp, "dedup", nvroot, 0,
1586 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1587 }
1588
1589 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1590 print_vdev_tree(zhp, "special", poolnvroot, 0,
1591 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1592 print_vdev_tree(zhp, NULL, nvroot, 0,
1593 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1594 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1595 print_vdev_tree(zhp, "special", nvroot, 0,
1596 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1597 }
1598
1599 if (num_logs(poolnvroot) > 0) {
1600 print_vdev_tree(zhp, "logs", poolnvroot, 0,
1601 VDEV_ALLOC_BIAS_LOG, name_flags);
1602 print_vdev_tree(zhp, NULL, nvroot, 0,
1603 VDEV_ALLOC_BIAS_LOG, name_flags);
1604 } else if (num_logs(nvroot) > 0) {
1605 print_vdev_tree(zhp, "logs", nvroot, 0,
1606 VDEV_ALLOC_BIAS_LOG, name_flags);
1607 }
1608
1609 /* Do the same for the caches */
1610 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
1611 &l2child, &l2children) == 0 && l2children) {
1612 hadcache = B_TRUE;
1613 (void) printf(gettext("\tcache\n"));
1614 for (c = 0; c < l2children; c++) {
1615 vname = zpool_vdev_name(g_zfs, NULL,
1616 l2child[c], name_flags);
1617 (void) printf("\t %s\n", vname);
1618 free(vname);
1619 }
1620 }
1621 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1622 &l2child, &l2children) == 0 && l2children) {
1623 if (!hadcache)
1624 (void) printf(gettext("\tcache\n"));
1625 for (c = 0; c < l2children; c++) {
1626 vname = zpool_vdev_name(g_zfs, NULL,
1627 l2child[c], name_flags);
1628 (void) printf("\t %s\n", vname);
1629 free(vname);
1630 }
1631 }
1632 /* And finally the spares */
1633 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_SPARES,
1634 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1635 hadspare = B_TRUE;
1636 (void) printf(gettext("\tspares\n"));
1637 for (c = 0; c < sparechildren; c++) {
1638 vname = zpool_vdev_name(g_zfs, NULL,
1639 sparechild[c], name_flags);
1640 (void) printf("\t %s\n", vname);
1641 free(vname);
1642 }
1643 }
1644 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1645 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1646 if (!hadspare)
1647 (void) printf(gettext("\tspares\n"));
1648 for (c = 0; c < sparechildren; c++) {
1649 vname = zpool_vdev_name(g_zfs, NULL,
1650 sparechild[c], name_flags);
1651 (void) printf("\t %s\n", vname);
1652 free(vname);
1653 }
1654 }
1655
1656 ret = 0;
1657 } else {
1658 ret = (zpool_add(zhp, nvroot, check_ashift) != 0);
1659 }
1660
1661 nvlist_free(props);
1662 nvlist_free(nvroot);
1663 zpool_close(zhp);
1664
1665 return (ret);
1666 }
1667
1668 /*
1669 * zpool remove [-npsw] <pool> <vdev> ...
1670 *
1671 * Removes the given vdev from the pool.
1672 */
1673 int
zpool_do_remove(int argc,char ** argv)1674 zpool_do_remove(int argc, char **argv)
1675 {
1676 char *poolname;
1677 int i, ret = 0;
1678 zpool_handle_t *zhp = NULL;
1679 boolean_t stop = B_FALSE;
1680 int c;
1681 boolean_t noop = B_FALSE;
1682 boolean_t parsable = B_FALSE;
1683 boolean_t wait = B_FALSE;
1684
1685 /* check options */
1686 while ((c = getopt(argc, argv, "npsw")) != -1) {
1687 switch (c) {
1688 case 'n':
1689 noop = B_TRUE;
1690 break;
1691 case 'p':
1692 parsable = B_TRUE;
1693 break;
1694 case 's':
1695 stop = B_TRUE;
1696 break;
1697 case 'w':
1698 wait = B_TRUE;
1699 break;
1700 case '?':
1701 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1702 optopt);
1703 usage(B_FALSE);
1704 }
1705 }
1706
1707 argc -= optind;
1708 argv += optind;
1709
1710 /* get pool name and check number of arguments */
1711 if (argc < 1) {
1712 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1713 usage(B_FALSE);
1714 }
1715
1716 poolname = argv[0];
1717
1718 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1719 return (1);
1720
1721 if (stop && noop) {
1722 zpool_close(zhp);
1723 (void) fprintf(stderr, gettext("stop request ignored\n"));
1724 return (0);
1725 }
1726
1727 if (stop) {
1728 if (argc > 1) {
1729 (void) fprintf(stderr, gettext("too many arguments\n"));
1730 usage(B_FALSE);
1731 }
1732 if (zpool_vdev_remove_cancel(zhp) != 0)
1733 ret = 1;
1734 if (wait) {
1735 (void) fprintf(stderr, gettext("invalid option "
1736 "combination: -w cannot be used with -s\n"));
1737 usage(B_FALSE);
1738 }
1739 } else {
1740 if (argc < 2) {
1741 (void) fprintf(stderr, gettext("missing device\n"));
1742 usage(B_FALSE);
1743 }
1744
1745 for (i = 1; i < argc; i++) {
1746 if (noop) {
1747 uint64_t size;
1748
1749 if (zpool_vdev_indirect_size(zhp, argv[i],
1750 &size) != 0) {
1751 ret = 1;
1752 break;
1753 }
1754 if (parsable) {
1755 (void) printf("%s %llu\n",
1756 argv[i], (unsigned long long)size);
1757 } else {
1758 char valstr[32];
1759 zfs_nicenum(size, valstr,
1760 sizeof (valstr));
1761 (void) printf("Memory that will be "
1762 "used after removing %s: %s\n",
1763 argv[i], valstr);
1764 }
1765 } else {
1766 if (zpool_vdev_remove(zhp, argv[i]) != 0)
1767 ret = 1;
1768 }
1769 }
1770
1771 if (ret == 0 && wait)
1772 ret = zpool_wait(zhp, ZPOOL_WAIT_REMOVE);
1773 }
1774 zpool_close(zhp);
1775
1776 return (ret);
1777 }
1778
1779 /*
1780 * Return 1 if a vdev is active (being used in a pool)
1781 * Return 0 if a vdev is inactive (offlined or faulted, or not in active pool)
1782 *
1783 * This is useful for checking if a disk in an active pool is offlined or
1784 * faulted.
1785 */
1786 static int
vdev_is_active(char * vdev_path)1787 vdev_is_active(char *vdev_path)
1788 {
1789 int fd;
1790 fd = open(vdev_path, O_EXCL);
1791 if (fd < 0) {
1792 return (1); /* cant open O_EXCL - disk is active */
1793 }
1794
1795 (void) close(fd);
1796 return (0); /* disk is inactive in the pool */
1797 }
1798
1799 /*
1800 * zpool labelclear [-f] <vdev>
1801 *
1802 * -f Force clearing the label for the vdevs which are members of
1803 * the exported or foreign pools.
1804 *
1805 * Verifies that the vdev is not active and zeros out the label information
1806 * on the device.
1807 */
1808 int
zpool_do_labelclear(int argc,char ** argv)1809 zpool_do_labelclear(int argc, char **argv)
1810 {
1811 char vdev[MAXPATHLEN];
1812 char *name = NULL;
1813 int c, fd, ret = 0;
1814 nvlist_t *config;
1815 pool_state_t state;
1816 boolean_t inuse = B_FALSE;
1817 boolean_t force = B_FALSE;
1818
1819 /* check options */
1820 while ((c = getopt(argc, argv, "f")) != -1) {
1821 switch (c) {
1822 case 'f':
1823 force = B_TRUE;
1824 break;
1825 default:
1826 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1827 optopt);
1828 usage(B_FALSE);
1829 }
1830 }
1831
1832 argc -= optind;
1833 argv += optind;
1834
1835 /* get vdev name */
1836 if (argc < 1) {
1837 (void) fprintf(stderr, gettext("missing vdev name\n"));
1838 usage(B_FALSE);
1839 }
1840 if (argc > 1) {
1841 (void) fprintf(stderr, gettext("too many arguments\n"));
1842 usage(B_FALSE);
1843 }
1844
1845 (void) strlcpy(vdev, argv[0], sizeof (vdev));
1846
1847 /*
1848 * If we cannot open an absolute path, we quit.
1849 * Otherwise if the provided vdev name doesn't point to a file,
1850 * try prepending expected disk paths and partition numbers.
1851 */
1852 if ((fd = open(vdev, O_RDWR)) < 0) {
1853 int error;
1854 if (vdev[0] == '/') {
1855 (void) fprintf(stderr, gettext("failed to open "
1856 "%s: %s\n"), vdev, strerror(errno));
1857 return (1);
1858 }
1859
1860 error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
1861 if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
1862 if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
1863 error = ENOENT;
1864 }
1865
1866 if (error || ((fd = open(vdev, O_RDWR)) < 0)) {
1867 if (errno == ENOENT) {
1868 (void) fprintf(stderr, gettext(
1869 "failed to find device %s, try "
1870 "specifying absolute path instead\n"),
1871 argv[0]);
1872 return (1);
1873 }
1874
1875 (void) fprintf(stderr, gettext("failed to open %s:"
1876 " %s\n"), vdev, strerror(errno));
1877 return (1);
1878 }
1879 }
1880
1881 /*
1882 * Flush all dirty pages for the block device. This should not be
1883 * fatal when the device does not support BLKFLSBUF as would be the
1884 * case for a file vdev.
1885 */
1886 if ((zfs_dev_flush(fd) != 0) && (errno != ENOTTY))
1887 (void) fprintf(stderr, gettext("failed to invalidate "
1888 "cache for %s: %s\n"), vdev, strerror(errno));
1889
1890 if (zpool_read_label(fd, &config, NULL) != 0) {
1891 (void) fprintf(stderr,
1892 gettext("failed to read label from %s\n"), vdev);
1893 ret = 1;
1894 goto errout;
1895 }
1896 nvlist_free(config);
1897
1898 ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1899 if (ret != 0) {
1900 (void) fprintf(stderr,
1901 gettext("failed to check state for %s\n"), vdev);
1902 ret = 1;
1903 goto errout;
1904 }
1905
1906 if (!inuse)
1907 goto wipe_label;
1908
1909 switch (state) {
1910 default:
1911 case POOL_STATE_ACTIVE:
1912 case POOL_STATE_SPARE:
1913 case POOL_STATE_L2CACHE:
1914 /*
1915 * We allow the user to call 'zpool offline -f'
1916 * on an offlined disk in an active pool. We can check if
1917 * the disk is online by calling vdev_is_active().
1918 */
1919 if (force && !vdev_is_active(vdev))
1920 break;
1921
1922 (void) fprintf(stderr, gettext(
1923 "%s is a member (%s) of pool \"%s\""),
1924 vdev, zpool_pool_state_to_name(state), name);
1925
1926 if (force) {
1927 (void) fprintf(stderr, gettext(
1928 ". Offline the disk first to clear its label."));
1929 }
1930 printf("\n");
1931 ret = 1;
1932 goto errout;
1933
1934 case POOL_STATE_EXPORTED:
1935 if (force)
1936 break;
1937 (void) fprintf(stderr, gettext(
1938 "use '-f' to override the following error:\n"
1939 "%s is a member of exported pool \"%s\"\n"),
1940 vdev, name);
1941 ret = 1;
1942 goto errout;
1943
1944 case POOL_STATE_POTENTIALLY_ACTIVE:
1945 if (force)
1946 break;
1947 (void) fprintf(stderr, gettext(
1948 "use '-f' to override the following error:\n"
1949 "%s is a member of potentially active pool \"%s\"\n"),
1950 vdev, name);
1951 ret = 1;
1952 goto errout;
1953
1954 case POOL_STATE_DESTROYED:
1955 /* inuse should never be set for a destroyed pool */
1956 assert(0);
1957 break;
1958 }
1959
1960 wipe_label:
1961 ret = zpool_clear_label(fd);
1962 if (ret != 0) {
1963 (void) fprintf(stderr,
1964 gettext("failed to clear label for %s\n"), vdev);
1965 }
1966
1967 errout:
1968 free(name);
1969 (void) close(fd);
1970
1971 return (ret);
1972 }
1973
1974 /*
1975 * zpool create [-fnd] [-o property=value] ...
1976 * [-O file-system-property=value] ...
1977 * [-R root] [-m mountpoint] <pool> <dev> ...
1978 *
1979 * -f Force creation, even if devices appear in use
1980 * -n Do not create the pool, but display the resulting layout if it
1981 * were to be created.
1982 * -R Create a pool under an alternate root
1983 * -m Set default mountpoint for the root dataset. By default it's
1984 * '/<pool>'
1985 * -o Set property=value.
1986 * -o Set feature@feature=enabled|disabled.
1987 * -d Don't automatically enable all supported pool features
1988 * (individual features can be enabled with -o).
1989 * -O Set fsproperty=value in the pool's root file system
1990 *
1991 * Creates the named pool according to the given vdev specification. The
1992 * bulk of the vdev processing is done in make_root_vdev() in zpool_vdev.c.
1993 * Once we get the nvlist back from make_root_vdev(), we either print out the
1994 * contents (if '-n' was specified), or pass it to libzfs to do the creation.
1995 */
1996 int
zpool_do_create(int argc,char ** argv)1997 zpool_do_create(int argc, char **argv)
1998 {
1999 boolean_t force = B_FALSE;
2000 boolean_t dryrun = B_FALSE;
2001 boolean_t enable_pool_features = B_TRUE;
2002
2003 int c;
2004 nvlist_t *nvroot = NULL;
2005 char *poolname;
2006 char *tname = NULL;
2007 int ret = 1;
2008 char *altroot = NULL;
2009 char *compat = NULL;
2010 char *mountpoint = NULL;
2011 nvlist_t *fsprops = NULL;
2012 nvlist_t *props = NULL;
2013 char *propval;
2014
2015 /* check options */
2016 while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
2017 switch (c) {
2018 case 'f':
2019 force = B_TRUE;
2020 break;
2021 case 'n':
2022 dryrun = B_TRUE;
2023 break;
2024 case 'd':
2025 enable_pool_features = B_FALSE;
2026 break;
2027 case 'R':
2028 altroot = optarg;
2029 if (add_prop_list(zpool_prop_to_name(
2030 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
2031 goto errout;
2032 if (add_prop_list_default(zpool_prop_to_name(
2033 ZPOOL_PROP_CACHEFILE), "none", &props))
2034 goto errout;
2035 break;
2036 case 'm':
2037 /* Equivalent to -O mountpoint=optarg */
2038 mountpoint = optarg;
2039 break;
2040 case 'o':
2041 if ((propval = strchr(optarg, '=')) == NULL) {
2042 (void) fprintf(stderr, gettext("missing "
2043 "'=' for -o option\n"));
2044 goto errout;
2045 }
2046 *propval = '\0';
2047 propval++;
2048
2049 if (add_prop_list(optarg, propval, &props, B_TRUE))
2050 goto errout;
2051
2052 /*
2053 * If the user is creating a pool that doesn't support
2054 * feature flags, don't enable any features.
2055 */
2056 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
2057 char *end;
2058 u_longlong_t ver;
2059
2060 ver = strtoull(propval, &end, 0);
2061 if (*end == '\0' &&
2062 ver < SPA_VERSION_FEATURES) {
2063 enable_pool_features = B_FALSE;
2064 }
2065 }
2066 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
2067 altroot = propval;
2068 if (zpool_name_to_prop(optarg) ==
2069 ZPOOL_PROP_COMPATIBILITY)
2070 compat = propval;
2071 break;
2072 case 'O':
2073 if ((propval = strchr(optarg, '=')) == NULL) {
2074 (void) fprintf(stderr, gettext("missing "
2075 "'=' for -O option\n"));
2076 goto errout;
2077 }
2078 *propval = '\0';
2079 propval++;
2080
2081 /*
2082 * Mountpoints are checked and then added later.
2083 * Uniquely among properties, they can be specified
2084 * more than once, to avoid conflict with -m.
2085 */
2086 if (0 == strcmp(optarg,
2087 zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
2088 mountpoint = propval;
2089 } else if (add_prop_list(optarg, propval, &fsprops,
2090 B_FALSE)) {
2091 goto errout;
2092 }
2093 break;
2094 case 't':
2095 /*
2096 * Sanity check temporary pool name.
2097 */
2098 if (strchr(optarg, '/') != NULL) {
2099 (void) fprintf(stderr, gettext("cannot create "
2100 "'%s': invalid character '/' in temporary "
2101 "name\n"), optarg);
2102 (void) fprintf(stderr, gettext("use 'zfs "
2103 "create' to create a dataset\n"));
2104 goto errout;
2105 }
2106
2107 if (add_prop_list(zpool_prop_to_name(
2108 ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
2109 goto errout;
2110 if (add_prop_list_default(zpool_prop_to_name(
2111 ZPOOL_PROP_CACHEFILE), "none", &props))
2112 goto errout;
2113 tname = optarg;
2114 break;
2115 case ':':
2116 (void) fprintf(stderr, gettext("missing argument for "
2117 "'%c' option\n"), optopt);
2118 goto badusage;
2119 case '?':
2120 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2121 optopt);
2122 goto badusage;
2123 }
2124 }
2125
2126 argc -= optind;
2127 argv += optind;
2128
2129 /* get pool name and check number of arguments */
2130 if (argc < 1) {
2131 (void) fprintf(stderr, gettext("missing pool name argument\n"));
2132 goto badusage;
2133 }
2134 if (argc < 2) {
2135 (void) fprintf(stderr, gettext("missing vdev specification\n"));
2136 goto badusage;
2137 }
2138
2139 poolname = argv[0];
2140
2141 /*
2142 * As a special case, check for use of '/' in the name, and direct the
2143 * user to use 'zfs create' instead.
2144 */
2145 if (strchr(poolname, '/') != NULL) {
2146 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
2147 "character '/' in pool name\n"), poolname);
2148 (void) fprintf(stderr, gettext("use 'zfs create' to "
2149 "create a dataset\n"));
2150 goto errout;
2151 }
2152
2153 /* pass off to make_root_vdev for bulk processing */
2154 nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
2155 argc - 1, argv + 1);
2156 if (nvroot == NULL)
2157 goto errout;
2158
2159 /* make_root_vdev() allows 0 toplevel children if there are spares */
2160 if (!zfs_allocatable_devs(nvroot)) {
2161 (void) fprintf(stderr, gettext("invalid vdev "
2162 "specification: at least one toplevel vdev must be "
2163 "specified\n"));
2164 goto errout;
2165 }
2166
2167 if (altroot != NULL && altroot[0] != '/') {
2168 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
2169 "must be an absolute path\n"), altroot);
2170 goto errout;
2171 }
2172
2173 /*
2174 * Check the validity of the mountpoint and direct the user to use the
2175 * '-m' mountpoint option if it looks like its in use.
2176 */
2177 if (mountpoint == NULL ||
2178 (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
2179 strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
2180 char buf[MAXPATHLEN];
2181 DIR *dirp;
2182
2183 if (mountpoint && mountpoint[0] != '/') {
2184 (void) fprintf(stderr, gettext("invalid mountpoint "
2185 "'%s': must be an absolute path, 'legacy', or "
2186 "'none'\n"), mountpoint);
2187 goto errout;
2188 }
2189
2190 if (mountpoint == NULL) {
2191 if (altroot != NULL)
2192 (void) snprintf(buf, sizeof (buf), "%s/%s",
2193 altroot, poolname);
2194 else
2195 (void) snprintf(buf, sizeof (buf), "/%s",
2196 poolname);
2197 } else {
2198 if (altroot != NULL)
2199 (void) snprintf(buf, sizeof (buf), "%s%s",
2200 altroot, mountpoint);
2201 else
2202 (void) snprintf(buf, sizeof (buf), "%s",
2203 mountpoint);
2204 }
2205
2206 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
2207 (void) fprintf(stderr, gettext("mountpoint '%s' : "
2208 "%s\n"), buf, strerror(errno));
2209 (void) fprintf(stderr, gettext("use '-m' "
2210 "option to provide a different default\n"));
2211 goto errout;
2212 } else if (dirp) {
2213 int count = 0;
2214
2215 while (count < 3 && readdir(dirp) != NULL)
2216 count++;
2217 (void) closedir(dirp);
2218
2219 if (count > 2) {
2220 (void) fprintf(stderr, gettext("mountpoint "
2221 "'%s' exists and is not empty\n"), buf);
2222 (void) fprintf(stderr, gettext("use '-m' "
2223 "option to provide a "
2224 "different default\n"));
2225 goto errout;
2226 }
2227 }
2228 }
2229
2230 /*
2231 * Now that the mountpoint's validity has been checked, ensure that
2232 * the property is set appropriately prior to creating the pool.
2233 */
2234 if (mountpoint != NULL) {
2235 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
2236 mountpoint, &fsprops, B_FALSE);
2237 if (ret != 0)
2238 goto errout;
2239 }
2240
2241 ret = 1;
2242 if (dryrun) {
2243 /*
2244 * For a dry run invocation, print out a basic message and run
2245 * through all the vdevs in the list and print out in an
2246 * appropriate hierarchy.
2247 */
2248 (void) printf(gettext("would create '%s' with the "
2249 "following layout:\n\n"), poolname);
2250
2251 print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
2252 print_vdev_tree(NULL, "dedup", nvroot, 0,
2253 VDEV_ALLOC_BIAS_DEDUP, 0);
2254 print_vdev_tree(NULL, "special", nvroot, 0,
2255 VDEV_ALLOC_BIAS_SPECIAL, 0);
2256 print_vdev_tree(NULL, "logs", nvroot, 0,
2257 VDEV_ALLOC_BIAS_LOG, 0);
2258 print_cache_list(nvroot, 0);
2259 print_spare_list(nvroot, 0);
2260
2261 ret = 0;
2262 } else {
2263 /*
2264 * Load in feature set.
2265 * Note: if compatibility property not given, we'll have
2266 * NULL, which means 'all features'.
2267 */
2268 boolean_t requested_features[SPA_FEATURES];
2269 if (zpool_do_load_compat(compat, requested_features) !=
2270 ZPOOL_COMPATIBILITY_OK)
2271 goto errout;
2272
2273 /*
2274 * props contains list of features to enable.
2275 * For each feature:
2276 * - remove it if feature@name=disabled
2277 * - leave it there if feature@name=enabled
2278 * - add it if:
2279 * - enable_pool_features (ie: no '-d' or '-o version')
2280 * - it's supported by the kernel module
2281 * - it's in the requested feature set
2282 * - warn if it's enabled but not in compat
2283 */
2284 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
2285 char propname[MAXPATHLEN];
2286 const char *propval;
2287 zfeature_info_t *feat = &spa_feature_table[i];
2288
2289 (void) snprintf(propname, sizeof (propname),
2290 "feature@%s", feat->fi_uname);
2291
2292 if (!nvlist_lookup_string(props, propname, &propval)) {
2293 if (strcmp(propval,
2294 ZFS_FEATURE_DISABLED) == 0) {
2295 (void) nvlist_remove_all(props,
2296 propname);
2297 } else if (strcmp(propval,
2298 ZFS_FEATURE_ENABLED) == 0 &&
2299 !requested_features[i]) {
2300 (void) fprintf(stderr, gettext(
2301 "Warning: feature \"%s\" enabled "
2302 "but is not in specified "
2303 "'compatibility' feature set.\n"),
2304 feat->fi_uname);
2305 }
2306 } else if (
2307 enable_pool_features &&
2308 feat->fi_zfs_mod_supported &&
2309 requested_features[i]) {
2310 ret = add_prop_list(propname,
2311 ZFS_FEATURE_ENABLED, &props, B_TRUE);
2312 if (ret != 0)
2313 goto errout;
2314 }
2315 }
2316
2317 ret = 1;
2318 if (zpool_create(g_zfs, poolname,
2319 nvroot, props, fsprops) == 0) {
2320 zfs_handle_t *pool = zfs_open(g_zfs,
2321 tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
2322 if (pool != NULL) {
2323 if (zfs_mount(pool, NULL, 0) == 0) {
2324 ret = zfs_share(pool, NULL);
2325 zfs_commit_shares(NULL);
2326 }
2327 zfs_close(pool);
2328 }
2329 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
2330 (void) fprintf(stderr, gettext("pool name may have "
2331 "been omitted\n"));
2332 }
2333 }
2334
2335 errout:
2336 nvlist_free(nvroot);
2337 nvlist_free(fsprops);
2338 nvlist_free(props);
2339 return (ret);
2340 badusage:
2341 nvlist_free(fsprops);
2342 nvlist_free(props);
2343 usage(B_FALSE);
2344 return (2);
2345 }
2346
2347 /*
2348 * zpool destroy <pool>
2349 *
2350 * -f Forcefully unmount any datasets
2351 *
2352 * Destroy the given pool. Automatically unmounts any datasets in the pool.
2353 */
2354 int
zpool_do_destroy(int argc,char ** argv)2355 zpool_do_destroy(int argc, char **argv)
2356 {
2357 boolean_t force = B_FALSE;
2358 int c;
2359 char *pool;
2360 zpool_handle_t *zhp;
2361 int ret;
2362
2363 /* check options */
2364 while ((c = getopt(argc, argv, "f")) != -1) {
2365 switch (c) {
2366 case 'f':
2367 force = B_TRUE;
2368 break;
2369 case '?':
2370 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2371 optopt);
2372 usage(B_FALSE);
2373 }
2374 }
2375
2376 argc -= optind;
2377 argv += optind;
2378
2379 /* check arguments */
2380 if (argc < 1) {
2381 (void) fprintf(stderr, gettext("missing pool argument\n"));
2382 usage(B_FALSE);
2383 }
2384 if (argc > 1) {
2385 (void) fprintf(stderr, gettext("too many arguments\n"));
2386 usage(B_FALSE);
2387 }
2388
2389 pool = argv[0];
2390
2391 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
2392 /*
2393 * As a special case, check for use of '/' in the name, and
2394 * direct the user to use 'zfs destroy' instead.
2395 */
2396 if (strchr(pool, '/') != NULL)
2397 (void) fprintf(stderr, gettext("use 'zfs destroy' to "
2398 "destroy a dataset\n"));
2399 return (1);
2400 }
2401
2402 if (zpool_disable_datasets(zhp, force) != 0) {
2403 (void) fprintf(stderr, gettext("could not destroy '%s': "
2404 "could not unmount datasets\n"), zpool_get_name(zhp));
2405 zpool_close(zhp);
2406 return (1);
2407 }
2408
2409 /* The history must be logged as part of the export */
2410 log_history = B_FALSE;
2411
2412 ret = (zpool_destroy(zhp, history_str) != 0);
2413
2414 zpool_close(zhp);
2415
2416 return (ret);
2417 }
2418
2419 typedef struct export_cbdata {
2420 taskq_t *taskq;
2421 pthread_mutex_t mnttab_lock;
2422 boolean_t force;
2423 boolean_t hardforce;
2424 int retval;
2425 } export_cbdata_t;
2426
2427
2428 typedef struct {
2429 char *aea_poolname;
2430 export_cbdata_t *aea_cbdata;
2431 } async_export_args_t;
2432
2433 /*
2434 * Export one pool
2435 */
2436 static int
zpool_export_one(zpool_handle_t * zhp,void * data)2437 zpool_export_one(zpool_handle_t *zhp, void *data)
2438 {
2439 export_cbdata_t *cb = data;
2440
2441 /*
2442 * zpool_disable_datasets() is not thread-safe for mnttab access.
2443 * So we serialize access here for 'zpool export -a' parallel case.
2444 */
2445 if (cb->taskq != NULL)
2446 (void) pthread_mutex_lock(&cb->mnttab_lock);
2447
2448 int retval = zpool_disable_datasets(zhp, cb->force);
2449
2450 if (cb->taskq != NULL)
2451 (void) pthread_mutex_unlock(&cb->mnttab_lock);
2452
2453 if (retval)
2454 return (1);
2455
2456 if (cb->hardforce) {
2457 if (zpool_export_force(zhp, history_str) != 0)
2458 return (1);
2459 } else if (zpool_export(zhp, cb->force, history_str) != 0) {
2460 return (1);
2461 }
2462
2463 return (0);
2464 }
2465
2466 /*
2467 * Asynchronous export request
2468 */
2469 static void
zpool_export_task(void * arg)2470 zpool_export_task(void *arg)
2471 {
2472 async_export_args_t *aea = arg;
2473
2474 zpool_handle_t *zhp = zpool_open(g_zfs, aea->aea_poolname);
2475 if (zhp != NULL) {
2476 int ret = zpool_export_one(zhp, aea->aea_cbdata);
2477 if (ret != 0)
2478 aea->aea_cbdata->retval = ret;
2479 zpool_close(zhp);
2480 } else {
2481 aea->aea_cbdata->retval = 1;
2482 }
2483
2484 free(aea->aea_poolname);
2485 free(aea);
2486 }
2487
2488 /*
2489 * Process an export request in parallel
2490 */
2491 static int
zpool_export_one_async(zpool_handle_t * zhp,void * data)2492 zpool_export_one_async(zpool_handle_t *zhp, void *data)
2493 {
2494 taskq_t *tq = ((export_cbdata_t *)data)->taskq;
2495 async_export_args_t *aea = safe_malloc(sizeof (async_export_args_t));
2496
2497 /* save pool name since zhp will go out of scope */
2498 aea->aea_poolname = strdup(zpool_get_name(zhp));
2499 aea->aea_cbdata = data;
2500
2501 /* ship off actual export to another thread */
2502 if (taskq_dispatch(tq, zpool_export_task, (void *)aea,
2503 TQ_SLEEP) == TASKQID_INVALID)
2504 return (errno); /* unlikely */
2505 else
2506 return (0);
2507 }
2508
2509 /*
2510 * zpool export [-f] <pool> ...
2511 *
2512 * -a Export all pools
2513 * -f Forcefully unmount datasets
2514 *
2515 * Export the given pools. By default, the command will attempt to cleanly
2516 * unmount any active datasets within the pool. If the '-f' flag is specified,
2517 * then the datasets will be forcefully unmounted.
2518 */
2519 int
zpool_do_export(int argc,char ** argv)2520 zpool_do_export(int argc, char **argv)
2521 {
2522 export_cbdata_t cb;
2523 boolean_t do_all = B_FALSE;
2524 boolean_t force = B_FALSE;
2525 boolean_t hardforce = B_FALSE;
2526 int c, ret;
2527
2528 /* check options */
2529 while ((c = getopt(argc, argv, "afF")) != -1) {
2530 switch (c) {
2531 case 'a':
2532 do_all = B_TRUE;
2533 break;
2534 case 'f':
2535 force = B_TRUE;
2536 break;
2537 case 'F':
2538 hardforce = B_TRUE;
2539 break;
2540 case '?':
2541 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2542 optopt);
2543 usage(B_FALSE);
2544 }
2545 }
2546
2547 cb.force = force;
2548 cb.hardforce = hardforce;
2549 cb.taskq = NULL;
2550 cb.retval = 0;
2551 argc -= optind;
2552 argv += optind;
2553
2554 /* The history will be logged as part of the export itself */
2555 log_history = B_FALSE;
2556
2557 if (do_all) {
2558 if (argc != 0) {
2559 (void) fprintf(stderr, gettext("too many arguments\n"));
2560 usage(B_FALSE);
2561 }
2562
2563 cb.taskq = taskq_create("zpool_export",
2564 5 * sysconf(_SC_NPROCESSORS_ONLN), minclsyspri, 1, INT_MAX,
2565 TASKQ_DYNAMIC);
2566 (void) pthread_mutex_init(&cb.mnttab_lock, NULL);
2567
2568 /* Asynchronously call zpool_export_one using thread pool */
2569 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2570 B_FALSE, zpool_export_one_async, &cb);
2571
2572 taskq_wait(cb.taskq);
2573 taskq_destroy(cb.taskq);
2574 (void) pthread_mutex_destroy(&cb.mnttab_lock);
2575
2576 return (ret | cb.retval);
2577 }
2578
2579 /* check arguments */
2580 if (argc < 1) {
2581 (void) fprintf(stderr, gettext("missing pool argument\n"));
2582 usage(B_FALSE);
2583 }
2584
2585 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2586 B_FALSE, zpool_export_one, &cb);
2587
2588 return (ret);
2589 }
2590
2591 /*
2592 * Given a vdev configuration, determine the maximum width needed for the device
2593 * name column.
2594 */
2595 static int
max_width(zpool_handle_t * zhp,nvlist_t * nv,int depth,int max,int name_flags)2596 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
2597 int name_flags)
2598 {
2599 static const char *const subtypes[] =
2600 {ZPOOL_CONFIG_SPARES, ZPOOL_CONFIG_L2CACHE, ZPOOL_CONFIG_CHILDREN};
2601
2602 char *name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
2603 max = MAX(strlen(name) + depth, max);
2604 free(name);
2605
2606 nvlist_t **child;
2607 uint_t children;
2608 for (size_t i = 0; i < ARRAY_SIZE(subtypes); ++i)
2609 if (nvlist_lookup_nvlist_array(nv, subtypes[i],
2610 &child, &children) == 0)
2611 for (uint_t c = 0; c < children; ++c)
2612 max = MAX(max_width(zhp, child[c], depth + 2,
2613 max, name_flags), max);
2614
2615 return (max);
2616 }
2617
2618 typedef struct status_cbdata {
2619 int cb_count;
2620 int cb_name_flags;
2621 int cb_namewidth;
2622 int cb_verbosity;
2623 boolean_t cb_allpools;
2624 boolean_t cb_literal;
2625 boolean_t cb_explain;
2626 boolean_t cb_first;
2627 boolean_t cb_dedup_stats;
2628 boolean_t cb_print_unhealthy;
2629 boolean_t cb_print_status;
2630 boolean_t cb_print_slow_ios;
2631 boolean_t cb_print_dio_verify;
2632 boolean_t cb_print_vdev_init;
2633 boolean_t cb_print_vdev_trim;
2634 vdev_cmd_data_list_t *vcdl;
2635 boolean_t cb_print_power;
2636 boolean_t cb_json;
2637 boolean_t cb_flat_vdevs;
2638 nvlist_t *cb_jsobj;
2639 boolean_t cb_json_as_int;
2640 boolean_t cb_json_pool_key_guid;
2641 } status_cbdata_t;
2642
2643 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
2644 static boolean_t
is_blank_str(const char * str)2645 is_blank_str(const char *str)
2646 {
2647 for (; str != NULL && *str != '\0'; ++str)
2648 if (!isblank(*str))
2649 return (B_FALSE);
2650 return (B_TRUE);
2651 }
2652
2653 static void
zpool_nvlist_cmd(vdev_cmd_data_list_t * vcdl,const char * pool,const char * path,nvlist_t * item)2654 zpool_nvlist_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path,
2655 nvlist_t *item)
2656 {
2657 vdev_cmd_data_t *data;
2658 int i, j, k = 1;
2659 char tmp[256];
2660 const char *val;
2661
2662 for (i = 0; i < vcdl->count; i++) {
2663 if ((strcmp(vcdl->data[i].path, path) != 0) ||
2664 (strcmp(vcdl->data[i].pool, pool) != 0))
2665 continue;
2666
2667 data = &vcdl->data[i];
2668 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2669 val = NULL;
2670 for (int k = 0; k < data->cols_cnt; k++) {
2671 if (strcmp(data->cols[k],
2672 vcdl->uniq_cols[j]) == 0) {
2673 val = data->lines[k];
2674 break;
2675 }
2676 }
2677 if (val == NULL || is_blank_str(val))
2678 val = "-";
2679 fnvlist_add_string(item, vcdl->uniq_cols[j], val);
2680 }
2681
2682 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2683 if (data->lines[j]) {
2684 (void) snprintf(tmp, 256, "extra_%d", k++);
2685 fnvlist_add_string(item, tmp,
2686 data->lines[j]);
2687 }
2688 }
2689 break;
2690 }
2691 }
2692
2693 /* Print command output lines for specific vdev in a specific pool */
2694 static void
zpool_print_cmd(vdev_cmd_data_list_t * vcdl,const char * pool,const char * path)2695 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path)
2696 {
2697 vdev_cmd_data_t *data;
2698 int i, j;
2699 const char *val;
2700
2701 for (i = 0; i < vcdl->count; i++) {
2702 if ((strcmp(vcdl->data[i].path, path) != 0) ||
2703 (strcmp(vcdl->data[i].pool, pool) != 0)) {
2704 /* Not the vdev we're looking for */
2705 continue;
2706 }
2707
2708 data = &vcdl->data[i];
2709 /* Print out all the output values for this vdev */
2710 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2711 val = NULL;
2712 /* Does this vdev have values for this column? */
2713 for (int k = 0; k < data->cols_cnt; k++) {
2714 if (strcmp(data->cols[k],
2715 vcdl->uniq_cols[j]) == 0) {
2716 /* yes it does, record the value */
2717 val = data->lines[k];
2718 break;
2719 }
2720 }
2721 /*
2722 * Mark empty values with dashes to make output
2723 * awk-able.
2724 */
2725 if (val == NULL || is_blank_str(val))
2726 val = "-";
2727
2728 printf("%*s", vcdl->uniq_cols_width[j], val);
2729 if (j < vcdl->uniq_cols_cnt - 1)
2730 (void) fputs(" ", stdout);
2731 }
2732
2733 /* Print out any values that aren't in a column at the end */
2734 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2735 /* Did we have any columns? If so print a spacer. */
2736 if (vcdl->uniq_cols_cnt > 0)
2737 (void) fputs(" ", stdout);
2738
2739 val = data->lines[j];
2740 (void) fputs(val ?: "", stdout);
2741 }
2742 break;
2743 }
2744 }
2745
2746 /*
2747 * Print vdev initialization status for leaves
2748 */
2749 static void
print_status_initialize(vdev_stat_t * vs,boolean_t verbose)2750 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
2751 {
2752 if (verbose) {
2753 if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
2754 vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
2755 vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
2756 !vs->vs_scan_removing) {
2757 char zbuf[1024];
2758 char tbuf[256];
2759
2760 time_t t = vs->vs_initialize_action_time;
2761 int initialize_pct = 100;
2762 if (vs->vs_initialize_state !=
2763 VDEV_INITIALIZE_COMPLETE) {
2764 initialize_pct = (vs->vs_initialize_bytes_done *
2765 100 / (vs->vs_initialize_bytes_est + 1));
2766 }
2767
2768 (void) ctime_r(&t, tbuf);
2769 tbuf[24] = 0;
2770
2771 switch (vs->vs_initialize_state) {
2772 case VDEV_INITIALIZE_SUSPENDED:
2773 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2774 gettext("suspended, started at"), tbuf);
2775 break;
2776 case VDEV_INITIALIZE_ACTIVE:
2777 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2778 gettext("started at"), tbuf);
2779 break;
2780 case VDEV_INITIALIZE_COMPLETE:
2781 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2782 gettext("completed at"), tbuf);
2783 break;
2784 }
2785
2786 (void) printf(gettext(" (%d%% initialized%s)"),
2787 initialize_pct, zbuf);
2788 } else {
2789 (void) printf(gettext(" (uninitialized)"));
2790 }
2791 } else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
2792 (void) printf(gettext(" (initializing)"));
2793 }
2794 }
2795
2796 /*
2797 * Print vdev TRIM status for leaves
2798 */
2799 static void
print_status_trim(vdev_stat_t * vs,boolean_t verbose)2800 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
2801 {
2802 if (verbose) {
2803 if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
2804 vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
2805 vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
2806 !vs->vs_scan_removing) {
2807 char zbuf[1024];
2808 char tbuf[256];
2809
2810 time_t t = vs->vs_trim_action_time;
2811 int trim_pct = 100;
2812 if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
2813 trim_pct = (vs->vs_trim_bytes_done *
2814 100 / (vs->vs_trim_bytes_est + 1));
2815 }
2816
2817 (void) ctime_r(&t, tbuf);
2818 tbuf[24] = 0;
2819
2820 switch (vs->vs_trim_state) {
2821 case VDEV_TRIM_SUSPENDED:
2822 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2823 gettext("suspended, started at"), tbuf);
2824 break;
2825 case VDEV_TRIM_ACTIVE:
2826 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2827 gettext("started at"), tbuf);
2828 break;
2829 case VDEV_TRIM_COMPLETE:
2830 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2831 gettext("completed at"), tbuf);
2832 break;
2833 }
2834
2835 (void) printf(gettext(" (%d%% trimmed%s)"),
2836 trim_pct, zbuf);
2837 } else if (vs->vs_trim_notsup) {
2838 (void) printf(gettext(" (trim unsupported)"));
2839 } else {
2840 (void) printf(gettext(" (untrimmed)"));
2841 }
2842 } else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
2843 (void) printf(gettext(" (trimming)"));
2844 }
2845 }
2846
2847 /*
2848 * Return the color associated with a health string. This includes returning
2849 * NULL for no color change.
2850 */
2851 static const char *
health_str_to_color(const char * health)2852 health_str_to_color(const char *health)
2853 {
2854 if (strcmp(health, gettext("FAULTED")) == 0 ||
2855 strcmp(health, gettext("SUSPENDED")) == 0 ||
2856 strcmp(health, gettext("UNAVAIL")) == 0) {
2857 return (ANSI_RED);
2858 }
2859
2860 if (strcmp(health, gettext("OFFLINE")) == 0 ||
2861 strcmp(health, gettext("DEGRADED")) == 0 ||
2862 strcmp(health, gettext("REMOVED")) == 0) {
2863 return (ANSI_YELLOW);
2864 }
2865
2866 return (NULL);
2867 }
2868
2869 /*
2870 * Called for each leaf vdev. Returns 0 if the vdev is healthy.
2871 * A vdev is unhealthy if any of the following are true:
2872 * 1) there are read, write, or checksum errors,
2873 * 2) its state is not ONLINE, or
2874 * 3) slow IO reporting was requested (-s) and there are slow IOs.
2875 */
2876 static int
vdev_health_check_cb(void * hdl_data,nvlist_t * nv,void * data)2877 vdev_health_check_cb(void *hdl_data, nvlist_t *nv, void *data)
2878 {
2879 status_cbdata_t *cb = data;
2880 vdev_stat_t *vs;
2881 uint_t vsc;
2882 (void) hdl_data;
2883
2884 if (nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2885 (uint64_t **)&vs, &vsc) != 0)
2886 return (1);
2887
2888 if (vs->vs_checksum_errors || vs->vs_read_errors ||
2889 vs->vs_write_errors || vs->vs_state != VDEV_STATE_HEALTHY)
2890 return (1);
2891
2892 if (cb->cb_print_slow_ios && vs->vs_slow_ios)
2893 return (1);
2894
2895 return (0);
2896 }
2897
2898 /*
2899 * Print out configuration state as requested by status_callback.
2900 */
2901 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)2902 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
2903 nvlist_t *nv, int depth, boolean_t isspare, vdev_rebuild_stat_t *vrs)
2904 {
2905 nvlist_t **child, *root;
2906 uint_t c, i, vsc, children;
2907 pool_scan_stat_t *ps = NULL;
2908 vdev_stat_t *vs;
2909 char rbuf[6], wbuf[6], cbuf[6], dbuf[6];
2910 char *vname;
2911 uint64_t notpresent;
2912 spare_cbdata_t spare_cb;
2913 const char *state;
2914 const char *type;
2915 const char *path = NULL;
2916 const char *rcolor = NULL, *wcolor = NULL, *ccolor = NULL,
2917 *scolor = NULL;
2918
2919 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2920 &child, &children) != 0)
2921 children = 0;
2922
2923 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2924 (uint64_t **)&vs, &vsc) == 0);
2925
2926 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2927
2928 if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2929 return;
2930
2931 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2932
2933 if (isspare) {
2934 /*
2935 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
2936 * online drives.
2937 */
2938 if (vs->vs_aux == VDEV_AUX_SPARED)
2939 state = gettext("INUSE");
2940 else if (vs->vs_state == VDEV_STATE_HEALTHY)
2941 state = gettext("AVAIL");
2942 }
2943
2944 /*
2945 * If '-e' is specified then top-level vdevs and their children
2946 * can be pruned if all of their leaves are healthy.
2947 */
2948 if (cb->cb_print_unhealthy && depth > 0 &&
2949 for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
2950 return;
2951 }
2952
2953 (void) printf_color(health_str_to_color(state),
2954 "\t%*s%-*s %-8s", depth, "", cb->cb_namewidth - depth,
2955 name, state);
2956
2957 if (!isspare) {
2958 if (vs->vs_read_errors)
2959 rcolor = ANSI_RED;
2960
2961 if (vs->vs_write_errors)
2962 wcolor = ANSI_RED;
2963
2964 if (vs->vs_checksum_errors)
2965 ccolor = ANSI_RED;
2966
2967 if (vs->vs_slow_ios)
2968 scolor = ANSI_BLUE;
2969
2970 if (cb->cb_literal) {
2971 (void) fputc(' ', stdout);
2972 (void) printf_color(rcolor, "%5llu",
2973 (u_longlong_t)vs->vs_read_errors);
2974 (void) fputc(' ', stdout);
2975 (void) printf_color(wcolor, "%5llu",
2976 (u_longlong_t)vs->vs_write_errors);
2977 (void) fputc(' ', stdout);
2978 (void) printf_color(ccolor, "%5llu",
2979 (u_longlong_t)vs->vs_checksum_errors);
2980 } else {
2981 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
2982 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
2983 zfs_nicenum(vs->vs_checksum_errors, cbuf,
2984 sizeof (cbuf));
2985 (void) fputc(' ', stdout);
2986 (void) printf_color(rcolor, "%5s", rbuf);
2987 (void) fputc(' ', stdout);
2988 (void) printf_color(wcolor, "%5s", wbuf);
2989 (void) fputc(' ', stdout);
2990 (void) printf_color(ccolor, "%5s", cbuf);
2991 }
2992 if (cb->cb_print_slow_ios) {
2993 if (children == 0) {
2994 /* Only leafs vdevs have slow IOs */
2995 zfs_nicenum(vs->vs_slow_ios, rbuf,
2996 sizeof (rbuf));
2997 } else {
2998 (void) snprintf(rbuf, sizeof (rbuf), "-");
2999 }
3000
3001 if (cb->cb_literal)
3002 (void) printf_color(scolor, " %5llu",
3003 (u_longlong_t)vs->vs_slow_ios);
3004 else
3005 (void) printf_color(scolor, " %5s", rbuf);
3006 }
3007 if (cb->cb_print_power) {
3008 if (children == 0) {
3009 /* Only leaf vdevs have physical slots */
3010 switch (zpool_power_current_state(zhp, (char *)
3011 fnvlist_lookup_string(nv,
3012 ZPOOL_CONFIG_PATH))) {
3013 case 0:
3014 (void) printf_color(ANSI_RED, " %5s",
3015 gettext("off"));
3016 break;
3017 case 1:
3018 printf(" %5s", gettext("on"));
3019 break;
3020 default:
3021 printf(" %5s", "-");
3022 }
3023 } else {
3024 printf(" %5s", "-");
3025 }
3026 }
3027 if (VDEV_STAT_VALID(vs_dio_verify_errors, vsc) &&
3028 cb->cb_print_dio_verify) {
3029 zfs_nicenum(vs->vs_dio_verify_errors, dbuf,
3030 sizeof (dbuf));
3031
3032 if (cb->cb_literal)
3033 printf(" %5llu",
3034 (u_longlong_t)vs->vs_dio_verify_errors);
3035 else
3036 printf(" %5s", dbuf);
3037 }
3038 }
3039
3040 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
3041 ¬present) == 0) {
3042 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
3043 (void) printf(" %s %s", gettext("was"), path);
3044 } else if (vs->vs_aux != 0) {
3045 (void) printf(" ");
3046 color_start(ANSI_RED);
3047 switch (vs->vs_aux) {
3048 case VDEV_AUX_OPEN_FAILED:
3049 (void) printf(gettext("cannot open"));
3050 break;
3051
3052 case VDEV_AUX_BAD_GUID_SUM:
3053 (void) printf(gettext("missing device"));
3054 break;
3055
3056 case VDEV_AUX_NO_REPLICAS:
3057 (void) printf(gettext("insufficient replicas"));
3058 break;
3059
3060 case VDEV_AUX_VERSION_NEWER:
3061 (void) printf(gettext("newer version"));
3062 break;
3063
3064 case VDEV_AUX_UNSUP_FEAT:
3065 (void) printf(gettext("unsupported feature(s)"));
3066 break;
3067
3068 case VDEV_AUX_ASHIFT_TOO_BIG:
3069 (void) printf(gettext("unsupported minimum blocksize"));
3070 break;
3071
3072 case VDEV_AUX_SPARED:
3073 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3074 &spare_cb.cb_guid) == 0);
3075 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
3076 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
3077 zpool_get_name(zhp)) == 0)
3078 (void) printf(gettext("currently in "
3079 "use"));
3080 else
3081 (void) printf(gettext("in use by "
3082 "pool '%s'"),
3083 zpool_get_name(spare_cb.cb_zhp));
3084 zpool_close(spare_cb.cb_zhp);
3085 } else {
3086 (void) printf(gettext("currently in use"));
3087 }
3088 break;
3089
3090 case VDEV_AUX_ERR_EXCEEDED:
3091 if (vs->vs_read_errors + vs->vs_write_errors +
3092 vs->vs_checksum_errors == 0 && children == 0 &&
3093 vs->vs_slow_ios > 0) {
3094 (void) printf(gettext("too many slow I/Os"));
3095 } else {
3096 (void) printf(gettext("too many errors"));
3097 }
3098 break;
3099
3100 case VDEV_AUX_IO_FAILURE:
3101 (void) printf(gettext("experienced I/O failures"));
3102 break;
3103
3104 case VDEV_AUX_BAD_LOG:
3105 (void) printf(gettext("bad intent log"));
3106 break;
3107
3108 case VDEV_AUX_EXTERNAL:
3109 (void) printf(gettext("external device fault"));
3110 break;
3111
3112 case VDEV_AUX_SPLIT_POOL:
3113 (void) printf(gettext("split into new pool"));
3114 break;
3115
3116 case VDEV_AUX_ACTIVE:
3117 (void) printf(gettext("currently in use"));
3118 break;
3119
3120 case VDEV_AUX_CHILDREN_OFFLINE:
3121 (void) printf(gettext("all children offline"));
3122 break;
3123
3124 case VDEV_AUX_BAD_LABEL:
3125 (void) printf(gettext("invalid label"));
3126 break;
3127
3128 default:
3129 (void) printf(gettext("corrupted data"));
3130 break;
3131 }
3132 color_end();
3133 } else if (children == 0 && !isspare &&
3134 getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
3135 VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
3136 vs->vs_configured_ashift < vs->vs_physical_ashift) {
3137 (void) printf(
3138 gettext(" block size: %dB configured, %dB native"),
3139 1 << vs->vs_configured_ashift, 1 << vs->vs_physical_ashift);
3140 }
3141
3142 if (vs->vs_scan_removing != 0) {
3143 (void) printf(gettext(" (removing)"));
3144 } else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
3145 (void) printf(gettext(" (non-allocating)"));
3146 }
3147
3148 /* The root vdev has the scrub/resilver stats */
3149 root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
3150 ZPOOL_CONFIG_VDEV_TREE);
3151 (void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
3152 (uint64_t **)&ps, &c);
3153
3154 /*
3155 * If you force fault a drive that's resilvering, its scan stats can
3156 * get frozen in time, giving the false impression that it's
3157 * being resilvered. That's why we check the state to see if the vdev
3158 * is healthy before reporting "resilvering" or "repairing".
3159 */
3160 if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0 &&
3161 vs->vs_state == VDEV_STATE_HEALTHY) {
3162 if (vs->vs_scan_processed != 0) {
3163 (void) printf(gettext(" (%s)"),
3164 (ps->pss_func == POOL_SCAN_RESILVER) ?
3165 "resilvering" : "repairing");
3166 } else if (vs->vs_resilver_deferred) {
3167 (void) printf(gettext(" (awaiting resilver)"));
3168 }
3169 }
3170
3171 /* The top-level vdevs have the rebuild stats */
3172 if (vrs != NULL && vrs->vrs_state == VDEV_REBUILD_ACTIVE &&
3173 children == 0 && vs->vs_state == VDEV_STATE_HEALTHY) {
3174 if (vs->vs_rebuild_processed != 0) {
3175 (void) printf(gettext(" (resilvering)"));
3176 }
3177 }
3178
3179 if (cb->vcdl != NULL) {
3180 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
3181 printf(" ");
3182 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
3183 }
3184 }
3185
3186 /* Display vdev initialization and trim status for leaves. */
3187 if (children == 0) {
3188 print_status_initialize(vs, cb->cb_print_vdev_init);
3189 print_status_trim(vs, cb->cb_print_vdev_trim);
3190 }
3191
3192 (void) printf("\n");
3193
3194 for (c = 0; c < children; c++) {
3195 uint64_t islog = B_FALSE, ishole = B_FALSE;
3196
3197 /* Don't print logs or holes here */
3198 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3199 &islog);
3200 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
3201 &ishole);
3202 if (islog || ishole)
3203 continue;
3204 /* Only print normal classes here */
3205 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3206 continue;
3207
3208 /* Provide vdev_rebuild_stats to children if available */
3209 if (vrs == NULL) {
3210 (void) nvlist_lookup_uint64_array(nv,
3211 ZPOOL_CONFIG_REBUILD_STATS,
3212 (uint64_t **)&vrs, &i);
3213 }
3214
3215 vname = zpool_vdev_name(g_zfs, zhp, child[c],
3216 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3217 print_status_config(zhp, cb, vname, child[c], depth + 2,
3218 isspare, vrs);
3219 free(vname);
3220 }
3221 }
3222
3223 /*
3224 * Print the configuration of an exported pool. Iterate over all vdevs in the
3225 * pool, printing out the name and status for each one.
3226 */
3227 static void
print_import_config(status_cbdata_t * cb,const char * name,nvlist_t * nv,int depth)3228 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
3229 int depth)
3230 {
3231 nvlist_t **child;
3232 uint_t c, children;
3233 vdev_stat_t *vs;
3234 const char *type;
3235 char *vname;
3236
3237 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
3238 if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
3239 strcmp(type, VDEV_TYPE_HOLE) == 0)
3240 return;
3241
3242 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
3243 (uint64_t **)&vs, &c) == 0);
3244
3245 (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
3246 (void) printf(" %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
3247
3248 if (vs->vs_aux != 0) {
3249 (void) printf(" ");
3250
3251 switch (vs->vs_aux) {
3252 case VDEV_AUX_OPEN_FAILED:
3253 (void) printf(gettext("cannot open"));
3254 break;
3255
3256 case VDEV_AUX_BAD_GUID_SUM:
3257 (void) printf(gettext("missing device"));
3258 break;
3259
3260 case VDEV_AUX_NO_REPLICAS:
3261 (void) printf(gettext("insufficient replicas"));
3262 break;
3263
3264 case VDEV_AUX_VERSION_NEWER:
3265 (void) printf(gettext("newer version"));
3266 break;
3267
3268 case VDEV_AUX_UNSUP_FEAT:
3269 (void) printf(gettext("unsupported feature(s)"));
3270 break;
3271
3272 case VDEV_AUX_ERR_EXCEEDED:
3273 (void) printf(gettext("too many errors"));
3274 break;
3275
3276 case VDEV_AUX_ACTIVE:
3277 (void) printf(gettext("currently in use"));
3278 break;
3279
3280 case VDEV_AUX_CHILDREN_OFFLINE:
3281 (void) printf(gettext("all children offline"));
3282 break;
3283
3284 case VDEV_AUX_BAD_LABEL:
3285 (void) printf(gettext("invalid label"));
3286 break;
3287
3288 default:
3289 (void) printf(gettext("corrupted data"));
3290 break;
3291 }
3292 }
3293 (void) printf("\n");
3294
3295 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
3296 &child, &children) != 0)
3297 return;
3298
3299 for (c = 0; c < children; c++) {
3300 uint64_t is_log = B_FALSE;
3301
3302 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3303 &is_log);
3304 if (is_log)
3305 continue;
3306 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3307 continue;
3308
3309 vname = zpool_vdev_name(g_zfs, NULL, child[c],
3310 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3311 print_import_config(cb, vname, child[c], depth + 2);
3312 free(vname);
3313 }
3314
3315 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
3316 &child, &children) == 0) {
3317 (void) printf(gettext("\tcache\n"));
3318 for (c = 0; c < children; c++) {
3319 vname = zpool_vdev_name(g_zfs, NULL, child[c],
3320 cb->cb_name_flags);
3321 (void) printf("\t %s\n", vname);
3322 free(vname);
3323 }
3324 }
3325
3326 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
3327 &child, &children) == 0) {
3328 (void) printf(gettext("\tspares\n"));
3329 for (c = 0; c < children; c++) {
3330 vname = zpool_vdev_name(g_zfs, NULL, child[c],
3331 cb->cb_name_flags);
3332 (void) printf("\t %s\n", vname);
3333 free(vname);
3334 }
3335 }
3336 }
3337
3338 /*
3339 * Print specialized class vdevs.
3340 *
3341 * These are recorded as top level vdevs in the main pool child array
3342 * but with "is_log" set to 1 or an "alloc_bias" string. We use either
3343 * print_status_config() or print_import_config() to print the top level
3344 * class vdevs then any of their children (eg mirrored slogs) are printed
3345 * recursively - which works because only the top level vdev is marked.
3346 */
3347 static void
print_class_vdevs(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,const char * class)3348 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
3349 const char *class)
3350 {
3351 uint_t c, children;
3352 nvlist_t **child;
3353 boolean_t printed = B_FALSE;
3354
3355 assert(zhp != NULL || cb->cb_verbosity == 0);
3356
3357 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
3358 &children) != 0)
3359 return;
3360
3361 for (c = 0; c < children; c++) {
3362 uint64_t is_log = B_FALSE;
3363 const char *bias = NULL;
3364 const char *type = NULL;
3365
3366 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3367 &is_log);
3368
3369 if (is_log) {
3370 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
3371 } else {
3372 (void) nvlist_lookup_string(child[c],
3373 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
3374 (void) nvlist_lookup_string(child[c],
3375 ZPOOL_CONFIG_TYPE, &type);
3376 }
3377
3378 if (bias == NULL || strcmp(bias, class) != 0)
3379 continue;
3380 if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
3381 continue;
3382
3383 if (!printed) {
3384 (void) printf("\t%s\t\n", gettext(class));
3385 printed = B_TRUE;
3386 }
3387
3388 char *name = zpool_vdev_name(g_zfs, zhp, child[c],
3389 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3390 if (cb->cb_print_status)
3391 print_status_config(zhp, cb, name, child[c], 2,
3392 B_FALSE, NULL);
3393 else
3394 print_import_config(cb, name, child[c], 2);
3395 free(name);
3396 }
3397 }
3398
3399 /*
3400 * Display the status for the given pool.
3401 */
3402 static int
show_import(nvlist_t * config,boolean_t report_error)3403 show_import(nvlist_t *config, boolean_t report_error)
3404 {
3405 uint64_t pool_state;
3406 vdev_stat_t *vs;
3407 const char *name;
3408 uint64_t guid;
3409 uint64_t hostid = 0;
3410 const char *msgid;
3411 const char *hostname = "unknown";
3412 nvlist_t *nvroot, *nvinfo;
3413 zpool_status_t reason;
3414 zpool_errata_t errata;
3415 const char *health;
3416 uint_t vsc;
3417 const char *comment;
3418 const char *indent;
3419 char buf[2048];
3420 status_cbdata_t cb = { 0 };
3421
3422 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3423 &name) == 0);
3424 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3425 &guid) == 0);
3426 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3427 &pool_state) == 0);
3428 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3429 &nvroot) == 0);
3430
3431 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
3432 (uint64_t **)&vs, &vsc) == 0);
3433 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
3434
3435 reason = zpool_import_status(config, &msgid, &errata);
3436
3437 /*
3438 * If we're importing using a cachefile, then we won't report any
3439 * errors unless we are in the scan phase of the import.
3440 */
3441 if (reason != ZPOOL_STATUS_OK && !report_error)
3442 return (reason);
3443
3444 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0) {
3445 indent = " ";
3446 } else {
3447 comment = NULL;
3448 indent = "";
3449 }
3450
3451 (void) printf(gettext("%s pool: %s\n"), indent, name);
3452 (void) printf(gettext("%s id: %llu\n"), indent, (u_longlong_t)guid);
3453 (void) printf(gettext("%s state: %s"), indent, health);
3454 if (pool_state == POOL_STATE_DESTROYED)
3455 (void) printf(gettext(" (DESTROYED)"));
3456 (void) printf("\n");
3457
3458 if (reason != ZPOOL_STATUS_OK) {
3459 (void) printf("%s", indent);
3460 (void) printf_color(ANSI_BOLD, gettext("status: "));
3461 }
3462 switch (reason) {
3463 case ZPOOL_STATUS_MISSING_DEV_R:
3464 case ZPOOL_STATUS_MISSING_DEV_NR:
3465 case ZPOOL_STATUS_BAD_GUID_SUM:
3466 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3467 "are missing from the system.\n"));
3468 break;
3469
3470 case ZPOOL_STATUS_CORRUPT_LABEL_R:
3471 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
3472 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3473 "contains corrupted data.\n"));
3474 break;
3475
3476 case ZPOOL_STATUS_CORRUPT_DATA:
3477 (void) printf_color(ANSI_YELLOW, gettext("The pool data is "
3478 "corrupted.\n"));
3479 break;
3480
3481 case ZPOOL_STATUS_OFFLINE_DEV:
3482 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3483 "are offlined.\n"));
3484 break;
3485
3486 case ZPOOL_STATUS_CORRUPT_POOL:
3487 (void) printf_color(ANSI_YELLOW, gettext("The pool metadata is "
3488 "incomplete or corrupted.\n"));
3489 break;
3490
3491 case ZPOOL_STATUS_VERSION_OLDER:
3492 (void) printf_color(ANSI_YELLOW, gettext("The pool is "
3493 "formatted using a legacy on-disk version.\n"));
3494 break;
3495
3496 case ZPOOL_STATUS_VERSION_NEWER:
3497 (void) printf_color(ANSI_YELLOW, gettext("The pool is "
3498 "formatted using an incompatible version.\n"));
3499 break;
3500
3501 case ZPOOL_STATUS_FEAT_DISABLED:
3502 (void) printf_color(ANSI_YELLOW, gettext("Some supported "
3503 "features are not enabled on the pool.\n"
3504 "\t%s(Note that they may be intentionally disabled if the\n"
3505 "\t%s'compatibility' property is set.)\n"), indent, indent);
3506 break;
3507
3508 case ZPOOL_STATUS_COMPATIBILITY_ERR:
3509 (void) printf_color(ANSI_YELLOW, gettext("Error reading or "
3510 "parsing the file(s) indicated by the 'compatibility'\n"
3511 "\t%sproperty.\n"), indent);
3512 break;
3513
3514 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
3515 (void) printf_color(ANSI_YELLOW, gettext("One or more features "
3516 "are enabled on the pool despite not being\n"
3517 "\t%srequested by the 'compatibility' property.\n"),
3518 indent);
3519 break;
3520
3521 case ZPOOL_STATUS_UNSUP_FEAT_READ:
3522 (void) printf_color(ANSI_YELLOW, gettext("The pool uses the "
3523 "following feature(s) not supported on this system:\n"));
3524 color_start(ANSI_YELLOW);
3525 zpool_collect_unsup_feat(config, buf, 2048);
3526 (void) printf("%s", buf);
3527 color_end();
3528 break;
3529
3530 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3531 (void) printf_color(ANSI_YELLOW, gettext("The pool can only be "
3532 "accessed in read-only mode on this system. It\n"
3533 "\t%scannot be accessed in read-write mode because it uses "
3534 "the following\n"
3535 "\t%sfeature(s) not supported on this system:\n"),
3536 indent, indent);
3537 color_start(ANSI_YELLOW);
3538 zpool_collect_unsup_feat(config, buf, 2048);
3539 (void) printf("%s", buf);
3540 color_end();
3541 break;
3542
3543 case ZPOOL_STATUS_HOSTID_ACTIVE:
3544 (void) printf_color(ANSI_YELLOW, gettext("The pool is "
3545 "currently imported by another system.\n"));
3546 break;
3547
3548 case ZPOOL_STATUS_HOSTID_REQUIRED:
3549 (void) printf_color(ANSI_YELLOW, gettext("The pool has the "
3550 "multihost property on. It cannot\n"
3551 "\t%sbe safely imported when the system hostid is not "
3552 "set.\n"), indent);
3553 break;
3554
3555 case ZPOOL_STATUS_HOSTID_MISMATCH:
3556 (void) printf_color(ANSI_YELLOW, gettext("The pool was last "
3557 "accessed by another system.\n"));
3558 break;
3559
3560 case ZPOOL_STATUS_FAULTED_FDOM_R:
3561 (void) printf_color(ANSI_YELLOW, gettext("One or more failure "
3562 " domains are faulted.\n"));
3563 break;
3564
3565 case ZPOOL_STATUS_FAULTED_DEV_R:
3566 case ZPOOL_STATUS_FAULTED_DEV_NR:
3567 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3568 "are faulted.\n"));
3569 break;
3570
3571 case ZPOOL_STATUS_BAD_LOG:
3572 (void) printf_color(ANSI_YELLOW, gettext("An intent log record "
3573 "cannot be read.\n"));
3574 break;
3575
3576 case ZPOOL_STATUS_RESILVERING:
3577 case ZPOOL_STATUS_REBUILDING:
3578 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3579 "were being resilvered.\n"));
3580 break;
3581
3582 case ZPOOL_STATUS_ERRATA:
3583 (void) printf_color(ANSI_YELLOW,
3584 gettext("Errata #%d detected.\n"),
3585 errata);
3586 break;
3587
3588 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
3589 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3590 "are configured to use a non-native block size.\n"
3591 "\t%sExpect reduced performance.\n"), indent);
3592 break;
3593
3594 default:
3595 /*
3596 * No other status can be seen when importing pools.
3597 */
3598 assert(reason == ZPOOL_STATUS_OK);
3599 }
3600
3601 /*
3602 * Print out an action according to the overall state of the pool.
3603 */
3604 if (vs->vs_state != VDEV_STATE_HEALTHY ||
3605 reason != ZPOOL_STATUS_ERRATA || errata != ZPOOL_ERRATA_NONE) {
3606 (void) printf("%s", indent);
3607 (void) printf(gettext("action: "));
3608 }
3609 if (vs->vs_state == VDEV_STATE_HEALTHY) {
3610 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
3611 reason == ZPOOL_STATUS_FEAT_DISABLED) {
3612 (void) printf(gettext("The pool can be imported using "
3613 "its name or numeric identifier, though\n"
3614 "\t%ssome features will not be available without "
3615 "an explicit 'zpool upgrade'.\n"), indent);
3616 } else if (reason == ZPOOL_STATUS_COMPATIBILITY_ERR) {
3617 (void) printf(gettext("The pool can be imported using "
3618 "its name or numeric\n"
3619 "\t%sidentifier, though the file(s) indicated by "
3620 "its 'compatibility'\n"
3621 "\t%sproperty cannot be parsed at this time.\n"),
3622 indent, indent);
3623 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
3624 (void) printf(gettext("The pool can be imported using "
3625 "its name or numeric identifier and\n"
3626 "\t%sthe '-f' flag.\n"), indent);
3627 } else if (reason == ZPOOL_STATUS_ERRATA) {
3628 switch (errata) {
3629 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
3630 (void) printf(gettext("The pool can be "
3631 "imported using its name or numeric "
3632 "identifier,\n"
3633 "\t%showever there is a compatibility "
3634 "issue which should be corrected\n"
3635 "\t%sby running 'zpool scrub'\n"),
3636 indent, indent);
3637 break;
3638
3639 case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
3640 (void) printf(gettext("The pool cannot be "
3641 "imported with this version of ZFS due to\n"
3642 "\t%san active asynchronous destroy. "
3643 "Revert to an earlier version\n"
3644 "\t%sand allow the destroy to complete "
3645 "before updating.\n"), indent, indent);
3646 break;
3647
3648 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
3649 (void) printf(gettext("Existing encrypted "
3650 "datasets contain an on-disk "
3651 "incompatibility, which\n"
3652 "\t%sneeds to be corrected. Backup these "
3653 "datasets to new encrypted datasets\n"
3654 "\t%sand destroy the old ones.\n"),
3655 indent, indent);
3656 break;
3657
3658 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
3659 (void) printf(gettext("Existing encrypted "
3660 "snapshots and bookmarks contain an "
3661 "on-disk\n"
3662 "\t%sincompatibility. This may cause "
3663 "on-disk corruption if they are used\n"
3664 "\t%swith 'zfs recv'. To correct the "
3665 "issue, enable the bookmark_v2 feature.\n"
3666 "\t%sNo additional action is needed if "
3667 "there are no encrypted snapshots or\n"
3668 "\t%sbookmarks. If preserving the "
3669 "encrypted snapshots and bookmarks is\n"
3670 "\t%srequired, use a non-raw send to "
3671 "backup and restore them. Alternately,\n"
3672 "\t%sthey may be removed to resolve the "
3673 "incompatibility.\n"), indent, indent,
3674 indent, indent, indent, indent);
3675 break;
3676 default:
3677 /*
3678 * All errata must contain an action message.
3679 */
3680 assert(errata == ZPOOL_ERRATA_NONE);
3681 }
3682 } else {
3683 (void) printf(gettext("The pool can be imported using "
3684 "its name or numeric identifier.\n"));
3685 }
3686 } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
3687 (void) printf(gettext("The pool can be imported despite "
3688 "missing or damaged devices. The\n"
3689 "\t%sfault tolerance of the pool may be compromised if "
3690 "imported.\n"), indent);
3691 } else {
3692 switch (reason) {
3693 case ZPOOL_STATUS_VERSION_NEWER:
3694 (void) printf(gettext("The pool cannot be imported. "
3695 "Access the pool on a system running newer\n"
3696 "\t%ssoftware, or recreate the pool from "
3697 "backup.\n"), indent);
3698 break;
3699 case ZPOOL_STATUS_UNSUP_FEAT_READ:
3700 (void) printf(gettext("The pool cannot be imported. "
3701 "Access the pool on a system that supports\n"
3702 "\t%sthe required feature(s), or recreate the pool "
3703 "from backup.\n"), indent);
3704 break;
3705 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3706 (void) printf(gettext("The pool cannot be imported in "
3707 "read-write mode. Import the pool with\n"
3708 "\t%s'-o readonly=on', access the pool on a system "
3709 "that supports the\n"
3710 "\t%srequired feature(s), or recreate the pool "
3711 "from backup.\n"), indent, indent);
3712 break;
3713 case ZPOOL_STATUS_MISSING_DEV_R:
3714 case ZPOOL_STATUS_MISSING_DEV_NR:
3715 case ZPOOL_STATUS_BAD_GUID_SUM:
3716 (void) printf(gettext("The pool cannot be imported. "
3717 "Attach the missing\n"
3718 "\t%sdevices and try again.\n"), indent);
3719 break;
3720 case ZPOOL_STATUS_HOSTID_ACTIVE:
3721 VERIFY0(nvlist_lookup_nvlist(config,
3722 ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
3723
3724 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3725 hostname = fnvlist_lookup_string(nvinfo,
3726 ZPOOL_CONFIG_MMP_HOSTNAME);
3727
3728 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3729 hostid = fnvlist_lookup_uint64(nvinfo,
3730 ZPOOL_CONFIG_MMP_HOSTID);
3731
3732 (void) printf(gettext("The pool must be exported from "
3733 "%s (hostid=%"PRIx64")\n"
3734 "\t%sbefore it can be safely imported.\n"),
3735 hostname, hostid, indent);
3736 break;
3737 case ZPOOL_STATUS_HOSTID_REQUIRED:
3738 (void) printf(gettext("Set a unique system hostid with "
3739 "the zgenhostid(8) command.\n"));
3740 break;
3741 case ZPOOL_STATUS_CORRUPT_POOL:
3742 (void) printf(gettext("The pool cannot be imported due "
3743 "to missing or damaged devices. Ensure\n"
3744 "\t%sall devices are present and not in use by "
3745 "another subsystem.\n"), indent);
3746 break;
3747 default:
3748 (void) printf(gettext("The pool cannot be imported due "
3749 "to damaged devices or data.\n"));
3750 }
3751 }
3752
3753 /* Print the comment attached to the pool. */
3754 if (comment != NULL)
3755 (void) printf(gettext("comment: %s\n"), comment);
3756
3757 /*
3758 * If the state is "closed" or "can't open", and the aux state
3759 * is "corrupt data":
3760 */
3761 if ((vs->vs_state == VDEV_STATE_CLOSED ||
3762 vs->vs_state == VDEV_STATE_CANT_OPEN) &&
3763 vs->vs_aux == VDEV_AUX_CORRUPT_DATA) {
3764 if (pool_state == POOL_STATE_DESTROYED)
3765 (void) printf(gettext("\t%sThe pool was destroyed, "
3766 "but can be imported using the '-Df' flags.\n"),
3767 indent);
3768 else if (pool_state != POOL_STATE_EXPORTED)
3769 (void) printf(gettext("\t%sThe pool may be active on "
3770 "another system, but can be imported using\n"
3771 "\t%sthe '-f' flag.\n"), indent, indent);
3772 }
3773
3774 if (msgid != NULL) {
3775 (void) printf(gettext("%s see: "
3776 "https://openzfs.github.io/openzfs-docs/msg/%s\n"),
3777 indent, msgid);
3778 }
3779
3780 (void) printf(gettext("%sconfig:\n\n"), indent);
3781
3782 cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
3783 VDEV_NAME_TYPE_ID);
3784 if (cb.cb_namewidth < 10)
3785 cb.cb_namewidth = 10;
3786
3787 print_import_config(&cb, name, nvroot, 0);
3788
3789 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
3790 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
3791 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
3792
3793 if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
3794 (void) printf(gettext("\n\t%sAdditional devices are known to "
3795 "be part of this pool, though their\n"
3796 "\t%sexact configuration cannot be determined.\n"),
3797 indent, indent);
3798 }
3799 return (0);
3800 }
3801
3802 static boolean_t
zfs_force_import_required(nvlist_t * config)3803 zfs_force_import_required(nvlist_t *config)
3804 {
3805 uint64_t state;
3806 uint64_t hostid = 0;
3807 nvlist_t *nvinfo;
3808
3809 state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
3810 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3811
3812 /*
3813 * The hostid on LOAD_INFO comes from the MOS label via
3814 * spa_tryimport(). If its not there then we're likely talking to an
3815 * older kernel, so use the top one, which will be from the label
3816 * discovered in zpool_find_import(), or if a cachefile is in use, the
3817 * local hostid.
3818 */
3819 if (nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_HOSTID, &hostid) != 0)
3820 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
3821 &hostid);
3822
3823 if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
3824 return (B_TRUE);
3825
3826 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
3827 mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
3828 ZPOOL_CONFIG_MMP_STATE);
3829
3830 if (mmp_state != MMP_STATE_INACTIVE)
3831 return (B_TRUE);
3832 }
3833
3834 return (B_FALSE);
3835 }
3836
3837 /*
3838 * Perform the import for the given configuration. This passes the heavy
3839 * lifting off to zpool_import_props(), and then mounts the datasets contained
3840 * within the pool.
3841 */
3842 static int
do_import(nvlist_t * config,const char * newname,const char * mntopts,nvlist_t * props,int flags,uint_t mntthreads)3843 do_import(nvlist_t *config, const char *newname, const char *mntopts,
3844 nvlist_t *props, int flags, uint_t mntthreads)
3845 {
3846 int ret = 0;
3847 int ms_status = 0;
3848 zpool_handle_t *zhp;
3849 const char *name;
3850 uint64_t version;
3851
3852 name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
3853 version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3854
3855 if (!SPA_VERSION_IS_SUPPORTED(version)) {
3856 (void) fprintf(stderr, gettext("cannot import '%s': pool "
3857 "is formatted using an unsupported ZFS version\n"), name);
3858 return (1);
3859 } else if (zfs_force_import_required(config) &&
3860 !(flags & ZFS_IMPORT_ANY_HOST)) {
3861 mmp_state_t mmp_state = MMP_STATE_INACTIVE;
3862 nvlist_t *nvinfo;
3863
3864 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3865 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
3866 mmp_state = fnvlist_lookup_uint64(nvinfo,
3867 ZPOOL_CONFIG_MMP_STATE);
3868
3869 if (mmp_state == MMP_STATE_ACTIVE) {
3870 const char *hostname = "<unknown>";
3871 uint64_t hostid = 0;
3872
3873 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3874 hostname = fnvlist_lookup_string(nvinfo,
3875 ZPOOL_CONFIG_MMP_HOSTNAME);
3876
3877 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3878 hostid = fnvlist_lookup_uint64(nvinfo,
3879 ZPOOL_CONFIG_MMP_HOSTID);
3880
3881 (void) fprintf(stderr, gettext("cannot import '%s': "
3882 "pool is imported on %s (hostid: "
3883 "0x%"PRIx64")\nExport the pool on the other "
3884 "system, then run 'zpool import'.\n"),
3885 name, hostname, hostid);
3886 } else if (mmp_state == MMP_STATE_NO_HOSTID) {
3887 (void) fprintf(stderr, gettext("Cannot import '%s': "
3888 "pool has the multihost property on and the\n"
3889 "system's hostid is not set. Set a unique hostid "
3890 "with the zgenhostid(8) command.\n"), name);
3891 } else {
3892 const char *hostname = "<unknown>";
3893 time_t timestamp = 0;
3894 uint64_t hostid = 0;
3895
3896 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTNAME))
3897 hostname = fnvlist_lookup_string(nvinfo,
3898 ZPOOL_CONFIG_HOSTNAME);
3899 else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
3900 hostname = fnvlist_lookup_string(config,
3901 ZPOOL_CONFIG_HOSTNAME);
3902
3903 if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
3904 timestamp = fnvlist_lookup_uint64(config,
3905 ZPOOL_CONFIG_TIMESTAMP);
3906
3907 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTID))
3908 hostid = fnvlist_lookup_uint64(nvinfo,
3909 ZPOOL_CONFIG_HOSTID);
3910 else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
3911 hostid = fnvlist_lookup_uint64(config,
3912 ZPOOL_CONFIG_HOSTID);
3913
3914 (void) fprintf(stderr, gettext("cannot import '%s': "
3915 "pool was previously in use from another system.\n"
3916 "Last accessed by %s (hostid=%"PRIx64") at %s"
3917 "The pool can be imported, use 'zpool import -f' "
3918 "to import the pool.\n"), name, hostname,
3919 hostid, ctime(×tamp));
3920 }
3921
3922 if (getenv("ZFS_LOAD_INFO_DEBUG"))
3923 dump_nvlist(nvinfo, 4);
3924
3925 return (1);
3926 }
3927
3928 if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
3929 return (1);
3930
3931 if (newname != NULL)
3932 name = newname;
3933
3934 if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
3935 return (1);
3936
3937 /*
3938 * Loading keys is best effort. We don't want to return immediately
3939 * if it fails but we do want to give the error to the caller.
3940 */
3941 if (flags & ZFS_IMPORT_LOAD_KEYS &&
3942 zfs_crypto_attempt_load_keys(g_zfs, name) != 0)
3943 ret = 1;
3944
3945 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3946 !(flags & ZFS_IMPORT_ONLY)) {
3947 ms_status = zpool_enable_datasets(zhp, mntopts, 0, mntthreads);
3948 if (ms_status == EZFS_SHAREFAILED) {
3949 (void) fprintf(stderr, gettext("Import was "
3950 "successful, but unable to share some datasets\n"));
3951 } else if (ms_status == EZFS_MOUNTFAILED) {
3952 (void) fprintf(stderr, gettext("Import was "
3953 "successful, but unable to mount some datasets\n"));
3954 }
3955 }
3956
3957 zpool_close(zhp);
3958 return (ret);
3959 }
3960
3961 typedef struct import_parameters {
3962 nvlist_t *ip_config;
3963 const char *ip_mntopts;
3964 nvlist_t *ip_props;
3965 int ip_flags;
3966 uint_t ip_mntthreads;
3967 int *ip_err;
3968 } import_parameters_t;
3969
3970 static void
do_import_task(void * arg)3971 do_import_task(void *arg)
3972 {
3973 import_parameters_t *ip = arg;
3974 *ip->ip_err |= do_import(ip->ip_config, NULL, ip->ip_mntopts,
3975 ip->ip_props, ip->ip_flags, ip->ip_mntthreads);
3976 free(ip);
3977 }
3978
3979
3980 static int
import_pools(nvlist_t * pools,nvlist_t * props,char * mntopts,int flags,char * orig_name,char * new_name,importargs_t * import)3981 import_pools(nvlist_t *pools, nvlist_t *props, char *mntopts, int flags,
3982 char *orig_name, char *new_name, importargs_t *import)
3983 {
3984 nvlist_t *config = NULL;
3985 nvlist_t *found_config = NULL;
3986 uint64_t pool_state;
3987 boolean_t pool_specified = (import->poolname != NULL ||
3988 import->guid != 0);
3989 uint_t npools = 0;
3990
3991
3992 taskq_t *tq = NULL;
3993 if (import->do_all) {
3994 tq = taskq_create("zpool_import_all",
3995 5 * sysconf(_SC_NPROCESSORS_ONLN), minclsyspri, 1, INT_MAX,
3996 TASKQ_DYNAMIC);
3997 }
3998
3999 /*
4000 * At this point we have a list of import candidate configs. Even if
4001 * we were searching by pool name or guid, we still need to
4002 * post-process the list to deal with pool state and possible
4003 * duplicate names.
4004 */
4005 int err = 0;
4006 nvpair_t *elem = NULL;
4007 boolean_t first = B_TRUE;
4008 if (!pool_specified && import->do_all) {
4009 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL)
4010 npools++;
4011 }
4012 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
4013
4014 verify(nvpair_value_nvlist(elem, &config) == 0);
4015
4016 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4017 &pool_state) == 0);
4018 if (!import->do_destroyed &&
4019 pool_state == POOL_STATE_DESTROYED)
4020 continue;
4021 if (import->do_destroyed &&
4022 pool_state != POOL_STATE_DESTROYED)
4023 continue;
4024
4025 verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
4026 import->policy) == 0);
4027
4028 if (!pool_specified) {
4029 if (first)
4030 first = B_FALSE;
4031 else if (!import->do_all)
4032 (void) fputc('\n', stdout);
4033
4034 if (import->do_all) {
4035 import_parameters_t *ip = safe_malloc(
4036 sizeof (import_parameters_t));
4037
4038 ip->ip_config = config;
4039 ip->ip_mntopts = mntopts;
4040 ip->ip_props = props;
4041 ip->ip_flags = flags;
4042 ip->ip_mntthreads = mount_tp_nthr / npools;
4043 ip->ip_err = &err;
4044
4045 (void) taskq_dispatch(tq, do_import_task,
4046 (void *)ip, TQ_SLEEP);
4047 } else {
4048 /*
4049 * If we're importing from cachefile, then
4050 * we don't want to report errors until we
4051 * are in the scan phase of the import. If
4052 * we get an error, then we return that error
4053 * to invoke the scan phase.
4054 */
4055 if (import->cachefile && !import->scan)
4056 err = show_import(config, B_FALSE);
4057 else
4058 (void) show_import(config, B_TRUE);
4059 }
4060 } else if (import->poolname != NULL) {
4061 const char *name;
4062
4063 /*
4064 * We are searching for a pool based on name.
4065 */
4066 verify(nvlist_lookup_string(config,
4067 ZPOOL_CONFIG_POOL_NAME, &name) == 0);
4068
4069 if (strcmp(name, import->poolname) == 0) {
4070 if (found_config != NULL) {
4071 (void) fprintf(stderr, gettext(
4072 "cannot import '%s': more than "
4073 "one matching pool\n"),
4074 import->poolname);
4075 (void) fprintf(stderr, gettext(
4076 "import by numeric ID instead\n"));
4077 err = B_TRUE;
4078 }
4079 found_config = config;
4080 }
4081 } else {
4082 uint64_t guid;
4083
4084 /*
4085 * Search for a pool by guid.
4086 */
4087 verify(nvlist_lookup_uint64(config,
4088 ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
4089
4090 if (guid == import->guid)
4091 found_config = config;
4092 }
4093 }
4094 if (import->do_all) {
4095 taskq_wait(tq);
4096 taskq_destroy(tq);
4097 }
4098
4099 /*
4100 * If we were searching for a specific pool, verify that we found a
4101 * pool, and then do the import.
4102 */
4103 if (pool_specified && err == 0) {
4104 if (found_config == NULL) {
4105 (void) fprintf(stderr, gettext("cannot import '%s': "
4106 "no such pool available\n"), orig_name);
4107 err = B_TRUE;
4108 } else {
4109 err |= do_import(found_config, new_name,
4110 mntopts, props, flags, mount_tp_nthr);
4111 }
4112 }
4113
4114 /*
4115 * If we were just looking for pools, report an error if none were
4116 * found.
4117 */
4118 if (!pool_specified && first)
4119 (void) fprintf(stderr,
4120 gettext("no pools available to import\n"));
4121 return (err);
4122 }
4123
4124 typedef struct target_exists_args {
4125 const char *poolname;
4126 uint64_t poolguid;
4127 } target_exists_args_t;
4128
4129 static int
name_or_guid_exists(zpool_handle_t * zhp,void * data)4130 name_or_guid_exists(zpool_handle_t *zhp, void *data)
4131 {
4132 target_exists_args_t *args = data;
4133 nvlist_t *config = zpool_get_config(zhp, NULL);
4134 int found = 0;
4135
4136 if (config == NULL)
4137 return (0);
4138
4139 if (args->poolname != NULL) {
4140 const char *pool_name;
4141
4142 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4143 &pool_name) == 0);
4144 if (strcmp(pool_name, args->poolname) == 0)
4145 found = 1;
4146 } else {
4147 uint64_t pool_guid;
4148
4149 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4150 &pool_guid) == 0);
4151 if (pool_guid == args->poolguid)
4152 found = 1;
4153 }
4154 zpool_close(zhp);
4155
4156 return (found);
4157 }
4158 /*
4159 * zpool checkpoint <pool>
4160 * checkpoint --discard <pool>
4161 *
4162 * -d Discard the checkpoint from a checkpointed
4163 * --discard pool.
4164 *
4165 * -w Wait for discarding a checkpoint to complete.
4166 * --wait
4167 *
4168 * Checkpoints the specified pool, by taking a "snapshot" of its
4169 * current state. A pool can only have one checkpoint at a time.
4170 */
4171 int
zpool_do_checkpoint(int argc,char ** argv)4172 zpool_do_checkpoint(int argc, char **argv)
4173 {
4174 boolean_t discard, wait;
4175 char *pool;
4176 zpool_handle_t *zhp;
4177 int c, err;
4178
4179 struct option long_options[] = {
4180 {"discard", no_argument, NULL, 'd'},
4181 {"wait", no_argument, NULL, 'w'},
4182 {0, 0, 0, 0}
4183 };
4184
4185 discard = B_FALSE;
4186 wait = B_FALSE;
4187 while ((c = getopt_long(argc, argv, ":dw", long_options, NULL)) != -1) {
4188 switch (c) {
4189 case 'd':
4190 discard = B_TRUE;
4191 break;
4192 case 'w':
4193 wait = B_TRUE;
4194 break;
4195 case '?':
4196 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4197 optopt);
4198 usage(B_FALSE);
4199 }
4200 }
4201
4202 if (wait && !discard) {
4203 (void) fprintf(stderr, gettext("--wait only valid when "
4204 "--discard also specified\n"));
4205 usage(B_FALSE);
4206 }
4207
4208 argc -= optind;
4209 argv += optind;
4210
4211 if (argc < 1) {
4212 (void) fprintf(stderr, gettext("missing pool argument\n"));
4213 usage(B_FALSE);
4214 }
4215
4216 if (argc > 1) {
4217 (void) fprintf(stderr, gettext("too many arguments\n"));
4218 usage(B_FALSE);
4219 }
4220
4221 pool = argv[0];
4222
4223 if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
4224 /* As a special case, check for use of '/' in the name */
4225 if (strchr(pool, '/') != NULL)
4226 (void) fprintf(stderr, gettext("'zpool checkpoint' "
4227 "doesn't work on datasets. To save the state "
4228 "of a dataset from a specific point in time "
4229 "please use 'zfs snapshot'\n"));
4230 return (1);
4231 }
4232
4233 if (discard) {
4234 err = (zpool_discard_checkpoint(zhp) != 0);
4235 if (err == 0 && wait)
4236 err = zpool_wait(zhp, ZPOOL_WAIT_CKPT_DISCARD);
4237 } else {
4238 err = (zpool_checkpoint(zhp) != 0);
4239 }
4240
4241 zpool_close(zhp);
4242
4243 return (err);
4244 }
4245
4246 #define CHECKPOINT_OPT 1024
4247
4248 /*
4249 * zpool prefetch [-t <type>] <pool>
4250 *
4251 * Prefetchs a particular type of data in the specified pool.
4252 */
4253 int
zpool_do_prefetch(int argc,char ** argv)4254 zpool_do_prefetch(int argc, char **argv)
4255 {
4256 int c;
4257 char *poolname;
4258 char *typestr = NULL;
4259 zpool_prefetch_type_t type;
4260 zpool_handle_t *zhp;
4261 int err = 0;
4262
4263 while ((c = getopt(argc, argv, "t:")) != -1) {
4264 switch (c) {
4265 case 't':
4266 typestr = optarg;
4267 break;
4268 case ':':
4269 (void) fprintf(stderr, gettext("missing argument for "
4270 "'%c' option\n"), optopt);
4271 usage(B_FALSE);
4272 break;
4273 case '?':
4274 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4275 optopt);
4276 usage(B_FALSE);
4277 }
4278 }
4279 argc -= optind;
4280 argv += optind;
4281
4282 if (argc < 1) {
4283 (void) fprintf(stderr, gettext("missing pool name argument\n"));
4284 usage(B_FALSE);
4285 }
4286
4287 if (argc > 1) {
4288 (void) fprintf(stderr, gettext("too many arguments\n"));
4289 usage(B_FALSE);
4290 }
4291
4292 poolname = argv[0];
4293
4294 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
4295 return (1);
4296
4297 if (typestr == NULL) {
4298 /* Prefetch all types */
4299 err = zpool_prefetch(zhp, ZPOOL_PREFETCH_DDT);
4300 if (err == 0)
4301 err = zpool_prefetch(zhp, ZPOOL_PREFETCH_BRT);
4302 } else {
4303 if (strcmp(typestr, "ddt") == 0) {
4304 type = ZPOOL_PREFETCH_DDT;
4305 } else if (strcmp(typestr, "brt") == 0) {
4306 type = ZPOOL_PREFETCH_BRT;
4307 } else {
4308 (void) fprintf(stderr,
4309 gettext("unsupported prefetch type\n"));
4310 zpool_close(zhp);
4311 usage(B_FALSE);
4312 }
4313 err = zpool_prefetch(zhp, type);
4314 }
4315
4316 zpool_close(zhp);
4317
4318 return (err);
4319 }
4320
4321 /*
4322 * zpool import [-d dir] [-D]
4323 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4324 * [-d dir | -c cachefile | -s] [-f] -a
4325 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4326 * [-d dir | -c cachefile | -s] [-f] [-n] [-F] <pool | id>
4327 * [newpool]
4328 *
4329 * -c Read pool information from a cachefile instead of searching
4330 * devices. If importing from a cachefile config fails, then
4331 * fallback to searching for devices only in the directories that
4332 * exist in the cachefile.
4333 *
4334 * -d Scan in a specific directory, other than /dev/. More than
4335 * one directory can be specified using multiple '-d' options.
4336 *
4337 * -D Scan for previously destroyed pools or import all or only
4338 * specified destroyed pools.
4339 *
4340 * -R Temporarily import the pool, with all mountpoints relative to
4341 * the given root. The pool will remain exported when the machine
4342 * is rebooted.
4343 *
4344 * -V Import even in the presence of faulted vdevs. This is an
4345 * intentionally undocumented option for testing purposes, and
4346 * treats the pool configuration as complete, leaving any bad
4347 * vdevs in the FAULTED state. In other words, it does verbatim
4348 * import.
4349 *
4350 * -f Force import, even if it appears that the pool is active.
4351 *
4352 * -F Attempt rewind if necessary.
4353 *
4354 * -M Tolerate meta-data read errors that are not critical for the
4355 * pool operation.
4356 *
4357 * -n See if rewind would work, but don't actually rewind.
4358 *
4359 * -N Import the pool but don't mount datasets.
4360 *
4361 * -T Specify a starting txg to use for import. This option is
4362 * intentionally undocumented option for testing purposes.
4363 *
4364 * -a Import all pools found.
4365 *
4366 * -l Load encryption keys while importing.
4367 *
4368 * -o Set property=value and/or temporary mount options (without '=').
4369 *
4370 * -s Scan using the default search path, the libblkid cache will
4371 * not be consulted.
4372 *
4373 * --rewind-to-checkpoint
4374 * Import the pool and revert back to the checkpoint.
4375 *
4376 * The import command scans for pools to import, and import pools based on pool
4377 * name and GUID. The pool can also be renamed as part of the import process.
4378 */
4379 int
zpool_do_import(int argc,char ** argv)4380 zpool_do_import(int argc, char **argv)
4381 {
4382 char **searchdirs = NULL;
4383 char *env, *envdup = NULL;
4384 int nsearch = 0;
4385 int c;
4386 int err = 0;
4387 nvlist_t *pools = NULL;
4388 boolean_t do_all = B_FALSE;
4389 boolean_t do_destroyed = B_FALSE;
4390 char *mntopts = NULL;
4391 uint64_t searchguid = 0;
4392 char *searchname = NULL;
4393 char *propval;
4394 nvlist_t *policy = NULL;
4395 nvlist_t *props = NULL;
4396 int flags = ZFS_IMPORT_NORMAL;
4397 uint32_t rewind_policy = ZPOOL_NO_REWIND;
4398 boolean_t dryrun = B_FALSE;
4399 boolean_t do_rewind = B_FALSE;
4400 boolean_t xtreme_rewind = B_FALSE;
4401 boolean_t relax_meta = B_FALSE;
4402 boolean_t do_scan = B_FALSE;
4403 boolean_t pool_exists = B_FALSE;
4404 uint64_t txg = -1ULL;
4405 char *cachefile = NULL;
4406 importargs_t idata = { 0 };
4407 char *endptr;
4408
4409 struct option long_options[] = {
4410 {"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
4411 {0, 0, 0, 0}
4412 };
4413
4414 /* check options */
4415 while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmMnNo:R:stT:VX",
4416 long_options, NULL)) != -1) {
4417 switch (c) {
4418 case 'a':
4419 do_all = B_TRUE;
4420 break;
4421 case 'c':
4422 cachefile = optarg;
4423 break;
4424 case 'd':
4425 searchdirs = safe_realloc(searchdirs,
4426 (nsearch + 1) * sizeof (char *));
4427 searchdirs[nsearch++] = optarg;
4428 break;
4429 case 'D':
4430 do_destroyed = B_TRUE;
4431 break;
4432 case 'f':
4433 flags |= ZFS_IMPORT_ANY_HOST;
4434 break;
4435 case 'F':
4436 do_rewind = B_TRUE;
4437 break;
4438 case 'l':
4439 flags |= ZFS_IMPORT_LOAD_KEYS;
4440 break;
4441 case 'm':
4442 flags |= ZFS_IMPORT_MISSING_LOG;
4443 break;
4444 case 'M':
4445 relax_meta = B_TRUE;
4446 break;
4447 case 'n':
4448 dryrun = B_TRUE;
4449 break;
4450 case 'N':
4451 flags |= ZFS_IMPORT_ONLY;
4452 break;
4453 case 'o':
4454 if ((propval = strchr(optarg, '=')) != NULL) {
4455 *propval = '\0';
4456 propval++;
4457 if (add_prop_list(optarg, propval,
4458 &props, B_TRUE))
4459 goto error;
4460 } else {
4461 mntopts = optarg;
4462 }
4463 break;
4464 case 'R':
4465 if (add_prop_list(zpool_prop_to_name(
4466 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
4467 goto error;
4468 if (add_prop_list_default(zpool_prop_to_name(
4469 ZPOOL_PROP_CACHEFILE), "none", &props))
4470 goto error;
4471 break;
4472 case 's':
4473 do_scan = B_TRUE;
4474 break;
4475 case 't':
4476 flags |= ZFS_IMPORT_TEMP_NAME;
4477 if (add_prop_list_default(zpool_prop_to_name(
4478 ZPOOL_PROP_CACHEFILE), "none", &props))
4479 goto error;
4480 break;
4481
4482 case 'T':
4483 errno = 0;
4484 txg = strtoull(optarg, &endptr, 0);
4485 if (errno != 0 || *endptr != '\0') {
4486 (void) fprintf(stderr,
4487 gettext("invalid txg value\n"));
4488 usage(B_FALSE);
4489 }
4490 /* Rollback to a specific txg implies -FX. */
4491 do_rewind = B_TRUE;
4492 xtreme_rewind = B_TRUE;
4493 break;
4494 case 'V':
4495 flags |= ZFS_IMPORT_VERBATIM;
4496 break;
4497 case 'X':
4498 xtreme_rewind = B_TRUE;
4499 break;
4500 case CHECKPOINT_OPT:
4501 flags |= ZFS_IMPORT_CHECKPOINT;
4502 break;
4503 case ':':
4504 (void) fprintf(stderr, gettext("missing argument for "
4505 "'%c' option\n"), optopt);
4506 usage(B_FALSE);
4507 break;
4508 case '?':
4509 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4510 optopt);
4511 usage(B_FALSE);
4512 }
4513 }
4514
4515 argc -= optind;
4516 argv += optind;
4517
4518 if (cachefile && nsearch != 0) {
4519 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
4520 usage(B_FALSE);
4521 }
4522
4523 if (cachefile && do_scan) {
4524 (void) fprintf(stderr, gettext("-c is incompatible with -s\n"));
4525 usage(B_FALSE);
4526 }
4527
4528 if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
4529 (void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
4530 usage(B_FALSE);
4531 }
4532
4533 if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
4534 (void) fprintf(stderr, gettext("-l is only meaningful during "
4535 "an import\n"));
4536 usage(B_FALSE);
4537 }
4538
4539 if ((dryrun || xtreme_rewind) && !do_rewind) {
4540 (void) fprintf(stderr,
4541 gettext("-n or -X only meaningful with -F\n"));
4542 usage(B_FALSE);
4543 }
4544 if (dryrun)
4545 rewind_policy = ZPOOL_TRY_REWIND;
4546 else if (do_rewind)
4547 rewind_policy = ZPOOL_DO_REWIND;
4548 if (xtreme_rewind)
4549 rewind_policy |= ZPOOL_EXTREME_REWIND;
4550
4551 /* In the future, we can capture further policy and include it here */
4552 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
4553 nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
4554 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
4555 rewind_policy) != 0 ||
4556 nvlist_add_boolean_value(policy, ZPOOL_LOAD_RELAX_META,
4557 relax_meta) != 0)
4558 goto error;
4559
4560 /* check argument count */
4561 if (do_all) {
4562 if (argc != 0) {
4563 (void) fprintf(stderr, gettext("too many arguments\n"));
4564 usage(B_FALSE);
4565 }
4566 } else {
4567 if (argc > 2) {
4568 (void) fprintf(stderr, gettext("too many arguments\n"));
4569 usage(B_FALSE);
4570 }
4571 }
4572
4573 /*
4574 * Check for the effective uid. We do this explicitly here because
4575 * otherwise any attempt to discover pools will silently fail.
4576 */
4577 if (argc == 0 && geteuid() != 0) {
4578 (void) fprintf(stderr, gettext("cannot "
4579 "discover pools: permission denied\n"));
4580
4581 free(searchdirs);
4582 nvlist_free(props);
4583 nvlist_free(policy);
4584 return (1);
4585 }
4586
4587 /*
4588 * Depending on the arguments given, we do one of the following:
4589 *
4590 * <none> Iterate through all pools and display information about
4591 * each one.
4592 *
4593 * -a Iterate through all pools and try to import each one.
4594 *
4595 * <id> Find the pool that corresponds to the given GUID/pool
4596 * name and import that one.
4597 *
4598 * -D Above options applies only to destroyed pools.
4599 */
4600 if (argc != 0) {
4601 char *endptr;
4602
4603 errno = 0;
4604 searchguid = strtoull(argv[0], &endptr, 10);
4605 if (errno != 0 || *endptr != '\0') {
4606 searchname = argv[0];
4607 searchguid = 0;
4608 }
4609
4610 /*
4611 * User specified a name or guid. Ensure it's unique.
4612 */
4613 target_exists_args_t search = {searchname, searchguid};
4614 pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
4615 }
4616
4617 /*
4618 * Check the environment for the preferred search path.
4619 */
4620 if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
4621 char *dir, *tmp = NULL;
4622
4623 envdup = strdup(env);
4624
4625 for (dir = strtok_r(envdup, ":", &tmp);
4626 dir != NULL;
4627 dir = strtok_r(NULL, ":", &tmp)) {
4628 searchdirs = safe_realloc(searchdirs,
4629 (nsearch + 1) * sizeof (char *));
4630 searchdirs[nsearch++] = dir;
4631 }
4632 }
4633
4634 idata.path = searchdirs;
4635 idata.paths = nsearch;
4636 idata.poolname = searchname;
4637 idata.guid = searchguid;
4638 idata.cachefile = cachefile;
4639 idata.scan = do_scan;
4640 idata.policy = policy;
4641 idata.do_destroyed = do_destroyed;
4642 idata.do_all = do_all;
4643
4644 libpc_handle_t lpch = {
4645 .lpc_lib_handle = g_zfs,
4646 .lpc_ops = &libzfs_config_ops,
4647 .lpc_printerr = B_TRUE
4648 };
4649 pools = zpool_search_import(&lpch, &idata);
4650
4651 if (pools != NULL && pool_exists &&
4652 (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
4653 (void) fprintf(stderr, gettext("cannot import '%s': "
4654 "a pool with that name already exists\n"),
4655 argv[0]);
4656 (void) fprintf(stderr, gettext("use the form '%s "
4657 "<pool | id> <newpool>' to give it a new name\n"),
4658 "zpool import");
4659 err = 1;
4660 } else if (pools == NULL && pool_exists) {
4661 (void) fprintf(stderr, gettext("cannot import '%s': "
4662 "a pool with that name is already created/imported,\n"),
4663 argv[0]);
4664 (void) fprintf(stderr, gettext("and no additional pools "
4665 "with that name were found\n"));
4666 err = 1;
4667 } else if (pools == NULL) {
4668 if (argc != 0) {
4669 (void) fprintf(stderr, gettext("cannot import '%s': "
4670 "no such pool available\n"), argv[0]);
4671 }
4672 err = 1;
4673 }
4674
4675 if (err == 1) {
4676 free(searchdirs);
4677 free(envdup);
4678 nvlist_free(policy);
4679 nvlist_free(pools);
4680 nvlist_free(props);
4681 return (1);
4682 }
4683
4684 err = import_pools(pools, props, mntopts, flags,
4685 argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL, &idata);
4686
4687 /*
4688 * If we're using the cachefile and we failed to import, then
4689 * fallback to scanning the directory for pools that match
4690 * those in the cachefile.
4691 */
4692 if (err != 0 && cachefile != NULL) {
4693 (void) printf(gettext("cachefile import failed, retrying\n"));
4694
4695 /*
4696 * We use the scan flag to gather the directories that exist
4697 * in the cachefile. If we need to fallback to searching for
4698 * the pool config, we will only search devices in these
4699 * directories.
4700 */
4701 idata.scan = B_TRUE;
4702 nvlist_free(pools);
4703 pools = zpool_search_import(&lpch, &idata);
4704
4705 err = import_pools(pools, props, mntopts, flags,
4706 argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL,
4707 &idata);
4708 }
4709
4710 error:
4711 nvlist_free(props);
4712 nvlist_free(pools);
4713 nvlist_free(policy);
4714 free(searchdirs);
4715 free(envdup);
4716
4717 return (err ? 1 : 0);
4718 }
4719
4720 /*
4721 * zpool sync [-f] [pool] ...
4722 *
4723 * -f (undocumented) force uberblock (and config including zpool cache file)
4724 * update.
4725 *
4726 * Sync the specified pool(s).
4727 * Without arguments "zpool sync" will sync all pools.
4728 * This command initiates TXG sync(s) and will return after the TXG(s) commit.
4729 *
4730 */
4731 static int
zpool_do_sync(int argc,char ** argv)4732 zpool_do_sync(int argc, char **argv)
4733 {
4734 int ret;
4735 boolean_t force = B_FALSE;
4736
4737 /* check options */
4738 while ((ret = getopt(argc, argv, "f")) != -1) {
4739 switch (ret) {
4740 case 'f':
4741 force = B_TRUE;
4742 break;
4743 case '?':
4744 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4745 optopt);
4746 usage(B_FALSE);
4747 }
4748 }
4749
4750 argc -= optind;
4751 argv += optind;
4752
4753 /* if argc == 0 we will execute zpool_sync_one on all pools */
4754 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
4755 B_FALSE, zpool_sync_one, &force);
4756
4757 return (ret);
4758 }
4759
4760 typedef struct iostat_cbdata {
4761 uint64_t cb_flags;
4762 int cb_namewidth;
4763 int cb_iteration;
4764 boolean_t cb_verbose;
4765 boolean_t cb_literal;
4766 boolean_t cb_scripted;
4767 zpool_list_t *cb_list;
4768 vdev_cmd_data_list_t *vcdl;
4769 vdev_cbdata_t cb_vdevs;
4770 } iostat_cbdata_t;
4771
4772 /* iostat labels */
4773 typedef struct name_and_columns {
4774 const char *name; /* Column name */
4775 unsigned int columns; /* Center name to this number of columns */
4776 } name_and_columns_t;
4777
4778 #define IOSTAT_MAX_LABELS 15 /* Max number of labels on one line */
4779
4780 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
4781 {
4782 [IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
4783 {NULL}},
4784 [IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4785 {"asyncq_wait", 2}, {"scrub", 1}, {"trim", 1}, {"rebuild", 1},
4786 {NULL}},
4787 [IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
4788 {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
4789 {"trimq_write", 2}, {"rebuildq_write", 2}, {NULL}},
4790 [IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4791 {"asyncq_wait", 2}, {NULL}},
4792 [IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
4793 {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
4794 {"trim", 2}, {"rebuild", 2}, {NULL}},
4795 };
4796
4797 /* Shorthand - if "columns" field not set, default to 1 column */
4798 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
4799 {
4800 [IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
4801 {"write"}, {NULL}},
4802 [IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4803 {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {"wait"},
4804 {NULL}},
4805 [IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
4806 {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
4807 {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
4808 [IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4809 {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {"rebuild"},
4810 {NULL}},
4811 [IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4812 {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4813 {"ind"}, {"agg"}, {NULL}},
4814 };
4815
4816 static const char *histo_to_title[] = {
4817 [IOS_L_HISTO] = "latency",
4818 [IOS_RQ_HISTO] = "req_size",
4819 };
4820
4821 /*
4822 * Return the number of labels in a null-terminated name_and_columns_t
4823 * array.
4824 *
4825 */
4826 static unsigned int
label_array_len(const name_and_columns_t * labels)4827 label_array_len(const name_and_columns_t *labels)
4828 {
4829 int i = 0;
4830
4831 while (labels[i].name)
4832 i++;
4833
4834 return (i);
4835 }
4836
4837 /*
4838 * Return the number of strings in a null-terminated string array.
4839 * For example:
4840 *
4841 * const char foo[] = {"bar", "baz", NULL}
4842 *
4843 * returns 2
4844 */
4845 static uint64_t
str_array_len(const char * array[])4846 str_array_len(const char *array[])
4847 {
4848 uint64_t i = 0;
4849 while (array[i])
4850 i++;
4851
4852 return (i);
4853 }
4854
4855
4856 /*
4857 * Return a default column width for default/latency/queue columns. This does
4858 * not include histograms, which have their columns autosized.
4859 */
4860 static unsigned int
default_column_width(iostat_cbdata_t * cb,enum iostat_type type)4861 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
4862 {
4863 unsigned long column_width = 5; /* Normal niceprint */
4864 static unsigned long widths[] = {
4865 /*
4866 * Choose some sane default column sizes for printing the
4867 * raw numbers.
4868 */
4869 [IOS_DEFAULT] = 15, /* 1PB capacity */
4870 [IOS_LATENCY] = 10, /* 1B ns = 10sec */
4871 [IOS_QUEUES] = 6, /* 1M queue entries */
4872 [IOS_L_HISTO] = 10, /* 1B ns = 10sec */
4873 [IOS_RQ_HISTO] = 6, /* 1M queue entries */
4874 };
4875
4876 if (cb->cb_literal)
4877 column_width = widths[type];
4878
4879 return (column_width);
4880 }
4881
4882 /*
4883 * Print the column labels, i.e:
4884 *
4885 * capacity operations bandwidth
4886 * alloc free read write read write ...
4887 *
4888 * If force_column_width is set, use it for the column width. If not set, use
4889 * the default column width.
4890 */
4891 static void
print_iostat_labels(iostat_cbdata_t * cb,unsigned int force_column_width,const name_and_columns_t labels[][IOSTAT_MAX_LABELS])4892 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
4893 const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
4894 {
4895 int i, idx, s;
4896 int text_start, rw_column_width, spaces_to_end;
4897 uint64_t flags = cb->cb_flags;
4898 uint64_t f;
4899 unsigned int column_width = force_column_width;
4900
4901 /* For each bit set in flags */
4902 for (f = flags; f; f &= ~(1ULL << idx)) {
4903 idx = lowbit64(f) - 1;
4904 if (!force_column_width)
4905 column_width = default_column_width(cb, idx);
4906 /* Print our top labels centered over "read write" label. */
4907 for (i = 0; i < label_array_len(labels[idx]); i++) {
4908 const char *name = labels[idx][i].name;
4909 /*
4910 * We treat labels[][].columns == 0 as shorthand
4911 * for one column. It makes writing out the label
4912 * tables more concise.
4913 */
4914 unsigned int columns = MAX(1, labels[idx][i].columns);
4915 unsigned int slen = strlen(name);
4916
4917 rw_column_width = (column_width * columns) +
4918 (2 * (columns - 1));
4919
4920 text_start = (int)((rw_column_width) / columns -
4921 slen / columns);
4922 if (text_start < 0)
4923 text_start = 0;
4924
4925 printf(" "); /* Two spaces between columns */
4926
4927 /* Space from beginning of column to label */
4928 for (s = 0; s < text_start; s++)
4929 printf(" ");
4930
4931 printf("%s", name);
4932
4933 /* Print space after label to end of column */
4934 spaces_to_end = rw_column_width - text_start - slen;
4935 if (spaces_to_end < 0)
4936 spaces_to_end = 0;
4937
4938 for (s = 0; s < spaces_to_end; s++)
4939 printf(" ");
4940 }
4941 }
4942 }
4943
4944
4945 /*
4946 * print_cmd_columns - Print custom column titles from -c
4947 *
4948 * If the user specified the "zpool status|iostat -c" then print their custom
4949 * column titles in the header. For example, print_cmd_columns() would print
4950 * the " col1 col2" part of this:
4951 *
4952 * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
4953 * ...
4954 * capacity operations bandwidth
4955 * pool alloc free read write read write col1 col2
4956 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4957 * mypool 269K 1008M 0 0 107 946
4958 * mirror 269K 1008M 0 0 107 946
4959 * sdb - - 0 0 102 473 val1 val2
4960 * sdc - - 0 0 5 473 val1 val2
4961 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4962 */
4963 static void
print_cmd_columns(vdev_cmd_data_list_t * vcdl,int use_dashes)4964 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
4965 {
4966 int i, j;
4967 vdev_cmd_data_t *data = &vcdl->data[0];
4968
4969 if (vcdl->count == 0 || data == NULL)
4970 return;
4971
4972 /*
4973 * Each vdev cmd should have the same column names unless the user did
4974 * something weird with their cmd. Just take the column names from the
4975 * first vdev and assume it works for all of them.
4976 */
4977 for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
4978 printf(" ");
4979 if (use_dashes) {
4980 for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
4981 printf("-");
4982 } else {
4983 (void) printf_color(ANSI_BOLD, "%*s",
4984 vcdl->uniq_cols_width[i],
4985 vcdl->uniq_cols[i]);
4986 }
4987 }
4988 }
4989
4990
4991 /*
4992 * Utility function to print out a line of dashes like:
4993 *
4994 * -------------------------------- ----- ----- ----- ----- -----
4995 *
4996 * ...or a dashed named-row line like:
4997 *
4998 * logs - - - - -
4999 *
5000 * @cb: iostat data
5001 *
5002 * @force_column_width If non-zero, use the value as the column width.
5003 * Otherwise use the default column widths.
5004 *
5005 * @name: Print a dashed named-row line starting
5006 * with @name. Otherwise, print a regular
5007 * dashed line.
5008 */
5009 static void
print_iostat_dashes(iostat_cbdata_t * cb,unsigned int force_column_width,const char * name)5010 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
5011 const char *name)
5012 {
5013 int i;
5014 unsigned int namewidth;
5015 uint64_t flags = cb->cb_flags;
5016 uint64_t f;
5017 int idx;
5018 const name_and_columns_t *labels;
5019 const char *title;
5020
5021
5022 if (cb->cb_flags & IOS_ANYHISTO_M) {
5023 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
5024 } else if (cb->cb_vdevs.cb_names_count) {
5025 title = "vdev";
5026 } else {
5027 title = "pool";
5028 }
5029
5030 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
5031 name ? strlen(name) : 0);
5032
5033
5034 if (name) {
5035 printf("%-*s", namewidth, name);
5036 } else {
5037 for (i = 0; i < namewidth; i++)
5038 (void) printf("-");
5039 }
5040
5041 /* For each bit in flags */
5042 for (f = flags; f; f &= ~(1ULL << idx)) {
5043 unsigned int column_width;
5044 idx = lowbit64(f) - 1;
5045 if (force_column_width)
5046 column_width = force_column_width;
5047 else
5048 column_width = default_column_width(cb, idx);
5049
5050 labels = iostat_bottom_labels[idx];
5051 for (i = 0; i < label_array_len(labels); i++) {
5052 if (name)
5053 printf(" %*s-", column_width - 1, " ");
5054 else
5055 printf(" %.*s", column_width,
5056 "--------------------");
5057 }
5058 }
5059 }
5060
5061
5062 static void
print_iostat_separator_impl(iostat_cbdata_t * cb,unsigned int force_column_width)5063 print_iostat_separator_impl(iostat_cbdata_t *cb,
5064 unsigned int force_column_width)
5065 {
5066 print_iostat_dashes(cb, force_column_width, NULL);
5067 }
5068
5069 static void
print_iostat_separator(iostat_cbdata_t * cb)5070 print_iostat_separator(iostat_cbdata_t *cb)
5071 {
5072 print_iostat_separator_impl(cb, 0);
5073 }
5074
5075 static void
print_iostat_header_impl(iostat_cbdata_t * cb,unsigned int force_column_width,const char * histo_vdev_name)5076 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
5077 const char *histo_vdev_name)
5078 {
5079 unsigned int namewidth;
5080 const char *title;
5081
5082 color_start(ANSI_BOLD);
5083
5084 if (cb->cb_flags & IOS_ANYHISTO_M) {
5085 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
5086 } else if (cb->cb_vdevs.cb_names_count) {
5087 title = "vdev";
5088 } else {
5089 title = "pool";
5090 }
5091
5092 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
5093 histo_vdev_name ? strlen(histo_vdev_name) : 0);
5094
5095 if (histo_vdev_name)
5096 printf("%-*s", namewidth, histo_vdev_name);
5097 else
5098 printf("%*s", namewidth, "");
5099
5100
5101 print_iostat_labels(cb, force_column_width, iostat_top_labels);
5102 printf("\n");
5103
5104 printf("%-*s", namewidth, title);
5105
5106 print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
5107 if (cb->vcdl != NULL)
5108 print_cmd_columns(cb->vcdl, 0);
5109
5110 printf("\n");
5111
5112 print_iostat_separator_impl(cb, force_column_width);
5113
5114 if (cb->vcdl != NULL)
5115 print_cmd_columns(cb->vcdl, 1);
5116
5117 color_end();
5118
5119 printf("\n");
5120 }
5121
5122 static void
print_iostat_header(iostat_cbdata_t * cb)5123 print_iostat_header(iostat_cbdata_t *cb)
5124 {
5125 print_iostat_header_impl(cb, 0, NULL);
5126 }
5127
5128 /*
5129 * Prints a size string (i.e. 120M) with the suffix ("M") colored
5130 * by order of magnitude. Uses column_size to add padding.
5131 */
5132 static void
print_stat_color(const char * statbuf,unsigned int column_size)5133 print_stat_color(const char *statbuf, unsigned int column_size)
5134 {
5135 (void) fputs(" ", stdout);
5136 size_t len = strlen(statbuf);
5137 while (len < column_size) {
5138 (void) fputc(' ', stdout);
5139 column_size--;
5140 }
5141 if (*statbuf == '0') {
5142 color_start(ANSI_GRAY);
5143 (void) fputc('0', stdout);
5144 } else {
5145 for (; *statbuf; statbuf++) {
5146 if (*statbuf == 'K') color_start(ANSI_GREEN);
5147 else if (*statbuf == 'M') color_start(ANSI_YELLOW);
5148 else if (*statbuf == 'G') color_start(ANSI_RED);
5149 else if (*statbuf == 'T') color_start(ANSI_BOLD_BLUE);
5150 else if (*statbuf == 'P') color_start(ANSI_MAGENTA);
5151 else if (*statbuf == 'E') color_start(ANSI_CYAN);
5152 (void) fputc(*statbuf, stdout);
5153 if (--column_size <= 0)
5154 break;
5155 }
5156 }
5157 color_end();
5158 }
5159
5160 /*
5161 * Display a single statistic.
5162 */
5163 static void
print_one_stat(uint64_t value,enum zfs_nicenum_format format,unsigned int column_size,boolean_t scripted)5164 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
5165 unsigned int column_size, boolean_t scripted)
5166 {
5167 char buf[64];
5168
5169 zfs_nicenum_format(value, buf, sizeof (buf), format);
5170
5171 if (scripted)
5172 printf("\t%s", buf);
5173 else
5174 print_stat_color(buf, column_size);
5175 }
5176
5177 /*
5178 * Calculate the default vdev stats
5179 *
5180 * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
5181 * stats into calcvs.
5182 */
5183 static void
calc_default_iostats(vdev_stat_t * oldvs,vdev_stat_t * newvs,vdev_stat_t * calcvs)5184 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
5185 vdev_stat_t *calcvs)
5186 {
5187 int i;
5188
5189 memcpy(calcvs, newvs, sizeof (*calcvs));
5190 for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
5191 calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
5192
5193 for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
5194 calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
5195 }
5196
5197 /*
5198 * Internal representation of the extended iostats data.
5199 *
5200 * The extended iostat stats are exported in nvlists as either uint64_t arrays
5201 * or single uint64_t's. We make both look like arrays to make them easier
5202 * to process. In order to make single uint64_t's look like arrays, we set
5203 * __data to the stat data, and then set *data = &__data with count = 1. Then,
5204 * we can just use *data and count.
5205 */
5206 struct stat_array {
5207 uint64_t *data;
5208 uint_t count; /* Number of entries in data[] */
5209 uint64_t __data; /* Only used when data is a single uint64_t */
5210 };
5211
5212 static uint64_t
stat_histo_max(struct stat_array * nva,unsigned int len)5213 stat_histo_max(struct stat_array *nva, unsigned int len)
5214 {
5215 uint64_t max = 0;
5216 int i;
5217 for (i = 0; i < len; i++)
5218 max = MAX(max, array64_max(nva[i].data, nva[i].count));
5219
5220 return (max);
5221 }
5222
5223 /*
5224 * Helper function to lookup a uint64_t array or uint64_t value and store its
5225 * data as a stat_array. If the nvpair is a single uint64_t value, then we make
5226 * it look like a one element array to make it easier to process.
5227 */
5228 static int
nvpair64_to_stat_array(nvlist_t * nvl,const char * name,struct stat_array * nva)5229 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
5230 struct stat_array *nva)
5231 {
5232 nvpair_t *tmp;
5233 int ret;
5234
5235 verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
5236 switch (nvpair_type(tmp)) {
5237 case DATA_TYPE_UINT64_ARRAY:
5238 ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
5239 break;
5240 case DATA_TYPE_UINT64:
5241 ret = nvpair_value_uint64(tmp, &nva->__data);
5242 nva->data = &nva->__data;
5243 nva->count = 1;
5244 break;
5245 default:
5246 /* Not a uint64_t */
5247 ret = EINVAL;
5248 break;
5249 }
5250
5251 return (ret);
5252 }
5253
5254 /*
5255 * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
5256 * subtract them, and return the results in a newly allocated stat_array.
5257 * You must free the returned array after you are done with it with
5258 * free_calc_stats().
5259 *
5260 * Additionally, you can set "oldnv" to NULL if you simply want the newnv
5261 * values.
5262 */
5263 static struct stat_array *
calc_and_alloc_stats_ex(const char ** names,unsigned int len,nvlist_t * oldnv,nvlist_t * newnv)5264 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
5265 nvlist_t *newnv)
5266 {
5267 nvlist_t *oldnvx = NULL, *newnvx;
5268 struct stat_array *oldnva, *newnva, *calcnva;
5269 int i, j;
5270 unsigned int alloc_size = (sizeof (struct stat_array)) * len;
5271
5272 /* Extract our extended stats nvlist from the main list */
5273 verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5274 &newnvx) == 0);
5275 if (oldnv) {
5276 verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5277 &oldnvx) == 0);
5278 }
5279
5280 newnva = safe_malloc(alloc_size);
5281 oldnva = safe_malloc(alloc_size);
5282 calcnva = safe_malloc(alloc_size);
5283
5284 for (j = 0; j < len; j++) {
5285 verify(nvpair64_to_stat_array(newnvx, names[j],
5286 &newnva[j]) == 0);
5287 calcnva[j].count = newnva[j].count;
5288 alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
5289 calcnva[j].data = safe_malloc(alloc_size);
5290 memcpy(calcnva[j].data, newnva[j].data, alloc_size);
5291
5292 if (oldnvx) {
5293 verify(nvpair64_to_stat_array(oldnvx, names[j],
5294 &oldnva[j]) == 0);
5295 for (i = 0; i < oldnva[j].count; i++)
5296 calcnva[j].data[i] -= oldnva[j].data[i];
5297 }
5298 }
5299 free(newnva);
5300 free(oldnva);
5301 return (calcnva);
5302 }
5303
5304 static void
free_calc_stats(struct stat_array * nva,unsigned int len)5305 free_calc_stats(struct stat_array *nva, unsigned int len)
5306 {
5307 int i;
5308 for (i = 0; i < len; i++)
5309 free(nva[i].data);
5310
5311 free(nva);
5312 }
5313
5314 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)5315 print_iostat_histo(struct stat_array *nva, unsigned int len,
5316 iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
5317 double scale)
5318 {
5319 int i, j;
5320 char buf[6];
5321 uint64_t val;
5322 enum zfs_nicenum_format format;
5323 unsigned int buckets;
5324 unsigned int start_bucket;
5325
5326 if (cb->cb_literal)
5327 format = ZFS_NICENUM_RAW;
5328 else
5329 format = ZFS_NICENUM_1024;
5330
5331 /* All these histos are the same size, so just use nva[0].count */
5332 buckets = nva[0].count;
5333
5334 if (cb->cb_flags & IOS_RQ_HISTO_M) {
5335 /* Start at 512 - req size should never be lower than this */
5336 start_bucket = 9;
5337 } else {
5338 start_bucket = 0;
5339 }
5340
5341 for (j = start_bucket; j < buckets; j++) {
5342 /* Print histogram bucket label */
5343 if (cb->cb_flags & IOS_L_HISTO_M) {
5344 /* Ending range of this bucket */
5345 val = (1UL << (j + 1)) - 1;
5346 zfs_nicetime(val, buf, sizeof (buf));
5347 } else {
5348 /* Request size (starting range of bucket) */
5349 val = (1UL << j);
5350 zfs_nicenum(val, buf, sizeof (buf));
5351 }
5352
5353 if (cb->cb_scripted)
5354 printf("%llu", (u_longlong_t)val);
5355 else
5356 printf("%-*s", namewidth, buf);
5357
5358 /* Print the values on the line */
5359 for (i = 0; i < len; i++) {
5360 print_one_stat(nva[i].data[j] * scale, format,
5361 column_width, cb->cb_scripted);
5362 }
5363 printf("\n");
5364 }
5365 }
5366
5367 static void
print_solid_separator(unsigned int length)5368 print_solid_separator(unsigned int length)
5369 {
5370 while (length--)
5371 printf("-");
5372 printf("\n");
5373 }
5374
5375 static void
print_iostat_histos(iostat_cbdata_t * cb,nvlist_t * oldnv,nvlist_t * newnv,double scale,const char * name)5376 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
5377 nvlist_t *newnv, double scale, const char *name)
5378 {
5379 unsigned int column_width;
5380 unsigned int namewidth;
5381 unsigned int entire_width;
5382 enum iostat_type type;
5383 struct stat_array *nva;
5384 const char **names;
5385 unsigned int names_len;
5386
5387 /* What type of histo are we? */
5388 type = IOS_HISTO_IDX(cb->cb_flags);
5389
5390 /* Get NULL-terminated array of nvlist names for our histo */
5391 names = vsx_type_to_nvlist[type];
5392 names_len = str_array_len(names); /* num of names */
5393
5394 nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
5395
5396 if (cb->cb_literal) {
5397 column_width = MAX(5,
5398 (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
5399 } else {
5400 column_width = 5;
5401 }
5402
5403 namewidth = MAX(cb->cb_namewidth,
5404 strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
5405
5406 /*
5407 * Calculate the entire line width of what we're printing. The
5408 * +2 is for the two spaces between columns:
5409 */
5410 /* read write */
5411 /* ----- ----- */
5412 /* |___| <---------- column_width */
5413 /* */
5414 /* |__________| <--- entire_width */
5415 /* */
5416 entire_width = namewidth + (column_width + 2) *
5417 label_array_len(iostat_bottom_labels[type]);
5418
5419 if (cb->cb_scripted)
5420 printf("%s\n", name);
5421 else
5422 print_iostat_header_impl(cb, column_width, name);
5423
5424 print_iostat_histo(nva, names_len, cb, column_width,
5425 namewidth, scale);
5426
5427 free_calc_stats(nva, names_len);
5428 if (!cb->cb_scripted)
5429 print_solid_separator(entire_width);
5430 }
5431
5432 /*
5433 * Calculate the average latency of a power-of-two latency histogram
5434 */
5435 static uint64_t
single_histo_average(uint64_t * histo,unsigned int buckets)5436 single_histo_average(uint64_t *histo, unsigned int buckets)
5437 {
5438 int i;
5439 uint64_t count = 0, total = 0;
5440
5441 for (i = 0; i < buckets; i++) {
5442 /*
5443 * Our buckets are power-of-two latency ranges. Use the
5444 * midpoint latency of each bucket to calculate the average.
5445 * For example:
5446 *
5447 * Bucket Midpoint
5448 * 8ns-15ns: 12ns
5449 * 16ns-31ns: 24ns
5450 * ...
5451 */
5452 if (histo[i] != 0) {
5453 total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
5454 count += histo[i];
5455 }
5456 }
5457
5458 /* Prevent divide by zero */
5459 return (count == 0 ? 0 : total / count);
5460 }
5461
5462 static void
print_iostat_queues(iostat_cbdata_t * cb,nvlist_t * newnv)5463 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *newnv)
5464 {
5465 const char *names[] = {
5466 ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
5467 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
5468 ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
5469 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
5470 ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
5471 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
5472 ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
5473 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
5474 ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
5475 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
5476 ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
5477 ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
5478 ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
5479 ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
5480 };
5481
5482 struct stat_array *nva;
5483
5484 unsigned int column_width = default_column_width(cb, IOS_QUEUES);
5485 enum zfs_nicenum_format format;
5486
5487 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
5488
5489 if (cb->cb_literal)
5490 format = ZFS_NICENUM_RAW;
5491 else
5492 format = ZFS_NICENUM_1024;
5493
5494 for (int i = 0; i < ARRAY_SIZE(names); i++) {
5495 uint64_t val = nva[i].data[0];
5496 print_one_stat(val, format, column_width, cb->cb_scripted);
5497 }
5498
5499 free_calc_stats(nva, ARRAY_SIZE(names));
5500 }
5501
5502 static void
print_iostat_latency(iostat_cbdata_t * cb,nvlist_t * oldnv,nvlist_t * newnv)5503 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
5504 nvlist_t *newnv)
5505 {
5506 int i;
5507 uint64_t val;
5508 const char *names[] = {
5509 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
5510 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
5511 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
5512 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
5513 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
5514 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
5515 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
5516 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
5517 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
5518 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
5519 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
5520 };
5521 struct stat_array *nva;
5522
5523 unsigned int column_width = default_column_width(cb, IOS_LATENCY);
5524 enum zfs_nicenum_format format;
5525
5526 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
5527
5528 if (cb->cb_literal)
5529 format = ZFS_NICENUM_RAWTIME;
5530 else
5531 format = ZFS_NICENUM_TIME;
5532
5533 /* Print our avg latencies on the line */
5534 for (i = 0; i < ARRAY_SIZE(names); i++) {
5535 /* Compute average latency for a latency histo */
5536 val = single_histo_average(nva[i].data, nva[i].count);
5537 print_one_stat(val, format, column_width, cb->cb_scripted);
5538 }
5539 free_calc_stats(nva, ARRAY_SIZE(names));
5540 }
5541
5542 /*
5543 * Print default statistics (capacity/operations/bandwidth)
5544 */
5545 static void
print_iostat_default(vdev_stat_t * vs,iostat_cbdata_t * cb,double scale)5546 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
5547 {
5548 unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
5549 enum zfs_nicenum_format format;
5550 char na; /* char to print for "not applicable" values */
5551
5552 if (cb->cb_literal) {
5553 format = ZFS_NICENUM_RAW;
5554 na = '0';
5555 } else {
5556 format = ZFS_NICENUM_1024;
5557 na = '-';
5558 }
5559
5560 /* only toplevel vdevs have capacity stats */
5561 if (vs->vs_space == 0) {
5562 if (cb->cb_scripted)
5563 printf("\t%c\t%c", na, na);
5564 else
5565 printf(" %*c %*c", column_width, na, column_width,
5566 na);
5567 } else {
5568 print_one_stat(vs->vs_alloc, format, column_width,
5569 cb->cb_scripted);
5570 print_one_stat(vs->vs_space - vs->vs_alloc, format,
5571 column_width, cb->cb_scripted);
5572 }
5573
5574 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
5575 format, column_width, cb->cb_scripted);
5576 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
5577 format, column_width, cb->cb_scripted);
5578 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
5579 format, column_width, cb->cb_scripted);
5580 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
5581 format, column_width, cb->cb_scripted);
5582 }
5583
5584 static const char *const class_name[] = {
5585 VDEV_ALLOC_BIAS_DEDUP,
5586 VDEV_ALLOC_BIAS_SPECIAL,
5587 VDEV_ALLOC_CLASS_LOGS
5588 };
5589
5590 /*
5591 * Print out all the statistics for the given vdev. This can either be the
5592 * toplevel configuration, or called recursively. If 'name' is NULL, then this
5593 * is a verbose output, and we don't want to display the toplevel pool stats.
5594 *
5595 * Returns the number of stat lines printed.
5596 */
5597 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)5598 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
5599 nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
5600 {
5601 nvlist_t **oldchild, **newchild;
5602 uint_t c, children, oldchildren;
5603 vdev_stat_t *oldvs, *newvs, *calcvs;
5604 vdev_stat_t zerovs = { 0 };
5605 char *vname;
5606 int i;
5607 int ret = 0;
5608 uint64_t tdelta;
5609 double scale;
5610
5611 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
5612 return (ret);
5613
5614 calcvs = safe_malloc(sizeof (*calcvs));
5615
5616 if (oldnv != NULL) {
5617 verify(nvlist_lookup_uint64_array(oldnv,
5618 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
5619 } else {
5620 oldvs = &zerovs;
5621 }
5622
5623 /* Do we only want to see a specific vdev? */
5624 for (i = 0; i < cb->cb_vdevs.cb_names_count; i++) {
5625 /* Yes we do. Is this the vdev? */
5626 if (strcmp(name, cb->cb_vdevs.cb_names[i]) == 0) {
5627 /*
5628 * This is our vdev. Since it is the only vdev we
5629 * will be displaying, make depth = 0 so that it
5630 * doesn't get indented.
5631 */
5632 depth = 0;
5633 break;
5634 }
5635 }
5636
5637 if (cb->cb_vdevs.cb_names_count && (i == cb->cb_vdevs.cb_names_count)) {
5638 /* Couldn't match the name */
5639 goto children;
5640 }
5641
5642
5643 verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
5644 (uint64_t **)&newvs, &c) == 0);
5645
5646 /*
5647 * Print the vdev name unless it's is a histogram. Histograms
5648 * display the vdev name in the header itself.
5649 */
5650 if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
5651 if (cb->cb_scripted) {
5652 printf("%s", name);
5653 } else {
5654 if (strlen(name) + depth > cb->cb_namewidth)
5655 (void) printf("%*s%s", depth, "", name);
5656 else
5657 (void) printf("%*s%s%*s", depth, "", name,
5658 (int)(cb->cb_namewidth - strlen(name) -
5659 depth), "");
5660 }
5661 }
5662
5663 /* Calculate our scaling factor */
5664 tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
5665 if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
5666 /*
5667 * If we specify printing histograms with no time interval, then
5668 * print the histogram numbers over the entire lifetime of the
5669 * vdev.
5670 */
5671 scale = 1;
5672 } else {
5673 if (tdelta == 0)
5674 scale = 1.0;
5675 else
5676 scale = (double)NANOSEC / tdelta;
5677 }
5678
5679 if (cb->cb_flags & IOS_DEFAULT_M) {
5680 calc_default_iostats(oldvs, newvs, calcvs);
5681 print_iostat_default(calcvs, cb, scale);
5682 }
5683 if (cb->cb_flags & IOS_LATENCY_M)
5684 print_iostat_latency(cb, oldnv, newnv);
5685 if (cb->cb_flags & IOS_QUEUES_M)
5686 print_iostat_queues(cb, newnv);
5687 if (cb->cb_flags & IOS_ANYHISTO_M) {
5688 printf("\n");
5689 print_iostat_histos(cb, oldnv, newnv, scale, name);
5690 }
5691
5692 if (cb->vcdl != NULL) {
5693 const char *path;
5694 if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
5695 &path) == 0) {
5696 printf(" ");
5697 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
5698 }
5699 }
5700
5701 if (!(cb->cb_flags & IOS_ANYHISTO_M))
5702 printf("\n");
5703
5704 ret++;
5705
5706 children:
5707
5708 free(calcvs);
5709
5710 if (!cb->cb_verbose)
5711 return (ret);
5712
5713 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
5714 &newchild, &children) != 0)
5715 return (ret);
5716
5717 if (oldnv) {
5718 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
5719 &oldchild, &oldchildren) != 0)
5720 return (ret);
5721
5722 children = MIN(oldchildren, children);
5723 }
5724
5725 /*
5726 * print normal top-level devices
5727 */
5728 for (c = 0; c < children; c++) {
5729 uint64_t ishole = B_FALSE, islog = B_FALSE;
5730
5731 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
5732 &ishole);
5733
5734 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
5735 &islog);
5736
5737 if (ishole || islog)
5738 continue;
5739
5740 if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
5741 continue;
5742
5743 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5744 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5745 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
5746 newchild[c], cb, depth + 2);
5747 free(vname);
5748 }
5749
5750 /*
5751 * print all other top-level devices
5752 */
5753 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
5754 boolean_t printed = B_FALSE;
5755
5756 for (c = 0; c < children; c++) {
5757 uint64_t islog = B_FALSE;
5758 const char *bias = NULL;
5759 const char *type = NULL;
5760
5761 (void) nvlist_lookup_uint64(newchild[c],
5762 ZPOOL_CONFIG_IS_LOG, &islog);
5763 if (islog) {
5764 bias = VDEV_ALLOC_CLASS_LOGS;
5765 } else {
5766 (void) nvlist_lookup_string(newchild[c],
5767 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
5768 (void) nvlist_lookup_string(newchild[c],
5769 ZPOOL_CONFIG_TYPE, &type);
5770 }
5771 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
5772 continue;
5773 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
5774 continue;
5775
5776 if (!printed) {
5777 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
5778 !cb->cb_scripted &&
5779 !cb->cb_vdevs.cb_names) {
5780 print_iostat_dashes(cb, 0,
5781 class_name[n]);
5782 }
5783 printf("\n");
5784 printed = B_TRUE;
5785 }
5786
5787 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5788 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5789 ret += print_vdev_stats(zhp, vname, oldnv ?
5790 oldchild[c] : NULL, newchild[c], cb, depth + 2);
5791 free(vname);
5792 }
5793 }
5794
5795 /*
5796 * Include level 2 ARC devices in iostat output
5797 */
5798 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
5799 &newchild, &children) != 0)
5800 return (ret);
5801
5802 if (oldnv) {
5803 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
5804 &oldchild, &oldchildren) != 0)
5805 return (ret);
5806
5807 children = MIN(oldchildren, children);
5808 }
5809
5810 if (children > 0) {
5811 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
5812 !cb->cb_vdevs.cb_names) {
5813 print_iostat_dashes(cb, 0, "cache");
5814 }
5815 printf("\n");
5816
5817 for (c = 0; c < children; c++) {
5818 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5819 cb->cb_vdevs.cb_name_flags);
5820 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
5821 : NULL, newchild[c], cb, depth + 2);
5822 free(vname);
5823 }
5824 }
5825
5826 return (ret);
5827 }
5828
5829 /*
5830 * Callback to print out the iostats for the given pool.
5831 */
5832 static int
print_iostat(zpool_handle_t * zhp,void * data)5833 print_iostat(zpool_handle_t *zhp, void *data)
5834 {
5835 iostat_cbdata_t *cb = data;
5836 nvlist_t *oldconfig, *newconfig;
5837 nvlist_t *oldnvroot, *newnvroot;
5838 int ret;
5839
5840 newconfig = zpool_get_config(zhp, &oldconfig);
5841
5842 if (cb->cb_iteration == 1)
5843 oldconfig = NULL;
5844
5845 verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
5846 &newnvroot) == 0);
5847
5848 if (oldconfig == NULL)
5849 oldnvroot = NULL;
5850 else
5851 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
5852 &oldnvroot) == 0);
5853
5854 ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
5855 cb, 0);
5856 if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
5857 !cb->cb_scripted && cb->cb_verbose &&
5858 !cb->cb_vdevs.cb_names_count) {
5859 print_iostat_separator(cb);
5860 if (cb->vcdl != NULL) {
5861 print_cmd_columns(cb->vcdl, 1);
5862 }
5863 printf("\n");
5864 }
5865
5866 return (ret);
5867 }
5868
5869 static int
get_columns(void)5870 get_columns(void)
5871 {
5872 struct winsize ws;
5873 int columns = 80;
5874 int error;
5875
5876 if (isatty(STDOUT_FILENO)) {
5877 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
5878 if (error == 0 && ws.ws_col > 0)
5879 columns = ws.ws_col;
5880 } else {
5881 columns = 999;
5882 }
5883
5884 return (columns);
5885 }
5886
5887 /*
5888 * Return the required length of the pool/vdev name column. The minimum
5889 * allowed width and output formatting flags must be provided.
5890 */
5891 static int
get_namewidth(zpool_handle_t * zhp,int min_width,int flags,boolean_t verbose)5892 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
5893 {
5894 nvlist_t *config, *nvroot;
5895 int width = min_width;
5896
5897 if ((config = zpool_get_config(zhp, NULL)) != NULL) {
5898 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5899 &nvroot) == 0);
5900 size_t poolname_len = strlen(zpool_get_name(zhp));
5901 if (verbose == B_FALSE) {
5902 width = MAX(poolname_len, min_width);
5903 } else {
5904 width = MAX(poolname_len,
5905 max_width(zhp, nvroot, 0, min_width, flags));
5906 }
5907 }
5908
5909 return (width);
5910 }
5911
5912 /*
5913 * Parse the input string, get the 'interval' and 'count' value if there is one.
5914 */
5915 static void
get_interval_count(int * argcp,char ** argv,float * iv,unsigned long * cnt)5916 get_interval_count(int *argcp, char **argv, float *iv,
5917 unsigned long *cnt)
5918 {
5919 float interval = 0;
5920 unsigned long count = 0;
5921 int argc = *argcp;
5922
5923 /*
5924 * Determine if the last argument is an integer or a pool name
5925 */
5926 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5927 char *end;
5928
5929 errno = 0;
5930 interval = strtof(argv[argc - 1], &end);
5931
5932 if (*end == '\0' && errno == 0) {
5933 if (interval == 0) {
5934 (void) fprintf(stderr, gettext(
5935 "interval cannot be zero\n"));
5936 usage(B_FALSE);
5937 }
5938 /*
5939 * Ignore the last parameter
5940 */
5941 argc--;
5942 } else {
5943 /*
5944 * If this is not a valid number, just plow on. The
5945 * user will get a more informative error message later
5946 * on.
5947 */
5948 interval = 0;
5949 }
5950 }
5951
5952 /*
5953 * If the last argument is also an integer, then we have both a count
5954 * and an interval.
5955 */
5956 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5957 char *end;
5958
5959 errno = 0;
5960 count = interval;
5961 interval = strtof(argv[argc - 1], &end);
5962
5963 if (*end == '\0' && errno == 0) {
5964 if (interval == 0) {
5965 (void) fprintf(stderr, gettext(
5966 "interval cannot be zero\n"));
5967 usage(B_FALSE);
5968 }
5969
5970 /*
5971 * Ignore the last parameter
5972 */
5973 argc--;
5974 } else {
5975 interval = 0;
5976 }
5977 }
5978
5979 *iv = interval;
5980 *cnt = count;
5981 *argcp = argc;
5982 }
5983
5984 static void
get_timestamp_arg(char c)5985 get_timestamp_arg(char c)
5986 {
5987 if (c == 'u')
5988 timestamp_fmt = UDATE;
5989 else if (c == 'd')
5990 timestamp_fmt = DDATE;
5991 else
5992 usage(B_FALSE);
5993 }
5994
5995 /*
5996 * Return stat flags that are supported by all pools by both the module and
5997 * zpool iostat. "*data" should be initialized to all 0xFFs before running.
5998 * It will get ANDed down until only the flags that are supported on all pools
5999 * remain.
6000 */
6001 static int
get_stat_flags_cb(zpool_handle_t * zhp,void * data)6002 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
6003 {
6004 uint64_t *mask = data;
6005 nvlist_t *config, *nvroot, *nvx;
6006 uint64_t flags = 0;
6007 int i, j;
6008
6009 config = zpool_get_config(zhp, NULL);
6010 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
6011 &nvroot) == 0);
6012
6013 /* Default stats are always supported, but for completeness.. */
6014 if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
6015 flags |= IOS_DEFAULT_M;
6016
6017 /* Get our extended stats nvlist from the main list */
6018 if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
6019 &nvx) != 0) {
6020 /*
6021 * No extended stats; they're probably running an older
6022 * module. No big deal, we support that too.
6023 */
6024 goto end;
6025 }
6026
6027 /* For each extended stat, make sure all its nvpairs are supported */
6028 for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
6029 if (!vsx_type_to_nvlist[j][0])
6030 continue;
6031
6032 /* Start off by assuming the flag is supported, then check */
6033 flags |= (1ULL << j);
6034 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
6035 if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
6036 /* flag isn't supported */
6037 flags = flags & ~(1ULL << j);
6038 break;
6039 }
6040 }
6041 }
6042 end:
6043 *mask = *mask & flags;
6044 return (0);
6045 }
6046
6047 /*
6048 * Return a bitmask of stats that are supported on all pools by both the module
6049 * and zpool iostat.
6050 */
6051 static uint64_t
get_stat_flags(zpool_list_t * list)6052 get_stat_flags(zpool_list_t *list)
6053 {
6054 uint64_t mask = -1;
6055
6056 /*
6057 * get_stat_flags_cb() will lop off bits from "mask" until only the
6058 * flags that are supported on all pools remain.
6059 */
6060 (void) pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
6061 return (mask);
6062 }
6063
6064 /*
6065 * Return 1 if cb_data->cb_names[0] is this vdev's name, 0 otherwise.
6066 */
6067 static int
is_vdev_cb(void * zhp_data,nvlist_t * nv,void * cb_data)6068 is_vdev_cb(void *zhp_data, nvlist_t *nv, void *cb_data)
6069 {
6070 uint64_t guid;
6071 vdev_cbdata_t *cb = cb_data;
6072 zpool_handle_t *zhp = zhp_data;
6073
6074 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
6075 return (0);
6076
6077 return (guid == zpool_vdev_path_to_guid(zhp, cb->cb_names[0]));
6078 }
6079
6080 /*
6081 * Returns 1 if cb_data->cb_names[0] is a vdev name, 0 otherwise.
6082 */
6083 static int
is_vdev(zpool_handle_t * zhp,void * cb_data)6084 is_vdev(zpool_handle_t *zhp, void *cb_data)
6085 {
6086 return (for_each_vdev(zhp, is_vdev_cb, cb_data));
6087 }
6088
6089 /*
6090 * Check if vdevs are in a pool
6091 *
6092 * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
6093 * return 0. If pool_name is NULL, then search all pools.
6094 */
6095 static int
are_vdevs_in_pool(int argc,char ** argv,char * pool_name,vdev_cbdata_t * cb)6096 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
6097 vdev_cbdata_t *cb)
6098 {
6099 char **tmp_name;
6100 int ret = 0;
6101 int i;
6102 int pool_count = 0;
6103
6104 if ((argc == 0) || !*argv)
6105 return (0);
6106
6107 if (pool_name)
6108 pool_count = 1;
6109
6110 /* Temporarily hijack cb_names for a second... */
6111 tmp_name = cb->cb_names;
6112
6113 /* Go though our list of prospective vdev names */
6114 for (i = 0; i < argc; i++) {
6115 cb->cb_names = argv + i;
6116
6117 /* Is this name a vdev in our pools? */
6118 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
6119 ZFS_TYPE_POOL, B_FALSE, is_vdev, cb);
6120 if (!ret) {
6121 /* No match */
6122 break;
6123 }
6124 }
6125
6126 cb->cb_names = tmp_name;
6127
6128 return (ret);
6129 }
6130
6131 static int
is_pool_cb(zpool_handle_t * zhp,void * data)6132 is_pool_cb(zpool_handle_t *zhp, void *data)
6133 {
6134 char *name = data;
6135 if (strcmp(name, zpool_get_name(zhp)) == 0)
6136 return (1);
6137
6138 return (0);
6139 }
6140
6141 /*
6142 * Do we have a pool named *name? If so, return 1, otherwise 0.
6143 */
6144 static int
is_pool(char * name)6145 is_pool(char *name)
6146 {
6147 return (for_each_pool(0, NULL, B_TRUE, NULL, ZFS_TYPE_POOL, B_FALSE,
6148 is_pool_cb, name));
6149 }
6150
6151 /* Are all our argv[] strings pool names? If so return 1, 0 otherwise. */
6152 static int
are_all_pools(int argc,char ** argv)6153 are_all_pools(int argc, char **argv)
6154 {
6155 if ((argc == 0) || !*argv)
6156 return (0);
6157
6158 while (--argc >= 0)
6159 if (!is_pool(argv[argc]))
6160 return (0);
6161
6162 return (1);
6163 }
6164
6165 /*
6166 * Helper function to print out vdev/pool names we can't resolve. Used for an
6167 * error message.
6168 */
6169 static void
error_list_unresolved_vdevs(int argc,char ** argv,char * pool_name,vdev_cbdata_t * cb)6170 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
6171 vdev_cbdata_t *cb)
6172 {
6173 int i;
6174 char *name;
6175 char *str;
6176 for (i = 0; i < argc; i++) {
6177 name = argv[i];
6178
6179 if (is_pool(name))
6180 str = gettext("pool");
6181 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
6182 str = gettext("vdev in this pool");
6183 else if (are_vdevs_in_pool(1, &name, NULL, cb))
6184 str = gettext("vdev in another pool");
6185 else
6186 str = gettext("unknown");
6187
6188 fprintf(stderr, "\t%s (%s)\n", name, str);
6189 }
6190 }
6191
6192 /*
6193 * Same as get_interval_count(), but with additional checks to not misinterpret
6194 * guids as interval/count values. Assumes VDEV_NAME_GUID is set in
6195 * cb.cb_vdevs.cb_name_flags.
6196 */
6197 static void
get_interval_count_filter_guids(int * argc,char ** argv,float * interval,unsigned long * count,iostat_cbdata_t * cb)6198 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
6199 unsigned long *count, iostat_cbdata_t *cb)
6200 {
6201 int argc_for_interval = 0;
6202
6203 /* Is the last arg an interval value? Or a guid? */
6204 if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL,
6205 &cb->cb_vdevs)) {
6206 /*
6207 * The last arg is not a guid, so it's probably an
6208 * interval value.
6209 */
6210 argc_for_interval++;
6211
6212 if (*argc >= 2 &&
6213 !are_vdevs_in_pool(1, &argv[*argc - 2], NULL,
6214 &cb->cb_vdevs)) {
6215 /*
6216 * The 2nd to last arg is not a guid, so it's probably
6217 * an interval value.
6218 */
6219 argc_for_interval++;
6220 }
6221 }
6222
6223 /* Point to our list of possible intervals */
6224 char **tmpargv = &argv[*argc - argc_for_interval];
6225
6226 *argc = *argc - argc_for_interval;
6227 get_interval_count(&argc_for_interval, tmpargv,
6228 interval, count);
6229 }
6230
6231 /*
6232 * Terminal height, in rows. Returns -1 if stdout is not connected to a TTY or
6233 * if we were unable to determine its size.
6234 */
6235 static int
terminal_height(void)6236 terminal_height(void)
6237 {
6238 struct winsize win;
6239
6240 if (isatty(STDOUT_FILENO) == 0)
6241 return (-1);
6242
6243 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_row > 0)
6244 return (win.ws_row);
6245
6246 return (-1);
6247 }
6248
6249 /*
6250 * Run one of the zpool status/iostat -c scripts with the help (-h) option and
6251 * print the result.
6252 *
6253 * name: Short name of the script ('iostat').
6254 * path: Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
6255 */
6256 static void
print_zpool_script_help(char * name,char * path)6257 print_zpool_script_help(char *name, char *path)
6258 {
6259 char *argv[] = {path, (char *)"-h", NULL};
6260 char **lines = NULL;
6261 int lines_cnt = 0;
6262 int rc;
6263
6264 rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
6265 &lines_cnt);
6266 if (rc != 0 || lines == NULL || lines_cnt <= 0) {
6267 if (lines != NULL)
6268 libzfs_free_str_array(lines, lines_cnt);
6269 return;
6270 }
6271
6272 for (int i = 0; i < lines_cnt; i++)
6273 if (!is_blank_str(lines[i]))
6274 printf(" %-14s %s\n", name, lines[i]);
6275
6276 libzfs_free_str_array(lines, lines_cnt);
6277 }
6278
6279 /*
6280 * Go though the zpool status/iostat -c scripts in the user's path, run their
6281 * help option (-h), and print out the results.
6282 */
6283 static void
print_zpool_dir_scripts(char * dirpath)6284 print_zpool_dir_scripts(char *dirpath)
6285 {
6286 DIR *dir;
6287 struct dirent *ent;
6288 char fullpath[MAXPATHLEN];
6289 struct stat dir_stat;
6290
6291 if ((dir = opendir(dirpath)) != NULL) {
6292 /* print all the files and directories within directory */
6293 while ((ent = readdir(dir)) != NULL) {
6294 if (snprintf(fullpath, sizeof (fullpath), "%s/%s",
6295 dirpath, ent->d_name) >= sizeof (fullpath)) {
6296 (void) fprintf(stderr,
6297 gettext("internal error: "
6298 "ZPOOL_SCRIPTS_PATH too large.\n"));
6299 exit(1);
6300 }
6301
6302 /* Print the scripts */
6303 if (stat(fullpath, &dir_stat) == 0)
6304 if (dir_stat.st_mode & S_IXUSR &&
6305 S_ISREG(dir_stat.st_mode))
6306 print_zpool_script_help(ent->d_name,
6307 fullpath);
6308 }
6309 (void) closedir(dir);
6310 }
6311 }
6312
6313 /*
6314 * Print out help text for all zpool status/iostat -c scripts.
6315 */
6316 static void
print_zpool_script_list(const char * subcommand)6317 print_zpool_script_list(const char *subcommand)
6318 {
6319 char *dir, *sp, *tmp;
6320
6321 printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
6322
6323 sp = zpool_get_cmd_search_path();
6324 if (sp == NULL)
6325 return;
6326
6327 for (dir = strtok_r(sp, ":", &tmp);
6328 dir != NULL;
6329 dir = strtok_r(NULL, ":", &tmp))
6330 print_zpool_dir_scripts(dir);
6331
6332 free(sp);
6333 }
6334
6335 /*
6336 * Set the minimum pool/vdev name column width. The width must be at least 10,
6337 * but may be as large as the column width - 42 so it still fits on one line.
6338 * NOTE: 42 is the width of the default capacity/operations/bandwidth output
6339 */
6340 static int
get_namewidth_iostat(zpool_handle_t * zhp,void * data)6341 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
6342 {
6343 iostat_cbdata_t *cb = data;
6344 int width, available_width;
6345
6346 /*
6347 * get_namewidth() returns the maximum width of any name in that column
6348 * for any pool/vdev/device line that will be output.
6349 */
6350 width = get_namewidth(zhp, cb->cb_namewidth,
6351 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
6352
6353 /*
6354 * The width we are calculating is the width of the header and also the
6355 * padding width for names that are less than maximum width. The stats
6356 * take up 42 characters, so the width available for names is:
6357 */
6358 available_width = get_columns() - 42;
6359
6360 /*
6361 * If the maximum width fits on a screen, then great! Make everything
6362 * line up by justifying all lines to the same width. If that max
6363 * width is larger than what's available, the name plus stats won't fit
6364 * on one line, and justifying to that width would cause every line to
6365 * wrap on the screen. We only want lines with long names to wrap.
6366 * Limit the padding to what won't wrap.
6367 */
6368 if (width > available_width)
6369 width = available_width;
6370
6371 /*
6372 * And regardless of whatever the screen width is (get_columns can
6373 * return 0 if the width is not known or less than 42 for a narrow
6374 * terminal) have the width be a minimum of 10.
6375 */
6376 if (width < 10)
6377 width = 10;
6378
6379 /* Save the calculated width */
6380 cb->cb_namewidth = width;
6381
6382 return (0);
6383 }
6384
6385 /*
6386 * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
6387 * [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
6388 * [interval [count]]
6389 *
6390 * -c CMD For each vdev, run command CMD
6391 * -g Display guid for individual vdev name.
6392 * -L Follow links when resolving vdev path name.
6393 * -P Display full path for vdev name.
6394 * -v Display statistics for individual vdevs
6395 * -h Display help
6396 * -p Display values in parsable (exact) format.
6397 * -H Scripted mode. Don't display headers, and separate properties
6398 * by a single tab.
6399 * -l Display average latency
6400 * -q Display queue depths
6401 * -w Display latency histograms
6402 * -r Display request size histogram
6403 * -T Display a timestamp in date(1) or Unix format
6404 * -n Only print headers once
6405 *
6406 * This command can be tricky because we want to be able to deal with pool
6407 * creation/destruction as well as vdev configuration changes. The bulk of this
6408 * processing is handled by the pool_list_* routines in zpool_iter.c. We rely
6409 * on pool_list_refresh() to detect the addition and removal of pools.
6410 * Configuration changes are all handled within libzfs.
6411 */
6412 int
zpool_do_iostat(int argc,char ** argv)6413 zpool_do_iostat(int argc, char **argv)
6414 {
6415 int c;
6416 int ret;
6417 float interval = 0;
6418 unsigned long count = 0;
6419 zpool_list_t *list;
6420 boolean_t verbose = B_FALSE;
6421 boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
6422 boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
6423 boolean_t omit_since_boot = B_FALSE;
6424 boolean_t guid = B_FALSE;
6425 boolean_t follow_links = B_FALSE;
6426 boolean_t full_name = B_FALSE;
6427 boolean_t headers_once = B_FALSE;
6428 iostat_cbdata_t cb = { 0 };
6429 char *cmd = NULL;
6430
6431 /* Used for printing error message */
6432 const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
6433 [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
6434
6435 uint64_t unsupported_flags;
6436
6437 /* check options */
6438 while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwnH")) != -1) {
6439 switch (c) {
6440 case 'c':
6441 if (cmd != NULL) {
6442 fprintf(stderr,
6443 gettext("Can't set -c flag twice\n"));
6444 exit(1);
6445 }
6446
6447 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
6448 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
6449 fprintf(stderr, gettext(
6450 "Can't run -c, disabled by "
6451 "ZPOOL_SCRIPTS_ENABLED.\n"));
6452 exit(1);
6453 }
6454
6455 if ((getuid() <= 0 || geteuid() <= 0) &&
6456 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
6457 fprintf(stderr, gettext(
6458 "Can't run -c with root privileges "
6459 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
6460 exit(1);
6461 }
6462 cmd = optarg;
6463 verbose = B_TRUE;
6464 break;
6465 case 'g':
6466 guid = B_TRUE;
6467 break;
6468 case 'L':
6469 follow_links = B_TRUE;
6470 break;
6471 case 'P':
6472 full_name = B_TRUE;
6473 break;
6474 case 'T':
6475 get_timestamp_arg(*optarg);
6476 break;
6477 case 'v':
6478 verbose = B_TRUE;
6479 break;
6480 case 'p':
6481 parsable = B_TRUE;
6482 break;
6483 case 'l':
6484 latency = B_TRUE;
6485 break;
6486 case 'q':
6487 queues = B_TRUE;
6488 break;
6489 case 'H':
6490 scripted = B_TRUE;
6491 break;
6492 case 'w':
6493 l_histo = B_TRUE;
6494 break;
6495 case 'r':
6496 rq_histo = B_TRUE;
6497 break;
6498 case 'y':
6499 omit_since_boot = B_TRUE;
6500 break;
6501 case 'n':
6502 headers_once = B_TRUE;
6503 break;
6504 case 'h':
6505 usage(B_FALSE);
6506 break;
6507 case '?':
6508 if (optopt == 'c') {
6509 print_zpool_script_list("iostat");
6510 exit(0);
6511 } else {
6512 fprintf(stderr,
6513 gettext("invalid option '%c'\n"), optopt);
6514 }
6515 usage(B_FALSE);
6516 }
6517 }
6518
6519 argc -= optind;
6520 argv += optind;
6521
6522 cb.cb_literal = parsable;
6523 cb.cb_scripted = scripted;
6524
6525 if (guid)
6526 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_GUID;
6527 if (follow_links)
6528 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6529 if (full_name)
6530 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_PATH;
6531 cb.cb_iteration = 0;
6532 cb.cb_namewidth = 0;
6533 cb.cb_verbose = verbose;
6534
6535 /* Get our interval and count values (if any) */
6536 if (guid) {
6537 get_interval_count_filter_guids(&argc, argv, &interval,
6538 &count, &cb);
6539 } else {
6540 get_interval_count(&argc, argv, &interval, &count);
6541 }
6542
6543 if (argc == 0) {
6544 /* No args, so just print the defaults. */
6545 } else if (are_all_pools(argc, argv)) {
6546 /* All the args are pool names */
6547 } else if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
6548 /* All the args are vdevs */
6549 cb.cb_vdevs.cb_names = argv;
6550 cb.cb_vdevs.cb_names_count = argc;
6551 argc = 0; /* No pools to process */
6552 } else if (are_all_pools(1, argv)) {
6553 /* The first arg is a pool name */
6554 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
6555 &cb.cb_vdevs)) {
6556 /* ...and the rest are vdev names */
6557 cb.cb_vdevs.cb_names = argv + 1;
6558 cb.cb_vdevs.cb_names_count = argc - 1;
6559 argc = 1; /* One pool to process */
6560 } else {
6561 fprintf(stderr, gettext("Expected either a list of "));
6562 fprintf(stderr, gettext("pools, or list of vdevs in"));
6563 fprintf(stderr, " \"%s\", ", argv[0]);
6564 fprintf(stderr, gettext("but got:\n"));
6565 error_list_unresolved_vdevs(argc - 1, argv + 1,
6566 argv[0], &cb.cb_vdevs);
6567 fprintf(stderr, "\n");
6568 usage(B_FALSE);
6569 }
6570 } else {
6571 /*
6572 * The args don't make sense. The first arg isn't a pool name,
6573 * nor are all the args vdevs.
6574 */
6575 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
6576 fprintf(stderr, "\n");
6577 return (1);
6578 }
6579
6580 if (cb.cb_vdevs.cb_names_count != 0) {
6581 /*
6582 * If user specified vdevs, it implies verbose.
6583 */
6584 cb.cb_verbose = B_TRUE;
6585 }
6586
6587 /*
6588 * Construct the list of all interesting pools.
6589 */
6590 ret = 0;
6591 if ((list = pool_list_get(argc, argv, NULL, ZFS_TYPE_POOL, parsable,
6592 &ret)) == NULL)
6593 return (1);
6594
6595 if (pool_list_count(list) == 0 && argc != 0) {
6596 pool_list_free(list);
6597 return (1);
6598 }
6599
6600 if (pool_list_count(list) == 0 && interval == 0) {
6601 pool_list_free(list);
6602 (void) fprintf(stderr, gettext("no pools available\n"));
6603 return (1);
6604 }
6605
6606 if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
6607 pool_list_free(list);
6608 (void) fprintf(stderr,
6609 gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
6610 usage(B_FALSE);
6611 }
6612
6613 if (l_histo && rq_histo) {
6614 pool_list_free(list);
6615 (void) fprintf(stderr,
6616 gettext("Only one of [-r|-w] can be passed at a time\n"));
6617 usage(B_FALSE);
6618 }
6619
6620 /*
6621 * Enter the main iostat loop.
6622 */
6623 cb.cb_list = list;
6624
6625 if (l_histo) {
6626 /*
6627 * Histograms tables look out of place when you try to display
6628 * them with the other stats, so make a rule that you can only
6629 * print histograms by themselves.
6630 */
6631 cb.cb_flags = IOS_L_HISTO_M;
6632 } else if (rq_histo) {
6633 cb.cb_flags = IOS_RQ_HISTO_M;
6634 } else {
6635 cb.cb_flags = IOS_DEFAULT_M;
6636 if (latency)
6637 cb.cb_flags |= IOS_LATENCY_M;
6638 if (queues)
6639 cb.cb_flags |= IOS_QUEUES_M;
6640 }
6641
6642 /*
6643 * See if the module supports all the stats we want to display.
6644 */
6645 unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
6646 if (unsupported_flags) {
6647 uint64_t f;
6648 int idx;
6649 fprintf(stderr,
6650 gettext("The loaded zfs module doesn't support:"));
6651
6652 /* for each bit set in unsupported_flags */
6653 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
6654 idx = lowbit64(f) - 1;
6655 fprintf(stderr, " -%c", flag_to_arg[idx]);
6656 }
6657
6658 fprintf(stderr, ". Try running a newer module.\n");
6659 pool_list_free(list);
6660
6661 return (1);
6662 }
6663
6664 int last_npools = 0;
6665 for (;;) {
6666 /*
6667 * Refresh all pools in list, adding or removing pools as
6668 * necessary.
6669 */
6670 int npools = pool_list_refresh(list);
6671 if (npools == 0) {
6672 (void) fprintf(stderr, gettext("no pools available\n"));
6673 } else {
6674 /*
6675 * If the list of pools has changed since last time
6676 * around, reset the iteration count to force the
6677 * header to be redisplayed.
6678 */
6679 if (last_npools != npools)
6680 cb.cb_iteration = 0;
6681
6682 /*
6683 * If this is the first iteration and -y was supplied
6684 * we skip any printing.
6685 */
6686 boolean_t skip = (omit_since_boot &&
6687 cb.cb_iteration == 0);
6688
6689 /*
6690 * Iterate over all pools to determine the maximum width
6691 * for the pool / device name column across all pools.
6692 */
6693 cb.cb_namewidth = 0;
6694 (void) pool_list_iter(list, B_FALSE,
6695 get_namewidth_iostat, &cb);
6696
6697 if (timestamp_fmt != NODATE)
6698 print_timestamp(timestamp_fmt);
6699
6700 if (cmd != NULL && cb.cb_verbose &&
6701 !(cb.cb_flags & IOS_ANYHISTO_M)) {
6702 cb.vcdl = all_pools_for_each_vdev_run(argc,
6703 argv, cmd, g_zfs, cb.cb_vdevs.cb_names,
6704 cb.cb_vdevs.cb_names_count,
6705 cb.cb_vdevs.cb_name_flags);
6706 } else {
6707 cb.vcdl = NULL;
6708 }
6709
6710
6711 /*
6712 * Check terminal size so we can print headers
6713 * even when terminal window has its height
6714 * changed.
6715 */
6716 int winheight = terminal_height();
6717 /*
6718 * Are we connected to TTY? If not, headers_once
6719 * should be true, to avoid breaking scripts.
6720 */
6721 if (winheight < 0)
6722 headers_once = B_TRUE;
6723
6724 /*
6725 * If it's the first time and we're not skipping it,
6726 * or either skip or verbose mode, print the header.
6727 *
6728 * The histogram code explicitly prints its header on
6729 * every vdev, so skip this for histograms.
6730 */
6731 if (((++cb.cb_iteration == 1 && !skip) ||
6732 (skip != verbose) ||
6733 (!headers_once &&
6734 (cb.cb_iteration % winheight) == 0)) &&
6735 (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
6736 !cb.cb_scripted)
6737 print_iostat_header(&cb);
6738
6739 if (skip) {
6740 (void) fflush(stdout);
6741 (void) fsleep(interval);
6742 last_npools = npools;
6743 continue;
6744 }
6745
6746 (void) pool_list_iter(list, B_FALSE, print_iostat, &cb);
6747
6748 /*
6749 * If there's more than one pool, and we're not in
6750 * verbose mode (which prints a separator for us),
6751 * then print a separator.
6752 *
6753 * In addition, if we're printing specific vdevs then
6754 * we also want an ending separator.
6755 */
6756 if (((npools > 1 && !verbose &&
6757 !(cb.cb_flags & IOS_ANYHISTO_M)) ||
6758 (!(cb.cb_flags & IOS_ANYHISTO_M) &&
6759 cb.cb_vdevs.cb_names_count)) &&
6760 !cb.cb_scripted) {
6761 print_iostat_separator(&cb);
6762 if (cb.vcdl != NULL)
6763 print_cmd_columns(cb.vcdl, 1);
6764 printf("\n");
6765 }
6766
6767 if (cb.vcdl != NULL)
6768 free_vdev_cmd_data_list(cb.vcdl);
6769
6770 }
6771
6772 if (interval == 0)
6773 break;
6774
6775 if (count != 0 && --count == 0)
6776 break;
6777
6778 (void) fflush(stdout);
6779 (void) fsleep(interval);
6780
6781 last_npools = npools;
6782 }
6783
6784 pool_list_free(list);
6785
6786 return (ret);
6787 }
6788
6789 typedef struct list_cbdata {
6790 boolean_t cb_verbose;
6791 int cb_name_flags;
6792 int cb_namewidth;
6793 boolean_t cb_json;
6794 boolean_t cb_scripted;
6795 zprop_list_t *cb_proplist;
6796 boolean_t cb_literal;
6797 nvlist_t *cb_jsobj;
6798 boolean_t cb_json_as_int;
6799 boolean_t cb_json_pool_key_guid;
6800 } list_cbdata_t;
6801
6802
6803 /*
6804 * Given a list of columns to display, print an appropriate line. If
6805 * `vdev_name` is not NULL, we print `vdev_name` followed by a line of dashes.
6806 * If `vdev_name` is NULL, we print a line of the headers.
6807 */
6808 static void
print_line(list_cbdata_t * cb,const char * vdev_name)6809 print_line(list_cbdata_t *cb, const char *vdev_name)
6810 {
6811 zprop_list_t *pl = cb->cb_proplist;
6812 char headerbuf[ZPOOL_MAXPROPLEN];
6813 const char *header;
6814 boolean_t first = B_TRUE;
6815 boolean_t right_justify;
6816 size_t width = 0;
6817
6818 boolean_t print_header = (vdev_name == NULL);
6819
6820 for (; pl != NULL; pl = pl->pl_next) {
6821 width = pl->pl_width;
6822 if (first && cb->cb_verbose) {
6823 /*
6824 * Reset the width to accommodate the verbose listing
6825 * of devices.
6826 */
6827 width = cb->cb_namewidth;
6828 }
6829
6830 if (!first)
6831 (void) fputs(" ", stdout);
6832
6833 if (print_header) {
6834 right_justify = B_FALSE;
6835 if (pl->pl_prop != ZPROP_USERPROP) {
6836 header = zpool_prop_column_name(pl->pl_prop);
6837 right_justify = zpool_prop_align_right(
6838 pl->pl_prop);
6839 } else {
6840 int i;
6841
6842 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
6843 headerbuf[i] = toupper(
6844 pl->pl_user_prop[i]);
6845 headerbuf[i] = '\0';
6846 header = headerbuf;
6847 }
6848
6849 }
6850 /*
6851 * If `print_header` is false, we want to print a line of
6852 * dashes.
6853 */
6854 else {
6855 if (first) {
6856 header = vdev_name;
6857 right_justify = B_FALSE;
6858 } else {
6859 header = "-";
6860 right_justify = B_TRUE;
6861 }
6862 }
6863
6864 if (pl->pl_next == NULL && !right_justify)
6865 (void) fputs(header, stdout);
6866 else if (right_justify)
6867 (void) printf("%*s", (int)width, header);
6868 else
6869 (void) printf("%-*s", (int)width, header);
6870
6871 if (first)
6872 first = B_FALSE;
6873 }
6874
6875 (void) fputc('\n', stdout);
6876 }
6877
6878 /*
6879 * Given a pool and a list of properties, print out all the properties according
6880 * to the described layout. Used by zpool_do_list().
6881 */
6882 static void
collect_pool(zpool_handle_t * zhp,list_cbdata_t * cb)6883 collect_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
6884 {
6885 zprop_list_t *pl = cb->cb_proplist;
6886 boolean_t first = B_TRUE;
6887 char property[ZPOOL_MAXPROPLEN];
6888 const char *propstr;
6889 boolean_t right_justify;
6890 size_t width;
6891 zprop_source_t sourcetype = ZPROP_SRC_NONE;
6892 nvlist_t *item, *d, *props;
6893 item = d = props = NULL;
6894
6895 if (cb->cb_json) {
6896 item = fnvlist_alloc();
6897 props = fnvlist_alloc();
6898 d = fnvlist_lookup_nvlist(cb->cb_jsobj, "pools");
6899 if (d == NULL) {
6900 fprintf(stderr, "pools obj not found.\n");
6901 exit(1);
6902 }
6903 fill_pool_info(item, zhp, B_TRUE, cb->cb_json_as_int);
6904 }
6905
6906 for (; pl != NULL; pl = pl->pl_next) {
6907
6908 width = pl->pl_width;
6909 if (first && cb->cb_verbose) {
6910 /*
6911 * Reset the width to accommodate the verbose listing
6912 * of devices.
6913 */
6914 width = cb->cb_namewidth;
6915 }
6916
6917 if (!cb->cb_json && !first) {
6918 if (cb->cb_scripted)
6919 (void) fputc('\t', stdout);
6920 else
6921 (void) fputs(" ", stdout);
6922 } else {
6923 first = B_FALSE;
6924 }
6925
6926 right_justify = B_FALSE;
6927 if (pl->pl_prop != ZPROP_USERPROP) {
6928 if (zpool_get_prop(zhp, pl->pl_prop, property,
6929 sizeof (property), &sourcetype,
6930 cb->cb_literal) != 0)
6931 propstr = "-";
6932 else
6933 propstr = property;
6934
6935 right_justify = zpool_prop_align_right(pl->pl_prop);
6936 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
6937 zpool_prop_unsupported(pl->pl_user_prop)) &&
6938 zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
6939 sizeof (property)) == 0) {
6940 propstr = property;
6941 sourcetype = ZPROP_SRC_LOCAL;
6942 } else if (zfs_prop_user(pl->pl_user_prop) &&
6943 zpool_get_userprop(zhp, pl->pl_user_prop, property,
6944 sizeof (property), &sourcetype) == 0) {
6945 propstr = property;
6946 } else {
6947 propstr = "-";
6948 }
6949
6950 if (cb->cb_json) {
6951 if (pl->pl_prop == ZPOOL_PROP_NAME)
6952 continue;
6953 const char *prop_name;
6954 if (pl->pl_prop != ZPROP_USERPROP)
6955 prop_name = zpool_prop_to_name(pl->pl_prop);
6956 else
6957 prop_name = pl->pl_user_prop;
6958 (void) zprop_nvlist_one_property(
6959 prop_name, propstr,
6960 sourcetype, NULL, NULL, props, cb->cb_json_as_int);
6961 } else {
6962 /*
6963 * If this is being called in scripted mode, or if this
6964 * is the last column and it is left-justified, don't
6965 * include a width format specifier.
6966 */
6967 if (cb->cb_scripted || (pl->pl_next == NULL &&
6968 !right_justify))
6969 (void) fputs(propstr, stdout);
6970 else if (right_justify)
6971 (void) printf("%*s", (int)width, propstr);
6972 else
6973 (void) printf("%-*s", (int)width, propstr);
6974 }
6975 }
6976
6977 if (cb->cb_json) {
6978 fnvlist_add_nvlist(item, "properties", props);
6979 if (cb->cb_json_pool_key_guid) {
6980 char pool_guid[256];
6981 uint64_t guid = fnvlist_lookup_uint64(
6982 zpool_get_config(zhp, NULL),
6983 ZPOOL_CONFIG_POOL_GUID);
6984 (void) snprintf(pool_guid, 256, "%llu",
6985 (u_longlong_t)guid);
6986 fnvlist_add_nvlist(d, pool_guid, item);
6987 } else {
6988 fnvlist_add_nvlist(d, zpool_get_name(zhp),
6989 item);
6990 }
6991 fnvlist_free(props);
6992 fnvlist_free(item);
6993 } else
6994 (void) fputc('\n', stdout);
6995 }
6996
6997 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)6998 collect_vdev_prop(zpool_prop_t prop, uint64_t value, const char *str,
6999 boolean_t scripted, boolean_t valid, enum zfs_nicenum_format format,
7000 boolean_t json, nvlist_t *nvl, boolean_t as_int)
7001 {
7002 char propval[64];
7003 boolean_t fixed;
7004 size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
7005
7006 switch (prop) {
7007 case ZPOOL_PROP_SIZE:
7008 case ZPOOL_PROP_NORMAL_SIZE:
7009 case ZPOOL_PROP_SPECIAL_SIZE:
7010 case ZPOOL_PROP_DEDUP_SIZE:
7011 case ZPOOL_PROP_LOG_SIZE:
7012 case ZPOOL_PROP_ELOG_SIZE:
7013 case ZPOOL_PROP_SELOG_SIZE:
7014 case ZPOOL_PROP_EXPANDSZ:
7015 case ZPOOL_PROP_NORMAL_EXPANDSZ:
7016 case ZPOOL_PROP_SPECIAL_EXPANDSZ:
7017 case ZPOOL_PROP_DEDUP_EXPANDSZ:
7018 case ZPOOL_PROP_LOG_EXPANDSZ:
7019 case ZPOOL_PROP_ELOG_EXPANDSZ:
7020 case ZPOOL_PROP_SELOG_EXPANDSZ:
7021 case ZPOOL_PROP_CHECKPOINT:
7022 case ZPOOL_PROP_DEDUPRATIO:
7023 case ZPOOL_PROP_DEDUPCACHED:
7024 if (value == 0)
7025 (void) strlcpy(propval, "-", sizeof (propval));
7026 else
7027 zfs_nicenum_format(value, propval, sizeof (propval),
7028 format);
7029 break;
7030 case ZPOOL_PROP_FRAGMENTATION:
7031 case ZPOOL_PROP_NORMAL_FRAGMENTATION:
7032 case ZPOOL_PROP_SPECIAL_FRAGMENTATION:
7033 case ZPOOL_PROP_DEDUP_FRAGMENTATION:
7034 case ZPOOL_PROP_LOG_FRAGMENTATION:
7035 case ZPOOL_PROP_ELOG_FRAGMENTATION:
7036 case ZPOOL_PROP_SELOG_FRAGMENTATION:
7037 if (value == ZFS_FRAG_INVALID) {
7038 (void) strlcpy(propval, "-", sizeof (propval));
7039 } else if (format == ZFS_NICENUM_RAW) {
7040 (void) snprintf(propval, sizeof (propval), "%llu",
7041 (unsigned long long)value);
7042 } else {
7043 (void) snprintf(propval, sizeof (propval), "%llu%%",
7044 (unsigned long long)value);
7045 }
7046 break;
7047 case ZPOOL_PROP_CAPACITY:
7048 case ZPOOL_PROP_NORMAL_CAPACITY:
7049 case ZPOOL_PROP_SPECIAL_CAPACITY:
7050 case ZPOOL_PROP_DEDUP_CAPACITY:
7051 case ZPOOL_PROP_LOG_CAPACITY:
7052 case ZPOOL_PROP_ELOG_CAPACITY:
7053 case ZPOOL_PROP_SELOG_CAPACITY:
7054 /* capacity value is in parts-per-10,000 (aka permyriad) */
7055 if (format == ZFS_NICENUM_RAW)
7056 (void) snprintf(propval, sizeof (propval), "%llu",
7057 (unsigned long long)value / 100);
7058 else
7059 (void) snprintf(propval, sizeof (propval),
7060 value < 1000 ? "%1.2f%%" : value < 10000 ?
7061 "%2.1f%%" : "%3.0f%%", value / 100.0);
7062 break;
7063 case ZPOOL_PROP_HEALTH:
7064 width = 8;
7065 (void) strlcpy(propval, str, sizeof (propval));
7066 break;
7067 default:
7068 zfs_nicenum_format(value, propval, sizeof (propval), format);
7069 }
7070
7071 if (!valid)
7072 (void) strlcpy(propval, "-", sizeof (propval));
7073
7074 if (json) {
7075 (void) zprop_nvlist_one_property(zpool_prop_to_name(prop),
7076 propval, ZPROP_SRC_NONE, NULL, NULL, nvl, as_int);
7077 } else {
7078 if (scripted)
7079 (void) printf("\t%s", propval);
7080 else
7081 (void) printf(" %*s", (int)width, propval);
7082 }
7083 }
7084
7085 /*
7086 * print static default line per vdev
7087 */
7088 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)7089 collect_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
7090 list_cbdata_t *cb, int depth, boolean_t isspare, nvlist_t *item)
7091 {
7092 nvlist_t **child;
7093 vdev_stat_t *vs;
7094 uint_t c, children = 0;
7095 char *vname;
7096 boolean_t scripted = cb->cb_scripted;
7097 uint64_t islog = B_FALSE;
7098 nvlist_t *props, *ent, *ch, *obj, *l2c, *sp;
7099 props = ent = ch = obj = sp = l2c = NULL;
7100
7101 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
7102 (uint64_t **)&vs, &c) == 0);
7103
7104 if (name != NULL) {
7105 boolean_t toplevel = (vs->vs_space != 0);
7106 uint64_t cap;
7107 enum zfs_nicenum_format format;
7108 const char *state;
7109
7110 if (cb->cb_literal)
7111 format = ZFS_NICENUM_RAW;
7112 else
7113 format = ZFS_NICENUM_1024;
7114
7115 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
7116 return;
7117
7118 if (cb->cb_json) {
7119 props = fnvlist_alloc();
7120 ent = fnvlist_alloc();
7121 fill_vdev_info(ent, zhp, (char *)name, B_FALSE,
7122 cb->cb_json_as_int);
7123 } else {
7124 if (scripted)
7125 (void) printf("\t%s", name);
7126 else if (strlen(name) + depth > cb->cb_namewidth)
7127 (void) printf("%*s%s", depth, "", name);
7128 else
7129 (void) printf("%*s%s%*s", depth, "", name,
7130 (int)(cb->cb_namewidth - strlen(name) -
7131 depth), "");
7132 }
7133
7134 /*
7135 * Print the properties for the individual vdevs. Some
7136 * properties are only applicable to toplevel vdevs. The
7137 * 'toplevel' boolean value is passed to the print_one_column()
7138 * to indicate that the value is valid.
7139 */
7140 for (zprop_list_t *pl = cb->cb_proplist; pl != NULL;
7141 pl = pl->pl_next) {
7142 switch (pl->pl_prop) {
7143 case ZPOOL_PROP_SIZE:
7144 if (VDEV_STAT_VALID(vs_pspace, c) &&
7145 vs->vs_pspace) {
7146 collect_vdev_prop(
7147 ZPOOL_PROP_SIZE, vs->vs_pspace,
7148 NULL, scripted, B_TRUE, format,
7149 cb->cb_json, props,
7150 cb->cb_json_as_int);
7151 } else {
7152 collect_vdev_prop(
7153 ZPOOL_PROP_SIZE, vs->vs_space, NULL,
7154 scripted, toplevel, format,
7155 cb->cb_json, props,
7156 cb->cb_json_as_int);
7157 }
7158 break;
7159 case ZPOOL_PROP_ALLOCATED:
7160 collect_vdev_prop(ZPOOL_PROP_ALLOCATED,
7161 vs->vs_alloc, NULL, scripted, toplevel,
7162 format, cb->cb_json, props,
7163 cb->cb_json_as_int);
7164 break;
7165
7166 case ZPOOL_PROP_FREE:
7167 collect_vdev_prop(ZPOOL_PROP_FREE,
7168 vs->vs_space - vs->vs_alloc, NULL, scripted,
7169 toplevel, format, cb->cb_json, props,
7170 cb->cb_json_as_int);
7171 break;
7172
7173 case ZPOOL_PROP_CHECKPOINT:
7174 collect_vdev_prop(ZPOOL_PROP_CHECKPOINT,
7175 vs->vs_checkpoint_space, NULL, scripted,
7176 toplevel, format, cb->cb_json, props,
7177 cb->cb_json_as_int);
7178 break;
7179
7180 case ZPOOL_PROP_EXPANDSZ:
7181 collect_vdev_prop(ZPOOL_PROP_EXPANDSZ,
7182 vs->vs_esize, NULL, scripted, B_TRUE,
7183 format, cb->cb_json, props,
7184 cb->cb_json_as_int);
7185 break;
7186
7187 case ZPOOL_PROP_FRAGMENTATION:
7188 collect_vdev_prop(
7189 ZPOOL_PROP_FRAGMENTATION,
7190 vs->vs_fragmentation, NULL, scripted,
7191 (vs->vs_fragmentation != ZFS_FRAG_INVALID &&
7192 toplevel),
7193 format, cb->cb_json, props,
7194 cb->cb_json_as_int);
7195 break;
7196
7197 case ZPOOL_PROP_CAPACITY:
7198 cap = (vs->vs_space == 0) ?
7199 0 : (vs->vs_alloc * 10000 / vs->vs_space);
7200 collect_vdev_prop(ZPOOL_PROP_CAPACITY, cap,
7201 NULL, scripted, toplevel, format,
7202 cb->cb_json, props, cb->cb_json_as_int);
7203 break;
7204
7205 case ZPOOL_PROP_HEALTH:
7206 state = zpool_state_to_name(vs->vs_state,
7207 vs->vs_aux);
7208 if (isspare) {
7209 if (vs->vs_aux == VDEV_AUX_SPARED)
7210 state = "INUSE";
7211 else if (vs->vs_state ==
7212 VDEV_STATE_HEALTHY)
7213 state = "AVAIL";
7214 }
7215 collect_vdev_prop(ZPOOL_PROP_HEALTH, 0, state,
7216 scripted, B_TRUE, format, cb->cb_json,
7217 props, cb->cb_json_as_int);
7218 break;
7219
7220 case ZPOOL_PROP_NAME:
7221 break;
7222
7223 default:
7224 collect_vdev_prop(pl->pl_prop, 0,
7225 NULL, scripted, B_FALSE, format,
7226 cb->cb_json, props, cb->cb_json_as_int);
7227
7228 }
7229
7230
7231 }
7232
7233 if (cb->cb_json) {
7234 fnvlist_add_nvlist(ent, "properties", props);
7235 fnvlist_free(props);
7236 } else
7237 (void) fputc('\n', stdout);
7238 }
7239
7240 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
7241 &child, &children) != 0) {
7242 if (cb->cb_json) {
7243 fnvlist_add_nvlist(item, name, ent);
7244 fnvlist_free(ent);
7245 }
7246 return;
7247 }
7248
7249 if (cb->cb_json) {
7250 ch = fnvlist_alloc();
7251 }
7252
7253 /* list the normal vdevs first */
7254 for (c = 0; c < children; c++) {
7255 uint64_t ishole = B_FALSE;
7256
7257 if (nvlist_lookup_uint64(child[c],
7258 ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
7259 continue;
7260
7261 if (nvlist_lookup_uint64(child[c],
7262 ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
7263 continue;
7264
7265 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
7266 continue;
7267
7268 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7269 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7270
7271 if (name == NULL || cb->cb_json != B_TRUE)
7272 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7273 B_FALSE, item);
7274 else if (cb->cb_json) {
7275 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7276 B_FALSE, ch);
7277 }
7278 free(vname);
7279 }
7280
7281 if (cb->cb_json) {
7282 if (!nvlist_empty(ch))
7283 fnvlist_add_nvlist(ent, "vdevs", ch);
7284 fnvlist_free(ch);
7285 }
7286
7287 /* list the classes: 'logs', 'dedup', and 'special' */
7288 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
7289 boolean_t printed = B_FALSE;
7290 if (cb->cb_json)
7291 obj = fnvlist_alloc();
7292 for (c = 0; c < children; c++) {
7293 const char *bias = NULL;
7294 const char *type = NULL;
7295
7296 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
7297 &islog) == 0 && islog) {
7298 bias = VDEV_ALLOC_CLASS_LOGS;
7299 } else {
7300 (void) nvlist_lookup_string(child[c],
7301 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
7302 (void) nvlist_lookup_string(child[c],
7303 ZPOOL_CONFIG_TYPE, &type);
7304 }
7305 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
7306 continue;
7307 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
7308 continue;
7309
7310 if (!printed && !cb->cb_json) {
7311 print_line(cb, class_name[n]);
7312 printed = B_TRUE;
7313 }
7314 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7315 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7316 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7317 B_FALSE, obj);
7318 free(vname);
7319 }
7320 if (cb->cb_json) {
7321 if (!nvlist_empty(obj))
7322 fnvlist_add_nvlist(item, class_name[n], obj);
7323 fnvlist_free(obj);
7324 }
7325 }
7326
7327 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
7328 &child, &children) == 0 && children > 0) {
7329 if (cb->cb_json) {
7330 l2c = fnvlist_alloc();
7331 } else {
7332 print_line(cb, "cache");
7333 }
7334 for (c = 0; c < children; c++) {
7335 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7336 cb->cb_name_flags);
7337 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7338 B_FALSE, l2c);
7339 free(vname);
7340 }
7341 if (cb->cb_json) {
7342 if (!nvlist_empty(l2c))
7343 fnvlist_add_nvlist(item, "l2cache", l2c);
7344 fnvlist_free(l2c);
7345 }
7346 }
7347
7348 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
7349 &children) == 0 && children > 0) {
7350 if (cb->cb_json) {
7351 sp = fnvlist_alloc();
7352 } else {
7353 print_line(cb, "spare");
7354 }
7355 for (c = 0; c < children; c++) {
7356 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7357 cb->cb_name_flags);
7358 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7359 B_TRUE, sp);
7360 free(vname);
7361 }
7362 if (cb->cb_json) {
7363 if (!nvlist_empty(sp))
7364 fnvlist_add_nvlist(item, "spares", sp);
7365 fnvlist_free(sp);
7366 }
7367 }
7368
7369 if (name != NULL && cb->cb_json) {
7370 fnvlist_add_nvlist(item, name, ent);
7371 fnvlist_free(ent);
7372 }
7373 }
7374
7375 /*
7376 * Generic callback function to list a pool.
7377 */
7378 static int
list_callback(zpool_handle_t * zhp,void * data)7379 list_callback(zpool_handle_t *zhp, void *data)
7380 {
7381 nvlist_t *p, *d, *nvdevs;
7382 uint64_t guid;
7383 char pool_guid[256];
7384 const char *pool_name = zpool_get_name(zhp);
7385 list_cbdata_t *cbp = data;
7386 p = d = nvdevs = NULL;
7387
7388 collect_pool(zhp, cbp);
7389
7390 if (cbp->cb_verbose) {
7391 nvlist_t *config, *nvroot;
7392 config = zpool_get_config(zhp, NULL);
7393 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
7394 &nvroot) == 0);
7395 if (cbp->cb_json) {
7396 d = fnvlist_lookup_nvlist(cbp->cb_jsobj,
7397 "pools");
7398 if (cbp->cb_json_pool_key_guid) {
7399 guid = fnvlist_lookup_uint64(config,
7400 ZPOOL_CONFIG_POOL_GUID);
7401 (void) snprintf(pool_guid, 256, "%llu",
7402 (u_longlong_t)guid);
7403 p = fnvlist_lookup_nvlist(d, pool_guid);
7404 } else {
7405 p = fnvlist_lookup_nvlist(d, pool_name);
7406 }
7407 nvdevs = fnvlist_alloc();
7408 }
7409 collect_list_stats(zhp, NULL, nvroot, cbp, 0, B_FALSE, nvdevs);
7410 if (cbp->cb_json) {
7411 fnvlist_add_nvlist(p, "vdevs", nvdevs);
7412 if (cbp->cb_json_pool_key_guid)
7413 fnvlist_add_nvlist(d, pool_guid, p);
7414 else
7415 fnvlist_add_nvlist(d, pool_name, p);
7416 fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
7417 fnvlist_free(nvdevs);
7418 }
7419 }
7420
7421 return (0);
7422 }
7423
7424 /*
7425 * Set the minimum pool/vdev name column width. The width must be at least 9,
7426 * but may be as large as needed.
7427 */
7428 static int
get_namewidth_list(zpool_handle_t * zhp,void * data)7429 get_namewidth_list(zpool_handle_t *zhp, void *data)
7430 {
7431 list_cbdata_t *cb = data;
7432 int width;
7433
7434 width = get_namewidth(zhp, cb->cb_namewidth,
7435 cb->cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
7436
7437 if (width < 9)
7438 width = 9;
7439
7440 cb->cb_namewidth = width;
7441
7442 return (0);
7443 }
7444
7445 /*
7446 * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
7447 *
7448 * -g Display guid for individual vdev name.
7449 * -H Scripted mode. Don't display headers, and separate properties
7450 * by a single tab.
7451 * -L Follow links when resolving vdev path name.
7452 * -o List of properties to display. Defaults to
7453 * "name,size,allocated,free,expandsize,fragmentation,capacity,"
7454 * "dedupratio,health,altroot"
7455 * -p Display values in parsable (exact) format.
7456 * -P Display full path for vdev name.
7457 * -T Display a timestamp in date(1) or Unix format
7458 * -j Display the output in JSON format
7459 * --json-int Display the numbers as integer instead of strings.
7460 * --json-pool-key-guid Set pool GUID as key for pool objects.
7461 *
7462 * List all pools in the system, whether or not they're healthy. Output space
7463 * statistics for each one, as well as health status summary.
7464 */
7465 int
zpool_do_list(int argc,char ** argv)7466 zpool_do_list(int argc, char **argv)
7467 {
7468 int c;
7469 int ret = 0;
7470 list_cbdata_t cb = { 0 };
7471 static char default_props[] =
7472 "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
7473 "capacity,dedupratio,health,altroot";
7474 char *props = default_props;
7475 float interval = 0;
7476 unsigned long count = 0;
7477 zpool_list_t *list;
7478 boolean_t first = B_TRUE;
7479 nvlist_t *data = NULL;
7480 current_prop_type = ZFS_TYPE_POOL;
7481
7482 struct option long_options[] = {
7483 {"json", no_argument, NULL, 'j'},
7484 {"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
7485 {"json-pool-key-guid", no_argument, NULL,
7486 ZPOOL_OPTION_POOL_KEY_GUID},
7487 {0, 0, 0, 0}
7488 };
7489
7490 /* check options */
7491 while ((c = getopt_long(argc, argv, ":gjHLo:pPT:v", long_options,
7492 NULL)) != -1) {
7493 switch (c) {
7494 case 'g':
7495 cb.cb_name_flags |= VDEV_NAME_GUID;
7496 break;
7497 case 'H':
7498 cb.cb_scripted = B_TRUE;
7499 break;
7500 case 'L':
7501 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
7502 break;
7503 case 'o':
7504 props = optarg;
7505 break;
7506 case 'P':
7507 cb.cb_name_flags |= VDEV_NAME_PATH;
7508 break;
7509 case 'p':
7510 cb.cb_literal = B_TRUE;
7511 break;
7512 case 'j':
7513 cb.cb_json = B_TRUE;
7514 break;
7515 case ZPOOL_OPTION_JSON_NUMS_AS_INT:
7516 cb.cb_json_as_int = B_TRUE;
7517 cb.cb_literal = B_TRUE;
7518 break;
7519 case ZPOOL_OPTION_POOL_KEY_GUID:
7520 cb.cb_json_pool_key_guid = B_TRUE;
7521 break;
7522 case 'T':
7523 get_timestamp_arg(*optarg);
7524 break;
7525 case 'v':
7526 cb.cb_verbose = B_TRUE;
7527 cb.cb_namewidth = 8; /* 8 until precalc is avail */
7528 break;
7529 case ':':
7530 (void) fprintf(stderr, gettext("missing argument for "
7531 "'%c' option\n"), optopt);
7532 usage(B_FALSE);
7533 break;
7534 case '?':
7535 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7536 optopt);
7537 usage(B_FALSE);
7538 }
7539 }
7540
7541 argc -= optind;
7542 argv += optind;
7543
7544 if (!cb.cb_json && cb.cb_json_as_int) {
7545 (void) fprintf(stderr, gettext("'--json-int' only works with"
7546 " '-j' option\n"));
7547 usage(B_FALSE);
7548 }
7549
7550 if (!cb.cb_json && cb.cb_json_pool_key_guid) {
7551 (void) fprintf(stderr, gettext("'json-pool-key-guid' only"
7552 " works with '-j' option\n"));
7553 usage(B_FALSE);
7554 }
7555
7556 get_interval_count(&argc, argv, &interval, &count);
7557
7558 if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
7559 usage(B_FALSE);
7560
7561 for (;;) {
7562 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
7563 ZFS_TYPE_POOL, cb.cb_literal, &ret)) == NULL)
7564 return (1);
7565
7566 if (pool_list_count(list) == 0)
7567 break;
7568
7569 if (cb.cb_json) {
7570 cb.cb_jsobj = zpool_json_schema(0, 1);
7571 data = fnvlist_alloc();
7572 fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
7573 fnvlist_free(data);
7574 }
7575
7576 cb.cb_namewidth = 0;
7577 (void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
7578
7579 if (timestamp_fmt != NODATE) {
7580 if (cb.cb_json) {
7581 if (cb.cb_json_as_int) {
7582 fnvlist_add_uint64(cb.cb_jsobj, "time",
7583 time(NULL));
7584 } else {
7585 char ts[128];
7586 get_timestamp(timestamp_fmt, ts, 128);
7587 fnvlist_add_string(cb.cb_jsobj, "time",
7588 ts);
7589 }
7590 } else
7591 print_timestamp(timestamp_fmt);
7592 }
7593
7594 if (!cb.cb_scripted && (first || cb.cb_verbose) &&
7595 !cb.cb_json) {
7596 print_line(&cb, NULL);
7597 first = B_FALSE;
7598 }
7599 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
7600
7601 if (ret == 0 && cb.cb_json)
7602 zcmd_print_json(cb.cb_jsobj);
7603 else if (ret != 0 && cb.cb_json)
7604 nvlist_free(cb.cb_jsobj);
7605
7606 if (interval == 0)
7607 break;
7608
7609 if (count != 0 && --count == 0)
7610 break;
7611
7612 pool_list_free(list);
7613
7614 (void) fflush(stdout);
7615 (void) fsleep(interval);
7616 }
7617
7618 if (argc == 0 && !cb.cb_scripted && !cb.cb_json &&
7619 pool_list_count(list) == 0) {
7620 (void) printf(gettext("no pools available\n"));
7621 ret = 0;
7622 }
7623
7624 pool_list_free(list);
7625 zprop_free_list(cb.cb_proplist);
7626 return (ret);
7627 }
7628
7629 static int
zpool_do_attach_or_replace(int argc,char ** argv,int replacing)7630 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
7631 {
7632 boolean_t force = B_FALSE;
7633 boolean_t rebuild = B_FALSE;
7634 boolean_t wait = B_FALSE;
7635 int c;
7636 nvlist_t *nvroot;
7637 char *poolname, *old_disk, *new_disk;
7638 zpool_handle_t *zhp;
7639 nvlist_t *props = NULL;
7640 char *propval;
7641 int ret;
7642
7643 /* check options */
7644 while ((c = getopt(argc, argv, "fo:sw")) != -1) {
7645 switch (c) {
7646 case 'f':
7647 force = B_TRUE;
7648 break;
7649 case 'o':
7650 if ((propval = strchr(optarg, '=')) == NULL) {
7651 (void) fprintf(stderr, gettext("missing "
7652 "'=' for -o option\n"));
7653 usage(B_FALSE);
7654 }
7655 *propval = '\0';
7656 propval++;
7657
7658 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
7659 (add_prop_list(optarg, propval, &props, B_TRUE)))
7660 usage(B_FALSE);
7661 break;
7662 case 's':
7663 rebuild = B_TRUE;
7664 break;
7665 case 'w':
7666 wait = B_TRUE;
7667 break;
7668 case '?':
7669 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7670 optopt);
7671 usage(B_FALSE);
7672 }
7673 }
7674
7675 argc -= optind;
7676 argv += optind;
7677
7678 /* get pool name and check number of arguments */
7679 if (argc < 1) {
7680 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7681 usage(B_FALSE);
7682 }
7683
7684 poolname = argv[0];
7685
7686 if (argc < 2) {
7687 (void) fprintf(stderr,
7688 gettext("missing <device> specification\n"));
7689 usage(B_FALSE);
7690 }
7691
7692 old_disk = argv[1];
7693
7694 if (argc < 3) {
7695 if (!replacing) {
7696 (void) fprintf(stderr,
7697 gettext("missing <new_device> specification\n"));
7698 usage(B_FALSE);
7699 }
7700 new_disk = old_disk;
7701 argc -= 1;
7702 argv += 1;
7703 } else {
7704 new_disk = argv[2];
7705 argc -= 2;
7706 argv += 2;
7707 }
7708
7709 if (argc > 1) {
7710 (void) fprintf(stderr, gettext("too many arguments\n"));
7711 usage(B_FALSE);
7712 }
7713
7714 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7715 nvlist_free(props);
7716 return (1);
7717 }
7718
7719 if (zpool_get_config(zhp, NULL) == NULL) {
7720 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
7721 poolname);
7722 zpool_close(zhp);
7723 nvlist_free(props);
7724 return (1);
7725 }
7726
7727 /* unless manually specified use "ashift" pool property (if set) */
7728 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
7729 int intval;
7730 zprop_source_t src;
7731 char strval[ZPOOL_MAXPROPLEN];
7732
7733 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
7734 if (src != ZPROP_SRC_DEFAULT) {
7735 (void) sprintf(strval, "%" PRId32, intval);
7736 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
7737 &props, B_TRUE) == 0);
7738 }
7739 }
7740
7741 nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
7742 argc, argv);
7743 if (nvroot == NULL) {
7744 zpool_close(zhp);
7745 nvlist_free(props);
7746 return (1);
7747 }
7748
7749 ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing,
7750 rebuild);
7751
7752 if (ret == 0 && wait) {
7753 zpool_wait_activity_t activity = ZPOOL_WAIT_RESILVER;
7754 char raidz_prefix[] = "raidz";
7755 if (replacing) {
7756 activity = ZPOOL_WAIT_REPLACE;
7757 } else if (strncmp(old_disk,
7758 raidz_prefix, strlen(raidz_prefix)) == 0) {
7759 activity = ZPOOL_WAIT_RAIDZ_EXPAND;
7760 }
7761 ret = zpool_wait(zhp, activity);
7762 }
7763
7764 nvlist_free(props);
7765 nvlist_free(nvroot);
7766 zpool_close(zhp);
7767
7768 return (ret);
7769 }
7770
7771 /*
7772 * zpool replace [-fsw] [-o property=value] <pool> <device> <new_device>
7773 *
7774 * -f Force attach, even if <new_device> appears to be in use.
7775 * -s Use sequential instead of healing reconstruction for resilver.
7776 * -o Set property=value.
7777 * -w Wait for replacing to complete before returning
7778 *
7779 * Replace <device> with <new_device>.
7780 */
7781 int
zpool_do_replace(int argc,char ** argv)7782 zpool_do_replace(int argc, char **argv)
7783 {
7784 return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
7785 }
7786
7787 /*
7788 * zpool attach [-fsw] [-o property=value] <pool> <vdev> <new_device>
7789 *
7790 * -f Force attach, even if <new_device> appears to be in use.
7791 * -s Use sequential instead of healing reconstruction for resilver.
7792 * -o Set property=value.
7793 * -w Wait for resilvering (mirror) or expansion (raidz) to complete
7794 * before returning.
7795 *
7796 * Attach <new_device> to a <vdev>, where the vdev can be of type
7797 * device, mirror or raidz. If <vdev> is not part of a mirror, then <vdev> will
7798 * be transformed into a mirror of <vdev> and <new_device>. When a mirror
7799 * is involved, <new_device> will begin life with a DTL of [0, now], and will
7800 * immediately begin to resilver itself. For the raidz case, a expansion will
7801 * commence and reflow the raidz data across all the disks including the
7802 * <new_device>.
7803 */
7804 int
zpool_do_attach(int argc,char ** argv)7805 zpool_do_attach(int argc, char **argv)
7806 {
7807 return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
7808 }
7809
7810 /*
7811 * zpool detach [-f] <pool> <device>
7812 *
7813 * -f Force detach of <device>, even if DTLs argue against it
7814 * (not supported yet)
7815 *
7816 * Detach a device from a mirror. The operation will be refused if <device>
7817 * is the last device in the mirror, or if the DTLs indicate that this device
7818 * has the only valid copy of some data.
7819 */
7820 int
zpool_do_detach(int argc,char ** argv)7821 zpool_do_detach(int argc, char **argv)
7822 {
7823 int c;
7824 char *poolname, *path;
7825 zpool_handle_t *zhp;
7826 int ret;
7827
7828 /* check options */
7829 while ((c = getopt(argc, argv, "")) != -1) {
7830 switch (c) {
7831 case '?':
7832 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7833 optopt);
7834 usage(B_FALSE);
7835 }
7836 }
7837
7838 argc -= optind;
7839 argv += optind;
7840
7841 /* get pool name and check number of arguments */
7842 if (argc < 1) {
7843 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7844 usage(B_FALSE);
7845 }
7846
7847 if (argc < 2) {
7848 (void) fprintf(stderr,
7849 gettext("missing <device> specification\n"));
7850 usage(B_FALSE);
7851 }
7852
7853 poolname = argv[0];
7854 path = argv[1];
7855
7856 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7857 return (1);
7858
7859 ret = zpool_vdev_detach(zhp, path);
7860
7861 zpool_close(zhp);
7862
7863 return (ret);
7864 }
7865
7866 /*
7867 * zpool split [-gLnP] [-o prop=val] ...
7868 * [-o mntopt] ...
7869 * [-R altroot] <pool> <newpool> [<device> ...]
7870 *
7871 * -g Display guid for individual vdev name.
7872 * -L Follow links when resolving vdev path name.
7873 * -n Do not split the pool, but display the resulting layout if
7874 * it were to be split.
7875 * -o Set property=value, or set mount options.
7876 * -P Display full path for vdev name.
7877 * -R Mount the split-off pool under an alternate root.
7878 * -l Load encryption keys while importing.
7879 *
7880 * Splits the named pool and gives it the new pool name. Devices to be split
7881 * off may be listed, provided that no more than one device is specified
7882 * per top-level vdev mirror. The newly split pool is left in an exported
7883 * state unless -R is specified.
7884 *
7885 * Restrictions: the top-level of the pool pool must only be made up of
7886 * mirrors; all devices in the pool must be healthy; no device may be
7887 * undergoing a resilvering operation.
7888 */
7889 int
zpool_do_split(int argc,char ** argv)7890 zpool_do_split(int argc, char **argv)
7891 {
7892 char *srcpool, *newpool, *propval;
7893 char *mntopts = NULL;
7894 splitflags_t flags;
7895 int c, ret = 0;
7896 int ms_status = 0;
7897 boolean_t loadkeys = B_FALSE;
7898 zpool_handle_t *zhp;
7899 nvlist_t *config, *props = NULL;
7900
7901 flags.dryrun = B_FALSE;
7902 flags.import = B_FALSE;
7903 flags.name_flags = 0;
7904
7905 /* check options */
7906 while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
7907 switch (c) {
7908 case 'g':
7909 flags.name_flags |= VDEV_NAME_GUID;
7910 break;
7911 case 'L':
7912 flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
7913 break;
7914 case 'R':
7915 flags.import = B_TRUE;
7916 if (add_prop_list(
7917 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
7918 &props, B_TRUE) != 0) {
7919 nvlist_free(props);
7920 usage(B_FALSE);
7921 }
7922 break;
7923 case 'l':
7924 loadkeys = B_TRUE;
7925 break;
7926 case 'n':
7927 flags.dryrun = B_TRUE;
7928 break;
7929 case 'o':
7930 if ((propval = strchr(optarg, '=')) != NULL) {
7931 *propval = '\0';
7932 propval++;
7933 if (add_prop_list(optarg, propval,
7934 &props, B_TRUE) != 0) {
7935 nvlist_free(props);
7936 usage(B_FALSE);
7937 }
7938 } else {
7939 mntopts = optarg;
7940 }
7941 break;
7942 case 'P':
7943 flags.name_flags |= VDEV_NAME_PATH;
7944 break;
7945 case ':':
7946 (void) fprintf(stderr, gettext("missing argument for "
7947 "'%c' option\n"), optopt);
7948 usage(B_FALSE);
7949 break;
7950 case '?':
7951 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7952 optopt);
7953 usage(B_FALSE);
7954 break;
7955 }
7956 }
7957
7958 if (!flags.import && mntopts != NULL) {
7959 (void) fprintf(stderr, gettext("setting mntopts is only "
7960 "valid when importing the pool\n"));
7961 usage(B_FALSE);
7962 }
7963
7964 if (!flags.import && loadkeys) {
7965 (void) fprintf(stderr, gettext("loading keys is only "
7966 "valid when importing the pool\n"));
7967 usage(B_FALSE);
7968 }
7969
7970 argc -= optind;
7971 argv += optind;
7972
7973 if (argc < 1) {
7974 (void) fprintf(stderr, gettext("Missing pool name\n"));
7975 usage(B_FALSE);
7976 }
7977 if (argc < 2) {
7978 (void) fprintf(stderr, gettext("Missing new pool name\n"));
7979 usage(B_FALSE);
7980 }
7981
7982 srcpool = argv[0];
7983 newpool = argv[1];
7984
7985 argc -= 2;
7986 argv += 2;
7987
7988 if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
7989 nvlist_free(props);
7990 return (1);
7991 }
7992
7993 config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
7994 if (config == NULL) {
7995 ret = 1;
7996 } else {
7997 if (flags.dryrun) {
7998 (void) printf(gettext("would create '%s' with the "
7999 "following layout:\n\n"), newpool);
8000 print_vdev_tree(NULL, newpool, config, 0, "",
8001 flags.name_flags);
8002 print_vdev_tree(NULL, "dedup", config, 0,
8003 VDEV_ALLOC_BIAS_DEDUP, 0);
8004 print_vdev_tree(NULL, "special", config, 0,
8005 VDEV_ALLOC_BIAS_SPECIAL, 0);
8006 }
8007 }
8008
8009 zpool_close(zhp);
8010
8011 if (ret != 0 || flags.dryrun || !flags.import) {
8012 nvlist_free(config);
8013 nvlist_free(props);
8014 return (ret);
8015 }
8016
8017 /*
8018 * The split was successful. Now we need to open the new
8019 * pool and import it.
8020 */
8021 if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
8022 nvlist_free(config);
8023 nvlist_free(props);
8024 return (1);
8025 }
8026
8027 if (loadkeys) {
8028 ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
8029 if (ret != 0)
8030 ret = 1;
8031 }
8032
8033 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL) {
8034 ms_status = zpool_enable_datasets(zhp, mntopts, 0,
8035 mount_tp_nthr);
8036 if (ms_status == EZFS_SHAREFAILED) {
8037 (void) fprintf(stderr, gettext("Split was successful, "
8038 "datasets are mounted but sharing of some datasets "
8039 "has failed\n"));
8040 } else if (ms_status == EZFS_MOUNTFAILED) {
8041 (void) fprintf(stderr, gettext("Split was successful"
8042 ", but some datasets could not be mounted\n"));
8043 (void) fprintf(stderr, gettext("Try doing '%s' with a "
8044 "different altroot\n"), "zpool import");
8045 }
8046 }
8047 zpool_close(zhp);
8048 nvlist_free(config);
8049 nvlist_free(props);
8050
8051 return (ret);
8052 }
8053
8054
8055 /*
8056 * zpool online [--power] <pool> <device> ...
8057 *
8058 * --power: Power on the enclosure slot to the drive (if possible)
8059 */
8060 int
zpool_do_online(int argc,char ** argv)8061 zpool_do_online(int argc, char **argv)
8062 {
8063 int c, i;
8064 char *poolname;
8065 zpool_handle_t *zhp;
8066 int ret = 0;
8067 vdev_state_t newstate;
8068 int flags = 0;
8069 boolean_t is_power_on = B_FALSE;
8070 struct option long_options[] = {
8071 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8072 {0, 0, 0, 0}
8073 };
8074
8075 /* check options */
8076 while ((c = getopt_long(argc, argv, "e", long_options, NULL)) != -1) {
8077 switch (c) {
8078 case 'e':
8079 flags |= ZFS_ONLINE_EXPAND;
8080 break;
8081 case ZPOOL_OPTION_POWER:
8082 is_power_on = B_TRUE;
8083 break;
8084 case '?':
8085 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8086 optopt);
8087 usage(B_FALSE);
8088 }
8089 }
8090
8091 if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8092 is_power_on = B_TRUE;
8093
8094 argc -= optind;
8095 argv += optind;
8096
8097 /* get pool name and check number of arguments */
8098 if (argc < 1) {
8099 (void) fprintf(stderr, gettext("missing pool name\n"));
8100 usage(B_FALSE);
8101 }
8102 if (argc < 2) {
8103 (void) fprintf(stderr, gettext("missing device name\n"));
8104 usage(B_FALSE);
8105 }
8106
8107 poolname = argv[0];
8108
8109 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8110 (void) fprintf(stderr, gettext("failed to open pool "
8111 "\"%s\"\n"), poolname);
8112 return (1);
8113 }
8114
8115 for (i = 1; i < argc; i++) {
8116 vdev_state_t oldstate;
8117 boolean_t avail_spare, l2cache;
8118 int rc;
8119
8120 if (is_power_on) {
8121 rc = zpool_power_on_and_disk_wait(zhp, argv[i]);
8122 if (rc == ENOTSUP) {
8123 (void) fprintf(stderr,
8124 gettext("Power control not supported\n"));
8125 }
8126 if (rc != 0)
8127 return (rc);
8128 }
8129
8130 nvlist_t *tgt = zpool_find_vdev(zhp, argv[i], &avail_spare,
8131 &l2cache, NULL);
8132 if (tgt == NULL) {
8133 ret = 1;
8134 (void) fprintf(stderr, gettext("couldn't find device "
8135 "\"%s\" in pool \"%s\"\n"), argv[i], poolname);
8136 continue;
8137 }
8138 uint_t vsc;
8139 oldstate = ((vdev_stat_t *)fnvlist_lookup_uint64_array(tgt,
8140 ZPOOL_CONFIG_VDEV_STATS, &vsc))->vs_state;
8141 if ((rc = zpool_vdev_online(zhp, argv[i], flags,
8142 &newstate)) == 0) {
8143 if (newstate != VDEV_STATE_HEALTHY) {
8144 (void) printf(gettext("warning: device '%s' "
8145 "onlined, but remains in faulted state\n"),
8146 argv[i]);
8147 if (newstate == VDEV_STATE_FAULTED)
8148 (void) printf(gettext("use 'zpool "
8149 "clear' to restore a faulted "
8150 "device\n"));
8151 else
8152 (void) printf(gettext("use 'zpool "
8153 "replace' to replace devices "
8154 "that are no longer present\n"));
8155 if ((flags & ZFS_ONLINE_EXPAND)) {
8156 (void) printf(gettext("%s: failed "
8157 "to expand usable space on "
8158 "unhealthy device '%s'\n"),
8159 (oldstate >= VDEV_STATE_DEGRADED ?
8160 "error" : "warning"), argv[i]);
8161 if (oldstate >= VDEV_STATE_DEGRADED) {
8162 ret = 1;
8163 break;
8164 }
8165 }
8166 }
8167 } else {
8168 (void) fprintf(stderr, gettext("Failed to online "
8169 "\"%s\" in pool \"%s\": %d\n"),
8170 argv[i], poolname, rc);
8171 ret = 1;
8172 }
8173 }
8174
8175 zpool_close(zhp);
8176
8177 return (ret);
8178 }
8179
8180 /*
8181 * zpool offline [-ft]|[--power] <pool> <device> ...
8182 *
8183 *
8184 * -f Force the device into a faulted state.
8185 *
8186 * -t Only take the device off-line temporarily. The offline/faulted
8187 * state will not be persistent across reboots.
8188 *
8189 * --power Power off the enclosure slot to the drive (if possible)
8190 */
8191 int
zpool_do_offline(int argc,char ** argv)8192 zpool_do_offline(int argc, char **argv)
8193 {
8194 int c, i;
8195 char *poolname;
8196 zpool_handle_t *zhp;
8197 int ret = 0;
8198 boolean_t istmp = B_FALSE;
8199 boolean_t fault = B_FALSE;
8200 boolean_t is_power_off = B_FALSE;
8201
8202 struct option long_options[] = {
8203 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8204 {0, 0, 0, 0}
8205 };
8206
8207 /* check options */
8208 while ((c = getopt_long(argc, argv, "ft", long_options, NULL)) != -1) {
8209 switch (c) {
8210 case 'f':
8211 fault = B_TRUE;
8212 break;
8213 case 't':
8214 istmp = B_TRUE;
8215 break;
8216 case ZPOOL_OPTION_POWER:
8217 is_power_off = B_TRUE;
8218 break;
8219 case '?':
8220 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8221 optopt);
8222 usage(B_FALSE);
8223 }
8224 }
8225
8226 if (is_power_off && fault) {
8227 (void) fprintf(stderr,
8228 gettext("-0 and -f cannot be used together\n"));
8229 usage(B_FALSE);
8230 }
8231
8232 if (is_power_off && istmp) {
8233 (void) fprintf(stderr,
8234 gettext("-0 and -t cannot be used together\n"));
8235 usage(B_FALSE);
8236 }
8237
8238 argc -= optind;
8239 argv += optind;
8240
8241 /* get pool name and check number of arguments */
8242 if (argc < 1) {
8243 (void) fprintf(stderr, gettext("missing pool name\n"));
8244 usage(B_FALSE);
8245 }
8246 if (argc < 2) {
8247 (void) fprintf(stderr, gettext("missing device name\n"));
8248 usage(B_FALSE);
8249 }
8250
8251 poolname = argv[0];
8252
8253 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8254 (void) fprintf(stderr, gettext("failed to open pool "
8255 "\"%s\"\n"), poolname);
8256 return (1);
8257 }
8258
8259 for (i = 1; i < argc; i++) {
8260 uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
8261 if (is_power_off) {
8262 /*
8263 * Note: we have to power off first, then set REMOVED,
8264 * or else zpool_vdev_set_removed_state() returns
8265 * EAGAIN.
8266 */
8267 ret = zpool_power_off(zhp, argv[i]);
8268 if (ret != 0) {
8269 (void) fprintf(stderr, "%s %s %d\n",
8270 gettext("unable to power off slot for"),
8271 argv[i], ret);
8272 }
8273 (void) zpool_vdev_set_removed_state(zhp, guid,
8274 VDEV_AUX_NONE);
8275
8276 } else if (fault) {
8277 vdev_aux_t aux;
8278 if (istmp == B_FALSE) {
8279 /* Force the fault to persist across imports */
8280 aux = VDEV_AUX_EXTERNAL_PERSIST;
8281 } else {
8282 aux = VDEV_AUX_EXTERNAL;
8283 }
8284
8285 if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
8286 ret = 1;
8287 } else {
8288 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
8289 ret = 1;
8290 }
8291 }
8292
8293 zpool_close(zhp);
8294
8295 return (ret);
8296 }
8297
8298 /*
8299 * zpool clear [--power] <pool> [device]
8300 *
8301 * Clear all errors associated with a pool or a particular device.
8302 */
8303 int
zpool_do_clear(int argc,char ** argv)8304 zpool_do_clear(int argc, char **argv)
8305 {
8306 int c;
8307 int ret = 0;
8308 boolean_t is_power_on = B_FALSE;
8309 nvlist_t *policy = NULL;
8310 zpool_handle_t *zhp;
8311 char *pool, *device;
8312
8313 struct option long_options[] = {
8314 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8315 {0, 0, 0, 0}
8316 };
8317
8318 /* check options */
8319 while ((c = getopt_long(argc, argv, "", long_options,
8320 NULL)) != -1) {
8321 switch (c) {
8322 case ZPOOL_OPTION_POWER:
8323 is_power_on = B_TRUE;
8324 break;
8325 case '?':
8326 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8327 optopt);
8328 usage(B_FALSE);
8329 }
8330 }
8331
8332 if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8333 is_power_on = B_TRUE;
8334
8335 argc -= optind;
8336 argv += optind;
8337
8338 if (argc < 1) {
8339 (void) fprintf(stderr, gettext("missing pool name\n"));
8340 usage(B_FALSE);
8341 }
8342
8343 if (argc > 2) {
8344 (void) fprintf(stderr, gettext("too many arguments\n"));
8345 usage(B_FALSE);
8346 }
8347
8348 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0)
8349 return (1);
8350
8351 pool = argv[0];
8352 device = argc == 2 ? argv[1] : NULL;
8353
8354 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
8355 nvlist_free(policy);
8356 return (1);
8357 }
8358
8359 if (is_power_on) {
8360 if (device == NULL) {
8361 (void) zpool_power_on_pool_and_wait_for_devices(zhp);
8362 } else {
8363 (void) zpool_power_on_and_disk_wait(zhp, device);
8364 }
8365 }
8366
8367 if (zpool_clear(zhp, device, policy) != 0)
8368 ret = 1;
8369
8370 zpool_close(zhp);
8371
8372 nvlist_free(policy);
8373
8374 return (ret);
8375 }
8376
8377 /*
8378 * zpool reguid [-g <guid>] <pool>
8379 */
8380 int
zpool_do_reguid(int argc,char ** argv)8381 zpool_do_reguid(int argc, char **argv)
8382 {
8383 uint64_t guid;
8384 uint64_t *guidp = NULL;
8385 int c;
8386 char *endptr;
8387 char *poolname;
8388 zpool_handle_t *zhp;
8389 int ret = 0;
8390
8391 /* check options */
8392 while ((c = getopt(argc, argv, "g:")) != -1) {
8393 switch (c) {
8394 case 'g':
8395 errno = 0;
8396 guid = strtoull(optarg, &endptr, 10);
8397 if (errno != 0 || *endptr != '\0') {
8398 (void) fprintf(stderr,
8399 gettext("invalid GUID: %s\n"), optarg);
8400 usage(B_FALSE);
8401 }
8402 guidp = &guid;
8403 break;
8404 case '?':
8405 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8406 optopt);
8407 usage(B_FALSE);
8408 }
8409 }
8410
8411 argc -= optind;
8412 argv += optind;
8413
8414 /* get pool name and check number of arguments */
8415 if (argc < 1) {
8416 (void) fprintf(stderr, gettext("missing pool name\n"));
8417 usage(B_FALSE);
8418 }
8419
8420 if (argc > 1) {
8421 (void) fprintf(stderr, gettext("too many arguments\n"));
8422 usage(B_FALSE);
8423 }
8424
8425 poolname = argv[0];
8426 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
8427 return (1);
8428
8429 ret = zpool_set_guid(zhp, guidp);
8430
8431 zpool_close(zhp);
8432 return (ret);
8433 }
8434
8435
8436 /*
8437 * zpool reopen <pool>
8438 *
8439 * Reopen the pool so that the kernel can update the sizes of all vdevs.
8440 */
8441 int
zpool_do_reopen(int argc,char ** argv)8442 zpool_do_reopen(int argc, char **argv)
8443 {
8444 int c;
8445 int ret = 0;
8446 boolean_t scrub_restart = B_TRUE;
8447
8448 /* check options */
8449 while ((c = getopt(argc, argv, "n")) != -1) {
8450 switch (c) {
8451 case 'n':
8452 scrub_restart = B_FALSE;
8453 break;
8454 case '?':
8455 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8456 optopt);
8457 usage(B_FALSE);
8458 }
8459 }
8460
8461 argc -= optind;
8462 argv += optind;
8463
8464 /* if argc == 0 we will execute zpool_reopen_one on all pools */
8465 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8466 B_FALSE, zpool_reopen_one, &scrub_restart);
8467
8468 return (ret);
8469 }
8470
8471 typedef struct scrub_cbdata {
8472 int cb_type;
8473 pool_scrub_cmd_t cb_scrub_cmd;
8474 pool_scrub_flags_t cb_scrub_flags;
8475 time_t cb_date_start;
8476 time_t cb_date_end;
8477 } scrub_cbdata_t;
8478
8479 static boolean_t
zpool_has_checkpoint(zpool_handle_t * zhp)8480 zpool_has_checkpoint(zpool_handle_t *zhp)
8481 {
8482 nvlist_t *config, *nvroot;
8483
8484 config = zpool_get_config(zhp, NULL);
8485
8486 if (config != NULL) {
8487 pool_checkpoint_stat_t *pcs = NULL;
8488 uint_t c;
8489
8490 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
8491 (void) nvlist_lookup_uint64_array(nvroot,
8492 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
8493
8494 if (pcs == NULL || pcs->pcs_state == CS_NONE)
8495 return (B_FALSE);
8496
8497 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
8498 pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
8499 return (B_TRUE);
8500 }
8501
8502 return (B_FALSE);
8503 }
8504
8505 static int
scrub_callback(zpool_handle_t * zhp,void * data)8506 scrub_callback(zpool_handle_t *zhp, void *data)
8507 {
8508 scrub_cbdata_t *cb = data;
8509 int err;
8510
8511 /*
8512 * Ignore faulted pools.
8513 */
8514 if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
8515 (void) fprintf(stderr, gettext("cannot scan '%s': pool is "
8516 "currently unavailable\n"), zpool_get_name(zhp));
8517 return (1);
8518 }
8519
8520 err = zpool_scan_range(zhp, cb->cb_type, cb->cb_scrub_cmd,
8521 cb->cb_scrub_flags, cb->cb_date_start, cb->cb_date_end);
8522 if (err == 0 && zpool_has_checkpoint(zhp) &&
8523 cb->cb_type == POOL_SCAN_SCRUB) {
8524 (void) printf(gettext("warning: will not scrub state that "
8525 "belongs to the checkpoint of pool '%s'\n"),
8526 zpool_get_name(zhp));
8527 }
8528
8529 return (err != 0);
8530 }
8531
8532 static int
wait_callback(zpool_handle_t * zhp,void * data)8533 wait_callback(zpool_handle_t *zhp, void *data)
8534 {
8535 zpool_wait_activity_t *act = data;
8536 return (zpool_wait(zhp, *act));
8537 }
8538
8539 static time_t
date_string_to_sec(const char * timestr,boolean_t rounding)8540 date_string_to_sec(const char *timestr, boolean_t rounding)
8541 {
8542 struct tm tm = {0};
8543 int adjustment = rounding ? 1 : 0;
8544
8545 /* Allow mktime to determine timezone. */
8546 tm.tm_isdst = -1;
8547
8548 if (strptime(timestr, "%Y-%m-%d %H:%M", &tm) == NULL) {
8549 if (strptime(timestr, "%Y-%m-%d", &tm) == NULL) {
8550 fprintf(stderr, gettext("Failed to parse the date.\n"));
8551 usage(B_FALSE);
8552 }
8553 adjustment *= 24 * 60 * 60;
8554 } else {
8555 adjustment *= 60;
8556 }
8557
8558 return (mktime(&tm) + adjustment);
8559 }
8560
8561 /*
8562 * zpool scrub [-e | -s | -p | -C | -E | -S | -t] [-w] [-a | <pool> ...]
8563 *
8564 * -a Scrub all pools.
8565 * -e Only scrub blocks in the error log.
8566 * -E End date of scrub.
8567 * -S Start date of scrub.
8568 * -s Stop. Stops any in-progress scrub.
8569 * -p Pause. Pause in-progress scrub.
8570 * -w Wait. Blocks until scrub has completed.
8571 * -t Decompress and decrypt (if key is loaded) scrubbed blocks.
8572 * -C Scrub from last saved txg.
8573 */
8574 int
zpool_do_scrub(int argc,char ** argv)8575 zpool_do_scrub(int argc, char **argv)
8576 {
8577 int c;
8578 scrub_cbdata_t cb;
8579 boolean_t wait = B_FALSE;
8580 int error;
8581
8582 cb.cb_type = POOL_SCAN_SCRUB;
8583 cb.cb_scrub_cmd = 0;
8584 cb.cb_scrub_flags = 0;
8585 cb.cb_date_start = cb.cb_date_end = 0;
8586
8587 boolean_t is_error_scrub = B_FALSE;
8588 boolean_t is_pause = B_FALSE;
8589 boolean_t is_stop = B_FALSE;
8590 boolean_t scrub_all = B_FALSE;
8591
8592 /* check options */
8593 while ((c = getopt(argc, argv, "aspweCE:S:t")) != -1) {
8594 switch (c) {
8595 case 'a':
8596 scrub_all = B_TRUE;
8597 break;
8598 case 'e':
8599 is_error_scrub = B_TRUE;
8600 break;
8601 case 't':
8602 cb.cb_scrub_flags |= POOL_SCRUB_THOROUGH;
8603 break;
8604 case 'E':
8605 /*
8606 * Round the date. It's better to scrub more data than
8607 * less. This also makes the date inclusive.
8608 */
8609 cb.cb_date_end = date_string_to_sec(optarg, B_TRUE);
8610 break;
8611 case 's':
8612 is_stop = B_TRUE;
8613 break;
8614 case 'S':
8615 cb.cb_date_start = date_string_to_sec(optarg, B_FALSE);
8616 break;
8617 case 'p':
8618 is_pause = B_TRUE;
8619 break;
8620 case 'w':
8621 wait = B_TRUE;
8622 break;
8623 case 'C':
8624 cb.cb_scrub_cmd |= POOL_SCRUB_FROM_LAST_TXG;
8625 break;
8626 case '?':
8627 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8628 optopt);
8629 usage(B_FALSE);
8630 }
8631 }
8632
8633 if (is_pause && is_stop) {
8634 (void) fprintf(stderr, gettext("invalid option "
8635 "combination: -s and -p are mutually exclusive\n"));
8636 usage(B_FALSE);
8637 } else if (is_error_scrub && is_pause) {
8638 (void) fprintf(stderr, gettext("invalid option "
8639 "combination: -e and -p are mutually exclusive\n"));
8640 usage(B_FALSE);
8641 } else if (is_error_scrub && is_stop) {
8642 (void) fprintf(stderr, gettext("invalid option "
8643 "combination: -e and -s are mutually exclusive\n"));
8644 usage(B_FALSE);
8645 } else if (is_error_scrub &&
8646 (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8647 (void) fprintf(stderr, gettext("invalid option "
8648 "combination: -e and -C are mutually exclusive\n"));
8649 usage(B_FALSE);
8650 } else if (is_error_scrub &&
8651 (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH)) {
8652 (void) fprintf(stderr, gettext("invalid option "
8653 "combination: -e and -t are mutually exclusive\n"));
8654 usage(B_FALSE);
8655 } else if (is_pause && (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8656 (void) fprintf(stderr, gettext("invalid option "
8657 "combination: -p and -C are mutually exclusive\n"));
8658 usage(B_FALSE);
8659 } else if (is_pause && (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH)) {
8660 (void) fprintf(stderr, gettext("invalid option "
8661 "combination: -p and -t are mutually exclusive\n"));
8662 usage(B_FALSE);
8663 } else if (is_stop && (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8664 (void) fprintf(stderr, gettext("invalid option "
8665 "combination: -s and -C are mutually exclusive\n"));
8666 usage(B_FALSE);
8667 } else if (is_stop && (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH)) {
8668 (void) fprintf(stderr, gettext("invalid option "
8669 "combination: -s and -t are mutually exclusive\n"));
8670 usage(B_FALSE);
8671 } else {
8672 if (is_error_scrub)
8673 cb.cb_type = POOL_SCAN_ERRORSCRUB;
8674
8675 if (is_pause) {
8676 cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
8677 } else if (is_stop) {
8678 cb.cb_type = POOL_SCAN_NONE;
8679 }
8680 }
8681
8682 boolean_t is_thorough =
8683 (cb.cb_scrub_flags & POOL_SCRUB_THOROUGH) != 0;
8684 if ((cb.cb_date_start != 0 || cb.cb_date_end != 0) &&
8685 (cb.cb_scrub_cmd & POOL_SCRUB_FROM_LAST_TXG)) {
8686 (void) fprintf(stderr, gettext("invalid option "
8687 "combination: -C and -S/-E date are mutually "
8688 "exclusive\n"));
8689 usage(B_FALSE);
8690 } else if ((cb.cb_date_start != 0 || cb.cb_date_end != 0) &&
8691 (is_error_scrub || is_stop || is_pause ||
8692 (!is_thorough && cb.cb_scrub_cmd != POOL_SCRUB_NORMAL))) {
8693 (void) fprintf(stderr, gettext("invalid option "
8694 "combination: start/end date is available only "
8695 "with normal or thorough scrub\n"));
8696 usage(B_FALSE);
8697 }
8698
8699 if (cb.cb_date_start != 0 && cb.cb_date_end != 0 &&
8700 cb.cb_date_start > cb.cb_date_end) {
8701 (void) fprintf(stderr, gettext("invalid arguments: "
8702 "end date has to be later than start date\n"));
8703 usage(B_FALSE);
8704 }
8705
8706 if (wait && (cb.cb_type == POOL_SCAN_NONE ||
8707 cb.cb_scrub_cmd == POOL_SCRUB_PAUSE)) {
8708 (void) fprintf(stderr, gettext("invalid option combination: "
8709 "-w cannot be used with -p or -s\n"));
8710 usage(B_FALSE);
8711 }
8712
8713 argc -= optind;
8714 argv += optind;
8715
8716 if (argc < 1 && !scrub_all) {
8717 (void) fprintf(stderr, gettext("missing pool name argument\n"));
8718 usage(B_FALSE);
8719 }
8720
8721 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8722 B_FALSE, scrub_callback, &cb);
8723
8724 if (wait && !error) {
8725 zpool_wait_activity_t act = ZPOOL_WAIT_SCRUB;
8726 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8727 B_FALSE, wait_callback, &act);
8728 }
8729
8730 return (error);
8731 }
8732
8733 /*
8734 * zpool resilver <pool> ...
8735 *
8736 * Restarts any in-progress resilver
8737 */
8738 int
zpool_do_resilver(int argc,char ** argv)8739 zpool_do_resilver(int argc, char **argv)
8740 {
8741 int c;
8742 scrub_cbdata_t cb;
8743
8744 cb.cb_type = POOL_SCAN_RESILVER;
8745 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8746 cb.cb_scrub_flags = 0;
8747 cb.cb_date_start = cb.cb_date_end = 0;
8748
8749 /* check options */
8750 while ((c = getopt(argc, argv, "")) != -1) {
8751 switch (c) {
8752 case '?':
8753 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8754 optopt);
8755 usage(B_FALSE);
8756 }
8757 }
8758
8759 argc -= optind;
8760 argv += optind;
8761
8762 if (argc < 1) {
8763 (void) fprintf(stderr, gettext("missing pool name argument\n"));
8764 usage(B_FALSE);
8765 }
8766
8767 return (for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8768 B_FALSE, scrub_callback, &cb));
8769 }
8770
8771 /*
8772 * zpool trim [-d] [-r <rate>] [-c | -s] <-a | pool> [<device> ...]
8773 *
8774 * -a Trim all pools.
8775 * -c Cancel. Ends any in-progress trim.
8776 * -d Secure trim. Requires kernel and device support.
8777 * -r <rate> Sets the TRIM rate in bytes (per second). Supports
8778 * adding a multiplier suffix such as 'k' or 'm'.
8779 * -s Suspend. TRIM can then be restarted with no flags.
8780 * -w Wait. Blocks until trimming has completed.
8781 */
8782 int
zpool_do_trim(int argc,char ** argv)8783 zpool_do_trim(int argc, char **argv)
8784 {
8785 struct option long_options[] = {
8786 {"cancel", no_argument, NULL, 'c'},
8787 {"secure", no_argument, NULL, 'd'},
8788 {"rate", required_argument, NULL, 'r'},
8789 {"suspend", no_argument, NULL, 's'},
8790 {"wait", no_argument, NULL, 'w'},
8791 {"all", no_argument, NULL, 'a'},
8792 {0, 0, 0, 0}
8793 };
8794
8795 pool_trim_func_t cmd_type = POOL_TRIM_START;
8796 uint64_t rate = 0;
8797 boolean_t secure = B_FALSE;
8798 boolean_t wait = B_FALSE;
8799 boolean_t trimall = B_FALSE;
8800 int error;
8801
8802 int c;
8803 while ((c = getopt_long(argc, argv, "acdr:sw", long_options, NULL))
8804 != -1) {
8805 switch (c) {
8806 case 'a':
8807 trimall = B_TRUE;
8808 break;
8809 case 'c':
8810 if (cmd_type != POOL_TRIM_START &&
8811 cmd_type != POOL_TRIM_CANCEL) {
8812 (void) fprintf(stderr, gettext("-c cannot be "
8813 "combined with other options\n"));
8814 usage(B_FALSE);
8815 }
8816 cmd_type = POOL_TRIM_CANCEL;
8817 break;
8818 case 'd':
8819 if (cmd_type != POOL_TRIM_START) {
8820 (void) fprintf(stderr, gettext("-d cannot be "
8821 "combined with the -c or -s options\n"));
8822 usage(B_FALSE);
8823 }
8824 secure = B_TRUE;
8825 break;
8826 case 'r':
8827 if (cmd_type != POOL_TRIM_START) {
8828 (void) fprintf(stderr, gettext("-r cannot be "
8829 "combined with the -c or -s options\n"));
8830 usage(B_FALSE);
8831 }
8832 if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
8833 (void) fprintf(stderr, "%s: %s\n",
8834 gettext("invalid value for rate"),
8835 libzfs_error_description(g_zfs));
8836 usage(B_FALSE);
8837 }
8838 break;
8839 case 's':
8840 if (cmd_type != POOL_TRIM_START &&
8841 cmd_type != POOL_TRIM_SUSPEND) {
8842 (void) fprintf(stderr, gettext("-s cannot be "
8843 "combined with other options\n"));
8844 usage(B_FALSE);
8845 }
8846 cmd_type = POOL_TRIM_SUSPEND;
8847 break;
8848 case 'w':
8849 wait = B_TRUE;
8850 break;
8851 case '?':
8852 if (optopt != 0) {
8853 (void) fprintf(stderr,
8854 gettext("invalid option '%c'\n"), optopt);
8855 } else {
8856 (void) fprintf(stderr,
8857 gettext("invalid option '%s'\n"),
8858 argv[optind - 1]);
8859 }
8860 usage(B_FALSE);
8861 }
8862 }
8863
8864 argc -= optind;
8865 argv += optind;
8866
8867 trimflags_t trim_flags = {
8868 .secure = secure,
8869 .rate = rate,
8870 .wait = wait,
8871 };
8872
8873 trim_cbdata_t cbdata = {
8874 .trim_flags = trim_flags,
8875 .cmd_type = cmd_type
8876 };
8877
8878 if (argc < 1 && !trimall) {
8879 (void) fprintf(stderr, gettext("missing pool name argument\n"));
8880 usage(B_FALSE);
8881 }
8882
8883 if (wait && (cmd_type != POOL_TRIM_START)) {
8884 (void) fprintf(stderr, gettext("-w cannot be used with -c or "
8885 "-s options\n"));
8886 usage(B_FALSE);
8887 }
8888
8889 if (trimall && argc > 0) {
8890 (void) fprintf(stderr, gettext("-a cannot be combined with "
8891 "individual zpools or vdevs\n"));
8892 usage(B_FALSE);
8893 }
8894
8895 if (argc == 0 && trimall) {
8896 cbdata.trim_flags.fullpool = B_TRUE;
8897 /* Trim each pool recursively */
8898 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8899 B_FALSE, zpool_trim_one, &cbdata);
8900 } else if (argc == 1) {
8901 char *poolname = argv[0];
8902 zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8903 if (zhp == NULL)
8904 return (-1);
8905 /* no individual leaf vdevs specified, so add them all */
8906 error = zpool_trim_one(zhp, &cbdata);
8907 zpool_close(zhp);
8908 } else {
8909 char *poolname = argv[0];
8910 zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8911 if (zhp == NULL)
8912 return (-1);
8913 /* leaf vdevs specified, trim only those */
8914 cbdata.trim_flags.fullpool = B_FALSE;
8915 nvlist_t *vdevs = fnvlist_alloc();
8916 for (int i = 1; i < argc; i++) {
8917 fnvlist_add_boolean(vdevs, argv[i]);
8918 }
8919 error = zpool_trim(zhp, cbdata.cmd_type, vdevs,
8920 &cbdata.trim_flags);
8921 fnvlist_free(vdevs);
8922 zpool_close(zhp);
8923 }
8924
8925 return (error);
8926 }
8927
8928 static const char *condense_types[] = {
8929 POOL_CONDENSE_LOG_SPACEMAP,
8930 #ifdef ZFS_DEBUG
8931 "debug",
8932 #endif
8933 NULL,
8934 };
8935
8936 typedef struct {
8937 const char *cmd;
8938 const char *type;
8939 } condense_cb_t;
8940
8941 static int
condense_cb(zpool_handle_t * zhp,void * data)8942 condense_cb(zpool_handle_t *zhp, void *data)
8943 {
8944 condense_cb_t *cb = data;
8945 if (cb->type != NULL)
8946 return (zpool_condense(zhp, cb->cmd, cb->type));
8947
8948 int err = 0;
8949 for (uint_t i = 0; condense_types[i] != NULL; i++) {
8950 #ifdef ZFS_DEBUG
8951 /*
8952 * Skip the debug type when no type is specificed. This is
8953 * the "condense everything" mode, and people _do_ run debug
8954 * builds, and we don't want them to be accidentally running
8955 * the debug condense op.
8956 */
8957 if (strcmp(condense_types[i], "debug") == 0)
8958 continue;
8959 #endif
8960 err = zpool_condense(zhp, cb->cmd, condense_types[i]);
8961
8962 /*
8963 * Quietly ignore ENOTSUP, so we don't fail all condense types
8964 * just because one isn't supporte.d
8965 */
8966 if (err != 0 && err != ENOTSUP)
8967 break;
8968 }
8969
8970 return (err);
8971 }
8972
8973 /*
8974 * zpool condense [-t <type>] [-c | -w] [-a | <pool> ...]
8975 *
8976 * -t <type> What to condense.
8977 * -a Condense all pools.
8978 * -c Cancel. Ends any in-progress condense.
8979 * -w Wait. Blocks until condense has completed.
8980 *
8981 * Condense (flush, garbage-collect) the pool metadata on the specfied pools.
8982 */
8983 static int
zpool_do_condense(int argc,char ** argv)8984 zpool_do_condense(int argc, char **argv)
8985 {
8986 struct option long_options[] = {
8987 {"type", required_argument, NULL, 't'},
8988 {"all", no_argument, NULL, 'a'},
8989 {"cancel", no_argument, NULL, 'c'},
8990 {"wait", no_argument, NULL, 'w'},
8991 {"types", no_argument, NULL,
8992 ZPOOL_OPTION_CONDENSE_LIST_TYPES},
8993 {0, 0, 0, 0}
8994 };
8995
8996 condense_cb_t cb = {
8997 .cmd = "start",
8998 .type = NULL,
8999 };
9000
9001 boolean_t cancel = B_FALSE;
9002 boolean_t all_pools = B_FALSE;
9003 boolean_t wait = B_FALSE;
9004
9005 int c;
9006 while ((c = getopt_long(argc, argv, "at:cw", long_options, NULL))
9007 != -1) {
9008 switch (c) {
9009 case 'a':
9010 all_pools = B_TRUE;
9011 break;
9012 case 't': {
9013 for (uint_t i = 0; condense_types[i] != NULL; i++) {
9014 if (strcmp(condense_types[i], optarg) == 0) {
9015 cb.type = condense_types[i];
9016 break;
9017 }
9018 }
9019 if (cb.type == NULL) {
9020 (void) fprintf(stderr,
9021 gettext("invalid condense type '%s'\n"),
9022 optarg);
9023 usage(B_FALSE);
9024 }
9025 break;
9026 }
9027 case 'c':
9028 cb.cmd = "cancel";
9029 cancel = B_TRUE;
9030 break;
9031 case 'w':
9032 wait = B_TRUE;
9033 break;
9034 case ZPOOL_OPTION_CONDENSE_LIST_TYPES:
9035 for (uint_t i = 0; condense_types[i] != NULL; i++)
9036 printf("%s\n", condense_types[i]);
9037 return (0);
9038 case '?':
9039 if (optopt != 0) {
9040 (void) fprintf(stderr,
9041 gettext("invalid option '%c'\n"), optopt);
9042 } else {
9043 (void) fprintf(stderr,
9044 gettext("invalid option '%s'\n"),
9045 argv[optind - 1]);
9046 }
9047 usage(B_FALSE);
9048 }
9049 }
9050
9051 argc -= optind;
9052 argv += optind;
9053
9054 if (argc < 1 && !all_pools) {
9055 (void) fprintf(stderr, gettext("missing pool name argument\n"));
9056 usage(B_FALSE);
9057 return (-1);
9058 }
9059
9060 if (wait && cancel) {
9061 (void) fprintf(stderr, gettext("-w cannot be used with -c\n"));
9062 usage(B_FALSE);
9063 }
9064
9065 int error = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9066 B_FALSE, condense_cb, &cb);
9067
9068 if (wait && !error) {
9069 zpool_wait_activity_t act = ZPOOL_WAIT_CONDENSE;
9070 error = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9071 B_FALSE, wait_callback, &act);
9072 }
9073
9074 return (error);
9075 }
9076
9077
9078 /*
9079 * Converts a total number of seconds to a human readable string broken
9080 * down in to days/hours/minutes/seconds.
9081 */
9082 static void
secs_to_dhms(uint64_t total,char * buf)9083 secs_to_dhms(uint64_t total, char *buf)
9084 {
9085 uint64_t days = total / 60 / 60 / 24;
9086 uint64_t hours = (total / 60 / 60) % 24;
9087 uint64_t mins = (total / 60) % 60;
9088 uint64_t secs = (total % 60);
9089
9090 if (days > 0) {
9091 (void) sprintf(buf, "%llu days %02llu:%02llu:%02llu",
9092 (u_longlong_t)days, (u_longlong_t)hours,
9093 (u_longlong_t)mins, (u_longlong_t)secs);
9094 } else {
9095 (void) sprintf(buf, "%02llu:%02llu:%02llu",
9096 (u_longlong_t)hours, (u_longlong_t)mins,
9097 (u_longlong_t)secs);
9098 }
9099 }
9100
9101 /*
9102 * Print out detailed error scrub status.
9103 */
9104 static void
print_err_scrub_status(pool_scan_stat_t * ps)9105 print_err_scrub_status(pool_scan_stat_t *ps)
9106 {
9107 time_t start, end, pause;
9108 uint64_t total_secs_left;
9109 uint64_t secs_left, mins_left, hours_left, days_left;
9110 uint64_t examined, to_be_examined;
9111
9112 if (ps == NULL || ps->pss_error_scrub_func != POOL_SCAN_ERRORSCRUB) {
9113 return;
9114 }
9115
9116 (void) printf(gettext(" scrub: "));
9117
9118 start = ps->pss_error_scrub_start;
9119 end = ps->pss_error_scrub_end;
9120 pause = ps->pss_pass_error_scrub_pause;
9121 examined = ps->pss_error_scrub_examined;
9122 to_be_examined = ps->pss_error_scrub_to_be_examined;
9123
9124 assert(ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB);
9125
9126 if (ps->pss_error_scrub_state == DSS_FINISHED) {
9127 total_secs_left = end - start;
9128 days_left = total_secs_left / 60 / 60 / 24;
9129 hours_left = (total_secs_left / 60 / 60) % 24;
9130 mins_left = (total_secs_left / 60) % 60;
9131 secs_left = (total_secs_left % 60);
9132
9133 (void) printf(gettext("scrubbed %llu error blocks in %llu days "
9134 "%02llu:%02llu:%02llu on %s"), (u_longlong_t)examined,
9135 (u_longlong_t)days_left, (u_longlong_t)hours_left,
9136 (u_longlong_t)mins_left, (u_longlong_t)secs_left,
9137 ctime(&end));
9138
9139 return;
9140 } else if (ps->pss_error_scrub_state == DSS_CANCELED) {
9141 (void) printf(gettext("error scrub canceled on %s"),
9142 ctime(&end));
9143 return;
9144 }
9145 assert(ps->pss_error_scrub_state == DSS_ERRORSCRUBBING);
9146
9147 /* Error scrub is in progress. */
9148 if (pause == 0) {
9149 (void) printf(gettext("error scrub in progress since %s"),
9150 ctime(&start));
9151 } else {
9152 (void) printf(gettext("error scrub paused since %s"),
9153 ctime(&pause));
9154 (void) printf(gettext("\terror scrub started on %s"),
9155 ctime(&start));
9156 }
9157
9158 double fraction_done = (double)examined / (to_be_examined + examined);
9159 (void) printf(gettext("\t%.2f%% done, issued I/O for %llu error"
9160 " blocks"), 100 * fraction_done, (u_longlong_t)examined);
9161
9162 (void) printf("\n");
9163 }
9164
9165 /*
9166 * Print out detailed scrub status.
9167 */
9168 static void
print_scan_scrub_resilver_status(pool_scan_stat_t * ps,boolean_t is_thorough)9169 print_scan_scrub_resilver_status(pool_scan_stat_t *ps, boolean_t is_thorough)
9170 {
9171 time_t start, end, pause;
9172 uint64_t pass_scanned, scanned, pass_issued, issued, total_s, total_i;
9173 uint64_t elapsed, scan_rate, issue_rate;
9174 double fraction_done;
9175 char processed_buf[7], scanned_buf[7], issued_buf[7], total_s_buf[7];
9176 char total_i_buf[7], srate_buf[7], irate_buf[7], time_buf[32];
9177
9178 printf(" ");
9179 (void) printf_color(ANSI_BOLD, gettext("scan:"));
9180 printf(" ");
9181
9182 /* If there's never been a scan, there's not much to say. */
9183 if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
9184 ps->pss_func >= POOL_SCAN_FUNCS) {
9185 (void) printf(gettext("none requested\n"));
9186 return;
9187 }
9188
9189 start = ps->pss_start_time;
9190 end = ps->pss_end_time;
9191 pause = ps->pss_pass_scrub_pause;
9192
9193 zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
9194
9195 int is_resilver = ps->pss_func == POOL_SCAN_RESILVER;
9196 int is_scrub = ps->pss_func == POOL_SCAN_SCRUB;
9197 assert(is_resilver || is_scrub);
9198
9199 /* Scan is finished or canceled. */
9200 if (ps->pss_state == DSS_FINISHED) {
9201 secs_to_dhms(end - start, time_buf);
9202
9203 if (is_scrub) {
9204 if (is_thorough) {
9205 (void) printf(gettext("thorough scrub "
9206 "repaired %s in %s with %llu errors on %s"),
9207 processed_buf, time_buf,
9208 (u_longlong_t)ps->pss_errors, ctime(&end));
9209 } else {
9210 (void) printf(gettext("scrub repaired %s "
9211 "in %s with %llu errors on %s"),
9212 processed_buf, time_buf,
9213 (u_longlong_t)ps->pss_errors, ctime(&end));
9214 }
9215 } else if (is_resilver) {
9216 (void) printf(gettext("resilvered %s "
9217 "in %s with %llu errors on %s"), processed_buf,
9218 time_buf, (u_longlong_t)ps->pss_errors,
9219 ctime(&end));
9220 }
9221 return;
9222 } else if (ps->pss_state == DSS_CANCELED) {
9223 if (is_scrub) {
9224 if (is_thorough) {
9225 (void) printf(gettext("thorough scrub canceled "
9226 "on %s"), ctime(&end));
9227 } else {
9228 (void) printf(gettext("scrub canceled on %s"),
9229 ctime(&end));
9230 }
9231 } else if (is_resilver) {
9232 (void) printf(gettext("resilver canceled on %s"),
9233 ctime(&end));
9234 }
9235 return;
9236 }
9237
9238 assert(ps->pss_state == DSS_SCANNING);
9239
9240 /* Scan is in progress. Resilvers can't be paused. */
9241 if (is_scrub) {
9242 if (pause == 0) {
9243 if (is_thorough) {
9244 (void) printf(gettext("thorough scrub "
9245 "in progress since %s"), ctime(&start));
9246 } else {
9247 (void) printf(gettext("scrub in progress "
9248 "since %s"), ctime(&start));
9249 }
9250 } else {
9251 if (is_thorough) {
9252 (void) printf(gettext("thorough scrub paused "
9253 "since %s"), ctime(&pause));
9254 (void) printf(gettext("\tthorough scrub "
9255 "started on %s"), ctime(&start));
9256 } else {
9257 (void) printf(gettext("scrub paused since %s"),
9258 ctime(&pause));
9259 (void) printf(gettext("\tscrub started on %s"),
9260 ctime(&start));
9261 }
9262 }
9263 } else if (is_resilver) {
9264 (void) printf(gettext("resilver in progress since %s"),
9265 ctime(&start));
9266 }
9267
9268 scanned = ps->pss_examined;
9269 pass_scanned = ps->pss_pass_exam;
9270 issued = ps->pss_issued;
9271 pass_issued = ps->pss_pass_issued;
9272 total_s = ps->pss_to_examine;
9273 total_i = ps->pss_to_examine - ps->pss_skipped;
9274
9275 /* we are only done with a block once we have issued the IO for it */
9276 fraction_done = (double)issued / total_i;
9277
9278 /* elapsed time for this pass, rounding up to 1 if it's 0 */
9279 elapsed = time(NULL) - ps->pss_pass_start;
9280 elapsed -= ps->pss_pass_scrub_spent_paused;
9281 elapsed = (elapsed != 0) ? elapsed : 1;
9282
9283 scan_rate = pass_scanned / elapsed;
9284 issue_rate = pass_issued / elapsed;
9285
9286 /* format all of the numbers we will be reporting */
9287 zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
9288 zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
9289 zfs_nicebytes(total_s, total_s_buf, sizeof (total_s_buf));
9290 zfs_nicebytes(total_i, total_i_buf, sizeof (total_i_buf));
9291
9292 /* do not print estimated time if we have a paused scrub */
9293 (void) printf(gettext("\t%s / %s scanned"), scanned_buf, total_s_buf);
9294 if (pause == 0 && scan_rate > 0) {
9295 zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
9296 (void) printf(gettext(" at %s/s"), srate_buf);
9297 }
9298 (void) printf(gettext(", %s / %s issued"), issued_buf, total_i_buf);
9299 if (pause == 0 && issue_rate > 0) {
9300 zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
9301 (void) printf(gettext(" at %s/s"), irate_buf);
9302 }
9303 (void) printf(gettext("\n"));
9304
9305 if (is_resilver) {
9306 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
9307 processed_buf, 100 * fraction_done);
9308 } else if (is_scrub) {
9309 (void) printf(gettext("\t%s repaired, %.2f%% done"),
9310 processed_buf, 100 * fraction_done);
9311 }
9312
9313 if (pause == 0) {
9314 /*
9315 * Only provide an estimate iff:
9316 * 1) we haven't yet issued all we expected, and
9317 * 2) the issue rate exceeds 10 MB/s, and
9318 * 3) it's either:
9319 * a) a resilver which has started repairs, or
9320 * b) a scrub which has entered the issue phase.
9321 */
9322 if (total_i >= issued && issue_rate >= 10 * 1024 * 1024 &&
9323 ((is_resilver && ps->pss_processed > 0) ||
9324 (is_scrub && issued > 0))) {
9325 secs_to_dhms((total_i - issued) / issue_rate, time_buf);
9326 (void) printf(gettext(", %s to go\n"), time_buf);
9327 } else {
9328 (void) printf(gettext(", no estimated "
9329 "completion time\n"));
9330 }
9331 } else {
9332 (void) printf(gettext("\n"));
9333 }
9334 }
9335
9336 static void
print_rebuild_status_impl(vdev_rebuild_stat_t * vrs,uint_t c,char * vdev_name)9337 print_rebuild_status_impl(vdev_rebuild_stat_t *vrs, uint_t c, char *vdev_name)
9338 {
9339 if (vrs == NULL || vrs->vrs_state == VDEV_REBUILD_NONE)
9340 return;
9341
9342 printf(" ");
9343 (void) printf_color(ANSI_BOLD, gettext("scan:"));
9344 printf(" ");
9345
9346 uint64_t bytes_scanned = vrs->vrs_bytes_scanned;
9347 uint64_t bytes_issued = vrs->vrs_bytes_issued;
9348 uint64_t bytes_rebuilt = vrs->vrs_bytes_rebuilt;
9349 uint64_t bytes_est_s = vrs->vrs_bytes_est;
9350 uint64_t bytes_est_i = vrs->vrs_bytes_est;
9351 if (c > offsetof(vdev_rebuild_stat_t, vrs_pass_bytes_skipped) / 8)
9352 bytes_est_i -= vrs->vrs_pass_bytes_skipped;
9353 uint64_t scan_rate = (vrs->vrs_pass_bytes_scanned /
9354 (vrs->vrs_pass_time_ms + 1)) * 1000;
9355 uint64_t issue_rate = (vrs->vrs_pass_bytes_issued /
9356 (vrs->vrs_pass_time_ms + 1)) * 1000;
9357 double scan_pct = MIN((double)bytes_scanned * 100 /
9358 (bytes_est_s + 1), 100);
9359
9360 /* Format all of the numbers we will be reporting */
9361 char bytes_scanned_buf[7], bytes_issued_buf[7];
9362 char bytes_rebuilt_buf[7], bytes_est_s_buf[7], bytes_est_i_buf[7];
9363 char scan_rate_buf[7], issue_rate_buf[7], time_buf[32];
9364 zfs_nicebytes(bytes_scanned, bytes_scanned_buf,
9365 sizeof (bytes_scanned_buf));
9366 zfs_nicebytes(bytes_issued, bytes_issued_buf,
9367 sizeof (bytes_issued_buf));
9368 zfs_nicebytes(bytes_rebuilt, bytes_rebuilt_buf,
9369 sizeof (bytes_rebuilt_buf));
9370 zfs_nicebytes(bytes_est_s, bytes_est_s_buf, sizeof (bytes_est_s_buf));
9371 zfs_nicebytes(bytes_est_i, bytes_est_i_buf, sizeof (bytes_est_i_buf));
9372
9373 time_t start = vrs->vrs_start_time;
9374 time_t end = vrs->vrs_end_time;
9375
9376 /* Rebuild is finished or canceled. */
9377 if (vrs->vrs_state == VDEV_REBUILD_COMPLETE) {
9378 secs_to_dhms(vrs->vrs_scan_time_ms / 1000, time_buf);
9379 (void) printf(gettext("resilvered (%s) %s in %s "
9380 "with %llu errors on %s"), vdev_name, bytes_rebuilt_buf,
9381 time_buf, (u_longlong_t)vrs->vrs_errors, ctime(&end));
9382 return;
9383 } else if (vrs->vrs_state == VDEV_REBUILD_CANCELED) {
9384 (void) printf(gettext("resilver (%s) canceled on %s"),
9385 vdev_name, ctime(&end));
9386 return;
9387 } else if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9388 (void) printf(gettext("resilver (%s) in progress since %s"),
9389 vdev_name, ctime(&start));
9390 }
9391
9392 assert(vrs->vrs_state == VDEV_REBUILD_ACTIVE);
9393
9394 (void) printf(gettext("\t%s / %s scanned"), bytes_scanned_buf,
9395 bytes_est_s_buf);
9396 if (scan_rate > 0) {
9397 zfs_nicebytes(scan_rate, scan_rate_buf, sizeof (scan_rate_buf));
9398 (void) printf(gettext(" at %s/s"), scan_rate_buf);
9399 }
9400 (void) printf(gettext(", %s / %s issued"), bytes_issued_buf,
9401 bytes_est_i_buf);
9402 if (issue_rate > 0) {
9403 zfs_nicebytes(issue_rate, issue_rate_buf,
9404 sizeof (issue_rate_buf));
9405 (void) printf(gettext(" at %s/s"), issue_rate_buf);
9406 }
9407 (void) printf(gettext("\n"));
9408
9409 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
9410 bytes_rebuilt_buf, scan_pct);
9411
9412 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9413 if (bytes_est_s >= bytes_scanned &&
9414 scan_rate >= 10 * 1024 * 1024) {
9415 secs_to_dhms((bytes_est_s - bytes_scanned) / scan_rate,
9416 time_buf);
9417 (void) printf(gettext(", %s to go\n"), time_buf);
9418 } else {
9419 (void) printf(gettext(", no estimated "
9420 "completion time\n"));
9421 }
9422 } else {
9423 (void) printf(gettext("\n"));
9424 }
9425 }
9426
9427 /*
9428 * Print rebuild status for top-level vdevs.
9429 */
9430 static void
print_rebuild_status(zpool_handle_t * zhp,nvlist_t * nvroot)9431 print_rebuild_status(zpool_handle_t *zhp, nvlist_t *nvroot)
9432 {
9433 nvlist_t **child;
9434 uint_t children;
9435
9436 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9437 &child, &children) != 0)
9438 children = 0;
9439
9440 for (uint_t c = 0; c < children; c++) {
9441 vdev_rebuild_stat_t *vrs;
9442 uint_t i;
9443
9444 if (nvlist_lookup_uint64_array(child[c],
9445 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9446 char *name = zpool_vdev_name(g_zfs, zhp,
9447 child[c], VDEV_NAME_TYPE_ID);
9448 print_rebuild_status_impl(vrs, i, name);
9449 free(name);
9450 }
9451 }
9452 }
9453
9454 /*
9455 * As we don't scrub checkpointed blocks, we want to warn the user that we
9456 * skipped scanning some blocks if a checkpoint exists or existed at any
9457 * time during the scan. If a sequential instead of healing reconstruction
9458 * was performed then the blocks were reconstructed. However, their checksums
9459 * have not been verified so we still print the warning.
9460 */
9461 static void
print_checkpoint_scan_warning(pool_scan_stat_t * ps,pool_checkpoint_stat_t * pcs)9462 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
9463 {
9464 if (ps == NULL || pcs == NULL)
9465 return;
9466
9467 if (pcs->pcs_state == CS_NONE ||
9468 pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
9469 return;
9470
9471 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
9472
9473 if (ps->pss_state == DSS_NONE)
9474 return;
9475
9476 if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
9477 ps->pss_end_time < pcs->pcs_start_time)
9478 return;
9479
9480 if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
9481 (void) printf(gettext(" scan warning: skipped blocks "
9482 "that are only referenced by the checkpoint.\n"));
9483 } else {
9484 assert(ps->pss_state == DSS_SCANNING);
9485 (void) printf(gettext(" scan warning: skipping blocks "
9486 "that are only referenced by the checkpoint.\n"));
9487 }
9488 }
9489
9490 /*
9491 * Returns B_TRUE if there is an active rebuild in progress. Otherwise,
9492 * B_FALSE is returned and 'rebuild_end_time' is set to the end time for
9493 * the last completed (or cancelled) rebuild.
9494 */
9495 static boolean_t
check_rebuilding(nvlist_t * nvroot,uint64_t * rebuild_end_time)9496 check_rebuilding(nvlist_t *nvroot, uint64_t *rebuild_end_time)
9497 {
9498 nvlist_t **child;
9499 uint_t children;
9500 boolean_t rebuilding = B_FALSE;
9501 uint64_t end_time = 0;
9502
9503 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9504 &child, &children) != 0)
9505 children = 0;
9506
9507 for (uint_t c = 0; c < children; c++) {
9508 vdev_rebuild_stat_t *vrs;
9509 uint_t i;
9510
9511 if (nvlist_lookup_uint64_array(child[c],
9512 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9513
9514 if (vrs->vrs_end_time > end_time)
9515 end_time = vrs->vrs_end_time;
9516
9517 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9518 rebuilding = B_TRUE;
9519 end_time = 0;
9520 break;
9521 }
9522 }
9523 }
9524
9525 if (rebuild_end_time != NULL)
9526 *rebuild_end_time = end_time;
9527
9528 return (rebuilding);
9529 }
9530
9531 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)9532 vdev_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9533 int depth, boolean_t isspare, char *parent, nvlist_t *item)
9534 {
9535 nvlist_t *vds, **child, *ch = NULL;
9536 uint_t vsc, children;
9537 vdev_stat_t *vs;
9538 char *vname;
9539 uint64_t notpresent;
9540 const char *type, *path;
9541
9542 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
9543 &child, &children) != 0)
9544 children = 0;
9545 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
9546 (uint64_t **)&vs, &vsc) == 0);
9547 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
9548 if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9549 return;
9550
9551 if (cb->cb_print_unhealthy && depth > 0 &&
9552 for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
9553 return;
9554 }
9555 vname = zpool_vdev_name(g_zfs, zhp, nv,
9556 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9557 vds = fnvlist_alloc();
9558 fill_vdev_info(vds, zhp, vname, B_FALSE, cb->cb_json_as_int);
9559 if (cb->cb_flat_vdevs && parent != NULL) {
9560 fnvlist_add_string(vds, "parent", parent);
9561 }
9562
9563 if (isspare) {
9564 if (vs->vs_aux == VDEV_AUX_SPARED) {
9565 fnvlist_add_string(vds, "state", "INUSE");
9566 used_by_other(zhp, nv, vds);
9567 } else if (vs->vs_state == VDEV_STATE_HEALTHY)
9568 fnvlist_add_string(vds, "state", "AVAIL");
9569 } else {
9570 if (vs->vs_alloc) {
9571 nice_num_str_nvlist(vds, "alloc_space", vs->vs_alloc,
9572 cb->cb_literal, cb->cb_json_as_int,
9573 ZFS_NICENUM_BYTES);
9574 }
9575 if (vs->vs_space) {
9576 nice_num_str_nvlist(vds, "total_space", vs->vs_space,
9577 cb->cb_literal, cb->cb_json_as_int,
9578 ZFS_NICENUM_BYTES);
9579 }
9580 if (vs->vs_dspace) {
9581 nice_num_str_nvlist(vds, "def_space", vs->vs_dspace,
9582 cb->cb_literal, cb->cb_json_as_int,
9583 ZFS_NICENUM_BYTES);
9584 }
9585 if (vs->vs_rsize) {
9586 nice_num_str_nvlist(vds, "rep_dev_size", vs->vs_rsize,
9587 cb->cb_literal, cb->cb_json_as_int,
9588 ZFS_NICENUM_BYTES);
9589 }
9590 if (vs->vs_esize) {
9591 nice_num_str_nvlist(vds, "ex_dev_size", vs->vs_esize,
9592 cb->cb_literal, cb->cb_json_as_int,
9593 ZFS_NICENUM_BYTES);
9594 }
9595 if (vs->vs_self_healed) {
9596 nice_num_str_nvlist(vds, "self_healed",
9597 vs->vs_self_healed, cb->cb_literal,
9598 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9599 }
9600 if (vs->vs_pspace) {
9601 nice_num_str_nvlist(vds, "phys_space", vs->vs_pspace,
9602 cb->cb_literal, cb->cb_json_as_int,
9603 ZFS_NICENUM_BYTES);
9604 }
9605 nice_num_str_nvlist(vds, "read_errors", vs->vs_read_errors,
9606 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9607 nice_num_str_nvlist(vds, "write_errors", vs->vs_write_errors,
9608 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9609 nice_num_str_nvlist(vds, "checksum_errors",
9610 vs->vs_checksum_errors, cb->cb_literal,
9611 cb->cb_json_as_int, ZFS_NICENUM_1024);
9612 if (vs->vs_scan_processed) {
9613 nice_num_str_nvlist(vds, "scan_processed",
9614 vs->vs_scan_processed, cb->cb_literal,
9615 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9616 }
9617 if (vs->vs_checkpoint_space) {
9618 nice_num_str_nvlist(vds, "checkpoint_space",
9619 vs->vs_checkpoint_space, cb->cb_literal,
9620 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9621 }
9622 if (vs->vs_resilver_deferred) {
9623 nice_num_str_nvlist(vds, "resilver_deferred",
9624 vs->vs_resilver_deferred, B_TRUE,
9625 cb->cb_json_as_int, ZFS_NICENUM_1024);
9626 }
9627 if (children == 0) {
9628 nice_num_str_nvlist(vds, "slow_ios", vs->vs_slow_ios,
9629 cb->cb_literal, cb->cb_json_as_int,
9630 ZFS_NICENUM_1024);
9631 }
9632 if (cb->cb_print_power) {
9633 if (children == 0) {
9634 /* Only leaf vdevs have physical slots */
9635 switch (zpool_power_current_state(zhp, (char *)
9636 fnvlist_lookup_string(nv,
9637 ZPOOL_CONFIG_PATH))) {
9638 case 0:
9639 fnvlist_add_string(vds, "power_state",
9640 "off");
9641 break;
9642 case 1:
9643 fnvlist_add_string(vds, "power_state",
9644 "on");
9645 break;
9646 default:
9647 fnvlist_add_string(vds, "power_state",
9648 "-");
9649 }
9650 } else {
9651 fnvlist_add_string(vds, "power_state", "-");
9652 }
9653 }
9654 }
9655
9656 if (cb->cb_print_dio_verify) {
9657 nice_num_str_nvlist(vds, "dio_verify_errors",
9658 vs->vs_dio_verify_errors, cb->cb_literal,
9659 cb->cb_json_as_int, ZFS_NICENUM_1024);
9660 }
9661
9662 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
9663 ¬present) == 0) {
9664 nice_num_str_nvlist(vds, ZPOOL_CONFIG_NOT_PRESENT,
9665 1, B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9666 fnvlist_add_string(vds, "was",
9667 fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH));
9668 } else if (vs->vs_aux != VDEV_AUX_NONE) {
9669 fnvlist_add_string(vds, "aux", vdev_aux_str[vs->vs_aux]);
9670 } else if (children == 0 && !isspare &&
9671 getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
9672 VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
9673 vs->vs_configured_ashift < vs->vs_physical_ashift) {
9674 nice_num_str_nvlist(vds, "configured_ashift",
9675 vs->vs_configured_ashift, B_TRUE, cb->cb_json_as_int,
9676 ZFS_NICENUM_1024);
9677 nice_num_str_nvlist(vds, "physical_ashift",
9678 vs->vs_physical_ashift, B_TRUE, cb->cb_json_as_int,
9679 ZFS_NICENUM_1024);
9680 }
9681 if (vs->vs_scan_removing != 0) {
9682 nice_num_str_nvlist(vds, "removing", vs->vs_scan_removing,
9683 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9684 } else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
9685 nice_num_str_nvlist(vds, "noalloc", vs->vs_noalloc,
9686 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9687 }
9688
9689 if (cb->vcdl != NULL) {
9690 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
9691 zpool_nvlist_cmd(cb->vcdl, zpool_get_name(zhp),
9692 path, vds);
9693 }
9694 }
9695
9696 if (children == 0) {
9697 if (cb->cb_print_vdev_init) {
9698 if (vs->vs_initialize_state != 0) {
9699 uint64_t st = vs->vs_initialize_state;
9700 fnvlist_add_string(vds, "init_state",
9701 vdev_init_state_str[st]);
9702 nice_num_str_nvlist(vds, "initialized",
9703 vs->vs_initialize_bytes_done,
9704 cb->cb_literal, cb->cb_json_as_int,
9705 ZFS_NICENUM_BYTES);
9706 nice_num_str_nvlist(vds, "to_initialize",
9707 vs->vs_initialize_bytes_est,
9708 cb->cb_literal, cb->cb_json_as_int,
9709 ZFS_NICENUM_BYTES);
9710 nice_num_str_nvlist(vds, "init_time",
9711 vs->vs_initialize_action_time,
9712 cb->cb_literal, cb->cb_json_as_int,
9713 ZFS_NICE_TIMESTAMP);
9714 nice_num_str_nvlist(vds, "init_errors",
9715 vs->vs_initialize_errors,
9716 cb->cb_literal, cb->cb_json_as_int,
9717 ZFS_NICENUM_1024);
9718 } else {
9719 fnvlist_add_string(vds, "init_state",
9720 "UNINITIALIZED");
9721 }
9722 }
9723 if (cb->cb_print_vdev_trim) {
9724 if (vs->vs_trim_notsup == 0) {
9725 if (vs->vs_trim_state != 0) {
9726 uint64_t st = vs->vs_trim_state;
9727 fnvlist_add_string(vds, "trim_state",
9728 vdev_trim_state_str[st]);
9729 nice_num_str_nvlist(vds, "trimmed",
9730 vs->vs_trim_bytes_done,
9731 cb->cb_literal, cb->cb_json_as_int,
9732 ZFS_NICENUM_BYTES);
9733 nice_num_str_nvlist(vds, "to_trim",
9734 vs->vs_trim_bytes_est,
9735 cb->cb_literal, cb->cb_json_as_int,
9736 ZFS_NICENUM_BYTES);
9737 nice_num_str_nvlist(vds, "trim_time",
9738 vs->vs_trim_action_time,
9739 cb->cb_literal, cb->cb_json_as_int,
9740 ZFS_NICE_TIMESTAMP);
9741 nice_num_str_nvlist(vds, "trim_errors",
9742 vs->vs_trim_errors,
9743 cb->cb_literal, cb->cb_json_as_int,
9744 ZFS_NICENUM_1024);
9745 } else
9746 fnvlist_add_string(vds, "trim_state",
9747 "UNTRIMMED");
9748 }
9749 nice_num_str_nvlist(vds, "trim_notsup",
9750 vs->vs_trim_notsup, B_TRUE,
9751 cb->cb_json_as_int, ZFS_NICENUM_1024);
9752 }
9753 } else {
9754 ch = fnvlist_alloc();
9755 }
9756
9757 if (cb->cb_flat_vdevs && children == 0) {
9758 fnvlist_add_nvlist(item, vname, vds);
9759 }
9760
9761 for (int c = 0; c < children; c++) {
9762 uint64_t islog = B_FALSE, ishole = B_FALSE;
9763 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9764 &islog);
9765 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
9766 &ishole);
9767 if (islog || ishole)
9768 continue;
9769 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
9770 continue;
9771 if (cb->cb_flat_vdevs) {
9772 vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9773 vname, item);
9774 }
9775 vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9776 vname, ch);
9777 }
9778
9779 if (ch != NULL) {
9780 if (!nvlist_empty(ch))
9781 fnvlist_add_nvlist(vds, "vdevs", ch);
9782 fnvlist_free(ch);
9783 }
9784 fnvlist_add_nvlist(item, vname, vds);
9785 fnvlist_free(vds);
9786 free(vname);
9787 }
9788
9789 static void
class_vdevs_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,const char * class,nvlist_t * item)9790 class_vdevs_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9791 const char *class, nvlist_t *item)
9792 {
9793 uint_t c, children;
9794 nvlist_t **child;
9795 nvlist_t *class_obj = NULL;
9796
9797 if (!cb->cb_flat_vdevs)
9798 class_obj = fnvlist_alloc();
9799
9800 assert(zhp != NULL || cb->cb_verbosity == 0);
9801
9802 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
9803 &children) != 0)
9804 return;
9805
9806 for (c = 0; c < children; c++) {
9807 uint64_t is_log = B_FALSE;
9808 const char *bias = NULL;
9809 const char *type = NULL;
9810 char *name = zpool_vdev_name(g_zfs, zhp, child[c],
9811 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9812
9813 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9814 &is_log);
9815
9816 if (is_log) {
9817 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
9818 } else {
9819 (void) nvlist_lookup_string(child[c],
9820 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
9821 (void) nvlist_lookup_string(child[c],
9822 ZPOOL_CONFIG_TYPE, &type);
9823 }
9824
9825 if (bias == NULL || strcmp(bias, class) != 0)
9826 continue;
9827 if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9828 continue;
9829
9830 if (cb->cb_flat_vdevs) {
9831 vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9832 NULL, item);
9833 } else {
9834 vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9835 NULL, class_obj);
9836 }
9837 free(name);
9838 }
9839 if (!cb->cb_flat_vdevs) {
9840 if (!nvlist_empty(class_obj))
9841 fnvlist_add_nvlist(item, class, class_obj);
9842 fnvlist_free(class_obj);
9843 }
9844 }
9845
9846 static void
l2cache_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,nvlist_t * item)9847 l2cache_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9848 nvlist_t *item)
9849 {
9850 nvlist_t *l2c = NULL, **l2cache;
9851 uint_t nl2cache;
9852 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
9853 &l2cache, &nl2cache) == 0) {
9854 if (nl2cache == 0)
9855 return;
9856 if (!cb->cb_flat_vdevs)
9857 l2c = fnvlist_alloc();
9858 for (int i = 0; i < nl2cache; i++) {
9859 if (cb->cb_flat_vdevs) {
9860 vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9861 B_FALSE, NULL, item);
9862 } else {
9863 vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9864 B_FALSE, NULL, l2c);
9865 }
9866 }
9867 }
9868 if (!cb->cb_flat_vdevs) {
9869 if (!nvlist_empty(l2c))
9870 fnvlist_add_nvlist(item, "l2cache", l2c);
9871 fnvlist_free(l2c);
9872 }
9873 }
9874
9875 static void
spares_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,nvlist_t * item)9876 spares_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9877 nvlist_t *item)
9878 {
9879 nvlist_t *sp = NULL, **spares;
9880 uint_t nspares;
9881 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
9882 &spares, &nspares) == 0) {
9883 if (nspares == 0)
9884 return;
9885 if (!cb->cb_flat_vdevs)
9886 sp = fnvlist_alloc();
9887 for (int i = 0; i < nspares; i++) {
9888 if (cb->cb_flat_vdevs) {
9889 vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9890 NULL, item);
9891 } else {
9892 vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9893 NULL, sp);
9894 }
9895 }
9896 }
9897 if (!cb->cb_flat_vdevs) {
9898 if (!nvlist_empty(sp))
9899 fnvlist_add_nvlist(item, "spares", sp);
9900 fnvlist_free(sp);
9901 }
9902 }
9903
9904 /*
9905 * Take a uint64 nvpair named 'name' from nverrlist, nicenum-ify it, and
9906 * put it back in 'nverrlist', possibly as a string, with the same 'name'.
9907 */
9908 static void
convert_nvlist_uint64_to_nicenum(status_cbdata_t * cb,nvlist_t * parent,const char * name,enum zfs_nicenum_format format)9909 convert_nvlist_uint64_to_nicenum(status_cbdata_t *cb, nvlist_t *parent,
9910 const char *name, enum zfs_nicenum_format format)
9911 {
9912 uint64_t val;
9913 nvpair_t *nvp;
9914
9915 if (nvlist_lookup_nvpair(parent, name, &nvp) != 0)
9916 return; /* nothing by that name, ignore */
9917
9918 val = fnvpair_value_uint64(nvp);
9919 nvlist_remove_nvpair(parent, nvp);
9920 nice_num_str_nvlist(parent, name, val,
9921 cb->cb_literal, cb->cb_json_as_int, format);
9922 }
9923
9924 static void
errors_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * item)9925 errors_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9926 {
9927 int verbosity = cb->cb_verbosity;
9928 nvlist_t *nverrlist = NULL;
9929 nvpair_t *elem;
9930 char *pathname;
9931 size_t len = MAXPATHLEN * 2;
9932 nvlist_t **ranges;
9933 uint_t count;
9934 uint_t objs = 0, i;
9935 nvlist_t **nv_arr = NULL;
9936 char **str_arr = NULL;
9937 uint64_t nerr;
9938
9939 if (zpool_get_errlog(zhp, &nverrlist) != 0) {
9940 /* We're expected to always return an error count */
9941 nice_num_str_nvlist(item, ZPOOL_CONFIG_ERRCOUNT, 0,
9942 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9943 return;
9944 }
9945
9946 /*
9947 * This 'error_count' entry is just the full error log block count.
9948 * This includes duplicate and overlapping entries so it can be
9949 * inaccurate. It's only included for historical reasons.
9950 */
9951 nvlist_t *config = zpool_get_config(zhp, NULL);
9952 nerr = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT);
9953 nice_num_str_nvlist(item, ZPOOL_CONFIG_ERRCOUNT, nerr,
9954 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9955
9956 pathname = safe_malloc(len);
9957
9958 /* Get an initial count of all the objects (files) with errors */
9959 elem = NULL;
9960 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL)
9961 objs++;
9962
9963 if (verbosity <= 1)
9964 str_arr = safe_malloc(objs * sizeof (*str_arr));
9965 else
9966 nv_arr = safe_malloc(objs * sizeof (*nv_arr));
9967
9968 elem = NULL;
9969 for (i = 0; i < objs; i++) {
9970 nvlist_t *nv;
9971 uint64_t dsobj, obj;
9972 elem = nvlist_next_nvpair(nverrlist, elem);
9973
9974 nv = fnvpair_value_nvlist(elem);
9975
9976 dsobj = fnvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET);
9977 obj = fnvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT);
9978
9979 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
9980
9981 /*
9982 * Each JSON entry is a different file/zvol. If user has
9983 * verbosity = 1, then just we're just constructing an array
9984 * of strings.
9985 */
9986 if (str_arr != NULL) {
9987 str_arr[i] = strdup(pathname);
9988 continue;
9989 }
9990
9991 fnvlist_add_string(nv, ZPOOL_ERR_NAME, pathname);
9992
9993 /* nicenum-ify our nvlist */
9994 convert_nvlist_uint64_to_nicenum(cb, nv, ZPOOL_ERR_OBJECT,
9995 ZFS_NICENUM_RAW);
9996 convert_nvlist_uint64_to_nicenum(cb, nv, ZPOOL_ERR_DATASET,
9997 ZFS_NICENUM_RAW);
9998 convert_nvlist_uint64_to_nicenum(cb, nv, ZPOOL_ERR_BLOCK_SIZE,
9999 ZFS_NICENUM_1024);
10000
10001 if (nvlist_lookup_nvlist_array(nv, ZPOOL_ERR_RANGES, &ranges,
10002 &count) == 0) {
10003 for (uint_t i = 0; i < count; i++) {
10004 convert_nvlist_uint64_to_nicenum(cb, ranges[i],
10005 ZPOOL_ERR_START_BYTE, ZFS_NICENUM_1024);
10006 convert_nvlist_uint64_to_nicenum(cb, ranges[i],
10007 ZPOOL_ERR_END_BYTE, ZFS_NICENUM_1024);
10008 }
10009 }
10010 nv_arr[i] = fnvlist_alloc();
10011 fnvlist_add_nvlist(nv_arr[i], pathname, nv);
10012 }
10013
10014 /* Place our error list in a top level "errlist" JSON array object. */
10015 if (str_arr != NULL) {
10016 fnvlist_add_string_array(item, ZPOOL_ERR_JSON,
10017 (const char **) str_arr, objs);
10018 for (i = 0; i < objs; i++)
10019 free(str_arr[i]);
10020 free(str_arr);
10021 } else {
10022 fnvlist_add_nvlist_array(item, ZPOOL_ERR_JSON,
10023 (const nvlist_t **) nv_arr, objs);
10024 for (i = 0; i < objs; i++)
10025 nvlist_free(nv_arr[i]);
10026 free(nv_arr);
10027 }
10028
10029 free(pathname);
10030 nvlist_free(nverrlist);
10031 }
10032
10033 static void
ddt_stats_nvlist(ddt_stat_t * dds,status_cbdata_t * cb,nvlist_t * item)10034 ddt_stats_nvlist(ddt_stat_t *dds, status_cbdata_t *cb, nvlist_t *item)
10035 {
10036 nice_num_str_nvlist(item, "blocks", dds->dds_blocks,
10037 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10038 nice_num_str_nvlist(item, "logical_size", dds->dds_lsize,
10039 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10040 nice_num_str_nvlist(item, "physical_size", dds->dds_psize,
10041 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10042 nice_num_str_nvlist(item, "deflated_size", dds->dds_dsize,
10043 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10044 nice_num_str_nvlist(item, "ref_blocks", dds->dds_ref_blocks,
10045 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10046 nice_num_str_nvlist(item, "ref_lsize", dds->dds_ref_lsize,
10047 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10048 nice_num_str_nvlist(item, "ref_psize", dds->dds_ref_psize,
10049 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10050 nice_num_str_nvlist(item, "ref_dsize", dds->dds_ref_dsize,
10051 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10052 }
10053
10054 static void
dedup_stats_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * item)10055 dedup_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
10056 {
10057 nvlist_t *config;
10058 if (cb->cb_dedup_stats) {
10059 ddt_histogram_t *ddh;
10060 ddt_stat_t *dds;
10061 ddt_object_t *ddo;
10062 nvlist_t *ddt_stat, *ddt_obj, *dedup;
10063 uint_t c;
10064 uint64_t cspace_prop;
10065
10066 config = zpool_get_config(zhp, NULL);
10067 if (nvlist_lookup_uint64_array(config,
10068 ZPOOL_CONFIG_DDT_OBJ_STATS, (uint64_t **)&ddo, &c) != 0)
10069 return;
10070
10071 dedup = fnvlist_alloc();
10072 ddt_obj = fnvlist_alloc();
10073 nice_num_str_nvlist(dedup, "obj_count", ddo->ddo_count,
10074 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10075 if (ddo->ddo_count == 0) {
10076 fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
10077 ddt_obj);
10078 fnvlist_add_nvlist(item, "dedup_stats", dedup);
10079 fnvlist_free(ddt_obj);
10080 fnvlist_free(dedup);
10081 return;
10082 } else {
10083 nice_num_str_nvlist(dedup, "dspace", ddo->ddo_dspace,
10084 cb->cb_literal, cb->cb_json_as_int,
10085 ZFS_NICENUM_1024);
10086 nice_num_str_nvlist(dedup, "mspace", ddo->ddo_mspace,
10087 cb->cb_literal, cb->cb_json_as_int,
10088 ZFS_NICENUM_1024);
10089 /*
10090 * Squash cached size into in-core size to handle race.
10091 * Only include cached size if it is available.
10092 */
10093 cspace_prop = zpool_get_prop_int(zhp,
10094 ZPOOL_PROP_DEDUPCACHED, NULL);
10095 cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
10096 nice_num_str_nvlist(dedup, "cspace", cspace_prop,
10097 cb->cb_literal, cb->cb_json_as_int,
10098 ZFS_NICENUM_1024);
10099 }
10100
10101 ddt_stat = fnvlist_alloc();
10102 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
10103 (uint64_t **)&dds, &c) == 0) {
10104 nvlist_t *total = fnvlist_alloc();
10105 if (dds->dds_blocks == 0)
10106 fnvlist_add_string(total, "blocks", "0");
10107 else
10108 ddt_stats_nvlist(dds, cb, total);
10109 fnvlist_add_nvlist(ddt_stat, "total", total);
10110 fnvlist_free(total);
10111 }
10112 if (nvlist_lookup_uint64_array(config,
10113 ZPOOL_CONFIG_DDT_HISTOGRAM, (uint64_t **)&ddh, &c) == 0) {
10114 nvlist_t *hist = fnvlist_alloc();
10115 nvlist_t *entry = NULL;
10116 char buf[16];
10117 for (int h = 0; h < 64; h++) {
10118 if (ddh->ddh_stat[h].dds_blocks != 0) {
10119 entry = fnvlist_alloc();
10120 ddt_stats_nvlist(&ddh->ddh_stat[h], cb,
10121 entry);
10122 (void) snprintf(buf, 16, "%d", h);
10123 fnvlist_add_nvlist(hist, buf, entry);
10124 fnvlist_free(entry);
10125 }
10126 }
10127 if (!nvlist_empty(hist))
10128 fnvlist_add_nvlist(ddt_stat, "histogram", hist);
10129 fnvlist_free(hist);
10130 }
10131
10132 if (!nvlist_empty(ddt_obj)) {
10133 fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
10134 ddt_obj);
10135 }
10136 fnvlist_free(ddt_obj);
10137 if (!nvlist_empty(ddt_stat)) {
10138 fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_STATS,
10139 ddt_stat);
10140 }
10141 fnvlist_free(ddt_stat);
10142 if (!nvlist_empty(dedup))
10143 fnvlist_add_nvlist(item, "dedup_stats", dedup);
10144 fnvlist_free(dedup);
10145 }
10146 }
10147
10148 static void
raidz_expand_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)10149 raidz_expand_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
10150 nvlist_t *nvroot, nvlist_t *item)
10151 {
10152 uint_t c;
10153 pool_raidz_expand_stat_t *pres = NULL;
10154 if (nvlist_lookup_uint64_array(nvroot,
10155 ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c) == 0) {
10156 nvlist_t **child;
10157 uint_t children;
10158 nvlist_t *nv = fnvlist_alloc();
10159 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10160 &child, &children) == 0);
10161 assert(pres->pres_expanding_vdev < children);
10162 char *name =
10163 zpool_vdev_name(g_zfs, zhp,
10164 child[pres->pres_expanding_vdev], 0);
10165 fill_vdev_info(nv, zhp, name, B_FALSE, cb->cb_json_as_int);
10166 fnvlist_add_string(nv, "state",
10167 pool_scan_state_str[pres->pres_state]);
10168 nice_num_str_nvlist(nv, "expanding_vdev",
10169 pres->pres_expanding_vdev, B_TRUE, cb->cb_json_as_int,
10170 ZFS_NICENUM_1024);
10171 nice_num_str_nvlist(nv, "start_time", pres->pres_start_time,
10172 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10173 nice_num_str_nvlist(nv, "end_time", pres->pres_end_time,
10174 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10175 nice_num_str_nvlist(nv, "to_reflow", pres->pres_to_reflow,
10176 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10177 nice_num_str_nvlist(nv, "reflowed", pres->pres_reflowed,
10178 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10179 nice_num_str_nvlist(nv, "waiting_for_resilver",
10180 pres->pres_waiting_for_resilver, B_TRUE,
10181 cb->cb_json_as_int, ZFS_NICENUM_1024);
10182 fnvlist_add_nvlist(item, ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, nv);
10183 fnvlist_free(nv);
10184 free(name);
10185 }
10186 }
10187
10188 static void
checkpoint_status_nvlist(nvlist_t * nvroot,status_cbdata_t * cb,nvlist_t * item)10189 checkpoint_status_nvlist(nvlist_t *nvroot, status_cbdata_t *cb,
10190 nvlist_t *item)
10191 {
10192 uint_t c;
10193 pool_checkpoint_stat_t *pcs = NULL;
10194 if (nvlist_lookup_uint64_array(nvroot,
10195 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c) == 0) {
10196 nvlist_t *nv = fnvlist_alloc();
10197 fnvlist_add_string(nv, "state",
10198 checkpoint_state_str[pcs->pcs_state]);
10199 nice_num_str_nvlist(nv, "start_time",
10200 pcs->pcs_start_time, cb->cb_literal, cb->cb_json_as_int,
10201 ZFS_NICE_TIMESTAMP);
10202 nice_num_str_nvlist(nv, "space",
10203 pcs->pcs_space, cb->cb_literal, cb->cb_json_as_int,
10204 ZFS_NICENUM_BYTES);
10205 fnvlist_add_nvlist(item, ZPOOL_CONFIG_CHECKPOINT_STATS, nv);
10206 fnvlist_free(nv);
10207 }
10208 }
10209
10210 static void
removal_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)10211 removal_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
10212 nvlist_t *nvroot, nvlist_t *item)
10213 {
10214 uint_t c;
10215 pool_removal_stat_t *prs = NULL;
10216 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_REMOVAL_STATS,
10217 (uint64_t **)&prs, &c) == 0) {
10218 if (prs->prs_state != DSS_NONE) {
10219 nvlist_t **child;
10220 uint_t children;
10221 verify(nvlist_lookup_nvlist_array(nvroot,
10222 ZPOOL_CONFIG_CHILDREN, &child, &children) == 0);
10223 assert(prs->prs_removing_vdev < children);
10224 char *vdev_name = zpool_vdev_name(g_zfs, zhp,
10225 child[prs->prs_removing_vdev], B_TRUE);
10226 nvlist_t *nv = fnvlist_alloc();
10227 fill_vdev_info(nv, zhp, vdev_name, B_FALSE,
10228 cb->cb_json_as_int);
10229 fnvlist_add_string(nv, "state",
10230 pool_scan_state_str[prs->prs_state]);
10231 nice_num_str_nvlist(nv, "removing_vdev",
10232 prs->prs_removing_vdev, B_TRUE, cb->cb_json_as_int,
10233 ZFS_NICENUM_1024);
10234 nice_num_str_nvlist(nv, "start_time",
10235 prs->prs_start_time, cb->cb_literal,
10236 cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10237 nice_num_str_nvlist(nv, "end_time", prs->prs_end_time,
10238 cb->cb_literal, cb->cb_json_as_int,
10239 ZFS_NICE_TIMESTAMP);
10240 nice_num_str_nvlist(nv, "to_copy", prs->prs_to_copy,
10241 cb->cb_literal, cb->cb_json_as_int,
10242 ZFS_NICENUM_BYTES);
10243 nice_num_str_nvlist(nv, "copied", prs->prs_copied,
10244 cb->cb_literal, cb->cb_json_as_int,
10245 ZFS_NICENUM_BYTES);
10246 nice_num_str_nvlist(nv, "mapping_memory",
10247 prs->prs_mapping_memory, cb->cb_literal,
10248 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10249 fnvlist_add_nvlist(item,
10250 ZPOOL_CONFIG_REMOVAL_STATS, nv);
10251 fnvlist_free(nv);
10252 free(vdev_name);
10253 }
10254 }
10255 }
10256
10257 static void
condense_status_nvlist(nvlist_t * nvroot,status_cbdata_t * cb,nvlist_t * item)10258 condense_status_nvlist(nvlist_t *nvroot, status_cbdata_t *cb, nvlist_t *item)
10259 {
10260 nvlist_t *cnv = NULL;
10261 nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_CONDENSE_STATS, &cnv);
10262 if (cnv == NULL)
10263 return;
10264
10265 nvlist_t *onv = fnvlist_alloc();
10266 for (nvpair_t *nvp = nvlist_next_nvpair(cnv, NULL);
10267 nvp != NULL; nvp = nvlist_next_nvpair(cnv, nvp)) {
10268 const char *type = nvpair_name(nvp);
10269 nvlist_t *tnv = fnvpair_value_nvlist(nvp);
10270
10271 uint64_t start_time = fnvlist_lookup_uint64(tnv, "start_time");
10272 if (start_time == 0)
10273 continue;
10274
10275 uint64_t end_time = fnvlist_lookup_uint64(tnv, "end_time");
10276 uint64_t processed = fnvlist_lookup_uint64(tnv, "processed");
10277 uint64_t total = fnvlist_lookup_uint64(tnv, "total");
10278
10279 nvlist_t *nv = fnvlist_alloc();
10280 nice_num_str_nvlist(nv, "start_time", start_time,
10281 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10282 if (end_time > 0)
10283 nice_num_str_nvlist(nv, "end_time", end_time,
10284 cb->cb_literal, cb->cb_json_as_int,
10285 ZFS_NICE_TIMESTAMP);
10286 nice_num_str_nvlist(nv, "processed", processed,
10287 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10288 nice_num_str_nvlist(nv, "total", total,
10289 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10290
10291 fnvlist_add_string(nv, "unit", condense_unit(type));
10292
10293 fnvlist_add_nvlist(onv, type, nv);
10294 fnvlist_free(nv);
10295 }
10296
10297 if (fnvlist_num_pairs(onv))
10298 fnvlist_add_nvlist(item, "condense", onv);
10299
10300 fnvlist_free(onv);
10301 }
10302
10303
10304 static void
scan_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)10305 scan_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
10306 nvlist_t *nvroot, nvlist_t *item)
10307 {
10308 pool_scan_stat_t *ps = NULL;
10309 uint_t c;
10310 nvlist_t *scan = fnvlist_alloc();
10311 nvlist_t **child;
10312 uint_t children;
10313
10314 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
10315 (uint64_t **)&ps, &c) == 0) {
10316 fnvlist_add_string(scan, "function",
10317 pool_scan_func_str[ps->pss_func]);
10318 fnvlist_add_string(scan, "state",
10319 pool_scan_state_str[ps->pss_state]);
10320 nice_num_str_nvlist(scan, "start_time", ps->pss_start_time,
10321 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10322 nice_num_str_nvlist(scan, "end_time", ps->pss_end_time,
10323 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10324 nice_num_str_nvlist(scan, "to_examine", ps->pss_to_examine,
10325 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10326 nice_num_str_nvlist(scan, "examined", ps->pss_examined,
10327 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10328 nice_num_str_nvlist(scan, "skipped", ps->pss_skipped,
10329 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10330 nice_num_str_nvlist(scan, "processed", ps->pss_processed,
10331 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10332 nice_num_str_nvlist(scan, "errors", ps->pss_errors,
10333 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
10334 nice_num_str_nvlist(scan, "bytes_per_scan", ps->pss_pass_exam,
10335 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10336 nice_num_str_nvlist(scan, "pass_start", ps->pss_pass_start,
10337 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
10338 nice_num_str_nvlist(scan, "scrub_pause",
10339 ps->pss_pass_scrub_pause, cb->cb_literal,
10340 cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
10341 nice_num_str_nvlist(scan, "scrub_spent_paused",
10342 ps->pss_pass_scrub_spent_paused,
10343 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
10344 nice_num_str_nvlist(scan, "issued_bytes_per_scan",
10345 ps->pss_pass_issued, cb->cb_literal,
10346 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10347 nice_num_str_nvlist(scan, "issued", ps->pss_issued,
10348 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
10349 if (ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB &&
10350 ps->pss_error_scrub_start > ps->pss_start_time) {
10351 fnvlist_add_string(scan, "err_scrub_func",
10352 pool_scan_func_str[ps->pss_error_scrub_func]);
10353 fnvlist_add_string(scan, "err_scrub_state",
10354 pool_scan_state_str[ps->pss_error_scrub_state]);
10355 nice_num_str_nvlist(scan, "err_scrub_start_time",
10356 ps->pss_error_scrub_start,
10357 cb->cb_literal, cb->cb_json_as_int,
10358 ZFS_NICE_TIMESTAMP);
10359 nice_num_str_nvlist(scan, "err_scrub_end_time",
10360 ps->pss_error_scrub_end,
10361 cb->cb_literal, cb->cb_json_as_int,
10362 ZFS_NICE_TIMESTAMP);
10363 nice_num_str_nvlist(scan, "err_scrub_examined",
10364 ps->pss_error_scrub_examined,
10365 cb->cb_literal, cb->cb_json_as_int,
10366 ZFS_NICENUM_1024);
10367 nice_num_str_nvlist(scan, "err_scrub_to_examine",
10368 ps->pss_error_scrub_to_be_examined,
10369 cb->cb_literal, cb->cb_json_as_int,
10370 ZFS_NICENUM_1024);
10371 nice_num_str_nvlist(scan, "err_scrub_pause",
10372 ps->pss_pass_error_scrub_pause,
10373 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
10374 }
10375 }
10376
10377 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10378 &child, &children) == 0) {
10379 vdev_rebuild_stat_t *vrs;
10380 uint_t i;
10381 char *name;
10382 nvlist_t *nv;
10383 nvlist_t *rebuild = fnvlist_alloc();
10384 uint64_t st;
10385 for (uint_t c = 0; c < children; c++) {
10386 if (nvlist_lookup_uint64_array(child[c],
10387 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs,
10388 &i) == 0) {
10389 if (vrs->vrs_state != VDEV_REBUILD_NONE) {
10390 nv = fnvlist_alloc();
10391 name = zpool_vdev_name(g_zfs, zhp,
10392 child[c], VDEV_NAME_TYPE_ID);
10393 fill_vdev_info(nv, zhp, name, B_FALSE,
10394 cb->cb_json_as_int);
10395 st = vrs->vrs_state;
10396 fnvlist_add_string(nv, "state",
10397 vdev_rebuild_state_str[st]);
10398 nice_num_str_nvlist(nv, "start_time",
10399 vrs->vrs_start_time, cb->cb_literal,
10400 cb->cb_json_as_int,
10401 ZFS_NICE_TIMESTAMP);
10402 nice_num_str_nvlist(nv, "end_time",
10403 vrs->vrs_end_time, cb->cb_literal,
10404 cb->cb_json_as_int,
10405 ZFS_NICE_TIMESTAMP);
10406 nice_num_str_nvlist(nv, "scan_time",
10407 vrs->vrs_scan_time_ms * 1000000,
10408 cb->cb_literal, cb->cb_json_as_int,
10409 ZFS_NICENUM_TIME);
10410 nice_num_str_nvlist(nv, "scanned",
10411 vrs->vrs_bytes_scanned,
10412 cb->cb_literal, cb->cb_json_as_int,
10413 ZFS_NICENUM_BYTES);
10414 nice_num_str_nvlist(nv, "issued",
10415 vrs->vrs_bytes_issued,
10416 cb->cb_literal, cb->cb_json_as_int,
10417 ZFS_NICENUM_BYTES);
10418 nice_num_str_nvlist(nv, "rebuilt",
10419 vrs->vrs_bytes_rebuilt,
10420 cb->cb_literal, cb->cb_json_as_int,
10421 ZFS_NICENUM_BYTES);
10422 nice_num_str_nvlist(nv, "to_scan",
10423 vrs->vrs_bytes_est, cb->cb_literal,
10424 cb->cb_json_as_int,
10425 ZFS_NICENUM_BYTES);
10426 nice_num_str_nvlist(nv, "errors",
10427 vrs->vrs_errors, cb->cb_literal,
10428 cb->cb_json_as_int,
10429 ZFS_NICENUM_1024);
10430 nice_num_str_nvlist(nv, "pass_time",
10431 vrs->vrs_pass_time_ms * 1000000,
10432 cb->cb_literal, cb->cb_json_as_int,
10433 ZFS_NICENUM_TIME);
10434 nice_num_str_nvlist(nv, "pass_scanned",
10435 vrs->vrs_pass_bytes_scanned,
10436 cb->cb_literal, cb->cb_json_as_int,
10437 ZFS_NICENUM_BYTES);
10438 nice_num_str_nvlist(nv, "pass_issued",
10439 vrs->vrs_pass_bytes_issued,
10440 cb->cb_literal, cb->cb_json_as_int,
10441 ZFS_NICENUM_BYTES);
10442 nice_num_str_nvlist(nv, "pass_skipped",
10443 vrs->vrs_pass_bytes_skipped,
10444 cb->cb_literal, cb->cb_json_as_int,
10445 ZFS_NICENUM_BYTES);
10446 fnvlist_add_nvlist(rebuild, name, nv);
10447 free(name);
10448 }
10449 }
10450 }
10451 if (!nvlist_empty(rebuild))
10452 fnvlist_add_nvlist(scan, "rebuild_stats", rebuild);
10453 fnvlist_free(rebuild);
10454 }
10455
10456 if (!nvlist_empty(scan))
10457 fnvlist_add_nvlist(item, ZPOOL_CONFIG_SCAN_STATS, scan);
10458 fnvlist_free(scan);
10459 }
10460
10461 /*
10462 * Print the scan status.
10463 */
10464 static void
print_scan_status(zpool_handle_t * zhp,nvlist_t * nvroot)10465 print_scan_status(zpool_handle_t *zhp, nvlist_t *nvroot)
10466 {
10467 uint64_t rebuild_end_time = 0, resilver_end_time = 0;
10468 boolean_t have_resilver = B_FALSE, have_scrub = B_FALSE;
10469 boolean_t have_errorscrub = B_FALSE;
10470 boolean_t active_resilver = B_FALSE;
10471 pool_checkpoint_stat_t *pcs = NULL;
10472 pool_scan_stat_t *ps = NULL;
10473 uint_t c;
10474 boolean_t is_thorough = B_FALSE;
10475 time_t scrub_start = 0, errorscrub_start = 0;
10476
10477 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
10478 (uint64_t **)&ps, &c) == 0) {
10479 if (ps->pss_func == POOL_SCAN_RESILVER) {
10480 resilver_end_time = ps->pss_end_time;
10481 active_resilver = (ps->pss_state == DSS_SCANNING);
10482 }
10483
10484 have_resilver = (ps->pss_func == POOL_SCAN_RESILVER);
10485 have_scrub = (ps->pss_func == POOL_SCAN_SCRUB);
10486 scrub_start = ps->pss_start_time;
10487 if (POOL_SCAN_STAT_VALID(pss_pass_scrub_flags, c) &&
10488 (ps->pss_pass_scrub_flags & POOL_SCRUB_THOROUGH) != 0)
10489 is_thorough = B_TRUE;
10490 if (POOL_SCAN_STAT_VALID(pss_pass_error_scrub_pause, c)) {
10491 have_errorscrub = (ps->pss_error_scrub_func ==
10492 POOL_SCAN_ERRORSCRUB);
10493 errorscrub_start = ps->pss_error_scrub_start;
10494 }
10495 }
10496
10497 boolean_t active_rebuild = check_rebuilding(nvroot, &rebuild_end_time);
10498 boolean_t have_rebuild = (active_rebuild || (rebuild_end_time > 0));
10499
10500 /* Always print the scrub status when available. */
10501 if (have_scrub && scrub_start > errorscrub_start)
10502 print_scan_scrub_resilver_status(ps, is_thorough);
10503 else if (have_errorscrub && errorscrub_start >= scrub_start)
10504 print_err_scrub_status(ps);
10505
10506 /*
10507 * When there is an active resilver or rebuild print its status.
10508 * Otherwise print the status of the last resilver or rebuild.
10509 */
10510 if (active_resilver || (!active_rebuild && have_resilver &&
10511 resilver_end_time && resilver_end_time > rebuild_end_time)) {
10512 print_scan_scrub_resilver_status(ps, is_thorough);
10513 } else if (active_rebuild || (!active_resilver && have_rebuild &&
10514 rebuild_end_time && rebuild_end_time > resilver_end_time)) {
10515 print_rebuild_status(zhp, nvroot);
10516 }
10517
10518 (void) nvlist_lookup_uint64_array(nvroot,
10519 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
10520 print_checkpoint_scan_warning(ps, pcs);
10521 }
10522
10523 /*
10524 * Print out detailed removal status.
10525 */
10526 static void
print_removal_status(zpool_handle_t * zhp,pool_removal_stat_t * prs)10527 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
10528 {
10529 char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
10530 time_t start, end;
10531 nvlist_t *config, *nvroot;
10532 nvlist_t **child;
10533 uint_t children;
10534 char *vdev_name;
10535
10536 if (prs == NULL || prs->prs_state == DSS_NONE)
10537 return;
10538
10539 /*
10540 * Determine name of vdev.
10541 */
10542 config = zpool_get_config(zhp, NULL);
10543 nvroot = fnvlist_lookup_nvlist(config,
10544 ZPOOL_CONFIG_VDEV_TREE);
10545 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10546 &child, &children) == 0);
10547 assert(prs->prs_removing_vdev < children);
10548 vdev_name = zpool_vdev_name(g_zfs, zhp,
10549 child[prs->prs_removing_vdev], B_TRUE);
10550
10551 (void) printf_color(ANSI_BOLD, gettext("remove: "));
10552
10553 start = prs->prs_start_time;
10554 end = prs->prs_end_time;
10555 zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
10556
10557 /*
10558 * Removal is finished or canceled.
10559 */
10560 if (prs->prs_state == DSS_FINISHED) {
10561 uint64_t minutes_taken = (end - start) / 60;
10562
10563 (void) printf(gettext("Removal of vdev %llu copied %s "
10564 "in %lluh%um, completed on %s"),
10565 (longlong_t)prs->prs_removing_vdev,
10566 copied_buf,
10567 (u_longlong_t)(minutes_taken / 60),
10568 (uint_t)(minutes_taken % 60),
10569 ctime((time_t *)&end));
10570 } else if (prs->prs_state == DSS_CANCELED) {
10571 (void) printf(gettext("Removal of %s canceled on %s"),
10572 vdev_name, ctime(&end));
10573 } else {
10574 uint64_t copied, total, elapsed, rate, mins_left, hours_left;
10575 double fraction_done;
10576
10577 assert(prs->prs_state == DSS_SCANNING);
10578
10579 /*
10580 * Removal is in progress.
10581 */
10582 (void) printf(gettext(
10583 "Evacuation of %s in progress since %s"),
10584 vdev_name, ctime(&start));
10585
10586 copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
10587 total = prs->prs_to_copy;
10588 fraction_done = (double)copied / total;
10589
10590 /* elapsed time for this pass */
10591 elapsed = time(NULL) - prs->prs_start_time;
10592 elapsed = elapsed > 0 ? elapsed : 1;
10593 rate = copied / elapsed;
10594 rate = rate > 0 ? rate : 1;
10595 mins_left = ((total - copied) / rate) / 60;
10596 hours_left = mins_left / 60;
10597
10598 zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10599 zfs_nicenum(total, total_buf, sizeof (total_buf));
10600 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10601
10602 /*
10603 * do not print estimated time if hours_left is more than
10604 * 30 days
10605 */
10606 (void) printf(gettext(
10607 "\t%s copied out of %s at %s/s, %.2f%% done"),
10608 examined_buf, total_buf, rate_buf, 100 * fraction_done);
10609 if (hours_left < (30 * 24)) {
10610 (void) printf(gettext(", %lluh%um to go\n"),
10611 (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
10612 } else {
10613 (void) printf(gettext(
10614 ", (copy is slow, no estimated time)\n"));
10615 }
10616 }
10617 free(vdev_name);
10618
10619 if (prs->prs_mapping_memory > 0) {
10620 char mem_buf[7];
10621 zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
10622 (void) printf(gettext(
10623 "\t%s memory used for removed device mappings\n"),
10624 mem_buf);
10625 }
10626 }
10627
10628 /*
10629 * Print out detailed raidz expansion status.
10630 */
10631 static void
print_raidz_expand_status(zpool_handle_t * zhp,pool_raidz_expand_stat_t * pres)10632 print_raidz_expand_status(zpool_handle_t *zhp, pool_raidz_expand_stat_t *pres)
10633 {
10634 char copied_buf[7];
10635
10636 if (pres == NULL || pres->pres_state == DSS_NONE)
10637 return;
10638
10639 /*
10640 * Determine name of vdev.
10641 */
10642 nvlist_t *config = zpool_get_config(zhp, NULL);
10643 nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
10644 ZPOOL_CONFIG_VDEV_TREE);
10645 nvlist_t **child;
10646 uint_t children;
10647 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10648 &child, &children) == 0);
10649 assert(pres->pres_expanding_vdev < children);
10650
10651 (void) printf_color(ANSI_BOLD, gettext("expand: "));
10652
10653 time_t start = pres->pres_start_time;
10654 time_t end = pres->pres_end_time;
10655 char *vname =
10656 zpool_vdev_name(g_zfs, zhp, child[pres->pres_expanding_vdev], 0);
10657 zfs_nicenum(pres->pres_reflowed, copied_buf, sizeof (copied_buf));
10658
10659 /*
10660 * Expansion is finished or canceled.
10661 */
10662 if (pres->pres_state == DSS_FINISHED) {
10663 char time_buf[32];
10664 secs_to_dhms(end - start, time_buf);
10665
10666 (void) printf(gettext("expanded %s-%u copied %s in %s, "
10667 "on %s"), vname, (int)pres->pres_expanding_vdev,
10668 copied_buf, time_buf, ctime((time_t *)&end));
10669 } else {
10670 char examined_buf[7], total_buf[7], rate_buf[7];
10671 uint64_t copied, total, elapsed, rate, secs_left;
10672 double fraction_done;
10673
10674 assert(pres->pres_state == DSS_SCANNING);
10675
10676 /*
10677 * Expansion is in progress.
10678 */
10679 (void) printf(gettext(
10680 "expansion of %s-%u in progress since %s"),
10681 vname, (int)pres->pres_expanding_vdev, ctime(&start));
10682
10683 copied = pres->pres_reflowed > 0 ? pres->pres_reflowed : 1;
10684 total = pres->pres_to_reflow;
10685 fraction_done = (double)copied / total;
10686
10687 /* elapsed time for this pass */
10688 elapsed = time(NULL) - pres->pres_start_time;
10689 elapsed = elapsed > 0 ? elapsed : 1;
10690 rate = copied / elapsed;
10691 rate = rate > 0 ? rate : 1;
10692 secs_left = (total - copied) / rate;
10693
10694 zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10695 zfs_nicenum(total, total_buf, sizeof (total_buf));
10696 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10697
10698 /*
10699 * do not print estimated time if hours_left is more than
10700 * 30 days
10701 */
10702 (void) printf(gettext("\t%s / %s copied at %s/s, %.2f%% done"),
10703 examined_buf, total_buf, rate_buf, 100 * fraction_done);
10704 if (pres->pres_waiting_for_resilver) {
10705 (void) printf(gettext(", paused for resilver or "
10706 "clear\n"));
10707 } else if (secs_left < (30 * 24 * 3600)) {
10708 char time_buf[32];
10709 secs_to_dhms(secs_left, time_buf);
10710 (void) printf(gettext(", %s to go\n"), time_buf);
10711 } else {
10712 (void) printf(gettext(
10713 ", (copy is slow, no estimated time)\n"));
10714 }
10715 }
10716 free(vname);
10717 }
10718 static void
print_checkpoint_status(pool_checkpoint_stat_t * pcs)10719 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
10720 {
10721 time_t start;
10722 char space_buf[7];
10723
10724 if (pcs == NULL || pcs->pcs_state == CS_NONE)
10725 return;
10726
10727 (void) printf(gettext("checkpoint: "));
10728
10729 start = pcs->pcs_start_time;
10730 zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
10731
10732 if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
10733 char *date = ctime(&start);
10734
10735 /*
10736 * ctime() adds a newline at the end of the generated
10737 * string, thus the weird format specifier and the
10738 * strlen() call used to chop it off from the output.
10739 */
10740 (void) printf(gettext("created %.*s, consumes %s\n"),
10741 (int)(strlen(date) - 1), date, space_buf);
10742 return;
10743 }
10744
10745 assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
10746
10747 (void) printf(gettext("discarding, %s remaining.\n"),
10748 space_buf);
10749 }
10750
10751 static void
print_condense_status(nvlist_t * nv)10752 print_condense_status(nvlist_t *nv)
10753 {
10754 if (nv == NULL)
10755 return;
10756
10757 for (nvpair_t *nvp = nvlist_next_nvpair(nv, NULL);
10758 nvp != NULL; nvp = nvlist_next_nvpair(nv, nvp)) {
10759 const char *type = nvpair_name(nvp);
10760 nvlist_t *tnv = fnvpair_value_nvlist(nvp);
10761
10762 uint64_t start_time = fnvlist_lookup_uint64(tnv, "start_time");
10763 if (start_time == 0)
10764 continue;
10765
10766 uint64_t end_time = fnvlist_lookup_uint64(tnv, "end_time");
10767 uint64_t processed = fnvlist_lookup_uint64(tnv, "processed");
10768 uint64_t total = fnvlist_lookup_uint64(tnv, "total");
10769
10770 const char *units = condense_unit(type);
10771
10772 char cur[32], tot[32], elapsed[32];
10773 zfs_nicenum(processed, cur, sizeof (cur));
10774 zfs_nicenum(total, tot, sizeof (tot));
10775
10776 if (end_time == 0) {
10777 secs_to_dhms(time(NULL) - start_time, elapsed);
10778 (void) printf(gettext(
10779 "condense: %s: condensing, %s/%s %s done in %s\n"),
10780 type, cur, tot, units, elapsed);
10781 } else if (processed < total) {
10782 secs_to_dhms(end_time - start_time, elapsed);
10783 (void) printf(gettext(
10784 "condense: %s: cancelled, %s/%s %s done in %s\n"),
10785 type, cur, tot, units, elapsed);
10786 } else {
10787 secs_to_dhms(end_time - start_time, elapsed);
10788 (void) printf(gettext(
10789 "condense: %s: done, %s %s done in %s\n"),
10790 type, cur, units, elapsed);
10791 }
10792 }
10793 }
10794
10795 static void
print_error_log(zpool_handle_t * zhp,int verbosity,boolean_t literal)10796 print_error_log(zpool_handle_t *zhp, int verbosity, boolean_t literal)
10797 {
10798 nvlist_t *nverrlist = NULL;
10799 nvpair_t *elem;
10800 char *pathname;
10801 size_t len = MAXPATHLEN * 2;
10802 boolean_t started = B_FALSE;
10803 char last_pathname[MAXPATHLEN] = "";
10804
10805 if (zpool_get_errlog(zhp, &nverrlist) != 0)
10806 return;
10807
10808 if (nvlist_empty(nverrlist)) {
10809 (void) printf(gettext("errors: Permanent errors have been "
10810 "detected, but none of the affected\n\tblocks could be "
10811 "resolved to a file.\n"));
10812 nvlist_free(nverrlist);
10813 return;
10814 }
10815
10816 (void) printf("errors: Permanent errors have been "
10817 "detected in the following files:\n\n");
10818
10819 pathname = safe_malloc(len);
10820 elem = NULL;
10821 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
10822 nvlist_t *nv;
10823 uint64_t dsobj, obj;
10824
10825 verify(nvpair_value_nvlist(elem, &nv) == 0);
10826 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
10827 &dsobj) == 0);
10828 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
10829 &obj) == 0);
10830 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
10831 if (last_pathname[0] == '\0' ||
10832 strncmp(pathname, last_pathname, sizeof (last_pathname))
10833 != 0) {
10834 strlcpy(last_pathname, pathname,
10835 sizeof (last_pathname));
10836 if (started)
10837 (void) printf("\n");
10838 else
10839 started = B_TRUE;
10840 (void) printf("%7s %s ", "", pathname);
10841 } else if (verbosity > 1) {
10842 (void) printf(",");
10843 }
10844 if (verbosity > 1) {
10845 nvlist_t **arr;
10846 uint_t count;
10847 if (nvlist_lookup_nvlist_array(nv, ZPOOL_ERR_RANGES,
10848 &arr, &count) != 0) {
10849 (void) printf("(no ranges)");
10850 continue;
10851 }
10852
10853 for (uint_t i = 0; i < count; i++) {
10854 uint64_t start;
10855 uint64_t end;
10856 start = fnvlist_lookup_uint64(arr[i],
10857 ZPOOL_ERR_START_BYTE);
10858 end = fnvlist_lookup_uint64(arr[i],
10859 ZPOOL_ERR_END_BYTE);
10860 if (literal) {
10861 (void) printf("%llu-%llu",
10862 (u_longlong_t)start,
10863 (u_longlong_t)end);
10864 } else {
10865 char s1[32], s2[32];
10866 zfs_nicenum(start, s1, sizeof (s1));
10867 zfs_nicenum(end, s2, sizeof (s2));
10868 (void) printf("%s-%s", s1, s2);
10869 }
10870 if (i != count - 1)
10871 (void) printf(",");
10872 }
10873 }
10874 }
10875 (void) printf("\n");
10876 free(pathname);
10877 nvlist_free(nverrlist);
10878 }
10879
10880 static void
print_spares(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t ** spares,uint_t nspares)10881 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
10882 uint_t nspares)
10883 {
10884 uint_t i;
10885 char *name;
10886
10887 if (nspares == 0)
10888 return;
10889
10890 (void) printf(gettext("\tspares\n"));
10891
10892 for (i = 0; i < nspares; i++) {
10893 name = zpool_vdev_name(g_zfs, zhp, spares[i],
10894 cb->cb_name_flags);
10895 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE, NULL);
10896 free(name);
10897 }
10898 }
10899
10900 static void
print_l2cache(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t ** l2cache,uint_t nl2cache)10901 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
10902 uint_t nl2cache)
10903 {
10904 uint_t i;
10905 char *name;
10906
10907 if (nl2cache == 0)
10908 return;
10909
10910 (void) printf(gettext("\tcache\n"));
10911
10912 for (i = 0; i < nl2cache; i++) {
10913 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
10914 cb->cb_name_flags);
10915 print_status_config(zhp, cb, name, l2cache[i], 2,
10916 B_FALSE, NULL);
10917 free(name);
10918 }
10919 }
10920
10921 static void
print_dedup_stats(zpool_handle_t * zhp,nvlist_t * config,boolean_t literal)10922 print_dedup_stats(zpool_handle_t *zhp, nvlist_t *config, boolean_t literal)
10923 {
10924 ddt_histogram_t *ddh;
10925 ddt_stat_t *dds;
10926 ddt_object_t *ddo;
10927 uint_t c;
10928 /* Extra space provided for literal display */
10929 char dspace[32], mspace[32], cspace[32];
10930 uint64_t cspace_prop;
10931 enum zfs_nicenum_format format;
10932 zprop_source_t src;
10933
10934 /*
10935 * If the pool was faulted then we may not have been able to
10936 * obtain the config. Otherwise, if we have anything in the dedup
10937 * table continue processing the stats.
10938 */
10939 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
10940 (uint64_t **)&ddo, &c) != 0)
10941 return;
10942
10943 (void) printf("\n");
10944 (void) printf(gettext(" dedup: "));
10945 if (ddo->ddo_count == 0) {
10946 (void) printf(gettext("no DDT entries\n"));
10947 return;
10948 }
10949
10950 /*
10951 * Squash cached size into in-core size to handle race.
10952 * Only include cached size if it is available.
10953 */
10954 cspace_prop = zpool_get_prop_int(zhp, ZPOOL_PROP_DEDUPCACHED, &src);
10955 cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
10956 format = literal ? ZFS_NICENUM_RAW : ZFS_NICENUM_1024;
10957 zfs_nicenum_format(cspace_prop, cspace, sizeof (cspace), format);
10958 zfs_nicenum_format(ddo->ddo_dspace, dspace, sizeof (dspace), format);
10959 zfs_nicenum_format(ddo->ddo_mspace, mspace, sizeof (mspace), format);
10960 (void) printf("DDT entries %llu, size %s on disk, %s in core",
10961 (u_longlong_t)ddo->ddo_count,
10962 dspace,
10963 mspace);
10964 if (src != ZPROP_SRC_DEFAULT) {
10965 (void) printf(", %s cached (%.02f%%)",
10966 cspace,
10967 (double)cspace_prop / (double)ddo->ddo_mspace * 100.0);
10968 }
10969 (void) printf("\n");
10970
10971 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
10972 (uint64_t **)&dds, &c) == 0);
10973 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
10974 (uint64_t **)&ddh, &c) == 0);
10975 zpool_dump_ddt(dds, ddh, literal);
10976 }
10977
10978 #define ST_SIZE 4096
10979 #define AC_SIZE 2048
10980
10981 static void
print_status_reason(zpool_handle_t * zhp,status_cbdata_t * cbp,zpool_status_t reason,zpool_errata_t errata,nvlist_t * item)10982 print_status_reason(zpool_handle_t *zhp, status_cbdata_t *cbp,
10983 zpool_status_t reason, zpool_errata_t errata, nvlist_t *item)
10984 {
10985 char status[ST_SIZE];
10986 char action[AC_SIZE];
10987 memset(status, 0, ST_SIZE);
10988 memset(action, 0, AC_SIZE);
10989
10990 switch (reason) {
10991 case ZPOOL_STATUS_MISSING_DEV_R:
10992 (void) snprintf(status, ST_SIZE,
10993 gettext("One or more devices could "
10994 "not be opened. Sufficient replicas exist for\n\tthe pool "
10995 "to continue functioning in a degraded state.\n"));
10996 (void) snprintf(action, AC_SIZE,
10997 gettext("Attach the missing device "
10998 "and online it using 'zpool online'.\n"));
10999 break;
11000
11001 case ZPOOL_STATUS_MISSING_DEV_NR:
11002 (void) snprintf(status, ST_SIZE,
11003 gettext("One or more devices could "
11004 "not be opened. There are insufficient\n\treplicas for the"
11005 " pool to continue functioning.\n"));
11006 (void) snprintf(action, AC_SIZE,
11007 gettext("Attach the missing device "
11008 "and online it using 'zpool online'.\n"));
11009 break;
11010
11011 case ZPOOL_STATUS_CORRUPT_LABEL_R:
11012 (void) snprintf(status, ST_SIZE,
11013 gettext("One or more devices could "
11014 "not be used because the label is missing or\n\tinvalid. "
11015 "Sufficient replicas exist for the pool to continue\n\t"
11016 "functioning in a degraded state.\n"));
11017 (void) snprintf(action, AC_SIZE,
11018 gettext("Replace the device using 'zpool replace'.\n"));
11019 break;
11020
11021 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
11022 (void) snprintf(status, ST_SIZE,
11023 gettext("One or more devices could "
11024 "not be used because the label is missing \n\tor invalid. "
11025 "There are insufficient replicas for the pool to "
11026 "continue\n\tfunctioning.\n"));
11027 zpool_explain_recover(zpool_get_handle(zhp),
11028 zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
11029 action, AC_SIZE);
11030 break;
11031
11032 case ZPOOL_STATUS_FAILING_DEV:
11033 (void) snprintf(status, ST_SIZE,
11034 gettext("One or more devices has "
11035 "experienced an unrecoverable error. An\n\tattempt was "
11036 "made to correct the error. Applications are "
11037 "unaffected.\n"));
11038 (void) snprintf(action, AC_SIZE, gettext("Determine if the "
11039 "device needs to be replaced, and clear the errors\n\tusing"
11040 " 'zpool clear' or replace the device with 'zpool "
11041 "replace'.\n"));
11042 break;
11043
11044 case ZPOOL_STATUS_OFFLINE_DEV:
11045 (void) snprintf(status, ST_SIZE,
11046 gettext("One or more devices has "
11047 "been taken offline by the administrator.\n\tSufficient "
11048 "replicas exist for the pool to continue functioning in "
11049 "a\n\tdegraded state.\n"));
11050 (void) snprintf(action, AC_SIZE, gettext("Online the device "
11051 "using 'zpool online' or replace the device with\n\t'zpool "
11052 "replace'.\n"));
11053 break;
11054
11055 case ZPOOL_STATUS_REMOVED_DEV:
11056 (void) snprintf(status, ST_SIZE,
11057 gettext("One or more devices have "
11058 "been removed.\n\tSufficient replicas exist for the pool "
11059 "to continue functioning in a\n\tdegraded state.\n"));
11060 (void) snprintf(action, AC_SIZE, gettext("Online the device "
11061 "using zpool online' or replace the device with\n\t'zpool "
11062 "replace'.\n"));
11063 break;
11064
11065 case ZPOOL_STATUS_RESILVERING:
11066 case ZPOOL_STATUS_REBUILDING:
11067 (void) snprintf(status, ST_SIZE,
11068 gettext("One or more devices is "
11069 "currently being resilvered. The pool will\n\tcontinue "
11070 "to function, possibly in a degraded state.\n"));
11071 (void) snprintf(action, AC_SIZE,
11072 gettext("Wait for the resilver to complete.\n"));
11073 break;
11074
11075 case ZPOOL_STATUS_REBUILD_SCRUB:
11076 (void) snprintf(status, ST_SIZE,
11077 gettext("One or more devices have "
11078 "been sequentially resilvered, scrubbing\n\tthe pool "
11079 "is recommended.\n"));
11080 (void) snprintf(action, AC_SIZE, gettext("Use 'zpool scrub' to "
11081 "verify all data checksums.\n"));
11082 break;
11083
11084 case ZPOOL_STATUS_CORRUPT_DATA:
11085 (void) snprintf(status, ST_SIZE,
11086 gettext("One or more devices has "
11087 "experienced an error resulting in data\n\tcorruption. "
11088 "Applications may be affected.\n"));
11089 (void) snprintf(action, AC_SIZE,
11090 gettext("Restore the file in question"
11091 " if possible. Otherwise restore the\n\tentire pool from "
11092 "backup.\n"));
11093 break;
11094
11095 case ZPOOL_STATUS_CORRUPT_POOL:
11096 (void) snprintf(status, ST_SIZE, gettext("The pool metadata is "
11097 "incomplete or corrupted and the pool cannot be "
11098 "opened.\n"));
11099 zpool_explain_recover(zpool_get_handle(zhp),
11100 zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
11101 action, AC_SIZE);
11102 break;
11103
11104 case ZPOOL_STATUS_VERSION_OLDER:
11105 (void) snprintf(status, ST_SIZE,
11106 gettext("The pool is formatted using "
11107 "a legacy on-disk format. The pool can\n\tstill be used, "
11108 "but some features are unavailable.\n"));
11109 (void) snprintf(action, AC_SIZE,
11110 gettext("Upgrade the pool using "
11111 "'zpool upgrade'. Once this is done, the\n\tpool will no "
11112 "longer be accessible on software that does not support\n\t"
11113 "feature flags.\n"));
11114 break;
11115
11116 case ZPOOL_STATUS_VERSION_NEWER:
11117 (void) snprintf(status, ST_SIZE,
11118 gettext("The pool has been upgraded "
11119 "to a newer, incompatible on-disk version.\n\tThe pool "
11120 "cannot be accessed on this system.\n"));
11121 (void) snprintf(action, AC_SIZE,
11122 gettext("Access the pool from a "
11123 "system running more recent software, or\n\trestore the "
11124 "pool from backup.\n"));
11125 break;
11126
11127 case ZPOOL_STATUS_FEAT_DISABLED:
11128 (void) snprintf(status, ST_SIZE, gettext("Some supported and "
11129 "requested features are not enabled on the pool.\n\t"
11130 "The pool can still be used, but some features are "
11131 "unavailable.\n"));
11132 (void) snprintf(action, AC_SIZE,
11133 gettext("Enable all features using "
11134 "'zpool upgrade'. Once this is done,\n\tthe pool may no "
11135 "longer be accessible by software that does not support\n\t"
11136 "the features. See zpool-features(7) for details.\n"));
11137 break;
11138
11139 case ZPOOL_STATUS_COMPATIBILITY_ERR:
11140 (void) snprintf(status, ST_SIZE, gettext("This pool has a "
11141 "compatibility list specified, but it could not be\n\t"
11142 "read/parsed at this time. The pool can still be used, "
11143 "but this\n\tshould be investigated.\n"));
11144 (void) snprintf(action, AC_SIZE,
11145 gettext("Check the value of the "
11146 "'compatibility' property against the\n\t"
11147 "appropriate file in %s or %s.\n"),
11148 ZPOOL_SYSCONF_COMPAT_D, ZPOOL_DATA_COMPAT_D);
11149 break;
11150
11151 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
11152 (void) snprintf(status, ST_SIZE, gettext("One or more features "
11153 "are enabled on the pool despite not being\n\t"
11154 "requested by the 'compatibility' property.\n"));
11155 (void) snprintf(action, AC_SIZE, gettext("Consider setting "
11156 "'compatibility' to an appropriate value, or\n\t"
11157 "adding needed features to the relevant file in\n\t"
11158 "%s or %s.\n"),
11159 ZPOOL_SYSCONF_COMPAT_D, ZPOOL_DATA_COMPAT_D);
11160 break;
11161
11162 case ZPOOL_STATUS_UNSUP_FEAT_READ:
11163 (void) snprintf(status, ST_SIZE,
11164 gettext("The pool cannot be accessed "
11165 "on this system because it uses the\n\tfollowing feature(s)"
11166 " not supported on this system:\n"));
11167 zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
11168 1024);
11169 (void) snprintf(action, AC_SIZE,
11170 gettext("Access the pool from a "
11171 "system that supports the required feature(s),\n\tor "
11172 "restore the pool from backup.\n"));
11173 break;
11174
11175 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
11176 (void) snprintf(status, ST_SIZE, gettext("The pool can only be "
11177 "accessed in read-only mode on this system. It\n\tcannot be"
11178 " accessed in read-write mode because it uses the "
11179 "following\n\tfeature(s) not supported on this system:\n"));
11180 zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
11181 1024);
11182 (void) snprintf(action, AC_SIZE,
11183 gettext("The pool cannot be accessed "
11184 "in read-write mode. Import the pool with\n"
11185 "\t\"-o readonly=on\", access the pool from a system that "
11186 "supports the\n\trequired feature(s), or restore the "
11187 "pool from backup.\n"));
11188 break;
11189
11190 case ZPOOL_STATUS_FAULTED_DEV_R:
11191 (void) snprintf(status, ST_SIZE,
11192 gettext("One or more devices are "
11193 "faulted in response to persistent errors.\n\tSufficient "
11194 "replicas exist for the pool to continue functioning "
11195 "in a\n\tdegraded state.\n"));
11196 (void) snprintf(action, AC_SIZE,
11197 gettext("Replace the faulted device, "
11198 "or use 'zpool clear' to mark the device\n\trepaired.\n"));
11199 break;
11200
11201 case ZPOOL_STATUS_FAULTED_FDOM_R:
11202 (void) snprintf(status, ST_SIZE,
11203 gettext("One or more failure domains are faulted. "
11204 "The storage devices may be\n\tintact. Sufficient "
11205 "replicas exist for the pool to continue functioning\n\t"
11206 "in a degraded state.\n"));
11207 (void) snprintf(action, AC_SIZE,
11208 gettext("Replace the faulted domain device, "
11209 "or use 'zpool clear' to mark domain\n\tstorage devices "
11210 "repaired.\n"));
11211 break;
11212
11213 case ZPOOL_STATUS_FAULTED_DEV_NR:
11214 (void) snprintf(status, ST_SIZE,
11215 gettext("One or more devices are "
11216 "faulted in response to persistent errors. There are "
11217 "insufficient replicas for the pool to\n\tcontinue "
11218 "functioning.\n"));
11219 (void) snprintf(action, AC_SIZE,
11220 gettext("Destroy and re-create the "
11221 "pool from a backup source. Manually marking the device\n"
11222 "\trepaired using 'zpool clear' may allow some data "
11223 "to be recovered.\n"));
11224 break;
11225
11226 case ZPOOL_STATUS_IO_FAILURE_MMP:
11227 (void) snprintf(status, ST_SIZE,
11228 gettext("The pool is suspended "
11229 "because multihost writes failed or were delayed;\n\t"
11230 "another system could import the pool undetected.\n"));
11231 (void) snprintf(action, AC_SIZE,
11232 gettext("Make sure the pool's devices"
11233 " are connected, then reboot your system and\n\timport the "
11234 "pool or run 'zpool clear' to resume the pool.\n"));
11235 break;
11236
11237 case ZPOOL_STATUS_IO_FAILURE_WAIT:
11238 case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
11239 (void) snprintf(status, ST_SIZE,
11240 gettext("One or more devices are "
11241 "faulted in response to IO failures.\n"));
11242 (void) snprintf(action, AC_SIZE,
11243 gettext("Make sure the affected "
11244 "devices are connected, then run 'zpool clear'.\n"));
11245 break;
11246
11247 case ZPOOL_STATUS_BAD_LOG:
11248 (void) snprintf(status, ST_SIZE, gettext("An intent log record "
11249 "could not be read.\n"
11250 "\tWaiting for administrator intervention to fix the "
11251 "faulted pool.\n"));
11252 (void) snprintf(action, AC_SIZE,
11253 gettext("Either restore the affected "
11254 "device(s) and run 'zpool online',\n"
11255 "\tor ignore the intent log records by running "
11256 "'zpool clear'.\n"));
11257 break;
11258
11259 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
11260 (void) snprintf(status, ST_SIZE,
11261 gettext("One or more devices are "
11262 "configured to use a non-native block size.\n"
11263 "\tExpect reduced performance.\n"));
11264 (void) snprintf(action, AC_SIZE,
11265 gettext("Replace affected devices "
11266 "with devices that support the\n\tconfigured block size, "
11267 "or migrate data to a properly configured\n\tpool.\n"));
11268 break;
11269
11270 case ZPOOL_STATUS_HOSTID_MISMATCH:
11271 (void) snprintf(status, ST_SIZE,
11272 gettext("Mismatch between pool hostid"
11273 " and system hostid on imported pool.\n\tThis pool was "
11274 "previously imported into a system with a different "
11275 "hostid,\n\tand then was verbatim imported into this "
11276 "system.\n"));
11277 (void) snprintf(action, AC_SIZE,
11278 gettext("Export this pool on all "
11279 "systems on which it is imported.\n"
11280 "\tThen import it to correct the mismatch.\n"));
11281 break;
11282
11283 case ZPOOL_STATUS_ERRATA:
11284 (void) snprintf(status, ST_SIZE,
11285 gettext("Errata #%d detected.\n"), errata);
11286 switch (errata) {
11287 case ZPOOL_ERRATA_NONE:
11288 break;
11289
11290 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
11291 (void) snprintf(action, AC_SIZE,
11292 gettext("To correct the issue run "
11293 "'zpool scrub'.\n"));
11294 break;
11295
11296 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
11297 (void) strlcat(status, gettext("\tExisting encrypted "
11298 "datasets contain an on-disk incompatibility\n\t "
11299 "which needs to be corrected.\n"), ST_SIZE);
11300 (void) snprintf(action, AC_SIZE,
11301 gettext("To correct the issue"
11302 " backup existing encrypted datasets to new\n\t"
11303 "encrypted datasets and destroy the old ones. "
11304 "'zfs mount -o ro' can\n\tbe used to temporarily "
11305 "mount existing encrypted datasets readonly.\n"));
11306 break;
11307
11308 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
11309 (void) strlcat(status, gettext("\tExisting encrypted "
11310 "snapshots and bookmarks contain an on-disk\n\t"
11311 "incompatibility. This may cause on-disk "
11312 "corruption if they are used\n\twith "
11313 "'zfs recv'.\n"), ST_SIZE);
11314 (void) snprintf(action, AC_SIZE,
11315 gettext("To correct the"
11316 "issue, enable the bookmark_v2 feature. No "
11317 "additional\n\taction is needed if there are no "
11318 "encrypted snapshots or bookmarks.\n\tIf preserving"
11319 "the encrypted snapshots and bookmarks is required,"
11320 " use\n\ta non-raw send to backup and restore them."
11321 " Alternately, they may be\n\tremoved to resolve "
11322 "the incompatibility.\n"));
11323 break;
11324
11325 default:
11326 /*
11327 * All errata which allow the pool to be imported
11328 * must contain an action message.
11329 */
11330 assert(0);
11331 }
11332 break;
11333
11334 default:
11335 /*
11336 * The remaining errors can't actually be generated, yet.
11337 */
11338 assert(reason == ZPOOL_STATUS_OK);
11339 }
11340
11341 if (status[0] != 0) {
11342 if (cbp->cb_json)
11343 fnvlist_add_string(item, "status", status);
11344 else {
11345 (void) printf_color(ANSI_BOLD, gettext("status: "));
11346 (void) printf_color(ANSI_YELLOW, status);
11347 }
11348 }
11349
11350 if (action[0] != 0) {
11351 if (cbp->cb_json)
11352 fnvlist_add_string(item, "action", action);
11353 else {
11354 (void) printf_color(ANSI_BOLD, gettext("action: "));
11355 (void) printf_color(ANSI_YELLOW, action);
11356 }
11357 }
11358 }
11359
11360 static int
status_callback_json(zpool_handle_t * zhp,void * data)11361 status_callback_json(zpool_handle_t *zhp, void *data)
11362 {
11363 status_cbdata_t *cbp = data;
11364 nvlist_t *config, *nvroot;
11365 const char *msgid;
11366 char pool_guid[256];
11367 char msgbuf[256];
11368 uint64_t guid;
11369 zpool_status_t reason;
11370 zpool_errata_t errata;
11371 uint_t c;
11372 vdev_stat_t *vs;
11373 nvlist_t *item, *d, *load_info, *vds;
11374
11375 /* If dedup stats were requested, also fetch dedupcached. */
11376 if (cbp->cb_dedup_stats > 1)
11377 zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
11378 reason = zpool_get_status(zhp, &msgid, &errata);
11379 /*
11380 * If we were given 'zpool status -x', only report those pools with
11381 * problems.
11382 */
11383 if (cbp->cb_explain &&
11384 (reason == ZPOOL_STATUS_OK ||
11385 reason == ZPOOL_STATUS_VERSION_OLDER ||
11386 reason == ZPOOL_STATUS_FEAT_DISABLED ||
11387 reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
11388 reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
11389 return (0);
11390 }
11391
11392 d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
11393 item = fnvlist_alloc();
11394 vds = fnvlist_alloc();
11395 fill_pool_info(item, zhp, B_FALSE, cbp->cb_json_as_int);
11396 config = zpool_get_config(zhp, NULL);
11397
11398 if (config != NULL) {
11399 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
11400 verify(nvlist_lookup_uint64_array(nvroot,
11401 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &c) == 0);
11402 if (cbp->cb_json_pool_key_guid) {
11403 guid = fnvlist_lookup_uint64(config,
11404 ZPOOL_CONFIG_POOL_GUID);
11405 (void) snprintf(pool_guid, 256, "%llu",
11406 (u_longlong_t)guid);
11407 }
11408 cbp->cb_count++;
11409
11410 print_status_reason(zhp, cbp, reason, errata, item);
11411 if (msgid != NULL) {
11412 (void) snprintf(msgbuf, 256,
11413 "https://openzfs.github.io/openzfs-docs/msg/%s",
11414 msgid);
11415 fnvlist_add_string(item, "msgid", msgid);
11416 fnvlist_add_string(item, "moreinfo", msgbuf);
11417 }
11418
11419 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
11420 &load_info) == 0) {
11421 fnvlist_add_nvlist(item, ZPOOL_CONFIG_LOAD_INFO,
11422 load_info);
11423 }
11424
11425 scan_status_nvlist(zhp, cbp, nvroot, item);
11426 removal_status_nvlist(zhp, cbp, nvroot, item);
11427 checkpoint_status_nvlist(nvroot, cbp, item);
11428 condense_status_nvlist(nvroot, cbp, item);
11429 raidz_expand_status_nvlist(zhp, cbp, nvroot, item);
11430 vdev_stats_nvlist(zhp, cbp, nvroot, 0, B_FALSE, NULL, vds);
11431 if (cbp->cb_flat_vdevs) {
11432 class_vdevs_nvlist(zhp, cbp, nvroot,
11433 VDEV_ALLOC_BIAS_DEDUP, vds);
11434 class_vdevs_nvlist(zhp, cbp, nvroot,
11435 VDEV_ALLOC_BIAS_SPECIAL, vds);
11436 class_vdevs_nvlist(zhp, cbp, nvroot,
11437 VDEV_ALLOC_CLASS_LOGS, vds);
11438 l2cache_nvlist(zhp, cbp, nvroot, vds);
11439 spares_nvlist(zhp, cbp, nvroot, vds);
11440
11441 fnvlist_add_nvlist(item, "vdevs", vds);
11442 fnvlist_free(vds);
11443 } else {
11444 fnvlist_add_nvlist(item, "vdevs", vds);
11445 fnvlist_free(vds);
11446
11447 class_vdevs_nvlist(zhp, cbp, nvroot,
11448 VDEV_ALLOC_BIAS_DEDUP, item);
11449 class_vdevs_nvlist(zhp, cbp, nvroot,
11450 VDEV_ALLOC_BIAS_SPECIAL, item);
11451 class_vdevs_nvlist(zhp, cbp, nvroot,
11452 VDEV_ALLOC_CLASS_LOGS, item);
11453 l2cache_nvlist(zhp, cbp, nvroot, item);
11454 spares_nvlist(zhp, cbp, nvroot, item);
11455 }
11456 dedup_stats_nvlist(zhp, cbp, item);
11457
11458 /*
11459 * Historically, -j would always print the number of errors
11460 * so check for that in addition to verbosity.
11461 */
11462 if (cbp->cb_verbosity > 0 || cbp->cb_json)
11463 errors_nvlist(zhp, cbp, item);
11464 }
11465 if (cbp->cb_json_pool_key_guid) {
11466 fnvlist_add_nvlist(d, pool_guid, item);
11467 } else {
11468 fnvlist_add_nvlist(d, zpool_get_name(zhp),
11469 item);
11470 }
11471 fnvlist_free(item);
11472 return (0);
11473 }
11474
11475 /*
11476 * Display a summary of pool status. Displays a summary such as:
11477 *
11478 * pool: tank
11479 * status: DEGRADED
11480 * reason: One or more devices ...
11481 * see: https://openzfs.github.io/openzfs-docs/msg/ZFS-xxxx-01
11482 * config:
11483 * mirror DEGRADED
11484 * c1t0d0 OK
11485 * c2t0d0 UNAVAIL
11486 *
11487 * When given the '-v' option, we print out the complete config. If the '-e'
11488 * option is specified, then we print out error rate information as well.
11489 */
11490 static int
status_callback(zpool_handle_t * zhp,void * data)11491 status_callback(zpool_handle_t *zhp, void *data)
11492 {
11493 status_cbdata_t *cbp = data;
11494 nvlist_t *config, *nvroot;
11495 const char *msgid;
11496 zpool_status_t reason;
11497 zpool_errata_t errata;
11498 const char *health;
11499 uint_t c;
11500 vdev_stat_t *vs;
11501
11502 /* If dedup stats were requested, also fetch dedupcached. */
11503 if (cbp->cb_dedup_stats > 1)
11504 zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
11505
11506 config = zpool_get_config(zhp, NULL);
11507 reason = zpool_get_status(zhp, &msgid, &errata);
11508
11509 cbp->cb_count++;
11510
11511 /*
11512 * If we were given 'zpool status -x', only report those pools with
11513 * problems.
11514 */
11515 if (cbp->cb_explain &&
11516 (reason == ZPOOL_STATUS_OK ||
11517 reason == ZPOOL_STATUS_VERSION_OLDER ||
11518 reason == ZPOOL_STATUS_FEAT_DISABLED ||
11519 reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
11520 reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
11521 if (!cbp->cb_allpools) {
11522 (void) printf(gettext("pool '%s' is healthy\n"),
11523 zpool_get_name(zhp));
11524 if (cbp->cb_first)
11525 cbp->cb_first = B_FALSE;
11526 }
11527 return (0);
11528 }
11529
11530 if (cbp->cb_first)
11531 cbp->cb_first = B_FALSE;
11532 else
11533 (void) printf("\n");
11534
11535 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
11536 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
11537 (uint64_t **)&vs, &c) == 0);
11538
11539 health = zpool_get_state_str(zhp);
11540
11541 printf(" ");
11542 (void) printf_color(ANSI_BOLD, gettext("pool:"));
11543 printf(" %s\n", zpool_get_name(zhp));
11544 (void) fputc(' ', stdout);
11545 (void) printf_color(ANSI_BOLD, gettext("state: "));
11546
11547 (void) printf_color(health_str_to_color(health), "%s", health);
11548
11549 (void) fputc('\n', stdout);
11550 print_status_reason(zhp, cbp, reason, errata, NULL);
11551
11552 if (msgid != NULL) {
11553 printf(" ");
11554 (void) printf_color(ANSI_BOLD, gettext("see:"));
11555 printf(gettext(
11556 " https://openzfs.github.io/openzfs-docs/msg/%s\n"),
11557 msgid);
11558 }
11559
11560 if (config != NULL) {
11561 uint64_t nerr;
11562 nvlist_t **spares, **l2cache;
11563 uint_t nspares, nl2cache;
11564
11565 print_scan_status(zhp, nvroot);
11566
11567 pool_removal_stat_t *prs = NULL;
11568 (void) nvlist_lookup_uint64_array(nvroot,
11569 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
11570 print_removal_status(zhp, prs);
11571
11572 pool_checkpoint_stat_t *pcs = NULL;
11573 (void) nvlist_lookup_uint64_array(nvroot,
11574 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
11575 print_checkpoint_status(pcs);
11576
11577 pool_raidz_expand_stat_t *pres = NULL;
11578 (void) nvlist_lookup_uint64_array(nvroot,
11579 ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
11580 print_raidz_expand_status(zhp, pres);
11581
11582 nvlist_t *cnv = NULL;
11583 nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_CONDENSE_STATS, &cnv);
11584 print_condense_status(cnv);
11585
11586 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
11587 cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
11588 if (cbp->cb_namewidth < 10)
11589 cbp->cb_namewidth = 10;
11590
11591 color_start(ANSI_BOLD);
11592 (void) printf(gettext("config:\n\n"));
11593 (void) printf(gettext("\t%-*s %-8s %5s %5s %5s"),
11594 cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
11595 "CKSUM");
11596 color_end();
11597
11598 if (cbp->cb_print_slow_ios) {
11599 (void) printf_color(ANSI_BOLD, " %5s", gettext("SLOW"));
11600 }
11601
11602 if (cbp->cb_print_power) {
11603 (void) printf_color(ANSI_BOLD, " %5s",
11604 gettext("POWER"));
11605 }
11606
11607 if (cbp->cb_print_dio_verify) {
11608 (void) printf_color(ANSI_BOLD, " %5s", gettext("DIO"));
11609 }
11610
11611 if (cbp->vcdl != NULL)
11612 print_cmd_columns(cbp->vcdl, 0);
11613
11614 printf("\n");
11615
11616 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
11617 B_FALSE, NULL);
11618
11619 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
11620 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
11621 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
11622
11623 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
11624 &l2cache, &nl2cache) == 0)
11625 print_l2cache(zhp, cbp, l2cache, nl2cache);
11626
11627 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
11628 &spares, &nspares) == 0)
11629 print_spares(zhp, cbp, spares, nspares);
11630
11631 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
11632 &nerr) == 0) {
11633 (void) printf("\n");
11634 if (nerr == 0) {
11635 (void) printf(gettext(
11636 "errors: No known data errors\n"));
11637 } else if (cbp->cb_verbosity == 0) {
11638 color_start(ANSI_RED);
11639 (void) printf(gettext("errors: %llu data "
11640 "errors, use '-v' for details\n"),
11641 (u_longlong_t)nerr);
11642 color_end();
11643 } else {
11644 print_error_log(zhp, cbp->cb_verbosity,
11645 cbp->cb_literal);
11646 }
11647 }
11648
11649 if (cbp->cb_dedup_stats)
11650 print_dedup_stats(zhp, config, cbp->cb_literal);
11651 } else {
11652 (void) printf(gettext("config: The configuration cannot be "
11653 "determined.\n"));
11654 }
11655
11656 return (0);
11657 }
11658
11659 /*
11660 * zpool status [-dDegiLpPstvx] [-c [script1,script2,...]] ...
11661 * [-j|--json [--json-flat-vdevs] [--json-int] ...
11662 * [--json-pool-key-guid]] [--power] [-T d|u] ...
11663 * [pool] [interval [count]]
11664 *
11665 * -c CMD For each vdev, run command CMD
11666 * -D Display dedup status (undocumented)
11667 * -d Display Direct I/O write verify errors
11668 * -e Display only unhealthy vdevs
11669 * -g Display guid for individual vdev name.
11670 * -i Display vdev initialization status.
11671 * -j [...] Display output in JSON format
11672 * --json-flat-vdevs Display vdevs in flat hierarchy
11673 * --json-int Display numbers in integer format instead of string
11674 * --json-pool-key-guid Use pool GUID as key for pool objects
11675 * -L Follow links when resolving vdev path name.
11676 * -P Display full path for vdev name.
11677 * -p Display values in parsable (exact) format.
11678 * --power Display vdev enclosure slot power status
11679 * -s Display slow IOs column.
11680 * -T Display a timestamp in date(1) or Unix format
11681 * -t Display vdev TRIM status.
11682 * -v Display complete error logs
11683 * -x Display only pools with potential problems
11684 *
11685 * Describes the health status of all pools or some subset.
11686 */
11687 int
zpool_do_status(int argc,char ** argv)11688 zpool_do_status(int argc, char **argv)
11689 {
11690 int c;
11691 int ret;
11692 float interval = 0;
11693 unsigned long count = 0;
11694 status_cbdata_t cb = { 0 };
11695 nvlist_t *data;
11696 char *cmd = NULL;
11697
11698 struct option long_options[] = {
11699 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
11700 {"json", no_argument, NULL, 'j'},
11701 {"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
11702 {"json-flat-vdevs", no_argument, NULL,
11703 ZPOOL_OPTION_JSON_FLAT_VDEVS},
11704 {"json-pool-key-guid", no_argument, NULL,
11705 ZPOOL_OPTION_POOL_KEY_GUID},
11706 {0, 0, 0, 0}
11707 };
11708
11709 /* check options */
11710 while ((c = getopt_long(argc, argv, "c:jdDegiLpPstT:vx", long_options,
11711 NULL)) != -1) {
11712 switch (c) {
11713 case 'c':
11714 if (cmd != NULL) {
11715 fprintf(stderr,
11716 gettext("Can't set -c flag twice\n"));
11717 exit(1);
11718 }
11719
11720 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
11721 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
11722 fprintf(stderr, gettext(
11723 "Can't run -c, disabled by "
11724 "ZPOOL_SCRIPTS_ENABLED.\n"));
11725 exit(1);
11726 }
11727
11728 if ((getuid() <= 0 || geteuid() <= 0) &&
11729 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
11730 fprintf(stderr, gettext(
11731 "Can't run -c with root privileges "
11732 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
11733 exit(1);
11734 }
11735 cmd = optarg;
11736 break;
11737 case 'd':
11738 cb.cb_print_dio_verify = B_TRUE;
11739 break;
11740 case 'D':
11741 if (++cb.cb_dedup_stats > 2)
11742 cb.cb_dedup_stats = 2;
11743 break;
11744 case 'e':
11745 cb.cb_print_unhealthy = B_TRUE;
11746 break;
11747 case 'g':
11748 cb.cb_name_flags |= VDEV_NAME_GUID;
11749 break;
11750 case 'i':
11751 cb.cb_print_vdev_init = B_TRUE;
11752 break;
11753 case 'L':
11754 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
11755 break;
11756 case 'p':
11757 cb.cb_literal = B_TRUE;
11758 break;
11759 case 'P':
11760 cb.cb_name_flags |= VDEV_NAME_PATH;
11761 break;
11762 case 's':
11763 cb.cb_print_slow_ios = B_TRUE;
11764 break;
11765 case 't':
11766 cb.cb_print_vdev_trim = B_TRUE;
11767 break;
11768 case 'T':
11769 get_timestamp_arg(*optarg);
11770 break;
11771 case 'v':
11772 cb.cb_verbosity++;
11773 break;
11774 case 'j':
11775 cb.cb_json = B_TRUE;
11776 break;
11777 case 'x':
11778 cb.cb_explain = B_TRUE;
11779 break;
11780 case ZPOOL_OPTION_POWER:
11781 cb.cb_print_power = B_TRUE;
11782 break;
11783 case ZPOOL_OPTION_JSON_FLAT_VDEVS:
11784 cb.cb_flat_vdevs = B_TRUE;
11785 break;
11786 case ZPOOL_OPTION_JSON_NUMS_AS_INT:
11787 cb.cb_json_as_int = B_TRUE;
11788 cb.cb_literal = B_TRUE;
11789 break;
11790 case ZPOOL_OPTION_POOL_KEY_GUID:
11791 cb.cb_json_pool_key_guid = B_TRUE;
11792 break;
11793 case '?':
11794 if (optopt == 'c') {
11795 print_zpool_script_list("status");
11796 exit(0);
11797 } else {
11798 fprintf(stderr,
11799 gettext("invalid option '%c'\n"), optopt);
11800 }
11801 usage(B_FALSE);
11802 }
11803 }
11804
11805 argc -= optind;
11806 argv += optind;
11807
11808 get_interval_count(&argc, argv, &interval, &count);
11809
11810 if (argc == 0)
11811 cb.cb_allpools = B_TRUE;
11812
11813 cb.cb_first = B_TRUE;
11814 cb.cb_print_status = B_TRUE;
11815
11816 if (cb.cb_flat_vdevs && !cb.cb_json) {
11817 fprintf(stderr, gettext("'--json-flat-vdevs' only works with"
11818 " '-j' option\n"));
11819 usage(B_FALSE);
11820 }
11821
11822 if (cb.cb_json_as_int && !cb.cb_json) {
11823 (void) fprintf(stderr, gettext("'--json-int' only works with"
11824 " '-j' option\n"));
11825 usage(B_FALSE);
11826 }
11827
11828 if (!cb.cb_json && cb.cb_json_pool_key_guid) {
11829 (void) fprintf(stderr, gettext("'json-pool-key-guid' only"
11830 " works with '-j' option\n"));
11831 usage(B_FALSE);
11832 }
11833
11834 for (;;) {
11835 if (cb.cb_json) {
11836 cb.cb_jsobj = zpool_json_schema(0, 1);
11837 data = fnvlist_alloc();
11838 fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
11839 fnvlist_free(data);
11840 }
11841
11842 if (timestamp_fmt != NODATE) {
11843 if (cb.cb_json) {
11844 if (cb.cb_json_as_int) {
11845 fnvlist_add_uint64(cb.cb_jsobj, "time",
11846 time(NULL));
11847 } else {
11848 char ts[128];
11849 get_timestamp(timestamp_fmt, ts, 128);
11850 fnvlist_add_string(cb.cb_jsobj, "time",
11851 ts);
11852 }
11853 } else
11854 print_timestamp(timestamp_fmt);
11855 }
11856
11857 if (cmd != NULL)
11858 cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
11859 NULL, NULL, 0, 0);
11860
11861 if (cb.cb_json) {
11862 ret = for_each_pool(argc, argv, B_TRUE, NULL,
11863 ZFS_TYPE_POOL, cb.cb_literal,
11864 status_callback_json, &cb);
11865 } else {
11866 ret = for_each_pool(argc, argv, B_TRUE, NULL,
11867 ZFS_TYPE_POOL, cb.cb_literal,
11868 status_callback, &cb);
11869 }
11870
11871 if (cb.vcdl != NULL)
11872 free_vdev_cmd_data_list(cb.vcdl);
11873
11874 if (cb.cb_json) {
11875 if (ret == 0)
11876 zcmd_print_json(cb.cb_jsobj);
11877 else
11878 nvlist_free(cb.cb_jsobj);
11879 } else {
11880 if (argc == 0 && cb.cb_count == 0) {
11881 (void) fprintf(stderr, "%s",
11882 gettext("no pools available\n"));
11883 } else if (cb.cb_explain && cb.cb_first &&
11884 cb.cb_allpools) {
11885 (void) printf("%s",
11886 gettext("all pools are healthy\n"));
11887 }
11888 }
11889
11890 if (ret != 0)
11891 return (ret);
11892
11893 if (interval == 0)
11894 break;
11895
11896 if (count != 0 && --count == 0)
11897 break;
11898
11899 (void) fflush(stdout);
11900 (void) fsleep(interval);
11901 }
11902
11903 return (0);
11904 }
11905
11906 typedef struct upgrade_cbdata {
11907 int cb_first;
11908 int cb_argc;
11909 uint64_t cb_version;
11910 char **cb_argv;
11911 } upgrade_cbdata_t;
11912
11913 static int
check_unsupp_fs(zfs_handle_t * zhp,void * unsupp_fs)11914 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
11915 {
11916 int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
11917 int *count = (int *)unsupp_fs;
11918
11919 if (zfs_version > ZPL_VERSION) {
11920 (void) printf(gettext("%s (v%d) is not supported by this "
11921 "implementation of ZFS.\n"),
11922 zfs_get_name(zhp), zfs_version);
11923 (*count)++;
11924 }
11925
11926 (void) zfs_iter_filesystems_v2(zhp, 0, check_unsupp_fs, unsupp_fs);
11927
11928 zfs_close(zhp);
11929
11930 return (0);
11931 }
11932
11933 static int
upgrade_version(zpool_handle_t * zhp,uint64_t version)11934 upgrade_version(zpool_handle_t *zhp, uint64_t version)
11935 {
11936 int ret;
11937 nvlist_t *config;
11938 uint64_t oldversion;
11939 int unsupp_fs = 0;
11940
11941 config = zpool_get_config(zhp, NULL);
11942 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11943 &oldversion) == 0);
11944
11945 char compat[ZFS_MAXPROPLEN];
11946 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11947 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11948 compat[0] = '\0';
11949
11950 assert(SPA_VERSION_IS_SUPPORTED(oldversion));
11951 assert(oldversion < version);
11952
11953 ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
11954 if (ret != 0)
11955 return (ret);
11956
11957 if (unsupp_fs) {
11958 (void) fprintf(stderr, gettext("Upgrade not performed due "
11959 "to %d unsupported filesystems (max v%d).\n"),
11960 unsupp_fs, (int)ZPL_VERSION);
11961 return (1);
11962 }
11963
11964 if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
11965 (void) fprintf(stderr, gettext("Upgrade not performed because "
11966 "'compatibility' property set to '"
11967 ZPOOL_COMPAT_LEGACY "'.\n"));
11968 return (1);
11969 }
11970
11971 ret = zpool_upgrade(zhp, version);
11972 if (ret != 0)
11973 return (ret);
11974
11975 if (version >= SPA_VERSION_FEATURES) {
11976 (void) printf(gettext("Successfully upgraded "
11977 "'%s' from version %llu to feature flags.\n"),
11978 zpool_get_name(zhp), (u_longlong_t)oldversion);
11979 } else {
11980 (void) printf(gettext("Successfully upgraded "
11981 "'%s' from version %llu to version %llu.\n"),
11982 zpool_get_name(zhp), (u_longlong_t)oldversion,
11983 (u_longlong_t)version);
11984 }
11985
11986 return (0);
11987 }
11988
11989 static int
upgrade_enable_all(zpool_handle_t * zhp,int * countp)11990 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
11991 {
11992 int i, ret, count;
11993 boolean_t firstff = B_TRUE;
11994 nvlist_t *enabled = zpool_get_features(zhp);
11995
11996 char compat[ZFS_MAXPROPLEN];
11997 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11998 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11999 compat[0] = '\0';
12000
12001 boolean_t requested_features[SPA_FEATURES];
12002 if (zpool_do_load_compat(compat, requested_features) !=
12003 ZPOOL_COMPATIBILITY_OK)
12004 return (-1);
12005
12006 count = 0;
12007 for (i = 0; i < SPA_FEATURES; i++) {
12008 const char *fname = spa_feature_table[i].fi_uname;
12009 const char *fguid = spa_feature_table[i].fi_guid;
12010
12011 if (!spa_feature_table[i].fi_zfs_mod_supported ||
12012 (spa_feature_table[i].fi_flags & ZFEATURE_FLAG_NO_UPGRADE))
12013 continue;
12014
12015 if (!nvlist_exists(enabled, fguid) && requested_features[i]) {
12016 char *propname;
12017 verify(-1 != asprintf(&propname, "feature@%s", fname));
12018 ret = zpool_set_prop(zhp, propname,
12019 ZFS_FEATURE_ENABLED);
12020 if (ret != 0) {
12021 free(propname);
12022 return (ret);
12023 }
12024 count++;
12025
12026 if (firstff) {
12027 (void) printf(gettext("Enabled the "
12028 "following features on '%s':\n"),
12029 zpool_get_name(zhp));
12030 firstff = B_FALSE;
12031 }
12032 (void) printf(gettext(" %s\n"), fname);
12033 free(propname);
12034 }
12035 }
12036
12037 if (countp != NULL)
12038 *countp = count;
12039 return (0);
12040 }
12041
12042 static int
upgrade_cb(zpool_handle_t * zhp,void * arg)12043 upgrade_cb(zpool_handle_t *zhp, void *arg)
12044 {
12045 upgrade_cbdata_t *cbp = arg;
12046 nvlist_t *config;
12047 uint64_t version;
12048 boolean_t modified_pool = B_FALSE;
12049 int ret;
12050
12051 config = zpool_get_config(zhp, NULL);
12052 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
12053 &version) == 0);
12054
12055 assert(SPA_VERSION_IS_SUPPORTED(version));
12056
12057 if (version < cbp->cb_version) {
12058 cbp->cb_first = B_FALSE;
12059 ret = upgrade_version(zhp, cbp->cb_version);
12060 if (ret != 0)
12061 return (ret);
12062 modified_pool = B_TRUE;
12063
12064 /*
12065 * If they did "zpool upgrade -a", then we could
12066 * be doing ioctls to different pools. We need
12067 * to log this history once to each pool, and bypass
12068 * the normal history logging that happens in main().
12069 */
12070 (void) zpool_log_history(g_zfs, history_str);
12071 log_history = B_FALSE;
12072 }
12073
12074 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
12075 int count;
12076 ret = upgrade_enable_all(zhp, &count);
12077 if (ret != 0)
12078 return (ret);
12079
12080 if (count > 0) {
12081 cbp->cb_first = B_FALSE;
12082 modified_pool = B_TRUE;
12083 }
12084 }
12085
12086 if (modified_pool) {
12087 (void) printf("\n");
12088 (void) after_zpool_upgrade(zhp);
12089 }
12090
12091 return (0);
12092 }
12093
12094 static int
upgrade_list_older_cb(zpool_handle_t * zhp,void * arg)12095 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
12096 {
12097 upgrade_cbdata_t *cbp = arg;
12098 nvlist_t *config;
12099 uint64_t version;
12100
12101 config = zpool_get_config(zhp, NULL);
12102 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
12103 &version) == 0);
12104
12105 assert(SPA_VERSION_IS_SUPPORTED(version));
12106
12107 if (version < SPA_VERSION_FEATURES) {
12108 if (cbp->cb_first) {
12109 (void) printf(gettext("The following pools are "
12110 "formatted with legacy version numbers and can\n"
12111 "be upgraded to use feature flags. After "
12112 "being upgraded, these pools\nwill no "
12113 "longer be accessible by software that does not "
12114 "support feature\nflags.\n\n"
12115 "Note that setting a pool's 'compatibility' "
12116 "feature to '" ZPOOL_COMPAT_LEGACY "' will\n"
12117 "inhibit upgrades.\n\n"));
12118 (void) printf(gettext("VER POOL\n"));
12119 (void) printf(gettext("--- ------------\n"));
12120 cbp->cb_first = B_FALSE;
12121 }
12122
12123 (void) printf("%2llu %s\n", (u_longlong_t)version,
12124 zpool_get_name(zhp));
12125 }
12126
12127 return (0);
12128 }
12129
12130 static int
upgrade_list_disabled_cb(zpool_handle_t * zhp,void * arg)12131 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
12132 {
12133 upgrade_cbdata_t *cbp = arg;
12134 nvlist_t *config;
12135 uint64_t version;
12136
12137 config = zpool_get_config(zhp, NULL);
12138 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
12139 &version) == 0);
12140
12141 if (version >= SPA_VERSION_FEATURES) {
12142 int i;
12143 boolean_t poolfirst = B_TRUE;
12144 nvlist_t *enabled = zpool_get_features(zhp);
12145
12146 for (i = 0; i < SPA_FEATURES; i++) {
12147 const char *fguid = spa_feature_table[i].fi_guid;
12148 const char *fname = spa_feature_table[i].fi_uname;
12149
12150 if (!spa_feature_table[i].fi_zfs_mod_supported)
12151 continue;
12152
12153 if (!nvlist_exists(enabled, fguid)) {
12154 if (cbp->cb_first) {
12155 (void) printf(gettext("\nSome "
12156 "supported features are not "
12157 "enabled on the following pools. "
12158 "Once a\nfeature is enabled the "
12159 "pool may become incompatible with "
12160 "software\nthat does not support "
12161 "the feature. See "
12162 "zpool-features(7) for "
12163 "details.\n\n"
12164 "Note that the pool "
12165 "'compatibility' feature can be "
12166 "used to inhibit\nfeature "
12167 "upgrades.\n\n"
12168 "Features marked with (*) are not "
12169 "applied automatically on upgrade, "
12170 "and\nmust be applied explicitly "
12171 "with zpool-set(7).\n\n"));
12172 (void) printf(gettext("POOL "
12173 "FEATURE\n"));
12174 (void) printf(gettext("------"
12175 "---------\n"));
12176 cbp->cb_first = B_FALSE;
12177 }
12178
12179 if (poolfirst) {
12180 (void) printf(gettext("%s\n"),
12181 zpool_get_name(zhp));
12182 poolfirst = B_FALSE;
12183 }
12184
12185 (void) printf(gettext(" %s%s\n"), fname,
12186 spa_feature_table[i].fi_flags &
12187 ZFEATURE_FLAG_NO_UPGRADE ? "(*)" : "");
12188 }
12189 /*
12190 * If they did "zpool upgrade -a", then we could
12191 * be doing ioctls to different pools. We need
12192 * to log this history once to each pool, and bypass
12193 * the normal history logging that happens in main().
12194 */
12195 (void) zpool_log_history(g_zfs, history_str);
12196 log_history = B_FALSE;
12197 }
12198 }
12199
12200 return (0);
12201 }
12202
12203 static int
upgrade_one(zpool_handle_t * zhp,void * data)12204 upgrade_one(zpool_handle_t *zhp, void *data)
12205 {
12206 boolean_t modified_pool = B_FALSE;
12207 upgrade_cbdata_t *cbp = data;
12208 uint64_t cur_version;
12209 int ret;
12210
12211 if (strcmp("log", zpool_get_name(zhp)) == 0) {
12212 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
12213 "Pool 'log' must be renamed using export and import"
12214 " to upgrade.\n"));
12215 return (1);
12216 }
12217
12218 cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
12219 if (cur_version > cbp->cb_version) {
12220 (void) printf(gettext("Pool '%s' is already formatted "
12221 "using more current version '%llu'.\n\n"),
12222 zpool_get_name(zhp), (u_longlong_t)cur_version);
12223 return (0);
12224 }
12225
12226 if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
12227 (void) printf(gettext("Pool '%s' is already formatted "
12228 "using version %llu.\n\n"), zpool_get_name(zhp),
12229 (u_longlong_t)cbp->cb_version);
12230 return (0);
12231 }
12232
12233 if (cur_version != cbp->cb_version) {
12234 modified_pool = B_TRUE;
12235 ret = upgrade_version(zhp, cbp->cb_version);
12236 if (ret != 0)
12237 return (ret);
12238 }
12239
12240 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
12241 int count = 0;
12242 ret = upgrade_enable_all(zhp, &count);
12243 if (ret != 0)
12244 return (ret);
12245
12246 if (count != 0) {
12247 modified_pool = B_TRUE;
12248 } else if (cur_version == SPA_VERSION) {
12249 (void) printf(gettext("Pool '%s' already has all "
12250 "supported and requested features enabled.\n"),
12251 zpool_get_name(zhp));
12252 }
12253 }
12254
12255 if (modified_pool) {
12256 (void) printf("\n");
12257 (void) after_zpool_upgrade(zhp);
12258 }
12259
12260 return (0);
12261 }
12262
12263 /*
12264 * zpool upgrade
12265 * zpool upgrade -v
12266 * zpool upgrade [-V version] <-a | pool ...>
12267 *
12268 * With no arguments, display downrev'd ZFS pool available for upgrade.
12269 * Individual pools can be upgraded by specifying the pool, and '-a' will
12270 * upgrade all pools.
12271 */
12272 int
zpool_do_upgrade(int argc,char ** argv)12273 zpool_do_upgrade(int argc, char **argv)
12274 {
12275 int c;
12276 upgrade_cbdata_t cb = { 0 };
12277 int ret = 0;
12278 boolean_t showversions = B_FALSE;
12279 boolean_t upgradeall = B_FALSE;
12280 char *end;
12281
12282
12283 /* check options */
12284 while ((c = getopt(argc, argv, ":avV:")) != -1) {
12285 switch (c) {
12286 case 'a':
12287 upgradeall = B_TRUE;
12288 break;
12289 case 'v':
12290 showversions = B_TRUE;
12291 break;
12292 case 'V':
12293 cb.cb_version = strtoll(optarg, &end, 10);
12294 if (*end != '\0' ||
12295 !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
12296 (void) fprintf(stderr,
12297 gettext("invalid version '%s'\n"), optarg);
12298 usage(B_FALSE);
12299 }
12300 break;
12301 case ':':
12302 (void) fprintf(stderr, gettext("missing argument for "
12303 "'%c' option\n"), optopt);
12304 usage(B_FALSE);
12305 break;
12306 case '?':
12307 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
12308 optopt);
12309 usage(B_FALSE);
12310 }
12311 }
12312
12313 cb.cb_argc = argc;
12314 cb.cb_argv = argv;
12315 argc -= optind;
12316 argv += optind;
12317
12318 if (cb.cb_version == 0) {
12319 cb.cb_version = SPA_VERSION;
12320 } else if (!upgradeall && argc == 0) {
12321 (void) fprintf(stderr, gettext("-V option is "
12322 "incompatible with other arguments\n"));
12323 usage(B_FALSE);
12324 }
12325
12326 if (showversions) {
12327 if (upgradeall || argc != 0) {
12328 (void) fprintf(stderr, gettext("-v option is "
12329 "incompatible with other arguments\n"));
12330 usage(B_FALSE);
12331 }
12332 } else if (upgradeall) {
12333 if (argc != 0) {
12334 (void) fprintf(stderr, gettext("-a option should not "
12335 "be used along with a pool name\n"));
12336 usage(B_FALSE);
12337 }
12338 }
12339
12340 (void) printf("%s", gettext("This system supports ZFS pool feature "
12341 "flags.\n\n"));
12342 if (showversions) {
12343 int i;
12344
12345 (void) printf(gettext("The following features are "
12346 "supported:\n\n"));
12347 (void) printf(gettext("FEAT DESCRIPTION\n"));
12348 (void) printf("----------------------------------------------"
12349 "---------------\n");
12350 for (i = 0; i < SPA_FEATURES; i++) {
12351 zfeature_info_t *fi = &spa_feature_table[i];
12352 if (!fi->fi_zfs_mod_supported)
12353 continue;
12354 const char *ro =
12355 (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
12356 " (read-only compatible)" : "";
12357
12358 (void) printf("%-37s%s\n", fi->fi_uname, ro);
12359 (void) printf(" %s\n", fi->fi_desc);
12360 }
12361 (void) printf("\n");
12362
12363 (void) printf(gettext("The following legacy versions are also "
12364 "supported:\n\n"));
12365 (void) printf(gettext("VER DESCRIPTION\n"));
12366 (void) printf("--- -----------------------------------------"
12367 "---------------\n");
12368 (void) printf(gettext(" 1 Initial ZFS version\n"));
12369 (void) printf(gettext(" 2 Ditto blocks "
12370 "(replicated metadata)\n"));
12371 (void) printf(gettext(" 3 Hot spares and double parity "
12372 "RAID-Z\n"));
12373 (void) printf(gettext(" 4 zpool history\n"));
12374 (void) printf(gettext(" 5 Compression using the gzip "
12375 "algorithm\n"));
12376 (void) printf(gettext(" 6 bootfs pool property\n"));
12377 (void) printf(gettext(" 7 Separate intent log devices\n"));
12378 (void) printf(gettext(" 8 Delegated administration\n"));
12379 (void) printf(gettext(" 9 refquota and refreservation "
12380 "properties\n"));
12381 (void) printf(gettext(" 10 Cache devices\n"));
12382 (void) printf(gettext(" 11 Improved scrub performance\n"));
12383 (void) printf(gettext(" 12 Snapshot properties\n"));
12384 (void) printf(gettext(" 13 snapused property\n"));
12385 (void) printf(gettext(" 14 passthrough-x aclinherit\n"));
12386 (void) printf(gettext(" 15 user/group space accounting\n"));
12387 (void) printf(gettext(" 16 stmf property support\n"));
12388 (void) printf(gettext(" 17 Triple-parity RAID-Z\n"));
12389 (void) printf(gettext(" 18 Snapshot user holds\n"));
12390 (void) printf(gettext(" 19 Log device removal\n"));
12391 (void) printf(gettext(" 20 Compression using zle "
12392 "(zero-length encoding)\n"));
12393 (void) printf(gettext(" 21 Deduplication\n"));
12394 (void) printf(gettext(" 22 Received properties\n"));
12395 (void) printf(gettext(" 23 Slim ZIL\n"));
12396 (void) printf(gettext(" 24 System attributes\n"));
12397 (void) printf(gettext(" 25 Improved scrub stats\n"));
12398 (void) printf(gettext(" 26 Improved snapshot deletion "
12399 "performance\n"));
12400 (void) printf(gettext(" 27 Improved snapshot creation "
12401 "performance\n"));
12402 (void) printf(gettext(" 28 Multiple vdev replacements\n"));
12403 (void) printf(gettext("\nFor more information on a particular "
12404 "version, including supported releases,\n"));
12405 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
12406 } else if (argc == 0 && upgradeall) {
12407 cb.cb_first = B_TRUE;
12408 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
12409 if (ret == 0 && cb.cb_first) {
12410 if (cb.cb_version == SPA_VERSION) {
12411 (void) printf(gettext("All pools are already "
12412 "formatted using feature flags.\n\n"));
12413 (void) printf(gettext("Every feature flags "
12414 "pool already has all supported and "
12415 "requested features enabled.\n"));
12416 } else {
12417 (void) printf(gettext("All pools are already "
12418 "formatted with version %llu or higher.\n"),
12419 (u_longlong_t)cb.cb_version);
12420 }
12421 }
12422 } else if (argc == 0) {
12423 cb.cb_first = B_TRUE;
12424 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
12425 assert(ret == 0);
12426
12427 if (cb.cb_first) {
12428 (void) printf(gettext("All pools are formatted "
12429 "using feature flags.\n\n"));
12430 } else {
12431 (void) printf(gettext("\nUse 'zpool upgrade -v' "
12432 "for a list of available legacy versions.\n"));
12433 }
12434
12435 cb.cb_first = B_TRUE;
12436 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
12437 assert(ret == 0);
12438
12439 if (cb.cb_first) {
12440 (void) printf(gettext("Every feature flags pool has "
12441 "all supported and requested features enabled.\n"));
12442 } else {
12443 (void) printf(gettext("\n"));
12444 }
12445 } else {
12446 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
12447 B_FALSE, upgrade_one, &cb);
12448 }
12449
12450 return (ret);
12451 }
12452
12453 typedef struct hist_cbdata {
12454 boolean_t first;
12455 boolean_t longfmt;
12456 boolean_t internal;
12457 } hist_cbdata_t;
12458
12459 static void
print_history_records(nvlist_t * nvhis,hist_cbdata_t * cb)12460 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
12461 {
12462 nvlist_t **records;
12463 uint_t numrecords;
12464 int i;
12465
12466 verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
12467 &records, &numrecords) == 0);
12468 for (i = 0; i < numrecords; i++) {
12469 nvlist_t *rec = records[i];
12470 char tbuf[64] = "";
12471
12472 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
12473 time_t tsec;
12474 struct tm t;
12475
12476 tsec = fnvlist_lookup_uint64(records[i],
12477 ZPOOL_HIST_TIME);
12478 (void) localtime_r(&tsec, &t);
12479 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
12480 }
12481
12482 if (nvlist_exists(rec, ZPOOL_HIST_ELAPSED_NS)) {
12483 uint64_t elapsed_ns = fnvlist_lookup_int64(records[i],
12484 ZPOOL_HIST_ELAPSED_NS);
12485 (void) snprintf(tbuf + strlen(tbuf),
12486 sizeof (tbuf) - strlen(tbuf),
12487 " (%lldms)", (long long)elapsed_ns / 1000 / 1000);
12488 }
12489
12490 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
12491 (void) printf("%s %s", tbuf,
12492 fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
12493 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
12494 int ievent =
12495 fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
12496 if (!cb->internal)
12497 continue;
12498 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
12499 (void) printf("%s unrecognized record:\n",
12500 tbuf);
12501 dump_nvlist(rec, 4);
12502 continue;
12503 }
12504 (void) printf("%s [internal %s txg:%lld] %s", tbuf,
12505 zfs_history_event_names[ievent],
12506 (longlong_t)fnvlist_lookup_uint64(
12507 rec, ZPOOL_HIST_TXG),
12508 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
12509 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
12510 if (!cb->internal)
12511 continue;
12512 (void) printf("%s [txg:%lld] %s", tbuf,
12513 (longlong_t)fnvlist_lookup_uint64(
12514 rec, ZPOOL_HIST_TXG),
12515 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
12516 if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
12517 (void) printf(" %s (%llu)",
12518 fnvlist_lookup_string(rec,
12519 ZPOOL_HIST_DSNAME),
12520 (u_longlong_t)fnvlist_lookup_uint64(rec,
12521 ZPOOL_HIST_DSID));
12522 }
12523 (void) printf(" %s", fnvlist_lookup_string(rec,
12524 ZPOOL_HIST_INT_STR));
12525 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
12526 if (!cb->internal)
12527 continue;
12528 (void) printf("%s ioctl %s\n", tbuf,
12529 fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
12530 if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
12531 (void) printf(" input:\n");
12532 dump_nvlist(fnvlist_lookup_nvlist(rec,
12533 ZPOOL_HIST_INPUT_NVL), 8);
12534 }
12535 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
12536 (void) printf(" output:\n");
12537 dump_nvlist(fnvlist_lookup_nvlist(rec,
12538 ZPOOL_HIST_OUTPUT_NVL), 8);
12539 }
12540 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_SIZE)) {
12541 (void) printf(" output nvlist omitted; "
12542 "original size: %lldKB\n",
12543 (longlong_t)fnvlist_lookup_int64(rec,
12544 ZPOOL_HIST_OUTPUT_SIZE) / 1024);
12545 }
12546 if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
12547 (void) printf(" errno: %lld\n",
12548 (longlong_t)fnvlist_lookup_int64(rec,
12549 ZPOOL_HIST_ERRNO));
12550 }
12551 } else {
12552 if (!cb->internal)
12553 continue;
12554 (void) printf("%s unrecognized record:\n", tbuf);
12555 dump_nvlist(rec, 4);
12556 }
12557
12558 if (!cb->longfmt) {
12559 (void) printf("\n");
12560 continue;
12561 }
12562 (void) printf(" [");
12563 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
12564 uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
12565 struct passwd *pwd = getpwuid(who);
12566 (void) printf("user %d ", (int)who);
12567 if (pwd != NULL)
12568 (void) printf("(%s) ", pwd->pw_name);
12569 }
12570 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
12571 (void) printf("on %s",
12572 fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
12573 }
12574 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
12575 (void) printf(":%s",
12576 fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
12577 }
12578
12579 (void) printf("]");
12580 (void) printf("\n");
12581 }
12582 }
12583
12584 /*
12585 * Print out the command history for a specific pool.
12586 */
12587 static int
get_history_one(zpool_handle_t * zhp,void * data)12588 get_history_one(zpool_handle_t *zhp, void *data)
12589 {
12590 nvlist_t *nvhis;
12591 int ret;
12592 hist_cbdata_t *cb = (hist_cbdata_t *)data;
12593 uint64_t off = 0;
12594 boolean_t eof = B_FALSE;
12595
12596 cb->first = B_FALSE;
12597
12598 (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
12599
12600 while (!eof) {
12601 if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
12602 return (ret);
12603
12604 print_history_records(nvhis, cb);
12605 nvlist_free(nvhis);
12606 }
12607 (void) printf("\n");
12608
12609 return (ret);
12610 }
12611
12612 /*
12613 * zpool history <pool>
12614 *
12615 * Displays the history of commands that modified pools.
12616 */
12617 int
zpool_do_history(int argc,char ** argv)12618 zpool_do_history(int argc, char **argv)
12619 {
12620 hist_cbdata_t cbdata = { 0 };
12621 int ret;
12622 int c;
12623
12624 cbdata.first = B_TRUE;
12625 /* check options */
12626 while ((c = getopt(argc, argv, "li")) != -1) {
12627 switch (c) {
12628 case 'l':
12629 cbdata.longfmt = B_TRUE;
12630 break;
12631 case 'i':
12632 cbdata.internal = B_TRUE;
12633 break;
12634 case '?':
12635 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
12636 optopt);
12637 usage(B_FALSE);
12638 }
12639 }
12640 argc -= optind;
12641 argv += optind;
12642
12643 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
12644 B_FALSE, get_history_one, &cbdata);
12645
12646 if (argc == 0 && cbdata.first == B_TRUE) {
12647 (void) fprintf(stderr, gettext("no pools available\n"));
12648 return (0);
12649 }
12650
12651 return (ret);
12652 }
12653
12654 typedef struct ev_opts {
12655 int verbose;
12656 int scripted;
12657 int follow;
12658 int clear;
12659 char poolname[ZFS_MAX_DATASET_NAME_LEN];
12660 } ev_opts_t;
12661
12662 static void
zpool_do_events_short(nvlist_t * nvl,ev_opts_t * opts)12663 zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
12664 {
12665 char ctime_str[26], str[32];
12666 const char *ptr;
12667 int64_t *tv;
12668 uint_t n;
12669
12670 verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
12671 memset(str, ' ', 32);
12672 (void) ctime_r((const time_t *)&tv[0], ctime_str);
12673 (void) memcpy(str, ctime_str+4, 6); /* 'Jun 30' */
12674 (void) memcpy(str+7, ctime_str+20, 4); /* '1993' */
12675 (void) memcpy(str+12, ctime_str+11, 8); /* '21:49:08' */
12676 (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
12677 if (opts->scripted)
12678 (void) printf(gettext("%s\t"), str);
12679 else
12680 (void) printf(gettext("%s "), str);
12681
12682 verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
12683 (void) printf(gettext("%s\n"), ptr);
12684 }
12685
12686 static void
zpool_do_events_nvprint(nvlist_t * nvl,int depth)12687 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
12688 {
12689 nvpair_t *nvp;
12690 static char flagstr[256];
12691
12692 for (nvp = nvlist_next_nvpair(nvl, NULL);
12693 nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
12694
12695 data_type_t type = nvpair_type(nvp);
12696 const char *name = nvpair_name(nvp);
12697
12698 boolean_t b;
12699 uint8_t i8;
12700 uint16_t i16;
12701 uint32_t i32;
12702 uint64_t i64;
12703 const char *str;
12704 nvlist_t *cnv;
12705
12706 printf(gettext("%*s%s = "), depth, "", name);
12707
12708 switch (type) {
12709 case DATA_TYPE_BOOLEAN:
12710 printf(gettext("%s"), "1");
12711 break;
12712
12713 case DATA_TYPE_BOOLEAN_VALUE:
12714 (void) nvpair_value_boolean_value(nvp, &b);
12715 printf(gettext("%s"), b ? "1" : "0");
12716 break;
12717
12718 case DATA_TYPE_BYTE:
12719 (void) nvpair_value_byte(nvp, &i8);
12720 printf(gettext("0x%x"), i8);
12721 break;
12722
12723 case DATA_TYPE_INT8:
12724 (void) nvpair_value_int8(nvp, (void *)&i8);
12725 printf(gettext("0x%x"), i8);
12726 break;
12727
12728 case DATA_TYPE_UINT8:
12729 (void) nvpair_value_uint8(nvp, &i8);
12730 printf(gettext("0x%x"), i8);
12731 break;
12732
12733 case DATA_TYPE_INT16:
12734 (void) nvpair_value_int16(nvp, (void *)&i16);
12735 printf(gettext("0x%x"), i16);
12736 break;
12737
12738 case DATA_TYPE_UINT16:
12739 (void) nvpair_value_uint16(nvp, &i16);
12740 printf(gettext("0x%x"), i16);
12741 break;
12742
12743 case DATA_TYPE_INT32:
12744 (void) nvpair_value_int32(nvp, (void *)&i32);
12745 printf(gettext("0x%x"), i32);
12746 break;
12747
12748 case DATA_TYPE_UINT32:
12749 (void) nvpair_value_uint32(nvp, &i32);
12750 if (strcmp(name,
12751 FM_EREPORT_PAYLOAD_ZFS_ZIO_STAGE) == 0 ||
12752 strcmp(name,
12753 FM_EREPORT_PAYLOAD_ZFS_ZIO_PIPELINE) == 0) {
12754 (void) zfs_valstr_zio_stage(i32, flagstr,
12755 sizeof (flagstr));
12756 printf(gettext("0x%x [%s]"), i32, flagstr);
12757 } else if (strcmp(name,
12758 FM_EREPORT_PAYLOAD_ZFS_ZIO_TYPE) == 0) {
12759 (void) zfs_valstr_zio_type(i32, flagstr,
12760 sizeof (flagstr));
12761 printf(gettext("0x%x [%s]"), i32, flagstr);
12762 } else if (strcmp(name,
12763 FM_EREPORT_PAYLOAD_ZFS_ZIO_PRIORITY) == 0) {
12764 (void) zfs_valstr_zio_priority(i32, flagstr,
12765 sizeof (flagstr));
12766 printf(gettext("0x%x [%s]"), i32, flagstr);
12767 } else {
12768 printf(gettext("0x%x"), i32);
12769 }
12770 break;
12771
12772 case DATA_TYPE_INT64:
12773 (void) nvpair_value_int64(nvp, (void *)&i64);
12774 printf(gettext("0x%llx"), (u_longlong_t)i64);
12775 break;
12776
12777 case DATA_TYPE_UINT64:
12778 (void) nvpair_value_uint64(nvp, &i64);
12779 /*
12780 * translate vdev state values to readable
12781 * strings to aide zpool events consumers
12782 */
12783 if (strcmp(name,
12784 FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
12785 strcmp(name,
12786 FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
12787 printf(gettext("\"%s\" (0x%llx)"),
12788 zpool_state_to_name(i64, VDEV_AUX_NONE),
12789 (u_longlong_t)i64);
12790 } else if (strcmp(name,
12791 FM_EREPORT_PAYLOAD_ZFS_ZIO_FLAGS) == 0) {
12792 (void) zfs_valstr_zio_flag(i64, flagstr,
12793 sizeof (flagstr));
12794 printf(gettext("0x%llx [%s]"),
12795 (u_longlong_t)i64, flagstr);
12796 } else {
12797 printf(gettext("0x%llx"), (u_longlong_t)i64);
12798 }
12799 break;
12800
12801 case DATA_TYPE_HRTIME:
12802 (void) nvpair_value_hrtime(nvp, (void *)&i64);
12803 printf(gettext("0x%llx"), (u_longlong_t)i64);
12804 break;
12805
12806 case DATA_TYPE_STRING:
12807 (void) nvpair_value_string(nvp, &str);
12808 printf(gettext("\"%s\""), str ? str : "<NULL>");
12809 break;
12810
12811 case DATA_TYPE_NVLIST:
12812 printf(gettext("(embedded nvlist)\n"));
12813 (void) nvpair_value_nvlist(nvp, &cnv);
12814 zpool_do_events_nvprint(cnv, depth + 8);
12815 printf(gettext("%*s(end %s)"), depth, "", name);
12816 break;
12817
12818 case DATA_TYPE_NVLIST_ARRAY: {
12819 nvlist_t **val;
12820 uint_t i, nelem;
12821
12822 (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
12823 printf(gettext("(%d embedded nvlists)\n"), nelem);
12824 for (i = 0; i < nelem; i++) {
12825 printf(gettext("%*s%s[%d] = %s\n"),
12826 depth, "", name, i, "(embedded nvlist)");
12827 zpool_do_events_nvprint(val[i], depth + 8);
12828 printf(gettext("%*s(end %s[%i])\n"),
12829 depth, "", name, i);
12830 }
12831 printf(gettext("%*s(end %s)\n"), depth, "", name);
12832 }
12833 break;
12834
12835 case DATA_TYPE_INT8_ARRAY: {
12836 int8_t *val;
12837 uint_t i, nelem;
12838
12839 (void) nvpair_value_int8_array(nvp, &val, &nelem);
12840 for (i = 0; i < nelem; i++)
12841 printf(gettext("0x%x "), val[i]);
12842
12843 break;
12844 }
12845
12846 case DATA_TYPE_UINT8_ARRAY: {
12847 uint8_t *val;
12848 uint_t i, nelem;
12849
12850 (void) nvpair_value_uint8_array(nvp, &val, &nelem);
12851 for (i = 0; i < nelem; i++)
12852 printf(gettext("0x%x "), val[i]);
12853
12854 break;
12855 }
12856
12857 case DATA_TYPE_INT16_ARRAY: {
12858 int16_t *val;
12859 uint_t i, nelem;
12860
12861 (void) nvpair_value_int16_array(nvp, &val, &nelem);
12862 for (i = 0; i < nelem; i++)
12863 printf(gettext("0x%x "), val[i]);
12864
12865 break;
12866 }
12867
12868 case DATA_TYPE_UINT16_ARRAY: {
12869 uint16_t *val;
12870 uint_t i, nelem;
12871
12872 (void) nvpair_value_uint16_array(nvp, &val, &nelem);
12873 for (i = 0; i < nelem; i++)
12874 printf(gettext("0x%x "), val[i]);
12875
12876 break;
12877 }
12878
12879 case DATA_TYPE_INT32_ARRAY: {
12880 int32_t *val;
12881 uint_t i, nelem;
12882
12883 (void) nvpair_value_int32_array(nvp, &val, &nelem);
12884 for (i = 0; i < nelem; i++)
12885 printf(gettext("0x%x "), val[i]);
12886
12887 break;
12888 }
12889
12890 case DATA_TYPE_UINT32_ARRAY: {
12891 uint32_t *val;
12892 uint_t i, nelem;
12893
12894 (void) nvpair_value_uint32_array(nvp, &val, &nelem);
12895 for (i = 0; i < nelem; i++)
12896 printf(gettext("0x%x "), val[i]);
12897
12898 break;
12899 }
12900
12901 case DATA_TYPE_INT64_ARRAY: {
12902 int64_t *val;
12903 uint_t i, nelem;
12904
12905 (void) nvpair_value_int64_array(nvp, &val, &nelem);
12906 for (i = 0; i < nelem; i++)
12907 printf(gettext("0x%llx "),
12908 (u_longlong_t)val[i]);
12909
12910 break;
12911 }
12912
12913 case DATA_TYPE_UINT64_ARRAY: {
12914 uint64_t *val;
12915 uint_t i, nelem;
12916
12917 (void) nvpair_value_uint64_array(nvp, &val, &nelem);
12918 for (i = 0; i < nelem; i++)
12919 printf(gettext("0x%llx "),
12920 (u_longlong_t)val[i]);
12921
12922 break;
12923 }
12924
12925 case DATA_TYPE_STRING_ARRAY: {
12926 const char **str;
12927 uint_t i, nelem;
12928
12929 (void) nvpair_value_string_array(nvp, &str, &nelem);
12930 for (i = 0; i < nelem; i++)
12931 printf(gettext("\"%s\" "),
12932 str[i] ? str[i] : "<NULL>");
12933
12934 break;
12935 }
12936
12937 case DATA_TYPE_BOOLEAN_ARRAY:
12938 case DATA_TYPE_BYTE_ARRAY:
12939 case DATA_TYPE_DOUBLE:
12940 case DATA_TYPE_DONTCARE:
12941 case DATA_TYPE_UNKNOWN:
12942 printf(gettext("<unknown>"));
12943 break;
12944 }
12945
12946 printf(gettext("\n"));
12947 }
12948 }
12949
12950 static int
zpool_do_events_next(ev_opts_t * opts)12951 zpool_do_events_next(ev_opts_t *opts)
12952 {
12953 nvlist_t *nvl;
12954 int zevent_fd, ret, dropped;
12955 const char *pool;
12956
12957 zevent_fd = open(ZFS_DEV, O_RDWR);
12958 VERIFY(zevent_fd >= 0);
12959
12960 if (!opts->scripted)
12961 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
12962
12963 while (1) {
12964 ret = zpool_events_next(g_zfs, &nvl, &dropped,
12965 (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
12966 if (ret || nvl == NULL)
12967 break;
12968
12969 if (dropped > 0)
12970 (void) printf(gettext("dropped %d events\n"), dropped);
12971
12972 if (strlen(opts->poolname) > 0 &&
12973 nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
12974 strcmp(opts->poolname, pool) != 0)
12975 continue;
12976
12977 zpool_do_events_short(nvl, opts);
12978
12979 if (opts->verbose) {
12980 zpool_do_events_nvprint(nvl, 8);
12981 printf(gettext("\n"));
12982 }
12983 (void) fflush(stdout);
12984
12985 nvlist_free(nvl);
12986 }
12987
12988 VERIFY0(close(zevent_fd));
12989
12990 return (ret);
12991 }
12992
12993 static int
zpool_do_events_clear(void)12994 zpool_do_events_clear(void)
12995 {
12996 int count, ret;
12997
12998 ret = zpool_events_clear(g_zfs, &count);
12999 if (!ret)
13000 (void) printf(gettext("cleared %d events\n"), count);
13001
13002 return (ret);
13003 }
13004
13005 /*
13006 * zpool events [-vHf [pool] | -c]
13007 *
13008 * Displays events logs by ZFS.
13009 */
13010 int
zpool_do_events(int argc,char ** argv)13011 zpool_do_events(int argc, char **argv)
13012 {
13013 ev_opts_t opts = { 0 };
13014 int ret;
13015 int c;
13016
13017 /* check options */
13018 while ((c = getopt(argc, argv, "vHfc")) != -1) {
13019 switch (c) {
13020 case 'v':
13021 opts.verbose = 1;
13022 break;
13023 case 'H':
13024 opts.scripted = 1;
13025 break;
13026 case 'f':
13027 opts.follow = 1;
13028 break;
13029 case 'c':
13030 opts.clear = 1;
13031 break;
13032 case '?':
13033 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
13034 optopt);
13035 usage(B_FALSE);
13036 }
13037 }
13038 argc -= optind;
13039 argv += optind;
13040
13041 if (argc > 1) {
13042 (void) fprintf(stderr, gettext("too many arguments\n"));
13043 usage(B_FALSE);
13044 } else if (argc == 1) {
13045 (void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
13046 if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
13047 (void) fprintf(stderr,
13048 gettext("invalid pool name '%s'\n"), opts.poolname);
13049 usage(B_FALSE);
13050 }
13051 }
13052
13053 if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
13054 opts.clear) {
13055 (void) fprintf(stderr,
13056 gettext("invalid options combined with -c\n"));
13057 usage(B_FALSE);
13058 }
13059
13060 if (opts.clear)
13061 ret = zpool_do_events_clear();
13062 else
13063 ret = zpool_do_events_next(&opts);
13064
13065 return (ret);
13066 }
13067
13068 static int
get_callback_vdev(zpool_handle_t * zhp,char * vdevname,void * data)13069 get_callback_vdev(zpool_handle_t *zhp, char *vdevname, void *data)
13070 {
13071 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
13072 char value[ZFS_MAXPROPLEN];
13073 zprop_source_t srctype;
13074 nvlist_t *props, *item, *d;
13075 props = item = d = NULL;
13076
13077 if (cbp->cb_json) {
13078 d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "vdevs");
13079 if (d == NULL) {
13080 fprintf(stderr, "vdevs obj not found.\n");
13081 exit(1);
13082 }
13083 props = fnvlist_alloc();
13084 }
13085
13086 for (zprop_list_t *pl = cbp->cb_proplist; pl != NULL;
13087 pl = pl->pl_next) {
13088 char *prop_name;
13089 /*
13090 * If the first property is pool name, it is a special
13091 * placeholder that we can skip. This will also skip
13092 * over the name property when 'all' is specified.
13093 */
13094 if (pl->pl_prop == ZPOOL_PROP_NAME &&
13095 pl == cbp->cb_proplist)
13096 continue;
13097
13098 if (pl->pl_prop == ZPROP_INVAL) {
13099 prop_name = pl->pl_user_prop;
13100 } else {
13101 prop_name = (char *)vdev_prop_to_name(pl->pl_prop);
13102 }
13103 if (zpool_get_vdev_prop(zhp, vdevname, pl->pl_prop,
13104 prop_name, value, sizeof (value), &srctype,
13105 cbp->cb_literal) == 0) {
13106 (void) zprop_collect_property(vdevname, cbp, prop_name,
13107 value, srctype, NULL, NULL, props);
13108 }
13109 }
13110
13111 if (cbp->cb_json) {
13112 if (!nvlist_empty(props)) {
13113 item = fnvlist_alloc();
13114 fill_vdev_info(item, zhp, vdevname, B_TRUE,
13115 cbp->cb_json_as_int);
13116 fnvlist_add_nvlist(item, "properties", props);
13117 fnvlist_add_nvlist(d, vdevname, item);
13118 fnvlist_add_nvlist(cbp->cb_jsobj, "vdevs", d);
13119 fnvlist_free(item);
13120 }
13121 fnvlist_free(props);
13122 }
13123
13124 return (0);
13125 }
13126
13127 static int
get_callback_vdev_cb(void * zhp_data,nvlist_t * nv,void * data)13128 get_callback_vdev_cb(void *zhp_data, nvlist_t *nv, void *data)
13129 {
13130 zpool_handle_t *zhp = zhp_data;
13131 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
13132 char *vdevname;
13133 const char *type;
13134 int ret;
13135
13136 /*
13137 * zpool_vdev_name() transforms the root vdev name (i.e., root-0) to the
13138 * pool name for display purposes, which is not desired. Fallback to
13139 * zpool_vdev_name() when not dealing with the root vdev.
13140 */
13141 type = fnvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE);
13142 if (zhp != NULL && strcmp(type, "root") == 0)
13143 vdevname = strdup("root-0");
13144 else
13145 vdevname = zpool_vdev_name(g_zfs, zhp, nv,
13146 cbp->cb_vdevs.cb_name_flags);
13147
13148 (void) vdev_expand_proplist(zhp, vdevname, &cbp->cb_proplist);
13149
13150 ret = get_callback_vdev(zhp, vdevname, data);
13151
13152 free(vdevname);
13153
13154 return (ret);
13155 }
13156
13157 static int
get_callback(zpool_handle_t * zhp,void * data)13158 get_callback(zpool_handle_t *zhp, void *data)
13159 {
13160 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
13161 char value[ZFS_MAXPROPLEN];
13162 zprop_source_t srctype;
13163 zprop_list_t *pl;
13164 int vid;
13165 int err = 0;
13166 nvlist_t *props, *item, *d;
13167 props = item = d = NULL;
13168
13169 if (cbp->cb_type == ZFS_TYPE_VDEV) {
13170 if (cbp->cb_json) {
13171 nvlist_t *pool = fnvlist_alloc();
13172 fill_pool_info(pool, zhp, B_FALSE, cbp->cb_json_as_int);
13173 fnvlist_add_nvlist(cbp->cb_jsobj, "pool", pool);
13174 fnvlist_free(pool);
13175 }
13176
13177 if (strcmp(cbp->cb_vdevs.cb_names[0], "all-vdevs") == 0) {
13178 (void) for_each_vdev(zhp, get_callback_vdev_cb, data);
13179 } else {
13180 /* Adjust column widths for vdev properties */
13181 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
13182 vid++) {
13183 (void) vdev_expand_proplist(zhp,
13184 cbp->cb_vdevs.cb_names[vid],
13185 &cbp->cb_proplist);
13186 }
13187 /* Display the properties */
13188 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
13189 vid++) {
13190 (void) get_callback_vdev(zhp,
13191 cbp->cb_vdevs.cb_names[vid], data);
13192 }
13193 }
13194 } else {
13195 assert(cbp->cb_type == ZFS_TYPE_POOL);
13196 if (cbp->cb_json) {
13197 d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
13198 if (d == NULL) {
13199 fprintf(stderr, "pools obj not found.\n");
13200 exit(1);
13201 }
13202 props = fnvlist_alloc();
13203 }
13204 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
13205 /*
13206 * Skip the special fake placeholder. This will also
13207 * skip over the name property when 'all' is specified.
13208 */
13209 if (pl->pl_prop == ZPOOL_PROP_NAME &&
13210 pl == cbp->cb_proplist)
13211 continue;
13212
13213 if (pl->pl_prop == ZPROP_INVAL &&
13214 zfs_prop_user(pl->pl_user_prop)) {
13215 srctype = ZPROP_SRC_LOCAL;
13216
13217 if (zpool_get_userprop(zhp, pl->pl_user_prop,
13218 value, sizeof (value), &srctype) != 0)
13219 continue;
13220
13221 err = zprop_collect_property(
13222 zpool_get_name(zhp), cbp, pl->pl_user_prop,
13223 value, srctype, NULL, NULL, props);
13224 } else if (pl->pl_prop == ZPROP_INVAL &&
13225 (zpool_prop_feature(pl->pl_user_prop) ||
13226 zpool_prop_unsupported(pl->pl_user_prop))) {
13227 srctype = ZPROP_SRC_LOCAL;
13228
13229 if (zpool_prop_get_feature(zhp,
13230 pl->pl_user_prop, value,
13231 sizeof (value)) == 0) {
13232 err = zprop_collect_property(
13233 zpool_get_name(zhp), cbp,
13234 pl->pl_user_prop, value, srctype,
13235 NULL, NULL, props);
13236 }
13237 } else {
13238 if (zpool_get_prop(zhp, pl->pl_prop, value,
13239 sizeof (value), &srctype,
13240 cbp->cb_literal) != 0)
13241 continue;
13242
13243 err = zprop_collect_property(
13244 zpool_get_name(zhp), cbp,
13245 zpool_prop_to_name(pl->pl_prop),
13246 value, srctype, NULL, NULL, props);
13247 }
13248 if (err != 0)
13249 return (err);
13250 }
13251
13252 if (cbp->cb_json) {
13253 if (!nvlist_empty(props)) {
13254 item = fnvlist_alloc();
13255 fill_pool_info(item, zhp, B_TRUE,
13256 cbp->cb_json_as_int);
13257 fnvlist_add_nvlist(item, "properties", props);
13258 if (cbp->cb_json_pool_key_guid) {
13259 char buf[256];
13260 uint64_t guid = fnvlist_lookup_uint64(
13261 zpool_get_config(zhp, NULL),
13262 ZPOOL_CONFIG_POOL_GUID);
13263 (void) snprintf(buf, 256, "%llu",
13264 (u_longlong_t)guid);
13265 fnvlist_add_nvlist(d, buf, item);
13266 } else {
13267 const char *name = zpool_get_name(zhp);
13268 fnvlist_add_nvlist(d, name, item);
13269 }
13270 fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
13271 fnvlist_free(item);
13272 }
13273 fnvlist_free(props);
13274 }
13275 }
13276
13277 return (0);
13278 }
13279
13280 /*
13281 * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
13282 *
13283 * -H Scripted mode. Don't display headers, and separate properties
13284 * by a single tab.
13285 * -o List of columns to display. Defaults to
13286 * "name,property,value,source".
13287 * -p Display values in parsable (exact) format.
13288 * -j Display output in JSON format.
13289 * --json-int Display numbers as integers instead of strings.
13290 * --json-pool-key-guid Set pool GUID as key for pool objects.
13291 *
13292 * Get properties of pools in the system. Output space statistics
13293 * for each one as well as other attributes.
13294 */
13295 int
zpool_do_get(int argc,char ** argv)13296 zpool_do_get(int argc, char **argv)
13297 {
13298 zprop_get_cbdata_t cb = { 0 };
13299 zprop_list_t fake_name = { 0 };
13300 int ret;
13301 int c, i;
13302 char *propstr = NULL;
13303 char *vdev = NULL;
13304 nvlist_t *data = NULL;
13305
13306 cb.cb_first = B_TRUE;
13307
13308 /*
13309 * Set up default columns and sources.
13310 */
13311 cb.cb_sources = ZPROP_SRC_ALL;
13312 cb.cb_columns[0] = GET_COL_NAME;
13313 cb.cb_columns[1] = GET_COL_PROPERTY;
13314 cb.cb_columns[2] = GET_COL_VALUE;
13315 cb.cb_columns[3] = GET_COL_SOURCE;
13316 cb.cb_type = ZFS_TYPE_POOL;
13317 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
13318 current_prop_type = cb.cb_type;
13319
13320 struct option long_options[] = {
13321 {"json", no_argument, NULL, 'j'},
13322 {"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
13323 {"json-pool-key-guid", no_argument, NULL,
13324 ZPOOL_OPTION_POOL_KEY_GUID},
13325 {0, 0, 0, 0}
13326 };
13327
13328 /* check options */
13329 while ((c = getopt_long(argc, argv, ":jHpo:", long_options,
13330 NULL)) != -1) {
13331 switch (c) {
13332 case 'p':
13333 cb.cb_literal = B_TRUE;
13334 break;
13335 case 'H':
13336 cb.cb_scripted = B_TRUE;
13337 break;
13338 case 'j':
13339 cb.cb_json = B_TRUE;
13340 cb.cb_jsobj = zpool_json_schema(0, 1);
13341 data = fnvlist_alloc();
13342 break;
13343 case ZPOOL_OPTION_POOL_KEY_GUID:
13344 cb.cb_json_pool_key_guid = B_TRUE;
13345 break;
13346 case ZPOOL_OPTION_JSON_NUMS_AS_INT:
13347 cb.cb_json_as_int = B_TRUE;
13348 cb.cb_literal = B_TRUE;
13349 break;
13350 case 'o':
13351 memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
13352 i = 0;
13353
13354 for (char *tok; (tok = strsep(&optarg, ",")); ) {
13355 static const char *const col_opts[] =
13356 { "name", "property", "value", "source",
13357 "all" };
13358 static const zfs_get_column_t col_cols[] =
13359 { GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
13360 GET_COL_SOURCE };
13361
13362 if (i == ZFS_GET_NCOLS - 1) {
13363 (void) fprintf(stderr, gettext("too "
13364 "many fields given to -o "
13365 "option\n"));
13366 usage(B_FALSE);
13367 }
13368
13369 for (c = 0; c < ARRAY_SIZE(col_opts); ++c)
13370 if (strcmp(tok, col_opts[c]) == 0)
13371 goto found;
13372
13373 (void) fprintf(stderr,
13374 gettext("invalid column name '%s'\n"), tok);
13375 usage(B_FALSE);
13376
13377 found:
13378 if (c >= 4) {
13379 if (i > 0) {
13380 (void) fprintf(stderr,
13381 gettext("\"all\" conflicts "
13382 "with specific fields "
13383 "given to -o option\n"));
13384 usage(B_FALSE);
13385 }
13386
13387 memcpy(cb.cb_columns, col_cols,
13388 sizeof (col_cols));
13389 i = ZFS_GET_NCOLS - 1;
13390 } else
13391 cb.cb_columns[i++] = col_cols[c];
13392 }
13393 break;
13394 case '?':
13395 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
13396 optopt);
13397 usage(B_FALSE);
13398 }
13399 }
13400
13401 argc -= optind;
13402 argv += optind;
13403
13404 if (!cb.cb_json && cb.cb_json_as_int) {
13405 (void) fprintf(stderr, gettext("'--json-int' only works with"
13406 " '-j' option\n"));
13407 usage(B_FALSE);
13408 }
13409
13410 if (!cb.cb_json && cb.cb_json_pool_key_guid) {
13411 (void) fprintf(stderr, gettext("'json-pool-key-guid' only"
13412 " works with '-j' option\n"));
13413 usage(B_FALSE);
13414 }
13415
13416 if (argc < 1) {
13417 (void) fprintf(stderr, gettext("missing property "
13418 "argument\n"));
13419 usage(B_FALSE);
13420 }
13421
13422 /* Properties list is needed later by zprop_get_list() */
13423 propstr = argv[0];
13424
13425 argc--;
13426 argv++;
13427
13428 if (argc == 0) {
13429 /* No args, so just print the defaults. */
13430 } else if (are_all_pools(argc, argv)) {
13431 /* All the args are pool names */
13432 } else if (are_all_pools(1, argv)) {
13433 /* The first arg is a pool name */
13434 if ((argc == 2 && strcmp(argv[1], "all-vdevs") == 0) ||
13435 (argc == 2 && strcmp(argv[1], "root") == 0) ||
13436 are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
13437 &cb.cb_vdevs)) {
13438
13439 if (strcmp(argv[1], "root") == 0)
13440 vdev = strdup("root-0");
13441
13442 /* ... and the rest are vdev names */
13443 if (vdev == NULL)
13444 cb.cb_vdevs.cb_names = argv + 1;
13445 else
13446 cb.cb_vdevs.cb_names = &vdev;
13447
13448 cb.cb_vdevs.cb_names_count = argc - 1;
13449 cb.cb_type = ZFS_TYPE_VDEV;
13450 argc = 1; /* One pool to process */
13451 } else {
13452 if (cb.cb_json) {
13453 nvlist_free(cb.cb_jsobj);
13454 nvlist_free(data);
13455 }
13456 fprintf(stderr, gettext("Expected a list of vdevs in"
13457 " \"%s\", but got:\n"), argv[0]);
13458 error_list_unresolved_vdevs(argc - 1, argv + 1,
13459 argv[0], &cb.cb_vdevs);
13460 fprintf(stderr, "\n");
13461 usage(B_FALSE);
13462 }
13463 } else {
13464 if (cb.cb_json) {
13465 nvlist_free(cb.cb_jsobj);
13466 nvlist_free(data);
13467 }
13468 /*
13469 * The first arg isn't the name of a valid pool.
13470 */
13471 fprintf(stderr, gettext("Cannot get properties of %s: "
13472 "no such pool available.\n"), argv[0]);
13473 return (1);
13474 }
13475
13476 if (zprop_get_list(g_zfs, propstr, &cb.cb_proplist,
13477 cb.cb_type) != 0) {
13478 /* Use correct list of valid properties (pool or vdev) */
13479 current_prop_type = cb.cb_type;
13480 usage(B_FALSE);
13481 }
13482
13483 if (cb.cb_proplist != NULL) {
13484 fake_name.pl_prop = ZPOOL_PROP_NAME;
13485 fake_name.pl_width = strlen(gettext("NAME"));
13486 fake_name.pl_next = cb.cb_proplist;
13487 cb.cb_proplist = &fake_name;
13488 }
13489
13490 if (cb.cb_json) {
13491 if (cb.cb_type == ZFS_TYPE_VDEV)
13492 fnvlist_add_nvlist(cb.cb_jsobj, "vdevs", data);
13493 else
13494 fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
13495 fnvlist_free(data);
13496 }
13497
13498 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist, cb.cb_type,
13499 cb.cb_literal, get_callback, &cb);
13500
13501 if (ret == 0 && cb.cb_json)
13502 zcmd_print_json(cb.cb_jsobj);
13503 else if (ret != 0 && cb.cb_json)
13504 nvlist_free(cb.cb_jsobj);
13505
13506 if (cb.cb_proplist == &fake_name)
13507 zprop_free_list(fake_name.pl_next);
13508 else
13509 zprop_free_list(cb.cb_proplist);
13510
13511 if (vdev != NULL)
13512 free(vdev);
13513
13514 return (ret);
13515 }
13516
13517 typedef struct set_cbdata {
13518 char *cb_propname;
13519 char *cb_value;
13520 zfs_type_t cb_type;
13521 vdev_cbdata_t cb_vdevs;
13522 boolean_t cb_any_successful;
13523 } set_cbdata_t;
13524
13525 static int
set_pool_callback(zpool_handle_t * zhp,set_cbdata_t * cb)13526 set_pool_callback(zpool_handle_t *zhp, set_cbdata_t *cb)
13527 {
13528 int error;
13529
13530 /* Check if we have out-of-bounds features */
13531 if (strcmp(cb->cb_propname, ZPOOL_CONFIG_COMPATIBILITY) == 0) {
13532 boolean_t features[SPA_FEATURES];
13533 if (zpool_do_load_compat(cb->cb_value, features) !=
13534 ZPOOL_COMPATIBILITY_OK)
13535 return (-1);
13536
13537 nvlist_t *enabled = zpool_get_features(zhp);
13538 spa_feature_t i;
13539 for (i = 0; i < SPA_FEATURES; i++) {
13540 const char *fguid = spa_feature_table[i].fi_guid;
13541 if (nvlist_exists(enabled, fguid) && !features[i])
13542 break;
13543 }
13544 if (i < SPA_FEATURES)
13545 (void) fprintf(stderr, gettext("Warning: one or "
13546 "more features already enabled on pool '%s'\n"
13547 "are not present in this compatibility set.\n"),
13548 zpool_get_name(zhp));
13549 }
13550
13551 /* if we're setting a feature, check it's in compatibility set */
13552 if (zpool_prop_feature(cb->cb_propname) &&
13553 strcmp(cb->cb_value, ZFS_FEATURE_ENABLED) == 0) {
13554 char *fname = strchr(cb->cb_propname, '@') + 1;
13555 spa_feature_t f;
13556
13557 if (zfeature_lookup_name(fname, &f) == 0) {
13558 char compat[ZFS_MAXPROPLEN];
13559 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY,
13560 compat, ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
13561 compat[0] = '\0';
13562
13563 boolean_t features[SPA_FEATURES];
13564 if (zpool_do_load_compat(compat, features) !=
13565 ZPOOL_COMPATIBILITY_OK) {
13566 (void) fprintf(stderr, gettext("Error: "
13567 "cannot enable feature '%s' on pool '%s'\n"
13568 "because the pool's 'compatibility' "
13569 "property cannot be parsed.\n"),
13570 fname, zpool_get_name(zhp));
13571 return (-1);
13572 }
13573
13574 if (!features[f]) {
13575 (void) fprintf(stderr, gettext("Error: "
13576 "cannot enable feature '%s' on pool '%s'\n"
13577 "as it is not specified in this pool's "
13578 "current compatibility set.\n"
13579 "Consider setting 'compatibility' to a "
13580 "less restrictive set, or to 'off'.\n"),
13581 fname, zpool_get_name(zhp));
13582 return (-1);
13583 }
13584 }
13585 }
13586
13587 error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
13588
13589 return (error);
13590 }
13591
13592 static int
set_callback(zpool_handle_t * zhp,void * data)13593 set_callback(zpool_handle_t *zhp, void *data)
13594 {
13595 int error;
13596 set_cbdata_t *cb = (set_cbdata_t *)data;
13597
13598 if (cb->cb_type == ZFS_TYPE_VDEV) {
13599 error = zpool_set_vdev_prop(zhp, *cb->cb_vdevs.cb_names,
13600 cb->cb_propname, cb->cb_value);
13601 } else {
13602 assert(cb->cb_type == ZFS_TYPE_POOL);
13603 error = set_pool_callback(zhp, cb);
13604 }
13605
13606 cb->cb_any_successful = !error;
13607 return (error);
13608 }
13609
13610 int
zpool_do_set(int argc,char ** argv)13611 zpool_do_set(int argc, char **argv)
13612 {
13613 set_cbdata_t cb = { 0 };
13614 int error;
13615 char *vdev = NULL;
13616
13617 current_prop_type = ZFS_TYPE_POOL;
13618 if (argc > 1 && argv[1][0] == '-') {
13619 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
13620 argv[1][1]);
13621 usage(B_FALSE);
13622 }
13623
13624 if (argc < 2) {
13625 (void) fprintf(stderr, gettext("missing property=value "
13626 "argument\n"));
13627 usage(B_FALSE);
13628 }
13629
13630 if (argc < 3) {
13631 (void) fprintf(stderr, gettext("missing pool name\n"));
13632 usage(B_FALSE);
13633 }
13634
13635 if (argc > 4) {
13636 (void) fprintf(stderr, gettext("too many pool names\n"));
13637 usage(B_FALSE);
13638 }
13639
13640 cb.cb_propname = argv[1];
13641 cb.cb_type = ZFS_TYPE_POOL;
13642 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
13643 cb.cb_value = strchr(cb.cb_propname, '=');
13644 if (cb.cb_value == NULL) {
13645 (void) fprintf(stderr, gettext("missing value in "
13646 "property=value argument\n"));
13647 usage(B_FALSE);
13648 }
13649
13650 *(cb.cb_value) = '\0';
13651 cb.cb_value++;
13652 argc -= 2;
13653 argv += 2;
13654
13655 /* argv[0] is pool name */
13656 if (!is_pool(argv[0])) {
13657 (void) fprintf(stderr,
13658 gettext("cannot open '%s': is not a pool\n"), argv[0]);
13659 return (EINVAL);
13660 }
13661
13662 /* argv[1], when supplied, is vdev name */
13663 if (argc == 2) {
13664
13665 if (strcmp(argv[1], "root") == 0)
13666 vdev = strdup("root-0");
13667 else
13668 vdev = strdup(argv[1]);
13669
13670 if (!are_vdevs_in_pool(1, &vdev, argv[0], &cb.cb_vdevs)) {
13671 (void) fprintf(stderr, gettext(
13672 "cannot find '%s' in '%s': device not in pool\n"),
13673 vdev, argv[0]);
13674 free(vdev);
13675 return (EINVAL);
13676 }
13677 cb.cb_vdevs.cb_names = &vdev;
13678 cb.cb_vdevs.cb_names_count = 1;
13679 cb.cb_type = ZFS_TYPE_VDEV;
13680 }
13681
13682 error = for_each_pool(1, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
13683 B_FALSE, set_callback, &cb);
13684
13685 if (vdev != NULL)
13686 free(vdev);
13687
13688 return (error);
13689 }
13690
13691 /* Add up the total number of bytes left to initialize/trim across all vdevs */
13692 static uint64_t
vdev_activity_remaining(nvlist_t * nv,zpool_wait_activity_t activity)13693 vdev_activity_remaining(nvlist_t *nv, zpool_wait_activity_t activity)
13694 {
13695 uint64_t bytes_remaining;
13696 nvlist_t **child;
13697 uint_t c, children;
13698 vdev_stat_t *vs;
13699
13700 assert(activity == ZPOOL_WAIT_INITIALIZE ||
13701 activity == ZPOOL_WAIT_TRIM);
13702
13703 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
13704 (uint64_t **)&vs, &c) == 0);
13705
13706 if (activity == ZPOOL_WAIT_INITIALIZE &&
13707 vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE)
13708 bytes_remaining = vs->vs_initialize_bytes_est -
13709 vs->vs_initialize_bytes_done;
13710 else if (activity == ZPOOL_WAIT_TRIM &&
13711 vs->vs_trim_state == VDEV_TRIM_ACTIVE)
13712 bytes_remaining = vs->vs_trim_bytes_est -
13713 vs->vs_trim_bytes_done;
13714 else
13715 bytes_remaining = 0;
13716
13717 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13718 &child, &children) != 0)
13719 children = 0;
13720
13721 for (c = 0; c < children; c++)
13722 bytes_remaining += vdev_activity_remaining(child[c], activity);
13723
13724 return (bytes_remaining);
13725 }
13726
13727 /* Add up the total number of bytes left to rebuild across top-level vdevs */
13728 static uint64_t
vdev_activity_top_remaining(nvlist_t * nv)13729 vdev_activity_top_remaining(nvlist_t *nv)
13730 {
13731 uint64_t bytes_remaining = 0;
13732 nvlist_t **child;
13733 uint_t children;
13734 int error;
13735
13736 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13737 &child, &children) != 0)
13738 children = 0;
13739
13740 for (uint_t c = 0; c < children; c++) {
13741 vdev_rebuild_stat_t *vrs;
13742 uint_t i;
13743
13744 error = nvlist_lookup_uint64_array(child[c],
13745 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i);
13746 if (error == 0) {
13747 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
13748 bytes_remaining += (vrs->vrs_bytes_est -
13749 vrs->vrs_bytes_rebuilt);
13750 }
13751 }
13752 }
13753
13754 return (bytes_remaining);
13755 }
13756
13757 /* Whether any vdevs are 'spare' or 'replacing' vdevs */
13758 static boolean_t
vdev_any_spare_replacing(nvlist_t * nv)13759 vdev_any_spare_replacing(nvlist_t *nv)
13760 {
13761 nvlist_t **child;
13762 uint_t c, children;
13763 const char *vdev_type;
13764
13765 (void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &vdev_type);
13766
13767 if (strcmp(vdev_type, VDEV_TYPE_REPLACING) == 0 ||
13768 strcmp(vdev_type, VDEV_TYPE_SPARE) == 0 ||
13769 strcmp(vdev_type, VDEV_TYPE_DRAID_SPARE) == 0) {
13770 return (B_TRUE);
13771 }
13772
13773 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13774 &child, &children) != 0)
13775 children = 0;
13776
13777 for (c = 0; c < children; c++) {
13778 if (vdev_any_spare_replacing(child[c]))
13779 return (B_TRUE);
13780 }
13781
13782 return (B_FALSE);
13783 }
13784
13785 typedef struct wait_data {
13786 char *wd_poolname;
13787 boolean_t wd_scripted;
13788 boolean_t wd_exact;
13789 boolean_t wd_headers_once;
13790 boolean_t wd_should_exit;
13791 /* Which activities to wait for */
13792 boolean_t wd_enabled[ZPOOL_WAIT_NUM_ACTIVITIES];
13793 float wd_interval;
13794 pthread_cond_t wd_cv;
13795 pthread_mutex_t wd_mutex;
13796 } wait_data_t;
13797
13798 /*
13799 * Print to stdout a single line, containing one column for each activity that
13800 * we are waiting for specifying how many bytes of work are left for that
13801 * activity.
13802 */
13803 static void
print_wait_status_row(wait_data_t * wd,zpool_handle_t * zhp,int row)13804 print_wait_status_row(wait_data_t *wd, zpool_handle_t *zhp, int row)
13805 {
13806 nvlist_t *config, *nvroot;
13807 uint_t c;
13808 int i;
13809 pool_checkpoint_stat_t *pcs = NULL;
13810 pool_scan_stat_t *pss = NULL;
13811 pool_removal_stat_t *prs = NULL;
13812 pool_raidz_expand_stat_t *pres = NULL;
13813 nvlist_t *cnv = NULL;
13814 const char *const headers[] = {"DISCARD", "FREE", "INITIALIZE",
13815 "REPLACE", "REMOVE", "RESILVER", "SCRUB", "TRIM", "RAIDZ_EXPAND",
13816 "CONDENSE"};
13817 int col_widths[ZPOOL_WAIT_NUM_ACTIVITIES];
13818
13819 /* Calculate the width of each column */
13820 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13821 /*
13822 * Make sure we have enough space in the col for pretty-printed
13823 * numbers and for the column header, and then leave a couple
13824 * spaces between cols for readability.
13825 */
13826 col_widths[i] = MAX(strlen(headers[i]), 6) + 2;
13827 }
13828
13829 if (timestamp_fmt != NODATE)
13830 print_timestamp(timestamp_fmt);
13831
13832 /* Print header if appropriate */
13833 int term_height = terminal_height();
13834 boolean_t reprint_header = (!wd->wd_headers_once && term_height > 0 &&
13835 row % (term_height-1) == 0);
13836 if (!wd->wd_scripted && (row == 0 || reprint_header)) {
13837 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13838 if (wd->wd_enabled[i])
13839 (void) printf("%*s", col_widths[i], headers[i]);
13840 }
13841 (void) fputc('\n', stdout);
13842 }
13843
13844 /* Bytes of work remaining in each activity */
13845 int64_t bytes_rem[ZPOOL_WAIT_NUM_ACTIVITIES] = {0};
13846
13847 bytes_rem[ZPOOL_WAIT_FREE] =
13848 zpool_get_prop_int(zhp, ZPOOL_PROP_FREEING, NULL);
13849
13850 config = zpool_get_config(zhp, NULL);
13851 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
13852
13853 (void) nvlist_lookup_uint64_array(nvroot,
13854 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
13855 if (pcs != NULL && pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
13856 bytes_rem[ZPOOL_WAIT_CKPT_DISCARD] = pcs->pcs_space;
13857
13858 (void) nvlist_lookup_uint64_array(nvroot,
13859 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
13860 if (prs != NULL && prs->prs_state == DSS_SCANNING)
13861 bytes_rem[ZPOOL_WAIT_REMOVE] = prs->prs_to_copy -
13862 prs->prs_copied;
13863
13864 (void) nvlist_lookup_uint64_array(nvroot,
13865 ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&pss, &c);
13866 if (pss != NULL && pss->pss_state == DSS_SCANNING &&
13867 pss->pss_pass_scrub_pause == 0) {
13868 int64_t rem = pss->pss_to_examine - pss->pss_issued;
13869 if (pss->pss_func == POOL_SCAN_SCRUB)
13870 bytes_rem[ZPOOL_WAIT_SCRUB] = rem;
13871 else
13872 bytes_rem[ZPOOL_WAIT_RESILVER] = rem;
13873 } else if (check_rebuilding(nvroot, NULL)) {
13874 bytes_rem[ZPOOL_WAIT_RESILVER] =
13875 vdev_activity_top_remaining(nvroot);
13876 }
13877
13878 (void) nvlist_lookup_uint64_array(nvroot,
13879 ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
13880 if (pres != NULL && pres->pres_state == DSS_SCANNING) {
13881 int64_t rem = pres->pres_to_reflow - pres->pres_reflowed;
13882 bytes_rem[ZPOOL_WAIT_RAIDZ_EXPAND] = rem;
13883 }
13884
13885 /*
13886 * Count each outstanding condense item as a "byte". Its not true,
13887 * but its a counter, and it'll display nicely.
13888 */
13889 if (nvlist_lookup_nvlist(nvroot,
13890 ZPOOL_CONFIG_CONDENSE_STATS, &cnv) == 0) {
13891 for (nvpair_t *nvp = nvlist_next_nvpair(cnv, NULL);
13892 nvp != NULL; nvp = nvlist_next_nvpair(cnv, nvp)) {
13893 nvlist_t *tnv = fnvpair_value_nvlist(nvp);
13894 uint64_t total = fnvlist_lookup_uint64(tnv, "total");
13895 uint64_t processed =
13896 fnvlist_lookup_uint64(tnv, "processed");
13897 bytes_rem[ZPOOL_WAIT_CONDENSE] += (total - processed);
13898 }
13899 }
13900
13901 bytes_rem[ZPOOL_WAIT_INITIALIZE] =
13902 vdev_activity_remaining(nvroot, ZPOOL_WAIT_INITIALIZE);
13903 bytes_rem[ZPOOL_WAIT_TRIM] =
13904 vdev_activity_remaining(nvroot, ZPOOL_WAIT_TRIM);
13905
13906 /*
13907 * A replace finishes after resilvering finishes, so the amount of work
13908 * left for a replace is the same as for resilvering.
13909 *
13910 * It isn't quite correct to say that if we have any 'spare' or
13911 * 'replacing' vdevs and a resilver is happening, then a replace is in
13912 * progress, like we do here. When a hot spare is used, the faulted vdev
13913 * is not removed after the hot spare is resilvered, so parent 'spare'
13914 * vdev is not removed either. So we could have a 'spare' vdev, but be
13915 * resilvering for a different reason. However, we use it as a heuristic
13916 * because we don't have access to the DTLs, which could tell us whether
13917 * or not we have really finished resilvering a hot spare.
13918 */
13919 if (vdev_any_spare_replacing(nvroot))
13920 bytes_rem[ZPOOL_WAIT_REPLACE] = bytes_rem[ZPOOL_WAIT_RESILVER];
13921
13922 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13923 char buf[64];
13924 if (!wd->wd_enabled[i])
13925 continue;
13926
13927 if (wd->wd_exact) {
13928 (void) snprintf(buf, sizeof (buf), "%" PRIi64,
13929 bytes_rem[i]);
13930 } else {
13931 zfs_nicenum(bytes_rem[i], buf, sizeof (buf));
13932 }
13933
13934 if (wd->wd_scripted)
13935 (void) printf(i == 0 ? "%s" : "\t%s", buf);
13936 else
13937 (void) printf(" %*s", col_widths[i] - 1, buf);
13938 }
13939 (void) printf("\n");
13940 (void) fflush(stdout);
13941 }
13942
13943 static void *
wait_status_thread(void * arg)13944 wait_status_thread(void *arg)
13945 {
13946 wait_data_t *wd = (wait_data_t *)arg;
13947 zpool_handle_t *zhp;
13948
13949 if ((zhp = zpool_open(g_zfs, wd->wd_poolname)) == NULL)
13950 return (void *)(1);
13951
13952 for (int row = 0; ; row++) {
13953 boolean_t missing;
13954 struct timespec timeout;
13955 int ret = 0;
13956 (void) clock_gettime(CLOCK_REALTIME, &timeout);
13957
13958 if (zpool_refresh_stats(zhp, &missing) != 0 || missing ||
13959 zpool_props_refresh(zhp) != 0) {
13960 zpool_close(zhp);
13961 return (void *)(uintptr_t)(missing ? 0 : 1);
13962 }
13963
13964 print_wait_status_row(wd, zhp, row);
13965
13966 timeout.tv_sec += floor(wd->wd_interval);
13967 long nanos = timeout.tv_nsec +
13968 (wd->wd_interval - floor(wd->wd_interval)) * NANOSEC;
13969 if (nanos >= NANOSEC) {
13970 timeout.tv_sec++;
13971 timeout.tv_nsec = nanos - NANOSEC;
13972 } else {
13973 timeout.tv_nsec = nanos;
13974 }
13975 (void) pthread_mutex_lock(&wd->wd_mutex);
13976 if (!wd->wd_should_exit)
13977 ret = pthread_cond_timedwait(&wd->wd_cv, &wd->wd_mutex,
13978 &timeout);
13979 (void) pthread_mutex_unlock(&wd->wd_mutex);
13980 if (ret == 0) {
13981 break; /* signaled by main thread */
13982 } else if (ret != ETIMEDOUT) {
13983 (void) fprintf(stderr, gettext("pthread_cond_timedwait "
13984 "failed: %s\n"), strerror(ret));
13985 zpool_close(zhp);
13986 return (void *)(uintptr_t)(1);
13987 }
13988 }
13989
13990 zpool_close(zhp);
13991 return (void *)(0);
13992 }
13993
13994 int
zpool_do_wait(int argc,char ** argv)13995 zpool_do_wait(int argc, char **argv)
13996 {
13997 boolean_t verbose = B_FALSE;
13998 int c, i;
13999 unsigned long count;
14000 pthread_t status_thr;
14001 int error = 0;
14002 zpool_handle_t *zhp;
14003
14004 wait_data_t wd;
14005 wd.wd_scripted = B_FALSE;
14006 wd.wd_exact = B_FALSE;
14007 wd.wd_headers_once = B_FALSE;
14008 wd.wd_should_exit = B_FALSE;
14009
14010 (void) pthread_mutex_init(&wd.wd_mutex, NULL);
14011 (void) pthread_cond_init(&wd.wd_cv, NULL);
14012
14013 /* By default, wait for all types of activity. */
14014 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++)
14015 wd.wd_enabled[i] = B_TRUE;
14016
14017 while ((c = getopt(argc, argv, "HpT:t:")) != -1) {
14018 switch (c) {
14019 case 'H':
14020 wd.wd_scripted = B_TRUE;
14021 break;
14022 case 'n':
14023 wd.wd_headers_once = B_TRUE;
14024 break;
14025 case 'p':
14026 wd.wd_exact = B_TRUE;
14027 break;
14028 case 'T':
14029 get_timestamp_arg(*optarg);
14030 break;
14031 case 't':
14032 /* Reset activities array */
14033 memset(&wd.wd_enabled, 0, sizeof (wd.wd_enabled));
14034
14035 for (char *tok; (tok = strsep(&optarg, ",")); ) {
14036 static const char *const col_opts[] = {
14037 "discard", "free", "initialize", "replace",
14038 "remove", "resilver", "scrub", "trim",
14039 "raidz_expand", "condense" };
14040
14041 for (i = 0; i < ARRAY_SIZE(col_opts); ++i)
14042 if (strcmp(tok, col_opts[i]) == 0) {
14043 wd.wd_enabled[i] = B_TRUE;
14044 goto found;
14045 }
14046
14047 (void) fprintf(stderr,
14048 gettext("invalid activity '%s'\n"), tok);
14049 usage(B_FALSE);
14050 found:;
14051 }
14052 break;
14053 case '?':
14054 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
14055 optopt);
14056 usage(B_FALSE);
14057 }
14058 }
14059
14060 argc -= optind;
14061 argv += optind;
14062
14063 get_interval_count(&argc, argv, &wd.wd_interval, &count);
14064 if (count != 0) {
14065 /* This subcmd only accepts an interval, not a count */
14066 (void) fprintf(stderr, gettext("too many arguments\n"));
14067 usage(B_FALSE);
14068 }
14069
14070 if (wd.wd_interval != 0)
14071 verbose = B_TRUE;
14072
14073 if (argc < 1) {
14074 (void) fprintf(stderr, gettext("missing 'pool' argument\n"));
14075 usage(B_FALSE);
14076 }
14077 if (argc > 1) {
14078 (void) fprintf(stderr, gettext("too many arguments\n"));
14079 usage(B_FALSE);
14080 }
14081
14082 wd.wd_poolname = argv[0];
14083
14084 if ((zhp = zpool_open(g_zfs, wd.wd_poolname)) == NULL)
14085 return (1);
14086
14087 if (verbose) {
14088 /*
14089 * We use a separate thread for printing status updates because
14090 * the main thread will call lzc_wait(), which blocks as long
14091 * as an activity is in progress, which can be a long time.
14092 */
14093 if (pthread_create(&status_thr, NULL, wait_status_thread, &wd)
14094 != 0) {
14095 (void) fprintf(stderr, gettext("failed to create status"
14096 "thread: %s\n"), strerror(errno));
14097 zpool_close(zhp);
14098 return (1);
14099 }
14100 }
14101
14102 /*
14103 * Loop over all activities that we are supposed to wait for until none
14104 * of them are in progress. Note that this means we can end up waiting
14105 * for more activities to complete than just those that were in progress
14106 * when we began waiting; if an activity we are interested in begins
14107 * while we are waiting for another activity, we will wait for both to
14108 * complete before exiting.
14109 */
14110 for (;;) {
14111 boolean_t missing = B_FALSE;
14112 boolean_t any_waited = B_FALSE;
14113
14114 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
14115 boolean_t waited;
14116
14117 if (!wd.wd_enabled[i])
14118 continue;
14119
14120 error = zpool_wait_status(zhp, i, &missing, &waited);
14121 if (error != 0 || missing)
14122 break;
14123
14124 any_waited = (any_waited || waited);
14125 }
14126
14127 if (error != 0 || missing || !any_waited)
14128 break;
14129 }
14130
14131 zpool_close(zhp);
14132
14133 if (verbose) {
14134 uintptr_t status;
14135 (void) pthread_mutex_lock(&wd.wd_mutex);
14136 wd.wd_should_exit = B_TRUE;
14137 (void) pthread_cond_signal(&wd.wd_cv);
14138 (void) pthread_mutex_unlock(&wd.wd_mutex);
14139 (void) pthread_join(status_thr, (void *)&status);
14140 if (status != 0)
14141 error = status;
14142 }
14143
14144 (void) pthread_mutex_destroy(&wd.wd_mutex);
14145 (void) pthread_cond_destroy(&wd.wd_cv);
14146 return (error);
14147 }
14148
14149 /*
14150 * zpool ddtprune -d|-p <amount> <pool>
14151 *
14152 * -d <days> Prune entries <days> old and older
14153 * -p <percent> Prune <percent> amount of entries
14154 *
14155 * Prune single reference entries from DDT to satisfy the amount specified.
14156 */
14157 int
zpool_do_ddt_prune(int argc,char ** argv)14158 zpool_do_ddt_prune(int argc, char **argv)
14159 {
14160 zpool_ddt_prune_unit_t unit = ZPOOL_DDT_PRUNE_NONE;
14161 uint64_t amount = 0;
14162 zpool_handle_t *zhp;
14163 char *endptr;
14164 int c;
14165
14166 while ((c = getopt(argc, argv, "d:p:")) != -1) {
14167 switch (c) {
14168 case 'd':
14169 if (unit == ZPOOL_DDT_PRUNE_PERCENTAGE) {
14170 (void) fprintf(stderr, gettext("-d cannot be "
14171 "combined with -p option\n"));
14172 usage(B_FALSE);
14173 }
14174 errno = 0;
14175 amount = strtoull(optarg, &endptr, 0);
14176 if (errno != 0 || *endptr != '\0' || amount == 0) {
14177 (void) fprintf(stderr,
14178 gettext("invalid days value\n"));
14179 usage(B_FALSE);
14180 }
14181 amount *= 86400; /* convert days to seconds */
14182 unit = ZPOOL_DDT_PRUNE_AGE;
14183 break;
14184 case 'p':
14185 if (unit == ZPOOL_DDT_PRUNE_AGE) {
14186 (void) fprintf(stderr, gettext("-p cannot be "
14187 "combined with -d option\n"));
14188 usage(B_FALSE);
14189 }
14190 errno = 0;
14191 amount = strtoull(optarg, &endptr, 0);
14192 if (errno != 0 || *endptr != '\0' ||
14193 amount == 0 || amount > 100) {
14194 (void) fprintf(stderr,
14195 gettext("invalid percentage value\n"));
14196 usage(B_FALSE);
14197 }
14198 unit = ZPOOL_DDT_PRUNE_PERCENTAGE;
14199 break;
14200 case '?':
14201 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
14202 optopt);
14203 usage(B_FALSE);
14204 }
14205 }
14206 argc -= optind;
14207 argv += optind;
14208
14209 if (unit == ZPOOL_DDT_PRUNE_NONE) {
14210 (void) fprintf(stderr,
14211 gettext("missing amount option (-d|-p <value>)\n"));
14212 usage(B_FALSE);
14213 } else if (argc < 1) {
14214 (void) fprintf(stderr, gettext("missing pool argument\n"));
14215 usage(B_FALSE);
14216 } else if (argc > 1) {
14217 (void) fprintf(stderr, gettext("too many arguments\n"));
14218 usage(B_FALSE);
14219 }
14220 zhp = zpool_open(g_zfs, argv[0]);
14221 if (zhp == NULL)
14222 return (-1);
14223
14224 int error = zpool_ddt_prune(zhp, unit, amount);
14225
14226 zpool_close(zhp);
14227
14228 return (error);
14229 }
14230
14231 static int
find_command_idx(const char * command,int * idx)14232 find_command_idx(const char *command, int *idx)
14233 {
14234 for (int i = 0; i < NCOMMAND; ++i) {
14235 if (command_table[i].name == NULL)
14236 continue;
14237
14238 if (strcmp(command, command_table[i].name) == 0) {
14239 *idx = i;
14240 return (0);
14241 }
14242 }
14243 return (1);
14244 }
14245
14246 /*
14247 * Display version message
14248 */
14249 static int
zpool_do_version(int argc,char ** argv)14250 zpool_do_version(int argc, char **argv)
14251 {
14252 int c;
14253 nvlist_t *jsobj = NULL, *zfs_ver = NULL;
14254 boolean_t json = B_FALSE;
14255
14256 struct option long_options[] = {
14257 {"json", no_argument, NULL, 'j'},
14258 };
14259
14260 while ((c = getopt_long(argc, argv, "j", long_options, NULL)) != -1) {
14261 switch (c) {
14262 case 'j':
14263 json = B_TRUE;
14264 jsobj = zpool_json_schema(0, 1);
14265 break;
14266 case '?':
14267 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
14268 optopt);
14269 usage(B_FALSE);
14270 }
14271 }
14272
14273 argc -= optind;
14274 if (argc != 0) {
14275 (void) fprintf(stderr, "too many arguments\n");
14276 usage(B_FALSE);
14277 }
14278
14279 if (json) {
14280 zfs_ver = zfs_version_nvlist();
14281 if (zfs_ver) {
14282 fnvlist_add_nvlist(jsobj, "zfs_version", zfs_ver);
14283 zcmd_print_json(jsobj);
14284 fnvlist_free(zfs_ver);
14285 return (0);
14286 } else
14287 return (-1);
14288 } else
14289 return (zfs_version_print() != 0);
14290 }
14291
14292 /* Display documentation */
14293 static int
zpool_do_help(int argc,char ** argv)14294 zpool_do_help(int argc, char **argv)
14295 {
14296 char page[MAXNAMELEN];
14297 if (argc < 3 || strcmp(argv[2], "zpool") == 0)
14298 (void) strcpy(page, "zpool");
14299 else if (strcmp(argv[2], "concepts") == 0 ||
14300 strcmp(argv[2], "props") == 0)
14301 (void) snprintf(page, sizeof (page), "zpool%s", argv[2]);
14302 else
14303 (void) snprintf(page, sizeof (page), "zpool-%s", argv[2]);
14304
14305 (void) execlp("man", "man", page, NULL);
14306
14307 fprintf(stderr, "couldn't run man program: %s\n", strerror(errno));
14308 return (-1);
14309 }
14310
14311 /*
14312 * Do zpool_load_compat() and print error message on failure
14313 */
14314 static zpool_compat_status_t
zpool_do_load_compat(const char * compat,boolean_t * list)14315 zpool_do_load_compat(const char *compat, boolean_t *list)
14316 {
14317 char report[1024];
14318
14319 zpool_compat_status_t ret;
14320
14321 ret = zpool_load_compat(compat, list, report, 1024);
14322 switch (ret) {
14323
14324 case ZPOOL_COMPATIBILITY_OK:
14325 break;
14326
14327 case ZPOOL_COMPATIBILITY_NOFILES:
14328 case ZPOOL_COMPATIBILITY_BADFILE:
14329 case ZPOOL_COMPATIBILITY_BADTOKEN:
14330 (void) fprintf(stderr, "Error: %s\n", report);
14331 break;
14332
14333 case ZPOOL_COMPATIBILITY_WARNTOKEN:
14334 (void) fprintf(stderr, "Warning: %s\n", report);
14335 ret = ZPOOL_COMPATIBILITY_OK;
14336 break;
14337 }
14338 return (ret);
14339 }
14340
14341 int
main(int argc,char ** argv)14342 main(int argc, char **argv)
14343 {
14344 int ret = 0;
14345 int i = 0;
14346 char *cmdname;
14347 char **newargv;
14348
14349 (void) setlocale(LC_ALL, "");
14350 (void) setlocale(LC_NUMERIC, "C");
14351 (void) textdomain(TEXT_DOMAIN);
14352 srand(time(NULL));
14353
14354 opterr = 0;
14355
14356 /*
14357 * Make sure the user has specified some command.
14358 */
14359 if (argc < 2) {
14360 (void) fprintf(stderr, gettext("missing command\n"));
14361 usage(B_FALSE);
14362 }
14363
14364 cmdname = argv[1];
14365
14366 /*
14367 * Special case '-?'
14368 */
14369 if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
14370 usage(B_TRUE);
14371
14372 /*
14373 * Special case '-V|--version'
14374 */
14375 if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
14376 return (zfs_version_print() != 0);
14377
14378 /*
14379 * Special case 'help'
14380 */
14381 if (strcmp(cmdname, "help") == 0)
14382 return (zpool_do_help(argc, argv));
14383
14384 /*
14385 * Special case '<subcommand> --help|-?'
14386 */
14387 if (argc >= 3 && (strcmp(argv[2], "--help") == 0 ||
14388 strcmp(argv[2], "-?") == 0)) {
14389 int idx;
14390 if (find_command_idx(cmdname, &idx) == 0) {
14391 current_command = &command_table[idx];
14392 usage(B_FALSE);
14393 }
14394 }
14395
14396 if ((g_zfs = libzfs_init()) == NULL) {
14397 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
14398 return (1);
14399 }
14400
14401 libzfs_print_on_error(g_zfs, B_TRUE);
14402
14403 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
14404
14405 /*
14406 * Many commands modify input strings for string parsing reasons.
14407 * We create a copy to protect the original argv.
14408 */
14409 newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
14410 for (i = 0; i < argc; i++)
14411 newargv[i] = strdup(argv[i]);
14412 newargv[argc] = NULL;
14413
14414 /*
14415 * Run the appropriate command.
14416 */
14417 if (find_command_idx(cmdname, &i) == 0) {
14418 current_command = &command_table[i];
14419 ret = command_table[i].func(argc - 1, newargv + 1);
14420 } else if (strchr(cmdname, '=')) {
14421 verify(find_command_idx("set", &i) == 0);
14422 current_command = &command_table[i];
14423 ret = command_table[i].func(argc, newargv);
14424 } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
14425 /*
14426 * 'freeze' is a vile debugging abomination, so we treat
14427 * it as such.
14428 */
14429 zfs_cmd_t zc = {"\0"};
14430
14431 (void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
14432 ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
14433 if (ret != 0) {
14434 (void) fprintf(stderr,
14435 gettext("failed to freeze pool: %d\n"), errno);
14436 ret = 1;
14437 }
14438
14439 log_history = 0;
14440 } else {
14441 (void) fprintf(stderr, gettext("unrecognized "
14442 "command '%s'\n"), cmdname);
14443 usage(B_FALSE);
14444 }
14445
14446 for (i = 0; i < argc; i++)
14447 free(newargv[i]);
14448 free(newargv);
14449
14450 if (ret == 0 && log_history)
14451 (void) zpool_log_history(g_zfs, history_str);
14452
14453 libzfs_fini(g_zfs);
14454
14455 /*
14456 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
14457 * for the purposes of running ::findleaks.
14458 */
14459 if (getenv("ZFS_ABORT") != NULL) {
14460 (void) printf("dumping core by request\n");
14461 abort();
14462 }
14463
14464 return (ret);
14465 }
14466