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