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