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