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