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