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