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