1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * CDDL HEADER START
4 *
5 * The contents of this file are subject to the terms of the
6 * Common Development and Distribution License (the "License").
7 * You may not use this file except in compliance with the License.
8 *
9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 * or https://opensource.org/licenses/CDDL-1.0.
11 * See the License for the specific language governing permissions
12 * and limitations under the License.
13 *
14 * When distributing Covered Code, include this CDDL HEADER in each
15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 * If applicable, add the following below this CDDL HEADER, with the
17 * fields enclosed by brackets "[]" replaced with your own identifying
18 * information: Portions Copyright [yyyy] [name of copyright owner]
19 *
20 * CDDL HEADER END
21 */
22
23 /*
24 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25 * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
26 * Copyright (c) 2011, 2024 by Delphix. All rights reserved.
27 * Copyright (c) 2012 by Frederik Wessels. All rights reserved.
28 * Copyright (c) 2012 by Cyril Plisko. All rights reserved.
29 * Copyright (c) 2013 by Prasad Joshi (sTec). All rights reserved.
30 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
31 * Copyright (c) 2017 Datto Inc.
32 * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
33 * Copyright (c) 2017, Intel Corporation.
34 * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>
35 * Copyright (c) 2021, Colm Buckley <colm@tuatha.org>
36 * Copyright (c) 2021, 2023, 2025, Klara, Inc.
37 * Copyright (c) 2021, 2025 Hewlett Packard Enterprise Development LP.
38 */
39
40 #include <assert.h>
41 #include <ctype.h>
42 #include <dirent.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <getopt.h>
46 #include <inttypes.h>
47 #include <libgen.h>
48 #include <libintl.h>
49 #include <locale.h>
50 #include <pthread.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <termios.h>
55 #include <time.h>
56 #include <unistd.h>
57 #include <pwd.h>
58 #include <zone.h>
59 #include <sys/wait.h>
60 #include <zfs_prop.h>
61 #include <sys/fs/zfs.h>
62 #include <sys/stat.h>
63 #include <sys/systeminfo.h>
64 #include <sys/fm/fs/zfs.h>
65 #include <sys/fm/util.h>
66 #include <sys/fm/protocol.h>
67 #include <sys/zfs_ioctl.h>
68 #include <sys/mount.h>
69 #include <sys/sysmacros.h>
70 #include <string.h>
71 #include <math.h>
72
73 #include <libzfs.h>
74 #include <libzutil.h>
75
76 #include "zpool_util.h"
77 #include "zfs_comutil.h"
78 #include "zfeature_common.h"
79 #include "zfs_valstr.h"
80
81 #include "statcommon.h"
82
83 libzfs_handle_t *g_zfs;
84
85 static int mount_tp_nthr = 512; /* tpool threads for multi-threaded mounting */
86
87 static int zpool_do_create(int, char **);
88 static int zpool_do_destroy(int, char **);
89
90 static int zpool_do_add(int, char **);
91 static int zpool_do_remove(int, char **);
92 static int zpool_do_labelclear(int, char **);
93
94 static int zpool_do_checkpoint(int, char **);
95 static int zpool_do_prefetch(int, char **);
96
97 static int zpool_do_list(int, char **);
98 static int zpool_do_iostat(int, char **);
99 static int zpool_do_status(int, char **);
100
101 static int zpool_do_online(int, char **);
102 static int zpool_do_offline(int, char **);
103 static int zpool_do_clear(int, char **);
104 static int zpool_do_reopen(int, char **);
105
106 static int zpool_do_reguid(int, char **);
107
108 static int zpool_do_attach(int, char **);
109 static int zpool_do_detach(int, char **);
110 static int zpool_do_replace(int, char **);
111 static int zpool_do_split(int, char **);
112
113 static int zpool_do_initialize(int, char **);
114 static int zpool_do_scrub(int, char **);
115 static int zpool_do_resilver(int, char **);
116 static int zpool_do_trim(int, char **);
117
118 static int zpool_do_import(int, char **);
119 static int zpool_do_export(int, char **);
120
121 static int zpool_do_upgrade(int, char **);
122
123 static int zpool_do_history(int, char **);
124 static int zpool_do_events(int, char **);
125
126 static int zpool_do_get(int, char **);
127 static int zpool_do_set(int, char **);
128
129 static int zpool_do_sync(int, char **);
130
131 static int zpool_do_version(int, char **);
132
133 static int zpool_do_wait(int, char **);
134
135 static int zpool_do_ddt_prune(int, char **);
136
137 static int zpool_do_help(int argc, char **argv);
138
139 static zpool_compat_status_t zpool_do_load_compat(
140 const char *, boolean_t *);
141
142 enum zpool_options {
143 ZPOOL_OPTION_POWER = 1024,
144 ZPOOL_OPTION_ALLOW_INUSE,
145 ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH,
146 ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH,
147 ZPOOL_OPTION_POOL_KEY_GUID,
148 ZPOOL_OPTION_JSON_NUMS_AS_INT,
149 ZPOOL_OPTION_JSON_FLAT_VDEVS
150 };
151
152 /*
153 * These libumem hooks provide a reasonable set of defaults for the allocator's
154 * debugging facilities.
155 */
156
157 #ifdef DEBUG
158 const char *
_umem_debug_init(void)159 _umem_debug_init(void)
160 {
161 return ("default,verbose"); /* $UMEM_DEBUG setting */
162 }
163
164 const char *
_umem_logging_init(void)165 _umem_logging_init(void)
166 {
167 return ("fail,contents"); /* $UMEM_LOGGING setting */
168 }
169 #endif
170
171 typedef enum {
172 HELP_ADD,
173 HELP_ATTACH,
174 HELP_CLEAR,
175 HELP_CREATE,
176 HELP_CHECKPOINT,
177 HELP_DDT_PRUNE,
178 HELP_DESTROY,
179 HELP_DETACH,
180 HELP_EXPORT,
181 HELP_HISTORY,
182 HELP_IMPORT,
183 HELP_IOSTAT,
184 HELP_LABELCLEAR,
185 HELP_LIST,
186 HELP_OFFLINE,
187 HELP_ONLINE,
188 HELP_PREFETCH,
189 HELP_REPLACE,
190 HELP_REMOVE,
191 HELP_INITIALIZE,
192 HELP_SCRUB,
193 HELP_RESILVER,
194 HELP_TRIM,
195 HELP_STATUS,
196 HELP_UPGRADE,
197 HELP_EVENTS,
198 HELP_GET,
199 HELP_SET,
200 HELP_SPLIT,
201 HELP_SYNC,
202 HELP_REGUID,
203 HELP_REOPEN,
204 HELP_VERSION,
205 HELP_WAIT
206 } zpool_help_t;
207
208
209 /*
210 * Flags for stats to display with "zpool iostats"
211 */
212 enum iostat_type {
213 IOS_DEFAULT = 0,
214 IOS_LATENCY = 1,
215 IOS_QUEUES = 2,
216 IOS_L_HISTO = 3,
217 IOS_RQ_HISTO = 4,
218 IOS_COUNT, /* always last element */
219 };
220
221 /* iostat_type entries as bitmasks */
222 #define IOS_DEFAULT_M (1ULL << IOS_DEFAULT)
223 #define IOS_LATENCY_M (1ULL << IOS_LATENCY)
224 #define IOS_QUEUES_M (1ULL << IOS_QUEUES)
225 #define IOS_L_HISTO_M (1ULL << IOS_L_HISTO)
226 #define IOS_RQ_HISTO_M (1ULL << IOS_RQ_HISTO)
227
228 /* Mask of all the histo bits */
229 #define IOS_ANYHISTO_M (IOS_L_HISTO_M | IOS_RQ_HISTO_M)
230
231 /*
232 * Lookup table for iostat flags to nvlist names. Basically a list
233 * of all the nvlists a flag requires. Also specifies the order in
234 * which data gets printed in zpool iostat.
235 */
236 static const char *vsx_type_to_nvlist[IOS_COUNT][15] = {
237 [IOS_L_HISTO] = {
238 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
239 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
240 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
241 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
242 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
243 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
244 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
245 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
246 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
247 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
248 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
249 NULL},
250 [IOS_LATENCY] = {
251 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
252 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
253 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
254 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
255 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
256 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
257 NULL},
258 [IOS_QUEUES] = {
259 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
260 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
261 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
262 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
263 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
264 ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
265 ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
266 NULL},
267 [IOS_RQ_HISTO] = {
268 ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
269 ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
270 ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
271 ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
272 ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
273 ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
274 ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
275 ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
276 ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
277 ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
278 ZPOOL_CONFIG_VDEV_IND_TRIM_HISTO,
279 ZPOOL_CONFIG_VDEV_AGG_TRIM_HISTO,
280 ZPOOL_CONFIG_VDEV_IND_REBUILD_HISTO,
281 ZPOOL_CONFIG_VDEV_AGG_REBUILD_HISTO,
282 NULL},
283 };
284
285 static const char *pool_scan_func_str[] = {
286 "NONE",
287 "SCRUB",
288 "RESILVER",
289 "ERRORSCRUB"
290 };
291
292 static const char *pool_scan_state_str[] = {
293 "NONE",
294 "SCANNING",
295 "FINISHED",
296 "CANCELED",
297 "ERRORSCRUBBING"
298 };
299
300 static const char *vdev_rebuild_state_str[] = {
301 "NONE",
302 "ACTIVE",
303 "CANCELED",
304 "COMPLETE"
305 };
306
307 static const char *checkpoint_state_str[] = {
308 "NONE",
309 "EXISTS",
310 "DISCARDING"
311 };
312
313 static const char *vdev_state_str[] = {
314 "UNKNOWN",
315 "CLOSED",
316 "OFFLINE",
317 "REMOVED",
318 "CANT_OPEN",
319 "FAULTED",
320 "DEGRADED",
321 "ONLINE"
322 };
323
324 static const char *vdev_aux_str[] = {
325 "NONE",
326 "OPEN_FAILED",
327 "CORRUPT_DATA",
328 "NO_REPLICAS",
329 "BAD_GUID_SUM",
330 "TOO_SMALL",
331 "BAD_LABEL",
332 "VERSION_NEWER",
333 "VERSION_OLDER",
334 "UNSUP_FEAT",
335 "SPARED",
336 "ERR_EXCEEDED",
337 "IO_FAILURE",
338 "BAD_LOG",
339 "EXTERNAL",
340 "SPLIT_POOL",
341 "BAD_ASHIFT",
342 "EXTERNAL_PERSIST",
343 "ACTIVE",
344 "CHILDREN_OFFLINE",
345 "ASHIFT_TOO_BIG"
346 };
347
348 static const char *vdev_init_state_str[] = {
349 "NONE",
350 "ACTIVE",
351 "CANCELED",
352 "SUSPENDED",
353 "COMPLETE"
354 };
355
356 static const char *vdev_trim_state_str[] = {
357 "NONE",
358 "ACTIVE",
359 "CANCELED",
360 "SUSPENDED",
361 "COMPLETE"
362 };
363
364 #define ZFS_NICE_TIMESTAMP 100
365
366 /*
367 * Given a cb->cb_flags with a histogram bit set, return the iostat_type.
368 * Right now, only one histo bit is ever set at one time, so we can
369 * just do a highbit64(a)
370 */
371 #define IOS_HISTO_IDX(a) (highbit64(a & IOS_ANYHISTO_M) - 1)
372
373 typedef struct zpool_command {
374 const char *name;
375 int (*func)(int, char **);
376 zpool_help_t usage;
377 } zpool_command_t;
378
379 /*
380 * Master command table. Each ZFS command has a name, associated function, and
381 * usage message. The usage messages need to be internationalized, so we have
382 * to have a function to return the usage message based on a command index.
383 *
384 * These commands are organized according to how they are displayed in the usage
385 * message. An empty command (one with a NULL name) indicates an empty line in
386 * the generic usage message.
387 */
388 static zpool_command_t command_table[] = {
389 { "version", zpool_do_version, HELP_VERSION },
390 { NULL },
391 { "create", zpool_do_create, HELP_CREATE },
392 { "destroy", zpool_do_destroy, HELP_DESTROY },
393 { NULL },
394 { "add", zpool_do_add, HELP_ADD },
395 { "remove", zpool_do_remove, HELP_REMOVE },
396 { NULL },
397 { "labelclear", zpool_do_labelclear, HELP_LABELCLEAR },
398 { NULL },
399 { "checkpoint", zpool_do_checkpoint, HELP_CHECKPOINT },
400 { "prefetch", zpool_do_prefetch, HELP_PREFETCH },
401 { NULL },
402 { "list", zpool_do_list, HELP_LIST },
403 { "iostat", zpool_do_iostat, HELP_IOSTAT },
404 { "status", zpool_do_status, HELP_STATUS },
405 { NULL },
406 { "online", zpool_do_online, HELP_ONLINE },
407 { "offline", zpool_do_offline, HELP_OFFLINE },
408 { "clear", zpool_do_clear, HELP_CLEAR },
409 { "reopen", zpool_do_reopen, HELP_REOPEN },
410 { NULL },
411 { "attach", zpool_do_attach, HELP_ATTACH },
412 { "detach", zpool_do_detach, HELP_DETACH },
413 { "replace", zpool_do_replace, HELP_REPLACE },
414 { "split", zpool_do_split, HELP_SPLIT },
415 { NULL },
416 { "initialize", zpool_do_initialize, HELP_INITIALIZE },
417 { "resilver", zpool_do_resilver, HELP_RESILVER },
418 { "scrub", zpool_do_scrub, HELP_SCRUB },
419 { "trim", zpool_do_trim, HELP_TRIM },
420 { NULL },
421 { "import", zpool_do_import, HELP_IMPORT },
422 { "export", zpool_do_export, HELP_EXPORT },
423 { "upgrade", zpool_do_upgrade, HELP_UPGRADE },
424 { "reguid", zpool_do_reguid, HELP_REGUID },
425 { NULL },
426 { "history", zpool_do_history, HELP_HISTORY },
427 { "events", zpool_do_events, HELP_EVENTS },
428 { NULL },
429 { "get", zpool_do_get, HELP_GET },
430 { "set", zpool_do_set, HELP_SET },
431 { "sync", zpool_do_sync, HELP_SYNC },
432 { NULL },
433 { "wait", zpool_do_wait, HELP_WAIT },
434 { NULL },
435 { "ddtprune", zpool_do_ddt_prune, HELP_DDT_PRUNE },
436 };
437
438 #define NCOMMAND (ARRAY_SIZE(command_table))
439
440 #define VDEV_ALLOC_CLASS_LOGS "logs"
441
442 #define MAX_CMD_LEN 256
443
444 static zpool_command_t *current_command;
445 static zfs_type_t current_prop_type = (ZFS_TYPE_POOL | ZFS_TYPE_VDEV);
446 static char history_str[HIS_MAX_RECORD_LEN];
447 static boolean_t log_history = B_TRUE;
448 static uint_t timestamp_fmt = NODATE;
449
450 static const char *
get_usage(zpool_help_t idx)451 get_usage(zpool_help_t idx)
452 {
453 switch (idx) {
454 case HELP_ADD:
455 return (gettext("\tadd [-afgLnP] [-o property=value] "
456 "<pool> <vdev> ...\n"));
457 case HELP_ATTACH:
458 return (gettext("\tattach [-fsw] [-o property=value] "
459 "<pool> <vdev> <new-device>\n"));
460 case HELP_CLEAR:
461 return (gettext("\tclear [--power] <pool> [device]\n"));
462 case HELP_CREATE:
463 return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
464 "\t [-O file-system-property=value] ... \n"
465 "\t [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
466 case HELP_CHECKPOINT:
467 return (gettext("\tcheckpoint [-d [-w]] <pool> ...\n"));
468 case HELP_DESTROY:
469 return (gettext("\tdestroy [-f] <pool>\n"));
470 case HELP_DETACH:
471 return (gettext("\tdetach <pool> <device>\n"));
472 case HELP_EXPORT:
473 return (gettext("\texport [-af] <pool> ...\n"));
474 case HELP_HISTORY:
475 return (gettext("\thistory [-il] [<pool>] ...\n"));
476 case HELP_IMPORT:
477 return (gettext("\timport [-d dir] [-D]\n"
478 "\timport [-o mntopts] [-o property=value] ... \n"
479 "\t [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
480 "[-R root] [-F [-n]] -a\n"
481 "\timport [-o mntopts] [-o property=value] ... \n"
482 "\t [-d dir | -c cachefile] [-D] [-l] [-f] [-m] [-N] "
483 "[-R root] [-F [-n]]\n"
484 "\t [--rewind-to-checkpoint] <pool | id> [newpool]\n"));
485 case HELP_IOSTAT:
486 return (gettext("\tiostat [[[-c [script1,script2,...]"
487 "[-lq]]|[-rw]] [-T d | u] [-ghHLpPvy]\n"
488 "\t [[pool ...]|[pool vdev ...]|[vdev ...]]"
489 " [[-n] interval [count]]\n"));
490 case HELP_LABELCLEAR:
491 return (gettext("\tlabelclear [-f] <vdev>\n"));
492 case HELP_LIST:
493 return (gettext("\tlist [-gHLpPv] [-o property[,...]] [-j "
494 "[--json-int, --json-pool-key-guid]] ...\n"
495 "\t [-T d|u] [pool] [interval [count]]\n"));
496 case HELP_PREFETCH:
497 return (gettext("\tprefetch [-t <type>] <pool>\n"));
498 case HELP_OFFLINE:
499 return (gettext("\toffline [--power]|[[-f][-t]] <pool> "
500 "<device> ...\n"));
501 case HELP_ONLINE:
502 return (gettext("\tonline [--power][-e] <pool> <device> "
503 "...\n"));
504 case HELP_REPLACE:
505 return (gettext("\treplace [-fsw] [-o property=value] "
506 "<pool> <device> [new-device]\n"));
507 case HELP_REMOVE:
508 return (gettext("\tremove [-npsw] <pool> <device> ...\n"));
509 case HELP_REOPEN:
510 return (gettext("\treopen [-n] <pool>\n"));
511 case HELP_INITIALIZE:
512 return (gettext("\tinitialize [-c | -s | -u] [-w] <-a | <pool> "
513 "[<device> ...]>\n"));
514 case HELP_SCRUB:
515 return (gettext("\tscrub [-e | -s | -p | -C | -E | -S] [-w] "
516 "<-a | <pool> [<pool> ...]>\n"));
517 case HELP_RESILVER:
518 return (gettext("\tresilver <pool> ...\n"));
519 case HELP_TRIM:
520 return (gettext("\ttrim [-dw] [-r <rate>] [-c | -s] "
521 "<-a | <pool> [<device> ...]>\n"));
522 case HELP_STATUS:
523 return (gettext("\tstatus [-DdegiLPpstvx] "
524 "[-c script1[,script2,...]] ...\n"
525 "\t [-j|--json [--json-flat-vdevs] [--json-int] "
526 "[--json-pool-key-guid]] ...\n"
527 "\t [-T d|u] [--power] [pool] [interval [count]]\n"));
528 case HELP_UPGRADE:
529 return (gettext("\tupgrade\n"
530 "\tupgrade -v\n"
531 "\tupgrade [-V version] <-a | pool ...>\n"));
532 case HELP_EVENTS:
533 return (gettext("\tevents [-vHf [pool] | -c]\n"));
534 case HELP_GET:
535 return (gettext("\tget [-Hp] [-j [--json-int, "
536 "--json-pool-key-guid]] ...\n"
537 "\t [-o \"all\" | field[,...]] "
538 "<\"all\" | property[,...]> <pool> ...\n"));
539 case HELP_SET:
540 return (gettext("\tset <property=value> <pool>\n"
541 "\tset <vdev_property=value> <pool> <vdev>\n"));
542 case HELP_SPLIT:
543 return (gettext("\tsplit [-gLnPl] [-R altroot] [-o mntopts]\n"
544 "\t [-o property=value] <pool> <newpool> "
545 "[<device> ...]\n"));
546 case HELP_REGUID:
547 return (gettext("\treguid [-g guid] <pool>\n"));
548 case HELP_SYNC:
549 return (gettext("\tsync [pool] ...\n"));
550 case HELP_VERSION:
551 return (gettext("\tversion [-j]\n"));
552 case HELP_WAIT:
553 return (gettext("\twait [-Hp] [-T d|u] [-t <activity>[,...]] "
554 "<pool> [interval]\n"));
555 case HELP_DDT_PRUNE:
556 return (gettext("\tddtprune -d|-p <amount> <pool>\n"));
557 default:
558 __builtin_unreachable();
559 }
560 }
561
562 /*
563 * Callback routine that will print out a pool property value.
564 */
565 static int
print_pool_prop_cb(int prop,void * cb)566 print_pool_prop_cb(int prop, void *cb)
567 {
568 FILE *fp = cb;
569
570 (void) fprintf(fp, "\t%-19s ", zpool_prop_to_name(prop));
571
572 if (zpool_prop_readonly(prop))
573 (void) fprintf(fp, " NO ");
574 else
575 (void) fprintf(fp, " YES ");
576
577 if (zpool_prop_values(prop) == NULL)
578 (void) fprintf(fp, "-\n");
579 else
580 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
581
582 return (ZPROP_CONT);
583 }
584
585 /*
586 * Callback routine that will print out a vdev property value.
587 */
588 static int
print_vdev_prop_cb(int prop,void * cb)589 print_vdev_prop_cb(int prop, void *cb)
590 {
591 FILE *fp = cb;
592
593 (void) fprintf(fp, "\t%-19s ", vdev_prop_to_name(prop));
594
595 if (vdev_prop_readonly(prop))
596 (void) fprintf(fp, " NO ");
597 else
598 (void) fprintf(fp, " YES ");
599
600 if (vdev_prop_values(prop) == NULL)
601 (void) fprintf(fp, "-\n");
602 else
603 (void) fprintf(fp, "%s\n", vdev_prop_values(prop));
604
605 return (ZPROP_CONT);
606 }
607
608 /*
609 * Given a leaf vdev name like 'L5' return its VDEV_CONFIG_PATH like
610 * '/dev/disk/by-vdev/L5'.
611 */
612 static const char *
vdev_name_to_path(zpool_handle_t * zhp,char * vdev)613 vdev_name_to_path(zpool_handle_t *zhp, char *vdev)
614 {
615 nvlist_t *vdev_nv = zpool_find_vdev(zhp, vdev, NULL, NULL, NULL);
616 if (vdev_nv == NULL) {
617 return (NULL);
618 }
619 return (fnvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH));
620 }
621
622 static int
zpool_power_on(zpool_handle_t * zhp,char * vdev)623 zpool_power_on(zpool_handle_t *zhp, char *vdev)
624 {
625 return (zpool_power(zhp, vdev, B_TRUE));
626 }
627
628 static int
zpool_power_on_and_disk_wait(zpool_handle_t * zhp,char * vdev)629 zpool_power_on_and_disk_wait(zpool_handle_t *zhp, char *vdev)
630 {
631 int rc;
632
633 rc = zpool_power_on(zhp, vdev);
634 if (rc != 0)
635 return (rc);
636
637 (void) zpool_disk_wait(vdev_name_to_path(zhp, vdev));
638
639 return (0);
640 }
641
642 static int
zpool_power_on_pool_and_wait_for_devices(zpool_handle_t * zhp)643 zpool_power_on_pool_and_wait_for_devices(zpool_handle_t *zhp)
644 {
645 nvlist_t *nv;
646 const char *path = NULL;
647 int rc;
648
649 /* Power up all the devices first */
650 FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
651 path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
652 if (path != NULL) {
653 rc = zpool_power_on(zhp, (char *)path);
654 if (rc != 0) {
655 return (rc);
656 }
657 }
658 }
659
660 /*
661 * Wait for their devices to show up. Since we powered them on
662 * at roughly the same time, they should all come online around
663 * the same time.
664 */
665 FOR_EACH_REAL_LEAF_VDEV(zhp, nv) {
666 path = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
667 (void) zpool_disk_wait(path);
668 }
669
670 return (0);
671 }
672
673 static int
zpool_power_off(zpool_handle_t * zhp,char * vdev)674 zpool_power_off(zpool_handle_t *zhp, char *vdev)
675 {
676 return (zpool_power(zhp, vdev, B_FALSE));
677 }
678
679 /*
680 * Display usage message. If we're inside a command, display only the usage for
681 * that command. Otherwise, iterate over the entire command table and display
682 * a complete usage message.
683 */
684 static __attribute__((noreturn)) void
usage(boolean_t requested)685 usage(boolean_t requested)
686 {
687 FILE *fp = requested ? stdout : stderr;
688
689 if (current_command == NULL) {
690 int i;
691
692 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
693 (void) fprintf(fp,
694 gettext("where 'command' is one of the following:\n\n"));
695
696 for (i = 0; i < NCOMMAND; i++) {
697 if (command_table[i].name == NULL)
698 (void) fprintf(fp, "\n");
699 else
700 (void) fprintf(fp, "%s",
701 get_usage(command_table[i].usage));
702 }
703
704 (void) fprintf(fp,
705 gettext("\nFor further help on a command or topic, "
706 "run: %s\n"), "zpool help [<topic>]");
707 } else {
708 (void) fprintf(fp, gettext("usage:\n"));
709 (void) fprintf(fp, "%s", get_usage(current_command->usage));
710 }
711
712 if (current_command != NULL &&
713 current_prop_type != (ZFS_TYPE_POOL | ZFS_TYPE_VDEV) &&
714 ((strcmp(current_command->name, "set") == 0) ||
715 (strcmp(current_command->name, "get") == 0) ||
716 (strcmp(current_command->name, "list") == 0))) {
717
718 (void) fprintf(fp, "%s",
719 gettext("\nthe following properties are supported:\n"));
720
721 (void) fprintf(fp, "\n\t%-19s %s %s\n\n",
722 "PROPERTY", "EDIT", "VALUES");
723
724 /* Iterate over all properties */
725 if (current_prop_type == ZFS_TYPE_POOL) {
726 (void) zprop_iter(print_pool_prop_cb, fp, B_FALSE,
727 B_TRUE, current_prop_type);
728
729 (void) fprintf(fp, "\t%-19s ", "feature@...");
730 (void) fprintf(fp, "YES "
731 "disabled | enabled | active\n");
732
733 (void) fprintf(fp, gettext("\nThe feature@ properties "
734 "must be appended with a feature name.\n"
735 "See zpool-features(7).\n"));
736 } else if (current_prop_type == ZFS_TYPE_VDEV) {
737 (void) zprop_iter(print_vdev_prop_cb, fp, B_FALSE,
738 B_TRUE, current_prop_type);
739 }
740 }
741
742 /*
743 * See comments at end of main().
744 */
745 if (getenv("ZFS_ABORT") != NULL) {
746 (void) printf("dumping core by request\n");
747 abort();
748 }
749
750 exit(requested ? 0 : 2);
751 }
752
753 /*
754 * zpool initialize [-c | -s | -u] [-w] <-a | pool> [<vdev> ...]
755 * Initialize all unused blocks in the specified vdevs, or all vdevs in the pool
756 * if none specified.
757 *
758 * -a Use all pools.
759 * -c Cancel. Ends active initializing.
760 * -s Suspend. Initializing can then be restarted with no flags.
761 * -u Uninitialize. Clears initialization state.
762 * -w Wait. Blocks until initializing has completed.
763 */
764 int
zpool_do_initialize(int argc,char ** argv)765 zpool_do_initialize(int argc, char **argv)
766 {
767 int c;
768 char *poolname;
769 zpool_handle_t *zhp;
770 int err = 0;
771 boolean_t wait = B_FALSE;
772 boolean_t initialize_all = B_FALSE;
773
774 struct option long_options[] = {
775 {"cancel", no_argument, NULL, 'c'},
776 {"suspend", no_argument, NULL, 's'},
777 {"uninit", no_argument, NULL, 'u'},
778 {"wait", no_argument, NULL, 'w'},
779 {"all", no_argument, NULL, 'a'},
780 {0, 0, 0, 0}
781 };
782
783 pool_initialize_func_t cmd_type = POOL_INITIALIZE_START;
784 while ((c = getopt_long(argc, argv, "acsuw", long_options,
785 NULL)) != -1) {
786 switch (c) {
787 case 'a':
788 initialize_all = B_TRUE;
789 break;
790 case 'c':
791 if (cmd_type != POOL_INITIALIZE_START &&
792 cmd_type != POOL_INITIALIZE_CANCEL) {
793 (void) fprintf(stderr, gettext("-c cannot be "
794 "combined with other options\n"));
795 usage(B_FALSE);
796 }
797 cmd_type = POOL_INITIALIZE_CANCEL;
798 break;
799 case 's':
800 if (cmd_type != POOL_INITIALIZE_START &&
801 cmd_type != POOL_INITIALIZE_SUSPEND) {
802 (void) fprintf(stderr, gettext("-s cannot be "
803 "combined with other options\n"));
804 usage(B_FALSE);
805 }
806 cmd_type = POOL_INITIALIZE_SUSPEND;
807 break;
808 case 'u':
809 if (cmd_type != POOL_INITIALIZE_START &&
810 cmd_type != POOL_INITIALIZE_UNINIT) {
811 (void) fprintf(stderr, gettext("-u cannot be "
812 "combined with other options\n"));
813 usage(B_FALSE);
814 }
815 cmd_type = POOL_INITIALIZE_UNINIT;
816 break;
817 case 'w':
818 wait = B_TRUE;
819 break;
820 case '?':
821 if (optopt != 0) {
822 (void) fprintf(stderr,
823 gettext("invalid option '%c'\n"), optopt);
824 } else {
825 (void) fprintf(stderr,
826 gettext("invalid option '%s'\n"),
827 argv[optind - 1]);
828 }
829 usage(B_FALSE);
830 }
831 }
832
833 argc -= optind;
834 argv += optind;
835
836 initialize_cbdata_t cbdata = {
837 .wait = wait,
838 .cmd_type = cmd_type
839 };
840
841 if (initialize_all && argc > 0) {
842 (void) fprintf(stderr, gettext("-a cannot be combined with "
843 "individual pools or vdevs\n"));
844 usage(B_FALSE);
845 }
846
847 if (argc < 1 && !initialize_all) {
848 (void) fprintf(stderr, gettext("missing pool name argument\n"));
849 usage(B_FALSE);
850 }
851
852 if (wait && (cmd_type != POOL_INITIALIZE_START)) {
853 (void) fprintf(stderr, gettext("-w cannot be used with -c, -s"
854 "or -u\n"));
855 usage(B_FALSE);
856 }
857
858 if (argc == 0 && initialize_all) {
859 /* Initilize each pool recursively */
860 err = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
861 B_FALSE, zpool_initialize_one, &cbdata);
862 return (err);
863 } else if (argc == 1) {
864 /* no individual leaf vdevs specified, initialize the pool */
865 poolname = argv[0];
866 zhp = zpool_open(g_zfs, poolname);
867 if (zhp == NULL)
868 return (-1);
869 err = zpool_initialize_one(zhp, &cbdata);
870 } else {
871 /* individual leaf vdevs specified, initialize them */
872 poolname = argv[0];
873 zhp = zpool_open(g_zfs, poolname);
874 if (zhp == NULL)
875 return (-1);
876 nvlist_t *vdevs = fnvlist_alloc();
877 for (int i = 1; i < argc; i++) {
878 fnvlist_add_boolean(vdevs, argv[i]);
879 }
880 if (wait)
881 err = zpool_initialize_wait(zhp, cmd_type, vdevs);
882 else
883 err = zpool_initialize(zhp, cmd_type, vdevs);
884 fnvlist_free(vdevs);
885 }
886
887 zpool_close(zhp);
888
889 return (err);
890 }
891
892 /*
893 * print a pool vdev config for dry runs
894 */
895 static void
print_vdev_tree(zpool_handle_t * zhp,const char * name,nvlist_t * nv,int indent,const char * match,int name_flags)896 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
897 const char *match, int name_flags)
898 {
899 nvlist_t **child;
900 uint_t c, children;
901 char *vname;
902 boolean_t printed = B_FALSE;
903
904 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
905 &child, &children) != 0) {
906 if (name != NULL)
907 (void) printf("\t%*s%s\n", indent, "", name);
908 return;
909 }
910
911 for (c = 0; c < children; c++) {
912 uint64_t is_log = B_FALSE, is_hole = B_FALSE;
913 const char *class = "";
914
915 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
916 &is_hole);
917
918 if (is_hole == B_TRUE) {
919 continue;
920 }
921
922 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
923 &is_log);
924 if (is_log)
925 class = VDEV_ALLOC_BIAS_LOG;
926 (void) nvlist_lookup_string(child[c],
927 ZPOOL_CONFIG_ALLOCATION_BIAS, &class);
928 if (strcmp(match, class) != 0)
929 continue;
930
931 if (!printed && name != NULL) {
932 (void) printf("\t%*s%s\n", indent, "", name);
933 printed = B_TRUE;
934 }
935 vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
936 print_vdev_tree(zhp, vname, child[c], indent + 2, "",
937 name_flags);
938 free(vname);
939 }
940 }
941
942 /*
943 * Print the list of l2cache devices for dry runs.
944 */
945 static void
print_cache_list(nvlist_t * nv,int indent)946 print_cache_list(nvlist_t *nv, int indent)
947 {
948 nvlist_t **child;
949 uint_t c, children;
950
951 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
952 &child, &children) == 0 && children > 0) {
953 (void) printf("\t%*s%s\n", indent, "", "cache");
954 } else {
955 return;
956 }
957 for (c = 0; c < children; c++) {
958 char *vname;
959
960 vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
961 (void) printf("\t%*s%s\n", indent + 2, "", vname);
962 free(vname);
963 }
964 }
965
966 /*
967 * Print the list of spares for dry runs.
968 */
969 static void
print_spare_list(nvlist_t * nv,int indent)970 print_spare_list(nvlist_t *nv, int indent)
971 {
972 nvlist_t **child;
973 uint_t c, children;
974
975 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
976 &child, &children) == 0 && children > 0) {
977 (void) printf("\t%*s%s\n", indent, "", "spares");
978 } else {
979 return;
980 }
981 for (c = 0; c < children; c++) {
982 char *vname;
983
984 vname = zpool_vdev_name(g_zfs, NULL, child[c], 0);
985 (void) printf("\t%*s%s\n", indent + 2, "", vname);
986 free(vname);
987 }
988 }
989
990 typedef struct spare_cbdata {
991 uint64_t cb_guid;
992 zpool_handle_t *cb_zhp;
993 } spare_cbdata_t;
994
995 static boolean_t
find_vdev(nvlist_t * nv,uint64_t search)996 find_vdev(nvlist_t *nv, uint64_t search)
997 {
998 uint64_t guid;
999 nvlist_t **child;
1000 uint_t c, children;
1001
1002 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1003 search == guid)
1004 return (B_TRUE);
1005
1006 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1007 &child, &children) == 0) {
1008 for (c = 0; c < children; c++)
1009 if (find_vdev(child[c], search))
1010 return (B_TRUE);
1011 }
1012
1013 return (B_FALSE);
1014 }
1015
1016 static int
find_spare(zpool_handle_t * zhp,void * data)1017 find_spare(zpool_handle_t *zhp, void *data)
1018 {
1019 spare_cbdata_t *cbp = data;
1020 nvlist_t *config, *nvroot;
1021
1022 config = zpool_get_config(zhp, NULL);
1023 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1024 &nvroot) == 0);
1025
1026 if (find_vdev(nvroot, cbp->cb_guid)) {
1027 cbp->cb_zhp = zhp;
1028 return (1);
1029 }
1030
1031 zpool_close(zhp);
1032 return (0);
1033 }
1034
1035 static void
nice_num_str_nvlist(nvlist_t * item,const char * key,uint64_t value,boolean_t literal,boolean_t as_int,int format)1036 nice_num_str_nvlist(nvlist_t *item, const char *key, uint64_t value,
1037 boolean_t literal, boolean_t as_int, int format)
1038 {
1039 char buf[256];
1040
1041 if (literal) {
1042 if (!as_int)
1043 (void) snprintf(buf, 256, "%llu", (u_longlong_t)value);
1044 } else {
1045 switch (format) {
1046 case ZFS_NICENUM_1024:
1047 zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_1024);
1048 break;
1049 case ZFS_NICENUM_BYTES:
1050 zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_BYTES);
1051 break;
1052 case ZFS_NICENUM_TIME:
1053 zfs_nicenum_format(value, buf, 256, ZFS_NICENUM_TIME);
1054 break;
1055 case ZFS_NICE_TIMESTAMP:
1056 format_timestamp(value, buf, 256);
1057 break;
1058 default:
1059 fprintf(stderr, "Invalid number format");
1060 exit(1);
1061 }
1062 }
1063 if (as_int)
1064 fnvlist_add_uint64(item, key, value);
1065 else
1066 fnvlist_add_string(item, key, buf);
1067 }
1068
1069 /*
1070 * Generates an nvlist with output version for every command based on params.
1071 * Purpose of this is to add a version of JSON output, considering the schema
1072 * format might be updated for each command in future.
1073 *
1074 * Schema:
1075 *
1076 * "output_version": {
1077 * "command": string,
1078 * "vers_major": integer,
1079 * "vers_minor": integer,
1080 * }
1081 */
1082 static nvlist_t *
zpool_json_schema(int maj_v,int min_v)1083 zpool_json_schema(int maj_v, int min_v)
1084 {
1085 char cmd[MAX_CMD_LEN];
1086 nvlist_t *sch = fnvlist_alloc();
1087 nvlist_t *ov = fnvlist_alloc();
1088
1089 (void) snprintf(cmd, MAX_CMD_LEN, "zpool %s", current_command->name);
1090 fnvlist_add_string(ov, "command", cmd);
1091 fnvlist_add_uint32(ov, "vers_major", maj_v);
1092 fnvlist_add_uint32(ov, "vers_minor", min_v);
1093 fnvlist_add_nvlist(sch, "output_version", ov);
1094 fnvlist_free(ov);
1095 return (sch);
1096 }
1097
1098 static void
fill_pool_info(nvlist_t * list,zpool_handle_t * zhp,boolean_t addtype,boolean_t as_int)1099 fill_pool_info(nvlist_t *list, zpool_handle_t *zhp, boolean_t addtype,
1100 boolean_t as_int)
1101 {
1102 nvlist_t *config = zpool_get_config(zhp, NULL);
1103 uint64_t guid = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID);
1104 uint64_t txg = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG);
1105
1106 fnvlist_add_string(list, "name", zpool_get_name(zhp));
1107 if (addtype)
1108 fnvlist_add_string(list, "type", "POOL");
1109 fnvlist_add_string(list, "state", zpool_get_state_str(zhp));
1110 if (as_int) {
1111 if (guid)
1112 fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_GUID, guid);
1113 if (txg)
1114 fnvlist_add_uint64(list, ZPOOL_CONFIG_POOL_TXG, txg);
1115 fnvlist_add_uint64(list, "spa_version", SPA_VERSION);
1116 fnvlist_add_uint64(list, "zpl_version", ZPL_VERSION);
1117 } else {
1118 char value[ZFS_MAXPROPLEN];
1119 if (guid) {
1120 (void) snprintf(value, ZFS_MAXPROPLEN, "%llu",
1121 (u_longlong_t)guid);
1122 fnvlist_add_string(list, ZPOOL_CONFIG_POOL_GUID, value);
1123 }
1124 if (txg) {
1125 (void) snprintf(value, ZFS_MAXPROPLEN, "%llu",
1126 (u_longlong_t)txg);
1127 fnvlist_add_string(list, ZPOOL_CONFIG_POOL_TXG, value);
1128 }
1129 fnvlist_add_string(list, "spa_version", SPA_VERSION_STRING);
1130 fnvlist_add_string(list, "zpl_version", ZPL_VERSION_STRING);
1131 }
1132 }
1133
1134 static void
used_by_other(zpool_handle_t * zhp,nvlist_t * nvdev,nvlist_t * list)1135 used_by_other(zpool_handle_t *zhp, nvlist_t *nvdev, nvlist_t *list)
1136 {
1137 spare_cbdata_t spare_cb;
1138 verify(nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID,
1139 &spare_cb.cb_guid) == 0);
1140 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1141 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
1142 zpool_get_name(zhp)) != 0) {
1143 fnvlist_add_string(list, "used_by",
1144 zpool_get_name(spare_cb.cb_zhp));
1145 }
1146 zpool_close(spare_cb.cb_zhp);
1147 }
1148 }
1149
1150 static void
fill_vdev_info(nvlist_t * list,zpool_handle_t * zhp,char * name,boolean_t addtype,boolean_t as_int)1151 fill_vdev_info(nvlist_t *list, zpool_handle_t *zhp, char *name,
1152 boolean_t addtype, boolean_t as_int)
1153 {
1154 boolean_t l2c = B_FALSE;
1155 const char *path, *phys, *devid, *bias = NULL;
1156 uint64_t hole = 0, log = 0, spare = 0;
1157 vdev_stat_t *vs;
1158 uint_t c;
1159 nvlist_t *nvdev;
1160 nvlist_t *nvdev_parent = NULL;
1161 char *_name;
1162
1163 if (strcmp(name, zpool_get_name(zhp)) != 0)
1164 _name = name;
1165 else
1166 _name = (char *)"root-0";
1167
1168 nvdev = zpool_find_vdev(zhp, _name, NULL, &l2c, NULL);
1169
1170 fnvlist_add_string(list, "name", name);
1171 if (addtype)
1172 fnvlist_add_string(list, "type", "VDEV");
1173 if (nvdev) {
1174 const char *type = fnvlist_lookup_string(nvdev,
1175 ZPOOL_CONFIG_TYPE);
1176 if (type)
1177 fnvlist_add_string(list, "vdev_type", type);
1178 uint64_t guid = fnvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_GUID);
1179 if (guid) {
1180 if (as_int) {
1181 fnvlist_add_uint64(list, "guid", guid);
1182 } else {
1183 char buf[ZFS_MAXPROPLEN];
1184 (void) snprintf(buf, ZFS_MAXPROPLEN, "%llu",
1185 (u_longlong_t)guid);
1186 fnvlist_add_string(list, "guid", buf);
1187 }
1188 }
1189 if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PATH, &path) == 0)
1190 fnvlist_add_string(list, "path", path);
1191 if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_PHYS_PATH,
1192 &phys) == 0)
1193 fnvlist_add_string(list, "phys_path", phys);
1194 if (nvlist_lookup_string(nvdev, ZPOOL_CONFIG_DEVID,
1195 &devid) == 0)
1196 fnvlist_add_string(list, "devid", devid);
1197 (void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_LOG, &log);
1198 (void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_SPARE,
1199 &spare);
1200 (void) nvlist_lookup_uint64(nvdev, ZPOOL_CONFIG_IS_HOLE, &hole);
1201 if (hole)
1202 fnvlist_add_string(list, "class", VDEV_TYPE_HOLE);
1203 else if (l2c)
1204 fnvlist_add_string(list, "class", VDEV_TYPE_L2CACHE);
1205 else if (spare)
1206 fnvlist_add_string(list, "class", VDEV_TYPE_SPARE);
1207 else if (log)
1208 fnvlist_add_string(list, "class", VDEV_TYPE_LOG);
1209 else {
1210 (void) nvlist_lookup_string(nvdev,
1211 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
1212 if (bias != NULL)
1213 fnvlist_add_string(list, "class", bias);
1214 else {
1215 nvdev_parent = NULL;
1216 nvdev_parent = zpool_find_parent_vdev(zhp,
1217 _name, NULL, NULL, NULL);
1218
1219 /*
1220 * With a mirrored special device, the parent
1221 * "mirror" vdev will have
1222 * ZPOOL_CONFIG_ALLOCATION_BIAS set to "special"
1223 * not the leaf vdevs. If we're a leaf vdev
1224 * in that case we need to look at our parent
1225 * to see if they're "special" to know if we
1226 * are "special" too.
1227 */
1228 if (nvdev_parent) {
1229 (void) nvlist_lookup_string(
1230 nvdev_parent,
1231 ZPOOL_CONFIG_ALLOCATION_BIAS,
1232 &bias);
1233 }
1234 if (bias != NULL)
1235 fnvlist_add_string(list, "class", bias);
1236 else
1237 fnvlist_add_string(list, "class",
1238 "normal");
1239 }
1240 }
1241 if (nvlist_lookup_uint64_array(nvdev, ZPOOL_CONFIG_VDEV_STATS,
1242 (uint64_t **)&vs, &c) == 0) {
1243 fnvlist_add_string(list, "state",
1244 vdev_state_str[vs->vs_state]);
1245 }
1246 }
1247 }
1248
1249 static boolean_t
prop_list_contains_feature(nvlist_t * proplist)1250 prop_list_contains_feature(nvlist_t *proplist)
1251 {
1252 nvpair_t *nvp;
1253 for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
1254 nvp = nvlist_next_nvpair(proplist, nvp)) {
1255 if (zpool_prop_feature(nvpair_name(nvp)))
1256 return (B_TRUE);
1257 }
1258 return (B_FALSE);
1259 }
1260
1261 /*
1262 * Add a property pair (name, string-value) into a property nvlist.
1263 */
1264 static int
add_prop_list(const char * propname,const char * propval,nvlist_t ** props,boolean_t poolprop)1265 add_prop_list(const char *propname, const char *propval, nvlist_t **props,
1266 boolean_t poolprop)
1267 {
1268 zpool_prop_t prop = ZPOOL_PROP_INVAL;
1269 nvlist_t *proplist;
1270 const char *normnm;
1271 const char *strval;
1272
1273 if (*props == NULL &&
1274 nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
1275 (void) fprintf(stderr,
1276 gettext("internal error: out of memory\n"));
1277 return (1);
1278 }
1279
1280 proplist = *props;
1281
1282 if (poolprop) {
1283 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
1284 const char *cname =
1285 zpool_prop_to_name(ZPOOL_PROP_COMPATIBILITY);
1286
1287 if ((prop = zpool_name_to_prop(propname)) == ZPOOL_PROP_INVAL &&
1288 (!zpool_prop_feature(propname) &&
1289 !zpool_prop_vdev(propname))) {
1290 (void) fprintf(stderr, gettext("property '%s' is "
1291 "not a valid pool or vdev property\n"), propname);
1292 return (2);
1293 }
1294
1295 /*
1296 * feature@ properties and version should not be specified
1297 * at the same time.
1298 */
1299 if ((prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname) &&
1300 nvlist_exists(proplist, vname)) ||
1301 (prop == ZPOOL_PROP_VERSION &&
1302 prop_list_contains_feature(proplist))) {
1303 (void) fprintf(stderr, gettext("'feature@' and "
1304 "'version' properties cannot be specified "
1305 "together\n"));
1306 return (2);
1307 }
1308
1309 /*
1310 * if version is specified, only "legacy" compatibility
1311 * may be requested
1312 */
1313 if ((prop == ZPOOL_PROP_COMPATIBILITY &&
1314 strcmp(propval, ZPOOL_COMPAT_LEGACY) != 0 &&
1315 nvlist_exists(proplist, vname)) ||
1316 (prop == ZPOOL_PROP_VERSION &&
1317 nvlist_exists(proplist, cname) &&
1318 strcmp(fnvlist_lookup_string(proplist, cname),
1319 ZPOOL_COMPAT_LEGACY) != 0)) {
1320 (void) fprintf(stderr, gettext("when 'version' is "
1321 "specified, the 'compatibility' feature may only "
1322 "be set to '" ZPOOL_COMPAT_LEGACY "'\n"));
1323 return (2);
1324 }
1325
1326 if (zpool_prop_feature(propname) || zpool_prop_vdev(propname))
1327 normnm = propname;
1328 else
1329 normnm = zpool_prop_to_name(prop);
1330 } else {
1331 zfs_prop_t fsprop = zfs_name_to_prop(propname);
1332
1333 if (zfs_prop_valid_for_type(fsprop, ZFS_TYPE_FILESYSTEM,
1334 B_FALSE)) {
1335 normnm = zfs_prop_to_name(fsprop);
1336 } else if (zfs_prop_user(propname) ||
1337 zfs_prop_userquota(propname)) {
1338 normnm = propname;
1339 } else {
1340 (void) fprintf(stderr, gettext("property '%s' is "
1341 "not a valid filesystem property\n"), propname);
1342 return (2);
1343 }
1344 }
1345
1346 if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
1347 prop != ZPOOL_PROP_CACHEFILE) {
1348 (void) fprintf(stderr, gettext("property '%s' "
1349 "specified multiple times\n"), propname);
1350 return (2);
1351 }
1352
1353 if (nvlist_add_string(proplist, normnm, propval) != 0) {
1354 (void) fprintf(stderr, gettext("internal "
1355 "error: out of memory\n"));
1356 return (1);
1357 }
1358
1359 return (0);
1360 }
1361
1362 /*
1363 * Set a default property pair (name, string-value) in a property nvlist
1364 */
1365 static int
add_prop_list_default(const char * propname,const char * propval,nvlist_t ** props)1366 add_prop_list_default(const char *propname, const char *propval,
1367 nvlist_t **props)
1368 {
1369 const char *pval;
1370
1371 if (nvlist_lookup_string(*props, propname, &pval) == 0)
1372 return (0);
1373
1374 return (add_prop_list(propname, propval, props, B_TRUE));
1375 }
1376
1377 /*
1378 * zpool add [-afgLnP] [-o property=value] <pool> <vdev> ...
1379 *
1380 * -a Disable the ashift validation checks
1381 * -f Force addition of devices, even if they appear in use
1382 * -g Display guid for individual vdev name.
1383 * -L Follow links when resolving vdev path name.
1384 * -n Do not add the devices, but display the resulting layout if
1385 * they were to be added.
1386 * -o Set property=value.
1387 * -P Display full path for vdev name.
1388 *
1389 * Adds the given vdevs to 'pool'. As with create, the bulk of this work is
1390 * handled by make_root_vdev(), which constructs the nvlist needed to pass to
1391 * libzfs.
1392 */
1393 int
zpool_do_add(int argc,char ** argv)1394 zpool_do_add(int argc, char **argv)
1395 {
1396 boolean_t check_replication = B_TRUE;
1397 boolean_t check_inuse = B_TRUE;
1398 boolean_t dryrun = B_FALSE;
1399 boolean_t check_ashift = B_TRUE;
1400 boolean_t force = B_FALSE;
1401 int name_flags = 0;
1402 int c;
1403 nvlist_t *nvroot;
1404 char *poolname;
1405 int ret;
1406 zpool_handle_t *zhp;
1407 nvlist_t *config;
1408 nvlist_t *props = NULL;
1409 char *propval;
1410
1411 struct option long_options[] = {
1412 {"allow-in-use", no_argument, NULL, ZPOOL_OPTION_ALLOW_INUSE},
1413 {"allow-replication-mismatch", no_argument, NULL,
1414 ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH},
1415 {"allow-ashift-mismatch", no_argument, NULL,
1416 ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH},
1417 {0, 0, 0, 0}
1418 };
1419
1420 /* check options */
1421 while ((c = getopt_long(argc, argv, "fgLno:P", long_options, NULL))
1422 != -1) {
1423 switch (c) {
1424 case 'f':
1425 force = B_TRUE;
1426 break;
1427 case 'g':
1428 name_flags |= VDEV_NAME_GUID;
1429 break;
1430 case 'L':
1431 name_flags |= VDEV_NAME_FOLLOW_LINKS;
1432 break;
1433 case 'n':
1434 dryrun = B_TRUE;
1435 break;
1436 case 'o':
1437 if ((propval = strchr(optarg, '=')) == NULL) {
1438 (void) fprintf(stderr, gettext("missing "
1439 "'=' for -o option\n"));
1440 usage(B_FALSE);
1441 }
1442 *propval = '\0';
1443 propval++;
1444
1445 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
1446 (add_prop_list(optarg, propval, &props, B_TRUE)))
1447 usage(B_FALSE);
1448 break;
1449 case 'P':
1450 name_flags |= VDEV_NAME_PATH;
1451 break;
1452 case ZPOOL_OPTION_ALLOW_INUSE:
1453 check_inuse = B_FALSE;
1454 break;
1455 case ZPOOL_OPTION_ALLOW_REPLICATION_MISMATCH:
1456 check_replication = B_FALSE;
1457 break;
1458 case ZPOOL_OPTION_ALLOW_ASHIFT_MISMATCH:
1459 check_ashift = B_FALSE;
1460 break;
1461 case '?':
1462 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1463 optopt);
1464 usage(B_FALSE);
1465 }
1466 }
1467
1468 argc -= optind;
1469 argv += optind;
1470
1471 /* get pool name and check number of arguments */
1472 if (argc < 1) {
1473 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1474 usage(B_FALSE);
1475 }
1476 if (argc < 2) {
1477 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1478 usage(B_FALSE);
1479 }
1480
1481 if (force) {
1482 if (!check_inuse || !check_replication || !check_ashift) {
1483 (void) fprintf(stderr, gettext("'-f' option is not "
1484 "allowed with '--allow-replication-mismatch', "
1485 "'--allow-ashift-mismatch', or "
1486 "'--allow-in-use'\n"));
1487 usage(B_FALSE);
1488 }
1489 check_inuse = B_FALSE;
1490 check_replication = B_FALSE;
1491 check_ashift = B_FALSE;
1492 }
1493
1494 poolname = argv[0];
1495
1496 argc--;
1497 argv++;
1498
1499 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1500 return (1);
1501
1502 if ((config = zpool_get_config(zhp, NULL)) == NULL) {
1503 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
1504 poolname);
1505 zpool_close(zhp);
1506 return (1);
1507 }
1508
1509 /* unless manually specified use "ashift" pool property (if set) */
1510 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
1511 int intval;
1512 zprop_source_t src;
1513 char strval[ZPOOL_MAXPROPLEN];
1514
1515 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
1516 if (src != ZPROP_SRC_DEFAULT) {
1517 (void) sprintf(strval, "%" PRId32, intval);
1518 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
1519 &props, B_TRUE) == 0);
1520 }
1521 }
1522
1523 /* pass off to make_root_vdev for processing */
1524 nvroot = make_root_vdev(zhp, props, !check_inuse,
1525 check_replication, B_FALSE, dryrun, argc, argv);
1526 if (nvroot == NULL) {
1527 zpool_close(zhp);
1528 return (1);
1529 }
1530
1531 if (dryrun) {
1532 nvlist_t *poolnvroot;
1533 nvlist_t **l2child, **sparechild;
1534 uint_t l2children, sparechildren, c;
1535 char *vname;
1536 boolean_t hadcache = B_FALSE, hadspare = B_FALSE;
1537
1538 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1539 &poolnvroot) == 0);
1540
1541 (void) printf(gettext("would update '%s' to the following "
1542 "configuration:\n\n"), zpool_get_name(zhp));
1543
1544 /* print original main pool and new tree */
1545 print_vdev_tree(zhp, poolname, poolnvroot, 0, "",
1546 name_flags | VDEV_NAME_TYPE_ID);
1547 print_vdev_tree(zhp, NULL, nvroot, 0, "", name_flags);
1548
1549 /* print other classes: 'dedup', 'special', and 'log' */
1550 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1551 print_vdev_tree(zhp, "dedup", poolnvroot, 0,
1552 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1553 print_vdev_tree(zhp, NULL, nvroot, 0,
1554 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1555 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_DEDUP)) {
1556 print_vdev_tree(zhp, "dedup", nvroot, 0,
1557 VDEV_ALLOC_BIAS_DEDUP, name_flags);
1558 }
1559
1560 if (zfs_special_devs(poolnvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1561 print_vdev_tree(zhp, "special", poolnvroot, 0,
1562 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1563 print_vdev_tree(zhp, NULL, nvroot, 0,
1564 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1565 } else if (zfs_special_devs(nvroot, VDEV_ALLOC_BIAS_SPECIAL)) {
1566 print_vdev_tree(zhp, "special", nvroot, 0,
1567 VDEV_ALLOC_BIAS_SPECIAL, name_flags);
1568 }
1569
1570 if (num_logs(poolnvroot) > 0) {
1571 print_vdev_tree(zhp, "logs", poolnvroot, 0,
1572 VDEV_ALLOC_BIAS_LOG, name_flags);
1573 print_vdev_tree(zhp, NULL, nvroot, 0,
1574 VDEV_ALLOC_BIAS_LOG, name_flags);
1575 } else if (num_logs(nvroot) > 0) {
1576 print_vdev_tree(zhp, "logs", nvroot, 0,
1577 VDEV_ALLOC_BIAS_LOG, name_flags);
1578 }
1579
1580 /* Do the same for the caches */
1581 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
1582 &l2child, &l2children) == 0 && l2children) {
1583 hadcache = B_TRUE;
1584 (void) printf(gettext("\tcache\n"));
1585 for (c = 0; c < l2children; c++) {
1586 vname = zpool_vdev_name(g_zfs, NULL,
1587 l2child[c], name_flags);
1588 (void) printf("\t %s\n", vname);
1589 free(vname);
1590 }
1591 }
1592 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1593 &l2child, &l2children) == 0 && l2children) {
1594 if (!hadcache)
1595 (void) printf(gettext("\tcache\n"));
1596 for (c = 0; c < l2children; c++) {
1597 vname = zpool_vdev_name(g_zfs, NULL,
1598 l2child[c], name_flags);
1599 (void) printf("\t %s\n", vname);
1600 free(vname);
1601 }
1602 }
1603 /* And finally the spares */
1604 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_SPARES,
1605 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1606 hadspare = B_TRUE;
1607 (void) printf(gettext("\tspares\n"));
1608 for (c = 0; c < sparechildren; c++) {
1609 vname = zpool_vdev_name(g_zfs, NULL,
1610 sparechild[c], name_flags);
1611 (void) printf("\t %s\n", vname);
1612 free(vname);
1613 }
1614 }
1615 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1616 &sparechild, &sparechildren) == 0 && sparechildren > 0) {
1617 if (!hadspare)
1618 (void) printf(gettext("\tspares\n"));
1619 for (c = 0; c < sparechildren; c++) {
1620 vname = zpool_vdev_name(g_zfs, NULL,
1621 sparechild[c], name_flags);
1622 (void) printf("\t %s\n", vname);
1623 free(vname);
1624 }
1625 }
1626
1627 ret = 0;
1628 } else {
1629 ret = (zpool_add(zhp, nvroot, check_ashift) != 0);
1630 }
1631
1632 nvlist_free(props);
1633 nvlist_free(nvroot);
1634 zpool_close(zhp);
1635
1636 return (ret);
1637 }
1638
1639 /*
1640 * zpool remove [-npsw] <pool> <vdev> ...
1641 *
1642 * Removes the given vdev from the pool.
1643 */
1644 int
zpool_do_remove(int argc,char ** argv)1645 zpool_do_remove(int argc, char **argv)
1646 {
1647 char *poolname;
1648 int i, ret = 0;
1649 zpool_handle_t *zhp = NULL;
1650 boolean_t stop = B_FALSE;
1651 int c;
1652 boolean_t noop = B_FALSE;
1653 boolean_t parsable = B_FALSE;
1654 boolean_t wait = B_FALSE;
1655
1656 /* check options */
1657 while ((c = getopt(argc, argv, "npsw")) != -1) {
1658 switch (c) {
1659 case 'n':
1660 noop = B_TRUE;
1661 break;
1662 case 'p':
1663 parsable = B_TRUE;
1664 break;
1665 case 's':
1666 stop = B_TRUE;
1667 break;
1668 case 'w':
1669 wait = B_TRUE;
1670 break;
1671 case '?':
1672 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1673 optopt);
1674 usage(B_FALSE);
1675 }
1676 }
1677
1678 argc -= optind;
1679 argv += optind;
1680
1681 /* get pool name and check number of arguments */
1682 if (argc < 1) {
1683 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1684 usage(B_FALSE);
1685 }
1686
1687 poolname = argv[0];
1688
1689 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
1690 return (1);
1691
1692 if (stop && noop) {
1693 zpool_close(zhp);
1694 (void) fprintf(stderr, gettext("stop request ignored\n"));
1695 return (0);
1696 }
1697
1698 if (stop) {
1699 if (argc > 1) {
1700 (void) fprintf(stderr, gettext("too many arguments\n"));
1701 usage(B_FALSE);
1702 }
1703 if (zpool_vdev_remove_cancel(zhp) != 0)
1704 ret = 1;
1705 if (wait) {
1706 (void) fprintf(stderr, gettext("invalid option "
1707 "combination: -w cannot be used with -s\n"));
1708 usage(B_FALSE);
1709 }
1710 } else {
1711 if (argc < 2) {
1712 (void) fprintf(stderr, gettext("missing device\n"));
1713 usage(B_FALSE);
1714 }
1715
1716 for (i = 1; i < argc; i++) {
1717 if (noop) {
1718 uint64_t size;
1719
1720 if (zpool_vdev_indirect_size(zhp, argv[i],
1721 &size) != 0) {
1722 ret = 1;
1723 break;
1724 }
1725 if (parsable) {
1726 (void) printf("%s %llu\n",
1727 argv[i], (unsigned long long)size);
1728 } else {
1729 char valstr[32];
1730 zfs_nicenum(size, valstr,
1731 sizeof (valstr));
1732 (void) printf("Memory that will be "
1733 "used after removing %s: %s\n",
1734 argv[i], valstr);
1735 }
1736 } else {
1737 if (zpool_vdev_remove(zhp, argv[i]) != 0)
1738 ret = 1;
1739 }
1740 }
1741
1742 if (ret == 0 && wait)
1743 ret = zpool_wait(zhp, ZPOOL_WAIT_REMOVE);
1744 }
1745 zpool_close(zhp);
1746
1747 return (ret);
1748 }
1749
1750 /*
1751 * Return 1 if a vdev is active (being used in a pool)
1752 * Return 0 if a vdev is inactive (offlined or faulted, or not in active pool)
1753 *
1754 * This is useful for checking if a disk in an active pool is offlined or
1755 * faulted.
1756 */
1757 static int
vdev_is_active(char * vdev_path)1758 vdev_is_active(char *vdev_path)
1759 {
1760 int fd;
1761 fd = open(vdev_path, O_EXCL);
1762 if (fd < 0) {
1763 return (1); /* cant open O_EXCL - disk is active */
1764 }
1765
1766 (void) close(fd);
1767 return (0); /* disk is inactive in the pool */
1768 }
1769
1770 /*
1771 * zpool labelclear [-f] <vdev>
1772 *
1773 * -f Force clearing the label for the vdevs which are members of
1774 * the exported or foreign pools.
1775 *
1776 * Verifies that the vdev is not active and zeros out the label information
1777 * on the device.
1778 */
1779 int
zpool_do_labelclear(int argc,char ** argv)1780 zpool_do_labelclear(int argc, char **argv)
1781 {
1782 char vdev[MAXPATHLEN];
1783 char *name = NULL;
1784 int c, fd, ret = 0;
1785 nvlist_t *config;
1786 pool_state_t state;
1787 boolean_t inuse = B_FALSE;
1788 boolean_t force = B_FALSE;
1789
1790 /* check options */
1791 while ((c = getopt(argc, argv, "f")) != -1) {
1792 switch (c) {
1793 case 'f':
1794 force = B_TRUE;
1795 break;
1796 default:
1797 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1798 optopt);
1799 usage(B_FALSE);
1800 }
1801 }
1802
1803 argc -= optind;
1804 argv += optind;
1805
1806 /* get vdev name */
1807 if (argc < 1) {
1808 (void) fprintf(stderr, gettext("missing vdev name\n"));
1809 usage(B_FALSE);
1810 }
1811 if (argc > 1) {
1812 (void) fprintf(stderr, gettext("too many arguments\n"));
1813 usage(B_FALSE);
1814 }
1815
1816 (void) strlcpy(vdev, argv[0], sizeof (vdev));
1817
1818 /*
1819 * If we cannot open an absolute path, we quit.
1820 * Otherwise if the provided vdev name doesn't point to a file,
1821 * try prepending expected disk paths and partition numbers.
1822 */
1823 if ((fd = open(vdev, O_RDWR)) < 0) {
1824 int error;
1825 if (vdev[0] == '/') {
1826 (void) fprintf(stderr, gettext("failed to open "
1827 "%s: %s\n"), vdev, strerror(errno));
1828 return (1);
1829 }
1830
1831 error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
1832 if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
1833 if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
1834 error = ENOENT;
1835 }
1836
1837 if (error || ((fd = open(vdev, O_RDWR)) < 0)) {
1838 if (errno == ENOENT) {
1839 (void) fprintf(stderr, gettext(
1840 "failed to find device %s, try "
1841 "specifying absolute path instead\n"),
1842 argv[0]);
1843 return (1);
1844 }
1845
1846 (void) fprintf(stderr, gettext("failed to open %s:"
1847 " %s\n"), vdev, strerror(errno));
1848 return (1);
1849 }
1850 }
1851
1852 /*
1853 * Flush all dirty pages for the block device. This should not be
1854 * fatal when the device does not support BLKFLSBUF as would be the
1855 * case for a file vdev.
1856 */
1857 if ((zfs_dev_flush(fd) != 0) && (errno != ENOTTY))
1858 (void) fprintf(stderr, gettext("failed to invalidate "
1859 "cache for %s: %s\n"), vdev, strerror(errno));
1860
1861 if (zpool_read_label(fd, &config, NULL) != 0) {
1862 (void) fprintf(stderr,
1863 gettext("failed to read label from %s\n"), vdev);
1864 ret = 1;
1865 goto errout;
1866 }
1867 nvlist_free(config);
1868
1869 ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
1870 if (ret != 0) {
1871 (void) fprintf(stderr,
1872 gettext("failed to check state for %s\n"), vdev);
1873 ret = 1;
1874 goto errout;
1875 }
1876
1877 if (!inuse)
1878 goto wipe_label;
1879
1880 switch (state) {
1881 default:
1882 case POOL_STATE_ACTIVE:
1883 case POOL_STATE_SPARE:
1884 case POOL_STATE_L2CACHE:
1885 /*
1886 * We allow the user to call 'zpool offline -f'
1887 * on an offlined disk in an active pool. We can check if
1888 * the disk is online by calling vdev_is_active().
1889 */
1890 if (force && !vdev_is_active(vdev))
1891 break;
1892
1893 (void) fprintf(stderr, gettext(
1894 "%s is a member (%s) of pool \"%s\""),
1895 vdev, zpool_pool_state_to_name(state), name);
1896
1897 if (force) {
1898 (void) fprintf(stderr, gettext(
1899 ". Offline the disk first to clear its label."));
1900 }
1901 printf("\n");
1902 ret = 1;
1903 goto errout;
1904
1905 case POOL_STATE_EXPORTED:
1906 if (force)
1907 break;
1908 (void) fprintf(stderr, gettext(
1909 "use '-f' to override the following error:\n"
1910 "%s is a member of exported pool \"%s\"\n"),
1911 vdev, name);
1912 ret = 1;
1913 goto errout;
1914
1915 case POOL_STATE_POTENTIALLY_ACTIVE:
1916 if (force)
1917 break;
1918 (void) fprintf(stderr, gettext(
1919 "use '-f' to override the following error:\n"
1920 "%s is a member of potentially active pool \"%s\"\n"),
1921 vdev, name);
1922 ret = 1;
1923 goto errout;
1924
1925 case POOL_STATE_DESTROYED:
1926 /* inuse should never be set for a destroyed pool */
1927 assert(0);
1928 break;
1929 }
1930
1931 wipe_label:
1932 ret = zpool_clear_label(fd);
1933 if (ret != 0) {
1934 (void) fprintf(stderr,
1935 gettext("failed to clear label for %s\n"), vdev);
1936 }
1937
1938 errout:
1939 free(name);
1940 (void) close(fd);
1941
1942 return (ret);
1943 }
1944
1945 /*
1946 * zpool create [-fnd] [-o property=value] ...
1947 * [-O file-system-property=value] ...
1948 * [-R root] [-m mountpoint] <pool> <dev> ...
1949 *
1950 * -f Force creation, even if devices appear in use
1951 * -n Do not create the pool, but display the resulting layout if it
1952 * were to be created.
1953 * -R Create a pool under an alternate root
1954 * -m Set default mountpoint for the root dataset. By default it's
1955 * '/<pool>'
1956 * -o Set property=value.
1957 * -o Set feature@feature=enabled|disabled.
1958 * -d Don't automatically enable all supported pool features
1959 * (individual features can be enabled with -o).
1960 * -O Set fsproperty=value in the pool's root file system
1961 *
1962 * Creates the named pool according to the given vdev specification. The
1963 * bulk of the vdev processing is done in make_root_vdev() in zpool_vdev.c.
1964 * Once we get the nvlist back from make_root_vdev(), we either print out the
1965 * contents (if '-n' was specified), or pass it to libzfs to do the creation.
1966 */
1967 int
zpool_do_create(int argc,char ** argv)1968 zpool_do_create(int argc, char **argv)
1969 {
1970 boolean_t force = B_FALSE;
1971 boolean_t dryrun = B_FALSE;
1972 boolean_t enable_pool_features = B_TRUE;
1973
1974 int c;
1975 nvlist_t *nvroot = NULL;
1976 char *poolname;
1977 char *tname = NULL;
1978 int ret = 1;
1979 char *altroot = NULL;
1980 char *compat = NULL;
1981 char *mountpoint = NULL;
1982 nvlist_t *fsprops = NULL;
1983 nvlist_t *props = NULL;
1984 char *propval;
1985
1986 /* check options */
1987 while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
1988 switch (c) {
1989 case 'f':
1990 force = B_TRUE;
1991 break;
1992 case 'n':
1993 dryrun = B_TRUE;
1994 break;
1995 case 'd':
1996 enable_pool_features = B_FALSE;
1997 break;
1998 case 'R':
1999 altroot = optarg;
2000 if (add_prop_list(zpool_prop_to_name(
2001 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
2002 goto errout;
2003 if (add_prop_list_default(zpool_prop_to_name(
2004 ZPOOL_PROP_CACHEFILE), "none", &props))
2005 goto errout;
2006 break;
2007 case 'm':
2008 /* Equivalent to -O mountpoint=optarg */
2009 mountpoint = optarg;
2010 break;
2011 case 'o':
2012 if ((propval = strchr(optarg, '=')) == NULL) {
2013 (void) fprintf(stderr, gettext("missing "
2014 "'=' for -o option\n"));
2015 goto errout;
2016 }
2017 *propval = '\0';
2018 propval++;
2019
2020 if (add_prop_list(optarg, propval, &props, B_TRUE))
2021 goto errout;
2022
2023 /*
2024 * If the user is creating a pool that doesn't support
2025 * feature flags, don't enable any features.
2026 */
2027 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
2028 char *end;
2029 u_longlong_t ver;
2030
2031 ver = strtoull(propval, &end, 0);
2032 if (*end == '\0' &&
2033 ver < SPA_VERSION_FEATURES) {
2034 enable_pool_features = B_FALSE;
2035 }
2036 }
2037 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
2038 altroot = propval;
2039 if (zpool_name_to_prop(optarg) ==
2040 ZPOOL_PROP_COMPATIBILITY)
2041 compat = propval;
2042 break;
2043 case 'O':
2044 if ((propval = strchr(optarg, '=')) == NULL) {
2045 (void) fprintf(stderr, gettext("missing "
2046 "'=' for -O option\n"));
2047 goto errout;
2048 }
2049 *propval = '\0';
2050 propval++;
2051
2052 /*
2053 * Mountpoints are checked and then added later.
2054 * Uniquely among properties, they can be specified
2055 * more than once, to avoid conflict with -m.
2056 */
2057 if (0 == strcmp(optarg,
2058 zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
2059 mountpoint = propval;
2060 } else if (add_prop_list(optarg, propval, &fsprops,
2061 B_FALSE)) {
2062 goto errout;
2063 }
2064 break;
2065 case 't':
2066 /*
2067 * Sanity check temporary pool name.
2068 */
2069 if (strchr(optarg, '/') != NULL) {
2070 (void) fprintf(stderr, gettext("cannot create "
2071 "'%s': invalid character '/' in temporary "
2072 "name\n"), optarg);
2073 (void) fprintf(stderr, gettext("use 'zfs "
2074 "create' to create a dataset\n"));
2075 goto errout;
2076 }
2077
2078 if (add_prop_list(zpool_prop_to_name(
2079 ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
2080 goto errout;
2081 if (add_prop_list_default(zpool_prop_to_name(
2082 ZPOOL_PROP_CACHEFILE), "none", &props))
2083 goto errout;
2084 tname = optarg;
2085 break;
2086 case ':':
2087 (void) fprintf(stderr, gettext("missing argument for "
2088 "'%c' option\n"), optopt);
2089 goto badusage;
2090 case '?':
2091 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2092 optopt);
2093 goto badusage;
2094 }
2095 }
2096
2097 argc -= optind;
2098 argv += optind;
2099
2100 /* get pool name and check number of arguments */
2101 if (argc < 1) {
2102 (void) fprintf(stderr, gettext("missing pool name argument\n"));
2103 goto badusage;
2104 }
2105 if (argc < 2) {
2106 (void) fprintf(stderr, gettext("missing vdev specification\n"));
2107 goto badusage;
2108 }
2109
2110 poolname = argv[0];
2111
2112 /*
2113 * As a special case, check for use of '/' in the name, and direct the
2114 * user to use 'zfs create' instead.
2115 */
2116 if (strchr(poolname, '/') != NULL) {
2117 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
2118 "character '/' in pool name\n"), poolname);
2119 (void) fprintf(stderr, gettext("use 'zfs create' to "
2120 "create a dataset\n"));
2121 goto errout;
2122 }
2123
2124 /* pass off to make_root_vdev for bulk processing */
2125 nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
2126 argc - 1, argv + 1);
2127 if (nvroot == NULL)
2128 goto errout;
2129
2130 /* make_root_vdev() allows 0 toplevel children if there are spares */
2131 if (!zfs_allocatable_devs(nvroot)) {
2132 (void) fprintf(stderr, gettext("invalid vdev "
2133 "specification: at least one toplevel vdev must be "
2134 "specified\n"));
2135 goto errout;
2136 }
2137
2138 if (altroot != NULL && altroot[0] != '/') {
2139 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
2140 "must be an absolute path\n"), altroot);
2141 goto errout;
2142 }
2143
2144 /*
2145 * Check the validity of the mountpoint and direct the user to use the
2146 * '-m' mountpoint option if it looks like its in use.
2147 */
2148 if (mountpoint == NULL ||
2149 (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
2150 strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
2151 char buf[MAXPATHLEN];
2152 DIR *dirp;
2153
2154 if (mountpoint && mountpoint[0] != '/') {
2155 (void) fprintf(stderr, gettext("invalid mountpoint "
2156 "'%s': must be an absolute path, 'legacy', or "
2157 "'none'\n"), mountpoint);
2158 goto errout;
2159 }
2160
2161 if (mountpoint == NULL) {
2162 if (altroot != NULL)
2163 (void) snprintf(buf, sizeof (buf), "%s/%s",
2164 altroot, poolname);
2165 else
2166 (void) snprintf(buf, sizeof (buf), "/%s",
2167 poolname);
2168 } else {
2169 if (altroot != NULL)
2170 (void) snprintf(buf, sizeof (buf), "%s%s",
2171 altroot, mountpoint);
2172 else
2173 (void) snprintf(buf, sizeof (buf), "%s",
2174 mountpoint);
2175 }
2176
2177 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
2178 (void) fprintf(stderr, gettext("mountpoint '%s' : "
2179 "%s\n"), buf, strerror(errno));
2180 (void) fprintf(stderr, gettext("use '-m' "
2181 "option to provide a different default\n"));
2182 goto errout;
2183 } else if (dirp) {
2184 int count = 0;
2185
2186 while (count < 3 && readdir(dirp) != NULL)
2187 count++;
2188 (void) closedir(dirp);
2189
2190 if (count > 2) {
2191 (void) fprintf(stderr, gettext("mountpoint "
2192 "'%s' exists and is not empty\n"), buf);
2193 (void) fprintf(stderr, gettext("use '-m' "
2194 "option to provide a "
2195 "different default\n"));
2196 goto errout;
2197 }
2198 }
2199 }
2200
2201 /*
2202 * Now that the mountpoint's validity has been checked, ensure that
2203 * the property is set appropriately prior to creating the pool.
2204 */
2205 if (mountpoint != NULL) {
2206 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
2207 mountpoint, &fsprops, B_FALSE);
2208 if (ret != 0)
2209 goto errout;
2210 }
2211
2212 ret = 1;
2213 if (dryrun) {
2214 /*
2215 * For a dry run invocation, print out a basic message and run
2216 * through all the vdevs in the list and print out in an
2217 * appropriate hierarchy.
2218 */
2219 (void) printf(gettext("would create '%s' with the "
2220 "following layout:\n\n"), poolname);
2221
2222 print_vdev_tree(NULL, poolname, nvroot, 0, "", 0);
2223 print_vdev_tree(NULL, "dedup", nvroot, 0,
2224 VDEV_ALLOC_BIAS_DEDUP, 0);
2225 print_vdev_tree(NULL, "special", nvroot, 0,
2226 VDEV_ALLOC_BIAS_SPECIAL, 0);
2227 print_vdev_tree(NULL, "logs", nvroot, 0,
2228 VDEV_ALLOC_BIAS_LOG, 0);
2229 print_cache_list(nvroot, 0);
2230 print_spare_list(nvroot, 0);
2231
2232 ret = 0;
2233 } else {
2234 /*
2235 * Load in feature set.
2236 * Note: if compatibility property not given, we'll have
2237 * NULL, which means 'all features'.
2238 */
2239 boolean_t requested_features[SPA_FEATURES];
2240 if (zpool_do_load_compat(compat, requested_features) !=
2241 ZPOOL_COMPATIBILITY_OK)
2242 goto errout;
2243
2244 /*
2245 * props contains list of features to enable.
2246 * For each feature:
2247 * - remove it if feature@name=disabled
2248 * - leave it there if feature@name=enabled
2249 * - add it if:
2250 * - enable_pool_features (ie: no '-d' or '-o version')
2251 * - it's supported by the kernel module
2252 * - it's in the requested feature set
2253 * - warn if it's enabled but not in compat
2254 */
2255 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
2256 char propname[MAXPATHLEN];
2257 const char *propval;
2258 zfeature_info_t *feat = &spa_feature_table[i];
2259
2260 (void) snprintf(propname, sizeof (propname),
2261 "feature@%s", feat->fi_uname);
2262
2263 if (!nvlist_lookup_string(props, propname, &propval)) {
2264 if (strcmp(propval,
2265 ZFS_FEATURE_DISABLED) == 0) {
2266 (void) nvlist_remove_all(props,
2267 propname);
2268 } else if (strcmp(propval,
2269 ZFS_FEATURE_ENABLED) == 0 &&
2270 !requested_features[i]) {
2271 (void) fprintf(stderr, gettext(
2272 "Warning: feature \"%s\" enabled "
2273 "but is not in specified "
2274 "'compatibility' feature set.\n"),
2275 feat->fi_uname);
2276 }
2277 } else if (
2278 enable_pool_features &&
2279 feat->fi_zfs_mod_supported &&
2280 requested_features[i]) {
2281 ret = add_prop_list(propname,
2282 ZFS_FEATURE_ENABLED, &props, B_TRUE);
2283 if (ret != 0)
2284 goto errout;
2285 }
2286 }
2287
2288 ret = 1;
2289 if (zpool_create(g_zfs, poolname,
2290 nvroot, props, fsprops) == 0) {
2291 zfs_handle_t *pool = zfs_open(g_zfs,
2292 tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
2293 if (pool != NULL) {
2294 if (zfs_mount(pool, NULL, 0) == 0) {
2295 ret = zfs_share(pool, NULL);
2296 zfs_commit_shares(NULL);
2297 }
2298 zfs_close(pool);
2299 }
2300 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
2301 (void) fprintf(stderr, gettext("pool name may have "
2302 "been omitted\n"));
2303 }
2304 }
2305
2306 errout:
2307 nvlist_free(nvroot);
2308 nvlist_free(fsprops);
2309 nvlist_free(props);
2310 return (ret);
2311 badusage:
2312 nvlist_free(fsprops);
2313 nvlist_free(props);
2314 usage(B_FALSE);
2315 return (2);
2316 }
2317
2318 /*
2319 * zpool destroy <pool>
2320 *
2321 * -f Forcefully unmount any datasets
2322 *
2323 * Destroy the given pool. Automatically unmounts any datasets in the pool.
2324 */
2325 int
zpool_do_destroy(int argc,char ** argv)2326 zpool_do_destroy(int argc, char **argv)
2327 {
2328 boolean_t force = B_FALSE;
2329 int c;
2330 char *pool;
2331 zpool_handle_t *zhp;
2332 int ret;
2333
2334 /* check options */
2335 while ((c = getopt(argc, argv, "f")) != -1) {
2336 switch (c) {
2337 case 'f':
2338 force = B_TRUE;
2339 break;
2340 case '?':
2341 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2342 optopt);
2343 usage(B_FALSE);
2344 }
2345 }
2346
2347 argc -= optind;
2348 argv += optind;
2349
2350 /* check arguments */
2351 if (argc < 1) {
2352 (void) fprintf(stderr, gettext("missing pool argument\n"));
2353 usage(B_FALSE);
2354 }
2355 if (argc > 1) {
2356 (void) fprintf(stderr, gettext("too many arguments\n"));
2357 usage(B_FALSE);
2358 }
2359
2360 pool = argv[0];
2361
2362 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
2363 /*
2364 * As a special case, check for use of '/' in the name, and
2365 * direct the user to use 'zfs destroy' instead.
2366 */
2367 if (strchr(pool, '/') != NULL)
2368 (void) fprintf(stderr, gettext("use 'zfs destroy' to "
2369 "destroy a dataset\n"));
2370 return (1);
2371 }
2372
2373 if (zpool_disable_datasets(zhp, force) != 0) {
2374 (void) fprintf(stderr, gettext("could not destroy '%s': "
2375 "could not unmount datasets\n"), zpool_get_name(zhp));
2376 zpool_close(zhp);
2377 return (1);
2378 }
2379
2380 /* The history must be logged as part of the export */
2381 log_history = B_FALSE;
2382
2383 ret = (zpool_destroy(zhp, history_str) != 0);
2384
2385 zpool_close(zhp);
2386
2387 return (ret);
2388 }
2389
2390 typedef struct export_cbdata {
2391 taskq_t *taskq;
2392 pthread_mutex_t mnttab_lock;
2393 boolean_t force;
2394 boolean_t hardforce;
2395 int retval;
2396 } export_cbdata_t;
2397
2398
2399 typedef struct {
2400 char *aea_poolname;
2401 export_cbdata_t *aea_cbdata;
2402 } async_export_args_t;
2403
2404 /*
2405 * Export one pool
2406 */
2407 static int
zpool_export_one(zpool_handle_t * zhp,void * data)2408 zpool_export_one(zpool_handle_t *zhp, void *data)
2409 {
2410 export_cbdata_t *cb = data;
2411
2412 /*
2413 * zpool_disable_datasets() is not thread-safe for mnttab access.
2414 * So we serialize access here for 'zpool export -a' parallel case.
2415 */
2416 if (cb->taskq != NULL)
2417 (void) pthread_mutex_lock(&cb->mnttab_lock);
2418
2419 int retval = zpool_disable_datasets(zhp, cb->force);
2420
2421 if (cb->taskq != NULL)
2422 (void) pthread_mutex_unlock(&cb->mnttab_lock);
2423
2424 if (retval)
2425 return (1);
2426
2427 if (cb->hardforce) {
2428 if (zpool_export_force(zhp, history_str) != 0)
2429 return (1);
2430 } else if (zpool_export(zhp, cb->force, history_str) != 0) {
2431 return (1);
2432 }
2433
2434 return (0);
2435 }
2436
2437 /*
2438 * Asynchronous export request
2439 */
2440 static void
zpool_export_task(void * arg)2441 zpool_export_task(void *arg)
2442 {
2443 async_export_args_t *aea = arg;
2444
2445 zpool_handle_t *zhp = zpool_open(g_zfs, aea->aea_poolname);
2446 if (zhp != NULL) {
2447 int ret = zpool_export_one(zhp, aea->aea_cbdata);
2448 if (ret != 0)
2449 aea->aea_cbdata->retval = ret;
2450 zpool_close(zhp);
2451 } else {
2452 aea->aea_cbdata->retval = 1;
2453 }
2454
2455 free(aea->aea_poolname);
2456 free(aea);
2457 }
2458
2459 /*
2460 * Process an export request in parallel
2461 */
2462 static int
zpool_export_one_async(zpool_handle_t * zhp,void * data)2463 zpool_export_one_async(zpool_handle_t *zhp, void *data)
2464 {
2465 taskq_t *tq = ((export_cbdata_t *)data)->taskq;
2466 async_export_args_t *aea = safe_malloc(sizeof (async_export_args_t));
2467
2468 /* save pool name since zhp will go out of scope */
2469 aea->aea_poolname = strdup(zpool_get_name(zhp));
2470 aea->aea_cbdata = data;
2471
2472 /* ship off actual export to another thread */
2473 if (taskq_dispatch(tq, zpool_export_task, (void *)aea,
2474 TQ_SLEEP) == TASKQID_INVALID)
2475 return (errno); /* unlikely */
2476 else
2477 return (0);
2478 }
2479
2480 /*
2481 * zpool export [-f] <pool> ...
2482 *
2483 * -a Export all pools
2484 * -f Forcefully unmount datasets
2485 *
2486 * Export the given pools. By default, the command will attempt to cleanly
2487 * unmount any active datasets within the pool. If the '-f' flag is specified,
2488 * then the datasets will be forcefully unmounted.
2489 */
2490 int
zpool_do_export(int argc,char ** argv)2491 zpool_do_export(int argc, char **argv)
2492 {
2493 export_cbdata_t cb;
2494 boolean_t do_all = B_FALSE;
2495 boolean_t force = B_FALSE;
2496 boolean_t hardforce = B_FALSE;
2497 int c, ret;
2498
2499 /* check options */
2500 while ((c = getopt(argc, argv, "afF")) != -1) {
2501 switch (c) {
2502 case 'a':
2503 do_all = B_TRUE;
2504 break;
2505 case 'f':
2506 force = B_TRUE;
2507 break;
2508 case 'F':
2509 hardforce = B_TRUE;
2510 break;
2511 case '?':
2512 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2513 optopt);
2514 usage(B_FALSE);
2515 }
2516 }
2517
2518 cb.force = force;
2519 cb.hardforce = hardforce;
2520 cb.taskq = NULL;
2521 cb.retval = 0;
2522 argc -= optind;
2523 argv += optind;
2524
2525 /* The history will be logged as part of the export itself */
2526 log_history = B_FALSE;
2527
2528 if (do_all) {
2529 if (argc != 0) {
2530 (void) fprintf(stderr, gettext("too many arguments\n"));
2531 usage(B_FALSE);
2532 }
2533
2534 cb.taskq = taskq_create("zpool_export",
2535 5 * sysconf(_SC_NPROCESSORS_ONLN), minclsyspri, 1, INT_MAX,
2536 TASKQ_DYNAMIC);
2537 (void) pthread_mutex_init(&cb.mnttab_lock, NULL);
2538
2539 /* Asynchronously call zpool_export_one using thread pool */
2540 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2541 B_FALSE, zpool_export_one_async, &cb);
2542
2543 taskq_wait(cb.taskq);
2544 taskq_destroy(cb.taskq);
2545 (void) pthread_mutex_destroy(&cb.mnttab_lock);
2546
2547 return (ret | cb.retval);
2548 }
2549
2550 /* check arguments */
2551 if (argc < 1) {
2552 (void) fprintf(stderr, gettext("missing pool argument\n"));
2553 usage(B_FALSE);
2554 }
2555
2556 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
2557 B_FALSE, zpool_export_one, &cb);
2558
2559 return (ret);
2560 }
2561
2562 /*
2563 * Given a vdev configuration, determine the maximum width needed for the device
2564 * name column.
2565 */
2566 static int
max_width(zpool_handle_t * zhp,nvlist_t * nv,int depth,int max,int name_flags)2567 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
2568 int name_flags)
2569 {
2570 static const char *const subtypes[] =
2571 {ZPOOL_CONFIG_SPARES, ZPOOL_CONFIG_L2CACHE, ZPOOL_CONFIG_CHILDREN};
2572
2573 char *name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
2574 max = MAX(strlen(name) + depth, max);
2575 free(name);
2576
2577 nvlist_t **child;
2578 uint_t children;
2579 for (size_t i = 0; i < ARRAY_SIZE(subtypes); ++i)
2580 if (nvlist_lookup_nvlist_array(nv, subtypes[i],
2581 &child, &children) == 0)
2582 for (uint_t c = 0; c < children; ++c)
2583 max = MAX(max_width(zhp, child[c], depth + 2,
2584 max, name_flags), max);
2585
2586 return (max);
2587 }
2588
2589 typedef struct status_cbdata {
2590 int cb_count;
2591 int cb_name_flags;
2592 int cb_namewidth;
2593 boolean_t cb_allpools;
2594 boolean_t cb_verbose;
2595 boolean_t cb_literal;
2596 boolean_t cb_explain;
2597 boolean_t cb_first;
2598 boolean_t cb_dedup_stats;
2599 boolean_t cb_print_unhealthy;
2600 boolean_t cb_print_status;
2601 boolean_t cb_print_slow_ios;
2602 boolean_t cb_print_dio_verify;
2603 boolean_t cb_print_vdev_init;
2604 boolean_t cb_print_vdev_trim;
2605 vdev_cmd_data_list_t *vcdl;
2606 boolean_t cb_print_power;
2607 boolean_t cb_json;
2608 boolean_t cb_flat_vdevs;
2609 nvlist_t *cb_jsobj;
2610 boolean_t cb_json_as_int;
2611 boolean_t cb_json_pool_key_guid;
2612 } status_cbdata_t;
2613
2614 /* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
2615 static boolean_t
is_blank_str(const char * str)2616 is_blank_str(const char *str)
2617 {
2618 for (; str != NULL && *str != '\0'; ++str)
2619 if (!isblank(*str))
2620 return (B_FALSE);
2621 return (B_TRUE);
2622 }
2623
2624 static void
zpool_nvlist_cmd(vdev_cmd_data_list_t * vcdl,const char * pool,const char * path,nvlist_t * item)2625 zpool_nvlist_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path,
2626 nvlist_t *item)
2627 {
2628 vdev_cmd_data_t *data;
2629 int i, j, k = 1;
2630 char tmp[256];
2631 const char *val;
2632
2633 for (i = 0; i < vcdl->count; i++) {
2634 if ((strcmp(vcdl->data[i].path, path) != 0) ||
2635 (strcmp(vcdl->data[i].pool, pool) != 0))
2636 continue;
2637
2638 data = &vcdl->data[i];
2639 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2640 val = NULL;
2641 for (int k = 0; k < data->cols_cnt; k++) {
2642 if (strcmp(data->cols[k],
2643 vcdl->uniq_cols[j]) == 0) {
2644 val = data->lines[k];
2645 break;
2646 }
2647 }
2648 if (val == NULL || is_blank_str(val))
2649 val = "-";
2650 fnvlist_add_string(item, vcdl->uniq_cols[j], val);
2651 }
2652
2653 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2654 if (data->lines[j]) {
2655 (void) snprintf(tmp, 256, "extra_%d", k++);
2656 fnvlist_add_string(item, tmp,
2657 data->lines[j]);
2658 }
2659 }
2660 break;
2661 }
2662 }
2663
2664 /* Print command output lines for specific vdev in a specific pool */
2665 static void
zpool_print_cmd(vdev_cmd_data_list_t * vcdl,const char * pool,const char * path)2666 zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, const char *path)
2667 {
2668 vdev_cmd_data_t *data;
2669 int i, j;
2670 const char *val;
2671
2672 for (i = 0; i < vcdl->count; i++) {
2673 if ((strcmp(vcdl->data[i].path, path) != 0) ||
2674 (strcmp(vcdl->data[i].pool, pool) != 0)) {
2675 /* Not the vdev we're looking for */
2676 continue;
2677 }
2678
2679 data = &vcdl->data[i];
2680 /* Print out all the output values for this vdev */
2681 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
2682 val = NULL;
2683 /* Does this vdev have values for this column? */
2684 for (int k = 0; k < data->cols_cnt; k++) {
2685 if (strcmp(data->cols[k],
2686 vcdl->uniq_cols[j]) == 0) {
2687 /* yes it does, record the value */
2688 val = data->lines[k];
2689 break;
2690 }
2691 }
2692 /*
2693 * Mark empty values with dashes to make output
2694 * awk-able.
2695 */
2696 if (val == NULL || is_blank_str(val))
2697 val = "-";
2698
2699 printf("%*s", vcdl->uniq_cols_width[j], val);
2700 if (j < vcdl->uniq_cols_cnt - 1)
2701 (void) fputs(" ", stdout);
2702 }
2703
2704 /* Print out any values that aren't in a column at the end */
2705 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
2706 /* Did we have any columns? If so print a spacer. */
2707 if (vcdl->uniq_cols_cnt > 0)
2708 (void) fputs(" ", stdout);
2709
2710 val = data->lines[j];
2711 (void) fputs(val ?: "", stdout);
2712 }
2713 break;
2714 }
2715 }
2716
2717 /*
2718 * Print vdev initialization status for leaves
2719 */
2720 static void
print_status_initialize(vdev_stat_t * vs,boolean_t verbose)2721 print_status_initialize(vdev_stat_t *vs, boolean_t verbose)
2722 {
2723 if (verbose) {
2724 if ((vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE ||
2725 vs->vs_initialize_state == VDEV_INITIALIZE_SUSPENDED ||
2726 vs->vs_initialize_state == VDEV_INITIALIZE_COMPLETE) &&
2727 !vs->vs_scan_removing) {
2728 char zbuf[1024];
2729 char tbuf[256];
2730
2731 time_t t = vs->vs_initialize_action_time;
2732 int initialize_pct = 100;
2733 if (vs->vs_initialize_state !=
2734 VDEV_INITIALIZE_COMPLETE) {
2735 initialize_pct = (vs->vs_initialize_bytes_done *
2736 100 / (vs->vs_initialize_bytes_est + 1));
2737 }
2738
2739 (void) ctime_r(&t, tbuf);
2740 tbuf[24] = 0;
2741
2742 switch (vs->vs_initialize_state) {
2743 case VDEV_INITIALIZE_SUSPENDED:
2744 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2745 gettext("suspended, started at"), tbuf);
2746 break;
2747 case VDEV_INITIALIZE_ACTIVE:
2748 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2749 gettext("started at"), tbuf);
2750 break;
2751 case VDEV_INITIALIZE_COMPLETE:
2752 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2753 gettext("completed at"), tbuf);
2754 break;
2755 }
2756
2757 (void) printf(gettext(" (%d%% initialized%s)"),
2758 initialize_pct, zbuf);
2759 } else {
2760 (void) printf(gettext(" (uninitialized)"));
2761 }
2762 } else if (vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE) {
2763 (void) printf(gettext(" (initializing)"));
2764 }
2765 }
2766
2767 /*
2768 * Print vdev TRIM status for leaves
2769 */
2770 static void
print_status_trim(vdev_stat_t * vs,boolean_t verbose)2771 print_status_trim(vdev_stat_t *vs, boolean_t verbose)
2772 {
2773 if (verbose) {
2774 if ((vs->vs_trim_state == VDEV_TRIM_ACTIVE ||
2775 vs->vs_trim_state == VDEV_TRIM_SUSPENDED ||
2776 vs->vs_trim_state == VDEV_TRIM_COMPLETE) &&
2777 !vs->vs_scan_removing) {
2778 char zbuf[1024];
2779 char tbuf[256];
2780
2781 time_t t = vs->vs_trim_action_time;
2782 int trim_pct = 100;
2783 if (vs->vs_trim_state != VDEV_TRIM_COMPLETE) {
2784 trim_pct = (vs->vs_trim_bytes_done *
2785 100 / (vs->vs_trim_bytes_est + 1));
2786 }
2787
2788 (void) ctime_r(&t, tbuf);
2789 tbuf[24] = 0;
2790
2791 switch (vs->vs_trim_state) {
2792 case VDEV_TRIM_SUSPENDED:
2793 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2794 gettext("suspended, started at"), tbuf);
2795 break;
2796 case VDEV_TRIM_ACTIVE:
2797 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2798 gettext("started at"), tbuf);
2799 break;
2800 case VDEV_TRIM_COMPLETE:
2801 (void) snprintf(zbuf, sizeof (zbuf), ", %s %s",
2802 gettext("completed at"), tbuf);
2803 break;
2804 }
2805
2806 (void) printf(gettext(" (%d%% trimmed%s)"),
2807 trim_pct, zbuf);
2808 } else if (vs->vs_trim_notsup) {
2809 (void) printf(gettext(" (trim unsupported)"));
2810 } else {
2811 (void) printf(gettext(" (untrimmed)"));
2812 }
2813 } else if (vs->vs_trim_state == VDEV_TRIM_ACTIVE) {
2814 (void) printf(gettext(" (trimming)"));
2815 }
2816 }
2817
2818 /*
2819 * Return the color associated with a health string. This includes returning
2820 * NULL for no color change.
2821 */
2822 static const char *
health_str_to_color(const char * health)2823 health_str_to_color(const char *health)
2824 {
2825 if (strcmp(health, gettext("FAULTED")) == 0 ||
2826 strcmp(health, gettext("SUSPENDED")) == 0 ||
2827 strcmp(health, gettext("UNAVAIL")) == 0) {
2828 return (ANSI_RED);
2829 }
2830
2831 if (strcmp(health, gettext("OFFLINE")) == 0 ||
2832 strcmp(health, gettext("DEGRADED")) == 0 ||
2833 strcmp(health, gettext("REMOVED")) == 0) {
2834 return (ANSI_YELLOW);
2835 }
2836
2837 return (NULL);
2838 }
2839
2840 /*
2841 * Called for each leaf vdev. Returns 0 if the vdev is healthy.
2842 * A vdev is unhealthy if any of the following are true:
2843 * 1) there are read, write, or checksum errors,
2844 * 2) its state is not ONLINE, or
2845 * 3) slow IO reporting was requested (-s) and there are slow IOs.
2846 */
2847 static int
vdev_health_check_cb(void * hdl_data,nvlist_t * nv,void * data)2848 vdev_health_check_cb(void *hdl_data, nvlist_t *nv, void *data)
2849 {
2850 status_cbdata_t *cb = data;
2851 vdev_stat_t *vs;
2852 uint_t vsc;
2853 (void) hdl_data;
2854
2855 if (nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2856 (uint64_t **)&vs, &vsc) != 0)
2857 return (1);
2858
2859 if (vs->vs_checksum_errors || vs->vs_read_errors ||
2860 vs->vs_write_errors || vs->vs_state != VDEV_STATE_HEALTHY)
2861 return (1);
2862
2863 if (cb->cb_print_slow_ios && vs->vs_slow_ios)
2864 return (1);
2865
2866 return (0);
2867 }
2868
2869 /*
2870 * Print out configuration state as requested by status_callback.
2871 */
2872 static void
print_status_config(zpool_handle_t * zhp,status_cbdata_t * cb,const char * name,nvlist_t * nv,int depth,boolean_t isspare,vdev_rebuild_stat_t * vrs)2873 print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
2874 nvlist_t *nv, int depth, boolean_t isspare, vdev_rebuild_stat_t *vrs)
2875 {
2876 nvlist_t **child, *root;
2877 uint_t c, i, vsc, children;
2878 pool_scan_stat_t *ps = NULL;
2879 vdev_stat_t *vs;
2880 char rbuf[6], wbuf[6], cbuf[6], dbuf[6];
2881 char *vname;
2882 uint64_t notpresent;
2883 spare_cbdata_t spare_cb;
2884 const char *state;
2885 const char *type;
2886 const char *path = NULL;
2887 const char *rcolor = NULL, *wcolor = NULL, *ccolor = NULL,
2888 *scolor = NULL;
2889
2890 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2891 &child, &children) != 0)
2892 children = 0;
2893
2894 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2895 (uint64_t **)&vs, &vsc) == 0);
2896
2897 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
2898
2899 if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
2900 return;
2901
2902 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
2903
2904 if (isspare) {
2905 /*
2906 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
2907 * online drives.
2908 */
2909 if (vs->vs_aux == VDEV_AUX_SPARED)
2910 state = gettext("INUSE");
2911 else if (vs->vs_state == VDEV_STATE_HEALTHY)
2912 state = gettext("AVAIL");
2913 }
2914
2915 /*
2916 * If '-e' is specified then top-level vdevs and their children
2917 * can be pruned if all of their leaves are healthy.
2918 */
2919 if (cb->cb_print_unhealthy && depth > 0 &&
2920 for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
2921 return;
2922 }
2923
2924 (void) printf_color(health_str_to_color(state),
2925 "\t%*s%-*s %-8s", depth, "", cb->cb_namewidth - depth,
2926 name, state);
2927
2928 if (!isspare) {
2929 if (vs->vs_read_errors)
2930 rcolor = ANSI_RED;
2931
2932 if (vs->vs_write_errors)
2933 wcolor = ANSI_RED;
2934
2935 if (vs->vs_checksum_errors)
2936 ccolor = ANSI_RED;
2937
2938 if (vs->vs_slow_ios)
2939 scolor = ANSI_BLUE;
2940
2941 if (cb->cb_literal) {
2942 (void) fputc(' ', stdout);
2943 (void) printf_color(rcolor, "%5llu",
2944 (u_longlong_t)vs->vs_read_errors);
2945 (void) fputc(' ', stdout);
2946 (void) printf_color(wcolor, "%5llu",
2947 (u_longlong_t)vs->vs_write_errors);
2948 (void) fputc(' ', stdout);
2949 (void) printf_color(ccolor, "%5llu",
2950 (u_longlong_t)vs->vs_checksum_errors);
2951 } else {
2952 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
2953 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
2954 zfs_nicenum(vs->vs_checksum_errors, cbuf,
2955 sizeof (cbuf));
2956 (void) fputc(' ', stdout);
2957 (void) printf_color(rcolor, "%5s", rbuf);
2958 (void) fputc(' ', stdout);
2959 (void) printf_color(wcolor, "%5s", wbuf);
2960 (void) fputc(' ', stdout);
2961 (void) printf_color(ccolor, "%5s", cbuf);
2962 }
2963 if (cb->cb_print_slow_ios) {
2964 if (children == 0) {
2965 /* Only leafs vdevs have slow IOs */
2966 zfs_nicenum(vs->vs_slow_ios, rbuf,
2967 sizeof (rbuf));
2968 } else {
2969 (void) snprintf(rbuf, sizeof (rbuf), "-");
2970 }
2971
2972 if (cb->cb_literal)
2973 (void) printf_color(scolor, " %5llu",
2974 (u_longlong_t)vs->vs_slow_ios);
2975 else
2976 (void) printf_color(scolor, " %5s", rbuf);
2977 }
2978 if (cb->cb_print_power) {
2979 if (children == 0) {
2980 /* Only leaf vdevs have physical slots */
2981 switch (zpool_power_current_state(zhp, (char *)
2982 fnvlist_lookup_string(nv,
2983 ZPOOL_CONFIG_PATH))) {
2984 case 0:
2985 (void) printf_color(ANSI_RED, " %5s",
2986 gettext("off"));
2987 break;
2988 case 1:
2989 printf(" %5s", gettext("on"));
2990 break;
2991 default:
2992 printf(" %5s", "-");
2993 }
2994 } else {
2995 printf(" %5s", "-");
2996 }
2997 }
2998 if (VDEV_STAT_VALID(vs_dio_verify_errors, vsc) &&
2999 cb->cb_print_dio_verify) {
3000 zfs_nicenum(vs->vs_dio_verify_errors, dbuf,
3001 sizeof (dbuf));
3002
3003 if (cb->cb_literal)
3004 printf(" %5llu",
3005 (u_longlong_t)vs->vs_dio_verify_errors);
3006 else
3007 printf(" %5s", dbuf);
3008 }
3009 }
3010
3011 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
3012 ¬present) == 0) {
3013 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
3014 (void) printf(" %s %s", gettext("was"), path);
3015 } else if (vs->vs_aux != 0) {
3016 (void) printf(" ");
3017 color_start(ANSI_RED);
3018 switch (vs->vs_aux) {
3019 case VDEV_AUX_OPEN_FAILED:
3020 (void) printf(gettext("cannot open"));
3021 break;
3022
3023 case VDEV_AUX_BAD_GUID_SUM:
3024 (void) printf(gettext("missing device"));
3025 break;
3026
3027 case VDEV_AUX_NO_REPLICAS:
3028 (void) printf(gettext("insufficient replicas"));
3029 break;
3030
3031 case VDEV_AUX_VERSION_NEWER:
3032 (void) printf(gettext("newer version"));
3033 break;
3034
3035 case VDEV_AUX_UNSUP_FEAT:
3036 (void) printf(gettext("unsupported feature(s)"));
3037 break;
3038
3039 case VDEV_AUX_ASHIFT_TOO_BIG:
3040 (void) printf(gettext("unsupported minimum blocksize"));
3041 break;
3042
3043 case VDEV_AUX_SPARED:
3044 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3045 &spare_cb.cb_guid) == 0);
3046 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
3047 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
3048 zpool_get_name(zhp)) == 0)
3049 (void) printf(gettext("currently in "
3050 "use"));
3051 else
3052 (void) printf(gettext("in use by "
3053 "pool '%s'"),
3054 zpool_get_name(spare_cb.cb_zhp));
3055 zpool_close(spare_cb.cb_zhp);
3056 } else {
3057 (void) printf(gettext("currently in use"));
3058 }
3059 break;
3060
3061 case VDEV_AUX_ERR_EXCEEDED:
3062 if (vs->vs_read_errors + vs->vs_write_errors +
3063 vs->vs_checksum_errors == 0 && children == 0 &&
3064 vs->vs_slow_ios > 0) {
3065 (void) printf(gettext("too many slow I/Os"));
3066 } else {
3067 (void) printf(gettext("too many errors"));
3068 }
3069 break;
3070
3071 case VDEV_AUX_IO_FAILURE:
3072 (void) printf(gettext("experienced I/O failures"));
3073 break;
3074
3075 case VDEV_AUX_BAD_LOG:
3076 (void) printf(gettext("bad intent log"));
3077 break;
3078
3079 case VDEV_AUX_EXTERNAL:
3080 (void) printf(gettext("external device fault"));
3081 break;
3082
3083 case VDEV_AUX_SPLIT_POOL:
3084 (void) printf(gettext("split into new pool"));
3085 break;
3086
3087 case VDEV_AUX_ACTIVE:
3088 (void) printf(gettext("currently in use"));
3089 break;
3090
3091 case VDEV_AUX_CHILDREN_OFFLINE:
3092 (void) printf(gettext("all children offline"));
3093 break;
3094
3095 case VDEV_AUX_BAD_LABEL:
3096 (void) printf(gettext("invalid label"));
3097 break;
3098
3099 default:
3100 (void) printf(gettext("corrupted data"));
3101 break;
3102 }
3103 color_end();
3104 } else if (children == 0 && !isspare &&
3105 getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
3106 VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
3107 vs->vs_configured_ashift < vs->vs_physical_ashift) {
3108 (void) printf(
3109 gettext(" block size: %dB configured, %dB native"),
3110 1 << vs->vs_configured_ashift, 1 << vs->vs_physical_ashift);
3111 }
3112
3113 if (vs->vs_scan_removing != 0) {
3114 (void) printf(gettext(" (removing)"));
3115 } else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
3116 (void) printf(gettext(" (non-allocating)"));
3117 }
3118
3119 /* The root vdev has the scrub/resilver stats */
3120 root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
3121 ZPOOL_CONFIG_VDEV_TREE);
3122 (void) nvlist_lookup_uint64_array(root, ZPOOL_CONFIG_SCAN_STATS,
3123 (uint64_t **)&ps, &c);
3124
3125 /*
3126 * If you force fault a drive that's resilvering, its scan stats can
3127 * get frozen in time, giving the false impression that it's
3128 * being resilvered. That's why we check the state to see if the vdev
3129 * is healthy before reporting "resilvering" or "repairing".
3130 */
3131 if (ps != NULL && ps->pss_state == DSS_SCANNING && children == 0 &&
3132 vs->vs_state == VDEV_STATE_HEALTHY) {
3133 if (vs->vs_scan_processed != 0) {
3134 (void) printf(gettext(" (%s)"),
3135 (ps->pss_func == POOL_SCAN_RESILVER) ?
3136 "resilvering" : "repairing");
3137 } else if (vs->vs_resilver_deferred) {
3138 (void) printf(gettext(" (awaiting resilver)"));
3139 }
3140 }
3141
3142 /* The top-level vdevs have the rebuild stats */
3143 if (vrs != NULL && vrs->vrs_state == VDEV_REBUILD_ACTIVE &&
3144 children == 0 && vs->vs_state == VDEV_STATE_HEALTHY) {
3145 if (vs->vs_rebuild_processed != 0) {
3146 (void) printf(gettext(" (resilvering)"));
3147 }
3148 }
3149
3150 if (cb->vcdl != NULL) {
3151 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
3152 printf(" ");
3153 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
3154 }
3155 }
3156
3157 /* Display vdev initialization and trim status for leaves. */
3158 if (children == 0) {
3159 print_status_initialize(vs, cb->cb_print_vdev_init);
3160 print_status_trim(vs, cb->cb_print_vdev_trim);
3161 }
3162
3163 (void) printf("\n");
3164
3165 for (c = 0; c < children; c++) {
3166 uint64_t islog = B_FALSE, ishole = B_FALSE;
3167
3168 /* Don't print logs or holes here */
3169 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3170 &islog);
3171 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
3172 &ishole);
3173 if (islog || ishole)
3174 continue;
3175 /* Only print normal classes here */
3176 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3177 continue;
3178
3179 /* Provide vdev_rebuild_stats to children if available */
3180 if (vrs == NULL) {
3181 (void) nvlist_lookup_uint64_array(nv,
3182 ZPOOL_CONFIG_REBUILD_STATS,
3183 (uint64_t **)&vrs, &i);
3184 }
3185
3186 vname = zpool_vdev_name(g_zfs, zhp, child[c],
3187 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3188 print_status_config(zhp, cb, vname, child[c], depth + 2,
3189 isspare, vrs);
3190 free(vname);
3191 }
3192 }
3193
3194 /*
3195 * Print the configuration of an exported pool. Iterate over all vdevs in the
3196 * pool, printing out the name and status for each one.
3197 */
3198 static void
print_import_config(status_cbdata_t * cb,const char * name,nvlist_t * nv,int depth)3199 print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
3200 int depth)
3201 {
3202 nvlist_t **child;
3203 uint_t c, children;
3204 vdev_stat_t *vs;
3205 const char *type;
3206 char *vname;
3207
3208 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
3209 if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
3210 strcmp(type, VDEV_TYPE_HOLE) == 0)
3211 return;
3212
3213 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
3214 (uint64_t **)&vs, &c) == 0);
3215
3216 (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
3217 (void) printf(" %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
3218
3219 if (vs->vs_aux != 0) {
3220 (void) printf(" ");
3221
3222 switch (vs->vs_aux) {
3223 case VDEV_AUX_OPEN_FAILED:
3224 (void) printf(gettext("cannot open"));
3225 break;
3226
3227 case VDEV_AUX_BAD_GUID_SUM:
3228 (void) printf(gettext("missing device"));
3229 break;
3230
3231 case VDEV_AUX_NO_REPLICAS:
3232 (void) printf(gettext("insufficient replicas"));
3233 break;
3234
3235 case VDEV_AUX_VERSION_NEWER:
3236 (void) printf(gettext("newer version"));
3237 break;
3238
3239 case VDEV_AUX_UNSUP_FEAT:
3240 (void) printf(gettext("unsupported feature(s)"));
3241 break;
3242
3243 case VDEV_AUX_ERR_EXCEEDED:
3244 (void) printf(gettext("too many errors"));
3245 break;
3246
3247 case VDEV_AUX_ACTIVE:
3248 (void) printf(gettext("currently in use"));
3249 break;
3250
3251 case VDEV_AUX_CHILDREN_OFFLINE:
3252 (void) printf(gettext("all children offline"));
3253 break;
3254
3255 case VDEV_AUX_BAD_LABEL:
3256 (void) printf(gettext("invalid label"));
3257 break;
3258
3259 default:
3260 (void) printf(gettext("corrupted data"));
3261 break;
3262 }
3263 }
3264 (void) printf("\n");
3265
3266 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
3267 &child, &children) != 0)
3268 return;
3269
3270 for (c = 0; c < children; c++) {
3271 uint64_t is_log = B_FALSE;
3272
3273 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3274 &is_log);
3275 if (is_log)
3276 continue;
3277 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
3278 continue;
3279
3280 vname = zpool_vdev_name(g_zfs, NULL, child[c],
3281 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3282 print_import_config(cb, vname, child[c], depth + 2);
3283 free(vname);
3284 }
3285
3286 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
3287 &child, &children) == 0) {
3288 (void) printf(gettext("\tcache\n"));
3289 for (c = 0; c < children; c++) {
3290 vname = zpool_vdev_name(g_zfs, NULL, child[c],
3291 cb->cb_name_flags);
3292 (void) printf("\t %s\n", vname);
3293 free(vname);
3294 }
3295 }
3296
3297 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
3298 &child, &children) == 0) {
3299 (void) printf(gettext("\tspares\n"));
3300 for (c = 0; c < children; c++) {
3301 vname = zpool_vdev_name(g_zfs, NULL, child[c],
3302 cb->cb_name_flags);
3303 (void) printf("\t %s\n", vname);
3304 free(vname);
3305 }
3306 }
3307 }
3308
3309 /*
3310 * Print specialized class vdevs.
3311 *
3312 * These are recorded as top level vdevs in the main pool child array
3313 * but with "is_log" set to 1 or an "alloc_bias" string. We use either
3314 * print_status_config() or print_import_config() to print the top level
3315 * class vdevs then any of their children (eg mirrored slogs) are printed
3316 * recursively - which works because only the top level vdev is marked.
3317 */
3318 static void
print_class_vdevs(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,const char * class)3319 print_class_vdevs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
3320 const char *class)
3321 {
3322 uint_t c, children;
3323 nvlist_t **child;
3324 boolean_t printed = B_FALSE;
3325
3326 assert(zhp != NULL || !cb->cb_verbose);
3327
3328 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
3329 &children) != 0)
3330 return;
3331
3332 for (c = 0; c < children; c++) {
3333 uint64_t is_log = B_FALSE;
3334 const char *bias = NULL;
3335 const char *type = NULL;
3336
3337 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3338 &is_log);
3339
3340 if (is_log) {
3341 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
3342 } else {
3343 (void) nvlist_lookup_string(child[c],
3344 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
3345 (void) nvlist_lookup_string(child[c],
3346 ZPOOL_CONFIG_TYPE, &type);
3347 }
3348
3349 if (bias == NULL || strcmp(bias, class) != 0)
3350 continue;
3351 if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
3352 continue;
3353
3354 if (!printed) {
3355 (void) printf("\t%s\t\n", gettext(class));
3356 printed = B_TRUE;
3357 }
3358
3359 char *name = zpool_vdev_name(g_zfs, zhp, child[c],
3360 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
3361 if (cb->cb_print_status)
3362 print_status_config(zhp, cb, name, child[c], 2,
3363 B_FALSE, NULL);
3364 else
3365 print_import_config(cb, name, child[c], 2);
3366 free(name);
3367 }
3368 }
3369
3370 /*
3371 * Display the status for the given pool.
3372 */
3373 static int
show_import(nvlist_t * config,boolean_t report_error)3374 show_import(nvlist_t *config, boolean_t report_error)
3375 {
3376 uint64_t pool_state;
3377 vdev_stat_t *vs;
3378 const char *name;
3379 uint64_t guid;
3380 uint64_t hostid = 0;
3381 const char *msgid;
3382 const char *hostname = "unknown";
3383 nvlist_t *nvroot, *nvinfo;
3384 zpool_status_t reason;
3385 zpool_errata_t errata;
3386 const char *health;
3387 uint_t vsc;
3388 const char *comment;
3389 const char *indent;
3390 char buf[2048];
3391 status_cbdata_t cb = { 0 };
3392
3393 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
3394 &name) == 0);
3395 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3396 &guid) == 0);
3397 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3398 &pool_state) == 0);
3399 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3400 &nvroot) == 0);
3401
3402 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
3403 (uint64_t **)&vs, &vsc) == 0);
3404 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
3405
3406 reason = zpool_import_status(config, &msgid, &errata);
3407
3408 /*
3409 * If we're importing using a cachefile, then we won't report any
3410 * errors unless we are in the scan phase of the import.
3411 */
3412 if (reason != ZPOOL_STATUS_OK && !report_error)
3413 return (reason);
3414
3415 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0) {
3416 indent = " ";
3417 } else {
3418 comment = NULL;
3419 indent = "";
3420 }
3421
3422 (void) printf(gettext("%s pool: %s\n"), indent, name);
3423 (void) printf(gettext("%s id: %llu\n"), indent, (u_longlong_t)guid);
3424 (void) printf(gettext("%s state: %s"), indent, health);
3425 if (pool_state == POOL_STATE_DESTROYED)
3426 (void) printf(gettext(" (DESTROYED)"));
3427 (void) printf("\n");
3428
3429 if (reason != ZPOOL_STATUS_OK) {
3430 (void) printf("%s", indent);
3431 (void) printf_color(ANSI_BOLD, gettext("status: "));
3432 }
3433 switch (reason) {
3434 case ZPOOL_STATUS_MISSING_DEV_R:
3435 case ZPOOL_STATUS_MISSING_DEV_NR:
3436 case ZPOOL_STATUS_BAD_GUID_SUM:
3437 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3438 "are missing from the system.\n"));
3439 break;
3440
3441 case ZPOOL_STATUS_CORRUPT_LABEL_R:
3442 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
3443 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3444 "contains corrupted data.\n"));
3445 break;
3446
3447 case ZPOOL_STATUS_CORRUPT_DATA:
3448 (void) printf_color(ANSI_YELLOW, gettext("The pool data is "
3449 "corrupted.\n"));
3450 break;
3451
3452 case ZPOOL_STATUS_OFFLINE_DEV:
3453 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3454 "are offlined.\n"));
3455 break;
3456
3457 case ZPOOL_STATUS_CORRUPT_POOL:
3458 (void) printf_color(ANSI_YELLOW, gettext("The pool metadata is "
3459 "incomplete or corrupted.\n"));
3460 break;
3461
3462 case ZPOOL_STATUS_VERSION_OLDER:
3463 (void) printf_color(ANSI_YELLOW, gettext("The pool is "
3464 "formatted using a legacy on-disk version.\n"));
3465 break;
3466
3467 case ZPOOL_STATUS_VERSION_NEWER:
3468 (void) printf_color(ANSI_YELLOW, gettext("The pool is "
3469 "formatted using an incompatible version.\n"));
3470 break;
3471
3472 case ZPOOL_STATUS_FEAT_DISABLED:
3473 (void) printf_color(ANSI_YELLOW, gettext("Some supported "
3474 "features are not enabled on the pool.\n"
3475 "\t%s(Note that they may be intentionally disabled if the\n"
3476 "\t%s'compatibility' property is set.)\n"), indent, indent);
3477 break;
3478
3479 case ZPOOL_STATUS_COMPATIBILITY_ERR:
3480 (void) printf_color(ANSI_YELLOW, gettext("Error reading or "
3481 "parsing the file(s) indicated by the 'compatibility'\n"
3482 "\t%sproperty.\n"), indent);
3483 break;
3484
3485 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
3486 (void) printf_color(ANSI_YELLOW, gettext("One or more features "
3487 "are enabled on the pool despite not being\n"
3488 "\t%srequested by the 'compatibility' property.\n"),
3489 indent);
3490 break;
3491
3492 case ZPOOL_STATUS_UNSUP_FEAT_READ:
3493 (void) printf_color(ANSI_YELLOW, gettext("The pool uses the "
3494 "following feature(s) not supported on this system:\n"));
3495 color_start(ANSI_YELLOW);
3496 zpool_collect_unsup_feat(config, buf, 2048);
3497 (void) printf("%s", buf);
3498 color_end();
3499 break;
3500
3501 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3502 (void) printf_color(ANSI_YELLOW, gettext("The pool can only be "
3503 "accessed in read-only mode on this system. It\n"
3504 "\t%scannot be accessed in read-write mode because it uses "
3505 "the following\n"
3506 "\t%sfeature(s) not supported on this system:\n"),
3507 indent, indent);
3508 color_start(ANSI_YELLOW);
3509 zpool_collect_unsup_feat(config, buf, 2048);
3510 (void) printf("%s", buf);
3511 color_end();
3512 break;
3513
3514 case ZPOOL_STATUS_HOSTID_ACTIVE:
3515 (void) printf_color(ANSI_YELLOW, gettext("The pool is "
3516 "currently imported by another system.\n"));
3517 break;
3518
3519 case ZPOOL_STATUS_HOSTID_REQUIRED:
3520 (void) printf_color(ANSI_YELLOW, gettext("The pool has the "
3521 "multihost property on. It cannot\n"
3522 "\t%sbe safely imported when the system hostid is not "
3523 "set.\n"), indent);
3524 break;
3525
3526 case ZPOOL_STATUS_HOSTID_MISMATCH:
3527 (void) printf_color(ANSI_YELLOW, gettext("The pool was last "
3528 "accessed by another system.\n"));
3529 break;
3530
3531 case ZPOOL_STATUS_FAULTED_FDOM_R:
3532 (void) printf_color(ANSI_YELLOW, gettext("One or more failure "
3533 " domains are faulted.\n"));
3534 break;
3535
3536 case ZPOOL_STATUS_FAULTED_DEV_R:
3537 case ZPOOL_STATUS_FAULTED_DEV_NR:
3538 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3539 "are faulted.\n"));
3540 break;
3541
3542 case ZPOOL_STATUS_BAD_LOG:
3543 (void) printf_color(ANSI_YELLOW, gettext("An intent log record "
3544 "cannot be read.\n"));
3545 break;
3546
3547 case ZPOOL_STATUS_RESILVERING:
3548 case ZPOOL_STATUS_REBUILDING:
3549 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3550 "were being resilvered.\n"));
3551 break;
3552
3553 case ZPOOL_STATUS_ERRATA:
3554 (void) printf_color(ANSI_YELLOW,
3555 gettext("Errata #%d detected.\n"),
3556 errata);
3557 break;
3558
3559 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
3560 (void) printf_color(ANSI_YELLOW, gettext("One or more devices "
3561 "are configured to use a non-native block size.\n"
3562 "\t%sExpect reduced performance.\n"), indent);
3563 break;
3564
3565 default:
3566 /*
3567 * No other status can be seen when importing pools.
3568 */
3569 assert(reason == ZPOOL_STATUS_OK);
3570 }
3571
3572 /*
3573 * Print out an action according to the overall state of the pool.
3574 */
3575 if (vs->vs_state != VDEV_STATE_HEALTHY ||
3576 reason != ZPOOL_STATUS_ERRATA || errata != ZPOOL_ERRATA_NONE) {
3577 (void) printf("%s", indent);
3578 (void) printf(gettext("action: "));
3579 }
3580 if (vs->vs_state == VDEV_STATE_HEALTHY) {
3581 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
3582 reason == ZPOOL_STATUS_FEAT_DISABLED) {
3583 (void) printf(gettext("The pool can be imported using "
3584 "its name or numeric identifier, though\n"
3585 "\t%ssome features will not be available without "
3586 "an explicit 'zpool upgrade'.\n"), indent);
3587 } else if (reason == ZPOOL_STATUS_COMPATIBILITY_ERR) {
3588 (void) printf(gettext("The pool can be imported using "
3589 "its name or numeric\n"
3590 "\t%sidentifier, though the file(s) indicated by "
3591 "its 'compatibility'\n"
3592 "\t%sproperty cannot be parsed at this time.\n"),
3593 indent, indent);
3594 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
3595 (void) printf(gettext("The pool can be imported using "
3596 "its name or numeric identifier and\n"
3597 "\t%sthe '-f' flag.\n"), indent);
3598 } else if (reason == ZPOOL_STATUS_ERRATA) {
3599 switch (errata) {
3600 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
3601 (void) printf(gettext("The pool can be "
3602 "imported using its name or numeric "
3603 "identifier,\n"
3604 "\t%showever there is a compatibility "
3605 "issue which should be corrected\n"
3606 "\t%sby running 'zpool scrub'\n"),
3607 indent, indent);
3608 break;
3609
3610 case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
3611 (void) printf(gettext("The pool cannot be "
3612 "imported with this version of ZFS due to\n"
3613 "\t%san active asynchronous destroy. "
3614 "Revert to an earlier version\n"
3615 "\t%sand allow the destroy to complete "
3616 "before updating.\n"), indent, indent);
3617 break;
3618
3619 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
3620 (void) printf(gettext("Existing encrypted "
3621 "datasets contain an on-disk "
3622 "incompatibility, which\n"
3623 "\t%sneeds to be corrected. Backup these "
3624 "datasets to new encrypted datasets\n"
3625 "\t%sand destroy the old ones.\n"),
3626 indent, indent);
3627 break;
3628
3629 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
3630 (void) printf(gettext("Existing encrypted "
3631 "snapshots and bookmarks contain an "
3632 "on-disk\n"
3633 "\t%sincompatibility. This may cause "
3634 "on-disk corruption if they are used\n"
3635 "\t%swith 'zfs recv'. To correct the "
3636 "issue, enable the bookmark_v2 feature.\n"
3637 "\t%sNo additional action is needed if "
3638 "there are no encrypted snapshots or\n"
3639 "\t%sbookmarks. If preserving the "
3640 "encrypted snapshots and bookmarks is\n"
3641 "\t%srequired, use a non-raw send to "
3642 "backup and restore them. Alternately,\n"
3643 "\t%sthey may be removed to resolve the "
3644 "incompatibility.\n"), indent, indent,
3645 indent, indent, indent, indent);
3646 break;
3647 default:
3648 /*
3649 * All errata must contain an action message.
3650 */
3651 assert(errata == ZPOOL_ERRATA_NONE);
3652 }
3653 } else {
3654 (void) printf(gettext("The pool can be imported using "
3655 "its name or numeric identifier.\n"));
3656 }
3657 } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
3658 (void) printf(gettext("The pool can be imported despite "
3659 "missing or damaged devices. The\n"
3660 "\t%sfault tolerance of the pool may be compromised if "
3661 "imported.\n"), indent);
3662 } else {
3663 switch (reason) {
3664 case ZPOOL_STATUS_VERSION_NEWER:
3665 (void) printf(gettext("The pool cannot be imported. "
3666 "Access the pool on a system running newer\n"
3667 "\t%ssoftware, or recreate the pool from "
3668 "backup.\n"), indent);
3669 break;
3670 case ZPOOL_STATUS_UNSUP_FEAT_READ:
3671 (void) printf(gettext("The pool cannot be imported. "
3672 "Access the pool on a system that supports\n"
3673 "\t%sthe required feature(s), or recreate the pool "
3674 "from backup.\n"), indent);
3675 break;
3676 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
3677 (void) printf(gettext("The pool cannot be imported in "
3678 "read-write mode. Import the pool with\n"
3679 "\t%s'-o readonly=on', access the pool on a system "
3680 "that supports the\n"
3681 "\t%srequired feature(s), or recreate the pool "
3682 "from backup.\n"), indent, indent);
3683 break;
3684 case ZPOOL_STATUS_MISSING_DEV_R:
3685 case ZPOOL_STATUS_MISSING_DEV_NR:
3686 case ZPOOL_STATUS_BAD_GUID_SUM:
3687 (void) printf(gettext("The pool cannot be imported. "
3688 "Attach the missing\n"
3689 "\t%sdevices and try again.\n"), indent);
3690 break;
3691 case ZPOOL_STATUS_HOSTID_ACTIVE:
3692 VERIFY0(nvlist_lookup_nvlist(config,
3693 ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
3694
3695 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3696 hostname = fnvlist_lookup_string(nvinfo,
3697 ZPOOL_CONFIG_MMP_HOSTNAME);
3698
3699 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3700 hostid = fnvlist_lookup_uint64(nvinfo,
3701 ZPOOL_CONFIG_MMP_HOSTID);
3702
3703 (void) printf(gettext("The pool must be exported from "
3704 "%s (hostid=%"PRIx64")\n"
3705 "\t%sbefore it can be safely imported.\n"),
3706 hostname, hostid, indent);
3707 break;
3708 case ZPOOL_STATUS_HOSTID_REQUIRED:
3709 (void) printf(gettext("Set a unique system hostid with "
3710 "the zgenhostid(8) command.\n"));
3711 break;
3712 case ZPOOL_STATUS_CORRUPT_POOL:
3713 (void) printf(gettext("The pool cannot be imported due "
3714 "to missing or damaged devices. Ensure\n"
3715 "\t%sall devices are present and not in use by "
3716 "another subsystem.\n"), indent);
3717 break;
3718 default:
3719 (void) printf(gettext("The pool cannot be imported due "
3720 "to damaged devices or data.\n"));
3721 }
3722 }
3723
3724 /* Print the comment attached to the pool. */
3725 if (comment != NULL)
3726 (void) printf(gettext("comment: %s\n"), comment);
3727
3728 /*
3729 * If the state is "closed" or "can't open", and the aux state
3730 * is "corrupt data":
3731 */
3732 if ((vs->vs_state == VDEV_STATE_CLOSED ||
3733 vs->vs_state == VDEV_STATE_CANT_OPEN) &&
3734 vs->vs_aux == VDEV_AUX_CORRUPT_DATA) {
3735 if (pool_state == POOL_STATE_DESTROYED)
3736 (void) printf(gettext("\t%sThe pool was destroyed, "
3737 "but can be imported using the '-Df' flags.\n"),
3738 indent);
3739 else if (pool_state != POOL_STATE_EXPORTED)
3740 (void) printf(gettext("\t%sThe pool may be active on "
3741 "another system, but can be imported using\n"
3742 "\t%sthe '-f' flag.\n"), indent, indent);
3743 }
3744
3745 if (msgid != NULL) {
3746 (void) printf(gettext("%s see: "
3747 "https://openzfs.github.io/openzfs-docs/msg/%s\n"),
3748 indent, msgid);
3749 }
3750
3751 (void) printf(gettext("%sconfig:\n\n"), indent);
3752
3753 cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
3754 VDEV_NAME_TYPE_ID);
3755 if (cb.cb_namewidth < 10)
3756 cb.cb_namewidth = 10;
3757
3758 print_import_config(&cb, name, nvroot, 0);
3759
3760 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_DEDUP);
3761 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
3762 print_class_vdevs(NULL, &cb, nvroot, VDEV_ALLOC_CLASS_LOGS);
3763
3764 if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
3765 (void) printf(gettext("\n\t%sAdditional devices are known to "
3766 "be part of this pool, though their\n"
3767 "\t%sexact configuration cannot be determined.\n"),
3768 indent, indent);
3769 }
3770 return (0);
3771 }
3772
3773 static boolean_t
zfs_force_import_required(nvlist_t * config)3774 zfs_force_import_required(nvlist_t *config)
3775 {
3776 uint64_t state;
3777 uint64_t hostid = 0;
3778 nvlist_t *nvinfo;
3779
3780 state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
3781 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3782
3783 /*
3784 * The hostid on LOAD_INFO comes from the MOS label via
3785 * spa_tryimport(). If its not there then we're likely talking to an
3786 * older kernel, so use the top one, which will be from the label
3787 * discovered in zpool_find_import(), or if a cachefile is in use, the
3788 * local hostid.
3789 */
3790 if (nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_HOSTID, &hostid) != 0)
3791 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
3792 &hostid);
3793
3794 if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
3795 return (B_TRUE);
3796
3797 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
3798 mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
3799 ZPOOL_CONFIG_MMP_STATE);
3800
3801 if (mmp_state != MMP_STATE_INACTIVE)
3802 return (B_TRUE);
3803 }
3804
3805 return (B_FALSE);
3806 }
3807
3808 /*
3809 * Perform the import for the given configuration. This passes the heavy
3810 * lifting off to zpool_import_props(), and then mounts the datasets contained
3811 * within the pool.
3812 */
3813 static int
do_import(nvlist_t * config,const char * newname,const char * mntopts,nvlist_t * props,int flags,uint_t mntthreads)3814 do_import(nvlist_t *config, const char *newname, const char *mntopts,
3815 nvlist_t *props, int flags, uint_t mntthreads)
3816 {
3817 int ret = 0;
3818 int ms_status = 0;
3819 zpool_handle_t *zhp;
3820 const char *name;
3821 uint64_t version;
3822
3823 name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
3824 version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3825
3826 if (!SPA_VERSION_IS_SUPPORTED(version)) {
3827 (void) fprintf(stderr, gettext("cannot import '%s': pool "
3828 "is formatted using an unsupported ZFS version\n"), name);
3829 return (1);
3830 } else if (zfs_force_import_required(config) &&
3831 !(flags & ZFS_IMPORT_ANY_HOST)) {
3832 mmp_state_t mmp_state = MMP_STATE_INACTIVE;
3833 nvlist_t *nvinfo;
3834
3835 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
3836 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE))
3837 mmp_state = fnvlist_lookup_uint64(nvinfo,
3838 ZPOOL_CONFIG_MMP_STATE);
3839
3840 if (mmp_state == MMP_STATE_ACTIVE) {
3841 const char *hostname = "<unknown>";
3842 uint64_t hostid = 0;
3843
3844 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
3845 hostname = fnvlist_lookup_string(nvinfo,
3846 ZPOOL_CONFIG_MMP_HOSTNAME);
3847
3848 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
3849 hostid = fnvlist_lookup_uint64(nvinfo,
3850 ZPOOL_CONFIG_MMP_HOSTID);
3851
3852 (void) fprintf(stderr, gettext("cannot import '%s': "
3853 "pool is imported on %s (hostid: "
3854 "0x%"PRIx64")\nExport the pool on the other "
3855 "system, then run 'zpool import'.\n"),
3856 name, hostname, hostid);
3857 } else if (mmp_state == MMP_STATE_NO_HOSTID) {
3858 (void) fprintf(stderr, gettext("Cannot import '%s': "
3859 "pool has the multihost property on and the\n"
3860 "system's hostid is not set. Set a unique hostid "
3861 "with the zgenhostid(8) command.\n"), name);
3862 } else {
3863 const char *hostname = "<unknown>";
3864 time_t timestamp = 0;
3865 uint64_t hostid = 0;
3866
3867 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTNAME))
3868 hostname = fnvlist_lookup_string(nvinfo,
3869 ZPOOL_CONFIG_HOSTNAME);
3870 else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTNAME))
3871 hostname = fnvlist_lookup_string(config,
3872 ZPOOL_CONFIG_HOSTNAME);
3873
3874 if (nvlist_exists(config, ZPOOL_CONFIG_TIMESTAMP))
3875 timestamp = fnvlist_lookup_uint64(config,
3876 ZPOOL_CONFIG_TIMESTAMP);
3877
3878 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_HOSTID))
3879 hostid = fnvlist_lookup_uint64(nvinfo,
3880 ZPOOL_CONFIG_HOSTID);
3881 else if (nvlist_exists(config, ZPOOL_CONFIG_HOSTID))
3882 hostid = fnvlist_lookup_uint64(config,
3883 ZPOOL_CONFIG_HOSTID);
3884
3885 (void) fprintf(stderr, gettext("cannot import '%s': "
3886 "pool was previously in use from another system.\n"
3887 "Last accessed by %s (hostid=%"PRIx64") at %s"
3888 "The pool can be imported, use 'zpool import -f' "
3889 "to import the pool.\n"), name, hostname,
3890 hostid, ctime(×tamp));
3891 }
3892
3893 if (getenv("ZFS_LOAD_INFO_DEBUG"))
3894 dump_nvlist(nvinfo, 4);
3895
3896 return (1);
3897 }
3898
3899 if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
3900 return (1);
3901
3902 if (newname != NULL)
3903 name = newname;
3904
3905 if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
3906 return (1);
3907
3908 /*
3909 * Loading keys is best effort. We don't want to return immediately
3910 * if it fails but we do want to give the error to the caller.
3911 */
3912 if (flags & ZFS_IMPORT_LOAD_KEYS &&
3913 zfs_crypto_attempt_load_keys(g_zfs, name) != 0)
3914 ret = 1;
3915
3916 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3917 !(flags & ZFS_IMPORT_ONLY)) {
3918 ms_status = zpool_enable_datasets(zhp, mntopts, 0, mntthreads);
3919 if (ms_status == EZFS_SHAREFAILED) {
3920 (void) fprintf(stderr, gettext("Import was "
3921 "successful, but unable to share some datasets\n"));
3922 } else if (ms_status == EZFS_MOUNTFAILED) {
3923 (void) fprintf(stderr, gettext("Import was "
3924 "successful, but unable to mount some datasets\n"));
3925 }
3926 }
3927
3928 zpool_close(zhp);
3929 return (ret);
3930 }
3931
3932 typedef struct import_parameters {
3933 nvlist_t *ip_config;
3934 const char *ip_mntopts;
3935 nvlist_t *ip_props;
3936 int ip_flags;
3937 uint_t ip_mntthreads;
3938 int *ip_err;
3939 } import_parameters_t;
3940
3941 static void
do_import_task(void * arg)3942 do_import_task(void *arg)
3943 {
3944 import_parameters_t *ip = arg;
3945 *ip->ip_err |= do_import(ip->ip_config, NULL, ip->ip_mntopts,
3946 ip->ip_props, ip->ip_flags, ip->ip_mntthreads);
3947 free(ip);
3948 }
3949
3950
3951 static int
import_pools(nvlist_t * pools,nvlist_t * props,char * mntopts,int flags,char * orig_name,char * new_name,importargs_t * import)3952 import_pools(nvlist_t *pools, nvlist_t *props, char *mntopts, int flags,
3953 char *orig_name, char *new_name, importargs_t *import)
3954 {
3955 nvlist_t *config = NULL;
3956 nvlist_t *found_config = NULL;
3957 uint64_t pool_state;
3958 boolean_t pool_specified = (import->poolname != NULL ||
3959 import->guid != 0);
3960 uint_t npools = 0;
3961
3962
3963 taskq_t *tq = NULL;
3964 if (import->do_all) {
3965 tq = taskq_create("zpool_import_all",
3966 5 * sysconf(_SC_NPROCESSORS_ONLN), minclsyspri, 1, INT_MAX,
3967 TASKQ_DYNAMIC);
3968 }
3969
3970 /*
3971 * At this point we have a list of import candidate configs. Even if
3972 * we were searching by pool name or guid, we still need to
3973 * post-process the list to deal with pool state and possible
3974 * duplicate names.
3975 */
3976 int err = 0;
3977 nvpair_t *elem = NULL;
3978 boolean_t first = B_TRUE;
3979 if (!pool_specified && import->do_all) {
3980 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL)
3981 npools++;
3982 }
3983 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3984
3985 verify(nvpair_value_nvlist(elem, &config) == 0);
3986
3987 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
3988 &pool_state) == 0);
3989 if (!import->do_destroyed &&
3990 pool_state == POOL_STATE_DESTROYED)
3991 continue;
3992 if (import->do_destroyed &&
3993 pool_state != POOL_STATE_DESTROYED)
3994 continue;
3995
3996 verify(nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
3997 import->policy) == 0);
3998
3999 if (!pool_specified) {
4000 if (first)
4001 first = B_FALSE;
4002 else if (!import->do_all)
4003 (void) fputc('\n', stdout);
4004
4005 if (import->do_all) {
4006 import_parameters_t *ip = safe_malloc(
4007 sizeof (import_parameters_t));
4008
4009 ip->ip_config = config;
4010 ip->ip_mntopts = mntopts;
4011 ip->ip_props = props;
4012 ip->ip_flags = flags;
4013 ip->ip_mntthreads = mount_tp_nthr / npools;
4014 ip->ip_err = &err;
4015
4016 (void) taskq_dispatch(tq, do_import_task,
4017 (void *)ip, TQ_SLEEP);
4018 } else {
4019 /*
4020 * If we're importing from cachefile, then
4021 * we don't want to report errors until we
4022 * are in the scan phase of the import. If
4023 * we get an error, then we return that error
4024 * to invoke the scan phase.
4025 */
4026 if (import->cachefile && !import->scan)
4027 err = show_import(config, B_FALSE);
4028 else
4029 (void) show_import(config, B_TRUE);
4030 }
4031 } else if (import->poolname != NULL) {
4032 const char *name;
4033
4034 /*
4035 * We are searching for a pool based on name.
4036 */
4037 verify(nvlist_lookup_string(config,
4038 ZPOOL_CONFIG_POOL_NAME, &name) == 0);
4039
4040 if (strcmp(name, import->poolname) == 0) {
4041 if (found_config != NULL) {
4042 (void) fprintf(stderr, gettext(
4043 "cannot import '%s': more than "
4044 "one matching pool\n"),
4045 import->poolname);
4046 (void) fprintf(stderr, gettext(
4047 "import by numeric ID instead\n"));
4048 err = B_TRUE;
4049 }
4050 found_config = config;
4051 }
4052 } else {
4053 uint64_t guid;
4054
4055 /*
4056 * Search for a pool by guid.
4057 */
4058 verify(nvlist_lookup_uint64(config,
4059 ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
4060
4061 if (guid == import->guid)
4062 found_config = config;
4063 }
4064 }
4065 if (import->do_all) {
4066 taskq_wait(tq);
4067 taskq_destroy(tq);
4068 }
4069
4070 /*
4071 * If we were searching for a specific pool, verify that we found a
4072 * pool, and then do the import.
4073 */
4074 if (pool_specified && err == 0) {
4075 if (found_config == NULL) {
4076 (void) fprintf(stderr, gettext("cannot import '%s': "
4077 "no such pool available\n"), orig_name);
4078 err = B_TRUE;
4079 } else {
4080 err |= do_import(found_config, new_name,
4081 mntopts, props, flags, mount_tp_nthr);
4082 }
4083 }
4084
4085 /*
4086 * If we were just looking for pools, report an error if none were
4087 * found.
4088 */
4089 if (!pool_specified && first)
4090 (void) fprintf(stderr,
4091 gettext("no pools available to import\n"));
4092 return (err);
4093 }
4094
4095 typedef struct target_exists_args {
4096 const char *poolname;
4097 uint64_t poolguid;
4098 } target_exists_args_t;
4099
4100 static int
name_or_guid_exists(zpool_handle_t * zhp,void * data)4101 name_or_guid_exists(zpool_handle_t *zhp, void *data)
4102 {
4103 target_exists_args_t *args = data;
4104 nvlist_t *config = zpool_get_config(zhp, NULL);
4105 int found = 0;
4106
4107 if (config == NULL)
4108 return (0);
4109
4110 if (args->poolname != NULL) {
4111 const char *pool_name;
4112
4113 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4114 &pool_name) == 0);
4115 if (strcmp(pool_name, args->poolname) == 0)
4116 found = 1;
4117 } else {
4118 uint64_t pool_guid;
4119
4120 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4121 &pool_guid) == 0);
4122 if (pool_guid == args->poolguid)
4123 found = 1;
4124 }
4125 zpool_close(zhp);
4126
4127 return (found);
4128 }
4129 /*
4130 * zpool checkpoint <pool>
4131 * checkpoint --discard <pool>
4132 *
4133 * -d Discard the checkpoint from a checkpointed
4134 * --discard pool.
4135 *
4136 * -w Wait for discarding a checkpoint to complete.
4137 * --wait
4138 *
4139 * Checkpoints the specified pool, by taking a "snapshot" of its
4140 * current state. A pool can only have one checkpoint at a time.
4141 */
4142 int
zpool_do_checkpoint(int argc,char ** argv)4143 zpool_do_checkpoint(int argc, char **argv)
4144 {
4145 boolean_t discard, wait;
4146 char *pool;
4147 zpool_handle_t *zhp;
4148 int c, err;
4149
4150 struct option long_options[] = {
4151 {"discard", no_argument, NULL, 'd'},
4152 {"wait", no_argument, NULL, 'w'},
4153 {0, 0, 0, 0}
4154 };
4155
4156 discard = B_FALSE;
4157 wait = B_FALSE;
4158 while ((c = getopt_long(argc, argv, ":dw", long_options, NULL)) != -1) {
4159 switch (c) {
4160 case 'd':
4161 discard = B_TRUE;
4162 break;
4163 case 'w':
4164 wait = B_TRUE;
4165 break;
4166 case '?':
4167 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4168 optopt);
4169 usage(B_FALSE);
4170 }
4171 }
4172
4173 if (wait && !discard) {
4174 (void) fprintf(stderr, gettext("--wait only valid when "
4175 "--discard also specified\n"));
4176 usage(B_FALSE);
4177 }
4178
4179 argc -= optind;
4180 argv += optind;
4181
4182 if (argc < 1) {
4183 (void) fprintf(stderr, gettext("missing pool argument\n"));
4184 usage(B_FALSE);
4185 }
4186
4187 if (argc > 1) {
4188 (void) fprintf(stderr, gettext("too many arguments\n"));
4189 usage(B_FALSE);
4190 }
4191
4192 pool = argv[0];
4193
4194 if ((zhp = zpool_open(g_zfs, pool)) == NULL) {
4195 /* As a special case, check for use of '/' in the name */
4196 if (strchr(pool, '/') != NULL)
4197 (void) fprintf(stderr, gettext("'zpool checkpoint' "
4198 "doesn't work on datasets. To save the state "
4199 "of a dataset from a specific point in time "
4200 "please use 'zfs snapshot'\n"));
4201 return (1);
4202 }
4203
4204 if (discard) {
4205 err = (zpool_discard_checkpoint(zhp) != 0);
4206 if (err == 0 && wait)
4207 err = zpool_wait(zhp, ZPOOL_WAIT_CKPT_DISCARD);
4208 } else {
4209 err = (zpool_checkpoint(zhp) != 0);
4210 }
4211
4212 zpool_close(zhp);
4213
4214 return (err);
4215 }
4216
4217 #define CHECKPOINT_OPT 1024
4218
4219 /*
4220 * zpool prefetch [-t <type>] <pool>
4221 *
4222 * Prefetchs a particular type of data in the specified pool.
4223 */
4224 int
zpool_do_prefetch(int argc,char ** argv)4225 zpool_do_prefetch(int argc, char **argv)
4226 {
4227 int c;
4228 char *poolname;
4229 char *typestr = NULL;
4230 zpool_prefetch_type_t type;
4231 zpool_handle_t *zhp;
4232 int err = 0;
4233
4234 while ((c = getopt(argc, argv, "t:")) != -1) {
4235 switch (c) {
4236 case 't':
4237 typestr = optarg;
4238 break;
4239 case ':':
4240 (void) fprintf(stderr, gettext("missing argument for "
4241 "'%c' option\n"), optopt);
4242 usage(B_FALSE);
4243 break;
4244 case '?':
4245 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4246 optopt);
4247 usage(B_FALSE);
4248 }
4249 }
4250 argc -= optind;
4251 argv += optind;
4252
4253 if (argc < 1) {
4254 (void) fprintf(stderr, gettext("missing pool name argument\n"));
4255 usage(B_FALSE);
4256 }
4257
4258 if (argc > 1) {
4259 (void) fprintf(stderr, gettext("too many arguments\n"));
4260 usage(B_FALSE);
4261 }
4262
4263 poolname = argv[0];
4264
4265 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
4266 return (1);
4267
4268 if (typestr == NULL) {
4269 /* Prefetch all types */
4270 err = zpool_prefetch(zhp, ZPOOL_PREFETCH_DDT);
4271 if (err == 0)
4272 err = zpool_prefetch(zhp, ZPOOL_PREFETCH_BRT);
4273 } else {
4274 if (strcmp(typestr, "ddt") == 0) {
4275 type = ZPOOL_PREFETCH_DDT;
4276 } else if (strcmp(typestr, "brt") == 0) {
4277 type = ZPOOL_PREFETCH_BRT;
4278 } else {
4279 (void) fprintf(stderr,
4280 gettext("unsupported prefetch type\n"));
4281 zpool_close(zhp);
4282 usage(B_FALSE);
4283 }
4284 err = zpool_prefetch(zhp, type);
4285 }
4286
4287 zpool_close(zhp);
4288
4289 return (err);
4290 }
4291
4292 /*
4293 * zpool import [-d dir] [-D]
4294 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4295 * [-d dir | -c cachefile | -s] [-f] -a
4296 * import [-o mntopts] [-o prop=value] ... [-R root] [-D] [-l]
4297 * [-d dir | -c cachefile | -s] [-f] [-n] [-F] <pool | id>
4298 * [newpool]
4299 *
4300 * -c Read pool information from a cachefile instead of searching
4301 * devices. If importing from a cachefile config fails, then
4302 * fallback to searching for devices only in the directories that
4303 * exist in the cachefile.
4304 *
4305 * -d Scan in a specific directory, other than /dev/. More than
4306 * one directory can be specified using multiple '-d' options.
4307 *
4308 * -D Scan for previously destroyed pools or import all or only
4309 * specified destroyed pools.
4310 *
4311 * -R Temporarily import the pool, with all mountpoints relative to
4312 * the given root. The pool will remain exported when the machine
4313 * is rebooted.
4314 *
4315 * -V Import even in the presence of faulted vdevs. This is an
4316 * intentionally undocumented option for testing purposes, and
4317 * treats the pool configuration as complete, leaving any bad
4318 * vdevs in the FAULTED state. In other words, it does verbatim
4319 * import.
4320 *
4321 * -f Force import, even if it appears that the pool is active.
4322 *
4323 * -F Attempt rewind if necessary.
4324 *
4325 * -n See if rewind would work, but don't actually rewind.
4326 *
4327 * -N Import the pool but don't mount datasets.
4328 *
4329 * -T Specify a starting txg to use for import. This option is
4330 * intentionally undocumented option for testing purposes.
4331 *
4332 * -a Import all pools found.
4333 *
4334 * -l Load encryption keys while importing.
4335 *
4336 * -o Set property=value and/or temporary mount options (without '=').
4337 *
4338 * -s Scan using the default search path, the libblkid cache will
4339 * not be consulted.
4340 *
4341 * --rewind-to-checkpoint
4342 * Import the pool and revert back to the checkpoint.
4343 *
4344 * The import command scans for pools to import, and import pools based on pool
4345 * name and GUID. The pool can also be renamed as part of the import process.
4346 */
4347 int
zpool_do_import(int argc,char ** argv)4348 zpool_do_import(int argc, char **argv)
4349 {
4350 char **searchdirs = NULL;
4351 char *env, *envdup = NULL;
4352 int nsearch = 0;
4353 int c;
4354 int err = 0;
4355 nvlist_t *pools = NULL;
4356 boolean_t do_all = B_FALSE;
4357 boolean_t do_destroyed = B_FALSE;
4358 char *mntopts = NULL;
4359 uint64_t searchguid = 0;
4360 char *searchname = NULL;
4361 char *propval;
4362 nvlist_t *policy = NULL;
4363 nvlist_t *props = NULL;
4364 int flags = ZFS_IMPORT_NORMAL;
4365 uint32_t rewind_policy = ZPOOL_NO_REWIND;
4366 boolean_t dryrun = B_FALSE;
4367 boolean_t do_rewind = B_FALSE;
4368 boolean_t xtreme_rewind = B_FALSE;
4369 boolean_t do_scan = B_FALSE;
4370 boolean_t pool_exists = B_FALSE;
4371 uint64_t txg = -1ULL;
4372 char *cachefile = NULL;
4373 importargs_t idata = { 0 };
4374 char *endptr;
4375
4376 struct option long_options[] = {
4377 {"rewind-to-checkpoint", no_argument, NULL, CHECKPOINT_OPT},
4378 {0, 0, 0, 0}
4379 };
4380
4381 /* check options */
4382 while ((c = getopt_long(argc, argv, ":aCc:d:DEfFlmnNo:R:stT:VX",
4383 long_options, NULL)) != -1) {
4384 switch (c) {
4385 case 'a':
4386 do_all = B_TRUE;
4387 break;
4388 case 'c':
4389 cachefile = optarg;
4390 break;
4391 case 'd':
4392 searchdirs = safe_realloc(searchdirs,
4393 (nsearch + 1) * sizeof (char *));
4394 searchdirs[nsearch++] = optarg;
4395 break;
4396 case 'D':
4397 do_destroyed = B_TRUE;
4398 break;
4399 case 'f':
4400 flags |= ZFS_IMPORT_ANY_HOST;
4401 break;
4402 case 'F':
4403 do_rewind = B_TRUE;
4404 break;
4405 case 'l':
4406 flags |= ZFS_IMPORT_LOAD_KEYS;
4407 break;
4408 case 'm':
4409 flags |= ZFS_IMPORT_MISSING_LOG;
4410 break;
4411 case 'n':
4412 dryrun = B_TRUE;
4413 break;
4414 case 'N':
4415 flags |= ZFS_IMPORT_ONLY;
4416 break;
4417 case 'o':
4418 if ((propval = strchr(optarg, '=')) != NULL) {
4419 *propval = '\0';
4420 propval++;
4421 if (add_prop_list(optarg, propval,
4422 &props, B_TRUE))
4423 goto error;
4424 } else {
4425 mntopts = optarg;
4426 }
4427 break;
4428 case 'R':
4429 if (add_prop_list(zpool_prop_to_name(
4430 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
4431 goto error;
4432 if (add_prop_list_default(zpool_prop_to_name(
4433 ZPOOL_PROP_CACHEFILE), "none", &props))
4434 goto error;
4435 break;
4436 case 's':
4437 do_scan = B_TRUE;
4438 break;
4439 case 't':
4440 flags |= ZFS_IMPORT_TEMP_NAME;
4441 if (add_prop_list_default(zpool_prop_to_name(
4442 ZPOOL_PROP_CACHEFILE), "none", &props))
4443 goto error;
4444 break;
4445
4446 case 'T':
4447 errno = 0;
4448 txg = strtoull(optarg, &endptr, 0);
4449 if (errno != 0 || *endptr != '\0') {
4450 (void) fprintf(stderr,
4451 gettext("invalid txg value\n"));
4452 usage(B_FALSE);
4453 }
4454 rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
4455 break;
4456 case 'V':
4457 flags |= ZFS_IMPORT_VERBATIM;
4458 break;
4459 case 'X':
4460 xtreme_rewind = B_TRUE;
4461 break;
4462 case CHECKPOINT_OPT:
4463 flags |= ZFS_IMPORT_CHECKPOINT;
4464 break;
4465 case ':':
4466 (void) fprintf(stderr, gettext("missing argument for "
4467 "'%c' option\n"), optopt);
4468 usage(B_FALSE);
4469 break;
4470 case '?':
4471 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4472 optopt);
4473 usage(B_FALSE);
4474 }
4475 }
4476
4477 argc -= optind;
4478 argv += optind;
4479
4480 if (cachefile && nsearch != 0) {
4481 (void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
4482 usage(B_FALSE);
4483 }
4484
4485 if (cachefile && do_scan) {
4486 (void) fprintf(stderr, gettext("-c is incompatible with -s\n"));
4487 usage(B_FALSE);
4488 }
4489
4490 if ((flags & ZFS_IMPORT_LOAD_KEYS) && (flags & ZFS_IMPORT_ONLY)) {
4491 (void) fprintf(stderr, gettext("-l is incompatible with -N\n"));
4492 usage(B_FALSE);
4493 }
4494
4495 if ((flags & ZFS_IMPORT_LOAD_KEYS) && !do_all && argc == 0) {
4496 (void) fprintf(stderr, gettext("-l is only meaningful during "
4497 "an import\n"));
4498 usage(B_FALSE);
4499 }
4500
4501 if ((dryrun || xtreme_rewind) && !do_rewind) {
4502 (void) fprintf(stderr,
4503 gettext("-n or -X only meaningful with -F\n"));
4504 usage(B_FALSE);
4505 }
4506 if (dryrun)
4507 rewind_policy = ZPOOL_TRY_REWIND;
4508 else if (do_rewind)
4509 rewind_policy = ZPOOL_DO_REWIND;
4510 if (xtreme_rewind)
4511 rewind_policy |= ZPOOL_EXTREME_REWIND;
4512
4513 /* In the future, we can capture further policy and include it here */
4514 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
4515 nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, txg) != 0 ||
4516 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY,
4517 rewind_policy) != 0)
4518 goto error;
4519
4520 /* check argument count */
4521 if (do_all) {
4522 if (argc != 0) {
4523 (void) fprintf(stderr, gettext("too many arguments\n"));
4524 usage(B_FALSE);
4525 }
4526 } else {
4527 if (argc > 2) {
4528 (void) fprintf(stderr, gettext("too many arguments\n"));
4529 usage(B_FALSE);
4530 }
4531 }
4532
4533 /*
4534 * Check for the effective uid. We do this explicitly here because
4535 * otherwise any attempt to discover pools will silently fail.
4536 */
4537 if (argc == 0 && geteuid() != 0) {
4538 (void) fprintf(stderr, gettext("cannot "
4539 "discover pools: permission denied\n"));
4540
4541 free(searchdirs);
4542 nvlist_free(props);
4543 nvlist_free(policy);
4544 return (1);
4545 }
4546
4547 /*
4548 * Depending on the arguments given, we do one of the following:
4549 *
4550 * <none> Iterate through all pools and display information about
4551 * each one.
4552 *
4553 * -a Iterate through all pools and try to import each one.
4554 *
4555 * <id> Find the pool that corresponds to the given GUID/pool
4556 * name and import that one.
4557 *
4558 * -D Above options applies only to destroyed pools.
4559 */
4560 if (argc != 0) {
4561 char *endptr;
4562
4563 errno = 0;
4564 searchguid = strtoull(argv[0], &endptr, 10);
4565 if (errno != 0 || *endptr != '\0') {
4566 searchname = argv[0];
4567 searchguid = 0;
4568 }
4569
4570 /*
4571 * User specified a name or guid. Ensure it's unique.
4572 */
4573 target_exists_args_t search = {searchname, searchguid};
4574 pool_exists = zpool_iter(g_zfs, name_or_guid_exists, &search);
4575 }
4576
4577 /*
4578 * Check the environment for the preferred search path.
4579 */
4580 if ((searchdirs == NULL) && (env = getenv("ZPOOL_IMPORT_PATH"))) {
4581 char *dir, *tmp = NULL;
4582
4583 envdup = strdup(env);
4584
4585 for (dir = strtok_r(envdup, ":", &tmp);
4586 dir != NULL;
4587 dir = strtok_r(NULL, ":", &tmp)) {
4588 searchdirs = safe_realloc(searchdirs,
4589 (nsearch + 1) * sizeof (char *));
4590 searchdirs[nsearch++] = dir;
4591 }
4592 }
4593
4594 idata.path = searchdirs;
4595 idata.paths = nsearch;
4596 idata.poolname = searchname;
4597 idata.guid = searchguid;
4598 idata.cachefile = cachefile;
4599 idata.scan = do_scan;
4600 idata.policy = policy;
4601 idata.do_destroyed = do_destroyed;
4602 idata.do_all = do_all;
4603
4604 libpc_handle_t lpch = {
4605 .lpc_lib_handle = g_zfs,
4606 .lpc_ops = &libzfs_config_ops,
4607 .lpc_printerr = B_TRUE
4608 };
4609 pools = zpool_search_import(&lpch, &idata);
4610
4611 if (pools != NULL && pool_exists &&
4612 (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
4613 (void) fprintf(stderr, gettext("cannot import '%s': "
4614 "a pool with that name already exists\n"),
4615 argv[0]);
4616 (void) fprintf(stderr, gettext("use the form '%s "
4617 "<pool | id> <newpool>' to give it a new name\n"),
4618 "zpool import");
4619 err = 1;
4620 } else if (pools == NULL && pool_exists) {
4621 (void) fprintf(stderr, gettext("cannot import '%s': "
4622 "a pool with that name is already created/imported,\n"),
4623 argv[0]);
4624 (void) fprintf(stderr, gettext("and no additional pools "
4625 "with that name were found\n"));
4626 err = 1;
4627 } else if (pools == NULL) {
4628 if (argc != 0) {
4629 (void) fprintf(stderr, gettext("cannot import '%s': "
4630 "no such pool available\n"), argv[0]);
4631 }
4632 err = 1;
4633 }
4634
4635 if (err == 1) {
4636 free(searchdirs);
4637 free(envdup);
4638 nvlist_free(policy);
4639 nvlist_free(pools);
4640 nvlist_free(props);
4641 return (1);
4642 }
4643
4644 err = import_pools(pools, props, mntopts, flags,
4645 argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL, &idata);
4646
4647 /*
4648 * If we're using the cachefile and we failed to import, then
4649 * fallback to scanning the directory for pools that match
4650 * those in the cachefile.
4651 */
4652 if (err != 0 && cachefile != NULL) {
4653 (void) printf(gettext("cachefile import failed, retrying\n"));
4654
4655 /*
4656 * We use the scan flag to gather the directories that exist
4657 * in the cachefile. If we need to fallback to searching for
4658 * the pool config, we will only search devices in these
4659 * directories.
4660 */
4661 idata.scan = B_TRUE;
4662 nvlist_free(pools);
4663 pools = zpool_search_import(&lpch, &idata);
4664
4665 err = import_pools(pools, props, mntopts, flags,
4666 argc >= 1 ? argv[0] : NULL, argc >= 2 ? argv[1] : NULL,
4667 &idata);
4668 }
4669
4670 error:
4671 nvlist_free(props);
4672 nvlist_free(pools);
4673 nvlist_free(policy);
4674 free(searchdirs);
4675 free(envdup);
4676
4677 return (err ? 1 : 0);
4678 }
4679
4680 /*
4681 * zpool sync [-f] [pool] ...
4682 *
4683 * -f (undocumented) force uberblock (and config including zpool cache file)
4684 * update.
4685 *
4686 * Sync the specified pool(s).
4687 * Without arguments "zpool sync" will sync all pools.
4688 * This command initiates TXG sync(s) and will return after the TXG(s) commit.
4689 *
4690 */
4691 static int
zpool_do_sync(int argc,char ** argv)4692 zpool_do_sync(int argc, char **argv)
4693 {
4694 int ret;
4695 boolean_t force = B_FALSE;
4696
4697 /* check options */
4698 while ((ret = getopt(argc, argv, "f")) != -1) {
4699 switch (ret) {
4700 case 'f':
4701 force = B_TRUE;
4702 break;
4703 case '?':
4704 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4705 optopt);
4706 usage(B_FALSE);
4707 }
4708 }
4709
4710 argc -= optind;
4711 argv += optind;
4712
4713 /* if argc == 0 we will execute zpool_sync_one on all pools */
4714 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
4715 B_FALSE, zpool_sync_one, &force);
4716
4717 return (ret);
4718 }
4719
4720 typedef struct iostat_cbdata {
4721 uint64_t cb_flags;
4722 int cb_namewidth;
4723 int cb_iteration;
4724 boolean_t cb_verbose;
4725 boolean_t cb_literal;
4726 boolean_t cb_scripted;
4727 zpool_list_t *cb_list;
4728 vdev_cmd_data_list_t *vcdl;
4729 vdev_cbdata_t cb_vdevs;
4730 } iostat_cbdata_t;
4731
4732 /* iostat labels */
4733 typedef struct name_and_columns {
4734 const char *name; /* Column name */
4735 unsigned int columns; /* Center name to this number of columns */
4736 } name_and_columns_t;
4737
4738 #define IOSTAT_MAX_LABELS 15 /* Max number of labels on one line */
4739
4740 static const name_and_columns_t iostat_top_labels[][IOSTAT_MAX_LABELS] =
4741 {
4742 [IOS_DEFAULT] = {{"capacity", 2}, {"operations", 2}, {"bandwidth", 2},
4743 {NULL}},
4744 [IOS_LATENCY] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4745 {"asyncq_wait", 2}, {"scrub", 1}, {"trim", 1}, {"rebuild", 1},
4746 {NULL}},
4747 [IOS_QUEUES] = {{"syncq_read", 2}, {"syncq_write", 2},
4748 {"asyncq_read", 2}, {"asyncq_write", 2}, {"scrubq_read", 2},
4749 {"trimq_write", 2}, {"rebuildq_write", 2}, {NULL}},
4750 [IOS_L_HISTO] = {{"total_wait", 2}, {"disk_wait", 2}, {"syncq_wait", 2},
4751 {"asyncq_wait", 2}, {NULL}},
4752 [IOS_RQ_HISTO] = {{"sync_read", 2}, {"sync_write", 2},
4753 {"async_read", 2}, {"async_write", 2}, {"scrub", 2},
4754 {"trim", 2}, {"rebuild", 2}, {NULL}},
4755 };
4756
4757 /* Shorthand - if "columns" field not set, default to 1 column */
4758 static const name_and_columns_t iostat_bottom_labels[][IOSTAT_MAX_LABELS] =
4759 {
4760 [IOS_DEFAULT] = {{"alloc"}, {"free"}, {"read"}, {"write"}, {"read"},
4761 {"write"}, {NULL}},
4762 [IOS_LATENCY] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4763 {"write"}, {"read"}, {"write"}, {"wait"}, {"wait"}, {"wait"},
4764 {NULL}},
4765 [IOS_QUEUES] = {{"pend"}, {"activ"}, {"pend"}, {"activ"}, {"pend"},
4766 {"activ"}, {"pend"}, {"activ"}, {"pend"}, {"activ"},
4767 {"pend"}, {"activ"}, {"pend"}, {"activ"}, {NULL}},
4768 [IOS_L_HISTO] = {{"read"}, {"write"}, {"read"}, {"write"}, {"read"},
4769 {"write"}, {"read"}, {"write"}, {"scrub"}, {"trim"}, {"rebuild"},
4770 {NULL}},
4771 [IOS_RQ_HISTO] = {{"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4772 {"ind"}, {"agg"}, {"ind"}, {"agg"}, {"ind"}, {"agg"},
4773 {"ind"}, {"agg"}, {NULL}},
4774 };
4775
4776 static const char *histo_to_title[] = {
4777 [IOS_L_HISTO] = "latency",
4778 [IOS_RQ_HISTO] = "req_size",
4779 };
4780
4781 /*
4782 * Return the number of labels in a null-terminated name_and_columns_t
4783 * array.
4784 *
4785 */
4786 static unsigned int
label_array_len(const name_and_columns_t * labels)4787 label_array_len(const name_and_columns_t *labels)
4788 {
4789 int i = 0;
4790
4791 while (labels[i].name)
4792 i++;
4793
4794 return (i);
4795 }
4796
4797 /*
4798 * Return the number of strings in a null-terminated string array.
4799 * For example:
4800 *
4801 * const char foo[] = {"bar", "baz", NULL}
4802 *
4803 * returns 2
4804 */
4805 static uint64_t
str_array_len(const char * array[])4806 str_array_len(const char *array[])
4807 {
4808 uint64_t i = 0;
4809 while (array[i])
4810 i++;
4811
4812 return (i);
4813 }
4814
4815
4816 /*
4817 * Return a default column width for default/latency/queue columns. This does
4818 * not include histograms, which have their columns autosized.
4819 */
4820 static unsigned int
default_column_width(iostat_cbdata_t * cb,enum iostat_type type)4821 default_column_width(iostat_cbdata_t *cb, enum iostat_type type)
4822 {
4823 unsigned long column_width = 5; /* Normal niceprint */
4824 static unsigned long widths[] = {
4825 /*
4826 * Choose some sane default column sizes for printing the
4827 * raw numbers.
4828 */
4829 [IOS_DEFAULT] = 15, /* 1PB capacity */
4830 [IOS_LATENCY] = 10, /* 1B ns = 10sec */
4831 [IOS_QUEUES] = 6, /* 1M queue entries */
4832 [IOS_L_HISTO] = 10, /* 1B ns = 10sec */
4833 [IOS_RQ_HISTO] = 6, /* 1M queue entries */
4834 };
4835
4836 if (cb->cb_literal)
4837 column_width = widths[type];
4838
4839 return (column_width);
4840 }
4841
4842 /*
4843 * Print the column labels, i.e:
4844 *
4845 * capacity operations bandwidth
4846 * alloc free read write read write ...
4847 *
4848 * If force_column_width is set, use it for the column width. If not set, use
4849 * the default column width.
4850 */
4851 static void
print_iostat_labels(iostat_cbdata_t * cb,unsigned int force_column_width,const name_and_columns_t labels[][IOSTAT_MAX_LABELS])4852 print_iostat_labels(iostat_cbdata_t *cb, unsigned int force_column_width,
4853 const name_and_columns_t labels[][IOSTAT_MAX_LABELS])
4854 {
4855 int i, idx, s;
4856 int text_start, rw_column_width, spaces_to_end;
4857 uint64_t flags = cb->cb_flags;
4858 uint64_t f;
4859 unsigned int column_width = force_column_width;
4860
4861 /* For each bit set in flags */
4862 for (f = flags; f; f &= ~(1ULL << idx)) {
4863 idx = lowbit64(f) - 1;
4864 if (!force_column_width)
4865 column_width = default_column_width(cb, idx);
4866 /* Print our top labels centered over "read write" label. */
4867 for (i = 0; i < label_array_len(labels[idx]); i++) {
4868 const char *name = labels[idx][i].name;
4869 /*
4870 * We treat labels[][].columns == 0 as shorthand
4871 * for one column. It makes writing out the label
4872 * tables more concise.
4873 */
4874 unsigned int columns = MAX(1, labels[idx][i].columns);
4875 unsigned int slen = strlen(name);
4876
4877 rw_column_width = (column_width * columns) +
4878 (2 * (columns - 1));
4879
4880 text_start = (int)((rw_column_width) / columns -
4881 slen / columns);
4882 if (text_start < 0)
4883 text_start = 0;
4884
4885 printf(" "); /* Two spaces between columns */
4886
4887 /* Space from beginning of column to label */
4888 for (s = 0; s < text_start; s++)
4889 printf(" ");
4890
4891 printf("%s", name);
4892
4893 /* Print space after label to end of column */
4894 spaces_to_end = rw_column_width - text_start - slen;
4895 if (spaces_to_end < 0)
4896 spaces_to_end = 0;
4897
4898 for (s = 0; s < spaces_to_end; s++)
4899 printf(" ");
4900 }
4901 }
4902 }
4903
4904
4905 /*
4906 * print_cmd_columns - Print custom column titles from -c
4907 *
4908 * If the user specified the "zpool status|iostat -c" then print their custom
4909 * column titles in the header. For example, print_cmd_columns() would print
4910 * the " col1 col2" part of this:
4911 *
4912 * $ zpool iostat -vc 'echo col1=val1; echo col2=val2'
4913 * ...
4914 * capacity operations bandwidth
4915 * pool alloc free read write read write col1 col2
4916 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4917 * mypool 269K 1008M 0 0 107 946
4918 * mirror 269K 1008M 0 0 107 946
4919 * sdb - - 0 0 102 473 val1 val2
4920 * sdc - - 0 0 5 473 val1 val2
4921 * ---------- ----- ----- ----- ----- ----- ----- ---- ----
4922 */
4923 static void
print_cmd_columns(vdev_cmd_data_list_t * vcdl,int use_dashes)4924 print_cmd_columns(vdev_cmd_data_list_t *vcdl, int use_dashes)
4925 {
4926 int i, j;
4927 vdev_cmd_data_t *data = &vcdl->data[0];
4928
4929 if (vcdl->count == 0 || data == NULL)
4930 return;
4931
4932 /*
4933 * Each vdev cmd should have the same column names unless the user did
4934 * something weird with their cmd. Just take the column names from the
4935 * first vdev and assume it works for all of them.
4936 */
4937 for (i = 0; i < vcdl->uniq_cols_cnt; i++) {
4938 printf(" ");
4939 if (use_dashes) {
4940 for (j = 0; j < vcdl->uniq_cols_width[i]; j++)
4941 printf("-");
4942 } else {
4943 (void) printf_color(ANSI_BOLD, "%*s",
4944 vcdl->uniq_cols_width[i],
4945 vcdl->uniq_cols[i]);
4946 }
4947 }
4948 }
4949
4950
4951 /*
4952 * Utility function to print out a line of dashes like:
4953 *
4954 * -------------------------------- ----- ----- ----- ----- -----
4955 *
4956 * ...or a dashed named-row line like:
4957 *
4958 * logs - - - - -
4959 *
4960 * @cb: iostat data
4961 *
4962 * @force_column_width If non-zero, use the value as the column width.
4963 * Otherwise use the default column widths.
4964 *
4965 * @name: Print a dashed named-row line starting
4966 * with @name. Otherwise, print a regular
4967 * dashed line.
4968 */
4969 static void
print_iostat_dashes(iostat_cbdata_t * cb,unsigned int force_column_width,const char * name)4970 print_iostat_dashes(iostat_cbdata_t *cb, unsigned int force_column_width,
4971 const char *name)
4972 {
4973 int i;
4974 unsigned int namewidth;
4975 uint64_t flags = cb->cb_flags;
4976 uint64_t f;
4977 int idx;
4978 const name_and_columns_t *labels;
4979 const char *title;
4980
4981
4982 if (cb->cb_flags & IOS_ANYHISTO_M) {
4983 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
4984 } else if (cb->cb_vdevs.cb_names_count) {
4985 title = "vdev";
4986 } else {
4987 title = "pool";
4988 }
4989
4990 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
4991 name ? strlen(name) : 0);
4992
4993
4994 if (name) {
4995 printf("%-*s", namewidth, name);
4996 } else {
4997 for (i = 0; i < namewidth; i++)
4998 (void) printf("-");
4999 }
5000
5001 /* For each bit in flags */
5002 for (f = flags; f; f &= ~(1ULL << idx)) {
5003 unsigned int column_width;
5004 idx = lowbit64(f) - 1;
5005 if (force_column_width)
5006 column_width = force_column_width;
5007 else
5008 column_width = default_column_width(cb, idx);
5009
5010 labels = iostat_bottom_labels[idx];
5011 for (i = 0; i < label_array_len(labels); i++) {
5012 if (name)
5013 printf(" %*s-", column_width - 1, " ");
5014 else
5015 printf(" %.*s", column_width,
5016 "--------------------");
5017 }
5018 }
5019 }
5020
5021
5022 static void
print_iostat_separator_impl(iostat_cbdata_t * cb,unsigned int force_column_width)5023 print_iostat_separator_impl(iostat_cbdata_t *cb,
5024 unsigned int force_column_width)
5025 {
5026 print_iostat_dashes(cb, force_column_width, NULL);
5027 }
5028
5029 static void
print_iostat_separator(iostat_cbdata_t * cb)5030 print_iostat_separator(iostat_cbdata_t *cb)
5031 {
5032 print_iostat_separator_impl(cb, 0);
5033 }
5034
5035 static void
print_iostat_header_impl(iostat_cbdata_t * cb,unsigned int force_column_width,const char * histo_vdev_name)5036 print_iostat_header_impl(iostat_cbdata_t *cb, unsigned int force_column_width,
5037 const char *histo_vdev_name)
5038 {
5039 unsigned int namewidth;
5040 const char *title;
5041
5042 color_start(ANSI_BOLD);
5043
5044 if (cb->cb_flags & IOS_ANYHISTO_M) {
5045 title = histo_to_title[IOS_HISTO_IDX(cb->cb_flags)];
5046 } else if (cb->cb_vdevs.cb_names_count) {
5047 title = "vdev";
5048 } else {
5049 title = "pool";
5050 }
5051
5052 namewidth = MAX(MAX(strlen(title), cb->cb_namewidth),
5053 histo_vdev_name ? strlen(histo_vdev_name) : 0);
5054
5055 if (histo_vdev_name)
5056 printf("%-*s", namewidth, histo_vdev_name);
5057 else
5058 printf("%*s", namewidth, "");
5059
5060
5061 print_iostat_labels(cb, force_column_width, iostat_top_labels);
5062 printf("\n");
5063
5064 printf("%-*s", namewidth, title);
5065
5066 print_iostat_labels(cb, force_column_width, iostat_bottom_labels);
5067 if (cb->vcdl != NULL)
5068 print_cmd_columns(cb->vcdl, 0);
5069
5070 printf("\n");
5071
5072 print_iostat_separator_impl(cb, force_column_width);
5073
5074 if (cb->vcdl != NULL)
5075 print_cmd_columns(cb->vcdl, 1);
5076
5077 color_end();
5078
5079 printf("\n");
5080 }
5081
5082 static void
print_iostat_header(iostat_cbdata_t * cb)5083 print_iostat_header(iostat_cbdata_t *cb)
5084 {
5085 print_iostat_header_impl(cb, 0, NULL);
5086 }
5087
5088 /*
5089 * Prints a size string (i.e. 120M) with the suffix ("M") colored
5090 * by order of magnitude. Uses column_size to add padding.
5091 */
5092 static void
print_stat_color(const char * statbuf,unsigned int column_size)5093 print_stat_color(const char *statbuf, unsigned int column_size)
5094 {
5095 (void) fputs(" ", stdout);
5096 size_t len = strlen(statbuf);
5097 while (len < column_size) {
5098 (void) fputc(' ', stdout);
5099 column_size--;
5100 }
5101 if (*statbuf == '0') {
5102 color_start(ANSI_GRAY);
5103 (void) fputc('0', stdout);
5104 } else {
5105 for (; *statbuf; statbuf++) {
5106 if (*statbuf == 'K') color_start(ANSI_GREEN);
5107 else if (*statbuf == 'M') color_start(ANSI_YELLOW);
5108 else if (*statbuf == 'G') color_start(ANSI_RED);
5109 else if (*statbuf == 'T') color_start(ANSI_BOLD_BLUE);
5110 else if (*statbuf == 'P') color_start(ANSI_MAGENTA);
5111 else if (*statbuf == 'E') color_start(ANSI_CYAN);
5112 (void) fputc(*statbuf, stdout);
5113 if (--column_size <= 0)
5114 break;
5115 }
5116 }
5117 color_end();
5118 }
5119
5120 /*
5121 * Display a single statistic.
5122 */
5123 static void
print_one_stat(uint64_t value,enum zfs_nicenum_format format,unsigned int column_size,boolean_t scripted)5124 print_one_stat(uint64_t value, enum zfs_nicenum_format format,
5125 unsigned int column_size, boolean_t scripted)
5126 {
5127 char buf[64];
5128
5129 zfs_nicenum_format(value, buf, sizeof (buf), format);
5130
5131 if (scripted)
5132 printf("\t%s", buf);
5133 else
5134 print_stat_color(buf, column_size);
5135 }
5136
5137 /*
5138 * Calculate the default vdev stats
5139 *
5140 * Subtract oldvs from newvs, apply a scaling factor, and save the resulting
5141 * stats into calcvs.
5142 */
5143 static void
calc_default_iostats(vdev_stat_t * oldvs,vdev_stat_t * newvs,vdev_stat_t * calcvs)5144 calc_default_iostats(vdev_stat_t *oldvs, vdev_stat_t *newvs,
5145 vdev_stat_t *calcvs)
5146 {
5147 int i;
5148
5149 memcpy(calcvs, newvs, sizeof (*calcvs));
5150 for (i = 0; i < ARRAY_SIZE(calcvs->vs_ops); i++)
5151 calcvs->vs_ops[i] = (newvs->vs_ops[i] - oldvs->vs_ops[i]);
5152
5153 for (i = 0; i < ARRAY_SIZE(calcvs->vs_bytes); i++)
5154 calcvs->vs_bytes[i] = (newvs->vs_bytes[i] - oldvs->vs_bytes[i]);
5155 }
5156
5157 /*
5158 * Internal representation of the extended iostats data.
5159 *
5160 * The extended iostat stats are exported in nvlists as either uint64_t arrays
5161 * or single uint64_t's. We make both look like arrays to make them easier
5162 * to process. In order to make single uint64_t's look like arrays, we set
5163 * __data to the stat data, and then set *data = &__data with count = 1. Then,
5164 * we can just use *data and count.
5165 */
5166 struct stat_array {
5167 uint64_t *data;
5168 uint_t count; /* Number of entries in data[] */
5169 uint64_t __data; /* Only used when data is a single uint64_t */
5170 };
5171
5172 static uint64_t
stat_histo_max(struct stat_array * nva,unsigned int len)5173 stat_histo_max(struct stat_array *nva, unsigned int len)
5174 {
5175 uint64_t max = 0;
5176 int i;
5177 for (i = 0; i < len; i++)
5178 max = MAX(max, array64_max(nva[i].data, nva[i].count));
5179
5180 return (max);
5181 }
5182
5183 /*
5184 * Helper function to lookup a uint64_t array or uint64_t value and store its
5185 * data as a stat_array. If the nvpair is a single uint64_t value, then we make
5186 * it look like a one element array to make it easier to process.
5187 */
5188 static int
nvpair64_to_stat_array(nvlist_t * nvl,const char * name,struct stat_array * nva)5189 nvpair64_to_stat_array(nvlist_t *nvl, const char *name,
5190 struct stat_array *nva)
5191 {
5192 nvpair_t *tmp;
5193 int ret;
5194
5195 verify(nvlist_lookup_nvpair(nvl, name, &tmp) == 0);
5196 switch (nvpair_type(tmp)) {
5197 case DATA_TYPE_UINT64_ARRAY:
5198 ret = nvpair_value_uint64_array(tmp, &nva->data, &nva->count);
5199 break;
5200 case DATA_TYPE_UINT64:
5201 ret = nvpair_value_uint64(tmp, &nva->__data);
5202 nva->data = &nva->__data;
5203 nva->count = 1;
5204 break;
5205 default:
5206 /* Not a uint64_t */
5207 ret = EINVAL;
5208 break;
5209 }
5210
5211 return (ret);
5212 }
5213
5214 /*
5215 * Given a list of nvlist names, look up the extended stats in newnv and oldnv,
5216 * subtract them, and return the results in a newly allocated stat_array.
5217 * You must free the returned array after you are done with it with
5218 * free_calc_stats().
5219 *
5220 * Additionally, you can set "oldnv" to NULL if you simply want the newnv
5221 * values.
5222 */
5223 static struct stat_array *
calc_and_alloc_stats_ex(const char ** names,unsigned int len,nvlist_t * oldnv,nvlist_t * newnv)5224 calc_and_alloc_stats_ex(const char **names, unsigned int len, nvlist_t *oldnv,
5225 nvlist_t *newnv)
5226 {
5227 nvlist_t *oldnvx = NULL, *newnvx;
5228 struct stat_array *oldnva, *newnva, *calcnva;
5229 int i, j;
5230 unsigned int alloc_size = (sizeof (struct stat_array)) * len;
5231
5232 /* Extract our extended stats nvlist from the main list */
5233 verify(nvlist_lookup_nvlist(newnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5234 &newnvx) == 0);
5235 if (oldnv) {
5236 verify(nvlist_lookup_nvlist(oldnv, ZPOOL_CONFIG_VDEV_STATS_EX,
5237 &oldnvx) == 0);
5238 }
5239
5240 newnva = safe_malloc(alloc_size);
5241 oldnva = safe_malloc(alloc_size);
5242 calcnva = safe_malloc(alloc_size);
5243
5244 for (j = 0; j < len; j++) {
5245 verify(nvpair64_to_stat_array(newnvx, names[j],
5246 &newnva[j]) == 0);
5247 calcnva[j].count = newnva[j].count;
5248 alloc_size = calcnva[j].count * sizeof (calcnva[j].data[0]);
5249 calcnva[j].data = safe_malloc(alloc_size);
5250 memcpy(calcnva[j].data, newnva[j].data, alloc_size);
5251
5252 if (oldnvx) {
5253 verify(nvpair64_to_stat_array(oldnvx, names[j],
5254 &oldnva[j]) == 0);
5255 for (i = 0; i < oldnva[j].count; i++)
5256 calcnva[j].data[i] -= oldnva[j].data[i];
5257 }
5258 }
5259 free(newnva);
5260 free(oldnva);
5261 return (calcnva);
5262 }
5263
5264 static void
free_calc_stats(struct stat_array * nva,unsigned int len)5265 free_calc_stats(struct stat_array *nva, unsigned int len)
5266 {
5267 int i;
5268 for (i = 0; i < len; i++)
5269 free(nva[i].data);
5270
5271 free(nva);
5272 }
5273
5274 static void
print_iostat_histo(struct stat_array * nva,unsigned int len,iostat_cbdata_t * cb,unsigned int column_width,unsigned int namewidth,double scale)5275 print_iostat_histo(struct stat_array *nva, unsigned int len,
5276 iostat_cbdata_t *cb, unsigned int column_width, unsigned int namewidth,
5277 double scale)
5278 {
5279 int i, j;
5280 char buf[6];
5281 uint64_t val;
5282 enum zfs_nicenum_format format;
5283 unsigned int buckets;
5284 unsigned int start_bucket;
5285
5286 if (cb->cb_literal)
5287 format = ZFS_NICENUM_RAW;
5288 else
5289 format = ZFS_NICENUM_1024;
5290
5291 /* All these histos are the same size, so just use nva[0].count */
5292 buckets = nva[0].count;
5293
5294 if (cb->cb_flags & IOS_RQ_HISTO_M) {
5295 /* Start at 512 - req size should never be lower than this */
5296 start_bucket = 9;
5297 } else {
5298 start_bucket = 0;
5299 }
5300
5301 for (j = start_bucket; j < buckets; j++) {
5302 /* Print histogram bucket label */
5303 if (cb->cb_flags & IOS_L_HISTO_M) {
5304 /* Ending range of this bucket */
5305 val = (1UL << (j + 1)) - 1;
5306 zfs_nicetime(val, buf, sizeof (buf));
5307 } else {
5308 /* Request size (starting range of bucket) */
5309 val = (1UL << j);
5310 zfs_nicenum(val, buf, sizeof (buf));
5311 }
5312
5313 if (cb->cb_scripted)
5314 printf("%llu", (u_longlong_t)val);
5315 else
5316 printf("%-*s", namewidth, buf);
5317
5318 /* Print the values on the line */
5319 for (i = 0; i < len; i++) {
5320 print_one_stat(nva[i].data[j] * scale, format,
5321 column_width, cb->cb_scripted);
5322 }
5323 printf("\n");
5324 }
5325 }
5326
5327 static void
print_solid_separator(unsigned int length)5328 print_solid_separator(unsigned int length)
5329 {
5330 while (length--)
5331 printf("-");
5332 printf("\n");
5333 }
5334
5335 static void
print_iostat_histos(iostat_cbdata_t * cb,nvlist_t * oldnv,nvlist_t * newnv,double scale,const char * name)5336 print_iostat_histos(iostat_cbdata_t *cb, nvlist_t *oldnv,
5337 nvlist_t *newnv, double scale, const char *name)
5338 {
5339 unsigned int column_width;
5340 unsigned int namewidth;
5341 unsigned int entire_width;
5342 enum iostat_type type;
5343 struct stat_array *nva;
5344 const char **names;
5345 unsigned int names_len;
5346
5347 /* What type of histo are we? */
5348 type = IOS_HISTO_IDX(cb->cb_flags);
5349
5350 /* Get NULL-terminated array of nvlist names for our histo */
5351 names = vsx_type_to_nvlist[type];
5352 names_len = str_array_len(names); /* num of names */
5353
5354 nva = calc_and_alloc_stats_ex(names, names_len, oldnv, newnv);
5355
5356 if (cb->cb_literal) {
5357 column_width = MAX(5,
5358 (unsigned int) log10(stat_histo_max(nva, names_len)) + 1);
5359 } else {
5360 column_width = 5;
5361 }
5362
5363 namewidth = MAX(cb->cb_namewidth,
5364 strlen(histo_to_title[IOS_HISTO_IDX(cb->cb_flags)]));
5365
5366 /*
5367 * Calculate the entire line width of what we're printing. The
5368 * +2 is for the two spaces between columns:
5369 */
5370 /* read write */
5371 /* ----- ----- */
5372 /* |___| <---------- column_width */
5373 /* */
5374 /* |__________| <--- entire_width */
5375 /* */
5376 entire_width = namewidth + (column_width + 2) *
5377 label_array_len(iostat_bottom_labels[type]);
5378
5379 if (cb->cb_scripted)
5380 printf("%s\n", name);
5381 else
5382 print_iostat_header_impl(cb, column_width, name);
5383
5384 print_iostat_histo(nva, names_len, cb, column_width,
5385 namewidth, scale);
5386
5387 free_calc_stats(nva, names_len);
5388 if (!cb->cb_scripted)
5389 print_solid_separator(entire_width);
5390 }
5391
5392 /*
5393 * Calculate the average latency of a power-of-two latency histogram
5394 */
5395 static uint64_t
single_histo_average(uint64_t * histo,unsigned int buckets)5396 single_histo_average(uint64_t *histo, unsigned int buckets)
5397 {
5398 int i;
5399 uint64_t count = 0, total = 0;
5400
5401 for (i = 0; i < buckets; i++) {
5402 /*
5403 * Our buckets are power-of-two latency ranges. Use the
5404 * midpoint latency of each bucket to calculate the average.
5405 * For example:
5406 *
5407 * Bucket Midpoint
5408 * 8ns-15ns: 12ns
5409 * 16ns-31ns: 24ns
5410 * ...
5411 */
5412 if (histo[i] != 0) {
5413 total += histo[i] * (((1UL << i) + ((1UL << i)/2)));
5414 count += histo[i];
5415 }
5416 }
5417
5418 /* Prevent divide by zero */
5419 return (count == 0 ? 0 : total / count);
5420 }
5421
5422 static void
print_iostat_queues(iostat_cbdata_t * cb,nvlist_t * newnv)5423 print_iostat_queues(iostat_cbdata_t *cb, nvlist_t *newnv)
5424 {
5425 const char *names[] = {
5426 ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
5427 ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
5428 ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
5429 ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
5430 ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
5431 ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
5432 ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
5433 ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
5434 ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
5435 ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
5436 ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
5437 ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
5438 ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
5439 ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
5440 };
5441
5442 struct stat_array *nva;
5443
5444 unsigned int column_width = default_column_width(cb, IOS_QUEUES);
5445 enum zfs_nicenum_format format;
5446
5447 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), NULL, newnv);
5448
5449 if (cb->cb_literal)
5450 format = ZFS_NICENUM_RAW;
5451 else
5452 format = ZFS_NICENUM_1024;
5453
5454 for (int i = 0; i < ARRAY_SIZE(names); i++) {
5455 uint64_t val = nva[i].data[0];
5456 print_one_stat(val, format, column_width, cb->cb_scripted);
5457 }
5458
5459 free_calc_stats(nva, ARRAY_SIZE(names));
5460 }
5461
5462 static void
print_iostat_latency(iostat_cbdata_t * cb,nvlist_t * oldnv,nvlist_t * newnv)5463 print_iostat_latency(iostat_cbdata_t *cb, nvlist_t *oldnv,
5464 nvlist_t *newnv)
5465 {
5466 int i;
5467 uint64_t val;
5468 const char *names[] = {
5469 ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
5470 ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
5471 ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
5472 ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
5473 ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
5474 ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
5475 ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
5476 ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
5477 ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
5478 ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
5479 ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
5480 };
5481 struct stat_array *nva;
5482
5483 unsigned int column_width = default_column_width(cb, IOS_LATENCY);
5484 enum zfs_nicenum_format format;
5485
5486 nva = calc_and_alloc_stats_ex(names, ARRAY_SIZE(names), oldnv, newnv);
5487
5488 if (cb->cb_literal)
5489 format = ZFS_NICENUM_RAWTIME;
5490 else
5491 format = ZFS_NICENUM_TIME;
5492
5493 /* Print our avg latencies on the line */
5494 for (i = 0; i < ARRAY_SIZE(names); i++) {
5495 /* Compute average latency for a latency histo */
5496 val = single_histo_average(nva[i].data, nva[i].count);
5497 print_one_stat(val, format, column_width, cb->cb_scripted);
5498 }
5499 free_calc_stats(nva, ARRAY_SIZE(names));
5500 }
5501
5502 /*
5503 * Print default statistics (capacity/operations/bandwidth)
5504 */
5505 static void
print_iostat_default(vdev_stat_t * vs,iostat_cbdata_t * cb,double scale)5506 print_iostat_default(vdev_stat_t *vs, iostat_cbdata_t *cb, double scale)
5507 {
5508 unsigned int column_width = default_column_width(cb, IOS_DEFAULT);
5509 enum zfs_nicenum_format format;
5510 char na; /* char to print for "not applicable" values */
5511
5512 if (cb->cb_literal) {
5513 format = ZFS_NICENUM_RAW;
5514 na = '0';
5515 } else {
5516 format = ZFS_NICENUM_1024;
5517 na = '-';
5518 }
5519
5520 /* only toplevel vdevs have capacity stats */
5521 if (vs->vs_space == 0) {
5522 if (cb->cb_scripted)
5523 printf("\t%c\t%c", na, na);
5524 else
5525 printf(" %*c %*c", column_width, na, column_width,
5526 na);
5527 } else {
5528 print_one_stat(vs->vs_alloc, format, column_width,
5529 cb->cb_scripted);
5530 print_one_stat(vs->vs_space - vs->vs_alloc, format,
5531 column_width, cb->cb_scripted);
5532 }
5533
5534 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_READ] * scale),
5535 format, column_width, cb->cb_scripted);
5536 print_one_stat((uint64_t)(vs->vs_ops[ZIO_TYPE_WRITE] * scale),
5537 format, column_width, cb->cb_scripted);
5538 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_READ] * scale),
5539 format, column_width, cb->cb_scripted);
5540 print_one_stat((uint64_t)(vs->vs_bytes[ZIO_TYPE_WRITE] * scale),
5541 format, column_width, cb->cb_scripted);
5542 }
5543
5544 static const char *const class_name[] = {
5545 VDEV_ALLOC_BIAS_DEDUP,
5546 VDEV_ALLOC_BIAS_SPECIAL,
5547 VDEV_ALLOC_CLASS_LOGS
5548 };
5549
5550 /*
5551 * Print out all the statistics for the given vdev. This can either be the
5552 * toplevel configuration, or called recursively. If 'name' is NULL, then this
5553 * is a verbose output, and we don't want to display the toplevel pool stats.
5554 *
5555 * Returns the number of stat lines printed.
5556 */
5557 static unsigned int
print_vdev_stats(zpool_handle_t * zhp,const char * name,nvlist_t * oldnv,nvlist_t * newnv,iostat_cbdata_t * cb,int depth)5558 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
5559 nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
5560 {
5561 nvlist_t **oldchild, **newchild;
5562 uint_t c, children, oldchildren;
5563 vdev_stat_t *oldvs, *newvs, *calcvs;
5564 vdev_stat_t zerovs = { 0 };
5565 char *vname;
5566 int i;
5567 int ret = 0;
5568 uint64_t tdelta;
5569 double scale;
5570
5571 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
5572 return (ret);
5573
5574 calcvs = safe_malloc(sizeof (*calcvs));
5575
5576 if (oldnv != NULL) {
5577 verify(nvlist_lookup_uint64_array(oldnv,
5578 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
5579 } else {
5580 oldvs = &zerovs;
5581 }
5582
5583 /* Do we only want to see a specific vdev? */
5584 for (i = 0; i < cb->cb_vdevs.cb_names_count; i++) {
5585 /* Yes we do. Is this the vdev? */
5586 if (strcmp(name, cb->cb_vdevs.cb_names[i]) == 0) {
5587 /*
5588 * This is our vdev. Since it is the only vdev we
5589 * will be displaying, make depth = 0 so that it
5590 * doesn't get indented.
5591 */
5592 depth = 0;
5593 break;
5594 }
5595 }
5596
5597 if (cb->cb_vdevs.cb_names_count && (i == cb->cb_vdevs.cb_names_count)) {
5598 /* Couldn't match the name */
5599 goto children;
5600 }
5601
5602
5603 verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
5604 (uint64_t **)&newvs, &c) == 0);
5605
5606 /*
5607 * Print the vdev name unless it's is a histogram. Histograms
5608 * display the vdev name in the header itself.
5609 */
5610 if (!(cb->cb_flags & IOS_ANYHISTO_M)) {
5611 if (cb->cb_scripted) {
5612 printf("%s", name);
5613 } else {
5614 if (strlen(name) + depth > cb->cb_namewidth)
5615 (void) printf("%*s%s", depth, "", name);
5616 else
5617 (void) printf("%*s%s%*s", depth, "", name,
5618 (int)(cb->cb_namewidth - strlen(name) -
5619 depth), "");
5620 }
5621 }
5622
5623 /* Calculate our scaling factor */
5624 tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
5625 if ((oldvs->vs_timestamp == 0) && (cb->cb_flags & IOS_ANYHISTO_M)) {
5626 /*
5627 * If we specify printing histograms with no time interval, then
5628 * print the histogram numbers over the entire lifetime of the
5629 * vdev.
5630 */
5631 scale = 1;
5632 } else {
5633 if (tdelta == 0)
5634 scale = 1.0;
5635 else
5636 scale = (double)NANOSEC / tdelta;
5637 }
5638
5639 if (cb->cb_flags & IOS_DEFAULT_M) {
5640 calc_default_iostats(oldvs, newvs, calcvs);
5641 print_iostat_default(calcvs, cb, scale);
5642 }
5643 if (cb->cb_flags & IOS_LATENCY_M)
5644 print_iostat_latency(cb, oldnv, newnv);
5645 if (cb->cb_flags & IOS_QUEUES_M)
5646 print_iostat_queues(cb, newnv);
5647 if (cb->cb_flags & IOS_ANYHISTO_M) {
5648 printf("\n");
5649 print_iostat_histos(cb, oldnv, newnv, scale, name);
5650 }
5651
5652 if (cb->vcdl != NULL) {
5653 const char *path;
5654 if (nvlist_lookup_string(newnv, ZPOOL_CONFIG_PATH,
5655 &path) == 0) {
5656 printf(" ");
5657 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
5658 }
5659 }
5660
5661 if (!(cb->cb_flags & IOS_ANYHISTO_M))
5662 printf("\n");
5663
5664 ret++;
5665
5666 children:
5667
5668 free(calcvs);
5669
5670 if (!cb->cb_verbose)
5671 return (ret);
5672
5673 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
5674 &newchild, &children) != 0)
5675 return (ret);
5676
5677 if (oldnv) {
5678 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
5679 &oldchild, &oldchildren) != 0)
5680 return (ret);
5681
5682 children = MIN(oldchildren, children);
5683 }
5684
5685 /*
5686 * print normal top-level devices
5687 */
5688 for (c = 0; c < children; c++) {
5689 uint64_t ishole = B_FALSE, islog = B_FALSE;
5690
5691 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
5692 &ishole);
5693
5694 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
5695 &islog);
5696
5697 if (ishole || islog)
5698 continue;
5699
5700 if (nvlist_exists(newchild[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
5701 continue;
5702
5703 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5704 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5705 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
5706 newchild[c], cb, depth + 2);
5707 free(vname);
5708 }
5709
5710 /*
5711 * print all other top-level devices
5712 */
5713 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
5714 boolean_t printed = B_FALSE;
5715
5716 for (c = 0; c < children; c++) {
5717 uint64_t islog = B_FALSE;
5718 const char *bias = NULL;
5719 const char *type = NULL;
5720
5721 (void) nvlist_lookup_uint64(newchild[c],
5722 ZPOOL_CONFIG_IS_LOG, &islog);
5723 if (islog) {
5724 bias = VDEV_ALLOC_CLASS_LOGS;
5725 } else {
5726 (void) nvlist_lookup_string(newchild[c],
5727 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
5728 (void) nvlist_lookup_string(newchild[c],
5729 ZPOOL_CONFIG_TYPE, &type);
5730 }
5731 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
5732 continue;
5733 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
5734 continue;
5735
5736 if (!printed) {
5737 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) &&
5738 !cb->cb_scripted &&
5739 !cb->cb_vdevs.cb_names) {
5740 print_iostat_dashes(cb, 0,
5741 class_name[n]);
5742 }
5743 printf("\n");
5744 printed = B_TRUE;
5745 }
5746
5747 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5748 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID);
5749 ret += print_vdev_stats(zhp, vname, oldnv ?
5750 oldchild[c] : NULL, newchild[c], cb, depth + 2);
5751 free(vname);
5752 }
5753 }
5754
5755 /*
5756 * Include level 2 ARC devices in iostat output
5757 */
5758 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
5759 &newchild, &children) != 0)
5760 return (ret);
5761
5762 if (oldnv) {
5763 if (nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
5764 &oldchild, &oldchildren) != 0)
5765 return (ret);
5766
5767 children = MIN(oldchildren, children);
5768 }
5769
5770 if (children > 0) {
5771 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
5772 !cb->cb_vdevs.cb_names) {
5773 print_iostat_dashes(cb, 0, "cache");
5774 }
5775 printf("\n");
5776
5777 for (c = 0; c < children; c++) {
5778 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
5779 cb->cb_vdevs.cb_name_flags);
5780 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
5781 : NULL, newchild[c], cb, depth + 2);
5782 free(vname);
5783 }
5784 }
5785
5786 return (ret);
5787 }
5788
5789 /*
5790 * Callback to print out the iostats for the given pool.
5791 */
5792 static int
print_iostat(zpool_handle_t * zhp,void * data)5793 print_iostat(zpool_handle_t *zhp, void *data)
5794 {
5795 iostat_cbdata_t *cb = data;
5796 nvlist_t *oldconfig, *newconfig;
5797 nvlist_t *oldnvroot, *newnvroot;
5798 int ret;
5799
5800 newconfig = zpool_get_config(zhp, &oldconfig);
5801
5802 if (cb->cb_iteration == 1)
5803 oldconfig = NULL;
5804
5805 verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
5806 &newnvroot) == 0);
5807
5808 if (oldconfig == NULL)
5809 oldnvroot = NULL;
5810 else
5811 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
5812 &oldnvroot) == 0);
5813
5814 ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
5815 cb, 0);
5816 if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
5817 !cb->cb_scripted && cb->cb_verbose &&
5818 !cb->cb_vdevs.cb_names_count) {
5819 print_iostat_separator(cb);
5820 if (cb->vcdl != NULL) {
5821 print_cmd_columns(cb->vcdl, 1);
5822 }
5823 printf("\n");
5824 }
5825
5826 return (ret);
5827 }
5828
5829 static int
get_columns(void)5830 get_columns(void)
5831 {
5832 struct winsize ws;
5833 int columns = 80;
5834 int error;
5835
5836 if (isatty(STDOUT_FILENO)) {
5837 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
5838 if (error == 0)
5839 columns = ws.ws_col;
5840 } else {
5841 columns = 999;
5842 }
5843
5844 return (columns);
5845 }
5846
5847 /*
5848 * Return the required length of the pool/vdev name column. The minimum
5849 * allowed width and output formatting flags must be provided.
5850 */
5851 static int
get_namewidth(zpool_handle_t * zhp,int min_width,int flags,boolean_t verbose)5852 get_namewidth(zpool_handle_t *zhp, int min_width, int flags, boolean_t verbose)
5853 {
5854 nvlist_t *config, *nvroot;
5855 int width = min_width;
5856
5857 if ((config = zpool_get_config(zhp, NULL)) != NULL) {
5858 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5859 &nvroot) == 0);
5860 size_t poolname_len = strlen(zpool_get_name(zhp));
5861 if (verbose == B_FALSE) {
5862 width = MAX(poolname_len, min_width);
5863 } else {
5864 width = MAX(poolname_len,
5865 max_width(zhp, nvroot, 0, min_width, flags));
5866 }
5867 }
5868
5869 return (width);
5870 }
5871
5872 /*
5873 * Parse the input string, get the 'interval' and 'count' value if there is one.
5874 */
5875 static void
get_interval_count(int * argcp,char ** argv,float * iv,unsigned long * cnt)5876 get_interval_count(int *argcp, char **argv, float *iv,
5877 unsigned long *cnt)
5878 {
5879 float interval = 0;
5880 unsigned long count = 0;
5881 int argc = *argcp;
5882
5883 /*
5884 * Determine if the last argument is an integer or a pool name
5885 */
5886 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5887 char *end;
5888
5889 errno = 0;
5890 interval = strtof(argv[argc - 1], &end);
5891
5892 if (*end == '\0' && errno == 0) {
5893 if (interval == 0) {
5894 (void) fprintf(stderr, gettext(
5895 "interval cannot be zero\n"));
5896 usage(B_FALSE);
5897 }
5898 /*
5899 * Ignore the last parameter
5900 */
5901 argc--;
5902 } else {
5903 /*
5904 * If this is not a valid number, just plow on. The
5905 * user will get a more informative error message later
5906 * on.
5907 */
5908 interval = 0;
5909 }
5910 }
5911
5912 /*
5913 * If the last argument is also an integer, then we have both a count
5914 * and an interval.
5915 */
5916 if (argc > 0 && zfs_isnumber(argv[argc - 1])) {
5917 char *end;
5918
5919 errno = 0;
5920 count = interval;
5921 interval = strtof(argv[argc - 1], &end);
5922
5923 if (*end == '\0' && errno == 0) {
5924 if (interval == 0) {
5925 (void) fprintf(stderr, gettext(
5926 "interval cannot be zero\n"));
5927 usage(B_FALSE);
5928 }
5929
5930 /*
5931 * Ignore the last parameter
5932 */
5933 argc--;
5934 } else {
5935 interval = 0;
5936 }
5937 }
5938
5939 *iv = interval;
5940 *cnt = count;
5941 *argcp = argc;
5942 }
5943
5944 static void
get_timestamp_arg(char c)5945 get_timestamp_arg(char c)
5946 {
5947 if (c == 'u')
5948 timestamp_fmt = UDATE;
5949 else if (c == 'd')
5950 timestamp_fmt = DDATE;
5951 else
5952 usage(B_FALSE);
5953 }
5954
5955 /*
5956 * Return stat flags that are supported by all pools by both the module and
5957 * zpool iostat. "*data" should be initialized to all 0xFFs before running.
5958 * It will get ANDed down until only the flags that are supported on all pools
5959 * remain.
5960 */
5961 static int
get_stat_flags_cb(zpool_handle_t * zhp,void * data)5962 get_stat_flags_cb(zpool_handle_t *zhp, void *data)
5963 {
5964 uint64_t *mask = data;
5965 nvlist_t *config, *nvroot, *nvx;
5966 uint64_t flags = 0;
5967 int i, j;
5968
5969 config = zpool_get_config(zhp, NULL);
5970 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5971 &nvroot) == 0);
5972
5973 /* Default stats are always supported, but for completeness.. */
5974 if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
5975 flags |= IOS_DEFAULT_M;
5976
5977 /* Get our extended stats nvlist from the main list */
5978 if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
5979 &nvx) != 0) {
5980 /*
5981 * No extended stats; they're probably running an older
5982 * module. No big deal, we support that too.
5983 */
5984 goto end;
5985 }
5986
5987 /* For each extended stat, make sure all its nvpairs are supported */
5988 for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
5989 if (!vsx_type_to_nvlist[j][0])
5990 continue;
5991
5992 /* Start off by assuming the flag is supported, then check */
5993 flags |= (1ULL << j);
5994 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
5995 if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
5996 /* flag isn't supported */
5997 flags = flags & ~(1ULL << j);
5998 break;
5999 }
6000 }
6001 }
6002 end:
6003 *mask = *mask & flags;
6004 return (0);
6005 }
6006
6007 /*
6008 * Return a bitmask of stats that are supported on all pools by both the module
6009 * and zpool iostat.
6010 */
6011 static uint64_t
get_stat_flags(zpool_list_t * list)6012 get_stat_flags(zpool_list_t *list)
6013 {
6014 uint64_t mask = -1;
6015
6016 /*
6017 * get_stat_flags_cb() will lop off bits from "mask" until only the
6018 * flags that are supported on all pools remain.
6019 */
6020 (void) pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
6021 return (mask);
6022 }
6023
6024 /*
6025 * Return 1 if cb_data->cb_names[0] is this vdev's name, 0 otherwise.
6026 */
6027 static int
is_vdev_cb(void * zhp_data,nvlist_t * nv,void * cb_data)6028 is_vdev_cb(void *zhp_data, nvlist_t *nv, void *cb_data)
6029 {
6030 uint64_t guid;
6031 vdev_cbdata_t *cb = cb_data;
6032 zpool_handle_t *zhp = zhp_data;
6033
6034 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
6035 return (0);
6036
6037 return (guid == zpool_vdev_path_to_guid(zhp, cb->cb_names[0]));
6038 }
6039
6040 /*
6041 * Returns 1 if cb_data->cb_names[0] is a vdev name, 0 otherwise.
6042 */
6043 static int
is_vdev(zpool_handle_t * zhp,void * cb_data)6044 is_vdev(zpool_handle_t *zhp, void *cb_data)
6045 {
6046 return (for_each_vdev(zhp, is_vdev_cb, cb_data));
6047 }
6048
6049 /*
6050 * Check if vdevs are in a pool
6051 *
6052 * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
6053 * return 0. If pool_name is NULL, then search all pools.
6054 */
6055 static int
are_vdevs_in_pool(int argc,char ** argv,char * pool_name,vdev_cbdata_t * cb)6056 are_vdevs_in_pool(int argc, char **argv, char *pool_name,
6057 vdev_cbdata_t *cb)
6058 {
6059 char **tmp_name;
6060 int ret = 0;
6061 int i;
6062 int pool_count = 0;
6063
6064 if ((argc == 0) || !*argv)
6065 return (0);
6066
6067 if (pool_name)
6068 pool_count = 1;
6069
6070 /* Temporarily hijack cb_names for a second... */
6071 tmp_name = cb->cb_names;
6072
6073 /* Go though our list of prospective vdev names */
6074 for (i = 0; i < argc; i++) {
6075 cb->cb_names = argv + i;
6076
6077 /* Is this name a vdev in our pools? */
6078 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
6079 ZFS_TYPE_POOL, B_FALSE, is_vdev, cb);
6080 if (!ret) {
6081 /* No match */
6082 break;
6083 }
6084 }
6085
6086 cb->cb_names = tmp_name;
6087
6088 return (ret);
6089 }
6090
6091 static int
is_pool_cb(zpool_handle_t * zhp,void * data)6092 is_pool_cb(zpool_handle_t *zhp, void *data)
6093 {
6094 char *name = data;
6095 if (strcmp(name, zpool_get_name(zhp)) == 0)
6096 return (1);
6097
6098 return (0);
6099 }
6100
6101 /*
6102 * Do we have a pool named *name? If so, return 1, otherwise 0.
6103 */
6104 static int
is_pool(char * name)6105 is_pool(char *name)
6106 {
6107 return (for_each_pool(0, NULL, B_TRUE, NULL, ZFS_TYPE_POOL, B_FALSE,
6108 is_pool_cb, name));
6109 }
6110
6111 /* Are all our argv[] strings pool names? If so return 1, 0 otherwise. */
6112 static int
are_all_pools(int argc,char ** argv)6113 are_all_pools(int argc, char **argv)
6114 {
6115 if ((argc == 0) || !*argv)
6116 return (0);
6117
6118 while (--argc >= 0)
6119 if (!is_pool(argv[argc]))
6120 return (0);
6121
6122 return (1);
6123 }
6124
6125 /*
6126 * Helper function to print out vdev/pool names we can't resolve. Used for an
6127 * error message.
6128 */
6129 static void
error_list_unresolved_vdevs(int argc,char ** argv,char * pool_name,vdev_cbdata_t * cb)6130 error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
6131 vdev_cbdata_t *cb)
6132 {
6133 int i;
6134 char *name;
6135 char *str;
6136 for (i = 0; i < argc; i++) {
6137 name = argv[i];
6138
6139 if (is_pool(name))
6140 str = gettext("pool");
6141 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
6142 str = gettext("vdev in this pool");
6143 else if (are_vdevs_in_pool(1, &name, NULL, cb))
6144 str = gettext("vdev in another pool");
6145 else
6146 str = gettext("unknown");
6147
6148 fprintf(stderr, "\t%s (%s)\n", name, str);
6149 }
6150 }
6151
6152 /*
6153 * Same as get_interval_count(), but with additional checks to not misinterpret
6154 * guids as interval/count values. Assumes VDEV_NAME_GUID is set in
6155 * cb.cb_vdevs.cb_name_flags.
6156 */
6157 static void
get_interval_count_filter_guids(int * argc,char ** argv,float * interval,unsigned long * count,iostat_cbdata_t * cb)6158 get_interval_count_filter_guids(int *argc, char **argv, float *interval,
6159 unsigned long *count, iostat_cbdata_t *cb)
6160 {
6161 int argc_for_interval = 0;
6162
6163 /* Is the last arg an interval value? Or a guid? */
6164 if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL,
6165 &cb->cb_vdevs)) {
6166 /*
6167 * The last arg is not a guid, so it's probably an
6168 * interval value.
6169 */
6170 argc_for_interval++;
6171
6172 if (*argc >= 2 &&
6173 !are_vdevs_in_pool(1, &argv[*argc - 2], NULL,
6174 &cb->cb_vdevs)) {
6175 /*
6176 * The 2nd to last arg is not a guid, so it's probably
6177 * an interval value.
6178 */
6179 argc_for_interval++;
6180 }
6181 }
6182
6183 /* Point to our list of possible intervals */
6184 char **tmpargv = &argv[*argc - argc_for_interval];
6185
6186 *argc = *argc - argc_for_interval;
6187 get_interval_count(&argc_for_interval, tmpargv,
6188 interval, count);
6189 }
6190
6191 /*
6192 * Terminal height, in rows. Returns -1 if stdout is not connected to a TTY or
6193 * if we were unable to determine its size.
6194 */
6195 static int
terminal_height(void)6196 terminal_height(void)
6197 {
6198 struct winsize win;
6199
6200 if (isatty(STDOUT_FILENO) == 0)
6201 return (-1);
6202
6203 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 && win.ws_row > 0)
6204 return (win.ws_row);
6205
6206 return (-1);
6207 }
6208
6209 /*
6210 * Run one of the zpool status/iostat -c scripts with the help (-h) option and
6211 * print the result.
6212 *
6213 * name: Short name of the script ('iostat').
6214 * path: Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
6215 */
6216 static void
print_zpool_script_help(char * name,char * path)6217 print_zpool_script_help(char *name, char *path)
6218 {
6219 char *argv[] = {path, (char *)"-h", NULL};
6220 char **lines = NULL;
6221 int lines_cnt = 0;
6222 int rc;
6223
6224 rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
6225 &lines_cnt);
6226 if (rc != 0 || lines == NULL || lines_cnt <= 0) {
6227 if (lines != NULL)
6228 libzfs_free_str_array(lines, lines_cnt);
6229 return;
6230 }
6231
6232 for (int i = 0; i < lines_cnt; i++)
6233 if (!is_blank_str(lines[i]))
6234 printf(" %-14s %s\n", name, lines[i]);
6235
6236 libzfs_free_str_array(lines, lines_cnt);
6237 }
6238
6239 /*
6240 * Go though the zpool status/iostat -c scripts in the user's path, run their
6241 * help option (-h), and print out the results.
6242 */
6243 static void
print_zpool_dir_scripts(char * dirpath)6244 print_zpool_dir_scripts(char *dirpath)
6245 {
6246 DIR *dir;
6247 struct dirent *ent;
6248 char fullpath[MAXPATHLEN];
6249 struct stat dir_stat;
6250
6251 if ((dir = opendir(dirpath)) != NULL) {
6252 /* print all the files and directories within directory */
6253 while ((ent = readdir(dir)) != NULL) {
6254 if (snprintf(fullpath, sizeof (fullpath), "%s/%s",
6255 dirpath, ent->d_name) >= sizeof (fullpath)) {
6256 (void) fprintf(stderr,
6257 gettext("internal error: "
6258 "ZPOOL_SCRIPTS_PATH too large.\n"));
6259 exit(1);
6260 }
6261
6262 /* Print the scripts */
6263 if (stat(fullpath, &dir_stat) == 0)
6264 if (dir_stat.st_mode & S_IXUSR &&
6265 S_ISREG(dir_stat.st_mode))
6266 print_zpool_script_help(ent->d_name,
6267 fullpath);
6268 }
6269 (void) closedir(dir);
6270 }
6271 }
6272
6273 /*
6274 * Print out help text for all zpool status/iostat -c scripts.
6275 */
6276 static void
print_zpool_script_list(const char * subcommand)6277 print_zpool_script_list(const char *subcommand)
6278 {
6279 char *dir, *sp, *tmp;
6280
6281 printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
6282
6283 sp = zpool_get_cmd_search_path();
6284 if (sp == NULL)
6285 return;
6286
6287 for (dir = strtok_r(sp, ":", &tmp);
6288 dir != NULL;
6289 dir = strtok_r(NULL, ":", &tmp))
6290 print_zpool_dir_scripts(dir);
6291
6292 free(sp);
6293 }
6294
6295 /*
6296 * Set the minimum pool/vdev name column width. The width must be at least 10,
6297 * but may be as large as the column width - 42 so it still fits on one line.
6298 * NOTE: 42 is the width of the default capacity/operations/bandwidth output
6299 */
6300 static int
get_namewidth_iostat(zpool_handle_t * zhp,void * data)6301 get_namewidth_iostat(zpool_handle_t *zhp, void *data)
6302 {
6303 iostat_cbdata_t *cb = data;
6304 int width, available_width;
6305
6306 /*
6307 * get_namewidth() returns the maximum width of any name in that column
6308 * for any pool/vdev/device line that will be output.
6309 */
6310 width = get_namewidth(zhp, cb->cb_namewidth,
6311 cb->cb_vdevs.cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
6312
6313 /*
6314 * The width we are calculating is the width of the header and also the
6315 * padding width for names that are less than maximum width. The stats
6316 * take up 42 characters, so the width available for names is:
6317 */
6318 available_width = get_columns() - 42;
6319
6320 /*
6321 * If the maximum width fits on a screen, then great! Make everything
6322 * line up by justifying all lines to the same width. If that max
6323 * width is larger than what's available, the name plus stats won't fit
6324 * on one line, and justifying to that width would cause every line to
6325 * wrap on the screen. We only want lines with long names to wrap.
6326 * Limit the padding to what won't wrap.
6327 */
6328 if (width > available_width)
6329 width = available_width;
6330
6331 /*
6332 * And regardless of whatever the screen width is (get_columns can
6333 * return 0 if the width is not known or less than 42 for a narrow
6334 * terminal) have the width be a minimum of 10.
6335 */
6336 if (width < 10)
6337 width = 10;
6338
6339 /* Save the calculated width */
6340 cb->cb_namewidth = width;
6341
6342 return (0);
6343 }
6344
6345 /*
6346 * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
6347 * [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
6348 * [interval [count]]
6349 *
6350 * -c CMD For each vdev, run command CMD
6351 * -g Display guid for individual vdev name.
6352 * -L Follow links when resolving vdev path name.
6353 * -P Display full path for vdev name.
6354 * -v Display statistics for individual vdevs
6355 * -h Display help
6356 * -p Display values in parsable (exact) format.
6357 * -H Scripted mode. Don't display headers, and separate properties
6358 * by a single tab.
6359 * -l Display average latency
6360 * -q Display queue depths
6361 * -w Display latency histograms
6362 * -r Display request size histogram
6363 * -T Display a timestamp in date(1) or Unix format
6364 * -n Only print headers once
6365 *
6366 * This command can be tricky because we want to be able to deal with pool
6367 * creation/destruction as well as vdev configuration changes. The bulk of this
6368 * processing is handled by the pool_list_* routines in zpool_iter.c. We rely
6369 * on pool_list_refresh() to detect the addition and removal of pools.
6370 * Configuration changes are all handled within libzfs.
6371 */
6372 int
zpool_do_iostat(int argc,char ** argv)6373 zpool_do_iostat(int argc, char **argv)
6374 {
6375 int c;
6376 int ret;
6377 float interval = 0;
6378 unsigned long count = 0;
6379 zpool_list_t *list;
6380 boolean_t verbose = B_FALSE;
6381 boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
6382 boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
6383 boolean_t omit_since_boot = B_FALSE;
6384 boolean_t guid = B_FALSE;
6385 boolean_t follow_links = B_FALSE;
6386 boolean_t full_name = B_FALSE;
6387 boolean_t headers_once = B_FALSE;
6388 iostat_cbdata_t cb = { 0 };
6389 char *cmd = NULL;
6390
6391 /* Used for printing error message */
6392 const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
6393 [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
6394
6395 uint64_t unsupported_flags;
6396
6397 /* check options */
6398 while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwnH")) != -1) {
6399 switch (c) {
6400 case 'c':
6401 if (cmd != NULL) {
6402 fprintf(stderr,
6403 gettext("Can't set -c flag twice\n"));
6404 exit(1);
6405 }
6406
6407 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
6408 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
6409 fprintf(stderr, gettext(
6410 "Can't run -c, disabled by "
6411 "ZPOOL_SCRIPTS_ENABLED.\n"));
6412 exit(1);
6413 }
6414
6415 if ((getuid() <= 0 || geteuid() <= 0) &&
6416 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
6417 fprintf(stderr, gettext(
6418 "Can't run -c with root privileges "
6419 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
6420 exit(1);
6421 }
6422 cmd = optarg;
6423 verbose = B_TRUE;
6424 break;
6425 case 'g':
6426 guid = B_TRUE;
6427 break;
6428 case 'L':
6429 follow_links = B_TRUE;
6430 break;
6431 case 'P':
6432 full_name = B_TRUE;
6433 break;
6434 case 'T':
6435 get_timestamp_arg(*optarg);
6436 break;
6437 case 'v':
6438 verbose = B_TRUE;
6439 break;
6440 case 'p':
6441 parsable = B_TRUE;
6442 break;
6443 case 'l':
6444 latency = B_TRUE;
6445 break;
6446 case 'q':
6447 queues = B_TRUE;
6448 break;
6449 case 'H':
6450 scripted = B_TRUE;
6451 break;
6452 case 'w':
6453 l_histo = B_TRUE;
6454 break;
6455 case 'r':
6456 rq_histo = B_TRUE;
6457 break;
6458 case 'y':
6459 omit_since_boot = B_TRUE;
6460 break;
6461 case 'n':
6462 headers_once = B_TRUE;
6463 break;
6464 case 'h':
6465 usage(B_FALSE);
6466 break;
6467 case '?':
6468 if (optopt == 'c') {
6469 print_zpool_script_list("iostat");
6470 exit(0);
6471 } else {
6472 fprintf(stderr,
6473 gettext("invalid option '%c'\n"), optopt);
6474 }
6475 usage(B_FALSE);
6476 }
6477 }
6478
6479 argc -= optind;
6480 argv += optind;
6481
6482 cb.cb_literal = parsable;
6483 cb.cb_scripted = scripted;
6484
6485 if (guid)
6486 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_GUID;
6487 if (follow_links)
6488 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6489 if (full_name)
6490 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_PATH;
6491 cb.cb_iteration = 0;
6492 cb.cb_namewidth = 0;
6493 cb.cb_verbose = verbose;
6494
6495 /* Get our interval and count values (if any) */
6496 if (guid) {
6497 get_interval_count_filter_guids(&argc, argv, &interval,
6498 &count, &cb);
6499 } else {
6500 get_interval_count(&argc, argv, &interval, &count);
6501 }
6502
6503 if (argc == 0) {
6504 /* No args, so just print the defaults. */
6505 } else if (are_all_pools(argc, argv)) {
6506 /* All the args are pool names */
6507 } else if (are_vdevs_in_pool(argc, argv, NULL, &cb.cb_vdevs)) {
6508 /* All the args are vdevs */
6509 cb.cb_vdevs.cb_names = argv;
6510 cb.cb_vdevs.cb_names_count = argc;
6511 argc = 0; /* No pools to process */
6512 } else if (are_all_pools(1, argv)) {
6513 /* The first arg is a pool name */
6514 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
6515 &cb.cb_vdevs)) {
6516 /* ...and the rest are vdev names */
6517 cb.cb_vdevs.cb_names = argv + 1;
6518 cb.cb_vdevs.cb_names_count = argc - 1;
6519 argc = 1; /* One pool to process */
6520 } else {
6521 fprintf(stderr, gettext("Expected either a list of "));
6522 fprintf(stderr, gettext("pools, or list of vdevs in"));
6523 fprintf(stderr, " \"%s\", ", argv[0]);
6524 fprintf(stderr, gettext("but got:\n"));
6525 error_list_unresolved_vdevs(argc - 1, argv + 1,
6526 argv[0], &cb.cb_vdevs);
6527 fprintf(stderr, "\n");
6528 usage(B_FALSE);
6529 }
6530 } else {
6531 /*
6532 * The args don't make sense. The first arg isn't a pool name,
6533 * nor are all the args vdevs.
6534 */
6535 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
6536 fprintf(stderr, "\n");
6537 return (1);
6538 }
6539
6540 if (cb.cb_vdevs.cb_names_count != 0) {
6541 /*
6542 * If user specified vdevs, it implies verbose.
6543 */
6544 cb.cb_verbose = B_TRUE;
6545 }
6546
6547 /*
6548 * Construct the list of all interesting pools.
6549 */
6550 ret = 0;
6551 if ((list = pool_list_get(argc, argv, NULL, ZFS_TYPE_POOL, parsable,
6552 &ret)) == NULL)
6553 return (1);
6554
6555 if (pool_list_count(list) == 0 && argc != 0) {
6556 pool_list_free(list);
6557 return (1);
6558 }
6559
6560 if (pool_list_count(list) == 0 && interval == 0) {
6561 pool_list_free(list);
6562 (void) fprintf(stderr, gettext("no pools available\n"));
6563 return (1);
6564 }
6565
6566 if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
6567 pool_list_free(list);
6568 (void) fprintf(stderr,
6569 gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
6570 usage(B_FALSE);
6571 }
6572
6573 if (l_histo && rq_histo) {
6574 pool_list_free(list);
6575 (void) fprintf(stderr,
6576 gettext("Only one of [-r|-w] can be passed at a time\n"));
6577 usage(B_FALSE);
6578 }
6579
6580 /*
6581 * Enter the main iostat loop.
6582 */
6583 cb.cb_list = list;
6584
6585 if (l_histo) {
6586 /*
6587 * Histograms tables look out of place when you try to display
6588 * them with the other stats, so make a rule that you can only
6589 * print histograms by themselves.
6590 */
6591 cb.cb_flags = IOS_L_HISTO_M;
6592 } else if (rq_histo) {
6593 cb.cb_flags = IOS_RQ_HISTO_M;
6594 } else {
6595 cb.cb_flags = IOS_DEFAULT_M;
6596 if (latency)
6597 cb.cb_flags |= IOS_LATENCY_M;
6598 if (queues)
6599 cb.cb_flags |= IOS_QUEUES_M;
6600 }
6601
6602 /*
6603 * See if the module supports all the stats we want to display.
6604 */
6605 unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
6606 if (unsupported_flags) {
6607 uint64_t f;
6608 int idx;
6609 fprintf(stderr,
6610 gettext("The loaded zfs module doesn't support:"));
6611
6612 /* for each bit set in unsupported_flags */
6613 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
6614 idx = lowbit64(f) - 1;
6615 fprintf(stderr, " -%c", flag_to_arg[idx]);
6616 }
6617
6618 fprintf(stderr, ". Try running a newer module.\n");
6619 pool_list_free(list);
6620
6621 return (1);
6622 }
6623
6624 int last_npools = 0;
6625 for (;;) {
6626 /*
6627 * Refresh all pools in list, adding or removing pools as
6628 * necessary.
6629 */
6630 int npools = pool_list_refresh(list);
6631 if (npools == 0) {
6632 (void) fprintf(stderr, gettext("no pools available\n"));
6633 } else {
6634 /*
6635 * If the list of pools has changed since last time
6636 * around, reset the iteration count to force the
6637 * header to be redisplayed.
6638 */
6639 if (last_npools != npools)
6640 cb.cb_iteration = 0;
6641
6642 /*
6643 * If this is the first iteration and -y was supplied
6644 * we skip any printing.
6645 */
6646 boolean_t skip = (omit_since_boot &&
6647 cb.cb_iteration == 0);
6648
6649 /*
6650 * Iterate over all pools to determine the maximum width
6651 * for the pool / device name column across all pools.
6652 */
6653 cb.cb_namewidth = 0;
6654 (void) pool_list_iter(list, B_FALSE,
6655 get_namewidth_iostat, &cb);
6656
6657 if (timestamp_fmt != NODATE)
6658 print_timestamp(timestamp_fmt);
6659
6660 if (cmd != NULL && cb.cb_verbose &&
6661 !(cb.cb_flags & IOS_ANYHISTO_M)) {
6662 cb.vcdl = all_pools_for_each_vdev_run(argc,
6663 argv, cmd, g_zfs, cb.cb_vdevs.cb_names,
6664 cb.cb_vdevs.cb_names_count,
6665 cb.cb_vdevs.cb_name_flags);
6666 } else {
6667 cb.vcdl = NULL;
6668 }
6669
6670
6671 /*
6672 * Check terminal size so we can print headers
6673 * even when terminal window has its height
6674 * changed.
6675 */
6676 int winheight = terminal_height();
6677 /*
6678 * Are we connected to TTY? If not, headers_once
6679 * should be true, to avoid breaking scripts.
6680 */
6681 if (winheight < 0)
6682 headers_once = B_TRUE;
6683
6684 /*
6685 * If it's the first time and we're not skipping it,
6686 * or either skip or verbose mode, print the header.
6687 *
6688 * The histogram code explicitly prints its header on
6689 * every vdev, so skip this for histograms.
6690 */
6691 if (((++cb.cb_iteration == 1 && !skip) ||
6692 (skip != verbose) ||
6693 (!headers_once &&
6694 (cb.cb_iteration % winheight) == 0)) &&
6695 (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
6696 !cb.cb_scripted)
6697 print_iostat_header(&cb);
6698
6699 if (skip) {
6700 (void) fflush(stdout);
6701 (void) fsleep(interval);
6702 last_npools = npools;
6703 continue;
6704 }
6705
6706 (void) pool_list_iter(list, B_FALSE, print_iostat, &cb);
6707
6708 /*
6709 * If there's more than one pool, and we're not in
6710 * verbose mode (which prints a separator for us),
6711 * then print a separator.
6712 *
6713 * In addition, if we're printing specific vdevs then
6714 * we also want an ending separator.
6715 */
6716 if (((npools > 1 && !verbose &&
6717 !(cb.cb_flags & IOS_ANYHISTO_M)) ||
6718 (!(cb.cb_flags & IOS_ANYHISTO_M) &&
6719 cb.cb_vdevs.cb_names_count)) &&
6720 !cb.cb_scripted) {
6721 print_iostat_separator(&cb);
6722 if (cb.vcdl != NULL)
6723 print_cmd_columns(cb.vcdl, 1);
6724 printf("\n");
6725 }
6726
6727 if (cb.vcdl != NULL)
6728 free_vdev_cmd_data_list(cb.vcdl);
6729
6730 }
6731
6732 if (interval == 0)
6733 break;
6734
6735 if (count != 0 && --count == 0)
6736 break;
6737
6738 (void) fflush(stdout);
6739 (void) fsleep(interval);
6740
6741 last_npools = npools;
6742 }
6743
6744 pool_list_free(list);
6745
6746 return (ret);
6747 }
6748
6749 typedef struct list_cbdata {
6750 boolean_t cb_verbose;
6751 int cb_name_flags;
6752 int cb_namewidth;
6753 boolean_t cb_json;
6754 boolean_t cb_scripted;
6755 zprop_list_t *cb_proplist;
6756 boolean_t cb_literal;
6757 nvlist_t *cb_jsobj;
6758 boolean_t cb_json_as_int;
6759 boolean_t cb_json_pool_key_guid;
6760 } list_cbdata_t;
6761
6762
6763 /*
6764 * Given a list of columns to display, print an appropriate line. If
6765 * `vdev_name` is not NULL, we print `vdev_name` followed by a line of dashes.
6766 * If `vdev_name` is NULL, we print a line of the headers.
6767 */
6768 static void
print_line(list_cbdata_t * cb,const char * vdev_name)6769 print_line(list_cbdata_t *cb, const char *vdev_name)
6770 {
6771 zprop_list_t *pl = cb->cb_proplist;
6772 char headerbuf[ZPOOL_MAXPROPLEN];
6773 const char *header;
6774 boolean_t first = B_TRUE;
6775 boolean_t right_justify;
6776 size_t width = 0;
6777
6778 boolean_t print_header = (vdev_name == NULL);
6779
6780 for (; pl != NULL; pl = pl->pl_next) {
6781 width = pl->pl_width;
6782 if (first && cb->cb_verbose) {
6783 /*
6784 * Reset the width to accommodate the verbose listing
6785 * of devices.
6786 */
6787 width = cb->cb_namewidth;
6788 }
6789
6790 if (!first)
6791 (void) fputs(" ", stdout);
6792
6793 if (print_header) {
6794 right_justify = B_FALSE;
6795 if (pl->pl_prop != ZPROP_USERPROP) {
6796 header = zpool_prop_column_name(pl->pl_prop);
6797 right_justify = zpool_prop_align_right(
6798 pl->pl_prop);
6799 } else {
6800 int i;
6801
6802 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
6803 headerbuf[i] = toupper(
6804 pl->pl_user_prop[i]);
6805 headerbuf[i] = '\0';
6806 header = headerbuf;
6807 }
6808
6809 }
6810 /*
6811 * If `print_header` is false, we want to print a line of
6812 * dashes.
6813 */
6814 else {
6815 if (first) {
6816 header = vdev_name;
6817 right_justify = B_FALSE;
6818 } else {
6819 header = "-";
6820 right_justify = B_TRUE;
6821 }
6822 }
6823
6824 if (pl->pl_next == NULL && !right_justify)
6825 (void) fputs(header, stdout);
6826 else if (right_justify)
6827 (void) printf("%*s", (int)width, header);
6828 else
6829 (void) printf("%-*s", (int)width, header);
6830
6831 if (first)
6832 first = B_FALSE;
6833 }
6834
6835 (void) fputc('\n', stdout);
6836 }
6837
6838 /*
6839 * Given a pool and a list of properties, print out all the properties according
6840 * to the described layout. Used by zpool_do_list().
6841 */
6842 static void
collect_pool(zpool_handle_t * zhp,list_cbdata_t * cb)6843 collect_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
6844 {
6845 zprop_list_t *pl = cb->cb_proplist;
6846 boolean_t first = B_TRUE;
6847 char property[ZPOOL_MAXPROPLEN];
6848 const char *propstr;
6849 boolean_t right_justify;
6850 size_t width;
6851 zprop_source_t sourcetype = ZPROP_SRC_NONE;
6852 nvlist_t *item, *d, *props;
6853 item = d = props = NULL;
6854
6855 if (cb->cb_json) {
6856 item = fnvlist_alloc();
6857 props = fnvlist_alloc();
6858 d = fnvlist_lookup_nvlist(cb->cb_jsobj, "pools");
6859 if (d == NULL) {
6860 fprintf(stderr, "pools obj not found.\n");
6861 exit(1);
6862 }
6863 fill_pool_info(item, zhp, B_TRUE, cb->cb_json_as_int);
6864 }
6865
6866 for (; pl != NULL; pl = pl->pl_next) {
6867
6868 width = pl->pl_width;
6869 if (first && cb->cb_verbose) {
6870 /*
6871 * Reset the width to accommodate the verbose listing
6872 * of devices.
6873 */
6874 width = cb->cb_namewidth;
6875 }
6876
6877 if (!cb->cb_json && !first) {
6878 if (cb->cb_scripted)
6879 (void) fputc('\t', stdout);
6880 else
6881 (void) fputs(" ", stdout);
6882 } else {
6883 first = B_FALSE;
6884 }
6885
6886 right_justify = B_FALSE;
6887 if (pl->pl_prop != ZPROP_USERPROP) {
6888 if (zpool_get_prop(zhp, pl->pl_prop, property,
6889 sizeof (property), &sourcetype,
6890 cb->cb_literal) != 0)
6891 propstr = "-";
6892 else
6893 propstr = property;
6894
6895 right_justify = zpool_prop_align_right(pl->pl_prop);
6896 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
6897 zpool_prop_unsupported(pl->pl_user_prop)) &&
6898 zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
6899 sizeof (property)) == 0) {
6900 propstr = property;
6901 sourcetype = ZPROP_SRC_LOCAL;
6902 } else if (zfs_prop_user(pl->pl_user_prop) &&
6903 zpool_get_userprop(zhp, pl->pl_user_prop, property,
6904 sizeof (property), &sourcetype) == 0) {
6905 propstr = property;
6906 } else {
6907 propstr = "-";
6908 }
6909
6910 if (cb->cb_json) {
6911 if (pl->pl_prop == ZPOOL_PROP_NAME)
6912 continue;
6913 const char *prop_name;
6914 if (pl->pl_prop != ZPROP_USERPROP)
6915 prop_name = zpool_prop_to_name(pl->pl_prop);
6916 else
6917 prop_name = pl->pl_user_prop;
6918 (void) zprop_nvlist_one_property(
6919 prop_name, propstr,
6920 sourcetype, NULL, NULL, props, cb->cb_json_as_int);
6921 } else {
6922 /*
6923 * If this is being called in scripted mode, or if this
6924 * is the last column and it is left-justified, don't
6925 * include a width format specifier.
6926 */
6927 if (cb->cb_scripted || (pl->pl_next == NULL &&
6928 !right_justify))
6929 (void) fputs(propstr, stdout);
6930 else if (right_justify)
6931 (void) printf("%*s", (int)width, propstr);
6932 else
6933 (void) printf("%-*s", (int)width, propstr);
6934 }
6935 }
6936
6937 if (cb->cb_json) {
6938 fnvlist_add_nvlist(item, "properties", props);
6939 if (cb->cb_json_pool_key_guid) {
6940 char pool_guid[256];
6941 uint64_t guid = fnvlist_lookup_uint64(
6942 zpool_get_config(zhp, NULL),
6943 ZPOOL_CONFIG_POOL_GUID);
6944 (void) snprintf(pool_guid, 256, "%llu",
6945 (u_longlong_t)guid);
6946 fnvlist_add_nvlist(d, pool_guid, item);
6947 } else {
6948 fnvlist_add_nvlist(d, zpool_get_name(zhp),
6949 item);
6950 }
6951 fnvlist_free(props);
6952 fnvlist_free(item);
6953 } else
6954 (void) fputc('\n', stdout);
6955 }
6956
6957 static void
collect_vdev_prop(zpool_prop_t prop,uint64_t value,const char * str,boolean_t scripted,boolean_t valid,enum zfs_nicenum_format format,boolean_t json,nvlist_t * nvl,boolean_t as_int)6958 collect_vdev_prop(zpool_prop_t prop, uint64_t value, const char *str,
6959 boolean_t scripted, boolean_t valid, enum zfs_nicenum_format format,
6960 boolean_t json, nvlist_t *nvl, boolean_t as_int)
6961 {
6962 char propval[64];
6963 boolean_t fixed;
6964 size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
6965
6966 switch (prop) {
6967 case ZPOOL_PROP_SIZE:
6968 case ZPOOL_PROP_NORMAL_SIZE:
6969 case ZPOOL_PROP_SPECIAL_SIZE:
6970 case ZPOOL_PROP_DEDUP_SIZE:
6971 case ZPOOL_PROP_LOG_SIZE:
6972 case ZPOOL_PROP_ELOG_SIZE:
6973 case ZPOOL_PROP_SELOG_SIZE:
6974 case ZPOOL_PROP_EXPANDSZ:
6975 case ZPOOL_PROP_NORMAL_EXPANDSZ:
6976 case ZPOOL_PROP_SPECIAL_EXPANDSZ:
6977 case ZPOOL_PROP_DEDUP_EXPANDSZ:
6978 case ZPOOL_PROP_LOG_EXPANDSZ:
6979 case ZPOOL_PROP_ELOG_EXPANDSZ:
6980 case ZPOOL_PROP_SELOG_EXPANDSZ:
6981 case ZPOOL_PROP_CHECKPOINT:
6982 case ZPOOL_PROP_DEDUPRATIO:
6983 case ZPOOL_PROP_DEDUPCACHED:
6984 if (value == 0)
6985 (void) strlcpy(propval, "-", sizeof (propval));
6986 else
6987 zfs_nicenum_format(value, propval, sizeof (propval),
6988 format);
6989 break;
6990 case ZPOOL_PROP_FRAGMENTATION:
6991 case ZPOOL_PROP_NORMAL_FRAGMENTATION:
6992 case ZPOOL_PROP_SPECIAL_FRAGMENTATION:
6993 case ZPOOL_PROP_DEDUP_FRAGMENTATION:
6994 case ZPOOL_PROP_LOG_FRAGMENTATION:
6995 case ZPOOL_PROP_ELOG_FRAGMENTATION:
6996 case ZPOOL_PROP_SELOG_FRAGMENTATION:
6997 if (value == ZFS_FRAG_INVALID) {
6998 (void) strlcpy(propval, "-", sizeof (propval));
6999 } else if (format == ZFS_NICENUM_RAW) {
7000 (void) snprintf(propval, sizeof (propval), "%llu",
7001 (unsigned long long)value);
7002 } else {
7003 (void) snprintf(propval, sizeof (propval), "%llu%%",
7004 (unsigned long long)value);
7005 }
7006 break;
7007 case ZPOOL_PROP_CAPACITY:
7008 case ZPOOL_PROP_NORMAL_CAPACITY:
7009 case ZPOOL_PROP_SPECIAL_CAPACITY:
7010 case ZPOOL_PROP_DEDUP_CAPACITY:
7011 case ZPOOL_PROP_LOG_CAPACITY:
7012 case ZPOOL_PROP_ELOG_CAPACITY:
7013 case ZPOOL_PROP_SELOG_CAPACITY:
7014 /* capacity value is in parts-per-10,000 (aka permyriad) */
7015 if (format == ZFS_NICENUM_RAW)
7016 (void) snprintf(propval, sizeof (propval), "%llu",
7017 (unsigned long long)value / 100);
7018 else
7019 (void) snprintf(propval, sizeof (propval),
7020 value < 1000 ? "%1.2f%%" : value < 10000 ?
7021 "%2.1f%%" : "%3.0f%%", value / 100.0);
7022 break;
7023 case ZPOOL_PROP_HEALTH:
7024 width = 8;
7025 (void) strlcpy(propval, str, sizeof (propval));
7026 break;
7027 default:
7028 zfs_nicenum_format(value, propval, sizeof (propval), format);
7029 }
7030
7031 if (!valid)
7032 (void) strlcpy(propval, "-", sizeof (propval));
7033
7034 if (json) {
7035 (void) zprop_nvlist_one_property(zpool_prop_to_name(prop),
7036 propval, ZPROP_SRC_NONE, NULL, NULL, nvl, as_int);
7037 } else {
7038 if (scripted)
7039 (void) printf("\t%s", propval);
7040 else
7041 (void) printf(" %*s", (int)width, propval);
7042 }
7043 }
7044
7045 /*
7046 * print static default line per vdev
7047 */
7048 static void
collect_list_stats(zpool_handle_t * zhp,const char * name,nvlist_t * nv,list_cbdata_t * cb,int depth,boolean_t isspare,nvlist_t * item)7049 collect_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
7050 list_cbdata_t *cb, int depth, boolean_t isspare, nvlist_t *item)
7051 {
7052 nvlist_t **child;
7053 vdev_stat_t *vs;
7054 uint_t c, children = 0;
7055 char *vname;
7056 boolean_t scripted = cb->cb_scripted;
7057 uint64_t islog = B_FALSE;
7058 nvlist_t *props, *ent, *ch, *obj, *l2c, *sp;
7059 props = ent = ch = obj = sp = l2c = NULL;
7060
7061 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
7062 (uint64_t **)&vs, &c) == 0);
7063
7064 if (name != NULL) {
7065 boolean_t toplevel = (vs->vs_space != 0);
7066 uint64_t cap;
7067 enum zfs_nicenum_format format;
7068 const char *state;
7069
7070 if (cb->cb_literal)
7071 format = ZFS_NICENUM_RAW;
7072 else
7073 format = ZFS_NICENUM_1024;
7074
7075 if (strcmp(name, VDEV_TYPE_INDIRECT) == 0)
7076 return;
7077
7078 if (cb->cb_json) {
7079 props = fnvlist_alloc();
7080 ent = fnvlist_alloc();
7081 fill_vdev_info(ent, zhp, (char *)name, B_FALSE,
7082 cb->cb_json_as_int);
7083 } else {
7084 if (scripted)
7085 (void) printf("\t%s", name);
7086 else if (strlen(name) + depth > cb->cb_namewidth)
7087 (void) printf("%*s%s", depth, "", name);
7088 else
7089 (void) printf("%*s%s%*s", depth, "", name,
7090 (int)(cb->cb_namewidth - strlen(name) -
7091 depth), "");
7092 }
7093
7094 /*
7095 * Print the properties for the individual vdevs. Some
7096 * properties are only applicable to toplevel vdevs. The
7097 * 'toplevel' boolean value is passed to the print_one_column()
7098 * to indicate that the value is valid.
7099 */
7100 for (zprop_list_t *pl = cb->cb_proplist; pl != NULL;
7101 pl = pl->pl_next) {
7102 switch (pl->pl_prop) {
7103 case ZPOOL_PROP_SIZE:
7104 if (VDEV_STAT_VALID(vs_pspace, c) &&
7105 vs->vs_pspace) {
7106 collect_vdev_prop(
7107 ZPOOL_PROP_SIZE, vs->vs_pspace,
7108 NULL, scripted, B_TRUE, format,
7109 cb->cb_json, props,
7110 cb->cb_json_as_int);
7111 } else {
7112 collect_vdev_prop(
7113 ZPOOL_PROP_SIZE, vs->vs_space, NULL,
7114 scripted, toplevel, format,
7115 cb->cb_json, props,
7116 cb->cb_json_as_int);
7117 }
7118 break;
7119 case ZPOOL_PROP_ALLOCATED:
7120 collect_vdev_prop(ZPOOL_PROP_ALLOCATED,
7121 vs->vs_alloc, NULL, scripted, toplevel,
7122 format, cb->cb_json, props,
7123 cb->cb_json_as_int);
7124 break;
7125
7126 case ZPOOL_PROP_FREE:
7127 collect_vdev_prop(ZPOOL_PROP_FREE,
7128 vs->vs_space - vs->vs_alloc, NULL, scripted,
7129 toplevel, format, cb->cb_json, props,
7130 cb->cb_json_as_int);
7131 break;
7132
7133 case ZPOOL_PROP_CHECKPOINT:
7134 collect_vdev_prop(ZPOOL_PROP_CHECKPOINT,
7135 vs->vs_checkpoint_space, NULL, scripted,
7136 toplevel, format, cb->cb_json, props,
7137 cb->cb_json_as_int);
7138 break;
7139
7140 case ZPOOL_PROP_EXPANDSZ:
7141 collect_vdev_prop(ZPOOL_PROP_EXPANDSZ,
7142 vs->vs_esize, NULL, scripted, B_TRUE,
7143 format, cb->cb_json, props,
7144 cb->cb_json_as_int);
7145 break;
7146
7147 case ZPOOL_PROP_FRAGMENTATION:
7148 collect_vdev_prop(
7149 ZPOOL_PROP_FRAGMENTATION,
7150 vs->vs_fragmentation, NULL, scripted,
7151 (vs->vs_fragmentation != ZFS_FRAG_INVALID &&
7152 toplevel),
7153 format, cb->cb_json, props,
7154 cb->cb_json_as_int);
7155 break;
7156
7157 case ZPOOL_PROP_CAPACITY:
7158 cap = (vs->vs_space == 0) ?
7159 0 : (vs->vs_alloc * 10000 / vs->vs_space);
7160 collect_vdev_prop(ZPOOL_PROP_CAPACITY, cap,
7161 NULL, scripted, toplevel, format,
7162 cb->cb_json, props, cb->cb_json_as_int);
7163 break;
7164
7165 case ZPOOL_PROP_HEALTH:
7166 state = zpool_state_to_name(vs->vs_state,
7167 vs->vs_aux);
7168 if (isspare) {
7169 if (vs->vs_aux == VDEV_AUX_SPARED)
7170 state = "INUSE";
7171 else if (vs->vs_state ==
7172 VDEV_STATE_HEALTHY)
7173 state = "AVAIL";
7174 }
7175 collect_vdev_prop(ZPOOL_PROP_HEALTH, 0, state,
7176 scripted, B_TRUE, format, cb->cb_json,
7177 props, cb->cb_json_as_int);
7178 break;
7179
7180 case ZPOOL_PROP_NAME:
7181 break;
7182
7183 default:
7184 collect_vdev_prop(pl->pl_prop, 0,
7185 NULL, scripted, B_FALSE, format,
7186 cb->cb_json, props, cb->cb_json_as_int);
7187
7188 }
7189
7190
7191 }
7192
7193 if (cb->cb_json) {
7194 fnvlist_add_nvlist(ent, "properties", props);
7195 fnvlist_free(props);
7196 } else
7197 (void) fputc('\n', stdout);
7198 }
7199
7200 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
7201 &child, &children) != 0) {
7202 if (cb->cb_json) {
7203 fnvlist_add_nvlist(item, name, ent);
7204 fnvlist_free(ent);
7205 }
7206 return;
7207 }
7208
7209 if (cb->cb_json) {
7210 ch = fnvlist_alloc();
7211 }
7212
7213 /* list the normal vdevs first */
7214 for (c = 0; c < children; c++) {
7215 uint64_t ishole = B_FALSE;
7216
7217 if (nvlist_lookup_uint64(child[c],
7218 ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
7219 continue;
7220
7221 if (nvlist_lookup_uint64(child[c],
7222 ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog)
7223 continue;
7224
7225 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
7226 continue;
7227
7228 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7229 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7230
7231 if (name == NULL || cb->cb_json != B_TRUE)
7232 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7233 B_FALSE, item);
7234 else if (cb->cb_json) {
7235 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7236 B_FALSE, ch);
7237 }
7238 free(vname);
7239 }
7240
7241 if (cb->cb_json) {
7242 if (!nvlist_empty(ch))
7243 fnvlist_add_nvlist(ent, "vdevs", ch);
7244 fnvlist_free(ch);
7245 }
7246
7247 /* list the classes: 'logs', 'dedup', and 'special' */
7248 for (uint_t n = 0; n < ARRAY_SIZE(class_name); n++) {
7249 boolean_t printed = B_FALSE;
7250 if (cb->cb_json)
7251 obj = fnvlist_alloc();
7252 for (c = 0; c < children; c++) {
7253 const char *bias = NULL;
7254 const char *type = NULL;
7255
7256 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
7257 &islog) == 0 && islog) {
7258 bias = VDEV_ALLOC_CLASS_LOGS;
7259 } else {
7260 (void) nvlist_lookup_string(child[c],
7261 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
7262 (void) nvlist_lookup_string(child[c],
7263 ZPOOL_CONFIG_TYPE, &type);
7264 }
7265 if (bias == NULL || strcmp(bias, class_name[n]) != 0)
7266 continue;
7267 if (!islog && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
7268 continue;
7269
7270 if (!printed && !cb->cb_json) {
7271 print_line(cb, class_name[n]);
7272 printed = B_TRUE;
7273 }
7274 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7275 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
7276 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7277 B_FALSE, obj);
7278 free(vname);
7279 }
7280 if (cb->cb_json) {
7281 if (!nvlist_empty(obj))
7282 fnvlist_add_nvlist(item, class_name[n], obj);
7283 fnvlist_free(obj);
7284 }
7285 }
7286
7287 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
7288 &child, &children) == 0 && children > 0) {
7289 if (cb->cb_json) {
7290 l2c = fnvlist_alloc();
7291 } else {
7292 print_line(cb, "cache");
7293 }
7294 for (c = 0; c < children; c++) {
7295 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7296 cb->cb_name_flags);
7297 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7298 B_FALSE, l2c);
7299 free(vname);
7300 }
7301 if (cb->cb_json) {
7302 if (!nvlist_empty(l2c))
7303 fnvlist_add_nvlist(item, "l2cache", l2c);
7304 fnvlist_free(l2c);
7305 }
7306 }
7307
7308 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
7309 &children) == 0 && children > 0) {
7310 if (cb->cb_json) {
7311 sp = fnvlist_alloc();
7312 } else {
7313 print_line(cb, "spare");
7314 }
7315 for (c = 0; c < children; c++) {
7316 vname = zpool_vdev_name(g_zfs, zhp, child[c],
7317 cb->cb_name_flags);
7318 collect_list_stats(zhp, vname, child[c], cb, depth + 2,
7319 B_TRUE, sp);
7320 free(vname);
7321 }
7322 if (cb->cb_json) {
7323 if (!nvlist_empty(sp))
7324 fnvlist_add_nvlist(item, "spares", sp);
7325 fnvlist_free(sp);
7326 }
7327 }
7328
7329 if (name != NULL && cb->cb_json) {
7330 fnvlist_add_nvlist(item, name, ent);
7331 fnvlist_free(ent);
7332 }
7333 }
7334
7335 /*
7336 * Generic callback function to list a pool.
7337 */
7338 static int
list_callback(zpool_handle_t * zhp,void * data)7339 list_callback(zpool_handle_t *zhp, void *data)
7340 {
7341 nvlist_t *p, *d, *nvdevs;
7342 uint64_t guid;
7343 char pool_guid[256];
7344 const char *pool_name = zpool_get_name(zhp);
7345 list_cbdata_t *cbp = data;
7346 p = d = nvdevs = NULL;
7347
7348 collect_pool(zhp, cbp);
7349
7350 if (cbp->cb_verbose) {
7351 nvlist_t *config, *nvroot;
7352 config = zpool_get_config(zhp, NULL);
7353 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
7354 &nvroot) == 0);
7355 if (cbp->cb_json) {
7356 d = fnvlist_lookup_nvlist(cbp->cb_jsobj,
7357 "pools");
7358 if (cbp->cb_json_pool_key_guid) {
7359 guid = fnvlist_lookup_uint64(config,
7360 ZPOOL_CONFIG_POOL_GUID);
7361 (void) snprintf(pool_guid, 256, "%llu",
7362 (u_longlong_t)guid);
7363 p = fnvlist_lookup_nvlist(d, pool_guid);
7364 } else {
7365 p = fnvlist_lookup_nvlist(d, pool_name);
7366 }
7367 nvdevs = fnvlist_alloc();
7368 }
7369 collect_list_stats(zhp, NULL, nvroot, cbp, 0, B_FALSE, nvdevs);
7370 if (cbp->cb_json) {
7371 fnvlist_add_nvlist(p, "vdevs", nvdevs);
7372 if (cbp->cb_json_pool_key_guid)
7373 fnvlist_add_nvlist(d, pool_guid, p);
7374 else
7375 fnvlist_add_nvlist(d, pool_name, p);
7376 fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
7377 fnvlist_free(nvdevs);
7378 }
7379 }
7380
7381 return (0);
7382 }
7383
7384 /*
7385 * Set the minimum pool/vdev name column width. The width must be at least 9,
7386 * but may be as large as needed.
7387 */
7388 static int
get_namewidth_list(zpool_handle_t * zhp,void * data)7389 get_namewidth_list(zpool_handle_t *zhp, void *data)
7390 {
7391 list_cbdata_t *cb = data;
7392 int width;
7393
7394 width = get_namewidth(zhp, cb->cb_namewidth,
7395 cb->cb_name_flags | VDEV_NAME_TYPE_ID, cb->cb_verbose);
7396
7397 if (width < 9)
7398 width = 9;
7399
7400 cb->cb_namewidth = width;
7401
7402 return (0);
7403 }
7404
7405 /*
7406 * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
7407 *
7408 * -g Display guid for individual vdev name.
7409 * -H Scripted mode. Don't display headers, and separate properties
7410 * by a single tab.
7411 * -L Follow links when resolving vdev path name.
7412 * -o List of properties to display. Defaults to
7413 * "name,size,allocated,free,expandsize,fragmentation,capacity,"
7414 * "dedupratio,health,altroot"
7415 * -p Display values in parsable (exact) format.
7416 * -P Display full path for vdev name.
7417 * -T Display a timestamp in date(1) or Unix format
7418 * -j Display the output in JSON format
7419 * --json-int Display the numbers as integer instead of strings.
7420 * --json-pool-key-guid Set pool GUID as key for pool objects.
7421 *
7422 * List all pools in the system, whether or not they're healthy. Output space
7423 * statistics for each one, as well as health status summary.
7424 */
7425 int
zpool_do_list(int argc,char ** argv)7426 zpool_do_list(int argc, char **argv)
7427 {
7428 int c;
7429 int ret = 0;
7430 list_cbdata_t cb = { 0 };
7431 static char default_props[] =
7432 "name,size,allocated,free,checkpoint,expandsize,fragmentation,"
7433 "capacity,dedupratio,health,altroot";
7434 char *props = default_props;
7435 float interval = 0;
7436 unsigned long count = 0;
7437 zpool_list_t *list;
7438 boolean_t first = B_TRUE;
7439 nvlist_t *data = NULL;
7440 current_prop_type = ZFS_TYPE_POOL;
7441
7442 struct option long_options[] = {
7443 {"json", no_argument, NULL, 'j'},
7444 {"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
7445 {"json-pool-key-guid", no_argument, NULL,
7446 ZPOOL_OPTION_POOL_KEY_GUID},
7447 {0, 0, 0, 0}
7448 };
7449
7450 /* check options */
7451 while ((c = getopt_long(argc, argv, ":gjHLo:pPT:v", long_options,
7452 NULL)) != -1) {
7453 switch (c) {
7454 case 'g':
7455 cb.cb_name_flags |= VDEV_NAME_GUID;
7456 break;
7457 case 'H':
7458 cb.cb_scripted = B_TRUE;
7459 break;
7460 case 'L':
7461 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
7462 break;
7463 case 'o':
7464 props = optarg;
7465 break;
7466 case 'P':
7467 cb.cb_name_flags |= VDEV_NAME_PATH;
7468 break;
7469 case 'p':
7470 cb.cb_literal = B_TRUE;
7471 break;
7472 case 'j':
7473 cb.cb_json = B_TRUE;
7474 break;
7475 case ZPOOL_OPTION_JSON_NUMS_AS_INT:
7476 cb.cb_json_as_int = B_TRUE;
7477 cb.cb_literal = B_TRUE;
7478 break;
7479 case ZPOOL_OPTION_POOL_KEY_GUID:
7480 cb.cb_json_pool_key_guid = B_TRUE;
7481 break;
7482 case 'T':
7483 get_timestamp_arg(*optarg);
7484 break;
7485 case 'v':
7486 cb.cb_verbose = B_TRUE;
7487 cb.cb_namewidth = 8; /* 8 until precalc is avail */
7488 break;
7489 case ':':
7490 (void) fprintf(stderr, gettext("missing argument for "
7491 "'%c' option\n"), optopt);
7492 usage(B_FALSE);
7493 break;
7494 case '?':
7495 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7496 optopt);
7497 usage(B_FALSE);
7498 }
7499 }
7500
7501 argc -= optind;
7502 argv += optind;
7503
7504 if (!cb.cb_json && cb.cb_json_as_int) {
7505 (void) fprintf(stderr, gettext("'--json-int' only works with"
7506 " '-j' option\n"));
7507 usage(B_FALSE);
7508 }
7509
7510 if (!cb.cb_json && cb.cb_json_pool_key_guid) {
7511 (void) fprintf(stderr, gettext("'json-pool-key-guid' only"
7512 " works with '-j' option\n"));
7513 usage(B_FALSE);
7514 }
7515
7516 get_interval_count(&argc, argv, &interval, &count);
7517
7518 if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
7519 usage(B_FALSE);
7520
7521 for (;;) {
7522 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
7523 ZFS_TYPE_POOL, cb.cb_literal, &ret)) == NULL)
7524 return (1);
7525
7526 if (pool_list_count(list) == 0)
7527 break;
7528
7529 if (cb.cb_json) {
7530 cb.cb_jsobj = zpool_json_schema(0, 1);
7531 data = fnvlist_alloc();
7532 fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
7533 fnvlist_free(data);
7534 }
7535
7536 cb.cb_namewidth = 0;
7537 (void) pool_list_iter(list, B_FALSE, get_namewidth_list, &cb);
7538
7539 if (timestamp_fmt != NODATE) {
7540 if (cb.cb_json) {
7541 if (cb.cb_json_as_int) {
7542 fnvlist_add_uint64(cb.cb_jsobj, "time",
7543 time(NULL));
7544 } else {
7545 char ts[128];
7546 get_timestamp(timestamp_fmt, ts, 128);
7547 fnvlist_add_string(cb.cb_jsobj, "time",
7548 ts);
7549 }
7550 } else
7551 print_timestamp(timestamp_fmt);
7552 }
7553
7554 if (!cb.cb_scripted && (first || cb.cb_verbose) &&
7555 !cb.cb_json) {
7556 print_line(&cb, NULL);
7557 first = B_FALSE;
7558 }
7559 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
7560
7561 if (ret == 0 && cb.cb_json)
7562 zcmd_print_json(cb.cb_jsobj);
7563 else if (ret != 0 && cb.cb_json)
7564 nvlist_free(cb.cb_jsobj);
7565
7566 if (interval == 0)
7567 break;
7568
7569 if (count != 0 && --count == 0)
7570 break;
7571
7572 pool_list_free(list);
7573
7574 (void) fflush(stdout);
7575 (void) fsleep(interval);
7576 }
7577
7578 if (argc == 0 && !cb.cb_scripted && !cb.cb_json &&
7579 pool_list_count(list) == 0) {
7580 (void) printf(gettext("no pools available\n"));
7581 ret = 0;
7582 }
7583
7584 pool_list_free(list);
7585 zprop_free_list(cb.cb_proplist);
7586 return (ret);
7587 }
7588
7589 static int
zpool_do_attach_or_replace(int argc,char ** argv,int replacing)7590 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
7591 {
7592 boolean_t force = B_FALSE;
7593 boolean_t rebuild = B_FALSE;
7594 boolean_t wait = B_FALSE;
7595 int c;
7596 nvlist_t *nvroot;
7597 char *poolname, *old_disk, *new_disk;
7598 zpool_handle_t *zhp;
7599 nvlist_t *props = NULL;
7600 char *propval;
7601 int ret;
7602
7603 /* check options */
7604 while ((c = getopt(argc, argv, "fo:sw")) != -1) {
7605 switch (c) {
7606 case 'f':
7607 force = B_TRUE;
7608 break;
7609 case 'o':
7610 if ((propval = strchr(optarg, '=')) == NULL) {
7611 (void) fprintf(stderr, gettext("missing "
7612 "'=' for -o option\n"));
7613 usage(B_FALSE);
7614 }
7615 *propval = '\0';
7616 propval++;
7617
7618 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
7619 (add_prop_list(optarg, propval, &props, B_TRUE)))
7620 usage(B_FALSE);
7621 break;
7622 case 's':
7623 rebuild = B_TRUE;
7624 break;
7625 case 'w':
7626 wait = B_TRUE;
7627 break;
7628 case '?':
7629 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7630 optopt);
7631 usage(B_FALSE);
7632 }
7633 }
7634
7635 argc -= optind;
7636 argv += optind;
7637
7638 /* get pool name and check number of arguments */
7639 if (argc < 1) {
7640 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7641 usage(B_FALSE);
7642 }
7643
7644 poolname = argv[0];
7645
7646 if (argc < 2) {
7647 (void) fprintf(stderr,
7648 gettext("missing <device> specification\n"));
7649 usage(B_FALSE);
7650 }
7651
7652 old_disk = argv[1];
7653
7654 if (argc < 3) {
7655 if (!replacing) {
7656 (void) fprintf(stderr,
7657 gettext("missing <new_device> specification\n"));
7658 usage(B_FALSE);
7659 }
7660 new_disk = old_disk;
7661 argc -= 1;
7662 argv += 1;
7663 } else {
7664 new_disk = argv[2];
7665 argc -= 2;
7666 argv += 2;
7667 }
7668
7669 if (argc > 1) {
7670 (void) fprintf(stderr, gettext("too many arguments\n"));
7671 usage(B_FALSE);
7672 }
7673
7674 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7675 nvlist_free(props);
7676 return (1);
7677 }
7678
7679 if (zpool_get_config(zhp, NULL) == NULL) {
7680 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
7681 poolname);
7682 zpool_close(zhp);
7683 nvlist_free(props);
7684 return (1);
7685 }
7686
7687 /* unless manually specified use "ashift" pool property (if set) */
7688 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
7689 int intval;
7690 zprop_source_t src;
7691 char strval[ZPOOL_MAXPROPLEN];
7692
7693 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
7694 if (src != ZPROP_SRC_DEFAULT) {
7695 (void) sprintf(strval, "%" PRId32, intval);
7696 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
7697 &props, B_TRUE) == 0);
7698 }
7699 }
7700
7701 nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
7702 argc, argv);
7703 if (nvroot == NULL) {
7704 zpool_close(zhp);
7705 nvlist_free(props);
7706 return (1);
7707 }
7708
7709 ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing,
7710 rebuild);
7711
7712 if (ret == 0 && wait) {
7713 zpool_wait_activity_t activity = ZPOOL_WAIT_RESILVER;
7714 char raidz_prefix[] = "raidz";
7715 if (replacing) {
7716 activity = ZPOOL_WAIT_REPLACE;
7717 } else if (strncmp(old_disk,
7718 raidz_prefix, strlen(raidz_prefix)) == 0) {
7719 activity = ZPOOL_WAIT_RAIDZ_EXPAND;
7720 }
7721 ret = zpool_wait(zhp, activity);
7722 }
7723
7724 nvlist_free(props);
7725 nvlist_free(nvroot);
7726 zpool_close(zhp);
7727
7728 return (ret);
7729 }
7730
7731 /*
7732 * zpool replace [-fsw] [-o property=value] <pool> <device> <new_device>
7733 *
7734 * -f Force attach, even if <new_device> appears to be in use.
7735 * -s Use sequential instead of healing reconstruction for resilver.
7736 * -o Set property=value.
7737 * -w Wait for replacing to complete before returning
7738 *
7739 * Replace <device> with <new_device>.
7740 */
7741 int
zpool_do_replace(int argc,char ** argv)7742 zpool_do_replace(int argc, char **argv)
7743 {
7744 return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
7745 }
7746
7747 /*
7748 * zpool attach [-fsw] [-o property=value] <pool> <vdev> <new_device>
7749 *
7750 * -f Force attach, even if <new_device> appears to be in use.
7751 * -s Use sequential instead of healing reconstruction for resilver.
7752 * -o Set property=value.
7753 * -w Wait for resilvering (mirror) or expansion (raidz) to complete
7754 * before returning.
7755 *
7756 * Attach <new_device> to a <vdev>, where the vdev can be of type
7757 * device, mirror or raidz. If <vdev> is not part of a mirror, then <vdev> will
7758 * be transformed into a mirror of <vdev> and <new_device>. When a mirror
7759 * is involved, <new_device> will begin life with a DTL of [0, now], and will
7760 * immediately begin to resilver itself. For the raidz case, a expansion will
7761 * commence and reflow the raidz data across all the disks including the
7762 * <new_device>.
7763 */
7764 int
zpool_do_attach(int argc,char ** argv)7765 zpool_do_attach(int argc, char **argv)
7766 {
7767 return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
7768 }
7769
7770 /*
7771 * zpool detach [-f] <pool> <device>
7772 *
7773 * -f Force detach of <device>, even if DTLs argue against it
7774 * (not supported yet)
7775 *
7776 * Detach a device from a mirror. The operation will be refused if <device>
7777 * is the last device in the mirror, or if the DTLs indicate that this device
7778 * has the only valid copy of some data.
7779 */
7780 int
zpool_do_detach(int argc,char ** argv)7781 zpool_do_detach(int argc, char **argv)
7782 {
7783 int c;
7784 char *poolname, *path;
7785 zpool_handle_t *zhp;
7786 int ret;
7787
7788 /* check options */
7789 while ((c = getopt(argc, argv, "")) != -1) {
7790 switch (c) {
7791 case '?':
7792 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7793 optopt);
7794 usage(B_FALSE);
7795 }
7796 }
7797
7798 argc -= optind;
7799 argv += optind;
7800
7801 /* get pool name and check number of arguments */
7802 if (argc < 1) {
7803 (void) fprintf(stderr, gettext("missing pool name argument\n"));
7804 usage(B_FALSE);
7805 }
7806
7807 if (argc < 2) {
7808 (void) fprintf(stderr,
7809 gettext("missing <device> specification\n"));
7810 usage(B_FALSE);
7811 }
7812
7813 poolname = argv[0];
7814 path = argv[1];
7815
7816 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
7817 return (1);
7818
7819 ret = zpool_vdev_detach(zhp, path);
7820
7821 zpool_close(zhp);
7822
7823 return (ret);
7824 }
7825
7826 /*
7827 * zpool split [-gLnP] [-o prop=val] ...
7828 * [-o mntopt] ...
7829 * [-R altroot] <pool> <newpool> [<device> ...]
7830 *
7831 * -g Display guid for individual vdev name.
7832 * -L Follow links when resolving vdev path name.
7833 * -n Do not split the pool, but display the resulting layout if
7834 * it were to be split.
7835 * -o Set property=value, or set mount options.
7836 * -P Display full path for vdev name.
7837 * -R Mount the split-off pool under an alternate root.
7838 * -l Load encryption keys while importing.
7839 *
7840 * Splits the named pool and gives it the new pool name. Devices to be split
7841 * off may be listed, provided that no more than one device is specified
7842 * per top-level vdev mirror. The newly split pool is left in an exported
7843 * state unless -R is specified.
7844 *
7845 * Restrictions: the top-level of the pool pool must only be made up of
7846 * mirrors; all devices in the pool must be healthy; no device may be
7847 * undergoing a resilvering operation.
7848 */
7849 int
zpool_do_split(int argc,char ** argv)7850 zpool_do_split(int argc, char **argv)
7851 {
7852 char *srcpool, *newpool, *propval;
7853 char *mntopts = NULL;
7854 splitflags_t flags;
7855 int c, ret = 0;
7856 int ms_status = 0;
7857 boolean_t loadkeys = B_FALSE;
7858 zpool_handle_t *zhp;
7859 nvlist_t *config, *props = NULL;
7860
7861 flags.dryrun = B_FALSE;
7862 flags.import = B_FALSE;
7863 flags.name_flags = 0;
7864
7865 /* check options */
7866 while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
7867 switch (c) {
7868 case 'g':
7869 flags.name_flags |= VDEV_NAME_GUID;
7870 break;
7871 case 'L':
7872 flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
7873 break;
7874 case 'R':
7875 flags.import = B_TRUE;
7876 if (add_prop_list(
7877 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
7878 &props, B_TRUE) != 0) {
7879 nvlist_free(props);
7880 usage(B_FALSE);
7881 }
7882 break;
7883 case 'l':
7884 loadkeys = B_TRUE;
7885 break;
7886 case 'n':
7887 flags.dryrun = B_TRUE;
7888 break;
7889 case 'o':
7890 if ((propval = strchr(optarg, '=')) != NULL) {
7891 *propval = '\0';
7892 propval++;
7893 if (add_prop_list(optarg, propval,
7894 &props, B_TRUE) != 0) {
7895 nvlist_free(props);
7896 usage(B_FALSE);
7897 }
7898 } else {
7899 mntopts = optarg;
7900 }
7901 break;
7902 case 'P':
7903 flags.name_flags |= VDEV_NAME_PATH;
7904 break;
7905 case ':':
7906 (void) fprintf(stderr, gettext("missing argument for "
7907 "'%c' option\n"), optopt);
7908 usage(B_FALSE);
7909 break;
7910 case '?':
7911 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7912 optopt);
7913 usage(B_FALSE);
7914 break;
7915 }
7916 }
7917
7918 if (!flags.import && mntopts != NULL) {
7919 (void) fprintf(stderr, gettext("setting mntopts is only "
7920 "valid when importing the pool\n"));
7921 usage(B_FALSE);
7922 }
7923
7924 if (!flags.import && loadkeys) {
7925 (void) fprintf(stderr, gettext("loading keys is only "
7926 "valid when importing the pool\n"));
7927 usage(B_FALSE);
7928 }
7929
7930 argc -= optind;
7931 argv += optind;
7932
7933 if (argc < 1) {
7934 (void) fprintf(stderr, gettext("Missing pool name\n"));
7935 usage(B_FALSE);
7936 }
7937 if (argc < 2) {
7938 (void) fprintf(stderr, gettext("Missing new pool name\n"));
7939 usage(B_FALSE);
7940 }
7941
7942 srcpool = argv[0];
7943 newpool = argv[1];
7944
7945 argc -= 2;
7946 argv += 2;
7947
7948 if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
7949 nvlist_free(props);
7950 return (1);
7951 }
7952
7953 config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
7954 if (config == NULL) {
7955 ret = 1;
7956 } else {
7957 if (flags.dryrun) {
7958 (void) printf(gettext("would create '%s' with the "
7959 "following layout:\n\n"), newpool);
7960 print_vdev_tree(NULL, newpool, config, 0, "",
7961 flags.name_flags);
7962 print_vdev_tree(NULL, "dedup", config, 0,
7963 VDEV_ALLOC_BIAS_DEDUP, 0);
7964 print_vdev_tree(NULL, "special", config, 0,
7965 VDEV_ALLOC_BIAS_SPECIAL, 0);
7966 }
7967 }
7968
7969 zpool_close(zhp);
7970
7971 if (ret != 0 || flags.dryrun || !flags.import) {
7972 nvlist_free(config);
7973 nvlist_free(props);
7974 return (ret);
7975 }
7976
7977 /*
7978 * The split was successful. Now we need to open the new
7979 * pool and import it.
7980 */
7981 if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
7982 nvlist_free(config);
7983 nvlist_free(props);
7984 return (1);
7985 }
7986
7987 if (loadkeys) {
7988 ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
7989 if (ret != 0)
7990 ret = 1;
7991 }
7992
7993 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL) {
7994 ms_status = zpool_enable_datasets(zhp, mntopts, 0,
7995 mount_tp_nthr);
7996 if (ms_status == EZFS_SHAREFAILED) {
7997 (void) fprintf(stderr, gettext("Split was successful, "
7998 "datasets are mounted but sharing of some datasets "
7999 "has failed\n"));
8000 } else if (ms_status == EZFS_MOUNTFAILED) {
8001 (void) fprintf(stderr, gettext("Split was successful"
8002 ", but some datasets could not be mounted\n"));
8003 (void) fprintf(stderr, gettext("Try doing '%s' with a "
8004 "different altroot\n"), "zpool import");
8005 }
8006 }
8007 zpool_close(zhp);
8008 nvlist_free(config);
8009 nvlist_free(props);
8010
8011 return (ret);
8012 }
8013
8014
8015 /*
8016 * zpool online [--power] <pool> <device> ...
8017 *
8018 * --power: Power on the enclosure slot to the drive (if possible)
8019 */
8020 int
zpool_do_online(int argc,char ** argv)8021 zpool_do_online(int argc, char **argv)
8022 {
8023 int c, i;
8024 char *poolname;
8025 zpool_handle_t *zhp;
8026 int ret = 0;
8027 vdev_state_t newstate;
8028 int flags = 0;
8029 boolean_t is_power_on = B_FALSE;
8030 struct option long_options[] = {
8031 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8032 {0, 0, 0, 0}
8033 };
8034
8035 /* check options */
8036 while ((c = getopt_long(argc, argv, "e", long_options, NULL)) != -1) {
8037 switch (c) {
8038 case 'e':
8039 flags |= ZFS_ONLINE_EXPAND;
8040 break;
8041 case ZPOOL_OPTION_POWER:
8042 is_power_on = B_TRUE;
8043 break;
8044 case '?':
8045 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8046 optopt);
8047 usage(B_FALSE);
8048 }
8049 }
8050
8051 if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8052 is_power_on = B_TRUE;
8053
8054 argc -= optind;
8055 argv += optind;
8056
8057 /* get pool name and check number of arguments */
8058 if (argc < 1) {
8059 (void) fprintf(stderr, gettext("missing pool name\n"));
8060 usage(B_FALSE);
8061 }
8062 if (argc < 2) {
8063 (void) fprintf(stderr, gettext("missing device name\n"));
8064 usage(B_FALSE);
8065 }
8066
8067 poolname = argv[0];
8068
8069 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8070 (void) fprintf(stderr, gettext("failed to open pool "
8071 "\"%s\"\n"), poolname);
8072 return (1);
8073 }
8074
8075 for (i = 1; i < argc; i++) {
8076 vdev_state_t oldstate;
8077 boolean_t avail_spare, l2cache;
8078 int rc;
8079
8080 if (is_power_on) {
8081 rc = zpool_power_on_and_disk_wait(zhp, argv[i]);
8082 if (rc == ENOTSUP) {
8083 (void) fprintf(stderr,
8084 gettext("Power control not supported\n"));
8085 }
8086 if (rc != 0)
8087 return (rc);
8088 }
8089
8090 nvlist_t *tgt = zpool_find_vdev(zhp, argv[i], &avail_spare,
8091 &l2cache, NULL);
8092 if (tgt == NULL) {
8093 ret = 1;
8094 (void) fprintf(stderr, gettext("couldn't find device "
8095 "\"%s\" in pool \"%s\"\n"), argv[i], poolname);
8096 continue;
8097 }
8098 uint_t vsc;
8099 oldstate = ((vdev_stat_t *)fnvlist_lookup_uint64_array(tgt,
8100 ZPOOL_CONFIG_VDEV_STATS, &vsc))->vs_state;
8101 if ((rc = zpool_vdev_online(zhp, argv[i], flags,
8102 &newstate)) == 0) {
8103 if (newstate != VDEV_STATE_HEALTHY) {
8104 (void) printf(gettext("warning: device '%s' "
8105 "onlined, but remains in faulted state\n"),
8106 argv[i]);
8107 if (newstate == VDEV_STATE_FAULTED)
8108 (void) printf(gettext("use 'zpool "
8109 "clear' to restore a faulted "
8110 "device\n"));
8111 else
8112 (void) printf(gettext("use 'zpool "
8113 "replace' to replace devices "
8114 "that are no longer present\n"));
8115 if ((flags & ZFS_ONLINE_EXPAND)) {
8116 (void) printf(gettext("%s: failed "
8117 "to expand usable space on "
8118 "unhealthy device '%s'\n"),
8119 (oldstate >= VDEV_STATE_DEGRADED ?
8120 "error" : "warning"), argv[i]);
8121 if (oldstate >= VDEV_STATE_DEGRADED) {
8122 ret = 1;
8123 break;
8124 }
8125 }
8126 }
8127 } else {
8128 (void) fprintf(stderr, gettext("Failed to online "
8129 "\"%s\" in pool \"%s\": %d\n"),
8130 argv[i], poolname, rc);
8131 ret = 1;
8132 }
8133 }
8134
8135 zpool_close(zhp);
8136
8137 return (ret);
8138 }
8139
8140 /*
8141 * zpool offline [-ft]|[--power] <pool> <device> ...
8142 *
8143 *
8144 * -f Force the device into a faulted state.
8145 *
8146 * -t Only take the device off-line temporarily. The offline/faulted
8147 * state will not be persistent across reboots.
8148 *
8149 * --power Power off the enclosure slot to the drive (if possible)
8150 */
8151 int
zpool_do_offline(int argc,char ** argv)8152 zpool_do_offline(int argc, char **argv)
8153 {
8154 int c, i;
8155 char *poolname;
8156 zpool_handle_t *zhp;
8157 int ret = 0;
8158 boolean_t istmp = B_FALSE;
8159 boolean_t fault = B_FALSE;
8160 boolean_t is_power_off = B_FALSE;
8161
8162 struct option long_options[] = {
8163 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8164 {0, 0, 0, 0}
8165 };
8166
8167 /* check options */
8168 while ((c = getopt_long(argc, argv, "ft", long_options, NULL)) != -1) {
8169 switch (c) {
8170 case 'f':
8171 fault = B_TRUE;
8172 break;
8173 case 't':
8174 istmp = B_TRUE;
8175 break;
8176 case ZPOOL_OPTION_POWER:
8177 is_power_off = B_TRUE;
8178 break;
8179 case '?':
8180 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8181 optopt);
8182 usage(B_FALSE);
8183 }
8184 }
8185
8186 if (is_power_off && fault) {
8187 (void) fprintf(stderr,
8188 gettext("-0 and -f cannot be used together\n"));
8189 usage(B_FALSE);
8190 }
8191
8192 if (is_power_off && istmp) {
8193 (void) fprintf(stderr,
8194 gettext("-0 and -t cannot be used together\n"));
8195 usage(B_FALSE);
8196 }
8197
8198 argc -= optind;
8199 argv += optind;
8200
8201 /* get pool name and check number of arguments */
8202 if (argc < 1) {
8203 (void) fprintf(stderr, gettext("missing pool name\n"));
8204 usage(B_FALSE);
8205 }
8206 if (argc < 2) {
8207 (void) fprintf(stderr, gettext("missing device name\n"));
8208 usage(B_FALSE);
8209 }
8210
8211 poolname = argv[0];
8212
8213 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8214 (void) fprintf(stderr, gettext("failed to open pool "
8215 "\"%s\"\n"), poolname);
8216 return (1);
8217 }
8218
8219 for (i = 1; i < argc; i++) {
8220 uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
8221 if (is_power_off) {
8222 /*
8223 * Note: we have to power off first, then set REMOVED,
8224 * or else zpool_vdev_set_removed_state() returns
8225 * EAGAIN.
8226 */
8227 ret = zpool_power_off(zhp, argv[i]);
8228 if (ret != 0) {
8229 (void) fprintf(stderr, "%s %s %d\n",
8230 gettext("unable to power off slot for"),
8231 argv[i], ret);
8232 }
8233 (void) zpool_vdev_set_removed_state(zhp, guid,
8234 VDEV_AUX_NONE);
8235
8236 } else if (fault) {
8237 vdev_aux_t aux;
8238 if (istmp == B_FALSE) {
8239 /* Force the fault to persist across imports */
8240 aux = VDEV_AUX_EXTERNAL_PERSIST;
8241 } else {
8242 aux = VDEV_AUX_EXTERNAL;
8243 }
8244
8245 if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
8246 ret = 1;
8247 } else {
8248 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
8249 ret = 1;
8250 }
8251 }
8252
8253 zpool_close(zhp);
8254
8255 return (ret);
8256 }
8257
8258 /*
8259 * zpool clear [--power] <pool> [device]
8260 *
8261 * Clear all errors associated with a pool or a particular device.
8262 */
8263 int
zpool_do_clear(int argc,char ** argv)8264 zpool_do_clear(int argc, char **argv)
8265 {
8266 int c;
8267 int ret = 0;
8268 boolean_t is_power_on = B_FALSE;
8269 nvlist_t *policy = NULL;
8270 zpool_handle_t *zhp;
8271 char *pool, *device;
8272
8273 struct option long_options[] = {
8274 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
8275 {0, 0, 0, 0}
8276 };
8277
8278 /* check options */
8279 while ((c = getopt_long(argc, argv, "", long_options,
8280 NULL)) != -1) {
8281 switch (c) {
8282 case ZPOOL_OPTION_POWER:
8283 is_power_on = B_TRUE;
8284 break;
8285 case '?':
8286 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8287 optopt);
8288 usage(B_FALSE);
8289 }
8290 }
8291
8292 if (libzfs_envvar_is_set("ZPOOL_AUTO_POWER_ON_SLOT"))
8293 is_power_on = B_TRUE;
8294
8295 argc -= optind;
8296 argv += optind;
8297
8298 if (argc < 1) {
8299 (void) fprintf(stderr, gettext("missing pool name\n"));
8300 usage(B_FALSE);
8301 }
8302
8303 if (argc > 2) {
8304 (void) fprintf(stderr, gettext("too many arguments\n"));
8305 usage(B_FALSE);
8306 }
8307
8308 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0)
8309 return (1);
8310
8311 pool = argv[0];
8312 device = argc == 2 ? argv[1] : NULL;
8313
8314 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
8315 nvlist_free(policy);
8316 return (1);
8317 }
8318
8319 if (is_power_on) {
8320 if (device == NULL) {
8321 (void) zpool_power_on_pool_and_wait_for_devices(zhp);
8322 } else {
8323 (void) zpool_power_on_and_disk_wait(zhp, device);
8324 }
8325 }
8326
8327 if (zpool_clear(zhp, device, policy) != 0)
8328 ret = 1;
8329
8330 zpool_close(zhp);
8331
8332 nvlist_free(policy);
8333
8334 return (ret);
8335 }
8336
8337 /*
8338 * zpool reguid [-g <guid>] <pool>
8339 */
8340 int
zpool_do_reguid(int argc,char ** argv)8341 zpool_do_reguid(int argc, char **argv)
8342 {
8343 uint64_t guid;
8344 uint64_t *guidp = NULL;
8345 int c;
8346 char *endptr;
8347 char *poolname;
8348 zpool_handle_t *zhp;
8349 int ret = 0;
8350
8351 /* check options */
8352 while ((c = getopt(argc, argv, "g:")) != -1) {
8353 switch (c) {
8354 case 'g':
8355 errno = 0;
8356 guid = strtoull(optarg, &endptr, 10);
8357 if (errno != 0 || *endptr != '\0') {
8358 (void) fprintf(stderr,
8359 gettext("invalid GUID: %s\n"), optarg);
8360 usage(B_FALSE);
8361 }
8362 guidp = &guid;
8363 break;
8364 case '?':
8365 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8366 optopt);
8367 usage(B_FALSE);
8368 }
8369 }
8370
8371 argc -= optind;
8372 argv += optind;
8373
8374 /* get pool name and check number of arguments */
8375 if (argc < 1) {
8376 (void) fprintf(stderr, gettext("missing pool name\n"));
8377 usage(B_FALSE);
8378 }
8379
8380 if (argc > 1) {
8381 (void) fprintf(stderr, gettext("too many arguments\n"));
8382 usage(B_FALSE);
8383 }
8384
8385 poolname = argv[0];
8386 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
8387 return (1);
8388
8389 ret = zpool_set_guid(zhp, guidp);
8390
8391 zpool_close(zhp);
8392 return (ret);
8393 }
8394
8395
8396 /*
8397 * zpool reopen <pool>
8398 *
8399 * Reopen the pool so that the kernel can update the sizes of all vdevs.
8400 */
8401 int
zpool_do_reopen(int argc,char ** argv)8402 zpool_do_reopen(int argc, char **argv)
8403 {
8404 int c;
8405 int ret = 0;
8406 boolean_t scrub_restart = B_TRUE;
8407
8408 /* check options */
8409 while ((c = getopt(argc, argv, "n")) != -1) {
8410 switch (c) {
8411 case 'n':
8412 scrub_restart = B_FALSE;
8413 break;
8414 case '?':
8415 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8416 optopt);
8417 usage(B_FALSE);
8418 }
8419 }
8420
8421 argc -= optind;
8422 argv += optind;
8423
8424 /* if argc == 0 we will execute zpool_reopen_one on all pools */
8425 ret = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8426 B_FALSE, zpool_reopen_one, &scrub_restart);
8427
8428 return (ret);
8429 }
8430
8431 typedef struct scrub_cbdata {
8432 int cb_type;
8433 pool_scrub_cmd_t cb_scrub_cmd;
8434 time_t cb_date_start;
8435 time_t cb_date_end;
8436 } scrub_cbdata_t;
8437
8438 static boolean_t
zpool_has_checkpoint(zpool_handle_t * zhp)8439 zpool_has_checkpoint(zpool_handle_t *zhp)
8440 {
8441 nvlist_t *config, *nvroot;
8442
8443 config = zpool_get_config(zhp, NULL);
8444
8445 if (config != NULL) {
8446 pool_checkpoint_stat_t *pcs = NULL;
8447 uint_t c;
8448
8449 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
8450 (void) nvlist_lookup_uint64_array(nvroot,
8451 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
8452
8453 if (pcs == NULL || pcs->pcs_state == CS_NONE)
8454 return (B_FALSE);
8455
8456 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS ||
8457 pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
8458 return (B_TRUE);
8459 }
8460
8461 return (B_FALSE);
8462 }
8463
8464 static int
scrub_callback(zpool_handle_t * zhp,void * data)8465 scrub_callback(zpool_handle_t *zhp, void *data)
8466 {
8467 scrub_cbdata_t *cb = data;
8468 int err;
8469
8470 /*
8471 * Ignore faulted pools.
8472 */
8473 if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
8474 (void) fprintf(stderr, gettext("cannot scan '%s': pool is "
8475 "currently unavailable\n"), zpool_get_name(zhp));
8476 return (1);
8477 }
8478
8479 err = zpool_scan_range(zhp, cb->cb_type, cb->cb_scrub_cmd,
8480 cb->cb_date_start, cb->cb_date_end);
8481 if (err == 0 && zpool_has_checkpoint(zhp) &&
8482 cb->cb_type == POOL_SCAN_SCRUB) {
8483 (void) printf(gettext("warning: will not scrub state that "
8484 "belongs to the checkpoint of pool '%s'\n"),
8485 zpool_get_name(zhp));
8486 }
8487
8488 return (err != 0);
8489 }
8490
8491 static int
wait_callback(zpool_handle_t * zhp,void * data)8492 wait_callback(zpool_handle_t *zhp, void *data)
8493 {
8494 zpool_wait_activity_t *act = data;
8495 return (zpool_wait(zhp, *act));
8496 }
8497
8498 static time_t
date_string_to_sec(const char * timestr,boolean_t rounding)8499 date_string_to_sec(const char *timestr, boolean_t rounding)
8500 {
8501 struct tm tm = {0};
8502 int adjustment = rounding ? 1 : 0;
8503
8504 /* Allow mktime to determine timezone. */
8505 tm.tm_isdst = -1;
8506
8507 if (strptime(timestr, "%Y-%m-%d %H:%M", &tm) == NULL) {
8508 if (strptime(timestr, "%Y-%m-%d", &tm) == NULL) {
8509 fprintf(stderr, gettext("Failed to parse the date.\n"));
8510 usage(B_FALSE);
8511 }
8512 adjustment *= 24 * 60 * 60;
8513 } else {
8514 adjustment *= 60;
8515 }
8516
8517 return (mktime(&tm) + adjustment);
8518 }
8519
8520 /*
8521 * zpool scrub [-e | -s | -p | -C | -E | -S] [-w] [-a | <pool> ...]
8522 *
8523 * -a Scrub all pools.
8524 * -e Only scrub blocks in the error log.
8525 * -E End date of scrub.
8526 * -S Start date of scrub.
8527 * -s Stop. Stops any in-progress scrub.
8528 * -p Pause. Pause in-progress scrub.
8529 * -w Wait. Blocks until scrub has completed.
8530 * -C Scrub from last saved txg.
8531 */
8532 int
zpool_do_scrub(int argc,char ** argv)8533 zpool_do_scrub(int argc, char **argv)
8534 {
8535 int c;
8536 scrub_cbdata_t cb;
8537 boolean_t wait = B_FALSE;
8538 int error;
8539
8540 cb.cb_type = POOL_SCAN_SCRUB;
8541 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8542 cb.cb_date_start = cb.cb_date_end = 0;
8543
8544 boolean_t is_error_scrub = B_FALSE;
8545 boolean_t is_pause = B_FALSE;
8546 boolean_t is_stop = B_FALSE;
8547 boolean_t is_txg_continue = B_FALSE;
8548 boolean_t scrub_all = B_FALSE;
8549
8550 /* check options */
8551 while ((c = getopt(argc, argv, "aspweCE:S:")) != -1) {
8552 switch (c) {
8553 case 'a':
8554 scrub_all = B_TRUE;
8555 break;
8556 case 'e':
8557 is_error_scrub = B_TRUE;
8558 break;
8559 case 'E':
8560 /*
8561 * Round the date. It's better to scrub more data than
8562 * less. This also makes the date inclusive.
8563 */
8564 cb.cb_date_end = date_string_to_sec(optarg, B_TRUE);
8565 break;
8566 case 's':
8567 is_stop = B_TRUE;
8568 break;
8569 case 'S':
8570 cb.cb_date_start = date_string_to_sec(optarg, B_FALSE);
8571 break;
8572 case 'p':
8573 is_pause = B_TRUE;
8574 break;
8575 case 'w':
8576 wait = B_TRUE;
8577 break;
8578 case 'C':
8579 is_txg_continue = B_TRUE;
8580 break;
8581 case '?':
8582 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8583 optopt);
8584 usage(B_FALSE);
8585 }
8586 }
8587
8588 if (is_pause && is_stop) {
8589 (void) fprintf(stderr, gettext("invalid option "
8590 "combination: -s and -p are mutually exclusive\n"));
8591 usage(B_FALSE);
8592 } else if (is_pause && is_txg_continue) {
8593 (void) fprintf(stderr, gettext("invalid option "
8594 "combination: -p and -C are mutually exclusive\n"));
8595 usage(B_FALSE);
8596 } else if (is_stop && is_txg_continue) {
8597 (void) fprintf(stderr, gettext("invalid option "
8598 "combination: -s and -C are mutually exclusive\n"));
8599 usage(B_FALSE);
8600 } else if (is_error_scrub && is_txg_continue) {
8601 (void) fprintf(stderr, gettext("invalid option "
8602 "combination: -e and -C are mutually exclusive\n"));
8603 usage(B_FALSE);
8604 } else {
8605 if (is_error_scrub)
8606 cb.cb_type = POOL_SCAN_ERRORSCRUB;
8607
8608 if (is_pause) {
8609 cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
8610 } else if (is_stop) {
8611 cb.cb_type = POOL_SCAN_NONE;
8612 } else if (is_txg_continue) {
8613 cb.cb_scrub_cmd = POOL_SCRUB_FROM_LAST_TXG;
8614 } else {
8615 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8616 }
8617 }
8618
8619 if ((cb.cb_date_start != 0 || cb.cb_date_end != 0) &&
8620 cb.cb_scrub_cmd != POOL_SCRUB_NORMAL) {
8621 (void) fprintf(stderr, gettext("invalid option combination: "
8622 "start/end date is available only with normal scrub\n"));
8623 usage(B_FALSE);
8624 }
8625 if (cb.cb_date_start != 0 && cb.cb_date_end != 0 &&
8626 cb.cb_date_start > cb.cb_date_end) {
8627 (void) fprintf(stderr, gettext("invalid arguments: "
8628 "end date has to be later than start date\n"));
8629 usage(B_FALSE);
8630 }
8631
8632 if (wait && (cb.cb_type == POOL_SCAN_NONE ||
8633 cb.cb_scrub_cmd == POOL_SCRUB_PAUSE)) {
8634 (void) fprintf(stderr, gettext("invalid option combination: "
8635 "-w cannot be used with -p or -s\n"));
8636 usage(B_FALSE);
8637 }
8638
8639 argc -= optind;
8640 argv += optind;
8641
8642 if (argc < 1 && !scrub_all) {
8643 (void) fprintf(stderr, gettext("missing pool name argument\n"));
8644 usage(B_FALSE);
8645 }
8646
8647 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8648 B_FALSE, scrub_callback, &cb);
8649
8650 if (wait && !error) {
8651 zpool_wait_activity_t act = ZPOOL_WAIT_SCRUB;
8652 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8653 B_FALSE, wait_callback, &act);
8654 }
8655
8656 return (error);
8657 }
8658
8659 /*
8660 * zpool resilver <pool> ...
8661 *
8662 * Restarts any in-progress resilver
8663 */
8664 int
zpool_do_resilver(int argc,char ** argv)8665 zpool_do_resilver(int argc, char **argv)
8666 {
8667 int c;
8668 scrub_cbdata_t cb;
8669
8670 cb.cb_type = POOL_SCAN_RESILVER;
8671 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
8672 cb.cb_date_start = cb.cb_date_end = 0;
8673
8674 /* check options */
8675 while ((c = getopt(argc, argv, "")) != -1) {
8676 switch (c) {
8677 case '?':
8678 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8679 optopt);
8680 usage(B_FALSE);
8681 }
8682 }
8683
8684 argc -= optind;
8685 argv += optind;
8686
8687 if (argc < 1) {
8688 (void) fprintf(stderr, gettext("missing pool name argument\n"));
8689 usage(B_FALSE);
8690 }
8691
8692 return (for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8693 B_FALSE, scrub_callback, &cb));
8694 }
8695
8696 /*
8697 * zpool trim [-d] [-r <rate>] [-c | -s] <-a | pool> [<device> ...]
8698 *
8699 * -a Trim all pools.
8700 * -c Cancel. Ends any in-progress trim.
8701 * -d Secure trim. Requires kernel and device support.
8702 * -r <rate> Sets the TRIM rate in bytes (per second). Supports
8703 * adding a multiplier suffix such as 'k' or 'm'.
8704 * -s Suspend. TRIM can then be restarted with no flags.
8705 * -w Wait. Blocks until trimming has completed.
8706 */
8707 int
zpool_do_trim(int argc,char ** argv)8708 zpool_do_trim(int argc, char **argv)
8709 {
8710 struct option long_options[] = {
8711 {"cancel", no_argument, NULL, 'c'},
8712 {"secure", no_argument, NULL, 'd'},
8713 {"rate", required_argument, NULL, 'r'},
8714 {"suspend", no_argument, NULL, 's'},
8715 {"wait", no_argument, NULL, 'w'},
8716 {"all", no_argument, NULL, 'a'},
8717 {0, 0, 0, 0}
8718 };
8719
8720 pool_trim_func_t cmd_type = POOL_TRIM_START;
8721 uint64_t rate = 0;
8722 boolean_t secure = B_FALSE;
8723 boolean_t wait = B_FALSE;
8724 boolean_t trimall = B_FALSE;
8725 int error;
8726
8727 int c;
8728 while ((c = getopt_long(argc, argv, "acdr:sw", long_options, NULL))
8729 != -1) {
8730 switch (c) {
8731 case 'a':
8732 trimall = B_TRUE;
8733 break;
8734 case 'c':
8735 if (cmd_type != POOL_TRIM_START &&
8736 cmd_type != POOL_TRIM_CANCEL) {
8737 (void) fprintf(stderr, gettext("-c cannot be "
8738 "combined with other options\n"));
8739 usage(B_FALSE);
8740 }
8741 cmd_type = POOL_TRIM_CANCEL;
8742 break;
8743 case 'd':
8744 if (cmd_type != POOL_TRIM_START) {
8745 (void) fprintf(stderr, gettext("-d cannot be "
8746 "combined with the -c or -s options\n"));
8747 usage(B_FALSE);
8748 }
8749 secure = B_TRUE;
8750 break;
8751 case 'r':
8752 if (cmd_type != POOL_TRIM_START) {
8753 (void) fprintf(stderr, gettext("-r cannot be "
8754 "combined with the -c or -s options\n"));
8755 usage(B_FALSE);
8756 }
8757 if (zfs_nicestrtonum(g_zfs, optarg, &rate) == -1) {
8758 (void) fprintf(stderr, "%s: %s\n",
8759 gettext("invalid value for rate"),
8760 libzfs_error_description(g_zfs));
8761 usage(B_FALSE);
8762 }
8763 break;
8764 case 's':
8765 if (cmd_type != POOL_TRIM_START &&
8766 cmd_type != POOL_TRIM_SUSPEND) {
8767 (void) fprintf(stderr, gettext("-s cannot be "
8768 "combined with other options\n"));
8769 usage(B_FALSE);
8770 }
8771 cmd_type = POOL_TRIM_SUSPEND;
8772 break;
8773 case 'w':
8774 wait = B_TRUE;
8775 break;
8776 case '?':
8777 if (optopt != 0) {
8778 (void) fprintf(stderr,
8779 gettext("invalid option '%c'\n"), optopt);
8780 } else {
8781 (void) fprintf(stderr,
8782 gettext("invalid option '%s'\n"),
8783 argv[optind - 1]);
8784 }
8785 usage(B_FALSE);
8786 }
8787 }
8788
8789 argc -= optind;
8790 argv += optind;
8791
8792 trimflags_t trim_flags = {
8793 .secure = secure,
8794 .rate = rate,
8795 .wait = wait,
8796 };
8797
8798 trim_cbdata_t cbdata = {
8799 .trim_flags = trim_flags,
8800 .cmd_type = cmd_type
8801 };
8802
8803 if (argc < 1 && !trimall) {
8804 (void) fprintf(stderr, gettext("missing pool name argument\n"));
8805 usage(B_FALSE);
8806 }
8807
8808 if (wait && (cmd_type != POOL_TRIM_START)) {
8809 (void) fprintf(stderr, gettext("-w cannot be used with -c or "
8810 "-s options\n"));
8811 usage(B_FALSE);
8812 }
8813
8814 if (trimall && argc > 0) {
8815 (void) fprintf(stderr, gettext("-a cannot be combined with "
8816 "individual zpools or vdevs\n"));
8817 usage(B_FALSE);
8818 }
8819
8820 if (argc == 0 && trimall) {
8821 cbdata.trim_flags.fullpool = B_TRUE;
8822 /* Trim each pool recursively */
8823 error = for_each_pool(argc, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
8824 B_FALSE, zpool_trim_one, &cbdata);
8825 } else if (argc == 1) {
8826 char *poolname = argv[0];
8827 zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8828 if (zhp == NULL)
8829 return (-1);
8830 /* no individual leaf vdevs specified, so add them all */
8831 error = zpool_trim_one(zhp, &cbdata);
8832 zpool_close(zhp);
8833 } else {
8834 char *poolname = argv[0];
8835 zpool_handle_t *zhp = zpool_open(g_zfs, poolname);
8836 if (zhp == NULL)
8837 return (-1);
8838 /* leaf vdevs specified, trim only those */
8839 cbdata.trim_flags.fullpool = B_FALSE;
8840 nvlist_t *vdevs = fnvlist_alloc();
8841 for (int i = 1; i < argc; i++) {
8842 fnvlist_add_boolean(vdevs, argv[i]);
8843 }
8844 error = zpool_trim(zhp, cbdata.cmd_type, vdevs,
8845 &cbdata.trim_flags);
8846 fnvlist_free(vdevs);
8847 zpool_close(zhp);
8848 }
8849
8850 return (error);
8851 }
8852
8853 /*
8854 * Converts a total number of seconds to a human readable string broken
8855 * down in to days/hours/minutes/seconds.
8856 */
8857 static void
secs_to_dhms(uint64_t total,char * buf)8858 secs_to_dhms(uint64_t total, char *buf)
8859 {
8860 uint64_t days = total / 60 / 60 / 24;
8861 uint64_t hours = (total / 60 / 60) % 24;
8862 uint64_t mins = (total / 60) % 60;
8863 uint64_t secs = (total % 60);
8864
8865 if (days > 0) {
8866 (void) sprintf(buf, "%llu days %02llu:%02llu:%02llu",
8867 (u_longlong_t)days, (u_longlong_t)hours,
8868 (u_longlong_t)mins, (u_longlong_t)secs);
8869 } else {
8870 (void) sprintf(buf, "%02llu:%02llu:%02llu",
8871 (u_longlong_t)hours, (u_longlong_t)mins,
8872 (u_longlong_t)secs);
8873 }
8874 }
8875
8876 /*
8877 * Print out detailed error scrub status.
8878 */
8879 static void
print_err_scrub_status(pool_scan_stat_t * ps)8880 print_err_scrub_status(pool_scan_stat_t *ps)
8881 {
8882 time_t start, end, pause;
8883 uint64_t total_secs_left;
8884 uint64_t secs_left, mins_left, hours_left, days_left;
8885 uint64_t examined, to_be_examined;
8886
8887 if (ps == NULL || ps->pss_error_scrub_func != POOL_SCAN_ERRORSCRUB) {
8888 return;
8889 }
8890
8891 (void) printf(gettext(" scrub: "));
8892
8893 start = ps->pss_error_scrub_start;
8894 end = ps->pss_error_scrub_end;
8895 pause = ps->pss_pass_error_scrub_pause;
8896 examined = ps->pss_error_scrub_examined;
8897 to_be_examined = ps->pss_error_scrub_to_be_examined;
8898
8899 assert(ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB);
8900
8901 if (ps->pss_error_scrub_state == DSS_FINISHED) {
8902 total_secs_left = end - start;
8903 days_left = total_secs_left / 60 / 60 / 24;
8904 hours_left = (total_secs_left / 60 / 60) % 24;
8905 mins_left = (total_secs_left / 60) % 60;
8906 secs_left = (total_secs_left % 60);
8907
8908 (void) printf(gettext("scrubbed %llu error blocks in %llu days "
8909 "%02llu:%02llu:%02llu on %s"), (u_longlong_t)examined,
8910 (u_longlong_t)days_left, (u_longlong_t)hours_left,
8911 (u_longlong_t)mins_left, (u_longlong_t)secs_left,
8912 ctime(&end));
8913
8914 return;
8915 } else if (ps->pss_error_scrub_state == DSS_CANCELED) {
8916 (void) printf(gettext("error scrub canceled on %s"),
8917 ctime(&end));
8918 return;
8919 }
8920 assert(ps->pss_error_scrub_state == DSS_ERRORSCRUBBING);
8921
8922 /* Error scrub is in progress. */
8923 if (pause == 0) {
8924 (void) printf(gettext("error scrub in progress since %s"),
8925 ctime(&start));
8926 } else {
8927 (void) printf(gettext("error scrub paused since %s"),
8928 ctime(&pause));
8929 (void) printf(gettext("\terror scrub started on %s"),
8930 ctime(&start));
8931 }
8932
8933 double fraction_done = (double)examined / (to_be_examined + examined);
8934 (void) printf(gettext("\t%.2f%% done, issued I/O for %llu error"
8935 " blocks"), 100 * fraction_done, (u_longlong_t)examined);
8936
8937 (void) printf("\n");
8938 }
8939
8940 /*
8941 * Print out detailed scrub status.
8942 */
8943 static void
print_scan_scrub_resilver_status(pool_scan_stat_t * ps)8944 print_scan_scrub_resilver_status(pool_scan_stat_t *ps)
8945 {
8946 time_t start, end, pause;
8947 uint64_t pass_scanned, scanned, pass_issued, issued, total_s, total_i;
8948 uint64_t elapsed, scan_rate, issue_rate;
8949 double fraction_done;
8950 char processed_buf[7], scanned_buf[7], issued_buf[7], total_s_buf[7];
8951 char total_i_buf[7], srate_buf[7], irate_buf[7], time_buf[32];
8952
8953 printf(" ");
8954 (void) printf_color(ANSI_BOLD, gettext("scan:"));
8955 printf(" ");
8956
8957 /* If there's never been a scan, there's not much to say. */
8958 if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
8959 ps->pss_func >= POOL_SCAN_FUNCS) {
8960 (void) printf(gettext("none requested\n"));
8961 return;
8962 }
8963
8964 start = ps->pss_start_time;
8965 end = ps->pss_end_time;
8966 pause = ps->pss_pass_scrub_pause;
8967
8968 zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
8969
8970 int is_resilver = ps->pss_func == POOL_SCAN_RESILVER;
8971 int is_scrub = ps->pss_func == POOL_SCAN_SCRUB;
8972 assert(is_resilver || is_scrub);
8973
8974 /* Scan is finished or canceled. */
8975 if (ps->pss_state == DSS_FINISHED) {
8976 secs_to_dhms(end - start, time_buf);
8977
8978 if (is_scrub) {
8979 (void) printf(gettext("scrub repaired %s "
8980 "in %s with %llu errors on %s"), processed_buf,
8981 time_buf, (u_longlong_t)ps->pss_errors,
8982 ctime(&end));
8983 } else if (is_resilver) {
8984 (void) printf(gettext("resilvered %s "
8985 "in %s with %llu errors on %s"), processed_buf,
8986 time_buf, (u_longlong_t)ps->pss_errors,
8987 ctime(&end));
8988 }
8989 return;
8990 } else if (ps->pss_state == DSS_CANCELED) {
8991 if (is_scrub) {
8992 (void) printf(gettext("scrub canceled on %s"),
8993 ctime(&end));
8994 } else if (is_resilver) {
8995 (void) printf(gettext("resilver canceled on %s"),
8996 ctime(&end));
8997 }
8998 return;
8999 }
9000
9001 assert(ps->pss_state == DSS_SCANNING);
9002
9003 /* Scan is in progress. Resilvers can't be paused. */
9004 if (is_scrub) {
9005 if (pause == 0) {
9006 (void) printf(gettext("scrub in progress since %s"),
9007 ctime(&start));
9008 } else {
9009 (void) printf(gettext("scrub paused since %s"),
9010 ctime(&pause));
9011 (void) printf(gettext("\tscrub started on %s"),
9012 ctime(&start));
9013 }
9014 } else if (is_resilver) {
9015 (void) printf(gettext("resilver in progress since %s"),
9016 ctime(&start));
9017 }
9018
9019 scanned = ps->pss_examined;
9020 pass_scanned = ps->pss_pass_exam;
9021 issued = ps->pss_issued;
9022 pass_issued = ps->pss_pass_issued;
9023 total_s = ps->pss_to_examine;
9024 total_i = ps->pss_to_examine - ps->pss_skipped;
9025
9026 /* we are only done with a block once we have issued the IO for it */
9027 fraction_done = (double)issued / total_i;
9028
9029 /* elapsed time for this pass, rounding up to 1 if it's 0 */
9030 elapsed = time(NULL) - ps->pss_pass_start;
9031 elapsed -= ps->pss_pass_scrub_spent_paused;
9032 elapsed = (elapsed != 0) ? elapsed : 1;
9033
9034 scan_rate = pass_scanned / elapsed;
9035 issue_rate = pass_issued / elapsed;
9036
9037 /* format all of the numbers we will be reporting */
9038 zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
9039 zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
9040 zfs_nicebytes(total_s, total_s_buf, sizeof (total_s_buf));
9041 zfs_nicebytes(total_i, total_i_buf, sizeof (total_i_buf));
9042
9043 /* do not print estimated time if we have a paused scrub */
9044 (void) printf(gettext("\t%s / %s scanned"), scanned_buf, total_s_buf);
9045 if (pause == 0 && scan_rate > 0) {
9046 zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
9047 (void) printf(gettext(" at %s/s"), srate_buf);
9048 }
9049 (void) printf(gettext(", %s / %s issued"), issued_buf, total_i_buf);
9050 if (pause == 0 && issue_rate > 0) {
9051 zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
9052 (void) printf(gettext(" at %s/s"), irate_buf);
9053 }
9054 (void) printf(gettext("\n"));
9055
9056 if (is_resilver) {
9057 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
9058 processed_buf, 100 * fraction_done);
9059 } else if (is_scrub) {
9060 (void) printf(gettext("\t%s repaired, %.2f%% done"),
9061 processed_buf, 100 * fraction_done);
9062 }
9063
9064 if (pause == 0) {
9065 /*
9066 * Only provide an estimate iff:
9067 * 1) we haven't yet issued all we expected, and
9068 * 2) the issue rate exceeds 10 MB/s, and
9069 * 3) it's either:
9070 * a) a resilver which has started repairs, or
9071 * b) a scrub which has entered the issue phase.
9072 */
9073 if (total_i >= issued && issue_rate >= 10 * 1024 * 1024 &&
9074 ((is_resilver && ps->pss_processed > 0) ||
9075 (is_scrub && issued > 0))) {
9076 secs_to_dhms((total_i - issued) / issue_rate, time_buf);
9077 (void) printf(gettext(", %s to go\n"), time_buf);
9078 } else {
9079 (void) printf(gettext(", no estimated "
9080 "completion time\n"));
9081 }
9082 } else {
9083 (void) printf(gettext("\n"));
9084 }
9085 }
9086
9087 static void
print_rebuild_status_impl(vdev_rebuild_stat_t * vrs,uint_t c,char * vdev_name)9088 print_rebuild_status_impl(vdev_rebuild_stat_t *vrs, uint_t c, char *vdev_name)
9089 {
9090 if (vrs == NULL || vrs->vrs_state == VDEV_REBUILD_NONE)
9091 return;
9092
9093 printf(" ");
9094 (void) printf_color(ANSI_BOLD, gettext("scan:"));
9095 printf(" ");
9096
9097 uint64_t bytes_scanned = vrs->vrs_bytes_scanned;
9098 uint64_t bytes_issued = vrs->vrs_bytes_issued;
9099 uint64_t bytes_rebuilt = vrs->vrs_bytes_rebuilt;
9100 uint64_t bytes_est_s = vrs->vrs_bytes_est;
9101 uint64_t bytes_est_i = vrs->vrs_bytes_est;
9102 if (c > offsetof(vdev_rebuild_stat_t, vrs_pass_bytes_skipped) / 8)
9103 bytes_est_i -= vrs->vrs_pass_bytes_skipped;
9104 uint64_t scan_rate = (vrs->vrs_pass_bytes_scanned /
9105 (vrs->vrs_pass_time_ms + 1)) * 1000;
9106 uint64_t issue_rate = (vrs->vrs_pass_bytes_issued /
9107 (vrs->vrs_pass_time_ms + 1)) * 1000;
9108 double scan_pct = MIN((double)bytes_scanned * 100 /
9109 (bytes_est_s + 1), 100);
9110
9111 /* Format all of the numbers we will be reporting */
9112 char bytes_scanned_buf[7], bytes_issued_buf[7];
9113 char bytes_rebuilt_buf[7], bytes_est_s_buf[7], bytes_est_i_buf[7];
9114 char scan_rate_buf[7], issue_rate_buf[7], time_buf[32];
9115 zfs_nicebytes(bytes_scanned, bytes_scanned_buf,
9116 sizeof (bytes_scanned_buf));
9117 zfs_nicebytes(bytes_issued, bytes_issued_buf,
9118 sizeof (bytes_issued_buf));
9119 zfs_nicebytes(bytes_rebuilt, bytes_rebuilt_buf,
9120 sizeof (bytes_rebuilt_buf));
9121 zfs_nicebytes(bytes_est_s, bytes_est_s_buf, sizeof (bytes_est_s_buf));
9122 zfs_nicebytes(bytes_est_i, bytes_est_i_buf, sizeof (bytes_est_i_buf));
9123
9124 time_t start = vrs->vrs_start_time;
9125 time_t end = vrs->vrs_end_time;
9126
9127 /* Rebuild is finished or canceled. */
9128 if (vrs->vrs_state == VDEV_REBUILD_COMPLETE) {
9129 secs_to_dhms(vrs->vrs_scan_time_ms / 1000, time_buf);
9130 (void) printf(gettext("resilvered (%s) %s in %s "
9131 "with %llu errors on %s"), vdev_name, bytes_rebuilt_buf,
9132 time_buf, (u_longlong_t)vrs->vrs_errors, ctime(&end));
9133 return;
9134 } else if (vrs->vrs_state == VDEV_REBUILD_CANCELED) {
9135 (void) printf(gettext("resilver (%s) canceled on %s"),
9136 vdev_name, ctime(&end));
9137 return;
9138 } else if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9139 (void) printf(gettext("resilver (%s) in progress since %s"),
9140 vdev_name, ctime(&start));
9141 }
9142
9143 assert(vrs->vrs_state == VDEV_REBUILD_ACTIVE);
9144
9145 (void) printf(gettext("\t%s / %s scanned"), bytes_scanned_buf,
9146 bytes_est_s_buf);
9147 if (scan_rate > 0) {
9148 zfs_nicebytes(scan_rate, scan_rate_buf, sizeof (scan_rate_buf));
9149 (void) printf(gettext(" at %s/s"), scan_rate_buf);
9150 }
9151 (void) printf(gettext(", %s / %s issued"), bytes_issued_buf,
9152 bytes_est_i_buf);
9153 if (issue_rate > 0) {
9154 zfs_nicebytes(issue_rate, issue_rate_buf,
9155 sizeof (issue_rate_buf));
9156 (void) printf(gettext(" at %s/s"), issue_rate_buf);
9157 }
9158 (void) printf(gettext("\n"));
9159
9160 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
9161 bytes_rebuilt_buf, scan_pct);
9162
9163 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9164 if (bytes_est_s >= bytes_scanned &&
9165 scan_rate >= 10 * 1024 * 1024) {
9166 secs_to_dhms((bytes_est_s - bytes_scanned) / scan_rate,
9167 time_buf);
9168 (void) printf(gettext(", %s to go\n"), time_buf);
9169 } else {
9170 (void) printf(gettext(", no estimated "
9171 "completion time\n"));
9172 }
9173 } else {
9174 (void) printf(gettext("\n"));
9175 }
9176 }
9177
9178 /*
9179 * Print rebuild status for top-level vdevs.
9180 */
9181 static void
print_rebuild_status(zpool_handle_t * zhp,nvlist_t * nvroot)9182 print_rebuild_status(zpool_handle_t *zhp, nvlist_t *nvroot)
9183 {
9184 nvlist_t **child;
9185 uint_t children;
9186
9187 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9188 &child, &children) != 0)
9189 children = 0;
9190
9191 for (uint_t c = 0; c < children; c++) {
9192 vdev_rebuild_stat_t *vrs;
9193 uint_t i;
9194
9195 if (nvlist_lookup_uint64_array(child[c],
9196 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9197 char *name = zpool_vdev_name(g_zfs, zhp,
9198 child[c], VDEV_NAME_TYPE_ID);
9199 print_rebuild_status_impl(vrs, i, name);
9200 free(name);
9201 }
9202 }
9203 }
9204
9205 /*
9206 * As we don't scrub checkpointed blocks, we want to warn the user that we
9207 * skipped scanning some blocks if a checkpoint exists or existed at any
9208 * time during the scan. If a sequential instead of healing reconstruction
9209 * was performed then the blocks were reconstructed. However, their checksums
9210 * have not been verified so we still print the warning.
9211 */
9212 static void
print_checkpoint_scan_warning(pool_scan_stat_t * ps,pool_checkpoint_stat_t * pcs)9213 print_checkpoint_scan_warning(pool_scan_stat_t *ps, pool_checkpoint_stat_t *pcs)
9214 {
9215 if (ps == NULL || pcs == NULL)
9216 return;
9217
9218 if (pcs->pcs_state == CS_NONE ||
9219 pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
9220 return;
9221
9222 assert(pcs->pcs_state == CS_CHECKPOINT_EXISTS);
9223
9224 if (ps->pss_state == DSS_NONE)
9225 return;
9226
9227 if ((ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) &&
9228 ps->pss_end_time < pcs->pcs_start_time)
9229 return;
9230
9231 if (ps->pss_state == DSS_FINISHED || ps->pss_state == DSS_CANCELED) {
9232 (void) printf(gettext(" scan warning: skipped blocks "
9233 "that are only referenced by the checkpoint.\n"));
9234 } else {
9235 assert(ps->pss_state == DSS_SCANNING);
9236 (void) printf(gettext(" scan warning: skipping blocks "
9237 "that are only referenced by the checkpoint.\n"));
9238 }
9239 }
9240
9241 /*
9242 * Returns B_TRUE if there is an active rebuild in progress. Otherwise,
9243 * B_FALSE is returned and 'rebuild_end_time' is set to the end time for
9244 * the last completed (or cancelled) rebuild.
9245 */
9246 static boolean_t
check_rebuilding(nvlist_t * nvroot,uint64_t * rebuild_end_time)9247 check_rebuilding(nvlist_t *nvroot, uint64_t *rebuild_end_time)
9248 {
9249 nvlist_t **child;
9250 uint_t children;
9251 boolean_t rebuilding = B_FALSE;
9252 uint64_t end_time = 0;
9253
9254 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9255 &child, &children) != 0)
9256 children = 0;
9257
9258 for (uint_t c = 0; c < children; c++) {
9259 vdev_rebuild_stat_t *vrs;
9260 uint_t i;
9261
9262 if (nvlist_lookup_uint64_array(child[c],
9263 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i) == 0) {
9264
9265 if (vrs->vrs_end_time > end_time)
9266 end_time = vrs->vrs_end_time;
9267
9268 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
9269 rebuilding = B_TRUE;
9270 end_time = 0;
9271 break;
9272 }
9273 }
9274 }
9275
9276 if (rebuild_end_time != NULL)
9277 *rebuild_end_time = end_time;
9278
9279 return (rebuilding);
9280 }
9281
9282 static void
vdev_stats_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,int depth,boolean_t isspare,char * parent,nvlist_t * item)9283 vdev_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9284 int depth, boolean_t isspare, char *parent, nvlist_t *item)
9285 {
9286 nvlist_t *vds, **child, *ch = NULL;
9287 uint_t vsc, children;
9288 vdev_stat_t *vs;
9289 char *vname;
9290 uint64_t notpresent;
9291 const char *type, *path;
9292
9293 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
9294 &child, &children) != 0)
9295 children = 0;
9296 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
9297 (uint64_t **)&vs, &vsc) == 0);
9298 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
9299 if (strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9300 return;
9301
9302 if (cb->cb_print_unhealthy && depth > 0 &&
9303 for_each_vdev_in_nvlist(nv, vdev_health_check_cb, cb) == 0) {
9304 return;
9305 }
9306 vname = zpool_vdev_name(g_zfs, zhp, nv,
9307 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9308 vds = fnvlist_alloc();
9309 fill_vdev_info(vds, zhp, vname, B_FALSE, cb->cb_json_as_int);
9310 if (cb->cb_flat_vdevs && parent != NULL) {
9311 fnvlist_add_string(vds, "parent", parent);
9312 }
9313
9314 if (isspare) {
9315 if (vs->vs_aux == VDEV_AUX_SPARED) {
9316 fnvlist_add_string(vds, "state", "INUSE");
9317 used_by_other(zhp, nv, vds);
9318 } else if (vs->vs_state == VDEV_STATE_HEALTHY)
9319 fnvlist_add_string(vds, "state", "AVAIL");
9320 } else {
9321 if (vs->vs_alloc) {
9322 nice_num_str_nvlist(vds, "alloc_space", vs->vs_alloc,
9323 cb->cb_literal, cb->cb_json_as_int,
9324 ZFS_NICENUM_BYTES);
9325 }
9326 if (vs->vs_space) {
9327 nice_num_str_nvlist(vds, "total_space", vs->vs_space,
9328 cb->cb_literal, cb->cb_json_as_int,
9329 ZFS_NICENUM_BYTES);
9330 }
9331 if (vs->vs_dspace) {
9332 nice_num_str_nvlist(vds, "def_space", vs->vs_dspace,
9333 cb->cb_literal, cb->cb_json_as_int,
9334 ZFS_NICENUM_BYTES);
9335 }
9336 if (vs->vs_rsize) {
9337 nice_num_str_nvlist(vds, "rep_dev_size", vs->vs_rsize,
9338 cb->cb_literal, cb->cb_json_as_int,
9339 ZFS_NICENUM_BYTES);
9340 }
9341 if (vs->vs_esize) {
9342 nice_num_str_nvlist(vds, "ex_dev_size", vs->vs_esize,
9343 cb->cb_literal, cb->cb_json_as_int,
9344 ZFS_NICENUM_BYTES);
9345 }
9346 if (vs->vs_self_healed) {
9347 nice_num_str_nvlist(vds, "self_healed",
9348 vs->vs_self_healed, cb->cb_literal,
9349 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9350 }
9351 if (vs->vs_pspace) {
9352 nice_num_str_nvlist(vds, "phys_space", vs->vs_pspace,
9353 cb->cb_literal, cb->cb_json_as_int,
9354 ZFS_NICENUM_BYTES);
9355 }
9356 nice_num_str_nvlist(vds, "read_errors", vs->vs_read_errors,
9357 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9358 nice_num_str_nvlist(vds, "write_errors", vs->vs_write_errors,
9359 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9360 nice_num_str_nvlist(vds, "checksum_errors",
9361 vs->vs_checksum_errors, cb->cb_literal,
9362 cb->cb_json_as_int, ZFS_NICENUM_1024);
9363 if (vs->vs_scan_processed) {
9364 nice_num_str_nvlist(vds, "scan_processed",
9365 vs->vs_scan_processed, cb->cb_literal,
9366 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9367 }
9368 if (vs->vs_checkpoint_space) {
9369 nice_num_str_nvlist(vds, "checkpoint_space",
9370 vs->vs_checkpoint_space, cb->cb_literal,
9371 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9372 }
9373 if (vs->vs_resilver_deferred) {
9374 nice_num_str_nvlist(vds, "resilver_deferred",
9375 vs->vs_resilver_deferred, B_TRUE,
9376 cb->cb_json_as_int, ZFS_NICENUM_1024);
9377 }
9378 if (children == 0) {
9379 nice_num_str_nvlist(vds, "slow_ios", vs->vs_slow_ios,
9380 cb->cb_literal, cb->cb_json_as_int,
9381 ZFS_NICENUM_1024);
9382 }
9383 if (cb->cb_print_power) {
9384 if (children == 0) {
9385 /* Only leaf vdevs have physical slots */
9386 switch (zpool_power_current_state(zhp, (char *)
9387 fnvlist_lookup_string(nv,
9388 ZPOOL_CONFIG_PATH))) {
9389 case 0:
9390 fnvlist_add_string(vds, "power_state",
9391 "off");
9392 break;
9393 case 1:
9394 fnvlist_add_string(vds, "power_state",
9395 "on");
9396 break;
9397 default:
9398 fnvlist_add_string(vds, "power_state",
9399 "-");
9400 }
9401 } else {
9402 fnvlist_add_string(vds, "power_state", "-");
9403 }
9404 }
9405 }
9406
9407 if (cb->cb_print_dio_verify) {
9408 nice_num_str_nvlist(vds, "dio_verify_errors",
9409 vs->vs_dio_verify_errors, cb->cb_literal,
9410 cb->cb_json_as_int, ZFS_NICENUM_1024);
9411 }
9412
9413 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
9414 ¬present) == 0) {
9415 nice_num_str_nvlist(vds, ZPOOL_CONFIG_NOT_PRESENT,
9416 1, B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9417 fnvlist_add_string(vds, "was",
9418 fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH));
9419 } else if (vs->vs_aux != VDEV_AUX_NONE) {
9420 fnvlist_add_string(vds, "aux", vdev_aux_str[vs->vs_aux]);
9421 } else if (children == 0 && !isspare &&
9422 getenv("ZPOOL_STATUS_NON_NATIVE_ASHIFT_IGNORE") == NULL &&
9423 VDEV_STAT_VALID(vs_physical_ashift, vsc) &&
9424 vs->vs_configured_ashift < vs->vs_physical_ashift) {
9425 nice_num_str_nvlist(vds, "configured_ashift",
9426 vs->vs_configured_ashift, B_TRUE, cb->cb_json_as_int,
9427 ZFS_NICENUM_1024);
9428 nice_num_str_nvlist(vds, "physical_ashift",
9429 vs->vs_physical_ashift, B_TRUE, cb->cb_json_as_int,
9430 ZFS_NICENUM_1024);
9431 }
9432 if (vs->vs_scan_removing != 0) {
9433 nice_num_str_nvlist(vds, "removing", vs->vs_scan_removing,
9434 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9435 } else if (VDEV_STAT_VALID(vs_noalloc, vsc) && vs->vs_noalloc != 0) {
9436 nice_num_str_nvlist(vds, "noalloc", vs->vs_noalloc,
9437 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9438 }
9439
9440 if (cb->vcdl != NULL) {
9441 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
9442 zpool_nvlist_cmd(cb->vcdl, zpool_get_name(zhp),
9443 path, vds);
9444 }
9445 }
9446
9447 if (children == 0) {
9448 if (cb->cb_print_vdev_init) {
9449 if (vs->vs_initialize_state != 0) {
9450 uint64_t st = vs->vs_initialize_state;
9451 fnvlist_add_string(vds, "init_state",
9452 vdev_init_state_str[st]);
9453 nice_num_str_nvlist(vds, "initialized",
9454 vs->vs_initialize_bytes_done,
9455 cb->cb_literal, cb->cb_json_as_int,
9456 ZFS_NICENUM_BYTES);
9457 nice_num_str_nvlist(vds, "to_initialize",
9458 vs->vs_initialize_bytes_est,
9459 cb->cb_literal, cb->cb_json_as_int,
9460 ZFS_NICENUM_BYTES);
9461 nice_num_str_nvlist(vds, "init_time",
9462 vs->vs_initialize_action_time,
9463 cb->cb_literal, cb->cb_json_as_int,
9464 ZFS_NICE_TIMESTAMP);
9465 nice_num_str_nvlist(vds, "init_errors",
9466 vs->vs_initialize_errors,
9467 cb->cb_literal, cb->cb_json_as_int,
9468 ZFS_NICENUM_1024);
9469 } else {
9470 fnvlist_add_string(vds, "init_state",
9471 "UNINITIALIZED");
9472 }
9473 }
9474 if (cb->cb_print_vdev_trim) {
9475 if (vs->vs_trim_notsup == 0) {
9476 if (vs->vs_trim_state != 0) {
9477 uint64_t st = vs->vs_trim_state;
9478 fnvlist_add_string(vds, "trim_state",
9479 vdev_trim_state_str[st]);
9480 nice_num_str_nvlist(vds, "trimmed",
9481 vs->vs_trim_bytes_done,
9482 cb->cb_literal, cb->cb_json_as_int,
9483 ZFS_NICENUM_BYTES);
9484 nice_num_str_nvlist(vds, "to_trim",
9485 vs->vs_trim_bytes_est,
9486 cb->cb_literal, cb->cb_json_as_int,
9487 ZFS_NICENUM_BYTES);
9488 nice_num_str_nvlist(vds, "trim_time",
9489 vs->vs_trim_action_time,
9490 cb->cb_literal, cb->cb_json_as_int,
9491 ZFS_NICE_TIMESTAMP);
9492 nice_num_str_nvlist(vds, "trim_errors",
9493 vs->vs_trim_errors,
9494 cb->cb_literal, cb->cb_json_as_int,
9495 ZFS_NICENUM_1024);
9496 } else
9497 fnvlist_add_string(vds, "trim_state",
9498 "UNTRIMMED");
9499 }
9500 nice_num_str_nvlist(vds, "trim_notsup",
9501 vs->vs_trim_notsup, B_TRUE,
9502 cb->cb_json_as_int, ZFS_NICENUM_1024);
9503 }
9504 } else {
9505 ch = fnvlist_alloc();
9506 }
9507
9508 if (cb->cb_flat_vdevs && children == 0) {
9509 fnvlist_add_nvlist(item, vname, vds);
9510 }
9511
9512 for (int c = 0; c < children; c++) {
9513 uint64_t islog = B_FALSE, ishole = B_FALSE;
9514 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9515 &islog);
9516 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
9517 &ishole);
9518 if (islog || ishole)
9519 continue;
9520 if (nvlist_exists(child[c], ZPOOL_CONFIG_ALLOCATION_BIAS))
9521 continue;
9522 if (cb->cb_flat_vdevs) {
9523 vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9524 vname, item);
9525 }
9526 vdev_stats_nvlist(zhp, cb, child[c], depth + 2, isspare,
9527 vname, ch);
9528 }
9529
9530 if (ch != NULL) {
9531 if (!nvlist_empty(ch))
9532 fnvlist_add_nvlist(vds, "vdevs", ch);
9533 fnvlist_free(ch);
9534 }
9535 fnvlist_add_nvlist(item, vname, vds);
9536 fnvlist_free(vds);
9537 free(vname);
9538 }
9539
9540 static void
class_vdevs_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,const char * class,nvlist_t * item)9541 class_vdevs_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9542 const char *class, nvlist_t *item)
9543 {
9544 uint_t c, children;
9545 nvlist_t **child;
9546 nvlist_t *class_obj = NULL;
9547
9548 if (!cb->cb_flat_vdevs)
9549 class_obj = fnvlist_alloc();
9550
9551 assert(zhp != NULL || !cb->cb_verbose);
9552
9553 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
9554 &children) != 0)
9555 return;
9556
9557 for (c = 0; c < children; c++) {
9558 uint64_t is_log = B_FALSE;
9559 const char *bias = NULL;
9560 const char *type = NULL;
9561 char *name = zpool_vdev_name(g_zfs, zhp, child[c],
9562 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
9563
9564 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
9565 &is_log);
9566
9567 if (is_log) {
9568 bias = (char *)VDEV_ALLOC_CLASS_LOGS;
9569 } else {
9570 (void) nvlist_lookup_string(child[c],
9571 ZPOOL_CONFIG_ALLOCATION_BIAS, &bias);
9572 (void) nvlist_lookup_string(child[c],
9573 ZPOOL_CONFIG_TYPE, &type);
9574 }
9575
9576 if (bias == NULL || strcmp(bias, class) != 0)
9577 continue;
9578 if (!is_log && strcmp(type, VDEV_TYPE_INDIRECT) == 0)
9579 continue;
9580
9581 if (cb->cb_flat_vdevs) {
9582 vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9583 NULL, item);
9584 } else {
9585 vdev_stats_nvlist(zhp, cb, child[c], 2, B_FALSE,
9586 NULL, class_obj);
9587 }
9588 free(name);
9589 }
9590 if (!cb->cb_flat_vdevs) {
9591 if (!nvlist_empty(class_obj))
9592 fnvlist_add_nvlist(item, class, class_obj);
9593 fnvlist_free(class_obj);
9594 }
9595 }
9596
9597 static void
l2cache_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,nvlist_t * item)9598 l2cache_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9599 nvlist_t *item)
9600 {
9601 nvlist_t *l2c = NULL, **l2cache;
9602 uint_t nl2cache;
9603 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
9604 &l2cache, &nl2cache) == 0) {
9605 if (nl2cache == 0)
9606 return;
9607 if (!cb->cb_flat_vdevs)
9608 l2c = fnvlist_alloc();
9609 for (int i = 0; i < nl2cache; i++) {
9610 if (cb->cb_flat_vdevs) {
9611 vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9612 B_FALSE, NULL, item);
9613 } else {
9614 vdev_stats_nvlist(zhp, cb, l2cache[i], 2,
9615 B_FALSE, NULL, l2c);
9616 }
9617 }
9618 }
9619 if (!cb->cb_flat_vdevs) {
9620 if (!nvlist_empty(l2c))
9621 fnvlist_add_nvlist(item, "l2cache", l2c);
9622 fnvlist_free(l2c);
9623 }
9624 }
9625
9626 static void
spares_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nv,nvlist_t * item)9627 spares_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv,
9628 nvlist_t *item)
9629 {
9630 nvlist_t *sp = NULL, **spares;
9631 uint_t nspares;
9632 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
9633 &spares, &nspares) == 0) {
9634 if (nspares == 0)
9635 return;
9636 if (!cb->cb_flat_vdevs)
9637 sp = fnvlist_alloc();
9638 for (int i = 0; i < nspares; i++) {
9639 if (cb->cb_flat_vdevs) {
9640 vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9641 NULL, item);
9642 } else {
9643 vdev_stats_nvlist(zhp, cb, spares[i], 2, B_TRUE,
9644 NULL, sp);
9645 }
9646 }
9647 }
9648 if (!cb->cb_flat_vdevs) {
9649 if (!nvlist_empty(sp))
9650 fnvlist_add_nvlist(item, "spares", sp);
9651 fnvlist_free(sp);
9652 }
9653 }
9654
9655 static void
errors_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * item)9656 errors_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9657 {
9658 uint64_t nerr;
9659 nvlist_t *config = zpool_get_config(zhp, NULL);
9660 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
9661 &nerr) == 0) {
9662 nice_num_str_nvlist(item, ZPOOL_CONFIG_ERRCOUNT, nerr,
9663 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9664 if (nerr != 0 && cb->cb_verbose) {
9665 nvlist_t *nverrlist = NULL;
9666 if (zpool_get_errlog(zhp, &nverrlist) == 0) {
9667 int i = 0;
9668 int count = 0;
9669 size_t len = MAXPATHLEN * 2;
9670 nvpair_t *elem = NULL;
9671
9672 for (nvpair_t *pair =
9673 nvlist_next_nvpair(nverrlist, NULL);
9674 pair != NULL;
9675 pair = nvlist_next_nvpair(nverrlist, pair))
9676 count++;
9677 char **errl = (char **)malloc(
9678 count * sizeof (char *));
9679
9680 while ((elem = nvlist_next_nvpair(nverrlist,
9681 elem)) != NULL) {
9682 nvlist_t *nv;
9683 uint64_t dsobj, obj;
9684
9685 verify(nvpair_value_nvlist(elem,
9686 &nv) == 0);
9687 verify(nvlist_lookup_uint64(nv,
9688 ZPOOL_ERR_DATASET, &dsobj) == 0);
9689 verify(nvlist_lookup_uint64(nv,
9690 ZPOOL_ERR_OBJECT, &obj) == 0);
9691 errl[i] = safe_malloc(len);
9692 zpool_obj_to_path(zhp, dsobj, obj,
9693 errl[i++], len);
9694 }
9695 nvlist_free(nverrlist);
9696 fnvlist_add_string_array(item, "errlist",
9697 (const char **)errl, count);
9698 for (int i = 0; i < count; ++i)
9699 free(errl[i]);
9700 free(errl);
9701 } else
9702 fnvlist_add_string(item, "errlist",
9703 strerror(errno));
9704 }
9705 }
9706 }
9707
9708 static void
ddt_stats_nvlist(ddt_stat_t * dds,status_cbdata_t * cb,nvlist_t * item)9709 ddt_stats_nvlist(ddt_stat_t *dds, status_cbdata_t *cb, nvlist_t *item)
9710 {
9711 nice_num_str_nvlist(item, "blocks", dds->dds_blocks,
9712 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9713 nice_num_str_nvlist(item, "logical_size", dds->dds_lsize,
9714 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9715 nice_num_str_nvlist(item, "physical_size", dds->dds_psize,
9716 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9717 nice_num_str_nvlist(item, "deflated_size", dds->dds_dsize,
9718 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9719 nice_num_str_nvlist(item, "ref_blocks", dds->dds_ref_blocks,
9720 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9721 nice_num_str_nvlist(item, "ref_lsize", dds->dds_ref_lsize,
9722 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9723 nice_num_str_nvlist(item, "ref_psize", dds->dds_ref_psize,
9724 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9725 nice_num_str_nvlist(item, "ref_dsize", dds->dds_ref_dsize,
9726 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9727 }
9728
9729 static void
dedup_stats_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * item)9730 dedup_stats_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *item)
9731 {
9732 nvlist_t *config;
9733 if (cb->cb_dedup_stats) {
9734 ddt_histogram_t *ddh;
9735 ddt_stat_t *dds;
9736 ddt_object_t *ddo;
9737 nvlist_t *ddt_stat, *ddt_obj, *dedup;
9738 uint_t c;
9739 uint64_t cspace_prop;
9740
9741 config = zpool_get_config(zhp, NULL);
9742 if (nvlist_lookup_uint64_array(config,
9743 ZPOOL_CONFIG_DDT_OBJ_STATS, (uint64_t **)&ddo, &c) != 0)
9744 return;
9745
9746 dedup = fnvlist_alloc();
9747 ddt_obj = fnvlist_alloc();
9748 nice_num_str_nvlist(dedup, "obj_count", ddo->ddo_count,
9749 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9750 if (ddo->ddo_count == 0) {
9751 fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
9752 ddt_obj);
9753 fnvlist_add_nvlist(item, "dedup_stats", dedup);
9754 fnvlist_free(ddt_obj);
9755 fnvlist_free(dedup);
9756 return;
9757 } else {
9758 nice_num_str_nvlist(dedup, "dspace", ddo->ddo_dspace,
9759 cb->cb_literal, cb->cb_json_as_int,
9760 ZFS_NICENUM_1024);
9761 nice_num_str_nvlist(dedup, "mspace", ddo->ddo_mspace,
9762 cb->cb_literal, cb->cb_json_as_int,
9763 ZFS_NICENUM_1024);
9764 /*
9765 * Squash cached size into in-core size to handle race.
9766 * Only include cached size if it is available.
9767 */
9768 cspace_prop = zpool_get_prop_int(zhp,
9769 ZPOOL_PROP_DEDUPCACHED, NULL);
9770 cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
9771 nice_num_str_nvlist(dedup, "cspace", cspace_prop,
9772 cb->cb_literal, cb->cb_json_as_int,
9773 ZFS_NICENUM_1024);
9774 }
9775
9776 ddt_stat = fnvlist_alloc();
9777 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
9778 (uint64_t **)&dds, &c) == 0) {
9779 nvlist_t *total = fnvlist_alloc();
9780 if (dds->dds_blocks == 0)
9781 fnvlist_add_string(total, "blocks", "0");
9782 else
9783 ddt_stats_nvlist(dds, cb, total);
9784 fnvlist_add_nvlist(ddt_stat, "total", total);
9785 fnvlist_free(total);
9786 }
9787 if (nvlist_lookup_uint64_array(config,
9788 ZPOOL_CONFIG_DDT_HISTOGRAM, (uint64_t **)&ddh, &c) == 0) {
9789 nvlist_t *hist = fnvlist_alloc();
9790 nvlist_t *entry = NULL;
9791 char buf[16];
9792 for (int h = 0; h < 64; h++) {
9793 if (ddh->ddh_stat[h].dds_blocks != 0) {
9794 entry = fnvlist_alloc();
9795 ddt_stats_nvlist(&ddh->ddh_stat[h], cb,
9796 entry);
9797 (void) snprintf(buf, 16, "%d", h);
9798 fnvlist_add_nvlist(hist, buf, entry);
9799 fnvlist_free(entry);
9800 }
9801 }
9802 if (!nvlist_empty(hist))
9803 fnvlist_add_nvlist(ddt_stat, "histogram", hist);
9804 fnvlist_free(hist);
9805 }
9806
9807 if (!nvlist_empty(ddt_obj)) {
9808 fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_OBJ_STATS,
9809 ddt_obj);
9810 }
9811 fnvlist_free(ddt_obj);
9812 if (!nvlist_empty(ddt_stat)) {
9813 fnvlist_add_nvlist(dedup, ZPOOL_CONFIG_DDT_STATS,
9814 ddt_stat);
9815 }
9816 fnvlist_free(ddt_stat);
9817 if (!nvlist_empty(dedup))
9818 fnvlist_add_nvlist(item, "dedup_stats", dedup);
9819 fnvlist_free(dedup);
9820 }
9821 }
9822
9823 static void
raidz_expand_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)9824 raidz_expand_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
9825 nvlist_t *nvroot, nvlist_t *item)
9826 {
9827 uint_t c;
9828 pool_raidz_expand_stat_t *pres = NULL;
9829 if (nvlist_lookup_uint64_array(nvroot,
9830 ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c) == 0) {
9831 nvlist_t **child;
9832 uint_t children;
9833 nvlist_t *nv = fnvlist_alloc();
9834 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
9835 &child, &children) == 0);
9836 assert(pres->pres_expanding_vdev < children);
9837 char *name =
9838 zpool_vdev_name(g_zfs, zhp,
9839 child[pres->pres_expanding_vdev], 0);
9840 fill_vdev_info(nv, zhp, name, B_FALSE, cb->cb_json_as_int);
9841 fnvlist_add_string(nv, "state",
9842 pool_scan_state_str[pres->pres_state]);
9843 nice_num_str_nvlist(nv, "expanding_vdev",
9844 pres->pres_expanding_vdev, B_TRUE, cb->cb_json_as_int,
9845 ZFS_NICENUM_1024);
9846 nice_num_str_nvlist(nv, "start_time", pres->pres_start_time,
9847 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9848 nice_num_str_nvlist(nv, "end_time", pres->pres_end_time,
9849 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9850 nice_num_str_nvlist(nv, "to_reflow", pres->pres_to_reflow,
9851 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9852 nice_num_str_nvlist(nv, "reflowed", pres->pres_reflowed,
9853 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9854 nice_num_str_nvlist(nv, "waiting_for_resilver",
9855 pres->pres_waiting_for_resilver, B_TRUE,
9856 cb->cb_json_as_int, ZFS_NICENUM_1024);
9857 fnvlist_add_nvlist(item, ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, nv);
9858 fnvlist_free(nv);
9859 free(name);
9860 }
9861 }
9862
9863 static void
checkpoint_status_nvlist(nvlist_t * nvroot,status_cbdata_t * cb,nvlist_t * item)9864 checkpoint_status_nvlist(nvlist_t *nvroot, status_cbdata_t *cb,
9865 nvlist_t *item)
9866 {
9867 uint_t c;
9868 pool_checkpoint_stat_t *pcs = NULL;
9869 if (nvlist_lookup_uint64_array(nvroot,
9870 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c) == 0) {
9871 nvlist_t *nv = fnvlist_alloc();
9872 fnvlist_add_string(nv, "state",
9873 checkpoint_state_str[pcs->pcs_state]);
9874 nice_num_str_nvlist(nv, "start_time",
9875 pcs->pcs_start_time, cb->cb_literal, cb->cb_json_as_int,
9876 ZFS_NICE_TIMESTAMP);
9877 nice_num_str_nvlist(nv, "space",
9878 pcs->pcs_space, cb->cb_literal, cb->cb_json_as_int,
9879 ZFS_NICENUM_BYTES);
9880 fnvlist_add_nvlist(item, ZPOOL_CONFIG_CHECKPOINT_STATS, nv);
9881 fnvlist_free(nv);
9882 }
9883 }
9884
9885 static void
removal_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)9886 removal_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
9887 nvlist_t *nvroot, nvlist_t *item)
9888 {
9889 uint_t c;
9890 pool_removal_stat_t *prs = NULL;
9891 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_REMOVAL_STATS,
9892 (uint64_t **)&prs, &c) == 0) {
9893 if (prs->prs_state != DSS_NONE) {
9894 nvlist_t **child;
9895 uint_t children;
9896 verify(nvlist_lookup_nvlist_array(nvroot,
9897 ZPOOL_CONFIG_CHILDREN, &child, &children) == 0);
9898 assert(prs->prs_removing_vdev < children);
9899 char *vdev_name = zpool_vdev_name(g_zfs, zhp,
9900 child[prs->prs_removing_vdev], B_TRUE);
9901 nvlist_t *nv = fnvlist_alloc();
9902 fill_vdev_info(nv, zhp, vdev_name, B_FALSE,
9903 cb->cb_json_as_int);
9904 fnvlist_add_string(nv, "state",
9905 pool_scan_state_str[prs->prs_state]);
9906 nice_num_str_nvlist(nv, "removing_vdev",
9907 prs->prs_removing_vdev, B_TRUE, cb->cb_json_as_int,
9908 ZFS_NICENUM_1024);
9909 nice_num_str_nvlist(nv, "start_time",
9910 prs->prs_start_time, cb->cb_literal,
9911 cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9912 nice_num_str_nvlist(nv, "end_time", prs->prs_end_time,
9913 cb->cb_literal, cb->cb_json_as_int,
9914 ZFS_NICE_TIMESTAMP);
9915 nice_num_str_nvlist(nv, "to_copy", prs->prs_to_copy,
9916 cb->cb_literal, cb->cb_json_as_int,
9917 ZFS_NICENUM_BYTES);
9918 nice_num_str_nvlist(nv, "copied", prs->prs_copied,
9919 cb->cb_literal, cb->cb_json_as_int,
9920 ZFS_NICENUM_BYTES);
9921 nice_num_str_nvlist(nv, "mapping_memory",
9922 prs->prs_mapping_memory, cb->cb_literal,
9923 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9924 fnvlist_add_nvlist(item,
9925 ZPOOL_CONFIG_REMOVAL_STATS, nv);
9926 fnvlist_free(nv);
9927 free(vdev_name);
9928 }
9929 }
9930 }
9931
9932 static void
scan_status_nvlist(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t * nvroot,nvlist_t * item)9933 scan_status_nvlist(zpool_handle_t *zhp, status_cbdata_t *cb,
9934 nvlist_t *nvroot, nvlist_t *item)
9935 {
9936 pool_scan_stat_t *ps = NULL;
9937 uint_t c;
9938 nvlist_t *scan = fnvlist_alloc();
9939 nvlist_t **child;
9940 uint_t children;
9941
9942 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
9943 (uint64_t **)&ps, &c) == 0) {
9944 fnvlist_add_string(scan, "function",
9945 pool_scan_func_str[ps->pss_func]);
9946 fnvlist_add_string(scan, "state",
9947 pool_scan_state_str[ps->pss_state]);
9948 nice_num_str_nvlist(scan, "start_time", ps->pss_start_time,
9949 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9950 nice_num_str_nvlist(scan, "end_time", ps->pss_end_time,
9951 cb->cb_literal, cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9952 nice_num_str_nvlist(scan, "to_examine", ps->pss_to_examine,
9953 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9954 nice_num_str_nvlist(scan, "examined", ps->pss_examined,
9955 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9956 nice_num_str_nvlist(scan, "skipped", ps->pss_skipped,
9957 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9958 nice_num_str_nvlist(scan, "processed", ps->pss_processed,
9959 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9960 nice_num_str_nvlist(scan, "errors", ps->pss_errors,
9961 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_1024);
9962 nice_num_str_nvlist(scan, "bytes_per_scan", ps->pss_pass_exam,
9963 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9964 nice_num_str_nvlist(scan, "pass_start", ps->pss_pass_start,
9965 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9966 nice_num_str_nvlist(scan, "scrub_pause",
9967 ps->pss_pass_scrub_pause, cb->cb_literal,
9968 cb->cb_json_as_int, ZFS_NICE_TIMESTAMP);
9969 nice_num_str_nvlist(scan, "scrub_spent_paused",
9970 ps->pss_pass_scrub_spent_paused,
9971 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
9972 nice_num_str_nvlist(scan, "issued_bytes_per_scan",
9973 ps->pss_pass_issued, cb->cb_literal,
9974 cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9975 nice_num_str_nvlist(scan, "issued", ps->pss_issued,
9976 cb->cb_literal, cb->cb_json_as_int, ZFS_NICENUM_BYTES);
9977 if (ps->pss_error_scrub_func == POOL_SCAN_ERRORSCRUB &&
9978 ps->pss_error_scrub_start > ps->pss_start_time) {
9979 fnvlist_add_string(scan, "err_scrub_func",
9980 pool_scan_func_str[ps->pss_error_scrub_func]);
9981 fnvlist_add_string(scan, "err_scrub_state",
9982 pool_scan_state_str[ps->pss_error_scrub_state]);
9983 nice_num_str_nvlist(scan, "err_scrub_start_time",
9984 ps->pss_error_scrub_start,
9985 cb->cb_literal, cb->cb_json_as_int,
9986 ZFS_NICE_TIMESTAMP);
9987 nice_num_str_nvlist(scan, "err_scrub_end_time",
9988 ps->pss_error_scrub_end,
9989 cb->cb_literal, cb->cb_json_as_int,
9990 ZFS_NICE_TIMESTAMP);
9991 nice_num_str_nvlist(scan, "err_scrub_examined",
9992 ps->pss_error_scrub_examined,
9993 cb->cb_literal, cb->cb_json_as_int,
9994 ZFS_NICENUM_1024);
9995 nice_num_str_nvlist(scan, "err_scrub_to_examine",
9996 ps->pss_error_scrub_to_be_examined,
9997 cb->cb_literal, cb->cb_json_as_int,
9998 ZFS_NICENUM_1024);
9999 nice_num_str_nvlist(scan, "err_scrub_pause",
10000 ps->pss_pass_error_scrub_pause,
10001 B_TRUE, cb->cb_json_as_int, ZFS_NICENUM_1024);
10002 }
10003 }
10004
10005 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10006 &child, &children) == 0) {
10007 vdev_rebuild_stat_t *vrs;
10008 uint_t i;
10009 char *name;
10010 nvlist_t *nv;
10011 nvlist_t *rebuild = fnvlist_alloc();
10012 uint64_t st;
10013 for (uint_t c = 0; c < children; c++) {
10014 if (nvlist_lookup_uint64_array(child[c],
10015 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs,
10016 &i) == 0) {
10017 if (vrs->vrs_state != VDEV_REBUILD_NONE) {
10018 nv = fnvlist_alloc();
10019 name = zpool_vdev_name(g_zfs, zhp,
10020 child[c], VDEV_NAME_TYPE_ID);
10021 fill_vdev_info(nv, zhp, name, B_FALSE,
10022 cb->cb_json_as_int);
10023 st = vrs->vrs_state;
10024 fnvlist_add_string(nv, "state",
10025 vdev_rebuild_state_str[st]);
10026 nice_num_str_nvlist(nv, "start_time",
10027 vrs->vrs_start_time, cb->cb_literal,
10028 cb->cb_json_as_int,
10029 ZFS_NICE_TIMESTAMP);
10030 nice_num_str_nvlist(nv, "end_time",
10031 vrs->vrs_end_time, cb->cb_literal,
10032 cb->cb_json_as_int,
10033 ZFS_NICE_TIMESTAMP);
10034 nice_num_str_nvlist(nv, "scan_time",
10035 vrs->vrs_scan_time_ms * 1000000,
10036 cb->cb_literal, cb->cb_json_as_int,
10037 ZFS_NICENUM_TIME);
10038 nice_num_str_nvlist(nv, "scanned",
10039 vrs->vrs_bytes_scanned,
10040 cb->cb_literal, cb->cb_json_as_int,
10041 ZFS_NICENUM_BYTES);
10042 nice_num_str_nvlist(nv, "issued",
10043 vrs->vrs_bytes_issued,
10044 cb->cb_literal, cb->cb_json_as_int,
10045 ZFS_NICENUM_BYTES);
10046 nice_num_str_nvlist(nv, "rebuilt",
10047 vrs->vrs_bytes_rebuilt,
10048 cb->cb_literal, cb->cb_json_as_int,
10049 ZFS_NICENUM_BYTES);
10050 nice_num_str_nvlist(nv, "to_scan",
10051 vrs->vrs_bytes_est, cb->cb_literal,
10052 cb->cb_json_as_int,
10053 ZFS_NICENUM_BYTES);
10054 nice_num_str_nvlist(nv, "errors",
10055 vrs->vrs_errors, cb->cb_literal,
10056 cb->cb_json_as_int,
10057 ZFS_NICENUM_1024);
10058 nice_num_str_nvlist(nv, "pass_time",
10059 vrs->vrs_pass_time_ms * 1000000,
10060 cb->cb_literal, cb->cb_json_as_int,
10061 ZFS_NICENUM_TIME);
10062 nice_num_str_nvlist(nv, "pass_scanned",
10063 vrs->vrs_pass_bytes_scanned,
10064 cb->cb_literal, cb->cb_json_as_int,
10065 ZFS_NICENUM_BYTES);
10066 nice_num_str_nvlist(nv, "pass_issued",
10067 vrs->vrs_pass_bytes_issued,
10068 cb->cb_literal, cb->cb_json_as_int,
10069 ZFS_NICENUM_BYTES);
10070 nice_num_str_nvlist(nv, "pass_skipped",
10071 vrs->vrs_pass_bytes_skipped,
10072 cb->cb_literal, cb->cb_json_as_int,
10073 ZFS_NICENUM_BYTES);
10074 fnvlist_add_nvlist(rebuild, name, nv);
10075 free(name);
10076 }
10077 }
10078 }
10079 if (!nvlist_empty(rebuild))
10080 fnvlist_add_nvlist(scan, "rebuild_stats", rebuild);
10081 fnvlist_free(rebuild);
10082 }
10083
10084 if (!nvlist_empty(scan))
10085 fnvlist_add_nvlist(item, ZPOOL_CONFIG_SCAN_STATS, scan);
10086 fnvlist_free(scan);
10087 }
10088
10089 /*
10090 * Print the scan status.
10091 */
10092 static void
print_scan_status(zpool_handle_t * zhp,nvlist_t * nvroot)10093 print_scan_status(zpool_handle_t *zhp, nvlist_t *nvroot)
10094 {
10095 uint64_t rebuild_end_time = 0, resilver_end_time = 0;
10096 boolean_t have_resilver = B_FALSE, have_scrub = B_FALSE;
10097 boolean_t have_errorscrub = B_FALSE;
10098 boolean_t active_resilver = B_FALSE;
10099 pool_checkpoint_stat_t *pcs = NULL;
10100 pool_scan_stat_t *ps = NULL;
10101 uint_t c;
10102 time_t scrub_start = 0, errorscrub_start = 0;
10103
10104 if (nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS,
10105 (uint64_t **)&ps, &c) == 0) {
10106 if (ps->pss_func == POOL_SCAN_RESILVER) {
10107 resilver_end_time = ps->pss_end_time;
10108 active_resilver = (ps->pss_state == DSS_SCANNING);
10109 }
10110
10111 have_resilver = (ps->pss_func == POOL_SCAN_RESILVER);
10112 have_scrub = (ps->pss_func == POOL_SCAN_SCRUB);
10113 scrub_start = ps->pss_start_time;
10114 if (c > offsetof(pool_scan_stat_t,
10115 pss_pass_error_scrub_pause) / 8) {
10116 have_errorscrub = (ps->pss_error_scrub_func ==
10117 POOL_SCAN_ERRORSCRUB);
10118 errorscrub_start = ps->pss_error_scrub_start;
10119 }
10120 }
10121
10122 boolean_t active_rebuild = check_rebuilding(nvroot, &rebuild_end_time);
10123 boolean_t have_rebuild = (active_rebuild || (rebuild_end_time > 0));
10124
10125 /* Always print the scrub status when available. */
10126 if (have_scrub && scrub_start > errorscrub_start)
10127 print_scan_scrub_resilver_status(ps);
10128 else if (have_errorscrub && errorscrub_start >= scrub_start)
10129 print_err_scrub_status(ps);
10130
10131 /*
10132 * When there is an active resilver or rebuild print its status.
10133 * Otherwise print the status of the last resilver or rebuild.
10134 */
10135 if (active_resilver || (!active_rebuild && have_resilver &&
10136 resilver_end_time && resilver_end_time > rebuild_end_time)) {
10137 print_scan_scrub_resilver_status(ps);
10138 } else if (active_rebuild || (!active_resilver && have_rebuild &&
10139 rebuild_end_time && rebuild_end_time > resilver_end_time)) {
10140 print_rebuild_status(zhp, nvroot);
10141 }
10142
10143 (void) nvlist_lookup_uint64_array(nvroot,
10144 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
10145 print_checkpoint_scan_warning(ps, pcs);
10146 }
10147
10148 /*
10149 * Print out detailed removal status.
10150 */
10151 static void
print_removal_status(zpool_handle_t * zhp,pool_removal_stat_t * prs)10152 print_removal_status(zpool_handle_t *zhp, pool_removal_stat_t *prs)
10153 {
10154 char copied_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
10155 time_t start, end;
10156 nvlist_t *config, *nvroot;
10157 nvlist_t **child;
10158 uint_t children;
10159 char *vdev_name;
10160
10161 if (prs == NULL || prs->prs_state == DSS_NONE)
10162 return;
10163
10164 /*
10165 * Determine name of vdev.
10166 */
10167 config = zpool_get_config(zhp, NULL);
10168 nvroot = fnvlist_lookup_nvlist(config,
10169 ZPOOL_CONFIG_VDEV_TREE);
10170 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10171 &child, &children) == 0);
10172 assert(prs->prs_removing_vdev < children);
10173 vdev_name = zpool_vdev_name(g_zfs, zhp,
10174 child[prs->prs_removing_vdev], B_TRUE);
10175
10176 (void) printf_color(ANSI_BOLD, gettext("remove: "));
10177
10178 start = prs->prs_start_time;
10179 end = prs->prs_end_time;
10180 zfs_nicenum(prs->prs_copied, copied_buf, sizeof (copied_buf));
10181
10182 /*
10183 * Removal is finished or canceled.
10184 */
10185 if (prs->prs_state == DSS_FINISHED) {
10186 uint64_t minutes_taken = (end - start) / 60;
10187
10188 (void) printf(gettext("Removal of vdev %llu copied %s "
10189 "in %lluh%um, completed on %s"),
10190 (longlong_t)prs->prs_removing_vdev,
10191 copied_buf,
10192 (u_longlong_t)(minutes_taken / 60),
10193 (uint_t)(minutes_taken % 60),
10194 ctime((time_t *)&end));
10195 } else if (prs->prs_state == DSS_CANCELED) {
10196 (void) printf(gettext("Removal of %s canceled on %s"),
10197 vdev_name, ctime(&end));
10198 } else {
10199 uint64_t copied, total, elapsed, rate, mins_left, hours_left;
10200 double fraction_done;
10201
10202 assert(prs->prs_state == DSS_SCANNING);
10203
10204 /*
10205 * Removal is in progress.
10206 */
10207 (void) printf(gettext(
10208 "Evacuation of %s in progress since %s"),
10209 vdev_name, ctime(&start));
10210
10211 copied = prs->prs_copied > 0 ? prs->prs_copied : 1;
10212 total = prs->prs_to_copy;
10213 fraction_done = (double)copied / total;
10214
10215 /* elapsed time for this pass */
10216 elapsed = time(NULL) - prs->prs_start_time;
10217 elapsed = elapsed > 0 ? elapsed : 1;
10218 rate = copied / elapsed;
10219 rate = rate > 0 ? rate : 1;
10220 mins_left = ((total - copied) / rate) / 60;
10221 hours_left = mins_left / 60;
10222
10223 zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10224 zfs_nicenum(total, total_buf, sizeof (total_buf));
10225 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10226
10227 /*
10228 * do not print estimated time if hours_left is more than
10229 * 30 days
10230 */
10231 (void) printf(gettext(
10232 "\t%s copied out of %s at %s/s, %.2f%% done"),
10233 examined_buf, total_buf, rate_buf, 100 * fraction_done);
10234 if (hours_left < (30 * 24)) {
10235 (void) printf(gettext(", %lluh%um to go\n"),
10236 (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
10237 } else {
10238 (void) printf(gettext(
10239 ", (copy is slow, no estimated time)\n"));
10240 }
10241 }
10242 free(vdev_name);
10243
10244 if (prs->prs_mapping_memory > 0) {
10245 char mem_buf[7];
10246 zfs_nicenum(prs->prs_mapping_memory, mem_buf, sizeof (mem_buf));
10247 (void) printf(gettext(
10248 "\t%s memory used for removed device mappings\n"),
10249 mem_buf);
10250 }
10251 }
10252
10253 /*
10254 * Print out detailed raidz expansion status.
10255 */
10256 static void
print_raidz_expand_status(zpool_handle_t * zhp,pool_raidz_expand_stat_t * pres)10257 print_raidz_expand_status(zpool_handle_t *zhp, pool_raidz_expand_stat_t *pres)
10258 {
10259 char copied_buf[7];
10260
10261 if (pres == NULL || pres->pres_state == DSS_NONE)
10262 return;
10263
10264 /*
10265 * Determine name of vdev.
10266 */
10267 nvlist_t *config = zpool_get_config(zhp, NULL);
10268 nvlist_t *nvroot = fnvlist_lookup_nvlist(config,
10269 ZPOOL_CONFIG_VDEV_TREE);
10270 nvlist_t **child;
10271 uint_t children;
10272 verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
10273 &child, &children) == 0);
10274 assert(pres->pres_expanding_vdev < children);
10275
10276 (void) printf_color(ANSI_BOLD, gettext("expand: "));
10277
10278 time_t start = pres->pres_start_time;
10279 time_t end = pres->pres_end_time;
10280 char *vname =
10281 zpool_vdev_name(g_zfs, zhp, child[pres->pres_expanding_vdev], 0);
10282 zfs_nicenum(pres->pres_reflowed, copied_buf, sizeof (copied_buf));
10283
10284 /*
10285 * Expansion is finished or canceled.
10286 */
10287 if (pres->pres_state == DSS_FINISHED) {
10288 char time_buf[32];
10289 secs_to_dhms(end - start, time_buf);
10290
10291 (void) printf(gettext("expanded %s-%u copied %s in %s, "
10292 "on %s"), vname, (int)pres->pres_expanding_vdev,
10293 copied_buf, time_buf, ctime((time_t *)&end));
10294 } else {
10295 char examined_buf[7], total_buf[7], rate_buf[7];
10296 uint64_t copied, total, elapsed, rate, secs_left;
10297 double fraction_done;
10298
10299 assert(pres->pres_state == DSS_SCANNING);
10300
10301 /*
10302 * Expansion is in progress.
10303 */
10304 (void) printf(gettext(
10305 "expansion of %s-%u in progress since %s"),
10306 vname, (int)pres->pres_expanding_vdev, ctime(&start));
10307
10308 copied = pres->pres_reflowed > 0 ? pres->pres_reflowed : 1;
10309 total = pres->pres_to_reflow;
10310 fraction_done = (double)copied / total;
10311
10312 /* elapsed time for this pass */
10313 elapsed = time(NULL) - pres->pres_start_time;
10314 elapsed = elapsed > 0 ? elapsed : 1;
10315 rate = copied / elapsed;
10316 rate = rate > 0 ? rate : 1;
10317 secs_left = (total - copied) / rate;
10318
10319 zfs_nicenum(copied, examined_buf, sizeof (examined_buf));
10320 zfs_nicenum(total, total_buf, sizeof (total_buf));
10321 zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
10322
10323 /*
10324 * do not print estimated time if hours_left is more than
10325 * 30 days
10326 */
10327 (void) printf(gettext("\t%s / %s copied at %s/s, %.2f%% done"),
10328 examined_buf, total_buf, rate_buf, 100 * fraction_done);
10329 if (pres->pres_waiting_for_resilver) {
10330 (void) printf(gettext(", paused for resilver or "
10331 "clear\n"));
10332 } else if (secs_left < (30 * 24 * 3600)) {
10333 char time_buf[32];
10334 secs_to_dhms(secs_left, time_buf);
10335 (void) printf(gettext(", %s to go\n"), time_buf);
10336 } else {
10337 (void) printf(gettext(
10338 ", (copy is slow, no estimated time)\n"));
10339 }
10340 }
10341 free(vname);
10342 }
10343 static void
print_checkpoint_status(pool_checkpoint_stat_t * pcs)10344 print_checkpoint_status(pool_checkpoint_stat_t *pcs)
10345 {
10346 time_t start;
10347 char space_buf[7];
10348
10349 if (pcs == NULL || pcs->pcs_state == CS_NONE)
10350 return;
10351
10352 (void) printf(gettext("checkpoint: "));
10353
10354 start = pcs->pcs_start_time;
10355 zfs_nicenum(pcs->pcs_space, space_buf, sizeof (space_buf));
10356
10357 if (pcs->pcs_state == CS_CHECKPOINT_EXISTS) {
10358 char *date = ctime(&start);
10359
10360 /*
10361 * ctime() adds a newline at the end of the generated
10362 * string, thus the weird format specifier and the
10363 * strlen() call used to chop it off from the output.
10364 */
10365 (void) printf(gettext("created %.*s, consumes %s\n"),
10366 (int)(strlen(date) - 1), date, space_buf);
10367 return;
10368 }
10369
10370 assert(pcs->pcs_state == CS_CHECKPOINT_DISCARDING);
10371
10372 (void) printf(gettext("discarding, %s remaining.\n"),
10373 space_buf);
10374 }
10375
10376 static void
print_error_log(zpool_handle_t * zhp)10377 print_error_log(zpool_handle_t *zhp)
10378 {
10379 nvlist_t *nverrlist = NULL;
10380 nvpair_t *elem;
10381 char *pathname;
10382 size_t len = MAXPATHLEN * 2;
10383
10384 if (zpool_get_errlog(zhp, &nverrlist) != 0)
10385 return;
10386
10387 (void) printf("errors: Permanent errors have been "
10388 "detected in the following files:\n\n");
10389
10390 pathname = safe_malloc(len);
10391 elem = NULL;
10392 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
10393 nvlist_t *nv;
10394 uint64_t dsobj, obj;
10395
10396 verify(nvpair_value_nvlist(elem, &nv) == 0);
10397 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
10398 &dsobj) == 0);
10399 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
10400 &obj) == 0);
10401 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
10402 (void) printf("%7s %s\n", "", pathname);
10403 }
10404 free(pathname);
10405 nvlist_free(nverrlist);
10406 }
10407
10408 static void
print_spares(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t ** spares,uint_t nspares)10409 print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
10410 uint_t nspares)
10411 {
10412 uint_t i;
10413 char *name;
10414
10415 if (nspares == 0)
10416 return;
10417
10418 (void) printf(gettext("\tspares\n"));
10419
10420 for (i = 0; i < nspares; i++) {
10421 name = zpool_vdev_name(g_zfs, zhp, spares[i],
10422 cb->cb_name_flags);
10423 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE, NULL);
10424 free(name);
10425 }
10426 }
10427
10428 static void
print_l2cache(zpool_handle_t * zhp,status_cbdata_t * cb,nvlist_t ** l2cache,uint_t nl2cache)10429 print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
10430 uint_t nl2cache)
10431 {
10432 uint_t i;
10433 char *name;
10434
10435 if (nl2cache == 0)
10436 return;
10437
10438 (void) printf(gettext("\tcache\n"));
10439
10440 for (i = 0; i < nl2cache; i++) {
10441 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
10442 cb->cb_name_flags);
10443 print_status_config(zhp, cb, name, l2cache[i], 2,
10444 B_FALSE, NULL);
10445 free(name);
10446 }
10447 }
10448
10449 static void
print_dedup_stats(zpool_handle_t * zhp,nvlist_t * config,boolean_t literal)10450 print_dedup_stats(zpool_handle_t *zhp, nvlist_t *config, boolean_t literal)
10451 {
10452 ddt_histogram_t *ddh;
10453 ddt_stat_t *dds;
10454 ddt_object_t *ddo;
10455 uint_t c;
10456 /* Extra space provided for literal display */
10457 char dspace[32], mspace[32], cspace[32];
10458 uint64_t cspace_prop;
10459 enum zfs_nicenum_format format;
10460 zprop_source_t src;
10461
10462 /*
10463 * If the pool was faulted then we may not have been able to
10464 * obtain the config. Otherwise, if we have anything in the dedup
10465 * table continue processing the stats.
10466 */
10467 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
10468 (uint64_t **)&ddo, &c) != 0)
10469 return;
10470
10471 (void) printf("\n");
10472 (void) printf(gettext(" dedup: "));
10473 if (ddo->ddo_count == 0) {
10474 (void) printf(gettext("no DDT entries\n"));
10475 return;
10476 }
10477
10478 /*
10479 * Squash cached size into in-core size to handle race.
10480 * Only include cached size if it is available.
10481 */
10482 cspace_prop = zpool_get_prop_int(zhp, ZPOOL_PROP_DEDUPCACHED, &src);
10483 cspace_prop = MIN(cspace_prop, ddo->ddo_mspace);
10484 format = literal ? ZFS_NICENUM_RAW : ZFS_NICENUM_1024;
10485 zfs_nicenum_format(cspace_prop, cspace, sizeof (cspace), format);
10486 zfs_nicenum_format(ddo->ddo_dspace, dspace, sizeof (dspace), format);
10487 zfs_nicenum_format(ddo->ddo_mspace, mspace, sizeof (mspace), format);
10488 (void) printf("DDT entries %llu, size %s on disk, %s in core",
10489 (u_longlong_t)ddo->ddo_count,
10490 dspace,
10491 mspace);
10492 if (src != ZPROP_SRC_DEFAULT) {
10493 (void) printf(", %s cached (%.02f%%)",
10494 cspace,
10495 (double)cspace_prop / (double)ddo->ddo_mspace * 100.0);
10496 }
10497 (void) printf("\n");
10498
10499 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
10500 (uint64_t **)&dds, &c) == 0);
10501 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
10502 (uint64_t **)&ddh, &c) == 0);
10503 zpool_dump_ddt(dds, ddh, literal);
10504 }
10505
10506 #define ST_SIZE 4096
10507 #define AC_SIZE 2048
10508
10509 static void
print_status_reason(zpool_handle_t * zhp,status_cbdata_t * cbp,zpool_status_t reason,zpool_errata_t errata,nvlist_t * item)10510 print_status_reason(zpool_handle_t *zhp, status_cbdata_t *cbp,
10511 zpool_status_t reason, zpool_errata_t errata, nvlist_t *item)
10512 {
10513 char status[ST_SIZE];
10514 char action[AC_SIZE];
10515 memset(status, 0, ST_SIZE);
10516 memset(action, 0, AC_SIZE);
10517
10518 switch (reason) {
10519 case ZPOOL_STATUS_MISSING_DEV_R:
10520 (void) snprintf(status, ST_SIZE,
10521 gettext("One or more devices could "
10522 "not be opened. Sufficient replicas exist for\n\tthe pool "
10523 "to continue functioning in a degraded state.\n"));
10524 (void) snprintf(action, AC_SIZE,
10525 gettext("Attach the missing device "
10526 "and online it using 'zpool online'.\n"));
10527 break;
10528
10529 case ZPOOL_STATUS_MISSING_DEV_NR:
10530 (void) snprintf(status, ST_SIZE,
10531 gettext("One or more devices could "
10532 "not be opened. There are insufficient\n\treplicas for the"
10533 " pool to continue functioning.\n"));
10534 (void) snprintf(action, AC_SIZE,
10535 gettext("Attach the missing device "
10536 "and online it using 'zpool online'.\n"));
10537 break;
10538
10539 case ZPOOL_STATUS_CORRUPT_LABEL_R:
10540 (void) snprintf(status, ST_SIZE,
10541 gettext("One or more devices could "
10542 "not be used because the label is missing or\n\tinvalid. "
10543 "Sufficient replicas exist for the pool to continue\n\t"
10544 "functioning in a degraded state.\n"));
10545 (void) snprintf(action, AC_SIZE,
10546 gettext("Replace the device using 'zpool replace'.\n"));
10547 break;
10548
10549 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
10550 (void) snprintf(status, ST_SIZE,
10551 gettext("One or more devices could "
10552 "not be used because the label is missing \n\tor invalid. "
10553 "There are insufficient replicas for the pool to "
10554 "continue\n\tfunctioning.\n"));
10555 zpool_explain_recover(zpool_get_handle(zhp),
10556 zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
10557 action, AC_SIZE);
10558 break;
10559
10560 case ZPOOL_STATUS_FAILING_DEV:
10561 (void) snprintf(status, ST_SIZE,
10562 gettext("One or more devices has "
10563 "experienced an unrecoverable error. An\n\tattempt was "
10564 "made to correct the error. Applications are "
10565 "unaffected.\n"));
10566 (void) snprintf(action, AC_SIZE, gettext("Determine if the "
10567 "device needs to be replaced, and clear the errors\n\tusing"
10568 " 'zpool clear' or replace the device with 'zpool "
10569 "replace'.\n"));
10570 break;
10571
10572 case ZPOOL_STATUS_OFFLINE_DEV:
10573 (void) snprintf(status, ST_SIZE,
10574 gettext("One or more devices has "
10575 "been taken offline by the administrator.\n\tSufficient "
10576 "replicas exist for the pool to continue functioning in "
10577 "a\n\tdegraded state.\n"));
10578 (void) snprintf(action, AC_SIZE, gettext("Online the device "
10579 "using 'zpool online' or replace the device with\n\t'zpool "
10580 "replace'.\n"));
10581 break;
10582
10583 case ZPOOL_STATUS_REMOVED_DEV:
10584 (void) snprintf(status, ST_SIZE,
10585 gettext("One or more devices have "
10586 "been removed.\n\tSufficient replicas exist for the pool "
10587 "to continue functioning in a\n\tdegraded state.\n"));
10588 (void) snprintf(action, AC_SIZE, gettext("Online the device "
10589 "using zpool online' or replace the device with\n\t'zpool "
10590 "replace'.\n"));
10591 break;
10592
10593 case ZPOOL_STATUS_RESILVERING:
10594 case ZPOOL_STATUS_REBUILDING:
10595 (void) snprintf(status, ST_SIZE,
10596 gettext("One or more devices is "
10597 "currently being resilvered. The pool will\n\tcontinue "
10598 "to function, possibly in a degraded state.\n"));
10599 (void) snprintf(action, AC_SIZE,
10600 gettext("Wait for the resilver to complete.\n"));
10601 break;
10602
10603 case ZPOOL_STATUS_REBUILD_SCRUB:
10604 (void) snprintf(status, ST_SIZE,
10605 gettext("One or more devices have "
10606 "been sequentially resilvered, scrubbing\n\tthe pool "
10607 "is recommended.\n"));
10608 (void) snprintf(action, AC_SIZE, gettext("Use 'zpool scrub' to "
10609 "verify all data checksums.\n"));
10610 break;
10611
10612 case ZPOOL_STATUS_CORRUPT_DATA:
10613 (void) snprintf(status, ST_SIZE,
10614 gettext("One or more devices has "
10615 "experienced an error resulting in data\n\tcorruption. "
10616 "Applications may be affected.\n"));
10617 (void) snprintf(action, AC_SIZE,
10618 gettext("Restore the file in question"
10619 " if possible. Otherwise restore the\n\tentire pool from "
10620 "backup.\n"));
10621 break;
10622
10623 case ZPOOL_STATUS_CORRUPT_POOL:
10624 (void) snprintf(status, ST_SIZE, gettext("The pool metadata is "
10625 "incomplete or corrupted and the pool cannot be "
10626 "opened.\n"));
10627 zpool_explain_recover(zpool_get_handle(zhp),
10628 zpool_get_name(zhp), reason, zpool_get_config(zhp, NULL),
10629 action, AC_SIZE);
10630 break;
10631
10632 case ZPOOL_STATUS_VERSION_OLDER:
10633 (void) snprintf(status, ST_SIZE,
10634 gettext("The pool is formatted using "
10635 "a legacy on-disk format. The pool can\n\tstill be used, "
10636 "but some features are unavailable.\n"));
10637 (void) snprintf(action, AC_SIZE,
10638 gettext("Upgrade the pool using "
10639 "'zpool upgrade'. Once this is done, the\n\tpool will no "
10640 "longer be accessible on software that does not support\n\t"
10641 "feature flags.\n"));
10642 break;
10643
10644 case ZPOOL_STATUS_VERSION_NEWER:
10645 (void) snprintf(status, ST_SIZE,
10646 gettext("The pool has been upgraded "
10647 "to a newer, incompatible on-disk version.\n\tThe pool "
10648 "cannot be accessed on this system.\n"));
10649 (void) snprintf(action, AC_SIZE,
10650 gettext("Access the pool from a "
10651 "system running more recent software, or\n\trestore the "
10652 "pool from backup.\n"));
10653 break;
10654
10655 case ZPOOL_STATUS_FEAT_DISABLED:
10656 (void) snprintf(status, ST_SIZE, gettext("Some supported and "
10657 "requested features are not enabled on the pool.\n\t"
10658 "The pool can still be used, but some features are "
10659 "unavailable.\n"));
10660 (void) snprintf(action, AC_SIZE,
10661 gettext("Enable all features using "
10662 "'zpool upgrade'. Once this is done,\n\tthe pool may no "
10663 "longer be accessible by software that does not support\n\t"
10664 "the features. See zpool-features(7) for details.\n"));
10665 break;
10666
10667 case ZPOOL_STATUS_COMPATIBILITY_ERR:
10668 (void) snprintf(status, ST_SIZE, gettext("This pool has a "
10669 "compatibility list specified, but it could not be\n\t"
10670 "read/parsed at this time. The pool can still be used, "
10671 "but this\n\tshould be investigated.\n"));
10672 (void) snprintf(action, AC_SIZE,
10673 gettext("Check the value of the "
10674 "'compatibility' property against the\n\t"
10675 "appropriate file in " ZPOOL_SYSCONF_COMPAT_D " or "
10676 ZPOOL_DATA_COMPAT_D ".\n"));
10677 break;
10678
10679 case ZPOOL_STATUS_INCOMPATIBLE_FEAT:
10680 (void) snprintf(status, ST_SIZE, gettext("One or more features "
10681 "are enabled on the pool despite not being\n\t"
10682 "requested by the 'compatibility' property.\n"));
10683 (void) snprintf(action, AC_SIZE, gettext("Consider setting "
10684 "'compatibility' to an appropriate value, or\n\t"
10685 "adding needed features to the relevant file in\n\t"
10686 ZPOOL_SYSCONF_COMPAT_D " or " ZPOOL_DATA_COMPAT_D ".\n"));
10687 break;
10688
10689 case ZPOOL_STATUS_UNSUP_FEAT_READ:
10690 (void) snprintf(status, ST_SIZE,
10691 gettext("The pool cannot be accessed "
10692 "on this system because it uses the\n\tfollowing feature(s)"
10693 " not supported on this system:\n"));
10694 zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
10695 1024);
10696 (void) snprintf(action, AC_SIZE,
10697 gettext("Access the pool from a "
10698 "system that supports the required feature(s),\n\tor "
10699 "restore the pool from backup.\n"));
10700 break;
10701
10702 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
10703 (void) snprintf(status, ST_SIZE, gettext("The pool can only be "
10704 "accessed in read-only mode on this system. It\n\tcannot be"
10705 " accessed in read-write mode because it uses the "
10706 "following\n\tfeature(s) not supported on this system:\n"));
10707 zpool_collect_unsup_feat(zpool_get_config(zhp, NULL), status,
10708 1024);
10709 (void) snprintf(action, AC_SIZE,
10710 gettext("The pool cannot be accessed "
10711 "in read-write mode. Import the pool with\n"
10712 "\t\"-o readonly=on\", access the pool from a system that "
10713 "supports the\n\trequired feature(s), or restore the "
10714 "pool from backup.\n"));
10715 break;
10716
10717 case ZPOOL_STATUS_FAULTED_DEV_R:
10718 (void) snprintf(status, ST_SIZE,
10719 gettext("One or more devices are "
10720 "faulted in response to persistent errors.\n\tSufficient "
10721 "replicas exist for the pool to continue functioning "
10722 "in a\n\tdegraded state.\n"));
10723 (void) snprintf(action, AC_SIZE,
10724 gettext("Replace the faulted device, "
10725 "or use 'zpool clear' to mark the device\n\trepaired.\n"));
10726 break;
10727
10728 case ZPOOL_STATUS_FAULTED_FDOM_R:
10729 (void) snprintf(status, ST_SIZE,
10730 gettext("One or more failure domains are faulted. "
10731 "The storage devices may be\n\tintact. Sufficient "
10732 "replicas exist for the pool to continue functioning\n\t"
10733 "in a degraded state.\n"));
10734 (void) snprintf(action, AC_SIZE,
10735 gettext("Replace the faulted domain device, "
10736 "or use 'zpool clear' to mark domain\n\tstorage devices "
10737 "repaired.\n"));
10738 break;
10739
10740 case ZPOOL_STATUS_FAULTED_DEV_NR:
10741 (void) snprintf(status, ST_SIZE,
10742 gettext("One or more devices are "
10743 "faulted in response to persistent errors. There are "
10744 "insufficient replicas for the pool to\n\tcontinue "
10745 "functioning.\n"));
10746 (void) snprintf(action, AC_SIZE,
10747 gettext("Destroy and re-create the "
10748 "pool from a backup source. Manually marking the device\n"
10749 "\trepaired using 'zpool clear' may allow some data "
10750 "to be recovered.\n"));
10751 break;
10752
10753 case ZPOOL_STATUS_IO_FAILURE_MMP:
10754 (void) snprintf(status, ST_SIZE,
10755 gettext("The pool is suspended "
10756 "because multihost writes failed or were delayed;\n\t"
10757 "another system could import the pool undetected.\n"));
10758 (void) snprintf(action, AC_SIZE,
10759 gettext("Make sure the pool's devices"
10760 " are connected, then reboot your system and\n\timport the "
10761 "pool or run 'zpool clear' to resume the pool.\n"));
10762 break;
10763
10764 case ZPOOL_STATUS_IO_FAILURE_WAIT:
10765 case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
10766 (void) snprintf(status, ST_SIZE,
10767 gettext("One or more devices are "
10768 "faulted in response to IO failures.\n"));
10769 (void) snprintf(action, AC_SIZE,
10770 gettext("Make sure the affected "
10771 "devices are connected, then run 'zpool clear'.\n"));
10772 break;
10773
10774 case ZPOOL_STATUS_BAD_LOG:
10775 (void) snprintf(status, ST_SIZE, gettext("An intent log record "
10776 "could not be read.\n"
10777 "\tWaiting for administrator intervention to fix the "
10778 "faulted pool.\n"));
10779 (void) snprintf(action, AC_SIZE,
10780 gettext("Either restore the affected "
10781 "device(s) and run 'zpool online',\n"
10782 "\tor ignore the intent log records by running "
10783 "'zpool clear'.\n"));
10784 break;
10785
10786 case ZPOOL_STATUS_NON_NATIVE_ASHIFT:
10787 (void) snprintf(status, ST_SIZE,
10788 gettext("One or more devices are "
10789 "configured to use a non-native block size.\n"
10790 "\tExpect reduced performance.\n"));
10791 (void) snprintf(action, AC_SIZE,
10792 gettext("Replace affected devices "
10793 "with devices that support the\n\tconfigured block size, "
10794 "or migrate data to a properly configured\n\tpool.\n"));
10795 break;
10796
10797 case ZPOOL_STATUS_HOSTID_MISMATCH:
10798 (void) snprintf(status, ST_SIZE,
10799 gettext("Mismatch between pool hostid"
10800 " and system hostid on imported pool.\n\tThis pool was "
10801 "previously imported into a system with a different "
10802 "hostid,\n\tand then was verbatim imported into this "
10803 "system.\n"));
10804 (void) snprintf(action, AC_SIZE,
10805 gettext("Export this pool on all "
10806 "systems on which it is imported.\n"
10807 "\tThen import it to correct the mismatch.\n"));
10808 break;
10809
10810 case ZPOOL_STATUS_ERRATA:
10811 (void) snprintf(status, ST_SIZE,
10812 gettext("Errata #%d detected.\n"), errata);
10813 switch (errata) {
10814 case ZPOOL_ERRATA_NONE:
10815 break;
10816
10817 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
10818 (void) snprintf(action, AC_SIZE,
10819 gettext("To correct the issue run "
10820 "'zpool scrub'.\n"));
10821 break;
10822
10823 case ZPOOL_ERRATA_ZOL_6845_ENCRYPTION:
10824 (void) strlcat(status, gettext("\tExisting encrypted "
10825 "datasets contain an on-disk incompatibility\n\t "
10826 "which needs to be corrected.\n"), ST_SIZE);
10827 (void) snprintf(action, AC_SIZE,
10828 gettext("To correct the issue"
10829 " backup existing encrypted datasets to new\n\t"
10830 "encrypted datasets and destroy the old ones. "
10831 "'zfs mount -o ro' can\n\tbe used to temporarily "
10832 "mount existing encrypted datasets readonly.\n"));
10833 break;
10834
10835 case ZPOOL_ERRATA_ZOL_8308_ENCRYPTION:
10836 (void) strlcat(status, gettext("\tExisting encrypted "
10837 "snapshots and bookmarks contain an on-disk\n\t"
10838 "incompatibility. This may cause on-disk "
10839 "corruption if they are used\n\twith "
10840 "'zfs recv'.\n"), ST_SIZE);
10841 (void) snprintf(action, AC_SIZE,
10842 gettext("To correct the"
10843 "issue, enable the bookmark_v2 feature. No "
10844 "additional\n\taction is needed if there are no "
10845 "encrypted snapshots or bookmarks.\n\tIf preserving"
10846 "the encrypted snapshots and bookmarks is required,"
10847 " use\n\ta non-raw send to backup and restore them."
10848 " Alternately, they may be\n\tremoved to resolve "
10849 "the incompatibility.\n"));
10850 break;
10851
10852 default:
10853 /*
10854 * All errata which allow the pool to be imported
10855 * must contain an action message.
10856 */
10857 assert(0);
10858 }
10859 break;
10860
10861 default:
10862 /*
10863 * The remaining errors can't actually be generated, yet.
10864 */
10865 assert(reason == ZPOOL_STATUS_OK);
10866 }
10867
10868 if (status[0] != 0) {
10869 if (cbp->cb_json)
10870 fnvlist_add_string(item, "status", status);
10871 else {
10872 (void) printf_color(ANSI_BOLD, gettext("status: "));
10873 (void) printf_color(ANSI_YELLOW, status);
10874 }
10875 }
10876
10877 if (action[0] != 0) {
10878 if (cbp->cb_json)
10879 fnvlist_add_string(item, "action", action);
10880 else {
10881 (void) printf_color(ANSI_BOLD, gettext("action: "));
10882 (void) printf_color(ANSI_YELLOW, action);
10883 }
10884 }
10885 }
10886
10887 static int
status_callback_json(zpool_handle_t * zhp,void * data)10888 status_callback_json(zpool_handle_t *zhp, void *data)
10889 {
10890 status_cbdata_t *cbp = data;
10891 nvlist_t *config, *nvroot;
10892 const char *msgid;
10893 char pool_guid[256];
10894 char msgbuf[256];
10895 uint64_t guid;
10896 zpool_status_t reason;
10897 zpool_errata_t errata;
10898 uint_t c;
10899 vdev_stat_t *vs;
10900 nvlist_t *item, *d, *load_info, *vds;
10901
10902 /* If dedup stats were requested, also fetch dedupcached. */
10903 if (cbp->cb_dedup_stats > 1)
10904 zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
10905 reason = zpool_get_status(zhp, &msgid, &errata);
10906 /*
10907 * If we were given 'zpool status -x', only report those pools with
10908 * problems.
10909 */
10910 if (cbp->cb_explain &&
10911 (reason == ZPOOL_STATUS_OK ||
10912 reason == ZPOOL_STATUS_VERSION_OLDER ||
10913 reason == ZPOOL_STATUS_FEAT_DISABLED ||
10914 reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
10915 reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
10916 return (0);
10917 }
10918
10919 d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
10920 item = fnvlist_alloc();
10921 vds = fnvlist_alloc();
10922 fill_pool_info(item, zhp, B_FALSE, cbp->cb_json_as_int);
10923 config = zpool_get_config(zhp, NULL);
10924
10925 if (config != NULL) {
10926 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
10927 verify(nvlist_lookup_uint64_array(nvroot,
10928 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &c) == 0);
10929 if (cbp->cb_json_pool_key_guid) {
10930 guid = fnvlist_lookup_uint64(config,
10931 ZPOOL_CONFIG_POOL_GUID);
10932 (void) snprintf(pool_guid, 256, "%llu",
10933 (u_longlong_t)guid);
10934 }
10935 cbp->cb_count++;
10936
10937 print_status_reason(zhp, cbp, reason, errata, item);
10938 if (msgid != NULL) {
10939 (void) snprintf(msgbuf, 256,
10940 "https://openzfs.github.io/openzfs-docs/msg/%s",
10941 msgid);
10942 fnvlist_add_string(item, "msgid", msgid);
10943 fnvlist_add_string(item, "moreinfo", msgbuf);
10944 }
10945
10946 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
10947 &load_info) == 0) {
10948 fnvlist_add_nvlist(item, ZPOOL_CONFIG_LOAD_INFO,
10949 load_info);
10950 }
10951
10952 scan_status_nvlist(zhp, cbp, nvroot, item);
10953 removal_status_nvlist(zhp, cbp, nvroot, item);
10954 checkpoint_status_nvlist(nvroot, cbp, item);
10955 raidz_expand_status_nvlist(zhp, cbp, nvroot, item);
10956 vdev_stats_nvlist(zhp, cbp, nvroot, 0, B_FALSE, NULL, vds);
10957 if (cbp->cb_flat_vdevs) {
10958 class_vdevs_nvlist(zhp, cbp, nvroot,
10959 VDEV_ALLOC_BIAS_DEDUP, vds);
10960 class_vdevs_nvlist(zhp, cbp, nvroot,
10961 VDEV_ALLOC_BIAS_SPECIAL, vds);
10962 class_vdevs_nvlist(zhp, cbp, nvroot,
10963 VDEV_ALLOC_CLASS_LOGS, vds);
10964 l2cache_nvlist(zhp, cbp, nvroot, vds);
10965 spares_nvlist(zhp, cbp, nvroot, vds);
10966
10967 fnvlist_add_nvlist(item, "vdevs", vds);
10968 fnvlist_free(vds);
10969 } else {
10970 fnvlist_add_nvlist(item, "vdevs", vds);
10971 fnvlist_free(vds);
10972
10973 class_vdevs_nvlist(zhp, cbp, nvroot,
10974 VDEV_ALLOC_BIAS_DEDUP, item);
10975 class_vdevs_nvlist(zhp, cbp, nvroot,
10976 VDEV_ALLOC_BIAS_SPECIAL, item);
10977 class_vdevs_nvlist(zhp, cbp, nvroot,
10978 VDEV_ALLOC_CLASS_LOGS, item);
10979 l2cache_nvlist(zhp, cbp, nvroot, item);
10980 spares_nvlist(zhp, cbp, nvroot, item);
10981 }
10982 dedup_stats_nvlist(zhp, cbp, item);
10983 errors_nvlist(zhp, cbp, item);
10984 }
10985 if (cbp->cb_json_pool_key_guid) {
10986 fnvlist_add_nvlist(d, pool_guid, item);
10987 } else {
10988 fnvlist_add_nvlist(d, zpool_get_name(zhp),
10989 item);
10990 }
10991 fnvlist_free(item);
10992 return (0);
10993 }
10994
10995 /*
10996 * Display a summary of pool status. Displays a summary such as:
10997 *
10998 * pool: tank
10999 * status: DEGRADED
11000 * reason: One or more devices ...
11001 * see: https://openzfs.github.io/openzfs-docs/msg/ZFS-xxxx-01
11002 * config:
11003 * mirror DEGRADED
11004 * c1t0d0 OK
11005 * c2t0d0 UNAVAIL
11006 *
11007 * When given the '-v' option, we print out the complete config. If the '-e'
11008 * option is specified, then we print out error rate information as well.
11009 */
11010 static int
status_callback(zpool_handle_t * zhp,void * data)11011 status_callback(zpool_handle_t *zhp, void *data)
11012 {
11013 status_cbdata_t *cbp = data;
11014 nvlist_t *config, *nvroot;
11015 const char *msgid;
11016 zpool_status_t reason;
11017 zpool_errata_t errata;
11018 const char *health;
11019 uint_t c;
11020 vdev_stat_t *vs;
11021
11022 /* If dedup stats were requested, also fetch dedupcached. */
11023 if (cbp->cb_dedup_stats > 1)
11024 zpool_add_propname(zhp, ZPOOL_DEDUPCACHED_PROP_NAME);
11025
11026 config = zpool_get_config(zhp, NULL);
11027 reason = zpool_get_status(zhp, &msgid, &errata);
11028
11029 cbp->cb_count++;
11030
11031 /*
11032 * If we were given 'zpool status -x', only report those pools with
11033 * problems.
11034 */
11035 if (cbp->cb_explain &&
11036 (reason == ZPOOL_STATUS_OK ||
11037 reason == ZPOOL_STATUS_VERSION_OLDER ||
11038 reason == ZPOOL_STATUS_FEAT_DISABLED ||
11039 reason == ZPOOL_STATUS_COMPATIBILITY_ERR ||
11040 reason == ZPOOL_STATUS_INCOMPATIBLE_FEAT)) {
11041 if (!cbp->cb_allpools) {
11042 (void) printf(gettext("pool '%s' is healthy\n"),
11043 zpool_get_name(zhp));
11044 if (cbp->cb_first)
11045 cbp->cb_first = B_FALSE;
11046 }
11047 return (0);
11048 }
11049
11050 if (cbp->cb_first)
11051 cbp->cb_first = B_FALSE;
11052 else
11053 (void) printf("\n");
11054
11055 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
11056 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
11057 (uint64_t **)&vs, &c) == 0);
11058
11059 health = zpool_get_state_str(zhp);
11060
11061 printf(" ");
11062 (void) printf_color(ANSI_BOLD, gettext("pool:"));
11063 printf(" %s\n", zpool_get_name(zhp));
11064 (void) fputc(' ', stdout);
11065 (void) printf_color(ANSI_BOLD, gettext("state: "));
11066
11067 (void) printf_color(health_str_to_color(health), "%s", health);
11068
11069 (void) fputc('\n', stdout);
11070 print_status_reason(zhp, cbp, reason, errata, NULL);
11071
11072 if (msgid != NULL) {
11073 printf(" ");
11074 (void) printf_color(ANSI_BOLD, gettext("see:"));
11075 printf(gettext(
11076 " https://openzfs.github.io/openzfs-docs/msg/%s\n"),
11077 msgid);
11078 }
11079
11080 if (config != NULL) {
11081 uint64_t nerr;
11082 nvlist_t **spares, **l2cache;
11083 uint_t nspares, nl2cache;
11084
11085 print_scan_status(zhp, nvroot);
11086
11087 pool_removal_stat_t *prs = NULL;
11088 (void) nvlist_lookup_uint64_array(nvroot,
11089 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
11090 print_removal_status(zhp, prs);
11091
11092 pool_checkpoint_stat_t *pcs = NULL;
11093 (void) nvlist_lookup_uint64_array(nvroot,
11094 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
11095 print_checkpoint_status(pcs);
11096
11097 pool_raidz_expand_stat_t *pres = NULL;
11098 (void) nvlist_lookup_uint64_array(nvroot,
11099 ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
11100 print_raidz_expand_status(zhp, pres);
11101
11102 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
11103 cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
11104 if (cbp->cb_namewidth < 10)
11105 cbp->cb_namewidth = 10;
11106
11107 color_start(ANSI_BOLD);
11108 (void) printf(gettext("config:\n\n"));
11109 (void) printf(gettext("\t%-*s %-8s %5s %5s %5s"),
11110 cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
11111 "CKSUM");
11112 color_end();
11113
11114 if (cbp->cb_print_slow_ios) {
11115 (void) printf_color(ANSI_BOLD, " %5s", gettext("SLOW"));
11116 }
11117
11118 if (cbp->cb_print_power) {
11119 (void) printf_color(ANSI_BOLD, " %5s",
11120 gettext("POWER"));
11121 }
11122
11123 if (cbp->cb_print_dio_verify) {
11124 (void) printf_color(ANSI_BOLD, " %5s", gettext("DIO"));
11125 }
11126
11127 if (cbp->vcdl != NULL)
11128 print_cmd_columns(cbp->vcdl, 0);
11129
11130 printf("\n");
11131
11132 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
11133 B_FALSE, NULL);
11134
11135 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_DEDUP);
11136 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_BIAS_SPECIAL);
11137 print_class_vdevs(zhp, cbp, nvroot, VDEV_ALLOC_CLASS_LOGS);
11138
11139 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
11140 &l2cache, &nl2cache) == 0)
11141 print_l2cache(zhp, cbp, l2cache, nl2cache);
11142
11143 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
11144 &spares, &nspares) == 0)
11145 print_spares(zhp, cbp, spares, nspares);
11146
11147 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
11148 &nerr) == 0) {
11149 (void) printf("\n");
11150 if (nerr == 0) {
11151 (void) printf(gettext(
11152 "errors: No known data errors\n"));
11153 } else if (!cbp->cb_verbose) {
11154 color_start(ANSI_RED);
11155 (void) printf(gettext("errors: %llu data "
11156 "errors, use '-v' for a list\n"),
11157 (u_longlong_t)nerr);
11158 color_end();
11159 } else {
11160 print_error_log(zhp);
11161 }
11162 }
11163
11164 if (cbp->cb_dedup_stats)
11165 print_dedup_stats(zhp, config, cbp->cb_literal);
11166 } else {
11167 (void) printf(gettext("config: The configuration cannot be "
11168 "determined.\n"));
11169 }
11170
11171 return (0);
11172 }
11173
11174 /*
11175 * zpool status [-dDegiLpPstvx] [-c [script1,script2,...]] ...
11176 * [-j|--json [--json-flat-vdevs] [--json-int] ...
11177 * [--json-pool-key-guid]] [--power] [-T d|u] ...
11178 * [pool] [interval [count]]
11179 *
11180 * -c CMD For each vdev, run command CMD
11181 * -D Display dedup status (undocumented)
11182 * -d Display Direct I/O write verify errors
11183 * -e Display only unhealthy vdevs
11184 * -g Display guid for individual vdev name.
11185 * -i Display vdev initialization status.
11186 * -j [...] Display output in JSON format
11187 * --json-flat-vdevs Display vdevs in flat hierarchy
11188 * --json-int Display numbers in integer format instead of string
11189 * --json-pool-key-guid Use pool GUID as key for pool objects
11190 * -L Follow links when resolving vdev path name.
11191 * -P Display full path for vdev name.
11192 * -p Display values in parsable (exact) format.
11193 * --power Display vdev enclosure slot power status
11194 * -s Display slow IOs column.
11195 * -T Display a timestamp in date(1) or Unix format
11196 * -t Display vdev TRIM status.
11197 * -v Display complete error logs
11198 * -x Display only pools with potential problems
11199 *
11200 * Describes the health status of all pools or some subset.
11201 */
11202 int
zpool_do_status(int argc,char ** argv)11203 zpool_do_status(int argc, char **argv)
11204 {
11205 int c;
11206 int ret;
11207 float interval = 0;
11208 unsigned long count = 0;
11209 status_cbdata_t cb = { 0 };
11210 nvlist_t *data;
11211 char *cmd = NULL;
11212
11213 struct option long_options[] = {
11214 {"power", no_argument, NULL, ZPOOL_OPTION_POWER},
11215 {"json", no_argument, NULL, 'j'},
11216 {"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
11217 {"json-flat-vdevs", no_argument, NULL,
11218 ZPOOL_OPTION_JSON_FLAT_VDEVS},
11219 {"json-pool-key-guid", no_argument, NULL,
11220 ZPOOL_OPTION_POOL_KEY_GUID},
11221 {0, 0, 0, 0}
11222 };
11223
11224 /* check options */
11225 while ((c = getopt_long(argc, argv, "c:jdDegiLpPstT:vx", long_options,
11226 NULL)) != -1) {
11227 switch (c) {
11228 case 'c':
11229 if (cmd != NULL) {
11230 fprintf(stderr,
11231 gettext("Can't set -c flag twice\n"));
11232 exit(1);
11233 }
11234
11235 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
11236 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
11237 fprintf(stderr, gettext(
11238 "Can't run -c, disabled by "
11239 "ZPOOL_SCRIPTS_ENABLED.\n"));
11240 exit(1);
11241 }
11242
11243 if ((getuid() <= 0 || geteuid() <= 0) &&
11244 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
11245 fprintf(stderr, gettext(
11246 "Can't run -c with root privileges "
11247 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
11248 exit(1);
11249 }
11250 cmd = optarg;
11251 break;
11252 case 'd':
11253 cb.cb_print_dio_verify = B_TRUE;
11254 break;
11255 case 'D':
11256 if (++cb.cb_dedup_stats > 2)
11257 cb.cb_dedup_stats = 2;
11258 break;
11259 case 'e':
11260 cb.cb_print_unhealthy = B_TRUE;
11261 break;
11262 case 'g':
11263 cb.cb_name_flags |= VDEV_NAME_GUID;
11264 break;
11265 case 'i':
11266 cb.cb_print_vdev_init = B_TRUE;
11267 break;
11268 case 'L':
11269 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
11270 break;
11271 case 'p':
11272 cb.cb_literal = B_TRUE;
11273 break;
11274 case 'P':
11275 cb.cb_name_flags |= VDEV_NAME_PATH;
11276 break;
11277 case 's':
11278 cb.cb_print_slow_ios = B_TRUE;
11279 break;
11280 case 't':
11281 cb.cb_print_vdev_trim = B_TRUE;
11282 break;
11283 case 'T':
11284 get_timestamp_arg(*optarg);
11285 break;
11286 case 'v':
11287 cb.cb_verbose = B_TRUE;
11288 break;
11289 case 'j':
11290 cb.cb_json = B_TRUE;
11291 break;
11292 case 'x':
11293 cb.cb_explain = B_TRUE;
11294 break;
11295 case ZPOOL_OPTION_POWER:
11296 cb.cb_print_power = B_TRUE;
11297 break;
11298 case ZPOOL_OPTION_JSON_FLAT_VDEVS:
11299 cb.cb_flat_vdevs = B_TRUE;
11300 break;
11301 case ZPOOL_OPTION_JSON_NUMS_AS_INT:
11302 cb.cb_json_as_int = B_TRUE;
11303 cb.cb_literal = B_TRUE;
11304 break;
11305 case ZPOOL_OPTION_POOL_KEY_GUID:
11306 cb.cb_json_pool_key_guid = B_TRUE;
11307 break;
11308 case '?':
11309 if (optopt == 'c') {
11310 print_zpool_script_list("status");
11311 exit(0);
11312 } else {
11313 fprintf(stderr,
11314 gettext("invalid option '%c'\n"), optopt);
11315 }
11316 usage(B_FALSE);
11317 }
11318 }
11319
11320 argc -= optind;
11321 argv += optind;
11322
11323 get_interval_count(&argc, argv, &interval, &count);
11324
11325 if (argc == 0)
11326 cb.cb_allpools = B_TRUE;
11327
11328 cb.cb_first = B_TRUE;
11329 cb.cb_print_status = B_TRUE;
11330
11331 if (cb.cb_flat_vdevs && !cb.cb_json) {
11332 fprintf(stderr, gettext("'--json-flat-vdevs' only works with"
11333 " '-j' option\n"));
11334 usage(B_FALSE);
11335 }
11336
11337 if (cb.cb_json_as_int && !cb.cb_json) {
11338 (void) fprintf(stderr, gettext("'--json-int' only works with"
11339 " '-j' option\n"));
11340 usage(B_FALSE);
11341 }
11342
11343 if (!cb.cb_json && cb.cb_json_pool_key_guid) {
11344 (void) fprintf(stderr, gettext("'json-pool-key-guid' only"
11345 " works with '-j' option\n"));
11346 usage(B_FALSE);
11347 }
11348
11349 for (;;) {
11350 if (cb.cb_json) {
11351 cb.cb_jsobj = zpool_json_schema(0, 1);
11352 data = fnvlist_alloc();
11353 fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
11354 fnvlist_free(data);
11355 }
11356
11357 if (timestamp_fmt != NODATE) {
11358 if (cb.cb_json) {
11359 if (cb.cb_json_as_int) {
11360 fnvlist_add_uint64(cb.cb_jsobj, "time",
11361 time(NULL));
11362 } else {
11363 char ts[128];
11364 get_timestamp(timestamp_fmt, ts, 128);
11365 fnvlist_add_string(cb.cb_jsobj, "time",
11366 ts);
11367 }
11368 } else
11369 print_timestamp(timestamp_fmt);
11370 }
11371
11372 if (cmd != NULL)
11373 cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
11374 NULL, NULL, 0, 0);
11375
11376 if (cb.cb_json) {
11377 ret = for_each_pool(argc, argv, B_TRUE, NULL,
11378 ZFS_TYPE_POOL, cb.cb_literal,
11379 status_callback_json, &cb);
11380 } else {
11381 ret = for_each_pool(argc, argv, B_TRUE, NULL,
11382 ZFS_TYPE_POOL, cb.cb_literal,
11383 status_callback, &cb);
11384 }
11385
11386 if (cb.vcdl != NULL)
11387 free_vdev_cmd_data_list(cb.vcdl);
11388
11389 if (cb.cb_json) {
11390 if (ret == 0)
11391 zcmd_print_json(cb.cb_jsobj);
11392 else
11393 nvlist_free(cb.cb_jsobj);
11394 } else {
11395 if (argc == 0 && cb.cb_count == 0) {
11396 (void) fprintf(stderr, "%s",
11397 gettext("no pools available\n"));
11398 } else if (cb.cb_explain && cb.cb_first &&
11399 cb.cb_allpools) {
11400 (void) printf("%s",
11401 gettext("all pools are healthy\n"));
11402 }
11403 }
11404
11405 if (ret != 0)
11406 return (ret);
11407
11408 if (interval == 0)
11409 break;
11410
11411 if (count != 0 && --count == 0)
11412 break;
11413
11414 (void) fflush(stdout);
11415 (void) fsleep(interval);
11416 }
11417
11418 return (0);
11419 }
11420
11421 typedef struct upgrade_cbdata {
11422 int cb_first;
11423 int cb_argc;
11424 uint64_t cb_version;
11425 char **cb_argv;
11426 } upgrade_cbdata_t;
11427
11428 static int
check_unsupp_fs(zfs_handle_t * zhp,void * unsupp_fs)11429 check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
11430 {
11431 int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
11432 int *count = (int *)unsupp_fs;
11433
11434 if (zfs_version > ZPL_VERSION) {
11435 (void) printf(gettext("%s (v%d) is not supported by this "
11436 "implementation of ZFS.\n"),
11437 zfs_get_name(zhp), zfs_version);
11438 (*count)++;
11439 }
11440
11441 (void) zfs_iter_filesystems_v2(zhp, 0, check_unsupp_fs, unsupp_fs);
11442
11443 zfs_close(zhp);
11444
11445 return (0);
11446 }
11447
11448 static int
upgrade_version(zpool_handle_t * zhp,uint64_t version)11449 upgrade_version(zpool_handle_t *zhp, uint64_t version)
11450 {
11451 int ret;
11452 nvlist_t *config;
11453 uint64_t oldversion;
11454 int unsupp_fs = 0;
11455
11456 config = zpool_get_config(zhp, NULL);
11457 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11458 &oldversion) == 0);
11459
11460 char compat[ZFS_MAXPROPLEN];
11461 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11462 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11463 compat[0] = '\0';
11464
11465 assert(SPA_VERSION_IS_SUPPORTED(oldversion));
11466 assert(oldversion < version);
11467
11468 ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
11469 if (ret != 0)
11470 return (ret);
11471
11472 if (unsupp_fs) {
11473 (void) fprintf(stderr, gettext("Upgrade not performed due "
11474 "to %d unsupported filesystems (max v%d).\n"),
11475 unsupp_fs, (int)ZPL_VERSION);
11476 return (1);
11477 }
11478
11479 if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
11480 (void) fprintf(stderr, gettext("Upgrade not performed because "
11481 "'compatibility' property set to '"
11482 ZPOOL_COMPAT_LEGACY "'.\n"));
11483 return (1);
11484 }
11485
11486 ret = zpool_upgrade(zhp, version);
11487 if (ret != 0)
11488 return (ret);
11489
11490 if (version >= SPA_VERSION_FEATURES) {
11491 (void) printf(gettext("Successfully upgraded "
11492 "'%s' from version %llu to feature flags.\n"),
11493 zpool_get_name(zhp), (u_longlong_t)oldversion);
11494 } else {
11495 (void) printf(gettext("Successfully upgraded "
11496 "'%s' from version %llu to version %llu.\n"),
11497 zpool_get_name(zhp), (u_longlong_t)oldversion,
11498 (u_longlong_t)version);
11499 }
11500
11501 return (0);
11502 }
11503
11504 static int
upgrade_enable_all(zpool_handle_t * zhp,int * countp)11505 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
11506 {
11507 int i, ret, count;
11508 boolean_t firstff = B_TRUE;
11509 nvlist_t *enabled = zpool_get_features(zhp);
11510
11511 char compat[ZFS_MAXPROPLEN];
11512 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY, compat,
11513 ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
11514 compat[0] = '\0';
11515
11516 boolean_t requested_features[SPA_FEATURES];
11517 if (zpool_do_load_compat(compat, requested_features) !=
11518 ZPOOL_COMPATIBILITY_OK)
11519 return (-1);
11520
11521 count = 0;
11522 for (i = 0; i < SPA_FEATURES; i++) {
11523 const char *fname = spa_feature_table[i].fi_uname;
11524 const char *fguid = spa_feature_table[i].fi_guid;
11525
11526 if (!spa_feature_table[i].fi_zfs_mod_supported ||
11527 (spa_feature_table[i].fi_flags & ZFEATURE_FLAG_NO_UPGRADE))
11528 continue;
11529
11530 if (!nvlist_exists(enabled, fguid) && requested_features[i]) {
11531 char *propname;
11532 verify(-1 != asprintf(&propname, "feature@%s", fname));
11533 ret = zpool_set_prop(zhp, propname,
11534 ZFS_FEATURE_ENABLED);
11535 if (ret != 0) {
11536 free(propname);
11537 return (ret);
11538 }
11539 count++;
11540
11541 if (firstff) {
11542 (void) printf(gettext("Enabled the "
11543 "following features on '%s':\n"),
11544 zpool_get_name(zhp));
11545 firstff = B_FALSE;
11546 }
11547 (void) printf(gettext(" %s\n"), fname);
11548 free(propname);
11549 }
11550 }
11551
11552 if (countp != NULL)
11553 *countp = count;
11554 return (0);
11555 }
11556
11557 static int
upgrade_cb(zpool_handle_t * zhp,void * arg)11558 upgrade_cb(zpool_handle_t *zhp, void *arg)
11559 {
11560 upgrade_cbdata_t *cbp = arg;
11561 nvlist_t *config;
11562 uint64_t version;
11563 boolean_t modified_pool = B_FALSE;
11564 int ret;
11565
11566 config = zpool_get_config(zhp, NULL);
11567 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11568 &version) == 0);
11569
11570 assert(SPA_VERSION_IS_SUPPORTED(version));
11571
11572 if (version < cbp->cb_version) {
11573 cbp->cb_first = B_FALSE;
11574 ret = upgrade_version(zhp, cbp->cb_version);
11575 if (ret != 0)
11576 return (ret);
11577 modified_pool = B_TRUE;
11578
11579 /*
11580 * If they did "zpool upgrade -a", then we could
11581 * be doing ioctls to different pools. We need
11582 * to log this history once to each pool, and bypass
11583 * the normal history logging that happens in main().
11584 */
11585 (void) zpool_log_history(g_zfs, history_str);
11586 log_history = B_FALSE;
11587 }
11588
11589 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
11590 int count;
11591 ret = upgrade_enable_all(zhp, &count);
11592 if (ret != 0)
11593 return (ret);
11594
11595 if (count > 0) {
11596 cbp->cb_first = B_FALSE;
11597 modified_pool = B_TRUE;
11598 }
11599 }
11600
11601 if (modified_pool) {
11602 (void) printf("\n");
11603 (void) after_zpool_upgrade(zhp);
11604 }
11605
11606 return (0);
11607 }
11608
11609 static int
upgrade_list_older_cb(zpool_handle_t * zhp,void * arg)11610 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
11611 {
11612 upgrade_cbdata_t *cbp = arg;
11613 nvlist_t *config;
11614 uint64_t version;
11615
11616 config = zpool_get_config(zhp, NULL);
11617 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11618 &version) == 0);
11619
11620 assert(SPA_VERSION_IS_SUPPORTED(version));
11621
11622 if (version < SPA_VERSION_FEATURES) {
11623 if (cbp->cb_first) {
11624 (void) printf(gettext("The following pools are "
11625 "formatted with legacy version numbers and can\n"
11626 "be upgraded to use feature flags. After "
11627 "being upgraded, these pools\nwill no "
11628 "longer be accessible by software that does not "
11629 "support feature\nflags.\n\n"
11630 "Note that setting a pool's 'compatibility' "
11631 "feature to '" ZPOOL_COMPAT_LEGACY "' will\n"
11632 "inhibit upgrades.\n\n"));
11633 (void) printf(gettext("VER POOL\n"));
11634 (void) printf(gettext("--- ------------\n"));
11635 cbp->cb_first = B_FALSE;
11636 }
11637
11638 (void) printf("%2llu %s\n", (u_longlong_t)version,
11639 zpool_get_name(zhp));
11640 }
11641
11642 return (0);
11643 }
11644
11645 static int
upgrade_list_disabled_cb(zpool_handle_t * zhp,void * arg)11646 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
11647 {
11648 upgrade_cbdata_t *cbp = arg;
11649 nvlist_t *config;
11650 uint64_t version;
11651
11652 config = zpool_get_config(zhp, NULL);
11653 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
11654 &version) == 0);
11655
11656 if (version >= SPA_VERSION_FEATURES) {
11657 int i;
11658 boolean_t poolfirst = B_TRUE;
11659 nvlist_t *enabled = zpool_get_features(zhp);
11660
11661 for (i = 0; i < SPA_FEATURES; i++) {
11662 const char *fguid = spa_feature_table[i].fi_guid;
11663 const char *fname = spa_feature_table[i].fi_uname;
11664
11665 if (!spa_feature_table[i].fi_zfs_mod_supported)
11666 continue;
11667
11668 if (!nvlist_exists(enabled, fguid)) {
11669 if (cbp->cb_first) {
11670 (void) printf(gettext("\nSome "
11671 "supported features are not "
11672 "enabled on the following pools. "
11673 "Once a\nfeature is enabled the "
11674 "pool may become incompatible with "
11675 "software\nthat does not support "
11676 "the feature. See "
11677 "zpool-features(7) for "
11678 "details.\n\n"
11679 "Note that the pool "
11680 "'compatibility' feature can be "
11681 "used to inhibit\nfeature "
11682 "upgrades.\n\n"
11683 "Features marked with (*) are not "
11684 "applied automatically on upgrade, "
11685 "and\nmust be applied explicitly "
11686 "with zpool-set(7).\n\n"));
11687 (void) printf(gettext("POOL "
11688 "FEATURE\n"));
11689 (void) printf(gettext("------"
11690 "---------\n"));
11691 cbp->cb_first = B_FALSE;
11692 }
11693
11694 if (poolfirst) {
11695 (void) printf(gettext("%s\n"),
11696 zpool_get_name(zhp));
11697 poolfirst = B_FALSE;
11698 }
11699
11700 (void) printf(gettext(" %s%s\n"), fname,
11701 spa_feature_table[i].fi_flags &
11702 ZFEATURE_FLAG_NO_UPGRADE ? "(*)" : "");
11703 }
11704 /*
11705 * If they did "zpool upgrade -a", then we could
11706 * be doing ioctls to different pools. We need
11707 * to log this history once to each pool, and bypass
11708 * the normal history logging that happens in main().
11709 */
11710 (void) zpool_log_history(g_zfs, history_str);
11711 log_history = B_FALSE;
11712 }
11713 }
11714
11715 return (0);
11716 }
11717
11718 static int
upgrade_one(zpool_handle_t * zhp,void * data)11719 upgrade_one(zpool_handle_t *zhp, void *data)
11720 {
11721 boolean_t modified_pool = B_FALSE;
11722 upgrade_cbdata_t *cbp = data;
11723 uint64_t cur_version;
11724 int ret;
11725
11726 if (strcmp("log", zpool_get_name(zhp)) == 0) {
11727 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
11728 "Pool 'log' must be renamed using export and import"
11729 " to upgrade.\n"));
11730 return (1);
11731 }
11732
11733 cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
11734 if (cur_version > cbp->cb_version) {
11735 (void) printf(gettext("Pool '%s' is already formatted "
11736 "using more current version '%llu'.\n\n"),
11737 zpool_get_name(zhp), (u_longlong_t)cur_version);
11738 return (0);
11739 }
11740
11741 if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
11742 (void) printf(gettext("Pool '%s' is already formatted "
11743 "using version %llu.\n\n"), zpool_get_name(zhp),
11744 (u_longlong_t)cbp->cb_version);
11745 return (0);
11746 }
11747
11748 if (cur_version != cbp->cb_version) {
11749 modified_pool = B_TRUE;
11750 ret = upgrade_version(zhp, cbp->cb_version);
11751 if (ret != 0)
11752 return (ret);
11753 }
11754
11755 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
11756 int count = 0;
11757 ret = upgrade_enable_all(zhp, &count);
11758 if (ret != 0)
11759 return (ret);
11760
11761 if (count != 0) {
11762 modified_pool = B_TRUE;
11763 } else if (cur_version == SPA_VERSION) {
11764 (void) printf(gettext("Pool '%s' already has all "
11765 "supported and requested features enabled.\n"),
11766 zpool_get_name(zhp));
11767 }
11768 }
11769
11770 if (modified_pool) {
11771 (void) printf("\n");
11772 (void) after_zpool_upgrade(zhp);
11773 }
11774
11775 return (0);
11776 }
11777
11778 /*
11779 * zpool upgrade
11780 * zpool upgrade -v
11781 * zpool upgrade [-V version] <-a | pool ...>
11782 *
11783 * With no arguments, display downrev'd ZFS pool available for upgrade.
11784 * Individual pools can be upgraded by specifying the pool, and '-a' will
11785 * upgrade all pools.
11786 */
11787 int
zpool_do_upgrade(int argc,char ** argv)11788 zpool_do_upgrade(int argc, char **argv)
11789 {
11790 int c;
11791 upgrade_cbdata_t cb = { 0 };
11792 int ret = 0;
11793 boolean_t showversions = B_FALSE;
11794 boolean_t upgradeall = B_FALSE;
11795 char *end;
11796
11797
11798 /* check options */
11799 while ((c = getopt(argc, argv, ":avV:")) != -1) {
11800 switch (c) {
11801 case 'a':
11802 upgradeall = B_TRUE;
11803 break;
11804 case 'v':
11805 showversions = B_TRUE;
11806 break;
11807 case 'V':
11808 cb.cb_version = strtoll(optarg, &end, 10);
11809 if (*end != '\0' ||
11810 !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
11811 (void) fprintf(stderr,
11812 gettext("invalid version '%s'\n"), optarg);
11813 usage(B_FALSE);
11814 }
11815 break;
11816 case ':':
11817 (void) fprintf(stderr, gettext("missing argument for "
11818 "'%c' option\n"), optopt);
11819 usage(B_FALSE);
11820 break;
11821 case '?':
11822 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
11823 optopt);
11824 usage(B_FALSE);
11825 }
11826 }
11827
11828 cb.cb_argc = argc;
11829 cb.cb_argv = argv;
11830 argc -= optind;
11831 argv += optind;
11832
11833 if (cb.cb_version == 0) {
11834 cb.cb_version = SPA_VERSION;
11835 } else if (!upgradeall && argc == 0) {
11836 (void) fprintf(stderr, gettext("-V option is "
11837 "incompatible with other arguments\n"));
11838 usage(B_FALSE);
11839 }
11840
11841 if (showversions) {
11842 if (upgradeall || argc != 0) {
11843 (void) fprintf(stderr, gettext("-v option is "
11844 "incompatible with other arguments\n"));
11845 usage(B_FALSE);
11846 }
11847 } else if (upgradeall) {
11848 if (argc != 0) {
11849 (void) fprintf(stderr, gettext("-a option should not "
11850 "be used along with a pool name\n"));
11851 usage(B_FALSE);
11852 }
11853 }
11854
11855 (void) printf("%s", gettext("This system supports ZFS pool feature "
11856 "flags.\n\n"));
11857 if (showversions) {
11858 int i;
11859
11860 (void) printf(gettext("The following features are "
11861 "supported:\n\n"));
11862 (void) printf(gettext("FEAT DESCRIPTION\n"));
11863 (void) printf("----------------------------------------------"
11864 "---------------\n");
11865 for (i = 0; i < SPA_FEATURES; i++) {
11866 zfeature_info_t *fi = &spa_feature_table[i];
11867 if (!fi->fi_zfs_mod_supported)
11868 continue;
11869 const char *ro =
11870 (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
11871 " (read-only compatible)" : "";
11872
11873 (void) printf("%-37s%s\n", fi->fi_uname, ro);
11874 (void) printf(" %s\n", fi->fi_desc);
11875 }
11876 (void) printf("\n");
11877
11878 (void) printf(gettext("The following legacy versions are also "
11879 "supported:\n\n"));
11880 (void) printf(gettext("VER DESCRIPTION\n"));
11881 (void) printf("--- -----------------------------------------"
11882 "---------------\n");
11883 (void) printf(gettext(" 1 Initial ZFS version\n"));
11884 (void) printf(gettext(" 2 Ditto blocks "
11885 "(replicated metadata)\n"));
11886 (void) printf(gettext(" 3 Hot spares and double parity "
11887 "RAID-Z\n"));
11888 (void) printf(gettext(" 4 zpool history\n"));
11889 (void) printf(gettext(" 5 Compression using the gzip "
11890 "algorithm\n"));
11891 (void) printf(gettext(" 6 bootfs pool property\n"));
11892 (void) printf(gettext(" 7 Separate intent log devices\n"));
11893 (void) printf(gettext(" 8 Delegated administration\n"));
11894 (void) printf(gettext(" 9 refquota and refreservation "
11895 "properties\n"));
11896 (void) printf(gettext(" 10 Cache devices\n"));
11897 (void) printf(gettext(" 11 Improved scrub performance\n"));
11898 (void) printf(gettext(" 12 Snapshot properties\n"));
11899 (void) printf(gettext(" 13 snapused property\n"));
11900 (void) printf(gettext(" 14 passthrough-x aclinherit\n"));
11901 (void) printf(gettext(" 15 user/group space accounting\n"));
11902 (void) printf(gettext(" 16 stmf property support\n"));
11903 (void) printf(gettext(" 17 Triple-parity RAID-Z\n"));
11904 (void) printf(gettext(" 18 Snapshot user holds\n"));
11905 (void) printf(gettext(" 19 Log device removal\n"));
11906 (void) printf(gettext(" 20 Compression using zle "
11907 "(zero-length encoding)\n"));
11908 (void) printf(gettext(" 21 Deduplication\n"));
11909 (void) printf(gettext(" 22 Received properties\n"));
11910 (void) printf(gettext(" 23 Slim ZIL\n"));
11911 (void) printf(gettext(" 24 System attributes\n"));
11912 (void) printf(gettext(" 25 Improved scrub stats\n"));
11913 (void) printf(gettext(" 26 Improved snapshot deletion "
11914 "performance\n"));
11915 (void) printf(gettext(" 27 Improved snapshot creation "
11916 "performance\n"));
11917 (void) printf(gettext(" 28 Multiple vdev replacements\n"));
11918 (void) printf(gettext("\nFor more information on a particular "
11919 "version, including supported releases,\n"));
11920 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
11921 } else if (argc == 0 && upgradeall) {
11922 cb.cb_first = B_TRUE;
11923 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
11924 if (ret == 0 && cb.cb_first) {
11925 if (cb.cb_version == SPA_VERSION) {
11926 (void) printf(gettext("All pools are already "
11927 "formatted using feature flags.\n\n"));
11928 (void) printf(gettext("Every feature flags "
11929 "pool already has all supported and "
11930 "requested features enabled.\n"));
11931 } else {
11932 (void) printf(gettext("All pools are already "
11933 "formatted with version %llu or higher.\n"),
11934 (u_longlong_t)cb.cb_version);
11935 }
11936 }
11937 } else if (argc == 0) {
11938 cb.cb_first = B_TRUE;
11939 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
11940 assert(ret == 0);
11941
11942 if (cb.cb_first) {
11943 (void) printf(gettext("All pools are formatted "
11944 "using feature flags.\n\n"));
11945 } else {
11946 (void) printf(gettext("\nUse 'zpool upgrade -v' "
11947 "for a list of available legacy versions.\n"));
11948 }
11949
11950 cb.cb_first = B_TRUE;
11951 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
11952 assert(ret == 0);
11953
11954 if (cb.cb_first) {
11955 (void) printf(gettext("Every feature flags pool has "
11956 "all supported and requested features enabled.\n"));
11957 } else {
11958 (void) printf(gettext("\n"));
11959 }
11960 } else {
11961 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
11962 B_FALSE, upgrade_one, &cb);
11963 }
11964
11965 return (ret);
11966 }
11967
11968 typedef struct hist_cbdata {
11969 boolean_t first;
11970 boolean_t longfmt;
11971 boolean_t internal;
11972 } hist_cbdata_t;
11973
11974 static void
print_history_records(nvlist_t * nvhis,hist_cbdata_t * cb)11975 print_history_records(nvlist_t *nvhis, hist_cbdata_t *cb)
11976 {
11977 nvlist_t **records;
11978 uint_t numrecords;
11979 int i;
11980
11981 verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
11982 &records, &numrecords) == 0);
11983 for (i = 0; i < numrecords; i++) {
11984 nvlist_t *rec = records[i];
11985 char tbuf[64] = "";
11986
11987 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
11988 time_t tsec;
11989 struct tm t;
11990
11991 tsec = fnvlist_lookup_uint64(records[i],
11992 ZPOOL_HIST_TIME);
11993 (void) localtime_r(&tsec, &t);
11994 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
11995 }
11996
11997 if (nvlist_exists(rec, ZPOOL_HIST_ELAPSED_NS)) {
11998 uint64_t elapsed_ns = fnvlist_lookup_int64(records[i],
11999 ZPOOL_HIST_ELAPSED_NS);
12000 (void) snprintf(tbuf + strlen(tbuf),
12001 sizeof (tbuf) - strlen(tbuf),
12002 " (%lldms)", (long long)elapsed_ns / 1000 / 1000);
12003 }
12004
12005 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
12006 (void) printf("%s %s", tbuf,
12007 fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
12008 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
12009 int ievent =
12010 fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
12011 if (!cb->internal)
12012 continue;
12013 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
12014 (void) printf("%s unrecognized record:\n",
12015 tbuf);
12016 dump_nvlist(rec, 4);
12017 continue;
12018 }
12019 (void) printf("%s [internal %s txg:%lld] %s", tbuf,
12020 zfs_history_event_names[ievent],
12021 (longlong_t)fnvlist_lookup_uint64(
12022 rec, ZPOOL_HIST_TXG),
12023 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
12024 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
12025 if (!cb->internal)
12026 continue;
12027 (void) printf("%s [txg:%lld] %s", tbuf,
12028 (longlong_t)fnvlist_lookup_uint64(
12029 rec, ZPOOL_HIST_TXG),
12030 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
12031 if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
12032 (void) printf(" %s (%llu)",
12033 fnvlist_lookup_string(rec,
12034 ZPOOL_HIST_DSNAME),
12035 (u_longlong_t)fnvlist_lookup_uint64(rec,
12036 ZPOOL_HIST_DSID));
12037 }
12038 (void) printf(" %s", fnvlist_lookup_string(rec,
12039 ZPOOL_HIST_INT_STR));
12040 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
12041 if (!cb->internal)
12042 continue;
12043 (void) printf("%s ioctl %s\n", tbuf,
12044 fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
12045 if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
12046 (void) printf(" input:\n");
12047 dump_nvlist(fnvlist_lookup_nvlist(rec,
12048 ZPOOL_HIST_INPUT_NVL), 8);
12049 }
12050 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
12051 (void) printf(" output:\n");
12052 dump_nvlist(fnvlist_lookup_nvlist(rec,
12053 ZPOOL_HIST_OUTPUT_NVL), 8);
12054 }
12055 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_SIZE)) {
12056 (void) printf(" output nvlist omitted; "
12057 "original size: %lldKB\n",
12058 (longlong_t)fnvlist_lookup_int64(rec,
12059 ZPOOL_HIST_OUTPUT_SIZE) / 1024);
12060 }
12061 if (nvlist_exists(rec, ZPOOL_HIST_ERRNO)) {
12062 (void) printf(" errno: %lld\n",
12063 (longlong_t)fnvlist_lookup_int64(rec,
12064 ZPOOL_HIST_ERRNO));
12065 }
12066 } else {
12067 if (!cb->internal)
12068 continue;
12069 (void) printf("%s unrecognized record:\n", tbuf);
12070 dump_nvlist(rec, 4);
12071 }
12072
12073 if (!cb->longfmt) {
12074 (void) printf("\n");
12075 continue;
12076 }
12077 (void) printf(" [");
12078 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
12079 uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
12080 struct passwd *pwd = getpwuid(who);
12081 (void) printf("user %d ", (int)who);
12082 if (pwd != NULL)
12083 (void) printf("(%s) ", pwd->pw_name);
12084 }
12085 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
12086 (void) printf("on %s",
12087 fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
12088 }
12089 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
12090 (void) printf(":%s",
12091 fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
12092 }
12093
12094 (void) printf("]");
12095 (void) printf("\n");
12096 }
12097 }
12098
12099 /*
12100 * Print out the command history for a specific pool.
12101 */
12102 static int
get_history_one(zpool_handle_t * zhp,void * data)12103 get_history_one(zpool_handle_t *zhp, void *data)
12104 {
12105 nvlist_t *nvhis;
12106 int ret;
12107 hist_cbdata_t *cb = (hist_cbdata_t *)data;
12108 uint64_t off = 0;
12109 boolean_t eof = B_FALSE;
12110
12111 cb->first = B_FALSE;
12112
12113 (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
12114
12115 while (!eof) {
12116 if ((ret = zpool_get_history(zhp, &nvhis, &off, &eof)) != 0)
12117 return (ret);
12118
12119 print_history_records(nvhis, cb);
12120 nvlist_free(nvhis);
12121 }
12122 (void) printf("\n");
12123
12124 return (ret);
12125 }
12126
12127 /*
12128 * zpool history <pool>
12129 *
12130 * Displays the history of commands that modified pools.
12131 */
12132 int
zpool_do_history(int argc,char ** argv)12133 zpool_do_history(int argc, char **argv)
12134 {
12135 hist_cbdata_t cbdata = { 0 };
12136 int ret;
12137 int c;
12138
12139 cbdata.first = B_TRUE;
12140 /* check options */
12141 while ((c = getopt(argc, argv, "li")) != -1) {
12142 switch (c) {
12143 case 'l':
12144 cbdata.longfmt = B_TRUE;
12145 break;
12146 case 'i':
12147 cbdata.internal = B_TRUE;
12148 break;
12149 case '?':
12150 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
12151 optopt);
12152 usage(B_FALSE);
12153 }
12154 }
12155 argc -= optind;
12156 argv += optind;
12157
12158 ret = for_each_pool(argc, argv, B_FALSE, NULL, ZFS_TYPE_POOL,
12159 B_FALSE, get_history_one, &cbdata);
12160
12161 if (argc == 0 && cbdata.first == B_TRUE) {
12162 (void) fprintf(stderr, gettext("no pools available\n"));
12163 return (0);
12164 }
12165
12166 return (ret);
12167 }
12168
12169 typedef struct ev_opts {
12170 int verbose;
12171 int scripted;
12172 int follow;
12173 int clear;
12174 char poolname[ZFS_MAX_DATASET_NAME_LEN];
12175 } ev_opts_t;
12176
12177 static void
zpool_do_events_short(nvlist_t * nvl,ev_opts_t * opts)12178 zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
12179 {
12180 char ctime_str[26], str[32];
12181 const char *ptr;
12182 int64_t *tv;
12183 uint_t n;
12184
12185 verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
12186 memset(str, ' ', 32);
12187 (void) ctime_r((const time_t *)&tv[0], ctime_str);
12188 (void) memcpy(str, ctime_str+4, 6); /* 'Jun 30' */
12189 (void) memcpy(str+7, ctime_str+20, 4); /* '1993' */
12190 (void) memcpy(str+12, ctime_str+11, 8); /* '21:49:08' */
12191 (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
12192 if (opts->scripted)
12193 (void) printf(gettext("%s\t"), str);
12194 else
12195 (void) printf(gettext("%s "), str);
12196
12197 verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
12198 (void) printf(gettext("%s\n"), ptr);
12199 }
12200
12201 static void
zpool_do_events_nvprint(nvlist_t * nvl,int depth)12202 zpool_do_events_nvprint(nvlist_t *nvl, int depth)
12203 {
12204 nvpair_t *nvp;
12205 static char flagstr[256];
12206
12207 for (nvp = nvlist_next_nvpair(nvl, NULL);
12208 nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
12209
12210 data_type_t type = nvpair_type(nvp);
12211 const char *name = nvpair_name(nvp);
12212
12213 boolean_t b;
12214 uint8_t i8;
12215 uint16_t i16;
12216 uint32_t i32;
12217 uint64_t i64;
12218 const char *str;
12219 nvlist_t *cnv;
12220
12221 printf(gettext("%*s%s = "), depth, "", name);
12222
12223 switch (type) {
12224 case DATA_TYPE_BOOLEAN:
12225 printf(gettext("%s"), "1");
12226 break;
12227
12228 case DATA_TYPE_BOOLEAN_VALUE:
12229 (void) nvpair_value_boolean_value(nvp, &b);
12230 printf(gettext("%s"), b ? "1" : "0");
12231 break;
12232
12233 case DATA_TYPE_BYTE:
12234 (void) nvpair_value_byte(nvp, &i8);
12235 printf(gettext("0x%x"), i8);
12236 break;
12237
12238 case DATA_TYPE_INT8:
12239 (void) nvpair_value_int8(nvp, (void *)&i8);
12240 printf(gettext("0x%x"), i8);
12241 break;
12242
12243 case DATA_TYPE_UINT8:
12244 (void) nvpair_value_uint8(nvp, &i8);
12245 printf(gettext("0x%x"), i8);
12246 break;
12247
12248 case DATA_TYPE_INT16:
12249 (void) nvpair_value_int16(nvp, (void *)&i16);
12250 printf(gettext("0x%x"), i16);
12251 break;
12252
12253 case DATA_TYPE_UINT16:
12254 (void) nvpair_value_uint16(nvp, &i16);
12255 printf(gettext("0x%x"), i16);
12256 break;
12257
12258 case DATA_TYPE_INT32:
12259 (void) nvpair_value_int32(nvp, (void *)&i32);
12260 printf(gettext("0x%x"), i32);
12261 break;
12262
12263 case DATA_TYPE_UINT32:
12264 (void) nvpair_value_uint32(nvp, &i32);
12265 if (strcmp(name,
12266 FM_EREPORT_PAYLOAD_ZFS_ZIO_STAGE) == 0 ||
12267 strcmp(name,
12268 FM_EREPORT_PAYLOAD_ZFS_ZIO_PIPELINE) == 0) {
12269 (void) zfs_valstr_zio_stage(i32, flagstr,
12270 sizeof (flagstr));
12271 printf(gettext("0x%x [%s]"), i32, flagstr);
12272 } else if (strcmp(name,
12273 FM_EREPORT_PAYLOAD_ZFS_ZIO_TYPE) == 0) {
12274 (void) zfs_valstr_zio_type(i32, flagstr,
12275 sizeof (flagstr));
12276 printf(gettext("0x%x [%s]"), i32, flagstr);
12277 } else if (strcmp(name,
12278 FM_EREPORT_PAYLOAD_ZFS_ZIO_PRIORITY) == 0) {
12279 (void) zfs_valstr_zio_priority(i32, flagstr,
12280 sizeof (flagstr));
12281 printf(gettext("0x%x [%s]"), i32, flagstr);
12282 } else {
12283 printf(gettext("0x%x"), i32);
12284 }
12285 break;
12286
12287 case DATA_TYPE_INT64:
12288 (void) nvpair_value_int64(nvp, (void *)&i64);
12289 printf(gettext("0x%llx"), (u_longlong_t)i64);
12290 break;
12291
12292 case DATA_TYPE_UINT64:
12293 (void) nvpair_value_uint64(nvp, &i64);
12294 /*
12295 * translate vdev state values to readable
12296 * strings to aide zpool events consumers
12297 */
12298 if (strcmp(name,
12299 FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
12300 strcmp(name,
12301 FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
12302 printf(gettext("\"%s\" (0x%llx)"),
12303 zpool_state_to_name(i64, VDEV_AUX_NONE),
12304 (u_longlong_t)i64);
12305 } else if (strcmp(name,
12306 FM_EREPORT_PAYLOAD_ZFS_ZIO_FLAGS) == 0) {
12307 (void) zfs_valstr_zio_flag(i64, flagstr,
12308 sizeof (flagstr));
12309 printf(gettext("0x%llx [%s]"),
12310 (u_longlong_t)i64, flagstr);
12311 } else {
12312 printf(gettext("0x%llx"), (u_longlong_t)i64);
12313 }
12314 break;
12315
12316 case DATA_TYPE_HRTIME:
12317 (void) nvpair_value_hrtime(nvp, (void *)&i64);
12318 printf(gettext("0x%llx"), (u_longlong_t)i64);
12319 break;
12320
12321 case DATA_TYPE_STRING:
12322 (void) nvpair_value_string(nvp, &str);
12323 printf(gettext("\"%s\""), str ? str : "<NULL>");
12324 break;
12325
12326 case DATA_TYPE_NVLIST:
12327 printf(gettext("(embedded nvlist)\n"));
12328 (void) nvpair_value_nvlist(nvp, &cnv);
12329 zpool_do_events_nvprint(cnv, depth + 8);
12330 printf(gettext("%*s(end %s)"), depth, "", name);
12331 break;
12332
12333 case DATA_TYPE_NVLIST_ARRAY: {
12334 nvlist_t **val;
12335 uint_t i, nelem;
12336
12337 (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
12338 printf(gettext("(%d embedded nvlists)\n"), nelem);
12339 for (i = 0; i < nelem; i++) {
12340 printf(gettext("%*s%s[%d] = %s\n"),
12341 depth, "", name, i, "(embedded nvlist)");
12342 zpool_do_events_nvprint(val[i], depth + 8);
12343 printf(gettext("%*s(end %s[%i])\n"),
12344 depth, "", name, i);
12345 }
12346 printf(gettext("%*s(end %s)\n"), depth, "", name);
12347 }
12348 break;
12349
12350 case DATA_TYPE_INT8_ARRAY: {
12351 int8_t *val;
12352 uint_t i, nelem;
12353
12354 (void) nvpair_value_int8_array(nvp, &val, &nelem);
12355 for (i = 0; i < nelem; i++)
12356 printf(gettext("0x%x "), val[i]);
12357
12358 break;
12359 }
12360
12361 case DATA_TYPE_UINT8_ARRAY: {
12362 uint8_t *val;
12363 uint_t i, nelem;
12364
12365 (void) nvpair_value_uint8_array(nvp, &val, &nelem);
12366 for (i = 0; i < nelem; i++)
12367 printf(gettext("0x%x "), val[i]);
12368
12369 break;
12370 }
12371
12372 case DATA_TYPE_INT16_ARRAY: {
12373 int16_t *val;
12374 uint_t i, nelem;
12375
12376 (void) nvpair_value_int16_array(nvp, &val, &nelem);
12377 for (i = 0; i < nelem; i++)
12378 printf(gettext("0x%x "), val[i]);
12379
12380 break;
12381 }
12382
12383 case DATA_TYPE_UINT16_ARRAY: {
12384 uint16_t *val;
12385 uint_t i, nelem;
12386
12387 (void) nvpair_value_uint16_array(nvp, &val, &nelem);
12388 for (i = 0; i < nelem; i++)
12389 printf(gettext("0x%x "), val[i]);
12390
12391 break;
12392 }
12393
12394 case DATA_TYPE_INT32_ARRAY: {
12395 int32_t *val;
12396 uint_t i, nelem;
12397
12398 (void) nvpair_value_int32_array(nvp, &val, &nelem);
12399 for (i = 0; i < nelem; i++)
12400 printf(gettext("0x%x "), val[i]);
12401
12402 break;
12403 }
12404
12405 case DATA_TYPE_UINT32_ARRAY: {
12406 uint32_t *val;
12407 uint_t i, nelem;
12408
12409 (void) nvpair_value_uint32_array(nvp, &val, &nelem);
12410 for (i = 0; i < nelem; i++)
12411 printf(gettext("0x%x "), val[i]);
12412
12413 break;
12414 }
12415
12416 case DATA_TYPE_INT64_ARRAY: {
12417 int64_t *val;
12418 uint_t i, nelem;
12419
12420 (void) nvpair_value_int64_array(nvp, &val, &nelem);
12421 for (i = 0; i < nelem; i++)
12422 printf(gettext("0x%llx "),
12423 (u_longlong_t)val[i]);
12424
12425 break;
12426 }
12427
12428 case DATA_TYPE_UINT64_ARRAY: {
12429 uint64_t *val;
12430 uint_t i, nelem;
12431
12432 (void) nvpair_value_uint64_array(nvp, &val, &nelem);
12433 for (i = 0; i < nelem; i++)
12434 printf(gettext("0x%llx "),
12435 (u_longlong_t)val[i]);
12436
12437 break;
12438 }
12439
12440 case DATA_TYPE_STRING_ARRAY: {
12441 const char **str;
12442 uint_t i, nelem;
12443
12444 (void) nvpair_value_string_array(nvp, &str, &nelem);
12445 for (i = 0; i < nelem; i++)
12446 printf(gettext("\"%s\" "),
12447 str[i] ? str[i] : "<NULL>");
12448
12449 break;
12450 }
12451
12452 case DATA_TYPE_BOOLEAN_ARRAY:
12453 case DATA_TYPE_BYTE_ARRAY:
12454 case DATA_TYPE_DOUBLE:
12455 case DATA_TYPE_DONTCARE:
12456 case DATA_TYPE_UNKNOWN:
12457 printf(gettext("<unknown>"));
12458 break;
12459 }
12460
12461 printf(gettext("\n"));
12462 }
12463 }
12464
12465 static int
zpool_do_events_next(ev_opts_t * opts)12466 zpool_do_events_next(ev_opts_t *opts)
12467 {
12468 nvlist_t *nvl;
12469 int zevent_fd, ret, dropped;
12470 const char *pool;
12471
12472 zevent_fd = open(ZFS_DEV, O_RDWR);
12473 VERIFY(zevent_fd >= 0);
12474
12475 if (!opts->scripted)
12476 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
12477
12478 while (1) {
12479 ret = zpool_events_next(g_zfs, &nvl, &dropped,
12480 (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
12481 if (ret || nvl == NULL)
12482 break;
12483
12484 if (dropped > 0)
12485 (void) printf(gettext("dropped %d events\n"), dropped);
12486
12487 if (strlen(opts->poolname) > 0 &&
12488 nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
12489 strcmp(opts->poolname, pool) != 0)
12490 continue;
12491
12492 zpool_do_events_short(nvl, opts);
12493
12494 if (opts->verbose) {
12495 zpool_do_events_nvprint(nvl, 8);
12496 printf(gettext("\n"));
12497 }
12498 (void) fflush(stdout);
12499
12500 nvlist_free(nvl);
12501 }
12502
12503 VERIFY0(close(zevent_fd));
12504
12505 return (ret);
12506 }
12507
12508 static int
zpool_do_events_clear(void)12509 zpool_do_events_clear(void)
12510 {
12511 int count, ret;
12512
12513 ret = zpool_events_clear(g_zfs, &count);
12514 if (!ret)
12515 (void) printf(gettext("cleared %d events\n"), count);
12516
12517 return (ret);
12518 }
12519
12520 /*
12521 * zpool events [-vHf [pool] | -c]
12522 *
12523 * Displays events logs by ZFS.
12524 */
12525 int
zpool_do_events(int argc,char ** argv)12526 zpool_do_events(int argc, char **argv)
12527 {
12528 ev_opts_t opts = { 0 };
12529 int ret;
12530 int c;
12531
12532 /* check options */
12533 while ((c = getopt(argc, argv, "vHfc")) != -1) {
12534 switch (c) {
12535 case 'v':
12536 opts.verbose = 1;
12537 break;
12538 case 'H':
12539 opts.scripted = 1;
12540 break;
12541 case 'f':
12542 opts.follow = 1;
12543 break;
12544 case 'c':
12545 opts.clear = 1;
12546 break;
12547 case '?':
12548 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
12549 optopt);
12550 usage(B_FALSE);
12551 }
12552 }
12553 argc -= optind;
12554 argv += optind;
12555
12556 if (argc > 1) {
12557 (void) fprintf(stderr, gettext("too many arguments\n"));
12558 usage(B_FALSE);
12559 } else if (argc == 1) {
12560 (void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
12561 if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
12562 (void) fprintf(stderr,
12563 gettext("invalid pool name '%s'\n"), opts.poolname);
12564 usage(B_FALSE);
12565 }
12566 }
12567
12568 if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
12569 opts.clear) {
12570 (void) fprintf(stderr,
12571 gettext("invalid options combined with -c\n"));
12572 usage(B_FALSE);
12573 }
12574
12575 if (opts.clear)
12576 ret = zpool_do_events_clear();
12577 else
12578 ret = zpool_do_events_next(&opts);
12579
12580 return (ret);
12581 }
12582
12583 static int
get_callback_vdev(zpool_handle_t * zhp,char * vdevname,void * data)12584 get_callback_vdev(zpool_handle_t *zhp, char *vdevname, void *data)
12585 {
12586 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12587 char value[ZFS_MAXPROPLEN];
12588 zprop_source_t srctype;
12589 nvlist_t *props, *item, *d;
12590 props = item = d = NULL;
12591
12592 if (cbp->cb_json) {
12593 d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "vdevs");
12594 if (d == NULL) {
12595 fprintf(stderr, "vdevs obj not found.\n");
12596 exit(1);
12597 }
12598 props = fnvlist_alloc();
12599 }
12600
12601 for (zprop_list_t *pl = cbp->cb_proplist; pl != NULL;
12602 pl = pl->pl_next) {
12603 char *prop_name;
12604 /*
12605 * If the first property is pool name, it is a special
12606 * placeholder that we can skip. This will also skip
12607 * over the name property when 'all' is specified.
12608 */
12609 if (pl->pl_prop == ZPOOL_PROP_NAME &&
12610 pl == cbp->cb_proplist)
12611 continue;
12612
12613 if (pl->pl_prop == ZPROP_INVAL) {
12614 prop_name = pl->pl_user_prop;
12615 } else {
12616 prop_name = (char *)vdev_prop_to_name(pl->pl_prop);
12617 }
12618 if (zpool_get_vdev_prop(zhp, vdevname, pl->pl_prop,
12619 prop_name, value, sizeof (value), &srctype,
12620 cbp->cb_literal) == 0) {
12621 (void) zprop_collect_property(vdevname, cbp, prop_name,
12622 value, srctype, NULL, NULL, props);
12623 }
12624 }
12625
12626 if (cbp->cb_json) {
12627 if (!nvlist_empty(props)) {
12628 item = fnvlist_alloc();
12629 fill_vdev_info(item, zhp, vdevname, B_TRUE,
12630 cbp->cb_json_as_int);
12631 fnvlist_add_nvlist(item, "properties", props);
12632 fnvlist_add_nvlist(d, vdevname, item);
12633 fnvlist_add_nvlist(cbp->cb_jsobj, "vdevs", d);
12634 fnvlist_free(item);
12635 }
12636 fnvlist_free(props);
12637 }
12638
12639 return (0);
12640 }
12641
12642 static int
get_callback_vdev_cb(void * zhp_data,nvlist_t * nv,void * data)12643 get_callback_vdev_cb(void *zhp_data, nvlist_t *nv, void *data)
12644 {
12645 zpool_handle_t *zhp = zhp_data;
12646 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12647 char *vdevname;
12648 const char *type;
12649 int ret;
12650
12651 /*
12652 * zpool_vdev_name() transforms the root vdev name (i.e., root-0) to the
12653 * pool name for display purposes, which is not desired. Fallback to
12654 * zpool_vdev_name() when not dealing with the root vdev.
12655 */
12656 type = fnvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE);
12657 if (zhp != NULL && strcmp(type, "root") == 0)
12658 vdevname = strdup("root-0");
12659 else
12660 vdevname = zpool_vdev_name(g_zfs, zhp, nv,
12661 cbp->cb_vdevs.cb_name_flags);
12662
12663 (void) vdev_expand_proplist(zhp, vdevname, &cbp->cb_proplist);
12664
12665 ret = get_callback_vdev(zhp, vdevname, data);
12666
12667 free(vdevname);
12668
12669 return (ret);
12670 }
12671
12672 static int
get_callback(zpool_handle_t * zhp,void * data)12673 get_callback(zpool_handle_t *zhp, void *data)
12674 {
12675 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
12676 char value[ZFS_MAXPROPLEN];
12677 zprop_source_t srctype;
12678 zprop_list_t *pl;
12679 int vid;
12680 int err = 0;
12681 nvlist_t *props, *item, *d;
12682 props = item = d = NULL;
12683
12684 if (cbp->cb_type == ZFS_TYPE_VDEV) {
12685 if (cbp->cb_json) {
12686 nvlist_t *pool = fnvlist_alloc();
12687 fill_pool_info(pool, zhp, B_FALSE, cbp->cb_json_as_int);
12688 fnvlist_add_nvlist(cbp->cb_jsobj, "pool", pool);
12689 fnvlist_free(pool);
12690 }
12691
12692 if (strcmp(cbp->cb_vdevs.cb_names[0], "all-vdevs") == 0) {
12693 (void) for_each_vdev(zhp, get_callback_vdev_cb, data);
12694 } else {
12695 /* Adjust column widths for vdev properties */
12696 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
12697 vid++) {
12698 (void) vdev_expand_proplist(zhp,
12699 cbp->cb_vdevs.cb_names[vid],
12700 &cbp->cb_proplist);
12701 }
12702 /* Display the properties */
12703 for (vid = 0; vid < cbp->cb_vdevs.cb_names_count;
12704 vid++) {
12705 (void) get_callback_vdev(zhp,
12706 cbp->cb_vdevs.cb_names[vid], data);
12707 }
12708 }
12709 } else {
12710 assert(cbp->cb_type == ZFS_TYPE_POOL);
12711 if (cbp->cb_json) {
12712 d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "pools");
12713 if (d == NULL) {
12714 fprintf(stderr, "pools obj not found.\n");
12715 exit(1);
12716 }
12717 props = fnvlist_alloc();
12718 }
12719 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
12720 /*
12721 * Skip the special fake placeholder. This will also
12722 * skip over the name property when 'all' is specified.
12723 */
12724 if (pl->pl_prop == ZPOOL_PROP_NAME &&
12725 pl == cbp->cb_proplist)
12726 continue;
12727
12728 if (pl->pl_prop == ZPROP_INVAL &&
12729 zfs_prop_user(pl->pl_user_prop)) {
12730 srctype = ZPROP_SRC_LOCAL;
12731
12732 if (zpool_get_userprop(zhp, pl->pl_user_prop,
12733 value, sizeof (value), &srctype) != 0)
12734 continue;
12735
12736 err = zprop_collect_property(
12737 zpool_get_name(zhp), cbp, pl->pl_user_prop,
12738 value, srctype, NULL, NULL, props);
12739 } else if (pl->pl_prop == ZPROP_INVAL &&
12740 (zpool_prop_feature(pl->pl_user_prop) ||
12741 zpool_prop_unsupported(pl->pl_user_prop))) {
12742 srctype = ZPROP_SRC_LOCAL;
12743
12744 if (zpool_prop_get_feature(zhp,
12745 pl->pl_user_prop, value,
12746 sizeof (value)) == 0) {
12747 err = zprop_collect_property(
12748 zpool_get_name(zhp), cbp,
12749 pl->pl_user_prop, value, srctype,
12750 NULL, NULL, props);
12751 }
12752 } else {
12753 if (zpool_get_prop(zhp, pl->pl_prop, value,
12754 sizeof (value), &srctype,
12755 cbp->cb_literal) != 0)
12756 continue;
12757
12758 err = zprop_collect_property(
12759 zpool_get_name(zhp), cbp,
12760 zpool_prop_to_name(pl->pl_prop),
12761 value, srctype, NULL, NULL, props);
12762 }
12763 if (err != 0)
12764 return (err);
12765 }
12766
12767 if (cbp->cb_json) {
12768 if (!nvlist_empty(props)) {
12769 item = fnvlist_alloc();
12770 fill_pool_info(item, zhp, B_TRUE,
12771 cbp->cb_json_as_int);
12772 fnvlist_add_nvlist(item, "properties", props);
12773 if (cbp->cb_json_pool_key_guid) {
12774 char buf[256];
12775 uint64_t guid = fnvlist_lookup_uint64(
12776 zpool_get_config(zhp, NULL),
12777 ZPOOL_CONFIG_POOL_GUID);
12778 (void) snprintf(buf, 256, "%llu",
12779 (u_longlong_t)guid);
12780 fnvlist_add_nvlist(d, buf, item);
12781 } else {
12782 const char *name = zpool_get_name(zhp);
12783 fnvlist_add_nvlist(d, name, item);
12784 }
12785 fnvlist_add_nvlist(cbp->cb_jsobj, "pools", d);
12786 fnvlist_free(item);
12787 }
12788 fnvlist_free(props);
12789 }
12790 }
12791
12792 return (0);
12793 }
12794
12795 /*
12796 * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
12797 *
12798 * -H Scripted mode. Don't display headers, and separate properties
12799 * by a single tab.
12800 * -o List of columns to display. Defaults to
12801 * "name,property,value,source".
12802 * -p Display values in parsable (exact) format.
12803 * -j Display output in JSON format.
12804 * --json-int Display numbers as integers instead of strings.
12805 * --json-pool-key-guid Set pool GUID as key for pool objects.
12806 *
12807 * Get properties of pools in the system. Output space statistics
12808 * for each one as well as other attributes.
12809 */
12810 int
zpool_do_get(int argc,char ** argv)12811 zpool_do_get(int argc, char **argv)
12812 {
12813 zprop_get_cbdata_t cb = { 0 };
12814 zprop_list_t fake_name = { 0 };
12815 int ret;
12816 int c, i;
12817 char *propstr = NULL;
12818 char *vdev = NULL;
12819 nvlist_t *data = NULL;
12820
12821 cb.cb_first = B_TRUE;
12822
12823 /*
12824 * Set up default columns and sources.
12825 */
12826 cb.cb_sources = ZPROP_SRC_ALL;
12827 cb.cb_columns[0] = GET_COL_NAME;
12828 cb.cb_columns[1] = GET_COL_PROPERTY;
12829 cb.cb_columns[2] = GET_COL_VALUE;
12830 cb.cb_columns[3] = GET_COL_SOURCE;
12831 cb.cb_type = ZFS_TYPE_POOL;
12832 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
12833 current_prop_type = cb.cb_type;
12834
12835 struct option long_options[] = {
12836 {"json", no_argument, NULL, 'j'},
12837 {"json-int", no_argument, NULL, ZPOOL_OPTION_JSON_NUMS_AS_INT},
12838 {"json-pool-key-guid", no_argument, NULL,
12839 ZPOOL_OPTION_POOL_KEY_GUID},
12840 {0, 0, 0, 0}
12841 };
12842
12843 /* check options */
12844 while ((c = getopt_long(argc, argv, ":jHpo:", long_options,
12845 NULL)) != -1) {
12846 switch (c) {
12847 case 'p':
12848 cb.cb_literal = B_TRUE;
12849 break;
12850 case 'H':
12851 cb.cb_scripted = B_TRUE;
12852 break;
12853 case 'j':
12854 cb.cb_json = B_TRUE;
12855 cb.cb_jsobj = zpool_json_schema(0, 1);
12856 data = fnvlist_alloc();
12857 break;
12858 case ZPOOL_OPTION_POOL_KEY_GUID:
12859 cb.cb_json_pool_key_guid = B_TRUE;
12860 break;
12861 case ZPOOL_OPTION_JSON_NUMS_AS_INT:
12862 cb.cb_json_as_int = B_TRUE;
12863 cb.cb_literal = B_TRUE;
12864 break;
12865 case 'o':
12866 memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
12867 i = 0;
12868
12869 for (char *tok; (tok = strsep(&optarg, ",")); ) {
12870 static const char *const col_opts[] =
12871 { "name", "property", "value", "source",
12872 "all" };
12873 static const zfs_get_column_t col_cols[] =
12874 { GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
12875 GET_COL_SOURCE };
12876
12877 if (i == ZFS_GET_NCOLS - 1) {
12878 (void) fprintf(stderr, gettext("too "
12879 "many fields given to -o "
12880 "option\n"));
12881 usage(B_FALSE);
12882 }
12883
12884 for (c = 0; c < ARRAY_SIZE(col_opts); ++c)
12885 if (strcmp(tok, col_opts[c]) == 0)
12886 goto found;
12887
12888 (void) fprintf(stderr,
12889 gettext("invalid column name '%s'\n"), tok);
12890 usage(B_FALSE);
12891
12892 found:
12893 if (c >= 4) {
12894 if (i > 0) {
12895 (void) fprintf(stderr,
12896 gettext("\"all\" conflicts "
12897 "with specific fields "
12898 "given to -o option\n"));
12899 usage(B_FALSE);
12900 }
12901
12902 memcpy(cb.cb_columns, col_cols,
12903 sizeof (col_cols));
12904 i = ZFS_GET_NCOLS - 1;
12905 } else
12906 cb.cb_columns[i++] = col_cols[c];
12907 }
12908 break;
12909 case '?':
12910 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
12911 optopt);
12912 usage(B_FALSE);
12913 }
12914 }
12915
12916 argc -= optind;
12917 argv += optind;
12918
12919 if (!cb.cb_json && cb.cb_json_as_int) {
12920 (void) fprintf(stderr, gettext("'--json-int' only works with"
12921 " '-j' option\n"));
12922 usage(B_FALSE);
12923 }
12924
12925 if (!cb.cb_json && cb.cb_json_pool_key_guid) {
12926 (void) fprintf(stderr, gettext("'json-pool-key-guid' only"
12927 " works with '-j' option\n"));
12928 usage(B_FALSE);
12929 }
12930
12931 if (argc < 1) {
12932 (void) fprintf(stderr, gettext("missing property "
12933 "argument\n"));
12934 usage(B_FALSE);
12935 }
12936
12937 /* Properties list is needed later by zprop_get_list() */
12938 propstr = argv[0];
12939
12940 argc--;
12941 argv++;
12942
12943 if (argc == 0) {
12944 /* No args, so just print the defaults. */
12945 } else if (are_all_pools(argc, argv)) {
12946 /* All the args are pool names */
12947 } else if (are_all_pools(1, argv)) {
12948 /* The first arg is a pool name */
12949 if ((argc == 2 && strcmp(argv[1], "all-vdevs") == 0) ||
12950 (argc == 2 && strcmp(argv[1], "root") == 0) ||
12951 are_vdevs_in_pool(argc - 1, argv + 1, argv[0],
12952 &cb.cb_vdevs)) {
12953
12954 if (strcmp(argv[1], "root") == 0)
12955 vdev = strdup("root-0");
12956
12957 /* ... and the rest are vdev names */
12958 if (vdev == NULL)
12959 cb.cb_vdevs.cb_names = argv + 1;
12960 else
12961 cb.cb_vdevs.cb_names = &vdev;
12962
12963 cb.cb_vdevs.cb_names_count = argc - 1;
12964 cb.cb_type = ZFS_TYPE_VDEV;
12965 argc = 1; /* One pool to process */
12966 } else {
12967 if (cb.cb_json) {
12968 nvlist_free(cb.cb_jsobj);
12969 nvlist_free(data);
12970 }
12971 fprintf(stderr, gettext("Expected a list of vdevs in"
12972 " \"%s\", but got:\n"), argv[0]);
12973 error_list_unresolved_vdevs(argc - 1, argv + 1,
12974 argv[0], &cb.cb_vdevs);
12975 fprintf(stderr, "\n");
12976 usage(B_FALSE);
12977 }
12978 } else {
12979 if (cb.cb_json) {
12980 nvlist_free(cb.cb_jsobj);
12981 nvlist_free(data);
12982 }
12983 /*
12984 * The first arg isn't the name of a valid pool.
12985 */
12986 fprintf(stderr, gettext("Cannot get properties of %s: "
12987 "no such pool available.\n"), argv[0]);
12988 return (1);
12989 }
12990
12991 if (zprop_get_list(g_zfs, propstr, &cb.cb_proplist,
12992 cb.cb_type) != 0) {
12993 /* Use correct list of valid properties (pool or vdev) */
12994 current_prop_type = cb.cb_type;
12995 usage(B_FALSE);
12996 }
12997
12998 if (cb.cb_proplist != NULL) {
12999 fake_name.pl_prop = ZPOOL_PROP_NAME;
13000 fake_name.pl_width = strlen(gettext("NAME"));
13001 fake_name.pl_next = cb.cb_proplist;
13002 cb.cb_proplist = &fake_name;
13003 }
13004
13005 if (cb.cb_json) {
13006 if (cb.cb_type == ZFS_TYPE_VDEV)
13007 fnvlist_add_nvlist(cb.cb_jsobj, "vdevs", data);
13008 else
13009 fnvlist_add_nvlist(cb.cb_jsobj, "pools", data);
13010 fnvlist_free(data);
13011 }
13012
13013 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist, cb.cb_type,
13014 cb.cb_literal, get_callback, &cb);
13015
13016 if (ret == 0 && cb.cb_json)
13017 zcmd_print_json(cb.cb_jsobj);
13018 else if (ret != 0 && cb.cb_json)
13019 nvlist_free(cb.cb_jsobj);
13020
13021 if (cb.cb_proplist == &fake_name)
13022 zprop_free_list(fake_name.pl_next);
13023 else
13024 zprop_free_list(cb.cb_proplist);
13025
13026 if (vdev != NULL)
13027 free(vdev);
13028
13029 return (ret);
13030 }
13031
13032 typedef struct set_cbdata {
13033 char *cb_propname;
13034 char *cb_value;
13035 zfs_type_t cb_type;
13036 vdev_cbdata_t cb_vdevs;
13037 boolean_t cb_any_successful;
13038 } set_cbdata_t;
13039
13040 static int
set_pool_callback(zpool_handle_t * zhp,set_cbdata_t * cb)13041 set_pool_callback(zpool_handle_t *zhp, set_cbdata_t *cb)
13042 {
13043 int error;
13044
13045 /* Check if we have out-of-bounds features */
13046 if (strcmp(cb->cb_propname, ZPOOL_CONFIG_COMPATIBILITY) == 0) {
13047 boolean_t features[SPA_FEATURES];
13048 if (zpool_do_load_compat(cb->cb_value, features) !=
13049 ZPOOL_COMPATIBILITY_OK)
13050 return (-1);
13051
13052 nvlist_t *enabled = zpool_get_features(zhp);
13053 spa_feature_t i;
13054 for (i = 0; i < SPA_FEATURES; i++) {
13055 const char *fguid = spa_feature_table[i].fi_guid;
13056 if (nvlist_exists(enabled, fguid) && !features[i])
13057 break;
13058 }
13059 if (i < SPA_FEATURES)
13060 (void) fprintf(stderr, gettext("Warning: one or "
13061 "more features already enabled on pool '%s'\n"
13062 "are not present in this compatibility set.\n"),
13063 zpool_get_name(zhp));
13064 }
13065
13066 /* if we're setting a feature, check it's in compatibility set */
13067 if (zpool_prop_feature(cb->cb_propname) &&
13068 strcmp(cb->cb_value, ZFS_FEATURE_ENABLED) == 0) {
13069 char *fname = strchr(cb->cb_propname, '@') + 1;
13070 spa_feature_t f;
13071
13072 if (zfeature_lookup_name(fname, &f) == 0) {
13073 char compat[ZFS_MAXPROPLEN];
13074 if (zpool_get_prop(zhp, ZPOOL_PROP_COMPATIBILITY,
13075 compat, ZFS_MAXPROPLEN, NULL, B_FALSE) != 0)
13076 compat[0] = '\0';
13077
13078 boolean_t features[SPA_FEATURES];
13079 if (zpool_do_load_compat(compat, features) !=
13080 ZPOOL_COMPATIBILITY_OK) {
13081 (void) fprintf(stderr, gettext("Error: "
13082 "cannot enable feature '%s' on pool '%s'\n"
13083 "because the pool's 'compatibility' "
13084 "property cannot be parsed.\n"),
13085 fname, zpool_get_name(zhp));
13086 return (-1);
13087 }
13088
13089 if (!features[f]) {
13090 (void) fprintf(stderr, gettext("Error: "
13091 "cannot enable feature '%s' on pool '%s'\n"
13092 "as it is not specified in this pool's "
13093 "current compatibility set.\n"
13094 "Consider setting 'compatibility' to a "
13095 "less restrictive set, or to 'off'.\n"),
13096 fname, zpool_get_name(zhp));
13097 return (-1);
13098 }
13099 }
13100 }
13101
13102 error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
13103
13104 return (error);
13105 }
13106
13107 static int
set_callback(zpool_handle_t * zhp,void * data)13108 set_callback(zpool_handle_t *zhp, void *data)
13109 {
13110 int error;
13111 set_cbdata_t *cb = (set_cbdata_t *)data;
13112
13113 if (cb->cb_type == ZFS_TYPE_VDEV) {
13114 error = zpool_set_vdev_prop(zhp, *cb->cb_vdevs.cb_names,
13115 cb->cb_propname, cb->cb_value);
13116 } else {
13117 assert(cb->cb_type == ZFS_TYPE_POOL);
13118 error = set_pool_callback(zhp, cb);
13119 }
13120
13121 cb->cb_any_successful = !error;
13122 return (error);
13123 }
13124
13125 int
zpool_do_set(int argc,char ** argv)13126 zpool_do_set(int argc, char **argv)
13127 {
13128 set_cbdata_t cb = { 0 };
13129 int error;
13130 char *vdev = NULL;
13131
13132 current_prop_type = ZFS_TYPE_POOL;
13133 if (argc > 1 && argv[1][0] == '-') {
13134 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
13135 argv[1][1]);
13136 usage(B_FALSE);
13137 }
13138
13139 if (argc < 2) {
13140 (void) fprintf(stderr, gettext("missing property=value "
13141 "argument\n"));
13142 usage(B_FALSE);
13143 }
13144
13145 if (argc < 3) {
13146 (void) fprintf(stderr, gettext("missing pool name\n"));
13147 usage(B_FALSE);
13148 }
13149
13150 if (argc > 4) {
13151 (void) fprintf(stderr, gettext("too many pool names\n"));
13152 usage(B_FALSE);
13153 }
13154
13155 cb.cb_propname = argv[1];
13156 cb.cb_type = ZFS_TYPE_POOL;
13157 cb.cb_vdevs.cb_name_flags |= VDEV_NAME_TYPE_ID;
13158 cb.cb_value = strchr(cb.cb_propname, '=');
13159 if (cb.cb_value == NULL) {
13160 (void) fprintf(stderr, gettext("missing value in "
13161 "property=value argument\n"));
13162 usage(B_FALSE);
13163 }
13164
13165 *(cb.cb_value) = '\0';
13166 cb.cb_value++;
13167 argc -= 2;
13168 argv += 2;
13169
13170 /* argv[0] is pool name */
13171 if (!is_pool(argv[0])) {
13172 (void) fprintf(stderr,
13173 gettext("cannot open '%s': is not a pool\n"), argv[0]);
13174 return (EINVAL);
13175 }
13176
13177 /* argv[1], when supplied, is vdev name */
13178 if (argc == 2) {
13179
13180 if (strcmp(argv[1], "root") == 0)
13181 vdev = strdup("root-0");
13182 else
13183 vdev = strdup(argv[1]);
13184
13185 if (!are_vdevs_in_pool(1, &vdev, argv[0], &cb.cb_vdevs)) {
13186 (void) fprintf(stderr, gettext(
13187 "cannot find '%s' in '%s': device not in pool\n"),
13188 vdev, argv[0]);
13189 free(vdev);
13190 return (EINVAL);
13191 }
13192 cb.cb_vdevs.cb_names = &vdev;
13193 cb.cb_vdevs.cb_names_count = 1;
13194 cb.cb_type = ZFS_TYPE_VDEV;
13195 }
13196
13197 error = for_each_pool(1, argv, B_TRUE, NULL, ZFS_TYPE_POOL,
13198 B_FALSE, set_callback, &cb);
13199
13200 if (vdev != NULL)
13201 free(vdev);
13202
13203 return (error);
13204 }
13205
13206 /* Add up the total number of bytes left to initialize/trim across all vdevs */
13207 static uint64_t
vdev_activity_remaining(nvlist_t * nv,zpool_wait_activity_t activity)13208 vdev_activity_remaining(nvlist_t *nv, zpool_wait_activity_t activity)
13209 {
13210 uint64_t bytes_remaining;
13211 nvlist_t **child;
13212 uint_t c, children;
13213 vdev_stat_t *vs;
13214
13215 assert(activity == ZPOOL_WAIT_INITIALIZE ||
13216 activity == ZPOOL_WAIT_TRIM);
13217
13218 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
13219 (uint64_t **)&vs, &c) == 0);
13220
13221 if (activity == ZPOOL_WAIT_INITIALIZE &&
13222 vs->vs_initialize_state == VDEV_INITIALIZE_ACTIVE)
13223 bytes_remaining = vs->vs_initialize_bytes_est -
13224 vs->vs_initialize_bytes_done;
13225 else if (activity == ZPOOL_WAIT_TRIM &&
13226 vs->vs_trim_state == VDEV_TRIM_ACTIVE)
13227 bytes_remaining = vs->vs_trim_bytes_est -
13228 vs->vs_trim_bytes_done;
13229 else
13230 bytes_remaining = 0;
13231
13232 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13233 &child, &children) != 0)
13234 children = 0;
13235
13236 for (c = 0; c < children; c++)
13237 bytes_remaining += vdev_activity_remaining(child[c], activity);
13238
13239 return (bytes_remaining);
13240 }
13241
13242 /* Add up the total number of bytes left to rebuild across top-level vdevs */
13243 static uint64_t
vdev_activity_top_remaining(nvlist_t * nv)13244 vdev_activity_top_remaining(nvlist_t *nv)
13245 {
13246 uint64_t bytes_remaining = 0;
13247 nvlist_t **child;
13248 uint_t children;
13249 int error;
13250
13251 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13252 &child, &children) != 0)
13253 children = 0;
13254
13255 for (uint_t c = 0; c < children; c++) {
13256 vdev_rebuild_stat_t *vrs;
13257 uint_t i;
13258
13259 error = nvlist_lookup_uint64_array(child[c],
13260 ZPOOL_CONFIG_REBUILD_STATS, (uint64_t **)&vrs, &i);
13261 if (error == 0) {
13262 if (vrs->vrs_state == VDEV_REBUILD_ACTIVE) {
13263 bytes_remaining += (vrs->vrs_bytes_est -
13264 vrs->vrs_bytes_rebuilt);
13265 }
13266 }
13267 }
13268
13269 return (bytes_remaining);
13270 }
13271
13272 /* Whether any vdevs are 'spare' or 'replacing' vdevs */
13273 static boolean_t
vdev_any_spare_replacing(nvlist_t * nv)13274 vdev_any_spare_replacing(nvlist_t *nv)
13275 {
13276 nvlist_t **child;
13277 uint_t c, children;
13278 const char *vdev_type;
13279
13280 (void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &vdev_type);
13281
13282 if (strcmp(vdev_type, VDEV_TYPE_REPLACING) == 0 ||
13283 strcmp(vdev_type, VDEV_TYPE_SPARE) == 0 ||
13284 strcmp(vdev_type, VDEV_TYPE_DRAID_SPARE) == 0) {
13285 return (B_TRUE);
13286 }
13287
13288 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
13289 &child, &children) != 0)
13290 children = 0;
13291
13292 for (c = 0; c < children; c++) {
13293 if (vdev_any_spare_replacing(child[c]))
13294 return (B_TRUE);
13295 }
13296
13297 return (B_FALSE);
13298 }
13299
13300 typedef struct wait_data {
13301 char *wd_poolname;
13302 boolean_t wd_scripted;
13303 boolean_t wd_exact;
13304 boolean_t wd_headers_once;
13305 boolean_t wd_should_exit;
13306 /* Which activities to wait for */
13307 boolean_t wd_enabled[ZPOOL_WAIT_NUM_ACTIVITIES];
13308 float wd_interval;
13309 pthread_cond_t wd_cv;
13310 pthread_mutex_t wd_mutex;
13311 } wait_data_t;
13312
13313 /*
13314 * Print to stdout a single line, containing one column for each activity that
13315 * we are waiting for specifying how many bytes of work are left for that
13316 * activity.
13317 */
13318 static void
print_wait_status_row(wait_data_t * wd,zpool_handle_t * zhp,int row)13319 print_wait_status_row(wait_data_t *wd, zpool_handle_t *zhp, int row)
13320 {
13321 nvlist_t *config, *nvroot;
13322 uint_t c;
13323 int i;
13324 pool_checkpoint_stat_t *pcs = NULL;
13325 pool_scan_stat_t *pss = NULL;
13326 pool_removal_stat_t *prs = NULL;
13327 pool_raidz_expand_stat_t *pres = NULL;
13328 const char *const headers[] = {"DISCARD", "FREE", "INITIALIZE",
13329 "REPLACE", "REMOVE", "RESILVER", "SCRUB", "TRIM", "RAIDZ_EXPAND"};
13330 int col_widths[ZPOOL_WAIT_NUM_ACTIVITIES];
13331
13332 /* Calculate the width of each column */
13333 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13334 /*
13335 * Make sure we have enough space in the col for pretty-printed
13336 * numbers and for the column header, and then leave a couple
13337 * spaces between cols for readability.
13338 */
13339 col_widths[i] = MAX(strlen(headers[i]), 6) + 2;
13340 }
13341
13342 if (timestamp_fmt != NODATE)
13343 print_timestamp(timestamp_fmt);
13344
13345 /* Print header if appropriate */
13346 int term_height = terminal_height();
13347 boolean_t reprint_header = (!wd->wd_headers_once && term_height > 0 &&
13348 row % (term_height-1) == 0);
13349 if (!wd->wd_scripted && (row == 0 || reprint_header)) {
13350 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13351 if (wd->wd_enabled[i])
13352 (void) printf("%*s", col_widths[i], headers[i]);
13353 }
13354 (void) fputc('\n', stdout);
13355 }
13356
13357 /* Bytes of work remaining in each activity */
13358 int64_t bytes_rem[ZPOOL_WAIT_NUM_ACTIVITIES] = {0};
13359
13360 bytes_rem[ZPOOL_WAIT_FREE] =
13361 zpool_get_prop_int(zhp, ZPOOL_PROP_FREEING, NULL);
13362
13363 config = zpool_get_config(zhp, NULL);
13364 nvroot = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
13365
13366 (void) nvlist_lookup_uint64_array(nvroot,
13367 ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t **)&pcs, &c);
13368 if (pcs != NULL && pcs->pcs_state == CS_CHECKPOINT_DISCARDING)
13369 bytes_rem[ZPOOL_WAIT_CKPT_DISCARD] = pcs->pcs_space;
13370
13371 (void) nvlist_lookup_uint64_array(nvroot,
13372 ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t **)&prs, &c);
13373 if (prs != NULL && prs->prs_state == DSS_SCANNING)
13374 bytes_rem[ZPOOL_WAIT_REMOVE] = prs->prs_to_copy -
13375 prs->prs_copied;
13376
13377 (void) nvlist_lookup_uint64_array(nvroot,
13378 ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&pss, &c);
13379 if (pss != NULL && pss->pss_state == DSS_SCANNING &&
13380 pss->pss_pass_scrub_pause == 0) {
13381 int64_t rem = pss->pss_to_examine - pss->pss_issued;
13382 if (pss->pss_func == POOL_SCAN_SCRUB)
13383 bytes_rem[ZPOOL_WAIT_SCRUB] = rem;
13384 else
13385 bytes_rem[ZPOOL_WAIT_RESILVER] = rem;
13386 } else if (check_rebuilding(nvroot, NULL)) {
13387 bytes_rem[ZPOOL_WAIT_RESILVER] =
13388 vdev_activity_top_remaining(nvroot);
13389 }
13390
13391 (void) nvlist_lookup_uint64_array(nvroot,
13392 ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t **)&pres, &c);
13393 if (pres != NULL && pres->pres_state == DSS_SCANNING) {
13394 int64_t rem = pres->pres_to_reflow - pres->pres_reflowed;
13395 bytes_rem[ZPOOL_WAIT_RAIDZ_EXPAND] = rem;
13396 }
13397
13398 bytes_rem[ZPOOL_WAIT_INITIALIZE] =
13399 vdev_activity_remaining(nvroot, ZPOOL_WAIT_INITIALIZE);
13400 bytes_rem[ZPOOL_WAIT_TRIM] =
13401 vdev_activity_remaining(nvroot, ZPOOL_WAIT_TRIM);
13402
13403 /*
13404 * A replace finishes after resilvering finishes, so the amount of work
13405 * left for a replace is the same as for resilvering.
13406 *
13407 * It isn't quite correct to say that if we have any 'spare' or
13408 * 'replacing' vdevs and a resilver is happening, then a replace is in
13409 * progress, like we do here. When a hot spare is used, the faulted vdev
13410 * is not removed after the hot spare is resilvered, so parent 'spare'
13411 * vdev is not removed either. So we could have a 'spare' vdev, but be
13412 * resilvering for a different reason. However, we use it as a heuristic
13413 * because we don't have access to the DTLs, which could tell us whether
13414 * or not we have really finished resilvering a hot spare.
13415 */
13416 if (vdev_any_spare_replacing(nvroot))
13417 bytes_rem[ZPOOL_WAIT_REPLACE] = bytes_rem[ZPOOL_WAIT_RESILVER];
13418
13419 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13420 char buf[64];
13421 if (!wd->wd_enabled[i])
13422 continue;
13423
13424 if (wd->wd_exact) {
13425 (void) snprintf(buf, sizeof (buf), "%" PRIi64,
13426 bytes_rem[i]);
13427 } else {
13428 zfs_nicenum(bytes_rem[i], buf, sizeof (buf));
13429 }
13430
13431 if (wd->wd_scripted)
13432 (void) printf(i == 0 ? "%s" : "\t%s", buf);
13433 else
13434 (void) printf(" %*s", col_widths[i] - 1, buf);
13435 }
13436 (void) printf("\n");
13437 (void) fflush(stdout);
13438 }
13439
13440 static void *
wait_status_thread(void * arg)13441 wait_status_thread(void *arg)
13442 {
13443 wait_data_t *wd = (wait_data_t *)arg;
13444 zpool_handle_t *zhp;
13445
13446 if ((zhp = zpool_open(g_zfs, wd->wd_poolname)) == NULL)
13447 return (void *)(1);
13448
13449 for (int row = 0; ; row++) {
13450 boolean_t missing;
13451 struct timespec timeout;
13452 int ret = 0;
13453 (void) clock_gettime(CLOCK_REALTIME, &timeout);
13454
13455 if (zpool_refresh_stats(zhp, &missing) != 0 || missing ||
13456 zpool_props_refresh(zhp) != 0) {
13457 zpool_close(zhp);
13458 return (void *)(uintptr_t)(missing ? 0 : 1);
13459 }
13460
13461 print_wait_status_row(wd, zhp, row);
13462
13463 timeout.tv_sec += floor(wd->wd_interval);
13464 long nanos = timeout.tv_nsec +
13465 (wd->wd_interval - floor(wd->wd_interval)) * NANOSEC;
13466 if (nanos >= NANOSEC) {
13467 timeout.tv_sec++;
13468 timeout.tv_nsec = nanos - NANOSEC;
13469 } else {
13470 timeout.tv_nsec = nanos;
13471 }
13472 (void) pthread_mutex_lock(&wd->wd_mutex);
13473 if (!wd->wd_should_exit)
13474 ret = pthread_cond_timedwait(&wd->wd_cv, &wd->wd_mutex,
13475 &timeout);
13476 (void) pthread_mutex_unlock(&wd->wd_mutex);
13477 if (ret == 0) {
13478 break; /* signaled by main thread */
13479 } else if (ret != ETIMEDOUT) {
13480 (void) fprintf(stderr, gettext("pthread_cond_timedwait "
13481 "failed: %s\n"), strerror(ret));
13482 zpool_close(zhp);
13483 return (void *)(uintptr_t)(1);
13484 }
13485 }
13486
13487 zpool_close(zhp);
13488 return (void *)(0);
13489 }
13490
13491 int
zpool_do_wait(int argc,char ** argv)13492 zpool_do_wait(int argc, char **argv)
13493 {
13494 boolean_t verbose = B_FALSE;
13495 int c, i;
13496 unsigned long count;
13497 pthread_t status_thr;
13498 int error = 0;
13499 zpool_handle_t *zhp;
13500
13501 wait_data_t wd;
13502 wd.wd_scripted = B_FALSE;
13503 wd.wd_exact = B_FALSE;
13504 wd.wd_headers_once = B_FALSE;
13505 wd.wd_should_exit = B_FALSE;
13506
13507 (void) pthread_mutex_init(&wd.wd_mutex, NULL);
13508 (void) pthread_cond_init(&wd.wd_cv, NULL);
13509
13510 /* By default, wait for all types of activity. */
13511 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++)
13512 wd.wd_enabled[i] = B_TRUE;
13513
13514 while ((c = getopt(argc, argv, "HpT:t:")) != -1) {
13515 switch (c) {
13516 case 'H':
13517 wd.wd_scripted = B_TRUE;
13518 break;
13519 case 'n':
13520 wd.wd_headers_once = B_TRUE;
13521 break;
13522 case 'p':
13523 wd.wd_exact = B_TRUE;
13524 break;
13525 case 'T':
13526 get_timestamp_arg(*optarg);
13527 break;
13528 case 't':
13529 /* Reset activities array */
13530 memset(&wd.wd_enabled, 0, sizeof (wd.wd_enabled));
13531
13532 for (char *tok; (tok = strsep(&optarg, ",")); ) {
13533 static const char *const col_opts[] = {
13534 "discard", "free", "initialize", "replace",
13535 "remove", "resilver", "scrub", "trim",
13536 "raidz_expand" };
13537
13538 for (i = 0; i < ARRAY_SIZE(col_opts); ++i)
13539 if (strcmp(tok, col_opts[i]) == 0) {
13540 wd.wd_enabled[i] = B_TRUE;
13541 goto found;
13542 }
13543
13544 (void) fprintf(stderr,
13545 gettext("invalid activity '%s'\n"), tok);
13546 usage(B_FALSE);
13547 found:;
13548 }
13549 break;
13550 case '?':
13551 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
13552 optopt);
13553 usage(B_FALSE);
13554 }
13555 }
13556
13557 argc -= optind;
13558 argv += optind;
13559
13560 get_interval_count(&argc, argv, &wd.wd_interval, &count);
13561 if (count != 0) {
13562 /* This subcmd only accepts an interval, not a count */
13563 (void) fprintf(stderr, gettext("too many arguments\n"));
13564 usage(B_FALSE);
13565 }
13566
13567 if (wd.wd_interval != 0)
13568 verbose = B_TRUE;
13569
13570 if (argc < 1) {
13571 (void) fprintf(stderr, gettext("missing 'pool' argument\n"));
13572 usage(B_FALSE);
13573 }
13574 if (argc > 1) {
13575 (void) fprintf(stderr, gettext("too many arguments\n"));
13576 usage(B_FALSE);
13577 }
13578
13579 wd.wd_poolname = argv[0];
13580
13581 if ((zhp = zpool_open(g_zfs, wd.wd_poolname)) == NULL)
13582 return (1);
13583
13584 if (verbose) {
13585 /*
13586 * We use a separate thread for printing status updates because
13587 * the main thread will call lzc_wait(), which blocks as long
13588 * as an activity is in progress, which can be a long time.
13589 */
13590 if (pthread_create(&status_thr, NULL, wait_status_thread, &wd)
13591 != 0) {
13592 (void) fprintf(stderr, gettext("failed to create status"
13593 "thread: %s\n"), strerror(errno));
13594 zpool_close(zhp);
13595 return (1);
13596 }
13597 }
13598
13599 /*
13600 * Loop over all activities that we are supposed to wait for until none
13601 * of them are in progress. Note that this means we can end up waiting
13602 * for more activities to complete than just those that were in progress
13603 * when we began waiting; if an activity we are interested in begins
13604 * while we are waiting for another activity, we will wait for both to
13605 * complete before exiting.
13606 */
13607 for (;;) {
13608 boolean_t missing = B_FALSE;
13609 boolean_t any_waited = B_FALSE;
13610
13611 for (i = 0; i < ZPOOL_WAIT_NUM_ACTIVITIES; i++) {
13612 boolean_t waited;
13613
13614 if (!wd.wd_enabled[i])
13615 continue;
13616
13617 error = zpool_wait_status(zhp, i, &missing, &waited);
13618 if (error != 0 || missing)
13619 break;
13620
13621 any_waited = (any_waited || waited);
13622 }
13623
13624 if (error != 0 || missing || !any_waited)
13625 break;
13626 }
13627
13628 zpool_close(zhp);
13629
13630 if (verbose) {
13631 uintptr_t status;
13632 (void) pthread_mutex_lock(&wd.wd_mutex);
13633 wd.wd_should_exit = B_TRUE;
13634 (void) pthread_cond_signal(&wd.wd_cv);
13635 (void) pthread_mutex_unlock(&wd.wd_mutex);
13636 (void) pthread_join(status_thr, (void *)&status);
13637 if (status != 0)
13638 error = status;
13639 }
13640
13641 (void) pthread_mutex_destroy(&wd.wd_mutex);
13642 (void) pthread_cond_destroy(&wd.wd_cv);
13643 return (error);
13644 }
13645
13646 /*
13647 * zpool ddtprune -d|-p <amount> <pool>
13648 *
13649 * -d <days> Prune entries <days> old and older
13650 * -p <percent> Prune <percent> amount of entries
13651 *
13652 * Prune single reference entries from DDT to satisfy the amount specified.
13653 */
13654 int
zpool_do_ddt_prune(int argc,char ** argv)13655 zpool_do_ddt_prune(int argc, char **argv)
13656 {
13657 zpool_ddt_prune_unit_t unit = ZPOOL_DDT_PRUNE_NONE;
13658 uint64_t amount = 0;
13659 zpool_handle_t *zhp;
13660 char *endptr;
13661 int c;
13662
13663 while ((c = getopt(argc, argv, "d:p:")) != -1) {
13664 switch (c) {
13665 case 'd':
13666 if (unit == ZPOOL_DDT_PRUNE_PERCENTAGE) {
13667 (void) fprintf(stderr, gettext("-d cannot be "
13668 "combined with -p option\n"));
13669 usage(B_FALSE);
13670 }
13671 errno = 0;
13672 amount = strtoull(optarg, &endptr, 0);
13673 if (errno != 0 || *endptr != '\0' || amount == 0) {
13674 (void) fprintf(stderr,
13675 gettext("invalid days value\n"));
13676 usage(B_FALSE);
13677 }
13678 amount *= 86400; /* convert days to seconds */
13679 unit = ZPOOL_DDT_PRUNE_AGE;
13680 break;
13681 case 'p':
13682 if (unit == ZPOOL_DDT_PRUNE_AGE) {
13683 (void) fprintf(stderr, gettext("-p cannot be "
13684 "combined with -d option\n"));
13685 usage(B_FALSE);
13686 }
13687 errno = 0;
13688 amount = strtoull(optarg, &endptr, 0);
13689 if (errno != 0 || *endptr != '\0' ||
13690 amount == 0 || amount > 100) {
13691 (void) fprintf(stderr,
13692 gettext("invalid percentage value\n"));
13693 usage(B_FALSE);
13694 }
13695 unit = ZPOOL_DDT_PRUNE_PERCENTAGE;
13696 break;
13697 case '?':
13698 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
13699 optopt);
13700 usage(B_FALSE);
13701 }
13702 }
13703 argc -= optind;
13704 argv += optind;
13705
13706 if (unit == ZPOOL_DDT_PRUNE_NONE) {
13707 (void) fprintf(stderr,
13708 gettext("missing amount option (-d|-p <value>)\n"));
13709 usage(B_FALSE);
13710 } else if (argc < 1) {
13711 (void) fprintf(stderr, gettext("missing pool argument\n"));
13712 usage(B_FALSE);
13713 } else if (argc > 1) {
13714 (void) fprintf(stderr, gettext("too many arguments\n"));
13715 usage(B_FALSE);
13716 }
13717 zhp = zpool_open(g_zfs, argv[0]);
13718 if (zhp == NULL)
13719 return (-1);
13720
13721 int error = zpool_ddt_prune(zhp, unit, amount);
13722
13723 zpool_close(zhp);
13724
13725 return (error);
13726 }
13727
13728 static int
find_command_idx(const char * command,int * idx)13729 find_command_idx(const char *command, int *idx)
13730 {
13731 for (int i = 0; i < NCOMMAND; ++i) {
13732 if (command_table[i].name == NULL)
13733 continue;
13734
13735 if (strcmp(command, command_table[i].name) == 0) {
13736 *idx = i;
13737 return (0);
13738 }
13739 }
13740 return (1);
13741 }
13742
13743 /*
13744 * Display version message
13745 */
13746 static int
zpool_do_version(int argc,char ** argv)13747 zpool_do_version(int argc, char **argv)
13748 {
13749 int c;
13750 nvlist_t *jsobj = NULL, *zfs_ver = NULL;
13751 boolean_t json = B_FALSE;
13752
13753 struct option long_options[] = {
13754 {"json", no_argument, NULL, 'j'},
13755 };
13756
13757 while ((c = getopt_long(argc, argv, "j", long_options, NULL)) != -1) {
13758 switch (c) {
13759 case 'j':
13760 json = B_TRUE;
13761 jsobj = zpool_json_schema(0, 1);
13762 break;
13763 case '?':
13764 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
13765 optopt);
13766 usage(B_FALSE);
13767 }
13768 }
13769
13770 argc -= optind;
13771 if (argc != 0) {
13772 (void) fprintf(stderr, "too many arguments\n");
13773 usage(B_FALSE);
13774 }
13775
13776 if (json) {
13777 zfs_ver = zfs_version_nvlist();
13778 if (zfs_ver) {
13779 fnvlist_add_nvlist(jsobj, "zfs_version", zfs_ver);
13780 zcmd_print_json(jsobj);
13781 fnvlist_free(zfs_ver);
13782 return (0);
13783 } else
13784 return (-1);
13785 } else
13786 return (zfs_version_print() != 0);
13787 }
13788
13789 /* Display documentation */
13790 static int
zpool_do_help(int argc,char ** argv)13791 zpool_do_help(int argc, char **argv)
13792 {
13793 char page[MAXNAMELEN];
13794 if (argc < 3 || strcmp(argv[2], "zpool") == 0)
13795 (void) strcpy(page, "zpool");
13796 else if (strcmp(argv[2], "concepts") == 0 ||
13797 strcmp(argv[2], "props") == 0)
13798 (void) snprintf(page, sizeof (page), "zpool%s", argv[2]);
13799 else
13800 (void) snprintf(page, sizeof (page), "zpool-%s", argv[2]);
13801
13802 (void) execlp("man", "man", page, NULL);
13803
13804 fprintf(stderr, "couldn't run man program: %s\n", strerror(errno));
13805 return (-1);
13806 }
13807
13808 /*
13809 * Do zpool_load_compat() and print error message on failure
13810 */
13811 static zpool_compat_status_t
zpool_do_load_compat(const char * compat,boolean_t * list)13812 zpool_do_load_compat(const char *compat, boolean_t *list)
13813 {
13814 char report[1024];
13815
13816 zpool_compat_status_t ret;
13817
13818 ret = zpool_load_compat(compat, list, report, 1024);
13819 switch (ret) {
13820
13821 case ZPOOL_COMPATIBILITY_OK:
13822 break;
13823
13824 case ZPOOL_COMPATIBILITY_NOFILES:
13825 case ZPOOL_COMPATIBILITY_BADFILE:
13826 case ZPOOL_COMPATIBILITY_BADTOKEN:
13827 (void) fprintf(stderr, "Error: %s\n", report);
13828 break;
13829
13830 case ZPOOL_COMPATIBILITY_WARNTOKEN:
13831 (void) fprintf(stderr, "Warning: %s\n", report);
13832 ret = ZPOOL_COMPATIBILITY_OK;
13833 break;
13834 }
13835 return (ret);
13836 }
13837
13838 int
main(int argc,char ** argv)13839 main(int argc, char **argv)
13840 {
13841 int ret = 0;
13842 int i = 0;
13843 char *cmdname;
13844 char **newargv;
13845
13846 (void) setlocale(LC_ALL, "");
13847 (void) setlocale(LC_NUMERIC, "C");
13848 (void) textdomain(TEXT_DOMAIN);
13849 srand(time(NULL));
13850
13851 opterr = 0;
13852
13853 /*
13854 * Make sure the user has specified some command.
13855 */
13856 if (argc < 2) {
13857 (void) fprintf(stderr, gettext("missing command\n"));
13858 usage(B_FALSE);
13859 }
13860
13861 cmdname = argv[1];
13862
13863 /*
13864 * Special case '-?'
13865 */
13866 if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
13867 usage(B_TRUE);
13868
13869 /*
13870 * Special case '-V|--version'
13871 */
13872 if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
13873 return (zfs_version_print() != 0);
13874
13875 /*
13876 * Special case 'help'
13877 */
13878 if (strcmp(cmdname, "help") == 0)
13879 return (zpool_do_help(argc, argv));
13880
13881 if ((g_zfs = libzfs_init()) == NULL) {
13882 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
13883 return (1);
13884 }
13885
13886 libzfs_print_on_error(g_zfs, B_TRUE);
13887
13888 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
13889
13890 /*
13891 * Many commands modify input strings for string parsing reasons.
13892 * We create a copy to protect the original argv.
13893 */
13894 newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
13895 for (i = 0; i < argc; i++)
13896 newargv[i] = strdup(argv[i]);
13897 newargv[argc] = NULL;
13898
13899 /*
13900 * Run the appropriate command.
13901 */
13902 if (find_command_idx(cmdname, &i) == 0) {
13903 current_command = &command_table[i];
13904 ret = command_table[i].func(argc - 1, newargv + 1);
13905 } else if (strchr(cmdname, '=')) {
13906 verify(find_command_idx("set", &i) == 0);
13907 current_command = &command_table[i];
13908 ret = command_table[i].func(argc, newargv);
13909 } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
13910 /*
13911 * 'freeze' is a vile debugging abomination, so we treat
13912 * it as such.
13913 */
13914 zfs_cmd_t zc = {"\0"};
13915
13916 (void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
13917 ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
13918 if (ret != 0) {
13919 (void) fprintf(stderr,
13920 gettext("failed to freeze pool: %d\n"), errno);
13921 ret = 1;
13922 }
13923
13924 log_history = 0;
13925 } else {
13926 (void) fprintf(stderr, gettext("unrecognized "
13927 "command '%s'\n"), cmdname);
13928 usage(B_FALSE);
13929 }
13930
13931 for (i = 0; i < argc; i++)
13932 free(newargv[i]);
13933 free(newargv);
13934
13935 if (ret == 0 && log_history)
13936 (void) zpool_log_history(g_zfs, history_str);
13937
13938 libzfs_fini(g_zfs);
13939
13940 /*
13941 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
13942 * for the purposes of running ::findleaks.
13943 */
13944 if (getenv("ZFS_ABORT") != NULL) {
13945 (void) printf("dumping core by request\n");
13946 abort();
13947 }
13948
13949 return (ret);
13950 }
13951