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