Prebaked scripts for zpool status/iostat -c
[zfs.git] / cmd / zpool / zpool_main.c
blob4b67bfde0e1b460e6ff1fee5941282562957f92a
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 http://www.opensolaris.org/os/licensing.
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, 2015 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>.
32 #include <assert.h>
33 #include <ctype.h>
34 #include <dirent.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <libgen.h>
38 #include <libintl.h>
39 #include <libuutil.h>
40 #include <locale.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <strings.h>
45 #include <unistd.h>
46 #include <pwd.h>
47 #include <zone.h>
48 #include <sys/wait.h>
49 #include <zfs_prop.h>
50 #include <sys/fs/zfs.h>
51 #include <sys/stat.h>
52 #include <sys/fm/fs/zfs.h>
53 #include <sys/fm/util.h>
54 #include <sys/fm/protocol.h>
55 #include <sys/zfs_ioctl.h>
57 #include <math.h>
59 #include <libzfs.h>
61 #include "zpool_util.h"
62 #include "zfs_comutil.h"
63 #include "zfeature_common.h"
65 #include "statcommon.h"
67 static int zpool_do_create(int, char **);
68 static int zpool_do_destroy(int, char **);
70 static int zpool_do_add(int, char **);
71 static int zpool_do_remove(int, char **);
72 static int zpool_do_labelclear(int, char **);
74 static int zpool_do_list(int, char **);
75 static int zpool_do_iostat(int, char **);
76 static int zpool_do_status(int, char **);
78 static int zpool_do_online(int, char **);
79 static int zpool_do_offline(int, char **);
80 static int zpool_do_clear(int, char **);
81 static int zpool_do_reopen(int, char **);
83 static int zpool_do_reguid(int, char **);
85 static int zpool_do_attach(int, char **);
86 static int zpool_do_detach(int, char **);
87 static int zpool_do_replace(int, char **);
88 static int zpool_do_split(int, char **);
90 static int zpool_do_scrub(int, char **);
92 static int zpool_do_import(int, char **);
93 static int zpool_do_export(int, char **);
95 static int zpool_do_upgrade(int, char **);
97 static int zpool_do_history(int, char **);
98 static int zpool_do_events(int, char **);
100 static int zpool_do_get(int, char **);
101 static int zpool_do_set(int, char **);
104 * These libumem hooks provide a reasonable set of defaults for the allocator's
105 * debugging facilities.
108 #ifdef DEBUG
109 const char *
110 _umem_debug_init(void)
112 return ("default,verbose"); /* $UMEM_DEBUG setting */
115 const char *
116 _umem_logging_init(void)
118 return ("fail,contents"); /* $UMEM_LOGGING setting */
120 #endif
122 typedef enum {
123 HELP_ADD,
124 HELP_ATTACH,
125 HELP_CLEAR,
126 HELP_CREATE,
127 HELP_DESTROY,
128 HELP_DETACH,
129 HELP_EXPORT,
130 HELP_HISTORY,
131 HELP_IMPORT,
132 HELP_IOSTAT,
133 HELP_LABELCLEAR,
134 HELP_LIST,
135 HELP_OFFLINE,
136 HELP_ONLINE,
137 HELP_REPLACE,
138 HELP_REMOVE,
139 HELP_SCRUB,
140 HELP_STATUS,
141 HELP_UPGRADE,
142 HELP_EVENTS,
143 HELP_GET,
144 HELP_SET,
145 HELP_SPLIT,
146 HELP_REGUID,
147 HELP_REOPEN
148 } zpool_help_t;
152 * Flags for stats to display with "zpool iostats"
154 enum iostat_type {
155 IOS_DEFAULT = 0,
156 IOS_LATENCY = 1,
157 IOS_QUEUES = 2,
158 IOS_L_HISTO = 3,
159 IOS_RQ_HISTO = 4,
160 IOS_COUNT, /* always last element */
163 /* iostat_type entries as bitmasks */
164 #define IOS_DEFAULT_M (1ULL << IOS_DEFAULT)
165 #define IOS_LATENCY_M (1ULL << IOS_LATENCY)
166 #define IOS_QUEUES_M (1ULL << IOS_QUEUES)
167 #define IOS_L_HISTO_M (1ULL << IOS_L_HISTO)
168 #define IOS_RQ_HISTO_M (1ULL << IOS_RQ_HISTO)
170 /* Mask of all the histo bits */
171 #define IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
174 * Lookup table for iostat flags to nvlist names. Basically a list
175 * of all the nvlists a flag requires. Also specifies the order in
176 * which data gets printed in zpool iostat.
178 static const char *vsx_type_to_nvlist[IOS_COUNT][11] = {
179 [IOS_L_HISTO] = {
180 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
181 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
182 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
183 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
184 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
185 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
186 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
187 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
188 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
189 NULL},
190 [IOS_LATENCY] = {
191 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
192 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
193 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
194 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
195 NULL},
196 [IOS_QUEUES] = {
197 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
198 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
199 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
200 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
201 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
202 NULL},
203 [IOS_RQ_HISTO] = {
204 ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
205 ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
206 ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
207 ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
208 ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
209 ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
210 ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
211 ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
212 ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
213 ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
214 NULL},
219 * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
220 * Right now, only one histo bit is ever set at one time, so we can
221 * just do a highbit64(a)
223 #define IOS_HISTO_IDX(a) (highbit64(a & IOS_ANYHISTO_M) - 1)
225 typedef struct zpool_command {
226 const char *name;
227 int (*func)(int, char **);
228 zpool_help_t usage;
229 } zpool_command_t;
232 * Master command table. Each ZFS command has a name, associated function, and
233 * usage message. The usage messages need to be internationalized, so we have
234 * to have a function to return the usage message based on a command index.
236 * These commands are organized according to how they are displayed in the usage
237 * message. An empty command (one with a NULL name) indicates an empty line in
238 * the generic usage message.
240 static zpool_command_t command_table[] = {
241 { "create", zpool_do_create, HELP_CREATE },
242 { "destroy", zpool_do_destroy, HELP_DESTROY },
243 { NULL },
244 { "add", zpool_do_add, HELP_ADD },
245 { "remove", zpool_do_remove, HELP_REMOVE },
246 { NULL },
247 { "labelclear", zpool_do_labelclear, HELP_LABELCLEAR },
248 { NULL },
249 { "list", zpool_do_list, HELP_LIST },
250 { "iostat", zpool_do_iostat, HELP_IOSTAT },
251 { "status", zpool_do_status, HELP_STATUS },
252 { NULL },
253 { "online", zpool_do_online, HELP_ONLINE },
254 { "offline", zpool_do_offline, HELP_OFFLINE },
255 { "clear", zpool_do_clear, HELP_CLEAR },
256 { "reopen", zpool_do_reopen, HELP_REOPEN },
257 { NULL },
258 { "attach", zpool_do_attach, HELP_ATTACH },
259 { "detach", zpool_do_detach, HELP_DETACH },
260 { "replace", zpool_do_replace, HELP_REPLACE },
261 { "split", zpool_do_split, HELP_SPLIT },
262 { NULL },
263 { "scrub", zpool_do_scrub, HELP_SCRUB },
264 { NULL },
265 { "import", zpool_do_import, HELP_IMPORT },
266 { "export", zpool_do_export, HELP_EXPORT },
267 { "upgrade", zpool_do_upgrade, HELP_UPGRADE },
268 { "reguid", zpool_do_reguid, HELP_REGUID },
269 { NULL },
270 { "history", zpool_do_history, HELP_HISTORY },
271 { "events", zpool_do_events, HELP_EVENTS },
272 { NULL },
273 { "get", zpool_do_get, HELP_GET },
274 { "set", zpool_do_set, HELP_SET },
277 #define NCOMMAND (ARRAY_SIZE(command_table))
279 static zpool_command_t *current_command;
280 static char history_str[HIS_MAX_RECORD_LEN];
281 static boolean_t log_history = B_TRUE;
282 static uint_t timestamp_fmt = NODATE;
284 static const char *
285 get_usage(zpool_help_t idx)
287 switch (idx) {
288 case HELP_ADD:
289 return (gettext("\tadd [-fgLnP] [-o property=value] "
290 "<pool> <vdev> ...\n"));
291 case HELP_ATTACH:
292 return (gettext("\tattach [-f] [-o property=value] "
293 "<pool> <device> <new-device>\n"));
294 case HELP_CLEAR:
295 return (gettext("\tclear [-nF] <pool> [device]\n"));
296 case HELP_CREATE:
297 return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
298 "\t [-O file-system-property=value] ... \n"
299 "\t [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
300 case HELP_DESTROY:
301 return (gettext("\tdestroy [-f] <pool>\n"));
302 case HELP_DETACH:
303 return (gettext("\tdetach <pool> <device>\n"));
304 case HELP_EXPORT:
305 return (gettext("\texport [-af] <pool> ...\n"));
306 case HELP_HISTORY:
307 return (gettext("\thistory [-il] [<pool>] ...\n"));
308 case HELP_IMPORT:
309 return (gettext("\timport [-d dir] [-D]\n"
310 "\timport [-d dir | -c cachefile] [-F [-n]] <pool | id>\n"
311 "\timport [-o mntopts] [-o property=value] ... \n"
312 "\t [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
313 "[-R root] [-F [-n]] -a\n"
314 "\timport [-o mntopts] [-o property=value] ... \n"
315 "\t [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
316 "[-R root] [-F [-n]]\n"
317 "\t <pool | id> [newpool]\n"));
318 case HELP_IOSTAT:
319 return (gettext("\tiostat [[[-c [script1,script2,...]"
320 "[-lq]]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
321 "\t [[pool ...]|[pool vdev ...]|[vdev ...]]"
322 " [interval [count]]\n"));
323 case HELP_LABELCLEAR:
324 return (gettext("\tlabelclear [-f] <vdev>\n"));
325 case HELP_LIST:
326 return (gettext("\tlist [-gHLpPv] [-o property[,...]] "
327 "[-T d|u] [pool] ... [interval [count]]\n"));
328 case HELP_OFFLINE:
329 return (gettext("\toffline [-t] <pool> <device> ...\n"));
330 case HELP_ONLINE:
331 return (gettext("\tonline <pool> <device> ...\n"));
332 case HELP_REPLACE:
333 return (gettext("\treplace [-f] [-o property=value] "
334 "<pool> <device> [new-device]\n"));
335 case HELP_REMOVE:
336 return (gettext("\tremove <pool> <device> ...\n"));
337 case HELP_REOPEN:
338 return (gettext("\treopen <pool>\n"));
339 case HELP_SCRUB:
340 return (gettext("\tscrub [-s] <pool> ...\n"));
341 case HELP_STATUS:
342 return (gettext("\tstatus [-c [script1,script2,...]] [-gLPvxD]"
343 "[-T d|u] [pool] ... [interval [count]]\n"));
344 case HELP_UPGRADE:
345 return (gettext("\tupgrade\n"
346 "\tupgrade -v\n"
347 "\tupgrade [-V version] <-a | pool ...>\n"));
348 case HELP_EVENTS:
349 return (gettext("\tevents [-vHfc]\n"));
350 case HELP_GET:
351 return (gettext("\tget [-Hp] [-o \"all\" | field[,...]] "
352 "<\"all\" | property[,...]> <pool> ...\n"));
353 case HELP_SET:
354 return (gettext("\tset <property=value> <pool> \n"));
355 case HELP_SPLIT:
356 return (gettext("\tsplit [-gLnP] [-R altroot] [-o mntopts]\n"
357 "\t [-o property=value] <pool> <newpool> "
358 "[<device> ...]\n"));
359 case HELP_REGUID:
360 return (gettext("\treguid <pool>\n"));
363 abort();
364 /* NOTREACHED */
369 * Callback routine that will print out a pool property value.
371 static int
372 print_prop_cb(int prop, void *cb)
374 FILE *fp = cb;
376 (void) fprintf(fp, "\t%-15s ", zpool_prop_to_name(prop));
378 if (zpool_prop_readonly(prop))
379 (void) fprintf(fp, " NO ");
380 else
381 (void) fprintf(fp, " YES ");
383 if (zpool_prop_values(prop) == NULL)
384 (void) fprintf(fp, "-\n");
385 else
386 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
388 return (ZPROP_CONT);
392 * Display usage message. If we're inside a command, display only the usage for
393 * that command. Otherwise, iterate over the entire command table and display
394 * a complete usage message.
396 void
397 usage(boolean_t requested)
399 FILE *fp = requested ? stdout : stderr;
401 if (current_command == NULL) {
402 int i;
404 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
405 (void) fprintf(fp,
406 gettext("where 'command' is one of the following:\n\n"));
408 for (i = 0; i < NCOMMAND; i++) {
409 if (command_table[i].name == NULL)
410 (void) fprintf(fp, "\n");
411 else
412 (void) fprintf(fp, "%s",
413 get_usage(command_table[i].usage));
415 } else {
416 (void) fprintf(fp, gettext("usage:\n"));
417 (void) fprintf(fp, "%s", get_usage(current_command->usage));
420 if (current_command != NULL &&
421 ((strcmp(current_command->name, "set") == 0) ||
422 (strcmp(current_command->name, "get") == 0) ||
423 (strcmp(current_command->name, "list") == 0))) {
425 (void) fprintf(fp,
426 gettext("\nthe following properties are supported:\n"));
428 (void) fprintf(fp, "\n\t%-15s %s %s\n\n",
429 "PROPERTY", "EDIT", "VALUES");
431 /* Iterate over all properties */
432 (void) zprop_iter(print_prop_cb, fp, B_FALSE, B_TRUE,
433 ZFS_TYPE_POOL);
435 (void) fprintf(fp, "\t%-15s ", "feature@...");
436 (void) fprintf(fp, "YES disabled | enabled | active\n");
438 (void) fprintf(fp, gettext("\nThe feature@ properties must be "
439 "appended with a feature name.\nSee zpool-features(5).\n"));
443 * See comments at end of main().
445 if (getenv("ZFS_ABORT") != NULL) {
446 (void) printf("dumping core by request\n");
447 abort();
450 exit(requested ? 0 : 2);
453 void
454 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
455 boolean_t print_logs, int name_flags)
457 nvlist_t **child;
458 uint_t c, children;
459 char *vname;
461 if (name != NULL)
462 (void) printf("\t%*s%s\n", indent, "", name);
464 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
465 &child, &children) != 0)
466 return;
468 for (c = 0; c < children; c++) {
469 uint64_t is_log = B_FALSE;
471 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
472 &is_log);
473 if ((is_log && !print_logs) || (!is_log && print_logs))
474 continue;
476 vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
477 print_vdev_tree(zhp, vname, child[c], indent + 2,
478 B_FALSE, name_flags);
479 free(vname);
483 static boolean_t
484 prop_list_contains_feature(nvlist_t *proplist)
486 nvpair_t *nvp;
487 for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
488 nvp = nvlist_next_nvpair(proplist, nvp)) {
489 if (zpool_prop_feature(nvpair_name(nvp)))
490 return (B_TRUE);
492 return (B_FALSE);
496 * Add a property pair (name, string-value) into a property nvlist.
498 static int
499 add_prop_list(const char *propname, char *propval, nvlist_t **props,
500 boolean_t poolprop)
502 zpool_prop_t prop = ZPROP_INVAL;
503 zfs_prop_t fprop;
504 nvlist_t *proplist;
505 const char *normnm;
506 char *strval;
508 if (*props == NULL &&
509 nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
510 (void) fprintf(stderr,
511 gettext("internal error: out of memory\n"));
512 return (1);
515 proplist = *props;
517 if (poolprop) {
518 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
520 if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL &&
521 !zpool_prop_feature(propname)) {
522 (void) fprintf(stderr, gettext("property '%s' is "
523 "not a valid pool property\n"), propname);
524 return (2);
528 * feature@ properties and version should not be specified
529 * at the same time.
531 if ((prop == ZPROP_INVAL && zpool_prop_feature(propname) &&
532 nvlist_exists(proplist, vname)) ||
533 (prop == ZPOOL_PROP_VERSION &&
534 prop_list_contains_feature(proplist))) {
535 (void) fprintf(stderr, gettext("'feature@' and "
536 "'version' properties cannot be specified "
537 "together\n"));
538 return (2);
542 if (zpool_prop_feature(propname))
543 normnm = propname;
544 else
545 normnm = zpool_prop_to_name(prop);
546 } else {
547 if ((fprop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
548 normnm = zfs_prop_to_name(fprop);
549 } else {
550 normnm = propname;
554 if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
555 prop != ZPOOL_PROP_CACHEFILE) {
556 (void) fprintf(stderr, gettext("property '%s' "
557 "specified multiple times\n"), propname);
558 return (2);
561 if (nvlist_add_string(proplist, normnm, propval) != 0) {
562 (void) fprintf(stderr, gettext("internal "
563 "error: out of memory\n"));
564 return (1);
567 return (0);
571 * Set a default property pair (name, string-value) in a property nvlist
573 static int
574 add_prop_list_default(const char *propname, char *propval, nvlist_t **props,
575 boolean_t poolprop)
577 char *pval;
579 if (nvlist_lookup_string(*props, propname, &pval) == 0)
580 return (0);
582 return (add_prop_list(propname, propval, props, B_TRUE));
586 * zpool add [-fgLnP] [-o property=value] <pool> <vdev> ...
588 * -f Force addition of devices, even if they appear in use
589 * -g Display guid for individual vdev name.
590 * -L Follow links when resolving vdev path name.
591 * -n Do not add the devices, but display the resulting layout if
592 * they were to be added.
593 * -o Set property=value.
594 * -P Display full path for vdev name.
596 * Adds the given vdevs to 'pool'. As with create, the bulk of this work is
597 * handled by get_vdev_spec(), which constructs the nvlist needed to pass to
598 * libzfs.
601 zpool_do_add(int argc, char **argv)
603 boolean_t force = B_FALSE;
604 boolean_t dryrun = B_FALSE;
605 int name_flags = 0;
606 int c;
607 nvlist_t *nvroot;
608 char *poolname;
609 int ret;
610 zpool_handle_t *zhp;
611 nvlist_t *config;
612 nvlist_t *props = NULL;
613 char *propval;
615 /* check options */
616 while ((c = getopt(argc, argv, "fgLno:P")) != -1) {
617 switch (c) {
618 case 'f':
619 force = B_TRUE;
620 break;
621 case 'g':
622 name_flags |= VDEV_NAME_GUID;
623 break;
624 case 'L':
625 name_flags |= VDEV_NAME_FOLLOW_LINKS;
626 break;
627 case 'n':
628 dryrun = B_TRUE;
629 break;
630 case 'o':
631 if ((propval = strchr(optarg, '=')) == NULL) {
632 (void) fprintf(stderr, gettext("missing "
633 "'=' for -o option\n"));
634 usage(B_FALSE);
636 *propval = '\0';
637 propval++;
639 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
640 (add_prop_list(optarg, propval, &props, B_TRUE)))
641 usage(B_FALSE);
642 break;
643 case 'P':
644 name_flags |= VDEV_NAME_PATH;
645 break;
646 case '?':
647 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
648 optopt);
649 usage(B_FALSE);
653 argc -= optind;
654 argv += optind;
656 /* get pool name and check number of arguments */
657 if (argc < 1) {
658 (void) fprintf(stderr, gettext("missing pool name argument\n"));
659 usage(B_FALSE);
661 if (argc < 2) {
662 (void) fprintf(stderr, gettext("missing vdev specification\n"));
663 usage(B_FALSE);
666 poolname = argv[0];
668 argc--;
669 argv++;
671 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
672 return (1);
674 if ((config = zpool_get_config(zhp, NULL)) == NULL) {
675 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
676 poolname);
677 zpool_close(zhp);
678 return (1);
681 /* pass off to get_vdev_spec for processing */
682 nvroot = make_root_vdev(zhp, props, force, !force, B_FALSE, dryrun,
683 argc, argv);
684 if (nvroot == NULL) {
685 zpool_close(zhp);
686 return (1);
689 if (dryrun) {
690 nvlist_t *poolnvroot;
691 nvlist_t **l2child;
692 uint_t l2children, c;
693 char *vname;
694 boolean_t hadcache = B_FALSE;
696 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
697 &poolnvroot) == 0);
699 (void) printf(gettext("would update '%s' to the following "
700 "configuration:\n"), zpool_get_name(zhp));
702 /* print original main pool and new tree */
703 print_vdev_tree(zhp, poolname, poolnvroot, 0, B_FALSE,
704 name_flags);
705 print_vdev_tree(zhp, NULL, nvroot, 0, B_FALSE, name_flags);
707 /* Do the same for the logs */
708 if (num_logs(poolnvroot) > 0) {
709 print_vdev_tree(zhp, "logs", poolnvroot, 0, B_TRUE,
710 name_flags);
711 print_vdev_tree(zhp, NULL, nvroot, 0, B_TRUE,
712 name_flags);
713 } else if (num_logs(nvroot) > 0) {
714 print_vdev_tree(zhp, "logs", nvroot, 0, B_TRUE,
715 name_flags);
718 /* Do the same for the caches */
719 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
720 &l2child, &l2children) == 0 && l2children) {
721 hadcache = B_TRUE;
722 (void) printf(gettext("\tcache\n"));
723 for (c = 0; c < l2children; c++) {
724 vname = zpool_vdev_name(g_zfs, NULL,
725 l2child[c], name_flags);
726 (void) printf("\t %s\n", vname);
727 free(vname);
730 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
731 &l2child, &l2children) == 0 && l2children) {
732 if (!hadcache)
733 (void) printf(gettext("\tcache\n"));
734 for (c = 0; c < l2children; c++) {
735 vname = zpool_vdev_name(g_zfs, NULL,
736 l2child[c], name_flags);
737 (void) printf("\t %s\n", vname);
738 free(vname);
742 ret = 0;
743 } else {
744 ret = (zpool_add(zhp, nvroot) != 0);
747 nvlist_free(props);
748 nvlist_free(nvroot);
749 zpool_close(zhp);
751 return (ret);
755 * zpool remove <pool> <vdev> ...
757 * Removes the given vdev from the pool. Currently, this supports removing
758 * spares, cache, and log devices from the pool.
761 zpool_do_remove(int argc, char **argv)
763 char *poolname;
764 int i, ret = 0;
765 zpool_handle_t *zhp = NULL;
767 argc--;
768 argv++;
770 /* get pool name and check number of arguments */
771 if (argc < 1) {
772 (void) fprintf(stderr, gettext("missing pool name argument\n"));
773 usage(B_FALSE);
775 if (argc < 2) {
776 (void) fprintf(stderr, gettext("missing device\n"));
777 usage(B_FALSE);
780 poolname = argv[0];
782 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
783 return (1);
785 for (i = 1; i < argc; i++) {
786 if (zpool_vdev_remove(zhp, argv[i]) != 0)
787 ret = 1;
789 zpool_close(zhp);
791 return (ret);
795 * zpool labelclear [-f] <vdev>
797 * -f Force clearing the label for the vdevs which are members of
798 * the exported or foreign pools.
800 * Verifies that the vdev is not active and zeros out the label information
801 * on the device.
804 zpool_do_labelclear(int argc, char **argv)
806 char vdev[MAXPATHLEN];
807 char *name = NULL;
808 struct stat st;
809 int c, fd = -1, ret = 0;
810 nvlist_t *config;
811 pool_state_t state;
812 boolean_t inuse = B_FALSE;
813 boolean_t force = B_FALSE;
815 /* check options */
816 while ((c = getopt(argc, argv, "f")) != -1) {
817 switch (c) {
818 case 'f':
819 force = B_TRUE;
820 break;
821 default:
822 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
823 optopt);
824 usage(B_FALSE);
828 argc -= optind;
829 argv += optind;
831 /* get vdev name */
832 if (argc < 1) {
833 (void) fprintf(stderr, gettext("missing vdev name\n"));
834 usage(B_FALSE);
836 if (argc > 1) {
837 (void) fprintf(stderr, gettext("too many arguments\n"));
838 usage(B_FALSE);
842 * Check if we were given absolute path and use it as is.
843 * Otherwise if the provided vdev name doesn't point to a file,
844 * try prepending expected disk paths and partition numbers.
846 (void) strlcpy(vdev, argv[0], sizeof (vdev));
847 if (vdev[0] != '/' && stat(vdev, &st) != 0) {
848 int error;
850 error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
851 if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
852 if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
853 error = ENOENT;
856 if (error || (stat(vdev, &st) != 0)) {
857 (void) fprintf(stderr, gettext(
858 "failed to find device %s, try specifying absolute "
859 "path instead\n"), argv[0]);
860 return (1);
864 if ((fd = open(vdev, O_RDWR)) < 0) {
865 (void) fprintf(stderr, gettext("failed to open %s: %s\n"),
866 vdev, strerror(errno));
867 return (1);
870 if (ioctl(fd, BLKFLSBUF) != 0)
871 (void) fprintf(stderr, gettext("failed to invalidate "
872 "cache for %s: %s\n"), vdev, strerror(errno));
874 if (zpool_read_label(fd, &config, NULL) != 0 || config == NULL) {
875 (void) fprintf(stderr,
876 gettext("failed to check state for %s\n"), vdev);
877 return (1);
879 nvlist_free(config);
881 ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
882 if (ret != 0) {
883 (void) fprintf(stderr,
884 gettext("failed to check state for %s\n"), vdev);
885 return (1);
888 if (!inuse)
889 goto wipe_label;
891 switch (state) {
892 default:
893 case POOL_STATE_ACTIVE:
894 case POOL_STATE_SPARE:
895 case POOL_STATE_L2CACHE:
896 (void) fprintf(stderr, gettext(
897 "%s is a member (%s) of pool \"%s\"\n"),
898 vdev, zpool_pool_state_to_name(state), name);
899 ret = 1;
900 goto errout;
902 case POOL_STATE_EXPORTED:
903 if (force)
904 break;
905 (void) fprintf(stderr, gettext(
906 "use '-f' to override the following error:\n"
907 "%s is a member of exported pool \"%s\"\n"),
908 vdev, name);
909 ret = 1;
910 goto errout;
912 case POOL_STATE_POTENTIALLY_ACTIVE:
913 if (force)
914 break;
915 (void) fprintf(stderr, gettext(
916 "use '-f' to override the following error:\n"
917 "%s is a member of potentially active pool \"%s\"\n"),
918 vdev, name);
919 ret = 1;
920 goto errout;
922 case POOL_STATE_DESTROYED:
923 /* inuse should never be set for a destroyed pool */
924 assert(0);
925 break;
928 wipe_label:
929 ret = zpool_clear_label(fd);
930 if (ret != 0) {
931 (void) fprintf(stderr,
932 gettext("failed to clear label for %s\n"), vdev);
935 errout:
936 free(name);
937 (void) close(fd);
939 return (ret);
943 * zpool create [-fnd] [-o property=value] ...
944 * [-O file-system-property=value] ...
945 * [-R root] [-m mountpoint] <pool> <dev> ...
947 * -f Force creation, even if devices appear in use
948 * -n Do not create the pool, but display the resulting layout if it
949 * were to be created.
950 * -R Create a pool under an alternate root
951 * -m Set default mountpoint for the root dataset. By default it's
952 * '/<pool>'
953 * -o Set property=value.
954 * -o Set feature@feature=enabled|disabled.
955 * -d Don't automatically enable all supported pool features
956 * (individual features can be enabled with -o).
957 * -O Set fsproperty=value in the pool's root file system
959 * Creates the named pool according to the given vdev specification. The
960 * bulk of the vdev processing is done in get_vdev_spec() in zpool_vdev.c. Once
961 * we get the nvlist back from get_vdev_spec(), we either print out the contents
962 * (if '-n' was specified), or pass it to libzfs to do the creation.
965 zpool_do_create(int argc, char **argv)
967 boolean_t force = B_FALSE;
968 boolean_t dryrun = B_FALSE;
969 boolean_t enable_all_pool_feat = B_TRUE;
970 int c;
971 nvlist_t *nvroot = NULL;
972 char *poolname;
973 char *tname = NULL;
974 int ret = 1;
975 char *altroot = NULL;
976 char *mountpoint = NULL;
977 nvlist_t *fsprops = NULL;
978 nvlist_t *props = NULL;
979 char *propval;
981 /* check options */
982 while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
983 switch (c) {
984 case 'f':
985 force = B_TRUE;
986 break;
987 case 'n':
988 dryrun = B_TRUE;
989 break;
990 case 'd':
991 enable_all_pool_feat = B_FALSE;
992 break;
993 case 'R':
994 altroot = optarg;
995 if (add_prop_list(zpool_prop_to_name(
996 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
997 goto errout;
998 if (add_prop_list_default(zpool_prop_to_name(
999 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1000 goto errout;
1001 break;
1002 case 'm':
1003 /* Equivalent to -O mountpoint=optarg */
1004 mountpoint = optarg;
1005 break;
1006 case 'o':
1007 if ((propval = strchr(optarg, '=')) == NULL) {
1008 (void) fprintf(stderr, gettext("missing "
1009 "'=' for -o option\n"));
1010 goto errout;
1012 *propval = '\0';
1013 propval++;
1015 if (add_prop_list(optarg, propval, &props, B_TRUE))
1016 goto errout;
1019 * If the user is creating a pool that doesn't support
1020 * feature flags, don't enable any features.
1022 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
1023 char *end;
1024 u_longlong_t ver;
1026 ver = strtoull(propval, &end, 10);
1027 if (*end == '\0' &&
1028 ver < SPA_VERSION_FEATURES) {
1029 enable_all_pool_feat = B_FALSE;
1032 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
1033 altroot = propval;
1034 break;
1035 case 'O':
1036 if ((propval = strchr(optarg, '=')) == NULL) {
1037 (void) fprintf(stderr, gettext("missing "
1038 "'=' for -O option\n"));
1039 goto errout;
1041 *propval = '\0';
1042 propval++;
1045 * Mountpoints are checked and then added later.
1046 * Uniquely among properties, they can be specified
1047 * more than once, to avoid conflict with -m.
1049 if (0 == strcmp(optarg,
1050 zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
1051 mountpoint = propval;
1052 } else if (add_prop_list(optarg, propval, &fsprops,
1053 B_FALSE)) {
1054 goto errout;
1056 break;
1057 case 't':
1059 * Sanity check temporary pool name.
1061 if (strchr(optarg, '/') != NULL) {
1062 (void) fprintf(stderr, gettext("cannot create "
1063 "'%s': invalid character '/' in temporary "
1064 "name\n"), optarg);
1065 (void) fprintf(stderr, gettext("use 'zfs "
1066 "create' to create a dataset\n"));
1067 goto errout;
1070 if (add_prop_list(zpool_prop_to_name(
1071 ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
1072 goto errout;
1073 if (add_prop_list_default(zpool_prop_to_name(
1074 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1075 goto errout;
1076 tname = optarg;
1077 break;
1078 case ':':
1079 (void) fprintf(stderr, gettext("missing argument for "
1080 "'%c' option\n"), optopt);
1081 goto badusage;
1082 case '?':
1083 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1084 optopt);
1085 goto badusage;
1089 argc -= optind;
1090 argv += optind;
1092 /* get pool name and check number of arguments */
1093 if (argc < 1) {
1094 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1095 goto badusage;
1097 if (argc < 2) {
1098 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1099 goto badusage;
1102 poolname = argv[0];
1105 * As a special case, check for use of '/' in the name, and direct the
1106 * user to use 'zfs create' instead.
1108 if (strchr(poolname, '/') != NULL) {
1109 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
1110 "character '/' in pool name\n"), poolname);
1111 (void) fprintf(stderr, gettext("use 'zfs create' to "
1112 "create a dataset\n"));
1113 goto errout;
1116 /* pass off to get_vdev_spec for bulk processing */
1117 nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
1118 argc - 1, argv + 1);
1119 if (nvroot == NULL)
1120 goto errout;
1122 /* make_root_vdev() allows 0 toplevel children if there are spares */
1123 if (!zfs_allocatable_devs(nvroot)) {
1124 (void) fprintf(stderr, gettext("invalid vdev "
1125 "specification: at least one toplevel vdev must be "
1126 "specified\n"));
1127 goto errout;
1130 if (altroot != NULL && altroot[0] != '/') {
1131 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
1132 "must be an absolute path\n"), altroot);
1133 goto errout;
1137 * Check the validity of the mountpoint and direct the user to use the
1138 * '-m' mountpoint option if it looks like its in use.
1140 if (mountpoint == NULL ||
1141 (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
1142 strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
1143 char buf[MAXPATHLEN];
1144 DIR *dirp;
1146 if (mountpoint && mountpoint[0] != '/') {
1147 (void) fprintf(stderr, gettext("invalid mountpoint "
1148 "'%s': must be an absolute path, 'legacy', or "
1149 "'none'\n"), mountpoint);
1150 goto errout;
1153 if (mountpoint == NULL) {
1154 if (altroot != NULL)
1155 (void) snprintf(buf, sizeof (buf), "%s/%s",
1156 altroot, poolname);
1157 else
1158 (void) snprintf(buf, sizeof (buf), "/%s",
1159 poolname);
1160 } else {
1161 if (altroot != NULL)
1162 (void) snprintf(buf, sizeof (buf), "%s%s",
1163 altroot, mountpoint);
1164 else
1165 (void) snprintf(buf, sizeof (buf), "%s",
1166 mountpoint);
1169 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
1170 (void) fprintf(stderr, gettext("mountpoint '%s' : "
1171 "%s\n"), buf, strerror(errno));
1172 (void) fprintf(stderr, gettext("use '-m' "
1173 "option to provide a different default\n"));
1174 goto errout;
1175 } else if (dirp) {
1176 int count = 0;
1178 while (count < 3 && readdir(dirp) != NULL)
1179 count++;
1180 (void) closedir(dirp);
1182 if (count > 2) {
1183 (void) fprintf(stderr, gettext("mountpoint "
1184 "'%s' exists and is not empty\n"), buf);
1185 (void) fprintf(stderr, gettext("use '-m' "
1186 "option to provide a "
1187 "different default\n"));
1188 goto errout;
1194 * Now that the mountpoint's validity has been checked, ensure that
1195 * the property is set appropriately prior to creating the pool.
1197 if (mountpoint != NULL) {
1198 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
1199 mountpoint, &fsprops, B_FALSE);
1200 if (ret != 0)
1201 goto errout;
1204 ret = 1;
1205 if (dryrun) {
1207 * For a dry run invocation, print out a basic message and run
1208 * through all the vdevs in the list and print out in an
1209 * appropriate hierarchy.
1211 (void) printf(gettext("would create '%s' with the "
1212 "following layout:\n\n"), poolname);
1214 print_vdev_tree(NULL, poolname, nvroot, 0, B_FALSE, 0);
1215 if (num_logs(nvroot) > 0)
1216 print_vdev_tree(NULL, "logs", nvroot, 0, B_TRUE, 0);
1218 ret = 0;
1219 } else {
1221 * Hand off to libzfs.
1223 spa_feature_t i;
1224 for (i = 0; i < SPA_FEATURES; i++) {
1225 char propname[MAXPATHLEN];
1226 char *propval;
1227 zfeature_info_t *feat = &spa_feature_table[i];
1229 (void) snprintf(propname, sizeof (propname),
1230 "feature@%s", feat->fi_uname);
1233 * Only features contained in props will be enabled:
1234 * remove from the nvlist every ZFS_FEATURE_DISABLED
1235 * value and add every missing ZFS_FEATURE_ENABLED if
1236 * enable_all_pool_feat is set.
1238 if (!nvlist_lookup_string(props, propname, &propval)) {
1239 if (strcmp(propval, ZFS_FEATURE_DISABLED) == 0)
1240 (void) nvlist_remove_all(props,
1241 propname);
1242 } else if (enable_all_pool_feat) {
1243 ret = add_prop_list(propname,
1244 ZFS_FEATURE_ENABLED, &props, B_TRUE);
1245 if (ret != 0)
1246 goto errout;
1250 ret = 1;
1251 if (zpool_create(g_zfs, poolname,
1252 nvroot, props, fsprops) == 0) {
1253 zfs_handle_t *pool = zfs_open(g_zfs,
1254 tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
1255 if (pool != NULL) {
1256 if (zfs_mount(pool, NULL, 0) == 0)
1257 ret = zfs_shareall(pool);
1258 zfs_close(pool);
1260 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
1261 (void) fprintf(stderr, gettext("pool name may have "
1262 "been omitted\n"));
1266 errout:
1267 nvlist_free(nvroot);
1268 nvlist_free(fsprops);
1269 nvlist_free(props);
1270 return (ret);
1271 badusage:
1272 nvlist_free(fsprops);
1273 nvlist_free(props);
1274 usage(B_FALSE);
1275 return (2);
1279 * zpool destroy <pool>
1281 * -f Forcefully unmount any datasets
1283 * Destroy the given pool. Automatically unmounts any datasets in the pool.
1286 zpool_do_destroy(int argc, char **argv)
1288 boolean_t force = B_FALSE;
1289 int c;
1290 char *pool;
1291 zpool_handle_t *zhp;
1292 int ret;
1294 /* check options */
1295 while ((c = getopt(argc, argv, "f")) != -1) {
1296 switch (c) {
1297 case 'f':
1298 force = B_TRUE;
1299 break;
1300 case '?':
1301 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1302 optopt);
1303 usage(B_FALSE);
1307 argc -= optind;
1308 argv += optind;
1310 /* check arguments */
1311 if (argc < 1) {
1312 (void) fprintf(stderr, gettext("missing pool argument\n"));
1313 usage(B_FALSE);
1315 if (argc > 1) {
1316 (void) fprintf(stderr, gettext("too many arguments\n"));
1317 usage(B_FALSE);
1320 pool = argv[0];
1322 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
1324 * As a special case, check for use of '/' in the name, and
1325 * direct the user to use 'zfs destroy' instead.
1327 if (strchr(pool, '/') != NULL)
1328 (void) fprintf(stderr, gettext("use 'zfs destroy' to "
1329 "destroy a dataset\n"));
1330 return (1);
1333 if (zpool_disable_datasets(zhp, force) != 0) {
1334 (void) fprintf(stderr, gettext("could not destroy '%s': "
1335 "could not unmount datasets\n"), zpool_get_name(zhp));
1336 zpool_close(zhp);
1337 return (1);
1340 /* The history must be logged as part of the export */
1341 log_history = B_FALSE;
1343 ret = (zpool_destroy(zhp, history_str) != 0);
1345 zpool_close(zhp);
1347 return (ret);
1350 typedef struct export_cbdata {
1351 boolean_t force;
1352 boolean_t hardforce;
1353 } export_cbdata_t;
1356 * Export one pool
1359 zpool_export_one(zpool_handle_t *zhp, void *data)
1361 export_cbdata_t *cb = data;
1363 if (zpool_disable_datasets(zhp, cb->force) != 0)
1364 return (1);
1366 /* The history must be logged as part of the export */
1367 log_history = B_FALSE;
1369 if (cb->hardforce) {
1370 if (zpool_export_force(zhp, history_str) != 0)
1371 return (1);
1372 } else if (zpool_export(zhp, cb->force, history_str) != 0) {
1373 return (1);
1376 return (0);
1380 * zpool export [-f] <pool> ...
1382 * -a Export all pools
1383 * -f Forcefully unmount datasets
1385 * Export the given pools. By default, the command will attempt to cleanly
1386 * unmount any active datasets within the pool. If the '-f' flag is specified,
1387 * then the datasets will be forcefully unmounted.
1390 zpool_do_export(int argc, char **argv)
1392 export_cbdata_t cb;
1393 boolean_t do_all = B_FALSE;
1394 boolean_t force = B_FALSE;
1395 boolean_t hardforce = B_FALSE;
1396 int c, ret;
1398 /* check options */
1399 while ((c = getopt(argc, argv, "afF")) != -1) {
1400 switch (c) {
1401 case 'a':
1402 do_all = B_TRUE;
1403 break;
1404 case 'f':
1405 force = B_TRUE;
1406 break;
1407 case 'F':
1408 hardforce = B_TRUE;
1409 break;
1410 case '?':
1411 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1412 optopt);
1413 usage(B_FALSE);
1417 cb.force = force;
1418 cb.hardforce = hardforce;
1419 argc -= optind;
1420 argv += optind;
1422 if (do_all) {
1423 if (argc != 0) {
1424 (void) fprintf(stderr, gettext("too many arguments\n"));
1425 usage(B_FALSE);
1428 return (for_each_pool(argc, argv, B_TRUE, NULL,
1429 zpool_export_one, &cb));
1432 /* check arguments */
1433 if (argc < 1) {
1434 (void) fprintf(stderr, gettext("missing pool argument\n"));
1435 usage(B_FALSE);
1438 ret = for_each_pool(argc, argv, B_TRUE, NULL, zpool_export_one, &cb);
1440 return (ret);
1444 * Given a vdev configuration, determine the maximum width needed for the device
1445 * name column.
1447 static int
1448 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
1449 int name_flags)
1451 char *name;
1452 nvlist_t **child;
1453 uint_t c, children;
1454 int ret;
1456 name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
1457 if (strlen(name) + depth > max)
1458 max = strlen(name) + depth;
1460 free(name);
1462 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1463 &child, &children) == 0) {
1464 for (c = 0; c < children; c++)
1465 if ((ret = max_width(zhp, child[c], depth + 2,
1466 max, name_flags)) > max)
1467 max = ret;
1470 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1471 &child, &children) == 0) {
1472 for (c = 0; c < children; c++)
1473 if ((ret = max_width(zhp, child[c], depth + 2,
1474 max, name_flags)) > max)
1475 max = ret;
1478 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1479 &child, &children) == 0) {
1480 for (c = 0; c < children; c++)
1481 if ((ret = max_width(zhp, child[c], depth + 2,
1482 max, name_flags)) > max)
1483 max = ret;
1486 return (max);
1489 typedef struct spare_cbdata {
1490 uint64_t cb_guid;
1491 zpool_handle_t *cb_zhp;
1492 } spare_cbdata_t;
1494 static boolean_t
1495 find_vdev(nvlist_t *nv, uint64_t search)
1497 uint64_t guid;
1498 nvlist_t **child;
1499 uint_t c, children;
1501 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1502 search == guid)
1503 return (B_TRUE);
1505 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1506 &child, &children) == 0) {
1507 for (c = 0; c < children; c++)
1508 if (find_vdev(child[c], search))
1509 return (B_TRUE);
1512 return (B_FALSE);
1515 static int
1516 find_spare(zpool_handle_t *zhp, void *data)
1518 spare_cbdata_t *cbp = data;
1519 nvlist_t *config, *nvroot;
1521 config = zpool_get_config(zhp, NULL);
1522 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1523 &nvroot) == 0);
1525 if (find_vdev(nvroot, cbp->cb_guid)) {
1526 cbp->cb_zhp = zhp;
1527 return (1);
1530 zpool_close(zhp);
1531 return (0);
1534 typedef struct status_cbdata {
1535 int cb_count;
1536 int cb_name_flags;
1537 int cb_namewidth;
1538 boolean_t cb_allpools;
1539 boolean_t cb_verbose;
1540 boolean_t cb_explain;
1541 boolean_t cb_first;
1542 boolean_t cb_dedup_stats;
1543 boolean_t cb_print_status;
1544 vdev_cmd_data_list_t *vcdl;
1545 } status_cbdata_t;
1547 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
1548 static int
1549 is_blank_str(char *str)
1551 while (str != NULL && *str != '\0') {
1552 if (!isblank(*str))
1553 return (0);
1554 str++;
1556 return (1);
1559 /* Print command output lines for specific vdev in a specific pool */
1560 static void
1561 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, char *path)
1563 vdev_cmd_data_t *data;
1564 int i, j;
1565 char *val;
1567 for (i = 0; i < vcdl->count; i++) {
1568 if ((strcmp(vcdl->data[i].path, path) != 0) ||
1569 (strcmp(vcdl->data[i].pool, pool) != 0)) {
1570 /* Not the vdev we're looking for */
1571 continue;
1574 data = &vcdl->data[i];
1575 /* Print out all the output values for this vdev */
1576 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
1577 val = NULL;
1578 /* Does this vdev have values for this column? */
1579 for (int k = 0; k < data->cols_cnt; k++) {
1580 if (strcmp(data->cols[k],
1581 vcdl->uniq_cols[j]) == 0) {
1582 /* yes it does, record the value */
1583 val = data->lines[k];
1584 break;
1588 * Mark empty values with dashes to make output
1589 * awk-able.
1591 if (is_blank_str(val))
1592 val = "-";
1594 printf("%*s", vcdl->uniq_cols_width[j], val);
1595 if (j < vcdl->uniq_cols_cnt - 1)
1596 printf(" ");
1599 /* Print out any values that aren't in a column at the end */
1600 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
1601 /* Did we have any columns? If so print a spacer. */
1602 if (vcdl->uniq_cols_cnt > 0)
1603 printf(" ");
1605 val = data->lines[j];
1606 printf("%s", val ? val : "");
1608 break;
1613 * Print out configuration state as requested by status_callback.
1615 static void
1616 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
1617 nvlist_t *nv, int depth, boolean_t isspare)
1619 nvlist_t **child;
1620 uint_t c, children;
1621 pool_scan_stat_t *ps = NULL;
1622 vdev_stat_t *vs;
1623 char rbuf[6], wbuf[6], cbuf[6];
1624 char *vname;
1625 uint64_t notpresent;
1626 spare_cbdata_t spare_cb;
1627 char *state;
1628 char *path = NULL;
1630 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1631 &child, &children) != 0)
1632 children = 0;
1634 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1635 (uint64_t **)&vs, &c) == 0);
1637 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1638 if (isspare) {
1640 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
1641 * online drives.
1643 if (vs->vs_aux == VDEV_AUX_SPARED)
1644 state = "INUSE";
1645 else if (vs->vs_state == VDEV_STATE_HEALTHY)
1646 state = "AVAIL";
1649 (void) printf("\t%*s%-*s %-8s", depth, "", cb->cb_namewidth - depth,
1650 name, state);
1652 if (!isspare) {
1653 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
1654 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
1655 zfs_nicenum(vs->vs_checksum_errors, cbuf, sizeof (cbuf));
1656 (void) printf(" %5s %5s %5s", rbuf, wbuf, cbuf);
1659 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
1660 &notpresent) == 0) {
1661 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
1662 (void) printf(" was %s", path);
1663 } else if (vs->vs_aux != 0) {
1664 (void) printf(" ");
1666 switch (vs->vs_aux) {
1667 case VDEV_AUX_OPEN_FAILED:
1668 (void) printf(gettext("cannot open"));
1669 break;
1671 case VDEV_AUX_BAD_GUID_SUM:
1672 (void) printf(gettext("missing device"));
1673 break;
1675 case VDEV_AUX_NO_REPLICAS:
1676 (void) printf(gettext("insufficient replicas"));
1677 break;
1679 case VDEV_AUX_VERSION_NEWER:
1680 (void) printf(gettext("newer version"));
1681 break;
1683 case VDEV_AUX_UNSUP_FEAT:
1684 (void) printf(gettext("unsupported feature(s)"));
1685 break;
1687 case VDEV_AUX_SPARED:
1688 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
1689 &spare_cb.cb_guid) == 0);
1690 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1691 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1692 zpool_get_name(zhp)) == 0)
1693 (void) printf(gettext("currently in "
1694 "use"));
1695 else
1696 (void) printf(gettext("in use by "
1697 "pool '%s'"),
1698 zpool_get_name(spare_cb.cb_zhp));
1699 zpool_close(spare_cb.cb_zhp);
1700 } else {
1701 (void) printf(gettext("currently in use"));
1703 break;
1705 case VDEV_AUX_ERR_EXCEEDED:
1706 (void) printf(gettext("too many errors"));
1707 break;
1709 case VDEV_AUX_IO_FAILURE:
1710 (void) printf(gettext("experienced I/O failures"));
1711 break;
1713 case VDEV_AUX_BAD_LOG:
1714 (void) printf(gettext("bad intent log"));
1715 break;
1717 case VDEV_AUX_EXTERNAL:
1718 (void) printf(gettext("external device fault"));
1719 break;
1721 case VDEV_AUX_SPLIT_POOL:
1722 (void) printf(gettext("split into new pool"));
1723 break;
1725 default:
1726 (void) printf(gettext("corrupted data"));
1727 break;
1731 (void) nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_SCAN_STATS,
1732 (uint64_t **)&ps, &c);
1734 if (ps && ps->pss_state == DSS_SCANNING &&
1735 vs->vs_scan_processed != 0 && children == 0) {
1736 (void) printf(gettext(" (%s)"),
1737 (ps->pss_func == POOL_SCAN_RESILVER) ?
1738 "resilvering" : "repairing");
1741 if (cb->vcdl != NULL) {
1742 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
1743 printf(" ");
1744 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
1748 (void) printf("\n");
1750 for (c = 0; c < children; c++) {
1751 uint64_t islog = B_FALSE, ishole = B_FALSE;
1753 /* Don't print logs or holes here */
1754 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1755 &islog);
1756 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
1757 &ishole);
1758 if (islog || ishole)
1759 continue;
1760 vname = zpool_vdev_name(g_zfs, zhp, child[c],
1761 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1762 print_status_config(zhp, cb, vname, child[c], depth + 2,
1763 isspare);
1764 free(vname);
1769 * Print the configuration of an exported pool. Iterate over all vdevs in the
1770 * pool, printing out the name and status for each one.
1772 static void
1773 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
1774 int depth)
1776 nvlist_t **child;
1777 uint_t c, children;
1778 vdev_stat_t *vs;
1779 char *type, *vname;
1781 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1782 if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
1783 strcmp(type, VDEV_TYPE_HOLE) == 0)
1784 return;
1786 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1787 (uint64_t **)&vs, &c) == 0);
1789 (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
1790 (void) printf(" %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
1792 if (vs->vs_aux != 0) {
1793 (void) printf(" ");
1795 switch (vs->vs_aux) {
1796 case VDEV_AUX_OPEN_FAILED:
1797 (void) printf(gettext("cannot open"));
1798 break;
1800 case VDEV_AUX_BAD_GUID_SUM:
1801 (void) printf(gettext("missing device"));
1802 break;
1804 case VDEV_AUX_NO_REPLICAS:
1805 (void) printf(gettext("insufficient replicas"));
1806 break;
1808 case VDEV_AUX_VERSION_NEWER:
1809 (void) printf(gettext("newer version"));
1810 break;
1812 case VDEV_AUX_UNSUP_FEAT:
1813 (void) printf(gettext("unsupported feature(s)"));
1814 break;
1816 case VDEV_AUX_ERR_EXCEEDED:
1817 (void) printf(gettext("too many errors"));
1818 break;
1820 default:
1821 (void) printf(gettext("corrupted data"));
1822 break;
1825 (void) printf("\n");
1827 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1828 &child, &children) != 0)
1829 return;
1831 for (c = 0; c < children; c++) {
1832 uint64_t is_log = B_FALSE;
1834 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1835 &is_log);
1836 if (is_log)
1837 continue;
1839 vname = zpool_vdev_name(g_zfs, NULL, child[c],
1840 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1841 print_import_config(cb, vname, child[c], depth + 2);
1842 free(vname);
1845 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1846 &child, &children) == 0) {
1847 (void) printf(gettext("\tcache\n"));
1848 for (c = 0; c < children; c++) {
1849 vname = zpool_vdev_name(g_zfs, NULL, child[c],
1850 cb->cb_name_flags);
1851 (void) printf("\t %s\n", vname);
1852 free(vname);
1856 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1857 &child, &children) == 0) {
1858 (void) printf(gettext("\tspares\n"));
1859 for (c = 0; c < children; c++) {
1860 vname = zpool_vdev_name(g_zfs, NULL, child[c],
1861 cb->cb_name_flags);
1862 (void) printf("\t %s\n", vname);
1863 free(vname);
1869 * Print log vdevs.
1870 * Logs are recorded as top level vdevs in the main pool child array
1871 * but with "is_log" set to 1. We use either print_status_config() or
1872 * print_import_config() to print the top level logs then any log
1873 * children (eg mirrored slogs) are printed recursively - which
1874 * works because only the top level vdev is marked "is_log"
1876 static void
1877 print_logs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv)
1879 uint_t c, children;
1880 nvlist_t **child;
1882 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
1883 &children) != 0)
1884 return;
1886 (void) printf(gettext("\tlogs\n"));
1888 for (c = 0; c < children; c++) {
1889 uint64_t is_log = B_FALSE;
1890 char *name;
1892 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1893 &is_log);
1894 if (!is_log)
1895 continue;
1896 name = zpool_vdev_name(g_zfs, zhp, child[c],
1897 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1898 if (cb->cb_print_status)
1899 print_status_config(zhp, cb, name, child[c], 2,
1900 B_FALSE);
1901 else
1902 print_import_config(cb, name, child[c], 2);
1903 free(name);
1908 * Display the status for the given pool.
1910 static void
1911 show_import(nvlist_t *config)
1913 uint64_t pool_state;
1914 vdev_stat_t *vs;
1915 char *name;
1916 uint64_t guid;
1917 char *msgid;
1918 nvlist_t *nvroot;
1919 zpool_status_t reason;
1920 zpool_errata_t errata;
1921 const char *health;
1922 uint_t vsc;
1923 char *comment;
1924 status_cbdata_t cb = { 0 };
1926 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1927 &name) == 0);
1928 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1929 &guid) == 0);
1930 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
1931 &pool_state) == 0);
1932 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1933 &nvroot) == 0);
1935 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
1936 (uint64_t **)&vs, &vsc) == 0);
1937 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1939 reason = zpool_import_status(config, &msgid, &errata);
1941 (void) printf(gettext(" pool: %s\n"), name);
1942 (void) printf(gettext(" id: %llu\n"), (u_longlong_t)guid);
1943 (void) printf(gettext(" state: %s"), health);
1944 if (pool_state == POOL_STATE_DESTROYED)
1945 (void) printf(gettext(" (DESTROYED)"));
1946 (void) printf("\n");
1948 switch (reason) {
1949 case ZPOOL_STATUS_MISSING_DEV_R:
1950 case ZPOOL_STATUS_MISSING_DEV_NR:
1951 case ZPOOL_STATUS_BAD_GUID_SUM:
1952 (void) printf(gettext(" status: One or more devices are "
1953 "missing from the system.\n"));
1954 break;
1956 case ZPOOL_STATUS_CORRUPT_LABEL_R:
1957 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
1958 (void) printf(gettext(" status: One or more devices contains "
1959 "corrupted data.\n"));
1960 break;
1962 case ZPOOL_STATUS_CORRUPT_DATA:
1963 (void) printf(
1964 gettext(" status: The pool data is corrupted.\n"));
1965 break;
1967 case ZPOOL_STATUS_OFFLINE_DEV:
1968 (void) printf(gettext(" status: One or more devices "
1969 "are offlined.\n"));
1970 break;
1972 case ZPOOL_STATUS_CORRUPT_POOL:
1973 (void) printf(gettext(" status: The pool metadata is "
1974 "corrupted.\n"));
1975 break;
1977 case ZPOOL_STATUS_VERSION_OLDER:
1978 (void) printf(gettext(" status: The pool is formatted using a "
1979 "legacy on-disk version.\n"));
1980 break;
1982 case ZPOOL_STATUS_VERSION_NEWER:
1983 (void) printf(gettext(" status: The pool is formatted using an "
1984 "incompatible version.\n"));
1985 break;
1987 case ZPOOL_STATUS_FEAT_DISABLED:
1988 (void) printf(gettext(" status: Some supported features are "
1989 "not enabled on the pool.\n"));
1990 break;
1992 case ZPOOL_STATUS_UNSUP_FEAT_READ:
1993 (void) printf(gettext("status: The pool uses the following "
1994 "feature(s) not supported on this system:\n"));
1995 zpool_print_unsup_feat(config);
1996 break;
1998 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
1999 (void) printf(gettext("status: The pool can only be accessed "
2000 "in read-only mode on this system. It\n\tcannot be "
2001 "accessed in read-write mode because it uses the "
2002 "following\n\tfeature(s) not supported on this system:\n"));
2003 zpool_print_unsup_feat(config);
2004 break;
2006 case ZPOOL_STATUS_HOSTID_MISMATCH:
2007 (void) printf(gettext(" status: The pool was last accessed by "
2008 "another system.\n"));
2009 break;
2011 case ZPOOL_STATUS_FAULTED_DEV_R:
2012 case ZPOOL_STATUS_FAULTED_DEV_NR:
2013 (void) printf(gettext(" status: One or more devices are "
2014 "faulted.\n"));
2015 break;
2017 case ZPOOL_STATUS_BAD_LOG:
2018 (void) printf(gettext(" status: An intent log record cannot be "
2019 "read.\n"));
2020 break;
2022 case ZPOOL_STATUS_RESILVERING:
2023 (void) printf(gettext(" status: One or more devices were being "
2024 "resilvered.\n"));
2025 break;
2027 case ZPOOL_STATUS_ERRATA:
2028 (void) printf(gettext(" status: Errata #%d detected.\n"),
2029 errata);
2030 break;
2032 default:
2034 * No other status can be seen when importing pools.
2036 assert(reason == ZPOOL_STATUS_OK);
2040 * Print out an action according to the overall state of the pool.
2042 if (vs->vs_state == VDEV_STATE_HEALTHY) {
2043 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
2044 reason == ZPOOL_STATUS_FEAT_DISABLED) {
2045 (void) printf(gettext(" action: The pool can be "
2046 "imported using its name or numeric identifier, "
2047 "though\n\tsome features will not be available "
2048 "without an explicit 'zpool upgrade'.\n"));
2049 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
2050 (void) printf(gettext(" action: The pool can be "
2051 "imported using its name or numeric "
2052 "identifier and\n\tthe '-f' flag.\n"));
2053 } else if (reason == ZPOOL_STATUS_ERRATA) {
2054 switch (errata) {
2055 case ZPOOL_ERRATA_NONE:
2056 break;
2058 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
2059 (void) printf(gettext(" action: The pool can "
2060 "be imported using its name or numeric "
2061 "identifier,\n\thowever there is a compat"
2062 "ibility issue which should be corrected"
2063 "\n\tby running 'zpool scrub'\n"));
2064 break;
2066 case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
2067 (void) printf(gettext(" action: The pool can"
2068 "not be imported with this version of ZFS "
2069 "due to\n\tan active asynchronous destroy. "
2070 "Revert to an earlier version\n\tand "
2071 "allow the destroy to complete before "
2072 "updating.\n"));
2073 break;
2075 default:
2077 * All errata must contain an action message.
2079 assert(0);
2081 } else {
2082 (void) printf(gettext(" action: The pool can be "
2083 "imported using its name or numeric "
2084 "identifier.\n"));
2086 } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
2087 (void) printf(gettext(" action: The pool can be imported "
2088 "despite missing or damaged devices. The\n\tfault "
2089 "tolerance of the pool may be compromised if imported.\n"));
2090 } else {
2091 switch (reason) {
2092 case ZPOOL_STATUS_VERSION_NEWER:
2093 (void) printf(gettext(" action: The pool cannot be "
2094 "imported. Access the pool on a system running "
2095 "newer\n\tsoftware, or recreate the pool from "
2096 "backup.\n"));
2097 break;
2098 case ZPOOL_STATUS_UNSUP_FEAT_READ:
2099 (void) printf(gettext("action: The pool cannot be "
2100 "imported. Access the pool on a system that "
2101 "supports\n\tthe required feature(s), or recreate "
2102 "the pool from backup.\n"));
2103 break;
2104 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2105 (void) printf(gettext("action: The pool cannot be "
2106 "imported in read-write mode. Import the pool "
2107 "with\n"
2108 "\t\"-o readonly=on\", access the pool on a system "
2109 "that supports the\n\trequired feature(s), or "
2110 "recreate the pool from backup.\n"));
2111 break;
2112 case ZPOOL_STATUS_MISSING_DEV_R:
2113 case ZPOOL_STATUS_MISSING_DEV_NR:
2114 case ZPOOL_STATUS_BAD_GUID_SUM:
2115 (void) printf(gettext(" action: The pool cannot be "
2116 "imported. Attach the missing\n\tdevices and try "
2117 "again.\n"));
2118 break;
2119 default:
2120 (void) printf(gettext(" action: The pool cannot be "
2121 "imported due to damaged devices or data.\n"));
2125 /* Print the comment attached to the pool. */
2126 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2127 (void) printf(gettext("comment: %s\n"), comment);
2130 * If the state is "closed" or "can't open", and the aux state
2131 * is "corrupt data":
2133 if (((vs->vs_state == VDEV_STATE_CLOSED) ||
2134 (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
2135 (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
2136 if (pool_state == POOL_STATE_DESTROYED)
2137 (void) printf(gettext("\tThe pool was destroyed, "
2138 "but can be imported using the '-Df' flags.\n"));
2139 else if (pool_state != POOL_STATE_EXPORTED)
2140 (void) printf(gettext("\tThe pool may be active on "
2141 "another system, but can be imported using\n\t"
2142 "the '-f' flag.\n"));
2145 if (msgid != NULL)
2146 (void) printf(gettext(" see: http://zfsonlinux.org/msg/%s\n"),
2147 msgid);
2149 (void) printf(gettext(" config:\n\n"));
2151 cb.cb_namewidth = max_width(NULL, nvroot, 0, 0, VDEV_NAME_TYPE_ID);
2152 if (cb.cb_namewidth < 10)
2153 cb.cb_namewidth = 10;
2155 print_import_config(&cb, name, nvroot, 0);
2156 if (num_logs(nvroot) > 0)
2157 print_logs(NULL, &cb, nvroot);
2159 if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
2160 (void) printf(gettext("\n\tAdditional devices are known to "
2161 "be part of this pool, though their\n\texact "
2162 "configuration cannot be determined.\n"));
2167 * Perform the import for the given configuration. This passes the heavy
2168 * lifting off to zpool_import_props(), and then mounts the datasets contained
2169 * within the pool.
2171 static int
2172 do_import(nvlist_t *config, const char *newname, const char *mntopts,
2173 nvlist_t *props, int flags)
2175 zpool_handle_t *zhp;
2176 char *name;
2177 uint64_t state;
2178 uint64_t version;
2180 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2181 &name) == 0);
2183 verify(nvlist_lookup_uint64(config,
2184 ZPOOL_CONFIG_POOL_STATE, &state) == 0);
2185 verify(nvlist_lookup_uint64(config,
2186 ZPOOL_CONFIG_VERSION, &version) == 0);
2187 if (!SPA_VERSION_IS_SUPPORTED(version)) {
2188 (void) fprintf(stderr, gettext("cannot import '%s': pool "
2189 "is formatted using an unsupported ZFS version\n"), name);
2190 return (1);
2191 } else if (state != POOL_STATE_EXPORTED &&
2192 !(flags & ZFS_IMPORT_ANY_HOST)) {
2193 uint64_t hostid = 0;
2194 unsigned long system_hostid = get_system_hostid();
2196 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
2197 &hostid);
2199 if (hostid != 0 && (unsigned long)hostid != system_hostid) {
2200 char *hostname;
2201 uint64_t timestamp;
2202 time_t t;
2204 verify(nvlist_lookup_string(config,
2205 ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2206 verify(nvlist_lookup_uint64(config,
2207 ZPOOL_CONFIG_TIMESTAMP, &timestamp) == 0);
2208 t = timestamp;
2209 (void) fprintf(stderr, gettext("cannot import "
2210 "'%s': pool may be in use from other "
2211 "system, it was last accessed by %s "
2212 "(hostid: 0x%lx) on %s"), name, hostname,
2213 (unsigned long)hostid,
2214 asctime(localtime(&t)));
2215 (void) fprintf(stderr, gettext("use '-f' to "
2216 "import anyway\n"));
2217 return (1);
2221 if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
2222 return (1);
2224 if (newname != NULL)
2225 name = (char *)newname;
2227 if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
2228 return (1);
2230 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
2231 !(flags & ZFS_IMPORT_ONLY) &&
2232 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
2233 zpool_close(zhp);
2234 return (1);
2237 zpool_close(zhp);
2238 return (0);
2242 * zpool import [-d dir] [-D]
2243 * import [-o mntopts] [-o prop=value] ... [-R root] [-D]
2244 * [-d dir | -c cachefile] [-f] -a
2245 * import [-o mntopts] [-o prop=value] ... [-R root] [-D]
2246 * [-d dir | -c cachefile] [-f] [-n] [-F] <pool | id> [newpool]
2248 * -c Read pool information from a cachefile instead of searching
2249 * devices.
2251 * -d Scan in a specific directory, other than /dev/. More than
2252 * one directory can be specified using multiple '-d' options.
2254 * -D Scan for previously destroyed pools or import all or only
2255 * specified destroyed pools.
2257 * -R Temporarily import the pool, with all mountpoints relative to
2258 * the given root. The pool will remain exported when the machine
2259 * is rebooted.
2261 * -V Import even in the presence of faulted vdevs. This is an
2262 * intentionally undocumented option for testing purposes, and
2263 * treats the pool configuration as complete, leaving any bad
2264 * vdevs in the FAULTED state. In other words, it does verbatim
2265 * import.
2267 * -f Force import, even if it appears that the pool is active.
2269 * -F Attempt rewind if necessary.
2271 * -n See if rewind would work, but don't actually rewind.
2273 * -N Import the pool but don't mount datasets.
2275 * -T Specify a starting txg to use for import. This option is
2276 * intentionally undocumented option for testing purposes.
2278 * -a Import all pools found.
2280 * -o Set property=value and/or temporary mount options (without '=').
2282 * -s Scan using the default search path, the libblkid cache will
2283 * not be consulted.
2285 * The import command scans for pools to import, and import pools based on pool
2286 * name and GUID. The pool can also be renamed as part of the import process.
2289 zpool_do_import(int argc, char **argv)
2291 char **searchdirs = NULL;
2292 char *env, *envdup = NULL;
2293 int nsearch = 0;
2294 int c;
2295 int err = 0;
2296 nvlist_t *pools = NULL;
2297 boolean_t do_all = B_FALSE;
2298 boolean_t do_destroyed = B_FALSE;
2299 char *mntopts = NULL;
2300 nvpair_t *elem;
2301 nvlist_t *config;
2302 uint64_t searchguid = 0;
2303 char *searchname = NULL;
2304 char *propval;
2305 nvlist_t *found_config;
2306 nvlist_t *policy = NULL;
2307 nvlist_t *props = NULL;
2308 boolean_t first;
2309 int flags = ZFS_IMPORT_NORMAL;
2310 uint32_t rewind_policy = ZPOOL_NO_REWIND;
2311 boolean_t dryrun = B_FALSE;
2312 boolean_t do_rewind = B_FALSE;
2313 boolean_t xtreme_rewind = B_FALSE;
2314 boolean_t do_scan = B_FALSE;
2315 uint64_t pool_state, txg = -1ULL;
2316 char *cachefile = NULL;
2317 importargs_t idata = { 0 };
2318 char *endptr;
2320 /* check options */
2321 while ((c = getopt(argc, argv, ":aCc:d:DEfFmnNo:R:stT:VX")) != -1) {
2322 switch (c) {
2323 case 'a':
2324 do_all = B_TRUE;
2325 break;
2326 case 'c':
2327 cachefile = optarg;
2328 break;
2329 case 'd':
2330 if (searchdirs == NULL) {
2331 searchdirs = safe_malloc(sizeof (char *));
2332 } else {
2333 char **tmp = safe_malloc((nsearch + 1) *
2334 sizeof (char *));
2335 bcopy(searchdirs, tmp, nsearch *
2336 sizeof (char *));
2337 free(searchdirs);
2338 searchdirs = tmp;
2340 searchdirs[nsearch++] = optarg;
2341 break;
2342 case 'D':
2343 do_destroyed = B_TRUE;
2344 break;
2345 case 'f':
2346 flags |= ZFS_IMPORT_ANY_HOST;
2347 break;
2348 case 'F':
2349 do_rewind = B_TRUE;
2350 break;
2351 case 'm':
2352 flags |= ZFS_IMPORT_MISSING_LOG;
2353 break;
2354 case 'n':
2355 dryrun = B_TRUE;
2356 break;
2357 case 'N':
2358 flags |= ZFS_IMPORT_ONLY;
2359 break;
2360 case 'o':
2361 if ((propval = strchr(optarg, '=')) != NULL) {
2362 *propval = '\0';
2363 propval++;
2364 if (add_prop_list(optarg, propval,
2365 &props, B_TRUE))
2366 goto error;
2367 } else {
2368 mntopts = optarg;
2370 break;
2371 case 'R':
2372 if (add_prop_list(zpool_prop_to_name(
2373 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
2374 goto error;
2375 if (add_prop_list_default(zpool_prop_to_name(
2376 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
2377 goto error;
2378 break;
2379 case 's':
2380 do_scan = B_TRUE;
2381 break;
2382 case 't':
2383 flags |= ZFS_IMPORT_TEMP_NAME;
2384 if (add_prop_list_default(zpool_prop_to_name(
2385 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
2386 goto error;
2387 break;
2389 case 'T':
2390 errno = 0;
2391 txg = strtoull(optarg, &endptr, 0);
2392 if (errno != 0 || *endptr != '\0') {
2393 (void) fprintf(stderr,
2394 gettext("invalid txg value\n"));
2395 usage(B_FALSE);
2397 rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
2398 break;
2399 case 'V':
2400 flags |= ZFS_IMPORT_VERBATIM;
2401 break;
2402 case 'X':
2403 xtreme_rewind = B_TRUE;
2404 break;
2405 case ':':
2406 (void) fprintf(stderr, gettext("missing argument for "
2407 "'%c' option\n"), optopt);
2408 usage(B_FALSE);
2409 break;
2410 case '?':
2411 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2412 optopt);
2413 usage(B_FALSE);
2417 argc -= optind;
2418 argv += optind;
2420 if (cachefile && nsearch != 0) {
2421 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
2422 usage(B_FALSE);
2425 if ((dryrun || xtreme_rewind) && !do_rewind) {
2426 (void) fprintf(stderr,
2427 gettext("-n or -X only meaningful with -F\n"));
2428 usage(B_FALSE);
2430 if (dryrun)
2431 rewind_policy = ZPOOL_TRY_REWIND;
2432 else if (do_rewind)
2433 rewind_policy = ZPOOL_DO_REWIND;
2434 if (xtreme_rewind)
2435 rewind_policy |= ZPOOL_EXTREME_REWIND;
2437 /* In the future, we can capture further policy and include it here */
2438 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
2439 nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, txg) != 0 ||
2440 nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
2441 goto error;
2443 /* check argument count */
2444 if (do_all) {
2445 if (argc != 0) {
2446 (void) fprintf(stderr, gettext("too many arguments\n"));
2447 usage(B_FALSE);
2449 } else {
2450 if (argc > 2) {
2451 (void) fprintf(stderr, gettext("too many arguments\n"));
2452 usage(B_FALSE);
2457 * Check for the effective uid. We do this explicitly here because
2458 * otherwise any attempt to discover pools will silently fail.
2460 if (argc == 0 && geteuid() != 0) {
2461 (void) fprintf(stderr, gettext("cannot "
2462 "discover pools: permission denied\n"));
2463 if (searchdirs != NULL)
2464 free(searchdirs);
2466 nvlist_free(props);
2467 nvlist_free(policy);
2468 return (1);
2472 * Depending on the arguments given, we do one of the following:
2474 * <none> Iterate through all pools and display information about
2475 * each one.
2477 * -a Iterate through all pools and try to import each one.
2479 * <id> Find the pool that corresponds to the given GUID/pool
2480 * name and import that one.
2482 * -D Above options applies only to destroyed pools.
2484 if (argc != 0) {
2485 char *endptr;
2487 errno = 0;
2488 searchguid = strtoull(argv[0], &endptr, 10);
2489 if (errno != 0 || *endptr != '\0') {
2490 searchname = argv[0];
2491 searchguid = 0;
2493 found_config = NULL;
2496 * User specified a name or guid. Ensure it's unique.
2498 idata.unique = B_TRUE;
2502 * Check the environment for the preferred search path.
2504 if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
2505 char *dir;
2507 envdup = strdup(env);
2509 dir = strtok(envdup, ":");
2510 while (dir != NULL) {
2511 if (searchdirs == NULL) {
2512 searchdirs = safe_malloc(sizeof (char *));
2513 } else {
2514 char **tmp = safe_malloc((nsearch + 1) *
2515 sizeof (char *));
2516 bcopy(searchdirs, tmp, nsearch *
2517 sizeof (char *));
2518 free(searchdirs);
2519 searchdirs = tmp;
2521 searchdirs[nsearch++] = dir;
2522 dir = strtok(NULL, ":");
2526 idata.path = searchdirs;
2527 idata.paths = nsearch;
2528 idata.poolname = searchname;
2529 idata.guid = searchguid;
2530 idata.cachefile = cachefile;
2531 idata.scan = do_scan;
2534 * Under Linux the zpool_find_import_impl() function leverages the
2535 * taskq implementation to parallelize device scanning. It is
2536 * therefore necessary to initialize this functionality for the
2537 * duration of the zpool_search_import() function.
2539 thread_init();
2540 pools = zpool_search_import(g_zfs, &idata);
2541 thread_fini();
2543 if (pools != NULL && idata.exists &&
2544 (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
2545 (void) fprintf(stderr, gettext("cannot import '%s': "
2546 "a pool with that name already exists\n"),
2547 argv[0]);
2548 (void) fprintf(stderr, gettext("use the form '%s "
2549 "<pool | id> <newpool>' to give it a new name\n"),
2550 "zpool import");
2551 err = 1;
2552 } else if (pools == NULL && idata.exists) {
2553 (void) fprintf(stderr, gettext("cannot import '%s': "
2554 "a pool with that name is already created/imported,\n"),
2555 argv[0]);
2556 (void) fprintf(stderr, gettext("and no additional pools "
2557 "with that name were found\n"));
2558 err = 1;
2559 } else if (pools == NULL) {
2560 if (argc != 0) {
2561 (void) fprintf(stderr, gettext("cannot import '%s': "
2562 "no such pool available\n"), argv[0]);
2564 err = 1;
2567 if (err == 1) {
2568 if (searchdirs != NULL)
2569 free(searchdirs);
2570 if (envdup != NULL)
2571 free(envdup);
2572 nvlist_free(policy);
2573 nvlist_free(pools);
2574 nvlist_free(props);
2575 return (1);
2579 * At this point we have a list of import candidate configs. Even if
2580 * we were searching by pool name or guid, we still need to
2581 * post-process the list to deal with pool state and possible
2582 * duplicate names.
2584 err = 0;
2585 elem = NULL;
2586 first = B_TRUE;
2587 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2589 verify(nvpair_value_nvlist(elem, &config) == 0);
2591 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2592 &pool_state) == 0);
2593 if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
2594 continue;
2595 if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
2596 continue;
2598 verify(nvlist_add_nvlist(config, ZPOOL_REWIND_POLICY,
2599 policy) == 0);
2601 if (argc == 0) {
2602 if (first)
2603 first = B_FALSE;
2604 else if (!do_all)
2605 (void) printf("\n");
2607 if (do_all) {
2608 err |= do_import(config, NULL, mntopts,
2609 props, flags);
2610 } else {
2611 show_import(config);
2613 } else if (searchname != NULL) {
2614 char *name;
2617 * We are searching for a pool based on name.
2619 verify(nvlist_lookup_string(config,
2620 ZPOOL_CONFIG_POOL_NAME, &name) == 0);
2622 if (strcmp(name, searchname) == 0) {
2623 if (found_config != NULL) {
2624 (void) fprintf(stderr, gettext(
2625 "cannot import '%s': more than "
2626 "one matching pool\n"), searchname);
2627 (void) fprintf(stderr, gettext(
2628 "import by numeric ID instead\n"));
2629 err = B_TRUE;
2631 found_config = config;
2633 } else {
2634 uint64_t guid;
2637 * Search for a pool by guid.
2639 verify(nvlist_lookup_uint64(config,
2640 ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
2642 if (guid == searchguid)
2643 found_config = config;
2648 * If we were searching for a specific pool, verify that we found a
2649 * pool, and then do the import.
2651 if (argc != 0 && err == 0) {
2652 if (found_config == NULL) {
2653 (void) fprintf(stderr, gettext("cannot import '%s': "
2654 "no such pool available\n"), argv[0]);
2655 err = B_TRUE;
2656 } else {
2657 err |= do_import(found_config, argc == 1 ? NULL :
2658 argv[1], mntopts, props, flags);
2663 * If we were just looking for pools, report an error if none were
2664 * found.
2666 if (argc == 0 && first)
2667 (void) fprintf(stderr,
2668 gettext("no pools available to import\n"));
2670 error:
2671 nvlist_free(props);
2672 nvlist_free(pools);
2673 nvlist_free(policy);
2674 if (searchdirs != NULL)
2675 free(searchdirs);
2676 if (envdup != NULL)
2677 free(envdup);
2679 return (err ? 1 : 0);
2682 typedef struct iostat_cbdata {
2683 uint64_t cb_flags;
2684 int cb_name_flags;
2685 int cb_namewidth;
2686 int cb_iteration;
2687 char **cb_vdev_names; /* Only show these vdevs */
2688 unsigned int cb_vdev_names_count;
2689 boolean_t cb_verbose;
2690 boolean_t cb_literal;
2691 boolean_t cb_scripted;
2692 zpool_list_t *cb_list;
2693 vdev_cmd_data_list_t *vcdl;
2694 } iostat_cbdata_t;
2696 /* iostat labels */
2697 typedef struct name_and_columns {
2698 const char *name; /* Column name */
2699 unsigned int columns; /* Center name to this number of columns */
2700 } name_and_columns_t;
2702 #define IOSTAT_MAX_LABELS 11 /* Max number of labels on one line */
2704 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
2706 [IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
2707 {NULL}},
2708 [IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
2709 {"asyncq_wait", 2}, {"scrub"}},
2710 [IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
2711 {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
2712 {NULL}},
2713 [IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2},
2714 {"sync_queue", 2}, {"async_queue", 2}, {NULL}},
2715 [IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
2716 {"async_read", 2}, {"async_write", 2}, {"scrub", 2}, {NULL}},
2720 /* Shorthand - if "columns" field not set, default to 1 column */
2721 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
2723 [IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
2724 {"write"}, {NULL}},
2725 [IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
2726 {"write"}, {"read"}, {"write"}, {"wait"}, {NULL}},
2727 [IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
2728 {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
2729 [IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
2730 {"write"}, {"read"}, {"write"}, {"scrub"}, {NULL}},
2731 [IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
2732 {"ind"}, {"agg"}, {"ind"}, {"agg"}, {NULL}},
2735 static const char *histo_to_title[] = {
2736 [IOS_L_HISTO] = "latency",
2737 [IOS_RQ_HISTO] = "req_size",
2741 * Return the number of labels in a null-terminated name_and_columns_t
2742 * array.
2745 static unsigned int
2746 label_array_len(const name_and_columns_t *labels)
2748 int i = 0;
2750 while (labels[i].name)
2751 i++;
2753 return (i);
2757 * Return the number of strings in a null-terminated string array.
2758 * For example:
2760 * const char foo[] = {"bar", "baz", NULL}
2762 * returns 2
2764 static uint64_t
2765 str_array_len(const char *array[])
2767 uint64_t i = 0;
2768 while (array[i])
2769 i++;
2771 return (i);
2776 * Return a default column width for default/latency/queue columns. This does
2777 * not include histograms, which have their columns autosized.
2779 static unsigned int
2780 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
2782 unsigned long column_width = 5; /* Normal niceprint */
2783 static unsigned long widths[] = {
2785 * Choose some sane default column sizes for printing the
2786 * raw numbers.
2788 [IOS_DEFAULT] = 15, /* 1PB capacity */
2789 [IOS_LATENCY] = 10, /* 1B ns = 10sec */
2790 [IOS_QUEUES] = 6, /* 1M queue entries */
2793 if (cb->cb_literal)
2794 column_width = widths[type];
2796 return (column_width);
2800 * Print the column labels, i.e:
2802 * capacity operations bandwidth
2803 * alloc free read write read write ...
2805 * If force_column_width is set, use it for the column width. If not set, use
2806 * the default column width.
2808 void
2809 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
2810 const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
2812 int i, idx, s;
2813 unsigned int text_start, rw_column_width, spaces_to_end;
2814 uint64_t flags = cb->cb_flags;
2815 uint64_t f;
2816 unsigned int column_width = force_column_width;
2818 /* For each bit set in flags */
2819 for (f = flags; f; f &= ~(1ULL << idx)) {
2820 idx = lowbit64(f) - 1;
2821 if (!force_column_width)
2822 column_width = default_column_width(cb, idx);
2823 /* Print our top labels centered over "read write" label. */
2824 for (i = 0; i < label_array_len(labels[idx]); i++) {
2825 const char *name = labels[idx][i].name;
2827 * We treat labels[][].columns == 0 as shorthand
2828 * for one column. It makes writing out the label
2829 * tables more concise.
2831 unsigned int columns = MAX(1, labels[idx][i].columns);
2832 unsigned int slen = strlen(name);
2834 rw_column_width = (column_width * columns) +
2835 (2 * (columns - 1));
2837 text_start = (int)((rw_column_width)/columns -
2838 slen/columns);
2840 printf(" "); /* Two spaces between columns */
2842 /* Space from beginning of column to label */
2843 for (s = 0; s < text_start; s++)
2844 printf(" ");
2846 printf("%s", name);
2848 /* Print space after label to end of column */
2849 spaces_to_end = rw_column_width - text_start - slen;
2850 for (s = 0; s < spaces_to_end; s++)
2851 printf(" ");
2859 * print_cmd_columns - Print custom column titles from -c
2861 * If the user specified the "zpool status|iostat -c" then print their custom
2862 * column titles in the header. For example, print_cmd_columns() would print
2863 * the " col1 col2" part of this:
2865 * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
2866 * ...
2867 * capacity operations bandwidth
2868 * pool alloc free read write read write col1 col2
2869 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
2870 * mypool 269K 1008M 0 0 107 946
2871 * mirror 269K 1008M 0 0 107 946
2872 * sdb - - 0 0 102 473 val1 val2
2873 * sdc - - 0 0 5 473 val1 val2
2874 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
2876 void
2877 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
2879 int i, j;
2880 vdev_cmd_data_t *data = &vcdl->data[0];
2882 if (vcdl->count == 0 || data == NULL)
2883 return;
2886 * Each vdev cmd should have the same column names unless the user did
2887 * something weird with their cmd. Just take the column names from the
2888 * first vdev and assume it works for all of them.
2890 for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
2891 printf(" ");
2892 if (use_dashes) {
2893 for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
2894 printf("-");
2895 } else {
2896 printf("%*s", vcdl->uniq_cols_width[i],
2897 vcdl->uniq_cols[i]);
2904 * Utility function to print out a line of dashes like:
2906 * -------------------------------- ----- ----- ----- ----- -----
2908 * ...or a dashed named-row line like:
2910 * logs - - - - -
2912 * @cb: iostat data
2914 * @force_column_width If non-zero, use the value as the column width.
2915 * Otherwise use the default column widths.
2917 * @name: Print a dashed named-row line starting
2918 * with @name. Otherwise, print a regular
2919 * dashed line.
2921 static void
2922 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
2923 const char *name)
2925 int i;
2926 unsigned int namewidth;
2927 uint64_t flags = cb->cb_flags;
2928 uint64_t f;
2929 int idx;
2930 const name_and_columns_t *labels;
2931 const char *title;
2934 if (cb->cb_flags & IOS_ANYHISTO_M) {
2935 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
2936 } else if (cb->cb_vdev_names_count) {
2937 title = "vdev";
2938 } else {
2939 title = "pool";
2942 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
2943 name ? strlen(name) : 0);
2946 if (name) {
2947 printf("%-*s", namewidth, name);
2948 } else {
2949 for (i = 0; i < namewidth; i++)
2950 (void) printf("-");
2953 /* For each bit in flags */
2954 for (f = flags; f; f &= ~(1ULL << idx)) {
2955 unsigned int column_width;
2956 idx = lowbit64(f) - 1;
2957 if (force_column_width)
2958 column_width = force_column_width;
2959 else
2960 column_width = default_column_width(cb, idx);
2962 labels = iostat_bottom_labels[idx];
2963 for (i = 0; i < label_array_len(labels); i++) {
2964 if (name)
2965 printf(" %*s-", column_width - 1, " ");
2966 else
2967 printf(" %.*s", column_width,
2968 "--------------------");
2974 static void
2975 print_iostat_separator_impl(iostat_cbdata_t *cb,
2976 unsigned int force_column_width)
2978 print_iostat_dashes(cb, force_column_width, NULL);
2981 static void
2982 print_iostat_separator(iostat_cbdata_t *cb)
2984 print_iostat_separator_impl(cb, 0);
2987 static void
2988 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
2989 const char *histo_vdev_name)
2991 unsigned int namewidth;
2992 const char *title;
2994 if (cb->cb_flags & IOS_ANYHISTO_M) {
2995 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
2996 } else if (cb->cb_vdev_names_count) {
2997 title = "vdev";
2998 } else {
2999 title = "pool";
3002 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
3003 histo_vdev_name ? strlen(histo_vdev_name) : 0);
3005 if (histo_vdev_name)
3006 printf("%-*s", namewidth, histo_vdev_name);
3007 else
3008 printf("%*s", namewidth, "");
3011 print_iostat_labels(cb, force_column_width, iostat_top_labels);
3012 printf("\n");
3014 printf("%-*s", namewidth, title);
3016 print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
3017 if (cb->vcdl != NULL)
3018 print_cmd_columns(cb->vcdl, 0);
3020 printf("\n");
3022 print_iostat_separator_impl(cb, force_column_width);
3024 if (cb->vcdl != NULL)
3025 print_cmd_columns(cb->vcdl, 1);
3027 printf("\n");
3030 static void
3031 print_iostat_header(iostat_cbdata_t *cb)
3033 print_iostat_header_impl(cb, 0, NULL);
3038 * Display a single statistic.
3040 static void
3041 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
3042 unsigned int column_size, boolean_t scripted)
3044 char buf[64];
3046 zfs_nicenum_format(value, buf, sizeof (buf), format);
3048 if (scripted)
3049 printf("\t%s", buf);
3050 else
3051 printf(" %*s", column_size, buf);
3055 * Calculate the default vdev stats
3057 * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
3058 * stats into calcvs.
3060 static void
3061 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
3062 vdev_stat_t *calcvs)
3064 int i;
3066 memcpy(calcvs, newvs, sizeof (*calcvs));
3067 for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
3068 calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
3070 for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
3071 calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
3075 * Internal representation of the extended iostats data.
3077 * The extended iostat stats are exported in nvlists as either uint64_t arrays
3078 * or single uint64_t's. We make both look like arrays to make them easier
3079 * to process. In order to make single uint64_t's look like arrays, we set
3080 * __data to the stat data, and then set *data = &__data with count = 1. Then,
3081 * we can just use *data and count.
3083 struct stat_array {
3084 uint64_t *data;
3085 uint_t count; /* Number of entries in data[] */
3086 uint64_t __data; /* Only used when data is a single uint64_t */
3089 static uint64_t
3090 stat_histo_max(struct stat_array *nva, unsigned int len)
3092 uint64_t max = 0;
3093 int i;
3094 for (i = 0; i < len; i++)
3095 max = MAX(max, array64_max(nva[i].data, nva[i].count));
3097 return (max);
3101 * Helper function to lookup a uint64_t array or uint64_t value and store its
3102 * data as a stat_array. If the nvpair is a single uint64_t value, then we make
3103 * it look like a one element array to make it easier to process.
3105 static int
3106 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
3107 struct stat_array *nva)
3109 nvpair_t *tmp;
3110 int ret;
3112 verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
3113 switch (nvpair_type(tmp)) {
3114 case DATA_TYPE_UINT64_ARRAY:
3115 ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
3116 break;
3117 case DATA_TYPE_UINT64:
3118 ret = nvpair_value_uint64(tmp, &nva->__data);
3119 nva->data = &nva->__data;
3120 nva->count = 1;
3121 break;
3122 default:
3123 /* Not a uint64_t */
3124 ret = EINVAL;
3125 break;
3128 return (ret);
3132 * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
3133 * subtract them, and return the results in a newly allocated stat_array.
3134 * You must free the returned array after you are done with it with
3135 * free_calc_stats().
3137 * Additionally, you can set "oldnv" to NULL if you simply want the newnv
3138 * values.
3140 static struct stat_array *
3141 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
3142 nvlist_t *newnv)
3144 nvlist_t *oldnvx = NULL, *newnvx;
3145 struct stat_array *oldnva, *newnva, *calcnva;
3146 int i, j;
3147 unsigned int alloc_size = (sizeof (struct stat_array)) * len;
3149 /* Extract our extended stats nvlist from the main list */
3150 verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
3151 &newnvx) == 0);
3152 if (oldnv) {
3153 verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
3154 &oldnvx) == 0);
3157 newnva = safe_malloc(alloc_size);
3158 oldnva = safe_malloc(alloc_size);
3159 calcnva = safe_malloc(alloc_size);
3161 for (j = 0; j < len; j++) {
3162 verify(nvpair64_to_stat_array(newnvx, names[j],
3163 &newnva[j]) == 0);
3164 calcnva[j].count = newnva[j].count;
3165 alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
3166 calcnva[j].data = safe_malloc(alloc_size);
3167 memcpy(calcnva[j].data, newnva[j].data, alloc_size);
3169 if (oldnvx) {
3170 verify(nvpair64_to_stat_array(oldnvx, names[j],
3171 &oldnva[j]) == 0);
3172 for (i = 0; i < oldnva[j].count; i++)
3173 calcnva[j].data[i] -= oldnva[j].data[i];
3176 free(newnva);
3177 free(oldnva);
3178 return (calcnva);
3181 static void
3182 free_calc_stats(struct stat_array *nva, unsigned int len)
3184 int i;
3185 for (i = 0; i < len; i++)
3186 free(nva[i].data);
3188 free(nva);
3191 static void
3192 print_iostat_histo(struct stat_array *nva, unsigned int len,
3193 iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
3194 double scale)
3196 int i, j;
3197 char buf[6];
3198 uint64_t val;
3199 enum zfs_nicenum_format format;
3200 unsigned int buckets;
3201 unsigned int start_bucket;
3203 if (cb->cb_literal)
3204 format = ZFS_NICENUM_RAW;
3205 else
3206 format = ZFS_NICENUM_1024;
3208 /* All these histos are the same size, so just use nva[0].count */
3209 buckets = nva[0].count;
3211 if (cb->cb_flags & IOS_RQ_HISTO_M) {
3212 /* Start at 512 - req size should never be lower than this */
3213 start_bucket = 9;
3214 } else {
3215 start_bucket = 0;
3218 for (j = start_bucket; j < buckets; j++) {
3219 /* Print histogram bucket label */
3220 if (cb->cb_flags & IOS_L_HISTO_M) {
3221 /* Ending range of this bucket */
3222 val = (1UL << (j + 1)) - 1;
3223 zfs_nicetime(val, buf, sizeof (buf));
3224 } else {
3225 /* Request size (starting range of bucket) */
3226 val = (1UL << j);
3227 zfs_nicenum(val, buf, sizeof (buf));
3230 if (cb->cb_scripted)
3231 printf("%llu", (u_longlong_t)val);
3232 else
3233 printf("%-*s", namewidth, buf);
3235 /* Print the values on the line */
3236 for (i = 0; i < len; i++) {
3237 print_one_stat(nva[i].data[j] * scale, format,
3238 column_width, cb->cb_scripted);
3240 printf("\n");
3244 static void
3245 print_solid_separator(unsigned int length)
3247 while (length--)
3248 printf("-");
3249 printf("\n");
3252 static void
3253 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
3254 nvlist_t *newnv, double scale, const char *name)
3256 unsigned int column_width;
3257 unsigned int namewidth;
3258 unsigned int entire_width;
3259 enum iostat_type type;
3260 struct stat_array *nva;
3261 const char **names;
3262 unsigned int names_len;
3264 /* What type of histo are we? */
3265 type = IOS_HISTO_IDX(cb->cb_flags);
3267 /* Get NULL-terminated array of nvlist names for our histo */
3268 names = vsx_type_to_nvlist[type];
3269 names_len = str_array_len(names); /* num of names */
3271 nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
3273 if (cb->cb_literal) {
3274 column_width = MAX(5,
3275 (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
3276 } else {
3277 column_width = 5;
3280 namewidth = MAX(cb->cb_namewidth,
3281 strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
3284 * Calculate the entire line width of what we're printing. The
3285 * +2 is for the two spaces between columns:
3287 /* read write */
3288 /* ----- ----- */
3289 /* |___| <---------- column_width */
3290 /* */
3291 /* |__________| <--- entire_width */
3292 /* */
3293 entire_width = namewidth + (column_width + 2) *
3294 label_array_len(iostat_bottom_labels[type]);
3296 if (cb->cb_scripted)
3297 printf("%s\n", name);
3298 else
3299 print_iostat_header_impl(cb, column_width, name);
3301 print_iostat_histo(nva, names_len, cb, column_width,
3302 namewidth, scale);
3304 free_calc_stats(nva, names_len);
3305 if (!cb->cb_scripted)
3306 print_solid_separator(entire_width);
3310 * Calculate the average latency of a power-of-two latency histogram
3312 static uint64_t
3313 single_histo_average(uint64_t *histo, unsigned int buckets)
3315 int i;
3316 uint64_t count = 0, total = 0;
3318 for (i = 0; i < buckets; i++) {
3320 * Our buckets are power-of-two latency ranges. Use the
3321 * midpoint latency of each bucket to calculate the average.
3322 * For example:
3324 * Bucket Midpoint
3325 * 8ns-15ns: 12ns
3326 * 16ns-31ns: 24ns
3327 * ...
3329 if (histo[i] != 0) {
3330 total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
3331 count += histo[i];
3335 /* Prevent divide by zero */
3336 return (count == 0 ? 0 : total / count);
3339 static void
3340 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *oldnv,
3341 nvlist_t *newnv, double scale)
3343 int i;
3344 uint64_t val;
3345 const char *names[] = {
3346 ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
3347 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
3348 ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
3349 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
3350 ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
3351 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
3352 ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
3353 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
3354 ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
3355 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
3358 struct stat_array *nva;
3360 unsigned int column_width = default_column_width(cb, IOS_QUEUES);
3361 enum zfs_nicenum_format format;
3363 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
3365 if (cb->cb_literal)
3366 format = ZFS_NICENUM_RAW;
3367 else
3368 format = ZFS_NICENUM_1024;
3370 for (i = 0; i < ARRAY_SIZE(names); i++) {
3371 val = nva[i].data[0] * scale;
3372 print_one_stat(val, format, column_width, cb->cb_scripted);
3375 free_calc_stats(nva, ARRAY_SIZE(names));
3378 static void
3379 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
3380 nvlist_t *newnv, double scale)
3382 int i;
3383 uint64_t val;
3384 const char *names[] = {
3385 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
3386 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
3387 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
3388 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
3389 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
3390 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
3391 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
3392 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
3393 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
3395 struct stat_array *nva;
3397 unsigned int column_width = default_column_width(cb, IOS_LATENCY);
3398 enum zfs_nicenum_format format;
3400 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
3402 if (cb->cb_literal)
3403 format = ZFS_NICENUM_RAW;
3404 else
3405 format = ZFS_NICENUM_TIME;
3407 /* Print our avg latencies on the line */
3408 for (i = 0; i < ARRAY_SIZE(names); i++) {
3409 /* Compute average latency for a latency histo */
3410 val = single_histo_average(nva[i].data, nva[i].count) * scale;
3411 print_one_stat(val, format, column_width, cb->cb_scripted);
3413 free_calc_stats(nva, ARRAY_SIZE(names));
3417 * Print default statistics (capacity/operations/bandwidth)
3419 static void
3420 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
3422 unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
3423 enum zfs_nicenum_format format;
3424 char na; /* char to print for "not applicable" values */
3426 if (cb->cb_literal) {
3427 format = ZFS_NICENUM_RAW;
3428 na = '0';
3429 } else {
3430 format = ZFS_NICENUM_1024;
3431 na = '-';
3434 /* only toplevel vdevs have capacity stats */
3435 if (vs->vs_space == 0) {
3436 if (cb->cb_scripted)
3437 printf("\t%c\t%c", na, na);
3438 else
3439 printf(" %*c %*c", column_width, na, column_width,
3440 na);
3441 } else {
3442 print_one_stat(vs->vs_alloc, format, column_width,
3443 cb->cb_scripted);
3444 print_one_stat(vs->vs_space - vs->vs_alloc, format,
3445 column_width, cb->cb_scripted);
3448 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
3449 format, column_width, cb->cb_scripted);
3450 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
3451 format, column_width, cb->cb_scripted);
3452 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
3453 format, column_width, cb->cb_scripted);
3454 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
3455 format, column_width, cb->cb_scripted);
3459 * Print out all the statistics for the given vdev. This can either be the
3460 * toplevel configuration, or called recursively. If 'name' is NULL, then this
3461 * is a verbose output, and we don't want to display the toplevel pool stats.
3463 * Returns the number of stat lines printed.
3465 unsigned int
3466 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
3467 nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
3469 nvlist_t **oldchild, **newchild;
3470 uint_t c, children;
3471 vdev_stat_t *oldvs, *newvs, *calcvs;
3472 vdev_stat_t zerovs = { 0 };
3473 char *vname;
3474 int i;
3475 int ret = 0;
3476 uint64_t tdelta;
3477 double scale;
3479 calcvs = safe_malloc(sizeof (*calcvs));
3481 if (oldnv != NULL) {
3482 verify(nvlist_lookup_uint64_array(oldnv,
3483 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
3484 } else {
3485 oldvs = &zerovs;
3488 /* Do we only want to see a specific vdev? */
3489 for (i = 0; i < cb->cb_vdev_names_count; i++) {
3490 /* Yes we do. Is this the vdev? */
3491 if (strcmp(name, cb->cb_vdev_names[i]) == 0) {
3493 * This is our vdev. Since it is the only vdev we
3494 * will be displaying, make depth = 0 so that it
3495 * doesn't get indented.
3497 depth = 0;
3498 break;
3502 if (cb->cb_vdev_names_count && (i == cb->cb_vdev_names_count)) {
3503 /* Couldn't match the name */
3504 goto children;
3508 verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
3509 (uint64_t **)&newvs, &c) == 0);
3512 * Print the vdev name unless it's is a histogram. Histograms
3513 * display the vdev name in the header itself.
3515 if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
3516 if (cb->cb_scripted) {
3517 printf("%s", name);
3518 } else {
3519 if (strlen(name) + depth > cb->cb_namewidth)
3520 (void) printf("%*s%s", depth, "", name);
3521 else
3522 (void) printf("%*s%s%*s", depth, "", name,
3523 (int)(cb->cb_namewidth - strlen(name) -
3524 depth), "");
3528 /* Calculate our scaling factor */
3529 tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
3530 if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
3532 * If we specify printing histograms with no time interval, then
3533 * print the histogram numbers over the entire lifetime of the
3534 * vdev.
3536 scale = 1;
3537 } else {
3538 if (tdelta == 0)
3539 scale = 1.0;
3540 else
3541 scale = (double)NANOSEC / tdelta;
3544 if (cb->cb_flags & IOS_DEFAULT_M) {
3545 calc_default_iostats(oldvs, newvs, calcvs);
3546 print_iostat_default(calcvs, cb, scale);
3548 if (cb->cb_flags & IOS_LATENCY_M)
3549 print_iostat_latency(cb, oldnv, newnv, scale);
3550 if (cb->cb_flags & IOS_QUEUES_M)
3551 print_iostat_queues(cb, oldnv, newnv, scale);
3552 if (cb->cb_flags & IOS_ANYHISTO_M) {
3553 printf("\n");
3554 print_iostat_histos(cb, oldnv, newnv, scale, name);
3557 if (cb->vcdl != NULL) {
3558 char *path;
3559 if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
3560 &path) == 0) {
3561 printf(" ");
3562 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
3566 if (!(cb->cb_flags & IOS_ANYHISTO_M))
3567 printf("\n");
3569 ret++;
3571 children:
3573 free(calcvs);
3575 if (!cb->cb_verbose)
3576 return (ret);
3578 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
3579 &newchild, &children) != 0)
3580 return (ret);
3582 if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
3583 &oldchild, &c) != 0)
3584 return (ret);
3586 for (c = 0; c < children; c++) {
3587 uint64_t ishole = B_FALSE, islog = B_FALSE;
3589 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
3590 &ishole);
3592 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
3593 &islog);
3595 if (ishole || islog)
3596 continue;
3598 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3599 cb->cb_name_flags);
3600 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
3601 newchild[c], cb, depth + 2);
3602 free(vname);
3606 * Log device section
3609 if (num_logs(newnv) > 0) {
3610 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
3611 !cb->cb_vdev_names) {
3612 print_iostat_dashes(cb, 0, "logs");
3615 for (c = 0; c < children; c++) {
3616 uint64_t islog = B_FALSE;
3617 (void) nvlist_lookup_uint64(newchild[c],
3618 ZPOOL_CONFIG_IS_LOG, &islog);
3620 if (islog) {
3621 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3622 cb->cb_name_flags);
3623 ret += print_vdev_stats(zhp, vname, oldnv ?
3624 oldchild[c] : NULL, newchild[c],
3625 cb, depth + 2);
3626 free(vname);
3633 * Include level 2 ARC devices in iostat output
3635 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
3636 &newchild, &children) != 0)
3637 return (ret);
3639 if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
3640 &oldchild, &c) != 0)
3641 return (ret);
3643 if (children > 0) {
3644 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
3645 !cb->cb_vdev_names) {
3646 print_iostat_dashes(cb, 0, "cache");
3649 for (c = 0; c < children; c++) {
3650 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3651 cb->cb_name_flags);
3652 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
3653 : NULL, newchild[c], cb, depth + 2);
3654 free(vname);
3658 return (ret);
3661 static int
3662 refresh_iostat(zpool_handle_t *zhp, void *data)
3664 iostat_cbdata_t *cb = data;
3665 boolean_t missing;
3668 * If the pool has disappeared, remove it from the list and continue.
3670 if (zpool_refresh_stats(zhp, &missing) != 0)
3671 return (-1);
3673 if (missing)
3674 pool_list_remove(cb->cb_list, zhp);
3676 return (0);
3680 * Callback to print out the iostats for the given pool.
3683 print_iostat(zpool_handle_t *zhp, void *data)
3685 iostat_cbdata_t *cb = data;
3686 nvlist_t *oldconfig, *newconfig;
3687 nvlist_t *oldnvroot, *newnvroot;
3688 int ret;
3690 newconfig = zpool_get_config(zhp, &oldconfig);
3692 if (cb->cb_iteration == 1)
3693 oldconfig = NULL;
3695 verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
3696 &newnvroot) == 0);
3698 if (oldconfig == NULL)
3699 oldnvroot = NULL;
3700 else
3701 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
3702 &oldnvroot) == 0);
3704 ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
3705 cb, 0);
3706 if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
3707 !cb->cb_scripted && cb->cb_verbose && !cb->cb_vdev_names_count) {
3708 print_iostat_separator(cb);
3709 if (cb->vcdl != NULL) {
3710 print_cmd_columns(cb->vcdl, 1);
3712 printf("\n");
3715 return (ret);
3718 static int
3719 get_columns(void)
3721 struct winsize ws;
3722 int columns = 80;
3723 int error;
3725 if (isatty(STDOUT_FILENO)) {
3726 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
3727 if (error == 0)
3728 columns = ws.ws_col;
3729 } else {
3730 columns = 999;
3733 return (columns);
3737 get_namewidth(zpool_handle_t *zhp, void *data)
3739 iostat_cbdata_t *cb = data;
3740 nvlist_t *config, *nvroot;
3741 int columns;
3743 if ((config = zpool_get_config(zhp, NULL)) != NULL) {
3744 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3745 &nvroot) == 0);
3746 unsigned int poolname_len = strlen(zpool_get_name(zhp));
3747 if (!cb->cb_verbose)
3748 cb->cb_namewidth = poolname_len;
3749 else
3750 cb->cb_namewidth = MAX(poolname_len,
3751 max_width(zhp, nvroot, 0, cb->cb_namewidth,
3752 cb->cb_name_flags));
3755 * The width must be at least 10, but may be as large as the
3756 * column width - 42 so that we can still fit in one line.
3758 columns = get_columns();
3760 if (cb->cb_namewidth < 10)
3761 cb->cb_namewidth = 10;
3762 if (cb->cb_namewidth > columns - 42)
3763 cb->cb_namewidth = columns - 42;
3765 return (0);
3769 * Parse the input string, get the 'interval' and 'count' value if there is one.
3771 static void
3772 get_interval_count(int *argcp, char **argv, float *iv,
3773 unsigned long *cnt)
3775 float interval = 0;
3776 unsigned long count = 0;
3777 int argc = *argcp;
3780 * Determine if the last argument is an integer or a pool name
3782 if (argc > 0 && isnumber(argv[argc - 1])) {
3783 char *end;
3785 errno = 0;
3786 interval = strtof(argv[argc - 1], &end);
3788 if (*end == '\0' && errno == 0) {
3789 if (interval == 0) {
3790 (void) fprintf(stderr, gettext("interval "
3791 "cannot be zero\n"));
3792 usage(B_FALSE);
3795 * Ignore the last parameter
3797 argc--;
3798 } else {
3800 * If this is not a valid number, just plow on. The
3801 * user will get a more informative error message later
3802 * on.
3804 interval = 0;
3809 * If the last argument is also an integer, then we have both a count
3810 * and an interval.
3812 if (argc > 0 && isnumber(argv[argc - 1])) {
3813 char *end;
3815 errno = 0;
3816 count = interval;
3817 interval = strtof(argv[argc - 1], &end);
3819 if (*end == '\0' && errno == 0) {
3820 if (interval == 0) {
3821 (void) fprintf(stderr, gettext("interval "
3822 "cannot be zero\n"));
3823 usage(B_FALSE);
3827 * Ignore the last parameter
3829 argc--;
3830 } else {
3831 interval = 0;
3835 *iv = interval;
3836 *cnt = count;
3837 *argcp = argc;
3840 static void
3841 get_timestamp_arg(char c)
3843 if (c == 'u')
3844 timestamp_fmt = UDATE;
3845 else if (c == 'd')
3846 timestamp_fmt = DDATE;
3847 else
3848 usage(B_FALSE);
3852 * Return stat flags that are supported by all pools by both the module and
3853 * zpool iostat. "*data" should be initialized to all 0xFFs before running.
3854 * It will get ANDed down until only the flags that are supported on all pools
3855 * remain.
3857 static int
3858 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
3860 uint64_t *mask = data;
3861 nvlist_t *config, *nvroot, *nvx;
3862 uint64_t flags = 0;
3863 int i, j;
3865 config = zpool_get_config(zhp, NULL);
3866 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3867 &nvroot) == 0);
3869 /* Default stats are always supported, but for completeness.. */
3870 if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
3871 flags |= IOS_DEFAULT_M;
3873 /* Get our extended stats nvlist from the main list */
3874 if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
3875 &nvx) != 0) {
3877 * No extended stats; they're probably running an older
3878 * module. No big deal, we support that too.
3880 goto end;
3883 /* For each extended stat, make sure all its nvpairs are supported */
3884 for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
3885 if (!vsx_type_to_nvlist[j][0])
3886 continue;
3888 /* Start off by assuming the flag is supported, then check */
3889 flags |= (1ULL << j);
3890 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
3891 if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
3892 /* flag isn't supported */
3893 flags = flags & ~(1ULL << j);
3894 break;
3898 end:
3899 *mask = *mask & flags;
3900 return (0);
3904 * Return a bitmask of stats that are supported on all pools by both the module
3905 * and zpool iostat.
3907 static uint64_t
3908 get_stat_flags(zpool_list_t *list)
3910 uint64_t mask = -1;
3913 * get_stat_flags_cb() will lop off bits from "mask" until only the
3914 * flags that are supported on all pools remain.
3916 pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
3917 return (mask);
3921 * Return 1 if cb_data->cb_vdev_names[0] is this vdev's name, 0 otherwise.
3923 static int
3924 is_vdev_cb(zpool_handle_t *zhp, nvlist_t *nv, void *cb_data)
3926 iostat_cbdata_t *cb = cb_data;
3927 char *name = NULL;
3928 int ret = 0;
3930 name = zpool_vdev_name(g_zfs, zhp, nv, cb->cb_name_flags);
3932 if (strcmp(name, cb->cb_vdev_names[0]) == 0)
3933 ret = 1; /* match */
3934 free(name);
3936 return (ret);
3940 * Returns 1 if cb_data->cb_vdev_names[0] is a vdev name, 0 otherwise.
3942 static int
3943 is_vdev(zpool_handle_t *zhp, void *cb_data)
3945 return (for_each_vdev(zhp, is_vdev_cb, cb_data));
3949 * Check if vdevs are in a pool
3951 * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
3952 * return 0. If pool_name is NULL, then search all pools.
3954 static int
3955 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
3956 iostat_cbdata_t *cb)
3958 char **tmp_name;
3959 int ret = 0;
3960 int i;
3961 int pool_count = 0;
3963 if ((argc == 0) || !*argv)
3964 return (0);
3966 if (pool_name)
3967 pool_count = 1;
3969 /* Temporarily hijack cb_vdev_names for a second... */
3970 tmp_name = cb->cb_vdev_names;
3972 /* Go though our list of prospective vdev names */
3973 for (i = 0; i < argc; i++) {
3974 cb->cb_vdev_names = argv + i;
3976 /* Is this name a vdev in our pools? */
3977 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
3978 is_vdev, cb);
3979 if (!ret) {
3980 /* No match */
3981 break;
3985 cb->cb_vdev_names = tmp_name;
3987 return (ret);
3990 static int
3991 is_pool_cb(zpool_handle_t *zhp, void *data)
3993 char *name = data;
3994 if (strcmp(name, zpool_get_name(zhp)) == 0)
3995 return (1);
3997 return (0);
4001 * Do we have a pool named *name? If so, return 1, otherwise 0.
4003 static int
4004 is_pool(char *name)
4006 return (for_each_pool(0, NULL, B_TRUE, NULL, is_pool_cb, name));
4009 /* Are all our argv[] strings pool names? If so return 1, 0 otherwise. */
4010 static int
4011 are_all_pools(int argc, char **argv)
4013 if ((argc == 0) || !*argv)
4014 return (0);
4016 while (--argc >= 0)
4017 if (!is_pool(argv[argc]))
4018 return (0);
4020 return (1);
4024 * Helper function to print out vdev/pool names we can't resolve. Used for an
4025 * error message.
4027 static void
4028 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
4029 iostat_cbdata_t *cb)
4031 int i;
4032 char *name;
4033 char *str;
4034 for (i = 0; i < argc; i++) {
4035 name = argv[i];
4037 if (is_pool(name))
4038 str = gettext("pool");
4039 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
4040 str = gettext("vdev in this pool");
4041 else if (are_vdevs_in_pool(1, &name, NULL, cb))
4042 str = gettext("vdev in another pool");
4043 else
4044 str = gettext("unknown");
4046 fprintf(stderr, "\t%s (%s)\n", name, str);
4051 * Same as get_interval_count(), but with additional checks to not misinterpret
4052 * guids as interval/count values. Assumes VDEV_NAME_GUID is set in
4053 * cb.cb_name_flags.
4055 static void
4056 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
4057 unsigned long *count, iostat_cbdata_t *cb)
4059 char **tmpargv = argv;
4060 int argc_for_interval = 0;
4062 /* Is the last arg an interval value? Or a guid? */
4063 if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL, cb)) {
4065 * The last arg is not a guid, so it's probably an
4066 * interval value.
4068 argc_for_interval++;
4070 if (*argc >= 2 &&
4071 !are_vdevs_in_pool(1, &argv[*argc - 2], NULL, cb)) {
4073 * The 2nd to last arg is not a guid, so it's probably
4074 * an interval value.
4076 argc_for_interval++;
4080 /* Point to our list of possible intervals */
4081 tmpargv = &argv[*argc - argc_for_interval];
4083 *argc = *argc - argc_for_interval;
4084 get_interval_count(&argc_for_interval, tmpargv,
4085 interval, count);
4089 * Floating point sleep(). Allows you to pass in a floating point value for
4090 * seconds.
4092 static void
4093 fsleep(float sec)
4095 struct timespec req;
4096 req.tv_sec = floor(sec);
4097 req.tv_nsec = (sec - (float)req.tv_sec) * NANOSEC;
4098 nanosleep(&req, NULL);
4102 * Run one of the zpool status/iostat -c scripts with the help (-h) option and
4103 * print the result.
4105 * name: Short name of the script ('iostat').
4106 * path: Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
4108 static void
4109 print_zpool_script_help(char *name, char *path)
4111 char *argv[] = {path, "-h", NULL};
4112 char **lines = NULL;
4113 int lines_cnt = 0;
4114 int rc;
4116 rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
4117 &lines_cnt);
4118 if (rc != 0 || lines == NULL || lines_cnt <= 0)
4119 return;
4121 for (int i = 0; i < lines_cnt; i++)
4122 if (!is_blank_str(lines[i]))
4123 printf(" %-14s %s\n", name, lines[i]);
4125 libzfs_free_str_array(lines, lines_cnt);
4130 * Go though the list of all the zpool status/iostat -c scripts, run their
4131 * help option (-h), and print out the results.
4133 static void
4134 print_zpool_script_list(void)
4136 DIR *dir;
4137 struct dirent *ent;
4138 char fullpath[MAXPATHLEN];
4139 struct stat dir_stat;
4141 if ((dir = opendir(ZPOOL_SCRIPTS_DIR)) != NULL) {
4142 printf("\n");
4143 /* print all the files and directories within directory */
4144 while ((ent = readdir(dir)) != NULL) {
4145 sprintf(fullpath, "%s/%s", ZPOOL_SCRIPTS_DIR,
4146 ent->d_name);
4148 /* Print the scripts */
4149 if (stat(fullpath, &dir_stat) == 0)
4150 if (dir_stat.st_mode & S_IXUSR &&
4151 S_ISREG(dir_stat.st_mode))
4152 print_zpool_script_help(ent->d_name,
4153 fullpath);
4155 printf("\n");
4156 closedir(dir);
4157 } else {
4158 fprintf(stderr, gettext("Can't open %s scripts dir\n"),
4159 ZPOOL_SCRIPTS_DIR);
4164 * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
4165 * [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
4166 * [interval [count]]
4168 * -c CMD For each vdev, run command CMD
4169 * -g Display guid for individual vdev name.
4170 * -L Follow links when resolving vdev path name.
4171 * -P Display full path for vdev name.
4172 * -v Display statistics for individual vdevs
4173 * -h Display help
4174 * -p Display values in parsable (exact) format.
4175 * -H Scripted mode. Don't display headers, and separate properties
4176 * by a single tab.
4177 * -l Display average latency
4178 * -q Display queue depths
4179 * -w Display latency histograms
4180 * -r Display request size histogram
4181 * -T Display a timestamp in date(1) or Unix format
4183 * This command can be tricky because we want to be able to deal with pool
4184 * creation/destruction as well as vdev configuration changes. The bulk of this
4185 * processing is handled by the pool_list_* routines in zpool_iter.c. We rely
4186 * on pool_list_update() to detect the addition of new pools. Configuration
4187 * changes are all handled within libzfs.
4190 zpool_do_iostat(int argc, char **argv)
4192 int c;
4193 int ret;
4194 int npools;
4195 float interval = 0;
4196 unsigned long count = 0;
4197 zpool_list_t *list;
4198 boolean_t verbose = B_FALSE;
4199 boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
4200 boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
4201 boolean_t omit_since_boot = B_FALSE;
4202 boolean_t guid = B_FALSE;
4203 boolean_t follow_links = B_FALSE;
4204 boolean_t full_name = B_FALSE;
4205 iostat_cbdata_t cb = { 0 };
4206 char *cmd = NULL;
4208 /* Used for printing error message */
4209 const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
4210 [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
4212 uint64_t unsupported_flags;
4214 /* check options */
4215 while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwH")) != -1) {
4216 switch (c) {
4217 case 'c':
4218 if (cmd != NULL) {
4219 fprintf(stderr,
4220 gettext("Can't set -c flag twice\n"));
4221 exit(1);
4223 if ((getuid() <= 0 || geteuid() <= 0) &&
4224 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
4225 fprintf(stderr, gettext(
4226 "Can't run -c with root privileges "
4227 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
4228 exit(1);
4230 cmd = optarg;
4231 verbose = B_TRUE;
4232 break;
4233 case 'g':
4234 guid = B_TRUE;
4235 break;
4236 case 'L':
4237 follow_links = B_TRUE;
4238 break;
4239 case 'P':
4240 full_name = B_TRUE;
4241 break;
4242 case 'T':
4243 get_timestamp_arg(*optarg);
4244 break;
4245 case 'v':
4246 verbose = B_TRUE;
4247 break;
4248 case 'p':
4249 parsable = B_TRUE;
4250 break;
4251 case 'l':
4252 latency = B_TRUE;
4253 break;
4254 case 'q':
4255 queues = B_TRUE;
4256 break;
4257 case 'H':
4258 scripted = B_TRUE;
4259 break;
4260 case 'w':
4261 l_histo = B_TRUE;
4262 break;
4263 case 'r':
4264 rq_histo = B_TRUE;
4265 break;
4266 case 'y':
4267 omit_since_boot = B_TRUE;
4268 break;
4269 case 'h':
4270 usage(B_FALSE);
4271 break;
4272 case '?':
4273 if (optopt == 'c') {
4274 fprintf(stderr, gettext(
4275 "Current scripts in %s:\n"),
4276 ZPOOL_SCRIPTS_DIR);
4277 print_zpool_script_list();
4278 exit(0);
4279 } else {
4280 fprintf(stderr,
4281 gettext("invalid option '%c'\n"), optopt);
4283 usage(B_FALSE);
4287 argc -= optind;
4288 argv += optind;
4290 cb.cb_literal = parsable;
4291 cb.cb_scripted = scripted;
4293 if (guid)
4294 cb.cb_name_flags |= VDEV_NAME_GUID;
4295 if (follow_links)
4296 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
4297 if (full_name)
4298 cb.cb_name_flags |= VDEV_NAME_PATH;
4299 cb.cb_iteration = 0;
4300 cb.cb_namewidth = 0;
4301 cb.cb_verbose = verbose;
4303 /* Get our interval and count values (if any) */
4304 if (guid) {
4305 get_interval_count_filter_guids(&argc, argv, &interval,
4306 &count, &cb);
4307 } else {
4308 get_interval_count(&argc, argv, &interval, &count);
4311 if (argc == 0) {
4312 /* No args, so just print the defaults. */
4313 } else if (are_all_pools(argc, argv)) {
4314 /* All the args are pool names */
4315 } else if (are_vdevs_in_pool(argc, argv, NULL, &cb)) {
4316 /* All the args are vdevs */
4317 cb.cb_vdev_names = argv;
4318 cb.cb_vdev_names_count = argc;
4319 argc = 0; /* No pools to process */
4320 } else if (are_all_pools(1, argv)) {
4321 /* The first arg is a pool name */
4322 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0], &cb)) {
4323 /* ...and the rest are vdev names */
4324 cb.cb_vdev_names = argv + 1;
4325 cb.cb_vdev_names_count = argc - 1;
4326 argc = 1; /* One pool to process */
4327 } else {
4328 fprintf(stderr, gettext("Expected either a list of "));
4329 fprintf(stderr, gettext("pools, or list of vdevs in"));
4330 fprintf(stderr, " \"%s\", ", argv[0]);
4331 fprintf(stderr, gettext("but got:\n"));
4332 error_list_unresolved_vdevs(argc - 1, argv + 1,
4333 argv[0], &cb);
4334 fprintf(stderr, "\n");
4335 usage(B_FALSE);
4336 return (1);
4338 } else {
4340 * The args don't make sense. The first arg isn't a pool name,
4341 * nor are all the args vdevs.
4343 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
4344 fprintf(stderr, "\n");
4345 return (1);
4348 if (cb.cb_vdev_names_count != 0) {
4350 * If user specified vdevs, it implies verbose.
4352 cb.cb_verbose = B_TRUE;
4356 * Construct the list of all interesting pools.
4358 ret = 0;
4359 if ((list = pool_list_get(argc, argv, NULL, &ret)) == NULL)
4360 return (1);
4362 if (pool_list_count(list) == 0 && argc != 0) {
4363 pool_list_free(list);
4364 return (1);
4367 if (pool_list_count(list) == 0 && interval == 0) {
4368 pool_list_free(list);
4369 (void) fprintf(stderr, gettext("no pools available\n"));
4370 return (1);
4373 if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
4374 pool_list_free(list);
4375 (void) fprintf(stderr,
4376 gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
4377 usage(B_FALSE);
4378 return (1);
4381 if (l_histo && rq_histo) {
4382 pool_list_free(list);
4383 (void) fprintf(stderr,
4384 gettext("Only one of [-r|-w] can be passed at a time\n"));
4385 usage(B_FALSE);
4386 return (1);
4390 * Enter the main iostat loop.
4392 cb.cb_list = list;
4394 if (l_histo) {
4396 * Histograms tables look out of place when you try to display
4397 * them with the other stats, so make a rule that you can only
4398 * print histograms by themselves.
4400 cb.cb_flags = IOS_L_HISTO_M;
4401 } else if (rq_histo) {
4402 cb.cb_flags = IOS_RQ_HISTO_M;
4403 } else {
4404 cb.cb_flags = IOS_DEFAULT_M;
4405 if (latency)
4406 cb.cb_flags |= IOS_LATENCY_M;
4407 if (queues)
4408 cb.cb_flags |= IOS_QUEUES_M;
4412 * See if the module supports all the stats we want to display.
4414 unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
4415 if (unsupported_flags) {
4416 uint64_t f;
4417 int idx;
4418 fprintf(stderr,
4419 gettext("The loaded zfs module doesn't support:"));
4421 /* for each bit set in unsupported_flags */
4422 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
4423 idx = lowbit64(f) - 1;
4424 fprintf(stderr, " -%c", flag_to_arg[idx]);
4427 fprintf(stderr, ". Try running a newer module.\n");
4428 pool_list_free(list);
4430 return (1);
4433 for (;;) {
4434 if ((npools = pool_list_count(list)) == 0)
4435 (void) fprintf(stderr, gettext("no pools available\n"));
4436 else {
4438 * If this is the first iteration and -y was supplied
4439 * we skip any printing.
4441 boolean_t skip = (omit_since_boot &&
4442 cb.cb_iteration == 0);
4445 * Refresh all statistics. This is done as an
4446 * explicit step before calculating the maximum name
4447 * width, so that any * configuration changes are
4448 * properly accounted for.
4450 (void) pool_list_iter(list, B_FALSE, refresh_iostat,
4451 &cb);
4454 * Iterate over all pools to determine the maximum width
4455 * for the pool / device name column across all pools.
4457 cb.cb_namewidth = 0;
4458 (void) pool_list_iter(list, B_FALSE, get_namewidth,
4459 &cb);
4461 if (timestamp_fmt != NODATE)
4462 print_timestamp(timestamp_fmt);
4464 if (cmd != NULL && cb.cb_verbose &&
4465 !(cb.cb_flags & IOS_ANYHISTO_M)) {
4466 cb.vcdl = all_pools_for_each_vdev_run(argc,
4467 argv, cmd, g_zfs, cb.cb_vdev_names,
4468 cb.cb_vdev_names_count, cb.cb_name_flags);
4469 } else {
4470 cb.vcdl = NULL;
4474 * If it's the first time and we're not skipping it,
4475 * or either skip or verbose mode, print the header.
4477 * The histogram code explicitly prints its header on
4478 * every vdev, so skip this for histograms.
4480 if (((++cb.cb_iteration == 1 && !skip) ||
4481 (skip != verbose)) &&
4482 (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
4483 !cb.cb_scripted)
4484 print_iostat_header(&cb);
4486 if (skip) {
4487 (void) fsleep(interval);
4488 continue;
4492 pool_list_iter(list, B_FALSE, print_iostat, &cb);
4495 * If there's more than one pool, and we're not in
4496 * verbose mode (which prints a separator for us),
4497 * then print a separator.
4499 * In addition, if we're printing specific vdevs then
4500 * we also want an ending separator.
4502 if (((npools > 1 && !verbose &&
4503 !(cb.cb_flags & IOS_ANYHISTO_M)) ||
4504 (!(cb.cb_flags & IOS_ANYHISTO_M) &&
4505 cb.cb_vdev_names_count)) &&
4506 !cb.cb_scripted) {
4507 print_iostat_separator(&cb);
4508 if (cb.vcdl != NULL)
4509 print_cmd_columns(cb.vcdl, 1);
4510 printf("\n");
4513 if (cb.vcdl != NULL)
4514 free_vdev_cmd_data_list(cb.vcdl);
4519 * Flush the output so that redirection to a file isn't buffered
4520 * indefinitely.
4522 (void) fflush(stdout);
4524 if (interval == 0)
4525 break;
4527 if (count != 0 && --count == 0)
4528 break;
4530 (void) fsleep(interval);
4533 pool_list_free(list);
4535 return (ret);
4538 typedef struct list_cbdata {
4539 boolean_t cb_verbose;
4540 int cb_name_flags;
4541 int cb_namewidth;
4542 boolean_t cb_scripted;
4543 zprop_list_t *cb_proplist;
4544 boolean_t cb_literal;
4545 } list_cbdata_t;
4548 * Given a list of columns to display, output appropriate headers for each one.
4550 static void
4551 print_header(list_cbdata_t *cb)
4553 zprop_list_t *pl = cb->cb_proplist;
4554 char headerbuf[ZPOOL_MAXPROPLEN];
4555 const char *header;
4556 boolean_t first = B_TRUE;
4557 boolean_t right_justify;
4558 size_t width = 0;
4560 for (; pl != NULL; pl = pl->pl_next) {
4561 width = pl->pl_width;
4562 if (first && cb->cb_verbose) {
4564 * Reset the width to accommodate the verbose listing
4565 * of devices.
4567 width = cb->cb_namewidth;
4570 if (!first)
4571 (void) printf(" ");
4572 else
4573 first = B_FALSE;
4575 right_justify = B_FALSE;
4576 if (pl->pl_prop != ZPROP_INVAL) {
4577 header = zpool_prop_column_name(pl->pl_prop);
4578 right_justify = zpool_prop_align_right(pl->pl_prop);
4579 } else {
4580 int i;
4582 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
4583 headerbuf[i] = toupper(pl->pl_user_prop[i]);
4584 headerbuf[i] = '\0';
4585 header = headerbuf;
4588 if (pl->pl_next == NULL && !right_justify)
4589 (void) printf("%s", header);
4590 else if (right_justify)
4591 (void) printf("%*s", (int)width, header);
4592 else
4593 (void) printf("%-*s", (int)width, header);
4596 (void) printf("\n");
4600 * Given a pool and a list of properties, print out all the properties according
4601 * to the described layout.
4603 static void
4604 print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
4606 zprop_list_t *pl = cb->cb_proplist;
4607 boolean_t first = B_TRUE;
4608 char property[ZPOOL_MAXPROPLEN];
4609 char *propstr;
4610 boolean_t right_justify;
4611 size_t width;
4613 for (; pl != NULL; pl = pl->pl_next) {
4615 width = pl->pl_width;
4616 if (first && cb->cb_verbose) {
4618 * Reset the width to accommodate the verbose listing
4619 * of devices.
4621 width = cb->cb_namewidth;
4624 if (!first) {
4625 if (cb->cb_scripted)
4626 (void) printf("\t");
4627 else
4628 (void) printf(" ");
4629 } else {
4630 first = B_FALSE;
4633 right_justify = B_FALSE;
4634 if (pl->pl_prop != ZPROP_INVAL) {
4635 if (zpool_get_prop(zhp, pl->pl_prop, property,
4636 sizeof (property), NULL, cb->cb_literal) != 0)
4637 propstr = "-";
4638 else
4639 propstr = property;
4641 right_justify = zpool_prop_align_right(pl->pl_prop);
4642 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
4643 zpool_prop_unsupported(pl->pl_user_prop)) &&
4644 zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
4645 sizeof (property)) == 0) {
4646 propstr = property;
4647 } else {
4648 propstr = "-";
4653 * If this is being called in scripted mode, or if this is the
4654 * last column and it is left-justified, don't include a width
4655 * format specifier.
4657 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
4658 (void) printf("%s", propstr);
4659 else if (right_justify)
4660 (void) printf("%*s", (int)width, propstr);
4661 else
4662 (void) printf("%-*s", (int)width, propstr);
4665 (void) printf("\n");
4668 static void
4669 print_one_column(zpool_prop_t prop, uint64_t value, boolean_t scripted,
4670 boolean_t valid, enum zfs_nicenum_format format)
4672 char propval[64];
4673 boolean_t fixed;
4674 size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
4676 switch (prop) {
4677 case ZPOOL_PROP_EXPANDSZ:
4678 if (value == 0)
4679 (void) strlcpy(propval, "-", sizeof (propval));
4680 else
4681 zfs_nicenum_format(value, propval, sizeof (propval),
4682 format);
4683 break;
4684 case ZPOOL_PROP_FRAGMENTATION:
4685 if (value == ZFS_FRAG_INVALID) {
4686 (void) strlcpy(propval, "-", sizeof (propval));
4687 } else if (format == ZFS_NICENUM_RAW) {
4688 (void) snprintf(propval, sizeof (propval), "%llu",
4689 (unsigned long long)value);
4690 } else {
4691 (void) snprintf(propval, sizeof (propval), "%llu%%",
4692 (unsigned long long)value);
4694 break;
4695 case ZPOOL_PROP_CAPACITY:
4696 if (format == ZFS_NICENUM_RAW)
4697 (void) snprintf(propval, sizeof (propval), "%llu",
4698 (unsigned long long)value);
4699 else
4700 (void) snprintf(propval, sizeof (propval), "%llu%%",
4701 (unsigned long long)value);
4702 break;
4703 default:
4704 zfs_nicenum_format(value, propval, sizeof (propval), format);
4707 if (!valid)
4708 (void) strlcpy(propval, "-", sizeof (propval));
4710 if (scripted)
4711 (void) printf("\t%s", propval);
4712 else
4713 (void) printf(" %*s", (int)width, propval);
4716 void
4717 print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
4718 list_cbdata_t *cb, int depth)
4720 nvlist_t **child;
4721 vdev_stat_t *vs;
4722 uint_t c, children;
4723 char *vname;
4724 boolean_t scripted = cb->cb_scripted;
4725 uint64_t islog = B_FALSE;
4726 boolean_t haslog = B_FALSE;
4727 char *dashes = "%-*s - - - - - -\n";
4729 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
4730 (uint64_t **)&vs, &c) == 0);
4732 if (name != NULL) {
4733 boolean_t toplevel = (vs->vs_space != 0);
4734 uint64_t cap;
4735 enum zfs_nicenum_format format;
4737 if (cb->cb_literal)
4738 format = ZFS_NICENUM_RAW;
4739 else
4740 format = ZFS_NICENUM_1024;
4742 if (scripted)
4743 (void) printf("\t%s", name);
4744 else if (strlen(name) + depth > cb->cb_namewidth)
4745 (void) printf("%*s%s", depth, "", name);
4746 else
4747 (void) printf("%*s%s%*s", depth, "", name,
4748 (int)(cb->cb_namewidth - strlen(name) - depth), "");
4751 * Print the properties for the individual vdevs. Some
4752 * properties are only applicable to toplevel vdevs. The
4753 * 'toplevel' boolean value is passed to the print_one_column()
4754 * to indicate that the value is valid.
4756 print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, scripted,
4757 toplevel, format);
4758 print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, scripted,
4759 toplevel, format);
4760 print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
4761 scripted, toplevel, format);
4762 print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, scripted,
4763 B_TRUE, format);
4764 print_one_column(ZPOOL_PROP_FRAGMENTATION,
4765 vs->vs_fragmentation, scripted,
4766 (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
4767 format);
4768 cap = (vs->vs_space == 0) ? 0 :
4769 (vs->vs_alloc * 100 / vs->vs_space);
4770 print_one_column(ZPOOL_PROP_CAPACITY, cap, scripted, toplevel,
4771 format);
4772 (void) printf("\n");
4775 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
4776 &child, &children) != 0)
4777 return;
4779 for (c = 0; c < children; c++) {
4780 uint64_t ishole = B_FALSE;
4782 if (nvlist_lookup_uint64(child[c],
4783 ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
4784 continue;
4786 if (nvlist_lookup_uint64(child[c],
4787 ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog) {
4788 haslog = B_TRUE;
4789 continue;
4792 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4793 cb->cb_name_flags);
4794 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4795 free(vname);
4798 if (haslog == B_TRUE) {
4799 /* LINTED E_SEC_PRINTF_VAR_FMT */
4800 (void) printf(dashes, cb->cb_namewidth, "log");
4801 for (c = 0; c < children; c++) {
4802 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
4803 &islog) != 0 || !islog)
4804 continue;
4805 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4806 cb->cb_name_flags);
4807 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4808 free(vname);
4812 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
4813 &child, &children) == 0 && children > 0) {
4814 /* LINTED E_SEC_PRINTF_VAR_FMT */
4815 (void) printf(dashes, cb->cb_namewidth, "cache");
4816 for (c = 0; c < children; c++) {
4817 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4818 cb->cb_name_flags);
4819 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4820 free(vname);
4824 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
4825 &children) == 0 && children > 0) {
4826 /* LINTED E_SEC_PRINTF_VAR_FMT */
4827 (void) printf(dashes, cb->cb_namewidth, "spare");
4828 for (c = 0; c < children; c++) {
4829 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4830 cb->cb_name_flags);
4831 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4832 free(vname);
4839 * Generic callback function to list a pool.
4842 list_callback(zpool_handle_t *zhp, void *data)
4844 list_cbdata_t *cbp = data;
4845 nvlist_t *config;
4846 nvlist_t *nvroot;
4848 config = zpool_get_config(zhp, NULL);
4850 print_pool(zhp, cbp);
4851 if (!cbp->cb_verbose)
4852 return (0);
4854 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4855 &nvroot) == 0);
4856 print_list_stats(zhp, NULL, nvroot, cbp, 0);
4858 return (0);
4862 * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
4864 * -g Display guid for individual vdev name.
4865 * -H Scripted mode. Don't display headers, and separate properties
4866 * by a single tab.
4867 * -L Follow links when resolving vdev path name.
4868 * -o List of properties to display. Defaults to
4869 * "name,size,allocated,free,expandsize,fragmentation,capacity,"
4870 * "dedupratio,health,altroot"
4871 * -p Display values in parsable (exact) format.
4872 * -P Display full path for vdev name.
4873 * -T Display a timestamp in date(1) or Unix format
4875 * List all pools in the system, whether or not they're healthy. Output space
4876 * statistics for each one, as well as health status summary.
4879 zpool_do_list(int argc, char **argv)
4881 int c;
4882 int ret = 0;
4883 list_cbdata_t cb = { 0 };
4884 static char default_props[] =
4885 "name,size,allocated,free,expandsize,fragmentation,capacity,"
4886 "dedupratio,health,altroot";
4887 char *props = default_props;
4888 float interval = 0;
4889 unsigned long count = 0;
4890 zpool_list_t *list;
4891 boolean_t first = B_TRUE;
4893 /* check options */
4894 while ((c = getopt(argc, argv, ":gHLo:pPT:v")) != -1) {
4895 switch (c) {
4896 case 'g':
4897 cb.cb_name_flags |= VDEV_NAME_GUID;
4898 break;
4899 case 'H':
4900 cb.cb_scripted = B_TRUE;
4901 break;
4902 case 'L':
4903 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
4904 break;
4905 case 'o':
4906 props = optarg;
4907 break;
4908 case 'P':
4909 cb.cb_name_flags |= VDEV_NAME_PATH;
4910 break;
4911 case 'p':
4912 cb.cb_literal = B_TRUE;
4913 break;
4914 case 'T':
4915 get_timestamp_arg(*optarg);
4916 break;
4917 case 'v':
4918 cb.cb_verbose = B_TRUE;
4919 break;
4920 case ':':
4921 (void) fprintf(stderr, gettext("missing argument for "
4922 "'%c' option\n"), optopt);
4923 usage(B_FALSE);
4924 break;
4925 case '?':
4926 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4927 optopt);
4928 usage(B_FALSE);
4932 argc -= optind;
4933 argv += optind;
4935 get_interval_count(&argc, argv, &interval, &count);
4937 if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
4938 usage(B_FALSE);
4940 for (;;) {
4941 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
4942 &ret)) == NULL)
4943 return (1);
4945 if (pool_list_count(list) == 0)
4946 break;
4948 if (timestamp_fmt != NODATE)
4949 print_timestamp(timestamp_fmt);
4951 if (!cb.cb_scripted && (first || cb.cb_verbose)) {
4952 print_header(&cb);
4953 first = B_FALSE;
4955 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
4957 if (interval == 0)
4958 break;
4960 if (count != 0 && --count == 0)
4961 break;
4963 pool_list_free(list);
4964 (void) fsleep(interval);
4967 if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
4968 (void) printf(gettext("no pools available\n"));
4969 ret = 0;
4972 pool_list_free(list);
4973 zprop_free_list(cb.cb_proplist);
4974 return (ret);
4977 static int
4978 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
4980 boolean_t force = B_FALSE;
4981 int c;
4982 nvlist_t *nvroot;
4983 char *poolname, *old_disk, *new_disk;
4984 zpool_handle_t *zhp;
4985 nvlist_t *props = NULL;
4986 char *propval;
4987 int ret;
4989 /* check options */
4990 while ((c = getopt(argc, argv, "fo:")) != -1) {
4991 switch (c) {
4992 case 'f':
4993 force = B_TRUE;
4994 break;
4995 case 'o':
4996 if ((propval = strchr(optarg, '=')) == NULL) {
4997 (void) fprintf(stderr, gettext("missing "
4998 "'=' for -o option\n"));
4999 usage(B_FALSE);
5001 *propval = '\0';
5002 propval++;
5004 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
5005 (add_prop_list(optarg, propval, &props, B_TRUE)))
5006 usage(B_FALSE);
5007 break;
5008 case '?':
5009 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5010 optopt);
5011 usage(B_FALSE);
5015 argc -= optind;
5016 argv += optind;
5018 /* get pool name and check number of arguments */
5019 if (argc < 1) {
5020 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5021 usage(B_FALSE);
5024 poolname = argv[0];
5026 if (argc < 2) {
5027 (void) fprintf(stderr,
5028 gettext("missing <device> specification\n"));
5029 usage(B_FALSE);
5032 old_disk = argv[1];
5034 if (argc < 3) {
5035 if (!replacing) {
5036 (void) fprintf(stderr,
5037 gettext("missing <new_device> specification\n"));
5038 usage(B_FALSE);
5040 new_disk = old_disk;
5041 argc -= 1;
5042 argv += 1;
5043 } else {
5044 new_disk = argv[2];
5045 argc -= 2;
5046 argv += 2;
5049 if (argc > 1) {
5050 (void) fprintf(stderr, gettext("too many arguments\n"));
5051 usage(B_FALSE);
5054 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
5055 nvlist_free(props);
5056 return (1);
5059 if (zpool_get_config(zhp, NULL) == NULL) {
5060 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
5061 poolname);
5062 zpool_close(zhp);
5063 nvlist_free(props);
5064 return (1);
5067 nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
5068 argc, argv);
5069 if (nvroot == NULL) {
5070 zpool_close(zhp);
5071 nvlist_free(props);
5072 return (1);
5075 ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing);
5077 nvlist_free(props);
5078 nvlist_free(nvroot);
5079 zpool_close(zhp);
5081 return (ret);
5085 * zpool replace [-f] <pool> <device> <new_device>
5087 * -f Force attach, even if <new_device> appears to be in use.
5089 * Replace <device> with <new_device>.
5091 /* ARGSUSED */
5093 zpool_do_replace(int argc, char **argv)
5095 return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
5099 * zpool attach [-f] [-o property=value] <pool> <device> <new_device>
5101 * -f Force attach, even if <new_device> appears to be in use.
5102 * -o Set property=value.
5104 * Attach <new_device> to the mirror containing <device>. If <device> is not
5105 * part of a mirror, then <device> will be transformed into a mirror of
5106 * <device> and <new_device>. In either case, <new_device> will begin life
5107 * with a DTL of [0, now], and will immediately begin to resilver itself.
5110 zpool_do_attach(int argc, char **argv)
5112 return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
5116 * zpool detach [-f] <pool> <device>
5118 * -f Force detach of <device>, even if DTLs argue against it
5119 * (not supported yet)
5121 * Detach a device from a mirror. The operation will be refused if <device>
5122 * is the last device in the mirror, or if the DTLs indicate that this device
5123 * has the only valid copy of some data.
5125 /* ARGSUSED */
5127 zpool_do_detach(int argc, char **argv)
5129 int c;
5130 char *poolname, *path;
5131 zpool_handle_t *zhp;
5132 int ret;
5134 /* check options */
5135 while ((c = getopt(argc, argv, "f")) != -1) {
5136 switch (c) {
5137 case 'f':
5138 case '?':
5139 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5140 optopt);
5141 usage(B_FALSE);
5145 argc -= optind;
5146 argv += optind;
5148 /* get pool name and check number of arguments */
5149 if (argc < 1) {
5150 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5151 usage(B_FALSE);
5154 if (argc < 2) {
5155 (void) fprintf(stderr,
5156 gettext("missing <device> specification\n"));
5157 usage(B_FALSE);
5160 poolname = argv[0];
5161 path = argv[1];
5163 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5164 return (1);
5166 ret = zpool_vdev_detach(zhp, path);
5168 zpool_close(zhp);
5170 return (ret);
5174 * zpool split [-gLnP] [-o prop=val] ...
5175 * [-o mntopt] ...
5176 * [-R altroot] <pool> <newpool> [<device> ...]
5178 * -g Display guid for individual vdev name.
5179 * -L Follow links when resolving vdev path name.
5180 * -n Do not split the pool, but display the resulting layout if
5181 * it were to be split.
5182 * -o Set property=value, or set mount options.
5183 * -P Display full path for vdev name.
5184 * -R Mount the split-off pool under an alternate root.
5186 * Splits the named pool and gives it the new pool name. Devices to be split
5187 * off may be listed, provided that no more than one device is specified
5188 * per top-level vdev mirror. The newly split pool is left in an exported
5189 * state unless -R is specified.
5191 * Restrictions: the top-level of the pool pool must only be made up of
5192 * mirrors; all devices in the pool must be healthy; no device may be
5193 * undergoing a resilvering operation.
5196 zpool_do_split(int argc, char **argv)
5198 char *srcpool, *newpool, *propval;
5199 char *mntopts = NULL;
5200 splitflags_t flags;
5201 int c, ret = 0;
5202 zpool_handle_t *zhp;
5203 nvlist_t *config, *props = NULL;
5205 flags.dryrun = B_FALSE;
5206 flags.import = B_FALSE;
5207 flags.name_flags = 0;
5209 /* check options */
5210 while ((c = getopt(argc, argv, ":gLR:no:P")) != -1) {
5211 switch (c) {
5212 case 'g':
5213 flags.name_flags |= VDEV_NAME_GUID;
5214 break;
5215 case 'L':
5216 flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
5217 break;
5218 case 'R':
5219 flags.import = B_TRUE;
5220 if (add_prop_list(
5221 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
5222 &props, B_TRUE) != 0) {
5223 nvlist_free(props);
5224 usage(B_FALSE);
5226 break;
5227 case 'n':
5228 flags.dryrun = B_TRUE;
5229 break;
5230 case 'o':
5231 if ((propval = strchr(optarg, '=')) != NULL) {
5232 *propval = '\0';
5233 propval++;
5234 if (add_prop_list(optarg, propval,
5235 &props, B_TRUE) != 0) {
5236 nvlist_free(props);
5237 usage(B_FALSE);
5239 } else {
5240 mntopts = optarg;
5242 break;
5243 case 'P':
5244 flags.name_flags |= VDEV_NAME_PATH;
5245 break;
5246 case ':':
5247 (void) fprintf(stderr, gettext("missing argument for "
5248 "'%c' option\n"), optopt);
5249 usage(B_FALSE);
5250 break;
5251 case '?':
5252 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5253 optopt);
5254 usage(B_FALSE);
5255 break;
5259 if (!flags.import && mntopts != NULL) {
5260 (void) fprintf(stderr, gettext("setting mntopts is only "
5261 "valid when importing the pool\n"));
5262 usage(B_FALSE);
5265 argc -= optind;
5266 argv += optind;
5268 if (argc < 1) {
5269 (void) fprintf(stderr, gettext("Missing pool name\n"));
5270 usage(B_FALSE);
5272 if (argc < 2) {
5273 (void) fprintf(stderr, gettext("Missing new pool name\n"));
5274 usage(B_FALSE);
5277 srcpool = argv[0];
5278 newpool = argv[1];
5280 argc -= 2;
5281 argv += 2;
5283 if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
5284 nvlist_free(props);
5285 return (1);
5288 config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
5289 if (config == NULL) {
5290 ret = 1;
5291 } else {
5292 if (flags.dryrun) {
5293 (void) printf(gettext("would create '%s' with the "
5294 "following layout:\n\n"), newpool);
5295 print_vdev_tree(NULL, newpool, config, 0, B_FALSE,
5296 flags.name_flags);
5300 zpool_close(zhp);
5302 if (ret != 0 || flags.dryrun || !flags.import) {
5303 nvlist_free(config);
5304 nvlist_free(props);
5305 return (ret);
5309 * The split was successful. Now we need to open the new
5310 * pool and import it.
5312 if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
5313 nvlist_free(config);
5314 nvlist_free(props);
5315 return (1);
5317 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
5318 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
5319 ret = 1;
5320 (void) fprintf(stderr, gettext("Split was successful, but "
5321 "the datasets could not all be mounted\n"));
5322 (void) fprintf(stderr, gettext("Try doing '%s' with a "
5323 "different altroot\n"), "zpool import");
5325 zpool_close(zhp);
5326 nvlist_free(config);
5327 nvlist_free(props);
5329 return (ret);
5335 * zpool online <pool> <device> ...
5338 zpool_do_online(int argc, char **argv)
5340 int c, i;
5341 char *poolname;
5342 zpool_handle_t *zhp;
5343 int ret = 0;
5344 vdev_state_t newstate;
5345 int flags = 0;
5347 /* check options */
5348 while ((c = getopt(argc, argv, "et")) != -1) {
5349 switch (c) {
5350 case 'e':
5351 flags |= ZFS_ONLINE_EXPAND;
5352 break;
5353 case 't':
5354 case '?':
5355 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5356 optopt);
5357 usage(B_FALSE);
5361 argc -= optind;
5362 argv += optind;
5364 /* get pool name and check number of arguments */
5365 if (argc < 1) {
5366 (void) fprintf(stderr, gettext("missing pool name\n"));
5367 usage(B_FALSE);
5369 if (argc < 2) {
5370 (void) fprintf(stderr, gettext("missing device name\n"));
5371 usage(B_FALSE);
5374 poolname = argv[0];
5376 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5377 return (1);
5379 for (i = 1; i < argc; i++) {
5380 if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
5381 if (newstate != VDEV_STATE_HEALTHY) {
5382 (void) printf(gettext("warning: device '%s' "
5383 "onlined, but remains in faulted state\n"),
5384 argv[i]);
5385 if (newstate == VDEV_STATE_FAULTED)
5386 (void) printf(gettext("use 'zpool "
5387 "clear' to restore a faulted "
5388 "device\n"));
5389 else
5390 (void) printf(gettext("use 'zpool "
5391 "replace' to replace devices "
5392 "that are no longer present\n"));
5394 } else {
5395 ret = 1;
5399 zpool_close(zhp);
5401 return (ret);
5405 * zpool offline [-ft] <pool> <device> ...
5407 * -f Force the device into the offline state, even if doing
5408 * so would appear to compromise pool availability.
5409 * (not supported yet)
5411 * -t Only take the device off-line temporarily. The offline
5412 * state will not be persistent across reboots.
5414 /* ARGSUSED */
5416 zpool_do_offline(int argc, char **argv)
5418 int c, i;
5419 char *poolname;
5420 zpool_handle_t *zhp;
5421 int ret = 0;
5422 boolean_t istmp = B_FALSE;
5424 /* check options */
5425 while ((c = getopt(argc, argv, "ft")) != -1) {
5426 switch (c) {
5427 case 't':
5428 istmp = B_TRUE;
5429 break;
5430 case 'f':
5431 case '?':
5432 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5433 optopt);
5434 usage(B_FALSE);
5438 argc -= optind;
5439 argv += optind;
5441 /* get pool name and check number of arguments */
5442 if (argc < 1) {
5443 (void) fprintf(stderr, gettext("missing pool name\n"));
5444 usage(B_FALSE);
5446 if (argc < 2) {
5447 (void) fprintf(stderr, gettext("missing device name\n"));
5448 usage(B_FALSE);
5451 poolname = argv[0];
5453 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5454 return (1);
5456 for (i = 1; i < argc; i++) {
5457 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
5458 ret = 1;
5461 zpool_close(zhp);
5463 return (ret);
5467 * zpool clear <pool> [device]
5469 * Clear all errors associated with a pool or a particular device.
5472 zpool_do_clear(int argc, char **argv)
5474 int c;
5475 int ret = 0;
5476 boolean_t dryrun = B_FALSE;
5477 boolean_t do_rewind = B_FALSE;
5478 boolean_t xtreme_rewind = B_FALSE;
5479 uint32_t rewind_policy = ZPOOL_NO_REWIND;
5480 nvlist_t *policy = NULL;
5481 zpool_handle_t *zhp;
5482 char *pool, *device;
5484 /* check options */
5485 while ((c = getopt(argc, argv, "FnX")) != -1) {
5486 switch (c) {
5487 case 'F':
5488 do_rewind = B_TRUE;
5489 break;
5490 case 'n':
5491 dryrun = B_TRUE;
5492 break;
5493 case 'X':
5494 xtreme_rewind = B_TRUE;
5495 break;
5496 case '?':
5497 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5498 optopt);
5499 usage(B_FALSE);
5503 argc -= optind;
5504 argv += optind;
5506 if (argc < 1) {
5507 (void) fprintf(stderr, gettext("missing pool name\n"));
5508 usage(B_FALSE);
5511 if (argc > 2) {
5512 (void) fprintf(stderr, gettext("too many arguments\n"));
5513 usage(B_FALSE);
5516 if ((dryrun || xtreme_rewind) && !do_rewind) {
5517 (void) fprintf(stderr,
5518 gettext("-n or -X only meaningful with -F\n"));
5519 usage(B_FALSE);
5521 if (dryrun)
5522 rewind_policy = ZPOOL_TRY_REWIND;
5523 else if (do_rewind)
5524 rewind_policy = ZPOOL_DO_REWIND;
5525 if (xtreme_rewind)
5526 rewind_policy |= ZPOOL_EXTREME_REWIND;
5528 /* In future, further rewind policy choices can be passed along here */
5529 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
5530 nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
5531 return (1);
5533 pool = argv[0];
5534 device = argc == 2 ? argv[1] : NULL;
5536 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
5537 nvlist_free(policy);
5538 return (1);
5541 if (zpool_clear(zhp, device, policy) != 0)
5542 ret = 1;
5544 zpool_close(zhp);
5546 nvlist_free(policy);
5548 return (ret);
5552 * zpool reguid <pool>
5555 zpool_do_reguid(int argc, char **argv)
5557 int c;
5558 char *poolname;
5559 zpool_handle_t *zhp;
5560 int ret = 0;
5562 /* check options */
5563 while ((c = getopt(argc, argv, "")) != -1) {
5564 switch (c) {
5565 case '?':
5566 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5567 optopt);
5568 usage(B_FALSE);
5572 argc -= optind;
5573 argv += optind;
5575 /* get pool name and check number of arguments */
5576 if (argc < 1) {
5577 (void) fprintf(stderr, gettext("missing pool name\n"));
5578 usage(B_FALSE);
5581 if (argc > 1) {
5582 (void) fprintf(stderr, gettext("too many arguments\n"));
5583 usage(B_FALSE);
5586 poolname = argv[0];
5587 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5588 return (1);
5590 ret = zpool_reguid(zhp);
5592 zpool_close(zhp);
5593 return (ret);
5598 * zpool reopen <pool>
5600 * Reopen the pool so that the kernel can update the sizes of all vdevs.
5603 zpool_do_reopen(int argc, char **argv)
5605 int c;
5606 int ret = 0;
5607 zpool_handle_t *zhp;
5608 char *pool;
5610 /* check options */
5611 while ((c = getopt(argc, argv, "")) != -1) {
5612 switch (c) {
5613 case '?':
5614 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5615 optopt);
5616 usage(B_FALSE);
5620 argc--;
5621 argv++;
5623 if (argc < 1) {
5624 (void) fprintf(stderr, gettext("missing pool name\n"));
5625 usage(B_FALSE);
5628 if (argc > 1) {
5629 (void) fprintf(stderr, gettext("too many arguments\n"));
5630 usage(B_FALSE);
5633 pool = argv[0];
5634 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL)
5635 return (1);
5637 ret = zpool_reopen(zhp);
5638 zpool_close(zhp);
5639 return (ret);
5642 typedef struct scrub_cbdata {
5643 int cb_type;
5644 int cb_argc;
5645 char **cb_argv;
5646 } scrub_cbdata_t;
5649 scrub_callback(zpool_handle_t *zhp, void *data)
5651 scrub_cbdata_t *cb = data;
5652 int err;
5655 * Ignore faulted pools.
5657 if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
5658 (void) fprintf(stderr, gettext("cannot scrub '%s': pool is "
5659 "currently unavailable\n"), zpool_get_name(zhp));
5660 return (1);
5663 err = zpool_scan(zhp, cb->cb_type);
5665 return (err != 0);
5669 * zpool scrub [-s] <pool> ...
5671 * -s Stop. Stops any in-progress scrub.
5674 zpool_do_scrub(int argc, char **argv)
5676 int c;
5677 scrub_cbdata_t cb;
5679 cb.cb_type = POOL_SCAN_SCRUB;
5681 /* check options */
5682 while ((c = getopt(argc, argv, "s")) != -1) {
5683 switch (c) {
5684 case 's':
5685 cb.cb_type = POOL_SCAN_NONE;
5686 break;
5687 case '?':
5688 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5689 optopt);
5690 usage(B_FALSE);
5694 cb.cb_argc = argc;
5695 cb.cb_argv = argv;
5696 argc -= optind;
5697 argv += optind;
5699 if (argc < 1) {
5700 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5701 usage(B_FALSE);
5704 return (for_each_pool(argc, argv, B_TRUE, NULL, scrub_callback, &cb));
5708 * Print out detailed scrub status.
5710 void
5711 print_scan_status(pool_scan_stat_t *ps)
5713 time_t start, end;
5714 uint64_t elapsed, mins_left, hours_left;
5715 uint64_t pass_exam, examined, total;
5716 uint_t rate;
5717 double fraction_done;
5718 char processed_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
5720 (void) printf(gettext(" scan: "));
5722 /* If there's never been a scan, there's not much to say. */
5723 if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
5724 ps->pss_func >= POOL_SCAN_FUNCS) {
5725 (void) printf(gettext("none requested\n"));
5726 return;
5729 start = ps->pss_start_time;
5730 end = ps->pss_end_time;
5731 zfs_nicenum(ps->pss_processed, processed_buf, sizeof (processed_buf));
5733 assert(ps->pss_func == POOL_SCAN_SCRUB ||
5734 ps->pss_func == POOL_SCAN_RESILVER);
5736 * Scan is finished or canceled.
5738 if (ps->pss_state == DSS_FINISHED) {
5739 uint64_t minutes_taken = (end - start) / 60;
5740 char *fmt = NULL;
5742 if (ps->pss_func == POOL_SCAN_SCRUB) {
5743 fmt = gettext("scrub repaired %s in %lluh%um with "
5744 "%llu errors on %s");
5745 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5746 fmt = gettext("resilvered %s in %lluh%um with "
5747 "%llu errors on %s");
5749 /* LINTED */
5750 (void) printf(fmt, processed_buf,
5751 (u_longlong_t)(minutes_taken / 60),
5752 (uint_t)(minutes_taken % 60),
5753 (u_longlong_t)ps->pss_errors,
5754 ctime((time_t *)&end));
5755 return;
5756 } else if (ps->pss_state == DSS_CANCELED) {
5757 if (ps->pss_func == POOL_SCAN_SCRUB) {
5758 (void) printf(gettext("scrub canceled on %s"),
5759 ctime(&end));
5760 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5761 (void) printf(gettext("resilver canceled on %s"),
5762 ctime(&end));
5764 return;
5767 assert(ps->pss_state == DSS_SCANNING);
5770 * Scan is in progress.
5772 if (ps->pss_func == POOL_SCAN_SCRUB) {
5773 (void) printf(gettext("scrub in progress since %s"),
5774 ctime(&start));
5775 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5776 (void) printf(gettext("resilver in progress since %s"),
5777 ctime(&start));
5780 examined = ps->pss_examined ? ps->pss_examined : 1;
5781 total = ps->pss_to_examine;
5782 fraction_done = (double)examined / total;
5784 /* elapsed time for this pass */
5785 elapsed = time(NULL) - ps->pss_pass_start;
5786 elapsed = elapsed ? elapsed : 1;
5787 pass_exam = ps->pss_pass_exam ? ps->pss_pass_exam : 1;
5788 rate = pass_exam / elapsed;
5789 rate = rate ? rate : 1;
5790 mins_left = ((total - examined) / rate) / 60;
5791 hours_left = mins_left / 60;
5793 zfs_nicenum(examined, examined_buf, sizeof (examined_buf));
5794 zfs_nicenum(total, total_buf, sizeof (total_buf));
5795 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
5798 * do not print estimated time if hours_left is more than 30 days
5800 (void) printf(gettext("\t%s scanned out of %s at %s/s"),
5801 examined_buf, total_buf, rate_buf);
5802 if (hours_left < (30 * 24)) {
5803 (void) printf(gettext(", %lluh%um to go\n"),
5804 (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
5805 } else {
5806 (void) printf(gettext(
5807 ", (scan is slow, no estimated time)\n"));
5810 if (ps->pss_func == POOL_SCAN_RESILVER) {
5811 (void) printf(gettext("\t%s resilvered, %.2f%% done\n"),
5812 processed_buf, 100 * fraction_done);
5813 } else if (ps->pss_func == POOL_SCAN_SCRUB) {
5814 (void) printf(gettext("\t%s repaired, %.2f%% done\n"),
5815 processed_buf, 100 * fraction_done);
5819 static void
5820 print_error_log(zpool_handle_t *zhp)
5822 nvlist_t *nverrlist = NULL;
5823 nvpair_t *elem;
5824 char *pathname;
5825 size_t len = MAXPATHLEN * 2;
5827 if (zpool_get_errlog(zhp, &nverrlist) != 0)
5828 return;
5830 (void) printf("errors: Permanent errors have been "
5831 "detected in the following files:\n\n");
5833 pathname = safe_malloc(len);
5834 elem = NULL;
5835 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
5836 nvlist_t *nv;
5837 uint64_t dsobj, obj;
5839 verify(nvpair_value_nvlist(elem, &nv) == 0);
5840 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
5841 &dsobj) == 0);
5842 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
5843 &obj) == 0);
5844 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
5845 (void) printf("%7s %s\n", "", pathname);
5847 free(pathname);
5848 nvlist_free(nverrlist);
5851 static void
5852 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
5853 uint_t nspares)
5855 uint_t i;
5856 char *name;
5858 if (nspares == 0)
5859 return;
5861 (void) printf(gettext("\tspares\n"));
5863 for (i = 0; i < nspares; i++) {
5864 name = zpool_vdev_name(g_zfs, zhp, spares[i],
5865 cb->cb_name_flags);
5866 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE);
5867 free(name);
5871 static void
5872 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
5873 uint_t nl2cache)
5875 uint_t i;
5876 char *name;
5878 if (nl2cache == 0)
5879 return;
5881 (void) printf(gettext("\tcache\n"));
5883 for (i = 0; i < nl2cache; i++) {
5884 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
5885 cb->cb_name_flags);
5886 print_status_config(zhp, cb, name, l2cache[i], 2, B_FALSE);
5887 free(name);
5891 static void
5892 print_dedup_stats(nvlist_t *config)
5894 ddt_histogram_t *ddh;
5895 ddt_stat_t *dds;
5896 ddt_object_t *ddo;
5897 uint_t c;
5900 * If the pool was faulted then we may not have been able to
5901 * obtain the config. Otherwise, if we have anything in the dedup
5902 * table continue processing the stats.
5904 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
5905 (uint64_t **)&ddo, &c) != 0)
5906 return;
5908 (void) printf("\n");
5909 (void) printf(gettext(" dedup: "));
5910 if (ddo->ddo_count == 0) {
5911 (void) printf(gettext("no DDT entries\n"));
5912 return;
5915 (void) printf("DDT entries %llu, size %llu on disk, %llu in core\n",
5916 (u_longlong_t)ddo->ddo_count,
5917 (u_longlong_t)ddo->ddo_dspace,
5918 (u_longlong_t)ddo->ddo_mspace);
5920 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
5921 (uint64_t **)&dds, &c) == 0);
5922 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
5923 (uint64_t **)&ddh, &c) == 0);
5924 zpool_dump_ddt(dds, ddh);
5928 * Display a summary of pool status. Displays a summary such as:
5930 * pool: tank
5931 * status: DEGRADED
5932 * reason: One or more devices ...
5933 * see: http://zfsonlinux.org/msg/ZFS-xxxx-01
5934 * config:
5935 * mirror DEGRADED
5936 * c1t0d0 OK
5937 * c2t0d0 UNAVAIL
5939 * When given the '-v' option, we print out the complete config. If the '-e'
5940 * option is specified, then we print out error rate information as well.
5943 status_callback(zpool_handle_t *zhp, void *data)
5945 status_cbdata_t *cbp = data;
5946 nvlist_t *config, *nvroot;
5947 char *msgid;
5948 zpool_status_t reason;
5949 zpool_errata_t errata;
5950 const char *health;
5951 uint_t c;
5952 vdev_stat_t *vs;
5954 config = zpool_get_config(zhp, NULL);
5955 reason = zpool_get_status(zhp, &msgid, &errata);
5957 cbp->cb_count++;
5960 * If we were given 'zpool status -x', only report those pools with
5961 * problems.
5963 if (cbp->cb_explain &&
5964 (reason == ZPOOL_STATUS_OK ||
5965 reason == ZPOOL_STATUS_VERSION_OLDER ||
5966 reason == ZPOOL_STATUS_FEAT_DISABLED)) {
5967 if (!cbp->cb_allpools) {
5968 (void) printf(gettext("pool '%s' is healthy\n"),
5969 zpool_get_name(zhp));
5970 if (cbp->cb_first)
5971 cbp->cb_first = B_FALSE;
5973 return (0);
5976 if (cbp->cb_first)
5977 cbp->cb_first = B_FALSE;
5978 else
5979 (void) printf("\n");
5981 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5982 &nvroot) == 0);
5983 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
5984 (uint64_t **)&vs, &c) == 0);
5985 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
5987 (void) printf(gettext(" pool: %s\n"), zpool_get_name(zhp));
5988 (void) printf(gettext(" state: %s\n"), health);
5990 switch (reason) {
5991 case ZPOOL_STATUS_MISSING_DEV_R:
5992 (void) printf(gettext("status: One or more devices could not "
5993 "be opened. Sufficient replicas exist for\n\tthe pool to "
5994 "continue functioning in a degraded state.\n"));
5995 (void) printf(gettext("action: Attach the missing device and "
5996 "online it using 'zpool online'.\n"));
5997 break;
5999 case ZPOOL_STATUS_MISSING_DEV_NR:
6000 (void) printf(gettext("status: One or more devices could not "
6001 "be opened. There are insufficient\n\treplicas for the "
6002 "pool to continue functioning.\n"));
6003 (void) printf(gettext("action: Attach the missing device and "
6004 "online it using 'zpool online'.\n"));
6005 break;
6007 case ZPOOL_STATUS_CORRUPT_LABEL_R:
6008 (void) printf(gettext("status: One or more devices could not "
6009 "be used because the label is missing or\n\tinvalid. "
6010 "Sufficient replicas exist for the pool to continue\n\t"
6011 "functioning in a degraded state.\n"));
6012 (void) printf(gettext("action: Replace the device using "
6013 "'zpool replace'.\n"));
6014 break;
6016 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
6017 (void) printf(gettext("status: One or more devices could not "
6018 "be used because the label is missing \n\tor invalid. "
6019 "There are insufficient replicas for the pool to "
6020 "continue\n\tfunctioning.\n"));
6021 zpool_explain_recover(zpool_get_handle(zhp),
6022 zpool_get_name(zhp), reason, config);
6023 break;
6025 case ZPOOL_STATUS_FAILING_DEV:
6026 (void) printf(gettext("status: One or more devices has "
6027 "experienced an unrecoverable error. An\n\tattempt was "
6028 "made to correct the error. Applications are "
6029 "unaffected.\n"));
6030 (void) printf(gettext("action: Determine if the device needs "
6031 "to be replaced, and clear the errors\n\tusing "
6032 "'zpool clear' or replace the device with 'zpool "
6033 "replace'.\n"));
6034 break;
6036 case ZPOOL_STATUS_OFFLINE_DEV:
6037 (void) printf(gettext("status: One or more devices has "
6038 "been taken offline by the administrator.\n\tSufficient "
6039 "replicas exist for the pool to continue functioning in "
6040 "a\n\tdegraded state.\n"));
6041 (void) printf(gettext("action: Online the device using "
6042 "'zpool online' or replace the device with\n\t'zpool "
6043 "replace'.\n"));
6044 break;
6046 case ZPOOL_STATUS_REMOVED_DEV:
6047 (void) printf(gettext("status: One or more devices has "
6048 "been removed by the administrator.\n\tSufficient "
6049 "replicas exist for the pool to continue functioning in "
6050 "a\n\tdegraded state.\n"));
6051 (void) printf(gettext("action: Online the device using "
6052 "'zpool online' or replace the device with\n\t'zpool "
6053 "replace'.\n"));
6054 break;
6056 case ZPOOL_STATUS_RESILVERING:
6057 (void) printf(gettext("status: One or more devices is "
6058 "currently being resilvered. The pool will\n\tcontinue "
6059 "to function, possibly in a degraded state.\n"));
6060 (void) printf(gettext("action: Wait for the resilver to "
6061 "complete.\n"));
6062 break;
6064 case ZPOOL_STATUS_CORRUPT_DATA:
6065 (void) printf(gettext("status: One or more devices has "
6066 "experienced an error resulting in data\n\tcorruption. "
6067 "Applications may be affected.\n"));
6068 (void) printf(gettext("action: Restore the file in question "
6069 "if possible. Otherwise restore the\n\tentire pool from "
6070 "backup.\n"));
6071 break;
6073 case ZPOOL_STATUS_CORRUPT_POOL:
6074 (void) printf(gettext("status: The pool metadata is corrupted "
6075 "and the pool cannot be opened.\n"));
6076 zpool_explain_recover(zpool_get_handle(zhp),
6077 zpool_get_name(zhp), reason, config);
6078 break;
6080 case ZPOOL_STATUS_VERSION_OLDER:
6081 (void) printf(gettext("status: The pool is formatted using a "
6082 "legacy on-disk format. The pool can\n\tstill be used, "
6083 "but some features are unavailable.\n"));
6084 (void) printf(gettext("action: Upgrade the pool using 'zpool "
6085 "upgrade'. Once this is done, the\n\tpool will no longer "
6086 "be accessible on software that does not support\n\t"
6087 "feature flags.\n"));
6088 break;
6090 case ZPOOL_STATUS_VERSION_NEWER:
6091 (void) printf(gettext("status: The pool has been upgraded to a "
6092 "newer, incompatible on-disk version.\n\tThe pool cannot "
6093 "be accessed on this system.\n"));
6094 (void) printf(gettext("action: Access the pool from a system "
6095 "running more recent software, or\n\trestore the pool from "
6096 "backup.\n"));
6097 break;
6099 case ZPOOL_STATUS_FEAT_DISABLED:
6100 (void) printf(gettext("status: Some supported features are not "
6101 "enabled on the pool. The pool can\n\tstill be used, but "
6102 "some features are unavailable.\n"));
6103 (void) printf(gettext("action: Enable all features using "
6104 "'zpool upgrade'. Once this is done,\n\tthe pool may no "
6105 "longer be accessible by software that does not support\n\t"
6106 "the features. See zpool-features(5) for details.\n"));
6107 break;
6109 case ZPOOL_STATUS_UNSUP_FEAT_READ:
6110 (void) printf(gettext("status: The pool cannot be accessed on "
6111 "this system because it uses the\n\tfollowing feature(s) "
6112 "not supported on this system:\n"));
6113 zpool_print_unsup_feat(config);
6114 (void) printf("\n");
6115 (void) printf(gettext("action: Access the pool from a system "
6116 "that supports the required feature(s),\n\tor restore the "
6117 "pool from backup.\n"));
6118 break;
6120 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
6121 (void) printf(gettext("status: The pool can only be accessed "
6122 "in read-only mode on this system. It\n\tcannot be "
6123 "accessed in read-write mode because it uses the "
6124 "following\n\tfeature(s) not supported on this system:\n"));
6125 zpool_print_unsup_feat(config);
6126 (void) printf("\n");
6127 (void) printf(gettext("action: The pool cannot be accessed in "
6128 "read-write mode. Import the pool with\n"
6129 "\t\"-o readonly=on\", access the pool from a system that "
6130 "supports the\n\trequired feature(s), or restore the "
6131 "pool from backup.\n"));
6132 break;
6134 case ZPOOL_STATUS_FAULTED_DEV_R:
6135 (void) printf(gettext("status: One or more devices are "
6136 "faulted in response to persistent errors.\n\tSufficient "
6137 "replicas exist for the pool to continue functioning "
6138 "in a\n\tdegraded state.\n"));
6139 (void) printf(gettext("action: Replace the faulted device, "
6140 "or use 'zpool clear' to mark the device\n\trepaired.\n"));
6141 break;
6143 case ZPOOL_STATUS_FAULTED_DEV_NR:
6144 (void) printf(gettext("status: One or more devices are "
6145 "faulted in response to persistent errors. There are "
6146 "insufficient replicas for the pool to\n\tcontinue "
6147 "functioning.\n"));
6148 (void) printf(gettext("action: Destroy and re-create the pool "
6149 "from a backup source. Manually marking the device\n"
6150 "\trepaired using 'zpool clear' may allow some data "
6151 "to be recovered.\n"));
6152 break;
6154 case ZPOOL_STATUS_IO_FAILURE_WAIT:
6155 case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
6156 (void) printf(gettext("status: One or more devices are "
6157 "faulted in response to IO failures.\n"));
6158 (void) printf(gettext("action: Make sure the affected devices "
6159 "are connected, then run 'zpool clear'.\n"));
6160 break;
6162 case ZPOOL_STATUS_BAD_LOG:
6163 (void) printf(gettext("status: An intent log record "
6164 "could not be read.\n"
6165 "\tWaiting for administrator intervention to fix the "
6166 "faulted pool.\n"));
6167 (void) printf(gettext("action: Either restore the affected "
6168 "device(s) and run 'zpool online',\n"
6169 "\tor ignore the intent log records by running "
6170 "'zpool clear'.\n"));
6171 break;
6173 case ZPOOL_STATUS_HOSTID_MISMATCH:
6174 (void) printf(gettext("status: Mismatch between pool hostid "
6175 "and system hostid on imported pool.\n\tThis pool was "
6176 "previously imported into a system with a different "
6177 "hostid,\n\tand then was verbatim imported into this "
6178 "system.\n"));
6179 (void) printf(gettext("action: Export this pool on all systems "
6180 "on which it is imported.\n"
6181 "\tThen import it to correct the mismatch.\n"));
6182 break;
6184 case ZPOOL_STATUS_ERRATA:
6185 (void) printf(gettext("status: Errata #%d detected.\n"),
6186 errata);
6188 switch (errata) {
6189 case ZPOOL_ERRATA_NONE:
6190 break;
6192 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
6193 (void) printf(gettext("action: To correct the issue "
6194 "run 'zpool scrub'.\n"));
6195 break;
6197 default:
6199 * All errata which allow the pool to be imported
6200 * must contain an action message.
6202 assert(0);
6204 break;
6206 default:
6208 * The remaining errors can't actually be generated, yet.
6210 assert(reason == ZPOOL_STATUS_OK);
6213 if (msgid != NULL)
6214 (void) printf(gettext(" see: http://zfsonlinux.org/msg/%s\n"),
6215 msgid);
6217 if (config != NULL) {
6218 uint64_t nerr;
6219 nvlist_t **spares, **l2cache;
6220 uint_t nspares, nl2cache;
6221 pool_scan_stat_t *ps = NULL;
6223 (void) nvlist_lookup_uint64_array(nvroot,
6224 ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &c);
6225 print_scan_status(ps);
6227 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
6228 cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
6229 if (cbp->cb_namewidth < 10)
6230 cbp->cb_namewidth = 10;
6232 (void) printf(gettext("config:\n\n"));
6233 (void) printf(gettext("\t%-*s %-8s %5s %5s %5s"),
6234 cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
6235 "CKSUM");
6237 if (cbp->vcdl != NULL)
6238 print_cmd_columns(cbp->vcdl, 0);
6240 printf("\n");
6241 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
6242 B_FALSE);
6244 if (num_logs(nvroot) > 0)
6245 print_logs(zhp, cbp, nvroot);
6246 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
6247 &l2cache, &nl2cache) == 0)
6248 print_l2cache(zhp, cbp, l2cache, nl2cache);
6250 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
6251 &spares, &nspares) == 0)
6252 print_spares(zhp, cbp, spares, nspares);
6254 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
6255 &nerr) == 0) {
6256 nvlist_t *nverrlist = NULL;
6259 * If the approximate error count is small, get a
6260 * precise count by fetching the entire log and
6261 * uniquifying the results.
6263 if (nerr > 0 && nerr < 100 && !cbp->cb_verbose &&
6264 zpool_get_errlog(zhp, &nverrlist) == 0) {
6265 nvpair_t *elem;
6267 elem = NULL;
6268 nerr = 0;
6269 while ((elem = nvlist_next_nvpair(nverrlist,
6270 elem)) != NULL) {
6271 nerr++;
6274 nvlist_free(nverrlist);
6276 (void) printf("\n");
6278 if (nerr == 0)
6279 (void) printf(gettext("errors: No known data "
6280 "errors\n"));
6281 else if (!cbp->cb_verbose)
6282 (void) printf(gettext("errors: %llu data "
6283 "errors, use '-v' for a list\n"),
6284 (u_longlong_t)nerr);
6285 else
6286 print_error_log(zhp);
6289 if (cbp->cb_dedup_stats)
6290 print_dedup_stats(config);
6291 } else {
6292 (void) printf(gettext("config: The configuration cannot be "
6293 "determined.\n"));
6296 return (0);
6300 * zpool status [-c [script1,script2,...]] [-gLPvx] [-T d|u] [pool] ...
6301 * [interval [count]]
6303 * -c CMD For each vdev, run command CMD
6304 * -g Display guid for individual vdev name.
6305 * -L Follow links when resolving vdev path name.
6306 * -P Display full path for vdev name.
6307 * -v Display complete error logs
6308 * -x Display only pools with potential problems
6309 * -D Display dedup status (undocumented)
6310 * -T Display a timestamp in date(1) or Unix format
6312 * Describes the health status of all pools or some subset.
6315 zpool_do_status(int argc, char **argv)
6317 int c;
6318 int ret;
6319 float interval = 0;
6320 unsigned long count = 0;
6321 status_cbdata_t cb = { 0 };
6322 char *cmd = NULL;
6324 /* check options */
6325 while ((c = getopt(argc, argv, "c:gLPvxDT:")) != -1) {
6326 switch (c) {
6327 case 'c':
6328 if (cmd != NULL) {
6329 fprintf(stderr,
6330 gettext("Can't set -c flag twice\n"));
6331 exit(1);
6333 if ((getuid() <= 0 || geteuid() <= 0) &&
6334 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
6335 fprintf(stderr, gettext(
6336 "Can't run -c with root privileges "
6337 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
6338 exit(1);
6340 cmd = optarg;
6341 break;
6342 case 'g':
6343 cb.cb_name_flags |= VDEV_NAME_GUID;
6344 break;
6345 case 'L':
6346 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6347 break;
6348 case 'P':
6349 cb.cb_name_flags |= VDEV_NAME_PATH;
6350 break;
6351 case 'v':
6352 cb.cb_verbose = B_TRUE;
6353 break;
6354 case 'x':
6355 cb.cb_explain = B_TRUE;
6356 break;
6357 case 'D':
6358 cb.cb_dedup_stats = B_TRUE;
6359 break;
6360 case 'T':
6361 get_timestamp_arg(*optarg);
6362 break;
6363 case '?':
6364 if (optopt == 'c') {
6365 fprintf(stderr, gettext(
6366 "Current scripts in %s:\n"),
6367 ZPOOL_SCRIPTS_DIR);
6368 print_zpool_script_list();
6369 exit(0);
6370 } else {
6371 fprintf(stderr,
6372 gettext("invalid option '%c'\n"), optopt);
6374 usage(B_FALSE);
6378 argc -= optind;
6379 argv += optind;
6381 get_interval_count(&argc, argv, &interval, &count);
6383 if (argc == 0)
6384 cb.cb_allpools = B_TRUE;
6386 cb.cb_first = B_TRUE;
6387 cb.cb_print_status = B_TRUE;
6389 for (;;) {
6390 if (timestamp_fmt != NODATE)
6391 print_timestamp(timestamp_fmt);
6393 if (cmd != NULL)
6394 cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
6395 NULL, NULL, 0, 0);
6397 ret = for_each_pool(argc, argv, B_TRUE, NULL,
6398 status_callback, &cb);
6400 if (cb.vcdl != NULL)
6401 free_vdev_cmd_data_list(cb.vcdl);
6403 if (argc == 0 && cb.cb_count == 0)
6404 (void) fprintf(stderr, gettext("no pools available\n"));
6405 else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
6406 (void) printf(gettext("all pools are healthy\n"));
6408 if (ret != 0)
6409 return (ret);
6411 if (interval == 0)
6412 break;
6414 if (count != 0 && --count == 0)
6415 break;
6417 (void) fsleep(interval);
6420 return (0);
6423 typedef struct upgrade_cbdata {
6424 int cb_first;
6425 int cb_argc;
6426 uint64_t cb_version;
6427 char **cb_argv;
6428 } upgrade_cbdata_t;
6430 static int
6431 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
6433 int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
6434 int *count = (int *)unsupp_fs;
6436 if (zfs_version > ZPL_VERSION) {
6437 (void) printf(gettext("%s (v%d) is not supported by this "
6438 "implementation of ZFS.\n"),
6439 zfs_get_name(zhp), zfs_version);
6440 (*count)++;
6443 zfs_iter_filesystems(zhp, check_unsupp_fs, unsupp_fs);
6445 zfs_close(zhp);
6447 return (0);
6450 static int
6451 upgrade_version(zpool_handle_t *zhp, uint64_t version)
6453 int ret;
6454 nvlist_t *config;
6455 uint64_t oldversion;
6456 int unsupp_fs = 0;
6458 config = zpool_get_config(zhp, NULL);
6459 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6460 &oldversion) == 0);
6462 assert(SPA_VERSION_IS_SUPPORTED(oldversion));
6463 assert(oldversion < version);
6465 ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
6466 if (ret != 0)
6467 return (ret);
6469 if (unsupp_fs) {
6470 (void) fprintf(stderr, gettext("Upgrade not performed due "
6471 "to %d unsupported filesystems (max v%d).\n"),
6472 unsupp_fs, (int)ZPL_VERSION);
6473 return (1);
6476 ret = zpool_upgrade(zhp, version);
6477 if (ret != 0)
6478 return (ret);
6480 if (version >= SPA_VERSION_FEATURES) {
6481 (void) printf(gettext("Successfully upgraded "
6482 "'%s' from version %llu to feature flags.\n"),
6483 zpool_get_name(zhp), (u_longlong_t)oldversion);
6484 } else {
6485 (void) printf(gettext("Successfully upgraded "
6486 "'%s' from version %llu to version %llu.\n"),
6487 zpool_get_name(zhp), (u_longlong_t)oldversion,
6488 (u_longlong_t)version);
6491 return (0);
6494 static int
6495 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
6497 int i, ret, count;
6498 boolean_t firstff = B_TRUE;
6499 nvlist_t *enabled = zpool_get_features(zhp);
6501 count = 0;
6502 for (i = 0; i < SPA_FEATURES; i++) {
6503 const char *fname = spa_feature_table[i].fi_uname;
6504 const char *fguid = spa_feature_table[i].fi_guid;
6505 if (!nvlist_exists(enabled, fguid)) {
6506 char *propname;
6507 verify(-1 != asprintf(&propname, "feature@%s", fname));
6508 ret = zpool_set_prop(zhp, propname,
6509 ZFS_FEATURE_ENABLED);
6510 if (ret != 0) {
6511 free(propname);
6512 return (ret);
6514 count++;
6516 if (firstff) {
6517 (void) printf(gettext("Enabled the "
6518 "following features on '%s':\n"),
6519 zpool_get_name(zhp));
6520 firstff = B_FALSE;
6522 (void) printf(gettext(" %s\n"), fname);
6523 free(propname);
6527 if (countp != NULL)
6528 *countp = count;
6529 return (0);
6532 static int
6533 upgrade_cb(zpool_handle_t *zhp, void *arg)
6535 upgrade_cbdata_t *cbp = arg;
6536 nvlist_t *config;
6537 uint64_t version;
6538 boolean_t printnl = B_FALSE;
6539 int ret;
6541 config = zpool_get_config(zhp, NULL);
6542 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6543 &version) == 0);
6545 assert(SPA_VERSION_IS_SUPPORTED(version));
6547 if (version < cbp->cb_version) {
6548 cbp->cb_first = B_FALSE;
6549 ret = upgrade_version(zhp, cbp->cb_version);
6550 if (ret != 0)
6551 return (ret);
6552 printnl = B_TRUE;
6555 * If they did "zpool upgrade -a", then we could
6556 * be doing ioctls to different pools. We need
6557 * to log this history once to each pool, and bypass
6558 * the normal history logging that happens in main().
6560 (void) zpool_log_history(g_zfs, history_str);
6561 log_history = B_FALSE;
6564 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
6565 int count;
6566 ret = upgrade_enable_all(zhp, &count);
6567 if (ret != 0)
6568 return (ret);
6570 if (count > 0) {
6571 cbp->cb_first = B_FALSE;
6572 printnl = B_TRUE;
6576 if (printnl) {
6577 (void) printf(gettext("\n"));
6580 return (0);
6583 static int
6584 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
6586 upgrade_cbdata_t *cbp = arg;
6587 nvlist_t *config;
6588 uint64_t version;
6590 config = zpool_get_config(zhp, NULL);
6591 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6592 &version) == 0);
6594 assert(SPA_VERSION_IS_SUPPORTED(version));
6596 if (version < SPA_VERSION_FEATURES) {
6597 if (cbp->cb_first) {
6598 (void) printf(gettext("The following pools are "
6599 "formatted with legacy version numbers and can\n"
6600 "be upgraded to use feature flags. After "
6601 "being upgraded, these pools\nwill no "
6602 "longer be accessible by software that does not "
6603 "support feature\nflags.\n\n"));
6604 (void) printf(gettext("VER POOL\n"));
6605 (void) printf(gettext("--- ------------\n"));
6606 cbp->cb_first = B_FALSE;
6609 (void) printf("%2llu %s\n", (u_longlong_t)version,
6610 zpool_get_name(zhp));
6613 return (0);
6616 static int
6617 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
6619 upgrade_cbdata_t *cbp = arg;
6620 nvlist_t *config;
6621 uint64_t version;
6623 config = zpool_get_config(zhp, NULL);
6624 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6625 &version) == 0);
6627 if (version >= SPA_VERSION_FEATURES) {
6628 int i;
6629 boolean_t poolfirst = B_TRUE;
6630 nvlist_t *enabled = zpool_get_features(zhp);
6632 for (i = 0; i < SPA_FEATURES; i++) {
6633 const char *fguid = spa_feature_table[i].fi_guid;
6634 const char *fname = spa_feature_table[i].fi_uname;
6635 if (!nvlist_exists(enabled, fguid)) {
6636 if (cbp->cb_first) {
6637 (void) printf(gettext("\nSome "
6638 "supported features are not "
6639 "enabled on the following pools. "
6640 "Once a\nfeature is enabled the "
6641 "pool may become incompatible with "
6642 "software\nthat does not support "
6643 "the feature. See "
6644 "zpool-features(5) for "
6645 "details.\n\n"));
6646 (void) printf(gettext("POOL "
6647 "FEATURE\n"));
6648 (void) printf(gettext("------"
6649 "---------\n"));
6650 cbp->cb_first = B_FALSE;
6653 if (poolfirst) {
6654 (void) printf(gettext("%s\n"),
6655 zpool_get_name(zhp));
6656 poolfirst = B_FALSE;
6659 (void) printf(gettext(" %s\n"), fname);
6662 * If they did "zpool upgrade -a", then we could
6663 * be doing ioctls to different pools. We need
6664 * to log this history once to each pool, and bypass
6665 * the normal history logging that happens in main().
6667 (void) zpool_log_history(g_zfs, history_str);
6668 log_history = B_FALSE;
6672 return (0);
6675 /* ARGSUSED */
6676 static int
6677 upgrade_one(zpool_handle_t *zhp, void *data)
6679 boolean_t printnl = B_FALSE;
6680 upgrade_cbdata_t *cbp = data;
6681 uint64_t cur_version;
6682 int ret;
6684 if (strcmp("log", zpool_get_name(zhp)) == 0) {
6685 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
6686 "Pool 'log' must be renamed using export and import"
6687 " to upgrade.\n"));
6688 return (1);
6691 cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
6692 if (cur_version > cbp->cb_version) {
6693 (void) printf(gettext("Pool '%s' is already formatted "
6694 "using more current version '%llu'.\n\n"),
6695 zpool_get_name(zhp), (u_longlong_t)cur_version);
6696 return (0);
6699 if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
6700 (void) printf(gettext("Pool '%s' is already formatted "
6701 "using version %llu.\n\n"), zpool_get_name(zhp),
6702 (u_longlong_t)cbp->cb_version);
6703 return (0);
6706 if (cur_version != cbp->cb_version) {
6707 printnl = B_TRUE;
6708 ret = upgrade_version(zhp, cbp->cb_version);
6709 if (ret != 0)
6710 return (ret);
6713 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
6714 int count = 0;
6715 ret = upgrade_enable_all(zhp, &count);
6716 if (ret != 0)
6717 return (ret);
6719 if (count != 0) {
6720 printnl = B_TRUE;
6721 } else if (cur_version == SPA_VERSION) {
6722 (void) printf(gettext("Pool '%s' already has all "
6723 "supported features enabled.\n"),
6724 zpool_get_name(zhp));
6728 if (printnl) {
6729 (void) printf(gettext("\n"));
6732 return (0);
6736 * zpool upgrade
6737 * zpool upgrade -v
6738 * zpool upgrade [-V version] <-a | pool ...>
6740 * With no arguments, display downrev'd ZFS pool available for upgrade.
6741 * Individual pools can be upgraded by specifying the pool, and '-a' will
6742 * upgrade all pools.
6745 zpool_do_upgrade(int argc, char **argv)
6747 int c;
6748 upgrade_cbdata_t cb = { 0 };
6749 int ret = 0;
6750 boolean_t showversions = B_FALSE;
6751 boolean_t upgradeall = B_FALSE;
6752 char *end;
6755 /* check options */
6756 while ((c = getopt(argc, argv, ":avV:")) != -1) {
6757 switch (c) {
6758 case 'a':
6759 upgradeall = B_TRUE;
6760 break;
6761 case 'v':
6762 showversions = B_TRUE;
6763 break;
6764 case 'V':
6765 cb.cb_version = strtoll(optarg, &end, 10);
6766 if (*end != '\0' ||
6767 !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
6768 (void) fprintf(stderr,
6769 gettext("invalid version '%s'\n"), optarg);
6770 usage(B_FALSE);
6772 break;
6773 case ':':
6774 (void) fprintf(stderr, gettext("missing argument for "
6775 "'%c' option\n"), optopt);
6776 usage(B_FALSE);
6777 break;
6778 case '?':
6779 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6780 optopt);
6781 usage(B_FALSE);
6785 cb.cb_argc = argc;
6786 cb.cb_argv = argv;
6787 argc -= optind;
6788 argv += optind;
6790 if (cb.cb_version == 0) {
6791 cb.cb_version = SPA_VERSION;
6792 } else if (!upgradeall && argc == 0) {
6793 (void) fprintf(stderr, gettext("-V option is "
6794 "incompatible with other arguments\n"));
6795 usage(B_FALSE);
6798 if (showversions) {
6799 if (upgradeall || argc != 0) {
6800 (void) fprintf(stderr, gettext("-v option is "
6801 "incompatible with other arguments\n"));
6802 usage(B_FALSE);
6804 } else if (upgradeall) {
6805 if (argc != 0) {
6806 (void) fprintf(stderr, gettext("-a option should not "
6807 "be used along with a pool name\n"));
6808 usage(B_FALSE);
6812 (void) printf(gettext("This system supports ZFS pool feature "
6813 "flags.\n\n"));
6814 if (showversions) {
6815 int i;
6817 (void) printf(gettext("The following features are "
6818 "supported:\n\n"));
6819 (void) printf(gettext("FEAT DESCRIPTION\n"));
6820 (void) printf("----------------------------------------------"
6821 "---------------\n");
6822 for (i = 0; i < SPA_FEATURES; i++) {
6823 zfeature_info_t *fi = &spa_feature_table[i];
6824 const char *ro =
6825 (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
6826 " (read-only compatible)" : "";
6828 (void) printf("%-37s%s\n", fi->fi_uname, ro);
6829 (void) printf(" %s\n", fi->fi_desc);
6831 (void) printf("\n");
6833 (void) printf(gettext("The following legacy versions are also "
6834 "supported:\n\n"));
6835 (void) printf(gettext("VER DESCRIPTION\n"));
6836 (void) printf("--- -----------------------------------------"
6837 "---------------\n");
6838 (void) printf(gettext(" 1 Initial ZFS version\n"));
6839 (void) printf(gettext(" 2 Ditto blocks "
6840 "(replicated metadata)\n"));
6841 (void) printf(gettext(" 3 Hot spares and double parity "
6842 "RAID-Z\n"));
6843 (void) printf(gettext(" 4 zpool history\n"));
6844 (void) printf(gettext(" 5 Compression using the gzip "
6845 "algorithm\n"));
6846 (void) printf(gettext(" 6 bootfs pool property\n"));
6847 (void) printf(gettext(" 7 Separate intent log devices\n"));
6848 (void) printf(gettext(" 8 Delegated administration\n"));
6849 (void) printf(gettext(" 9 refquota and refreservation "
6850 "properties\n"));
6851 (void) printf(gettext(" 10 Cache devices\n"));
6852 (void) printf(gettext(" 11 Improved scrub performance\n"));
6853 (void) printf(gettext(" 12 Snapshot properties\n"));
6854 (void) printf(gettext(" 13 snapused property\n"));
6855 (void) printf(gettext(" 14 passthrough-x aclinherit\n"));
6856 (void) printf(gettext(" 15 user/group space accounting\n"));
6857 (void) printf(gettext(" 16 stmf property support\n"));
6858 (void) printf(gettext(" 17 Triple-parity RAID-Z\n"));
6859 (void) printf(gettext(" 18 Snapshot user holds\n"));
6860 (void) printf(gettext(" 19 Log device removal\n"));
6861 (void) printf(gettext(" 20 Compression using zle "
6862 "(zero-length encoding)\n"));
6863 (void) printf(gettext(" 21 Deduplication\n"));
6864 (void) printf(gettext(" 22 Received properties\n"));
6865 (void) printf(gettext(" 23 Slim ZIL\n"));
6866 (void) printf(gettext(" 24 System attributes\n"));
6867 (void) printf(gettext(" 25 Improved scrub stats\n"));
6868 (void) printf(gettext(" 26 Improved snapshot deletion "
6869 "performance\n"));
6870 (void) printf(gettext(" 27 Improved snapshot creation "
6871 "performance\n"));
6872 (void) printf(gettext(" 28 Multiple vdev replacements\n"));
6873 (void) printf(gettext("\nFor more information on a particular "
6874 "version, including supported releases,\n"));
6875 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
6876 } else if (argc == 0 && upgradeall) {
6877 cb.cb_first = B_TRUE;
6878 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
6879 if (ret == 0 && cb.cb_first) {
6880 if (cb.cb_version == SPA_VERSION) {
6881 (void) printf(gettext("All pools are already "
6882 "formatted using feature flags.\n\n"));
6883 (void) printf(gettext("Every feature flags "
6884 "pool already has all supported features "
6885 "enabled.\n"));
6886 } else {
6887 (void) printf(gettext("All pools are already "
6888 "formatted with version %llu or higher.\n"),
6889 (u_longlong_t)cb.cb_version);
6892 } else if (argc == 0) {
6893 cb.cb_first = B_TRUE;
6894 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
6895 assert(ret == 0);
6897 if (cb.cb_first) {
6898 (void) printf(gettext("All pools are formatted "
6899 "using feature flags.\n\n"));
6900 } else {
6901 (void) printf(gettext("\nUse 'zpool upgrade -v' "
6902 "for a list of available legacy versions.\n"));
6905 cb.cb_first = B_TRUE;
6906 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
6907 assert(ret == 0);
6909 if (cb.cb_first) {
6910 (void) printf(gettext("Every feature flags pool has "
6911 "all supported features enabled.\n"));
6912 } else {
6913 (void) printf(gettext("\n"));
6915 } else {
6916 ret = for_each_pool(argc, argv, B_FALSE, NULL,
6917 upgrade_one, &cb);
6920 return (ret);
6923 typedef struct hist_cbdata {
6924 boolean_t first;
6925 boolean_t longfmt;
6926 boolean_t internal;
6927 } hist_cbdata_t;
6930 * Print out the command history for a specific pool.
6932 static int
6933 get_history_one(zpool_handle_t *zhp, void *data)
6935 nvlist_t *nvhis;
6936 nvlist_t **records;
6937 uint_t numrecords;
6938 int ret, i;
6939 hist_cbdata_t *cb = (hist_cbdata_t *)data;
6941 cb->first = B_FALSE;
6943 (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
6945 if ((ret = zpool_get_history(zhp, &nvhis)) != 0)
6946 return (ret);
6948 verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
6949 &records, &numrecords) == 0);
6950 for (i = 0; i < numrecords; i++) {
6951 nvlist_t *rec = records[i];
6952 char tbuf[30] = "";
6954 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
6955 time_t tsec;
6956 struct tm t;
6958 tsec = fnvlist_lookup_uint64(records[i],
6959 ZPOOL_HIST_TIME);
6960 (void) localtime_r(&tsec, &t);
6961 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
6964 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
6965 (void) printf("%s %s", tbuf,
6966 fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
6967 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
6968 int ievent =
6969 fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
6970 if (!cb->internal)
6971 continue;
6972 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
6973 (void) printf("%s unrecognized record:\n",
6974 tbuf);
6975 dump_nvlist(rec, 4);
6976 continue;
6978 (void) printf("%s [internal %s txg:%lld] %s", tbuf,
6979 zfs_history_event_names[ievent],
6980 (longlong_t)fnvlist_lookup_uint64(
6981 rec, ZPOOL_HIST_TXG),
6982 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
6983 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
6984 if (!cb->internal)
6985 continue;
6986 (void) printf("%s [txg:%lld] %s", tbuf,
6987 (longlong_t)fnvlist_lookup_uint64(
6988 rec, ZPOOL_HIST_TXG),
6989 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
6990 if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
6991 (void) printf(" %s (%llu)",
6992 fnvlist_lookup_string(rec,
6993 ZPOOL_HIST_DSNAME),
6994 (u_longlong_t)fnvlist_lookup_uint64(rec,
6995 ZPOOL_HIST_DSID));
6997 (void) printf(" %s", fnvlist_lookup_string(rec,
6998 ZPOOL_HIST_INT_STR));
6999 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
7000 if (!cb->internal)
7001 continue;
7002 (void) printf("%s ioctl %s\n", tbuf,
7003 fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
7004 if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
7005 (void) printf(" input:\n");
7006 dump_nvlist(fnvlist_lookup_nvlist(rec,
7007 ZPOOL_HIST_INPUT_NVL), 8);
7009 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
7010 (void) printf(" output:\n");
7011 dump_nvlist(fnvlist_lookup_nvlist(rec,
7012 ZPOOL_HIST_OUTPUT_NVL), 8);
7014 } else {
7015 if (!cb->internal)
7016 continue;
7017 (void) printf("%s unrecognized record:\n", tbuf);
7018 dump_nvlist(rec, 4);
7021 if (!cb->longfmt) {
7022 (void) printf("\n");
7023 continue;
7025 (void) printf(" [");
7026 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
7027 uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
7028 struct passwd *pwd = getpwuid(who);
7029 (void) printf("user %d ", (int)who);
7030 if (pwd != NULL)
7031 (void) printf("(%s) ", pwd->pw_name);
7033 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
7034 (void) printf("on %s",
7035 fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
7037 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
7038 (void) printf(":%s",
7039 fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
7042 (void) printf("]");
7043 (void) printf("\n");
7045 (void) printf("\n");
7046 nvlist_free(nvhis);
7048 return (ret);
7052 * zpool history <pool>
7054 * Displays the history of commands that modified pools.
7057 zpool_do_history(int argc, char **argv)
7059 hist_cbdata_t cbdata = { 0 };
7060 int ret;
7061 int c;
7063 cbdata.first = B_TRUE;
7064 /* check options */
7065 while ((c = getopt(argc, argv, "li")) != -1) {
7066 switch (c) {
7067 case 'l':
7068 cbdata.longfmt = B_TRUE;
7069 break;
7070 case 'i':
7071 cbdata.internal = B_TRUE;
7072 break;
7073 case '?':
7074 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7075 optopt);
7076 usage(B_FALSE);
7079 argc -= optind;
7080 argv += optind;
7082 ret = for_each_pool(argc, argv, B_FALSE, NULL, get_history_one,
7083 &cbdata);
7085 if (argc == 0 && cbdata.first == B_TRUE) {
7086 (void) fprintf(stderr, gettext("no pools available\n"));
7087 return (0);
7090 return (ret);
7093 typedef struct ev_opts {
7094 int verbose;
7095 int scripted;
7096 int follow;
7097 int clear;
7098 } ev_opts_t;
7100 static void
7101 zpool_do_events_short(nvlist_t *nvl)
7103 char ctime_str[26], str[32], *ptr;
7104 int64_t *tv;
7105 uint_t n;
7107 verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
7108 memset(str, ' ', 32);
7109 (void) ctime_r((const time_t *)&tv[0], ctime_str);
7110 (void) strncpy(str, ctime_str+4, 6); /* 'Jun 30' */
7111 (void) strncpy(str+7, ctime_str+20, 4); /* '1993' */
7112 (void) strncpy(str+12, ctime_str+11, 8); /* '21:49:08' */
7113 (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
7114 (void) printf(gettext("%s "), str);
7116 verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
7117 (void) printf(gettext("%s\n"), ptr);
7120 static void
7121 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
7123 nvpair_t *nvp;
7125 for (nvp = nvlist_next_nvpair(nvl, NULL);
7126 nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
7128 data_type_t type = nvpair_type(nvp);
7129 const char *name = nvpair_name(nvp);
7131 boolean_t b;
7132 uint8_t i8;
7133 uint16_t i16;
7134 uint32_t i32;
7135 uint64_t i64;
7136 char *str;
7137 nvlist_t *cnv;
7139 printf(gettext("%*s%s = "), depth, "", name);
7141 switch (type) {
7142 case DATA_TYPE_BOOLEAN:
7143 printf(gettext("%s"), "1");
7144 break;
7146 case DATA_TYPE_BOOLEAN_VALUE:
7147 (void) nvpair_value_boolean_value(nvp, &b);
7148 printf(gettext("%s"), b ? "1" : "0");
7149 break;
7151 case DATA_TYPE_BYTE:
7152 (void) nvpair_value_byte(nvp, &i8);
7153 printf(gettext("0x%x"), i8);
7154 break;
7156 case DATA_TYPE_INT8:
7157 (void) nvpair_value_int8(nvp, (void *)&i8);
7158 printf(gettext("0x%x"), i8);
7159 break;
7161 case DATA_TYPE_UINT8:
7162 (void) nvpair_value_uint8(nvp, &i8);
7163 printf(gettext("0x%x"), i8);
7164 break;
7166 case DATA_TYPE_INT16:
7167 (void) nvpair_value_int16(nvp, (void *)&i16);
7168 printf(gettext("0x%x"), i16);
7169 break;
7171 case DATA_TYPE_UINT16:
7172 (void) nvpair_value_uint16(nvp, &i16);
7173 printf(gettext("0x%x"), i16);
7174 break;
7176 case DATA_TYPE_INT32:
7177 (void) nvpair_value_int32(nvp, (void *)&i32);
7178 printf(gettext("0x%x"), i32);
7179 break;
7181 case DATA_TYPE_UINT32:
7182 (void) nvpair_value_uint32(nvp, &i32);
7183 printf(gettext("0x%x"), i32);
7184 break;
7186 case DATA_TYPE_INT64:
7187 (void) nvpair_value_int64(nvp, (void *)&i64);
7188 printf(gettext("0x%llx"), (u_longlong_t)i64);
7189 break;
7191 case DATA_TYPE_UINT64:
7192 (void) nvpair_value_uint64(nvp, &i64);
7194 * translate vdev state values to readable
7195 * strings to aide zpool events consumers
7197 if (strcmp(name,
7198 FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
7199 strcmp(name,
7200 FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
7201 printf(gettext("\"%s\" (0x%llx)"),
7202 zpool_state_to_name(i64, VDEV_AUX_NONE),
7203 (u_longlong_t)i64);
7204 } else {
7205 printf(gettext("0x%llx"), (u_longlong_t)i64);
7207 break;
7209 case DATA_TYPE_HRTIME:
7210 (void) nvpair_value_hrtime(nvp, (void *)&i64);
7211 printf(gettext("0x%llx"), (u_longlong_t)i64);
7212 break;
7214 case DATA_TYPE_STRING:
7215 (void) nvpair_value_string(nvp, &str);
7216 printf(gettext("\"%s\""), str ? str : "<NULL>");
7217 break;
7219 case DATA_TYPE_NVLIST:
7220 printf(gettext("(embedded nvlist)\n"));
7221 (void) nvpair_value_nvlist(nvp, &cnv);
7222 zpool_do_events_nvprint(cnv, depth + 8);
7223 printf(gettext("%*s(end %s)"), depth, "", name);
7224 break;
7226 case DATA_TYPE_NVLIST_ARRAY: {
7227 nvlist_t **val;
7228 uint_t i, nelem;
7230 (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
7231 printf(gettext("(%d embedded nvlists)\n"), nelem);
7232 for (i = 0; i < nelem; i++) {
7233 printf(gettext("%*s%s[%d] = %s\n"),
7234 depth, "", name, i, "(embedded nvlist)");
7235 zpool_do_events_nvprint(val[i], depth + 8);
7236 printf(gettext("%*s(end %s[%i])\n"),
7237 depth, "", name, i);
7239 printf(gettext("%*s(end %s)\n"), depth, "", name);
7241 break;
7243 case DATA_TYPE_INT8_ARRAY: {
7244 int8_t *val;
7245 uint_t i, nelem;
7247 (void) nvpair_value_int8_array(nvp, &val, &nelem);
7248 for (i = 0; i < nelem; i++)
7249 printf(gettext("0x%x "), val[i]);
7251 break;
7254 case DATA_TYPE_UINT8_ARRAY: {
7255 uint8_t *val;
7256 uint_t i, nelem;
7258 (void) nvpair_value_uint8_array(nvp, &val, &nelem);
7259 for (i = 0; i < nelem; i++)
7260 printf(gettext("0x%x "), val[i]);
7262 break;
7265 case DATA_TYPE_INT16_ARRAY: {
7266 int16_t *val;
7267 uint_t i, nelem;
7269 (void) nvpair_value_int16_array(nvp, &val, &nelem);
7270 for (i = 0; i < nelem; i++)
7271 printf(gettext("0x%x "), val[i]);
7273 break;
7276 case DATA_TYPE_UINT16_ARRAY: {
7277 uint16_t *val;
7278 uint_t i, nelem;
7280 (void) nvpair_value_uint16_array(nvp, &val, &nelem);
7281 for (i = 0; i < nelem; i++)
7282 printf(gettext("0x%x "), val[i]);
7284 break;
7287 case DATA_TYPE_INT32_ARRAY: {
7288 int32_t *val;
7289 uint_t i, nelem;
7291 (void) nvpair_value_int32_array(nvp, &val, &nelem);
7292 for (i = 0; i < nelem; i++)
7293 printf(gettext("0x%x "), val[i]);
7295 break;
7298 case DATA_TYPE_UINT32_ARRAY: {
7299 uint32_t *val;
7300 uint_t i, nelem;
7302 (void) nvpair_value_uint32_array(nvp, &val, &nelem);
7303 for (i = 0; i < nelem; i++)
7304 printf(gettext("0x%x "), val[i]);
7306 break;
7309 case DATA_TYPE_INT64_ARRAY: {
7310 int64_t *val;
7311 uint_t i, nelem;
7313 (void) nvpair_value_int64_array(nvp, &val, &nelem);
7314 for (i = 0; i < nelem; i++)
7315 printf(gettext("0x%llx "),
7316 (u_longlong_t)val[i]);
7318 break;
7321 case DATA_TYPE_UINT64_ARRAY: {
7322 uint64_t *val;
7323 uint_t i, nelem;
7325 (void) nvpair_value_uint64_array(nvp, &val, &nelem);
7326 for (i = 0; i < nelem; i++)
7327 printf(gettext("0x%llx "),
7328 (u_longlong_t)val[i]);
7330 break;
7333 case DATA_TYPE_STRING_ARRAY: {
7334 char **str;
7335 uint_t i, nelem;
7337 (void) nvpair_value_string_array(nvp, &str, &nelem);
7338 for (i = 0; i < nelem; i++)
7339 printf(gettext("\"%s\" "),
7340 str[i] ? str[i] : "<NULL>");
7342 break;
7345 case DATA_TYPE_BOOLEAN_ARRAY:
7346 case DATA_TYPE_BYTE_ARRAY:
7347 case DATA_TYPE_DOUBLE:
7348 case DATA_TYPE_UNKNOWN:
7349 printf(gettext("<unknown>"));
7350 break;
7353 printf(gettext("\n"));
7357 static int
7358 zpool_do_events_next(ev_opts_t *opts)
7360 nvlist_t *nvl;
7361 int zevent_fd, ret, dropped;
7363 zevent_fd = open(ZFS_DEV, O_RDWR);
7364 VERIFY(zevent_fd >= 0);
7366 if (!opts->scripted)
7367 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
7369 while (1) {
7370 ret = zpool_events_next(g_zfs, &nvl, &dropped,
7371 (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
7372 if (ret || nvl == NULL)
7373 break;
7375 if (dropped > 0)
7376 (void) printf(gettext("dropped %d events\n"), dropped);
7378 zpool_do_events_short(nvl);
7380 if (opts->verbose) {
7381 zpool_do_events_nvprint(nvl, 8);
7382 printf(gettext("\n"));
7384 (void) fflush(stdout);
7386 nvlist_free(nvl);
7389 VERIFY(0 == close(zevent_fd));
7391 return (ret);
7394 static int
7395 zpool_do_events_clear(ev_opts_t *opts)
7397 int count, ret;
7399 ret = zpool_events_clear(g_zfs, &count);
7400 if (!ret)
7401 (void) printf(gettext("cleared %d events\n"), count);
7403 return (ret);
7407 * zpool events [-vfc]
7409 * Displays events logs by ZFS.
7412 zpool_do_events(int argc, char **argv)
7414 ev_opts_t opts = { 0 };
7415 int ret;
7416 int c;
7418 /* check options */
7419 while ((c = getopt(argc, argv, "vHfc")) != -1) {
7420 switch (c) {
7421 case 'v':
7422 opts.verbose = 1;
7423 break;
7424 case 'H':
7425 opts.scripted = 1;
7426 break;
7427 case 'f':
7428 opts.follow = 1;
7429 break;
7430 case 'c':
7431 opts.clear = 1;
7432 break;
7433 case '?':
7434 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7435 optopt);
7436 usage(B_FALSE);
7439 argc -= optind;
7440 argv += optind;
7442 if (opts.clear)
7443 ret = zpool_do_events_clear(&opts);
7444 else
7445 ret = zpool_do_events_next(&opts);
7447 return (ret);
7450 static int
7451 get_callback(zpool_handle_t *zhp, void *data)
7453 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
7454 char value[MAXNAMELEN];
7455 zprop_source_t srctype;
7456 zprop_list_t *pl;
7458 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
7461 * Skip the special fake placeholder. This will also skip
7462 * over the name property when 'all' is specified.
7464 if (pl->pl_prop == ZPOOL_PROP_NAME &&
7465 pl == cbp->cb_proplist)
7466 continue;
7468 if (pl->pl_prop == ZPROP_INVAL &&
7469 (zpool_prop_feature(pl->pl_user_prop) ||
7470 zpool_prop_unsupported(pl->pl_user_prop))) {
7471 srctype = ZPROP_SRC_LOCAL;
7473 if (zpool_prop_get_feature(zhp, pl->pl_user_prop,
7474 value, sizeof (value)) == 0) {
7475 zprop_print_one_property(zpool_get_name(zhp),
7476 cbp, pl->pl_user_prop, value, srctype,
7477 NULL, NULL);
7479 } else {
7480 if (zpool_get_prop(zhp, pl->pl_prop, value,
7481 sizeof (value), &srctype, cbp->cb_literal) != 0)
7482 continue;
7484 zprop_print_one_property(zpool_get_name(zhp), cbp,
7485 zpool_prop_to_name(pl->pl_prop), value, srctype,
7486 NULL, NULL);
7489 return (0);
7493 * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
7495 * -H Scripted mode. Don't display headers, and separate properties
7496 * by a single tab.
7497 * -o List of columns to display. Defaults to
7498 * "name,property,value,source".
7499 * -p Display values in parsable (exact) format.
7501 * Get properties of pools in the system. Output space statistics
7502 * for each one as well as other attributes.
7505 zpool_do_get(int argc, char **argv)
7507 zprop_get_cbdata_t cb = { 0 };
7508 zprop_list_t fake_name = { 0 };
7509 int ret;
7510 int c, i;
7511 char *value;
7513 cb.cb_first = B_TRUE;
7516 * Set up default columns and sources.
7518 cb.cb_sources = ZPROP_SRC_ALL;
7519 cb.cb_columns[0] = GET_COL_NAME;
7520 cb.cb_columns[1] = GET_COL_PROPERTY;
7521 cb.cb_columns[2] = GET_COL_VALUE;
7522 cb.cb_columns[3] = GET_COL_SOURCE;
7523 cb.cb_type = ZFS_TYPE_POOL;
7525 /* check options */
7526 while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
7527 switch (c) {
7528 case 'p':
7529 cb.cb_literal = B_TRUE;
7530 break;
7531 case 'H':
7532 cb.cb_scripted = B_TRUE;
7533 break;
7534 case 'o':
7535 bzero(&cb.cb_columns, sizeof (cb.cb_columns));
7536 i = 0;
7537 while (*optarg != '\0') {
7538 static char *col_subopts[] =
7539 { "name", "property", "value", "source",
7540 "all", NULL };
7542 if (i == ZFS_GET_NCOLS) {
7543 (void) fprintf(stderr, gettext("too "
7544 "many fields given to -o "
7545 "option\n"));
7546 usage(B_FALSE);
7549 switch (getsubopt(&optarg, col_subopts,
7550 &value)) {
7551 case 0:
7552 cb.cb_columns[i++] = GET_COL_NAME;
7553 break;
7554 case 1:
7555 cb.cb_columns[i++] = GET_COL_PROPERTY;
7556 break;
7557 case 2:
7558 cb.cb_columns[i++] = GET_COL_VALUE;
7559 break;
7560 case 3:
7561 cb.cb_columns[i++] = GET_COL_SOURCE;
7562 break;
7563 case 4:
7564 if (i > 0) {
7565 (void) fprintf(stderr,
7566 gettext("\"all\" conflicts "
7567 "with specific fields "
7568 "given to -o option\n"));
7569 usage(B_FALSE);
7571 cb.cb_columns[0] = GET_COL_NAME;
7572 cb.cb_columns[1] = GET_COL_PROPERTY;
7573 cb.cb_columns[2] = GET_COL_VALUE;
7574 cb.cb_columns[3] = GET_COL_SOURCE;
7575 i = ZFS_GET_NCOLS;
7576 break;
7577 default:
7578 (void) fprintf(stderr,
7579 gettext("invalid column name "
7580 "'%s'\n"), value);
7581 usage(B_FALSE);
7584 break;
7585 case '?':
7586 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7587 optopt);
7588 usage(B_FALSE);
7592 argc -= optind;
7593 argv += optind;
7595 if (argc < 1) {
7596 (void) fprintf(stderr, gettext("missing property "
7597 "argument\n"));
7598 usage(B_FALSE);
7601 if (zprop_get_list(g_zfs, argv[0], &cb.cb_proplist,
7602 ZFS_TYPE_POOL) != 0)
7603 usage(B_FALSE);
7605 argc--;
7606 argv++;
7608 if (cb.cb_proplist != NULL) {
7609 fake_name.pl_prop = ZPOOL_PROP_NAME;
7610 fake_name.pl_width = strlen(gettext("NAME"));
7611 fake_name.pl_next = cb.cb_proplist;
7612 cb.cb_proplist = &fake_name;
7615 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist,
7616 get_callback, &cb);
7618 if (cb.cb_proplist == &fake_name)
7619 zprop_free_list(fake_name.pl_next);
7620 else
7621 zprop_free_list(cb.cb_proplist);
7623 return (ret);
7626 typedef struct set_cbdata {
7627 char *cb_propname;
7628 char *cb_value;
7629 boolean_t cb_any_successful;
7630 } set_cbdata_t;
7633 set_callback(zpool_handle_t *zhp, void *data)
7635 int error;
7636 set_cbdata_t *cb = (set_cbdata_t *)data;
7638 error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
7640 if (!error)
7641 cb->cb_any_successful = B_TRUE;
7643 return (error);
7647 zpool_do_set(int argc, char **argv)
7649 set_cbdata_t cb = { 0 };
7650 int error;
7652 if (argc > 1 && argv[1][0] == '-') {
7653 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7654 argv[1][1]);
7655 usage(B_FALSE);
7658 if (argc < 2) {
7659 (void) fprintf(stderr, gettext("missing property=value "
7660 "argument\n"));
7661 usage(B_FALSE);
7664 if (argc < 3) {
7665 (void) fprintf(stderr, gettext("missing pool name\n"));
7666 usage(B_FALSE);
7669 if (argc > 3) {
7670 (void) fprintf(stderr, gettext("too many pool names\n"));
7671 usage(B_FALSE);
7674 cb.cb_propname = argv[1];
7675 cb.cb_value = strchr(cb.cb_propname, '=');
7676 if (cb.cb_value == NULL) {
7677 (void) fprintf(stderr, gettext("missing value in "
7678 "property=value argument\n"));
7679 usage(B_FALSE);
7682 *(cb.cb_value) = '\0';
7683 cb.cb_value++;
7685 error = for_each_pool(argc - 2, argv + 2, B_TRUE, NULL,
7686 set_callback, &cb);
7688 return (error);
7691 static int
7692 find_command_idx(char *command, int *idx)
7694 int i;
7696 for (i = 0; i < NCOMMAND; i++) {
7697 if (command_table[i].name == NULL)
7698 continue;
7700 if (strcmp(command, command_table[i].name) == 0) {
7701 *idx = i;
7702 return (0);
7705 return (1);
7709 main(int argc, char **argv)
7711 int ret = 0;
7712 int i = 0;
7713 char *cmdname;
7715 (void) setlocale(LC_ALL, "");
7716 (void) textdomain(TEXT_DOMAIN);
7717 srand(time(NULL));
7719 dprintf_setup(&argc, argv);
7721 opterr = 0;
7724 * Make sure the user has specified some command.
7726 if (argc < 2) {
7727 (void) fprintf(stderr, gettext("missing command\n"));
7728 usage(B_FALSE);
7731 cmdname = argv[1];
7734 * Special case '-?'
7736 if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
7737 usage(B_TRUE);
7739 if ((g_zfs = libzfs_init()) == NULL) {
7740 (void) fprintf(stderr, "%s", libzfs_error_init(errno));
7741 return (1);
7744 libzfs_print_on_error(g_zfs, B_TRUE);
7746 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
7749 * Run the appropriate command.
7751 if (find_command_idx(cmdname, &i) == 0) {
7752 current_command = &command_table[i];
7753 ret = command_table[i].func(argc - 1, argv + 1);
7754 } else if (strchr(cmdname, '=')) {
7755 verify(find_command_idx("set", &i) == 0);
7756 current_command = &command_table[i];
7757 ret = command_table[i].func(argc, argv);
7758 } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
7760 * 'freeze' is a vile debugging abomination, so we treat
7761 * it as such.
7763 char buf[16384];
7764 int fd = open(ZFS_DEV, O_RDWR);
7765 (void) strlcpy((void *)buf, argv[2], sizeof (buf));
7766 return (!!ioctl(fd, ZFS_IOC_POOL_FREEZE, buf));
7767 } else {
7768 (void) fprintf(stderr, gettext("unrecognized "
7769 "command '%s'\n"), cmdname);
7770 usage(B_FALSE);
7771 ret = 1;
7774 if (ret == 0 && log_history)
7775 (void) zpool_log_history(g_zfs, history_str);
7777 libzfs_fini(g_zfs);
7780 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
7781 * for the purposes of running ::findleaks.
7783 if (getenv("ZFS_ABORT") != NULL) {
7784 (void) printf("dumping core by request\n");
7785 abort();
7788 return (ret);