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