]> git.proxmox.com Git - mirror_zfs.git/blob - cmd/zpool/zpool_main.c
Allow for '-o feature@<feature>=disabled' on the command line
[mirror_zfs.git] / cmd / zpool / zpool_main.c
1 /*
2 * CDDL HEADER START
3 *
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.
7 *
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.
12 *
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]
18 *
19 * CDDL HEADER END
20 */
21
22 /*
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 */
30
31 #include <assert.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <libgen.h>
37 #include <libintl.h>
38 #include <libuutil.h>
39 #include <locale.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <strings.h>
44 #include <unistd.h>
45 #include <pwd.h>
46 #include <zone.h>
47 #include <zfs_prop.h>
48 #include <sys/fs/zfs.h>
49 #include <sys/stat.h>
50 #include <sys/fm/fs/zfs.h>
51 #include <sys/fm/util.h>
52 #include <sys/fm/protocol.h>
53 #include <sys/zfs_ioctl.h>
54 #include <math.h>
55
56 #include <libzfs.h>
57
58 #include "zpool_util.h"
59 #include "zfs_comutil.h"
60 #include "zfeature_common.h"
61
62 #include "statcommon.h"
63
64 static int zpool_do_create(int, char **);
65 static int zpool_do_destroy(int, char **);
66
67 static int zpool_do_add(int, char **);
68 static int zpool_do_remove(int, char **);
69 static int zpool_do_labelclear(int, char **);
70
71 static int zpool_do_list(int, char **);
72 static int zpool_do_iostat(int, char **);
73 static int zpool_do_status(int, char **);
74
75 static int zpool_do_online(int, char **);
76 static int zpool_do_offline(int, char **);
77 static int zpool_do_clear(int, char **);
78 static int zpool_do_reopen(int, char **);
79
80 static int zpool_do_reguid(int, char **);
81
82 static int zpool_do_attach(int, char **);
83 static int zpool_do_detach(int, char **);
84 static int zpool_do_replace(int, char **);
85 static int zpool_do_split(int, char **);
86
87 static int zpool_do_scrub(int, char **);
88
89 static int zpool_do_import(int, char **);
90 static int zpool_do_export(int, char **);
91
92 static int zpool_do_upgrade(int, char **);
93
94 static int zpool_do_history(int, char **);
95 static int zpool_do_events(int, char **);
96
97 static int zpool_do_get(int, char **);
98 static int zpool_do_set(int, char **);
99
100 /*
101 * These libumem hooks provide a reasonable set of defaults for the allocator's
102 * debugging facilities.
103 */
104
105 #ifdef DEBUG
106 const char *
107 _umem_debug_init(void)
108 {
109 return ("default,verbose"); /* $UMEM_DEBUG setting */
110 }
111
112 const char *
113 _umem_logging_init(void)
114 {
115 return ("fail,contents"); /* $UMEM_LOGGING setting */
116 }
117 #endif
118
119 typedef enum {
120 HELP_ADD,
121 HELP_ATTACH,
122 HELP_CLEAR,
123 HELP_CREATE,
124 HELP_DESTROY,
125 HELP_DETACH,
126 HELP_EXPORT,
127 HELP_HISTORY,
128 HELP_IMPORT,
129 HELP_IOSTAT,
130 HELP_LABELCLEAR,
131 HELP_LIST,
132 HELP_OFFLINE,
133 HELP_ONLINE,
134 HELP_REPLACE,
135 HELP_REMOVE,
136 HELP_SCRUB,
137 HELP_STATUS,
138 HELP_UPGRADE,
139 HELP_EVENTS,
140 HELP_GET,
141 HELP_SET,
142 HELP_SPLIT,
143 HELP_REGUID,
144 HELP_REOPEN
145 } zpool_help_t;
146
147
148 /*
149 * Flags for stats to display with "zpool iostats"
150 */
151 enum iostat_type {
152 IOS_DEFAULT = 0,
153 IOS_LATENCY = 1,
154 IOS_QUEUES = 2,
155 IOS_L_HISTO = 3,
156 IOS_RQ_HISTO = 4,
157 IOS_COUNT, /* always last element */
158 };
159
160 /* iostat_type entries as bitmasks */
161 #define IOS_DEFAULT_M (1ULL << IOS_DEFAULT)
162 #define IOS_LATENCY_M (1ULL << IOS_LATENCY)
163 #define IOS_QUEUES_M (1ULL << IOS_QUEUES)
164 #define IOS_L_HISTO_M (1ULL << IOS_L_HISTO)
165 #define IOS_RQ_HISTO_M (1ULL << IOS_RQ_HISTO)
166
167 /* Mask of all the histo bits */
168 #define IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
169
170 /*
171 * Lookup table for iostat flags to nvlist names. Basically a list
172 * of all the nvlists a flag requires. Also specifies the order in
173 * which data gets printed in zpool iostat.
174 */
175 static const char *vsx_type_to_nvlist[IOS_COUNT][11] = {
176 [IOS_L_HISTO] = {
177 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
178 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
179 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
180 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
181 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
182 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
183 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
184 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
185 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
186 NULL},
187 [IOS_LATENCY] = {
188 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
189 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
190 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
191 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
192 NULL},
193 [IOS_QUEUES] = {
194 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
195 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
196 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
197 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
198 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
199 NULL},
200 [IOS_RQ_HISTO] = {
201 ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
202 ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
203 ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
204 ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
205 ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
206 ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
207 ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
208 ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
209 ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
210 ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
211 NULL},
212 };
213
214
215 /*
216 * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
217 * Right now, only one histo bit is ever set at one time, so we can
218 * just do a highbit64(a)
219 */
220 #define IOS_HISTO_IDX(a) (highbit64(a & IOS_ANYHISTO_M) - 1)
221
222 typedef struct zpool_command {
223 const char *name;
224 int (*func)(int, char **);
225 zpool_help_t usage;
226 } zpool_command_t;
227
228 /*
229 * Master command table. Each ZFS command has a name, associated function, and
230 * usage message. The usage messages need to be internationalized, so we have
231 * to have a function to return the usage message based on a command index.
232 *
233 * These commands are organized according to how they are displayed in the usage
234 * message. An empty command (one with a NULL name) indicates an empty line in
235 * the generic usage message.
236 */
237 static zpool_command_t command_table[] = {
238 { "create", zpool_do_create, HELP_CREATE },
239 { "destroy", zpool_do_destroy, HELP_DESTROY },
240 { NULL },
241 { "add", zpool_do_add, HELP_ADD },
242 { "remove", zpool_do_remove, HELP_REMOVE },
243 { NULL },
244 { "labelclear", zpool_do_labelclear, HELP_LABELCLEAR },
245 { NULL },
246 { "list", zpool_do_list, HELP_LIST },
247 { "iostat", zpool_do_iostat, HELP_IOSTAT },
248 { "status", zpool_do_status, HELP_STATUS },
249 { NULL },
250 { "online", zpool_do_online, HELP_ONLINE },
251 { "offline", zpool_do_offline, HELP_OFFLINE },
252 { "clear", zpool_do_clear, HELP_CLEAR },
253 { "reopen", zpool_do_reopen, HELP_REOPEN },
254 { NULL },
255 { "attach", zpool_do_attach, HELP_ATTACH },
256 { "detach", zpool_do_detach, HELP_DETACH },
257 { "replace", zpool_do_replace, HELP_REPLACE },
258 { "split", zpool_do_split, HELP_SPLIT },
259 { NULL },
260 { "scrub", zpool_do_scrub, HELP_SCRUB },
261 { NULL },
262 { "import", zpool_do_import, HELP_IMPORT },
263 { "export", zpool_do_export, HELP_EXPORT },
264 { "upgrade", zpool_do_upgrade, HELP_UPGRADE },
265 { "reguid", zpool_do_reguid, HELP_REGUID },
266 { NULL },
267 { "history", zpool_do_history, HELP_HISTORY },
268 { "events", zpool_do_events, HELP_EVENTS },
269 { NULL },
270 { "get", zpool_do_get, HELP_GET },
271 { "set", zpool_do_set, HELP_SET },
272 };
273
274 #define NCOMMAND (ARRAY_SIZE(command_table))
275
276 static zpool_command_t *current_command;
277 static char history_str[HIS_MAX_RECORD_LEN];
278 static boolean_t log_history = B_TRUE;
279 static uint_t timestamp_fmt = NODATE;
280
281 static const char *
282 get_usage(zpool_help_t idx) {
283 switch (idx) {
284 case HELP_ADD:
285 return (gettext("\tadd [-fgLnP] [-o property=value] "
286 "<pool> <vdev> ...\n"));
287 case HELP_ATTACH:
288 return (gettext("\tattach [-f] [-o property=value] "
289 "<pool> <device> <new-device>\n"));
290 case HELP_CLEAR:
291 return (gettext("\tclear [-nF] <pool> [device]\n"));
292 case HELP_CREATE:
293 return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
294 "\t [-O file-system-property=value] ... \n"
295 "\t [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
296 case HELP_DESTROY:
297 return (gettext("\tdestroy [-f] <pool>\n"));
298 case HELP_DETACH:
299 return (gettext("\tdetach <pool> <device>\n"));
300 case HELP_EXPORT:
301 return (gettext("\texport [-af] <pool> ...\n"));
302 case HELP_HISTORY:
303 return (gettext("\thistory [-il] [<pool>] ...\n"));
304 case HELP_IMPORT:
305 return (gettext("\timport [-d dir] [-D]\n"
306 "\timport [-d dir | -c cachefile] [-F [-n]] <pool | id>\n"
307 "\timport [-o mntopts] [-o property=value] ... \n"
308 "\t [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
309 "[-R root] [-F [-n]] -a\n"
310 "\timport [-o mntopts] [-o property=value] ... \n"
311 "\t [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
312 "[-R root] [-F [-n]]\n"
313 "\t <pool | id> [newpool]\n"));
314 case HELP_IOSTAT:
315 return (gettext("\tiostat [-T d | u] [-ghHLpPvy] "
316 "[[-lq]|[-r|-w]]\n"
317 "\t [[pool ...]|[pool vdev ...]|[vdev ...]] "
318 "[interval [count]]\n"));
319 case HELP_LABELCLEAR:
320 return (gettext("\tlabelclear [-f] <vdev>\n"));
321 case HELP_LIST:
322 return (gettext("\tlist [-gHLpPv] [-o property[,...]] "
323 "[-T d|u] [pool] ... [interval [count]]\n"));
324 case HELP_OFFLINE:
325 return (gettext("\toffline [-t] <pool> <device> ...\n"));
326 case HELP_ONLINE:
327 return (gettext("\tonline <pool> <device> ...\n"));
328 case HELP_REPLACE:
329 return (gettext("\treplace [-f] [-o property=value] "
330 "<pool> <device> [new-device]\n"));
331 case HELP_REMOVE:
332 return (gettext("\tremove <pool> <device> ...\n"));
333 case HELP_REOPEN:
334 return (gettext("\treopen <pool>\n"));
335 case HELP_SCRUB:
336 return (gettext("\tscrub [-s] <pool> ...\n"));
337 case HELP_STATUS:
338 return (gettext("\tstatus [-gLPvxD] [-T d|u] [pool] ... "
339 "[interval [count]]\n"));
340 case HELP_UPGRADE:
341 return (gettext("\tupgrade\n"
342 "\tupgrade -v\n"
343 "\tupgrade [-V version] <-a | pool ...>\n"));
344 case HELP_EVENTS:
345 return (gettext("\tevents [-vHfc]\n"));
346 case HELP_GET:
347 return (gettext("\tget [-Hp] [-o \"all\" | field[,...]] "
348 "<\"all\" | property[,...]> <pool> ...\n"));
349 case HELP_SET:
350 return (gettext("\tset <property=value> <pool> \n"));
351 case HELP_SPLIT:
352 return (gettext("\tsplit [-gLnP] [-R altroot] [-o mntopts]\n"
353 "\t [-o property=value] <pool> <newpool> "
354 "[<device> ...]\n"));
355 case HELP_REGUID:
356 return (gettext("\treguid <pool>\n"));
357 }
358
359 abort();
360 /* NOTREACHED */
361 }
362
363
364 /*
365 * Callback routine that will print out a pool property value.
366 */
367 static int
368 print_prop_cb(int prop, void *cb)
369 {
370 FILE *fp = cb;
371
372 (void) fprintf(fp, "\t%-15s ", zpool_prop_to_name(prop));
373
374 if (zpool_prop_readonly(prop))
375 (void) fprintf(fp, " NO ");
376 else
377 (void) fprintf(fp, " YES ");
378
379 if (zpool_prop_values(prop) == NULL)
380 (void) fprintf(fp, "-\n");
381 else
382 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
383
384 return (ZPROP_CONT);
385 }
386
387 /*
388 * Display usage message. If we're inside a command, display only the usage for
389 * that command. Otherwise, iterate over the entire command table and display
390 * a complete usage message.
391 */
392 void
393 usage(boolean_t requested)
394 {
395 FILE *fp = requested ? stdout : stderr;
396
397 if (current_command == NULL) {
398 int i;
399
400 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
401 (void) fprintf(fp,
402 gettext("where 'command' is one of the following:\n\n"));
403
404 for (i = 0; i < NCOMMAND; i++) {
405 if (command_table[i].name == NULL)
406 (void) fprintf(fp, "\n");
407 else
408 (void) fprintf(fp, "%s",
409 get_usage(command_table[i].usage));
410 }
411 } else {
412 (void) fprintf(fp, gettext("usage:\n"));
413 (void) fprintf(fp, "%s", get_usage(current_command->usage));
414 }
415
416 if (current_command != NULL &&
417 ((strcmp(current_command->name, "set") == 0) ||
418 (strcmp(current_command->name, "get") == 0) ||
419 (strcmp(current_command->name, "list") == 0))) {
420
421 (void) fprintf(fp,
422 gettext("\nthe following properties are supported:\n"));
423
424 (void) fprintf(fp, "\n\t%-15s %s %s\n\n",
425 "PROPERTY", "EDIT", "VALUES");
426
427 /* Iterate over all properties */
428 (void) zprop_iter(print_prop_cb, fp, B_FALSE, B_TRUE,
429 ZFS_TYPE_POOL);
430
431 (void) fprintf(fp, "\t%-15s ", "feature@...");
432 (void) fprintf(fp, "YES disabled | enabled | active\n");
433
434 (void) fprintf(fp, gettext("\nThe feature@ properties must be "
435 "appended with a feature name.\nSee zpool-features(5).\n"));
436 }
437
438 /*
439 * See comments at end of main().
440 */
441 if (getenv("ZFS_ABORT") != NULL) {
442 (void) printf("dumping core by request\n");
443 abort();
444 }
445
446 exit(requested ? 0 : 2);
447 }
448
449 void
450 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
451 boolean_t print_logs, int name_flags)
452 {
453 nvlist_t **child;
454 uint_t c, children;
455 char *vname;
456
457 if (name != NULL)
458 (void) printf("\t%*s%s\n", indent, "", name);
459
460 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
461 &child, &children) != 0)
462 return;
463
464 for (c = 0; c < children; c++) {
465 uint64_t is_log = B_FALSE;
466
467 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
468 &is_log);
469 if ((is_log && !print_logs) || (!is_log && print_logs))
470 continue;
471
472 vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
473 print_vdev_tree(zhp, vname, child[c], indent + 2,
474 B_FALSE, name_flags);
475 free(vname);
476 }
477 }
478
479 static boolean_t
480 prop_list_contains_feature(nvlist_t *proplist)
481 {
482 nvpair_t *nvp;
483 for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
484 nvp = nvlist_next_nvpair(proplist, nvp)) {
485 if (zpool_prop_feature(nvpair_name(nvp)))
486 return (B_TRUE);
487 }
488 return (B_FALSE);
489 }
490
491 /*
492 * Add a property pair (name, string-value) into a property nvlist.
493 */
494 static int
495 add_prop_list(const char *propname, char *propval, nvlist_t **props,
496 boolean_t poolprop)
497 {
498 zpool_prop_t prop = ZPROP_INVAL;
499 zfs_prop_t fprop;
500 nvlist_t *proplist;
501 const char *normnm;
502 char *strval;
503
504 if (*props == NULL &&
505 nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
506 (void) fprintf(stderr,
507 gettext("internal error: out of memory\n"));
508 return (1);
509 }
510
511 proplist = *props;
512
513 if (poolprop) {
514 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
515
516 if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL &&
517 !zpool_prop_feature(propname)) {
518 (void) fprintf(stderr, gettext("property '%s' is "
519 "not a valid pool property\n"), propname);
520 return (2);
521 }
522
523 /*
524 * feature@ properties and version should not be specified
525 * at the same time.
526 */
527 if ((prop == ZPROP_INVAL && zpool_prop_feature(propname) &&
528 nvlist_exists(proplist, vname)) ||
529 (prop == ZPOOL_PROP_VERSION &&
530 prop_list_contains_feature(proplist))) {
531 (void) fprintf(stderr, gettext("'feature@' and "
532 "'version' properties cannot be specified "
533 "together\n"));
534 return (2);
535 }
536
537
538 if (zpool_prop_feature(propname))
539 normnm = propname;
540 else
541 normnm = zpool_prop_to_name(prop);
542 } else {
543 if ((fprop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
544 normnm = zfs_prop_to_name(fprop);
545 } else {
546 normnm = propname;
547 }
548 }
549
550 if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
551 prop != ZPOOL_PROP_CACHEFILE) {
552 (void) fprintf(stderr, gettext("property '%s' "
553 "specified multiple times\n"), propname);
554 return (2);
555 }
556
557 if (nvlist_add_string(proplist, normnm, propval) != 0) {
558 (void) fprintf(stderr, gettext("internal "
559 "error: out of memory\n"));
560 return (1);
561 }
562
563 return (0);
564 }
565
566 /*
567 * Set a default property pair (name, string-value) in a property nvlist
568 */
569 static int
570 add_prop_list_default(const char *propname, char *propval, nvlist_t **props,
571 boolean_t poolprop)
572 {
573 char *pval;
574
575 if (nvlist_lookup_string(*props, propname, &pval) == 0)
576 return (0);
577
578 return (add_prop_list(propname, propval, props, B_TRUE));
579 }
580
581 /*
582 * zpool add [-fgLnP] [-o property=value] <pool> <vdev> ...
583 *
584 * -f Force addition of devices, even if they appear in use
585 * -g Display guid for individual vdev name.
586 * -L Follow links when resolving vdev path name.
587 * -n Do not add the devices, but display the resulting layout if
588 * they were to be added.
589 * -o Set property=value.
590 * -P Display full path for vdev name.
591 *
592 * Adds the given vdevs to 'pool'. As with create, the bulk of this work is
593 * handled by get_vdev_spec(), which constructs the nvlist needed to pass to
594 * libzfs.
595 */
596 int
597 zpool_do_add(int argc, char **argv)
598 {
599 boolean_t force = B_FALSE;
600 boolean_t dryrun = B_FALSE;
601 int name_flags = 0;
602 int c;
603 nvlist_t *nvroot;
604 char *poolname;
605 int ret;
606 zpool_handle_t *zhp;
607 nvlist_t *config;
608 nvlist_t *props = NULL;
609 char *propval;
610
611 /* check options */
612 while ((c = getopt(argc, argv, "fgLno:P")) != -1) {
613 switch (c) {
614 case 'f':
615 force = B_TRUE;
616 break;
617 case 'g':
618 name_flags |= VDEV_NAME_GUID;
619 break;
620 case 'L':
621 name_flags |= VDEV_NAME_FOLLOW_LINKS;
622 break;
623 case 'n':
624 dryrun = B_TRUE;
625 break;
626 case 'o':
627 if ((propval = strchr(optarg, '=')) == NULL) {
628 (void) fprintf(stderr, gettext("missing "
629 "'=' for -o option\n"));
630 usage(B_FALSE);
631 }
632 *propval = '\0';
633 propval++;
634
635 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
636 (add_prop_list(optarg, propval, &props, B_TRUE)))
637 usage(B_FALSE);
638 break;
639 case 'P':
640 name_flags |= VDEV_NAME_PATH;
641 break;
642 case '?':
643 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
644 optopt);
645 usage(B_FALSE);
646 }
647 }
648
649 argc -= optind;
650 argv += optind;
651
652 /* get pool name and check number of arguments */
653 if (argc < 1) {
654 (void) fprintf(stderr, gettext("missing pool name argument\n"));
655 usage(B_FALSE);
656 }
657 if (argc < 2) {
658 (void) fprintf(stderr, gettext("missing vdev specification\n"));
659 usage(B_FALSE);
660 }
661
662 poolname = argv[0];
663
664 argc--;
665 argv++;
666
667 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
668 return (1);
669
670 if ((config = zpool_get_config(zhp, NULL)) == NULL) {
671 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
672 poolname);
673 zpool_close(zhp);
674 return (1);
675 }
676
677 /* pass off to get_vdev_spec for processing */
678 nvroot = make_root_vdev(zhp, props, force, !force, B_FALSE, dryrun,
679 argc, argv);
680 if (nvroot == NULL) {
681 zpool_close(zhp);
682 return (1);
683 }
684
685 if (dryrun) {
686 nvlist_t *poolnvroot;
687 nvlist_t **l2child;
688 uint_t l2children, c;
689 char *vname;
690 boolean_t hadcache = B_FALSE;
691
692 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
693 &poolnvroot) == 0);
694
695 (void) printf(gettext("would update '%s' to the following "
696 "configuration:\n"), zpool_get_name(zhp));
697
698 /* print original main pool and new tree */
699 print_vdev_tree(zhp, poolname, poolnvroot, 0, B_FALSE,
700 name_flags);
701 print_vdev_tree(zhp, NULL, nvroot, 0, B_FALSE, name_flags);
702
703 /* Do the same for the logs */
704 if (num_logs(poolnvroot) > 0) {
705 print_vdev_tree(zhp, "logs", poolnvroot, 0, B_TRUE,
706 name_flags);
707 print_vdev_tree(zhp, NULL, nvroot, 0, B_TRUE,
708 name_flags);
709 } else if (num_logs(nvroot) > 0) {
710 print_vdev_tree(zhp, "logs", nvroot, 0, B_TRUE,
711 name_flags);
712 }
713
714 /* Do the same for the caches */
715 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
716 &l2child, &l2children) == 0 && l2children) {
717 hadcache = B_TRUE;
718 (void) printf(gettext("\tcache\n"));
719 for (c = 0; c < l2children; c++) {
720 vname = zpool_vdev_name(g_zfs, NULL,
721 l2child[c], name_flags);
722 (void) printf("\t %s\n", vname);
723 free(vname);
724 }
725 }
726 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
727 &l2child, &l2children) == 0 && l2children) {
728 if (!hadcache)
729 (void) printf(gettext("\tcache\n"));
730 for (c = 0; c < l2children; c++) {
731 vname = zpool_vdev_name(g_zfs, NULL,
732 l2child[c], name_flags);
733 (void) printf("\t %s\n", vname);
734 free(vname);
735 }
736 }
737
738 ret = 0;
739 } else {
740 ret = (zpool_add(zhp, nvroot) != 0);
741 }
742
743 nvlist_free(props);
744 nvlist_free(nvroot);
745 zpool_close(zhp);
746
747 return (ret);
748 }
749
750 /*
751 * zpool remove <pool> <vdev> ...
752 *
753 * Removes the given vdev from the pool. Currently, this supports removing
754 * spares, cache, and log devices from the pool.
755 */
756 int
757 zpool_do_remove(int argc, char **argv)
758 {
759 char *poolname;
760 int i, ret = 0;
761 zpool_handle_t *zhp = NULL;
762
763 argc--;
764 argv++;
765
766 /* get pool name and check number of arguments */
767 if (argc < 1) {
768 (void) fprintf(stderr, gettext("missing pool name argument\n"));
769 usage(B_FALSE);
770 }
771 if (argc < 2) {
772 (void) fprintf(stderr, gettext("missing device\n"));
773 usage(B_FALSE);
774 }
775
776 poolname = argv[0];
777
778 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
779 return (1);
780
781 for (i = 1; i < argc; i++) {
782 if (zpool_vdev_remove(zhp, argv[i]) != 0)
783 ret = 1;
784 }
785 zpool_close(zhp);
786
787 return (ret);
788 }
789
790 /*
791 * zpool labelclear <vdev>
792 *
793 * Verifies that the vdev is not active and zeros out the label information
794 * on the device.
795 */
796 int
797 zpool_do_labelclear(int argc, char **argv)
798 {
799 char *vdev, *name;
800 int c, fd = -1, ret = 0;
801 pool_state_t state;
802 boolean_t inuse = B_FALSE;
803 boolean_t force = B_FALSE;
804
805 /* check options */
806 while ((c = getopt(argc, argv, "f")) != -1) {
807 switch (c) {
808 case 'f':
809 force = B_TRUE;
810 break;
811 default:
812 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
813 optopt);
814 usage(B_FALSE);
815 }
816 }
817
818 argc -= optind;
819 argv += optind;
820
821 /* get vdev name */
822 if (argc < 1) {
823 (void) fprintf(stderr, gettext("missing vdev device name\n"));
824 usage(B_FALSE);
825 }
826
827 vdev = argv[0];
828 if ((fd = open(vdev, O_RDWR)) < 0) {
829 (void) fprintf(stderr, gettext("Unable to open %s\n"), vdev);
830 return (B_FALSE);
831 }
832
833 name = NULL;
834 if (zpool_in_use(g_zfs, fd, &state, &name, &inuse) != 0) {
835 if (force)
836 goto wipe_label;
837
838 (void) fprintf(stderr,
839 gettext("Unable to determine pool state for %s\n"
840 "Use -f to force the clearing any label data\n"), vdev);
841
842 return (1);
843 }
844
845 if (inuse) {
846 switch (state) {
847 default:
848 case POOL_STATE_ACTIVE:
849 case POOL_STATE_SPARE:
850 case POOL_STATE_L2CACHE:
851 (void) fprintf(stderr,
852 gettext("labelclear operation failed.\n"
853 "\tVdev %s is a member (%s), of pool \"%s\".\n"
854 "\tTo remove label information from this device, "
855 "export or destroy\n\tthe pool, or remove %s from "
856 "the configuration of this pool\n\tand retry the "
857 "labelclear operation.\n"),
858 vdev, zpool_pool_state_to_name(state), name, vdev);
859 ret = 1;
860 goto errout;
861
862 case POOL_STATE_EXPORTED:
863 if (force)
864 break;
865
866 (void) fprintf(stderr,
867 gettext("labelclear operation failed.\n\tVdev "
868 "%s is a member of the exported pool \"%s\".\n"
869 "\tUse \"zpool labelclear -f %s\" to force the "
870 "removal of label\n\tinformation.\n"),
871 vdev, name, vdev);
872 ret = 1;
873 goto errout;
874
875 case POOL_STATE_POTENTIALLY_ACTIVE:
876 if (force)
877 break;
878
879 (void) fprintf(stderr,
880 gettext("labelclear operation failed.\n"
881 "\tVdev %s is a member of the pool \"%s\".\n"
882 "\tThis pool is unknown to this system, but may "
883 "be active on\n\tanother system. Use "
884 "\'zpool labelclear -f %s\' to force the\n"
885 "\tremoval of label information.\n"),
886 vdev, name, vdev);
887 ret = 1;
888 goto errout;
889
890 case POOL_STATE_DESTROYED:
891 /* inuse should never be set for a destroyed pool... */
892 break;
893 }
894 }
895
896 wipe_label:
897 if (zpool_clear_label(fd) != 0) {
898 (void) fprintf(stderr,
899 gettext("Label clear failed on vdev %s\n"), vdev);
900 ret = 1;
901 }
902
903 errout:
904 close(fd);
905 if (name != NULL)
906 free(name);
907
908 return (ret);
909 }
910
911 /*
912 * zpool create [-fnd] [-o property=value] ...
913 * [-O file-system-property=value] ...
914 * [-R root] [-m mountpoint] <pool> <dev> ...
915 *
916 * -f Force creation, even if devices appear in use
917 * -n Do not create the pool, but display the resulting layout if it
918 * were to be created.
919 * -R Create a pool under an alternate root
920 * -m Set default mountpoint for the root dataset. By default it's
921 * '/<pool>'
922 * -o Set property=value.
923 * -o Set feature@feature=enabled|disabled.
924 * -d Don't automatically enable all supported pool features
925 * (individual features can be enabled with -o).
926 * -O Set fsproperty=value in the pool's root file system
927 *
928 * Creates the named pool according to the given vdev specification. The
929 * bulk of the vdev processing is done in get_vdev_spec() in zpool_vdev.c. Once
930 * we get the nvlist back from get_vdev_spec(), we either print out the contents
931 * (if '-n' was specified), or pass it to libzfs to do the creation.
932 */
933 int
934 zpool_do_create(int argc, char **argv)
935 {
936 boolean_t force = B_FALSE;
937 boolean_t dryrun = B_FALSE;
938 boolean_t enable_all_pool_feat = B_TRUE;
939 int c;
940 nvlist_t *nvroot = NULL;
941 char *poolname;
942 char *tname = NULL;
943 int ret = 1;
944 char *altroot = NULL;
945 char *mountpoint = NULL;
946 nvlist_t *fsprops = NULL;
947 nvlist_t *props = NULL;
948 char *propval;
949
950 /* check options */
951 while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
952 switch (c) {
953 case 'f':
954 force = B_TRUE;
955 break;
956 case 'n':
957 dryrun = B_TRUE;
958 break;
959 case 'd':
960 enable_all_pool_feat = B_FALSE;
961 break;
962 case 'R':
963 altroot = optarg;
964 if (add_prop_list(zpool_prop_to_name(
965 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
966 goto errout;
967 if (add_prop_list_default(zpool_prop_to_name(
968 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
969 goto errout;
970 break;
971 case 'm':
972 /* Equivalent to -O mountpoint=optarg */
973 mountpoint = optarg;
974 break;
975 case 'o':
976 if ((propval = strchr(optarg, '=')) == NULL) {
977 (void) fprintf(stderr, gettext("missing "
978 "'=' for -o option\n"));
979 goto errout;
980 }
981 *propval = '\0';
982 propval++;
983
984 if (add_prop_list(optarg, propval, &props, B_TRUE))
985 goto errout;
986
987 /*
988 * If the user is creating a pool that doesn't support
989 * feature flags, don't enable any features.
990 */
991 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
992 char *end;
993 u_longlong_t ver;
994
995 ver = strtoull(propval, &end, 10);
996 if (*end == '\0' &&
997 ver < SPA_VERSION_FEATURES) {
998 enable_all_pool_feat = B_FALSE;
999 }
1000 }
1001 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
1002 altroot = propval;
1003 break;
1004 case 'O':
1005 if ((propval = strchr(optarg, '=')) == NULL) {
1006 (void) fprintf(stderr, gettext("missing "
1007 "'=' for -O option\n"));
1008 goto errout;
1009 }
1010 *propval = '\0';
1011 propval++;
1012
1013 /*
1014 * Mountpoints are checked and then added later.
1015 * Uniquely among properties, they can be specified
1016 * more than once, to avoid conflict with -m.
1017 */
1018 if (0 == strcmp(optarg,
1019 zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
1020 mountpoint = propval;
1021 } else if (add_prop_list(optarg, propval, &fsprops,
1022 B_FALSE)) {
1023 goto errout;
1024 }
1025 break;
1026 case 't':
1027 /*
1028 * Sanity check temporary pool name.
1029 */
1030 if (strchr(optarg, '/') != NULL) {
1031 (void) fprintf(stderr, gettext("cannot create "
1032 "'%s': invalid character '/' in temporary "
1033 "name\n"), optarg);
1034 (void) fprintf(stderr, gettext("use 'zfs "
1035 "create' to create a dataset\n"));
1036 goto errout;
1037 }
1038
1039 if (add_prop_list(zpool_prop_to_name(
1040 ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
1041 goto errout;
1042 if (add_prop_list_default(zpool_prop_to_name(
1043 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1044 goto errout;
1045 tname = optarg;
1046 break;
1047 case ':':
1048 (void) fprintf(stderr, gettext("missing argument for "
1049 "'%c' option\n"), optopt);
1050 goto badusage;
1051 case '?':
1052 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1053 optopt);
1054 goto badusage;
1055 }
1056 }
1057
1058 argc -= optind;
1059 argv += optind;
1060
1061 /* get pool name and check number of arguments */
1062 if (argc < 1) {
1063 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1064 goto badusage;
1065 }
1066 if (argc < 2) {
1067 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1068 goto badusage;
1069 }
1070
1071 poolname = argv[0];
1072
1073 /*
1074 * As a special case, check for use of '/' in the name, and direct the
1075 * user to use 'zfs create' instead.
1076 */
1077 if (strchr(poolname, '/') != NULL) {
1078 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
1079 "character '/' in pool name\n"), poolname);
1080 (void) fprintf(stderr, gettext("use 'zfs create' to "
1081 "create a dataset\n"));
1082 goto errout;
1083 }
1084
1085 /* pass off to get_vdev_spec for bulk processing */
1086 nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
1087 argc - 1, argv + 1);
1088 if (nvroot == NULL)
1089 goto errout;
1090
1091 /* make_root_vdev() allows 0 toplevel children if there are spares */
1092 if (!zfs_allocatable_devs(nvroot)) {
1093 (void) fprintf(stderr, gettext("invalid vdev "
1094 "specification: at least one toplevel vdev must be "
1095 "specified\n"));
1096 goto errout;
1097 }
1098
1099 if (altroot != NULL && altroot[0] != '/') {
1100 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
1101 "must be an absolute path\n"), altroot);
1102 goto errout;
1103 }
1104
1105 /*
1106 * Check the validity of the mountpoint and direct the user to use the
1107 * '-m' mountpoint option if it looks like its in use.
1108 */
1109 if (mountpoint == NULL ||
1110 (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
1111 strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
1112 char buf[MAXPATHLEN];
1113 DIR *dirp;
1114
1115 if (mountpoint && mountpoint[0] != '/') {
1116 (void) fprintf(stderr, gettext("invalid mountpoint "
1117 "'%s': must be an absolute path, 'legacy', or "
1118 "'none'\n"), mountpoint);
1119 goto errout;
1120 }
1121
1122 if (mountpoint == NULL) {
1123 if (altroot != NULL)
1124 (void) snprintf(buf, sizeof (buf), "%s/%s",
1125 altroot, poolname);
1126 else
1127 (void) snprintf(buf, sizeof (buf), "/%s",
1128 poolname);
1129 } else {
1130 if (altroot != NULL)
1131 (void) snprintf(buf, sizeof (buf), "%s%s",
1132 altroot, mountpoint);
1133 else
1134 (void) snprintf(buf, sizeof (buf), "%s",
1135 mountpoint);
1136 }
1137
1138 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
1139 (void) fprintf(stderr, gettext("mountpoint '%s' : "
1140 "%s\n"), buf, strerror(errno));
1141 (void) fprintf(stderr, gettext("use '-m' "
1142 "option to provide a different default\n"));
1143 goto errout;
1144 } else if (dirp) {
1145 int count = 0;
1146
1147 while (count < 3 && readdir(dirp) != NULL)
1148 count++;
1149 (void) closedir(dirp);
1150
1151 if (count > 2) {
1152 (void) fprintf(stderr, gettext("mountpoint "
1153 "'%s' exists and is not empty\n"), buf);
1154 (void) fprintf(stderr, gettext("use '-m' "
1155 "option to provide a "
1156 "different default\n"));
1157 goto errout;
1158 }
1159 }
1160 }
1161
1162 /*
1163 * Now that the mountpoint's validity has been checked, ensure that
1164 * the property is set appropriately prior to creating the pool.
1165 */
1166 if (mountpoint != NULL) {
1167 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
1168 mountpoint, &fsprops, B_FALSE);
1169 if (ret != 0)
1170 goto errout;
1171 }
1172
1173 ret = 1;
1174 if (dryrun) {
1175 /*
1176 * For a dry run invocation, print out a basic message and run
1177 * through all the vdevs in the list and print out in an
1178 * appropriate hierarchy.
1179 */
1180 (void) printf(gettext("would create '%s' with the "
1181 "following layout:\n\n"), poolname);
1182
1183 print_vdev_tree(NULL, poolname, nvroot, 0, B_FALSE, 0);
1184 if (num_logs(nvroot) > 0)
1185 print_vdev_tree(NULL, "logs", nvroot, 0, B_TRUE, 0);
1186
1187 ret = 0;
1188 } else {
1189 /*
1190 * Hand off to libzfs.
1191 */
1192 spa_feature_t i;
1193 for (i = 0; i < SPA_FEATURES; i++) {
1194 char propname[MAXPATHLEN];
1195 char *propval;
1196 zfeature_info_t *feat = &spa_feature_table[i];
1197
1198 (void) snprintf(propname, sizeof (propname),
1199 "feature@%s", feat->fi_uname);
1200
1201 /*
1202 * Only features contained in props will be enabled:
1203 * remove from the nvlist every ZFS_FEATURE_DISABLED
1204 * value and add every missing ZFS_FEATURE_ENABLED if
1205 * enable_all_pool_feat is set.
1206 */
1207 if (!nvlist_lookup_string(props, propname, &propval)) {
1208 if (strcmp(propval, ZFS_FEATURE_DISABLED) == 0)
1209 (void) nvlist_remove_all(props,
1210 propname);
1211 } else if (enable_all_pool_feat) {
1212 ret = add_prop_list(propname,
1213 ZFS_FEATURE_ENABLED, &props, B_TRUE);
1214 if (ret != 0)
1215 goto errout;
1216 }
1217 }
1218
1219 ret = 1;
1220 if (zpool_create(g_zfs, poolname,
1221 nvroot, props, fsprops) == 0) {
1222 zfs_handle_t *pool = zfs_open(g_zfs,
1223 tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
1224 if (pool != NULL) {
1225 if (zfs_mount(pool, NULL, 0) == 0)
1226 ret = zfs_shareall(pool);
1227 zfs_close(pool);
1228 }
1229 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
1230 (void) fprintf(stderr, gettext("pool name may have "
1231 "been omitted\n"));
1232 }
1233 }
1234
1235 errout:
1236 nvlist_free(nvroot);
1237 nvlist_free(fsprops);
1238 nvlist_free(props);
1239 return (ret);
1240 badusage:
1241 nvlist_free(fsprops);
1242 nvlist_free(props);
1243 usage(B_FALSE);
1244 return (2);
1245 }
1246
1247 /*
1248 * zpool destroy <pool>
1249 *
1250 * -f Forcefully unmount any datasets
1251 *
1252 * Destroy the given pool. Automatically unmounts any datasets in the pool.
1253 */
1254 int
1255 zpool_do_destroy(int argc, char **argv)
1256 {
1257 boolean_t force = B_FALSE;
1258 int c;
1259 char *pool;
1260 zpool_handle_t *zhp;
1261 int ret;
1262
1263 /* check options */
1264 while ((c = getopt(argc, argv, "f")) != -1) {
1265 switch (c) {
1266 case 'f':
1267 force = B_TRUE;
1268 break;
1269 case '?':
1270 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1271 optopt);
1272 usage(B_FALSE);
1273 }
1274 }
1275
1276 argc -= optind;
1277 argv += optind;
1278
1279 /* check arguments */
1280 if (argc < 1) {
1281 (void) fprintf(stderr, gettext("missing pool argument\n"));
1282 usage(B_FALSE);
1283 }
1284 if (argc > 1) {
1285 (void) fprintf(stderr, gettext("too many arguments\n"));
1286 usage(B_FALSE);
1287 }
1288
1289 pool = argv[0];
1290
1291 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
1292 /*
1293 * As a special case, check for use of '/' in the name, and
1294 * direct the user to use 'zfs destroy' instead.
1295 */
1296 if (strchr(pool, '/') != NULL)
1297 (void) fprintf(stderr, gettext("use 'zfs destroy' to "
1298 "destroy a dataset\n"));
1299 return (1);
1300 }
1301
1302 if (zpool_disable_datasets(zhp, force) != 0) {
1303 (void) fprintf(stderr, gettext("could not destroy '%s': "
1304 "could not unmount datasets\n"), zpool_get_name(zhp));
1305 zpool_close(zhp);
1306 return (1);
1307 }
1308
1309 /* The history must be logged as part of the export */
1310 log_history = B_FALSE;
1311
1312 ret = (zpool_destroy(zhp, history_str) != 0);
1313
1314 zpool_close(zhp);
1315
1316 return (ret);
1317 }
1318
1319 typedef struct export_cbdata {
1320 boolean_t force;
1321 boolean_t hardforce;
1322 } export_cbdata_t;
1323
1324 /*
1325 * Export one pool
1326 */
1327 int
1328 zpool_export_one(zpool_handle_t *zhp, void *data)
1329 {
1330 export_cbdata_t *cb = data;
1331
1332 if (zpool_disable_datasets(zhp, cb->force) != 0)
1333 return (1);
1334
1335 /* The history must be logged as part of the export */
1336 log_history = B_FALSE;
1337
1338 if (cb->hardforce) {
1339 if (zpool_export_force(zhp, history_str) != 0)
1340 return (1);
1341 } else if (zpool_export(zhp, cb->force, history_str) != 0) {
1342 return (1);
1343 }
1344
1345 return (0);
1346 }
1347
1348 /*
1349 * zpool export [-f] <pool> ...
1350 *
1351 * -a Export all pools
1352 * -f Forcefully unmount datasets
1353 *
1354 * Export the given pools. By default, the command will attempt to cleanly
1355 * unmount any active datasets within the pool. If the '-f' flag is specified,
1356 * then the datasets will be forcefully unmounted.
1357 */
1358 int
1359 zpool_do_export(int argc, char **argv)
1360 {
1361 export_cbdata_t cb;
1362 boolean_t do_all = B_FALSE;
1363 boolean_t force = B_FALSE;
1364 boolean_t hardforce = B_FALSE;
1365 int c, ret;
1366
1367 /* check options */
1368 while ((c = getopt(argc, argv, "afF")) != -1) {
1369 switch (c) {
1370 case 'a':
1371 do_all = B_TRUE;
1372 break;
1373 case 'f':
1374 force = B_TRUE;
1375 break;
1376 case 'F':
1377 hardforce = B_TRUE;
1378 break;
1379 case '?':
1380 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1381 optopt);
1382 usage(B_FALSE);
1383 }
1384 }
1385
1386 cb.force = force;
1387 cb.hardforce = hardforce;
1388 argc -= optind;
1389 argv += optind;
1390
1391 if (do_all) {
1392 if (argc != 0) {
1393 (void) fprintf(stderr, gettext("too many arguments\n"));
1394 usage(B_FALSE);
1395 }
1396
1397 return (for_each_pool(argc, argv, B_TRUE, NULL,
1398 zpool_export_one, &cb));
1399 }
1400
1401 /* check arguments */
1402 if (argc < 1) {
1403 (void) fprintf(stderr, gettext("missing pool argument\n"));
1404 usage(B_FALSE);
1405 }
1406
1407 ret = for_each_pool(argc, argv, B_TRUE, NULL, zpool_export_one, &cb);
1408
1409 return (ret);
1410 }
1411
1412 /*
1413 * Given a vdev configuration, determine the maximum width needed for the device
1414 * name column.
1415 */
1416 static int
1417 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
1418 int name_flags)
1419 {
1420 char *name;
1421 nvlist_t **child;
1422 uint_t c, children;
1423 int ret;
1424
1425 name = zpool_vdev_name(g_zfs, zhp, nv, name_flags | VDEV_NAME_TYPE_ID);
1426 if (strlen(name) + depth > max)
1427 max = strlen(name) + depth;
1428
1429 free(name);
1430
1431 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1432 &child, &children) == 0) {
1433 for (c = 0; c < children; c++)
1434 if ((ret = max_width(zhp, child[c], depth + 2,
1435 max, name_flags)) > max)
1436 max = ret;
1437 }
1438
1439 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1440 &child, &children) == 0) {
1441 for (c = 0; c < children; c++)
1442 if ((ret = max_width(zhp, child[c], depth + 2,
1443 max, name_flags)) > max)
1444 max = ret;
1445 }
1446
1447 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1448 &child, &children) == 0) {
1449 for (c = 0; c < children; c++)
1450 if ((ret = max_width(zhp, child[c], depth + 2,
1451 max, name_flags)) > max)
1452 max = ret;
1453 }
1454
1455 return (max);
1456 }
1457
1458 typedef struct spare_cbdata {
1459 uint64_t cb_guid;
1460 zpool_handle_t *cb_zhp;
1461 } spare_cbdata_t;
1462
1463 static boolean_t
1464 find_vdev(nvlist_t *nv, uint64_t search)
1465 {
1466 uint64_t guid;
1467 nvlist_t **child;
1468 uint_t c, children;
1469
1470 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1471 search == guid)
1472 return (B_TRUE);
1473
1474 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1475 &child, &children) == 0) {
1476 for (c = 0; c < children; c++)
1477 if (find_vdev(child[c], search))
1478 return (B_TRUE);
1479 }
1480
1481 return (B_FALSE);
1482 }
1483
1484 static int
1485 find_spare(zpool_handle_t *zhp, void *data)
1486 {
1487 spare_cbdata_t *cbp = data;
1488 nvlist_t *config, *nvroot;
1489
1490 config = zpool_get_config(zhp, NULL);
1491 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1492 &nvroot) == 0);
1493
1494 if (find_vdev(nvroot, cbp->cb_guid)) {
1495 cbp->cb_zhp = zhp;
1496 return (1);
1497 }
1498
1499 zpool_close(zhp);
1500 return (0);
1501 }
1502
1503 typedef struct status_cbdata {
1504 int cb_count;
1505 int cb_name_flags;
1506 int cb_namewidth;
1507 boolean_t cb_allpools;
1508 boolean_t cb_verbose;
1509 boolean_t cb_explain;
1510 boolean_t cb_first;
1511 boolean_t cb_dedup_stats;
1512 boolean_t cb_print_status;
1513 } status_cbdata_t;
1514
1515 /*
1516 * Print out configuration state as requested by status_callback.
1517 */
1518 static void
1519 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
1520 nvlist_t *nv, int depth, boolean_t isspare)
1521 {
1522 nvlist_t **child;
1523 uint_t c, children;
1524 pool_scan_stat_t *ps = NULL;
1525 vdev_stat_t *vs;
1526 char rbuf[6], wbuf[6], cbuf[6];
1527 char *vname;
1528 uint64_t notpresent;
1529 spare_cbdata_t spare_cb;
1530 char *state;
1531
1532 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1533 &child, &children) != 0)
1534 children = 0;
1535
1536 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1537 (uint64_t **)&vs, &c) == 0);
1538
1539 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1540 if (isspare) {
1541 /*
1542 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
1543 * online drives.
1544 */
1545 if (vs->vs_aux == VDEV_AUX_SPARED)
1546 state = "INUSE";
1547 else if (vs->vs_state == VDEV_STATE_HEALTHY)
1548 state = "AVAIL";
1549 }
1550
1551 (void) printf("\t%*s%-*s %-8s", depth, "", cb->cb_namewidth - depth,
1552 name, state);
1553
1554 if (!isspare) {
1555 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
1556 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
1557 zfs_nicenum(vs->vs_checksum_errors, cbuf, sizeof (cbuf));
1558 (void) printf(" %5s %5s %5s", rbuf, wbuf, cbuf);
1559 }
1560
1561 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
1562 &notpresent) == 0) {
1563 char *path;
1564 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
1565 (void) printf(" was %s", path);
1566 } else if (vs->vs_aux != 0) {
1567 (void) printf(" ");
1568
1569 switch (vs->vs_aux) {
1570 case VDEV_AUX_OPEN_FAILED:
1571 (void) printf(gettext("cannot open"));
1572 break;
1573
1574 case VDEV_AUX_BAD_GUID_SUM:
1575 (void) printf(gettext("missing device"));
1576 break;
1577
1578 case VDEV_AUX_NO_REPLICAS:
1579 (void) printf(gettext("insufficient replicas"));
1580 break;
1581
1582 case VDEV_AUX_VERSION_NEWER:
1583 (void) printf(gettext("newer version"));
1584 break;
1585
1586 case VDEV_AUX_UNSUP_FEAT:
1587 (void) printf(gettext("unsupported feature(s)"));
1588 break;
1589
1590 case VDEV_AUX_SPARED:
1591 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
1592 &spare_cb.cb_guid) == 0);
1593 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1594 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1595 zpool_get_name(zhp)) == 0)
1596 (void) printf(gettext("currently in "
1597 "use"));
1598 else
1599 (void) printf(gettext("in use by "
1600 "pool '%s'"),
1601 zpool_get_name(spare_cb.cb_zhp));
1602 zpool_close(spare_cb.cb_zhp);
1603 } else {
1604 (void) printf(gettext("currently in use"));
1605 }
1606 break;
1607
1608 case VDEV_AUX_ERR_EXCEEDED:
1609 (void) printf(gettext("too many errors"));
1610 break;
1611
1612 case VDEV_AUX_IO_FAILURE:
1613 (void) printf(gettext("experienced I/O failures"));
1614 break;
1615
1616 case VDEV_AUX_BAD_LOG:
1617 (void) printf(gettext("bad intent log"));
1618 break;
1619
1620 case VDEV_AUX_EXTERNAL:
1621 (void) printf(gettext("external device fault"));
1622 break;
1623
1624 case VDEV_AUX_SPLIT_POOL:
1625 (void) printf(gettext("split into new pool"));
1626 break;
1627
1628 default:
1629 (void) printf(gettext("corrupted data"));
1630 break;
1631 }
1632 }
1633
1634 (void) nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_SCAN_STATS,
1635 (uint64_t **)&ps, &c);
1636
1637 if (ps && ps->pss_state == DSS_SCANNING &&
1638 vs->vs_scan_processed != 0 && children == 0) {
1639 (void) printf(gettext(" (%s)"),
1640 (ps->pss_func == POOL_SCAN_RESILVER) ?
1641 "resilvering" : "repairing");
1642 }
1643
1644 (void) printf("\n");
1645
1646 for (c = 0; c < children; c++) {
1647 uint64_t islog = B_FALSE, ishole = B_FALSE;
1648
1649 /* Don't print logs or holes here */
1650 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1651 &islog);
1652 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
1653 &ishole);
1654 if (islog || ishole)
1655 continue;
1656 vname = zpool_vdev_name(g_zfs, zhp, child[c],
1657 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1658 print_status_config(zhp, cb, vname, child[c], depth + 2,
1659 isspare);
1660 free(vname);
1661 }
1662 }
1663
1664 /*
1665 * Print the configuration of an exported pool. Iterate over all vdevs in the
1666 * pool, printing out the name and status for each one.
1667 */
1668 static void
1669 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
1670 int depth)
1671 {
1672 nvlist_t **child;
1673 uint_t c, children;
1674 vdev_stat_t *vs;
1675 char *type, *vname;
1676
1677 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1678 if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
1679 strcmp(type, VDEV_TYPE_HOLE) == 0)
1680 return;
1681
1682 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1683 (uint64_t **)&vs, &c) == 0);
1684
1685 (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
1686 (void) printf(" %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
1687
1688 if (vs->vs_aux != 0) {
1689 (void) printf(" ");
1690
1691 switch (vs->vs_aux) {
1692 case VDEV_AUX_OPEN_FAILED:
1693 (void) printf(gettext("cannot open"));
1694 break;
1695
1696 case VDEV_AUX_BAD_GUID_SUM:
1697 (void) printf(gettext("missing device"));
1698 break;
1699
1700 case VDEV_AUX_NO_REPLICAS:
1701 (void) printf(gettext("insufficient replicas"));
1702 break;
1703
1704 case VDEV_AUX_VERSION_NEWER:
1705 (void) printf(gettext("newer version"));
1706 break;
1707
1708 case VDEV_AUX_UNSUP_FEAT:
1709 (void) printf(gettext("unsupported feature(s)"));
1710 break;
1711
1712 case VDEV_AUX_ERR_EXCEEDED:
1713 (void) printf(gettext("too many errors"));
1714 break;
1715
1716 default:
1717 (void) printf(gettext("corrupted data"));
1718 break;
1719 }
1720 }
1721 (void) printf("\n");
1722
1723 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1724 &child, &children) != 0)
1725 return;
1726
1727 for (c = 0; c < children; c++) {
1728 uint64_t is_log = B_FALSE;
1729
1730 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1731 &is_log);
1732 if (is_log)
1733 continue;
1734
1735 vname = zpool_vdev_name(g_zfs, NULL, child[c],
1736 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1737 print_import_config(cb, vname, child[c], depth + 2);
1738 free(vname);
1739 }
1740
1741 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1742 &child, &children) == 0) {
1743 (void) printf(gettext("\tcache\n"));
1744 for (c = 0; c < children; c++) {
1745 vname = zpool_vdev_name(g_zfs, NULL, child[c],
1746 cb->cb_name_flags);
1747 (void) printf("\t %s\n", vname);
1748 free(vname);
1749 }
1750 }
1751
1752 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1753 &child, &children) == 0) {
1754 (void) printf(gettext("\tspares\n"));
1755 for (c = 0; c < children; c++) {
1756 vname = zpool_vdev_name(g_zfs, NULL, child[c],
1757 cb->cb_name_flags);
1758 (void) printf("\t %s\n", vname);
1759 free(vname);
1760 }
1761 }
1762 }
1763
1764 /*
1765 * Print log vdevs.
1766 * Logs are recorded as top level vdevs in the main pool child array
1767 * but with "is_log" set to 1. We use either print_status_config() or
1768 * print_import_config() to print the top level logs then any log
1769 * children (eg mirrored slogs) are printed recursively - which
1770 * works because only the top level vdev is marked "is_log"
1771 */
1772 static void
1773 print_logs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv)
1774 {
1775 uint_t c, children;
1776 nvlist_t **child;
1777
1778 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
1779 &children) != 0)
1780 return;
1781
1782 (void) printf(gettext("\tlogs\n"));
1783
1784 for (c = 0; c < children; c++) {
1785 uint64_t is_log = B_FALSE;
1786 char *name;
1787
1788 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1789 &is_log);
1790 if (!is_log)
1791 continue;
1792 name = zpool_vdev_name(g_zfs, zhp, child[c],
1793 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1794 if (cb->cb_print_status)
1795 print_status_config(zhp, cb, name, child[c], 2,
1796 B_FALSE);
1797 else
1798 print_import_config(cb, name, child[c], 2);
1799 free(name);
1800 }
1801 }
1802
1803 /*
1804 * Display the status for the given pool.
1805 */
1806 static void
1807 show_import(nvlist_t *config)
1808 {
1809 uint64_t pool_state;
1810 vdev_stat_t *vs;
1811 char *name;
1812 uint64_t guid;
1813 char *msgid;
1814 nvlist_t *nvroot;
1815 zpool_status_t reason;
1816 zpool_errata_t errata;
1817 const char *health;
1818 uint_t vsc;
1819 char *comment;
1820 status_cbdata_t cb = { 0 };
1821
1822 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1823 &name) == 0);
1824 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1825 &guid) == 0);
1826 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
1827 &pool_state) == 0);
1828 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1829 &nvroot) == 0);
1830
1831 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
1832 (uint64_t **)&vs, &vsc) == 0);
1833 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1834
1835 reason = zpool_import_status(config, &msgid, &errata);
1836
1837 (void) printf(gettext(" pool: %s\n"), name);
1838 (void) printf(gettext(" id: %llu\n"), (u_longlong_t)guid);
1839 (void) printf(gettext(" state: %s"), health);
1840 if (pool_state == POOL_STATE_DESTROYED)
1841 (void) printf(gettext(" (DESTROYED)"));
1842 (void) printf("\n");
1843
1844 switch (reason) {
1845 case ZPOOL_STATUS_MISSING_DEV_R:
1846 case ZPOOL_STATUS_MISSING_DEV_NR:
1847 case ZPOOL_STATUS_BAD_GUID_SUM:
1848 (void) printf(gettext(" status: One or more devices are "
1849 "missing from the system.\n"));
1850 break;
1851
1852 case ZPOOL_STATUS_CORRUPT_LABEL_R:
1853 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
1854 (void) printf(gettext(" status: One or more devices contains "
1855 "corrupted data.\n"));
1856 break;
1857
1858 case ZPOOL_STATUS_CORRUPT_DATA:
1859 (void) printf(
1860 gettext(" status: The pool data is corrupted.\n"));
1861 break;
1862
1863 case ZPOOL_STATUS_OFFLINE_DEV:
1864 (void) printf(gettext(" status: One or more devices "
1865 "are offlined.\n"));
1866 break;
1867
1868 case ZPOOL_STATUS_CORRUPT_POOL:
1869 (void) printf(gettext(" status: The pool metadata is "
1870 "corrupted.\n"));
1871 break;
1872
1873 case ZPOOL_STATUS_VERSION_OLDER:
1874 (void) printf(gettext(" status: The pool is formatted using a "
1875 "legacy on-disk version.\n"));
1876 break;
1877
1878 case ZPOOL_STATUS_VERSION_NEWER:
1879 (void) printf(gettext(" status: The pool is formatted using an "
1880 "incompatible version.\n"));
1881 break;
1882
1883 case ZPOOL_STATUS_FEAT_DISABLED:
1884 (void) printf(gettext(" status: Some supported features are "
1885 "not enabled on the pool.\n"));
1886 break;
1887
1888 case ZPOOL_STATUS_UNSUP_FEAT_READ:
1889 (void) printf(gettext("status: The pool uses the following "
1890 "feature(s) not supported on this sytem:\n"));
1891 zpool_print_unsup_feat(config);
1892 break;
1893
1894 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
1895 (void) printf(gettext("status: The pool can only be accessed "
1896 "in read-only mode on this system. It\n\tcannot be "
1897 "accessed in read-write mode because it uses the "
1898 "following\n\tfeature(s) not supported on this system:\n"));
1899 zpool_print_unsup_feat(config);
1900 break;
1901
1902 case ZPOOL_STATUS_HOSTID_MISMATCH:
1903 (void) printf(gettext(" status: The pool was last accessed by "
1904 "another system.\n"));
1905 break;
1906
1907 case ZPOOL_STATUS_FAULTED_DEV_R:
1908 case ZPOOL_STATUS_FAULTED_DEV_NR:
1909 (void) printf(gettext(" status: One or more devices are "
1910 "faulted.\n"));
1911 break;
1912
1913 case ZPOOL_STATUS_BAD_LOG:
1914 (void) printf(gettext(" status: An intent log record cannot be "
1915 "read.\n"));
1916 break;
1917
1918 case ZPOOL_STATUS_RESILVERING:
1919 (void) printf(gettext(" status: One or more devices were being "
1920 "resilvered.\n"));
1921 break;
1922
1923 case ZPOOL_STATUS_ERRATA:
1924 (void) printf(gettext(" status: Errata #%d detected.\n"),
1925 errata);
1926 break;
1927
1928 default:
1929 /*
1930 * No other status can be seen when importing pools.
1931 */
1932 assert(reason == ZPOOL_STATUS_OK);
1933 }
1934
1935 /*
1936 * Print out an action according to the overall state of the pool.
1937 */
1938 if (vs->vs_state == VDEV_STATE_HEALTHY) {
1939 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
1940 reason == ZPOOL_STATUS_FEAT_DISABLED) {
1941 (void) printf(gettext(" action: The pool can be "
1942 "imported using its name or numeric identifier, "
1943 "though\n\tsome features will not be available "
1944 "without an explicit 'zpool upgrade'.\n"));
1945 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
1946 (void) printf(gettext(" action: The pool can be "
1947 "imported using its name or numeric "
1948 "identifier and\n\tthe '-f' flag.\n"));
1949 } else if (reason == ZPOOL_STATUS_ERRATA) {
1950 switch (errata) {
1951 case ZPOOL_ERRATA_NONE:
1952 break;
1953
1954 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
1955 (void) printf(gettext(" action: The pool can "
1956 "be imported using its name or numeric "
1957 "identifier,\n\thowever there is a compat"
1958 "ibility issue which should be corrected"
1959 "\n\tby running 'zpool scrub'\n"));
1960 break;
1961
1962 case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
1963 (void) printf(gettext(" action: The pool can"
1964 "not be imported with this version of ZFS "
1965 "due to\n\tan active asynchronous destroy. "
1966 "Revert to an earlier version\n\tand "
1967 "allow the destroy to complete before "
1968 "updating.\n"));
1969 break;
1970
1971 default:
1972 /*
1973 * All errata must contain an action message.
1974 */
1975 assert(0);
1976 }
1977 } else {
1978 (void) printf(gettext(" action: The pool can be "
1979 "imported using its name or numeric "
1980 "identifier.\n"));
1981 }
1982 } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
1983 (void) printf(gettext(" action: The pool can be imported "
1984 "despite missing or damaged devices. The\n\tfault "
1985 "tolerance of the pool may be compromised if imported.\n"));
1986 } else {
1987 switch (reason) {
1988 case ZPOOL_STATUS_VERSION_NEWER:
1989 (void) printf(gettext(" action: The pool cannot be "
1990 "imported. Access the pool on a system running "
1991 "newer\n\tsoftware, or recreate the pool from "
1992 "backup.\n"));
1993 break;
1994 case ZPOOL_STATUS_UNSUP_FEAT_READ:
1995 (void) printf(gettext("action: The pool cannot be "
1996 "imported. Access the pool on a system that "
1997 "supports\n\tthe required feature(s), or recreate "
1998 "the pool from backup.\n"));
1999 break;
2000 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2001 (void) printf(gettext("action: The pool cannot be "
2002 "imported in read-write mode. Import the pool "
2003 "with\n"
2004 "\t\"-o readonly=on\", access the pool on a system "
2005 "that supports the\n\trequired feature(s), or "
2006 "recreate the pool from backup.\n"));
2007 break;
2008 case ZPOOL_STATUS_MISSING_DEV_R:
2009 case ZPOOL_STATUS_MISSING_DEV_NR:
2010 case ZPOOL_STATUS_BAD_GUID_SUM:
2011 (void) printf(gettext(" action: The pool cannot be "
2012 "imported. Attach the missing\n\tdevices and try "
2013 "again.\n"));
2014 break;
2015 default:
2016 (void) printf(gettext(" action: The pool cannot be "
2017 "imported due to damaged devices or data.\n"));
2018 }
2019 }
2020
2021 /* Print the comment attached to the pool. */
2022 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2023 (void) printf(gettext("comment: %s\n"), comment);
2024
2025 /*
2026 * If the state is "closed" or "can't open", and the aux state
2027 * is "corrupt data":
2028 */
2029 if (((vs->vs_state == VDEV_STATE_CLOSED) ||
2030 (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
2031 (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
2032 if (pool_state == POOL_STATE_DESTROYED)
2033 (void) printf(gettext("\tThe pool was destroyed, "
2034 "but can be imported using the '-Df' flags.\n"));
2035 else if (pool_state != POOL_STATE_EXPORTED)
2036 (void) printf(gettext("\tThe pool may be active on "
2037 "another system, but can be imported using\n\t"
2038 "the '-f' flag.\n"));
2039 }
2040
2041 if (msgid != NULL)
2042 (void) printf(gettext(" see: http://zfsonlinux.org/msg/%s\n"),
2043 msgid);
2044
2045 (void) printf(gettext(" config:\n\n"));
2046
2047 cb.cb_namewidth = max_width(NULL, nvroot, 0, 0, 0);
2048 if (cb.cb_namewidth < 10)
2049 cb.cb_namewidth = 10;
2050
2051 print_import_config(&cb, name, nvroot, 0);
2052 if (num_logs(nvroot) > 0)
2053 print_logs(NULL, &cb, nvroot);
2054
2055 if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
2056 (void) printf(gettext("\n\tAdditional devices are known to "
2057 "be part of this pool, though their\n\texact "
2058 "configuration cannot be determined.\n"));
2059 }
2060 }
2061
2062 /*
2063 * Perform the import for the given configuration. This passes the heavy
2064 * lifting off to zpool_import_props(), and then mounts the datasets contained
2065 * within the pool.
2066 */
2067 static int
2068 do_import(nvlist_t *config, const char *newname, const char *mntopts,
2069 nvlist_t *props, int flags)
2070 {
2071 zpool_handle_t *zhp;
2072 char *name;
2073 uint64_t state;
2074 uint64_t version;
2075
2076 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2077 &name) == 0);
2078
2079 verify(nvlist_lookup_uint64(config,
2080 ZPOOL_CONFIG_POOL_STATE, &state) == 0);
2081 verify(nvlist_lookup_uint64(config,
2082 ZPOOL_CONFIG_VERSION, &version) == 0);
2083 if (!SPA_VERSION_IS_SUPPORTED(version)) {
2084 (void) fprintf(stderr, gettext("cannot import '%s': pool "
2085 "is formatted using an unsupported ZFS version\n"), name);
2086 return (1);
2087 } else if (state != POOL_STATE_EXPORTED &&
2088 !(flags & ZFS_IMPORT_ANY_HOST)) {
2089 uint64_t hostid = 0;
2090 unsigned long system_hostid = get_system_hostid();
2091
2092 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
2093 &hostid);
2094
2095 if (hostid != 0 && (unsigned long)hostid != system_hostid) {
2096 char *hostname;
2097 uint64_t timestamp;
2098 time_t t;
2099
2100 verify(nvlist_lookup_string(config,
2101 ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2102 verify(nvlist_lookup_uint64(config,
2103 ZPOOL_CONFIG_TIMESTAMP, &timestamp) == 0);
2104 t = timestamp;
2105 (void) fprintf(stderr, gettext("cannot import "
2106 "'%s': pool may be in use from other "
2107 "system, it was last accessed by %s "
2108 "(hostid: 0x%lx) on %s"), name, hostname,
2109 (unsigned long)hostid,
2110 asctime(localtime(&t)));
2111 (void) fprintf(stderr, gettext("use '-f' to "
2112 "import anyway\n"));
2113 return (1);
2114 }
2115 }
2116
2117 if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
2118 return (1);
2119
2120 if (newname != NULL)
2121 name = (char *)newname;
2122
2123 if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
2124 return (1);
2125
2126 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
2127 !(flags & ZFS_IMPORT_ONLY) &&
2128 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
2129 zpool_close(zhp);
2130 return (1);
2131 }
2132
2133 zpool_close(zhp);
2134 return (0);
2135 }
2136
2137 /*
2138 * zpool import [-d dir] [-D]
2139 * import [-o mntopts] [-o prop=value] ... [-R root] [-D]
2140 * [-d dir | -c cachefile] [-f] -a
2141 * import [-o mntopts] [-o prop=value] ... [-R root] [-D]
2142 * [-d dir | -c cachefile] [-f] [-n] [-F] <pool | id> [newpool]
2143 *
2144 * -c Read pool information from a cachefile instead of searching
2145 * devices.
2146 *
2147 * -d Scan in a specific directory, other than /dev/. More than
2148 * one directory can be specified using multiple '-d' options.
2149 *
2150 * -D Scan for previously destroyed pools or import all or only
2151 * specified destroyed pools.
2152 *
2153 * -R Temporarily import the pool, with all mountpoints relative to
2154 * the given root. The pool will remain exported when the machine
2155 * is rebooted.
2156 *
2157 * -V Import even in the presence of faulted vdevs. This is an
2158 * intentionally undocumented option for testing purposes, and
2159 * treats the pool configuration as complete, leaving any bad
2160 * vdevs in the FAULTED state. In other words, it does verbatim
2161 * import.
2162 *
2163 * -f Force import, even if it appears that the pool is active.
2164 *
2165 * -F Attempt rewind if necessary.
2166 *
2167 * -n See if rewind would work, but don't actually rewind.
2168 *
2169 * -N Import the pool but don't mount datasets.
2170 *
2171 * -T Specify a starting txg to use for import. This option is
2172 * intentionally undocumented option for testing purposes.
2173 *
2174 * -a Import all pools found.
2175 *
2176 * -o Set property=value and/or temporary mount options (without '=').
2177 *
2178 * -s Scan using the default search path, the libblkid cache will
2179 * not be consulted.
2180 *
2181 * The import command scans for pools to import, and import pools based on pool
2182 * name and GUID. The pool can also be renamed as part of the import process.
2183 */
2184 int
2185 zpool_do_import(int argc, char **argv)
2186 {
2187 char **searchdirs = NULL;
2188 char *env, *envdup = NULL;
2189 int nsearch = 0;
2190 int c;
2191 int err = 0;
2192 nvlist_t *pools = NULL;
2193 boolean_t do_all = B_FALSE;
2194 boolean_t do_destroyed = B_FALSE;
2195 char *mntopts = NULL;
2196 nvpair_t *elem;
2197 nvlist_t *config;
2198 uint64_t searchguid = 0;
2199 char *searchname = NULL;
2200 char *propval;
2201 nvlist_t *found_config;
2202 nvlist_t *policy = NULL;
2203 nvlist_t *props = NULL;
2204 boolean_t first;
2205 int flags = ZFS_IMPORT_NORMAL;
2206 uint32_t rewind_policy = ZPOOL_NO_REWIND;
2207 boolean_t dryrun = B_FALSE;
2208 boolean_t do_rewind = B_FALSE;
2209 boolean_t xtreme_rewind = B_FALSE;
2210 boolean_t do_scan = B_FALSE;
2211 uint64_t pool_state, txg = -1ULL;
2212 char *cachefile = NULL;
2213 importargs_t idata = { 0 };
2214 char *endptr;
2215
2216 /* check options */
2217 while ((c = getopt(argc, argv, ":aCc:d:DEfFmnNo:R:stT:VX")) != -1) {
2218 switch (c) {
2219 case 'a':
2220 do_all = B_TRUE;
2221 break;
2222 case 'c':
2223 cachefile = optarg;
2224 break;
2225 case 'd':
2226 if (searchdirs == NULL) {
2227 searchdirs = safe_malloc(sizeof (char *));
2228 } else {
2229 char **tmp = safe_malloc((nsearch + 1) *
2230 sizeof (char *));
2231 bcopy(searchdirs, tmp, nsearch *
2232 sizeof (char *));
2233 free(searchdirs);
2234 searchdirs = tmp;
2235 }
2236 searchdirs[nsearch++] = optarg;
2237 break;
2238 case 'D':
2239 do_destroyed = B_TRUE;
2240 break;
2241 case 'f':
2242 flags |= ZFS_IMPORT_ANY_HOST;
2243 break;
2244 case 'F':
2245 do_rewind = B_TRUE;
2246 break;
2247 case 'm':
2248 flags |= ZFS_IMPORT_MISSING_LOG;
2249 break;
2250 case 'n':
2251 dryrun = B_TRUE;
2252 break;
2253 case 'N':
2254 flags |= ZFS_IMPORT_ONLY;
2255 break;
2256 case 'o':
2257 if ((propval = strchr(optarg, '=')) != NULL) {
2258 *propval = '\0';
2259 propval++;
2260 if (add_prop_list(optarg, propval,
2261 &props, B_TRUE))
2262 goto error;
2263 } else {
2264 mntopts = optarg;
2265 }
2266 break;
2267 case 'R':
2268 if (add_prop_list(zpool_prop_to_name(
2269 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
2270 goto error;
2271 if (add_prop_list_default(zpool_prop_to_name(
2272 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
2273 goto error;
2274 break;
2275 case 's':
2276 do_scan = B_TRUE;
2277 break;
2278 case 't':
2279 flags |= ZFS_IMPORT_TEMP_NAME;
2280 if (add_prop_list_default(zpool_prop_to_name(
2281 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
2282 goto error;
2283 break;
2284
2285 case 'T':
2286 errno = 0;
2287 txg = strtoull(optarg, &endptr, 0);
2288 if (errno != 0 || *endptr != '\0') {
2289 (void) fprintf(stderr,
2290 gettext("invalid txg value\n"));
2291 usage(B_FALSE);
2292 }
2293 rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
2294 break;
2295 case 'V':
2296 flags |= ZFS_IMPORT_VERBATIM;
2297 break;
2298 case 'X':
2299 xtreme_rewind = B_TRUE;
2300 break;
2301 case ':':
2302 (void) fprintf(stderr, gettext("missing argument for "
2303 "'%c' option\n"), optopt);
2304 usage(B_FALSE);
2305 break;
2306 case '?':
2307 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2308 optopt);
2309 usage(B_FALSE);
2310 }
2311 }
2312
2313 argc -= optind;
2314 argv += optind;
2315
2316 if (cachefile && nsearch != 0) {
2317 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
2318 usage(B_FALSE);
2319 }
2320
2321 if ((dryrun || xtreme_rewind) && !do_rewind) {
2322 (void) fprintf(stderr,
2323 gettext("-n or -X only meaningful with -F\n"));
2324 usage(B_FALSE);
2325 }
2326 if (dryrun)
2327 rewind_policy = ZPOOL_TRY_REWIND;
2328 else if (do_rewind)
2329 rewind_policy = ZPOOL_DO_REWIND;
2330 if (xtreme_rewind)
2331 rewind_policy |= ZPOOL_EXTREME_REWIND;
2332
2333 /* In the future, we can capture further policy and include it here */
2334 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
2335 nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, txg) != 0 ||
2336 nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
2337 goto error;
2338
2339 /* check argument count */
2340 if (do_all) {
2341 if (argc != 0) {
2342 (void) fprintf(stderr, gettext("too many arguments\n"));
2343 usage(B_FALSE);
2344 }
2345 } else {
2346 if (argc > 2) {
2347 (void) fprintf(stderr, gettext("too many arguments\n"));
2348 usage(B_FALSE);
2349 }
2350 }
2351
2352 /*
2353 * Check for the effective uid. We do this explicitly here because
2354 * otherwise any attempt to discover pools will silently fail.
2355 */
2356 if (argc == 0 && geteuid() != 0) {
2357 (void) fprintf(stderr, gettext("cannot "
2358 "discover pools: permission denied\n"));
2359 if (searchdirs != NULL)
2360 free(searchdirs);
2361
2362 nvlist_free(props);
2363 nvlist_free(policy);
2364 return (1);
2365 }
2366
2367 /*
2368 * Depending on the arguments given, we do one of the following:
2369 *
2370 * <none> Iterate through all pools and display information about
2371 * each one.
2372 *
2373 * -a Iterate through all pools and try to import each one.
2374 *
2375 * <id> Find the pool that corresponds to the given GUID/pool
2376 * name and import that one.
2377 *
2378 * -D Above options applies only to destroyed pools.
2379 */
2380 if (argc != 0) {
2381 char *endptr;
2382
2383 errno = 0;
2384 searchguid = strtoull(argv[0], &endptr, 10);
2385 if (errno != 0 || *endptr != '\0') {
2386 searchname = argv[0];
2387 searchguid = 0;
2388 }
2389 found_config = NULL;
2390
2391 /*
2392 * User specified a name or guid. Ensure it's unique.
2393 */
2394 idata.unique = B_TRUE;
2395 }
2396
2397 /*
2398 * Check the environment for the preferred search path.
2399 */
2400 if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
2401 char *dir;
2402
2403 envdup = strdup(env);
2404
2405 dir = strtok(envdup, ":");
2406 while (dir != NULL) {
2407 if (searchdirs == NULL) {
2408 searchdirs = safe_malloc(sizeof (char *));
2409 } else {
2410 char **tmp = safe_malloc((nsearch + 1) *
2411 sizeof (char *));
2412 bcopy(searchdirs, tmp, nsearch *
2413 sizeof (char *));
2414 free(searchdirs);
2415 searchdirs = tmp;
2416 }
2417 searchdirs[nsearch++] = dir;
2418 dir = strtok(NULL, ":");
2419 }
2420 }
2421
2422 idata.path = searchdirs;
2423 idata.paths = nsearch;
2424 idata.poolname = searchname;
2425 idata.guid = searchguid;
2426 idata.cachefile = cachefile;
2427 idata.scan = do_scan;
2428
2429 /*
2430 * Under Linux the zpool_find_import_impl() function leverages the
2431 * taskq implementation to parallelize device scanning. It is
2432 * therefore necessary to initialize this functionality for the
2433 * duration of the zpool_search_import() function.
2434 */
2435 thread_init();
2436 pools = zpool_search_import(g_zfs, &idata);
2437 thread_fini();
2438
2439 if (pools != NULL && idata.exists &&
2440 (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
2441 (void) fprintf(stderr, gettext("cannot import '%s': "
2442 "a pool with that name already exists\n"),
2443 argv[0]);
2444 (void) fprintf(stderr, gettext("use the form '%s "
2445 "<pool | id> <newpool>' to give it a new name\n"),
2446 "zpool import");
2447 err = 1;
2448 } else if (pools == NULL && idata.exists) {
2449 (void) fprintf(stderr, gettext("cannot import '%s': "
2450 "a pool with that name is already created/imported,\n"),
2451 argv[0]);
2452 (void) fprintf(stderr, gettext("and no additional pools "
2453 "with that name were found\n"));
2454 err = 1;
2455 } else if (pools == NULL) {
2456 if (argc != 0) {
2457 (void) fprintf(stderr, gettext("cannot import '%s': "
2458 "no such pool available\n"), argv[0]);
2459 }
2460 err = 1;
2461 }
2462
2463 if (err == 1) {
2464 if (searchdirs != NULL)
2465 free(searchdirs);
2466 if (envdup != NULL)
2467 free(envdup);
2468 nvlist_free(policy);
2469 nvlist_free(pools);
2470 nvlist_free(props);
2471 return (1);
2472 }
2473
2474 /*
2475 * At this point we have a list of import candidate configs. Even if
2476 * we were searching by pool name or guid, we still need to
2477 * post-process the list to deal with pool state and possible
2478 * duplicate names.
2479 */
2480 err = 0;
2481 elem = NULL;
2482 first = B_TRUE;
2483 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2484
2485 verify(nvpair_value_nvlist(elem, &config) == 0);
2486
2487 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2488 &pool_state) == 0);
2489 if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
2490 continue;
2491 if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
2492 continue;
2493
2494 verify(nvlist_add_nvlist(config, ZPOOL_REWIND_POLICY,
2495 policy) == 0);
2496
2497 if (argc == 0) {
2498 if (first)
2499 first = B_FALSE;
2500 else if (!do_all)
2501 (void) printf("\n");
2502
2503 if (do_all) {
2504 err |= do_import(config, NULL, mntopts,
2505 props, flags);
2506 } else {
2507 show_import(config);
2508 }
2509 } else if (searchname != NULL) {
2510 char *name;
2511
2512 /*
2513 * We are searching for a pool based on name.
2514 */
2515 verify(nvlist_lookup_string(config,
2516 ZPOOL_CONFIG_POOL_NAME, &name) == 0);
2517
2518 if (strcmp(name, searchname) == 0) {
2519 if (found_config != NULL) {
2520 (void) fprintf(stderr, gettext(
2521 "cannot import '%s': more than "
2522 "one matching pool\n"), searchname);
2523 (void) fprintf(stderr, gettext(
2524 "import by numeric ID instead\n"));
2525 err = B_TRUE;
2526 }
2527 found_config = config;
2528 }
2529 } else {
2530 uint64_t guid;
2531
2532 /*
2533 * Search for a pool by guid.
2534 */
2535 verify(nvlist_lookup_uint64(config,
2536 ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
2537
2538 if (guid == searchguid)
2539 found_config = config;
2540 }
2541 }
2542
2543 /*
2544 * If we were searching for a specific pool, verify that we found a
2545 * pool, and then do the import.
2546 */
2547 if (argc != 0 && err == 0) {
2548 if (found_config == NULL) {
2549 (void) fprintf(stderr, gettext("cannot import '%s': "
2550 "no such pool available\n"), argv[0]);
2551 err = B_TRUE;
2552 } else {
2553 err |= do_import(found_config, argc == 1 ? NULL :
2554 argv[1], mntopts, props, flags);
2555 }
2556 }
2557
2558 /*
2559 * If we were just looking for pools, report an error if none were
2560 * found.
2561 */
2562 if (argc == 0 && first)
2563 (void) fprintf(stderr,
2564 gettext("no pools available to import\n"));
2565
2566 error:
2567 nvlist_free(props);
2568 nvlist_free(pools);
2569 nvlist_free(policy);
2570 if (searchdirs != NULL)
2571 free(searchdirs);
2572 if (envdup != NULL)
2573 free(envdup);
2574
2575 return (err ? 1 : 0);
2576 }
2577
2578 typedef struct iostat_cbdata {
2579 uint64_t cb_flags;
2580 int cb_name_flags;
2581 int cb_namewidth;
2582 int cb_iteration;
2583 char **cb_vdev_names; /* Only show these vdevs */
2584 unsigned int cb_vdev_names_count;
2585 boolean_t cb_verbose;
2586 boolean_t cb_literal;
2587 boolean_t cb_scripted;
2588 zpool_list_t *cb_list;
2589 } iostat_cbdata_t;
2590
2591 /* iostat labels */
2592 typedef struct name_and_columns {
2593 const char *name; /* Column name */
2594 unsigned int columns; /* Center name to this number of columns */
2595 } name_and_columns_t;
2596
2597 #define IOSTAT_MAX_LABELS 11 /* Max number of labels on one line */
2598
2599 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
2600 {
2601 [IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
2602 {NULL}},
2603 [IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
2604 {"asyncq_wait", 2}, {"scrub"}},
2605 [IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
2606 {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
2607 {NULL}},
2608 [IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2},
2609 {"sync_queue", 2}, {"async_queue", 2}, {NULL}},
2610 [IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
2611 {"async_read", 2}, {"async_write", 2}, {"scrub", 2}, {NULL}},
2612
2613 };
2614
2615 /* Shorthand - if "columns" field not set, default to 1 column */
2616 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
2617 {
2618 [IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
2619 {"write"}, {NULL}},
2620 [IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
2621 {"write"}, {"read"}, {"write"}, {"wait"}, {NULL}},
2622 [IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
2623 {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
2624 [IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
2625 {"write"}, {"read"}, {"write"}, {"scrub"}, {NULL}},
2626 [IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
2627 {"ind"}, {"agg"}, {"ind"}, {"agg"}, {NULL}},
2628 };
2629
2630 static const char *histo_to_title[] = {
2631 [IOS_L_HISTO] = "latency",
2632 [IOS_RQ_HISTO] = "req_size",
2633 };
2634
2635 /*
2636 * Return the number of labels in a null-terminated name_and_columns_t
2637 * array.
2638 *
2639 */
2640 static unsigned int
2641 label_array_len(const name_and_columns_t *labels)
2642 {
2643 int i = 0;
2644
2645 while (labels[i].name)
2646 i++;
2647
2648 return (i);
2649 }
2650
2651 /*
2652 * Return the number of strings in a null-terminated string array.
2653 * For example:
2654 *
2655 * const char foo[] = {"bar", "baz", NULL}
2656 *
2657 * returns 2
2658 */
2659 static uint64_t
2660 str_array_len(const char *array[])
2661 {
2662 uint64_t i = 0;
2663 while (array[i])
2664 i++;
2665
2666 return (i);
2667 }
2668
2669
2670 /*
2671 * Return a default column width for default/latency/queue columns. This does
2672 * not include histograms, which have their columns autosized.
2673 */
2674 static unsigned int
2675 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
2676 {
2677 unsigned long column_width = 5; /* Normal niceprint */
2678 static unsigned long widths[] = {
2679 /*
2680 * Choose some sane default column sizes for printing the
2681 * raw numbers.
2682 */
2683 [IOS_DEFAULT] = 15, /* 1PB capacity */
2684 [IOS_LATENCY] = 10, /* 1B ns = 10sec */
2685 [IOS_QUEUES] = 6, /* 1M queue entries */
2686 };
2687
2688 if (cb->cb_literal)
2689 column_width = widths[type];
2690
2691 return (column_width);
2692 }
2693
2694 /*
2695 * Print the column labels, i.e:
2696 *
2697 * capacity operations bandwidth
2698 * alloc free read write read write ...
2699 *
2700 * If force_column_width is set, use it for the column width. If not set, use
2701 * the default column width.
2702 */
2703 void
2704 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
2705 const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
2706 {
2707 int i, idx, s;
2708 unsigned int text_start, rw_column_width, spaces_to_end;
2709 uint64_t flags = cb->cb_flags;
2710 uint64_t f;
2711 unsigned int column_width = force_column_width;
2712
2713 /* For each bit set in flags */
2714 for (f = flags; f; f &= ~(1ULL << idx)) {
2715 idx = lowbit64(f) - 1;
2716 if (!force_column_width)
2717 column_width = default_column_width(cb, idx);
2718 /* Print our top labels centered over "read write" label. */
2719 for (i = 0; i < label_array_len(labels[idx]); i++) {
2720 const char *name = labels[idx][i].name;
2721 /*
2722 * We treat labels[][].columns == 0 as shorthand
2723 * for one column. It makes writing out the label
2724 * tables more concise.
2725 */
2726 unsigned int columns = MAX(1, labels[idx][i].columns);
2727 unsigned int slen = strlen(name);
2728
2729 rw_column_width = (column_width * columns) +
2730 (2 * (columns - 1));
2731
2732 text_start = (int) ((rw_column_width)/columns -
2733 slen/columns);
2734
2735 printf(" "); /* Two spaces between columns */
2736
2737 /* Space from beginning of column to label */
2738 for (s = 0; s < text_start; s++)
2739 printf(" ");
2740
2741 printf("%s", name);
2742
2743 /* Print space after label to end of column */
2744 spaces_to_end = rw_column_width - text_start - slen;
2745 for (s = 0; s < spaces_to_end; s++)
2746 printf(" ");
2747
2748 }
2749 }
2750 printf("\n");
2751 }
2752
2753 /*
2754 * Utility function to print out a line of dashes like:
2755 *
2756 * -------------------------------- ----- ----- ----- ----- -----
2757 *
2758 * ...or a dashed named-row line like:
2759 *
2760 * logs - - - - -
2761 *
2762 * @cb: iostat data
2763 *
2764 * @force_column_width If non-zero, use the value as the column width.
2765 * Otherwise use the default column widths.
2766 *
2767 * @name: Print a dashed named-row line starting
2768 * with @name. Otherwise, print a regular
2769 * dashed line.
2770 */
2771 static void
2772 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
2773 const char *name)
2774 {
2775 int i;
2776 unsigned int namewidth;
2777 uint64_t flags = cb->cb_flags;
2778 uint64_t f;
2779 int idx;
2780 const name_and_columns_t *labels;
2781 const char *title;
2782
2783
2784 if (cb->cb_flags & IOS_ANYHISTO_M) {
2785 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
2786 } else if (cb->cb_vdev_names_count) {
2787 title = "vdev";
2788 } else {
2789 title = "pool";
2790 }
2791
2792 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
2793 name ? strlen(name) : 0);
2794
2795
2796 if (name) {
2797 printf("%-*s", namewidth, name);
2798 } else {
2799 for (i = 0; i < namewidth; i++)
2800 (void) printf("-");
2801 }
2802
2803 /* For each bit in flags */
2804 for (f = flags; f; f &= ~(1ULL << idx)) {
2805 unsigned int column_width;
2806 idx = lowbit64(f) - 1;
2807 if (force_column_width)
2808 column_width = force_column_width;
2809 else
2810 column_width = default_column_width(cb, idx);
2811
2812 labels = iostat_bottom_labels[idx];
2813 for (i = 0; i < label_array_len(labels); i++) {
2814 if (name)
2815 printf(" %*s-", column_width - 1, " ");
2816 else
2817 printf(" %.*s", column_width,
2818 "--------------------");
2819 }
2820 }
2821 printf("\n");
2822 }
2823
2824
2825 static void
2826 print_iostat_separator_impl(iostat_cbdata_t *cb,
2827 unsigned int force_column_width)
2828 {
2829 print_iostat_dashes(cb, force_column_width, NULL);
2830 }
2831
2832 static void
2833 print_iostat_separator(iostat_cbdata_t *cb)
2834 {
2835 print_iostat_separator_impl(cb, 0);
2836 }
2837
2838 static void
2839 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
2840 const char *histo_vdev_name)
2841 {
2842 unsigned int namewidth;
2843 const char *title;
2844
2845 if (cb->cb_flags & IOS_ANYHISTO_M) {
2846 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
2847 } else if (cb->cb_vdev_names_count) {
2848 title = "vdev";
2849 } else {
2850 title = "pool";
2851 }
2852
2853 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
2854 histo_vdev_name ? strlen(histo_vdev_name) : 0);
2855
2856 if (histo_vdev_name)
2857 printf("%-*s", namewidth, histo_vdev_name);
2858 else
2859 printf("%*s", namewidth, "");
2860
2861
2862 print_iostat_labels(cb, force_column_width, iostat_top_labels);
2863
2864 printf("%-*s", namewidth, title);
2865
2866 print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
2867
2868 print_iostat_separator_impl(cb, force_column_width);
2869 }
2870
2871 static void
2872 print_iostat_header(iostat_cbdata_t *cb)
2873 {
2874 print_iostat_header_impl(cb, 0, NULL);
2875 }
2876
2877
2878 /*
2879 * Display a single statistic.
2880 */
2881 static void
2882 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
2883 unsigned int column_size, boolean_t scripted)
2884 {
2885 char buf[64];
2886
2887 zfs_nicenum_format(value, buf, sizeof (buf), format);
2888
2889 if (scripted)
2890 printf("\t%s", buf);
2891 else
2892 printf(" %*s", column_size, buf);
2893 }
2894
2895 /*
2896 * Calculate the default vdev stats
2897 *
2898 * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
2899 * stats into calcvs.
2900 */
2901 static void
2902 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
2903 vdev_stat_t *calcvs)
2904 {
2905 int i;
2906
2907 memcpy(calcvs, newvs, sizeof (*calcvs));
2908 for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
2909 calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
2910
2911 for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
2912 calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
2913 }
2914
2915 /*
2916 * Internal representation of the extended iostats data.
2917 *
2918 * The extended iostat stats are exported in nvlists as either uint64_t arrays
2919 * or single uint64_t's. We make both look like arrays to make them easier
2920 * to process. In order to make single uint64_t's look like arrays, we set
2921 * __data to the stat data, and then set *data = &__data with count = 1. Then,
2922 * we can just use *data and count.
2923 */
2924 struct stat_array {
2925 uint64_t *data;
2926 uint_t count; /* Number of entries in data[] */
2927 uint64_t __data; /* Only used when data is a single uint64_t */
2928 };
2929
2930 static uint64_t
2931 stat_histo_max(struct stat_array *nva, unsigned int len) {
2932 uint64_t max = 0;
2933 int i;
2934 for (i = 0; i < len; i++)
2935 max = MAX(max, array64_max(nva[i].data, nva[i].count));
2936
2937 return (max);
2938 }
2939
2940 /*
2941 * Helper function to lookup a uint64_t array or uint64_t value and store its
2942 * data as a stat_array. If the nvpair is a single uint64_t value, then we make
2943 * it look like a one element array to make it easier to process.
2944 */
2945 static int
2946 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
2947 struct stat_array *nva) {
2948 nvpair_t *tmp;
2949 int ret;
2950
2951 verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
2952 switch (nvpair_type(tmp)) {
2953 case DATA_TYPE_UINT64_ARRAY:
2954 ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
2955 break;
2956 case DATA_TYPE_UINT64:
2957 ret = nvpair_value_uint64(tmp, &nva->__data);
2958 nva->data = &nva->__data;
2959 nva->count = 1;
2960 break;
2961 default:
2962 /* Not a uint64_t */
2963 ret = EINVAL;
2964 break;
2965 }
2966
2967 return (ret);
2968 }
2969
2970 /*
2971 * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
2972 * subtract them, and return the results in a newly allocated stat_array.
2973 * You must free the returned array after you are done with it with
2974 * free_calc_stats().
2975 *
2976 * Additionally, you can set "oldnv" to NULL if you simply want the newnv
2977 * values.
2978 */
2979 static struct stat_array *
2980 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
2981 nvlist_t *newnv)
2982 {
2983 nvlist_t *oldnvx = NULL, *newnvx;
2984 struct stat_array *oldnva, *newnva, *calcnva;
2985 int i, j;
2986 unsigned int alloc_size = (sizeof (struct stat_array)) * len;
2987
2988 /* Extract our extended stats nvlist from the main list */
2989 verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
2990 &newnvx) == 0);
2991 if (oldnv) {
2992 verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
2993 &oldnvx) == 0);
2994 }
2995
2996 newnva = safe_malloc(alloc_size);
2997 oldnva = safe_malloc(alloc_size);
2998 calcnva = safe_malloc(alloc_size);
2999
3000 for (j = 0; j < len; j++) {
3001 verify(nvpair64_to_stat_array(newnvx, names[j],
3002 &newnva[j]) == 0);
3003 calcnva[j].count = newnva[j].count;
3004 alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
3005 calcnva[j].data = safe_malloc(alloc_size);
3006 memcpy(calcnva[j].data, newnva[j].data, alloc_size);
3007
3008 if (oldnvx) {
3009 verify(nvpair64_to_stat_array(oldnvx, names[j],
3010 &oldnva[j]) == 0);
3011 for (i = 0; i < oldnva[j].count; i++)
3012 calcnva[j].data[i] -= oldnva[j].data[i];
3013 }
3014 }
3015 free(newnva);
3016 free(oldnva);
3017 return (calcnva);
3018 }
3019
3020 static void
3021 free_calc_stats(struct stat_array *nva, unsigned int len)
3022 {
3023 int i;
3024 for (i = 0; i < len; i++)
3025 free(nva[i].data);
3026
3027 free(nva);
3028 }
3029
3030 static void
3031 print_iostat_histo(struct stat_array *nva, unsigned int len,
3032 iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
3033 double scale)
3034 {
3035 int i, j;
3036 char buf[6];
3037 uint64_t val;
3038 enum zfs_nicenum_format format;
3039 unsigned int buckets;
3040 unsigned int start_bucket;
3041
3042 if (cb->cb_literal)
3043 format = ZFS_NICENUM_RAW;
3044 else
3045 format = ZFS_NICENUM_1024;
3046
3047 /* All these histos are the same size, so just use nva[0].count */
3048 buckets = nva[0].count;
3049
3050 if (cb->cb_flags & IOS_RQ_HISTO_M) {
3051 /* Start at 512 - req size should never be lower than this */
3052 start_bucket = 9;
3053 } else {
3054 start_bucket = 0;
3055 }
3056
3057 for (j = start_bucket; j < buckets; j++) {
3058 /* Print histogram bucket label */
3059 if (cb->cb_flags & IOS_L_HISTO_M) {
3060 /* Ending range of this bucket */
3061 val = (1UL << (j + 1)) - 1;
3062 zfs_nicetime(val, buf, sizeof (buf));
3063 } else {
3064 /* Request size (starting range of bucket) */
3065 val = (1UL << j);
3066 zfs_nicenum(val, buf, sizeof (buf));
3067 }
3068
3069 if (cb->cb_scripted)
3070 printf("%llu", (u_longlong_t) val);
3071 else
3072 printf("%-*s", namewidth, buf);
3073
3074 /* Print the values on the line */
3075 for (i = 0; i < len; i++) {
3076 print_one_stat(nva[i].data[j] * scale, format,
3077 column_width, cb->cb_scripted);
3078 }
3079 printf("\n");
3080 }
3081 }
3082
3083 static void
3084 print_solid_separator(unsigned int length)
3085 {
3086 while (length--)
3087 printf("-");
3088 printf("\n");
3089 }
3090
3091 static void
3092 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
3093 nvlist_t *newnv, double scale, const char *name)
3094 {
3095 unsigned int column_width;
3096 unsigned int namewidth;
3097 unsigned int entire_width;
3098 enum iostat_type type;
3099 struct stat_array *nva;
3100 const char **names;
3101 unsigned int names_len;
3102
3103 /* What type of histo are we? */
3104 type = IOS_HISTO_IDX(cb->cb_flags);
3105
3106 /* Get NULL-terminated array of nvlist names for our histo */
3107 names = vsx_type_to_nvlist[type];
3108 names_len = str_array_len(names); /* num of names */
3109
3110 nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
3111
3112 if (cb->cb_literal) {
3113 column_width = MAX(5,
3114 (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
3115 } else {
3116 column_width = 5;
3117 }
3118
3119 namewidth = MAX(cb->cb_namewidth,
3120 strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
3121
3122 /*
3123 * Calculate the entire line width of what we're printing. The
3124 * +2 is for the two spaces between columns:
3125 */
3126 /* read write */
3127 /* ----- ----- */
3128 /* |___| <---------- column_width */
3129 /* */
3130 /* |__________| <--- entire_width */
3131 /* */
3132 entire_width = namewidth + (column_width + 2) *
3133 label_array_len(iostat_bottom_labels[type]);
3134
3135 if (cb->cb_scripted)
3136 printf("%s\n", name);
3137 else
3138 print_iostat_header_impl(cb, column_width, name);
3139
3140 print_iostat_histo(nva, names_len, cb, column_width,
3141 namewidth, scale);
3142
3143 free_calc_stats(nva, names_len);
3144 if (!cb->cb_scripted)
3145 print_solid_separator(entire_width);
3146 }
3147
3148 /*
3149 * Calculate the average latency of a power-of-two latency histogram
3150 */
3151 static uint64_t
3152 single_histo_average(uint64_t *histo, unsigned int buckets)
3153 {
3154 int i;
3155 uint64_t count = 0, total = 0;
3156
3157 for (i = 0; i < buckets; i++) {
3158 /*
3159 * Our buckets are power-of-two latency ranges. Use the
3160 * midpoint latency of each bucket to calculate the average.
3161 * For example:
3162 *
3163 * Bucket Midpoint
3164 * 8ns-15ns: 12ns
3165 * 16ns-31ns: 24ns
3166 * ...
3167 */
3168 if (histo[i] != 0) {
3169 total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
3170 count += histo[i];
3171 }
3172 }
3173
3174 /* Prevent divide by zero */
3175 return (count == 0 ? 0 : total / count);
3176 }
3177
3178 static void
3179 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *oldnv,
3180 nvlist_t *newnv, double scale)
3181 {
3182 int i;
3183 uint64_t val;
3184 const char *names[] = {
3185 ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
3186 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
3187 ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
3188 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
3189 ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
3190 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
3191 ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
3192 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
3193 ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
3194 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
3195 };
3196
3197 struct stat_array *nva;
3198
3199 unsigned int column_width = default_column_width(cb, IOS_QUEUES);
3200 enum zfs_nicenum_format format;
3201
3202 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
3203
3204 if (cb->cb_literal)
3205 format = ZFS_NICENUM_RAW;
3206 else
3207 format = ZFS_NICENUM_1024;
3208
3209 for (i = 0; i < ARRAY_SIZE(names); i++) {
3210 val = nva[i].data[0] * scale;
3211 print_one_stat(val, format, column_width, cb->cb_scripted);
3212 }
3213
3214 free_calc_stats(nva, ARRAY_SIZE(names));
3215 }
3216
3217 static void
3218 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
3219 nvlist_t *newnv, double scale)
3220 {
3221 int i;
3222 uint64_t val;
3223 const char *names[] = {
3224 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
3225 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
3226 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
3227 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
3228 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
3229 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
3230 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
3231 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
3232 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
3233 };
3234 struct stat_array *nva;
3235
3236 unsigned int column_width = default_column_width(cb, IOS_LATENCY);
3237 enum zfs_nicenum_format format;
3238
3239 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
3240
3241 if (cb->cb_literal)
3242 format = ZFS_NICENUM_RAW;
3243 else
3244 format = ZFS_NICENUM_TIME;
3245
3246 /* Print our avg latencies on the line */
3247 for (i = 0; i < ARRAY_SIZE(names); i++) {
3248 /* Compute average latency for a latency histo */
3249 val = single_histo_average(nva[i].data, nva[i].count) * scale;
3250 print_one_stat(val, format, column_width, cb->cb_scripted);
3251 }
3252 free_calc_stats(nva, ARRAY_SIZE(names));
3253 }
3254
3255 /*
3256 * Print default statistics (capacity/operations/bandwidth)
3257 */
3258 static void
3259 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
3260 {
3261 unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
3262 enum zfs_nicenum_format format;
3263 char na; /* char to print for "not applicable" values */
3264
3265 if (cb->cb_literal) {
3266 format = ZFS_NICENUM_RAW;
3267 na = '0';
3268 } else {
3269 format = ZFS_NICENUM_1024;
3270 na = '-';
3271 }
3272
3273 /* only toplevel vdevs have capacity stats */
3274 if (vs->vs_space == 0) {
3275 if (cb->cb_scripted)
3276 printf("\t%c\t%c", na, na);
3277 else
3278 printf(" %*c %*c", column_width, na, column_width,
3279 na);
3280 } else {
3281 print_one_stat(vs->vs_alloc, format, column_width,
3282 cb->cb_scripted);
3283 print_one_stat(vs->vs_space - vs->vs_alloc, format,
3284 column_width, cb->cb_scripted);
3285 }
3286
3287 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
3288 format, column_width, cb->cb_scripted);
3289 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
3290 format, column_width, cb->cb_scripted);
3291 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
3292 format, column_width, cb->cb_scripted);
3293 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
3294 format, column_width, cb->cb_scripted);
3295 }
3296
3297 /*
3298 * Print out all the statistics for the given vdev. This can either be the
3299 * toplevel configuration, or called recursively. If 'name' is NULL, then this
3300 * is a verbose output, and we don't want to display the toplevel pool stats.
3301 *
3302 * Returns the number of stat lines printed.
3303 */
3304 unsigned int
3305 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
3306 nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
3307 {
3308 nvlist_t **oldchild, **newchild;
3309 uint_t c, children;
3310 vdev_stat_t *oldvs, *newvs, *calcvs;
3311 vdev_stat_t zerovs = { 0 };
3312 char *vname;
3313 int i;
3314 int ret = 0;
3315 uint64_t tdelta;
3316 double scale;
3317
3318 calcvs = safe_malloc(sizeof (*calcvs));
3319
3320 if (oldnv != NULL) {
3321 verify(nvlist_lookup_uint64_array(oldnv,
3322 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
3323 } else {
3324 oldvs = &zerovs;
3325 }
3326
3327 /* Do we only want to see a specific vdev? */
3328 for (i = 0; i < cb->cb_vdev_names_count; i++) {
3329 /* Yes we do. Is this the vdev? */
3330 if (strcmp(name, cb->cb_vdev_names[i]) == 0) {
3331 /*
3332 * This is our vdev. Since it is the only vdev we
3333 * will be displaying, make depth = 0 so that it
3334 * doesn't get indented.
3335 */
3336 depth = 0;
3337 break;
3338 }
3339 }
3340
3341 if (cb->cb_vdev_names_count && (i == cb->cb_vdev_names_count)) {
3342 /* Couldn't match the name */
3343 goto children;
3344 }
3345
3346
3347 verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
3348 (uint64_t **)&newvs, &c) == 0);
3349
3350 /*
3351 * Print the vdev name unless it's is a histogram. Histograms
3352 * display the vdev name in the header itself.
3353 */
3354 if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
3355 if (cb->cb_scripted) {
3356 printf("%s", name);
3357 } else {
3358 if (strlen(name) + depth > cb->cb_namewidth)
3359 (void) printf("%*s%s", depth, "", name);
3360 else
3361 (void) printf("%*s%s%*s", depth, "", name,
3362 (int)(cb->cb_namewidth - strlen(name) -
3363 depth), "");
3364 }
3365 }
3366
3367 /* Calculate our scaling factor */
3368 tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
3369 if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
3370 /*
3371 * If we specify printing histograms with no time interval, then
3372 * print the histogram numbers over the entire lifetime of the
3373 * vdev.
3374 */
3375 scale = 1;
3376 } else {
3377 if (tdelta == 0)
3378 scale = 1.0;
3379 else
3380 scale = (double)NANOSEC / tdelta;
3381 }
3382
3383 if (cb->cb_flags & IOS_DEFAULT_M) {
3384 calc_default_iostats(oldvs, newvs, calcvs);
3385 print_iostat_default(calcvs, cb, scale);
3386 }
3387 if (cb->cb_flags & IOS_LATENCY_M)
3388 print_iostat_latency(cb, oldnv, newnv, scale);
3389 if (cb->cb_flags & IOS_QUEUES_M)
3390 print_iostat_queues(cb, oldnv, newnv, scale);
3391 if (cb->cb_flags & IOS_ANYHISTO_M) {
3392 printf("\n");
3393 print_iostat_histos(cb, oldnv, newnv, scale, name);
3394 }
3395
3396 if (!(cb->cb_flags & IOS_ANYHISTO_M))
3397 printf("\n");
3398
3399 ret++;
3400
3401 children:
3402
3403 free(calcvs);
3404
3405 if (!cb->cb_verbose)
3406 return (ret);
3407
3408 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
3409 &newchild, &children) != 0)
3410 return (ret);
3411
3412 if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
3413 &oldchild, &c) != 0)
3414 return (ret);
3415
3416 for (c = 0; c < children; c++) {
3417 uint64_t ishole = B_FALSE, islog = B_FALSE;
3418
3419 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
3420 &ishole);
3421
3422 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
3423 &islog);
3424
3425 if (ishole || islog)
3426 continue;
3427
3428 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3429 cb->cb_name_flags);
3430 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
3431 newchild[c], cb, depth + 2);
3432 free(vname);
3433 }
3434
3435 /*
3436 * Log device section
3437 */
3438
3439 if (num_logs(newnv) > 0) {
3440 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
3441 !cb->cb_vdev_names) {
3442 print_iostat_dashes(cb, 0, "logs");
3443 }
3444
3445 for (c = 0; c < children; c++) {
3446 uint64_t islog = B_FALSE;
3447 (void) nvlist_lookup_uint64(newchild[c],
3448 ZPOOL_CONFIG_IS_LOG, &islog);
3449
3450 if (islog) {
3451 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3452 cb->cb_name_flags);
3453 ret += print_vdev_stats(zhp, vname, oldnv ?
3454 oldchild[c] : NULL, newchild[c],
3455 cb, depth + 2);
3456 free(vname);
3457 }
3458 }
3459
3460 }
3461
3462 /*
3463 * Include level 2 ARC devices in iostat output
3464 */
3465 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
3466 &newchild, &children) != 0)
3467 return (ret);
3468
3469 if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
3470 &oldchild, &c) != 0)
3471 return (ret);
3472
3473 if (children > 0) {
3474 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
3475 !cb->cb_vdev_names) {
3476 print_iostat_dashes(cb, 0, "cache");
3477 }
3478
3479 for (c = 0; c < children; c++) {
3480 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3481 cb->cb_name_flags);
3482 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
3483 : NULL, newchild[c], cb, depth + 2);
3484 free(vname);
3485 }
3486 }
3487
3488 return (ret);
3489 }
3490
3491 static int
3492 refresh_iostat(zpool_handle_t *zhp, void *data)
3493 {
3494 iostat_cbdata_t *cb = data;
3495 boolean_t missing;
3496
3497 /*
3498 * If the pool has disappeared, remove it from the list and continue.
3499 */
3500 if (zpool_refresh_stats(zhp, &missing) != 0)
3501 return (-1);
3502
3503 if (missing)
3504 pool_list_remove(cb->cb_list, zhp);
3505
3506 return (0);
3507 }
3508
3509 /*
3510 * Callback to print out the iostats for the given pool.
3511 */
3512 int
3513 print_iostat(zpool_handle_t *zhp, void *data)
3514 {
3515 iostat_cbdata_t *cb = data;
3516 nvlist_t *oldconfig, *newconfig;
3517 nvlist_t *oldnvroot, *newnvroot;
3518 int ret;
3519
3520 newconfig = zpool_get_config(zhp, &oldconfig);
3521
3522 if (cb->cb_iteration == 1)
3523 oldconfig = NULL;
3524
3525 verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
3526 &newnvroot) == 0);
3527
3528 if (oldconfig == NULL)
3529 oldnvroot = NULL;
3530 else
3531 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
3532 &oldnvroot) == 0);
3533
3534 ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
3535 cb, 0);
3536 if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
3537 !cb->cb_scripted && cb->cb_verbose && !cb->cb_vdev_names_count) {
3538 print_iostat_separator(cb);
3539 }
3540
3541 return (ret);
3542 }
3543
3544 static int
3545 get_columns(void)
3546 {
3547 struct winsize ws;
3548 int columns = 80;
3549 int error;
3550
3551 if (isatty(STDOUT_FILENO)) {
3552 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
3553 if (error == 0)
3554 columns = ws.ws_col;
3555 } else {
3556 columns = 999;
3557 }
3558
3559 return (columns);
3560 }
3561
3562 int
3563 get_namewidth(zpool_handle_t *zhp, void *data)
3564 {
3565 iostat_cbdata_t *cb = data;
3566 nvlist_t *config, *nvroot;
3567 int columns;
3568
3569 if ((config = zpool_get_config(zhp, NULL)) != NULL) {
3570 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3571 &nvroot) == 0);
3572 unsigned int poolname_len = strlen(zpool_get_name(zhp));
3573 if (!cb->cb_verbose)
3574 cb->cb_namewidth = poolname_len;
3575 else
3576 cb->cb_namewidth = MAX(poolname_len,
3577 max_width(zhp, nvroot, 0, cb->cb_namewidth,
3578 cb->cb_name_flags));
3579 }
3580 /*
3581 * The width must be at least 10, but may be as large as the
3582 * column width - 42 so that we can still fit in one line.
3583 */
3584 columns = get_columns();
3585
3586 if (cb->cb_namewidth < 10)
3587 cb->cb_namewidth = 10;
3588 if (cb->cb_namewidth > columns - 42)
3589 cb->cb_namewidth = columns - 42;
3590
3591 return (0);
3592 }
3593
3594 /*
3595 * Parse the input string, get the 'interval' and 'count' value if there is one.
3596 */
3597 static void
3598 get_interval_count(int *argcp, char **argv, float *iv,
3599 unsigned long *cnt)
3600 {
3601 float interval = 0;
3602 unsigned long count = 0;
3603 int argc = *argcp;
3604
3605 /*
3606 * Determine if the last argument is an integer or a pool name
3607 */
3608 if (argc > 0 && isnumber(argv[argc - 1])) {
3609 char *end;
3610
3611 errno = 0;
3612 interval = strtof(argv[argc - 1], &end);
3613
3614 if (*end == '\0' && errno == 0) {
3615 if (interval == 0) {
3616 (void) fprintf(stderr, gettext("interval "
3617 "cannot be zero\n"));
3618 usage(B_FALSE);
3619 }
3620 /*
3621 * Ignore the last parameter
3622 */
3623 argc--;
3624 } else {
3625 /*
3626 * If this is not a valid number, just plow on. The
3627 * user will get a more informative error message later
3628 * on.
3629 */
3630 interval = 0;
3631 }
3632 }
3633
3634 /*
3635 * If the last argument is also an integer, then we have both a count
3636 * and an interval.
3637 */
3638 if (argc > 0 && isnumber(argv[argc - 1])) {
3639 char *end;
3640
3641 errno = 0;
3642 count = interval;
3643 interval = strtof(argv[argc - 1], &end);
3644
3645 if (*end == '\0' && errno == 0) {
3646 if (interval == 0) {
3647 (void) fprintf(stderr, gettext("interval "
3648 "cannot be zero\n"));
3649 usage(B_FALSE);
3650 }
3651
3652 /*
3653 * Ignore the last parameter
3654 */
3655 argc--;
3656 } else {
3657 interval = 0;
3658 }
3659 }
3660
3661 *iv = interval;
3662 *cnt = count;
3663 *argcp = argc;
3664 }
3665
3666 static void
3667 get_timestamp_arg(char c)
3668 {
3669 if (c == 'u')
3670 timestamp_fmt = UDATE;
3671 else if (c == 'd')
3672 timestamp_fmt = DDATE;
3673 else
3674 usage(B_FALSE);
3675 }
3676
3677 /*
3678 * Return stat flags that are supported by all pools by both the module and
3679 * zpool iostat. "*data" should be initialized to all 0xFFs before running.
3680 * It will get ANDed down until only the flags that are supported on all pools
3681 * remain.
3682 */
3683 static int
3684 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
3685 {
3686 uint64_t *mask = data;
3687 nvlist_t *config, *nvroot, *nvx;
3688 uint64_t flags = 0;
3689 int i, j;
3690
3691 config = zpool_get_config(zhp, NULL);
3692 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3693 &nvroot) == 0);
3694
3695 /* Default stats are always supported, but for completeness.. */
3696 if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
3697 flags |= IOS_DEFAULT_M;
3698
3699 /* Get our extended stats nvlist from the main list */
3700 if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
3701 &nvx) != 0) {
3702 /*
3703 * No extended stats; they're probably running an older
3704 * module. No big deal, we support that too.
3705 */
3706 goto end;
3707 }
3708
3709 /* For each extended stat, make sure all its nvpairs are supported */
3710 for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
3711 if (!vsx_type_to_nvlist[j][0])
3712 continue;
3713
3714 /* Start off by assuming the flag is supported, then check */
3715 flags |= (1ULL << j);
3716 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
3717 if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
3718 /* flag isn't supported */
3719 flags = flags & ~(1ULL << j);
3720 break;
3721 }
3722 }
3723 }
3724 end:
3725 *mask = *mask & flags;
3726 return (0);
3727 }
3728
3729 /*
3730 * Return a bitmask of stats that are supported on all pools by both the module
3731 * and zpool iostat.
3732 */
3733 static uint64_t
3734 get_stat_flags(zpool_list_t *list)
3735 {
3736 uint64_t mask = -1;
3737
3738 /*
3739 * get_stat_flags_cb() will lop off bits from "mask" until only the
3740 * flags that are supported on all pools remain.
3741 */
3742 pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
3743 return (mask);
3744 }
3745
3746 /*
3747 * Return 1 if cb_data->cb_vdev_names[0] is this vdev's name, 0 otherwise.
3748 */
3749 static int
3750 is_vdev_cb(zpool_handle_t *zhp, nvlist_t *nv, void *cb_data)
3751 {
3752 iostat_cbdata_t *cb = cb_data;
3753 char *name = NULL;
3754 int ret = 0;
3755
3756 name = zpool_vdev_name(g_zfs, zhp, nv, cb->cb_name_flags);
3757
3758 if (strcmp(name, cb->cb_vdev_names[0]) == 0)
3759 ret = 1; /* match */
3760 free(name);
3761
3762 return (ret);
3763 }
3764
3765 /*
3766 * Returns 1 if cb_data->cb_vdev_names[0] is a vdev name, 0 otherwise.
3767 */
3768 static int
3769 is_vdev(zpool_handle_t *zhp, void *cb_data)
3770 {
3771 return (for_each_vdev(zhp, is_vdev_cb, cb_data));
3772 }
3773
3774 /*
3775 * Check if vdevs are in a pool
3776 *
3777 * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
3778 * return 0. If pool_name is NULL, then search all pools.
3779 */
3780 static int
3781 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
3782 iostat_cbdata_t *cb)
3783 {
3784 char **tmp_name;
3785 int ret = 0;
3786 int i;
3787 int pool_count = 0;
3788
3789 if ((argc == 0) || !*argv)
3790 return (0);
3791
3792 if (pool_name)
3793 pool_count = 1;
3794
3795 /* Temporarily hijack cb_vdev_names for a second... */
3796 tmp_name = cb->cb_vdev_names;
3797
3798 /* Go though our list of prospective vdev names */
3799 for (i = 0; i < argc; i++) {
3800 cb->cb_vdev_names = argv + i;
3801
3802 /* Is this name a vdev in our pools? */
3803 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
3804 is_vdev, cb);
3805 if (!ret) {
3806 /* No match */
3807 break;
3808 }
3809 }
3810
3811 cb->cb_vdev_names = tmp_name;
3812
3813 return (ret);
3814 }
3815
3816 static int
3817 is_pool_cb(zpool_handle_t *zhp, void *data)
3818 {
3819 char *name = data;
3820 if (strcmp(name, zpool_get_name(zhp)) == 0)
3821 return (1);
3822
3823 return (0);
3824 }
3825
3826 /*
3827 * Do we have a pool named *name? If so, return 1, otherwise 0.
3828 */
3829 static int
3830 is_pool(char *name)
3831 {
3832 return (for_each_pool(0, NULL, B_TRUE, NULL, is_pool_cb, name));
3833 }
3834
3835 /* Are all our argv[] strings pool names? If so return 1, 0 otherwise. */
3836 static int
3837 are_all_pools(int argc, char **argv) {
3838 if ((argc == 0) || !*argv)
3839 return (0);
3840
3841 while (--argc >= 0)
3842 if (!is_pool(argv[argc]))
3843 return (0);
3844
3845 return (1);
3846 }
3847
3848 /*
3849 * Helper function to print out vdev/pool names we can't resolve. Used for an
3850 * error message.
3851 */
3852 static void
3853 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
3854 iostat_cbdata_t *cb)
3855 {
3856 int i;
3857 char *name;
3858 char *str;
3859 for (i = 0; i < argc; i++) {
3860 name = argv[i];
3861
3862 if (is_pool(name))
3863 str = gettext("pool");
3864 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
3865 str = gettext("vdev in this pool");
3866 else if (are_vdevs_in_pool(1, &name, NULL, cb))
3867 str = gettext("vdev in another pool");
3868 else
3869 str = gettext("unknown");
3870
3871 fprintf(stderr, "\t%s (%s)\n", name, str);
3872 }
3873 }
3874
3875 /*
3876 * Same as get_interval_count(), but with additional checks to not misinterpret
3877 * guids as interval/count values. Assumes VDEV_NAME_GUID is set in
3878 * cb.cb_name_flags.
3879 */
3880 static void
3881 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
3882 unsigned long *count, iostat_cbdata_t *cb)
3883 {
3884 char **tmpargv = argv;
3885 int argc_for_interval = 0;
3886
3887 /* Is the last arg an interval value? Or a guid? */
3888 if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL, cb)) {
3889 /*
3890 * The last arg is not a guid, so it's probably an
3891 * interval value.
3892 */
3893 argc_for_interval++;
3894
3895 if (*argc >= 2 &&
3896 !are_vdevs_in_pool(1, &argv[*argc - 2], NULL, cb)) {
3897 /*
3898 * The 2nd to last arg is not a guid, so it's probably
3899 * an interval value.
3900 */
3901 argc_for_interval++;
3902 }
3903 }
3904
3905 /* Point to our list of possible intervals */
3906 tmpargv = &argv[*argc - argc_for_interval];
3907
3908 *argc = *argc - argc_for_interval;
3909 get_interval_count(&argc_for_interval, tmpargv,
3910 interval, count);
3911 }
3912
3913 /*
3914 * Floating point sleep(). Allows you to pass in a floating point value for
3915 * seconds.
3916 */
3917 static void
3918 fsleep(float sec) {
3919 struct timespec req;
3920 req.tv_sec = floor(sec);
3921 req.tv_nsec = (sec - (float)req.tv_sec) * NANOSEC;
3922 nanosleep(&req, NULL);
3923 }
3924
3925
3926 /*
3927 * zpool iostat [-ghHLpPvy] [[-lq]|[-r|-w]] [-n name] [-T d|u]
3928 * [[ pool ...]|[pool vdev ...]|[vdev ...]]
3929 * [interval [count]]
3930 *
3931 * -g Display guid for individual vdev name.
3932 * -L Follow links when resolving vdev path name.
3933 * -P Display full path for vdev name.
3934 * -v Display statistics for individual vdevs
3935 * -h Display help
3936 * -p Display values in parsable (exact) format.
3937 * -H Scripted mode. Don't display headers, and separate properties
3938 * by a single tab.
3939 * -l Display average latency
3940 * -q Display queue depths
3941 * -w Display latency histograms
3942 * -r Display request size histogram
3943 * -T Display a timestamp in date(1) or Unix format
3944 *
3945 * This command can be tricky because we want to be able to deal with pool
3946 * creation/destruction as well as vdev configuration changes. The bulk of this
3947 * processing is handled by the pool_list_* routines in zpool_iter.c. We rely
3948 * on pool_list_update() to detect the addition of new pools. Configuration
3949 * changes are all handled within libzfs.
3950 */
3951 int
3952 zpool_do_iostat(int argc, char **argv)
3953 {
3954 int c;
3955 int ret;
3956 int npools;
3957 float interval = 0;
3958 unsigned long count = 0;
3959 zpool_list_t *list;
3960 boolean_t verbose = B_FALSE;
3961 boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
3962 boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
3963 boolean_t omit_since_boot = B_FALSE;
3964 boolean_t guid = B_FALSE;
3965 boolean_t follow_links = B_FALSE;
3966 boolean_t full_name = B_FALSE;
3967 iostat_cbdata_t cb = { 0 };
3968
3969 /* Used for printing error message */
3970 const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
3971 [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
3972
3973 uint64_t unsupported_flags;
3974
3975 /* check options */
3976 while ((c = getopt(argc, argv, "gLPT:vyhplqrwH")) != -1) {
3977 switch (c) {
3978 case 'g':
3979 guid = B_TRUE;
3980 break;
3981 case 'L':
3982 follow_links = B_TRUE;
3983 break;
3984 case 'P':
3985 full_name = B_TRUE;
3986 break;
3987 case 'T':
3988 get_timestamp_arg(*optarg);
3989 break;
3990 case 'v':
3991 verbose = B_TRUE;
3992 break;
3993 case 'p':
3994 parsable = B_TRUE;
3995 break;
3996 case 'l':
3997 latency = B_TRUE;
3998 break;
3999 case 'q':
4000 queues = B_TRUE;
4001 break;
4002 case 'H':
4003 scripted = B_TRUE;
4004 break;
4005 case 'w':
4006 l_histo = B_TRUE;
4007 break;
4008 case 'r':
4009 rq_histo = B_TRUE;
4010 break;
4011 case 'y':
4012 omit_since_boot = B_TRUE;
4013 break;
4014 case 'h':
4015 usage(B_FALSE);
4016 break;
4017 case '?':
4018 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4019 optopt);
4020 usage(B_FALSE);
4021 }
4022 }
4023
4024 argc -= optind;
4025 argv += optind;
4026
4027 cb.cb_literal = parsable;
4028 cb.cb_scripted = scripted;
4029
4030 if (guid)
4031 cb.cb_name_flags |= VDEV_NAME_GUID;
4032 if (follow_links)
4033 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
4034 if (full_name)
4035 cb.cb_name_flags |= VDEV_NAME_PATH;
4036 cb.cb_iteration = 0;
4037 cb.cb_namewidth = 0;
4038 cb.cb_verbose = verbose;
4039
4040 /* Get our interval and count values (if any) */
4041 if (guid) {
4042 get_interval_count_filter_guids(&argc, argv, &interval,
4043 &count, &cb);
4044 } else {
4045 get_interval_count(&argc, argv, &interval, &count);
4046 }
4047
4048 if (argc == 0) {
4049 /* No args, so just print the defaults. */
4050 } else if (are_all_pools(argc, argv)) {
4051 /* All the args are pool names */
4052 } else if (are_vdevs_in_pool(argc, argv, NULL, &cb)) {
4053 /* All the args are vdevs */
4054 cb.cb_vdev_names = argv;
4055 cb.cb_vdev_names_count = argc;
4056 argc = 0; /* No pools to process */
4057 } else if (are_all_pools(1, argv)) {
4058 /* The first arg is a pool name */
4059 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0], &cb)) {
4060 /* ...and the rest are vdev names */
4061 cb.cb_vdev_names = argv + 1;
4062 cb.cb_vdev_names_count = argc - 1;
4063 argc = 1; /* One pool to process */
4064 } else {
4065 fprintf(stderr, gettext("Expected either a list of "));
4066 fprintf(stderr, gettext("pools, or list of vdevs in"));
4067 fprintf(stderr, " \"%s\", ", argv[0]);
4068 fprintf(stderr, gettext("but got:\n"));
4069 error_list_unresolved_vdevs(argc - 1, argv + 1,
4070 argv[0], &cb);
4071 fprintf(stderr, "\n");
4072 usage(B_FALSE);
4073 return (1);
4074 }
4075 } else {
4076 /*
4077 * The args don't make sense. The first arg isn't a pool name,
4078 * nor are all the args vdevs.
4079 */
4080 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
4081 fprintf(stderr, "\n");
4082 return (1);
4083 }
4084
4085 if (cb.cb_vdev_names_count != 0) {
4086 /*
4087 * If user specified vdevs, it implies verbose.
4088 */
4089 cb.cb_verbose = B_TRUE;
4090 }
4091
4092 /*
4093 * Construct the list of all interesting pools.
4094 */
4095 ret = 0;
4096 if ((list = pool_list_get(argc, argv, NULL, &ret)) == NULL)
4097 return (1);
4098
4099 if (pool_list_count(list) == 0 && argc != 0) {
4100 pool_list_free(list);
4101 return (1);
4102 }
4103
4104 if (pool_list_count(list) == 0 && interval == 0) {
4105 pool_list_free(list);
4106 (void) fprintf(stderr, gettext("no pools available\n"));
4107 return (1);
4108 }
4109
4110 if ((l_histo || rq_histo) && (queues || latency)) {
4111 pool_list_free(list);
4112 (void) fprintf(stderr,
4113 gettext("[-r|-w] isn't allowed with [-q|-l]\n"));
4114 usage(B_FALSE);
4115 return (1);
4116 }
4117
4118 if (l_histo && rq_histo) {
4119 pool_list_free(list);
4120 (void) fprintf(stderr,
4121 gettext("Only one of [-r|-w] can be passed at a time\n"));
4122 usage(B_FALSE);
4123 return (1);
4124 }
4125
4126 /*
4127 * Enter the main iostat loop.
4128 */
4129 cb.cb_list = list;
4130
4131 if (l_histo) {
4132 /*
4133 * Histograms tables look out of place when you try to display
4134 * them with the other stats, so make a rule that you can only
4135 * print histograms by themselves.
4136 */
4137 cb.cb_flags = IOS_L_HISTO_M;
4138 } else if (rq_histo) {
4139 cb.cb_flags = IOS_RQ_HISTO_M;
4140 } else {
4141 cb.cb_flags = IOS_DEFAULT_M;
4142 if (latency)
4143 cb.cb_flags |= IOS_LATENCY_M;
4144 if (queues)
4145 cb.cb_flags |= IOS_QUEUES_M;
4146 }
4147
4148 /*
4149 * See if the module supports all the stats we want to display.
4150 */
4151 unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
4152 if (unsupported_flags) {
4153 uint64_t f;
4154 int idx;
4155 fprintf(stderr,
4156 gettext("The loaded zfs module doesn't support:"));
4157
4158 /* for each bit set in unsupported_flags */
4159 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
4160 idx = lowbit64(f) - 1;
4161 fprintf(stderr, " -%c", flag_to_arg[idx]);
4162 }
4163
4164 fprintf(stderr, ". Try running a newer module.\n"),
4165 pool_list_free(list);
4166
4167 return (1);
4168 }
4169
4170
4171 for (;;) {
4172 if ((npools = pool_list_count(list)) == 0)
4173 (void) fprintf(stderr, gettext("no pools available\n"));
4174 else {
4175 /*
4176 * If this is the first iteration and -y was supplied
4177 * we skip any printing.
4178 */
4179 boolean_t skip = (omit_since_boot &&
4180 cb.cb_iteration == 0);
4181
4182 /*
4183 * Refresh all statistics. This is done as an
4184 * explicit step before calculating the maximum name
4185 * width, so that any * configuration changes are
4186 * properly accounted for.
4187 */
4188 (void) pool_list_iter(list, B_FALSE, refresh_iostat,
4189 &cb);
4190
4191 /*
4192 * Iterate over all pools to determine the maximum width
4193 * for the pool / device name column across all pools.
4194 */
4195 cb.cb_namewidth = 0;
4196 (void) pool_list_iter(list, B_FALSE, get_namewidth,
4197 &cb);
4198
4199 if (timestamp_fmt != NODATE)
4200 print_timestamp(timestamp_fmt);
4201
4202 /*
4203 * If it's the first time and we're not skipping it,
4204 * or either skip or verbose mode, print the header.
4205 *
4206 * The histogram code explicitly prints its header on
4207 * every vdev, so skip this for histograms.
4208 */
4209 if (((++cb.cb_iteration == 1 && !skip) ||
4210 (skip != verbose)) &&
4211 (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
4212 !cb.cb_scripted)
4213 print_iostat_header(&cb);
4214
4215 if (skip) {
4216 (void) fsleep(interval);
4217 continue;
4218 }
4219
4220 pool_list_iter(list, B_FALSE, print_iostat, &cb);
4221
4222 /*
4223 * If there's more than one pool, and we're not in
4224 * verbose mode (which prints a separator for us),
4225 * then print a separator.
4226 *
4227 * In addition, if we're printing specific vdevs then
4228 * we also want an ending separator.
4229 */
4230 if (((npools > 1 && !verbose &&
4231 !(cb.cb_flags & IOS_ANYHISTO_M)) ||
4232 (!(cb.cb_flags & IOS_ANYHISTO_M) &&
4233 cb.cb_vdev_names_count)) &&
4234 !cb.cb_scripted) {
4235 print_iostat_separator(&cb);
4236 }
4237 }
4238
4239 /*
4240 * Flush the output so that redirection to a file isn't buffered
4241 * indefinitely.
4242 */
4243 (void) fflush(stdout);
4244
4245 if (interval == 0)
4246 break;
4247
4248 if (count != 0 && --count == 0)
4249 break;
4250
4251 (void) fsleep(interval);
4252 }
4253
4254 pool_list_free(list);
4255
4256 return (ret);
4257 }
4258
4259 typedef struct list_cbdata {
4260 boolean_t cb_verbose;
4261 int cb_name_flags;
4262 int cb_namewidth;
4263 boolean_t cb_scripted;
4264 zprop_list_t *cb_proplist;
4265 boolean_t cb_literal;
4266 } list_cbdata_t;
4267
4268 /*
4269 * Given a list of columns to display, output appropriate headers for each one.
4270 */
4271 static void
4272 print_header(list_cbdata_t *cb)
4273 {
4274 zprop_list_t *pl = cb->cb_proplist;
4275 char headerbuf[ZPOOL_MAXPROPLEN];
4276 const char *header;
4277 boolean_t first = B_TRUE;
4278 boolean_t right_justify;
4279 size_t width = 0;
4280
4281 for (; pl != NULL; pl = pl->pl_next) {
4282 width = pl->pl_width;
4283 if (first && cb->cb_verbose) {
4284 /*
4285 * Reset the width to accommodate the verbose listing
4286 * of devices.
4287 */
4288 width = cb->cb_namewidth;
4289 }
4290
4291 if (!first)
4292 (void) printf(" ");
4293 else
4294 first = B_FALSE;
4295
4296 right_justify = B_FALSE;
4297 if (pl->pl_prop != ZPROP_INVAL) {
4298 header = zpool_prop_column_name(pl->pl_prop);
4299 right_justify = zpool_prop_align_right(pl->pl_prop);
4300 } else {
4301 int i;
4302
4303 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
4304 headerbuf[i] = toupper(pl->pl_user_prop[i]);
4305 headerbuf[i] = '\0';
4306 header = headerbuf;
4307 }
4308
4309 if (pl->pl_next == NULL && !right_justify)
4310 (void) printf("%s", header);
4311 else if (right_justify)
4312 (void) printf("%*s", (int)width, header);
4313 else
4314 (void) printf("%-*s", (int)width, header);
4315 }
4316
4317 (void) printf("\n");
4318 }
4319
4320 /*
4321 * Given a pool and a list of properties, print out all the properties according
4322 * to the described layout.
4323 */
4324 static void
4325 print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
4326 {
4327 zprop_list_t *pl = cb->cb_proplist;
4328 boolean_t first = B_TRUE;
4329 char property[ZPOOL_MAXPROPLEN];
4330 char *propstr;
4331 boolean_t right_justify;
4332 size_t width;
4333
4334 for (; pl != NULL; pl = pl->pl_next) {
4335
4336 width = pl->pl_width;
4337 if (first && cb->cb_verbose) {
4338 /*
4339 * Reset the width to accommodate the verbose listing
4340 * of devices.
4341 */
4342 width = cb->cb_namewidth;
4343 }
4344
4345 if (!first) {
4346 if (cb->cb_scripted)
4347 (void) printf("\t");
4348 else
4349 (void) printf(" ");
4350 } else {
4351 first = B_FALSE;
4352 }
4353
4354 right_justify = B_FALSE;
4355 if (pl->pl_prop != ZPROP_INVAL) {
4356 if (zpool_get_prop(zhp, pl->pl_prop, property,
4357 sizeof (property), NULL, cb->cb_literal) != 0)
4358 propstr = "-";
4359 else
4360 propstr = property;
4361
4362 right_justify = zpool_prop_align_right(pl->pl_prop);
4363 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
4364 zpool_prop_unsupported(pl->pl_user_prop)) &&
4365 zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
4366 sizeof (property)) == 0) {
4367 propstr = property;
4368 } else {
4369 propstr = "-";
4370 }
4371
4372
4373 /*
4374 * If this is being called in scripted mode, or if this is the
4375 * last column and it is left-justified, don't include a width
4376 * format specifier.
4377 */
4378 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
4379 (void) printf("%s", propstr);
4380 else if (right_justify)
4381 (void) printf("%*s", (int)width, propstr);
4382 else
4383 (void) printf("%-*s", (int)width, propstr);
4384 }
4385
4386 (void) printf("\n");
4387 }
4388
4389 static void
4390 print_one_column(zpool_prop_t prop, uint64_t value, boolean_t scripted,
4391 boolean_t valid, enum zfs_nicenum_format format)
4392 {
4393 char propval[64];
4394 boolean_t fixed;
4395 size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
4396
4397 switch (prop) {
4398 case ZPOOL_PROP_EXPANDSZ:
4399 if (value == 0)
4400 (void) strlcpy(propval, "-", sizeof (propval));
4401 else
4402 zfs_nicenum_format(value, propval, sizeof (propval),
4403 format);
4404 break;
4405 case ZPOOL_PROP_FRAGMENTATION:
4406 if (value == ZFS_FRAG_INVALID) {
4407 (void) strlcpy(propval, "-", sizeof (propval));
4408 } else if (format == ZFS_NICENUM_RAW) {
4409 (void) snprintf(propval, sizeof (propval), "%llu",
4410 (unsigned long long)value);
4411 } else {
4412 (void) snprintf(propval, sizeof (propval), "%llu%%",
4413 (unsigned long long)value);
4414 }
4415 break;
4416 case ZPOOL_PROP_CAPACITY:
4417 if (format == ZFS_NICENUM_RAW)
4418 (void) snprintf(propval, sizeof (propval), "%llu",
4419 (unsigned long long)value);
4420 else
4421 (void) snprintf(propval, sizeof (propval), "%llu%%",
4422 (unsigned long long)value);
4423 break;
4424 default:
4425 zfs_nicenum_format(value, propval, sizeof (propval), format);
4426 }
4427
4428 if (!valid)
4429 (void) strlcpy(propval, "-", sizeof (propval));
4430
4431 if (scripted)
4432 (void) printf("\t%s", propval);
4433 else
4434 (void) printf(" %*s", (int)width, propval);
4435 }
4436
4437 void
4438 print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
4439 list_cbdata_t *cb, int depth)
4440 {
4441 nvlist_t **child;
4442 vdev_stat_t *vs;
4443 uint_t c, children;
4444 char *vname;
4445 boolean_t scripted = cb->cb_scripted;
4446 uint64_t islog = B_FALSE;
4447 boolean_t haslog = B_FALSE;
4448 char *dashes = "%-*s - - - - - -\n";
4449
4450 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
4451 (uint64_t **)&vs, &c) == 0);
4452
4453 if (name != NULL) {
4454 boolean_t toplevel = (vs->vs_space != 0);
4455 uint64_t cap;
4456 enum zfs_nicenum_format format;
4457
4458 if (cb->cb_literal)
4459 format = ZFS_NICENUM_RAW;
4460 else
4461 format = ZFS_NICENUM_1024;
4462
4463 if (scripted)
4464 (void) printf("\t%s", name);
4465 else if (strlen(name) + depth > cb->cb_namewidth)
4466 (void) printf("%*s%s", depth, "", name);
4467 else
4468 (void) printf("%*s%s%*s", depth, "", name,
4469 (int)(cb->cb_namewidth - strlen(name) - depth), "");
4470
4471 /*
4472 * Print the properties for the individual vdevs. Some
4473 * properties are only applicable to toplevel vdevs. The
4474 * 'toplevel' boolean value is passed to the print_one_column()
4475 * to indicate that the value is valid.
4476 */
4477 print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, scripted,
4478 toplevel, format);
4479 print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, scripted,
4480 toplevel, format);
4481 print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
4482 scripted, toplevel, format);
4483 print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, scripted,
4484 B_TRUE, format);
4485 print_one_column(ZPOOL_PROP_FRAGMENTATION,
4486 vs->vs_fragmentation, scripted,
4487 (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
4488 format);
4489 cap = (vs->vs_space == 0) ? 0 :
4490 (vs->vs_alloc * 100 / vs->vs_space);
4491 print_one_column(ZPOOL_PROP_CAPACITY, cap, scripted, toplevel,
4492 format);
4493 (void) printf("\n");
4494 }
4495
4496 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
4497 &child, &children) != 0)
4498 return;
4499
4500 for (c = 0; c < children; c++) {
4501 uint64_t ishole = B_FALSE;
4502
4503 if (nvlist_lookup_uint64(child[c],
4504 ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
4505 continue;
4506
4507 if (nvlist_lookup_uint64(child[c],
4508 ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog) {
4509 haslog = B_TRUE;
4510 continue;
4511 }
4512
4513 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4514 cb->cb_name_flags);
4515 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4516 free(vname);
4517 }
4518
4519 if (haslog == B_TRUE) {
4520 /* LINTED E_SEC_PRINTF_VAR_FMT */
4521 (void) printf(dashes, cb->cb_namewidth, "log");
4522 for (c = 0; c < children; c++) {
4523 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
4524 &islog) != 0 || !islog)
4525 continue;
4526 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4527 cb->cb_name_flags);
4528 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4529 free(vname);
4530 }
4531 }
4532
4533 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
4534 &child, &children) == 0 && children > 0) {
4535 /* LINTED E_SEC_PRINTF_VAR_FMT */
4536 (void) printf(dashes, cb->cb_namewidth, "cache");
4537 for (c = 0; c < children; c++) {
4538 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4539 cb->cb_name_flags);
4540 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4541 free(vname);
4542 }
4543 }
4544
4545 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
4546 &children) == 0 && children > 0) {
4547 /* LINTED E_SEC_PRINTF_VAR_FMT */
4548 (void) printf(dashes, cb->cb_namewidth, "spare");
4549 for (c = 0; c < children; c++) {
4550 vname = zpool_vdev_name(g_zfs, zhp, child[c],
4551 cb->cb_name_flags);
4552 print_list_stats(zhp, vname, child[c], cb, depth + 2);
4553 free(vname);
4554 }
4555 }
4556 }
4557
4558
4559 /*
4560 * Generic callback function to list a pool.
4561 */
4562 int
4563 list_callback(zpool_handle_t *zhp, void *data)
4564 {
4565 list_cbdata_t *cbp = data;
4566 nvlist_t *config;
4567 nvlist_t *nvroot;
4568
4569 config = zpool_get_config(zhp, NULL);
4570
4571 print_pool(zhp, cbp);
4572 if (!cbp->cb_verbose)
4573 return (0);
4574
4575 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4576 &nvroot) == 0);
4577 print_list_stats(zhp, NULL, nvroot, cbp, 0);
4578
4579 return (0);
4580 }
4581
4582 /*
4583 * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
4584 *
4585 * -g Display guid for individual vdev name.
4586 * -H Scripted mode. Don't display headers, and separate properties
4587 * by a single tab.
4588 * -L Follow links when resolving vdev path name.
4589 * -o List of properties to display. Defaults to
4590 * "name,size,allocated,free,expandsize,fragmentation,capacity,"
4591 * "dedupratio,health,altroot"
4592 * -p Display values in parsable (exact) format.
4593 * -P Display full path for vdev name.
4594 * -T Display a timestamp in date(1) or Unix format
4595 *
4596 * List all pools in the system, whether or not they're healthy. Output space
4597 * statistics for each one, as well as health status summary.
4598 */
4599 int
4600 zpool_do_list(int argc, char **argv)
4601 {
4602 int c;
4603 int ret = 0;
4604 list_cbdata_t cb = { 0 };
4605 static char default_props[] =
4606 "name,size,allocated,free,expandsize,fragmentation,capacity,"
4607 "dedupratio,health,altroot";
4608 char *props = default_props;
4609 float interval = 0;
4610 unsigned long count = 0;
4611 zpool_list_t *list;
4612 boolean_t first = B_TRUE;
4613
4614 /* check options */
4615 while ((c = getopt(argc, argv, ":gHLo:pPT:v")) != -1) {
4616 switch (c) {
4617 case 'g':
4618 cb.cb_name_flags |= VDEV_NAME_GUID;
4619 break;
4620 case 'H':
4621 cb.cb_scripted = B_TRUE;
4622 break;
4623 case 'L':
4624 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
4625 break;
4626 case 'o':
4627 props = optarg;
4628 break;
4629 case 'P':
4630 cb.cb_name_flags |= VDEV_NAME_PATH;
4631 break;
4632 case 'p':
4633 cb.cb_literal = B_TRUE;
4634 break;
4635 case 'T':
4636 get_timestamp_arg(*optarg);
4637 break;
4638 case 'v':
4639 cb.cb_verbose = B_TRUE;
4640 break;
4641 case ':':
4642 (void) fprintf(stderr, gettext("missing argument for "
4643 "'%c' option\n"), optopt);
4644 usage(B_FALSE);
4645 break;
4646 case '?':
4647 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4648 optopt);
4649 usage(B_FALSE);
4650 }
4651 }
4652
4653 argc -= optind;
4654 argv += optind;
4655
4656 get_interval_count(&argc, argv, &interval, &count);
4657
4658 if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
4659 usage(B_FALSE);
4660
4661 for (;;) {
4662 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
4663 &ret)) == NULL)
4664 return (1);
4665
4666 if (pool_list_count(list) == 0)
4667 break;
4668
4669 if (timestamp_fmt != NODATE)
4670 print_timestamp(timestamp_fmt);
4671
4672 if (!cb.cb_scripted && (first || cb.cb_verbose)) {
4673 print_header(&cb);
4674 first = B_FALSE;
4675 }
4676 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
4677
4678 if (interval == 0)
4679 break;
4680
4681 if (count != 0 && --count == 0)
4682 break;
4683
4684 pool_list_free(list);
4685 (void) fsleep(interval);
4686 }
4687
4688 if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
4689 (void) printf(gettext("no pools available\n"));
4690 ret = 0;
4691 }
4692
4693 pool_list_free(list);
4694 zprop_free_list(cb.cb_proplist);
4695 return (ret);
4696 }
4697
4698 static int
4699 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
4700 {
4701 boolean_t force = B_FALSE;
4702 int c;
4703 nvlist_t *nvroot;
4704 char *poolname, *old_disk, *new_disk;
4705 zpool_handle_t *zhp;
4706 nvlist_t *props = NULL;
4707 char *propval;
4708 int ret;
4709
4710 /* check options */
4711 while ((c = getopt(argc, argv, "fo:")) != -1) {
4712 switch (c) {
4713 case 'f':
4714 force = B_TRUE;
4715 break;
4716 case 'o':
4717 if ((propval = strchr(optarg, '=')) == NULL) {
4718 (void) fprintf(stderr, gettext("missing "
4719 "'=' for -o option\n"));
4720 usage(B_FALSE);
4721 }
4722 *propval = '\0';
4723 propval++;
4724
4725 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
4726 (add_prop_list(optarg, propval, &props, B_TRUE)))
4727 usage(B_FALSE);
4728 break;
4729 case '?':
4730 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4731 optopt);
4732 usage(B_FALSE);
4733 }
4734 }
4735
4736 argc -= optind;
4737 argv += optind;
4738
4739 /* get pool name and check number of arguments */
4740 if (argc < 1) {
4741 (void) fprintf(stderr, gettext("missing pool name argument\n"));
4742 usage(B_FALSE);
4743 }
4744
4745 poolname = argv[0];
4746
4747 if (argc < 2) {
4748 (void) fprintf(stderr,
4749 gettext("missing <device> specification\n"));
4750 usage(B_FALSE);
4751 }
4752
4753 old_disk = argv[1];
4754
4755 if (argc < 3) {
4756 if (!replacing) {
4757 (void) fprintf(stderr,
4758 gettext("missing <new_device> specification\n"));
4759 usage(B_FALSE);
4760 }
4761 new_disk = old_disk;
4762 argc -= 1;
4763 argv += 1;
4764 } else {
4765 new_disk = argv[2];
4766 argc -= 2;
4767 argv += 2;
4768 }
4769
4770 if (argc > 1) {
4771 (void) fprintf(stderr, gettext("too many arguments\n"));
4772 usage(B_FALSE);
4773 }
4774
4775 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
4776 nvlist_free(props);
4777 return (1);
4778 }
4779
4780 if (zpool_get_config(zhp, NULL) == NULL) {
4781 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
4782 poolname);
4783 zpool_close(zhp);
4784 nvlist_free(props);
4785 return (1);
4786 }
4787
4788 nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
4789 argc, argv);
4790 if (nvroot == NULL) {
4791 zpool_close(zhp);
4792 nvlist_free(props);
4793 return (1);
4794 }
4795
4796 ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing);
4797
4798 nvlist_free(props);
4799 nvlist_free(nvroot);
4800 zpool_close(zhp);
4801
4802 return (ret);
4803 }
4804
4805 /*
4806 * zpool replace [-f] <pool> <device> <new_device>
4807 *
4808 * -f Force attach, even if <new_device> appears to be in use.
4809 *
4810 * Replace <device> with <new_device>.
4811 */
4812 /* ARGSUSED */
4813 int
4814 zpool_do_replace(int argc, char **argv)
4815 {
4816 return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
4817 }
4818
4819 /*
4820 * zpool attach [-f] [-o property=value] <pool> <device> <new_device>
4821 *
4822 * -f Force attach, even if <new_device> appears to be in use.
4823 * -o Set property=value.
4824 *
4825 * Attach <new_device> to the mirror containing <device>. If <device> is not
4826 * part of a mirror, then <device> will be transformed into a mirror of
4827 * <device> and <new_device>. In either case, <new_device> will begin life
4828 * with a DTL of [0, now], and will immediately begin to resilver itself.
4829 */
4830 int
4831 zpool_do_attach(int argc, char **argv)
4832 {
4833 return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
4834 }
4835
4836 /*
4837 * zpool detach [-f] <pool> <device>
4838 *
4839 * -f Force detach of <device>, even if DTLs argue against it
4840 * (not supported yet)
4841 *
4842 * Detach a device from a mirror. The operation will be refused if <device>
4843 * is the last device in the mirror, or if the DTLs indicate that this device
4844 * has the only valid copy of some data.
4845 */
4846 /* ARGSUSED */
4847 int
4848 zpool_do_detach(int argc, char **argv)
4849 {
4850 int c;
4851 char *poolname, *path;
4852 zpool_handle_t *zhp;
4853 int ret;
4854
4855 /* check options */
4856 while ((c = getopt(argc, argv, "f")) != -1) {
4857 switch (c) {
4858 case 'f':
4859 case '?':
4860 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4861 optopt);
4862 usage(B_FALSE);
4863 }
4864 }
4865
4866 argc -= optind;
4867 argv += optind;
4868
4869 /* get pool name and check number of arguments */
4870 if (argc < 1) {
4871 (void) fprintf(stderr, gettext("missing pool name argument\n"));
4872 usage(B_FALSE);
4873 }
4874
4875 if (argc < 2) {
4876 (void) fprintf(stderr,
4877 gettext("missing <device> specification\n"));
4878 usage(B_FALSE);
4879 }
4880
4881 poolname = argv[0];
4882 path = argv[1];
4883
4884 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
4885 return (1);
4886
4887 ret = zpool_vdev_detach(zhp, path);
4888
4889 zpool_close(zhp);
4890
4891 return (ret);
4892 }
4893
4894 /*
4895 * zpool split [-gLnP] [-o prop=val] ...
4896 * [-o mntopt] ...
4897 * [-R altroot] <pool> <newpool> [<device> ...]
4898 *
4899 * -g Display guid for individual vdev name.
4900 * -L Follow links when resolving vdev path name.
4901 * -n Do not split the pool, but display the resulting layout if
4902 * it were to be split.
4903 * -o Set property=value, or set mount options.
4904 * -P Display full path for vdev name.
4905 * -R Mount the split-off pool under an alternate root.
4906 *
4907 * Splits the named pool and gives it the new pool name. Devices to be split
4908 * off may be listed, provided that no more than one device is specified
4909 * per top-level vdev mirror. The newly split pool is left in an exported
4910 * state unless -R is specified.
4911 *
4912 * Restrictions: the top-level of the pool pool must only be made up of
4913 * mirrors; all devices in the pool must be healthy; no device may be
4914 * undergoing a resilvering operation.
4915 */
4916 int
4917 zpool_do_split(int argc, char **argv)
4918 {
4919 char *srcpool, *newpool, *propval;
4920 char *mntopts = NULL;
4921 splitflags_t flags;
4922 int c, ret = 0;
4923 zpool_handle_t *zhp;
4924 nvlist_t *config, *props = NULL;
4925
4926 flags.dryrun = B_FALSE;
4927 flags.import = B_FALSE;
4928 flags.name_flags = 0;
4929
4930 /* check options */
4931 while ((c = getopt(argc, argv, ":gLR:no:P")) != -1) {
4932 switch (c) {
4933 case 'g':
4934 flags.name_flags |= VDEV_NAME_GUID;
4935 break;
4936 case 'L':
4937 flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
4938 break;
4939 case 'R':
4940 flags.import = B_TRUE;
4941 if (add_prop_list(
4942 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
4943 &props, B_TRUE) != 0) {
4944 nvlist_free(props);
4945 usage(B_FALSE);
4946 }
4947 break;
4948 case 'n':
4949 flags.dryrun = B_TRUE;
4950 break;
4951 case 'o':
4952 if ((propval = strchr(optarg, '=')) != NULL) {
4953 *propval = '\0';
4954 propval++;
4955 if (add_prop_list(optarg, propval,
4956 &props, B_TRUE) != 0) {
4957 nvlist_free(props);
4958 usage(B_FALSE);
4959 }
4960 } else {
4961 mntopts = optarg;
4962 }
4963 break;
4964 case 'P':
4965 flags.name_flags |= VDEV_NAME_PATH;
4966 break;
4967 case ':':
4968 (void) fprintf(stderr, gettext("missing argument for "
4969 "'%c' option\n"), optopt);
4970 usage(B_FALSE);
4971 break;
4972 case '?':
4973 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4974 optopt);
4975 usage(B_FALSE);
4976 break;
4977 }
4978 }
4979
4980 if (!flags.import && mntopts != NULL) {
4981 (void) fprintf(stderr, gettext("setting mntopts is only "
4982 "valid when importing the pool\n"));
4983 usage(B_FALSE);
4984 }
4985
4986 argc -= optind;
4987 argv += optind;
4988
4989 if (argc < 1) {
4990 (void) fprintf(stderr, gettext("Missing pool name\n"));
4991 usage(B_FALSE);
4992 }
4993 if (argc < 2) {
4994 (void) fprintf(stderr, gettext("Missing new pool name\n"));
4995 usage(B_FALSE);
4996 }
4997
4998 srcpool = argv[0];
4999 newpool = argv[1];
5000
5001 argc -= 2;
5002 argv += 2;
5003
5004 if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
5005 nvlist_free(props);
5006 return (1);
5007 }
5008
5009 config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
5010 if (config == NULL) {
5011 ret = 1;
5012 } else {
5013 if (flags.dryrun) {
5014 (void) printf(gettext("would create '%s' with the "
5015 "following layout:\n\n"), newpool);
5016 print_vdev_tree(NULL, newpool, config, 0, B_FALSE,
5017 flags.name_flags);
5018 }
5019 }
5020
5021 zpool_close(zhp);
5022
5023 if (ret != 0 || flags.dryrun || !flags.import) {
5024 nvlist_free(config);
5025 nvlist_free(props);
5026 return (ret);
5027 }
5028
5029 /*
5030 * The split was successful. Now we need to open the new
5031 * pool and import it.
5032 */
5033 if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
5034 nvlist_free(config);
5035 nvlist_free(props);
5036 return (1);
5037 }
5038 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
5039 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
5040 ret = 1;
5041 (void) fprintf(stderr, gettext("Split was successful, but "
5042 "the datasets could not all be mounted\n"));
5043 (void) fprintf(stderr, gettext("Try doing '%s' with a "
5044 "different altroot\n"), "zpool import");
5045 }
5046 zpool_close(zhp);
5047 nvlist_free(config);
5048 nvlist_free(props);
5049
5050 return (ret);
5051 }
5052
5053
5054
5055 /*
5056 * zpool online <pool> <device> ...
5057 */
5058 int
5059 zpool_do_online(int argc, char **argv)
5060 {
5061 int c, i;
5062 char *poolname;
5063 zpool_handle_t *zhp;
5064 int ret = 0;
5065 vdev_state_t newstate;
5066 int flags = 0;
5067
5068 /* check options */
5069 while ((c = getopt(argc, argv, "et")) != -1) {
5070 switch (c) {
5071 case 'e':
5072 flags |= ZFS_ONLINE_EXPAND;
5073 break;
5074 case 't':
5075 case '?':
5076 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5077 optopt);
5078 usage(B_FALSE);
5079 }
5080 }
5081
5082 argc -= optind;
5083 argv += optind;
5084
5085 /* get pool name and check number of arguments */
5086 if (argc < 1) {
5087 (void) fprintf(stderr, gettext("missing pool name\n"));
5088 usage(B_FALSE);
5089 }
5090 if (argc < 2) {
5091 (void) fprintf(stderr, gettext("missing device name\n"));
5092 usage(B_FALSE);
5093 }
5094
5095 poolname = argv[0];
5096
5097 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5098 return (1);
5099
5100 for (i = 1; i < argc; i++) {
5101 if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
5102 if (newstate != VDEV_STATE_HEALTHY) {
5103 (void) printf(gettext("warning: device '%s' "
5104 "onlined, but remains in faulted state\n"),
5105 argv[i]);
5106 if (newstate == VDEV_STATE_FAULTED)
5107 (void) printf(gettext("use 'zpool "
5108 "clear' to restore a faulted "
5109 "device\n"));
5110 else
5111 (void) printf(gettext("use 'zpool "
5112 "replace' to replace devices "
5113 "that are no longer present\n"));
5114 }
5115 } else {
5116 ret = 1;
5117 }
5118 }
5119
5120 zpool_close(zhp);
5121
5122 return (ret);
5123 }
5124
5125 /*
5126 * zpool offline [-ft] <pool> <device> ...
5127 *
5128 * -f Force the device into the offline state, even if doing
5129 * so would appear to compromise pool availability.
5130 * (not supported yet)
5131 *
5132 * -t Only take the device off-line temporarily. The offline
5133 * state will not be persistent across reboots.
5134 */
5135 /* ARGSUSED */
5136 int
5137 zpool_do_offline(int argc, char **argv)
5138 {
5139 int c, i;
5140 char *poolname;
5141 zpool_handle_t *zhp;
5142 int ret = 0;
5143 boolean_t istmp = B_FALSE;
5144
5145 /* check options */
5146 while ((c = getopt(argc, argv, "ft")) != -1) {
5147 switch (c) {
5148 case 't':
5149 istmp = B_TRUE;
5150 break;
5151 case 'f':
5152 case '?':
5153 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5154 optopt);
5155 usage(B_FALSE);
5156 }
5157 }
5158
5159 argc -= optind;
5160 argv += optind;
5161
5162 /* get pool name and check number of arguments */
5163 if (argc < 1) {
5164 (void) fprintf(stderr, gettext("missing pool name\n"));
5165 usage(B_FALSE);
5166 }
5167 if (argc < 2) {
5168 (void) fprintf(stderr, gettext("missing device name\n"));
5169 usage(B_FALSE);
5170 }
5171
5172 poolname = argv[0];
5173
5174 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5175 return (1);
5176
5177 for (i = 1; i < argc; i++) {
5178 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
5179 ret = 1;
5180 }
5181
5182 zpool_close(zhp);
5183
5184 return (ret);
5185 }
5186
5187 /*
5188 * zpool clear <pool> [device]
5189 *
5190 * Clear all errors associated with a pool or a particular device.
5191 */
5192 int
5193 zpool_do_clear(int argc, char **argv)
5194 {
5195 int c;
5196 int ret = 0;
5197 boolean_t dryrun = B_FALSE;
5198 boolean_t do_rewind = B_FALSE;
5199 boolean_t xtreme_rewind = B_FALSE;
5200 uint32_t rewind_policy = ZPOOL_NO_REWIND;
5201 nvlist_t *policy = NULL;
5202 zpool_handle_t *zhp;
5203 char *pool, *device;
5204
5205 /* check options */
5206 while ((c = getopt(argc, argv, "FnX")) != -1) {
5207 switch (c) {
5208 case 'F':
5209 do_rewind = B_TRUE;
5210 break;
5211 case 'n':
5212 dryrun = B_TRUE;
5213 break;
5214 case 'X':
5215 xtreme_rewind = B_TRUE;
5216 break;
5217 case '?':
5218 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5219 optopt);
5220 usage(B_FALSE);
5221 }
5222 }
5223
5224 argc -= optind;
5225 argv += optind;
5226
5227 if (argc < 1) {
5228 (void) fprintf(stderr, gettext("missing pool name\n"));
5229 usage(B_FALSE);
5230 }
5231
5232 if (argc > 2) {
5233 (void) fprintf(stderr, gettext("too many arguments\n"));
5234 usage(B_FALSE);
5235 }
5236
5237 if ((dryrun || xtreme_rewind) && !do_rewind) {
5238 (void) fprintf(stderr,
5239 gettext("-n or -X only meaningful with -F\n"));
5240 usage(B_FALSE);
5241 }
5242 if (dryrun)
5243 rewind_policy = ZPOOL_TRY_REWIND;
5244 else if (do_rewind)
5245 rewind_policy = ZPOOL_DO_REWIND;
5246 if (xtreme_rewind)
5247 rewind_policy |= ZPOOL_EXTREME_REWIND;
5248
5249 /* In future, further rewind policy choices can be passed along here */
5250 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
5251 nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
5252 return (1);
5253
5254 pool = argv[0];
5255 device = argc == 2 ? argv[1] : NULL;
5256
5257 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
5258 nvlist_free(policy);
5259 return (1);
5260 }
5261
5262 if (zpool_clear(zhp, device, policy) != 0)
5263 ret = 1;
5264
5265 zpool_close(zhp);
5266
5267 nvlist_free(policy);
5268
5269 return (ret);
5270 }
5271
5272 /*
5273 * zpool reguid <pool>
5274 */
5275 int
5276 zpool_do_reguid(int argc, char **argv)
5277 {
5278 int c;
5279 char *poolname;
5280 zpool_handle_t *zhp;
5281 int ret = 0;
5282
5283 /* check options */
5284 while ((c = getopt(argc, argv, "")) != -1) {
5285 switch (c) {
5286 case '?':
5287 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5288 optopt);
5289 usage(B_FALSE);
5290 }
5291 }
5292
5293 argc -= optind;
5294 argv += optind;
5295
5296 /* get pool name and check number of arguments */
5297 if (argc < 1) {
5298 (void) fprintf(stderr, gettext("missing pool name\n"));
5299 usage(B_FALSE);
5300 }
5301
5302 if (argc > 1) {
5303 (void) fprintf(stderr, gettext("too many arguments\n"));
5304 usage(B_FALSE);
5305 }
5306
5307 poolname = argv[0];
5308 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5309 return (1);
5310
5311 ret = zpool_reguid(zhp);
5312
5313 zpool_close(zhp);
5314 return (ret);
5315 }
5316
5317
5318 /*
5319 * zpool reopen <pool>
5320 *
5321 * Reopen the pool so that the kernel can update the sizes of all vdevs.
5322 */
5323 int
5324 zpool_do_reopen(int argc, char **argv)
5325 {
5326 int c;
5327 int ret = 0;
5328 zpool_handle_t *zhp;
5329 char *pool;
5330
5331 /* check options */
5332 while ((c = getopt(argc, argv, "")) != -1) {
5333 switch (c) {
5334 case '?':
5335 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5336 optopt);
5337 usage(B_FALSE);
5338 }
5339 }
5340
5341 argc--;
5342 argv++;
5343
5344 if (argc < 1) {
5345 (void) fprintf(stderr, gettext("missing pool name\n"));
5346 usage(B_FALSE);
5347 }
5348
5349 if (argc > 1) {
5350 (void) fprintf(stderr, gettext("too many arguments\n"));
5351 usage(B_FALSE);
5352 }
5353
5354 pool = argv[0];
5355 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL)
5356 return (1);
5357
5358 ret = zpool_reopen(zhp);
5359 zpool_close(zhp);
5360 return (ret);
5361 }
5362
5363 typedef struct scrub_cbdata {
5364 int cb_type;
5365 int cb_argc;
5366 char **cb_argv;
5367 } scrub_cbdata_t;
5368
5369 int
5370 scrub_callback(zpool_handle_t *zhp, void *data)
5371 {
5372 scrub_cbdata_t *cb = data;
5373 int err;
5374
5375 /*
5376 * Ignore faulted pools.
5377 */
5378 if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
5379 (void) fprintf(stderr, gettext("cannot scrub '%s': pool is "
5380 "currently unavailable\n"), zpool_get_name(zhp));
5381 return (1);
5382 }
5383
5384 err = zpool_scan(zhp, cb->cb_type);
5385
5386 return (err != 0);
5387 }
5388
5389 /*
5390 * zpool scrub [-s] <pool> ...
5391 *
5392 * -s Stop. Stops any in-progress scrub.
5393 */
5394 int
5395 zpool_do_scrub(int argc, char **argv)
5396 {
5397 int c;
5398 scrub_cbdata_t cb;
5399
5400 cb.cb_type = POOL_SCAN_SCRUB;
5401
5402 /* check options */
5403 while ((c = getopt(argc, argv, "s")) != -1) {
5404 switch (c) {
5405 case 's':
5406 cb.cb_type = POOL_SCAN_NONE;
5407 break;
5408 case '?':
5409 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5410 optopt);
5411 usage(B_FALSE);
5412 }
5413 }
5414
5415 cb.cb_argc = argc;
5416 cb.cb_argv = argv;
5417 argc -= optind;
5418 argv += optind;
5419
5420 if (argc < 1) {
5421 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5422 usage(B_FALSE);
5423 }
5424
5425 return (for_each_pool(argc, argv, B_TRUE, NULL, scrub_callback, &cb));
5426 }
5427
5428 /*
5429 * Print out detailed scrub status.
5430 */
5431 void
5432 print_scan_status(pool_scan_stat_t *ps)
5433 {
5434 time_t start, end;
5435 uint64_t elapsed, mins_left, hours_left;
5436 uint64_t pass_exam, examined, total;
5437 uint_t rate;
5438 double fraction_done;
5439 char processed_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
5440
5441 (void) printf(gettext(" scan: "));
5442
5443 /* If there's never been a scan, there's not much to say. */
5444 if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
5445 ps->pss_func >= POOL_SCAN_FUNCS) {
5446 (void) printf(gettext("none requested\n"));
5447 return;
5448 }
5449
5450 start = ps->pss_start_time;
5451 end = ps->pss_end_time;
5452 zfs_nicenum(ps->pss_processed, processed_buf, sizeof (processed_buf));
5453
5454 assert(ps->pss_func == POOL_SCAN_SCRUB ||
5455 ps->pss_func == POOL_SCAN_RESILVER);
5456 /*
5457 * Scan is finished or canceled.
5458 */
5459 if (ps->pss_state == DSS_FINISHED) {
5460 uint64_t minutes_taken = (end - start) / 60;
5461 char *fmt = NULL;
5462
5463 if (ps->pss_func == POOL_SCAN_SCRUB) {
5464 fmt = gettext("scrub repaired %s in %lluh%um with "
5465 "%llu errors on %s");
5466 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5467 fmt = gettext("resilvered %s in %lluh%um with "
5468 "%llu errors on %s");
5469 }
5470 /* LINTED */
5471 (void) printf(fmt, processed_buf,
5472 (u_longlong_t)(minutes_taken / 60),
5473 (uint_t)(minutes_taken % 60),
5474 (u_longlong_t)ps->pss_errors,
5475 ctime((time_t *)&end));
5476 return;
5477 } else if (ps->pss_state == DSS_CANCELED) {
5478 if (ps->pss_func == POOL_SCAN_SCRUB) {
5479 (void) printf(gettext("scrub canceled on %s"),
5480 ctime(&end));
5481 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5482 (void) printf(gettext("resilver canceled on %s"),
5483 ctime(&end));
5484 }
5485 return;
5486 }
5487
5488 assert(ps->pss_state == DSS_SCANNING);
5489
5490 /*
5491 * Scan is in progress.
5492 */
5493 if (ps->pss_func == POOL_SCAN_SCRUB) {
5494 (void) printf(gettext("scrub in progress since %s"),
5495 ctime(&start));
5496 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
5497 (void) printf(gettext("resilver in progress since %s"),
5498 ctime(&start));
5499 }
5500
5501 examined = ps->pss_examined ? ps->pss_examined : 1;
5502 total = ps->pss_to_examine;
5503 fraction_done = (double)examined / total;
5504
5505 /* elapsed time for this pass */
5506 elapsed = time(NULL) - ps->pss_pass_start;
5507 elapsed = elapsed ? elapsed : 1;
5508 pass_exam = ps->pss_pass_exam ? ps->pss_pass_exam : 1;
5509 rate = pass_exam / elapsed;
5510 rate = rate ? rate : 1;
5511 mins_left = ((total - examined) / rate) / 60;
5512 hours_left = mins_left / 60;
5513
5514 zfs_nicenum(examined, examined_buf, sizeof (examined_buf));
5515 zfs_nicenum(total, total_buf, sizeof (total_buf));
5516 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
5517
5518 /*
5519 * do not print estimated time if hours_left is more than 30 days
5520 */
5521 (void) printf(gettext("\t%s scanned out of %s at %s/s"),
5522 examined_buf, total_buf, rate_buf);
5523 if (hours_left < (30 * 24)) {
5524 (void) printf(gettext(", %lluh%um to go\n"),
5525 (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
5526 } else {
5527 (void) printf(gettext(
5528 ", (scan is slow, no estimated time)\n"));
5529 }
5530
5531 if (ps->pss_func == POOL_SCAN_RESILVER) {
5532 (void) printf(gettext("\t%s resilvered, %.2f%% done\n"),
5533 processed_buf, 100 * fraction_done);
5534 } else if (ps->pss_func == POOL_SCAN_SCRUB) {
5535 (void) printf(gettext("\t%s repaired, %.2f%% done\n"),
5536 processed_buf, 100 * fraction_done);
5537 }
5538 }
5539
5540 static void
5541 print_error_log(zpool_handle_t *zhp)
5542 {
5543 nvlist_t *nverrlist = NULL;
5544 nvpair_t *elem;
5545 char *pathname;
5546 size_t len = MAXPATHLEN * 2;
5547
5548 if (zpool_get_errlog(zhp, &nverrlist) != 0) {
5549 (void) printf("errors: List of errors unavailable "
5550 "(insufficient privileges)\n");
5551 return;
5552 }
5553
5554 (void) printf("errors: Permanent errors have been "
5555 "detected in the following files:\n\n");
5556
5557 pathname = safe_malloc(len);
5558 elem = NULL;
5559 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
5560 nvlist_t *nv;
5561 uint64_t dsobj, obj;
5562
5563 verify(nvpair_value_nvlist(elem, &nv) == 0);
5564 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
5565 &dsobj) == 0);
5566 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
5567 &obj) == 0);
5568 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
5569 (void) printf("%7s %s\n", "", pathname);
5570 }
5571 free(pathname);
5572 nvlist_free(nverrlist);
5573 }
5574
5575 static void
5576 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
5577 uint_t nspares)
5578 {
5579 uint_t i;
5580 char *name;
5581
5582 if (nspares == 0)
5583 return;
5584
5585 (void) printf(gettext("\tspares\n"));
5586
5587 for (i = 0; i < nspares; i++) {
5588 name = zpool_vdev_name(g_zfs, zhp, spares[i],
5589 cb->cb_name_flags);
5590 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE);
5591 free(name);
5592 }
5593 }
5594
5595 static void
5596 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
5597 uint_t nl2cache)
5598 {
5599 uint_t i;
5600 char *name;
5601
5602 if (nl2cache == 0)
5603 return;
5604
5605 (void) printf(gettext("\tcache\n"));
5606
5607 for (i = 0; i < nl2cache; i++) {
5608 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
5609 cb->cb_name_flags);
5610 print_status_config(zhp, cb, name, l2cache[i], 2, B_FALSE);
5611 free(name);
5612 }
5613 }
5614
5615 static void
5616 print_dedup_stats(nvlist_t *config)
5617 {
5618 ddt_histogram_t *ddh;
5619 ddt_stat_t *dds;
5620 ddt_object_t *ddo;
5621 uint_t c;
5622
5623 /*
5624 * If the pool was faulted then we may not have been able to
5625 * obtain the config. Otherwise, if we have anything in the dedup
5626 * table continue processing the stats.
5627 */
5628 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
5629 (uint64_t **)&ddo, &c) != 0)
5630 return;
5631
5632 (void) printf("\n");
5633 (void) printf(gettext(" dedup: "));
5634 if (ddo->ddo_count == 0) {
5635 (void) printf(gettext("no DDT entries\n"));
5636 return;
5637 }
5638
5639 (void) printf("DDT entries %llu, size %llu on disk, %llu in core\n",
5640 (u_longlong_t)ddo->ddo_count,
5641 (u_longlong_t)ddo->ddo_dspace,
5642 (u_longlong_t)ddo->ddo_mspace);
5643
5644 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
5645 (uint64_t **)&dds, &c) == 0);
5646 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
5647 (uint64_t **)&ddh, &c) == 0);
5648 zpool_dump_ddt(dds, ddh);
5649 }
5650
5651 /*
5652 * Display a summary of pool status. Displays a summary such as:
5653 *
5654 * pool: tank
5655 * status: DEGRADED
5656 * reason: One or more devices ...
5657 * see: http://zfsonlinux.org/msg/ZFS-xxxx-01
5658 * config:
5659 * mirror DEGRADED
5660 * c1t0d0 OK
5661 * c2t0d0 UNAVAIL
5662 *
5663 * When given the '-v' option, we print out the complete config. If the '-e'
5664 * option is specified, then we print out error rate information as well.
5665 */
5666 int
5667 status_callback(zpool_handle_t *zhp, void *data)
5668 {
5669 status_cbdata_t *cbp = data;
5670 nvlist_t *config, *nvroot;
5671 char *msgid;
5672 zpool_status_t reason;
5673 zpool_errata_t errata;
5674 const char *health;
5675 uint_t c;
5676 vdev_stat_t *vs;
5677
5678 config = zpool_get_config(zhp, NULL);
5679 reason = zpool_get_status(zhp, &msgid, &errata);
5680
5681 cbp->cb_count++;
5682
5683 /*
5684 * If we were given 'zpool status -x', only report those pools with
5685 * problems.
5686 */
5687 if (cbp->cb_explain &&
5688 (reason == ZPOOL_STATUS_OK ||
5689 reason == ZPOOL_STATUS_VERSION_OLDER ||
5690 reason == ZPOOL_STATUS_FEAT_DISABLED)) {
5691 if (!cbp->cb_allpools) {
5692 (void) printf(gettext("pool '%s' is healthy\n"),
5693 zpool_get_name(zhp));
5694 if (cbp->cb_first)
5695 cbp->cb_first = B_FALSE;
5696 }
5697 return (0);
5698 }
5699
5700 if (cbp->cb_first)
5701 cbp->cb_first = B_FALSE;
5702 else
5703 (void) printf("\n");
5704
5705 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5706 &nvroot) == 0);
5707 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
5708 (uint64_t **)&vs, &c) == 0);
5709 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
5710
5711 (void) printf(gettext(" pool: %s\n"), zpool_get_name(zhp));
5712 (void) printf(gettext(" state: %s\n"), health);
5713
5714 switch (reason) {
5715 case ZPOOL_STATUS_MISSING_DEV_R:
5716 (void) printf(gettext("status: One or more devices could not "
5717 "be opened. Sufficient replicas exist for\n\tthe pool to "
5718 "continue functioning in a degraded state.\n"));
5719 (void) printf(gettext("action: Attach the missing device and "
5720 "online it using 'zpool online'.\n"));
5721 break;
5722
5723 case ZPOOL_STATUS_MISSING_DEV_NR:
5724 (void) printf(gettext("status: One or more devices could not "
5725 "be opened. There are insufficient\n\treplicas for the "
5726 "pool to continue functioning.\n"));
5727 (void) printf(gettext("action: Attach the missing device and "
5728 "online it using 'zpool online'.\n"));
5729 break;
5730
5731 case ZPOOL_STATUS_CORRUPT_LABEL_R:
5732 (void) printf(gettext("status: One or more devices could not "
5733 "be used because the label is missing or\n\tinvalid. "
5734 "Sufficient replicas exist for the pool to continue\n\t"
5735 "functioning in a degraded state.\n"));
5736 (void) printf(gettext("action: Replace the device using "
5737 "'zpool replace'.\n"));
5738 break;
5739
5740 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
5741 (void) printf(gettext("status: One or more devices could not "
5742 "be used because the label is missing \n\tor invalid. "
5743 "There are insufficient replicas for the pool to "
5744 "continue\n\tfunctioning.\n"));
5745 zpool_explain_recover(zpool_get_handle(zhp),
5746 zpool_get_name(zhp), reason, config);
5747 break;
5748
5749 case ZPOOL_STATUS_FAILING_DEV:
5750 (void) printf(gettext("status: One or more devices has "
5751 "experienced an unrecoverable error. An\n\tattempt was "
5752 "made to correct the error. Applications are "
5753 "unaffected.\n"));
5754 (void) printf(gettext("action: Determine if the device needs "
5755 "to be replaced, and clear the errors\n\tusing "
5756 "'zpool clear' or replace the device with 'zpool "
5757 "replace'.\n"));
5758 break;
5759
5760 case ZPOOL_STATUS_OFFLINE_DEV:
5761 (void) printf(gettext("status: One or more devices has "
5762 "been taken offline by the administrator.\n\tSufficient "
5763 "replicas exist for the pool to continue functioning in "
5764 "a\n\tdegraded state.\n"));
5765 (void) printf(gettext("action: Online the device using "
5766 "'zpool online' or replace the device with\n\t'zpool "
5767 "replace'.\n"));
5768 break;
5769
5770 case ZPOOL_STATUS_REMOVED_DEV:
5771 (void) printf(gettext("status: One or more devices has "
5772 "been removed by the administrator.\n\tSufficient "
5773 "replicas exist for the pool to continue functioning in "
5774 "a\n\tdegraded state.\n"));
5775 (void) printf(gettext("action: Online the device using "
5776 "'zpool online' or replace the device with\n\t'zpool "
5777 "replace'.\n"));
5778 break;
5779
5780 case ZPOOL_STATUS_RESILVERING:
5781 (void) printf(gettext("status: One or more devices is "
5782 "currently being resilvered. The pool will\n\tcontinue "
5783 "to function, possibly in a degraded state.\n"));
5784 (void) printf(gettext("action: Wait for the resilver to "
5785 "complete.\n"));
5786 break;
5787
5788 case ZPOOL_STATUS_CORRUPT_DATA:
5789 (void) printf(gettext("status: One or more devices has "
5790 "experienced an error resulting in data\n\tcorruption. "
5791 "Applications may be affected.\n"));
5792 (void) printf(gettext("action: Restore the file in question "
5793 "if possible. Otherwise restore the\n\tentire pool from "
5794 "backup.\n"));
5795 break;
5796
5797 case ZPOOL_STATUS_CORRUPT_POOL:
5798 (void) printf(gettext("status: The pool metadata is corrupted "
5799 "and the pool cannot be opened.\n"));
5800 zpool_explain_recover(zpool_get_handle(zhp),
5801 zpool_get_name(zhp), reason, config);
5802 break;
5803
5804 case ZPOOL_STATUS_VERSION_OLDER:
5805 (void) printf(gettext("status: The pool is formatted using a "
5806 "legacy on-disk format. The pool can\n\tstill be used, "
5807 "but some features are unavailable.\n"));
5808 (void) printf(gettext("action: Upgrade the pool using 'zpool "
5809 "upgrade'. Once this is done, the\n\tpool will no longer "
5810 "be accessible on software that does not support\n\t"
5811 "feature flags.\n"));
5812 break;
5813
5814 case ZPOOL_STATUS_VERSION_NEWER:
5815 (void) printf(gettext("status: The pool has been upgraded to a "
5816 "newer, incompatible on-disk version.\n\tThe pool cannot "
5817 "be accessed on this system.\n"));
5818 (void) printf(gettext("action: Access the pool from a system "
5819 "running more recent software, or\n\trestore the pool from "
5820 "backup.\n"));
5821 break;
5822
5823 case ZPOOL_STATUS_FEAT_DISABLED:
5824 (void) printf(gettext("status: Some supported features are not "
5825 "enabled on the pool. The pool can\n\tstill be used, but "
5826 "some features are unavailable.\n"));
5827 (void) printf(gettext("action: Enable all features using "
5828 "'zpool upgrade'. Once this is done,\n\tthe pool may no "
5829 "longer be accessible by software that does not support\n\t"
5830 "the features. See zpool-features(5) for details.\n"));
5831 break;
5832
5833 case ZPOOL_STATUS_UNSUP_FEAT_READ:
5834 (void) printf(gettext("status: The pool cannot be accessed on "
5835 "this system because it uses the\n\tfollowing feature(s) "
5836 "not supported on this system:\n"));
5837 zpool_print_unsup_feat(config);
5838 (void) printf("\n");
5839 (void) printf(gettext("action: Access the pool from a system "
5840 "that supports the required feature(s),\n\tor restore the "
5841 "pool from backup.\n"));
5842 break;
5843
5844 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
5845 (void) printf(gettext("status: The pool can only be accessed "
5846 "in read-only mode on this system. It\n\tcannot be "
5847 "accessed in read-write mode because it uses the "
5848 "following\n\tfeature(s) not supported on this system:\n"));
5849 zpool_print_unsup_feat(config);
5850 (void) printf("\n");
5851 (void) printf(gettext("action: The pool cannot be accessed in "
5852 "read-write mode. Import the pool with\n"
5853 "\t\"-o readonly=on\", access the pool from a system that "
5854 "supports the\n\trequired feature(s), or restore the "
5855 "pool from backup.\n"));
5856 break;
5857
5858 case ZPOOL_STATUS_FAULTED_DEV_R:
5859 (void) printf(gettext("status: One or more devices are "
5860 "faulted in response to persistent errors.\n\tSufficient "
5861 "replicas exist for the pool to continue functioning "
5862 "in a\n\tdegraded state.\n"));
5863 (void) printf(gettext("action: Replace the faulted device, "
5864 "or use 'zpool clear' to mark the device\n\trepaired.\n"));
5865 break;
5866
5867 case ZPOOL_STATUS_FAULTED_DEV_NR:
5868 (void) printf(gettext("status: One or more devices are "
5869 "faulted in response to persistent errors. There are "
5870 "insufficient replicas for the pool to\n\tcontinue "
5871 "functioning.\n"));
5872 (void) printf(gettext("action: Destroy and re-create the pool "
5873 "from a backup source. Manually marking the device\n"
5874 "\trepaired using 'zpool clear' may allow some data "
5875 "to be recovered.\n"));
5876 break;
5877
5878 case ZPOOL_STATUS_IO_FAILURE_WAIT:
5879 case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
5880 (void) printf(gettext("status: One or more devices are "
5881 "faulted in response to IO failures.\n"));
5882 (void) printf(gettext("action: Make sure the affected devices "
5883 "are connected, then run 'zpool clear'.\n"));
5884 break;
5885
5886 case ZPOOL_STATUS_BAD_LOG:
5887 (void) printf(gettext("status: An intent log record "
5888 "could not be read.\n"
5889 "\tWaiting for administrator intervention to fix the "
5890 "faulted pool.\n"));
5891 (void) printf(gettext("action: Either restore the affected "
5892 "device(s) and run 'zpool online',\n"
5893 "\tor ignore the intent log records by running "
5894 "'zpool clear'.\n"));
5895 break;
5896
5897 case ZPOOL_STATUS_HOSTID_MISMATCH:
5898 (void) printf(gettext("status: Mismatch between pool hostid "
5899 "and system hostid on imported pool.\n\tThis pool was "
5900 "previously imported into a system with a different "
5901 "hostid,\n\tand then was verbatim imported into this "
5902 "system.\n"));
5903 (void) printf(gettext("action: Export this pool on all systems "
5904 "on which it is imported.\n"
5905 "\tThen import it to correct the mismatch.\n"));
5906 break;
5907
5908 case ZPOOL_STATUS_ERRATA:
5909 (void) printf(gettext("status: Errata #%d detected.\n"),
5910 errata);
5911
5912 switch (errata) {
5913 case ZPOOL_ERRATA_NONE:
5914 break;
5915
5916 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
5917 (void) printf(gettext("action: To correct the issue "
5918 "run 'zpool scrub'.\n"));
5919 break;
5920
5921 default:
5922 /*
5923 * All errata which allow the pool to be imported
5924 * must contain an action message.
5925 */
5926 assert(0);
5927 }
5928 break;
5929
5930 default:
5931 /*
5932 * The remaining errors can't actually be generated, yet.
5933 */
5934 assert(reason == ZPOOL_STATUS_OK);
5935 }
5936
5937 if (msgid != NULL)
5938 (void) printf(gettext(" see: http://zfsonlinux.org/msg/%s\n"),
5939 msgid);
5940
5941 if (config != NULL) {
5942 uint64_t nerr;
5943 nvlist_t **spares, **l2cache;
5944 uint_t nspares, nl2cache;
5945 pool_scan_stat_t *ps = NULL;
5946
5947 (void) nvlist_lookup_uint64_array(nvroot,
5948 ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &c);
5949 print_scan_status(ps);
5950
5951 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
5952 cbp->cb_name_flags);
5953 if (cbp->cb_namewidth < 10)
5954 cbp->cb_namewidth = 10;
5955
5956 (void) printf(gettext("config:\n\n"));
5957 (void) printf(gettext("\t%-*s %-8s %5s %5s %5s\n"),
5958 cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
5959 "CKSUM");
5960 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
5961 B_FALSE);
5962
5963 if (num_logs(nvroot) > 0)
5964 print_logs(zhp, cbp, nvroot);
5965 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5966 &l2cache, &nl2cache) == 0)
5967 print_l2cache(zhp, cbp, l2cache, nl2cache);
5968
5969 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5970 &spares, &nspares) == 0)
5971 print_spares(zhp, cbp, spares, nspares);
5972
5973 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
5974 &nerr) == 0) {
5975 nvlist_t *nverrlist = NULL;
5976
5977 /*
5978 * If the approximate error count is small, get a
5979 * precise count by fetching the entire log and
5980 * uniquifying the results.
5981 */
5982 if (nerr > 0 && nerr < 100 && !cbp->cb_verbose &&
5983 zpool_get_errlog(zhp, &nverrlist) == 0) {
5984 nvpair_t *elem;
5985
5986 elem = NULL;
5987 nerr = 0;
5988 while ((elem = nvlist_next_nvpair(nverrlist,
5989 elem)) != NULL) {
5990 nerr++;
5991 }
5992 }
5993 nvlist_free(nverrlist);
5994
5995 (void) printf("\n");
5996
5997 if (nerr == 0)
5998 (void) printf(gettext("errors: No known data "
5999 "errors\n"));
6000 else if (!cbp->cb_verbose)
6001 (void) printf(gettext("errors: %llu data "
6002 "errors, use '-v' for a list\n"),
6003 (u_longlong_t)nerr);
6004 else
6005 print_error_log(zhp);
6006 }
6007
6008 if (cbp->cb_dedup_stats)
6009 print_dedup_stats(config);
6010 } else {
6011 (void) printf(gettext("config: The configuration cannot be "
6012 "determined.\n"));
6013 }
6014
6015 return (0);
6016 }
6017
6018 /*
6019 * zpool status [-gLPvx] [-T d|u] [pool] ... [interval [count]]
6020 *
6021 * -g Display guid for individual vdev name.
6022 * -L Follow links when resolving vdev path name.
6023 * -P Display full path for vdev name.
6024 * -v Display complete error logs
6025 * -x Display only pools with potential problems
6026 * -D Display dedup status (undocumented)
6027 * -T Display a timestamp in date(1) or Unix format
6028 *
6029 * Describes the health status of all pools or some subset.
6030 */
6031 int
6032 zpool_do_status(int argc, char **argv)
6033 {
6034 int c;
6035 int ret;
6036 float interval = 0;
6037 unsigned long count = 0;
6038 status_cbdata_t cb = { 0 };
6039
6040 /* check options */
6041 while ((c = getopt(argc, argv, "gLPvxDT:")) != -1) {
6042 switch (c) {
6043 case 'g':
6044 cb.cb_name_flags |= VDEV_NAME_GUID;
6045 break;
6046 case 'L':
6047 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6048 break;
6049 case 'P':
6050 cb.cb_name_flags |= VDEV_NAME_PATH;
6051 break;
6052 case 'v':
6053 cb.cb_verbose = B_TRUE;
6054 break;
6055 case 'x':
6056 cb.cb_explain = B_TRUE;
6057 break;
6058 case 'D':
6059 cb.cb_dedup_stats = B_TRUE;
6060 break;
6061 case 'T':
6062 get_timestamp_arg(*optarg);
6063 break;
6064 case '?':
6065 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6066 optopt);
6067 usage(B_FALSE);
6068 }
6069 }
6070
6071 argc -= optind;
6072 argv += optind;
6073
6074 get_interval_count(&argc, argv, &interval, &count);
6075
6076 if (argc == 0)
6077 cb.cb_allpools = B_TRUE;
6078
6079 cb.cb_first = B_TRUE;
6080 cb.cb_print_status = B_TRUE;
6081
6082 for (;;) {
6083 if (timestamp_fmt != NODATE)
6084 print_timestamp(timestamp_fmt);
6085
6086 ret = for_each_pool(argc, argv, B_TRUE, NULL,
6087 status_callback, &cb);
6088
6089 if (argc == 0 && cb.cb_count == 0)
6090 (void) fprintf(stderr, gettext("no pools available\n"));
6091 else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
6092 (void) printf(gettext("all pools are healthy\n"));
6093
6094 if (ret != 0)
6095 return (ret);
6096
6097 if (interval == 0)
6098 break;
6099
6100 if (count != 0 && --count == 0)
6101 break;
6102
6103 (void) fsleep(interval);
6104 }
6105
6106 return (0);
6107 }
6108
6109 typedef struct upgrade_cbdata {
6110 int cb_first;
6111 int cb_argc;
6112 uint64_t cb_version;
6113 char **cb_argv;
6114 } upgrade_cbdata_t;
6115
6116 static int
6117 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
6118 {
6119 int zfs_version = (int) zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
6120 int *count = (int *)unsupp_fs;
6121
6122 if (zfs_version > ZPL_VERSION) {
6123 (void) printf(gettext("%s (v%d) is not supported by this "
6124 "implementation of ZFS.\n"),
6125 zfs_get_name(zhp), zfs_version);
6126 (*count)++;
6127 }
6128
6129 zfs_iter_filesystems(zhp, check_unsupp_fs, unsupp_fs);
6130
6131 zfs_close(zhp);
6132
6133 return (0);
6134 }
6135
6136 static int
6137 upgrade_version(zpool_handle_t *zhp, uint64_t version)
6138 {
6139 int ret;
6140 nvlist_t *config;
6141 uint64_t oldversion;
6142 int unsupp_fs = 0;
6143
6144 config = zpool_get_config(zhp, NULL);
6145 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6146 &oldversion) == 0);
6147
6148 assert(SPA_VERSION_IS_SUPPORTED(oldversion));
6149 assert(oldversion < version);
6150
6151 ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
6152 if (ret != 0)
6153 return (ret);
6154
6155 if (unsupp_fs) {
6156 (void) fprintf(stderr, gettext("Upgrade not performed due "
6157 "to %d unsupported filesystems (max v%d).\n"),
6158 unsupp_fs, (int) ZPL_VERSION);
6159 return (1);
6160 }
6161
6162 ret = zpool_upgrade(zhp, version);
6163 if (ret != 0)
6164 return (ret);
6165
6166 if (version >= SPA_VERSION_FEATURES) {
6167 (void) printf(gettext("Successfully upgraded "
6168 "'%s' from version %llu to feature flags.\n"),
6169 zpool_get_name(zhp), (u_longlong_t) oldversion);
6170 } else {
6171 (void) printf(gettext("Successfully upgraded "
6172 "'%s' from version %llu to version %llu.\n"),
6173 zpool_get_name(zhp), (u_longlong_t) oldversion,
6174 (u_longlong_t) version);
6175 }
6176
6177 return (0);
6178 }
6179
6180 static int
6181 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
6182 {
6183 int i, ret, count;
6184 boolean_t firstff = B_TRUE;
6185 nvlist_t *enabled = zpool_get_features(zhp);
6186
6187 count = 0;
6188 for (i = 0; i < SPA_FEATURES; i++) {
6189 const char *fname = spa_feature_table[i].fi_uname;
6190 const char *fguid = spa_feature_table[i].fi_guid;
6191 if (!nvlist_exists(enabled, fguid)) {
6192 char *propname;
6193 verify(-1 != asprintf(&propname, "feature@%s", fname));
6194 ret = zpool_set_prop(zhp, propname,
6195 ZFS_FEATURE_ENABLED);
6196 if (ret != 0) {
6197 free(propname);
6198 return (ret);
6199 }
6200 count++;
6201
6202 if (firstff) {
6203 (void) printf(gettext("Enabled the "
6204 "following features on '%s':\n"),
6205 zpool_get_name(zhp));
6206 firstff = B_FALSE;
6207 }
6208 (void) printf(gettext(" %s\n"), fname);
6209 free(propname);
6210 }
6211 }
6212
6213 if (countp != NULL)
6214 *countp = count;
6215 return (0);
6216 }
6217
6218 static int
6219 upgrade_cb(zpool_handle_t *zhp, void *arg)
6220 {
6221 upgrade_cbdata_t *cbp = arg;
6222 nvlist_t *config;
6223 uint64_t version;
6224 boolean_t printnl = B_FALSE;
6225 int ret;
6226
6227 config = zpool_get_config(zhp, NULL);
6228 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6229 &version) == 0);
6230
6231 assert(SPA_VERSION_IS_SUPPORTED(version));
6232
6233 if (version < cbp->cb_version) {
6234 cbp->cb_first = B_FALSE;
6235 ret = upgrade_version(zhp, cbp->cb_version);
6236 if (ret != 0)
6237 return (ret);
6238 printnl = B_TRUE;
6239
6240 /*
6241 * If they did "zpool upgrade -a", then we could
6242 * be doing ioctls to different pools. We need
6243 * to log this history once to each pool, and bypass
6244 * the normal history logging that happens in main().
6245 */
6246 (void) zpool_log_history(g_zfs, history_str);
6247 log_history = B_FALSE;
6248 }
6249
6250 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
6251 int count;
6252 ret = upgrade_enable_all(zhp, &count);
6253 if (ret != 0)
6254 return (ret);
6255
6256 if (count > 0) {
6257 cbp->cb_first = B_FALSE;
6258 printnl = B_TRUE;
6259 }
6260 }
6261
6262 if (printnl) {
6263 (void) printf(gettext("\n"));
6264 }
6265
6266 return (0);
6267 }
6268
6269 static int
6270 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
6271 {
6272 upgrade_cbdata_t *cbp = arg;
6273 nvlist_t *config;
6274 uint64_t version;
6275
6276 config = zpool_get_config(zhp, NULL);
6277 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6278 &version) == 0);
6279
6280 assert(SPA_VERSION_IS_SUPPORTED(version));
6281
6282 if (version < SPA_VERSION_FEATURES) {
6283 if (cbp->cb_first) {
6284 (void) printf(gettext("The following pools are "
6285 "formatted with legacy version numbers and can\n"
6286 "be upgraded to use feature flags. After "
6287 "being upgraded, these pools\nwill no "
6288 "longer be accessible by software that does not "
6289 "support feature\nflags.\n\n"));
6290 (void) printf(gettext("VER POOL\n"));
6291 (void) printf(gettext("--- ------------\n"));
6292 cbp->cb_first = B_FALSE;
6293 }
6294
6295 (void) printf("%2llu %s\n", (u_longlong_t)version,
6296 zpool_get_name(zhp));
6297 }
6298
6299 return (0);
6300 }
6301
6302 static int
6303 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
6304 {
6305 upgrade_cbdata_t *cbp = arg;
6306 nvlist_t *config;
6307 uint64_t version;
6308
6309 config = zpool_get_config(zhp, NULL);
6310 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6311 &version) == 0);
6312
6313 if (version >= SPA_VERSION_FEATURES) {
6314 int i;
6315 boolean_t poolfirst = B_TRUE;
6316 nvlist_t *enabled = zpool_get_features(zhp);
6317
6318 for (i = 0; i < SPA_FEATURES; i++) {
6319 const char *fguid = spa_feature_table[i].fi_guid;
6320 const char *fname = spa_feature_table[i].fi_uname;
6321 if (!nvlist_exists(enabled, fguid)) {
6322 if (cbp->cb_first) {
6323 (void) printf(gettext("\nSome "
6324 "supported features are not "
6325 "enabled on the following pools. "
6326 "Once a\nfeature is enabled the "
6327 "pool may become incompatible with "
6328 "software\nthat does not support "
6329 "the feature. See "
6330 "zpool-features(5) for "
6331 "details.\n\n"));
6332 (void) printf(gettext("POOL "
6333 "FEATURE\n"));
6334 (void) printf(gettext("------"
6335 "---------\n"));
6336 cbp->cb_first = B_FALSE;
6337 }
6338
6339 if (poolfirst) {
6340 (void) printf(gettext("%s\n"),
6341 zpool_get_name(zhp));
6342 poolfirst = B_FALSE;
6343 }
6344
6345 (void) printf(gettext(" %s\n"), fname);
6346 }
6347 /*
6348 * If they did "zpool upgrade -a", then we could
6349 * be doing ioctls to different pools. We need
6350 * to log this history once to each pool, and bypass
6351 * the normal history logging that happens in main().
6352 */
6353 (void) zpool_log_history(g_zfs, history_str);
6354 log_history = B_FALSE;
6355 }
6356 }
6357
6358 return (0);
6359 }
6360
6361 /* ARGSUSED */
6362 static int
6363 upgrade_one(zpool_handle_t *zhp, void *data)
6364 {
6365 boolean_t printnl = B_FALSE;
6366 upgrade_cbdata_t *cbp = data;
6367 uint64_t cur_version;
6368 int ret;
6369
6370 if (strcmp("log", zpool_get_name(zhp)) == 0) {
6371 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
6372 "Pool 'log' must be renamed using export and import"
6373 " to upgrade.\n"));
6374 return (1);
6375 }
6376
6377 cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
6378 if (cur_version > cbp->cb_version) {
6379 (void) printf(gettext("Pool '%s' is already formatted "
6380 "using more current version '%llu'.\n\n"),
6381 zpool_get_name(zhp), (u_longlong_t) cur_version);
6382 return (0);
6383 }
6384
6385 if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
6386 (void) printf(gettext("Pool '%s' is already formatted "
6387 "using version %llu.\n\n"), zpool_get_name(zhp),
6388 (u_longlong_t) cbp->cb_version);
6389 return (0);
6390 }
6391
6392 if (cur_version != cbp->cb_version) {
6393 printnl = B_TRUE;
6394 ret = upgrade_version(zhp, cbp->cb_version);
6395 if (ret != 0)
6396 return (ret);
6397 }
6398
6399 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
6400 int count = 0;
6401 ret = upgrade_enable_all(zhp, &count);
6402 if (ret != 0)
6403 return (ret);
6404
6405 if (count != 0) {
6406 printnl = B_TRUE;
6407 } else if (cur_version == SPA_VERSION) {
6408 (void) printf(gettext("Pool '%s' already has all "
6409 "supported features enabled.\n"),
6410 zpool_get_name(zhp));
6411 }
6412 }
6413
6414 if (printnl) {
6415 (void) printf(gettext("\n"));
6416 }
6417
6418 return (0);
6419 }
6420
6421 /*
6422 * zpool upgrade
6423 * zpool upgrade -v
6424 * zpool upgrade [-V version] <-a | pool ...>
6425 *
6426 * With no arguments, display downrev'd ZFS pool available for upgrade.
6427 * Individual pools can be upgraded by specifying the pool, and '-a' will
6428 * upgrade all pools.
6429 */
6430 int
6431 zpool_do_upgrade(int argc, char **argv)
6432 {
6433 int c;
6434 upgrade_cbdata_t cb = { 0 };
6435 int ret = 0;
6436 boolean_t showversions = B_FALSE;
6437 boolean_t upgradeall = B_FALSE;
6438 char *end;
6439
6440
6441 /* check options */
6442 while ((c = getopt(argc, argv, ":avV:")) != -1) {
6443 switch (c) {
6444 case 'a':
6445 upgradeall = B_TRUE;
6446 break;
6447 case 'v':
6448 showversions = B_TRUE;
6449 break;
6450 case 'V':
6451 cb.cb_version = strtoll(optarg, &end, 10);
6452 if (*end != '\0' ||
6453 !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
6454 (void) fprintf(stderr,
6455 gettext("invalid version '%s'\n"), optarg);
6456 usage(B_FALSE);
6457 }
6458 break;
6459 case ':':
6460 (void) fprintf(stderr, gettext("missing argument for "
6461 "'%c' option\n"), optopt);
6462 usage(B_FALSE);
6463 break;
6464 case '?':
6465 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6466 optopt);
6467 usage(B_FALSE);
6468 }
6469 }
6470
6471 cb.cb_argc = argc;
6472 cb.cb_argv = argv;
6473 argc -= optind;
6474 argv += optind;
6475
6476 if (cb.cb_version == 0) {
6477 cb.cb_version = SPA_VERSION;
6478 } else if (!upgradeall && argc == 0) {
6479 (void) fprintf(stderr, gettext("-V option is "
6480 "incompatible with other arguments\n"));
6481 usage(B_FALSE);
6482 }
6483
6484 if (showversions) {
6485 if (upgradeall || argc != 0) {
6486 (void) fprintf(stderr, gettext("-v option is "
6487 "incompatible with other arguments\n"));
6488 usage(B_FALSE);
6489 }
6490 } else if (upgradeall) {
6491 if (argc != 0) {
6492 (void) fprintf(stderr, gettext("-a option should not "
6493 "be used along with a pool name\n"));
6494 usage(B_FALSE);
6495 }
6496 }
6497
6498 (void) printf(gettext("This system supports ZFS pool feature "
6499 "flags.\n\n"));
6500 if (showversions) {
6501 int i;
6502
6503 (void) printf(gettext("The following features are "
6504 "supported:\n\n"));
6505 (void) printf(gettext("FEAT DESCRIPTION\n"));
6506 (void) printf("----------------------------------------------"
6507 "---------------\n");
6508 for (i = 0; i < SPA_FEATURES; i++) {
6509 zfeature_info_t *fi = &spa_feature_table[i];
6510 const char *ro =
6511 (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
6512 " (read-only compatible)" : "";
6513
6514 (void) printf("%-37s%s\n", fi->fi_uname, ro);
6515 (void) printf(" %s\n", fi->fi_desc);
6516 }
6517 (void) printf("\n");
6518
6519 (void) printf(gettext("The following legacy versions are also "
6520 "supported:\n\n"));
6521 (void) printf(gettext("VER DESCRIPTION\n"));
6522 (void) printf("--- -----------------------------------------"
6523 "---------------\n");
6524 (void) printf(gettext(" 1 Initial ZFS version\n"));
6525 (void) printf(gettext(" 2 Ditto blocks "
6526 "(replicated metadata)\n"));
6527 (void) printf(gettext(" 3 Hot spares and double parity "
6528 "RAID-Z\n"));
6529 (void) printf(gettext(" 4 zpool history\n"));
6530 (void) printf(gettext(" 5 Compression using the gzip "
6531 "algorithm\n"));
6532 (void) printf(gettext(" 6 bootfs pool property\n"));
6533 (void) printf(gettext(" 7 Separate intent log devices\n"));
6534 (void) printf(gettext(" 8 Delegated administration\n"));
6535 (void) printf(gettext(" 9 refquota and refreservation "
6536 "properties\n"));
6537 (void) printf(gettext(" 10 Cache devices\n"));
6538 (void) printf(gettext(" 11 Improved scrub performance\n"));
6539 (void) printf(gettext(" 12 Snapshot properties\n"));
6540 (void) printf(gettext(" 13 snapused property\n"));
6541 (void) printf(gettext(" 14 passthrough-x aclinherit\n"));
6542 (void) printf(gettext(" 15 user/group space accounting\n"));
6543 (void) printf(gettext(" 16 stmf property support\n"));
6544 (void) printf(gettext(" 17 Triple-parity RAID-Z\n"));
6545 (void) printf(gettext(" 18 Snapshot user holds\n"));
6546 (void) printf(gettext(" 19 Log device removal\n"));
6547 (void) printf(gettext(" 20 Compression using zle "
6548 "(zero-length encoding)\n"));
6549 (void) printf(gettext(" 21 Deduplication\n"));
6550 (void) printf(gettext(" 22 Received properties\n"));
6551 (void) printf(gettext(" 23 Slim ZIL\n"));
6552 (void) printf(gettext(" 24 System attributes\n"));
6553 (void) printf(gettext(" 25 Improved scrub stats\n"));
6554 (void) printf(gettext(" 26 Improved snapshot deletion "
6555 "performance\n"));
6556 (void) printf(gettext(" 27 Improved snapshot creation "
6557 "performance\n"));
6558 (void) printf(gettext(" 28 Multiple vdev replacements\n"));
6559 (void) printf(gettext("\nFor more information on a particular "
6560 "version, including supported releases,\n"));
6561 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
6562 } else if (argc == 0 && upgradeall) {
6563 cb.cb_first = B_TRUE;
6564 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
6565 if (ret == 0 && cb.cb_first) {
6566 if (cb.cb_version == SPA_VERSION) {
6567 (void) printf(gettext("All pools are already "
6568 "formatted using feature flags.\n\n"));
6569 (void) printf(gettext("Every feature flags "
6570 "pool already has all supported features "
6571 "enabled.\n"));
6572 } else {
6573 (void) printf(gettext("All pools are already "
6574 "formatted with version %llu or higher.\n"),
6575 (u_longlong_t) cb.cb_version);
6576 }
6577 }
6578 } else if (argc == 0) {
6579 cb.cb_first = B_TRUE;
6580 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
6581 assert(ret == 0);
6582
6583 if (cb.cb_first) {
6584 (void) printf(gettext("All pools are formatted "
6585 "using feature flags.\n\n"));
6586 } else {
6587 (void) printf(gettext("\nUse 'zpool upgrade -v' "
6588 "for a list of available legacy versions.\n"));
6589 }
6590
6591 cb.cb_first = B_TRUE;
6592 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
6593 assert(ret == 0);
6594
6595 if (cb.cb_first) {
6596 (void) printf(gettext("Every feature flags pool has "
6597 "all supported features enabled.\n"));
6598 } else {
6599 (void) printf(gettext("\n"));
6600 }
6601 } else {
6602 ret = for_each_pool(argc, argv, B_FALSE, NULL,
6603 upgrade_one, &cb);
6604 }
6605
6606 return (ret);
6607 }
6608
6609 typedef struct hist_cbdata {
6610 boolean_t first;
6611 boolean_t longfmt;
6612 boolean_t internal;
6613 } hist_cbdata_t;
6614
6615 /*
6616 * Print out the command history for a specific pool.
6617 */
6618 static int
6619 get_history_one(zpool_handle_t *zhp, void *data)
6620 {
6621 nvlist_t *nvhis;
6622 nvlist_t **records;
6623 uint_t numrecords;
6624 int ret, i;
6625 hist_cbdata_t *cb = (hist_cbdata_t *)data;
6626
6627 cb->first = B_FALSE;
6628
6629 (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
6630
6631 if ((ret = zpool_get_history(zhp, &nvhis)) != 0)
6632 return (ret);
6633
6634 verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
6635 &records, &numrecords) == 0);
6636 for (i = 0; i < numrecords; i++) {
6637 nvlist_t *rec = records[i];
6638 char tbuf[30] = "";
6639
6640 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
6641 time_t tsec;
6642 struct tm t;
6643
6644 tsec = fnvlist_lookup_uint64(records[i],
6645 ZPOOL_HIST_TIME);
6646 (void) localtime_r(&tsec, &t);
6647 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
6648 }
6649
6650 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
6651 (void) printf("%s %s", tbuf,
6652 fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
6653 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
6654 int ievent =
6655 fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
6656 if (!cb->internal)
6657 continue;
6658 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
6659 (void) printf("%s unrecognized record:\n",
6660 tbuf);
6661 dump_nvlist(rec, 4);
6662 continue;
6663 }
6664 (void) printf("%s [internal %s txg:%lld] %s", tbuf,
6665 zfs_history_event_names[ievent],
6666 (longlong_t) fnvlist_lookup_uint64(
6667 rec, ZPOOL_HIST_TXG),
6668 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
6669 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
6670 if (!cb->internal)
6671 continue;
6672 (void) printf("%s [txg:%lld] %s", tbuf,
6673 (longlong_t) fnvlist_lookup_uint64(
6674 rec, ZPOOL_HIST_TXG),
6675 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
6676 if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
6677 (void) printf(" %s (%llu)",
6678 fnvlist_lookup_string(rec,
6679 ZPOOL_HIST_DSNAME),
6680 (u_longlong_t)fnvlist_lookup_uint64(rec,
6681 ZPOOL_HIST_DSID));
6682 }
6683 (void) printf(" %s", fnvlist_lookup_string(rec,
6684 ZPOOL_HIST_INT_STR));
6685 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
6686 if (!cb->internal)
6687 continue;
6688 (void) printf("%s ioctl %s\n", tbuf,
6689 fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
6690 if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
6691 (void) printf(" input:\n");
6692 dump_nvlist(fnvlist_lookup_nvlist(rec,
6693 ZPOOL_HIST_INPUT_NVL), 8);
6694 }
6695 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
6696 (void) printf(" output:\n");
6697 dump_nvlist(fnvlist_lookup_nvlist(rec,
6698 ZPOOL_HIST_OUTPUT_NVL), 8);
6699 }
6700 } else {
6701 if (!cb->internal)
6702 continue;
6703 (void) printf("%s unrecognized record:\n", tbuf);
6704 dump_nvlist(rec, 4);
6705 }
6706
6707 if (!cb->longfmt) {
6708 (void) printf("\n");
6709 continue;
6710 }
6711 (void) printf(" [");
6712 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
6713 uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
6714 struct passwd *pwd = getpwuid(who);
6715 (void) printf("user %d ", (int)who);
6716 if (pwd != NULL)
6717 (void) printf("(%s) ", pwd->pw_name);
6718 }
6719 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
6720 (void) printf("on %s",
6721 fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
6722 }
6723 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
6724 (void) printf(":%s",
6725 fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
6726 }
6727
6728 (void) printf("]");
6729 (void) printf("\n");
6730 }
6731 (void) printf("\n");
6732 nvlist_free(nvhis);
6733
6734 return (ret);
6735 }
6736
6737 /*
6738 * zpool history <pool>
6739 *
6740 * Displays the history of commands that modified pools.
6741 */
6742 int
6743 zpool_do_history(int argc, char **argv)
6744 {
6745 hist_cbdata_t cbdata = { 0 };
6746 int ret;
6747 int c;
6748
6749 cbdata.first = B_TRUE;
6750 /* check options */
6751 while ((c = getopt(argc, argv, "li")) != -1) {
6752 switch (c) {
6753 case 'l':
6754 cbdata.longfmt = B_TRUE;
6755 break;
6756 case 'i':
6757 cbdata.internal = B_TRUE;
6758 break;
6759 case '?':
6760 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6761 optopt);
6762 usage(B_FALSE);
6763 }
6764 }
6765 argc -= optind;
6766 argv += optind;
6767
6768 ret = for_each_pool(argc, argv, B_FALSE, NULL, get_history_one,
6769 &cbdata);
6770
6771 if (argc == 0 && cbdata.first == B_TRUE) {
6772 (void) fprintf(stderr, gettext("no pools available\n"));
6773 return (0);
6774 }
6775
6776 return (ret);
6777 }
6778
6779 typedef struct ev_opts {
6780 int verbose;
6781 int scripted;
6782 int follow;
6783 int clear;
6784 } ev_opts_t;
6785
6786 static void
6787 zpool_do_events_short(nvlist_t *nvl)
6788 {
6789 char ctime_str[26], str[32], *ptr;
6790 int64_t *tv;
6791 uint_t n;
6792
6793 verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
6794 memset(str, ' ', 32);
6795 (void) ctime_r((const time_t *)&tv[0], ctime_str);
6796 (void) strncpy(str, ctime_str+4, 6); /* 'Jun 30' */
6797 (void) strncpy(str+7, ctime_str+20, 4); /* '1993' */
6798 (void) strncpy(str+12, ctime_str+11, 8); /* '21:49:08' */
6799 (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
6800 (void) printf(gettext("%s "), str);
6801
6802 verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
6803 (void) printf(gettext("%s\n"), ptr);
6804 }
6805
6806 static void
6807 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
6808 {
6809 nvpair_t *nvp;
6810
6811 for (nvp = nvlist_next_nvpair(nvl, NULL);
6812 nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
6813
6814 data_type_t type = nvpair_type(nvp);
6815 const char *name = nvpair_name(nvp);
6816
6817 boolean_t b;
6818 uint8_t i8;
6819 uint16_t i16;
6820 uint32_t i32;
6821 uint64_t i64;
6822 char *str;
6823 nvlist_t *cnv;
6824
6825 printf(gettext("%*s%s = "), depth, "", name);
6826
6827 switch (type) {
6828 case DATA_TYPE_BOOLEAN:
6829 printf(gettext("%s"), "1");
6830 break;
6831
6832 case DATA_TYPE_BOOLEAN_VALUE:
6833 (void) nvpair_value_boolean_value(nvp, &b);
6834 printf(gettext("%s"), b ? "1" : "0");
6835 break;
6836
6837 case DATA_TYPE_BYTE:
6838 (void) nvpair_value_byte(nvp, &i8);
6839 printf(gettext("0x%x"), i8);
6840 break;
6841
6842 case DATA_TYPE_INT8:
6843 (void) nvpair_value_int8(nvp, (void *)&i8);
6844 printf(gettext("0x%x"), i8);
6845 break;
6846
6847 case DATA_TYPE_UINT8:
6848 (void) nvpair_value_uint8(nvp, &i8);
6849 printf(gettext("0x%x"), i8);
6850 break;
6851
6852 case DATA_TYPE_INT16:
6853 (void) nvpair_value_int16(nvp, (void *)&i16);
6854 printf(gettext("0x%x"), i16);
6855 break;
6856
6857 case DATA_TYPE_UINT16:
6858 (void) nvpair_value_uint16(nvp, &i16);
6859 printf(gettext("0x%x"), i16);
6860 break;
6861
6862 case DATA_TYPE_INT32:
6863 (void) nvpair_value_int32(nvp, (void *)&i32);
6864 printf(gettext("0x%x"), i32);
6865 break;
6866
6867 case DATA_TYPE_UINT32:
6868 (void) nvpair_value_uint32(nvp, &i32);
6869 printf(gettext("0x%x"), i32);
6870 break;
6871
6872 case DATA_TYPE_INT64:
6873 (void) nvpair_value_int64(nvp, (void *)&i64);
6874 printf(gettext("0x%llx"), (u_longlong_t)i64);
6875 break;
6876
6877 case DATA_TYPE_UINT64:
6878 (void) nvpair_value_uint64(nvp, &i64);
6879 /*
6880 * translate vdev state values to readable
6881 * strings to aide zpool events consumers
6882 */
6883 if (strcmp(name,
6884 FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
6885 strcmp(name,
6886 FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
6887 printf(gettext("\"%s\" (0x%llx)"),
6888 zpool_state_to_name(i64, VDEV_AUX_NONE),
6889 (u_longlong_t)i64);
6890 } else {
6891 printf(gettext("0x%llx"), (u_longlong_t)i64);
6892 }
6893 break;
6894
6895 case DATA_TYPE_HRTIME:
6896 (void) nvpair_value_hrtime(nvp, (void *)&i64);
6897 printf(gettext("0x%llx"), (u_longlong_t)i64);
6898 break;
6899
6900 case DATA_TYPE_STRING:
6901 (void) nvpair_value_string(nvp, &str);
6902 printf(gettext("\"%s\""), str ? str : "<NULL>");
6903 break;
6904
6905 case DATA_TYPE_NVLIST:
6906 printf(gettext("(embedded nvlist)\n"));
6907 (void) nvpair_value_nvlist(nvp, &cnv);
6908 zpool_do_events_nvprint(cnv, depth + 8);
6909 printf(gettext("%*s(end %s)"), depth, "", name);
6910 break;
6911
6912 case DATA_TYPE_NVLIST_ARRAY: {
6913 nvlist_t **val;
6914 uint_t i, nelem;
6915
6916 (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
6917 printf(gettext("(%d embedded nvlists)\n"), nelem);
6918 for (i = 0; i < nelem; i++) {
6919 printf(gettext("%*s%s[%d] = %s\n"),
6920 depth, "", name, i, "(embedded nvlist)");
6921 zpool_do_events_nvprint(val[i], depth + 8);
6922 printf(gettext("%*s(end %s[%i])\n"),
6923 depth, "", name, i);
6924 }
6925 printf(gettext("%*s(end %s)\n"), depth, "", name);
6926 }
6927 break;
6928
6929 case DATA_TYPE_INT8_ARRAY: {
6930 int8_t *val;
6931 uint_t i, nelem;
6932
6933 (void) nvpair_value_int8_array(nvp, &val, &nelem);
6934 for (i = 0; i < nelem; i++)
6935 printf(gettext("0x%x "), val[i]);
6936
6937 break;
6938 }
6939
6940 case DATA_TYPE_UINT8_ARRAY: {
6941 uint8_t *val;
6942 uint_t i, nelem;
6943
6944 (void) nvpair_value_uint8_array(nvp, &val, &nelem);
6945 for (i = 0; i < nelem; i++)
6946 printf(gettext("0x%x "), val[i]);
6947
6948 break;
6949 }
6950
6951 case DATA_TYPE_INT16_ARRAY: {
6952 int16_t *val;
6953 uint_t i, nelem;
6954
6955 (void) nvpair_value_int16_array(nvp, &val, &nelem);
6956 for (i = 0; i < nelem; i++)
6957 printf(gettext("0x%x "), val[i]);
6958
6959 break;
6960 }
6961
6962 case DATA_TYPE_UINT16_ARRAY: {
6963 uint16_t *val;
6964 uint_t i, nelem;
6965
6966 (void) nvpair_value_uint16_array(nvp, &val, &nelem);
6967 for (i = 0; i < nelem; i++)
6968 printf(gettext("0x%x "), val[i]);
6969
6970 break;
6971 }
6972
6973 case DATA_TYPE_INT32_ARRAY: {
6974 int32_t *val;
6975 uint_t i, nelem;
6976
6977 (void) nvpair_value_int32_array(nvp, &val, &nelem);
6978 for (i = 0; i < nelem; i++)
6979 printf(gettext("0x%x "), val[i]);
6980
6981 break;
6982 }
6983
6984 case DATA_TYPE_UINT32_ARRAY: {
6985 uint32_t *val;
6986 uint_t i, nelem;
6987
6988 (void) nvpair_value_uint32_array(nvp, &val, &nelem);
6989 for (i = 0; i < nelem; i++)
6990 printf(gettext("0x%x "), val[i]);
6991
6992 break;
6993 }
6994
6995 case DATA_TYPE_INT64_ARRAY: {
6996 int64_t *val;
6997 uint_t i, nelem;
6998
6999 (void) nvpair_value_int64_array(nvp, &val, &nelem);
7000 for (i = 0; i < nelem; i++)
7001 printf(gettext("0x%llx "),
7002 (u_longlong_t)val[i]);
7003
7004 break;
7005 }
7006
7007 case DATA_TYPE_UINT64_ARRAY: {
7008 uint64_t *val;
7009 uint_t i, nelem;
7010
7011 (void) nvpair_value_uint64_array(nvp, &val, &nelem);
7012 for (i = 0; i < nelem; i++)
7013 printf(gettext("0x%llx "),
7014 (u_longlong_t)val[i]);
7015
7016 break;
7017 }
7018
7019 case DATA_TYPE_STRING_ARRAY: {
7020 char **str;
7021 uint_t i, nelem;
7022
7023 (void) nvpair_value_string_array(nvp, &str, &nelem);
7024 for (i = 0; i < nelem; i++)
7025 printf(gettext("\"%s\" "),
7026 str[i] ? str[i] : "<NULL>");
7027
7028 break;
7029 }
7030
7031 case DATA_TYPE_BOOLEAN_ARRAY:
7032 case DATA_TYPE_BYTE_ARRAY:
7033 case DATA_TYPE_DOUBLE:
7034 case DATA_TYPE_UNKNOWN:
7035 printf(gettext("<unknown>"));
7036 break;
7037 }
7038
7039 printf(gettext("\n"));
7040 }
7041 }
7042
7043 static int
7044 zpool_do_events_next(ev_opts_t *opts)
7045 {
7046 nvlist_t *nvl;
7047 int zevent_fd, ret, dropped;
7048
7049 zevent_fd = open(ZFS_DEV, O_RDWR);
7050 VERIFY(zevent_fd >= 0);
7051
7052 if (!opts->scripted)
7053 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
7054
7055 while (1) {
7056 ret = zpool_events_next(g_zfs, &nvl, &dropped,
7057 (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
7058 if (ret || nvl == NULL)
7059 break;
7060
7061 if (dropped > 0)
7062 (void) printf(gettext("dropped %d events\n"), dropped);
7063
7064 zpool_do_events_short(nvl);
7065
7066 if (opts->verbose) {
7067 zpool_do_events_nvprint(nvl, 8);
7068 printf(gettext("\n"));
7069 }
7070 (void) fflush(stdout);
7071
7072 nvlist_free(nvl);
7073 }
7074
7075 VERIFY(0 == close(zevent_fd));
7076
7077 return (ret);
7078 }
7079
7080 static int
7081 zpool_do_events_clear(ev_opts_t *opts)
7082 {
7083 int count, ret;
7084
7085 ret = zpool_events_clear(g_zfs, &count);
7086 if (!ret)
7087 (void) printf(gettext("cleared %d events\n"), count);
7088
7089 return (ret);
7090 }
7091
7092 /*
7093 * zpool events [-vfc]
7094 *
7095 * Displays events logs by ZFS.
7096 */
7097 int
7098 zpool_do_events(int argc, char **argv)
7099 {
7100 ev_opts_t opts = { 0 };
7101 int ret;
7102 int c;
7103
7104 /* check options */
7105 while ((c = getopt(argc, argv, "vHfc")) != -1) {
7106 switch (c) {
7107 case 'v':
7108 opts.verbose = 1;
7109 break;
7110 case 'H':
7111 opts.scripted = 1;
7112 break;
7113 case 'f':
7114 opts.follow = 1;
7115 break;
7116 case 'c':
7117 opts.clear = 1;
7118 break;
7119 case '?':
7120 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7121 optopt);
7122 usage(B_FALSE);
7123 }
7124 }
7125 argc -= optind;
7126 argv += optind;
7127
7128 if (opts.clear)
7129 ret = zpool_do_events_clear(&opts);
7130 else
7131 ret = zpool_do_events_next(&opts);
7132
7133 return (ret);
7134 }
7135
7136 static int
7137 get_callback(zpool_handle_t *zhp, void *data)
7138 {
7139 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
7140 char value[MAXNAMELEN];
7141 zprop_source_t srctype;
7142 zprop_list_t *pl;
7143
7144 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
7145
7146 /*
7147 * Skip the special fake placeholder. This will also skip
7148 * over the name property when 'all' is specified.
7149 */
7150 if (pl->pl_prop == ZPOOL_PROP_NAME &&
7151 pl == cbp->cb_proplist)
7152 continue;
7153
7154 if (pl->pl_prop == ZPROP_INVAL &&
7155 (zpool_prop_feature(pl->pl_user_prop) ||
7156 zpool_prop_unsupported(pl->pl_user_prop))) {
7157 srctype = ZPROP_SRC_LOCAL;
7158
7159 if (zpool_prop_get_feature(zhp, pl->pl_user_prop,
7160 value, sizeof (value)) == 0) {
7161 zprop_print_one_property(zpool_get_name(zhp),
7162 cbp, pl->pl_user_prop, value, srctype,
7163 NULL, NULL);
7164 }
7165 } else {
7166 if (zpool_get_prop(zhp, pl->pl_prop, value,
7167 sizeof (value), &srctype, cbp->cb_literal) != 0)
7168 continue;
7169
7170 zprop_print_one_property(zpool_get_name(zhp), cbp,
7171 zpool_prop_to_name(pl->pl_prop), value, srctype,
7172 NULL, NULL);
7173 }
7174 }
7175 return (0);
7176 }
7177
7178 /*
7179 * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
7180 *
7181 * -H Scripted mode. Don't display headers, and separate properties
7182 * by a single tab.
7183 * -o List of columns to display. Defaults to
7184 * "name,property,value,source".
7185 * -p Diplay values in parsable (exact) format.
7186 *
7187 * Get properties of pools in the system. Output space statistics
7188 * for each one as well as other attributes.
7189 */
7190 int
7191 zpool_do_get(int argc, char **argv)
7192 {
7193 zprop_get_cbdata_t cb = { 0 };
7194 zprop_list_t fake_name = { 0 };
7195 int ret;
7196 int c, i;
7197 char *value;
7198
7199 cb.cb_first = B_TRUE;
7200
7201 /*
7202 * Set up default columns and sources.
7203 */
7204 cb.cb_sources = ZPROP_SRC_ALL;
7205 cb.cb_columns[0] = GET_COL_NAME;
7206 cb.cb_columns[1] = GET_COL_PROPERTY;
7207 cb.cb_columns[2] = GET_COL_VALUE;
7208 cb.cb_columns[3] = GET_COL_SOURCE;
7209 cb.cb_type = ZFS_TYPE_POOL;
7210
7211 /* check options */
7212 while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
7213 switch (c) {
7214 case 'p':
7215 cb.cb_literal = B_TRUE;
7216 break;
7217 case 'H':
7218 cb.cb_scripted = B_TRUE;
7219 break;
7220 case 'o':
7221 bzero(&cb.cb_columns, sizeof (cb.cb_columns));
7222 i = 0;
7223 while (*optarg != '\0') {
7224 static char *col_subopts[] =
7225 { "name", "property", "value", "source",
7226 "all", NULL };
7227
7228 if (i == ZFS_GET_NCOLS) {
7229 (void) fprintf(stderr, gettext("too "
7230 "many fields given to -o "
7231 "option\n"));
7232 usage(B_FALSE);
7233 }
7234
7235 switch (getsubopt(&optarg, col_subopts,
7236 &value)) {
7237 case 0:
7238 cb.cb_columns[i++] = GET_COL_NAME;
7239 break;
7240 case 1:
7241 cb.cb_columns[i++] = GET_COL_PROPERTY;
7242 break;
7243 case 2:
7244 cb.cb_columns[i++] = GET_COL_VALUE;
7245 break;
7246 case 3:
7247 cb.cb_columns[i++] = GET_COL_SOURCE;
7248 break;
7249 case 4:
7250 if (i > 0) {
7251 (void) fprintf(stderr,
7252 gettext("\"all\" conflicts "
7253 "with specific fields "
7254 "given to -o option\n"));
7255 usage(B_FALSE);
7256 }
7257 cb.cb_columns[0] = GET_COL_NAME;
7258 cb.cb_columns[1] = GET_COL_PROPERTY;
7259 cb.cb_columns[2] = GET_COL_VALUE;
7260 cb.cb_columns[3] = GET_COL_SOURCE;
7261 i = ZFS_GET_NCOLS;
7262 break;
7263 default:
7264 (void) fprintf(stderr,
7265 gettext("invalid column name "
7266 "'%s'\n"), value);
7267 usage(B_FALSE);
7268 }
7269 }
7270 break;
7271 case '?':
7272 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7273 optopt);
7274 usage(B_FALSE);
7275 }
7276 }
7277
7278 argc -= optind;
7279 argv += optind;
7280
7281 if (argc < 1) {
7282 (void) fprintf(stderr, gettext("missing property "
7283 "argument\n"));
7284 usage(B_FALSE);
7285 }
7286
7287 if (zprop_get_list(g_zfs, argv[0], &cb.cb_proplist,
7288 ZFS_TYPE_POOL) != 0)
7289 usage(B_FALSE);
7290
7291 argc--;
7292 argv++;
7293
7294 if (cb.cb_proplist != NULL) {
7295 fake_name.pl_prop = ZPOOL_PROP_NAME;
7296 fake_name.pl_width = strlen(gettext("NAME"));
7297 fake_name.pl_next = cb.cb_proplist;
7298 cb.cb_proplist = &fake_name;
7299 }
7300
7301 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist,
7302 get_callback, &cb);
7303
7304 if (cb.cb_proplist == &fake_name)
7305 zprop_free_list(fake_name.pl_next);
7306 else
7307 zprop_free_list(cb.cb_proplist);
7308
7309 return (ret);
7310 }
7311
7312 typedef struct set_cbdata {
7313 char *cb_propname;
7314 char *cb_value;
7315 boolean_t cb_any_successful;
7316 } set_cbdata_t;
7317
7318 int
7319 set_callback(zpool_handle_t *zhp, void *data)
7320 {
7321 int error;
7322 set_cbdata_t *cb = (set_cbdata_t *)data;
7323
7324 error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
7325
7326 if (!error)
7327 cb->cb_any_successful = B_TRUE;
7328
7329 return (error);
7330 }
7331
7332 int
7333 zpool_do_set(int argc, char **argv)
7334 {
7335 set_cbdata_t cb = { 0 };
7336 int error;
7337
7338 if (argc > 1 && argv[1][0] == '-') {
7339 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7340 argv[1][1]);
7341 usage(B_FALSE);
7342 }
7343
7344 if (argc < 2) {
7345 (void) fprintf(stderr, gettext("missing property=value "
7346 "argument\n"));
7347 usage(B_FALSE);
7348 }
7349
7350 if (argc < 3) {
7351 (void) fprintf(stderr, gettext("missing pool name\n"));
7352 usage(B_FALSE);
7353 }
7354
7355 if (argc > 3) {
7356 (void) fprintf(stderr, gettext("too many pool names\n"));
7357 usage(B_FALSE);
7358 }
7359
7360 cb.cb_propname = argv[1];
7361 cb.cb_value = strchr(cb.cb_propname, '=');
7362 if (cb.cb_value == NULL) {
7363 (void) fprintf(stderr, gettext("missing value in "
7364 "property=value argument\n"));
7365 usage(B_FALSE);
7366 }
7367
7368 *(cb.cb_value) = '\0';
7369 cb.cb_value++;
7370
7371 error = for_each_pool(argc - 2, argv + 2, B_TRUE, NULL,
7372 set_callback, &cb);
7373
7374 return (error);
7375 }
7376
7377 static int
7378 find_command_idx(char *command, int *idx)
7379 {
7380 int i;
7381
7382 for (i = 0; i < NCOMMAND; i++) {
7383 if (command_table[i].name == NULL)
7384 continue;
7385
7386 if (strcmp(command, command_table[i].name) == 0) {
7387 *idx = i;
7388 return (0);
7389 }
7390 }
7391 return (1);
7392 }
7393
7394 int
7395 main(int argc, char **argv)
7396 {
7397 int ret;
7398 int i = 0;
7399 char *cmdname;
7400
7401 (void) setlocale(LC_ALL, "");
7402 (void) textdomain(TEXT_DOMAIN);
7403 srand(time(NULL));
7404
7405 dprintf_setup(&argc, argv);
7406
7407 opterr = 0;
7408
7409 /*
7410 * Make sure the user has specified some command.
7411 */
7412 if (argc < 2) {
7413 (void) fprintf(stderr, gettext("missing command\n"));
7414 usage(B_FALSE);
7415 }
7416
7417 cmdname = argv[1];
7418
7419 /*
7420 * Special case '-?'
7421 */
7422 if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
7423 usage(B_TRUE);
7424
7425 if ((g_zfs = libzfs_init()) == NULL) {
7426 (void) fprintf(stderr, "%s", libzfs_error_init(errno));
7427 return (1);
7428 }
7429
7430 libzfs_print_on_error(g_zfs, B_TRUE);
7431
7432 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
7433
7434 /*
7435 * Run the appropriate command.
7436 */
7437 if (find_command_idx(cmdname, &i) == 0) {
7438 current_command = &command_table[i];
7439 ret = command_table[i].func(argc - 1, argv + 1);
7440 } else if (strchr(cmdname, '=')) {
7441 verify(find_command_idx("set", &i) == 0);
7442 current_command = &command_table[i];
7443 ret = command_table[i].func(argc, argv);
7444 } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
7445 /*
7446 * 'freeze' is a vile debugging abomination, so we treat
7447 * it as such.
7448 */
7449 char buf[16384];
7450 int fd = open(ZFS_DEV, O_RDWR);
7451 (void) strlcpy((void *)buf, argv[2], sizeof (buf));
7452 return (!!ioctl(fd, ZFS_IOC_POOL_FREEZE, buf));
7453 } else {
7454 (void) fprintf(stderr, gettext("unrecognized "
7455 "command '%s'\n"), cmdname);
7456 usage(B_FALSE);
7457 ret = 1;
7458 }
7459
7460 if (ret == 0 && log_history)
7461 (void) zpool_log_history(g_zfs, history_str);
7462
7463 libzfs_fini(g_zfs);
7464
7465 /*
7466 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
7467 * for the purposes of running ::findleaks.
7468 */
7469 if (getenv("ZFS_ABORT") != NULL) {
7470 (void) printf("dumping core by request\n");
7471 abort();
7472 }
7473
7474 return (ret);
7475 }