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