Implemented zpool sync command
[zfs.git] / cmd / zpool / zpool_main.c
blobf99145da9632f46bdc7361da4f9ebf59dedf5463
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>.
30 * Copyright (c) 2017 Datto Inc.
33 #include <assert.h>
34 #include <ctype.h>
35 #include <dirent.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <libgen.h>
39 #include <libintl.h>
40 #include <libuutil.h>
41 #include <locale.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <strings.h>
46 #include <unistd.h>
47 #include <pwd.h>
48 #include <zone.h>
49 #include <sys/wait.h>
50 #include <zfs_prop.h>
51 #include <sys/fs/zfs.h>
52 #include <sys/stat.h>
53 #include <sys/fm/fs/zfs.h>
54 #include <sys/fm/util.h>
55 #include <sys/fm/protocol.h>
56 #include <sys/zfs_ioctl.h>
58 #include <math.h>
60 #include <libzfs.h>
62 #include "zpool_util.h"
63 #include "zfs_comutil.h"
64 #include "zfeature_common.h"
66 #include "statcommon.h"
68 static int zpool_do_create(int, char **);
69 static int zpool_do_destroy(int, char **);
71 static int zpool_do_add(int, char **);
72 static int zpool_do_remove(int, char **);
73 static int zpool_do_labelclear(int, char **);
75 static int zpool_do_list(int, char **);
76 static int zpool_do_iostat(int, char **);
77 static int zpool_do_status(int, char **);
79 static int zpool_do_online(int, char **);
80 static int zpool_do_offline(int, char **);
81 static int zpool_do_clear(int, char **);
82 static int zpool_do_reopen(int, char **);
84 static int zpool_do_reguid(int, char **);
86 static int zpool_do_attach(int, char **);
87 static int zpool_do_detach(int, char **);
88 static int zpool_do_replace(int, char **);
89 static int zpool_do_split(int, char **);
91 static int zpool_do_scrub(int, char **);
93 static int zpool_do_import(int, char **);
94 static int zpool_do_export(int, char **);
96 static int zpool_do_upgrade(int, char **);
98 static int zpool_do_history(int, char **);
99 static int zpool_do_events(int, char **);
101 static int zpool_do_get(int, char **);
102 static int zpool_do_set(int, char **);
104 static int zpool_do_sync(int, char **);
107 * These libumem hooks provide a reasonable set of defaults for the allocator's
108 * debugging facilities.
111 #ifdef DEBUG
112 const char *
113 _umem_debug_init(void)
115 return ("default,verbose"); /* $UMEM_DEBUG setting */
118 const char *
119 _umem_logging_init(void)
121 return ("fail,contents"); /* $UMEM_LOGGING setting */
123 #endif
125 typedef enum {
126 HELP_ADD,
127 HELP_ATTACH,
128 HELP_CLEAR,
129 HELP_CREATE,
130 HELP_DESTROY,
131 HELP_DETACH,
132 HELP_EXPORT,
133 HELP_HISTORY,
134 HELP_IMPORT,
135 HELP_IOSTAT,
136 HELP_LABELCLEAR,
137 HELP_LIST,
138 HELP_OFFLINE,
139 HELP_ONLINE,
140 HELP_REPLACE,
141 HELP_REMOVE,
142 HELP_SCRUB,
143 HELP_STATUS,
144 HELP_UPGRADE,
145 HELP_EVENTS,
146 HELP_GET,
147 HELP_SET,
148 HELP_SPLIT,
149 HELP_SYNC,
150 HELP_REGUID,
151 HELP_REOPEN
152 } zpool_help_t;
156 * Flags for stats to display with "zpool iostats"
158 enum iostat_type {
159 IOS_DEFAULT = 0,
160 IOS_LATENCY = 1,
161 IOS_QUEUES = 2,
162 IOS_L_HISTO = 3,
163 IOS_RQ_HISTO = 4,
164 IOS_COUNT, /* always last element */
167 /* iostat_type entries as bitmasks */
168 #define IOS_DEFAULT_M (1ULL << IOS_DEFAULT)
169 #define IOS_LATENCY_M (1ULL << IOS_LATENCY)
170 #define IOS_QUEUES_M (1ULL << IOS_QUEUES)
171 #define IOS_L_HISTO_M (1ULL << IOS_L_HISTO)
172 #define IOS_RQ_HISTO_M (1ULL << IOS_RQ_HISTO)
174 /* Mask of all the histo bits */
175 #define IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
178 * Lookup table for iostat flags to nvlist names. Basically a list
179 * of all the nvlists a flag requires. Also specifies the order in
180 * which data gets printed in zpool iostat.
182 static const char *vsx_type_to_nvlist[IOS_COUNT][11] = {
183 [IOS_L_HISTO] = {
184 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
185 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
186 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
187 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
188 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
189 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
190 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
191 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
192 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
193 NULL},
194 [IOS_LATENCY] = {
195 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
196 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
197 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
198 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
199 NULL},
200 [IOS_QUEUES] = {
201 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
202 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
203 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
204 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
205 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
206 NULL},
207 [IOS_RQ_HISTO] = {
208 ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
209 ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
210 ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
211 ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
212 ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
213 ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
214 ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
215 ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
216 ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
217 ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
218 NULL},
223 * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
224 * Right now, only one histo bit is ever set at one time, so we can
225 * just do a highbit64(a)
227 #define IOS_HISTO_IDX(a) (highbit64(a & IOS_ANYHISTO_M) - 1)
229 typedef struct zpool_command {
230 const char *name;
231 int (*func)(int, char **);
232 zpool_help_t usage;
233 } zpool_command_t;
236 * Master command table. Each ZFS command has a name, associated function, and
237 * usage message. The usage messages need to be internationalized, so we have
238 * to have a function to return the usage message based on a command index.
240 * These commands are organized according to how they are displayed in the usage
241 * message. An empty command (one with a NULL name) indicates an empty line in
242 * the generic usage message.
244 static zpool_command_t command_table[] = {
245 { "create", zpool_do_create, HELP_CREATE },
246 { "destroy", zpool_do_destroy, HELP_DESTROY },
247 { NULL },
248 { "add", zpool_do_add, HELP_ADD },
249 { "remove", zpool_do_remove, HELP_REMOVE },
250 { NULL },
251 { "labelclear", zpool_do_labelclear, HELP_LABELCLEAR },
252 { NULL },
253 { "list", zpool_do_list, HELP_LIST },
254 { "iostat", zpool_do_iostat, HELP_IOSTAT },
255 { "status", zpool_do_status, HELP_STATUS },
256 { NULL },
257 { "online", zpool_do_online, HELP_ONLINE },
258 { "offline", zpool_do_offline, HELP_OFFLINE },
259 { "clear", zpool_do_clear, HELP_CLEAR },
260 { "reopen", zpool_do_reopen, HELP_REOPEN },
261 { NULL },
262 { "attach", zpool_do_attach, HELP_ATTACH },
263 { "detach", zpool_do_detach, HELP_DETACH },
264 { "replace", zpool_do_replace, HELP_REPLACE },
265 { "split", zpool_do_split, HELP_SPLIT },
266 { NULL },
267 { "scrub", zpool_do_scrub, HELP_SCRUB },
268 { NULL },
269 { "import", zpool_do_import, HELP_IMPORT },
270 { "export", zpool_do_export, HELP_EXPORT },
271 { "upgrade", zpool_do_upgrade, HELP_UPGRADE },
272 { "reguid", zpool_do_reguid, HELP_REGUID },
273 { NULL },
274 { "history", zpool_do_history, HELP_HISTORY },
275 { "events", zpool_do_events, HELP_EVENTS },
276 { NULL },
277 { "get", zpool_do_get, HELP_GET },
278 { "set", zpool_do_set, HELP_SET },
279 { "sync", zpool_do_sync, HELP_SYNC },
282 #define NCOMMAND (ARRAY_SIZE(command_table))
284 static zpool_command_t *current_command;
285 static char history_str[HIS_MAX_RECORD_LEN];
286 static boolean_t log_history = B_TRUE;
287 static uint_t timestamp_fmt = NODATE;
289 static const char *
290 get_usage(zpool_help_t idx)
292 switch (idx) {
293 case HELP_ADD:
294 return (gettext("\tadd [-fgLnP] [-o property=value] "
295 "<pool> <vdev> ...\n"));
296 case HELP_ATTACH:
297 return (gettext("\tattach [-f] [-o property=value] "
298 "<pool> <device> <new-device>\n"));
299 case HELP_CLEAR:
300 return (gettext("\tclear [-nF] <pool> [device]\n"));
301 case HELP_CREATE:
302 return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
303 "\t [-O file-system-property=value] ... \n"
304 "\t [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
305 case HELP_DESTROY:
306 return (gettext("\tdestroy [-f] <pool>\n"));
307 case HELP_DETACH:
308 return (gettext("\tdetach <pool> <device>\n"));
309 case HELP_EXPORT:
310 return (gettext("\texport [-af] <pool> ...\n"));
311 case HELP_HISTORY:
312 return (gettext("\thistory [-il] [<pool>] ...\n"));
313 case HELP_IMPORT:
314 return (gettext("\timport [-d dir] [-D]\n"
315 "\timport [-d dir | -c cachefile] [-F [-n]] <pool | id>\n"
316 "\timport [-o mntopts] [-o property=value] ... \n"
317 "\t [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
318 "[-R root] [-F [-n]] -a\n"
319 "\timport [-o mntopts] [-o property=value] ... \n"
320 "\t [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
321 "[-R root] [-F [-n]]\n"
322 "\t <pool | id> [newpool]\n"));
323 case HELP_IOSTAT:
324 return (gettext("\tiostat [[[-c [script1,script2,...]"
325 "[-lq]]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
326 "\t [[pool ...]|[pool vdev ...]|[vdev ...]]"
327 " [interval [count]]\n"));
328 case HELP_LABELCLEAR:
329 return (gettext("\tlabelclear [-f] <vdev>\n"));
330 case HELP_LIST:
331 return (gettext("\tlist [-gHLpPv] [-o property[,...]] "
332 "[-T d|u] [pool] ... [interval [count]]\n"));
333 case HELP_OFFLINE:
334 return (gettext("\toffline [-f] [-t] <pool> <device> ...\n"));
335 case HELP_ONLINE:
336 return (gettext("\tonline <pool> <device> ...\n"));
337 case HELP_REPLACE:
338 return (gettext("\treplace [-f] [-o property=value] "
339 "<pool> <device> [new-device]\n"));
340 case HELP_REMOVE:
341 return (gettext("\tremove <pool> <device> ...\n"));
342 case HELP_REOPEN:
343 return (gettext("\treopen <pool>\n"));
344 case HELP_SCRUB:
345 return (gettext("\tscrub [-s] <pool> ...\n"));
346 case HELP_STATUS:
347 return (gettext("\tstatus [-c [script1,script2,...]] [-gLPvxD]"
348 "[-T d|u] [pool] ... [interval [count]]\n"));
349 case HELP_UPGRADE:
350 return (gettext("\tupgrade\n"
351 "\tupgrade -v\n"
352 "\tupgrade [-V version] <-a | pool ...>\n"));
353 case HELP_EVENTS:
354 return (gettext("\tevents [-vHfc]\n"));
355 case HELP_GET:
356 return (gettext("\tget [-Hp] [-o \"all\" | field[,...]] "
357 "<\"all\" | property[,...]> <pool> ...\n"));
358 case HELP_SET:
359 return (gettext("\tset <property=value> <pool> \n"));
360 case HELP_SPLIT:
361 return (gettext("\tsplit [-gLnP] [-R altroot] [-o mntopts]\n"
362 "\t [-o property=value] <pool> <newpool> "
363 "[<device> ...]\n"));
364 case HELP_REGUID:
365 return (gettext("\treguid <pool>\n"));
366 case HELP_SYNC:
367 return (gettext("\tsync [pool] ...\n"));
370 abort();
371 /* NOTREACHED */
376 * Callback routine that will print out a pool property value.
378 static int
379 print_prop_cb(int prop, void *cb)
381 FILE *fp = cb;
383 (void) fprintf(fp, "\t%-15s ", zpool_prop_to_name(prop));
385 if (zpool_prop_readonly(prop))
386 (void) fprintf(fp, " NO ");
387 else
388 (void) fprintf(fp, " YES ");
390 if (zpool_prop_values(prop) == NULL)
391 (void) fprintf(fp, "-\n");
392 else
393 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
395 return (ZPROP_CONT);
399 * Display usage message. If we're inside a command, display only the usage for
400 * that command. Otherwise, iterate over the entire command table and display
401 * a complete usage message.
403 void
404 usage(boolean_t requested)
406 FILE *fp = requested ? stdout : stderr;
408 if (current_command == NULL) {
409 int i;
411 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
412 (void) fprintf(fp,
413 gettext("where 'command' is one of the following:\n\n"));
415 for (i = 0; i < NCOMMAND; i++) {
416 if (command_table[i].name == NULL)
417 (void) fprintf(fp, "\n");
418 else
419 (void) fprintf(fp, "%s",
420 get_usage(command_table[i].usage));
422 } else {
423 (void) fprintf(fp, gettext("usage:\n"));
424 (void) fprintf(fp, "%s", get_usage(current_command->usage));
427 if (current_command != NULL &&
428 ((strcmp(current_command->name, "set") == 0) ||
429 (strcmp(current_command->name, "get") == 0) ||
430 (strcmp(current_command->name, "list") == 0))) {
432 (void) fprintf(fp,
433 gettext("\nthe following properties are supported:\n"));
435 (void) fprintf(fp, "\n\t%-15s %s %s\n\n",
436 "PROPERTY", "EDIT", "VALUES");
438 /* Iterate over all properties */
439 (void) zprop_iter(print_prop_cb, fp, B_FALSE, B_TRUE,
440 ZFS_TYPE_POOL);
442 (void) fprintf(fp, "\t%-15s ", "feature@...");
443 (void) fprintf(fp, "YES disabled | enabled | active\n");
445 (void) fprintf(fp, gettext("\nThe feature@ properties must be "
446 "appended with a feature name.\nSee zpool-features(5).\n"));
450 * See comments at end of main().
452 if (getenv("ZFS_ABORT") != NULL) {
453 (void) printf("dumping core by request\n");
454 abort();
457 exit(requested ? 0 : 2);
460 void
461 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
462 boolean_t print_logs, int name_flags)
464 nvlist_t **child;
465 uint_t c, children;
466 char *vname;
468 if (name != NULL)
469 (void) printf("\t%*s%s\n", indent, "", name);
471 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
472 &child, &children) != 0)
473 return;
475 for (c = 0; c < children; c++) {
476 uint64_t is_log = B_FALSE;
478 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
479 &is_log);
480 if ((is_log && !print_logs) || (!is_log && print_logs))
481 continue;
483 vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
484 print_vdev_tree(zhp, vname, child[c], indent + 2,
485 B_FALSE, name_flags);
486 free(vname);
490 static boolean_t
491 prop_list_contains_feature(nvlist_t *proplist)
493 nvpair_t *nvp;
494 for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
495 nvp = nvlist_next_nvpair(proplist, nvp)) {
496 if (zpool_prop_feature(nvpair_name(nvp)))
497 return (B_TRUE);
499 return (B_FALSE);
503 * Add a property pair (name, string-value) into a property nvlist.
505 static int
506 add_prop_list(const char *propname, char *propval, nvlist_t **props,
507 boolean_t poolprop)
509 zpool_prop_t prop = ZPROP_INVAL;
510 zfs_prop_t fprop;
511 nvlist_t *proplist;
512 const char *normnm;
513 char *strval;
515 if (*props == NULL &&
516 nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
517 (void) fprintf(stderr,
518 gettext("internal error: out of memory\n"));
519 return (1);
522 proplist = *props;
524 if (poolprop) {
525 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
527 if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL &&
528 !zpool_prop_feature(propname)) {
529 (void) fprintf(stderr, gettext("property '%s' is "
530 "not a valid pool property\n"), propname);
531 return (2);
535 * feature@ properties and version should not be specified
536 * at the same time.
538 if ((prop == ZPROP_INVAL && zpool_prop_feature(propname) &&
539 nvlist_exists(proplist, vname)) ||
540 (prop == ZPOOL_PROP_VERSION &&
541 prop_list_contains_feature(proplist))) {
542 (void) fprintf(stderr, gettext("'feature@' and "
543 "'version' properties cannot be specified "
544 "together\n"));
545 return (2);
549 if (zpool_prop_feature(propname))
550 normnm = propname;
551 else
552 normnm = zpool_prop_to_name(prop);
553 } else {
554 if ((fprop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
555 normnm = zfs_prop_to_name(fprop);
556 } else {
557 normnm = propname;
561 if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
562 prop != ZPOOL_PROP_CACHEFILE) {
563 (void) fprintf(stderr, gettext("property '%s' "
564 "specified multiple times\n"), propname);
565 return (2);
568 if (nvlist_add_string(proplist, normnm, propval) != 0) {
569 (void) fprintf(stderr, gettext("internal "
570 "error: out of memory\n"));
571 return (1);
574 return (0);
578 * Set a default property pair (name, string-value) in a property nvlist
580 static int
581 add_prop_list_default(const char *propname, char *propval, nvlist_t **props,
582 boolean_t poolprop)
584 char *pval;
586 if (nvlist_lookup_string(*props, propname, &pval) == 0)
587 return (0);
589 return (add_prop_list(propname, propval, props, B_TRUE));
593 * zpool add [-fgLnP] [-o property=value] <pool> <vdev> ...
595 * -f Force addition of devices, even if they appear in use
596 * -g Display guid for individual vdev name.
597 * -L Follow links when resolving vdev path name.
598 * -n Do not add the devices, but display the resulting layout if
599 * they were to be added.
600 * -o Set property=value.
601 * -P Display full path for vdev name.
603 * Adds the given vdevs to 'pool'. As with create, the bulk of this work is
604 * handled by get_vdev_spec(), which constructs the nvlist needed to pass to
605 * libzfs.
608 zpool_do_add(int argc, char **argv)
610 boolean_t force = B_FALSE;
611 boolean_t dryrun = B_FALSE;
612 int name_flags = 0;
613 int c;
614 nvlist_t *nvroot;
615 char *poolname;
616 int ret;
617 zpool_handle_t *zhp;
618 nvlist_t *config;
619 nvlist_t *props = NULL;
620 char *propval;
622 /* check options */
623 while ((c = getopt(argc, argv, "fgLno:P")) != -1) {
624 switch (c) {
625 case 'f':
626 force = B_TRUE;
627 break;
628 case 'g':
629 name_flags |= VDEV_NAME_GUID;
630 break;
631 case 'L':
632 name_flags |= VDEV_NAME_FOLLOW_LINKS;
633 break;
634 case 'n':
635 dryrun = B_TRUE;
636 break;
637 case 'o':
638 if ((propval = strchr(optarg, '=')) == NULL) {
639 (void) fprintf(stderr, gettext("missing "
640 "'=' for -o option\n"));
641 usage(B_FALSE);
643 *propval = '\0';
644 propval++;
646 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
647 (add_prop_list(optarg, propval, &props, B_TRUE)))
648 usage(B_FALSE);
649 break;
650 case 'P':
651 name_flags |= VDEV_NAME_PATH;
652 break;
653 case '?':
654 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
655 optopt);
656 usage(B_FALSE);
660 argc -= optind;
661 argv += optind;
663 /* get pool name and check number of arguments */
664 if (argc < 1) {
665 (void) fprintf(stderr, gettext("missing pool name argument\n"));
666 usage(B_FALSE);
668 if (argc < 2) {
669 (void) fprintf(stderr, gettext("missing vdev specification\n"));
670 usage(B_FALSE);
673 poolname = argv[0];
675 argc--;
676 argv++;
678 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
679 return (1);
681 if ((config = zpool_get_config(zhp, NULL)) == NULL) {
682 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
683 poolname);
684 zpool_close(zhp);
685 return (1);
688 /* unless manually specified use "ashift" pool property (if set) */
689 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
690 int intval;
691 zprop_source_t src;
692 char strval[ZPOOL_MAXPROPLEN];
694 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
695 if (src != ZPROP_SRC_DEFAULT) {
696 (void) sprintf(strval, "%" PRId32, intval);
697 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
698 &props, B_TRUE) == 0);
702 /* pass off to get_vdev_spec for processing */
703 nvroot = make_root_vdev(zhp, props, force, !force, B_FALSE, dryrun,
704 argc, argv);
705 if (nvroot == NULL) {
706 zpool_close(zhp);
707 return (1);
710 if (dryrun) {
711 nvlist_t *poolnvroot;
712 nvlist_t **l2child;
713 uint_t l2children, c;
714 char *vname;
715 boolean_t hadcache = B_FALSE;
717 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
718 &poolnvroot) == 0);
720 (void) printf(gettext("would update '%s' to the following "
721 "configuration:\n"), zpool_get_name(zhp));
723 /* print original main pool and new tree */
724 print_vdev_tree(zhp, poolname, poolnvroot, 0, B_FALSE,
725 name_flags);
726 print_vdev_tree(zhp, NULL, nvroot, 0, B_FALSE, name_flags);
728 /* Do the same for the logs */
729 if (num_logs(poolnvroot) > 0) {
730 print_vdev_tree(zhp, "logs", poolnvroot, 0, B_TRUE,
731 name_flags);
732 print_vdev_tree(zhp, NULL, nvroot, 0, B_TRUE,
733 name_flags);
734 } else if (num_logs(nvroot) > 0) {
735 print_vdev_tree(zhp, "logs", nvroot, 0, B_TRUE,
736 name_flags);
739 /* Do the same for the caches */
740 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
741 &l2child, &l2children) == 0 && l2children) {
742 hadcache = B_TRUE;
743 (void) printf(gettext("\tcache\n"));
744 for (c = 0; c < l2children; c++) {
745 vname = zpool_vdev_name(g_zfs, NULL,
746 l2child[c], name_flags);
747 (void) printf("\t %s\n", vname);
748 free(vname);
751 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
752 &l2child, &l2children) == 0 && l2children) {
753 if (!hadcache)
754 (void) printf(gettext("\tcache\n"));
755 for (c = 0; c < l2children; c++) {
756 vname = zpool_vdev_name(g_zfs, NULL,
757 l2child[c], name_flags);
758 (void) printf("\t %s\n", vname);
759 free(vname);
763 ret = 0;
764 } else {
765 ret = (zpool_add(zhp, nvroot) != 0);
768 nvlist_free(props);
769 nvlist_free(nvroot);
770 zpool_close(zhp);
772 return (ret);
776 * zpool remove <pool> <vdev> ...
778 * Removes the given vdev from the pool. Currently, this supports removing
779 * spares, cache, and log devices from the pool.
782 zpool_do_remove(int argc, char **argv)
784 char *poolname;
785 int i, ret = 0;
786 zpool_handle_t *zhp = NULL;
788 argc--;
789 argv++;
791 /* get pool name and check number of arguments */
792 if (argc < 1) {
793 (void) fprintf(stderr, gettext("missing pool name argument\n"));
794 usage(B_FALSE);
796 if (argc < 2) {
797 (void) fprintf(stderr, gettext("missing device\n"));
798 usage(B_FALSE);
801 poolname = argv[0];
803 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
804 return (1);
806 for (i = 1; i < argc; i++) {
807 if (zpool_vdev_remove(zhp, argv[i]) != 0)
808 ret = 1;
810 zpool_close(zhp);
812 return (ret);
816 * zpool labelclear [-f] <vdev>
818 * -f Force clearing the label for the vdevs which are members of
819 * the exported or foreign pools.
821 * Verifies that the vdev is not active and zeros out the label information
822 * on the device.
825 zpool_do_labelclear(int argc, char **argv)
827 char vdev[MAXPATHLEN];
828 char *name = NULL;
829 struct stat st;
830 int c, fd = -1, ret = 0;
831 nvlist_t *config;
832 pool_state_t state;
833 boolean_t inuse = B_FALSE;
834 boolean_t force = B_FALSE;
836 /* check options */
837 while ((c = getopt(argc, argv, "f")) != -1) {
838 switch (c) {
839 case 'f':
840 force = B_TRUE;
841 break;
842 default:
843 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
844 optopt);
845 usage(B_FALSE);
849 argc -= optind;
850 argv += optind;
852 /* get vdev name */
853 if (argc < 1) {
854 (void) fprintf(stderr, gettext("missing vdev name\n"));
855 usage(B_FALSE);
857 if (argc > 1) {
858 (void) fprintf(stderr, gettext("too many arguments\n"));
859 usage(B_FALSE);
863 * Check if we were given absolute path and use it as is.
864 * Otherwise if the provided vdev name doesn't point to a file,
865 * try prepending expected disk paths and partition numbers.
867 (void) strlcpy(vdev, argv[0], sizeof (vdev));
868 if (vdev[0] != '/' && stat(vdev, &st) != 0) {
869 int error;
871 error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
872 if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
873 if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
874 error = ENOENT;
877 if (error || (stat(vdev, &st) != 0)) {
878 (void) fprintf(stderr, gettext(
879 "failed to find device %s, try specifying absolute "
880 "path instead\n"), argv[0]);
881 return (1);
885 if ((fd = open(vdev, O_RDWR)) < 0) {
886 (void) fprintf(stderr, gettext("failed to open %s: %s\n"),
887 vdev, strerror(errno));
888 return (1);
891 if (ioctl(fd, BLKFLSBUF) != 0)
892 (void) fprintf(stderr, gettext("failed to invalidate "
893 "cache for %s: %s\n"), vdev, strerror(errno));
895 if (zpool_read_label(fd, &config, NULL) != 0 || config == NULL) {
896 (void) fprintf(stderr,
897 gettext("failed to check state for %s\n"), vdev);
898 return (1);
900 nvlist_free(config);
902 ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
903 if (ret != 0) {
904 (void) fprintf(stderr,
905 gettext("failed to check state for %s\n"), vdev);
906 return (1);
909 if (!inuse)
910 goto wipe_label;
912 switch (state) {
913 default:
914 case POOL_STATE_ACTIVE:
915 case POOL_STATE_SPARE:
916 case POOL_STATE_L2CACHE:
917 (void) fprintf(stderr, gettext(
918 "%s is a member (%s) of pool \"%s\"\n"),
919 vdev, zpool_pool_state_to_name(state), name);
920 ret = 1;
921 goto errout;
923 case POOL_STATE_EXPORTED:
924 if (force)
925 break;
926 (void) fprintf(stderr, gettext(
927 "use '-f' to override the following error:\n"
928 "%s is a member of exported pool \"%s\"\n"),
929 vdev, name);
930 ret = 1;
931 goto errout;
933 case POOL_STATE_POTENTIALLY_ACTIVE:
934 if (force)
935 break;
936 (void) fprintf(stderr, gettext(
937 "use '-f' to override the following error:\n"
938 "%s is a member of potentially active pool \"%s\"\n"),
939 vdev, name);
940 ret = 1;
941 goto errout;
943 case POOL_STATE_DESTROYED:
944 /* inuse should never be set for a destroyed pool */
945 assert(0);
946 break;
949 wipe_label:
950 ret = zpool_clear_label(fd);
951 if (ret != 0) {
952 (void) fprintf(stderr,
953 gettext("failed to clear label for %s\n"), vdev);
956 errout:
957 free(name);
958 (void) close(fd);
960 return (ret);
964 * zpool create [-fnd] [-o property=value] ...
965 * [-O file-system-property=value] ...
966 * [-R root] [-m mountpoint] <pool> <dev> ...
968 * -f Force creation, even if devices appear in use
969 * -n Do not create the pool, but display the resulting layout if it
970 * were to be created.
971 * -R Create a pool under an alternate root
972 * -m Set default mountpoint for the root dataset. By default it's
973 * '/<pool>'
974 * -o Set property=value.
975 * -o Set feature@feature=enabled|disabled.
976 * -d Don't automatically enable all supported pool features
977 * (individual features can be enabled with -o).
978 * -O Set fsproperty=value in the pool's root file system
980 * Creates the named pool according to the given vdev specification. The
981 * bulk of the vdev processing is done in get_vdev_spec() in zpool_vdev.c. Once
982 * we get the nvlist back from get_vdev_spec(), we either print out the contents
983 * (if '-n' was specified), or pass it to libzfs to do the creation.
986 zpool_do_create(int argc, char **argv)
988 boolean_t force = B_FALSE;
989 boolean_t dryrun = B_FALSE;
990 boolean_t enable_all_pool_feat = B_TRUE;
991 int c;
992 nvlist_t *nvroot = NULL;
993 char *poolname;
994 char *tname = NULL;
995 int ret = 1;
996 char *altroot = NULL;
997 char *mountpoint = NULL;
998 nvlist_t *fsprops = NULL;
999 nvlist_t *props = NULL;
1000 char *propval;
1002 /* check options */
1003 while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
1004 switch (c) {
1005 case 'f':
1006 force = B_TRUE;
1007 break;
1008 case 'n':
1009 dryrun = B_TRUE;
1010 break;
1011 case 'd':
1012 enable_all_pool_feat = B_FALSE;
1013 break;
1014 case 'R':
1015 altroot = optarg;
1016 if (add_prop_list(zpool_prop_to_name(
1017 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
1018 goto errout;
1019 if (add_prop_list_default(zpool_prop_to_name(
1020 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1021 goto errout;
1022 break;
1023 case 'm':
1024 /* Equivalent to -O mountpoint=optarg */
1025 mountpoint = optarg;
1026 break;
1027 case 'o':
1028 if ((propval = strchr(optarg, '=')) == NULL) {
1029 (void) fprintf(stderr, gettext("missing "
1030 "'=' for -o option\n"));
1031 goto errout;
1033 *propval = '\0';
1034 propval++;
1036 if (add_prop_list(optarg, propval, &props, B_TRUE))
1037 goto errout;
1040 * If the user is creating a pool that doesn't support
1041 * feature flags, don't enable any features.
1043 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
1044 char *end;
1045 u_longlong_t ver;
1047 ver = strtoull(propval, &end, 10);
1048 if (*end == '\0' &&
1049 ver < SPA_VERSION_FEATURES) {
1050 enable_all_pool_feat = B_FALSE;
1053 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
1054 altroot = propval;
1055 break;
1056 case 'O':
1057 if ((propval = strchr(optarg, '=')) == NULL) {
1058 (void) fprintf(stderr, gettext("missing "
1059 "'=' for -O option\n"));
1060 goto errout;
1062 *propval = '\0';
1063 propval++;
1066 * Mountpoints are checked and then added later.
1067 * Uniquely among properties, they can be specified
1068 * more than once, to avoid conflict with -m.
1070 if (0 == strcmp(optarg,
1071 zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
1072 mountpoint = propval;
1073 } else if (add_prop_list(optarg, propval, &fsprops,
1074 B_FALSE)) {
1075 goto errout;
1077 break;
1078 case 't':
1080 * Sanity check temporary pool name.
1082 if (strchr(optarg, '/') != NULL) {
1083 (void) fprintf(stderr, gettext("cannot create "
1084 "'%s': invalid character '/' in temporary "
1085 "name\n"), optarg);
1086 (void) fprintf(stderr, gettext("use 'zfs "
1087 "create' to create a dataset\n"));
1088 goto errout;
1091 if (add_prop_list(zpool_prop_to_name(
1092 ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
1093 goto errout;
1094 if (add_prop_list_default(zpool_prop_to_name(
1095 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1096 goto errout;
1097 tname = optarg;
1098 break;
1099 case ':':
1100 (void) fprintf(stderr, gettext("missing argument for "
1101 "'%c' option\n"), optopt);
1102 goto badusage;
1103 case '?':
1104 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1105 optopt);
1106 goto badusage;
1110 argc -= optind;
1111 argv += optind;
1113 /* get pool name and check number of arguments */
1114 if (argc < 1) {
1115 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1116 goto badusage;
1118 if (argc < 2) {
1119 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1120 goto badusage;
1123 poolname = argv[0];
1126 * As a special case, check for use of '/' in the name, and direct the
1127 * user to use 'zfs create' instead.
1129 if (strchr(poolname, '/') != NULL) {
1130 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
1131 "character '/' in pool name\n"), poolname);
1132 (void) fprintf(stderr, gettext("use 'zfs create' to "
1133 "create a dataset\n"));
1134 goto errout;
1137 /* pass off to get_vdev_spec for bulk processing */
1138 nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
1139 argc - 1, argv + 1);
1140 if (nvroot == NULL)
1141 goto errout;
1143 /* make_root_vdev() allows 0 toplevel children if there are spares */
1144 if (!zfs_allocatable_devs(nvroot)) {
1145 (void) fprintf(stderr, gettext("invalid vdev "
1146 "specification: at least one toplevel vdev must be "
1147 "specified\n"));
1148 goto errout;
1151 if (altroot != NULL && altroot[0] != '/') {
1152 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
1153 "must be an absolute path\n"), altroot);
1154 goto errout;
1158 * Check the validity of the mountpoint and direct the user to use the
1159 * '-m' mountpoint option if it looks like its in use.
1161 if (mountpoint == NULL ||
1162 (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
1163 strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
1164 char buf[MAXPATHLEN];
1165 DIR *dirp;
1167 if (mountpoint && mountpoint[0] != '/') {
1168 (void) fprintf(stderr, gettext("invalid mountpoint "
1169 "'%s': must be an absolute path, 'legacy', or "
1170 "'none'\n"), mountpoint);
1171 goto errout;
1174 if (mountpoint == NULL) {
1175 if (altroot != NULL)
1176 (void) snprintf(buf, sizeof (buf), "%s/%s",
1177 altroot, poolname);
1178 else
1179 (void) snprintf(buf, sizeof (buf), "/%s",
1180 poolname);
1181 } else {
1182 if (altroot != NULL)
1183 (void) snprintf(buf, sizeof (buf), "%s%s",
1184 altroot, mountpoint);
1185 else
1186 (void) snprintf(buf, sizeof (buf), "%s",
1187 mountpoint);
1190 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
1191 (void) fprintf(stderr, gettext("mountpoint '%s' : "
1192 "%s\n"), buf, strerror(errno));
1193 (void) fprintf(stderr, gettext("use '-m' "
1194 "option to provide a different default\n"));
1195 goto errout;
1196 } else if (dirp) {
1197 int count = 0;
1199 while (count < 3 && readdir(dirp) != NULL)
1200 count++;
1201 (void) closedir(dirp);
1203 if (count > 2) {
1204 (void) fprintf(stderr, gettext("mountpoint "
1205 "'%s' exists and is not empty\n"), buf);
1206 (void) fprintf(stderr, gettext("use '-m' "
1207 "option to provide a "
1208 "different default\n"));
1209 goto errout;
1215 * Now that the mountpoint's validity has been checked, ensure that
1216 * the property is set appropriately prior to creating the pool.
1218 if (mountpoint != NULL) {
1219 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
1220 mountpoint, &fsprops, B_FALSE);
1221 if (ret != 0)
1222 goto errout;
1225 ret = 1;
1226 if (dryrun) {
1228 * For a dry run invocation, print out a basic message and run
1229 * through all the vdevs in the list and print out in an
1230 * appropriate hierarchy.
1232 (void) printf(gettext("would create '%s' with the "
1233 "following layout:\n\n"), poolname);
1235 print_vdev_tree(NULL, poolname, nvroot, 0, B_FALSE, 0);
1236 if (num_logs(nvroot) > 0)
1237 print_vdev_tree(NULL, "logs", nvroot, 0, B_TRUE, 0);
1239 ret = 0;
1240 } else {
1242 * Hand off to libzfs.
1244 spa_feature_t i;
1245 for (i = 0; i < SPA_FEATURES; i++) {
1246 char propname[MAXPATHLEN];
1247 char *propval;
1248 zfeature_info_t *feat = &spa_feature_table[i];
1250 (void) snprintf(propname, sizeof (propname),
1251 "feature@%s", feat->fi_uname);
1254 * Only features contained in props will be enabled:
1255 * remove from the nvlist every ZFS_FEATURE_DISABLED
1256 * value and add every missing ZFS_FEATURE_ENABLED if
1257 * enable_all_pool_feat is set.
1259 if (!nvlist_lookup_string(props, propname, &propval)) {
1260 if (strcmp(propval, ZFS_FEATURE_DISABLED) == 0)
1261 (void) nvlist_remove_all(props,
1262 propname);
1263 } else if (enable_all_pool_feat) {
1264 ret = add_prop_list(propname,
1265 ZFS_FEATURE_ENABLED, &props, B_TRUE);
1266 if (ret != 0)
1267 goto errout;
1271 ret = 1;
1272 if (zpool_create(g_zfs, poolname,
1273 nvroot, props, fsprops) == 0) {
1274 zfs_handle_t *pool = zfs_open(g_zfs,
1275 tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
1276 if (pool != NULL) {
1277 if (zfs_mount(pool, NULL, 0) == 0)
1278 ret = zfs_shareall(pool);
1279 zfs_close(pool);
1281 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
1282 (void) fprintf(stderr, gettext("pool name may have "
1283 "been omitted\n"));
1287 errout:
1288 nvlist_free(nvroot);
1289 nvlist_free(fsprops);
1290 nvlist_free(props);
1291 return (ret);
1292 badusage:
1293 nvlist_free(fsprops);
1294 nvlist_free(props);
1295 usage(B_FALSE);
1296 return (2);
1300 * zpool destroy <pool>
1302 * -f Forcefully unmount any datasets
1304 * Destroy the given pool. Automatically unmounts any datasets in the pool.
1307 zpool_do_destroy(int argc, char **argv)
1309 boolean_t force = B_FALSE;
1310 int c;
1311 char *pool;
1312 zpool_handle_t *zhp;
1313 int ret;
1315 /* check options */
1316 while ((c = getopt(argc, argv, "f")) != -1) {
1317 switch (c) {
1318 case 'f':
1319 force = B_TRUE;
1320 break;
1321 case '?':
1322 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1323 optopt);
1324 usage(B_FALSE);
1328 argc -= optind;
1329 argv += optind;
1331 /* check arguments */
1332 if (argc < 1) {
1333 (void) fprintf(stderr, gettext("missing pool argument\n"));
1334 usage(B_FALSE);
1336 if (argc > 1) {
1337 (void) fprintf(stderr, gettext("too many arguments\n"));
1338 usage(B_FALSE);
1341 pool = argv[0];
1343 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
1345 * As a special case, check for use of '/' in the name, and
1346 * direct the user to use 'zfs destroy' instead.
1348 if (strchr(pool, '/') != NULL)
1349 (void) fprintf(stderr, gettext("use 'zfs destroy' to "
1350 "destroy a dataset\n"));
1351 return (1);
1354 if (zpool_disable_datasets(zhp, force) != 0) {
1355 (void) fprintf(stderr, gettext("could not destroy '%s': "
1356 "could not unmount datasets\n"), zpool_get_name(zhp));
1357 zpool_close(zhp);
1358 return (1);
1361 /* The history must be logged as part of the export */
1362 log_history = B_FALSE;
1364 ret = (zpool_destroy(zhp, history_str) != 0);
1366 zpool_close(zhp);
1368 return (ret);
1371 typedef struct export_cbdata {
1372 boolean_t force;
1373 boolean_t hardforce;
1374 } export_cbdata_t;
1377 * Export one pool
1380 zpool_export_one(zpool_handle_t *zhp, void *data)
1382 export_cbdata_t *cb = data;
1384 if (zpool_disable_datasets(zhp, cb->force) != 0)
1385 return (1);
1387 /* The history must be logged as part of the export */
1388 log_history = B_FALSE;
1390 if (cb->hardforce) {
1391 if (zpool_export_force(zhp, history_str) != 0)
1392 return (1);
1393 } else if (zpool_export(zhp, cb->force, history_str) != 0) {
1394 return (1);
1397 return (0);
1401 * zpool export [-f] <pool> ...
1403 * -a Export all pools
1404 * -f Forcefully unmount datasets
1406 * Export the given pools. By default, the command will attempt to cleanly
1407 * unmount any active datasets within the pool. If the '-f' flag is specified,
1408 * then the datasets will be forcefully unmounted.
1411 zpool_do_export(int argc, char **argv)
1413 export_cbdata_t cb;
1414 boolean_t do_all = B_FALSE;
1415 boolean_t force = B_FALSE;
1416 boolean_t hardforce = B_FALSE;
1417 int c, ret;
1419 /* check options */
1420 while ((c = getopt(argc, argv, "afF")) != -1) {
1421 switch (c) {
1422 case 'a':
1423 do_all = B_TRUE;
1424 break;
1425 case 'f':
1426 force = B_TRUE;
1427 break;
1428 case 'F':
1429 hardforce = B_TRUE;
1430 break;
1431 case '?':
1432 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1433 optopt);
1434 usage(B_FALSE);
1438 cb.force = force;
1439 cb.hardforce = hardforce;
1440 argc -= optind;
1441 argv += optind;
1443 if (do_all) {
1444 if (argc != 0) {
1445 (void) fprintf(stderr, gettext("too many arguments\n"));
1446 usage(B_FALSE);
1449 return (for_each_pool(argc, argv, B_TRUE, NULL,
1450 zpool_export_one, &cb));
1453 /* check arguments */
1454 if (argc < 1) {
1455 (void) fprintf(stderr, gettext("missing pool argument\n"));
1456 usage(B_FALSE);
1459 ret = for_each_pool(argc, argv, B_TRUE, NULL, zpool_export_one, &cb);
1461 return (ret);
1465 * Given a vdev configuration, determine the maximum width needed for the device
1466 * name column.
1468 static int
1469 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
1470 int name_flags)
1472 char *name;
1473 nvlist_t **child;
1474 uint_t c, children;
1475 int ret;
1477 name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
1478 if (strlen(name) + depth > max)
1479 max = strlen(name) + depth;
1481 free(name);
1483 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1484 &child, &children) == 0) {
1485 for (c = 0; c < children; c++)
1486 if ((ret = max_width(zhp, child[c], depth + 2,
1487 max, name_flags)) > max)
1488 max = ret;
1491 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1492 &child, &children) == 0) {
1493 for (c = 0; c < children; c++)
1494 if ((ret = max_width(zhp, child[c], depth + 2,
1495 max, name_flags)) > max)
1496 max = ret;
1499 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1500 &child, &children) == 0) {
1501 for (c = 0; c < children; c++)
1502 if ((ret = max_width(zhp, child[c], depth + 2,
1503 max, name_flags)) > max)
1504 max = ret;
1507 return (max);
1510 typedef struct spare_cbdata {
1511 uint64_t cb_guid;
1512 zpool_handle_t *cb_zhp;
1513 } spare_cbdata_t;
1515 static boolean_t
1516 find_vdev(nvlist_t *nv, uint64_t search)
1518 uint64_t guid;
1519 nvlist_t **child;
1520 uint_t c, children;
1522 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1523 search == guid)
1524 return (B_TRUE);
1526 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1527 &child, &children) == 0) {
1528 for (c = 0; c < children; c++)
1529 if (find_vdev(child[c], search))
1530 return (B_TRUE);
1533 return (B_FALSE);
1536 static int
1537 find_spare(zpool_handle_t *zhp, void *data)
1539 spare_cbdata_t *cbp = data;
1540 nvlist_t *config, *nvroot;
1542 config = zpool_get_config(zhp, NULL);
1543 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1544 &nvroot) == 0);
1546 if (find_vdev(nvroot, cbp->cb_guid)) {
1547 cbp->cb_zhp = zhp;
1548 return (1);
1551 zpool_close(zhp);
1552 return (0);
1555 typedef struct status_cbdata {
1556 int cb_count;
1557 int cb_name_flags;
1558 int cb_namewidth;
1559 boolean_t cb_allpools;
1560 boolean_t cb_verbose;
1561 boolean_t cb_explain;
1562 boolean_t cb_first;
1563 boolean_t cb_dedup_stats;
1564 boolean_t cb_print_status;
1565 vdev_cmd_data_list_t *vcdl;
1566 } status_cbdata_t;
1568 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
1569 static int
1570 is_blank_str(char *str)
1572 while (str != NULL && *str != '\0') {
1573 if (!isblank(*str))
1574 return (0);
1575 str++;
1577 return (1);
1580 /* Print command output lines for specific vdev in a specific pool */
1581 static void
1582 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, char *path)
1584 vdev_cmd_data_t *data;
1585 int i, j;
1586 char *val;
1588 for (i = 0; i < vcdl->count; i++) {
1589 if ((strcmp(vcdl->data[i].path, path) != 0) ||
1590 (strcmp(vcdl->data[i].pool, pool) != 0)) {
1591 /* Not the vdev we're looking for */
1592 continue;
1595 data = &vcdl->data[i];
1596 /* Print out all the output values for this vdev */
1597 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
1598 val = NULL;
1599 /* Does this vdev have values for this column? */
1600 for (int k = 0; k < data->cols_cnt; k++) {
1601 if (strcmp(data->cols[k],
1602 vcdl->uniq_cols[j]) == 0) {
1603 /* yes it does, record the value */
1604 val = data->lines[k];
1605 break;
1609 * Mark empty values with dashes to make output
1610 * awk-able.
1612 if (is_blank_str(val))
1613 val = "-";
1615 printf("%*s", vcdl->uniq_cols_width[j], val);
1616 if (j < vcdl->uniq_cols_cnt - 1)
1617 printf(" ");
1620 /* Print out any values that aren't in a column at the end */
1621 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
1622 /* Did we have any columns? If so print a spacer. */
1623 if (vcdl->uniq_cols_cnt > 0)
1624 printf(" ");
1626 val = data->lines[j];
1627 printf("%s", val ? val : "");
1629 break;
1634 * Print out configuration state as requested by status_callback.
1636 static void
1637 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
1638 nvlist_t *nv, int depth, boolean_t isspare)
1640 nvlist_t **child;
1641 uint_t c, children;
1642 pool_scan_stat_t *ps = NULL;
1643 vdev_stat_t *vs;
1644 char rbuf[6], wbuf[6], cbuf[6];
1645 char *vname;
1646 uint64_t notpresent;
1647 spare_cbdata_t spare_cb;
1648 char *state;
1649 char *path = NULL;
1651 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1652 &child, &children) != 0)
1653 children = 0;
1655 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1656 (uint64_t **)&vs, &c) == 0);
1658 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1659 if (isspare) {
1661 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
1662 * online drives.
1664 if (vs->vs_aux == VDEV_AUX_SPARED)
1665 state = "INUSE";
1666 else if (vs->vs_state == VDEV_STATE_HEALTHY)
1667 state = "AVAIL";
1670 (void) printf("\t%*s%-*s %-8s", depth, "", cb->cb_namewidth - depth,
1671 name, state);
1673 if (!isspare) {
1674 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
1675 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
1676 zfs_nicenum(vs->vs_checksum_errors, cbuf, sizeof (cbuf));
1677 (void) printf(" %5s %5s %5s", rbuf, wbuf, cbuf);
1680 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
1681 &notpresent) == 0) {
1682 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
1683 (void) printf(" was %s", path);
1684 } else if (vs->vs_aux != 0) {
1685 (void) printf(" ");
1687 switch (vs->vs_aux) {
1688 case VDEV_AUX_OPEN_FAILED:
1689 (void) printf(gettext("cannot open"));
1690 break;
1692 case VDEV_AUX_BAD_GUID_SUM:
1693 (void) printf(gettext("missing device"));
1694 break;
1696 case VDEV_AUX_NO_REPLICAS:
1697 (void) printf(gettext("insufficient replicas"));
1698 break;
1700 case VDEV_AUX_VERSION_NEWER:
1701 (void) printf(gettext("newer version"));
1702 break;
1704 case VDEV_AUX_UNSUP_FEAT:
1705 (void) printf(gettext("unsupported feature(s)"));
1706 break;
1708 case VDEV_AUX_SPARED:
1709 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
1710 &spare_cb.cb_guid) == 0);
1711 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1712 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1713 zpool_get_name(zhp)) == 0)
1714 (void) printf(gettext("currently in "
1715 "use"));
1716 else
1717 (void) printf(gettext("in use by "
1718 "pool '%s'"),
1719 zpool_get_name(spare_cb.cb_zhp));
1720 zpool_close(spare_cb.cb_zhp);
1721 } else {
1722 (void) printf(gettext("currently in use"));
1724 break;
1726 case VDEV_AUX_ERR_EXCEEDED:
1727 (void) printf(gettext("too many errors"));
1728 break;
1730 case VDEV_AUX_IO_FAILURE:
1731 (void) printf(gettext("experienced I/O failures"));
1732 break;
1734 case VDEV_AUX_BAD_LOG:
1735 (void) printf(gettext("bad intent log"));
1736 break;
1738 case VDEV_AUX_EXTERNAL:
1739 (void) printf(gettext("external device fault"));
1740 break;
1742 case VDEV_AUX_SPLIT_POOL:
1743 (void) printf(gettext("split into new pool"));
1744 break;
1746 default:
1747 (void) printf(gettext("corrupted data"));
1748 break;
1752 (void) nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_SCAN_STATS,
1753 (uint64_t **)&ps, &c);
1755 if (ps && ps->pss_state == DSS_SCANNING &&
1756 vs->vs_scan_processed != 0 && children == 0) {
1757 (void) printf(gettext(" (%s)"),
1758 (ps->pss_func == POOL_SCAN_RESILVER) ?
1759 "resilvering" : "repairing");
1762 if (cb->vcdl != NULL) {
1763 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
1764 printf(" ");
1765 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
1769 (void) printf("\n");
1771 for (c = 0; c < children; c++) {
1772 uint64_t islog = B_FALSE, ishole = B_FALSE;
1774 /* Don't print logs or holes here */
1775 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1776 &islog);
1777 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
1778 &ishole);
1779 if (islog || ishole)
1780 continue;
1781 vname = zpool_vdev_name(g_zfs, zhp, child[c],
1782 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1783 print_status_config(zhp, cb, vname, child[c], depth + 2,
1784 isspare);
1785 free(vname);
1790 * Print the configuration of an exported pool. Iterate over all vdevs in the
1791 * pool, printing out the name and status for each one.
1793 static void
1794 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
1795 int depth)
1797 nvlist_t **child;
1798 uint_t c, children;
1799 vdev_stat_t *vs;
1800 char *type, *vname;
1802 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1803 if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
1804 strcmp(type, VDEV_TYPE_HOLE) == 0)
1805 return;
1807 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1808 (uint64_t **)&vs, &c) == 0);
1810 (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
1811 (void) printf(" %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
1813 if (vs->vs_aux != 0) {
1814 (void) printf(" ");
1816 switch (vs->vs_aux) {
1817 case VDEV_AUX_OPEN_FAILED:
1818 (void) printf(gettext("cannot open"));
1819 break;
1821 case VDEV_AUX_BAD_GUID_SUM:
1822 (void) printf(gettext("missing device"));
1823 break;
1825 case VDEV_AUX_NO_REPLICAS:
1826 (void) printf(gettext("insufficient replicas"));
1827 break;
1829 case VDEV_AUX_VERSION_NEWER:
1830 (void) printf(gettext("newer version"));
1831 break;
1833 case VDEV_AUX_UNSUP_FEAT:
1834 (void) printf(gettext("unsupported feature(s)"));
1835 break;
1837 case VDEV_AUX_ERR_EXCEEDED:
1838 (void) printf(gettext("too many errors"));
1839 break;
1841 default:
1842 (void) printf(gettext("corrupted data"));
1843 break;
1846 (void) printf("\n");
1848 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1849 &child, &children) != 0)
1850 return;
1852 for (c = 0; c < children; c++) {
1853 uint64_t is_log = B_FALSE;
1855 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1856 &is_log);
1857 if (is_log)
1858 continue;
1860 vname = zpool_vdev_name(g_zfs, NULL, child[c],
1861 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1862 print_import_config(cb, vname, child[c], depth + 2);
1863 free(vname);
1866 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1867 &child, &children) == 0) {
1868 (void) printf(gettext("\tcache\n"));
1869 for (c = 0; c < children; c++) {
1870 vname = zpool_vdev_name(g_zfs, NULL, child[c],
1871 cb->cb_name_flags);
1872 (void) printf("\t %s\n", vname);
1873 free(vname);
1877 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1878 &child, &children) == 0) {
1879 (void) printf(gettext("\tspares\n"));
1880 for (c = 0; c < children; c++) {
1881 vname = zpool_vdev_name(g_zfs, NULL, child[c],
1882 cb->cb_name_flags);
1883 (void) printf("\t %s\n", vname);
1884 free(vname);
1890 * Print log vdevs.
1891 * Logs are recorded as top level vdevs in the main pool child array
1892 * but with "is_log" set to 1. We use either print_status_config() or
1893 * print_import_config() to print the top level logs then any log
1894 * children (eg mirrored slogs) are printed recursively - which
1895 * works because only the top level vdev is marked "is_log"
1897 static void
1898 print_logs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv)
1900 uint_t c, children;
1901 nvlist_t **child;
1903 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
1904 &children) != 0)
1905 return;
1907 (void) printf(gettext("\tlogs\n"));
1909 for (c = 0; c < children; c++) {
1910 uint64_t is_log = B_FALSE;
1911 char *name;
1913 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1914 &is_log);
1915 if (!is_log)
1916 continue;
1917 name = zpool_vdev_name(g_zfs, zhp, child[c],
1918 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1919 if (cb->cb_print_status)
1920 print_status_config(zhp, cb, name, child[c], 2,
1921 B_FALSE);
1922 else
1923 print_import_config(cb, name, child[c], 2);
1924 free(name);
1929 * Display the status for the given pool.
1931 static void
1932 show_import(nvlist_t *config)
1934 uint64_t pool_state;
1935 vdev_stat_t *vs;
1936 char *name;
1937 uint64_t guid;
1938 char *msgid;
1939 nvlist_t *nvroot;
1940 zpool_status_t reason;
1941 zpool_errata_t errata;
1942 const char *health;
1943 uint_t vsc;
1944 char *comment;
1945 status_cbdata_t cb = { 0 };
1947 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1948 &name) == 0);
1949 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1950 &guid) == 0);
1951 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
1952 &pool_state) == 0);
1953 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1954 &nvroot) == 0);
1956 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
1957 (uint64_t **)&vs, &vsc) == 0);
1958 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1960 reason = zpool_import_status(config, &msgid, &errata);
1962 (void) printf(gettext(" pool: %s\n"), name);
1963 (void) printf(gettext(" id: %llu\n"), (u_longlong_t)guid);
1964 (void) printf(gettext(" state: %s"), health);
1965 if (pool_state == POOL_STATE_DESTROYED)
1966 (void) printf(gettext(" (DESTROYED)"));
1967 (void) printf("\n");
1969 switch (reason) {
1970 case ZPOOL_STATUS_MISSING_DEV_R:
1971 case ZPOOL_STATUS_MISSING_DEV_NR:
1972 case ZPOOL_STATUS_BAD_GUID_SUM:
1973 (void) printf(gettext(" status: One or more devices are "
1974 "missing from the system.\n"));
1975 break;
1977 case ZPOOL_STATUS_CORRUPT_LABEL_R:
1978 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
1979 (void) printf(gettext(" status: One or more devices contains "
1980 "corrupted data.\n"));
1981 break;
1983 case ZPOOL_STATUS_CORRUPT_DATA:
1984 (void) printf(
1985 gettext(" status: The pool data is corrupted.\n"));
1986 break;
1988 case ZPOOL_STATUS_OFFLINE_DEV:
1989 (void) printf(gettext(" status: One or more devices "
1990 "are offlined.\n"));
1991 break;
1993 case ZPOOL_STATUS_CORRUPT_POOL:
1994 (void) printf(gettext(" status: The pool metadata is "
1995 "corrupted.\n"));
1996 break;
1998 case ZPOOL_STATUS_VERSION_OLDER:
1999 (void) printf(gettext(" status: The pool is formatted using a "
2000 "legacy on-disk version.\n"));
2001 break;
2003 case ZPOOL_STATUS_VERSION_NEWER:
2004 (void) printf(gettext(" status: The pool is formatted using an "
2005 "incompatible version.\n"));
2006 break;
2008 case ZPOOL_STATUS_FEAT_DISABLED:
2009 (void) printf(gettext(" status: Some supported features are "
2010 "not enabled on the pool.\n"));
2011 break;
2013 case ZPOOL_STATUS_UNSUP_FEAT_READ:
2014 (void) printf(gettext("status: The pool uses the following "
2015 "feature(s) not supported on this system:\n"));
2016 zpool_print_unsup_feat(config);
2017 break;
2019 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2020 (void) printf(gettext("status: The pool can only be accessed "
2021 "in read-only mode on this system. It\n\tcannot be "
2022 "accessed in read-write mode because it uses the "
2023 "following\n\tfeature(s) not supported on this system:\n"));
2024 zpool_print_unsup_feat(config);
2025 break;
2027 case ZPOOL_STATUS_HOSTID_MISMATCH:
2028 (void) printf(gettext(" status: The pool was last accessed by "
2029 "another system.\n"));
2030 break;
2032 case ZPOOL_STATUS_FAULTED_DEV_R:
2033 case ZPOOL_STATUS_FAULTED_DEV_NR:
2034 (void) printf(gettext(" status: One or more devices are "
2035 "faulted.\n"));
2036 break;
2038 case ZPOOL_STATUS_BAD_LOG:
2039 (void) printf(gettext(" status: An intent log record cannot be "
2040 "read.\n"));
2041 break;
2043 case ZPOOL_STATUS_RESILVERING:
2044 (void) printf(gettext(" status: One or more devices were being "
2045 "resilvered.\n"));
2046 break;
2048 case ZPOOL_STATUS_ERRATA:
2049 (void) printf(gettext(" status: Errata #%d detected.\n"),
2050 errata);
2051 break;
2053 default:
2055 * No other status can be seen when importing pools.
2057 assert(reason == ZPOOL_STATUS_OK);
2061 * Print out an action according to the overall state of the pool.
2063 if (vs->vs_state == VDEV_STATE_HEALTHY) {
2064 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
2065 reason == ZPOOL_STATUS_FEAT_DISABLED) {
2066 (void) printf(gettext(" action: The pool can be "
2067 "imported using its name or numeric identifier, "
2068 "though\n\tsome features will not be available "
2069 "without an explicit 'zpool upgrade'.\n"));
2070 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
2071 (void) printf(gettext(" action: The pool can be "
2072 "imported using its name or numeric "
2073 "identifier and\n\tthe '-f' flag.\n"));
2074 } else if (reason == ZPOOL_STATUS_ERRATA) {
2075 switch (errata) {
2076 case ZPOOL_ERRATA_NONE:
2077 break;
2079 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
2080 (void) printf(gettext(" action: The pool can "
2081 "be imported using its name or numeric "
2082 "identifier,\n\thowever there is a compat"
2083 "ibility issue which should be corrected"
2084 "\n\tby running 'zpool scrub'\n"));
2085 break;
2087 case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
2088 (void) printf(gettext(" action: The pool can"
2089 "not be imported with this version of ZFS "
2090 "due to\n\tan active asynchronous destroy. "
2091 "Revert to an earlier version\n\tand "
2092 "allow the destroy to complete before "
2093 "updating.\n"));
2094 break;
2096 default:
2098 * All errata must contain an action message.
2100 assert(0);
2102 } else {
2103 (void) printf(gettext(" action: The pool can be "
2104 "imported using its name or numeric "
2105 "identifier.\n"));
2107 } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
2108 (void) printf(gettext(" action: The pool can be imported "
2109 "despite missing or damaged devices. The\n\tfault "
2110 "tolerance of the pool may be compromised if imported.\n"));
2111 } else {
2112 switch (reason) {
2113 case ZPOOL_STATUS_VERSION_NEWER:
2114 (void) printf(gettext(" action: The pool cannot be "
2115 "imported. Access the pool on a system running "
2116 "newer\n\tsoftware, or recreate the pool from "
2117 "backup.\n"));
2118 break;
2119 case ZPOOL_STATUS_UNSUP_FEAT_READ:
2120 (void) printf(gettext("action: The pool cannot be "
2121 "imported. Access the pool on a system that "
2122 "supports\n\tthe required feature(s), or recreate "
2123 "the pool from backup.\n"));
2124 break;
2125 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2126 (void) printf(gettext("action: The pool cannot be "
2127 "imported in read-write mode. Import the pool "
2128 "with\n"
2129 "\t\"-o readonly=on\", access the pool on a system "
2130 "that supports the\n\trequired feature(s), or "
2131 "recreate the pool from backup.\n"));
2132 break;
2133 case ZPOOL_STATUS_MISSING_DEV_R:
2134 case ZPOOL_STATUS_MISSING_DEV_NR:
2135 case ZPOOL_STATUS_BAD_GUID_SUM:
2136 (void) printf(gettext(" action: The pool cannot be "
2137 "imported. Attach the missing\n\tdevices and try "
2138 "again.\n"));
2139 break;
2140 default:
2141 (void) printf(gettext(" action: The pool cannot be "
2142 "imported due to damaged devices or data.\n"));
2146 /* Print the comment attached to the pool. */
2147 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2148 (void) printf(gettext("comment: %s\n"), comment);
2151 * If the state is "closed" or "can't open", and the aux state
2152 * is "corrupt data":
2154 if (((vs->vs_state == VDEV_STATE_CLOSED) ||
2155 (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
2156 (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
2157 if (pool_state == POOL_STATE_DESTROYED)
2158 (void) printf(gettext("\tThe pool was destroyed, "
2159 "but can be imported using the '-Df' flags.\n"));
2160 else if (pool_state != POOL_STATE_EXPORTED)
2161 (void) printf(gettext("\tThe pool may be active on "
2162 "another system, but can be imported using\n\t"
2163 "the '-f' flag.\n"));
2166 if (msgid != NULL)
2167 (void) printf(gettext(" see: http://zfsonlinux.org/msg/%s\n"),
2168 msgid);
2170 (void) printf(gettext(" config:\n\n"));
2172 cb.cb_namewidth = max_width(NULL, nvroot, 0, 0, VDEV_NAME_TYPE_ID);
2173 if (cb.cb_namewidth < 10)
2174 cb.cb_namewidth = 10;
2176 print_import_config(&cb, name, nvroot, 0);
2177 if (num_logs(nvroot) > 0)
2178 print_logs(NULL, &cb, nvroot);
2180 if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
2181 (void) printf(gettext("\n\tAdditional devices are known to "
2182 "be part of this pool, though their\n\texact "
2183 "configuration cannot be determined.\n"));
2188 * Perform the import for the given configuration. This passes the heavy
2189 * lifting off to zpool_import_props(), and then mounts the datasets contained
2190 * within the pool.
2192 static int
2193 do_import(nvlist_t *config, const char *newname, const char *mntopts,
2194 nvlist_t *props, int flags)
2196 zpool_handle_t *zhp;
2197 char *name;
2198 uint64_t state;
2199 uint64_t version;
2201 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2202 &name) == 0);
2204 verify(nvlist_lookup_uint64(config,
2205 ZPOOL_CONFIG_POOL_STATE, &state) == 0);
2206 verify(nvlist_lookup_uint64(config,
2207 ZPOOL_CONFIG_VERSION, &version) == 0);
2208 if (!SPA_VERSION_IS_SUPPORTED(version)) {
2209 (void) fprintf(stderr, gettext("cannot import '%s': pool "
2210 "is formatted using an unsupported ZFS version\n"), name);
2211 return (1);
2212 } else if (state != POOL_STATE_EXPORTED &&
2213 !(flags & ZFS_IMPORT_ANY_HOST)) {
2214 uint64_t hostid = 0;
2215 unsigned long system_hostid = get_system_hostid();
2217 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
2218 &hostid);
2220 if (hostid != 0 && (unsigned long)hostid != system_hostid) {
2221 char *hostname;
2222 uint64_t timestamp;
2223 time_t t;
2225 verify(nvlist_lookup_string(config,
2226 ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2227 verify(nvlist_lookup_uint64(config,
2228 ZPOOL_CONFIG_TIMESTAMP, &timestamp) == 0);
2229 t = timestamp;
2230 (void) fprintf(stderr, gettext("cannot import "
2231 "'%s': pool may be in use from other "
2232 "system, it was last accessed by %s "
2233 "(hostid: 0x%lx) on %s"), name, hostname,
2234 (unsigned long)hostid,
2235 asctime(localtime(&t)));
2236 (void) fprintf(stderr, gettext("use '-f' to "
2237 "import anyway\n"));
2238 return (1);
2242 if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
2243 return (1);
2245 if (newname != NULL)
2246 name = (char *)newname;
2248 if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
2249 return (1);
2251 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
2252 !(flags & ZFS_IMPORT_ONLY) &&
2253 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
2254 zpool_close(zhp);
2255 return (1);
2258 zpool_close(zhp);
2259 return (0);
2263 * zpool import [-d dir] [-D]
2264 * import [-o mntopts] [-o prop=value] ... [-R root] [-D]
2265 * [-d dir | -c cachefile] [-f] -a
2266 * import [-o mntopts] [-o prop=value] ... [-R root] [-D]
2267 * [-d dir | -c cachefile] [-f] [-n] [-F] <pool | id> [newpool]
2269 * -c Read pool information from a cachefile instead of searching
2270 * devices.
2272 * -d Scan in a specific directory, other than /dev/. More than
2273 * one directory can be specified using multiple '-d' options.
2275 * -D Scan for previously destroyed pools or import all or only
2276 * specified destroyed pools.
2278 * -R Temporarily import the pool, with all mountpoints relative to
2279 * the given root. The pool will remain exported when the machine
2280 * is rebooted.
2282 * -V Import even in the presence of faulted vdevs. This is an
2283 * intentionally undocumented option for testing purposes, and
2284 * treats the pool configuration as complete, leaving any bad
2285 * vdevs in the FAULTED state. In other words, it does verbatim
2286 * import.
2288 * -f Force import, even if it appears that the pool is active.
2290 * -F Attempt rewind if necessary.
2292 * -n See if rewind would work, but don't actually rewind.
2294 * -N Import the pool but don't mount datasets.
2296 * -T Specify a starting txg to use for import. This option is
2297 * intentionally undocumented option for testing purposes.
2299 * -a Import all pools found.
2301 * -o Set property=value and/or temporary mount options (without '=').
2303 * -s Scan using the default search path, the libblkid cache will
2304 * not be consulted.
2306 * The import command scans for pools to import, and import pools based on pool
2307 * name and GUID. The pool can also be renamed as part of the import process.
2310 zpool_do_import(int argc, char **argv)
2312 char **searchdirs = NULL;
2313 char *env, *envdup = NULL;
2314 int nsearch = 0;
2315 int c;
2316 int err = 0;
2317 nvlist_t *pools = NULL;
2318 boolean_t do_all = B_FALSE;
2319 boolean_t do_destroyed = B_FALSE;
2320 char *mntopts = NULL;
2321 nvpair_t *elem;
2322 nvlist_t *config;
2323 uint64_t searchguid = 0;
2324 char *searchname = NULL;
2325 char *propval;
2326 nvlist_t *found_config;
2327 nvlist_t *policy = NULL;
2328 nvlist_t *props = NULL;
2329 boolean_t first;
2330 int flags = ZFS_IMPORT_NORMAL;
2331 uint32_t rewind_policy = ZPOOL_NO_REWIND;
2332 boolean_t dryrun = B_FALSE;
2333 boolean_t do_rewind = B_FALSE;
2334 boolean_t xtreme_rewind = B_FALSE;
2335 boolean_t do_scan = B_FALSE;
2336 uint64_t pool_state, txg = -1ULL;
2337 char *cachefile = NULL;
2338 importargs_t idata = { 0 };
2339 char *endptr;
2341 /* check options */
2342 while ((c = getopt(argc, argv, ":aCc:d:DEfFmnNo:R:stT:VX")) != -1) {
2343 switch (c) {
2344 case 'a':
2345 do_all = B_TRUE;
2346 break;
2347 case 'c':
2348 cachefile = optarg;
2349 break;
2350 case 'd':
2351 if (searchdirs == NULL) {
2352 searchdirs = safe_malloc(sizeof (char *));
2353 } else {
2354 char **tmp = safe_malloc((nsearch + 1) *
2355 sizeof (char *));
2356 bcopy(searchdirs, tmp, nsearch *
2357 sizeof (char *));
2358 free(searchdirs);
2359 searchdirs = tmp;
2361 searchdirs[nsearch++] = optarg;
2362 break;
2363 case 'D':
2364 do_destroyed = B_TRUE;
2365 break;
2366 case 'f':
2367 flags |= ZFS_IMPORT_ANY_HOST;
2368 break;
2369 case 'F':
2370 do_rewind = B_TRUE;
2371 break;
2372 case 'm':
2373 flags |= ZFS_IMPORT_MISSING_LOG;
2374 break;
2375 case 'n':
2376 dryrun = B_TRUE;
2377 break;
2378 case 'N':
2379 flags |= ZFS_IMPORT_ONLY;
2380 break;
2381 case 'o':
2382 if ((propval = strchr(optarg, '=')) != NULL) {
2383 *propval = '\0';
2384 propval++;
2385 if (add_prop_list(optarg, propval,
2386 &props, B_TRUE))
2387 goto error;
2388 } else {
2389 mntopts = optarg;
2391 break;
2392 case 'R':
2393 if (add_prop_list(zpool_prop_to_name(
2394 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
2395 goto error;
2396 if (add_prop_list_default(zpool_prop_to_name(
2397 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
2398 goto error;
2399 break;
2400 case 's':
2401 do_scan = B_TRUE;
2402 break;
2403 case 't':
2404 flags |= ZFS_IMPORT_TEMP_NAME;
2405 if (add_prop_list_default(zpool_prop_to_name(
2406 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
2407 goto error;
2408 break;
2410 case 'T':
2411 errno = 0;
2412 txg = strtoull(optarg, &endptr, 0);
2413 if (errno != 0 || *endptr != '\0') {
2414 (void) fprintf(stderr,
2415 gettext("invalid txg value\n"));
2416 usage(B_FALSE);
2418 rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
2419 break;
2420 case 'V':
2421 flags |= ZFS_IMPORT_VERBATIM;
2422 break;
2423 case 'X':
2424 xtreme_rewind = B_TRUE;
2425 break;
2426 case ':':
2427 (void) fprintf(stderr, gettext("missing argument for "
2428 "'%c' option\n"), optopt);
2429 usage(B_FALSE);
2430 break;
2431 case '?':
2432 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2433 optopt);
2434 usage(B_FALSE);
2438 argc -= optind;
2439 argv += optind;
2441 if (cachefile && nsearch != 0) {
2442 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
2443 usage(B_FALSE);
2446 if ((dryrun || xtreme_rewind) && !do_rewind) {
2447 (void) fprintf(stderr,
2448 gettext("-n or -X only meaningful with -F\n"));
2449 usage(B_FALSE);
2451 if (dryrun)
2452 rewind_policy = ZPOOL_TRY_REWIND;
2453 else if (do_rewind)
2454 rewind_policy = ZPOOL_DO_REWIND;
2455 if (xtreme_rewind)
2456 rewind_policy |= ZPOOL_EXTREME_REWIND;
2458 /* In the future, we can capture further policy and include it here */
2459 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
2460 nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, txg) != 0 ||
2461 nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
2462 goto error;
2464 /* check argument count */
2465 if (do_all) {
2466 if (argc != 0) {
2467 (void) fprintf(stderr, gettext("too many arguments\n"));
2468 usage(B_FALSE);
2470 } else {
2471 if (argc > 2) {
2472 (void) fprintf(stderr, gettext("too many arguments\n"));
2473 usage(B_FALSE);
2478 * Check for the effective uid. We do this explicitly here because
2479 * otherwise any attempt to discover pools will silently fail.
2481 if (argc == 0 && geteuid() != 0) {
2482 (void) fprintf(stderr, gettext("cannot "
2483 "discover pools: permission denied\n"));
2484 if (searchdirs != NULL)
2485 free(searchdirs);
2487 nvlist_free(props);
2488 nvlist_free(policy);
2489 return (1);
2493 * Depending on the arguments given, we do one of the following:
2495 * <none> Iterate through all pools and display information about
2496 * each one.
2498 * -a Iterate through all pools and try to import each one.
2500 * <id> Find the pool that corresponds to the given GUID/pool
2501 * name and import that one.
2503 * -D Above options applies only to destroyed pools.
2505 if (argc != 0) {
2506 char *endptr;
2508 errno = 0;
2509 searchguid = strtoull(argv[0], &endptr, 10);
2510 if (errno != 0 || *endptr != '\0') {
2511 searchname = argv[0];
2512 searchguid = 0;
2514 found_config = NULL;
2517 * User specified a name or guid. Ensure it's unique.
2519 idata.unique = B_TRUE;
2523 * Check the environment for the preferred search path.
2525 if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
2526 char *dir;
2528 envdup = strdup(env);
2530 dir = strtok(envdup, ":");
2531 while (dir != NULL) {
2532 if (searchdirs == NULL) {
2533 searchdirs = safe_malloc(sizeof (char *));
2534 } else {
2535 char **tmp = safe_malloc((nsearch + 1) *
2536 sizeof (char *));
2537 bcopy(searchdirs, tmp, nsearch *
2538 sizeof (char *));
2539 free(searchdirs);
2540 searchdirs = tmp;
2542 searchdirs[nsearch++] = dir;
2543 dir = strtok(NULL, ":");
2547 idata.path = searchdirs;
2548 idata.paths = nsearch;
2549 idata.poolname = searchname;
2550 idata.guid = searchguid;
2551 idata.cachefile = cachefile;
2552 idata.scan = do_scan;
2555 * Under Linux the zpool_find_import_impl() function leverages the
2556 * taskq implementation to parallelize device scanning. It is
2557 * therefore necessary to initialize this functionality for the
2558 * duration of the zpool_search_import() function.
2560 thread_init();
2561 pools = zpool_search_import(g_zfs, &idata);
2562 thread_fini();
2564 if (pools != NULL && idata.exists &&
2565 (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
2566 (void) fprintf(stderr, gettext("cannot import '%s': "
2567 "a pool with that name already exists\n"),
2568 argv[0]);
2569 (void) fprintf(stderr, gettext("use the form '%s "
2570 "<pool | id> <newpool>' to give it a new name\n"),
2571 "zpool import");
2572 err = 1;
2573 } else if (pools == NULL && idata.exists) {
2574 (void) fprintf(stderr, gettext("cannot import '%s': "
2575 "a pool with that name is already created/imported,\n"),
2576 argv[0]);
2577 (void) fprintf(stderr, gettext("and no additional pools "
2578 "with that name were found\n"));
2579 err = 1;
2580 } else if (pools == NULL) {
2581 if (argc != 0) {
2582 (void) fprintf(stderr, gettext("cannot import '%s': "
2583 "no such pool available\n"), argv[0]);
2585 err = 1;
2588 if (err == 1) {
2589 if (searchdirs != NULL)
2590 free(searchdirs);
2591 if (envdup != NULL)
2592 free(envdup);
2593 nvlist_free(policy);
2594 nvlist_free(pools);
2595 nvlist_free(props);
2596 return (1);
2600 * At this point we have a list of import candidate configs. Even if
2601 * we were searching by pool name or guid, we still need to
2602 * post-process the list to deal with pool state and possible
2603 * duplicate names.
2605 err = 0;
2606 elem = NULL;
2607 first = B_TRUE;
2608 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2610 verify(nvpair_value_nvlist(elem, &config) == 0);
2612 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2613 &pool_state) == 0);
2614 if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
2615 continue;
2616 if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
2617 continue;
2619 verify(nvlist_add_nvlist(config, ZPOOL_REWIND_POLICY,
2620 policy) == 0);
2622 if (argc == 0) {
2623 if (first)
2624 first = B_FALSE;
2625 else if (!do_all)
2626 (void) printf("\n");
2628 if (do_all) {
2629 err |= do_import(config, NULL, mntopts,
2630 props, flags);
2631 } else {
2632 show_import(config);
2634 } else if (searchname != NULL) {
2635 char *name;
2638 * We are searching for a pool based on name.
2640 verify(nvlist_lookup_string(config,
2641 ZPOOL_CONFIG_POOL_NAME, &name) == 0);
2643 if (strcmp(name, searchname) == 0) {
2644 if (found_config != NULL) {
2645 (void) fprintf(stderr, gettext(
2646 "cannot import '%s': more than "
2647 "one matching pool\n"), searchname);
2648 (void) fprintf(stderr, gettext(
2649 "import by numeric ID instead\n"));
2650 err = B_TRUE;
2652 found_config = config;
2654 } else {
2655 uint64_t guid;
2658 * Search for a pool by guid.
2660 verify(nvlist_lookup_uint64(config,
2661 ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
2663 if (guid == searchguid)
2664 found_config = config;
2669 * If we were searching for a specific pool, verify that we found a
2670 * pool, and then do the import.
2672 if (argc != 0 && err == 0) {
2673 if (found_config == NULL) {
2674 (void) fprintf(stderr, gettext("cannot import '%s': "
2675 "no such pool available\n"), argv[0]);
2676 err = B_TRUE;
2677 } else {
2678 err |= do_import(found_config, argc == 1 ? NULL :
2679 argv[1], mntopts, props, flags);
2684 * If we were just looking for pools, report an error if none were
2685 * found.
2687 if (argc == 0 && first)
2688 (void) fprintf(stderr,
2689 gettext("no pools available to import\n"));
2691 error:
2692 nvlist_free(props);
2693 nvlist_free(pools);
2694 nvlist_free(policy);
2695 if (searchdirs != NULL)
2696 free(searchdirs);
2697 if (envdup != NULL)
2698 free(envdup);
2700 return (err ? 1 : 0);
2704 * zpool sync [-f] [pool] ...
2706 * -f (undocumented) force uberblock (and config including zpool cache file)
2707 * update.
2709 * Sync the specified pool(s).
2710 * Without arguments "zpool sync" will sync all pools.
2711 * This command initiates TXG sync(s) and will return after the TXG(s) commit.
2714 static int
2715 zpool_do_sync(int argc, char **argv)
2717 int ret;
2718 boolean_t force = B_FALSE;
2720 /* check options */
2721 while ((ret = getopt(argc, argv, "f")) != -1) {
2722 switch (ret) {
2723 case 'f':
2724 force = B_TRUE;
2725 break;
2726 case '?':
2727 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2728 optopt);
2729 usage(B_FALSE);
2733 argc -= optind;
2734 argv += optind;
2736 /* if argc == 0 we will execute zpool_sync_one on all pools */
2737 ret = for_each_pool(argc, argv, B_FALSE, NULL, zpool_sync_one, &force);
2739 return (ret);
2742 typedef struct iostat_cbdata {
2743 uint64_t cb_flags;
2744 int cb_name_flags;
2745 int cb_namewidth;
2746 int cb_iteration;
2747 char **cb_vdev_names; /* Only show these vdevs */
2748 unsigned int cb_vdev_names_count;
2749 boolean_t cb_verbose;
2750 boolean_t cb_literal;
2751 boolean_t cb_scripted;
2752 zpool_list_t *cb_list;
2753 vdev_cmd_data_list_t *vcdl;
2754 } iostat_cbdata_t;
2756 /* iostat labels */
2757 typedef struct name_and_columns {
2758 const char *name; /* Column name */
2759 unsigned int columns; /* Center name to this number of columns */
2760 } name_and_columns_t;
2762 #define IOSTAT_MAX_LABELS 11 /* Max number of labels on one line */
2764 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
2766 [IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
2767 {NULL}},
2768 [IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
2769 {"asyncq_wait", 2}, {"scrub"}},
2770 [IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
2771 {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
2772 {NULL}},
2773 [IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2},
2774 {"sync_queue", 2}, {"async_queue", 2}, {NULL}},
2775 [IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
2776 {"async_read", 2}, {"async_write", 2}, {"scrub", 2}, {NULL}},
2780 /* Shorthand - if "columns" field not set, default to 1 column */
2781 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
2783 [IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
2784 {"write"}, {NULL}},
2785 [IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
2786 {"write"}, {"read"}, {"write"}, {"wait"}, {NULL}},
2787 [IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
2788 {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
2789 [IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
2790 {"write"}, {"read"}, {"write"}, {"scrub"}, {NULL}},
2791 [IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
2792 {"ind"}, {"agg"}, {"ind"}, {"agg"}, {NULL}},
2795 static const char *histo_to_title[] = {
2796 [IOS_L_HISTO] = "latency",
2797 [IOS_RQ_HISTO] = "req_size",
2801 * Return the number of labels in a null-terminated name_and_columns_t
2802 * array.
2805 static unsigned int
2806 label_array_len(const name_and_columns_t *labels)
2808 int i = 0;
2810 while (labels[i].name)
2811 i++;
2813 return (i);
2817 * Return the number of strings in a null-terminated string array.
2818 * For example:
2820 * const char foo[] = {"bar", "baz", NULL}
2822 * returns 2
2824 static uint64_t
2825 str_array_len(const char *array[])
2827 uint64_t i = 0;
2828 while (array[i])
2829 i++;
2831 return (i);
2836 * Return a default column width for default/latency/queue columns. This does
2837 * not include histograms, which have their columns autosized.
2839 static unsigned int
2840 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
2842 unsigned long column_width = 5; /* Normal niceprint */
2843 static unsigned long widths[] = {
2845 * Choose some sane default column sizes for printing the
2846 * raw numbers.
2848 [IOS_DEFAULT] = 15, /* 1PB capacity */
2849 [IOS_LATENCY] = 10, /* 1B ns = 10sec */
2850 [IOS_QUEUES] = 6, /* 1M queue entries */
2853 if (cb->cb_literal)
2854 column_width = widths[type];
2856 return (column_width);
2860 * Print the column labels, i.e:
2862 * capacity operations bandwidth
2863 * alloc free read write read write ...
2865 * If force_column_width is set, use it for the column width. If not set, use
2866 * the default column width.
2868 void
2869 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
2870 const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
2872 int i, idx, s;
2873 unsigned int text_start, rw_column_width, spaces_to_end;
2874 uint64_t flags = cb->cb_flags;
2875 uint64_t f;
2876 unsigned int column_width = force_column_width;
2878 /* For each bit set in flags */
2879 for (f = flags; f; f &= ~(1ULL << idx)) {
2880 idx = lowbit64(f) - 1;
2881 if (!force_column_width)
2882 column_width = default_column_width(cb, idx);
2883 /* Print our top labels centered over "read write" label. */
2884 for (i = 0; i < label_array_len(labels[idx]); i++) {
2885 const char *name = labels[idx][i].name;
2887 * We treat labels[][].columns == 0 as shorthand
2888 * for one column. It makes writing out the label
2889 * tables more concise.
2891 unsigned int columns = MAX(1, labels[idx][i].columns);
2892 unsigned int slen = strlen(name);
2894 rw_column_width = (column_width * columns) +
2895 (2 * (columns - 1));
2897 text_start = (int)((rw_column_width)/columns -
2898 slen/columns);
2900 printf(" "); /* Two spaces between columns */
2902 /* Space from beginning of column to label */
2903 for (s = 0; s < text_start; s++)
2904 printf(" ");
2906 printf("%s", name);
2908 /* Print space after label to end of column */
2909 spaces_to_end = rw_column_width - text_start - slen;
2910 for (s = 0; s < spaces_to_end; s++)
2911 printf(" ");
2919 * print_cmd_columns - Print custom column titles from -c
2921 * If the user specified the "zpool status|iostat -c" then print their custom
2922 * column titles in the header. For example, print_cmd_columns() would print
2923 * the " col1 col2" part of this:
2925 * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
2926 * ...
2927 * capacity operations bandwidth
2928 * pool alloc free read write read write col1 col2
2929 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
2930 * mypool 269K 1008M 0 0 107 946
2931 * mirror 269K 1008M 0 0 107 946
2932 * sdb - - 0 0 102 473 val1 val2
2933 * sdc - - 0 0 5 473 val1 val2
2934 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
2936 void
2937 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
2939 int i, j;
2940 vdev_cmd_data_t *data = &vcdl->data[0];
2942 if (vcdl->count == 0 || data == NULL)
2943 return;
2946 * Each vdev cmd should have the same column names unless the user did
2947 * something weird with their cmd. Just take the column names from the
2948 * first vdev and assume it works for all of them.
2950 for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
2951 printf(" ");
2952 if (use_dashes) {
2953 for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
2954 printf("-");
2955 } else {
2956 printf("%*s", vcdl->uniq_cols_width[i],
2957 vcdl->uniq_cols[i]);
2964 * Utility function to print out a line of dashes like:
2966 * -------------------------------- ----- ----- ----- ----- -----
2968 * ...or a dashed named-row line like:
2970 * logs - - - - -
2972 * @cb: iostat data
2974 * @force_column_width If non-zero, use the value as the column width.
2975 * Otherwise use the default column widths.
2977 * @name: Print a dashed named-row line starting
2978 * with @name. Otherwise, print a regular
2979 * dashed line.
2981 static void
2982 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
2983 const char *name)
2985 int i;
2986 unsigned int namewidth;
2987 uint64_t flags = cb->cb_flags;
2988 uint64_t f;
2989 int idx;
2990 const name_and_columns_t *labels;
2991 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 name ? strlen(name) : 0);
3006 if (name) {
3007 printf("%-*s", namewidth, name);
3008 } else {
3009 for (i = 0; i < namewidth; i++)
3010 (void) printf("-");
3013 /* For each bit in flags */
3014 for (f = flags; f; f &= ~(1ULL << idx)) {
3015 unsigned int column_width;
3016 idx = lowbit64(f) - 1;
3017 if (force_column_width)
3018 column_width = force_column_width;
3019 else
3020 column_width = default_column_width(cb, idx);
3022 labels = iostat_bottom_labels[idx];
3023 for (i = 0; i < label_array_len(labels); i++) {
3024 if (name)
3025 printf(" %*s-", column_width - 1, " ");
3026 else
3027 printf(" %.*s", column_width,
3028 "--------------------");
3034 static void
3035 print_iostat_separator_impl(iostat_cbdata_t *cb,
3036 unsigned int force_column_width)
3038 print_iostat_dashes(cb, force_column_width, NULL);
3041 static void
3042 print_iostat_separator(iostat_cbdata_t *cb)
3044 print_iostat_separator_impl(cb, 0);
3047 static void
3048 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
3049 const char *histo_vdev_name)
3051 unsigned int namewidth;
3052 const char *title;
3054 if (cb->cb_flags & IOS_ANYHISTO_M) {
3055 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
3056 } else if (cb->cb_vdev_names_count) {
3057 title = "vdev";
3058 } else {
3059 title = "pool";
3062 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
3063 histo_vdev_name ? strlen(histo_vdev_name) : 0);
3065 if (histo_vdev_name)
3066 printf("%-*s", namewidth, histo_vdev_name);
3067 else
3068 printf("%*s", namewidth, "");
3071 print_iostat_labels(cb, force_column_width, iostat_top_labels);
3072 printf("\n");
3074 printf("%-*s", namewidth, title);
3076 print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
3077 if (cb->vcdl != NULL)
3078 print_cmd_columns(cb->vcdl, 0);
3080 printf("\n");
3082 print_iostat_separator_impl(cb, force_column_width);
3084 if (cb->vcdl != NULL)
3085 print_cmd_columns(cb->vcdl, 1);
3087 printf("\n");
3090 static void
3091 print_iostat_header(iostat_cbdata_t *cb)
3093 print_iostat_header_impl(cb, 0, NULL);
3098 * Display a single statistic.
3100 static void
3101 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
3102 unsigned int column_size, boolean_t scripted)
3104 char buf[64];
3106 zfs_nicenum_format(value, buf, sizeof (buf), format);
3108 if (scripted)
3109 printf("\t%s", buf);
3110 else
3111 printf(" %*s", column_size, buf);
3115 * Calculate the default vdev stats
3117 * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
3118 * stats into calcvs.
3120 static void
3121 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
3122 vdev_stat_t *calcvs)
3124 int i;
3126 memcpy(calcvs, newvs, sizeof (*calcvs));
3127 for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
3128 calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
3130 for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
3131 calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
3135 * Internal representation of the extended iostats data.
3137 * The extended iostat stats are exported in nvlists as either uint64_t arrays
3138 * or single uint64_t's. We make both look like arrays to make them easier
3139 * to process. In order to make single uint64_t's look like arrays, we set
3140 * __data to the stat data, and then set *data = &__data with count = 1. Then,
3141 * we can just use *data and count.
3143 struct stat_array {
3144 uint64_t *data;
3145 uint_t count; /* Number of entries in data[] */
3146 uint64_t __data; /* Only used when data is a single uint64_t */
3149 static uint64_t
3150 stat_histo_max(struct stat_array *nva, unsigned int len)
3152 uint64_t max = 0;
3153 int i;
3154 for (i = 0; i < len; i++)
3155 max = MAX(max, array64_max(nva[i].data, nva[i].count));
3157 return (max);
3161 * Helper function to lookup a uint64_t array or uint64_t value and store its
3162 * data as a stat_array. If the nvpair is a single uint64_t value, then we make
3163 * it look like a one element array to make it easier to process.
3165 static int
3166 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
3167 struct stat_array *nva)
3169 nvpair_t *tmp;
3170 int ret;
3172 verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
3173 switch (nvpair_type(tmp)) {
3174 case DATA_TYPE_UINT64_ARRAY:
3175 ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
3176 break;
3177 case DATA_TYPE_UINT64:
3178 ret = nvpair_value_uint64(tmp, &nva->__data);
3179 nva->data = &nva->__data;
3180 nva->count = 1;
3181 break;
3182 default:
3183 /* Not a uint64_t */
3184 ret = EINVAL;
3185 break;
3188 return (ret);
3192 * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
3193 * subtract them, and return the results in a newly allocated stat_array.
3194 * You must free the returned array after you are done with it with
3195 * free_calc_stats().
3197 * Additionally, you can set "oldnv" to NULL if you simply want the newnv
3198 * values.
3200 static struct stat_array *
3201 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
3202 nvlist_t *newnv)
3204 nvlist_t *oldnvx = NULL, *newnvx;
3205 struct stat_array *oldnva, *newnva, *calcnva;
3206 int i, j;
3207 unsigned int alloc_size = (sizeof (struct stat_array)) * len;
3209 /* Extract our extended stats nvlist from the main list */
3210 verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
3211 &newnvx) == 0);
3212 if (oldnv) {
3213 verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
3214 &oldnvx) == 0);
3217 newnva = safe_malloc(alloc_size);
3218 oldnva = safe_malloc(alloc_size);
3219 calcnva = safe_malloc(alloc_size);
3221 for (j = 0; j < len; j++) {
3222 verify(nvpair64_to_stat_array(newnvx, names[j],
3223 &newnva[j]) == 0);
3224 calcnva[j].count = newnva[j].count;
3225 alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
3226 calcnva[j].data = safe_malloc(alloc_size);
3227 memcpy(calcnva[j].data, newnva[j].data, alloc_size);
3229 if (oldnvx) {
3230 verify(nvpair64_to_stat_array(oldnvx, names[j],
3231 &oldnva[j]) == 0);
3232 for (i = 0; i < oldnva[j].count; i++)
3233 calcnva[j].data[i] -= oldnva[j].data[i];
3236 free(newnva);
3237 free(oldnva);
3238 return (calcnva);
3241 static void
3242 free_calc_stats(struct stat_array *nva, unsigned int len)
3244 int i;
3245 for (i = 0; i < len; i++)
3246 free(nva[i].data);
3248 free(nva);
3251 static void
3252 print_iostat_histo(struct stat_array *nva, unsigned int len,
3253 iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
3254 double scale)
3256 int i, j;
3257 char buf[6];
3258 uint64_t val;
3259 enum zfs_nicenum_format format;
3260 unsigned int buckets;
3261 unsigned int start_bucket;
3263 if (cb->cb_literal)
3264 format = ZFS_NICENUM_RAW;
3265 else
3266 format = ZFS_NICENUM_1024;
3268 /* All these histos are the same size, so just use nva[0].count */
3269 buckets = nva[0].count;
3271 if (cb->cb_flags & IOS_RQ_HISTO_M) {
3272 /* Start at 512 - req size should never be lower than this */
3273 start_bucket = 9;
3274 } else {
3275 start_bucket = 0;
3278 for (j = start_bucket; j < buckets; j++) {
3279 /* Print histogram bucket label */
3280 if (cb->cb_flags & IOS_L_HISTO_M) {
3281 /* Ending range of this bucket */
3282 val = (1UL << (j + 1)) - 1;
3283 zfs_nicetime(val, buf, sizeof (buf));
3284 } else {
3285 /* Request size (starting range of bucket) */
3286 val = (1UL << j);
3287 zfs_nicenum(val, buf, sizeof (buf));
3290 if (cb->cb_scripted)
3291 printf("%llu", (u_longlong_t)val);
3292 else
3293 printf("%-*s", namewidth, buf);
3295 /* Print the values on the line */
3296 for (i = 0; i < len; i++) {
3297 print_one_stat(nva[i].data[j] * scale, format,
3298 column_width, cb->cb_scripted);
3300 printf("\n");
3304 static void
3305 print_solid_separator(unsigned int length)
3307 while (length--)
3308 printf("-");
3309 printf("\n");
3312 static void
3313 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
3314 nvlist_t *newnv, double scale, const char *name)
3316 unsigned int column_width;
3317 unsigned int namewidth;
3318 unsigned int entire_width;
3319 enum iostat_type type;
3320 struct stat_array *nva;
3321 const char **names;
3322 unsigned int names_len;
3324 /* What type of histo are we? */
3325 type = IOS_HISTO_IDX(cb->cb_flags);
3327 /* Get NULL-terminated array of nvlist names for our histo */
3328 names = vsx_type_to_nvlist[type];
3329 names_len = str_array_len(names); /* num of names */
3331 nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
3333 if (cb->cb_literal) {
3334 column_width = MAX(5,
3335 (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
3336 } else {
3337 column_width = 5;
3340 namewidth = MAX(cb->cb_namewidth,
3341 strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
3344 * Calculate the entire line width of what we're printing. The
3345 * +2 is for the two spaces between columns:
3347 /* read write */
3348 /* ----- ----- */
3349 /* |___| <---------- column_width */
3350 /* */
3351 /* |__________| <--- entire_width */
3352 /* */
3353 entire_width = namewidth + (column_width + 2) *
3354 label_array_len(iostat_bottom_labels[type]);
3356 if (cb->cb_scripted)
3357 printf("%s\n", name);
3358 else
3359 print_iostat_header_impl(cb, column_width, name);
3361 print_iostat_histo(nva, names_len, cb, column_width,
3362 namewidth, scale);
3364 free_calc_stats(nva, names_len);
3365 if (!cb->cb_scripted)
3366 print_solid_separator(entire_width);
3370 * Calculate the average latency of a power-of-two latency histogram
3372 static uint64_t
3373 single_histo_average(uint64_t *histo, unsigned int buckets)
3375 int i;
3376 uint64_t count = 0, total = 0;
3378 for (i = 0; i < buckets; i++) {
3380 * Our buckets are power-of-two latency ranges. Use the
3381 * midpoint latency of each bucket to calculate the average.
3382 * For example:
3384 * Bucket Midpoint
3385 * 8ns-15ns: 12ns
3386 * 16ns-31ns: 24ns
3387 * ...
3389 if (histo[i] != 0) {
3390 total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
3391 count += histo[i];
3395 /* Prevent divide by zero */
3396 return (count == 0 ? 0 : total / count);
3399 static void
3400 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *oldnv,
3401 nvlist_t *newnv, double scale)
3403 int i;
3404 uint64_t val;
3405 const char *names[] = {
3406 ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
3407 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
3408 ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
3409 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
3410 ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
3411 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
3412 ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
3413 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
3414 ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
3415 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
3418 struct stat_array *nva;
3420 unsigned int column_width = default_column_width(cb, IOS_QUEUES);
3421 enum zfs_nicenum_format format;
3423 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
3425 if (cb->cb_literal)
3426 format = ZFS_NICENUM_RAW;
3427 else
3428 format = ZFS_NICENUM_1024;
3430 for (i = 0; i < ARRAY_SIZE(names); i++) {
3431 val = nva[i].data[0] * scale;
3432 print_one_stat(val, format, column_width, cb->cb_scripted);
3435 free_calc_stats(nva, ARRAY_SIZE(names));
3438 static void
3439 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
3440 nvlist_t *newnv, double scale)
3442 int i;
3443 uint64_t val;
3444 const char *names[] = {
3445 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
3446 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
3447 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
3448 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
3449 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
3450 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
3451 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
3452 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
3453 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
3455 struct stat_array *nva;
3457 unsigned int column_width = default_column_width(cb, IOS_LATENCY);
3458 enum zfs_nicenum_format format;
3460 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
3462 if (cb->cb_literal)
3463 format = ZFS_NICENUM_RAW;
3464 else
3465 format = ZFS_NICENUM_TIME;
3467 /* Print our avg latencies on the line */
3468 for (i = 0; i < ARRAY_SIZE(names); i++) {
3469 /* Compute average latency for a latency histo */
3470 val = single_histo_average(nva[i].data, nva[i].count) * scale;
3471 print_one_stat(val, format, column_width, cb->cb_scripted);
3473 free_calc_stats(nva, ARRAY_SIZE(names));
3477 * Print default statistics (capacity/operations/bandwidth)
3479 static void
3480 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
3482 unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
3483 enum zfs_nicenum_format format;
3484 char na; /* char to print for "not applicable" values */
3486 if (cb->cb_literal) {
3487 format = ZFS_NICENUM_RAW;
3488 na = '0';
3489 } else {
3490 format = ZFS_NICENUM_1024;
3491 na = '-';
3494 /* only toplevel vdevs have capacity stats */
3495 if (vs->vs_space == 0) {
3496 if (cb->cb_scripted)
3497 printf("\t%c\t%c", na, na);
3498 else
3499 printf(" %*c %*c", column_width, na, column_width,
3500 na);
3501 } else {
3502 print_one_stat(vs->vs_alloc, format, column_width,
3503 cb->cb_scripted);
3504 print_one_stat(vs->vs_space - vs->vs_alloc, format,
3505 column_width, cb->cb_scripted);
3508 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
3509 format, column_width, cb->cb_scripted);
3510 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
3511 format, column_width, cb->cb_scripted);
3512 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
3513 format, column_width, cb->cb_scripted);
3514 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
3515 format, column_width, cb->cb_scripted);
3519 * Print out all the statistics for the given vdev. This can either be the
3520 * toplevel configuration, or called recursively. If 'name' is NULL, then this
3521 * is a verbose output, and we don't want to display the toplevel pool stats.
3523 * Returns the number of stat lines printed.
3525 unsigned int
3526 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
3527 nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
3529 nvlist_t **oldchild, **newchild;
3530 uint_t c, children;
3531 vdev_stat_t *oldvs, *newvs, *calcvs;
3532 vdev_stat_t zerovs = { 0 };
3533 char *vname;
3534 int i;
3535 int ret = 0;
3536 uint64_t tdelta;
3537 double scale;
3539 calcvs = safe_malloc(sizeof (*calcvs));
3541 if (oldnv != NULL) {
3542 verify(nvlist_lookup_uint64_array(oldnv,
3543 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
3544 } else {
3545 oldvs = &zerovs;
3548 /* Do we only want to see a specific vdev? */
3549 for (i = 0; i < cb->cb_vdev_names_count; i++) {
3550 /* Yes we do. Is this the vdev? */
3551 if (strcmp(name, cb->cb_vdev_names[i]) == 0) {
3553 * This is our vdev. Since it is the only vdev we
3554 * will be displaying, make depth = 0 so that it
3555 * doesn't get indented.
3557 depth = 0;
3558 break;
3562 if (cb->cb_vdev_names_count && (i == cb->cb_vdev_names_count)) {
3563 /* Couldn't match the name */
3564 goto children;
3568 verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
3569 (uint64_t **)&newvs, &c) == 0);
3572 * Print the vdev name unless it's is a histogram. Histograms
3573 * display the vdev name in the header itself.
3575 if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
3576 if (cb->cb_scripted) {
3577 printf("%s", name);
3578 } else {
3579 if (strlen(name) + depth > cb->cb_namewidth)
3580 (void) printf("%*s%s", depth, "", name);
3581 else
3582 (void) printf("%*s%s%*s", depth, "", name,
3583 (int)(cb->cb_namewidth - strlen(name) -
3584 depth), "");
3588 /* Calculate our scaling factor */
3589 tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
3590 if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
3592 * If we specify printing histograms with no time interval, then
3593 * print the histogram numbers over the entire lifetime of the
3594 * vdev.
3596 scale = 1;
3597 } else {
3598 if (tdelta == 0)
3599 scale = 1.0;
3600 else
3601 scale = (double)NANOSEC / tdelta;
3604 if (cb->cb_flags & IOS_DEFAULT_M) {
3605 calc_default_iostats(oldvs, newvs, calcvs);
3606 print_iostat_default(calcvs, cb, scale);
3608 if (cb->cb_flags & IOS_LATENCY_M)
3609 print_iostat_latency(cb, oldnv, newnv, scale);
3610 if (cb->cb_flags & IOS_QUEUES_M)
3611 print_iostat_queues(cb, oldnv, newnv, scale);
3612 if (cb->cb_flags & IOS_ANYHISTO_M) {
3613 printf("\n");
3614 print_iostat_histos(cb, oldnv, newnv, scale, name);
3617 if (cb->vcdl != NULL) {
3618 char *path;
3619 if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
3620 &path) == 0) {
3621 printf(" ");
3622 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
3626 if (!(cb->cb_flags & IOS_ANYHISTO_M))
3627 printf("\n");
3629 ret++;
3631 children:
3633 free(calcvs);
3635 if (!cb->cb_verbose)
3636 return (ret);
3638 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
3639 &newchild, &children) != 0)
3640 return (ret);
3642 if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
3643 &oldchild, &c) != 0)
3644 return (ret);
3646 for (c = 0; c < children; c++) {
3647 uint64_t ishole = B_FALSE, islog = B_FALSE;
3649 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
3650 &ishole);
3652 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
3653 &islog);
3655 if (ishole || islog)
3656 continue;
3658 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3659 cb->cb_name_flags);
3660 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
3661 newchild[c], cb, depth + 2);
3662 free(vname);
3666 * Log device section
3669 if (num_logs(newnv) > 0) {
3670 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
3671 !cb->cb_vdev_names) {
3672 print_iostat_dashes(cb, 0, "logs");
3674 printf("\n");
3676 for (c = 0; c < children; c++) {
3677 uint64_t islog = B_FALSE;
3678 (void) nvlist_lookup_uint64(newchild[c],
3679 ZPOOL_CONFIG_IS_LOG, &islog);
3681 if (islog) {
3682 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3683 cb->cb_name_flags);
3684 ret += print_vdev_stats(zhp, vname, oldnv ?
3685 oldchild[c] : NULL, newchild[c],
3686 cb, depth + 2);
3687 free(vname);
3694 * Include level 2 ARC devices in iostat output
3696 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
3697 &newchild, &children) != 0)
3698 return (ret);
3700 if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
3701 &oldchild, &c) != 0)
3702 return (ret);
3704 if (children > 0) {
3705 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
3706 !cb->cb_vdev_names) {
3707 print_iostat_dashes(cb, 0, "cache");
3709 printf("\n");
3711 for (c = 0; c < children; c++) {
3712 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3713 cb->cb_name_flags);
3714 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
3715 : NULL, newchild[c], cb, depth + 2);
3716 free(vname);
3720 return (ret);
3723 static int
3724 refresh_iostat(zpool_handle_t *zhp, void *data)
3726 iostat_cbdata_t *cb = data;
3727 boolean_t missing;
3730 * If the pool has disappeared, remove it from the list and continue.
3732 if (zpool_refresh_stats(zhp, &missing) != 0)
3733 return (-1);
3735 if (missing)
3736 pool_list_remove(cb->cb_list, zhp);
3738 return (0);
3742 * Callback to print out the iostats for the given pool.
3745 print_iostat(zpool_handle_t *zhp, void *data)
3747 iostat_cbdata_t *cb = data;
3748 nvlist_t *oldconfig, *newconfig;
3749 nvlist_t *oldnvroot, *newnvroot;
3750 int ret;
3752 newconfig = zpool_get_config(zhp, &oldconfig);
3754 if (cb->cb_iteration == 1)
3755 oldconfig = NULL;
3757 verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
3758 &newnvroot) == 0);
3760 if (oldconfig == NULL)
3761 oldnvroot = NULL;
3762 else
3763 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
3764 &oldnvroot) == 0);
3766 ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
3767 cb, 0);
3768 if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
3769 !cb->cb_scripted && cb->cb_verbose && !cb->cb_vdev_names_count) {
3770 print_iostat_separator(cb);
3771 if (cb->vcdl != NULL) {
3772 print_cmd_columns(cb->vcdl, 1);
3774 printf("\n");
3777 return (ret);
3780 static int
3781 get_columns(void)
3783 struct winsize ws;
3784 int columns = 80;
3785 int error;
3787 if (isatty(STDOUT_FILENO)) {
3788 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
3789 if (error == 0)
3790 columns = ws.ws_col;
3791 } else {
3792 columns = 999;
3795 return (columns);
3799 get_namewidth(zpool_handle_t *zhp, void *data)
3801 iostat_cbdata_t *cb = data;
3802 nvlist_t *config, *nvroot;
3803 int columns;
3805 if ((config = zpool_get_config(zhp, NULL)) != NULL) {
3806 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3807 &nvroot) == 0);
3808 unsigned int poolname_len = strlen(zpool_get_name(zhp));
3809 if (!cb->cb_verbose)
3810 cb->cb_namewidth = poolname_len;
3811 else
3812 cb->cb_namewidth = MAX(poolname_len,
3813 max_width(zhp, nvroot, 0, cb->cb_namewidth,
3814 cb->cb_name_flags));
3817 * The width must be at least 10, but may be as large as the
3818 * column width - 42 so that we can still fit in one line.
3820 columns = get_columns();
3822 if (cb->cb_namewidth < 10)
3823 cb->cb_namewidth = 10;
3824 if (cb->cb_namewidth > columns - 42)
3825 cb->cb_namewidth = columns - 42;
3827 return (0);
3831 * Parse the input string, get the 'interval' and 'count' value if there is one.
3833 static void
3834 get_interval_count(int *argcp, char **argv, float *iv,
3835 unsigned long *cnt)
3837 float interval = 0;
3838 unsigned long count = 0;
3839 int argc = *argcp;
3842 * Determine if the last argument is an integer or a pool name
3844 if (argc > 0 && isnumber(argv[argc - 1])) {
3845 char *end;
3847 errno = 0;
3848 interval = strtof(argv[argc - 1], &end);
3850 if (*end == '\0' && errno == 0) {
3851 if (interval == 0) {
3852 (void) fprintf(stderr, gettext("interval "
3853 "cannot be zero\n"));
3854 usage(B_FALSE);
3857 * Ignore the last parameter
3859 argc--;
3860 } else {
3862 * If this is not a valid number, just plow on. The
3863 * user will get a more informative error message later
3864 * on.
3866 interval = 0;
3871 * If the last argument is also an integer, then we have both a count
3872 * and an interval.
3874 if (argc > 0 && isnumber(argv[argc - 1])) {
3875 char *end;
3877 errno = 0;
3878 count = interval;
3879 interval = strtof(argv[argc - 1], &end);
3881 if (*end == '\0' && errno == 0) {
3882 if (interval == 0) {
3883 (void) fprintf(stderr, gettext("interval "
3884 "cannot be zero\n"));
3885 usage(B_FALSE);
3889 * Ignore the last parameter
3891 argc--;
3892 } else {
3893 interval = 0;
3897 *iv = interval;
3898 *cnt = count;
3899 *argcp = argc;
3902 static void
3903 get_timestamp_arg(char c)
3905 if (c == 'u')
3906 timestamp_fmt = UDATE;
3907 else if (c == 'd')
3908 timestamp_fmt = DDATE;
3909 else
3910 usage(B_FALSE);
3914 * Return stat flags that are supported by all pools by both the module and
3915 * zpool iostat. "*data" should be initialized to all 0xFFs before running.
3916 * It will get ANDed down until only the flags that are supported on all pools
3917 * remain.
3919 static int
3920 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
3922 uint64_t *mask = data;
3923 nvlist_t *config, *nvroot, *nvx;
3924 uint64_t flags = 0;
3925 int i, j;
3927 config = zpool_get_config(zhp, NULL);
3928 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3929 &nvroot) == 0);
3931 /* Default stats are always supported, but for completeness.. */
3932 if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
3933 flags |= IOS_DEFAULT_M;
3935 /* Get our extended stats nvlist from the main list */
3936 if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
3937 &nvx) != 0) {
3939 * No extended stats; they're probably running an older
3940 * module. No big deal, we support that too.
3942 goto end;
3945 /* For each extended stat, make sure all its nvpairs are supported */
3946 for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
3947 if (!vsx_type_to_nvlist[j][0])
3948 continue;
3950 /* Start off by assuming the flag is supported, then check */
3951 flags |= (1ULL << j);
3952 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
3953 if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
3954 /* flag isn't supported */
3955 flags = flags & ~(1ULL << j);
3956 break;
3960 end:
3961 *mask = *mask & flags;
3962 return (0);
3966 * Return a bitmask of stats that are supported on all pools by both the module
3967 * and zpool iostat.
3969 static uint64_t
3970 get_stat_flags(zpool_list_t *list)
3972 uint64_t mask = -1;
3975 * get_stat_flags_cb() will lop off bits from "mask" until only the
3976 * flags that are supported on all pools remain.
3978 pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
3979 return (mask);
3983 * Return 1 if cb_data->cb_vdev_names[0] is this vdev's name, 0 otherwise.
3985 static int
3986 is_vdev_cb(zpool_handle_t *zhp, nvlist_t *nv, void *cb_data)
3988 iostat_cbdata_t *cb = cb_data;
3989 char *name = NULL;
3990 int ret = 0;
3992 name = zpool_vdev_name(g_zfs, zhp, nv, cb->cb_name_flags);
3994 if (strcmp(name, cb->cb_vdev_names[0]) == 0)
3995 ret = 1; /* match */
3996 free(name);
3998 return (ret);
4002 * Returns 1 if cb_data->cb_vdev_names[0] is a vdev name, 0 otherwise.
4004 static int
4005 is_vdev(zpool_handle_t *zhp, void *cb_data)
4007 return (for_each_vdev(zhp, is_vdev_cb, cb_data));
4011 * Check if vdevs are in a pool
4013 * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
4014 * return 0. If pool_name is NULL, then search all pools.
4016 static int
4017 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
4018 iostat_cbdata_t *cb)
4020 char **tmp_name;
4021 int ret = 0;
4022 int i;
4023 int pool_count = 0;
4025 if ((argc == 0) || !*argv)
4026 return (0);
4028 if (pool_name)
4029 pool_count = 1;
4031 /* Temporarily hijack cb_vdev_names for a second... */
4032 tmp_name = cb->cb_vdev_names;
4034 /* Go though our list of prospective vdev names */
4035 for (i = 0; i < argc; i++) {
4036 cb->cb_vdev_names = argv + i;
4038 /* Is this name a vdev in our pools? */
4039 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
4040 is_vdev, cb);
4041 if (!ret) {
4042 /* No match */
4043 break;
4047 cb->cb_vdev_names = tmp_name;
4049 return (ret);
4052 static int
4053 is_pool_cb(zpool_handle_t *zhp, void *data)
4055 char *name = data;
4056 if (strcmp(name, zpool_get_name(zhp)) == 0)
4057 return (1);
4059 return (0);
4063 * Do we have a pool named *name? If so, return 1, otherwise 0.
4065 static int
4066 is_pool(char *name)
4068 return (for_each_pool(0, NULL, B_TRUE, NULL, is_pool_cb, name));
4071 /* Are all our argv[] strings pool names? If so return 1, 0 otherwise. */
4072 static int
4073 are_all_pools(int argc, char **argv)
4075 if ((argc == 0) || !*argv)
4076 return (0);
4078 while (--argc >= 0)
4079 if (!is_pool(argv[argc]))
4080 return (0);
4082 return (1);
4086 * Helper function to print out vdev/pool names we can't resolve. Used for an
4087 * error message.
4089 static void
4090 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
4091 iostat_cbdata_t *cb)
4093 int i;
4094 char *name;
4095 char *str;
4096 for (i = 0; i < argc; i++) {
4097 name = argv[i];
4099 if (is_pool(name))
4100 str = gettext("pool");
4101 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
4102 str = gettext("vdev in this pool");
4103 else if (are_vdevs_in_pool(1, &name, NULL, cb))
4104 str = gettext("vdev in another pool");
4105 else
4106 str = gettext("unknown");
4108 fprintf(stderr, "\t%s (%s)\n", name, str);
4113 * Same as get_interval_count(), but with additional checks to not misinterpret
4114 * guids as interval/count values. Assumes VDEV_NAME_GUID is set in
4115 * cb.cb_name_flags.
4117 static void
4118 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
4119 unsigned long *count, iostat_cbdata_t *cb)
4121 char **tmpargv = argv;
4122 int argc_for_interval = 0;
4124 /* Is the last arg an interval value? Or a guid? */
4125 if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL, cb)) {
4127 * The last arg is not a guid, so it's probably an
4128 * interval value.
4130 argc_for_interval++;
4132 if (*argc >= 2 &&
4133 !are_vdevs_in_pool(1, &argv[*argc - 2], NULL, cb)) {
4135 * The 2nd to last arg is not a guid, so it's probably
4136 * an interval value.
4138 argc_for_interval++;
4142 /* Point to our list of possible intervals */
4143 tmpargv = &argv[*argc - argc_for_interval];
4145 *argc = *argc - argc_for_interval;
4146 get_interval_count(&argc_for_interval, tmpargv,
4147 interval, count);
4151 * Floating point sleep(). Allows you to pass in a floating point value for
4152 * seconds.
4154 static void
4155 fsleep(float sec)
4157 struct timespec req;
4158 req.tv_sec = floor(sec);
4159 req.tv_nsec = (sec - (float)req.tv_sec) * NANOSEC;
4160 nanosleep(&req, NULL);
4164 * Run one of the zpool status/iostat -c scripts with the help (-h) option and
4165 * print the result.
4167 * name: Short name of the script ('iostat').
4168 * path: Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
4170 static void
4171 print_zpool_script_help(char *name, char *path)
4173 char *argv[] = {path, "-h", NULL};
4174 char **lines = NULL;
4175 int lines_cnt = 0;
4176 int rc;
4178 rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
4179 &lines_cnt);
4180 if (rc != 0 || lines == NULL || lines_cnt <= 0) {
4181 if (lines != NULL)
4182 libzfs_free_str_array(lines, lines_cnt);
4183 return;
4186 for (int i = 0; i < lines_cnt; i++)
4187 if (!is_blank_str(lines[i]))
4188 printf(" %-14s %s\n", name, lines[i]);
4190 libzfs_free_str_array(lines, lines_cnt);
4195 * Go though the list of all the zpool status/iostat -c scripts, run their
4196 * help option (-h), and print out the results.
4198 static void
4199 print_zpool_script_list(void)
4201 DIR *dir;
4202 struct dirent *ent;
4203 char fullpath[MAXPATHLEN];
4204 struct stat dir_stat;
4206 if ((dir = opendir(ZPOOL_SCRIPTS_DIR)) != NULL) {
4207 printf("\n");
4208 /* print all the files and directories within directory */
4209 while ((ent = readdir(dir)) != NULL) {
4210 sprintf(fullpath, "%s/%s", ZPOOL_SCRIPTS_DIR,
4211 ent->d_name);
4213 /* Print the scripts */
4214 if (stat(fullpath, &dir_stat) == 0)
4215 if (dir_stat.st_mode & S_IXUSR &&
4216 S_ISREG(dir_stat.st_mode))
4217 print_zpool_script_help(ent->d_name,
4218 fullpath);
4220 printf("\n");
4221 closedir(dir);
4222 } else {
4223 fprintf(stderr, gettext("Can't open %s scripts dir\n"),
4224 ZPOOL_SCRIPTS_DIR);
4229 * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
4230 * [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
4231 * [interval [count]]
4233 * -c CMD For each vdev, run command CMD
4234 * -g Display guid for individual vdev name.
4235 * -L Follow links when resolving vdev path name.
4236 * -P Display full path for vdev name.
4237 * -v Display statistics for individual vdevs
4238 * -h Display help
4239 * -p Display values in parsable (exact) format.
4240 * -H Scripted mode. Don't display headers, and separate properties
4241 * by a single tab.
4242 * -l Display average latency
4243 * -q Display queue depths
4244 * -w Display latency histograms
4245 * -r Display request size histogram
4246 * -T Display a timestamp in date(1) or Unix format
4248 * This command can be tricky because we want to be able to deal with pool
4249 * creation/destruction as well as vdev configuration changes. The bulk of this
4250 * processing is handled by the pool_list_* routines in zpool_iter.c. We rely
4251 * on pool_list_update() to detect the addition of new pools. Configuration
4252 * changes are all handled within libzfs.
4255 zpool_do_iostat(int argc, char **argv)
4257 int c;
4258 int ret;
4259 int npools;
4260 float interval = 0;
4261 unsigned long count = 0;
4262 zpool_list_t *list;
4263 boolean_t verbose = B_FALSE;
4264 boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
4265 boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
4266 boolean_t omit_since_boot = B_FALSE;
4267 boolean_t guid = B_FALSE;
4268 boolean_t follow_links = B_FALSE;
4269 boolean_t full_name = B_FALSE;
4270 iostat_cbdata_t cb = { 0 };
4271 char *cmd = NULL;
4273 /* Used for printing error message */
4274 const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
4275 [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
4277 uint64_t unsupported_flags;
4279 /* check options */
4280 while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwH")) != -1) {
4281 switch (c) {
4282 case 'c':
4283 if (cmd != NULL) {
4284 fprintf(stderr,
4285 gettext("Can't set -c flag twice\n"));
4286 exit(1);
4288 if ((getuid() <= 0 || geteuid() <= 0) &&
4289 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
4290 fprintf(stderr, gettext(
4291 "Can't run -c with root privileges "
4292 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
4293 exit(1);
4295 cmd = optarg;
4296 verbose = B_TRUE;
4297 break;
4298 case 'g':
4299 guid = B_TRUE;
4300 break;
4301 case 'L':
4302 follow_links = B_TRUE;
4303 break;
4304 case 'P':
4305 full_name = B_TRUE;
4306 break;
4307 case 'T':
4308 get_timestamp_arg(*optarg);
4309 break;
4310 case 'v':
4311 verbose = B_TRUE;
4312 break;
4313 case 'p':
4314 parsable = B_TRUE;
4315 break;
4316 case 'l':
4317 latency = B_TRUE;
4318 break;
4319 case 'q':
4320 queues = B_TRUE;
4321 break;
4322 case 'H':
4323 scripted = B_TRUE;
4324 break;
4325 case 'w':
4326 l_histo = B_TRUE;
4327 break;
4328 case 'r':
4329 rq_histo = B_TRUE;
4330 break;
4331 case 'y':
4332 omit_since_boot = B_TRUE;
4333 break;
4334 case 'h':
4335 usage(B_FALSE);
4336 break;
4337 case '?':
4338 if (optopt == 'c') {
4339 fprintf(stderr, gettext(
4340 "Current scripts in %s:\n"),
4341 ZPOOL_SCRIPTS_DIR);
4342 print_zpool_script_list();
4343 exit(0);
4344 } else {
4345 fprintf(stderr,
4346 gettext("invalid option '%c'\n"), optopt);
4348 usage(B_FALSE);
4352 argc -= optind;
4353 argv += optind;
4355 cb.cb_literal = parsable;
4356 cb.cb_scripted = scripted;
4358 if (guid)
4359 cb.cb_name_flags |= VDEV_NAME_GUID;
4360 if (follow_links)
4361 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
4362 if (full_name)
4363 cb.cb_name_flags |= VDEV_NAME_PATH;
4364 cb.cb_iteration = 0;
4365 cb.cb_namewidth = 0;
4366 cb.cb_verbose = verbose;
4368 /* Get our interval and count values (if any) */
4369 if (guid) {
4370 get_interval_count_filter_guids(&argc, argv, &interval,
4371 &count, &cb);
4372 } else {
4373 get_interval_count(&argc, argv, &interval, &count);
4376 if (argc == 0) {
4377 /* No args, so just print the defaults. */
4378 } else if (are_all_pools(argc, argv)) {
4379 /* All the args are pool names */
4380 } else if (are_vdevs_in_pool(argc, argv, NULL, &cb)) {
4381 /* All the args are vdevs */
4382 cb.cb_vdev_names = argv;
4383 cb.cb_vdev_names_count = argc;
4384 argc = 0; /* No pools to process */
4385 } else if (are_all_pools(1, argv)) {
4386 /* The first arg is a pool name */
4387 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0], &cb)) {
4388 /* ...and the rest are vdev names */
4389 cb.cb_vdev_names = argv + 1;
4390 cb.cb_vdev_names_count = argc - 1;
4391 argc = 1; /* One pool to process */
4392 } else {
4393 fprintf(stderr, gettext("Expected either a list of "));
4394 fprintf(stderr, gettext("pools, or list of vdevs in"));
4395 fprintf(stderr, " \"%s\", ", argv[0]);
4396 fprintf(stderr, gettext("but got:\n"));
4397 error_list_unresolved_vdevs(argc - 1, argv + 1,
4398 argv[0], &cb);
4399 fprintf(stderr, "\n");
4400 usage(B_FALSE);
4401 return (1);
4403 } else {
4405 * The args don't make sense. The first arg isn't a pool name,
4406 * nor are all the args vdevs.
4408 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
4409 fprintf(stderr, "\n");
4410 return (1);
4413 if (cb.cb_vdev_names_count != 0) {
4415 * If user specified vdevs, it implies verbose.
4417 cb.cb_verbose = B_TRUE;
4421 * Construct the list of all interesting pools.
4423 ret = 0;
4424 if ((list = pool_list_get(argc, argv, NULL, &ret)) == NULL)
4425 return (1);
4427 if (pool_list_count(list) == 0 && argc != 0) {
4428 pool_list_free(list);
4429 return (1);
4432 if (pool_list_count(list) == 0 && interval == 0) {
4433 pool_list_free(list);
4434 (void) fprintf(stderr, gettext("no pools available\n"));
4435 return (1);
4438 if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
4439 pool_list_free(list);
4440 (void) fprintf(stderr,
4441 gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
4442 usage(B_FALSE);
4443 return (1);
4446 if (l_histo && rq_histo) {
4447 pool_list_free(list);
4448 (void) fprintf(stderr,
4449 gettext("Only one of [-r|-w] can be passed at a time\n"));
4450 usage(B_FALSE);
4451 return (1);
4455 * Enter the main iostat loop.
4457 cb.cb_list = list;
4459 if (l_histo) {
4461 * Histograms tables look out of place when you try to display
4462 * them with the other stats, so make a rule that you can only
4463 * print histograms by themselves.
4465 cb.cb_flags = IOS_L_HISTO_M;
4466 } else if (rq_histo) {
4467 cb.cb_flags = IOS_RQ_HISTO_M;
4468 } else {
4469 cb.cb_flags = IOS_DEFAULT_M;
4470 if (latency)
4471 cb.cb_flags |= IOS_LATENCY_M;
4472 if (queues)
4473 cb.cb_flags |= IOS_QUEUES_M;
4477 * See if the module supports all the stats we want to display.
4479 unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
4480 if (unsupported_flags) {
4481 uint64_t f;
4482 int idx;
4483 fprintf(stderr,
4484 gettext("The loaded zfs module doesn't support:"));
4486 /* for each bit set in unsupported_flags */
4487 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
4488 idx = lowbit64(f) - 1;
4489 fprintf(stderr, " -%c", flag_to_arg[idx]);
4492 fprintf(stderr, ". Try running a newer module.\n");
4493 pool_list_free(list);
4495 return (1);
4498 for (;;) {
4499 if ((npools = pool_list_count(list)) == 0)
4500 (void) fprintf(stderr, gettext("no pools available\n"));
4501 else {
4503 * If this is the first iteration and -y was supplied
4504 * we skip any printing.
4506 boolean_t skip = (omit_since_boot &&
4507 cb.cb_iteration == 0);
4510 * Refresh all statistics. This is done as an
4511 * explicit step before calculating the maximum name
4512 * width, so that any * configuration changes are
4513 * properly accounted for.
4515 (void) pool_list_iter(list, B_FALSE, refresh_iostat,
4516 &cb);
4519 * Iterate over all pools to determine the maximum width
4520 * for the pool / device name column across all pools.
4522 cb.cb_namewidth = 0;
4523 (void) pool_list_iter(list, B_FALSE, get_namewidth,
4524 &cb);
4526 if (timestamp_fmt != NODATE)
4527 print_timestamp(timestamp_fmt);
4529 if (cmd != NULL && cb.cb_verbose &&
4530 !(cb.cb_flags & IOS_ANYHISTO_M)) {
4531 cb.vcdl = all_pools_for_each_vdev_run(argc,
4532 argv, cmd, g_zfs, cb.cb_vdev_names,
4533 cb.cb_vdev_names_count, cb.cb_name_flags);
4534 } else {
4535 cb.vcdl = NULL;
4539 * If it's the first time and we're not skipping it,
4540 * or either skip or verbose mode, print the header.
4542 * The histogram code explicitly prints its header on
4543 * every vdev, so skip this for histograms.
4545 if (((++cb.cb_iteration == 1 && !skip) ||
4546 (skip != verbose)) &&
4547 (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
4548 !cb.cb_scripted)
4549 print_iostat_header(&cb);
4551 if (skip) {
4552 (void) fsleep(interval);
4553 continue;
4557 pool_list_iter(list, B_FALSE, print_iostat, &cb);
4560 * If there's more than one pool, and we're not in
4561 * verbose mode (which prints a separator for us),
4562 * then print a separator.
4564 * In addition, if we're printing specific vdevs then
4565 * we also want an ending separator.
4567 if (((npools > 1 && !verbose &&
4568 !(cb.cb_flags & IOS_ANYHISTO_M)) ||
4569 (!(cb.cb_flags & IOS_ANYHISTO_M) &&
4570 cb.cb_vdev_names_count)) &&
4571 !cb.cb_scripted) {
4572 print_iostat_separator(&cb);
4573 if (cb.vcdl != NULL)
4574 print_cmd_columns(cb.vcdl, 1);
4575 printf("\n");
4578 if (cb.vcdl != NULL)
4579 free_vdev_cmd_data_list(cb.vcdl);
4584 * Flush the output so that redirection to a file isn't buffered
4585 * indefinitely.
4587 (void) fflush(stdout);
4589 if (interval == 0)
4590 break;
4592 if (count != 0 && --count == 0)
4593 break;
4595 (void) fsleep(interval);
4598 pool_list_free(list);
4600 return (ret);
4603 typedef struct list_cbdata {
4604 boolean_t cb_verbose;
4605 int cb_name_flags;
4606 int cb_namewidth;
4607 boolean_t cb_scripted;
4608 zprop_list_t *cb_proplist;
4609 boolean_t cb_literal;
4610 } list_cbdata_t;
4613 * Given a list of columns to display, output appropriate headers for each one.
4615 static void
4616 print_header(list_cbdata_t *cb)
4618 zprop_list_t *pl = cb->cb_proplist;
4619 char headerbuf[ZPOOL_MAXPROPLEN];
4620 const char *header;
4621 boolean_t first = B_TRUE;
4622 boolean_t right_justify;
4623 size_t width = 0;
4625 for (; pl != NULL; pl = pl->pl_next) {
4626 width = pl->pl_width;
4627 if (first && cb->cb_verbose) {
4629 * Reset the width to accommodate the verbose listing
4630 * of devices.
4632 width = cb->cb_namewidth;
4635 if (!first)
4636 (void) printf(" ");
4637 else
4638 first = B_FALSE;
4640 right_justify = B_FALSE;
4641 if (pl->pl_prop != ZPROP_INVAL) {
4642 header = zpool_prop_column_name(pl->pl_prop);
4643 right_justify = zpool_prop_align_right(pl->pl_prop);
4644 } else {
4645 int i;
4647 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
4648 headerbuf[i] = toupper(pl->pl_user_prop[i]);
4649 headerbuf[i] = '\0';
4650 header = headerbuf;
4653 if (pl->pl_next == NULL && !right_justify)
4654 (void) printf("%s", header);
4655 else if (right_justify)
4656 (void) printf("%*s", (int)width, header);
4657 else
4658 (void) printf("%-*s", (int)width, header);
4661 (void) printf("\n");
4665 * Given a pool and a list of properties, print out all the properties according
4666 * to the described layout.
4668 static void
4669 print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
4671 zprop_list_t *pl = cb->cb_proplist;
4672 boolean_t first = B_TRUE;
4673 char property[ZPOOL_MAXPROPLEN];
4674 char *propstr;
4675 boolean_t right_justify;
4676 size_t width;
4678 for (; pl != NULL; pl = pl->pl_next) {
4680 width = pl->pl_width;
4681 if (first && cb->cb_verbose) {
4683 * Reset the width to accommodate the verbose listing
4684 * of devices.
4686 width = cb->cb_namewidth;
4689 if (!first) {
4690 if (cb->cb_scripted)
4691 (void) printf("\t");
4692 else
4693 (void) printf(" ");
4694 } else {
4695 first = B_FALSE;
4698 right_justify = B_FALSE;
4699 if (pl->pl_prop != ZPROP_INVAL) {
4700 if (zpool_get_prop(zhp, pl->pl_prop, property,
4701 sizeof (property), NULL, cb->cb_literal) != 0)
4702 propstr = "-";
4703 else
4704 propstr = property;
4706 right_justify = zpool_prop_align_right(pl->pl_prop);
4707 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
4708 zpool_prop_unsupported(pl->pl_user_prop)) &&
4709 zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
4710 sizeof (property)) == 0) {
4711 propstr = property;
4712 } else {
4713 propstr = "-";
4718 * If this is being called in scripted mode, or if this is the
4719 * last column and it is left-justified, don't include a width
4720 * format specifier.
4722 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
4723 (void) printf("%s", propstr);
4724 else if (right_justify)
4725 (void) printf("%*s", (int)width, propstr);
4726 else
4727 (void) printf("%-*s", (int)width, propstr);
4730 (void) printf("\n");
4733 static void
4734 print_one_column(zpool_prop_t prop, uint64_t value, boolean_t scripted,
4735 boolean_t valid, enum zfs_nicenum_format format)
4737 char propval[64];
4738 boolean_t fixed;
4739 size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
4741 switch (prop) {
4742 case ZPOOL_PROP_EXPANDSZ:
4743 if (value == 0)
4744 (void) strlcpy(propval, "-", sizeof (propval));
4745 else
4746 zfs_nicenum_format(value, propval, sizeof (propval),
4747 format);
4748 break;
4749 case ZPOOL_PROP_FRAGMENTATION:
4750 if (value == ZFS_FRAG_INVALID) {
4751 (void) strlcpy(propval, "-", sizeof (propval));
4752 } else if (format == ZFS_NICENUM_RAW) {
4753 (void) snprintf(propval, sizeof (propval), "%llu",
4754 (unsigned long long)value);
4755 } else {
4756 (void) snprintf(propval, sizeof (propval), "%llu%%",
4757 (unsigned long long)value);
4759 break;
4760 case ZPOOL_PROP_CAPACITY:
4761 if (format == ZFS_NICENUM_RAW)
4762 (void) snprintf(propval, sizeof (propval), "%llu",
4763 (unsigned long long)value);
4764 else
4765 (void) snprintf(propval, sizeof (propval), "%llu%%",
4766 (unsigned long long)value);
4767 break;
4768 default:
4769 zfs_nicenum_format(value, propval, sizeof (propval), format);
4772 if (!valid)
4773 (void) strlcpy(propval, "-", sizeof (propval));
4775 if (scripted)
4776 (void) printf("\t%s", propval);
4777 else
4778 (void) printf(" %*s", (int)width, propval);
4781 void
4782 print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
4783 list_cbdata_t *cb, int depth)
4785 nvlist_t **child;
4786 vdev_stat_t *vs;
4787 uint_t c, children;
4788 char *vname;
4789 boolean_t scripted = cb->cb_scripted;
4790 uint64_t islog = B_FALSE;
4791 boolean_t haslog = B_FALSE;
4792 char *dashes = "%-*s - - - - - -\n";
4794 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
4795 (uint64_t **)&vs, &c) == 0);
4797 if (name != NULL) {
4798 boolean_t toplevel = (vs->vs_space != 0);
4799 uint64_t cap;
4800 enum zfs_nicenum_format format;
4802 if (cb->cb_literal)
4803 format = ZFS_NICENUM_RAW;
4804 else
4805 format = ZFS_NICENUM_1024;
4807 if (scripted)
4808 (void) printf("\t%s", name);
4809 else if (strlen(name) + depth > cb->cb_namewidth)
4810 (void) printf("%*s%s", depth, "", name);
4811 else
4812 (void) printf("%*s%s%*s", depth, "", name,
4813 (int)(cb->cb_namewidth - strlen(name) - depth), "");
4816 * Print the properties for the individual vdevs. Some
4817 * properties are only applicable to toplevel vdevs. The
4818 * 'toplevel' boolean value is passed to the print_one_column()
4819 * to indicate that the value is valid.
4821 print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, scripted,
4822 toplevel, format);
4823 print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, scripted,
4824 toplevel, format);
4825 print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
4826 scripted, toplevel, format);
4827 print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, scripted,
4828 B_TRUE, format);
4829 print_one_column(ZPOOL_PROP_FRAGMENTATION,
4830 vs->vs_fragmentation, scripted,
4831 (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
4832 format);
4833 cap = (vs->vs_space == 0) ? 0 :
4834 (vs->vs_alloc * 100 / vs->vs_space);
4835 print_one_column(ZPOOL_PROP_CAPACITY, cap, scripted, toplevel,
4836 format);
4837 (void) printf("\n");
4840 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
4841 &child, &children) != 0)
4842 return;
4844 for (c = 0; c < children; c++) {
4845 uint64_t ishole = B_FALSE;
4847 if (nvlist_lookup_uint64(child[c],
4848 ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
4849 continue;
4851 if (nvlist_lookup_uint64(child[c],
4852 ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog) {
4853 haslog = B_TRUE;
4854 continue;
4857 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4858 cb->cb_name_flags);
4859 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4860 free(vname);
4863 if (haslog == B_TRUE) {
4864 /* LINTED E_SEC_PRINTF_VAR_FMT */
4865 (void) printf(dashes, cb->cb_namewidth, "log");
4866 for (c = 0; c < children; c++) {
4867 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
4868 &islog) != 0 || !islog)
4869 continue;
4870 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4871 cb->cb_name_flags);
4872 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4873 free(vname);
4877 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
4878 &child, &children) == 0 && children > 0) {
4879 /* LINTED E_SEC_PRINTF_VAR_FMT */
4880 (void) printf(dashes, cb->cb_namewidth, "cache");
4881 for (c = 0; c < children; c++) {
4882 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4883 cb->cb_name_flags);
4884 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4885 free(vname);
4889 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
4890 &children) == 0 && children > 0) {
4891 /* LINTED E_SEC_PRINTF_VAR_FMT */
4892 (void) printf(dashes, cb->cb_namewidth, "spare");
4893 for (c = 0; c < children; c++) {
4894 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4895 cb->cb_name_flags);
4896 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4897 free(vname);
4904 * Generic callback function to list a pool.
4907 list_callback(zpool_handle_t *zhp, void *data)
4909 list_cbdata_t *cbp = data;
4910 nvlist_t *config;
4911 nvlist_t *nvroot;
4913 config = zpool_get_config(zhp, NULL);
4915 print_pool(zhp, cbp);
4916 if (!cbp->cb_verbose)
4917 return (0);
4919 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4920 &nvroot) == 0);
4921 print_list_stats(zhp, NULL, nvroot, cbp, 0);
4923 return (0);
4927 * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
4929 * -g Display guid for individual vdev name.
4930 * -H Scripted mode. Don't display headers, and separate properties
4931 * by a single tab.
4932 * -L Follow links when resolving vdev path name.
4933 * -o List of properties to display. Defaults to
4934 * "name,size,allocated,free,expandsize,fragmentation,capacity,"
4935 * "dedupratio,health,altroot"
4936 * -p Display values in parsable (exact) format.
4937 * -P Display full path for vdev name.
4938 * -T Display a timestamp in date(1) or Unix format
4940 * List all pools in the system, whether or not they're healthy. Output space
4941 * statistics for each one, as well as health status summary.
4944 zpool_do_list(int argc, char **argv)
4946 int c;
4947 int ret = 0;
4948 list_cbdata_t cb = { 0 };
4949 static char default_props[] =
4950 "name,size,allocated,free,expandsize,fragmentation,capacity,"
4951 "dedupratio,health,altroot";
4952 char *props = default_props;
4953 float interval = 0;
4954 unsigned long count = 0;
4955 zpool_list_t *list;
4956 boolean_t first = B_TRUE;
4958 /* check options */
4959 while ((c = getopt(argc, argv, ":gHLo:pPT:v")) != -1) {
4960 switch (c) {
4961 case 'g':
4962 cb.cb_name_flags |= VDEV_NAME_GUID;
4963 break;
4964 case 'H':
4965 cb.cb_scripted = B_TRUE;
4966 break;
4967 case 'L':
4968 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
4969 break;
4970 case 'o':
4971 props = optarg;
4972 break;
4973 case 'P':
4974 cb.cb_name_flags |= VDEV_NAME_PATH;
4975 break;
4976 case 'p':
4977 cb.cb_literal = B_TRUE;
4978 break;
4979 case 'T':
4980 get_timestamp_arg(*optarg);
4981 break;
4982 case 'v':
4983 cb.cb_verbose = B_TRUE;
4984 break;
4985 case ':':
4986 (void) fprintf(stderr, gettext("missing argument for "
4987 "'%c' option\n"), optopt);
4988 usage(B_FALSE);
4989 break;
4990 case '?':
4991 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4992 optopt);
4993 usage(B_FALSE);
4997 argc -= optind;
4998 argv += optind;
5000 get_interval_count(&argc, argv, &interval, &count);
5002 if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
5003 usage(B_FALSE);
5005 for (;;) {
5006 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
5007 &ret)) == NULL)
5008 return (1);
5010 if (pool_list_count(list) == 0)
5011 break;
5013 if (timestamp_fmt != NODATE)
5014 print_timestamp(timestamp_fmt);
5016 if (!cb.cb_scripted && (first || cb.cb_verbose)) {
5017 print_header(&cb);
5018 first = B_FALSE;
5020 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
5022 if (interval == 0)
5023 break;
5025 if (count != 0 && --count == 0)
5026 break;
5028 pool_list_free(list);
5029 (void) fsleep(interval);
5032 if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
5033 (void) printf(gettext("no pools available\n"));
5034 ret = 0;
5037 pool_list_free(list);
5038 zprop_free_list(cb.cb_proplist);
5039 return (ret);
5042 static int
5043 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
5045 boolean_t force = B_FALSE;
5046 int c;
5047 nvlist_t *nvroot;
5048 char *poolname, *old_disk, *new_disk;
5049 zpool_handle_t *zhp;
5050 nvlist_t *props = NULL;
5051 char *propval;
5052 int ret;
5054 /* check options */
5055 while ((c = getopt(argc, argv, "fo:")) != -1) {
5056 switch (c) {
5057 case 'f':
5058 force = B_TRUE;
5059 break;
5060 case 'o':
5061 if ((propval = strchr(optarg, '=')) == NULL) {
5062 (void) fprintf(stderr, gettext("missing "
5063 "'=' for -o option\n"));
5064 usage(B_FALSE);
5066 *propval = '\0';
5067 propval++;
5069 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
5070 (add_prop_list(optarg, propval, &props, B_TRUE)))
5071 usage(B_FALSE);
5072 break;
5073 case '?':
5074 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5075 optopt);
5076 usage(B_FALSE);
5080 argc -= optind;
5081 argv += optind;
5083 /* get pool name and check number of arguments */
5084 if (argc < 1) {
5085 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5086 usage(B_FALSE);
5089 poolname = argv[0];
5091 if (argc < 2) {
5092 (void) fprintf(stderr,
5093 gettext("missing <device> specification\n"));
5094 usage(B_FALSE);
5097 old_disk = argv[1];
5099 if (argc < 3) {
5100 if (!replacing) {
5101 (void) fprintf(stderr,
5102 gettext("missing <new_device> specification\n"));
5103 usage(B_FALSE);
5105 new_disk = old_disk;
5106 argc -= 1;
5107 argv += 1;
5108 } else {
5109 new_disk = argv[2];
5110 argc -= 2;
5111 argv += 2;
5114 if (argc > 1) {
5115 (void) fprintf(stderr, gettext("too many arguments\n"));
5116 usage(B_FALSE);
5119 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
5120 nvlist_free(props);
5121 return (1);
5124 if (zpool_get_config(zhp, NULL) == NULL) {
5125 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
5126 poolname);
5127 zpool_close(zhp);
5128 nvlist_free(props);
5129 return (1);
5132 /* unless manually specified use "ashift" pool property (if set) */
5133 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
5134 int intval;
5135 zprop_source_t src;
5136 char strval[ZPOOL_MAXPROPLEN];
5138 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
5139 if (src != ZPROP_SRC_DEFAULT) {
5140 (void) sprintf(strval, "%" PRId32, intval);
5141 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
5142 &props, B_TRUE) == 0);
5146 nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
5147 argc, argv);
5148 if (nvroot == NULL) {
5149 zpool_close(zhp);
5150 nvlist_free(props);
5151 return (1);
5154 ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing);
5156 nvlist_free(props);
5157 nvlist_free(nvroot);
5158 zpool_close(zhp);
5160 return (ret);
5164 * zpool replace [-f] <pool> <device> <new_device>
5166 * -f Force attach, even if <new_device> appears to be in use.
5168 * Replace <device> with <new_device>.
5170 /* ARGSUSED */
5172 zpool_do_replace(int argc, char **argv)
5174 return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
5178 * zpool attach [-f] [-o property=value] <pool> <device> <new_device>
5180 * -f Force attach, even if <new_device> appears to be in use.
5181 * -o Set property=value.
5183 * Attach <new_device> to the mirror containing <device>. If <device> is not
5184 * part of a mirror, then <device> will be transformed into a mirror of
5185 * <device> and <new_device>. In either case, <new_device> will begin life
5186 * with a DTL of [0, now], and will immediately begin to resilver itself.
5189 zpool_do_attach(int argc, char **argv)
5191 return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
5195 * zpool detach [-f] <pool> <device>
5197 * -f Force detach of <device>, even if DTLs argue against it
5198 * (not supported yet)
5200 * Detach a device from a mirror. The operation will be refused if <device>
5201 * is the last device in the mirror, or if the DTLs indicate that this device
5202 * has the only valid copy of some data.
5204 /* ARGSUSED */
5206 zpool_do_detach(int argc, char **argv)
5208 int c;
5209 char *poolname, *path;
5210 zpool_handle_t *zhp;
5211 int ret;
5213 /* check options */
5214 while ((c = getopt(argc, argv, "f")) != -1) {
5215 switch (c) {
5216 case 'f':
5217 case '?':
5218 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5219 optopt);
5220 usage(B_FALSE);
5224 argc -= optind;
5225 argv += optind;
5227 /* get pool name and check number of arguments */
5228 if (argc < 1) {
5229 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5230 usage(B_FALSE);
5233 if (argc < 2) {
5234 (void) fprintf(stderr,
5235 gettext("missing <device> specification\n"));
5236 usage(B_FALSE);
5239 poolname = argv[0];
5240 path = argv[1];
5242 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5243 return (1);
5245 ret = zpool_vdev_detach(zhp, path);
5247 zpool_close(zhp);
5249 return (ret);
5253 * zpool split [-gLnP] [-o prop=val] ...
5254 * [-o mntopt] ...
5255 * [-R altroot] <pool> <newpool> [<device> ...]
5257 * -g Display guid for individual vdev name.
5258 * -L Follow links when resolving vdev path name.
5259 * -n Do not split the pool, but display the resulting layout if
5260 * it were to be split.
5261 * -o Set property=value, or set mount options.
5262 * -P Display full path for vdev name.
5263 * -R Mount the split-off pool under an alternate root.
5265 * Splits the named pool and gives it the new pool name. Devices to be split
5266 * off may be listed, provided that no more than one device is specified
5267 * per top-level vdev mirror. The newly split pool is left in an exported
5268 * state unless -R is specified.
5270 * Restrictions: the top-level of the pool pool must only be made up of
5271 * mirrors; all devices in the pool must be healthy; no device may be
5272 * undergoing a resilvering operation.
5275 zpool_do_split(int argc, char **argv)
5277 char *srcpool, *newpool, *propval;
5278 char *mntopts = NULL;
5279 splitflags_t flags;
5280 int c, ret = 0;
5281 zpool_handle_t *zhp;
5282 nvlist_t *config, *props = NULL;
5284 flags.dryrun = B_FALSE;
5285 flags.import = B_FALSE;
5286 flags.name_flags = 0;
5288 /* check options */
5289 while ((c = getopt(argc, argv, ":gLR:no:P")) != -1) {
5290 switch (c) {
5291 case 'g':
5292 flags.name_flags |= VDEV_NAME_GUID;
5293 break;
5294 case 'L':
5295 flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
5296 break;
5297 case 'R':
5298 flags.import = B_TRUE;
5299 if (add_prop_list(
5300 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
5301 &props, B_TRUE) != 0) {
5302 nvlist_free(props);
5303 usage(B_FALSE);
5305 break;
5306 case 'n':
5307 flags.dryrun = B_TRUE;
5308 break;
5309 case 'o':
5310 if ((propval = strchr(optarg, '=')) != NULL) {
5311 *propval = '\0';
5312 propval++;
5313 if (add_prop_list(optarg, propval,
5314 &props, B_TRUE) != 0) {
5315 nvlist_free(props);
5316 usage(B_FALSE);
5318 } else {
5319 mntopts = optarg;
5321 break;
5322 case 'P':
5323 flags.name_flags |= VDEV_NAME_PATH;
5324 break;
5325 case ':':
5326 (void) fprintf(stderr, gettext("missing argument for "
5327 "'%c' option\n"), optopt);
5328 usage(B_FALSE);
5329 break;
5330 case '?':
5331 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5332 optopt);
5333 usage(B_FALSE);
5334 break;
5338 if (!flags.import && mntopts != NULL) {
5339 (void) fprintf(stderr, gettext("setting mntopts is only "
5340 "valid when importing the pool\n"));
5341 usage(B_FALSE);
5344 argc -= optind;
5345 argv += optind;
5347 if (argc < 1) {
5348 (void) fprintf(stderr, gettext("Missing pool name\n"));
5349 usage(B_FALSE);
5351 if (argc < 2) {
5352 (void) fprintf(stderr, gettext("Missing new pool name\n"));
5353 usage(B_FALSE);
5356 srcpool = argv[0];
5357 newpool = argv[1];
5359 argc -= 2;
5360 argv += 2;
5362 if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
5363 nvlist_free(props);
5364 return (1);
5367 config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
5368 if (config == NULL) {
5369 ret = 1;
5370 } else {
5371 if (flags.dryrun) {
5372 (void) printf(gettext("would create '%s' with the "
5373 "following layout:\n\n"), newpool);
5374 print_vdev_tree(NULL, newpool, config, 0, B_FALSE,
5375 flags.name_flags);
5379 zpool_close(zhp);
5381 if (ret != 0 || flags.dryrun || !flags.import) {
5382 nvlist_free(config);
5383 nvlist_free(props);
5384 return (ret);
5388 * The split was successful. Now we need to open the new
5389 * pool and import it.
5391 if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
5392 nvlist_free(config);
5393 nvlist_free(props);
5394 return (1);
5396 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
5397 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
5398 ret = 1;
5399 (void) fprintf(stderr, gettext("Split was successful, but "
5400 "the datasets could not all be mounted\n"));
5401 (void) fprintf(stderr, gettext("Try doing '%s' with a "
5402 "different altroot\n"), "zpool import");
5404 zpool_close(zhp);
5405 nvlist_free(config);
5406 nvlist_free(props);
5408 return (ret);
5414 * zpool online <pool> <device> ...
5417 zpool_do_online(int argc, char **argv)
5419 int c, i;
5420 char *poolname;
5421 zpool_handle_t *zhp;
5422 int ret = 0;
5423 vdev_state_t newstate;
5424 int flags = 0;
5426 /* check options */
5427 while ((c = getopt(argc, argv, "et")) != -1) {
5428 switch (c) {
5429 case 'e':
5430 flags |= ZFS_ONLINE_EXPAND;
5431 break;
5432 case 't':
5433 case '?':
5434 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5435 optopt);
5436 usage(B_FALSE);
5440 argc -= optind;
5441 argv += optind;
5443 /* get pool name and check number of arguments */
5444 if (argc < 1) {
5445 (void) fprintf(stderr, gettext("missing pool name\n"));
5446 usage(B_FALSE);
5448 if (argc < 2) {
5449 (void) fprintf(stderr, gettext("missing device name\n"));
5450 usage(B_FALSE);
5453 poolname = argv[0];
5455 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5456 return (1);
5458 for (i = 1; i < argc; i++) {
5459 if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
5460 if (newstate != VDEV_STATE_HEALTHY) {
5461 (void) printf(gettext("warning: device '%s' "
5462 "onlined, but remains in faulted state\n"),
5463 argv[i]);
5464 if (newstate == VDEV_STATE_FAULTED)
5465 (void) printf(gettext("use 'zpool "
5466 "clear' to restore a faulted "
5467 "device\n"));
5468 else
5469 (void) printf(gettext("use 'zpool "
5470 "replace' to replace devices "
5471 "that are no longer present\n"));
5473 } else {
5474 ret = 1;
5478 zpool_close(zhp);
5480 return (ret);
5484 * zpool offline [-ft] <pool> <device> ...
5486 * -f Force the device into a faulted state.
5488 * -t Only take the device off-line temporarily. The offline/faulted
5489 * state will not be persistent across reboots.
5491 /* ARGSUSED */
5493 zpool_do_offline(int argc, char **argv)
5495 int c, i;
5496 char *poolname;
5497 zpool_handle_t *zhp;
5498 int ret = 0;
5499 boolean_t istmp = B_FALSE;
5500 boolean_t fault = B_FALSE;
5502 /* check options */
5503 while ((c = getopt(argc, argv, "ft")) != -1) {
5504 switch (c) {
5505 case 'f':
5506 fault = B_TRUE;
5507 break;
5508 case 't':
5509 istmp = B_TRUE;
5510 break;
5511 case '?':
5512 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5513 optopt);
5514 usage(B_FALSE);
5518 argc -= optind;
5519 argv += optind;
5521 /* get pool name and check number of arguments */
5522 if (argc < 1) {
5523 (void) fprintf(stderr, gettext("missing pool name\n"));
5524 usage(B_FALSE);
5526 if (argc < 2) {
5527 (void) fprintf(stderr, gettext("missing device name\n"));
5528 usage(B_FALSE);
5531 poolname = argv[0];
5533 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5534 return (1);
5536 for (i = 1; i < argc; i++) {
5537 if (fault) {
5538 uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
5539 vdev_aux_t aux;
5540 if (istmp == B_FALSE) {
5541 /* Force the fault to persist across imports */
5542 aux = VDEV_AUX_EXTERNAL_PERSIST;
5543 } else {
5544 aux = VDEV_AUX_EXTERNAL;
5547 if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
5548 ret = 1;
5549 } else {
5550 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
5551 ret = 1;
5555 zpool_close(zhp);
5557 return (ret);
5561 * zpool clear <pool> [device]
5563 * Clear all errors associated with a pool or a particular device.
5566 zpool_do_clear(int argc, char **argv)
5568 int c;
5569 int ret = 0;
5570 boolean_t dryrun = B_FALSE;
5571 boolean_t do_rewind = B_FALSE;
5572 boolean_t xtreme_rewind = B_FALSE;
5573 uint32_t rewind_policy = ZPOOL_NO_REWIND;
5574 nvlist_t *policy = NULL;
5575 zpool_handle_t *zhp;
5576 char *pool, *device;
5578 /* check options */
5579 while ((c = getopt(argc, argv, "FnX")) != -1) {
5580 switch (c) {
5581 case 'F':
5582 do_rewind = B_TRUE;
5583 break;
5584 case 'n':
5585 dryrun = B_TRUE;
5586 break;
5587 case 'X':
5588 xtreme_rewind = B_TRUE;
5589 break;
5590 case '?':
5591 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5592 optopt);
5593 usage(B_FALSE);
5597 argc -= optind;
5598 argv += optind;
5600 if (argc < 1) {
5601 (void) fprintf(stderr, gettext("missing pool name\n"));
5602 usage(B_FALSE);
5605 if (argc > 2) {
5606 (void) fprintf(stderr, gettext("too many arguments\n"));
5607 usage(B_FALSE);
5610 if ((dryrun || xtreme_rewind) && !do_rewind) {
5611 (void) fprintf(stderr,
5612 gettext("-n or -X only meaningful with -F\n"));
5613 usage(B_FALSE);
5615 if (dryrun)
5616 rewind_policy = ZPOOL_TRY_REWIND;
5617 else if (do_rewind)
5618 rewind_policy = ZPOOL_DO_REWIND;
5619 if (xtreme_rewind)
5620 rewind_policy |= ZPOOL_EXTREME_REWIND;
5622 /* In future, further rewind policy choices can be passed along here */
5623 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
5624 nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
5625 return (1);
5627 pool = argv[0];
5628 device = argc == 2 ? argv[1] : NULL;
5630 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
5631 nvlist_free(policy);
5632 return (1);
5635 if (zpool_clear(zhp, device, policy) != 0)
5636 ret = 1;
5638 zpool_close(zhp);
5640 nvlist_free(policy);
5642 return (ret);
5646 * zpool reguid <pool>
5649 zpool_do_reguid(int argc, char **argv)
5651 int c;
5652 char *poolname;
5653 zpool_handle_t *zhp;
5654 int ret = 0;
5656 /* check options */
5657 while ((c = getopt(argc, argv, "")) != -1) {
5658 switch (c) {
5659 case '?':
5660 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5661 optopt);
5662 usage(B_FALSE);
5666 argc -= optind;
5667 argv += optind;
5669 /* get pool name and check number of arguments */
5670 if (argc < 1) {
5671 (void) fprintf(stderr, gettext("missing pool name\n"));
5672 usage(B_FALSE);
5675 if (argc > 1) {
5676 (void) fprintf(stderr, gettext("too many arguments\n"));
5677 usage(B_FALSE);
5680 poolname = argv[0];
5681 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5682 return (1);
5684 ret = zpool_reguid(zhp);
5686 zpool_close(zhp);
5687 return (ret);
5692 * zpool reopen <pool>
5694 * Reopen the pool so that the kernel can update the sizes of all vdevs.
5697 zpool_do_reopen(int argc, char **argv)
5699 int c;
5700 int ret = 0;
5701 zpool_handle_t *zhp;
5702 char *pool;
5704 /* check options */
5705 while ((c = getopt(argc, argv, "")) != -1) {
5706 switch (c) {
5707 case '?':
5708 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5709 optopt);
5710 usage(B_FALSE);
5714 argc--;
5715 argv++;
5717 if (argc < 1) {
5718 (void) fprintf(stderr, gettext("missing pool name\n"));
5719 usage(B_FALSE);
5722 if (argc > 1) {
5723 (void) fprintf(stderr, gettext("too many arguments\n"));
5724 usage(B_FALSE);
5727 pool = argv[0];
5728 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL)
5729 return (1);
5731 ret = zpool_reopen(zhp);
5732 zpool_close(zhp);
5733 return (ret);
5736 typedef struct scrub_cbdata {
5737 int cb_type;
5738 int cb_argc;
5739 char **cb_argv;
5740 } scrub_cbdata_t;
5743 scrub_callback(zpool_handle_t *zhp, void *data)
5745 scrub_cbdata_t *cb = data;
5746 int err;
5749 * Ignore faulted pools.
5751 if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
5752 (void) fprintf(stderr, gettext("cannot scrub '%s': pool is "
5753 "currently unavailable\n"), zpool_get_name(zhp));
5754 return (1);
5757 err = zpool_scan(zhp, cb->cb_type);
5759 return (err != 0);
5763 * zpool scrub [-s] <pool> ...
5765 * -s Stop. Stops any in-progress scrub.
5768 zpool_do_scrub(int argc, char **argv)
5770 int c;
5771 scrub_cbdata_t cb;
5773 cb.cb_type = POOL_SCAN_SCRUB;
5775 /* check options */
5776 while ((c = getopt(argc, argv, "s")) != -1) {
5777 switch (c) {
5778 case 's':
5779 cb.cb_type = POOL_SCAN_NONE;
5780 break;
5781 case '?':
5782 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5783 optopt);
5784 usage(B_FALSE);
5788 cb.cb_argc = argc;
5789 cb.cb_argv = argv;
5790 argc -= optind;
5791 argv += optind;
5793 if (argc < 1) {
5794 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5795 usage(B_FALSE);
5798 return (for_each_pool(argc, argv, B_TRUE, NULL, scrub_callback, &cb));
5802 * Print out detailed scrub status.
5804 void
5805 print_scan_status(pool_scan_stat_t *ps)
5807 time_t start, end;
5808 uint64_t elapsed, mins_left, hours_left;
5809 uint64_t pass_exam, examined, total;
5810 uint_t rate;
5811 double fraction_done;
5812 char processed_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
5814 (void) printf(gettext(" scan: "));
5816 /* If there's never been a scan, there's not much to say. */
5817 if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
5818 ps->pss_func >= POOL_SCAN_FUNCS) {
5819 (void) printf(gettext("none requested\n"));
5820 return;
5823 start = ps->pss_start_time;
5824 end = ps->pss_end_time;
5825 zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
5827 assert(ps->pss_func == POOL_SCAN_SCRUB ||
5828 ps->pss_func == POOL_SCAN_RESILVER);
5830 * Scan is finished or canceled.
5832 if (ps->pss_state == DSS_FINISHED) {
5833 uint64_t minutes_taken = (end - start) / 60;
5834 char *fmt = NULL;
5836 if (ps->pss_func == POOL_SCAN_SCRUB) {
5837 fmt = gettext("scrub repaired %s in %lluh%um with "
5838 "%llu errors on %s");
5839 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5840 fmt = gettext("resilvered %s in %lluh%um with "
5841 "%llu errors on %s");
5843 /* LINTED */
5844 (void) printf(fmt, processed_buf,
5845 (u_longlong_t)(minutes_taken / 60),
5846 (uint_t)(minutes_taken % 60),
5847 (u_longlong_t)ps->pss_errors,
5848 ctime((time_t *)&end));
5849 return;
5850 } else if (ps->pss_state == DSS_CANCELED) {
5851 if (ps->pss_func == POOL_SCAN_SCRUB) {
5852 (void) printf(gettext("scrub canceled on %s"),
5853 ctime(&end));
5854 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5855 (void) printf(gettext("resilver canceled on %s"),
5856 ctime(&end));
5858 return;
5861 assert(ps->pss_state == DSS_SCANNING);
5864 * Scan is in progress.
5866 if (ps->pss_func == POOL_SCAN_SCRUB) {
5867 (void) printf(gettext("scrub in progress since %s"),
5868 ctime(&start));
5869 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5870 (void) printf(gettext("resilver in progress since %s"),
5871 ctime(&start));
5874 examined = ps->pss_examined ? ps->pss_examined : 1;
5875 total = ps->pss_to_examine;
5876 fraction_done = (double)examined / total;
5878 /* elapsed time for this pass */
5879 elapsed = time(NULL) - ps->pss_pass_start;
5880 elapsed = elapsed ? elapsed : 1;
5881 pass_exam = ps->pss_pass_exam ? ps->pss_pass_exam : 1;
5882 rate = pass_exam / elapsed;
5883 rate = rate ? rate : 1;
5884 mins_left = ((total - examined) / rate) / 60;
5885 hours_left = mins_left / 60;
5887 zfs_nicebytes(examined, examined_buf, sizeof (examined_buf));
5888 zfs_nicebytes(total, total_buf, sizeof (total_buf));
5889 zfs_nicebytes(rate, rate_buf, sizeof (rate_buf));
5892 * do not print estimated time if hours_left is more than 30 days
5894 (void) printf(gettext("\t%s scanned out of %s at %s/s"),
5895 examined_buf, total_buf, rate_buf);
5896 if (hours_left < (30 * 24)) {
5897 (void) printf(gettext(", %lluh%um to go\n"),
5898 (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
5899 } else {
5900 (void) printf(gettext(
5901 ", (scan is slow, no estimated time)\n"));
5904 if (ps->pss_func == POOL_SCAN_RESILVER) {
5905 (void) printf(gettext("\t%s resilvered, %.2f%% done\n"),
5906 processed_buf, 100 * fraction_done);
5907 } else if (ps->pss_func == POOL_SCAN_SCRUB) {
5908 (void) printf(gettext("\t%s repaired, %.2f%% done\n"),
5909 processed_buf, 100 * fraction_done);
5913 static void
5914 print_error_log(zpool_handle_t *zhp)
5916 nvlist_t *nverrlist = NULL;
5917 nvpair_t *elem;
5918 char *pathname;
5919 size_t len = MAXPATHLEN * 2;
5921 if (zpool_get_errlog(zhp, &nverrlist) != 0)
5922 return;
5924 (void) printf("errors: Permanent errors have been "
5925 "detected in the following files:\n\n");
5927 pathname = safe_malloc(len);
5928 elem = NULL;
5929 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
5930 nvlist_t *nv;
5931 uint64_t dsobj, obj;
5933 verify(nvpair_value_nvlist(elem, &nv) == 0);
5934 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
5935 &dsobj) == 0);
5936 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
5937 &obj) == 0);
5938 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
5939 (void) printf("%7s %s\n", "", pathname);
5941 free(pathname);
5942 nvlist_free(nverrlist);
5945 static void
5946 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
5947 uint_t nspares)
5949 uint_t i;
5950 char *name;
5952 if (nspares == 0)
5953 return;
5955 (void) printf(gettext("\tspares\n"));
5957 for (i = 0; i < nspares; i++) {
5958 name = zpool_vdev_name(g_zfs, zhp, spares[i],
5959 cb->cb_name_flags);
5960 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE);
5961 free(name);
5965 static void
5966 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
5967 uint_t nl2cache)
5969 uint_t i;
5970 char *name;
5972 if (nl2cache == 0)
5973 return;
5975 (void) printf(gettext("\tcache\n"));
5977 for (i = 0; i < nl2cache; i++) {
5978 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
5979 cb->cb_name_flags);
5980 print_status_config(zhp, cb, name, l2cache[i], 2, B_FALSE);
5981 free(name);
5985 static void
5986 print_dedup_stats(nvlist_t *config)
5988 ddt_histogram_t *ddh;
5989 ddt_stat_t *dds;
5990 ddt_object_t *ddo;
5991 uint_t c;
5992 char dspace[6], mspace[6];
5995 * If the pool was faulted then we may not have been able to
5996 * obtain the config. Otherwise, if we have anything in the dedup
5997 * table continue processing the stats.
5999 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
6000 (uint64_t **)&ddo, &c) != 0)
6001 return;
6003 (void) printf("\n");
6004 (void) printf(gettext(" dedup: "));
6005 if (ddo->ddo_count == 0) {
6006 (void) printf(gettext("no DDT entries\n"));
6007 return;
6010 zfs_nicebytes(ddo->ddo_dspace, dspace, sizeof (dspace));
6011 zfs_nicebytes(ddo->ddo_mspace, mspace, sizeof (mspace));
6012 (void) printf("DDT entries %llu, size %s on disk, %s in core\n",
6013 (u_longlong_t)ddo->ddo_count,
6014 dspace,
6015 mspace);
6017 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
6018 (uint64_t **)&dds, &c) == 0);
6019 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
6020 (uint64_t **)&ddh, &c) == 0);
6021 zpool_dump_ddt(dds, ddh);
6025 * Display a summary of pool status. Displays a summary such as:
6027 * pool: tank
6028 * status: DEGRADED
6029 * reason: One or more devices ...
6030 * see: http://zfsonlinux.org/msg/ZFS-xxxx-01
6031 * config:
6032 * mirror DEGRADED
6033 * c1t0d0 OK
6034 * c2t0d0 UNAVAIL
6036 * When given the '-v' option, we print out the complete config. If the '-e'
6037 * option is specified, then we print out error rate information as well.
6040 status_callback(zpool_handle_t *zhp, void *data)
6042 status_cbdata_t *cbp = data;
6043 nvlist_t *config, *nvroot;
6044 char *msgid;
6045 zpool_status_t reason;
6046 zpool_errata_t errata;
6047 const char *health;
6048 uint_t c;
6049 vdev_stat_t *vs;
6051 config = zpool_get_config(zhp, NULL);
6052 reason = zpool_get_status(zhp, &msgid, &errata);
6054 cbp->cb_count++;
6057 * If we were given 'zpool status -x', only report those pools with
6058 * problems.
6060 if (cbp->cb_explain &&
6061 (reason == ZPOOL_STATUS_OK ||
6062 reason == ZPOOL_STATUS_VERSION_OLDER ||
6063 reason == ZPOOL_STATUS_FEAT_DISABLED)) {
6064 if (!cbp->cb_allpools) {
6065 (void) printf(gettext("pool '%s' is healthy\n"),
6066 zpool_get_name(zhp));
6067 if (cbp->cb_first)
6068 cbp->cb_first = B_FALSE;
6070 return (0);
6073 if (cbp->cb_first)
6074 cbp->cb_first = B_FALSE;
6075 else
6076 (void) printf("\n");
6078 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
6079 &nvroot) == 0);
6080 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
6081 (uint64_t **)&vs, &c) == 0);
6082 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
6084 (void) printf(gettext(" pool: %s\n"), zpool_get_name(zhp));
6085 (void) printf(gettext(" state: %s\n"), health);
6087 switch (reason) {
6088 case ZPOOL_STATUS_MISSING_DEV_R:
6089 (void) printf(gettext("status: One or more devices could not "
6090 "be opened. Sufficient replicas exist for\n\tthe pool to "
6091 "continue functioning in a degraded state.\n"));
6092 (void) printf(gettext("action: Attach the missing device and "
6093 "online it using 'zpool online'.\n"));
6094 break;
6096 case ZPOOL_STATUS_MISSING_DEV_NR:
6097 (void) printf(gettext("status: One or more devices could not "
6098 "be opened. There are insufficient\n\treplicas for the "
6099 "pool to continue functioning.\n"));
6100 (void) printf(gettext("action: Attach the missing device and "
6101 "online it using 'zpool online'.\n"));
6102 break;
6104 case ZPOOL_STATUS_CORRUPT_LABEL_R:
6105 (void) printf(gettext("status: One or more devices could not "
6106 "be used because the label is missing or\n\tinvalid. "
6107 "Sufficient replicas exist for the pool to continue\n\t"
6108 "functioning in a degraded state.\n"));
6109 (void) printf(gettext("action: Replace the device using "
6110 "'zpool replace'.\n"));
6111 break;
6113 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
6114 (void) printf(gettext("status: One or more devices could not "
6115 "be used because the label is missing \n\tor invalid. "
6116 "There are insufficient replicas for the pool to "
6117 "continue\n\tfunctioning.\n"));
6118 zpool_explain_recover(zpool_get_handle(zhp),
6119 zpool_get_name(zhp), reason, config);
6120 break;
6122 case ZPOOL_STATUS_FAILING_DEV:
6123 (void) printf(gettext("status: One or more devices has "
6124 "experienced an unrecoverable error. An\n\tattempt was "
6125 "made to correct the error. Applications are "
6126 "unaffected.\n"));
6127 (void) printf(gettext("action: Determine if the device needs "
6128 "to be replaced, and clear the errors\n\tusing "
6129 "'zpool clear' or replace the device with 'zpool "
6130 "replace'.\n"));
6131 break;
6133 case ZPOOL_STATUS_OFFLINE_DEV:
6134 (void) printf(gettext("status: One or more devices has "
6135 "been taken offline by the administrator.\n\tSufficient "
6136 "replicas exist for the pool to continue functioning in "
6137 "a\n\tdegraded state.\n"));
6138 (void) printf(gettext("action: Online the device using "
6139 "'zpool online' or replace the device with\n\t'zpool "
6140 "replace'.\n"));
6141 break;
6143 case ZPOOL_STATUS_REMOVED_DEV:
6144 (void) printf(gettext("status: One or more devices has "
6145 "been removed by the administrator.\n\tSufficient "
6146 "replicas exist for the pool to continue functioning in "
6147 "a\n\tdegraded state.\n"));
6148 (void) printf(gettext("action: Online the device using "
6149 "'zpool online' or replace the device with\n\t'zpool "
6150 "replace'.\n"));
6151 break;
6153 case ZPOOL_STATUS_RESILVERING:
6154 (void) printf(gettext("status: One or more devices is "
6155 "currently being resilvered. The pool will\n\tcontinue "
6156 "to function, possibly in a degraded state.\n"));
6157 (void) printf(gettext("action: Wait for the resilver to "
6158 "complete.\n"));
6159 break;
6161 case ZPOOL_STATUS_CORRUPT_DATA:
6162 (void) printf(gettext("status: One or more devices has "
6163 "experienced an error resulting in data\n\tcorruption. "
6164 "Applications may be affected.\n"));
6165 (void) printf(gettext("action: Restore the file in question "
6166 "if possible. Otherwise restore the\n\tentire pool from "
6167 "backup.\n"));
6168 break;
6170 case ZPOOL_STATUS_CORRUPT_POOL:
6171 (void) printf(gettext("status: The pool metadata is corrupted "
6172 "and the pool cannot be opened.\n"));
6173 zpool_explain_recover(zpool_get_handle(zhp),
6174 zpool_get_name(zhp), reason, config);
6175 break;
6177 case ZPOOL_STATUS_VERSION_OLDER:
6178 (void) printf(gettext("status: The pool is formatted using a "
6179 "legacy on-disk format. The pool can\n\tstill be used, "
6180 "but some features are unavailable.\n"));
6181 (void) printf(gettext("action: Upgrade the pool using 'zpool "
6182 "upgrade'. Once this is done, the\n\tpool will no longer "
6183 "be accessible on software that does not support\n\t"
6184 "feature flags.\n"));
6185 break;
6187 case ZPOOL_STATUS_VERSION_NEWER:
6188 (void) printf(gettext("status: The pool has been upgraded to a "
6189 "newer, incompatible on-disk version.\n\tThe pool cannot "
6190 "be accessed on this system.\n"));
6191 (void) printf(gettext("action: Access the pool from a system "
6192 "running more recent software, or\n\trestore the pool from "
6193 "backup.\n"));
6194 break;
6196 case ZPOOL_STATUS_FEAT_DISABLED:
6197 (void) printf(gettext("status: Some supported features are not "
6198 "enabled on the pool. The pool can\n\tstill be used, but "
6199 "some features are unavailable.\n"));
6200 (void) printf(gettext("action: Enable all features using "
6201 "'zpool upgrade'. Once this is done,\n\tthe pool may no "
6202 "longer be accessible by software that does not support\n\t"
6203 "the features. See zpool-features(5) for details.\n"));
6204 break;
6206 case ZPOOL_STATUS_UNSUP_FEAT_READ:
6207 (void) printf(gettext("status: The pool cannot be accessed on "
6208 "this system because it uses the\n\tfollowing feature(s) "
6209 "not supported on this system:\n"));
6210 zpool_print_unsup_feat(config);
6211 (void) printf("\n");
6212 (void) printf(gettext("action: Access the pool from a system "
6213 "that supports the required feature(s),\n\tor restore the "
6214 "pool from backup.\n"));
6215 break;
6217 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
6218 (void) printf(gettext("status: The pool can only be accessed "
6219 "in read-only mode on this system. It\n\tcannot be "
6220 "accessed in read-write mode because it uses the "
6221 "following\n\tfeature(s) not supported on this system:\n"));
6222 zpool_print_unsup_feat(config);
6223 (void) printf("\n");
6224 (void) printf(gettext("action: The pool cannot be accessed in "
6225 "read-write mode. Import the pool with\n"
6226 "\t\"-o readonly=on\", access the pool from a system that "
6227 "supports the\n\trequired feature(s), or restore the "
6228 "pool from backup.\n"));
6229 break;
6231 case ZPOOL_STATUS_FAULTED_DEV_R:
6232 (void) printf(gettext("status: One or more devices are "
6233 "faulted in response to persistent errors.\n\tSufficient "
6234 "replicas exist for the pool to continue functioning "
6235 "in a\n\tdegraded state.\n"));
6236 (void) printf(gettext("action: Replace the faulted device, "
6237 "or use 'zpool clear' to mark the device\n\trepaired.\n"));
6238 break;
6240 case ZPOOL_STATUS_FAULTED_DEV_NR:
6241 (void) printf(gettext("status: One or more devices are "
6242 "faulted in response to persistent errors. There are "
6243 "insufficient replicas for the pool to\n\tcontinue "
6244 "functioning.\n"));
6245 (void) printf(gettext("action: Destroy and re-create the pool "
6246 "from a backup source. Manually marking the device\n"
6247 "\trepaired using 'zpool clear' may allow some data "
6248 "to be recovered.\n"));
6249 break;
6251 case ZPOOL_STATUS_IO_FAILURE_WAIT:
6252 case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
6253 (void) printf(gettext("status: One or more devices are "
6254 "faulted in response to IO failures.\n"));
6255 (void) printf(gettext("action: Make sure the affected devices "
6256 "are connected, then run 'zpool clear'.\n"));
6257 break;
6259 case ZPOOL_STATUS_BAD_LOG:
6260 (void) printf(gettext("status: An intent log record "
6261 "could not be read.\n"
6262 "\tWaiting for administrator intervention to fix the "
6263 "faulted pool.\n"));
6264 (void) printf(gettext("action: Either restore the affected "
6265 "device(s) and run 'zpool online',\n"
6266 "\tor ignore the intent log records by running "
6267 "'zpool clear'.\n"));
6268 break;
6270 case ZPOOL_STATUS_HOSTID_MISMATCH:
6271 (void) printf(gettext("status: Mismatch between pool hostid "
6272 "and system hostid on imported pool.\n\tThis pool was "
6273 "previously imported into a system with a different "
6274 "hostid,\n\tand then was verbatim imported into this "
6275 "system.\n"));
6276 (void) printf(gettext("action: Export this pool on all systems "
6277 "on which it is imported.\n"
6278 "\tThen import it to correct the mismatch.\n"));
6279 break;
6281 case ZPOOL_STATUS_ERRATA:
6282 (void) printf(gettext("status: Errata #%d detected.\n"),
6283 errata);
6285 switch (errata) {
6286 case ZPOOL_ERRATA_NONE:
6287 break;
6289 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
6290 (void) printf(gettext("action: To correct the issue "
6291 "run 'zpool scrub'.\n"));
6292 break;
6294 default:
6296 * All errata which allow the pool to be imported
6297 * must contain an action message.
6299 assert(0);
6301 break;
6303 default:
6305 * The remaining errors can't actually be generated, yet.
6307 assert(reason == ZPOOL_STATUS_OK);
6310 if (msgid != NULL)
6311 (void) printf(gettext(" see: http://zfsonlinux.org/msg/%s\n"),
6312 msgid);
6314 if (config != NULL) {
6315 uint64_t nerr;
6316 nvlist_t **spares, **l2cache;
6317 uint_t nspares, nl2cache;
6318 pool_scan_stat_t *ps = NULL;
6320 (void) nvlist_lookup_uint64_array(nvroot,
6321 ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &c);
6322 print_scan_status(ps);
6324 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
6325 cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
6326 if (cbp->cb_namewidth < 10)
6327 cbp->cb_namewidth = 10;
6329 (void) printf(gettext("config:\n\n"));
6330 (void) printf(gettext("\t%-*s %-8s %5s %5s %5s"),
6331 cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
6332 "CKSUM");
6334 if (cbp->vcdl != NULL)
6335 print_cmd_columns(cbp->vcdl, 0);
6337 printf("\n");
6338 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
6339 B_FALSE);
6341 if (num_logs(nvroot) > 0)
6342 print_logs(zhp, cbp, nvroot);
6343 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
6344 &l2cache, &nl2cache) == 0)
6345 print_l2cache(zhp, cbp, l2cache, nl2cache);
6347 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
6348 &spares, &nspares) == 0)
6349 print_spares(zhp, cbp, spares, nspares);
6351 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
6352 &nerr) == 0) {
6353 nvlist_t *nverrlist = NULL;
6356 * If the approximate error count is small, get a
6357 * precise count by fetching the entire log and
6358 * uniquifying the results.
6360 if (nerr > 0 && nerr < 100 && !cbp->cb_verbose &&
6361 zpool_get_errlog(zhp, &nverrlist) == 0) {
6362 nvpair_t *elem;
6364 elem = NULL;
6365 nerr = 0;
6366 while ((elem = nvlist_next_nvpair(nverrlist,
6367 elem)) != NULL) {
6368 nerr++;
6371 nvlist_free(nverrlist);
6373 (void) printf("\n");
6375 if (nerr == 0)
6376 (void) printf(gettext("errors: No known data "
6377 "errors\n"));
6378 else if (!cbp->cb_verbose)
6379 (void) printf(gettext("errors: %llu data "
6380 "errors, use '-v' for a list\n"),
6381 (u_longlong_t)nerr);
6382 else
6383 print_error_log(zhp);
6386 if (cbp->cb_dedup_stats)
6387 print_dedup_stats(config);
6388 } else {
6389 (void) printf(gettext("config: The configuration cannot be "
6390 "determined.\n"));
6393 return (0);
6397 * zpool status [-c [script1,script2,...]] [-gLPvx] [-T d|u] [pool] ...
6398 * [interval [count]]
6400 * -c CMD For each vdev, run command CMD
6401 * -g Display guid for individual vdev name.
6402 * -L Follow links when resolving vdev path name.
6403 * -P Display full path for vdev name.
6404 * -v Display complete error logs
6405 * -x Display only pools with potential problems
6406 * -D Display dedup status (undocumented)
6407 * -T Display a timestamp in date(1) or Unix format
6409 * Describes the health status of all pools or some subset.
6412 zpool_do_status(int argc, char **argv)
6414 int c;
6415 int ret;
6416 float interval = 0;
6417 unsigned long count = 0;
6418 status_cbdata_t cb = { 0 };
6419 char *cmd = NULL;
6421 /* check options */
6422 while ((c = getopt(argc, argv, "c:gLPvxDT:")) != -1) {
6423 switch (c) {
6424 case 'c':
6425 if (cmd != NULL) {
6426 fprintf(stderr,
6427 gettext("Can't set -c flag twice\n"));
6428 exit(1);
6430 if ((getuid() <= 0 || geteuid() <= 0) &&
6431 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
6432 fprintf(stderr, gettext(
6433 "Can't run -c with root privileges "
6434 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
6435 exit(1);
6437 cmd = optarg;
6438 break;
6439 case 'g':
6440 cb.cb_name_flags |= VDEV_NAME_GUID;
6441 break;
6442 case 'L':
6443 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6444 break;
6445 case 'P':
6446 cb.cb_name_flags |= VDEV_NAME_PATH;
6447 break;
6448 case 'v':
6449 cb.cb_verbose = B_TRUE;
6450 break;
6451 case 'x':
6452 cb.cb_explain = B_TRUE;
6453 break;
6454 case 'D':
6455 cb.cb_dedup_stats = B_TRUE;
6456 break;
6457 case 'T':
6458 get_timestamp_arg(*optarg);
6459 break;
6460 case '?':
6461 if (optopt == 'c') {
6462 fprintf(stderr, gettext(
6463 "Current scripts in %s:\n"),
6464 ZPOOL_SCRIPTS_DIR);
6465 print_zpool_script_list();
6466 exit(0);
6467 } else {
6468 fprintf(stderr,
6469 gettext("invalid option '%c'\n"), optopt);
6471 usage(B_FALSE);
6475 argc -= optind;
6476 argv += optind;
6478 get_interval_count(&argc, argv, &interval, &count);
6480 if (argc == 0)
6481 cb.cb_allpools = B_TRUE;
6483 cb.cb_first = B_TRUE;
6484 cb.cb_print_status = B_TRUE;
6486 for (;;) {
6487 if (timestamp_fmt != NODATE)
6488 print_timestamp(timestamp_fmt);
6490 if (cmd != NULL)
6491 cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
6492 NULL, NULL, 0, 0);
6494 ret = for_each_pool(argc, argv, B_TRUE, NULL,
6495 status_callback, &cb);
6497 if (cb.vcdl != NULL)
6498 free_vdev_cmd_data_list(cb.vcdl);
6500 if (argc == 0 && cb.cb_count == 0)
6501 (void) fprintf(stderr, gettext("no pools available\n"));
6502 else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
6503 (void) printf(gettext("all pools are healthy\n"));
6505 if (ret != 0)
6506 return (ret);
6508 if (interval == 0)
6509 break;
6511 if (count != 0 && --count == 0)
6512 break;
6514 (void) fsleep(interval);
6517 return (0);
6520 typedef struct upgrade_cbdata {
6521 int cb_first;
6522 int cb_argc;
6523 uint64_t cb_version;
6524 char **cb_argv;
6525 } upgrade_cbdata_t;
6527 static int
6528 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
6530 int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
6531 int *count = (int *)unsupp_fs;
6533 if (zfs_version > ZPL_VERSION) {
6534 (void) printf(gettext("%s (v%d) is not supported by this "
6535 "implementation of ZFS.\n"),
6536 zfs_get_name(zhp), zfs_version);
6537 (*count)++;
6540 zfs_iter_filesystems(zhp, check_unsupp_fs, unsupp_fs);
6542 zfs_close(zhp);
6544 return (0);
6547 static int
6548 upgrade_version(zpool_handle_t *zhp, uint64_t version)
6550 int ret;
6551 nvlist_t *config;
6552 uint64_t oldversion;
6553 int unsupp_fs = 0;
6555 config = zpool_get_config(zhp, NULL);
6556 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6557 &oldversion) == 0);
6559 assert(SPA_VERSION_IS_SUPPORTED(oldversion));
6560 assert(oldversion < version);
6562 ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
6563 if (ret != 0)
6564 return (ret);
6566 if (unsupp_fs) {
6567 (void) fprintf(stderr, gettext("Upgrade not performed due "
6568 "to %d unsupported filesystems (max v%d).\n"),
6569 unsupp_fs, (int)ZPL_VERSION);
6570 return (1);
6573 ret = zpool_upgrade(zhp, version);
6574 if (ret != 0)
6575 return (ret);
6577 if (version >= SPA_VERSION_FEATURES) {
6578 (void) printf(gettext("Successfully upgraded "
6579 "'%s' from version %llu to feature flags.\n"),
6580 zpool_get_name(zhp), (u_longlong_t)oldversion);
6581 } else {
6582 (void) printf(gettext("Successfully upgraded "
6583 "'%s' from version %llu to version %llu.\n"),
6584 zpool_get_name(zhp), (u_longlong_t)oldversion,
6585 (u_longlong_t)version);
6588 return (0);
6591 static int
6592 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
6594 int i, ret, count;
6595 boolean_t firstff = B_TRUE;
6596 nvlist_t *enabled = zpool_get_features(zhp);
6598 count = 0;
6599 for (i = 0; i < SPA_FEATURES; i++) {
6600 const char *fname = spa_feature_table[i].fi_uname;
6601 const char *fguid = spa_feature_table[i].fi_guid;
6602 if (!nvlist_exists(enabled, fguid)) {
6603 char *propname;
6604 verify(-1 != asprintf(&propname, "feature@%s", fname));
6605 ret = zpool_set_prop(zhp, propname,
6606 ZFS_FEATURE_ENABLED);
6607 if (ret != 0) {
6608 free(propname);
6609 return (ret);
6611 count++;
6613 if (firstff) {
6614 (void) printf(gettext("Enabled the "
6615 "following features on '%s':\n"),
6616 zpool_get_name(zhp));
6617 firstff = B_FALSE;
6619 (void) printf(gettext(" %s\n"), fname);
6620 free(propname);
6624 if (countp != NULL)
6625 *countp = count;
6626 return (0);
6629 static int
6630 upgrade_cb(zpool_handle_t *zhp, void *arg)
6632 upgrade_cbdata_t *cbp = arg;
6633 nvlist_t *config;
6634 uint64_t version;
6635 boolean_t printnl = B_FALSE;
6636 int ret;
6638 config = zpool_get_config(zhp, NULL);
6639 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6640 &version) == 0);
6642 assert(SPA_VERSION_IS_SUPPORTED(version));
6644 if (version < cbp->cb_version) {
6645 cbp->cb_first = B_FALSE;
6646 ret = upgrade_version(zhp, cbp->cb_version);
6647 if (ret != 0)
6648 return (ret);
6649 printnl = B_TRUE;
6652 * If they did "zpool upgrade -a", then we could
6653 * be doing ioctls to different pools. We need
6654 * to log this history once to each pool, and bypass
6655 * the normal history logging that happens in main().
6657 (void) zpool_log_history(g_zfs, history_str);
6658 log_history = B_FALSE;
6661 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
6662 int count;
6663 ret = upgrade_enable_all(zhp, &count);
6664 if (ret != 0)
6665 return (ret);
6667 if (count > 0) {
6668 cbp->cb_first = B_FALSE;
6669 printnl = B_TRUE;
6673 if (printnl) {
6674 (void) printf(gettext("\n"));
6677 return (0);
6680 static int
6681 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
6683 upgrade_cbdata_t *cbp = arg;
6684 nvlist_t *config;
6685 uint64_t version;
6687 config = zpool_get_config(zhp, NULL);
6688 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6689 &version) == 0);
6691 assert(SPA_VERSION_IS_SUPPORTED(version));
6693 if (version < SPA_VERSION_FEATURES) {
6694 if (cbp->cb_first) {
6695 (void) printf(gettext("The following pools are "
6696 "formatted with legacy version numbers and can\n"
6697 "be upgraded to use feature flags. After "
6698 "being upgraded, these pools\nwill no "
6699 "longer be accessible by software that does not "
6700 "support feature\nflags.\n\n"));
6701 (void) printf(gettext("VER POOL\n"));
6702 (void) printf(gettext("--- ------------\n"));
6703 cbp->cb_first = B_FALSE;
6706 (void) printf("%2llu %s\n", (u_longlong_t)version,
6707 zpool_get_name(zhp));
6710 return (0);
6713 static int
6714 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
6716 upgrade_cbdata_t *cbp = arg;
6717 nvlist_t *config;
6718 uint64_t version;
6720 config = zpool_get_config(zhp, NULL);
6721 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6722 &version) == 0);
6724 if (version >= SPA_VERSION_FEATURES) {
6725 int i;
6726 boolean_t poolfirst = B_TRUE;
6727 nvlist_t *enabled = zpool_get_features(zhp);
6729 for (i = 0; i < SPA_FEATURES; i++) {
6730 const char *fguid = spa_feature_table[i].fi_guid;
6731 const char *fname = spa_feature_table[i].fi_uname;
6732 if (!nvlist_exists(enabled, fguid)) {
6733 if (cbp->cb_first) {
6734 (void) printf(gettext("\nSome "
6735 "supported features are not "
6736 "enabled on the following pools. "
6737 "Once a\nfeature is enabled the "
6738 "pool may become incompatible with "
6739 "software\nthat does not support "
6740 "the feature. See "
6741 "zpool-features(5) for "
6742 "details.\n\n"));
6743 (void) printf(gettext("POOL "
6744 "FEATURE\n"));
6745 (void) printf(gettext("------"
6746 "---------\n"));
6747 cbp->cb_first = B_FALSE;
6750 if (poolfirst) {
6751 (void) printf(gettext("%s\n"),
6752 zpool_get_name(zhp));
6753 poolfirst = B_FALSE;
6756 (void) printf(gettext(" %s\n"), fname);
6759 * If they did "zpool upgrade -a", then we could
6760 * be doing ioctls to different pools. We need
6761 * to log this history once to each pool, and bypass
6762 * the normal history logging that happens in main().
6764 (void) zpool_log_history(g_zfs, history_str);
6765 log_history = B_FALSE;
6769 return (0);
6772 /* ARGSUSED */
6773 static int
6774 upgrade_one(zpool_handle_t *zhp, void *data)
6776 boolean_t printnl = B_FALSE;
6777 upgrade_cbdata_t *cbp = data;
6778 uint64_t cur_version;
6779 int ret;
6781 if (strcmp("log", zpool_get_name(zhp)) == 0) {
6782 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
6783 "Pool 'log' must be renamed using export and import"
6784 " to upgrade.\n"));
6785 return (1);
6788 cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
6789 if (cur_version > cbp->cb_version) {
6790 (void) printf(gettext("Pool '%s' is already formatted "
6791 "using more current version '%llu'.\n\n"),
6792 zpool_get_name(zhp), (u_longlong_t)cur_version);
6793 return (0);
6796 if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
6797 (void) printf(gettext("Pool '%s' is already formatted "
6798 "using version %llu.\n\n"), zpool_get_name(zhp),
6799 (u_longlong_t)cbp->cb_version);
6800 return (0);
6803 if (cur_version != cbp->cb_version) {
6804 printnl = B_TRUE;
6805 ret = upgrade_version(zhp, cbp->cb_version);
6806 if (ret != 0)
6807 return (ret);
6810 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
6811 int count = 0;
6812 ret = upgrade_enable_all(zhp, &count);
6813 if (ret != 0)
6814 return (ret);
6816 if (count != 0) {
6817 printnl = B_TRUE;
6818 } else if (cur_version == SPA_VERSION) {
6819 (void) printf(gettext("Pool '%s' already has all "
6820 "supported features enabled.\n"),
6821 zpool_get_name(zhp));
6825 if (printnl) {
6826 (void) printf(gettext("\n"));
6829 return (0);
6833 * zpool upgrade
6834 * zpool upgrade -v
6835 * zpool upgrade [-V version] <-a | pool ...>
6837 * With no arguments, display downrev'd ZFS pool available for upgrade.
6838 * Individual pools can be upgraded by specifying the pool, and '-a' will
6839 * upgrade all pools.
6842 zpool_do_upgrade(int argc, char **argv)
6844 int c;
6845 upgrade_cbdata_t cb = { 0 };
6846 int ret = 0;
6847 boolean_t showversions = B_FALSE;
6848 boolean_t upgradeall = B_FALSE;
6849 char *end;
6852 /* check options */
6853 while ((c = getopt(argc, argv, ":avV:")) != -1) {
6854 switch (c) {
6855 case 'a':
6856 upgradeall = B_TRUE;
6857 break;
6858 case 'v':
6859 showversions = B_TRUE;
6860 break;
6861 case 'V':
6862 cb.cb_version = strtoll(optarg, &end, 10);
6863 if (*end != '\0' ||
6864 !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
6865 (void) fprintf(stderr,
6866 gettext("invalid version '%s'\n"), optarg);
6867 usage(B_FALSE);
6869 break;
6870 case ':':
6871 (void) fprintf(stderr, gettext("missing argument for "
6872 "'%c' option\n"), optopt);
6873 usage(B_FALSE);
6874 break;
6875 case '?':
6876 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6877 optopt);
6878 usage(B_FALSE);
6882 cb.cb_argc = argc;
6883 cb.cb_argv = argv;
6884 argc -= optind;
6885 argv += optind;
6887 if (cb.cb_version == 0) {
6888 cb.cb_version = SPA_VERSION;
6889 } else if (!upgradeall && argc == 0) {
6890 (void) fprintf(stderr, gettext("-V option is "
6891 "incompatible with other arguments\n"));
6892 usage(B_FALSE);
6895 if (showversions) {
6896 if (upgradeall || argc != 0) {
6897 (void) fprintf(stderr, gettext("-v option is "
6898 "incompatible with other arguments\n"));
6899 usage(B_FALSE);
6901 } else if (upgradeall) {
6902 if (argc != 0) {
6903 (void) fprintf(stderr, gettext("-a option should not "
6904 "be used along with a pool name\n"));
6905 usage(B_FALSE);
6909 (void) printf(gettext("This system supports ZFS pool feature "
6910 "flags.\n\n"));
6911 if (showversions) {
6912 int i;
6914 (void) printf(gettext("The following features are "
6915 "supported:\n\n"));
6916 (void) printf(gettext("FEAT DESCRIPTION\n"));
6917 (void) printf("----------------------------------------------"
6918 "---------------\n");
6919 for (i = 0; i < SPA_FEATURES; i++) {
6920 zfeature_info_t *fi = &spa_feature_table[i];
6921 const char *ro =
6922 (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
6923 " (read-only compatible)" : "";
6925 (void) printf("%-37s%s\n", fi->fi_uname, ro);
6926 (void) printf(" %s\n", fi->fi_desc);
6928 (void) printf("\n");
6930 (void) printf(gettext("The following legacy versions are also "
6931 "supported:\n\n"));
6932 (void) printf(gettext("VER DESCRIPTION\n"));
6933 (void) printf("--- -----------------------------------------"
6934 "---------------\n");
6935 (void) printf(gettext(" 1 Initial ZFS version\n"));
6936 (void) printf(gettext(" 2 Ditto blocks "
6937 "(replicated metadata)\n"));
6938 (void) printf(gettext(" 3 Hot spares and double parity "
6939 "RAID-Z\n"));
6940 (void) printf(gettext(" 4 zpool history\n"));
6941 (void) printf(gettext(" 5 Compression using the gzip "
6942 "algorithm\n"));
6943 (void) printf(gettext(" 6 bootfs pool property\n"));
6944 (void) printf(gettext(" 7 Separate intent log devices\n"));
6945 (void) printf(gettext(" 8 Delegated administration\n"));
6946 (void) printf(gettext(" 9 refquota and refreservation "
6947 "properties\n"));
6948 (void) printf(gettext(" 10 Cache devices\n"));
6949 (void) printf(gettext(" 11 Improved scrub performance\n"));
6950 (void) printf(gettext(" 12 Snapshot properties\n"));
6951 (void) printf(gettext(" 13 snapused property\n"));
6952 (void) printf(gettext(" 14 passthrough-x aclinherit\n"));
6953 (void) printf(gettext(" 15 user/group space accounting\n"));
6954 (void) printf(gettext(" 16 stmf property support\n"));
6955 (void) printf(gettext(" 17 Triple-parity RAID-Z\n"));
6956 (void) printf(gettext(" 18 Snapshot user holds\n"));
6957 (void) printf(gettext(" 19 Log device removal\n"));
6958 (void) printf(gettext(" 20 Compression using zle "
6959 "(zero-length encoding)\n"));
6960 (void) printf(gettext(" 21 Deduplication\n"));
6961 (void) printf(gettext(" 22 Received properties\n"));
6962 (void) printf(gettext(" 23 Slim ZIL\n"));
6963 (void) printf(gettext(" 24 System attributes\n"));
6964 (void) printf(gettext(" 25 Improved scrub stats\n"));
6965 (void) printf(gettext(" 26 Improved snapshot deletion "
6966 "performance\n"));
6967 (void) printf(gettext(" 27 Improved snapshot creation "
6968 "performance\n"));
6969 (void) printf(gettext(" 28 Multiple vdev replacements\n"));
6970 (void) printf(gettext("\nFor more information on a particular "
6971 "version, including supported releases,\n"));
6972 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
6973 } else if (argc == 0 && upgradeall) {
6974 cb.cb_first = B_TRUE;
6975 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
6976 if (ret == 0 && cb.cb_first) {
6977 if (cb.cb_version == SPA_VERSION) {
6978 (void) printf(gettext("All pools are already "
6979 "formatted using feature flags.\n\n"));
6980 (void) printf(gettext("Every feature flags "
6981 "pool already has all supported features "
6982 "enabled.\n"));
6983 } else {
6984 (void) printf(gettext("All pools are already "
6985 "formatted with version %llu or higher.\n"),
6986 (u_longlong_t)cb.cb_version);
6989 } else if (argc == 0) {
6990 cb.cb_first = B_TRUE;
6991 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
6992 assert(ret == 0);
6994 if (cb.cb_first) {
6995 (void) printf(gettext("All pools are formatted "
6996 "using feature flags.\n\n"));
6997 } else {
6998 (void) printf(gettext("\nUse 'zpool upgrade -v' "
6999 "for a list of available legacy versions.\n"));
7002 cb.cb_first = B_TRUE;
7003 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
7004 assert(ret == 0);
7006 if (cb.cb_first) {
7007 (void) printf(gettext("Every feature flags pool has "
7008 "all supported features enabled.\n"));
7009 } else {
7010 (void) printf(gettext("\n"));
7012 } else {
7013 ret = for_each_pool(argc, argv, B_FALSE, NULL,
7014 upgrade_one, &cb);
7017 return (ret);
7020 typedef struct hist_cbdata {
7021 boolean_t first;
7022 boolean_t longfmt;
7023 boolean_t internal;
7024 } hist_cbdata_t;
7027 * Print out the command history for a specific pool.
7029 static int
7030 get_history_one(zpool_handle_t *zhp, void *data)
7032 nvlist_t *nvhis;
7033 nvlist_t **records;
7034 uint_t numrecords;
7035 int ret, i;
7036 hist_cbdata_t *cb = (hist_cbdata_t *)data;
7038 cb->first = B_FALSE;
7040 (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
7042 if ((ret = zpool_get_history(zhp, &nvhis)) != 0)
7043 return (ret);
7045 verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
7046 &records, &numrecords) == 0);
7047 for (i = 0; i < numrecords; i++) {
7048 nvlist_t *rec = records[i];
7049 char tbuf[30] = "";
7051 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
7052 time_t tsec;
7053 struct tm t;
7055 tsec = fnvlist_lookup_uint64(records[i],
7056 ZPOOL_HIST_TIME);
7057 (void) localtime_r(&tsec, &t);
7058 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
7061 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
7062 (void) printf("%s %s", tbuf,
7063 fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
7064 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
7065 int ievent =
7066 fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
7067 if (!cb->internal)
7068 continue;
7069 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
7070 (void) printf("%s unrecognized record:\n",
7071 tbuf);
7072 dump_nvlist(rec, 4);
7073 continue;
7075 (void) printf("%s [internal %s txg:%lld] %s", tbuf,
7076 zfs_history_event_names[ievent],
7077 (longlong_t)fnvlist_lookup_uint64(
7078 rec, ZPOOL_HIST_TXG),
7079 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
7080 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
7081 if (!cb->internal)
7082 continue;
7083 (void) printf("%s [txg:%lld] %s", tbuf,
7084 (longlong_t)fnvlist_lookup_uint64(
7085 rec, ZPOOL_HIST_TXG),
7086 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
7087 if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
7088 (void) printf(" %s (%llu)",
7089 fnvlist_lookup_string(rec,
7090 ZPOOL_HIST_DSNAME),
7091 (u_longlong_t)fnvlist_lookup_uint64(rec,
7092 ZPOOL_HIST_DSID));
7094 (void) printf(" %s", fnvlist_lookup_string(rec,
7095 ZPOOL_HIST_INT_STR));
7096 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
7097 if (!cb->internal)
7098 continue;
7099 (void) printf("%s ioctl %s\n", tbuf,
7100 fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
7101 if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
7102 (void) printf(" input:\n");
7103 dump_nvlist(fnvlist_lookup_nvlist(rec,
7104 ZPOOL_HIST_INPUT_NVL), 8);
7106 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
7107 (void) printf(" output:\n");
7108 dump_nvlist(fnvlist_lookup_nvlist(rec,
7109 ZPOOL_HIST_OUTPUT_NVL), 8);
7111 } else {
7112 if (!cb->internal)
7113 continue;
7114 (void) printf("%s unrecognized record:\n", tbuf);
7115 dump_nvlist(rec, 4);
7118 if (!cb->longfmt) {
7119 (void) printf("\n");
7120 continue;
7122 (void) printf(" [");
7123 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
7124 uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
7125 struct passwd *pwd = getpwuid(who);
7126 (void) printf("user %d ", (int)who);
7127 if (pwd != NULL)
7128 (void) printf("(%s) ", pwd->pw_name);
7130 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
7131 (void) printf("on %s",
7132 fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
7134 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
7135 (void) printf(":%s",
7136 fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
7139 (void) printf("]");
7140 (void) printf("\n");
7142 (void) printf("\n");
7143 nvlist_free(nvhis);
7145 return (ret);
7149 * zpool history <pool>
7151 * Displays the history of commands that modified pools.
7154 zpool_do_history(int argc, char **argv)
7156 hist_cbdata_t cbdata = { 0 };
7157 int ret;
7158 int c;
7160 cbdata.first = B_TRUE;
7161 /* check options */
7162 while ((c = getopt(argc, argv, "li")) != -1) {
7163 switch (c) {
7164 case 'l':
7165 cbdata.longfmt = B_TRUE;
7166 break;
7167 case 'i':
7168 cbdata.internal = B_TRUE;
7169 break;
7170 case '?':
7171 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7172 optopt);
7173 usage(B_FALSE);
7176 argc -= optind;
7177 argv += optind;
7179 ret = for_each_pool(argc, argv, B_FALSE, NULL, get_history_one,
7180 &cbdata);
7182 if (argc == 0 && cbdata.first == B_TRUE) {
7183 (void) fprintf(stderr, gettext("no pools available\n"));
7184 return (0);
7187 return (ret);
7190 typedef struct ev_opts {
7191 int verbose;
7192 int scripted;
7193 int follow;
7194 int clear;
7195 } ev_opts_t;
7197 static void
7198 zpool_do_events_short(nvlist_t *nvl)
7200 char ctime_str[26], str[32], *ptr;
7201 int64_t *tv;
7202 uint_t n;
7204 verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
7205 memset(str, ' ', 32);
7206 (void) ctime_r((const time_t *)&tv[0], ctime_str);
7207 (void) strncpy(str, ctime_str+4, 6); /* 'Jun 30' */
7208 (void) strncpy(str+7, ctime_str+20, 4); /* '1993' */
7209 (void) strncpy(str+12, ctime_str+11, 8); /* '21:49:08' */
7210 (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
7211 (void) printf(gettext("%s "), str);
7213 verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
7214 (void) printf(gettext("%s\n"), ptr);
7217 static void
7218 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
7220 nvpair_t *nvp;
7222 for (nvp = nvlist_next_nvpair(nvl, NULL);
7223 nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
7225 data_type_t type = nvpair_type(nvp);
7226 const char *name = nvpair_name(nvp);
7228 boolean_t b;
7229 uint8_t i8;
7230 uint16_t i16;
7231 uint32_t i32;
7232 uint64_t i64;
7233 char *str;
7234 nvlist_t *cnv;
7236 printf(gettext("%*s%s = "), depth, "", name);
7238 switch (type) {
7239 case DATA_TYPE_BOOLEAN:
7240 printf(gettext("%s"), "1");
7241 break;
7243 case DATA_TYPE_BOOLEAN_VALUE:
7244 (void) nvpair_value_boolean_value(nvp, &b);
7245 printf(gettext("%s"), b ? "1" : "0");
7246 break;
7248 case DATA_TYPE_BYTE:
7249 (void) nvpair_value_byte(nvp, &i8);
7250 printf(gettext("0x%x"), i8);
7251 break;
7253 case DATA_TYPE_INT8:
7254 (void) nvpair_value_int8(nvp, (void *)&i8);
7255 printf(gettext("0x%x"), i8);
7256 break;
7258 case DATA_TYPE_UINT8:
7259 (void) nvpair_value_uint8(nvp, &i8);
7260 printf(gettext("0x%x"), i8);
7261 break;
7263 case DATA_TYPE_INT16:
7264 (void) nvpair_value_int16(nvp, (void *)&i16);
7265 printf(gettext("0x%x"), i16);
7266 break;
7268 case DATA_TYPE_UINT16:
7269 (void) nvpair_value_uint16(nvp, &i16);
7270 printf(gettext("0x%x"), i16);
7271 break;
7273 case DATA_TYPE_INT32:
7274 (void) nvpair_value_int32(nvp, (void *)&i32);
7275 printf(gettext("0x%x"), i32);
7276 break;
7278 case DATA_TYPE_UINT32:
7279 (void) nvpair_value_uint32(nvp, &i32);
7280 printf(gettext("0x%x"), i32);
7281 break;
7283 case DATA_TYPE_INT64:
7284 (void) nvpair_value_int64(nvp, (void *)&i64);
7285 printf(gettext("0x%llx"), (u_longlong_t)i64);
7286 break;
7288 case DATA_TYPE_UINT64:
7289 (void) nvpair_value_uint64(nvp, &i64);
7291 * translate vdev state values to readable
7292 * strings to aide zpool events consumers
7294 if (strcmp(name,
7295 FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
7296 strcmp(name,
7297 FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
7298 printf(gettext("\"%s\" (0x%llx)"),
7299 zpool_state_to_name(i64, VDEV_AUX_NONE),
7300 (u_longlong_t)i64);
7301 } else {
7302 printf(gettext("0x%llx"), (u_longlong_t)i64);
7304 break;
7306 case DATA_TYPE_HRTIME:
7307 (void) nvpair_value_hrtime(nvp, (void *)&i64);
7308 printf(gettext("0x%llx"), (u_longlong_t)i64);
7309 break;
7311 case DATA_TYPE_STRING:
7312 (void) nvpair_value_string(nvp, &str);
7313 printf(gettext("\"%s\""), str ? str : "<NULL>");
7314 break;
7316 case DATA_TYPE_NVLIST:
7317 printf(gettext("(embedded nvlist)\n"));
7318 (void) nvpair_value_nvlist(nvp, &cnv);
7319 zpool_do_events_nvprint(cnv, depth + 8);
7320 printf(gettext("%*s(end %s)"), depth, "", name);
7321 break;
7323 case DATA_TYPE_NVLIST_ARRAY: {
7324 nvlist_t **val;
7325 uint_t i, nelem;
7327 (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
7328 printf(gettext("(%d embedded nvlists)\n"), nelem);
7329 for (i = 0; i < nelem; i++) {
7330 printf(gettext("%*s%s[%d] = %s\n"),
7331 depth, "", name, i, "(embedded nvlist)");
7332 zpool_do_events_nvprint(val[i], depth + 8);
7333 printf(gettext("%*s(end %s[%i])\n"),
7334 depth, "", name, i);
7336 printf(gettext("%*s(end %s)\n"), depth, "", name);
7338 break;
7340 case DATA_TYPE_INT8_ARRAY: {
7341 int8_t *val;
7342 uint_t i, nelem;
7344 (void) nvpair_value_int8_array(nvp, &val, &nelem);
7345 for (i = 0; i < nelem; i++)
7346 printf(gettext("0x%x "), val[i]);
7348 break;
7351 case DATA_TYPE_UINT8_ARRAY: {
7352 uint8_t *val;
7353 uint_t i, nelem;
7355 (void) nvpair_value_uint8_array(nvp, &val, &nelem);
7356 for (i = 0; i < nelem; i++)
7357 printf(gettext("0x%x "), val[i]);
7359 break;
7362 case DATA_TYPE_INT16_ARRAY: {
7363 int16_t *val;
7364 uint_t i, nelem;
7366 (void) nvpair_value_int16_array(nvp, &val, &nelem);
7367 for (i = 0; i < nelem; i++)
7368 printf(gettext("0x%x "), val[i]);
7370 break;
7373 case DATA_TYPE_UINT16_ARRAY: {
7374 uint16_t *val;
7375 uint_t i, nelem;
7377 (void) nvpair_value_uint16_array(nvp, &val, &nelem);
7378 for (i = 0; i < nelem; i++)
7379 printf(gettext("0x%x "), val[i]);
7381 break;
7384 case DATA_TYPE_INT32_ARRAY: {
7385 int32_t *val;
7386 uint_t i, nelem;
7388 (void) nvpair_value_int32_array(nvp, &val, &nelem);
7389 for (i = 0; i < nelem; i++)
7390 printf(gettext("0x%x "), val[i]);
7392 break;
7395 case DATA_TYPE_UINT32_ARRAY: {
7396 uint32_t *val;
7397 uint_t i, nelem;
7399 (void) nvpair_value_uint32_array(nvp, &val, &nelem);
7400 for (i = 0; i < nelem; i++)
7401 printf(gettext("0x%x "), val[i]);
7403 break;
7406 case DATA_TYPE_INT64_ARRAY: {
7407 int64_t *val;
7408 uint_t i, nelem;
7410 (void) nvpair_value_int64_array(nvp, &val, &nelem);
7411 for (i = 0; i < nelem; i++)
7412 printf(gettext("0x%llx "),
7413 (u_longlong_t)val[i]);
7415 break;
7418 case DATA_TYPE_UINT64_ARRAY: {
7419 uint64_t *val;
7420 uint_t i, nelem;
7422 (void) nvpair_value_uint64_array(nvp, &val, &nelem);
7423 for (i = 0; i < nelem; i++)
7424 printf(gettext("0x%llx "),
7425 (u_longlong_t)val[i]);
7427 break;
7430 case DATA_TYPE_STRING_ARRAY: {
7431 char **str;
7432 uint_t i, nelem;
7434 (void) nvpair_value_string_array(nvp, &str, &nelem);
7435 for (i = 0; i < nelem; i++)
7436 printf(gettext("\"%s\" "),
7437 str[i] ? str[i] : "<NULL>");
7439 break;
7442 case DATA_TYPE_BOOLEAN_ARRAY:
7443 case DATA_TYPE_BYTE_ARRAY:
7444 case DATA_TYPE_DOUBLE:
7445 case DATA_TYPE_UNKNOWN:
7446 printf(gettext("<unknown>"));
7447 break;
7450 printf(gettext("\n"));
7454 static int
7455 zpool_do_events_next(ev_opts_t *opts)
7457 nvlist_t *nvl;
7458 int zevent_fd, ret, dropped;
7460 zevent_fd = open(ZFS_DEV, O_RDWR);
7461 VERIFY(zevent_fd >= 0);
7463 if (!opts->scripted)
7464 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
7466 while (1) {
7467 ret = zpool_events_next(g_zfs, &nvl, &dropped,
7468 (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
7469 if (ret || nvl == NULL)
7470 break;
7472 if (dropped > 0)
7473 (void) printf(gettext("dropped %d events\n"), dropped);
7475 zpool_do_events_short(nvl);
7477 if (opts->verbose) {
7478 zpool_do_events_nvprint(nvl, 8);
7479 printf(gettext("\n"));
7481 (void) fflush(stdout);
7483 nvlist_free(nvl);
7486 VERIFY(0 == close(zevent_fd));
7488 return (ret);
7491 static int
7492 zpool_do_events_clear(ev_opts_t *opts)
7494 int count, ret;
7496 ret = zpool_events_clear(g_zfs, &count);
7497 if (!ret)
7498 (void) printf(gettext("cleared %d events\n"), count);
7500 return (ret);
7504 * zpool events [-vfc]
7506 * Displays events logs by ZFS.
7509 zpool_do_events(int argc, char **argv)
7511 ev_opts_t opts = { 0 };
7512 int ret;
7513 int c;
7515 /* check options */
7516 while ((c = getopt(argc, argv, "vHfc")) != -1) {
7517 switch (c) {
7518 case 'v':
7519 opts.verbose = 1;
7520 break;
7521 case 'H':
7522 opts.scripted = 1;
7523 break;
7524 case 'f':
7525 opts.follow = 1;
7526 break;
7527 case 'c':
7528 opts.clear = 1;
7529 break;
7530 case '?':
7531 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7532 optopt);
7533 usage(B_FALSE);
7536 argc -= optind;
7537 argv += optind;
7539 if (opts.clear)
7540 ret = zpool_do_events_clear(&opts);
7541 else
7542 ret = zpool_do_events_next(&opts);
7544 return (ret);
7547 static int
7548 get_callback(zpool_handle_t *zhp, void *data)
7550 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
7551 char value[MAXNAMELEN];
7552 zprop_source_t srctype;
7553 zprop_list_t *pl;
7555 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
7558 * Skip the special fake placeholder. This will also skip
7559 * over the name property when 'all' is specified.
7561 if (pl->pl_prop == ZPOOL_PROP_NAME &&
7562 pl == cbp->cb_proplist)
7563 continue;
7565 if (pl->pl_prop == ZPROP_INVAL &&
7566 (zpool_prop_feature(pl->pl_user_prop) ||
7567 zpool_prop_unsupported(pl->pl_user_prop))) {
7568 srctype = ZPROP_SRC_LOCAL;
7570 if (zpool_prop_get_feature(zhp, pl->pl_user_prop,
7571 value, sizeof (value)) == 0) {
7572 zprop_print_one_property(zpool_get_name(zhp),
7573 cbp, pl->pl_user_prop, value, srctype,
7574 NULL, NULL);
7576 } else {
7577 if (zpool_get_prop(zhp, pl->pl_prop, value,
7578 sizeof (value), &srctype, cbp->cb_literal) != 0)
7579 continue;
7581 zprop_print_one_property(zpool_get_name(zhp), cbp,
7582 zpool_prop_to_name(pl->pl_prop), value, srctype,
7583 NULL, NULL);
7586 return (0);
7590 * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
7592 * -H Scripted mode. Don't display headers, and separate properties
7593 * by a single tab.
7594 * -o List of columns to display. Defaults to
7595 * "name,property,value,source".
7596 * -p Display values in parsable (exact) format.
7598 * Get properties of pools in the system. Output space statistics
7599 * for each one as well as other attributes.
7602 zpool_do_get(int argc, char **argv)
7604 zprop_get_cbdata_t cb = { 0 };
7605 zprop_list_t fake_name = { 0 };
7606 int ret;
7607 int c, i;
7608 char *value;
7610 cb.cb_first = B_TRUE;
7613 * Set up default columns and sources.
7615 cb.cb_sources = ZPROP_SRC_ALL;
7616 cb.cb_columns[0] = GET_COL_NAME;
7617 cb.cb_columns[1] = GET_COL_PROPERTY;
7618 cb.cb_columns[2] = GET_COL_VALUE;
7619 cb.cb_columns[3] = GET_COL_SOURCE;
7620 cb.cb_type = ZFS_TYPE_POOL;
7622 /* check options */
7623 while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
7624 switch (c) {
7625 case 'p':
7626 cb.cb_literal = B_TRUE;
7627 break;
7628 case 'H':
7629 cb.cb_scripted = B_TRUE;
7630 break;
7631 case 'o':
7632 bzero(&cb.cb_columns, sizeof (cb.cb_columns));
7633 i = 0;
7634 while (*optarg != '\0') {
7635 static char *col_subopts[] =
7636 { "name", "property", "value", "source",
7637 "all", NULL };
7639 if (i == ZFS_GET_NCOLS) {
7640 (void) fprintf(stderr, gettext("too "
7641 "many fields given to -o "
7642 "option\n"));
7643 usage(B_FALSE);
7646 switch (getsubopt(&optarg, col_subopts,
7647 &value)) {
7648 case 0:
7649 cb.cb_columns[i++] = GET_COL_NAME;
7650 break;
7651 case 1:
7652 cb.cb_columns[i++] = GET_COL_PROPERTY;
7653 break;
7654 case 2:
7655 cb.cb_columns[i++] = GET_COL_VALUE;
7656 break;
7657 case 3:
7658 cb.cb_columns[i++] = GET_COL_SOURCE;
7659 break;
7660 case 4:
7661 if (i > 0) {
7662 (void) fprintf(stderr,
7663 gettext("\"all\" conflicts "
7664 "with specific fields "
7665 "given to -o option\n"));
7666 usage(B_FALSE);
7668 cb.cb_columns[0] = GET_COL_NAME;
7669 cb.cb_columns[1] = GET_COL_PROPERTY;
7670 cb.cb_columns[2] = GET_COL_VALUE;
7671 cb.cb_columns[3] = GET_COL_SOURCE;
7672 i = ZFS_GET_NCOLS;
7673 break;
7674 default:
7675 (void) fprintf(stderr,
7676 gettext("invalid column name "
7677 "'%s'\n"), value);
7678 usage(B_FALSE);
7681 break;
7682 case '?':
7683 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7684 optopt);
7685 usage(B_FALSE);
7689 argc -= optind;
7690 argv += optind;
7692 if (argc < 1) {
7693 (void) fprintf(stderr, gettext("missing property "
7694 "argument\n"));
7695 usage(B_FALSE);
7698 if (zprop_get_list(g_zfs, argv[0], &cb.cb_proplist,
7699 ZFS_TYPE_POOL) != 0)
7700 usage(B_FALSE);
7702 argc--;
7703 argv++;
7705 if (cb.cb_proplist != NULL) {
7706 fake_name.pl_prop = ZPOOL_PROP_NAME;
7707 fake_name.pl_width = strlen(gettext("NAME"));
7708 fake_name.pl_next = cb.cb_proplist;
7709 cb.cb_proplist = &fake_name;
7712 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist,
7713 get_callback, &cb);
7715 if (cb.cb_proplist == &fake_name)
7716 zprop_free_list(fake_name.pl_next);
7717 else
7718 zprop_free_list(cb.cb_proplist);
7720 return (ret);
7723 typedef struct set_cbdata {
7724 char *cb_propname;
7725 char *cb_value;
7726 boolean_t cb_any_successful;
7727 } set_cbdata_t;
7730 set_callback(zpool_handle_t *zhp, void *data)
7732 int error;
7733 set_cbdata_t *cb = (set_cbdata_t *)data;
7735 error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
7737 if (!error)
7738 cb->cb_any_successful = B_TRUE;
7740 return (error);
7744 zpool_do_set(int argc, char **argv)
7746 set_cbdata_t cb = { 0 };
7747 int error;
7749 if (argc > 1 && argv[1][0] == '-') {
7750 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7751 argv[1][1]);
7752 usage(B_FALSE);
7755 if (argc < 2) {
7756 (void) fprintf(stderr, gettext("missing property=value "
7757 "argument\n"));
7758 usage(B_FALSE);
7761 if (argc < 3) {
7762 (void) fprintf(stderr, gettext("missing pool name\n"));
7763 usage(B_FALSE);
7766 if (argc > 3) {
7767 (void) fprintf(stderr, gettext("too many pool names\n"));
7768 usage(B_FALSE);
7771 cb.cb_propname = argv[1];
7772 cb.cb_value = strchr(cb.cb_propname, '=');
7773 if (cb.cb_value == NULL) {
7774 (void) fprintf(stderr, gettext("missing value in "
7775 "property=value argument\n"));
7776 usage(B_FALSE);
7779 *(cb.cb_value) = '\0';
7780 cb.cb_value++;
7782 error = for_each_pool(argc - 2, argv + 2, B_TRUE, NULL,
7783 set_callback, &cb);
7785 return (error);
7788 static int
7789 find_command_idx(char *command, int *idx)
7791 int i;
7793 for (i = 0; i < NCOMMAND; i++) {
7794 if (command_table[i].name == NULL)
7795 continue;
7797 if (strcmp(command, command_table[i].name) == 0) {
7798 *idx = i;
7799 return (0);
7802 return (1);
7806 main(int argc, char **argv)
7808 int ret = 0;
7809 int i = 0;
7810 char *cmdname;
7812 (void) setlocale(LC_ALL, "");
7813 (void) textdomain(TEXT_DOMAIN);
7814 srand(time(NULL));
7816 dprintf_setup(&argc, argv);
7818 opterr = 0;
7821 * Make sure the user has specified some command.
7823 if (argc < 2) {
7824 (void) fprintf(stderr, gettext("missing command\n"));
7825 usage(B_FALSE);
7828 cmdname = argv[1];
7831 * Special case '-?'
7833 if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
7834 usage(B_TRUE);
7836 if ((g_zfs = libzfs_init()) == NULL) {
7837 (void) fprintf(stderr, "%s", libzfs_error_init(errno));
7838 return (1);
7841 libzfs_print_on_error(g_zfs, B_TRUE);
7843 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
7846 * Run the appropriate command.
7848 if (find_command_idx(cmdname, &i) == 0) {
7849 current_command = &command_table[i];
7850 ret = command_table[i].func(argc - 1, argv + 1);
7851 } else if (strchr(cmdname, '=')) {
7852 verify(find_command_idx("set", &i) == 0);
7853 current_command = &command_table[i];
7854 ret = command_table[i].func(argc, argv);
7855 } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
7857 * 'freeze' is a vile debugging abomination, so we treat
7858 * it as such.
7860 char buf[16384];
7861 int fd = open(ZFS_DEV, O_RDWR);
7862 (void) strlcpy((void *)buf, argv[2], sizeof (buf));
7863 return (!!ioctl(fd, ZFS_IOC_POOL_FREEZE, buf));
7864 } else {
7865 (void) fprintf(stderr, gettext("unrecognized "
7866 "command '%s'\n"), cmdname);
7867 usage(B_FALSE);
7868 ret = 1;
7871 if (ret == 0 && log_history)
7872 (void) zpool_log_history(g_zfs, history_str);
7874 libzfs_fini(g_zfs);
7877 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
7878 * for the purposes of running ::findleaks.
7880 if (getenv("ZFS_ABORT") != NULL) {
7881 (void) printf("dumping core by request\n");
7882 abort();
7885 return (ret);