Extend import_progress kstat with a notes field
[zfs.git] / cmd / zpool / zpool_main.c
blob20b1c85065b46e0bef57ed43ea0d40ae74b97062
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, 2024 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 int zpool_do_help(int argc, char **argv);
131 static zpool_compat_status_t zpool_do_load_compat(
132 const char *, boolean_t *);
134 enum zpool_options {
135 ZPOOL_OPTION_POWER = 1024,
136 ZPOOL_OPTION_ALLOW_INUSE,
137 ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH,
138 ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH
142 * These libumem hooks provide a reasonable set of defaults for the allocator's
143 * debugging facilities.
146 #ifdef DEBUG
147 const char *
148 _umem_debug_init(void)
150 return ("default,verbose"); /* $UMEM_DEBUG setting */
153 const char *
154 _umem_logging_init(void)
156 return ("fail,contents"); /* $UMEM_LOGGING setting */
158 #endif
160 typedef enum {
161 HELP_ADD,
162 HELP_ATTACH,
163 HELP_CLEAR,
164 HELP_CREATE,
165 HELP_CHECKPOINT,
166 HELP_DESTROY,
167 HELP_DETACH,
168 HELP_EXPORT,
169 HELP_HISTORY,
170 HELP_IMPORT,
171 HELP_IOSTAT,
172 HELP_LABELCLEAR,
173 HELP_LIST,
174 HELP_OFFLINE,
175 HELP_ONLINE,
176 HELP_REPLACE,
177 HELP_REMOVE,
178 HELP_INITIALIZE,
179 HELP_SCRUB,
180 HELP_RESILVER,
181 HELP_TRIM,
182 HELP_STATUS,
183 HELP_UPGRADE,
184 HELP_EVENTS,
185 HELP_GET,
186 HELP_SET,
187 HELP_SPLIT,
188 HELP_SYNC,
189 HELP_REGUID,
190 HELP_REOPEN,
191 HELP_VERSION,
192 HELP_WAIT
193 } zpool_help_t;
197 * Flags for stats to display with "zpool iostats"
199 enum iostat_type {
200 IOS_DEFAULT = 0,
201 IOS_LATENCY = 1,
202 IOS_QUEUES = 2,
203 IOS_L_HISTO = 3,
204 IOS_RQ_HISTO = 4,
205 IOS_COUNT, /* always last element */
208 /* iostat_type entries as bitmasks */
209 #define IOS_DEFAULT_M (1ULL << IOS_DEFAULT)
210 #define IOS_LATENCY_M (1ULL << IOS_LATENCY)
211 #define IOS_QUEUES_M (1ULL << IOS_QUEUES)
212 #define IOS_L_HISTO_M (1ULL << IOS_L_HISTO)
213 #define IOS_RQ_HISTO_M (1ULL << IOS_RQ_HISTO)
215 /* Mask of all the histo bits */
216 #define IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
219 * Lookup table for iostat flags to nvlist names. Basically a list
220 * of all the nvlists a flag requires. Also specifies the order in
221 * which data gets printed in zpool iostat.
223 static const char *vsx_type_to_nvlist[IOS_COUNT][15] = {
224 [IOS_L_HISTO] = {
225 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
226 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
227 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
228 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
229 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
230 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
231 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
232 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
233 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
234 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
235 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
236 NULL},
237 [IOS_LATENCY] = {
238 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
239 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
240 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
241 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
242 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
243 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
244 NULL},
245 [IOS_QUEUES] = {
246 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
247 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
248 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
249 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
250 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
251 ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
252 ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
253 NULL},
254 [IOS_RQ_HISTO] = {
255 ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
256 ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
257 ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
258 ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
259 ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
260 ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
261 ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
262 ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
263 ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
264 ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
265 ZPOOL_CONFIG_VDEV_IND_TRIM_HISTO,
266 ZPOOL_CONFIG_VDEV_AGG_TRIM_HISTO,
267 ZPOOL_CONFIG_VDEV_IND_REBUILD_HISTO,
268 ZPOOL_CONFIG_VDEV_AGG_REBUILD_HISTO,
269 NULL},
274 * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
275 * Right now, only one histo bit is ever set at one time, so we can
276 * just do a highbit64(a)
278 #define IOS_HISTO_IDX(a) (highbit64(a & IOS_ANYHISTO_M) - 1)
280 typedef struct zpool_command {
281 const char *name;
282 int (*func)(int, char **);
283 zpool_help_t usage;
284 } zpool_command_t;
287 * Master command table. Each ZFS command has a name, associated function, and
288 * usage message. The usage messages need to be internationalized, so we have
289 * to have a function to return the usage message based on a command index.
291 * These commands are organized according to how they are displayed in the usage
292 * message. An empty command (one with a NULL name) indicates an empty line in
293 * the generic usage message.
295 static zpool_command_t command_table[] = {
296 { "version", zpool_do_version, HELP_VERSION },
297 { NULL },
298 { "create", zpool_do_create, HELP_CREATE },
299 { "destroy", zpool_do_destroy, HELP_DESTROY },
300 { NULL },
301 { "add", zpool_do_add, HELP_ADD },
302 { "remove", zpool_do_remove, HELP_REMOVE },
303 { NULL },
304 { "labelclear", zpool_do_labelclear, HELP_LABELCLEAR },
305 { NULL },
306 { "checkpoint", zpool_do_checkpoint, HELP_CHECKPOINT },
307 { NULL },
308 { "list", zpool_do_list, HELP_LIST },
309 { "iostat", zpool_do_iostat, HELP_IOSTAT },
310 { "status", zpool_do_status, HELP_STATUS },
311 { NULL },
312 { "online", zpool_do_online, HELP_ONLINE },
313 { "offline", zpool_do_offline, HELP_OFFLINE },
314 { "clear", zpool_do_clear, HELP_CLEAR },
315 { "reopen", zpool_do_reopen, HELP_REOPEN },
316 { NULL },
317 { "attach", zpool_do_attach, HELP_ATTACH },
318 { "detach", zpool_do_detach, HELP_DETACH },
319 { "replace", zpool_do_replace, HELP_REPLACE },
320 { "split", zpool_do_split, HELP_SPLIT },
321 { NULL },
322 { "initialize", zpool_do_initialize, HELP_INITIALIZE },
323 { "resilver", zpool_do_resilver, HELP_RESILVER },
324 { "scrub", zpool_do_scrub, HELP_SCRUB },
325 { "trim", zpool_do_trim, HELP_TRIM },
326 { NULL },
327 { "import", zpool_do_import, HELP_IMPORT },
328 { "export", zpool_do_export, HELP_EXPORT },
329 { "upgrade", zpool_do_upgrade, HELP_UPGRADE },
330 { "reguid", zpool_do_reguid, HELP_REGUID },
331 { NULL },
332 { "history", zpool_do_history, HELP_HISTORY },
333 { "events", zpool_do_events, HELP_EVENTS },
334 { NULL },
335 { "get", zpool_do_get, HELP_GET },
336 { "set", zpool_do_set, HELP_SET },
337 { "sync", zpool_do_sync, HELP_SYNC },
338 { NULL },
339 { "wait", zpool_do_wait, HELP_WAIT },
342 #define NCOMMAND (ARRAY_SIZE(command_table))
344 #define VDEV_ALLOC_CLASS_LOGS "logs"
346 static zpool_command_t *current_command;
347 static zfs_type_t current_prop_type = (ZFS_TYPE_POOL | ZFS_TYPE_VDEV);
348 static char history_str[HIS_MAX_RECORD_LEN];
349 static boolean_t log_history = B_TRUE;
350 static uint_t timestamp_fmt = NODATE;
352 static const char *
353 get_usage(zpool_help_t idx)
355 switch (idx) {
356 case HELP_ADD:
357 return (gettext("\tadd [-afgLnP] [-o property=value] "
358 "<pool> <vdev> ...\n"));
359 case HELP_ATTACH:
360 return (gettext("\tattach [-fsw] [-o property=value] "
361 "<pool> <device> <new-device>\n"));
362 case HELP_CLEAR:
363 return (gettext("\tclear [[--power]|[-nF]] <pool> [device]\n"));
364 case HELP_CREATE:
365 return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
366 "\t [-O file-system-property=value] ... \n"
367 "\t [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
368 case HELP_CHECKPOINT:
369 return (gettext("\tcheckpoint [-d [-w]] <pool> ...\n"));
370 case HELP_DESTROY:
371 return (gettext("\tdestroy [-f] <pool>\n"));
372 case HELP_DETACH:
373 return (gettext("\tdetach <pool> <device>\n"));
374 case HELP_EXPORT:
375 return (gettext("\texport [-af] <pool> ...\n"));
376 case HELP_HISTORY:
377 return (gettext("\thistory [-il] [<pool>] ...\n"));
378 case HELP_IMPORT:
379 return (gettext("\timport [-d dir] [-D]\n"
380 "\timport [-o mntopts] [-o property=value] ... \n"
381 "\t [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
382 "[-R root] [-F [-n]] -a\n"
383 "\timport [-o mntopts] [-o property=value] ... \n"
384 "\t [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
385 "[-R root] [-F [-n]]\n"
386 "\t [--rewind-to-checkpoint] <pool | id> [newpool]\n"));
387 case HELP_IOSTAT:
388 return (gettext("\tiostat [[[-c [script1,script2,...]"
389 "[-lq]]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
390 "\t [[pool ...]|[pool vdev ...]|[vdev ...]]"
391 " [[-n] interval [count]]\n"));
392 case HELP_LABELCLEAR:
393 return (gettext("\tlabelclear [-f] <vdev>\n"));
394 case HELP_LIST:
395 return (gettext("\tlist [-gHLpPv] [-o property[,...]] "
396 "[-T d|u] [pool] ... \n"
397 "\t [interval [count]]\n"));
398 case HELP_OFFLINE:
399 return (gettext("\toffline [--power]|[[-f][-t]] <pool> "
400 "<device> ...\n"));
401 case HELP_ONLINE:
402 return (gettext("\tonline [--power][-e] <pool> <device> "
403 "...\n"));
404 case HELP_REPLACE:
405 return (gettext("\treplace [-fsw] [-o property=value] "
406 "<pool> <device> [new-device]\n"));
407 case HELP_REMOVE:
408 return (gettext("\tremove [-npsw] <pool> <device> ...\n"));
409 case HELP_REOPEN:
410 return (gettext("\treopen [-n] <pool>\n"));
411 case HELP_INITIALIZE:
412 return (gettext("\tinitialize [-c | -s | -u] [-w] <pool> "
413 "[<device> ...]\n"));
414 case HELP_SCRUB:
415 return (gettext("\tscrub [-s | -p] [-w] [-e] <pool> ...\n"));
416 case HELP_RESILVER:
417 return (gettext("\tresilver <pool> ...\n"));
418 case HELP_TRIM:
419 return (gettext("\ttrim [-dw] [-r <rate>] [-c | -s] <pool> "
420 "[<device> ...]\n"));
421 case HELP_STATUS:
422 return (gettext("\tstatus [--power] [-c [script1,script2,...]] "
423 "[-DegiLpPstvx] [-T d|u] [pool] ...\n"
424 "\t [interval [count]]\n"));
425 case HELP_UPGRADE:
426 return (gettext("\tupgrade\n"
427 "\tupgrade -v\n"
428 "\tupgrade [-V version] <-a | pool ...>\n"));
429 case HELP_EVENTS:
430 return (gettext("\tevents [-vHf [pool] | -c]\n"));
431 case HELP_GET:
432 return (gettext("\tget [-Hp] [-o \"all\" | field[,...]] "
433 "<\"all\" | property[,...]> <pool> ...\n"));
434 case HELP_SET:
435 return (gettext("\tset <property=value> <pool>\n"
436 "\tset <vdev_property=value> <pool> <vdev>\n"));
437 case HELP_SPLIT:
438 return (gettext("\tsplit [-gLnPl] [-R altroot] [-o mntopts]\n"
439 "\t [-o property=value] <pool> <newpool> "
440 "[<device> ...]\n"));
441 case HELP_REGUID:
442 return (gettext("\treguid <pool>\n"));
443 case HELP_SYNC:
444 return (gettext("\tsync [pool] ...\n"));
445 case HELP_VERSION:
446 return (gettext("\tversion\n"));
447 case HELP_WAIT:
448 return (gettext("\twait [-Hp] [-T d|u] [-t <activity>[,...]] "
449 "<pool> [interval]\n"));
450 default:
451 __builtin_unreachable();
455 static void
456 zpool_collect_leaves(zpool_handle_t *zhp, nvlist_t *nvroot, nvlist_t *res)
458 uint_t children = 0;
459 nvlist_t **child;
460 uint_t i;
462 (void) nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
463 &child, &children);
465 if (children == 0) {
466 char *path = zpool_vdev_name(g_zfs, zhp, nvroot,
467 VDEV_NAME_PATH);
469 if (strcmp(path, VDEV_TYPE_INDIRECT) != 0 &&
470 strcmp(path, VDEV_TYPE_HOLE) != 0)
471 fnvlist_add_boolean(res, path);
473 free(path);
474 return;
477 for (i = 0; i < children; i++) {
478 zpool_collect_leaves(zhp, child[i], res);
483 * Callback routine that will print out a pool property value.
485 static int
486 print_pool_prop_cb(int prop, void *cb)
488 FILE *fp = cb;
490 (void) fprintf(fp, "\t%-19s ", zpool_prop_to_name(prop));
492 if (zpool_prop_readonly(prop))
493 (void) fprintf(fp, " NO ");
494 else
495 (void) fprintf(fp, " YES ");
497 if (zpool_prop_values(prop) == NULL)
498 (void) fprintf(fp, "-\n");
499 else
500 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
502 return (ZPROP_CONT);
506 * Callback routine that will print out a vdev property value.
508 static int
509 print_vdev_prop_cb(int prop, void *cb)
511 FILE *fp = cb;
513 (void) fprintf(fp, "\t%-19s ", vdev_prop_to_name(prop));
515 if (vdev_prop_readonly(prop))
516 (void) fprintf(fp, " NO ");
517 else
518 (void) fprintf(fp, " YES ");
520 if (vdev_prop_values(prop) == NULL)
521 (void) fprintf(fp, "-\n");
522 else
523 (void) fprintf(fp, "%s\n", vdev_prop_values(prop));
525 return (ZPROP_CONT);
529 * Given a leaf vdev name like 'L5' return its VDEV_CONFIG_PATH like
530 * '/dev/disk/by-vdev/L5'.
532 static const char *
533 vdev_name_to_path(zpool_handle_t *zhp, char *vdev)
535 nvlist_t *vdev_nv = zpool_find_vdev(zhp, vdev, NULL, NULL, NULL);
536 if (vdev_nv == NULL) {
537 return (NULL);
539 return (fnvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH));
542 static int
543 zpool_power_on(zpool_handle_t *zhp, char *vdev)
545 return (zpool_power(zhp, vdev, B_TRUE));
548 static int
549 zpool_power_on_and_disk_wait(zpool_handle_t *zhp, char *vdev)
551 int rc;
553 rc = zpool_power_on(zhp, vdev);
554 if (rc != 0)
555 return (rc);
557 zpool_disk_wait(vdev_name_to_path(zhp, vdev));
559 return (0);
562 static int
563 zpool_power_on_pool_and_wait_for_devices(zpool_handle_t *zhp)
565 nvlist_t *nv;
566 const char *path = NULL;
567 int rc;
569 /* Power up all the devices first */
570 FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
571 path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
572 if (path != NULL) {
573 rc = zpool_power_on(zhp, (char *)path);
574 if (rc != 0) {
575 return (rc);
581 * Wait for their devices to show up. Since we powered them on
582 * at roughly the same time, they should all come online around
583 * the same time.
585 FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
586 path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
587 zpool_disk_wait(path);
590 return (0);
593 static int
594 zpool_power_off(zpool_handle_t *zhp, char *vdev)
596 return (zpool_power(zhp, vdev, B_FALSE));
600 * Display usage message. If we're inside a command, display only the usage for
601 * that command. Otherwise, iterate over the entire command table and display
602 * a complete usage message.
604 static __attribute__((noreturn)) void
605 usage(boolean_t requested)
607 FILE *fp = requested ? stdout : stderr;
609 if (current_command == NULL) {
610 int i;
612 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
613 (void) fprintf(fp,
614 gettext("where 'command' is one of the following:\n\n"));
616 for (i = 0; i < NCOMMAND; i++) {
617 if (command_table[i].name == NULL)
618 (void) fprintf(fp, "\n");
619 else
620 (void) fprintf(fp, "%s",
621 get_usage(command_table[i].usage));
624 (void) fprintf(fp,
625 gettext("\nFor further help on a command or topic, "
626 "run: %s\n"), "zpool help [<topic>]");
627 } else {
628 (void) fprintf(fp, gettext("usage:\n"));
629 (void) fprintf(fp, "%s", get_usage(current_command->usage));
632 if (current_command != NULL &&
633 current_prop_type != (ZFS_TYPE_POOL | ZFS_TYPE_VDEV) &&
634 ((strcmp(current_command->name, "set") == 0) ||
635 (strcmp(current_command->name, "get") == 0) ||
636 (strcmp(current_command->name, "list") == 0))) {
638 (void) fprintf(fp, "%s",
639 gettext("\nthe following properties are supported:\n"));
641 (void) fprintf(fp, "\n\t%-19s %s %s\n\n",
642 "PROPERTY", "EDIT", "VALUES");
644 /* Iterate over all properties */
645 if (current_prop_type == ZFS_TYPE_POOL) {
646 (void) zprop_iter(print_pool_prop_cb, fp, B_FALSE,
647 B_TRUE, current_prop_type);
649 (void) fprintf(fp, "\t%-19s ", "feature@...");
650 (void) fprintf(fp, "YES "
651 "disabled | enabled | active\n");
653 (void) fprintf(fp, gettext("\nThe feature@ properties "
654 "must be appended with a feature name.\n"
655 "See zpool-features(7).\n"));
656 } else if (current_prop_type == ZFS_TYPE_VDEV) {
657 (void) zprop_iter(print_vdev_prop_cb, fp, B_FALSE,
658 B_TRUE, current_prop_type);
663 * See comments at end of main().
665 if (getenv("ZFS_ABORT") != NULL) {
666 (void) printf("dumping core by request\n");
667 abort();
670 exit(requested ? 0 : 2);
674 * zpool initialize [-c | -s | -u] [-w] <pool> [<vdev> ...]
675 * Initialize all unused blocks in the specified vdevs, or all vdevs in the pool
676 * if none specified.
678 * -c Cancel. Ends active initializing.
679 * -s Suspend. Initializing can then be restarted with no flags.
680 * -u Uninitialize. Clears initialization state.
681 * -w Wait. Blocks until initializing has completed.
684 zpool_do_initialize(int argc, char **argv)
686 int c;
687 char *poolname;
688 zpool_handle_t *zhp;
689 nvlist_t *vdevs;
690 int err = 0;
691 boolean_t wait = B_FALSE;
693 struct option long_options[] = {
694 {"cancel", no_argument, NULL, 'c'},
695 {"suspend", no_argument, NULL, 's'},
696 {"uninit", no_argument, NULL, 'u'},
697 {"wait", no_argument, NULL, 'w'},
698 {0, 0, 0, 0}
701 pool_initialize_func_t cmd_type = POOL_INITIALIZE_START;
702 while ((c = getopt_long(argc, argv, "csuw", long_options,
703 NULL)) != -1) {
704 switch (c) {
705 case 'c':
706 if (cmd_type != POOL_INITIALIZE_START &&
707 cmd_type != POOL_INITIALIZE_CANCEL) {
708 (void) fprintf(stderr, gettext("-c cannot be "
709 "combined with other options\n"));
710 usage(B_FALSE);
712 cmd_type = POOL_INITIALIZE_CANCEL;
713 break;
714 case 's':
715 if (cmd_type != POOL_INITIALIZE_START &&
716 cmd_type != POOL_INITIALIZE_SUSPEND) {
717 (void) fprintf(stderr, gettext("-s cannot be "
718 "combined with other options\n"));
719 usage(B_FALSE);
721 cmd_type = POOL_INITIALIZE_SUSPEND;
722 break;
723 case 'u':
724 if (cmd_type != POOL_INITIALIZE_START &&
725 cmd_type != POOL_INITIALIZE_UNINIT) {
726 (void) fprintf(stderr, gettext("-u cannot be "
727 "combined with other options\n"));
728 usage(B_FALSE);
730 cmd_type = POOL_INITIALIZE_UNINIT;
731 break;
732 case 'w':
733 wait = B_TRUE;
734 break;
735 case '?':
736 if (optopt != 0) {
737 (void) fprintf(stderr,
738 gettext("invalid option '%c'\n"), optopt);
739 } else {
740 (void) fprintf(stderr,
741 gettext("invalid option '%s'\n"),
742 argv[optind - 1]);
744 usage(B_FALSE);
748 argc -= optind;
749 argv += optind;
751 if (argc < 1) {
752 (void) fprintf(stderr, gettext("missing pool name argument\n"));
753 usage(B_FALSE);
754 return (-1);
757 if (wait && (cmd_type != POOL_INITIALIZE_START)) {
758 (void) fprintf(stderr, gettext("-w cannot be used with -c, -s"
759 "or -u\n"));
760 usage(B_FALSE);
763 poolname = argv[0];
764 zhp = zpool_open(g_zfs, poolname);
765 if (zhp == NULL)
766 return (-1);
768 vdevs = fnvlist_alloc();
769 if (argc == 1) {
770 /* no individual leaf vdevs specified, so add them all */
771 nvlist_t *config = zpool_get_config(zhp, NULL);
772 nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
773 ZPOOL_CONFIG_VDEV_TREE);
774 zpool_collect_leaves(zhp, nvroot, vdevs);
775 } else {
776 for (int i = 1; i < argc; i++) {
777 fnvlist_add_boolean(vdevs, argv[i]);
781 if (wait)
782 err = zpool_initialize_wait(zhp, cmd_type, vdevs);
783 else
784 err = zpool_initialize(zhp, cmd_type, vdevs);
786 fnvlist_free(vdevs);
787 zpool_close(zhp);
789 return (err);
793 * print a pool vdev config for dry runs
795 static void
796 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
797 const char *match, int name_flags)
799 nvlist_t **child;
800 uint_t c, children;
801 char *vname;
802 boolean_t printed = B_FALSE;
804 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
805 &child, &children) != 0) {
806 if (name != NULL)
807 (void) printf("\t%*s%s\n", indent, "", name);
808 return;
811 for (c = 0; c < children; c++) {
812 uint64_t is_log = B_FALSE, is_hole = B_FALSE;
813 const char *class = "";
815 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
816 &is_hole);
818 if (is_hole == B_TRUE) {
819 continue;
822 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
823 &is_log);
824 if (is_log)
825 class = VDEV_ALLOC_BIAS_LOG;
826 (void) nvlist_lookup_string(child[c],
827 ZPOOL_CONFIG_ALLOCATION_BIAS, &class);
828 if (strcmp(match, class) != 0)
829 continue;
831 if (!printed && name != NULL) {
832 (void) printf("\t%*s%s\n", indent, "", name);
833 printed = B_TRUE;
835 vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
836 print_vdev_tree(zhp, vname, child[c], indent + 2, "",
837 name_flags);
838 free(vname);
843 * Print the list of l2cache devices for dry runs.
845 static void
846 print_cache_list(nvlist_t *nv, int indent)
848 nvlist_t **child;
849 uint_t c, children;
851 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
852 &child, &children) == 0 && children > 0) {
853 (void) printf("\t%*s%s\n", indent, "", "cache");
854 } else {
855 return;
857 for (c = 0; c < children; c++) {
858 char *vname;
860 vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
861 (void) printf("\t%*s%s\n", indent + 2, "", vname);
862 free(vname);
867 * Print the list of spares for dry runs.
869 static void
870 print_spare_list(nvlist_t *nv, int indent)
872 nvlist_t **child;
873 uint_t c, children;
875 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
876 &child, &children) == 0 && children > 0) {
877 (void) printf("\t%*s%s\n", indent, "", "spares");
878 } else {
879 return;
881 for (c = 0; c < children; c++) {
882 char *vname;
884 vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
885 (void) printf("\t%*s%s\n", indent + 2, "", vname);
886 free(vname);
890 static boolean_t
891 prop_list_contains_feature(nvlist_t *proplist)
893 nvpair_t *nvp;
894 for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
895 nvp = nvlist_next_nvpair(proplist, nvp)) {
896 if (zpool_prop_feature(nvpair_name(nvp)))
897 return (B_TRUE);
899 return (B_FALSE);
903 * Add a property pair (name, string-value) into a property nvlist.
905 static int
906 add_prop_list(const char *propname, const char *propval, nvlist_t **props,
907 boolean_t poolprop)
909 zpool_prop_t prop = ZPOOL_PROP_INVAL;
910 nvlist_t *proplist;
911 const char *normnm;
912 const char *strval;
914 if (*props == NULL &&
915 nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
916 (void) fprintf(stderr,
917 gettext("internal error: out of memory\n"));
918 return (1);
921 proplist = *props;
923 if (poolprop) {
924 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
925 const char *cname =
926 zpool_prop_to_name(ZPOOL_PROP_COMPATIBILITY);
928 if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
929 (!zpool_prop_feature(propname) &&
930 !zpool_prop_vdev(propname))) {
931 (void) fprintf(stderr, gettext("property '%s' is "
932 "not a valid pool or vdev property\n"), propname);
933 return (2);
937 * feature@ properties and version should not be specified
938 * at the same time.
940 if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
941 nvlist_exists(proplist, vname)) ||
942 (prop == ZPOOL_PROP_VERSION &&
943 prop_list_contains_feature(proplist))) {
944 (void) fprintf(stderr, gettext("'feature@' and "
945 "'version' properties cannot be specified "
946 "together\n"));
947 return (2);
951 * if version is specified, only "legacy" compatibility
952 * may be requested
954 if ((prop == ZPOOL_PROP_COMPATIBILITY &&
955 strcmp(propval, ZPOOL_COMPAT_LEGACY) != 0 &&
956 nvlist_exists(proplist, vname)) ||
957 (prop == ZPOOL_PROP_VERSION &&
958 nvlist_exists(proplist, cname) &&
959 strcmp(fnvlist_lookup_string(proplist, cname),
960 ZPOOL_COMPAT_LEGACY) != 0)) {
961 (void) fprintf(stderr, gettext("when 'version' is "
962 "specified, the 'compatibility' feature may only "
963 "be set to '" ZPOOL_COMPAT_LEGACY "'\n"));
964 return (2);
967 if (zpool_prop_feature(propname) || zpool_prop_vdev(propname))
968 normnm = propname;
969 else
970 normnm = zpool_prop_to_name(prop);
971 } else {
972 zfs_prop_t fsprop = zfs_name_to_prop(propname);
974 if (zfs_prop_valid_for_type(fsprop, ZFS_TYPE_FILESYSTEM,
975 B_FALSE)) {
976 normnm = zfs_prop_to_name(fsprop);
977 } else if (zfs_prop_user(propname) ||
978 zfs_prop_userquota(propname)) {
979 normnm = propname;
980 } else {
981 (void) fprintf(stderr, gettext("property '%s' is "
982 "not a valid filesystem property\n"), propname);
983 return (2);
987 if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
988 prop != ZPOOL_PROP_CACHEFILE) {
989 (void) fprintf(stderr, gettext("property '%s' "
990 "specified multiple times\n"), propname);
991 return (2);
994 if (nvlist_add_string(proplist, normnm, propval) != 0) {
995 (void) fprintf(stderr, gettext("internal "
996 "error: out of memory\n"));
997 return (1);
1000 return (0);
1004 * Set a default property pair (name, string-value) in a property nvlist
1006 static int
1007 add_prop_list_default(const char *propname, const char *propval,
1008 nvlist_t **props)
1010 const char *pval;
1012 if (nvlist_lookup_string(*props, propname, &pval) == 0)
1013 return (0);
1015 return (add_prop_list(propname, propval, props, B_TRUE));
1019 * zpool add [-afgLnP] [-o property=value] <pool> <vdev> ...
1021 * -a Disable the ashift validation checks
1022 * -f Force addition of devices, even if they appear in use
1023 * -g Display guid for individual vdev name.
1024 * -L Follow links when resolving vdev path name.
1025 * -n Do not add the devices, but display the resulting layout if
1026 * they were to be added.
1027 * -o Set property=value.
1028 * -P Display full path for vdev name.
1030 * Adds the given vdevs to 'pool'. As with create, the bulk of this work is
1031 * handled by make_root_vdev(), which constructs the nvlist needed to pass to
1032 * libzfs.
1035 zpool_do_add(int argc, char **argv)
1037 boolean_t check_replication = B_TRUE;
1038 boolean_t check_inuse = B_TRUE;
1039 boolean_t dryrun = B_FALSE;
1040 boolean_t check_ashift = B_TRUE;
1041 boolean_t force = B_FALSE;
1042 int name_flags = 0;
1043 int c;
1044 nvlist_t *nvroot;
1045 char *poolname;
1046 int ret;
1047 zpool_handle_t *zhp;
1048 nvlist_t *config;
1049 nvlist_t *props = NULL;
1050 char *propval;
1052 struct option long_options[] = {
1053 {"allow-in-use", no_argument, NULL, ZPOOL_OPTION_ALLOW_INUSE},
1054 {"allow-replication-mismatch", no_argument, NULL,
1055 ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH},
1056 {"allow-ashift-mismatch", no_argument, NULL,
1057 ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH},
1058 {0, 0, 0, 0}
1061 /* check options */
1062 while ((c = getopt_long(argc, argv, "fgLno:P", long_options, NULL))
1063 != -1) {
1064 switch (c) {
1065 case 'f':
1066 force = B_TRUE;
1067 break;
1068 case 'g':
1069 name_flags |= VDEV_NAME_GUID;
1070 break;
1071 case 'L':
1072 name_flags |= VDEV_NAME_FOLLOW_LINKS;
1073 break;
1074 case 'n':
1075 dryrun = B_TRUE;
1076 break;
1077 case 'o':
1078 if ((propval = strchr(optarg, '=')) == NULL) {
1079 (void) fprintf(stderr, gettext("missing "
1080 "'=' for -o option\n"));
1081 usage(B_FALSE);
1083 *propval = '\0';
1084 propval++;
1086 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
1087 (add_prop_list(optarg, propval, &props, B_TRUE)))
1088 usage(B_FALSE);
1089 break;
1090 case 'P':
1091 name_flags |= VDEV_NAME_PATH;
1092 break;
1093 case ZPOOL_OPTION_ALLOW_INUSE:
1094 check_inuse = B_FALSE;
1095 break;
1096 case ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH:
1097 check_replication = B_FALSE;
1098 break;
1099 case ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH:
1100 check_ashift = B_FALSE;
1101 break;
1102 case '?':
1103 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1104 optopt);
1105 usage(B_FALSE);
1109 argc -= optind;
1110 argv += optind;
1112 /* get pool name and check number of arguments */
1113 if (argc < 1) {
1114 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1115 usage(B_FALSE);
1117 if (argc < 2) {
1118 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1119 usage(B_FALSE);
1122 if (force) {
1123 if (!check_inuse || !check_replication || !check_ashift) {
1124 (void) fprintf(stderr, gettext("'-f' option is not "
1125 "allowed with '--allow-replication-mismatch', "
1126 "'--allow-ashift-mismatch', or "
1127 "'--allow-in-use'\n"));
1128 usage(B_FALSE);
1130 check_inuse = B_FALSE;
1131 check_replication = B_FALSE;
1132 check_ashift = B_FALSE;
1135 poolname = argv[0];
1137 argc--;
1138 argv++;
1140 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1141 return (1);
1143 if ((config = zpool_get_config(zhp, NULL)) == NULL) {
1144 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
1145 poolname);
1146 zpool_close(zhp);
1147 return (1);
1150 /* unless manually specified use "ashift" pool property (if set) */
1151 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
1152 int intval;
1153 zprop_source_t src;
1154 char strval[ZPOOL_MAXPROPLEN];
1156 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
1157 if (src != ZPROP_SRC_DEFAULT) {
1158 (void) sprintf(strval, "%" PRId32, intval);
1159 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
1160 &props, B_TRUE) == 0);
1164 /* pass off to make_root_vdev for processing */
1165 nvroot = make_root_vdev(zhp, props, !check_inuse,
1166 check_replication, B_FALSE, dryrun, argc, argv);
1167 if (nvroot == NULL) {
1168 zpool_close(zhp);
1169 return (1);
1172 if (dryrun) {
1173 nvlist_t *poolnvroot;
1174 nvlist_t **l2child, **sparechild;
1175 uint_t l2children, sparechildren, c;
1176 char *vname;
1177 boolean_t hadcache = B_FALSE, hadspare = B_FALSE;
1179 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1180 &poolnvroot) == 0);
1182 (void) printf(gettext("would update '%s' to the following "
1183 "configuration:\n\n"), zpool_get_name(zhp));
1185 /* print original main pool and new tree */
1186 print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
1187 name_flags | VDEV_NAME_TYPE_ID);
1188 print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
1190 /* print other classes: 'dedup', 'special', and 'log' */
1191 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1192 print_vdev_tree(zhp, "dedup", poolnvroot, 0,
1193 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1194 print_vdev_tree(zhp, NULL, nvroot, 0,
1195 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1196 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1197 print_vdev_tree(zhp, "dedup", nvroot, 0,
1198 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1201 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1202 print_vdev_tree(zhp, "special", poolnvroot, 0,
1203 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1204 print_vdev_tree(zhp, NULL, nvroot, 0,
1205 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1206 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1207 print_vdev_tree(zhp, "special", nvroot, 0,
1208 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1211 if (num_logs(poolnvroot) > 0) {
1212 print_vdev_tree(zhp, "logs", poolnvroot, 0,
1213 VDEV_ALLOC_BIAS_LOG, name_flags);
1214 print_vdev_tree(zhp, NULL, nvroot, 0,
1215 VDEV_ALLOC_BIAS_LOG, name_flags);
1216 } else if (num_logs(nvroot) > 0) {
1217 print_vdev_tree(zhp, "logs", nvroot, 0,
1218 VDEV_ALLOC_BIAS_LOG, name_flags);
1221 /* Do the same for the caches */
1222 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
1223 &l2child, &l2children) == 0 && l2children) {
1224 hadcache = B_TRUE;
1225 (void) printf(gettext("\tcache\n"));
1226 for (c = 0; c < l2children; c++) {
1227 vname = zpool_vdev_name(g_zfs, NULL,
1228 l2child[c], name_flags);
1229 (void) printf("\t %s\n", vname);
1230 free(vname);
1233 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1234 &l2child, &l2children) == 0 && l2children) {
1235 if (!hadcache)
1236 (void) printf(gettext("\tcache\n"));
1237 for (c = 0; c < l2children; c++) {
1238 vname = zpool_vdev_name(g_zfs, NULL,
1239 l2child[c], name_flags);
1240 (void) printf("\t %s\n", vname);
1241 free(vname);
1244 /* And finally the spares */
1245 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_SPARES,
1246 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1247 hadspare = B_TRUE;
1248 (void) printf(gettext("\tspares\n"));
1249 for (c = 0; c < sparechildren; c++) {
1250 vname = zpool_vdev_name(g_zfs, NULL,
1251 sparechild[c], name_flags);
1252 (void) printf("\t %s\n", vname);
1253 free(vname);
1256 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1257 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1258 if (!hadspare)
1259 (void) printf(gettext("\tspares\n"));
1260 for (c = 0; c < sparechildren; c++) {
1261 vname = zpool_vdev_name(g_zfs, NULL,
1262 sparechild[c], name_flags);
1263 (void) printf("\t %s\n", vname);
1264 free(vname);
1268 ret = 0;
1269 } else {
1270 ret = (zpool_add(zhp, nvroot, check_ashift) != 0);
1273 nvlist_free(props);
1274 nvlist_free(nvroot);
1275 zpool_close(zhp);
1277 return (ret);
1281 * zpool remove [-npsw] <pool> <vdev> ...
1283 * Removes the given vdev from the pool.
1286 zpool_do_remove(int argc, char **argv)
1288 char *poolname;
1289 int i, ret = 0;
1290 zpool_handle_t *zhp = NULL;
1291 boolean_t stop = B_FALSE;
1292 int c;
1293 boolean_t noop = B_FALSE;
1294 boolean_t parsable = B_FALSE;
1295 boolean_t wait = B_FALSE;
1297 /* check options */
1298 while ((c = getopt(argc, argv, "npsw")) != -1) {
1299 switch (c) {
1300 case 'n':
1301 noop = B_TRUE;
1302 break;
1303 case 'p':
1304 parsable = B_TRUE;
1305 break;
1306 case 's':
1307 stop = B_TRUE;
1308 break;
1309 case 'w':
1310 wait = B_TRUE;
1311 break;
1312 case '?':
1313 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1314 optopt);
1315 usage(B_FALSE);
1319 argc -= optind;
1320 argv += optind;
1322 /* get pool name and check number of arguments */
1323 if (argc < 1) {
1324 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1325 usage(B_FALSE);
1328 poolname = argv[0];
1330 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1331 return (1);
1333 if (stop && noop) {
1334 zpool_close(zhp);
1335 (void) fprintf(stderr, gettext("stop request ignored\n"));
1336 return (0);
1339 if (stop) {
1340 if (argc > 1) {
1341 (void) fprintf(stderr, gettext("too many arguments\n"));
1342 usage(B_FALSE);
1344 if (zpool_vdev_remove_cancel(zhp) != 0)
1345 ret = 1;
1346 if (wait) {
1347 (void) fprintf(stderr, gettext("invalid option "
1348 "combination: -w cannot be used with -s\n"));
1349 usage(B_FALSE);
1351 } else {
1352 if (argc < 2) {
1353 (void) fprintf(stderr, gettext("missing device\n"));
1354 usage(B_FALSE);
1357 for (i = 1; i < argc; i++) {
1358 if (noop) {
1359 uint64_t size;
1361 if (zpool_vdev_indirect_size(zhp, argv[i],
1362 &size) != 0) {
1363 ret = 1;
1364 break;
1366 if (parsable) {
1367 (void) printf("%s %llu\n",
1368 argv[i], (unsigned long long)size);
1369 } else {
1370 char valstr[32];
1371 zfs_nicenum(size, valstr,
1372 sizeof (valstr));
1373 (void) printf("Memory that will be "
1374 "used after removing %s: %s\n",
1375 argv[i], valstr);
1377 } else {
1378 if (zpool_vdev_remove(zhp, argv[i]) != 0)
1379 ret = 1;
1383 if (ret == 0 && wait)
1384 ret = zpool_wait(zhp, ZPOOL_WAIT_REMOVE);
1386 zpool_close(zhp);
1388 return (ret);
1392 * Return 1 if a vdev is active (being used in a pool)
1393 * Return 0 if a vdev is inactive (offlined or faulted, or not in active pool)
1395 * This is useful for checking if a disk in an active pool is offlined or
1396 * faulted.
1398 static int
1399 vdev_is_active(char *vdev_path)
1401 int fd;
1402 fd = open(vdev_path, O_EXCL);
1403 if (fd < 0) {
1404 return (1); /* cant open O_EXCL - disk is active */
1407 close(fd);
1408 return (0); /* disk is inactive in the pool */
1412 * zpool labelclear [-f] <vdev>
1414 * -f Force clearing the label for the vdevs which are members of
1415 * the exported or foreign pools.
1417 * Verifies that the vdev is not active and zeros out the label information
1418 * on the device.
1421 zpool_do_labelclear(int argc, char **argv)
1423 char vdev[MAXPATHLEN];
1424 char *name = NULL;
1425 int c, fd = -1, ret = 0;
1426 nvlist_t *config;
1427 pool_state_t state;
1428 boolean_t inuse = B_FALSE;
1429 boolean_t force = B_FALSE;
1431 /* check options */
1432 while ((c = getopt(argc, argv, "f")) != -1) {
1433 switch (c) {
1434 case 'f':
1435 force = B_TRUE;
1436 break;
1437 default:
1438 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1439 optopt);
1440 usage(B_FALSE);
1444 argc -= optind;
1445 argv += optind;
1447 /* get vdev name */
1448 if (argc < 1) {
1449 (void) fprintf(stderr, gettext("missing vdev name\n"));
1450 usage(B_FALSE);
1452 if (argc > 1) {
1453 (void) fprintf(stderr, gettext("too many arguments\n"));
1454 usage(B_FALSE);
1457 (void) strlcpy(vdev, argv[0], sizeof (vdev));
1460 * If we cannot open an absolute path, we quit.
1461 * Otherwise if the provided vdev name doesn't point to a file,
1462 * try prepending expected disk paths and partition numbers.
1464 if ((fd = open(vdev, O_RDWR)) < 0) {
1465 int error;
1466 if (vdev[0] == '/') {
1467 (void) fprintf(stderr, gettext("failed to open "
1468 "%s: %s\n"), vdev, strerror(errno));
1469 return (1);
1472 error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
1473 if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
1474 if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
1475 error = ENOENT;
1478 if (error || ((fd = open(vdev, O_RDWR)) < 0)) {
1479 if (errno == ENOENT) {
1480 (void) fprintf(stderr, gettext(
1481 "failed to find device %s, try "
1482 "specifying absolute path instead\n"),
1483 argv[0]);
1484 return (1);
1487 (void) fprintf(stderr, gettext("failed to open %s:"
1488 " %s\n"), vdev, strerror(errno));
1489 return (1);
1494 * Flush all dirty pages for the block device. This should not be
1495 * fatal when the device does not support BLKFLSBUF as would be the
1496 * case for a file vdev.
1498 if ((zfs_dev_flush(fd) != 0) && (errno != ENOTTY))
1499 (void) fprintf(stderr, gettext("failed to invalidate "
1500 "cache for %s: %s\n"), vdev, strerror(errno));
1502 if (zpool_read_label(fd, &config, NULL) != 0) {
1503 (void) fprintf(stderr,
1504 gettext("failed to read label from %s\n"), vdev);
1505 ret = 1;
1506 goto errout;
1508 nvlist_free(config);
1510 ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1511 if (ret != 0) {
1512 (void) fprintf(stderr,
1513 gettext("failed to check state for %s\n"), vdev);
1514 ret = 1;
1515 goto errout;
1518 if (!inuse)
1519 goto wipe_label;
1521 switch (state) {
1522 default:
1523 case POOL_STATE_ACTIVE:
1524 case POOL_STATE_SPARE:
1525 case POOL_STATE_L2CACHE:
1527 * We allow the user to call 'zpool offline -f'
1528 * on an offlined disk in an active pool. We can check if
1529 * the disk is online by calling vdev_is_active().
1531 if (force && !vdev_is_active(vdev))
1532 break;
1534 (void) fprintf(stderr, gettext(
1535 "%s is a member (%s) of pool \"%s\""),
1536 vdev, zpool_pool_state_to_name(state), name);
1538 if (force) {
1539 (void) fprintf(stderr, gettext(
1540 ". Offline the disk first to clear its label."));
1542 printf("\n");
1543 ret = 1;
1544 goto errout;
1546 case POOL_STATE_EXPORTED:
1547 if (force)
1548 break;
1549 (void) fprintf(stderr, gettext(
1550 "use '-f' to override the following error:\n"
1551 "%s is a member of exported pool \"%s\"\n"),
1552 vdev, name);
1553 ret = 1;
1554 goto errout;
1556 case POOL_STATE_POTENTIALLY_ACTIVE:
1557 if (force)
1558 break;
1559 (void) fprintf(stderr, gettext(
1560 "use '-f' to override the following error:\n"
1561 "%s is a member of potentially active pool \"%s\"\n"),
1562 vdev, name);
1563 ret = 1;
1564 goto errout;
1566 case POOL_STATE_DESTROYED:
1567 /* inuse should never be set for a destroyed pool */
1568 assert(0);
1569 break;
1572 wipe_label:
1573 ret = zpool_clear_label(fd);
1574 if (ret != 0) {
1575 (void) fprintf(stderr,
1576 gettext("failed to clear label for %s\n"), vdev);
1579 errout:
1580 free(name);
1581 (void) close(fd);
1583 return (ret);
1587 * zpool create [-fnd] [-o property=value] ...
1588 * [-O file-system-property=value] ...
1589 * [-R root] [-m mountpoint] <pool> <dev> ...
1591 * -f Force creation, even if devices appear in use
1592 * -n Do not create the pool, but display the resulting layout if it
1593 * were to be created.
1594 * -R Create a pool under an alternate root
1595 * -m Set default mountpoint for the root dataset. By default it's
1596 * '/<pool>'
1597 * -o Set property=value.
1598 * -o Set feature@feature=enabled|disabled.
1599 * -d Don't automatically enable all supported pool features
1600 * (individual features can be enabled with -o).
1601 * -O Set fsproperty=value in the pool's root file system
1603 * Creates the named pool according to the given vdev specification. The
1604 * bulk of the vdev processing is done in make_root_vdev() in zpool_vdev.c.
1605 * Once we get the nvlist back from make_root_vdev(), we either print out the
1606 * contents (if '-n' was specified), or pass it to libzfs to do the creation.
1609 zpool_do_create(int argc, char **argv)
1611 boolean_t force = B_FALSE;
1612 boolean_t dryrun = B_FALSE;
1613 boolean_t enable_pool_features = B_TRUE;
1615 int c;
1616 nvlist_t *nvroot = NULL;
1617 char *poolname;
1618 char *tname = NULL;
1619 int ret = 1;
1620 char *altroot = NULL;
1621 char *compat = NULL;
1622 char *mountpoint = NULL;
1623 nvlist_t *fsprops = NULL;
1624 nvlist_t *props = NULL;
1625 char *propval;
1627 /* check options */
1628 while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
1629 switch (c) {
1630 case 'f':
1631 force = B_TRUE;
1632 break;
1633 case 'n':
1634 dryrun = B_TRUE;
1635 break;
1636 case 'd':
1637 enable_pool_features = B_FALSE;
1638 break;
1639 case 'R':
1640 altroot = optarg;
1641 if (add_prop_list(zpool_prop_to_name(
1642 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
1643 goto errout;
1644 if (add_prop_list_default(zpool_prop_to_name(
1645 ZPOOL_PROP_CACHEFILE), "none", &props))
1646 goto errout;
1647 break;
1648 case 'm':
1649 /* Equivalent to -O mountpoint=optarg */
1650 mountpoint = optarg;
1651 break;
1652 case 'o':
1653 if ((propval = strchr(optarg, '=')) == NULL) {
1654 (void) fprintf(stderr, gettext("missing "
1655 "'=' for -o option\n"));
1656 goto errout;
1658 *propval = '\0';
1659 propval++;
1661 if (add_prop_list(optarg, propval, &props, B_TRUE))
1662 goto errout;
1665 * If the user is creating a pool that doesn't support
1666 * feature flags, don't enable any features.
1668 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
1669 char *end;
1670 u_longlong_t ver;
1672 ver = strtoull(propval, &end, 10);
1673 if (*end == '\0' &&
1674 ver < SPA_VERSION_FEATURES) {
1675 enable_pool_features = B_FALSE;
1678 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
1679 altroot = propval;
1680 if (zpool_name_to_prop(optarg) ==
1681 ZPOOL_PROP_COMPATIBILITY)
1682 compat = propval;
1683 break;
1684 case 'O':
1685 if ((propval = strchr(optarg, '=')) == NULL) {
1686 (void) fprintf(stderr, gettext("missing "
1687 "'=' for -O option\n"));
1688 goto errout;
1690 *propval = '\0';
1691 propval++;
1694 * Mountpoints are checked and then added later.
1695 * Uniquely among properties, they can be specified
1696 * more than once, to avoid conflict with -m.
1698 if (0 == strcmp(optarg,
1699 zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
1700 mountpoint = propval;
1701 } else if (add_prop_list(optarg, propval, &fsprops,
1702 B_FALSE)) {
1703 goto errout;
1705 break;
1706 case 't':
1708 * Sanity check temporary pool name.
1710 if (strchr(optarg, '/') != NULL) {
1711 (void) fprintf(stderr, gettext("cannot create "
1712 "'%s': invalid character '/' in temporary "
1713 "name\n"), optarg);
1714 (void) fprintf(stderr, gettext("use 'zfs "
1715 "create' to create a dataset\n"));
1716 goto errout;
1719 if (add_prop_list(zpool_prop_to_name(
1720 ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
1721 goto errout;
1722 if (add_prop_list_default(zpool_prop_to_name(
1723 ZPOOL_PROP_CACHEFILE), "none", &props))
1724 goto errout;
1725 tname = optarg;
1726 break;
1727 case ':':
1728 (void) fprintf(stderr, gettext("missing argument for "
1729 "'%c' option\n"), optopt);
1730 goto badusage;
1731 case '?':
1732 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1733 optopt);
1734 goto badusage;
1738 argc -= optind;
1739 argv += optind;
1741 /* get pool name and check number of arguments */
1742 if (argc < 1) {
1743 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1744 goto badusage;
1746 if (argc < 2) {
1747 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1748 goto badusage;
1751 poolname = argv[0];
1754 * As a special case, check for use of '/' in the name, and direct the
1755 * user to use 'zfs create' instead.
1757 if (strchr(poolname, '/') != NULL) {
1758 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
1759 "character '/' in pool name\n"), poolname);
1760 (void) fprintf(stderr, gettext("use 'zfs create' to "
1761 "create a dataset\n"));
1762 goto errout;
1765 /* pass off to make_root_vdev for bulk processing */
1766 nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
1767 argc - 1, argv + 1);
1768 if (nvroot == NULL)
1769 goto errout;
1771 /* make_root_vdev() allows 0 toplevel children if there are spares */
1772 if (!zfs_allocatable_devs(nvroot)) {
1773 (void) fprintf(stderr, gettext("invalid vdev "
1774 "specification: at least one toplevel vdev must be "
1775 "specified\n"));
1776 goto errout;
1779 if (altroot != NULL && altroot[0] != '/') {
1780 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
1781 "must be an absolute path\n"), altroot);
1782 goto errout;
1786 * Check the validity of the mountpoint and direct the user to use the
1787 * '-m' mountpoint option if it looks like its in use.
1789 if (mountpoint == NULL ||
1790 (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
1791 strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
1792 char buf[MAXPATHLEN];
1793 DIR *dirp;
1795 if (mountpoint && mountpoint[0] != '/') {
1796 (void) fprintf(stderr, gettext("invalid mountpoint "
1797 "'%s': must be an absolute path, 'legacy', or "
1798 "'none'\n"), mountpoint);
1799 goto errout;
1802 if (mountpoint == NULL) {
1803 if (altroot != NULL)
1804 (void) snprintf(buf, sizeof (buf), "%s/%s",
1805 altroot, poolname);
1806 else
1807 (void) snprintf(buf, sizeof (buf), "/%s",
1808 poolname);
1809 } else {
1810 if (altroot != NULL)
1811 (void) snprintf(buf, sizeof (buf), "%s%s",
1812 altroot, mountpoint);
1813 else
1814 (void) snprintf(buf, sizeof (buf), "%s",
1815 mountpoint);
1818 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
1819 (void) fprintf(stderr, gettext("mountpoint '%s' : "
1820 "%s\n"), buf, strerror(errno));
1821 (void) fprintf(stderr, gettext("use '-m' "
1822 "option to provide a different default\n"));
1823 goto errout;
1824 } else if (dirp) {
1825 int count = 0;
1827 while (count < 3 && readdir(dirp) != NULL)
1828 count++;
1829 (void) closedir(dirp);
1831 if (count > 2) {
1832 (void) fprintf(stderr, gettext("mountpoint "
1833 "'%s' exists and is not empty\n"), buf);
1834 (void) fprintf(stderr, gettext("use '-m' "
1835 "option to provide a "
1836 "different default\n"));
1837 goto errout;
1843 * Now that the mountpoint's validity has been checked, ensure that
1844 * the property is set appropriately prior to creating the pool.
1846 if (mountpoint != NULL) {
1847 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
1848 mountpoint, &fsprops, B_FALSE);
1849 if (ret != 0)
1850 goto errout;
1853 ret = 1;
1854 if (dryrun) {
1856 * For a dry run invocation, print out a basic message and run
1857 * through all the vdevs in the list and print out in an
1858 * appropriate hierarchy.
1860 (void) printf(gettext("would create '%s' with the "
1861 "following layout:\n\n"), poolname);
1863 print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
1864 print_vdev_tree(NULL, "dedup", nvroot, 0,
1865 VDEV_ALLOC_BIAS_DEDUP, 0);
1866 print_vdev_tree(NULL, "special", nvroot, 0,
1867 VDEV_ALLOC_BIAS_SPECIAL, 0);
1868 print_vdev_tree(NULL, "logs", nvroot, 0,
1869 VDEV_ALLOC_BIAS_LOG, 0);
1870 print_cache_list(nvroot, 0);
1871 print_spare_list(nvroot, 0);
1873 ret = 0;
1874 } else {
1876 * Load in feature set.
1877 * Note: if compatibility property not given, we'll have
1878 * NULL, which means 'all features'.
1880 boolean_t requested_features[SPA_FEATURES];
1881 if (zpool_do_load_compat(compat, requested_features) !=
1882 ZPOOL_COMPATIBILITY_OK)
1883 goto errout;
1886 * props contains list of features to enable.
1887 * For each feature:
1888 * - remove it if feature@name=disabled
1889 * - leave it there if feature@name=enabled
1890 * - add it if:
1891 * - enable_pool_features (ie: no '-d' or '-o version')
1892 * - it's supported by the kernel module
1893 * - it's in the requested feature set
1894 * - warn if it's enabled but not in compat
1896 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
1897 char propname[MAXPATHLEN];
1898 const char *propval;
1899 zfeature_info_t *feat = &spa_feature_table[i];
1901 (void) snprintf(propname, sizeof (propname),
1902 "feature@%s", feat->fi_uname);
1904 if (!nvlist_lookup_string(props, propname, &propval)) {
1905 if (strcmp(propval,
1906 ZFS_FEATURE_DISABLED) == 0) {
1907 (void) nvlist_remove_all(props,
1908 propname);
1909 } else if (strcmp(propval,
1910 ZFS_FEATURE_ENABLED) == 0 &&
1911 !requested_features[i]) {
1912 (void) fprintf(stderr, gettext(
1913 "Warning: feature \"%s\" enabled "
1914 "but is not in specified "
1915 "'compatibility' feature set.\n"),
1916 feat->fi_uname);
1918 } else if (
1919 enable_pool_features &&
1920 feat->fi_zfs_mod_supported &&
1921 requested_features[i]) {
1922 ret = add_prop_list(propname,
1923 ZFS_FEATURE_ENABLED, &props, B_TRUE);
1924 if (ret != 0)
1925 goto errout;
1929 ret = 1;
1930 if (zpool_create(g_zfs, poolname,
1931 nvroot, props, fsprops) == 0) {
1932 zfs_handle_t *pool = zfs_open(g_zfs,
1933 tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
1934 if (pool != NULL) {
1935 if (zfs_mount(pool, NULL, 0) == 0) {
1936 ret = zfs_share(pool, NULL);
1937 zfs_commit_shares(NULL);
1939 zfs_close(pool);
1941 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
1942 (void) fprintf(stderr, gettext("pool name may have "
1943 "been omitted\n"));
1947 errout:
1948 nvlist_free(nvroot);
1949 nvlist_free(fsprops);
1950 nvlist_free(props);
1951 return (ret);
1952 badusage:
1953 nvlist_free(fsprops);
1954 nvlist_free(props);
1955 usage(B_FALSE);
1956 return (2);
1960 * zpool destroy <pool>
1962 * -f Forcefully unmount any datasets
1964 * Destroy the given pool. Automatically unmounts any datasets in the pool.
1967 zpool_do_destroy(int argc, char **argv)
1969 boolean_t force = B_FALSE;
1970 int c;
1971 char *pool;
1972 zpool_handle_t *zhp;
1973 int ret;
1975 /* check options */
1976 while ((c = getopt(argc, argv, "f")) != -1) {
1977 switch (c) {
1978 case 'f':
1979 force = B_TRUE;
1980 break;
1981 case '?':
1982 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1983 optopt);
1984 usage(B_FALSE);
1988 argc -= optind;
1989 argv += optind;
1991 /* check arguments */
1992 if (argc < 1) {
1993 (void) fprintf(stderr, gettext("missing pool argument\n"));
1994 usage(B_FALSE);
1996 if (argc > 1) {
1997 (void) fprintf(stderr, gettext("too many arguments\n"));
1998 usage(B_FALSE);
2001 pool = argv[0];
2003 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
2005 * As a special case, check for use of '/' in the name, and
2006 * direct the user to use 'zfs destroy' instead.
2008 if (strchr(pool, '/') != NULL)
2009 (void) fprintf(stderr, gettext("use 'zfs destroy' to "
2010 "destroy a dataset\n"));
2011 return (1);
2014 if (zpool_disable_datasets(zhp, force) != 0) {
2015 (void) fprintf(stderr, gettext("could not destroy '%s': "
2016 "could not unmount datasets\n"), zpool_get_name(zhp));
2017 zpool_close(zhp);
2018 return (1);
2021 /* The history must be logged as part of the export */
2022 log_history = B_FALSE;
2024 ret = (zpool_destroy(zhp, history_str) != 0);
2026 zpool_close(zhp);
2028 return (ret);
2031 typedef struct export_cbdata {
2032 boolean_t force;
2033 boolean_t hardforce;
2034 } export_cbdata_t;
2037 * Export one pool
2039 static int
2040 zpool_export_one(zpool_handle_t *zhp, void *data)
2042 export_cbdata_t *cb = data;
2044 if (zpool_disable_datasets(zhp, cb->force) != 0)
2045 return (1);
2047 /* The history must be logged as part of the export */
2048 log_history = B_FALSE;
2050 if (cb->hardforce) {
2051 if (zpool_export_force(zhp, history_str) != 0)
2052 return (1);
2053 } else if (zpool_export(zhp, cb->force, history_str) != 0) {
2054 return (1);
2057 return (0);
2061 * zpool export [-f] <pool> ...
2063 * -a Export all pools
2064 * -f Forcefully unmount datasets
2066 * Export the given pools. By default, the command will attempt to cleanly
2067 * unmount any active datasets within the pool. If the '-f' flag is specified,
2068 * then the datasets will be forcefully unmounted.
2071 zpool_do_export(int argc, char **argv)
2073 export_cbdata_t cb;
2074 boolean_t do_all = B_FALSE;
2075 boolean_t force = B_FALSE;
2076 boolean_t hardforce = B_FALSE;
2077 int c, ret;
2079 /* check options */
2080 while ((c = getopt(argc, argv, "afF")) != -1) {
2081 switch (c) {
2082 case 'a':
2083 do_all = B_TRUE;
2084 break;
2085 case 'f':
2086 force = B_TRUE;
2087 break;
2088 case 'F':
2089 hardforce = B_TRUE;
2090 break;
2091 case '?':
2092 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2093 optopt);
2094 usage(B_FALSE);
2098 cb.force = force;
2099 cb.hardforce = hardforce;
2100 argc -= optind;
2101 argv += optind;
2103 if (do_all) {
2104 if (argc != 0) {
2105 (void) fprintf(stderr, gettext("too many arguments\n"));
2106 usage(B_FALSE);
2109 return (for_each_pool(argc, argv, B_TRUE, NULL,
2110 ZFS_TYPE_POOL, B_FALSE, zpool_export_one, &cb));
2113 /* check arguments */
2114 if (argc < 1) {
2115 (void) fprintf(stderr, gettext("missing pool argument\n"));
2116 usage(B_FALSE);
2119 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2120 B_FALSE, zpool_export_one, &cb);
2122 return (ret);
2126 * Given a vdev configuration, determine the maximum width needed for the device
2127 * name column.
2129 static int
2130 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
2131 int name_flags)
2133 static const char *const subtypes[] =
2134 {ZPOOL_CONFIG_SPARES, ZPOOL_CONFIG_L2CACHE, ZPOOL_CONFIG_CHILDREN};
2136 char *name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
2137 max = MAX(strlen(name) + depth, max);
2138 free(name);
2140 nvlist_t **child;
2141 uint_t children;
2142 for (size_t i = 0; i < ARRAY_SIZE(subtypes); ++i)
2143 if (nvlist_lookup_nvlist_array(nv, subtypes[i],
2144 &child, &children) == 0)
2145 for (uint_t c = 0; c < children; ++c)
2146 max = MAX(max_width(zhp, child[c], depth + 2,
2147 max, name_flags), max);
2149 return (max);
2152 typedef struct spare_cbdata {
2153 uint64_t cb_guid;
2154 zpool_handle_t *cb_zhp;
2155 } spare_cbdata_t;
2157 static boolean_t
2158 find_vdev(nvlist_t *nv, uint64_t search)
2160 uint64_t guid;
2161 nvlist_t **child;
2162 uint_t c, children;
2164 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
2165 search == guid)
2166 return (B_TRUE);
2168 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2169 &child, &children) == 0) {
2170 for (c = 0; c < children; c++)
2171 if (find_vdev(child[c], search))
2172 return (B_TRUE);
2175 return (B_FALSE);
2178 static int
2179 find_spare(zpool_handle_t *zhp, void *data)
2181 spare_cbdata_t *cbp = data;
2182 nvlist_t *config, *nvroot;
2184 config = zpool_get_config(zhp, NULL);
2185 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2186 &nvroot) == 0);
2188 if (find_vdev(nvroot, cbp->cb_guid)) {
2189 cbp->cb_zhp = zhp;
2190 return (1);
2193 zpool_close(zhp);
2194 return (0);
2197 typedef struct status_cbdata {
2198 int cb_count;
2199 int cb_name_flags;
2200 int cb_namewidth;
2201 boolean_t cb_allpools;
2202 boolean_t cb_verbose;
2203 boolean_t cb_literal;
2204 boolean_t cb_explain;
2205 boolean_t cb_first;
2206 boolean_t cb_dedup_stats;
2207 boolean_t cb_print_unhealthy;
2208 boolean_t cb_print_status;
2209 boolean_t cb_print_slow_ios;
2210 boolean_t cb_print_vdev_init;
2211 boolean_t cb_print_vdev_trim;
2212 vdev_cmd_data_list_t *vcdl;
2213 boolean_t cb_print_power;
2214 } status_cbdata_t;
2216 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
2217 static boolean_t
2218 is_blank_str(const char *str)
2220 for (; str != NULL && *str != '\0'; ++str)
2221 if (!isblank(*str))
2222 return (B_FALSE);
2223 return (B_TRUE);
2226 /* Print command output lines for specific vdev in a specific pool */
2227 static void
2228 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path)
2230 vdev_cmd_data_t *data;
2231 int i, j;
2232 const char *val;
2234 for (i = 0; i < vcdl->count; i++) {
2235 if ((strcmp(vcdl->data[i].path, path) != 0) ||
2236 (strcmp(vcdl->data[i].pool, pool) != 0)) {
2237 /* Not the vdev we're looking for */
2238 continue;
2241 data = &vcdl->data[i];
2242 /* Print out all the output values for this vdev */
2243 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2244 val = NULL;
2245 /* Does this vdev have values for this column? */
2246 for (int k = 0; k < data->cols_cnt; k++) {
2247 if (strcmp(data->cols[k],
2248 vcdl->uniq_cols[j]) == 0) {
2249 /* yes it does, record the value */
2250 val = data->lines[k];
2251 break;
2255 * Mark empty values with dashes to make output
2256 * awk-able.
2258 if (val == NULL || is_blank_str(val))
2259 val = "-";
2261 printf("%*s", vcdl->uniq_cols_width[j], val);
2262 if (j < vcdl->uniq_cols_cnt - 1)
2263 fputs(" ", stdout);
2266 /* Print out any values that aren't in a column at the end */
2267 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2268 /* Did we have any columns? If so print a spacer. */
2269 if (vcdl->uniq_cols_cnt > 0)
2270 fputs(" ", stdout);
2272 val = data->lines[j];
2273 fputs(val ?: "", stdout);
2275 break;
2280 * Print vdev initialization status for leaves
2282 static void
2283 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
2285 if (verbose) {
2286 if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
2287 vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
2288 vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
2289 !vs->vs_scan_removing) {
2290 char zbuf[1024];
2291 char tbuf[256];
2293 time_t t = vs->vs_initialize_action_time;
2294 int initialize_pct = 100;
2295 if (vs->vs_initialize_state !=
2296 VDEV_INITIALIZE_COMPLETE) {
2297 initialize_pct = (vs->vs_initialize_bytes_done *
2298 100 / (vs->vs_initialize_bytes_est + 1));
2301 (void) ctime_r(&t, tbuf);
2302 tbuf[24] = 0;
2304 switch (vs->vs_initialize_state) {
2305 case VDEV_INITIALIZE_SUSPENDED:
2306 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2307 gettext("suspended, started at"), tbuf);
2308 break;
2309 case VDEV_INITIALIZE_ACTIVE:
2310 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2311 gettext("started at"), tbuf);
2312 break;
2313 case VDEV_INITIALIZE_COMPLETE:
2314 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2315 gettext("completed at"), tbuf);
2316 break;
2319 (void) printf(gettext(" (%d%% initialized%s)"),
2320 initialize_pct, zbuf);
2321 } else {
2322 (void) printf(gettext(" (uninitialized)"));
2324 } else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
2325 (void) printf(gettext(" (initializing)"));
2330 * Print vdev TRIM status for leaves
2332 static void
2333 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
2335 if (verbose) {
2336 if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
2337 vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
2338 vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
2339 !vs->vs_scan_removing) {
2340 char zbuf[1024];
2341 char tbuf[256];
2343 time_t t = vs->vs_trim_action_time;
2344 int trim_pct = 100;
2345 if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
2346 trim_pct = (vs->vs_trim_bytes_done *
2347 100 / (vs->vs_trim_bytes_est + 1));
2350 (void) ctime_r(&t, tbuf);
2351 tbuf[24] = 0;
2353 switch (vs->vs_trim_state) {
2354 case VDEV_TRIM_SUSPENDED:
2355 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2356 gettext("suspended, started at"), tbuf);
2357 break;
2358 case VDEV_TRIM_ACTIVE:
2359 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2360 gettext("started at"), tbuf);
2361 break;
2362 case VDEV_TRIM_COMPLETE:
2363 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2364 gettext("completed at"), tbuf);
2365 break;
2368 (void) printf(gettext(" (%d%% trimmed%s)"),
2369 trim_pct, zbuf);
2370 } else if (vs->vs_trim_notsup) {
2371 (void) printf(gettext(" (trim unsupported)"));
2372 } else {
2373 (void) printf(gettext(" (untrimmed)"));
2375 } else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
2376 (void) printf(gettext(" (trimming)"));
2381 * Return the color associated with a health string. This includes returning
2382 * NULL for no color change.
2384 static const char *
2385 health_str_to_color(const char *health)
2387 if (strcmp(health, gettext("FAULTED")) == 0 ||
2388 strcmp(health, gettext("SUSPENDED")) == 0 ||
2389 strcmp(health, gettext("UNAVAIL")) == 0) {
2390 return (ANSI_RED);
2393 if (strcmp(health, gettext("OFFLINE")) == 0 ||
2394 strcmp(health, gettext("DEGRADED")) == 0 ||
2395 strcmp(health, gettext("REMOVED")) == 0) {
2396 return (ANSI_YELLOW);
2399 return (NULL);
2403 * Called for each leaf vdev. Returns 0 if the vdev is healthy.
2404 * A vdev is unhealthy if any of the following are true:
2405 * 1) there are read, write, or checksum errors,
2406 * 2) its state is not ONLINE, or
2407 * 3) slow IO reporting was requested (-s) and there are slow IOs.
2409 static int
2410 vdev_health_check_cb(void *hdl_data, nvlist_t *nv, void *data)
2412 status_cbdata_t *cb = data;
2413 vdev_stat_t *vs;
2414 uint_t vsc;
2415 (void) hdl_data;
2417 if (nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2418 (uint64_t **)&vs, &vsc) != 0)
2419 return (1);
2421 if (vs->vs_checksum_errors || vs->vs_read_errors ||
2422 vs->vs_write_errors || vs->vs_state != VDEV_STATE_HEALTHY)
2423 return (1);
2425 if (cb->cb_print_slow_ios && vs->vs_slow_ios)
2426 return (1);
2428 return (0);
2432 * Print out configuration state as requested by status_callback.
2434 static void
2435 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
2436 nvlist_t *nv, int depth, boolean_t isspare, vdev_rebuild_stat_t *vrs)
2438 nvlist_t **child, *root;
2439 uint_t c, i, vsc, children;
2440 pool_scan_stat_t *ps = NULL;
2441 vdev_stat_t *vs;
2442 char rbuf[6], wbuf[6], cbuf[6];
2443 char *vname;
2444 uint64_t notpresent;
2445 spare_cbdata_t spare_cb;
2446 const char *state;
2447 const char *type;
2448 const char *path = NULL;
2449 const char *rcolor = NULL, *wcolor = NULL, *ccolor = NULL,
2450 *scolor = NULL;
2452 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2453 &child, &children) != 0)
2454 children = 0;
2456 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2457 (uint64_t **)&vs, &vsc) == 0);
2459 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2461 if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2462 return;
2464 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2466 if (isspare) {
2468 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
2469 * online drives.
2471 if (vs->vs_aux == VDEV_AUX_SPARED)
2472 state = gettext("INUSE");
2473 else if (vs->vs_state == VDEV_STATE_HEALTHY)
2474 state = gettext("AVAIL");
2478 * If '-e' is specified then top-level vdevs and their children
2479 * can be pruned if all of their leaves are healthy.
2481 if (cb->cb_print_unhealthy && depth > 0 &&
2482 for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
2483 return;
2486 printf_color(health_str_to_color(state),
2487 "\t%*s%-*s %-8s", depth, "", cb->cb_namewidth - depth,
2488 name, state);
2490 if (!isspare) {
2491 if (vs->vs_read_errors)
2492 rcolor = ANSI_RED;
2494 if (vs->vs_write_errors)
2495 wcolor = ANSI_RED;
2497 if (vs->vs_checksum_errors)
2498 ccolor = ANSI_RED;
2500 if (vs->vs_slow_ios)
2501 scolor = ANSI_BLUE;
2503 if (cb->cb_literal) {
2504 fputc(' ', stdout);
2505 printf_color(rcolor, "%5llu",
2506 (u_longlong_t)vs->vs_read_errors);
2507 fputc(' ', stdout);
2508 printf_color(wcolor, "%5llu",
2509 (u_longlong_t)vs->vs_write_errors);
2510 fputc(' ', stdout);
2511 printf_color(ccolor, "%5llu",
2512 (u_longlong_t)vs->vs_checksum_errors);
2513 } else {
2514 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
2515 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
2516 zfs_nicenum(vs->vs_checksum_errors, cbuf,
2517 sizeof (cbuf));
2518 fputc(' ', stdout);
2519 printf_color(rcolor, "%5s", rbuf);
2520 fputc(' ', stdout);
2521 printf_color(wcolor, "%5s", wbuf);
2522 fputc(' ', stdout);
2523 printf_color(ccolor, "%5s", cbuf);
2525 if (cb->cb_print_slow_ios) {
2526 if (children == 0) {
2527 /* Only leafs vdevs have slow IOs */
2528 zfs_nicenum(vs->vs_slow_ios, rbuf,
2529 sizeof (rbuf));
2530 } else {
2531 snprintf(rbuf, sizeof (rbuf), "-");
2534 if (cb->cb_literal)
2535 printf_color(scolor, " %5llu",
2536 (u_longlong_t)vs->vs_slow_ios);
2537 else
2538 printf_color(scolor, " %5s", rbuf);
2540 if (cb->cb_print_power) {
2541 if (children == 0) {
2542 /* Only leaf vdevs have physical slots */
2543 switch (zpool_power_current_state(zhp, (char *)
2544 fnvlist_lookup_string(nv,
2545 ZPOOL_CONFIG_PATH))) {
2546 case 0:
2547 printf_color(ANSI_RED, " %5s",
2548 gettext("off"));
2549 break;
2550 case 1:
2551 printf(" %5s", gettext("on"));
2552 break;
2553 default:
2554 printf(" %5s", "-");
2556 } else {
2557 printf(" %5s", "-");
2562 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
2563 &notpresent) == 0) {
2564 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
2565 (void) printf(" %s %s", gettext("was"), path);
2566 } else if (vs->vs_aux != 0) {
2567 (void) printf(" ");
2568 color_start(ANSI_RED);
2569 switch (vs->vs_aux) {
2570 case VDEV_AUX_OPEN_FAILED:
2571 (void) printf(gettext("cannot open"));
2572 break;
2574 case VDEV_AUX_BAD_GUID_SUM:
2575 (void) printf(gettext("missing device"));
2576 break;
2578 case VDEV_AUX_NO_REPLICAS:
2579 (void) printf(gettext("insufficient replicas"));
2580 break;
2582 case VDEV_AUX_VERSION_NEWER:
2583 (void) printf(gettext("newer version"));
2584 break;
2586 case VDEV_AUX_UNSUP_FEAT:
2587 (void) printf(gettext("unsupported feature(s)"));
2588 break;
2590 case VDEV_AUX_ASHIFT_TOO_BIG:
2591 (void) printf(gettext("unsupported minimum blocksize"));
2592 break;
2594 case VDEV_AUX_SPARED:
2595 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
2596 &spare_cb.cb_guid) == 0);
2597 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
2598 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
2599 zpool_get_name(zhp)) == 0)
2600 (void) printf(gettext("currently in "
2601 "use"));
2602 else
2603 (void) printf(gettext("in use by "
2604 "pool '%s'"),
2605 zpool_get_name(spare_cb.cb_zhp));
2606 zpool_close(spare_cb.cb_zhp);
2607 } else {
2608 (void) printf(gettext("currently in use"));
2610 break;
2612 case VDEV_AUX_ERR_EXCEEDED:
2613 if (vs->vs_read_errors + vs->vs_write_errors +
2614 vs->vs_checksum_errors == 0 && children == 0 &&
2615 vs->vs_slow_ios > 0) {
2616 (void) printf(gettext("too many slow I/Os"));
2617 } else {
2618 (void) printf(gettext("too many errors"));
2620 break;
2622 case VDEV_AUX_IO_FAILURE:
2623 (void) printf(gettext("experienced I/O failures"));
2624 break;
2626 case VDEV_AUX_BAD_LOG:
2627 (void) printf(gettext("bad intent log"));
2628 break;
2630 case VDEV_AUX_EXTERNAL:
2631 (void) printf(gettext("external device fault"));
2632 break;
2634 case VDEV_AUX_SPLIT_POOL:
2635 (void) printf(gettext("split into new pool"));
2636 break;
2638 case VDEV_AUX_ACTIVE:
2639 (void) printf(gettext("currently in use"));
2640 break;
2642 case VDEV_AUX_CHILDREN_OFFLINE:
2643 (void) printf(gettext("all children offline"));
2644 break;
2646 case VDEV_AUX_BAD_LABEL:
2647 (void) printf(gettext("invalid label"));
2648 break;
2650 default:
2651 (void) printf(gettext("corrupted data"));
2652 break;
2654 color_end();
2655 } else if (children == 0 && !isspare &&
2656 getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
2657 VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
2658 vs->vs_configured_ashift < vs->vs_physical_ashift) {
2659 (void) printf(
2660 gettext(" block size: %dB configured, %dB native"),
2661 1 << vs->vs_configured_ashift, 1 << vs->vs_physical_ashift);
2664 if (vs->vs_scan_removing != 0) {
2665 (void) printf(gettext(" (removing)"));
2666 } else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
2667 (void) printf(gettext(" (non-allocating)"));
2670 /* The root vdev has the scrub/resilver stats */
2671 root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
2672 ZPOOL_CONFIG_VDEV_TREE);
2673 (void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
2674 (uint64_t **)&ps, &c);
2677 * If you force fault a drive that's resilvering, its scan stats can
2678 * get frozen in time, giving the false impression that it's
2679 * being resilvered. That's why we check the state to see if the vdev
2680 * is healthy before reporting "resilvering" or "repairing".
2682 if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0 &&
2683 vs->vs_state == VDEV_STATE_HEALTHY) {
2684 if (vs->vs_scan_processed != 0) {
2685 (void) printf(gettext(" (%s)"),
2686 (ps->pss_func == POOL_SCAN_RESILVER) ?
2687 "resilvering" : "repairing");
2688 } else if (vs->vs_resilver_deferred) {
2689 (void) printf(gettext(" (awaiting resilver)"));
2693 /* The top-level vdevs have the rebuild stats */
2694 if (vrs != NULL && vrs->vrs_state == VDEV_REBUILD_ACTIVE &&
2695 children == 0 && vs->vs_state == VDEV_STATE_HEALTHY) {
2696 if (vs->vs_rebuild_processed != 0) {
2697 (void) printf(gettext(" (resilvering)"));
2701 if (cb->vcdl != NULL) {
2702 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
2703 printf(" ");
2704 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
2708 /* Display vdev initialization and trim status for leaves. */
2709 if (children == 0) {
2710 print_status_initialize(vs, cb->cb_print_vdev_init);
2711 print_status_trim(vs, cb->cb_print_vdev_trim);
2714 (void) printf("\n");
2716 for (c = 0; c < children; c++) {
2717 uint64_t islog = B_FALSE, ishole = B_FALSE;
2719 /* Don't print logs or holes here */
2720 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2721 &islog);
2722 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
2723 &ishole);
2724 if (islog || ishole)
2725 continue;
2726 /* Only print normal classes here */
2727 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
2728 continue;
2730 /* Provide vdev_rebuild_stats to children if available */
2731 if (vrs == NULL) {
2732 (void) nvlist_lookup_uint64_array(nv,
2733 ZPOOL_CONFIG_REBUILD_STATS,
2734 (uint64_t **)&vrs, &i);
2737 vname = zpool_vdev_name(g_zfs, zhp, child[c],
2738 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2739 print_status_config(zhp, cb, vname, child[c], depth + 2,
2740 isspare, vrs);
2741 free(vname);
2746 * Print the configuration of an exported pool. Iterate over all vdevs in the
2747 * pool, printing out the name and status for each one.
2749 static void
2750 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
2751 int depth)
2753 nvlist_t **child;
2754 uint_t c, children;
2755 vdev_stat_t *vs;
2756 const char *type;
2757 char *vname;
2759 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2760 if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
2761 strcmp(type, VDEV_TYPE_HOLE) == 0)
2762 return;
2764 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2765 (uint64_t **)&vs, &c) == 0);
2767 (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
2768 (void) printf(" %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
2770 if (vs->vs_aux != 0) {
2771 (void) printf(" ");
2773 switch (vs->vs_aux) {
2774 case VDEV_AUX_OPEN_FAILED:
2775 (void) printf(gettext("cannot open"));
2776 break;
2778 case VDEV_AUX_BAD_GUID_SUM:
2779 (void) printf(gettext("missing device"));
2780 break;
2782 case VDEV_AUX_NO_REPLICAS:
2783 (void) printf(gettext("insufficient replicas"));
2784 break;
2786 case VDEV_AUX_VERSION_NEWER:
2787 (void) printf(gettext("newer version"));
2788 break;
2790 case VDEV_AUX_UNSUP_FEAT:
2791 (void) printf(gettext("unsupported feature(s)"));
2792 break;
2794 case VDEV_AUX_ERR_EXCEEDED:
2795 (void) printf(gettext("too many errors"));
2796 break;
2798 case VDEV_AUX_ACTIVE:
2799 (void) printf(gettext("currently in use"));
2800 break;
2802 case VDEV_AUX_CHILDREN_OFFLINE:
2803 (void) printf(gettext("all children offline"));
2804 break;
2806 case VDEV_AUX_BAD_LABEL:
2807 (void) printf(gettext("invalid label"));
2808 break;
2810 default:
2811 (void) printf(gettext("corrupted data"));
2812 break;
2815 (void) printf("\n");
2817 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2818 &child, &children) != 0)
2819 return;
2821 for (c = 0; c < children; c++) {
2822 uint64_t is_log = B_FALSE;
2824 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2825 &is_log);
2826 if (is_log)
2827 continue;
2828 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
2829 continue;
2831 vname = zpool_vdev_name(g_zfs, NULL, child[c],
2832 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2833 print_import_config(cb, vname, child[c], depth + 2);
2834 free(vname);
2837 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2838 &child, &children) == 0) {
2839 (void) printf(gettext("\tcache\n"));
2840 for (c = 0; c < children; c++) {
2841 vname = zpool_vdev_name(g_zfs, NULL, child[c],
2842 cb->cb_name_flags);
2843 (void) printf("\t %s\n", vname);
2844 free(vname);
2848 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2849 &child, &children) == 0) {
2850 (void) printf(gettext("\tspares\n"));
2851 for (c = 0; c < children; c++) {
2852 vname = zpool_vdev_name(g_zfs, NULL, child[c],
2853 cb->cb_name_flags);
2854 (void) printf("\t %s\n", vname);
2855 free(vname);
2861 * Print specialized class vdevs.
2863 * These are recorded as top level vdevs in the main pool child array
2864 * but with "is_log" set to 1 or an "alloc_bias" string. We use either
2865 * print_status_config() or print_import_config() to print the top level
2866 * class vdevs then any of their children (eg mirrored slogs) are printed
2867 * recursively - which works because only the top level vdev is marked.
2869 static void
2870 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
2871 const char *class)
2873 uint_t c, children;
2874 nvlist_t **child;
2875 boolean_t printed = B_FALSE;
2877 assert(zhp != NULL || !cb->cb_verbose);
2879 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
2880 &children) != 0)
2881 return;
2883 for (c = 0; c < children; c++) {
2884 uint64_t is_log = B_FALSE;
2885 const char *bias = NULL;
2886 const char *type = NULL;
2888 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2889 &is_log);
2891 if (is_log) {
2892 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
2893 } else {
2894 (void) nvlist_lookup_string(child[c],
2895 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
2896 (void) nvlist_lookup_string(child[c],
2897 ZPOOL_CONFIG_TYPE, &type);
2900 if (bias == NULL || strcmp(bias, class) != 0)
2901 continue;
2902 if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2903 continue;
2905 if (!printed) {
2906 (void) printf("\t%s\t\n", gettext(class));
2907 printed = B_TRUE;
2910 char *name = zpool_vdev_name(g_zfs, zhp, child[c],
2911 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
2912 if (cb->cb_print_status)
2913 print_status_config(zhp, cb, name, child[c], 2,
2914 B_FALSE, NULL);
2915 else
2916 print_import_config(cb, name, child[c], 2);
2917 free(name);
2922 * Display the status for the given pool.
2924 static int
2925 show_import(nvlist_t *config, boolean_t report_error)
2927 uint64_t pool_state;
2928 vdev_stat_t *vs;
2929 const char *name;
2930 uint64_t guid;
2931 uint64_t hostid = 0;
2932 const char *msgid;
2933 const char *hostname = "unknown";
2934 nvlist_t *nvroot, *nvinfo;
2935 zpool_status_t reason;
2936 zpool_errata_t errata;
2937 const char *health;
2938 uint_t vsc;
2939 const char *comment;
2940 status_cbdata_t cb = { 0 };
2942 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2943 &name) == 0);
2944 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
2945 &guid) == 0);
2946 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2947 &pool_state) == 0);
2948 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2949 &nvroot) == 0);
2951 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
2952 (uint64_t **)&vs, &vsc) == 0);
2953 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2955 reason = zpool_import_status(config, &msgid, &errata);
2958 * If we're importing using a cachefile, then we won't report any
2959 * errors unless we are in the scan phase of the import.
2961 if (reason != ZPOOL_STATUS_OK && !report_error)
2962 return (reason);
2964 (void) printf(gettext(" pool: %s\n"), name);
2965 (void) printf(gettext(" id: %llu\n"), (u_longlong_t)guid);
2966 (void) printf(gettext(" state: %s"), health);
2967 if (pool_state == POOL_STATE_DESTROYED)
2968 (void) printf(gettext(" (DESTROYED)"));
2969 (void) printf("\n");
2971 switch (reason) {
2972 case ZPOOL_STATUS_MISSING_DEV_R:
2973 case ZPOOL_STATUS_MISSING_DEV_NR:
2974 case ZPOOL_STATUS_BAD_GUID_SUM:
2975 printf_color(ANSI_BOLD, gettext("status: "));
2976 printf_color(ANSI_YELLOW, gettext("One or more devices are "
2977 "missing from the system.\n"));
2978 break;
2980 case ZPOOL_STATUS_CORRUPT_LABEL_R:
2981 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
2982 printf_color(ANSI_BOLD, gettext("status: "));
2983 printf_color(ANSI_YELLOW, gettext("One or more devices contains"
2984 " corrupted data.\n"));
2985 break;
2987 case ZPOOL_STATUS_CORRUPT_DATA:
2988 (void) printf(
2989 gettext(" status: The pool data is corrupted.\n"));
2990 break;
2992 case ZPOOL_STATUS_OFFLINE_DEV:
2993 printf_color(ANSI_BOLD, gettext("status: "));
2994 printf_color(ANSI_YELLOW, gettext("One or more devices "
2995 "are offlined.\n"));
2996 break;
2998 case ZPOOL_STATUS_CORRUPT_POOL:
2999 printf_color(ANSI_BOLD, gettext("status: "));
3000 printf_color(ANSI_YELLOW, gettext("The pool metadata is "
3001 "corrupted.\n"));
3002 break;
3004 case ZPOOL_STATUS_VERSION_OLDER:
3005 printf_color(ANSI_BOLD, gettext("status: "));
3006 printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
3007 "a legacy on-disk version.\n"));
3008 break;
3010 case ZPOOL_STATUS_VERSION_NEWER:
3011 printf_color(ANSI_BOLD, gettext("status: "));
3012 printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
3013 "an incompatible version.\n"));
3014 break;
3016 case ZPOOL_STATUS_FEAT_DISABLED:
3017 printf_color(ANSI_BOLD, gettext("status: "));
3018 printf_color(ANSI_YELLOW, gettext("Some supported "
3019 "features are not enabled on the pool.\n\t"
3020 "(Note that they may be intentionally disabled "
3021 "if the\n\t'compatibility' property is set.)\n"));
3022 break;
3024 case ZPOOL_STATUS_COMPATIBILITY_ERR:
3025 printf_color(ANSI_BOLD, gettext("status: "));
3026 printf_color(ANSI_YELLOW, gettext("Error reading or parsing "
3027 "the file(s) indicated by the 'compatibility'\n"
3028 "property.\n"));
3029 break;
3031 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
3032 printf_color(ANSI_BOLD, gettext("status: "));
3033 printf_color(ANSI_YELLOW, gettext("One or more features "
3034 "are enabled on the pool despite not being\n"
3035 "requested by the 'compatibility' property.\n"));
3036 break;
3038 case ZPOOL_STATUS_UNSUP_FEAT_READ:
3039 printf_color(ANSI_BOLD, gettext("status: "));
3040 printf_color(ANSI_YELLOW, gettext("The pool uses the following "
3041 "feature(s) not supported on this system:\n"));
3042 color_start(ANSI_YELLOW);
3043 zpool_print_unsup_feat(config);
3044 color_end();
3045 break;
3047 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3048 printf_color(ANSI_BOLD, gettext("status: "));
3049 printf_color(ANSI_YELLOW, gettext("The pool can only be "
3050 "accessed in read-only mode on this system. It\n\tcannot be"
3051 " accessed in read-write mode because it uses the "
3052 "following\n\tfeature(s) not supported on this system:\n"));
3053 color_start(ANSI_YELLOW);
3054 zpool_print_unsup_feat(config);
3055 color_end();
3056 break;
3058 case ZPOOL_STATUS_HOSTID_ACTIVE:
3059 printf_color(ANSI_BOLD, gettext("status: "));
3060 printf_color(ANSI_YELLOW, gettext("The pool is currently "
3061 "imported by another system.\n"));
3062 break;
3064 case ZPOOL_STATUS_HOSTID_REQUIRED:
3065 printf_color(ANSI_BOLD, gettext("status: "));
3066 printf_color(ANSI_YELLOW, gettext("The pool has the "
3067 "multihost property on. It cannot\n\tbe safely imported "
3068 "when the system hostid is not set.\n"));
3069 break;
3071 case ZPOOL_STATUS_HOSTID_MISMATCH:
3072 printf_color(ANSI_BOLD, gettext("status: "));
3073 printf_color(ANSI_YELLOW, gettext("The pool was last accessed "
3074 "by another system.\n"));
3075 break;
3077 case ZPOOL_STATUS_FAULTED_DEV_R:
3078 case ZPOOL_STATUS_FAULTED_DEV_NR:
3079 printf_color(ANSI_BOLD, gettext("status: "));
3080 printf_color(ANSI_YELLOW, gettext("One or more devices are "
3081 "faulted.\n"));
3082 break;
3084 case ZPOOL_STATUS_BAD_LOG:
3085 printf_color(ANSI_BOLD, gettext("status: "));
3086 printf_color(ANSI_YELLOW, gettext("An intent log record cannot "
3087 "be read.\n"));
3088 break;
3090 case ZPOOL_STATUS_RESILVERING:
3091 case ZPOOL_STATUS_REBUILDING:
3092 printf_color(ANSI_BOLD, gettext("status: "));
3093 printf_color(ANSI_YELLOW, gettext("One or more devices were "
3094 "being resilvered.\n"));
3095 break;
3097 case ZPOOL_STATUS_ERRATA:
3098 printf_color(ANSI_BOLD, gettext("status: "));
3099 printf_color(ANSI_YELLOW, gettext("Errata #%d detected.\n"),
3100 errata);
3101 break;
3103 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
3104 printf_color(ANSI_BOLD, gettext("status: "));
3105 printf_color(ANSI_YELLOW, gettext("One or more devices are "
3106 "configured to use a non-native block size.\n"
3107 "\tExpect reduced performance.\n"));
3108 break;
3110 default:
3112 * No other status can be seen when importing pools.
3114 assert(reason == ZPOOL_STATUS_OK);
3118 * Print out an action according to the overall state of the pool.
3120 if (vs->vs_state == VDEV_STATE_HEALTHY) {
3121 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
3122 reason == ZPOOL_STATUS_FEAT_DISABLED) {
3123 (void) printf(gettext(" action: The pool can be "
3124 "imported using its name or numeric identifier, "
3125 "though\n\tsome features will not be available "
3126 "without an explicit 'zpool upgrade'.\n"));
3127 } else if (reason == ZPOOL_STATUS_COMPATIBILITY_ERR) {
3128 (void) printf(gettext(" action: The pool can be "
3129 "imported using its name or numeric\n\tidentifier, "
3130 "though the file(s) indicated by its "
3131 "'compatibility'\n\tproperty cannot be parsed at "
3132 "this time.\n"));
3133 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
3134 (void) printf(gettext(" action: The pool can be "
3135 "imported using its name or numeric "
3136 "identifier and\n\tthe '-f' flag.\n"));
3137 } else if (reason == ZPOOL_STATUS_ERRATA) {
3138 switch (errata) {
3139 case ZPOOL_ERRATA_NONE:
3140 break;
3142 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
3143 (void) printf(gettext(" action: The pool can "
3144 "be imported using its name or numeric "
3145 "identifier,\n\thowever there is a compat"
3146 "ibility issue which should be corrected"
3147 "\n\tby running 'zpool scrub'\n"));
3148 break;
3150 case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
3151 (void) printf(gettext(" action: The pool can"
3152 "not be imported with this version of ZFS "
3153 "due to\n\tan active asynchronous destroy. "
3154 "Revert to an earlier version\n\tand "
3155 "allow the destroy to complete before "
3156 "updating.\n"));
3157 break;
3159 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
3160 (void) printf(gettext(" action: Existing "
3161 "encrypted datasets contain an on-disk "
3162 "incompatibility, which\n\tneeds to be "
3163 "corrected. Backup these datasets to new "
3164 "encrypted datasets\n\tand destroy the "
3165 "old ones.\n"));
3166 break;
3168 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
3169 (void) printf(gettext(" action: Existing "
3170 "encrypted snapshots and bookmarks contain "
3171 "an on-disk\n\tincompatibility. This may "
3172 "cause on-disk corruption if they are used"
3173 "\n\twith 'zfs recv'. To correct the "
3174 "issue, enable the bookmark_v2 feature.\n\t"
3175 "No additional action is needed if there "
3176 "are no encrypted snapshots or\n\t"
3177 "bookmarks. If preserving the encrypted "
3178 "snapshots and bookmarks is\n\trequired, "
3179 "use a non-raw send to backup and restore "
3180 "them. Alternately,\n\tthey may be removed"
3181 " to resolve the incompatibility.\n"));
3182 break;
3183 default:
3185 * All errata must contain an action message.
3187 assert(0);
3189 } else {
3190 (void) printf(gettext(" action: The pool can be "
3191 "imported using its name or numeric "
3192 "identifier.\n"));
3194 } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
3195 (void) printf(gettext(" action: The pool can be imported "
3196 "despite missing or damaged devices. The\n\tfault "
3197 "tolerance of the pool may be compromised if imported.\n"));
3198 } else {
3199 switch (reason) {
3200 case ZPOOL_STATUS_VERSION_NEWER:
3201 (void) printf(gettext(" action: The pool cannot be "
3202 "imported. Access the pool on a system running "
3203 "newer\n\tsoftware, or recreate the pool from "
3204 "backup.\n"));
3205 break;
3206 case ZPOOL_STATUS_UNSUP_FEAT_READ:
3207 printf_color(ANSI_BOLD, gettext("action: "));
3208 printf_color(ANSI_YELLOW, gettext("The pool cannot be "
3209 "imported. Access the pool on a system that "
3210 "supports\n\tthe required feature(s), or recreate "
3211 "the pool from backup.\n"));
3212 break;
3213 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3214 printf_color(ANSI_BOLD, gettext("action: "));
3215 printf_color(ANSI_YELLOW, gettext("The pool cannot be "
3216 "imported in read-write mode. Import the pool "
3217 "with\n"
3218 "\t\"-o readonly=on\", access the pool on a system "
3219 "that supports the\n\trequired feature(s), or "
3220 "recreate the pool from backup.\n"));
3221 break;
3222 case ZPOOL_STATUS_MISSING_DEV_R:
3223 case ZPOOL_STATUS_MISSING_DEV_NR:
3224 case ZPOOL_STATUS_BAD_GUID_SUM:
3225 (void) printf(gettext(" action: The pool cannot be "
3226 "imported. Attach the missing\n\tdevices and try "
3227 "again.\n"));
3228 break;
3229 case ZPOOL_STATUS_HOSTID_ACTIVE:
3230 VERIFY0(nvlist_lookup_nvlist(config,
3231 ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
3233 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3234 hostname = fnvlist_lookup_string(nvinfo,
3235 ZPOOL_CONFIG_MMP_HOSTNAME);
3237 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3238 hostid = fnvlist_lookup_uint64(nvinfo,
3239 ZPOOL_CONFIG_MMP_HOSTID);
3241 (void) printf(gettext(" action: The pool must be "
3242 "exported from %s (hostid=%"PRIx64")\n\tbefore it "
3243 "can be safely imported.\n"), hostname, hostid);
3244 break;
3245 case ZPOOL_STATUS_HOSTID_REQUIRED:
3246 (void) printf(gettext(" action: Set a unique system "
3247 "hostid with the zgenhostid(8) command.\n"));
3248 break;
3249 default:
3250 (void) printf(gettext(" action: The pool cannot be "
3251 "imported due to damaged devices or data.\n"));
3255 /* Print the comment attached to the pool. */
3256 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
3257 (void) printf(gettext("comment: %s\n"), comment);
3260 * If the state is "closed" or "can't open", and the aux state
3261 * is "corrupt data":
3263 if (((vs->vs_state == VDEV_STATE_CLOSED) ||
3264 (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
3265 (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
3266 if (pool_state == POOL_STATE_DESTROYED)
3267 (void) printf(gettext("\tThe pool was destroyed, "
3268 "but can be imported using the '-Df' flags.\n"));
3269 else if (pool_state != POOL_STATE_EXPORTED)
3270 (void) printf(gettext("\tThe pool may be active on "
3271 "another system, but can be imported using\n\t"
3272 "the '-f' flag.\n"));
3275 if (msgid != NULL) {
3276 (void) printf(gettext(
3277 " see: https://openzfs.github.io/openzfs-docs/msg/%s\n"),
3278 msgid);
3281 (void) printf(gettext(" config:\n\n"));
3283 cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
3284 VDEV_NAME_TYPE_ID);
3285 if (cb.cb_namewidth < 10)
3286 cb.cb_namewidth = 10;
3288 print_import_config(&cb, name, nvroot, 0);
3290 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
3291 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
3292 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
3294 if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
3295 (void) printf(gettext("\n\tAdditional devices are known to "
3296 "be part of this pool, though their\n\texact "
3297 "configuration cannot be determined.\n"));
3299 return (0);
3302 static boolean_t
3303 zfs_force_import_required(nvlist_t *config)
3305 uint64_t state;
3306 uint64_t hostid = 0;
3307 nvlist_t *nvinfo;
3309 state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
3310 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3313 * The hostid on LOAD_INFO comes from the MOS label via
3314 * spa_tryimport(). If its not there then we're likely talking to an
3315 * older kernel, so use the top one, which will be from the label
3316 * discovered in zpool_find_import(), or if a cachefile is in use, the
3317 * local hostid.
3319 if (nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_HOSTID, &hostid) != 0)
3320 nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID, &hostid);
3322 if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
3323 return (B_TRUE);
3325 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
3326 mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
3327 ZPOOL_CONFIG_MMP_STATE);
3329 if (mmp_state != MMP_STATE_INACTIVE)
3330 return (B_TRUE);
3333 return (B_FALSE);
3337 * Perform the import for the given configuration. This passes the heavy
3338 * lifting off to zpool_import_props(), and then mounts the datasets contained
3339 * within the pool.
3341 static int
3342 do_import(nvlist_t *config, const char *newname, const char *mntopts,
3343 nvlist_t *props, int flags)
3345 int ret = 0;
3346 int ms_status = 0;
3347 zpool_handle_t *zhp;
3348 const char *name;
3349 uint64_t version;
3351 name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
3352 version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3354 if (!SPA_VERSION_IS_SUPPORTED(version)) {
3355 (void) fprintf(stderr, gettext("cannot import '%s': pool "
3356 "is formatted using an unsupported ZFS version\n"), name);
3357 return (1);
3358 } else if (zfs_force_import_required(config) &&
3359 !(flags & ZFS_IMPORT_ANY_HOST)) {
3360 mmp_state_t mmp_state = MMP_STATE_INACTIVE;
3361 nvlist_t *nvinfo;
3363 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3364 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
3365 mmp_state = fnvlist_lookup_uint64(nvinfo,
3366 ZPOOL_CONFIG_MMP_STATE);
3368 if (mmp_state == MMP_STATE_ACTIVE) {
3369 const char *hostname = "<unknown>";
3370 uint64_t hostid = 0;
3372 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3373 hostname = fnvlist_lookup_string(nvinfo,
3374 ZPOOL_CONFIG_MMP_HOSTNAME);
3376 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3377 hostid = fnvlist_lookup_uint64(nvinfo,
3378 ZPOOL_CONFIG_MMP_HOSTID);
3380 (void) fprintf(stderr, gettext("cannot import '%s': "
3381 "pool is imported on %s (hostid: "
3382 "0x%"PRIx64")\nExport the pool on the other "
3383 "system, then run 'zpool import'.\n"),
3384 name, hostname, hostid);
3385 } else if (mmp_state == MMP_STATE_NO_HOSTID) {
3386 (void) fprintf(stderr, gettext("Cannot import '%s': "
3387 "pool has the multihost property on and the\n"
3388 "system's hostid is not set. Set a unique hostid "
3389 "with the zgenhostid(8) command.\n"), name);
3390 } else {
3391 const char *hostname = "<unknown>";
3392 time_t timestamp = 0;
3393 uint64_t hostid = 0;
3395 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTNAME))
3396 hostname = fnvlist_lookup_string(nvinfo,
3397 ZPOOL_CONFIG_HOSTNAME);
3398 else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
3399 hostname = fnvlist_lookup_string(config,
3400 ZPOOL_CONFIG_HOSTNAME);
3402 if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
3403 timestamp = fnvlist_lookup_uint64(config,
3404 ZPOOL_CONFIG_TIMESTAMP);
3406 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTID))
3407 hostid = fnvlist_lookup_uint64(nvinfo,
3408 ZPOOL_CONFIG_HOSTID);
3409 else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
3410 hostid = fnvlist_lookup_uint64(config,
3411 ZPOOL_CONFIG_HOSTID);
3413 (void) fprintf(stderr, gettext("cannot import '%s': "
3414 "pool was previously in use from another system.\n"
3415 "Last accessed by %s (hostid=%"PRIx64") at %s"
3416 "The pool can be imported, use 'zpool import -f' "
3417 "to import the pool.\n"), name, hostname,
3418 hostid, ctime(&timestamp));
3421 return (1);
3424 if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
3425 return (1);
3427 if (newname != NULL)
3428 name = newname;
3430 if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
3431 return (1);
3434 * Loading keys is best effort. We don't want to return immediately
3435 * if it fails but we do want to give the error to the caller.
3437 if (flags & ZFS_IMPORT_LOAD_KEYS &&
3438 zfs_crypto_attempt_load_keys(g_zfs, name) != 0)
3439 ret = 1;
3441 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3442 !(flags & ZFS_IMPORT_ONLY)) {
3443 ms_status = zpool_enable_datasets(zhp, mntopts, 0);
3444 if (ms_status == EZFS_SHAREFAILED) {
3445 (void) fprintf(stderr, gettext("Import was "
3446 "successful, but unable to share some datasets\n"));
3447 } else if (ms_status == EZFS_MOUNTFAILED) {
3448 (void) fprintf(stderr, gettext("Import was "
3449 "successful, but unable to mount some datasets\n"));
3453 zpool_close(zhp);
3454 return (ret);
3457 static int
3458 import_pools(nvlist_t *pools, nvlist_t *props, char *mntopts, int flags,
3459 char *orig_name, char *new_name,
3460 boolean_t do_destroyed, boolean_t pool_specified, boolean_t do_all,
3461 importargs_t *import)
3463 nvlist_t *config = NULL;
3464 nvlist_t *found_config = NULL;
3465 uint64_t pool_state;
3468 * At this point we have a list of import candidate configs. Even if
3469 * we were searching by pool name or guid, we still need to
3470 * post-process the list to deal with pool state and possible
3471 * duplicate names.
3473 int err = 0;
3474 nvpair_t *elem = NULL;
3475 boolean_t first = B_TRUE;
3476 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3478 verify(nvpair_value_nvlist(elem, &config) == 0);
3480 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3481 &pool_state) == 0);
3482 if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
3483 continue;
3484 if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
3485 continue;
3487 verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
3488 import->policy) == 0);
3490 if (!pool_specified) {
3491 if (first)
3492 first = B_FALSE;
3493 else if (!do_all)
3494 (void) fputc('\n', stdout);
3496 if (do_all) {
3497 err |= do_import(config, NULL, mntopts,
3498 props, flags);
3499 } else {
3501 * If we're importing from cachefile, then
3502 * we don't want to report errors until we
3503 * are in the scan phase of the import. If
3504 * we get an error, then we return that error
3505 * to invoke the scan phase.
3507 if (import->cachefile && !import->scan)
3508 err = show_import(config, B_FALSE);
3509 else
3510 (void) show_import(config, B_TRUE);
3512 } else if (import->poolname != NULL) {
3513 const char *name;
3516 * We are searching for a pool based on name.
3518 verify(nvlist_lookup_string(config,
3519 ZPOOL_CONFIG_POOL_NAME, &name) == 0);
3521 if (strcmp(name, import->poolname) == 0) {
3522 if (found_config != NULL) {
3523 (void) fprintf(stderr, gettext(
3524 "cannot import '%s': more than "
3525 "one matching pool\n"),
3526 import->poolname);
3527 (void) fprintf(stderr, gettext(
3528 "import by numeric ID instead\n"));
3529 err = B_TRUE;
3531 found_config = config;
3533 } else {
3534 uint64_t guid;
3537 * Search for a pool by guid.
3539 verify(nvlist_lookup_uint64(config,
3540 ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
3542 if (guid == import->guid)
3543 found_config = config;
3548 * If we were searching for a specific pool, verify that we found a
3549 * pool, and then do the import.
3551 if (pool_specified && err == 0) {
3552 if (found_config == NULL) {
3553 (void) fprintf(stderr, gettext("cannot import '%s': "
3554 "no such pool available\n"), orig_name);
3555 err = B_TRUE;
3556 } else {
3557 err |= do_import(found_config, new_name,
3558 mntopts, props, flags);
3563 * If we were just looking for pools, report an error if none were
3564 * found.
3566 if (!pool_specified && first)
3567 (void) fprintf(stderr,
3568 gettext("no pools available to import\n"));
3569 return (err);
3572 typedef struct target_exists_args {
3573 const char *poolname;
3574 uint64_t poolguid;
3575 } target_exists_args_t;
3577 static int
3578 name_or_guid_exists(zpool_handle_t *zhp, void *data)
3580 target_exists_args_t *args = data;
3581 nvlist_t *config = zpool_get_config(zhp, NULL);
3582 int found = 0;
3584 if (config == NULL)
3585 return (0);
3587 if (args->poolname != NULL) {
3588 const char *pool_name;
3590 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3591 &pool_name) == 0);
3592 if (strcmp(pool_name, args->poolname) == 0)
3593 found = 1;
3594 } else {
3595 uint64_t pool_guid;
3597 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3598 &pool_guid) == 0);
3599 if (pool_guid == args->poolguid)
3600 found = 1;
3602 zpool_close(zhp);
3604 return (found);
3607 * zpool checkpoint <pool>
3608 * checkpoint --discard <pool>
3610 * -d Discard the checkpoint from a checkpointed
3611 * --discard pool.
3613 * -w Wait for discarding a checkpoint to complete.
3614 * --wait
3616 * Checkpoints the specified pool, by taking a "snapshot" of its
3617 * current state. A pool can only have one checkpoint at a time.
3620 zpool_do_checkpoint(int argc, char **argv)
3622 boolean_t discard, wait;
3623 char *pool;
3624 zpool_handle_t *zhp;
3625 int c, err;
3627 struct option long_options[] = {
3628 {"discard", no_argument, NULL, 'd'},
3629 {"wait", no_argument, NULL, 'w'},
3630 {0, 0, 0, 0}
3633 discard = B_FALSE;
3634 wait = B_FALSE;
3635 while ((c = getopt_long(argc, argv, ":dw", long_options, NULL)) != -1) {
3636 switch (c) {
3637 case 'd':
3638 discard = B_TRUE;
3639 break;
3640 case 'w':
3641 wait = B_TRUE;
3642 break;
3643 case '?':
3644 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3645 optopt);
3646 usage(B_FALSE);
3650 if (wait && !discard) {
3651 (void) fprintf(stderr, gettext("--wait only valid when "
3652 "--discard also specified\n"));
3653 usage(B_FALSE);
3656 argc -= optind;
3657 argv += optind;
3659 if (argc < 1) {
3660 (void) fprintf(stderr, gettext("missing pool argument\n"));
3661 usage(B_FALSE);
3664 if (argc > 1) {
3665 (void) fprintf(stderr, gettext("too many arguments\n"));
3666 usage(B_FALSE);
3669 pool = argv[0];
3671 if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
3672 /* As a special case, check for use of '/' in the name */
3673 if (strchr(pool, '/') != NULL)
3674 (void) fprintf(stderr, gettext("'zpool checkpoint' "
3675 "doesn't work on datasets. To save the state "
3676 "of a dataset from a specific point in time "
3677 "please use 'zfs snapshot'\n"));
3678 return (1);
3681 if (discard) {
3682 err = (zpool_discard_checkpoint(zhp) != 0);
3683 if (err == 0 && wait)
3684 err = zpool_wait(zhp, ZPOOL_WAIT_CKPT_DISCARD);
3685 } else {
3686 err = (zpool_checkpoint(zhp) != 0);
3689 zpool_close(zhp);
3691 return (err);
3694 #define CHECKPOINT_OPT 1024
3697 * zpool import [-d dir] [-D]
3698 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
3699 * [-d dir | -c cachefile | -s] [-f] -a
3700 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
3701 * [-d dir | -c cachefile | -s] [-f] [-n] [-F] <pool | id>
3702 * [newpool]
3704 * -c Read pool information from a cachefile instead of searching
3705 * devices. If importing from a cachefile config fails, then
3706 * fallback to searching for devices only in the directories that
3707 * exist in the cachefile.
3709 * -d Scan in a specific directory, other than /dev/. More than
3710 * one directory can be specified using multiple '-d' options.
3712 * -D Scan for previously destroyed pools or import all or only
3713 * specified destroyed pools.
3715 * -R Temporarily import the pool, with all mountpoints relative to
3716 * the given root. The pool will remain exported when the machine
3717 * is rebooted.
3719 * -V Import even in the presence of faulted vdevs. This is an
3720 * intentionally undocumented option for testing purposes, and
3721 * treats the pool configuration as complete, leaving any bad
3722 * vdevs in the FAULTED state. In other words, it does verbatim
3723 * import.
3725 * -f Force import, even if it appears that the pool is active.
3727 * -F Attempt rewind if necessary.
3729 * -n See if rewind would work, but don't actually rewind.
3731 * -N Import the pool but don't mount datasets.
3733 * -T Specify a starting txg to use for import. This option is
3734 * intentionally undocumented option for testing purposes.
3736 * -a Import all pools found.
3738 * -l Load encryption keys while importing.
3740 * -o Set property=value and/or temporary mount options (without '=').
3742 * -s Scan using the default search path, the libblkid cache will
3743 * not be consulted.
3745 * --rewind-to-checkpoint
3746 * Import the pool and revert back to the checkpoint.
3748 * The import command scans for pools to import, and import pools based on pool
3749 * name and GUID. The pool can also be renamed as part of the import process.
3752 zpool_do_import(int argc, char **argv)
3754 char **searchdirs = NULL;
3755 char *env, *envdup = NULL;
3756 int nsearch = 0;
3757 int c;
3758 int err = 0;
3759 nvlist_t *pools = NULL;
3760 boolean_t do_all = B_FALSE;
3761 boolean_t do_destroyed = B_FALSE;
3762 char *mntopts = NULL;
3763 uint64_t searchguid = 0;
3764 char *searchname = NULL;
3765 char *propval;
3766 nvlist_t *policy = NULL;
3767 nvlist_t *props = NULL;
3768 int flags = ZFS_IMPORT_NORMAL;
3769 uint32_t rewind_policy = ZPOOL_NO_REWIND;
3770 boolean_t dryrun = B_FALSE;
3771 boolean_t do_rewind = B_FALSE;
3772 boolean_t xtreme_rewind = B_FALSE;
3773 boolean_t do_scan = B_FALSE;
3774 boolean_t pool_exists = B_FALSE;
3775 boolean_t pool_specified = B_FALSE;
3776 uint64_t txg = -1ULL;
3777 char *cachefile = NULL;
3778 importargs_t idata = { 0 };
3779 char *endptr;
3781 struct option long_options[] = {
3782 {"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
3783 {0, 0, 0, 0}
3786 /* check options */
3787 while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmnNo:R:stT:VX",
3788 long_options, NULL)) != -1) {
3789 switch (c) {
3790 case 'a':
3791 do_all = B_TRUE;
3792 break;
3793 case 'c':
3794 cachefile = optarg;
3795 break;
3796 case 'd':
3797 searchdirs = safe_realloc(searchdirs,
3798 (nsearch + 1) * sizeof (char *));
3799 searchdirs[nsearch++] = optarg;
3800 break;
3801 case 'D':
3802 do_destroyed = B_TRUE;
3803 break;
3804 case 'f':
3805 flags |= ZFS_IMPORT_ANY_HOST;
3806 break;
3807 case 'F':
3808 do_rewind = B_TRUE;
3809 break;
3810 case 'l':
3811 flags |= ZFS_IMPORT_LOAD_KEYS;
3812 break;
3813 case 'm':
3814 flags |= ZFS_IMPORT_MISSING_LOG;
3815 break;
3816 case 'n':
3817 dryrun = B_TRUE;
3818 break;
3819 case 'N':
3820 flags |= ZFS_IMPORT_ONLY;
3821 break;
3822 case 'o':
3823 if ((propval = strchr(optarg, '=')) != NULL) {
3824 *propval = '\0';
3825 propval++;
3826 if (add_prop_list(optarg, propval,
3827 &props, B_TRUE))
3828 goto error;
3829 } else {
3830 mntopts = optarg;
3832 break;
3833 case 'R':
3834 if (add_prop_list(zpool_prop_to_name(
3835 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
3836 goto error;
3837 if (add_prop_list_default(zpool_prop_to_name(
3838 ZPOOL_PROP_CACHEFILE), "none", &props))
3839 goto error;
3840 break;
3841 case 's':
3842 do_scan = B_TRUE;
3843 break;
3844 case 't':
3845 flags |= ZFS_IMPORT_TEMP_NAME;
3846 if (add_prop_list_default(zpool_prop_to_name(
3847 ZPOOL_PROP_CACHEFILE), "none", &props))
3848 goto error;
3849 break;
3851 case 'T':
3852 errno = 0;
3853 txg = strtoull(optarg, &endptr, 0);
3854 if (errno != 0 || *endptr != '\0') {
3855 (void) fprintf(stderr,
3856 gettext("invalid txg value\n"));
3857 usage(B_FALSE);
3859 rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
3860 break;
3861 case 'V':
3862 flags |= ZFS_IMPORT_VERBATIM;
3863 break;
3864 case 'X':
3865 xtreme_rewind = B_TRUE;
3866 break;
3867 case CHECKPOINT_OPT:
3868 flags |= ZFS_IMPORT_CHECKPOINT;
3869 break;
3870 case ':':
3871 (void) fprintf(stderr, gettext("missing argument for "
3872 "'%c' option\n"), optopt);
3873 usage(B_FALSE);
3874 break;
3875 case '?':
3876 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3877 optopt);
3878 usage(B_FALSE);
3882 argc -= optind;
3883 argv += optind;
3885 if (cachefile && nsearch != 0) {
3886 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
3887 usage(B_FALSE);
3890 if (cachefile && do_scan) {
3891 (void) fprintf(stderr, gettext("-c is incompatible with -s\n"));
3892 usage(B_FALSE);
3895 if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
3896 (void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
3897 usage(B_FALSE);
3900 if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
3901 (void) fprintf(stderr, gettext("-l is only meaningful during "
3902 "an import\n"));
3903 usage(B_FALSE);
3906 if ((dryrun || xtreme_rewind) && !do_rewind) {
3907 (void) fprintf(stderr,
3908 gettext("-n or -X only meaningful with -F\n"));
3909 usage(B_FALSE);
3911 if (dryrun)
3912 rewind_policy = ZPOOL_TRY_REWIND;
3913 else if (do_rewind)
3914 rewind_policy = ZPOOL_DO_REWIND;
3915 if (xtreme_rewind)
3916 rewind_policy |= ZPOOL_EXTREME_REWIND;
3918 /* In the future, we can capture further policy and include it here */
3919 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
3920 nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
3921 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
3922 rewind_policy) != 0)
3923 goto error;
3925 /* check argument count */
3926 if (do_all) {
3927 if (argc != 0) {
3928 (void) fprintf(stderr, gettext("too many arguments\n"));
3929 usage(B_FALSE);
3931 } else {
3932 if (argc > 2) {
3933 (void) fprintf(stderr, gettext("too many arguments\n"));
3934 usage(B_FALSE);
3939 * Check for the effective uid. We do this explicitly here because
3940 * otherwise any attempt to discover pools will silently fail.
3942 if (argc == 0 && geteuid() != 0) {
3943 (void) fprintf(stderr, gettext("cannot "
3944 "discover pools: permission denied\n"));
3946 free(searchdirs);
3947 nvlist_free(props);
3948 nvlist_free(policy);
3949 return (1);
3953 * Depending on the arguments given, we do one of the following:
3955 * <none> Iterate through all pools and display information about
3956 * each one.
3958 * -a Iterate through all pools and try to import each one.
3960 * <id> Find the pool that corresponds to the given GUID/pool
3961 * name and import that one.
3963 * -D Above options applies only to destroyed pools.
3965 if (argc != 0) {
3966 char *endptr;
3968 errno = 0;
3969 searchguid = strtoull(argv[0], &endptr, 10);
3970 if (errno != 0 || *endptr != '\0') {
3971 searchname = argv[0];
3972 searchguid = 0;
3974 pool_specified = B_TRUE;
3977 * User specified a name or guid. Ensure it's unique.
3979 target_exists_args_t search = {searchname, searchguid};
3980 pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
3984 * Check the environment for the preferred search path.
3986 if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
3987 char *dir, *tmp = NULL;
3989 envdup = strdup(env);
3991 for (dir = strtok_r(envdup, ":", &tmp);
3992 dir != NULL;
3993 dir = strtok_r(NULL, ":", &tmp)) {
3994 searchdirs = safe_realloc(searchdirs,
3995 (nsearch + 1) * sizeof (char *));
3996 searchdirs[nsearch++] = dir;
4000 idata.path = searchdirs;
4001 idata.paths = nsearch;
4002 idata.poolname = searchname;
4003 idata.guid = searchguid;
4004 idata.cachefile = cachefile;
4005 idata.scan = do_scan;
4006 idata.policy = policy;
4008 libpc_handle_t lpch = {
4009 .lpc_lib_handle = g_zfs,
4010 .lpc_ops = &libzfs_config_ops,
4011 .lpc_printerr = B_TRUE
4013 pools = zpool_search_import(&lpch, &idata);
4015 if (pools != NULL && pool_exists &&
4016 (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
4017 (void) fprintf(stderr, gettext("cannot import '%s': "
4018 "a pool with that name already exists\n"),
4019 argv[0]);
4020 (void) fprintf(stderr, gettext("use the form '%s "
4021 "<pool | id> <newpool>' to give it a new name\n"),
4022 "zpool import");
4023 err = 1;
4024 } else if (pools == NULL && pool_exists) {
4025 (void) fprintf(stderr, gettext("cannot import '%s': "
4026 "a pool with that name is already created/imported,\n"),
4027 argv[0]);
4028 (void) fprintf(stderr, gettext("and no additional pools "
4029 "with that name were found\n"));
4030 err = 1;
4031 } else if (pools == NULL) {
4032 if (argc != 0) {
4033 (void) fprintf(stderr, gettext("cannot import '%s': "
4034 "no such pool available\n"), argv[0]);
4036 err = 1;
4039 if (err == 1) {
4040 free(searchdirs);
4041 free(envdup);
4042 nvlist_free(policy);
4043 nvlist_free(pools);
4044 nvlist_free(props);
4045 return (1);
4048 err = import_pools(pools, props, mntopts, flags,
4049 argc >= 1 ? argv[0] : NULL,
4050 argc >= 2 ? argv[1] : NULL,
4051 do_destroyed, pool_specified, do_all, &idata);
4054 * If we're using the cachefile and we failed to import, then
4055 * fallback to scanning the directory for pools that match
4056 * those in the cachefile.
4058 if (err != 0 && cachefile != NULL) {
4059 (void) printf(gettext("cachefile import failed, retrying\n"));
4062 * We use the scan flag to gather the directories that exist
4063 * in the cachefile. If we need to fallback to searching for
4064 * the pool config, we will only search devices in these
4065 * directories.
4067 idata.scan = B_TRUE;
4068 nvlist_free(pools);
4069 pools = zpool_search_import(&lpch, &idata);
4071 err = import_pools(pools, props, mntopts, flags,
4072 argc >= 1 ? argv[0] : NULL,
4073 argc >= 2 ? argv[1] : NULL,
4074 do_destroyed, pool_specified, do_all, &idata);
4077 error:
4078 nvlist_free(props);
4079 nvlist_free(pools);
4080 nvlist_free(policy);
4081 free(searchdirs);
4082 free(envdup);
4084 return (err ? 1 : 0);
4088 * zpool sync [-f] [pool] ...
4090 * -f (undocumented) force uberblock (and config including zpool cache file)
4091 * update.
4093 * Sync the specified pool(s).
4094 * Without arguments "zpool sync" will sync all pools.
4095 * This command initiates TXG sync(s) and will return after the TXG(s) commit.
4098 static int
4099 zpool_do_sync(int argc, char **argv)
4101 int ret;
4102 boolean_t force = B_FALSE;
4104 /* check options */
4105 while ((ret = getopt(argc, argv, "f")) != -1) {
4106 switch (ret) {
4107 case 'f':
4108 force = B_TRUE;
4109 break;
4110 case '?':
4111 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4112 optopt);
4113 usage(B_FALSE);
4117 argc -= optind;
4118 argv += optind;
4120 /* if argc == 0 we will execute zpool_sync_one on all pools */
4121 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
4122 B_FALSE, zpool_sync_one, &force);
4124 return (ret);
4127 typedef struct iostat_cbdata {
4128 uint64_t cb_flags;
4129 int cb_namewidth;
4130 int cb_iteration;
4131 boolean_t cb_verbose;
4132 boolean_t cb_literal;
4133 boolean_t cb_scripted;
4134 zpool_list_t *cb_list;
4135 vdev_cmd_data_list_t *vcdl;
4136 vdev_cbdata_t cb_vdevs;
4137 } iostat_cbdata_t;
4139 /* iostat labels */
4140 typedef struct name_and_columns {
4141 const char *name; /* Column name */
4142 unsigned int columns; /* Center name to this number of columns */
4143 } name_and_columns_t;
4145 #define IOSTAT_MAX_LABELS 15 /* Max number of labels on one line */
4147 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
4149 [IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
4150 {NULL}},
4151 [IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4152 {"asyncq_wait", 2}, {"scrub", 1}, {"trim", 1}, {"rebuild", 1},
4153 {NULL}},
4154 [IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
4155 {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
4156 {"trimq_write", 2}, {"rebuildq_write", 2}, {NULL}},
4157 [IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4158 {"asyncq_wait", 2}, {NULL}},
4159 [IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
4160 {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
4161 {"trim", 2}, {"rebuild", 2}, {NULL}},
4164 /* Shorthand - if "columns" field not set, default to 1 column */
4165 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
4167 [IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
4168 {"write"}, {NULL}},
4169 [IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4170 {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {"wait"},
4171 {NULL}},
4172 [IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
4173 {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
4174 {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
4175 [IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4176 {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {"rebuild"},
4177 {NULL}},
4178 [IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4179 {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4180 {"ind"}, {"agg"}, {NULL}},
4183 static const char *histo_to_title[] = {
4184 [IOS_L_HISTO] = "latency",
4185 [IOS_RQ_HISTO] = "req_size",
4189 * Return the number of labels in a null-terminated name_and_columns_t
4190 * array.
4193 static unsigned int
4194 label_array_len(const name_and_columns_t *labels)
4196 int i = 0;
4198 while (labels[i].name)
4199 i++;
4201 return (i);
4205 * Return the number of strings in a null-terminated string array.
4206 * For example:
4208 * const char foo[] = {"bar", "baz", NULL}
4210 * returns 2
4212 static uint64_t
4213 str_array_len(const char *array[])
4215 uint64_t i = 0;
4216 while (array[i])
4217 i++;
4219 return (i);
4224 * Return a default column width for default/latency/queue columns. This does
4225 * not include histograms, which have their columns autosized.
4227 static unsigned int
4228 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
4230 unsigned long column_width = 5; /* Normal niceprint */
4231 static unsigned long widths[] = {
4233 * Choose some sane default column sizes for printing the
4234 * raw numbers.
4236 [IOS_DEFAULT] = 15, /* 1PB capacity */
4237 [IOS_LATENCY] = 10, /* 1B ns = 10sec */
4238 [IOS_QUEUES] = 6, /* 1M queue entries */
4239 [IOS_L_HISTO] = 10, /* 1B ns = 10sec */
4240 [IOS_RQ_HISTO] = 6, /* 1M queue entries */
4243 if (cb->cb_literal)
4244 column_width = widths[type];
4246 return (column_width);
4250 * Print the column labels, i.e:
4252 * capacity operations bandwidth
4253 * alloc free read write read write ...
4255 * If force_column_width is set, use it for the column width. If not set, use
4256 * the default column width.
4258 static void
4259 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
4260 const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
4262 int i, idx, s;
4263 int text_start, rw_column_width, spaces_to_end;
4264 uint64_t flags = cb->cb_flags;
4265 uint64_t f;
4266 unsigned int column_width = force_column_width;
4268 /* For each bit set in flags */
4269 for (f = flags; f; f &= ~(1ULL << idx)) {
4270 idx = lowbit64(f) - 1;
4271 if (!force_column_width)
4272 column_width = default_column_width(cb, idx);
4273 /* Print our top labels centered over "read write" label. */
4274 for (i = 0; i < label_array_len(labels[idx]); i++) {
4275 const char *name = labels[idx][i].name;
4277 * We treat labels[][].columns == 0 as shorthand
4278 * for one column. It makes writing out the label
4279 * tables more concise.
4281 unsigned int columns = MAX(1, labels[idx][i].columns);
4282 unsigned int slen = strlen(name);
4284 rw_column_width = (column_width * columns) +
4285 (2 * (columns - 1));
4287 text_start = (int)((rw_column_width) / columns -
4288 slen / columns);
4289 if (text_start < 0)
4290 text_start = 0;
4292 printf(" "); /* Two spaces between columns */
4294 /* Space from beginning of column to label */
4295 for (s = 0; s < text_start; s++)
4296 printf(" ");
4298 printf("%s", name);
4300 /* Print space after label to end of column */
4301 spaces_to_end = rw_column_width - text_start - slen;
4302 if (spaces_to_end < 0)
4303 spaces_to_end = 0;
4305 for (s = 0; s < spaces_to_end; s++)
4306 printf(" ");
4313 * print_cmd_columns - Print custom column titles from -c
4315 * If the user specified the "zpool status|iostat -c" then print their custom
4316 * column titles in the header. For example, print_cmd_columns() would print
4317 * the " col1 col2" part of this:
4319 * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
4320 * ...
4321 * capacity operations bandwidth
4322 * pool alloc free read write read write col1 col2
4323 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4324 * mypool 269K 1008M 0 0 107 946
4325 * mirror 269K 1008M 0 0 107 946
4326 * sdb - - 0 0 102 473 val1 val2
4327 * sdc - - 0 0 5 473 val1 val2
4328 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4330 static void
4331 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
4333 int i, j;
4334 vdev_cmd_data_t *data = &vcdl->data[0];
4336 if (vcdl->count == 0 || data == NULL)
4337 return;
4340 * Each vdev cmd should have the same column names unless the user did
4341 * something weird with their cmd. Just take the column names from the
4342 * first vdev and assume it works for all of them.
4344 for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
4345 printf(" ");
4346 if (use_dashes) {
4347 for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
4348 printf("-");
4349 } else {
4350 printf_color(ANSI_BOLD, "%*s", vcdl->uniq_cols_width[i],
4351 vcdl->uniq_cols[i]);
4358 * Utility function to print out a line of dashes like:
4360 * -------------------------------- ----- ----- ----- ----- -----
4362 * ...or a dashed named-row line like:
4364 * logs - - - - -
4366 * @cb: iostat data
4368 * @force_column_width If non-zero, use the value as the column width.
4369 * Otherwise use the default column widths.
4371 * @name: Print a dashed named-row line starting
4372 * with @name. Otherwise, print a regular
4373 * dashed line.
4375 static void
4376 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
4377 const char *name)
4379 int i;
4380 unsigned int namewidth;
4381 uint64_t flags = cb->cb_flags;
4382 uint64_t f;
4383 int idx;
4384 const name_and_columns_t *labels;
4385 const char *title;
4388 if (cb->cb_flags & IOS_ANYHISTO_M) {
4389 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4390 } else if (cb->cb_vdevs.cb_names_count) {
4391 title = "vdev";
4392 } else {
4393 title = "pool";
4396 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4397 name ? strlen(name) : 0);
4400 if (name) {
4401 printf("%-*s", namewidth, name);
4402 } else {
4403 for (i = 0; i < namewidth; i++)
4404 (void) printf("-");
4407 /* For each bit in flags */
4408 for (f = flags; f; f &= ~(1ULL << idx)) {
4409 unsigned int column_width;
4410 idx = lowbit64(f) - 1;
4411 if (force_column_width)
4412 column_width = force_column_width;
4413 else
4414 column_width = default_column_width(cb, idx);
4416 labels = iostat_bottom_labels[idx];
4417 for (i = 0; i < label_array_len(labels); i++) {
4418 if (name)
4419 printf(" %*s-", column_width - 1, " ");
4420 else
4421 printf(" %.*s", column_width,
4422 "--------------------");
4428 static void
4429 print_iostat_separator_impl(iostat_cbdata_t *cb,
4430 unsigned int force_column_width)
4432 print_iostat_dashes(cb, force_column_width, NULL);
4435 static void
4436 print_iostat_separator(iostat_cbdata_t *cb)
4438 print_iostat_separator_impl(cb, 0);
4441 static void
4442 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
4443 const char *histo_vdev_name)
4445 unsigned int namewidth;
4446 const char *title;
4448 color_start(ANSI_BOLD);
4450 if (cb->cb_flags & IOS_ANYHISTO_M) {
4451 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4452 } else if (cb->cb_vdevs.cb_names_count) {
4453 title = "vdev";
4454 } else {
4455 title = "pool";
4458 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4459 histo_vdev_name ? strlen(histo_vdev_name) : 0);
4461 if (histo_vdev_name)
4462 printf("%-*s", namewidth, histo_vdev_name);
4463 else
4464 printf("%*s", namewidth, "");
4467 print_iostat_labels(cb, force_column_width, iostat_top_labels);
4468 printf("\n");
4470 printf("%-*s", namewidth, title);
4472 print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
4473 if (cb->vcdl != NULL)
4474 print_cmd_columns(cb->vcdl, 0);
4476 printf("\n");
4478 print_iostat_separator_impl(cb, force_column_width);
4480 if (cb->vcdl != NULL)
4481 print_cmd_columns(cb->vcdl, 1);
4483 color_end();
4485 printf("\n");
4488 static void
4489 print_iostat_header(iostat_cbdata_t *cb)
4491 print_iostat_header_impl(cb, 0, NULL);
4495 * Prints a size string (i.e. 120M) with the suffix ("M") colored
4496 * by order of magnitude. Uses column_size to add padding.
4498 static void
4499 print_stat_color(const char *statbuf, unsigned int column_size)
4501 fputs(" ", stdout);
4502 size_t len = strlen(statbuf);
4503 while (len < column_size) {
4504 fputc(' ', stdout);
4505 column_size--;
4507 if (*statbuf == '0') {
4508 color_start(ANSI_GRAY);
4509 fputc('0', stdout);
4510 } else {
4511 for (; *statbuf; statbuf++) {
4512 if (*statbuf == 'K') color_start(ANSI_GREEN);
4513 else if (*statbuf == 'M') color_start(ANSI_YELLOW);
4514 else if (*statbuf == 'G') color_start(ANSI_RED);
4515 else if (*statbuf == 'T') color_start(ANSI_BOLD_BLUE);
4516 else if (*statbuf == 'P') color_start(ANSI_MAGENTA);
4517 else if (*statbuf == 'E') color_start(ANSI_CYAN);
4518 fputc(*statbuf, stdout);
4519 if (--column_size <= 0)
4520 break;
4523 color_end();
4527 * Display a single statistic.
4529 static void
4530 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
4531 unsigned int column_size, boolean_t scripted)
4533 char buf[64];
4535 zfs_nicenum_format(value, buf, sizeof (buf), format);
4537 if (scripted)
4538 printf("\t%s", buf);
4539 else
4540 print_stat_color(buf, column_size);
4544 * Calculate the default vdev stats
4546 * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
4547 * stats into calcvs.
4549 static void
4550 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
4551 vdev_stat_t *calcvs)
4553 int i;
4555 memcpy(calcvs, newvs, sizeof (*calcvs));
4556 for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
4557 calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
4559 for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
4560 calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
4564 * Internal representation of the extended iostats data.
4566 * The extended iostat stats are exported in nvlists as either uint64_t arrays
4567 * or single uint64_t's. We make both look like arrays to make them easier
4568 * to process. In order to make single uint64_t's look like arrays, we set
4569 * __data to the stat data, and then set *data = &__data with count = 1. Then,
4570 * we can just use *data and count.
4572 struct stat_array {
4573 uint64_t *data;
4574 uint_t count; /* Number of entries in data[] */
4575 uint64_t __data; /* Only used when data is a single uint64_t */
4578 static uint64_t
4579 stat_histo_max(struct stat_array *nva, unsigned int len)
4581 uint64_t max = 0;
4582 int i;
4583 for (i = 0; i < len; i++)
4584 max = MAX(max, array64_max(nva[i].data, nva[i].count));
4586 return (max);
4590 * Helper function to lookup a uint64_t array or uint64_t value and store its
4591 * data as a stat_array. If the nvpair is a single uint64_t value, then we make
4592 * it look like a one element array to make it easier to process.
4594 static int
4595 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
4596 struct stat_array *nva)
4598 nvpair_t *tmp;
4599 int ret;
4601 verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
4602 switch (nvpair_type(tmp)) {
4603 case DATA_TYPE_UINT64_ARRAY:
4604 ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
4605 break;
4606 case DATA_TYPE_UINT64:
4607 ret = nvpair_value_uint64(tmp, &nva->__data);
4608 nva->data = &nva->__data;
4609 nva->count = 1;
4610 break;
4611 default:
4612 /* Not a uint64_t */
4613 ret = EINVAL;
4614 break;
4617 return (ret);
4621 * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
4622 * subtract them, and return the results in a newly allocated stat_array.
4623 * You must free the returned array after you are done with it with
4624 * free_calc_stats().
4626 * Additionally, you can set "oldnv" to NULL if you simply want the newnv
4627 * values.
4629 static struct stat_array *
4630 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
4631 nvlist_t *newnv)
4633 nvlist_t *oldnvx = NULL, *newnvx;
4634 struct stat_array *oldnva, *newnva, *calcnva;
4635 int i, j;
4636 unsigned int alloc_size = (sizeof (struct stat_array)) * len;
4638 /* Extract our extended stats nvlist from the main list */
4639 verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
4640 &newnvx) == 0);
4641 if (oldnv) {
4642 verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
4643 &oldnvx) == 0);
4646 newnva = safe_malloc(alloc_size);
4647 oldnva = safe_malloc(alloc_size);
4648 calcnva = safe_malloc(alloc_size);
4650 for (j = 0; j < len; j++) {
4651 verify(nvpair64_to_stat_array(newnvx, names[j],
4652 &newnva[j]) == 0);
4653 calcnva[j].count = newnva[j].count;
4654 alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
4655 calcnva[j].data = safe_malloc(alloc_size);
4656 memcpy(calcnva[j].data, newnva[j].data, alloc_size);
4658 if (oldnvx) {
4659 verify(nvpair64_to_stat_array(oldnvx, names[j],
4660 &oldnva[j]) == 0);
4661 for (i = 0; i < oldnva[j].count; i++)
4662 calcnva[j].data[i] -= oldnva[j].data[i];
4665 free(newnva);
4666 free(oldnva);
4667 return (calcnva);
4670 static void
4671 free_calc_stats(struct stat_array *nva, unsigned int len)
4673 int i;
4674 for (i = 0; i < len; i++)
4675 free(nva[i].data);
4677 free(nva);
4680 static void
4681 print_iostat_histo(struct stat_array *nva, unsigned int len,
4682 iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
4683 double scale)
4685 int i, j;
4686 char buf[6];
4687 uint64_t val;
4688 enum zfs_nicenum_format format;
4689 unsigned int buckets;
4690 unsigned int start_bucket;
4692 if (cb->cb_literal)
4693 format = ZFS_NICENUM_RAW;
4694 else
4695 format = ZFS_NICENUM_1024;
4697 /* All these histos are the same size, so just use nva[0].count */
4698 buckets = nva[0].count;
4700 if (cb->cb_flags & IOS_RQ_HISTO_M) {
4701 /* Start at 512 - req size should never be lower than this */
4702 start_bucket = 9;
4703 } else {
4704 start_bucket = 0;
4707 for (j = start_bucket; j < buckets; j++) {
4708 /* Print histogram bucket label */
4709 if (cb->cb_flags & IOS_L_HISTO_M) {
4710 /* Ending range of this bucket */
4711 val = (1UL << (j + 1)) - 1;
4712 zfs_nicetime(val, buf, sizeof (buf));
4713 } else {
4714 /* Request size (starting range of bucket) */
4715 val = (1UL << j);
4716 zfs_nicenum(val, buf, sizeof (buf));
4719 if (cb->cb_scripted)
4720 printf("%llu", (u_longlong_t)val);
4721 else
4722 printf("%-*s", namewidth, buf);
4724 /* Print the values on the line */
4725 for (i = 0; i < len; i++) {
4726 print_one_stat(nva[i].data[j] * scale, format,
4727 column_width, cb->cb_scripted);
4729 printf("\n");
4733 static void
4734 print_solid_separator(unsigned int length)
4736 while (length--)
4737 printf("-");
4738 printf("\n");
4741 static void
4742 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
4743 nvlist_t *newnv, double scale, const char *name)
4745 unsigned int column_width;
4746 unsigned int namewidth;
4747 unsigned int entire_width;
4748 enum iostat_type type;
4749 struct stat_array *nva;
4750 const char **names;
4751 unsigned int names_len;
4753 /* What type of histo are we? */
4754 type = IOS_HISTO_IDX(cb->cb_flags);
4756 /* Get NULL-terminated array of nvlist names for our histo */
4757 names = vsx_type_to_nvlist[type];
4758 names_len = str_array_len(names); /* num of names */
4760 nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
4762 if (cb->cb_literal) {
4763 column_width = MAX(5,
4764 (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
4765 } else {
4766 column_width = 5;
4769 namewidth = MAX(cb->cb_namewidth,
4770 strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
4773 * Calculate the entire line width of what we're printing. The
4774 * +2 is for the two spaces between columns:
4776 /* read write */
4777 /* ----- ----- */
4778 /* |___| <---------- column_width */
4779 /* */
4780 /* |__________| <--- entire_width */
4781 /* */
4782 entire_width = namewidth + (column_width + 2) *
4783 label_array_len(iostat_bottom_labels[type]);
4785 if (cb->cb_scripted)
4786 printf("%s\n", name);
4787 else
4788 print_iostat_header_impl(cb, column_width, name);
4790 print_iostat_histo(nva, names_len, cb, column_width,
4791 namewidth, scale);
4793 free_calc_stats(nva, names_len);
4794 if (!cb->cb_scripted)
4795 print_solid_separator(entire_width);
4799 * Calculate the average latency of a power-of-two latency histogram
4801 static uint64_t
4802 single_histo_average(uint64_t *histo, unsigned int buckets)
4804 int i;
4805 uint64_t count = 0, total = 0;
4807 for (i = 0; i < buckets; i++) {
4809 * Our buckets are power-of-two latency ranges. Use the
4810 * midpoint latency of each bucket to calculate the average.
4811 * For example:
4813 * Bucket Midpoint
4814 * 8ns-15ns: 12ns
4815 * 16ns-31ns: 24ns
4816 * ...
4818 if (histo[i] != 0) {
4819 total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
4820 count += histo[i];
4824 /* Prevent divide by zero */
4825 return (count == 0 ? 0 : total / count);
4828 static void
4829 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *newnv)
4831 const char *names[] = {
4832 ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
4833 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
4834 ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
4835 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
4836 ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
4837 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
4838 ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
4839 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
4840 ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
4841 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
4842 ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
4843 ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
4844 ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
4845 ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
4848 struct stat_array *nva;
4850 unsigned int column_width = default_column_width(cb, IOS_QUEUES);
4851 enum zfs_nicenum_format format;
4853 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
4855 if (cb->cb_literal)
4856 format = ZFS_NICENUM_RAW;
4857 else
4858 format = ZFS_NICENUM_1024;
4860 for (int i = 0; i < ARRAY_SIZE(names); i++) {
4861 uint64_t val = nva[i].data[0];
4862 print_one_stat(val, format, column_width, cb->cb_scripted);
4865 free_calc_stats(nva, ARRAY_SIZE(names));
4868 static void
4869 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
4870 nvlist_t *newnv)
4872 int i;
4873 uint64_t val;
4874 const char *names[] = {
4875 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
4876 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
4877 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
4878 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
4879 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
4880 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
4881 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
4882 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
4883 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
4884 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
4885 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
4887 struct stat_array *nva;
4889 unsigned int column_width = default_column_width(cb, IOS_LATENCY);
4890 enum zfs_nicenum_format format;
4892 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
4894 if (cb->cb_literal)
4895 format = ZFS_NICENUM_RAWTIME;
4896 else
4897 format = ZFS_NICENUM_TIME;
4899 /* Print our avg latencies on the line */
4900 for (i = 0; i < ARRAY_SIZE(names); i++) {
4901 /* Compute average latency for a latency histo */
4902 val = single_histo_average(nva[i].data, nva[i].count);
4903 print_one_stat(val, format, column_width, cb->cb_scripted);
4905 free_calc_stats(nva, ARRAY_SIZE(names));
4909 * Print default statistics (capacity/operations/bandwidth)
4911 static void
4912 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
4914 unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
4915 enum zfs_nicenum_format format;
4916 char na; /* char to print for "not applicable" values */
4918 if (cb->cb_literal) {
4919 format = ZFS_NICENUM_RAW;
4920 na = '0';
4921 } else {
4922 format = ZFS_NICENUM_1024;
4923 na = '-';
4926 /* only toplevel vdevs have capacity stats */
4927 if (vs->vs_space == 0) {
4928 if (cb->cb_scripted)
4929 printf("\t%c\t%c", na, na);
4930 else
4931 printf(" %*c %*c", column_width, na, column_width,
4932 na);
4933 } else {
4934 print_one_stat(vs->vs_alloc, format, column_width,
4935 cb->cb_scripted);
4936 print_one_stat(vs->vs_space - vs->vs_alloc, format,
4937 column_width, cb->cb_scripted);
4940 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
4941 format, column_width, cb->cb_scripted);
4942 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
4943 format, column_width, cb->cb_scripted);
4944 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
4945 format, column_width, cb->cb_scripted);
4946 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
4947 format, column_width, cb->cb_scripted);
4950 static const char *const class_name[] = {
4951 VDEV_ALLOC_BIAS_DEDUP,
4952 VDEV_ALLOC_BIAS_SPECIAL,
4953 VDEV_ALLOC_CLASS_LOGS
4957 * Print out all the statistics for the given vdev. This can either be the
4958 * toplevel configuration, or called recursively. If 'name' is NULL, then this
4959 * is a verbose output, and we don't want to display the toplevel pool stats.
4961 * Returns the number of stat lines printed.
4963 static unsigned int
4964 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
4965 nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
4967 nvlist_t **oldchild, **newchild;
4968 uint_t c, children, oldchildren;
4969 vdev_stat_t *oldvs, *newvs, *calcvs;
4970 vdev_stat_t zerovs = { 0 };
4971 char *vname;
4972 int i;
4973 int ret = 0;
4974 uint64_t tdelta;
4975 double scale;
4977 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
4978 return (ret);
4980 calcvs = safe_malloc(sizeof (*calcvs));
4982 if (oldnv != NULL) {
4983 verify(nvlist_lookup_uint64_array(oldnv,
4984 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
4985 } else {
4986 oldvs = &zerovs;
4989 /* Do we only want to see a specific vdev? */
4990 for (i = 0; i < cb->cb_vdevs.cb_names_count; i++) {
4991 /* Yes we do. Is this the vdev? */
4992 if (strcmp(name, cb->cb_vdevs.cb_names[i]) == 0) {
4994 * This is our vdev. Since it is the only vdev we
4995 * will be displaying, make depth = 0 so that it
4996 * doesn't get indented.
4998 depth = 0;
4999 break;
5003 if (cb->cb_vdevs.cb_names_count && (i == cb->cb_vdevs.cb_names_count)) {
5004 /* Couldn't match the name */
5005 goto children;
5009 verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
5010 (uint64_t **)&newvs, &c) == 0);
5013 * Print the vdev name unless it's is a histogram. Histograms
5014 * display the vdev name in the header itself.
5016 if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
5017 if (cb->cb_scripted) {
5018 printf("%s", name);
5019 } else {
5020 if (strlen(name) + depth > cb->cb_namewidth)
5021 (void) printf("%*s%s", depth, "", name);
5022 else
5023 (void) printf("%*s%s%*s", depth, "", name,
5024 (int)(cb->cb_namewidth - strlen(name) -
5025 depth), "");
5029 /* Calculate our scaling factor */
5030 tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
5031 if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
5033 * If we specify printing histograms with no time interval, then
5034 * print the histogram numbers over the entire lifetime of the
5035 * vdev.
5037 scale = 1;
5038 } else {
5039 if (tdelta == 0)
5040 scale = 1.0;
5041 else
5042 scale = (double)NANOSEC / tdelta;
5045 if (cb->cb_flags & IOS_DEFAULT_M) {
5046 calc_default_iostats(oldvs, newvs, calcvs);
5047 print_iostat_default(calcvs, cb, scale);
5049 if (cb->cb_flags & IOS_LATENCY_M)
5050 print_iostat_latency(cb, oldnv, newnv);
5051 if (cb->cb_flags & IOS_QUEUES_M)
5052 print_iostat_queues(cb, newnv);
5053 if (cb->cb_flags & IOS_ANYHISTO_M) {
5054 printf("\n");
5055 print_iostat_histos(cb, oldnv, newnv, scale, name);
5058 if (cb->vcdl != NULL) {
5059 const char *path;
5060 if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
5061 &path) == 0) {
5062 printf(" ");
5063 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
5067 if (!(cb->cb_flags & IOS_ANYHISTO_M))
5068 printf("\n");
5070 ret++;
5072 children:
5074 free(calcvs);
5076 if (!cb->cb_verbose)
5077 return (ret);
5079 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
5080 &newchild, &children) != 0)
5081 return (ret);
5083 if (oldnv) {
5084 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
5085 &oldchild, &oldchildren) != 0)
5086 return (ret);
5088 children = MIN(oldchildren, children);
5092 * print normal top-level devices
5094 for (c = 0; c < children; c++) {
5095 uint64_t ishole = B_FALSE, islog = B_FALSE;
5097 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
5098 &ishole);
5100 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
5101 &islog);
5103 if (ishole || islog)
5104 continue;
5106 if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
5107 continue;
5109 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5110 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5111 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
5112 newchild[c], cb, depth + 2);
5113 free(vname);
5117 * print all other top-level devices
5119 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
5120 boolean_t printed = B_FALSE;
5122 for (c = 0; c < children; c++) {
5123 uint64_t islog = B_FALSE;
5124 const char *bias = NULL;
5125 const char *type = NULL;
5127 (void) nvlist_lookup_uint64(newchild[c],
5128 ZPOOL_CONFIG_IS_LOG, &islog);
5129 if (islog) {
5130 bias = VDEV_ALLOC_CLASS_LOGS;
5131 } else {
5132 (void) nvlist_lookup_string(newchild[c],
5133 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
5134 (void) nvlist_lookup_string(newchild[c],
5135 ZPOOL_CONFIG_TYPE, &type);
5137 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
5138 continue;
5139 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
5140 continue;
5142 if (!printed) {
5143 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
5144 !cb->cb_scripted &&
5145 !cb->cb_vdevs.cb_names) {
5146 print_iostat_dashes(cb, 0,
5147 class_name[n]);
5149 printf("\n");
5150 printed = B_TRUE;
5153 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5154 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5155 ret += print_vdev_stats(zhp, vname, oldnv ?
5156 oldchild[c] : NULL, newchild[c], cb, depth + 2);
5157 free(vname);
5162 * Include level 2 ARC devices in iostat output
5164 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
5165 &newchild, &children) != 0)
5166 return (ret);
5168 if (oldnv) {
5169 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
5170 &oldchild, &oldchildren) != 0)
5171 return (ret);
5173 children = MIN(oldchildren, children);
5176 if (children > 0) {
5177 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
5178 !cb->cb_vdevs.cb_names) {
5179 print_iostat_dashes(cb, 0, "cache");
5181 printf("\n");
5183 for (c = 0; c < children; c++) {
5184 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5185 cb->cb_vdevs.cb_name_flags);
5186 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
5187 : NULL, newchild[c], cb, depth + 2);
5188 free(vname);
5192 return (ret);
5195 static int
5196 refresh_iostat(zpool_handle_t *zhp, void *data)
5198 iostat_cbdata_t *cb = data;
5199 boolean_t missing;
5202 * If the pool has disappeared, remove it from the list and continue.
5204 if (zpool_refresh_stats(zhp, &missing) != 0)
5205 return (-1);
5207 if (missing)
5208 pool_list_remove(cb->cb_list, zhp);
5210 return (0);
5214 * Callback to print out the iostats for the given pool.
5216 static int
5217 print_iostat(zpool_handle_t *zhp, void *data)
5219 iostat_cbdata_t *cb = data;
5220 nvlist_t *oldconfig, *newconfig;
5221 nvlist_t *oldnvroot, *newnvroot;
5222 int ret;
5224 newconfig = zpool_get_config(zhp, &oldconfig);
5226 if (cb->cb_iteration == 1)
5227 oldconfig = NULL;
5229 verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
5230 &newnvroot) == 0);
5232 if (oldconfig == NULL)
5233 oldnvroot = NULL;
5234 else
5235 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
5236 &oldnvroot) == 0);
5238 ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
5239 cb, 0);
5240 if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
5241 !cb->cb_scripted && cb->cb_verbose &&
5242 !cb->cb_vdevs.cb_names_count) {
5243 print_iostat_separator(cb);
5244 if (cb->vcdl != NULL) {
5245 print_cmd_columns(cb->vcdl, 1);
5247 printf("\n");
5250 return (ret);
5253 static int
5254 get_columns(void)
5256 struct winsize ws;
5257 int columns = 80;
5258 int error;
5260 if (isatty(STDOUT_FILENO)) {
5261 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
5262 if (error == 0)
5263 columns = ws.ws_col;
5264 } else {
5265 columns = 999;
5268 return (columns);
5272 * Return the required length of the pool/vdev name column. The minimum
5273 * allowed width and output formatting flags must be provided.
5275 static int
5276 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
5278 nvlist_t *config, *nvroot;
5279 int width = min_width;
5281 if ((config = zpool_get_config(zhp, NULL)) != NULL) {
5282 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5283 &nvroot) == 0);
5284 size_t poolname_len = strlen(zpool_get_name(zhp));
5285 if (verbose == B_FALSE) {
5286 width = MAX(poolname_len, min_width);
5287 } else {
5288 width = MAX(poolname_len,
5289 max_width(zhp, nvroot, 0, min_width, flags));
5293 return (width);
5297 * Parse the input string, get the 'interval' and 'count' value if there is one.
5299 static void
5300 get_interval_count(int *argcp, char **argv, float *iv,
5301 unsigned long *cnt)
5303 float interval = 0;
5304 unsigned long count = 0;
5305 int argc = *argcp;
5308 * Determine if the last argument is an integer or a pool name
5310 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5311 char *end;
5313 errno = 0;
5314 interval = strtof(argv[argc - 1], &end);
5316 if (*end == '\0' && errno == 0) {
5317 if (interval == 0) {
5318 (void) fprintf(stderr, gettext(
5319 "interval cannot be zero\n"));
5320 usage(B_FALSE);
5323 * Ignore the last parameter
5325 argc--;
5326 } else {
5328 * If this is not a valid number, just plow on. The
5329 * user will get a more informative error message later
5330 * on.
5332 interval = 0;
5337 * If the last argument is also an integer, then we have both a count
5338 * and an interval.
5340 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5341 char *end;
5343 errno = 0;
5344 count = interval;
5345 interval = strtof(argv[argc - 1], &end);
5347 if (*end == '\0' && errno == 0) {
5348 if (interval == 0) {
5349 (void) fprintf(stderr, gettext(
5350 "interval cannot be zero\n"));
5351 usage(B_FALSE);
5355 * Ignore the last parameter
5357 argc--;
5358 } else {
5359 interval = 0;
5363 *iv = interval;
5364 *cnt = count;
5365 *argcp = argc;
5368 static void
5369 get_timestamp_arg(char c)
5371 if (c == 'u')
5372 timestamp_fmt = UDATE;
5373 else if (c == 'd')
5374 timestamp_fmt = DDATE;
5375 else
5376 usage(B_FALSE);
5380 * Return stat flags that are supported by all pools by both the module and
5381 * zpool iostat. "*data" should be initialized to all 0xFFs before running.
5382 * It will get ANDed down until only the flags that are supported on all pools
5383 * remain.
5385 static int
5386 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
5388 uint64_t *mask = data;
5389 nvlist_t *config, *nvroot, *nvx;
5390 uint64_t flags = 0;
5391 int i, j;
5393 config = zpool_get_config(zhp, NULL);
5394 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5395 &nvroot) == 0);
5397 /* Default stats are always supported, but for completeness.. */
5398 if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
5399 flags |= IOS_DEFAULT_M;
5401 /* Get our extended stats nvlist from the main list */
5402 if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
5403 &nvx) != 0) {
5405 * No extended stats; they're probably running an older
5406 * module. No big deal, we support that too.
5408 goto end;
5411 /* For each extended stat, make sure all its nvpairs are supported */
5412 for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
5413 if (!vsx_type_to_nvlist[j][0])
5414 continue;
5416 /* Start off by assuming the flag is supported, then check */
5417 flags |= (1ULL << j);
5418 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
5419 if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
5420 /* flag isn't supported */
5421 flags = flags & ~(1ULL << j);
5422 break;
5426 end:
5427 *mask = *mask & flags;
5428 return (0);
5432 * Return a bitmask of stats that are supported on all pools by both the module
5433 * and zpool iostat.
5435 static uint64_t
5436 get_stat_flags(zpool_list_t *list)
5438 uint64_t mask = -1;
5441 * get_stat_flags_cb() will lop off bits from "mask" until only the
5442 * flags that are supported on all pools remain.
5444 pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
5445 return (mask);
5449 * Return 1 if cb_data->cb_names[0] is this vdev's name, 0 otherwise.
5451 static int
5452 is_vdev_cb(void *zhp_data, nvlist_t *nv, void *cb_data)
5454 uint64_t guid;
5455 vdev_cbdata_t *cb = cb_data;
5456 zpool_handle_t *zhp = zhp_data;
5458 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
5459 return (0);
5461 return (guid == zpool_vdev_path_to_guid(zhp, cb->cb_names[0]));
5465 * Returns 1 if cb_data->cb_names[0] is a vdev name, 0 otherwise.
5467 static int
5468 is_vdev(zpool_handle_t *zhp, void *cb_data)
5470 return (for_each_vdev(zhp, is_vdev_cb, cb_data));
5474 * Check if vdevs are in a pool
5476 * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
5477 * return 0. If pool_name is NULL, then search all pools.
5479 static int
5480 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
5481 vdev_cbdata_t *cb)
5483 char **tmp_name;
5484 int ret = 0;
5485 int i;
5486 int pool_count = 0;
5488 if ((argc == 0) || !*argv)
5489 return (0);
5491 if (pool_name)
5492 pool_count = 1;
5494 /* Temporarily hijack cb_names for a second... */
5495 tmp_name = cb->cb_names;
5497 /* Go though our list of prospective vdev names */
5498 for (i = 0; i < argc; i++) {
5499 cb->cb_names = argv + i;
5501 /* Is this name a vdev in our pools? */
5502 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
5503 ZFS_TYPE_POOL, B_FALSE, is_vdev, cb);
5504 if (!ret) {
5505 /* No match */
5506 break;
5510 cb->cb_names = tmp_name;
5512 return (ret);
5515 static int
5516 is_pool_cb(zpool_handle_t *zhp, void *data)
5518 char *name = data;
5519 if (strcmp(name, zpool_get_name(zhp)) == 0)
5520 return (1);
5522 return (0);
5526 * Do we have a pool named *name? If so, return 1, otherwise 0.
5528 static int
5529 is_pool(char *name)
5531 return (for_each_pool(0, NULL, B_TRUE, NULL, ZFS_TYPE_POOL, B_FALSE,
5532 is_pool_cb, name));
5535 /* Are all our argv[] strings pool names? If so return 1, 0 otherwise. */
5536 static int
5537 are_all_pools(int argc, char **argv)
5539 if ((argc == 0) || !*argv)
5540 return (0);
5542 while (--argc >= 0)
5543 if (!is_pool(argv[argc]))
5544 return (0);
5546 return (1);
5550 * Helper function to print out vdev/pool names we can't resolve. Used for an
5551 * error message.
5553 static void
5554 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
5555 vdev_cbdata_t *cb)
5557 int i;
5558 char *name;
5559 char *str;
5560 for (i = 0; i < argc; i++) {
5561 name = argv[i];
5563 if (is_pool(name))
5564 str = gettext("pool");
5565 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
5566 str = gettext("vdev in this pool");
5567 else if (are_vdevs_in_pool(1, &name, NULL, cb))
5568 str = gettext("vdev in another pool");
5569 else
5570 str = gettext("unknown");
5572 fprintf(stderr, "\t%s (%s)\n", name, str);
5577 * Same as get_interval_count(), but with additional checks to not misinterpret
5578 * guids as interval/count values. Assumes VDEV_NAME_GUID is set in
5579 * cb.cb_vdevs.cb_name_flags.
5581 static void
5582 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
5583 unsigned long *count, iostat_cbdata_t *cb)
5585 char **tmpargv = argv;
5586 int argc_for_interval = 0;
5588 /* Is the last arg an interval value? Or a guid? */
5589 if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL,
5590 &cb->cb_vdevs)) {
5592 * The last arg is not a guid, so it's probably an
5593 * interval value.
5595 argc_for_interval++;
5597 if (*argc >= 2 &&
5598 !are_vdevs_in_pool(1, &argv[*argc - 2], NULL,
5599 &cb->cb_vdevs)) {
5601 * The 2nd to last arg is not a guid, so it's probably
5602 * an interval value.
5604 argc_for_interval++;
5608 /* Point to our list of possible intervals */
5609 tmpargv = &argv[*argc - argc_for_interval];
5611 *argc = *argc - argc_for_interval;
5612 get_interval_count(&argc_for_interval, tmpargv,
5613 interval, count);
5617 * Terminal height, in rows. Returns -1 if stdout is not connected to a TTY or
5618 * if we were unable to determine its size.
5620 static int
5621 terminal_height(void)
5623 struct winsize win;
5625 if (isatty(STDOUT_FILENO) == 0)
5626 return (-1);
5628 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_row > 0)
5629 return (win.ws_row);
5631 return (-1);
5635 * Run one of the zpool status/iostat -c scripts with the help (-h) option and
5636 * print the result.
5638 * name: Short name of the script ('iostat').
5639 * path: Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
5641 static void
5642 print_zpool_script_help(char *name, char *path)
5644 char *argv[] = {path, (char *)"-h", NULL};
5645 char **lines = NULL;
5646 int lines_cnt = 0;
5647 int rc;
5649 rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
5650 &lines_cnt);
5651 if (rc != 0 || lines == NULL || lines_cnt <= 0) {
5652 if (lines != NULL)
5653 libzfs_free_str_array(lines, lines_cnt);
5654 return;
5657 for (int i = 0; i < lines_cnt; i++)
5658 if (!is_blank_str(lines[i]))
5659 printf(" %-14s %s\n", name, lines[i]);
5661 libzfs_free_str_array(lines, lines_cnt);
5665 * Go though the zpool status/iostat -c scripts in the user's path, run their
5666 * help option (-h), and print out the results.
5668 static void
5669 print_zpool_dir_scripts(char *dirpath)
5671 DIR *dir;
5672 struct dirent *ent;
5673 char fullpath[MAXPATHLEN];
5674 struct stat dir_stat;
5676 if ((dir = opendir(dirpath)) != NULL) {
5677 /* print all the files and directories within directory */
5678 while ((ent = readdir(dir)) != NULL) {
5679 if (snprintf(fullpath, sizeof (fullpath), "%s/%s",
5680 dirpath, ent->d_name) >= sizeof (fullpath)) {
5681 (void) fprintf(stderr,
5682 gettext("internal error: "
5683 "ZPOOL_SCRIPTS_PATH too large.\n"));
5684 exit(1);
5687 /* Print the scripts */
5688 if (stat(fullpath, &dir_stat) == 0)
5689 if (dir_stat.st_mode & S_IXUSR &&
5690 S_ISREG(dir_stat.st_mode))
5691 print_zpool_script_help(ent->d_name,
5692 fullpath);
5694 closedir(dir);
5699 * Print out help text for all zpool status/iostat -c scripts.
5701 static void
5702 print_zpool_script_list(const char *subcommand)
5704 char *dir, *sp, *tmp;
5706 printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
5708 sp = zpool_get_cmd_search_path();
5709 if (sp == NULL)
5710 return;
5712 for (dir = strtok_r(sp, ":", &tmp);
5713 dir != NULL;
5714 dir = strtok_r(NULL, ":", &tmp))
5715 print_zpool_dir_scripts(dir);
5717 free(sp);
5721 * Set the minimum pool/vdev name column width. The width must be at least 10,
5722 * but may be as large as the column width - 42 so it still fits on one line.
5723 * NOTE: 42 is the width of the default capacity/operations/bandwidth output
5725 static int
5726 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
5728 iostat_cbdata_t *cb = data;
5729 int width, available_width;
5732 * get_namewidth() returns the maximum width of any name in that column
5733 * for any pool/vdev/device line that will be output.
5735 width = get_namewidth(zhp, cb->cb_namewidth,
5736 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
5739 * The width we are calculating is the width of the header and also the
5740 * padding width for names that are less than maximum width. The stats
5741 * take up 42 characters, so the width available for names is:
5743 available_width = get_columns() - 42;
5746 * If the maximum width fits on a screen, then great! Make everything
5747 * line up by justifying all lines to the same width. If that max
5748 * width is larger than what's available, the name plus stats won't fit
5749 * on one line, and justifying to that width would cause every line to
5750 * wrap on the screen. We only want lines with long names to wrap.
5751 * Limit the padding to what won't wrap.
5753 if (width > available_width)
5754 width = available_width;
5757 * And regardless of whatever the screen width is (get_columns can
5758 * return 0 if the width is not known or less than 42 for a narrow
5759 * terminal) have the width be a minimum of 10.
5761 if (width < 10)
5762 width = 10;
5764 /* Save the calculated width */
5765 cb->cb_namewidth = width;
5767 return (0);
5771 * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
5772 * [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
5773 * [interval [count]]
5775 * -c CMD For each vdev, run command CMD
5776 * -g Display guid for individual vdev name.
5777 * -L Follow links when resolving vdev path name.
5778 * -P Display full path for vdev name.
5779 * -v Display statistics for individual vdevs
5780 * -h Display help
5781 * -p Display values in parsable (exact) format.
5782 * -H Scripted mode. Don't display headers, and separate properties
5783 * by a single tab.
5784 * -l Display average latency
5785 * -q Display queue depths
5786 * -w Display latency histograms
5787 * -r Display request size histogram
5788 * -T Display a timestamp in date(1) or Unix format
5789 * -n Only print headers once
5791 * This command can be tricky because we want to be able to deal with pool
5792 * creation/destruction as well as vdev configuration changes. The bulk of this
5793 * processing is handled by the pool_list_* routines in zpool_iter.c. We rely
5794 * on pool_list_update() to detect the addition of new pools. Configuration
5795 * changes are all handled within libzfs.
5798 zpool_do_iostat(int argc, char **argv)
5800 int c;
5801 int ret;
5802 int npools;
5803 float interval = 0;
5804 unsigned long count = 0;
5805 int winheight = 24;
5806 zpool_list_t *list;
5807 boolean_t verbose = B_FALSE;
5808 boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
5809 boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
5810 boolean_t omit_since_boot = B_FALSE;
5811 boolean_t guid = B_FALSE;
5812 boolean_t follow_links = B_FALSE;
5813 boolean_t full_name = B_FALSE;
5814 boolean_t headers_once = B_FALSE;
5815 iostat_cbdata_t cb = { 0 };
5816 char *cmd = NULL;
5818 /* Used for printing error message */
5819 const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
5820 [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
5822 uint64_t unsupported_flags;
5824 /* check options */
5825 while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwnH")) != -1) {
5826 switch (c) {
5827 case 'c':
5828 if (cmd != NULL) {
5829 fprintf(stderr,
5830 gettext("Can't set -c flag twice\n"));
5831 exit(1);
5834 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
5835 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
5836 fprintf(stderr, gettext(
5837 "Can't run -c, disabled by "
5838 "ZPOOL_SCRIPTS_ENABLED.\n"));
5839 exit(1);
5842 if ((getuid() <= 0 || geteuid() <= 0) &&
5843 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
5844 fprintf(stderr, gettext(
5845 "Can't run -c with root privileges "
5846 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
5847 exit(1);
5849 cmd = optarg;
5850 verbose = B_TRUE;
5851 break;
5852 case 'g':
5853 guid = B_TRUE;
5854 break;
5855 case 'L':
5856 follow_links = B_TRUE;
5857 break;
5858 case 'P':
5859 full_name = B_TRUE;
5860 break;
5861 case 'T':
5862 get_timestamp_arg(*optarg);
5863 break;
5864 case 'v':
5865 verbose = B_TRUE;
5866 break;
5867 case 'p':
5868 parsable = B_TRUE;
5869 break;
5870 case 'l':
5871 latency = B_TRUE;
5872 break;
5873 case 'q':
5874 queues = B_TRUE;
5875 break;
5876 case 'H':
5877 scripted = B_TRUE;
5878 break;
5879 case 'w':
5880 l_histo = B_TRUE;
5881 break;
5882 case 'r':
5883 rq_histo = B_TRUE;
5884 break;
5885 case 'y':
5886 omit_since_boot = B_TRUE;
5887 break;
5888 case 'n':
5889 headers_once = B_TRUE;
5890 break;
5891 case 'h':
5892 usage(B_FALSE);
5893 break;
5894 case '?':
5895 if (optopt == 'c') {
5896 print_zpool_script_list("iostat");
5897 exit(0);
5898 } else {
5899 fprintf(stderr,
5900 gettext("invalid option '%c'\n"), optopt);
5902 usage(B_FALSE);
5906 argc -= optind;
5907 argv += optind;
5909 cb.cb_literal = parsable;
5910 cb.cb_scripted = scripted;
5912 if (guid)
5913 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_GUID;
5914 if (follow_links)
5915 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
5916 if (full_name)
5917 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_PATH;
5918 cb.cb_iteration = 0;
5919 cb.cb_namewidth = 0;
5920 cb.cb_verbose = verbose;
5922 /* Get our interval and count values (if any) */
5923 if (guid) {
5924 get_interval_count_filter_guids(&argc, argv, &interval,
5925 &count, &cb);
5926 } else {
5927 get_interval_count(&argc, argv, &interval, &count);
5930 if (argc == 0) {
5931 /* No args, so just print the defaults. */
5932 } else if (are_all_pools(argc, argv)) {
5933 /* All the args are pool names */
5934 } else if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
5935 /* All the args are vdevs */
5936 cb.cb_vdevs.cb_names = argv;
5937 cb.cb_vdevs.cb_names_count = argc;
5938 argc = 0; /* No pools to process */
5939 } else if (are_all_pools(1, argv)) {
5940 /* The first arg is a pool name */
5941 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
5942 &cb.cb_vdevs)) {
5943 /* ...and the rest are vdev names */
5944 cb.cb_vdevs.cb_names = argv + 1;
5945 cb.cb_vdevs.cb_names_count = argc - 1;
5946 argc = 1; /* One pool to process */
5947 } else {
5948 fprintf(stderr, gettext("Expected either a list of "));
5949 fprintf(stderr, gettext("pools, or list of vdevs in"));
5950 fprintf(stderr, " \"%s\", ", argv[0]);
5951 fprintf(stderr, gettext("but got:\n"));
5952 error_list_unresolved_vdevs(argc - 1, argv + 1,
5953 argv[0], &cb.cb_vdevs);
5954 fprintf(stderr, "\n");
5955 usage(B_FALSE);
5956 return (1);
5958 } else {
5960 * The args don't make sense. The first arg isn't a pool name,
5961 * nor are all the args vdevs.
5963 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
5964 fprintf(stderr, "\n");
5965 return (1);
5968 if (cb.cb_vdevs.cb_names_count != 0) {
5970 * If user specified vdevs, it implies verbose.
5972 cb.cb_verbose = B_TRUE;
5976 * Construct the list of all interesting pools.
5978 ret = 0;
5979 if ((list = pool_list_get(argc, argv, NULL, ZFS_TYPE_POOL, parsable,
5980 &ret)) == NULL)
5981 return (1);
5983 if (pool_list_count(list) == 0 && argc != 0) {
5984 pool_list_free(list);
5985 return (1);
5988 if (pool_list_count(list) == 0 && interval == 0) {
5989 pool_list_free(list);
5990 (void) fprintf(stderr, gettext("no pools available\n"));
5991 return (1);
5994 if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
5995 pool_list_free(list);
5996 (void) fprintf(stderr,
5997 gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
5998 usage(B_FALSE);
5999 return (1);
6002 if (l_histo && rq_histo) {
6003 pool_list_free(list);
6004 (void) fprintf(stderr,
6005 gettext("Only one of [-r|-w] can be passed at a time\n"));
6006 usage(B_FALSE);
6007 return (1);
6011 * Enter the main iostat loop.
6013 cb.cb_list = list;
6015 if (l_histo) {
6017 * Histograms tables look out of place when you try to display
6018 * them with the other stats, so make a rule that you can only
6019 * print histograms by themselves.
6021 cb.cb_flags = IOS_L_HISTO_M;
6022 } else if (rq_histo) {
6023 cb.cb_flags = IOS_RQ_HISTO_M;
6024 } else {
6025 cb.cb_flags = IOS_DEFAULT_M;
6026 if (latency)
6027 cb.cb_flags |= IOS_LATENCY_M;
6028 if (queues)
6029 cb.cb_flags |= IOS_QUEUES_M;
6033 * See if the module supports all the stats we want to display.
6035 unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
6036 if (unsupported_flags) {
6037 uint64_t f;
6038 int idx;
6039 fprintf(stderr,
6040 gettext("The loaded zfs module doesn't support:"));
6042 /* for each bit set in unsupported_flags */
6043 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
6044 idx = lowbit64(f) - 1;
6045 fprintf(stderr, " -%c", flag_to_arg[idx]);
6048 fprintf(stderr, ". Try running a newer module.\n");
6049 pool_list_free(list);
6051 return (1);
6054 for (;;) {
6055 if ((npools = pool_list_count(list)) == 0)
6056 (void) fprintf(stderr, gettext("no pools available\n"));
6057 else {
6059 * If this is the first iteration and -y was supplied
6060 * we skip any printing.
6062 boolean_t skip = (omit_since_boot &&
6063 cb.cb_iteration == 0);
6066 * Refresh all statistics. This is done as an
6067 * explicit step before calculating the maximum name
6068 * width, so that any * configuration changes are
6069 * properly accounted for.
6071 (void) pool_list_iter(list, B_FALSE, refresh_iostat,
6072 &cb);
6075 * Iterate over all pools to determine the maximum width
6076 * for the pool / device name column across all pools.
6078 cb.cb_namewidth = 0;
6079 (void) pool_list_iter(list, B_FALSE,
6080 get_namewidth_iostat, &cb);
6082 if (timestamp_fmt != NODATE)
6083 print_timestamp(timestamp_fmt);
6085 if (cmd != NULL && cb.cb_verbose &&
6086 !(cb.cb_flags & IOS_ANYHISTO_M)) {
6087 cb.vcdl = all_pools_for_each_vdev_run(argc,
6088 argv, cmd, g_zfs, cb.cb_vdevs.cb_names,
6089 cb.cb_vdevs.cb_names_count,
6090 cb.cb_vdevs.cb_name_flags);
6091 } else {
6092 cb.vcdl = NULL;
6097 * Check terminal size so we can print headers
6098 * even when terminal window has its height
6099 * changed.
6101 winheight = terminal_height();
6103 * Are we connected to TTY? If not, headers_once
6104 * should be true, to avoid breaking scripts.
6106 if (winheight < 0)
6107 headers_once = B_TRUE;
6110 * If it's the first time and we're not skipping it,
6111 * or either skip or verbose mode, print the header.
6113 * The histogram code explicitly prints its header on
6114 * every vdev, so skip this for histograms.
6116 if (((++cb.cb_iteration == 1 && !skip) ||
6117 (skip != verbose) ||
6118 (!headers_once &&
6119 (cb.cb_iteration % winheight) == 0)) &&
6120 (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
6121 !cb.cb_scripted)
6122 print_iostat_header(&cb);
6124 if (skip) {
6125 (void) fsleep(interval);
6126 continue;
6129 pool_list_iter(list, B_FALSE, print_iostat, &cb);
6132 * If there's more than one pool, and we're not in
6133 * verbose mode (which prints a separator for us),
6134 * then print a separator.
6136 * In addition, if we're printing specific vdevs then
6137 * we also want an ending separator.
6139 if (((npools > 1 && !verbose &&
6140 !(cb.cb_flags & IOS_ANYHISTO_M)) ||
6141 (!(cb.cb_flags & IOS_ANYHISTO_M) &&
6142 cb.cb_vdevs.cb_names_count)) &&
6143 !cb.cb_scripted) {
6144 print_iostat_separator(&cb);
6145 if (cb.vcdl != NULL)
6146 print_cmd_columns(cb.vcdl, 1);
6147 printf("\n");
6150 if (cb.vcdl != NULL)
6151 free_vdev_cmd_data_list(cb.vcdl);
6156 * Flush the output so that redirection to a file isn't buffered
6157 * indefinitely.
6159 (void) fflush(stdout);
6161 if (interval == 0)
6162 break;
6164 if (count != 0 && --count == 0)
6165 break;
6167 (void) fsleep(interval);
6170 pool_list_free(list);
6172 return (ret);
6175 typedef struct list_cbdata {
6176 boolean_t cb_verbose;
6177 int cb_name_flags;
6178 int cb_namewidth;
6179 boolean_t cb_scripted;
6180 zprop_list_t *cb_proplist;
6181 boolean_t cb_literal;
6182 } list_cbdata_t;
6186 * Given a list of columns to display, output appropriate headers for each one.
6188 static void
6189 print_header(list_cbdata_t *cb)
6191 zprop_list_t *pl = cb->cb_proplist;
6192 char headerbuf[ZPOOL_MAXPROPLEN];
6193 const char *header;
6194 boolean_t first = B_TRUE;
6195 boolean_t right_justify;
6196 size_t width = 0;
6198 for (; pl != NULL; pl = pl->pl_next) {
6199 width = pl->pl_width;
6200 if (first && cb->cb_verbose) {
6202 * Reset the width to accommodate the verbose listing
6203 * of devices.
6205 width = cb->cb_namewidth;
6208 if (!first)
6209 (void) fputs(" ", stdout);
6210 else
6211 first = B_FALSE;
6213 right_justify = B_FALSE;
6214 if (pl->pl_prop != ZPROP_USERPROP) {
6215 header = zpool_prop_column_name(pl->pl_prop);
6216 right_justify = zpool_prop_align_right(pl->pl_prop);
6217 } else {
6218 int i;
6220 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
6221 headerbuf[i] = toupper(pl->pl_user_prop[i]);
6222 headerbuf[i] = '\0';
6223 header = headerbuf;
6226 if (pl->pl_next == NULL && !right_justify)
6227 (void) fputs(header, stdout);
6228 else if (right_justify)
6229 (void) printf("%*s", (int)width, header);
6230 else
6231 (void) printf("%-*s", (int)width, header);
6234 (void) fputc('\n', stdout);
6238 * Given a pool and a list of properties, print out all the properties according
6239 * to the described layout. Used by zpool_do_list().
6241 static void
6242 print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
6244 zprop_list_t *pl = cb->cb_proplist;
6245 boolean_t first = B_TRUE;
6246 char property[ZPOOL_MAXPROPLEN];
6247 const char *propstr;
6248 boolean_t right_justify;
6249 size_t width;
6251 for (; pl != NULL; pl = pl->pl_next) {
6253 width = pl->pl_width;
6254 if (first && cb->cb_verbose) {
6256 * Reset the width to accommodate the verbose listing
6257 * of devices.
6259 width = cb->cb_namewidth;
6262 if (!first) {
6263 if (cb->cb_scripted)
6264 (void) fputc('\t', stdout);
6265 else
6266 (void) fputs(" ", stdout);
6267 } else {
6268 first = B_FALSE;
6271 right_justify = B_FALSE;
6272 if (pl->pl_prop != ZPROP_USERPROP) {
6273 if (zpool_get_prop(zhp, pl->pl_prop, property,
6274 sizeof (property), NULL, cb->cb_literal) != 0)
6275 propstr = "-";
6276 else
6277 propstr = property;
6279 right_justify = zpool_prop_align_right(pl->pl_prop);
6280 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
6281 zpool_prop_unsupported(pl->pl_user_prop)) &&
6282 zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
6283 sizeof (property)) == 0) {
6284 propstr = property;
6285 } else if (zfs_prop_user(pl->pl_user_prop) &&
6286 zpool_get_userprop(zhp, pl->pl_user_prop, property,
6287 sizeof (property), NULL) == 0) {
6288 propstr = property;
6289 } else {
6290 propstr = "-";
6294 * If this is being called in scripted mode, or if this is the
6295 * last column and it is left-justified, don't include a width
6296 * format specifier.
6298 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
6299 (void) fputs(propstr, stdout);
6300 else if (right_justify)
6301 (void) printf("%*s", (int)width, propstr);
6302 else
6303 (void) printf("%-*s", (int)width, propstr);
6306 (void) fputc('\n', stdout);
6309 static void
6310 print_one_column(zpool_prop_t prop, uint64_t value, const char *str,
6311 boolean_t scripted, boolean_t valid, enum zfs_nicenum_format format)
6313 char propval[64];
6314 boolean_t fixed;
6315 size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
6317 switch (prop) {
6318 case ZPOOL_PROP_SIZE:
6319 case ZPOOL_PROP_EXPANDSZ:
6320 case ZPOOL_PROP_CHECKPOINT:
6321 case ZPOOL_PROP_DEDUPRATIO:
6322 if (value == 0)
6323 (void) strlcpy(propval, "-", sizeof (propval));
6324 else
6325 zfs_nicenum_format(value, propval, sizeof (propval),
6326 format);
6327 break;
6328 case ZPOOL_PROP_FRAGMENTATION:
6329 if (value == ZFS_FRAG_INVALID) {
6330 (void) strlcpy(propval, "-", sizeof (propval));
6331 } else if (format == ZFS_NICENUM_RAW) {
6332 (void) snprintf(propval, sizeof (propval), "%llu",
6333 (unsigned long long)value);
6334 } else {
6335 (void) snprintf(propval, sizeof (propval), "%llu%%",
6336 (unsigned long long)value);
6338 break;
6339 case ZPOOL_PROP_CAPACITY:
6340 /* capacity value is in parts-per-10,000 (aka permyriad) */
6341 if (format == ZFS_NICENUM_RAW)
6342 (void) snprintf(propval, sizeof (propval), "%llu",
6343 (unsigned long long)value / 100);
6344 else
6345 (void) snprintf(propval, sizeof (propval),
6346 value < 1000 ? "%1.2f%%" : value < 10000 ?
6347 "%2.1f%%" : "%3.0f%%", value / 100.0);
6348 break;
6349 case ZPOOL_PROP_HEALTH:
6350 width = 8;
6351 (void) strlcpy(propval, str, sizeof (propval));
6352 break;
6353 default:
6354 zfs_nicenum_format(value, propval, sizeof (propval), format);
6357 if (!valid)
6358 (void) strlcpy(propval, "-", sizeof (propval));
6360 if (scripted)
6361 (void) printf("\t%s", propval);
6362 else
6363 (void) printf(" %*s", (int)width, propval);
6367 * print static default line per vdev
6368 * not compatible with '-o' <proplist> option
6370 static void
6371 print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
6372 list_cbdata_t *cb, int depth, boolean_t isspare)
6374 nvlist_t **child;
6375 vdev_stat_t *vs;
6376 uint_t c, children;
6377 char *vname;
6378 boolean_t scripted = cb->cb_scripted;
6379 uint64_t islog = B_FALSE;
6380 const char *dashes = "%-*s - - - - "
6381 "- - - - -\n";
6383 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
6384 (uint64_t **)&vs, &c) == 0);
6386 if (name != NULL) {
6387 boolean_t toplevel = (vs->vs_space != 0);
6388 uint64_t cap;
6389 enum zfs_nicenum_format format;
6390 const char *state;
6392 if (cb->cb_literal)
6393 format = ZFS_NICENUM_RAW;
6394 else
6395 format = ZFS_NICENUM_1024;
6397 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
6398 return;
6400 if (scripted)
6401 (void) printf("\t%s", name);
6402 else if (strlen(name) + depth > cb->cb_namewidth)
6403 (void) printf("%*s%s", depth, "", name);
6404 else
6405 (void) printf("%*s%s%*s", depth, "", name,
6406 (int)(cb->cb_namewidth - strlen(name) - depth), "");
6409 * Print the properties for the individual vdevs. Some
6410 * properties are only applicable to toplevel vdevs. The
6411 * 'toplevel' boolean value is passed to the print_one_column()
6412 * to indicate that the value is valid.
6414 if (VDEV_STAT_VALID(vs_pspace, c) && vs->vs_pspace)
6415 print_one_column(ZPOOL_PROP_SIZE, vs->vs_pspace, NULL,
6416 scripted, B_TRUE, format);
6417 else
6418 print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, NULL,
6419 scripted, toplevel, format);
6420 print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, NULL,
6421 scripted, toplevel, format);
6422 print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
6423 NULL, scripted, toplevel, format);
6424 print_one_column(ZPOOL_PROP_CHECKPOINT,
6425 vs->vs_checkpoint_space, NULL, scripted, toplevel, format);
6426 print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, NULL,
6427 scripted, B_TRUE, format);
6428 print_one_column(ZPOOL_PROP_FRAGMENTATION,
6429 vs->vs_fragmentation, NULL, scripted,
6430 (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
6431 format);
6432 cap = (vs->vs_space == 0) ? 0 :
6433 (vs->vs_alloc * 10000 / vs->vs_space);
6434 print_one_column(ZPOOL_PROP_CAPACITY, cap, NULL,
6435 scripted, toplevel, format);
6436 print_one_column(ZPOOL_PROP_DEDUPRATIO, 0, NULL,
6437 scripted, toplevel, format);
6438 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
6439 if (isspare) {
6440 if (vs->vs_aux == VDEV_AUX_SPARED)
6441 state = "INUSE";
6442 else if (vs->vs_state == VDEV_STATE_HEALTHY)
6443 state = "AVAIL";
6445 print_one_column(ZPOOL_PROP_HEALTH, 0, state, scripted,
6446 B_TRUE, format);
6447 (void) fputc('\n', stdout);
6450 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
6451 &child, &children) != 0)
6452 return;
6454 /* list the normal vdevs first */
6455 for (c = 0; c < children; c++) {
6456 uint64_t ishole = B_FALSE;
6458 if (nvlist_lookup_uint64(child[c],
6459 ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
6460 continue;
6462 if (nvlist_lookup_uint64(child[c],
6463 ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
6464 continue;
6466 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
6467 continue;
6469 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6470 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
6471 print_list_stats(zhp, vname, child[c], cb, depth + 2, B_FALSE);
6472 free(vname);
6475 /* list the classes: 'logs', 'dedup', and 'special' */
6476 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
6477 boolean_t printed = B_FALSE;
6479 for (c = 0; c < children; c++) {
6480 const char *bias = NULL;
6481 const char *type = NULL;
6483 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
6484 &islog) == 0 && islog) {
6485 bias = VDEV_ALLOC_CLASS_LOGS;
6486 } else {
6487 (void) nvlist_lookup_string(child[c],
6488 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
6489 (void) nvlist_lookup_string(child[c],
6490 ZPOOL_CONFIG_TYPE, &type);
6492 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
6493 continue;
6494 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
6495 continue;
6497 if (!printed) {
6498 /* LINTED E_SEC_PRINTF_VAR_FMT */
6499 (void) printf(dashes, cb->cb_namewidth,
6500 class_name[n]);
6501 printed = B_TRUE;
6503 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6504 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
6505 print_list_stats(zhp, vname, child[c], cb, depth + 2,
6506 B_FALSE);
6507 free(vname);
6511 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
6512 &child, &children) == 0 && children > 0) {
6513 /* LINTED E_SEC_PRINTF_VAR_FMT */
6514 (void) printf(dashes, cb->cb_namewidth, "cache");
6515 for (c = 0; c < children; c++) {
6516 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6517 cb->cb_name_flags);
6518 print_list_stats(zhp, vname, child[c], cb, depth + 2,
6519 B_FALSE);
6520 free(vname);
6524 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
6525 &children) == 0 && children > 0) {
6526 /* LINTED E_SEC_PRINTF_VAR_FMT */
6527 (void) printf(dashes, cb->cb_namewidth, "spare");
6528 for (c = 0; c < children; c++) {
6529 vname = zpool_vdev_name(g_zfs, zhp, child[c],
6530 cb->cb_name_flags);
6531 print_list_stats(zhp, vname, child[c], cb, depth + 2,
6532 B_TRUE);
6533 free(vname);
6539 * Generic callback function to list a pool.
6541 static int
6542 list_callback(zpool_handle_t *zhp, void *data)
6544 list_cbdata_t *cbp = data;
6546 print_pool(zhp, cbp);
6548 if (cbp->cb_verbose) {
6549 nvlist_t *config, *nvroot;
6551 config = zpool_get_config(zhp, NULL);
6552 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
6553 &nvroot) == 0);
6554 print_list_stats(zhp, NULL, nvroot, cbp, 0, B_FALSE);
6557 return (0);
6561 * Set the minimum pool/vdev name column width. The width must be at least 9,
6562 * but may be as large as needed.
6564 static int
6565 get_namewidth_list(zpool_handle_t *zhp, void *data)
6567 list_cbdata_t *cb = data;
6568 int width;
6570 width = get_namewidth(zhp, cb->cb_namewidth,
6571 cb->cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
6573 if (width < 9)
6574 width = 9;
6576 cb->cb_namewidth = width;
6578 return (0);
6582 * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
6584 * -g Display guid for individual vdev name.
6585 * -H Scripted mode. Don't display headers, and separate properties
6586 * by a single tab.
6587 * -L Follow links when resolving vdev path name.
6588 * -o List of properties to display. Defaults to
6589 * "name,size,allocated,free,expandsize,fragmentation,capacity,"
6590 * "dedupratio,health,altroot"
6591 * -p Display values in parsable (exact) format.
6592 * -P Display full path for vdev name.
6593 * -T Display a timestamp in date(1) or Unix format
6595 * List all pools in the system, whether or not they're healthy. Output space
6596 * statistics for each one, as well as health status summary.
6599 zpool_do_list(int argc, char **argv)
6601 int c;
6602 int ret = 0;
6603 list_cbdata_t cb = { 0 };
6604 static char default_props[] =
6605 "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
6606 "capacity,dedupratio,health,altroot";
6607 char *props = default_props;
6608 float interval = 0;
6609 unsigned long count = 0;
6610 zpool_list_t *list;
6611 boolean_t first = B_TRUE;
6612 current_prop_type = ZFS_TYPE_POOL;
6614 /* check options */
6615 while ((c = getopt(argc, argv, ":gHLo:pPT:v")) != -1) {
6616 switch (c) {
6617 case 'g':
6618 cb.cb_name_flags |= VDEV_NAME_GUID;
6619 break;
6620 case 'H':
6621 cb.cb_scripted = B_TRUE;
6622 break;
6623 case 'L':
6624 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6625 break;
6626 case 'o':
6627 props = optarg;
6628 break;
6629 case 'P':
6630 cb.cb_name_flags |= VDEV_NAME_PATH;
6631 break;
6632 case 'p':
6633 cb.cb_literal = B_TRUE;
6634 break;
6635 case 'T':
6636 get_timestamp_arg(*optarg);
6637 break;
6638 case 'v':
6639 cb.cb_verbose = B_TRUE;
6640 cb.cb_namewidth = 8; /* 8 until precalc is avail */
6641 break;
6642 case ':':
6643 (void) fprintf(stderr, gettext("missing argument for "
6644 "'%c' option\n"), optopt);
6645 usage(B_FALSE);
6646 break;
6647 case '?':
6648 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6649 optopt);
6650 usage(B_FALSE);
6654 argc -= optind;
6655 argv += optind;
6657 get_interval_count(&argc, argv, &interval, &count);
6659 if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
6660 usage(B_FALSE);
6662 for (;;) {
6663 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
6664 ZFS_TYPE_POOL, cb.cb_literal, &ret)) == NULL)
6665 return (1);
6667 if (pool_list_count(list) == 0)
6668 break;
6670 cb.cb_namewidth = 0;
6671 (void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
6673 if (timestamp_fmt != NODATE)
6674 print_timestamp(timestamp_fmt);
6676 if (!cb.cb_scripted && (first || cb.cb_verbose)) {
6677 print_header(&cb);
6678 first = B_FALSE;
6680 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
6682 if (interval == 0)
6683 break;
6685 if (count != 0 && --count == 0)
6686 break;
6688 pool_list_free(list);
6689 (void) fsleep(interval);
6692 if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
6693 (void) printf(gettext("no pools available\n"));
6694 ret = 0;
6697 pool_list_free(list);
6698 zprop_free_list(cb.cb_proplist);
6699 return (ret);
6702 static int
6703 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
6705 boolean_t force = B_FALSE;
6706 boolean_t rebuild = B_FALSE;
6707 boolean_t wait = B_FALSE;
6708 int c;
6709 nvlist_t *nvroot;
6710 char *poolname, *old_disk, *new_disk;
6711 zpool_handle_t *zhp;
6712 nvlist_t *props = NULL;
6713 char *propval;
6714 int ret;
6716 /* check options */
6717 while ((c = getopt(argc, argv, "fo:sw")) != -1) {
6718 switch (c) {
6719 case 'f':
6720 force = B_TRUE;
6721 break;
6722 case 'o':
6723 if ((propval = strchr(optarg, '=')) == NULL) {
6724 (void) fprintf(stderr, gettext("missing "
6725 "'=' for -o option\n"));
6726 usage(B_FALSE);
6728 *propval = '\0';
6729 propval++;
6731 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
6732 (add_prop_list(optarg, propval, &props, B_TRUE)))
6733 usage(B_FALSE);
6734 break;
6735 case 's':
6736 rebuild = B_TRUE;
6737 break;
6738 case 'w':
6739 wait = B_TRUE;
6740 break;
6741 case '?':
6742 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6743 optopt);
6744 usage(B_FALSE);
6748 argc -= optind;
6749 argv += optind;
6751 /* get pool name and check number of arguments */
6752 if (argc < 1) {
6753 (void) fprintf(stderr, gettext("missing pool name argument\n"));
6754 usage(B_FALSE);
6757 poolname = argv[0];
6759 if (argc < 2) {
6760 (void) fprintf(stderr,
6761 gettext("missing <device> specification\n"));
6762 usage(B_FALSE);
6765 old_disk = argv[1];
6767 if (argc < 3) {
6768 if (!replacing) {
6769 (void) fprintf(stderr,
6770 gettext("missing <new_device> specification\n"));
6771 usage(B_FALSE);
6773 new_disk = old_disk;
6774 argc -= 1;
6775 argv += 1;
6776 } else {
6777 new_disk = argv[2];
6778 argc -= 2;
6779 argv += 2;
6782 if (argc > 1) {
6783 (void) fprintf(stderr, gettext("too many arguments\n"));
6784 usage(B_FALSE);
6787 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
6788 nvlist_free(props);
6789 return (1);
6792 if (zpool_get_config(zhp, NULL) == NULL) {
6793 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
6794 poolname);
6795 zpool_close(zhp);
6796 nvlist_free(props);
6797 return (1);
6800 /* unless manually specified use "ashift" pool property (if set) */
6801 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
6802 int intval;
6803 zprop_source_t src;
6804 char strval[ZPOOL_MAXPROPLEN];
6806 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
6807 if (src != ZPROP_SRC_DEFAULT) {
6808 (void) sprintf(strval, "%" PRId32, intval);
6809 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
6810 &props, B_TRUE) == 0);
6814 nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
6815 argc, argv);
6816 if (nvroot == NULL) {
6817 zpool_close(zhp);
6818 nvlist_free(props);
6819 return (1);
6822 ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing,
6823 rebuild);
6825 if (ret == 0 && wait)
6826 ret = zpool_wait(zhp,
6827 replacing ? ZPOOL_WAIT_REPLACE : ZPOOL_WAIT_RESILVER);
6829 nvlist_free(props);
6830 nvlist_free(nvroot);
6831 zpool_close(zhp);
6833 return (ret);
6837 * zpool replace [-fsw] [-o property=value] <pool> <device> <new_device>
6839 * -f Force attach, even if <new_device> appears to be in use.
6840 * -s Use sequential instead of healing reconstruction for resilver.
6841 * -o Set property=value.
6842 * -w Wait for replacing to complete before returning
6844 * Replace <device> with <new_device>.
6847 zpool_do_replace(int argc, char **argv)
6849 return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
6853 * zpool attach [-fsw] [-o property=value] <pool> <device> <new_device>
6855 * -f Force attach, even if <new_device> appears to be in use.
6856 * -s Use sequential instead of healing reconstruction for resilver.
6857 * -o Set property=value.
6858 * -w Wait for resilvering to complete before returning
6860 * Attach <new_device> to the mirror containing <device>. If <device> is not
6861 * part of a mirror, then <device> will be transformed into a mirror of
6862 * <device> and <new_device>. In either case, <new_device> will begin life
6863 * with a DTL of [0, now], and will immediately begin to resilver itself.
6866 zpool_do_attach(int argc, char **argv)
6868 return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
6872 * zpool detach [-f] <pool> <device>
6874 * -f Force detach of <device>, even if DTLs argue against it
6875 * (not supported yet)
6877 * Detach a device from a mirror. The operation will be refused if <device>
6878 * is the last device in the mirror, or if the DTLs indicate that this device
6879 * has the only valid copy of some data.
6882 zpool_do_detach(int argc, char **argv)
6884 int c;
6885 char *poolname, *path;
6886 zpool_handle_t *zhp;
6887 int ret;
6889 /* check options */
6890 while ((c = getopt(argc, argv, "")) != -1) {
6891 switch (c) {
6892 case '?':
6893 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6894 optopt);
6895 usage(B_FALSE);
6899 argc -= optind;
6900 argv += optind;
6902 /* get pool name and check number of arguments */
6903 if (argc < 1) {
6904 (void) fprintf(stderr, gettext("missing pool name argument\n"));
6905 usage(B_FALSE);
6908 if (argc < 2) {
6909 (void) fprintf(stderr,
6910 gettext("missing <device> specification\n"));
6911 usage(B_FALSE);
6914 poolname = argv[0];
6915 path = argv[1];
6917 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
6918 return (1);
6920 ret = zpool_vdev_detach(zhp, path);
6922 zpool_close(zhp);
6924 return (ret);
6928 * zpool split [-gLnP] [-o prop=val] ...
6929 * [-o mntopt] ...
6930 * [-R altroot] <pool> <newpool> [<device> ...]
6932 * -g Display guid for individual vdev name.
6933 * -L Follow links when resolving vdev path name.
6934 * -n Do not split the pool, but display the resulting layout if
6935 * it were to be split.
6936 * -o Set property=value, or set mount options.
6937 * -P Display full path for vdev name.
6938 * -R Mount the split-off pool under an alternate root.
6939 * -l Load encryption keys while importing.
6941 * Splits the named pool and gives it the new pool name. Devices to be split
6942 * off may be listed, provided that no more than one device is specified
6943 * per top-level vdev mirror. The newly split pool is left in an exported
6944 * state unless -R is specified.
6946 * Restrictions: the top-level of the pool pool must only be made up of
6947 * mirrors; all devices in the pool must be healthy; no device may be
6948 * undergoing a resilvering operation.
6951 zpool_do_split(int argc, char **argv)
6953 char *srcpool, *newpool, *propval;
6954 char *mntopts = NULL;
6955 splitflags_t flags;
6956 int c, ret = 0;
6957 int ms_status = 0;
6958 boolean_t loadkeys = B_FALSE;
6959 zpool_handle_t *zhp;
6960 nvlist_t *config, *props = NULL;
6962 flags.dryrun = B_FALSE;
6963 flags.import = B_FALSE;
6964 flags.name_flags = 0;
6966 /* check options */
6967 while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
6968 switch (c) {
6969 case 'g':
6970 flags.name_flags |= VDEV_NAME_GUID;
6971 break;
6972 case 'L':
6973 flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
6974 break;
6975 case 'R':
6976 flags.import = B_TRUE;
6977 if (add_prop_list(
6978 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
6979 &props, B_TRUE) != 0) {
6980 nvlist_free(props);
6981 usage(B_FALSE);
6983 break;
6984 case 'l':
6985 loadkeys = B_TRUE;
6986 break;
6987 case 'n':
6988 flags.dryrun = B_TRUE;
6989 break;
6990 case 'o':
6991 if ((propval = strchr(optarg, '=')) != NULL) {
6992 *propval = '\0';
6993 propval++;
6994 if (add_prop_list(optarg, propval,
6995 &props, B_TRUE) != 0) {
6996 nvlist_free(props);
6997 usage(B_FALSE);
6999 } else {
7000 mntopts = optarg;
7002 break;
7003 case 'P':
7004 flags.name_flags |= VDEV_NAME_PATH;
7005 break;
7006 case ':':
7007 (void) fprintf(stderr, gettext("missing argument for "
7008 "'%c' option\n"), optopt);
7009 usage(B_FALSE);
7010 break;
7011 case '?':
7012 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7013 optopt);
7014 usage(B_FALSE);
7015 break;
7019 if (!flags.import && mntopts != NULL) {
7020 (void) fprintf(stderr, gettext("setting mntopts is only "
7021 "valid when importing the pool\n"));
7022 usage(B_FALSE);
7025 if (!flags.import && loadkeys) {
7026 (void) fprintf(stderr, gettext("loading keys is only "
7027 "valid when importing the pool\n"));
7028 usage(B_FALSE);
7031 argc -= optind;
7032 argv += optind;
7034 if (argc < 1) {
7035 (void) fprintf(stderr, gettext("Missing pool name\n"));
7036 usage(B_FALSE);
7038 if (argc < 2) {
7039 (void) fprintf(stderr, gettext("Missing new pool name\n"));
7040 usage(B_FALSE);
7043 srcpool = argv[0];
7044 newpool = argv[1];
7046 argc -= 2;
7047 argv += 2;
7049 if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
7050 nvlist_free(props);
7051 return (1);
7054 config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
7055 if (config == NULL) {
7056 ret = 1;
7057 } else {
7058 if (flags.dryrun) {
7059 (void) printf(gettext("would create '%s' with the "
7060 "following layout:\n\n"), newpool);
7061 print_vdev_tree(NULL, newpool, config, 0, "",
7062 flags.name_flags);
7063 print_vdev_tree(NULL, "dedup", config, 0,
7064 VDEV_ALLOC_BIAS_DEDUP, 0);
7065 print_vdev_tree(NULL, "special", config, 0,
7066 VDEV_ALLOC_BIAS_SPECIAL, 0);
7070 zpool_close(zhp);
7072 if (ret != 0 || flags.dryrun || !flags.import) {
7073 nvlist_free(config);
7074 nvlist_free(props);
7075 return (ret);
7079 * The split was successful. Now we need to open the new
7080 * pool and import it.
7082 if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
7083 nvlist_free(config);
7084 nvlist_free(props);
7085 return (1);
7088 if (loadkeys) {
7089 ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
7090 if (ret != 0)
7091 ret = 1;
7094 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL) {
7095 ms_status = zpool_enable_datasets(zhp, mntopts, 0);
7096 if (ms_status == EZFS_SHAREFAILED) {
7097 (void) fprintf(stderr, gettext("Split was successful, "
7098 "datasets are mounted but sharing of some datasets "
7099 "has failed\n"));
7100 } else if (ms_status == EZFS_MOUNTFAILED) {
7101 (void) fprintf(stderr, gettext("Split was successful"
7102 ", but some datasets could not be mounted\n"));
7103 (void) fprintf(stderr, gettext("Try doing '%s' with a "
7104 "different altroot\n"), "zpool import");
7107 zpool_close(zhp);
7108 nvlist_free(config);
7109 nvlist_free(props);
7111 return (ret);
7116 * zpool online [--power] <pool> <device> ...
7118 * --power: Power on the enclosure slot to the drive (if possible)
7121 zpool_do_online(int argc, char **argv)
7123 int c, i;
7124 char *poolname;
7125 zpool_handle_t *zhp;
7126 int ret = 0;
7127 vdev_state_t newstate;
7128 int flags = 0;
7129 boolean_t is_power_on = B_FALSE;
7130 struct option long_options[] = {
7131 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
7132 {0, 0, 0, 0}
7135 /* check options */
7136 while ((c = getopt_long(argc, argv, "e", long_options, NULL)) != -1) {
7137 switch (c) {
7138 case 'e':
7139 flags |= ZFS_ONLINE_EXPAND;
7140 break;
7141 case ZPOOL_OPTION_POWER:
7142 is_power_on = B_TRUE;
7143 break;
7144 case '?':
7145 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7146 optopt);
7147 usage(B_FALSE);
7151 if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
7152 is_power_on = B_TRUE;
7154 argc -= optind;
7155 argv += optind;
7157 /* get pool name and check number of arguments */
7158 if (argc < 1) {
7159 (void) fprintf(stderr, gettext("missing pool name\n"));
7160 usage(B_FALSE);
7162 if (argc < 2) {
7163 (void) fprintf(stderr, gettext("missing device name\n"));
7164 usage(B_FALSE);
7167 poolname = argv[0];
7169 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7170 return (1);
7172 for (i = 1; i < argc; i++) {
7173 vdev_state_t oldstate;
7174 boolean_t avail_spare, l2cache;
7175 int rc;
7177 if (is_power_on) {
7178 rc = zpool_power_on_and_disk_wait(zhp, argv[i]);
7179 if (rc == ENOTSUP) {
7180 (void) fprintf(stderr,
7181 gettext("Power control not supported\n"));
7183 if (rc != 0)
7184 return (rc);
7187 nvlist_t *tgt = zpool_find_vdev(zhp, argv[i], &avail_spare,
7188 &l2cache, NULL);
7189 if (tgt == NULL) {
7190 ret = 1;
7191 continue;
7193 uint_t vsc;
7194 oldstate = ((vdev_stat_t *)fnvlist_lookup_uint64_array(tgt,
7195 ZPOOL_CONFIG_VDEV_STATS, &vsc))->vs_state;
7196 if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
7197 if (newstate != VDEV_STATE_HEALTHY) {
7198 (void) printf(gettext("warning: device '%s' "
7199 "onlined, but remains in faulted state\n"),
7200 argv[i]);
7201 if (newstate == VDEV_STATE_FAULTED)
7202 (void) printf(gettext("use 'zpool "
7203 "clear' to restore a faulted "
7204 "device\n"));
7205 else
7206 (void) printf(gettext("use 'zpool "
7207 "replace' to replace devices "
7208 "that are no longer present\n"));
7209 if ((flags & ZFS_ONLINE_EXPAND)) {
7210 (void) printf(gettext("%s: failed "
7211 "to expand usable space on "
7212 "unhealthy device '%s'\n"),
7213 (oldstate >= VDEV_STATE_DEGRADED ?
7214 "error" : "warning"), argv[i]);
7215 if (oldstate >= VDEV_STATE_DEGRADED) {
7216 ret = 1;
7217 break;
7221 } else {
7222 ret = 1;
7226 zpool_close(zhp);
7228 return (ret);
7232 * zpool offline [-ft]|[--power] <pool> <device> ...
7235 * -f Force the device into a faulted state.
7237 * -t Only take the device off-line temporarily. The offline/faulted
7238 * state will not be persistent across reboots.
7240 * --power Power off the enclosure slot to the drive (if possible)
7243 zpool_do_offline(int argc, char **argv)
7245 int c, i;
7246 char *poolname;
7247 zpool_handle_t *zhp;
7248 int ret = 0;
7249 boolean_t istmp = B_FALSE;
7250 boolean_t fault = B_FALSE;
7251 boolean_t is_power_off = B_FALSE;
7253 struct option long_options[] = {
7254 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
7255 {0, 0, 0, 0}
7258 /* check options */
7259 while ((c = getopt_long(argc, argv, "ft", long_options, NULL)) != -1) {
7260 switch (c) {
7261 case 'f':
7262 fault = B_TRUE;
7263 break;
7264 case 't':
7265 istmp = B_TRUE;
7266 break;
7267 case ZPOOL_OPTION_POWER:
7268 is_power_off = B_TRUE;
7269 break;
7270 case '?':
7271 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7272 optopt);
7273 usage(B_FALSE);
7277 if (is_power_off && fault) {
7278 (void) fprintf(stderr,
7279 gettext("-0 and -f cannot be used together\n"));
7280 usage(B_FALSE);
7281 return (1);
7284 if (is_power_off && istmp) {
7285 (void) fprintf(stderr,
7286 gettext("-0 and -t cannot be used together\n"));
7287 usage(B_FALSE);
7288 return (1);
7291 argc -= optind;
7292 argv += optind;
7294 /* get pool name and check number of arguments */
7295 if (argc < 1) {
7296 (void) fprintf(stderr, gettext("missing pool name\n"));
7297 usage(B_FALSE);
7299 if (argc < 2) {
7300 (void) fprintf(stderr, gettext("missing device name\n"));
7301 usage(B_FALSE);
7304 poolname = argv[0];
7306 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7307 return (1);
7309 for (i = 1; i < argc; i++) {
7310 uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
7311 if (is_power_off) {
7313 * Note: we have to power off first, then set REMOVED,
7314 * or else zpool_vdev_set_removed_state() returns
7315 * EAGAIN.
7317 ret = zpool_power_off(zhp, argv[i]);
7318 if (ret != 0) {
7319 (void) fprintf(stderr, "%s %s %d\n",
7320 gettext("unable to power off slot for"),
7321 argv[i], ret);
7323 zpool_vdev_set_removed_state(zhp, guid, VDEV_AUX_NONE);
7325 } else if (fault) {
7326 vdev_aux_t aux;
7327 if (istmp == B_FALSE) {
7328 /* Force the fault to persist across imports */
7329 aux = VDEV_AUX_EXTERNAL_PERSIST;
7330 } else {
7331 aux = VDEV_AUX_EXTERNAL;
7334 if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
7335 ret = 1;
7336 } else {
7337 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
7338 ret = 1;
7342 zpool_close(zhp);
7344 return (ret);
7348 * zpool clear [-nF]|[--power] <pool> [device]
7350 * Clear all errors associated with a pool or a particular device.
7353 zpool_do_clear(int argc, char **argv)
7355 int c;
7356 int ret = 0;
7357 boolean_t dryrun = B_FALSE;
7358 boolean_t do_rewind = B_FALSE;
7359 boolean_t xtreme_rewind = B_FALSE;
7360 boolean_t is_power_on = B_FALSE;
7361 uint32_t rewind_policy = ZPOOL_NO_REWIND;
7362 nvlist_t *policy = NULL;
7363 zpool_handle_t *zhp;
7364 char *pool, *device;
7366 struct option long_options[] = {
7367 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
7368 {0, 0, 0, 0}
7371 /* check options */
7372 while ((c = getopt_long(argc, argv, "FnX", long_options,
7373 NULL)) != -1) {
7374 switch (c) {
7375 case 'F':
7376 do_rewind = B_TRUE;
7377 break;
7378 case 'n':
7379 dryrun = B_TRUE;
7380 break;
7381 case 'X':
7382 xtreme_rewind = B_TRUE;
7383 break;
7384 case ZPOOL_OPTION_POWER:
7385 is_power_on = B_TRUE;
7386 break;
7387 case '?':
7388 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7389 optopt);
7390 usage(B_FALSE);
7394 if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
7395 is_power_on = B_TRUE;
7397 argc -= optind;
7398 argv += optind;
7400 if (argc < 1) {
7401 (void) fprintf(stderr, gettext("missing pool name\n"));
7402 usage(B_FALSE);
7405 if (argc > 2) {
7406 (void) fprintf(stderr, gettext("too many arguments\n"));
7407 usage(B_FALSE);
7410 if ((dryrun || xtreme_rewind) && !do_rewind) {
7411 (void) fprintf(stderr,
7412 gettext("-n or -X only meaningful with -F\n"));
7413 usage(B_FALSE);
7415 if (dryrun)
7416 rewind_policy = ZPOOL_TRY_REWIND;
7417 else if (do_rewind)
7418 rewind_policy = ZPOOL_DO_REWIND;
7419 if (xtreme_rewind)
7420 rewind_policy |= ZPOOL_EXTREME_REWIND;
7422 /* In future, further rewind policy choices can be passed along here */
7423 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
7424 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
7425 rewind_policy) != 0) {
7426 return (1);
7429 pool = argv[0];
7430 device = argc == 2 ? argv[1] : NULL;
7432 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
7433 nvlist_free(policy);
7434 return (1);
7437 if (is_power_on) {
7438 if (device == NULL) {
7439 zpool_power_on_pool_and_wait_for_devices(zhp);
7440 } else {
7441 zpool_power_on_and_disk_wait(zhp, device);
7445 if (zpool_clear(zhp, device, policy) != 0)
7446 ret = 1;
7448 zpool_close(zhp);
7450 nvlist_free(policy);
7452 return (ret);
7456 * zpool reguid <pool>
7459 zpool_do_reguid(int argc, char **argv)
7461 int c;
7462 char *poolname;
7463 zpool_handle_t *zhp;
7464 int ret = 0;
7466 /* check options */
7467 while ((c = getopt(argc, argv, "")) != -1) {
7468 switch (c) {
7469 case '?':
7470 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7471 optopt);
7472 usage(B_FALSE);
7476 argc -= optind;
7477 argv += optind;
7479 /* get pool name and check number of arguments */
7480 if (argc < 1) {
7481 (void) fprintf(stderr, gettext("missing pool name\n"));
7482 usage(B_FALSE);
7485 if (argc > 1) {
7486 (void) fprintf(stderr, gettext("too many arguments\n"));
7487 usage(B_FALSE);
7490 poolname = argv[0];
7491 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7492 return (1);
7494 ret = zpool_reguid(zhp);
7496 zpool_close(zhp);
7497 return (ret);
7502 * zpool reopen <pool>
7504 * Reopen the pool so that the kernel can update the sizes of all vdevs.
7507 zpool_do_reopen(int argc, char **argv)
7509 int c;
7510 int ret = 0;
7511 boolean_t scrub_restart = B_TRUE;
7513 /* check options */
7514 while ((c = getopt(argc, argv, "n")) != -1) {
7515 switch (c) {
7516 case 'n':
7517 scrub_restart = B_FALSE;
7518 break;
7519 case '?':
7520 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7521 optopt);
7522 usage(B_FALSE);
7526 argc -= optind;
7527 argv += optind;
7529 /* if argc == 0 we will execute zpool_reopen_one on all pools */
7530 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7531 B_FALSE, zpool_reopen_one, &scrub_restart);
7533 return (ret);
7536 typedef struct scrub_cbdata {
7537 int cb_type;
7538 pool_scrub_cmd_t cb_scrub_cmd;
7539 } scrub_cbdata_t;
7541 static boolean_t
7542 zpool_has_checkpoint(zpool_handle_t *zhp)
7544 nvlist_t *config, *nvroot;
7546 config = zpool_get_config(zhp, NULL);
7548 if (config != NULL) {
7549 pool_checkpoint_stat_t *pcs = NULL;
7550 uint_t c;
7552 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
7553 (void) nvlist_lookup_uint64_array(nvroot,
7554 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
7556 if (pcs == NULL || pcs->pcs_state == CS_NONE)
7557 return (B_FALSE);
7559 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
7560 pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
7561 return (B_TRUE);
7564 return (B_FALSE);
7567 static int
7568 scrub_callback(zpool_handle_t *zhp, void *data)
7570 scrub_cbdata_t *cb = data;
7571 int err;
7574 * Ignore faulted pools.
7576 if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
7577 (void) fprintf(stderr, gettext("cannot scan '%s': pool is "
7578 "currently unavailable\n"), zpool_get_name(zhp));
7579 return (1);
7582 err = zpool_scan(zhp, cb->cb_type, cb->cb_scrub_cmd);
7584 if (err == 0 && zpool_has_checkpoint(zhp) &&
7585 cb->cb_type == POOL_SCAN_SCRUB) {
7586 (void) printf(gettext("warning: will not scrub state that "
7587 "belongs to the checkpoint of pool '%s'\n"),
7588 zpool_get_name(zhp));
7591 return (err != 0);
7594 static int
7595 wait_callback(zpool_handle_t *zhp, void *data)
7597 zpool_wait_activity_t *act = data;
7598 return (zpool_wait(zhp, *act));
7602 * zpool scrub [-s | -p] [-w] [-e] <pool> ...
7604 * -e Only scrub blocks in the error log.
7605 * -s Stop. Stops any in-progress scrub.
7606 * -p Pause. Pause in-progress scrub.
7607 * -w Wait. Blocks until scrub has completed.
7610 zpool_do_scrub(int argc, char **argv)
7612 int c;
7613 scrub_cbdata_t cb;
7614 boolean_t wait = B_FALSE;
7615 int error;
7617 cb.cb_type = POOL_SCAN_SCRUB;
7618 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
7620 boolean_t is_error_scrub = B_FALSE;
7621 boolean_t is_pause = B_FALSE;
7622 boolean_t is_stop = B_FALSE;
7624 /* check options */
7625 while ((c = getopt(argc, argv, "spwe")) != -1) {
7626 switch (c) {
7627 case 'e':
7628 is_error_scrub = B_TRUE;
7629 break;
7630 case 's':
7631 is_stop = B_TRUE;
7632 break;
7633 case 'p':
7634 is_pause = B_TRUE;
7635 break;
7636 case 'w':
7637 wait = B_TRUE;
7638 break;
7639 case '?':
7640 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7641 optopt);
7642 usage(B_FALSE);
7646 if (is_pause && is_stop) {
7647 (void) fprintf(stderr, gettext("invalid option "
7648 "combination :-s and -p are mutually exclusive\n"));
7649 usage(B_FALSE);
7650 } else {
7651 if (is_error_scrub)
7652 cb.cb_type = POOL_SCAN_ERRORSCRUB;
7654 if (is_pause) {
7655 cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
7656 } else if (is_stop) {
7657 cb.cb_type = POOL_SCAN_NONE;
7658 } else {
7659 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
7663 if (wait && (cb.cb_type == POOL_SCAN_NONE ||
7664 cb.cb_scrub_cmd == POOL_SCRUB_PAUSE)) {
7665 (void) fprintf(stderr, gettext("invalid option combination: "
7666 "-w cannot be used with -p or -s\n"));
7667 usage(B_FALSE);
7670 argc -= optind;
7671 argv += optind;
7673 if (argc < 1) {
7674 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7675 usage(B_FALSE);
7678 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7679 B_FALSE, scrub_callback, &cb);
7681 if (wait && !error) {
7682 zpool_wait_activity_t act = ZPOOL_WAIT_SCRUB;
7683 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7684 B_FALSE, wait_callback, &act);
7687 return (error);
7691 * zpool resilver <pool> ...
7693 * Restarts any in-progress resilver
7696 zpool_do_resilver(int argc, char **argv)
7698 int c;
7699 scrub_cbdata_t cb;
7701 cb.cb_type = POOL_SCAN_RESILVER;
7702 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
7704 /* check options */
7705 while ((c = getopt(argc, argv, "")) != -1) {
7706 switch (c) {
7707 case '?':
7708 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7709 optopt);
7710 usage(B_FALSE);
7714 argc -= optind;
7715 argv += optind;
7717 if (argc < 1) {
7718 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7719 usage(B_FALSE);
7722 return (for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
7723 B_FALSE, scrub_callback, &cb));
7727 * zpool trim [-d] [-r <rate>] [-c | -s] <pool> [<device> ...]
7729 * -c Cancel. Ends any in-progress trim.
7730 * -d Secure trim. Requires kernel and device support.
7731 * -r <rate> Sets the TRIM rate in bytes (per second). Supports
7732 * adding a multiplier suffix such as 'k' or 'm'.
7733 * -s Suspend. TRIM can then be restarted with no flags.
7734 * -w Wait. Blocks until trimming has completed.
7737 zpool_do_trim(int argc, char **argv)
7739 struct option long_options[] = {
7740 {"cancel", no_argument, NULL, 'c'},
7741 {"secure", no_argument, NULL, 'd'},
7742 {"rate", required_argument, NULL, 'r'},
7743 {"suspend", no_argument, NULL, 's'},
7744 {"wait", no_argument, NULL, 'w'},
7745 {0, 0, 0, 0}
7748 pool_trim_func_t cmd_type = POOL_TRIM_START;
7749 uint64_t rate = 0;
7750 boolean_t secure = B_FALSE;
7751 boolean_t wait = B_FALSE;
7753 int c;
7754 while ((c = getopt_long(argc, argv, "cdr:sw", long_options, NULL))
7755 != -1) {
7756 switch (c) {
7757 case 'c':
7758 if (cmd_type != POOL_TRIM_START &&
7759 cmd_type != POOL_TRIM_CANCEL) {
7760 (void) fprintf(stderr, gettext("-c cannot be "
7761 "combined with other options\n"));
7762 usage(B_FALSE);
7764 cmd_type = POOL_TRIM_CANCEL;
7765 break;
7766 case 'd':
7767 if (cmd_type != POOL_TRIM_START) {
7768 (void) fprintf(stderr, gettext("-d cannot be "
7769 "combined with the -c or -s options\n"));
7770 usage(B_FALSE);
7772 secure = B_TRUE;
7773 break;
7774 case 'r':
7775 if (cmd_type != POOL_TRIM_START) {
7776 (void) fprintf(stderr, gettext("-r cannot be "
7777 "combined with the -c or -s options\n"));
7778 usage(B_FALSE);
7780 if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
7781 (void) fprintf(stderr, "%s: %s\n",
7782 gettext("invalid value for rate"),
7783 libzfs_error_description(g_zfs));
7784 usage(B_FALSE);
7786 break;
7787 case 's':
7788 if (cmd_type != POOL_TRIM_START &&
7789 cmd_type != POOL_TRIM_SUSPEND) {
7790 (void) fprintf(stderr, gettext("-s cannot be "
7791 "combined with other options\n"));
7792 usage(B_FALSE);
7794 cmd_type = POOL_TRIM_SUSPEND;
7795 break;
7796 case 'w':
7797 wait = B_TRUE;
7798 break;
7799 case '?':
7800 if (optopt != 0) {
7801 (void) fprintf(stderr,
7802 gettext("invalid option '%c'\n"), optopt);
7803 } else {
7804 (void) fprintf(stderr,
7805 gettext("invalid option '%s'\n"),
7806 argv[optind - 1]);
7808 usage(B_FALSE);
7812 argc -= optind;
7813 argv += optind;
7815 if (argc < 1) {
7816 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7817 usage(B_FALSE);
7818 return (-1);
7821 if (wait && (cmd_type != POOL_TRIM_START)) {
7822 (void) fprintf(stderr, gettext("-w cannot be used with -c or "
7823 "-s\n"));
7824 usage(B_FALSE);
7827 char *poolname = argv[0];
7828 zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
7829 if (zhp == NULL)
7830 return (-1);
7832 trimflags_t trim_flags = {
7833 .secure = secure,
7834 .rate = rate,
7835 .wait = wait,
7838 nvlist_t *vdevs = fnvlist_alloc();
7839 if (argc == 1) {
7840 /* no individual leaf vdevs specified, so add them all */
7841 nvlist_t *config = zpool_get_config(zhp, NULL);
7842 nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
7843 ZPOOL_CONFIG_VDEV_TREE);
7844 zpool_collect_leaves(zhp, nvroot, vdevs);
7845 trim_flags.fullpool = B_TRUE;
7846 } else {
7847 trim_flags.fullpool = B_FALSE;
7848 for (int i = 1; i < argc; i++) {
7849 fnvlist_add_boolean(vdevs, argv[i]);
7853 int error = zpool_trim(zhp, cmd_type, vdevs, &trim_flags);
7855 fnvlist_free(vdevs);
7856 zpool_close(zhp);
7858 return (error);
7862 * Converts a total number of seconds to a human readable string broken
7863 * down in to days/hours/minutes/seconds.
7865 static void
7866 secs_to_dhms(uint64_t total, char *buf)
7868 uint64_t days = total / 60 / 60 / 24;
7869 uint64_t hours = (total / 60 / 60) % 24;
7870 uint64_t mins = (total / 60) % 60;
7871 uint64_t secs = (total % 60);
7873 if (days > 0) {
7874 (void) sprintf(buf, "%llu days %02llu:%02llu:%02llu",
7875 (u_longlong_t)days, (u_longlong_t)hours,
7876 (u_longlong_t)mins, (u_longlong_t)secs);
7877 } else {
7878 (void) sprintf(buf, "%02llu:%02llu:%02llu",
7879 (u_longlong_t)hours, (u_longlong_t)mins,
7880 (u_longlong_t)secs);
7885 * Print out detailed error scrub status.
7887 static void
7888 print_err_scrub_status(pool_scan_stat_t *ps)
7890 time_t start, end, pause;
7891 uint64_t total_secs_left;
7892 uint64_t secs_left, mins_left, hours_left, days_left;
7893 uint64_t examined, to_be_examined;
7895 if (ps == NULL || ps->pss_error_scrub_func != POOL_SCAN_ERRORSCRUB) {
7896 return;
7899 (void) printf(gettext(" scrub: "));
7901 start = ps->pss_error_scrub_start;
7902 end = ps->pss_error_scrub_end;
7903 pause = ps->pss_pass_error_scrub_pause;
7904 examined = ps->pss_error_scrub_examined;
7905 to_be_examined = ps->pss_error_scrub_to_be_examined;
7907 assert(ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB);
7909 if (ps->pss_error_scrub_state == DSS_FINISHED) {
7910 total_secs_left = end - start;
7911 days_left = total_secs_left / 60 / 60 / 24;
7912 hours_left = (total_secs_left / 60 / 60) % 24;
7913 mins_left = (total_secs_left / 60) % 60;
7914 secs_left = (total_secs_left % 60);
7916 (void) printf(gettext("scrubbed %llu error blocks in %llu days "
7917 "%02llu:%02llu:%02llu on %s"), (u_longlong_t)examined,
7918 (u_longlong_t)days_left, (u_longlong_t)hours_left,
7919 (u_longlong_t)mins_left, (u_longlong_t)secs_left,
7920 ctime(&end));
7922 return;
7923 } else if (ps->pss_error_scrub_state == DSS_CANCELED) {
7924 (void) printf(gettext("error scrub canceled on %s"),
7925 ctime(&end));
7926 return;
7928 assert(ps->pss_error_scrub_state == DSS_ERRORSCRUBBING);
7930 /* Error scrub is in progress. */
7931 if (pause == 0) {
7932 (void) printf(gettext("error scrub in progress since %s"),
7933 ctime(&start));
7934 } else {
7935 (void) printf(gettext("error scrub paused since %s"),
7936 ctime(&pause));
7937 (void) printf(gettext("\terror scrub started on %s"),
7938 ctime(&start));
7941 double fraction_done = (double)examined / (to_be_examined + examined);
7942 (void) printf(gettext("\t%.2f%% done, issued I/O for %llu error"
7943 " blocks"), 100 * fraction_done, (u_longlong_t)examined);
7945 (void) printf("\n");
7949 * Print out detailed scrub status.
7951 static void
7952 print_scan_scrub_resilver_status(pool_scan_stat_t *ps)
7954 time_t start, end, pause;
7955 uint64_t pass_scanned, scanned, pass_issued, issued, total_s, total_i;
7956 uint64_t elapsed, scan_rate, issue_rate;
7957 double fraction_done;
7958 char processed_buf[7], scanned_buf[7], issued_buf[7], total_s_buf[7];
7959 char total_i_buf[7], srate_buf[7], irate_buf[7], time_buf[32];
7961 printf(" ");
7962 printf_color(ANSI_BOLD, gettext("scan:"));
7963 printf(" ");
7965 /* If there's never been a scan, there's not much to say. */
7966 if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
7967 ps->pss_func >= POOL_SCAN_FUNCS) {
7968 (void) printf(gettext("none requested\n"));
7969 return;
7972 start = ps->pss_start_time;
7973 end = ps->pss_end_time;
7974 pause = ps->pss_pass_scrub_pause;
7976 zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
7978 int is_resilver = ps->pss_func == POOL_SCAN_RESILVER;
7979 int is_scrub = ps->pss_func == POOL_SCAN_SCRUB;
7980 assert(is_resilver || is_scrub);
7982 /* Scan is finished or canceled. */
7983 if (ps->pss_state == DSS_FINISHED) {
7984 secs_to_dhms(end - start, time_buf);
7986 if (is_scrub) {
7987 (void) printf(gettext("scrub repaired %s "
7988 "in %s with %llu errors on %s"), processed_buf,
7989 time_buf, (u_longlong_t)ps->pss_errors,
7990 ctime(&end));
7991 } else if (is_resilver) {
7992 (void) printf(gettext("resilvered %s "
7993 "in %s with %llu errors on %s"), processed_buf,
7994 time_buf, (u_longlong_t)ps->pss_errors,
7995 ctime(&end));
7997 return;
7998 } else if (ps->pss_state == DSS_CANCELED) {
7999 if (is_scrub) {
8000 (void) printf(gettext("scrub canceled on %s"),
8001 ctime(&end));
8002 } else if (is_resilver) {
8003 (void) printf(gettext("resilver canceled on %s"),
8004 ctime(&end));
8006 return;
8009 assert(ps->pss_state == DSS_SCANNING);
8011 /* Scan is in progress. Resilvers can't be paused. */
8012 if (is_scrub) {
8013 if (pause == 0) {
8014 (void) printf(gettext("scrub in progress since %s"),
8015 ctime(&start));
8016 } else {
8017 (void) printf(gettext("scrub paused since %s"),
8018 ctime(&pause));
8019 (void) printf(gettext("\tscrub started on %s"),
8020 ctime(&start));
8022 } else if (is_resilver) {
8023 (void) printf(gettext("resilver in progress since %s"),
8024 ctime(&start));
8027 scanned = ps->pss_examined;
8028 pass_scanned = ps->pss_pass_exam;
8029 issued = ps->pss_issued;
8030 pass_issued = ps->pss_pass_issued;
8031 total_s = ps->pss_to_examine;
8032 total_i = ps->pss_to_examine - ps->pss_skipped;
8034 /* we are only done with a block once we have issued the IO for it */
8035 fraction_done = (double)issued / total_i;
8037 /* elapsed time for this pass, rounding up to 1 if it's 0 */
8038 elapsed = time(NULL) - ps->pss_pass_start;
8039 elapsed -= ps->pss_pass_scrub_spent_paused;
8040 elapsed = (elapsed != 0) ? elapsed : 1;
8042 scan_rate = pass_scanned / elapsed;
8043 issue_rate = pass_issued / elapsed;
8045 /* format all of the numbers we will be reporting */
8046 zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
8047 zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
8048 zfs_nicebytes(total_s, total_s_buf, sizeof (total_s_buf));
8049 zfs_nicebytes(total_i, total_i_buf, sizeof (total_i_buf));
8051 /* do not print estimated time if we have a paused scrub */
8052 (void) printf(gettext("\t%s / %s scanned"), scanned_buf, total_s_buf);
8053 if (pause == 0 && scan_rate > 0) {
8054 zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
8055 (void) printf(gettext(" at %s/s"), srate_buf);
8057 (void) printf(gettext(", %s / %s issued"), issued_buf, total_i_buf);
8058 if (pause == 0 && issue_rate > 0) {
8059 zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
8060 (void) printf(gettext(" at %s/s"), irate_buf);
8062 (void) printf(gettext("\n"));
8064 if (is_resilver) {
8065 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
8066 processed_buf, 100 * fraction_done);
8067 } else if (is_scrub) {
8068 (void) printf(gettext("\t%s repaired, %.2f%% done"),
8069 processed_buf, 100 * fraction_done);
8072 if (pause == 0) {
8074 * Only provide an estimate iff:
8075 * 1) we haven't yet issued all we expected, and
8076 * 2) the issue rate exceeds 10 MB/s, and
8077 * 3) it's either:
8078 * a) a resilver which has started repairs, or
8079 * b) a scrub which has entered the issue phase.
8081 if (total_i >= issued && issue_rate >= 10 * 1024 * 1024 &&
8082 ((is_resilver && ps->pss_processed > 0) ||
8083 (is_scrub && issued > 0))) {
8084 secs_to_dhms((total_i - issued) / issue_rate, time_buf);
8085 (void) printf(gettext(", %s to go\n"), time_buf);
8086 } else {
8087 (void) printf(gettext(", no estimated "
8088 "completion time\n"));
8090 } else {
8091 (void) printf(gettext("\n"));
8095 static void
8096 print_rebuild_status_impl(vdev_rebuild_stat_t *vrs, uint_t c, char *vdev_name)
8098 if (vrs == NULL || vrs->vrs_state == VDEV_REBUILD_NONE)
8099 return;
8101 printf(" ");
8102 printf_color(ANSI_BOLD, gettext("scan:"));
8103 printf(" ");
8105 uint64_t bytes_scanned = vrs->vrs_bytes_scanned;
8106 uint64_t bytes_issued = vrs->vrs_bytes_issued;
8107 uint64_t bytes_rebuilt = vrs->vrs_bytes_rebuilt;
8108 uint64_t bytes_est_s = vrs->vrs_bytes_est;
8109 uint64_t bytes_est_i = vrs->vrs_bytes_est;
8110 if (c > offsetof(vdev_rebuild_stat_t, vrs_pass_bytes_skipped) / 8)
8111 bytes_est_i -= vrs->vrs_pass_bytes_skipped;
8112 uint64_t scan_rate = (vrs->vrs_pass_bytes_scanned /
8113 (vrs->vrs_pass_time_ms + 1)) * 1000;
8114 uint64_t issue_rate = (vrs->vrs_pass_bytes_issued /
8115 (vrs->vrs_pass_time_ms + 1)) * 1000;
8116 double scan_pct = MIN((double)bytes_scanned * 100 /
8117 (bytes_est_s + 1), 100);
8119 /* Format all of the numbers we will be reporting */
8120 char bytes_scanned_buf[7], bytes_issued_buf[7];
8121 char bytes_rebuilt_buf[7], bytes_est_s_buf[7], bytes_est_i_buf[7];
8122 char scan_rate_buf[7], issue_rate_buf[7], time_buf[32];
8123 zfs_nicebytes(bytes_scanned, bytes_scanned_buf,
8124 sizeof (bytes_scanned_buf));
8125 zfs_nicebytes(bytes_issued, bytes_issued_buf,
8126 sizeof (bytes_issued_buf));
8127 zfs_nicebytes(bytes_rebuilt, bytes_rebuilt_buf,
8128 sizeof (bytes_rebuilt_buf));
8129 zfs_nicebytes(bytes_est_s, bytes_est_s_buf, sizeof (bytes_est_s_buf));
8130 zfs_nicebytes(bytes_est_i, bytes_est_i_buf, sizeof (bytes_est_i_buf));
8132 time_t start = vrs->vrs_start_time;
8133 time_t end = vrs->vrs_end_time;
8135 /* Rebuild is finished or canceled. */
8136 if (vrs->vrs_state == VDEV_REBUILD_COMPLETE) {
8137 secs_to_dhms(vrs->vrs_scan_time_ms / 1000, time_buf);
8138 (void) printf(gettext("resilvered (%s) %s in %s "
8139 "with %llu errors on %s"), vdev_name, bytes_rebuilt_buf,
8140 time_buf, (u_longlong_t)vrs->vrs_errors, ctime(&end));
8141 return;
8142 } else if (vrs->vrs_state == VDEV_REBUILD_CANCELED) {
8143 (void) printf(gettext("resilver (%s) canceled on %s"),
8144 vdev_name, ctime(&end));
8145 return;
8146 } else if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
8147 (void) printf(gettext("resilver (%s) in progress since %s"),
8148 vdev_name, ctime(&start));
8151 assert(vrs->vrs_state == VDEV_REBUILD_ACTIVE);
8153 (void) printf(gettext("\t%s / %s scanned"), bytes_scanned_buf,
8154 bytes_est_s_buf);
8155 if (scan_rate > 0) {
8156 zfs_nicebytes(scan_rate, scan_rate_buf, sizeof (scan_rate_buf));
8157 (void) printf(gettext(" at %s/s"), scan_rate_buf);
8159 (void) printf(gettext(", %s / %s issued"), bytes_issued_buf,
8160 bytes_est_i_buf);
8161 if (issue_rate > 0) {
8162 zfs_nicebytes(issue_rate, issue_rate_buf,
8163 sizeof (issue_rate_buf));
8164 (void) printf(gettext(" at %s/s"), issue_rate_buf);
8166 (void) printf(gettext("\n"));
8168 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
8169 bytes_rebuilt_buf, scan_pct);
8171 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
8172 if (bytes_est_s >= bytes_scanned &&
8173 scan_rate >= 10 * 1024 * 1024) {
8174 secs_to_dhms((bytes_est_s - bytes_scanned) / scan_rate,
8175 time_buf);
8176 (void) printf(gettext(", %s to go\n"), time_buf);
8177 } else {
8178 (void) printf(gettext(", no estimated "
8179 "completion time\n"));
8181 } else {
8182 (void) printf(gettext("\n"));
8187 * Print rebuild status for top-level vdevs.
8189 static void
8190 print_rebuild_status(zpool_handle_t *zhp, nvlist_t *nvroot)
8192 nvlist_t **child;
8193 uint_t children;
8195 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
8196 &child, &children) != 0)
8197 children = 0;
8199 for (uint_t c = 0; c < children; c++) {
8200 vdev_rebuild_stat_t *vrs;
8201 uint_t i;
8203 if (nvlist_lookup_uint64_array(child[c],
8204 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
8205 char *name = zpool_vdev_name(g_zfs, zhp,
8206 child[c], VDEV_NAME_TYPE_ID);
8207 print_rebuild_status_impl(vrs, i, name);
8208 free(name);
8214 * As we don't scrub checkpointed blocks, we want to warn the user that we
8215 * skipped scanning some blocks if a checkpoint exists or existed at any
8216 * time during the scan. If a sequential instead of healing reconstruction
8217 * was performed then the blocks were reconstructed. However, their checksums
8218 * have not been verified so we still print the warning.
8220 static void
8221 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
8223 if (ps == NULL || pcs == NULL)
8224 return;
8226 if (pcs->pcs_state == CS_NONE ||
8227 pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
8228 return;
8230 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
8232 if (ps->pss_state == DSS_NONE)
8233 return;
8235 if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
8236 ps->pss_end_time < pcs->pcs_start_time)
8237 return;
8239 if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
8240 (void) printf(gettext(" scan warning: skipped blocks "
8241 "that are only referenced by the checkpoint.\n"));
8242 } else {
8243 assert(ps->pss_state == DSS_SCANNING);
8244 (void) printf(gettext(" scan warning: skipping blocks "
8245 "that are only referenced by the checkpoint.\n"));
8250 * Returns B_TRUE if there is an active rebuild in progress. Otherwise,
8251 * B_FALSE is returned and 'rebuild_end_time' is set to the end time for
8252 * the last completed (or cancelled) rebuild.
8254 static boolean_t
8255 check_rebuilding(nvlist_t *nvroot, uint64_t *rebuild_end_time)
8257 nvlist_t **child;
8258 uint_t children;
8259 boolean_t rebuilding = B_FALSE;
8260 uint64_t end_time = 0;
8262 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
8263 &child, &children) != 0)
8264 children = 0;
8266 for (uint_t c = 0; c < children; c++) {
8267 vdev_rebuild_stat_t *vrs;
8268 uint_t i;
8270 if (nvlist_lookup_uint64_array(child[c],
8271 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
8273 if (vrs->vrs_end_time > end_time)
8274 end_time = vrs->vrs_end_time;
8276 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
8277 rebuilding = B_TRUE;
8278 end_time = 0;
8279 break;
8284 if (rebuild_end_time != NULL)
8285 *rebuild_end_time = end_time;
8287 return (rebuilding);
8291 * Print the scan status.
8293 static void
8294 print_scan_status(zpool_handle_t *zhp, nvlist_t *nvroot)
8296 uint64_t rebuild_end_time = 0, resilver_end_time = 0;
8297 boolean_t have_resilver = B_FALSE, have_scrub = B_FALSE;
8298 boolean_t have_errorscrub = B_FALSE;
8299 boolean_t active_resilver = B_FALSE;
8300 pool_checkpoint_stat_t *pcs = NULL;
8301 pool_scan_stat_t *ps = NULL;
8302 uint_t c;
8303 time_t scrub_start = 0, errorscrub_start = 0;
8305 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
8306 (uint64_t **)&ps, &c) == 0) {
8307 if (ps->pss_func == POOL_SCAN_RESILVER) {
8308 resilver_end_time = ps->pss_end_time;
8309 active_resilver = (ps->pss_state == DSS_SCANNING);
8312 have_resilver = (ps->pss_func == POOL_SCAN_RESILVER);
8313 have_scrub = (ps->pss_func == POOL_SCAN_SCRUB);
8314 scrub_start = ps->pss_start_time;
8315 if (c > offsetof(pool_scan_stat_t,
8316 pss_pass_error_scrub_pause) / 8) {
8317 have_errorscrub = (ps->pss_error_scrub_func ==
8318 POOL_SCAN_ERRORSCRUB);
8319 errorscrub_start = ps->pss_error_scrub_start;
8323 boolean_t active_rebuild = check_rebuilding(nvroot, &rebuild_end_time);
8324 boolean_t have_rebuild = (active_rebuild || (rebuild_end_time > 0));
8326 /* Always print the scrub status when available. */
8327 if (have_scrub && scrub_start > errorscrub_start)
8328 print_scan_scrub_resilver_status(ps);
8329 else if (have_errorscrub && errorscrub_start >= scrub_start)
8330 print_err_scrub_status(ps);
8333 * When there is an active resilver or rebuild print its status.
8334 * Otherwise print the status of the last resilver or rebuild.
8336 if (active_resilver || (!active_rebuild && have_resilver &&
8337 resilver_end_time && resilver_end_time > rebuild_end_time)) {
8338 print_scan_scrub_resilver_status(ps);
8339 } else if (active_rebuild || (!active_resilver && have_rebuild &&
8340 rebuild_end_time && rebuild_end_time > resilver_end_time)) {
8341 print_rebuild_status(zhp, nvroot);
8344 (void) nvlist_lookup_uint64_array(nvroot,
8345 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
8346 print_checkpoint_scan_warning(ps, pcs);
8350 * Print out detailed removal status.
8352 static void
8353 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
8355 char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
8356 time_t start, end;
8357 nvlist_t *config, *nvroot;
8358 nvlist_t **child;
8359 uint_t children;
8360 char *vdev_name;
8362 if (prs == NULL || prs->prs_state == DSS_NONE)
8363 return;
8366 * Determine name of vdev.
8368 config = zpool_get_config(zhp, NULL);
8369 nvroot = fnvlist_lookup_nvlist(config,
8370 ZPOOL_CONFIG_VDEV_TREE);
8371 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
8372 &child, &children) == 0);
8373 assert(prs->prs_removing_vdev < children);
8374 vdev_name = zpool_vdev_name(g_zfs, zhp,
8375 child[prs->prs_removing_vdev], B_TRUE);
8377 printf_color(ANSI_BOLD, gettext("remove: "));
8379 start = prs->prs_start_time;
8380 end = prs->prs_end_time;
8381 zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
8384 * Removal is finished or canceled.
8386 if (prs->prs_state == DSS_FINISHED) {
8387 uint64_t minutes_taken = (end - start) / 60;
8389 (void) printf(gettext("Removal of vdev %llu copied %s "
8390 "in %lluh%um, completed on %s"),
8391 (longlong_t)prs->prs_removing_vdev,
8392 copied_buf,
8393 (u_longlong_t)(minutes_taken / 60),
8394 (uint_t)(minutes_taken % 60),
8395 ctime((time_t *)&end));
8396 } else if (prs->prs_state == DSS_CANCELED) {
8397 (void) printf(gettext("Removal of %s canceled on %s"),
8398 vdev_name, ctime(&end));
8399 } else {
8400 uint64_t copied, total, elapsed, mins_left, hours_left;
8401 double fraction_done;
8402 uint_t rate;
8404 assert(prs->prs_state == DSS_SCANNING);
8407 * Removal is in progress.
8409 (void) printf(gettext(
8410 "Evacuation of %s in progress since %s"),
8411 vdev_name, ctime(&start));
8413 copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
8414 total = prs->prs_to_copy;
8415 fraction_done = (double)copied / total;
8417 /* elapsed time for this pass */
8418 elapsed = time(NULL) - prs->prs_start_time;
8419 elapsed = elapsed > 0 ? elapsed : 1;
8420 rate = copied / elapsed;
8421 rate = rate > 0 ? rate : 1;
8422 mins_left = ((total - copied) / rate) / 60;
8423 hours_left = mins_left / 60;
8425 zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
8426 zfs_nicenum(total, total_buf, sizeof (total_buf));
8427 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
8430 * do not print estimated time if hours_left is more than
8431 * 30 days
8433 (void) printf(gettext(
8434 "\t%s copied out of %s at %s/s, %.2f%% done"),
8435 examined_buf, total_buf, rate_buf, 100 * fraction_done);
8436 if (hours_left < (30 * 24)) {
8437 (void) printf(gettext(", %lluh%um to go\n"),
8438 (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
8439 } else {
8440 (void) printf(gettext(
8441 ", (copy is slow, no estimated time)\n"));
8444 free(vdev_name);
8446 if (prs->prs_mapping_memory > 0) {
8447 char mem_buf[7];
8448 zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
8449 (void) printf(gettext(
8450 "\t%s memory used for removed device mappings\n"),
8451 mem_buf);
8455 static void
8456 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
8458 time_t start;
8459 char space_buf[7];
8461 if (pcs == NULL || pcs->pcs_state == CS_NONE)
8462 return;
8464 (void) printf(gettext("checkpoint: "));
8466 start = pcs->pcs_start_time;
8467 zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
8469 if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
8470 char *date = ctime(&start);
8473 * ctime() adds a newline at the end of the generated
8474 * string, thus the weird format specifier and the
8475 * strlen() call used to chop it off from the output.
8477 (void) printf(gettext("created %.*s, consumes %s\n"),
8478 (int)(strlen(date) - 1), date, space_buf);
8479 return;
8482 assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
8484 (void) printf(gettext("discarding, %s remaining.\n"),
8485 space_buf);
8488 static void
8489 print_error_log(zpool_handle_t *zhp)
8491 nvlist_t *nverrlist = NULL;
8492 nvpair_t *elem;
8493 char *pathname;
8494 size_t len = MAXPATHLEN * 2;
8496 if (zpool_get_errlog(zhp, &nverrlist) != 0)
8497 return;
8499 (void) printf("errors: Permanent errors have been "
8500 "detected in the following files:\n\n");
8502 pathname = safe_malloc(len);
8503 elem = NULL;
8504 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
8505 nvlist_t *nv;
8506 uint64_t dsobj, obj;
8508 verify(nvpair_value_nvlist(elem, &nv) == 0);
8509 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
8510 &dsobj) == 0);
8511 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
8512 &obj) == 0);
8513 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
8514 (void) printf("%7s %s\n", "", pathname);
8516 free(pathname);
8517 nvlist_free(nverrlist);
8520 static void
8521 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
8522 uint_t nspares)
8524 uint_t i;
8525 char *name;
8527 if (nspares == 0)
8528 return;
8530 (void) printf(gettext("\tspares\n"));
8532 for (i = 0; i < nspares; i++) {
8533 name = zpool_vdev_name(g_zfs, zhp, spares[i],
8534 cb->cb_name_flags);
8535 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE, NULL);
8536 free(name);
8540 static void
8541 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
8542 uint_t nl2cache)
8544 uint_t i;
8545 char *name;
8547 if (nl2cache == 0)
8548 return;
8550 (void) printf(gettext("\tcache\n"));
8552 for (i = 0; i < nl2cache; i++) {
8553 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
8554 cb->cb_name_flags);
8555 print_status_config(zhp, cb, name, l2cache[i], 2,
8556 B_FALSE, NULL);
8557 free(name);
8561 static void
8562 print_dedup_stats(nvlist_t *config)
8564 ddt_histogram_t *ddh;
8565 ddt_stat_t *dds;
8566 ddt_object_t *ddo;
8567 uint_t c;
8568 char dspace[6], mspace[6];
8571 * If the pool was faulted then we may not have been able to
8572 * obtain the config. Otherwise, if we have anything in the dedup
8573 * table continue processing the stats.
8575 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
8576 (uint64_t **)&ddo, &c) != 0)
8577 return;
8579 (void) printf("\n");
8580 (void) printf(gettext(" dedup: "));
8581 if (ddo->ddo_count == 0) {
8582 (void) printf(gettext("no DDT entries\n"));
8583 return;
8586 zfs_nicebytes(ddo->ddo_dspace, dspace, sizeof (dspace));
8587 zfs_nicebytes(ddo->ddo_mspace, mspace, sizeof (mspace));
8588 (void) printf("DDT entries %llu, size %s on disk, %s in core\n",
8589 (u_longlong_t)ddo->ddo_count,
8590 dspace,
8591 mspace);
8593 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
8594 (uint64_t **)&dds, &c) == 0);
8595 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
8596 (uint64_t **)&ddh, &c) == 0);
8597 zpool_dump_ddt(dds, ddh);
8601 * Display a summary of pool status. Displays a summary such as:
8603 * pool: tank
8604 * status: DEGRADED
8605 * reason: One or more devices ...
8606 * see: https://openzfs.github.io/openzfs-docs/msg/ZFS-xxxx-01
8607 * config:
8608 * mirror DEGRADED
8609 * c1t0d0 OK
8610 * c2t0d0 UNAVAIL
8612 * When given the '-v' option, we print out the complete config. If the '-e'
8613 * option is specified, then we print out error rate information as well.
8615 static int
8616 status_callback(zpool_handle_t *zhp, void *data)
8618 status_cbdata_t *cbp = data;
8619 nvlist_t *config, *nvroot;
8620 const char *msgid;
8621 zpool_status_t reason;
8622 zpool_errata_t errata;
8623 const char *health;
8624 uint_t c;
8625 vdev_stat_t *vs;
8627 config = zpool_get_config(zhp, NULL);
8628 reason = zpool_get_status(zhp, &msgid, &errata);
8630 cbp->cb_count++;
8633 * If we were given 'zpool status -x', only report those pools with
8634 * problems.
8636 if (cbp->cb_explain &&
8637 (reason == ZPOOL_STATUS_OK ||
8638 reason == ZPOOL_STATUS_VERSION_OLDER ||
8639 reason == ZPOOL_STATUS_FEAT_DISABLED ||
8640 reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
8641 reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
8642 if (!cbp->cb_allpools) {
8643 (void) printf(gettext("pool '%s' is healthy\n"),
8644 zpool_get_name(zhp));
8645 if (cbp->cb_first)
8646 cbp->cb_first = B_FALSE;
8648 return (0);
8651 if (cbp->cb_first)
8652 cbp->cb_first = B_FALSE;
8653 else
8654 (void) printf("\n");
8656 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
8657 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
8658 (uint64_t **)&vs, &c) == 0);
8660 health = zpool_get_state_str(zhp);
8662 printf(" ");
8663 printf_color(ANSI_BOLD, gettext("pool:"));
8664 printf(" %s\n", zpool_get_name(zhp));
8665 fputc(' ', stdout);
8666 printf_color(ANSI_BOLD, gettext("state: "));
8668 printf_color(health_str_to_color(health), "%s", health);
8670 fputc('\n', stdout);
8672 switch (reason) {
8673 case ZPOOL_STATUS_MISSING_DEV_R:
8674 printf_color(ANSI_BOLD, gettext("status: "));
8675 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8676 "not be opened. Sufficient replicas exist for\n\tthe pool "
8677 "to continue functioning in a degraded state.\n"));
8678 printf_color(ANSI_BOLD, gettext("action: "));
8679 printf_color(ANSI_YELLOW, gettext("Attach the missing device "
8680 "and online it using 'zpool online'.\n"));
8681 break;
8683 case ZPOOL_STATUS_MISSING_DEV_NR:
8684 printf_color(ANSI_BOLD, gettext("status: "));
8685 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8686 "not be opened. There are insufficient\n\treplicas for the"
8687 " pool to continue functioning.\n"));
8688 printf_color(ANSI_BOLD, gettext("action: "));
8689 printf_color(ANSI_YELLOW, gettext("Attach the missing device "
8690 "and online it using 'zpool online'.\n"));
8691 break;
8693 case ZPOOL_STATUS_CORRUPT_LABEL_R:
8694 printf_color(ANSI_BOLD, gettext("status: "));
8695 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8696 "not be used because the label is missing or\n\tinvalid. "
8697 "Sufficient replicas exist for the pool to continue\n\t"
8698 "functioning in a degraded state.\n"));
8699 printf_color(ANSI_BOLD, gettext("action: "));
8700 printf_color(ANSI_YELLOW, gettext("Replace the device using "
8701 "'zpool replace'.\n"));
8702 break;
8704 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
8705 printf_color(ANSI_BOLD, gettext("status: "));
8706 printf_color(ANSI_YELLOW, gettext("One or more devices could "
8707 "not be used because the label is missing \n\tor invalid. "
8708 "There are insufficient replicas for the pool to "
8709 "continue\n\tfunctioning.\n"));
8710 zpool_explain_recover(zpool_get_handle(zhp),
8711 zpool_get_name(zhp), reason, config);
8712 break;
8714 case ZPOOL_STATUS_FAILING_DEV:
8715 printf_color(ANSI_BOLD, gettext("status: "));
8716 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8717 "experienced an unrecoverable error. An\n\tattempt was "
8718 "made to correct the error. Applications are "
8719 "unaffected.\n"));
8720 printf_color(ANSI_BOLD, gettext("action: "));
8721 printf_color(ANSI_YELLOW, gettext("Determine if the "
8722 "device needs to be replaced, and clear the errors\n\tusing"
8723 " 'zpool clear' or replace the device with 'zpool "
8724 "replace'.\n"));
8725 break;
8727 case ZPOOL_STATUS_OFFLINE_DEV:
8728 printf_color(ANSI_BOLD, gettext("status: "));
8729 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8730 "been taken offline by the administrator.\n\tSufficient "
8731 "replicas exist for the pool to continue functioning in "
8732 "a\n\tdegraded state.\n"));
8733 printf_color(ANSI_BOLD, gettext("action: "));
8734 printf_color(ANSI_YELLOW, gettext("Online the device "
8735 "using 'zpool online' or replace the device with\n\t'zpool "
8736 "replace'.\n"));
8737 break;
8739 case ZPOOL_STATUS_REMOVED_DEV:
8740 printf_color(ANSI_BOLD, gettext("status: "));
8741 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8742 "been removed by the administrator.\n\tSufficient "
8743 "replicas exist for the pool to continue functioning in "
8744 "a\n\tdegraded state.\n"));
8745 printf_color(ANSI_BOLD, gettext("action: "));
8746 printf_color(ANSI_YELLOW, gettext("Online the device "
8747 "using zpool online' or replace the device with\n\t'zpool "
8748 "replace'.\n"));
8749 break;
8751 case ZPOOL_STATUS_RESILVERING:
8752 case ZPOOL_STATUS_REBUILDING:
8753 printf_color(ANSI_BOLD, gettext("status: "));
8754 printf_color(ANSI_YELLOW, gettext("One or more devices is "
8755 "currently being resilvered. The pool will\n\tcontinue "
8756 "to function, possibly in a degraded state.\n"));
8757 printf_color(ANSI_BOLD, gettext("action: "));
8758 printf_color(ANSI_YELLOW, gettext("Wait for the resilver to "
8759 "complete.\n"));
8760 break;
8762 case ZPOOL_STATUS_REBUILD_SCRUB:
8763 printf_color(ANSI_BOLD, gettext("status: "));
8764 printf_color(ANSI_YELLOW, gettext("One or more devices have "
8765 "been sequentially resilvered, scrubbing\n\tthe pool "
8766 "is recommended.\n"));
8767 printf_color(ANSI_BOLD, gettext("action: "));
8768 printf_color(ANSI_YELLOW, gettext("Use 'zpool scrub' to "
8769 "verify all data checksums.\n"));
8770 break;
8772 case ZPOOL_STATUS_CORRUPT_DATA:
8773 printf_color(ANSI_BOLD, gettext("status: "));
8774 printf_color(ANSI_YELLOW, gettext("One or more devices has "
8775 "experienced an error resulting in data\n\tcorruption. "
8776 "Applications may be affected.\n"));
8777 printf_color(ANSI_BOLD, gettext("action: "));
8778 printf_color(ANSI_YELLOW, gettext("Restore the file in question"
8779 " if possible. Otherwise restore the\n\tentire pool from "
8780 "backup.\n"));
8781 break;
8783 case ZPOOL_STATUS_CORRUPT_POOL:
8784 printf_color(ANSI_BOLD, gettext("status: "));
8785 printf_color(ANSI_YELLOW, gettext("The pool metadata is "
8786 "corrupted and the pool cannot be opened.\n"));
8787 zpool_explain_recover(zpool_get_handle(zhp),
8788 zpool_get_name(zhp), reason, config);
8789 break;
8791 case ZPOOL_STATUS_VERSION_OLDER:
8792 printf_color(ANSI_BOLD, gettext("status: "));
8793 printf_color(ANSI_YELLOW, gettext("The pool is formatted using "
8794 "a legacy on-disk format. The pool can\n\tstill be used, "
8795 "but some features are unavailable.\n"));
8796 printf_color(ANSI_BOLD, gettext("action: "));
8797 printf_color(ANSI_YELLOW, gettext("Upgrade the pool using "
8798 "'zpool upgrade'. Once this is done, the\n\tpool will no "
8799 "longer be accessible on software that does not support\n\t"
8800 "feature flags.\n"));
8801 break;
8803 case ZPOOL_STATUS_VERSION_NEWER:
8804 printf_color(ANSI_BOLD, gettext("status: "));
8805 printf_color(ANSI_YELLOW, gettext("The pool has been upgraded "
8806 "to a newer, incompatible on-disk version.\n\tThe pool "
8807 "cannot be accessed on this system.\n"));
8808 printf_color(ANSI_BOLD, gettext("action: "));
8809 printf_color(ANSI_YELLOW, gettext("Access the pool from a "
8810 "system running more recent software, or\n\trestore the "
8811 "pool from backup.\n"));
8812 break;
8814 case ZPOOL_STATUS_FEAT_DISABLED:
8815 printf_color(ANSI_BOLD, gettext("status: "));
8816 printf_color(ANSI_YELLOW, gettext("Some supported and "
8817 "requested features are not enabled on the pool.\n\t"
8818 "The pool can still be used, but some features are "
8819 "unavailable.\n"));
8820 printf_color(ANSI_BOLD, gettext("action: "));
8821 printf_color(ANSI_YELLOW, gettext("Enable all features using "
8822 "'zpool upgrade'. Once this is done,\n\tthe pool may no "
8823 "longer be accessible by software that does not support\n\t"
8824 "the features. See zpool-features(7) for details.\n"));
8825 break;
8827 case ZPOOL_STATUS_COMPATIBILITY_ERR:
8828 printf_color(ANSI_BOLD, gettext("status: "));
8829 printf_color(ANSI_YELLOW, gettext("This pool has a "
8830 "compatibility list specified, but it could not be\n\t"
8831 "read/parsed at this time. The pool can still be used, "
8832 "but this\n\tshould be investigated.\n"));
8833 printf_color(ANSI_BOLD, gettext("action: "));
8834 printf_color(ANSI_YELLOW, gettext("Check the value of the "
8835 "'compatibility' property against the\n\t"
8836 "appropriate file in " ZPOOL_SYSCONF_COMPAT_D " or "
8837 ZPOOL_DATA_COMPAT_D ".\n"));
8838 break;
8840 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
8841 printf_color(ANSI_BOLD, gettext("status: "));
8842 printf_color(ANSI_YELLOW, gettext("One or more features "
8843 "are enabled on the pool despite not being\n\t"
8844 "requested by the 'compatibility' property.\n"));
8845 printf_color(ANSI_BOLD, gettext("action: "));
8846 printf_color(ANSI_YELLOW, gettext("Consider setting "
8847 "'compatibility' to an appropriate value, or\n\t"
8848 "adding needed features to the relevant file in\n\t"
8849 ZPOOL_SYSCONF_COMPAT_D " or " ZPOOL_DATA_COMPAT_D ".\n"));
8850 break;
8852 case ZPOOL_STATUS_UNSUP_FEAT_READ:
8853 printf_color(ANSI_BOLD, gettext("status: "));
8854 printf_color(ANSI_YELLOW, gettext("The pool cannot be accessed "
8855 "on this system because it uses the\n\tfollowing feature(s)"
8856 " not supported on this system:\n"));
8857 zpool_print_unsup_feat(config);
8858 (void) printf("\n");
8859 printf_color(ANSI_BOLD, gettext("action: "));
8860 printf_color(ANSI_YELLOW, gettext("Access the pool from a "
8861 "system that supports the required feature(s),\n\tor "
8862 "restore the pool from backup.\n"));
8863 break;
8865 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
8866 printf_color(ANSI_BOLD, gettext("status: "));
8867 printf_color(ANSI_YELLOW, gettext("The pool can only be "
8868 "accessed in read-only mode on this system. It\n\tcannot be"
8869 " accessed in read-write mode because it uses the "
8870 "following\n\tfeature(s) not supported on this system:\n"));
8871 zpool_print_unsup_feat(config);
8872 (void) printf("\n");
8873 printf_color(ANSI_BOLD, gettext("action: "));
8874 printf_color(ANSI_YELLOW, gettext("The pool cannot be accessed "
8875 "in read-write mode. Import the pool with\n"
8876 "\t\"-o readonly=on\", access the pool from a system that "
8877 "supports the\n\trequired feature(s), or restore the "
8878 "pool from backup.\n"));
8879 break;
8881 case ZPOOL_STATUS_FAULTED_DEV_R:
8882 printf_color(ANSI_BOLD, gettext("status: "));
8883 printf_color(ANSI_YELLOW, gettext("One or more devices are "
8884 "faulted in response to persistent errors.\n\tSufficient "
8885 "replicas exist for the pool to continue functioning "
8886 "in a\n\tdegraded state.\n"));
8887 printf_color(ANSI_BOLD, gettext("action: "));
8888 printf_color(ANSI_YELLOW, gettext("Replace the faulted device, "
8889 "or use 'zpool clear' to mark the device\n\trepaired.\n"));
8890 break;
8892 case ZPOOL_STATUS_FAULTED_DEV_NR:
8893 printf_color(ANSI_BOLD, gettext("status: "));
8894 printf_color(ANSI_YELLOW, gettext("One or more devices are "
8895 "faulted in response to persistent errors. There are "
8896 "insufficient replicas for the pool to\n\tcontinue "
8897 "functioning.\n"));
8898 printf_color(ANSI_BOLD, gettext("action: "));
8899 printf_color(ANSI_YELLOW, gettext("Destroy and re-create the "
8900 "pool from a backup source. Manually marking the device\n"
8901 "\trepaired using 'zpool clear' may allow some data "
8902 "to be recovered.\n"));
8903 break;
8905 case ZPOOL_STATUS_IO_FAILURE_MMP:
8906 printf_color(ANSI_BOLD, gettext("status: "));
8907 printf_color(ANSI_YELLOW, gettext("The pool is suspended "
8908 "because multihost writes failed or were delayed;\n\t"
8909 "another system could import the pool undetected.\n"));
8910 printf_color(ANSI_BOLD, gettext("action: "));
8911 printf_color(ANSI_YELLOW, gettext("Make sure the pool's devices"
8912 " are connected, then reboot your system and\n\timport the "
8913 "pool.\n"));
8914 break;
8916 case ZPOOL_STATUS_IO_FAILURE_WAIT:
8917 case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
8918 printf_color(ANSI_BOLD, gettext("status: "));
8919 printf_color(ANSI_YELLOW, gettext("One or more devices are "
8920 "faulted in response to IO failures.\n"));
8921 printf_color(ANSI_BOLD, gettext("action: "));
8922 printf_color(ANSI_YELLOW, gettext("Make sure the affected "
8923 "devices are connected, then run 'zpool clear'.\n"));
8924 break;
8926 case ZPOOL_STATUS_BAD_LOG:
8927 printf_color(ANSI_BOLD, gettext("status: "));
8928 printf_color(ANSI_YELLOW, gettext("An intent log record "
8929 "could not be read.\n"
8930 "\tWaiting for administrator intervention to fix the "
8931 "faulted pool.\n"));
8932 printf_color(ANSI_BOLD, gettext("action: "));
8933 printf_color(ANSI_YELLOW, gettext("Either restore the affected "
8934 "device(s) and run 'zpool online',\n"
8935 "\tor ignore the intent log records by running "
8936 "'zpool clear'.\n"));
8937 break;
8939 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
8940 (void) printf(gettext("status: One or more devices are "
8941 "configured to use a non-native block size.\n"
8942 "\tExpect reduced performance.\n"));
8943 (void) printf(gettext("action: Replace affected devices with "
8944 "devices that support the\n\tconfigured block size, or "
8945 "migrate data to a properly configured\n\tpool.\n"));
8946 break;
8948 case ZPOOL_STATUS_HOSTID_MISMATCH:
8949 printf_color(ANSI_BOLD, gettext("status: "));
8950 printf_color(ANSI_YELLOW, gettext("Mismatch between pool hostid"
8951 " and system hostid on imported pool.\n\tThis pool was "
8952 "previously imported into a system with a different "
8953 "hostid,\n\tand then was verbatim imported into this "
8954 "system.\n"));
8955 printf_color(ANSI_BOLD, gettext("action: "));
8956 printf_color(ANSI_YELLOW, gettext("Export this pool on all "
8957 "systems on which it is imported.\n"
8958 "\tThen import it to correct the mismatch.\n"));
8959 break;
8961 case ZPOOL_STATUS_ERRATA:
8962 printf_color(ANSI_BOLD, gettext("status: "));
8963 printf_color(ANSI_YELLOW, gettext("Errata #%d detected.\n"),
8964 errata);
8966 switch (errata) {
8967 case ZPOOL_ERRATA_NONE:
8968 break;
8970 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
8971 printf_color(ANSI_BOLD, gettext("action: "));
8972 printf_color(ANSI_YELLOW, gettext("To correct the issue"
8973 " run 'zpool scrub'.\n"));
8974 break;
8976 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
8977 (void) printf(gettext("\tExisting encrypted datasets "
8978 "contain an on-disk incompatibility\n\twhich "
8979 "needs to be corrected.\n"));
8980 printf_color(ANSI_BOLD, gettext("action: "));
8981 printf_color(ANSI_YELLOW, gettext("To correct the issue"
8982 " backup existing encrypted datasets to new\n\t"
8983 "encrypted datasets and destroy the old ones. "
8984 "'zfs mount -o ro' can\n\tbe used to temporarily "
8985 "mount existing encrypted datasets readonly.\n"));
8986 break;
8988 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
8989 (void) printf(gettext("\tExisting encrypted snapshots "
8990 "and bookmarks contain an on-disk\n\tincompat"
8991 "ibility. This may cause on-disk corruption if "
8992 "they are used\n\twith 'zfs recv'.\n"));
8993 printf_color(ANSI_BOLD, gettext("action: "));
8994 printf_color(ANSI_YELLOW, gettext("To correct the"
8995 "issue, enable the bookmark_v2 feature. No "
8996 "additional\n\taction is needed if there are no "
8997 "encrypted snapshots or bookmarks.\n\tIf preserving"
8998 "the encrypted snapshots and bookmarks is required,"
8999 " use\n\ta non-raw send to backup and restore them."
9000 " Alternately, they may be\n\tremoved to resolve "
9001 "the incompatibility.\n"));
9002 break;
9004 default:
9006 * All errata which allow the pool to be imported
9007 * must contain an action message.
9009 assert(0);
9011 break;
9013 default:
9015 * The remaining errors can't actually be generated, yet.
9017 assert(reason == ZPOOL_STATUS_OK);
9020 if (msgid != NULL) {
9021 printf(" ");
9022 printf_color(ANSI_BOLD, gettext("see:"));
9023 printf(gettext(
9024 " https://openzfs.github.io/openzfs-docs/msg/%s\n"),
9025 msgid);
9028 if (config != NULL) {
9029 uint64_t nerr;
9030 nvlist_t **spares, **l2cache;
9031 uint_t nspares, nl2cache;
9032 pool_checkpoint_stat_t *pcs = NULL;
9033 pool_removal_stat_t *prs = NULL;
9035 print_scan_status(zhp, nvroot);
9037 (void) nvlist_lookup_uint64_array(nvroot,
9038 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
9039 print_removal_status(zhp, prs);
9041 (void) nvlist_lookup_uint64_array(nvroot,
9042 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
9043 print_checkpoint_status(pcs);
9045 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
9046 cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
9047 if (cbp->cb_namewidth < 10)
9048 cbp->cb_namewidth = 10;
9050 color_start(ANSI_BOLD);
9051 (void) printf(gettext("config:\n\n"));
9052 (void) printf(gettext("\t%-*s %-8s %5s %5s %5s"),
9053 cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
9054 "CKSUM");
9055 color_end();
9057 if (cbp->cb_print_slow_ios) {
9058 printf_color(ANSI_BOLD, " %5s", gettext("SLOW"));
9061 if (cbp->cb_print_power) {
9062 printf_color(ANSI_BOLD, " %5s", gettext("POWER"));
9065 if (cbp->vcdl != NULL)
9066 print_cmd_columns(cbp->vcdl, 0);
9068 printf("\n");
9070 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
9071 B_FALSE, NULL);
9073 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
9074 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
9075 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
9077 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
9078 &l2cache, &nl2cache) == 0)
9079 print_l2cache(zhp, cbp, l2cache, nl2cache);
9081 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
9082 &spares, &nspares) == 0)
9083 print_spares(zhp, cbp, spares, nspares);
9085 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
9086 &nerr) == 0) {
9087 (void) printf("\n");
9088 if (nerr == 0) {
9089 (void) printf(gettext(
9090 "errors: No known data errors\n"));
9091 } else if (!cbp->cb_verbose) {
9092 color_start(ANSI_RED);
9093 (void) printf(gettext("errors: %llu data "
9094 "errors, use '-v' for a list\n"),
9095 (u_longlong_t)nerr);
9096 color_end();
9097 } else {
9098 print_error_log(zhp);
9102 if (cbp->cb_dedup_stats)
9103 print_dedup_stats(config);
9104 } else {
9105 (void) printf(gettext("config: The configuration cannot be "
9106 "determined.\n"));
9109 return (0);
9113 * zpool status [-c [script1,script2,...]] [-DegiLpPstvx] [--power] [-T d|u] ...
9114 * [pool] [interval [count]]
9116 * -c CMD For each vdev, run command CMD
9117 * -D Display dedup status (undocumented)
9118 * -e Display only unhealthy vdevs
9119 * -g Display guid for individual vdev name.
9120 * -i Display vdev initialization status.
9121 * -L Follow links when resolving vdev path name.
9122 * -p Display values in parsable (exact) format.
9123 * -P Display full path for vdev name.
9124 * -s Display slow IOs column.
9125 * -t Display vdev TRIM status.
9126 * -T Display a timestamp in date(1) or Unix format
9127 * -v Display complete error logs
9128 * -x Display only pools with potential problems
9129 * --power Display vdev enclosure slot power status
9131 * Describes the health status of all pools or some subset.
9134 zpool_do_status(int argc, char **argv)
9136 int c;
9137 int ret;
9138 float interval = 0;
9139 unsigned long count = 0;
9140 status_cbdata_t cb = { 0 };
9141 char *cmd = NULL;
9143 struct option long_options[] = {
9144 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
9145 {0, 0, 0, 0}
9148 /* check options */
9149 while ((c = getopt_long(argc, argv, "c:DegiLpPstT:vx", long_options,
9150 NULL)) != -1) {
9151 switch (c) {
9152 case 'c':
9153 if (cmd != NULL) {
9154 fprintf(stderr,
9155 gettext("Can't set -c flag twice\n"));
9156 exit(1);
9159 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
9160 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
9161 fprintf(stderr, gettext(
9162 "Can't run -c, disabled by "
9163 "ZPOOL_SCRIPTS_ENABLED.\n"));
9164 exit(1);
9167 if ((getuid() <= 0 || geteuid() <= 0) &&
9168 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
9169 fprintf(stderr, gettext(
9170 "Can't run -c with root privileges "
9171 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
9172 exit(1);
9174 cmd = optarg;
9175 break;
9176 case 'D':
9177 cb.cb_dedup_stats = B_TRUE;
9178 break;
9179 case 'e':
9180 cb.cb_print_unhealthy = B_TRUE;
9181 break;
9182 case 'g':
9183 cb.cb_name_flags |= VDEV_NAME_GUID;
9184 break;
9185 case 'i':
9186 cb.cb_print_vdev_init = B_TRUE;
9187 break;
9188 case 'L':
9189 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
9190 break;
9191 case 'p':
9192 cb.cb_literal = B_TRUE;
9193 break;
9194 case 'P':
9195 cb.cb_name_flags |= VDEV_NAME_PATH;
9196 break;
9197 case 's':
9198 cb.cb_print_slow_ios = B_TRUE;
9199 break;
9200 case 't':
9201 cb.cb_print_vdev_trim = B_TRUE;
9202 break;
9203 case 'T':
9204 get_timestamp_arg(*optarg);
9205 break;
9206 case 'v':
9207 cb.cb_verbose = B_TRUE;
9208 break;
9209 case 'x':
9210 cb.cb_explain = B_TRUE;
9211 break;
9212 case ZPOOL_OPTION_POWER:
9213 cb.cb_print_power = B_TRUE;
9214 break;
9215 case '?':
9216 if (optopt == 'c') {
9217 print_zpool_script_list("status");
9218 exit(0);
9219 } else {
9220 fprintf(stderr,
9221 gettext("invalid option '%c'\n"), optopt);
9223 usage(B_FALSE);
9227 argc -= optind;
9228 argv += optind;
9230 get_interval_count(&argc, argv, &interval, &count);
9232 if (argc == 0)
9233 cb.cb_allpools = B_TRUE;
9235 cb.cb_first = B_TRUE;
9236 cb.cb_print_status = B_TRUE;
9238 for (;;) {
9239 if (timestamp_fmt != NODATE)
9240 print_timestamp(timestamp_fmt);
9242 if (cmd != NULL)
9243 cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
9244 NULL, NULL, 0, 0);
9246 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
9247 cb.cb_literal, status_callback, &cb);
9249 if (cb.vcdl != NULL)
9250 free_vdev_cmd_data_list(cb.vcdl);
9251 if (argc == 0 && cb.cb_count == 0)
9252 (void) fprintf(stderr, gettext("no pools available\n"));
9253 else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
9254 (void) printf(gettext("all pools are healthy\n"));
9256 if (ret != 0)
9257 return (ret);
9259 if (interval == 0)
9260 break;
9262 if (count != 0 && --count == 0)
9263 break;
9265 (void) fsleep(interval);
9268 return (0);
9271 typedef struct upgrade_cbdata {
9272 int cb_first;
9273 int cb_argc;
9274 uint64_t cb_version;
9275 char **cb_argv;
9276 } upgrade_cbdata_t;
9278 static int
9279 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
9281 int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
9282 int *count = (int *)unsupp_fs;
9284 if (zfs_version > ZPL_VERSION) {
9285 (void) printf(gettext("%s (v%d) is not supported by this "
9286 "implementation of ZFS.\n"),
9287 zfs_get_name(zhp), zfs_version);
9288 (*count)++;
9291 zfs_iter_filesystems_v2(zhp, 0, check_unsupp_fs, unsupp_fs);
9293 zfs_close(zhp);
9295 return (0);
9298 static int
9299 upgrade_version(zpool_handle_t *zhp, uint64_t version)
9301 int ret;
9302 nvlist_t *config;
9303 uint64_t oldversion;
9304 int unsupp_fs = 0;
9306 config = zpool_get_config(zhp, NULL);
9307 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
9308 &oldversion) == 0);
9310 char compat[ZFS_MAXPROPLEN];
9311 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
9312 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
9313 compat[0] = '\0';
9315 assert(SPA_VERSION_IS_SUPPORTED(oldversion));
9316 assert(oldversion < version);
9318 ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
9319 if (ret != 0)
9320 return (ret);
9322 if (unsupp_fs) {
9323 (void) fprintf(stderr, gettext("Upgrade not performed due "
9324 "to %d unsupported filesystems (max v%d).\n"),
9325 unsupp_fs, (int)ZPL_VERSION);
9326 return (1);
9329 if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
9330 (void) fprintf(stderr, gettext("Upgrade not performed because "
9331 "'compatibility' property set to '"
9332 ZPOOL_COMPAT_LEGACY "'.\n"));
9333 return (1);
9336 ret = zpool_upgrade(zhp, version);
9337 if (ret != 0)
9338 return (ret);
9340 if (version >= SPA_VERSION_FEATURES) {
9341 (void) printf(gettext("Successfully upgraded "
9342 "'%s' from version %llu to feature flags.\n"),
9343 zpool_get_name(zhp), (u_longlong_t)oldversion);
9344 } else {
9345 (void) printf(gettext("Successfully upgraded "
9346 "'%s' from version %llu to version %llu.\n"),
9347 zpool_get_name(zhp), (u_longlong_t)oldversion,
9348 (u_longlong_t)version);
9351 return (0);
9354 static int
9355 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
9357 int i, ret, count;
9358 boolean_t firstff = B_TRUE;
9359 nvlist_t *enabled = zpool_get_features(zhp);
9361 char compat[ZFS_MAXPROPLEN];
9362 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
9363 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
9364 compat[0] = '\0';
9366 boolean_t requested_features[SPA_FEATURES];
9367 if (zpool_do_load_compat(compat, requested_features) !=
9368 ZPOOL_COMPATIBILITY_OK)
9369 return (-1);
9371 count = 0;
9372 for (i = 0; i < SPA_FEATURES; i++) {
9373 const char *fname = spa_feature_table[i].fi_uname;
9374 const char *fguid = spa_feature_table[i].fi_guid;
9376 if (!spa_feature_table[i].fi_zfs_mod_supported)
9377 continue;
9379 if (!nvlist_exists(enabled, fguid) && requested_features[i]) {
9380 char *propname;
9381 verify(-1 != asprintf(&propname, "feature@%s", fname));
9382 ret = zpool_set_prop(zhp, propname,
9383 ZFS_FEATURE_ENABLED);
9384 if (ret != 0) {
9385 free(propname);
9386 return (ret);
9388 count++;
9390 if (firstff) {
9391 (void) printf(gettext("Enabled the "
9392 "following features on '%s':\n"),
9393 zpool_get_name(zhp));
9394 firstff = B_FALSE;
9396 (void) printf(gettext(" %s\n"), fname);
9397 free(propname);
9401 if (countp != NULL)
9402 *countp = count;
9403 return (0);
9406 static int
9407 upgrade_cb(zpool_handle_t *zhp, void *arg)
9409 upgrade_cbdata_t *cbp = arg;
9410 nvlist_t *config;
9411 uint64_t version;
9412 boolean_t modified_pool = B_FALSE;
9413 int ret;
9415 config = zpool_get_config(zhp, NULL);
9416 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
9417 &version) == 0);
9419 assert(SPA_VERSION_IS_SUPPORTED(version));
9421 if (version < cbp->cb_version) {
9422 cbp->cb_first = B_FALSE;
9423 ret = upgrade_version(zhp, cbp->cb_version);
9424 if (ret != 0)
9425 return (ret);
9426 modified_pool = B_TRUE;
9429 * If they did "zpool upgrade -a", then we could
9430 * be doing ioctls to different pools. We need
9431 * to log this history once to each pool, and bypass
9432 * the normal history logging that happens in main().
9434 (void) zpool_log_history(g_zfs, history_str);
9435 log_history = B_FALSE;
9438 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
9439 int count;
9440 ret = upgrade_enable_all(zhp, &count);
9441 if (ret != 0)
9442 return (ret);
9444 if (count > 0) {
9445 cbp->cb_first = B_FALSE;
9446 modified_pool = B_TRUE;
9450 if (modified_pool) {
9451 (void) printf("\n");
9452 (void) after_zpool_upgrade(zhp);
9455 return (0);
9458 static int
9459 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
9461 upgrade_cbdata_t *cbp = arg;
9462 nvlist_t *config;
9463 uint64_t version;
9465 config = zpool_get_config(zhp, NULL);
9466 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
9467 &version) == 0);
9469 assert(SPA_VERSION_IS_SUPPORTED(version));
9471 if (version < SPA_VERSION_FEATURES) {
9472 if (cbp->cb_first) {
9473 (void) printf(gettext("The following pools are "
9474 "formatted with legacy version numbers and can\n"
9475 "be upgraded to use feature flags. After "
9476 "being upgraded, these pools\nwill no "
9477 "longer be accessible by software that does not "
9478 "support feature\nflags.\n\n"
9479 "Note that setting a pool's 'compatibility' "
9480 "feature to '" ZPOOL_COMPAT_LEGACY "' will\n"
9481 "inhibit upgrades.\n\n"));
9482 (void) printf(gettext("VER POOL\n"));
9483 (void) printf(gettext("--- ------------\n"));
9484 cbp->cb_first = B_FALSE;
9487 (void) printf("%2llu %s\n", (u_longlong_t)version,
9488 zpool_get_name(zhp));
9491 return (0);
9494 static int
9495 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
9497 upgrade_cbdata_t *cbp = arg;
9498 nvlist_t *config;
9499 uint64_t version;
9501 config = zpool_get_config(zhp, NULL);
9502 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
9503 &version) == 0);
9505 if (version >= SPA_VERSION_FEATURES) {
9506 int i;
9507 boolean_t poolfirst = B_TRUE;
9508 nvlist_t *enabled = zpool_get_features(zhp);
9510 for (i = 0; i < SPA_FEATURES; i++) {
9511 const char *fguid = spa_feature_table[i].fi_guid;
9512 const char *fname = spa_feature_table[i].fi_uname;
9514 if (!spa_feature_table[i].fi_zfs_mod_supported)
9515 continue;
9517 if (!nvlist_exists(enabled, fguid)) {
9518 if (cbp->cb_first) {
9519 (void) printf(gettext("\nSome "
9520 "supported features are not "
9521 "enabled on the following pools. "
9522 "Once a\nfeature is enabled the "
9523 "pool may become incompatible with "
9524 "software\nthat does not support "
9525 "the feature. See "
9526 "zpool-features(7) for "
9527 "details.\n\n"
9528 "Note that the pool "
9529 "'compatibility' feature can be "
9530 "used to inhibit\nfeature "
9531 "upgrades.\n\n"));
9532 (void) printf(gettext("POOL "
9533 "FEATURE\n"));
9534 (void) printf(gettext("------"
9535 "---------\n"));
9536 cbp->cb_first = B_FALSE;
9539 if (poolfirst) {
9540 (void) printf(gettext("%s\n"),
9541 zpool_get_name(zhp));
9542 poolfirst = B_FALSE;
9545 (void) printf(gettext(" %s\n"), fname);
9548 * If they did "zpool upgrade -a", then we could
9549 * be doing ioctls to different pools. We need
9550 * to log this history once to each pool, and bypass
9551 * the normal history logging that happens in main().
9553 (void) zpool_log_history(g_zfs, history_str);
9554 log_history = B_FALSE;
9558 return (0);
9561 static int
9562 upgrade_one(zpool_handle_t *zhp, void *data)
9564 boolean_t modified_pool = B_FALSE;
9565 upgrade_cbdata_t *cbp = data;
9566 uint64_t cur_version;
9567 int ret;
9569 if (strcmp("log", zpool_get_name(zhp)) == 0) {
9570 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
9571 "Pool 'log' must be renamed using export and import"
9572 " to upgrade.\n"));
9573 return (1);
9576 cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
9577 if (cur_version > cbp->cb_version) {
9578 (void) printf(gettext("Pool '%s' is already formatted "
9579 "using more current version '%llu'.\n\n"),
9580 zpool_get_name(zhp), (u_longlong_t)cur_version);
9581 return (0);
9584 if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
9585 (void) printf(gettext("Pool '%s' is already formatted "
9586 "using version %llu.\n\n"), zpool_get_name(zhp),
9587 (u_longlong_t)cbp->cb_version);
9588 return (0);
9591 if (cur_version != cbp->cb_version) {
9592 modified_pool = B_TRUE;
9593 ret = upgrade_version(zhp, cbp->cb_version);
9594 if (ret != 0)
9595 return (ret);
9598 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
9599 int count = 0;
9600 ret = upgrade_enable_all(zhp, &count);
9601 if (ret != 0)
9602 return (ret);
9604 if (count != 0) {
9605 modified_pool = B_TRUE;
9606 } else if (cur_version == SPA_VERSION) {
9607 (void) printf(gettext("Pool '%s' already has all "
9608 "supported and requested features enabled.\n"),
9609 zpool_get_name(zhp));
9613 if (modified_pool) {
9614 (void) printf("\n");
9615 (void) after_zpool_upgrade(zhp);
9618 return (0);
9622 * zpool upgrade
9623 * zpool upgrade -v
9624 * zpool upgrade [-V version] <-a | pool ...>
9626 * With no arguments, display downrev'd ZFS pool available for upgrade.
9627 * Individual pools can be upgraded by specifying the pool, and '-a' will
9628 * upgrade all pools.
9631 zpool_do_upgrade(int argc, char **argv)
9633 int c;
9634 upgrade_cbdata_t cb = { 0 };
9635 int ret = 0;
9636 boolean_t showversions = B_FALSE;
9637 boolean_t upgradeall = B_FALSE;
9638 char *end;
9641 /* check options */
9642 while ((c = getopt(argc, argv, ":avV:")) != -1) {
9643 switch (c) {
9644 case 'a':
9645 upgradeall = B_TRUE;
9646 break;
9647 case 'v':
9648 showversions = B_TRUE;
9649 break;
9650 case 'V':
9651 cb.cb_version = strtoll(optarg, &end, 10);
9652 if (*end != '\0' ||
9653 !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
9654 (void) fprintf(stderr,
9655 gettext("invalid version '%s'\n"), optarg);
9656 usage(B_FALSE);
9658 break;
9659 case ':':
9660 (void) fprintf(stderr, gettext("missing argument for "
9661 "'%c' option\n"), optopt);
9662 usage(B_FALSE);
9663 break;
9664 case '?':
9665 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9666 optopt);
9667 usage(B_FALSE);
9671 cb.cb_argc = argc;
9672 cb.cb_argv = argv;
9673 argc -= optind;
9674 argv += optind;
9676 if (cb.cb_version == 0) {
9677 cb.cb_version = SPA_VERSION;
9678 } else if (!upgradeall && argc == 0) {
9679 (void) fprintf(stderr, gettext("-V option is "
9680 "incompatible with other arguments\n"));
9681 usage(B_FALSE);
9684 if (showversions) {
9685 if (upgradeall || argc != 0) {
9686 (void) fprintf(stderr, gettext("-v option is "
9687 "incompatible with other arguments\n"));
9688 usage(B_FALSE);
9690 } else if (upgradeall) {
9691 if (argc != 0) {
9692 (void) fprintf(stderr, gettext("-a option should not "
9693 "be used along with a pool name\n"));
9694 usage(B_FALSE);
9698 (void) printf("%s", gettext("This system supports ZFS pool feature "
9699 "flags.\n\n"));
9700 if (showversions) {
9701 int i;
9703 (void) printf(gettext("The following features are "
9704 "supported:\n\n"));
9705 (void) printf(gettext("FEAT DESCRIPTION\n"));
9706 (void) printf("----------------------------------------------"
9707 "---------------\n");
9708 for (i = 0; i < SPA_FEATURES; i++) {
9709 zfeature_info_t *fi = &spa_feature_table[i];
9710 if (!fi->fi_zfs_mod_supported)
9711 continue;
9712 const char *ro =
9713 (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
9714 " (read-only compatible)" : "";
9716 (void) printf("%-37s%s\n", fi->fi_uname, ro);
9717 (void) printf(" %s\n", fi->fi_desc);
9719 (void) printf("\n");
9721 (void) printf(gettext("The following legacy versions are also "
9722 "supported:\n\n"));
9723 (void) printf(gettext("VER DESCRIPTION\n"));
9724 (void) printf("--- -----------------------------------------"
9725 "---------------\n");
9726 (void) printf(gettext(" 1 Initial ZFS version\n"));
9727 (void) printf(gettext(" 2 Ditto blocks "
9728 "(replicated metadata)\n"));
9729 (void) printf(gettext(" 3 Hot spares and double parity "
9730 "RAID-Z\n"));
9731 (void) printf(gettext(" 4 zpool history\n"));
9732 (void) printf(gettext(" 5 Compression using the gzip "
9733 "algorithm\n"));
9734 (void) printf(gettext(" 6 bootfs pool property\n"));
9735 (void) printf(gettext(" 7 Separate intent log devices\n"));
9736 (void) printf(gettext(" 8 Delegated administration\n"));
9737 (void) printf(gettext(" 9 refquota and refreservation "
9738 "properties\n"));
9739 (void) printf(gettext(" 10 Cache devices\n"));
9740 (void) printf(gettext(" 11 Improved scrub performance\n"));
9741 (void) printf(gettext(" 12 Snapshot properties\n"));
9742 (void) printf(gettext(" 13 snapused property\n"));
9743 (void) printf(gettext(" 14 passthrough-x aclinherit\n"));
9744 (void) printf(gettext(" 15 user/group space accounting\n"));
9745 (void) printf(gettext(" 16 stmf property support\n"));
9746 (void) printf(gettext(" 17 Triple-parity RAID-Z\n"));
9747 (void) printf(gettext(" 18 Snapshot user holds\n"));
9748 (void) printf(gettext(" 19 Log device removal\n"));
9749 (void) printf(gettext(" 20 Compression using zle "
9750 "(zero-length encoding)\n"));
9751 (void) printf(gettext(" 21 Deduplication\n"));
9752 (void) printf(gettext(" 22 Received properties\n"));
9753 (void) printf(gettext(" 23 Slim ZIL\n"));
9754 (void) printf(gettext(" 24 System attributes\n"));
9755 (void) printf(gettext(" 25 Improved scrub stats\n"));
9756 (void) printf(gettext(" 26 Improved snapshot deletion "
9757 "performance\n"));
9758 (void) printf(gettext(" 27 Improved snapshot creation "
9759 "performance\n"));
9760 (void) printf(gettext(" 28 Multiple vdev replacements\n"));
9761 (void) printf(gettext("\nFor more information on a particular "
9762 "version, including supported releases,\n"));
9763 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
9764 } else if (argc == 0 && upgradeall) {
9765 cb.cb_first = B_TRUE;
9766 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
9767 if (ret == 0 && cb.cb_first) {
9768 if (cb.cb_version == SPA_VERSION) {
9769 (void) printf(gettext("All pools are already "
9770 "formatted using feature flags.\n\n"));
9771 (void) printf(gettext("Every feature flags "
9772 "pool already has all supported and "
9773 "requested features enabled.\n"));
9774 } else {
9775 (void) printf(gettext("All pools are already "
9776 "formatted with version %llu or higher.\n"),
9777 (u_longlong_t)cb.cb_version);
9780 } else if (argc == 0) {
9781 cb.cb_first = B_TRUE;
9782 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
9783 assert(ret == 0);
9785 if (cb.cb_first) {
9786 (void) printf(gettext("All pools are formatted "
9787 "using feature flags.\n\n"));
9788 } else {
9789 (void) printf(gettext("\nUse 'zpool upgrade -v' "
9790 "for a list of available legacy versions.\n"));
9793 cb.cb_first = B_TRUE;
9794 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
9795 assert(ret == 0);
9797 if (cb.cb_first) {
9798 (void) printf(gettext("Every feature flags pool has "
9799 "all supported and requested features enabled.\n"));
9800 } else {
9801 (void) printf(gettext("\n"));
9803 } else {
9804 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
9805 B_FALSE, upgrade_one, &cb);
9808 return (ret);
9811 typedef struct hist_cbdata {
9812 boolean_t first;
9813 boolean_t longfmt;
9814 boolean_t internal;
9815 } hist_cbdata_t;
9817 static void
9818 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
9820 nvlist_t **records;
9821 uint_t numrecords;
9822 int i;
9824 verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
9825 &records, &numrecords) == 0);
9826 for (i = 0; i < numrecords; i++) {
9827 nvlist_t *rec = records[i];
9828 char tbuf[64] = "";
9830 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
9831 time_t tsec;
9832 struct tm t;
9834 tsec = fnvlist_lookup_uint64(records[i],
9835 ZPOOL_HIST_TIME);
9836 (void) localtime_r(&tsec, &t);
9837 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
9840 if (nvlist_exists(rec, ZPOOL_HIST_ELAPSED_NS)) {
9841 uint64_t elapsed_ns = fnvlist_lookup_int64(records[i],
9842 ZPOOL_HIST_ELAPSED_NS);
9843 (void) snprintf(tbuf + strlen(tbuf),
9844 sizeof (tbuf) - strlen(tbuf),
9845 " (%lldms)", (long long)elapsed_ns / 1000 / 1000);
9848 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
9849 (void) printf("%s %s", tbuf,
9850 fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
9851 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
9852 int ievent =
9853 fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
9854 if (!cb->internal)
9855 continue;
9856 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
9857 (void) printf("%s unrecognized record:\n",
9858 tbuf);
9859 dump_nvlist(rec, 4);
9860 continue;
9862 (void) printf("%s [internal %s txg:%lld] %s", tbuf,
9863 zfs_history_event_names[ievent],
9864 (longlong_t)fnvlist_lookup_uint64(
9865 rec, ZPOOL_HIST_TXG),
9866 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
9867 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
9868 if (!cb->internal)
9869 continue;
9870 (void) printf("%s [txg:%lld] %s", tbuf,
9871 (longlong_t)fnvlist_lookup_uint64(
9872 rec, ZPOOL_HIST_TXG),
9873 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
9874 if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
9875 (void) printf(" %s (%llu)",
9876 fnvlist_lookup_string(rec,
9877 ZPOOL_HIST_DSNAME),
9878 (u_longlong_t)fnvlist_lookup_uint64(rec,
9879 ZPOOL_HIST_DSID));
9881 (void) printf(" %s", fnvlist_lookup_string(rec,
9882 ZPOOL_HIST_INT_STR));
9883 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
9884 if (!cb->internal)
9885 continue;
9886 (void) printf("%s ioctl %s\n", tbuf,
9887 fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
9888 if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
9889 (void) printf(" input:\n");
9890 dump_nvlist(fnvlist_lookup_nvlist(rec,
9891 ZPOOL_HIST_INPUT_NVL), 8);
9893 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
9894 (void) printf(" output:\n");
9895 dump_nvlist(fnvlist_lookup_nvlist(rec,
9896 ZPOOL_HIST_OUTPUT_NVL), 8);
9898 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_SIZE)) {
9899 (void) printf(" output nvlist omitted; "
9900 "original size: %lldKB\n",
9901 (longlong_t)fnvlist_lookup_int64(rec,
9902 ZPOOL_HIST_OUTPUT_SIZE) / 1024);
9904 if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
9905 (void) printf(" errno: %lld\n",
9906 (longlong_t)fnvlist_lookup_int64(rec,
9907 ZPOOL_HIST_ERRNO));
9909 } else {
9910 if (!cb->internal)
9911 continue;
9912 (void) printf("%s unrecognized record:\n", tbuf);
9913 dump_nvlist(rec, 4);
9916 if (!cb->longfmt) {
9917 (void) printf("\n");
9918 continue;
9920 (void) printf(" [");
9921 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
9922 uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
9923 struct passwd *pwd = getpwuid(who);
9924 (void) printf("user %d ", (int)who);
9925 if (pwd != NULL)
9926 (void) printf("(%s) ", pwd->pw_name);
9928 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
9929 (void) printf("on %s",
9930 fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
9932 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
9933 (void) printf(":%s",
9934 fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
9937 (void) printf("]");
9938 (void) printf("\n");
9943 * Print out the command history for a specific pool.
9945 static int
9946 get_history_one(zpool_handle_t *zhp, void *data)
9948 nvlist_t *nvhis;
9949 int ret;
9950 hist_cbdata_t *cb = (hist_cbdata_t *)data;
9951 uint64_t off = 0;
9952 boolean_t eof = B_FALSE;
9954 cb->first = B_FALSE;
9956 (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
9958 while (!eof) {
9959 if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
9960 return (ret);
9962 print_history_records(nvhis, cb);
9963 nvlist_free(nvhis);
9965 (void) printf("\n");
9967 return (ret);
9971 * zpool history <pool>
9973 * Displays the history of commands that modified pools.
9976 zpool_do_history(int argc, char **argv)
9978 hist_cbdata_t cbdata = { 0 };
9979 int ret;
9980 int c;
9982 cbdata.first = B_TRUE;
9983 /* check options */
9984 while ((c = getopt(argc, argv, "li")) != -1) {
9985 switch (c) {
9986 case 'l':
9987 cbdata.longfmt = B_TRUE;
9988 break;
9989 case 'i':
9990 cbdata.internal = B_TRUE;
9991 break;
9992 case '?':
9993 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9994 optopt);
9995 usage(B_FALSE);
9998 argc -= optind;
9999 argv += optind;
10001 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
10002 B_FALSE, get_history_one, &cbdata);
10004 if (argc == 0 && cbdata.first == B_TRUE) {
10005 (void) fprintf(stderr, gettext("no pools available\n"));
10006 return (0);
10009 return (ret);
10012 typedef struct ev_opts {
10013 int verbose;
10014 int scripted;
10015 int follow;
10016 int clear;
10017 char poolname[ZFS_MAX_DATASET_NAME_LEN];
10018 } ev_opts_t;
10020 static void
10021 zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
10023 char ctime_str[26], str[32];
10024 const char *ptr;
10025 int64_t *tv;
10026 uint_t n;
10028 verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
10029 memset(str, ' ', 32);
10030 (void) ctime_r((const time_t *)&tv[0], ctime_str);
10031 (void) memcpy(str, ctime_str+4, 6); /* 'Jun 30' */
10032 (void) memcpy(str+7, ctime_str+20, 4); /* '1993' */
10033 (void) memcpy(str+12, ctime_str+11, 8); /* '21:49:08' */
10034 (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
10035 if (opts->scripted)
10036 (void) printf(gettext("%s\t"), str);
10037 else
10038 (void) printf(gettext("%s "), str);
10040 verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
10041 (void) printf(gettext("%s\n"), ptr);
10044 static void
10045 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
10047 nvpair_t *nvp;
10049 for (nvp = nvlist_next_nvpair(nvl, NULL);
10050 nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
10052 data_type_t type = nvpair_type(nvp);
10053 const char *name = nvpair_name(nvp);
10055 boolean_t b;
10056 uint8_t i8;
10057 uint16_t i16;
10058 uint32_t i32;
10059 uint64_t i64;
10060 const char *str;
10061 nvlist_t *cnv;
10063 printf(gettext("%*s%s = "), depth, "", name);
10065 switch (type) {
10066 case DATA_TYPE_BOOLEAN:
10067 printf(gettext("%s"), "1");
10068 break;
10070 case DATA_TYPE_BOOLEAN_VALUE:
10071 (void) nvpair_value_boolean_value(nvp, &b);
10072 printf(gettext("%s"), b ? "1" : "0");
10073 break;
10075 case DATA_TYPE_BYTE:
10076 (void) nvpair_value_byte(nvp, &i8);
10077 printf(gettext("0x%x"), i8);
10078 break;
10080 case DATA_TYPE_INT8:
10081 (void) nvpair_value_int8(nvp, (void *)&i8);
10082 printf(gettext("0x%x"), i8);
10083 break;
10085 case DATA_TYPE_UINT8:
10086 (void) nvpair_value_uint8(nvp, &i8);
10087 printf(gettext("0x%x"), i8);
10088 break;
10090 case DATA_TYPE_INT16:
10091 (void) nvpair_value_int16(nvp, (void *)&i16);
10092 printf(gettext("0x%x"), i16);
10093 break;
10095 case DATA_TYPE_UINT16:
10096 (void) nvpair_value_uint16(nvp, &i16);
10097 printf(gettext("0x%x"), i16);
10098 break;
10100 case DATA_TYPE_INT32:
10101 (void) nvpair_value_int32(nvp, (void *)&i32);
10102 printf(gettext("0x%x"), i32);
10103 break;
10105 case DATA_TYPE_UINT32:
10106 (void) nvpair_value_uint32(nvp, &i32);
10107 printf(gettext("0x%x"), i32);
10108 break;
10110 case DATA_TYPE_INT64:
10111 (void) nvpair_value_int64(nvp, (void *)&i64);
10112 printf(gettext("0x%llx"), (u_longlong_t)i64);
10113 break;
10115 case DATA_TYPE_UINT64:
10116 (void) nvpair_value_uint64(nvp, &i64);
10118 * translate vdev state values to readable
10119 * strings to aide zpool events consumers
10121 if (strcmp(name,
10122 FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
10123 strcmp(name,
10124 FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
10125 printf(gettext("\"%s\" (0x%llx)"),
10126 zpool_state_to_name(i64, VDEV_AUX_NONE),
10127 (u_longlong_t)i64);
10128 } else {
10129 printf(gettext("0x%llx"), (u_longlong_t)i64);
10131 break;
10133 case DATA_TYPE_HRTIME:
10134 (void) nvpair_value_hrtime(nvp, (void *)&i64);
10135 printf(gettext("0x%llx"), (u_longlong_t)i64);
10136 break;
10138 case DATA_TYPE_STRING:
10139 (void) nvpair_value_string(nvp, &str);
10140 printf(gettext("\"%s\""), str ? str : "<NULL>");
10141 break;
10143 case DATA_TYPE_NVLIST:
10144 printf(gettext("(embedded nvlist)\n"));
10145 (void) nvpair_value_nvlist(nvp, &cnv);
10146 zpool_do_events_nvprint(cnv, depth + 8);
10147 printf(gettext("%*s(end %s)"), depth, "", name);
10148 break;
10150 case DATA_TYPE_NVLIST_ARRAY: {
10151 nvlist_t **val;
10152 uint_t i, nelem;
10154 (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
10155 printf(gettext("(%d embedded nvlists)\n"), nelem);
10156 for (i = 0; i < nelem; i++) {
10157 printf(gettext("%*s%s[%d] = %s\n"),
10158 depth, "", name, i, "(embedded nvlist)");
10159 zpool_do_events_nvprint(val[i], depth + 8);
10160 printf(gettext("%*s(end %s[%i])\n"),
10161 depth, "", name, i);
10163 printf(gettext("%*s(end %s)\n"), depth, "", name);
10165 break;
10167 case DATA_TYPE_INT8_ARRAY: {
10168 int8_t *val;
10169 uint_t i, nelem;
10171 (void) nvpair_value_int8_array(nvp, &val, &nelem);
10172 for (i = 0; i < nelem; i++)
10173 printf(gettext("0x%x "), val[i]);
10175 break;
10178 case DATA_TYPE_UINT8_ARRAY: {
10179 uint8_t *val;
10180 uint_t i, nelem;
10182 (void) nvpair_value_uint8_array(nvp, &val, &nelem);
10183 for (i = 0; i < nelem; i++)
10184 printf(gettext("0x%x "), val[i]);
10186 break;
10189 case DATA_TYPE_INT16_ARRAY: {
10190 int16_t *val;
10191 uint_t i, nelem;
10193 (void) nvpair_value_int16_array(nvp, &val, &nelem);
10194 for (i = 0; i < nelem; i++)
10195 printf(gettext("0x%x "), val[i]);
10197 break;
10200 case DATA_TYPE_UINT16_ARRAY: {
10201 uint16_t *val;
10202 uint_t i, nelem;
10204 (void) nvpair_value_uint16_array(nvp, &val, &nelem);
10205 for (i = 0; i < nelem; i++)
10206 printf(gettext("0x%x "), val[i]);
10208 break;
10211 case DATA_TYPE_INT32_ARRAY: {
10212 int32_t *val;
10213 uint_t i, nelem;
10215 (void) nvpair_value_int32_array(nvp, &val, &nelem);
10216 for (i = 0; i < nelem; i++)
10217 printf(gettext("0x%x "), val[i]);
10219 break;
10222 case DATA_TYPE_UINT32_ARRAY: {
10223 uint32_t *val;
10224 uint_t i, nelem;
10226 (void) nvpair_value_uint32_array(nvp, &val, &nelem);
10227 for (i = 0; i < nelem; i++)
10228 printf(gettext("0x%x "), val[i]);
10230 break;
10233 case DATA_TYPE_INT64_ARRAY: {
10234 int64_t *val;
10235 uint_t i, nelem;
10237 (void) nvpair_value_int64_array(nvp, &val, &nelem);
10238 for (i = 0; i < nelem; i++)
10239 printf(gettext("0x%llx "),
10240 (u_longlong_t)val[i]);
10242 break;
10245 case DATA_TYPE_UINT64_ARRAY: {
10246 uint64_t *val;
10247 uint_t i, nelem;
10249 (void) nvpair_value_uint64_array(nvp, &val, &nelem);
10250 for (i = 0; i < nelem; i++)
10251 printf(gettext("0x%llx "),
10252 (u_longlong_t)val[i]);
10254 break;
10257 case DATA_TYPE_STRING_ARRAY: {
10258 const char **str;
10259 uint_t i, nelem;
10261 (void) nvpair_value_string_array(nvp, &str, &nelem);
10262 for (i = 0; i < nelem; i++)
10263 printf(gettext("\"%s\" "),
10264 str[i] ? str[i] : "<NULL>");
10266 break;
10269 case DATA_TYPE_BOOLEAN_ARRAY:
10270 case DATA_TYPE_BYTE_ARRAY:
10271 case DATA_TYPE_DOUBLE:
10272 case DATA_TYPE_DONTCARE:
10273 case DATA_TYPE_UNKNOWN:
10274 printf(gettext("<unknown>"));
10275 break;
10278 printf(gettext("\n"));
10282 static int
10283 zpool_do_events_next(ev_opts_t *opts)
10285 nvlist_t *nvl;
10286 int zevent_fd, ret, dropped;
10287 const char *pool;
10289 zevent_fd = open(ZFS_DEV, O_RDWR);
10290 VERIFY(zevent_fd >= 0);
10292 if (!opts->scripted)
10293 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
10295 while (1) {
10296 ret = zpool_events_next(g_zfs, &nvl, &dropped,
10297 (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
10298 if (ret || nvl == NULL)
10299 break;
10301 if (dropped > 0)
10302 (void) printf(gettext("dropped %d events\n"), dropped);
10304 if (strlen(opts->poolname) > 0 &&
10305 nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
10306 strcmp(opts->poolname, pool) != 0)
10307 continue;
10309 zpool_do_events_short(nvl, opts);
10311 if (opts->verbose) {
10312 zpool_do_events_nvprint(nvl, 8);
10313 printf(gettext("\n"));
10315 (void) fflush(stdout);
10317 nvlist_free(nvl);
10320 VERIFY(0 == close(zevent_fd));
10322 return (ret);
10325 static int
10326 zpool_do_events_clear(void)
10328 int count, ret;
10330 ret = zpool_events_clear(g_zfs, &count);
10331 if (!ret)
10332 (void) printf(gettext("cleared %d events\n"), count);
10334 return (ret);
10338 * zpool events [-vHf [pool] | -c]
10340 * Displays events logs by ZFS.
10343 zpool_do_events(int argc, char **argv)
10345 ev_opts_t opts = { 0 };
10346 int ret;
10347 int c;
10349 /* check options */
10350 while ((c = getopt(argc, argv, "vHfc")) != -1) {
10351 switch (c) {
10352 case 'v':
10353 opts.verbose = 1;
10354 break;
10355 case 'H':
10356 opts.scripted = 1;
10357 break;
10358 case 'f':
10359 opts.follow = 1;
10360 break;
10361 case 'c':
10362 opts.clear = 1;
10363 break;
10364 case '?':
10365 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
10366 optopt);
10367 usage(B_FALSE);
10370 argc -= optind;
10371 argv += optind;
10373 if (argc > 1) {
10374 (void) fprintf(stderr, gettext("too many arguments\n"));
10375 usage(B_FALSE);
10376 } else if (argc == 1) {
10377 (void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
10378 if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
10379 (void) fprintf(stderr,
10380 gettext("invalid pool name '%s'\n"), opts.poolname);
10381 usage(B_FALSE);
10385 if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
10386 opts.clear) {
10387 (void) fprintf(stderr,
10388 gettext("invalid options combined with -c\n"));
10389 usage(B_FALSE);
10392 if (opts.clear)
10393 ret = zpool_do_events_clear();
10394 else
10395 ret = zpool_do_events_next(&opts);
10397 return (ret);
10400 static int
10401 get_callback_vdev(zpool_handle_t *zhp, char *vdevname, void *data)
10403 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
10404 char value[ZFS_MAXPROPLEN];
10405 zprop_source_t srctype;
10407 for (zprop_list_t *pl = cbp->cb_proplist; pl != NULL;
10408 pl = pl->pl_next) {
10409 char *prop_name;
10411 * If the first property is pool name, it is a special
10412 * placeholder that we can skip. This will also skip
10413 * over the name property when 'all' is specified.
10415 if (pl->pl_prop == ZPOOL_PROP_NAME &&
10416 pl == cbp->cb_proplist)
10417 continue;
10419 if (pl->pl_prop == ZPROP_INVAL) {
10420 prop_name = pl->pl_user_prop;
10421 } else {
10422 prop_name = (char *)vdev_prop_to_name(pl->pl_prop);
10424 if (zpool_get_vdev_prop(zhp, vdevname, pl->pl_prop,
10425 prop_name, value, sizeof (value), &srctype,
10426 cbp->cb_literal) == 0) {
10427 zprop_print_one_property(vdevname, cbp, prop_name,
10428 value, srctype, NULL, NULL);
10432 return (0);
10435 static int
10436 get_callback_vdev_cb(void *zhp_data, nvlist_t *nv, void *data)
10438 zpool_handle_t *zhp = zhp_data;
10439 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
10440 char *vdevname;
10441 const char *type;
10442 int ret;
10445 * zpool_vdev_name() transforms the root vdev name (i.e., root-0) to the
10446 * pool name for display purposes, which is not desired. Fallback to
10447 * zpool_vdev_name() when not dealing with the root vdev.
10449 type = fnvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE);
10450 if (zhp != NULL && strcmp(type, "root") == 0)
10451 vdevname = strdup("root-0");
10452 else
10453 vdevname = zpool_vdev_name(g_zfs, zhp, nv,
10454 cbp->cb_vdevs.cb_name_flags);
10456 (void) vdev_expand_proplist(zhp, vdevname, &cbp->cb_proplist);
10458 ret = get_callback_vdev(zhp, vdevname, data);
10460 free(vdevname);
10462 return (ret);
10465 static int
10466 get_callback(zpool_handle_t *zhp, void *data)
10468 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
10469 char value[ZFS_MAXPROPLEN];
10470 zprop_source_t srctype;
10471 zprop_list_t *pl;
10472 int vid;
10474 if (cbp->cb_type == ZFS_TYPE_VDEV) {
10475 if (strcmp(cbp->cb_vdevs.cb_names[0], "all-vdevs") == 0) {
10476 for_each_vdev(zhp, get_callback_vdev_cb, data);
10477 } else {
10478 /* Adjust column widths for vdev properties */
10479 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
10480 vid++) {
10481 vdev_expand_proplist(zhp,
10482 cbp->cb_vdevs.cb_names[vid],
10483 &cbp->cb_proplist);
10485 /* Display the properties */
10486 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
10487 vid++) {
10488 get_callback_vdev(zhp,
10489 cbp->cb_vdevs.cb_names[vid], data);
10492 } else {
10493 assert(cbp->cb_type == ZFS_TYPE_POOL);
10494 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
10496 * Skip the special fake placeholder. This will also
10497 * skip over the name property when 'all' is specified.
10499 if (pl->pl_prop == ZPOOL_PROP_NAME &&
10500 pl == cbp->cb_proplist)
10501 continue;
10503 if (pl->pl_prop == ZPROP_INVAL &&
10504 zfs_prop_user(pl->pl_user_prop)) {
10505 srctype = ZPROP_SRC_LOCAL;
10507 if (zpool_get_userprop(zhp, pl->pl_user_prop,
10508 value, sizeof (value), &srctype) != 0)
10509 continue;
10511 zprop_print_one_property(zpool_get_name(zhp),
10512 cbp, pl->pl_user_prop, value, srctype,
10513 NULL, NULL);
10514 } else if (pl->pl_prop == ZPROP_INVAL &&
10515 (zpool_prop_feature(pl->pl_user_prop) ||
10516 zpool_prop_unsupported(pl->pl_user_prop))) {
10517 srctype = ZPROP_SRC_LOCAL;
10519 if (zpool_prop_get_feature(zhp,
10520 pl->pl_user_prop, value,
10521 sizeof (value)) == 0) {
10522 zprop_print_one_property(
10523 zpool_get_name(zhp), cbp,
10524 pl->pl_user_prop, value, srctype,
10525 NULL, NULL);
10527 } else {
10528 if (zpool_get_prop(zhp, pl->pl_prop, value,
10529 sizeof (value), &srctype,
10530 cbp->cb_literal) != 0)
10531 continue;
10533 zprop_print_one_property(zpool_get_name(zhp),
10534 cbp, zpool_prop_to_name(pl->pl_prop),
10535 value, srctype, NULL, NULL);
10540 return (0);
10544 * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
10546 * -H Scripted mode. Don't display headers, and separate properties
10547 * by a single tab.
10548 * -o List of columns to display. Defaults to
10549 * "name,property,value,source".
10550 * -p Display values in parsable (exact) format.
10552 * Get properties of pools in the system. Output space statistics
10553 * for each one as well as other attributes.
10556 zpool_do_get(int argc, char **argv)
10558 zprop_get_cbdata_t cb = { 0 };
10559 zprop_list_t fake_name = { 0 };
10560 int ret;
10561 int c, i;
10562 char *propstr = NULL;
10563 char *vdev = NULL;
10565 cb.cb_first = B_TRUE;
10568 * Set up default columns and sources.
10570 cb.cb_sources = ZPROP_SRC_ALL;
10571 cb.cb_columns[0] = GET_COL_NAME;
10572 cb.cb_columns[1] = GET_COL_PROPERTY;
10573 cb.cb_columns[2] = GET_COL_VALUE;
10574 cb.cb_columns[3] = GET_COL_SOURCE;
10575 cb.cb_type = ZFS_TYPE_POOL;
10576 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
10577 current_prop_type = cb.cb_type;
10579 /* check options */
10580 while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
10581 switch (c) {
10582 case 'p':
10583 cb.cb_literal = B_TRUE;
10584 break;
10585 case 'H':
10586 cb.cb_scripted = B_TRUE;
10587 break;
10588 case 'o':
10589 memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
10590 i = 0;
10592 for (char *tok; (tok = strsep(&optarg, ",")); ) {
10593 static const char *const col_opts[] =
10594 { "name", "property", "value", "source",
10595 "all" };
10596 static const zfs_get_column_t col_cols[] =
10597 { GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
10598 GET_COL_SOURCE };
10600 if (i == ZFS_GET_NCOLS - 1) {
10601 (void) fprintf(stderr, gettext("too "
10602 "many fields given to -o "
10603 "option\n"));
10604 usage(B_FALSE);
10607 for (c = 0; c < ARRAY_SIZE(col_opts); ++c)
10608 if (strcmp(tok, col_opts[c]) == 0)
10609 goto found;
10611 (void) fprintf(stderr,
10612 gettext("invalid column name '%s'\n"), tok);
10613 usage(B_FALSE);
10615 found:
10616 if (c >= 4) {
10617 if (i > 0) {
10618 (void) fprintf(stderr,
10619 gettext("\"all\" conflicts "
10620 "with specific fields "
10621 "given to -o option\n"));
10622 usage(B_FALSE);
10625 memcpy(cb.cb_columns, col_cols,
10626 sizeof (col_cols));
10627 i = ZFS_GET_NCOLS - 1;
10628 } else
10629 cb.cb_columns[i++] = col_cols[c];
10631 break;
10632 case '?':
10633 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
10634 optopt);
10635 usage(B_FALSE);
10639 argc -= optind;
10640 argv += optind;
10642 if (argc < 1) {
10643 (void) fprintf(stderr, gettext("missing property "
10644 "argument\n"));
10645 usage(B_FALSE);
10648 /* Properties list is needed later by zprop_get_list() */
10649 propstr = argv[0];
10651 argc--;
10652 argv++;
10654 if (argc == 0) {
10655 /* No args, so just print the defaults. */
10656 } else if (are_all_pools(argc, argv)) {
10657 /* All the args are pool names */
10658 } else if (are_all_pools(1, argv)) {
10659 /* The first arg is a pool name */
10660 if ((argc == 2 && strcmp(argv[1], "all-vdevs") == 0) ||
10661 (argc == 2 && strcmp(argv[1], "root") == 0) ||
10662 are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
10663 &cb.cb_vdevs)) {
10665 if (strcmp(argv[1], "root") == 0)
10666 vdev = strdup("root-0");
10667 else
10668 vdev = strdup(argv[1]);
10670 /* ... and the rest are vdev names */
10671 cb.cb_vdevs.cb_names = &vdev;
10672 cb.cb_vdevs.cb_names_count = argc - 1;
10673 cb.cb_type = ZFS_TYPE_VDEV;
10674 argc = 1; /* One pool to process */
10675 } else {
10676 fprintf(stderr, gettext("Expected a list of vdevs in"
10677 " \"%s\", but got:\n"), argv[0]);
10678 error_list_unresolved_vdevs(argc - 1, argv + 1,
10679 argv[0], &cb.cb_vdevs);
10680 fprintf(stderr, "\n");
10681 usage(B_FALSE);
10682 return (1);
10684 } else {
10686 * The first arg isn't the name of a valid pool.
10688 fprintf(stderr, gettext("Cannot get properties of %s: "
10689 "no such pool available.\n"), argv[0]);
10690 return (1);
10693 if (zprop_get_list(g_zfs, propstr, &cb.cb_proplist,
10694 cb.cb_type) != 0) {
10695 /* Use correct list of valid properties (pool or vdev) */
10696 current_prop_type = cb.cb_type;
10697 usage(B_FALSE);
10700 if (cb.cb_proplist != NULL) {
10701 fake_name.pl_prop = ZPOOL_PROP_NAME;
10702 fake_name.pl_width = strlen(gettext("NAME"));
10703 fake_name.pl_next = cb.cb_proplist;
10704 cb.cb_proplist = &fake_name;
10707 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist, cb.cb_type,
10708 cb.cb_literal, get_callback, &cb);
10710 if (cb.cb_proplist == &fake_name)
10711 zprop_free_list(fake_name.pl_next);
10712 else
10713 zprop_free_list(cb.cb_proplist);
10715 if (vdev != NULL)
10716 free(vdev);
10718 return (ret);
10721 typedef struct set_cbdata {
10722 char *cb_propname;
10723 char *cb_value;
10724 zfs_type_t cb_type;
10725 vdev_cbdata_t cb_vdevs;
10726 boolean_t cb_any_successful;
10727 } set_cbdata_t;
10729 static int
10730 set_pool_callback(zpool_handle_t *zhp, set_cbdata_t *cb)
10732 int error;
10734 /* Check if we have out-of-bounds features */
10735 if (strcmp(cb->cb_propname, ZPOOL_CONFIG_COMPATIBILITY) == 0) {
10736 boolean_t features[SPA_FEATURES];
10737 if (zpool_do_load_compat(cb->cb_value, features) !=
10738 ZPOOL_COMPATIBILITY_OK)
10739 return (-1);
10741 nvlist_t *enabled = zpool_get_features(zhp);
10742 spa_feature_t i;
10743 for (i = 0; i < SPA_FEATURES; i++) {
10744 const char *fguid = spa_feature_table[i].fi_guid;
10745 if (nvlist_exists(enabled, fguid) && !features[i])
10746 break;
10748 if (i < SPA_FEATURES)
10749 (void) fprintf(stderr, gettext("Warning: one or "
10750 "more features already enabled on pool '%s'\n"
10751 "are not present in this compatibility set.\n"),
10752 zpool_get_name(zhp));
10755 /* if we're setting a feature, check it's in compatibility set */
10756 if (zpool_prop_feature(cb->cb_propname) &&
10757 strcmp(cb->cb_value, ZFS_FEATURE_ENABLED) == 0) {
10758 char *fname = strchr(cb->cb_propname, '@') + 1;
10759 spa_feature_t f;
10761 if (zfeature_lookup_name(fname, &f) == 0) {
10762 char compat[ZFS_MAXPROPLEN];
10763 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY,
10764 compat, ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
10765 compat[0] = '\0';
10767 boolean_t features[SPA_FEATURES];
10768 if (zpool_do_load_compat(compat, features) !=
10769 ZPOOL_COMPATIBILITY_OK) {
10770 (void) fprintf(stderr, gettext("Error: "
10771 "cannot enable feature '%s' on pool '%s'\n"
10772 "because the pool's 'compatibility' "
10773 "property cannot be parsed.\n"),
10774 fname, zpool_get_name(zhp));
10775 return (-1);
10778 if (!features[f]) {
10779 (void) fprintf(stderr, gettext("Error: "
10780 "cannot enable feature '%s' on pool '%s'\n"
10781 "as it is not specified in this pool's "
10782 "current compatibility set.\n"
10783 "Consider setting 'compatibility' to a "
10784 "less restrictive set, or to 'off'.\n"),
10785 fname, zpool_get_name(zhp));
10786 return (-1);
10791 error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
10793 return (error);
10796 static int
10797 set_callback(zpool_handle_t *zhp, void *data)
10799 int error;
10800 set_cbdata_t *cb = (set_cbdata_t *)data;
10802 if (cb->cb_type == ZFS_TYPE_VDEV) {
10803 error = zpool_set_vdev_prop(zhp, *cb->cb_vdevs.cb_names,
10804 cb->cb_propname, cb->cb_value);
10805 } else {
10806 assert(cb->cb_type == ZFS_TYPE_POOL);
10807 error = set_pool_callback(zhp, cb);
10810 cb->cb_any_successful = !error;
10811 return (error);
10815 zpool_do_set(int argc, char **argv)
10817 set_cbdata_t cb = { 0 };
10818 int error;
10819 char *vdev = NULL;
10821 current_prop_type = ZFS_TYPE_POOL;
10822 if (argc > 1 && argv[1][0] == '-') {
10823 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
10824 argv[1][1]);
10825 usage(B_FALSE);
10828 if (argc < 2) {
10829 (void) fprintf(stderr, gettext("missing property=value "
10830 "argument\n"));
10831 usage(B_FALSE);
10834 if (argc < 3) {
10835 (void) fprintf(stderr, gettext("missing pool name\n"));
10836 usage(B_FALSE);
10839 if (argc > 4) {
10840 (void) fprintf(stderr, gettext("too many pool names\n"));
10841 usage(B_FALSE);
10844 cb.cb_propname = argv[1];
10845 cb.cb_type = ZFS_TYPE_POOL;
10846 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
10847 cb.cb_value = strchr(cb.cb_propname, '=');
10848 if (cb.cb_value == NULL) {
10849 (void) fprintf(stderr, gettext("missing value in "
10850 "property=value argument\n"));
10851 usage(B_FALSE);
10854 *(cb.cb_value) = '\0';
10855 cb.cb_value++;
10856 argc -= 2;
10857 argv += 2;
10859 /* argv[0] is pool name */
10860 if (!is_pool(argv[0])) {
10861 (void) fprintf(stderr,
10862 gettext("cannot open '%s': is not a pool\n"), argv[0]);
10863 return (EINVAL);
10866 /* argv[1], when supplied, is vdev name */
10867 if (argc == 2) {
10869 if (strcmp(argv[1], "root") == 0)
10870 vdev = strdup("root-0");
10871 else
10872 vdev = strdup(argv[1]);
10874 if (!are_vdevs_in_pool(1, &vdev, argv[0], &cb.cb_vdevs)) {
10875 (void) fprintf(stderr, gettext(
10876 "cannot find '%s' in '%s': device not in pool\n"),
10877 vdev, argv[0]);
10878 free(vdev);
10879 return (EINVAL);
10881 cb.cb_vdevs.cb_names = &vdev;
10882 cb.cb_vdevs.cb_names_count = 1;
10883 cb.cb_type = ZFS_TYPE_VDEV;
10886 error = for_each_pool(1, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
10887 B_FALSE, set_callback, &cb);
10889 if (vdev != NULL)
10890 free(vdev);
10892 return (error);
10895 /* Add up the total number of bytes left to initialize/trim across all vdevs */
10896 static uint64_t
10897 vdev_activity_remaining(nvlist_t *nv, zpool_wait_activity_t activity)
10899 uint64_t bytes_remaining;
10900 nvlist_t **child;
10901 uint_t c, children;
10902 vdev_stat_t *vs;
10904 assert(activity == ZPOOL_WAIT_INITIALIZE ||
10905 activity == ZPOOL_WAIT_TRIM);
10907 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
10908 (uint64_t **)&vs, &c) == 0);
10910 if (activity == ZPOOL_WAIT_INITIALIZE &&
10911 vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE)
10912 bytes_remaining = vs->vs_initialize_bytes_est -
10913 vs->vs_initialize_bytes_done;
10914 else if (activity == ZPOOL_WAIT_TRIM &&
10915 vs->vs_trim_state == VDEV_TRIM_ACTIVE)
10916 bytes_remaining = vs->vs_trim_bytes_est -
10917 vs->vs_trim_bytes_done;
10918 else
10919 bytes_remaining = 0;
10921 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10922 &child, &children) != 0)
10923 children = 0;
10925 for (c = 0; c < children; c++)
10926 bytes_remaining += vdev_activity_remaining(child[c], activity);
10928 return (bytes_remaining);
10931 /* Add up the total number of bytes left to rebuild across top-level vdevs */
10932 static uint64_t
10933 vdev_activity_top_remaining(nvlist_t *nv)
10935 uint64_t bytes_remaining = 0;
10936 nvlist_t **child;
10937 uint_t children;
10938 int error;
10940 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10941 &child, &children) != 0)
10942 children = 0;
10944 for (uint_t c = 0; c < children; c++) {
10945 vdev_rebuild_stat_t *vrs;
10946 uint_t i;
10948 error = nvlist_lookup_uint64_array(child[c],
10949 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i);
10950 if (error == 0) {
10951 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
10952 bytes_remaining += (vrs->vrs_bytes_est -
10953 vrs->vrs_bytes_rebuilt);
10958 return (bytes_remaining);
10961 /* Whether any vdevs are 'spare' or 'replacing' vdevs */
10962 static boolean_t
10963 vdev_any_spare_replacing(nvlist_t *nv)
10965 nvlist_t **child;
10966 uint_t c, children;
10967 const char *vdev_type;
10969 (void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &vdev_type);
10971 if (strcmp(vdev_type, VDEV_TYPE_REPLACING) == 0 ||
10972 strcmp(vdev_type, VDEV_TYPE_SPARE) == 0 ||
10973 strcmp(vdev_type, VDEV_TYPE_DRAID_SPARE) == 0) {
10974 return (B_TRUE);
10977 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
10978 &child, &children) != 0)
10979 children = 0;
10981 for (c = 0; c < children; c++) {
10982 if (vdev_any_spare_replacing(child[c]))
10983 return (B_TRUE);
10986 return (B_FALSE);
10989 typedef struct wait_data {
10990 char *wd_poolname;
10991 boolean_t wd_scripted;
10992 boolean_t wd_exact;
10993 boolean_t wd_headers_once;
10994 boolean_t wd_should_exit;
10995 /* Which activities to wait for */
10996 boolean_t wd_enabled[ZPOOL_WAIT_NUM_ACTIVITIES];
10997 float wd_interval;
10998 pthread_cond_t wd_cv;
10999 pthread_mutex_t wd_mutex;
11000 } wait_data_t;
11003 * Print to stdout a single line, containing one column for each activity that
11004 * we are waiting for specifying how many bytes of work are left for that
11005 * activity.
11007 static void
11008 print_wait_status_row(wait_data_t *wd, zpool_handle_t *zhp, int row)
11010 nvlist_t *config, *nvroot;
11011 uint_t c;
11012 int i;
11013 pool_checkpoint_stat_t *pcs = NULL;
11014 pool_scan_stat_t *pss = NULL;
11015 pool_removal_stat_t *prs = NULL;
11016 const char *const headers[] = {"DISCARD", "FREE", "INITIALIZE",
11017 "REPLACE", "REMOVE", "RESILVER", "SCRUB", "TRIM"};
11018 int col_widths[ZPOOL_WAIT_NUM_ACTIVITIES];
11020 /* Calculate the width of each column */
11021 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
11023 * Make sure we have enough space in the col for pretty-printed
11024 * numbers and for the column header, and then leave a couple
11025 * spaces between cols for readability.
11027 col_widths[i] = MAX(strlen(headers[i]), 6) + 2;
11030 if (timestamp_fmt != NODATE)
11031 print_timestamp(timestamp_fmt);
11033 /* Print header if appropriate */
11034 int term_height = terminal_height();
11035 boolean_t reprint_header = (!wd->wd_headers_once && term_height > 0 &&
11036 row % (term_height-1) == 0);
11037 if (!wd->wd_scripted && (row == 0 || reprint_header)) {
11038 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
11039 if (wd->wd_enabled[i])
11040 (void) printf("%*s", col_widths[i], headers[i]);
11042 (void) fputc('\n', stdout);
11045 /* Bytes of work remaining in each activity */
11046 int64_t bytes_rem[ZPOOL_WAIT_NUM_ACTIVITIES] = {0};
11048 bytes_rem[ZPOOL_WAIT_FREE] =
11049 zpool_get_prop_int(zhp, ZPOOL_PROP_FREEING, NULL);
11051 config = zpool_get_config(zhp, NULL);
11052 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
11054 (void) nvlist_lookup_uint64_array(nvroot,
11055 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
11056 if (pcs != NULL && pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
11057 bytes_rem[ZPOOL_WAIT_CKPT_DISCARD] = pcs->pcs_space;
11059 (void) nvlist_lookup_uint64_array(nvroot,
11060 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
11061 if (prs != NULL && prs->prs_state == DSS_SCANNING)
11062 bytes_rem[ZPOOL_WAIT_REMOVE] = prs->prs_to_copy -
11063 prs->prs_copied;
11065 (void) nvlist_lookup_uint64_array(nvroot,
11066 ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&pss, &c);
11067 if (pss != NULL && pss->pss_state == DSS_SCANNING &&
11068 pss->pss_pass_scrub_pause == 0) {
11069 int64_t rem = pss->pss_to_examine - pss->pss_issued;
11070 if (pss->pss_func == POOL_SCAN_SCRUB)
11071 bytes_rem[ZPOOL_WAIT_SCRUB] = rem;
11072 else
11073 bytes_rem[ZPOOL_WAIT_RESILVER] = rem;
11074 } else if (check_rebuilding(nvroot, NULL)) {
11075 bytes_rem[ZPOOL_WAIT_RESILVER] =
11076 vdev_activity_top_remaining(nvroot);
11079 bytes_rem[ZPOOL_WAIT_INITIALIZE] =
11080 vdev_activity_remaining(nvroot, ZPOOL_WAIT_INITIALIZE);
11081 bytes_rem[ZPOOL_WAIT_TRIM] =
11082 vdev_activity_remaining(nvroot, ZPOOL_WAIT_TRIM);
11085 * A replace finishes after resilvering finishes, so the amount of work
11086 * left for a replace is the same as for resilvering.
11088 * It isn't quite correct to say that if we have any 'spare' or
11089 * 'replacing' vdevs and a resilver is happening, then a replace is in
11090 * progress, like we do here. When a hot spare is used, the faulted vdev
11091 * is not removed after the hot spare is resilvered, so parent 'spare'
11092 * vdev is not removed either. So we could have a 'spare' vdev, but be
11093 * resilvering for a different reason. However, we use it as a heuristic
11094 * because we don't have access to the DTLs, which could tell us whether
11095 * or not we have really finished resilvering a hot spare.
11097 if (vdev_any_spare_replacing(nvroot))
11098 bytes_rem[ZPOOL_WAIT_REPLACE] = bytes_rem[ZPOOL_WAIT_RESILVER];
11100 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
11101 char buf[64];
11102 if (!wd->wd_enabled[i])
11103 continue;
11105 if (wd->wd_exact)
11106 (void) snprintf(buf, sizeof (buf), "%" PRIi64,
11107 bytes_rem[i]);
11108 else
11109 zfs_nicenum(bytes_rem[i], buf, sizeof (buf));
11111 if (wd->wd_scripted)
11112 (void) printf(i == 0 ? "%s" : "\t%s", buf);
11113 else
11114 (void) printf(" %*s", col_widths[i] - 1, buf);
11116 (void) printf("\n");
11117 (void) fflush(stdout);
11120 static void *
11121 wait_status_thread(void *arg)
11123 wait_data_t *wd = (wait_data_t *)arg;
11124 zpool_handle_t *zhp;
11126 if ((zhp = zpool_open(g_zfs, wd->wd_poolname)) == NULL)
11127 return (void *)(1);
11129 for (int row = 0; ; row++) {
11130 boolean_t missing;
11131 struct timespec timeout;
11132 int ret = 0;
11133 (void) clock_gettime(CLOCK_REALTIME, &timeout);
11135 if (zpool_refresh_stats(zhp, &missing) != 0 || missing ||
11136 zpool_props_refresh(zhp) != 0) {
11137 zpool_close(zhp);
11138 return (void *)(uintptr_t)(missing ? 0 : 1);
11141 print_wait_status_row(wd, zhp, row);
11143 timeout.tv_sec += floor(wd->wd_interval);
11144 long nanos = timeout.tv_nsec +
11145 (wd->wd_interval - floor(wd->wd_interval)) * NANOSEC;
11146 if (nanos >= NANOSEC) {
11147 timeout.tv_sec++;
11148 timeout.tv_nsec = nanos - NANOSEC;
11149 } else {
11150 timeout.tv_nsec = nanos;
11152 pthread_mutex_lock(&wd->wd_mutex);
11153 if (!wd->wd_should_exit)
11154 ret = pthread_cond_timedwait(&wd->wd_cv, &wd->wd_mutex,
11155 &timeout);
11156 pthread_mutex_unlock(&wd->wd_mutex);
11157 if (ret == 0) {
11158 break; /* signaled by main thread */
11159 } else if (ret != ETIMEDOUT) {
11160 (void) fprintf(stderr, gettext("pthread_cond_timedwait "
11161 "failed: %s\n"), strerror(ret));
11162 zpool_close(zhp);
11163 return (void *)(uintptr_t)(1);
11167 zpool_close(zhp);
11168 return (void *)(0);
11172 zpool_do_wait(int argc, char **argv)
11174 boolean_t verbose = B_FALSE;
11175 int c, i;
11176 unsigned long count;
11177 pthread_t status_thr;
11178 int error = 0;
11179 zpool_handle_t *zhp;
11181 wait_data_t wd;
11182 wd.wd_scripted = B_FALSE;
11183 wd.wd_exact = B_FALSE;
11184 wd.wd_headers_once = B_FALSE;
11185 wd.wd_should_exit = B_FALSE;
11187 pthread_mutex_init(&wd.wd_mutex, NULL);
11188 pthread_cond_init(&wd.wd_cv, NULL);
11190 /* By default, wait for all types of activity. */
11191 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++)
11192 wd.wd_enabled[i] = B_TRUE;
11194 while ((c = getopt(argc, argv, "HpT:t:")) != -1) {
11195 switch (c) {
11196 case 'H':
11197 wd.wd_scripted = B_TRUE;
11198 break;
11199 case 'n':
11200 wd.wd_headers_once = B_TRUE;
11201 break;
11202 case 'p':
11203 wd.wd_exact = B_TRUE;
11204 break;
11205 case 'T':
11206 get_timestamp_arg(*optarg);
11207 break;
11208 case 't':
11209 /* Reset activities array */
11210 memset(&wd.wd_enabled, 0, sizeof (wd.wd_enabled));
11212 for (char *tok; (tok = strsep(&optarg, ",")); ) {
11213 static const char *const col_opts[] = {
11214 "discard", "free", "initialize", "replace",
11215 "remove", "resilver", "scrub", "trim" };
11217 for (i = 0; i < ARRAY_SIZE(col_opts); ++i)
11218 if (strcmp(tok, col_opts[i]) == 0) {
11219 wd.wd_enabled[i] = B_TRUE;
11220 goto found;
11223 (void) fprintf(stderr,
11224 gettext("invalid activity '%s'\n"), tok);
11225 usage(B_FALSE);
11226 found:;
11228 break;
11229 case '?':
11230 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
11231 optopt);
11232 usage(B_FALSE);
11236 argc -= optind;
11237 argv += optind;
11239 get_interval_count(&argc, argv, &wd.wd_interval, &count);
11240 if (count != 0) {
11241 /* This subcmd only accepts an interval, not a count */
11242 (void) fprintf(stderr, gettext("too many arguments\n"));
11243 usage(B_FALSE);
11246 if (wd.wd_interval != 0)
11247 verbose = B_TRUE;
11249 if (argc < 1) {
11250 (void) fprintf(stderr, gettext("missing 'pool' argument\n"));
11251 usage(B_FALSE);
11253 if (argc > 1) {
11254 (void) fprintf(stderr, gettext("too many arguments\n"));
11255 usage(B_FALSE);
11258 wd.wd_poolname = argv[0];
11260 if ((zhp = zpool_open(g_zfs, wd.wd_poolname)) == NULL)
11261 return (1);
11263 if (verbose) {
11265 * We use a separate thread for printing status updates because
11266 * the main thread will call lzc_wait(), which blocks as long
11267 * as an activity is in progress, which can be a long time.
11269 if (pthread_create(&status_thr, NULL, wait_status_thread, &wd)
11270 != 0) {
11271 (void) fprintf(stderr, gettext("failed to create status"
11272 "thread: %s\n"), strerror(errno));
11273 zpool_close(zhp);
11274 return (1);
11279 * Loop over all activities that we are supposed to wait for until none
11280 * of them are in progress. Note that this means we can end up waiting
11281 * for more activities to complete than just those that were in progress
11282 * when we began waiting; if an activity we are interested in begins
11283 * while we are waiting for another activity, we will wait for both to
11284 * complete before exiting.
11286 for (;;) {
11287 boolean_t missing = B_FALSE;
11288 boolean_t any_waited = B_FALSE;
11290 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
11291 boolean_t waited;
11293 if (!wd.wd_enabled[i])
11294 continue;
11296 error = zpool_wait_status(zhp, i, &missing, &waited);
11297 if (error != 0 || missing)
11298 break;
11300 any_waited = (any_waited || waited);
11303 if (error != 0 || missing || !any_waited)
11304 break;
11307 zpool_close(zhp);
11309 if (verbose) {
11310 uintptr_t status;
11311 pthread_mutex_lock(&wd.wd_mutex);
11312 wd.wd_should_exit = B_TRUE;
11313 pthread_cond_signal(&wd.wd_cv);
11314 pthread_mutex_unlock(&wd.wd_mutex);
11315 (void) pthread_join(status_thr, (void *)&status);
11316 if (status != 0)
11317 error = status;
11320 pthread_mutex_destroy(&wd.wd_mutex);
11321 pthread_cond_destroy(&wd.wd_cv);
11322 return (error);
11325 static int
11326 find_command_idx(const char *command, int *idx)
11328 for (int i = 0; i < NCOMMAND; ++i) {
11329 if (command_table[i].name == NULL)
11330 continue;
11332 if (strcmp(command, command_table[i].name) == 0) {
11333 *idx = i;
11334 return (0);
11337 return (1);
11341 * Display version message
11343 static int
11344 zpool_do_version(int argc, char **argv)
11346 (void) argc, (void) argv;
11347 return (zfs_version_print() != 0);
11350 /* Display documentation */
11351 static int
11352 zpool_do_help(int argc, char **argv)
11354 char page[MAXNAMELEN];
11355 if (argc < 3 || strcmp(argv[2], "zpool") == 0)
11356 strcpy(page, "zpool");
11357 else if (strcmp(argv[2], "concepts") == 0 ||
11358 strcmp(argv[2], "props") == 0)
11359 snprintf(page, sizeof (page), "zpool%s", argv[2]);
11360 else
11361 snprintf(page, sizeof (page), "zpool-%s", argv[2]);
11363 execlp("man", "man", page, NULL);
11365 fprintf(stderr, "couldn't run man program: %s", strerror(errno));
11366 return (-1);
11370 * Do zpool_load_compat() and print error message on failure
11372 static zpool_compat_status_t
11373 zpool_do_load_compat(const char *compat, boolean_t *list)
11375 char report[1024];
11377 zpool_compat_status_t ret;
11379 ret = zpool_load_compat(compat, list, report, 1024);
11380 switch (ret) {
11382 case ZPOOL_COMPATIBILITY_OK:
11383 break;
11385 case ZPOOL_COMPATIBILITY_NOFILES:
11386 case ZPOOL_COMPATIBILITY_BADFILE:
11387 case ZPOOL_COMPATIBILITY_BADTOKEN:
11388 (void) fprintf(stderr, "Error: %s\n", report);
11389 break;
11391 case ZPOOL_COMPATIBILITY_WARNTOKEN:
11392 (void) fprintf(stderr, "Warning: %s\n", report);
11393 ret = ZPOOL_COMPATIBILITY_OK;
11394 break;
11396 return (ret);
11400 main(int argc, char **argv)
11402 int ret = 0;
11403 int i = 0;
11404 char *cmdname;
11405 char **newargv;
11407 (void) setlocale(LC_ALL, "");
11408 (void) setlocale(LC_NUMERIC, "C");
11409 (void) textdomain(TEXT_DOMAIN);
11410 srand(time(NULL));
11412 opterr = 0;
11415 * Make sure the user has specified some command.
11417 if (argc < 2) {
11418 (void) fprintf(stderr, gettext("missing command\n"));
11419 usage(B_FALSE);
11422 cmdname = argv[1];
11425 * Special case '-?'
11427 if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
11428 usage(B_TRUE);
11431 * Special case '-V|--version'
11433 if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
11434 return (zpool_do_version(argc, argv));
11437 * Special case 'help'
11439 if (strcmp(cmdname, "help") == 0)
11440 return (zpool_do_help(argc, argv));
11442 if ((g_zfs = libzfs_init()) == NULL) {
11443 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
11444 return (1);
11447 libzfs_print_on_error(g_zfs, B_TRUE);
11449 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
11452 * Many commands modify input strings for string parsing reasons.
11453 * We create a copy to protect the original argv.
11455 newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
11456 for (i = 0; i < argc; i++)
11457 newargv[i] = strdup(argv[i]);
11458 newargv[argc] = NULL;
11461 * Run the appropriate command.
11463 if (find_command_idx(cmdname, &i) == 0) {
11464 current_command = &command_table[i];
11465 ret = command_table[i].func(argc - 1, newargv + 1);
11466 } else if (strchr(cmdname, '=')) {
11467 verify(find_command_idx("set", &i) == 0);
11468 current_command = &command_table[i];
11469 ret = command_table[i].func(argc, newargv);
11470 } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
11472 * 'freeze' is a vile debugging abomination, so we treat
11473 * it as such.
11475 zfs_cmd_t zc = {"\0"};
11477 (void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
11478 ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
11479 if (ret != 0) {
11480 (void) fprintf(stderr,
11481 gettext("failed to freeze pool: %d\n"), errno);
11482 ret = 1;
11485 log_history = 0;
11486 } else {
11487 (void) fprintf(stderr, gettext("unrecognized "
11488 "command '%s'\n"), cmdname);
11489 usage(B_FALSE);
11490 ret = 1;
11493 for (i = 0; i < argc; i++)
11494 free(newargv[i]);
11495 free(newargv);
11497 if (ret == 0 && log_history)
11498 (void) zpool_log_history(g_zfs, history_str);
11500 libzfs_fini(g_zfs);
11503 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
11504 * for the purposes of running ::findleaks.
11506 if (getenv("ZFS_ABORT") != NULL) {
11507 (void) printf("dumping core by request\n");
11508 abort();
11511 return (ret);