xref: /titanic_50/usr/src/cmd/zpool/zpool_main.c (revision 986ccb2981903ad100842c6fde78b8152146700d)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
25  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
26  * Copyright (c) 2012 by Frederik Wessels. All rights reserved.
27  * Copyright (c) 2013 by Prasad Joshi (sTec). All rights reserved.
28  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
29  */
30 
31 #include <assert.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <libgen.h>
37 #include <libintl.h>
38 #include <libuutil.h>
39 #include <locale.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <strings.h>
44 #include <unistd.h>
45 #include <priv.h>
46 #include <pwd.h>
47 #include <zone.h>
48 #include <zfs_prop.h>
49 #include <sys/fs/zfs.h>
50 #include <sys/stat.h>
51 #include <syslog.h>
52 
53 #include <libzfs.h>
54 
55 #include "zpool_util.h"
56 #include "zfs_comutil.h"
57 #include "zfeature_common.h"
58 
59 #include "statcommon.h"
60 
61 static int zpool_do_create(int, char **);
62 static int zpool_do_destroy(int, char **);
63 
64 static int zpool_do_add(int, char **);
65 static int zpool_do_remove(int, char **);
66 
67 static int zpool_do_list(int, char **);
68 static int zpool_do_iostat(int, char **);
69 static int zpool_do_status(int, char **);
70 
71 static int zpool_do_online(int, char **);
72 static int zpool_do_offline(int, char **);
73 static int zpool_do_clear(int, char **);
74 static int zpool_do_reopen(int, char **);
75 
76 static int zpool_do_reguid(int, char **);
77 
78 static int zpool_do_attach(int, char **);
79 static int zpool_do_detach(int, char **);
80 static int zpool_do_replace(int, char **);
81 static int zpool_do_split(int, char **);
82 
83 static int zpool_do_scrub(int, char **);
84 
85 static int zpool_do_import(int, char **);
86 static int zpool_do_export(int, char **);
87 
88 static int zpool_do_upgrade(int, char **);
89 
90 static int zpool_do_history(int, char **);
91 
92 static int zpool_do_get(int, char **);
93 static int zpool_do_set(int, char **);
94 
95 /*
96  * These libumem hooks provide a reasonable set of defaults for the allocator's
97  * debugging facilities.
98  */
99 
100 #ifdef DEBUG
101 const char *
_umem_debug_init(void)102 _umem_debug_init(void)
103 {
104 	return ("default,verbose"); /* $UMEM_DEBUG setting */
105 }
106 
107 const char *
_umem_logging_init(void)108 _umem_logging_init(void)
109 {
110 	return ("fail,contents"); /* $UMEM_LOGGING setting */
111 }
112 #endif
113 
114 typedef enum {
115 	HELP_ADD,
116 	HELP_ATTACH,
117 	HELP_CLEAR,
118 	HELP_CREATE,
119 	HELP_DESTROY,
120 	HELP_DETACH,
121 	HELP_EXPORT,
122 	HELP_HISTORY,
123 	HELP_IMPORT,
124 	HELP_IOSTAT,
125 	HELP_LIST,
126 	HELP_OFFLINE,
127 	HELP_ONLINE,
128 	HELP_REPLACE,
129 	HELP_REMOVE,
130 	HELP_SCRUB,
131 	HELP_STATUS,
132 	HELP_UPGRADE,
133 	HELP_GET,
134 	HELP_SET,
135 	HELP_SPLIT,
136 	HELP_REGUID,
137 	HELP_REOPEN
138 } zpool_help_t;
139 
140 
141 typedef struct zpool_command {
142 	const char	*name;
143 	int		(*func)(int, char **);
144 	zpool_help_t	usage;
145 } zpool_command_t;
146 
147 /*
148  * Master command table.  Each ZFS command has a name, associated function, and
149  * usage message.  The usage messages need to be internationalized, so we have
150  * to have a function to return the usage message based on a command index.
151  *
152  * These commands are organized according to how they are displayed in the usage
153  * message.  An empty command (one with a NULL name) indicates an empty line in
154  * the generic usage message.
155  */
156 static zpool_command_t command_table[] = {
157 	{ "create",	zpool_do_create,	HELP_CREATE		},
158 	{ "destroy",	zpool_do_destroy,	HELP_DESTROY		},
159 	{ NULL },
160 	{ "add",	zpool_do_add,		HELP_ADD		},
161 	{ "remove",	zpool_do_remove,	HELP_REMOVE		},
162 	{ NULL },
163 	{ "list",	zpool_do_list,		HELP_LIST		},
164 	{ "iostat",	zpool_do_iostat,	HELP_IOSTAT		},
165 	{ "status",	zpool_do_status,	HELP_STATUS		},
166 	{ NULL },
167 	{ "online",	zpool_do_online,	HELP_ONLINE		},
168 	{ "offline",	zpool_do_offline,	HELP_OFFLINE		},
169 	{ "clear",	zpool_do_clear,		HELP_CLEAR		},
170 	{ "reopen",	zpool_do_reopen,	HELP_REOPEN		},
171 	{ NULL },
172 	{ "attach",	zpool_do_attach,	HELP_ATTACH		},
173 	{ "detach",	zpool_do_detach,	HELP_DETACH		},
174 	{ "replace",	zpool_do_replace,	HELP_REPLACE		},
175 	{ "split",	zpool_do_split,		HELP_SPLIT		},
176 	{ NULL },
177 	{ "scrub",	zpool_do_scrub,		HELP_SCRUB		},
178 	{ NULL },
179 	{ "import",	zpool_do_import,	HELP_IMPORT		},
180 	{ "export",	zpool_do_export,	HELP_EXPORT		},
181 	{ "upgrade",	zpool_do_upgrade,	HELP_UPGRADE		},
182 	{ "reguid",	zpool_do_reguid,	HELP_REGUID		},
183 	{ NULL },
184 	{ "history",	zpool_do_history,	HELP_HISTORY		},
185 	{ "get",	zpool_do_get,		HELP_GET		},
186 	{ "set",	zpool_do_set,		HELP_SET		},
187 };
188 
189 #define	NCOMMAND	(sizeof (command_table) / sizeof (command_table[0]))
190 
191 static zpool_command_t *current_command;
192 static char history_str[HIS_MAX_RECORD_LEN];
193 static boolean_t log_history = B_TRUE;
194 static uint_t timestamp_fmt = NODATE;
195 
196 static const char *
get_usage(zpool_help_t idx)197 get_usage(zpool_help_t idx)
198 {
199 	switch (idx) {
200 	case HELP_ADD:
201 		return (gettext("\tadd [-fn] <pool> <vdev> ...\n"));
202 	case HELP_ATTACH:
203 		return (gettext("\tattach [-f] <pool> <device> "
204 		    "<new-device>\n"));
205 	case HELP_CLEAR:
206 		return (gettext("\tclear [-nF] <pool> [device]\n"));
207 	case HELP_CREATE:
208 		return (gettext("\tcreate [-fnd] [-o property=value] ... \n"
209 		    "\t    [-O file-system-property=value] ... \n"
210 		    "\t    [-m mountpoint] [-R root] <pool> <vdev> ...\n"));
211 	case HELP_DESTROY:
212 		return (gettext("\tdestroy [-f] <pool>\n"));
213 	case HELP_DETACH:
214 		return (gettext("\tdetach <pool> <device>\n"));
215 	case HELP_EXPORT:
216 		return (gettext("\texport [-f] <pool> ...\n"));
217 	case HELP_HISTORY:
218 		return (gettext("\thistory [-il] [<pool>] ...\n"));
219 	case HELP_IMPORT:
220 		return (gettext("\timport [-d dir] [-D]\n"
221 		    "\timport [-d dir | -c cachefile] [-F [-n]] <pool | id>\n"
222 		    "\timport [-o mntopts] [-o property=value] ... \n"
223 		    "\t    [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
224 		    "[-R root] [-F [-n]] -a\n"
225 		    "\timport [-o mntopts] [-o property=value] ... \n"
226 		    "\t    [-d dir | -c cachefile] [-D] [-f] [-m] [-N] "
227 		    "[-R root] [-F [-n]]\n"
228 		    "\t    <pool | id> [newpool]\n"));
229 	case HELP_IOSTAT:
230 		return (gettext("\tiostat [-v] [-T d|u] [pool] ... [interval "
231 		    "[count]]\n"));
232 	case HELP_LIST:
233 		return (gettext("\tlist [-Hp] [-o property[,...]] "
234 		    "[-T d|u] [pool] ... [interval [count]]\n"));
235 	case HELP_OFFLINE:
236 		return (gettext("\toffline [-t] <pool> <device> ...\n"));
237 	case HELP_ONLINE:
238 		return (gettext("\tonline <pool> <device> ...\n"));
239 	case HELP_REPLACE:
240 		return (gettext("\treplace [-f] <pool> <device> "
241 		    "[new-device]\n"));
242 	case HELP_REMOVE:
243 		return (gettext("\tremove <pool> <device> ...\n"));
244 	case HELP_REOPEN:
245 		return (gettext("\treopen <pool>\n"));
246 	case HELP_SCRUB:
247 		return (gettext("\tscrub [-s] <pool> ...\n"));
248 	case HELP_STATUS:
249 		return (gettext("\tstatus [-vx] [-T d|u] [pool] ... [interval "
250 		    "[count]]\n"));
251 	case HELP_UPGRADE:
252 		return (gettext("\tupgrade\n"
253 		    "\tupgrade -v\n"
254 		    "\tupgrade [-V version] <-a | pool ...>\n"));
255 	case HELP_GET:
256 		return (gettext("\tget [-Hp] [-o \"all\" | field[,...]] "
257 		    "<\"all\" | property[,...]> <pool> ...\n"));
258 	case HELP_SET:
259 		return (gettext("\tset <property=value> <pool> \n"));
260 	case HELP_SPLIT:
261 		return (gettext("\tsplit [-n] [-R altroot] [-o mntopts]\n"
262 		    "\t    [-o property=value] <pool> <newpool> "
263 		    "[<device> ...]\n"));
264 	case HELP_REGUID:
265 		return (gettext("\treguid <pool>\n"));
266 	}
267 
268 	abort();
269 	/* NOTREACHED */
270 }
271 
272 
273 /*
274  * Callback routine that will print out a pool property value.
275  */
276 static int
print_prop_cb(int prop,void * cb)277 print_prop_cb(int prop, void *cb)
278 {
279 	FILE *fp = cb;
280 
281 	(void) fprintf(fp, "\t%-15s  ", zpool_prop_to_name(prop));
282 
283 	if (zpool_prop_readonly(prop))
284 		(void) fprintf(fp, "  NO   ");
285 	else
286 		(void) fprintf(fp, " YES   ");
287 
288 	if (zpool_prop_values(prop) == NULL)
289 		(void) fprintf(fp, "-\n");
290 	else
291 		(void) fprintf(fp, "%s\n", zpool_prop_values(prop));
292 
293 	return (ZPROP_CONT);
294 }
295 
296 /*
297  * Display usage message.  If we're inside a command, display only the usage for
298  * that command.  Otherwise, iterate over the entire command table and display
299  * a complete usage message.
300  */
301 void
usage(boolean_t requested)302 usage(boolean_t requested)
303 {
304 	FILE *fp = requested ? stdout : stderr;
305 
306 	if (current_command == NULL) {
307 		int i;
308 
309 		(void) fprintf(fp, gettext("usage: zpool command args ...\n"));
310 		(void) fprintf(fp,
311 		    gettext("where 'command' is one of the following:\n\n"));
312 
313 		for (i = 0; i < NCOMMAND; i++) {
314 			if (command_table[i].name == NULL)
315 				(void) fprintf(fp, "\n");
316 			else
317 				(void) fprintf(fp, "%s",
318 				    get_usage(command_table[i].usage));
319 		}
320 	} else {
321 		(void) fprintf(fp, gettext("usage:\n"));
322 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
323 	}
324 
325 	if (current_command != NULL &&
326 	    ((strcmp(current_command->name, "set") == 0) ||
327 	    (strcmp(current_command->name, "get") == 0) ||
328 	    (strcmp(current_command->name, "list") == 0))) {
329 
330 		(void) fprintf(fp,
331 		    gettext("\nthe following properties are supported:\n"));
332 
333 		(void) fprintf(fp, "\n\t%-15s  %s   %s\n\n",
334 		    "PROPERTY", "EDIT", "VALUES");
335 
336 		/* Iterate over all properties */
337 		(void) zprop_iter(print_prop_cb, fp, B_FALSE, B_TRUE,
338 		    ZFS_TYPE_POOL);
339 
340 		(void) fprintf(fp, "\t%-15s   ", "feature@...");
341 		(void) fprintf(fp, "YES   disabled | enabled | active\n");
342 
343 		(void) fprintf(fp, gettext("\nThe feature@ properties must be "
344 		    "appended with a feature name.\nSee zpool-features(5).\n"));
345 	}
346 
347 	/*
348 	 * See comments at end of main().
349 	 */
350 	if (getenv("ZFS_ABORT") != NULL) {
351 		(void) printf("dumping core by request\n");
352 		abort();
353 	}
354 
355 	exit(requested ? 0 : 2);
356 }
357 
358 void
print_vdev_tree(zpool_handle_t * zhp,const char * name,nvlist_t * nv,int indent,boolean_t print_logs)359 print_vdev_tree(zpool_handle_t *zhp, const char *name, nvlist_t *nv, int indent,
360     boolean_t print_logs)
361 {
362 	nvlist_t **child;
363 	uint_t c, children;
364 	char *vname;
365 
366 	if (name != NULL)
367 		(void) printf("\t%*s%s\n", indent, "", name);
368 
369 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
370 	    &child, &children) != 0)
371 		return;
372 
373 	for (c = 0; c < children; c++) {
374 		uint64_t is_log = B_FALSE;
375 
376 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
377 		    &is_log);
378 		if ((is_log && !print_logs) || (!is_log && print_logs))
379 			continue;
380 
381 		vname = zpool_vdev_name(g_zfs, zhp, child[c], B_FALSE);
382 		print_vdev_tree(zhp, vname, child[c], indent + 2,
383 		    B_FALSE);
384 		free(vname);
385 	}
386 }
387 
388 static boolean_t
prop_list_contains_feature(nvlist_t * proplist)389 prop_list_contains_feature(nvlist_t *proplist)
390 {
391 	nvpair_t *nvp;
392 	for (nvp = nvlist_next_nvpair(proplist, NULL); NULL != nvp;
393 	    nvp = nvlist_next_nvpair(proplist, nvp)) {
394 		if (zpool_prop_feature(nvpair_name(nvp)))
395 			return (B_TRUE);
396 	}
397 	return (B_FALSE);
398 }
399 
400 /*
401  * Add a property pair (name, string-value) into a property nvlist.
402  */
403 static int
add_prop_list(const char * propname,char * propval,nvlist_t ** props,boolean_t poolprop)404 add_prop_list(const char *propname, char *propval, nvlist_t **props,
405     boolean_t poolprop)
406 {
407 	zpool_prop_t prop = ZPROP_INVAL;
408 	zfs_prop_t fprop;
409 	nvlist_t *proplist;
410 	const char *normnm;
411 	char *strval;
412 
413 	if (*props == NULL &&
414 	    nvlist_alloc(props, NV_UNIQUE_NAME, 0) != 0) {
415 		(void) fprintf(stderr,
416 		    gettext("internal error: out of memory\n"));
417 		return (1);
418 	}
419 
420 	proplist = *props;
421 
422 	if (poolprop) {
423 		const char *vname = zpool_prop_to_name(ZPOOL_PROP_VERSION);
424 
425 		if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL &&
426 		    !zpool_prop_feature(propname)) {
427 			(void) fprintf(stderr, gettext("property '%s' is "
428 			    "not a valid pool property\n"), propname);
429 			return (2);
430 		}
431 
432 		/*
433 		 * feature@ properties and version should not be specified
434 		 * at the same time.
435 		 */
436 		if ((prop == ZPROP_INVAL && zpool_prop_feature(propname) &&
437 		    nvlist_exists(proplist, vname)) ||
438 		    (prop == ZPOOL_PROP_VERSION &&
439 		    prop_list_contains_feature(proplist))) {
440 			(void) fprintf(stderr, gettext("'feature@' and "
441 			    "'version' properties cannot be specified "
442 			    "together\n"));
443 			return (2);
444 		}
445 
446 
447 		if (zpool_prop_feature(propname))
448 			normnm = propname;
449 		else
450 			normnm = zpool_prop_to_name(prop);
451 	} else {
452 		if ((fprop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
453 			normnm = zfs_prop_to_name(fprop);
454 		} else {
455 			normnm = propname;
456 		}
457 	}
458 
459 	if (nvlist_lookup_string(proplist, normnm, &strval) == 0 &&
460 	    prop != ZPOOL_PROP_CACHEFILE) {
461 		(void) fprintf(stderr, gettext("property '%s' "
462 		    "specified multiple times\n"), propname);
463 		return (2);
464 	}
465 
466 	if (nvlist_add_string(proplist, normnm, propval) != 0) {
467 		(void) fprintf(stderr, gettext("internal "
468 		    "error: out of memory\n"));
469 		return (1);
470 	}
471 
472 	return (0);
473 }
474 
475 /*
476  * zpool add [-fn] <pool> <vdev> ...
477  *
478  *	-f	Force addition of devices, even if they appear in use
479  *	-n	Do not add the devices, but display the resulting layout if
480  *		they were to be added.
481  *
482  * Adds the given vdevs to 'pool'.  As with create, the bulk of this work is
483  * handled by get_vdev_spec(), which constructs the nvlist needed to pass to
484  * libzfs.
485  */
486 int
zpool_do_add(int argc,char ** argv)487 zpool_do_add(int argc, char **argv)
488 {
489 	boolean_t force = B_FALSE;
490 	boolean_t dryrun = B_FALSE;
491 	int c;
492 	nvlist_t *nvroot;
493 	char *poolname;
494 	int ret;
495 	zpool_handle_t *zhp;
496 	nvlist_t *config;
497 
498 	/* check options */
499 	while ((c = getopt(argc, argv, "fn")) != -1) {
500 		switch (c) {
501 		case 'f':
502 			force = B_TRUE;
503 			break;
504 		case 'n':
505 			dryrun = B_TRUE;
506 			break;
507 		case '?':
508 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
509 			    optopt);
510 			usage(B_FALSE);
511 		}
512 	}
513 
514 	argc -= optind;
515 	argv += optind;
516 
517 	/* get pool name and check number of arguments */
518 	if (argc < 1) {
519 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
520 		usage(B_FALSE);
521 	}
522 	if (argc < 2) {
523 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
524 		usage(B_FALSE);
525 	}
526 
527 	poolname = argv[0];
528 
529 	argc--;
530 	argv++;
531 
532 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
533 		return (1);
534 
535 	if ((config = zpool_get_config(zhp, NULL)) == NULL) {
536 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
537 		    poolname);
538 		zpool_close(zhp);
539 		return (1);
540 	}
541 
542 	/* pass off to get_vdev_spec for processing */
543 	nvroot = make_root_vdev(zhp, force, !force, B_FALSE, dryrun,
544 	    argc, argv);
545 	if (nvroot == NULL) {
546 		zpool_close(zhp);
547 		return (1);
548 	}
549 
550 	if (dryrun) {
551 		nvlist_t *poolnvroot;
552 
553 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
554 		    &poolnvroot) == 0);
555 
556 		(void) printf(gettext("would update '%s' to the following "
557 		    "configuration:\n"), zpool_get_name(zhp));
558 
559 		/* print original main pool and new tree */
560 		print_vdev_tree(zhp, poolname, poolnvroot, 0, B_FALSE);
561 		print_vdev_tree(zhp, NULL, nvroot, 0, B_FALSE);
562 
563 		/* Do the same for the logs */
564 		if (num_logs(poolnvroot) > 0) {
565 			print_vdev_tree(zhp, "logs", poolnvroot, 0, B_TRUE);
566 			print_vdev_tree(zhp, NULL, nvroot, 0, B_TRUE);
567 		} else if (num_logs(nvroot) > 0) {
568 			print_vdev_tree(zhp, "logs", nvroot, 0, B_TRUE);
569 		}
570 
571 		ret = 0;
572 	} else {
573 		ret = (zpool_add(zhp, nvroot) != 0);
574 	}
575 
576 	nvlist_free(nvroot);
577 	zpool_close(zhp);
578 
579 	return (ret);
580 }
581 
582 /*
583  * zpool remove  <pool> <vdev> ...
584  *
585  * Removes the given vdev from the pool.  Currently, this supports removing
586  * spares, cache, and log devices from the pool.
587  */
588 int
zpool_do_remove(int argc,char ** argv)589 zpool_do_remove(int argc, char **argv)
590 {
591 	char *poolname;
592 	int i, ret = 0;
593 	zpool_handle_t *zhp;
594 
595 	argc--;
596 	argv++;
597 
598 	/* get pool name and check number of arguments */
599 	if (argc < 1) {
600 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
601 		usage(B_FALSE);
602 	}
603 	if (argc < 2) {
604 		(void) fprintf(stderr, gettext("missing device\n"));
605 		usage(B_FALSE);
606 	}
607 
608 	poolname = argv[0];
609 
610 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
611 		return (1);
612 
613 	for (i = 1; i < argc; i++) {
614 		if (zpool_vdev_remove(zhp, argv[i]) != 0)
615 			ret = 1;
616 	}
617 
618 	return (ret);
619 }
620 
621 /*
622  * zpool create [-fnd] [-o property=value] ...
623  *		[-O file-system-property=value] ...
624  *		[-R root] [-m mountpoint] <pool> <dev> ...
625  *
626  *	-f	Force creation, even if devices appear in use
627  *	-n	Do not create the pool, but display the resulting layout if it
628  *		were to be created.
629  *      -R	Create a pool under an alternate root
630  *      -m	Set default mountpoint for the root dataset.  By default it's
631  *		'/<pool>'
632  *	-o	Set property=value.
633  *	-d	Don't automatically enable all supported pool features
634  *		(individual features can be enabled with -o).
635  *	-O	Set fsproperty=value in the pool's root file system
636  *
637  * Creates the named pool according to the given vdev specification.  The
638  * bulk of the vdev processing is done in get_vdev_spec() in zpool_vdev.c.  Once
639  * we get the nvlist back from get_vdev_spec(), we either print out the contents
640  * (if '-n' was specified), or pass it to libzfs to do the creation.
641  */
642 int
zpool_do_create(int argc,char ** argv)643 zpool_do_create(int argc, char **argv)
644 {
645 	boolean_t force = B_FALSE;
646 	boolean_t dryrun = B_FALSE;
647 	boolean_t enable_all_pool_feat = B_TRUE;
648 	int c;
649 	nvlist_t *nvroot = NULL;
650 	char *poolname;
651 	int ret = 1;
652 	char *altroot = NULL;
653 	char *mountpoint = NULL;
654 	nvlist_t *fsprops = NULL;
655 	nvlist_t *props = NULL;
656 	char *propval;
657 
658 	/* check options */
659 	while ((c = getopt(argc, argv, ":fndR:m:o:O:")) != -1) {
660 		switch (c) {
661 		case 'f':
662 			force = B_TRUE;
663 			break;
664 		case 'n':
665 			dryrun = B_TRUE;
666 			break;
667 		case 'd':
668 			enable_all_pool_feat = B_FALSE;
669 			break;
670 		case 'R':
671 			altroot = optarg;
672 			if (add_prop_list(zpool_prop_to_name(
673 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
674 				goto errout;
675 			if (nvlist_lookup_string(props,
676 			    zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
677 			    &propval) == 0)
678 				break;
679 			if (add_prop_list(zpool_prop_to_name(
680 			    ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
681 				goto errout;
682 			break;
683 		case 'm':
684 			/* Equivalent to -O mountpoint=optarg */
685 			mountpoint = optarg;
686 			break;
687 		case 'o':
688 			if ((propval = strchr(optarg, '=')) == NULL) {
689 				(void) fprintf(stderr, gettext("missing "
690 				    "'=' for -o option\n"));
691 				goto errout;
692 			}
693 			*propval = '\0';
694 			propval++;
695 
696 			if (add_prop_list(optarg, propval, &props, B_TRUE))
697 				goto errout;
698 
699 			/*
700 			 * If the user is creating a pool that doesn't support
701 			 * feature flags, don't enable any features.
702 			 */
703 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_VERSION) {
704 				char *end;
705 				u_longlong_t ver;
706 
707 				ver = strtoull(propval, &end, 10);
708 				if (*end == '\0' &&
709 				    ver < SPA_VERSION_FEATURES) {
710 					enable_all_pool_feat = B_FALSE;
711 				}
712 			}
713 			if (zpool_name_to_prop(optarg) == ZPOOL_PROP_ALTROOT)
714 				altroot = propval;
715 			break;
716 		case 'O':
717 			if ((propval = strchr(optarg, '=')) == NULL) {
718 				(void) fprintf(stderr, gettext("missing "
719 				    "'=' for -O option\n"));
720 				goto errout;
721 			}
722 			*propval = '\0';
723 			propval++;
724 
725 			/*
726 			 * Mountpoints are checked and then added later.
727 			 * Uniquely among properties, they can be specified
728 			 * more than once, to avoid conflict with -m.
729 			 */
730 			if (0 == strcmp(optarg,
731 			    zfs_prop_to_name(ZFS_PROP_MOUNTPOINT))) {
732 				mountpoint = propval;
733 			} else if (add_prop_list(optarg, propval, &fsprops,
734 			    B_FALSE)) {
735 				goto errout;
736 			}
737 			break;
738 		case ':':
739 			(void) fprintf(stderr, gettext("missing argument for "
740 			    "'%c' option\n"), optopt);
741 			goto badusage;
742 		case '?':
743 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
744 			    optopt);
745 			goto badusage;
746 		}
747 	}
748 
749 	argc -= optind;
750 	argv += optind;
751 
752 	/* get pool name and check number of arguments */
753 	if (argc < 1) {
754 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
755 		goto badusage;
756 	}
757 	if (argc < 2) {
758 		(void) fprintf(stderr, gettext("missing vdev specification\n"));
759 		goto badusage;
760 	}
761 
762 	poolname = argv[0];
763 
764 	/*
765 	 * As a special case, check for use of '/' in the name, and direct the
766 	 * user to use 'zfs create' instead.
767 	 */
768 	if (strchr(poolname, '/') != NULL) {
769 		(void) fprintf(stderr, gettext("cannot create '%s': invalid "
770 		    "character '/' in pool name\n"), poolname);
771 		(void) fprintf(stderr, gettext("use 'zfs create' to "
772 		    "create a dataset\n"));
773 		goto errout;
774 	}
775 
776 	/* pass off to get_vdev_spec for bulk processing */
777 	nvroot = make_root_vdev(NULL, force, !force, B_FALSE, dryrun,
778 	    argc - 1, argv + 1);
779 	if (nvroot == NULL)
780 		goto errout;
781 
782 	/* make_root_vdev() allows 0 toplevel children if there are spares */
783 	if (!zfs_allocatable_devs(nvroot)) {
784 		(void) fprintf(stderr, gettext("invalid vdev "
785 		    "specification: at least one toplevel vdev must be "
786 		    "specified\n"));
787 		goto errout;
788 	}
789 
790 	if (altroot != NULL && altroot[0] != '/') {
791 		(void) fprintf(stderr, gettext("invalid alternate root '%s': "
792 		    "must be an absolute path\n"), altroot);
793 		goto errout;
794 	}
795 
796 	/*
797 	 * Check the validity of the mountpoint and direct the user to use the
798 	 * '-m' mountpoint option if it looks like its in use.
799 	 */
800 	if (mountpoint == NULL ||
801 	    (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) != 0 &&
802 	    strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) != 0)) {
803 		char buf[MAXPATHLEN];
804 		DIR *dirp;
805 
806 		if (mountpoint && mountpoint[0] != '/') {
807 			(void) fprintf(stderr, gettext("invalid mountpoint "
808 			    "'%s': must be an absolute path, 'legacy', or "
809 			    "'none'\n"), mountpoint);
810 			goto errout;
811 		}
812 
813 		if (mountpoint == NULL) {
814 			if (altroot != NULL)
815 				(void) snprintf(buf, sizeof (buf), "%s/%s",
816 				    altroot, poolname);
817 			else
818 				(void) snprintf(buf, sizeof (buf), "/%s",
819 				    poolname);
820 		} else {
821 			if (altroot != NULL)
822 				(void) snprintf(buf, sizeof (buf), "%s%s",
823 				    altroot, mountpoint);
824 			else
825 				(void) snprintf(buf, sizeof (buf), "%s",
826 				    mountpoint);
827 		}
828 
829 		if ((dirp = opendir(buf)) == NULL && errno != ENOENT) {
830 			(void) fprintf(stderr, gettext("mountpoint '%s' : "
831 			    "%s\n"), buf, strerror(errno));
832 			(void) fprintf(stderr, gettext("use '-m' "
833 			    "option to provide a different default\n"));
834 			goto errout;
835 		} else if (dirp) {
836 			int count = 0;
837 
838 			while (count < 3 && readdir(dirp) != NULL)
839 				count++;
840 			(void) closedir(dirp);
841 
842 			if (count > 2) {
843 				(void) fprintf(stderr, gettext("mountpoint "
844 				    "'%s' exists and is not empty\n"), buf);
845 				(void) fprintf(stderr, gettext("use '-m' "
846 				    "option to provide a "
847 				    "different default\n"));
848 				goto errout;
849 			}
850 		}
851 	}
852 
853 	/*
854 	 * Now that the mountpoint's validity has been checked, ensure that
855 	 * the property is set appropriately prior to creating the pool.
856 	 */
857 	if (mountpoint != NULL) {
858 		ret = add_prop_list(zfs_prop_to_name(ZFS_PROP_MOUNTPOINT),
859 		    mountpoint, &fsprops, B_FALSE);
860 		if (ret != 0)
861 			goto errout;
862 	}
863 
864 	ret = 1;
865 	if (dryrun) {
866 		/*
867 		 * For a dry run invocation, print out a basic message and run
868 		 * through all the vdevs in the list and print out in an
869 		 * appropriate hierarchy.
870 		 */
871 		(void) printf(gettext("would create '%s' with the "
872 		    "following layout:\n\n"), poolname);
873 
874 		print_vdev_tree(NULL, poolname, nvroot, 0, B_FALSE);
875 		if (num_logs(nvroot) > 0)
876 			print_vdev_tree(NULL, "logs", nvroot, 0, B_TRUE);
877 
878 		ret = 0;
879 	} else {
880 		/*
881 		 * Hand off to libzfs.
882 		 */
883 		if (enable_all_pool_feat) {
884 			spa_feature_t i;
885 			for (i = 0; i < SPA_FEATURES; i++) {
886 				char propname[MAXPATHLEN];
887 				zfeature_info_t *feat = &spa_feature_table[i];
888 
889 				(void) snprintf(propname, sizeof (propname),
890 				    "feature@%s", feat->fi_uname);
891 
892 				/*
893 				 * Skip feature if user specified it manually
894 				 * on the command line.
895 				 */
896 				if (nvlist_exists(props, propname))
897 					continue;
898 
899 				ret = add_prop_list(propname,
900 				    ZFS_FEATURE_ENABLED, &props, B_TRUE);
901 				if (ret != 0)
902 					goto errout;
903 			}
904 		}
905 
906 		ret = 1;
907 		if (zpool_create(g_zfs, poolname,
908 		    nvroot, props, fsprops) == 0) {
909 			zfs_handle_t *pool = zfs_open(g_zfs, poolname,
910 			    ZFS_TYPE_FILESYSTEM);
911 			if (pool != NULL) {
912 				if (zfs_mount(pool, NULL, 0) == 0)
913 					ret = zfs_shareall(pool);
914 				zfs_close(pool);
915 			}
916 		} else if (libzfs_errno(g_zfs) == EZFS_INVALIDNAME) {
917 			(void) fprintf(stderr, gettext("pool name may have "
918 			    "been omitted\n"));
919 		}
920 	}
921 
922 errout:
923 	nvlist_free(nvroot);
924 	nvlist_free(fsprops);
925 	nvlist_free(props);
926 	return (ret);
927 badusage:
928 	nvlist_free(fsprops);
929 	nvlist_free(props);
930 	usage(B_FALSE);
931 	return (2);
932 }
933 
934 /*
935  * zpool destroy <pool>
936  *
937  * 	-f	Forcefully unmount any datasets
938  *
939  * Destroy the given pool.  Automatically unmounts any datasets in the pool.
940  */
941 int
zpool_do_destroy(int argc,char ** argv)942 zpool_do_destroy(int argc, char **argv)
943 {
944 	boolean_t force = B_FALSE;
945 	int c;
946 	char *pool;
947 	zpool_handle_t *zhp;
948 	int ret;
949 
950 	/* check options */
951 	while ((c = getopt(argc, argv, "f")) != -1) {
952 		switch (c) {
953 		case 'f':
954 			force = B_TRUE;
955 			break;
956 		case '?':
957 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
958 			    optopt);
959 			usage(B_FALSE);
960 		}
961 	}
962 
963 	argc -= optind;
964 	argv += optind;
965 
966 	/* check arguments */
967 	if (argc < 1) {
968 		(void) fprintf(stderr, gettext("missing pool argument\n"));
969 		usage(B_FALSE);
970 	}
971 	if (argc > 1) {
972 		(void) fprintf(stderr, gettext("too many arguments\n"));
973 		usage(B_FALSE);
974 	}
975 
976 	pool = argv[0];
977 
978 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
979 		/*
980 		 * As a special case, check for use of '/' in the name, and
981 		 * direct the user to use 'zfs destroy' instead.
982 		 */
983 		if (strchr(pool, '/') != NULL)
984 			(void) fprintf(stderr, gettext("use 'zfs destroy' to "
985 			    "destroy a dataset\n"));
986 		return (1);
987 	}
988 
989 	if (zpool_disable_datasets(zhp, force) != 0) {
990 		(void) fprintf(stderr, gettext("could not destroy '%s': "
991 		    "could not unmount datasets\n"), zpool_get_name(zhp));
992 		return (1);
993 	}
994 
995 	/* The history must be logged as part of the export */
996 	log_history = B_FALSE;
997 
998 	ret = (zpool_destroy(zhp, history_str) != 0);
999 
1000 	zpool_close(zhp);
1001 
1002 	return (ret);
1003 }
1004 
1005 /*
1006  * zpool export [-f] <pool> ...
1007  *
1008  *	-f	Forcefully unmount datasets
1009  *
1010  * Export the given pools.  By default, the command will attempt to cleanly
1011  * unmount any active datasets within the pool.  If the '-f' flag is specified,
1012  * then the datasets will be forcefully unmounted.
1013  */
1014 int
zpool_do_export(int argc,char ** argv)1015 zpool_do_export(int argc, char **argv)
1016 {
1017 	boolean_t force = B_FALSE;
1018 	boolean_t hardforce = B_FALSE;
1019 	int c;
1020 	zpool_handle_t *zhp;
1021 	int ret;
1022 	int i;
1023 
1024 	/* check options */
1025 	while ((c = getopt(argc, argv, "fF")) != -1) {
1026 		switch (c) {
1027 		case 'f':
1028 			force = B_TRUE;
1029 			break;
1030 		case 'F':
1031 			hardforce = B_TRUE;
1032 			break;
1033 		case '?':
1034 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1035 			    optopt);
1036 			usage(B_FALSE);
1037 		}
1038 	}
1039 
1040 	argc -= optind;
1041 	argv += optind;
1042 
1043 	/* check arguments */
1044 	if (argc < 1) {
1045 		(void) fprintf(stderr, gettext("missing pool argument\n"));
1046 		usage(B_FALSE);
1047 	}
1048 
1049 	ret = 0;
1050 	for (i = 0; i < argc; i++) {
1051 		if ((zhp = zpool_open_canfail(g_zfs, argv[i])) == NULL) {
1052 			ret = 1;
1053 			continue;
1054 		}
1055 
1056 		if (zpool_disable_datasets(zhp, force) != 0) {
1057 			ret = 1;
1058 			zpool_close(zhp);
1059 			continue;
1060 		}
1061 
1062 		/* The history must be logged as part of the export */
1063 		log_history = B_FALSE;
1064 
1065 		if (hardforce) {
1066 			if (zpool_export_force(zhp, history_str) != 0)
1067 				ret = 1;
1068 		} else if (zpool_export(zhp, force, history_str) != 0) {
1069 			ret = 1;
1070 		}
1071 
1072 		zpool_close(zhp);
1073 	}
1074 
1075 	return (ret);
1076 }
1077 
1078 /*
1079  * Given a vdev configuration, determine the maximum width needed for the device
1080  * name column.
1081  */
1082 static int
max_width(zpool_handle_t * zhp,nvlist_t * nv,int depth,int max)1083 max_width(zpool_handle_t *zhp, nvlist_t *nv, int depth, int max)
1084 {
1085 	char *name = zpool_vdev_name(g_zfs, zhp, nv, B_TRUE);
1086 	nvlist_t **child;
1087 	uint_t c, children;
1088 	int ret;
1089 
1090 	if (strlen(name) + depth > max)
1091 		max = strlen(name) + depth;
1092 
1093 	free(name);
1094 
1095 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1096 	    &child, &children) == 0) {
1097 		for (c = 0; c < children; c++)
1098 			if ((ret = max_width(zhp, child[c], depth + 2,
1099 			    max)) > max)
1100 				max = ret;
1101 	}
1102 
1103 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1104 	    &child, &children) == 0) {
1105 		for (c = 0; c < children; c++)
1106 			if ((ret = max_width(zhp, child[c], depth + 2,
1107 			    max)) > max)
1108 				max = ret;
1109 	}
1110 
1111 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1112 	    &child, &children) == 0) {
1113 		for (c = 0; c < children; c++)
1114 			if ((ret = max_width(zhp, child[c], depth + 2,
1115 			    max)) > max)
1116 				max = ret;
1117 	}
1118 
1119 
1120 	return (max);
1121 }
1122 
1123 typedef struct spare_cbdata {
1124 	uint64_t	cb_guid;
1125 	zpool_handle_t	*cb_zhp;
1126 } spare_cbdata_t;
1127 
1128 static boolean_t
find_vdev(nvlist_t * nv,uint64_t search)1129 find_vdev(nvlist_t *nv, uint64_t search)
1130 {
1131 	uint64_t guid;
1132 	nvlist_t **child;
1133 	uint_t c, children;
1134 
1135 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0 &&
1136 	    search == guid)
1137 		return (B_TRUE);
1138 
1139 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1140 	    &child, &children) == 0) {
1141 		for (c = 0; c < children; c++)
1142 			if (find_vdev(child[c], search))
1143 				return (B_TRUE);
1144 	}
1145 
1146 	return (B_FALSE);
1147 }
1148 
1149 static int
find_spare(zpool_handle_t * zhp,void * data)1150 find_spare(zpool_handle_t *zhp, void *data)
1151 {
1152 	spare_cbdata_t *cbp = data;
1153 	nvlist_t *config, *nvroot;
1154 
1155 	config = zpool_get_config(zhp, NULL);
1156 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1157 	    &nvroot) == 0);
1158 
1159 	if (find_vdev(nvroot, cbp->cb_guid)) {
1160 		cbp->cb_zhp = zhp;
1161 		return (1);
1162 	}
1163 
1164 	zpool_close(zhp);
1165 	return (0);
1166 }
1167 
1168 /*
1169  * Print out configuration state as requested by status_callback.
1170  */
1171 void
print_status_config(zpool_handle_t * zhp,const char * name,nvlist_t * nv,int namewidth,int depth,boolean_t isspare)1172 print_status_config(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
1173     int namewidth, int depth, boolean_t isspare)
1174 {
1175 	nvlist_t **child;
1176 	uint_t c, children;
1177 	pool_scan_stat_t *ps = NULL;
1178 	vdev_stat_t *vs;
1179 	char rbuf[6], wbuf[6], cbuf[6];
1180 	char *vname;
1181 	uint64_t notpresent;
1182 	spare_cbdata_t cb;
1183 	char *state;
1184 
1185 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1186 	    &child, &children) != 0)
1187 		children = 0;
1188 
1189 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1190 	    (uint64_t **)&vs, &c) == 0);
1191 
1192 	state = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1193 	if (isspare) {
1194 		/*
1195 		 * For hot spares, we use the terms 'INUSE' and 'AVAILABLE' for
1196 		 * online drives.
1197 		 */
1198 		if (vs->vs_aux == VDEV_AUX_SPARED)
1199 			state = "INUSE";
1200 		else if (vs->vs_state == VDEV_STATE_HEALTHY)
1201 			state = "AVAIL";
1202 	}
1203 
1204 	(void) printf("\t%*s%-*s  %-8s", depth, "", namewidth - depth,
1205 	    name, state);
1206 
1207 	if (!isspare) {
1208 		zfs_nicenum(vs->vs_read_errors, rbuf, sizeof (rbuf));
1209 		zfs_nicenum(vs->vs_write_errors, wbuf, sizeof (wbuf));
1210 		zfs_nicenum(vs->vs_checksum_errors, cbuf, sizeof (cbuf));
1211 		(void) printf(" %5s %5s %5s", rbuf, wbuf, cbuf);
1212 	}
1213 
1214 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
1215 	    &notpresent) == 0) {
1216 		char *path;
1217 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0);
1218 		(void) printf("  was %s", path);
1219 	} else if (vs->vs_aux != 0) {
1220 		(void) printf("  ");
1221 
1222 		switch (vs->vs_aux) {
1223 		case VDEV_AUX_OPEN_FAILED:
1224 			(void) printf(gettext("cannot open"));
1225 			break;
1226 
1227 		case VDEV_AUX_BAD_GUID_SUM:
1228 			(void) printf(gettext("missing device"));
1229 			break;
1230 
1231 		case VDEV_AUX_NO_REPLICAS:
1232 			(void) printf(gettext("insufficient replicas"));
1233 			break;
1234 
1235 		case VDEV_AUX_VERSION_NEWER:
1236 			(void) printf(gettext("newer version"));
1237 			break;
1238 
1239 		case VDEV_AUX_UNSUP_FEAT:
1240 			(void) printf(gettext("unsupported feature(s)"));
1241 			break;
1242 
1243 		case VDEV_AUX_SPARED:
1244 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
1245 			    &cb.cb_guid) == 0);
1246 			if (zpool_iter(g_zfs, find_spare, &cb) == 1) {
1247 				if (strcmp(zpool_get_name(cb.cb_zhp),
1248 				    zpool_get_name(zhp)) == 0)
1249 					(void) printf(gettext("currently in "
1250 					    "use"));
1251 				else
1252 					(void) printf(gettext("in use by "
1253 					    "pool '%s'"),
1254 					    zpool_get_name(cb.cb_zhp));
1255 				zpool_close(cb.cb_zhp);
1256 			} else {
1257 				(void) printf(gettext("currently in use"));
1258 			}
1259 			break;
1260 
1261 		case VDEV_AUX_ERR_EXCEEDED:
1262 			(void) printf(gettext("too many errors"));
1263 			break;
1264 
1265 		case VDEV_AUX_IO_FAILURE:
1266 			(void) printf(gettext("experienced I/O failures"));
1267 			break;
1268 
1269 		case VDEV_AUX_BAD_LOG:
1270 			(void) printf(gettext("bad intent log"));
1271 			break;
1272 
1273 		case VDEV_AUX_EXTERNAL:
1274 			(void) printf(gettext("external device fault"));
1275 			break;
1276 
1277 		case VDEV_AUX_SPLIT_POOL:
1278 			(void) printf(gettext("split into new pool"));
1279 			break;
1280 
1281 		default:
1282 			(void) printf(gettext("corrupted data"));
1283 			break;
1284 		}
1285 	}
1286 
1287 	(void) nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_SCAN_STATS,
1288 	    (uint64_t **)&ps, &c);
1289 
1290 	if (ps && ps->pss_state == DSS_SCANNING &&
1291 	    vs->vs_scan_processed != 0 && children == 0) {
1292 		(void) printf(gettext("  (%s)"),
1293 		    (ps->pss_func == POOL_SCAN_RESILVER) ?
1294 		    "resilvering" : "repairing");
1295 	}
1296 
1297 	(void) printf("\n");
1298 
1299 	for (c = 0; c < children; c++) {
1300 		uint64_t islog = B_FALSE, ishole = B_FALSE;
1301 
1302 		/* Don't print logs or holes here */
1303 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1304 		    &islog);
1305 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
1306 		    &ishole);
1307 		if (islog || ishole)
1308 			continue;
1309 		vname = zpool_vdev_name(g_zfs, zhp, child[c], B_TRUE);
1310 		print_status_config(zhp, vname, child[c],
1311 		    namewidth, depth + 2, isspare);
1312 		free(vname);
1313 	}
1314 }
1315 
1316 
1317 /*
1318  * Print the configuration of an exported pool.  Iterate over all vdevs in the
1319  * pool, printing out the name and status for each one.
1320  */
1321 void
print_import_config(const char * name,nvlist_t * nv,int namewidth,int depth)1322 print_import_config(const char *name, nvlist_t *nv, int namewidth, int depth)
1323 {
1324 	nvlist_t **child;
1325 	uint_t c, children;
1326 	vdev_stat_t *vs;
1327 	char *type, *vname;
1328 
1329 	verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) == 0);
1330 	if (strcmp(type, VDEV_TYPE_MISSING) == 0 ||
1331 	    strcmp(type, VDEV_TYPE_HOLE) == 0)
1332 		return;
1333 
1334 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
1335 	    (uint64_t **)&vs, &c) == 0);
1336 
1337 	(void) printf("\t%*s%-*s", depth, "", namewidth - depth, name);
1338 	(void) printf("  %s", zpool_state_to_name(vs->vs_state, vs->vs_aux));
1339 
1340 	if (vs->vs_aux != 0) {
1341 		(void) printf("  ");
1342 
1343 		switch (vs->vs_aux) {
1344 		case VDEV_AUX_OPEN_FAILED:
1345 			(void) printf(gettext("cannot open"));
1346 			break;
1347 
1348 		case VDEV_AUX_BAD_GUID_SUM:
1349 			(void) printf(gettext("missing device"));
1350 			break;
1351 
1352 		case VDEV_AUX_NO_REPLICAS:
1353 			(void) printf(gettext("insufficient replicas"));
1354 			break;
1355 
1356 		case VDEV_AUX_VERSION_NEWER:
1357 			(void) printf(gettext("newer version"));
1358 			break;
1359 
1360 		case VDEV_AUX_UNSUP_FEAT:
1361 			(void) printf(gettext("unsupported feature(s)"));
1362 			break;
1363 
1364 		case VDEV_AUX_ERR_EXCEEDED:
1365 			(void) printf(gettext("too many errors"));
1366 			break;
1367 
1368 		default:
1369 			(void) printf(gettext("corrupted data"));
1370 			break;
1371 		}
1372 	}
1373 	(void) printf("\n");
1374 
1375 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1376 	    &child, &children) != 0)
1377 		return;
1378 
1379 	for (c = 0; c < children; c++) {
1380 		uint64_t is_log = B_FALSE;
1381 
1382 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1383 		    &is_log);
1384 		if (is_log)
1385 			continue;
1386 
1387 		vname = zpool_vdev_name(g_zfs, NULL, child[c], B_TRUE);
1388 		print_import_config(vname, child[c], namewidth, depth + 2);
1389 		free(vname);
1390 	}
1391 
1392 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
1393 	    &child, &children) == 0) {
1394 		(void) printf(gettext("\tcache\n"));
1395 		for (c = 0; c < children; c++) {
1396 			vname = zpool_vdev_name(g_zfs, NULL, child[c], B_FALSE);
1397 			(void) printf("\t  %s\n", vname);
1398 			free(vname);
1399 		}
1400 	}
1401 
1402 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
1403 	    &child, &children) == 0) {
1404 		(void) printf(gettext("\tspares\n"));
1405 		for (c = 0; c < children; c++) {
1406 			vname = zpool_vdev_name(g_zfs, NULL, child[c], B_FALSE);
1407 			(void) printf("\t  %s\n", vname);
1408 			free(vname);
1409 		}
1410 	}
1411 }
1412 
1413 /*
1414  * Print log vdevs.
1415  * Logs are recorded as top level vdevs in the main pool child array
1416  * but with "is_log" set to 1. We use either print_status_config() or
1417  * print_import_config() to print the top level logs then any log
1418  * children (eg mirrored slogs) are printed recursively - which
1419  * works because only the top level vdev is marked "is_log"
1420  */
1421 static void
print_logs(zpool_handle_t * zhp,nvlist_t * nv,int namewidth,boolean_t verbose)1422 print_logs(zpool_handle_t *zhp, nvlist_t *nv, int namewidth, boolean_t verbose)
1423 {
1424 	uint_t c, children;
1425 	nvlist_t **child;
1426 
1427 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child,
1428 	    &children) != 0)
1429 		return;
1430 
1431 	(void) printf(gettext("\tlogs\n"));
1432 
1433 	for (c = 0; c < children; c++) {
1434 		uint64_t is_log = B_FALSE;
1435 		char *name;
1436 
1437 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1438 		    &is_log);
1439 		if (!is_log)
1440 			continue;
1441 		name = zpool_vdev_name(g_zfs, zhp, child[c], B_TRUE);
1442 		if (verbose)
1443 			print_status_config(zhp, name, child[c], namewidth,
1444 			    2, B_FALSE);
1445 		else
1446 			print_import_config(name, child[c], namewidth, 2);
1447 		free(name);
1448 	}
1449 }
1450 
1451 /*
1452  * Display the status for the given pool.
1453  */
1454 static void
show_import(nvlist_t * config)1455 show_import(nvlist_t *config)
1456 {
1457 	uint64_t pool_state;
1458 	vdev_stat_t *vs;
1459 	char *name;
1460 	uint64_t guid;
1461 	char *msgid;
1462 	nvlist_t *nvroot;
1463 	int reason;
1464 	const char *health;
1465 	uint_t vsc;
1466 	int namewidth;
1467 	char *comment;
1468 
1469 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1470 	    &name) == 0);
1471 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1472 	    &guid) == 0);
1473 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
1474 	    &pool_state) == 0);
1475 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1476 	    &nvroot) == 0);
1477 
1478 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
1479 	    (uint64_t **)&vs, &vsc) == 0);
1480 	health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
1481 
1482 	reason = zpool_import_status(config, &msgid);
1483 
1484 	(void) printf(gettext("   pool: %s\n"), name);
1485 	(void) printf(gettext("     id: %llu\n"), (u_longlong_t)guid);
1486 	(void) printf(gettext("  state: %s"), health);
1487 	if (pool_state == POOL_STATE_DESTROYED)
1488 		(void) printf(gettext(" (DESTROYED)"));
1489 	(void) printf("\n");
1490 
1491 	switch (reason) {
1492 	case ZPOOL_STATUS_MISSING_DEV_R:
1493 	case ZPOOL_STATUS_MISSING_DEV_NR:
1494 	case ZPOOL_STATUS_BAD_GUID_SUM:
1495 		(void) printf(gettext(" status: One or more devices are "
1496 		    "missing from the system.\n"));
1497 		break;
1498 
1499 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
1500 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
1501 		(void) printf(gettext(" status: One or more devices contains "
1502 		    "corrupted data.\n"));
1503 		break;
1504 
1505 	case ZPOOL_STATUS_CORRUPT_DATA:
1506 		(void) printf(
1507 		    gettext(" status: The pool data is corrupted.\n"));
1508 		break;
1509 
1510 	case ZPOOL_STATUS_OFFLINE_DEV:
1511 		(void) printf(gettext(" status: One or more devices "
1512 		    "are offlined.\n"));
1513 		break;
1514 
1515 	case ZPOOL_STATUS_CORRUPT_POOL:
1516 		(void) printf(gettext(" status: The pool metadata is "
1517 		    "corrupted.\n"));
1518 		break;
1519 
1520 	case ZPOOL_STATUS_VERSION_OLDER:
1521 		(void) printf(gettext(" status: The pool is formatted using a "
1522 		    "legacy on-disk version.\n"));
1523 		break;
1524 
1525 	case ZPOOL_STATUS_VERSION_NEWER:
1526 		(void) printf(gettext(" status: The pool is formatted using an "
1527 		    "incompatible version.\n"));
1528 		break;
1529 
1530 	case ZPOOL_STATUS_FEAT_DISABLED:
1531 		(void) printf(gettext(" status: Some supported features are "
1532 		    "not enabled on the pool.\n"));
1533 		break;
1534 
1535 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
1536 		(void) printf(gettext("status: The pool uses the following "
1537 		    "feature(s) not supported on this sytem:\n"));
1538 		zpool_print_unsup_feat(config);
1539 		break;
1540 
1541 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
1542 		(void) printf(gettext("status: The pool can only be accessed "
1543 		    "in read-only mode on this system. It\n\tcannot be "
1544 		    "accessed in read-write mode because it uses the "
1545 		    "following\n\tfeature(s) not supported on this system:\n"));
1546 		zpool_print_unsup_feat(config);
1547 		break;
1548 
1549 	case ZPOOL_STATUS_HOSTID_MISMATCH:
1550 		(void) printf(gettext(" status: The pool was last accessed by "
1551 		    "another system.\n"));
1552 		break;
1553 
1554 	case ZPOOL_STATUS_FAULTED_DEV_R:
1555 	case ZPOOL_STATUS_FAULTED_DEV_NR:
1556 		(void) printf(gettext(" status: One or more devices are "
1557 		    "faulted.\n"));
1558 		break;
1559 
1560 	case ZPOOL_STATUS_BAD_LOG:
1561 		(void) printf(gettext(" status: An intent log record cannot be "
1562 		    "read.\n"));
1563 		break;
1564 
1565 	case ZPOOL_STATUS_RESILVERING:
1566 		(void) printf(gettext(" status: One or more devices were being "
1567 		    "resilvered.\n"));
1568 		break;
1569 
1570 	default:
1571 		/*
1572 		 * No other status can be seen when importing pools.
1573 		 */
1574 		assert(reason == ZPOOL_STATUS_OK);
1575 	}
1576 
1577 	/*
1578 	 * Print out an action according to the overall state of the pool.
1579 	 */
1580 	if (vs->vs_state == VDEV_STATE_HEALTHY) {
1581 		if (reason == ZPOOL_STATUS_VERSION_OLDER ||
1582 		    reason == ZPOOL_STATUS_FEAT_DISABLED) {
1583 			(void) printf(gettext(" action: The pool can be "
1584 			    "imported using its name or numeric identifier, "
1585 			    "though\n\tsome features will not be available "
1586 			    "without an explicit 'zpool upgrade'.\n"));
1587 		} else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH) {
1588 			(void) printf(gettext(" action: The pool can be "
1589 			    "imported using its name or numeric "
1590 			    "identifier and\n\tthe '-f' flag.\n"));
1591 		} else {
1592 			(void) printf(gettext(" action: The pool can be "
1593 			    "imported using its name or numeric "
1594 			    "identifier.\n"));
1595 		}
1596 	} else if (vs->vs_state == VDEV_STATE_DEGRADED) {
1597 		(void) printf(gettext(" action: The pool can be imported "
1598 		    "despite missing or damaged devices.  The\n\tfault "
1599 		    "tolerance of the pool may be compromised if imported.\n"));
1600 	} else {
1601 		switch (reason) {
1602 		case ZPOOL_STATUS_VERSION_NEWER:
1603 			(void) printf(gettext(" action: The pool cannot be "
1604 			    "imported.  Access the pool on a system running "
1605 			    "newer\n\tsoftware, or recreate the pool from "
1606 			    "backup.\n"));
1607 			break;
1608 		case ZPOOL_STATUS_UNSUP_FEAT_READ:
1609 			(void) printf(gettext("action: The pool cannot be "
1610 			    "imported. Access the pool on a system that "
1611 			    "supports\n\tthe required feature(s), or recreate "
1612 			    "the pool from backup.\n"));
1613 			break;
1614 		case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
1615 			(void) printf(gettext("action: The pool cannot be "
1616 			    "imported in read-write mode. Import the pool "
1617 			    "with\n"
1618 			    "\t\"-o readonly=on\", access the pool on a system "
1619 			    "that supports the\n\trequired feature(s), or "
1620 			    "recreate the pool from backup.\n"));
1621 			break;
1622 		case ZPOOL_STATUS_MISSING_DEV_R:
1623 		case ZPOOL_STATUS_MISSING_DEV_NR:
1624 		case ZPOOL_STATUS_BAD_GUID_SUM:
1625 			(void) printf(gettext(" action: The pool cannot be "
1626 			    "imported. Attach the missing\n\tdevices and try "
1627 			    "again.\n"));
1628 			break;
1629 		default:
1630 			(void) printf(gettext(" action: The pool cannot be "
1631 			    "imported due to damaged devices or data.\n"));
1632 		}
1633 	}
1634 
1635 	/* Print the comment attached to the pool. */
1636 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
1637 		(void) printf(gettext("comment: %s\n"), comment);
1638 
1639 	/*
1640 	 * If the state is "closed" or "can't open", and the aux state
1641 	 * is "corrupt data":
1642 	 */
1643 	if (((vs->vs_state == VDEV_STATE_CLOSED) ||
1644 	    (vs->vs_state == VDEV_STATE_CANT_OPEN)) &&
1645 	    (vs->vs_aux == VDEV_AUX_CORRUPT_DATA)) {
1646 		if (pool_state == POOL_STATE_DESTROYED)
1647 			(void) printf(gettext("\tThe pool was destroyed, "
1648 			    "but can be imported using the '-Df' flags.\n"));
1649 		else if (pool_state != POOL_STATE_EXPORTED)
1650 			(void) printf(gettext("\tThe pool may be active on "
1651 			    "another system, but can be imported using\n\t"
1652 			    "the '-f' flag.\n"));
1653 	}
1654 
1655 	if (msgid != NULL)
1656 		(void) printf(gettext("   see: http://illumos.org/msg/%s\n"),
1657 		    msgid);
1658 
1659 	(void) printf(gettext(" config:\n\n"));
1660 
1661 	namewidth = max_width(NULL, nvroot, 0, 0);
1662 	if (namewidth < 10)
1663 		namewidth = 10;
1664 
1665 	print_import_config(name, nvroot, namewidth, 0);
1666 	if (num_logs(nvroot) > 0)
1667 		print_logs(NULL, nvroot, namewidth, B_FALSE);
1668 
1669 	if (reason == ZPOOL_STATUS_BAD_GUID_SUM) {
1670 		(void) printf(gettext("\n\tAdditional devices are known to "
1671 		    "be part of this pool, though their\n\texact "
1672 		    "configuration cannot be determined.\n"));
1673 	}
1674 }
1675 
1676 /*
1677  * Perform the import for the given configuration.  This passes the heavy
1678  * lifting off to zpool_import_props(), and then mounts the datasets contained
1679  * within the pool.
1680  */
1681 static int
do_import(nvlist_t * config,const char * newname,const char * mntopts,nvlist_t * props,int flags)1682 do_import(nvlist_t *config, const char *newname, const char *mntopts,
1683     nvlist_t *props, int flags)
1684 {
1685 	zpool_handle_t *zhp;
1686 	char *name;
1687 	uint64_t state;
1688 	uint64_t version;
1689 
1690 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1691 	    &name) == 0);
1692 
1693 	verify(nvlist_lookup_uint64(config,
1694 	    ZPOOL_CONFIG_POOL_STATE, &state) == 0);
1695 	verify(nvlist_lookup_uint64(config,
1696 	    ZPOOL_CONFIG_VERSION, &version) == 0);
1697 	if (!SPA_VERSION_IS_SUPPORTED(version)) {
1698 		(void) fprintf(stderr, gettext("cannot import '%s': pool "
1699 		    "is formatted using an unsupported ZFS version\n"), name);
1700 		return (1);
1701 	} else if (state != POOL_STATE_EXPORTED &&
1702 	    !(flags & ZFS_IMPORT_ANY_HOST)) {
1703 		uint64_t hostid;
1704 
1705 		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_HOSTID,
1706 		    &hostid) == 0) {
1707 			if ((unsigned long)hostid != gethostid()) {
1708 				char *hostname;
1709 				uint64_t timestamp;
1710 				time_t t;
1711 
1712 				verify(nvlist_lookup_string(config,
1713 				    ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
1714 				verify(nvlist_lookup_uint64(config,
1715 				    ZPOOL_CONFIG_TIMESTAMP, &timestamp) == 0);
1716 				t = timestamp;
1717 				(void) fprintf(stderr, gettext("cannot import "
1718 				    "'%s': pool may be in use from other "
1719 				    "system, it was last accessed by %s "
1720 				    "(hostid: 0x%lx) on %s"), name, hostname,
1721 				    (unsigned long)hostid,
1722 				    asctime(localtime(&t)));
1723 				(void) fprintf(stderr, gettext("use '-f' to "
1724 				    "import anyway\n"));
1725 				return (1);
1726 			}
1727 		} else {
1728 			(void) fprintf(stderr, gettext("cannot import '%s': "
1729 			    "pool may be in use from other system\n"), name);
1730 			(void) fprintf(stderr, gettext("use '-f' to import "
1731 			    "anyway\n"));
1732 			return (1);
1733 		}
1734 	}
1735 
1736 	if (zpool_import_props(g_zfs, config, newname, props, flags) != 0)
1737 		return (1);
1738 
1739 	if (newname != NULL)
1740 		name = (char *)newname;
1741 
1742 	if ((zhp = zpool_open_canfail(g_zfs, name)) == NULL)
1743 		return (1);
1744 
1745 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
1746 	    !(flags & ZFS_IMPORT_ONLY) &&
1747 	    zpool_enable_datasets(zhp, mntopts, 0) != 0) {
1748 		zpool_close(zhp);
1749 		return (1);
1750 	}
1751 
1752 	zpool_close(zhp);
1753 	return (0);
1754 }
1755 
1756 /*
1757  * zpool import [-d dir] [-D]
1758  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D]
1759  *              [-d dir | -c cachefile] [-f] -a
1760  *       import [-o mntopts] [-o prop=value] ... [-R root] [-D]
1761  *              [-d dir | -c cachefile] [-f] [-n] [-F] <pool | id> [newpool]
1762  *
1763  *	 -c	Read pool information from a cachefile instead of searching
1764  *		devices.
1765  *
1766  *       -d	Scan in a specific directory, other than /dev/dsk.  More than
1767  *		one directory can be specified using multiple '-d' options.
1768  *
1769  *       -D     Scan for previously destroyed pools or import all or only
1770  *              specified destroyed pools.
1771  *
1772  *       -R	Temporarily import the pool, with all mountpoints relative to
1773  *		the given root.  The pool will remain exported when the machine
1774  *		is rebooted.
1775  *
1776  *       -V	Import even in the presence of faulted vdevs.  This is an
1777  *       	intentionally undocumented option for testing purposes, and
1778  *       	treats the pool configuration as complete, leaving any bad
1779  *		vdevs in the FAULTED state. In other words, it does verbatim
1780  *		import.
1781  *
1782  *       -f	Force import, even if it appears that the pool is active.
1783  *
1784  *       -F     Attempt rewind if necessary.
1785  *
1786  *       -n     See if rewind would work, but don't actually rewind.
1787  *
1788  *       -N     Import the pool but don't mount datasets.
1789  *
1790  *       -T     Specify a starting txg to use for import. This option is
1791  *       	intentionally undocumented option for testing purposes.
1792  *
1793  *       -a	Import all pools found.
1794  *
1795  *       -o	Set property=value and/or temporary mount options (without '=').
1796  *
1797  * The import command scans for pools to import, and import pools based on pool
1798  * name and GUID.  The pool can also be renamed as part of the import process.
1799  */
1800 int
zpool_do_import(int argc,char ** argv)1801 zpool_do_import(int argc, char **argv)
1802 {
1803 	char **searchdirs = NULL;
1804 	int nsearch = 0;
1805 	int c;
1806 	int err = 0;
1807 	nvlist_t *pools = NULL;
1808 	boolean_t do_all = B_FALSE;
1809 	boolean_t do_destroyed = B_FALSE;
1810 	char *mntopts = NULL;
1811 	nvpair_t *elem;
1812 	nvlist_t *config;
1813 	uint64_t searchguid = 0;
1814 	char *searchname = NULL;
1815 	char *propval;
1816 	nvlist_t *found_config;
1817 	nvlist_t *policy = NULL;
1818 	nvlist_t *props = NULL;
1819 	boolean_t first;
1820 	int flags = ZFS_IMPORT_NORMAL;
1821 	uint32_t rewind_policy = ZPOOL_NO_REWIND;
1822 	boolean_t dryrun = B_FALSE;
1823 	boolean_t do_rewind = B_FALSE;
1824 	boolean_t xtreme_rewind = B_FALSE;
1825 	uint64_t pool_state, txg = -1ULL;
1826 	char *cachefile = NULL;
1827 	importargs_t idata = { 0 };
1828 	char *endptr;
1829 
1830 	/* check options */
1831 	while ((c = getopt(argc, argv, ":aCc:d:DEfFmnNo:rR:T:VX")) != -1) {
1832 		switch (c) {
1833 		case 'a':
1834 			do_all = B_TRUE;
1835 			break;
1836 		case 'c':
1837 			cachefile = optarg;
1838 			break;
1839 		case 'd':
1840 			if (searchdirs == NULL) {
1841 				searchdirs = safe_malloc(sizeof (char *));
1842 			} else {
1843 				char **tmp = safe_malloc((nsearch + 1) *
1844 				    sizeof (char *));
1845 				bcopy(searchdirs, tmp, nsearch *
1846 				    sizeof (char *));
1847 				free(searchdirs);
1848 				searchdirs = tmp;
1849 			}
1850 			searchdirs[nsearch++] = optarg;
1851 			break;
1852 		case 'D':
1853 			do_destroyed = B_TRUE;
1854 			break;
1855 		case 'f':
1856 			flags |= ZFS_IMPORT_ANY_HOST;
1857 			break;
1858 		case 'F':
1859 			do_rewind = B_TRUE;
1860 			break;
1861 		case 'm':
1862 			flags |= ZFS_IMPORT_MISSING_LOG;
1863 			break;
1864 		case 'n':
1865 			dryrun = B_TRUE;
1866 			break;
1867 		case 'N':
1868 			flags |= ZFS_IMPORT_ONLY;
1869 			break;
1870 		case 'o':
1871 			if ((propval = strchr(optarg, '=')) != NULL) {
1872 				*propval = '\0';
1873 				propval++;
1874 				if (add_prop_list(optarg, propval,
1875 				    &props, B_TRUE))
1876 					goto error;
1877 			} else {
1878 				mntopts = optarg;
1879 			}
1880 			break;
1881 		case 'R':
1882 			if (add_prop_list(zpool_prop_to_name(
1883 			    ZPOOL_PROP_ALTROOT), optarg, &props, B_TRUE))
1884 				goto error;
1885 			if (nvlist_lookup_string(props,
1886 			    zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
1887 			    &propval) == 0)
1888 				break;
1889 			if (add_prop_list(zpool_prop_to_name(
1890 			    ZPOOL_PROP_CACHEFILE), "none", &props, B_TRUE))
1891 				goto error;
1892 			break;
1893 		case 'T':
1894 			errno = 0;
1895 			txg = strtoull(optarg, &endptr, 0);
1896 			if (errno != 0 || *endptr != '\0') {
1897 				(void) fprintf(stderr,
1898 				    gettext("invalid txg value\n"));
1899 				usage(B_FALSE);
1900 			}
1901 			rewind_policy = ZPOOL_DO_REWIND | ZPOOL_EXTREME_REWIND;
1902 			break;
1903 		case 'V':
1904 			flags |= ZFS_IMPORT_VERBATIM;
1905 			break;
1906 		case 'X':
1907 			xtreme_rewind = B_TRUE;
1908 			break;
1909 		case ':':
1910 			(void) fprintf(stderr, gettext("missing argument for "
1911 			    "'%c' option\n"), optopt);
1912 			usage(B_FALSE);
1913 			break;
1914 		case '?':
1915 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1916 			    optopt);
1917 			usage(B_FALSE);
1918 		}
1919 	}
1920 
1921 	argc -= optind;
1922 	argv += optind;
1923 
1924 	if (cachefile && nsearch != 0) {
1925 		(void) fprintf(stderr, gettext("-c is incompatible with -d\n"));
1926 		usage(B_FALSE);
1927 	}
1928 
1929 	if ((dryrun || xtreme_rewind) && !do_rewind) {
1930 		(void) fprintf(stderr,
1931 		    gettext("-n or -X only meaningful with -F\n"));
1932 		usage(B_FALSE);
1933 	}
1934 	if (dryrun)
1935 		rewind_policy = ZPOOL_TRY_REWIND;
1936 	else if (do_rewind)
1937 		rewind_policy = ZPOOL_DO_REWIND;
1938 	if (xtreme_rewind)
1939 		rewind_policy |= ZPOOL_EXTREME_REWIND;
1940 
1941 	/* In the future, we can capture further policy and include it here */
1942 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
1943 	    nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, txg) != 0 ||
1944 	    nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
1945 		goto error;
1946 
1947 	if (searchdirs == NULL) {
1948 		searchdirs = safe_malloc(sizeof (char *));
1949 		searchdirs[0] = "/dev/dsk";
1950 		nsearch = 1;
1951 	}
1952 
1953 	/* check argument count */
1954 	if (do_all) {
1955 		if (argc != 0) {
1956 			(void) fprintf(stderr, gettext("too many arguments\n"));
1957 			usage(B_FALSE);
1958 		}
1959 	} else {
1960 		if (argc > 2) {
1961 			(void) fprintf(stderr, gettext("too many arguments\n"));
1962 			usage(B_FALSE);
1963 		}
1964 
1965 		/*
1966 		 * Check for the SYS_CONFIG privilege.  We do this explicitly
1967 		 * here because otherwise any attempt to discover pools will
1968 		 * silently fail.
1969 		 */
1970 		if (argc == 0 && !priv_ineffect(PRIV_SYS_CONFIG)) {
1971 			(void) fprintf(stderr, gettext("cannot "
1972 			    "discover pools: permission denied\n"));
1973 			free(searchdirs);
1974 			nvlist_free(policy);
1975 			return (1);
1976 		}
1977 	}
1978 
1979 	/*
1980 	 * Depending on the arguments given, we do one of the following:
1981 	 *
1982 	 *	<none>	Iterate through all pools and display information about
1983 	 *		each one.
1984 	 *
1985 	 *	-a	Iterate through all pools and try to import each one.
1986 	 *
1987 	 *	<id>	Find the pool that corresponds to the given GUID/pool
1988 	 *		name and import that one.
1989 	 *
1990 	 *	-D	Above options applies only to destroyed pools.
1991 	 */
1992 	if (argc != 0) {
1993 		char *endptr;
1994 
1995 		errno = 0;
1996 		searchguid = strtoull(argv[0], &endptr, 10);
1997 		if (errno != 0 || *endptr != '\0') {
1998 			searchname = argv[0];
1999 			searchguid = 0;
2000 		}
2001 		found_config = NULL;
2002 
2003 		/*
2004 		 * User specified a name or guid.  Ensure it's unique.
2005 		 */
2006 		idata.unique = B_TRUE;
2007 	}
2008 
2009 
2010 	idata.path = searchdirs;
2011 	idata.paths = nsearch;
2012 	idata.poolname = searchname;
2013 	idata.guid = searchguid;
2014 	idata.cachefile = cachefile;
2015 
2016 	pools = zpool_search_import(g_zfs, &idata);
2017 
2018 	if (pools != NULL && idata.exists &&
2019 	    (argc == 1 || strcmp(argv[0], argv[1]) == 0)) {
2020 		(void) fprintf(stderr, gettext("cannot import '%s': "
2021 		    "a pool with that name already exists\n"),
2022 		    argv[0]);
2023 		(void) fprintf(stderr, gettext("use the form '%s "
2024 		    "<pool | id> <newpool>' to give it a new name\n"),
2025 		    "zpool import");
2026 		err = 1;
2027 	} else if (pools == NULL && idata.exists) {
2028 		(void) fprintf(stderr, gettext("cannot import '%s': "
2029 		    "a pool with that name is already created/imported,\n"),
2030 		    argv[0]);
2031 		(void) fprintf(stderr, gettext("and no additional pools "
2032 		    "with that name were found\n"));
2033 		err = 1;
2034 	} else if (pools == NULL) {
2035 		if (argc != 0) {
2036 			(void) fprintf(stderr, gettext("cannot import '%s': "
2037 			    "no such pool available\n"), argv[0]);
2038 		}
2039 		err = 1;
2040 	}
2041 
2042 	if (err == 1) {
2043 		free(searchdirs);
2044 		nvlist_free(policy);
2045 		return (1);
2046 	}
2047 
2048 	/*
2049 	 * At this point we have a list of import candidate configs. Even if
2050 	 * we were searching by pool name or guid, we still need to
2051 	 * post-process the list to deal with pool state and possible
2052 	 * duplicate names.
2053 	 */
2054 	err = 0;
2055 	elem = NULL;
2056 	first = B_TRUE;
2057 	while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2058 
2059 		verify(nvpair_value_nvlist(elem, &config) == 0);
2060 
2061 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2062 		    &pool_state) == 0);
2063 		if (!do_destroyed && pool_state == POOL_STATE_DESTROYED)
2064 			continue;
2065 		if (do_destroyed && pool_state != POOL_STATE_DESTROYED)
2066 			continue;
2067 
2068 		verify(nvlist_add_nvlist(config, ZPOOL_REWIND_POLICY,
2069 		    policy) == 0);
2070 
2071 		if (argc == 0) {
2072 			if (first)
2073 				first = B_FALSE;
2074 			else if (!do_all)
2075 				(void) printf("\n");
2076 
2077 			if (do_all) {
2078 				err |= do_import(config, NULL, mntopts,
2079 				    props, flags);
2080 			} else {
2081 				show_import(config);
2082 			}
2083 		} else if (searchname != NULL) {
2084 			char *name;
2085 
2086 			/*
2087 			 * We are searching for a pool based on name.
2088 			 */
2089 			verify(nvlist_lookup_string(config,
2090 			    ZPOOL_CONFIG_POOL_NAME, &name) == 0);
2091 
2092 			if (strcmp(name, searchname) == 0) {
2093 				if (found_config != NULL) {
2094 					(void) fprintf(stderr, gettext(
2095 					    "cannot import '%s': more than "
2096 					    "one matching pool\n"), searchname);
2097 					(void) fprintf(stderr, gettext(
2098 					    "import by numeric ID instead\n"));
2099 					err = B_TRUE;
2100 				}
2101 				found_config = config;
2102 			}
2103 		} else {
2104 			uint64_t guid;
2105 
2106 			/*
2107 			 * Search for a pool by guid.
2108 			 */
2109 			verify(nvlist_lookup_uint64(config,
2110 			    ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
2111 
2112 			if (guid == searchguid)
2113 				found_config = config;
2114 		}
2115 	}
2116 
2117 	/*
2118 	 * If we were searching for a specific pool, verify that we found a
2119 	 * pool, and then do the import.
2120 	 */
2121 	if (argc != 0 && err == 0) {
2122 		if (found_config == NULL) {
2123 			(void) fprintf(stderr, gettext("cannot import '%s': "
2124 			    "no such pool available\n"), argv[0]);
2125 			err = B_TRUE;
2126 		} else {
2127 			err |= do_import(found_config, argc == 1 ? NULL :
2128 			    argv[1], mntopts, props, flags);
2129 		}
2130 	}
2131 
2132 	/*
2133 	 * If we were just looking for pools, report an error if none were
2134 	 * found.
2135 	 */
2136 	if (argc == 0 && first)
2137 		(void) fprintf(stderr,
2138 		    gettext("no pools available to import\n"));
2139 
2140 error:
2141 	nvlist_free(props);
2142 	nvlist_free(pools);
2143 	nvlist_free(policy);
2144 	free(searchdirs);
2145 
2146 	return (err ? 1 : 0);
2147 }
2148 
2149 typedef struct iostat_cbdata {
2150 	boolean_t cb_verbose;
2151 	int cb_namewidth;
2152 	int cb_iteration;
2153 	zpool_list_t *cb_list;
2154 } iostat_cbdata_t;
2155 
2156 static void
print_iostat_separator(iostat_cbdata_t * cb)2157 print_iostat_separator(iostat_cbdata_t *cb)
2158 {
2159 	int i = 0;
2160 
2161 	for (i = 0; i < cb->cb_namewidth; i++)
2162 		(void) printf("-");
2163 	(void) printf("  -----  -----  -----  -----  -----  -----\n");
2164 }
2165 
2166 static void
print_iostat_header(iostat_cbdata_t * cb)2167 print_iostat_header(iostat_cbdata_t *cb)
2168 {
2169 	(void) printf("%*s     capacity     operations    bandwidth\n",
2170 	    cb->cb_namewidth, "");
2171 	(void) printf("%-*s  alloc   free   read  write   read  write\n",
2172 	    cb->cb_namewidth, "pool");
2173 	print_iostat_separator(cb);
2174 }
2175 
2176 /*
2177  * Display a single statistic.
2178  */
2179 static void
print_one_stat(uint64_t value)2180 print_one_stat(uint64_t value)
2181 {
2182 	char buf[64];
2183 
2184 	zfs_nicenum(value, buf, sizeof (buf));
2185 	(void) printf("  %5s", buf);
2186 }
2187 
2188 /*
2189  * Print out all the statistics for the given vdev.  This can either be the
2190  * toplevel configuration, or called recursively.  If 'name' is NULL, then this
2191  * is a verbose output, and we don't want to display the toplevel pool stats.
2192  */
2193 void
print_vdev_stats(zpool_handle_t * zhp,const char * name,nvlist_t * oldnv,nvlist_t * newnv,iostat_cbdata_t * cb,int depth)2194 print_vdev_stats(zpool_handle_t *zhp, const char *name, nvlist_t *oldnv,
2195     nvlist_t *newnv, iostat_cbdata_t *cb, int depth)
2196 {
2197 	nvlist_t **oldchild, **newchild;
2198 	uint_t c, children;
2199 	vdev_stat_t *oldvs, *newvs;
2200 	vdev_stat_t zerovs = { 0 };
2201 	uint64_t tdelta;
2202 	double scale;
2203 	char *vname;
2204 
2205 	if (oldnv != NULL) {
2206 		verify(nvlist_lookup_uint64_array(oldnv,
2207 		    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&oldvs, &c) == 0);
2208 	} else {
2209 		oldvs = &zerovs;
2210 	}
2211 
2212 	verify(nvlist_lookup_uint64_array(newnv, ZPOOL_CONFIG_VDEV_STATS,
2213 	    (uint64_t **)&newvs, &c) == 0);
2214 
2215 	if (strlen(name) + depth > cb->cb_namewidth)
2216 		(void) printf("%*s%s", depth, "", name);
2217 	else
2218 		(void) printf("%*s%s%*s", depth, "", name,
2219 		    (int)(cb->cb_namewidth - strlen(name) - depth), "");
2220 
2221 	tdelta = newvs->vs_timestamp - oldvs->vs_timestamp;
2222 
2223 	if (tdelta == 0)
2224 		scale = 1.0;
2225 	else
2226 		scale = (double)NANOSEC / tdelta;
2227 
2228 	/* only toplevel vdevs have capacity stats */
2229 	if (newvs->vs_space == 0) {
2230 		(void) printf("      -      -");
2231 	} else {
2232 		print_one_stat(newvs->vs_alloc);
2233 		print_one_stat(newvs->vs_space - newvs->vs_alloc);
2234 	}
2235 
2236 	print_one_stat((uint64_t)(scale * (newvs->vs_ops[ZIO_TYPE_READ] -
2237 	    oldvs->vs_ops[ZIO_TYPE_READ])));
2238 
2239 	print_one_stat((uint64_t)(scale * (newvs->vs_ops[ZIO_TYPE_WRITE] -
2240 	    oldvs->vs_ops[ZIO_TYPE_WRITE])));
2241 
2242 	print_one_stat((uint64_t)(scale * (newvs->vs_bytes[ZIO_TYPE_READ] -
2243 	    oldvs->vs_bytes[ZIO_TYPE_READ])));
2244 
2245 	print_one_stat((uint64_t)(scale * (newvs->vs_bytes[ZIO_TYPE_WRITE] -
2246 	    oldvs->vs_bytes[ZIO_TYPE_WRITE])));
2247 
2248 	(void) printf("\n");
2249 
2250 	if (!cb->cb_verbose)
2251 		return;
2252 
2253 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_CHILDREN,
2254 	    &newchild, &children) != 0)
2255 		return;
2256 
2257 	if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_CHILDREN,
2258 	    &oldchild, &c) != 0)
2259 		return;
2260 
2261 	for (c = 0; c < children; c++) {
2262 		uint64_t ishole = B_FALSE, islog = B_FALSE;
2263 
2264 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_HOLE,
2265 		    &ishole);
2266 
2267 		(void) nvlist_lookup_uint64(newchild[c], ZPOOL_CONFIG_IS_LOG,
2268 		    &islog);
2269 
2270 		if (ishole || islog)
2271 			continue;
2272 
2273 		vname = zpool_vdev_name(g_zfs, zhp, newchild[c], B_FALSE);
2274 		print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
2275 		    newchild[c], cb, depth + 2);
2276 		free(vname);
2277 	}
2278 
2279 	/*
2280 	 * Log device section
2281 	 */
2282 
2283 	if (num_logs(newnv) > 0) {
2284 		(void) printf("%-*s      -      -      -      -      -      "
2285 		    "-\n", cb->cb_namewidth, "logs");
2286 
2287 		for (c = 0; c < children; c++) {
2288 			uint64_t islog = B_FALSE;
2289 			(void) nvlist_lookup_uint64(newchild[c],
2290 			    ZPOOL_CONFIG_IS_LOG, &islog);
2291 
2292 			if (islog) {
2293 				vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
2294 				    B_FALSE);
2295 				print_vdev_stats(zhp, vname, oldnv ?
2296 				    oldchild[c] : NULL, newchild[c],
2297 				    cb, depth + 2);
2298 				free(vname);
2299 			}
2300 		}
2301 
2302 	}
2303 
2304 	/*
2305 	 * Include level 2 ARC devices in iostat output
2306 	 */
2307 	if (nvlist_lookup_nvlist_array(newnv, ZPOOL_CONFIG_L2CACHE,
2308 	    &newchild, &children) != 0)
2309 		return;
2310 
2311 	if (oldnv && nvlist_lookup_nvlist_array(oldnv, ZPOOL_CONFIG_L2CACHE,
2312 	    &oldchild, &c) != 0)
2313 		return;
2314 
2315 	if (children > 0) {
2316 		(void) printf("%-*s      -      -      -      -      -      "
2317 		    "-\n", cb->cb_namewidth, "cache");
2318 		for (c = 0; c < children; c++) {
2319 			vname = zpool_vdev_name(g_zfs, zhp, newchild[c],
2320 			    B_FALSE);
2321 			print_vdev_stats(zhp, vname, oldnv ? oldchild[c] : NULL,
2322 			    newchild[c], cb, depth + 2);
2323 			free(vname);
2324 		}
2325 	}
2326 }
2327 
2328 static int
refresh_iostat(zpool_handle_t * zhp,void * data)2329 refresh_iostat(zpool_handle_t *zhp, void *data)
2330 {
2331 	iostat_cbdata_t *cb = data;
2332 	boolean_t missing;
2333 
2334 	/*
2335 	 * If the pool has disappeared, remove it from the list and continue.
2336 	 */
2337 	if (zpool_refresh_stats(zhp, &missing) != 0)
2338 		return (-1);
2339 
2340 	if (missing)
2341 		pool_list_remove(cb->cb_list, zhp);
2342 
2343 	return (0);
2344 }
2345 
2346 /*
2347  * Callback to print out the iostats for the given pool.
2348  */
2349 int
print_iostat(zpool_handle_t * zhp,void * data)2350 print_iostat(zpool_handle_t *zhp, void *data)
2351 {
2352 	iostat_cbdata_t *cb = data;
2353 	nvlist_t *oldconfig, *newconfig;
2354 	nvlist_t *oldnvroot, *newnvroot;
2355 
2356 	newconfig = zpool_get_config(zhp, &oldconfig);
2357 
2358 	if (cb->cb_iteration == 1)
2359 		oldconfig = NULL;
2360 
2361 	verify(nvlist_lookup_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE,
2362 	    &newnvroot) == 0);
2363 
2364 	if (oldconfig == NULL)
2365 		oldnvroot = NULL;
2366 	else
2367 		verify(nvlist_lookup_nvlist(oldconfig, ZPOOL_CONFIG_VDEV_TREE,
2368 		    &oldnvroot) == 0);
2369 
2370 	/*
2371 	 * Print out the statistics for the pool.
2372 	 */
2373 	print_vdev_stats(zhp, zpool_get_name(zhp), oldnvroot, newnvroot, cb, 0);
2374 
2375 	if (cb->cb_verbose)
2376 		print_iostat_separator(cb);
2377 
2378 	return (0);
2379 }
2380 
2381 int
get_namewidth(zpool_handle_t * zhp,void * data)2382 get_namewidth(zpool_handle_t *zhp, void *data)
2383 {
2384 	iostat_cbdata_t *cb = data;
2385 	nvlist_t *config, *nvroot;
2386 
2387 	if ((config = zpool_get_config(zhp, NULL)) != NULL) {
2388 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2389 		    &nvroot) == 0);
2390 		if (!cb->cb_verbose)
2391 			cb->cb_namewidth = strlen(zpool_get_name(zhp));
2392 		else
2393 			cb->cb_namewidth = max_width(zhp, nvroot, 0,
2394 			    cb->cb_namewidth);
2395 	}
2396 
2397 	/*
2398 	 * The width must fall into the range [10,38].  The upper limit is the
2399 	 * maximum we can have and still fit in 80 columns.
2400 	 */
2401 	if (cb->cb_namewidth < 10)
2402 		cb->cb_namewidth = 10;
2403 	if (cb->cb_namewidth > 38)
2404 		cb->cb_namewidth = 38;
2405 
2406 	return (0);
2407 }
2408 
2409 /*
2410  * Parse the input string, get the 'interval' and 'count' value if there is one.
2411  */
2412 static void
get_interval_count(int * argcp,char ** argv,unsigned long * iv,unsigned long * cnt)2413 get_interval_count(int *argcp, char **argv, unsigned long *iv,
2414     unsigned long *cnt)
2415 {
2416 	unsigned long interval = 0, count = 0;
2417 	int argc = *argcp, errno;
2418 
2419 	/*
2420 	 * Determine if the last argument is an integer or a pool name
2421 	 */
2422 	if (argc > 0 && isdigit(argv[argc - 1][0])) {
2423 		char *end;
2424 
2425 		errno = 0;
2426 		interval = strtoul(argv[argc - 1], &end, 10);
2427 
2428 		if (*end == '\0' && errno == 0) {
2429 			if (interval == 0) {
2430 				(void) fprintf(stderr, gettext("interval "
2431 				    "cannot be zero\n"));
2432 				usage(B_FALSE);
2433 			}
2434 			/*
2435 			 * Ignore the last parameter
2436 			 */
2437 			argc--;
2438 		} else {
2439 			/*
2440 			 * If this is not a valid number, just plow on.  The
2441 			 * user will get a more informative error message later
2442 			 * on.
2443 			 */
2444 			interval = 0;
2445 		}
2446 	}
2447 
2448 	/*
2449 	 * If the last argument is also an integer, then we have both a count
2450 	 * and an interval.
2451 	 */
2452 	if (argc > 0 && isdigit(argv[argc - 1][0])) {
2453 		char *end;
2454 
2455 		errno = 0;
2456 		count = interval;
2457 		interval = strtoul(argv[argc - 1], &end, 10);
2458 
2459 		if (*end == '\0' && errno == 0) {
2460 			if (interval == 0) {
2461 				(void) fprintf(stderr, gettext("interval "
2462 				    "cannot be zero\n"));
2463 				usage(B_FALSE);
2464 			}
2465 
2466 			/*
2467 			 * Ignore the last parameter
2468 			 */
2469 			argc--;
2470 		} else {
2471 			interval = 0;
2472 		}
2473 	}
2474 
2475 	*iv = interval;
2476 	*cnt = count;
2477 	*argcp = argc;
2478 }
2479 
2480 static void
get_timestamp_arg(char c)2481 get_timestamp_arg(char c)
2482 {
2483 	if (c == 'u')
2484 		timestamp_fmt = UDATE;
2485 	else if (c == 'd')
2486 		timestamp_fmt = DDATE;
2487 	else
2488 		usage(B_FALSE);
2489 }
2490 
2491 /*
2492  * zpool iostat [-v] [-T d|u] [pool] ... [interval [count]]
2493  *
2494  *	-v	Display statistics for individual vdevs
2495  *	-T	Display a timestamp in date(1) or Unix format
2496  *
2497  * This command can be tricky because we want to be able to deal with pool
2498  * creation/destruction as well as vdev configuration changes.  The bulk of this
2499  * processing is handled by the pool_list_* routines in zpool_iter.c.  We rely
2500  * on pool_list_update() to detect the addition of new pools.  Configuration
2501  * changes are all handled within libzfs.
2502  */
2503 int
zpool_do_iostat(int argc,char ** argv)2504 zpool_do_iostat(int argc, char **argv)
2505 {
2506 	int c;
2507 	int ret;
2508 	int npools;
2509 	unsigned long interval = 0, count = 0;
2510 	zpool_list_t *list;
2511 	boolean_t verbose = B_FALSE;
2512 	iostat_cbdata_t cb;
2513 
2514 	/* check options */
2515 	while ((c = getopt(argc, argv, "T:v")) != -1) {
2516 		switch (c) {
2517 		case 'T':
2518 			get_timestamp_arg(*optarg);
2519 			break;
2520 		case 'v':
2521 			verbose = B_TRUE;
2522 			break;
2523 		case '?':
2524 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2525 			    optopt);
2526 			usage(B_FALSE);
2527 		}
2528 	}
2529 
2530 	argc -= optind;
2531 	argv += optind;
2532 
2533 	get_interval_count(&argc, argv, &interval, &count);
2534 
2535 	/*
2536 	 * Construct the list of all interesting pools.
2537 	 */
2538 	ret = 0;
2539 	if ((list = pool_list_get(argc, argv, NULL, &ret)) == NULL)
2540 		return (1);
2541 
2542 	if (pool_list_count(list) == 0 && argc != 0) {
2543 		pool_list_free(list);
2544 		return (1);
2545 	}
2546 
2547 	if (pool_list_count(list) == 0 && interval == 0) {
2548 		pool_list_free(list);
2549 		(void) fprintf(stderr, gettext("no pools available\n"));
2550 		return (1);
2551 	}
2552 
2553 	/*
2554 	 * Enter the main iostat loop.
2555 	 */
2556 	cb.cb_list = list;
2557 	cb.cb_verbose = verbose;
2558 	cb.cb_iteration = 0;
2559 	cb.cb_namewidth = 0;
2560 
2561 	for (;;) {
2562 		pool_list_update(list);
2563 
2564 		if ((npools = pool_list_count(list)) == 0)
2565 			break;
2566 
2567 		/*
2568 		 * Refresh all statistics.  This is done as an explicit step
2569 		 * before calculating the maximum name width, so that any
2570 		 * configuration changes are properly accounted for.
2571 		 */
2572 		(void) pool_list_iter(list, B_FALSE, refresh_iostat, &cb);
2573 
2574 		/*
2575 		 * Iterate over all pools to determine the maximum width
2576 		 * for the pool / device name column across all pools.
2577 		 */
2578 		cb.cb_namewidth = 0;
2579 		(void) pool_list_iter(list, B_FALSE, get_namewidth, &cb);
2580 
2581 		if (timestamp_fmt != NODATE)
2582 			print_timestamp(timestamp_fmt);
2583 
2584 		/*
2585 		 * If it's the first time, or verbose mode, print the header.
2586 		 */
2587 		if (++cb.cb_iteration == 1 || verbose)
2588 			print_iostat_header(&cb);
2589 
2590 		(void) pool_list_iter(list, B_FALSE, print_iostat, &cb);
2591 
2592 		/*
2593 		 * If there's more than one pool, and we're not in verbose mode
2594 		 * (which prints a separator for us), then print a separator.
2595 		 */
2596 		if (npools > 1 && !verbose)
2597 			print_iostat_separator(&cb);
2598 
2599 		if (verbose)
2600 			(void) printf("\n");
2601 
2602 		/*
2603 		 * Flush the output so that redirection to a file isn't buffered
2604 		 * indefinitely.
2605 		 */
2606 		(void) fflush(stdout);
2607 
2608 		if (interval == 0)
2609 			break;
2610 
2611 		if (count != 0 && --count == 0)
2612 			break;
2613 
2614 		(void) sleep(interval);
2615 	}
2616 
2617 	pool_list_free(list);
2618 
2619 	return (ret);
2620 }
2621 
2622 typedef struct list_cbdata {
2623 	boolean_t	cb_verbose;
2624 	int		cb_namewidth;
2625 	boolean_t	cb_scripted;
2626 	zprop_list_t	*cb_proplist;
2627 	boolean_t	cb_literal;
2628 } list_cbdata_t;
2629 
2630 /*
2631  * Given a list of columns to display, output appropriate headers for each one.
2632  */
2633 static void
print_header(list_cbdata_t * cb)2634 print_header(list_cbdata_t *cb)
2635 {
2636 	zprop_list_t *pl = cb->cb_proplist;
2637 	char headerbuf[ZPOOL_MAXPROPLEN];
2638 	const char *header;
2639 	boolean_t first = B_TRUE;
2640 	boolean_t right_justify;
2641 	size_t width = 0;
2642 
2643 	for (; pl != NULL; pl = pl->pl_next) {
2644 		width = pl->pl_width;
2645 		if (first && cb->cb_verbose) {
2646 			/*
2647 			 * Reset the width to accommodate the verbose listing
2648 			 * of devices.
2649 			 */
2650 			width = cb->cb_namewidth;
2651 		}
2652 
2653 		if (!first)
2654 			(void) printf("  ");
2655 		else
2656 			first = B_FALSE;
2657 
2658 		right_justify = B_FALSE;
2659 		if (pl->pl_prop != ZPROP_INVAL) {
2660 			header = zpool_prop_column_name(pl->pl_prop);
2661 			right_justify = zpool_prop_align_right(pl->pl_prop);
2662 		} else {
2663 			int i;
2664 
2665 			for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2666 				headerbuf[i] = toupper(pl->pl_user_prop[i]);
2667 			headerbuf[i] = '\0';
2668 			header = headerbuf;
2669 		}
2670 
2671 		if (pl->pl_next == NULL && !right_justify)
2672 			(void) printf("%s", header);
2673 		else if (right_justify)
2674 			(void) printf("%*s", width, header);
2675 		else
2676 			(void) printf("%-*s", width, header);
2677 
2678 	}
2679 
2680 	(void) printf("\n");
2681 }
2682 
2683 /*
2684  * Given a pool and a list of properties, print out all the properties according
2685  * to the described layout.
2686  */
2687 static void
print_pool(zpool_handle_t * zhp,list_cbdata_t * cb)2688 print_pool(zpool_handle_t *zhp, list_cbdata_t *cb)
2689 {
2690 	zprop_list_t *pl = cb->cb_proplist;
2691 	boolean_t first = B_TRUE;
2692 	char property[ZPOOL_MAXPROPLEN];
2693 	char *propstr;
2694 	boolean_t right_justify;
2695 	size_t width;
2696 
2697 	for (; pl != NULL; pl = pl->pl_next) {
2698 
2699 		width = pl->pl_width;
2700 		if (first && cb->cb_verbose) {
2701 			/*
2702 			 * Reset the width to accommodate the verbose listing
2703 			 * of devices.
2704 			 */
2705 			width = cb->cb_namewidth;
2706 		}
2707 
2708 		if (!first) {
2709 			if (cb->cb_scripted)
2710 				(void) printf("\t");
2711 			else
2712 				(void) printf("  ");
2713 		} else {
2714 			first = B_FALSE;
2715 		}
2716 
2717 		right_justify = B_FALSE;
2718 		if (pl->pl_prop != ZPROP_INVAL) {
2719 			if (zpool_get_prop(zhp, pl->pl_prop, property,
2720 			    sizeof (property), NULL, cb->cb_literal) != 0)
2721 				propstr = "-";
2722 			else
2723 				propstr = property;
2724 
2725 			right_justify = zpool_prop_align_right(pl->pl_prop);
2726 		} else if ((zpool_prop_feature(pl->pl_user_prop) ||
2727 		    zpool_prop_unsupported(pl->pl_user_prop)) &&
2728 		    zpool_prop_get_feature(zhp, pl->pl_user_prop, property,
2729 		    sizeof (property)) == 0) {
2730 			propstr = property;
2731 		} else {
2732 			propstr = "-";
2733 		}
2734 
2735 
2736 		/*
2737 		 * If this is being called in scripted mode, or if this is the
2738 		 * last column and it is left-justified, don't include a width
2739 		 * format specifier.
2740 		 */
2741 		if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
2742 			(void) printf("%s", propstr);
2743 		else if (right_justify)
2744 			(void) printf("%*s", width, propstr);
2745 		else
2746 			(void) printf("%-*s", width, propstr);
2747 	}
2748 
2749 	(void) printf("\n");
2750 }
2751 
2752 static void
print_one_column(zpool_prop_t prop,uint64_t value,boolean_t scripted,boolean_t valid)2753 print_one_column(zpool_prop_t prop, uint64_t value, boolean_t scripted,
2754     boolean_t valid)
2755 {
2756 	char propval[64];
2757 	boolean_t fixed;
2758 	size_t width = zprop_width(prop, &fixed, ZFS_TYPE_POOL);
2759 
2760 	switch (prop) {
2761 	case ZPOOL_PROP_EXPANDSZ:
2762 		if (value == 0)
2763 			(void) strlcpy(propval, "-", sizeof (propval));
2764 		else
2765 			zfs_nicenum(value, propval, sizeof (propval));
2766 		break;
2767 	case ZPOOL_PROP_FRAGMENTATION:
2768 		if (value == ZFS_FRAG_INVALID) {
2769 			(void) strlcpy(propval, "-", sizeof (propval));
2770 		} else {
2771 			(void) snprintf(propval, sizeof (propval), "%llu%%",
2772 			    value);
2773 		}
2774 		break;
2775 	case ZPOOL_PROP_CAPACITY:
2776 		(void) snprintf(propval, sizeof (propval), "%llu%%", value);
2777 		break;
2778 	default:
2779 		zfs_nicenum(value, propval, sizeof (propval));
2780 	}
2781 
2782 	if (!valid)
2783 		(void) strlcpy(propval, "-", sizeof (propval));
2784 
2785 	if (scripted)
2786 		(void) printf("\t%s", propval);
2787 	else
2788 		(void) printf("  %*s", width, propval);
2789 }
2790 
2791 void
print_list_stats(zpool_handle_t * zhp,const char * name,nvlist_t * nv,list_cbdata_t * cb,int depth)2792 print_list_stats(zpool_handle_t *zhp, const char *name, nvlist_t *nv,
2793     list_cbdata_t *cb, int depth)
2794 {
2795 	nvlist_t **child;
2796 	vdev_stat_t *vs;
2797 	uint_t c, children;
2798 	char *vname;
2799 	boolean_t scripted = cb->cb_scripted;
2800 	uint64_t islog = B_FALSE;
2801 	boolean_t haslog = B_FALSE;
2802 	char *dashes = "%-*s      -      -      -         -      -      -\n";
2803 
2804 	verify(nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
2805 	    (uint64_t **)&vs, &c) == 0);
2806 
2807 	if (name != NULL) {
2808 		boolean_t toplevel = (vs->vs_space != 0);
2809 		uint64_t cap;
2810 
2811 		if (scripted)
2812 			(void) printf("\t%s", name);
2813 		else if (strlen(name) + depth > cb->cb_namewidth)
2814 			(void) printf("%*s%s", depth, "", name);
2815 		else
2816 			(void) printf("%*s%s%*s", depth, "", name,
2817 			    (int)(cb->cb_namewidth - strlen(name) - depth), "");
2818 
2819 		/*
2820 		 * Print the properties for the individual vdevs. Some
2821 		 * properties are only applicable to toplevel vdevs. The
2822 		 * 'toplevel' boolean value is passed to the print_one_column()
2823 		 * to indicate that the value is valid.
2824 		 */
2825 		print_one_column(ZPOOL_PROP_SIZE, vs->vs_space, scripted,
2826 		    toplevel);
2827 		print_one_column(ZPOOL_PROP_ALLOCATED, vs->vs_alloc, scripted,
2828 		    toplevel);
2829 		print_one_column(ZPOOL_PROP_FREE, vs->vs_space - vs->vs_alloc,
2830 		    scripted, toplevel);
2831 		print_one_column(ZPOOL_PROP_EXPANDSZ, vs->vs_esize, scripted,
2832 		    B_TRUE);
2833 		print_one_column(ZPOOL_PROP_FRAGMENTATION,
2834 		    vs->vs_fragmentation, scripted,
2835 		    (vs->vs_fragmentation != ZFS_FRAG_INVALID && toplevel));
2836 		cap = (vs->vs_space == 0) ? 0 :
2837 		    (vs->vs_alloc * 100 / vs->vs_space);
2838 		print_one_column(ZPOOL_PROP_CAPACITY, cap, scripted, toplevel);
2839 		(void) printf("\n");
2840 	}
2841 
2842 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2843 	    &child, &children) != 0)
2844 		return;
2845 
2846 	for (c = 0; c < children; c++) {
2847 		uint64_t ishole = B_FALSE;
2848 
2849 		if (nvlist_lookup_uint64(child[c],
2850 		    ZPOOL_CONFIG_IS_HOLE, &ishole) == 0 && ishole)
2851 			continue;
2852 
2853 		if (nvlist_lookup_uint64(child[c],
2854 		    ZPOOL_CONFIG_IS_LOG, &islog) == 0 && islog) {
2855 			haslog = B_TRUE;
2856 			continue;
2857 		}
2858 
2859 		vname = zpool_vdev_name(g_zfs, zhp, child[c], B_FALSE);
2860 		print_list_stats(zhp, vname, child[c], cb, depth + 2);
2861 		free(vname);
2862 	}
2863 
2864 	if (haslog == B_TRUE) {
2865 		/* LINTED E_SEC_PRINTF_VAR_FMT */
2866 		(void) printf(dashes, cb->cb_namewidth, "log");
2867 		for (c = 0; c < children; c++) {
2868 			if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2869 			    &islog) != 0 || !islog)
2870 				continue;
2871 			vname = zpool_vdev_name(g_zfs, zhp, child[c], B_FALSE);
2872 			print_list_stats(zhp, vname, child[c], cb, depth + 2);
2873 			free(vname);
2874 		}
2875 	}
2876 
2877 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2878 	    &child, &children) == 0 && children > 0) {
2879 		/* LINTED E_SEC_PRINTF_VAR_FMT */
2880 		(void) printf(dashes, cb->cb_namewidth, "cache");
2881 		for (c = 0; c < children; c++) {
2882 			vname = zpool_vdev_name(g_zfs, zhp, child[c], B_FALSE);
2883 			print_list_stats(zhp, vname, child[c], cb, depth + 2);
2884 			free(vname);
2885 		}
2886 	}
2887 
2888 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child,
2889 	    &children) == 0 && children > 0) {
2890 		/* LINTED E_SEC_PRINTF_VAR_FMT */
2891 		(void) printf(dashes, cb->cb_namewidth, "spare");
2892 		for (c = 0; c < children; c++) {
2893 			vname = zpool_vdev_name(g_zfs, zhp, child[c], B_FALSE);
2894 			print_list_stats(zhp, vname, child[c], cb, depth + 2);
2895 			free(vname);
2896 		}
2897 	}
2898 }
2899 
2900 
2901 /*
2902  * Generic callback function to list a pool.
2903  */
2904 int
list_callback(zpool_handle_t * zhp,void * data)2905 list_callback(zpool_handle_t *zhp, void *data)
2906 {
2907 	list_cbdata_t *cbp = data;
2908 	nvlist_t *config;
2909 	nvlist_t *nvroot;
2910 
2911 	config = zpool_get_config(zhp, NULL);
2912 
2913 	print_pool(zhp, cbp);
2914 	if (!cbp->cb_verbose)
2915 		return (0);
2916 
2917 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2918 	    &nvroot) == 0);
2919 	print_list_stats(zhp, NULL, nvroot, cbp, 0);
2920 
2921 	return (0);
2922 }
2923 
2924 /*
2925  * zpool list [-Hp] [-o prop[,prop]*] [-T d|u] [pool] ... [interval [count]]
2926  *
2927  *	-H	Scripted mode.  Don't display headers, and separate properties
2928  *		by a single tab.
2929  *	-o	List of properties to display.  Defaults to
2930  *		"name,size,allocated,free,expandsize,fragmentation,capacity,"
2931  *		"dedupratio,health,altroot"
2932  * 	-p	Diplay values in parsable (exact) format.
2933  *	-T	Display a timestamp in date(1) or Unix format
2934  *
2935  * List all pools in the system, whether or not they're healthy.  Output space
2936  * statistics for each one, as well as health status summary.
2937  */
2938 int
zpool_do_list(int argc,char ** argv)2939 zpool_do_list(int argc, char **argv)
2940 {
2941 	int c;
2942 	int ret;
2943 	list_cbdata_t cb = { 0 };
2944 	static char default_props[] =
2945 	    "name,size,allocated,free,expandsize,fragmentation,capacity,"
2946 	    "dedupratio,health,altroot";
2947 	char *props = default_props;
2948 	unsigned long interval = 0, count = 0;
2949 	zpool_list_t *list;
2950 	boolean_t first = B_TRUE;
2951 
2952 	/* check options */
2953 	while ((c = getopt(argc, argv, ":Ho:pT:v")) != -1) {
2954 		switch (c) {
2955 		case 'H':
2956 			cb.cb_scripted = B_TRUE;
2957 			break;
2958 		case 'o':
2959 			props = optarg;
2960 			break;
2961 		case 'p':
2962 			cb.cb_literal = B_TRUE;
2963 			break;
2964 		case 'T':
2965 			get_timestamp_arg(*optarg);
2966 			break;
2967 		case 'v':
2968 			cb.cb_verbose = B_TRUE;
2969 			break;
2970 		case ':':
2971 			(void) fprintf(stderr, gettext("missing argument for "
2972 			    "'%c' option\n"), optopt);
2973 			usage(B_FALSE);
2974 			break;
2975 		case '?':
2976 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2977 			    optopt);
2978 			usage(B_FALSE);
2979 		}
2980 	}
2981 
2982 	argc -= optind;
2983 	argv += optind;
2984 
2985 	get_interval_count(&argc, argv, &interval, &count);
2986 
2987 	if (zprop_get_list(g_zfs, props, &cb.cb_proplist, ZFS_TYPE_POOL) != 0)
2988 		usage(B_FALSE);
2989 
2990 	for (;;) {
2991 		if ((list = pool_list_get(argc, argv, &cb.cb_proplist,
2992 		    &ret)) == NULL)
2993 			return (1);
2994 
2995 		if (pool_list_count(list) == 0)
2996 			break;
2997 
2998 		cb.cb_namewidth = 0;
2999 		(void) pool_list_iter(list, B_FALSE, get_namewidth, &cb);
3000 
3001 		if (timestamp_fmt != NODATE)
3002 			print_timestamp(timestamp_fmt);
3003 
3004 		if (!cb.cb_scripted && (first || cb.cb_verbose)) {
3005 			print_header(&cb);
3006 			first = B_FALSE;
3007 		}
3008 		ret = pool_list_iter(list, B_TRUE, list_callback, &cb);
3009 
3010 		if (interval == 0)
3011 			break;
3012 
3013 		if (count != 0 && --count == 0)
3014 			break;
3015 
3016 		pool_list_free(list);
3017 		(void) sleep(interval);
3018 	}
3019 
3020 	if (argc == 0 && !cb.cb_scripted && pool_list_count(list) == 0) {
3021 		(void) printf(gettext("no pools available\n"));
3022 		ret = 0;
3023 	}
3024 
3025 	pool_list_free(list);
3026 	zprop_free_list(cb.cb_proplist);
3027 	return (ret);
3028 }
3029 
3030 static int
zpool_do_attach_or_replace(int argc,char ** argv,int replacing)3031 zpool_do_attach_or_replace(int argc, char **argv, int replacing)
3032 {
3033 	boolean_t force = B_FALSE;
3034 	int c;
3035 	nvlist_t *nvroot;
3036 	char *poolname, *old_disk, *new_disk;
3037 	zpool_handle_t *zhp;
3038 	int ret;
3039 
3040 	/* check options */
3041 	while ((c = getopt(argc, argv, "f")) != -1) {
3042 		switch (c) {
3043 		case 'f':
3044 			force = B_TRUE;
3045 			break;
3046 		case '?':
3047 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3048 			    optopt);
3049 			usage(B_FALSE);
3050 		}
3051 	}
3052 
3053 	argc -= optind;
3054 	argv += optind;
3055 
3056 	/* get pool name and check number of arguments */
3057 	if (argc < 1) {
3058 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
3059 		usage(B_FALSE);
3060 	}
3061 
3062 	poolname = argv[0];
3063 
3064 	if (argc < 2) {
3065 		(void) fprintf(stderr,
3066 		    gettext("missing <device> specification\n"));
3067 		usage(B_FALSE);
3068 	}
3069 
3070 	old_disk = argv[1];
3071 
3072 	if (argc < 3) {
3073 		if (!replacing) {
3074 			(void) fprintf(stderr,
3075 			    gettext("missing <new_device> specification\n"));
3076 			usage(B_FALSE);
3077 		}
3078 		new_disk = old_disk;
3079 		argc -= 1;
3080 		argv += 1;
3081 	} else {
3082 		new_disk = argv[2];
3083 		argc -= 2;
3084 		argv += 2;
3085 	}
3086 
3087 	if (argc > 1) {
3088 		(void) fprintf(stderr, gettext("too many arguments\n"));
3089 		usage(B_FALSE);
3090 	}
3091 
3092 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
3093 		return (1);
3094 
3095 	if (zpool_get_config(zhp, NULL) == NULL) {
3096 		(void) fprintf(stderr, gettext("pool '%s' is unavailable\n"),
3097 		    poolname);
3098 		zpool_close(zhp);
3099 		return (1);
3100 	}
3101 
3102 	nvroot = make_root_vdev(zhp, force, B_FALSE, replacing, B_FALSE,
3103 	    argc, argv);
3104 	if (nvroot == NULL) {
3105 		zpool_close(zhp);
3106 		return (1);
3107 	}
3108 
3109 	ret = zpool_vdev_attach(zhp, old_disk, new_disk, nvroot, replacing);
3110 
3111 	nvlist_free(nvroot);
3112 	zpool_close(zhp);
3113 
3114 	return (ret);
3115 }
3116 
3117 /*
3118  * zpool replace [-f] <pool> <device> <new_device>
3119  *
3120  *	-f	Force attach, even if <new_device> appears to be in use.
3121  *
3122  * Replace <device> with <new_device>.
3123  */
3124 /* ARGSUSED */
3125 int
zpool_do_replace(int argc,char ** argv)3126 zpool_do_replace(int argc, char **argv)
3127 {
3128 	return (zpool_do_attach_or_replace(argc, argv, B_TRUE));
3129 }
3130 
3131 /*
3132  * zpool attach [-f] <pool> <device> <new_device>
3133  *
3134  *	-f	Force attach, even if <new_device> appears to be in use.
3135  *
3136  * Attach <new_device> to the mirror containing <device>.  If <device> is not
3137  * part of a mirror, then <device> will be transformed into a mirror of
3138  * <device> and <new_device>.  In either case, <new_device> will begin life
3139  * with a DTL of [0, now], and will immediately begin to resilver itself.
3140  */
3141 int
zpool_do_attach(int argc,char ** argv)3142 zpool_do_attach(int argc, char **argv)
3143 {
3144 	return (zpool_do_attach_or_replace(argc, argv, B_FALSE));
3145 }
3146 
3147 /*
3148  * zpool detach [-f] <pool> <device>
3149  *
3150  *	-f	Force detach of <device>, even if DTLs argue against it
3151  *		(not supported yet)
3152  *
3153  * Detach a device from a mirror.  The operation will be refused if <device>
3154  * is the last device in the mirror, or if the DTLs indicate that this device
3155  * has the only valid copy of some data.
3156  */
3157 /* ARGSUSED */
3158 int
zpool_do_detach(int argc,char ** argv)3159 zpool_do_detach(int argc, char **argv)
3160 {
3161 	int c;
3162 	char *poolname, *path;
3163 	zpool_handle_t *zhp;
3164 	int ret;
3165 
3166 	/* check options */
3167 	while ((c = getopt(argc, argv, "f")) != -1) {
3168 		switch (c) {
3169 		case 'f':
3170 		case '?':
3171 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3172 			    optopt);
3173 			usage(B_FALSE);
3174 		}
3175 	}
3176 
3177 	argc -= optind;
3178 	argv += optind;
3179 
3180 	/* get pool name and check number of arguments */
3181 	if (argc < 1) {
3182 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
3183 		usage(B_FALSE);
3184 	}
3185 
3186 	if (argc < 2) {
3187 		(void) fprintf(stderr,
3188 		    gettext("missing <device> specification\n"));
3189 		usage(B_FALSE);
3190 	}
3191 
3192 	poolname = argv[0];
3193 	path = argv[1];
3194 
3195 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
3196 		return (1);
3197 
3198 	ret = zpool_vdev_detach(zhp, path);
3199 
3200 	zpool_close(zhp);
3201 
3202 	return (ret);
3203 }
3204 
3205 /*
3206  * zpool split [-n] [-o prop=val] ...
3207  *		[-o mntopt] ...
3208  *		[-R altroot] <pool> <newpool> [<device> ...]
3209  *
3210  *	-n	Do not split the pool, but display the resulting layout if
3211  *		it were to be split.
3212  *	-o	Set property=value, or set mount options.
3213  *	-R	Mount the split-off pool under an alternate root.
3214  *
3215  * Splits the named pool and gives it the new pool name.  Devices to be split
3216  * off may be listed, provided that no more than one device is specified
3217  * per top-level vdev mirror.  The newly split pool is left in an exported
3218  * state unless -R is specified.
3219  *
3220  * Restrictions: the top-level of the pool pool must only be made up of
3221  * mirrors; all devices in the pool must be healthy; no device may be
3222  * undergoing a resilvering operation.
3223  */
3224 int
zpool_do_split(int argc,char ** argv)3225 zpool_do_split(int argc, char **argv)
3226 {
3227 	char *srcpool, *newpool, *propval;
3228 	char *mntopts = NULL;
3229 	splitflags_t flags;
3230 	int c, ret = 0;
3231 	zpool_handle_t *zhp;
3232 	nvlist_t *config, *props = NULL;
3233 
3234 	flags.dryrun = B_FALSE;
3235 	flags.import = B_FALSE;
3236 
3237 	/* check options */
3238 	while ((c = getopt(argc, argv, ":R:no:")) != -1) {
3239 		switch (c) {
3240 		case 'R':
3241 			flags.import = B_TRUE;
3242 			if (add_prop_list(
3243 			    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), optarg,
3244 			    &props, B_TRUE) != 0) {
3245 				nvlist_free(props);
3246 				usage(B_FALSE);
3247 			}
3248 			break;
3249 		case 'n':
3250 			flags.dryrun = B_TRUE;
3251 			break;
3252 		case 'o':
3253 			if ((propval = strchr(optarg, '=')) != NULL) {
3254 				*propval = '\0';
3255 				propval++;
3256 				if (add_prop_list(optarg, propval,
3257 				    &props, B_TRUE) != 0) {
3258 					nvlist_free(props);
3259 					usage(B_FALSE);
3260 				}
3261 			} else {
3262 				mntopts = optarg;
3263 			}
3264 			break;
3265 		case ':':
3266 			(void) fprintf(stderr, gettext("missing argument for "
3267 			    "'%c' option\n"), optopt);
3268 			usage(B_FALSE);
3269 			break;
3270 		case '?':
3271 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3272 			    optopt);
3273 			usage(B_FALSE);
3274 			break;
3275 		}
3276 	}
3277 
3278 	if (!flags.import && mntopts != NULL) {
3279 		(void) fprintf(stderr, gettext("setting mntopts is only "
3280 		    "valid when importing the pool\n"));
3281 		usage(B_FALSE);
3282 	}
3283 
3284 	argc -= optind;
3285 	argv += optind;
3286 
3287 	if (argc < 1) {
3288 		(void) fprintf(stderr, gettext("Missing pool name\n"));
3289 		usage(B_FALSE);
3290 	}
3291 	if (argc < 2) {
3292 		(void) fprintf(stderr, gettext("Missing new pool name\n"));
3293 		usage(B_FALSE);
3294 	}
3295 
3296 	srcpool = argv[0];
3297 	newpool = argv[1];
3298 
3299 	argc -= 2;
3300 	argv += 2;
3301 
3302 	if ((zhp = zpool_open(g_zfs, srcpool)) == NULL)
3303 		return (1);
3304 
3305 	config = split_mirror_vdev(zhp, newpool, props, flags, argc, argv);
3306 	if (config == NULL) {
3307 		ret = 1;
3308 	} else {
3309 		if (flags.dryrun) {
3310 			(void) printf(gettext("would create '%s' with the "
3311 			    "following layout:\n\n"), newpool);
3312 			print_vdev_tree(NULL, newpool, config, 0, B_FALSE);
3313 		}
3314 		nvlist_free(config);
3315 	}
3316 
3317 	zpool_close(zhp);
3318 
3319 	if (ret != 0 || flags.dryrun || !flags.import)
3320 		return (ret);
3321 
3322 	/*
3323 	 * The split was successful. Now we need to open the new
3324 	 * pool and import it.
3325 	 */
3326 	if ((zhp = zpool_open_canfail(g_zfs, newpool)) == NULL)
3327 		return (1);
3328 	if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL &&
3329 	    zpool_enable_datasets(zhp, mntopts, 0) != 0) {
3330 		ret = 1;
3331 		(void) fprintf(stderr, gettext("Split was successful, but "
3332 		    "the datasets could not all be mounted\n"));
3333 		(void) fprintf(stderr, gettext("Try doing '%s' with a "
3334 		    "different altroot\n"), "zpool import");
3335 	}
3336 	zpool_close(zhp);
3337 
3338 	return (ret);
3339 }
3340 
3341 
3342 
3343 /*
3344  * zpool online <pool> <device> ...
3345  */
3346 int
zpool_do_online(int argc,char ** argv)3347 zpool_do_online(int argc, char **argv)
3348 {
3349 	int c, i;
3350 	char *poolname;
3351 	zpool_handle_t *zhp;
3352 	int ret = 0;
3353 	vdev_state_t newstate;
3354 	int flags = 0;
3355 
3356 	/* check options */
3357 	while ((c = getopt(argc, argv, "et")) != -1) {
3358 		switch (c) {
3359 		case 'e':
3360 			flags |= ZFS_ONLINE_EXPAND;
3361 			break;
3362 		case 't':
3363 		case '?':
3364 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3365 			    optopt);
3366 			usage(B_FALSE);
3367 		}
3368 	}
3369 
3370 	argc -= optind;
3371 	argv += optind;
3372 
3373 	/* get pool name and check number of arguments */
3374 	if (argc < 1) {
3375 		(void) fprintf(stderr, gettext("missing pool name\n"));
3376 		usage(B_FALSE);
3377 	}
3378 	if (argc < 2) {
3379 		(void) fprintf(stderr, gettext("missing device name\n"));
3380 		usage(B_FALSE);
3381 	}
3382 
3383 	poolname = argv[0];
3384 
3385 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
3386 		return (1);
3387 
3388 	for (i = 1; i < argc; i++) {
3389 		if (zpool_vdev_online(zhp, argv[i], flags, &newstate) == 0) {
3390 			if (newstate != VDEV_STATE_HEALTHY) {
3391 				(void) printf(gettext("warning: device '%s' "
3392 				    "onlined, but remains in faulted state\n"),
3393 				    argv[i]);
3394 				if (newstate == VDEV_STATE_FAULTED)
3395 					(void) printf(gettext("use 'zpool "
3396 					    "clear' to restore a faulted "
3397 					    "device\n"));
3398 				else
3399 					(void) printf(gettext("use 'zpool "
3400 					    "replace' to replace devices "
3401 					    "that are no longer present\n"));
3402 			}
3403 		} else {
3404 			ret = 1;
3405 		}
3406 	}
3407 
3408 	zpool_close(zhp);
3409 
3410 	return (ret);
3411 }
3412 
3413 /*
3414  * zpool offline [-ft] <pool> <device> ...
3415  *
3416  *	-f	Force the device into the offline state, even if doing
3417  *		so would appear to compromise pool availability.
3418  *		(not supported yet)
3419  *
3420  *	-t	Only take the device off-line temporarily.  The offline
3421  *		state will not be persistent across reboots.
3422  */
3423 /* ARGSUSED */
3424 int
zpool_do_offline(int argc,char ** argv)3425 zpool_do_offline(int argc, char **argv)
3426 {
3427 	int c, i;
3428 	char *poolname;
3429 	zpool_handle_t *zhp;
3430 	int ret = 0;
3431 	boolean_t istmp = B_FALSE;
3432 
3433 	/* check options */
3434 	while ((c = getopt(argc, argv, "ft")) != -1) {
3435 		switch (c) {
3436 		case 't':
3437 			istmp = B_TRUE;
3438 			break;
3439 		case 'f':
3440 		case '?':
3441 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3442 			    optopt);
3443 			usage(B_FALSE);
3444 		}
3445 	}
3446 
3447 	argc -= optind;
3448 	argv += optind;
3449 
3450 	/* get pool name and check number of arguments */
3451 	if (argc < 1) {
3452 		(void) fprintf(stderr, gettext("missing pool name\n"));
3453 		usage(B_FALSE);
3454 	}
3455 	if (argc < 2) {
3456 		(void) fprintf(stderr, gettext("missing device name\n"));
3457 		usage(B_FALSE);
3458 	}
3459 
3460 	poolname = argv[0];
3461 
3462 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
3463 		return (1);
3464 
3465 	for (i = 1; i < argc; i++) {
3466 		if (zpool_vdev_offline(zhp, argv[i], istmp) != 0)
3467 			ret = 1;
3468 	}
3469 
3470 	zpool_close(zhp);
3471 
3472 	return (ret);
3473 }
3474 
3475 /*
3476  * zpool clear <pool> [device]
3477  *
3478  * Clear all errors associated with a pool or a particular device.
3479  */
3480 int
zpool_do_clear(int argc,char ** argv)3481 zpool_do_clear(int argc, char **argv)
3482 {
3483 	int c;
3484 	int ret = 0;
3485 	boolean_t dryrun = B_FALSE;
3486 	boolean_t do_rewind = B_FALSE;
3487 	boolean_t xtreme_rewind = B_FALSE;
3488 	uint32_t rewind_policy = ZPOOL_NO_REWIND;
3489 	nvlist_t *policy = NULL;
3490 	zpool_handle_t *zhp;
3491 	char *pool, *device;
3492 
3493 	/* check options */
3494 	while ((c = getopt(argc, argv, "FnX")) != -1) {
3495 		switch (c) {
3496 		case 'F':
3497 			do_rewind = B_TRUE;
3498 			break;
3499 		case 'n':
3500 			dryrun = B_TRUE;
3501 			break;
3502 		case 'X':
3503 			xtreme_rewind = B_TRUE;
3504 			break;
3505 		case '?':
3506 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3507 			    optopt);
3508 			usage(B_FALSE);
3509 		}
3510 	}
3511 
3512 	argc -= optind;
3513 	argv += optind;
3514 
3515 	if (argc < 1) {
3516 		(void) fprintf(stderr, gettext("missing pool name\n"));
3517 		usage(B_FALSE);
3518 	}
3519 
3520 	if (argc > 2) {
3521 		(void) fprintf(stderr, gettext("too many arguments\n"));
3522 		usage(B_FALSE);
3523 	}
3524 
3525 	if ((dryrun || xtreme_rewind) && !do_rewind) {
3526 		(void) fprintf(stderr,
3527 		    gettext("-n or -X only meaningful with -F\n"));
3528 		usage(B_FALSE);
3529 	}
3530 	if (dryrun)
3531 		rewind_policy = ZPOOL_TRY_REWIND;
3532 	else if (do_rewind)
3533 		rewind_policy = ZPOOL_DO_REWIND;
3534 	if (xtreme_rewind)
3535 		rewind_policy |= ZPOOL_EXTREME_REWIND;
3536 
3537 	/* In future, further rewind policy choices can be passed along here */
3538 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
3539 	    nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind_policy) != 0)
3540 		return (1);
3541 
3542 	pool = argv[0];
3543 	device = argc == 2 ? argv[1] : NULL;
3544 
3545 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL) {
3546 		nvlist_free(policy);
3547 		return (1);
3548 	}
3549 
3550 	if (zpool_clear(zhp, device, policy) != 0)
3551 		ret = 1;
3552 
3553 	zpool_close(zhp);
3554 
3555 	nvlist_free(policy);
3556 
3557 	return (ret);
3558 }
3559 
3560 /*
3561  * zpool reguid <pool>
3562  */
3563 int
zpool_do_reguid(int argc,char ** argv)3564 zpool_do_reguid(int argc, char **argv)
3565 {
3566 	int c;
3567 	char *poolname;
3568 	zpool_handle_t *zhp;
3569 	int ret = 0;
3570 
3571 	/* check options */
3572 	while ((c = getopt(argc, argv, "")) != -1) {
3573 		switch (c) {
3574 		case '?':
3575 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3576 			    optopt);
3577 			usage(B_FALSE);
3578 		}
3579 	}
3580 
3581 	argc -= optind;
3582 	argv += optind;
3583 
3584 	/* get pool name and check number of arguments */
3585 	if (argc < 1) {
3586 		(void) fprintf(stderr, gettext("missing pool name\n"));
3587 		usage(B_FALSE);
3588 	}
3589 
3590 	if (argc > 1) {
3591 		(void) fprintf(stderr, gettext("too many arguments\n"));
3592 		usage(B_FALSE);
3593 	}
3594 
3595 	poolname = argv[0];
3596 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
3597 		return (1);
3598 
3599 	ret = zpool_reguid(zhp);
3600 
3601 	zpool_close(zhp);
3602 	return (ret);
3603 }
3604 
3605 
3606 /*
3607  * zpool reopen <pool>
3608  *
3609  * Reopen the pool so that the kernel can update the sizes of all vdevs.
3610  */
3611 int
zpool_do_reopen(int argc,char ** argv)3612 zpool_do_reopen(int argc, char **argv)
3613 {
3614 	int c;
3615 	int ret = 0;
3616 	zpool_handle_t *zhp;
3617 	char *pool;
3618 
3619 	/* check options */
3620 	while ((c = getopt(argc, argv, "")) != -1) {
3621 		switch (c) {
3622 		case '?':
3623 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3624 			    optopt);
3625 			usage(B_FALSE);
3626 		}
3627 	}
3628 
3629 	argc--;
3630 	argv++;
3631 
3632 	if (argc < 1) {
3633 		(void) fprintf(stderr, gettext("missing pool name\n"));
3634 		usage(B_FALSE);
3635 	}
3636 
3637 	if (argc > 1) {
3638 		(void) fprintf(stderr, gettext("too many arguments\n"));
3639 		usage(B_FALSE);
3640 	}
3641 
3642 	pool = argv[0];
3643 	if ((zhp = zpool_open_canfail(g_zfs, pool)) == NULL)
3644 		return (1);
3645 
3646 	ret = zpool_reopen(zhp);
3647 	zpool_close(zhp);
3648 	return (ret);
3649 }
3650 
3651 typedef struct scrub_cbdata {
3652 	int	cb_type;
3653 	int	cb_argc;
3654 	char	**cb_argv;
3655 } scrub_cbdata_t;
3656 
3657 int
scrub_callback(zpool_handle_t * zhp,void * data)3658 scrub_callback(zpool_handle_t *zhp, void *data)
3659 {
3660 	scrub_cbdata_t *cb = data;
3661 	int err;
3662 
3663 	/*
3664 	 * Ignore faulted pools.
3665 	 */
3666 	if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
3667 		(void) fprintf(stderr, gettext("cannot scrub '%s': pool is "
3668 		    "currently unavailable\n"), zpool_get_name(zhp));
3669 		return (1);
3670 	}
3671 
3672 	err = zpool_scan(zhp, cb->cb_type);
3673 
3674 	return (err != 0);
3675 }
3676 
3677 /*
3678  * zpool scrub [-s] <pool> ...
3679  *
3680  *	-s	Stop.  Stops any in-progress scrub.
3681  */
3682 int
zpool_do_scrub(int argc,char ** argv)3683 zpool_do_scrub(int argc, char **argv)
3684 {
3685 	int c;
3686 	scrub_cbdata_t cb;
3687 
3688 	cb.cb_type = POOL_SCAN_SCRUB;
3689 
3690 	/* check options */
3691 	while ((c = getopt(argc, argv, "s")) != -1) {
3692 		switch (c) {
3693 		case 's':
3694 			cb.cb_type = POOL_SCAN_NONE;
3695 			break;
3696 		case '?':
3697 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3698 			    optopt);
3699 			usage(B_FALSE);
3700 		}
3701 	}
3702 
3703 	cb.cb_argc = argc;
3704 	cb.cb_argv = argv;
3705 	argc -= optind;
3706 	argv += optind;
3707 
3708 	if (argc < 1) {
3709 		(void) fprintf(stderr, gettext("missing pool name argument\n"));
3710 		usage(B_FALSE);
3711 	}
3712 
3713 	return (for_each_pool(argc, argv, B_TRUE, NULL, scrub_callback, &cb));
3714 }
3715 
3716 typedef struct status_cbdata {
3717 	int		cb_count;
3718 	boolean_t	cb_allpools;
3719 	boolean_t	cb_verbose;
3720 	boolean_t	cb_explain;
3721 	boolean_t	cb_first;
3722 	boolean_t	cb_dedup_stats;
3723 } status_cbdata_t;
3724 
3725 /*
3726  * Print out detailed scrub status.
3727  */
3728 void
print_scan_status(pool_scan_stat_t * ps)3729 print_scan_status(pool_scan_stat_t *ps)
3730 {
3731 	time_t start, end;
3732 	uint64_t elapsed, mins_left, hours_left;
3733 	uint64_t pass_exam, examined, total;
3734 	uint_t rate;
3735 	double fraction_done;
3736 	char processed_buf[7], examined_buf[7], total_buf[7], rate_buf[7];
3737 
3738 	(void) printf(gettext("  scan: "));
3739 
3740 	/* If there's never been a scan, there's not much to say. */
3741 	if (ps == NULL || ps->pss_func == POOL_SCAN_NONE ||
3742 	    ps->pss_func >= POOL_SCAN_FUNCS) {
3743 		(void) printf(gettext("none requested\n"));
3744 		return;
3745 	}
3746 
3747 	start = ps->pss_start_time;
3748 	end = ps->pss_end_time;
3749 	zfs_nicenum(ps->pss_processed, processed_buf, sizeof (processed_buf));
3750 
3751 	assert(ps->pss_func == POOL_SCAN_SCRUB ||
3752 	    ps->pss_func == POOL_SCAN_RESILVER);
3753 	/*
3754 	 * Scan is finished or canceled.
3755 	 */
3756 	if (ps->pss_state == DSS_FINISHED) {
3757 		uint64_t minutes_taken = (end - start) / 60;
3758 		char *fmt = NULL;
3759 
3760 		if (ps->pss_func == POOL_SCAN_SCRUB) {
3761 			fmt = gettext("scrub repaired %s in %lluh%um with "
3762 			    "%llu errors on %s");
3763 		} else if (ps->pss_func == POOL_SCAN_RESILVER) {
3764 			fmt = gettext("resilvered %s in %lluh%um with "
3765 			    "%llu errors on %s");
3766 		}
3767 		/* LINTED */
3768 		(void) printf(fmt, processed_buf,
3769 		    (u_longlong_t)(minutes_taken / 60),
3770 		    (uint_t)(minutes_taken % 60),
3771 		    (u_longlong_t)ps->pss_errors,
3772 		    ctime((time_t *)&end));
3773 		return;
3774 	} else if (ps->pss_state == DSS_CANCELED) {
3775 		if (ps->pss_func == POOL_SCAN_SCRUB) {
3776 			(void) printf(gettext("scrub canceled on %s"),
3777 			    ctime(&end));
3778 		} else if (ps->pss_func == POOL_SCAN_RESILVER) {
3779 			(void) printf(gettext("resilver canceled on %s"),
3780 			    ctime(&end));
3781 		}
3782 		return;
3783 	}
3784 
3785 	assert(ps->pss_state == DSS_SCANNING);
3786 
3787 	/*
3788 	 * Scan is in progress.
3789 	 */
3790 	if (ps->pss_func == POOL_SCAN_SCRUB) {
3791 		(void) printf(gettext("scrub in progress since %s"),
3792 		    ctime(&start));
3793 	} else if (ps->pss_func == POOL_SCAN_RESILVER) {
3794 		(void) printf(gettext("resilver in progress since %s"),
3795 		    ctime(&start));
3796 	}
3797 
3798 	examined = ps->pss_examined ? ps->pss_examined : 1;
3799 	total = ps->pss_to_examine;
3800 	fraction_done = (double)examined / total;
3801 
3802 	/* elapsed time for this pass */
3803 	elapsed = time(NULL) - ps->pss_pass_start;
3804 	elapsed = elapsed ? elapsed : 1;
3805 	pass_exam = ps->pss_pass_exam ? ps->pss_pass_exam : 1;
3806 	rate = pass_exam / elapsed;
3807 	rate = rate ? rate : 1;
3808 	mins_left = ((total - examined) / rate) / 60;
3809 	hours_left = mins_left / 60;
3810 
3811 	zfs_nicenum(examined, examined_buf, sizeof (examined_buf));
3812 	zfs_nicenum(total, total_buf, sizeof (total_buf));
3813 	zfs_nicenum(rate, rate_buf, sizeof (rate_buf));
3814 
3815 	/*
3816 	 * do not print estimated time if hours_left is more than 30 days
3817 	 */
3818 	(void) printf(gettext("    %s scanned out of %s at %s/s"),
3819 	    examined_buf, total_buf, rate_buf);
3820 	if (hours_left < (30 * 24)) {
3821 		(void) printf(gettext(", %lluh%um to go\n"),
3822 		    (u_longlong_t)hours_left, (uint_t)(mins_left % 60));
3823 	} else {
3824 		(void) printf(gettext(
3825 		    ", (scan is slow, no estimated time)\n"));
3826 	}
3827 
3828 	if (ps->pss_func == POOL_SCAN_RESILVER) {
3829 		(void) printf(gettext("    %s resilvered, %.2f%% done\n"),
3830 		    processed_buf, 100 * fraction_done);
3831 	} else if (ps->pss_func == POOL_SCAN_SCRUB) {
3832 		(void) printf(gettext("    %s repaired, %.2f%% done\n"),
3833 		    processed_buf, 100 * fraction_done);
3834 	}
3835 }
3836 
3837 static void
print_error_log(zpool_handle_t * zhp)3838 print_error_log(zpool_handle_t *zhp)
3839 {
3840 	nvlist_t *nverrlist = NULL;
3841 	nvpair_t *elem;
3842 	char *pathname;
3843 	size_t len = MAXPATHLEN * 2;
3844 
3845 	if (zpool_get_errlog(zhp, &nverrlist) != 0) {
3846 		(void) printf("errors: List of errors unavailable "
3847 		    "(insufficient privileges)\n");
3848 		return;
3849 	}
3850 
3851 	(void) printf("errors: Permanent errors have been "
3852 	    "detected in the following files:\n\n");
3853 
3854 	pathname = safe_malloc(len);
3855 	elem = NULL;
3856 	while ((elem = nvlist_next_nvpair(nverrlist, elem)) != NULL) {
3857 		nvlist_t *nv;
3858 		uint64_t dsobj, obj;
3859 
3860 		verify(nvpair_value_nvlist(elem, &nv) == 0);
3861 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_DATASET,
3862 		    &dsobj) == 0);
3863 		verify(nvlist_lookup_uint64(nv, ZPOOL_ERR_OBJECT,
3864 		    &obj) == 0);
3865 		zpool_obj_to_path(zhp, dsobj, obj, pathname, len);
3866 		(void) printf("%7s %s\n", "", pathname);
3867 	}
3868 	free(pathname);
3869 	nvlist_free(nverrlist);
3870 }
3871 
3872 static void
print_spares(zpool_handle_t * zhp,nvlist_t ** spares,uint_t nspares,int namewidth)3873 print_spares(zpool_handle_t *zhp, nvlist_t **spares, uint_t nspares,
3874     int namewidth)
3875 {
3876 	uint_t i;
3877 	char *name;
3878 
3879 	if (nspares == 0)
3880 		return;
3881 
3882 	(void) printf(gettext("\tspares\n"));
3883 
3884 	for (i = 0; i < nspares; i++) {
3885 		name = zpool_vdev_name(g_zfs, zhp, spares[i], B_FALSE);
3886 		print_status_config(zhp, name, spares[i],
3887 		    namewidth, 2, B_TRUE);
3888 		free(name);
3889 	}
3890 }
3891 
3892 static void
print_l2cache(zpool_handle_t * zhp,nvlist_t ** l2cache,uint_t nl2cache,int namewidth)3893 print_l2cache(zpool_handle_t *zhp, nvlist_t **l2cache, uint_t nl2cache,
3894     int namewidth)
3895 {
3896 	uint_t i;
3897 	char *name;
3898 
3899 	if (nl2cache == 0)
3900 		return;
3901 
3902 	(void) printf(gettext("\tcache\n"));
3903 
3904 	for (i = 0; i < nl2cache; i++) {
3905 		name = zpool_vdev_name(g_zfs, zhp, l2cache[i], B_FALSE);
3906 		print_status_config(zhp, name, l2cache[i],
3907 		    namewidth, 2, B_FALSE);
3908 		free(name);
3909 	}
3910 }
3911 
3912 static void
print_dedup_stats(nvlist_t * config)3913 print_dedup_stats(nvlist_t *config)
3914 {
3915 	ddt_histogram_t *ddh;
3916 	ddt_stat_t *dds;
3917 	ddt_object_t *ddo;
3918 	uint_t c;
3919 
3920 	/*
3921 	 * If the pool was faulted then we may not have been able to
3922 	 * obtain the config. Otherwise, if we have anything in the dedup
3923 	 * table continue processing the stats.
3924 	 */
3925 	if (nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_OBJ_STATS,
3926 	    (uint64_t **)&ddo, &c) != 0)
3927 		return;
3928 
3929 	(void) printf("\n");
3930 	(void) printf(gettext(" dedup: "));
3931 	if (ddo->ddo_count == 0) {
3932 		(void) printf(gettext("no DDT entries\n"));
3933 		return;
3934 	}
3935 
3936 	(void) printf("DDT entries %llu, size %llu on disk, %llu in core\n",
3937 	    (u_longlong_t)ddo->ddo_count,
3938 	    (u_longlong_t)ddo->ddo_dspace,
3939 	    (u_longlong_t)ddo->ddo_mspace);
3940 
3941 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_STATS,
3942 	    (uint64_t **)&dds, &c) == 0);
3943 	verify(nvlist_lookup_uint64_array(config, ZPOOL_CONFIG_DDT_HISTOGRAM,
3944 	    (uint64_t **)&ddh, &c) == 0);
3945 	zpool_dump_ddt(dds, ddh);
3946 }
3947 
3948 /*
3949  * Display a summary of pool status.  Displays a summary such as:
3950  *
3951  *        pool: tank
3952  *	status: DEGRADED
3953  *	reason: One or more devices ...
3954  *         see: http://illumos.org/msg/ZFS-xxxx-01
3955  *	config:
3956  *		mirror		DEGRADED
3957  *                c1t0d0	OK
3958  *                c2t0d0	UNAVAIL
3959  *
3960  * When given the '-v' option, we print out the complete config.  If the '-e'
3961  * option is specified, then we print out error rate information as well.
3962  */
3963 int
status_callback(zpool_handle_t * zhp,void * data)3964 status_callback(zpool_handle_t *zhp, void *data)
3965 {
3966 	status_cbdata_t *cbp = data;
3967 	nvlist_t *config, *nvroot;
3968 	char *msgid;
3969 	int reason;
3970 	const char *health;
3971 	uint_t c;
3972 	vdev_stat_t *vs;
3973 
3974 	config = zpool_get_config(zhp, NULL);
3975 	reason = zpool_get_status(zhp, &msgid);
3976 
3977 	cbp->cb_count++;
3978 
3979 	/*
3980 	 * If we were given 'zpool status -x', only report those pools with
3981 	 * problems.
3982 	 */
3983 	if (cbp->cb_explain &&
3984 	    (reason == ZPOOL_STATUS_OK ||
3985 	    reason == ZPOOL_STATUS_VERSION_OLDER ||
3986 	    reason == ZPOOL_STATUS_FEAT_DISABLED)) {
3987 		if (!cbp->cb_allpools) {
3988 			(void) printf(gettext("pool '%s' is healthy\n"),
3989 			    zpool_get_name(zhp));
3990 			if (cbp->cb_first)
3991 				cbp->cb_first = B_FALSE;
3992 		}
3993 		return (0);
3994 	}
3995 
3996 	if (cbp->cb_first)
3997 		cbp->cb_first = B_FALSE;
3998 	else
3999 		(void) printf("\n");
4000 
4001 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4002 	    &nvroot) == 0);
4003 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
4004 	    (uint64_t **)&vs, &c) == 0);
4005 	health = zpool_state_to_name(vs->vs_state, vs->vs_aux);
4006 
4007 	(void) printf(gettext("  pool: %s\n"), zpool_get_name(zhp));
4008 	(void) printf(gettext(" state: %s\n"), health);
4009 
4010 	switch (reason) {
4011 	case ZPOOL_STATUS_MISSING_DEV_R:
4012 		(void) printf(gettext("status: One or more devices could not "
4013 		    "be opened.  Sufficient replicas exist for\n\tthe pool to "
4014 		    "continue functioning in a degraded state.\n"));
4015 		(void) printf(gettext("action: Attach the missing device and "
4016 		    "online it using 'zpool online'.\n"));
4017 		break;
4018 
4019 	case ZPOOL_STATUS_MISSING_DEV_NR:
4020 		(void) printf(gettext("status: One or more devices could not "
4021 		    "be opened.  There are insufficient\n\treplicas for the "
4022 		    "pool to continue functioning.\n"));
4023 		(void) printf(gettext("action: Attach the missing device and "
4024 		    "online it using 'zpool online'.\n"));
4025 		break;
4026 
4027 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
4028 		(void) printf(gettext("status: One or more devices could not "
4029 		    "be used because the label is missing or\n\tinvalid.  "
4030 		    "Sufficient replicas exist for the pool to continue\n\t"
4031 		    "functioning in a degraded state.\n"));
4032 		(void) printf(gettext("action: Replace the device using "
4033 		    "'zpool replace'.\n"));
4034 		break;
4035 
4036 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
4037 		(void) printf(gettext("status: One or more devices could not "
4038 		    "be used because the label is missing \n\tor invalid.  "
4039 		    "There are insufficient replicas for the pool to "
4040 		    "continue\n\tfunctioning.\n"));
4041 		zpool_explain_recover(zpool_get_handle(zhp),
4042 		    zpool_get_name(zhp), reason, config);
4043 		break;
4044 
4045 	case ZPOOL_STATUS_FAILING_DEV:
4046 		(void) printf(gettext("status: One or more devices has "
4047 		    "experienced an unrecoverable error.  An\n\tattempt was "
4048 		    "made to correct the error.  Applications are "
4049 		    "unaffected.\n"));
4050 		(void) printf(gettext("action: Determine if the device needs "
4051 		    "to be replaced, and clear the errors\n\tusing "
4052 		    "'zpool clear' or replace the device with 'zpool "
4053 		    "replace'.\n"));
4054 		break;
4055 
4056 	case ZPOOL_STATUS_OFFLINE_DEV:
4057 		(void) printf(gettext("status: One or more devices has "
4058 		    "been taken offline by the administrator.\n\tSufficient "
4059 		    "replicas exist for the pool to continue functioning in "
4060 		    "a\n\tdegraded state.\n"));
4061 		(void) printf(gettext("action: Online the device using "
4062 		    "'zpool online' or replace the device with\n\t'zpool "
4063 		    "replace'.\n"));
4064 		break;
4065 
4066 	case ZPOOL_STATUS_REMOVED_DEV:
4067 		(void) printf(gettext("status: One or more devices has "
4068 		    "been removed by the administrator.\n\tSufficient "
4069 		    "replicas exist for the pool to continue functioning in "
4070 		    "a\n\tdegraded state.\n"));
4071 		(void) printf(gettext("action: Online the device using "
4072 		    "'zpool online' or replace the device with\n\t'zpool "
4073 		    "replace'.\n"));
4074 		break;
4075 
4076 	case ZPOOL_STATUS_RESILVERING:
4077 		(void) printf(gettext("status: One or more devices is "
4078 		    "currently being resilvered.  The pool will\n\tcontinue "
4079 		    "to function, possibly in a degraded state.\n"));
4080 		(void) printf(gettext("action: Wait for the resilver to "
4081 		    "complete.\n"));
4082 		break;
4083 
4084 	case ZPOOL_STATUS_CORRUPT_DATA:
4085 		(void) printf(gettext("status: One or more devices has "
4086 		    "experienced an error resulting in data\n\tcorruption.  "
4087 		    "Applications may be affected.\n"));
4088 		(void) printf(gettext("action: Restore the file in question "
4089 		    "if possible.  Otherwise restore the\n\tentire pool from "
4090 		    "backup.\n"));
4091 		break;
4092 
4093 	case ZPOOL_STATUS_CORRUPT_POOL:
4094 		(void) printf(gettext("status: The pool metadata is corrupted "
4095 		    "and the pool cannot be opened.\n"));
4096 		zpool_explain_recover(zpool_get_handle(zhp),
4097 		    zpool_get_name(zhp), reason, config);
4098 		break;
4099 
4100 	case ZPOOL_STATUS_VERSION_OLDER:
4101 		(void) printf(gettext("status: The pool is formatted using a "
4102 		    "legacy on-disk format.  The pool can\n\tstill be used, "
4103 		    "but some features are unavailable.\n"));
4104 		(void) printf(gettext("action: Upgrade the pool using 'zpool "
4105 		    "upgrade'.  Once this is done, the\n\tpool will no longer "
4106 		    "be accessible on software that does not support feature\n"
4107 		    "\tflags.\n"));
4108 		break;
4109 
4110 	case ZPOOL_STATUS_VERSION_NEWER:
4111 		(void) printf(gettext("status: The pool has been upgraded to a "
4112 		    "newer, incompatible on-disk version.\n\tThe pool cannot "
4113 		    "be accessed on this system.\n"));
4114 		(void) printf(gettext("action: Access the pool from a system "
4115 		    "running more recent software, or\n\trestore the pool from "
4116 		    "backup.\n"));
4117 		break;
4118 
4119 	case ZPOOL_STATUS_FEAT_DISABLED:
4120 		(void) printf(gettext("status: Some supported features are not "
4121 		    "enabled on the pool. The pool can\n\tstill be used, but "
4122 		    "some features are unavailable.\n"));
4123 		(void) printf(gettext("action: Enable all features using "
4124 		    "'zpool upgrade'. Once this is done,\n\tthe pool may no "
4125 		    "longer be accessible by software that does not support\n\t"
4126 		    "the features. See zpool-features(5) for details.\n"));
4127 		break;
4128 
4129 	case ZPOOL_STATUS_UNSUP_FEAT_READ:
4130 		(void) printf(gettext("status: The pool cannot be accessed on "
4131 		    "this system because it uses the\n\tfollowing feature(s) "
4132 		    "not supported on this system:\n"));
4133 		zpool_print_unsup_feat(config);
4134 		(void) printf("\n");
4135 		(void) printf(gettext("action: Access the pool from a system "
4136 		    "that supports the required feature(s),\n\tor restore the "
4137 		    "pool from backup.\n"));
4138 		break;
4139 
4140 	case ZPOOL_STATUS_UNSUP_FEAT_WRITE:
4141 		(void) printf(gettext("status: The pool can only be accessed "
4142 		    "in read-only mode on this system. It\n\tcannot be "
4143 		    "accessed in read-write mode because it uses the "
4144 		    "following\n\tfeature(s) not supported on this system:\n"));
4145 		zpool_print_unsup_feat(config);
4146 		(void) printf("\n");
4147 		(void) printf(gettext("action: The pool cannot be accessed in "
4148 		    "read-write mode. Import the pool with\n"
4149 		    "\t\"-o readonly=on\", access the pool from a system that "
4150 		    "supports the\n\trequired feature(s), or restore the "
4151 		    "pool from backup.\n"));
4152 		break;
4153 
4154 	case ZPOOL_STATUS_FAULTED_DEV_R:
4155 		(void) printf(gettext("status: One or more devices are "
4156 		    "faulted in response to persistent errors.\n\tSufficient "
4157 		    "replicas exist for the pool to continue functioning "
4158 		    "in a\n\tdegraded state.\n"));
4159 		(void) printf(gettext("action: Replace the faulted device, "
4160 		    "or use 'zpool clear' to mark the device\n\trepaired.\n"));
4161 		break;
4162 
4163 	case ZPOOL_STATUS_FAULTED_DEV_NR:
4164 		(void) printf(gettext("status: One or more devices are "
4165 		    "faulted in response to persistent errors.  There are "
4166 		    "insufficient replicas for the pool to\n\tcontinue "
4167 		    "functioning.\n"));
4168 		(void) printf(gettext("action: Destroy and re-create the pool "
4169 		    "from a backup source.  Manually marking the device\n"
4170 		    "\trepaired using 'zpool clear' may allow some data "
4171 		    "to be recovered.\n"));
4172 		break;
4173 
4174 	case ZPOOL_STATUS_IO_FAILURE_WAIT:
4175 	case ZPOOL_STATUS_IO_FAILURE_CONTINUE:
4176 		(void) printf(gettext("status: One or more devices are "
4177 		    "faulted in response to IO failures.\n"));
4178 		(void) printf(gettext("action: Make sure the affected devices "
4179 		    "are connected, then run 'zpool clear'.\n"));
4180 		break;
4181 
4182 	case ZPOOL_STATUS_BAD_LOG:
4183 		(void) printf(gettext("status: An intent log record "
4184 		    "could not be read.\n"
4185 		    "\tWaiting for adminstrator intervention to fix the "
4186 		    "faulted pool.\n"));
4187 		(void) printf(gettext("action: Either restore the affected "
4188 		    "device(s) and run 'zpool online',\n"
4189 		    "\tor ignore the intent log records by running "
4190 		    "'zpool clear'.\n"));
4191 		break;
4192 
4193 	default:
4194 		/*
4195 		 * The remaining errors can't actually be generated, yet.
4196 		 */
4197 		assert(reason == ZPOOL_STATUS_OK);
4198 	}
4199 
4200 	if (msgid != NULL)
4201 		(void) printf(gettext("   see: http://illumos.org/msg/%s\n"),
4202 		    msgid);
4203 
4204 	if (config != NULL) {
4205 		int namewidth;
4206 		uint64_t nerr;
4207 		nvlist_t **spares, **l2cache;
4208 		uint_t nspares, nl2cache;
4209 		pool_scan_stat_t *ps = NULL;
4210 
4211 		(void) nvlist_lookup_uint64_array(nvroot,
4212 		    ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &c);
4213 		print_scan_status(ps);
4214 
4215 		namewidth = max_width(zhp, nvroot, 0, 0);
4216 		if (namewidth < 10)
4217 			namewidth = 10;
4218 
4219 		(void) printf(gettext("config:\n\n"));
4220 		(void) printf(gettext("\t%-*s  %-8s %5s %5s %5s\n"), namewidth,
4221 		    "NAME", "STATE", "READ", "WRITE", "CKSUM");
4222 		print_status_config(zhp, zpool_get_name(zhp), nvroot,
4223 		    namewidth, 0, B_FALSE);
4224 
4225 		if (num_logs(nvroot) > 0)
4226 			print_logs(zhp, nvroot, namewidth, B_TRUE);
4227 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4228 		    &l2cache, &nl2cache) == 0)
4229 			print_l2cache(zhp, l2cache, nl2cache, namewidth);
4230 
4231 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4232 		    &spares, &nspares) == 0)
4233 			print_spares(zhp, spares, nspares, namewidth);
4234 
4235 		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_ERRCOUNT,
4236 		    &nerr) == 0) {
4237 			nvlist_t *nverrlist = NULL;
4238 
4239 			/*
4240 			 * If the approximate error count is small, get a
4241 			 * precise count by fetching the entire log and
4242 			 * uniquifying the results.
4243 			 */
4244 			if (nerr > 0 && nerr < 100 && !cbp->cb_verbose &&
4245 			    zpool_get_errlog(zhp, &nverrlist) == 0) {
4246 				nvpair_t *elem;
4247 
4248 				elem = NULL;
4249 				nerr = 0;
4250 				while ((elem = nvlist_next_nvpair(nverrlist,
4251 				    elem)) != NULL) {
4252 					nerr++;
4253 				}
4254 			}
4255 			nvlist_free(nverrlist);
4256 
4257 			(void) printf("\n");
4258 
4259 			if (nerr == 0)
4260 				(void) printf(gettext("errors: No known data "
4261 				    "errors\n"));
4262 			else if (!cbp->cb_verbose)
4263 				(void) printf(gettext("errors: %llu data "
4264 				    "errors, use '-v' for a list\n"),
4265 				    (u_longlong_t)nerr);
4266 			else
4267 				print_error_log(zhp);
4268 		}
4269 
4270 		if (cbp->cb_dedup_stats)
4271 			print_dedup_stats(config);
4272 	} else {
4273 		(void) printf(gettext("config: The configuration cannot be "
4274 		    "determined.\n"));
4275 	}
4276 
4277 	return (0);
4278 }
4279 
4280 /*
4281  * zpool status [-vx] [-T d|u] [pool] ... [interval [count]]
4282  *
4283  *	-v	Display complete error logs
4284  *	-x	Display only pools with potential problems
4285  *	-D	Display dedup status (undocumented)
4286  *	-T	Display a timestamp in date(1) or Unix format
4287  *
4288  * Describes the health status of all pools or some subset.
4289  */
4290 int
zpool_do_status(int argc,char ** argv)4291 zpool_do_status(int argc, char **argv)
4292 {
4293 	int c;
4294 	int ret;
4295 	unsigned long interval = 0, count = 0;
4296 	status_cbdata_t cb = { 0 };
4297 
4298 	/* check options */
4299 	while ((c = getopt(argc, argv, "vxDT:")) != -1) {
4300 		switch (c) {
4301 		case 'v':
4302 			cb.cb_verbose = B_TRUE;
4303 			break;
4304 		case 'x':
4305 			cb.cb_explain = B_TRUE;
4306 			break;
4307 		case 'D':
4308 			cb.cb_dedup_stats = B_TRUE;
4309 			break;
4310 		case 'T':
4311 			get_timestamp_arg(*optarg);
4312 			break;
4313 		case '?':
4314 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4315 			    optopt);
4316 			usage(B_FALSE);
4317 		}
4318 	}
4319 
4320 	argc -= optind;
4321 	argv += optind;
4322 
4323 	get_interval_count(&argc, argv, &interval, &count);
4324 
4325 	if (argc == 0)
4326 		cb.cb_allpools = B_TRUE;
4327 
4328 	cb.cb_first = B_TRUE;
4329 
4330 	for (;;) {
4331 		if (timestamp_fmt != NODATE)
4332 			print_timestamp(timestamp_fmt);
4333 
4334 		ret = for_each_pool(argc, argv, B_TRUE, NULL,
4335 		    status_callback, &cb);
4336 
4337 		if (argc == 0 && cb.cb_count == 0)
4338 			(void) printf(gettext("no pools available\n"));
4339 		else if (cb.cb_explain && cb.cb_first && cb.cb_allpools)
4340 			(void) printf(gettext("all pools are healthy\n"));
4341 
4342 		if (ret != 0)
4343 			return (ret);
4344 
4345 		if (interval == 0)
4346 			break;
4347 
4348 		if (count != 0 && --count == 0)
4349 			break;
4350 
4351 		(void) sleep(interval);
4352 	}
4353 
4354 	return (0);
4355 }
4356 
4357 typedef struct upgrade_cbdata {
4358 	int	cb_first;
4359 	int	cb_argc;
4360 	uint64_t cb_version;
4361 	char	**cb_argv;
4362 } upgrade_cbdata_t;
4363 
4364 static int
upgrade_version(zpool_handle_t * zhp,uint64_t version)4365 upgrade_version(zpool_handle_t *zhp, uint64_t version)
4366 {
4367 	int ret;
4368 	nvlist_t *config;
4369 	uint64_t oldversion;
4370 
4371 	config = zpool_get_config(zhp, NULL);
4372 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
4373 	    &oldversion) == 0);
4374 
4375 	assert(SPA_VERSION_IS_SUPPORTED(oldversion));
4376 	assert(oldversion < version);
4377 
4378 	ret = zpool_upgrade(zhp, version);
4379 	if (ret != 0)
4380 		return (ret);
4381 
4382 	if (version >= SPA_VERSION_FEATURES) {
4383 		(void) printf(gettext("Successfully upgraded "
4384 		    "'%s' from version %llu to feature flags.\n"),
4385 		    zpool_get_name(zhp), oldversion);
4386 	} else {
4387 		(void) printf(gettext("Successfully upgraded "
4388 		    "'%s' from version %llu to version %llu.\n"),
4389 		    zpool_get_name(zhp), oldversion, version);
4390 	}
4391 
4392 	return (0);
4393 }
4394 
4395 static int
upgrade_enable_all(zpool_handle_t * zhp,int * countp)4396 upgrade_enable_all(zpool_handle_t *zhp, int *countp)
4397 {
4398 	int i, ret, count;
4399 	boolean_t firstff = B_TRUE;
4400 	nvlist_t *enabled = zpool_get_features(zhp);
4401 
4402 	count = 0;
4403 	for (i = 0; i < SPA_FEATURES; i++) {
4404 		const char *fname = spa_feature_table[i].fi_uname;
4405 		const char *fguid = spa_feature_table[i].fi_guid;
4406 		if (!nvlist_exists(enabled, fguid)) {
4407 			char *propname;
4408 			verify(-1 != asprintf(&propname, "feature@%s", fname));
4409 			ret = zpool_set_prop(zhp, propname,
4410 			    ZFS_FEATURE_ENABLED);
4411 			if (ret != 0) {
4412 				free(propname);
4413 				return (ret);
4414 			}
4415 			count++;
4416 
4417 			if (firstff) {
4418 				(void) printf(gettext("Enabled the "
4419 				    "following features on '%s':\n"),
4420 				    zpool_get_name(zhp));
4421 				firstff = B_FALSE;
4422 			}
4423 			(void) printf(gettext("  %s\n"), fname);
4424 			free(propname);
4425 		}
4426 	}
4427 
4428 	if (countp != NULL)
4429 		*countp = count;
4430 	return (0);
4431 }
4432 
4433 static int
upgrade_cb(zpool_handle_t * zhp,void * arg)4434 upgrade_cb(zpool_handle_t *zhp, void *arg)
4435 {
4436 	upgrade_cbdata_t *cbp = arg;
4437 	nvlist_t *config;
4438 	uint64_t version;
4439 	boolean_t printnl = B_FALSE;
4440 	int ret;
4441 
4442 	config = zpool_get_config(zhp, NULL);
4443 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
4444 	    &version) == 0);
4445 
4446 	assert(SPA_VERSION_IS_SUPPORTED(version));
4447 
4448 	if (version < cbp->cb_version) {
4449 		cbp->cb_first = B_FALSE;
4450 		ret = upgrade_version(zhp, cbp->cb_version);
4451 		if (ret != 0)
4452 			return (ret);
4453 		printnl = B_TRUE;
4454 
4455 		/*
4456 		 * If they did "zpool upgrade -a", then we could
4457 		 * be doing ioctls to different pools.  We need
4458 		 * to log this history once to each pool, and bypass
4459 		 * the normal history logging that happens in main().
4460 		 */
4461 		(void) zpool_log_history(g_zfs, history_str);
4462 		log_history = B_FALSE;
4463 	}
4464 
4465 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
4466 		int count;
4467 		ret = upgrade_enable_all(zhp, &count);
4468 		if (ret != 0)
4469 			return (ret);
4470 
4471 		if (count > 0) {
4472 			cbp->cb_first = B_FALSE;
4473 			printnl = B_TRUE;
4474 		}
4475 	}
4476 
4477 	if (printnl) {
4478 		(void) printf(gettext("\n"));
4479 	}
4480 
4481 	return (0);
4482 }
4483 
4484 static int
upgrade_list_older_cb(zpool_handle_t * zhp,void * arg)4485 upgrade_list_older_cb(zpool_handle_t *zhp, void *arg)
4486 {
4487 	upgrade_cbdata_t *cbp = arg;
4488 	nvlist_t *config;
4489 	uint64_t version;
4490 
4491 	config = zpool_get_config(zhp, NULL);
4492 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
4493 	    &version) == 0);
4494 
4495 	assert(SPA_VERSION_IS_SUPPORTED(version));
4496 
4497 	if (version < SPA_VERSION_FEATURES) {
4498 		if (cbp->cb_first) {
4499 			(void) printf(gettext("The following pools are "
4500 			    "formatted with legacy version numbers and can\n"
4501 			    "be upgraded to use feature flags.  After "
4502 			    "being upgraded, these pools\nwill no "
4503 			    "longer be accessible by software that does not "
4504 			    "support feature\nflags.\n\n"));
4505 			(void) printf(gettext("VER  POOL\n"));
4506 			(void) printf(gettext("---  ------------\n"));
4507 			cbp->cb_first = B_FALSE;
4508 		}
4509 
4510 		(void) printf("%2llu   %s\n", (u_longlong_t)version,
4511 		    zpool_get_name(zhp));
4512 	}
4513 
4514 	return (0);
4515 }
4516 
4517 static int
upgrade_list_disabled_cb(zpool_handle_t * zhp,void * arg)4518 upgrade_list_disabled_cb(zpool_handle_t *zhp, void *arg)
4519 {
4520 	upgrade_cbdata_t *cbp = arg;
4521 	nvlist_t *config;
4522 	uint64_t version;
4523 
4524 	config = zpool_get_config(zhp, NULL);
4525 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
4526 	    &version) == 0);
4527 
4528 	if (version >= SPA_VERSION_FEATURES) {
4529 		int i;
4530 		boolean_t poolfirst = B_TRUE;
4531 		nvlist_t *enabled = zpool_get_features(zhp);
4532 
4533 		for (i = 0; i < SPA_FEATURES; i++) {
4534 			const char *fguid = spa_feature_table[i].fi_guid;
4535 			const char *fname = spa_feature_table[i].fi_uname;
4536 			if (!nvlist_exists(enabled, fguid)) {
4537 				if (cbp->cb_first) {
4538 					(void) printf(gettext("\nSome "
4539 					    "supported features are not "
4540 					    "enabled on the following pools. "
4541 					    "Once a\nfeature is enabled the "
4542 					    "pool may become incompatible with "
4543 					    "software\nthat does not support "
4544 					    "the feature. See "
4545 					    "zpool-features(5) for "
4546 					    "details.\n\n"));
4547 					(void) printf(gettext("POOL  "
4548 					    "FEATURE\n"));
4549 					(void) printf(gettext("------"
4550 					    "---------\n"));
4551 					cbp->cb_first = B_FALSE;
4552 				}
4553 
4554 				if (poolfirst) {
4555 					(void) printf(gettext("%s\n"),
4556 					    zpool_get_name(zhp));
4557 					poolfirst = B_FALSE;
4558 				}
4559 
4560 				(void) printf(gettext("      %s\n"), fname);
4561 			}
4562 		}
4563 	}
4564 
4565 	return (0);
4566 }
4567 
4568 /* ARGSUSED */
4569 static int
upgrade_one(zpool_handle_t * zhp,void * data)4570 upgrade_one(zpool_handle_t *zhp, void *data)
4571 {
4572 	boolean_t printnl = B_FALSE;
4573 	upgrade_cbdata_t *cbp = data;
4574 	uint64_t cur_version;
4575 	int ret;
4576 
4577 	if (strcmp("log", zpool_get_name(zhp)) == 0) {
4578 		(void) printf(gettext("'log' is now a reserved word\n"
4579 		    "Pool 'log' must be renamed using export and import"
4580 		    " to upgrade.\n"));
4581 		return (1);
4582 	}
4583 
4584 	cur_version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
4585 	if (cur_version > cbp->cb_version) {
4586 		(void) printf(gettext("Pool '%s' is already formatted "
4587 		    "using more current version '%llu'.\n\n"),
4588 		    zpool_get_name(zhp), cur_version);
4589 		return (0);
4590 	}
4591 
4592 	if (cbp->cb_version != SPA_VERSION && cur_version == cbp->cb_version) {
4593 		(void) printf(gettext("Pool '%s' is already formatted "
4594 		    "using version %llu.\n\n"), zpool_get_name(zhp),
4595 		    cbp->cb_version);
4596 		return (0);
4597 	}
4598 
4599 	if (cur_version != cbp->cb_version) {
4600 		printnl = B_TRUE;
4601 		ret = upgrade_version(zhp, cbp->cb_version);
4602 		if (ret != 0)
4603 			return (ret);
4604 	}
4605 
4606 	if (cbp->cb_version >= SPA_VERSION_FEATURES) {
4607 		int count = 0;
4608 		ret = upgrade_enable_all(zhp, &count);
4609 		if (ret != 0)
4610 			return (ret);
4611 
4612 		if (count != 0) {
4613 			printnl = B_TRUE;
4614 		} else if (cur_version == SPA_VERSION) {
4615 			(void) printf(gettext("Pool '%s' already has all "
4616 			    "supported features enabled.\n"),
4617 			    zpool_get_name(zhp));
4618 		}
4619 	}
4620 
4621 	if (printnl) {
4622 		(void) printf(gettext("\n"));
4623 	}
4624 
4625 	return (0);
4626 }
4627 
4628 /*
4629  * zpool upgrade
4630  * zpool upgrade -v
4631  * zpool upgrade [-V version] <-a | pool ...>
4632  *
4633  * With no arguments, display downrev'd ZFS pool available for upgrade.
4634  * Individual pools can be upgraded by specifying the pool, and '-a' will
4635  * upgrade all pools.
4636  */
4637 int
zpool_do_upgrade(int argc,char ** argv)4638 zpool_do_upgrade(int argc, char **argv)
4639 {
4640 	int c;
4641 	upgrade_cbdata_t cb = { 0 };
4642 	int ret = 0;
4643 	boolean_t showversions = B_FALSE;
4644 	boolean_t upgradeall = B_FALSE;
4645 	char *end;
4646 
4647 
4648 	/* check options */
4649 	while ((c = getopt(argc, argv, ":avV:")) != -1) {
4650 		switch (c) {
4651 		case 'a':
4652 			upgradeall = B_TRUE;
4653 			break;
4654 		case 'v':
4655 			showversions = B_TRUE;
4656 			break;
4657 		case 'V':
4658 			cb.cb_version = strtoll(optarg, &end, 10);
4659 			if (*end != '\0' ||
4660 			    !SPA_VERSION_IS_SUPPORTED(cb.cb_version)) {
4661 				(void) fprintf(stderr,
4662 				    gettext("invalid version '%s'\n"), optarg);
4663 				usage(B_FALSE);
4664 			}
4665 			break;
4666 		case ':':
4667 			(void) fprintf(stderr, gettext("missing argument for "
4668 			    "'%c' option\n"), optopt);
4669 			usage(B_FALSE);
4670 			break;
4671 		case '?':
4672 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4673 			    optopt);
4674 			usage(B_FALSE);
4675 		}
4676 	}
4677 
4678 	cb.cb_argc = argc;
4679 	cb.cb_argv = argv;
4680 	argc -= optind;
4681 	argv += optind;
4682 
4683 	if (cb.cb_version == 0) {
4684 		cb.cb_version = SPA_VERSION;
4685 	} else if (!upgradeall && argc == 0) {
4686 		(void) fprintf(stderr, gettext("-V option is "
4687 		    "incompatible with other arguments\n"));
4688 		usage(B_FALSE);
4689 	}
4690 
4691 	if (showversions) {
4692 		if (upgradeall || argc != 0) {
4693 			(void) fprintf(stderr, gettext("-v option is "
4694 			    "incompatible with other arguments\n"));
4695 			usage(B_FALSE);
4696 		}
4697 	} else if (upgradeall) {
4698 		if (argc != 0) {
4699 			(void) fprintf(stderr, gettext("-a option should not "
4700 			    "be used along with a pool name\n"));
4701 			usage(B_FALSE);
4702 		}
4703 	}
4704 
4705 	(void) printf(gettext("This system supports ZFS pool feature "
4706 	    "flags.\n\n"));
4707 	if (showversions) {
4708 		int i;
4709 
4710 		(void) printf(gettext("The following features are "
4711 		    "supported:\n\n"));
4712 		(void) printf(gettext("FEAT DESCRIPTION\n"));
4713 		(void) printf("----------------------------------------------"
4714 		    "---------------\n");
4715 		for (i = 0; i < SPA_FEATURES; i++) {
4716 			zfeature_info_t *fi = &spa_feature_table[i];
4717 			const char *ro =
4718 			    (fi->fi_flags & ZFEATURE_FLAG_READONLY_COMPAT) ?
4719 			    " (read-only compatible)" : "";
4720 
4721 			(void) printf("%-37s%s\n", fi->fi_uname, ro);
4722 			(void) printf("     %s\n", fi->fi_desc);
4723 		}
4724 		(void) printf("\n");
4725 
4726 		(void) printf(gettext("The following legacy versions are also "
4727 		    "supported:\n\n"));
4728 		(void) printf(gettext("VER  DESCRIPTION\n"));
4729 		(void) printf("---  -----------------------------------------"
4730 		    "---------------\n");
4731 		(void) printf(gettext(" 1   Initial ZFS version\n"));
4732 		(void) printf(gettext(" 2   Ditto blocks "
4733 		    "(replicated metadata)\n"));
4734 		(void) printf(gettext(" 3   Hot spares and double parity "
4735 		    "RAID-Z\n"));
4736 		(void) printf(gettext(" 4   zpool history\n"));
4737 		(void) printf(gettext(" 5   Compression using the gzip "
4738 		    "algorithm\n"));
4739 		(void) printf(gettext(" 6   bootfs pool property\n"));
4740 		(void) printf(gettext(" 7   Separate intent log devices\n"));
4741 		(void) printf(gettext(" 8   Delegated administration\n"));
4742 		(void) printf(gettext(" 9   refquota and refreservation "
4743 		    "properties\n"));
4744 		(void) printf(gettext(" 10  Cache devices\n"));
4745 		(void) printf(gettext(" 11  Improved scrub performance\n"));
4746 		(void) printf(gettext(" 12  Snapshot properties\n"));
4747 		(void) printf(gettext(" 13  snapused property\n"));
4748 		(void) printf(gettext(" 14  passthrough-x aclinherit\n"));
4749 		(void) printf(gettext(" 15  user/group space accounting\n"));
4750 		(void) printf(gettext(" 16  stmf property support\n"));
4751 		(void) printf(gettext(" 17  Triple-parity RAID-Z\n"));
4752 		(void) printf(gettext(" 18  Snapshot user holds\n"));
4753 		(void) printf(gettext(" 19  Log device removal\n"));
4754 		(void) printf(gettext(" 20  Compression using zle "
4755 		    "(zero-length encoding)\n"));
4756 		(void) printf(gettext(" 21  Deduplication\n"));
4757 		(void) printf(gettext(" 22  Received properties\n"));
4758 		(void) printf(gettext(" 23  Slim ZIL\n"));
4759 		(void) printf(gettext(" 24  System attributes\n"));
4760 		(void) printf(gettext(" 25  Improved scrub stats\n"));
4761 		(void) printf(gettext(" 26  Improved snapshot deletion "
4762 		    "performance\n"));
4763 		(void) printf(gettext(" 27  Improved snapshot creation "
4764 		    "performance\n"));
4765 		(void) printf(gettext(" 28  Multiple vdev replacements\n"));
4766 		(void) printf(gettext("\nFor more information on a particular "
4767 		    "version, including supported releases,\n"));
4768 		(void) printf(gettext("see the ZFS Administration Guide.\n\n"));
4769 	} else if (argc == 0 && upgradeall) {
4770 		cb.cb_first = B_TRUE;
4771 		ret = zpool_iter(g_zfs, upgrade_cb, &cb);
4772 		if (ret == 0 && cb.cb_first) {
4773 			if (cb.cb_version == SPA_VERSION) {
4774 				(void) printf(gettext("All pools are already "
4775 				    "formatted using feature flags.\n\n"));
4776 				(void) printf(gettext("Every feature flags "
4777 				    "pool already has all supported features "
4778 				    "enabled.\n"));
4779 			} else {
4780 				(void) printf(gettext("All pools are already "
4781 				    "formatted with version %llu or higher.\n"),
4782 				    cb.cb_version);
4783 			}
4784 		}
4785 	} else if (argc == 0) {
4786 		cb.cb_first = B_TRUE;
4787 		ret = zpool_iter(g_zfs, upgrade_list_older_cb, &cb);
4788 		assert(ret == 0);
4789 
4790 		if (cb.cb_first) {
4791 			(void) printf(gettext("All pools are formatted "
4792 			    "using feature flags.\n\n"));
4793 		} else {
4794 			(void) printf(gettext("\nUse 'zpool upgrade -v' "
4795 			    "for a list of available legacy versions.\n"));
4796 		}
4797 
4798 		cb.cb_first = B_TRUE;
4799 		ret = zpool_iter(g_zfs, upgrade_list_disabled_cb, &cb);
4800 		assert(ret == 0);
4801 
4802 		if (cb.cb_first) {
4803 			(void) printf(gettext("Every feature flags pool has "
4804 			    "all supported features enabled.\n"));
4805 		} else {
4806 			(void) printf(gettext("\n"));
4807 		}
4808 	} else {
4809 		ret = for_each_pool(argc, argv, B_FALSE, NULL,
4810 		    upgrade_one, &cb);
4811 	}
4812 
4813 	return (ret);
4814 }
4815 
4816 typedef struct hist_cbdata {
4817 	boolean_t first;
4818 	boolean_t longfmt;
4819 	boolean_t internal;
4820 } hist_cbdata_t;
4821 
4822 /*
4823  * Print out the command history for a specific pool.
4824  */
4825 static int
get_history_one(zpool_handle_t * zhp,void * data)4826 get_history_one(zpool_handle_t *zhp, void *data)
4827 {
4828 	nvlist_t *nvhis;
4829 	nvlist_t **records;
4830 	uint_t numrecords;
4831 	int ret, i;
4832 	hist_cbdata_t *cb = (hist_cbdata_t *)data;
4833 
4834 	cb->first = B_FALSE;
4835 
4836 	(void) printf(gettext("History for '%s':\n"), zpool_get_name(zhp));
4837 
4838 	if ((ret = zpool_get_history(zhp, &nvhis)) != 0)
4839 		return (ret);
4840 
4841 	verify(nvlist_lookup_nvlist_array(nvhis, ZPOOL_HIST_RECORD,
4842 	    &records, &numrecords) == 0);
4843 	for (i = 0; i < numrecords; i++) {
4844 		nvlist_t *rec = records[i];
4845 		char tbuf[30] = "";
4846 
4847 		if (nvlist_exists(rec, ZPOOL_HIST_TIME)) {
4848 			time_t tsec;
4849 			struct tm t;
4850 
4851 			tsec = fnvlist_lookup_uint64(records[i],
4852 			    ZPOOL_HIST_TIME);
4853 			(void) localtime_r(&tsec, &t);
4854 			(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
4855 		}
4856 
4857 		if (nvlist_exists(rec, ZPOOL_HIST_CMD)) {
4858 			(void) printf("%s %s", tbuf,
4859 			    fnvlist_lookup_string(rec, ZPOOL_HIST_CMD));
4860 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_EVENT)) {
4861 			int ievent =
4862 			    fnvlist_lookup_uint64(rec, ZPOOL_HIST_INT_EVENT);
4863 			if (!cb->internal)
4864 				continue;
4865 			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS) {
4866 				(void) printf("%s unrecognized record:\n",
4867 				    tbuf);
4868 				dump_nvlist(rec, 4);
4869 				continue;
4870 			}
4871 			(void) printf("%s [internal %s txg:%lld] %s", tbuf,
4872 			    zfs_history_event_names[ievent],
4873 			    fnvlist_lookup_uint64(rec, ZPOOL_HIST_TXG),
4874 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_STR));
4875 		} else if (nvlist_exists(rec, ZPOOL_HIST_INT_NAME)) {
4876 			if (!cb->internal)
4877 				continue;
4878 			(void) printf("%s [txg:%lld] %s", tbuf,
4879 			    fnvlist_lookup_uint64(rec, ZPOOL_HIST_TXG),
4880 			    fnvlist_lookup_string(rec, ZPOOL_HIST_INT_NAME));
4881 			if (nvlist_exists(rec, ZPOOL_HIST_DSNAME)) {
4882 				(void) printf(" %s (%llu)",
4883 				    fnvlist_lookup_string(rec,
4884 				    ZPOOL_HIST_DSNAME),
4885 				    fnvlist_lookup_uint64(rec,
4886 				    ZPOOL_HIST_DSID));
4887 			}
4888 			(void) printf(" %s", fnvlist_lookup_string(rec,
4889 			    ZPOOL_HIST_INT_STR));
4890 		} else if (nvlist_exists(rec, ZPOOL_HIST_IOCTL)) {
4891 			if (!cb->internal)
4892 				continue;
4893 			(void) printf("%s ioctl %s\n", tbuf,
4894 			    fnvlist_lookup_string(rec, ZPOOL_HIST_IOCTL));
4895 			if (nvlist_exists(rec, ZPOOL_HIST_INPUT_NVL)) {
4896 				(void) printf("    input:\n");
4897 				dump_nvlist(fnvlist_lookup_nvlist(rec,
4898 				    ZPOOL_HIST_INPUT_NVL), 8);
4899 			}
4900 			if (nvlist_exists(rec, ZPOOL_HIST_OUTPUT_NVL)) {
4901 				(void) printf("    output:\n");
4902 				dump_nvlist(fnvlist_lookup_nvlist(rec,
4903 				    ZPOOL_HIST_OUTPUT_NVL), 8);
4904 			}
4905 		} else {
4906 			if (!cb->internal)
4907 				continue;
4908 			(void) printf("%s unrecognized record:\n", tbuf);
4909 			dump_nvlist(rec, 4);
4910 		}
4911 
4912 		if (!cb->longfmt) {
4913 			(void) printf("\n");
4914 			continue;
4915 		}
4916 		(void) printf(" [");
4917 		if (nvlist_exists(rec, ZPOOL_HIST_WHO)) {
4918 			uid_t who = fnvlist_lookup_uint64(rec, ZPOOL_HIST_WHO);
4919 			struct passwd *pwd = getpwuid(who);
4920 			(void) printf("user %d ", (int)who);
4921 			if (pwd != NULL)
4922 				(void) printf("(%s) ", pwd->pw_name);
4923 		}
4924 		if (nvlist_exists(rec, ZPOOL_HIST_HOST)) {
4925 			(void) printf("on %s",
4926 			    fnvlist_lookup_string(rec, ZPOOL_HIST_HOST));
4927 		}
4928 		if (nvlist_exists(rec, ZPOOL_HIST_ZONE)) {
4929 			(void) printf(":%s",
4930 			    fnvlist_lookup_string(rec, ZPOOL_HIST_ZONE));
4931 		}
4932 		(void) printf("]");
4933 		(void) printf("\n");
4934 	}
4935 	(void) printf("\n");
4936 	nvlist_free(nvhis);
4937 
4938 	return (ret);
4939 }
4940 
4941 /*
4942  * zpool history <pool>
4943  *
4944  * Displays the history of commands that modified pools.
4945  */
4946 int
zpool_do_history(int argc,char ** argv)4947 zpool_do_history(int argc, char **argv)
4948 {
4949 	hist_cbdata_t cbdata = { 0 };
4950 	int ret;
4951 	int c;
4952 
4953 	cbdata.first = B_TRUE;
4954 	/* check options */
4955 	while ((c = getopt(argc, argv, "li")) != -1) {
4956 		switch (c) {
4957 		case 'l':
4958 			cbdata.longfmt = B_TRUE;
4959 			break;
4960 		case 'i':
4961 			cbdata.internal = B_TRUE;
4962 			break;
4963 		case '?':
4964 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4965 			    optopt);
4966 			usage(B_FALSE);
4967 		}
4968 	}
4969 	argc -= optind;
4970 	argv += optind;
4971 
4972 	ret = for_each_pool(argc, argv, B_FALSE,  NULL, get_history_one,
4973 	    &cbdata);
4974 
4975 	if (argc == 0 && cbdata.first == B_TRUE) {
4976 		(void) printf(gettext("no pools available\n"));
4977 		return (0);
4978 	}
4979 
4980 	return (ret);
4981 }
4982 
4983 static int
get_callback(zpool_handle_t * zhp,void * data)4984 get_callback(zpool_handle_t *zhp, void *data)
4985 {
4986 	zprop_get_cbdata_t *cbp = (zprop_get_cbdata_t *)data;
4987 	char value[MAXNAMELEN];
4988 	zprop_source_t srctype;
4989 	zprop_list_t *pl;
4990 
4991 	for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
4992 
4993 		/*
4994 		 * Skip the special fake placeholder. This will also skip
4995 		 * over the name property when 'all' is specified.
4996 		 */
4997 		if (pl->pl_prop == ZPOOL_PROP_NAME &&
4998 		    pl == cbp->cb_proplist)
4999 			continue;
5000 
5001 		if (pl->pl_prop == ZPROP_INVAL &&
5002 		    (zpool_prop_feature(pl->pl_user_prop) ||
5003 		    zpool_prop_unsupported(pl->pl_user_prop))) {
5004 			srctype = ZPROP_SRC_LOCAL;
5005 
5006 			if (zpool_prop_get_feature(zhp, pl->pl_user_prop,
5007 			    value, sizeof (value)) == 0) {
5008 				zprop_print_one_property(zpool_get_name(zhp),
5009 				    cbp, pl->pl_user_prop, value, srctype,
5010 				    NULL, NULL);
5011 			}
5012 		} else {
5013 			if (zpool_get_prop(zhp, pl->pl_prop, value,
5014 			    sizeof (value), &srctype, cbp->cb_literal) != 0)
5015 				continue;
5016 
5017 			zprop_print_one_property(zpool_get_name(zhp), cbp,
5018 			    zpool_prop_to_name(pl->pl_prop), value, srctype,
5019 			    NULL, NULL);
5020 		}
5021 	}
5022 	return (0);
5023 }
5024 
5025 /*
5026  * zpool get [-Hp] [-o "all" | field[,...]] <"all" | property[,...]> <pool> ...
5027  *
5028  *	-H	Scripted mode.  Don't display headers, and separate properties
5029  *		by a single tab.
5030  *	-o	List of columns to display.  Defaults to
5031  *		"name,property,value,source".
5032  * 	-p	Diplay values in parsable (exact) format.
5033  *
5034  * Get properties of pools in the system. Output space statistics
5035  * for each one as well as other attributes.
5036  */
5037 int
zpool_do_get(int argc,char ** argv)5038 zpool_do_get(int argc, char **argv)
5039 {
5040 	zprop_get_cbdata_t cb = { 0 };
5041 	zprop_list_t fake_name = { 0 };
5042 	int ret;
5043 	int c, i;
5044 	char *value;
5045 
5046 	cb.cb_first = B_TRUE;
5047 
5048 	/*
5049 	 * Set up default columns and sources.
5050 	 */
5051 	cb.cb_sources = ZPROP_SRC_ALL;
5052 	cb.cb_columns[0] = GET_COL_NAME;
5053 	cb.cb_columns[1] = GET_COL_PROPERTY;
5054 	cb.cb_columns[2] = GET_COL_VALUE;
5055 	cb.cb_columns[3] = GET_COL_SOURCE;
5056 	cb.cb_type = ZFS_TYPE_POOL;
5057 
5058 	/* check options */
5059 	while ((c = getopt(argc, argv, ":Hpo:")) != -1) {
5060 		switch (c) {
5061 		case 'p':
5062 			cb.cb_literal = B_TRUE;
5063 			break;
5064 		case 'H':
5065 			cb.cb_scripted = B_TRUE;
5066 			break;
5067 		case 'o':
5068 			bzero(&cb.cb_columns, sizeof (cb.cb_columns));
5069 			i = 0;
5070 			while (*optarg != '\0') {
5071 				static char *col_subopts[] =
5072 				{ "name", "property", "value", "source",
5073 				"all", NULL };
5074 
5075 				if (i == ZFS_GET_NCOLS) {
5076 					(void) fprintf(stderr, gettext("too "
5077 					"many fields given to -o "
5078 					"option\n"));
5079 					usage(B_FALSE);
5080 				}
5081 
5082 				switch (getsubopt(&optarg, col_subopts,
5083 				    &value)) {
5084 				case 0:
5085 					cb.cb_columns[i++] = GET_COL_NAME;
5086 					break;
5087 				case 1:
5088 					cb.cb_columns[i++] = GET_COL_PROPERTY;
5089 					break;
5090 				case 2:
5091 					cb.cb_columns[i++] = GET_COL_VALUE;
5092 					break;
5093 				case 3:
5094 					cb.cb_columns[i++] = GET_COL_SOURCE;
5095 					break;
5096 				case 4:
5097 					if (i > 0) {
5098 						(void) fprintf(stderr,
5099 						    gettext("\"all\" conflicts "
5100 						    "with specific fields "
5101 						    "given to -o option\n"));
5102 						usage(B_FALSE);
5103 					}
5104 					cb.cb_columns[0] = GET_COL_NAME;
5105 					cb.cb_columns[1] = GET_COL_PROPERTY;
5106 					cb.cb_columns[2] = GET_COL_VALUE;
5107 					cb.cb_columns[3] = GET_COL_SOURCE;
5108 					i = ZFS_GET_NCOLS;
5109 					break;
5110 				default:
5111 					(void) fprintf(stderr,
5112 					    gettext("invalid column name "
5113 					    "'%s'\n"), value);
5114 					usage(B_FALSE);
5115 				}
5116 			}
5117 			break;
5118 		case '?':
5119 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5120 			    optopt);
5121 			usage(B_FALSE);
5122 		}
5123 	}
5124 
5125 	argc -= optind;
5126 	argv += optind;
5127 
5128 	if (argc < 1) {
5129 		(void) fprintf(stderr, gettext("missing property "
5130 		    "argument\n"));
5131 		usage(B_FALSE);
5132 	}
5133 
5134 	if (zprop_get_list(g_zfs, argv[0], &cb.cb_proplist,
5135 	    ZFS_TYPE_POOL) != 0)
5136 		usage(B_FALSE);
5137 
5138 	argc--;
5139 	argv++;
5140 
5141 	if (cb.cb_proplist != NULL) {
5142 		fake_name.pl_prop = ZPOOL_PROP_NAME;
5143 		fake_name.pl_width = strlen(gettext("NAME"));
5144 		fake_name.pl_next = cb.cb_proplist;
5145 		cb.cb_proplist = &fake_name;
5146 	}
5147 
5148 	ret = for_each_pool(argc, argv, B_TRUE, &cb.cb_proplist,
5149 	    get_callback, &cb);
5150 
5151 	if (cb.cb_proplist == &fake_name)
5152 		zprop_free_list(fake_name.pl_next);
5153 	else
5154 		zprop_free_list(cb.cb_proplist);
5155 
5156 	return (ret);
5157 }
5158 
5159 typedef struct set_cbdata {
5160 	char *cb_propname;
5161 	char *cb_value;
5162 	boolean_t cb_any_successful;
5163 } set_cbdata_t;
5164 
5165 int
set_callback(zpool_handle_t * zhp,void * data)5166 set_callback(zpool_handle_t *zhp, void *data)
5167 {
5168 	int error;
5169 	set_cbdata_t *cb = (set_cbdata_t *)data;
5170 
5171 	error = zpool_set_prop(zhp, cb->cb_propname, cb->cb_value);
5172 
5173 	if (!error)
5174 		cb->cb_any_successful = B_TRUE;
5175 
5176 	return (error);
5177 }
5178 
5179 int
zpool_do_set(int argc,char ** argv)5180 zpool_do_set(int argc, char **argv)
5181 {
5182 	set_cbdata_t cb = { 0 };
5183 	int error;
5184 
5185 	if (argc > 1 && argv[1][0] == '-') {
5186 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5187 		    argv[1][1]);
5188 		usage(B_FALSE);
5189 	}
5190 
5191 	if (argc < 2) {
5192 		(void) fprintf(stderr, gettext("missing property=value "
5193 		    "argument\n"));
5194 		usage(B_FALSE);
5195 	}
5196 
5197 	if (argc < 3) {
5198 		(void) fprintf(stderr, gettext("missing pool name\n"));
5199 		usage(B_FALSE);
5200 	}
5201 
5202 	if (argc > 3) {
5203 		(void) fprintf(stderr, gettext("too many pool names\n"));
5204 		usage(B_FALSE);
5205 	}
5206 
5207 	cb.cb_propname = argv[1];
5208 	cb.cb_value = strchr(cb.cb_propname, '=');
5209 	if (cb.cb_value == NULL) {
5210 		(void) fprintf(stderr, gettext("missing value in "
5211 		    "property=value argument\n"));
5212 		usage(B_FALSE);
5213 	}
5214 
5215 	*(cb.cb_value) = '\0';
5216 	cb.cb_value++;
5217 
5218 	error = for_each_pool(argc - 2, argv + 2, B_TRUE, NULL,
5219 	    set_callback, &cb);
5220 
5221 	return (error);
5222 }
5223 
5224 static int
find_command_idx(char * command,int * idx)5225 find_command_idx(char *command, int *idx)
5226 {
5227 	int i;
5228 
5229 	for (i = 0; i < NCOMMAND; i++) {
5230 		if (command_table[i].name == NULL)
5231 			continue;
5232 
5233 		if (strcmp(command, command_table[i].name) == 0) {
5234 			*idx = i;
5235 			return (0);
5236 		}
5237 	}
5238 	return (1);
5239 }
5240 
5241 int
main(int argc,char ** argv)5242 main(int argc, char **argv)
5243 {
5244 	int ret = 0;
5245 	int i;
5246 	char *cmdname;
5247 
5248 	(void) setlocale(LC_ALL, "");
5249 	(void) textdomain(TEXT_DOMAIN);
5250 
5251 	if ((g_zfs = libzfs_init()) == NULL) {
5252 		(void) fprintf(stderr, gettext("internal error: failed to "
5253 		    "initialize ZFS library\n"));
5254 		return (1);
5255 	}
5256 
5257 	libzfs_print_on_error(g_zfs, B_TRUE);
5258 
5259 	opterr = 0;
5260 
5261 	/*
5262 	 * Make sure the user has specified some command.
5263 	 */
5264 	if (argc < 2) {
5265 		(void) fprintf(stderr, gettext("missing command\n"));
5266 		usage(B_FALSE);
5267 	}
5268 
5269 	cmdname = argv[1];
5270 
5271 	/* Log zpool commands to syslog. */
5272 	if (argc > 1) {
5273 		char *fullcmd, *tmp;
5274 		int full_arg_len = 1;
5275 		int arg_len;
5276 
5277 		openlog("zpool", LOG_PID, LOG_DAEMON);
5278 		for (i = 0; i < argc; i++) {
5279 			full_arg_len += strlen(argv[i]) + 1;
5280 		}
5281 		fullcmd = malloc(full_arg_len);
5282 		assert(fullcmd != NULL);
5283 
5284 		tmp = fullcmd;
5285 		for (i = 0; i < argc; i++) {
5286 			arg_len = strlen(argv[i]);
5287 			strncpy(tmp, argv[i], arg_len);
5288 			tmp += arg_len;
5289 			strcpy(tmp, " ");
5290 			++tmp;
5291 		}
5292 		syslog(LOG_INFO, "%s", fullcmd);
5293 		closelog();
5294 		free(fullcmd);
5295 	}
5296 
5297 	/*
5298 	 * Special case '-?'
5299 	 */
5300 	if (strcmp(cmdname, "-?") == 0)
5301 		usage(B_TRUE);
5302 
5303 	zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
5304 
5305 	/*
5306 	 * Run the appropriate command.
5307 	 */
5308 	if (find_command_idx(cmdname, &i) == 0) {
5309 		current_command = &command_table[i];
5310 		ret = command_table[i].func(argc - 1, argv + 1);
5311 	} else if (strchr(cmdname, '=')) {
5312 		verify(find_command_idx("set", &i) == 0);
5313 		current_command = &command_table[i];
5314 		ret = command_table[i].func(argc, argv);
5315 	} else if (strcmp(cmdname, "freeze") == 0 && argc == 3) {
5316 		/*
5317 		 * 'freeze' is a vile debugging abomination, so we treat
5318 		 * it as such.
5319 		 */
5320 		char buf[16384];
5321 		int fd = open(ZFS_DEV, O_RDWR);
5322 		(void) strcpy((void *)buf, argv[2]);
5323 		return (!!ioctl(fd, ZFS_IOC_POOL_FREEZE, buf));
5324 	} else {
5325 		(void) fprintf(stderr, gettext("unrecognized "
5326 		    "command '%s'\n"), cmdname);
5327 		usage(B_FALSE);
5328 	}
5329 
5330 	if (ret == 0 && log_history)
5331 		(void) zpool_log_history(g_zfs, history_str);
5332 
5333 	libzfs_fini(g_zfs);
5334 
5335 	/*
5336 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
5337 	 * for the purposes of running ::findleaks.
5338 	 */
5339 	if (getenv("ZFS_ABORT") != NULL) {
5340 		(void) printf("dumping core by request\n");
5341 		abort();
5342 	}
5343 
5344 	return (ret);
5345 }
5346