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