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