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