Add the ability to uninitialize
[zfs.git] / cmd / zpool / zpool_main.c
blob3e08e031414d49b777bb918dc677de3204c043df
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 | -u] [-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 "\tset <vdev_property=value> <pool> <vdev>\n"));
426 case HELP_SPLIT:
427 return (gettext("\tsplit [-gLnPl] [-R altroot] [-o mntopts]\n"
428 "\t [-o property=value] <pool> <newpool> "
429 "[<device> ...]\n"));
430 case HELP_REGUID:
431 return (gettext("\treguid <pool>\n"));
432 case HELP_SYNC:
433 return (gettext("\tsync [pool] ...\n"));
434 case HELP_VERSION:
435 return (gettext("\tversion\n"));
436 case HELP_WAIT:
437 return (gettext("\twait [-Hp] [-T d|u] [-t <activity>[,...]] "
438 "<pool> [interval]\n"));
439 default:
440 __builtin_unreachable();
444 static void
445 zpool_collect_leaves(zpool_handle_t *zhp, nvlist_t *nvroot, nvlist_t *res)
447 uint_t children = 0;
448 nvlist_t **child;
449 uint_t i;
451 (void) nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
452 &child, &children);
454 if (children == 0) {
455 char *path = zpool_vdev_name(g_zfs, zhp, nvroot,
456 VDEV_NAME_PATH);
458 if (strcmp(path, VDEV_TYPE_INDIRECT) != 0 &&
459 strcmp(path, VDEV_TYPE_HOLE) != 0)
460 fnvlist_add_boolean(res, path);
462 free(path);
463 return;
466 for (i = 0; i < children; i++) {
467 zpool_collect_leaves(zhp, child[i], res);
472 * Callback routine that will print out a pool property value.
474 static int
475 print_pool_prop_cb(int prop, void *cb)
477 FILE *fp = cb;
479 (void) fprintf(fp, "\t%-19s ", zpool_prop_to_name(prop));
481 if (zpool_prop_readonly(prop))
482 (void) fprintf(fp, " NO ");
483 else
484 (void) fprintf(fp, " YES ");
486 if (zpool_prop_values(prop) == NULL)
487 (void) fprintf(fp, "-\n");
488 else
489 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
491 return (ZPROP_CONT);
495 * Callback routine that will print out a vdev property value.
497 static int
498 print_vdev_prop_cb(int prop, void *cb)
500 FILE *fp = cb;
502 (void) fprintf(fp, "\t%-19s ", vdev_prop_to_name(prop));
504 if (vdev_prop_readonly(prop))
505 (void) fprintf(fp, " NO ");
506 else
507 (void) fprintf(fp, " YES ");
509 if (vdev_prop_values(prop) == NULL)
510 (void) fprintf(fp, "-\n");
511 else
512 (void) fprintf(fp, "%s\n", vdev_prop_values(prop));
514 return (ZPROP_CONT);
518 * Display usage message. If we're inside a command, display only the usage for
519 * that command. Otherwise, iterate over the entire command table and display
520 * a complete usage message.
522 static __attribute__((noreturn)) void
523 usage(boolean_t requested)
525 FILE *fp = requested ? stdout : stderr;
527 if (current_command == NULL) {
528 int i;
530 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
531 (void) fprintf(fp,
532 gettext("where 'command' is one of the following:\n\n"));
534 for (i = 0; i < NCOMMAND; i++) {
535 if (command_table[i].name == NULL)
536 (void) fprintf(fp, "\n");
537 else
538 (void) fprintf(fp, "%s",
539 get_usage(command_table[i].usage));
541 } else {
542 (void) fprintf(fp, gettext("usage:\n"));
543 (void) fprintf(fp, "%s", get_usage(current_command->usage));
546 if (current_command != NULL &&
547 current_prop_type != (ZFS_TYPE_POOL | ZFS_TYPE_VDEV) &&
548 ((strcmp(current_command->name, "set") == 0) ||
549 (strcmp(current_command->name, "get") == 0) ||
550 (strcmp(current_command->name, "list") == 0))) {
552 (void) fprintf(fp, "%s",
553 gettext("\nthe following properties are supported:\n"));
555 (void) fprintf(fp, "\n\t%-19s %s %s\n\n",
556 "PROPERTY", "EDIT", "VALUES");
558 /* Iterate over all properties */
559 if (current_prop_type == ZFS_TYPE_POOL) {
560 (void) zprop_iter(print_pool_prop_cb, fp, B_FALSE,
561 B_TRUE, current_prop_type);
563 (void) fprintf(fp, "\t%-19s ", "feature@...");
564 (void) fprintf(fp, "YES "
565 "disabled | enabled | active\n");
567 (void) fprintf(fp, gettext("\nThe feature@ properties "
568 "must be appended with a feature name.\n"
569 "See zpool-features(7).\n"));
570 } else if (current_prop_type == ZFS_TYPE_VDEV) {
571 (void) zprop_iter(print_vdev_prop_cb, fp, B_FALSE,
572 B_TRUE, current_prop_type);
577 * See comments at end of main().
579 if (getenv("ZFS_ABORT") != NULL) {
580 (void) printf("dumping core by request\n");
581 abort();
584 exit(requested ? 0 : 2);
588 * zpool initialize [-c | -s | -u] [-w] <pool> [<vdev> ...]
589 * Initialize all unused blocks in the specified vdevs, or all vdevs in the pool
590 * if none specified.
592 * -c Cancel. Ends active initializing.
593 * -s Suspend. Initializing can then be restarted with no flags.
594 * -u Uninitialize. Clears initialization state.
595 * -w Wait. Blocks until initializing has completed.
598 zpool_do_initialize(int argc, char **argv)
600 int c;
601 char *poolname;
602 zpool_handle_t *zhp;
603 nvlist_t *vdevs;
604 int err = 0;
605 boolean_t wait = B_FALSE;
607 struct option long_options[] = {
608 {"cancel", no_argument, NULL, 'c'},
609 {"suspend", no_argument, NULL, 's'},
610 {"uninit", no_argument, NULL, 'u'},
611 {"wait", no_argument, NULL, 'w'},
612 {0, 0, 0, 0}
615 pool_initialize_func_t cmd_type = POOL_INITIALIZE_START;
616 while ((c = getopt_long(argc, argv, "csuw", long_options,
617 NULL)) != -1) {
618 switch (c) {
619 case 'c':
620 if (cmd_type != POOL_INITIALIZE_START &&
621 cmd_type != POOL_INITIALIZE_CANCEL) {
622 (void) fprintf(stderr, gettext("-c cannot be "
623 "combined with other options\n"));
624 usage(B_FALSE);
626 cmd_type = POOL_INITIALIZE_CANCEL;
627 break;
628 case 's':
629 if (cmd_type != POOL_INITIALIZE_START &&
630 cmd_type != POOL_INITIALIZE_SUSPEND) {
631 (void) fprintf(stderr, gettext("-s cannot be "
632 "combined with other options\n"));
633 usage(B_FALSE);
635 cmd_type = POOL_INITIALIZE_SUSPEND;
636 break;
637 case 'u':
638 if (cmd_type != POOL_INITIALIZE_START &&
639 cmd_type != POOL_INITIALIZE_UNINIT) {
640 (void) fprintf(stderr, gettext("-u cannot be "
641 "combined with other options\n"));
642 usage(B_FALSE);
644 cmd_type = POOL_INITIALIZE_UNINIT;
645 break;
646 case 'w':
647 wait = B_TRUE;
648 break;
649 case '?':
650 if (optopt != 0) {
651 (void) fprintf(stderr,
652 gettext("invalid option '%c'\n"), optopt);
653 } else {
654 (void) fprintf(stderr,
655 gettext("invalid option '%s'\n"),
656 argv[optind - 1]);
658 usage(B_FALSE);
662 argc -= optind;
663 argv += optind;
665 if (argc < 1) {
666 (void) fprintf(stderr, gettext("missing pool name argument\n"));
667 usage(B_FALSE);
668 return (-1);
671 if (wait && (cmd_type != POOL_INITIALIZE_START)) {
672 (void) fprintf(stderr, gettext("-w cannot be used with -c, -s"
673 "or -u\n"));
674 usage(B_FALSE);
677 poolname = argv[0];
678 zhp = zpool_open(g_zfs, poolname);
679 if (zhp == NULL)
680 return (-1);
682 vdevs = fnvlist_alloc();
683 if (argc == 1) {
684 /* no individual leaf vdevs specified, so add them all */
685 nvlist_t *config = zpool_get_config(zhp, NULL);
686 nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
687 ZPOOL_CONFIG_VDEV_TREE);
688 zpool_collect_leaves(zhp, nvroot, vdevs);
689 } else {
690 for (int i = 1; i < argc; i++) {
691 fnvlist_add_boolean(vdevs, argv[i]);
695 if (wait)
696 err = zpool_initialize_wait(zhp, cmd_type, vdevs);
697 else
698 err = zpool_initialize(zhp, cmd_type, vdevs);
700 fnvlist_free(vdevs);
701 zpool_close(zhp);
703 return (err);
707 * print a pool vdev config for dry runs
709 static void
710 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
711 const char *match, int name_flags)
713 nvlist_t **child;
714 uint_t c, children;
715 char *vname;
716 boolean_t printed = B_FALSE;
718 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
719 &child, &children) != 0) {
720 if (name != NULL)
721 (void) printf("\t%*s%s\n", indent, "", name);
722 return;
725 for (c = 0; c < children; c++) {
726 uint64_t is_log = B_FALSE, is_hole = B_FALSE;
727 const char *class = "";
729 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
730 &is_hole);
732 if (is_hole == B_TRUE) {
733 continue;
736 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
737 &is_log);
738 if (is_log)
739 class = VDEV_ALLOC_BIAS_LOG;
740 (void) nvlist_lookup_string(child[c],
741 ZPOOL_CONFIG_ALLOCATION_BIAS, &class);
742 if (strcmp(match, class) != 0)
743 continue;
745 if (!printed && name != NULL) {
746 (void) printf("\t%*s%s\n", indent, "", name);
747 printed = B_TRUE;
749 vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
750 print_vdev_tree(zhp, vname, child[c], indent + 2, "",
751 name_flags);
752 free(vname);
757 * Print the list of l2cache devices for dry runs.
759 static void
760 print_cache_list(nvlist_t *nv, int indent)
762 nvlist_t **child;
763 uint_t c, children;
765 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
766 &child, &children) == 0 && children > 0) {
767 (void) printf("\t%*s%s\n", indent, "", "cache");
768 } else {
769 return;
771 for (c = 0; c < children; c++) {
772 char *vname;
774 vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
775 (void) printf("\t%*s%s\n", indent + 2, "", vname);
776 free(vname);
781 * Print the list of spares for dry runs.
783 static void
784 print_spare_list(nvlist_t *nv, int indent)
786 nvlist_t **child;
787 uint_t c, children;
789 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
790 &child, &children) == 0 && children > 0) {
791 (void) printf("\t%*s%s\n", indent, "", "spares");
792 } else {
793 return;
795 for (c = 0; c < children; c++) {
796 char *vname;
798 vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
799 (void) printf("\t%*s%s\n", indent + 2, "", vname);
800 free(vname);
804 static boolean_t
805 prop_list_contains_feature(nvlist_t *proplist)
807 nvpair_t *nvp;
808 for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
809 nvp = nvlist_next_nvpair(proplist, nvp)) {
810 if (zpool_prop_feature(nvpair_name(nvp)))
811 return (B_TRUE);
813 return (B_FALSE);
817 * Add a property pair (name, string-value) into a property nvlist.
819 static int
820 add_prop_list(const char *propname, const char *propval, nvlist_t **props,
821 boolean_t poolprop)
823 zpool_prop_t prop = ZPOOL_PROP_INVAL;
824 nvlist_t *proplist;
825 const char *normnm;
826 const char *strval;
828 if (*props == NULL &&
829 nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
830 (void) fprintf(stderr,
831 gettext("internal error: out of memory\n"));
832 return (1);
835 proplist = *props;
837 if (poolprop) {
838 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
839 const char *cname =
840 zpool_prop_to_name(ZPOOL_PROP_COMPATIBILITY);
842 if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
843 (!zpool_prop_feature(propname) &&
844 !zpool_prop_vdev(propname))) {
845 (void) fprintf(stderr, gettext("property '%s' is "
846 "not a valid pool or vdev property\n"), propname);
847 return (2);
851 * feature@ properties and version should not be specified
852 * at the same time.
854 if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
855 nvlist_exists(proplist, vname)) ||
856 (prop == ZPOOL_PROP_VERSION &&
857 prop_list_contains_feature(proplist))) {
858 (void) fprintf(stderr, gettext("'feature@' and "
859 "'version' properties cannot be specified "
860 "together\n"));
861 return (2);
865 * if version is specified, only "legacy" compatibility
866 * may be requested
868 if ((prop == ZPOOL_PROP_COMPATIBILITY &&
869 strcmp(propval, ZPOOL_COMPAT_LEGACY) != 0 &&
870 nvlist_exists(proplist, vname)) ||
871 (prop == ZPOOL_PROP_VERSION &&
872 nvlist_exists(proplist, cname) &&
873 strcmp(fnvlist_lookup_string(proplist, cname),
874 ZPOOL_COMPAT_LEGACY) != 0)) {
875 (void) fprintf(stderr, gettext("when 'version' is "
876 "specified, the 'compatibility' feature may only "
877 "be set to '" ZPOOL_COMPAT_LEGACY "'\n"));
878 return (2);
881 if (zpool_prop_feature(propname) || zpool_prop_vdev(propname))
882 normnm = propname;
883 else
884 normnm = zpool_prop_to_name(prop);
885 } else {
886 zfs_prop_t fsprop = zfs_name_to_prop(propname);
888 if (zfs_prop_valid_for_type(fsprop, ZFS_TYPE_FILESYSTEM,
889 B_FALSE)) {
890 normnm = zfs_prop_to_name(fsprop);
891 } else if (zfs_prop_user(propname) ||
892 zfs_prop_userquota(propname)) {
893 normnm = propname;
894 } else {
895 (void) fprintf(stderr, gettext("property '%s' is "
896 "not a valid filesystem property\n"), propname);
897 return (2);
901 if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
902 prop != ZPOOL_PROP_CACHEFILE) {
903 (void) fprintf(stderr, gettext("property '%s' "
904 "specified multiple times\n"), propname);
905 return (2);
908 if (nvlist_add_string(proplist, normnm, propval) != 0) {
909 (void) fprintf(stderr, gettext("internal "
910 "error: out of memory\n"));
911 return (1);
914 return (0);
918 * Set a default property pair (name, string-value) in a property nvlist
920 static int
921 add_prop_list_default(const char *propname, const char *propval,
922 nvlist_t **props)
924 const char *pval;
926 if (nvlist_lookup_string(*props, propname, &pval) == 0)
927 return (0);
929 return (add_prop_list(propname, propval, props, B_TRUE));
933 * zpool add [-fgLnP] [-o property=value] <pool> <vdev> ...
935 * -f Force addition of devices, even if they appear in use
936 * -g Display guid for individual vdev name.
937 * -L Follow links when resolving vdev path name.
938 * -n Do not add the devices, but display the resulting layout if
939 * they were to be added.
940 * -o Set property=value.
941 * -P Display full path for vdev name.
943 * Adds the given vdevs to 'pool'. As with create, the bulk of this work is
944 * handled by make_root_vdev(), which constructs the nvlist needed to pass to
945 * libzfs.
948 zpool_do_add(int argc, char **argv)
950 boolean_t force = B_FALSE;
951 boolean_t dryrun = B_FALSE;
952 int name_flags = 0;
953 int c;
954 nvlist_t *nvroot;
955 char *poolname;
956 int ret;
957 zpool_handle_t *zhp;
958 nvlist_t *config;
959 nvlist_t *props = NULL;
960 char *propval;
962 /* check options */
963 while ((c = getopt(argc, argv, "fgLno:P")) != -1) {
964 switch (c) {
965 case 'f':
966 force = B_TRUE;
967 break;
968 case 'g':
969 name_flags |= VDEV_NAME_GUID;
970 break;
971 case 'L':
972 name_flags |= VDEV_NAME_FOLLOW_LINKS;
973 break;
974 case 'n':
975 dryrun = B_TRUE;
976 break;
977 case 'o':
978 if ((propval = strchr(optarg, '=')) == NULL) {
979 (void) fprintf(stderr, gettext("missing "
980 "'=' for -o option\n"));
981 usage(B_FALSE);
983 *propval = '\0';
984 propval++;
986 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
987 (add_prop_list(optarg, propval, &props, B_TRUE)))
988 usage(B_FALSE);
989 break;
990 case 'P':
991 name_flags |= VDEV_NAME_PATH;
992 break;
993 case '?':
994 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
995 optopt);
996 usage(B_FALSE);
1000 argc -= optind;
1001 argv += optind;
1003 /* get pool name and check number of arguments */
1004 if (argc < 1) {
1005 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1006 usage(B_FALSE);
1008 if (argc < 2) {
1009 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1010 usage(B_FALSE);
1013 poolname = argv[0];
1015 argc--;
1016 argv++;
1018 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1019 return (1);
1021 if ((config = zpool_get_config(zhp, NULL)) == NULL) {
1022 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
1023 poolname);
1024 zpool_close(zhp);
1025 return (1);
1028 /* unless manually specified use "ashift" pool property (if set) */
1029 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
1030 int intval;
1031 zprop_source_t src;
1032 char strval[ZPOOL_MAXPROPLEN];
1034 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
1035 if (src != ZPROP_SRC_DEFAULT) {
1036 (void) sprintf(strval, "%" PRId32, intval);
1037 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
1038 &props, B_TRUE) == 0);
1042 /* pass off to make_root_vdev for processing */
1043 nvroot = make_root_vdev(zhp, props, force, !force, B_FALSE, dryrun,
1044 argc, argv);
1045 if (nvroot == NULL) {
1046 zpool_close(zhp);
1047 return (1);
1050 if (dryrun) {
1051 nvlist_t *poolnvroot;
1052 nvlist_t **l2child, **sparechild;
1053 uint_t l2children, sparechildren, c;
1054 char *vname;
1055 boolean_t hadcache = B_FALSE, hadspare = B_FALSE;
1057 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1058 &poolnvroot) == 0);
1060 (void) printf(gettext("would update '%s' to the following "
1061 "configuration:\n\n"), zpool_get_name(zhp));
1063 /* print original main pool and new tree */
1064 print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
1065 name_flags | VDEV_NAME_TYPE_ID);
1066 print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
1068 /* print other classes: 'dedup', 'special', and 'log' */
1069 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1070 print_vdev_tree(zhp, "dedup", poolnvroot, 0,
1071 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1072 print_vdev_tree(zhp, NULL, nvroot, 0,
1073 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1074 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1075 print_vdev_tree(zhp, "dedup", nvroot, 0,
1076 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1079 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1080 print_vdev_tree(zhp, "special", poolnvroot, 0,
1081 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1082 print_vdev_tree(zhp, NULL, nvroot, 0,
1083 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1084 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1085 print_vdev_tree(zhp, "special", nvroot, 0,
1086 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1089 if (num_logs(poolnvroot) > 0) {
1090 print_vdev_tree(zhp, "logs", poolnvroot, 0,
1091 VDEV_ALLOC_BIAS_LOG, name_flags);
1092 print_vdev_tree(zhp, NULL, nvroot, 0,
1093 VDEV_ALLOC_BIAS_LOG, name_flags);
1094 } else if (num_logs(nvroot) > 0) {
1095 print_vdev_tree(zhp, "logs", nvroot, 0,
1096 VDEV_ALLOC_BIAS_LOG, name_flags);
1099 /* Do the same for the caches */
1100 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
1101 &l2child, &l2children) == 0 && l2children) {
1102 hadcache = B_TRUE;
1103 (void) printf(gettext("\tcache\n"));
1104 for (c = 0; c < l2children; c++) {
1105 vname = zpool_vdev_name(g_zfs, NULL,
1106 l2child[c], name_flags);
1107 (void) printf("\t %s\n", vname);
1108 free(vname);
1111 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1112 &l2child, &l2children) == 0 && l2children) {
1113 if (!hadcache)
1114 (void) printf(gettext("\tcache\n"));
1115 for (c = 0; c < l2children; c++) {
1116 vname = zpool_vdev_name(g_zfs, NULL,
1117 l2child[c], name_flags);
1118 (void) printf("\t %s\n", vname);
1119 free(vname);
1122 /* And finally the spares */
1123 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_SPARES,
1124 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1125 hadspare = B_TRUE;
1126 (void) printf(gettext("\tspares\n"));
1127 for (c = 0; c < sparechildren; c++) {
1128 vname = zpool_vdev_name(g_zfs, NULL,
1129 sparechild[c], name_flags);
1130 (void) printf("\t %s\n", vname);
1131 free(vname);
1134 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1135 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1136 if (!hadspare)
1137 (void) printf(gettext("\tspares\n"));
1138 for (c = 0; c < sparechildren; c++) {
1139 vname = zpool_vdev_name(g_zfs, NULL,
1140 sparechild[c], name_flags);
1141 (void) printf("\t %s\n", vname);
1142 free(vname);
1146 ret = 0;
1147 } else {
1148 ret = (zpool_add(zhp, nvroot) != 0);
1151 nvlist_free(props);
1152 nvlist_free(nvroot);
1153 zpool_close(zhp);
1155 return (ret);
1159 * zpool remove [-npsw] <pool> <vdev> ...
1161 * Removes the given vdev from the pool.
1164 zpool_do_remove(int argc, char **argv)
1166 char *poolname;
1167 int i, ret = 0;
1168 zpool_handle_t *zhp = NULL;
1169 boolean_t stop = B_FALSE;
1170 int c;
1171 boolean_t noop = B_FALSE;
1172 boolean_t parsable = B_FALSE;
1173 boolean_t wait = B_FALSE;
1175 /* check options */
1176 while ((c = getopt(argc, argv, "npsw")) != -1) {
1177 switch (c) {
1178 case 'n':
1179 noop = B_TRUE;
1180 break;
1181 case 'p':
1182 parsable = B_TRUE;
1183 break;
1184 case 's':
1185 stop = B_TRUE;
1186 break;
1187 case 'w':
1188 wait = B_TRUE;
1189 break;
1190 case '?':
1191 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1192 optopt);
1193 usage(B_FALSE);
1197 argc -= optind;
1198 argv += optind;
1200 /* get pool name and check number of arguments */
1201 if (argc < 1) {
1202 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1203 usage(B_FALSE);
1206 poolname = argv[0];
1208 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1209 return (1);
1211 if (stop && noop) {
1212 zpool_close(zhp);
1213 (void) fprintf(stderr, gettext("stop request ignored\n"));
1214 return (0);
1217 if (stop) {
1218 if (argc > 1) {
1219 (void) fprintf(stderr, gettext("too many arguments\n"));
1220 usage(B_FALSE);
1222 if (zpool_vdev_remove_cancel(zhp) != 0)
1223 ret = 1;
1224 if (wait) {
1225 (void) fprintf(stderr, gettext("invalid option "
1226 "combination: -w cannot be used with -s\n"));
1227 usage(B_FALSE);
1229 } else {
1230 if (argc < 2) {
1231 (void) fprintf(stderr, gettext("missing device\n"));
1232 usage(B_FALSE);
1235 for (i = 1; i < argc; i++) {
1236 if (noop) {
1237 uint64_t size;
1239 if (zpool_vdev_indirect_size(zhp, argv[i],
1240 &size) != 0) {
1241 ret = 1;
1242 break;
1244 if (parsable) {
1245 (void) printf("%s %llu\n",
1246 argv[i], (unsigned long long)size);
1247 } else {
1248 char valstr[32];
1249 zfs_nicenum(size, valstr,
1250 sizeof (valstr));
1251 (void) printf("Memory that will be "
1252 "used after removing %s: %s\n",
1253 argv[i], valstr);
1255 } else {
1256 if (zpool_vdev_remove(zhp, argv[i]) != 0)
1257 ret = 1;
1261 if (ret == 0 && wait)
1262 ret = zpool_wait(zhp, ZPOOL_WAIT_REMOVE);
1264 zpool_close(zhp);
1266 return (ret);
1270 * Return 1 if a vdev is active (being used in a pool)
1271 * Return 0 if a vdev is inactive (offlined or faulted, or not in active pool)
1273 * This is useful for checking if a disk in an active pool is offlined or
1274 * faulted.
1276 static int
1277 vdev_is_active(char *vdev_path)
1279 int fd;
1280 fd = open(vdev_path, O_EXCL);
1281 if (fd < 0) {
1282 return (1); /* cant open O_EXCL - disk is active */
1285 close(fd);
1286 return (0); /* disk is inactive in the pool */
1290 * zpool labelclear [-f] <vdev>
1292 * -f Force clearing the label for the vdevs which are members of
1293 * the exported or foreign pools.
1295 * Verifies that the vdev is not active and zeros out the label information
1296 * on the device.
1299 zpool_do_labelclear(int argc, char **argv)
1301 char vdev[MAXPATHLEN];
1302 char *name = NULL;
1303 int c, fd = -1, ret = 0;
1304 nvlist_t *config;
1305 pool_state_t state;
1306 boolean_t inuse = B_FALSE;
1307 boolean_t force = B_FALSE;
1309 /* check options */
1310 while ((c = getopt(argc, argv, "f")) != -1) {
1311 switch (c) {
1312 case 'f':
1313 force = B_TRUE;
1314 break;
1315 default:
1316 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1317 optopt);
1318 usage(B_FALSE);
1322 argc -= optind;
1323 argv += optind;
1325 /* get vdev name */
1326 if (argc < 1) {
1327 (void) fprintf(stderr, gettext("missing vdev name\n"));
1328 usage(B_FALSE);
1330 if (argc > 1) {
1331 (void) fprintf(stderr, gettext("too many arguments\n"));
1332 usage(B_FALSE);
1335 (void) strlcpy(vdev, argv[0], sizeof (vdev));
1338 * If we cannot open an absolute path, we quit.
1339 * Otherwise if the provided vdev name doesn't point to a file,
1340 * try prepending expected disk paths and partition numbers.
1342 if ((fd = open(vdev, O_RDWR)) < 0) {
1343 int error;
1344 if (vdev[0] == '/') {
1345 (void) fprintf(stderr, gettext("failed to open "
1346 "%s: %s\n"), vdev, strerror(errno));
1347 return (1);
1350 error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
1351 if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
1352 if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
1353 error = ENOENT;
1356 if (error || ((fd = open(vdev, O_RDWR)) < 0)) {
1357 if (errno == ENOENT) {
1358 (void) fprintf(stderr, gettext(
1359 "failed to find device %s, try "
1360 "specifying absolute path instead\n"),
1361 argv[0]);
1362 return (1);
1365 (void) fprintf(stderr, gettext("failed to open %s:"
1366 " %s\n"), vdev, strerror(errno));
1367 return (1);
1372 * Flush all dirty pages for the block device. This should not be
1373 * fatal when the device does not support BLKFLSBUF as would be the
1374 * case for a file vdev.
1376 if ((zfs_dev_flush(fd) != 0) && (errno != ENOTTY))
1377 (void) fprintf(stderr, gettext("failed to invalidate "
1378 "cache for %s: %s\n"), vdev, strerror(errno));
1380 if (zpool_read_label(fd, &config, NULL) != 0) {
1381 (void) fprintf(stderr,
1382 gettext("failed to read label from %s\n"), vdev);
1383 ret = 1;
1384 goto errout;
1386 nvlist_free(config);
1388 ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1389 if (ret != 0) {
1390 (void) fprintf(stderr,
1391 gettext("failed to check state for %s\n"), vdev);
1392 ret = 1;
1393 goto errout;
1396 if (!inuse)
1397 goto wipe_label;
1399 switch (state) {
1400 default:
1401 case POOL_STATE_ACTIVE:
1402 case POOL_STATE_SPARE:
1403 case POOL_STATE_L2CACHE:
1405 * We allow the user to call 'zpool offline -f'
1406 * on an offlined disk in an active pool. We can check if
1407 * the disk is online by calling vdev_is_active().
1409 if (force && !vdev_is_active(vdev))
1410 break;
1412 (void) fprintf(stderr, gettext(
1413 "%s is a member (%s) of pool \"%s\""),
1414 vdev, zpool_pool_state_to_name(state), name);
1416 if (force) {
1417 (void) fprintf(stderr, gettext(
1418 ". Offline the disk first to clear its label."));
1420 printf("\n");
1421 ret = 1;
1422 goto errout;
1424 case POOL_STATE_EXPORTED:
1425 if (force)
1426 break;
1427 (void) fprintf(stderr, gettext(
1428 "use '-f' to override the following error:\n"
1429 "%s is a member of exported pool \"%s\"\n"),
1430 vdev, name);
1431 ret = 1;
1432 goto errout;
1434 case POOL_STATE_POTENTIALLY_ACTIVE:
1435 if (force)
1436 break;
1437 (void) fprintf(stderr, gettext(
1438 "use '-f' to override the following error:\n"
1439 "%s is a member of potentially active pool \"%s\"\n"),
1440 vdev, name);
1441 ret = 1;
1442 goto errout;
1444 case POOL_STATE_DESTROYED:
1445 /* inuse should never be set for a destroyed pool */
1446 assert(0);
1447 break;
1450 wipe_label:
1451 ret = zpool_clear_label(fd);
1452 if (ret != 0) {
1453 (void) fprintf(stderr,
1454 gettext("failed to clear label for %s\n"), vdev);
1457 errout:
1458 free(name);
1459 (void) close(fd);
1461 return (ret);
1465 * zpool create [-fnd] [-o property=value] ...
1466 * [-O file-system-property=value] ...
1467 * [-R root] [-m mountpoint] <pool> <dev> ...
1469 * -f Force creation, even if devices appear in use
1470 * -n Do not create the pool, but display the resulting layout if it
1471 * were to be created.
1472 * -R Create a pool under an alternate root
1473 * -m Set default mountpoint for the root dataset. By default it's
1474 * '/<pool>'
1475 * -o Set property=value.
1476 * -o Set feature@feature=enabled|disabled.
1477 * -d Don't automatically enable all supported pool features
1478 * (individual features can be enabled with -o).
1479 * -O Set fsproperty=value in the pool's root file system
1481 * Creates the named pool according to the given vdev specification. The
1482 * bulk of the vdev processing is done in make_root_vdev() in zpool_vdev.c.
1483 * Once we get the nvlist back from make_root_vdev(), we either print out the
1484 * contents (if '-n' was specified), or pass it to libzfs to do the creation.
1487 zpool_do_create(int argc, char **argv)
1489 boolean_t force = B_FALSE;
1490 boolean_t dryrun = B_FALSE;
1491 boolean_t enable_pool_features = B_TRUE;
1493 int c;
1494 nvlist_t *nvroot = NULL;
1495 char *poolname;
1496 char *tname = NULL;
1497 int ret = 1;
1498 char *altroot = NULL;
1499 char *compat = NULL;
1500 char *mountpoint = NULL;
1501 nvlist_t *fsprops = NULL;
1502 nvlist_t *props = NULL;
1503 char *propval;
1505 /* check options */
1506 while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
1507 switch (c) {
1508 case 'f':
1509 force = B_TRUE;
1510 break;
1511 case 'n':
1512 dryrun = B_TRUE;
1513 break;
1514 case 'd':
1515 enable_pool_features = B_FALSE;
1516 break;
1517 case 'R':
1518 altroot = optarg;
1519 if (add_prop_list(zpool_prop_to_name(
1520 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
1521 goto errout;
1522 if (add_prop_list_default(zpool_prop_to_name(
1523 ZPOOL_PROP_CACHEFILE), "none", &props))
1524 goto errout;
1525 break;
1526 case 'm':
1527 /* Equivalent to -O mountpoint=optarg */
1528 mountpoint = optarg;
1529 break;
1530 case 'o':
1531 if ((propval = strchr(optarg, '=')) == NULL) {
1532 (void) fprintf(stderr, gettext("missing "
1533 "'=' for -o option\n"));
1534 goto errout;
1536 *propval = '\0';
1537 propval++;
1539 if (add_prop_list(optarg, propval, &props, B_TRUE))
1540 goto errout;
1543 * If the user is creating a pool that doesn't support
1544 * feature flags, don't enable any features.
1546 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
1547 char *end;
1548 u_longlong_t ver;
1550 ver = strtoull(propval, &end, 10);
1551 if (*end == '\0' &&
1552 ver < SPA_VERSION_FEATURES) {
1553 enable_pool_features = B_FALSE;
1556 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
1557 altroot = propval;
1558 if (zpool_name_to_prop(optarg) ==
1559 ZPOOL_PROP_COMPATIBILITY)
1560 compat = propval;
1561 break;
1562 case 'O':
1563 if ((propval = strchr(optarg, '=')) == NULL) {
1564 (void) fprintf(stderr, gettext("missing "
1565 "'=' for -O option\n"));
1566 goto errout;
1568 *propval = '\0';
1569 propval++;
1572 * Mountpoints are checked and then added later.
1573 * Uniquely among properties, they can be specified
1574 * more than once, to avoid conflict with -m.
1576 if (0 == strcmp(optarg,
1577 zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
1578 mountpoint = propval;
1579 } else if (add_prop_list(optarg, propval, &fsprops,
1580 B_FALSE)) {
1581 goto errout;
1583 break;
1584 case 't':
1586 * Sanity check temporary pool name.
1588 if (strchr(optarg, '/') != NULL) {
1589 (void) fprintf(stderr, gettext("cannot create "
1590 "'%s': invalid character '/' in temporary "
1591 "name\n"), optarg);
1592 (void) fprintf(stderr, gettext("use 'zfs "
1593 "create' to create a dataset\n"));
1594 goto errout;
1597 if (add_prop_list(zpool_prop_to_name(
1598 ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
1599 goto errout;
1600 if (add_prop_list_default(zpool_prop_to_name(
1601 ZPOOL_PROP_CACHEFILE), "none", &props))
1602 goto errout;
1603 tname = optarg;
1604 break;
1605 case ':':
1606 (void) fprintf(stderr, gettext("missing argument for "
1607 "'%c' option\n"), optopt);
1608 goto badusage;
1609 case '?':
1610 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1611 optopt);
1612 goto badusage;
1616 argc -= optind;
1617 argv += optind;
1619 /* get pool name and check number of arguments */
1620 if (argc < 1) {
1621 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1622 goto badusage;
1624 if (argc < 2) {
1625 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1626 goto badusage;
1629 poolname = argv[0];
1632 * As a special case, check for use of '/' in the name, and direct the
1633 * user to use 'zfs create' instead.
1635 if (strchr(poolname, '/') != NULL) {
1636 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
1637 "character '/' in pool name\n"), poolname);
1638 (void) fprintf(stderr, gettext("use 'zfs create' to "
1639 "create a dataset\n"));
1640 goto errout;
1643 /* pass off to make_root_vdev for bulk processing */
1644 nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
1645 argc - 1, argv + 1);
1646 if (nvroot == NULL)
1647 goto errout;
1649 /* make_root_vdev() allows 0 toplevel children if there are spares */
1650 if (!zfs_allocatable_devs(nvroot)) {
1651 (void) fprintf(stderr, gettext("invalid vdev "
1652 "specification: at least one toplevel vdev must be "
1653 "specified\n"));
1654 goto errout;
1657 if (altroot != NULL && altroot[0] != '/') {
1658 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
1659 "must be an absolute path\n"), altroot);
1660 goto errout;
1664 * Check the validity of the mountpoint and direct the user to use the
1665 * '-m' mountpoint option if it looks like its in use.
1667 if (mountpoint == NULL ||
1668 (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
1669 strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
1670 char buf[MAXPATHLEN];
1671 DIR *dirp;
1673 if (mountpoint && mountpoint[0] != '/') {
1674 (void) fprintf(stderr, gettext("invalid mountpoint "
1675 "'%s': must be an absolute path, 'legacy', or "
1676 "'none'\n"), mountpoint);
1677 goto errout;
1680 if (mountpoint == NULL) {
1681 if (altroot != NULL)
1682 (void) snprintf(buf, sizeof (buf), "%s/%s",
1683 altroot, poolname);
1684 else
1685 (void) snprintf(buf, sizeof (buf), "/%s",
1686 poolname);
1687 } else {
1688 if (altroot != NULL)
1689 (void) snprintf(buf, sizeof (buf), "%s%s",
1690 altroot, mountpoint);
1691 else
1692 (void) snprintf(buf, sizeof (buf), "%s",
1693 mountpoint);
1696 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
1697 (void) fprintf(stderr, gettext("mountpoint '%s' : "
1698 "%s\n"), buf, strerror(errno));
1699 (void) fprintf(stderr, gettext("use '-m' "
1700 "option to provide a different default\n"));
1701 goto errout;
1702 } else if (dirp) {
1703 int count = 0;
1705 while (count < 3 && readdir(dirp) != NULL)
1706 count++;
1707 (void) closedir(dirp);
1709 if (count > 2) {
1710 (void) fprintf(stderr, gettext("mountpoint "
1711 "'%s' exists and is not empty\n"), buf);
1712 (void) fprintf(stderr, gettext("use '-m' "
1713 "option to provide a "
1714 "different default\n"));
1715 goto errout;
1721 * Now that the mountpoint's validity has been checked, ensure that
1722 * the property is set appropriately prior to creating the pool.
1724 if (mountpoint != NULL) {
1725 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
1726 mountpoint, &fsprops, B_FALSE);
1727 if (ret != 0)
1728 goto errout;
1731 ret = 1;
1732 if (dryrun) {
1734 * For a dry run invocation, print out a basic message and run
1735 * through all the vdevs in the list and print out in an
1736 * appropriate hierarchy.
1738 (void) printf(gettext("would create '%s' with the "
1739 "following layout:\n\n"), poolname);
1741 print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
1742 print_vdev_tree(NULL, "dedup", nvroot, 0,
1743 VDEV_ALLOC_BIAS_DEDUP, 0);
1744 print_vdev_tree(NULL, "special", nvroot, 0,
1745 VDEV_ALLOC_BIAS_SPECIAL, 0);
1746 print_vdev_tree(NULL, "logs", nvroot, 0,
1747 VDEV_ALLOC_BIAS_LOG, 0);
1748 print_cache_list(nvroot, 0);
1749 print_spare_list(nvroot, 0);
1751 ret = 0;
1752 } else {
1754 * Load in feature set.
1755 * Note: if compatibility property not given, we'll have
1756 * NULL, which means 'all features'.
1758 boolean_t requested_features[SPA_FEATURES];
1759 if (zpool_do_load_compat(compat, requested_features) !=
1760 ZPOOL_COMPATIBILITY_OK)
1761 goto errout;
1764 * props contains list of features to enable.
1765 * For each feature:
1766 * - remove it if feature@name=disabled
1767 * - leave it there if feature@name=enabled
1768 * - add it if:
1769 * - enable_pool_features (ie: no '-d' or '-o version')
1770 * - it's supported by the kernel module
1771 * - it's in the requested feature set
1772 * - warn if it's enabled but not in compat
1774 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
1775 char propname[MAXPATHLEN];
1776 const char *propval;
1777 zfeature_info_t *feat = &spa_feature_table[i];
1779 (void) snprintf(propname, sizeof (propname),
1780 "feature@%s", feat->fi_uname);
1782 if (!nvlist_lookup_string(props, propname, &propval)) {
1783 if (strcmp(propval,
1784 ZFS_FEATURE_DISABLED) == 0) {
1785 (void) nvlist_remove_all(props,
1786 propname);
1787 } else if (strcmp(propval,
1788 ZFS_FEATURE_ENABLED) == 0 &&
1789 !requested_features[i]) {
1790 (void) fprintf(stderr, gettext(
1791 "Warning: feature \"%s\" enabled "
1792 "but is not in specified "
1793 "'compatibility' feature set.\n"),
1794 feat->fi_uname);
1796 } else if (
1797 enable_pool_features &&
1798 feat->fi_zfs_mod_supported &&
1799 requested_features[i]) {
1800 ret = add_prop_list(propname,
1801 ZFS_FEATURE_ENABLED, &props, B_TRUE);
1802 if (ret != 0)
1803 goto errout;
1807 ret = 1;
1808 if (zpool_create(g_zfs, poolname,
1809 nvroot, props, fsprops) == 0) {
1810 zfs_handle_t *pool = zfs_open(g_zfs,
1811 tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
1812 if (pool != NULL) {
1813 if (zfs_mount(pool, NULL, 0) == 0) {
1814 ret = zfs_share(pool, NULL);
1815 zfs_commit_shares(NULL);
1817 zfs_close(pool);
1819 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
1820 (void) fprintf(stderr, gettext("pool name may have "
1821 "been omitted\n"));
1825 errout:
1826 nvlist_free(nvroot);
1827 nvlist_free(fsprops);
1828 nvlist_free(props);
1829 return (ret);
1830 badusage:
1831 nvlist_free(fsprops);
1832 nvlist_free(props);
1833 usage(B_FALSE);
1834 return (2);
1838 * zpool destroy <pool>
1840 * -f Forcefully unmount any datasets
1842 * Destroy the given pool. Automatically unmounts any datasets in the pool.
1845 zpool_do_destroy(int argc, char **argv)
1847 boolean_t force = B_FALSE;
1848 int c;
1849 char *pool;
1850 zpool_handle_t *zhp;
1851 int ret;
1853 /* check options */
1854 while ((c = getopt(argc, argv, "f")) != -1) {
1855 switch (c) {
1856 case 'f':
1857 force = B_TRUE;
1858 break;
1859 case '?':
1860 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1861 optopt);
1862 usage(B_FALSE);
1866 argc -= optind;
1867 argv += optind;
1869 /* check arguments */
1870 if (argc < 1) {
1871 (void) fprintf(stderr, gettext("missing pool argument\n"));
1872 usage(B_FALSE);
1874 if (argc > 1) {
1875 (void) fprintf(stderr, gettext("too many arguments\n"));
1876 usage(B_FALSE);
1879 pool = argv[0];
1881 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
1883 * As a special case, check for use of '/' in the name, and
1884 * direct the user to use 'zfs destroy' instead.
1886 if (strchr(pool, '/') != NULL)
1887 (void) fprintf(stderr, gettext("use 'zfs destroy' to "
1888 "destroy a dataset\n"));
1889 return (1);
1892 if (zpool_disable_datasets(zhp, force) != 0) {
1893 (void) fprintf(stderr, gettext("could not destroy '%s': "
1894 "could not unmount datasets\n"), zpool_get_name(zhp));
1895 zpool_close(zhp);
1896 return (1);
1899 /* The history must be logged as part of the export */
1900 log_history = B_FALSE;
1902 ret = (zpool_destroy(zhp, history_str) != 0);
1904 zpool_close(zhp);
1906 return (ret);
1909 typedef struct export_cbdata {
1910 boolean_t force;
1911 boolean_t hardforce;
1912 } export_cbdata_t;
1915 * Export one pool
1917 static int
1918 zpool_export_one(zpool_handle_t *zhp, void *data)
1920 export_cbdata_t *cb = data;
1922 if (zpool_disable_datasets(zhp, cb->force) != 0)
1923 return (1);
1925 /* The history must be logged as part of the export */
1926 log_history = B_FALSE;
1928 if (cb->hardforce) {
1929 if (zpool_export_force(zhp, history_str) != 0)
1930 return (1);
1931 } else if (zpool_export(zhp, cb->force, history_str) != 0) {
1932 return (1);
1935 return (0);
1939 * zpool export [-f] <pool> ...
1941 * -a Export all pools
1942 * -f Forcefully unmount datasets
1944 * Export the given pools. By default, the command will attempt to cleanly
1945 * unmount any active datasets within the pool. If the '-f' flag is specified,
1946 * then the datasets will be forcefully unmounted.
1949 zpool_do_export(int argc, char **argv)
1951 export_cbdata_t cb;
1952 boolean_t do_all = B_FALSE;
1953 boolean_t force = B_FALSE;
1954 boolean_t hardforce = B_FALSE;
1955 int c, ret;
1957 /* check options */
1958 while ((c = getopt(argc, argv, "afF")) != -1) {
1959 switch (c) {
1960 case 'a':
1961 do_all = B_TRUE;
1962 break;
1963 case 'f':
1964 force = B_TRUE;
1965 break;
1966 case 'F':
1967 hardforce = B_TRUE;
1968 break;
1969 case '?':
1970 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1971 optopt);
1972 usage(B_FALSE);
1976 cb.force = force;
1977 cb.hardforce = hardforce;
1978 argc -= optind;
1979 argv += optind;
1981 if (do_all) {
1982 if (argc != 0) {
1983 (void) fprintf(stderr, gettext("too many arguments\n"));
1984 usage(B_FALSE);
1987 return (for_each_pool(argc, argv, B_TRUE, NULL,
1988 ZFS_TYPE_POOL, B_FALSE, zpool_export_one, &cb));
1991 /* check arguments */
1992 if (argc < 1) {
1993 (void) fprintf(stderr, gettext("missing pool argument\n"));
1994 usage(B_FALSE);
1997 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
1998 B_FALSE, zpool_export_one, &cb);
2000 return (ret);
2004 * Given a vdev configuration, determine the maximum width needed for the device
2005 * name column.
2007 static int
2008 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
2009 int name_flags)
2011 static const char *const subtypes[] =
2012 {ZPOOL_CONFIG_SPARES, ZPOOL_CONFIG_L2CACHE, ZPOOL_CONFIG_CHILDREN};
2014 char *name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
2015 max = MAX(strlen(name) + depth, max);
2016 free(name);
2018 nvlist_t **child;
2019 uint_t children;
2020 for (size_t i = 0; i < ARRAY_SIZE(subtypes); ++i)
2021 if (nvlist_lookup_nvlist_array(nv, subtypes[i],
2022 &child, &children) == 0)
2023 for (uint_t c = 0; c < children; ++c)
2024 max = MAX(max_width(zhp, child[c], depth + 2,
2025 max, name_flags), max);
2027 return (max);
2030 typedef struct spare_cbdata {
2031 uint64_t cb_guid;
2032 zpool_handle_t *cb_zhp;
2033 } spare_cbdata_t;
2035 static boolean_t
2036 find_vdev(nvlist_t *nv, uint64_t search)
2038 uint64_t guid;
2039 nvlist_t **child;
2040 uint_t c, children;
2042 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
2043 search == guid)
2044 return (B_TRUE);
2046 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2047 &child, &children) == 0) {
2048 for (c = 0; c < children; c++)
2049 if (find_vdev(child[c], search))
2050 return (B_TRUE);
2053 return (B_FALSE);
2056 static int
2057 find_spare(zpool_handle_t *zhp, void *data)
2059 spare_cbdata_t *cbp = data;
2060 nvlist_t *config, *nvroot;
2062 config = zpool_get_config(zhp, NULL);
2063 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2064 &nvroot) == 0);
2066 if (find_vdev(nvroot, cbp->cb_guid)) {
2067 cbp->cb_zhp = zhp;
2068 return (1);
2071 zpool_close(zhp);
2072 return (0);
2075 typedef struct status_cbdata {
2076 int cb_count;
2077 int cb_name_flags;
2078 int cb_namewidth;
2079 boolean_t cb_allpools;
2080 boolean_t cb_verbose;
2081 boolean_t cb_literal;
2082 boolean_t cb_explain;
2083 boolean_t cb_first;
2084 boolean_t cb_dedup_stats;
2085 boolean_t cb_print_status;
2086 boolean_t cb_print_slow_ios;
2087 boolean_t cb_print_vdev_init;
2088 boolean_t cb_print_vdev_trim;
2089 vdev_cmd_data_list_t *vcdl;
2090 } status_cbdata_t;
2092 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
2093 static boolean_t
2094 is_blank_str(const char *str)
2096 for (; str != NULL && *str != '\0'; ++str)
2097 if (!isblank(*str))
2098 return (B_FALSE);
2099 return (B_TRUE);
2102 /* Print command output lines for specific vdev in a specific pool */
2103 static void
2104 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path)
2106 vdev_cmd_data_t *data;
2107 int i, j;
2108 const char *val;
2110 for (i = 0; i < vcdl->count; i++) {
2111 if ((strcmp(vcdl->data[i].path, path) != 0) ||
2112 (strcmp(vcdl->data[i].pool, pool) != 0)) {
2113 /* Not the vdev we're looking for */
2114 continue;
2117 data = &vcdl->data[i];
2118 /* Print out all the output values for this vdev */
2119 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2120 val = NULL;
2121 /* Does this vdev have values for this column? */
2122 for (int k = 0; k < data->cols_cnt; k++) {
2123 if (strcmp(data->cols[k],
2124 vcdl->uniq_cols[j]) == 0) {
2125 /* yes it does, record the value */
2126 val = data->lines[k];
2127 break;
2131 * Mark empty values with dashes to make output
2132 * awk-able.
2134 if (val == NULL || is_blank_str(val))
2135 val = "-";
2137 printf("%*s", vcdl->uniq_cols_width[j], val);
2138 if (j < vcdl->uniq_cols_cnt - 1)
2139 fputs(" ", stdout);
2142 /* Print out any values that aren't in a column at the end */
2143 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2144 /* Did we have any columns? If so print a spacer. */
2145 if (vcdl->uniq_cols_cnt > 0)
2146 fputs(" ", stdout);
2148 val = data->lines[j];
2149 fputs(val ?: "", stdout);
2151 break;
2156 * Print vdev initialization status for leaves
2158 static void
2159 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
2161 if (verbose) {
2162 if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
2163 vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
2164 vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
2165 !vs->vs_scan_removing) {
2166 char zbuf[1024];
2167 char tbuf[256];
2168 struct tm zaction_ts;
2170 time_t t = vs->vs_initialize_action_time;
2171 int initialize_pct = 100;
2172 if (vs->vs_initialize_state !=
2173 VDEV_INITIALIZE_COMPLETE) {
2174 initialize_pct = (vs->vs_initialize_bytes_done *
2175 100 / (vs->vs_initialize_bytes_est + 1));
2178 (void) localtime_r(&t, &zaction_ts);
2179 (void) strftime(tbuf, sizeof (tbuf), "%c", &zaction_ts);
2181 switch (vs->vs_initialize_state) {
2182 case VDEV_INITIALIZE_SUSPENDED:
2183 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2184 gettext("suspended, started at"), tbuf);
2185 break;
2186 case VDEV_INITIALIZE_ACTIVE:
2187 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2188 gettext("started at"), tbuf);
2189 break;
2190 case VDEV_INITIALIZE_COMPLETE:
2191 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2192 gettext("completed at"), tbuf);
2193 break;
2196 (void) printf(gettext(" (%d%% initialized%s)"),
2197 initialize_pct, zbuf);
2198 } else {
2199 (void) printf(gettext(" (uninitialized)"));
2201 } else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
2202 (void) printf(gettext(" (initializing)"));
2207 * Print vdev TRIM status for leaves
2209 static void
2210 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
2212 if (verbose) {
2213 if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
2214 vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
2215 vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
2216 !vs->vs_scan_removing) {
2217 char zbuf[1024];
2218 char tbuf[256];
2219 struct tm zaction_ts;
2221 time_t t = vs->vs_trim_action_time;
2222 int trim_pct = 100;
2223 if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
2224 trim_pct = (vs->vs_trim_bytes_done *
2225 100 / (vs->vs_trim_bytes_est + 1));
2228 (void) localtime_r(&t, &zaction_ts);
2229 (void) strftime(tbuf, sizeof (tbuf), "%c", &zaction_ts);
2231 switch (vs->vs_trim_state) {
2232 case VDEV_TRIM_SUSPENDED:
2233 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2234 gettext("suspended, started at"), tbuf);
2235 break;
2236 case VDEV_TRIM_ACTIVE:
2237 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2238 gettext("started at"), tbuf);
2239 break;
2240 case VDEV_TRIM_COMPLETE:
2241 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2242 gettext("completed at"), tbuf);
2243 break;
2246 (void) printf(gettext(" (%d%% trimmed%s)"),
2247 trim_pct, zbuf);
2248 } else if (vs->vs_trim_notsup) {
2249 (void) printf(gettext(" (trim unsupported)"));
2250 } else {
2251 (void) printf(gettext(" (untrimmed)"));
2253 } else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
2254 (void) printf(gettext(" (trimming)"));
2259 * Return the color associated with a health string. This includes returning
2260 * NULL for no color change.
2262 static const char *
2263 health_str_to_color(const char *health)
2265 if (strcmp(health, gettext("FAULTED")) == 0 ||
2266 strcmp(health, gettext("SUSPENDED")) == 0 ||
2267 strcmp(health, gettext("UNAVAIL")) == 0) {
2268 return (ANSI_RED);
2271 if (strcmp(health, gettext("OFFLINE")) == 0 ||
2272 strcmp(health, gettext("DEGRADED")) == 0 ||
2273 strcmp(health, gettext("REMOVED")) == 0) {
2274 return (ANSI_YELLOW);
2277 return (NULL);
2281 * Print out configuration state as requested by status_callback.
2283 static void
2284 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
2285 nvlist_t *nv, int depth, boolean_t isspare, vdev_rebuild_stat_t *vrs)
2287 nvlist_t **child, *root;
2288 uint_t c, i, vsc, children;
2289 pool_scan_stat_t *ps = NULL;
2290 vdev_stat_t *vs;
2291 char rbuf[6], wbuf[6], cbuf[6];
2292 char *vname;
2293 uint64_t notpresent;
2294 spare_cbdata_t spare_cb;
2295 const char *state;
2296 const char *type;
2297 const char *path = NULL;
2298 const char *rcolor = NULL, *wcolor = NULL, *ccolor = NULL;
2300 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2301 &child, &children) != 0)
2302 children = 0;
2304 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2305 (uint64_t **)&vs, &vsc) == 0);
2307 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2309 if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2310 return;
2312 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2314 if (isspare) {
2316 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
2317 * online drives.
2319 if (vs->vs_aux == VDEV_AUX_SPARED)
2320 state = gettext("INUSE");
2321 else if (vs->vs_state == VDEV_STATE_HEALTHY)
2322 state = gettext("AVAIL");
2325 printf_color(health_str_to_color(state),
2326 "\t%*s%-*s %-8s", depth, "", cb->cb_namewidth - depth,
2327 name, state);
2329 if (!isspare) {
2330 if (vs->vs_read_errors)
2331 rcolor = ANSI_RED;
2333 if (vs->vs_write_errors)
2334 wcolor = ANSI_RED;
2336 if (vs->vs_checksum_errors)
2337 ccolor = ANSI_RED;
2339 if (cb->cb_literal) {
2340 fputc(' ', stdout);
2341 printf_color(rcolor, "%5llu",
2342 (u_longlong_t)vs->vs_read_errors);
2343 fputc(' ', stdout);
2344 printf_color(wcolor, "%5llu",
2345 (u_longlong_t)vs->vs_write_errors);
2346 fputc(' ', stdout);
2347 printf_color(ccolor, "%5llu",
2348 (u_longlong_t)vs->vs_checksum_errors);
2349 } else {
2350 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
2351 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
2352 zfs_nicenum(vs->vs_checksum_errors, cbuf,
2353 sizeof (cbuf));
2354 fputc(' ', stdout);
2355 printf_color(rcolor, "%5s", rbuf);
2356 fputc(' ', stdout);
2357 printf_color(wcolor, "%5s", wbuf);
2358 fputc(' ', stdout);
2359 printf_color(ccolor, "%5s", cbuf);
2361 if (cb->cb_print_slow_ios) {
2362 if (children == 0) {
2363 /* Only leafs vdevs have slow IOs */
2364 zfs_nicenum(vs->vs_slow_ios, rbuf,
2365 sizeof (rbuf));
2366 } else {
2367 snprintf(rbuf, sizeof (rbuf), "-");
2370 if (cb->cb_literal)
2371 printf(" %5llu", (u_longlong_t)vs->vs_slow_ios);
2372 else
2373 printf(" %5s", rbuf);
2377 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
2378 &notpresent) == 0) {
2379 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
2380 (void) printf(" %s %s", gettext("was"), path);
2381 } else if (vs->vs_aux != 0) {
2382 (void) printf(" ");
2383 color_start(ANSI_RED);
2384 switch (vs->vs_aux) {
2385 case VDEV_AUX_OPEN_FAILED:
2386 (void) printf(gettext("cannot open"));
2387 break;
2389 case VDEV_AUX_BAD_GUID_SUM:
2390 (void) printf(gettext("missing device"));
2391 break;
2393 case VDEV_AUX_NO_REPLICAS:
2394 (void) printf(gettext("insufficient replicas"));
2395 break;
2397 case VDEV_AUX_VERSION_NEWER:
2398 (void) printf(gettext("newer version"));
2399 break;
2401 case VDEV_AUX_UNSUP_FEAT:
2402 (void) printf(gettext("unsupported feature(s)"));
2403 break;
2405 case VDEV_AUX_ASHIFT_TOO_BIG:
2406 (void) printf(gettext("unsupported minimum blocksize"));
2407 break;
2409 case VDEV_AUX_SPARED:
2410 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
2411 &spare_cb.cb_guid) == 0);
2412 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
2413 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
2414 zpool_get_name(zhp)) == 0)
2415 (void) printf(gettext("currently in "
2416 "use"));
2417 else
2418 (void) printf(gettext("in use by "
2419 "pool '%s'"),
2420 zpool_get_name(spare_cb.cb_zhp));
2421 zpool_close(spare_cb.cb_zhp);
2422 } else {
2423 (void) printf(gettext("currently in use"));
2425 break;
2427 case VDEV_AUX_ERR_EXCEEDED:
2428 (void) printf(gettext("too many errors"));
2429 break;
2431 case VDEV_AUX_IO_FAILURE:
2432 (void) printf(gettext("experienced I/O failures"));
2433 break;
2435 case VDEV_AUX_BAD_LOG:
2436 (void) printf(gettext("bad intent log"));
2437 break;
2439 case VDEV_AUX_EXTERNAL:
2440 (void) printf(gettext("external device fault"));
2441 break;
2443 case VDEV_AUX_SPLIT_POOL:
2444 (void) printf(gettext("split into new pool"));
2445 break;
2447 case VDEV_AUX_ACTIVE:
2448 (void) printf(gettext("currently in use"));
2449 break;
2451 case VDEV_AUX_CHILDREN_OFFLINE:
2452 (void) printf(gettext("all children offline"));
2453 break;
2455 case VDEV_AUX_BAD_LABEL:
2456 (void) printf(gettext("invalid label"));
2457 break;
2459 default:
2460 (void) printf(gettext("corrupted data"));
2461 break;
2463 color_end();
2464 } else if (children == 0 && !isspare &&
2465 getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
2466 VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
2467 vs->vs_configured_ashift < vs->vs_physical_ashift) {
2468 (void) printf(
2469 gettext(" block size: %dB configured, %dB native"),
2470 1 << vs->vs_configured_ashift, 1 << vs->vs_physical_ashift);
2473 if (vs->vs_scan_removing != 0) {
2474 (void) printf(gettext(" (removing)"));
2475 } else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
2476 (void) printf(gettext(" (non-allocating)"));
2479 /* The root vdev has the scrub/resilver stats */
2480 root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
2481 ZPOOL_CONFIG_VDEV_TREE);
2482 (void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
2483 (uint64_t **)&ps, &c);
2486 * If you force fault a drive that's resilvering, its scan stats can
2487 * get frozen in time, giving the false impression that it's
2488 * being resilvered. That's why we check the state to see if the vdev
2489 * is healthy before reporting "resilvering" or "repairing".
2491 if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0 &&
2492 vs->vs_state == VDEV_STATE_HEALTHY) {
2493 if (vs->vs_scan_processed != 0) {
2494 (void) printf(gettext(" (%s)"),
2495 (ps->pss_func == POOL_SCAN_RESILVER) ?
2496 "resilvering" : "repairing");
2497 } else if (vs->vs_resilver_deferred) {
2498 (void) printf(gettext(" (awaiting resilver)"));
2502 /* The top-level vdevs have the rebuild stats */
2503 if (vrs != NULL && vrs->vrs_state == VDEV_REBUILD_ACTIVE &&
2504 children == 0 && vs->vs_state == VDEV_STATE_HEALTHY) {
2505 if (vs->vs_rebuild_processed != 0) {
2506 (void) printf(gettext(" (resilvering)"));
2510 if (cb->vcdl != NULL) {
2511 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
2512 printf(" ");
2513 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
2517 /* Display vdev initialization and trim status for leaves. */
2518 if (children == 0) {
2519 print_status_initialize(vs, cb->cb_print_vdev_init);
2520 print_status_trim(vs, cb->cb_print_vdev_trim);
2523 (void) printf("\n");
2525 for (c = 0; c < children; c++) {
2526 uint64_t islog = B_FALSE, ishole = B_FALSE;
2528 /* Don't print logs or holes here */
2529 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2530 &islog);
2531 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
2532 &ishole);
2533 if (islog || ishole)
2534 continue;
2535 /* Only print normal classes here */
2536 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
2537 continue;
2539 /* Provide vdev_rebuild_stats to children if available */
2540 if (vrs == NULL) {
2541 (void) nvlist_lookup_uint64_array(nv,
2542 ZPOOL_CONFIG_REBUILD_STATS,
2543 (uint64_t **)&vrs, &i);
2546 vname = zpool_vdev_name(g_zfs, zhp, child[c],
2547 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2548 print_status_config(zhp, cb, vname, child[c], depth + 2,
2549 isspare, vrs);
2550 free(vname);
2555 * Print the configuration of an exported pool. Iterate over all vdevs in the
2556 * pool, printing out the name and status for each one.
2558 static void
2559 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
2560 int depth)
2562 nvlist_t **child;
2563 uint_t c, children;
2564 vdev_stat_t *vs;
2565 const char *type;
2566 char *vname;
2568 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2569 if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
2570 strcmp(type, VDEV_TYPE_HOLE) == 0)
2571 return;
2573 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2574 (uint64_t **)&vs, &c) == 0);
2576 (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
2577 (void) printf(" %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
2579 if (vs->vs_aux != 0) {
2580 (void) printf(" ");
2582 switch (vs->vs_aux) {
2583 case VDEV_AUX_OPEN_FAILED:
2584 (void) printf(gettext("cannot open"));
2585 break;
2587 case VDEV_AUX_BAD_GUID_SUM:
2588 (void) printf(gettext("missing device"));
2589 break;
2591 case VDEV_AUX_NO_REPLICAS:
2592 (void) printf(gettext("insufficient replicas"));
2593 break;
2595 case VDEV_AUX_VERSION_NEWER:
2596 (void) printf(gettext("newer version"));
2597 break;
2599 case VDEV_AUX_UNSUP_FEAT:
2600 (void) printf(gettext("unsupported feature(s)"));
2601 break;
2603 case VDEV_AUX_ERR_EXCEEDED:
2604 (void) printf(gettext("too many errors"));
2605 break;
2607 case VDEV_AUX_ACTIVE:
2608 (void) printf(gettext("currently in use"));
2609 break;
2611 case VDEV_AUX_CHILDREN_OFFLINE:
2612 (void) printf(gettext("all children offline"));
2613 break;
2615 case VDEV_AUX_BAD_LABEL:
2616 (void) printf(gettext("invalid label"));
2617 break;
2619 default:
2620 (void) printf(gettext("corrupted data"));
2621 break;
2624 (void) printf("\n");
2626 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2627 &child, &children) != 0)
2628 return;
2630 for (c = 0; c < children; c++) {
2631 uint64_t is_log = B_FALSE;
2633 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2634 &is_log);
2635 if (is_log)
2636 continue;
2637 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
2638 continue;
2640 vname = zpool_vdev_name(g_zfs, NULL, child[c],
2641 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2642 print_import_config(cb, vname, child[c], depth + 2);
2643 free(vname);
2646 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2647 &child, &children) == 0) {
2648 (void) printf(gettext("\tcache\n"));
2649 for (c = 0; c < children; c++) {
2650 vname = zpool_vdev_name(g_zfs, NULL, child[c],
2651 cb->cb_name_flags);
2652 (void) printf("\t %s\n", vname);
2653 free(vname);
2657 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2658 &child, &children) == 0) {
2659 (void) printf(gettext("\tspares\n"));
2660 for (c = 0; c < children; c++) {
2661 vname = zpool_vdev_name(g_zfs, NULL, child[c],
2662 cb->cb_name_flags);
2663 (void) printf("\t %s\n", vname);
2664 free(vname);
2670 * Print specialized class vdevs.
2672 * These are recorded as top level vdevs in the main pool child array
2673 * but with "is_log" set to 1 or an "alloc_bias" string. We use either
2674 * print_status_config() or print_import_config() to print the top level
2675 * class vdevs then any of their children (eg mirrored slogs) are printed
2676 * recursively - which works because only the top level vdev is marked.
2678 static void
2679 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
2680 const char *class)
2682 uint_t c, children;
2683 nvlist_t **child;
2684 boolean_t printed = B_FALSE;
2686 assert(zhp != NULL || !cb->cb_verbose);
2688 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
2689 &children) != 0)
2690 return;
2692 for (c = 0; c < children; c++) {
2693 uint64_t is_log = B_FALSE;
2694 const char *bias = NULL;
2695 const char *type = NULL;
2697 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2698 &is_log);
2700 if (is_log) {
2701 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
2702 } else {
2703 (void) nvlist_lookup_string(child[c],
2704 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
2705 (void) nvlist_lookup_string(child[c],
2706 ZPOOL_CONFIG_TYPE, &type);
2709 if (bias == NULL || strcmp(bias, class) != 0)
2710 continue;
2711 if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2712 continue;
2714 if (!printed) {
2715 (void) printf("\t%s\t\n", gettext(class));
2716 printed = B_TRUE;
2719 char *name = zpool_vdev_name(g_zfs, zhp, child[c],
2720 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2721 if (cb->cb_print_status)
2722 print_status_config(zhp, cb, name, child[c], 2,
2723 B_FALSE, NULL);
2724 else
2725 print_import_config(cb, name, child[c], 2);
2726 free(name);
2731 * Display the status for the given pool.
2733 static int
2734 show_import(nvlist_t *config, boolean_t report_error)
2736 uint64_t pool_state;
2737 vdev_stat_t *vs;
2738 const char *name;
2739 uint64_t guid;
2740 uint64_t hostid = 0;
2741 const char *msgid;
2742 const char *hostname = "unknown";
2743 nvlist_t *nvroot, *nvinfo;
2744 zpool_status_t reason;
2745 zpool_errata_t errata;
2746 const char *health;
2747 uint_t vsc;
2748 const char *comment;
2749 status_cbdata_t cb = { 0 };
2751 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2752 &name) == 0);
2753 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
2754 &guid) == 0);
2755 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2756 &pool_state) == 0);
2757 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2758 &nvroot) == 0);
2760 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
2761 (uint64_t **)&vs, &vsc) == 0);
2762 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2764 reason = zpool_import_status(config, &msgid, &errata);
2767 * If we're importing using a cachefile, then we won't report any
2768 * errors unless we are in the scan phase of the import.
2770 if (reason != ZPOOL_STATUS_OK && !report_error)
2771 return (reason);
2773 (void) printf(gettext(" pool: %s\n"), name);
2774 (void) printf(gettext(" id: %llu\n"), (u_longlong_t)guid);
2775 (void) printf(gettext(" state: %s"), health);
2776 if (pool_state == POOL_STATE_DESTROYED)
2777 (void) printf(gettext(" (DESTROYED)"));
2778 (void) printf("\n");
2780 switch (reason) {
2781 case ZPOOL_STATUS_MISSING_DEV_R:
2782 case ZPOOL_STATUS_MISSING_DEV_NR:
2783 case ZPOOL_STATUS_BAD_GUID_SUM:
2784 printf_color(ANSI_BOLD, gettext("status: "));
2785 printf_color(ANSI_YELLOW, gettext("One or more devices are "
2786 "missing from the system.\n"));
2787 break;
2789 case ZPOOL_STATUS_CORRUPT_LABEL_R:
2790 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
2791 printf_color(ANSI_BOLD, gettext("status: "));
2792 printf_color(ANSI_YELLOW, gettext("One or more devices contains"
2793 " corrupted data.\n"));
2794 break;
2796 case ZPOOL_STATUS_CORRUPT_DATA:
2797 (void) printf(
2798 gettext(" status: The pool data is corrupted.\n"));
2799 break;
2801 case ZPOOL_STATUS_OFFLINE_DEV:
2802 printf_color(ANSI_BOLD, gettext("status: "));
2803 printf_color(ANSI_YELLOW, gettext("One or more devices "
2804 "are offlined.\n"));
2805 break;
2807 case ZPOOL_STATUS_CORRUPT_POOL:
2808 printf_color(ANSI_BOLD, gettext("status: "));
2809 printf_color(ANSI_YELLOW, gettext("The pool metadata is "
2810 "corrupted.\n"));
2811 break;
2813 case ZPOOL_STATUS_VERSION_OLDER:
2814 printf_color(ANSI_BOLD, gettext("status: "));
2815 printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
2816 "a legacy on-disk version.\n"));
2817 break;
2819 case ZPOOL_STATUS_VERSION_NEWER:
2820 printf_color(ANSI_BOLD, gettext("status: "));
2821 printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
2822 "an incompatible version.\n"));
2823 break;
2825 case ZPOOL_STATUS_FEAT_DISABLED:
2826 printf_color(ANSI_BOLD, gettext("status: "));
2827 printf_color(ANSI_YELLOW, gettext("Some supported "
2828 "features are not enabled on the pool.\n\t"
2829 "(Note that they may be intentionally disabled "
2830 "if the\n\t'compatibility' property is set.)\n"));
2831 break;
2833 case ZPOOL_STATUS_COMPATIBILITY_ERR:
2834 printf_color(ANSI_BOLD, gettext("status: "));
2835 printf_color(ANSI_YELLOW, gettext("Error reading or parsing "
2836 "the file(s) indicated by the 'compatibility'\n"
2837 "property.\n"));
2838 break;
2840 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
2841 printf_color(ANSI_BOLD, gettext("status: "));
2842 printf_color(ANSI_YELLOW, gettext("One or more features "
2843 "are enabled on the pool despite not being\n"
2844 "requested by the 'compatibility' property.\n"));
2845 break;
2847 case ZPOOL_STATUS_UNSUP_FEAT_READ:
2848 printf_color(ANSI_BOLD, gettext("status: "));
2849 printf_color(ANSI_YELLOW, gettext("The pool uses the following "
2850 "feature(s) not supported on this system:\n"));
2851 color_start(ANSI_YELLOW);
2852 zpool_print_unsup_feat(config);
2853 color_end();
2854 break;
2856 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2857 printf_color(ANSI_BOLD, gettext("status: "));
2858 printf_color(ANSI_YELLOW, gettext("The pool can only be "
2859 "accessed in read-only mode on this system. It\n\tcannot be"
2860 " accessed in read-write mode because it uses the "
2861 "following\n\tfeature(s) not supported on this system:\n"));
2862 color_start(ANSI_YELLOW);
2863 zpool_print_unsup_feat(config);
2864 color_end();
2865 break;
2867 case ZPOOL_STATUS_HOSTID_ACTIVE:
2868 printf_color(ANSI_BOLD, gettext("status: "));
2869 printf_color(ANSI_YELLOW, gettext("The pool is currently "
2870 "imported by another system.\n"));
2871 break;
2873 case ZPOOL_STATUS_HOSTID_REQUIRED:
2874 printf_color(ANSI_BOLD, gettext("status: "));
2875 printf_color(ANSI_YELLOW, gettext("The pool has the "
2876 "multihost property on. It cannot\n\tbe safely imported "
2877 "when the system hostid is not set.\n"));
2878 break;
2880 case ZPOOL_STATUS_HOSTID_MISMATCH:
2881 printf_color(ANSI_BOLD, gettext("status: "));
2882 printf_color(ANSI_YELLOW, gettext("The pool was last accessed "
2883 "by another system.\n"));
2884 break;
2886 case ZPOOL_STATUS_FAULTED_DEV_R:
2887 case ZPOOL_STATUS_FAULTED_DEV_NR:
2888 printf_color(ANSI_BOLD, gettext("status: "));
2889 printf_color(ANSI_YELLOW, gettext("One or more devices are "
2890 "faulted.\n"));
2891 break;
2893 case ZPOOL_STATUS_BAD_LOG:
2894 printf_color(ANSI_BOLD, gettext("status: "));
2895 printf_color(ANSI_YELLOW, gettext("An intent log record cannot "
2896 "be read.\n"));
2897 break;
2899 case ZPOOL_STATUS_RESILVERING:
2900 case ZPOOL_STATUS_REBUILDING:
2901 printf_color(ANSI_BOLD, gettext("status: "));
2902 printf_color(ANSI_YELLOW, gettext("One or more devices were "
2903 "being resilvered.\n"));
2904 break;
2906 case ZPOOL_STATUS_ERRATA:
2907 printf_color(ANSI_BOLD, gettext("status: "));
2908 printf_color(ANSI_YELLOW, gettext("Errata #%d detected.\n"),
2909 errata);
2910 break;
2912 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
2913 printf_color(ANSI_BOLD, gettext("status: "));
2914 printf_color(ANSI_YELLOW, gettext("One or more devices are "
2915 "configured to use a non-native block size.\n"
2916 "\tExpect reduced performance.\n"));
2917 break;
2919 default:
2921 * No other status can be seen when importing pools.
2923 assert(reason == ZPOOL_STATUS_OK);
2927 * Print out an action according to the overall state of the pool.
2929 if (vs->vs_state == VDEV_STATE_HEALTHY) {
2930 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
2931 reason == ZPOOL_STATUS_FEAT_DISABLED) {
2932 (void) printf(gettext(" action: The pool can be "
2933 "imported using its name or numeric identifier, "
2934 "though\n\tsome features will not be available "
2935 "without an explicit 'zpool upgrade'.\n"));
2936 } else if (reason == ZPOOL_STATUS_COMPATIBILITY_ERR) {
2937 (void) printf(gettext(" action: The pool can be "
2938 "imported using its name or numeric\n\tidentifier, "
2939 "though the file(s) indicated by its "
2940 "'compatibility'\n\tproperty cannot be parsed at "
2941 "this time.\n"));
2942 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
2943 (void) printf(gettext(" action: The pool can be "
2944 "imported using its name or numeric "
2945 "identifier and\n\tthe '-f' flag.\n"));
2946 } else if (reason == ZPOOL_STATUS_ERRATA) {
2947 switch (errata) {
2948 case ZPOOL_ERRATA_NONE:
2949 break;
2951 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
2952 (void) printf(gettext(" action: The pool can "
2953 "be imported using its name or numeric "
2954 "identifier,\n\thowever there is a compat"
2955 "ibility issue which should be corrected"
2956 "\n\tby running 'zpool scrub'\n"));
2957 break;
2959 case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
2960 (void) printf(gettext(" action: The pool can"
2961 "not be imported with this version of ZFS "
2962 "due to\n\tan active asynchronous destroy. "
2963 "Revert to an earlier version\n\tand "
2964 "allow the destroy to complete before "
2965 "updating.\n"));
2966 break;
2968 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
2969 (void) printf(gettext(" action: Existing "
2970 "encrypted datasets contain an on-disk "
2971 "incompatibility, which\n\tneeds to be "
2972 "corrected. Backup these datasets to new "
2973 "encrypted datasets\n\tand destroy the "
2974 "old ones.\n"));
2975 break;
2977 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
2978 (void) printf(gettext(" action: Existing "
2979 "encrypted snapshots and bookmarks contain "
2980 "an on-disk\n\tincompatibility. This may "
2981 "cause on-disk corruption if they are used"
2982 "\n\twith 'zfs recv'. To correct the "
2983 "issue, enable the bookmark_v2 feature.\n\t"
2984 "No additional action is needed if there "
2985 "are no encrypted snapshots or\n\t"
2986 "bookmarks. If preserving the encrypted "
2987 "snapshots and bookmarks is\n\trequired, "
2988 "use a non-raw send to backup and restore "
2989 "them. Alternately,\n\tthey may be removed"
2990 " to resolve the incompatibility.\n"));
2991 break;
2992 default:
2994 * All errata must contain an action message.
2996 assert(0);
2998 } else {
2999 (void) printf(gettext(" action: The pool can be "
3000 "imported using its name or numeric "
3001 "identifier.\n"));
3003 } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
3004 (void) printf(gettext(" action: The pool can be imported "
3005 "despite missing or damaged devices. The\n\tfault "
3006 "tolerance of the pool may be compromised if imported.\n"));
3007 } else {
3008 switch (reason) {
3009 case ZPOOL_STATUS_VERSION_NEWER:
3010 (void) printf(gettext(" action: The pool cannot be "
3011 "imported. Access the pool on a system running "
3012 "newer\n\tsoftware, or recreate the pool from "
3013 "backup.\n"));
3014 break;
3015 case ZPOOL_STATUS_UNSUP_FEAT_READ:
3016 printf_color(ANSI_BOLD, gettext("action: "));
3017 printf_color(ANSI_YELLOW, gettext("The pool cannot be "
3018 "imported. Access the pool on a system that "
3019 "supports\n\tthe required feature(s), or recreate "
3020 "the pool from backup.\n"));
3021 break;
3022 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3023 printf_color(ANSI_BOLD, gettext("action: "));
3024 printf_color(ANSI_YELLOW, gettext("The pool cannot be "
3025 "imported in read-write mode. Import the pool "
3026 "with\n"
3027 "\t\"-o readonly=on\", access the pool on a system "
3028 "that supports the\n\trequired feature(s), or "
3029 "recreate the pool from backup.\n"));
3030 break;
3031 case ZPOOL_STATUS_MISSING_DEV_R:
3032 case ZPOOL_STATUS_MISSING_DEV_NR:
3033 case ZPOOL_STATUS_BAD_GUID_SUM:
3034 (void) printf(gettext(" action: The pool cannot be "
3035 "imported. Attach the missing\n\tdevices and try "
3036 "again.\n"));
3037 break;
3038 case ZPOOL_STATUS_HOSTID_ACTIVE:
3039 VERIFY0(nvlist_lookup_nvlist(config,
3040 ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
3042 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3043 hostname = fnvlist_lookup_string(nvinfo,
3044 ZPOOL_CONFIG_MMP_HOSTNAME);
3046 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3047 hostid = fnvlist_lookup_uint64(nvinfo,
3048 ZPOOL_CONFIG_MMP_HOSTID);
3050 (void) printf(gettext(" action: The pool must be "
3051 "exported from %s (hostid=%"PRIx64")\n\tbefore it "
3052 "can be safely imported.\n"), hostname, hostid);
3053 break;
3054 case ZPOOL_STATUS_HOSTID_REQUIRED:
3055 (void) printf(gettext(" action: Set a unique system "
3056 "hostid with the zgenhostid(8) command.\n"));
3057 break;
3058 default:
3059 (void) printf(gettext(" action: The pool cannot be "
3060 "imported due to damaged devices or data.\n"));
3064 /* Print the comment attached to the pool. */
3065 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
3066 (void) printf(gettext("comment: %s\n"), comment);
3069 * If the state is "closed" or "can't open", and the aux state
3070 * is "corrupt data":
3072 if (((vs->vs_state == VDEV_STATE_CLOSED) ||
3073 (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
3074 (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
3075 if (pool_state == POOL_STATE_DESTROYED)
3076 (void) printf(gettext("\tThe pool was destroyed, "
3077 "but can be imported using the '-Df' flags.\n"));
3078 else if (pool_state != POOL_STATE_EXPORTED)
3079 (void) printf(gettext("\tThe pool may be active on "
3080 "another system, but can be imported using\n\t"
3081 "the '-f' flag.\n"));
3084 if (msgid != NULL) {
3085 (void) printf(gettext(
3086 " see: https://openzfs.github.io/openzfs-docs/msg/%s\n"),
3087 msgid);
3090 (void) printf(gettext(" config:\n\n"));
3092 cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
3093 VDEV_NAME_TYPE_ID);
3094 if (cb.cb_namewidth < 10)
3095 cb.cb_namewidth = 10;
3097 print_import_config(&cb, name, nvroot, 0);
3099 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
3100 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
3101 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
3103 if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
3104 (void) printf(gettext("\n\tAdditional devices are known to "
3105 "be part of this pool, though their\n\texact "
3106 "configuration cannot be determined.\n"));
3108 return (0);
3111 static boolean_t
3112 zfs_force_import_required(nvlist_t *config)
3114 uint64_t state;
3115 uint64_t hostid = 0;
3116 nvlist_t *nvinfo;
3118 state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
3119 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID, &hostid);
3121 if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
3122 return (B_TRUE);
3124 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3125 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
3126 mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
3127 ZPOOL_CONFIG_MMP_STATE);
3129 if (mmp_state != MMP_STATE_INACTIVE)
3130 return (B_TRUE);
3133 return (B_FALSE);
3137 * Perform the import for the given configuration. This passes the heavy
3138 * lifting off to zpool_import_props(), and then mounts the datasets contained
3139 * within the pool.
3141 static int
3142 do_import(nvlist_t *config, const char *newname, const char *mntopts,
3143 nvlist_t *props, int flags)
3145 int ret = 0;
3146 zpool_handle_t *zhp;
3147 const char *name;
3148 uint64_t version;
3150 name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
3151 version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3153 if (!SPA_VERSION_IS_SUPPORTED(version)) {
3154 (void) fprintf(stderr, gettext("cannot import '%s': pool "
3155 "is formatted using an unsupported ZFS version\n"), name);
3156 return (1);
3157 } else if (zfs_force_import_required(config) &&
3158 !(flags & ZFS_IMPORT_ANY_HOST)) {
3159 mmp_state_t mmp_state = MMP_STATE_INACTIVE;
3160 nvlist_t *nvinfo;
3162 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3163 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
3164 mmp_state = fnvlist_lookup_uint64(nvinfo,
3165 ZPOOL_CONFIG_MMP_STATE);
3167 if (mmp_state == MMP_STATE_ACTIVE) {
3168 const char *hostname = "<unknown>";
3169 uint64_t hostid = 0;
3171 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3172 hostname = fnvlist_lookup_string(nvinfo,
3173 ZPOOL_CONFIG_MMP_HOSTNAME);
3175 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3176 hostid = fnvlist_lookup_uint64(nvinfo,
3177 ZPOOL_CONFIG_MMP_HOSTID);
3179 (void) fprintf(stderr, gettext("cannot import '%s': "
3180 "pool is imported on %s (hostid: "
3181 "0x%"PRIx64")\nExport the pool on the other "
3182 "system, then run 'zpool import'.\n"),
3183 name, hostname, hostid);
3184 } else if (mmp_state == MMP_STATE_NO_HOSTID) {
3185 (void) fprintf(stderr, gettext("Cannot import '%s': "
3186 "pool has the multihost property on and the\n"
3187 "system's hostid is not set. Set a unique hostid "
3188 "with the zgenhostid(8) command.\n"), name);
3189 } else {
3190 const char *hostname = "<unknown>";
3191 time_t timestamp = 0;
3192 uint64_t hostid = 0;
3194 if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
3195 hostname = fnvlist_lookup_string(config,
3196 ZPOOL_CONFIG_HOSTNAME);
3198 if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
3199 timestamp = fnvlist_lookup_uint64(config,
3200 ZPOOL_CONFIG_TIMESTAMP);
3202 if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
3203 hostid = fnvlist_lookup_uint64(config,
3204 ZPOOL_CONFIG_HOSTID);
3206 (void) fprintf(stderr, gettext("cannot import '%s': "
3207 "pool was previously in use from another system.\n"
3208 "Last accessed by %s (hostid=%"PRIx64") at %s"
3209 "The pool can be imported, use 'zpool import -f' "
3210 "to import the pool.\n"), name, hostname,
3211 hostid, ctime(&timestamp));
3214 return (1);
3217 if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
3218 return (1);
3220 if (newname != NULL)
3221 name = newname;
3223 if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
3224 return (1);
3227 * Loading keys is best effort. We don't want to return immediately
3228 * if it fails but we do want to give the error to the caller.
3230 if (flags & ZFS_IMPORT_LOAD_KEYS &&
3231 zfs_crypto_attempt_load_keys(g_zfs, name) != 0)
3232 ret = 1;
3234 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3235 !(flags & ZFS_IMPORT_ONLY) &&
3236 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
3237 zpool_close(zhp);
3238 return (1);
3241 zpool_close(zhp);
3242 return (ret);
3245 static int
3246 import_pools(nvlist_t *pools, nvlist_t *props, char *mntopts, int flags,
3247 char *orig_name, char *new_name,
3248 boolean_t do_destroyed, boolean_t pool_specified, boolean_t do_all,
3249 importargs_t *import)
3251 nvlist_t *config = NULL;
3252 nvlist_t *found_config = NULL;
3253 uint64_t pool_state;
3256 * At this point we have a list of import candidate configs. Even if
3257 * we were searching by pool name or guid, we still need to
3258 * post-process the list to deal with pool state and possible
3259 * duplicate names.
3261 int err = 0;
3262 nvpair_t *elem = NULL;
3263 boolean_t first = B_TRUE;
3264 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3266 verify(nvpair_value_nvlist(elem, &config) == 0);
3268 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3269 &pool_state) == 0);
3270 if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
3271 continue;
3272 if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
3273 continue;
3275 verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
3276 import->policy) == 0);
3278 if (!pool_specified) {
3279 if (first)
3280 first = B_FALSE;
3281 else if (!do_all)
3282 (void) fputc('\n', stdout);
3284 if (do_all) {
3285 err |= do_import(config, NULL, mntopts,
3286 props, flags);
3287 } else {
3289 * If we're importing from cachefile, then
3290 * we don't want to report errors until we
3291 * are in the scan phase of the import. If
3292 * we get an error, then we return that error
3293 * to invoke the scan phase.
3295 if (import->cachefile && !import->scan)
3296 err = show_import(config, B_FALSE);
3297 else
3298 (void) show_import(config, B_TRUE);
3300 } else if (import->poolname != NULL) {
3301 const char *name;
3304 * We are searching for a pool based on name.
3306 verify(nvlist_lookup_string(config,
3307 ZPOOL_CONFIG_POOL_NAME, &name) == 0);
3309 if (strcmp(name, import->poolname) == 0) {
3310 if (found_config != NULL) {
3311 (void) fprintf(stderr, gettext(
3312 "cannot import '%s': more than "
3313 "one matching pool\n"),
3314 import->poolname);
3315 (void) fprintf(stderr, gettext(
3316 "import by numeric ID instead\n"));
3317 err = B_TRUE;
3319 found_config = config;
3321 } else {
3322 uint64_t guid;
3325 * Search for a pool by guid.
3327 verify(nvlist_lookup_uint64(config,
3328 ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
3330 if (guid == import->guid)
3331 found_config = config;
3336 * If we were searching for a specific pool, verify that we found a
3337 * pool, and then do the import.
3339 if (pool_specified && err == 0) {
3340 if (found_config == NULL) {
3341 (void) fprintf(stderr, gettext("cannot import '%s': "
3342 "no such pool available\n"), orig_name);
3343 err = B_TRUE;
3344 } else {
3345 err |= do_import(found_config, new_name,
3346 mntopts, props, flags);
3351 * If we were just looking for pools, report an error if none were
3352 * found.
3354 if (!pool_specified && first)
3355 (void) fprintf(stderr,
3356 gettext("no pools available to import\n"));
3357 return (err);
3360 typedef struct target_exists_args {
3361 const char *poolname;
3362 uint64_t poolguid;
3363 } target_exists_args_t;
3365 static int
3366 name_or_guid_exists(zpool_handle_t *zhp, void *data)
3368 target_exists_args_t *args = data;
3369 nvlist_t *config = zpool_get_config(zhp, NULL);
3370 int found = 0;
3372 if (config == NULL)
3373 return (0);
3375 if (args->poolname != NULL) {
3376 const char *pool_name;
3378 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3379 &pool_name) == 0);
3380 if (strcmp(pool_name, args->poolname) == 0)
3381 found = 1;
3382 } else {
3383 uint64_t pool_guid;
3385 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3386 &pool_guid) == 0);
3387 if (pool_guid == args->poolguid)
3388 found = 1;
3390 zpool_close(zhp);
3392 return (found);
3395 * zpool checkpoint <pool>
3396 * checkpoint --discard <pool>
3398 * -d Discard the checkpoint from a checkpointed
3399 * --discard pool.
3401 * -w Wait for discarding a checkpoint to complete.
3402 * --wait
3404 * Checkpoints the specified pool, by taking a "snapshot" of its
3405 * current state. A pool can only have one checkpoint at a time.
3408 zpool_do_checkpoint(int argc, char **argv)
3410 boolean_t discard, wait;
3411 char *pool;
3412 zpool_handle_t *zhp;
3413 int c, err;
3415 struct option long_options[] = {
3416 {"discard", no_argument, NULL, 'd'},
3417 {"wait", no_argument, NULL, 'w'},
3418 {0, 0, 0, 0}
3421 discard = B_FALSE;
3422 wait = B_FALSE;
3423 while ((c = getopt_long(argc, argv, ":dw", long_options, NULL)) != -1) {
3424 switch (c) {
3425 case 'd':
3426 discard = B_TRUE;
3427 break;
3428 case 'w':
3429 wait = B_TRUE;
3430 break;
3431 case '?':
3432 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3433 optopt);
3434 usage(B_FALSE);
3438 if (wait && !discard) {
3439 (void) fprintf(stderr, gettext("--wait only valid when "
3440 "--discard also specified\n"));
3441 usage(B_FALSE);
3444 argc -= optind;
3445 argv += optind;
3447 if (argc < 1) {
3448 (void) fprintf(stderr, gettext("missing pool argument\n"));
3449 usage(B_FALSE);
3452 if (argc > 1) {
3453 (void) fprintf(stderr, gettext("too many arguments\n"));
3454 usage(B_FALSE);
3457 pool = argv[0];
3459 if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
3460 /* As a special case, check for use of '/' in the name */
3461 if (strchr(pool, '/') != NULL)
3462 (void) fprintf(stderr, gettext("'zpool checkpoint' "
3463 "doesn't work on datasets. To save the state "
3464 "of a dataset from a specific point in time "
3465 "please use 'zfs snapshot'\n"));
3466 return (1);
3469 if (discard) {
3470 err = (zpool_discard_checkpoint(zhp) != 0);
3471 if (err == 0 && wait)
3472 err = zpool_wait(zhp, ZPOOL_WAIT_CKPT_DISCARD);
3473 } else {
3474 err = (zpool_checkpoint(zhp) != 0);
3477 zpool_close(zhp);
3479 return (err);
3482 #define CHECKPOINT_OPT 1024
3485 * zpool import [-d dir] [-D]
3486 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
3487 * [-d dir | -c cachefile | -s] [-f] -a
3488 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
3489 * [-d dir | -c cachefile | -s] [-f] [-n] [-F] <pool | id>
3490 * [newpool]
3492 * -c Read pool information from a cachefile instead of searching
3493 * devices. If importing from a cachefile config fails, then
3494 * fallback to searching for devices only in the directories that
3495 * exist in the cachefile.
3497 * -d Scan in a specific directory, other than /dev/. More than
3498 * one directory can be specified using multiple '-d' options.
3500 * -D Scan for previously destroyed pools or import all or only
3501 * specified destroyed pools.
3503 * -R Temporarily import the pool, with all mountpoints relative to
3504 * the given root. The pool will remain exported when the machine
3505 * is rebooted.
3507 * -V Import even in the presence of faulted vdevs. This is an
3508 * intentionally undocumented option for testing purposes, and
3509 * treats the pool configuration as complete, leaving any bad
3510 * vdevs in the FAULTED state. In other words, it does verbatim
3511 * import.
3513 * -f Force import, even if it appears that the pool is active.
3515 * -F Attempt rewind if necessary.
3517 * -n See if rewind would work, but don't actually rewind.
3519 * -N Import the pool but don't mount datasets.
3521 * -T Specify a starting txg to use for import. This option is
3522 * intentionally undocumented option for testing purposes.
3524 * -a Import all pools found.
3526 * -l Load encryption keys while importing.
3528 * -o Set property=value and/or temporary mount options (without '=').
3530 * -s Scan using the default search path, the libblkid cache will
3531 * not be consulted.
3533 * --rewind-to-checkpoint
3534 * Import the pool and revert back to the checkpoint.
3536 * The import command scans for pools to import, and import pools based on pool
3537 * name and GUID. The pool can also be renamed as part of the import process.
3540 zpool_do_import(int argc, char **argv)
3542 char **searchdirs = NULL;
3543 char *env, *envdup = NULL;
3544 int nsearch = 0;
3545 int c;
3546 int err = 0;
3547 nvlist_t *pools = NULL;
3548 boolean_t do_all = B_FALSE;
3549 boolean_t do_destroyed = B_FALSE;
3550 char *mntopts = NULL;
3551 uint64_t searchguid = 0;
3552 char *searchname = NULL;
3553 char *propval;
3554 nvlist_t *policy = NULL;
3555 nvlist_t *props = NULL;
3556 int flags = ZFS_IMPORT_NORMAL;
3557 uint32_t rewind_policy = ZPOOL_NO_REWIND;
3558 boolean_t dryrun = B_FALSE;
3559 boolean_t do_rewind = B_FALSE;
3560 boolean_t xtreme_rewind = B_FALSE;
3561 boolean_t do_scan = B_FALSE;
3562 boolean_t pool_exists = B_FALSE;
3563 boolean_t pool_specified = B_FALSE;
3564 uint64_t txg = -1ULL;
3565 char *cachefile = NULL;
3566 importargs_t idata = { 0 };
3567 char *endptr;
3569 struct option long_options[] = {
3570 {"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
3571 {0, 0, 0, 0}
3574 /* check options */
3575 while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmnNo:R:stT:VX",
3576 long_options, NULL)) != -1) {
3577 switch (c) {
3578 case 'a':
3579 do_all = B_TRUE;
3580 break;
3581 case 'c':
3582 cachefile = optarg;
3583 break;
3584 case 'd':
3585 searchdirs = safe_realloc(searchdirs,
3586 (nsearch + 1) * sizeof (char *));
3587 searchdirs[nsearch++] = optarg;
3588 break;
3589 case 'D':
3590 do_destroyed = B_TRUE;
3591 break;
3592 case 'f':
3593 flags |= ZFS_IMPORT_ANY_HOST;
3594 break;
3595 case 'F':
3596 do_rewind = B_TRUE;
3597 break;
3598 case 'l':
3599 flags |= ZFS_IMPORT_LOAD_KEYS;
3600 break;
3601 case 'm':
3602 flags |= ZFS_IMPORT_MISSING_LOG;
3603 break;
3604 case 'n':
3605 dryrun = B_TRUE;
3606 break;
3607 case 'N':
3608 flags |= ZFS_IMPORT_ONLY;
3609 break;
3610 case 'o':
3611 if ((propval = strchr(optarg, '=')) != NULL) {
3612 *propval = '\0';
3613 propval++;
3614 if (add_prop_list(optarg, propval,
3615 &props, B_TRUE))
3616 goto error;
3617 } else {
3618 mntopts = optarg;
3620 break;
3621 case 'R':
3622 if (add_prop_list(zpool_prop_to_name(
3623 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
3624 goto error;
3625 if (add_prop_list_default(zpool_prop_to_name(
3626 ZPOOL_PROP_CACHEFILE), "none", &props))
3627 goto error;
3628 break;
3629 case 's':
3630 do_scan = B_TRUE;
3631 break;
3632 case 't':
3633 flags |= ZFS_IMPORT_TEMP_NAME;
3634 if (add_prop_list_default(zpool_prop_to_name(
3635 ZPOOL_PROP_CACHEFILE), "none", &props))
3636 goto error;
3637 break;
3639 case 'T':
3640 errno = 0;
3641 txg = strtoull(optarg, &endptr, 0);
3642 if (errno != 0 || *endptr != '\0') {
3643 (void) fprintf(stderr,
3644 gettext("invalid txg value\n"));
3645 usage(B_FALSE);
3647 rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
3648 break;
3649 case 'V':
3650 flags |= ZFS_IMPORT_VERBATIM;
3651 break;
3652 case 'X':
3653 xtreme_rewind = B_TRUE;
3654 break;
3655 case CHECKPOINT_OPT:
3656 flags |= ZFS_IMPORT_CHECKPOINT;
3657 break;
3658 case ':':
3659 (void) fprintf(stderr, gettext("missing argument for "
3660 "'%c' option\n"), optopt);
3661 usage(B_FALSE);
3662 break;
3663 case '?':
3664 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3665 optopt);
3666 usage(B_FALSE);
3670 argc -= optind;
3671 argv += optind;
3673 if (cachefile && nsearch != 0) {
3674 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
3675 usage(B_FALSE);
3678 if (cachefile && do_scan) {
3679 (void) fprintf(stderr, gettext("-c is incompatible with -s\n"));
3680 usage(B_FALSE);
3683 if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
3684 (void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
3685 usage(B_FALSE);
3688 if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
3689 (void) fprintf(stderr, gettext("-l is only meaningful during "
3690 "an import\n"));
3691 usage(B_FALSE);
3694 if ((dryrun || xtreme_rewind) && !do_rewind) {
3695 (void) fprintf(stderr,
3696 gettext("-n or -X only meaningful with -F\n"));
3697 usage(B_FALSE);
3699 if (dryrun)
3700 rewind_policy = ZPOOL_TRY_REWIND;
3701 else if (do_rewind)
3702 rewind_policy = ZPOOL_DO_REWIND;
3703 if (xtreme_rewind)
3704 rewind_policy |= ZPOOL_EXTREME_REWIND;
3706 /* In the future, we can capture further policy and include it here */
3707 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
3708 nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
3709 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
3710 rewind_policy) != 0)
3711 goto error;
3713 /* check argument count */
3714 if (do_all) {
3715 if (argc != 0) {
3716 (void) fprintf(stderr, gettext("too many arguments\n"));
3717 usage(B_FALSE);
3719 } else {
3720 if (argc > 2) {
3721 (void) fprintf(stderr, gettext("too many arguments\n"));
3722 usage(B_FALSE);
3727 * Check for the effective uid. We do this explicitly here because
3728 * otherwise any attempt to discover pools will silently fail.
3730 if (argc == 0 && geteuid() != 0) {
3731 (void) fprintf(stderr, gettext("cannot "
3732 "discover pools: permission denied\n"));
3734 free(searchdirs);
3735 nvlist_free(props);
3736 nvlist_free(policy);
3737 return (1);
3741 * Depending on the arguments given, we do one of the following:
3743 * <none> Iterate through all pools and display information about
3744 * each one.
3746 * -a Iterate through all pools and try to import each one.
3748 * <id> Find the pool that corresponds to the given GUID/pool
3749 * name and import that one.
3751 * -D Above options applies only to destroyed pools.
3753 if (argc != 0) {
3754 char *endptr;
3756 errno = 0;
3757 searchguid = strtoull(argv[0], &endptr, 10);
3758 if (errno != 0 || *endptr != '\0') {
3759 searchname = argv[0];
3760 searchguid = 0;
3762 pool_specified = B_TRUE;
3765 * User specified a name or guid. Ensure it's unique.
3767 target_exists_args_t search = {searchname, searchguid};
3768 pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
3772 * Check the environment for the preferred search path.
3774 if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
3775 char *dir, *tmp = NULL;
3777 envdup = strdup(env);
3779 for (dir = strtok_r(envdup, ":", &tmp);
3780 dir != NULL;
3781 dir = strtok_r(NULL, ":", &tmp)) {
3782 searchdirs = safe_realloc(searchdirs,
3783 (nsearch + 1) * sizeof (char *));
3784 searchdirs[nsearch++] = dir;
3788 idata.path = searchdirs;
3789 idata.paths = nsearch;
3790 idata.poolname = searchname;
3791 idata.guid = searchguid;
3792 idata.cachefile = cachefile;
3793 idata.scan = do_scan;
3794 idata.policy = policy;
3796 libpc_handle_t lpch = {
3797 .lpc_lib_handle = g_zfs,
3798 .lpc_ops = &libzfs_config_ops,
3799 .lpc_printerr = B_TRUE
3801 pools = zpool_search_import(&lpch, &idata);
3803 if (pools != NULL && pool_exists &&
3804 (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
3805 (void) fprintf(stderr, gettext("cannot import '%s': "
3806 "a pool with that name already exists\n"),
3807 argv[0]);
3808 (void) fprintf(stderr, gettext("use the form '%s "
3809 "<pool | id> <newpool>' to give it a new name\n"),
3810 "zpool import");
3811 err = 1;
3812 } else if (pools == NULL && pool_exists) {
3813 (void) fprintf(stderr, gettext("cannot import '%s': "
3814 "a pool with that name is already created/imported,\n"),
3815 argv[0]);
3816 (void) fprintf(stderr, gettext("and no additional pools "
3817 "with that name were found\n"));
3818 err = 1;
3819 } else if (pools == NULL) {
3820 if (argc != 0) {
3821 (void) fprintf(stderr, gettext("cannot import '%s': "
3822 "no such pool available\n"), argv[0]);
3824 err = 1;
3827 if (err == 1) {
3828 free(searchdirs);
3829 free(envdup);
3830 nvlist_free(policy);
3831 nvlist_free(pools);
3832 nvlist_free(props);
3833 return (1);
3836 err = import_pools(pools, props, mntopts, flags,
3837 argc >= 1 ? argv[0] : NULL,
3838 argc >= 2 ? argv[1] : NULL,
3839 do_destroyed, pool_specified, do_all, &idata);
3842 * If we're using the cachefile and we failed to import, then
3843 * fallback to scanning the directory for pools that match
3844 * those in the cachefile.
3846 if (err != 0 && cachefile != NULL) {
3847 (void) printf(gettext("cachefile import failed, retrying\n"));
3850 * We use the scan flag to gather the directories that exist
3851 * in the cachefile. If we need to fallback to searching for
3852 * the pool config, we will only search devices in these
3853 * directories.
3855 idata.scan = B_TRUE;
3856 nvlist_free(pools);
3857 pools = zpool_search_import(&lpch, &idata);
3859 err = import_pools(pools, props, mntopts, flags,
3860 argc >= 1 ? argv[0] : NULL,
3861 argc >= 2 ? argv[1] : NULL,
3862 do_destroyed, pool_specified, do_all, &idata);
3865 error:
3866 nvlist_free(props);
3867 nvlist_free(pools);
3868 nvlist_free(policy);
3869 free(searchdirs);
3870 free(envdup);
3872 return (err ? 1 : 0);
3876 * zpool sync [-f] [pool] ...
3878 * -f (undocumented) force uberblock (and config including zpool cache file)
3879 * update.
3881 * Sync the specified pool(s).
3882 * Without arguments "zpool sync" will sync all pools.
3883 * This command initiates TXG sync(s) and will return after the TXG(s) commit.
3886 static int
3887 zpool_do_sync(int argc, char **argv)
3889 int ret;
3890 boolean_t force = B_FALSE;
3892 /* check options */
3893 while ((ret = getopt(argc, argv, "f")) != -1) {
3894 switch (ret) {
3895 case 'f':
3896 force = B_TRUE;
3897 break;
3898 case '?':
3899 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3900 optopt);
3901 usage(B_FALSE);
3905 argc -= optind;
3906 argv += optind;
3908 /* if argc == 0 we will execute zpool_sync_one on all pools */
3909 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
3910 B_FALSE, zpool_sync_one, &force);
3912 return (ret);
3915 typedef struct iostat_cbdata {
3916 uint64_t cb_flags;
3917 int cb_namewidth;
3918 int cb_iteration;
3919 boolean_t cb_verbose;
3920 boolean_t cb_literal;
3921 boolean_t cb_scripted;
3922 zpool_list_t *cb_list;
3923 vdev_cmd_data_list_t *vcdl;
3924 vdev_cbdata_t cb_vdevs;
3925 } iostat_cbdata_t;
3927 /* iostat labels */
3928 typedef struct name_and_columns {
3929 const char *name; /* Column name */
3930 unsigned int columns; /* Center name to this number of columns */
3931 } name_and_columns_t;
3933 #define IOSTAT_MAX_LABELS 15 /* Max number of labels on one line */
3935 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
3937 [IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
3938 {NULL}},
3939 [IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
3940 {"asyncq_wait", 2}, {"scrub", 1}, {"trim", 1}, {"rebuild", 1},
3941 {NULL}},
3942 [IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
3943 {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
3944 {"trimq_write", 2}, {"rebuildq_write", 2}, {NULL}},
3945 [IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
3946 {"asyncq_wait", 2}, {NULL}},
3947 [IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
3948 {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
3949 {"trim", 2}, {"rebuild", 2}, {NULL}},
3952 /* Shorthand - if "columns" field not set, default to 1 column */
3953 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
3955 [IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
3956 {"write"}, {NULL}},
3957 [IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
3958 {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {"wait"},
3959 {NULL}},
3960 [IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
3961 {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
3962 {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
3963 [IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
3964 {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {"rebuild"},
3965 {NULL}},
3966 [IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
3967 {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
3968 {"ind"}, {"agg"}, {NULL}},
3971 static const char *histo_to_title[] = {
3972 [IOS_L_HISTO] = "latency",
3973 [IOS_RQ_HISTO] = "req_size",
3977 * Return the number of labels in a null-terminated name_and_columns_t
3978 * array.
3981 static unsigned int
3982 label_array_len(const name_and_columns_t *labels)
3984 int i = 0;
3986 while (labels[i].name)
3987 i++;
3989 return (i);
3993 * Return the number of strings in a null-terminated string array.
3994 * For example:
3996 * const char foo[] = {"bar", "baz", NULL}
3998 * returns 2
4000 static uint64_t
4001 str_array_len(const char *array[])
4003 uint64_t i = 0;
4004 while (array[i])
4005 i++;
4007 return (i);
4012 * Return a default column width for default/latency/queue columns. This does
4013 * not include histograms, which have their columns autosized.
4015 static unsigned int
4016 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
4018 unsigned long column_width = 5; /* Normal niceprint */
4019 static unsigned long widths[] = {
4021 * Choose some sane default column sizes for printing the
4022 * raw numbers.
4024 [IOS_DEFAULT] = 15, /* 1PB capacity */
4025 [IOS_LATENCY] = 10, /* 1B ns = 10sec */
4026 [IOS_QUEUES] = 6, /* 1M queue entries */
4027 [IOS_L_HISTO] = 10, /* 1B ns = 10sec */
4028 [IOS_RQ_HISTO] = 6, /* 1M queue entries */
4031 if (cb->cb_literal)
4032 column_width = widths[type];
4034 return (column_width);
4038 * Print the column labels, i.e:
4040 * capacity operations bandwidth
4041 * alloc free read write read write ...
4043 * If force_column_width is set, use it for the column width. If not set, use
4044 * the default column width.
4046 static void
4047 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
4048 const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
4050 int i, idx, s;
4051 int text_start, rw_column_width, spaces_to_end;
4052 uint64_t flags = cb->cb_flags;
4053 uint64_t f;
4054 unsigned int column_width = force_column_width;
4056 /* For each bit set in flags */
4057 for (f = flags; f; f &= ~(1ULL << idx)) {
4058 idx = lowbit64(f) - 1;
4059 if (!force_column_width)
4060 column_width = default_column_width(cb, idx);
4061 /* Print our top labels centered over "read write" label. */
4062 for (i = 0; i < label_array_len(labels[idx]); i++) {
4063 const char *name = labels[idx][i].name;
4065 * We treat labels[][].columns == 0 as shorthand
4066 * for one column. It makes writing out the label
4067 * tables more concise.
4069 unsigned int columns = MAX(1, labels[idx][i].columns);
4070 unsigned int slen = strlen(name);
4072 rw_column_width = (column_width * columns) +
4073 (2 * (columns - 1));
4075 text_start = (int)((rw_column_width) / columns -
4076 slen / columns);
4077 if (text_start < 0)
4078 text_start = 0;
4080 printf(" "); /* Two spaces between columns */
4082 /* Space from beginning of column to label */
4083 for (s = 0; s < text_start; s++)
4084 printf(" ");
4086 printf("%s", name);
4088 /* Print space after label to end of column */
4089 spaces_to_end = rw_column_width - text_start - slen;
4090 if (spaces_to_end < 0)
4091 spaces_to_end = 0;
4093 for (s = 0; s < spaces_to_end; s++)
4094 printf(" ");
4101 * print_cmd_columns - Print custom column titles from -c
4103 * If the user specified the "zpool status|iostat -c" then print their custom
4104 * column titles in the header. For example, print_cmd_columns() would print
4105 * the " col1 col2" part of this:
4107 * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
4108 * ...
4109 * capacity operations bandwidth
4110 * pool alloc free read write read write col1 col2
4111 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4112 * mypool 269K 1008M 0 0 107 946
4113 * mirror 269K 1008M 0 0 107 946
4114 * sdb - - 0 0 102 473 val1 val2
4115 * sdc - - 0 0 5 473 val1 val2
4116 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4118 static void
4119 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
4121 int i, j;
4122 vdev_cmd_data_t *data = &vcdl->data[0];
4124 if (vcdl->count == 0 || data == NULL)
4125 return;
4128 * Each vdev cmd should have the same column names unless the user did
4129 * something weird with their cmd. Just take the column names from the
4130 * first vdev and assume it works for all of them.
4132 for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
4133 printf(" ");
4134 if (use_dashes) {
4135 for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
4136 printf("-");
4137 } else {
4138 printf_color(ANSI_BOLD, "%*s", vcdl->uniq_cols_width[i],
4139 vcdl->uniq_cols[i]);
4146 * Utility function to print out a line of dashes like:
4148 * -------------------------------- ----- ----- ----- ----- -----
4150 * ...or a dashed named-row line like:
4152 * logs - - - - -
4154 * @cb: iostat data
4156 * @force_column_width If non-zero, use the value as the column width.
4157 * Otherwise use the default column widths.
4159 * @name: Print a dashed named-row line starting
4160 * with @name. Otherwise, print a regular
4161 * dashed line.
4163 static void
4164 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
4165 const char *name)
4167 int i;
4168 unsigned int namewidth;
4169 uint64_t flags = cb->cb_flags;
4170 uint64_t f;
4171 int idx;
4172 const name_and_columns_t *labels;
4173 const char *title;
4176 if (cb->cb_flags & IOS_ANYHISTO_M) {
4177 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4178 } else if (cb->cb_vdevs.cb_names_count) {
4179 title = "vdev";
4180 } else {
4181 title = "pool";
4184 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4185 name ? strlen(name) : 0);
4188 if (name) {
4189 printf("%-*s", namewidth, name);
4190 } else {
4191 for (i = 0; i < namewidth; i++)
4192 (void) printf("-");
4195 /* For each bit in flags */
4196 for (f = flags; f; f &= ~(1ULL << idx)) {
4197 unsigned int column_width;
4198 idx = lowbit64(f) - 1;
4199 if (force_column_width)
4200 column_width = force_column_width;
4201 else
4202 column_width = default_column_width(cb, idx);
4204 labels = iostat_bottom_labels[idx];
4205 for (i = 0; i < label_array_len(labels); i++) {
4206 if (name)
4207 printf(" %*s-", column_width - 1, " ");
4208 else
4209 printf(" %.*s", column_width,
4210 "--------------------");
4216 static void
4217 print_iostat_separator_impl(iostat_cbdata_t *cb,
4218 unsigned int force_column_width)
4220 print_iostat_dashes(cb, force_column_width, NULL);
4223 static void
4224 print_iostat_separator(iostat_cbdata_t *cb)
4226 print_iostat_separator_impl(cb, 0);
4229 static void
4230 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
4231 const char *histo_vdev_name)
4233 unsigned int namewidth;
4234 const char *title;
4236 color_start(ANSI_BOLD);
4238 if (cb->cb_flags & IOS_ANYHISTO_M) {
4239 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4240 } else if (cb->cb_vdevs.cb_names_count) {
4241 title = "vdev";
4242 } else {
4243 title = "pool";
4246 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4247 histo_vdev_name ? strlen(histo_vdev_name) : 0);
4249 if (histo_vdev_name)
4250 printf("%-*s", namewidth, histo_vdev_name);
4251 else
4252 printf("%*s", namewidth, "");
4255 print_iostat_labels(cb, force_column_width, iostat_top_labels);
4256 printf("\n");
4258 printf("%-*s", namewidth, title);
4260 print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
4261 if (cb->vcdl != NULL)
4262 print_cmd_columns(cb->vcdl, 0);
4264 printf("\n");
4266 print_iostat_separator_impl(cb, force_column_width);
4268 if (cb->vcdl != NULL)
4269 print_cmd_columns(cb->vcdl, 1);
4271 color_end();
4273 printf("\n");
4276 static void
4277 print_iostat_header(iostat_cbdata_t *cb)
4279 print_iostat_header_impl(cb, 0, NULL);
4283 * Prints a size string (i.e. 120M) with the suffix ("M") colored
4284 * by order of magnitude. Uses column_size to add padding.
4286 static void
4287 print_stat_color(const char *statbuf, unsigned int column_size)
4289 fputs(" ", stdout);
4290 size_t len = strlen(statbuf);
4291 while (len < column_size) {
4292 fputc(' ', stdout);
4293 column_size--;
4295 if (*statbuf == '0') {
4296 color_start(ANSI_GRAY);
4297 fputc('0', stdout);
4298 } else {
4299 for (; *statbuf; statbuf++) {
4300 if (*statbuf == 'K') color_start(ANSI_GREEN);
4301 else if (*statbuf == 'M') color_start(ANSI_YELLOW);
4302 else if (*statbuf == 'G') color_start(ANSI_RED);
4303 else if (*statbuf == 'T') color_start(ANSI_BOLD_BLUE);
4304 else if (*statbuf == 'P') color_start(ANSI_MAGENTA);
4305 else if (*statbuf == 'E') color_start(ANSI_CYAN);
4306 fputc(*statbuf, stdout);
4307 if (--column_size <= 0)
4308 break;
4311 color_end();
4315 * Display a single statistic.
4317 static void
4318 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
4319 unsigned int column_size, boolean_t scripted)
4321 char buf[64];
4323 zfs_nicenum_format(value, buf, sizeof (buf), format);
4325 if (scripted)
4326 printf("\t%s", buf);
4327 else
4328 print_stat_color(buf, column_size);
4332 * Calculate the default vdev stats
4334 * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
4335 * stats into calcvs.
4337 static void
4338 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
4339 vdev_stat_t *calcvs)
4341 int i;
4343 memcpy(calcvs, newvs, sizeof (*calcvs));
4344 for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
4345 calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
4347 for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
4348 calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
4352 * Internal representation of the extended iostats data.
4354 * The extended iostat stats are exported in nvlists as either uint64_t arrays
4355 * or single uint64_t's. We make both look like arrays to make them easier
4356 * to process. In order to make single uint64_t's look like arrays, we set
4357 * __data to the stat data, and then set *data = &__data with count = 1. Then,
4358 * we can just use *data and count.
4360 struct stat_array {
4361 uint64_t *data;
4362 uint_t count; /* Number of entries in data[] */
4363 uint64_t __data; /* Only used when data is a single uint64_t */
4366 static uint64_t
4367 stat_histo_max(struct stat_array *nva, unsigned int len)
4369 uint64_t max = 0;
4370 int i;
4371 for (i = 0; i < len; i++)
4372 max = MAX(max, array64_max(nva[i].data, nva[i].count));
4374 return (max);
4378 * Helper function to lookup a uint64_t array or uint64_t value and store its
4379 * data as a stat_array. If the nvpair is a single uint64_t value, then we make
4380 * it look like a one element array to make it easier to process.
4382 static int
4383 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
4384 struct stat_array *nva)
4386 nvpair_t *tmp;
4387 int ret;
4389 verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
4390 switch (nvpair_type(tmp)) {
4391 case DATA_TYPE_UINT64_ARRAY:
4392 ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
4393 break;
4394 case DATA_TYPE_UINT64:
4395 ret = nvpair_value_uint64(tmp, &nva->__data);
4396 nva->data = &nva->__data;
4397 nva->count = 1;
4398 break;
4399 default:
4400 /* Not a uint64_t */
4401 ret = EINVAL;
4402 break;
4405 return (ret);
4409 * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
4410 * subtract them, and return the results in a newly allocated stat_array.
4411 * You must free the returned array after you are done with it with
4412 * free_calc_stats().
4414 * Additionally, you can set "oldnv" to NULL if you simply want the newnv
4415 * values.
4417 static struct stat_array *
4418 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
4419 nvlist_t *newnv)
4421 nvlist_t *oldnvx = NULL, *newnvx;
4422 struct stat_array *oldnva, *newnva, *calcnva;
4423 int i, j;
4424 unsigned int alloc_size = (sizeof (struct stat_array)) * len;
4426 /* Extract our extended stats nvlist from the main list */
4427 verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
4428 &newnvx) == 0);
4429 if (oldnv) {
4430 verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
4431 &oldnvx) == 0);
4434 newnva = safe_malloc(alloc_size);
4435 oldnva = safe_malloc(alloc_size);
4436 calcnva = safe_malloc(alloc_size);
4438 for (j = 0; j < len; j++) {
4439 verify(nvpair64_to_stat_array(newnvx, names[j],
4440 &newnva[j]) == 0);
4441 calcnva[j].count = newnva[j].count;
4442 alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
4443 calcnva[j].data = safe_malloc(alloc_size);
4444 memcpy(calcnva[j].data, newnva[j].data, alloc_size);
4446 if (oldnvx) {
4447 verify(nvpair64_to_stat_array(oldnvx, names[j],
4448 &oldnva[j]) == 0);
4449 for (i = 0; i < oldnva[j].count; i++)
4450 calcnva[j].data[i] -= oldnva[j].data[i];
4453 free(newnva);
4454 free(oldnva);
4455 return (calcnva);
4458 static void
4459 free_calc_stats(struct stat_array *nva, unsigned int len)
4461 int i;
4462 for (i = 0; i < len; i++)
4463 free(nva[i].data);
4465 free(nva);
4468 static void
4469 print_iostat_histo(struct stat_array *nva, unsigned int len,
4470 iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
4471 double scale)
4473 int i, j;
4474 char buf[6];
4475 uint64_t val;
4476 enum zfs_nicenum_format format;
4477 unsigned int buckets;
4478 unsigned int start_bucket;
4480 if (cb->cb_literal)
4481 format = ZFS_NICENUM_RAW;
4482 else
4483 format = ZFS_NICENUM_1024;
4485 /* All these histos are the same size, so just use nva[0].count */
4486 buckets = nva[0].count;
4488 if (cb->cb_flags & IOS_RQ_HISTO_M) {
4489 /* Start at 512 - req size should never be lower than this */
4490 start_bucket = 9;
4491 } else {
4492 start_bucket = 0;
4495 for (j = start_bucket; j < buckets; j++) {
4496 /* Print histogram bucket label */
4497 if (cb->cb_flags & IOS_L_HISTO_M) {
4498 /* Ending range of this bucket */
4499 val = (1UL << (j + 1)) - 1;
4500 zfs_nicetime(val, buf, sizeof (buf));
4501 } else {
4502 /* Request size (starting range of bucket) */
4503 val = (1UL << j);
4504 zfs_nicenum(val, buf, sizeof (buf));
4507 if (cb->cb_scripted)
4508 printf("%llu", (u_longlong_t)val);
4509 else
4510 printf("%-*s", namewidth, buf);
4512 /* Print the values on the line */
4513 for (i = 0; i < len; i++) {
4514 print_one_stat(nva[i].data[j] * scale, format,
4515 column_width, cb->cb_scripted);
4517 printf("\n");
4521 static void
4522 print_solid_separator(unsigned int length)
4524 while (length--)
4525 printf("-");
4526 printf("\n");
4529 static void
4530 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
4531 nvlist_t *newnv, double scale, const char *name)
4533 unsigned int column_width;
4534 unsigned int namewidth;
4535 unsigned int entire_width;
4536 enum iostat_type type;
4537 struct stat_array *nva;
4538 const char **names;
4539 unsigned int names_len;
4541 /* What type of histo are we? */
4542 type = IOS_HISTO_IDX(cb->cb_flags);
4544 /* Get NULL-terminated array of nvlist names for our histo */
4545 names = vsx_type_to_nvlist[type];
4546 names_len = str_array_len(names); /* num of names */
4548 nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
4550 if (cb->cb_literal) {
4551 column_width = MAX(5,
4552 (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
4553 } else {
4554 column_width = 5;
4557 namewidth = MAX(cb->cb_namewidth,
4558 strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
4561 * Calculate the entire line width of what we're printing. The
4562 * +2 is for the two spaces between columns:
4564 /* read write */
4565 /* ----- ----- */
4566 /* |___| <---------- column_width */
4567 /* */
4568 /* |__________| <--- entire_width */
4569 /* */
4570 entire_width = namewidth + (column_width + 2) *
4571 label_array_len(iostat_bottom_labels[type]);
4573 if (cb->cb_scripted)
4574 printf("%s\n", name);
4575 else
4576 print_iostat_header_impl(cb, column_width, name);
4578 print_iostat_histo(nva, names_len, cb, column_width,
4579 namewidth, scale);
4581 free_calc_stats(nva, names_len);
4582 if (!cb->cb_scripted)
4583 print_solid_separator(entire_width);
4587 * Calculate the average latency of a power-of-two latency histogram
4589 static uint64_t
4590 single_histo_average(uint64_t *histo, unsigned int buckets)
4592 int i;
4593 uint64_t count = 0, total = 0;
4595 for (i = 0; i < buckets; i++) {
4597 * Our buckets are power-of-two latency ranges. Use the
4598 * midpoint latency of each bucket to calculate the average.
4599 * For example:
4601 * Bucket Midpoint
4602 * 8ns-15ns: 12ns
4603 * 16ns-31ns: 24ns
4604 * ...
4606 if (histo[i] != 0) {
4607 total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
4608 count += histo[i];
4612 /* Prevent divide by zero */
4613 return (count == 0 ? 0 : total / count);
4616 static void
4617 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *newnv)
4619 const char *names[] = {
4620 ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
4621 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
4622 ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
4623 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
4624 ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
4625 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
4626 ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
4627 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
4628 ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
4629 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
4630 ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
4631 ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
4632 ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
4633 ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
4636 struct stat_array *nva;
4638 unsigned int column_width = default_column_width(cb, IOS_QUEUES);
4639 enum zfs_nicenum_format format;
4641 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
4643 if (cb->cb_literal)
4644 format = ZFS_NICENUM_RAW;
4645 else
4646 format = ZFS_NICENUM_1024;
4648 for (int i = 0; i < ARRAY_SIZE(names); i++) {
4649 uint64_t val = nva[i].data[0];
4650 print_one_stat(val, format, column_width, cb->cb_scripted);
4653 free_calc_stats(nva, ARRAY_SIZE(names));
4656 static void
4657 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
4658 nvlist_t *newnv)
4660 int i;
4661 uint64_t val;
4662 const char *names[] = {
4663 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
4664 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
4665 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
4666 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
4667 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
4668 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
4669 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
4670 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
4671 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
4672 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
4673 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
4675 struct stat_array *nva;
4677 unsigned int column_width = default_column_width(cb, IOS_LATENCY);
4678 enum zfs_nicenum_format format;
4680 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
4682 if (cb->cb_literal)
4683 format = ZFS_NICENUM_RAWTIME;
4684 else
4685 format = ZFS_NICENUM_TIME;
4687 /* Print our avg latencies on the line */
4688 for (i = 0; i < ARRAY_SIZE(names); i++) {
4689 /* Compute average latency for a latency histo */
4690 val = single_histo_average(nva[i].data, nva[i].count);
4691 print_one_stat(val, format, column_width, cb->cb_scripted);
4693 free_calc_stats(nva, ARRAY_SIZE(names));
4697 * Print default statistics (capacity/operations/bandwidth)
4699 static void
4700 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
4702 unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
4703 enum zfs_nicenum_format format;
4704 char na; /* char to print for "not applicable" values */
4706 if (cb->cb_literal) {
4707 format = ZFS_NICENUM_RAW;
4708 na = '0';
4709 } else {
4710 format = ZFS_NICENUM_1024;
4711 na = '-';
4714 /* only toplevel vdevs have capacity stats */
4715 if (vs->vs_space == 0) {
4716 if (cb->cb_scripted)
4717 printf("\t%c\t%c", na, na);
4718 else
4719 printf(" %*c %*c", column_width, na, column_width,
4720 na);
4721 } else {
4722 print_one_stat(vs->vs_alloc, format, column_width,
4723 cb->cb_scripted);
4724 print_one_stat(vs->vs_space - vs->vs_alloc, format,
4725 column_width, cb->cb_scripted);
4728 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
4729 format, column_width, cb->cb_scripted);
4730 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
4731 format, column_width, cb->cb_scripted);
4732 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
4733 format, column_width, cb->cb_scripted);
4734 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
4735 format, column_width, cb->cb_scripted);
4738 static const char *const class_name[] = {
4739 VDEV_ALLOC_BIAS_DEDUP,
4740 VDEV_ALLOC_BIAS_SPECIAL,
4741 VDEV_ALLOC_CLASS_LOGS
4745 * Print out all the statistics for the given vdev. This can either be the
4746 * toplevel configuration, or called recursively. If 'name' is NULL, then this
4747 * is a verbose output, and we don't want to display the toplevel pool stats.
4749 * Returns the number of stat lines printed.
4751 static unsigned int
4752 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
4753 nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
4755 nvlist_t **oldchild, **newchild;
4756 uint_t c, children, oldchildren;
4757 vdev_stat_t *oldvs, *newvs, *calcvs;
4758 vdev_stat_t zerovs = { 0 };
4759 char *vname;
4760 int i;
4761 int ret = 0;
4762 uint64_t tdelta;
4763 double scale;
4765 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
4766 return (ret);
4768 calcvs = safe_malloc(sizeof (*calcvs));
4770 if (oldnv != NULL) {
4771 verify(nvlist_lookup_uint64_array(oldnv,
4772 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
4773 } else {
4774 oldvs = &zerovs;
4777 /* Do we only want to see a specific vdev? */
4778 for (i = 0; i < cb->cb_vdevs.cb_names_count; i++) {
4779 /* Yes we do. Is this the vdev? */
4780 if (strcmp(name, cb->cb_vdevs.cb_names[i]) == 0) {
4782 * This is our vdev. Since it is the only vdev we
4783 * will be displaying, make depth = 0 so that it
4784 * doesn't get indented.
4786 depth = 0;
4787 break;
4791 if (cb->cb_vdevs.cb_names_count && (i == cb->cb_vdevs.cb_names_count)) {
4792 /* Couldn't match the name */
4793 goto children;
4797 verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
4798 (uint64_t **)&newvs, &c) == 0);
4801 * Print the vdev name unless it's is a histogram. Histograms
4802 * display the vdev name in the header itself.
4804 if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
4805 if (cb->cb_scripted) {
4806 printf("%s", name);
4807 } else {
4808 if (strlen(name) + depth > cb->cb_namewidth)
4809 (void) printf("%*s%s", depth, "", name);
4810 else
4811 (void) printf("%*s%s%*s", depth, "", name,
4812 (int)(cb->cb_namewidth - strlen(name) -
4813 depth), "");
4817 /* Calculate our scaling factor */
4818 tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
4819 if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
4821 * If we specify printing histograms with no time interval, then
4822 * print the histogram numbers over the entire lifetime of the
4823 * vdev.
4825 scale = 1;
4826 } else {
4827 if (tdelta == 0)
4828 scale = 1.0;
4829 else
4830 scale = (double)NANOSEC / tdelta;
4833 if (cb->cb_flags & IOS_DEFAULT_M) {
4834 calc_default_iostats(oldvs, newvs, calcvs);
4835 print_iostat_default(calcvs, cb, scale);
4837 if (cb->cb_flags & IOS_LATENCY_M)
4838 print_iostat_latency(cb, oldnv, newnv);
4839 if (cb->cb_flags & IOS_QUEUES_M)
4840 print_iostat_queues(cb, newnv);
4841 if (cb->cb_flags & IOS_ANYHISTO_M) {
4842 printf("\n");
4843 print_iostat_histos(cb, oldnv, newnv, scale, name);
4846 if (cb->vcdl != NULL) {
4847 const char *path;
4848 if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
4849 &path) == 0) {
4850 printf(" ");
4851 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
4855 if (!(cb->cb_flags & IOS_ANYHISTO_M))
4856 printf("\n");
4858 ret++;
4860 children:
4862 free(calcvs);
4864 if (!cb->cb_verbose)
4865 return (ret);
4867 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
4868 &newchild, &children) != 0)
4869 return (ret);
4871 if (oldnv) {
4872 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
4873 &oldchild, &oldchildren) != 0)
4874 return (ret);
4876 children = MIN(oldchildren, children);
4880 * print normal top-level devices
4882 for (c = 0; c < children; c++) {
4883 uint64_t ishole = B_FALSE, islog = B_FALSE;
4885 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
4886 &ishole);
4888 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
4889 &islog);
4891 if (ishole || islog)
4892 continue;
4894 if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
4895 continue;
4897 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4898 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
4899 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
4900 newchild[c], cb, depth + 2);
4901 free(vname);
4905 * print all other top-level devices
4907 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
4908 boolean_t printed = B_FALSE;
4910 for (c = 0; c < children; c++) {
4911 uint64_t islog = B_FALSE;
4912 const char *bias = NULL;
4913 const char *type = NULL;
4915 (void) nvlist_lookup_uint64(newchild[c],
4916 ZPOOL_CONFIG_IS_LOG, &islog);
4917 if (islog) {
4918 bias = VDEV_ALLOC_CLASS_LOGS;
4919 } else {
4920 (void) nvlist_lookup_string(newchild[c],
4921 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
4922 (void) nvlist_lookup_string(newchild[c],
4923 ZPOOL_CONFIG_TYPE, &type);
4925 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
4926 continue;
4927 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
4928 continue;
4930 if (!printed) {
4931 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
4932 !cb->cb_scripted &&
4933 !cb->cb_vdevs.cb_names) {
4934 print_iostat_dashes(cb, 0,
4935 class_name[n]);
4937 printf("\n");
4938 printed = B_TRUE;
4941 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4942 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
4943 ret += print_vdev_stats(zhp, vname, oldnv ?
4944 oldchild[c] : NULL, newchild[c], cb, depth + 2);
4945 free(vname);
4950 * Include level 2 ARC devices in iostat output
4952 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
4953 &newchild, &children) != 0)
4954 return (ret);
4956 if (oldnv) {
4957 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
4958 &oldchild, &oldchildren) != 0)
4959 return (ret);
4961 children = MIN(oldchildren, children);
4964 if (children > 0) {
4965 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
4966 !cb->cb_vdevs.cb_names) {
4967 print_iostat_dashes(cb, 0, "cache");
4969 printf("\n");
4971 for (c = 0; c < children; c++) {
4972 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
4973 cb->cb_vdevs.cb_name_flags);
4974 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
4975 : NULL, newchild[c], cb, depth + 2);
4976 free(vname);
4980 return (ret);
4983 static int
4984 refresh_iostat(zpool_handle_t *zhp, void *data)
4986 iostat_cbdata_t *cb = data;
4987 boolean_t missing;
4990 * If the pool has disappeared, remove it from the list and continue.
4992 if (zpool_refresh_stats(zhp, &missing) != 0)
4993 return (-1);
4995 if (missing)
4996 pool_list_remove(cb->cb_list, zhp);
4998 return (0);
5002 * Callback to print out the iostats for the given pool.
5004 static int
5005 print_iostat(zpool_handle_t *zhp, void *data)
5007 iostat_cbdata_t *cb = data;
5008 nvlist_t *oldconfig, *newconfig;
5009 nvlist_t *oldnvroot, *newnvroot;
5010 int ret;
5012 newconfig = zpool_get_config(zhp, &oldconfig);
5014 if (cb->cb_iteration == 1)
5015 oldconfig = NULL;
5017 verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
5018 &newnvroot) == 0);
5020 if (oldconfig == NULL)
5021 oldnvroot = NULL;
5022 else
5023 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
5024 &oldnvroot) == 0);
5026 ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
5027 cb, 0);
5028 if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
5029 !cb->cb_scripted && cb->cb_verbose &&
5030 !cb->cb_vdevs.cb_names_count) {
5031 print_iostat_separator(cb);
5032 if (cb->vcdl != NULL) {
5033 print_cmd_columns(cb->vcdl, 1);
5035 printf("\n");
5038 return (ret);
5041 static int
5042 get_columns(void)
5044 struct winsize ws;
5045 int columns = 80;
5046 int error;
5048 if (isatty(STDOUT_FILENO)) {
5049 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
5050 if (error == 0)
5051 columns = ws.ws_col;
5052 } else {
5053 columns = 999;
5056 return (columns);
5060 * Return the required length of the pool/vdev name column. The minimum
5061 * allowed width and output formatting flags must be provided.
5063 static int
5064 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
5066 nvlist_t *config, *nvroot;
5067 int width = min_width;
5069 if ((config = zpool_get_config(zhp, NULL)) != NULL) {
5070 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5071 &nvroot) == 0);
5072 size_t poolname_len = strlen(zpool_get_name(zhp));
5073 if (verbose == B_FALSE) {
5074 width = MAX(poolname_len, min_width);
5075 } else {
5076 width = MAX(poolname_len,
5077 max_width(zhp, nvroot, 0, min_width, flags));
5081 return (width);
5085 * Parse the input string, get the 'interval' and 'count' value if there is one.
5087 static void
5088 get_interval_count(int *argcp, char **argv, float *iv,
5089 unsigned long *cnt)
5091 float interval = 0;
5092 unsigned long count = 0;
5093 int argc = *argcp;
5096 * Determine if the last argument is an integer or a pool name
5098 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5099 char *end;
5101 errno = 0;
5102 interval = strtof(argv[argc - 1], &end);
5104 if (*end == '\0' && errno == 0) {
5105 if (interval == 0) {
5106 (void) fprintf(stderr, gettext(
5107 "interval cannot be zero\n"));
5108 usage(B_FALSE);
5111 * Ignore the last parameter
5113 argc--;
5114 } else {
5116 * If this is not a valid number, just plow on. The
5117 * user will get a more informative error message later
5118 * on.
5120 interval = 0;
5125 * If the last argument is also an integer, then we have both a count
5126 * and an interval.
5128 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5129 char *end;
5131 errno = 0;
5132 count = interval;
5133 interval = strtof(argv[argc - 1], &end);
5135 if (*end == '\0' && errno == 0) {
5136 if (interval == 0) {
5137 (void) fprintf(stderr, gettext(
5138 "interval cannot be zero\n"));
5139 usage(B_FALSE);
5143 * Ignore the last parameter
5145 argc--;
5146 } else {
5147 interval = 0;
5151 *iv = interval;
5152 *cnt = count;
5153 *argcp = argc;
5156 static void
5157 get_timestamp_arg(char c)
5159 if (c == 'u')
5160 timestamp_fmt = UDATE;
5161 else if (c == 'd')
5162 timestamp_fmt = DDATE;
5163 else
5164 usage(B_FALSE);
5168 * Return stat flags that are supported by all pools by both the module and
5169 * zpool iostat. "*data" should be initialized to all 0xFFs before running.
5170 * It will get ANDed down until only the flags that are supported on all pools
5171 * remain.
5173 static int
5174 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
5176 uint64_t *mask = data;
5177 nvlist_t *config, *nvroot, *nvx;
5178 uint64_t flags = 0;
5179 int i, j;
5181 config = zpool_get_config(zhp, NULL);
5182 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5183 &nvroot) == 0);
5185 /* Default stats are always supported, but for completeness.. */
5186 if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
5187 flags |= IOS_DEFAULT_M;
5189 /* Get our extended stats nvlist from the main list */
5190 if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
5191 &nvx) != 0) {
5193 * No extended stats; they're probably running an older
5194 * module. No big deal, we support that too.
5196 goto end;
5199 /* For each extended stat, make sure all its nvpairs are supported */
5200 for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
5201 if (!vsx_type_to_nvlist[j][0])
5202 continue;
5204 /* Start off by assuming the flag is supported, then check */
5205 flags |= (1ULL << j);
5206 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
5207 if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
5208 /* flag isn't supported */
5209 flags = flags & ~(1ULL << j);
5210 break;
5214 end:
5215 *mask = *mask & flags;
5216 return (0);
5220 * Return a bitmask of stats that are supported on all pools by both the module
5221 * and zpool iostat.
5223 static uint64_t
5224 get_stat_flags(zpool_list_t *list)
5226 uint64_t mask = -1;
5229 * get_stat_flags_cb() will lop off bits from "mask" until only the
5230 * flags that are supported on all pools remain.
5232 pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
5233 return (mask);
5237 * Return 1 if cb_data->cb_names[0] is this vdev's name, 0 otherwise.
5239 static int
5240 is_vdev_cb(void *zhp_data, nvlist_t *nv, void *cb_data)
5242 uint64_t guid;
5243 vdev_cbdata_t *cb = cb_data;
5244 zpool_handle_t *zhp = zhp_data;
5246 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
5247 return (0);
5249 return (guid == zpool_vdev_path_to_guid(zhp, cb->cb_names[0]));
5253 * Returns 1 if cb_data->cb_names[0] is a vdev name, 0 otherwise.
5255 static int
5256 is_vdev(zpool_handle_t *zhp, void *cb_data)
5258 return (for_each_vdev(zhp, is_vdev_cb, cb_data));
5262 * Check if vdevs are in a pool
5264 * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
5265 * return 0. If pool_name is NULL, then search all pools.
5267 static int
5268 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
5269 vdev_cbdata_t *cb)
5271 char **tmp_name;
5272 int ret = 0;
5273 int i;
5274 int pool_count = 0;
5276 if ((argc == 0) || !*argv)
5277 return (0);
5279 if (pool_name)
5280 pool_count = 1;
5282 /* Temporarily hijack cb_names for a second... */
5283 tmp_name = cb->cb_names;
5285 /* Go though our list of prospective vdev names */
5286 for (i = 0; i < argc; i++) {
5287 cb->cb_names = argv + i;
5289 /* Is this name a vdev in our pools? */
5290 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
5291 ZFS_TYPE_POOL, B_FALSE, is_vdev, cb);
5292 if (!ret) {
5293 /* No match */
5294 break;
5298 cb->cb_names = tmp_name;
5300 return (ret);
5303 static int
5304 is_pool_cb(zpool_handle_t *zhp, void *data)
5306 char *name = data;
5307 if (strcmp(name, zpool_get_name(zhp)) == 0)
5308 return (1);
5310 return (0);
5314 * Do we have a pool named *name? If so, return 1, otherwise 0.
5316 static int
5317 is_pool(char *name)
5319 return (for_each_pool(0, NULL, B_TRUE, NULL, ZFS_TYPE_POOL, B_FALSE,
5320 is_pool_cb, name));
5323 /* Are all our argv[] strings pool names? If so return 1, 0 otherwise. */
5324 static int
5325 are_all_pools(int argc, char **argv)
5327 if ((argc == 0) || !*argv)
5328 return (0);
5330 while (--argc >= 0)
5331 if (!is_pool(argv[argc]))
5332 return (0);
5334 return (1);
5338 * Helper function to print out vdev/pool names we can't resolve. Used for an
5339 * error message.
5341 static void
5342 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
5343 vdev_cbdata_t *cb)
5345 int i;
5346 char *name;
5347 char *str;
5348 for (i = 0; i < argc; i++) {
5349 name = argv[i];
5351 if (is_pool(name))
5352 str = gettext("pool");
5353 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
5354 str = gettext("vdev in this pool");
5355 else if (are_vdevs_in_pool(1, &name, NULL, cb))
5356 str = gettext("vdev in another pool");
5357 else
5358 str = gettext("unknown");
5360 fprintf(stderr, "\t%s (%s)\n", name, str);
5365 * Same as get_interval_count(), but with additional checks to not misinterpret
5366 * guids as interval/count values. Assumes VDEV_NAME_GUID is set in
5367 * cb.cb_vdevs.cb_name_flags.
5369 static void
5370 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
5371 unsigned long *count, iostat_cbdata_t *cb)
5373 char **tmpargv = argv;
5374 int argc_for_interval = 0;
5376 /* Is the last arg an interval value? Or a guid? */
5377 if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL,
5378 &cb->cb_vdevs)) {
5380 * The last arg is not a guid, so it's probably an
5381 * interval value.
5383 argc_for_interval++;
5385 if (*argc >= 2 &&
5386 !are_vdevs_in_pool(1, &argv[*argc - 2], NULL,
5387 &cb->cb_vdevs)) {
5389 * The 2nd to last arg is not a guid, so it's probably
5390 * an interval value.
5392 argc_for_interval++;
5396 /* Point to our list of possible intervals */
5397 tmpargv = &argv[*argc - argc_for_interval];
5399 *argc = *argc - argc_for_interval;
5400 get_interval_count(&argc_for_interval, tmpargv,
5401 interval, count);
5405 * Floating point sleep(). Allows you to pass in a floating point value for
5406 * seconds.
5408 static void
5409 fsleep(float sec)
5411 struct timespec req;
5412 req.tv_sec = floor(sec);
5413 req.tv_nsec = (sec - (float)req.tv_sec) * NANOSEC;
5414 nanosleep(&req, NULL);
5418 * Terminal height, in rows. Returns -1 if stdout is not connected to a TTY or
5419 * if we were unable to determine its size.
5421 static int
5422 terminal_height(void)
5424 struct winsize win;
5426 if (isatty(STDOUT_FILENO) == 0)
5427 return (-1);
5429 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_row > 0)
5430 return (win.ws_row);
5432 return (-1);
5436 * Run one of the zpool status/iostat -c scripts with the help (-h) option and
5437 * print the result.
5439 * name: Short name of the script ('iostat').
5440 * path: Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
5442 static void
5443 print_zpool_script_help(char *name, char *path)
5445 char *argv[] = {path, (char *)"-h", NULL};
5446 char **lines = NULL;
5447 int lines_cnt = 0;
5448 int rc;
5450 rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
5451 &lines_cnt);
5452 if (rc != 0 || lines == NULL || lines_cnt <= 0) {
5453 if (lines != NULL)
5454 libzfs_free_str_array(lines, lines_cnt);
5455 return;
5458 for (int i = 0; i < lines_cnt; i++)
5459 if (!is_blank_str(lines[i]))
5460 printf(" %-14s %s\n", name, lines[i]);
5462 libzfs_free_str_array(lines, lines_cnt);
5466 * Go though the zpool status/iostat -c scripts in the user's path, run their
5467 * help option (-h), and print out the results.
5469 static void
5470 print_zpool_dir_scripts(char *dirpath)
5472 DIR *dir;
5473 struct dirent *ent;
5474 char fullpath[MAXPATHLEN];
5475 struct stat dir_stat;
5477 if ((dir = opendir(dirpath)) != NULL) {
5478 /* print all the files and directories within directory */
5479 while ((ent = readdir(dir)) != NULL) {
5480 if (snprintf(fullpath, sizeof (fullpath), "%s/%s",
5481 dirpath, ent->d_name) >= sizeof (fullpath)) {
5482 (void) fprintf(stderr,
5483 gettext("internal error: "
5484 "ZPOOL_SCRIPTS_PATH too large.\n"));
5485 exit(1);
5488 /* Print the scripts */
5489 if (stat(fullpath, &dir_stat) == 0)
5490 if (dir_stat.st_mode & S_IXUSR &&
5491 S_ISREG(dir_stat.st_mode))
5492 print_zpool_script_help(ent->d_name,
5493 fullpath);
5495 closedir(dir);
5500 * Print out help text for all zpool status/iostat -c scripts.
5502 static void
5503 print_zpool_script_list(const char *subcommand)
5505 char *dir, *sp, *tmp;
5507 printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
5509 sp = zpool_get_cmd_search_path();
5510 if (sp == NULL)
5511 return;
5513 for (dir = strtok_r(sp, ":", &tmp);
5514 dir != NULL;
5515 dir = strtok_r(NULL, ":", &tmp))
5516 print_zpool_dir_scripts(dir);
5518 free(sp);
5522 * Set the minimum pool/vdev name column width. The width must be at least 10,
5523 * but may be as large as the column width - 42 so it still fits on one line.
5524 * NOTE: 42 is the width of the default capacity/operations/bandwidth output
5526 static int
5527 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
5529 iostat_cbdata_t *cb = data;
5530 int width, available_width;
5533 * get_namewidth() returns the maximum width of any name in that column
5534 * for any pool/vdev/device line that will be output.
5536 width = get_namewidth(zhp, cb->cb_namewidth,
5537 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
5540 * The width we are calculating is the width of the header and also the
5541 * padding width for names that are less than maximum width. The stats
5542 * take up 42 characters, so the width available for names is:
5544 available_width = get_columns() - 42;
5547 * If the maximum width fits on a screen, then great! Make everything
5548 * line up by justifying all lines to the same width. If that max
5549 * width is larger than what's available, the name plus stats won't fit
5550 * on one line, and justifying to that width would cause every line to
5551 * wrap on the screen. We only want lines with long names to wrap.
5552 * Limit the padding to what won't wrap.
5554 if (width > available_width)
5555 width = available_width;
5558 * And regardless of whatever the screen width is (get_columns can
5559 * return 0 if the width is not known or less than 42 for a narrow
5560 * terminal) have the width be a minimum of 10.
5562 if (width < 10)
5563 width = 10;
5565 /* Save the calculated width */
5566 cb->cb_namewidth = width;
5568 return (0);
5572 * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
5573 * [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
5574 * [interval [count]]
5576 * -c CMD For each vdev, run command CMD
5577 * -g Display guid for individual vdev name.
5578 * -L Follow links when resolving vdev path name.
5579 * -P Display full path for vdev name.
5580 * -v Display statistics for individual vdevs
5581 * -h Display help
5582 * -p Display values in parsable (exact) format.
5583 * -H Scripted mode. Don't display headers, and separate properties
5584 * by a single tab.
5585 * -l Display average latency
5586 * -q Display queue depths
5587 * -w Display latency histograms
5588 * -r Display request size histogram
5589 * -T Display a timestamp in date(1) or Unix format
5590 * -n Only print headers once
5592 * This command can be tricky because we want to be able to deal with pool
5593 * creation/destruction as well as vdev configuration changes. The bulk of this
5594 * processing is handled by the pool_list_* routines in zpool_iter.c. We rely
5595 * on pool_list_update() to detect the addition of new pools. Configuration
5596 * changes are all handled within libzfs.
5599 zpool_do_iostat(int argc, char **argv)
5601 int c;
5602 int ret;
5603 int npools;
5604 float interval = 0;
5605 unsigned long count = 0;
5606 int winheight = 24;
5607 zpool_list_t *list;
5608 boolean_t verbose = B_FALSE;
5609 boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
5610 boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
5611 boolean_t omit_since_boot = B_FALSE;
5612 boolean_t guid = B_FALSE;
5613 boolean_t follow_links = B_FALSE;
5614 boolean_t full_name = B_FALSE;
5615 boolean_t headers_once = B_FALSE;
5616 iostat_cbdata_t cb = { 0 };
5617 char *cmd = NULL;
5619 /* Used for printing error message */
5620 const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
5621 [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
5623 uint64_t unsupported_flags;
5625 /* check options */
5626 while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwnH")) != -1) {
5627 switch (c) {
5628 case 'c':
5629 if (cmd != NULL) {
5630 fprintf(stderr,
5631 gettext("Can't set -c flag twice\n"));
5632 exit(1);
5635 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
5636 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
5637 fprintf(stderr, gettext(
5638 "Can't run -c, disabled by "
5639 "ZPOOL_SCRIPTS_ENABLED.\n"));
5640 exit(1);
5643 if ((getuid() <= 0 || geteuid() <= 0) &&
5644 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
5645 fprintf(stderr, gettext(
5646 "Can't run -c with root privileges "
5647 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
5648 exit(1);
5650 cmd = optarg;
5651 verbose = B_TRUE;
5652 break;
5653 case 'g':
5654 guid = B_TRUE;
5655 break;
5656 case 'L':
5657 follow_links = B_TRUE;
5658 break;
5659 case 'P':
5660 full_name = B_TRUE;
5661 break;
5662 case 'T':
5663 get_timestamp_arg(*optarg);
5664 break;
5665 case 'v':
5666 verbose = B_TRUE;
5667 break;
5668 case 'p':
5669 parsable = B_TRUE;
5670 break;
5671 case 'l':
5672 latency = B_TRUE;
5673 break;
5674 case 'q':
5675 queues = B_TRUE;
5676 break;
5677 case 'H':
5678 scripted = B_TRUE;
5679 break;
5680 case 'w':
5681 l_histo = B_TRUE;
5682 break;
5683 case 'r':
5684 rq_histo = B_TRUE;
5685 break;
5686 case 'y':
5687 omit_since_boot = B_TRUE;
5688 break;
5689 case 'n':
5690 headers_once = B_TRUE;
5691 break;
5692 case 'h':
5693 usage(B_FALSE);
5694 break;
5695 case '?':
5696 if (optopt == 'c') {
5697 print_zpool_script_list("iostat");
5698 exit(0);
5699 } else {
5700 fprintf(stderr,
5701 gettext("invalid option '%c'\n"), optopt);
5703 usage(B_FALSE);
5707 argc -= optind;
5708 argv += optind;
5710 cb.cb_literal = parsable;
5711 cb.cb_scripted = scripted;
5713 if (guid)
5714 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_GUID;
5715 if (follow_links)
5716 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
5717 if (full_name)
5718 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_PATH;
5719 cb.cb_iteration = 0;
5720 cb.cb_namewidth = 0;
5721 cb.cb_verbose = verbose;
5723 /* Get our interval and count values (if any) */
5724 if (guid) {
5725 get_interval_count_filter_guids(&argc, argv, &interval,
5726 &count, &cb);
5727 } else {
5728 get_interval_count(&argc, argv, &interval, &count);
5731 if (argc == 0) {
5732 /* No args, so just print the defaults. */
5733 } else if (are_all_pools(argc, argv)) {
5734 /* All the args are pool names */
5735 } else if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
5736 /* All the args are vdevs */
5737 cb.cb_vdevs.cb_names = argv;
5738 cb.cb_vdevs.cb_names_count = argc;
5739 argc = 0; /* No pools to process */
5740 } else if (are_all_pools(1, argv)) {
5741 /* The first arg is a pool name */
5742 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
5743 &cb.cb_vdevs)) {
5744 /* ...and the rest are vdev names */
5745 cb.cb_vdevs.cb_names = argv + 1;
5746 cb.cb_vdevs.cb_names_count = argc - 1;
5747 argc = 1; /* One pool to process */
5748 } else {
5749 fprintf(stderr, gettext("Expected either a list of "));
5750 fprintf(stderr, gettext("pools, or list of vdevs in"));
5751 fprintf(stderr, " \"%s\", ", argv[0]);
5752 fprintf(stderr, gettext("but got:\n"));
5753 error_list_unresolved_vdevs(argc - 1, argv + 1,
5754 argv[0], &cb.cb_vdevs);
5755 fprintf(stderr, "\n");
5756 usage(B_FALSE);
5757 return (1);
5759 } else {
5761 * The args don't make sense. The first arg isn't a pool name,
5762 * nor are all the args vdevs.
5764 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
5765 fprintf(stderr, "\n");
5766 return (1);
5769 if (cb.cb_vdevs.cb_names_count != 0) {
5771 * If user specified vdevs, it implies verbose.
5773 cb.cb_verbose = B_TRUE;
5777 * Construct the list of all interesting pools.
5779 ret = 0;
5780 if ((list = pool_list_get(argc, argv, NULL, ZFS_TYPE_POOL, parsable,
5781 &ret)) == NULL)
5782 return (1);
5784 if (pool_list_count(list) == 0 && argc != 0) {
5785 pool_list_free(list);
5786 return (1);
5789 if (pool_list_count(list) == 0 && interval == 0) {
5790 pool_list_free(list);
5791 (void) fprintf(stderr, gettext("no pools available\n"));
5792 return (1);
5795 if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
5796 pool_list_free(list);
5797 (void) fprintf(stderr,
5798 gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
5799 usage(B_FALSE);
5800 return (1);
5803 if (l_histo && rq_histo) {
5804 pool_list_free(list);
5805 (void) fprintf(stderr,
5806 gettext("Only one of [-r|-w] can be passed at a time\n"));
5807 usage(B_FALSE);
5808 return (1);
5812 * Enter the main iostat loop.
5814 cb.cb_list = list;
5816 if (l_histo) {
5818 * Histograms tables look out of place when you try to display
5819 * them with the other stats, so make a rule that you can only
5820 * print histograms by themselves.
5822 cb.cb_flags = IOS_L_HISTO_M;
5823 } else if (rq_histo) {
5824 cb.cb_flags = IOS_RQ_HISTO_M;
5825 } else {
5826 cb.cb_flags = IOS_DEFAULT_M;
5827 if (latency)
5828 cb.cb_flags |= IOS_LATENCY_M;
5829 if (queues)
5830 cb.cb_flags |= IOS_QUEUES_M;
5834 * See if the module supports all the stats we want to display.
5836 unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
5837 if (unsupported_flags) {
5838 uint64_t f;
5839 int idx;
5840 fprintf(stderr,
5841 gettext("The loaded zfs module doesn't support:"));
5843 /* for each bit set in unsupported_flags */
5844 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
5845 idx = lowbit64(f) - 1;
5846 fprintf(stderr, " -%c", flag_to_arg[idx]);
5849 fprintf(stderr, ". Try running a newer module.\n");
5850 pool_list_free(list);
5852 return (1);
5855 for (;;) {
5856 if ((npools = pool_list_count(list)) == 0)
5857 (void) fprintf(stderr, gettext("no pools available\n"));
5858 else {
5860 * If this is the first iteration and -y was supplied
5861 * we skip any printing.
5863 boolean_t skip = (omit_since_boot &&
5864 cb.cb_iteration == 0);
5867 * Refresh all statistics. This is done as an
5868 * explicit step before calculating the maximum name
5869 * width, so that any * configuration changes are
5870 * properly accounted for.
5872 (void) pool_list_iter(list, B_FALSE, refresh_iostat,
5873 &cb);
5876 * Iterate over all pools to determine the maximum width
5877 * for the pool / device name column across all pools.
5879 cb.cb_namewidth = 0;
5880 (void) pool_list_iter(list, B_FALSE,
5881 get_namewidth_iostat, &cb);
5883 if (timestamp_fmt != NODATE)
5884 print_timestamp(timestamp_fmt);
5886 if (cmd != NULL && cb.cb_verbose &&
5887 !(cb.cb_flags & IOS_ANYHISTO_M)) {
5888 cb.vcdl = all_pools_for_each_vdev_run(argc,
5889 argv, cmd, g_zfs, cb.cb_vdevs.cb_names,
5890 cb.cb_vdevs.cb_names_count,
5891 cb.cb_vdevs.cb_name_flags);
5892 } else {
5893 cb.vcdl = NULL;
5898 * Check terminal size so we can print headers
5899 * even when terminal window has its height
5900 * changed.
5902 winheight = terminal_height();
5904 * Are we connected to TTY? If not, headers_once
5905 * should be true, to avoid breaking scripts.
5907 if (winheight < 0)
5908 headers_once = B_TRUE;
5911 * If it's the first time and we're not skipping it,
5912 * or either skip or verbose mode, print the header.
5914 * The histogram code explicitly prints its header on
5915 * every vdev, so skip this for histograms.
5917 if (((++cb.cb_iteration == 1 && !skip) ||
5918 (skip != verbose) ||
5919 (!headers_once &&
5920 (cb.cb_iteration % winheight) == 0)) &&
5921 (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
5922 !cb.cb_scripted)
5923 print_iostat_header(&cb);
5925 if (skip) {
5926 (void) fsleep(interval);
5927 continue;
5930 pool_list_iter(list, B_FALSE, print_iostat, &cb);
5933 * If there's more than one pool, and we're not in
5934 * verbose mode (which prints a separator for us),
5935 * then print a separator.
5937 * In addition, if we're printing specific vdevs then
5938 * we also want an ending separator.
5940 if (((npools > 1 && !verbose &&
5941 !(cb.cb_flags & IOS_ANYHISTO_M)) ||
5942 (!(cb.cb_flags & IOS_ANYHISTO_M) &&
5943 cb.cb_vdevs.cb_names_count)) &&
5944 !cb.cb_scripted) {
5945 print_iostat_separator(&cb);
5946 if (cb.vcdl != NULL)
5947 print_cmd_columns(cb.vcdl, 1);
5948 printf("\n");
5951 if (cb.vcdl != NULL)
5952 free_vdev_cmd_data_list(cb.vcdl);
5957 * Flush the output so that redirection to a file isn't buffered
5958 * indefinitely.
5960 (void) fflush(stdout);
5962 if (interval == 0)
5963 break;
5965 if (count != 0 && --count == 0)
5966 break;
5968 (void) fsleep(interval);
5971 pool_list_free(list);
5973 return (ret);
5976 typedef struct list_cbdata {
5977 boolean_t cb_verbose;
5978 int cb_name_flags;
5979 int cb_namewidth;
5980 boolean_t cb_scripted;
5981 zprop_list_t *cb_proplist;
5982 boolean_t cb_literal;
5983 } list_cbdata_t;
5987 * Given a list of columns to display, output appropriate headers for each one.
5989 static void
5990 print_header(list_cbdata_t *cb)
5992 zprop_list_t *pl = cb->cb_proplist;
5993 char headerbuf[ZPOOL_MAXPROPLEN];
5994 const char *header;
5995 boolean_t first = B_TRUE;
5996 boolean_t right_justify;
5997 size_t width = 0;
5999 for (; pl != NULL; pl = pl->pl_next) {
6000 width = pl->pl_width;
6001 if (first && cb->cb_verbose) {
6003 * Reset the width to accommodate the verbose listing
6004 * of devices.
6006 width = cb->cb_namewidth;
6009 if (!first)
6010 (void) fputs(" ", stdout);
6011 else
6012 first = B_FALSE;
6014 right_justify = B_FALSE;
6015 if (pl->pl_prop != ZPROP_USERPROP) {
6016 header = zpool_prop_column_name(pl->pl_prop);
6017 right_justify = zpool_prop_align_right(pl->pl_prop);
6018 } else {
6019 int i;
6021 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
6022 headerbuf[i] = toupper(pl->pl_user_prop[i]);
6023 headerbuf[i] = '\0';
6024 header = headerbuf;
6027 if (pl->pl_next == NULL && !right_justify)
6028 (void) fputs(header, stdout);
6029 else if (right_justify)
6030 (void) printf("%*s", (int)width, header);
6031 else
6032 (void) printf("%-*s", (int)width, header);
6035 (void) fputc('\n', stdout);
6039 * Given a pool and a list of properties, print out all the properties according
6040 * to the described layout. Used by zpool_do_list().
6042 static void
6043 print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
6045 zprop_list_t *pl = cb->cb_proplist;
6046 boolean_t first = B_TRUE;
6047 char property[ZPOOL_MAXPROPLEN];
6048 const char *propstr;
6049 boolean_t right_justify;
6050 size_t width;
6052 for (; pl != NULL; pl = pl->pl_next) {
6054 width = pl->pl_width;
6055 if (first && cb->cb_verbose) {
6057 * Reset the width to accommodate the verbose listing
6058 * of devices.
6060 width = cb->cb_namewidth;
6063 if (!first) {
6064 if (cb->cb_scripted)
6065 (void) fputc('\t', stdout);
6066 else
6067 (void) fputs(" ", stdout);
6068 } else {
6069 first = B_FALSE;
6072 right_justify = B_FALSE;
6073 if (pl->pl_prop != ZPROP_USERPROP) {
6074 if (zpool_get_prop(zhp, pl->pl_prop, property,
6075 sizeof (property), NULL, cb->cb_literal) != 0)
6076 propstr = "-";
6077 else
6078 propstr = property;
6080 right_justify = zpool_prop_align_right(pl->pl_prop);
6081 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
6082 zpool_prop_unsupported(pl->pl_user_prop)) &&
6083 zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
6084 sizeof (property)) == 0) {
6085 propstr = property;
6086 } else if (zfs_prop_user(pl->pl_user_prop) &&
6087 zpool_get_userprop(zhp, pl->pl_user_prop, property,
6088 sizeof (property), NULL) == 0) {
6089 propstr = property;
6090 } else {
6091 propstr = "-";
6095 * If this is being called in scripted mode, or if this is the
6096 * last column and it is left-justified, don't include a width
6097 * format specifier.
6099 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
6100 (void) fputs(propstr, stdout);
6101 else if (right_justify)
6102 (void) printf("%*s", (int)width, propstr);
6103 else
6104 (void) printf("%-*s", (int)width, propstr);
6107 (void) fputc('\n', stdout);
6110 static void
6111 print_one_column(zpool_prop_t prop, uint64_t value, const char *str,
6112 boolean_t scripted, boolean_t valid, enum zfs_nicenum_format format)
6114 char propval[64];
6115 boolean_t fixed;
6116 size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
6118 switch (prop) {
6119 case ZPOOL_PROP_SIZE:
6120 case ZPOOL_PROP_EXPANDSZ:
6121 case ZPOOL_PROP_CHECKPOINT:
6122 case ZPOOL_PROP_DEDUPRATIO:
6123 if (value == 0)
6124 (void) strlcpy(propval, "-", sizeof (propval));
6125 else
6126 zfs_nicenum_format(value, propval, sizeof (propval),
6127 format);
6128 break;
6129 case ZPOOL_PROP_FRAGMENTATION:
6130 if (value == ZFS_FRAG_INVALID) {
6131 (void) strlcpy(propval, "-", sizeof (propval));
6132 } else if (format == ZFS_NICENUM_RAW) {
6133 (void) snprintf(propval, sizeof (propval), "%llu",
6134 (unsigned long long)value);
6135 } else {
6136 (void) snprintf(propval, sizeof (propval), "%llu%%",
6137 (unsigned long long)value);
6139 break;
6140 case ZPOOL_PROP_CAPACITY:
6141 /* capacity value is in parts-per-10,000 (aka permyriad) */
6142 if (format == ZFS_NICENUM_RAW)
6143 (void) snprintf(propval, sizeof (propval), "%llu",
6144 (unsigned long long)value / 100);
6145 else
6146 (void) snprintf(propval, sizeof (propval),
6147 value < 1000 ? "%1.2f%%" : value < 10000 ?
6148 "%2.1f%%" : "%3.0f%%", value / 100.0);
6149 break;
6150 case ZPOOL_PROP_HEALTH:
6151 width = 8;
6152 (void) strlcpy(propval, str, sizeof (propval));
6153 break;
6154 default:
6155 zfs_nicenum_format(value, propval, sizeof (propval), format);
6158 if (!valid)
6159 (void) strlcpy(propval, "-", sizeof (propval));
6161 if (scripted)
6162 (void) printf("\t%s", propval);
6163 else
6164 (void) printf(" %*s", (int)width, propval);
6168 * print static default line per vdev
6169 * not compatible with '-o' <proplist> option
6171 static void
6172 print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
6173 list_cbdata_t *cb, int depth, boolean_t isspare)
6175 nvlist_t **child;
6176 vdev_stat_t *vs;
6177 uint_t c, children;
6178 char *vname;
6179 boolean_t scripted = cb->cb_scripted;
6180 uint64_t islog = B_FALSE;
6181 const char *dashes = "%-*s - - - - "
6182 "- - - - -\n";
6184 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
6185 (uint64_t **)&vs, &c) == 0);
6187 if (name != NULL) {
6188 boolean_t toplevel = (vs->vs_space != 0);
6189 uint64_t cap;
6190 enum zfs_nicenum_format format;
6191 const char *state;
6193 if (cb->cb_literal)
6194 format = ZFS_NICENUM_RAW;
6195 else
6196 format = ZFS_NICENUM_1024;
6198 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
6199 return;
6201 if (scripted)
6202 (void) printf("\t%s", name);
6203 else if (strlen(name) + depth > cb->cb_namewidth)
6204 (void) printf("%*s%s", depth, "", name);
6205 else
6206 (void) printf("%*s%s%*s", depth, "", name,
6207 (int)(cb->cb_namewidth - strlen(name) - depth), "");
6210 * Print the properties for the individual vdevs. Some
6211 * properties are only applicable to toplevel vdevs. The
6212 * 'toplevel' boolean value is passed to the print_one_column()
6213 * to indicate that the value is valid.
6215 if (VDEV_STAT_VALID(vs_pspace, c) && vs->vs_pspace)
6216 print_one_column(ZPOOL_PROP_SIZE, vs->vs_pspace, NULL,
6217 scripted, B_TRUE, format);
6218 else
6219 print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, NULL,
6220 scripted, toplevel, format);
6221 print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, NULL,
6222 scripted, toplevel, format);
6223 print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
6224 NULL, scripted, toplevel, format);
6225 print_one_column(ZPOOL_PROP_CHECKPOINT,
6226 vs->vs_checkpoint_space, NULL, scripted, toplevel, format);
6227 print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, NULL,
6228 scripted, B_TRUE, format);
6229 print_one_column(ZPOOL_PROP_FRAGMENTATION,
6230 vs->vs_fragmentation, NULL, scripted,
6231 (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
6232 format);
6233 cap = (vs->vs_space == 0) ? 0 :
6234 (vs->vs_alloc * 10000 / vs->vs_space);
6235 print_one_column(ZPOOL_PROP_CAPACITY, cap, NULL,
6236 scripted, toplevel, format);
6237 print_one_column(ZPOOL_PROP_DEDUPRATIO, 0, NULL,
6238 scripted, toplevel, format);
6239 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
6240 if (isspare) {
6241 if (vs->vs_aux == VDEV_AUX_SPARED)
6242 state = "INUSE";
6243 else if (vs->vs_state == VDEV_STATE_HEALTHY)
6244 state = "AVAIL";
6246 print_one_column(ZPOOL_PROP_HEALTH, 0, state, scripted,
6247 B_TRUE, format);
6248 (void) fputc('\n', stdout);
6251 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
6252 &child, &children) != 0)
6253 return;
6255 /* list the normal vdevs first */
6256 for (c = 0; c < children; c++) {
6257 uint64_t ishole = B_FALSE;
6259 if (nvlist_lookup_uint64(child[c],
6260 ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
6261 continue;
6263 if (nvlist_lookup_uint64(child[c],
6264 ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
6265 continue;
6267 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
6268 continue;
6270 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6271 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
6272 print_list_stats(zhp, vname, child[c], cb, depth + 2, B_FALSE);
6273 free(vname);
6276 /* list the classes: 'logs', 'dedup', and 'special' */
6277 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
6278 boolean_t printed = B_FALSE;
6280 for (c = 0; c < children; c++) {
6281 const char *bias = NULL;
6282 const char *type = NULL;
6284 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
6285 &islog) == 0 && islog) {
6286 bias = VDEV_ALLOC_CLASS_LOGS;
6287 } else {
6288 (void) nvlist_lookup_string(child[c],
6289 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
6290 (void) nvlist_lookup_string(child[c],
6291 ZPOOL_CONFIG_TYPE, &type);
6293 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
6294 continue;
6295 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
6296 continue;
6298 if (!printed) {
6299 /* LINTED E_SEC_PRINTF_VAR_FMT */
6300 (void) printf(dashes, cb->cb_namewidth,
6301 class_name[n]);
6302 printed = B_TRUE;
6304 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6305 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
6306 print_list_stats(zhp, vname, child[c], cb, depth + 2,
6307 B_FALSE);
6308 free(vname);
6312 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
6313 &child, &children) == 0 && children > 0) {
6314 /* LINTED E_SEC_PRINTF_VAR_FMT */
6315 (void) printf(dashes, cb->cb_namewidth, "cache");
6316 for (c = 0; c < children; c++) {
6317 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6318 cb->cb_name_flags);
6319 print_list_stats(zhp, vname, child[c], cb, depth + 2,
6320 B_FALSE);
6321 free(vname);
6325 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
6326 &children) == 0 && children > 0) {
6327 /* LINTED E_SEC_PRINTF_VAR_FMT */
6328 (void) printf(dashes, cb->cb_namewidth, "spare");
6329 for (c = 0; c < children; c++) {
6330 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6331 cb->cb_name_flags);
6332 print_list_stats(zhp, vname, child[c], cb, depth + 2,
6333 B_TRUE);
6334 free(vname);
6340 * Generic callback function to list a pool.
6342 static int
6343 list_callback(zpool_handle_t *zhp, void *data)
6345 list_cbdata_t *cbp = data;
6347 print_pool(zhp, cbp);
6349 if (cbp->cb_verbose) {
6350 nvlist_t *config, *nvroot;
6352 config = zpool_get_config(zhp, NULL);
6353 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
6354 &nvroot) == 0);
6355 print_list_stats(zhp, NULL, nvroot, cbp, 0, B_FALSE);
6358 return (0);
6362 * Set the minimum pool/vdev name column width. The width must be at least 9,
6363 * but may be as large as needed.
6365 static int
6366 get_namewidth_list(zpool_handle_t *zhp, void *data)
6368 list_cbdata_t *cb = data;
6369 int width;
6371 width = get_namewidth(zhp, cb->cb_namewidth,
6372 cb->cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
6374 if (width < 9)
6375 width = 9;
6377 cb->cb_namewidth = width;
6379 return (0);
6383 * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
6385 * -g Display guid for individual vdev name.
6386 * -H Scripted mode. Don't display headers, and separate properties
6387 * by a single tab.
6388 * -L Follow links when resolving vdev path name.
6389 * -o List of properties to display. Defaults to
6390 * "name,size,allocated,free,expandsize,fragmentation,capacity,"
6391 * "dedupratio,health,altroot"
6392 * -p Display values in parsable (exact) format.
6393 * -P Display full path for vdev name.
6394 * -T Display a timestamp in date(1) or Unix format
6396 * List all pools in the system, whether or not they're healthy. Output space
6397 * statistics for each one, as well as health status summary.
6400 zpool_do_list(int argc, char **argv)
6402 int c;
6403 int ret = 0;
6404 list_cbdata_t cb = { 0 };
6405 static char default_props[] =
6406 "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
6407 "capacity,dedupratio,health,altroot";
6408 char *props = default_props;
6409 float interval = 0;
6410 unsigned long count = 0;
6411 zpool_list_t *list;
6412 boolean_t first = B_TRUE;
6413 current_prop_type = ZFS_TYPE_POOL;
6415 /* check options */
6416 while ((c = getopt(argc, argv, ":gHLo:pPT:v")) != -1) {
6417 switch (c) {
6418 case 'g':
6419 cb.cb_name_flags |= VDEV_NAME_GUID;
6420 break;
6421 case 'H':
6422 cb.cb_scripted = B_TRUE;
6423 break;
6424 case 'L':
6425 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6426 break;
6427 case 'o':
6428 props = optarg;
6429 break;
6430 case 'P':
6431 cb.cb_name_flags |= VDEV_NAME_PATH;
6432 break;
6433 case 'p':
6434 cb.cb_literal = B_TRUE;
6435 break;
6436 case 'T':
6437 get_timestamp_arg(*optarg);
6438 break;
6439 case 'v':
6440 cb.cb_verbose = B_TRUE;
6441 cb.cb_namewidth = 8; /* 8 until precalc is avail */
6442 break;
6443 case ':':
6444 (void) fprintf(stderr, gettext("missing argument for "
6445 "'%c' option\n"), optopt);
6446 usage(B_FALSE);
6447 break;
6448 case '?':
6449 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6450 optopt);
6451 usage(B_FALSE);
6455 argc -= optind;
6456 argv += optind;
6458 get_interval_count(&argc, argv, &interval, &count);
6460 if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
6461 usage(B_FALSE);
6463 for (;;) {
6464 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
6465 ZFS_TYPE_POOL, cb.cb_literal, &ret)) == NULL)
6466 return (1);
6468 if (pool_list_count(list) == 0)
6469 break;
6471 cb.cb_namewidth = 0;
6472 (void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
6474 if (timestamp_fmt != NODATE)
6475 print_timestamp(timestamp_fmt);
6477 if (!cb.cb_scripted && (first || cb.cb_verbose)) {
6478 print_header(&cb);
6479 first = B_FALSE;
6481 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
6483 if (interval == 0)
6484 break;
6486 if (count != 0 && --count == 0)
6487 break;
6489 pool_list_free(list);
6490 (void) fsleep(interval);
6493 if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
6494 (void) printf(gettext("no pools available\n"));
6495 ret = 0;
6498 pool_list_free(list);
6499 zprop_free_list(cb.cb_proplist);
6500 return (ret);
6503 static int
6504 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
6506 boolean_t force = B_FALSE;
6507 boolean_t rebuild = B_FALSE;
6508 boolean_t wait = B_FALSE;
6509 int c;
6510 nvlist_t *nvroot;
6511 char *poolname, *old_disk, *new_disk;
6512 zpool_handle_t *zhp;
6513 nvlist_t *props = NULL;
6514 char *propval;
6515 int ret;
6517 /* check options */
6518 while ((c = getopt(argc, argv, "fo:sw")) != -1) {
6519 switch (c) {
6520 case 'f':
6521 force = B_TRUE;
6522 break;
6523 case 'o':
6524 if ((propval = strchr(optarg, '=')) == NULL) {
6525 (void) fprintf(stderr, gettext("missing "
6526 "'=' for -o option\n"));
6527 usage(B_FALSE);
6529 *propval = '\0';
6530 propval++;
6532 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
6533 (add_prop_list(optarg, propval, &props, B_TRUE)))
6534 usage(B_FALSE);
6535 break;
6536 case 's':
6537 rebuild = B_TRUE;
6538 break;
6539 case 'w':
6540 wait = B_TRUE;
6541 break;
6542 case '?':
6543 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6544 optopt);
6545 usage(B_FALSE);
6549 argc -= optind;
6550 argv += optind;
6552 /* get pool name and check number of arguments */
6553 if (argc < 1) {
6554 (void) fprintf(stderr, gettext("missing pool name argument\n"));
6555 usage(B_FALSE);
6558 poolname = argv[0];
6560 if (argc < 2) {
6561 (void) fprintf(stderr,
6562 gettext("missing <device> specification\n"));
6563 usage(B_FALSE);
6566 old_disk = argv[1];
6568 if (argc < 3) {
6569 if (!replacing) {
6570 (void) fprintf(stderr,
6571 gettext("missing <new_device> specification\n"));
6572 usage(B_FALSE);
6574 new_disk = old_disk;
6575 argc -= 1;
6576 argv += 1;
6577 } else {
6578 new_disk = argv[2];
6579 argc -= 2;
6580 argv += 2;
6583 if (argc > 1) {
6584 (void) fprintf(stderr, gettext("too many arguments\n"));
6585 usage(B_FALSE);
6588 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
6589 nvlist_free(props);
6590 return (1);
6593 if (zpool_get_config(zhp, NULL) == NULL) {
6594 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
6595 poolname);
6596 zpool_close(zhp);
6597 nvlist_free(props);
6598 return (1);
6601 /* unless manually specified use "ashift" pool property (if set) */
6602 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
6603 int intval;
6604 zprop_source_t src;
6605 char strval[ZPOOL_MAXPROPLEN];
6607 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
6608 if (src != ZPROP_SRC_DEFAULT) {
6609 (void) sprintf(strval, "%" PRId32, intval);
6610 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
6611 &props, B_TRUE) == 0);
6615 nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
6616 argc, argv);
6617 if (nvroot == NULL) {
6618 zpool_close(zhp);
6619 nvlist_free(props);
6620 return (1);
6623 ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing,
6624 rebuild);
6626 if (ret == 0 && wait)
6627 ret = zpool_wait(zhp,
6628 replacing ? ZPOOL_WAIT_REPLACE : ZPOOL_WAIT_RESILVER);
6630 nvlist_free(props);
6631 nvlist_free(nvroot);
6632 zpool_close(zhp);
6634 return (ret);
6638 * zpool replace [-fsw] [-o property=value] <pool> <device> <new_device>
6640 * -f Force attach, even if <new_device> appears to be in use.
6641 * -s Use sequential instead of healing reconstruction for resilver.
6642 * -o Set property=value.
6643 * -w Wait for replacing to complete before returning
6645 * Replace <device> with <new_device>.
6648 zpool_do_replace(int argc, char **argv)
6650 return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
6654 * zpool attach [-fsw] [-o property=value] <pool> <device> <new_device>
6656 * -f Force attach, even if <new_device> appears to be in use.
6657 * -s Use sequential instead of healing reconstruction for resilver.
6658 * -o Set property=value.
6659 * -w Wait for resilvering to complete before returning
6661 * Attach <new_device> to the mirror containing <device>. If <device> is not
6662 * part of a mirror, then <device> will be transformed into a mirror of
6663 * <device> and <new_device>. In either case, <new_device> will begin life
6664 * with a DTL of [0, now], and will immediately begin to resilver itself.
6667 zpool_do_attach(int argc, char **argv)
6669 return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
6673 * zpool detach [-f] <pool> <device>
6675 * -f Force detach of <device>, even if DTLs argue against it
6676 * (not supported yet)
6678 * Detach a device from a mirror. The operation will be refused if <device>
6679 * is the last device in the mirror, or if the DTLs indicate that this device
6680 * has the only valid copy of some data.
6683 zpool_do_detach(int argc, char **argv)
6685 int c;
6686 char *poolname, *path;
6687 zpool_handle_t *zhp;
6688 int ret;
6690 /* check options */
6691 while ((c = getopt(argc, argv, "")) != -1) {
6692 switch (c) {
6693 case '?':
6694 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6695 optopt);
6696 usage(B_FALSE);
6700 argc -= optind;
6701 argv += optind;
6703 /* get pool name and check number of arguments */
6704 if (argc < 1) {
6705 (void) fprintf(stderr, gettext("missing pool name argument\n"));
6706 usage(B_FALSE);
6709 if (argc < 2) {
6710 (void) fprintf(stderr,
6711 gettext("missing <device> specification\n"));
6712 usage(B_FALSE);
6715 poolname = argv[0];
6716 path = argv[1];
6718 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6719 return (1);
6721 ret = zpool_vdev_detach(zhp, path);
6723 zpool_close(zhp);
6725 return (ret);
6729 * zpool split [-gLnP] [-o prop=val] ...
6730 * [-o mntopt] ...
6731 * [-R altroot] <pool> <newpool> [<device> ...]
6733 * -g Display guid for individual vdev name.
6734 * -L Follow links when resolving vdev path name.
6735 * -n Do not split the pool, but display the resulting layout if
6736 * it were to be split.
6737 * -o Set property=value, or set mount options.
6738 * -P Display full path for vdev name.
6739 * -R Mount the split-off pool under an alternate root.
6740 * -l Load encryption keys while importing.
6742 * Splits the named pool and gives it the new pool name. Devices to be split
6743 * off may be listed, provided that no more than one device is specified
6744 * per top-level vdev mirror. The newly split pool is left in an exported
6745 * state unless -R is specified.
6747 * Restrictions: the top-level of the pool pool must only be made up of
6748 * mirrors; all devices in the pool must be healthy; no device may be
6749 * undergoing a resilvering operation.
6752 zpool_do_split(int argc, char **argv)
6754 char *srcpool, *newpool, *propval;
6755 char *mntopts = NULL;
6756 splitflags_t flags;
6757 int c, ret = 0;
6758 boolean_t loadkeys = B_FALSE;
6759 zpool_handle_t *zhp;
6760 nvlist_t *config, *props = NULL;
6762 flags.dryrun = B_FALSE;
6763 flags.import = B_FALSE;
6764 flags.name_flags = 0;
6766 /* check options */
6767 while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
6768 switch (c) {
6769 case 'g':
6770 flags.name_flags |= VDEV_NAME_GUID;
6771 break;
6772 case 'L':
6773 flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
6774 break;
6775 case 'R':
6776 flags.import = B_TRUE;
6777 if (add_prop_list(
6778 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
6779 &props, B_TRUE) != 0) {
6780 nvlist_free(props);
6781 usage(B_FALSE);
6783 break;
6784 case 'l':
6785 loadkeys = B_TRUE;
6786 break;
6787 case 'n':
6788 flags.dryrun = B_TRUE;
6789 break;
6790 case 'o':
6791 if ((propval = strchr(optarg, '=')) != NULL) {
6792 *propval = '\0';
6793 propval++;
6794 if (add_prop_list(optarg, propval,
6795 &props, B_TRUE) != 0) {
6796 nvlist_free(props);
6797 usage(B_FALSE);
6799 } else {
6800 mntopts = optarg;
6802 break;
6803 case 'P':
6804 flags.name_flags |= VDEV_NAME_PATH;
6805 break;
6806 case ':':
6807 (void) fprintf(stderr, gettext("missing argument for "
6808 "'%c' option\n"), optopt);
6809 usage(B_FALSE);
6810 break;
6811 case '?':
6812 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6813 optopt);
6814 usage(B_FALSE);
6815 break;
6819 if (!flags.import && mntopts != NULL) {
6820 (void) fprintf(stderr, gettext("setting mntopts is only "
6821 "valid when importing the pool\n"));
6822 usage(B_FALSE);
6825 if (!flags.import && loadkeys) {
6826 (void) fprintf(stderr, gettext("loading keys is only "
6827 "valid when importing the pool\n"));
6828 usage(B_FALSE);
6831 argc -= optind;
6832 argv += optind;
6834 if (argc < 1) {
6835 (void) fprintf(stderr, gettext("Missing pool name\n"));
6836 usage(B_FALSE);
6838 if (argc < 2) {
6839 (void) fprintf(stderr, gettext("Missing new pool name\n"));
6840 usage(B_FALSE);
6843 srcpool = argv[0];
6844 newpool = argv[1];
6846 argc -= 2;
6847 argv += 2;
6849 if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
6850 nvlist_free(props);
6851 return (1);
6854 config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
6855 if (config == NULL) {
6856 ret = 1;
6857 } else {
6858 if (flags.dryrun) {
6859 (void) printf(gettext("would create '%s' with the "
6860 "following layout:\n\n"), newpool);
6861 print_vdev_tree(NULL, newpool, config, 0, "",
6862 flags.name_flags);
6863 print_vdev_tree(NULL, "dedup", config, 0,
6864 VDEV_ALLOC_BIAS_DEDUP, 0);
6865 print_vdev_tree(NULL, "special", config, 0,
6866 VDEV_ALLOC_BIAS_SPECIAL, 0);
6870 zpool_close(zhp);
6872 if (ret != 0 || flags.dryrun || !flags.import) {
6873 nvlist_free(config);
6874 nvlist_free(props);
6875 return (ret);
6879 * The split was successful. Now we need to open the new
6880 * pool and import it.
6882 if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
6883 nvlist_free(config);
6884 nvlist_free(props);
6885 return (1);
6888 if (loadkeys) {
6889 ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
6890 if (ret != 0)
6891 ret = 1;
6894 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
6895 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
6896 ret = 1;
6897 (void) fprintf(stderr, gettext("Split was successful, but "
6898 "the datasets could not all be mounted\n"));
6899 (void) fprintf(stderr, gettext("Try doing '%s' with a "
6900 "different altroot\n"), "zpool import");
6902 zpool_close(zhp);
6903 nvlist_free(config);
6904 nvlist_free(props);
6906 return (ret);
6912 * zpool online <pool> <device> ...
6915 zpool_do_online(int argc, char **argv)
6917 int c, i;
6918 char *poolname;
6919 zpool_handle_t *zhp;
6920 int ret = 0;
6921 vdev_state_t newstate;
6922 int flags = 0;
6924 /* check options */
6925 while ((c = getopt(argc, argv, "e")) != -1) {
6926 switch (c) {
6927 case 'e':
6928 flags |= ZFS_ONLINE_EXPAND;
6929 break;
6930 case '?':
6931 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6932 optopt);
6933 usage(B_FALSE);
6937 argc -= optind;
6938 argv += optind;
6940 /* get pool name and check number of arguments */
6941 if (argc < 1) {
6942 (void) fprintf(stderr, gettext("missing pool name\n"));
6943 usage(B_FALSE);
6945 if (argc < 2) {
6946 (void) fprintf(stderr, gettext("missing device name\n"));
6947 usage(B_FALSE);
6950 poolname = argv[0];
6952 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6953 return (1);
6955 for (i = 1; i < argc; i++) {
6956 vdev_state_t oldstate;
6957 boolean_t avail_spare, l2cache;
6958 nvlist_t *tgt = zpool_find_vdev(zhp, argv[i], &avail_spare,
6959 &l2cache, NULL);
6960 if (tgt == NULL) {
6961 ret = 1;
6962 continue;
6964 uint_t vsc;
6965 oldstate = ((vdev_stat_t *)fnvlist_lookup_uint64_array(tgt,
6966 ZPOOL_CONFIG_VDEV_STATS, &vsc))->vs_state;
6967 if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
6968 if (newstate != VDEV_STATE_HEALTHY) {
6969 (void) printf(gettext("warning: device '%s' "
6970 "onlined, but remains in faulted state\n"),
6971 argv[i]);
6972 if (newstate == VDEV_STATE_FAULTED)
6973 (void) printf(gettext("use 'zpool "
6974 "clear' to restore a faulted "
6975 "device\n"));
6976 else
6977 (void) printf(gettext("use 'zpool "
6978 "replace' to replace devices "
6979 "that are no longer present\n"));
6980 if ((flags & ZFS_ONLINE_EXPAND)) {
6981 (void) printf(gettext("%s: failed "
6982 "to expand usable space on "
6983 "unhealthy device '%s'\n"),
6984 (oldstate >= VDEV_STATE_DEGRADED ?
6985 "error" : "warning"), argv[i]);
6986 if (oldstate >= VDEV_STATE_DEGRADED) {
6987 ret = 1;
6988 break;
6992 } else {
6993 ret = 1;
6997 zpool_close(zhp);
6999 return (ret);
7003 * zpool offline [-ft] <pool> <device> ...
7005 * -f Force the device into a faulted state.
7007 * -t Only take the device off-line temporarily. The offline/faulted
7008 * state will not be persistent across reboots.
7011 zpool_do_offline(int argc, char **argv)
7013 int c, i;
7014 char *poolname;
7015 zpool_handle_t *zhp;
7016 int ret = 0;
7017 boolean_t istmp = B_FALSE;
7018 boolean_t fault = B_FALSE;
7020 /* check options */
7021 while ((c = getopt(argc, argv, "ft")) != -1) {
7022 switch (c) {
7023 case 'f':
7024 fault = B_TRUE;
7025 break;
7026 case 't':
7027 istmp = B_TRUE;
7028 break;
7029 case '?':
7030 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7031 optopt);
7032 usage(B_FALSE);
7036 argc -= optind;
7037 argv += optind;
7039 /* get pool name and check number of arguments */
7040 if (argc < 1) {
7041 (void) fprintf(stderr, gettext("missing pool name\n"));
7042 usage(B_FALSE);
7044 if (argc < 2) {
7045 (void) fprintf(stderr, gettext("missing device name\n"));
7046 usage(B_FALSE);
7049 poolname = argv[0];
7051 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7052 return (1);
7054 for (i = 1; i < argc; i++) {
7055 if (fault) {
7056 uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
7057 vdev_aux_t aux;
7058 if (istmp == B_FALSE) {
7059 /* Force the fault to persist across imports */
7060 aux = VDEV_AUX_EXTERNAL_PERSIST;
7061 } else {
7062 aux = VDEV_AUX_EXTERNAL;
7065 if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
7066 ret = 1;
7067 } else {
7068 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
7069 ret = 1;
7073 zpool_close(zhp);
7075 return (ret);
7079 * zpool clear <pool> [device]
7081 * Clear all errors associated with a pool or a particular device.
7084 zpool_do_clear(int argc, char **argv)
7086 int c;
7087 int ret = 0;
7088 boolean_t dryrun = B_FALSE;
7089 boolean_t do_rewind = B_FALSE;
7090 boolean_t xtreme_rewind = B_FALSE;
7091 uint32_t rewind_policy = ZPOOL_NO_REWIND;
7092 nvlist_t *policy = NULL;
7093 zpool_handle_t *zhp;
7094 char *pool, *device;
7096 /* check options */
7097 while ((c = getopt(argc, argv, "FnX")) != -1) {
7098 switch (c) {
7099 case 'F':
7100 do_rewind = B_TRUE;
7101 break;
7102 case 'n':
7103 dryrun = B_TRUE;
7104 break;
7105 case 'X':
7106 xtreme_rewind = B_TRUE;
7107 break;
7108 case '?':
7109 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7110 optopt);
7111 usage(B_FALSE);
7115 argc -= optind;
7116 argv += optind;
7118 if (argc < 1) {
7119 (void) fprintf(stderr, gettext("missing pool name\n"));
7120 usage(B_FALSE);
7123 if (argc > 2) {
7124 (void) fprintf(stderr, gettext("too many arguments\n"));
7125 usage(B_FALSE);
7128 if ((dryrun || xtreme_rewind) && !do_rewind) {
7129 (void) fprintf(stderr,
7130 gettext("-n or -X only meaningful with -F\n"));
7131 usage(B_FALSE);
7133 if (dryrun)
7134 rewind_policy = ZPOOL_TRY_REWIND;
7135 else if (do_rewind)
7136 rewind_policy = ZPOOL_DO_REWIND;
7137 if (xtreme_rewind)
7138 rewind_policy |= ZPOOL_EXTREME_REWIND;
7140 /* In future, further rewind policy choices can be passed along here */
7141 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
7142 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
7143 rewind_policy) != 0) {
7144 return (1);
7147 pool = argv[0];
7148 device = argc == 2 ? argv[1] : NULL;
7150 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
7151 nvlist_free(policy);
7152 return (1);
7155 if (zpool_clear(zhp, device, policy) != 0)
7156 ret = 1;
7158 zpool_close(zhp);
7160 nvlist_free(policy);
7162 return (ret);
7166 * zpool reguid <pool>
7169 zpool_do_reguid(int argc, char **argv)
7171 int c;
7172 char *poolname;
7173 zpool_handle_t *zhp;
7174 int ret = 0;
7176 /* check options */
7177 while ((c = getopt(argc, argv, "")) != -1) {
7178 switch (c) {
7179 case '?':
7180 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7181 optopt);
7182 usage(B_FALSE);
7186 argc -= optind;
7187 argv += optind;
7189 /* get pool name and check number of arguments */
7190 if (argc < 1) {
7191 (void) fprintf(stderr, gettext("missing pool name\n"));
7192 usage(B_FALSE);
7195 if (argc > 1) {
7196 (void) fprintf(stderr, gettext("too many arguments\n"));
7197 usage(B_FALSE);
7200 poolname = argv[0];
7201 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7202 return (1);
7204 ret = zpool_reguid(zhp);
7206 zpool_close(zhp);
7207 return (ret);
7212 * zpool reopen <pool>
7214 * Reopen the pool so that the kernel can update the sizes of all vdevs.
7217 zpool_do_reopen(int argc, char **argv)
7219 int c;
7220 int ret = 0;
7221 boolean_t scrub_restart = B_TRUE;
7223 /* check options */
7224 while ((c = getopt(argc, argv, "n")) != -1) {
7225 switch (c) {
7226 case 'n':
7227 scrub_restart = B_FALSE;
7228 break;
7229 case '?':
7230 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7231 optopt);
7232 usage(B_FALSE);
7236 argc -= optind;
7237 argv += optind;
7239 /* if argc == 0 we will execute zpool_reopen_one on all pools */
7240 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7241 B_FALSE, zpool_reopen_one, &scrub_restart);
7243 return (ret);
7246 typedef struct scrub_cbdata {
7247 int cb_type;
7248 pool_scrub_cmd_t cb_scrub_cmd;
7249 } scrub_cbdata_t;
7251 static boolean_t
7252 zpool_has_checkpoint(zpool_handle_t *zhp)
7254 nvlist_t *config, *nvroot;
7256 config = zpool_get_config(zhp, NULL);
7258 if (config != NULL) {
7259 pool_checkpoint_stat_t *pcs = NULL;
7260 uint_t c;
7262 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
7263 (void) nvlist_lookup_uint64_array(nvroot,
7264 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
7266 if (pcs == NULL || pcs->pcs_state == CS_NONE)
7267 return (B_FALSE);
7269 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
7270 pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
7271 return (B_TRUE);
7274 return (B_FALSE);
7277 static int
7278 scrub_callback(zpool_handle_t *zhp, void *data)
7280 scrub_cbdata_t *cb = data;
7281 int err;
7284 * Ignore faulted pools.
7286 if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
7287 (void) fprintf(stderr, gettext("cannot scan '%s': pool is "
7288 "currently unavailable\n"), zpool_get_name(zhp));
7289 return (1);
7292 err = zpool_scan(zhp, cb->cb_type, cb->cb_scrub_cmd);
7294 if (err == 0 && zpool_has_checkpoint(zhp) &&
7295 cb->cb_type == POOL_SCAN_SCRUB) {
7296 (void) printf(gettext("warning: will not scrub state that "
7297 "belongs to the checkpoint of pool '%s'\n"),
7298 zpool_get_name(zhp));
7301 return (err != 0);
7304 static int
7305 wait_callback(zpool_handle_t *zhp, void *data)
7307 zpool_wait_activity_t *act = data;
7308 return (zpool_wait(zhp, *act));
7312 * zpool scrub [-s | -p] [-w] <pool> ...
7314 * -s Stop. Stops any in-progress scrub.
7315 * -p Pause. Pause in-progress scrub.
7316 * -w Wait. Blocks until scrub has completed.
7319 zpool_do_scrub(int argc, char **argv)
7321 int c;
7322 scrub_cbdata_t cb;
7323 boolean_t wait = B_FALSE;
7324 int error;
7326 cb.cb_type = POOL_SCAN_SCRUB;
7327 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
7329 /* check options */
7330 while ((c = getopt(argc, argv, "spw")) != -1) {
7331 switch (c) {
7332 case 's':
7333 cb.cb_type = POOL_SCAN_NONE;
7334 break;
7335 case 'p':
7336 cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
7337 break;
7338 case 'w':
7339 wait = B_TRUE;
7340 break;
7341 case '?':
7342 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7343 optopt);
7344 usage(B_FALSE);
7348 if (cb.cb_type == POOL_SCAN_NONE &&
7349 cb.cb_scrub_cmd == POOL_SCRUB_PAUSE) {
7350 (void) fprintf(stderr, gettext("invalid option combination: "
7351 "-s and -p are mutually exclusive\n"));
7352 usage(B_FALSE);
7355 if (wait && (cb.cb_type == POOL_SCAN_NONE ||
7356 cb.cb_scrub_cmd == POOL_SCRUB_PAUSE)) {
7357 (void) fprintf(stderr, gettext("invalid option combination: "
7358 "-w cannot be used with -p or -s\n"));
7359 usage(B_FALSE);
7362 argc -= optind;
7363 argv += optind;
7365 if (argc < 1) {
7366 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7367 usage(B_FALSE);
7370 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7371 B_FALSE, scrub_callback, &cb);
7373 if (wait && !error) {
7374 zpool_wait_activity_t act = ZPOOL_WAIT_SCRUB;
7375 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7376 B_FALSE, wait_callback, &act);
7379 return (error);
7383 * zpool resilver <pool> ...
7385 * Restarts any in-progress resilver
7388 zpool_do_resilver(int argc, char **argv)
7390 int c;
7391 scrub_cbdata_t cb;
7393 cb.cb_type = POOL_SCAN_RESILVER;
7394 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
7396 /* check options */
7397 while ((c = getopt(argc, argv, "")) != -1) {
7398 switch (c) {
7399 case '?':
7400 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7401 optopt);
7402 usage(B_FALSE);
7406 argc -= optind;
7407 argv += optind;
7409 if (argc < 1) {
7410 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7411 usage(B_FALSE);
7414 return (for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7415 B_FALSE, scrub_callback, &cb));
7419 * zpool trim [-d] [-r <rate>] [-c | -s] <pool> [<device> ...]
7421 * -c Cancel. Ends any in-progress trim.
7422 * -d Secure trim. Requires kernel and device support.
7423 * -r <rate> Sets the TRIM rate in bytes (per second). Supports
7424 * adding a multiplier suffix such as 'k' or 'm'.
7425 * -s Suspend. TRIM can then be restarted with no flags.
7426 * -w Wait. Blocks until trimming has completed.
7429 zpool_do_trim(int argc, char **argv)
7431 struct option long_options[] = {
7432 {"cancel", no_argument, NULL, 'c'},
7433 {"secure", no_argument, NULL, 'd'},
7434 {"rate", required_argument, NULL, 'r'},
7435 {"suspend", no_argument, NULL, 's'},
7436 {"wait", no_argument, NULL, 'w'},
7437 {0, 0, 0, 0}
7440 pool_trim_func_t cmd_type = POOL_TRIM_START;
7441 uint64_t rate = 0;
7442 boolean_t secure = B_FALSE;
7443 boolean_t wait = B_FALSE;
7445 int c;
7446 while ((c = getopt_long(argc, argv, "cdr:sw", long_options, NULL))
7447 != -1) {
7448 switch (c) {
7449 case 'c':
7450 if (cmd_type != POOL_TRIM_START &&
7451 cmd_type != POOL_TRIM_CANCEL) {
7452 (void) fprintf(stderr, gettext("-c cannot be "
7453 "combined with other options\n"));
7454 usage(B_FALSE);
7456 cmd_type = POOL_TRIM_CANCEL;
7457 break;
7458 case 'd':
7459 if (cmd_type != POOL_TRIM_START) {
7460 (void) fprintf(stderr, gettext("-d cannot be "
7461 "combined with the -c or -s options\n"));
7462 usage(B_FALSE);
7464 secure = B_TRUE;
7465 break;
7466 case 'r':
7467 if (cmd_type != POOL_TRIM_START) {
7468 (void) fprintf(stderr, gettext("-r cannot be "
7469 "combined with the -c or -s options\n"));
7470 usage(B_FALSE);
7472 if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
7473 (void) fprintf(stderr, "%s: %s\n",
7474 gettext("invalid value for rate"),
7475 libzfs_error_description(g_zfs));
7476 usage(B_FALSE);
7478 break;
7479 case 's':
7480 if (cmd_type != POOL_TRIM_START &&
7481 cmd_type != POOL_TRIM_SUSPEND) {
7482 (void) fprintf(stderr, gettext("-s cannot be "
7483 "combined with other options\n"));
7484 usage(B_FALSE);
7486 cmd_type = POOL_TRIM_SUSPEND;
7487 break;
7488 case 'w':
7489 wait = B_TRUE;
7490 break;
7491 case '?':
7492 if (optopt != 0) {
7493 (void) fprintf(stderr,
7494 gettext("invalid option '%c'\n"), optopt);
7495 } else {
7496 (void) fprintf(stderr,
7497 gettext("invalid option '%s'\n"),
7498 argv[optind - 1]);
7500 usage(B_FALSE);
7504 argc -= optind;
7505 argv += optind;
7507 if (argc < 1) {
7508 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7509 usage(B_FALSE);
7510 return (-1);
7513 if (wait && (cmd_type != POOL_TRIM_START)) {
7514 (void) fprintf(stderr, gettext("-w cannot be used with -c or "
7515 "-s\n"));
7516 usage(B_FALSE);
7519 char *poolname = argv[0];
7520 zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
7521 if (zhp == NULL)
7522 return (-1);
7524 trimflags_t trim_flags = {
7525 .secure = secure,
7526 .rate = rate,
7527 .wait = wait,
7530 nvlist_t *vdevs = fnvlist_alloc();
7531 if (argc == 1) {
7532 /* no individual leaf vdevs specified, so add them all */
7533 nvlist_t *config = zpool_get_config(zhp, NULL);
7534 nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
7535 ZPOOL_CONFIG_VDEV_TREE);
7536 zpool_collect_leaves(zhp, nvroot, vdevs);
7537 trim_flags.fullpool = B_TRUE;
7538 } else {
7539 trim_flags.fullpool = B_FALSE;
7540 for (int i = 1; i < argc; i++) {
7541 fnvlist_add_boolean(vdevs, argv[i]);
7545 int error = zpool_trim(zhp, cmd_type, vdevs, &trim_flags);
7547 fnvlist_free(vdevs);
7548 zpool_close(zhp);
7550 return (error);
7554 * Converts a total number of seconds to a human readable string broken
7555 * down in to days/hours/minutes/seconds.
7557 static void
7558 secs_to_dhms(uint64_t total, char *buf)
7560 uint64_t days = total / 60 / 60 / 24;
7561 uint64_t hours = (total / 60 / 60) % 24;
7562 uint64_t mins = (total / 60) % 60;
7563 uint64_t secs = (total % 60);
7565 if (days > 0) {
7566 (void) sprintf(buf, "%llu days %02llu:%02llu:%02llu",
7567 (u_longlong_t)days, (u_longlong_t)hours,
7568 (u_longlong_t)mins, (u_longlong_t)secs);
7569 } else {
7570 (void) sprintf(buf, "%02llu:%02llu:%02llu",
7571 (u_longlong_t)hours, (u_longlong_t)mins,
7572 (u_longlong_t)secs);
7577 * Print out detailed scrub status.
7579 static void
7580 print_scan_scrub_resilver_status(pool_scan_stat_t *ps)
7582 time_t start, end, pause;
7583 uint64_t pass_scanned, scanned, pass_issued, issued, total;
7584 uint64_t elapsed, scan_rate, issue_rate;
7585 double fraction_done;
7586 char processed_buf[7], scanned_buf[7], issued_buf[7], total_buf[7];
7587 char srate_buf[7], irate_buf[7], time_buf[32];
7589 printf(" ");
7590 printf_color(ANSI_BOLD, gettext("scan:"));
7591 printf(" ");
7593 /* If there's never been a scan, there's not much to say. */
7594 if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
7595 ps->pss_func >= POOL_SCAN_FUNCS) {
7596 (void) printf(gettext("none requested\n"));
7597 return;
7600 start = ps->pss_start_time;
7601 end = ps->pss_end_time;
7602 pause = ps->pss_pass_scrub_pause;
7604 zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
7606 int is_resilver = ps->pss_func == POOL_SCAN_RESILVER;
7607 int is_scrub = ps->pss_func == POOL_SCAN_SCRUB;
7608 assert(is_resilver || is_scrub);
7610 /* Scan is finished or canceled. */
7611 if (ps->pss_state == DSS_FINISHED) {
7612 secs_to_dhms(end - start, time_buf);
7614 if (is_scrub) {
7615 (void) printf(gettext("scrub repaired %s "
7616 "in %s with %llu errors on %s"), processed_buf,
7617 time_buf, (u_longlong_t)ps->pss_errors,
7618 ctime(&end));
7619 } else if (is_resilver) {
7620 (void) printf(gettext("resilvered %s "
7621 "in %s with %llu errors on %s"), processed_buf,
7622 time_buf, (u_longlong_t)ps->pss_errors,
7623 ctime(&end));
7625 return;
7626 } else if (ps->pss_state == DSS_CANCELED) {
7627 if (is_scrub) {
7628 (void) printf(gettext("scrub canceled on %s"),
7629 ctime(&end));
7630 } else if (is_resilver) {
7631 (void) printf(gettext("resilver canceled on %s"),
7632 ctime(&end));
7634 return;
7637 assert(ps->pss_state == DSS_SCANNING);
7639 /* Scan is in progress. Resilvers can't be paused. */
7640 if (is_scrub) {
7641 if (pause == 0) {
7642 (void) printf(gettext("scrub in progress since %s"),
7643 ctime(&start));
7644 } else {
7645 (void) printf(gettext("scrub paused since %s"),
7646 ctime(&pause));
7647 (void) printf(gettext("\tscrub started on %s"),
7648 ctime(&start));
7650 } else if (is_resilver) {
7651 (void) printf(gettext("resilver in progress since %s"),
7652 ctime(&start));
7655 scanned = ps->pss_examined;
7656 pass_scanned = ps->pss_pass_exam;
7657 issued = ps->pss_issued;
7658 pass_issued = ps->pss_pass_issued;
7659 total = ps->pss_to_examine;
7661 /* we are only done with a block once we have issued the IO for it */
7662 fraction_done = (double)issued / total;
7664 /* elapsed time for this pass, rounding up to 1 if it's 0 */
7665 elapsed = time(NULL) - ps->pss_pass_start;
7666 elapsed -= ps->pss_pass_scrub_spent_paused;
7667 elapsed = (elapsed != 0) ? elapsed : 1;
7669 scan_rate = pass_scanned / elapsed;
7670 issue_rate = pass_issued / elapsed;
7671 uint64_t total_secs_left = (issue_rate != 0 && total >= issued) ?
7672 ((total - issued) / issue_rate) : UINT64_MAX;
7673 secs_to_dhms(total_secs_left, time_buf);
7675 /* format all of the numbers we will be reporting */
7676 zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
7677 zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
7678 zfs_nicebytes(total, total_buf, sizeof (total_buf));
7679 zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
7680 zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
7682 /* do not print estimated time if we have a paused scrub */
7683 if (pause == 0) {
7684 (void) printf(gettext("\t%s scanned at %s/s, "
7685 "%s issued at %s/s, %s total\n"),
7686 scanned_buf, srate_buf, issued_buf, irate_buf, total_buf);
7687 } else {
7688 (void) printf(gettext("\t%s scanned, %s issued, %s total\n"),
7689 scanned_buf, issued_buf, total_buf);
7692 if (is_resilver) {
7693 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
7694 processed_buf, 100 * fraction_done);
7695 } else if (is_scrub) {
7696 (void) printf(gettext("\t%s repaired, %.2f%% done"),
7697 processed_buf, 100 * fraction_done);
7700 if (pause == 0) {
7702 * Only provide an estimate iff:
7703 * 1) the time remaining is valid, and
7704 * 2) the issue rate exceeds 10 MB/s, and
7705 * 3) it's either:
7706 * a) a resilver which has started repairs, or
7707 * b) a scrub which has entered the issue phase.
7709 if (total_secs_left != UINT64_MAX &&
7710 issue_rate >= 10 * 1024 * 1024 &&
7711 ((is_resilver && ps->pss_processed > 0) ||
7712 (is_scrub && issued > 0))) {
7713 (void) printf(gettext(", %s to go\n"), time_buf);
7714 } else {
7715 (void) printf(gettext(", no estimated "
7716 "completion time\n"));
7718 } else {
7719 (void) printf(gettext("\n"));
7723 static void
7724 print_rebuild_status_impl(vdev_rebuild_stat_t *vrs, char *vdev_name)
7726 if (vrs == NULL || vrs->vrs_state == VDEV_REBUILD_NONE)
7727 return;
7729 printf(" ");
7730 printf_color(ANSI_BOLD, gettext("scan:"));
7731 printf(" ");
7733 uint64_t bytes_scanned = vrs->vrs_bytes_scanned;
7734 uint64_t bytes_issued = vrs->vrs_bytes_issued;
7735 uint64_t bytes_rebuilt = vrs->vrs_bytes_rebuilt;
7736 uint64_t bytes_est = vrs->vrs_bytes_est;
7737 uint64_t scan_rate = (vrs->vrs_pass_bytes_scanned /
7738 (vrs->vrs_pass_time_ms + 1)) * 1000;
7739 uint64_t issue_rate = (vrs->vrs_pass_bytes_issued /
7740 (vrs->vrs_pass_time_ms + 1)) * 1000;
7741 double scan_pct = MIN((double)bytes_scanned * 100 /
7742 (bytes_est + 1), 100);
7744 /* Format all of the numbers we will be reporting */
7745 char bytes_scanned_buf[7], bytes_issued_buf[7];
7746 char bytes_rebuilt_buf[7], bytes_est_buf[7];
7747 char scan_rate_buf[7], issue_rate_buf[7], time_buf[32];
7748 zfs_nicebytes(bytes_scanned, bytes_scanned_buf,
7749 sizeof (bytes_scanned_buf));
7750 zfs_nicebytes(bytes_issued, bytes_issued_buf,
7751 sizeof (bytes_issued_buf));
7752 zfs_nicebytes(bytes_rebuilt, bytes_rebuilt_buf,
7753 sizeof (bytes_rebuilt_buf));
7754 zfs_nicebytes(bytes_est, bytes_est_buf, sizeof (bytes_est_buf));
7755 zfs_nicebytes(scan_rate, scan_rate_buf, sizeof (scan_rate_buf));
7756 zfs_nicebytes(issue_rate, issue_rate_buf, sizeof (issue_rate_buf));
7758 time_t start = vrs->vrs_start_time;
7759 time_t end = vrs->vrs_end_time;
7761 /* Rebuild is finished or canceled. */
7762 if (vrs->vrs_state == VDEV_REBUILD_COMPLETE) {
7763 secs_to_dhms(vrs->vrs_scan_time_ms / 1000, time_buf);
7764 (void) printf(gettext("resilvered (%s) %s in %s "
7765 "with %llu errors on %s"), vdev_name, bytes_rebuilt_buf,
7766 time_buf, (u_longlong_t)vrs->vrs_errors, ctime(&end));
7767 return;
7768 } else if (vrs->vrs_state == VDEV_REBUILD_CANCELED) {
7769 (void) printf(gettext("resilver (%s) canceled on %s"),
7770 vdev_name, ctime(&end));
7771 return;
7772 } else if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
7773 (void) printf(gettext("resilver (%s) in progress since %s"),
7774 vdev_name, ctime(&start));
7777 assert(vrs->vrs_state == VDEV_REBUILD_ACTIVE);
7779 secs_to_dhms(MAX((int64_t)bytes_est - (int64_t)bytes_scanned, 0) /
7780 MAX(scan_rate, 1), time_buf);
7782 (void) printf(gettext("\t%s scanned at %s/s, %s issued %s/s, "
7783 "%s total\n"), bytes_scanned_buf, scan_rate_buf,
7784 bytes_issued_buf, issue_rate_buf, bytes_est_buf);
7785 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
7786 bytes_rebuilt_buf, scan_pct);
7788 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
7789 if (scan_rate >= 10 * 1024 * 1024) {
7790 (void) printf(gettext(", %s to go\n"), time_buf);
7791 } else {
7792 (void) printf(gettext(", no estimated "
7793 "completion time\n"));
7795 } else {
7796 (void) printf(gettext("\n"));
7801 * Print rebuild status for top-level vdevs.
7803 static void
7804 print_rebuild_status(zpool_handle_t *zhp, nvlist_t *nvroot)
7806 nvlist_t **child;
7807 uint_t children;
7809 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
7810 &child, &children) != 0)
7811 children = 0;
7813 for (uint_t c = 0; c < children; c++) {
7814 vdev_rebuild_stat_t *vrs;
7815 uint_t i;
7817 if (nvlist_lookup_uint64_array(child[c],
7818 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
7819 char *name = zpool_vdev_name(g_zfs, zhp,
7820 child[c], VDEV_NAME_TYPE_ID);
7821 print_rebuild_status_impl(vrs, name);
7822 free(name);
7828 * As we don't scrub checkpointed blocks, we want to warn the user that we
7829 * skipped scanning some blocks if a checkpoint exists or existed at any
7830 * time during the scan. If a sequential instead of healing reconstruction
7831 * was performed then the blocks were reconstructed. However, their checksums
7832 * have not been verified so we still print the warning.
7834 static void
7835 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
7837 if (ps == NULL || pcs == NULL)
7838 return;
7840 if (pcs->pcs_state == CS_NONE ||
7841 pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
7842 return;
7844 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
7846 if (ps->pss_state == DSS_NONE)
7847 return;
7849 if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
7850 ps->pss_end_time < pcs->pcs_start_time)
7851 return;
7853 if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
7854 (void) printf(gettext(" scan warning: skipped blocks "
7855 "that are only referenced by the checkpoint.\n"));
7856 } else {
7857 assert(ps->pss_state == DSS_SCANNING);
7858 (void) printf(gettext(" scan warning: skipping blocks "
7859 "that are only referenced by the checkpoint.\n"));
7864 * Returns B_TRUE if there is an active rebuild in progress. Otherwise,
7865 * B_FALSE is returned and 'rebuild_end_time' is set to the end time for
7866 * the last completed (or cancelled) rebuild.
7868 static boolean_t
7869 check_rebuilding(nvlist_t *nvroot, uint64_t *rebuild_end_time)
7871 nvlist_t **child;
7872 uint_t children;
7873 boolean_t rebuilding = B_FALSE;
7874 uint64_t end_time = 0;
7876 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
7877 &child, &children) != 0)
7878 children = 0;
7880 for (uint_t c = 0; c < children; c++) {
7881 vdev_rebuild_stat_t *vrs;
7882 uint_t i;
7884 if (nvlist_lookup_uint64_array(child[c],
7885 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
7887 if (vrs->vrs_end_time > end_time)
7888 end_time = vrs->vrs_end_time;
7890 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
7891 rebuilding = B_TRUE;
7892 end_time = 0;
7893 break;
7898 if (rebuild_end_time != NULL)
7899 *rebuild_end_time = end_time;
7901 return (rebuilding);
7905 * Print the scan status.
7907 static void
7908 print_scan_status(zpool_handle_t *zhp, nvlist_t *nvroot)
7910 uint64_t rebuild_end_time = 0, resilver_end_time = 0;
7911 boolean_t have_resilver = B_FALSE, have_scrub = B_FALSE;
7912 boolean_t active_resilver = B_FALSE;
7913 pool_checkpoint_stat_t *pcs = NULL;
7914 pool_scan_stat_t *ps = NULL;
7915 uint_t c;
7917 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
7918 (uint64_t **)&ps, &c) == 0) {
7919 if (ps->pss_func == POOL_SCAN_RESILVER) {
7920 resilver_end_time = ps->pss_end_time;
7921 active_resilver = (ps->pss_state == DSS_SCANNING);
7924 have_resilver = (ps->pss_func == POOL_SCAN_RESILVER);
7925 have_scrub = (ps->pss_func == POOL_SCAN_SCRUB);
7928 boolean_t active_rebuild = check_rebuilding(nvroot, &rebuild_end_time);
7929 boolean_t have_rebuild = (active_rebuild || (rebuild_end_time > 0));
7931 /* Always print the scrub status when available. */
7932 if (have_scrub)
7933 print_scan_scrub_resilver_status(ps);
7936 * When there is an active resilver or rebuild print its status.
7937 * Otherwise print the status of the last resilver or rebuild.
7939 if (active_resilver || (!active_rebuild && have_resilver &&
7940 resilver_end_time && resilver_end_time > rebuild_end_time)) {
7941 print_scan_scrub_resilver_status(ps);
7942 } else if (active_rebuild || (!active_resilver && have_rebuild &&
7943 rebuild_end_time && rebuild_end_time > resilver_end_time)) {
7944 print_rebuild_status(zhp, nvroot);
7947 (void) nvlist_lookup_uint64_array(nvroot,
7948 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
7949 print_checkpoint_scan_warning(ps, pcs);
7953 * Print out detailed removal status.
7955 static void
7956 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
7958 char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
7959 time_t start, end;
7960 nvlist_t *config, *nvroot;
7961 nvlist_t **child;
7962 uint_t children;
7963 char *vdev_name;
7965 if (prs == NULL || prs->prs_state == DSS_NONE)
7966 return;
7969 * Determine name of vdev.
7971 config = zpool_get_config(zhp, NULL);
7972 nvroot = fnvlist_lookup_nvlist(config,
7973 ZPOOL_CONFIG_VDEV_TREE);
7974 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
7975 &child, &children) == 0);
7976 assert(prs->prs_removing_vdev < children);
7977 vdev_name = zpool_vdev_name(g_zfs, zhp,
7978 child[prs->prs_removing_vdev], B_TRUE);
7980 printf_color(ANSI_BOLD, gettext("remove: "));
7982 start = prs->prs_start_time;
7983 end = prs->prs_end_time;
7984 zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
7987 * Removal is finished or canceled.
7989 if (prs->prs_state == DSS_FINISHED) {
7990 uint64_t minutes_taken = (end - start) / 60;
7992 (void) printf(gettext("Removal of vdev %llu copied %s "
7993 "in %lluh%um, completed on %s"),
7994 (longlong_t)prs->prs_removing_vdev,
7995 copied_buf,
7996 (u_longlong_t)(minutes_taken / 60),
7997 (uint_t)(minutes_taken % 60),
7998 ctime((time_t *)&end));
7999 } else if (prs->prs_state == DSS_CANCELED) {
8000 (void) printf(gettext("Removal of %s canceled on %s"),
8001 vdev_name, ctime(&end));
8002 } else {
8003 uint64_t copied, total, elapsed, mins_left, hours_left;
8004 double fraction_done;
8005 uint_t rate;
8007 assert(prs->prs_state == DSS_SCANNING);
8010 * Removal is in progress.
8012 (void) printf(gettext(
8013 "Evacuation of %s in progress since %s"),
8014 vdev_name, ctime(&start));
8016 copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
8017 total = prs->prs_to_copy;
8018 fraction_done = (double)copied / total;
8020 /* elapsed time for this pass */
8021 elapsed = time(NULL) - prs->prs_start_time;
8022 elapsed = elapsed > 0 ? elapsed : 1;
8023 rate = copied / elapsed;
8024 rate = rate > 0 ? rate : 1;
8025 mins_left = ((total - copied) / rate) / 60;
8026 hours_left = mins_left / 60;
8028 zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
8029 zfs_nicenum(total, total_buf, sizeof (total_buf));
8030 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
8033 * do not print estimated time if hours_left is more than
8034 * 30 days
8036 (void) printf(gettext(
8037 "\t%s copied out of %s at %s/s, %.2f%% done"),
8038 examined_buf, total_buf, rate_buf, 100 * fraction_done);
8039 if (hours_left < (30 * 24)) {
8040 (void) printf(gettext(", %lluh%um to go\n"),
8041 (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
8042 } else {
8043 (void) printf(gettext(
8044 ", (copy is slow, no estimated time)\n"));
8047 free(vdev_name);
8049 if (prs->prs_mapping_memory > 0) {
8050 char mem_buf[7];
8051 zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
8052 (void) printf(gettext(
8053 "\t%s memory used for removed device mappings\n"),
8054 mem_buf);
8058 static void
8059 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
8061 time_t start;
8062 char space_buf[7];
8064 if (pcs == NULL || pcs->pcs_state == CS_NONE)
8065 return;
8067 (void) printf(gettext("checkpoint: "));
8069 start = pcs->pcs_start_time;
8070 zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
8072 if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
8073 char *date = ctime(&start);
8076 * ctime() adds a newline at the end of the generated
8077 * string, thus the weird format specifier and the
8078 * strlen() call used to chop it off from the output.
8080 (void) printf(gettext("created %.*s, consumes %s\n"),
8081 (int)(strlen(date) - 1), date, space_buf);
8082 return;
8085 assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
8087 (void) printf(gettext("discarding, %s remaining.\n"),
8088 space_buf);
8091 static void
8092 print_error_log(zpool_handle_t *zhp)
8094 nvlist_t *nverrlist = NULL;
8095 nvpair_t *elem;
8096 char *pathname;
8097 size_t len = MAXPATHLEN * 2;
8099 if (zpool_get_errlog(zhp, &nverrlist) != 0)
8100 return;
8102 (void) printf("errors: Permanent errors have been "
8103 "detected in the following files:\n\n");
8105 pathname = safe_malloc(len);
8106 elem = NULL;
8107 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
8108 nvlist_t *nv;
8109 uint64_t dsobj, obj;
8111 verify(nvpair_value_nvlist(elem, &nv) == 0);
8112 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
8113 &dsobj) == 0);
8114 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
8115 &obj) == 0);
8116 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
8117 (void) printf("%7s %s\n", "", pathname);
8119 free(pathname);
8120 nvlist_free(nverrlist);
8123 static void
8124 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
8125 uint_t nspares)
8127 uint_t i;
8128 char *name;
8130 if (nspares == 0)
8131 return;
8133 (void) printf(gettext("\tspares\n"));
8135 for (i = 0; i < nspares; i++) {
8136 name = zpool_vdev_name(g_zfs, zhp, spares[i],
8137 cb->cb_name_flags);
8138 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE, NULL);
8139 free(name);
8143 static void
8144 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
8145 uint_t nl2cache)
8147 uint_t i;
8148 char *name;
8150 if (nl2cache == 0)
8151 return;
8153 (void) printf(gettext("\tcache\n"));
8155 for (i = 0; i < nl2cache; i++) {
8156 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
8157 cb->cb_name_flags);
8158 print_status_config(zhp, cb, name, l2cache[i], 2,
8159 B_FALSE, NULL);
8160 free(name);
8164 static void
8165 print_dedup_stats(nvlist_t *config)
8167 ddt_histogram_t *ddh;
8168 ddt_stat_t *dds;
8169 ddt_object_t *ddo;
8170 uint_t c;
8171 char dspace[6], mspace[6];
8174 * If the pool was faulted then we may not have been able to
8175 * obtain the config. Otherwise, if we have anything in the dedup
8176 * table continue processing the stats.
8178 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
8179 (uint64_t **)&ddo, &c) != 0)
8180 return;
8182 (void) printf("\n");
8183 (void) printf(gettext(" dedup: "));
8184 if (ddo->ddo_count == 0) {
8185 (void) printf(gettext("no DDT entries\n"));
8186 return;
8189 zfs_nicebytes(ddo->ddo_dspace, dspace, sizeof (dspace));
8190 zfs_nicebytes(ddo->ddo_mspace, mspace, sizeof (mspace));
8191 (void) printf("DDT entries %llu, size %s on disk, %s in core\n",
8192 (u_longlong_t)ddo->ddo_count,
8193 dspace,
8194 mspace);
8196 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
8197 (uint64_t **)&dds, &c) == 0);
8198 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
8199 (uint64_t **)&ddh, &c) == 0);
8200 zpool_dump_ddt(dds, ddh);
8204 * Display a summary of pool status. Displays a summary such as:
8206 * pool: tank
8207 * status: DEGRADED
8208 * reason: One or more devices ...
8209 * see: https://openzfs.github.io/openzfs-docs/msg/ZFS-xxxx-01
8210 * config:
8211 * mirror DEGRADED
8212 * c1t0d0 OK
8213 * c2t0d0 UNAVAIL
8215 * When given the '-v' option, we print out the complete config. If the '-e'
8216 * option is specified, then we print out error rate information as well.
8218 static int
8219 status_callback(zpool_handle_t *zhp, void *data)
8221 status_cbdata_t *cbp = data;
8222 nvlist_t *config, *nvroot;
8223 const char *msgid;
8224 zpool_status_t reason;
8225 zpool_errata_t errata;
8226 const char *health;
8227 uint_t c;
8228 vdev_stat_t *vs;
8230 config = zpool_get_config(zhp, NULL);
8231 reason = zpool_get_status(zhp, &msgid, &errata);
8233 cbp->cb_count++;
8236 * If we were given 'zpool status -x', only report those pools with
8237 * problems.
8239 if (cbp->cb_explain &&
8240 (reason == ZPOOL_STATUS_OK ||
8241 reason == ZPOOL_STATUS_VERSION_OLDER ||
8242 reason == ZPOOL_STATUS_FEAT_DISABLED ||
8243 reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
8244 reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
8245 if (!cbp->cb_allpools) {
8246 (void) printf(gettext("pool '%s' is healthy\n"),
8247 zpool_get_name(zhp));
8248 if (cbp->cb_first)
8249 cbp->cb_first = B_FALSE;
8251 return (0);
8254 if (cbp->cb_first)
8255 cbp->cb_first = B_FALSE;
8256 else
8257 (void) printf("\n");
8259 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
8260 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
8261 (uint64_t **)&vs, &c) == 0);
8263 health = zpool_get_state_str(zhp);
8265 printf(" ");
8266 printf_color(ANSI_BOLD, gettext("pool:"));
8267 printf(" %s\n", zpool_get_name(zhp));
8268 fputc(' ', stdout);
8269 printf_color(ANSI_BOLD, gettext("state: "));
8271 printf_color(health_str_to_color(health), "%s", health);
8273 fputc('\n', stdout);
8275 switch (reason) {
8276 case ZPOOL_STATUS_MISSING_DEV_R:
8277 printf_color(ANSI_BOLD, gettext("status: "));
8278 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8279 "not be opened. Sufficient replicas exist for\n\tthe pool "
8280 "to continue functioning in a degraded state.\n"));
8281 printf_color(ANSI_BOLD, gettext("action: "));
8282 printf_color(ANSI_YELLOW, gettext("Attach the missing device "
8283 "and online it using 'zpool online'.\n"));
8284 break;
8286 case ZPOOL_STATUS_MISSING_DEV_NR:
8287 printf_color(ANSI_BOLD, gettext("status: "));
8288 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8289 "not be opened. There are insufficient\n\treplicas for the"
8290 " pool to continue functioning.\n"));
8291 printf_color(ANSI_BOLD, gettext("action: "));
8292 printf_color(ANSI_YELLOW, gettext("Attach the missing device "
8293 "and online it using 'zpool online'.\n"));
8294 break;
8296 case ZPOOL_STATUS_CORRUPT_LABEL_R:
8297 printf_color(ANSI_BOLD, gettext("status: "));
8298 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8299 "not be used because the label is missing or\n\tinvalid. "
8300 "Sufficient replicas exist for the pool to continue\n\t"
8301 "functioning in a degraded state.\n"));
8302 printf_color(ANSI_BOLD, gettext("action: "));
8303 printf_color(ANSI_YELLOW, gettext("Replace the device using "
8304 "'zpool replace'.\n"));
8305 break;
8307 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
8308 printf_color(ANSI_BOLD, gettext("status: "));
8309 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8310 "not be used because the label is missing \n\tor invalid. "
8311 "There are insufficient replicas for the pool to "
8312 "continue\n\tfunctioning.\n"));
8313 zpool_explain_recover(zpool_get_handle(zhp),
8314 zpool_get_name(zhp), reason, config);
8315 break;
8317 case ZPOOL_STATUS_FAILING_DEV:
8318 printf_color(ANSI_BOLD, gettext("status: "));
8319 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8320 "experienced an unrecoverable error. An\n\tattempt was "
8321 "made to correct the error. Applications are "
8322 "unaffected.\n"));
8323 printf_color(ANSI_BOLD, gettext("action: "));
8324 printf_color(ANSI_YELLOW, gettext("Determine if the "
8325 "device needs to be replaced, and clear the errors\n\tusing"
8326 " 'zpool clear' or replace the device with 'zpool "
8327 "replace'.\n"));
8328 break;
8330 case ZPOOL_STATUS_OFFLINE_DEV:
8331 printf_color(ANSI_BOLD, gettext("status: "));
8332 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8333 "been taken offline by the administrator.\n\tSufficient "
8334 "replicas exist for the pool to continue functioning in "
8335 "a\n\tdegraded state.\n"));
8336 printf_color(ANSI_BOLD, gettext("action: "));
8337 printf_color(ANSI_YELLOW, gettext("Online the device "
8338 "using 'zpool online' or replace the device with\n\t'zpool "
8339 "replace'.\n"));
8340 break;
8342 case ZPOOL_STATUS_REMOVED_DEV:
8343 printf_color(ANSI_BOLD, gettext("status: "));
8344 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8345 "been removed by the administrator.\n\tSufficient "
8346 "replicas exist for the pool to continue functioning in "
8347 "a\n\tdegraded state.\n"));
8348 printf_color(ANSI_BOLD, gettext("action: "));
8349 printf_color(ANSI_YELLOW, gettext("Online the device "
8350 "using zpool online' or replace the device with\n\t'zpool "
8351 "replace'.\n"));
8352 break;
8354 case ZPOOL_STATUS_RESILVERING:
8355 case ZPOOL_STATUS_REBUILDING:
8356 printf_color(ANSI_BOLD, gettext("status: "));
8357 printf_color(ANSI_YELLOW, gettext("One or more devices is "
8358 "currently being resilvered. The pool will\n\tcontinue "
8359 "to function, possibly in a degraded state.\n"));
8360 printf_color(ANSI_BOLD, gettext("action: "));
8361 printf_color(ANSI_YELLOW, gettext("Wait for the resilver to "
8362 "complete.\n"));
8363 break;
8365 case ZPOOL_STATUS_REBUILD_SCRUB:
8366 printf_color(ANSI_BOLD, gettext("status: "));
8367 printf_color(ANSI_YELLOW, gettext("One or more devices have "
8368 "been sequentially resilvered, scrubbing\n\tthe pool "
8369 "is recommended.\n"));
8370 printf_color(ANSI_BOLD, gettext("action: "));
8371 printf_color(ANSI_YELLOW, gettext("Use 'zpool scrub' to "
8372 "verify all data checksums.\n"));
8373 break;
8375 case ZPOOL_STATUS_CORRUPT_DATA:
8376 printf_color(ANSI_BOLD, gettext("status: "));
8377 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8378 "experienced an error resulting in data\n\tcorruption. "
8379 "Applications may be affected.\n"));
8380 printf_color(ANSI_BOLD, gettext("action: "));
8381 printf_color(ANSI_YELLOW, gettext("Restore the file in question"
8382 " if possible. Otherwise restore the\n\tentire pool from "
8383 "backup.\n"));
8384 break;
8386 case ZPOOL_STATUS_CORRUPT_POOL:
8387 printf_color(ANSI_BOLD, gettext("status: "));
8388 printf_color(ANSI_YELLOW, gettext("The pool metadata is "
8389 "corrupted and the pool cannot be opened.\n"));
8390 zpool_explain_recover(zpool_get_handle(zhp),
8391 zpool_get_name(zhp), reason, config);
8392 break;
8394 case ZPOOL_STATUS_VERSION_OLDER:
8395 printf_color(ANSI_BOLD, gettext("status: "));
8396 printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
8397 "a legacy on-disk format. The pool can\n\tstill be used, "
8398 "but some features are unavailable.\n"));
8399 printf_color(ANSI_BOLD, gettext("action: "));
8400 printf_color(ANSI_YELLOW, gettext("Upgrade the pool using "
8401 "'zpool upgrade'. Once this is done, the\n\tpool will no "
8402 "longer be accessible on software that does not support\n\t"
8403 "feature flags.\n"));
8404 break;
8406 case ZPOOL_STATUS_VERSION_NEWER:
8407 printf_color(ANSI_BOLD, gettext("status: "));
8408 printf_color(ANSI_YELLOW, gettext("The pool has been upgraded "
8409 "to a newer, incompatible on-disk version.\n\tThe pool "
8410 "cannot be accessed on this system.\n"));
8411 printf_color(ANSI_BOLD, gettext("action: "));
8412 printf_color(ANSI_YELLOW, gettext("Access the pool from a "
8413 "system running more recent software, or\n\trestore the "
8414 "pool from backup.\n"));
8415 break;
8417 case ZPOOL_STATUS_FEAT_DISABLED:
8418 printf_color(ANSI_BOLD, gettext("status: "));
8419 printf_color(ANSI_YELLOW, gettext("Some supported and "
8420 "requested features are not enabled on the pool.\n\t"
8421 "The pool can still be used, but some features are "
8422 "unavailable.\n"));
8423 printf_color(ANSI_BOLD, gettext("action: "));
8424 printf_color(ANSI_YELLOW, gettext("Enable all features using "
8425 "'zpool upgrade'. Once this is done,\n\tthe pool may no "
8426 "longer be accessible by software that does not support\n\t"
8427 "the features. See zpool-features(7) for details.\n"));
8428 break;
8430 case ZPOOL_STATUS_COMPATIBILITY_ERR:
8431 printf_color(ANSI_BOLD, gettext("status: "));
8432 printf_color(ANSI_YELLOW, gettext("This pool has a "
8433 "compatibility list specified, but it could not be\n\t"
8434 "read/parsed at this time. The pool can still be used, "
8435 "but this\n\tshould be investigated.\n"));
8436 printf_color(ANSI_BOLD, gettext("action: "));
8437 printf_color(ANSI_YELLOW, gettext("Check the value of the "
8438 "'compatibility' property against the\n\t"
8439 "appropriate file in " ZPOOL_SYSCONF_COMPAT_D " or "
8440 ZPOOL_DATA_COMPAT_D ".\n"));
8441 break;
8443 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
8444 printf_color(ANSI_BOLD, gettext("status: "));
8445 printf_color(ANSI_YELLOW, gettext("One or more features "
8446 "are enabled on the pool despite not being\n\t"
8447 "requested by the 'compatibility' property.\n"));
8448 printf_color(ANSI_BOLD, gettext("action: "));
8449 printf_color(ANSI_YELLOW, gettext("Consider setting "
8450 "'compatibility' to an appropriate value, or\n\t"
8451 "adding needed features to the relevant file in\n\t"
8452 ZPOOL_SYSCONF_COMPAT_D " or " ZPOOL_DATA_COMPAT_D ".\n"));
8453 break;
8455 case ZPOOL_STATUS_UNSUP_FEAT_READ:
8456 printf_color(ANSI_BOLD, gettext("status: "));
8457 printf_color(ANSI_YELLOW, gettext("The pool cannot be accessed "
8458 "on this system because it uses the\n\tfollowing feature(s)"
8459 " not supported on this system:\n"));
8460 zpool_print_unsup_feat(config);
8461 (void) printf("\n");
8462 printf_color(ANSI_BOLD, gettext("action: "));
8463 printf_color(ANSI_YELLOW, gettext("Access the pool from a "
8464 "system that supports the required feature(s),\n\tor "
8465 "restore the pool from backup.\n"));
8466 break;
8468 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
8469 printf_color(ANSI_BOLD, gettext("status: "));
8470 printf_color(ANSI_YELLOW, gettext("The pool can only be "
8471 "accessed in read-only mode on this system. It\n\tcannot be"
8472 " accessed in read-write mode because it uses the "
8473 "following\n\tfeature(s) not supported on this system:\n"));
8474 zpool_print_unsup_feat(config);
8475 (void) printf("\n");
8476 printf_color(ANSI_BOLD, gettext("action: "));
8477 printf_color(ANSI_YELLOW, gettext("The pool cannot be accessed "
8478 "in read-write mode. Import the pool with\n"
8479 "\t\"-o readonly=on\", access the pool from a system that "
8480 "supports the\n\trequired feature(s), or restore the "
8481 "pool from backup.\n"));
8482 break;
8484 case ZPOOL_STATUS_FAULTED_DEV_R:
8485 printf_color(ANSI_BOLD, gettext("status: "));
8486 printf_color(ANSI_YELLOW, gettext("One or more devices are "
8487 "faulted in response to persistent errors.\n\tSufficient "
8488 "replicas exist for the pool to continue functioning "
8489 "in a\n\tdegraded state.\n"));
8490 printf_color(ANSI_BOLD, gettext("action: "));
8491 printf_color(ANSI_YELLOW, gettext("Replace the faulted device, "
8492 "or use 'zpool clear' to mark the device\n\trepaired.\n"));
8493 break;
8495 case ZPOOL_STATUS_FAULTED_DEV_NR:
8496 printf_color(ANSI_BOLD, gettext("status: "));
8497 printf_color(ANSI_YELLOW, gettext("One or more devices are "
8498 "faulted in response to persistent errors. There are "
8499 "insufficient replicas for the pool to\n\tcontinue "
8500 "functioning.\n"));
8501 printf_color(ANSI_BOLD, gettext("action: "));
8502 printf_color(ANSI_YELLOW, gettext("Destroy and re-create the "
8503 "pool from a backup source. Manually marking the device\n"
8504 "\trepaired using 'zpool clear' may allow some data "
8505 "to be recovered.\n"));
8506 break;
8508 case ZPOOL_STATUS_IO_FAILURE_MMP:
8509 printf_color(ANSI_BOLD, gettext("status: "));
8510 printf_color(ANSI_YELLOW, gettext("The pool is suspended "
8511 "because multihost writes failed or were delayed;\n\t"
8512 "another system could import the pool undetected.\n"));
8513 printf_color(ANSI_BOLD, gettext("action: "));
8514 printf_color(ANSI_YELLOW, gettext("Make sure the pool's devices"
8515 " are connected, then reboot your system and\n\timport the "
8516 "pool.\n"));
8517 break;
8519 case ZPOOL_STATUS_IO_FAILURE_WAIT:
8520 case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
8521 printf_color(ANSI_BOLD, gettext("status: "));
8522 printf_color(ANSI_YELLOW, gettext("One or more devices are "
8523 "faulted in response to IO failures.\n"));
8524 printf_color(ANSI_BOLD, gettext("action: "));
8525 printf_color(ANSI_YELLOW, gettext("Make sure the affected "
8526 "devices are connected, then run 'zpool clear'.\n"));
8527 break;
8529 case ZPOOL_STATUS_BAD_LOG:
8530 printf_color(ANSI_BOLD, gettext("status: "));
8531 printf_color(ANSI_YELLOW, gettext("An intent log record "
8532 "could not be read.\n"
8533 "\tWaiting for administrator intervention to fix the "
8534 "faulted pool.\n"));
8535 printf_color(ANSI_BOLD, gettext("action: "));
8536 printf_color(ANSI_YELLOW, gettext("Either restore the affected "
8537 "device(s) and run 'zpool online',\n"
8538 "\tor ignore the intent log records by running "
8539 "'zpool clear'.\n"));
8540 break;
8542 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
8543 (void) printf(gettext("status: One or more devices are "
8544 "configured to use a non-native block size.\n"
8545 "\tExpect reduced performance.\n"));
8546 (void) printf(gettext("action: Replace affected devices with "
8547 "devices that support the\n\tconfigured block size, or "
8548 "migrate data to a properly configured\n\tpool.\n"));
8549 break;
8551 case ZPOOL_STATUS_HOSTID_MISMATCH:
8552 printf_color(ANSI_BOLD, gettext("status: "));
8553 printf_color(ANSI_YELLOW, gettext("Mismatch between pool hostid"
8554 " and system hostid on imported pool.\n\tThis pool was "
8555 "previously imported into a system with a different "
8556 "hostid,\n\tand then was verbatim imported into this "
8557 "system.\n"));
8558 printf_color(ANSI_BOLD, gettext("action: "));
8559 printf_color(ANSI_YELLOW, gettext("Export this pool on all "
8560 "systems on which it is imported.\n"
8561 "\tThen import it to correct the mismatch.\n"));
8562 break;
8564 case ZPOOL_STATUS_ERRATA:
8565 printf_color(ANSI_BOLD, gettext("status: "));
8566 printf_color(ANSI_YELLOW, gettext("Errata #%d detected.\n"),
8567 errata);
8569 switch (errata) {
8570 case ZPOOL_ERRATA_NONE:
8571 break;
8573 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
8574 printf_color(ANSI_BOLD, gettext("action: "));
8575 printf_color(ANSI_YELLOW, gettext("To correct the issue"
8576 " run 'zpool scrub'.\n"));
8577 break;
8579 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
8580 (void) printf(gettext("\tExisting encrypted datasets "
8581 "contain an on-disk incompatibility\n\twhich "
8582 "needs to be corrected.\n"));
8583 printf_color(ANSI_BOLD, gettext("action: "));
8584 printf_color(ANSI_YELLOW, gettext("To correct the issue"
8585 " backup existing encrypted datasets to new\n\t"
8586 "encrypted datasets and destroy the old ones. "
8587 "'zfs mount -o ro' can\n\tbe used to temporarily "
8588 "mount existing encrypted datasets readonly.\n"));
8589 break;
8591 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
8592 (void) printf(gettext("\tExisting encrypted snapshots "
8593 "and bookmarks contain an on-disk\n\tincompat"
8594 "ibility. This may cause on-disk corruption if "
8595 "they are used\n\twith 'zfs recv'.\n"));
8596 printf_color(ANSI_BOLD, gettext("action: "));
8597 printf_color(ANSI_YELLOW, gettext("To correct the"
8598 "issue, enable the bookmark_v2 feature. No "
8599 "additional\n\taction is needed if there are no "
8600 "encrypted snapshots or bookmarks.\n\tIf preserving"
8601 "the encrypted snapshots and bookmarks is required,"
8602 " use\n\ta non-raw send to backup and restore them."
8603 " Alternately, they may be\n\tremoved to resolve "
8604 "the incompatibility.\n"));
8605 break;
8607 default:
8609 * All errata which allow the pool to be imported
8610 * must contain an action message.
8612 assert(0);
8614 break;
8616 default:
8618 * The remaining errors can't actually be generated, yet.
8620 assert(reason == ZPOOL_STATUS_OK);
8623 if (msgid != NULL) {
8624 printf(" ");
8625 printf_color(ANSI_BOLD, gettext("see:"));
8626 printf(gettext(
8627 " https://openzfs.github.io/openzfs-docs/msg/%s\n"),
8628 msgid);
8631 if (config != NULL) {
8632 uint64_t nerr;
8633 nvlist_t **spares, **l2cache;
8634 uint_t nspares, nl2cache;
8635 pool_checkpoint_stat_t *pcs = NULL;
8636 pool_removal_stat_t *prs = NULL;
8638 print_scan_status(zhp, nvroot);
8640 (void) nvlist_lookup_uint64_array(nvroot,
8641 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
8642 print_removal_status(zhp, prs);
8644 (void) nvlist_lookup_uint64_array(nvroot,
8645 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
8646 print_checkpoint_status(pcs);
8648 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
8649 cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
8650 if (cbp->cb_namewidth < 10)
8651 cbp->cb_namewidth = 10;
8653 color_start(ANSI_BOLD);
8654 (void) printf(gettext("config:\n\n"));
8655 (void) printf(gettext("\t%-*s %-8s %5s %5s %5s"),
8656 cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
8657 "CKSUM");
8658 color_end();
8660 if (cbp->cb_print_slow_ios) {
8661 printf_color(ANSI_BOLD, " %5s", gettext("SLOW"));
8664 if (cbp->vcdl != NULL)
8665 print_cmd_columns(cbp->vcdl, 0);
8667 printf("\n");
8669 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
8670 B_FALSE, NULL);
8672 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
8673 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
8674 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
8676 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
8677 &l2cache, &nl2cache) == 0)
8678 print_l2cache(zhp, cbp, l2cache, nl2cache);
8680 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
8681 &spares, &nspares) == 0)
8682 print_spares(zhp, cbp, spares, nspares);
8684 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
8685 &nerr) == 0) {
8686 (void) printf("\n");
8687 if (nerr == 0) {
8688 (void) printf(gettext(
8689 "errors: No known data errors\n"));
8690 } else if (!cbp->cb_verbose) {
8691 (void) printf(gettext("errors: %llu data "
8692 "errors, use '-v' for a list\n"),
8693 (u_longlong_t)nerr);
8694 } else {
8695 print_error_log(zhp);
8699 if (cbp->cb_dedup_stats)
8700 print_dedup_stats(config);
8701 } else {
8702 (void) printf(gettext("config: The configuration cannot be "
8703 "determined.\n"));
8706 return (0);
8710 * zpool status [-c [script1,script2,...]] [-igLpPstvx] [-T d|u] [pool] ...
8711 * [interval [count]]
8713 * -c CMD For each vdev, run command CMD
8714 * -i Display vdev initialization status.
8715 * -g Display guid for individual vdev name.
8716 * -L Follow links when resolving vdev path name.
8717 * -p Display values in parsable (exact) format.
8718 * -P Display full path for vdev name.
8719 * -s Display slow IOs column.
8720 * -v Display complete error logs
8721 * -x Display only pools with potential problems
8722 * -D Display dedup status (undocumented)
8723 * -t Display vdev TRIM status.
8724 * -T Display a timestamp in date(1) or Unix format
8726 * Describes the health status of all pools or some subset.
8729 zpool_do_status(int argc, char **argv)
8731 int c;
8732 int ret;
8733 float interval = 0;
8734 unsigned long count = 0;
8735 status_cbdata_t cb = { 0 };
8736 char *cmd = NULL;
8738 /* check options */
8739 while ((c = getopt(argc, argv, "c:igLpPsvxDtT:")) != -1) {
8740 switch (c) {
8741 case 'c':
8742 if (cmd != NULL) {
8743 fprintf(stderr,
8744 gettext("Can't set -c flag twice\n"));
8745 exit(1);
8748 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
8749 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
8750 fprintf(stderr, gettext(
8751 "Can't run -c, disabled by "
8752 "ZPOOL_SCRIPTS_ENABLED.\n"));
8753 exit(1);
8756 if ((getuid() <= 0 || geteuid() <= 0) &&
8757 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
8758 fprintf(stderr, gettext(
8759 "Can't run -c with root privileges "
8760 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
8761 exit(1);
8763 cmd = optarg;
8764 break;
8765 case 'i':
8766 cb.cb_print_vdev_init = B_TRUE;
8767 break;
8768 case 'g':
8769 cb.cb_name_flags |= VDEV_NAME_GUID;
8770 break;
8771 case 'L':
8772 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
8773 break;
8774 case 'p':
8775 cb.cb_literal = B_TRUE;
8776 break;
8777 case 'P':
8778 cb.cb_name_flags |= VDEV_NAME_PATH;
8779 break;
8780 case 's':
8781 cb.cb_print_slow_ios = B_TRUE;
8782 break;
8783 case 'v':
8784 cb.cb_verbose = B_TRUE;
8785 break;
8786 case 'x':
8787 cb.cb_explain = B_TRUE;
8788 break;
8789 case 'D':
8790 cb.cb_dedup_stats = B_TRUE;
8791 break;
8792 case 't':
8793 cb.cb_print_vdev_trim = B_TRUE;
8794 break;
8795 case 'T':
8796 get_timestamp_arg(*optarg);
8797 break;
8798 case '?':
8799 if (optopt == 'c') {
8800 print_zpool_script_list("status");
8801 exit(0);
8802 } else {
8803 fprintf(stderr,
8804 gettext("invalid option '%c'\n"), optopt);
8806 usage(B_FALSE);
8810 argc -= optind;
8811 argv += optind;
8813 get_interval_count(&argc, argv, &interval, &count);
8815 if (argc == 0)
8816 cb.cb_allpools = B_TRUE;
8818 cb.cb_first = B_TRUE;
8819 cb.cb_print_status = B_TRUE;
8821 for (;;) {
8822 if (timestamp_fmt != NODATE)
8823 print_timestamp(timestamp_fmt);
8825 if (cmd != NULL)
8826 cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
8827 NULL, NULL, 0, 0);
8829 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8830 cb.cb_literal, status_callback, &cb);
8832 if (cb.vcdl != NULL)
8833 free_vdev_cmd_data_list(cb.vcdl);
8835 if (argc == 0 && cb.cb_count == 0)
8836 (void) fprintf(stderr, gettext("no pools available\n"));
8837 else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
8838 (void) printf(gettext("all pools are healthy\n"));
8840 if (ret != 0)
8841 return (ret);
8843 if (interval == 0)
8844 break;
8846 if (count != 0 && --count == 0)
8847 break;
8849 (void) fsleep(interval);
8852 return (0);
8855 typedef struct upgrade_cbdata {
8856 int cb_first;
8857 int cb_argc;
8858 uint64_t cb_version;
8859 char **cb_argv;
8860 } upgrade_cbdata_t;
8862 static int
8863 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
8865 int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
8866 int *count = (int *)unsupp_fs;
8868 if (zfs_version > ZPL_VERSION) {
8869 (void) printf(gettext("%s (v%d) is not supported by this "
8870 "implementation of ZFS.\n"),
8871 zfs_get_name(zhp), zfs_version);
8872 (*count)++;
8875 zfs_iter_filesystems_v2(zhp, 0, check_unsupp_fs, unsupp_fs);
8877 zfs_close(zhp);
8879 return (0);
8882 static int
8883 upgrade_version(zpool_handle_t *zhp, uint64_t version)
8885 int ret;
8886 nvlist_t *config;
8887 uint64_t oldversion;
8888 int unsupp_fs = 0;
8890 config = zpool_get_config(zhp, NULL);
8891 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
8892 &oldversion) == 0);
8894 char compat[ZFS_MAXPROPLEN];
8895 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
8896 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
8897 compat[0] = '\0';
8899 assert(SPA_VERSION_IS_SUPPORTED(oldversion));
8900 assert(oldversion < version);
8902 ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
8903 if (ret != 0)
8904 return (ret);
8906 if (unsupp_fs) {
8907 (void) fprintf(stderr, gettext("Upgrade not performed due "
8908 "to %d unsupported filesystems (max v%d).\n"),
8909 unsupp_fs, (int)ZPL_VERSION);
8910 return (1);
8913 if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
8914 (void) fprintf(stderr, gettext("Upgrade not performed because "
8915 "'compatibility' property set to '"
8916 ZPOOL_COMPAT_LEGACY "'.\n"));
8917 return (1);
8920 ret = zpool_upgrade(zhp, version);
8921 if (ret != 0)
8922 return (ret);
8924 if (version >= SPA_VERSION_FEATURES) {
8925 (void) printf(gettext("Successfully upgraded "
8926 "'%s' from version %llu to feature flags.\n"),
8927 zpool_get_name(zhp), (u_longlong_t)oldversion);
8928 } else {
8929 (void) printf(gettext("Successfully upgraded "
8930 "'%s' from version %llu to version %llu.\n"),
8931 zpool_get_name(zhp), (u_longlong_t)oldversion,
8932 (u_longlong_t)version);
8935 return (0);
8938 static int
8939 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
8941 int i, ret, count;
8942 boolean_t firstff = B_TRUE;
8943 nvlist_t *enabled = zpool_get_features(zhp);
8945 char compat[ZFS_MAXPROPLEN];
8946 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
8947 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
8948 compat[0] = '\0';
8950 boolean_t requested_features[SPA_FEATURES];
8951 if (zpool_do_load_compat(compat, requested_features) !=
8952 ZPOOL_COMPATIBILITY_OK)
8953 return (-1);
8955 count = 0;
8956 for (i = 0; i < SPA_FEATURES; i++) {
8957 const char *fname = spa_feature_table[i].fi_uname;
8958 const char *fguid = spa_feature_table[i].fi_guid;
8960 if (!spa_feature_table[i].fi_zfs_mod_supported)
8961 continue;
8963 if (!nvlist_exists(enabled, fguid) && requested_features[i]) {
8964 char *propname;
8965 verify(-1 != asprintf(&propname, "feature@%s", fname));
8966 ret = zpool_set_prop(zhp, propname,
8967 ZFS_FEATURE_ENABLED);
8968 if (ret != 0) {
8969 free(propname);
8970 return (ret);
8972 count++;
8974 if (firstff) {
8975 (void) printf(gettext("Enabled the "
8976 "following features on '%s':\n"),
8977 zpool_get_name(zhp));
8978 firstff = B_FALSE;
8980 (void) printf(gettext(" %s\n"), fname);
8981 free(propname);
8985 if (countp != NULL)
8986 *countp = count;
8987 return (0);
8990 static int
8991 upgrade_cb(zpool_handle_t *zhp, void *arg)
8993 upgrade_cbdata_t *cbp = arg;
8994 nvlist_t *config;
8995 uint64_t version;
8996 boolean_t modified_pool = B_FALSE;
8997 int ret;
8999 config = zpool_get_config(zhp, NULL);
9000 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
9001 &version) == 0);
9003 assert(SPA_VERSION_IS_SUPPORTED(version));
9005 if (version < cbp->cb_version) {
9006 cbp->cb_first = B_FALSE;
9007 ret = upgrade_version(zhp, cbp->cb_version);
9008 if (ret != 0)
9009 return (ret);
9010 modified_pool = B_TRUE;
9013 * If they did "zpool upgrade -a", then we could
9014 * be doing ioctls to different pools. We need
9015 * to log this history once to each pool, and bypass
9016 * the normal history logging that happens in main().
9018 (void) zpool_log_history(g_zfs, history_str);
9019 log_history = B_FALSE;
9022 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
9023 int count;
9024 ret = upgrade_enable_all(zhp, &count);
9025 if (ret != 0)
9026 return (ret);
9028 if (count > 0) {
9029 cbp->cb_first = B_FALSE;
9030 modified_pool = B_TRUE;
9034 if (modified_pool) {
9035 (void) printf("\n");
9036 (void) after_zpool_upgrade(zhp);
9039 return (0);
9042 static int
9043 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
9045 upgrade_cbdata_t *cbp = arg;
9046 nvlist_t *config;
9047 uint64_t version;
9049 config = zpool_get_config(zhp, NULL);
9050 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
9051 &version) == 0);
9053 assert(SPA_VERSION_IS_SUPPORTED(version));
9055 if (version < SPA_VERSION_FEATURES) {
9056 if (cbp->cb_first) {
9057 (void) printf(gettext("The following pools are "
9058 "formatted with legacy version numbers and can\n"
9059 "be upgraded to use feature flags. After "
9060 "being upgraded, these pools\nwill no "
9061 "longer be accessible by software that does not "
9062 "support feature\nflags.\n\n"
9063 "Note that setting a pool's 'compatibility' "
9064 "feature to '" ZPOOL_COMPAT_LEGACY "' will\n"
9065 "inhibit upgrades.\n\n"));
9066 (void) printf(gettext("VER POOL\n"));
9067 (void) printf(gettext("--- ------------\n"));
9068 cbp->cb_first = B_FALSE;
9071 (void) printf("%2llu %s\n", (u_longlong_t)version,
9072 zpool_get_name(zhp));
9075 return (0);
9078 static int
9079 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
9081 upgrade_cbdata_t *cbp = arg;
9082 nvlist_t *config;
9083 uint64_t version;
9085 config = zpool_get_config(zhp, NULL);
9086 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
9087 &version) == 0);
9089 if (version >= SPA_VERSION_FEATURES) {
9090 int i;
9091 boolean_t poolfirst = B_TRUE;
9092 nvlist_t *enabled = zpool_get_features(zhp);
9094 for (i = 0; i < SPA_FEATURES; i++) {
9095 const char *fguid = spa_feature_table[i].fi_guid;
9096 const char *fname = spa_feature_table[i].fi_uname;
9098 if (!spa_feature_table[i].fi_zfs_mod_supported)
9099 continue;
9101 if (!nvlist_exists(enabled, fguid)) {
9102 if (cbp->cb_first) {
9103 (void) printf(gettext("\nSome "
9104 "supported features are not "
9105 "enabled on the following pools. "
9106 "Once a\nfeature is enabled the "
9107 "pool may become incompatible with "
9108 "software\nthat does not support "
9109 "the feature. See "
9110 "zpool-features(7) for "
9111 "details.\n\n"
9112 "Note that the pool "
9113 "'compatibility' feature can be "
9114 "used to inhibit\nfeature "
9115 "upgrades.\n\n"));
9116 (void) printf(gettext("POOL "
9117 "FEATURE\n"));
9118 (void) printf(gettext("------"
9119 "---------\n"));
9120 cbp->cb_first = B_FALSE;
9123 if (poolfirst) {
9124 (void) printf(gettext("%s\n"),
9125 zpool_get_name(zhp));
9126 poolfirst = B_FALSE;
9129 (void) printf(gettext(" %s\n"), fname);
9132 * If they did "zpool upgrade -a", then we could
9133 * be doing ioctls to different pools. We need
9134 * to log this history once to each pool, and bypass
9135 * the normal history logging that happens in main().
9137 (void) zpool_log_history(g_zfs, history_str);
9138 log_history = B_FALSE;
9142 return (0);
9145 static int
9146 upgrade_one(zpool_handle_t *zhp, void *data)
9148 boolean_t modified_pool = B_FALSE;
9149 upgrade_cbdata_t *cbp = data;
9150 uint64_t cur_version;
9151 int ret;
9153 if (strcmp("log", zpool_get_name(zhp)) == 0) {
9154 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
9155 "Pool 'log' must be renamed using export and import"
9156 " to upgrade.\n"));
9157 return (1);
9160 cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
9161 if (cur_version > cbp->cb_version) {
9162 (void) printf(gettext("Pool '%s' is already formatted "
9163 "using more current version '%llu'.\n\n"),
9164 zpool_get_name(zhp), (u_longlong_t)cur_version);
9165 return (0);
9168 if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
9169 (void) printf(gettext("Pool '%s' is already formatted "
9170 "using version %llu.\n\n"), zpool_get_name(zhp),
9171 (u_longlong_t)cbp->cb_version);
9172 return (0);
9175 if (cur_version != cbp->cb_version) {
9176 modified_pool = B_TRUE;
9177 ret = upgrade_version(zhp, cbp->cb_version);
9178 if (ret != 0)
9179 return (ret);
9182 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
9183 int count = 0;
9184 ret = upgrade_enable_all(zhp, &count);
9185 if (ret != 0)
9186 return (ret);
9188 if (count != 0) {
9189 modified_pool = B_TRUE;
9190 } else if (cur_version == SPA_VERSION) {
9191 (void) printf(gettext("Pool '%s' already has all "
9192 "supported and requested features enabled.\n"),
9193 zpool_get_name(zhp));
9197 if (modified_pool) {
9198 (void) printf("\n");
9199 (void) after_zpool_upgrade(zhp);
9202 return (0);
9206 * zpool upgrade
9207 * zpool upgrade -v
9208 * zpool upgrade [-V version] <-a | pool ...>
9210 * With no arguments, display downrev'd ZFS pool available for upgrade.
9211 * Individual pools can be upgraded by specifying the pool, and '-a' will
9212 * upgrade all pools.
9215 zpool_do_upgrade(int argc, char **argv)
9217 int c;
9218 upgrade_cbdata_t cb = { 0 };
9219 int ret = 0;
9220 boolean_t showversions = B_FALSE;
9221 boolean_t upgradeall = B_FALSE;
9222 char *end;
9225 /* check options */
9226 while ((c = getopt(argc, argv, ":avV:")) != -1) {
9227 switch (c) {
9228 case 'a':
9229 upgradeall = B_TRUE;
9230 break;
9231 case 'v':
9232 showversions = B_TRUE;
9233 break;
9234 case 'V':
9235 cb.cb_version = strtoll(optarg, &end, 10);
9236 if (*end != '\0' ||
9237 !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
9238 (void) fprintf(stderr,
9239 gettext("invalid version '%s'\n"), optarg);
9240 usage(B_FALSE);
9242 break;
9243 case ':':
9244 (void) fprintf(stderr, gettext("missing argument for "
9245 "'%c' option\n"), optopt);
9246 usage(B_FALSE);
9247 break;
9248 case '?':
9249 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9250 optopt);
9251 usage(B_FALSE);
9255 cb.cb_argc = argc;
9256 cb.cb_argv = argv;
9257 argc -= optind;
9258 argv += optind;
9260 if (cb.cb_version == 0) {
9261 cb.cb_version = SPA_VERSION;
9262 } else if (!upgradeall && argc == 0) {
9263 (void) fprintf(stderr, gettext("-V option is "
9264 "incompatible with other arguments\n"));
9265 usage(B_FALSE);
9268 if (showversions) {
9269 if (upgradeall || argc != 0) {
9270 (void) fprintf(stderr, gettext("-v option is "
9271 "incompatible with other arguments\n"));
9272 usage(B_FALSE);
9274 } else if (upgradeall) {
9275 if (argc != 0) {
9276 (void) fprintf(stderr, gettext("-a option should not "
9277 "be used along with a pool name\n"));
9278 usage(B_FALSE);
9282 (void) printf("%s", gettext("This system supports ZFS pool feature "
9283 "flags.\n\n"));
9284 if (showversions) {
9285 int i;
9287 (void) printf(gettext("The following features are "
9288 "supported:\n\n"));
9289 (void) printf(gettext("FEAT DESCRIPTION\n"));
9290 (void) printf("----------------------------------------------"
9291 "---------------\n");
9292 for (i = 0; i < SPA_FEATURES; i++) {
9293 zfeature_info_t *fi = &spa_feature_table[i];
9294 if (!fi->fi_zfs_mod_supported)
9295 continue;
9296 const char *ro =
9297 (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
9298 " (read-only compatible)" : "";
9300 (void) printf("%-37s%s\n", fi->fi_uname, ro);
9301 (void) printf(" %s\n", fi->fi_desc);
9303 (void) printf("\n");
9305 (void) printf(gettext("The following legacy versions are also "
9306 "supported:\n\n"));
9307 (void) printf(gettext("VER DESCRIPTION\n"));
9308 (void) printf("--- -----------------------------------------"
9309 "---------------\n");
9310 (void) printf(gettext(" 1 Initial ZFS version\n"));
9311 (void) printf(gettext(" 2 Ditto blocks "
9312 "(replicated metadata)\n"));
9313 (void) printf(gettext(" 3 Hot spares and double parity "
9314 "RAID-Z\n"));
9315 (void) printf(gettext(" 4 zpool history\n"));
9316 (void) printf(gettext(" 5 Compression using the gzip "
9317 "algorithm\n"));
9318 (void) printf(gettext(" 6 bootfs pool property\n"));
9319 (void) printf(gettext(" 7 Separate intent log devices\n"));
9320 (void) printf(gettext(" 8 Delegated administration\n"));
9321 (void) printf(gettext(" 9 refquota and refreservation "
9322 "properties\n"));
9323 (void) printf(gettext(" 10 Cache devices\n"));
9324 (void) printf(gettext(" 11 Improved scrub performance\n"));
9325 (void) printf(gettext(" 12 Snapshot properties\n"));
9326 (void) printf(gettext(" 13 snapused property\n"));
9327 (void) printf(gettext(" 14 passthrough-x aclinherit\n"));
9328 (void) printf(gettext(" 15 user/group space accounting\n"));
9329 (void) printf(gettext(" 16 stmf property support\n"));
9330 (void) printf(gettext(" 17 Triple-parity RAID-Z\n"));
9331 (void) printf(gettext(" 18 Snapshot user holds\n"));
9332 (void) printf(gettext(" 19 Log device removal\n"));
9333 (void) printf(gettext(" 20 Compression using zle "
9334 "(zero-length encoding)\n"));
9335 (void) printf(gettext(" 21 Deduplication\n"));
9336 (void) printf(gettext(" 22 Received properties\n"));
9337 (void) printf(gettext(" 23 Slim ZIL\n"));
9338 (void) printf(gettext(" 24 System attributes\n"));
9339 (void) printf(gettext(" 25 Improved scrub stats\n"));
9340 (void) printf(gettext(" 26 Improved snapshot deletion "
9341 "performance\n"));
9342 (void) printf(gettext(" 27 Improved snapshot creation "
9343 "performance\n"));
9344 (void) printf(gettext(" 28 Multiple vdev replacements\n"));
9345 (void) printf(gettext("\nFor more information on a particular "
9346 "version, including supported releases,\n"));
9347 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
9348 } else if (argc == 0 && upgradeall) {
9349 cb.cb_first = B_TRUE;
9350 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
9351 if (ret == 0 && cb.cb_first) {
9352 if (cb.cb_version == SPA_VERSION) {
9353 (void) printf(gettext("All pools are already "
9354 "formatted using feature flags.\n\n"));
9355 (void) printf(gettext("Every feature flags "
9356 "pool already has all supported and "
9357 "requested features enabled.\n"));
9358 } else {
9359 (void) printf(gettext("All pools are already "
9360 "formatted with version %llu or higher.\n"),
9361 (u_longlong_t)cb.cb_version);
9364 } else if (argc == 0) {
9365 cb.cb_first = B_TRUE;
9366 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
9367 assert(ret == 0);
9369 if (cb.cb_first) {
9370 (void) printf(gettext("All pools are formatted "
9371 "using feature flags.\n\n"));
9372 } else {
9373 (void) printf(gettext("\nUse 'zpool upgrade -v' "
9374 "for a list of available legacy versions.\n"));
9377 cb.cb_first = B_TRUE;
9378 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
9379 assert(ret == 0);
9381 if (cb.cb_first) {
9382 (void) printf(gettext("Every feature flags pool has "
9383 "all supported and requested features enabled.\n"));
9384 } else {
9385 (void) printf(gettext("\n"));
9387 } else {
9388 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9389 B_FALSE, upgrade_one, &cb);
9392 return (ret);
9395 typedef struct hist_cbdata {
9396 boolean_t first;
9397 boolean_t longfmt;
9398 boolean_t internal;
9399 } hist_cbdata_t;
9401 static void
9402 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
9404 nvlist_t **records;
9405 uint_t numrecords;
9406 int i;
9408 verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
9409 &records, &numrecords) == 0);
9410 for (i = 0; i < numrecords; i++) {
9411 nvlist_t *rec = records[i];
9412 char tbuf[64] = "";
9414 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
9415 time_t tsec;
9416 struct tm t;
9418 tsec = fnvlist_lookup_uint64(records[i],
9419 ZPOOL_HIST_TIME);
9420 (void) localtime_r(&tsec, &t);
9421 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
9424 if (nvlist_exists(rec, ZPOOL_HIST_ELAPSED_NS)) {
9425 uint64_t elapsed_ns = fnvlist_lookup_int64(records[i],
9426 ZPOOL_HIST_ELAPSED_NS);
9427 (void) snprintf(tbuf + strlen(tbuf),
9428 sizeof (tbuf) - strlen(tbuf),
9429 " (%lldms)", (long long)elapsed_ns / 1000 / 1000);
9432 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
9433 (void) printf("%s %s", tbuf,
9434 fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
9435 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
9436 int ievent =
9437 fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
9438 if (!cb->internal)
9439 continue;
9440 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
9441 (void) printf("%s unrecognized record:\n",
9442 tbuf);
9443 dump_nvlist(rec, 4);
9444 continue;
9446 (void) printf("%s [internal %s txg:%lld] %s", tbuf,
9447 zfs_history_event_names[ievent],
9448 (longlong_t)fnvlist_lookup_uint64(
9449 rec, ZPOOL_HIST_TXG),
9450 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
9451 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
9452 if (!cb->internal)
9453 continue;
9454 (void) printf("%s [txg:%lld] %s", tbuf,
9455 (longlong_t)fnvlist_lookup_uint64(
9456 rec, ZPOOL_HIST_TXG),
9457 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
9458 if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
9459 (void) printf(" %s (%llu)",
9460 fnvlist_lookup_string(rec,
9461 ZPOOL_HIST_DSNAME),
9462 (u_longlong_t)fnvlist_lookup_uint64(rec,
9463 ZPOOL_HIST_DSID));
9465 (void) printf(" %s", fnvlist_lookup_string(rec,
9466 ZPOOL_HIST_INT_STR));
9467 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
9468 if (!cb->internal)
9469 continue;
9470 (void) printf("%s ioctl %s\n", tbuf,
9471 fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
9472 if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
9473 (void) printf(" input:\n");
9474 dump_nvlist(fnvlist_lookup_nvlist(rec,
9475 ZPOOL_HIST_INPUT_NVL), 8);
9477 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
9478 (void) printf(" output:\n");
9479 dump_nvlist(fnvlist_lookup_nvlist(rec,
9480 ZPOOL_HIST_OUTPUT_NVL), 8);
9482 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_SIZE)) {
9483 (void) printf(" output nvlist omitted; "
9484 "original size: %lldKB\n",
9485 (longlong_t)fnvlist_lookup_int64(rec,
9486 ZPOOL_HIST_OUTPUT_SIZE) / 1024);
9488 if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
9489 (void) printf(" errno: %lld\n",
9490 (longlong_t)fnvlist_lookup_int64(rec,
9491 ZPOOL_HIST_ERRNO));
9493 } else {
9494 if (!cb->internal)
9495 continue;
9496 (void) printf("%s unrecognized record:\n", tbuf);
9497 dump_nvlist(rec, 4);
9500 if (!cb->longfmt) {
9501 (void) printf("\n");
9502 continue;
9504 (void) printf(" [");
9505 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
9506 uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
9507 struct passwd *pwd = getpwuid(who);
9508 (void) printf("user %d ", (int)who);
9509 if (pwd != NULL)
9510 (void) printf("(%s) ", pwd->pw_name);
9512 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
9513 (void) printf("on %s",
9514 fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
9516 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
9517 (void) printf(":%s",
9518 fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
9521 (void) printf("]");
9522 (void) printf("\n");
9527 * Print out the command history for a specific pool.
9529 static int
9530 get_history_one(zpool_handle_t *zhp, void *data)
9532 nvlist_t *nvhis;
9533 int ret;
9534 hist_cbdata_t *cb = (hist_cbdata_t *)data;
9535 uint64_t off = 0;
9536 boolean_t eof = B_FALSE;
9538 cb->first = B_FALSE;
9540 (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
9542 while (!eof) {
9543 if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
9544 return (ret);
9546 print_history_records(nvhis, cb);
9547 nvlist_free(nvhis);
9549 (void) printf("\n");
9551 return (ret);
9555 * zpool history <pool>
9557 * Displays the history of commands that modified pools.
9560 zpool_do_history(int argc, char **argv)
9562 hist_cbdata_t cbdata = { 0 };
9563 int ret;
9564 int c;
9566 cbdata.first = B_TRUE;
9567 /* check options */
9568 while ((c = getopt(argc, argv, "li")) != -1) {
9569 switch (c) {
9570 case 'l':
9571 cbdata.longfmt = B_TRUE;
9572 break;
9573 case 'i':
9574 cbdata.internal = B_TRUE;
9575 break;
9576 case '?':
9577 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9578 optopt);
9579 usage(B_FALSE);
9582 argc -= optind;
9583 argv += optind;
9585 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9586 B_FALSE, get_history_one, &cbdata);
9588 if (argc == 0 && cbdata.first == B_TRUE) {
9589 (void) fprintf(stderr, gettext("no pools available\n"));
9590 return (0);
9593 return (ret);
9596 typedef struct ev_opts {
9597 int verbose;
9598 int scripted;
9599 int follow;
9600 int clear;
9601 char poolname[ZFS_MAX_DATASET_NAME_LEN];
9602 } ev_opts_t;
9604 static void
9605 zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
9607 char ctime_str[26], str[32];
9608 const char *ptr;
9609 int64_t *tv;
9610 uint_t n;
9612 verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
9613 memset(str, ' ', 32);
9614 (void) ctime_r((const time_t *)&tv[0], ctime_str);
9615 (void) memcpy(str, ctime_str+4, 6); /* 'Jun 30' */
9616 (void) memcpy(str+7, ctime_str+20, 4); /* '1993' */
9617 (void) memcpy(str+12, ctime_str+11, 8); /* '21:49:08' */
9618 (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
9619 if (opts->scripted)
9620 (void) printf(gettext("%s\t"), str);
9621 else
9622 (void) printf(gettext("%s "), str);
9624 verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
9625 (void) printf(gettext("%s\n"), ptr);
9628 static void
9629 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
9631 nvpair_t *nvp;
9633 for (nvp = nvlist_next_nvpair(nvl, NULL);
9634 nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
9636 data_type_t type = nvpair_type(nvp);
9637 const char *name = nvpair_name(nvp);
9639 boolean_t b;
9640 uint8_t i8;
9641 uint16_t i16;
9642 uint32_t i32;
9643 uint64_t i64;
9644 const char *str;
9645 nvlist_t *cnv;
9647 printf(gettext("%*s%s = "), depth, "", name);
9649 switch (type) {
9650 case DATA_TYPE_BOOLEAN:
9651 printf(gettext("%s"), "1");
9652 break;
9654 case DATA_TYPE_BOOLEAN_VALUE:
9655 (void) nvpair_value_boolean_value(nvp, &b);
9656 printf(gettext("%s"), b ? "1" : "0");
9657 break;
9659 case DATA_TYPE_BYTE:
9660 (void) nvpair_value_byte(nvp, &i8);
9661 printf(gettext("0x%x"), i8);
9662 break;
9664 case DATA_TYPE_INT8:
9665 (void) nvpair_value_int8(nvp, (void *)&i8);
9666 printf(gettext("0x%x"), i8);
9667 break;
9669 case DATA_TYPE_UINT8:
9670 (void) nvpair_value_uint8(nvp, &i8);
9671 printf(gettext("0x%x"), i8);
9672 break;
9674 case DATA_TYPE_INT16:
9675 (void) nvpair_value_int16(nvp, (void *)&i16);
9676 printf(gettext("0x%x"), i16);
9677 break;
9679 case DATA_TYPE_UINT16:
9680 (void) nvpair_value_uint16(nvp, &i16);
9681 printf(gettext("0x%x"), i16);
9682 break;
9684 case DATA_TYPE_INT32:
9685 (void) nvpair_value_int32(nvp, (void *)&i32);
9686 printf(gettext("0x%x"), i32);
9687 break;
9689 case DATA_TYPE_UINT32:
9690 (void) nvpair_value_uint32(nvp, &i32);
9691 printf(gettext("0x%x"), i32);
9692 break;
9694 case DATA_TYPE_INT64:
9695 (void) nvpair_value_int64(nvp, (void *)&i64);
9696 printf(gettext("0x%llx"), (u_longlong_t)i64);
9697 break;
9699 case DATA_TYPE_UINT64:
9700 (void) nvpair_value_uint64(nvp, &i64);
9702 * translate vdev state values to readable
9703 * strings to aide zpool events consumers
9705 if (strcmp(name,
9706 FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
9707 strcmp(name,
9708 FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
9709 printf(gettext("\"%s\" (0x%llx)"),
9710 zpool_state_to_name(i64, VDEV_AUX_NONE),
9711 (u_longlong_t)i64);
9712 } else {
9713 printf(gettext("0x%llx"), (u_longlong_t)i64);
9715 break;
9717 case DATA_TYPE_HRTIME:
9718 (void) nvpair_value_hrtime(nvp, (void *)&i64);
9719 printf(gettext("0x%llx"), (u_longlong_t)i64);
9720 break;
9722 case DATA_TYPE_STRING:
9723 (void) nvpair_value_string(nvp, &str);
9724 printf(gettext("\"%s\""), str ? str : "<NULL>");
9725 break;
9727 case DATA_TYPE_NVLIST:
9728 printf(gettext("(embedded nvlist)\n"));
9729 (void) nvpair_value_nvlist(nvp, &cnv);
9730 zpool_do_events_nvprint(cnv, depth + 8);
9731 printf(gettext("%*s(end %s)"), depth, "", name);
9732 break;
9734 case DATA_TYPE_NVLIST_ARRAY: {
9735 nvlist_t **val;
9736 uint_t i, nelem;
9738 (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
9739 printf(gettext("(%d embedded nvlists)\n"), nelem);
9740 for (i = 0; i < nelem; i++) {
9741 printf(gettext("%*s%s[%d] = %s\n"),
9742 depth, "", name, i, "(embedded nvlist)");
9743 zpool_do_events_nvprint(val[i], depth + 8);
9744 printf(gettext("%*s(end %s[%i])\n"),
9745 depth, "", name, i);
9747 printf(gettext("%*s(end %s)\n"), depth, "", name);
9749 break;
9751 case DATA_TYPE_INT8_ARRAY: {
9752 int8_t *val;
9753 uint_t i, nelem;
9755 (void) nvpair_value_int8_array(nvp, &val, &nelem);
9756 for (i = 0; i < nelem; i++)
9757 printf(gettext("0x%x "), val[i]);
9759 break;
9762 case DATA_TYPE_UINT8_ARRAY: {
9763 uint8_t *val;
9764 uint_t i, nelem;
9766 (void) nvpair_value_uint8_array(nvp, &val, &nelem);
9767 for (i = 0; i < nelem; i++)
9768 printf(gettext("0x%x "), val[i]);
9770 break;
9773 case DATA_TYPE_INT16_ARRAY: {
9774 int16_t *val;
9775 uint_t i, nelem;
9777 (void) nvpair_value_int16_array(nvp, &val, &nelem);
9778 for (i = 0; i < nelem; i++)
9779 printf(gettext("0x%x "), val[i]);
9781 break;
9784 case DATA_TYPE_UINT16_ARRAY: {
9785 uint16_t *val;
9786 uint_t i, nelem;
9788 (void) nvpair_value_uint16_array(nvp, &val, &nelem);
9789 for (i = 0; i < nelem; i++)
9790 printf(gettext("0x%x "), val[i]);
9792 break;
9795 case DATA_TYPE_INT32_ARRAY: {
9796 int32_t *val;
9797 uint_t i, nelem;
9799 (void) nvpair_value_int32_array(nvp, &val, &nelem);
9800 for (i = 0; i < nelem; i++)
9801 printf(gettext("0x%x "), val[i]);
9803 break;
9806 case DATA_TYPE_UINT32_ARRAY: {
9807 uint32_t *val;
9808 uint_t i, nelem;
9810 (void) nvpair_value_uint32_array(nvp, &val, &nelem);
9811 for (i = 0; i < nelem; i++)
9812 printf(gettext("0x%x "), val[i]);
9814 break;
9817 case DATA_TYPE_INT64_ARRAY: {
9818 int64_t *val;
9819 uint_t i, nelem;
9821 (void) nvpair_value_int64_array(nvp, &val, &nelem);
9822 for (i = 0; i < nelem; i++)
9823 printf(gettext("0x%llx "),
9824 (u_longlong_t)val[i]);
9826 break;
9829 case DATA_TYPE_UINT64_ARRAY: {
9830 uint64_t *val;
9831 uint_t i, nelem;
9833 (void) nvpair_value_uint64_array(nvp, &val, &nelem);
9834 for (i = 0; i < nelem; i++)
9835 printf(gettext("0x%llx "),
9836 (u_longlong_t)val[i]);
9838 break;
9841 case DATA_TYPE_STRING_ARRAY: {
9842 const char **str;
9843 uint_t i, nelem;
9845 (void) nvpair_value_string_array(nvp, &str, &nelem);
9846 for (i = 0; i < nelem; i++)
9847 printf(gettext("\"%s\" "),
9848 str[i] ? str[i] : "<NULL>");
9850 break;
9853 case DATA_TYPE_BOOLEAN_ARRAY:
9854 case DATA_TYPE_BYTE_ARRAY:
9855 case DATA_TYPE_DOUBLE:
9856 case DATA_TYPE_DONTCARE:
9857 case DATA_TYPE_UNKNOWN:
9858 printf(gettext("<unknown>"));
9859 break;
9862 printf(gettext("\n"));
9866 static int
9867 zpool_do_events_next(ev_opts_t *opts)
9869 nvlist_t *nvl;
9870 int zevent_fd, ret, dropped;
9871 const char *pool;
9873 zevent_fd = open(ZFS_DEV, O_RDWR);
9874 VERIFY(zevent_fd >= 0);
9876 if (!opts->scripted)
9877 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
9879 while (1) {
9880 ret = zpool_events_next(g_zfs, &nvl, &dropped,
9881 (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
9882 if (ret || nvl == NULL)
9883 break;
9885 if (dropped > 0)
9886 (void) printf(gettext("dropped %d events\n"), dropped);
9888 if (strlen(opts->poolname) > 0 &&
9889 nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
9890 strcmp(opts->poolname, pool) != 0)
9891 continue;
9893 zpool_do_events_short(nvl, opts);
9895 if (opts->verbose) {
9896 zpool_do_events_nvprint(nvl, 8);
9897 printf(gettext("\n"));
9899 (void) fflush(stdout);
9901 nvlist_free(nvl);
9904 VERIFY(0 == close(zevent_fd));
9906 return (ret);
9909 static int
9910 zpool_do_events_clear(void)
9912 int count, ret;
9914 ret = zpool_events_clear(g_zfs, &count);
9915 if (!ret)
9916 (void) printf(gettext("cleared %d events\n"), count);
9918 return (ret);
9922 * zpool events [-vHf [pool] | -c]
9924 * Displays events logs by ZFS.
9927 zpool_do_events(int argc, char **argv)
9929 ev_opts_t opts = { 0 };
9930 int ret;
9931 int c;
9933 /* check options */
9934 while ((c = getopt(argc, argv, "vHfc")) != -1) {
9935 switch (c) {
9936 case 'v':
9937 opts.verbose = 1;
9938 break;
9939 case 'H':
9940 opts.scripted = 1;
9941 break;
9942 case 'f':
9943 opts.follow = 1;
9944 break;
9945 case 'c':
9946 opts.clear = 1;
9947 break;
9948 case '?':
9949 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9950 optopt);
9951 usage(B_FALSE);
9954 argc -= optind;
9955 argv += optind;
9957 if (argc > 1) {
9958 (void) fprintf(stderr, gettext("too many arguments\n"));
9959 usage(B_FALSE);
9960 } else if (argc == 1) {
9961 (void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
9962 if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
9963 (void) fprintf(stderr,
9964 gettext("invalid pool name '%s'\n"), opts.poolname);
9965 usage(B_FALSE);
9969 if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
9970 opts.clear) {
9971 (void) fprintf(stderr,
9972 gettext("invalid options combined with -c\n"));
9973 usage(B_FALSE);
9976 if (opts.clear)
9977 ret = zpool_do_events_clear();
9978 else
9979 ret = zpool_do_events_next(&opts);
9981 return (ret);
9984 static int
9985 get_callback_vdev(zpool_handle_t *zhp, char *vdevname, void *data)
9987 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
9988 char value[ZFS_MAXPROPLEN];
9989 zprop_source_t srctype;
9991 for (zprop_list_t *pl = cbp->cb_proplist; pl != NULL;
9992 pl = pl->pl_next) {
9993 char *prop_name;
9995 * If the first property is pool name, it is a special
9996 * placeholder that we can skip. This will also skip
9997 * over the name property when 'all' is specified.
9999 if (pl->pl_prop == ZPOOL_PROP_NAME &&
10000 pl == cbp->cb_proplist)
10001 continue;
10003 if (pl->pl_prop == ZPROP_INVAL) {
10004 prop_name = pl->pl_user_prop;
10005 } else {
10006 prop_name = (char *)vdev_prop_to_name(pl->pl_prop);
10008 if (zpool_get_vdev_prop(zhp, vdevname, pl->pl_prop,
10009 prop_name, value, sizeof (value), &srctype,
10010 cbp->cb_literal) == 0) {
10011 zprop_print_one_property(vdevname, cbp, prop_name,
10012 value, srctype, NULL, NULL);
10016 return (0);
10019 static int
10020 get_callback_vdev_cb(void *zhp_data, nvlist_t *nv, void *data)
10022 zpool_handle_t *zhp = zhp_data;
10023 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
10024 char *vdevname;
10025 const char *type;
10026 int ret;
10029 * zpool_vdev_name() transforms the root vdev name (i.e., root-0) to the
10030 * pool name for display purposes, which is not desired. Fallback to
10031 * zpool_vdev_name() when not dealing with the root vdev.
10033 type = fnvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE);
10034 if (zhp != NULL && strcmp(type, "root") == 0)
10035 vdevname = strdup("root-0");
10036 else
10037 vdevname = zpool_vdev_name(g_zfs, zhp, nv,
10038 cbp->cb_vdevs.cb_name_flags);
10040 (void) vdev_expand_proplist(zhp, vdevname, &cbp->cb_proplist);
10042 ret = get_callback_vdev(zhp, vdevname, data);
10044 free(vdevname);
10046 return (ret);
10049 static int
10050 get_callback(zpool_handle_t *zhp, void *data)
10052 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
10053 char value[ZFS_MAXPROPLEN];
10054 zprop_source_t srctype;
10055 zprop_list_t *pl;
10056 int vid;
10058 if (cbp->cb_type == ZFS_TYPE_VDEV) {
10059 if (strcmp(cbp->cb_vdevs.cb_names[0], "all-vdevs") == 0) {
10060 for_each_vdev(zhp, get_callback_vdev_cb, data);
10061 } else {
10062 /* Adjust column widths for vdev properties */
10063 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
10064 vid++) {
10065 vdev_expand_proplist(zhp,
10066 cbp->cb_vdevs.cb_names[vid],
10067 &cbp->cb_proplist);
10069 /* Display the properties */
10070 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
10071 vid++) {
10072 get_callback_vdev(zhp,
10073 cbp->cb_vdevs.cb_names[vid], data);
10076 } else {
10077 assert(cbp->cb_type == ZFS_TYPE_POOL);
10078 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
10080 * Skip the special fake placeholder. This will also
10081 * skip over the name property when 'all' is specified.
10083 if (pl->pl_prop == ZPOOL_PROP_NAME &&
10084 pl == cbp->cb_proplist)
10085 continue;
10087 if (pl->pl_prop == ZPROP_INVAL &&
10088 zfs_prop_user(pl->pl_user_prop)) {
10089 srctype = ZPROP_SRC_LOCAL;
10091 if (zpool_get_userprop(zhp, pl->pl_user_prop,
10092 value, sizeof (value), &srctype) != 0)
10093 continue;
10095 zprop_print_one_property(zpool_get_name(zhp),
10096 cbp, pl->pl_user_prop, value, srctype,
10097 NULL, NULL);
10098 } else if (pl->pl_prop == ZPROP_INVAL &&
10099 (zpool_prop_feature(pl->pl_user_prop) ||
10100 zpool_prop_unsupported(pl->pl_user_prop))) {
10101 srctype = ZPROP_SRC_LOCAL;
10103 if (zpool_prop_get_feature(zhp,
10104 pl->pl_user_prop, value,
10105 sizeof (value)) == 0) {
10106 zprop_print_one_property(
10107 zpool_get_name(zhp), cbp,
10108 pl->pl_user_prop, value, srctype,
10109 NULL, NULL);
10111 } else {
10112 if (zpool_get_prop(zhp, pl->pl_prop, value,
10113 sizeof (value), &srctype,
10114 cbp->cb_literal) != 0)
10115 continue;
10117 zprop_print_one_property(zpool_get_name(zhp),
10118 cbp, zpool_prop_to_name(pl->pl_prop),
10119 value, srctype, NULL, NULL);
10124 return (0);
10128 * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
10130 * -H Scripted mode. Don't display headers, and separate properties
10131 * by a single tab.
10132 * -o List of columns to display. Defaults to
10133 * "name,property,value,source".
10134 * -p Display values in parsable (exact) format.
10136 * Get properties of pools in the system. Output space statistics
10137 * for each one as well as other attributes.
10140 zpool_do_get(int argc, char **argv)
10142 zprop_get_cbdata_t cb = { 0 };
10143 zprop_list_t fake_name = { 0 };
10144 int ret;
10145 int c, i;
10146 char *propstr = NULL;
10147 char *vdev = NULL;
10149 cb.cb_first = B_TRUE;
10152 * Set up default columns and sources.
10154 cb.cb_sources = ZPROP_SRC_ALL;
10155 cb.cb_columns[0] = GET_COL_NAME;
10156 cb.cb_columns[1] = GET_COL_PROPERTY;
10157 cb.cb_columns[2] = GET_COL_VALUE;
10158 cb.cb_columns[3] = GET_COL_SOURCE;
10159 cb.cb_type = ZFS_TYPE_POOL;
10160 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
10161 current_prop_type = cb.cb_type;
10163 /* check options */
10164 while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
10165 switch (c) {
10166 case 'p':
10167 cb.cb_literal = B_TRUE;
10168 break;
10169 case 'H':
10170 cb.cb_scripted = B_TRUE;
10171 break;
10172 case 'o':
10173 memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
10174 i = 0;
10176 for (char *tok; (tok = strsep(&optarg, ",")); ) {
10177 static const char *const col_opts[] =
10178 { "name", "property", "value", "source",
10179 "all" };
10180 static const zfs_get_column_t col_cols[] =
10181 { GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
10182 GET_COL_SOURCE };
10184 if (i == ZFS_GET_NCOLS - 1) {
10185 (void) fprintf(stderr, gettext("too "
10186 "many fields given to -o "
10187 "option\n"));
10188 usage(B_FALSE);
10191 for (c = 0; c < ARRAY_SIZE(col_opts); ++c)
10192 if (strcmp(tok, col_opts[c]) == 0)
10193 goto found;
10195 (void) fprintf(stderr,
10196 gettext("invalid column name '%s'\n"), tok);
10197 usage(B_FALSE);
10199 found:
10200 if (c >= 4) {
10201 if (i > 0) {
10202 (void) fprintf(stderr,
10203 gettext("\"all\" conflicts "
10204 "with specific fields "
10205 "given to -o option\n"));
10206 usage(B_FALSE);
10209 memcpy(cb.cb_columns, col_cols,
10210 sizeof (col_cols));
10211 i = ZFS_GET_NCOLS - 1;
10212 } else
10213 cb.cb_columns[i++] = col_cols[c];
10215 break;
10216 case '?':
10217 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
10218 optopt);
10219 usage(B_FALSE);
10223 argc -= optind;
10224 argv += optind;
10226 if (argc < 1) {
10227 (void) fprintf(stderr, gettext("missing property "
10228 "argument\n"));
10229 usage(B_FALSE);
10232 /* Properties list is needed later by zprop_get_list() */
10233 propstr = argv[0];
10235 argc--;
10236 argv++;
10238 if (argc == 0) {
10239 /* No args, so just print the defaults. */
10240 } else if (are_all_pools(argc, argv)) {
10241 /* All the args are pool names */
10242 } else if (are_all_pools(1, argv)) {
10243 /* The first arg is a pool name */
10244 if ((argc == 2 && strcmp(argv[1], "all-vdevs") == 0) ||
10245 (argc == 2 && strcmp(argv[1], "root") == 0) ||
10246 are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
10247 &cb.cb_vdevs)) {
10249 if (strcmp(argv[1], "root") == 0)
10250 vdev = strdup("root-0");
10251 else
10252 vdev = strdup(argv[1]);
10254 /* ... and the rest are vdev names */
10255 cb.cb_vdevs.cb_names = &vdev;
10256 cb.cb_vdevs.cb_names_count = argc - 1;
10257 cb.cb_type = ZFS_TYPE_VDEV;
10258 argc = 1; /* One pool to process */
10259 } else {
10260 fprintf(stderr, gettext("Expected a list of vdevs in"
10261 " \"%s\", but got:\n"), argv[0]);
10262 error_list_unresolved_vdevs(argc - 1, argv + 1,
10263 argv[0], &cb.cb_vdevs);
10264 fprintf(stderr, "\n");
10265 usage(B_FALSE);
10266 return (1);
10268 } else {
10270 * The first arg isn't a pool name,
10272 fprintf(stderr, gettext("missing pool name.\n"));
10273 fprintf(stderr, "\n");
10274 usage(B_FALSE);
10275 return (1);
10278 if (zprop_get_list(g_zfs, propstr, &cb.cb_proplist,
10279 cb.cb_type) != 0) {
10280 /* Use correct list of valid properties (pool or vdev) */
10281 current_prop_type = cb.cb_type;
10282 usage(B_FALSE);
10285 if (cb.cb_proplist != NULL) {
10286 fake_name.pl_prop = ZPOOL_PROP_NAME;
10287 fake_name.pl_width = strlen(gettext("NAME"));
10288 fake_name.pl_next = cb.cb_proplist;
10289 cb.cb_proplist = &fake_name;
10292 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist, cb.cb_type,
10293 cb.cb_literal, get_callback, &cb);
10295 if (cb.cb_proplist == &fake_name)
10296 zprop_free_list(fake_name.pl_next);
10297 else
10298 zprop_free_list(cb.cb_proplist);
10300 if (vdev != NULL)
10301 free(vdev);
10303 return (ret);
10306 typedef struct set_cbdata {
10307 char *cb_propname;
10308 char *cb_value;
10309 zfs_type_t cb_type;
10310 vdev_cbdata_t cb_vdevs;
10311 boolean_t cb_any_successful;
10312 } set_cbdata_t;
10314 static int
10315 set_pool_callback(zpool_handle_t *zhp, set_cbdata_t *cb)
10317 int error;
10319 /* Check if we have out-of-bounds features */
10320 if (strcmp(cb->cb_propname, ZPOOL_CONFIG_COMPATIBILITY) == 0) {
10321 boolean_t features[SPA_FEATURES];
10322 if (zpool_do_load_compat(cb->cb_value, features) !=
10323 ZPOOL_COMPATIBILITY_OK)
10324 return (-1);
10326 nvlist_t *enabled = zpool_get_features(zhp);
10327 spa_feature_t i;
10328 for (i = 0; i < SPA_FEATURES; i++) {
10329 const char *fguid = spa_feature_table[i].fi_guid;
10330 if (nvlist_exists(enabled, fguid) && !features[i])
10331 break;
10333 if (i < SPA_FEATURES)
10334 (void) fprintf(stderr, gettext("Warning: one or "
10335 "more features already enabled on pool '%s'\n"
10336 "are not present in this compatibility set.\n"),
10337 zpool_get_name(zhp));
10340 /* if we're setting a feature, check it's in compatibility set */
10341 if (zpool_prop_feature(cb->cb_propname) &&
10342 strcmp(cb->cb_value, ZFS_FEATURE_ENABLED) == 0) {
10343 char *fname = strchr(cb->cb_propname, '@') + 1;
10344 spa_feature_t f;
10346 if (zfeature_lookup_name(fname, &f) == 0) {
10347 char compat[ZFS_MAXPROPLEN];
10348 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY,
10349 compat, ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
10350 compat[0] = '\0';
10352 boolean_t features[SPA_FEATURES];
10353 if (zpool_do_load_compat(compat, features) !=
10354 ZPOOL_COMPATIBILITY_OK) {
10355 (void) fprintf(stderr, gettext("Error: "
10356 "cannot enable feature '%s' on pool '%s'\n"
10357 "because the pool's 'compatibility' "
10358 "property cannot be parsed.\n"),
10359 fname, zpool_get_name(zhp));
10360 return (-1);
10363 if (!features[f]) {
10364 (void) fprintf(stderr, gettext("Error: "
10365 "cannot enable feature '%s' on pool '%s'\n"
10366 "as it is not specified in this pool's "
10367 "current compatibility set.\n"
10368 "Consider setting 'compatibility' to a "
10369 "less restrictive set, or to 'off'.\n"),
10370 fname, zpool_get_name(zhp));
10371 return (-1);
10376 error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
10378 return (error);
10381 static int
10382 set_callback(zpool_handle_t *zhp, void *data)
10384 int error;
10385 set_cbdata_t *cb = (set_cbdata_t *)data;
10387 if (cb->cb_type == ZFS_TYPE_VDEV) {
10388 error = zpool_set_vdev_prop(zhp, *cb->cb_vdevs.cb_names,
10389 cb->cb_propname, cb->cb_value);
10390 } else {
10391 assert(cb->cb_type == ZFS_TYPE_POOL);
10392 error = set_pool_callback(zhp, cb);
10395 cb->cb_any_successful = !error;
10396 return (error);
10400 zpool_do_set(int argc, char **argv)
10402 set_cbdata_t cb = { 0 };
10403 int error;
10404 char *vdev = NULL;
10406 current_prop_type = ZFS_TYPE_POOL;
10407 if (argc > 1 && argv[1][0] == '-') {
10408 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
10409 argv[1][1]);
10410 usage(B_FALSE);
10413 if (argc < 2) {
10414 (void) fprintf(stderr, gettext("missing property=value "
10415 "argument\n"));
10416 usage(B_FALSE);
10419 if (argc < 3) {
10420 (void) fprintf(stderr, gettext("missing pool name\n"));
10421 usage(B_FALSE);
10424 if (argc > 4) {
10425 (void) fprintf(stderr, gettext("too many pool names\n"));
10426 usage(B_FALSE);
10429 cb.cb_propname = argv[1];
10430 cb.cb_type = ZFS_TYPE_POOL;
10431 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
10432 cb.cb_value = strchr(cb.cb_propname, '=');
10433 if (cb.cb_value == NULL) {
10434 (void) fprintf(stderr, gettext("missing value in "
10435 "property=value argument\n"));
10436 usage(B_FALSE);
10439 *(cb.cb_value) = '\0';
10440 cb.cb_value++;
10441 argc -= 2;
10442 argv += 2;
10444 /* argv[0] is pool name */
10445 if (!is_pool(argv[0])) {
10446 (void) fprintf(stderr,
10447 gettext("cannot open '%s': is not a pool\n"), argv[0]);
10448 return (EINVAL);
10451 /* argv[1], when supplied, is vdev name */
10452 if (argc == 2) {
10454 if (strcmp(argv[1], "root") == 0)
10455 vdev = strdup("root-0");
10456 else
10457 vdev = strdup(argv[1]);
10459 if (!are_vdevs_in_pool(1, &vdev, argv[0], &cb.cb_vdevs)) {
10460 (void) fprintf(stderr, gettext(
10461 "cannot find '%s' in '%s': device not in pool\n"),
10462 vdev, argv[0]);
10463 free(vdev);
10464 return (EINVAL);
10466 cb.cb_vdevs.cb_names = &vdev;
10467 cb.cb_vdevs.cb_names_count = 1;
10468 cb.cb_type = ZFS_TYPE_VDEV;
10471 error = for_each_pool(1, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
10472 B_FALSE, set_callback, &cb);
10474 if (vdev != NULL)
10475 free(vdev);
10477 return (error);
10480 /* Add up the total number of bytes left to initialize/trim across all vdevs */
10481 static uint64_t
10482 vdev_activity_remaining(nvlist_t *nv, zpool_wait_activity_t activity)
10484 uint64_t bytes_remaining;
10485 nvlist_t **child;
10486 uint_t c, children;
10487 vdev_stat_t *vs;
10489 assert(activity == ZPOOL_WAIT_INITIALIZE ||
10490 activity == ZPOOL_WAIT_TRIM);
10492 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
10493 (uint64_t **)&vs, &c) == 0);
10495 if (activity == ZPOOL_WAIT_INITIALIZE &&
10496 vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE)
10497 bytes_remaining = vs->vs_initialize_bytes_est -
10498 vs->vs_initialize_bytes_done;
10499 else if (activity == ZPOOL_WAIT_TRIM &&
10500 vs->vs_trim_state == VDEV_TRIM_ACTIVE)
10501 bytes_remaining = vs->vs_trim_bytes_est -
10502 vs->vs_trim_bytes_done;
10503 else
10504 bytes_remaining = 0;
10506 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10507 &child, &children) != 0)
10508 children = 0;
10510 for (c = 0; c < children; c++)
10511 bytes_remaining += vdev_activity_remaining(child[c], activity);
10513 return (bytes_remaining);
10516 /* Add up the total number of bytes left to rebuild across top-level vdevs */
10517 static uint64_t
10518 vdev_activity_top_remaining(nvlist_t *nv)
10520 uint64_t bytes_remaining = 0;
10521 nvlist_t **child;
10522 uint_t children;
10523 int error;
10525 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10526 &child, &children) != 0)
10527 children = 0;
10529 for (uint_t c = 0; c < children; c++) {
10530 vdev_rebuild_stat_t *vrs;
10531 uint_t i;
10533 error = nvlist_lookup_uint64_array(child[c],
10534 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i);
10535 if (error == 0) {
10536 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
10537 bytes_remaining += (vrs->vrs_bytes_est -
10538 vrs->vrs_bytes_rebuilt);
10543 return (bytes_remaining);
10546 /* Whether any vdevs are 'spare' or 'replacing' vdevs */
10547 static boolean_t
10548 vdev_any_spare_replacing(nvlist_t *nv)
10550 nvlist_t **child;
10551 uint_t c, children;
10552 const char *vdev_type;
10554 (void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &vdev_type);
10556 if (strcmp(vdev_type, VDEV_TYPE_REPLACING) == 0 ||
10557 strcmp(vdev_type, VDEV_TYPE_SPARE) == 0 ||
10558 strcmp(vdev_type, VDEV_TYPE_DRAID_SPARE) == 0) {
10559 return (B_TRUE);
10562 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10563 &child, &children) != 0)
10564 children = 0;
10566 for (c = 0; c < children; c++) {
10567 if (vdev_any_spare_replacing(child[c]))
10568 return (B_TRUE);
10571 return (B_FALSE);
10574 typedef struct wait_data {
10575 char *wd_poolname;
10576 boolean_t wd_scripted;
10577 boolean_t wd_exact;
10578 boolean_t wd_headers_once;
10579 boolean_t wd_should_exit;
10580 /* Which activities to wait for */
10581 boolean_t wd_enabled[ZPOOL_WAIT_NUM_ACTIVITIES];
10582 float wd_interval;
10583 pthread_cond_t wd_cv;
10584 pthread_mutex_t wd_mutex;
10585 } wait_data_t;
10588 * Print to stdout a single line, containing one column for each activity that
10589 * we are waiting for specifying how many bytes of work are left for that
10590 * activity.
10592 static void
10593 print_wait_status_row(wait_data_t *wd, zpool_handle_t *zhp, int row)
10595 nvlist_t *config, *nvroot;
10596 uint_t c;
10597 int i;
10598 pool_checkpoint_stat_t *pcs = NULL;
10599 pool_scan_stat_t *pss = NULL;
10600 pool_removal_stat_t *prs = NULL;
10601 const char *const headers[] = {"DISCARD", "FREE", "INITIALIZE",
10602 "REPLACE", "REMOVE", "RESILVER", "SCRUB", "TRIM"};
10603 int col_widths[ZPOOL_WAIT_NUM_ACTIVITIES];
10605 /* Calculate the width of each column */
10606 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10608 * Make sure we have enough space in the col for pretty-printed
10609 * numbers and for the column header, and then leave a couple
10610 * spaces between cols for readability.
10612 col_widths[i] = MAX(strlen(headers[i]), 6) + 2;
10615 /* Print header if appropriate */
10616 int term_height = terminal_height();
10617 boolean_t reprint_header = (!wd->wd_headers_once && term_height > 0 &&
10618 row % (term_height-1) == 0);
10619 if (!wd->wd_scripted && (row == 0 || reprint_header)) {
10620 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10621 if (wd->wd_enabled[i])
10622 (void) printf("%*s", col_widths[i], headers[i]);
10624 (void) fputc('\n', stdout);
10627 /* Bytes of work remaining in each activity */
10628 int64_t bytes_rem[ZPOOL_WAIT_NUM_ACTIVITIES] = {0};
10630 bytes_rem[ZPOOL_WAIT_FREE] =
10631 zpool_get_prop_int(zhp, ZPOOL_PROP_FREEING, NULL);
10633 config = zpool_get_config(zhp, NULL);
10634 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
10636 (void) nvlist_lookup_uint64_array(nvroot,
10637 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
10638 if (pcs != NULL && pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
10639 bytes_rem[ZPOOL_WAIT_CKPT_DISCARD] = pcs->pcs_space;
10641 (void) nvlist_lookup_uint64_array(nvroot,
10642 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
10643 if (prs != NULL && prs->prs_state == DSS_SCANNING)
10644 bytes_rem[ZPOOL_WAIT_REMOVE] = prs->prs_to_copy -
10645 prs->prs_copied;
10647 (void) nvlist_lookup_uint64_array(nvroot,
10648 ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&pss, &c);
10649 if (pss != NULL && pss->pss_state == DSS_SCANNING &&
10650 pss->pss_pass_scrub_pause == 0) {
10651 int64_t rem = pss->pss_to_examine - pss->pss_issued;
10652 if (pss->pss_func == POOL_SCAN_SCRUB)
10653 bytes_rem[ZPOOL_WAIT_SCRUB] = rem;
10654 else
10655 bytes_rem[ZPOOL_WAIT_RESILVER] = rem;
10656 } else if (check_rebuilding(nvroot, NULL)) {
10657 bytes_rem[ZPOOL_WAIT_RESILVER] =
10658 vdev_activity_top_remaining(nvroot);
10661 bytes_rem[ZPOOL_WAIT_INITIALIZE] =
10662 vdev_activity_remaining(nvroot, ZPOOL_WAIT_INITIALIZE);
10663 bytes_rem[ZPOOL_WAIT_TRIM] =
10664 vdev_activity_remaining(nvroot, ZPOOL_WAIT_TRIM);
10667 * A replace finishes after resilvering finishes, so the amount of work
10668 * left for a replace is the same as for resilvering.
10670 * It isn't quite correct to say that if we have any 'spare' or
10671 * 'replacing' vdevs and a resilver is happening, then a replace is in
10672 * progress, like we do here. When a hot spare is used, the faulted vdev
10673 * is not removed after the hot spare is resilvered, so parent 'spare'
10674 * vdev is not removed either. So we could have a 'spare' vdev, but be
10675 * resilvering for a different reason. However, we use it as a heuristic
10676 * because we don't have access to the DTLs, which could tell us whether
10677 * or not we have really finished resilvering a hot spare.
10679 if (vdev_any_spare_replacing(nvroot))
10680 bytes_rem[ZPOOL_WAIT_REPLACE] = bytes_rem[ZPOOL_WAIT_RESILVER];
10682 if (timestamp_fmt != NODATE)
10683 print_timestamp(timestamp_fmt);
10685 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10686 char buf[64];
10687 if (!wd->wd_enabled[i])
10688 continue;
10690 if (wd->wd_exact)
10691 (void) snprintf(buf, sizeof (buf), "%" PRIi64,
10692 bytes_rem[i]);
10693 else
10694 zfs_nicenum(bytes_rem[i], buf, sizeof (buf));
10696 if (wd->wd_scripted)
10697 (void) printf(i == 0 ? "%s" : "\t%s", buf);
10698 else
10699 (void) printf(" %*s", col_widths[i] - 1, buf);
10701 (void) printf("\n");
10702 (void) fflush(stdout);
10705 static void *
10706 wait_status_thread(void *arg)
10708 wait_data_t *wd = (wait_data_t *)arg;
10709 zpool_handle_t *zhp;
10711 if ((zhp = zpool_open(g_zfs, wd->wd_poolname)) == NULL)
10712 return (void *)(1);
10714 for (int row = 0; ; row++) {
10715 boolean_t missing;
10716 struct timespec timeout;
10717 int ret = 0;
10718 (void) clock_gettime(CLOCK_REALTIME, &timeout);
10720 if (zpool_refresh_stats(zhp, &missing) != 0 || missing ||
10721 zpool_props_refresh(zhp) != 0) {
10722 zpool_close(zhp);
10723 return (void *)(uintptr_t)(missing ? 0 : 1);
10726 print_wait_status_row(wd, zhp, row);
10728 timeout.tv_sec += floor(wd->wd_interval);
10729 long nanos = timeout.tv_nsec +
10730 (wd->wd_interval - floor(wd->wd_interval)) * NANOSEC;
10731 if (nanos >= NANOSEC) {
10732 timeout.tv_sec++;
10733 timeout.tv_nsec = nanos - NANOSEC;
10734 } else {
10735 timeout.tv_nsec = nanos;
10737 pthread_mutex_lock(&wd->wd_mutex);
10738 if (!wd->wd_should_exit)
10739 ret = pthread_cond_timedwait(&wd->wd_cv, &wd->wd_mutex,
10740 &timeout);
10741 pthread_mutex_unlock(&wd->wd_mutex);
10742 if (ret == 0) {
10743 break; /* signaled by main thread */
10744 } else if (ret != ETIMEDOUT) {
10745 (void) fprintf(stderr, gettext("pthread_cond_timedwait "
10746 "failed: %s\n"), strerror(ret));
10747 zpool_close(zhp);
10748 return (void *)(uintptr_t)(1);
10752 zpool_close(zhp);
10753 return (void *)(0);
10757 zpool_do_wait(int argc, char **argv)
10759 boolean_t verbose = B_FALSE;
10760 int c, i;
10761 unsigned long count;
10762 pthread_t status_thr;
10763 int error = 0;
10764 zpool_handle_t *zhp;
10766 wait_data_t wd;
10767 wd.wd_scripted = B_FALSE;
10768 wd.wd_exact = B_FALSE;
10769 wd.wd_headers_once = B_FALSE;
10770 wd.wd_should_exit = B_FALSE;
10772 pthread_mutex_init(&wd.wd_mutex, NULL);
10773 pthread_cond_init(&wd.wd_cv, NULL);
10775 /* By default, wait for all types of activity. */
10776 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++)
10777 wd.wd_enabled[i] = B_TRUE;
10779 while ((c = getopt(argc, argv, "HpT:t:")) != -1) {
10780 switch (c) {
10781 case 'H':
10782 wd.wd_scripted = B_TRUE;
10783 break;
10784 case 'n':
10785 wd.wd_headers_once = B_TRUE;
10786 break;
10787 case 'p':
10788 wd.wd_exact = B_TRUE;
10789 break;
10790 case 'T':
10791 get_timestamp_arg(*optarg);
10792 break;
10793 case 't':
10794 /* Reset activities array */
10795 memset(&wd.wd_enabled, 0, sizeof (wd.wd_enabled));
10797 for (char *tok; (tok = strsep(&optarg, ",")); ) {
10798 static const char *const col_opts[] = {
10799 "discard", "free", "initialize", "replace",
10800 "remove", "resilver", "scrub", "trim" };
10802 for (i = 0; i < ARRAY_SIZE(col_opts); ++i)
10803 if (strcmp(tok, col_opts[i]) == 0) {
10804 wd.wd_enabled[i] = B_TRUE;
10805 goto found;
10808 (void) fprintf(stderr,
10809 gettext("invalid activity '%s'\n"), tok);
10810 usage(B_FALSE);
10811 found:;
10813 break;
10814 case '?':
10815 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
10816 optopt);
10817 usage(B_FALSE);
10821 argc -= optind;
10822 argv += optind;
10824 get_interval_count(&argc, argv, &wd.wd_interval, &count);
10825 if (count != 0) {
10826 /* This subcmd only accepts an interval, not a count */
10827 (void) fprintf(stderr, gettext("too many arguments\n"));
10828 usage(B_FALSE);
10831 if (wd.wd_interval != 0)
10832 verbose = B_TRUE;
10834 if (argc < 1) {
10835 (void) fprintf(stderr, gettext("missing 'pool' argument\n"));
10836 usage(B_FALSE);
10838 if (argc > 1) {
10839 (void) fprintf(stderr, gettext("too many arguments\n"));
10840 usage(B_FALSE);
10843 wd.wd_poolname = argv[0];
10845 if ((zhp = zpool_open(g_zfs, wd.wd_poolname)) == NULL)
10846 return (1);
10848 if (verbose) {
10850 * We use a separate thread for printing status updates because
10851 * the main thread will call lzc_wait(), which blocks as long
10852 * as an activity is in progress, which can be a long time.
10854 if (pthread_create(&status_thr, NULL, wait_status_thread, &wd)
10855 != 0) {
10856 (void) fprintf(stderr, gettext("failed to create status"
10857 "thread: %s\n"), strerror(errno));
10858 zpool_close(zhp);
10859 return (1);
10864 * Loop over all activities that we are supposed to wait for until none
10865 * of them are in progress. Note that this means we can end up waiting
10866 * for more activities to complete than just those that were in progress
10867 * when we began waiting; if an activity we are interested in begins
10868 * while we are waiting for another activity, we will wait for both to
10869 * complete before exiting.
10871 for (;;) {
10872 boolean_t missing = B_FALSE;
10873 boolean_t any_waited = B_FALSE;
10875 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
10876 boolean_t waited;
10878 if (!wd.wd_enabled[i])
10879 continue;
10881 error = zpool_wait_status(zhp, i, &missing, &waited);
10882 if (error != 0 || missing)
10883 break;
10885 any_waited = (any_waited || waited);
10888 if (error != 0 || missing || !any_waited)
10889 break;
10892 zpool_close(zhp);
10894 if (verbose) {
10895 uintptr_t status;
10896 pthread_mutex_lock(&wd.wd_mutex);
10897 wd.wd_should_exit = B_TRUE;
10898 pthread_cond_signal(&wd.wd_cv);
10899 pthread_mutex_unlock(&wd.wd_mutex);
10900 (void) pthread_join(status_thr, (void *)&status);
10901 if (status != 0)
10902 error = status;
10905 pthread_mutex_destroy(&wd.wd_mutex);
10906 pthread_cond_destroy(&wd.wd_cv);
10907 return (error);
10910 static int
10911 find_command_idx(const char *command, int *idx)
10913 for (int i = 0; i < NCOMMAND; ++i) {
10914 if (command_table[i].name == NULL)
10915 continue;
10917 if (strcmp(command, command_table[i].name) == 0) {
10918 *idx = i;
10919 return (0);
10922 return (1);
10926 * Display version message
10928 static int
10929 zpool_do_version(int argc, char **argv)
10931 (void) argc, (void) argv;
10932 return (zfs_version_print() != 0);
10936 * Do zpool_load_compat() and print error message on failure
10938 static zpool_compat_status_t
10939 zpool_do_load_compat(const char *compat, boolean_t *list)
10941 char report[1024];
10943 zpool_compat_status_t ret;
10945 ret = zpool_load_compat(compat, list, report, 1024);
10946 switch (ret) {
10948 case ZPOOL_COMPATIBILITY_OK:
10949 break;
10951 case ZPOOL_COMPATIBILITY_NOFILES:
10952 case ZPOOL_COMPATIBILITY_BADFILE:
10953 case ZPOOL_COMPATIBILITY_BADTOKEN:
10954 (void) fprintf(stderr, "Error: %s\n", report);
10955 break;
10957 case ZPOOL_COMPATIBILITY_WARNTOKEN:
10958 (void) fprintf(stderr, "Warning: %s\n", report);
10959 ret = ZPOOL_COMPATIBILITY_OK;
10960 break;
10962 return (ret);
10966 main(int argc, char **argv)
10968 int ret = 0;
10969 int i = 0;
10970 char *cmdname;
10971 char **newargv;
10973 (void) setlocale(LC_ALL, "");
10974 (void) setlocale(LC_NUMERIC, "C");
10975 (void) textdomain(TEXT_DOMAIN);
10976 srand(time(NULL));
10978 opterr = 0;
10981 * Make sure the user has specified some command.
10983 if (argc < 2) {
10984 (void) fprintf(stderr, gettext("missing command\n"));
10985 usage(B_FALSE);
10988 cmdname = argv[1];
10991 * Special case '-?'
10993 if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
10994 usage(B_TRUE);
10997 * Special case '-V|--version'
10999 if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
11000 return (zpool_do_version(argc, argv));
11002 if ((g_zfs = libzfs_init()) == NULL) {
11003 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
11004 return (1);
11007 libzfs_print_on_error(g_zfs, B_TRUE);
11009 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
11012 * Many commands modify input strings for string parsing reasons.
11013 * We create a copy to protect the original argv.
11015 newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
11016 for (i = 0; i < argc; i++)
11017 newargv[i] = strdup(argv[i]);
11018 newargv[argc] = NULL;
11021 * Run the appropriate command.
11023 if (find_command_idx(cmdname, &i) == 0) {
11024 current_command = &command_table[i];
11025 ret = command_table[i].func(argc - 1, newargv + 1);
11026 } else if (strchr(cmdname, '=')) {
11027 verify(find_command_idx("set", &i) == 0);
11028 current_command = &command_table[i];
11029 ret = command_table[i].func(argc, newargv);
11030 } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
11032 * 'freeze' is a vile debugging abomination, so we treat
11033 * it as such.
11035 zfs_cmd_t zc = {"\0"};
11037 (void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
11038 ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
11039 if (ret != 0) {
11040 (void) fprintf(stderr,
11041 gettext("failed to freeze pool: %d\n"), errno);
11042 ret = 1;
11045 log_history = 0;
11046 } else {
11047 (void) fprintf(stderr, gettext("unrecognized "
11048 "command '%s'\n"), cmdname);
11049 usage(B_FALSE);
11050 ret = 1;
11053 for (i = 0; i < argc; i++)
11054 free(newargv[i]);
11055 free(newargv);
11057 if (ret == 0 && log_history)
11058 (void) zpool_log_history(g_zfs, history_str);
11060 libzfs_fini(g_zfs);
11063 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
11064 * for the purposes of running ::findleaks.
11066 if (getenv("ZFS_ABORT") != NULL) {
11067 (void) printf("dumping core by request\n");
11068 abort();
11071 return (ret);