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