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