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