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