]> git.proxmox.com Git - mirror_zfs.git/blame - cmd/zpool/zpool_main.c
OpenZFS 8603 - rename zilog's "zl_writer_lock" to "zl_issuer_lock"
[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[,...]] "
428870ff 337 "[-T d|u] [pool] ... [interval [count]]\n"));
34dc7c2f 338 case HELP_OFFLINE:
4a283c7f 339 return (gettext("\toffline [-f] [-t] <pool> <device> ...\n"));
34dc7c2f
BB
340 case HELP_ONLINE:
341 return (gettext("\tonline <pool> <device> ...\n"));
342 case HELP_REPLACE:
628668a3
TF
343 return (gettext("\treplace [-f] [-o property=value] "
344 "<pool> <device> [new-device]\n"));
34dc7c2f
BB
345 case HELP_REMOVE:
346 return (gettext("\tremove <pool> <device> ...\n"));
1bd201e7 347 case HELP_REOPEN:
d3f2cd7e 348 return (gettext("\treopen [-n] <pool>\n"));
34dc7c2f 349 case HELP_SCRUB:
0ea05c64 350 return (gettext("\tscrub [-s | -p] <pool> ...\n"));
34dc7c2f 351 case HELP_STATUS:
d6418de0
TH
352 return (gettext("\tstatus [-c [script1,script2,...]] [-gLPvxD]"
353 "[-T d|u] [pool] ... [interval [count]]\n"));
34dc7c2f
BB
354 case HELP_UPGRADE:
355 return (gettext("\tupgrade\n"
356 "\tupgrade -v\n"
357 "\tupgrade [-V version] <-a | pool ...>\n"));
26685276 358 case HELP_EVENTS:
88f9c939 359 return (gettext("\tevents [-vHf [pool] | -c]\n"));
34dc7c2f 360 case HELP_GET:
2a8b84b7
AS
361 return (gettext("\tget [-Hp] [-o \"all\" | field[,...]] "
362 "<\"all\" | property[,...]> <pool> ...\n"));
34dc7c2f
BB
363 case HELP_SET:
364 return (gettext("\tset <property=value> <pool> \n"));
428870ff 365 case HELP_SPLIT:
b5256303 366 return (gettext("\tsplit [-gLnPl] [-R altroot] [-o mntopts]\n"
428870ff
BB
367 "\t [-o property=value] <pool> <newpool> "
368 "[<device> ...]\n"));
3541dc6d
GA
369 case HELP_REGUID:
370 return (gettext("\treguid <pool>\n"));
bec1067d
AP
371 case HELP_SYNC:
372 return (gettext("\tsync [pool] ...\n"));
34dc7c2f
BB
373 }
374
375 abort();
376 /* NOTREACHED */
377}
378
379
380/*
381 * Callback routine that will print out a pool property value.
382 */
383static int
384print_prop_cb(int prop, void *cb)
385{
386 FILE *fp = cb;
387
428870ff 388 (void) fprintf(fp, "\t%-15s ", zpool_prop_to_name(prop));
34dc7c2f
BB
389
390 if (zpool_prop_readonly(prop))
391 (void) fprintf(fp, " NO ");
392 else
428870ff 393 (void) fprintf(fp, " YES ");
34dc7c2f
BB
394
395 if (zpool_prop_values(prop) == NULL)
396 (void) fprintf(fp, "-\n");
397 else
398 (void) fprintf(fp, "%s\n", zpool_prop_values(prop));
399
400 return (ZPROP_CONT);
401}
402
403/*
404 * Display usage message. If we're inside a command, display only the usage for
405 * that command. Otherwise, iterate over the entire command table and display
406 * a complete usage message.
407 */
408void
409usage(boolean_t requested)
410{
411 FILE *fp = requested ? stdout : stderr;
412
413 if (current_command == NULL) {
414 int i;
415
416 (void) fprintf(fp, gettext("usage: zpool command args ...\n"));
417 (void) fprintf(fp,
418 gettext("where 'command' is one of the following:\n\n"));
419
420 for (i = 0; i < NCOMMAND; i++) {
421 if (command_table[i].name == NULL)
422 (void) fprintf(fp, "\n");
423 else
424 (void) fprintf(fp, "%s",
425 get_usage(command_table[i].usage));
426 }
427 } else {
428 (void) fprintf(fp, gettext("usage:\n"));
429 (void) fprintf(fp, "%s", get_usage(current_command->usage));
430 }
431
432 if (current_command != NULL &&
433 ((strcmp(current_command->name, "set") == 0) ||
434 (strcmp(current_command->name, "get") == 0) ||
435 (strcmp(current_command->name, "list") == 0))) {
436
437 (void) fprintf(fp,
438 gettext("\nthe following properties are supported:\n"));
439
428870ff 440 (void) fprintf(fp, "\n\t%-15s %s %s\n\n",
34dc7c2f
BB
441 "PROPERTY", "EDIT", "VALUES");
442
443 /* Iterate over all properties */
444 (void) zprop_iter(print_prop_cb, fp, B_FALSE, B_TRUE,
445 ZFS_TYPE_POOL);
9ae529ec
CS
446
447 (void) fprintf(fp, "\t%-15s ", "feature@...");
448 (void) fprintf(fp, "YES disabled | enabled | active\n");
449
450 (void) fprintf(fp, gettext("\nThe feature@ properties must be "
451 "appended with a feature name.\nSee zpool-features(5).\n"));
34dc7c2f
BB
452 }
453
454 /*
455 * See comments at end of main().
456 */
457 if (getenv("ZFS_ABORT") != NULL) {
458 (void) printf("dumping core by request\n");
459 abort();
460 }
461
462 exit(requested ? 0 : 2);
463}
464
465void
466print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
d2f3e292 467 boolean_t print_logs, int name_flags)
34dc7c2f
BB
468{
469 nvlist_t **child;
470 uint_t c, children;
471 char *vname;
472
473 if (name != NULL)
474 (void) printf("\t%*s%s\n", indent, "", name);
475
476 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
477 &child, &children) != 0)
478 return;
479
480 for (c = 0; c < children; c++) {
481 uint64_t is_log = B_FALSE;
482
483 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
484 &is_log);
485 if ((is_log && !print_logs) || (!is_log && print_logs))
486 continue;
487
d2f3e292 488 vname = zpool_vdev_name(g_zfs, zhp, child[c], name_flags);
34dc7c2f 489 print_vdev_tree(zhp, vname, child[c], indent + 2,
d2f3e292 490 B_FALSE, name_flags);
34dc7c2f
BB
491 free(vname);
492 }
493}
494
b9b24bb4
CS
495static boolean_t
496prop_list_contains_feature(nvlist_t *proplist)
497{
498 nvpair_t *nvp;
499 for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
500 nvp = nvlist_next_nvpair(proplist, nvp)) {
501 if (zpool_prop_feature(nvpair_name(nvp)))
502 return (B_TRUE);
503 }
504 return (B_FALSE);
505}
506
34dc7c2f
BB
507/*
508 * Add a property pair (name, string-value) into a property nvlist.
509 */
510static int
b128c09f
BB
511add_prop_list(const char *propname, char *propval, nvlist_t **props,
512 boolean_t poolprop)
34dc7c2f 513{
b128c09f
BB
514 zpool_prop_t prop = ZPROP_INVAL;
515 zfs_prop_t fprop;
34dc7c2f 516 nvlist_t *proplist;
b128c09f
BB
517 const char *normnm;
518 char *strval;
34dc7c2f
BB
519
520 if (*props == NULL &&
521 nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
522 (void) fprintf(stderr,
523 gettext("internal error: out of memory\n"));
524 return (1);
525 }
526
527 proplist = *props;
528
b128c09f 529 if (poolprop) {
b9b24bb4
CS
530 const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
531
9ae529ec
CS
532 if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL &&
533 !zpool_prop_feature(propname)) {
b128c09f
BB
534 (void) fprintf(stderr, gettext("property '%s' is "
535 "not a valid pool property\n"), propname);
536 return (2);
537 }
b9b24bb4
CS
538
539 /*
540 * feature@ properties and version should not be specified
541 * at the same time.
542 */
543 if ((prop == ZPROP_INVAL && zpool_prop_feature(propname) &&
544 nvlist_exists(proplist, vname)) ||
545 (prop == ZPOOL_PROP_VERSION &&
546 prop_list_contains_feature(proplist))) {
547 (void) fprintf(stderr, gettext("'feature@' and "
548 "'version' properties cannot be specified "
549 "together\n"));
550 return (2);
551 }
552
553
9ae529ec
CS
554 if (zpool_prop_feature(propname))
555 normnm = propname;
556 else
557 normnm = zpool_prop_to_name(prop);
b128c09f 558 } else {
9babb374
BB
559 if ((fprop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
560 normnm = zfs_prop_to_name(fprop);
561 } else {
562 normnm = propname;
b128c09f 563 }
34dc7c2f
BB
564 }
565
b128c09f
BB
566 if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
567 prop != ZPOOL_PROP_CACHEFILE) {
34dc7c2f
BB
568 (void) fprintf(stderr, gettext("property '%s' "
569 "specified multiple times\n"), propname);
570 return (2);
571 }
572
b128c09f 573 if (nvlist_add_string(proplist, normnm, propval) != 0) {
34dc7c2f
BB
574 (void) fprintf(stderr, gettext("internal "
575 "error: out of memory\n"));
576 return (1);
577 }
578
579 return (0);
580}
581
2f3ec900
RY
582/*
583 * Set a default property pair (name, string-value) in a property nvlist
584 */
585static int
586add_prop_list_default(const char *propname, char *propval, nvlist_t **props,
587 boolean_t poolprop)
588{
589 char *pval;
590
591 if (nvlist_lookup_string(*props, propname, &pval) == 0)
592 return (0);
593
594 return (add_prop_list(propname, propval, props, B_TRUE));
595}
596
34dc7c2f 597/*
a77f29f9 598 * zpool add [-fgLnP] [-o property=value] <pool> <vdev> ...
34dc7c2f
BB
599 *
600 * -f Force addition of devices, even if they appear in use
d2f3e292
RY
601 * -g Display guid for individual vdev name.
602 * -L Follow links when resolving vdev path name.
34dc7c2f
BB
603 * -n Do not add the devices, but display the resulting layout if
604 * they were to be added.
df831108 605 * -o Set property=value.
a77f29f9 606 * -P Display full path for vdev name.
34dc7c2f
BB
607 *
608 * Adds the given vdevs to 'pool'. As with create, the bulk of this work is
609 * handled by get_vdev_spec(), which constructs the nvlist needed to pass to
610 * libzfs.
611 */
612int
613zpool_do_add(int argc, char **argv)
614{
615 boolean_t force = B_FALSE;
616 boolean_t dryrun = B_FALSE;
d2f3e292 617 int name_flags = 0;
34dc7c2f
BB
618 int c;
619 nvlist_t *nvroot;
620 char *poolname;
621 int ret;
622 zpool_handle_t *zhp;
623 nvlist_t *config;
df831108
CP
624 nvlist_t *props = NULL;
625 char *propval;
34dc7c2f
BB
626
627 /* check options */
a77f29f9 628 while ((c = getopt(argc, argv, "fgLno:P")) != -1) {
34dc7c2f
BB
629 switch (c) {
630 case 'f':
631 force = B_TRUE;
632 break;
d2f3e292
RY
633 case 'g':
634 name_flags |= VDEV_NAME_GUID;
635 break;
636 case 'L':
637 name_flags |= VDEV_NAME_FOLLOW_LINKS;
638 break;
34dc7c2f
BB
639 case 'n':
640 dryrun = B_TRUE;
641 break;
df831108
CP
642 case 'o':
643 if ((propval = strchr(optarg, '=')) == NULL) {
644 (void) fprintf(stderr, gettext("missing "
645 "'=' for -o option\n"));
646 usage(B_FALSE);
647 }
648 *propval = '\0';
649 propval++;
650
651 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
652 (add_prop_list(optarg, propval, &props, B_TRUE)))
653 usage(B_FALSE);
654 break;
a77f29f9 655 case 'P':
d2f3e292
RY
656 name_flags |= VDEV_NAME_PATH;
657 break;
34dc7c2f
BB
658 case '?':
659 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
660 optopt);
661 usage(B_FALSE);
662 }
663 }
664
665 argc -= optind;
666 argv += optind;
667
668 /* get pool name and check number of arguments */
669 if (argc < 1) {
670 (void) fprintf(stderr, gettext("missing pool name argument\n"));
671 usage(B_FALSE);
672 }
673 if (argc < 2) {
674 (void) fprintf(stderr, gettext("missing vdev specification\n"));
675 usage(B_FALSE);
676 }
677
678 poolname = argv[0];
679
680 argc--;
681 argv++;
682
683 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
684 return (1);
685
686 if ((config = zpool_get_config(zhp, NULL)) == NULL) {
687 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
688 poolname);
689 zpool_close(zhp);
690 return (1);
691 }
692
dddef7d6 693 /* unless manually specified use "ashift" pool property (if set) */
694 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
695 int intval;
696 zprop_source_t src;
697 char strval[ZPOOL_MAXPROPLEN];
698
699 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
700 if (src != ZPROP_SRC_DEFAULT) {
701 (void) sprintf(strval, "%" PRId32, intval);
702 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
703 &props, B_TRUE) == 0);
704 }
705 }
706
34dc7c2f 707 /* pass off to get_vdev_spec for processing */
df831108 708 nvroot = make_root_vdev(zhp, props, force, !force, B_FALSE, dryrun,
b128c09f 709 argc, argv);
34dc7c2f
BB
710 if (nvroot == NULL) {
711 zpool_close(zhp);
712 return (1);
713 }
714
715 if (dryrun) {
716 nvlist_t *poolnvroot;
e02b533e
TC
717 nvlist_t **l2child;
718 uint_t l2children, c;
719 char *vname;
720 boolean_t hadcache = B_FALSE;
34dc7c2f
BB
721
722 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
723 &poolnvroot) == 0);
724
725 (void) printf(gettext("would update '%s' to the following "
726 "configuration:\n"), zpool_get_name(zhp));
727
728 /* print original main pool and new tree */
d2f3e292
RY
729 print_vdev_tree(zhp, poolname, poolnvroot, 0, B_FALSE,
730 name_flags);
731 print_vdev_tree(zhp, NULL, nvroot, 0, B_FALSE, name_flags);
34dc7c2f
BB
732
733 /* Do the same for the logs */
734 if (num_logs(poolnvroot) > 0) {
d2f3e292
RY
735 print_vdev_tree(zhp, "logs", poolnvroot, 0, B_TRUE,
736 name_flags);
737 print_vdev_tree(zhp, NULL, nvroot, 0, B_TRUE,
738 name_flags);
34dc7c2f 739 } else if (num_logs(nvroot) > 0) {
d2f3e292
RY
740 print_vdev_tree(zhp, "logs", nvroot, 0, B_TRUE,
741 name_flags);
34dc7c2f
BB
742 }
743
e02b533e
TC
744 /* Do the same for the caches */
745 if (nvlist_lookup_nvlist_array(poolnvroot, ZPOOL_CONFIG_L2CACHE,
746 &l2child, &l2children) == 0 && l2children) {
747 hadcache = B_TRUE;
748 (void) printf(gettext("\tcache\n"));
749 for (c = 0; c < l2children; c++) {
750 vname = zpool_vdev_name(g_zfs, NULL,
d2f3e292 751 l2child[c], name_flags);
e02b533e
TC
752 (void) printf("\t %s\n", vname);
753 free(vname);
754 }
755 }
756 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
757 &l2child, &l2children) == 0 && l2children) {
758 if (!hadcache)
759 (void) printf(gettext("\tcache\n"));
760 for (c = 0; c < l2children; c++) {
761 vname = zpool_vdev_name(g_zfs, NULL,
d2f3e292 762 l2child[c], name_flags);
e02b533e
TC
763 (void) printf("\t %s\n", vname);
764 free(vname);
765 }
766 }
767
34dc7c2f
BB
768 ret = 0;
769 } else {
770 ret = (zpool_add(zhp, nvroot) != 0);
771 }
772
df831108 773 nvlist_free(props);
34dc7c2f
BB
774 nvlist_free(nvroot);
775 zpool_close(zhp);
776
777 return (ret);
778}
779
780/*
428870ff 781 * zpool remove <pool> <vdev> ...
34dc7c2f 782 *
428870ff
BB
783 * Removes the given vdev from the pool. Currently, this supports removing
784 * spares, cache, and log devices from the pool.
34dc7c2f
BB
785 */
786int
787zpool_do_remove(int argc, char **argv)
788{
789 char *poolname;
790 int i, ret = 0;
884385a0 791 zpool_handle_t *zhp = NULL;
34dc7c2f
BB
792
793 argc--;
794 argv++;
795
796 /* get pool name and check number of arguments */
797 if (argc < 1) {
798 (void) fprintf(stderr, gettext("missing pool name argument\n"));
799 usage(B_FALSE);
800 }
801 if (argc < 2) {
802 (void) fprintf(stderr, gettext("missing device\n"));
803 usage(B_FALSE);
804 }
805
806 poolname = argv[0];
807
808 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
809 return (1);
810
811 for (i = 1; i < argc; i++) {
812 if (zpool_vdev_remove(zhp, argv[i]) != 0)
813 ret = 1;
814 }
884385a0 815 zpool_close(zhp);
34dc7c2f
BB
816
817 return (ret);
818}
819
131cc95c 820/*
dbb38f66
YP
821 * zpool labelclear [-f] <vdev>
822 *
823 * -f Force clearing the label for the vdevs which are members of
824 * the exported or foreign pools.
131cc95c
DK
825 *
826 * Verifies that the vdev is not active and zeros out the label information
827 * on the device.
828 */
829int
830zpool_do_labelclear(int argc, char **argv)
831{
dbb38f66
YP
832 char vdev[MAXPATHLEN];
833 char *name = NULL;
834 struct stat st;
131cc95c 835 int c, fd = -1, ret = 0;
dbb38f66 836 nvlist_t *config;
131cc95c
DK
837 pool_state_t state;
838 boolean_t inuse = B_FALSE;
839 boolean_t force = B_FALSE;
840
841 /* check options */
842 while ((c = getopt(argc, argv, "f")) != -1) {
843 switch (c) {
844 case 'f':
845 force = B_TRUE;
846 break;
847 default:
848 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
849 optopt);
850 usage(B_FALSE);
851 }
852 }
853
854 argc -= optind;
855 argv += optind;
856
857 /* get vdev name */
858 if (argc < 1) {
dbb38f66
YP
859 (void) fprintf(stderr, gettext("missing vdev name\n"));
860 usage(B_FALSE);
861 }
862 if (argc > 1) {
863 (void) fprintf(stderr, gettext("too many arguments\n"));
131cc95c
DK
864 usage(B_FALSE);
865 }
866
dbb38f66
YP
867 /*
868 * Check if we were given absolute path and use it as is.
869 * Otherwise if the provided vdev name doesn't point to a file,
870 * try prepending expected disk paths and partition numbers.
871 */
872 (void) strlcpy(vdev, argv[0], sizeof (vdev));
873 if (vdev[0] != '/' && stat(vdev, &st) != 0) {
874 int error;
875
876 error = zfs_resolve_shortname(argv[0], vdev, MAXPATHLEN);
877 if (error == 0 && zfs_dev_is_whole_disk(vdev)) {
878 if (zfs_append_partition(vdev, MAXPATHLEN) == -1)
879 error = ENOENT;
880 }
881
882 if (error || (stat(vdev, &st) != 0)) {
883 (void) fprintf(stderr, gettext(
884 "failed to find device %s, try specifying absolute "
885 "path instead\n"), argv[0]);
886 return (1);
887 }
131cc95c
DK
888 }
889
dbb38f66
YP
890 if ((fd = open(vdev, O_RDWR)) < 0) {
891 (void) fprintf(stderr, gettext("failed to open %s: %s\n"),
892 vdev, strerror(errno));
893 return (1);
894 }
131cc95c 895
a167aa7c
GDN
896 if (ioctl(fd, BLKFLSBUF) != 0)
897 (void) fprintf(stderr, gettext("failed to invalidate "
898 "cache for %s: %s\n"), vdev, strerror(errno));
899
dbb38f66 900 if (zpool_read_label(fd, &config, NULL) != 0 || config == NULL) {
131cc95c 901 (void) fprintf(stderr,
dbb38f66 902 gettext("failed to check state for %s\n"), vdev);
c721ba43
TH
903 ret = 1;
904 goto errout;
dbb38f66
YP
905 }
906 nvlist_free(config);
131cc95c 907
dbb38f66
YP
908 ret = zpool_in_use(g_zfs, fd, &state, &name, &inuse);
909 if (ret != 0) {
910 (void) fprintf(stderr,
911 gettext("failed to check state for %s\n"), vdev);
c721ba43
TH
912 ret = 1;
913 goto errout;
131cc95c
DK
914 }
915
dbb38f66
YP
916 if (!inuse)
917 goto wipe_label;
918
919 switch (state) {
920 default:
921 case POOL_STATE_ACTIVE:
922 case POOL_STATE_SPARE:
923 case POOL_STATE_L2CACHE:
924 (void) fprintf(stderr, gettext(
925 "%s is a member (%s) of pool \"%s\"\n"),
926 vdev, zpool_pool_state_to_name(state), name);
927 ret = 1;
928 goto errout;
131cc95c 929
dbb38f66
YP
930 case POOL_STATE_EXPORTED:
931 if (force)
131cc95c 932 break;
dbb38f66
YP
933 (void) fprintf(stderr, gettext(
934 "use '-f' to override the following error:\n"
935 "%s is a member of exported pool \"%s\"\n"),
936 vdev, name);
937 ret = 1;
938 goto errout;
939
940 case POOL_STATE_POTENTIALLY_ACTIVE:
941 if (force)
942 break;
943 (void) fprintf(stderr, gettext(
944 "use '-f' to override the following error:\n"
945 "%s is a member of potentially active pool \"%s\"\n"),
946 vdev, name);
947 ret = 1;
948 goto errout;
949
950 case POOL_STATE_DESTROYED:
951 /* inuse should never be set for a destroyed pool */
952 assert(0);
953 break;
131cc95c
DK
954 }
955
956wipe_label:
dbb38f66
YP
957 ret = zpool_clear_label(fd);
958 if (ret != 0) {
131cc95c 959 (void) fprintf(stderr,
dbb38f66 960 gettext("failed to clear label for %s\n"), vdev);
131cc95c
DK
961 }
962
963errout:
dbb38f66
YP
964 free(name);
965 (void) close(fd);
131cc95c
DK
966
967 return (ret);
968}
969
34dc7c2f 970/*
9ae529ec 971 * zpool create [-fnd] [-o property=value] ...
b128c09f
BB
972 * [-O file-system-property=value] ...
973 * [-R root] [-m mountpoint] <pool> <dev> ...
34dc7c2f
BB
974 *
975 * -f Force creation, even if devices appear in use
976 * -n Do not create the pool, but display the resulting layout if it
977 * were to be created.
978 * -R Create a pool under an alternate root
979 * -m Set default mountpoint for the root dataset. By default it's
9ae529ec 980 * '/<pool>'
34dc7c2f 981 * -o Set property=value.
e4010f27 982 * -o Set feature@feature=enabled|disabled.
9ae529ec
CS
983 * -d Don't automatically enable all supported pool features
984 * (individual features can be enabled with -o).
b128c09f 985 * -O Set fsproperty=value in the pool's root file system
34dc7c2f
BB
986 *
987 * Creates the named pool according to the given vdev specification. The
988 * bulk of the vdev processing is done in get_vdev_spec() in zpool_vdev.c. Once
989 * we get the nvlist back from get_vdev_spec(), we either print out the contents
990 * (if '-n' was specified), or pass it to libzfs to do the creation.
991 */
992int
993zpool_do_create(int argc, char **argv)
994{
995 boolean_t force = B_FALSE;
996 boolean_t dryrun = B_FALSE;
9ae529ec 997 boolean_t enable_all_pool_feat = B_TRUE;
34dc7c2f
BB
998 int c;
999 nvlist_t *nvroot = NULL;
1000 char *poolname;
023bbe6f 1001 char *tname = NULL;
34dc7c2f
BB
1002 int ret = 1;
1003 char *altroot = NULL;
1004 char *mountpoint = NULL;
b128c09f 1005 nvlist_t *fsprops = NULL;
34dc7c2f
BB
1006 nvlist_t *props = NULL;
1007 char *propval;
1008
1009 /* check options */
83e9986f 1010 while ((c = getopt(argc, argv, ":fndR:m:o:O:t:")) != -1) {
34dc7c2f
BB
1011 switch (c) {
1012 case 'f':
1013 force = B_TRUE;
1014 break;
1015 case 'n':
1016 dryrun = B_TRUE;
1017 break;
9ae529ec
CS
1018 case 'd':
1019 enable_all_pool_feat = B_FALSE;
1020 break;
34dc7c2f
BB
1021 case 'R':
1022 altroot = optarg;
1023 if (add_prop_list(zpool_prop_to_name(
b128c09f 1024 ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
34dc7c2f 1025 goto errout;
2f3ec900 1026 if (add_prop_list_default(zpool_prop_to_name(
b128c09f 1027 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
34dc7c2f
BB
1028 goto errout;
1029 break;
1030 case 'm':
7bc7f250 1031 /* Equivalent to -O mountpoint=optarg */
34dc7c2f
BB
1032 mountpoint = optarg;
1033 break;
1034 case 'o':
1035 if ((propval = strchr(optarg, '=')) == NULL) {
1036 (void) fprintf(stderr, gettext("missing "
1037 "'=' for -o option\n"));
1038 goto errout;
1039 }
1040 *propval = '\0';
1041 propval++;
1042
b128c09f
BB
1043 if (add_prop_list(optarg, propval, &props, B_TRUE))
1044 goto errout;
9ae529ec
CS
1045
1046 /*
1047 * If the user is creating a pool that doesn't support
1048 * feature flags, don't enable any features.
1049 */
1050 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
1051 char *end;
1052 u_longlong_t ver;
1053
1054 ver = strtoull(propval, &end, 10);
1055 if (*end == '\0' &&
1056 ver < SPA_VERSION_FEATURES) {
1057 enable_all_pool_feat = B_FALSE;
1058 }
1059 }
3ac2794c
BB
1060 if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
1061 altroot = propval;
b128c09f
BB
1062 break;
1063 case 'O':
1064 if ((propval = strchr(optarg, '=')) == NULL) {
1065 (void) fprintf(stderr, gettext("missing "
1066 "'=' for -O option\n"));
1067 goto errout;
1068 }
1069 *propval = '\0';
1070 propval++;
1071
7bc7f250
WA
1072 /*
1073 * Mountpoints are checked and then added later.
1074 * Uniquely among properties, they can be specified
1075 * more than once, to avoid conflict with -m.
1076 */
1077 if (0 == strcmp(optarg,
1078 zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
1079 mountpoint = propval;
1080 } else if (add_prop_list(optarg, propval, &fsprops,
1081 B_FALSE)) {
34dc7c2f 1082 goto errout;
7bc7f250 1083 }
34dc7c2f 1084 break;
83e9986f
RY
1085 case 't':
1086 /*
1087 * Sanity check temporary pool name.
1088 */
1089 if (strchr(optarg, '/') != NULL) {
1090 (void) fprintf(stderr, gettext("cannot create "
1091 "'%s': invalid character '/' in temporary "
1092 "name\n"), optarg);
1093 (void) fprintf(stderr, gettext("use 'zfs "
1094 "create' to create a dataset\n"));
1095 goto errout;
1096 }
1097
1098 if (add_prop_list(zpool_prop_to_name(
1099 ZPOOL_PROP_TNAME), optarg, &props, B_TRUE))
1100 goto errout;
1101 if (add_prop_list_default(zpool_prop_to_name(
1102 ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1103 goto errout;
023bbe6f 1104 tname = optarg;
83e9986f 1105 break;
34dc7c2f
BB
1106 case ':':
1107 (void) fprintf(stderr, gettext("missing argument for "
1108 "'%c' option\n"), optopt);
1109 goto badusage;
1110 case '?':
1111 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1112 optopt);
1113 goto badusage;
1114 }
1115 }
1116
1117 argc -= optind;
1118 argv += optind;
1119
1120 /* get pool name and check number of arguments */
1121 if (argc < 1) {
1122 (void) fprintf(stderr, gettext("missing pool name argument\n"));
1123 goto badusage;
1124 }
1125 if (argc < 2) {
1126 (void) fprintf(stderr, gettext("missing vdev specification\n"));
1127 goto badusage;
1128 }
1129
1130 poolname = argv[0];
1131
1132 /*
1133 * As a special case, check for use of '/' in the name, and direct the
1134 * user to use 'zfs create' instead.
1135 */
1136 if (strchr(poolname, '/') != NULL) {
1137 (void) fprintf(stderr, gettext("cannot create '%s': invalid "
1138 "character '/' in pool name\n"), poolname);
1139 (void) fprintf(stderr, gettext("use 'zfs create' to "
1140 "create a dataset\n"));
1141 goto errout;
1142 }
1143
1144 /* pass off to get_vdev_spec for bulk processing */
df30f566 1145 nvroot = make_root_vdev(NULL, props, force, !force, B_FALSE, dryrun,
b128c09f 1146 argc - 1, argv + 1);
34dc7c2f 1147 if (nvroot == NULL)
b128c09f 1148 goto errout;
34dc7c2f
BB
1149
1150 /* make_root_vdev() allows 0 toplevel children if there are spares */
1151 if (!zfs_allocatable_devs(nvroot)) {
1152 (void) fprintf(stderr, gettext("invalid vdev "
1153 "specification: at least one toplevel vdev must be "
1154 "specified\n"));
1155 goto errout;
1156 }
1157
34dc7c2f
BB
1158 if (altroot != NULL && altroot[0] != '/') {
1159 (void) fprintf(stderr, gettext("invalid alternate root '%s': "
1160 "must be an absolute path\n"), altroot);
1161 goto errout;
1162 }
1163
1164 /*
1165 * Check the validity of the mountpoint and direct the user to use the
1166 * '-m' mountpoint option if it looks like its in use.
1167 */
1168 if (mountpoint == NULL ||
1169 (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
1170 strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
1171 char buf[MAXPATHLEN];
1172 DIR *dirp;
1173
1174 if (mountpoint && mountpoint[0] != '/') {
1175 (void) fprintf(stderr, gettext("invalid mountpoint "
1176 "'%s': must be an absolute path, 'legacy', or "
1177 "'none'\n"), mountpoint);
1178 goto errout;
1179 }
1180
1181 if (mountpoint == NULL) {
1182 if (altroot != NULL)
1183 (void) snprintf(buf, sizeof (buf), "%s/%s",
1184 altroot, poolname);
1185 else
1186 (void) snprintf(buf, sizeof (buf), "/%s",
1187 poolname);
1188 } else {
1189 if (altroot != NULL)
1190 (void) snprintf(buf, sizeof (buf), "%s%s",
1191 altroot, mountpoint);
1192 else
1193 (void) snprintf(buf, sizeof (buf), "%s",
1194 mountpoint);
1195 }
1196
1197 if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
1198 (void) fprintf(stderr, gettext("mountpoint '%s' : "
1199 "%s\n"), buf, strerror(errno));
1200 (void) fprintf(stderr, gettext("use '-m' "
1201 "option to provide a different default\n"));
1202 goto errout;
1203 } else if (dirp) {
1204 int count = 0;
1205
1206 while (count < 3 && readdir(dirp) != NULL)
1207 count++;
1208 (void) closedir(dirp);
1209
1210 if (count > 2) {
1211 (void) fprintf(stderr, gettext("mountpoint "
1212 "'%s' exists and is not empty\n"), buf);
1213 (void) fprintf(stderr, gettext("use '-m' "
1214 "option to provide a "
1215 "different default\n"));
1216 goto errout;
1217 }
1218 }
1219 }
1220
7bc7f250
WA
1221 /*
1222 * Now that the mountpoint's validity has been checked, ensure that
1223 * the property is set appropriately prior to creating the pool.
1224 */
1225 if (mountpoint != NULL) {
1226 ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
1227 mountpoint, &fsprops, B_FALSE);
1228 if (ret != 0)
1229 goto errout;
1230 }
1231
1232 ret = 1;
34dc7c2f
BB
1233 if (dryrun) {
1234 /*
1235 * For a dry run invocation, print out a basic message and run
1236 * through all the vdevs in the list and print out in an
1237 * appropriate hierarchy.
1238 */
1239 (void) printf(gettext("would create '%s' with the "
1240 "following layout:\n\n"), poolname);
1241
d2f3e292 1242 print_vdev_tree(NULL, poolname, nvroot, 0, B_FALSE, 0);
34dc7c2f 1243 if (num_logs(nvroot) > 0)
d2f3e292 1244 print_vdev_tree(NULL, "logs", nvroot, 0, B_TRUE, 0);
34dc7c2f
BB
1245
1246 ret = 0;
1247 } else {
1248 /*
1249 * Hand off to libzfs.
1250 */
e4010f27 1251 spa_feature_t i;
1252 for (i = 0; i < SPA_FEATURES; i++) {
1253 char propname[MAXPATHLEN];
1254 char *propval;
1255 zfeature_info_t *feat = &spa_feature_table[i];
9ae529ec 1256
e4010f27 1257 (void) snprintf(propname, sizeof (propname),
1258 "feature@%s", feat->fi_uname);
1259
1260 /*
1261 * Only features contained in props will be enabled:
1262 * remove from the nvlist every ZFS_FEATURE_DISABLED
1263 * value and add every missing ZFS_FEATURE_ENABLED if
1264 * enable_all_pool_feat is set.
1265 */
1266 if (!nvlist_lookup_string(props, propname, &propval)) {
1267 if (strcmp(propval, ZFS_FEATURE_DISABLED) == 0)
1268 (void) nvlist_remove_all(props,
1269 propname);
1270 } else if (enable_all_pool_feat) {
7bc7f250
WA
1271 ret = add_prop_list(propname,
1272 ZFS_FEATURE_ENABLED, &props, B_TRUE);
1273 if (ret != 0)
9ae529ec
CS
1274 goto errout;
1275 }
1276 }
7bc7f250
WA
1277
1278 ret = 1;
b128c09f
BB
1279 if (zpool_create(g_zfs, poolname,
1280 nvroot, props, fsprops) == 0) {
023bbe6f 1281 zfs_handle_t *pool = zfs_open(g_zfs,
1282 tname ? tname : poolname, ZFS_TYPE_FILESYSTEM);
34dc7c2f 1283 if (pool != NULL) {
34dc7c2f
BB
1284 if (zfs_mount(pool, NULL, 0) == 0)
1285 ret = zfs_shareall(pool);
1286 zfs_close(pool);
1287 }
1288 } else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
1289 (void) fprintf(stderr, gettext("pool name may have "
1290 "been omitted\n"));
1291 }
1292 }
1293
1294errout:
1295 nvlist_free(nvroot);
b128c09f 1296 nvlist_free(fsprops);
34dc7c2f
BB
1297 nvlist_free(props);
1298 return (ret);
1299badusage:
b128c09f 1300 nvlist_free(fsprops);
34dc7c2f
BB
1301 nvlist_free(props);
1302 usage(B_FALSE);
1303 return (2);
1304}
1305
1306/*
1307 * zpool destroy <pool>
1308 *
1309 * -f Forcefully unmount any datasets
1310 *
1311 * Destroy the given pool. Automatically unmounts any datasets in the pool.
1312 */
1313int
1314zpool_do_destroy(int argc, char **argv)
1315{
1316 boolean_t force = B_FALSE;
1317 int c;
1318 char *pool;
1319 zpool_handle_t *zhp;
1320 int ret;
1321
1322 /* check options */
1323 while ((c = getopt(argc, argv, "f")) != -1) {
1324 switch (c) {
1325 case 'f':
1326 force = B_TRUE;
1327 break;
1328 case '?':
1329 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1330 optopt);
1331 usage(B_FALSE);
1332 }
1333 }
1334
1335 argc -= optind;
1336 argv += optind;
1337
1338 /* check arguments */
1339 if (argc < 1) {
1340 (void) fprintf(stderr, gettext("missing pool argument\n"));
1341 usage(B_FALSE);
1342 }
1343 if (argc > 1) {
1344 (void) fprintf(stderr, gettext("too many arguments\n"));
1345 usage(B_FALSE);
1346 }
1347
1348 pool = argv[0];
1349
1350 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
1351 /*
1352 * As a special case, check for use of '/' in the name, and
1353 * direct the user to use 'zfs destroy' instead.
1354 */
1355 if (strchr(pool, '/') != NULL)
1356 (void) fprintf(stderr, gettext("use 'zfs destroy' to "
1357 "destroy a dataset\n"));
1358 return (1);
1359 }
1360
1361 if (zpool_disable_datasets(zhp, force) != 0) {
1362 (void) fprintf(stderr, gettext("could not destroy '%s': "
1363 "could not unmount datasets\n"), zpool_get_name(zhp));
a425f5bf 1364 zpool_close(zhp);
34dc7c2f
BB
1365 return (1);
1366 }
1367
6f1ffb06
MA
1368 /* The history must be logged as part of the export */
1369 log_history = B_FALSE;
1370
1371 ret = (zpool_destroy(zhp, history_str) != 0);
34dc7c2f
BB
1372
1373 zpool_close(zhp);
1374
1375 return (ret);
1376}
1377
859735c0
TF
1378typedef struct export_cbdata {
1379 boolean_t force;
1380 boolean_t hardforce;
1381} export_cbdata_t;
1382
1383/*
1384 * Export one pool
1385 */
1386int
1387zpool_export_one(zpool_handle_t *zhp, void *data)
1388{
1389 export_cbdata_t *cb = data;
1390
1391 if (zpool_disable_datasets(zhp, cb->force) != 0)
1392 return (1);
1393
1394 /* The history must be logged as part of the export */
1395 log_history = B_FALSE;
1396
1397 if (cb->hardforce) {
1398 if (zpool_export_force(zhp, history_str) != 0)
1399 return (1);
1400 } else if (zpool_export(zhp, cb->force, history_str) != 0) {
1401 return (1);
1402 }
1403
1404 return (0);
1405}
1406
34dc7c2f
BB
1407/*
1408 * zpool export [-f] <pool> ...
1409 *
859735c0 1410 * -a Export all pools
34dc7c2f
BB
1411 * -f Forcefully unmount datasets
1412 *
1413 * Export the given pools. By default, the command will attempt to cleanly
1414 * unmount any active datasets within the pool. If the '-f' flag is specified,
1415 * then the datasets will be forcefully unmounted.
1416 */
1417int
1418zpool_do_export(int argc, char **argv)
1419{
859735c0
TF
1420 export_cbdata_t cb;
1421 boolean_t do_all = B_FALSE;
34dc7c2f 1422 boolean_t force = B_FALSE;
fb5f0bc8 1423 boolean_t hardforce = B_FALSE;
859735c0 1424 int c, ret;
34dc7c2f
BB
1425
1426 /* check options */
859735c0 1427 while ((c = getopt(argc, argv, "afF")) != -1) {
34dc7c2f 1428 switch (c) {
859735c0
TF
1429 case 'a':
1430 do_all = B_TRUE;
1431 break;
34dc7c2f
BB
1432 case 'f':
1433 force = B_TRUE;
1434 break;
fb5f0bc8
BB
1435 case 'F':
1436 hardforce = B_TRUE;
1437 break;
34dc7c2f
BB
1438 case '?':
1439 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1440 optopt);
1441 usage(B_FALSE);
1442 }
1443 }
1444
859735c0
TF
1445 cb.force = force;
1446 cb.hardforce = hardforce;
34dc7c2f
BB
1447 argc -= optind;
1448 argv += optind;
1449
859735c0
TF
1450 if (do_all) {
1451 if (argc != 0) {
1452 (void) fprintf(stderr, gettext("too many arguments\n"));
1453 usage(B_FALSE);
1454 }
1455
1456 return (for_each_pool(argc, argv, B_TRUE, NULL,
1457 zpool_export_one, &cb));
1458 }
1459
34dc7c2f
BB
1460 /* check arguments */
1461 if (argc < 1) {
1462 (void) fprintf(stderr, gettext("missing pool argument\n"));
1463 usage(B_FALSE);
1464 }
1465
859735c0 1466 ret = for_each_pool(argc, argv, B_TRUE, NULL, zpool_export_one, &cb);
34dc7c2f
BB
1467
1468 return (ret);
1469}
1470
1471/*
1472 * Given a vdev configuration, determine the maximum width needed for the device
1473 * name column.
1474 */
1475static int
d2f3e292
RY
1476max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max,
1477 int name_flags)
34dc7c2f 1478{
d2f3e292 1479 char *name;
34dc7c2f
BB
1480 nvlist_t **child;
1481 uint_t c, children;
1482 int ret;
1483
5f20c145 1484 name = zpool_vdev_name(g_zfs, zhp, nv, name_flags);
34dc7c2f
BB
1485 if (strlen(name) + depth > max)
1486 max = strlen(name) + depth;
1487
1488 free(name);
1489
1490 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1491 &child, &children) == 0) {
1492 for (c = 0; c < children; c++)
1493 if ((ret = max_width(zhp, child[c], depth + 2,
d2f3e292 1494 max, name_flags)) > max)
34dc7c2f
BB
1495 max = ret;
1496 }
1497
1498 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1499 &child, &children) == 0) {
1500 for (c = 0; c < children; c++)
1501 if ((ret = max_width(zhp, child[c], depth + 2,
d2f3e292 1502 max, name_flags)) > max)
34dc7c2f
BB
1503 max = ret;
1504 }
1505
1506 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1507 &child, &children) == 0) {
1508 for (c = 0; c < children; c++)
1509 if ((ret = max_width(zhp, child[c], depth + 2,
d2f3e292 1510 max, name_flags)) > max)
34dc7c2f
BB
1511 max = ret;
1512 }
1513
34dc7c2f
BB
1514 return (max);
1515}
1516
9babb374
BB
1517typedef struct spare_cbdata {
1518 uint64_t cb_guid;
1519 zpool_handle_t *cb_zhp;
1520} spare_cbdata_t;
1521
1522static boolean_t
1523find_vdev(nvlist_t *nv, uint64_t search)
1524{
1525 uint64_t guid;
1526 nvlist_t **child;
1527 uint_t c, children;
1528
1529 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1530 search == guid)
1531 return (B_TRUE);
1532
1533 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1534 &child, &children) == 0) {
1535 for (c = 0; c < children; c++)
1536 if (find_vdev(child[c], search))
1537 return (B_TRUE);
1538 }
1539
1540 return (B_FALSE);
1541}
1542
1543static int
1544find_spare(zpool_handle_t *zhp, void *data)
1545{
1546 spare_cbdata_t *cbp = data;
1547 nvlist_t *config, *nvroot;
1548
1549 config = zpool_get_config(zhp, NULL);
1550 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1551 &nvroot) == 0);
1552
1553 if (find_vdev(nvroot, cbp->cb_guid)) {
1554 cbp->cb_zhp = zhp;
1555 return (1);
1556 }
1557
1558 zpool_close(zhp);
1559 return (0);
1560}
1561
fea33e4e
HJ
1562typedef struct status_cbdata {
1563 int cb_count;
1564 int cb_name_flags;
1565 int cb_namewidth;
1566 boolean_t cb_allpools;
1567 boolean_t cb_verbose;
1568 boolean_t cb_explain;
1569 boolean_t cb_first;
1570 boolean_t cb_dedup_stats;
1571 boolean_t cb_print_status;
8720e9e7 1572 vdev_cmd_data_list_t *vcdl;
fea33e4e
HJ
1573} status_cbdata_t;
1574
d6418de0
TH
1575/* Return 1 if string is NULL, empty, or whitespace; return 0 otherwise. */
1576static int
1577is_blank_str(char *str)
1578{
1579 while (str != NULL && *str != '\0') {
1580 if (!isblank(*str))
1581 return (0);
1582 str++;
1583 }
1584 return (1);
1585}
1586
1587/* Print command output lines for specific vdev in a specific pool */
8720e9e7
TH
1588static void
1589zpool_print_cmd(vdev_cmd_data_list_t *vcdl, const char *pool, char *path)
1590{
d6418de0
TH
1591 vdev_cmd_data_t *data;
1592 int i, j;
1593 char *val;
1594
8720e9e7 1595 for (i = 0; i < vcdl->count; i++) {
d6418de0
TH
1596 if ((strcmp(vcdl->data[i].path, path) != 0) ||
1597 (strcmp(vcdl->data[i].pool, pool) != 0)) {
1598 /* Not the vdev we're looking for */
1599 continue;
8720e9e7 1600 }
d6418de0
TH
1601
1602 data = &vcdl->data[i];
1603 /* Print out all the output values for this vdev */
1604 for (j = 0; j < vcdl->uniq_cols_cnt; j++) {
1605 val = NULL;
1606 /* Does this vdev have values for this column? */
1607 for (int k = 0; k < data->cols_cnt; k++) {
1608 if (strcmp(data->cols[k],
1609 vcdl->uniq_cols[j]) == 0) {
1610 /* yes it does, record the value */
1611 val = data->lines[k];
1612 break;
1613 }
1614 }
1615 /*
1616 * Mark empty values with dashes to make output
1617 * awk-able.
1618 */
1619 if (is_blank_str(val))
1620 val = "-";
1621
1622 printf("%*s", vcdl->uniq_cols_width[j], val);
1623 if (j < vcdl->uniq_cols_cnt - 1)
1624 printf(" ");
1625 }
1626
1627 /* Print out any values that aren't in a column at the end */
1628 for (j = data->cols_cnt; j < data->lines_cnt; j++) {
1629 /* Did we have any columns? If so print a spacer. */
1630 if (vcdl->uniq_cols_cnt > 0)
1631 printf(" ");
1632
1633 val = data->lines[j];
1634 printf("%s", val ? val : "");
1635 }
1636 break;
8720e9e7
TH
1637 }
1638}
1639
9babb374
BB
1640/*
1641 * Print out configuration state as requested by status_callback.
1642 */
d2f3e292 1643static void
fea33e4e
HJ
1644print_status_config(zpool_handle_t *zhp, status_cbdata_t *cb, const char *name,
1645 nvlist_t *nv, int depth, boolean_t isspare)
9babb374
BB
1646{
1647 nvlist_t **child;
1648 uint_t c, children;
428870ff 1649 pool_scan_stat_t *ps = NULL;
9babb374 1650 vdev_stat_t *vs;
428870ff 1651 char rbuf[6], wbuf[6], cbuf[6];
9babb374
BB
1652 char *vname;
1653 uint64_t notpresent;
fea33e4e 1654 spare_cbdata_t spare_cb;
9babb374 1655 char *state;
8720e9e7 1656 char *path = NULL;
9babb374 1657
9babb374
BB
1658 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1659 &child, &children) != 0)
1660 children = 0;
1661
428870ff
BB
1662 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1663 (uint64_t **)&vs, &c) == 0);
1664
9babb374
BB
1665 state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1666 if (isspare) {
1667 /*
1668 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
1669 * online drives.
1670 */
1671 if (vs->vs_aux == VDEV_AUX_SPARED)
1672 state = "INUSE";
1673 else if (vs->vs_state == VDEV_STATE_HEALTHY)
1674 state = "AVAIL";
1675 }
1676
fea33e4e 1677 (void) printf("\t%*s%-*s %-8s", depth, "", cb->cb_namewidth - depth,
9babb374
BB
1678 name, state);
1679
1680 if (!isspare) {
1681 zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
1682 zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
1683 zfs_nicenum(vs->vs_checksum_errors, cbuf, sizeof (cbuf));
1684 (void) printf(" %5s %5s %5s", rbuf, wbuf, cbuf);
1685 }
1686
1687 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
1688 &notpresent) == 0) {
9babb374
BB
1689 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
1690 (void) printf(" was %s", path);
1691 } else if (vs->vs_aux != 0) {
1692 (void) printf(" ");
1693
1694 switch (vs->vs_aux) {
1695 case VDEV_AUX_OPEN_FAILED:
1696 (void) printf(gettext("cannot open"));
1697 break;
1698
1699 case VDEV_AUX_BAD_GUID_SUM:
1700 (void) printf(gettext("missing device"));
1701 break;
1702
1703 case VDEV_AUX_NO_REPLICAS:
1704 (void) printf(gettext("insufficient replicas"));
1705 break;
1706
1707 case VDEV_AUX_VERSION_NEWER:
1708 (void) printf(gettext("newer version"));
1709 break;
1710
9ae529ec
CS
1711 case VDEV_AUX_UNSUP_FEAT:
1712 (void) printf(gettext("unsupported feature(s)"));
1713 break;
1714
9babb374
BB
1715 case VDEV_AUX_SPARED:
1716 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
fea33e4e
HJ
1717 &spare_cb.cb_guid) == 0);
1718 if (zpool_iter(g_zfs, find_spare, &spare_cb) == 1) {
1719 if (strcmp(zpool_get_name(spare_cb.cb_zhp),
9babb374
BB
1720 zpool_get_name(zhp)) == 0)
1721 (void) printf(gettext("currently in "
1722 "use"));
1723 else
1724 (void) printf(gettext("in use by "
1725 "pool '%s'"),
fea33e4e
HJ
1726 zpool_get_name(spare_cb.cb_zhp));
1727 zpool_close(spare_cb.cb_zhp);
9babb374
BB
1728 } else {
1729 (void) printf(gettext("currently in use"));
1730 }
1731 break;
1732
1733 case VDEV_AUX_ERR_EXCEEDED:
1734 (void) printf(gettext("too many errors"));
1735 break;
1736
1737 case VDEV_AUX_IO_FAILURE:
1738 (void) printf(gettext("experienced I/O failures"));
1739 break;
1740
1741 case VDEV_AUX_BAD_LOG:
1742 (void) printf(gettext("bad intent log"));
1743 break;
1744
428870ff
BB
1745 case VDEV_AUX_EXTERNAL:
1746 (void) printf(gettext("external device fault"));
1747 break;
1748
1749 case VDEV_AUX_SPLIT_POOL:
1750 (void) printf(gettext("split into new pool"));
1751 break;
1752
379ca9cf
OF
1753 case VDEV_AUX_ACTIVE:
1754 (void) printf(gettext("currently in use"));
4265a929 1755 break;
379ca9cf 1756
9babb374
BB
1757 default:
1758 (void) printf(gettext("corrupted data"));
1759 break;
1760 }
428870ff
BB
1761 }
1762
1763 (void) nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_SCAN_STATS,
1764 (uint64_t **)&ps, &c);
1765
d4a72f23 1766 if (ps != NULL && ps->pss_state == DSS_SCANNING &&
428870ff
BB
1767 vs->vs_scan_processed != 0 && children == 0) {
1768 (void) printf(gettext(" (%s)"),
1769 (ps->pss_func == POOL_SCAN_RESILVER) ?
1770 "resilvering" : "repairing");
9babb374
BB
1771 }
1772
8720e9e7
TH
1773 if (cb->vcdl != NULL) {
1774 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
1775 printf(" ");
1776 zpool_print_cmd(cb->vcdl, zpool_get_name(zhp), path);
1777 }
1778 }
1779
9babb374
BB
1780 (void) printf("\n");
1781
1782 for (c = 0; c < children; c++) {
428870ff 1783 uint64_t islog = B_FALSE, ishole = B_FALSE;
9babb374 1784
428870ff 1785 /* Don't print logs or holes here */
9babb374 1786 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
428870ff
BB
1787 &islog);
1788 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
1789 &ishole);
1790 if (islog || ishole)
9babb374 1791 continue;
d2f3e292 1792 vname = zpool_vdev_name(g_zfs, zhp, child[c],
fea33e4e
HJ
1793 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1794 print_status_config(zhp, cb, vname, child[c], depth + 2,
1795 isspare);
9babb374
BB
1796 free(vname);
1797 }
1798}
1799
34dc7c2f
BB
1800/*
1801 * Print the configuration of an exported pool. Iterate over all vdevs in the
1802 * pool, printing out the name and status for each one.
1803 */
d2f3e292 1804static void
fea33e4e
HJ
1805print_import_config(status_cbdata_t *cb, const char *name, nvlist_t *nv,
1806 int depth)
34dc7c2f
BB
1807{
1808 nvlist_t **child;
1809 uint_t c, children;
1810 vdev_stat_t *vs;
1811 char *type, *vname;
1812
1813 verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
428870ff
BB
1814 if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
1815 strcmp(type, VDEV_TYPE_HOLE) == 0)
34dc7c2f
BB
1816 return;
1817
428870ff 1818 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
34dc7c2f
BB
1819 (uint64_t **)&vs, &c) == 0);
1820
fea33e4e 1821 (void) printf("\t%*s%-*s", depth, "", cb->cb_namewidth - depth, name);
34dc7c2f
BB
1822 (void) printf(" %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
1823
1824 if (vs->vs_aux != 0) {
1825 (void) printf(" ");
1826
1827 switch (vs->vs_aux) {
1828 case VDEV_AUX_OPEN_FAILED:
1829 (void) printf(gettext("cannot open"));
1830 break;
1831
1832 case VDEV_AUX_BAD_GUID_SUM:
1833 (void) printf(gettext("missing device"));
1834 break;
1835
1836 case VDEV_AUX_NO_REPLICAS:
1837 (void) printf(gettext("insufficient replicas"));
1838 break;
1839
1840 case VDEV_AUX_VERSION_NEWER:
1841 (void) printf(gettext("newer version"));
1842 break;
1843
9ae529ec
CS
1844 case VDEV_AUX_UNSUP_FEAT:
1845 (void) printf(gettext("unsupported feature(s)"));
1846 break;
1847
34dc7c2f
BB
1848 case VDEV_AUX_ERR_EXCEEDED:
1849 (void) printf(gettext("too many errors"));
1850 break;
1851
379ca9cf
OF
1852 case VDEV_AUX_ACTIVE:
1853 (void) printf(gettext("currently in use"));
1854 break;
1855
34dc7c2f
BB
1856 default:
1857 (void) printf(gettext("corrupted data"));
1858 break;
1859 }
1860 }
1861 (void) printf("\n");
1862
1863 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1864 &child, &children) != 0)
1865 return;
1866
1867 for (c = 0; c < children; c++) {
1868 uint64_t is_log = B_FALSE;
1869
1870 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1871 &is_log);
9babb374 1872 if (is_log)
34dc7c2f
BB
1873 continue;
1874
d2f3e292 1875 vname = zpool_vdev_name(g_zfs, NULL, child[c],
fea33e4e
HJ
1876 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1877 print_import_config(cb, vname, child[c], depth + 2);
34dc7c2f
BB
1878 free(vname);
1879 }
1880
1881 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1882 &child, &children) == 0) {
1883 (void) printf(gettext("\tcache\n"));
1884 for (c = 0; c < children; c++) {
d2f3e292 1885 vname = zpool_vdev_name(g_zfs, NULL, child[c],
fea33e4e 1886 cb->cb_name_flags);
34dc7c2f
BB
1887 (void) printf("\t %s\n", vname);
1888 free(vname);
1889 }
1890 }
1891
1892 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1893 &child, &children) == 0) {
1894 (void) printf(gettext("\tspares\n"));
1895 for (c = 0; c < children; c++) {
d2f3e292 1896 vname = zpool_vdev_name(g_zfs, NULL, child[c],
fea33e4e 1897 cb->cb_name_flags);
34dc7c2f
BB
1898 (void) printf("\t %s\n", vname);
1899 free(vname);
1900 }
1901 }
1902}
1903
9babb374
BB
1904/*
1905 * Print log vdevs.
1906 * Logs are recorded as top level vdevs in the main pool child array
1907 * but with "is_log" set to 1. We use either print_status_config() or
1908 * print_import_config() to print the top level logs then any log
1909 * children (eg mirrored slogs) are printed recursively - which
1910 * works because only the top level vdev is marked "is_log"
1911 */
1912static void
fea33e4e 1913print_logs(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t *nv)
9babb374
BB
1914{
1915 uint_t c, children;
1916 nvlist_t **child;
1917
1918 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
1919 &children) != 0)
1920 return;
1921
1922 (void) printf(gettext("\tlogs\n"));
1923
1924 for (c = 0; c < children; c++) {
1925 uint64_t is_log = B_FALSE;
1926 char *name;
1927
1928 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1929 &is_log);
1930 if (!is_log)
1931 continue;
d2f3e292 1932 name = zpool_vdev_name(g_zfs, zhp, child[c],
fea33e4e
HJ
1933 cb->cb_name_flags | VDEV_NAME_TYPE_ID);
1934 if (cb->cb_print_status)
1935 print_status_config(zhp, cb, name, child[c], 2,
1936 B_FALSE);
9babb374 1937 else
fea33e4e 1938 print_import_config(cb, name, child[c], 2);
9babb374
BB
1939 free(name);
1940 }
1941}
428870ff 1942
34dc7c2f
BB
1943/*
1944 * Display the status for the given pool.
1945 */
1946static void
1947show_import(nvlist_t *config)
1948{
1949 uint64_t pool_state;
1950 vdev_stat_t *vs;
1951 char *name;
1952 uint64_t guid;
379ca9cf 1953 uint64_t hostid = 0;
34dc7c2f 1954 char *msgid;
379ca9cf
OF
1955 char *hostname = "unknown";
1956 nvlist_t *nvroot, *nvinfo;
731782ec 1957 zpool_status_t reason;
ffe9d382 1958 zpool_errata_t errata;
34dc7c2f
BB
1959 const char *health;
1960 uint_t vsc;
d96eb2b1 1961 char *comment;
fea33e4e 1962 status_cbdata_t cb = { 0 };
34dc7c2f
BB
1963
1964 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1965 &name) == 0);
1966 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1967 &guid) == 0);
1968 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
1969 &pool_state) == 0);
1970 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1971 &nvroot) == 0);
1972
428870ff 1973 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
34dc7c2f
BB
1974 (uint64_t **)&vs, &vsc) == 0);
1975 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1976
ffe9d382 1977 reason = zpool_import_status(config, &msgid, &errata);
34dc7c2f 1978
d96eb2b1
DM
1979 (void) printf(gettext(" pool: %s\n"), name);
1980 (void) printf(gettext(" id: %llu\n"), (u_longlong_t)guid);
1981 (void) printf(gettext(" state: %s"), health);
34dc7c2f
BB
1982 if (pool_state == POOL_STATE_DESTROYED)
1983 (void) printf(gettext(" (DESTROYED)"));
1984 (void) printf("\n");
1985
1986 switch (reason) {
1987 case ZPOOL_STATUS_MISSING_DEV_R:
1988 case ZPOOL_STATUS_MISSING_DEV_NR:
1989 case ZPOOL_STATUS_BAD_GUID_SUM:
d96eb2b1
DM
1990 (void) printf(gettext(" status: One or more devices are "
1991 "missing from the system.\n"));
34dc7c2f
BB
1992 break;
1993
1994 case ZPOOL_STATUS_CORRUPT_LABEL_R:
1995 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
d96eb2b1 1996 (void) printf(gettext(" status: One or more devices contains "
34dc7c2f
BB
1997 "corrupted data.\n"));
1998 break;
1999
2000 case ZPOOL_STATUS_CORRUPT_DATA:
d96eb2b1
DM
2001 (void) printf(
2002 gettext(" status: The pool data is corrupted.\n"));
34dc7c2f
BB
2003 break;
2004
2005 case ZPOOL_STATUS_OFFLINE_DEV:
d96eb2b1 2006 (void) printf(gettext(" status: One or more devices "
34dc7c2f
BB
2007 "are offlined.\n"));
2008 break;
2009
2010 case ZPOOL_STATUS_CORRUPT_POOL:
d96eb2b1 2011 (void) printf(gettext(" status: The pool metadata is "
34dc7c2f
BB
2012 "corrupted.\n"));
2013 break;
2014
2015 case ZPOOL_STATUS_VERSION_OLDER:
b9b24bb4
CS
2016 (void) printf(gettext(" status: The pool is formatted using a "
2017 "legacy on-disk version.\n"));
34dc7c2f
BB
2018 break;
2019
2020 case ZPOOL_STATUS_VERSION_NEWER:
d96eb2b1 2021 (void) printf(gettext(" status: The pool is formatted using an "
34dc7c2f
BB
2022 "incompatible version.\n"));
2023 break;
b128c09f 2024
b9b24bb4
CS
2025 case ZPOOL_STATUS_FEAT_DISABLED:
2026 (void) printf(gettext(" status: Some supported features are "
2027 "not enabled on the pool.\n"));
2028 break;
2029
9ae529ec
CS
2030 case ZPOOL_STATUS_UNSUP_FEAT_READ:
2031 (void) printf(gettext("status: The pool uses the following "
4e33ba4c 2032 "feature(s) not supported on this system:\n"));
9ae529ec
CS
2033 zpool_print_unsup_feat(config);
2034 break;
2035
2036 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2037 (void) printf(gettext("status: The pool can only be accessed "
2038 "in read-only mode on this system. It\n\tcannot be "
2039 "accessed in read-write mode because it uses the "
2040 "following\n\tfeature(s) not supported on this system:\n"));
2041 zpool_print_unsup_feat(config);
2042 break;
2043
379ca9cf
OF
2044 case ZPOOL_STATUS_HOSTID_ACTIVE:
2045 (void) printf(gettext(" status: The pool is currently "
2046 "imported by another system.\n"));
2047 break;
2048
2049 case ZPOOL_STATUS_HOSTID_REQUIRED:
2050 (void) printf(gettext(" status: The pool has the "
2051 "multihost property on. It cannot\n\tbe safely imported "
2052 "when the system hostid is not set.\n"));
2053 break;
2054
34dc7c2f 2055 case ZPOOL_STATUS_HOSTID_MISMATCH:
d96eb2b1 2056 (void) printf(gettext(" status: The pool was last accessed by "
34dc7c2f
BB
2057 "another system.\n"));
2058 break;
b128c09f 2059
34dc7c2f
BB
2060 case ZPOOL_STATUS_FAULTED_DEV_R:
2061 case ZPOOL_STATUS_FAULTED_DEV_NR:
d96eb2b1 2062 (void) printf(gettext(" status: One or more devices are "
34dc7c2f
BB
2063 "faulted.\n"));
2064 break;
2065
b128c09f 2066 case ZPOOL_STATUS_BAD_LOG:
d96eb2b1 2067 (void) printf(gettext(" status: An intent log record cannot be "
b128c09f
BB
2068 "read.\n"));
2069 break;
2070
428870ff 2071 case ZPOOL_STATUS_RESILVERING:
d96eb2b1 2072 (void) printf(gettext(" status: One or more devices were being "
428870ff
BB
2073 "resilvered.\n"));
2074 break;
2075
ffe9d382
BB
2076 case ZPOOL_STATUS_ERRATA:
2077 (void) printf(gettext(" status: Errata #%d detected.\n"),
2078 errata);
2079 break;
2080
34dc7c2f
BB
2081 default:
2082 /*
2083 * No other status can be seen when importing pools.
2084 */
2085 assert(reason == ZPOOL_STATUS_OK);
2086 }
2087
2088 /*
2089 * Print out an action according to the overall state of the pool.
2090 */
2091 if (vs->vs_state == VDEV_STATE_HEALTHY) {
b9b24bb4
CS
2092 if (reason == ZPOOL_STATUS_VERSION_OLDER ||
2093 reason == ZPOOL_STATUS_FEAT_DISABLED) {
d96eb2b1 2094 (void) printf(gettext(" action: The pool can be "
34dc7c2f
BB
2095 "imported using its name or numeric identifier, "
2096 "though\n\tsome features will not be available "
2097 "without an explicit 'zpool upgrade'.\n"));
b9b24bb4 2098 } else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
d96eb2b1 2099 (void) printf(gettext(" action: The pool can be "
34dc7c2f
BB
2100 "imported using its name or numeric "
2101 "identifier and\n\tthe '-f' flag.\n"));
ffe9d382
BB
2102 } else if (reason == ZPOOL_STATUS_ERRATA) {
2103 switch (errata) {
2104 case ZPOOL_ERRATA_NONE:
2105 break;
2106
4f2dcb3e
RY
2107 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
2108 (void) printf(gettext(" action: The pool can "
2109 "be imported using its name or numeric "
2110 "identifier,\n\thowever there is a compat"
2111 "ibility issue which should be corrected"
2112 "\n\tby running 'zpool scrub'\n"));
2113 break;
2114
2115 case ZPOOL_ERRATA_ZOL_2094_ASYNC_DESTROY:
2116 (void) printf(gettext(" action: The pool can"
2117 "not be imported with this version of ZFS "
2118 "due to\n\tan active asynchronous destroy. "
2119 "Revert to an earlier version\n\tand "
2120 "allow the destroy to complete before "
2121 "updating.\n"));
2122 break;
2123
ffe9d382
BB
2124 default:
2125 /*
2126 * All errata must contain an action message.
2127 */
2128 assert(0);
2129 }
b9b24bb4 2130 } else {
d96eb2b1 2131 (void) printf(gettext(" action: The pool can be "
34dc7c2f
BB
2132 "imported using its name or numeric "
2133 "identifier.\n"));
b9b24bb4 2134 }
34dc7c2f 2135 } else if (vs->vs_state == VDEV_STATE_DEGRADED) {
d96eb2b1 2136 (void) printf(gettext(" action: The pool can be imported "
34dc7c2f
BB
2137 "despite missing or damaged devices. The\n\tfault "
2138 "tolerance of the pool may be compromised if imported.\n"));
2139 } else {
2140 switch (reason) {
2141 case ZPOOL_STATUS_VERSION_NEWER:
d96eb2b1 2142 (void) printf(gettext(" action: The pool cannot be "
34dc7c2f
BB
2143 "imported. Access the pool on a system running "
2144 "newer\n\tsoftware, or recreate the pool from "
2145 "backup.\n"));
2146 break;
9ae529ec
CS
2147 case ZPOOL_STATUS_UNSUP_FEAT_READ:
2148 (void) printf(gettext("action: The pool cannot be "
2149 "imported. Access the pool on a system that "
2150 "supports\n\tthe required feature(s), or recreate "
2151 "the pool from backup.\n"));
2152 break;
2153 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
2154 (void) printf(gettext("action: The pool cannot be "
2155 "imported in read-write mode. Import the pool "
2156 "with\n"
2157 "\t\"-o readonly=on\", access the pool on a system "
2158 "that supports the\n\trequired feature(s), or "
2159 "recreate the pool from backup.\n"));
2160 break;
34dc7c2f
BB
2161 case ZPOOL_STATUS_MISSING_DEV_R:
2162 case ZPOOL_STATUS_MISSING_DEV_NR:
2163 case ZPOOL_STATUS_BAD_GUID_SUM:
d96eb2b1 2164 (void) printf(gettext(" action: The pool cannot be "
34dc7c2f
BB
2165 "imported. Attach the missing\n\tdevices and try "
2166 "again.\n"));
2167 break;
379ca9cf
OF
2168 case ZPOOL_STATUS_HOSTID_ACTIVE:
2169 VERIFY0(nvlist_lookup_nvlist(config,
2170 ZPOOL_CONFIG_LOAD_INFO, &nvinfo));
2171
2172 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTNAME))
2173 hostname = fnvlist_lookup_string(nvinfo,
2174 ZPOOL_CONFIG_MMP_HOSTNAME);
2175
2176 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_HOSTID))
2177 hostid = fnvlist_lookup_uint64(nvinfo,
2178 ZPOOL_CONFIG_MMP_HOSTID);
2179
2180 (void) printf(gettext(" action: The pool must be "
2181 "exported from %s (hostid=%lx)\n\tbefore it "
2182 "can be safely imported.\n"), hostname,
2183 (unsigned long) hostid);
2184 break;
2185 case ZPOOL_STATUS_HOSTID_REQUIRED:
2186 (void) printf(gettext(" action: Set a unique system "
b9373170 2187 "hostid with the zgenhostid(8) command.\n"));
379ca9cf 2188 break;
34dc7c2f 2189 default:
d96eb2b1 2190 (void) printf(gettext(" action: The pool cannot be "
34dc7c2f
BB
2191 "imported due to damaged devices or data.\n"));
2192 }
2193 }
2194
d96eb2b1
DM
2195 /* Print the comment attached to the pool. */
2196 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2197 (void) printf(gettext("comment: %s\n"), comment);
2198
34dc7c2f
BB
2199 /*
2200 * If the state is "closed" or "can't open", and the aux state
2201 * is "corrupt data":
2202 */
2203 if (((vs->vs_state == VDEV_STATE_CLOSED) ||
2204 (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
2205 (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
2206 if (pool_state == POOL_STATE_DESTROYED)
2207 (void) printf(gettext("\tThe pool was destroyed, "
2208 "but can be imported using the '-Df' flags.\n"));
2209 else if (pool_state != POOL_STATE_EXPORTED)
2210 (void) printf(gettext("\tThe pool may be active on "
2211 "another system, but can be imported using\n\t"
2212 "the '-f' flag.\n"));
2213 }
2214
2215 if (msgid != NULL)
3cee2262 2216 (void) printf(gettext(" see: http://zfsonlinux.org/msg/%s\n"),
34dc7c2f
BB
2217 msgid);
2218
d96eb2b1 2219 (void) printf(gettext(" config:\n\n"));
34dc7c2f 2220
2df9ad1c
GG
2221 cb.cb_namewidth = max_width(NULL, nvroot, 0, strlen(name),
2222 VDEV_NAME_TYPE_ID);
fea33e4e
HJ
2223 if (cb.cb_namewidth < 10)
2224 cb.cb_namewidth = 10;
34dc7c2f 2225
fea33e4e 2226 print_import_config(&cb, name, nvroot, 0);
9babb374 2227 if (num_logs(nvroot) > 0)
fea33e4e 2228 print_logs(NULL, &cb, nvroot);
34dc7c2f
BB
2229
2230 if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
2231 (void) printf(gettext("\n\tAdditional devices are known to "
2232 "be part of this pool, though their\n\texact "
2233 "configuration cannot be determined.\n"));
2234 }
2235}
2236
379ca9cf
OF
2237static boolean_t
2238zfs_force_import_required(nvlist_t *config)
2239{
2240 uint64_t state;
2241 uint64_t hostid = 0;
2242 nvlist_t *nvinfo;
2243
2244 state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
2245 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID, &hostid);
2246
2247 if (state != POOL_STATE_EXPORTED && hostid != get_system_hostid())
2248 return (B_TRUE);
2249
2250 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2251 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_STATE)) {
2252 mmp_state_t mmp_state = fnvlist_lookup_uint64(nvinfo,
2253 ZPOOL_CONFIG_MMP_STATE);
2254
2255 if (mmp_state != MMP_STATE_INACTIVE)
2256 return (B_TRUE);
2257 }
2258
2259 return (B_FALSE);
2260}
2261
34dc7c2f
BB
2262/*
2263 * Perform the import for the given configuration. This passes the heavy
2264 * lifting off to zpool_import_props(), and then mounts the datasets contained
2265 * within the pool.
2266 */
2267static int
2268do_import(nvlist_t *config, const char *newname, const char *mntopts,
572e2857 2269 nvlist_t *props, int flags)
34dc7c2f 2270{
b5256303 2271 int ret = 0;
34dc7c2f
BB
2272 zpool_handle_t *zhp;
2273 char *name;
2274 uint64_t state;
2275 uint64_t version;
34dc7c2f 2276
379ca9cf
OF
2277 name = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
2278 state = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE);
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;
3651 uint_t c, children;
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
BB
3762
3763 if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
3764 &oldchild, &c) != 0)
193a37cb 3765 return (ret);
34dc7c2f
BB
3766
3767 for (c = 0; c < children; c++) {
187632dc 3768 uint64_t ishole = B_FALSE, islog = B_FALSE;
428870ff 3769
187632dc
MH
3770 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
3771 &ishole);
3772
3773 (void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
3774 &islog);
3775
3776 if (ishole || islog)
428870ff
BB
3777 continue;
3778
d2f3e292
RY
3779 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
3780 cb->cb_name_flags);
193a37cb 3781 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
34dc7c2f
BB
3782 newchild[c], cb, depth + 2);
3783 free(vname);
3784 }
3785
187632dc
MH
3786 /*
3787 * Log device section
3788 */
3789
3790 if (num_logs(newnv) > 0) {
7e945072 3791 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
193a37cb
TH
3792 !cb->cb_vdev_names) {
3793 print_iostat_dashes(cb, 0, "logs");
3794 }
5034557b 3795 printf("\n");
187632dc
MH
3796
3797 for (c = 0; c < children; c++) {
3798 uint64_t islog = B_FALSE;
3799 (void) nvlist_lookup_uint64(newchild[c],
3800 ZPOOL_CONFIG_IS_LOG, &islog);
3801
3802 if (islog) {
3803 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
d2f3e292 3804 cb->cb_name_flags);
193a37cb 3805 ret += print_vdev_stats(zhp, vname, oldnv ?
187632dc
MH
3806 oldchild[c] : NULL, newchild[c],
3807 cb, depth + 2);
3808 free(vname);
3809 }
3810 }
3811
3812 }
3813
34dc7c2f
BB
3814 /*
3815 * Include level 2 ARC devices in iostat output
3816 */
3817 if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
3818 &newchild, &children) != 0)
193a37cb 3819 return (ret);
34dc7c2f
BB
3820
3821 if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
3822 &oldchild, &c) != 0)
193a37cb 3823 return (ret);
34dc7c2f
BB
3824
3825 if (children > 0) {
7e945072 3826 if ((!(cb->cb_flags & IOS_ANYHISTO_M)) && !cb->cb_scripted &&
193a37cb
TH
3827 !cb->cb_vdev_names) {
3828 print_iostat_dashes(cb, 0, "cache");
3829 }
5034557b 3830 printf("\n");
193a37cb 3831
34dc7c2f 3832 for (c = 0; c < children; c++) {
428870ff 3833 vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
d2f3e292 3834 cb->cb_name_flags);
193a37cb
TH
3835 ret += print_vdev_stats(zhp, vname, oldnv ? oldchild[c]
3836 : NULL, newchild[c], cb, depth + 2);
34dc7c2f
BB
3837 free(vname);
3838 }
3839 }
193a37cb
TH
3840
3841 return (ret);
34dc7c2f
BB
3842}
3843
3844static int
3845refresh_iostat(zpool_handle_t *zhp, void *data)
3846{
3847 iostat_cbdata_t *cb = data;
3848 boolean_t missing;
3849
3850 /*
3851 * If the pool has disappeared, remove it from the list and continue.
3852 */
3853 if (zpool_refresh_stats(zhp, &missing) != 0)
3854 return (-1);
3855
3856 if (missing)
3857 pool_list_remove(cb->cb_list, zhp);
3858
3859 return (0);
3860}
3861
3862/*
3863 * Callback to print out the iostats for the given pool.
3864 */
3865int
3866print_iostat(zpool_handle_t *zhp, void *data)
3867{
3868 iostat_cbdata_t *cb = data;
3869 nvlist_t *oldconfig, *newconfig;
3870 nvlist_t *oldnvroot, *newnvroot;
193a37cb 3871 int ret;
34dc7c2f
BB
3872
3873 newconfig = zpool_get_config(zhp, &oldconfig);
3874
3875 if (cb->cb_iteration == 1)
3876 oldconfig = NULL;
3877
3878 verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
3879 &newnvroot) == 0);
3880
3881 if (oldconfig == NULL)
3882 oldnvroot = NULL;
3883 else
3884 verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
3885 &oldnvroot) == 0);
3886
193a37cb 3887 ret = print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot,
02730c33 3888 cb, 0);
7e945072
TH
3889 if ((ret != 0) && !(cb->cb_flags & IOS_ANYHISTO_M) &&
3890 !cb->cb_scripted && cb->cb_verbose && !cb->cb_vdev_names_count) {
3891 print_iostat_separator(cb);
d6418de0
TH
3892 if (cb->vcdl != NULL) {
3893 print_cmd_columns(cb->vcdl, 1);
3894 }
3895 printf("\n");
7e945072 3896 }
34dc7c2f 3897
193a37cb 3898 return (ret);
34dc7c2f
BB
3899}
3900
9fc60702
CS
3901static int
3902get_columns(void)
3903{
3904 struct winsize ws;
3905 int columns = 80;
3906 int error;
3907
3908 if (isatty(STDOUT_FILENO)) {
3909 error = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
3910 if (error == 0)
3911 columns = ws.ws_col;
3912 } else {
3913 columns = 999;
3914 }
3915
d1d7e268 3916 return (columns);
9fc60702
CS
3917}
3918
34dc7c2f
BB
3919int
3920get_namewidth(zpool_handle_t *zhp, void *data)
3921{
3922 iostat_cbdata_t *cb = data;
3923 nvlist_t *config, *nvroot;
9fc60702 3924 int columns;
34dc7c2f
BB
3925
3926 if ((config = zpool_get_config(zhp, NULL)) != NULL) {
3927 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3928 &nvroot) == 0);
193a37cb 3929 unsigned int poolname_len = strlen(zpool_get_name(zhp));
34dc7c2f 3930 if (!cb->cb_verbose)
2df9ad1c 3931 cb->cb_namewidth = MAX(poolname_len, cb->cb_namewidth);
34dc7c2f 3932 else
193a37cb
TH
3933 cb->cb_namewidth = MAX(poolname_len,
3934 max_width(zhp, nvroot, 0, cb->cb_namewidth,
3935 cb->cb_name_flags));
34dc7c2f 3936 }
34dc7c2f 3937 /*
9fc60702
CS
3938 * The width must be at least 10, but may be as large as the
3939 * column width - 42 so that we can still fit in one line.
34dc7c2f 3940 */
9fc60702
CS
3941 columns = get_columns();
3942
34dc7c2f
BB
3943 if (cb->cb_namewidth < 10)
3944 cb->cb_namewidth = 10;
9fc60702
CS
3945 if (cb->cb_namewidth > columns - 42)
3946 cb->cb_namewidth = columns - 42;
34dc7c2f
BB
3947
3948 return (0);
3949}
3950
3951/*
428870ff 3952 * Parse the input string, get the 'interval' and 'count' value if there is one.
34dc7c2f 3953 */
428870ff 3954static void
193a37cb 3955get_interval_count(int *argcp, char **argv, float *iv,
428870ff 3956 unsigned long *cnt)
34dc7c2f 3957{
193a37cb
TH
3958 float interval = 0;
3959 unsigned long count = 0;
1fde1e37 3960 int argc = *argcp;
34dc7c2f
BB
3961
3962 /*
3963 * Determine if the last argument is an integer or a pool name
3964 */
193a37cb 3965 if (argc > 0 && isnumber(argv[argc - 1])) {
34dc7c2f
BB
3966 char *end;
3967
3968 errno = 0;
193a37cb 3969 interval = strtof(argv[argc - 1], &end);
34dc7c2f
BB
3970
3971 if (*end == '\0' && errno == 0) {
3972 if (interval == 0) {
3973 (void) fprintf(stderr, gettext("interval "
3974 "cannot be zero\n"));
3975 usage(B_FALSE);
3976 }
34dc7c2f
BB
3977 /*
3978 * Ignore the last parameter
3979 */
3980 argc--;
3981 } else {
3982 /*
3983 * If this is not a valid number, just plow on. The
3984 * user will get a more informative error message later
3985 * on.
3986 */
3987 interval = 0;
3988 }
3989 }
3990
3991 /*
3992 * If the last argument is also an integer, then we have both a count
428870ff 3993 * and an interval.
34dc7c2f 3994 */
193a37cb 3995 if (argc > 0 && isnumber(argv[argc - 1])) {
34dc7c2f
BB
3996 char *end;
3997
3998 errno = 0;
3999 count = interval;
193a37cb 4000 interval = strtof(argv[argc - 1], &end);
34dc7c2f
BB
4001
4002 if (*end == '\0' && errno == 0) {
4003 if (interval == 0) {
4004 (void) fprintf(stderr, gettext("interval "
4005 "cannot be zero\n"));
4006 usage(B_FALSE);
4007 }
4008
4009 /*
4010 * Ignore the last parameter
4011 */
4012 argc--;
4013 } else {
4014 interval = 0;
4015 }
4016 }
4017
428870ff
BB
4018 *iv = interval;
4019 *cnt = count;
4020 *argcp = argc;
4021}
4022
4023static void
4024get_timestamp_arg(char c)
4025{
4026 if (c == 'u')
4027 timestamp_fmt = UDATE;
4028 else if (c == 'd')
4029 timestamp_fmt = DDATE;
4030 else
4031 usage(B_FALSE);
4032}
4033
4034/*
193a37cb
TH
4035 * Return stat flags that are supported by all pools by both the module and
4036 * zpool iostat. "*data" should be initialized to all 0xFFs before running.
4037 * It will get ANDed down until only the flags that are supported on all pools
4038 * remain.
4039 */
4040static int
4041get_stat_flags_cb(zpool_handle_t *zhp, void *data)
4042{
4043 uint64_t *mask = data;
4044 nvlist_t *config, *nvroot, *nvx;
4045 uint64_t flags = 0;
4046 int i, j;
4047
193a37cb
TH
4048 config = zpool_get_config(zhp, NULL);
4049 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4050 &nvroot) == 0);
4051
4052 /* Default stats are always supported, but for completeness.. */
4053 if (nvlist_exists(nvroot, ZPOOL_CONFIG_VDEV_STATS))
4054 flags |= IOS_DEFAULT_M;
4055
4056 /* Get our extended stats nvlist from the main list */
4057 if (nvlist_lookup_nvlist(nvroot, ZPOOL_CONFIG_VDEV_STATS_EX,
4058 &nvx) != 0) {
4059 /*
4060 * No extended stats; they're probably running an older
4061 * module. No big deal, we support that too.
4062 */
4063 goto end;
4064 }
4065
4066 /* For each extended stat, make sure all its nvpairs are supported */
4067 for (j = 0; j < ARRAY_SIZE(vsx_type_to_nvlist); j++) {
4068 if (!vsx_type_to_nvlist[j][0])
4069 continue;
4070
4071 /* Start off by assuming the flag is supported, then check */
4072 flags |= (1ULL << j);
4073 for (i = 0; vsx_type_to_nvlist[j][i]; i++) {
4074 if (!nvlist_exists(nvx, vsx_type_to_nvlist[j][i])) {
4075 /* flag isn't supported */
4076 flags = flags & ~(1ULL << j);
4077 break;
4078 }
4079 }
4080 }
4081end:
4082 *mask = *mask & flags;
4083 return (0);
4084}
4085
4086/*
4087 * Return a bitmask of stats that are supported on all pools by both the module
4088 * and zpool iostat.
4089 */
4090static uint64_t
4091get_stat_flags(zpool_list_t *list)
4092{
4093 uint64_t mask = -1;
4094
4095 /*
4096 * get_stat_flags_cb() will lop off bits from "mask" until only the
4097 * flags that are supported on all pools remain.
4098 */
4099 pool_list_iter(list, B_FALSE, get_stat_flags_cb, &mask);
4100 return (mask);
4101}
4102
4103/*
4104 * Return 1 if cb_data->cb_vdev_names[0] is this vdev's name, 0 otherwise.
4105 */
4106static int
4107is_vdev_cb(zpool_handle_t *zhp, nvlist_t *nv, void *cb_data)
4108{
4109 iostat_cbdata_t *cb = cb_data;
92bc9278 4110 char *name = NULL;
4111 int ret = 0;
193a37cb
TH
4112
4113 name = zpool_vdev_name(g_zfs, zhp, nv, cb->cb_name_flags);
4114
4115 if (strcmp(name, cb->cb_vdev_names[0]) == 0)
92bc9278 4116 ret = 1; /* match */
4117 free(name);
193a37cb 4118
92bc9278 4119 return (ret);
193a37cb
TH
4120}
4121
4122/*
4123 * Returns 1 if cb_data->cb_vdev_names[0] is a vdev name, 0 otherwise.
4124 */
4125static int
4126is_vdev(zpool_handle_t *zhp, void *cb_data)
4127{
4128 return (for_each_vdev(zhp, is_vdev_cb, cb_data));
4129}
4130
4131/*
4132 * Check if vdevs are in a pool
4133 *
4134 * Return 1 if all argv[] strings are vdev names in pool "pool_name". Otherwise
4135 * return 0. If pool_name is NULL, then search all pools.
4136 */
4137static int
4138are_vdevs_in_pool(int argc, char **argv, char *pool_name,
4139 iostat_cbdata_t *cb)
4140{
4141 char **tmp_name;
4142 int ret = 0;
4143 int i;
4144 int pool_count = 0;
4145
4146 if ((argc == 0) || !*argv)
4147 return (0);
4148
4149 if (pool_name)
4150 pool_count = 1;
4151
4152 /* Temporarily hijack cb_vdev_names for a second... */
4153 tmp_name = cb->cb_vdev_names;
4154
4155 /* Go though our list of prospective vdev names */
4156 for (i = 0; i < argc; i++) {
4157 cb->cb_vdev_names = argv + i;
4158
4159 /* Is this name a vdev in our pools? */
4160 ret = for_each_pool(pool_count, &pool_name, B_TRUE, NULL,
4161 is_vdev, cb);
4162 if (!ret) {
4163 /* No match */
4164 break;
4165 }
4166 }
4167
4168 cb->cb_vdev_names = tmp_name;
4169
4170 return (ret);
4171}
4172
4173static int
4174is_pool_cb(zpool_handle_t *zhp, void *data)
4175{
4176 char *name = data;
4177 if (strcmp(name, zpool_get_name(zhp)) == 0)
4178 return (1);
4179
4180 return (0);
4181}
4182
4183/*
4184 * Do we have a pool named *name? If so, return 1, otherwise 0.
4185 */
4186static int
4187is_pool(char *name)
4188{
4189 return (for_each_pool(0, NULL, B_TRUE, NULL, is_pool_cb, name));
4190}
4191
4192/* Are all our argv[] strings pool names? If so return 1, 0 otherwise. */
4193static int
4ea3f864
GM
4194are_all_pools(int argc, char **argv)
4195{
193a37cb
TH
4196 if ((argc == 0) || !*argv)
4197 return (0);
4198
4199 while (--argc >= 0)
4200 if (!is_pool(argv[argc]))
4201 return (0);
4202
4203 return (1);
4204}
4205
4206/*
4207 * Helper function to print out vdev/pool names we can't resolve. Used for an
4208 * error message.
4209 */
4210static void
4211error_list_unresolved_vdevs(int argc, char **argv, char *pool_name,
4212 iostat_cbdata_t *cb)
4213{
4214 int i;
4215 char *name;
4216 char *str;
4217 for (i = 0; i < argc; i++) {
4218 name = argv[i];
4219
4220 if (is_pool(name))
4221 str = gettext("pool");
4222 else if (are_vdevs_in_pool(1, &name, pool_name, cb))
4223 str = gettext("vdev in this pool");
4224 else if (are_vdevs_in_pool(1, &name, NULL, cb))
4225 str = gettext("vdev in another pool");
4226 else
4227 str = gettext("unknown");
4228
4229 fprintf(stderr, "\t%s (%s)\n", name, str);
4230 }
4231}
4232
4233/*
4234 * Same as get_interval_count(), but with additional checks to not misinterpret
4235 * guids as interval/count values. Assumes VDEV_NAME_GUID is set in
4236 * cb.cb_name_flags.
4237 */
4238static void
4239get_interval_count_filter_guids(int *argc, char **argv, float *interval,
4240 unsigned long *count, iostat_cbdata_t *cb)
4241{
4242 char **tmpargv = argv;
4243 int argc_for_interval = 0;
4244
4245 /* Is the last arg an interval value? Or a guid? */
4246 if (*argc >= 1 && !are_vdevs_in_pool(1, &argv[*argc - 1], NULL, cb)) {
4247 /*
4248 * The last arg is not a guid, so it's probably an
4249 * interval value.
4250 */
4251 argc_for_interval++;
4252
4253 if (*argc >= 2 &&
4254 !are_vdevs_in_pool(1, &argv[*argc - 2], NULL, cb)) {
4255 /*
4256 * The 2nd to last arg is not a guid, so it's probably
4257 * an interval value.
4258 */
4259 argc_for_interval++;
4260 }
4261 }
4262
4263 /* Point to our list of possible intervals */
4264 tmpargv = &argv[*argc - argc_for_interval];
4265
4266 *argc = *argc - argc_for_interval;
4267 get_interval_count(&argc_for_interval, tmpargv,
4268 interval, count);
4269}
4270
4271/*
4272 * Floating point sleep(). Allows you to pass in a floating point value for
4273 * seconds.
4274 */
4275static void
4ea3f864
GM
4276fsleep(float sec)
4277{
193a37cb
TH
4278 struct timespec req;
4279 req.tv_sec = floor(sec);
4280 req.tv_nsec = (sec - (float)req.tv_sec) * NANOSEC;
4281 nanosleep(&req, NULL);
4282}
4283
d6418de0
TH
4284/*
4285 * Run one of the zpool status/iostat -c scripts with the help (-h) option and
4286 * print the result.
4287 *
4288 * name: Short name of the script ('iostat').
4289 * path: Full path to the script ('/usr/local/etc/zfs/zpool.d/iostat');
4290 */
4291static void
4292print_zpool_script_help(char *name, char *path)
4293{
4294 char *argv[] = {path, "-h", NULL};
4295 char **lines = NULL;
4296 int lines_cnt = 0;
4297 int rc;
4298
4299 rc = libzfs_run_process_get_stdout_nopath(path, argv, NULL, &lines,
4300 &lines_cnt);
3e2ecae0
GDN
4301 if (rc != 0 || lines == NULL || lines_cnt <= 0) {
4302 if (lines != NULL)
4303 libzfs_free_str_array(lines, lines_cnt);
d6418de0 4304 return;
3e2ecae0 4305 }
d6418de0
TH
4306
4307 for (int i = 0; i < lines_cnt; i++)
4308 if (!is_blank_str(lines[i]))
4309 printf(" %-14s %s\n", name, lines[i]);
4310
4311 libzfs_free_str_array(lines, lines_cnt);
4312}
4313
193a37cb 4314/*
099700d9 4315 * Go though the zpool status/iostat -c scripts in the user's path, run their
d6418de0
TH
4316 * help option (-h), and print out the results.
4317 */
4318static void
099700d9 4319print_zpool_dir_scripts(char *dirpath)
d6418de0
TH
4320{
4321 DIR *dir;
4322 struct dirent *ent;
4323 char fullpath[MAXPATHLEN];
4324 struct stat dir_stat;
4325
099700d9 4326 if ((dir = opendir(dirpath)) != NULL) {
d6418de0
TH
4327 /* print all the files and directories within directory */
4328 while ((ent = readdir(dir)) != NULL) {
099700d9 4329 sprintf(fullpath, "%s/%s", dirpath, ent->d_name);
d6418de0
TH
4330
4331 /* Print the scripts */
4332 if (stat(fullpath, &dir_stat) == 0)
4333 if (dir_stat.st_mode & S_IXUSR &&
4334 S_ISREG(dir_stat.st_mode))
4335 print_zpool_script_help(ent->d_name,
4336 fullpath);
4337 }
d6418de0 4338 closedir(dir);
d6418de0
TH
4339 }
4340}
4341
099700d9
GDN
4342/*
4343 * Print out help text for all zpool status/iostat -c scripts.
4344 */
4345static void
4346print_zpool_script_list(char *subcommand)
4347{
4348 char *dir, *sp;
4349
4350 printf(gettext("Available 'zpool %s -c' commands:\n"), subcommand);
4351
4352 sp = zpool_get_cmd_search_path();
4353 if (sp == NULL)
4354 return;
4355
4356 dir = strtok(sp, ":");
4357 while (dir != NULL) {
4358 print_zpool_dir_scripts(dir);
4359 dir = strtok(NULL, ":");
4360 }
4361
4362 free(sp);
4363}
4364
d6418de0
TH
4365/*
4366 * zpool iostat [[-c [script1,script2,...]] [-lq]|[-rw]] [-ghHLpPvy] [-n name]
4367 * [-T d|u] [[ pool ...]|[pool vdev ...]|[vdev ...]]
4368 * [interval [count]]
428870ff 4369 *
8720e9e7 4370 * -c CMD For each vdev, run command CMD
d2f3e292
RY
4371 * -g Display guid for individual vdev name.
4372 * -L Follow links when resolving vdev path name.
a77f29f9 4373 * -P Display full path for vdev name.
428870ff 4374 * -v Display statistics for individual vdevs
193a37cb
TH
4375 * -h Display help
4376 * -p Display values in parsable (exact) format.
4377 * -H Scripted mode. Don't display headers, and separate properties
4378 * by a single tab.
4379 * -l Display average latency
4380 * -q Display queue depths
7e945072
TH
4381 * -w Display latency histograms
4382 * -r Display request size histogram
428870ff
BB
4383 * -T Display a timestamp in date(1) or Unix format
4384 *
4385 * This command can be tricky because we want to be able to deal with pool
4386 * creation/destruction as well as vdev configuration changes. The bulk of this
4387 * processing is handled by the pool_list_* routines in zpool_iter.c. We rely
4388 * on pool_list_update() to detect the addition of new pools. Configuration
4389 * changes are all handled within libzfs.
4390 */
4391int
4392zpool_do_iostat(int argc, char **argv)
4393{
4394 int c;
4395 int ret;
4396 int npools;
193a37cb
TH
4397 float interval = 0;
4398 unsigned long count = 0;
428870ff
BB
4399 zpool_list_t *list;
4400 boolean_t verbose = B_FALSE;
7e945072 4401 boolean_t latency = B_FALSE, l_histo = B_FALSE, rq_histo = B_FALSE;
3491d6eb 4402 boolean_t queues = B_FALSE, parsable = B_FALSE, scripted = B_FALSE;
41092124 4403 boolean_t omit_since_boot = B_FALSE;
d2f3e292
RY
4404 boolean_t guid = B_FALSE;
4405 boolean_t follow_links = B_FALSE;
4406 boolean_t full_name = B_FALSE;
4407 iostat_cbdata_t cb = { 0 };
8720e9e7 4408 char *cmd = NULL;
428870ff 4409
193a37cb
TH
4410 /* Used for printing error message */
4411 const char flag_to_arg[] = {[IOS_LATENCY] = 'l', [IOS_QUEUES] = 'q',
7e945072 4412 [IOS_L_HISTO] = 'w', [IOS_RQ_HISTO] = 'r'};
193a37cb
TH
4413
4414 uint64_t unsupported_flags;
4415
428870ff 4416 /* check options */
8720e9e7 4417 while ((c = getopt(argc, argv, "c:gLPT:vyhplqrwH")) != -1) {
428870ff 4418 switch (c) {
8720e9e7 4419 case 'c':
d6418de0
TH
4420 if (cmd != NULL) {
4421 fprintf(stderr,
4422 gettext("Can't set -c flag twice\n"));
4423 exit(1);
4424 }
099700d9
GDN
4425
4426 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
4427 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
4428 fprintf(stderr, gettext(
4429 "Can't run -c, disabled by "
4430 "ZPOOL_SCRIPTS_ENABLED.\n"));
4431 exit(1);
4432 }
4433
d6418de0
TH
4434 if ((getuid() <= 0 || geteuid() <= 0) &&
4435 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
4436 fprintf(stderr, gettext(
4437 "Can't run -c with root privileges "
4438 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
4439 exit(1);
4440 }
8720e9e7 4441 cmd = optarg;
d6418de0 4442 verbose = B_TRUE;
8720e9e7 4443 break;
d2f3e292
RY
4444 case 'g':
4445 guid = B_TRUE;
4446 break;
4447 case 'L':
4448 follow_links = B_TRUE;
4449 break;
a77f29f9 4450 case 'P':
d2f3e292
RY
4451 full_name = B_TRUE;
4452 break;
428870ff
BB
4453 case 'T':
4454 get_timestamp_arg(*optarg);
4455 break;
4456 case 'v':
4457 verbose = B_TRUE;
4458 break;
193a37cb 4459 case 'p':
3491d6eb 4460 parsable = B_TRUE;
193a37cb
TH
4461 break;
4462 case 'l':
4463 latency = B_TRUE;
4464 break;
4465 case 'q':
4466 queues = B_TRUE;
4467 break;
4468 case 'H':
4469 scripted = B_TRUE;
4470 break;
4471 case 'w':
7e945072
TH
4472 l_histo = B_TRUE;
4473 break;
4474 case 'r':
4475 rq_histo = B_TRUE;
193a37cb 4476 break;
41092124
HM
4477 case 'y':
4478 omit_since_boot = B_TRUE;
4479 break;
193a37cb
TH
4480 case 'h':
4481 usage(B_FALSE);
4482 break;
428870ff 4483 case '?':
1528bfdb 4484 if (optopt == 'c') {
099700d9 4485 print_zpool_script_list("iostat");
d6418de0 4486 exit(0);
1528bfdb
TH
4487 } else {
4488 fprintf(stderr,
4489 gettext("invalid option '%c'\n"), optopt);
4490 }
428870ff
BB
4491 usage(B_FALSE);
4492 }
4493 }
4494
4495 argc -= optind;
4496 argv += optind;
4497
3491d6eb 4498 cb.cb_literal = parsable;
193a37cb
TH
4499 cb.cb_scripted = scripted;
4500
4501 if (guid)
4502 cb.cb_name_flags |= VDEV_NAME_GUID;
4503 if (follow_links)
4504 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
4505 if (full_name)
4506 cb.cb_name_flags |= VDEV_NAME_PATH;
4507 cb.cb_iteration = 0;
4508 cb.cb_namewidth = 0;
4509 cb.cb_verbose = verbose;
4510
4511 /* Get our interval and count values (if any) */
4512 if (guid) {
4513 get_interval_count_filter_guids(&argc, argv, &interval,
4514 &count, &cb);
4515 } else {
4516 get_interval_count(&argc, argv, &interval, &count);
4517 }
4518
4519 if (argc == 0) {
4520 /* No args, so just print the defaults. */
4521 } else if (are_all_pools(argc, argv)) {
4522 /* All the args are pool names */
4523 } else if (are_vdevs_in_pool(argc, argv, NULL, &cb)) {
4524 /* All the args are vdevs */
4525 cb.cb_vdev_names = argv;
4526 cb.cb_vdev_names_count = argc;
4527 argc = 0; /* No pools to process */
4528 } else if (are_all_pools(1, argv)) {
4529 /* The first arg is a pool name */
4530 if (are_vdevs_in_pool(argc - 1, argv + 1, argv[0], &cb)) {
4531 /* ...and the rest are vdev names */
4532 cb.cb_vdev_names = argv + 1;
4533 cb.cb_vdev_names_count = argc - 1;
4534 argc = 1; /* One pool to process */
4535 } else {
4536 fprintf(stderr, gettext("Expected either a list of "));
4537 fprintf(stderr, gettext("pools, or list of vdevs in"));
4538 fprintf(stderr, " \"%s\", ", argv[0]);
4539 fprintf(stderr, gettext("but got:\n"));
4540 error_list_unresolved_vdevs(argc - 1, argv + 1,
4541 argv[0], &cb);
4542 fprintf(stderr, "\n");
4543 usage(B_FALSE);
4544 return (1);
4545 }
4546 } else {
4547 /*
4548 * The args don't make sense. The first arg isn't a pool name,
4549 * nor are all the args vdevs.
4550 */
4551 fprintf(stderr, gettext("Unable to parse pools/vdevs list.\n"));
4552 fprintf(stderr, "\n");
4553 return (1);
4554 }
4555
4556 if (cb.cb_vdev_names_count != 0) {
4557 /*
4558 * If user specified vdevs, it implies verbose.
4559 */
4560 cb.cb_verbose = B_TRUE;
4561 }
428870ff 4562
34dc7c2f
BB
4563 /*
4564 * Construct the list of all interesting pools.
4565 */
4566 ret = 0;
4567 if ((list = pool_list_get(argc, argv, NULL, &ret)) == NULL)
4568 return (1);
4569
4570 if (pool_list_count(list) == 0 && argc != 0) {
4571 pool_list_free(list);
4572 return (1);
4573 }
4574
4575 if (pool_list_count(list) == 0 && interval == 0) {
4576 pool_list_free(list);
4577 (void) fprintf(stderr, gettext("no pools available\n"));
4578 return (1);
4579 }
4580
d6418de0 4581 if ((l_histo || rq_histo) && (cmd != NULL || latency || queues)) {
7e945072
TH
4582 pool_list_free(list);
4583 (void) fprintf(stderr,
d6418de0 4584 gettext("[-r|-w] isn't allowed with [-c|-l|-q]\n"));
7e945072
TH
4585 usage(B_FALSE);
4586 return (1);
4587 }
4588
4589 if (l_histo && rq_histo) {
193a37cb
TH
4590 pool_list_free(list);
4591 (void) fprintf(stderr,
7e945072 4592 gettext("Only one of [-r|-w] can be passed at a time\n"));
193a37cb
TH
4593 usage(B_FALSE);
4594 return (1);
4595 }
4596
34dc7c2f
BB
4597 /*
4598 * Enter the main iostat loop.
4599 */
4600 cb.cb_list = list;
193a37cb 4601
7e945072 4602 if (l_histo) {
193a37cb
TH
4603 /*
4604 * Histograms tables look out of place when you try to display
4605 * them with the other stats, so make a rule that you can only
4606 * print histograms by themselves.
4607 */
4608 cb.cb_flags = IOS_L_HISTO_M;
7e945072
TH
4609 } else if (rq_histo) {
4610 cb.cb_flags = IOS_RQ_HISTO_M;
193a37cb
TH
4611 } else {
4612 cb.cb_flags = IOS_DEFAULT_M;
4613 if (latency)
4614 cb.cb_flags |= IOS_LATENCY_M;
4615 if (queues)
4616 cb.cb_flags |= IOS_QUEUES_M;
4617 }
4618
4619 /*
4620 * See if the module supports all the stats we want to display.
4621 */
4622 unsupported_flags = cb.cb_flags & ~get_stat_flags(list);
4623 if (unsupported_flags) {
4624 uint64_t f;
4625 int idx;
4626 fprintf(stderr,
4627 gettext("The loaded zfs module doesn't support:"));
4628
4629 /* for each bit set in unsupported_flags */
4630 for (f = unsupported_flags; f; f &= ~(1ULL << idx)) {
4631 idx = lowbit64(f) - 1;
4632 fprintf(stderr, " -%c", flag_to_arg[idx]);
4633 }
4634
02730c33 4635 fprintf(stderr, ". Try running a newer module.\n");
193a37cb
TH
4636 pool_list_free(list);
4637
4638 return (1);
4639 }
4640
34dc7c2f 4641 for (;;) {
34dc7c2f 4642 if ((npools = pool_list_count(list)) == 0)
42cb3819 4643 (void) fprintf(stderr, gettext("no pools available\n"));
5a521059 4644 else {
41092124
HM
4645 /*
4646 * If this is the first iteration and -y was supplied
4647 * we skip any printing.
4648 */
4649 boolean_t skip = (omit_since_boot &&
193a37cb 4650 cb.cb_iteration == 0);
41092124 4651
5a521059
PJ
4652 /*
4653 * Refresh all statistics. This is done as an
4654 * explicit step before calculating the maximum name
4655 * width, so that any * configuration changes are
4656 * properly accounted for.
4657 */
4658 (void) pool_list_iter(list, B_FALSE, refresh_iostat,
193a37cb 4659 &cb);
34dc7c2f 4660
5a521059
PJ
4661 /*
4662 * Iterate over all pools to determine the maximum width
4663 * for the pool / device name column across all pools.
4664 */
4665 cb.cb_namewidth = 0;
4666 (void) pool_list_iter(list, B_FALSE, get_namewidth,
193a37cb 4667 &cb);
34dc7c2f 4668
5a521059
PJ
4669 if (timestamp_fmt != NODATE)
4670 print_timestamp(timestamp_fmt);
428870ff 4671
d6418de0
TH
4672 if (cmd != NULL && cb.cb_verbose &&
4673 !(cb.cb_flags & IOS_ANYHISTO_M)) {
4674 cb.vcdl = all_pools_for_each_vdev_run(argc,
4675 argv, cmd, g_zfs, cb.cb_vdev_names,
4676 cb.cb_vdev_names_count, cb.cb_name_flags);
4677 } else {
4678 cb.vcdl = NULL;
4679 }
4680
5a521059 4681 /*
41092124
HM
4682 * If it's the first time and we're not skipping it,
4683 * or either skip or verbose mode, print the header.
193a37cb
TH
4684 *
4685 * The histogram code explicitly prints its header on
4686 * every vdev, so skip this for histograms.
5a521059 4687 */
193a37cb
TH
4688 if (((++cb.cb_iteration == 1 && !skip) ||
4689 (skip != verbose)) &&
7e945072 4690 (!(cb.cb_flags & IOS_ANYHISTO_M)) &&
193a37cb 4691 !cb.cb_scripted)
5a521059 4692 print_iostat_header(&cb);
34dc7c2f 4693
41092124 4694 if (skip) {
193a37cb 4695 (void) fsleep(interval);
41092124
HM
4696 continue;
4697 }
4698
8720e9e7 4699
193a37cb 4700 pool_list_iter(list, B_FALSE, print_iostat, &cb);
34dc7c2f 4701
5a521059
PJ
4702 /*
4703 * If there's more than one pool, and we're not in
4704 * verbose mode (which prints a separator for us),
4705 * then print a separator.
193a37cb
TH
4706 *
4707 * In addition, if we're printing specific vdevs then
4708 * we also want an ending separator.
5a521059 4709 */
193a37cb 4710 if (((npools > 1 && !verbose &&
7e945072
TH
4711 !(cb.cb_flags & IOS_ANYHISTO_M)) ||
4712 (!(cb.cb_flags & IOS_ANYHISTO_M) &&
193a37cb
TH
4713 cb.cb_vdev_names_count)) &&
4714 !cb.cb_scripted) {
5a521059 4715 print_iostat_separator(&cb);
d6418de0
TH
4716 if (cb.vcdl != NULL)
4717 print_cmd_columns(cb.vcdl, 1);
4718 printf("\n");
193a37cb 4719 }
d6418de0
TH
4720
4721 if (cb.vcdl != NULL)
4722 free_vdev_cmd_data_list(cb.vcdl);
4723
5a521059 4724 }
34dc7c2f
BB
4725
4726 /*
4727 * Flush the output so that redirection to a file isn't buffered
4728 * indefinitely.
4729 */
4730 (void) fflush(stdout);
4731
4732 if (interval == 0)
4733 break;
4734
4735 if (count != 0 && --count == 0)
4736 break;
4737
193a37cb 4738 (void) fsleep(interval);
34dc7c2f
BB
4739 }
4740
4741 pool_list_free(list);
4742
4743 return (ret);
4744}
4745
4746typedef struct list_cbdata {
1bd201e7 4747 boolean_t cb_verbose;
d2f3e292 4748 int cb_name_flags;
1bd201e7 4749 int cb_namewidth;
34dc7c2f 4750 boolean_t cb_scripted;
34dc7c2f 4751 zprop_list_t *cb_proplist;
2a8b84b7 4752 boolean_t cb_literal;
34dc7c2f
BB
4753} list_cbdata_t;
4754
4755/*
4756 * Given a list of columns to display, output appropriate headers for each one.
4757 */
4758static void
1bd201e7 4759print_header(list_cbdata_t *cb)
34dc7c2f 4760{
1bd201e7 4761 zprop_list_t *pl = cb->cb_proplist;
9ae529ec 4762 char headerbuf[ZPOOL_MAXPROPLEN];
34dc7c2f
BB
4763 const char *header;
4764 boolean_t first = B_TRUE;
4765 boolean_t right_justify;
1bd201e7 4766 size_t width = 0;
34dc7c2f
BB
4767
4768 for (; pl != NULL; pl = pl->pl_next) {
1bd201e7
CS
4769 width = pl->pl_width;
4770 if (first && cb->cb_verbose) {
4771 /*
4772 * Reset the width to accommodate the verbose listing
4773 * of devices.
4774 */
4775 width = cb->cb_namewidth;
4776 }
4777
34dc7c2f
BB
4778 if (!first)
4779 (void) printf(" ");
4780 else
4781 first = B_FALSE;
4782
9ae529ec
CS
4783 right_justify = B_FALSE;
4784 if (pl->pl_prop != ZPROP_INVAL) {
4785 header = zpool_prop_column_name(pl->pl_prop);
4786 right_justify = zpool_prop_align_right(pl->pl_prop);
4787 } else {
4788 int i;
4789
4790 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
4791 headerbuf[i] = toupper(pl->pl_user_prop[i]);
4792 headerbuf[i] = '\0';
4793 header = headerbuf;
4794 }
34dc7c2f
BB
4795
4796 if (pl->pl_next == NULL && !right_justify)
4797 (void) printf("%s", header);
4798 else if (right_justify)
1bd201e7 4799 (void) printf("%*s", (int)width, header);
34dc7c2f 4800 else
1bd201e7 4801 (void) printf("%-*s", (int)width, header);
34dc7c2f
BB
4802 }
4803
4804 (void) printf("\n");
4805}
4806
4807/*
4808 * Given a pool and a list of properties, print out all the properties according
4809 * to the described layout.
4810 */
4811static void
1bd201e7 4812print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
34dc7c2f 4813{
1bd201e7 4814 zprop_list_t *pl = cb->cb_proplist;
34dc7c2f
BB
4815 boolean_t first = B_TRUE;
4816 char property[ZPOOL_MAXPROPLEN];
4817 char *propstr;
4818 boolean_t right_justify;
1bd201e7 4819 size_t width;
34dc7c2f
BB
4820
4821 for (; pl != NULL; pl = pl->pl_next) {
1bd201e7
CS
4822
4823 width = pl->pl_width;
4824 if (first && cb->cb_verbose) {
4825 /*
4826 * Reset the width to accommodate the verbose listing
4827 * of devices.
4828 */
4829 width = cb->cb_namewidth;
4830 }
4831
34dc7c2f 4832 if (!first) {
1bd201e7 4833 if (cb->cb_scripted)
34dc7c2f
BB
4834 (void) printf("\t");
4835 else
4836 (void) printf(" ");
4837 } else {
4838 first = B_FALSE;
4839 }
4840
4841 right_justify = B_FALSE;
4842 if (pl->pl_prop != ZPROP_INVAL) {
a05dfd00 4843 if (zpool_get_prop(zhp, pl->pl_prop, property,
2a8b84b7 4844 sizeof (property), NULL, cb->cb_literal) != 0)
34dc7c2f
BB
4845 propstr = "-";
4846 else
4847 propstr = property;
4848
4849 right_justify = zpool_prop_align_right(pl->pl_prop);
9ae529ec
CS
4850 } else if ((zpool_prop_feature(pl->pl_user_prop) ||
4851 zpool_prop_unsupported(pl->pl_user_prop)) &&
4852 zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
4853 sizeof (property)) == 0) {
4854 propstr = property;
34dc7c2f
BB
4855 } else {
4856 propstr = "-";
4857 }
4858
34dc7c2f
BB
4859
4860 /*
4861 * If this is being called in scripted mode, or if this is the
4862 * last column and it is left-justified, don't include a width
4863 * format specifier.
4864 */
1bd201e7 4865 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
34dc7c2f
BB
4866 (void) printf("%s", propstr);
4867 else if (right_justify)
1bd201e7 4868 (void) printf("%*s", (int)width, propstr);
34dc7c2f 4869 else
1bd201e7 4870 (void) printf("%-*s", (int)width, propstr);
34dc7c2f
BB
4871 }
4872
4873 (void) printf("\n");
4874}
4875
1bd201e7 4876static void
a05dfd00 4877print_one_column(zpool_prop_t prop, uint64_t value, boolean_t scripted,
bc2d8093 4878 boolean_t valid, enum zfs_nicenum_format format)
1bd201e7
CS
4879{
4880 char propval[64];
4881 boolean_t fixed;
4882 size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
4883
a05dfd00
GW
4884 switch (prop) {
4885 case ZPOOL_PROP_EXPANDSZ:
4886 if (value == 0)
4887 (void) strlcpy(propval, "-", sizeof (propval));
4888 else
bc2d8093
CE
4889 zfs_nicenum_format(value, propval, sizeof (propval),
4890 format);
a05dfd00
GW
4891 break;
4892 case ZPOOL_PROP_FRAGMENTATION:
4893 if (value == ZFS_FRAG_INVALID) {
4894 (void) strlcpy(propval, "-", sizeof (propval));
bc2d8093
CE
4895 } else if (format == ZFS_NICENUM_RAW) {
4896 (void) snprintf(propval, sizeof (propval), "%llu",
4897 (unsigned long long)value);
a05dfd00
GW
4898 } else {
4899 (void) snprintf(propval, sizeof (propval), "%llu%%",
4900 (unsigned long long)value);
4901 }
4902 break;
4903 case ZPOOL_PROP_CAPACITY:
bc2d8093
CE
4904 if (format == ZFS_NICENUM_RAW)
4905 (void) snprintf(propval, sizeof (propval), "%llu",
4906 (unsigned long long)value);
4907 else
4908 (void) snprintf(propval, sizeof (propval), "%llu%%",
4909 (unsigned long long)value);
a05dfd00
GW
4910 break;
4911 default:
bc2d8093 4912 zfs_nicenum_format(value, propval, sizeof (propval), format);
a05dfd00
GW
4913 }
4914
4915 if (!valid)
4916 (void) strlcpy(propval, "-", sizeof (propval));
1bd201e7
CS
4917
4918 if (scripted)
4919 (void) printf("\t%s", propval);
4920 else
4921 (void) printf(" %*s", (int)width, propval);
4922}
4923
4924void
4925print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
4926 list_cbdata_t *cb, int depth)
4927{
4928 nvlist_t **child;
4929 vdev_stat_t *vs;
4930 uint_t c, children;
4931 char *vname;
4932 boolean_t scripted = cb->cb_scripted;
8e4c5c9a
JWK
4933 uint64_t islog = B_FALSE;
4934 boolean_t haslog = B_FALSE;
4935 char *dashes = "%-*s - - - - - -\n";
1bd201e7
CS
4936
4937 verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
4938 (uint64_t **)&vs, &c) == 0);
4939
4940 if (name != NULL) {
a05dfd00
GW
4941 boolean_t toplevel = (vs->vs_space != 0);
4942 uint64_t cap;
bc2d8093
CE
4943 enum zfs_nicenum_format format;
4944
4945 if (cb->cb_literal)
4946 format = ZFS_NICENUM_RAW;
4947 else
4948 format = ZFS_NICENUM_1024;
a05dfd00 4949
1bd201e7
CS
4950 if (scripted)
4951 (void) printf("\t%s", name);
4952 else if (strlen(name) + depth > cb->cb_namewidth)
4953 (void) printf("%*s%s", depth, "", name);
4954 else
4955 (void) printf("%*s%s%*s", depth, "", name,
4956 (int)(cb->cb_namewidth - strlen(name) - depth), "");
4957
a05dfd00
GW
4958 /*
4959 * Print the properties for the individual vdevs. Some
4960 * properties are only applicable to toplevel vdevs. The
4961 * 'toplevel' boolean value is passed to the print_one_column()
4962 * to indicate that the value is valid.
4963 */
4964 print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, scripted,
bc2d8093 4965 toplevel, format);
a05dfd00 4966 print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, scripted,
bc2d8093 4967 toplevel, format);
a05dfd00 4968 print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
bc2d8093 4969 scripted, toplevel, format);
a05dfd00 4970 print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, scripted,
bc2d8093 4971 B_TRUE, format);
a05dfd00
GW
4972 print_one_column(ZPOOL_PROP_FRAGMENTATION,
4973 vs->vs_fragmentation, scripted,
bc2d8093
CE
4974 (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel),
4975 format);
a05dfd00
GW
4976 cap = (vs->vs_space == 0) ? 0 :
4977 (vs->vs_alloc * 100 / vs->vs_space);
bc2d8093
CE
4978 print_one_column(ZPOOL_PROP_CAPACITY, cap, scripted, toplevel,
4979 format);
1bd201e7
CS
4980 (void) printf("\n");
4981 }
4982
4983 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
4984 &child, &children) != 0)
4985 return;
4986
4987 for (c = 0; c < children; c++) {
4988 uint64_t ishole = B_FALSE;
4989
4990 if (nvlist_lookup_uint64(child[c],
4991 ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
4992 continue;
4993
8e4c5c9a
JWK
4994 if (nvlist_lookup_uint64(child[c],
4995 ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog) {
4996 haslog = B_TRUE;
4997 continue;
4998 }
4999
d2f3e292
RY
5000 vname = zpool_vdev_name(g_zfs, zhp, child[c],
5001 cb->cb_name_flags);
1bd201e7
CS
5002 print_list_stats(zhp, vname, child[c], cb, depth + 2);
5003 free(vname);
5004 }
5005
8e4c5c9a
JWK
5006 if (haslog == B_TRUE) {
5007 /* LINTED E_SEC_PRINTF_VAR_FMT */
5008 (void) printf(dashes, cb->cb_namewidth, "log");
5009 for (c = 0; c < children; c++) {
5010 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
5011 &islog) != 0 || !islog)
5012 continue;
d2f3e292
RY
5013 vname = zpool_vdev_name(g_zfs, zhp, child[c],
5014 cb->cb_name_flags);
8e4c5c9a
JWK
5015 print_list_stats(zhp, vname, child[c], cb, depth + 2);
5016 free(vname);
5017 }
5018 }
5019
1bd201e7 5020 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
8e4c5c9a
JWK
5021 &child, &children) == 0 && children > 0) {
5022 /* LINTED E_SEC_PRINTF_VAR_FMT */
5023 (void) printf(dashes, cb->cb_namewidth, "cache");
5024 for (c = 0; c < children; c++) {
d2f3e292
RY
5025 vname = zpool_vdev_name(g_zfs, zhp, child[c],
5026 cb->cb_name_flags);
8e4c5c9a
JWK
5027 print_list_stats(zhp, vname, child[c], cb, depth + 2);
5028 free(vname);
5029 }
5030 }
1bd201e7 5031
8e4c5c9a
JWK
5032 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
5033 &children) == 0 && children > 0) {
5034 /* LINTED E_SEC_PRINTF_VAR_FMT */
5035 (void) printf(dashes, cb->cb_namewidth, "spare");
1bd201e7 5036 for (c = 0; c < children; c++) {
d2f3e292
RY
5037 vname = zpool_vdev_name(g_zfs, zhp, child[c],
5038 cb->cb_name_flags);
1bd201e7
CS
5039 print_list_stats(zhp, vname, child[c], cb, depth + 2);
5040 free(vname);
5041 }
5042 }
5043}
5044
5045
34dc7c2f
BB
5046/*
5047 * Generic callback function to list a pool.
5048 */
5049int
5050list_callback(zpool_handle_t *zhp, void *data)
5051{
5052 list_cbdata_t *cbp = data;
1bd201e7
CS
5053 nvlist_t *config;
5054 nvlist_t *nvroot;
34dc7c2f 5055
1bd201e7 5056 config = zpool_get_config(zhp, NULL);
34dc7c2f 5057
1bd201e7
CS
5058 print_pool(zhp, cbp);
5059 if (!cbp->cb_verbose)
5060 return (0);
5061
5062 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5063 &nvroot) == 0);
5064 print_list_stats(zhp, NULL, nvroot, cbp, 0);
34dc7c2f
BB
5065
5066 return (0);
5067}
5068
5069/*
2a8b84b7 5070 * zpool list [-gHLpP] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
34dc7c2f 5071 *
d2f3e292 5072 * -g Display guid for individual vdev name.
34dc7c2f
BB
5073 * -H Scripted mode. Don't display headers, and separate properties
5074 * by a single tab.
d2f3e292 5075 * -L Follow links when resolving vdev path name.
34dc7c2f 5076 * -o List of properties to display. Defaults to
a05dfd00
GW
5077 * "name,size,allocated,free,expandsize,fragmentation,capacity,"
5078 * "dedupratio,health,altroot"
2a8b84b7 5079 * -p Display values in parsable (exact) format.
a77f29f9 5080 * -P Display full path for vdev name.
428870ff 5081 * -T Display a timestamp in date(1) or Unix format
34dc7c2f
BB
5082 *
5083 * List all pools in the system, whether or not they're healthy. Output space
5084 * statistics for each one, as well as health status summary.
5085 */
5086int
5087zpool_do_list(int argc, char **argv)
5088{
5089 int c;
cd72af9c 5090 int ret = 0;
34dc7c2f
BB
5091 list_cbdata_t cb = { 0 };
5092 static char default_props[] =
a05dfd00 5093 "name,size,allocated,free,expandsize,fragmentation,capacity,"
f3a7f661 5094 "dedupratio,health,altroot";
34dc7c2f 5095 char *props = default_props;
193a37cb
TH
5096 float interval = 0;
5097 unsigned long count = 0;
1bd201e7
CS
5098 zpool_list_t *list;
5099 boolean_t first = B_TRUE;
34dc7c2f
BB
5100
5101 /* check options */
2a8b84b7 5102 while ((c = getopt(argc, argv, ":gHLo:pPT:v")) != -1) {
34dc7c2f 5103 switch (c) {
d2f3e292
RY
5104 case 'g':
5105 cb.cb_name_flags |= VDEV_NAME_GUID;
5106 break;
34dc7c2f
BB
5107 case 'H':
5108 cb.cb_scripted = B_TRUE;
5109 break;
d2f3e292
RY
5110 case 'L':
5111 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
5112 break;
34dc7c2f
BB
5113 case 'o':
5114 props = optarg;
5115 break;
a77f29f9 5116 case 'P':
d2f3e292
RY
5117 cb.cb_name_flags |= VDEV_NAME_PATH;
5118 break;
2a8b84b7
AS
5119 case 'p':
5120 cb.cb_literal = B_TRUE;
5121 break;
428870ff
BB
5122 case 'T':
5123 get_timestamp_arg(*optarg);
5124 break;
1bd201e7
CS
5125 case 'v':
5126 cb.cb_verbose = B_TRUE;
5127 break;
34dc7c2f
BB
5128 case ':':
5129 (void) fprintf(stderr, gettext("missing argument for "
5130 "'%c' option\n"), optopt);
5131 usage(B_FALSE);
5132 break;
5133 case '?':
5134 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5135 optopt);
5136 usage(B_FALSE);
5137 }
5138 }
5139
5140 argc -= optind;
5141 argv += optind;
5142
428870ff
BB
5143 get_interval_count(&argc, argv, &interval, &count);
5144
34dc7c2f
BB
5145 if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
5146 usage(B_FALSE);
5147
428870ff 5148 for (;;) {
3e43edd2
GW
5149 if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
5150 &ret)) == NULL)
5151 return (1);
1bd201e7
CS
5152
5153 if (pool_list_count(list) == 0)
5154 break;
34dc7c2f 5155
428870ff
BB
5156 if (timestamp_fmt != NODATE)
5157 print_timestamp(timestamp_fmt);
34dc7c2f 5158
1bd201e7
CS
5159 if (!cb.cb_scripted && (first || cb.cb_verbose)) {
5160 print_header(&cb);
5161 first = B_FALSE;
428870ff 5162 }
1bd201e7 5163 ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
428870ff
BB
5164
5165 if (interval == 0)
5166 break;
5167
5168 if (count != 0 && --count == 0)
5169 break;
5170
3e43edd2 5171 pool_list_free(list);
193a37cb 5172 (void) fsleep(interval);
34dc7c2f
BB
5173 }
5174
3e43edd2
GW
5175 if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
5176 (void) printf(gettext("no pools available\n"));
5177 ret = 0;
5178 }
5179
5180 pool_list_free(list);
428870ff 5181 zprop_free_list(cb.cb_proplist);
34dc7c2f
BB
5182 return (ret);
5183}
5184
34dc7c2f
BB
5185static int
5186zpool_do_attach_or_replace(int argc, char **argv, int replacing)
5187{
5188 boolean_t force = B_FALSE;
5189 int c;
5190 nvlist_t *nvroot;
5191 char *poolname, *old_disk, *new_disk;
5192 zpool_handle_t *zhp;
df831108
CP
5193 nvlist_t *props = NULL;
5194 char *propval;
34dc7c2f
BB
5195 int ret;
5196
5197 /* check options */
4588bf57 5198 while ((c = getopt(argc, argv, "fo:")) != -1) {
34dc7c2f
BB
5199 switch (c) {
5200 case 'f':
5201 force = B_TRUE;
5202 break;
df831108
CP
5203 case 'o':
5204 if ((propval = strchr(optarg, '=')) == NULL) {
5205 (void) fprintf(stderr, gettext("missing "
5206 "'=' for -o option\n"));
5207 usage(B_FALSE);
5208 }
5209 *propval = '\0';
5210 propval++;
5211
5212 if ((strcmp(optarg, ZPOOL_CONFIG_ASHIFT) != 0) ||
5213 (add_prop_list(optarg, propval, &props, B_TRUE)))
5214 usage(B_FALSE);
5215 break;
34dc7c2f
BB
5216 case '?':
5217 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5218 optopt);
5219 usage(B_FALSE);
5220 }
5221 }
5222
5223 argc -= optind;
5224 argv += optind;
5225
5226 /* get pool name and check number of arguments */
5227 if (argc < 1) {
5228 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5229 usage(B_FALSE);
5230 }
5231
5232 poolname = argv[0];
5233
5234 if (argc < 2) {
5235 (void) fprintf(stderr,
5236 gettext("missing <device> specification\n"));
5237 usage(B_FALSE);
5238 }
5239
5240 old_disk = argv[1];
5241
5242 if (argc < 3) {
5243 if (!replacing) {
5244 (void) fprintf(stderr,
5245 gettext("missing <new_device> specification\n"));
5246 usage(B_FALSE);
5247 }
5248 new_disk = old_disk;
5249 argc -= 1;
5250 argv += 1;
5251 } else {
5252 new_disk = argv[2];
5253 argc -= 2;
5254 argv += 2;
5255 }
5256
5257 if (argc > 1) {
5258 (void) fprintf(stderr, gettext("too many arguments\n"));
5259 usage(B_FALSE);
5260 }
5261
a425f5bf 5262 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
5263 nvlist_free(props);
34dc7c2f 5264 return (1);
a425f5bf 5265 }
34dc7c2f
BB
5266
5267 if (zpool_get_config(zhp, NULL) == NULL) {
5268 (void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
5269 poolname);
5270 zpool_close(zhp);
a425f5bf 5271 nvlist_free(props);
34dc7c2f
BB
5272 return (1);
5273 }
5274
dddef7d6 5275 /* unless manually specified use "ashift" pool property (if set) */
5276 if (!nvlist_exists(props, ZPOOL_CONFIG_ASHIFT)) {
5277 int intval;
5278 zprop_source_t src;
5279 char strval[ZPOOL_MAXPROPLEN];
5280
5281 intval = zpool_get_prop_int(zhp, ZPOOL_PROP_ASHIFT, &src);
5282 if (src != ZPROP_SRC_DEFAULT) {
5283 (void) sprintf(strval, "%" PRId32, intval);
5284 verify(add_prop_list(ZPOOL_CONFIG_ASHIFT, strval,
5285 &props, B_TRUE) == 0);
5286 }
5287 }
5288
df831108 5289 nvroot = make_root_vdev(zhp, props, force, B_FALSE, replacing, B_FALSE,
b128c09f 5290 argc, argv);
34dc7c2f
BB
5291 if (nvroot == NULL) {
5292 zpool_close(zhp);
a425f5bf 5293 nvlist_free(props);
34dc7c2f
BB
5294 return (1);
5295 }
5296
5297 ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing);
5298
a425f5bf 5299 nvlist_free(props);
34dc7c2f
BB
5300 nvlist_free(nvroot);
5301 zpool_close(zhp);
5302
5303 return (ret);
5304}
5305
5306/*
5307 * zpool replace [-f] <pool> <device> <new_device>
5308 *
5309 * -f Force attach, even if <new_device> appears to be in use.
5310 *
5311 * Replace <device> with <new_device>.
5312 */
5313/* ARGSUSED */
5314int
5315zpool_do_replace(int argc, char **argv)
5316{
5317 return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
5318}
5319
5320/*
df831108 5321 * zpool attach [-f] [-o property=value] <pool> <device> <new_device>
34dc7c2f
BB
5322 *
5323 * -f Force attach, even if <new_device> appears to be in use.
df831108 5324 * -o Set property=value.
34dc7c2f
BB
5325 *
5326 * Attach <new_device> to the mirror containing <device>. If <device> is not
5327 * part of a mirror, then <device> will be transformed into a mirror of
5328 * <device> and <new_device>. In either case, <new_device> will begin life
5329 * with a DTL of [0, now], and will immediately begin to resilver itself.
5330 */
5331int
5332zpool_do_attach(int argc, char **argv)
5333{
5334 return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
5335}
5336
5337/*
5338 * zpool detach [-f] <pool> <device>
5339 *
5340 * -f Force detach of <device>, even if DTLs argue against it
5341 * (not supported yet)
5342 *
5343 * Detach a device from a mirror. The operation will be refused if <device>
5344 * is the last device in the mirror, or if the DTLs indicate that this device
5345 * has the only valid copy of some data.
5346 */
5347/* ARGSUSED */
5348int
5349zpool_do_detach(int argc, char **argv)
5350{
5351 int c;
5352 char *poolname, *path;
5353 zpool_handle_t *zhp;
5354 int ret;
5355
5356 /* check options */
5357 while ((c = getopt(argc, argv, "f")) != -1) {
5358 switch (c) {
5359 case 'f':
5360 case '?':
5361 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5362 optopt);
5363 usage(B_FALSE);
5364 }
5365 }
5366
5367 argc -= optind;
5368 argv += optind;
5369
5370 /* get pool name and check number of arguments */
5371 if (argc < 1) {
5372 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5373 usage(B_FALSE);
5374 }
5375
5376 if (argc < 2) {
5377 (void) fprintf(stderr,
5378 gettext("missing <device> specification\n"));
5379 usage(B_FALSE);
5380 }
5381
5382 poolname = argv[0];
5383 path = argv[1];
5384
5385 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5386 return (1);
5387
5388 ret = zpool_vdev_detach(zhp, path);
5389
5390 zpool_close(zhp);
5391
5392 return (ret);
5393}
5394
428870ff 5395/*
a77f29f9 5396 * zpool split [-gLnP] [-o prop=val] ...
428870ff
BB
5397 * [-o mntopt] ...
5398 * [-R altroot] <pool> <newpool> [<device> ...]
5399 *
d2f3e292
RY
5400 * -g Display guid for individual vdev name.
5401 * -L Follow links when resolving vdev path name.
428870ff
BB
5402 * -n Do not split the pool, but display the resulting layout if
5403 * it were to be split.
5404 * -o Set property=value, or set mount options.
a77f29f9 5405 * -P Display full path for vdev name.
428870ff 5406 * -R Mount the split-off pool under an alternate root.
b5256303 5407 * -l Load encryption keys while importing.
428870ff
BB
5408 *
5409 * Splits the named pool and gives it the new pool name. Devices to be split
5410 * off may be listed, provided that no more than one device is specified
5411 * per top-level vdev mirror. The newly split pool is left in an exported
5412 * state unless -R is specified.
5413 *
5414 * Restrictions: the top-level of the pool pool must only be made up of
5415 * mirrors; all devices in the pool must be healthy; no device may be
5416 * undergoing a resilvering operation.
5417 */
5418int
5419zpool_do_split(int argc, char **argv)
5420{
5421 char *srcpool, *newpool, *propval;
5422 char *mntopts = NULL;
5423 splitflags_t flags;
5424 int c, ret = 0;
b5256303 5425 boolean_t loadkeys = B_FALSE;
428870ff
BB
5426 zpool_handle_t *zhp;
5427 nvlist_t *config, *props = NULL;
5428
5429 flags.dryrun = B_FALSE;
5430 flags.import = B_FALSE;
d2f3e292 5431 flags.name_flags = 0;
428870ff
BB
5432
5433 /* check options */
b5256303 5434 while ((c = getopt(argc, argv, ":gLR:lno:P")) != -1) {
428870ff 5435 switch (c) {
d2f3e292
RY
5436 case 'g':
5437 flags.name_flags |= VDEV_NAME_GUID;
5438 break;
5439 case 'L':
5440 flags.name_flags |= VDEV_NAME_FOLLOW_LINKS;
5441 break;
428870ff
BB
5442 case 'R':
5443 flags.import = B_TRUE;
5444 if (add_prop_list(
5445 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
5446 &props, B_TRUE) != 0) {
8a5fc748 5447 nvlist_free(props);
428870ff
BB
5448 usage(B_FALSE);
5449 }
5450 break;
b5256303
TC
5451 case 'l':
5452 loadkeys = B_TRUE;
5453 break;
428870ff
BB
5454 case 'n':
5455 flags.dryrun = B_TRUE;
5456 break;
5457 case 'o':
5458 if ((propval = strchr(optarg, '=')) != NULL) {
5459 *propval = '\0';
5460 propval++;
5461 if (add_prop_list(optarg, propval,
5462 &props, B_TRUE) != 0) {
8a5fc748 5463 nvlist_free(props);
428870ff
BB
5464 usage(B_FALSE);
5465 }
5466 } else {
5467 mntopts = optarg;
5468 }
5469 break;
a77f29f9 5470 case 'P':
d2f3e292
RY
5471 flags.name_flags |= VDEV_NAME_PATH;
5472 break;
428870ff
BB
5473 case ':':
5474 (void) fprintf(stderr, gettext("missing argument for "
5475 "'%c' option\n"), optopt);
5476 usage(B_FALSE);
5477 break;
5478 case '?':
5479 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5480 optopt);
5481 usage(B_FALSE);
5482 break;
5483 }
5484 }
5485
5486 if (!flags.import && mntopts != NULL) {
5487 (void) fprintf(stderr, gettext("setting mntopts is only "
5488 "valid when importing the pool\n"));
5489 usage(B_FALSE);
5490 }
5491
b5256303
TC
5492 if (!flags.import && loadkeys) {
5493 (void) fprintf(stderr, gettext("loading keys is only "
5494 "valid when importing the pool\n"));
5495 usage(B_FALSE);
5496 }
5497
428870ff
BB
5498 argc -= optind;
5499 argv += optind;
5500
5501 if (argc < 1) {
5502 (void) fprintf(stderr, gettext("Missing pool name\n"));
5503 usage(B_FALSE);
5504 }
5505 if (argc < 2) {
5506 (void) fprintf(stderr, gettext("Missing new pool name\n"));
5507 usage(B_FALSE);
5508 }
5509
5510 srcpool = argv[0];
5511 newpool = argv[1];
5512
5513 argc -= 2;
5514 argv += 2;
5515
a425f5bf 5516 if ((zhp = zpool_open(g_zfs, srcpool)) == NULL) {
5517 nvlist_free(props);
428870ff 5518 return (1);
a425f5bf 5519 }
428870ff
BB
5520
5521 config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
5522 if (config == NULL) {
5523 ret = 1;
5524 } else {
5525 if (flags.dryrun) {
5526 (void) printf(gettext("would create '%s' with the "
5527 "following layout:\n\n"), newpool);
d2f3e292
RY
5528 print_vdev_tree(NULL, newpool, config, 0, B_FALSE,
5529 flags.name_flags);
428870ff 5530 }
428870ff
BB
5531 }
5532
5533 zpool_close(zhp);
5534
a425f5bf 5535 if (ret != 0 || flags.dryrun || !flags.import) {
5536 nvlist_free(config);
5537 nvlist_free(props);
428870ff 5538 return (ret);
a425f5bf 5539 }
428870ff
BB
5540
5541 /*
5542 * The split was successful. Now we need to open the new
5543 * pool and import it.
5544 */
a425f5bf 5545 if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL) {
5546 nvlist_free(config);
5547 nvlist_free(props);
428870ff 5548 return (1);
a425f5bf 5549 }
b5256303
TC
5550
5551 if (loadkeys) {
5552 ret = zfs_crypto_attempt_load_keys(g_zfs, newpool);
5553 if (ret != 0)
5554 ret = 1;
5555 }
5556
428870ff
BB
5557 if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
5558 zpool_enable_datasets(zhp, mntopts, 0) != 0) {
5559 ret = 1;
af909a10 5560 (void) fprintf(stderr, gettext("Split was successful, but "
428870ff
BB
5561 "the datasets could not all be mounted\n"));
5562 (void) fprintf(stderr, gettext("Try doing '%s' with a "
5563 "different altroot\n"), "zpool import");
5564 }
5565 zpool_close(zhp);
a425f5bf 5566 nvlist_free(config);
5567 nvlist_free(props);
428870ff
BB
5568
5569 return (ret);
5570}
5571
5572
5573
34dc7c2f
BB
5574/*
5575 * zpool online <pool> <device> ...
5576 */
5577int
5578zpool_do_online(int argc, char **argv)
5579{
5580 int c, i;
5581 char *poolname;
5582 zpool_handle_t *zhp;
5583 int ret = 0;
5584 vdev_state_t newstate;
9babb374 5585 int flags = 0;
34dc7c2f
BB
5586
5587 /* check options */
9babb374 5588 while ((c = getopt(argc, argv, "et")) != -1) {
34dc7c2f 5589 switch (c) {
9babb374
BB
5590 case 'e':
5591 flags |= ZFS_ONLINE_EXPAND;
5592 break;
34dc7c2f
BB
5593 case 't':
5594 case '?':
5595 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5596 optopt);
5597 usage(B_FALSE);
5598 }
5599 }
5600
5601 argc -= optind;
5602 argv += optind;
5603
5604 /* get pool name and check number of arguments */
5605 if (argc < 1) {
5606 (void) fprintf(stderr, gettext("missing pool name\n"));
5607 usage(B_FALSE);
5608 }
5609 if (argc < 2) {
5610 (void) fprintf(stderr, gettext("missing device name\n"));
5611 usage(B_FALSE);
5612 }
5613
5614 poolname = argv[0];
5615
5616 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5617 return (1);
5618
5619 for (i = 1; i < argc; i++) {
9babb374 5620 if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
34dc7c2f
BB
5621 if (newstate != VDEV_STATE_HEALTHY) {
5622 (void) printf(gettext("warning: device '%s' "
5623 "onlined, but remains in faulted state\n"),
5624 argv[i]);
5625 if (newstate == VDEV_STATE_FAULTED)
5626 (void) printf(gettext("use 'zpool "
5627 "clear' to restore a faulted "
5628 "device\n"));
5629 else
5630 (void) printf(gettext("use 'zpool "
5631 "replace' to replace devices "
5632 "that are no longer present\n"));
5633 }
5634 } else {
5635 ret = 1;
5636 }
5637 }
5638
5639 zpool_close(zhp);
5640
5641 return (ret);
5642}
5643
5644/*
5645 * zpool offline [-ft] <pool> <device> ...
5646 *
4a283c7f 5647 * -f Force the device into a faulted state.
34dc7c2f 5648 *
4a283c7f 5649 * -t Only take the device off-line temporarily. The offline/faulted
34dc7c2f
BB
5650 * state will not be persistent across reboots.
5651 */
5652/* ARGSUSED */
5653int
5654zpool_do_offline(int argc, char **argv)
5655{
5656 int c, i;
5657 char *poolname;
5658 zpool_handle_t *zhp;
5659 int ret = 0;
5660 boolean_t istmp = B_FALSE;
4a283c7f 5661 boolean_t fault = B_FALSE;
34dc7c2f
BB
5662
5663 /* check options */
5664 while ((c = getopt(argc, argv, "ft")) != -1) {
5665 switch (c) {
4a283c7f
TH
5666 case 'f':
5667 fault = B_TRUE;
5668 break;
34dc7c2f
BB
5669 case 't':
5670 istmp = B_TRUE;
5671 break;
34dc7c2f
BB
5672 case '?':
5673 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5674 optopt);
5675 usage(B_FALSE);
5676 }
5677 }
5678
5679 argc -= optind;
5680 argv += optind;
5681
5682 /* get pool name and check number of arguments */
5683 if (argc < 1) {
5684 (void) fprintf(stderr, gettext("missing pool name\n"));
5685 usage(B_FALSE);
5686 }
5687 if (argc < 2) {
5688 (void) fprintf(stderr, gettext("missing device name\n"));
5689 usage(B_FALSE);
5690 }
5691
5692 poolname = argv[0];
5693
5694 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5695 return (1);
5696
5697 for (i = 1; i < argc; i++) {
4a283c7f
TH
5698 if (fault) {
5699 uint64_t guid = zpool_vdev_path_to_guid(zhp, argv[i]);
5700 vdev_aux_t aux;
5701 if (istmp == B_FALSE) {
5702 /* Force the fault to persist across imports */
5703 aux = VDEV_AUX_EXTERNAL_PERSIST;
5704 } else {
5705 aux = VDEV_AUX_EXTERNAL;
5706 }
5707
5708 if (guid == 0 || zpool_vdev_fault(zhp, guid, aux) != 0)
5709 ret = 1;
5710 } else {
5711 if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
5712 ret = 1;
5713 }
34dc7c2f
BB
5714 }
5715
5716 zpool_close(zhp);
5717
5718 return (ret);
5719}
5720
5721/*
5722 * zpool clear <pool> [device]
5723 *
5724 * Clear all errors associated with a pool or a particular device.
5725 */
5726int
5727zpool_do_clear(int argc, char **argv)
5728{
428870ff 5729 int c;
34dc7c2f 5730 int ret = 0;
428870ff
BB
5731 boolean_t dryrun = B_FALSE;
5732 boolean_t do_rewind = B_FALSE;
5733 boolean_t xtreme_rewind = B_FALSE;
5734 uint32_t rewind_policy = ZPOOL_NO_REWIND;
5735 nvlist_t *policy = NULL;
34dc7c2f
BB
5736 zpool_handle_t *zhp;
5737 char *pool, *device;
5738
428870ff
BB
5739 /* check options */
5740 while ((c = getopt(argc, argv, "FnX")) != -1) {
5741 switch (c) {
5742 case 'F':
5743 do_rewind = B_TRUE;
5744 break;
5745 case 'n':
5746 dryrun = B_TRUE;
5747 break;
5748 case 'X':
5749 xtreme_rewind = B_TRUE;
5750 break;
5751 case '?':
5752 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5753 optopt);
5754 usage(B_FALSE);
5755 }
5756 }
5757
5758 argc -= optind;
5759 argv += optind;
5760
5761 if (argc < 1) {
34dc7c2f
BB
5762 (void) fprintf(stderr, gettext("missing pool name\n"));
5763 usage(B_FALSE);
5764 }
5765
428870ff 5766 if (argc > 2) {
34dc7c2f
BB
5767 (void) fprintf(stderr, gettext("too many arguments\n"));
5768 usage(B_FALSE);
5769 }
5770
428870ff
BB
5771 if ((dryrun || xtreme_rewind) && !do_rewind) {
5772 (void) fprintf(stderr,
5773 gettext("-n or -X only meaningful with -F\n"));
5774 usage(B_FALSE);
5775 }
5776 if (dryrun)
5777 rewind_policy = ZPOOL_TRY_REWIND;
5778 else if (do_rewind)
5779 rewind_policy = ZPOOL_DO_REWIND;
5780 if (xtreme_rewind)
5781 rewind_policy |= ZPOOL_EXTREME_REWIND;
5782
5783 /* In future, further rewind policy choices can be passed along here */
5784 if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
5785 nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
5786 return (1);
5787
5788 pool = argv[0];
5789 device = argc == 2 ? argv[1] : NULL;
34dc7c2f 5790
428870ff
BB
5791 if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
5792 nvlist_free(policy);
34dc7c2f 5793 return (1);
428870ff 5794 }
34dc7c2f 5795
428870ff 5796 if (zpool_clear(zhp, device, policy) != 0)
34dc7c2f
BB
5797 ret = 1;
5798
5799 zpool_close(zhp);
5800
428870ff
BB
5801 nvlist_free(policy);
5802
34dc7c2f
BB
5803 return (ret);
5804}
5805
3541dc6d
GA
5806/*
5807 * zpool reguid <pool>
5808 */
5809int
5810zpool_do_reguid(int argc, char **argv)
5811{
5812 int c;
5813 char *poolname;
5814 zpool_handle_t *zhp;
5815 int ret = 0;
5816
5817 /* check options */
5818 while ((c = getopt(argc, argv, "")) != -1) {
5819 switch (c) {
5820 case '?':
5821 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5822 optopt);
5823 usage(B_FALSE);
5824 }
5825 }
5826
5827 argc -= optind;
5828 argv += optind;
5829
5830 /* get pool name and check number of arguments */
5831 if (argc < 1) {
5832 (void) fprintf(stderr, gettext("missing pool name\n"));
5833 usage(B_FALSE);
5834 }
5835
5836 if (argc > 1) {
5837 (void) fprintf(stderr, gettext("too many arguments\n"));
5838 usage(B_FALSE);
5839 }
5840
5841 poolname = argv[0];
5842 if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
5843 return (1);
5844
5845 ret = zpool_reguid(zhp);
5846
5847 zpool_close(zhp);
5848 return (ret);
5849}
5850
5851
1bd201e7
CS
5852/*
5853 * zpool reopen <pool>
5854 *
5855 * Reopen the pool so that the kernel can update the sizes of all vdevs.
1bd201e7
CS
5856 */
5857int
5858zpool_do_reopen(int argc, char **argv)
5859{
5853fe79 5860 int c;
1bd201e7 5861 int ret = 0;
d3f2cd7e 5862 boolean_t scrub_restart = B_TRUE;
1bd201e7 5863
5853fe79 5864 /* check options */
d3f2cd7e 5865 while ((c = getopt(argc, argv, "n")) != -1) {
5853fe79 5866 switch (c) {
d3f2cd7e
AB
5867 case 'n':
5868 scrub_restart = B_FALSE;
5869 break;
5853fe79
GW
5870 case '?':
5871 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5872 optopt);
5873 usage(B_FALSE);
5874 }
5875 }
5876
d3f2cd7e
AB
5877 argc -= optind;
5878 argv += optind;
1bd201e7 5879
d3f2cd7e
AB
5880 /* if argc == 0 we will execute zpool_reopen_one on all pools */
5881 ret = for_each_pool(argc, argv, B_TRUE, NULL, zpool_reopen_one,
5882 &scrub_restart);
1bd201e7 5883
1bd201e7
CS
5884 return (ret);
5885}
5886
34dc7c2f
BB
5887typedef struct scrub_cbdata {
5888 int cb_type;
5889 int cb_argc;
5890 char **cb_argv;
0ea05c64 5891 pool_scrub_cmd_t cb_scrub_cmd;
34dc7c2f
BB
5892} scrub_cbdata_t;
5893
5894int
5895scrub_callback(zpool_handle_t *zhp, void *data)
5896{
5897 scrub_cbdata_t *cb = data;
5898 int err;
5899
5900 /*
5901 * Ignore faulted pools.
5902 */
5903 if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
5904 (void) fprintf(stderr, gettext("cannot scrub '%s': pool is "
5905 "currently unavailable\n"), zpool_get_name(zhp));
5906 return (1);
5907 }
5908
0ea05c64 5909 err = zpool_scan(zhp, cb->cb_type, cb->cb_scrub_cmd);
34dc7c2f
BB
5910
5911 return (err != 0);
5912}
5913
5914/*
0ea05c64 5915 * zpool scrub [-s | -p] <pool> ...
34dc7c2f
BB
5916 *
5917 * -s Stop. Stops any in-progress scrub.
0ea05c64 5918 * -p Pause. Pause in-progress scrub.
34dc7c2f
BB
5919 */
5920int
5921zpool_do_scrub(int argc, char **argv)
5922{
5923 int c;
5924 scrub_cbdata_t cb;
5925
428870ff 5926 cb.cb_type = POOL_SCAN_SCRUB;
0ea05c64 5927 cb.cb_scrub_cmd = POOL_SCRUB_NORMAL;
34dc7c2f
BB
5928
5929 /* check options */
0ea05c64 5930 while ((c = getopt(argc, argv, "sp")) != -1) {
34dc7c2f
BB
5931 switch (c) {
5932 case 's':
428870ff 5933 cb.cb_type = POOL_SCAN_NONE;
34dc7c2f 5934 break;
0ea05c64
AP
5935 case 'p':
5936 cb.cb_scrub_cmd = POOL_SCRUB_PAUSE;
5937 break;
34dc7c2f
BB
5938 case '?':
5939 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5940 optopt);
5941 usage(B_FALSE);
5942 }
5943 }
5944
0ea05c64
AP
5945 if (cb.cb_type == POOL_SCAN_NONE &&
5946 cb.cb_scrub_cmd == POOL_SCRUB_PAUSE) {
5947 (void) fprintf(stderr, gettext("invalid option combination: "
5948 "-s and -p are mutually exclusive\n"));
5949 usage(B_FALSE);
5950 }
5951
34dc7c2f
BB
5952 cb.cb_argc = argc;
5953 cb.cb_argv = argv;
5954 argc -= optind;
5955 argv += optind;
5956
5957 if (argc < 1) {
5958 (void) fprintf(stderr, gettext("missing pool name argument\n"));
5959 usage(B_FALSE);
5960 }
5961
5962 return (for_each_pool(argc, argv, B_TRUE, NULL, scrub_callback, &cb));
5963}
5964
34dc7c2f
BB
5965/*
5966 * Print out detailed scrub status.
5967 */
5968void
428870ff 5969print_scan_status(pool_scan_stat_t *ps)
34dc7c2f 5970{
0ea05c64 5971 time_t start, end, pause;
d4a72f23
TC
5972 uint64_t total_secs_left;
5973 uint64_t elapsed, secs_left, mins_left, hours_left, days_left;
5974 uint64_t pass_scanned, scanned, pass_issued, issued, total;
5975 uint_t scan_rate, issue_rate;
34dc7c2f 5976 double fraction_done;
d4a72f23
TC
5977 char processed_buf[7], scanned_buf[7], issued_buf[7], total_buf[7];
5978 char srate_buf[7], irate_buf[7];
34dc7c2f 5979
24024589 5980 (void) printf(gettext(" scan: "));
34dc7c2f 5981
428870ff
BB
5982 /* If there's never been a scan, there's not much to say. */
5983 if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
5984 ps->pss_func >= POOL_SCAN_FUNCS) {
34dc7c2f
BB
5985 (void) printf(gettext("none requested\n"));
5986 return;
5987 }
5988
428870ff
BB
5989 start = ps->pss_start_time;
5990 end = ps->pss_end_time;
0ea05c64 5991 pause = ps->pss_pass_scrub_pause;
d4a72f23 5992
e7fbeb60 5993 zfs_nicebytes(ps->pss_processed, processed_buf, sizeof (processed_buf));
34dc7c2f 5994
428870ff
BB
5995 assert(ps->pss_func == POOL_SCAN_SCRUB ||
5996 ps->pss_func == POOL_SCAN_RESILVER);
d4a72f23
TC
5997
5998 /* Scan is finished or canceled. */
428870ff 5999 if (ps->pss_state == DSS_FINISHED) {
d4a72f23
TC
6000 total_secs_left = end - start;
6001 days_left = total_secs_left / 60 / 60 / 24;
6002 hours_left = (total_secs_left / 60 / 60) % 24;
6003 mins_left = (total_secs_left / 60) % 60;
6004 secs_left = (total_secs_left % 60);
428870ff
BB
6005
6006 if (ps->pss_func == POOL_SCAN_SCRUB) {
d4a72f23
TC
6007 (void) printf(gettext("scrub repaired %s "
6008 "in %llu days %02llu:%02llu:%02llu "
6009 "with %llu errors on %s"), processed_buf,
6010 (u_longlong_t)days_left, (u_longlong_t)hours_left,
6011 (u_longlong_t)mins_left, (u_longlong_t)secs_left,
6012 (u_longlong_t)ps->pss_errors, ctime(&end));
428870ff 6013 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
d4a72f23
TC
6014 (void) printf(gettext("resilvered %s "
6015 "in %llu days %02llu:%02llu:%02llu "
6016 "with %llu errors on %s"), processed_buf,
6017 (u_longlong_t)days_left, (u_longlong_t)hours_left,
6018 (u_longlong_t)mins_left, (u_longlong_t)secs_left,
6019 (u_longlong_t)ps->pss_errors, ctime(&end));
428870ff 6020 }
428870ff
BB
6021 return;
6022 } else if (ps->pss_state == DSS_CANCELED) {
6023 if (ps->pss_func == POOL_SCAN_SCRUB) {
6024 (void) printf(gettext("scrub canceled on %s"),
6025 ctime(&end));
6026 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
6027 (void) printf(gettext("resilver canceled on %s"),
6028 ctime(&end));
6029 }
34dc7c2f
BB
6030 return;
6031 }
6032
428870ff
BB
6033 assert(ps->pss_state == DSS_SCANNING);
6034
d4a72f23 6035 /* Scan is in progress. Resilvers can't be paused. */
428870ff 6036 if (ps->pss_func == POOL_SCAN_SCRUB) {
0ea05c64
AP
6037 if (pause == 0) {
6038 (void) printf(gettext("scrub in progress since %s"),
6039 ctime(&start));
6040 } else {
d4a72f23
TC
6041 (void) printf(gettext("scrub paused since %s"),
6042 ctime(&pause));
6043 (void) printf(gettext("\tscrub started on %s"),
0ea05c64
AP
6044 ctime(&start));
6045 }
428870ff
BB
6046 } else if (ps->pss_func == POOL_SCAN_RESILVER) {
6047 (void) printf(gettext("resilver in progress since %s"),
6048 ctime(&start));
6049 }
34dc7c2f 6050
d4a72f23
TC
6051 scanned = ps->pss_examined;
6052 pass_scanned = ps->pss_pass_exam;
6053 issued = ps->pss_issued;
6054 pass_issued = ps->pss_pass_issued;
428870ff 6055 total = ps->pss_to_examine;
428870ff 6056
d4a72f23
TC
6057 /* we are only done with a block once we have issued the IO for it */
6058 fraction_done = (double)issued / total;
6059
6060 /* elapsed time for this pass, rounding up to 1 if it's 0 */
428870ff 6061 elapsed = time(NULL) - ps->pss_pass_start;
0ea05c64 6062 elapsed -= ps->pss_pass_scrub_spent_paused;
d4a72f23
TC
6063 elapsed = (elapsed != 0) ? elapsed : 1;
6064
6065 scan_rate = pass_scanned / elapsed;
6066 issue_rate = pass_issued / elapsed;
6067 total_secs_left = (issue_rate != 0) ?
6068 ((total - issued) / issue_rate) : UINT64_MAX;
6069
6070 days_left = total_secs_left / 60 / 60 / 24;
6071 hours_left = (total_secs_left / 60 / 60) % 24;
6072 mins_left = (total_secs_left / 60) % 60;
6073 secs_left = (total_secs_left % 60);
6074
6075 /* format all of the numbers we will be reporting */
6076 zfs_nicebytes(scanned, scanned_buf, sizeof (scanned_buf));
6077 zfs_nicebytes(issued, issued_buf, sizeof (issued_buf));
e7fbeb60 6078 zfs_nicebytes(total, total_buf, sizeof (total_buf));
d4a72f23
TC
6079 zfs_nicebytes(scan_rate, srate_buf, sizeof (srate_buf));
6080 zfs_nicebytes(issue_rate, irate_buf, sizeof (irate_buf));
428870ff 6081
d4a72f23 6082 /* do not print estimated time if we have a paused scrub */
0ea05c64 6083 if (pause == 0) {
d4a72f23
TC
6084 (void) printf(gettext("\t%s scanned at %s/s, "
6085 "%s issued at %s/s, %s total\n"),
6086 scanned_buf, srate_buf, issued_buf, irate_buf, total_buf);
572e2857 6087 } else {
d4a72f23
TC
6088 (void) printf(gettext("\t%s scanned, %s issued, %s total\n"),
6089 scanned_buf, issued_buf, total_buf);
572e2857 6090 }
428870ff
BB
6091
6092 if (ps->pss_func == POOL_SCAN_RESILVER) {
d4a72f23 6093 (void) printf(gettext("\t%s resilvered, %.2f%% done"),
428870ff
BB
6094 processed_buf, 100 * fraction_done);
6095 } else if (ps->pss_func == POOL_SCAN_SCRUB) {
d4a72f23 6096 (void) printf(gettext("\t%s repaired, %.2f%% done"),
428870ff
BB
6097 processed_buf, 100 * fraction_done);
6098 }
d4a72f23
TC
6099
6100 if (pause == 0) {
6101 if (issue_rate >= 10 * 1024 * 1024) {
6102 (void) printf(gettext(", %llu days "
6103 "%02llu:%02llu:%02llu to go\n"),
6104 (u_longlong_t)days_left, (u_longlong_t)hours_left,
6105 (u_longlong_t)mins_left, (u_longlong_t)secs_left);
6106 } else {
6107 (void) printf(gettext(", no estimated "
6108 "completion time\n"));
6109 }
6110 } else {
6111 (void) printf(gettext("\n"));
6112 }
34dc7c2f
BB
6113}
6114
34dc7c2f
BB
6115static void
6116print_error_log(zpool_handle_t *zhp)
6117{
6118 nvlist_t *nverrlist = NULL;
6119 nvpair_t *elem;
6120 char *pathname;
6121 size_t len = MAXPATHLEN * 2;
6122
56a6054d 6123 if (zpool_get_errlog(zhp, &nverrlist) != 0)
34dc7c2f 6124 return;
34dc7c2f
BB
6125
6126 (void) printf("errors: Permanent errors have been "
6127 "detected in the following files:\n\n");
6128
6129 pathname = safe_malloc(len);
6130 elem = NULL;
6131 while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
6132 nvlist_t *nv;
6133 uint64_t dsobj, obj;
6134
6135 verify(nvpair_value_nvlist(elem, &nv) == 0);
6136 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
6137 &dsobj) == 0);
6138 verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
6139 &obj) == 0);
6140 zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
6141 (void) printf("%7s %s\n", "", pathname);
6142 }
6143 free(pathname);
6144 nvlist_free(nverrlist);
6145}
6146
6147static void
fea33e4e
HJ
6148print_spares(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **spares,
6149 uint_t nspares)
34dc7c2f
BB
6150{
6151 uint_t i;
6152 char *name;
6153
6154 if (nspares == 0)
6155 return;
6156
6157 (void) printf(gettext("\tspares\n"));
6158
6159 for (i = 0; i < nspares; i++) {
fea33e4e
HJ
6160 name = zpool_vdev_name(g_zfs, zhp, spares[i],
6161 cb->cb_name_flags);
6162 print_status_config(zhp, cb, name, spares[i], 2, B_TRUE);
34dc7c2f
BB
6163 free(name);
6164 }
6165}
6166
6167static void
fea33e4e
HJ
6168print_l2cache(zpool_handle_t *zhp, status_cbdata_t *cb, nvlist_t **l2cache,
6169 uint_t nl2cache)
34dc7c2f
BB
6170{
6171 uint_t i;
6172 char *name;
6173
6174 if (nl2cache == 0)
6175 return;
6176
6177 (void) printf(gettext("\tcache\n"));
6178
6179 for (i = 0; i < nl2cache; i++) {
fea33e4e
HJ
6180 name = zpool_vdev_name(g_zfs, zhp, l2cache[i],
6181 cb->cb_name_flags);
6182 print_status_config(zhp, cb, name, l2cache[i], 2, B_FALSE);
34dc7c2f
BB
6183 free(name);
6184 }
6185}
6186
428870ff
BB
6187static void
6188print_dedup_stats(nvlist_t *config)
6189{
6190 ddt_histogram_t *ddh;
6191 ddt_stat_t *dds;
6192 ddt_object_t *ddo;
6193 uint_t c;
e7fbeb60 6194 char dspace[6], mspace[6];
428870ff
BB
6195
6196 /*
6197 * If the pool was faulted then we may not have been able to
32a9872b 6198 * obtain the config. Otherwise, if we have anything in the dedup
428870ff
BB
6199 * table continue processing the stats.
6200 */
6201 if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
24024589 6202 (uint64_t **)&ddo, &c) != 0)
428870ff
BB
6203 return;
6204
6205 (void) printf("\n");
24024589
YP
6206 (void) printf(gettext(" dedup: "));
6207 if (ddo->ddo_count == 0) {
6208 (void) printf(gettext("no DDT entries\n"));
6209 return;
6210 }
6211
e7fbeb60 6212 zfs_nicebytes(ddo->ddo_dspace, dspace, sizeof (dspace));
6213 zfs_nicebytes(ddo->ddo_mspace, mspace, sizeof (mspace));
6214 (void) printf("DDT entries %llu, size %s on disk, %s in core\n",
428870ff 6215 (u_longlong_t)ddo->ddo_count,
e7fbeb60 6216 dspace,
6217 mspace);
428870ff
BB
6218
6219 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
6220 (uint64_t **)&dds, &c) == 0);
6221 verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
6222 (uint64_t **)&ddh, &c) == 0);
6223 zpool_dump_ddt(dds, ddh);
6224}
6225
34dc7c2f
BB
6226/*
6227 * Display a summary of pool status. Displays a summary such as:
6228 *
6229 * pool: tank
6230 * status: DEGRADED
6231 * reason: One or more devices ...
3cee2262 6232 * see: http://zfsonlinux.org/msg/ZFS-xxxx-01
34dc7c2f
BB
6233 * config:
6234 * mirror DEGRADED
6235 * c1t0d0 OK
6236 * c2t0d0 UNAVAIL
6237 *
6238 * When given the '-v' option, we print out the complete config. If the '-e'
6239 * option is specified, then we print out error rate information as well.
6240 */
6241int
6242status_callback(zpool_handle_t *zhp, void *data)
6243{
6244 status_cbdata_t *cbp = data;
6245 nvlist_t *config, *nvroot;
6246 char *msgid;
731782ec 6247 zpool_status_t reason;
ffe9d382 6248 zpool_errata_t errata;
34dc7c2f
BB
6249 const char *health;
6250 uint_t c;
6251 vdev_stat_t *vs;
6252
6253 config = zpool_get_config(zhp, NULL);
ffe9d382 6254 reason = zpool_get_status(zhp, &msgid, &errata);
34dc7c2f
BB
6255
6256 cbp->cb_count++;
6257
6258 /*
6259 * If we were given 'zpool status -x', only report those pools with
6260 * problems.
6261 */
c5b247f3
TC
6262 if (cbp->cb_explain &&
6263 (reason == ZPOOL_STATUS_OK ||
6264 reason == ZPOOL_STATUS_VERSION_OLDER ||
6265 reason == ZPOOL_STATUS_FEAT_DISABLED)) {
34dc7c2f
BB
6266 if (!cbp->cb_allpools) {
6267 (void) printf(gettext("pool '%s' is healthy\n"),
6268 zpool_get_name(zhp));
6269 if (cbp->cb_first)
6270 cbp->cb_first = B_FALSE;
6271 }
6272 return (0);
6273 }
6274
6275 if (cbp->cb_first)
6276 cbp->cb_first = B_FALSE;
6277 else
6278 (void) printf("\n");
6279
6280 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
6281 &nvroot) == 0);
428870ff 6282 verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
34dc7c2f
BB
6283 (uint64_t **)&vs, &c) == 0);
6284 health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
6285
6286 (void) printf(gettext(" pool: %s\n"), zpool_get_name(zhp));
6287 (void) printf(gettext(" state: %s\n"), health);
6288
6289 switch (reason) {
6290 case ZPOOL_STATUS_MISSING_DEV_R:
6291 (void) printf(gettext("status: One or more devices could not "
6292 "be opened. Sufficient replicas exist for\n\tthe pool to "
6293 "continue functioning in a degraded state.\n"));
6294 (void) printf(gettext("action: Attach the missing device and "
6295 "online it using 'zpool online'.\n"));
6296 break;
6297
6298 case ZPOOL_STATUS_MISSING_DEV_NR:
6299 (void) printf(gettext("status: One or more devices could not "
6300 "be opened. There are insufficient\n\treplicas for the "
6301 "pool to continue functioning.\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_CORRUPT_LABEL_R:
6307 (void) printf(gettext("status: One or more devices could not "
6308 "be used because the label is missing or\n\tinvalid. "
6309 "Sufficient replicas exist for the pool to continue\n\t"
6310 "functioning in a degraded state.\n"));
6311 (void) printf(gettext("action: Replace the device using "
6312 "'zpool replace'.\n"));
6313 break;
6314
6315 case ZPOOL_STATUS_CORRUPT_LABEL_NR:
6316 (void) printf(gettext("status: One or more devices could not "
6317 "be used because the label is missing \n\tor invalid. "
6318 "There are insufficient replicas for the pool to "
6319 "continue\n\tfunctioning.\n"));
428870ff
BB
6320 zpool_explain_recover(zpool_get_handle(zhp),
6321 zpool_get_name(zhp), reason, config);
34dc7c2f
BB
6322 break;
6323
6324 case ZPOOL_STATUS_FAILING_DEV:
6325 (void) printf(gettext("status: One or more devices has "
6326 "experienced an unrecoverable error. An\n\tattempt was "
6327 "made to correct the error. Applications are "
6328 "unaffected.\n"));
6329 (void) printf(gettext("action: Determine if the device needs "
6330 "to be replaced, and clear the errors\n\tusing "
6331 "'zpool clear' or replace the device with 'zpool "
6332 "replace'.\n"));
6333 break;
6334
6335 case ZPOOL_STATUS_OFFLINE_DEV:
6336 (void) printf(gettext("status: One or more devices has "
6337 "been taken offline by the administrator.\n\tSufficient "
6338 "replicas exist for the pool to continue functioning in "
6339 "a\n\tdegraded state.\n"));
6340 (void) printf(gettext("action: Online the device using "
6341 "'zpool online' or replace the device with\n\t'zpool "
6342 "replace'.\n"));
6343 break;
6344
45d1cae3
BB
6345 case ZPOOL_STATUS_REMOVED_DEV:
6346 (void) printf(gettext("status: One or more devices has "
6347 "been removed by the administrator.\n\tSufficient "
6348 "replicas exist for the pool to continue functioning in "
6349 "a\n\tdegraded state.\n"));
6350 (void) printf(gettext("action: Online the device using "
6351 "'zpool online' or replace the device with\n\t'zpool "
6352 "replace'.\n"));
6353 break;
6354
34dc7c2f
BB
6355 case ZPOOL_STATUS_RESILVERING:
6356 (void) printf(gettext("status: One or more devices is "
6357 "currently being resilvered. The pool will\n\tcontinue "
6358 "to function, possibly in a degraded state.\n"));
6359 (void) printf(gettext("action: Wait for the resilver to "
6360 "complete.\n"));
6361 break;
6362
6363 case ZPOOL_STATUS_CORRUPT_DATA:
6364 (void) printf(gettext("status: One or more devices has "
6365 "experienced an error resulting in data\n\tcorruption. "
6366 "Applications may be affected.\n"));
6367 (void) printf(gettext("action: Restore the file in question "
6368 "if possible. Otherwise restore the\n\tentire pool from "
6369 "backup.\n"));
6370 break;
6371
6372 case ZPOOL_STATUS_CORRUPT_POOL:
6373 (void) printf(gettext("status: The pool metadata is corrupted "
6374 "and the pool cannot be opened.\n"));
428870ff
BB
6375 zpool_explain_recover(zpool_get_handle(zhp),
6376 zpool_get_name(zhp), reason, config);
34dc7c2f
BB
6377 break;
6378
6379 case ZPOOL_STATUS_VERSION_OLDER:
b9b24bb4
CS
6380 (void) printf(gettext("status: The pool is formatted using a "
6381 "legacy on-disk format. The pool can\n\tstill be used, "
6382 "but some features are unavailable.\n"));
34dc7c2f
BB
6383 (void) printf(gettext("action: Upgrade the pool using 'zpool "
6384 "upgrade'. Once this is done, the\n\tpool will no longer "
f52b31ea
BB
6385 "be accessible on software that does not support\n\t"
6386 "feature flags.\n"));
34dc7c2f
BB
6387 break;
6388
6389 case ZPOOL_STATUS_VERSION_NEWER:
6390 (void) printf(gettext("status: The pool has been upgraded to a "
6391 "newer, incompatible on-disk version.\n\tThe pool cannot "
6392 "be accessed on this system.\n"));
6393 (void) printf(gettext("action: Access the pool from a system "
6394 "running more recent software, or\n\trestore the pool from "
6395 "backup.\n"));
6396 break;
6397
b9b24bb4
CS
6398 case ZPOOL_STATUS_FEAT_DISABLED:
6399 (void) printf(gettext("status: Some supported features are not "
6400 "enabled on the pool. The pool can\n\tstill be used, but "
6401 "some features are unavailable.\n"));
6402 (void) printf(gettext("action: Enable all features using "
6403 "'zpool upgrade'. Once this is done,\n\tthe pool may no "
6404 "longer be accessible by software that does not support\n\t"
6405 "the features. See zpool-features(5) for details.\n"));
6406 break;
6407
9ae529ec
CS
6408 case ZPOOL_STATUS_UNSUP_FEAT_READ:
6409 (void) printf(gettext("status: The pool cannot be accessed on "
6410 "this system because it uses the\n\tfollowing feature(s) "
6411 "not supported on this system:\n"));
6412 zpool_print_unsup_feat(config);
6413 (void) printf("\n");
6414 (void) printf(gettext("action: Access the pool from a system "
6415 "that supports the required feature(s),\n\tor restore the "
6416 "pool from backup.\n"));
6417 break;
6418
6419 case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
6420 (void) printf(gettext("status: The pool can only be accessed "
6421 "in read-only mode on this system. It\n\tcannot be "
6422 "accessed in read-write mode because it uses the "
6423 "following\n\tfeature(s) not supported on this system:\n"));
6424 zpool_print_unsup_feat(config);
6425 (void) printf("\n");
6426 (void) printf(gettext("action: The pool cannot be accessed in "
6427 "read-write mode. Import the pool with\n"
6428 "\t\"-o readonly=on\", access the pool from a system that "
6429 "supports the\n\trequired feature(s), or restore the "
6430 "pool from backup.\n"));
6431 break;
6432
34dc7c2f
BB
6433 case ZPOOL_STATUS_FAULTED_DEV_R:
6434 (void) printf(gettext("status: One or more devices are "
6435 "faulted in response to persistent errors.\n\tSufficient "
6436 "replicas exist for the pool to continue functioning "
6437 "in a\n\tdegraded state.\n"));
6438 (void) printf(gettext("action: Replace the faulted device, "
6439 "or use 'zpool clear' to mark the device\n\trepaired.\n"));
6440 break;
6441
6442 case ZPOOL_STATUS_FAULTED_DEV_NR:
6443 (void) printf(gettext("status: One or more devices are "
6444 "faulted in response to persistent errors. There are "
6445 "insufficient replicas for the pool to\n\tcontinue "
6446 "functioning.\n"));
6447 (void) printf(gettext("action: Destroy and re-create the pool "
6448 "from a backup source. Manually marking the device\n"
6449 "\trepaired using 'zpool clear' may allow some data "
6450 "to be recovered.\n"));
6451 break;
6452
b128c09f
BB
6453 case ZPOOL_STATUS_IO_FAILURE_WAIT:
6454 case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
6455 (void) printf(gettext("status: One or more devices are "
6456 "faulted in response to IO failures.\n"));
6457 (void) printf(gettext("action: Make sure the affected devices "
6458 "are connected, then run 'zpool clear'.\n"));
6459 break;
6460
6461 case ZPOOL_STATUS_BAD_LOG:
6462 (void) printf(gettext("status: An intent log record "
6463 "could not be read.\n"
2627e752 6464 "\tWaiting for administrator intervention to fix the "
b128c09f
BB
6465 "faulted pool.\n"));
6466 (void) printf(gettext("action: Either restore the affected "
6467 "device(s) and run 'zpool online',\n"
6468 "\tor ignore the intent log records by running "
6469 "'zpool clear'.\n"));
6470 break;
6471
1cbae971
RY
6472 case ZPOOL_STATUS_HOSTID_MISMATCH:
6473 (void) printf(gettext("status: Mismatch between pool hostid "
6474 "and system hostid on imported pool.\n\tThis pool was "
6475 "previously imported into a system with a different "
6476 "hostid,\n\tand then was verbatim imported into this "
6477 "system.\n"));
6478 (void) printf(gettext("action: Export this pool on all systems "
6479 "on which it is imported.\n"
6480 "\tThen import it to correct the mismatch.\n"));
6481 break;
6482
ffe9d382
BB
6483 case ZPOOL_STATUS_ERRATA:
6484 (void) printf(gettext("status: Errata #%d detected.\n"),
6485 errata);
6486
6487 switch (errata) {
6488 case ZPOOL_ERRATA_NONE:
6489 break;
6490
4f2dcb3e
RY
6491 case ZPOOL_ERRATA_ZOL_2094_SCRUB:
6492 (void) printf(gettext("action: To correct the issue "
6493 "run 'zpool scrub'.\n"));
6494 break;
6495
ffe9d382
BB
6496 default:
6497 /*
6498 * All errata which allow the pool to be imported
6499 * must contain an action message.
6500 */
6501 assert(0);
6502 }
6503 break;
6504
34dc7c2f
BB
6505 default:
6506 /*
6507 * The remaining errors can't actually be generated, yet.
6508 */
6509 assert(reason == ZPOOL_STATUS_OK);
6510 }
6511
6512 if (msgid != NULL)
3cee2262 6513 (void) printf(gettext(" see: http://zfsonlinux.org/msg/%s\n"),
34dc7c2f
BB
6514 msgid);
6515
6516 if (config != NULL) {
34dc7c2f
BB
6517 uint64_t nerr;
6518 nvlist_t **spares, **l2cache;
6519 uint_t nspares, nl2cache;
428870ff 6520 pool_scan_stat_t *ps = NULL;
34dc7c2f 6521
428870ff
BB
6522 (void) nvlist_lookup_uint64_array(nvroot,
6523 ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &c);
6524 print_scan_status(ps);
34dc7c2f 6525
fea33e4e 6526 cbp->cb_namewidth = max_width(zhp, nvroot, 0, 0,
5f20c145 6527 cbp->cb_name_flags | VDEV_NAME_TYPE_ID);
fea33e4e
HJ
6528 if (cbp->cb_namewidth < 10)
6529 cbp->cb_namewidth = 10;
34dc7c2f
BB
6530
6531 (void) printf(gettext("config:\n\n"));
d6418de0 6532 (void) printf(gettext("\t%-*s %-8s %5s %5s %5s"),
fea33e4e
HJ
6533 cbp->cb_namewidth, "NAME", "STATE", "READ", "WRITE",
6534 "CKSUM");
d6418de0
TH
6535
6536 if (cbp->vcdl != NULL)
6537 print_cmd_columns(cbp->vcdl, 0);
6538
6539 printf("\n");
fea33e4e
HJ
6540 print_status_config(zhp, cbp, zpool_get_name(zhp), nvroot, 0,
6541 B_FALSE);
34dc7c2f 6542
9babb374 6543 if (num_logs(nvroot) > 0)
fea33e4e 6544 print_logs(zhp, cbp, nvroot);
34dc7c2f
BB
6545 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
6546 &l2cache, &nl2cache) == 0)
fea33e4e 6547 print_l2cache(zhp, cbp, l2cache, nl2cache);
34dc7c2f
BB
6548
6549 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
6550 &spares, &nspares) == 0)
fea33e4e 6551 print_spares(zhp, cbp, spares, nspares);
34dc7c2f
BB
6552
6553 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
6554 &nerr) == 0) {
6555 nvlist_t *nverrlist = NULL;
6556
6557 /*
6558 * If the approximate error count is small, get a
6559 * precise count by fetching the entire log and
6560 * uniquifying the results.
6561 */
6562 if (nerr > 0 && nerr < 100 && !cbp->cb_verbose &&
6563 zpool_get_errlog(zhp, &nverrlist) == 0) {
6564 nvpair_t *elem;
6565
6566 elem = NULL;
6567 nerr = 0;
6568 while ((elem = nvlist_next_nvpair(nverrlist,
6569 elem)) != NULL) {
6570 nerr++;
6571 }
6572 }
6573 nvlist_free(nverrlist);
6574
6575 (void) printf("\n");
6576
6577 if (nerr == 0)
6578 (void) printf(gettext("errors: No known data "
6579 "errors\n"));
6580 else if (!cbp->cb_verbose)
6581 (void) printf(gettext("errors: %llu data "
6582 "errors, use '-v' for a list\n"),
6583 (u_longlong_t)nerr);
6584 else
6585 print_error_log(zhp);
6586 }
428870ff
BB
6587
6588 if (cbp->cb_dedup_stats)
6589 print_dedup_stats(config);
34dc7c2f
BB
6590 } else {
6591 (void) printf(gettext("config: The configuration cannot be "
6592 "determined.\n"));
6593 }
6594
6595 return (0);
6596}
6597
6598/*
d6418de0
TH
6599 * zpool status [-c [script1,script2,...]] [-gLPvx] [-T d|u] [pool] ...
6600 * [interval [count]]
34dc7c2f 6601 *
8720e9e7 6602 * -c CMD For each vdev, run command CMD
d2f3e292
RY
6603 * -g Display guid for individual vdev name.
6604 * -L Follow links when resolving vdev path name.
a77f29f9 6605 * -P Display full path for vdev name.
34dc7c2f
BB
6606 * -v Display complete error logs
6607 * -x Display only pools with potential problems
428870ff
BB
6608 * -D Display dedup status (undocumented)
6609 * -T Display a timestamp in date(1) or Unix format
34dc7c2f
BB
6610 *
6611 * Describes the health status of all pools or some subset.
6612 */
6613int
6614zpool_do_status(int argc, char **argv)
6615{
6616 int c;
6617 int ret;
193a37cb
TH
6618 float interval = 0;
6619 unsigned long count = 0;
34dc7c2f 6620 status_cbdata_t cb = { 0 };
8720e9e7 6621 char *cmd = NULL;
34dc7c2f
BB
6622
6623 /* check options */
8720e9e7 6624 while ((c = getopt(argc, argv, "c:gLPvxDT:")) != -1) {
34dc7c2f 6625 switch (c) {
8720e9e7 6626 case 'c':
d6418de0
TH
6627 if (cmd != NULL) {
6628 fprintf(stderr,
6629 gettext("Can't set -c flag twice\n"));
6630 exit(1);
6631 }
099700d9
GDN
6632
6633 if (getenv("ZPOOL_SCRIPTS_ENABLED") != NULL &&
6634 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_ENABLED")) {
6635 fprintf(stderr, gettext(
6636 "Can't run -c, disabled by "
6637 "ZPOOL_SCRIPTS_ENABLED.\n"));
6638 exit(1);
6639 }
6640
d6418de0
TH
6641 if ((getuid() <= 0 || geteuid() <= 0) &&
6642 !libzfs_envvar_is_set("ZPOOL_SCRIPTS_AS_ROOT")) {
6643 fprintf(stderr, gettext(
6644 "Can't run -c with root privileges "
6645 "unless ZPOOL_SCRIPTS_AS_ROOT is set.\n"));
6646 exit(1);
6647 }
8720e9e7
TH
6648 cmd = optarg;
6649 break;
d2f3e292
RY
6650 case 'g':
6651 cb.cb_name_flags |= VDEV_NAME_GUID;
6652 break;
6653 case 'L':
6654 cb.cb_name_flags |= VDEV_NAME_FOLLOW_LINKS;
6655 break;
a77f29f9 6656 case 'P':
d2f3e292
RY
6657 cb.cb_name_flags |= VDEV_NAME_PATH;
6658 break;
34dc7c2f
BB
6659 case 'v':
6660 cb.cb_verbose = B_TRUE;
6661 break;
6662 case 'x':
6663 cb.cb_explain = B_TRUE;
6664 break;
428870ff
BB
6665 case 'D':
6666 cb.cb_dedup_stats = B_TRUE;
6667 break;
6668 case 'T':
6669 get_timestamp_arg(*optarg);
6670 break;
34dc7c2f 6671 case '?':
1528bfdb 6672 if (optopt == 'c') {
099700d9 6673 print_zpool_script_list("status");
d6418de0 6674 exit(0);
1528bfdb
TH
6675 } else {
6676 fprintf(stderr,
6677 gettext("invalid option '%c'\n"), optopt);
6678 }
34dc7c2f
BB
6679 usage(B_FALSE);
6680 }
6681 }
6682
6683 argc -= optind;
6684 argv += optind;
6685
428870ff 6686 get_interval_count(&argc, argv, &interval, &count);
34dc7c2f
BB
6687
6688 if (argc == 0)
6689 cb.cb_allpools = B_TRUE;
6690
428870ff 6691 cb.cb_first = B_TRUE;
fea33e4e 6692 cb.cb_print_status = B_TRUE;
34dc7c2f 6693
428870ff
BB
6694 for (;;) {
6695 if (timestamp_fmt != NODATE)
6696 print_timestamp(timestamp_fmt);
34dc7c2f 6697
8720e9e7 6698 if (cmd != NULL)
1528bfdb
TH
6699 cb.vcdl = all_pools_for_each_vdev_run(argc, argv, cmd,
6700 NULL, NULL, 0, 0);
8720e9e7 6701
428870ff
BB
6702 ret = for_each_pool(argc, argv, B_TRUE, NULL,
6703 status_callback, &cb);
6704
8720e9e7
TH
6705 if (cb.vcdl != NULL)
6706 free_vdev_cmd_data_list(cb.vcdl);
6707
428870ff 6708 if (argc == 0 && cb.cb_count == 0)
42cb3819 6709 (void) fprintf(stderr, gettext("no pools available\n"));
428870ff
BB
6710 else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
6711 (void) printf(gettext("all pools are healthy\n"));
6712
6713 if (ret != 0)
6714 return (ret);
6715
6716 if (interval == 0)
6717 break;
6718
6719 if (count != 0 && --count == 0)
6720 break;
6721
193a37cb 6722 (void) fsleep(interval);
428870ff
BB
6723 }
6724
6725 return (0);
34dc7c2f
BB
6726}
6727
6728typedef struct upgrade_cbdata {
34dc7c2f 6729 int cb_first;
34dc7c2f
BB
6730 int cb_argc;
6731 uint64_t cb_version;
6732 char **cb_argv;
6733} upgrade_cbdata_t;
6734
287be44f
DS
6735static int
6736check_unsupp_fs(zfs_handle_t *zhp, void *unsupp_fs)
6737{
02730c33 6738 int zfs_version = (int)zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
287be44f
DS
6739 int *count = (int *)unsupp_fs;
6740
6741 if (zfs_version > ZPL_VERSION) {
6742 (void) printf(gettext("%s (v%d) is not supported by this "
6743 "implementation of ZFS.\n"),
6744 zfs_get_name(zhp), zfs_version);
6745 (*count)++;
6746 }
6747
6748 zfs_iter_filesystems(zhp, check_unsupp_fs, unsupp_fs);
6749
6750 zfs_close(zhp);
6751
6752 return (0);
6753}
6754
b9b24bb4
CS
6755static int
6756upgrade_version(zpool_handle_t *zhp, uint64_t version)
6757{
6758 int ret;
6759 nvlist_t *config;
6760 uint64_t oldversion;
287be44f 6761 int unsupp_fs = 0;
b9b24bb4
CS
6762
6763 config = zpool_get_config(zhp, NULL);
6764 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6765 &oldversion) == 0);
6766
6767 assert(SPA_VERSION_IS_SUPPORTED(oldversion));
6768 assert(oldversion < version);
6769
287be44f
DS
6770 ret = zfs_iter_root(zpool_get_handle(zhp), check_unsupp_fs, &unsupp_fs);
6771 if (ret != 0)
6772 return (ret);
6773
6774 if (unsupp_fs) {
5c7afad4
BB
6775 (void) fprintf(stderr, gettext("Upgrade not performed due "
6776 "to %d unsupported filesystems (max v%d).\n"),
02730c33 6777 unsupp_fs, (int)ZPL_VERSION);
287be44f
DS
6778 return (1);
6779 }
6780
b9b24bb4
CS
6781 ret = zpool_upgrade(zhp, version);
6782 if (ret != 0)
6783 return (ret);
6784
6785 if (version >= SPA_VERSION_FEATURES) {
6786 (void) printf(gettext("Successfully upgraded "
6787 "'%s' from version %llu to feature flags.\n"),
02730c33 6788 zpool_get_name(zhp), (u_longlong_t)oldversion);
b9b24bb4
CS
6789 } else {
6790 (void) printf(gettext("Successfully upgraded "
6791 "'%s' from version %llu to version %llu.\n"),
02730c33
BB
6792 zpool_get_name(zhp), (u_longlong_t)oldversion,
6793 (u_longlong_t)version);
b9b24bb4
CS
6794 }
6795
6796 return (0);
6797}
6798
6799static int
6800upgrade_enable_all(zpool_handle_t *zhp, int *countp)
6801{
6802 int i, ret, count;
6803 boolean_t firstff = B_TRUE;
6804 nvlist_t *enabled = zpool_get_features(zhp);
6805
6806 count = 0;
6807 for (i = 0; i < SPA_FEATURES; i++) {
6808 const char *fname = spa_feature_table[i].fi_uname;
6809 const char *fguid = spa_feature_table[i].fi_guid;
6810 if (!nvlist_exists(enabled, fguid)) {
6811 char *propname;
6812 verify(-1 != asprintf(&propname, "feature@%s", fname));
6813 ret = zpool_set_prop(zhp, propname,
6814 ZFS_FEATURE_ENABLED);
6815 if (ret != 0) {
6816 free(propname);
6817 return (ret);
6818 }
6819 count++;
6820
6821 if (firstff) {
6822 (void) printf(gettext("Enabled the "
6823 "following features on '%s':\n"),
6824 zpool_get_name(zhp));
6825 firstff = B_FALSE;
6826 }
6827 (void) printf(gettext(" %s\n"), fname);
6828 free(propname);
6829 }
6830 }
6831
6832 if (countp != NULL)
6833 *countp = count;
6834 return (0);
6835}
6836
34dc7c2f
BB
6837static int
6838upgrade_cb(zpool_handle_t *zhp, void *arg)
6839{
6840 upgrade_cbdata_t *cbp = arg;
6841 nvlist_t *config;
6842 uint64_t version;
b9b24bb4
CS
6843 boolean_t printnl = B_FALSE;
6844 int ret;
34dc7c2f
BB
6845
6846 config = zpool_get_config(zhp, NULL);
6847 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6848 &version) == 0);
6849
b9b24bb4 6850 assert(SPA_VERSION_IS_SUPPORTED(version));
34dc7c2f 6851
b9b24bb4
CS
6852 if (version < cbp->cb_version) {
6853 cbp->cb_first = B_FALSE;
6854 ret = upgrade_version(zhp, cbp->cb_version);
6855 if (ret != 0)
6856 return (ret);
6857 printnl = B_TRUE;
6858
b9b24bb4
CS
6859 /*
6860 * If they did "zpool upgrade -a", then we could
6861 * be doing ioctls to different pools. We need
6862 * to log this history once to each pool, and bypass
6863 * the normal history logging that happens in main().
6864 */
6865 (void) zpool_log_history(g_zfs, history_str);
6866 log_history = B_FALSE;
b9b24bb4
CS
6867 }
6868
6869 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
6870 int count;
6871 ret = upgrade_enable_all(zhp, &count);
6872 if (ret != 0)
6873 return (ret);
6874
6875 if (count > 0) {
34dc7c2f 6876 cbp->cb_first = B_FALSE;
b9b24bb4 6877 printnl = B_TRUE;
34dc7c2f 6878 }
b9b24bb4 6879 }
34dc7c2f 6880
b9b24bb4
CS
6881 if (printnl) {
6882 (void) printf(gettext("\n"));
6883 }
6884
6885 return (0);
6886}
6887
6888static int
6889upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
6890{
6891 upgrade_cbdata_t *cbp = arg;
6892 nvlist_t *config;
6893 uint64_t version;
6894
6895 config = zpool_get_config(zhp, NULL);
6896 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6897 &version) == 0);
6898
6899 assert(SPA_VERSION_IS_SUPPORTED(version));
6900
6901 if (version < SPA_VERSION_FEATURES) {
34dc7c2f
BB
6902 if (cbp->cb_first) {
6903 (void) printf(gettext("The following pools are "
b9b24bb4
CS
6904 "formatted with legacy version numbers and can\n"
6905 "be upgraded to use feature flags. After "
6906 "being upgraded, these pools\nwill no "
6907 "longer be accessible by software that does not "
6908 "support feature\nflags.\n\n"));
34dc7c2f
BB
6909 (void) printf(gettext("VER POOL\n"));
6910 (void) printf(gettext("--- ------------\n"));
6911 cbp->cb_first = B_FALSE;
6912 }
6913
6914 (void) printf("%2llu %s\n", (u_longlong_t)version,
6915 zpool_get_name(zhp));
6916 }
6917
b9b24bb4
CS
6918 return (0);
6919}
6920
6921static int
6922upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
6923{
6924 upgrade_cbdata_t *cbp = arg;
6925 nvlist_t *config;
6926 uint64_t version;
6927
6928 config = zpool_get_config(zhp, NULL);
6929 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
6930 &version) == 0);
6931
6932 if (version >= SPA_VERSION_FEATURES) {
6933 int i;
6934 boolean_t poolfirst = B_TRUE;
6935 nvlist_t *enabled = zpool_get_features(zhp);
6936
6937 for (i = 0; i < SPA_FEATURES; i++) {
6938 const char *fguid = spa_feature_table[i].fi_guid;
6939 const char *fname = spa_feature_table[i].fi_uname;
6940 if (!nvlist_exists(enabled, fguid)) {
6941 if (cbp->cb_first) {
6942 (void) printf(gettext("\nSome "
6943 "supported features are not "
6944 "enabled on the following pools. "
6945 "Once a\nfeature is enabled the "
6946 "pool may become incompatible with "
6947 "software\nthat does not support "
6948 "the feature. See "
6949 "zpool-features(5) for "
6950 "details.\n\n"));
6951 (void) printf(gettext("POOL "
6952 "FEATURE\n"));
6953 (void) printf(gettext("------"
6954 "---------\n"));
6955 cbp->cb_first = B_FALSE;
6956 }
6957
6958 if (poolfirst) {
6959 (void) printf(gettext("%s\n"),
6960 zpool_get_name(zhp));
6961 poolfirst = B_FALSE;
6962 }
6963
6964 (void) printf(gettext(" %s\n"), fname);
6965 }
6f1ffb06
MA
6966 /*
6967 * If they did "zpool upgrade -a", then we could
6968 * be doing ioctls to different pools. We need
6969 * to log this history once to each pool, and bypass
6970 * the normal history logging that happens in main().
6971 */
6972 (void) zpool_log_history(g_zfs, history_str);
6973 log_history = B_FALSE;
b9b24bb4
CS
6974 }
6975 }
6976
6977 return (0);
34dc7c2f
BB
6978}
6979
6980/* ARGSUSED */
6981static int
6982upgrade_one(zpool_handle_t *zhp, void *data)
6983{
b9b24bb4 6984 boolean_t printnl = B_FALSE;
34dc7c2f
BB
6985 upgrade_cbdata_t *cbp = data;
6986 uint64_t cur_version;
6987 int ret;
6988
6989 if (strcmp("log", zpool_get_name(zhp)) == 0) {
c66989ba 6990 (void) fprintf(stderr, gettext("'log' is now a reserved word\n"
34dc7c2f
BB
6991 "Pool 'log' must be renamed using export and import"
6992 " to upgrade.\n"));
6993 return (1);
6994 }
6995
6996 cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
6997 if (cur_version > cbp->cb_version) {
6998 (void) printf(gettext("Pool '%s' is already formatted "
b9b24bb4 6999 "using more current version '%llu'.\n\n"),
02730c33 7000 zpool_get_name(zhp), (u_longlong_t)cur_version);
34dc7c2f
BB
7001 return (0);
7002 }
b9b24bb4
CS
7003
7004 if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
34dc7c2f 7005 (void) printf(gettext("Pool '%s' is already formatted "
b9b24bb4 7006 "using version %llu.\n\n"), zpool_get_name(zhp),
02730c33 7007 (u_longlong_t)cbp->cb_version);
34dc7c2f
BB
7008 return (0);
7009 }
7010
b9b24bb4
CS
7011 if (cur_version != cbp->cb_version) {
7012 printnl = B_TRUE;
7013 ret = upgrade_version(zhp, cbp->cb_version);
7014 if (ret != 0)
7015 return (ret);
7016 }
34dc7c2f 7017
b9b24bb4
CS
7018 if (cbp->cb_version >= SPA_VERSION_FEATURES) {
7019 int count = 0;
7020 ret = upgrade_enable_all(zhp, &count);
7021 if (ret != 0)
7022 return (ret);
7023
7024 if (count != 0) {
7025 printnl = B_TRUE;
7026 } else if (cur_version == SPA_VERSION) {
7027 (void) printf(gettext("Pool '%s' already has all "
7028 "supported features enabled.\n"),
7029 zpool_get_name(zhp));
7030 }
7031 }
7032
7033 if (printnl) {
7034 (void) printf(gettext("\n"));
34dc7c2f
BB
7035 }
7036
b9b24bb4 7037 return (0);
34dc7c2f
BB
7038}
7039
7040/*
7041 * zpool upgrade
7042 * zpool upgrade -v
7043 * zpool upgrade [-V version] <-a | pool ...>
7044 *
7045 * With no arguments, display downrev'd ZFS pool available for upgrade.
7046 * Individual pools can be upgraded by specifying the pool, and '-a' will
7047 * upgrade all pools.
7048 */
7049int
7050zpool_do_upgrade(int argc, char **argv)
7051{
7052 int c;
7053 upgrade_cbdata_t cb = { 0 };
7054 int ret = 0;
7055 boolean_t showversions = B_FALSE;
b9b24bb4 7056 boolean_t upgradeall = B_FALSE;
34dc7c2f
BB
7057 char *end;
7058
7059
7060 /* check options */
9babb374 7061 while ((c = getopt(argc, argv, ":avV:")) != -1) {
34dc7c2f
BB
7062 switch (c) {
7063 case 'a':
b9b24bb4 7064 upgradeall = B_TRUE;
34dc7c2f
BB
7065 break;
7066 case 'v':
7067 showversions = B_TRUE;
7068 break;
7069 case 'V':
7070 cb.cb_version = strtoll(optarg, &end, 10);
9ae529ec
CS
7071 if (*end != '\0' ||
7072 !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
34dc7c2f
BB
7073 (void) fprintf(stderr,
7074 gettext("invalid version '%s'\n"), optarg);
7075 usage(B_FALSE);
7076 }
7077 break;
9babb374
BB
7078 case ':':
7079 (void) fprintf(stderr, gettext("missing argument for "
7080 "'%c' option\n"), optopt);
7081 usage(B_FALSE);
7082 break;
34dc7c2f
BB
7083 case '?':
7084 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7085 optopt);
7086 usage(B_FALSE);
7087 }
7088 }
7089
7090 cb.cb_argc = argc;
7091 cb.cb_argv = argv;
7092 argc -= optind;
7093 argv += optind;
7094
7095 if (cb.cb_version == 0) {
7096 cb.cb_version = SPA_VERSION;
b9b24bb4 7097 } else if (!upgradeall && argc == 0) {
34dc7c2f
BB
7098 (void) fprintf(stderr, gettext("-V option is "
7099 "incompatible with other arguments\n"));
7100 usage(B_FALSE);
7101 }
7102
7103 if (showversions) {
b9b24bb4 7104 if (upgradeall || argc != 0) {
34dc7c2f
BB
7105 (void) fprintf(stderr, gettext("-v option is "
7106 "incompatible with other arguments\n"));
7107 usage(B_FALSE);
7108 }
b9b24bb4 7109 } else if (upgradeall) {
34dc7c2f
BB
7110 if (argc != 0) {
7111 (void) fprintf(stderr, gettext("-a option should not "
7112 "be used along with a pool name\n"));
7113 usage(B_FALSE);
7114 }
7115 }
7116
9ae529ec
CS
7117 (void) printf(gettext("This system supports ZFS pool feature "
7118 "flags.\n\n"));
34dc7c2f 7119 if (showversions) {
b9b24bb4
CS
7120 int i;
7121
7122 (void) printf(gettext("The following features are "
7123 "supported:\n\n"));
7124 (void) printf(gettext("FEAT DESCRIPTION\n"));
7125 (void) printf("----------------------------------------------"
7126 "---------------\n");
7127 for (i = 0; i < SPA_FEATURES; i++) {
7128 zfeature_info_t *fi = &spa_feature_table[i];
241b5415
MA
7129 const char *ro =
7130 (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
b9b24bb4
CS
7131 " (read-only compatible)" : "";
7132
7133 (void) printf("%-37s%s\n", fi->fi_uname, ro);
7134 (void) printf(" %s\n", fi->fi_desc);
7135 }
7136 (void) printf("\n");
7137
7138 (void) printf(gettext("The following legacy versions are also "
34dc7c2f
BB
7139 "supported:\n\n"));
7140 (void) printf(gettext("VER DESCRIPTION\n"));
7141 (void) printf("--- -----------------------------------------"
7142 "---------------\n");
7143 (void) printf(gettext(" 1 Initial ZFS version\n"));
7144 (void) printf(gettext(" 2 Ditto blocks "
7145 "(replicated metadata)\n"));
7146 (void) printf(gettext(" 3 Hot spares and double parity "
7147 "RAID-Z\n"));
7148 (void) printf(gettext(" 4 zpool history\n"));
7149 (void) printf(gettext(" 5 Compression using the gzip "
7150 "algorithm\n"));
7151 (void) printf(gettext(" 6 bootfs pool property\n"));
7152 (void) printf(gettext(" 7 Separate intent log devices\n"));
7153 (void) printf(gettext(" 8 Delegated administration\n"));
7154 (void) printf(gettext(" 9 refquota and refreservation "
7155 "properties\n"));
7156 (void) printf(gettext(" 10 Cache devices\n"));
b128c09f
BB
7157 (void) printf(gettext(" 11 Improved scrub performance\n"));
7158 (void) printf(gettext(" 12 Snapshot properties\n"));
7159 (void) printf(gettext(" 13 snapused property\n"));
9babb374
BB
7160 (void) printf(gettext(" 14 passthrough-x aclinherit\n"));
7161 (void) printf(gettext(" 15 user/group space accounting\n"));
7162 (void) printf(gettext(" 16 stmf property support\n"));
45d1cae3 7163 (void) printf(gettext(" 17 Triple-parity RAID-Z\n"));
428870ff
BB
7164 (void) printf(gettext(" 18 Snapshot user holds\n"));
7165 (void) printf(gettext(" 19 Log device removal\n"));
7166 (void) printf(gettext(" 20 Compression using zle "
7167 "(zero-length encoding)\n"));
7168 (void) printf(gettext(" 21 Deduplication\n"));
7169 (void) printf(gettext(" 22 Received properties\n"));
7170 (void) printf(gettext(" 23 Slim ZIL\n"));
7171 (void) printf(gettext(" 24 System attributes\n"));
7172 (void) printf(gettext(" 25 Improved scrub stats\n"));
7173 (void) printf(gettext(" 26 Improved snapshot deletion "
7174 "performance\n"));
572e2857
BB
7175 (void) printf(gettext(" 27 Improved snapshot creation "
7176 "performance\n"));
7177 (void) printf(gettext(" 28 Multiple vdev replacements\n"));
428870ff
BB
7178 (void) printf(gettext("\nFor more information on a particular "
7179 "version, including supported releases,\n"));
7180 (void) printf(gettext("see the ZFS Administration Guide.\n\n"));
b9b24bb4
CS
7181 } else if (argc == 0 && upgradeall) {
7182 cb.cb_first = B_TRUE;
34dc7c2f 7183 ret = zpool_iter(g_zfs, upgrade_cb, &cb);
b9b24bb4
CS
7184 if (ret == 0 && cb.cb_first) {
7185 if (cb.cb_version == SPA_VERSION) {
7186 (void) printf(gettext("All pools are already "
7187 "formatted using feature flags.\n\n"));
7188 (void) printf(gettext("Every feature flags "
7189 "pool already has all supported features "
7190 "enabled.\n"));
7191 } else {
7192 (void) printf(gettext("All pools are already "
7193 "formatted with version %llu or higher.\n"),
02730c33 7194 (u_longlong_t)cb.cb_version);
34dc7c2f
BB
7195 }
7196 }
b9b24bb4
CS
7197 } else if (argc == 0) {
7198 cb.cb_first = B_TRUE;
7199 ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
7200 assert(ret == 0);
34dc7c2f 7201
b9b24bb4
CS
7202 if (cb.cb_first) {
7203 (void) printf(gettext("All pools are formatted "
7204 "using feature flags.\n\n"));
7205 } else {
7206 (void) printf(gettext("\nUse 'zpool upgrade -v' "
7207 "for a list of available legacy versions.\n"));
7208 }
7209
7210 cb.cb_first = B_TRUE;
7211 ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
7212 assert(ret == 0);
7213
7214 if (cb.cb_first) {
7215 (void) printf(gettext("Every feature flags pool has "
7216 "all supported features enabled.\n"));
7217 } else {
7218 (void) printf(gettext("\n"));
34dc7c2f
BB
7219 }
7220 } else {
7221 ret = for_each_pool(argc, argv, B_FALSE, NULL,
7222 upgrade_one, &cb);
7223 }
7224
7225 return (ret);
7226}
7227
7228typedef struct hist_cbdata {
7229 boolean_t first;
6f1ffb06
MA
7230 boolean_t longfmt;
7231 boolean_t internal;
34dc7c2f
BB
7232} hist_cbdata_t;
7233
34dc7c2f
BB
7234/*
7235 * Print out the command history for a specific pool.
7236 */
7237static int
7238get_history_one(zpool_handle_t *zhp, void *data)
7239{
7240 nvlist_t *nvhis;
7241 nvlist_t **records;
7242 uint_t numrecords;
34dc7c2f 7243 int ret, i;
34dc7c2f 7244 hist_cbdata_t *cb = (hist_cbdata_t *)data;
34dc7c2f
BB
7245
7246 cb->first = B_FALSE;
7247
7248 (void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
7249
7250 if ((ret = zpool_get_history(zhp, &nvhis)) != 0)
7251 return (ret);
7252
7253 verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
7254 &records, &numrecords) == 0);
7255 for (i = 0; i < numrecords; i++) {
6f1ffb06
MA
7256 nvlist_t *rec = records[i];
7257 char tbuf[30] = "";
34dc7c2f 7258
6f1ffb06
MA
7259 if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
7260 time_t tsec;
7261 struct tm t;
34dc7c2f 7262
6f1ffb06
MA
7263 tsec = fnvlist_lookup_uint64(records[i],
7264 ZPOOL_HIST_TIME);
7265 (void) localtime_r(&tsec, &t);
7266 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
7267 }
7268
7269 if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
7270 (void) printf("%s %s", tbuf,
7271 fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
7272 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
7273 int ievent =
7274 fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
7275 if (!cb->internal)
34dc7c2f 7276 continue;
6f1ffb06
MA
7277 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
7278 (void) printf("%s unrecognized record:\n",
7279 tbuf);
7280 dump_nvlist(rec, 4);
34dc7c2f 7281 continue;
6f1ffb06
MA
7282 }
7283 (void) printf("%s [internal %s txg:%lld] %s", tbuf,
7284 zfs_history_event_names[ievent],
02730c33 7285 (longlong_t)fnvlist_lookup_uint64(
d1d7e268 7286 rec, ZPOOL_HIST_TXG),
6f1ffb06
MA
7287 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
7288 } else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
7289 if (!cb->internal)
7290 continue;
7291 (void) printf("%s [txg:%lld] %s", tbuf,
02730c33 7292 (longlong_t)fnvlist_lookup_uint64(
d1d7e268 7293 rec, ZPOOL_HIST_TXG),
6f1ffb06
MA
7294 fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
7295 if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
7296 (void) printf(" %s (%llu)",
7297 fnvlist_lookup_string(rec,
7298 ZPOOL_HIST_DSNAME),
d1d7e268 7299 (u_longlong_t)fnvlist_lookup_uint64(rec,
6f1ffb06
MA
7300 ZPOOL_HIST_DSID));
7301 }
7302 (void) printf(" %s", fnvlist_lookup_string(rec,
7303 ZPOOL_HIST_INT_STR));
7304 } else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
7305 if (!cb->internal)
7306 continue;
7307 (void) printf("%s ioctl %s\n", tbuf,
7308 fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
7309 if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
7310 (void) printf(" input:\n");
7311 dump_nvlist(fnvlist_lookup_nvlist(rec,
7312 ZPOOL_HIST_INPUT_NVL), 8);
7313 }
7314 if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
7315 (void) printf(" output:\n");
7316 dump_nvlist(fnvlist_lookup_nvlist(rec,
7317 ZPOOL_HIST_OUTPUT_NVL), 8);
7318 }
7319 } else {
7320 if (!cb->internal)
7321 continue;
7322 (void) printf("%s unrecognized record:\n", tbuf);
7323 dump_nvlist(rec, 4);
34dc7c2f 7324 }
34dc7c2f
BB
7325
7326 if (!cb->longfmt) {
7327 (void) printf("\n");
7328 continue;
7329 }
7330 (void) printf(" [");
6f1ffb06
MA
7331 if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
7332 uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
7333 struct passwd *pwd = getpwuid(who);
7334 (void) printf("user %d ", (int)who);
7335 if (pwd != NULL)
7336 (void) printf("(%s) ", pwd->pw_name);
34dc7c2f 7337 }
6f1ffb06
MA
7338 if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
7339 (void) printf("on %s",
7340 fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
34dc7c2f 7341 }
6f1ffb06
MA
7342 if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
7343 (void) printf(":%s",
7344 fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
34dc7c2f
BB
7345 }
7346
7347 (void) printf("]");
7348 (void) printf("\n");
7349 }
7350 (void) printf("\n");
7351 nvlist_free(nvhis);
7352
7353 return (ret);
7354}
7355
7356/*
7357 * zpool history <pool>
7358 *
7359 * Displays the history of commands that modified pools.
7360 */
34dc7c2f
BB
7361int
7362zpool_do_history(int argc, char **argv)
7363{
7364 hist_cbdata_t cbdata = { 0 };
7365 int ret;
7366 int c;
7367
7368 cbdata.first = B_TRUE;
7369 /* check options */
7370 while ((c = getopt(argc, argv, "li")) != -1) {
7371 switch (c) {
7372 case 'l':
6f1ffb06 7373 cbdata.longfmt = B_TRUE;
34dc7c2f
BB
7374 break;
7375 case 'i':
6f1ffb06 7376 cbdata.internal = B_TRUE;
34dc7c2f
BB
7377 break;
7378 case '?':
7379 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7380 optopt);
7381 usage(B_FALSE);
7382 }
7383 }
7384 argc -= optind;
7385 argv += optind;
7386
7387 ret = for_each_pool(argc, argv, B_FALSE, NULL, get_history_one,
7388 &cbdata);
7389
7390 if (argc == 0 && cbdata.first == B_TRUE) {
42cb3819 7391 (void) fprintf(stderr, gettext("no pools available\n"));
34dc7c2f
BB
7392 return (0);
7393 }
7394
7395 return (ret);
7396}
7397
26685276
BB
7398typedef struct ev_opts {
7399 int verbose;
c5343ba7 7400 int scripted;
26685276
BB
7401 int follow;
7402 int clear;
88f9c939 7403 char poolname[ZFS_MAX_DATASET_NAME_LEN];
26685276
BB
7404} ev_opts_t;
7405
7406static void
1e1c3980 7407zpool_do_events_short(nvlist_t *nvl, ev_opts_t *opts)
26685276
BB
7408{
7409 char ctime_str[26], str[32], *ptr;
7410 int64_t *tv;
7411 uint_t n;
7412
7413 verify(nvlist_lookup_int64_array(nvl, FM_EREPORT_TIME, &tv, &n) == 0);
7414 memset(str, ' ', 32);
7415 (void) ctime_r((const time_t *)&tv[0], ctime_str);
d1d7e268
MK
7416 (void) strncpy(str, ctime_str+4, 6); /* 'Jun 30' */
7417 (void) strncpy(str+7, ctime_str+20, 4); /* '1993' */
7418 (void) strncpy(str+12, ctime_str+11, 8); /* '21:49:08' */
7419 (void) sprintf(str+20, ".%09lld", (longlong_t)tv[1]); /* '.123456789' */
1e1c3980
SH
7420 if (opts->scripted)
7421 (void) printf(gettext("%s\t"), str);
7422 else
7423 (void) printf(gettext("%s "), str);
26685276
BB
7424
7425 verify(nvlist_lookup_string(nvl, FM_CLASS, &ptr) == 0);
7426 (void) printf(gettext("%s\n"), ptr);
7427}
7428
7429static void
7430zpool_do_events_nvprint(nvlist_t *nvl, int depth)
7431{
7432 nvpair_t *nvp;
7433
7434 for (nvp = nvlist_next_nvpair(nvl, NULL);
7435 nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp)) {
7436
7437 data_type_t type = nvpair_type(nvp);
7438 const char *name = nvpair_name(nvp);
7439
7440 boolean_t b;
7441 uint8_t i8;
7442 uint16_t i16;
7443 uint32_t i32;
7444 uint64_t i64;
7445 char *str;
7446 nvlist_t *cnv;
7447
7448 printf(gettext("%*s%s = "), depth, "", name);
7449
7450 switch (type) {
7451 case DATA_TYPE_BOOLEAN:
7452 printf(gettext("%s"), "1");
7453 break;
7454
7455 case DATA_TYPE_BOOLEAN_VALUE:
7456 (void) nvpair_value_boolean_value(nvp, &b);
7457 printf(gettext("%s"), b ? "1" : "0");
7458 break;
7459
7460 case DATA_TYPE_BYTE:
7461 (void) nvpair_value_byte(nvp, &i8);
7462 printf(gettext("0x%x"), i8);
7463 break;
7464
7465 case DATA_TYPE_INT8:
7466 (void) nvpair_value_int8(nvp, (void *)&i8);
7467 printf(gettext("0x%x"), i8);
7468 break;
7469
7470 case DATA_TYPE_UINT8:
7471 (void) nvpair_value_uint8(nvp, &i8);
7472 printf(gettext("0x%x"), i8);
7473 break;
7474
7475 case DATA_TYPE_INT16:
7476 (void) nvpair_value_int16(nvp, (void *)&i16);
7477 printf(gettext("0x%x"), i16);
7478 break;
7479
7480 case DATA_TYPE_UINT16:
7481 (void) nvpair_value_uint16(nvp, &i16);
7482 printf(gettext("0x%x"), i16);
7483 break;
7484
7485 case DATA_TYPE_INT32:
7486 (void) nvpair_value_int32(nvp, (void *)&i32);
7487 printf(gettext("0x%x"), i32);
7488 break;
7489
7490 case DATA_TYPE_UINT32:
7491 (void) nvpair_value_uint32(nvp, &i32);
7492 printf(gettext("0x%x"), i32);
7493 break;
7494
7495 case DATA_TYPE_INT64:
7496 (void) nvpair_value_int64(nvp, (void *)&i64);
7497 printf(gettext("0x%llx"), (u_longlong_t)i64);
7498 break;
7499
7500 case DATA_TYPE_UINT64:
7501 (void) nvpair_value_uint64(nvp, &i64);
d02ca379
DB
7502 /*
7503 * translate vdev state values to readable
7504 * strings to aide zpool events consumers
7505 */
7506 if (strcmp(name,
7507 FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE) == 0 ||
7508 strcmp(name,
7509 FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE) == 0) {
7510 printf(gettext("\"%s\" (0x%llx)"),
7511 zpool_state_to_name(i64, VDEV_AUX_NONE),
7512 (u_longlong_t)i64);
7513 } else {
7514 printf(gettext("0x%llx"), (u_longlong_t)i64);
7515 }
26685276
BB
7516 break;
7517
7518 case DATA_TYPE_HRTIME:
7519 (void) nvpair_value_hrtime(nvp, (void *)&i64);
7520 printf(gettext("0x%llx"), (u_longlong_t)i64);
7521 break;
7522
7523 case DATA_TYPE_STRING:
7524 (void) nvpair_value_string(nvp, &str);
7525 printf(gettext("\"%s\""), str ? str : "<NULL>");
7526 break;
7527
7528 case DATA_TYPE_NVLIST:
7529 printf(gettext("(embedded nvlist)\n"));
7530 (void) nvpair_value_nvlist(nvp, &cnv);
7531 zpool_do_events_nvprint(cnv, depth + 8);
c5343ba7 7532 printf(gettext("%*s(end %s)"), depth, "", name);
26685276
BB
7533 break;
7534
7535 case DATA_TYPE_NVLIST_ARRAY: {
7536 nvlist_t **val;
7537 uint_t i, nelem;
7538
7539 (void) nvpair_value_nvlist_array(nvp, &val, &nelem);
7540 printf(gettext("(%d embedded nvlists)\n"), nelem);
7541 for (i = 0; i < nelem; i++) {
7542 printf(gettext("%*s%s[%d] = %s\n"),
d1d7e268 7543 depth, "", name, i, "(embedded nvlist)");
26685276
BB
7544 zpool_do_events_nvprint(val[i], depth + 8);
7545 printf(gettext("%*s(end %s[%i])\n"),
d1d7e268 7546 depth, "", name, i);
26685276
BB
7547 }
7548 printf(gettext("%*s(end %s)\n"), depth, "", name);
7549 }
7550 break;
7551
7552 case DATA_TYPE_INT8_ARRAY: {
7553 int8_t *val;
7554 uint_t i, nelem;
7555
7556 (void) nvpair_value_int8_array(nvp, &val, &nelem);
7557 for (i = 0; i < nelem; i++)
7558 printf(gettext("0x%x "), val[i]);
7559
7560 break;
7561 }
7562
7563 case DATA_TYPE_UINT8_ARRAY: {
7564 uint8_t *val;
7565 uint_t i, nelem;
7566
7567 (void) nvpair_value_uint8_array(nvp, &val, &nelem);
7568 for (i = 0; i < nelem; i++)
7569 printf(gettext("0x%x "), val[i]);
7570
7571 break;
7572 }
7573
7574 case DATA_TYPE_INT16_ARRAY: {
7575 int16_t *val;
7576 uint_t i, nelem;
7577
7578 (void) nvpair_value_int16_array(nvp, &val, &nelem);
7579 for (i = 0; i < nelem; i++)
7580 printf(gettext("0x%x "), val[i]);
7581
7582 break;
7583 }
7584
7585 case DATA_TYPE_UINT16_ARRAY: {
7586 uint16_t *val;
7587 uint_t i, nelem;
7588
7589 (void) nvpair_value_uint16_array(nvp, &val, &nelem);
7590 for (i = 0; i < nelem; i++)
7591 printf(gettext("0x%x "), val[i]);
7592
7593 break;
7594 }
7595
7596 case DATA_TYPE_INT32_ARRAY: {
7597 int32_t *val;
7598 uint_t i, nelem;
7599
7600 (void) nvpair_value_int32_array(nvp, &val, &nelem);
7601 for (i = 0; i < nelem; i++)
7602 printf(gettext("0x%x "), val[i]);
7603
7604 break;
7605 }
7606
7607 case DATA_TYPE_UINT32_ARRAY: {
7608 uint32_t *val;
7609 uint_t i, nelem;
7610
7611 (void) nvpair_value_uint32_array(nvp, &val, &nelem);
7612 for (i = 0; i < nelem; i++)
7613 printf(gettext("0x%x "), val[i]);
7614
7615 break;
7616 }
7617
7618 case DATA_TYPE_INT64_ARRAY: {
7619 int64_t *val;
7620 uint_t i, nelem;
7621
7622 (void) nvpair_value_int64_array(nvp, &val, &nelem);
7623 for (i = 0; i < nelem; i++)
d1d7e268
MK
7624 printf(gettext("0x%llx "),
7625 (u_longlong_t)val[i]);
26685276
BB
7626
7627 break;
7628 }
7629
7630 case DATA_TYPE_UINT64_ARRAY: {
7631 uint64_t *val;
7632 uint_t i, nelem;
7633
7634 (void) nvpair_value_uint64_array(nvp, &val, &nelem);
7635 for (i = 0; i < nelem; i++)
d1d7e268
MK
7636 printf(gettext("0x%llx "),
7637 (u_longlong_t)val[i]);
26685276
BB
7638
7639 break;
7640 }
7641
d21705ea
BB
7642 case DATA_TYPE_STRING_ARRAY: {
7643 char **str;
7644 uint_t i, nelem;
7645
7646 (void) nvpair_value_string_array(nvp, &str, &nelem);
7647 for (i = 0; i < nelem; i++)
7648 printf(gettext("\"%s\" "),
7649 str[i] ? str[i] : "<NULL>");
7650
7651 break;
7652 }
7653
26685276
BB
7654 case DATA_TYPE_BOOLEAN_ARRAY:
7655 case DATA_TYPE_BYTE_ARRAY:
7656 case DATA_TYPE_DOUBLE:
7657 case DATA_TYPE_UNKNOWN:
7658 printf(gettext("<unknown>"));
7659 break;
7660 }
7661
7662 printf(gettext("\n"));
7663 }
7664}
7665
7666static int
7667zpool_do_events_next(ev_opts_t *opts)
7668{
7669 nvlist_t *nvl;
9b101a73 7670 int zevent_fd, ret, dropped;
88f9c939 7671 char *pool;
26685276 7672
9b101a73
BB
7673 zevent_fd = open(ZFS_DEV, O_RDWR);
7674 VERIFY(zevent_fd >= 0);
26685276 7675
c5343ba7
BB
7676 if (!opts->scripted)
7677 (void) printf(gettext("%-30s %s\n"), "TIME", "CLASS");
26685276
BB
7678
7679 while (1) {
7680 ret = zpool_events_next(g_zfs, &nvl, &dropped,
8c7aa0cf 7681 (opts->follow ? ZEVENT_NONE : ZEVENT_NONBLOCK), zevent_fd);
26685276
BB
7682 if (ret || nvl == NULL)
7683 break;
7684
7685 if (dropped > 0)
7686 (void) printf(gettext("dropped %d events\n"), dropped);
7687
88f9c939 7688 if (strlen(opts->poolname) > 0 &&
7689 nvlist_lookup_string(nvl, FM_FMRI_ZFS_POOL, &pool) == 0 &&
7690 strcmp(opts->poolname, pool) != 0)
7691 continue;
7692
1e1c3980 7693 zpool_do_events_short(nvl, opts);
26685276
BB
7694
7695 if (opts->verbose) {
7696 zpool_do_events_nvprint(nvl, 8);
7697 printf(gettext("\n"));
7698 }
50fe577d 7699 (void) fflush(stdout);
26685276
BB
7700
7701 nvlist_free(nvl);
7702 }
7703
9b101a73 7704 VERIFY(0 == close(zevent_fd));
26685276
BB
7705
7706 return (ret);
7707}
7708
7709static int
7710zpool_do_events_clear(ev_opts_t *opts)
7711{
7712 int count, ret;
7713
7714 ret = zpool_events_clear(g_zfs, &count);
7715 if (!ret)
7716 (void) printf(gettext("cleared %d events\n"), count);
7717
7718 return (ret);
7719}
7720
7721/*
88f9c939 7722 * zpool events [-vHf [pool] | -c]
26685276
BB
7723 *
7724 * Displays events logs by ZFS.
7725 */
7726int
7727zpool_do_events(int argc, char **argv)
7728{
7729 ev_opts_t opts = { 0 };
7730 int ret;
7731 int c;
7732
7733 /* check options */
c5343ba7 7734 while ((c = getopt(argc, argv, "vHfc")) != -1) {
26685276
BB
7735 switch (c) {
7736 case 'v':
7737 opts.verbose = 1;
c5343ba7
BB
7738 break;
7739 case 'H':
7740 opts.scripted = 1;
26685276
BB
7741 break;
7742 case 'f':
7743 opts.follow = 1;
7744 break;
7745 case 'c':
7746 opts.clear = 1;
7747 break;
7748 case '?':
7749 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7750 optopt);
7751 usage(B_FALSE);
7752 }
7753 }
7754 argc -= optind;
7755 argv += optind;
7756
88f9c939 7757 if (argc > 1) {
7758 (void) fprintf(stderr, gettext("too many arguments\n"));
7759 usage(B_FALSE);
7760 } else if (argc == 1) {
7761 (void) strlcpy(opts.poolname, argv[0], sizeof (opts.poolname));
7762 if (!zfs_name_valid(opts.poolname, ZFS_TYPE_POOL)) {
7763 (void) fprintf(stderr,
7764 gettext("invalid pool name '%s'\n"), opts.poolname);
7765 usage(B_FALSE);
7766 }
7767 }
7768
7769 if ((argc == 1 || opts.verbose || opts.scripted || opts.follow) &&
7770 opts.clear) {
7771 (void) fprintf(stderr,
7772 gettext("invalid options combined with -c\n"));
7773 usage(B_FALSE);
7774 }
7775
26685276
BB
7776 if (opts.clear)
7777 ret = zpool_do_events_clear(&opts);
7778 else
7779 ret = zpool_do_events_next(&opts);
7780
d1d7e268 7781 return (ret);
26685276
BB
7782}
7783
34dc7c2f
BB
7784static int
7785get_callback(zpool_handle_t *zhp, void *data)
7786{
7787 zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
7788 char value[MAXNAMELEN];
7789 zprop_source_t srctype;
7790 zprop_list_t *pl;
7791
7792 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
7793
7794 /*
7795 * Skip the special fake placeholder. This will also skip
7796 * over the name property when 'all' is specified.
7797 */
7798 if (pl->pl_prop == ZPOOL_PROP_NAME &&
7799 pl == cbp->cb_proplist)
7800 continue;
7801
9ae529ec
CS
7802 if (pl->pl_prop == ZPROP_INVAL &&
7803 (zpool_prop_feature(pl->pl_user_prop) ||
7804 zpool_prop_unsupported(pl->pl_user_prop))) {
7805 srctype = ZPROP_SRC_LOCAL;
34dc7c2f 7806
9ae529ec
CS
7807 if (zpool_prop_get_feature(zhp, pl->pl_user_prop,
7808 value, sizeof (value)) == 0) {
7809 zprop_print_one_property(zpool_get_name(zhp),
7810 cbp, pl->pl_user_prop, value, srctype,
7811 NULL, NULL);
7812 }
7813 } else {
2a8b84b7 7814 if (zpool_get_prop(zhp, pl->pl_prop, value,
d65e7381 7815 sizeof (value), &srctype, cbp->cb_literal) != 0)
9ae529ec
CS
7816 continue;
7817
7818 zprop_print_one_property(zpool_get_name(zhp), cbp,
7819 zpool_prop_to_name(pl->pl_prop), value, srctype,
7820 NULL, NULL);
7821 }
34dc7c2f
BB
7822 }
7823 return (0);
7824}
7825
2a8b84b7
AS
7826/*
7827 * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
7828 *
7829 * -H Scripted mode. Don't display headers, and separate properties
7830 * by a single tab.
7831 * -o List of columns to display. Defaults to
7832 * "name,property,value,source".
4e33ba4c 7833 * -p Display values in parsable (exact) format.
2a8b84b7
AS
7834 *
7835 * Get properties of pools in the system. Output space statistics
7836 * for each one as well as other attributes.
7837 */
34dc7c2f
BB
7838int
7839zpool_do_get(int argc, char **argv)
7840{
7841 zprop_get_cbdata_t cb = { 0 };
7842 zprop_list_t fake_name = { 0 };
2a8b84b7
AS
7843 int ret;
7844 int c, i;
7845 char *value;
7846
7847 cb.cb_first = B_TRUE;
7848
7849 /*
7850 * Set up default columns and sources.
7851 */
7852 cb.cb_sources = ZPROP_SRC_ALL;
7853 cb.cb_columns[0] = GET_COL_NAME;
7854 cb.cb_columns[1] = GET_COL_PROPERTY;
7855 cb.cb_columns[2] = GET_COL_VALUE;
7856 cb.cb_columns[3] = GET_COL_SOURCE;
7857 cb.cb_type = ZFS_TYPE_POOL;
34dc7c2f 7858
d65e7381 7859 /* check options */
2a8b84b7 7860 while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
d65e7381
RE
7861 switch (c) {
7862 case 'p':
7863 cb.cb_literal = B_TRUE;
7864 break;
79eb71dc
TF
7865 case 'H':
7866 cb.cb_scripted = B_TRUE;
7867 break;
2a8b84b7
AS
7868 case 'o':
7869 bzero(&cb.cb_columns, sizeof (cb.cb_columns));
7870 i = 0;
7871 while (*optarg != '\0') {
7872 static char *col_subopts[] =
7873 { "name", "property", "value", "source",
7874 "all", NULL };
7875
7876 if (i == ZFS_GET_NCOLS) {
7877 (void) fprintf(stderr, gettext("too "
7878 "many fields given to -o "
7879 "option\n"));
7880 usage(B_FALSE);
7881 }
79eb71dc 7882
2a8b84b7
AS
7883 switch (getsubopt(&optarg, col_subopts,
7884 &value)) {
7885 case 0:
7886 cb.cb_columns[i++] = GET_COL_NAME;
7887 break;
7888 case 1:
7889 cb.cb_columns[i++] = GET_COL_PROPERTY;
7890 break;
7891 case 2:
7892 cb.cb_columns[i++] = GET_COL_VALUE;
7893 break;
7894 case 3:
7895 cb.cb_columns[i++] = GET_COL_SOURCE;
7896 break;
7897 case 4:
7898 if (i > 0) {
7899 (void) fprintf(stderr,
7900 gettext("\"all\" conflicts "
7901 "with specific fields "
7902 "given to -o option\n"));
7903 usage(B_FALSE);
7904 }
7905 cb.cb_columns[0] = GET_COL_NAME;
7906 cb.cb_columns[1] = GET_COL_PROPERTY;
7907 cb.cb_columns[2] = GET_COL_VALUE;
7908 cb.cb_columns[3] = GET_COL_SOURCE;
7909 i = ZFS_GET_NCOLS;
7910 break;
7911 default:
7912 (void) fprintf(stderr,
7913 gettext("invalid column name "
7914 "'%s'\n"), value);
7915 usage(B_FALSE);
7916 }
7917 }
7918 break;
d65e7381
RE
7919 case '?':
7920 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7921 optopt);
7922 usage(B_FALSE);
7923 }
7924 }
7925
7926 argc -= optind;
7927 argv += optind;
7928
7929 if (argc < 1) {
9ae529ec
CS
7930 (void) fprintf(stderr, gettext("missing property "
7931 "argument\n"));
34dc7c2f 7932 usage(B_FALSE);
9ae529ec 7933 }
34dc7c2f 7934
2a8b84b7
AS
7935 if (zprop_get_list(g_zfs, argv[0], &cb.cb_proplist,
7936 ZFS_TYPE_POOL) != 0)
34dc7c2f
BB
7937 usage(B_FALSE);
7938
d65e7381
RE
7939 argc--;
7940 argv++;
7941
34dc7c2f
BB
7942 if (cb.cb_proplist != NULL) {
7943 fake_name.pl_prop = ZPOOL_PROP_NAME;
7944 fake_name.pl_width = strlen(gettext("NAME"));
7945 fake_name.pl_next = cb.cb_proplist;
7946 cb.cb_proplist = &fake_name;
7947 }
7948
d65e7381 7949 ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist,
34dc7c2f
BB
7950 get_callback, &cb);
7951
7952 if (cb.cb_proplist == &fake_name)
7953 zprop_free_list(fake_name.pl_next);
7954 else
7955 zprop_free_list(cb.cb_proplist);
7956
7957 return (ret);
7958}
7959
7960typedef struct set_cbdata {
7961 char *cb_propname;
7962 char *cb_value;
7963 boolean_t cb_any_successful;
7964} set_cbdata_t;
7965
7966int
7967set_callback(zpool_handle_t *zhp, void *data)
7968{
7969 int error;
7970 set_cbdata_t *cb = (set_cbdata_t *)data;
7971
7972 error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
7973
7974 if (!error)
7975 cb->cb_any_successful = B_TRUE;
7976
7977 return (error);
7978}
7979
7980int
7981zpool_do_set(int argc, char **argv)
7982{
7983 set_cbdata_t cb = { 0 };
7984 int error;
7985
7986 if (argc > 1 && argv[1][0] == '-') {
7987 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7988 argv[1][1]);
7989 usage(B_FALSE);
7990 }
7991
7992 if (argc < 2) {
7993 (void) fprintf(stderr, gettext("missing property=value "
7994 "argument\n"));
7995 usage(B_FALSE);
7996 }
7997
7998 if (argc < 3) {
7999 (void) fprintf(stderr, gettext("missing pool name\n"));
8000 usage(B_FALSE);
8001 }
8002
8003 if (argc > 3) {
8004 (void) fprintf(stderr, gettext("too many pool names\n"));
8005 usage(B_FALSE);
8006 }
8007
8008 cb.cb_propname = argv[1];
8009 cb.cb_value = strchr(cb.cb_propname, '=');
8010 if (cb.cb_value == NULL) {
8011 (void) fprintf(stderr, gettext("missing value in "
8012 "property=value argument\n"));
8013 usage(B_FALSE);
8014 }
8015
8016 *(cb.cb_value) = '\0';
8017 cb.cb_value++;
8018
8019 error = for_each_pool(argc - 2, argv + 2, B_TRUE, NULL,
8020 set_callback, &cb);
8021
8022 return (error);
8023}
8024
8025static int
8026find_command_idx(char *command, int *idx)
8027{
8028 int i;
8029
8030 for (i = 0; i < NCOMMAND; i++) {
8031 if (command_table[i].name == NULL)
8032 continue;
8033
8034 if (strcmp(command, command_table[i].name) == 0) {
8035 *idx = i;
8036 return (0);
8037 }
8038 }
8039 return (1);
8040}
8041
8042int
8043main(int argc, char **argv)
8044{
8e896579 8045 int ret = 0;
d4ed6673 8046 int i = 0;
34dc7c2f
BB
8047 char *cmdname;
8048
8049 (void) setlocale(LC_ALL, "");
8050 (void) textdomain(TEXT_DOMAIN);
5b4136bd 8051 srand(time(NULL));
34dc7c2f 8052
34dc7c2f
BB
8053 opterr = 0;
8054
8055 /*
8056 * Make sure the user has specified some command.
8057 */
8058 if (argc < 2) {
8059 (void) fprintf(stderr, gettext("missing command\n"));
8060 usage(B_FALSE);
8061 }
8062
8063 cmdname = argv[1];
8064
8065 /*
8066 * Special case '-?'
8067 */
d1d7e268 8068 if ((strcmp(cmdname, "-?") == 0) || strcmp(cmdname, "--help") == 0)
34dc7c2f
BB
8069 usage(B_TRUE);
8070
65037d9b
BB
8071 if ((g_zfs = libzfs_init()) == NULL) {
8072 (void) fprintf(stderr, "%s", libzfs_error_init(errno));
9b020fd9 8073 return (1);
65037d9b 8074 }
9b020fd9
BB
8075
8076 libzfs_print_on_error(g_zfs, B_TRUE);
8077
6f1ffb06 8078 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
34dc7c2f
BB
8079
8080 /*
8081 * Run the appropriate command.
8082 */
8083 if (find_command_idx(cmdname, &i) == 0) {
8084 current_command = &command_table[i];
8085 ret = command_table[i].func(argc - 1, argv + 1);
8086 } else if (strchr(cmdname, '=')) {
8087 verify(find_command_idx("set", &i) == 0);
8088 current_command = &command_table[i];
8089 ret = command_table[i].func(argc, argv);
8090 } else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
8091 /*
8092 * 'freeze' is a vile debugging abomination, so we treat
8093 * it as such.
8094 */
4807c0ba
TC
8095 zfs_cmd_t zc = {"\0"};
8096
8097 (void) strlcpy(zc.zc_name, argv[2], sizeof (zc.zc_name));
8098 ret = zfs_ioctl(g_zfs, ZFS_IOC_POOL_FREEZE, &zc);
8099 if (ret != 0) {
8100 (void) fprintf(stderr,
8101 gettext("failed to freeze pool: %d\n"), errno);
8102 ret = 1;
8103 }
8104
8105 log_history = 0;
34dc7c2f
BB
8106 } else {
8107 (void) fprintf(stderr, gettext("unrecognized "
8108 "command '%s'\n"), cmdname);
8109 usage(B_FALSE);
d4ed6673 8110 ret = 1;
34dc7c2f
BB
8111 }
8112
6f1ffb06
MA
8113 if (ret == 0 && log_history)
8114 (void) zpool_log_history(g_zfs, history_str);
8115
34dc7c2f
BB
8116 libzfs_fini(g_zfs);
8117
8118 /*
8119 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
8120 * for the purposes of running ::findleaks.
8121 */
8122 if (getenv("ZFS_ABORT") != NULL) {
8123 (void) printf("dumping core by request\n");
8124 abort();
8125 }
8126
8127 return (ret);
8128}