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