zpool: Don't print "repairing" on force faulted drives
[zfs.git] / cmd / zpool / zpool_main.c
blobf412c82f983be74c8054e1e2833532dc0f8dd983
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or https://opensource.org/licenses/CDDL-1.0.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
26 * Copyright (c) 2012 by Frederik Wessels. All rights reserved.
27 * Copyright (c) 2012 by Cyril Plisko. All rights reserved.
28 * Copyright (c) 2013 by Prasad Joshi (sTec). All rights reserved.
29 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
30 * Copyright (c) 2017 Datto Inc.
31 * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
32 * Copyright (c) 2017, Intel Corporation.
33 * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>
34 * Copyright (c) 2021, Colm Buckley <colm@tuatha.org>
35 * Copyright (c) 2021, Klara Inc.
36 * Copyright [2021] Hewlett Packard Enterprise Development LP
39 #include <assert.h>
40 #include <ctype.h>
41 #include <dirent.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <getopt.h>
45 #include <libgen.h>
46 #include <libintl.h>
47 #include <libuutil.h>
48 #include <locale.h>
49 #include <pthread.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <time.h>
54 #include <unistd.h>
55 #include <pwd.h>
56 #include <zone.h>
57 #include <sys/wait.h>
58 #include <zfs_prop.h>
59 #include <sys/fs/zfs.h>
60 #include <sys/stat.h>
61 #include <sys/systeminfo.h>
62 #include <sys/fm/fs/zfs.h>
63 #include <sys/fm/util.h>
64 #include <sys/fm/protocol.h>
65 #include <sys/zfs_ioctl.h>
66 #include <sys/mount.h>
67 #include <sys/sysmacros.h>
69 #include <math.h>
71 #include <libzfs.h>
72 #include <libzutil.h>
74 #include "zpool_util.h"
75 #include "zfs_comutil.h"
76 #include "zfeature_common.h"
78 #include "statcommon.h"
80 libzfs_handle_t *g_zfs;
82 static int zpool_do_create(int, char **);
83 static int zpool_do_destroy(int, char **);
85 static int zpool_do_add(int, char **);
86 static int zpool_do_remove(int, char **);
87 static int zpool_do_labelclear(int, char **);
89 static int zpool_do_checkpoint(int, char **);
91 static int zpool_do_list(int, char **);
92 static int zpool_do_iostat(int, char **);
93 static int zpool_do_status(int, char **);
95 static int zpool_do_online(int, char **);
96 static int zpool_do_offline(int, char **);
97 static int zpool_do_clear(int, char **);
98 static int zpool_do_reopen(int, char **);
100 static int zpool_do_reguid(int, char **);
102 static int zpool_do_attach(int, char **);
103 static int zpool_do_detach(int, char **);
104 static int zpool_do_replace(int, char **);
105 static int zpool_do_split(int, char **);
107 static int zpool_do_initialize(int, char **);
108 static int zpool_do_scrub(int, char **);
109 static int zpool_do_resilver(int, char **);
110 static int zpool_do_trim(int, char **);
112 static int zpool_do_import(int, char **);
113 static int zpool_do_export(int, char **);
115 static int zpool_do_upgrade(int, char **);
117 static int zpool_do_history(int, char **);
118 static int zpool_do_events(int, char **);
120 static int zpool_do_get(int, char **);
121 static int zpool_do_set(int, char **);
123 static int zpool_do_sync(int, char **);
125 static int zpool_do_version(int, char **);
127 static int zpool_do_wait(int, char **);
129 static zpool_compat_status_t zpool_do_load_compat(
130 const char *, boolean_t *);
133 * These libumem hooks provide a reasonable set of defaults for the allocator's
134 * debugging facilities.
137 #ifdef DEBUG
138 const char *
139 _umem_debug_init(void)
141 return ("default,verbose"); /* $UMEM_DEBUG setting */
144 const char *
145 _umem_logging_init(void)
147 return ("fail,contents"); /* $UMEM_LOGGING setting */
149 #endif
151 typedef enum {
152 HELP_ADD,
153 HELP_ATTACH,
154 HELP_CLEAR,
155 HELP_CREATE,
156 HELP_CHECKPOINT,
157 HELP_DESTROY,
158 HELP_DETACH,
159 HELP_EXPORT,
160 HELP_HISTORY,
161 HELP_IMPORT,
162 HELP_IOSTAT,
163 HELP_LABELCLEAR,
164 HELP_LIST,
165 HELP_OFFLINE,
166 HELP_ONLINE,
167 HELP_REPLACE,
168 HELP_REMOVE,
169 HELP_INITIALIZE,
170 HELP_SCRUB,
171 HELP_RESILVER,
172 HELP_TRIM,
173 HELP_STATUS,
174 HELP_UPGRADE,
175 HELP_EVENTS,
176 HELP_GET,
177 HELP_SET,
178 HELP_SPLIT,
179 HELP_SYNC,
180 HELP_REGUID,
181 HELP_REOPEN,
182 HELP_VERSION,
183 HELP_WAIT
184 } zpool_help_t;
188 * Flags for stats to display with "zpool iostats"
190 enum iostat_type {
191 IOS_DEFAULT = 0,
192 IOS_LATENCY = 1,
193 IOS_QUEUES = 2,
194 IOS_L_HISTO = 3,
195 IOS_RQ_HISTO = 4,
196 IOS_COUNT, /* always last element */
199 /* iostat_type entries as bitmasks */
200 #define IOS_DEFAULT_M (1ULL << IOS_DEFAULT)
201 #define IOS_LATENCY_M (1ULL << IOS_LATENCY)
202 #define IOS_QUEUES_M (1ULL << IOS_QUEUES)
203 #define IOS_L_HISTO_M (1ULL << IOS_L_HISTO)
204 #define IOS_RQ_HISTO_M (1ULL << IOS_RQ_HISTO)
206 /* Mask of all the histo bits */
207 #define IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
210 * Lookup table for iostat flags to nvlist names. Basically a list
211 * of all the nvlists a flag requires. Also specifies the order in
212 * which data gets printed in zpool iostat.
214 static const char *vsx_type_to_nvlist[IOS_COUNT][15] = {
215 [IOS_L_HISTO] = {
216 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
217 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
218 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
219 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
220 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
221 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
222 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
223 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
224 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
225 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
226 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
227 NULL},
228 [IOS_LATENCY] = {
229 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
230 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
231 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
232 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
233 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
234 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
235 NULL},
236 [IOS_QUEUES] = {
237 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
238 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
239 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
240 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
241 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
242 ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
243 ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
244 NULL},
245 [IOS_RQ_HISTO] = {
246 ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
247 ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
248 ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
249 ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
250 ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
251 ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
252 ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
253 ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
254 ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
255 ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
256 ZPOOL_CONFIG_VDEV_IND_TRIM_HISTO,
257 ZPOOL_CONFIG_VDEV_AGG_TRIM_HISTO,
258 ZPOOL_CONFIG_VDEV_IND_REBUILD_HISTO,
259 ZPOOL_CONFIG_VDEV_AGG_REBUILD_HISTO,
260 NULL},
265 * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
266 * Right now, only one histo bit is ever set at one time, so we can
267 * just do a highbit64(a)
269 #define IOS_HISTO_IDX(a) (highbit64(a & IOS_ANYHISTO_M) - 1)
271 typedef struct zpool_command {
272 const char *name;
273 int (*func)(int, char **);
274 zpool_help_t usage;
275 } zpool_command_t;
278 * Master command table. Each ZFS command has a name, associated function, and
279 * usage message. The usage messages need to be internationalized, so we have
280 * to have a function to return the usage message based on a command index.
282 * These commands are organized according to how they are displayed in the usage
283 * message. An empty command (one with a NULL name) indicates an empty line in
284 * the generic usage message.
286 static zpool_command_t command_table[] = {
287 { "version", zpool_do_version, HELP_VERSION },
288 { NULL },
289 { "create", zpool_do_create, HELP_CREATE },
290 { "destroy", zpool_do_destroy, HELP_DESTROY },
291 { NULL },
292 { "add", zpool_do_add, HELP_ADD },
293 { "remove", zpool_do_remove, HELP_REMOVE },
294 { NULL },
295 { "labelclear", zpool_do_labelclear, HELP_LABELCLEAR },
296 { NULL },
297 { "checkpoint", zpool_do_checkpoint, HELP_CHECKPOINT },
298 { NULL },
299 { "list", zpool_do_list, HELP_LIST },
300 { "iostat", zpool_do_iostat, HELP_IOSTAT },
301 { "status", zpool_do_status, HELP_STATUS },
302 { NULL },
303 { "online", zpool_do_online, HELP_ONLINE },
304 { "offline", zpool_do_offline, HELP_OFFLINE },
305 { "clear", zpool_do_clear, HELP_CLEAR },
306 { "reopen", zpool_do_reopen, HELP_REOPEN },
307 { NULL },
308 { "attach", zpool_do_attach, HELP_ATTACH },
309 { "detach", zpool_do_detach, HELP_DETACH },
310 { "replace", zpool_do_replace, HELP_REPLACE },
311 { "split", zpool_do_split, HELP_SPLIT },
312 { NULL },
313 { "initialize", zpool_do_initialize, HELP_INITIALIZE },
314 { "resilver", zpool_do_resilver, HELP_RESILVER },
315 { "scrub", zpool_do_scrub, HELP_SCRUB },
316 { "trim", zpool_do_trim, HELP_TRIM },
317 { NULL },
318 { "import", zpool_do_import, HELP_IMPORT },
319 { "export", zpool_do_export, HELP_EXPORT },
320 { "upgrade", zpool_do_upgrade, HELP_UPGRADE },
321 { "reguid", zpool_do_reguid, HELP_REGUID },
322 { NULL },
323 { "history", zpool_do_history, HELP_HISTORY },
324 { "events", zpool_do_events, HELP_EVENTS },
325 { NULL },
326 { "get", zpool_do_get, HELP_GET },
327 { "set", zpool_do_set, HELP_SET },
328 { "sync", zpool_do_sync, HELP_SYNC },
329 { NULL },
330 { "wait", zpool_do_wait, HELP_WAIT },
333 #define NCOMMAND (ARRAY_SIZE(command_table))
335 #define VDEV_ALLOC_CLASS_LOGS "logs"
337 static zpool_command_t *current_command;
338 static zfs_type_t current_prop_type = (ZFS_TYPE_POOL | ZFS_TYPE_VDEV);
339 static char history_str[HIS_MAX_RECORD_LEN];
340 static boolean_t log_history = B_TRUE;
341 static uint_t timestamp_fmt = NODATE;
343 static const char *
344 get_usage(zpool_help_t idx)
346 switch (idx) {
347 case HELP_ADD:
348 return (gettext("\tadd [-fgLnP] [-o property=value] "
349 "<pool> <vdev> ...\n"));
350 case HELP_ATTACH:
351 return (gettext("\tattach [-fsw] [-o property=value] "
352 "<pool> <device> <new-device>\n"));
353 case HELP_CLEAR:
354 return (gettext("\tclear [-nF] <pool> [device]\n"));
355 case HELP_CREATE:
356 return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
357 "\t [-O file-system-property=value] ... \n"
358 "\t [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
359 case HELP_CHECKPOINT:
360 return (gettext("\tcheckpoint [-d [-w]] <pool> ...\n"));
361 case HELP_DESTROY:
362 return (gettext("\tdestroy [-f] <pool>\n"));
363 case HELP_DETACH:
364 return (gettext("\tdetach <pool> <device>\n"));
365 case HELP_EXPORT:
366 return (gettext("\texport [-af] <pool> ...\n"));
367 case HELP_HISTORY:
368 return (gettext("\thistory [-il] [<pool>] ...\n"));
369 case HELP_IMPORT:
370 return (gettext("\timport [-d dir] [-D]\n"
371 "\timport [-o mntopts] [-o property=value] ... \n"
372 "\t [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
373 "[-R root] [-F [-n]] -a\n"
374 "\timport [-o mntopts] [-o property=value] ... \n"
375 "\t [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
376 "[-R root] [-F [-n]]\n"
377 "\t [--rewind-to-checkpoint] <pool | id> [newpool]\n"));
378 case HELP_IOSTAT:
379 return (gettext("\tiostat [[[-c [script1,script2,...]"
380 "[-lq]]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
381 "\t [[pool ...]|[pool vdev ...]|[vdev ...]]"
382 " [[-n] interval [count]]\n"));
383 case HELP_LABELCLEAR:
384 return (gettext("\tlabelclear [-f] <vdev>\n"));
385 case HELP_LIST:
386 return (gettext("\tlist [-gHLpPv] [-o property[,...]] "
387 "[-T d|u] [pool] ... \n"
388 "\t [interval [count]]\n"));
389 case HELP_OFFLINE:
390 return (gettext("\toffline [-f] [-t] <pool> <device> ...\n"));
391 case HELP_ONLINE:
392 return (gettext("\tonline [-e] <pool> <device> ...\n"));
393 case HELP_REPLACE:
394 return (gettext("\treplace [-fsw] [-o property=value] "
395 "<pool> <device> [new-device]\n"));
396 case HELP_REMOVE:
397 return (gettext("\tremove [-npsw] <pool> <device> ...\n"));
398 case HELP_REOPEN:
399 return (gettext("\treopen [-n] <pool>\n"));
400 case HELP_INITIALIZE:
401 return (gettext("\tinitialize [-c | -s] [-w] <pool> "
402 "[<device> ...]\n"));
403 case HELP_SCRUB:
404 return (gettext("\tscrub [-s | -p] [-w] <pool> ...\n"));
405 case HELP_RESILVER:
406 return (gettext("\tresilver <pool> ...\n"));
407 case HELP_TRIM:
408 return (gettext("\ttrim [-dw] [-r <rate>] [-c | -s] <pool> "
409 "[<device> ...]\n"));
410 case HELP_STATUS:
411 return (gettext("\tstatus [-c [script1,script2,...]] "
412 "[-igLpPstvxD] [-T d|u] [pool] ... \n"
413 "\t [interval [count]]\n"));
414 case HELP_UPGRADE:
415 return (gettext("\tupgrade\n"
416 "\tupgrade -v\n"
417 "\tupgrade [-V version] <-a | pool ...>\n"));
418 case HELP_EVENTS:
419 return (gettext("\tevents [-vHf [pool] | -c]\n"));
420 case HELP_GET:
421 return (gettext("\tget [-Hp] [-o \"all\" | field[,...]] "
422 "<\"all\" | property[,...]> <pool> ...\n"));
423 case HELP_SET:
424 return (gettext("\tset <property=value> <pool> \n"));
425 case HELP_SPLIT:
426 return (gettext("\tsplit [-gLnPl] [-R altroot] [-o mntopts]\n"
427 "\t [-o property=value] <pool> <newpool> "
428 "[<device> ...]\n"));
429 case HELP_REGUID:
430 return (gettext("\treguid <pool>\n"));
431 case HELP_SYNC:
432 return (gettext("\tsync [pool] ...\n"));
433 case HELP_VERSION:
434 return (gettext("\tversion\n"));
435 case HELP_WAIT:
436 return (gettext("\twait [-Hp] [-T d|u] [-t <activity>[,...]] "
437 "<pool> [interval]\n"));
438 default:
439 __builtin_unreachable();
443 static void
444 zpool_collect_leaves(zpool_handle_t *zhp, nvlist_t *nvroot, nvlist_t *res)
446 uint_t children = 0;
447 nvlist_t **child;
448 uint_t i;
450 (void) nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
451 &child, &children);
453 if (children == 0) {
454 char *path = zpool_vdev_name(g_zfs, zhp, nvroot,
455 VDEV_NAME_PATH);
457 if (strcmp(path, VDEV_TYPE_INDIRECT) != 0 &&
458 strcmp(path, VDEV_TYPE_HOLE) != 0)
459 fnvlist_add_boolean(res, path);
461 free(path);
462 return;
465 for (i = 0; i < children; i++) {
466 zpool_collect_leaves(zhp, child[i], res);
471 * Callback routine that will print out a pool property value.
473 static int
474 print_pool_prop_cb(int prop, void *cb)
476 FILE *fp = cb;
478 (void) fprintf(fp, "\t%-19s ", zpool_prop_to_name(prop));
480 if (zpool_prop_readonly(prop))
481 (void) fprintf(fp, " NO ");
482 else
483 (void) fprintf(fp, " YES ");
485 if (zpool_prop_values(prop) == NULL)
486 (void) fprintf(fp, "-\n");
487 else
488 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
490 return (ZPROP_CONT);
494 * Callback routine that will print out a vdev property value.
496 static int
497 print_vdev_prop_cb(int prop, void *cb)
499 FILE *fp = cb;
501 (void) fprintf(fp, "\t%-19s ", vdev_prop_to_name(prop));
503 if (vdev_prop_readonly(prop))
504 (void) fprintf(fp, " NO ");
505 else
506 (void) fprintf(fp, " YES ");
508 if (vdev_prop_values(prop) == NULL)
509 (void) fprintf(fp, "-\n");
510 else
511 (void) fprintf(fp, "%s\n", vdev_prop_values(prop));
513 return (ZPROP_CONT);
517 * Display usage message. If we're inside a command, display only the usage for
518 * that command. Otherwise, iterate over the entire command table and display
519 * a complete usage message.
521 static __attribute__((noreturn)) void
522 usage(boolean_t requested)
524 FILE *fp = requested ? stdout : stderr;
526 if (current_command == NULL) {
527 int i;
529 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
530 (void) fprintf(fp,
531 gettext("where 'command' is one of the following:\n\n"));
533 for (i = 0; i < NCOMMAND; i++) {
534 if (command_table[i].name == NULL)
535 (void) fprintf(fp, "\n");
536 else
537 (void) fprintf(fp, "%s",
538 get_usage(command_table[i].usage));
540 } else {
541 (void) fprintf(fp, gettext("usage:\n"));
542 (void) fprintf(fp, "%s", get_usage(current_command->usage));
545 if (current_command != NULL &&
546 current_prop_type != (ZFS_TYPE_POOL | ZFS_TYPE_VDEV) &&
547 ((strcmp(current_command->name, "set") == 0) ||
548 (strcmp(current_command->name, "get") == 0) ||
549 (strcmp(current_command->name, "list") == 0))) {
551 (void) fprintf(fp,
552 gettext("\nthe following properties are supported:\n"));
554 (void) fprintf(fp, "\n\t%-19s %s %s\n\n",
555 "PROPERTY", "EDIT", "VALUES");
557 /* Iterate over all properties */
558 if (current_prop_type == ZFS_TYPE_POOL) {
559 (void) zprop_iter(print_pool_prop_cb, fp, B_FALSE,
560 B_TRUE, current_prop_type);
562 (void) fprintf(fp, "\t%-19s ", "feature@...");
563 (void) fprintf(fp, "YES "
564 "disabled | enabled | active\n");
566 (void) fprintf(fp, gettext("\nThe feature@ properties "
567 "must be appended with a feature name.\n"
568 "See zpool-features(7).\n"));
569 } else if (current_prop_type == ZFS_TYPE_VDEV) {
570 (void) zprop_iter(print_vdev_prop_cb, fp, B_FALSE,
571 B_TRUE, current_prop_type);
576 * See comments at end of main().
578 if (getenv("ZFS_ABORT") != NULL) {
579 (void) printf("dumping core by request\n");
580 abort();
583 exit(requested ? 0 : 2);
587 * zpool initialize [-c | -s] [-w] <pool> [<vdev> ...]
588 * Initialize all unused blocks in the specified vdevs, or all vdevs in the pool
589 * if none specified.
591 * -c Cancel. Ends active initializing.
592 * -s Suspend. Initializing can then be restarted with no flags.
593 * -w Wait. Blocks until initializing has completed.
596 zpool_do_initialize(int argc, char **argv)
598 int c;
599 char *poolname;
600 zpool_handle_t *zhp;
601 nvlist_t *vdevs;
602 int err = 0;
603 boolean_t wait = B_FALSE;
605 struct option long_options[] = {
606 {"cancel", no_argument, NULL, 'c'},
607 {"suspend", no_argument, NULL, 's'},
608 {"wait", no_argument, NULL, 'w'},
609 {0, 0, 0, 0}
612 pool_initialize_func_t cmd_type = POOL_INITIALIZE_START;
613 while ((c = getopt_long(argc, argv, "csw", long_options, NULL)) != -1) {
614 switch (c) {
615 case 'c':
616 if (cmd_type != POOL_INITIALIZE_START &&
617 cmd_type != POOL_INITIALIZE_CANCEL) {
618 (void) fprintf(stderr, gettext("-c cannot be "
619 "combined with other options\n"));
620 usage(B_FALSE);
622 cmd_type = POOL_INITIALIZE_CANCEL;
623 break;
624 case 's':
625 if (cmd_type != POOL_INITIALIZE_START &&
626 cmd_type != POOL_INITIALIZE_SUSPEND) {
627 (void) fprintf(stderr, gettext("-s cannot be "
628 "combined with other options\n"));
629 usage(B_FALSE);
631 cmd_type = POOL_INITIALIZE_SUSPEND;
632 break;
633 case 'w':
634 wait = B_TRUE;
635 break;
636 case '?':
637 if (optopt != 0) {
638 (void) fprintf(stderr,
639 gettext("invalid option '%c'\n"), optopt);
640 } else {
641 (void) fprintf(stderr,
642 gettext("invalid option '%s'\n"),
643 argv[optind - 1]);
645 usage(B_FALSE);
649 argc -= optind;
650 argv += optind;
652 if (argc < 1) {
653 (void) fprintf(stderr, gettext("missing pool name argument\n"));
654 usage(B_FALSE);
655 return (-1);
658 if (wait && (cmd_type != POOL_INITIALIZE_START)) {
659 (void) fprintf(stderr, gettext("-w cannot be used with -c or "
660 "-s\n"));
661 usage(B_FALSE);
664 poolname = argv[0];
665 zhp = zpool_open(g_zfs, poolname);
666 if (zhp == NULL)
667 return (-1);
669 vdevs = fnvlist_alloc();
670 if (argc == 1) {
671 /* no individual leaf vdevs specified, so add them all */
672 nvlist_t *config = zpool_get_config(zhp, NULL);
673 nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
674 ZPOOL_CONFIG_VDEV_TREE);
675 zpool_collect_leaves(zhp, nvroot, vdevs);
676 } else {
677 for (int i = 1; i < argc; i++) {
678 fnvlist_add_boolean(vdevs, argv[i]);
682 if (wait)
683 err = zpool_initialize_wait(zhp, cmd_type, vdevs);
684 else
685 err = zpool_initialize(zhp, cmd_type, vdevs);
687 fnvlist_free(vdevs);
688 zpool_close(zhp);
690 return (err);
694 * print a pool vdev config for dry runs
696 static void
697 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
698 const char *match, int name_flags)
700 nvlist_t **child;
701 uint_t c, children;
702 char *vname;
703 boolean_t printed = B_FALSE;
705 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
706 &child, &children) != 0) {
707 if (name != NULL)
708 (void) printf("\t%*s%s\n", indent, "", name);
709 return;
712 for (c = 0; c < children; c++) {
713 uint64_t is_log = B_FALSE, is_hole = B_FALSE;
714 char *class = (char *)"";
716 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
717 &is_hole);
719 if (is_hole == B_TRUE) {
720 continue;
723 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
724 &is_log);
725 if (is_log)
726 class = (char *)VDEV_ALLOC_BIAS_LOG;
727 (void) nvlist_lookup_string(child[c],
728 ZPOOL_CONFIG_ALLOCATION_BIAS, &class);
729 if (strcmp(match, class) != 0)
730 continue;
732 if (!printed && name != NULL) {
733 (void) printf("\t%*s%s\n", indent, "", name);
734 printed = B_TRUE;
736 vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
737 print_vdev_tree(zhp, vname, child[c], indent + 2, "",
738 name_flags);
739 free(vname);
744 * Print the list of l2cache devices for dry runs.
746 static void
747 print_cache_list(nvlist_t *nv, int indent)
749 nvlist_t **child;
750 uint_t c, children;
752 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
753 &child, &children) == 0 && children > 0) {
754 (void) printf("\t%*s%s\n", indent, "", "cache");
755 } else {
756 return;
758 for (c = 0; c < children; c++) {
759 char *vname;
761 vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
762 (void) printf("\t%*s%s\n", indent + 2, "", vname);
763 free(vname);
768 * Print the list of spares for dry runs.
770 static void
771 print_spare_list(nvlist_t *nv, int indent)
773 nvlist_t **child;
774 uint_t c, children;
776 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
777 &child, &children) == 0 && children > 0) {
778 (void) printf("\t%*s%s\n", indent, "", "spares");
779 } else {
780 return;
782 for (c = 0; c < children; c++) {
783 char *vname;
785 vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
786 (void) printf("\t%*s%s\n", indent + 2, "", vname);
787 free(vname);
791 static boolean_t
792 prop_list_contains_feature(nvlist_t *proplist)
794 nvpair_t *nvp;
795 for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
796 nvp = nvlist_next_nvpair(proplist, nvp)) {
797 if (zpool_prop_feature(nvpair_name(nvp)))
798 return (B_TRUE);
800 return (B_FALSE);
804 * Add a property pair (name, string-value) into a property nvlist.
806 static int
807 add_prop_list(const char *propname, const char *propval, nvlist_t **props,
808 boolean_t poolprop)
810 zpool_prop_t prop = ZPOOL_PROP_INVAL;
811 nvlist_t *proplist;
812 const char *normnm;
813 char *strval;
815 if (*props == NULL &&
816 nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
817 (void) fprintf(stderr,
818 gettext("internal error: out of memory\n"));
819 return (1);
822 proplist = *props;
824 if (poolprop) {
825 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
826 const char *cname =
827 zpool_prop_to_name(ZPOOL_PROP_COMPATIBILITY);
829 if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
830 (!zpool_prop_feature(propname) &&
831 !zpool_prop_vdev(propname))) {
832 (void) fprintf(stderr, gettext("property '%s' is "
833 "not a valid pool or vdev property\n"), propname);
834 return (2);
838 * feature@ properties and version should not be specified
839 * at the same time.
841 if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
842 nvlist_exists(proplist, vname)) ||
843 (prop == ZPOOL_PROP_VERSION &&
844 prop_list_contains_feature(proplist))) {
845 (void) fprintf(stderr, gettext("'feature@' and "
846 "'version' properties cannot be specified "
847 "together\n"));
848 return (2);
852 * if version is specified, only "legacy" compatibility
853 * may be requested
855 if ((prop == ZPOOL_PROP_COMPATIBILITY &&
856 strcmp(propval, ZPOOL_COMPAT_LEGACY) != 0 &&
857 nvlist_exists(proplist, vname)) ||
858 (prop == ZPOOL_PROP_VERSION &&
859 nvlist_exists(proplist, cname) &&
860 strcmp(fnvlist_lookup_string(proplist, cname),
861 ZPOOL_COMPAT_LEGACY) != 0)) {
862 (void) fprintf(stderr, gettext("when 'version' is "
863 "specified, the 'compatibility' feature may only "
864 "be set to '" ZPOOL_COMPAT_LEGACY "'\n"));
865 return (2);
868 if (zpool_prop_feature(propname) || zpool_prop_vdev(propname))
869 normnm = propname;
870 else
871 normnm = zpool_prop_to_name(prop);
872 } else {
873 zfs_prop_t fsprop = zfs_name_to_prop(propname);
875 if (zfs_prop_valid_for_type(fsprop, ZFS_TYPE_FILESYSTEM,
876 B_FALSE)) {
877 normnm = zfs_prop_to_name(fsprop);
878 } else if (zfs_prop_user(propname) ||
879 zfs_prop_userquota(propname)) {
880 normnm = propname;
881 } else {
882 (void) fprintf(stderr, gettext("property '%s' is "
883 "not a valid filesystem property\n"), propname);
884 return (2);
888 if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
889 prop != ZPOOL_PROP_CACHEFILE) {
890 (void) fprintf(stderr, gettext("property '%s' "
891 "specified multiple times\n"), propname);
892 return (2);
895 if (nvlist_add_string(proplist, normnm, propval) != 0) {
896 (void) fprintf(stderr, gettext("internal "
897 "error: out of memory\n"));
898 return (1);
901 return (0);
905 * Set a default property pair (name, string-value) in a property nvlist
907 static int
908 add_prop_list_default(const char *propname, const char *propval,
909 nvlist_t **props)
911 char *pval;
913 if (nvlist_lookup_string(*props, propname, &pval) == 0)
914 return (0);
916 return (add_prop_list(propname, propval, props, B_TRUE));
920 * zpool add [-fgLnP] [-o property=value] <pool> <vdev> ...
922 * -f Force addition of devices, even if they appear in use
923 * -g Display guid for individual vdev name.
924 * -L Follow links when resolving vdev path name.
925 * -n Do not add the devices, but display the resulting layout if
926 * they were to be added.
927 * -o Set property=value.
928 * -P Display full path for vdev name.
930 * Adds the given vdevs to 'pool'. As with create, the bulk of this work is
931 * handled by make_root_vdev(), which constructs the nvlist needed to pass to
932 * libzfs.
935 zpool_do_add(int argc, char **argv)
937 boolean_t force = B_FALSE;
938 boolean_t dryrun = B_FALSE;
939 int name_flags = 0;
940 int c;
941 nvlist_t *nvroot;
942 char *poolname;
943 int ret;
944 zpool_handle_t *zhp;
945 nvlist_t *config;
946 nvlist_t *props = NULL;
947 char *propval;
949 /* check options */
950 while ((c = getopt(argc, argv, "fgLno:P")) != -1) {
951 switch (c) {
952 case 'f':
953 force = B_TRUE;
954 break;
955 case 'g':
956 name_flags |= VDEV_NAME_GUID;
957 break;
958 case 'L':
959 name_flags |= VDEV_NAME_FOLLOW_LINKS;
960 break;
961 case 'n':
962 dryrun = B_TRUE;
963 break;
964 case 'o':
965 if ((propval = strchr(optarg, '=')) == NULL) {
966 (void) fprintf(stderr, gettext("missing "
967 "'=' for -o option\n"));
968 usage(B_FALSE);
970 *propval = '\0';
971 propval++;
973 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
974 (add_prop_list(optarg, propval, &props, B_TRUE)))
975 usage(B_FALSE);
976 break;
977 case 'P':
978 name_flags |= VDEV_NAME_PATH;
979 break;
980 case '?':
981 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
982 optopt);
983 usage(B_FALSE);
987 argc -= optind;
988 argv += optind;
990 /* get pool name and check number of arguments */
991 if (argc < 1) {
992 (void) fprintf(stderr, gettext("missing pool name argument\n"));
993 usage(B_FALSE);
995 if (argc < 2) {
996 (void) fprintf(stderr, gettext("missing vdev specification\n"));
997 usage(B_FALSE);
1000 poolname = argv[0];
1002 argc--;
1003 argv++;
1005 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1006 return (1);
1008 if ((config = zpool_get_config(zhp, NULL)) == NULL) {
1009 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
1010 poolname);
1011 zpool_close(zhp);
1012 return (1);
1015 /* unless manually specified use "ashift" pool property (if set) */
1016 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
1017 int intval;
1018 zprop_source_t src;
1019 char strval[ZPOOL_MAXPROPLEN];
1021 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
1022 if (src != ZPROP_SRC_DEFAULT) {
1023 (void) sprintf(strval, "%" PRId32, intval);
1024 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
1025 &props, B_TRUE) == 0);
1029 /* pass off to make_root_vdev for processing */
1030 nvroot = make_root_vdev(zhp, props, force, !force, B_FALSE, dryrun,
1031 argc, argv);
1032 if (nvroot == NULL) {
1033 zpool_close(zhp);
1034 return (1);
1037 if (dryrun) {
1038 nvlist_t *poolnvroot;
1039 nvlist_t **l2child, **sparechild;
1040 uint_t l2children, sparechildren, c;
1041 char *vname;
1042 boolean_t hadcache = B_FALSE, hadspare = B_FALSE;
1044 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1045 &poolnvroot) == 0);
1047 (void) printf(gettext("would update '%s' to the following "
1048 "configuration:\n\n"), zpool_get_name(zhp));
1050 /* print original main pool and new tree */
1051 print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
1052 name_flags | VDEV_NAME_TYPE_ID);
1053 print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
1055 /* print other classes: 'dedup', 'special', and 'log' */
1056 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1057 print_vdev_tree(zhp, "dedup", poolnvroot, 0,
1058 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1059 print_vdev_tree(zhp, NULL, nvroot, 0,
1060 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1061 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1062 print_vdev_tree(zhp, "dedup", nvroot, 0,
1063 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1066 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1067 print_vdev_tree(zhp, "special", poolnvroot, 0,
1068 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1069 print_vdev_tree(zhp, NULL, nvroot, 0,
1070 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1071 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1072 print_vdev_tree(zhp, "special", nvroot, 0,
1073 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1076 if (num_logs(poolnvroot) > 0) {
1077 print_vdev_tree(zhp, "logs", poolnvroot, 0,
1078 VDEV_ALLOC_BIAS_LOG, name_flags);
1079 print_vdev_tree(zhp, NULL, nvroot, 0,
1080 VDEV_ALLOC_BIAS_LOG, name_flags);
1081 } else if (num_logs(nvroot) > 0) {
1082 print_vdev_tree(zhp, "logs", nvroot, 0,
1083 VDEV_ALLOC_BIAS_LOG, name_flags);
1086 /* Do the same for the caches */
1087 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
1088 &l2child, &l2children) == 0 && l2children) {
1089 hadcache = B_TRUE;
1090 (void) printf(gettext("\tcache\n"));
1091 for (c = 0; c < l2children; c++) {
1092 vname = zpool_vdev_name(g_zfs, NULL,
1093 l2child[c], name_flags);
1094 (void) printf("\t %s\n", vname);
1095 free(vname);
1098 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1099 &l2child, &l2children) == 0 && l2children) {
1100 if (!hadcache)
1101 (void) printf(gettext("\tcache\n"));
1102 for (c = 0; c < l2children; c++) {
1103 vname = zpool_vdev_name(g_zfs, NULL,
1104 l2child[c], name_flags);
1105 (void) printf("\t %s\n", vname);
1106 free(vname);
1109 /* And finally the spares */
1110 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_SPARES,
1111 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1112 hadspare = B_TRUE;
1113 (void) printf(gettext("\tspares\n"));
1114 for (c = 0; c < sparechildren; c++) {
1115 vname = zpool_vdev_name(g_zfs, NULL,
1116 sparechild[c], name_flags);
1117 (void) printf("\t %s\n", vname);
1118 free(vname);
1121 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1122 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1123 if (!hadspare)
1124 (void) printf(gettext("\tspares\n"));
1125 for (c = 0; c < sparechildren; c++) {
1126 vname = zpool_vdev_name(g_zfs, NULL,
1127 sparechild[c], name_flags);
1128 (void) printf("\t %s\n", vname);
1129 free(vname);
1133 ret = 0;
1134 } else {
1135 ret = (zpool_add(zhp, nvroot) != 0);
1138 nvlist_free(props);
1139 nvlist_free(nvroot);
1140 zpool_close(zhp);
1142 return (ret);
1146 * zpool remove [-npsw] <pool> <vdev> ...
1148 * Removes the given vdev from the pool.
1151 zpool_do_remove(int argc, char **argv)
1153 char *poolname;
1154 int i, ret = 0;
1155 zpool_handle_t *zhp = NULL;
1156 boolean_t stop = B_FALSE;
1157 int c;
1158 boolean_t noop = B_FALSE;
1159 boolean_t parsable = B_FALSE;
1160 boolean_t wait = B_FALSE;
1162 /* check options */
1163 while ((c = getopt(argc, argv, "npsw")) != -1) {
1164 switch (c) {
1165 case 'n':
1166 noop = B_TRUE;
1167 break;
1168 case 'p':
1169 parsable = B_TRUE;
1170 break;
1171 case 's':
1172 stop = B_TRUE;
1173 break;
1174 case 'w':
1175 wait = B_TRUE;
1176 break;
1177 case '?':
1178 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1179 optopt);
1180 usage(B_FALSE);
1184 argc -= optind;
1185 argv += optind;
1187 /* get pool name and check number of arguments */
1188 if (argc < 1) {
1189 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1190 usage(B_FALSE);
1193 poolname = argv[0];
1195 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1196 return (1);
1198 if (stop && noop) {
1199 (void) fprintf(stderr, gettext("stop request ignored\n"));
1200 return (0);
1203 if (stop) {
1204 if (argc > 1) {
1205 (void) fprintf(stderr, gettext("too many arguments\n"));
1206 usage(B_FALSE);
1208 if (zpool_vdev_remove_cancel(zhp) != 0)
1209 ret = 1;
1210 if (wait) {
1211 (void) fprintf(stderr, gettext("invalid option "
1212 "combination: -w cannot be used with -s\n"));
1213 usage(B_FALSE);
1215 } else {
1216 if (argc < 2) {
1217 (void) fprintf(stderr, gettext("missing device\n"));
1218 usage(B_FALSE);
1221 for (i = 1; i < argc; i++) {
1222 if (noop) {
1223 uint64_t size;
1225 if (zpool_vdev_indirect_size(zhp, argv[i],
1226 &size) != 0) {
1227 ret = 1;
1228 break;
1230 if (parsable) {
1231 (void) printf("%s %llu\n",
1232 argv[i], (unsigned long long)size);
1233 } else {
1234 char valstr[32];
1235 zfs_nicenum(size, valstr,
1236 sizeof (valstr));
1237 (void) printf("Memory that will be "
1238 "used after removing %s: %s\n",
1239 argv[i], valstr);
1241 } else {
1242 if (zpool_vdev_remove(zhp, argv[i]) != 0)
1243 ret = 1;
1247 if (ret == 0 && wait)
1248 ret = zpool_wait(zhp, ZPOOL_WAIT_REMOVE);
1250 zpool_close(zhp);
1252 return (ret);
1256 * Return 1 if a vdev is active (being used in a pool)
1257 * Return 0 if a vdev is inactive (offlined or faulted, or not in active pool)
1259 * This is useful for checking if a disk in an active pool is offlined or
1260 * faulted.
1262 static int
1263 vdev_is_active(char *vdev_path)
1265 int fd;
1266 fd = open(vdev_path, O_EXCL);
1267 if (fd < 0) {
1268 return (1); /* cant open O_EXCL - disk is active */
1271 close(fd);
1272 return (0); /* disk is inactive in the pool */
1276 * zpool labelclear [-f] <vdev>
1278 * -f Force clearing the label for the vdevs which are members of
1279 * the exported or foreign pools.
1281 * Verifies that the vdev is not active and zeros out the label information
1282 * on the device.
1285 zpool_do_labelclear(int argc, char **argv)
1287 char vdev[MAXPATHLEN];
1288 char *name = NULL;
1289 struct stat st;
1290 int c, fd = -1, ret = 0;
1291 nvlist_t *config;
1292 pool_state_t state;
1293 boolean_t inuse = B_FALSE;
1294 boolean_t force = B_FALSE;
1296 /* check options */
1297 while ((c = getopt(argc, argv, "f")) != -1) {
1298 switch (c) {
1299 case 'f':
1300 force = B_TRUE;
1301 break;
1302 default:
1303 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1304 optopt);
1305 usage(B_FALSE);
1309 argc -= optind;
1310 argv += optind;
1312 /* get vdev name */
1313 if (argc < 1) {
1314 (void) fprintf(stderr, gettext("missing vdev name\n"));
1315 usage(B_FALSE);
1317 if (argc > 1) {
1318 (void) fprintf(stderr, gettext("too many arguments\n"));
1319 usage(B_FALSE);
1323 * Check if we were given absolute path and use it as is.
1324 * Otherwise if the provided vdev name doesn't point to a file,
1325 * try prepending expected disk paths and partition numbers.
1327 (void) strlcpy(vdev, argv[0], sizeof (vdev));
1328 if (vdev[0] != '/' && stat(vdev, &st) != 0) {
1329 int error;
1331 error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
1332 if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
1333 if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
1334 error = ENOENT;
1337 if (error || (stat(vdev, &st) != 0)) {
1338 (void) fprintf(stderr, gettext(
1339 "failed to find device %s, try specifying absolute "
1340 "path instead\n"), argv[0]);
1341 return (1);
1345 if ((fd = open(vdev, O_RDWR)) < 0) {
1346 (void) fprintf(stderr, gettext("failed to open %s: %s\n"),
1347 vdev, strerror(errno));
1348 return (1);
1352 * Flush all dirty pages for the block device. This should not be
1353 * fatal when the device does not support BLKFLSBUF as would be the
1354 * case for a file vdev.
1356 if ((zfs_dev_flush(fd) != 0) && (errno != ENOTTY))
1357 (void) fprintf(stderr, gettext("failed to invalidate "
1358 "cache for %s: %s\n"), vdev, strerror(errno));
1360 if (zpool_read_label(fd, &config, NULL) != 0) {
1361 (void) fprintf(stderr,
1362 gettext("failed to read label from %s\n"), vdev);
1363 ret = 1;
1364 goto errout;
1366 nvlist_free(config);
1368 ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1369 if (ret != 0) {
1370 (void) fprintf(stderr,
1371 gettext("failed to check state for %s\n"), vdev);
1372 ret = 1;
1373 goto errout;
1376 if (!inuse)
1377 goto wipe_label;
1379 switch (state) {
1380 default:
1381 case POOL_STATE_ACTIVE:
1382 case POOL_STATE_SPARE:
1383 case POOL_STATE_L2CACHE:
1385 * We allow the user to call 'zpool offline -f'
1386 * on an offlined disk in an active pool. We can check if
1387 * the disk is online by calling vdev_is_active().
1389 if (force && !vdev_is_active(vdev))
1390 break;
1392 (void) fprintf(stderr, gettext(
1393 "%s is a member (%s) of pool \"%s\""),
1394 vdev, zpool_pool_state_to_name(state), name);
1396 if (force) {
1397 (void) fprintf(stderr, gettext(
1398 ". Offline the disk first to clear its label."));
1400 printf("\n");
1401 ret = 1;
1402 goto errout;
1404 case POOL_STATE_EXPORTED:
1405 if (force)
1406 break;
1407 (void) fprintf(stderr, gettext(
1408 "use '-f' to override the following error:\n"
1409 "%s is a member of exported pool \"%s\"\n"),
1410 vdev, name);
1411 ret = 1;
1412 goto errout;
1414 case POOL_STATE_POTENTIALLY_ACTIVE:
1415 if (force)
1416 break;
1417 (void) fprintf(stderr, gettext(
1418 "use '-f' to override the following error:\n"
1419 "%s is a member of potentially active pool \"%s\"\n"),
1420 vdev, name);
1421 ret = 1;
1422 goto errout;
1424 case POOL_STATE_DESTROYED:
1425 /* inuse should never be set for a destroyed pool */
1426 assert(0);
1427 break;
1430 wipe_label:
1431 ret = zpool_clear_label(fd);
1432 if (ret != 0) {
1433 (void) fprintf(stderr,
1434 gettext("failed to clear label for %s\n"), vdev);
1437 errout:
1438 free(name);
1439 (void) close(fd);
1441 return (ret);
1445 * zpool create [-fnd] [-o property=value] ...
1446 * [-O file-system-property=value] ...
1447 * [-R root] [-m mountpoint] <pool> <dev> ...
1449 * -f Force creation, even if devices appear in use
1450 * -n Do not create the pool, but display the resulting layout if it
1451 * were to be created.
1452 * -R Create a pool under an alternate root
1453 * -m Set default mountpoint for the root dataset. By default it's
1454 * '/<pool>'
1455 * -o Set property=value.
1456 * -o Set feature@feature=enabled|disabled.
1457 * -d Don't automatically enable all supported pool features
1458 * (individual features can be enabled with -o).
1459 * -O Set fsproperty=value in the pool's root file system
1461 * Creates the named pool according to the given vdev specification. The
1462 * bulk of the vdev processing is done in make_root_vdev() in zpool_vdev.c.
1463 * Once we get the nvlist back from make_root_vdev(), we either print out the
1464 * contents (if '-n' was specified), or pass it to libzfs to do the creation.
1467 zpool_do_create(int argc, char **argv)
1469 boolean_t force = B_FALSE;
1470 boolean_t dryrun = B_FALSE;
1471 boolean_t enable_pool_features = B_TRUE;
1473 int c;
1474 nvlist_t *nvroot = NULL;
1475 char *poolname;
1476 char *tname = NULL;
1477 int ret = 1;
1478 char *altroot = NULL;
1479 char *compat = NULL;
1480 char *mountpoint = NULL;
1481 nvlist_t *fsprops = NULL;
1482 nvlist_t *props = NULL;
1483 char *propval;
1485 /* check options */
1486 while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
1487 switch (c) {
1488 case 'f':
1489 force = B_TRUE;
1490 break;
1491 case 'n':
1492 dryrun = B_TRUE;
1493 break;
1494 case 'd':
1495 enable_pool_features = B_FALSE;
1496 break;
1497 case 'R':
1498 altroot = optarg;
1499 if (add_prop_list(zpool_prop_to_name(
1500 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
1501 goto errout;
1502 if (add_prop_list_default(zpool_prop_to_name(
1503 ZPOOL_PROP_CACHEFILE), "none", &props))
1504 goto errout;
1505 break;
1506 case 'm':
1507 /* Equivalent to -O mountpoint=optarg */
1508 mountpoint = optarg;
1509 break;
1510 case 'o':
1511 if ((propval = strchr(optarg, '=')) == NULL) {
1512 (void) fprintf(stderr, gettext("missing "
1513 "'=' for -o option\n"));
1514 goto errout;
1516 *propval = '\0';
1517 propval++;
1519 if (add_prop_list(optarg, propval, &props, B_TRUE))
1520 goto errout;
1523 * If the user is creating a pool that doesn't support
1524 * feature flags, don't enable any features.
1526 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
1527 char *end;
1528 u_longlong_t ver;
1530 ver = strtoull(propval, &end, 10);
1531 if (*end == '\0' &&
1532 ver < SPA_VERSION_FEATURES) {
1533 enable_pool_features = B_FALSE;
1536 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
1537 altroot = propval;
1538 if (zpool_name_to_prop(optarg) ==
1539 ZPOOL_PROP_COMPATIBILITY)
1540 compat = propval;
1541 break;
1542 case 'O':
1543 if ((propval = strchr(optarg, '=')) == NULL) {
1544 (void) fprintf(stderr, gettext("missing "
1545 "'=' for -O option\n"));
1546 goto errout;
1548 *propval = '\0';
1549 propval++;
1552 * Mountpoints are checked and then added later.
1553 * Uniquely among properties, they can be specified
1554 * more than once, to avoid conflict with -m.
1556 if (0 == strcmp(optarg,
1557 zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
1558 mountpoint = propval;
1559 } else if (add_prop_list(optarg, propval, &fsprops,
1560 B_FALSE)) {
1561 goto errout;
1563 break;
1564 case 't':
1566 * Sanity check temporary pool name.
1568 if (strchr(optarg, '/') != NULL) {
1569 (void) fprintf(stderr, gettext("cannot create "
1570 "'%s': invalid character '/' in temporary "
1571 "name\n"), optarg);
1572 (void) fprintf(stderr, gettext("use 'zfs "
1573 "create' to create a dataset\n"));
1574 goto errout;
1577 if (add_prop_list(zpool_prop_to_name(
1578 ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
1579 goto errout;
1580 if (add_prop_list_default(zpool_prop_to_name(
1581 ZPOOL_PROP_CACHEFILE), "none", &props))
1582 goto errout;
1583 tname = optarg;
1584 break;
1585 case ':':
1586 (void) fprintf(stderr, gettext("missing argument for "
1587 "'%c' option\n"), optopt);
1588 goto badusage;
1589 case '?':
1590 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1591 optopt);
1592 goto badusage;
1596 argc -= optind;
1597 argv += optind;
1599 /* get pool name and check number of arguments */
1600 if (argc < 1) {
1601 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1602 goto badusage;
1604 if (argc < 2) {
1605 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1606 goto badusage;
1609 poolname = argv[0];
1612 * As a special case, check for use of '/' in the name, and direct the
1613 * user to use 'zfs create' instead.
1615 if (strchr(poolname, '/') != NULL) {
1616 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
1617 "character '/' in pool name\n"), poolname);
1618 (void) fprintf(stderr, gettext("use 'zfs create' to "
1619 "create a dataset\n"));
1620 goto errout;
1623 /* pass off to make_root_vdev for bulk processing */
1624 nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
1625 argc - 1, argv + 1);
1626 if (nvroot == NULL)
1627 goto errout;
1629 /* make_root_vdev() allows 0 toplevel children if there are spares */
1630 if (!zfs_allocatable_devs(nvroot)) {
1631 (void) fprintf(stderr, gettext("invalid vdev "
1632 "specification: at least one toplevel vdev must be "
1633 "specified\n"));
1634 goto errout;
1637 if (altroot != NULL && altroot[0] != '/') {
1638 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
1639 "must be an absolute path\n"), altroot);
1640 goto errout;
1644 * Check the validity of the mountpoint and direct the user to use the
1645 * '-m' mountpoint option if it looks like its in use.
1647 if (mountpoint == NULL ||
1648 (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
1649 strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
1650 char buf[MAXPATHLEN];
1651 DIR *dirp;
1653 if (mountpoint && mountpoint[0] != '/') {
1654 (void) fprintf(stderr, gettext("invalid mountpoint "
1655 "'%s': must be an absolute path, 'legacy', or "
1656 "'none'\n"), mountpoint);
1657 goto errout;
1660 if (mountpoint == NULL) {
1661 if (altroot != NULL)
1662 (void) snprintf(buf, sizeof (buf), "%s/%s",
1663 altroot, poolname);
1664 else
1665 (void) snprintf(buf, sizeof (buf), "/%s",
1666 poolname);
1667 } else {
1668 if (altroot != NULL)
1669 (void) snprintf(buf, sizeof (buf), "%s%s",
1670 altroot, mountpoint);
1671 else
1672 (void) snprintf(buf, sizeof (buf), "%s",
1673 mountpoint);
1676 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
1677 (void) fprintf(stderr, gettext("mountpoint '%s' : "
1678 "%s\n"), buf, strerror(errno));
1679 (void) fprintf(stderr, gettext("use '-m' "
1680 "option to provide a different default\n"));
1681 goto errout;
1682 } else if (dirp) {
1683 int count = 0;
1685 while (count < 3 && readdir(dirp) != NULL)
1686 count++;
1687 (void) closedir(dirp);
1689 if (count > 2) {
1690 (void) fprintf(stderr, gettext("mountpoint "
1691 "'%s' exists and is not empty\n"), buf);
1692 (void) fprintf(stderr, gettext("use '-m' "
1693 "option to provide a "
1694 "different default\n"));
1695 goto errout;
1701 * Now that the mountpoint's validity has been checked, ensure that
1702 * the property is set appropriately prior to creating the pool.
1704 if (mountpoint != NULL) {
1705 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
1706 mountpoint, &fsprops, B_FALSE);
1707 if (ret != 0)
1708 goto errout;
1711 ret = 1;
1712 if (dryrun) {
1714 * For a dry run invocation, print out a basic message and run
1715 * through all the vdevs in the list and print out in an
1716 * appropriate hierarchy.
1718 (void) printf(gettext("would create '%s' with the "
1719 "following layout:\n\n"), poolname);
1721 print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
1722 print_vdev_tree(NULL, "dedup", nvroot, 0,
1723 VDEV_ALLOC_BIAS_DEDUP, 0);
1724 print_vdev_tree(NULL, "special", nvroot, 0,
1725 VDEV_ALLOC_BIAS_SPECIAL, 0);
1726 print_vdev_tree(NULL, "logs", nvroot, 0,
1727 VDEV_ALLOC_BIAS_LOG, 0);
1728 print_cache_list(nvroot, 0);
1729 print_spare_list(nvroot, 0);
1731 ret = 0;
1732 } else {
1734 * Load in feature set.
1735 * Note: if compatibility property not given, we'll have
1736 * NULL, which means 'all features'.
1738 boolean_t requested_features[SPA_FEATURES];
1739 if (zpool_do_load_compat(compat, requested_features) !=
1740 ZPOOL_COMPATIBILITY_OK)
1741 goto errout;
1744 * props contains list of features to enable.
1745 * For each feature:
1746 * - remove it if feature@name=disabled
1747 * - leave it there if feature@name=enabled
1748 * - add it if:
1749 * - enable_pool_features (ie: no '-d' or '-o version')
1750 * - it's supported by the kernel module
1751 * - it's in the requested feature set
1752 * - warn if it's enabled but not in compat
1754 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
1755 char propname[MAXPATHLEN];
1756 char *propval;
1757 zfeature_info_t *feat = &spa_feature_table[i];
1759 (void) snprintf(propname, sizeof (propname),
1760 "feature@%s", feat->fi_uname);
1762 if (!nvlist_lookup_string(props, propname, &propval)) {
1763 if (strcmp(propval,
1764 ZFS_FEATURE_DISABLED) == 0) {
1765 (void) nvlist_remove_all(props,
1766 propname);
1767 } else if (strcmp(propval,
1768 ZFS_FEATURE_ENABLED) == 0 &&
1769 !requested_features[i]) {
1770 (void) fprintf(stderr, gettext(
1771 "Warning: feature \"%s\" enabled "
1772 "but is not in specified "
1773 "'compatibility' feature set.\n"),
1774 feat->fi_uname);
1776 } else if (
1777 enable_pool_features &&
1778 feat->fi_zfs_mod_supported &&
1779 requested_features[i]) {
1780 ret = add_prop_list(propname,
1781 ZFS_FEATURE_ENABLED, &props, B_TRUE);
1782 if (ret != 0)
1783 goto errout;
1787 ret = 1;
1788 if (zpool_create(g_zfs, poolname,
1789 nvroot, props, fsprops) == 0) {
1790 zfs_handle_t *pool = zfs_open(g_zfs,
1791 tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
1792 if (pool != NULL) {
1793 if (zfs_mount(pool, NULL, 0) == 0) {
1794 ret = zfs_share(pool, NULL);
1795 zfs_commit_shares(NULL);
1797 zfs_close(pool);
1799 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
1800 (void) fprintf(stderr, gettext("pool name may have "
1801 "been omitted\n"));
1805 errout:
1806 nvlist_free(nvroot);
1807 nvlist_free(fsprops);
1808 nvlist_free(props);
1809 return (ret);
1810 badusage:
1811 nvlist_free(fsprops);
1812 nvlist_free(props);
1813 usage(B_FALSE);
1814 return (2);
1818 * zpool destroy <pool>
1820 * -f Forcefully unmount any datasets
1822 * Destroy the given pool. Automatically unmounts any datasets in the pool.
1825 zpool_do_destroy(int argc, char **argv)
1827 boolean_t force = B_FALSE;
1828 int c;
1829 char *pool;
1830 zpool_handle_t *zhp;
1831 int ret;
1833 /* check options */
1834 while ((c = getopt(argc, argv, "f")) != -1) {
1835 switch (c) {
1836 case 'f':
1837 force = B_TRUE;
1838 break;
1839 case '?':
1840 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1841 optopt);
1842 usage(B_FALSE);
1846 argc -= optind;
1847 argv += optind;
1849 /* check arguments */
1850 if (argc < 1) {
1851 (void) fprintf(stderr, gettext("missing pool argument\n"));
1852 usage(B_FALSE);
1854 if (argc > 1) {
1855 (void) fprintf(stderr, gettext("too many arguments\n"));
1856 usage(B_FALSE);
1859 pool = argv[0];
1861 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
1863 * As a special case, check for use of '/' in the name, and
1864 * direct the user to use 'zfs destroy' instead.
1866 if (strchr(pool, '/') != NULL)
1867 (void) fprintf(stderr, gettext("use 'zfs destroy' to "
1868 "destroy a dataset\n"));
1869 return (1);
1872 if (zpool_disable_datasets(zhp, force) != 0) {
1873 (void) fprintf(stderr, gettext("could not destroy '%s': "
1874 "could not unmount datasets\n"), zpool_get_name(zhp));
1875 zpool_close(zhp);
1876 return (1);
1879 /* The history must be logged as part of the export */
1880 log_history = B_FALSE;
1882 ret = (zpool_destroy(zhp, history_str) != 0);
1884 zpool_close(zhp);
1886 return (ret);
1889 typedef struct export_cbdata {
1890 boolean_t force;
1891 boolean_t hardforce;
1892 } export_cbdata_t;
1895 * Export one pool
1897 static int
1898 zpool_export_one(zpool_handle_t *zhp, void *data)
1900 export_cbdata_t *cb = data;
1902 if (zpool_disable_datasets(zhp, cb->force) != 0)
1903 return (1);
1905 /* The history must be logged as part of the export */
1906 log_history = B_FALSE;
1908 if (cb->hardforce) {
1909 if (zpool_export_force(zhp, history_str) != 0)
1910 return (1);
1911 } else if (zpool_export(zhp, cb->force, history_str) != 0) {
1912 return (1);
1915 return (0);
1919 * zpool export [-f] <pool> ...
1921 * -a Export all pools
1922 * -f Forcefully unmount datasets
1924 * Export the given pools. By default, the command will attempt to cleanly
1925 * unmount any active datasets within the pool. If the '-f' flag is specified,
1926 * then the datasets will be forcefully unmounted.
1929 zpool_do_export(int argc, char **argv)
1931 export_cbdata_t cb;
1932 boolean_t do_all = B_FALSE;
1933 boolean_t force = B_FALSE;
1934 boolean_t hardforce = B_FALSE;
1935 int c, ret;
1937 /* check options */
1938 while ((c = getopt(argc, argv, "afF")) != -1) {
1939 switch (c) {
1940 case 'a':
1941 do_all = B_TRUE;
1942 break;
1943 case 'f':
1944 force = B_TRUE;
1945 break;
1946 case 'F':
1947 hardforce = B_TRUE;
1948 break;
1949 case '?':
1950 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1951 optopt);
1952 usage(B_FALSE);
1956 cb.force = force;
1957 cb.hardforce = hardforce;
1958 argc -= optind;
1959 argv += optind;
1961 if (do_all) {
1962 if (argc != 0) {
1963 (void) fprintf(stderr, gettext("too many arguments\n"));
1964 usage(B_FALSE);
1967 return (for_each_pool(argc, argv, B_TRUE, NULL,
1968 ZFS_TYPE_POOL, B_FALSE, zpool_export_one, &cb));
1971 /* check arguments */
1972 if (argc < 1) {
1973 (void) fprintf(stderr, gettext("missing pool argument\n"));
1974 usage(B_FALSE);
1977 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
1978 B_FALSE, zpool_export_one, &cb);
1980 return (ret);
1984 * Given a vdev configuration, determine the maximum width needed for the device
1985 * name column.
1987 static int
1988 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
1989 int name_flags)
1991 static const char *const subtypes[] =
1992 {ZPOOL_CONFIG_SPARES, ZPOOL_CONFIG_L2CACHE, ZPOOL_CONFIG_CHILDREN};
1994 char *name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
1995 max = MAX(strlen(name) + depth, max);
1996 free(name);
1998 nvlist_t **child;
1999 uint_t children;
2000 for (size_t i = 0; i < ARRAY_SIZE(subtypes); ++i)
2001 if (nvlist_lookup_nvlist_array(nv, subtypes[i],
2002 &child, &children) == 0)
2003 for (uint_t c = 0; c < children; ++c)
2004 max = MAX(max_width(zhp, child[c], depth + 2,
2005 max, name_flags), max);
2007 return (max);
2010 typedef struct spare_cbdata {
2011 uint64_t cb_guid;
2012 zpool_handle_t *cb_zhp;
2013 } spare_cbdata_t;
2015 static boolean_t
2016 find_vdev(nvlist_t *nv, uint64_t search)
2018 uint64_t guid;
2019 nvlist_t **child;
2020 uint_t c, children;
2022 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
2023 search == guid)
2024 return (B_TRUE);
2026 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2027 &child, &children) == 0) {
2028 for (c = 0; c < children; c++)
2029 if (find_vdev(child[c], search))
2030 return (B_TRUE);
2033 return (B_FALSE);
2036 static int
2037 find_spare(zpool_handle_t *zhp, void *data)
2039 spare_cbdata_t *cbp = data;
2040 nvlist_t *config, *nvroot;
2042 config = zpool_get_config(zhp, NULL);
2043 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2044 &nvroot) == 0);
2046 if (find_vdev(nvroot, cbp->cb_guid)) {
2047 cbp->cb_zhp = zhp;
2048 return (1);
2051 zpool_close(zhp);
2052 return (0);
2055 typedef struct status_cbdata {
2056 int cb_count;
2057 int cb_name_flags;
2058 int cb_namewidth;
2059 boolean_t cb_allpools;
2060 boolean_t cb_verbose;
2061 boolean_t cb_literal;
2062 boolean_t cb_explain;
2063 boolean_t cb_first;
2064 boolean_t cb_dedup_stats;
2065 boolean_t cb_print_status;
2066 boolean_t cb_print_slow_ios;
2067 boolean_t cb_print_vdev_init;
2068 boolean_t cb_print_vdev_trim;
2069 vdev_cmd_data_list_t *vcdl;
2070 } status_cbdata_t;
2072 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
2073 static boolean_t
2074 is_blank_str(const char *str)
2076 for (; str != NULL && *str != '\0'; ++str)
2077 if (!isblank(*str))
2078 return (B_FALSE);
2079 return (B_TRUE);
2082 /* Print command output lines for specific vdev in a specific pool */
2083 static void
2084 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, char *path)
2086 vdev_cmd_data_t *data;
2087 int i, j;
2088 const char *val;
2090 for (i = 0; i < vcdl->count; i++) {
2091 if ((strcmp(vcdl->data[i].path, path) != 0) ||
2092 (strcmp(vcdl->data[i].pool, pool) != 0)) {
2093 /* Not the vdev we're looking for */
2094 continue;
2097 data = &vcdl->data[i];
2098 /* Print out all the output values for this vdev */
2099 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2100 val = NULL;
2101 /* Does this vdev have values for this column? */
2102 for (int k = 0; k < data->cols_cnt; k++) {
2103 if (strcmp(data->cols[k],
2104 vcdl->uniq_cols[j]) == 0) {
2105 /* yes it does, record the value */
2106 val = data->lines[k];
2107 break;
2111 * Mark empty values with dashes to make output
2112 * awk-able.
2114 if (val == NULL || is_blank_str(val))
2115 val = "-";
2117 printf("%*s", vcdl->uniq_cols_width[j], val);
2118 if (j < vcdl->uniq_cols_cnt - 1)
2119 fputs(" ", stdout);
2122 /* Print out any values that aren't in a column at the end */
2123 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2124 /* Did we have any columns? If so print a spacer. */
2125 if (vcdl->uniq_cols_cnt > 0)
2126 fputs(" ", stdout);
2128 val = data->lines[j];
2129 fputs(val ?: "", stdout);
2131 break;
2136 * Print vdev initialization status for leaves
2138 static void
2139 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
2141 if (verbose) {
2142 if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
2143 vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
2144 vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
2145 !vs->vs_scan_removing) {
2146 char zbuf[1024];
2147 char tbuf[256];
2148 struct tm zaction_ts;
2150 time_t t = vs->vs_initialize_action_time;
2151 int initialize_pct = 100;
2152 if (vs->vs_initialize_state !=
2153 VDEV_INITIALIZE_COMPLETE) {
2154 initialize_pct = (vs->vs_initialize_bytes_done *
2155 100 / (vs->vs_initialize_bytes_est + 1));
2158 (void) localtime_r(&t, &zaction_ts);
2159 (void) strftime(tbuf, sizeof (tbuf), "%c", &zaction_ts);
2161 switch (vs->vs_initialize_state) {
2162 case VDEV_INITIALIZE_SUSPENDED:
2163 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2164 gettext("suspended, started at"), tbuf);
2165 break;
2166 case VDEV_INITIALIZE_ACTIVE:
2167 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2168 gettext("started at"), tbuf);
2169 break;
2170 case VDEV_INITIALIZE_COMPLETE:
2171 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2172 gettext("completed at"), tbuf);
2173 break;
2176 (void) printf(gettext(" (%d%% initialized%s)"),
2177 initialize_pct, zbuf);
2178 } else {
2179 (void) printf(gettext(" (uninitialized)"));
2181 } else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
2182 (void) printf(gettext(" (initializing)"));
2187 * Print vdev TRIM status for leaves
2189 static void
2190 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
2192 if (verbose) {
2193 if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
2194 vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
2195 vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
2196 !vs->vs_scan_removing) {
2197 char zbuf[1024];
2198 char tbuf[256];
2199 struct tm zaction_ts;
2201 time_t t = vs->vs_trim_action_time;
2202 int trim_pct = 100;
2203 if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
2204 trim_pct = (vs->vs_trim_bytes_done *
2205 100 / (vs->vs_trim_bytes_est + 1));
2208 (void) localtime_r(&t, &zaction_ts);
2209 (void) strftime(tbuf, sizeof (tbuf), "%c", &zaction_ts);
2211 switch (vs->vs_trim_state) {
2212 case VDEV_TRIM_SUSPENDED:
2213 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2214 gettext("suspended, started at"), tbuf);
2215 break;
2216 case VDEV_TRIM_ACTIVE:
2217 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2218 gettext("started at"), tbuf);
2219 break;
2220 case VDEV_TRIM_COMPLETE:
2221 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2222 gettext("completed at"), tbuf);
2223 break;
2226 (void) printf(gettext(" (%d%% trimmed%s)"),
2227 trim_pct, zbuf);
2228 } else if (vs->vs_trim_notsup) {
2229 (void) printf(gettext(" (trim unsupported)"));
2230 } else {
2231 (void) printf(gettext(" (untrimmed)"));
2233 } else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
2234 (void) printf(gettext(" (trimming)"));
2239 * Return the color associated with a health string. This includes returning
2240 * NULL for no color change.
2242 static const char *
2243 health_str_to_color(const char *health)
2245 if (strcmp(health, gettext("FAULTED")) == 0 ||
2246 strcmp(health, gettext("SUSPENDED")) == 0 ||
2247 strcmp(health, gettext("UNAVAIL")) == 0) {
2248 return (ANSI_RED);
2251 if (strcmp(health, gettext("OFFLINE")) == 0 ||
2252 strcmp(health, gettext("DEGRADED")) == 0 ||
2253 strcmp(health, gettext("REMOVED")) == 0) {
2254 return (ANSI_YELLOW);
2257 return (NULL);
2261 * Print out configuration state as requested by status_callback.
2263 static void
2264 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
2265 nvlist_t *nv, int depth, boolean_t isspare, vdev_rebuild_stat_t *vrs)
2267 nvlist_t **child, *root;
2268 uint_t c, i, vsc, children;
2269 pool_scan_stat_t *ps = NULL;
2270 vdev_stat_t *vs;
2271 char rbuf[6], wbuf[6], cbuf[6];
2272 char *vname;
2273 uint64_t notpresent;
2274 spare_cbdata_t spare_cb;
2275 const char *state;
2276 char *type;
2277 char *path = NULL;
2278 const char *rcolor = NULL, *wcolor = NULL, *ccolor = NULL;
2280 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2281 &child, &children) != 0)
2282 children = 0;
2284 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2285 (uint64_t **)&vs, &vsc) == 0);
2287 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2289 if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2290 return;
2292 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2294 if (isspare) {
2296 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
2297 * online drives.
2299 if (vs->vs_aux == VDEV_AUX_SPARED)
2300 state = gettext("INUSE");
2301 else if (vs->vs_state == VDEV_STATE_HEALTHY)
2302 state = gettext("AVAIL");
2305 printf_color(health_str_to_color(state),
2306 "\t%*s%-*s %-8s", depth, "", cb->cb_namewidth - depth,
2307 name, state);
2309 if (!isspare) {
2310 if (vs->vs_read_errors)
2311 rcolor = ANSI_RED;
2313 if (vs->vs_write_errors)
2314 wcolor = ANSI_RED;
2316 if (vs->vs_checksum_errors)
2317 ccolor = ANSI_RED;
2319 if (cb->cb_literal) {
2320 fputc(' ', stdout);
2321 printf_color(rcolor, "%5llu",
2322 (u_longlong_t)vs->vs_read_errors);
2323 fputc(' ', stdout);
2324 printf_color(wcolor, "%5llu",
2325 (u_longlong_t)vs->vs_write_errors);
2326 fputc(' ', stdout);
2327 printf_color(ccolor, "%5llu",
2328 (u_longlong_t)vs->vs_checksum_errors);
2329 } else {
2330 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
2331 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
2332 zfs_nicenum(vs->vs_checksum_errors, cbuf,
2333 sizeof (cbuf));
2334 fputc(' ', stdout);
2335 printf_color(rcolor, "%5s", rbuf);
2336 fputc(' ', stdout);
2337 printf_color(wcolor, "%5s", wbuf);
2338 fputc(' ', stdout);
2339 printf_color(ccolor, "%5s", cbuf);
2341 if (cb->cb_print_slow_ios) {
2342 if (children == 0) {
2343 /* Only leafs vdevs have slow IOs */
2344 zfs_nicenum(vs->vs_slow_ios, rbuf,
2345 sizeof (rbuf));
2346 } else {
2347 snprintf(rbuf, sizeof (rbuf), "-");
2350 if (cb->cb_literal)
2351 printf(" %5llu", (u_longlong_t)vs->vs_slow_ios);
2352 else
2353 printf(" %5s", rbuf);
2357 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
2358 &notpresent) == 0) {
2359 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
2360 (void) printf(" %s %s", gettext("was"), path);
2361 } else if (vs->vs_aux != 0) {
2362 (void) printf(" ");
2363 color_start(ANSI_RED);
2364 switch (vs->vs_aux) {
2365 case VDEV_AUX_OPEN_FAILED:
2366 (void) printf(gettext("cannot open"));
2367 break;
2369 case VDEV_AUX_BAD_GUID_SUM:
2370 (void) printf(gettext("missing device"));
2371 break;
2373 case VDEV_AUX_NO_REPLICAS:
2374 (void) printf(gettext("insufficient replicas"));
2375 break;
2377 case VDEV_AUX_VERSION_NEWER:
2378 (void) printf(gettext("newer version"));
2379 break;
2381 case VDEV_AUX_UNSUP_FEAT:
2382 (void) printf(gettext("unsupported feature(s)"));
2383 break;
2385 case VDEV_AUX_ASHIFT_TOO_BIG:
2386 (void) printf(gettext("unsupported minimum blocksize"));
2387 break;
2389 case VDEV_AUX_SPARED:
2390 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
2391 &spare_cb.cb_guid) == 0);
2392 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
2393 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
2394 zpool_get_name(zhp)) == 0)
2395 (void) printf(gettext("currently in "
2396 "use"));
2397 else
2398 (void) printf(gettext("in use by "
2399 "pool '%s'"),
2400 zpool_get_name(spare_cb.cb_zhp));
2401 zpool_close(spare_cb.cb_zhp);
2402 } else {
2403 (void) printf(gettext("currently in use"));
2405 break;
2407 case VDEV_AUX_ERR_EXCEEDED:
2408 (void) printf(gettext("too many errors"));
2409 break;
2411 case VDEV_AUX_IO_FAILURE:
2412 (void) printf(gettext("experienced I/O failures"));
2413 break;
2415 case VDEV_AUX_BAD_LOG:
2416 (void) printf(gettext("bad intent log"));
2417 break;
2419 case VDEV_AUX_EXTERNAL:
2420 (void) printf(gettext("external device fault"));
2421 break;
2423 case VDEV_AUX_SPLIT_POOL:
2424 (void) printf(gettext("split into new pool"));
2425 break;
2427 case VDEV_AUX_ACTIVE:
2428 (void) printf(gettext("currently in use"));
2429 break;
2431 case VDEV_AUX_CHILDREN_OFFLINE:
2432 (void) printf(gettext("all children offline"));
2433 break;
2435 case VDEV_AUX_BAD_LABEL:
2436 (void) printf(gettext("invalid label"));
2437 break;
2439 default:
2440 (void) printf(gettext("corrupted data"));
2441 break;
2443 color_end();
2444 } else if (children == 0 && !isspare &&
2445 getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
2446 VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
2447 vs->vs_configured_ashift < vs->vs_physical_ashift) {
2448 (void) printf(
2449 gettext(" block size: %dB configured, %dB native"),
2450 1 << vs->vs_configured_ashift, 1 << vs->vs_physical_ashift);
2453 if (vs->vs_scan_removing != 0) {
2454 (void) printf(gettext(" (removing)"));
2455 } else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
2456 (void) printf(gettext(" (non-allocating)"));
2459 /* The root vdev has the scrub/resilver stats */
2460 root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
2461 ZPOOL_CONFIG_VDEV_TREE);
2462 (void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
2463 (uint64_t **)&ps, &c);
2466 * If you force fault a drive that's resilvering, its scan stats can
2467 * get frozen in time, giving the false impression that it's
2468 * being resilvered. That's why we check the state to see if the vdev
2469 * is healthy before reporting "resilvering" or "repairing".
2471 if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0 &&
2472 vs->vs_state == VDEV_STATE_HEALTHY) {
2473 if (vs->vs_scan_processed != 0) {
2474 (void) printf(gettext(" (%s)"),
2475 (ps->pss_func == POOL_SCAN_RESILVER) ?
2476 "resilvering" : "repairing");
2477 } else if (vs->vs_resilver_deferred) {
2478 (void) printf(gettext(" (awaiting resilver)"));
2482 /* The top-level vdevs have the rebuild stats */
2483 if (vrs != NULL && vrs->vrs_state == VDEV_REBUILD_ACTIVE &&
2484 children == 0 && vs->vs_state == VDEV_STATE_HEALTHY) {
2485 if (vs->vs_rebuild_processed != 0) {
2486 (void) printf(gettext(" (resilvering)"));
2490 if (cb->vcdl != NULL) {
2491 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
2492 printf(" ");
2493 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
2497 /* Display vdev initialization and trim status for leaves. */
2498 if (children == 0) {
2499 print_status_initialize(vs, cb->cb_print_vdev_init);
2500 print_status_trim(vs, cb->cb_print_vdev_trim);
2503 (void) printf("\n");
2505 for (c = 0; c < children; c++) {
2506 uint64_t islog = B_FALSE, ishole = B_FALSE;
2508 /* Don't print logs or holes here */
2509 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2510 &islog);
2511 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
2512 &ishole);
2513 if (islog || ishole)
2514 continue;
2515 /* Only print normal classes here */
2516 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
2517 continue;
2519 /* Provide vdev_rebuild_stats to children if available */
2520 if (vrs == NULL) {
2521 (void) nvlist_lookup_uint64_array(nv,
2522 ZPOOL_CONFIG_REBUILD_STATS,
2523 (uint64_t **)&vrs, &i);
2526 vname = zpool_vdev_name(g_zfs, zhp, child[c],
2527 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2528 print_status_config(zhp, cb, vname, child[c], depth + 2,
2529 isspare, vrs);
2530 free(vname);
2535 * Print the configuration of an exported pool. Iterate over all vdevs in the
2536 * pool, printing out the name and status for each one.
2538 static void
2539 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
2540 int depth)
2542 nvlist_t **child;
2543 uint_t c, children;
2544 vdev_stat_t *vs;
2545 char *type, *vname;
2547 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2548 if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
2549 strcmp(type, VDEV_TYPE_HOLE) == 0)
2550 return;
2552 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2553 (uint64_t **)&vs, &c) == 0);
2555 (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
2556 (void) printf(" %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
2558 if (vs->vs_aux != 0) {
2559 (void) printf(" ");
2561 switch (vs->vs_aux) {
2562 case VDEV_AUX_OPEN_FAILED:
2563 (void) printf(gettext("cannot open"));
2564 break;
2566 case VDEV_AUX_BAD_GUID_SUM:
2567 (void) printf(gettext("missing device"));
2568 break;
2570 case VDEV_AUX_NO_REPLICAS:
2571 (void) printf(gettext("insufficient replicas"));
2572 break;
2574 case VDEV_AUX_VERSION_NEWER:
2575 (void) printf(gettext("newer version"));
2576 break;
2578 case VDEV_AUX_UNSUP_FEAT:
2579 (void) printf(gettext("unsupported feature(s)"));
2580 break;
2582 case VDEV_AUX_ERR_EXCEEDED:
2583 (void) printf(gettext("too many errors"));
2584 break;
2586 case VDEV_AUX_ACTIVE:
2587 (void) printf(gettext("currently in use"));
2588 break;
2590 case VDEV_AUX_CHILDREN_OFFLINE:
2591 (void) printf(gettext("all children offline"));
2592 break;
2594 case VDEV_AUX_BAD_LABEL:
2595 (void) printf(gettext("invalid label"));
2596 break;
2598 default:
2599 (void) printf(gettext("corrupted data"));
2600 break;
2603 (void) printf("\n");
2605 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2606 &child, &children) != 0)
2607 return;
2609 for (c = 0; c < children; c++) {
2610 uint64_t is_log = B_FALSE;
2612 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2613 &is_log);
2614 if (is_log)
2615 continue;
2616 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
2617 continue;
2619 vname = zpool_vdev_name(g_zfs, NULL, child[c],
2620 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2621 print_import_config(cb, vname, child[c], depth + 2);
2622 free(vname);
2625 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2626 &child, &children) == 0) {
2627 (void) printf(gettext("\tcache\n"));
2628 for (c = 0; c < children; c++) {
2629 vname = zpool_vdev_name(g_zfs, NULL, child[c],
2630 cb->cb_name_flags);
2631 (void) printf("\t %s\n", vname);
2632 free(vname);
2636 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2637 &child, &children) == 0) {
2638 (void) printf(gettext("\tspares\n"));
2639 for (c = 0; c < children; c++) {
2640 vname = zpool_vdev_name(g_zfs, NULL, child[c],
2641 cb->cb_name_flags);
2642 (void) printf("\t %s\n", vname);
2643 free(vname);
2649 * Print specialized class vdevs.
2651 * These are recorded as top level vdevs in the main pool child array
2652 * but with "is_log" set to 1 or an "alloc_bias" string. We use either
2653 * print_status_config() or print_import_config() to print the top level
2654 * class vdevs then any of their children (eg mirrored slogs) are printed
2655 * recursively - which works because only the top level vdev is marked.
2657 static void
2658 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
2659 const char *class)
2661 uint_t c, children;
2662 nvlist_t **child;
2663 boolean_t printed = B_FALSE;
2665 assert(zhp != NULL || !cb->cb_verbose);
2667 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
2668 &children) != 0)
2669 return;
2671 for (c = 0; c < children; c++) {
2672 uint64_t is_log = B_FALSE;
2673 char *bias = NULL;
2674 char *type = NULL;
2676 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2677 &is_log);
2679 if (is_log) {
2680 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
2681 } else {
2682 (void) nvlist_lookup_string(child[c],
2683 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
2684 (void) nvlist_lookup_string(child[c],
2685 ZPOOL_CONFIG_TYPE, &type);
2688 if (bias == NULL || strcmp(bias, class) != 0)
2689 continue;
2690 if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2691 continue;
2693 if (!printed) {
2694 (void) printf("\t%s\t\n", gettext(class));
2695 printed = B_TRUE;
2698 char *name = zpool_vdev_name(g_zfs, zhp, child[c],
2699 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2700 if (cb->cb_print_status)
2701 print_status_config(zhp, cb, name, child[c], 2,
2702 B_FALSE, NULL);
2703 else
2704 print_import_config(cb, name, child[c], 2);
2705 free(name);
2710 * Display the status for the given pool.
2712 static int
2713 show_import(nvlist_t *config, boolean_t report_error)
2715 uint64_t pool_state;
2716 vdev_stat_t *vs;
2717 char *name;
2718 uint64_t guid;
2719 uint64_t hostid = 0;
2720 const char *msgid;
2721 const char *hostname = "unknown";
2722 nvlist_t *nvroot, *nvinfo;
2723 zpool_status_t reason;
2724 zpool_errata_t errata;
2725 const char *health;
2726 uint_t vsc;
2727 char *comment;
2728 status_cbdata_t cb = { 0 };
2730 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2731 &name) == 0);
2732 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
2733 &guid) == 0);
2734 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2735 &pool_state) == 0);
2736 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2737 &nvroot) == 0);
2739 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
2740 (uint64_t **)&vs, &vsc) == 0);
2741 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2743 reason = zpool_import_status(config, &msgid, &errata);
2746 * If we're importing using a cachefile, then we won't report any
2747 * errors unless we are in the scan phase of the import.
2749 if (reason != ZPOOL_STATUS_OK && !report_error)
2750 return (reason);
2752 (void) printf(gettext(" pool: %s\n"), name);
2753 (void) printf(gettext(" id: %llu\n"), (u_longlong_t)guid);
2754 (void) printf(gettext(" state: %s"), health);
2755 if (pool_state == POOL_STATE_DESTROYED)
2756 (void) printf(gettext(" (DESTROYED)"));
2757 (void) printf("\n");
2759 switch (reason) {
2760 case ZPOOL_STATUS_MISSING_DEV_R:
2761 case ZPOOL_STATUS_MISSING_DEV_NR:
2762 case ZPOOL_STATUS_BAD_GUID_SUM:
2763 printf_color(ANSI_BOLD, gettext("status: "));
2764 printf_color(ANSI_YELLOW, gettext("One or more devices are "
2765 "missing from the system.\n"));
2766 break;
2768 case ZPOOL_STATUS_CORRUPT_LABEL_R:
2769 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
2770 printf_color(ANSI_BOLD, gettext("status: "));
2771 printf_color(ANSI_YELLOW, gettext("One or more devices contains"
2772 " corrupted data.\n"));
2773 break;
2775 case ZPOOL_STATUS_CORRUPT_DATA:
2776 (void) printf(
2777 gettext(" status: The pool data is corrupted.\n"));
2778 break;
2780 case ZPOOL_STATUS_OFFLINE_DEV:
2781 printf_color(ANSI_BOLD, gettext("status: "));
2782 printf_color(ANSI_YELLOW, gettext("One or more devices "
2783 "are offlined.\n"));
2784 break;
2786 case ZPOOL_STATUS_CORRUPT_POOL:
2787 printf_color(ANSI_BOLD, gettext("status: "));
2788 printf_color(ANSI_YELLOW, gettext("The pool metadata is "
2789 "corrupted.\n"));
2790 break;
2792 case ZPOOL_STATUS_VERSION_OLDER:
2793 printf_color(ANSI_BOLD, gettext("status: "));
2794 printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
2795 "a legacy on-disk version.\n"));
2796 break;
2798 case ZPOOL_STATUS_VERSION_NEWER:
2799 printf_color(ANSI_BOLD, gettext("status: "));
2800 printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
2801 "an incompatible version.\n"));
2802 break;
2804 case ZPOOL_STATUS_FEAT_DISABLED:
2805 printf_color(ANSI_BOLD, gettext("status: "));
2806 printf_color(ANSI_YELLOW, gettext("Some supported "
2807 "features are not enabled on the pool.\n\t"
2808 "(Note that they may be intentionally disabled "
2809 "if the\n\t'compatibility' property is set.)\n"));
2810 break;
2812 case ZPOOL_STATUS_COMPATIBILITY_ERR:
2813 printf_color(ANSI_BOLD, gettext("status: "));
2814 printf_color(ANSI_YELLOW, gettext("Error reading or parsing "
2815 "the file(s) indicated by the 'compatibility'\n"
2816 "property.\n"));
2817 break;
2819 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
2820 printf_color(ANSI_BOLD, gettext("status: "));
2821 printf_color(ANSI_YELLOW, gettext("One or more features "
2822 "are enabled on the pool despite not being\n"
2823 "requested by the 'compatibility' property.\n"));
2824 break;
2826 case ZPOOL_STATUS_UNSUP_FEAT_READ:
2827 printf_color(ANSI_BOLD, gettext("status: "));
2828 printf_color(ANSI_YELLOW, gettext("The pool uses the following "
2829 "feature(s) not supported on this system:\n"));
2830 color_start(ANSI_YELLOW);
2831 zpool_print_unsup_feat(config);
2832 color_end();
2833 break;
2835 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2836 printf_color(ANSI_BOLD, gettext("status: "));
2837 printf_color(ANSI_YELLOW, gettext("The pool can only be "
2838 "accessed in read-only mode on this system. It\n\tcannot be"
2839 " accessed in read-write mode because it uses the "
2840 "following\n\tfeature(s) not supported on this system:\n"));
2841 color_start(ANSI_YELLOW);
2842 zpool_print_unsup_feat(config);
2843 color_end();
2844 break;
2846 case ZPOOL_STATUS_HOSTID_ACTIVE:
2847 printf_color(ANSI_BOLD, gettext("status: "));
2848 printf_color(ANSI_YELLOW, gettext("The pool is currently "
2849 "imported by another system.\n"));
2850 break;
2852 case ZPOOL_STATUS_HOSTID_REQUIRED:
2853 printf_color(ANSI_BOLD, gettext("status: "));
2854 printf_color(ANSI_YELLOW, gettext("The pool has the "
2855 "multihost property on. It cannot\n\tbe safely imported "
2856 "when the system hostid is not set.\n"));
2857 break;
2859 case ZPOOL_STATUS_HOSTID_MISMATCH:
2860 printf_color(ANSI_BOLD, gettext("status: "));
2861 printf_color(ANSI_YELLOW, gettext("The pool was last accessed "
2862 "by another system.\n"));
2863 break;
2865 case ZPOOL_STATUS_FAULTED_DEV_R:
2866 case ZPOOL_STATUS_FAULTED_DEV_NR:
2867 printf_color(ANSI_BOLD, gettext("status: "));
2868 printf_color(ANSI_YELLOW, gettext("One or more devices are "
2869 "faulted.\n"));
2870 break;
2872 case ZPOOL_STATUS_BAD_LOG:
2873 printf_color(ANSI_BOLD, gettext("status: "));
2874 printf_color(ANSI_YELLOW, gettext("An intent log record cannot "
2875 "be read.\n"));
2876 break;
2878 case ZPOOL_STATUS_RESILVERING:
2879 case ZPOOL_STATUS_REBUILDING:
2880 printf_color(ANSI_BOLD, gettext("status: "));
2881 printf_color(ANSI_YELLOW, gettext("One or more devices were "
2882 "being resilvered.\n"));
2883 break;
2885 case ZPOOL_STATUS_ERRATA:
2886 printf_color(ANSI_BOLD, gettext("status: "));
2887 printf_color(ANSI_YELLOW, gettext("Errata #%d detected.\n"),
2888 errata);
2889 break;
2891 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
2892 printf_color(ANSI_BOLD, gettext("status: "));
2893 printf_color(ANSI_YELLOW, gettext("One or more devices are "
2894 "configured to use a non-native block size.\n"
2895 "\tExpect reduced performance.\n"));
2896 break;
2898 default:
2900 * No other status can be seen when importing pools.
2902 assert(reason == ZPOOL_STATUS_OK);
2906 * Print out an action according to the overall state of the pool.
2908 if (vs->vs_state == VDEV_STATE_HEALTHY) {
2909 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
2910 reason == ZPOOL_STATUS_FEAT_DISABLED) {
2911 (void) printf(gettext(" action: The pool can be "
2912 "imported using its name or numeric identifier, "
2913 "though\n\tsome features will not be available "
2914 "without an explicit 'zpool upgrade'.\n"));
2915 } else if (reason == ZPOOL_STATUS_COMPATIBILITY_ERR) {
2916 (void) printf(gettext(" action: The pool can be "
2917 "imported using its name or numeric\n\tidentifier, "
2918 "though the file(s) indicated by its "
2919 "'compatibility'\n\tproperty cannot be parsed at "
2920 "this time.\n"));
2921 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
2922 (void) printf(gettext(" action: The pool can be "
2923 "imported using its name or numeric "
2924 "identifier and\n\tthe '-f' flag.\n"));
2925 } else if (reason == ZPOOL_STATUS_ERRATA) {
2926 switch (errata) {
2927 case ZPOOL_ERRATA_NONE:
2928 break;
2930 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
2931 (void) printf(gettext(" action: The pool can "
2932 "be imported using its name or numeric "
2933 "identifier,\n\thowever there is a compat"
2934 "ibility issue which should be corrected"
2935 "\n\tby running 'zpool scrub'\n"));
2936 break;
2938 case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
2939 (void) printf(gettext(" action: The pool can"
2940 "not be imported with this version of ZFS "
2941 "due to\n\tan active asynchronous destroy. "
2942 "Revert to an earlier version\n\tand "
2943 "allow the destroy to complete before "
2944 "updating.\n"));
2945 break;
2947 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
2948 (void) printf(gettext(" action: Existing "
2949 "encrypted datasets contain an on-disk "
2950 "incompatibility, which\n\tneeds to be "
2951 "corrected. Backup these datasets to new "
2952 "encrypted datasets\n\tand destroy the "
2953 "old ones.\n"));
2954 break;
2956 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
2957 (void) printf(gettext(" action: Existing "
2958 "encrypted snapshots and bookmarks contain "
2959 "an on-disk\n\tincompatibility. This may "
2960 "cause on-disk corruption if they are used"
2961 "\n\twith 'zfs recv'. To correct the "
2962 "issue, enable the bookmark_v2 feature.\n\t"
2963 "No additional action is needed if there "
2964 "are no encrypted snapshots or\n\t"
2965 "bookmarks. If preserving the encrypted "
2966 "snapshots and bookmarks is\n\trequired, "
2967 "use a non-raw send to backup and restore "
2968 "them. Alternately,\n\tthey may be removed"
2969 " to resolve the incompatibility.\n"));
2970 break;
2971 default:
2973 * All errata must contain an action message.
2975 assert(0);
2977 } else {
2978 (void) printf(gettext(" action: The pool can be "
2979 "imported using its name or numeric "
2980 "identifier.\n"));
2982 } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
2983 (void) printf(gettext(" action: The pool can be imported "
2984 "despite missing or damaged devices. The\n\tfault "
2985 "tolerance of the pool may be compromised if imported.\n"));
2986 } else {
2987 switch (reason) {
2988 case ZPOOL_STATUS_VERSION_NEWER:
2989 (void) printf(gettext(" action: The pool cannot be "
2990 "imported. Access the pool on a system running "
2991 "newer\n\tsoftware, or recreate the pool from "
2992 "backup.\n"));
2993 break;
2994 case ZPOOL_STATUS_UNSUP_FEAT_READ:
2995 printf_color(ANSI_BOLD, gettext("action: "));
2996 printf_color(ANSI_YELLOW, gettext("The pool cannot be "
2997 "imported. Access the pool on a system that "
2998 "supports\n\tthe required feature(s), or recreate "
2999 "the pool from backup.\n"));
3000 break;
3001 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3002 printf_color(ANSI_BOLD, gettext("action: "));
3003 printf_color(ANSI_YELLOW, gettext("The pool cannot be "
3004 "imported in read-write mode. Import the pool "
3005 "with\n"
3006 "\t\"-o readonly=on\", access the pool on a system "
3007 "that supports the\n\trequired feature(s), or "
3008 "recreate the pool from backup.\n"));
3009 break;
3010 case ZPOOL_STATUS_MISSING_DEV_R:
3011 case ZPOOL_STATUS_MISSING_DEV_NR:
3012 case ZPOOL_STATUS_BAD_GUID_SUM:
3013 (void) printf(gettext(" action: The pool cannot be "
3014 "imported. Attach the missing\n\tdevices and try "
3015 "again.\n"));
3016 break;
3017 case ZPOOL_STATUS_HOSTID_ACTIVE:
3018 VERIFY0(nvlist_lookup_nvlist(config,
3019 ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
3021 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3022 hostname = fnvlist_lookup_string(nvinfo,
3023 ZPOOL_CONFIG_MMP_HOSTNAME);
3025 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3026 hostid = fnvlist_lookup_uint64(nvinfo,
3027 ZPOOL_CONFIG_MMP_HOSTID);
3029 (void) printf(gettext(" action: The pool must be "
3030 "exported from %s (hostid=%"PRIx64")\n\tbefore it "
3031 "can be safely imported.\n"), hostname, hostid);
3032 break;
3033 case ZPOOL_STATUS_HOSTID_REQUIRED:
3034 (void) printf(gettext(" action: Set a unique system "
3035 "hostid with the zgenhostid(8) command.\n"));
3036 break;
3037 default:
3038 (void) printf(gettext(" action: The pool cannot be "
3039 "imported due to damaged devices or data.\n"));
3043 /* Print the comment attached to the pool. */
3044 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
3045 (void) printf(gettext("comment: %s\n"), comment);
3048 * If the state is "closed" or "can't open", and the aux state
3049 * is "corrupt data":
3051 if (((vs->vs_state == VDEV_STATE_CLOSED) ||
3052 (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
3053 (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
3054 if (pool_state == POOL_STATE_DESTROYED)
3055 (void) printf(gettext("\tThe pool was destroyed, "
3056 "but can be imported using the '-Df' flags.\n"));
3057 else if (pool_state != POOL_STATE_EXPORTED)
3058 (void) printf(gettext("\tThe pool may be active on "
3059 "another system, but can be imported using\n\t"
3060 "the '-f' flag.\n"));
3063 if (msgid != NULL) {
3064 (void) printf(gettext(
3065 " see: https://openzfs.github.io/openzfs-docs/msg/%s\n"),
3066 msgid);
3069 (void) printf(gettext(" config:\n\n"));
3071 cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
3072 VDEV_NAME_TYPE_ID);
3073 if (cb.cb_namewidth < 10)
3074 cb.cb_namewidth = 10;
3076 print_import_config(&cb, name, nvroot, 0);
3078 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
3079 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
3080 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
3082 if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
3083 (void) printf(gettext("\n\tAdditional devices are known to "
3084 "be part of this pool, though their\n\texact "
3085 "configuration cannot be determined.\n"));
3087 return (0);
3090 static boolean_t
3091 zfs_force_import_required(nvlist_t *config)
3093 uint64_t state;
3094 uint64_t hostid = 0;
3095 nvlist_t *nvinfo;
3097 state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
3098 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID, &hostid);
3100 if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
3101 return (B_TRUE);
3103 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3104 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
3105 mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
3106 ZPOOL_CONFIG_MMP_STATE);
3108 if (mmp_state != MMP_STATE_INACTIVE)
3109 return (B_TRUE);
3112 return (B_FALSE);
3116 * Perform the import for the given configuration. This passes the heavy
3117 * lifting off to zpool_import_props(), and then mounts the datasets contained
3118 * within the pool.
3120 static int
3121 do_import(nvlist_t *config, const char *newname, const char *mntopts,
3122 nvlist_t *props, int flags)
3124 int ret = 0;
3125 zpool_handle_t *zhp;
3126 const char *name;
3127 uint64_t version;
3129 name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
3130 version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3132 if (!SPA_VERSION_IS_SUPPORTED(version)) {
3133 (void) fprintf(stderr, gettext("cannot import '%s': pool "
3134 "is formatted using an unsupported ZFS version\n"), name);
3135 return (1);
3136 } else if (zfs_force_import_required(config) &&
3137 !(flags & ZFS_IMPORT_ANY_HOST)) {
3138 mmp_state_t mmp_state = MMP_STATE_INACTIVE;
3139 nvlist_t *nvinfo;
3141 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3142 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
3143 mmp_state = fnvlist_lookup_uint64(nvinfo,
3144 ZPOOL_CONFIG_MMP_STATE);
3146 if (mmp_state == MMP_STATE_ACTIVE) {
3147 const char *hostname = "<unknown>";
3148 uint64_t hostid = 0;
3150 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3151 hostname = fnvlist_lookup_string(nvinfo,
3152 ZPOOL_CONFIG_MMP_HOSTNAME);
3154 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3155 hostid = fnvlist_lookup_uint64(nvinfo,
3156 ZPOOL_CONFIG_MMP_HOSTID);
3158 (void) fprintf(stderr, gettext("cannot import '%s': "
3159 "pool is imported on %s (hostid: "
3160 "0x%"PRIx64")\nExport the pool on the other "
3161 "system, then run 'zpool import'.\n"),
3162 name, hostname, hostid);
3163 } else if (mmp_state == MMP_STATE_NO_HOSTID) {
3164 (void) fprintf(stderr, gettext("Cannot import '%s': "
3165 "pool has the multihost property on and the\n"
3166 "system's hostid is not set. Set a unique hostid "
3167 "with the zgenhostid(8) command.\n"), name);
3168 } else {
3169 const char *hostname = "<unknown>";
3170 time_t timestamp = 0;
3171 uint64_t hostid = 0;
3173 if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
3174 hostname = fnvlist_lookup_string(config,
3175 ZPOOL_CONFIG_HOSTNAME);
3177 if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
3178 timestamp = fnvlist_lookup_uint64(config,
3179 ZPOOL_CONFIG_TIMESTAMP);
3181 if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
3182 hostid = fnvlist_lookup_uint64(config,
3183 ZPOOL_CONFIG_HOSTID);
3185 (void) fprintf(stderr, gettext("cannot import '%s': "
3186 "pool was previously in use from another system.\n"
3187 "Last accessed by %s (hostid=%"PRIx64") at %s"
3188 "The pool can be imported, use 'zpool import -f' "
3189 "to import the pool.\n"), name, hostname,
3190 hostid, ctime(&timestamp));
3193 return (1);
3196 if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
3197 return (1);
3199 if (newname != NULL)
3200 name = newname;
3202 if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
3203 return (1);
3206 * Loading keys is best effort. We don't want to return immediately
3207 * if it fails but we do want to give the error to the caller.
3209 if (flags & ZFS_IMPORT_LOAD_KEYS &&
3210 zfs_crypto_attempt_load_keys(g_zfs, name) != 0)
3211 ret = 1;
3213 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3214 !(flags & ZFS_IMPORT_ONLY) &&
3215 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
3216 zpool_close(zhp);
3217 return (1);
3220 zpool_close(zhp);
3221 return (ret);
3224 static int
3225 import_pools(nvlist_t *pools, nvlist_t *props, char *mntopts, int flags,
3226 char *orig_name, char *new_name,
3227 boolean_t do_destroyed, boolean_t pool_specified, boolean_t do_all,
3228 importargs_t *import)
3230 nvlist_t *config = NULL;
3231 nvlist_t *found_config = NULL;
3232 uint64_t pool_state;
3235 * At this point we have a list of import candidate configs. Even if
3236 * we were searching by pool name or guid, we still need to
3237 * post-process the list to deal with pool state and possible
3238 * duplicate names.
3240 int err = 0;
3241 nvpair_t *elem = NULL;
3242 boolean_t first = B_TRUE;
3243 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3245 verify(nvpair_value_nvlist(elem, &config) == 0);
3247 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3248 &pool_state) == 0);
3249 if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
3250 continue;
3251 if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
3252 continue;
3254 verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
3255 import->policy) == 0);
3257 if (!pool_specified) {
3258 if (first)
3259 first = B_FALSE;
3260 else if (!do_all)
3261 (void) fputc('\n', stdout);
3263 if (do_all) {
3264 err |= do_import(config, NULL, mntopts,
3265 props, flags);
3266 } else {
3268 * If we're importing from cachefile, then
3269 * we don't want to report errors until we
3270 * are in the scan phase of the import. If
3271 * we get an error, then we return that error
3272 * to invoke the scan phase.
3274 if (import->cachefile && !import->scan)
3275 err = show_import(config, B_FALSE);
3276 else
3277 (void) show_import(config, B_TRUE);
3279 } else if (import->poolname != NULL) {
3280 char *name;
3283 * We are searching for a pool based on name.
3285 verify(nvlist_lookup_string(config,
3286 ZPOOL_CONFIG_POOL_NAME, &name) == 0);
3288 if (strcmp(name, import->poolname) == 0) {
3289 if (found_config != NULL) {
3290 (void) fprintf(stderr, gettext(
3291 "cannot import '%s': more than "
3292 "one matching pool\n"),
3293 import->poolname);
3294 (void) fprintf(stderr, gettext(
3295 "import by numeric ID instead\n"));
3296 err = B_TRUE;
3298 found_config = config;
3300 } else {
3301 uint64_t guid;
3304 * Search for a pool by guid.
3306 verify(nvlist_lookup_uint64(config,
3307 ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
3309 if (guid == import->guid)
3310 found_config = config;
3315 * If we were searching for a specific pool, verify that we found a
3316 * pool, and then do the import.
3318 if (pool_specified && err == 0) {
3319 if (found_config == NULL) {
3320 (void) fprintf(stderr, gettext("cannot import '%s': "
3321 "no such pool available\n"), orig_name);
3322 err = B_TRUE;
3323 } else {
3324 err |= do_import(found_config, new_name,
3325 mntopts, props, flags);
3330 * If we were just looking for pools, report an error if none were
3331 * found.
3333 if (!pool_specified && first)
3334 (void) fprintf(stderr,
3335 gettext("no pools available to import\n"));
3336 return (err);
3339 typedef struct target_exists_args {
3340 const char *poolname;
3341 uint64_t poolguid;
3342 } target_exists_args_t;
3344 static int
3345 name_or_guid_exists(zpool_handle_t *zhp, void *data)
3347 target_exists_args_t *args = data;
3348 nvlist_t *config = zpool_get_config(zhp, NULL);
3349 int found = 0;
3351 if (config == NULL)
3352 return (0);
3354 if (args->poolname != NULL) {
3355 char *pool_name;
3357 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3358 &pool_name) == 0);
3359 if (strcmp(pool_name, args->poolname) == 0)
3360 found = 1;
3361 } else {
3362 uint64_t pool_guid;
3364 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3365 &pool_guid) == 0);
3366 if (pool_guid == args->poolguid)
3367 found = 1;
3369 zpool_close(zhp);
3371 return (found);
3374 * zpool checkpoint <pool>
3375 * checkpoint --discard <pool>
3377 * -d Discard the checkpoint from a checkpointed
3378 * --discard pool.
3380 * -w Wait for discarding a checkpoint to complete.
3381 * --wait
3383 * Checkpoints the specified pool, by taking a "snapshot" of its
3384 * current state. A pool can only have one checkpoint at a time.
3387 zpool_do_checkpoint(int argc, char **argv)
3389 boolean_t discard, wait;
3390 char *pool;
3391 zpool_handle_t *zhp;
3392 int c, err;
3394 struct option long_options[] = {
3395 {"discard", no_argument, NULL, 'd'},
3396 {"wait", no_argument, NULL, 'w'},
3397 {0, 0, 0, 0}
3400 discard = B_FALSE;
3401 wait = B_FALSE;
3402 while ((c = getopt_long(argc, argv, ":dw", long_options, NULL)) != -1) {
3403 switch (c) {
3404 case 'd':
3405 discard = B_TRUE;
3406 break;
3407 case 'w':
3408 wait = B_TRUE;
3409 break;
3410 case '?':
3411 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3412 optopt);
3413 usage(B_FALSE);
3417 if (wait && !discard) {
3418 (void) fprintf(stderr, gettext("--wait only valid when "
3419 "--discard also specified\n"));
3420 usage(B_FALSE);
3423 argc -= optind;
3424 argv += optind;
3426 if (argc < 1) {
3427 (void) fprintf(stderr, gettext("missing pool argument\n"));
3428 usage(B_FALSE);
3431 if (argc > 1) {
3432 (void) fprintf(stderr, gettext("too many arguments\n"));
3433 usage(B_FALSE);
3436 pool = argv[0];
3438 if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
3439 /* As a special case, check for use of '/' in the name */
3440 if (strchr(pool, '/') != NULL)
3441 (void) fprintf(stderr, gettext("'zpool checkpoint' "
3442 "doesn't work on datasets. To save the state "
3443 "of a dataset from a specific point in time "
3444 "please use 'zfs snapshot'\n"));
3445 return (1);
3448 if (discard) {
3449 err = (zpool_discard_checkpoint(zhp) != 0);
3450 if (err == 0 && wait)
3451 err = zpool_wait(zhp, ZPOOL_WAIT_CKPT_DISCARD);
3452 } else {
3453 err = (zpool_checkpoint(zhp) != 0);
3456 zpool_close(zhp);
3458 return (err);
3461 #define CHECKPOINT_OPT 1024
3464 * zpool import [-d dir] [-D]
3465 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
3466 * [-d dir | -c cachefile | -s] [-f] -a
3467 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
3468 * [-d dir | -c cachefile | -s] [-f] [-n] [-F] <pool | id>
3469 * [newpool]
3471 * -c Read pool information from a cachefile instead of searching
3472 * devices. If importing from a cachefile config fails, then
3473 * fallback to searching for devices only in the directories that
3474 * exist in the cachefile.
3476 * -d Scan in a specific directory, other than /dev/. More than
3477 * one directory can be specified using multiple '-d' options.
3479 * -D Scan for previously destroyed pools or import all or only
3480 * specified destroyed pools.
3482 * -R Temporarily import the pool, with all mountpoints relative to
3483 * the given root. The pool will remain exported when the machine
3484 * is rebooted.
3486 * -V Import even in the presence of faulted vdevs. This is an
3487 * intentionally undocumented option for testing purposes, and
3488 * treats the pool configuration as complete, leaving any bad
3489 * vdevs in the FAULTED state. In other words, it does verbatim
3490 * import.
3492 * -f Force import, even if it appears that the pool is active.
3494 * -F Attempt rewind if necessary.
3496 * -n See if rewind would work, but don't actually rewind.
3498 * -N Import the pool but don't mount datasets.
3500 * -T Specify a starting txg to use for import. This option is
3501 * intentionally undocumented option for testing purposes.
3503 * -a Import all pools found.
3505 * -l Load encryption keys while importing.
3507 * -o Set property=value and/or temporary mount options (without '=').
3509 * -s Scan using the default search path, the libblkid cache will
3510 * not be consulted.
3512 * --rewind-to-checkpoint
3513 * Import the pool and revert back to the checkpoint.
3515 * The import command scans for pools to import, and import pools based on pool
3516 * name and GUID. The pool can also be renamed as part of the import process.
3519 zpool_do_import(int argc, char **argv)
3521 char **searchdirs = NULL;
3522 char *env, *envdup = NULL;
3523 int nsearch = 0;
3524 int c;
3525 int err = 0;
3526 nvlist_t *pools = NULL;
3527 boolean_t do_all = B_FALSE;
3528 boolean_t do_destroyed = B_FALSE;
3529 char *mntopts = NULL;
3530 uint64_t searchguid = 0;
3531 char *searchname = NULL;
3532 char *propval;
3533 nvlist_t *policy = NULL;
3534 nvlist_t *props = NULL;
3535 int flags = ZFS_IMPORT_NORMAL;
3536 uint32_t rewind_policy = ZPOOL_NO_REWIND;
3537 boolean_t dryrun = B_FALSE;
3538 boolean_t do_rewind = B_FALSE;
3539 boolean_t xtreme_rewind = B_FALSE;
3540 boolean_t do_scan = B_FALSE;
3541 boolean_t pool_exists = B_FALSE;
3542 boolean_t pool_specified = B_FALSE;
3543 uint64_t txg = -1ULL;
3544 char *cachefile = NULL;
3545 importargs_t idata = { 0 };
3546 char *endptr;
3548 struct option long_options[] = {
3549 {"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
3550 {0, 0, 0, 0}
3553 /* check options */
3554 while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmnNo:R:stT:VX",
3555 long_options, NULL)) != -1) {
3556 switch (c) {
3557 case 'a':
3558 do_all = B_TRUE;
3559 break;
3560 case 'c':
3561 cachefile = optarg;
3562 break;
3563 case 'd':
3564 searchdirs = safe_realloc(searchdirs,
3565 (nsearch + 1) * sizeof (char *));
3566 searchdirs[nsearch++] = optarg;
3567 break;
3568 case 'D':
3569 do_destroyed = B_TRUE;
3570 break;
3571 case 'f':
3572 flags |= ZFS_IMPORT_ANY_HOST;
3573 break;
3574 case 'F':
3575 do_rewind = B_TRUE;
3576 break;
3577 case 'l':
3578 flags |= ZFS_IMPORT_LOAD_KEYS;
3579 break;
3580 case 'm':
3581 flags |= ZFS_IMPORT_MISSING_LOG;
3582 break;
3583 case 'n':
3584 dryrun = B_TRUE;
3585 break;
3586 case 'N':
3587 flags |= ZFS_IMPORT_ONLY;
3588 break;
3589 case 'o':
3590 if ((propval = strchr(optarg, '=')) != NULL) {
3591 *propval = '\0';
3592 propval++;
3593 if (add_prop_list(optarg, propval,
3594 &props, B_TRUE))
3595 goto error;
3596 } else {
3597 mntopts = optarg;
3599 break;
3600 case 'R':
3601 if (add_prop_list(zpool_prop_to_name(
3602 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
3603 goto error;
3604 if (add_prop_list_default(zpool_prop_to_name(
3605 ZPOOL_PROP_CACHEFILE), "none", &props))
3606 goto error;
3607 break;
3608 case 's':
3609 do_scan = B_TRUE;
3610 break;
3611 case 't':
3612 flags |= ZFS_IMPORT_TEMP_NAME;
3613 if (add_prop_list_default(zpool_prop_to_name(
3614 ZPOOL_PROP_CACHEFILE), "none", &props))
3615 goto error;
3616 break;
3618 case 'T':
3619 errno = 0;
3620 txg = strtoull(optarg, &endptr, 0);
3621 if (errno != 0 || *endptr != '\0') {
3622 (void) fprintf(stderr,
3623 gettext("invalid txg value\n"));
3624 usage(B_FALSE);
3626 rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
3627 break;
3628 case 'V':
3629 flags |= ZFS_IMPORT_VERBATIM;
3630 break;
3631 case 'X':
3632 xtreme_rewind = B_TRUE;
3633 break;
3634 case CHECKPOINT_OPT:
3635 flags |= ZFS_IMPORT_CHECKPOINT;
3636 break;
3637 case ':':
3638 (void) fprintf(stderr, gettext("missing argument for "
3639 "'%c' option\n"), optopt);
3640 usage(B_FALSE);
3641 break;
3642 case '?':
3643 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3644 optopt);
3645 usage(B_FALSE);
3649 argc -= optind;
3650 argv += optind;
3652 if (cachefile && nsearch != 0) {
3653 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
3654 usage(B_FALSE);
3657 if (cachefile && do_scan) {
3658 (void) fprintf(stderr, gettext("-c is incompatible with -s\n"));
3659 usage(B_FALSE);
3662 if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
3663 (void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
3664 usage(B_FALSE);
3667 if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
3668 (void) fprintf(stderr, gettext("-l is only meaningful during "
3669 "an import\n"));
3670 usage(B_FALSE);
3673 if ((dryrun || xtreme_rewind) && !do_rewind) {
3674 (void) fprintf(stderr,
3675 gettext("-n or -X only meaningful with -F\n"));
3676 usage(B_FALSE);
3678 if (dryrun)
3679 rewind_policy = ZPOOL_TRY_REWIND;
3680 else if (do_rewind)
3681 rewind_policy = ZPOOL_DO_REWIND;
3682 if (xtreme_rewind)
3683 rewind_policy |= ZPOOL_EXTREME_REWIND;
3685 /* In the future, we can capture further policy and include it here */
3686 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
3687 nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
3688 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
3689 rewind_policy) != 0)
3690 goto error;
3692 /* check argument count */
3693 if (do_all) {
3694 if (argc != 0) {
3695 (void) fprintf(stderr, gettext("too many arguments\n"));
3696 usage(B_FALSE);
3698 } else {
3699 if (argc > 2) {
3700 (void) fprintf(stderr, gettext("too many arguments\n"));
3701 usage(B_FALSE);
3706 * Check for the effective uid. We do this explicitly here because
3707 * otherwise any attempt to discover pools will silently fail.
3709 if (argc == 0 && geteuid() != 0) {
3710 (void) fprintf(stderr, gettext("cannot "
3711 "discover pools: permission denied\n"));
3713 free(searchdirs);
3714 nvlist_free(props);
3715 nvlist_free(policy);
3716 return (1);
3720 * Depending on the arguments given, we do one of the following:
3722 * <none> Iterate through all pools and display information about
3723 * each one.
3725 * -a Iterate through all pools and try to import each one.
3727 * <id> Find the pool that corresponds to the given GUID/pool
3728 * name and import that one.
3730 * -D Above options applies only to destroyed pools.
3732 if (argc != 0) {
3733 char *endptr;
3735 errno = 0;
3736 searchguid = strtoull(argv[0], &endptr, 10);
3737 if (errno != 0 || *endptr != '\0') {
3738 searchname = argv[0];
3739 searchguid = 0;
3741 pool_specified = B_TRUE;
3744 * User specified a name or guid. Ensure it's unique.
3746 target_exists_args_t search = {searchname, searchguid};
3747 pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
3751 * Check the environment for the preferred search path.
3753 if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
3754 char *dir, *tmp = NULL;
3756 envdup = strdup(env);
3758 for (dir = strtok_r(envdup, ":", &tmp);
3759 dir != NULL;
3760 dir = strtok_r(NULL, ":", &tmp)) {
3761 searchdirs = safe_realloc(searchdirs,
3762 (nsearch + 1) * sizeof (char *));
3763 searchdirs[nsearch++] = dir;
3767 idata.path = searchdirs;
3768 idata.paths = nsearch;
3769 idata.poolname = searchname;
3770 idata.guid = searchguid;
3771 idata.cachefile = cachefile;
3772 idata.scan = do_scan;
3773 idata.policy = policy;
3775 pools = zpool_search_import(g_zfs, &idata, &libzfs_config_ops);
3777 if (pools != NULL && pool_exists &&
3778 (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
3779 (void) fprintf(stderr, gettext("cannot import '%s': "
3780 "a pool with that name already exists\n"),
3781 argv[0]);
3782 (void) fprintf(stderr, gettext("use the form '%s "
3783 "<pool | id> <newpool>' to give it a new name\n"),
3784 "zpool import");
3785 err = 1;
3786 } else if (pools == NULL && pool_exists) {
3787 (void) fprintf(stderr, gettext("cannot import '%s': "
3788 "a pool with that name is already created/imported,\n"),
3789 argv[0]);
3790 (void) fprintf(stderr, gettext("and no additional pools "
3791 "with that name were found\n"));
3792 err = 1;
3793 } else if (pools == NULL) {
3794 if (argc != 0) {
3795 (void) fprintf(stderr, gettext("cannot import '%s': "
3796 "no such pool available\n"), argv[0]);
3798 err = 1;
3801 if (err == 1) {
3802 free(searchdirs);
3803 free(envdup);
3804 nvlist_free(policy);
3805 nvlist_free(pools);
3806 nvlist_free(props);
3807 return (1);
3810 err = import_pools(pools, props, mntopts, flags,
3811 argc >= 1 ? argv[0] : NULL,
3812 argc >= 2 ? argv[1] : NULL,
3813 do_destroyed, pool_specified, do_all, &idata);
3816 * If we're using the cachefile and we failed to import, then
3817 * fallback to scanning the directory for pools that match
3818 * those in the cachefile.
3820 if (err != 0 && cachefile != NULL) {
3821 (void) printf(gettext("cachefile import failed, retrying\n"));
3824 * We use the scan flag to gather the directories that exist
3825 * in the cachefile. If we need to fallback to searching for
3826 * the pool config, we will only search devices in these
3827 * directories.
3829 idata.scan = B_TRUE;
3830 nvlist_free(pools);
3831 pools = zpool_search_import(g_zfs, &idata, &libzfs_config_ops);
3833 err = import_pools(pools, props, mntopts, flags,
3834 argc >= 1 ? argv[0] : NULL,
3835 argc >= 2 ? argv[1] : NULL,
3836 do_destroyed, pool_specified, do_all, &idata);
3839 error:
3840 nvlist_free(props);
3841 nvlist_free(pools);
3842 nvlist_free(policy);
3843 free(searchdirs);
3844 free(envdup);
3846 return (err ? 1 : 0);
3850 * zpool sync [-f] [pool] ...
3852 * -f (undocumented) force uberblock (and config including zpool cache file)
3853 * update.
3855 * Sync the specified pool(s).
3856 * Without arguments "zpool sync" will sync all pools.
3857 * This command initiates TXG sync(s) and will return after the TXG(s) commit.
3860 static int
3861 zpool_do_sync(int argc, char **argv)
3863 int ret;
3864 boolean_t force = B_FALSE;
3866 /* check options */
3867 while ((ret = getopt(argc, argv, "f")) != -1) {
3868 switch (ret) {
3869 case 'f':
3870 force = B_TRUE;
3871 break;
3872 case '?':
3873 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3874 optopt);
3875 usage(B_FALSE);
3879 argc -= optind;
3880 argv += optind;
3882 /* if argc == 0 we will execute zpool_sync_one on all pools */
3883 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
3884 B_FALSE, zpool_sync_one, &force);
3886 return (ret);
3889 typedef struct iostat_cbdata {
3890 uint64_t cb_flags;
3891 int cb_namewidth;
3892 int cb_iteration;
3893 boolean_t cb_verbose;
3894 boolean_t cb_literal;
3895 boolean_t cb_scripted;
3896 zpool_list_t *cb_list;
3897 vdev_cmd_data_list_t *vcdl;
3898 vdev_cbdata_t cb_vdevs;
3899 } iostat_cbdata_t;
3901 /* iostat labels */
3902 typedef struct name_and_columns {
3903 const char *name; /* Column name */
3904 unsigned int columns; /* Center name to this number of columns */
3905 } name_and_columns_t;
3907 #define IOSTAT_MAX_LABELS 15 /* Max number of labels on one line */
3909 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
3911 [IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
3912 {NULL}},
3913 [IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
3914 {"asyncq_wait", 2}, {"scrub", 1}, {"trim", 1}, {"rebuild", 1},
3915 {NULL}},
3916 [IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
3917 {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
3918 {"trimq_write", 2}, {"rebuildq_write", 2}, {NULL}},
3919 [IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
3920 {"asyncq_wait", 2}, {NULL}},
3921 [IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
3922 {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
3923 {"trim", 2}, {"rebuild", 2}, {NULL}},
3926 /* Shorthand - if "columns" field not set, default to 1 column */
3927 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
3929 [IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
3930 {"write"}, {NULL}},
3931 [IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
3932 {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {"wait"},
3933 {NULL}},
3934 [IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
3935 {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
3936 {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
3937 [IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
3938 {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {"rebuild"},
3939 {NULL}},
3940 [IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
3941 {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
3942 {"ind"}, {"agg"}, {NULL}},
3945 static const char *histo_to_title[] = {
3946 [IOS_L_HISTO] = "latency",
3947 [IOS_RQ_HISTO] = "req_size",
3951 * Return the number of labels in a null-terminated name_and_columns_t
3952 * array.
3955 static unsigned int
3956 label_array_len(const name_and_columns_t *labels)
3958 int i = 0;
3960 while (labels[i].name)
3961 i++;
3963 return (i);
3967 * Return the number of strings in a null-terminated string array.
3968 * For example:
3970 * const char foo[] = {"bar", "baz", NULL}
3972 * returns 2
3974 static uint64_t
3975 str_array_len(const char *array[])
3977 uint64_t i = 0;
3978 while (array[i])
3979 i++;
3981 return (i);
3986 * Return a default column width for default/latency/queue columns. This does
3987 * not include histograms, which have their columns autosized.
3989 static unsigned int
3990 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
3992 unsigned long column_width = 5; /* Normal niceprint */
3993 static unsigned long widths[] = {
3995 * Choose some sane default column sizes for printing the
3996 * raw numbers.
3998 [IOS_DEFAULT] = 15, /* 1PB capacity */
3999 [IOS_LATENCY] = 10, /* 1B ns = 10sec */
4000 [IOS_QUEUES] = 6, /* 1M queue entries */
4001 [IOS_L_HISTO] = 10, /* 1B ns = 10sec */
4002 [IOS_RQ_HISTO] = 6, /* 1M queue entries */
4005 if (cb->cb_literal)
4006 column_width = widths[type];
4008 return (column_width);
4012 * Print the column labels, i.e:
4014 * capacity operations bandwidth
4015 * alloc free read write read write ...
4017 * If force_column_width is set, use it for the column width. If not set, use
4018 * the default column width.
4020 static void
4021 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
4022 const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
4024 int i, idx, s;
4025 int text_start, rw_column_width, spaces_to_end;
4026 uint64_t flags = cb->cb_flags;
4027 uint64_t f;
4028 unsigned int column_width = force_column_width;
4030 /* For each bit set in flags */
4031 for (f = flags; f; f &= ~(1ULL << idx)) {
4032 idx = lowbit64(f) - 1;
4033 if (!force_column_width)
4034 column_width = default_column_width(cb, idx);
4035 /* Print our top labels centered over "read write" label. */
4036 for (i = 0; i < label_array_len(labels[idx]); i++) {
4037 const char *name = labels[idx][i].name;
4039 * We treat labels[][].columns == 0 as shorthand
4040 * for one column. It makes writing out the label
4041 * tables more concise.
4043 unsigned int columns = MAX(1, labels[idx][i].columns);
4044 unsigned int slen = strlen(name);
4046 rw_column_width = (column_width * columns) +
4047 (2 * (columns - 1));
4049 text_start = (int)((rw_column_width) / columns -
4050 slen / columns);
4051 if (text_start < 0)
4052 text_start = 0;
4054 printf(" "); /* Two spaces between columns */
4056 /* Space from beginning of column to label */
4057 for (s = 0; s < text_start; s++)
4058 printf(" ");
4060 printf("%s", name);
4062 /* Print space after label to end of column */
4063 spaces_to_end = rw_column_width - text_start - slen;
4064 if (spaces_to_end < 0)
4065 spaces_to_end = 0;
4067 for (s = 0; s < spaces_to_end; s++)
4068 printf(" ");
4075 * print_cmd_columns - Print custom column titles from -c
4077 * If the user specified the "zpool status|iostat -c" then print their custom
4078 * column titles in the header. For example, print_cmd_columns() would print
4079 * the " col1 col2" part of this:
4081 * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
4082 * ...
4083 * capacity operations bandwidth
4084 * pool alloc free read write read write col1 col2
4085 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4086 * mypool 269K 1008M 0 0 107 946
4087 * mirror 269K 1008M 0 0 107 946
4088 * sdb - - 0 0 102 473 val1 val2
4089 * sdc - - 0 0 5 473 val1 val2
4090 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4092 static void
4093 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
4095 int i, j;
4096 vdev_cmd_data_t *data = &vcdl->data[0];
4098 if (vcdl->count == 0 || data == NULL)
4099 return;
4102 * Each vdev cmd should have the same column names unless the user did
4103 * something weird with their cmd. Just take the column names from the
4104 * first vdev and assume it works for all of them.
4106 for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
4107 printf(" ");
4108 if (use_dashes) {
4109 for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
4110 printf("-");
4111 } else {
4112 printf_color(ANSI_BOLD, "%*s", vcdl->uniq_cols_width[i],
4113 vcdl->uniq_cols[i]);
4120 * Utility function to print out a line of dashes like:
4122 * -------------------------------- ----- ----- ----- ----- -----
4124 * ...or a dashed named-row line like:
4126 * logs - - - - -
4128 * @cb: iostat data
4130 * @force_column_width If non-zero, use the value as the column width.
4131 * Otherwise use the default column widths.
4133 * @name: Print a dashed named-row line starting
4134 * with @name. Otherwise, print a regular
4135 * dashed line.
4137 static void
4138 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
4139 const char *name)
4141 int i;
4142 unsigned int namewidth;
4143 uint64_t flags = cb->cb_flags;
4144 uint64_t f;
4145 int idx;
4146 const name_and_columns_t *labels;
4147 const char *title;
4150 if (cb->cb_flags & IOS_ANYHISTO_M) {
4151 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4152 } else if (cb->cb_vdevs.cb_names_count) {
4153 title = "vdev";
4154 } else {
4155 title = "pool";
4158 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4159 name ? strlen(name) : 0);
4162 if (name) {
4163 printf("%-*s", namewidth, name);
4164 } else {
4165 for (i = 0; i < namewidth; i++)
4166 (void) printf("-");
4169 /* For each bit in flags */
4170 for (f = flags; f; f &= ~(1ULL << idx)) {
4171 unsigned int column_width;
4172 idx = lowbit64(f) - 1;
4173 if (force_column_width)
4174 column_width = force_column_width;
4175 else
4176 column_width = default_column_width(cb, idx);
4178 labels = iostat_bottom_labels[idx];
4179 for (i = 0; i < label_array_len(labels); i++) {
4180 if (name)
4181 printf(" %*s-", column_width - 1, " ");
4182 else
4183 printf(" %.*s", column_width,
4184 "--------------------");
4190 static void
4191 print_iostat_separator_impl(iostat_cbdata_t *cb,
4192 unsigned int force_column_width)
4194 print_iostat_dashes(cb, force_column_width, NULL);
4197 static void
4198 print_iostat_separator(iostat_cbdata_t *cb)
4200 print_iostat_separator_impl(cb, 0);
4203 static void
4204 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
4205 const char *histo_vdev_name)
4207 unsigned int namewidth;
4208 const char *title;
4210 if (cb->cb_flags & IOS_ANYHISTO_M) {
4211 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4212 } else if (cb->cb_vdevs.cb_names_count) {
4213 title = "vdev";
4214 } else {
4215 title = "pool";
4218 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4219 histo_vdev_name ? strlen(histo_vdev_name) : 0);
4221 if (histo_vdev_name)
4222 printf("%-*s", namewidth, histo_vdev_name);
4223 else
4224 printf("%*s", namewidth, "");
4227 print_iostat_labels(cb, force_column_width, iostat_top_labels);
4228 printf("\n");
4230 printf("%-*s", namewidth, title);
4232 print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
4233 if (cb->vcdl != NULL)
4234 print_cmd_columns(cb->vcdl, 0);
4236 printf("\n");
4238 print_iostat_separator_impl(cb, force_column_width);
4240 if (cb->vcdl != NULL)
4241 print_cmd_columns(cb->vcdl, 1);
4243 printf("\n");
4246 static void
4247 print_iostat_header(iostat_cbdata_t *cb)
4249 print_iostat_header_impl(cb, 0, NULL);
4254 * Display a single statistic.
4256 static void
4257 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
4258 unsigned int column_size, boolean_t scripted)
4260 char buf[64];
4262 zfs_nicenum_format(value, buf, sizeof (buf), format);
4264 if (scripted)
4265 printf("\t%s", buf);
4266 else
4267 printf(" %*s", column_size, buf);
4271 * Calculate the default vdev stats
4273 * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
4274 * stats into calcvs.
4276 static void
4277 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
4278 vdev_stat_t *calcvs)
4280 int i;
4282 memcpy(calcvs, newvs, sizeof (*calcvs));
4283 for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
4284 calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
4286 for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
4287 calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
4291 * Internal representation of the extended iostats data.
4293 * The extended iostat stats are exported in nvlists as either uint64_t arrays
4294 * or single uint64_t's. We make both look like arrays to make them easier
4295 * to process. In order to make single uint64_t's look like arrays, we set
4296 * __data to the stat data, and then set *data = &__data with count = 1. Then,
4297 * we can just use *data and count.
4299 struct stat_array {
4300 uint64_t *data;
4301 uint_t count; /* Number of entries in data[] */
4302 uint64_t __data; /* Only used when data is a single uint64_t */
4305 static uint64_t
4306 stat_histo_max(struct stat_array *nva, unsigned int len)
4308 uint64_t max = 0;
4309 int i;
4310 for (i = 0; i < len; i++)
4311 max = MAX(max, array64_max(nva[i].data, nva[i].count));
4313 return (max);
4317 * Helper function to lookup a uint64_t array or uint64_t value and store its
4318 * data as a stat_array. If the nvpair is a single uint64_t value, then we make
4319 * it look like a one element array to make it easier to process.
4321 static int
4322 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
4323 struct stat_array *nva)
4325 nvpair_t *tmp;
4326 int ret;
4328 verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
4329 switch (nvpair_type(tmp)) {
4330 case DATA_TYPE_UINT64_ARRAY:
4331 ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
4332 break;
4333 case DATA_TYPE_UINT64:
4334 ret = nvpair_value_uint64(tmp, &nva->__data);
4335 nva->data = &nva->__data;
4336 nva->count = 1;
4337 break;
4338 default:
4339 /* Not a uint64_t */
4340 ret = EINVAL;
4341 break;
4344 return (ret);
4348 * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
4349 * subtract them, and return the results in a newly allocated stat_array.
4350 * You must free the returned array after you are done with it with
4351 * free_calc_stats().
4353 * Additionally, you can set "oldnv" to NULL if you simply want the newnv
4354 * values.
4356 static struct stat_array *
4357 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
4358 nvlist_t *newnv)
4360 nvlist_t *oldnvx = NULL, *newnvx;
4361 struct stat_array *oldnva, *newnva, *calcnva;
4362 int i, j;
4363 unsigned int alloc_size = (sizeof (struct stat_array)) * len;
4365 /* Extract our extended stats nvlist from the main list */
4366 verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
4367 &newnvx) == 0);
4368 if (oldnv) {
4369 verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
4370 &oldnvx) == 0);
4373 newnva = safe_malloc(alloc_size);
4374 oldnva = safe_malloc(alloc_size);
4375 calcnva = safe_malloc(alloc_size);
4377 for (j = 0; j < len; j++) {
4378 verify(nvpair64_to_stat_array(newnvx, names[j],
4379 &newnva[j]) == 0);
4380 calcnva[j].count = newnva[j].count;
4381 alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
4382 calcnva[j].data = safe_malloc(alloc_size);
4383 memcpy(calcnva[j].data, newnva[j].data, alloc_size);
4385 if (oldnvx) {
4386 verify(nvpair64_to_stat_array(oldnvx, names[j],
4387 &oldnva[j]) == 0);
4388 for (i = 0; i < oldnva[j].count; i++)
4389 calcnva[j].data[i] -= oldnva[j].data[i];
4392 free(newnva);
4393 free(oldnva);
4394 return (calcnva);
4397 static void
4398 free_calc_stats(struct stat_array *nva, unsigned int len)
4400 int i;
4401 for (i = 0; i < len; i++)
4402 free(nva[i].data);
4404 free(nva);
4407 static void
4408 print_iostat_histo(struct stat_array *nva, unsigned int len,
4409 iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
4410 double scale)
4412 int i, j;
4413 char buf[6];
4414 uint64_t val;
4415 enum zfs_nicenum_format format;
4416 unsigned int buckets;
4417 unsigned int start_bucket;
4419 if (cb->cb_literal)
4420 format = ZFS_NICENUM_RAW;
4421 else
4422 format = ZFS_NICENUM_1024;
4424 /* All these histos are the same size, so just use nva[0].count */
4425 buckets = nva[0].count;
4427 if (cb->cb_flags & IOS_RQ_HISTO_M) {
4428 /* Start at 512 - req size should never be lower than this */
4429 start_bucket = 9;
4430 } else {
4431 start_bucket = 0;
4434 for (j = start_bucket; j < buckets; j++) {
4435 /* Print histogram bucket label */
4436 if (cb->cb_flags & IOS_L_HISTO_M) {
4437 /* Ending range of this bucket */
4438 val = (1UL << (j + 1)) - 1;
4439 zfs_nicetime(val, buf, sizeof (buf));
4440 } else {
4441 /* Request size (starting range of bucket) */
4442 val = (1UL << j);
4443 zfs_nicenum(val, buf, sizeof (buf));
4446 if (cb->cb_scripted)
4447 printf("%llu", (u_longlong_t)val);
4448 else
4449 printf("%-*s", namewidth, buf);
4451 /* Print the values on the line */
4452 for (i = 0; i < len; i++) {
4453 print_one_stat(nva[i].data[j] * scale, format,
4454 column_width, cb->cb_scripted);
4456 printf("\n");
4460 static void
4461 print_solid_separator(unsigned int length)
4463 while (length--)
4464 printf("-");
4465 printf("\n");
4468 static void
4469 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
4470 nvlist_t *newnv, double scale, const char *name)
4472 unsigned int column_width;
4473 unsigned int namewidth;
4474 unsigned int entire_width;
4475 enum iostat_type type;
4476 struct stat_array *nva;
4477 const char **names;
4478 unsigned int names_len;
4480 /* What type of histo are we? */
4481 type = IOS_HISTO_IDX(cb->cb_flags);
4483 /* Get NULL-terminated array of nvlist names for our histo */
4484 names = vsx_type_to_nvlist[type];
4485 names_len = str_array_len(names); /* num of names */
4487 nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
4489 if (cb->cb_literal) {
4490 column_width = MAX(5,
4491 (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
4492 } else {
4493 column_width = 5;
4496 namewidth = MAX(cb->cb_namewidth,
4497 strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
4500 * Calculate the entire line width of what we're printing. The
4501 * +2 is for the two spaces between columns:
4503 /* read write */
4504 /* ----- ----- */
4505 /* |___| <---------- column_width */
4506 /* */
4507 /* |__________| <--- entire_width */
4508 /* */
4509 entire_width = namewidth + (column_width + 2) *
4510 label_array_len(iostat_bottom_labels[type]);
4512 if (cb->cb_scripted)
4513 printf("%s\n", name);
4514 else
4515 print_iostat_header_impl(cb, column_width, name);
4517 print_iostat_histo(nva, names_len, cb, column_width,
4518 namewidth, scale);
4520 free_calc_stats(nva, names_len);
4521 if (!cb->cb_scripted)
4522 print_solid_separator(entire_width);
4526 * Calculate the average latency of a power-of-two latency histogram
4528 static uint64_t
4529 single_histo_average(uint64_t *histo, unsigned int buckets)
4531 int i;
4532 uint64_t count = 0, total = 0;
4534 for (i = 0; i < buckets; i++) {
4536 * Our buckets are power-of-two latency ranges. Use the
4537 * midpoint latency of each bucket to calculate the average.
4538 * For example:
4540 * Bucket Midpoint
4541 * 8ns-15ns: 12ns
4542 * 16ns-31ns: 24ns
4543 * ...
4545 if (histo[i] != 0) {
4546 total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
4547 count += histo[i];
4551 /* Prevent divide by zero */
4552 return (count == 0 ? 0 : total / count);
4555 static void
4556 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *newnv)
4558 const char *names[] = {
4559 ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
4560 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
4561 ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
4562 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
4563 ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
4564 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
4565 ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
4566 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
4567 ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
4568 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
4569 ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
4570 ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
4571 ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
4572 ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
4575 struct stat_array *nva;
4577 unsigned int column_width = default_column_width(cb, IOS_QUEUES);
4578 enum zfs_nicenum_format format;
4580 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
4582 if (cb->cb_literal)
4583 format = ZFS_NICENUM_RAW;
4584 else
4585 format = ZFS_NICENUM_1024;
4587 for (int i = 0; i < ARRAY_SIZE(names); i++) {
4588 uint64_t val = nva[i].data[0];
4589 print_one_stat(val, format, column_width, cb->cb_scripted);
4592 free_calc_stats(nva, ARRAY_SIZE(names));
4595 static void
4596 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
4597 nvlist_t *newnv)
4599 int i;
4600 uint64_t val;
4601 const char *names[] = {
4602 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
4603 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
4604 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
4605 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
4606 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
4607 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
4608 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
4609 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
4610 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
4611 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
4612 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
4614 struct stat_array *nva;
4616 unsigned int column_width = default_column_width(cb, IOS_LATENCY);
4617 enum zfs_nicenum_format format;
4619 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
4621 if (cb->cb_literal)
4622 format = ZFS_NICENUM_RAWTIME;
4623 else
4624 format = ZFS_NICENUM_TIME;
4626 /* Print our avg latencies on the line */
4627 for (i = 0; i < ARRAY_SIZE(names); i++) {
4628 /* Compute average latency for a latency histo */
4629 val = single_histo_average(nva[i].data, nva[i].count);
4630 print_one_stat(val, format, column_width, cb->cb_scripted);
4632 free_calc_stats(nva, ARRAY_SIZE(names));
4636 * Print default statistics (capacity/operations/bandwidth)
4638 static void
4639 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
4641 unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
4642 enum zfs_nicenum_format format;
4643 char na; /* char to print for "not applicable" values */
4645 if (cb->cb_literal) {
4646 format = ZFS_NICENUM_RAW;
4647 na = '0';
4648 } else {
4649 format = ZFS_NICENUM_1024;
4650 na = '-';
4653 /* only toplevel vdevs have capacity stats */
4654 if (vs->vs_space == 0) {
4655 if (cb->cb_scripted)
4656 printf("\t%c\t%c", na, na);
4657 else
4658 printf(" %*c %*c", column_width, na, column_width,
4659 na);
4660 } else {
4661 print_one_stat(vs->vs_alloc, format, column_width,
4662 cb->cb_scripted);
4663 print_one_stat(vs->vs_space - vs->vs_alloc, format,
4664 column_width, cb->cb_scripted);
4667 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
4668 format, column_width, cb->cb_scripted);
4669 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
4670 format, column_width, cb->cb_scripted);
4671 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
4672 format, column_width, cb->cb_scripted);
4673 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
4674 format, column_width, cb->cb_scripted);
4677 static const char *const class_name[] = {
4678 VDEV_ALLOC_BIAS_DEDUP,
4679 VDEV_ALLOC_BIAS_SPECIAL,
4680 VDEV_ALLOC_CLASS_LOGS
4684 * Print out all the statistics for the given vdev. This can either be the
4685 * toplevel configuration, or called recursively. If 'name' is NULL, then this
4686 * is a verbose output, and we don't want to display the toplevel pool stats.
4688 * Returns the number of stat lines printed.
4690 static unsigned int
4691 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
4692 nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
4694 nvlist_t **oldchild, **newchild;
4695 uint_t c, children, oldchildren;
4696 vdev_stat_t *oldvs, *newvs, *calcvs;
4697 vdev_stat_t zerovs = { 0 };
4698 char *vname;
4699 int i;
4700 int ret = 0;
4701 uint64_t tdelta;
4702 double scale;
4704 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
4705 return (ret);
4707 calcvs = safe_malloc(sizeof (*calcvs));
4709 if (oldnv != NULL) {
4710 verify(nvlist_lookup_uint64_array(oldnv,
4711 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
4712 } else {
4713 oldvs = &zerovs;
4716 /* Do we only want to see a specific vdev? */
4717 for (i = 0; i < cb->cb_vdevs.cb_names_count; i++) {
4718 /* Yes we do. Is this the vdev? */
4719 if (strcmp(name, cb->cb_vdevs.cb_names[i]) == 0) {
4721 * This is our vdev. Since it is the only vdev we
4722 * will be displaying, make depth = 0 so that it
4723 * doesn't get indented.
4725 depth = 0;
4726 break;
4730 if (cb->cb_vdevs.cb_names_count && (i == cb->cb_vdevs.cb_names_count)) {
4731 /* Couldn't match the name */
4732 goto children;
4736 verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
4737 (uint64_t **)&newvs, &c) == 0);
4740 * Print the vdev name unless it's is a histogram. Histograms
4741 * display the vdev name in the header itself.
4743 if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
4744 if (cb->cb_scripted) {
4745 printf("%s", name);
4746 } else {
4747 if (strlen(name) + depth > cb->cb_namewidth)
4748 (void) printf("%*s%s", depth, "", name);
4749 else
4750 (void) printf("%*s%s%*s", depth, "", name,
4751 (int)(cb->cb_namewidth - strlen(name) -
4752 depth), "");
4756 /* Calculate our scaling factor */
4757 tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
4758 if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
4760 * If we specify printing histograms with no time interval, then
4761 * print the histogram numbers over the entire lifetime of the
4762 * vdev.
4764 scale = 1;
4765 } else {
4766 if (tdelta == 0)
4767 scale = 1.0;
4768 else
4769 scale = (double)NANOSEC / tdelta;
4772 if (cb->cb_flags & IOS_DEFAULT_M) {
4773 calc_default_iostats(oldvs, newvs, calcvs);
4774 print_iostat_default(calcvs, cb, scale);
4776 if (cb->cb_flags & IOS_LATENCY_M)
4777 print_iostat_latency(cb, oldnv, newnv);
4778 if (cb->cb_flags & IOS_QUEUES_M)
4779 print_iostat_queues(cb, newnv);
4780 if (cb->cb_flags & IOS_ANYHISTO_M) {
4781 printf("\n");
4782 print_iostat_histos(cb, oldnv, newnv, scale, name);
4785 if (cb->vcdl != NULL) {
4786 char *path;
4787 if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
4788 &path) == 0) {
4789 printf(" ");
4790 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
4794 if (!(cb->cb_flags & IOS_ANYHISTO_M))
4795 printf("\n");
4797 ret++;
4799 children:
4801 free(calcvs);
4803 if (!cb->cb_verbose)
4804 return (ret);
4806 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
4807 &newchild, &children) != 0)
4808 return (ret);
4810 if (oldnv) {
4811 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
4812 &oldchild, &oldchildren) != 0)
4813 return (ret);
4815 children = MIN(oldchildren, children);
4819 * print normal top-level devices
4821 for (c = 0; c < children; c++) {
4822 uint64_t ishole = B_FALSE, islog = B_FALSE;
4824 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
4825 &ishole);
4827 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
4828 &islog);
4830 if (ishole || islog)
4831 continue;
4833 if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
4834 continue;
4836 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4837 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
4838 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
4839 newchild[c], cb, depth + 2);
4840 free(vname);
4844 * print all other top-level devices
4846 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
4847 boolean_t printed = B_FALSE;
4849 for (c = 0; c < children; c++) {
4850 uint64_t islog = B_FALSE;
4851 char *bias = NULL;
4852 char *type = NULL;
4854 (void) nvlist_lookup_uint64(newchild[c],
4855 ZPOOL_CONFIG_IS_LOG, &islog);
4856 if (islog) {
4857 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
4858 } else {
4859 (void) nvlist_lookup_string(newchild[c],
4860 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
4861 (void) nvlist_lookup_string(newchild[c],
4862 ZPOOL_CONFIG_TYPE, &type);
4864 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
4865 continue;
4866 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
4867 continue;
4869 if (!printed) {
4870 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
4871 !cb->cb_scripted &&
4872 !cb->cb_vdevs.cb_names) {
4873 print_iostat_dashes(cb, 0,
4874 class_name[n]);
4876 printf("\n");
4877 printed = B_TRUE;
4880 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4881 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
4882 ret += print_vdev_stats(zhp, vname, oldnv ?
4883 oldchild[c] : NULL, newchild[c], cb, depth + 2);
4884 free(vname);
4889 * Include level 2 ARC devices in iostat output
4891 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
4892 &newchild, &children) != 0)
4893 return (ret);
4895 if (oldnv) {
4896 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
4897 &oldchild, &oldchildren) != 0)
4898 return (ret);
4900 children = MIN(oldchildren, children);
4903 if (children > 0) {
4904 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
4905 !cb->cb_vdevs.cb_names) {
4906 print_iostat_dashes(cb, 0, "cache");
4908 printf("\n");
4910 for (c = 0; c < children; c++) {
4911 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4912 cb->cb_vdevs.cb_name_flags);
4913 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
4914 : NULL, newchild[c], cb, depth + 2);
4915 free(vname);
4919 return (ret);
4922 static int
4923 refresh_iostat(zpool_handle_t *zhp, void *data)
4925 iostat_cbdata_t *cb = data;
4926 boolean_t missing;
4929 * If the pool has disappeared, remove it from the list and continue.
4931 if (zpool_refresh_stats(zhp, &missing) != 0)
4932 return (-1);
4934 if (missing)
4935 pool_list_remove(cb->cb_list, zhp);
4937 return (0);
4941 * Callback to print out the iostats for the given pool.
4943 static int
4944 print_iostat(zpool_handle_t *zhp, void *data)
4946 iostat_cbdata_t *cb = data;
4947 nvlist_t *oldconfig, *newconfig;
4948 nvlist_t *oldnvroot, *newnvroot;
4949 int ret;
4951 newconfig = zpool_get_config(zhp, &oldconfig);
4953 if (cb->cb_iteration == 1)
4954 oldconfig = NULL;
4956 verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
4957 &newnvroot) == 0);
4959 if (oldconfig == NULL)
4960 oldnvroot = NULL;
4961 else
4962 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
4963 &oldnvroot) == 0);
4965 ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
4966 cb, 0);
4967 if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
4968 !cb->cb_scripted && cb->cb_verbose &&
4969 !cb->cb_vdevs.cb_names_count) {
4970 print_iostat_separator(cb);
4971 if (cb->vcdl != NULL) {
4972 print_cmd_columns(cb->vcdl, 1);
4974 printf("\n");
4977 return (ret);
4980 static int
4981 get_columns(void)
4983 struct winsize ws;
4984 int columns = 80;
4985 int error;
4987 if (isatty(STDOUT_FILENO)) {
4988 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
4989 if (error == 0)
4990 columns = ws.ws_col;
4991 } else {
4992 columns = 999;
4995 return (columns);
4999 * Return the required length of the pool/vdev name column. The minimum
5000 * allowed width and output formatting flags must be provided.
5002 static int
5003 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
5005 nvlist_t *config, *nvroot;
5006 int width = min_width;
5008 if ((config = zpool_get_config(zhp, NULL)) != NULL) {
5009 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5010 &nvroot) == 0);
5011 size_t poolname_len = strlen(zpool_get_name(zhp));
5012 if (verbose == B_FALSE) {
5013 width = MAX(poolname_len, min_width);
5014 } else {
5015 width = MAX(poolname_len,
5016 max_width(zhp, nvroot, 0, min_width, flags));
5020 return (width);
5024 * Parse the input string, get the 'interval' and 'count' value if there is one.
5026 static void
5027 get_interval_count(int *argcp, char **argv, float *iv,
5028 unsigned long *cnt)
5030 float interval = 0;
5031 unsigned long count = 0;
5032 int argc = *argcp;
5035 * Determine if the last argument is an integer or a pool name
5037 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5038 char *end;
5040 errno = 0;
5041 interval = strtof(argv[argc - 1], &end);
5043 if (*end == '\0' && errno == 0) {
5044 if (interval == 0) {
5045 (void) fprintf(stderr, gettext(
5046 "interval cannot be zero\n"));
5047 usage(B_FALSE);
5050 * Ignore the last parameter
5052 argc--;
5053 } else {
5055 * If this is not a valid number, just plow on. The
5056 * user will get a more informative error message later
5057 * on.
5059 interval = 0;
5064 * If the last argument is also an integer, then we have both a count
5065 * and an interval.
5067 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5068 char *end;
5070 errno = 0;
5071 count = interval;
5072 interval = strtof(argv[argc - 1], &end);
5074 if (*end == '\0' && errno == 0) {
5075 if (interval == 0) {
5076 (void) fprintf(stderr, gettext(
5077 "interval cannot be zero\n"));
5078 usage(B_FALSE);
5082 * Ignore the last parameter
5084 argc--;
5085 } else {
5086 interval = 0;
5090 *iv = interval;
5091 *cnt = count;
5092 *argcp = argc;
5095 static void
5096 get_timestamp_arg(char c)
5098 if (c == 'u')
5099 timestamp_fmt = UDATE;
5100 else if (c == 'd')
5101 timestamp_fmt = DDATE;
5102 else
5103 usage(B_FALSE);
5107 * Return stat flags that are supported by all pools by both the module and
5108 * zpool iostat. "*data" should be initialized to all 0xFFs before running.
5109 * It will get ANDed down until only the flags that are supported on all pools
5110 * remain.
5112 static int
5113 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
5115 uint64_t *mask = data;
5116 nvlist_t *config, *nvroot, *nvx;
5117 uint64_t flags = 0;
5118 int i, j;
5120 config = zpool_get_config(zhp, NULL);
5121 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5122 &nvroot) == 0);
5124 /* Default stats are always supported, but for completeness.. */
5125 if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
5126 flags |= IOS_DEFAULT_M;
5128 /* Get our extended stats nvlist from the main list */
5129 if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
5130 &nvx) != 0) {
5132 * No extended stats; they're probably running an older
5133 * module. No big deal, we support that too.
5135 goto end;
5138 /* For each extended stat, make sure all its nvpairs are supported */
5139 for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
5140 if (!vsx_type_to_nvlist[j][0])
5141 continue;
5143 /* Start off by assuming the flag is supported, then check */
5144 flags |= (1ULL << j);
5145 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
5146 if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
5147 /* flag isn't supported */
5148 flags = flags & ~(1ULL << j);
5149 break;
5153 end:
5154 *mask = *mask & flags;
5155 return (0);
5159 * Return a bitmask of stats that are supported on all pools by both the module
5160 * and zpool iostat.
5162 static uint64_t
5163 get_stat_flags(zpool_list_t *list)
5165 uint64_t mask = -1;
5168 * get_stat_flags_cb() will lop off bits from "mask" until only the
5169 * flags that are supported on all pools remain.
5171 pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
5172 return (mask);
5176 * Return 1 if cb_data->cb_names[0] is this vdev's name, 0 otherwise.
5178 static int
5179 is_vdev_cb(void *zhp_data, nvlist_t *nv, void *cb_data)
5181 vdev_cbdata_t *cb = cb_data;
5182 char *name = NULL;
5183 int ret = 1; /* assume match */
5184 zpool_handle_t *zhp = zhp_data;
5186 name = zpool_vdev_name(g_zfs, zhp, nv, cb->cb_name_flags);
5188 if (strcmp(name, cb->cb_names[0])) {
5189 free(name);
5190 name = zpool_vdev_name(g_zfs, zhp, nv, VDEV_NAME_GUID);
5191 ret = (strcmp(name, cb->cb_names[0]) == 0);
5193 free(name);
5195 return (ret);
5199 * Returns 1 if cb_data->cb_names[0] is a vdev name, 0 otherwise.
5201 static int
5202 is_vdev(zpool_handle_t *zhp, void *cb_data)
5204 return (for_each_vdev(zhp, is_vdev_cb, cb_data));
5208 * Check if vdevs are in a pool
5210 * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
5211 * return 0. If pool_name is NULL, then search all pools.
5213 static int
5214 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
5215 vdev_cbdata_t *cb)
5217 char **tmp_name;
5218 int ret = 0;
5219 int i;
5220 int pool_count = 0;
5222 if ((argc == 0) || !*argv)
5223 return (0);
5225 if (pool_name)
5226 pool_count = 1;
5228 /* Temporarily hijack cb_names for a second... */
5229 tmp_name = cb->cb_names;
5231 /* Go though our list of prospective vdev names */
5232 for (i = 0; i < argc; i++) {
5233 cb->cb_names = argv + i;
5235 /* Is this name a vdev in our pools? */
5236 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
5237 ZFS_TYPE_POOL, B_FALSE, is_vdev, cb);
5238 if (!ret) {
5239 /* No match */
5240 break;
5244 cb->cb_names = tmp_name;
5246 return (ret);
5249 static int
5250 is_pool_cb(zpool_handle_t *zhp, void *data)
5252 char *name = data;
5253 if (strcmp(name, zpool_get_name(zhp)) == 0)
5254 return (1);
5256 return (0);
5260 * Do we have a pool named *name? If so, return 1, otherwise 0.
5262 static int
5263 is_pool(char *name)
5265 return (for_each_pool(0, NULL, B_TRUE, NULL, ZFS_TYPE_POOL, B_FALSE,
5266 is_pool_cb, name));
5269 /* Are all our argv[] strings pool names? If so return 1, 0 otherwise. */
5270 static int
5271 are_all_pools(int argc, char **argv)
5273 if ((argc == 0) || !*argv)
5274 return (0);
5276 while (--argc >= 0)
5277 if (!is_pool(argv[argc]))
5278 return (0);
5280 return (1);
5284 * Helper function to print out vdev/pool names we can't resolve. Used for an
5285 * error message.
5287 static void
5288 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
5289 vdev_cbdata_t *cb)
5291 int i;
5292 char *name;
5293 char *str;
5294 for (i = 0; i < argc; i++) {
5295 name = argv[i];
5297 if (is_pool(name))
5298 str = gettext("pool");
5299 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
5300 str = gettext("vdev in this pool");
5301 else if (are_vdevs_in_pool(1, &name, NULL, cb))
5302 str = gettext("vdev in another pool");
5303 else
5304 str = gettext("unknown");
5306 fprintf(stderr, "\t%s (%s)\n", name, str);
5311 * Same as get_interval_count(), but with additional checks to not misinterpret
5312 * guids as interval/count values. Assumes VDEV_NAME_GUID is set in
5313 * cb.cb_vdevs.cb_name_flags.
5315 static void
5316 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
5317 unsigned long *count, iostat_cbdata_t *cb)
5319 char **tmpargv = argv;
5320 int argc_for_interval = 0;
5322 /* Is the last arg an interval value? Or a guid? */
5323 if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL,
5324 &cb->cb_vdevs)) {
5326 * The last arg is not a guid, so it's probably an
5327 * interval value.
5329 argc_for_interval++;
5331 if (*argc >= 2 &&
5332 !are_vdevs_in_pool(1, &argv[*argc - 2], NULL,
5333 &cb->cb_vdevs)) {
5335 * The 2nd to last arg is not a guid, so it's probably
5336 * an interval value.
5338 argc_for_interval++;
5342 /* Point to our list of possible intervals */
5343 tmpargv = &argv[*argc - argc_for_interval];
5345 *argc = *argc - argc_for_interval;
5346 get_interval_count(&argc_for_interval, tmpargv,
5347 interval, count);
5351 * Floating point sleep(). Allows you to pass in a floating point value for
5352 * seconds.
5354 static void
5355 fsleep(float sec)
5357 struct timespec req;
5358 req.tv_sec = floor(sec);
5359 req.tv_nsec = (sec - (float)req.tv_sec) * NANOSEC;
5360 nanosleep(&req, NULL);
5364 * Terminal height, in rows. Returns -1 if stdout is not connected to a TTY or
5365 * if we were unable to determine its size.
5367 static int
5368 terminal_height(void)
5370 struct winsize win;
5372 if (isatty(STDOUT_FILENO) == 0)
5373 return (-1);
5375 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_row > 0)
5376 return (win.ws_row);
5378 return (-1);
5382 * Run one of the zpool status/iostat -c scripts with the help (-h) option and
5383 * print the result.
5385 * name: Short name of the script ('iostat').
5386 * path: Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
5388 static void
5389 print_zpool_script_help(char *name, char *path)
5391 char *argv[] = {path, (char *)"-h", NULL};
5392 char **lines = NULL;
5393 int lines_cnt = 0;
5394 int rc;
5396 rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
5397 &lines_cnt);
5398 if (rc != 0 || lines == NULL || lines_cnt <= 0) {
5399 if (lines != NULL)
5400 libzfs_free_str_array(lines, lines_cnt);
5401 return;
5404 for (int i = 0; i < lines_cnt; i++)
5405 if (!is_blank_str(lines[i]))
5406 printf(" %-14s %s\n", name, lines[i]);
5408 libzfs_free_str_array(lines, lines_cnt);
5412 * Go though the zpool status/iostat -c scripts in the user's path, run their
5413 * help option (-h), and print out the results.
5415 static void
5416 print_zpool_dir_scripts(char *dirpath)
5418 DIR *dir;
5419 struct dirent *ent;
5420 char fullpath[MAXPATHLEN];
5421 struct stat dir_stat;
5423 if ((dir = opendir(dirpath)) != NULL) {
5424 /* print all the files and directories within directory */
5425 while ((ent = readdir(dir)) != NULL) {
5426 sprintf(fullpath, "%s/%s", dirpath, ent->d_name);
5428 /* Print the scripts */
5429 if (stat(fullpath, &dir_stat) == 0)
5430 if (dir_stat.st_mode & S_IXUSR &&
5431 S_ISREG(dir_stat.st_mode))
5432 print_zpool_script_help(ent->d_name,
5433 fullpath);
5435 closedir(dir);
5440 * Print out help text for all zpool status/iostat -c scripts.
5442 static void
5443 print_zpool_script_list(const char *subcommand)
5445 char *dir, *sp, *tmp;
5447 printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
5449 sp = zpool_get_cmd_search_path();
5450 if (sp == NULL)
5451 return;
5453 for (dir = strtok_r(sp, ":", &tmp);
5454 dir != NULL;
5455 dir = strtok_r(NULL, ":", &tmp))
5456 print_zpool_dir_scripts(dir);
5458 free(sp);
5462 * Set the minimum pool/vdev name column width. The width must be at least 10,
5463 * but may be as large as the column width - 42 so it still fits on one line.
5464 * NOTE: 42 is the width of the default capacity/operations/bandwidth output
5466 static int
5467 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
5469 iostat_cbdata_t *cb = data;
5470 int width, available_width;
5473 * get_namewidth() returns the maximum width of any name in that column
5474 * for any pool/vdev/device line that will be output.
5476 width = get_namewidth(zhp, cb->cb_namewidth,
5477 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
5480 * The width we are calculating is the width of the header and also the
5481 * padding width for names that are less than maximum width. The stats
5482 * take up 42 characters, so the width available for names is:
5484 available_width = get_columns() - 42;
5487 * If the maximum width fits on a screen, then great! Make everything
5488 * line up by justifying all lines to the same width. If that max
5489 * width is larger than what's available, the name plus stats won't fit
5490 * on one line, and justifying to that width would cause every line to
5491 * wrap on the screen. We only want lines with long names to wrap.
5492 * Limit the padding to what won't wrap.
5494 if (width > available_width)
5495 width = available_width;
5498 * And regardless of whatever the screen width is (get_columns can
5499 * return 0 if the width is not known or less than 42 for a narrow
5500 * terminal) have the width be a minimum of 10.
5502 if (width < 10)
5503 width = 10;
5505 /* Save the calculated width */
5506 cb->cb_namewidth = width;
5508 return (0);
5512 * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
5513 * [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
5514 * [interval [count]]
5516 * -c CMD For each vdev, run command CMD
5517 * -g Display guid for individual vdev name.
5518 * -L Follow links when resolving vdev path name.
5519 * -P Display full path for vdev name.
5520 * -v Display statistics for individual vdevs
5521 * -h Display help
5522 * -p Display values in parsable (exact) format.
5523 * -H Scripted mode. Don't display headers, and separate properties
5524 * by a single tab.
5525 * -l Display average latency
5526 * -q Display queue depths
5527 * -w Display latency histograms
5528 * -r Display request size histogram
5529 * -T Display a timestamp in date(1) or Unix format
5530 * -n Only print headers once
5532 * This command can be tricky because we want to be able to deal with pool
5533 * creation/destruction as well as vdev configuration changes. The bulk of this
5534 * processing is handled by the pool_list_* routines in zpool_iter.c. We rely
5535 * on pool_list_update() to detect the addition of new pools. Configuration
5536 * changes are all handled within libzfs.
5539 zpool_do_iostat(int argc, char **argv)
5541 int c;
5542 int ret;
5543 int npools;
5544 float interval = 0;
5545 unsigned long count = 0;
5546 int winheight = 24;
5547 zpool_list_t *list;
5548 boolean_t verbose = B_FALSE;
5549 boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
5550 boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
5551 boolean_t omit_since_boot = B_FALSE;
5552 boolean_t guid = B_FALSE;
5553 boolean_t follow_links = B_FALSE;
5554 boolean_t full_name = B_FALSE;
5555 boolean_t headers_once = B_FALSE;
5556 iostat_cbdata_t cb = { 0 };
5557 char *cmd = NULL;
5559 /* Used for printing error message */
5560 const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
5561 [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
5563 uint64_t unsupported_flags;
5565 /* check options */
5566 while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwnH")) != -1) {
5567 switch (c) {
5568 case 'c':
5569 if (cmd != NULL) {
5570 fprintf(stderr,
5571 gettext("Can't set -c flag twice\n"));
5572 exit(1);
5575 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
5576 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
5577 fprintf(stderr, gettext(
5578 "Can't run -c, disabled by "
5579 "ZPOOL_SCRIPTS_ENABLED.\n"));
5580 exit(1);
5583 if ((getuid() <= 0 || geteuid() <= 0) &&
5584 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
5585 fprintf(stderr, gettext(
5586 "Can't run -c with root privileges "
5587 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
5588 exit(1);
5590 cmd = optarg;
5591 verbose = B_TRUE;
5592 break;
5593 case 'g':
5594 guid = B_TRUE;
5595 break;
5596 case 'L':
5597 follow_links = B_TRUE;
5598 break;
5599 case 'P':
5600 full_name = B_TRUE;
5601 break;
5602 case 'T':
5603 get_timestamp_arg(*optarg);
5604 break;
5605 case 'v':
5606 verbose = B_TRUE;
5607 break;
5608 case 'p':
5609 parsable = B_TRUE;
5610 break;
5611 case 'l':
5612 latency = B_TRUE;
5613 break;
5614 case 'q':
5615 queues = B_TRUE;
5616 break;
5617 case 'H':
5618 scripted = B_TRUE;
5619 break;
5620 case 'w':
5621 l_histo = B_TRUE;
5622 break;
5623 case 'r':
5624 rq_histo = B_TRUE;
5625 break;
5626 case 'y':
5627 omit_since_boot = B_TRUE;
5628 break;
5629 case 'n':
5630 headers_once = B_TRUE;
5631 break;
5632 case 'h':
5633 usage(B_FALSE);
5634 break;
5635 case '?':
5636 if (optopt == 'c') {
5637 print_zpool_script_list("iostat");
5638 exit(0);
5639 } else {
5640 fprintf(stderr,
5641 gettext("invalid option '%c'\n"), optopt);
5643 usage(B_FALSE);
5647 argc -= optind;
5648 argv += optind;
5650 cb.cb_literal = parsable;
5651 cb.cb_scripted = scripted;
5653 if (guid)
5654 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_GUID;
5655 if (follow_links)
5656 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
5657 if (full_name)
5658 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_PATH;
5659 cb.cb_iteration = 0;
5660 cb.cb_namewidth = 0;
5661 cb.cb_verbose = verbose;
5663 /* Get our interval and count values (if any) */
5664 if (guid) {
5665 get_interval_count_filter_guids(&argc, argv, &interval,
5666 &count, &cb);
5667 } else {
5668 get_interval_count(&argc, argv, &interval, &count);
5671 if (argc == 0) {
5672 /* No args, so just print the defaults. */
5673 } else if (are_all_pools(argc, argv)) {
5674 /* All the args are pool names */
5675 } else if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
5676 /* All the args are vdevs */
5677 cb.cb_vdevs.cb_names = argv;
5678 cb.cb_vdevs.cb_names_count = argc;
5679 argc = 0; /* No pools to process */
5680 } else if (are_all_pools(1, argv)) {
5681 /* The first arg is a pool name */
5682 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
5683 &cb.cb_vdevs)) {
5684 /* ...and the rest are vdev names */
5685 cb.cb_vdevs.cb_names = argv + 1;
5686 cb.cb_vdevs.cb_names_count = argc - 1;
5687 argc = 1; /* One pool to process */
5688 } else {
5689 fprintf(stderr, gettext("Expected either a list of "));
5690 fprintf(stderr, gettext("pools, or list of vdevs in"));
5691 fprintf(stderr, " \"%s\", ", argv[0]);
5692 fprintf(stderr, gettext("but got:\n"));
5693 error_list_unresolved_vdevs(argc - 1, argv + 1,
5694 argv[0], &cb.cb_vdevs);
5695 fprintf(stderr, "\n");
5696 usage(B_FALSE);
5697 return (1);
5699 } else {
5701 * The args don't make sense. The first arg isn't a pool name,
5702 * nor are all the args vdevs.
5704 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
5705 fprintf(stderr, "\n");
5706 return (1);
5709 if (cb.cb_vdevs.cb_names_count != 0) {
5711 * If user specified vdevs, it implies verbose.
5713 cb.cb_verbose = B_TRUE;
5717 * Construct the list of all interesting pools.
5719 ret = 0;
5720 if ((list = pool_list_get(argc, argv, NULL, ZFS_TYPE_POOL, parsable,
5721 &ret)) == NULL)
5722 return (1);
5724 if (pool_list_count(list) == 0 && argc != 0) {
5725 pool_list_free(list);
5726 return (1);
5729 if (pool_list_count(list) == 0 && interval == 0) {
5730 pool_list_free(list);
5731 (void) fprintf(stderr, gettext("no pools available\n"));
5732 return (1);
5735 if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
5736 pool_list_free(list);
5737 (void) fprintf(stderr,
5738 gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
5739 usage(B_FALSE);
5740 return (1);
5743 if (l_histo && rq_histo) {
5744 pool_list_free(list);
5745 (void) fprintf(stderr,
5746 gettext("Only one of [-r|-w] can be passed at a time\n"));
5747 usage(B_FALSE);
5748 return (1);
5752 * Enter the main iostat loop.
5754 cb.cb_list = list;
5756 if (l_histo) {
5758 * Histograms tables look out of place when you try to display
5759 * them with the other stats, so make a rule that you can only
5760 * print histograms by themselves.
5762 cb.cb_flags = IOS_L_HISTO_M;
5763 } else if (rq_histo) {
5764 cb.cb_flags = IOS_RQ_HISTO_M;
5765 } else {
5766 cb.cb_flags = IOS_DEFAULT_M;
5767 if (latency)
5768 cb.cb_flags |= IOS_LATENCY_M;
5769 if (queues)
5770 cb.cb_flags |= IOS_QUEUES_M;
5774 * See if the module supports all the stats we want to display.
5776 unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
5777 if (unsupported_flags) {
5778 uint64_t f;
5779 int idx;
5780 fprintf(stderr,
5781 gettext("The loaded zfs module doesn't support:"));
5783 /* for each bit set in unsupported_flags */
5784 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
5785 idx = lowbit64(f) - 1;
5786 fprintf(stderr, " -%c", flag_to_arg[idx]);
5789 fprintf(stderr, ". Try running a newer module.\n");
5790 pool_list_free(list);
5792 return (1);
5795 for (;;) {
5796 if ((npools = pool_list_count(list)) == 0)
5797 (void) fprintf(stderr, gettext("no pools available\n"));
5798 else {
5800 * If this is the first iteration and -y was supplied
5801 * we skip any printing.
5803 boolean_t skip = (omit_since_boot &&
5804 cb.cb_iteration == 0);
5807 * Refresh all statistics. This is done as an
5808 * explicit step before calculating the maximum name
5809 * width, so that any * configuration changes are
5810 * properly accounted for.
5812 (void) pool_list_iter(list, B_FALSE, refresh_iostat,
5813 &cb);
5816 * Iterate over all pools to determine the maximum width
5817 * for the pool / device name column across all pools.
5819 cb.cb_namewidth = 0;
5820 (void) pool_list_iter(list, B_FALSE,
5821 get_namewidth_iostat, &cb);
5823 if (timestamp_fmt != NODATE)
5824 print_timestamp(timestamp_fmt);
5826 if (cmd != NULL && cb.cb_verbose &&
5827 !(cb.cb_flags & IOS_ANYHISTO_M)) {
5828 cb.vcdl = all_pools_for_each_vdev_run(argc,
5829 argv, cmd, g_zfs, cb.cb_vdevs.cb_names,
5830 cb.cb_vdevs.cb_names_count,
5831 cb.cb_vdevs.cb_name_flags);
5832 } else {
5833 cb.vcdl = NULL;
5838 * Check terminal size so we can print headers
5839 * even when terminal window has its height
5840 * changed.
5842 winheight = terminal_height();
5844 * Are we connected to TTY? If not, headers_once
5845 * should be true, to avoid breaking scripts.
5847 if (winheight < 0)
5848 headers_once = B_TRUE;
5851 * If it's the first time and we're not skipping it,
5852 * or either skip or verbose mode, print the header.
5854 * The histogram code explicitly prints its header on
5855 * every vdev, so skip this for histograms.
5857 if (((++cb.cb_iteration == 1 && !skip) ||
5858 (skip != verbose) ||
5859 (!headers_once &&
5860 (cb.cb_iteration % winheight) == 0)) &&
5861 (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
5862 !cb.cb_scripted)
5863 print_iostat_header(&cb);
5865 if (skip) {
5866 (void) fsleep(interval);
5867 continue;
5870 pool_list_iter(list, B_FALSE, print_iostat, &cb);
5873 * If there's more than one pool, and we're not in
5874 * verbose mode (which prints a separator for us),
5875 * then print a separator.
5877 * In addition, if we're printing specific vdevs then
5878 * we also want an ending separator.
5880 if (((npools > 1 && !verbose &&
5881 !(cb.cb_flags & IOS_ANYHISTO_M)) ||
5882 (!(cb.cb_flags & IOS_ANYHISTO_M) &&
5883 cb.cb_vdevs.cb_names_count)) &&
5884 !cb.cb_scripted) {
5885 print_iostat_separator(&cb);
5886 if (cb.vcdl != NULL)
5887 print_cmd_columns(cb.vcdl, 1);
5888 printf("\n");
5891 if (cb.vcdl != NULL)
5892 free_vdev_cmd_data_list(cb.vcdl);
5897 * Flush the output so that redirection to a file isn't buffered
5898 * indefinitely.
5900 (void) fflush(stdout);
5902 if (interval == 0)
5903 break;
5905 if (count != 0 && --count == 0)
5906 break;
5908 (void) fsleep(interval);
5911 pool_list_free(list);
5913 return (ret);
5916 typedef struct list_cbdata {
5917 boolean_t cb_verbose;
5918 int cb_name_flags;
5919 int cb_namewidth;
5920 boolean_t cb_scripted;
5921 zprop_list_t *cb_proplist;
5922 boolean_t cb_literal;
5923 } list_cbdata_t;
5927 * Given a list of columns to display, output appropriate headers for each one.
5929 static void
5930 print_header(list_cbdata_t *cb)
5932 zprop_list_t *pl = cb->cb_proplist;
5933 char headerbuf[ZPOOL_MAXPROPLEN];
5934 const char *header;
5935 boolean_t first = B_TRUE;
5936 boolean_t right_justify;
5937 size_t width = 0;
5939 for (; pl != NULL; pl = pl->pl_next) {
5940 width = pl->pl_width;
5941 if (first && cb->cb_verbose) {
5943 * Reset the width to accommodate the verbose listing
5944 * of devices.
5946 width = cb->cb_namewidth;
5949 if (!first)
5950 (void) fputs(" ", stdout);
5951 else
5952 first = B_FALSE;
5954 right_justify = B_FALSE;
5955 if (pl->pl_prop != ZPROP_USERPROP) {
5956 header = zpool_prop_column_name(pl->pl_prop);
5957 right_justify = zpool_prop_align_right(pl->pl_prop);
5958 } else {
5959 int i;
5961 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
5962 headerbuf[i] = toupper(pl->pl_user_prop[i]);
5963 headerbuf[i] = '\0';
5964 header = headerbuf;
5967 if (pl->pl_next == NULL && !right_justify)
5968 (void) fputs(header, stdout);
5969 else if (right_justify)
5970 (void) printf("%*s", (int)width, header);
5971 else
5972 (void) printf("%-*s", (int)width, header);
5975 (void) fputc('\n', stdout);
5979 * Given a pool and a list of properties, print out all the properties according
5980 * to the described layout. Used by zpool_do_list().
5982 static void
5983 print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
5985 zprop_list_t *pl = cb->cb_proplist;
5986 boolean_t first = B_TRUE;
5987 char property[ZPOOL_MAXPROPLEN];
5988 const char *propstr;
5989 boolean_t right_justify;
5990 size_t width;
5992 for (; pl != NULL; pl = pl->pl_next) {
5994 width = pl->pl_width;
5995 if (first && cb->cb_verbose) {
5997 * Reset the width to accommodate the verbose listing
5998 * of devices.
6000 width = cb->cb_namewidth;
6003 if (!first) {
6004 if (cb->cb_scripted)
6005 (void) fputc('\t', stdout);
6006 else
6007 (void) fputs(" ", stdout);
6008 } else {
6009 first = B_FALSE;
6012 right_justify = B_FALSE;
6013 if (pl->pl_prop != ZPROP_USERPROP) {
6014 if (zpool_get_prop(zhp, pl->pl_prop, property,
6015 sizeof (property), NULL, cb->cb_literal) != 0)
6016 propstr = "-";
6017 else
6018 propstr = property;
6020 right_justify = zpool_prop_align_right(pl->pl_prop);
6021 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
6022 zpool_prop_unsupported(pl->pl_user_prop)) &&
6023 zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
6024 sizeof (property)) == 0) {
6025 propstr = property;
6026 } else {
6027 propstr = "-";
6032 * If this is being called in scripted mode, or if this is the
6033 * last column and it is left-justified, don't include a width
6034 * format specifier.
6036 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
6037 (void) fputs(propstr, stdout);
6038 else if (right_justify)
6039 (void) printf("%*s", (int)width, propstr);
6040 else
6041 (void) printf("%-*s", (int)width, propstr);
6044 (void) fputc('\n', stdout);
6047 static void
6048 print_one_column(zpool_prop_t prop, uint64_t value, const char *str,
6049 boolean_t scripted, boolean_t valid, enum zfs_nicenum_format format)
6051 char propval[64];
6052 boolean_t fixed;
6053 size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
6055 switch (prop) {
6056 case ZPOOL_PROP_SIZE:
6057 case ZPOOL_PROP_EXPANDSZ:
6058 case ZPOOL_PROP_CHECKPOINT:
6059 case ZPOOL_PROP_DEDUPRATIO:
6060 if (value == 0)
6061 (void) strlcpy(propval, "-", sizeof (propval));
6062 else
6063 zfs_nicenum_format(value, propval, sizeof (propval),
6064 format);
6065 break;
6066 case ZPOOL_PROP_FRAGMENTATION:
6067 if (value == ZFS_FRAG_INVALID) {
6068 (void) strlcpy(propval, "-", sizeof (propval));
6069 } else if (format == ZFS_NICENUM_RAW) {
6070 (void) snprintf(propval, sizeof (propval), "%llu",
6071 (unsigned long long)value);
6072 } else {
6073 (void) snprintf(propval, sizeof (propval), "%llu%%",
6074 (unsigned long long)value);
6076 break;
6077 case ZPOOL_PROP_CAPACITY:
6078 /* capacity value is in parts-per-10,000 (aka permyriad) */
6079 if (format == ZFS_NICENUM_RAW)
6080 (void) snprintf(propval, sizeof (propval), "%llu",
6081 (unsigned long long)value / 100);
6082 else
6083 (void) snprintf(propval, sizeof (propval),
6084 value < 1000 ? "%1.2f%%" : value < 10000 ?
6085 "%2.1f%%" : "%3.0f%%", value / 100.0);
6086 break;
6087 case ZPOOL_PROP_HEALTH:
6088 width = 8;
6089 (void) strlcpy(propval, str, sizeof (propval));
6090 break;
6091 default:
6092 zfs_nicenum_format(value, propval, sizeof (propval), format);
6095 if (!valid)
6096 (void) strlcpy(propval, "-", sizeof (propval));
6098 if (scripted)
6099 (void) printf("\t%s", propval);
6100 else
6101 (void) printf(" %*s", (int)width, propval);
6105 * print static default line per vdev
6106 * not compatible with '-o' <proplist> option
6108 static void
6109 print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
6110 list_cbdata_t *cb, int depth, boolean_t isspare)
6112 nvlist_t **child;
6113 vdev_stat_t *vs;
6114 uint_t c, children;
6115 char *vname;
6116 boolean_t scripted = cb->cb_scripted;
6117 uint64_t islog = B_FALSE;
6118 const char *dashes = "%-*s - - - - "
6119 "- - - - -\n";
6121 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
6122 (uint64_t **)&vs, &c) == 0);
6124 if (name != NULL) {
6125 boolean_t toplevel = (vs->vs_space != 0);
6126 uint64_t cap;
6127 enum zfs_nicenum_format format;
6128 const char *state;
6130 if (cb->cb_literal)
6131 format = ZFS_NICENUM_RAW;
6132 else
6133 format = ZFS_NICENUM_1024;
6135 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
6136 return;
6138 if (scripted)
6139 (void) printf("\t%s", name);
6140 else if (strlen(name) + depth > cb->cb_namewidth)
6141 (void) printf("%*s%s", depth, "", name);
6142 else
6143 (void) printf("%*s%s%*s", depth, "", name,
6144 (int)(cb->cb_namewidth - strlen(name) - depth), "");
6147 * Print the properties for the individual vdevs. Some
6148 * properties are only applicable to toplevel vdevs. The
6149 * 'toplevel' boolean value is passed to the print_one_column()
6150 * to indicate that the value is valid.
6152 if (VDEV_STAT_VALID(vs_pspace, c) && vs->vs_pspace)
6153 print_one_column(ZPOOL_PROP_SIZE, vs->vs_pspace, NULL,
6154 scripted, B_TRUE, format);
6155 else
6156 print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, NULL,
6157 scripted, toplevel, format);
6158 print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, NULL,
6159 scripted, toplevel, format);
6160 print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
6161 NULL, scripted, toplevel, format);
6162 print_one_column(ZPOOL_PROP_CHECKPOINT,
6163 vs->vs_checkpoint_space, NULL, scripted, toplevel, format);
6164 print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, NULL,
6165 scripted, B_TRUE, format);
6166 print_one_column(ZPOOL_PROP_FRAGMENTATION,
6167 vs->vs_fragmentation, NULL, scripted,
6168 (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
6169 format);
6170 cap = (vs->vs_space == 0) ? 0 :
6171 (vs->vs_alloc * 10000 / vs->vs_space);
6172 print_one_column(ZPOOL_PROP_CAPACITY, cap, NULL,
6173 scripted, toplevel, format);
6174 print_one_column(ZPOOL_PROP_DEDUPRATIO, 0, NULL,
6175 scripted, toplevel, format);
6176 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
6177 if (isspare) {
6178 if (vs->vs_aux == VDEV_AUX_SPARED)
6179 state = "INUSE";
6180 else if (vs->vs_state == VDEV_STATE_HEALTHY)
6181 state = "AVAIL";
6183 print_one_column(ZPOOL_PROP_HEALTH, 0, state, scripted,
6184 B_TRUE, format);
6185 (void) fputc('\n', stdout);
6188 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
6189 &child, &children) != 0)
6190 return;
6192 /* list the normal vdevs first */
6193 for (c = 0; c < children; c++) {
6194 uint64_t ishole = B_FALSE;
6196 if (nvlist_lookup_uint64(child[c],
6197 ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
6198 continue;
6200 if (nvlist_lookup_uint64(child[c],
6201 ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
6202 continue;
6204 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
6205 continue;
6207 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6208 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
6209 print_list_stats(zhp, vname, child[c], cb, depth + 2, B_FALSE);
6210 free(vname);
6213 /* list the classes: 'logs', 'dedup', and 'special' */
6214 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
6215 boolean_t printed = B_FALSE;
6217 for (c = 0; c < children; c++) {
6218 char *bias = NULL;
6219 char *type = NULL;
6221 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
6222 &islog) == 0 && islog) {
6223 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
6224 } else {
6225 (void) nvlist_lookup_string(child[c],
6226 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
6227 (void) nvlist_lookup_string(child[c],
6228 ZPOOL_CONFIG_TYPE, &type);
6230 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
6231 continue;
6232 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
6233 continue;
6235 if (!printed) {
6236 /* LINTED E_SEC_PRINTF_VAR_FMT */
6237 (void) printf(dashes, cb->cb_namewidth,
6238 class_name[n]);
6239 printed = B_TRUE;
6241 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6242 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
6243 print_list_stats(zhp, vname, child[c], cb, depth + 2,
6244 B_FALSE);
6245 free(vname);
6249 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
6250 &child, &children) == 0 && children > 0) {
6251 /* LINTED E_SEC_PRINTF_VAR_FMT */
6252 (void) printf(dashes, cb->cb_namewidth, "cache");
6253 for (c = 0; c < children; c++) {
6254 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6255 cb->cb_name_flags);
6256 print_list_stats(zhp, vname, child[c], cb, depth + 2,
6257 B_FALSE);
6258 free(vname);
6262 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
6263 &children) == 0 && children > 0) {
6264 /* LINTED E_SEC_PRINTF_VAR_FMT */
6265 (void) printf(dashes, cb->cb_namewidth, "spare");
6266 for (c = 0; c < children; c++) {
6267 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6268 cb->cb_name_flags);
6269 print_list_stats(zhp, vname, child[c], cb, depth + 2,
6270 B_TRUE);
6271 free(vname);
6277 * Generic callback function to list a pool.
6279 static int
6280 list_callback(zpool_handle_t *zhp, void *data)
6282 list_cbdata_t *cbp = data;
6284 print_pool(zhp, cbp);
6286 if (cbp->cb_verbose) {
6287 nvlist_t *config, *nvroot;
6289 config = zpool_get_config(zhp, NULL);
6290 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
6291 &nvroot) == 0);
6292 print_list_stats(zhp, NULL, nvroot, cbp, 0, B_FALSE);
6295 return (0);
6299 * Set the minimum pool/vdev name column width. The width must be at least 9,
6300 * but may be as large as needed.
6302 static int
6303 get_namewidth_list(zpool_handle_t *zhp, void *data)
6305 list_cbdata_t *cb = data;
6306 int width;
6308 width = get_namewidth(zhp, cb->cb_namewidth,
6309 cb->cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
6311 if (width < 9)
6312 width = 9;
6314 cb->cb_namewidth = width;
6316 return (0);
6320 * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
6322 * -g Display guid for individual vdev name.
6323 * -H Scripted mode. Don't display headers, and separate properties
6324 * by a single tab.
6325 * -L Follow links when resolving vdev path name.
6326 * -o List of properties to display. Defaults to
6327 * "name,size,allocated,free,expandsize,fragmentation,capacity,"
6328 * "dedupratio,health,altroot"
6329 * -p Display values in parsable (exact) format.
6330 * -P Display full path for vdev name.
6331 * -T Display a timestamp in date(1) or Unix format
6333 * List all pools in the system, whether or not they're healthy. Output space
6334 * statistics for each one, as well as health status summary.
6337 zpool_do_list(int argc, char **argv)
6339 int c;
6340 int ret = 0;
6341 list_cbdata_t cb = { 0 };
6342 static char default_props[] =
6343 "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
6344 "capacity,dedupratio,health,altroot";
6345 char *props = default_props;
6346 float interval = 0;
6347 unsigned long count = 0;
6348 zpool_list_t *list;
6349 boolean_t first = B_TRUE;
6350 current_prop_type = ZFS_TYPE_POOL;
6352 /* check options */
6353 while ((c = getopt(argc, argv, ":gHLo:pPT:v")) != -1) {
6354 switch (c) {
6355 case 'g':
6356 cb.cb_name_flags |= VDEV_NAME_GUID;
6357 break;
6358 case 'H':
6359 cb.cb_scripted = B_TRUE;
6360 break;
6361 case 'L':
6362 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6363 break;
6364 case 'o':
6365 props = optarg;
6366 break;
6367 case 'P':
6368 cb.cb_name_flags |= VDEV_NAME_PATH;
6369 break;
6370 case 'p':
6371 cb.cb_literal = B_TRUE;
6372 break;
6373 case 'T':
6374 get_timestamp_arg(*optarg);
6375 break;
6376 case 'v':
6377 cb.cb_verbose = B_TRUE;
6378 cb.cb_namewidth = 8; /* 8 until precalc is avail */
6379 break;
6380 case ':':
6381 (void) fprintf(stderr, gettext("missing argument for "
6382 "'%c' option\n"), optopt);
6383 usage(B_FALSE);
6384 break;
6385 case '?':
6386 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6387 optopt);
6388 usage(B_FALSE);
6392 argc -= optind;
6393 argv += optind;
6395 get_interval_count(&argc, argv, &interval, &count);
6397 if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
6398 usage(B_FALSE);
6400 for (;;) {
6401 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
6402 ZFS_TYPE_POOL, cb.cb_literal, &ret)) == NULL)
6403 return (1);
6405 if (pool_list_count(list) == 0)
6406 break;
6408 cb.cb_namewidth = 0;
6409 (void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
6411 if (timestamp_fmt != NODATE)
6412 print_timestamp(timestamp_fmt);
6414 if (!cb.cb_scripted && (first || cb.cb_verbose)) {
6415 print_header(&cb);
6416 first = B_FALSE;
6418 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
6420 if (interval == 0)
6421 break;
6423 if (count != 0 && --count == 0)
6424 break;
6426 pool_list_free(list);
6427 (void) fsleep(interval);
6430 if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
6431 (void) printf(gettext("no pools available\n"));
6432 ret = 0;
6435 pool_list_free(list);
6436 zprop_free_list(cb.cb_proplist);
6437 return (ret);
6440 static int
6441 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
6443 boolean_t force = B_FALSE;
6444 boolean_t rebuild = B_FALSE;
6445 boolean_t wait = B_FALSE;
6446 int c;
6447 nvlist_t *nvroot;
6448 char *poolname, *old_disk, *new_disk;
6449 zpool_handle_t *zhp;
6450 nvlist_t *props = NULL;
6451 char *propval;
6452 int ret;
6454 /* check options */
6455 while ((c = getopt(argc, argv, "fo:sw")) != -1) {
6456 switch (c) {
6457 case 'f':
6458 force = B_TRUE;
6459 break;
6460 case 'o':
6461 if ((propval = strchr(optarg, '=')) == NULL) {
6462 (void) fprintf(stderr, gettext("missing "
6463 "'=' for -o option\n"));
6464 usage(B_FALSE);
6466 *propval = '\0';
6467 propval++;
6469 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
6470 (add_prop_list(optarg, propval, &props, B_TRUE)))
6471 usage(B_FALSE);
6472 break;
6473 case 's':
6474 rebuild = B_TRUE;
6475 break;
6476 case 'w':
6477 wait = B_TRUE;
6478 break;
6479 case '?':
6480 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6481 optopt);
6482 usage(B_FALSE);
6486 argc -= optind;
6487 argv += optind;
6489 /* get pool name and check number of arguments */
6490 if (argc < 1) {
6491 (void) fprintf(stderr, gettext("missing pool name argument\n"));
6492 usage(B_FALSE);
6495 poolname = argv[0];
6497 if (argc < 2) {
6498 (void) fprintf(stderr,
6499 gettext("missing <device> specification\n"));
6500 usage(B_FALSE);
6503 old_disk = argv[1];
6505 if (argc < 3) {
6506 if (!replacing) {
6507 (void) fprintf(stderr,
6508 gettext("missing <new_device> specification\n"));
6509 usage(B_FALSE);
6511 new_disk = old_disk;
6512 argc -= 1;
6513 argv += 1;
6514 } else {
6515 new_disk = argv[2];
6516 argc -= 2;
6517 argv += 2;
6520 if (argc > 1) {
6521 (void) fprintf(stderr, gettext("too many arguments\n"));
6522 usage(B_FALSE);
6525 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
6526 nvlist_free(props);
6527 return (1);
6530 if (zpool_get_config(zhp, NULL) == NULL) {
6531 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
6532 poolname);
6533 zpool_close(zhp);
6534 nvlist_free(props);
6535 return (1);
6538 /* unless manually specified use "ashift" pool property (if set) */
6539 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
6540 int intval;
6541 zprop_source_t src;
6542 char strval[ZPOOL_MAXPROPLEN];
6544 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
6545 if (src != ZPROP_SRC_DEFAULT) {
6546 (void) sprintf(strval, "%" PRId32, intval);
6547 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
6548 &props, B_TRUE) == 0);
6552 nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
6553 argc, argv);
6554 if (nvroot == NULL) {
6555 zpool_close(zhp);
6556 nvlist_free(props);
6557 return (1);
6560 ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing,
6561 rebuild);
6563 if (ret == 0 && wait)
6564 ret = zpool_wait(zhp,
6565 replacing ? ZPOOL_WAIT_REPLACE : ZPOOL_WAIT_RESILVER);
6567 nvlist_free(props);
6568 nvlist_free(nvroot);
6569 zpool_close(zhp);
6571 return (ret);
6575 * zpool replace [-fsw] [-o property=value] <pool> <device> <new_device>
6577 * -f Force attach, even if <new_device> appears to be in use.
6578 * -s Use sequential instead of healing reconstruction for resilver.
6579 * -o Set property=value.
6580 * -w Wait for replacing to complete before returning
6582 * Replace <device> with <new_device>.
6585 zpool_do_replace(int argc, char **argv)
6587 return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
6591 * zpool attach [-fsw] [-o property=value] <pool> <device> <new_device>
6593 * -f Force attach, even if <new_device> appears to be in use.
6594 * -s Use sequential instead of healing reconstruction for resilver.
6595 * -o Set property=value.
6596 * -w Wait for resilvering to complete before returning
6598 * Attach <new_device> to the mirror containing <device>. If <device> is not
6599 * part of a mirror, then <device> will be transformed into a mirror of
6600 * <device> and <new_device>. In either case, <new_device> will begin life
6601 * with a DTL of [0, now], and will immediately begin to resilver itself.
6604 zpool_do_attach(int argc, char **argv)
6606 return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
6610 * zpool detach [-f] <pool> <device>
6612 * -f Force detach of <device>, even if DTLs argue against it
6613 * (not supported yet)
6615 * Detach a device from a mirror. The operation will be refused if <device>
6616 * is the last device in the mirror, or if the DTLs indicate that this device
6617 * has the only valid copy of some data.
6620 zpool_do_detach(int argc, char **argv)
6622 int c;
6623 char *poolname, *path;
6624 zpool_handle_t *zhp;
6625 int ret;
6627 /* check options */
6628 while ((c = getopt(argc, argv, "")) != -1) {
6629 switch (c) {
6630 case '?':
6631 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6632 optopt);
6633 usage(B_FALSE);
6637 argc -= optind;
6638 argv += optind;
6640 /* get pool name and check number of arguments */
6641 if (argc < 1) {
6642 (void) fprintf(stderr, gettext("missing pool name argument\n"));
6643 usage(B_FALSE);
6646 if (argc < 2) {
6647 (void) fprintf(stderr,
6648 gettext("missing <device> specification\n"));
6649 usage(B_FALSE);
6652 poolname = argv[0];
6653 path = argv[1];
6655 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6656 return (1);
6658 ret = zpool_vdev_detach(zhp, path);
6660 zpool_close(zhp);
6662 return (ret);
6666 * zpool split [-gLnP] [-o prop=val] ...
6667 * [-o mntopt] ...
6668 * [-R altroot] <pool> <newpool> [<device> ...]
6670 * -g Display guid for individual vdev name.
6671 * -L Follow links when resolving vdev path name.
6672 * -n Do not split the pool, but display the resulting layout if
6673 * it were to be split.
6674 * -o Set property=value, or set mount options.
6675 * -P Display full path for vdev name.
6676 * -R Mount the split-off pool under an alternate root.
6677 * -l Load encryption keys while importing.
6679 * Splits the named pool and gives it the new pool name. Devices to be split
6680 * off may be listed, provided that no more than one device is specified
6681 * per top-level vdev mirror. The newly split pool is left in an exported
6682 * state unless -R is specified.
6684 * Restrictions: the top-level of the pool pool must only be made up of
6685 * mirrors; all devices in the pool must be healthy; no device may be
6686 * undergoing a resilvering operation.
6689 zpool_do_split(int argc, char **argv)
6691 char *srcpool, *newpool, *propval;
6692 char *mntopts = NULL;
6693 splitflags_t flags;
6694 int c, ret = 0;
6695 boolean_t loadkeys = B_FALSE;
6696 zpool_handle_t *zhp;
6697 nvlist_t *config, *props = NULL;
6699 flags.dryrun = B_FALSE;
6700 flags.import = B_FALSE;
6701 flags.name_flags = 0;
6703 /* check options */
6704 while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
6705 switch (c) {
6706 case 'g':
6707 flags.name_flags |= VDEV_NAME_GUID;
6708 break;
6709 case 'L':
6710 flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
6711 break;
6712 case 'R':
6713 flags.import = B_TRUE;
6714 if (add_prop_list(
6715 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
6716 &props, B_TRUE) != 0) {
6717 nvlist_free(props);
6718 usage(B_FALSE);
6720 break;
6721 case 'l':
6722 loadkeys = B_TRUE;
6723 break;
6724 case 'n':
6725 flags.dryrun = B_TRUE;
6726 break;
6727 case 'o':
6728 if ((propval = strchr(optarg, '=')) != NULL) {
6729 *propval = '\0';
6730 propval++;
6731 if (add_prop_list(optarg, propval,
6732 &props, B_TRUE) != 0) {
6733 nvlist_free(props);
6734 usage(B_FALSE);
6736 } else {
6737 mntopts = optarg;
6739 break;
6740 case 'P':
6741 flags.name_flags |= VDEV_NAME_PATH;
6742 break;
6743 case ':':
6744 (void) fprintf(stderr, gettext("missing argument for "
6745 "'%c' option\n"), optopt);
6746 usage(B_FALSE);
6747 break;
6748 case '?':
6749 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6750 optopt);
6751 usage(B_FALSE);
6752 break;
6756 if (!flags.import && mntopts != NULL) {
6757 (void) fprintf(stderr, gettext("setting mntopts is only "
6758 "valid when importing the pool\n"));
6759 usage(B_FALSE);
6762 if (!flags.import && loadkeys) {
6763 (void) fprintf(stderr, gettext("loading keys is only "
6764 "valid when importing the pool\n"));
6765 usage(B_FALSE);
6768 argc -= optind;
6769 argv += optind;
6771 if (argc < 1) {
6772 (void) fprintf(stderr, gettext("Missing pool name\n"));
6773 usage(B_FALSE);
6775 if (argc < 2) {
6776 (void) fprintf(stderr, gettext("Missing new pool name\n"));
6777 usage(B_FALSE);
6780 srcpool = argv[0];
6781 newpool = argv[1];
6783 argc -= 2;
6784 argv += 2;
6786 if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
6787 nvlist_free(props);
6788 return (1);
6791 config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
6792 if (config == NULL) {
6793 ret = 1;
6794 } else {
6795 if (flags.dryrun) {
6796 (void) printf(gettext("would create '%s' with the "
6797 "following layout:\n\n"), newpool);
6798 print_vdev_tree(NULL, newpool, config, 0, "",
6799 flags.name_flags);
6800 print_vdev_tree(NULL, "dedup", config, 0,
6801 VDEV_ALLOC_BIAS_DEDUP, 0);
6802 print_vdev_tree(NULL, "special", config, 0,
6803 VDEV_ALLOC_BIAS_SPECIAL, 0);
6807 zpool_close(zhp);
6809 if (ret != 0 || flags.dryrun || !flags.import) {
6810 nvlist_free(config);
6811 nvlist_free(props);
6812 return (ret);
6816 * The split was successful. Now we need to open the new
6817 * pool and import it.
6819 if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
6820 nvlist_free(config);
6821 nvlist_free(props);
6822 return (1);
6825 if (loadkeys) {
6826 ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
6827 if (ret != 0)
6828 ret = 1;
6831 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
6832 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
6833 ret = 1;
6834 (void) fprintf(stderr, gettext("Split was successful, but "
6835 "the datasets could not all be mounted\n"));
6836 (void) fprintf(stderr, gettext("Try doing '%s' with a "
6837 "different altroot\n"), "zpool import");
6839 zpool_close(zhp);
6840 nvlist_free(config);
6841 nvlist_free(props);
6843 return (ret);
6849 * zpool online <pool> <device> ...
6852 zpool_do_online(int argc, char **argv)
6854 int c, i;
6855 char *poolname;
6856 zpool_handle_t *zhp;
6857 int ret = 0;
6858 vdev_state_t newstate;
6859 int flags = 0;
6861 /* check options */
6862 while ((c = getopt(argc, argv, "e")) != -1) {
6863 switch (c) {
6864 case 'e':
6865 flags |= ZFS_ONLINE_EXPAND;
6866 break;
6867 case '?':
6868 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6869 optopt);
6870 usage(B_FALSE);
6874 argc -= optind;
6875 argv += optind;
6877 /* get pool name and check number of arguments */
6878 if (argc < 1) {
6879 (void) fprintf(stderr, gettext("missing pool name\n"));
6880 usage(B_FALSE);
6882 if (argc < 2) {
6883 (void) fprintf(stderr, gettext("missing device name\n"));
6884 usage(B_FALSE);
6887 poolname = argv[0];
6889 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6890 return (1);
6892 for (i = 1; i < argc; i++) {
6893 if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
6894 if (newstate != VDEV_STATE_HEALTHY) {
6895 (void) printf(gettext("warning: device '%s' "
6896 "onlined, but remains in faulted state\n"),
6897 argv[i]);
6898 if (newstate == VDEV_STATE_FAULTED)
6899 (void) printf(gettext("use 'zpool "
6900 "clear' to restore a faulted "
6901 "device\n"));
6902 else
6903 (void) printf(gettext("use 'zpool "
6904 "replace' to replace devices "
6905 "that are no longer present\n"));
6907 } else {
6908 ret = 1;
6912 zpool_close(zhp);
6914 return (ret);
6918 * zpool offline [-ft] <pool> <device> ...
6920 * -f Force the device into a faulted state.
6922 * -t Only take the device off-line temporarily. The offline/faulted
6923 * state will not be persistent across reboots.
6926 zpool_do_offline(int argc, char **argv)
6928 int c, i;
6929 char *poolname;
6930 zpool_handle_t *zhp;
6931 int ret = 0;
6932 boolean_t istmp = B_FALSE;
6933 boolean_t fault = B_FALSE;
6935 /* check options */
6936 while ((c = getopt(argc, argv, "ft")) != -1) {
6937 switch (c) {
6938 case 'f':
6939 fault = B_TRUE;
6940 break;
6941 case 't':
6942 istmp = B_TRUE;
6943 break;
6944 case '?':
6945 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6946 optopt);
6947 usage(B_FALSE);
6951 argc -= optind;
6952 argv += optind;
6954 /* get pool name and check number of arguments */
6955 if (argc < 1) {
6956 (void) fprintf(stderr, gettext("missing pool name\n"));
6957 usage(B_FALSE);
6959 if (argc < 2) {
6960 (void) fprintf(stderr, gettext("missing device name\n"));
6961 usage(B_FALSE);
6964 poolname = argv[0];
6966 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6967 return (1);
6969 for (i = 1; i < argc; i++) {
6970 if (fault) {
6971 uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
6972 vdev_aux_t aux;
6973 if (istmp == B_FALSE) {
6974 /* Force the fault to persist across imports */
6975 aux = VDEV_AUX_EXTERNAL_PERSIST;
6976 } else {
6977 aux = VDEV_AUX_EXTERNAL;
6980 if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
6981 ret = 1;
6982 } else {
6983 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
6984 ret = 1;
6988 zpool_close(zhp);
6990 return (ret);
6994 * zpool clear <pool> [device]
6996 * Clear all errors associated with a pool or a particular device.
6999 zpool_do_clear(int argc, char **argv)
7001 int c;
7002 int ret = 0;
7003 boolean_t dryrun = B_FALSE;
7004 boolean_t do_rewind = B_FALSE;
7005 boolean_t xtreme_rewind = B_FALSE;
7006 uint32_t rewind_policy = ZPOOL_NO_REWIND;
7007 nvlist_t *policy = NULL;
7008 zpool_handle_t *zhp;
7009 char *pool, *device;
7011 /* check options */
7012 while ((c = getopt(argc, argv, "FnX")) != -1) {
7013 switch (c) {
7014 case 'F':
7015 do_rewind = B_TRUE;
7016 break;
7017 case 'n':
7018 dryrun = B_TRUE;
7019 break;
7020 case 'X':
7021 xtreme_rewind = B_TRUE;
7022 break;
7023 case '?':
7024 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7025 optopt);
7026 usage(B_FALSE);
7030 argc -= optind;
7031 argv += optind;
7033 if (argc < 1) {
7034 (void) fprintf(stderr, gettext("missing pool name\n"));
7035 usage(B_FALSE);
7038 if (argc > 2) {
7039 (void) fprintf(stderr, gettext("too many arguments\n"));
7040 usage(B_FALSE);
7043 if ((dryrun || xtreme_rewind) && !do_rewind) {
7044 (void) fprintf(stderr,
7045 gettext("-n or -X only meaningful with -F\n"));
7046 usage(B_FALSE);
7048 if (dryrun)
7049 rewind_policy = ZPOOL_TRY_REWIND;
7050 else if (do_rewind)
7051 rewind_policy = ZPOOL_DO_REWIND;
7052 if (xtreme_rewind)
7053 rewind_policy |= ZPOOL_EXTREME_REWIND;
7055 /* In future, further rewind policy choices can be passed along here */
7056 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
7057 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
7058 rewind_policy) != 0) {
7059 return (1);
7062 pool = argv[0];
7063 device = argc == 2 ? argv[1] : NULL;
7065 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
7066 nvlist_free(policy);
7067 return (1);
7070 if (zpool_clear(zhp, device, policy) != 0)
7071 ret = 1;
7073 zpool_close(zhp);
7075 nvlist_free(policy);
7077 return (ret);
7081 * zpool reguid <pool>
7084 zpool_do_reguid(int argc, char **argv)
7086 int c;
7087 char *poolname;
7088 zpool_handle_t *zhp;
7089 int ret = 0;
7091 /* check options */
7092 while ((c = getopt(argc, argv, "")) != -1) {
7093 switch (c) {
7094 case '?':
7095 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7096 optopt);
7097 usage(B_FALSE);
7101 argc -= optind;
7102 argv += optind;
7104 /* get pool name and check number of arguments */
7105 if (argc < 1) {
7106 (void) fprintf(stderr, gettext("missing pool name\n"));
7107 usage(B_FALSE);
7110 if (argc > 1) {
7111 (void) fprintf(stderr, gettext("too many arguments\n"));
7112 usage(B_FALSE);
7115 poolname = argv[0];
7116 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7117 return (1);
7119 ret = zpool_reguid(zhp);
7121 zpool_close(zhp);
7122 return (ret);
7127 * zpool reopen <pool>
7129 * Reopen the pool so that the kernel can update the sizes of all vdevs.
7132 zpool_do_reopen(int argc, char **argv)
7134 int c;
7135 int ret = 0;
7136 boolean_t scrub_restart = B_TRUE;
7138 /* check options */
7139 while ((c = getopt(argc, argv, "n")) != -1) {
7140 switch (c) {
7141 case 'n':
7142 scrub_restart = B_FALSE;
7143 break;
7144 case '?':
7145 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7146 optopt);
7147 usage(B_FALSE);
7151 argc -= optind;
7152 argv += optind;
7154 /* if argc == 0 we will execute zpool_reopen_one on all pools */
7155 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7156 B_FALSE, zpool_reopen_one, &scrub_restart);
7158 return (ret);
7161 typedef struct scrub_cbdata {
7162 int cb_type;
7163 pool_scrub_cmd_t cb_scrub_cmd;
7164 } scrub_cbdata_t;
7166 static boolean_t
7167 zpool_has_checkpoint(zpool_handle_t *zhp)
7169 nvlist_t *config, *nvroot;
7171 config = zpool_get_config(zhp, NULL);
7173 if (config != NULL) {
7174 pool_checkpoint_stat_t *pcs = NULL;
7175 uint_t c;
7177 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
7178 (void) nvlist_lookup_uint64_array(nvroot,
7179 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
7181 if (pcs == NULL || pcs->pcs_state == CS_NONE)
7182 return (B_FALSE);
7184 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
7185 pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
7186 return (B_TRUE);
7189 return (B_FALSE);
7192 static int
7193 scrub_callback(zpool_handle_t *zhp, void *data)
7195 scrub_cbdata_t *cb = data;
7196 int err;
7199 * Ignore faulted pools.
7201 if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
7202 (void) fprintf(stderr, gettext("cannot scan '%s': pool is "
7203 "currently unavailable\n"), zpool_get_name(zhp));
7204 return (1);
7207 err = zpool_scan(zhp, cb->cb_type, cb->cb_scrub_cmd);
7209 if (err == 0 && zpool_has_checkpoint(zhp) &&
7210 cb->cb_type == POOL_SCAN_SCRUB) {
7211 (void) printf(gettext("warning: will not scrub state that "
7212 "belongs to the checkpoint of pool '%s'\n"),
7213 zpool_get_name(zhp));
7216 return (err != 0);
7219 static int
7220 wait_callback(zpool_handle_t *zhp, void *data)
7222 zpool_wait_activity_t *act = data;
7223 return (zpool_wait(zhp, *act));
7227 * zpool scrub [-s | -p] [-w] <pool> ...
7229 * -s Stop. Stops any in-progress scrub.
7230 * -p Pause. Pause in-progress scrub.
7231 * -w Wait. Blocks until scrub has completed.
7234 zpool_do_scrub(int argc, char **argv)
7236 int c;
7237 scrub_cbdata_t cb;
7238 boolean_t wait = B_FALSE;
7239 int error;
7241 cb.cb_type = POOL_SCAN_SCRUB;
7242 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
7244 /* check options */
7245 while ((c = getopt(argc, argv, "spw")) != -1) {
7246 switch (c) {
7247 case 's':
7248 cb.cb_type = POOL_SCAN_NONE;
7249 break;
7250 case 'p':
7251 cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
7252 break;
7253 case 'w':
7254 wait = B_TRUE;
7255 break;
7256 case '?':
7257 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7258 optopt);
7259 usage(B_FALSE);
7263 if (cb.cb_type == POOL_SCAN_NONE &&
7264 cb.cb_scrub_cmd == POOL_SCRUB_PAUSE) {
7265 (void) fprintf(stderr, gettext("invalid option combination: "
7266 "-s and -p are mutually exclusive\n"));
7267 usage(B_FALSE);
7270 if (wait && (cb.cb_type == POOL_SCAN_NONE ||
7271 cb.cb_scrub_cmd == POOL_SCRUB_PAUSE)) {
7272 (void) fprintf(stderr, gettext("invalid option combination: "
7273 "-w cannot be used with -p or -s\n"));
7274 usage(B_FALSE);
7277 argc -= optind;
7278 argv += optind;
7280 if (argc < 1) {
7281 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7282 usage(B_FALSE);
7285 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7286 B_FALSE, scrub_callback, &cb);
7288 if (wait && !error) {
7289 zpool_wait_activity_t act = ZPOOL_WAIT_SCRUB;
7290 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7291 B_FALSE, wait_callback, &act);
7294 return (error);
7298 * zpool resilver <pool> ...
7300 * Restarts any in-progress resilver
7303 zpool_do_resilver(int argc, char **argv)
7305 int c;
7306 scrub_cbdata_t cb;
7308 cb.cb_type = POOL_SCAN_RESILVER;
7309 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
7311 /* check options */
7312 while ((c = getopt(argc, argv, "")) != -1) {
7313 switch (c) {
7314 case '?':
7315 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7316 optopt);
7317 usage(B_FALSE);
7321 argc -= optind;
7322 argv += optind;
7324 if (argc < 1) {
7325 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7326 usage(B_FALSE);
7329 return (for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7330 B_FALSE, scrub_callback, &cb));
7334 * zpool trim [-d] [-r <rate>] [-c | -s] <pool> [<device> ...]
7336 * -c Cancel. Ends any in-progress trim.
7337 * -d Secure trim. Requires kernel and device support.
7338 * -r <rate> Sets the TRIM rate in bytes (per second). Supports
7339 * adding a multiplier suffix such as 'k' or 'm'.
7340 * -s Suspend. TRIM can then be restarted with no flags.
7341 * -w Wait. Blocks until trimming has completed.
7344 zpool_do_trim(int argc, char **argv)
7346 struct option long_options[] = {
7347 {"cancel", no_argument, NULL, 'c'},
7348 {"secure", no_argument, NULL, 'd'},
7349 {"rate", required_argument, NULL, 'r'},
7350 {"suspend", no_argument, NULL, 's'},
7351 {"wait", no_argument, NULL, 'w'},
7352 {0, 0, 0, 0}
7355 pool_trim_func_t cmd_type = POOL_TRIM_START;
7356 uint64_t rate = 0;
7357 boolean_t secure = B_FALSE;
7358 boolean_t wait = B_FALSE;
7360 int c;
7361 while ((c = getopt_long(argc, argv, "cdr:sw", long_options, NULL))
7362 != -1) {
7363 switch (c) {
7364 case 'c':
7365 if (cmd_type != POOL_TRIM_START &&
7366 cmd_type != POOL_TRIM_CANCEL) {
7367 (void) fprintf(stderr, gettext("-c cannot be "
7368 "combined with other options\n"));
7369 usage(B_FALSE);
7371 cmd_type = POOL_TRIM_CANCEL;
7372 break;
7373 case 'd':
7374 if (cmd_type != POOL_TRIM_START) {
7375 (void) fprintf(stderr, gettext("-d cannot be "
7376 "combined with the -c or -s options\n"));
7377 usage(B_FALSE);
7379 secure = B_TRUE;
7380 break;
7381 case 'r':
7382 if (cmd_type != POOL_TRIM_START) {
7383 (void) fprintf(stderr, gettext("-r cannot be "
7384 "combined with the -c or -s options\n"));
7385 usage(B_FALSE);
7387 if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
7388 (void) fprintf(stderr, "%s: %s\n",
7389 gettext("invalid value for rate"),
7390 libzfs_error_description(g_zfs));
7391 usage(B_FALSE);
7393 break;
7394 case 's':
7395 if (cmd_type != POOL_TRIM_START &&
7396 cmd_type != POOL_TRIM_SUSPEND) {
7397 (void) fprintf(stderr, gettext("-s cannot be "
7398 "combined with other options\n"));
7399 usage(B_FALSE);
7401 cmd_type = POOL_TRIM_SUSPEND;
7402 break;
7403 case 'w':
7404 wait = B_TRUE;
7405 break;
7406 case '?':
7407 if (optopt != 0) {
7408 (void) fprintf(stderr,
7409 gettext("invalid option '%c'\n"), optopt);
7410 } else {
7411 (void) fprintf(stderr,
7412 gettext("invalid option '%s'\n"),
7413 argv[optind - 1]);
7415 usage(B_FALSE);
7419 argc -= optind;
7420 argv += optind;
7422 if (argc < 1) {
7423 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7424 usage(B_FALSE);
7425 return (-1);
7428 if (wait && (cmd_type != POOL_TRIM_START)) {
7429 (void) fprintf(stderr, gettext("-w cannot be used with -c or "
7430 "-s\n"));
7431 usage(B_FALSE);
7434 char *poolname = argv[0];
7435 zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
7436 if (zhp == NULL)
7437 return (-1);
7439 trimflags_t trim_flags = {
7440 .secure = secure,
7441 .rate = rate,
7442 .wait = wait,
7445 nvlist_t *vdevs = fnvlist_alloc();
7446 if (argc == 1) {
7447 /* no individual leaf vdevs specified, so add them all */
7448 nvlist_t *config = zpool_get_config(zhp, NULL);
7449 nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
7450 ZPOOL_CONFIG_VDEV_TREE);
7451 zpool_collect_leaves(zhp, nvroot, vdevs);
7452 trim_flags.fullpool = B_TRUE;
7453 } else {
7454 trim_flags.fullpool = B_FALSE;
7455 for (int i = 1; i < argc; i++) {
7456 fnvlist_add_boolean(vdevs, argv[i]);
7460 int error = zpool_trim(zhp, cmd_type, vdevs, &trim_flags);
7462 fnvlist_free(vdevs);
7463 zpool_close(zhp);
7465 return (error);
7469 * Converts a total number of seconds to a human readable string broken
7470 * down in to days/hours/minutes/seconds.
7472 static void
7473 secs_to_dhms(uint64_t total, char *buf)
7475 uint64_t days = total / 60 / 60 / 24;
7476 uint64_t hours = (total / 60 / 60) % 24;
7477 uint64_t mins = (total / 60) % 60;
7478 uint64_t secs = (total % 60);
7480 if (days > 0) {
7481 (void) sprintf(buf, "%llu days %02llu:%02llu:%02llu",
7482 (u_longlong_t)days, (u_longlong_t)hours,
7483 (u_longlong_t)mins, (u_longlong_t)secs);
7484 } else {
7485 (void) sprintf(buf, "%02llu:%02llu:%02llu",
7486 (u_longlong_t)hours, (u_longlong_t)mins,
7487 (u_longlong_t)secs);
7492 * Print out detailed scrub status.
7494 static void
7495 print_scan_scrub_resilver_status(pool_scan_stat_t *ps)
7497 time_t start, end, pause;
7498 uint64_t pass_scanned, scanned, pass_issued, issued, total;
7499 uint64_t elapsed, scan_rate, issue_rate;
7500 double fraction_done;
7501 char processed_buf[7], scanned_buf[7], issued_buf[7], total_buf[7];
7502 char srate_buf[7], irate_buf[7], time_buf[32];
7504 printf(" ");
7505 printf_color(ANSI_BOLD, gettext("scan:"));
7506 printf(" ");
7508 /* If there's never been a scan, there's not much to say. */
7509 if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
7510 ps->pss_func >= POOL_SCAN_FUNCS) {
7511 (void) printf(gettext("none requested\n"));
7512 return;
7515 start = ps->pss_start_time;
7516 end = ps->pss_end_time;
7517 pause = ps->pss_pass_scrub_pause;
7519 zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
7521 assert(ps->pss_func == POOL_SCAN_SCRUB ||
7522 ps->pss_func == POOL_SCAN_RESILVER);
7524 /* Scan is finished or canceled. */
7525 if (ps->pss_state == DSS_FINISHED) {
7526 secs_to_dhms(end - start, time_buf);
7528 if (ps->pss_func == POOL_SCAN_SCRUB) {
7529 (void) printf(gettext("scrub repaired %s "
7530 "in %s with %llu errors on %s"), processed_buf,
7531 time_buf, (u_longlong_t)ps->pss_errors,
7532 ctime(&end));
7533 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
7534 (void) printf(gettext("resilvered %s "
7535 "in %s with %llu errors on %s"), processed_buf,
7536 time_buf, (u_longlong_t)ps->pss_errors,
7537 ctime(&end));
7539 return;
7540 } else if (ps->pss_state == DSS_CANCELED) {
7541 if (ps->pss_func == POOL_SCAN_SCRUB) {
7542 (void) printf(gettext("scrub canceled on %s"),
7543 ctime(&end));
7544 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
7545 (void) printf(gettext("resilver canceled on %s"),
7546 ctime(&end));
7548 return;
7551 assert(ps->pss_state == DSS_SCANNING);
7553 /* Scan is in progress. Resilvers can't be paused. */
7554 if (ps->pss_func == POOL_SCAN_SCRUB) {
7555 if (pause == 0) {
7556 (void) printf(gettext("scrub in progress since %s"),
7557 ctime(&start));
7558 } else {
7559 (void) printf(gettext("scrub paused since %s"),
7560 ctime(&pause));
7561 (void) printf(gettext("\tscrub started on %s"),
7562 ctime(&start));
7564 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
7565 (void) printf(gettext("resilver in progress since %s"),
7566 ctime(&start));
7569 scanned = ps->pss_examined;
7570 pass_scanned = ps->pss_pass_exam;
7571 issued = ps->pss_issued;
7572 pass_issued = ps->pss_pass_issued;
7573 total = ps->pss_to_examine;
7575 /* we are only done with a block once we have issued the IO for it */
7576 fraction_done = (double)issued / total;
7578 /* elapsed time for this pass, rounding up to 1 if it's 0 */
7579 elapsed = time(NULL) - ps->pss_pass_start;
7580 elapsed -= ps->pss_pass_scrub_spent_paused;
7581 elapsed = (elapsed != 0) ? elapsed : 1;
7583 scan_rate = pass_scanned / elapsed;
7584 issue_rate = pass_issued / elapsed;
7585 uint64_t total_secs_left = (issue_rate != 0 && total >= issued) ?
7586 ((total - issued) / issue_rate) : UINT64_MAX;
7587 secs_to_dhms(total_secs_left, time_buf);
7589 /* format all of the numbers we will be reporting */
7590 zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
7591 zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
7592 zfs_nicebytes(total, total_buf, sizeof (total_buf));
7593 zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
7594 zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
7596 /* do not print estimated time if we have a paused scrub */
7597 if (pause == 0) {
7598 (void) printf(gettext("\t%s scanned at %s/s, "
7599 "%s issued at %s/s, %s total\n"),
7600 scanned_buf, srate_buf, issued_buf, irate_buf, total_buf);
7601 } else {
7602 (void) printf(gettext("\t%s scanned, %s issued, %s total\n"),
7603 scanned_buf, issued_buf, total_buf);
7606 if (ps->pss_func == POOL_SCAN_RESILVER) {
7607 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
7608 processed_buf, 100 * fraction_done);
7609 } else if (ps->pss_func == POOL_SCAN_SCRUB) {
7610 (void) printf(gettext("\t%s repaired, %.2f%% done"),
7611 processed_buf, 100 * fraction_done);
7614 if (pause == 0) {
7615 if (total_secs_left != UINT64_MAX &&
7616 issue_rate >= 10 * 1024 * 1024) {
7617 (void) printf(gettext(", %s to go\n"), time_buf);
7618 } else {
7619 (void) printf(gettext(", no estimated "
7620 "completion time\n"));
7622 } else {
7623 (void) printf(gettext("\n"));
7627 static void
7628 print_rebuild_status_impl(vdev_rebuild_stat_t *vrs, char *vdev_name)
7630 if (vrs == NULL || vrs->vrs_state == VDEV_REBUILD_NONE)
7631 return;
7633 printf(" ");
7634 printf_color(ANSI_BOLD, gettext("scan:"));
7635 printf(" ");
7637 uint64_t bytes_scanned = vrs->vrs_bytes_scanned;
7638 uint64_t bytes_issued = vrs->vrs_bytes_issued;
7639 uint64_t bytes_rebuilt = vrs->vrs_bytes_rebuilt;
7640 uint64_t bytes_est = vrs->vrs_bytes_est;
7641 uint64_t scan_rate = (vrs->vrs_pass_bytes_scanned /
7642 (vrs->vrs_pass_time_ms + 1)) * 1000;
7643 uint64_t issue_rate = (vrs->vrs_pass_bytes_issued /
7644 (vrs->vrs_pass_time_ms + 1)) * 1000;
7645 double scan_pct = MIN((double)bytes_scanned * 100 /
7646 (bytes_est + 1), 100);
7648 /* Format all of the numbers we will be reporting */
7649 char bytes_scanned_buf[7], bytes_issued_buf[7];
7650 char bytes_rebuilt_buf[7], bytes_est_buf[7];
7651 char scan_rate_buf[7], issue_rate_buf[7], time_buf[32];
7652 zfs_nicebytes(bytes_scanned, bytes_scanned_buf,
7653 sizeof (bytes_scanned_buf));
7654 zfs_nicebytes(bytes_issued, bytes_issued_buf,
7655 sizeof (bytes_issued_buf));
7656 zfs_nicebytes(bytes_rebuilt, bytes_rebuilt_buf,
7657 sizeof (bytes_rebuilt_buf));
7658 zfs_nicebytes(bytes_est, bytes_est_buf, sizeof (bytes_est_buf));
7659 zfs_nicebytes(scan_rate, scan_rate_buf, sizeof (scan_rate_buf));
7660 zfs_nicebytes(issue_rate, issue_rate_buf, sizeof (issue_rate_buf));
7662 time_t start = vrs->vrs_start_time;
7663 time_t end = vrs->vrs_end_time;
7665 /* Rebuild is finished or canceled. */
7666 if (vrs->vrs_state == VDEV_REBUILD_COMPLETE) {
7667 secs_to_dhms(vrs->vrs_scan_time_ms / 1000, time_buf);
7668 (void) printf(gettext("resilvered (%s) %s in %s "
7669 "with %llu errors on %s"), vdev_name, bytes_rebuilt_buf,
7670 time_buf, (u_longlong_t)vrs->vrs_errors, ctime(&end));
7671 return;
7672 } else if (vrs->vrs_state == VDEV_REBUILD_CANCELED) {
7673 (void) printf(gettext("resilver (%s) canceled on %s"),
7674 vdev_name, ctime(&end));
7675 return;
7676 } else if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
7677 (void) printf(gettext("resilver (%s) in progress since %s"),
7678 vdev_name, ctime(&start));
7681 assert(vrs->vrs_state == VDEV_REBUILD_ACTIVE);
7683 secs_to_dhms(MAX((int64_t)bytes_est - (int64_t)bytes_scanned, 0) /
7684 MAX(scan_rate, 1), time_buf);
7686 (void) printf(gettext("\t%s scanned at %s/s, %s issued %s/s, "
7687 "%s total\n"), bytes_scanned_buf, scan_rate_buf,
7688 bytes_issued_buf, issue_rate_buf, bytes_est_buf);
7689 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
7690 bytes_rebuilt_buf, scan_pct);
7692 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
7693 if (scan_rate >= 10 * 1024 * 1024) {
7694 (void) printf(gettext(", %s to go\n"), time_buf);
7695 } else {
7696 (void) printf(gettext(", no estimated "
7697 "completion time\n"));
7699 } else {
7700 (void) printf(gettext("\n"));
7705 * Print rebuild status for top-level vdevs.
7707 static void
7708 print_rebuild_status(zpool_handle_t *zhp, nvlist_t *nvroot)
7710 nvlist_t **child;
7711 uint_t children;
7713 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
7714 &child, &children) != 0)
7715 children = 0;
7717 for (uint_t c = 0; c < children; c++) {
7718 vdev_rebuild_stat_t *vrs;
7719 uint_t i;
7721 if (nvlist_lookup_uint64_array(child[c],
7722 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
7723 char *name = zpool_vdev_name(g_zfs, zhp,
7724 child[c], VDEV_NAME_TYPE_ID);
7725 print_rebuild_status_impl(vrs, name);
7726 free(name);
7732 * As we don't scrub checkpointed blocks, we want to warn the user that we
7733 * skipped scanning some blocks if a checkpoint exists or existed at any
7734 * time during the scan. If a sequential instead of healing reconstruction
7735 * was performed then the blocks were reconstructed. However, their checksums
7736 * have not been verified so we still print the warning.
7738 static void
7739 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
7741 if (ps == NULL || pcs == NULL)
7742 return;
7744 if (pcs->pcs_state == CS_NONE ||
7745 pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
7746 return;
7748 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
7750 if (ps->pss_state == DSS_NONE)
7751 return;
7753 if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
7754 ps->pss_end_time < pcs->pcs_start_time)
7755 return;
7757 if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
7758 (void) printf(gettext(" scan warning: skipped blocks "
7759 "that are only referenced by the checkpoint.\n"));
7760 } else {
7761 assert(ps->pss_state == DSS_SCANNING);
7762 (void) printf(gettext(" scan warning: skipping blocks "
7763 "that are only referenced by the checkpoint.\n"));
7768 * Returns B_TRUE if there is an active rebuild in progress. Otherwise,
7769 * B_FALSE is returned and 'rebuild_end_time' is set to the end time for
7770 * the last completed (or cancelled) rebuild.
7772 static boolean_t
7773 check_rebuilding(nvlist_t *nvroot, uint64_t *rebuild_end_time)
7775 nvlist_t **child;
7776 uint_t children;
7777 boolean_t rebuilding = B_FALSE;
7778 uint64_t end_time = 0;
7780 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
7781 &child, &children) != 0)
7782 children = 0;
7784 for (uint_t c = 0; c < children; c++) {
7785 vdev_rebuild_stat_t *vrs;
7786 uint_t i;
7788 if (nvlist_lookup_uint64_array(child[c],
7789 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
7791 if (vrs->vrs_end_time > end_time)
7792 end_time = vrs->vrs_end_time;
7794 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
7795 rebuilding = B_TRUE;
7796 end_time = 0;
7797 break;
7802 if (rebuild_end_time != NULL)
7803 *rebuild_end_time = end_time;
7805 return (rebuilding);
7809 * Print the scan status.
7811 static void
7812 print_scan_status(zpool_handle_t *zhp, nvlist_t *nvroot)
7814 uint64_t rebuild_end_time = 0, resilver_end_time = 0;
7815 boolean_t have_resilver = B_FALSE, have_scrub = B_FALSE;
7816 boolean_t active_resilver = B_FALSE;
7817 pool_checkpoint_stat_t *pcs = NULL;
7818 pool_scan_stat_t *ps = NULL;
7819 uint_t c;
7821 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
7822 (uint64_t **)&ps, &c) == 0) {
7823 if (ps->pss_func == POOL_SCAN_RESILVER) {
7824 resilver_end_time = ps->pss_end_time;
7825 active_resilver = (ps->pss_state == DSS_SCANNING);
7828 have_resilver = (ps->pss_func == POOL_SCAN_RESILVER);
7829 have_scrub = (ps->pss_func == POOL_SCAN_SCRUB);
7832 boolean_t active_rebuild = check_rebuilding(nvroot, &rebuild_end_time);
7833 boolean_t have_rebuild = (active_rebuild || (rebuild_end_time > 0));
7835 /* Always print the scrub status when available. */
7836 if (have_scrub)
7837 print_scan_scrub_resilver_status(ps);
7840 * When there is an active resilver or rebuild print its status.
7841 * Otherwise print the status of the last resilver or rebuild.
7843 if (active_resilver || (!active_rebuild && have_resilver &&
7844 resilver_end_time && resilver_end_time > rebuild_end_time)) {
7845 print_scan_scrub_resilver_status(ps);
7846 } else if (active_rebuild || (!active_resilver && have_rebuild &&
7847 rebuild_end_time && rebuild_end_time > resilver_end_time)) {
7848 print_rebuild_status(zhp, nvroot);
7851 (void) nvlist_lookup_uint64_array(nvroot,
7852 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
7853 print_checkpoint_scan_warning(ps, pcs);
7857 * Print out detailed removal status.
7859 static void
7860 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
7862 char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
7863 time_t start, end;
7864 nvlist_t *config, *nvroot;
7865 nvlist_t **child;
7866 uint_t children;
7867 char *vdev_name;
7869 if (prs == NULL || prs->prs_state == DSS_NONE)
7870 return;
7873 * Determine name of vdev.
7875 config = zpool_get_config(zhp, NULL);
7876 nvroot = fnvlist_lookup_nvlist(config,
7877 ZPOOL_CONFIG_VDEV_TREE);
7878 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
7879 &child, &children) == 0);
7880 assert(prs->prs_removing_vdev < children);
7881 vdev_name = zpool_vdev_name(g_zfs, zhp,
7882 child[prs->prs_removing_vdev], B_TRUE);
7884 printf_color(ANSI_BOLD, gettext("remove: "));
7886 start = prs->prs_start_time;
7887 end = prs->prs_end_time;
7888 zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
7891 * Removal is finished or canceled.
7893 if (prs->prs_state == DSS_FINISHED) {
7894 uint64_t minutes_taken = (end - start) / 60;
7896 (void) printf(gettext("Removal of vdev %llu copied %s "
7897 "in %lluh%um, completed on %s"),
7898 (longlong_t)prs->prs_removing_vdev,
7899 copied_buf,
7900 (u_longlong_t)(minutes_taken / 60),
7901 (uint_t)(minutes_taken % 60),
7902 ctime((time_t *)&end));
7903 } else if (prs->prs_state == DSS_CANCELED) {
7904 (void) printf(gettext("Removal of %s canceled on %s"),
7905 vdev_name, ctime(&end));
7906 } else {
7907 uint64_t copied, total, elapsed, mins_left, hours_left;
7908 double fraction_done;
7909 uint_t rate;
7911 assert(prs->prs_state == DSS_SCANNING);
7914 * Removal is in progress.
7916 (void) printf(gettext(
7917 "Evacuation of %s in progress since %s"),
7918 vdev_name, ctime(&start));
7920 copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
7921 total = prs->prs_to_copy;
7922 fraction_done = (double)copied / total;
7924 /* elapsed time for this pass */
7925 elapsed = time(NULL) - prs->prs_start_time;
7926 elapsed = elapsed > 0 ? elapsed : 1;
7927 rate = copied / elapsed;
7928 rate = rate > 0 ? rate : 1;
7929 mins_left = ((total - copied) / rate) / 60;
7930 hours_left = mins_left / 60;
7932 zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
7933 zfs_nicenum(total, total_buf, sizeof (total_buf));
7934 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
7937 * do not print estimated time if hours_left is more than
7938 * 30 days
7940 (void) printf(gettext(
7941 "\t%s copied out of %s at %s/s, %.2f%% done"),
7942 examined_buf, total_buf, rate_buf, 100 * fraction_done);
7943 if (hours_left < (30 * 24)) {
7944 (void) printf(gettext(", %lluh%um to go\n"),
7945 (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
7946 } else {
7947 (void) printf(gettext(
7948 ", (copy is slow, no estimated time)\n"));
7951 free(vdev_name);
7953 if (prs->prs_mapping_memory > 0) {
7954 char mem_buf[7];
7955 zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
7956 (void) printf(gettext(
7957 "\t%s memory used for removed device mappings\n"),
7958 mem_buf);
7962 static void
7963 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
7965 time_t start;
7966 char space_buf[7];
7968 if (pcs == NULL || pcs->pcs_state == CS_NONE)
7969 return;
7971 (void) printf(gettext("checkpoint: "));
7973 start = pcs->pcs_start_time;
7974 zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
7976 if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
7977 char *date = ctime(&start);
7980 * ctime() adds a newline at the end of the generated
7981 * string, thus the weird format specifier and the
7982 * strlen() call used to chop it off from the output.
7984 (void) printf(gettext("created %.*s, consumes %s\n"),
7985 (int)(strlen(date) - 1), date, space_buf);
7986 return;
7989 assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
7991 (void) printf(gettext("discarding, %s remaining.\n"),
7992 space_buf);
7995 static void
7996 print_error_log(zpool_handle_t *zhp)
7998 nvlist_t *nverrlist = NULL;
7999 nvpair_t *elem;
8000 char *pathname;
8001 size_t len = MAXPATHLEN * 2;
8003 if (zpool_get_errlog(zhp, &nverrlist) != 0)
8004 return;
8006 (void) printf("errors: Permanent errors have been "
8007 "detected in the following files:\n\n");
8009 pathname = safe_malloc(len);
8010 elem = NULL;
8011 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
8012 nvlist_t *nv;
8013 uint64_t dsobj, obj;
8015 verify(nvpair_value_nvlist(elem, &nv) == 0);
8016 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
8017 &dsobj) == 0);
8018 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
8019 &obj) == 0);
8020 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
8021 (void) printf("%7s %s\n", "", pathname);
8023 free(pathname);
8024 nvlist_free(nverrlist);
8027 static void
8028 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
8029 uint_t nspares)
8031 uint_t i;
8032 char *name;
8034 if (nspares == 0)
8035 return;
8037 (void) printf(gettext("\tspares\n"));
8039 for (i = 0; i < nspares; i++) {
8040 name = zpool_vdev_name(g_zfs, zhp, spares[i],
8041 cb->cb_name_flags);
8042 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE, NULL);
8043 free(name);
8047 static void
8048 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
8049 uint_t nl2cache)
8051 uint_t i;
8052 char *name;
8054 if (nl2cache == 0)
8055 return;
8057 (void) printf(gettext("\tcache\n"));
8059 for (i = 0; i < nl2cache; i++) {
8060 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
8061 cb->cb_name_flags);
8062 print_status_config(zhp, cb, name, l2cache[i], 2,
8063 B_FALSE, NULL);
8064 free(name);
8068 static void
8069 print_dedup_stats(nvlist_t *config)
8071 ddt_histogram_t *ddh;
8072 ddt_stat_t *dds;
8073 ddt_object_t *ddo;
8074 uint_t c;
8075 char dspace[6], mspace[6];
8078 * If the pool was faulted then we may not have been able to
8079 * obtain the config. Otherwise, if we have anything in the dedup
8080 * table continue processing the stats.
8082 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
8083 (uint64_t **)&ddo, &c) != 0)
8084 return;
8086 (void) printf("\n");
8087 (void) printf(gettext(" dedup: "));
8088 if (ddo->ddo_count == 0) {
8089 (void) printf(gettext("no DDT entries\n"));
8090 return;
8093 zfs_nicebytes(ddo->ddo_dspace, dspace, sizeof (dspace));
8094 zfs_nicebytes(ddo->ddo_mspace, mspace, sizeof (mspace));
8095 (void) printf("DDT entries %llu, size %s on disk, %s in core\n",
8096 (u_longlong_t)ddo->ddo_count,
8097 dspace,
8098 mspace);
8100 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
8101 (uint64_t **)&dds, &c) == 0);
8102 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
8103 (uint64_t **)&ddh, &c) == 0);
8104 zpool_dump_ddt(dds, ddh);
8108 * Display a summary of pool status. Displays a summary such as:
8110 * pool: tank
8111 * status: DEGRADED
8112 * reason: One or more devices ...
8113 * see: https://openzfs.github.io/openzfs-docs/msg/ZFS-xxxx-01
8114 * config:
8115 * mirror DEGRADED
8116 * c1t0d0 OK
8117 * c2t0d0 UNAVAIL
8119 * When given the '-v' option, we print out the complete config. If the '-e'
8120 * option is specified, then we print out error rate information as well.
8122 static int
8123 status_callback(zpool_handle_t *zhp, void *data)
8125 status_cbdata_t *cbp = data;
8126 nvlist_t *config, *nvroot;
8127 const char *msgid;
8128 zpool_status_t reason;
8129 zpool_errata_t errata;
8130 const char *health;
8131 uint_t c;
8132 vdev_stat_t *vs;
8134 config = zpool_get_config(zhp, NULL);
8135 reason = zpool_get_status(zhp, &msgid, &errata);
8137 cbp->cb_count++;
8140 * If we were given 'zpool status -x', only report those pools with
8141 * problems.
8143 if (cbp->cb_explain &&
8144 (reason == ZPOOL_STATUS_OK ||
8145 reason == ZPOOL_STATUS_VERSION_OLDER ||
8146 reason == ZPOOL_STATUS_FEAT_DISABLED ||
8147 reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
8148 reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
8149 if (!cbp->cb_allpools) {
8150 (void) printf(gettext("pool '%s' is healthy\n"),
8151 zpool_get_name(zhp));
8152 if (cbp->cb_first)
8153 cbp->cb_first = B_FALSE;
8155 return (0);
8158 if (cbp->cb_first)
8159 cbp->cb_first = B_FALSE;
8160 else
8161 (void) printf("\n");
8163 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
8164 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
8165 (uint64_t **)&vs, &c) == 0);
8167 health = zpool_get_state_str(zhp);
8169 printf(" ");
8170 printf_color(ANSI_BOLD, gettext("pool:"));
8171 printf(" %s\n", zpool_get_name(zhp));
8172 fputc(' ', stdout);
8173 printf_color(ANSI_BOLD, gettext("state: "));
8175 printf_color(health_str_to_color(health), "%s", health);
8177 fputc('\n', stdout);
8179 switch (reason) {
8180 case ZPOOL_STATUS_MISSING_DEV_R:
8181 printf_color(ANSI_BOLD, gettext("status: "));
8182 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8183 "not be opened. Sufficient replicas exist for\n\tthe pool "
8184 "to continue functioning in a degraded state.\n"));
8185 printf_color(ANSI_BOLD, gettext("action: "));
8186 printf_color(ANSI_YELLOW, gettext("Attach the missing device "
8187 "and online it using 'zpool online'.\n"));
8188 break;
8190 case ZPOOL_STATUS_MISSING_DEV_NR:
8191 printf_color(ANSI_BOLD, gettext("status: "));
8192 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8193 "not be opened. There are insufficient\n\treplicas for the"
8194 " pool to continue functioning.\n"));
8195 printf_color(ANSI_BOLD, gettext("action: "));
8196 printf_color(ANSI_YELLOW, gettext("Attach the missing device "
8197 "and online it using 'zpool online'.\n"));
8198 break;
8200 case ZPOOL_STATUS_CORRUPT_LABEL_R:
8201 printf_color(ANSI_BOLD, gettext("status: "));
8202 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8203 "not be used because the label is missing or\n\tinvalid. "
8204 "Sufficient replicas exist for the pool to continue\n\t"
8205 "functioning in a degraded state.\n"));
8206 printf_color(ANSI_BOLD, gettext("action: "));
8207 printf_color(ANSI_YELLOW, gettext("Replace the device using "
8208 "'zpool replace'.\n"));
8209 break;
8211 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
8212 printf_color(ANSI_BOLD, gettext("status: "));
8213 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8214 "not be used because the label is missing \n\tor invalid. "
8215 "There are insufficient replicas for the pool to "
8216 "continue\n\tfunctioning.\n"));
8217 zpool_explain_recover(zpool_get_handle(zhp),
8218 zpool_get_name(zhp), reason, config);
8219 break;
8221 case ZPOOL_STATUS_FAILING_DEV:
8222 printf_color(ANSI_BOLD, gettext("status: "));
8223 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8224 "experienced an unrecoverable error. An\n\tattempt was "
8225 "made to correct the error. Applications are "
8226 "unaffected.\n"));
8227 printf_color(ANSI_BOLD, gettext("action: "));
8228 printf_color(ANSI_YELLOW, gettext("Determine if the "
8229 "device needs to be replaced, and clear the errors\n\tusing"
8230 " 'zpool clear' or replace the device with 'zpool "
8231 "replace'.\n"));
8232 break;
8234 case ZPOOL_STATUS_OFFLINE_DEV:
8235 printf_color(ANSI_BOLD, gettext("status: "));
8236 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8237 "been taken offline by the administrator.\n\tSufficient "
8238 "replicas exist for the pool to continue functioning in "
8239 "a\n\tdegraded state.\n"));
8240 printf_color(ANSI_BOLD, gettext("action: "));
8241 printf_color(ANSI_YELLOW, gettext("Online the device "
8242 "using 'zpool online' or replace the device with\n\t'zpool "
8243 "replace'.\n"));
8244 break;
8246 case ZPOOL_STATUS_REMOVED_DEV:
8247 printf_color(ANSI_BOLD, gettext("status: "));
8248 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8249 "been removed by the administrator.\n\tSufficient "
8250 "replicas exist for the pool to continue functioning in "
8251 "a\n\tdegraded state.\n"));
8252 printf_color(ANSI_BOLD, gettext("action: "));
8253 printf_color(ANSI_YELLOW, gettext("Online the device "
8254 "using zpool online' or replace the device with\n\t'zpool "
8255 "replace'.\n"));
8256 break;
8258 case ZPOOL_STATUS_RESILVERING:
8259 case ZPOOL_STATUS_REBUILDING:
8260 printf_color(ANSI_BOLD, gettext("status: "));
8261 printf_color(ANSI_YELLOW, gettext("One or more devices is "
8262 "currently being resilvered. The pool will\n\tcontinue "
8263 "to function, possibly in a degraded state.\n"));
8264 printf_color(ANSI_BOLD, gettext("action: "));
8265 printf_color(ANSI_YELLOW, gettext("Wait for the resilver to "
8266 "complete.\n"));
8267 break;
8269 case ZPOOL_STATUS_REBUILD_SCRUB:
8270 printf_color(ANSI_BOLD, gettext("status: "));
8271 printf_color(ANSI_YELLOW, gettext("One or more devices have "
8272 "been sequentially resilvered, scrubbing\n\tthe pool "
8273 "is recommended.\n"));
8274 printf_color(ANSI_BOLD, gettext("action: "));
8275 printf_color(ANSI_YELLOW, gettext("Use 'zpool scrub' to "
8276 "verify all data checksums.\n"));
8277 break;
8279 case ZPOOL_STATUS_CORRUPT_DATA:
8280 printf_color(ANSI_BOLD, gettext("status: "));
8281 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8282 "experienced an error resulting in data\n\tcorruption. "
8283 "Applications may be affected.\n"));
8284 printf_color(ANSI_BOLD, gettext("action: "));
8285 printf_color(ANSI_YELLOW, gettext("Restore the file in question"
8286 " if possible. Otherwise restore the\n\tentire pool from "
8287 "backup.\n"));
8288 break;
8290 case ZPOOL_STATUS_CORRUPT_POOL:
8291 printf_color(ANSI_BOLD, gettext("status: "));
8292 printf_color(ANSI_YELLOW, gettext("The pool metadata is "
8293 "corrupted and the pool cannot be opened.\n"));
8294 zpool_explain_recover(zpool_get_handle(zhp),
8295 zpool_get_name(zhp), reason, config);
8296 break;
8298 case ZPOOL_STATUS_VERSION_OLDER:
8299 printf_color(ANSI_BOLD, gettext("status: "));
8300 printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
8301 "a legacy on-disk format. The pool can\n\tstill be used, "
8302 "but some features are unavailable.\n"));
8303 printf_color(ANSI_BOLD, gettext("action: "));
8304 printf_color(ANSI_YELLOW, gettext("Upgrade the pool using "
8305 "'zpool upgrade'. Once this is done, the\n\tpool will no "
8306 "longer be accessible on software that does not support\n\t"
8307 "feature flags.\n"));
8308 break;
8310 case ZPOOL_STATUS_VERSION_NEWER:
8311 printf_color(ANSI_BOLD, gettext("status: "));
8312 printf_color(ANSI_YELLOW, gettext("The pool has been upgraded "
8313 "to a newer, incompatible on-disk version.\n\tThe pool "
8314 "cannot be accessed on this system.\n"));
8315 printf_color(ANSI_BOLD, gettext("action: "));
8316 printf_color(ANSI_YELLOW, gettext("Access the pool from a "
8317 "system running more recent software, or\n\trestore the "
8318 "pool from backup.\n"));
8319 break;
8321 case ZPOOL_STATUS_FEAT_DISABLED:
8322 printf_color(ANSI_BOLD, gettext("status: "));
8323 printf_color(ANSI_YELLOW, gettext("Some supported and "
8324 "requested features are not enabled on the pool.\n\t"
8325 "The pool can still be used, but some features are "
8326 "unavailable.\n"));
8327 printf_color(ANSI_BOLD, gettext("action: "));
8328 printf_color(ANSI_YELLOW, gettext("Enable all features using "
8329 "'zpool upgrade'. Once this is done,\n\tthe pool may no "
8330 "longer be accessible by software that does not support\n\t"
8331 "the features. See zpool-features(7) for details.\n"));
8332 break;
8334 case ZPOOL_STATUS_COMPATIBILITY_ERR:
8335 printf_color(ANSI_BOLD, gettext("status: "));
8336 printf_color(ANSI_YELLOW, gettext("This pool has a "
8337 "compatibility list specified, but it could not be\n\t"
8338 "read/parsed at this time. The pool can still be used, "
8339 "but this\n\tshould be investigated.\n"));
8340 printf_color(ANSI_BOLD, gettext("action: "));
8341 printf_color(ANSI_YELLOW, gettext("Check the value of the "
8342 "'compatibility' property against the\n\t"
8343 "appropriate file in " ZPOOL_SYSCONF_COMPAT_D " or "
8344 ZPOOL_DATA_COMPAT_D ".\n"));
8345 break;
8347 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
8348 printf_color(ANSI_BOLD, gettext("status: "));
8349 printf_color(ANSI_YELLOW, gettext("One or more features "
8350 "are enabled on the pool despite not being\n\t"
8351 "requested by the 'compatibility' property.\n"));
8352 printf_color(ANSI_BOLD, gettext("action: "));
8353 printf_color(ANSI_YELLOW, gettext("Consider setting "
8354 "'compatibility' to an appropriate value, or\n\t"
8355 "adding needed features to the relevant file in\n\t"
8356 ZPOOL_SYSCONF_COMPAT_D " or " ZPOOL_DATA_COMPAT_D ".\n"));
8357 break;
8359 case ZPOOL_STATUS_UNSUP_FEAT_READ:
8360 printf_color(ANSI_BOLD, gettext("status: "));
8361 printf_color(ANSI_YELLOW, gettext("The pool cannot be accessed "
8362 "on this system because it uses the\n\tfollowing feature(s)"
8363 " not supported on this system:\n"));
8364 zpool_print_unsup_feat(config);
8365 (void) printf("\n");
8366 printf_color(ANSI_BOLD, gettext("action: "));
8367 printf_color(ANSI_YELLOW, gettext("Access the pool from a "
8368 "system that supports the required feature(s),\n\tor "
8369 "restore the pool from backup.\n"));
8370 break;
8372 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
8373 printf_color(ANSI_BOLD, gettext("status: "));
8374 printf_color(ANSI_YELLOW, gettext("The pool can only be "
8375 "accessed in read-only mode on this system. It\n\tcannot be"
8376 " accessed in read-write mode because it uses the "
8377 "following\n\tfeature(s) not supported on this system:\n"));
8378 zpool_print_unsup_feat(config);
8379 (void) printf("\n");
8380 printf_color(ANSI_BOLD, gettext("action: "));
8381 printf_color(ANSI_YELLOW, gettext("The pool cannot be accessed "
8382 "in read-write mode. Import the pool with\n"
8383 "\t\"-o readonly=on\", access the pool from a system that "
8384 "supports the\n\trequired feature(s), or restore the "
8385 "pool from backup.\n"));
8386 break;
8388 case ZPOOL_STATUS_FAULTED_DEV_R:
8389 printf_color(ANSI_BOLD, gettext("status: "));
8390 printf_color(ANSI_YELLOW, gettext("One or more devices are "
8391 "faulted in response to persistent errors.\n\tSufficient "
8392 "replicas exist for the pool to continue functioning "
8393 "in a\n\tdegraded state.\n"));
8394 printf_color(ANSI_BOLD, gettext("action: "));
8395 printf_color(ANSI_YELLOW, gettext("Replace the faulted device, "
8396 "or use 'zpool clear' to mark the device\n\trepaired.\n"));
8397 break;
8399 case ZPOOL_STATUS_FAULTED_DEV_NR:
8400 printf_color(ANSI_BOLD, gettext("status: "));
8401 printf_color(ANSI_YELLOW, gettext("One or more devices are "
8402 "faulted in response to persistent errors. There are "
8403 "insufficient replicas for the pool to\n\tcontinue "
8404 "functioning.\n"));
8405 printf_color(ANSI_BOLD, gettext("action: "));
8406 printf_color(ANSI_YELLOW, gettext("Destroy and re-create the "
8407 "pool from a backup source. Manually marking the device\n"
8408 "\trepaired using 'zpool clear' may allow some data "
8409 "to be recovered.\n"));
8410 break;
8412 case ZPOOL_STATUS_IO_FAILURE_MMP:
8413 printf_color(ANSI_BOLD, gettext("status: "));
8414 printf_color(ANSI_YELLOW, gettext("The pool is suspended "
8415 "because multihost writes failed or were delayed;\n\t"
8416 "another system could import the pool undetected.\n"));
8417 printf_color(ANSI_BOLD, gettext("action: "));
8418 printf_color(ANSI_YELLOW, gettext("Make sure the pool's devices"
8419 " are connected, then reboot your system and\n\timport the "
8420 "pool.\n"));
8421 break;
8423 case ZPOOL_STATUS_IO_FAILURE_WAIT:
8424 case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
8425 printf_color(ANSI_BOLD, gettext("status: "));
8426 printf_color(ANSI_YELLOW, gettext("One or more devices are "
8427 "faulted in response to IO failures.\n"));
8428 printf_color(ANSI_BOLD, gettext("action: "));
8429 printf_color(ANSI_YELLOW, gettext("Make sure the affected "
8430 "devices are connected, then run 'zpool clear'.\n"));
8431 break;
8433 case ZPOOL_STATUS_BAD_LOG:
8434 printf_color(ANSI_BOLD, gettext("status: "));
8435 printf_color(ANSI_YELLOW, gettext("An intent log record "
8436 "could not be read.\n"
8437 "\tWaiting for administrator intervention to fix the "
8438 "faulted pool.\n"));
8439 printf_color(ANSI_BOLD, gettext("action: "));
8440 printf_color(ANSI_YELLOW, gettext("Either restore the affected "
8441 "device(s) and run 'zpool online',\n"
8442 "\tor ignore the intent log records by running "
8443 "'zpool clear'.\n"));
8444 break;
8446 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
8447 (void) printf(gettext("status: One or more devices are "
8448 "configured to use a non-native block size.\n"
8449 "\tExpect reduced performance.\n"));
8450 (void) printf(gettext("action: Replace affected devices with "
8451 "devices that support the\n\tconfigured block size, or "
8452 "migrate data to a properly configured\n\tpool.\n"));
8453 break;
8455 case ZPOOL_STATUS_HOSTID_MISMATCH:
8456 printf_color(ANSI_BOLD, gettext("status: "));
8457 printf_color(ANSI_YELLOW, gettext("Mismatch between pool hostid"
8458 " and system hostid on imported pool.\n\tThis pool was "
8459 "previously imported into a system with a different "
8460 "hostid,\n\tand then was verbatim imported into this "
8461 "system.\n"));
8462 printf_color(ANSI_BOLD, gettext("action: "));
8463 printf_color(ANSI_YELLOW, gettext("Export this pool on all "
8464 "systems on which it is imported.\n"
8465 "\tThen import it to correct the mismatch.\n"));
8466 break;
8468 case ZPOOL_STATUS_ERRATA:
8469 printf_color(ANSI_BOLD, gettext("status: "));
8470 printf_color(ANSI_YELLOW, gettext("Errata #%d detected.\n"),
8471 errata);
8473 switch (errata) {
8474 case ZPOOL_ERRATA_NONE:
8475 break;
8477 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
8478 printf_color(ANSI_BOLD, gettext("action: "));
8479 printf_color(ANSI_YELLOW, gettext("To correct the issue"
8480 " run 'zpool scrub'.\n"));
8481 break;
8483 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
8484 (void) printf(gettext("\tExisting encrypted datasets "
8485 "contain an on-disk incompatibility\n\twhich "
8486 "needs to be corrected.\n"));
8487 printf_color(ANSI_BOLD, gettext("action: "));
8488 printf_color(ANSI_YELLOW, gettext("To correct the issue"
8489 " backup existing encrypted datasets to new\n\t"
8490 "encrypted datasets and destroy the old ones. "
8491 "'zfs mount -o ro' can\n\tbe used to temporarily "
8492 "mount existing encrypted datasets readonly.\n"));
8493 break;
8495 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
8496 (void) printf(gettext("\tExisting encrypted snapshots "
8497 "and bookmarks contain an on-disk\n\tincompat"
8498 "ibility. This may cause on-disk corruption if "
8499 "they are used\n\twith 'zfs recv'.\n"));
8500 printf_color(ANSI_BOLD, gettext("action: "));
8501 printf_color(ANSI_YELLOW, gettext("To correct the"
8502 "issue, enable the bookmark_v2 feature. No "
8503 "additional\n\taction is needed if there are no "
8504 "encrypted snapshots or bookmarks.\n\tIf preserving"
8505 "the encrypted snapshots and bookmarks is required,"
8506 " use\n\ta non-raw send to backup and restore them."
8507 " Alternately, they may be\n\tremoved to resolve "
8508 "the incompatibility.\n"));
8509 break;
8511 default:
8513 * All errata which allow the pool to be imported
8514 * must contain an action message.
8516 assert(0);
8518 break;
8520 default:
8522 * The remaining errors can't actually be generated, yet.
8524 assert(reason == ZPOOL_STATUS_OK);
8527 if (msgid != NULL) {
8528 printf(" ");
8529 printf_color(ANSI_BOLD, gettext("see:"));
8530 printf(gettext(
8531 " https://openzfs.github.io/openzfs-docs/msg/%s\n"),
8532 msgid);
8535 if (config != NULL) {
8536 uint64_t nerr;
8537 nvlist_t **spares, **l2cache;
8538 uint_t nspares, nl2cache;
8539 pool_checkpoint_stat_t *pcs = NULL;
8540 pool_removal_stat_t *prs = NULL;
8542 print_scan_status(zhp, nvroot);
8544 (void) nvlist_lookup_uint64_array(nvroot,
8545 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
8546 print_removal_status(zhp, prs);
8548 (void) nvlist_lookup_uint64_array(nvroot,
8549 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
8550 print_checkpoint_status(pcs);
8552 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
8553 cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
8554 if (cbp->cb_namewidth < 10)
8555 cbp->cb_namewidth = 10;
8557 color_start(ANSI_BOLD);
8558 (void) printf(gettext("config:\n\n"));
8559 (void) printf(gettext("\t%-*s %-8s %5s %5s %5s"),
8560 cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
8561 "CKSUM");
8562 color_end();
8564 if (cbp->cb_print_slow_ios) {
8565 printf_color(ANSI_BOLD, " %5s", gettext("SLOW"));
8568 if (cbp->vcdl != NULL)
8569 print_cmd_columns(cbp->vcdl, 0);
8571 printf("\n");
8573 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
8574 B_FALSE, NULL);
8576 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
8577 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
8578 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
8580 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
8581 &l2cache, &nl2cache) == 0)
8582 print_l2cache(zhp, cbp, l2cache, nl2cache);
8584 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
8585 &spares, &nspares) == 0)
8586 print_spares(zhp, cbp, spares, nspares);
8588 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
8589 &nerr) == 0) {
8590 nvlist_t *nverrlist = NULL;
8593 * If the approximate error count is small, get a
8594 * precise count by fetching the entire log and
8595 * uniquifying the results.
8597 if (nerr > 0 && nerr < 100 && !cbp->cb_verbose &&
8598 zpool_get_errlog(zhp, &nverrlist) == 0) {
8599 nvpair_t *elem;
8601 elem = NULL;
8602 nerr = 0;
8603 while ((elem = nvlist_next_nvpair(nverrlist,
8604 elem)) != NULL) {
8605 nerr++;
8608 nvlist_free(nverrlist);
8610 (void) printf("\n");
8612 if (nerr == 0)
8613 (void) printf(gettext("errors: No known data "
8614 "errors\n"));
8615 else if (!cbp->cb_verbose)
8616 (void) printf(gettext("errors: %llu data "
8617 "errors, use '-v' for a list\n"),
8618 (u_longlong_t)nerr);
8619 else
8620 print_error_log(zhp);
8623 if (cbp->cb_dedup_stats)
8624 print_dedup_stats(config);
8625 } else {
8626 (void) printf(gettext("config: The configuration cannot be "
8627 "determined.\n"));
8630 return (0);
8634 * zpool status [-c [script1,script2,...]] [-igLpPstvx] [-T d|u] [pool] ...
8635 * [interval [count]]
8637 * -c CMD For each vdev, run command CMD
8638 * -i Display vdev initialization status.
8639 * -g Display guid for individual vdev name.
8640 * -L Follow links when resolving vdev path name.
8641 * -p Display values in parsable (exact) format.
8642 * -P Display full path for vdev name.
8643 * -s Display slow IOs column.
8644 * -v Display complete error logs
8645 * -x Display only pools with potential problems
8646 * -D Display dedup status (undocumented)
8647 * -t Display vdev TRIM status.
8648 * -T Display a timestamp in date(1) or Unix format
8650 * Describes the health status of all pools or some subset.
8653 zpool_do_status(int argc, char **argv)
8655 int c;
8656 int ret;
8657 float interval = 0;
8658 unsigned long count = 0;
8659 status_cbdata_t cb = { 0 };
8660 char *cmd = NULL;
8662 /* check options */
8663 while ((c = getopt(argc, argv, "c:igLpPsvxDtT:")) != -1) {
8664 switch (c) {
8665 case 'c':
8666 if (cmd != NULL) {
8667 fprintf(stderr,
8668 gettext("Can't set -c flag twice\n"));
8669 exit(1);
8672 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
8673 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
8674 fprintf(stderr, gettext(
8675 "Can't run -c, disabled by "
8676 "ZPOOL_SCRIPTS_ENABLED.\n"));
8677 exit(1);
8680 if ((getuid() <= 0 || geteuid() <= 0) &&
8681 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
8682 fprintf(stderr, gettext(
8683 "Can't run -c with root privileges "
8684 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
8685 exit(1);
8687 cmd = optarg;
8688 break;
8689 case 'i':
8690 cb.cb_print_vdev_init = B_TRUE;
8691 break;
8692 case 'g':
8693 cb.cb_name_flags |= VDEV_NAME_GUID;
8694 break;
8695 case 'L':
8696 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
8697 break;
8698 case 'p':
8699 cb.cb_literal = B_TRUE;
8700 break;
8701 case 'P':
8702 cb.cb_name_flags |= VDEV_NAME_PATH;
8703 break;
8704 case 's':
8705 cb.cb_print_slow_ios = B_TRUE;
8706 break;
8707 case 'v':
8708 cb.cb_verbose = B_TRUE;
8709 break;
8710 case 'x':
8711 cb.cb_explain = B_TRUE;
8712 break;
8713 case 'D':
8714 cb.cb_dedup_stats = B_TRUE;
8715 break;
8716 case 't':
8717 cb.cb_print_vdev_trim = B_TRUE;
8718 break;
8719 case 'T':
8720 get_timestamp_arg(*optarg);
8721 break;
8722 case '?':
8723 if (optopt == 'c') {
8724 print_zpool_script_list("status");
8725 exit(0);
8726 } else {
8727 fprintf(stderr,
8728 gettext("invalid option '%c'\n"), optopt);
8730 usage(B_FALSE);
8734 argc -= optind;
8735 argv += optind;
8737 get_interval_count(&argc, argv, &interval, &count);
8739 if (argc == 0)
8740 cb.cb_allpools = B_TRUE;
8742 cb.cb_first = B_TRUE;
8743 cb.cb_print_status = B_TRUE;
8745 for (;;) {
8746 if (timestamp_fmt != NODATE)
8747 print_timestamp(timestamp_fmt);
8749 if (cmd != NULL)
8750 cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
8751 NULL, NULL, 0, 0);
8753 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8754 cb.cb_literal, status_callback, &cb);
8756 if (cb.vcdl != NULL)
8757 free_vdev_cmd_data_list(cb.vcdl);
8759 if (argc == 0 && cb.cb_count == 0)
8760 (void) fprintf(stderr, gettext("no pools available\n"));
8761 else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
8762 (void) printf(gettext("all pools are healthy\n"));
8764 if (ret != 0)
8765 return (ret);
8767 if (interval == 0)
8768 break;
8770 if (count != 0 && --count == 0)
8771 break;
8773 (void) fsleep(interval);
8776 return (0);
8779 typedef struct upgrade_cbdata {
8780 int cb_first;
8781 int cb_argc;
8782 uint64_t cb_version;
8783 char **cb_argv;
8784 } upgrade_cbdata_t;
8786 static int
8787 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
8789 int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
8790 int *count = (int *)unsupp_fs;
8792 if (zfs_version > ZPL_VERSION) {
8793 (void) printf(gettext("%s (v%d) is not supported by this "
8794 "implementation of ZFS.\n"),
8795 zfs_get_name(zhp), zfs_version);
8796 (*count)++;
8799 zfs_iter_filesystems(zhp, check_unsupp_fs, unsupp_fs);
8801 zfs_close(zhp);
8803 return (0);
8806 static int
8807 upgrade_version(zpool_handle_t *zhp, uint64_t version)
8809 int ret;
8810 nvlist_t *config;
8811 uint64_t oldversion;
8812 int unsupp_fs = 0;
8814 config = zpool_get_config(zhp, NULL);
8815 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
8816 &oldversion) == 0);
8818 char compat[ZFS_MAXPROPLEN];
8819 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
8820 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
8821 compat[0] = '\0';
8823 assert(SPA_VERSION_IS_SUPPORTED(oldversion));
8824 assert(oldversion < version);
8826 ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
8827 if (ret != 0)
8828 return (ret);
8830 if (unsupp_fs) {
8831 (void) fprintf(stderr, gettext("Upgrade not performed due "
8832 "to %d unsupported filesystems (max v%d).\n"),
8833 unsupp_fs, (int)ZPL_VERSION);
8834 return (1);
8837 if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
8838 (void) fprintf(stderr, gettext("Upgrade not performed because "
8839 "'compatibility' property set to '"
8840 ZPOOL_COMPAT_LEGACY "'.\n"));
8841 return (1);
8844 ret = zpool_upgrade(zhp, version);
8845 if (ret != 0)
8846 return (ret);
8848 if (version >= SPA_VERSION_FEATURES) {
8849 (void) printf(gettext("Successfully upgraded "
8850 "'%s' from version %llu to feature flags.\n"),
8851 zpool_get_name(zhp), (u_longlong_t)oldversion);
8852 } else {
8853 (void) printf(gettext("Successfully upgraded "
8854 "'%s' from version %llu to version %llu.\n"),
8855 zpool_get_name(zhp), (u_longlong_t)oldversion,
8856 (u_longlong_t)version);
8859 return (0);
8862 static int
8863 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
8865 int i, ret, count;
8866 boolean_t firstff = B_TRUE;
8867 nvlist_t *enabled = zpool_get_features(zhp);
8869 char compat[ZFS_MAXPROPLEN];
8870 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
8871 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
8872 compat[0] = '\0';
8874 boolean_t requested_features[SPA_FEATURES];
8875 if (zpool_do_load_compat(compat, requested_features) !=
8876 ZPOOL_COMPATIBILITY_OK)
8877 return (-1);
8879 count = 0;
8880 for (i = 0; i < SPA_FEATURES; i++) {
8881 const char *fname = spa_feature_table[i].fi_uname;
8882 const char *fguid = spa_feature_table[i].fi_guid;
8884 if (!spa_feature_table[i].fi_zfs_mod_supported)
8885 continue;
8887 if (!nvlist_exists(enabled, fguid) && requested_features[i]) {
8888 char *propname;
8889 verify(-1 != asprintf(&propname, "feature@%s", fname));
8890 ret = zpool_set_prop(zhp, propname,
8891 ZFS_FEATURE_ENABLED);
8892 if (ret != 0) {
8893 free(propname);
8894 return (ret);
8896 count++;
8898 if (firstff) {
8899 (void) printf(gettext("Enabled the "
8900 "following features on '%s':\n"),
8901 zpool_get_name(zhp));
8902 firstff = B_FALSE;
8904 (void) printf(gettext(" %s\n"), fname);
8905 free(propname);
8909 if (countp != NULL)
8910 *countp = count;
8911 return (0);
8914 static int
8915 upgrade_cb(zpool_handle_t *zhp, void *arg)
8917 upgrade_cbdata_t *cbp = arg;
8918 nvlist_t *config;
8919 uint64_t version;
8920 boolean_t modified_pool = B_FALSE;
8921 int ret;
8923 config = zpool_get_config(zhp, NULL);
8924 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
8925 &version) == 0);
8927 assert(SPA_VERSION_IS_SUPPORTED(version));
8929 if (version < cbp->cb_version) {
8930 cbp->cb_first = B_FALSE;
8931 ret = upgrade_version(zhp, cbp->cb_version);
8932 if (ret != 0)
8933 return (ret);
8934 modified_pool = B_TRUE;
8937 * If they did "zpool upgrade -a", then we could
8938 * be doing ioctls to different pools. We need
8939 * to log this history once to each pool, and bypass
8940 * the normal history logging that happens in main().
8942 (void) zpool_log_history(g_zfs, history_str);
8943 log_history = B_FALSE;
8946 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
8947 int count;
8948 ret = upgrade_enable_all(zhp, &count);
8949 if (ret != 0)
8950 return (ret);
8952 if (count > 0) {
8953 cbp->cb_first = B_FALSE;
8954 modified_pool = B_TRUE;
8958 if (modified_pool) {
8959 (void) printf("\n");
8960 (void) after_zpool_upgrade(zhp);
8963 return (0);
8966 static int
8967 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
8969 upgrade_cbdata_t *cbp = arg;
8970 nvlist_t *config;
8971 uint64_t version;
8973 config = zpool_get_config(zhp, NULL);
8974 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
8975 &version) == 0);
8977 assert(SPA_VERSION_IS_SUPPORTED(version));
8979 if (version < SPA_VERSION_FEATURES) {
8980 if (cbp->cb_first) {
8981 (void) printf(gettext("The following pools are "
8982 "formatted with legacy version numbers and can\n"
8983 "be upgraded to use feature flags. After "
8984 "being upgraded, these pools\nwill no "
8985 "longer be accessible by software that does not "
8986 "support feature\nflags.\n\n"
8987 "Note that setting a pool's 'compatibility' "
8988 "feature to '" ZPOOL_COMPAT_LEGACY "' will\n"
8989 "inhibit upgrades.\n\n"));
8990 (void) printf(gettext("VER POOL\n"));
8991 (void) printf(gettext("--- ------------\n"));
8992 cbp->cb_first = B_FALSE;
8995 (void) printf("%2llu %s\n", (u_longlong_t)version,
8996 zpool_get_name(zhp));
8999 return (0);
9002 static int
9003 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
9005 upgrade_cbdata_t *cbp = arg;
9006 nvlist_t *config;
9007 uint64_t version;
9009 config = zpool_get_config(zhp, NULL);
9010 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
9011 &version) == 0);
9013 if (version >= SPA_VERSION_FEATURES) {
9014 int i;
9015 boolean_t poolfirst = B_TRUE;
9016 nvlist_t *enabled = zpool_get_features(zhp);
9018 for (i = 0; i < SPA_FEATURES; i++) {
9019 const char *fguid = spa_feature_table[i].fi_guid;
9020 const char *fname = spa_feature_table[i].fi_uname;
9022 if (!spa_feature_table[i].fi_zfs_mod_supported)
9023 continue;
9025 if (!nvlist_exists(enabled, fguid)) {
9026 if (cbp->cb_first) {
9027 (void) printf(gettext("\nSome "
9028 "supported features are not "
9029 "enabled on the following pools. "
9030 "Once a\nfeature is enabled the "
9031 "pool may become incompatible with "
9032 "software\nthat does not support "
9033 "the feature. See "
9034 "zpool-features(7) for "
9035 "details.\n\n"
9036 "Note that the pool "
9037 "'compatibility' feature can be "
9038 "used to inhibit\nfeature "
9039 "upgrades.\n\n"));
9040 (void) printf(gettext("POOL "
9041 "FEATURE\n"));
9042 (void) printf(gettext("------"
9043 "---------\n"));
9044 cbp->cb_first = B_FALSE;
9047 if (poolfirst) {
9048 (void) printf(gettext("%s\n"),
9049 zpool_get_name(zhp));
9050 poolfirst = B_FALSE;
9053 (void) printf(gettext(" %s\n"), fname);
9056 * If they did "zpool upgrade -a", then we could
9057 * be doing ioctls to different pools. We need
9058 * to log this history once to each pool, and bypass
9059 * the normal history logging that happens in main().
9061 (void) zpool_log_history(g_zfs, history_str);
9062 log_history = B_FALSE;
9066 return (0);
9069 static int
9070 upgrade_one(zpool_handle_t *zhp, void *data)
9072 boolean_t modified_pool = B_FALSE;
9073 upgrade_cbdata_t *cbp = data;
9074 uint64_t cur_version;
9075 int ret;
9077 if (strcmp("log", zpool_get_name(zhp)) == 0) {
9078 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
9079 "Pool 'log' must be renamed using export and import"
9080 " to upgrade.\n"));
9081 return (1);
9084 cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
9085 if (cur_version > cbp->cb_version) {
9086 (void) printf(gettext("Pool '%s' is already formatted "
9087 "using more current version '%llu'.\n\n"),
9088 zpool_get_name(zhp), (u_longlong_t)cur_version);
9089 return (0);
9092 if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
9093 (void) printf(gettext("Pool '%s' is already formatted "
9094 "using version %llu.\n\n"), zpool_get_name(zhp),
9095 (u_longlong_t)cbp->cb_version);
9096 return (0);
9099 if (cur_version != cbp->cb_version) {
9100 modified_pool = B_TRUE;
9101 ret = upgrade_version(zhp, cbp->cb_version);
9102 if (ret != 0)
9103 return (ret);
9106 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
9107 int count = 0;
9108 ret = upgrade_enable_all(zhp, &count);
9109 if (ret != 0)
9110 return (ret);
9112 if (count != 0) {
9113 modified_pool = B_TRUE;
9114 } else if (cur_version == SPA_VERSION) {
9115 (void) printf(gettext("Pool '%s' already has all "
9116 "supported and requested features enabled.\n"),
9117 zpool_get_name(zhp));
9121 if (modified_pool) {
9122 (void) printf("\n");
9123 (void) after_zpool_upgrade(zhp);
9126 return (0);
9130 * zpool upgrade
9131 * zpool upgrade -v
9132 * zpool upgrade [-V version] <-a | pool ...>
9134 * With no arguments, display downrev'd ZFS pool available for upgrade.
9135 * Individual pools can be upgraded by specifying the pool, and '-a' will
9136 * upgrade all pools.
9139 zpool_do_upgrade(int argc, char **argv)
9141 int c;
9142 upgrade_cbdata_t cb = { 0 };
9143 int ret = 0;
9144 boolean_t showversions = B_FALSE;
9145 boolean_t upgradeall = B_FALSE;
9146 char *end;
9149 /* check options */
9150 while ((c = getopt(argc, argv, ":avV:")) != -1) {
9151 switch (c) {
9152 case 'a':
9153 upgradeall = B_TRUE;
9154 break;
9155 case 'v':
9156 showversions = B_TRUE;
9157 break;
9158 case 'V':
9159 cb.cb_version = strtoll(optarg, &end, 10);
9160 if (*end != '\0' ||
9161 !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
9162 (void) fprintf(stderr,
9163 gettext("invalid version '%s'\n"), optarg);
9164 usage(B_FALSE);
9166 break;
9167 case ':':
9168 (void) fprintf(stderr, gettext("missing argument for "
9169 "'%c' option\n"), optopt);
9170 usage(B_FALSE);
9171 break;
9172 case '?':
9173 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9174 optopt);
9175 usage(B_FALSE);
9179 cb.cb_argc = argc;
9180 cb.cb_argv = argv;
9181 argc -= optind;
9182 argv += optind;
9184 if (cb.cb_version == 0) {
9185 cb.cb_version = SPA_VERSION;
9186 } else if (!upgradeall && argc == 0) {
9187 (void) fprintf(stderr, gettext("-V option is "
9188 "incompatible with other arguments\n"));
9189 usage(B_FALSE);
9192 if (showversions) {
9193 if (upgradeall || argc != 0) {
9194 (void) fprintf(stderr, gettext("-v option is "
9195 "incompatible with other arguments\n"));
9196 usage(B_FALSE);
9198 } else if (upgradeall) {
9199 if (argc != 0) {
9200 (void) fprintf(stderr, gettext("-a option should not "
9201 "be used along with a pool name\n"));
9202 usage(B_FALSE);
9206 (void) printf("%s", gettext("This system supports ZFS pool feature "
9207 "flags.\n\n"));
9208 if (showversions) {
9209 int i;
9211 (void) printf(gettext("The following features are "
9212 "supported:\n\n"));
9213 (void) printf(gettext("FEAT DESCRIPTION\n"));
9214 (void) printf("----------------------------------------------"
9215 "---------------\n");
9216 for (i = 0; i < SPA_FEATURES; i++) {
9217 zfeature_info_t *fi = &spa_feature_table[i];
9218 if (!fi->fi_zfs_mod_supported)
9219 continue;
9220 const char *ro =
9221 (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
9222 " (read-only compatible)" : "";
9224 (void) printf("%-37s%s\n", fi->fi_uname, ro);
9225 (void) printf(" %s\n", fi->fi_desc);
9227 (void) printf("\n");
9229 (void) printf(gettext("The following legacy versions are also "
9230 "supported:\n\n"));
9231 (void) printf(gettext("VER DESCRIPTION\n"));
9232 (void) printf("--- -----------------------------------------"
9233 "---------------\n");
9234 (void) printf(gettext(" 1 Initial ZFS version\n"));
9235 (void) printf(gettext(" 2 Ditto blocks "
9236 "(replicated metadata)\n"));
9237 (void) printf(gettext(" 3 Hot spares and double parity "
9238 "RAID-Z\n"));
9239 (void) printf(gettext(" 4 zpool history\n"));
9240 (void) printf(gettext(" 5 Compression using the gzip "
9241 "algorithm\n"));
9242 (void) printf(gettext(" 6 bootfs pool property\n"));
9243 (void) printf(gettext(" 7 Separate intent log devices\n"));
9244 (void) printf(gettext(" 8 Delegated administration\n"));
9245 (void) printf(gettext(" 9 refquota and refreservation "
9246 "properties\n"));
9247 (void) printf(gettext(" 10 Cache devices\n"));
9248 (void) printf(gettext(" 11 Improved scrub performance\n"));
9249 (void) printf(gettext(" 12 Snapshot properties\n"));
9250 (void) printf(gettext(" 13 snapused property\n"));
9251 (void) printf(gettext(" 14 passthrough-x aclinherit\n"));
9252 (void) printf(gettext(" 15 user/group space accounting\n"));
9253 (void) printf(gettext(" 16 stmf property support\n"));
9254 (void) printf(gettext(" 17 Triple-parity RAID-Z\n"));
9255 (void) printf(gettext(" 18 Snapshot user holds\n"));
9256 (void) printf(gettext(" 19 Log device removal\n"));
9257 (void) printf(gettext(" 20 Compression using zle "
9258 "(zero-length encoding)\n"));
9259 (void) printf(gettext(" 21 Deduplication\n"));
9260 (void) printf(gettext(" 22 Received properties\n"));
9261 (void) printf(gettext(" 23 Slim ZIL\n"));
9262 (void) printf(gettext(" 24 System attributes\n"));
9263 (void) printf(gettext(" 25 Improved scrub stats\n"));
9264 (void) printf(gettext(" 26 Improved snapshot deletion "
9265 "performance\n"));
9266 (void) printf(gettext(" 27 Improved snapshot creation "
9267 "performance\n"));
9268 (void) printf(gettext(" 28 Multiple vdev replacements\n"));
9269 (void) printf(gettext("\nFor more information on a particular "
9270 "version, including supported releases,\n"));
9271 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
9272 } else if (argc == 0 && upgradeall) {
9273 cb.cb_first = B_TRUE;
9274 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
9275 if (ret == 0 && cb.cb_first) {
9276 if (cb.cb_version == SPA_VERSION) {
9277 (void) printf(gettext("All pools are already "
9278 "formatted using feature flags.\n\n"));
9279 (void) printf(gettext("Every feature flags "
9280 "pool already has all supported and "
9281 "requested features enabled.\n"));
9282 } else {
9283 (void) printf(gettext("All pools are already "
9284 "formatted with version %llu or higher.\n"),
9285 (u_longlong_t)cb.cb_version);
9288 } else if (argc == 0) {
9289 cb.cb_first = B_TRUE;
9290 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
9291 assert(ret == 0);
9293 if (cb.cb_first) {
9294 (void) printf(gettext("All pools are formatted "
9295 "using feature flags.\n\n"));
9296 } else {
9297 (void) printf(gettext("\nUse 'zpool upgrade -v' "
9298 "for a list of available legacy versions.\n"));
9301 cb.cb_first = B_TRUE;
9302 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
9303 assert(ret == 0);
9305 if (cb.cb_first) {
9306 (void) printf(gettext("Every feature flags pool has "
9307 "all supported and requested features enabled.\n"));
9308 } else {
9309 (void) printf(gettext("\n"));
9311 } else {
9312 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9313 B_FALSE, upgrade_one, &cb);
9316 return (ret);
9319 typedef struct hist_cbdata {
9320 boolean_t first;
9321 boolean_t longfmt;
9322 boolean_t internal;
9323 } hist_cbdata_t;
9325 static void
9326 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
9328 nvlist_t **records;
9329 uint_t numrecords;
9330 int i;
9332 verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
9333 &records, &numrecords) == 0);
9334 for (i = 0; i < numrecords; i++) {
9335 nvlist_t *rec = records[i];
9336 char tbuf[64] = "";
9338 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
9339 time_t tsec;
9340 struct tm t;
9342 tsec = fnvlist_lookup_uint64(records[i],
9343 ZPOOL_HIST_TIME);
9344 (void) localtime_r(&tsec, &t);
9345 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
9348 if (nvlist_exists(rec, ZPOOL_HIST_ELAPSED_NS)) {
9349 uint64_t elapsed_ns = fnvlist_lookup_int64(records[i],
9350 ZPOOL_HIST_ELAPSED_NS);
9351 (void) snprintf(tbuf + strlen(tbuf),
9352 sizeof (tbuf) - strlen(tbuf),
9353 " (%lldms)", (long long)elapsed_ns / 1000 / 1000);
9356 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
9357 (void) printf("%s %s", tbuf,
9358 fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
9359 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
9360 int ievent =
9361 fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
9362 if (!cb->internal)
9363 continue;
9364 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
9365 (void) printf("%s unrecognized record:\n",
9366 tbuf);
9367 dump_nvlist(rec, 4);
9368 continue;
9370 (void) printf("%s [internal %s txg:%lld] %s", tbuf,
9371 zfs_history_event_names[ievent],
9372 (longlong_t)fnvlist_lookup_uint64(
9373 rec, ZPOOL_HIST_TXG),
9374 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
9375 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
9376 if (!cb->internal)
9377 continue;
9378 (void) printf("%s [txg:%lld] %s", tbuf,
9379 (longlong_t)fnvlist_lookup_uint64(
9380 rec, ZPOOL_HIST_TXG),
9381 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
9382 if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
9383 (void) printf(" %s (%llu)",
9384 fnvlist_lookup_string(rec,
9385 ZPOOL_HIST_DSNAME),
9386 (u_longlong_t)fnvlist_lookup_uint64(rec,
9387 ZPOOL_HIST_DSID));
9389 (void) printf(" %s", fnvlist_lookup_string(rec,
9390 ZPOOL_HIST_INT_STR));
9391 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
9392 if (!cb->internal)
9393 continue;
9394 (void) printf("%s ioctl %s\n", tbuf,
9395 fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
9396 if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
9397 (void) printf(" input:\n");
9398 dump_nvlist(fnvlist_lookup_nvlist(rec,
9399 ZPOOL_HIST_INPUT_NVL), 8);
9401 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
9402 (void) printf(" output:\n");
9403 dump_nvlist(fnvlist_lookup_nvlist(rec,
9404 ZPOOL_HIST_OUTPUT_NVL), 8);
9406 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_SIZE)) {
9407 (void) printf(" output nvlist omitted; "
9408 "original size: %lldKB\n",
9409 (longlong_t)fnvlist_lookup_int64(rec,
9410 ZPOOL_HIST_OUTPUT_SIZE) / 1024);
9412 if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
9413 (void) printf(" errno: %lld\n",
9414 (longlong_t)fnvlist_lookup_int64(rec,
9415 ZPOOL_HIST_ERRNO));
9417 } else {
9418 if (!cb->internal)
9419 continue;
9420 (void) printf("%s unrecognized record:\n", tbuf);
9421 dump_nvlist(rec, 4);
9424 if (!cb->longfmt) {
9425 (void) printf("\n");
9426 continue;
9428 (void) printf(" [");
9429 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
9430 uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
9431 struct passwd *pwd = getpwuid(who);
9432 (void) printf("user %d ", (int)who);
9433 if (pwd != NULL)
9434 (void) printf("(%s) ", pwd->pw_name);
9436 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
9437 (void) printf("on %s",
9438 fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
9440 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
9441 (void) printf(":%s",
9442 fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
9445 (void) printf("]");
9446 (void) printf("\n");
9451 * Print out the command history for a specific pool.
9453 static int
9454 get_history_one(zpool_handle_t *zhp, void *data)
9456 nvlist_t *nvhis;
9457 int ret;
9458 hist_cbdata_t *cb = (hist_cbdata_t *)data;
9459 uint64_t off = 0;
9460 boolean_t eof = B_FALSE;
9462 cb->first = B_FALSE;
9464 (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
9466 while (!eof) {
9467 if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
9468 return (ret);
9470 print_history_records(nvhis, cb);
9471 nvlist_free(nvhis);
9473 (void) printf("\n");
9475 return (ret);
9479 * zpool history <pool>
9481 * Displays the history of commands that modified pools.
9484 zpool_do_history(int argc, char **argv)
9486 hist_cbdata_t cbdata = { 0 };
9487 int ret;
9488 int c;
9490 cbdata.first = B_TRUE;
9491 /* check options */
9492 while ((c = getopt(argc, argv, "li")) != -1) {
9493 switch (c) {
9494 case 'l':
9495 cbdata.longfmt = B_TRUE;
9496 break;
9497 case 'i':
9498 cbdata.internal = B_TRUE;
9499 break;
9500 case '?':
9501 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9502 optopt);
9503 usage(B_FALSE);
9506 argc -= optind;
9507 argv += optind;
9509 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9510 B_FALSE, get_history_one, &cbdata);
9512 if (argc == 0 && cbdata.first == B_TRUE) {
9513 (void) fprintf(stderr, gettext("no pools available\n"));
9514 return (0);
9517 return (ret);
9520 typedef struct ev_opts {
9521 int verbose;
9522 int scripted;
9523 int follow;
9524 int clear;
9525 char poolname[ZFS_MAX_DATASET_NAME_LEN];
9526 } ev_opts_t;
9528 static void
9529 zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
9531 char ctime_str[26], str[32], *ptr;
9532 int64_t *tv;
9533 uint_t n;
9535 verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
9536 memset(str, ' ', 32);
9537 (void) ctime_r((const time_t *)&tv[0], ctime_str);
9538 (void) memcpy(str, ctime_str+4, 6); /* 'Jun 30' */
9539 (void) memcpy(str+7, ctime_str+20, 4); /* '1993' */
9540 (void) memcpy(str+12, ctime_str+11, 8); /* '21:49:08' */
9541 (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
9542 if (opts->scripted)
9543 (void) printf(gettext("%s\t"), str);
9544 else
9545 (void) printf(gettext("%s "), str);
9547 verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
9548 (void) printf(gettext("%s\n"), ptr);
9551 static void
9552 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
9554 nvpair_t *nvp;
9556 for (nvp = nvlist_next_nvpair(nvl, NULL);
9557 nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
9559 data_type_t type = nvpair_type(nvp);
9560 const char *name = nvpair_name(nvp);
9562 boolean_t b;
9563 uint8_t i8;
9564 uint16_t i16;
9565 uint32_t i32;
9566 uint64_t i64;
9567 char *str;
9568 nvlist_t *cnv;
9570 printf(gettext("%*s%s = "), depth, "", name);
9572 switch (type) {
9573 case DATA_TYPE_BOOLEAN:
9574 printf(gettext("%s"), "1");
9575 break;
9577 case DATA_TYPE_BOOLEAN_VALUE:
9578 (void) nvpair_value_boolean_value(nvp, &b);
9579 printf(gettext("%s"), b ? "1" : "0");
9580 break;
9582 case DATA_TYPE_BYTE:
9583 (void) nvpair_value_byte(nvp, &i8);
9584 printf(gettext("0x%x"), i8);
9585 break;
9587 case DATA_TYPE_INT8:
9588 (void) nvpair_value_int8(nvp, (void *)&i8);
9589 printf(gettext("0x%x"), i8);
9590 break;
9592 case DATA_TYPE_UINT8:
9593 (void) nvpair_value_uint8(nvp, &i8);
9594 printf(gettext("0x%x"), i8);
9595 break;
9597 case DATA_TYPE_INT16:
9598 (void) nvpair_value_int16(nvp, (void *)&i16);
9599 printf(gettext("0x%x"), i16);
9600 break;
9602 case DATA_TYPE_UINT16:
9603 (void) nvpair_value_uint16(nvp, &i16);
9604 printf(gettext("0x%x"), i16);
9605 break;
9607 case DATA_TYPE_INT32:
9608 (void) nvpair_value_int32(nvp, (void *)&i32);
9609 printf(gettext("0x%x"), i32);
9610 break;
9612 case DATA_TYPE_UINT32:
9613 (void) nvpair_value_uint32(nvp, &i32);
9614 printf(gettext("0x%x"), i32);
9615 break;
9617 case DATA_TYPE_INT64:
9618 (void) nvpair_value_int64(nvp, (void *)&i64);
9619 printf(gettext("0x%llx"), (u_longlong_t)i64);
9620 break;
9622 case DATA_TYPE_UINT64:
9623 (void) nvpair_value_uint64(nvp, &i64);
9625 * translate vdev state values to readable
9626 * strings to aide zpool events consumers
9628 if (strcmp(name,
9629 FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
9630 strcmp(name,
9631 FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
9632 printf(gettext("\"%s\" (0x%llx)"),
9633 zpool_state_to_name(i64, VDEV_AUX_NONE),
9634 (u_longlong_t)i64);
9635 } else {
9636 printf(gettext("0x%llx"), (u_longlong_t)i64);
9638 break;
9640 case DATA_TYPE_HRTIME:
9641 (void) nvpair_value_hrtime(nvp, (void *)&i64);
9642 printf(gettext("0x%llx"), (u_longlong_t)i64);
9643 break;
9645 case DATA_TYPE_STRING:
9646 (void) nvpair_value_string(nvp, &str);
9647 printf(gettext("\"%s\""), str ? str : "<NULL>");
9648 break;
9650 case DATA_TYPE_NVLIST:
9651 printf(gettext("(embedded nvlist)\n"));
9652 (void) nvpair_value_nvlist(nvp, &cnv);
9653 zpool_do_events_nvprint(cnv, depth + 8);
9654 printf(gettext("%*s(end %s)"), depth, "", name);
9655 break;
9657 case DATA_TYPE_NVLIST_ARRAY: {
9658 nvlist_t **val;
9659 uint_t i, nelem;
9661 (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
9662 printf(gettext("(%d embedded nvlists)\n"), nelem);
9663 for (i = 0; i < nelem; i++) {
9664 printf(gettext("%*s%s[%d] = %s\n"),
9665 depth, "", name, i, "(embedded nvlist)");
9666 zpool_do_events_nvprint(val[i], depth + 8);
9667 printf(gettext("%*s(end %s[%i])\n"),
9668 depth, "", name, i);
9670 printf(gettext("%*s(end %s)\n"), depth, "", name);
9672 break;
9674 case DATA_TYPE_INT8_ARRAY: {
9675 int8_t *val;
9676 uint_t i, nelem;
9678 (void) nvpair_value_int8_array(nvp, &val, &nelem);
9679 for (i = 0; i < nelem; i++)
9680 printf(gettext("0x%x "), val[i]);
9682 break;
9685 case DATA_TYPE_UINT8_ARRAY: {
9686 uint8_t *val;
9687 uint_t i, nelem;
9689 (void) nvpair_value_uint8_array(nvp, &val, &nelem);
9690 for (i = 0; i < nelem; i++)
9691 printf(gettext("0x%x "), val[i]);
9693 break;
9696 case DATA_TYPE_INT16_ARRAY: {
9697 int16_t *val;
9698 uint_t i, nelem;
9700 (void) nvpair_value_int16_array(nvp, &val, &nelem);
9701 for (i = 0; i < nelem; i++)
9702 printf(gettext("0x%x "), val[i]);
9704 break;
9707 case DATA_TYPE_UINT16_ARRAY: {
9708 uint16_t *val;
9709 uint_t i, nelem;
9711 (void) nvpair_value_uint16_array(nvp, &val, &nelem);
9712 for (i = 0; i < nelem; i++)
9713 printf(gettext("0x%x "), val[i]);
9715 break;
9718 case DATA_TYPE_INT32_ARRAY: {
9719 int32_t *val;
9720 uint_t i, nelem;
9722 (void) nvpair_value_int32_array(nvp, &val, &nelem);
9723 for (i = 0; i < nelem; i++)
9724 printf(gettext("0x%x "), val[i]);
9726 break;
9729 case DATA_TYPE_UINT32_ARRAY: {
9730 uint32_t *val;
9731 uint_t i, nelem;
9733 (void) nvpair_value_uint32_array(nvp, &val, &nelem);
9734 for (i = 0; i < nelem; i++)
9735 printf(gettext("0x%x "), val[i]);
9737 break;
9740 case DATA_TYPE_INT64_ARRAY: {
9741 int64_t *val;
9742 uint_t i, nelem;
9744 (void) nvpair_value_int64_array(nvp, &val, &nelem);
9745 for (i = 0; i < nelem; i++)
9746 printf(gettext("0x%llx "),
9747 (u_longlong_t)val[i]);
9749 break;
9752 case DATA_TYPE_UINT64_ARRAY: {
9753 uint64_t *val;
9754 uint_t i, nelem;
9756 (void) nvpair_value_uint64_array(nvp, &val, &nelem);
9757 for (i = 0; i < nelem; i++)
9758 printf(gettext("0x%llx "),
9759 (u_longlong_t)val[i]);
9761 break;
9764 case DATA_TYPE_STRING_ARRAY: {
9765 char **str;
9766 uint_t i, nelem;
9768 (void) nvpair_value_string_array(nvp, &str, &nelem);
9769 for (i = 0; i < nelem; i++)
9770 printf(gettext("\"%s\" "),
9771 str[i] ? str[i] : "<NULL>");
9773 break;
9776 case DATA_TYPE_BOOLEAN_ARRAY:
9777 case DATA_TYPE_BYTE_ARRAY:
9778 case DATA_TYPE_DOUBLE:
9779 case DATA_TYPE_DONTCARE:
9780 case DATA_TYPE_UNKNOWN:
9781 printf(gettext("<unknown>"));
9782 break;
9785 printf(gettext("\n"));
9789 static int
9790 zpool_do_events_next(ev_opts_t *opts)
9792 nvlist_t *nvl;
9793 int zevent_fd, ret, dropped;
9794 char *pool;
9796 zevent_fd = open(ZFS_DEV, O_RDWR);
9797 VERIFY(zevent_fd >= 0);
9799 if (!opts->scripted)
9800 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
9802 while (1) {
9803 ret = zpool_events_next(g_zfs, &nvl, &dropped,
9804 (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
9805 if (ret || nvl == NULL)
9806 break;
9808 if (dropped > 0)
9809 (void) printf(gettext("dropped %d events\n"), dropped);
9811 if (strlen(opts->poolname) > 0 &&
9812 nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
9813 strcmp(opts->poolname, pool) != 0)
9814 continue;
9816 zpool_do_events_short(nvl, opts);
9818 if (opts->verbose) {
9819 zpool_do_events_nvprint(nvl, 8);
9820 printf(gettext("\n"));
9822 (void) fflush(stdout);
9824 nvlist_free(nvl);
9827 VERIFY(0 == close(zevent_fd));
9829 return (ret);
9832 static int
9833 zpool_do_events_clear(void)
9835 int count, ret;
9837 ret = zpool_events_clear(g_zfs, &count);
9838 if (!ret)
9839 (void) printf(gettext("cleared %d events\n"), count);
9841 return (ret);
9845 * zpool events [-vHf [pool] | -c]
9847 * Displays events logs by ZFS.
9850 zpool_do_events(int argc, char **argv)
9852 ev_opts_t opts = { 0 };
9853 int ret;
9854 int c;
9856 /* check options */
9857 while ((c = getopt(argc, argv, "vHfc")) != -1) {
9858 switch (c) {
9859 case 'v':
9860 opts.verbose = 1;
9861 break;
9862 case 'H':
9863 opts.scripted = 1;
9864 break;
9865 case 'f':
9866 opts.follow = 1;
9867 break;
9868 case 'c':
9869 opts.clear = 1;
9870 break;
9871 case '?':
9872 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9873 optopt);
9874 usage(B_FALSE);
9877 argc -= optind;
9878 argv += optind;
9880 if (argc > 1) {
9881 (void) fprintf(stderr, gettext("too many arguments\n"));
9882 usage(B_FALSE);
9883 } else if (argc == 1) {
9884 (void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
9885 if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
9886 (void) fprintf(stderr,
9887 gettext("invalid pool name '%s'\n"), opts.poolname);
9888 usage(B_FALSE);
9892 if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
9893 opts.clear) {
9894 (void) fprintf(stderr,
9895 gettext("invalid options combined with -c\n"));
9896 usage(B_FALSE);
9899 if (opts.clear)
9900 ret = zpool_do_events_clear();
9901 else
9902 ret = zpool_do_events_next(&opts);
9904 return (ret);
9907 static int
9908 get_callback_vdev(zpool_handle_t *zhp, char *vdevname, void *data)
9910 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
9911 char value[ZFS_MAXPROPLEN];
9912 zprop_source_t srctype;
9914 for (zprop_list_t *pl = cbp->cb_proplist; pl != NULL;
9915 pl = pl->pl_next) {
9916 char *prop_name;
9918 * If the first property is pool name, it is a special
9919 * placeholder that we can skip. This will also skip
9920 * over the name property when 'all' is specified.
9922 if (pl->pl_prop == ZPOOL_PROP_NAME &&
9923 pl == cbp->cb_proplist)
9924 continue;
9926 if (pl->pl_prop == ZPROP_INVAL) {
9927 prop_name = pl->pl_user_prop;
9928 } else {
9929 prop_name = (char *)vdev_prop_to_name(pl->pl_prop);
9931 if (zpool_get_vdev_prop(zhp, vdevname, pl->pl_prop,
9932 prop_name, value, sizeof (value), &srctype,
9933 cbp->cb_literal) == 0) {
9934 zprop_print_one_property(vdevname, cbp, prop_name,
9935 value, srctype, NULL, NULL);
9939 return (0);
9942 static int
9943 get_callback_vdev_width_cb(void *zhp_data, nvlist_t *nv, void *data)
9945 zpool_handle_t *zhp = zhp_data;
9946 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
9947 char *vdevname = zpool_vdev_name(g_zfs, zhp, nv,
9948 cbp->cb_vdevs.cb_name_flags);
9949 int ret;
9951 /* Adjust the column widths for the vdev properties */
9952 ret = vdev_expand_proplist(zhp, vdevname, &cbp->cb_proplist);
9954 return (ret);
9957 static int
9958 get_callback_vdev_cb(void *zhp_data, nvlist_t *nv, void *data)
9960 zpool_handle_t *zhp = zhp_data;
9961 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
9962 char *vdevname = zpool_vdev_name(g_zfs, zhp, nv,
9963 cbp->cb_vdevs.cb_name_flags);
9964 int ret;
9966 /* Display the properties */
9967 ret = get_callback_vdev(zhp, vdevname, data);
9969 return (ret);
9972 static int
9973 get_callback(zpool_handle_t *zhp, void *data)
9975 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
9976 char value[MAXNAMELEN];
9977 zprop_source_t srctype;
9978 zprop_list_t *pl;
9979 int vid;
9981 if (cbp->cb_type == ZFS_TYPE_VDEV) {
9982 if (strcmp(cbp->cb_vdevs.cb_names[0], "all-vdevs") == 0) {
9983 for_each_vdev(zhp, get_callback_vdev_width_cb, data);
9984 for_each_vdev(zhp, get_callback_vdev_cb, data);
9985 } else {
9986 /* Adjust column widths for vdev properties */
9987 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
9988 vid++) {
9989 vdev_expand_proplist(zhp,
9990 cbp->cb_vdevs.cb_names[vid],
9991 &cbp->cb_proplist);
9993 /* Display the properties */
9994 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
9995 vid++) {
9996 get_callback_vdev(zhp,
9997 cbp->cb_vdevs.cb_names[vid], data);
10000 } else {
10001 assert(cbp->cb_type == ZFS_TYPE_POOL);
10002 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
10004 * Skip the special fake placeholder. This will also
10005 * skip over the name property when 'all' is specified.
10007 if (pl->pl_prop == ZPOOL_PROP_NAME &&
10008 pl == cbp->cb_proplist)
10009 continue;
10011 if (pl->pl_prop == ZPROP_INVAL &&
10012 (zpool_prop_feature(pl->pl_user_prop) ||
10013 zpool_prop_unsupported(pl->pl_user_prop))) {
10014 srctype = ZPROP_SRC_LOCAL;
10016 if (zpool_prop_get_feature(zhp,
10017 pl->pl_user_prop, value,
10018 sizeof (value)) == 0) {
10019 zprop_print_one_property(
10020 zpool_get_name(zhp), cbp,
10021 pl->pl_user_prop, value, srctype,
10022 NULL, NULL);
10024 } else {
10025 if (zpool_get_prop(zhp, pl->pl_prop, value,
10026 sizeof (value), &srctype,
10027 cbp->cb_literal) != 0)
10028 continue;
10030 zprop_print_one_property(zpool_get_name(zhp),
10031 cbp, zpool_prop_to_name(pl->pl_prop),
10032 value, srctype, NULL, NULL);
10037 return (0);
10041 * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
10043 * -H Scripted mode. Don't display headers, and separate properties
10044 * by a single tab.
10045 * -o List of columns to display. Defaults to
10046 * "name,property,value,source".
10047 * -p Display values in parsable (exact) format.
10049 * Get properties of pools in the system. Output space statistics
10050 * for each one as well as other attributes.
10053 zpool_do_get(int argc, char **argv)
10055 zprop_get_cbdata_t cb = { 0 };
10056 zprop_list_t fake_name = { 0 };
10057 int ret;
10058 int c, i;
10059 char *propstr = NULL;
10061 cb.cb_first = B_TRUE;
10064 * Set up default columns and sources.
10066 cb.cb_sources = ZPROP_SRC_ALL;
10067 cb.cb_columns[0] = GET_COL_NAME;
10068 cb.cb_columns[1] = GET_COL_PROPERTY;
10069 cb.cb_columns[2] = GET_COL_VALUE;
10070 cb.cb_columns[3] = GET_COL_SOURCE;
10071 cb.cb_type = ZFS_TYPE_POOL;
10072 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
10073 current_prop_type = cb.cb_type;
10075 /* check options */
10076 while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
10077 switch (c) {
10078 case 'p':
10079 cb.cb_literal = B_TRUE;
10080 break;
10081 case 'H':
10082 cb.cb_scripted = B_TRUE;
10083 break;
10084 case 'o':
10085 memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
10086 i = 0;
10088 for (char *tok; (tok = strsep(&optarg, ",")); ) {
10089 static const char *const col_opts[] =
10090 { "name", "property", "value", "source",
10091 "all" };
10092 static const zfs_get_column_t col_cols[] =
10093 { GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
10094 GET_COL_SOURCE };
10096 if (i == ZFS_GET_NCOLS - 1) {
10097 (void) fprintf(stderr, gettext("too "
10098 "many fields given to -o "
10099 "option\n"));
10100 usage(B_FALSE);
10103 for (c = 0; c < ARRAY_SIZE(col_opts); ++c)
10104 if (strcmp(tok, col_opts[c]) == 0)
10105 goto found;
10107 (void) fprintf(stderr,
10108 gettext("invalid column name '%s'\n"), tok);
10109 usage(B_FALSE);
10111 found:
10112 if (c >= 4) {
10113 if (i > 0) {
10114 (void) fprintf(stderr,
10115 gettext("\"all\" conflicts "
10116 "with specific fields "
10117 "given to -o option\n"));
10118 usage(B_FALSE);
10121 memcpy(cb.cb_columns, col_cols,
10122 sizeof (col_cols));
10123 i = ZFS_GET_NCOLS - 1;
10124 } else
10125 cb.cb_columns[i++] = col_cols[c];
10127 break;
10128 case '?':
10129 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
10130 optopt);
10131 usage(B_FALSE);
10135 argc -= optind;
10136 argv += optind;
10138 if (argc < 1) {
10139 (void) fprintf(stderr, gettext("missing property "
10140 "argument\n"));
10141 usage(B_FALSE);
10144 /* Properties list is needed later by zprop_get_list() */
10145 propstr = argv[0];
10147 argc--;
10148 argv++;
10150 if (argc == 0) {
10151 /* No args, so just print the defaults. */
10152 } else if (are_all_pools(argc, argv)) {
10153 /* All the args are pool names */
10154 } else if (are_all_pools(1, argv)) {
10155 /* The first arg is a pool name */
10156 if ((argc == 2 && strcmp(argv[1], "all-vdevs") == 0) ||
10157 are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
10158 &cb.cb_vdevs)) {
10159 /* ... and the rest are vdev names */
10160 cb.cb_vdevs.cb_names = argv + 1;
10161 cb.cb_vdevs.cb_names_count = argc - 1;
10162 cb.cb_type = ZFS_TYPE_VDEV;
10163 argc = 1; /* One pool to process */
10164 } else {
10165 fprintf(stderr, gettext("Expected a list of vdevs in"
10166 " \"%s\", but got:\n"), argv[0]);
10167 error_list_unresolved_vdevs(argc - 1, argv + 1,
10168 argv[0], &cb.cb_vdevs);
10169 fprintf(stderr, "\n");
10170 usage(B_FALSE);
10171 return (1);
10173 } else {
10175 * The first arg isn't a pool name,
10177 fprintf(stderr, gettext("missing pool name.\n"));
10178 fprintf(stderr, "\n");
10179 usage(B_FALSE);
10180 return (1);
10183 if (zprop_get_list(g_zfs, propstr, &cb.cb_proplist,
10184 cb.cb_type) != 0) {
10185 /* Use correct list of valid properties (pool or vdev) */
10186 current_prop_type = cb.cb_type;
10187 usage(B_FALSE);
10190 if (cb.cb_proplist != NULL) {
10191 fake_name.pl_prop = ZPOOL_PROP_NAME;
10192 fake_name.pl_width = strlen(gettext("NAME"));
10193 fake_name.pl_next = cb.cb_proplist;
10194 cb.cb_proplist = &fake_name;
10197 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist, cb.cb_type,
10198 cb.cb_literal, get_callback, &cb);
10200 if (cb.cb_proplist == &fake_name)
10201 zprop_free_list(fake_name.pl_next);
10202 else
10203 zprop_free_list(cb.cb_proplist);
10205 return (ret);
10208 typedef struct set_cbdata {
10209 char *cb_propname;
10210 char *cb_value;
10211 zfs_type_t cb_type;
10212 vdev_cbdata_t cb_vdevs;
10213 boolean_t cb_any_successful;
10214 } set_cbdata_t;
10216 static int
10217 set_pool_callback(zpool_handle_t *zhp, set_cbdata_t *cb)
10219 int error;
10221 /* Check if we have out-of-bounds features */
10222 if (strcmp(cb->cb_propname, ZPOOL_CONFIG_COMPATIBILITY) == 0) {
10223 boolean_t features[SPA_FEATURES];
10224 if (zpool_do_load_compat(cb->cb_value, features) !=
10225 ZPOOL_COMPATIBILITY_OK)
10226 return (-1);
10228 nvlist_t *enabled = zpool_get_features(zhp);
10229 spa_feature_t i;
10230 for (i = 0; i < SPA_FEATURES; i++) {
10231 const char *fguid = spa_feature_table[i].fi_guid;
10232 if (nvlist_exists(enabled, fguid) && !features[i])
10233 break;
10235 if (i < SPA_FEATURES)
10236 (void) fprintf(stderr, gettext("Warning: one or "
10237 "more features already enabled on pool '%s'\n"
10238 "are not present in this compatibility set.\n"),
10239 zpool_get_name(zhp));
10242 /* if we're setting a feature, check it's in compatibility set */
10243 if (zpool_prop_feature(cb->cb_propname) &&
10244 strcmp(cb->cb_value, ZFS_FEATURE_ENABLED) == 0) {
10245 char *fname = strchr(cb->cb_propname, '@') + 1;
10246 spa_feature_t f;
10248 if (zfeature_lookup_name(fname, &f) == 0) {
10249 char compat[ZFS_MAXPROPLEN];
10250 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY,
10251 compat, ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
10252 compat[0] = '\0';
10254 boolean_t features[SPA_FEATURES];
10255 if (zpool_do_load_compat(compat, features) !=
10256 ZPOOL_COMPATIBILITY_OK) {
10257 (void) fprintf(stderr, gettext("Error: "
10258 "cannot enable feature '%s' on pool '%s'\n"
10259 "because the pool's 'compatibility' "
10260 "property cannot be parsed.\n"),
10261 fname, zpool_get_name(zhp));
10262 return (-1);
10265 if (!features[f]) {
10266 (void) fprintf(stderr, gettext("Error: "
10267 "cannot enable feature '%s' on pool '%s'\n"
10268 "as it is not specified in this pool's "
10269 "current compatibility set.\n"
10270 "Consider setting 'compatibility' to a "
10271 "less restrictive set, or to 'off'.\n"),
10272 fname, zpool_get_name(zhp));
10273 return (-1);
10278 error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
10280 return (error);
10283 static int
10284 set_callback(zpool_handle_t *zhp, void *data)
10286 int error;
10287 set_cbdata_t *cb = (set_cbdata_t *)data;
10289 if (cb->cb_type == ZFS_TYPE_VDEV) {
10290 error = zpool_set_vdev_prop(zhp, *cb->cb_vdevs.cb_names,
10291 cb->cb_propname, cb->cb_value);
10292 } else {
10293 assert(cb->cb_type == ZFS_TYPE_POOL);
10294 error = set_pool_callback(zhp, cb);
10297 cb->cb_any_successful = !error;
10298 return (error);
10302 zpool_do_set(int argc, char **argv)
10304 set_cbdata_t cb = { 0 };
10305 int error;
10307 current_prop_type = ZFS_TYPE_POOL;
10308 if (argc > 1 && argv[1][0] == '-') {
10309 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
10310 argv[1][1]);
10311 usage(B_FALSE);
10314 if (argc < 2) {
10315 (void) fprintf(stderr, gettext("missing property=value "
10316 "argument\n"));
10317 usage(B_FALSE);
10320 if (argc < 3) {
10321 (void) fprintf(stderr, gettext("missing pool name\n"));
10322 usage(B_FALSE);
10325 if (argc > 4) {
10326 (void) fprintf(stderr, gettext("too many pool names\n"));
10327 usage(B_FALSE);
10330 cb.cb_propname = argv[1];
10331 cb.cb_type = ZFS_TYPE_POOL;
10332 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
10333 cb.cb_value = strchr(cb.cb_propname, '=');
10334 if (cb.cb_value == NULL) {
10335 (void) fprintf(stderr, gettext("missing value in "
10336 "property=value argument\n"));
10337 usage(B_FALSE);
10340 *(cb.cb_value) = '\0';
10341 cb.cb_value++;
10342 argc -= 2;
10343 argv += 2;
10345 if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
10346 /* Argument is a vdev */
10347 cb.cb_vdevs.cb_names = argv;
10348 cb.cb_vdevs.cb_names_count = 1;
10349 cb.cb_type = ZFS_TYPE_VDEV;
10350 argc = 0; /* No pools to process */
10351 } else if (are_all_pools(1, argv)) {
10352 /* The first arg is a pool name */
10353 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
10354 &cb.cb_vdevs)) {
10355 /* 2nd argument is a vdev */
10356 cb.cb_vdevs.cb_names = argv + 1;
10357 cb.cb_vdevs.cb_names_count = 1;
10358 cb.cb_type = ZFS_TYPE_VDEV;
10359 argc = 1; /* One pool to process */
10360 } else if (argc > 1) {
10361 (void) fprintf(stderr,
10362 gettext("too many pool names\n"));
10363 usage(B_FALSE);
10367 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
10368 B_FALSE, set_callback, &cb);
10370 return (error);
10373 /* Add up the total number of bytes left to initialize/trim across all vdevs */
10374 static uint64_t
10375 vdev_activity_remaining(nvlist_t *nv, zpool_wait_activity_t activity)
10377 uint64_t bytes_remaining;
10378 nvlist_t **child;
10379 uint_t c, children;
10380 vdev_stat_t *vs;
10382 assert(activity == ZPOOL_WAIT_INITIALIZE ||
10383 activity == ZPOOL_WAIT_TRIM);
10385 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
10386 (uint64_t **)&vs, &c) == 0);
10388 if (activity == ZPOOL_WAIT_INITIALIZE &&
10389 vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE)
10390 bytes_remaining = vs->vs_initialize_bytes_est -
10391 vs->vs_initialize_bytes_done;
10392 else if (activity == ZPOOL_WAIT_TRIM &&
10393 vs->vs_trim_state == VDEV_TRIM_ACTIVE)
10394 bytes_remaining = vs->vs_trim_bytes_est -
10395 vs->vs_trim_bytes_done;
10396 else
10397 bytes_remaining = 0;
10399 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10400 &child, &children) != 0)
10401 children = 0;
10403 for (c = 0; c < children; c++)
10404 bytes_remaining += vdev_activity_remaining(child[c], activity);
10406 return (bytes_remaining);
10409 /* Add up the total number of bytes left to rebuild across top-level vdevs */
10410 static uint64_t
10411 vdev_activity_top_remaining(nvlist_t *nv)
10413 uint64_t bytes_remaining = 0;
10414 nvlist_t **child;
10415 uint_t children;
10416 int error;
10418 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10419 &child, &children) != 0)
10420 children = 0;
10422 for (uint_t c = 0; c < children; c++) {
10423 vdev_rebuild_stat_t *vrs;
10424 uint_t i;
10426 error = nvlist_lookup_uint64_array(child[c],
10427 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i);
10428 if (error == 0) {
10429 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
10430 bytes_remaining += (vrs->vrs_bytes_est -
10431 vrs->vrs_bytes_rebuilt);
10436 return (bytes_remaining);
10439 /* Whether any vdevs are 'spare' or 'replacing' vdevs */
10440 static boolean_t
10441 vdev_any_spare_replacing(nvlist_t *nv)
10443 nvlist_t **child;
10444 uint_t c, children;
10445 char *vdev_type;
10447 (void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &vdev_type);
10449 if (strcmp(vdev_type, VDEV_TYPE_REPLACING) == 0 ||
10450 strcmp(vdev_type, VDEV_TYPE_SPARE) == 0 ||
10451 strcmp(vdev_type, VDEV_TYPE_DRAID_SPARE) == 0) {
10452 return (B_TRUE);
10455 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10456 &child, &children) != 0)
10457 children = 0;
10459 for (c = 0; c < children; c++) {
10460 if (vdev_any_spare_replacing(child[c]))
10461 return (B_TRUE);
10464 return (B_FALSE);
10467 typedef struct wait_data {
10468 char *wd_poolname;
10469 boolean_t wd_scripted;
10470 boolean_t wd_exact;
10471 boolean_t wd_headers_once;
10472 boolean_t wd_should_exit;
10473 /* Which activities to wait for */
10474 boolean_t wd_enabled[ZPOOL_WAIT_NUM_ACTIVITIES];
10475 float wd_interval;
10476 pthread_cond_t wd_cv;
10477 pthread_mutex_t wd_mutex;
10478 } wait_data_t;
10481 * Print to stdout a single line, containing one column for each activity that
10482 * we are waiting for specifying how many bytes of work are left for that
10483 * activity.
10485 static void
10486 print_wait_status_row(wait_data_t *wd, zpool_handle_t *zhp, int row)
10488 nvlist_t *config, *nvroot;
10489 uint_t c;
10490 int i;
10491 pool_checkpoint_stat_t *pcs = NULL;
10492 pool_scan_stat_t *pss = NULL;
10493 pool_removal_stat_t *prs = NULL;
10494 const char *const headers[] = {"DISCARD", "FREE", "INITIALIZE",
10495 "REPLACE", "REMOVE", "RESILVER", "SCRUB", "TRIM"};
10496 int col_widths[ZPOOL_WAIT_NUM_ACTIVITIES];
10498 /* Calculate the width of each column */
10499 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10501 * Make sure we have enough space in the col for pretty-printed
10502 * numbers and for the column header, and then leave a couple
10503 * spaces between cols for readability.
10505 col_widths[i] = MAX(strlen(headers[i]), 6) + 2;
10508 /* Print header if appropriate */
10509 int term_height = terminal_height();
10510 boolean_t reprint_header = (!wd->wd_headers_once && term_height > 0 &&
10511 row % (term_height-1) == 0);
10512 if (!wd->wd_scripted && (row == 0 || reprint_header)) {
10513 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10514 if (wd->wd_enabled[i])
10515 (void) printf("%*s", col_widths[i], headers[i]);
10517 (void) fputc('\n', stdout);
10520 /* Bytes of work remaining in each activity */
10521 int64_t bytes_rem[ZPOOL_WAIT_NUM_ACTIVITIES] = {0};
10523 bytes_rem[ZPOOL_WAIT_FREE] =
10524 zpool_get_prop_int(zhp, ZPOOL_PROP_FREEING, NULL);
10526 config = zpool_get_config(zhp, NULL);
10527 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
10529 (void) nvlist_lookup_uint64_array(nvroot,
10530 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
10531 if (pcs != NULL && pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
10532 bytes_rem[ZPOOL_WAIT_CKPT_DISCARD] = pcs->pcs_space;
10534 (void) nvlist_lookup_uint64_array(nvroot,
10535 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
10536 if (prs != NULL && prs->prs_state == DSS_SCANNING)
10537 bytes_rem[ZPOOL_WAIT_REMOVE] = prs->prs_to_copy -
10538 prs->prs_copied;
10540 (void) nvlist_lookup_uint64_array(nvroot,
10541 ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&pss, &c);
10542 if (pss != NULL && pss->pss_state == DSS_SCANNING &&
10543 pss->pss_pass_scrub_pause == 0) {
10544 int64_t rem = pss->pss_to_examine - pss->pss_issued;
10545 if (pss->pss_func == POOL_SCAN_SCRUB)
10546 bytes_rem[ZPOOL_WAIT_SCRUB] = rem;
10547 else
10548 bytes_rem[ZPOOL_WAIT_RESILVER] = rem;
10549 } else if (check_rebuilding(nvroot, NULL)) {
10550 bytes_rem[ZPOOL_WAIT_RESILVER] =
10551 vdev_activity_top_remaining(nvroot);
10554 bytes_rem[ZPOOL_WAIT_INITIALIZE] =
10555 vdev_activity_remaining(nvroot, ZPOOL_WAIT_INITIALIZE);
10556 bytes_rem[ZPOOL_WAIT_TRIM] =
10557 vdev_activity_remaining(nvroot, ZPOOL_WAIT_TRIM);
10560 * A replace finishes after resilvering finishes, so the amount of work
10561 * left for a replace is the same as for resilvering.
10563 * It isn't quite correct to say that if we have any 'spare' or
10564 * 'replacing' vdevs and a resilver is happening, then a replace is in
10565 * progress, like we do here. When a hot spare is used, the faulted vdev
10566 * is not removed after the hot spare is resilvered, so parent 'spare'
10567 * vdev is not removed either. So we could have a 'spare' vdev, but be
10568 * resilvering for a different reason. However, we use it as a heuristic
10569 * because we don't have access to the DTLs, which could tell us whether
10570 * or not we have really finished resilvering a hot spare.
10572 if (vdev_any_spare_replacing(nvroot))
10573 bytes_rem[ZPOOL_WAIT_REPLACE] = bytes_rem[ZPOOL_WAIT_RESILVER];
10575 if (timestamp_fmt != NODATE)
10576 print_timestamp(timestamp_fmt);
10578 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10579 char buf[64];
10580 if (!wd->wd_enabled[i])
10581 continue;
10583 if (wd->wd_exact)
10584 (void) snprintf(buf, sizeof (buf), "%" PRIi64,
10585 bytes_rem[i]);
10586 else
10587 zfs_nicenum(bytes_rem[i], buf, sizeof (buf));
10589 if (wd->wd_scripted)
10590 (void) printf(i == 0 ? "%s" : "\t%s", buf);
10591 else
10592 (void) printf(" %*s", col_widths[i] - 1, buf);
10594 (void) printf("\n");
10595 (void) fflush(stdout);
10598 static void *
10599 wait_status_thread(void *arg)
10601 wait_data_t *wd = (wait_data_t *)arg;
10602 zpool_handle_t *zhp;
10604 if ((zhp = zpool_open(g_zfs, wd->wd_poolname)) == NULL)
10605 return (void *)(1);
10607 for (int row = 0; ; row++) {
10608 boolean_t missing;
10609 struct timespec timeout;
10610 int ret = 0;
10611 (void) clock_gettime(CLOCK_REALTIME, &timeout);
10613 if (zpool_refresh_stats(zhp, &missing) != 0 || missing ||
10614 zpool_props_refresh(zhp) != 0) {
10615 zpool_close(zhp);
10616 return (void *)(uintptr_t)(missing ? 0 : 1);
10619 print_wait_status_row(wd, zhp, row);
10621 timeout.tv_sec += floor(wd->wd_interval);
10622 long nanos = timeout.tv_nsec +
10623 (wd->wd_interval - floor(wd->wd_interval)) * NANOSEC;
10624 if (nanos >= NANOSEC) {
10625 timeout.tv_sec++;
10626 timeout.tv_nsec = nanos - NANOSEC;
10627 } else {
10628 timeout.tv_nsec = nanos;
10630 pthread_mutex_lock(&wd->wd_mutex);
10631 if (!wd->wd_should_exit)
10632 ret = pthread_cond_timedwait(&wd->wd_cv, &wd->wd_mutex,
10633 &timeout);
10634 pthread_mutex_unlock(&wd->wd_mutex);
10635 if (ret == 0) {
10636 break; /* signaled by main thread */
10637 } else if (ret != ETIMEDOUT) {
10638 (void) fprintf(stderr, gettext("pthread_cond_timedwait "
10639 "failed: %s\n"), strerror(ret));
10640 zpool_close(zhp);
10641 return (void *)(uintptr_t)(1);
10645 zpool_close(zhp);
10646 return (void *)(0);
10650 zpool_do_wait(int argc, char **argv)
10652 boolean_t verbose = B_FALSE;
10653 int c, i;
10654 unsigned long count;
10655 pthread_t status_thr;
10656 int error = 0;
10657 zpool_handle_t *zhp;
10659 wait_data_t wd;
10660 wd.wd_scripted = B_FALSE;
10661 wd.wd_exact = B_FALSE;
10662 wd.wd_headers_once = B_FALSE;
10663 wd.wd_should_exit = B_FALSE;
10665 pthread_mutex_init(&wd.wd_mutex, NULL);
10666 pthread_cond_init(&wd.wd_cv, NULL);
10668 /* By default, wait for all types of activity. */
10669 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++)
10670 wd.wd_enabled[i] = B_TRUE;
10672 while ((c = getopt(argc, argv, "HpT:t:")) != -1) {
10673 switch (c) {
10674 case 'H':
10675 wd.wd_scripted = B_TRUE;
10676 break;
10677 case 'n':
10678 wd.wd_headers_once = B_TRUE;
10679 break;
10680 case 'p':
10681 wd.wd_exact = B_TRUE;
10682 break;
10683 case 'T':
10684 get_timestamp_arg(*optarg);
10685 break;
10686 case 't':
10687 /* Reset activities array */
10688 memset(&wd.wd_enabled, 0, sizeof (wd.wd_enabled));
10690 for (char *tok; (tok = strsep(&optarg, ",")); ) {
10691 static const char *const col_opts[] = {
10692 "discard", "free", "initialize", "replace",
10693 "remove", "resilver", "scrub", "trim" };
10695 for (i = 0; i < ARRAY_SIZE(col_opts); ++i)
10696 if (strcmp(tok, col_opts[i]) == 0) {
10697 wd.wd_enabled[i] = B_TRUE;
10698 goto found;
10701 (void) fprintf(stderr,
10702 gettext("invalid activity '%s'\n"), tok);
10703 usage(B_FALSE);
10704 found:;
10706 break;
10707 case '?':
10708 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
10709 optopt);
10710 usage(B_FALSE);
10714 argc -= optind;
10715 argv += optind;
10717 get_interval_count(&argc, argv, &wd.wd_interval, &count);
10718 if (count != 0) {
10719 /* This subcmd only accepts an interval, not a count */
10720 (void) fprintf(stderr, gettext("too many arguments\n"));
10721 usage(B_FALSE);
10724 if (wd.wd_interval != 0)
10725 verbose = B_TRUE;
10727 if (argc < 1) {
10728 (void) fprintf(stderr, gettext("missing 'pool' argument\n"));
10729 usage(B_FALSE);
10731 if (argc > 1) {
10732 (void) fprintf(stderr, gettext("too many arguments\n"));
10733 usage(B_FALSE);
10736 wd.wd_poolname = argv[0];
10738 if ((zhp = zpool_open(g_zfs, wd.wd_poolname)) == NULL)
10739 return (1);
10741 if (verbose) {
10743 * We use a separate thread for printing status updates because
10744 * the main thread will call lzc_wait(), which blocks as long
10745 * as an activity is in progress, which can be a long time.
10747 if (pthread_create(&status_thr, NULL, wait_status_thread, &wd)
10748 != 0) {
10749 (void) fprintf(stderr, gettext("failed to create status"
10750 "thread: %s\n"), strerror(errno));
10751 zpool_close(zhp);
10752 return (1);
10757 * Loop over all activities that we are supposed to wait for until none
10758 * of them are in progress. Note that this means we can end up waiting
10759 * for more activities to complete than just those that were in progress
10760 * when we began waiting; if an activity we are interested in begins
10761 * while we are waiting for another activity, we will wait for both to
10762 * complete before exiting.
10764 for (;;) {
10765 boolean_t missing = B_FALSE;
10766 boolean_t any_waited = B_FALSE;
10768 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10769 boolean_t waited;
10771 if (!wd.wd_enabled[i])
10772 continue;
10774 error = zpool_wait_status(zhp, i, &missing, &waited);
10775 if (error != 0 || missing)
10776 break;
10778 any_waited = (any_waited || waited);
10781 if (error != 0 || missing || !any_waited)
10782 break;
10785 zpool_close(zhp);
10787 if (verbose) {
10788 uintptr_t status;
10789 pthread_mutex_lock(&wd.wd_mutex);
10790 wd.wd_should_exit = B_TRUE;
10791 pthread_cond_signal(&wd.wd_cv);
10792 pthread_mutex_unlock(&wd.wd_mutex);
10793 (void) pthread_join(status_thr, (void *)&status);
10794 if (status != 0)
10795 error = status;
10798 pthread_mutex_destroy(&wd.wd_mutex);
10799 pthread_cond_destroy(&wd.wd_cv);
10800 return (error);
10803 static int
10804 find_command_idx(const char *command, int *idx)
10806 for (int i = 0; i < NCOMMAND; ++i) {
10807 if (command_table[i].name == NULL)
10808 continue;
10810 if (strcmp(command, command_table[i].name) == 0) {
10811 *idx = i;
10812 return (0);
10815 return (1);
10819 * Display version message
10821 static int
10822 zpool_do_version(int argc, char **argv)
10824 (void) argc, (void) argv;
10825 return (zfs_version_print() != 0);
10829 * Do zpool_load_compat() and print error message on failure
10831 static zpool_compat_status_t
10832 zpool_do_load_compat(const char *compat, boolean_t *list)
10834 char report[1024];
10836 zpool_compat_status_t ret;
10838 ret = zpool_load_compat(compat, list, report, 1024);
10839 switch (ret) {
10841 case ZPOOL_COMPATIBILITY_OK:
10842 break;
10844 case ZPOOL_COMPATIBILITY_NOFILES:
10845 case ZPOOL_COMPATIBILITY_BADFILE:
10846 case ZPOOL_COMPATIBILITY_BADTOKEN:
10847 (void) fprintf(stderr, "Error: %s\n", report);
10848 break;
10850 case ZPOOL_COMPATIBILITY_WARNTOKEN:
10851 (void) fprintf(stderr, "Warning: %s\n", report);
10852 ret = ZPOOL_COMPATIBILITY_OK;
10853 break;
10855 return (ret);
10859 main(int argc, char **argv)
10861 int ret = 0;
10862 int i = 0;
10863 char *cmdname;
10864 char **newargv;
10866 (void) setlocale(LC_ALL, "");
10867 (void) setlocale(LC_NUMERIC, "C");
10868 (void) textdomain(TEXT_DOMAIN);
10869 srand(time(NULL));
10871 opterr = 0;
10874 * Make sure the user has specified some command.
10876 if (argc < 2) {
10877 (void) fprintf(stderr, gettext("missing command\n"));
10878 usage(B_FALSE);
10881 cmdname = argv[1];
10884 * Special case '-?'
10886 if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
10887 usage(B_TRUE);
10890 * Special case '-V|--version'
10892 if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
10893 return (zpool_do_version(argc, argv));
10895 if ((g_zfs = libzfs_init()) == NULL) {
10896 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
10897 return (1);
10900 libzfs_print_on_error(g_zfs, B_TRUE);
10902 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
10905 * Many commands modify input strings for string parsing reasons.
10906 * We create a copy to protect the original argv.
10908 newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
10909 for (i = 0; i < argc; i++)
10910 newargv[i] = strdup(argv[i]);
10911 newargv[argc] = NULL;
10914 * Run the appropriate command.
10916 if (find_command_idx(cmdname, &i) == 0) {
10917 current_command = &command_table[i];
10918 ret = command_table[i].func(argc - 1, newargv + 1);
10919 } else if (strchr(cmdname, '=')) {
10920 verify(find_command_idx("set", &i) == 0);
10921 current_command = &command_table[i];
10922 ret = command_table[i].func(argc, newargv);
10923 } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
10925 * 'freeze' is a vile debugging abomination, so we treat
10926 * it as such.
10928 zfs_cmd_t zc = {"\0"};
10930 (void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
10931 ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
10932 if (ret != 0) {
10933 (void) fprintf(stderr,
10934 gettext("failed to freeze pool: %d\n"), errno);
10935 ret = 1;
10938 log_history = 0;
10939 } else {
10940 (void) fprintf(stderr, gettext("unrecognized "
10941 "command '%s'\n"), cmdname);
10942 usage(B_FALSE);
10943 ret = 1;
10946 for (i = 0; i < argc; i++)
10947 free(newargv[i]);
10948 free(newargv);
10950 if (ret == 0 && log_history)
10951 (void) zpool_log_history(g_zfs, history_str);
10953 libzfs_fini(g_zfs);
10956 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
10957 * for the purposes of running ::findleaks.
10959 if (getenv("ZFS_ABORT") != NULL) {
10960 (void) printf("dumping core by request\n");
10961 abort();
10964 return (ret);