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