xref: /titanic_44/usr/src/cmd/zdb/zdb.c (revision 8339b41da2395f0525c46ceedfeb01961893ec44)
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  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 #include <stdio.h>
26 #include <stdio_ext.h>
27 #include <stdlib.h>
28 #include <ctype.h>
29 #include <sys/zfs_context.h>
30 #include <sys/spa.h>
31 #include <sys/spa_impl.h>
32 #include <sys/dmu.h>
33 #include <sys/zap.h>
34 #include <sys/fs/zfs.h>
35 #include <sys/zfs_znode.h>
36 #include <sys/zfs_sa.h>
37 #include <sys/sa.h>
38 #include <sys/sa_impl.h>
39 #include <sys/vdev.h>
40 #include <sys/vdev_impl.h>
41 #include <sys/metaslab_impl.h>
42 #include <sys/dmu_objset.h>
43 #include <sys/dsl_dir.h>
44 #include <sys/dsl_dataset.h>
45 #include <sys/dsl_pool.h>
46 #include <sys/dbuf.h>
47 #include <sys/zil.h>
48 #include <sys/zil_impl.h>
49 #include <sys/stat.h>
50 #include <sys/resource.h>
51 #include <sys/dmu_traverse.h>
52 #include <sys/zio_checksum.h>
53 #include <sys/zio_compress.h>
54 #include <sys/zfs_fuid.h>
55 #include <sys/arc.h>
56 #include <sys/ddt.h>
57 #undef ZFS_MAXNAMELEN
58 #undef verify
59 #include <libzfs.h>
60 
61 #define	ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ? \
62     zio_compress_table[(idx)].ci_name : "UNKNOWN")
63 #define	ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ? \
64     zio_checksum_table[(idx)].ci_name : "UNKNOWN")
65 #define	ZDB_OT_NAME(idx) ((idx) < DMU_OT_NUMTYPES ? \
66     dmu_ot[(idx)].ot_name : "UNKNOWN")
67 #define	ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) : DMU_OT_NUMTYPES)
68 
69 #ifndef lint
70 extern int zfs_recover;
71 #else
72 int zfs_recover;
73 #endif
74 
75 const char cmdname[] = "zdb";
76 uint8_t dump_opt[256];
77 
78 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
79 
80 extern void dump_intent_log(zilog_t *);
81 uint64_t *zopt_object = NULL;
82 int zopt_objects = 0;
83 libzfs_handle_t *g_zfs;
84 
85 /*
86  * These libumem hooks provide a reasonable set of defaults for the allocator's
87  * debugging facilities.
88  */
89 const char *
90 _umem_debug_init()
91 {
92 	return ("default,verbose"); /* $UMEM_DEBUG setting */
93 }
94 
95 const char *
96 _umem_logging_init(void)
97 {
98 	return ("fail,contents"); /* $UMEM_LOGGING setting */
99 }
100 
101 static void
102 usage(void)
103 {
104 	(void) fprintf(stderr,
105 	    "Usage: %s [-CumdibcsDvhL] poolname [object...]\n"
106 	    "       %s [-div] dataset [object...]\n"
107 	    "       %s -m [-L] poolname [vdev [metaslab...]]\n"
108 	    "       %s -R poolname vdev:offset:size[:flags]\n"
109 	    "       %s -S poolname\n"
110 	    "       %s -l [-u] device\n"
111 	    "       %s -C\n\n",
112 	    cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname);
113 
114 	(void) fprintf(stderr, "    Dataset name must include at least one "
115 	    "separator character '/' or '@'\n");
116 	(void) fprintf(stderr, "    If dataset name is specified, only that "
117 	    "dataset is dumped\n");
118 	(void) fprintf(stderr, "    If object numbers are specified, only "
119 	    "those objects are dumped\n\n");
120 	(void) fprintf(stderr, "    Options to control amount of output:\n");
121 	(void) fprintf(stderr, "        -u uberblock\n");
122 	(void) fprintf(stderr, "        -d dataset(s)\n");
123 	(void) fprintf(stderr, "        -i intent logs\n");
124 	(void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
125 	(void) fprintf(stderr, "        -h pool history\n");
126 	(void) fprintf(stderr, "        -b block statistics\n");
127 	(void) fprintf(stderr, "        -m metaslabs\n");
128 	(void) fprintf(stderr, "        -c checksum all metadata (twice for "
129 	    "all data) blocks\n");
130 	(void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
131 	(void) fprintf(stderr, "        -D dedup statistics\n");
132 	(void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
133 	(void) fprintf(stderr, "        -v verbose (applies to all others)\n");
134 	(void) fprintf(stderr, "        -l dump label contents\n");
135 	(void) fprintf(stderr, "        -L disable leak tracking (do not "
136 	    "load spacemaps)\n");
137 	(void) fprintf(stderr, "        -R read and display block from a "
138 	    "device\n\n");
139 	(void) fprintf(stderr, "    Below options are intended for use "
140 	    "with other options (except -l):\n");
141 	(void) fprintf(stderr, "        -A ignore assertions (-A), enable "
142 	    "panic recovery (-AA) or both (-AAA)\n");
143 	(void) fprintf(stderr, "        -F attempt automatic rewind within "
144 	    "safe range of transaction groups\n");
145 	(void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
146 	    "cachefile\n");
147 	(void) fprintf(stderr, "        -X attempt extreme rewind (does not "
148 	    "work with dataset)\n");
149 	(void) fprintf(stderr, "        -e pool is exported/destroyed/"
150 	    "has altroot/not in a cachefile\n");
151 	(void) fprintf(stderr, "        -p <path> -- use one or more with "
152 	    "-e to specify path to vdev dir\n");
153 	(void) fprintf(stderr, "	-P print numbers parsable\n");
154 	(void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
155 	    "searching for uberblocks\n");
156 	(void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
157 	    "to make only that option verbose\n");
158 	(void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
159 	exit(1);
160 }
161 
162 /*
163  * Called for usage errors that are discovered after a call to spa_open(),
164  * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
165  */
166 
167 static void
168 fatal(const char *fmt, ...)
169 {
170 	va_list ap;
171 
172 	va_start(ap, fmt);
173 	(void) fprintf(stderr, "%s: ", cmdname);
174 	(void) vfprintf(stderr, fmt, ap);
175 	va_end(ap);
176 	(void) fprintf(stderr, "\n");
177 
178 	exit(1);
179 }
180 
181 /* ARGSUSED */
182 static void
183 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
184 {
185 	nvlist_t *nv;
186 	size_t nvsize = *(uint64_t *)data;
187 	char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
188 
189 	VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
190 
191 	VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
192 
193 	umem_free(packed, nvsize);
194 
195 	dump_nvlist(nv, 8);
196 
197 	nvlist_free(nv);
198 }
199 
200 static void
201 zdb_nicenum(uint64_t num, char *buf)
202 {
203 	if (dump_opt['P'])
204 		(void) sprintf(buf, "%llu", (longlong_t)num);
205 	else
206 		nicenum(num, buf);
207 }
208 
209 const char dump_zap_stars[] = "****************************************";
210 const int dump_zap_width = sizeof (dump_zap_stars) - 1;
211 
212 static void
213 dump_zap_histogram(uint64_t histo[ZAP_HISTOGRAM_SIZE])
214 {
215 	int i;
216 	int minidx = ZAP_HISTOGRAM_SIZE - 1;
217 	int maxidx = 0;
218 	uint64_t max = 0;
219 
220 	for (i = 0; i < ZAP_HISTOGRAM_SIZE; i++) {
221 		if (histo[i] > max)
222 			max = histo[i];
223 		if (histo[i] > 0 && i > maxidx)
224 			maxidx = i;
225 		if (histo[i] > 0 && i < minidx)
226 			minidx = i;
227 	}
228 
229 	if (max < dump_zap_width)
230 		max = dump_zap_width;
231 
232 	for (i = minidx; i <= maxidx; i++)
233 		(void) printf("\t\t\t%u: %6llu %s\n", i, (u_longlong_t)histo[i],
234 		    &dump_zap_stars[(max - histo[i]) * dump_zap_width / max]);
235 }
236 
237 static void
238 dump_zap_stats(objset_t *os, uint64_t object)
239 {
240 	int error;
241 	zap_stats_t zs;
242 
243 	error = zap_get_stats(os, object, &zs);
244 	if (error)
245 		return;
246 
247 	if (zs.zs_ptrtbl_len == 0) {
248 		ASSERT(zs.zs_num_blocks == 1);
249 		(void) printf("\tmicrozap: %llu bytes, %llu entries\n",
250 		    (u_longlong_t)zs.zs_blocksize,
251 		    (u_longlong_t)zs.zs_num_entries);
252 		return;
253 	}
254 
255 	(void) printf("\tFat ZAP stats:\n");
256 
257 	(void) printf("\t\tPointer table:\n");
258 	(void) printf("\t\t\t%llu elements\n",
259 	    (u_longlong_t)zs.zs_ptrtbl_len);
260 	(void) printf("\t\t\tzt_blk: %llu\n",
261 	    (u_longlong_t)zs.zs_ptrtbl_zt_blk);
262 	(void) printf("\t\t\tzt_numblks: %llu\n",
263 	    (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
264 	(void) printf("\t\t\tzt_shift: %llu\n",
265 	    (u_longlong_t)zs.zs_ptrtbl_zt_shift);
266 	(void) printf("\t\t\tzt_blks_copied: %llu\n",
267 	    (u_longlong_t)zs.zs_ptrtbl_blks_copied);
268 	(void) printf("\t\t\tzt_nextblk: %llu\n",
269 	    (u_longlong_t)zs.zs_ptrtbl_nextblk);
270 
271 	(void) printf("\t\tZAP entries: %llu\n",
272 	    (u_longlong_t)zs.zs_num_entries);
273 	(void) printf("\t\tLeaf blocks: %llu\n",
274 	    (u_longlong_t)zs.zs_num_leafs);
275 	(void) printf("\t\tTotal blocks: %llu\n",
276 	    (u_longlong_t)zs.zs_num_blocks);
277 	(void) printf("\t\tzap_block_type: 0x%llx\n",
278 	    (u_longlong_t)zs.zs_block_type);
279 	(void) printf("\t\tzap_magic: 0x%llx\n",
280 	    (u_longlong_t)zs.zs_magic);
281 	(void) printf("\t\tzap_salt: 0x%llx\n",
282 	    (u_longlong_t)zs.zs_salt);
283 
284 	(void) printf("\t\tLeafs with 2^n pointers:\n");
285 	dump_zap_histogram(zs.zs_leafs_with_2n_pointers);
286 
287 	(void) printf("\t\tBlocks with n*5 entries:\n");
288 	dump_zap_histogram(zs.zs_blocks_with_n5_entries);
289 
290 	(void) printf("\t\tBlocks n/10 full:\n");
291 	dump_zap_histogram(zs.zs_blocks_n_tenths_full);
292 
293 	(void) printf("\t\tEntries with n chunks:\n");
294 	dump_zap_histogram(zs.zs_entries_using_n_chunks);
295 
296 	(void) printf("\t\tBuckets with n entries:\n");
297 	dump_zap_histogram(zs.zs_buckets_with_n_entries);
298 }
299 
300 /*ARGSUSED*/
301 static void
302 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
303 {
304 }
305 
306 /*ARGSUSED*/
307 static void
308 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
309 {
310 	(void) printf("\tUNKNOWN OBJECT TYPE\n");
311 }
312 
313 /*ARGSUSED*/
314 void
315 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
316 {
317 }
318 
319 /*ARGSUSED*/
320 static void
321 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
322 {
323 }
324 
325 /*ARGSUSED*/
326 static void
327 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
328 {
329 	zap_cursor_t zc;
330 	zap_attribute_t attr;
331 	void *prop;
332 	int i;
333 
334 	dump_zap_stats(os, object);
335 	(void) printf("\n");
336 
337 	for (zap_cursor_init(&zc, os, object);
338 	    zap_cursor_retrieve(&zc, &attr) == 0;
339 	    zap_cursor_advance(&zc)) {
340 		(void) printf("\t\t%s = ", attr.za_name);
341 		if (attr.za_num_integers == 0) {
342 			(void) printf("\n");
343 			continue;
344 		}
345 		prop = umem_zalloc(attr.za_num_integers *
346 		    attr.za_integer_length, UMEM_NOFAIL);
347 		(void) zap_lookup(os, object, attr.za_name,
348 		    attr.za_integer_length, attr.za_num_integers, prop);
349 		if (attr.za_integer_length == 1) {
350 			(void) printf("%s", (char *)prop);
351 		} else {
352 			for (i = 0; i < attr.za_num_integers; i++) {
353 				switch (attr.za_integer_length) {
354 				case 2:
355 					(void) printf("%u ",
356 					    ((uint16_t *)prop)[i]);
357 					break;
358 				case 4:
359 					(void) printf("%u ",
360 					    ((uint32_t *)prop)[i]);
361 					break;
362 				case 8:
363 					(void) printf("%lld ",
364 					    (u_longlong_t)((int64_t *)prop)[i]);
365 					break;
366 				}
367 			}
368 		}
369 		(void) printf("\n");
370 		umem_free(prop, attr.za_num_integers * attr.za_integer_length);
371 	}
372 	zap_cursor_fini(&zc);
373 }
374 
375 /*ARGSUSED*/
376 static void
377 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
378 {
379 	dump_zap_stats(os, object);
380 	/* contents are printed elsewhere, properly decoded */
381 }
382 
383 /*ARGSUSED*/
384 static void
385 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
386 {
387 	zap_cursor_t zc;
388 	zap_attribute_t attr;
389 
390 	dump_zap_stats(os, object);
391 	(void) printf("\n");
392 
393 	for (zap_cursor_init(&zc, os, object);
394 	    zap_cursor_retrieve(&zc, &attr) == 0;
395 	    zap_cursor_advance(&zc)) {
396 		(void) printf("\t\t%s = ", attr.za_name);
397 		if (attr.za_num_integers == 0) {
398 			(void) printf("\n");
399 			continue;
400 		}
401 		(void) printf(" %llx : [%d:%d:%d]\n",
402 		    (u_longlong_t)attr.za_first_integer,
403 		    (int)ATTR_LENGTH(attr.za_first_integer),
404 		    (int)ATTR_BSWAP(attr.za_first_integer),
405 		    (int)ATTR_NUM(attr.za_first_integer));
406 	}
407 	zap_cursor_fini(&zc);
408 }
409 
410 /*ARGSUSED*/
411 static void
412 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
413 {
414 	zap_cursor_t zc;
415 	zap_attribute_t attr;
416 	uint16_t *layout_attrs;
417 	int i;
418 
419 	dump_zap_stats(os, object);
420 	(void) printf("\n");
421 
422 	for (zap_cursor_init(&zc, os, object);
423 	    zap_cursor_retrieve(&zc, &attr) == 0;
424 	    zap_cursor_advance(&zc)) {
425 		(void) printf("\t\t%s = [", attr.za_name);
426 		if (attr.za_num_integers == 0) {
427 			(void) printf("\n");
428 			continue;
429 		}
430 
431 		VERIFY(attr.za_integer_length == 2);
432 		layout_attrs = umem_zalloc(attr.za_num_integers *
433 		    attr.za_integer_length, UMEM_NOFAIL);
434 
435 		VERIFY(zap_lookup(os, object, attr.za_name,
436 		    attr.za_integer_length,
437 		    attr.za_num_integers, layout_attrs) == 0);
438 
439 		for (i = 0; i != attr.za_num_integers; i++)
440 			(void) printf(" %d ", (int)layout_attrs[i]);
441 		(void) printf("]\n");
442 		umem_free(layout_attrs,
443 		    attr.za_num_integers * attr.za_integer_length);
444 	}
445 	zap_cursor_fini(&zc);
446 }
447 
448 /*ARGSUSED*/
449 static void
450 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
451 {
452 	zap_cursor_t zc;
453 	zap_attribute_t attr;
454 	const char *typenames[] = {
455 		/* 0 */ "not specified",
456 		/* 1 */ "FIFO",
457 		/* 2 */ "Character Device",
458 		/* 3 */ "3 (invalid)",
459 		/* 4 */ "Directory",
460 		/* 5 */ "5 (invalid)",
461 		/* 6 */ "Block Device",
462 		/* 7 */ "7 (invalid)",
463 		/* 8 */ "Regular File",
464 		/* 9 */ "9 (invalid)",
465 		/* 10 */ "Symbolic Link",
466 		/* 11 */ "11 (invalid)",
467 		/* 12 */ "Socket",
468 		/* 13 */ "Door",
469 		/* 14 */ "Event Port",
470 		/* 15 */ "15 (invalid)",
471 	};
472 
473 	dump_zap_stats(os, object);
474 	(void) printf("\n");
475 
476 	for (zap_cursor_init(&zc, os, object);
477 	    zap_cursor_retrieve(&zc, &attr) == 0;
478 	    zap_cursor_advance(&zc)) {
479 		(void) printf("\t\t%s = %lld (type: %s)\n",
480 		    attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
481 		    typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
482 	}
483 	zap_cursor_fini(&zc);
484 }
485 
486 static void
487 dump_spacemap(objset_t *os, space_map_obj_t *smo, space_map_t *sm)
488 {
489 	uint64_t alloc, offset, entry;
490 	uint8_t mapshift = sm->sm_shift;
491 	uint64_t mapstart = sm->sm_start;
492 	char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
493 			    "INVALID", "INVALID", "INVALID", "INVALID" };
494 
495 	if (smo->smo_object == 0)
496 		return;
497 
498 	/*
499 	 * Print out the freelist entries in both encoded and decoded form.
500 	 */
501 	alloc = 0;
502 	for (offset = 0; offset < smo->smo_objsize; offset += sizeof (entry)) {
503 		VERIFY3U(0, ==, dmu_read(os, smo->smo_object, offset,
504 		    sizeof (entry), &entry, DMU_READ_PREFETCH));
505 		if (SM_DEBUG_DECODE(entry)) {
506 			(void) printf("\t    [%6llu] %s: txg %llu, pass %llu\n",
507 			    (u_longlong_t)(offset / sizeof (entry)),
508 			    ddata[SM_DEBUG_ACTION_DECODE(entry)],
509 			    (u_longlong_t)SM_DEBUG_TXG_DECODE(entry),
510 			    (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(entry));
511 		} else {
512 			(void) printf("\t    [%6llu]    %c  range:"
513 			    " %010llx-%010llx  size: %06llx\n",
514 			    (u_longlong_t)(offset / sizeof (entry)),
515 			    SM_TYPE_DECODE(entry) == SM_ALLOC ? 'A' : 'F',
516 			    (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
517 			    mapshift) + mapstart),
518 			    (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
519 			    mapshift) + mapstart + (SM_RUN_DECODE(entry) <<
520 			    mapshift)),
521 			    (u_longlong_t)(SM_RUN_DECODE(entry) << mapshift));
522 			if (SM_TYPE_DECODE(entry) == SM_ALLOC)
523 				alloc += SM_RUN_DECODE(entry) << mapshift;
524 			else
525 				alloc -= SM_RUN_DECODE(entry) << mapshift;
526 		}
527 	}
528 	if (alloc != smo->smo_alloc) {
529 		(void) printf("space_map_object alloc (%llu) INCONSISTENT "
530 		    "with space map summary (%llu)\n",
531 		    (u_longlong_t)smo->smo_alloc, (u_longlong_t)alloc);
532 	}
533 }
534 
535 static void
536 dump_metaslab_stats(metaslab_t *msp)
537 {
538 	char maxbuf[32];
539 	space_map_t *sm = &msp->ms_map;
540 	avl_tree_t *t = sm->sm_pp_root;
541 	int free_pct = sm->sm_space * 100 / sm->sm_size;
542 
543 	zdb_nicenum(space_map_maxsize(sm), maxbuf);
544 
545 	(void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
546 	    "segments", avl_numnodes(t), "maxsize", maxbuf,
547 	    "freepct", free_pct);
548 }
549 
550 static void
551 dump_metaslab(metaslab_t *msp)
552 {
553 	vdev_t *vd = msp->ms_group->mg_vd;
554 	spa_t *spa = vd->vdev_spa;
555 	space_map_t *sm = &msp->ms_map;
556 	space_map_obj_t *smo = &msp->ms_smo;
557 	char freebuf[32];
558 
559 	zdb_nicenum(sm->sm_size - smo->smo_alloc, freebuf);
560 
561 	(void) printf(
562 	    "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
563 	    (u_longlong_t)(sm->sm_start / sm->sm_size),
564 	    (u_longlong_t)sm->sm_start, (u_longlong_t)smo->smo_object, freebuf);
565 
566 	if (dump_opt['m'] > 1 && !dump_opt['L']) {
567 		mutex_enter(&msp->ms_lock);
568 		space_map_load_wait(sm);
569 		if (!sm->sm_loaded)
570 			VERIFY(space_map_load(sm, zfs_metaslab_ops,
571 			    SM_FREE, smo, spa->spa_meta_objset) == 0);
572 		dump_metaslab_stats(msp);
573 		space_map_unload(sm);
574 		mutex_exit(&msp->ms_lock);
575 	}
576 
577 	if (dump_opt['d'] > 5 || dump_opt['m'] > 2) {
578 		ASSERT(sm->sm_size == (1ULL << vd->vdev_ms_shift));
579 
580 		mutex_enter(&msp->ms_lock);
581 		dump_spacemap(spa->spa_meta_objset, smo, sm);
582 		mutex_exit(&msp->ms_lock);
583 	}
584 }
585 
586 static void
587 print_vdev_metaslab_header(vdev_t *vd)
588 {
589 	(void) printf("\tvdev %10llu\n\t%-10s%5llu   %-19s   %-15s   %-10s\n",
590 	    (u_longlong_t)vd->vdev_id,
591 	    "metaslabs", (u_longlong_t)vd->vdev_ms_count,
592 	    "offset", "spacemap", "free");
593 	(void) printf("\t%15s   %19s   %15s   %10s\n",
594 	    "---------------", "-------------------",
595 	    "---------------", "-------------");
596 }
597 
598 static void
599 dump_metaslabs(spa_t *spa)
600 {
601 	vdev_t *vd, *rvd = spa->spa_root_vdev;
602 	uint64_t m, c = 0, children = rvd->vdev_children;
603 
604 	(void) printf("\nMetaslabs:\n");
605 
606 	if (!dump_opt['d'] && zopt_objects > 0) {
607 		c = zopt_object[0];
608 
609 		if (c >= children)
610 			(void) fatal("bad vdev id: %llu", (u_longlong_t)c);
611 
612 		if (zopt_objects > 1) {
613 			vd = rvd->vdev_child[c];
614 			print_vdev_metaslab_header(vd);
615 
616 			for (m = 1; m < zopt_objects; m++) {
617 				if (zopt_object[m] < vd->vdev_ms_count)
618 					dump_metaslab(
619 					    vd->vdev_ms[zopt_object[m]]);
620 				else
621 					(void) fprintf(stderr, "bad metaslab "
622 					    "number %llu\n",
623 					    (u_longlong_t)zopt_object[m]);
624 			}
625 			(void) printf("\n");
626 			return;
627 		}
628 		children = c + 1;
629 	}
630 	for (; c < children; c++) {
631 		vd = rvd->vdev_child[c];
632 		print_vdev_metaslab_header(vd);
633 
634 		for (m = 0; m < vd->vdev_ms_count; m++)
635 			dump_metaslab(vd->vdev_ms[m]);
636 		(void) printf("\n");
637 	}
638 }
639 
640 static void
641 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
642 {
643 	const ddt_phys_t *ddp = dde->dde_phys;
644 	const ddt_key_t *ddk = &dde->dde_key;
645 	char *types[4] = { "ditto", "single", "double", "triple" };
646 	char blkbuf[BP_SPRINTF_LEN];
647 	blkptr_t blk;
648 
649 	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
650 		if (ddp->ddp_phys_birth == 0)
651 			continue;
652 		ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
653 		sprintf_blkptr(blkbuf, &blk);
654 		(void) printf("index %llx refcnt %llu %s %s\n",
655 		    (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
656 		    types[p], blkbuf);
657 	}
658 }
659 
660 static void
661 dump_dedup_ratio(const ddt_stat_t *dds)
662 {
663 	double rL, rP, rD, D, dedup, compress, copies;
664 
665 	if (dds->dds_blocks == 0)
666 		return;
667 
668 	rL = (double)dds->dds_ref_lsize;
669 	rP = (double)dds->dds_ref_psize;
670 	rD = (double)dds->dds_ref_dsize;
671 	D = (double)dds->dds_dsize;
672 
673 	dedup = rD / D;
674 	compress = rL / rP;
675 	copies = rD / rP;
676 
677 	(void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
678 	    "dedup * compress / copies = %.2f\n\n",
679 	    dedup, compress, copies, dedup * compress / copies);
680 }
681 
682 static void
683 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
684 {
685 	char name[DDT_NAMELEN];
686 	ddt_entry_t dde;
687 	uint64_t walk = 0;
688 	dmu_object_info_t doi;
689 	uint64_t count, dspace, mspace;
690 	int error;
691 
692 	error = ddt_object_info(ddt, type, class, &doi);
693 
694 	if (error == ENOENT)
695 		return;
696 	ASSERT(error == 0);
697 
698 	count = ddt_object_count(ddt, type, class);
699 	dspace = doi.doi_physical_blocks_512 << 9;
700 	mspace = doi.doi_fill_count * doi.doi_data_block_size;
701 
702 	ASSERT(count != 0);	/* we should have destroyed it */
703 
704 	ddt_object_name(ddt, type, class, name);
705 
706 	(void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
707 	    name,
708 	    (u_longlong_t)count,
709 	    (u_longlong_t)(dspace / count),
710 	    (u_longlong_t)(mspace / count));
711 
712 	if (dump_opt['D'] < 3)
713 		return;
714 
715 	zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
716 
717 	if (dump_opt['D'] < 4)
718 		return;
719 
720 	if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
721 		return;
722 
723 	(void) printf("%s contents:\n\n", name);
724 
725 	while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
726 		dump_dde(ddt, &dde, walk);
727 
728 	ASSERT(error == ENOENT);
729 
730 	(void) printf("\n");
731 }
732 
733 static void
734 dump_all_ddts(spa_t *spa)
735 {
736 	ddt_histogram_t ddh_total = { 0 };
737 	ddt_stat_t dds_total = { 0 };
738 
739 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
740 		ddt_t *ddt = spa->spa_ddt[c];
741 		for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
742 			for (enum ddt_class class = 0; class < DDT_CLASSES;
743 			    class++) {
744 				dump_ddt(ddt, type, class);
745 			}
746 		}
747 	}
748 
749 	ddt_get_dedup_stats(spa, &dds_total);
750 
751 	if (dds_total.dds_blocks == 0) {
752 		(void) printf("All DDTs are empty\n");
753 		return;
754 	}
755 
756 	(void) printf("\n");
757 
758 	if (dump_opt['D'] > 1) {
759 		(void) printf("DDT histogram (aggregated over all DDTs):\n");
760 		ddt_get_dedup_histogram(spa, &ddh_total);
761 		zpool_dump_ddt(&dds_total, &ddh_total);
762 	}
763 
764 	dump_dedup_ratio(&dds_total);
765 }
766 
767 static void
768 dump_dtl_seg(space_map_t *sm, uint64_t start, uint64_t size)
769 {
770 	char *prefix = (void *)sm;
771 
772 	(void) printf("%s [%llu,%llu) length %llu\n",
773 	    prefix,
774 	    (u_longlong_t)start,
775 	    (u_longlong_t)(start + size),
776 	    (u_longlong_t)(size));
777 }
778 
779 static void
780 dump_dtl(vdev_t *vd, int indent)
781 {
782 	spa_t *spa = vd->vdev_spa;
783 	boolean_t required;
784 	char *name[DTL_TYPES] = { "missing", "partial", "scrub", "outage" };
785 	char prefix[256];
786 
787 	spa_vdev_state_enter(spa, SCL_NONE);
788 	required = vdev_dtl_required(vd);
789 	(void) spa_vdev_state_exit(spa, NULL, 0);
790 
791 	if (indent == 0)
792 		(void) printf("\nDirty time logs:\n\n");
793 
794 	(void) printf("\t%*s%s [%s]\n", indent, "",
795 	    vd->vdev_path ? vd->vdev_path :
796 	    vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
797 	    required ? "DTL-required" : "DTL-expendable");
798 
799 	for (int t = 0; t < DTL_TYPES; t++) {
800 		space_map_t *sm = &vd->vdev_dtl[t];
801 		if (sm->sm_space == 0)
802 			continue;
803 		(void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
804 		    indent + 2, "", name[t]);
805 		mutex_enter(sm->sm_lock);
806 		space_map_walk(sm, dump_dtl_seg, (void *)prefix);
807 		mutex_exit(sm->sm_lock);
808 		if (dump_opt['d'] > 5 && vd->vdev_children == 0)
809 			dump_spacemap(spa->spa_meta_objset,
810 			    &vd->vdev_dtl_smo, sm);
811 	}
812 
813 	for (int c = 0; c < vd->vdev_children; c++)
814 		dump_dtl(vd->vdev_child[c], indent + 4);
815 }
816 
817 static void
818 dump_history(spa_t *spa)
819 {
820 	nvlist_t **events = NULL;
821 	char buf[SPA_MAXBLOCKSIZE];
822 	uint64_t resid, len, off = 0;
823 	uint_t num = 0;
824 	int error;
825 	time_t tsec;
826 	struct tm t;
827 	char tbuf[30];
828 	char internalstr[MAXPATHLEN];
829 
830 	do {
831 		len = sizeof (buf);
832 
833 		if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
834 			(void) fprintf(stderr, "Unable to read history: "
835 			    "error %d\n", error);
836 			return;
837 		}
838 
839 		if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
840 			break;
841 
842 		off -= resid;
843 	} while (len != 0);
844 
845 	(void) printf("\nHistory:\n");
846 	for (int i = 0; i < num; i++) {
847 		uint64_t time, txg, ievent;
848 		char *cmd, *intstr;
849 
850 		if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
851 		    &time) != 0)
852 			continue;
853 		if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
854 		    &cmd) != 0) {
855 			if (nvlist_lookup_uint64(events[i],
856 			    ZPOOL_HIST_INT_EVENT, &ievent) != 0)
857 				continue;
858 			verify(nvlist_lookup_uint64(events[i],
859 			    ZPOOL_HIST_TXG, &txg) == 0);
860 			verify(nvlist_lookup_string(events[i],
861 			    ZPOOL_HIST_INT_STR, &intstr) == 0);
862 			if (ievent >= LOG_END)
863 				continue;
864 
865 			(void) snprintf(internalstr,
866 			    sizeof (internalstr),
867 			    "[internal %s txg:%lld] %s",
868 			    zfs_history_event_names[ievent], txg,
869 			    intstr);
870 			cmd = internalstr;
871 		}
872 		tsec = time;
873 		(void) localtime_r(&tsec, &t);
874 		(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
875 		(void) printf("%s %s\n", tbuf, cmd);
876 	}
877 }
878 
879 /*ARGSUSED*/
880 static void
881 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
882 {
883 }
884 
885 static uint64_t
886 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp, const zbookmark_t *zb)
887 {
888 	if (dnp == NULL) {
889 		ASSERT(zb->zb_level < 0);
890 		if (zb->zb_object == 0)
891 			return (zb->zb_blkid);
892 		return (zb->zb_blkid * BP_GET_LSIZE(bp));
893 	}
894 
895 	ASSERT(zb->zb_level >= 0);
896 
897 	return ((zb->zb_blkid <<
898 	    (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
899 	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
900 }
901 
902 static void
903 sprintf_blkptr_compact(char *blkbuf, blkptr_t *bp)
904 {
905 	dva_t *dva = bp->blk_dva;
906 	int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
907 
908 	if (dump_opt['b'] >= 5) {
909 		sprintf_blkptr(blkbuf, bp);
910 		return;
911 	}
912 
913 	blkbuf[0] = '\0';
914 
915 	for (int i = 0; i < ndvas; i++)
916 		(void) sprintf(blkbuf + strlen(blkbuf), "%llu:%llx:%llx ",
917 		    (u_longlong_t)DVA_GET_VDEV(&dva[i]),
918 		    (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
919 		    (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
920 
921 	(void) sprintf(blkbuf + strlen(blkbuf),
922 	    "%llxL/%llxP F=%llu B=%llu/%llu",
923 	    (u_longlong_t)BP_GET_LSIZE(bp),
924 	    (u_longlong_t)BP_GET_PSIZE(bp),
925 	    (u_longlong_t)bp->blk_fill,
926 	    (u_longlong_t)bp->blk_birth,
927 	    (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
928 }
929 
930 static void
931 print_indirect(blkptr_t *bp, const zbookmark_t *zb,
932     const dnode_phys_t *dnp)
933 {
934 	char blkbuf[BP_SPRINTF_LEN];
935 	int l;
936 
937 	ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
938 	ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
939 
940 	(void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
941 
942 	ASSERT(zb->zb_level >= 0);
943 
944 	for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
945 		if (l == zb->zb_level) {
946 			(void) printf("L%llx", (u_longlong_t)zb->zb_level);
947 		} else {
948 			(void) printf(" ");
949 		}
950 	}
951 
952 	sprintf_blkptr_compact(blkbuf, bp);
953 	(void) printf("%s\n", blkbuf);
954 }
955 
956 static int
957 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
958     blkptr_t *bp, const zbookmark_t *zb)
959 {
960 	int err = 0;
961 
962 	if (bp->blk_birth == 0)
963 		return (0);
964 
965 	print_indirect(bp, zb, dnp);
966 
967 	if (BP_GET_LEVEL(bp) > 0) {
968 		uint32_t flags = ARC_WAIT;
969 		int i;
970 		blkptr_t *cbp;
971 		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
972 		arc_buf_t *buf;
973 		uint64_t fill = 0;
974 
975 		err = arc_read_nolock(NULL, spa, bp, arc_getbuf_func, &buf,
976 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
977 		if (err)
978 			return (err);
979 		ASSERT(buf->b_data);
980 
981 		/* recursively visit blocks below this */
982 		cbp = buf->b_data;
983 		for (i = 0; i < epb; i++, cbp++) {
984 			zbookmark_t czb;
985 
986 			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
987 			    zb->zb_level - 1,
988 			    zb->zb_blkid * epb + i);
989 			err = visit_indirect(spa, dnp, cbp, &czb);
990 			if (err)
991 				break;
992 			fill += cbp->blk_fill;
993 		}
994 		if (!err)
995 			ASSERT3U(fill, ==, bp->blk_fill);
996 		(void) arc_buf_remove_ref(buf, &buf);
997 	}
998 
999 	return (err);
1000 }
1001 
1002 /*ARGSUSED*/
1003 static void
1004 dump_indirect(dnode_t *dn)
1005 {
1006 	dnode_phys_t *dnp = dn->dn_phys;
1007 	int j;
1008 	zbookmark_t czb;
1009 
1010 	(void) printf("Indirect blocks:\n");
1011 
1012 	SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1013 	    dn->dn_object, dnp->dn_nlevels - 1, 0);
1014 	for (j = 0; j < dnp->dn_nblkptr; j++) {
1015 		czb.zb_blkid = j;
1016 		(void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1017 		    &dnp->dn_blkptr[j], &czb);
1018 	}
1019 
1020 	(void) printf("\n");
1021 }
1022 
1023 /*ARGSUSED*/
1024 static void
1025 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1026 {
1027 	dsl_dir_phys_t *dd = data;
1028 	time_t crtime;
1029 	char nice[32];
1030 
1031 	if (dd == NULL)
1032 		return;
1033 
1034 	ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1035 
1036 	crtime = dd->dd_creation_time;
1037 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1038 	(void) printf("\t\thead_dataset_obj = %llu\n",
1039 	    (u_longlong_t)dd->dd_head_dataset_obj);
1040 	(void) printf("\t\tparent_dir_obj = %llu\n",
1041 	    (u_longlong_t)dd->dd_parent_obj);
1042 	(void) printf("\t\torigin_obj = %llu\n",
1043 	    (u_longlong_t)dd->dd_origin_obj);
1044 	(void) printf("\t\tchild_dir_zapobj = %llu\n",
1045 	    (u_longlong_t)dd->dd_child_dir_zapobj);
1046 	zdb_nicenum(dd->dd_used_bytes, nice);
1047 	(void) printf("\t\tused_bytes = %s\n", nice);
1048 	zdb_nicenum(dd->dd_compressed_bytes, nice);
1049 	(void) printf("\t\tcompressed_bytes = %s\n", nice);
1050 	zdb_nicenum(dd->dd_uncompressed_bytes, nice);
1051 	(void) printf("\t\tuncompressed_bytes = %s\n", nice);
1052 	zdb_nicenum(dd->dd_quota, nice);
1053 	(void) printf("\t\tquota = %s\n", nice);
1054 	zdb_nicenum(dd->dd_reserved, nice);
1055 	(void) printf("\t\treserved = %s\n", nice);
1056 	(void) printf("\t\tprops_zapobj = %llu\n",
1057 	    (u_longlong_t)dd->dd_props_zapobj);
1058 	(void) printf("\t\tdeleg_zapobj = %llu\n",
1059 	    (u_longlong_t)dd->dd_deleg_zapobj);
1060 	(void) printf("\t\tflags = %llx\n",
1061 	    (u_longlong_t)dd->dd_flags);
1062 
1063 #define	DO(which) \
1064 	zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice); \
1065 	(void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1066 	DO(HEAD);
1067 	DO(SNAP);
1068 	DO(CHILD);
1069 	DO(CHILD_RSRV);
1070 	DO(REFRSRV);
1071 #undef DO
1072 }
1073 
1074 /*ARGSUSED*/
1075 static void
1076 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1077 {
1078 	dsl_dataset_phys_t *ds = data;
1079 	time_t crtime;
1080 	char used[32], compressed[32], uncompressed[32], unique[32];
1081 	char blkbuf[BP_SPRINTF_LEN];
1082 
1083 	if (ds == NULL)
1084 		return;
1085 
1086 	ASSERT(size == sizeof (*ds));
1087 	crtime = ds->ds_creation_time;
1088 	zdb_nicenum(ds->ds_used_bytes, used);
1089 	zdb_nicenum(ds->ds_compressed_bytes, compressed);
1090 	zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed);
1091 	zdb_nicenum(ds->ds_unique_bytes, unique);
1092 	sprintf_blkptr(blkbuf, &ds->ds_bp);
1093 
1094 	(void) printf("\t\tdir_obj = %llu\n",
1095 	    (u_longlong_t)ds->ds_dir_obj);
1096 	(void) printf("\t\tprev_snap_obj = %llu\n",
1097 	    (u_longlong_t)ds->ds_prev_snap_obj);
1098 	(void) printf("\t\tprev_snap_txg = %llu\n",
1099 	    (u_longlong_t)ds->ds_prev_snap_txg);
1100 	(void) printf("\t\tnext_snap_obj = %llu\n",
1101 	    (u_longlong_t)ds->ds_next_snap_obj);
1102 	(void) printf("\t\tsnapnames_zapobj = %llu\n",
1103 	    (u_longlong_t)ds->ds_snapnames_zapobj);
1104 	(void) printf("\t\tnum_children = %llu\n",
1105 	    (u_longlong_t)ds->ds_num_children);
1106 	(void) printf("\t\tuserrefs_obj = %llu\n",
1107 	    (u_longlong_t)ds->ds_userrefs_obj);
1108 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1109 	(void) printf("\t\tcreation_txg = %llu\n",
1110 	    (u_longlong_t)ds->ds_creation_txg);
1111 	(void) printf("\t\tdeadlist_obj = %llu\n",
1112 	    (u_longlong_t)ds->ds_deadlist_obj);
1113 	(void) printf("\t\tused_bytes = %s\n", used);
1114 	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
1115 	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1116 	(void) printf("\t\tunique = %s\n", unique);
1117 	(void) printf("\t\tfsid_guid = %llu\n",
1118 	    (u_longlong_t)ds->ds_fsid_guid);
1119 	(void) printf("\t\tguid = %llu\n",
1120 	    (u_longlong_t)ds->ds_guid);
1121 	(void) printf("\t\tflags = %llx\n",
1122 	    (u_longlong_t)ds->ds_flags);
1123 	(void) printf("\t\tnext_clones_obj = %llu\n",
1124 	    (u_longlong_t)ds->ds_next_clones_obj);
1125 	(void) printf("\t\tprops_obj = %llu\n",
1126 	    (u_longlong_t)ds->ds_props_obj);
1127 	(void) printf("\t\tbp = %s\n", blkbuf);
1128 }
1129 
1130 static void
1131 dump_bplist(objset_t *mos, uint64_t object, char *name)
1132 {
1133 	bplist_t bpl = { 0 };
1134 	blkptr_t blk, *bp = &blk;
1135 	uint64_t itor = 0;
1136 	char bytes[32];
1137 	char comp[32];
1138 	char uncomp[32];
1139 
1140 	if (dump_opt['d'] < 3)
1141 		return;
1142 
1143 	bplist_init(&bpl);
1144 	VERIFY(0 == bplist_open(&bpl, mos, object));
1145 	if (bplist_empty(&bpl)) {
1146 		bplist_close(&bpl);
1147 		bplist_fini(&bpl);
1148 		return;
1149 	}
1150 
1151 	zdb_nicenum(bpl.bpl_phys->bpl_bytes, bytes);
1152 	if (bpl.bpl_dbuf->db_size == sizeof (bplist_phys_t)) {
1153 		zdb_nicenum(bpl.bpl_phys->bpl_comp, comp);
1154 		zdb_nicenum(bpl.bpl_phys->bpl_uncomp, uncomp);
1155 		(void) printf("\n    %s: %llu entries, %s (%s/%s comp)\n",
1156 		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries,
1157 		    bytes, comp, uncomp);
1158 	} else {
1159 		(void) printf("\n    %s: %llu entries, %s\n",
1160 		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries, bytes);
1161 	}
1162 
1163 	if (dump_opt['d'] < 5) {
1164 		bplist_close(&bpl);
1165 		bplist_fini(&bpl);
1166 		return;
1167 	}
1168 
1169 	(void) printf("\n");
1170 
1171 	while (bplist_iterate(&bpl, &itor, bp) == 0) {
1172 		char blkbuf[BP_SPRINTF_LEN];
1173 
1174 		ASSERT(bp->blk_birth != 0);
1175 		sprintf_blkptr_compact(blkbuf, bp);
1176 		(void) printf("\tItem %3llu: %s\n",
1177 		    (u_longlong_t)itor - 1, blkbuf);
1178 	}
1179 
1180 	bplist_close(&bpl);
1181 	bplist_fini(&bpl);
1182 }
1183 
1184 static avl_tree_t idx_tree;
1185 static avl_tree_t domain_tree;
1186 static boolean_t fuid_table_loaded;
1187 static boolean_t sa_loaded;
1188 sa_attr_type_t *sa_attr_table;
1189 
1190 static void
1191 fuid_table_destroy()
1192 {
1193 	if (fuid_table_loaded) {
1194 		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1195 		fuid_table_loaded = B_FALSE;
1196 	}
1197 }
1198 
1199 /*
1200  * print uid or gid information.
1201  * For normal POSIX id just the id is printed in decimal format.
1202  * For CIFS files with FUID the fuid is printed in hex followed by
1203  * the doman-rid string.
1204  */
1205 static void
1206 print_idstr(uint64_t id, const char *id_type)
1207 {
1208 	if (FUID_INDEX(id)) {
1209 		char *domain;
1210 
1211 		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1212 		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
1213 		    (u_longlong_t)id, domain, (int)FUID_RID(id));
1214 	} else {
1215 		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1216 	}
1217 
1218 }
1219 
1220 static void
1221 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
1222 {
1223 	uint32_t uid_idx, gid_idx;
1224 
1225 	uid_idx = FUID_INDEX(uid);
1226 	gid_idx = FUID_INDEX(gid);
1227 
1228 	/* Load domain table, if not already loaded */
1229 	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1230 		uint64_t fuid_obj;
1231 
1232 		/* first find the fuid object.  It lives in the master node */
1233 		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1234 		    8, 1, &fuid_obj) == 0);
1235 		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1236 		(void) zfs_fuid_table_load(os, fuid_obj,
1237 		    &idx_tree, &domain_tree);
1238 		fuid_table_loaded = B_TRUE;
1239 	}
1240 
1241 	print_idstr(uid, "uid");
1242 	print_idstr(gid, "gid");
1243 }
1244 
1245 /*ARGSUSED*/
1246 static void
1247 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
1248 {
1249 	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
1250 	sa_handle_t *hdl;
1251 	uint64_t xattr, rdev, gen;
1252 	uint64_t uid, gid, mode, fsize, parent, links;
1253 	uint64_t pflags;
1254 	uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
1255 	time_t z_crtime, z_atime, z_mtime, z_ctime;
1256 	sa_bulk_attr_t bulk[12];
1257 	int idx = 0;
1258 	int error;
1259 
1260 	if (!sa_loaded) {
1261 		uint64_t sa_attrs = 0;
1262 		uint64_t version;
1263 
1264 		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1265 		    8, 1, &version) == 0);
1266 		if (version >= ZPL_VERSION_SA) {
1267 			VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1268 			    8, 1, &sa_attrs) == 0);
1269 		}
1270 		sa_attr_table = sa_setup(os, sa_attrs,
1271 		    zfs_attr_table, ZPL_END);
1272 		sa_loaded = B_TRUE;
1273 	}
1274 
1275 	if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
1276 		(void) printf("Failed to get handle for SA znode\n");
1277 		return;
1278 	}
1279 
1280 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
1281 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
1282 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
1283 	    &links, 8);
1284 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
1285 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
1286 	    &mode, 8);
1287 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
1288 	    NULL, &parent, 8);
1289 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
1290 	    &fsize, 8);
1291 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
1292 	    acctm, 16);
1293 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
1294 	    modtm, 16);
1295 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
1296 	    crtm, 16);
1297 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
1298 	    chgtm, 16);
1299 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
1300 	    &pflags, 8);
1301 
1302 	if (sa_bulk_lookup(hdl, bulk, idx)) {
1303 		(void) sa_handle_destroy(hdl);
1304 		return;
1305 	}
1306 
1307 	error = zfs_obj_to_path(os, object, path, sizeof (path));
1308 	if (error != 0) {
1309 		(void) snprintf(path, sizeof (path), "\?\?\?<object#%llu>",
1310 		    (u_longlong_t)object);
1311 	}
1312 	if (dump_opt['d'] < 3) {
1313 		(void) printf("\t%s\n", path);
1314 		(void) sa_handle_destroy(hdl);
1315 		return;
1316 	}
1317 
1318 	z_crtime = (time_t)crtm[0];
1319 	z_atime = (time_t)acctm[0];
1320 	z_mtime = (time_t)modtm[0];
1321 	z_ctime = (time_t)chgtm[0];
1322 
1323 	(void) printf("\tpath	%s\n", path);
1324 	dump_uidgid(os, uid, gid);
1325 	(void) printf("\tatime	%s", ctime(&z_atime));
1326 	(void) printf("\tmtime	%s", ctime(&z_mtime));
1327 	(void) printf("\tctime	%s", ctime(&z_ctime));
1328 	(void) printf("\tcrtime	%s", ctime(&z_crtime));
1329 	(void) printf("\tgen	%llu\n", (u_longlong_t)gen);
1330 	(void) printf("\tmode	%llo\n", (u_longlong_t)mode);
1331 	(void) printf("\tsize	%llu\n", (u_longlong_t)fsize);
1332 	(void) printf("\tparent	%llu\n", (u_longlong_t)parent);
1333 	(void) printf("\tlinks	%llu\n", (u_longlong_t)links);
1334 	(void) printf("\tpflags	%llx\n", (u_longlong_t)pflags);
1335 	if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
1336 	    sizeof (uint64_t)) == 0)
1337 		(void) printf("\txattr	%llu\n", (u_longlong_t)xattr);
1338 	if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
1339 	    sizeof (uint64_t)) == 0)
1340 		(void) printf("\trdev	0x%016llx\n", (u_longlong_t)rdev);
1341 	sa_handle_destroy(hdl);
1342 }
1343 
1344 /*ARGSUSED*/
1345 static void
1346 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
1347 {
1348 }
1349 
1350 /*ARGSUSED*/
1351 static void
1352 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
1353 {
1354 }
1355 
1356 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
1357 	dump_none,		/* unallocated			*/
1358 	dump_zap,		/* object directory		*/
1359 	dump_uint64,		/* object array			*/
1360 	dump_none,		/* packed nvlist		*/
1361 	dump_packed_nvlist,	/* packed nvlist size		*/
1362 	dump_none,		/* bplist			*/
1363 	dump_none,		/* bplist header		*/
1364 	dump_none,		/* SPA space map header		*/
1365 	dump_none,		/* SPA space map		*/
1366 	dump_none,		/* ZIL intent log		*/
1367 	dump_dnode,		/* DMU dnode			*/
1368 	dump_dmu_objset,	/* DMU objset			*/
1369 	dump_dsl_dir,		/* DSL directory		*/
1370 	dump_zap,		/* DSL directory child map	*/
1371 	dump_zap,		/* DSL dataset snap map		*/
1372 	dump_zap,		/* DSL props			*/
1373 	dump_dsl_dataset,	/* DSL dataset			*/
1374 	dump_znode,		/* ZFS znode			*/
1375 	dump_acl,		/* ZFS V0 ACL			*/
1376 	dump_uint8,		/* ZFS plain file		*/
1377 	dump_zpldir,		/* ZFS directory		*/
1378 	dump_zap,		/* ZFS master node		*/
1379 	dump_zap,		/* ZFS delete queue		*/
1380 	dump_uint8,		/* zvol object			*/
1381 	dump_zap,		/* zvol prop			*/
1382 	dump_uint8,		/* other uint8[]		*/
1383 	dump_uint64,		/* other uint64[]		*/
1384 	dump_zap,		/* other ZAP			*/
1385 	dump_zap,		/* persistent error log		*/
1386 	dump_uint8,		/* SPA history			*/
1387 	dump_uint64,		/* SPA history offsets		*/
1388 	dump_zap,		/* Pool properties		*/
1389 	dump_zap,		/* DSL permissions		*/
1390 	dump_acl,		/* ZFS ACL			*/
1391 	dump_uint8,		/* ZFS SYSACL			*/
1392 	dump_none,		/* FUID nvlist			*/
1393 	dump_packed_nvlist,	/* FUID nvlist size		*/
1394 	dump_zap,		/* DSL dataset next clones	*/
1395 	dump_zap,		/* DSL scrub queue		*/
1396 	dump_zap,		/* ZFS user/group used		*/
1397 	dump_zap,		/* ZFS user/group quota		*/
1398 	dump_zap,		/* snapshot refcount tags	*/
1399 	dump_ddt_zap,		/* DDT ZAP object		*/
1400 	dump_zap,		/* DDT statistics		*/
1401 	dump_znode,		/* SA object			*/
1402 	dump_zap,		/* SA Master Node		*/
1403 	dump_sa_attrs,		/* SA attribute registration	*/
1404 	dump_sa_layouts,	/* SA attribute layouts		*/
1405 	dump_zap,		/* DSL scrub translations	*/
1406 	dump_none,		/* fake dedup BP		*/
1407 	dump_unknown,		/* Unknown type, must be last	*/
1408 };
1409 
1410 static void
1411 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1412 {
1413 	dmu_buf_t *db = NULL;
1414 	dmu_object_info_t doi;
1415 	dnode_t *dn;
1416 	void *bonus = NULL;
1417 	size_t bsize = 0;
1418 	char iblk[32], dblk[32], lsize[32], asize[32], fill[32];
1419 	char bonus_size[32];
1420 	char aux[50];
1421 	int error;
1422 
1423 	if (*print_header) {
1424 		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1425 		    "Object", "lvl", "iblk", "dblk", "dsize", "lsize",
1426 		    "%full", "type");
1427 		*print_header = 0;
1428 	}
1429 
1430 	if (object == 0) {
1431 		dn = os->os_meta_dnode;
1432 	} else {
1433 		error = dmu_bonus_hold(os, object, FTAG, &db);
1434 		if (error)
1435 			fatal("dmu_bonus_hold(%llu) failed, errno %u",
1436 			    object, error);
1437 		bonus = db->db_data;
1438 		bsize = db->db_size;
1439 		dn = ((dmu_buf_impl_t *)db)->db_dnode;
1440 	}
1441 	dmu_object_info_from_dnode(dn, &doi);
1442 
1443 	zdb_nicenum(doi.doi_metadata_block_size, iblk);
1444 	zdb_nicenum(doi.doi_data_block_size, dblk);
1445 	zdb_nicenum(doi.doi_max_offset, lsize);
1446 	zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize);
1447 	zdb_nicenum(doi.doi_bonus_size, bonus_size);
1448 	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
1449 	    doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
1450 	    doi.doi_max_offset);
1451 
1452 	aux[0] = '\0';
1453 
1454 	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1455 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1456 		    ZDB_CHECKSUM_NAME(doi.doi_checksum));
1457 	}
1458 
1459 	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1460 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1461 		    ZDB_COMPRESS_NAME(doi.doi_compress));
1462 	}
1463 
1464 	(void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %6s  %s%s\n",
1465 	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
1466 	    asize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
1467 
1468 	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1469 		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1470 		    "", "", "", "", "", bonus_size, "bonus",
1471 		    ZDB_OT_NAME(doi.doi_bonus_type));
1472 	}
1473 
1474 	if (verbosity >= 4) {
1475 		(void) printf("\tdnode flags: %s%s%s\n",
1476 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
1477 		    "USED_BYTES " : "",
1478 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
1479 		    "USERUSED_ACCOUNTED " : "",
1480 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
1481 		    "SPILL_BLKPTR" : "");
1482 		(void) printf("\tdnode maxblkid: %llu\n",
1483 		    (longlong_t)dn->dn_phys->dn_maxblkid);
1484 
1485 		object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os, object,
1486 		    bonus, bsize);
1487 		object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object, NULL, 0);
1488 		*print_header = 1;
1489 	}
1490 
1491 	if (verbosity >= 5)
1492 		dump_indirect(dn);
1493 
1494 	if (verbosity >= 5) {
1495 		/*
1496 		 * Report the list of segments that comprise the object.
1497 		 */
1498 		uint64_t start = 0;
1499 		uint64_t end;
1500 		uint64_t blkfill = 1;
1501 		int minlvl = 1;
1502 
1503 		if (dn->dn_type == DMU_OT_DNODE) {
1504 			minlvl = 0;
1505 			blkfill = DNODES_PER_BLOCK;
1506 		}
1507 
1508 		for (;;) {
1509 			char segsize[32];
1510 			error = dnode_next_offset(dn,
1511 			    0, &start, minlvl, blkfill, 0);
1512 			if (error)
1513 				break;
1514 			end = start;
1515 			error = dnode_next_offset(dn,
1516 			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
1517 			zdb_nicenum(end - start, segsize);
1518 			(void) printf("\t\tsegment [%016llx, %016llx)"
1519 			    " size %5s\n", (u_longlong_t)start,
1520 			    (u_longlong_t)end, segsize);
1521 			if (error)
1522 				break;
1523 			start = end;
1524 		}
1525 	}
1526 
1527 	if (db != NULL)
1528 		dmu_buf_rele(db, FTAG);
1529 }
1530 
1531 static char *objset_types[DMU_OST_NUMTYPES] = {
1532 	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1533 
1534 static void
1535 dump_dir(objset_t *os)
1536 {
1537 	dmu_objset_stats_t dds;
1538 	uint64_t object, object_count;
1539 	uint64_t refdbytes, usedobjs, scratch;
1540 	char numbuf[32];
1541 	char blkbuf[BP_SPRINTF_LEN + 20];
1542 	char osname[MAXNAMELEN];
1543 	char *type = "UNKNOWN";
1544 	int verbosity = dump_opt['d'];
1545 	int print_header = 1;
1546 	int i, error;
1547 
1548 	dmu_objset_fast_stat(os, &dds);
1549 
1550 	if (dds.dds_type < DMU_OST_NUMTYPES)
1551 		type = objset_types[dds.dds_type];
1552 
1553 	if (dds.dds_type == DMU_OST_META) {
1554 		dds.dds_creation_txg = TXG_INITIAL;
1555 		usedobjs = os->os_rootbp->blk_fill;
1556 		refdbytes = os->os_spa->spa_dsl_pool->
1557 		    dp_mos_dir->dd_phys->dd_used_bytes;
1558 	} else {
1559 		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
1560 	}
1561 
1562 	ASSERT3U(usedobjs, ==, os->os_rootbp->blk_fill);
1563 
1564 	zdb_nicenum(refdbytes, numbuf);
1565 
1566 	if (verbosity >= 4) {
1567 		(void) sprintf(blkbuf, ", rootbp ");
1568 		(void) sprintf_blkptr(blkbuf + strlen(blkbuf), os->os_rootbp);
1569 	} else {
1570 		blkbuf[0] = '\0';
1571 	}
1572 
1573 	dmu_objset_name(os, osname);
1574 
1575 	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
1576 	    "%s, %llu objects%s\n",
1577 	    osname, type, (u_longlong_t)dmu_objset_id(os),
1578 	    (u_longlong_t)dds.dds_creation_txg,
1579 	    numbuf, (u_longlong_t)usedobjs, blkbuf);
1580 
1581 	if (zopt_objects != 0) {
1582 		for (i = 0; i < zopt_objects; i++)
1583 			dump_object(os, zopt_object[i], verbosity,
1584 			    &print_header);
1585 		(void) printf("\n");
1586 		return;
1587 	}
1588 
1589 	if (dump_opt['i'] != 0 || verbosity >= 2)
1590 		dump_intent_log(dmu_objset_zil(os));
1591 
1592 	if (dmu_objset_ds(os) != NULL)
1593 		dump_bplist(dmu_objset_pool(os)->dp_meta_objset,
1594 		    dmu_objset_ds(os)->ds_phys->ds_deadlist_obj, "Deadlist");
1595 
1596 	if (verbosity < 2)
1597 		return;
1598 
1599 	if (os->os_rootbp->blk_birth == 0)
1600 		return;
1601 
1602 	dump_object(os, 0, verbosity, &print_header);
1603 	object_count = 0;
1604 	if (os->os_userused_dnode &&
1605 	    os->os_userused_dnode->dn_type != 0) {
1606 		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header);
1607 		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header);
1608 	}
1609 
1610 	object = 0;
1611 	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1612 		dump_object(os, object, verbosity, &print_header);
1613 		object_count++;
1614 	}
1615 
1616 	ASSERT3U(object_count, ==, usedobjs);
1617 
1618 	(void) printf("\n");
1619 
1620 	if (error != ESRCH) {
1621 		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
1622 		abort();
1623 	}
1624 }
1625 
1626 static void
1627 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
1628 {
1629 	time_t timestamp = ub->ub_timestamp;
1630 
1631 	(void) printf(header ? header : "");
1632 	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
1633 	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
1634 	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
1635 	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
1636 	(void) printf("\ttimestamp = %llu UTC = %s",
1637 	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
1638 	if (dump_opt['u'] >= 3) {
1639 		char blkbuf[BP_SPRINTF_LEN];
1640 		sprintf_blkptr(blkbuf, &ub->ub_rootbp);
1641 		(void) printf("\trootbp = %s\n", blkbuf);
1642 	}
1643 	(void) printf(footer ? footer : "");
1644 }
1645 
1646 static void
1647 dump_config(spa_t *spa)
1648 {
1649 	dmu_buf_t *db;
1650 	size_t nvsize = 0;
1651 	int error = 0;
1652 
1653 
1654 	error = dmu_bonus_hold(spa->spa_meta_objset,
1655 	    spa->spa_config_object, FTAG, &db);
1656 
1657 	if (error == 0) {
1658 		nvsize = *(uint64_t *)db->db_data;
1659 		dmu_buf_rele(db, FTAG);
1660 
1661 		(void) printf("\nMOS Configuration:\n");
1662 		dump_packed_nvlist(spa->spa_meta_objset,
1663 		    spa->spa_config_object, (void *)&nvsize, 1);
1664 	} else {
1665 		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
1666 		    (u_longlong_t)spa->spa_config_object, error);
1667 	}
1668 }
1669 
1670 static void
1671 dump_cachefile(const char *cachefile)
1672 {
1673 	int fd;
1674 	struct stat64 statbuf;
1675 	char *buf;
1676 	nvlist_t *config;
1677 
1678 	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
1679 		(void) printf("cannot open '%s': %s\n", cachefile,
1680 		    strerror(errno));
1681 		exit(1);
1682 	}
1683 
1684 	if (fstat64(fd, &statbuf) != 0) {
1685 		(void) printf("failed to stat '%s': %s\n", cachefile,
1686 		    strerror(errno));
1687 		exit(1);
1688 	}
1689 
1690 	if ((buf = malloc(statbuf.st_size)) == NULL) {
1691 		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
1692 		    (u_longlong_t)statbuf.st_size);
1693 		exit(1);
1694 	}
1695 
1696 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1697 		(void) fprintf(stderr, "failed to read %llu bytes\n",
1698 		    (u_longlong_t)statbuf.st_size);
1699 		exit(1);
1700 	}
1701 
1702 	(void) close(fd);
1703 
1704 	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
1705 		(void) fprintf(stderr, "failed to unpack nvlist\n");
1706 		exit(1);
1707 	}
1708 
1709 	free(buf);
1710 
1711 	dump_nvlist(config, 0);
1712 
1713 	nvlist_free(config);
1714 }
1715 
1716 #define	ZDB_MAX_UB_HEADER_SIZE 32
1717 
1718 static void
1719 dump_label_uberblocks(vdev_label_t *lbl, uint64_t ashift)
1720 {
1721 	vdev_t vd;
1722 	vdev_t *vdp = &vd;
1723 	char header[ZDB_MAX_UB_HEADER_SIZE];
1724 
1725 	vd.vdev_ashift = ashift;
1726 	vdp->vdev_top = vdp;
1727 
1728 	for (int i = 0; i < VDEV_UBERBLOCK_COUNT(vdp); i++) {
1729 		uint64_t uoff = VDEV_UBERBLOCK_OFFSET(vdp, i);
1730 		uberblock_t *ub = (void *)((char *)lbl + uoff);
1731 
1732 		if (uberblock_verify(ub))
1733 			continue;
1734 		(void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
1735 		    "Uberblock[%d]\n", i);
1736 		dump_uberblock(ub, header, "");
1737 	}
1738 }
1739 
1740 static void
1741 dump_label(const char *dev)
1742 {
1743 	int fd;
1744 	vdev_label_t label;
1745 	char *path, *buf = label.vl_vdev_phys.vp_nvlist;
1746 	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1747 	struct stat64 statbuf;
1748 	uint64_t psize, ashift;
1749 	int len = strlen(dev) + 1;
1750 
1751 	if (strncmp(dev, "/dev/dsk/", 9) == 0) {
1752 		len++;
1753 		path = malloc(len);
1754 		(void) snprintf(path, len, "%s%s", "/dev/rdsk/", dev + 9);
1755 	} else {
1756 		path = strdup(dev);
1757 	}
1758 
1759 	if ((fd = open64(path, O_RDONLY)) < 0) {
1760 		(void) printf("cannot open '%s': %s\n", path, strerror(errno));
1761 		free(path);
1762 		exit(1);
1763 	}
1764 
1765 	if (fstat64(fd, &statbuf) != 0) {
1766 		(void) printf("failed to stat '%s': %s\n", path,
1767 		    strerror(errno));
1768 		free(path);
1769 		(void) close(fd);
1770 		exit(1);
1771 	}
1772 
1773 	if (S_ISBLK(statbuf.st_mode)) {
1774 		(void) printf("cannot use '%s': character device required\n",
1775 		    path);
1776 		free(path);
1777 		(void) close(fd);
1778 		exit(1);
1779 	}
1780 
1781 	psize = statbuf.st_size;
1782 	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
1783 
1784 	for (int l = 0; l < VDEV_LABELS; l++) {
1785 		nvlist_t *config = NULL;
1786 
1787 		(void) printf("--------------------------------------------\n");
1788 		(void) printf("LABEL %d\n", l);
1789 		(void) printf("--------------------------------------------\n");
1790 
1791 		if (pread64(fd, &label, sizeof (label),
1792 		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
1793 			(void) printf("failed to read label %d\n", l);
1794 			continue;
1795 		}
1796 
1797 		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
1798 			(void) printf("failed to unpack label %d\n", l);
1799 			ashift = SPA_MINBLOCKSHIFT;
1800 		} else {
1801 			nvlist_t *vdev_tree = NULL;
1802 
1803 			dump_nvlist(config, 4);
1804 			if ((nvlist_lookup_nvlist(config,
1805 			    ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
1806 			    (nvlist_lookup_uint64(vdev_tree,
1807 			    ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
1808 				ashift = SPA_MINBLOCKSHIFT;
1809 			nvlist_free(config);
1810 		}
1811 		if (dump_opt['u'])
1812 			dump_label_uberblocks(&label, ashift);
1813 	}
1814 
1815 	free(path);
1816 	(void) close(fd);
1817 }
1818 
1819 /*ARGSUSED*/
1820 static int
1821 dump_one_dir(const char *dsname, void *arg)
1822 {
1823 	int error;
1824 	objset_t *os;
1825 
1826 	error = dmu_objset_own(dsname, DMU_OST_ANY, B_TRUE, FTAG, &os);
1827 	if (error) {
1828 		(void) printf("Could not open %s, error %d\n", dsname, error);
1829 		return (0);
1830 	}
1831 	dump_dir(os);
1832 	dmu_objset_disown(os, FTAG);
1833 	fuid_table_destroy();
1834 	sa_loaded = B_FALSE;
1835 	return (0);
1836 }
1837 
1838 /*
1839  * Block statistics.
1840  */
1841 typedef struct zdb_blkstats {
1842 	uint64_t	zb_asize;
1843 	uint64_t	zb_lsize;
1844 	uint64_t	zb_psize;
1845 	uint64_t	zb_count;
1846 } zdb_blkstats_t;
1847 
1848 /*
1849  * Extended object types to report deferred frees and dedup auto-ditto blocks.
1850  */
1851 #define	ZDB_OT_DEFERRED	(DMU_OT_NUMTYPES + 0)
1852 #define	ZDB_OT_DITTO	(DMU_OT_NUMTYPES + 1)
1853 #define	ZDB_OT_TOTAL	(DMU_OT_NUMTYPES + 2)
1854 
1855 static char *zdb_ot_extname[] = {
1856 	"deferred free",
1857 	"dedup ditto",
1858 	"Total",
1859 };
1860 
1861 #define	ZB_TOTAL	DN_MAX_LEVELS
1862 
1863 typedef struct zdb_cb {
1864 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
1865 	uint64_t	zcb_dedup_asize;
1866 	uint64_t	zcb_dedup_blocks;
1867 	uint64_t	zcb_errors[256];
1868 	int		zcb_readfails;
1869 	int		zcb_haderrors;
1870 } zdb_cb_t;
1871 
1872 static void
1873 zdb_count_block(spa_t *spa, zilog_t *zilog, zdb_cb_t *zcb, const blkptr_t *bp,
1874     dmu_object_type_t type)
1875 {
1876 	uint64_t refcnt = 0;
1877 
1878 	ASSERT(type < ZDB_OT_TOTAL);
1879 
1880 	if (zilog && zil_bp_tree_add(zilog, bp) != 0)
1881 		return;
1882 
1883 	for (int i = 0; i < 4; i++) {
1884 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
1885 		int t = (i & 1) ? type : ZDB_OT_TOTAL;
1886 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
1887 
1888 		zb->zb_asize += BP_GET_ASIZE(bp);
1889 		zb->zb_lsize += BP_GET_LSIZE(bp);
1890 		zb->zb_psize += BP_GET_PSIZE(bp);
1891 		zb->zb_count++;
1892 	}
1893 
1894 	if (dump_opt['L'])
1895 		return;
1896 
1897 	if (BP_GET_DEDUP(bp)) {
1898 		ddt_t *ddt;
1899 		ddt_entry_t *dde;
1900 
1901 		ddt = ddt_select(spa, bp);
1902 		ddt_enter(ddt);
1903 		dde = ddt_lookup(ddt, bp, B_FALSE);
1904 
1905 		if (dde == NULL) {
1906 			refcnt = 0;
1907 		} else {
1908 			ddt_phys_t *ddp = ddt_phys_select(dde, bp);
1909 			ddt_phys_decref(ddp);
1910 			refcnt = ddp->ddp_refcnt;
1911 			if (ddt_phys_total_refcnt(dde) == 0)
1912 				ddt_remove(ddt, dde);
1913 		}
1914 		ddt_exit(ddt);
1915 	}
1916 
1917 	VERIFY3U(zio_wait(zio_claim(NULL, spa,
1918 	    refcnt ? 0 : spa_first_txg(spa),
1919 	    bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
1920 }
1921 
1922 /* ARGSUSED */
1923 static int
1924 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp, arc_buf_t *pbuf,
1925     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
1926 {
1927 	zdb_cb_t *zcb = arg;
1928 	char blkbuf[BP_SPRINTF_LEN];
1929 	dmu_object_type_t type;
1930 	boolean_t is_metadata;
1931 
1932 	if (bp == NULL)
1933 		return (0);
1934 
1935 	type = BP_GET_TYPE(bp);
1936 
1937 	zdb_count_block(spa, zilog, zcb, bp, type);
1938 
1939 	is_metadata = (BP_GET_LEVEL(bp) != 0 || dmu_ot[type].ot_metadata);
1940 
1941 	if (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata)) {
1942 		int ioerr;
1943 		size_t size = BP_GET_PSIZE(bp);
1944 		void *data = malloc(size);
1945 		int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
1946 
1947 		/* If it's an intent log block, failure is expected. */
1948 		if (zb->zb_level == ZB_ZIL_LEVEL)
1949 			flags |= ZIO_FLAG_SPECULATIVE;
1950 
1951 		ioerr = zio_wait(zio_read(NULL, spa, bp, data, size,
1952 		    NULL, NULL, ZIO_PRIORITY_ASYNC_READ, flags, zb));
1953 
1954 		free(data);
1955 
1956 		if (ioerr && !(flags & ZIO_FLAG_SPECULATIVE)) {
1957 			zcb->zcb_haderrors = 1;
1958 			zcb->zcb_errors[ioerr]++;
1959 
1960 			if (dump_opt['b'] >= 2)
1961 				sprintf_blkptr(blkbuf, bp);
1962 			else
1963 				blkbuf[0] = '\0';
1964 
1965 			(void) printf("zdb_blkptr_cb: "
1966 			    "Got error %d reading "
1967 			    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
1968 			    ioerr,
1969 			    (u_longlong_t)zb->zb_objset,
1970 			    (u_longlong_t)zb->zb_object,
1971 			    (u_longlong_t)zb->zb_level,
1972 			    (u_longlong_t)zb->zb_blkid,
1973 			    blkbuf);
1974 		}
1975 	}
1976 
1977 	zcb->zcb_readfails = 0;
1978 
1979 	if (dump_opt['b'] >= 4) {
1980 		sprintf_blkptr(blkbuf, bp);
1981 		(void) printf("objset %llu object %llu "
1982 		    "level %lld offset 0x%llx %s\n",
1983 		    (u_longlong_t)zb->zb_objset,
1984 		    (u_longlong_t)zb->zb_object,
1985 		    (longlong_t)zb->zb_level,
1986 		    (u_longlong_t)blkid2offset(dnp, bp, zb),
1987 		    blkbuf);
1988 	}
1989 
1990 	return (0);
1991 }
1992 
1993 static void
1994 zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
1995 {
1996 	vdev_t *vd = sm->sm_ppd;
1997 
1998 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
1999 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
2000 }
2001 
2002 /* ARGSUSED */
2003 static void
2004 zdb_space_map_load(space_map_t *sm)
2005 {
2006 }
2007 
2008 static void
2009 zdb_space_map_unload(space_map_t *sm)
2010 {
2011 	space_map_vacate(sm, zdb_leak, sm);
2012 }
2013 
2014 /* ARGSUSED */
2015 static void
2016 zdb_space_map_claim(space_map_t *sm, uint64_t start, uint64_t size)
2017 {
2018 }
2019 
2020 static space_map_ops_t zdb_space_map_ops = {
2021 	zdb_space_map_load,
2022 	zdb_space_map_unload,
2023 	NULL,	/* alloc */
2024 	zdb_space_map_claim,
2025 	NULL,	/* free */
2026 	NULL	/* maxsize */
2027 };
2028 
2029 static void
2030 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
2031 {
2032 	ddt_bookmark_t ddb = { 0 };
2033 	ddt_entry_t dde;
2034 	int error;
2035 
2036 	while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
2037 		blkptr_t blk;
2038 		ddt_phys_t *ddp = dde.dde_phys;
2039 
2040 		if (ddb.ddb_class == DDT_CLASS_UNIQUE)
2041 			return;
2042 
2043 		ASSERT(ddt_phys_total_refcnt(&dde) > 1);
2044 
2045 		for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2046 			if (ddp->ddp_phys_birth == 0)
2047 				continue;
2048 			ddt_bp_create(ddb.ddb_checksum,
2049 			    &dde.dde_key, ddp, &blk);
2050 			if (p == DDT_PHYS_DITTO) {
2051 				zdb_count_block(spa, NULL, zcb, &blk,
2052 				    ZDB_OT_DITTO);
2053 			} else {
2054 				zcb->zcb_dedup_asize +=
2055 				    BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
2056 				zcb->zcb_dedup_blocks++;
2057 			}
2058 		}
2059 		if (!dump_opt['L']) {
2060 			ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
2061 			ddt_enter(ddt);
2062 			VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
2063 			ddt_exit(ddt);
2064 		}
2065 	}
2066 
2067 	ASSERT(error == ENOENT);
2068 }
2069 
2070 static void
2071 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
2072 {
2073 	if (!dump_opt['L']) {
2074 		vdev_t *rvd = spa->spa_root_vdev;
2075 		for (int c = 0; c < rvd->vdev_children; c++) {
2076 			vdev_t *vd = rvd->vdev_child[c];
2077 			for (int m = 0; m < vd->vdev_ms_count; m++) {
2078 				metaslab_t *msp = vd->vdev_ms[m];
2079 				mutex_enter(&msp->ms_lock);
2080 				space_map_unload(&msp->ms_map);
2081 				VERIFY(space_map_load(&msp->ms_map,
2082 				    &zdb_space_map_ops, SM_ALLOC, &msp->ms_smo,
2083 				    spa->spa_meta_objset) == 0);
2084 				msp->ms_map.sm_ppd = vd;
2085 				mutex_exit(&msp->ms_lock);
2086 			}
2087 		}
2088 	}
2089 
2090 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2091 
2092 	zdb_ddt_leak_init(spa, zcb);
2093 
2094 	spa_config_exit(spa, SCL_CONFIG, FTAG);
2095 }
2096 
2097 static void
2098 zdb_leak_fini(spa_t *spa)
2099 {
2100 	if (!dump_opt['L']) {
2101 		vdev_t *rvd = spa->spa_root_vdev;
2102 		for (int c = 0; c < rvd->vdev_children; c++) {
2103 			vdev_t *vd = rvd->vdev_child[c];
2104 			for (int m = 0; m < vd->vdev_ms_count; m++) {
2105 				metaslab_t *msp = vd->vdev_ms[m];
2106 				mutex_enter(&msp->ms_lock);
2107 				space_map_unload(&msp->ms_map);
2108 				mutex_exit(&msp->ms_lock);
2109 			}
2110 		}
2111 	}
2112 }
2113 
2114 static int
2115 dump_block_stats(spa_t *spa)
2116 {
2117 	zdb_cb_t zcb = { 0 };
2118 	zdb_blkstats_t *zb, *tzb;
2119 	uint64_t norm_alloc, norm_space, total_alloc, total_found;
2120 	int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA | TRAVERSE_HARD;
2121 	int leaks = 0;
2122 
2123 	(void) printf("\nTraversing all blocks %s%s%s%s%s...\n",
2124 	    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
2125 	    (dump_opt['c'] == 1) ? "metadata " : "",
2126 	    dump_opt['c'] ? "checksums " : "",
2127 	    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
2128 	    !dump_opt['L'] ? "nothing leaked " : "");
2129 
2130 	/*
2131 	 * Load all space maps as SM_ALLOC maps, then traverse the pool
2132 	 * claiming each block we discover.  If the pool is perfectly
2133 	 * consistent, the space maps will be empty when we're done.
2134 	 * Anything left over is a leak; any block we can't claim (because
2135 	 * it's not part of any space map) is a double allocation,
2136 	 * reference to a freed block, or an unclaimed log block.
2137 	 */
2138 	zdb_leak_init(spa, &zcb);
2139 
2140 	/*
2141 	 * If there's a deferred-free bplist, process that first.
2142 	 */
2143 	if (spa->spa_deferred_bplist_obj != 0) {
2144 		bplist_t *bpl = &spa->spa_deferred_bplist;
2145 		blkptr_t blk;
2146 		uint64_t itor = 0;
2147 
2148 		VERIFY(0 == bplist_open(bpl, spa->spa_meta_objset,
2149 		    spa->spa_deferred_bplist_obj));
2150 
2151 		while (bplist_iterate(bpl, &itor, &blk) == 0) {
2152 			if (dump_opt['b'] >= 4) {
2153 				char blkbuf[BP_SPRINTF_LEN];
2154 				sprintf_blkptr(blkbuf, &blk);
2155 				(void) printf("[%s] %s\n",
2156 				    "deferred free", blkbuf);
2157 			}
2158 			zdb_count_block(spa, NULL, &zcb, &blk, ZDB_OT_DEFERRED);
2159 		}
2160 
2161 		bplist_close(bpl);
2162 	}
2163 
2164 	if (dump_opt['c'] > 1)
2165 		flags |= TRAVERSE_PREFETCH_DATA;
2166 
2167 	zcb.zcb_haderrors |= traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
2168 
2169 	if (zcb.zcb_haderrors) {
2170 		(void) printf("\nError counts:\n\n");
2171 		(void) printf("\t%5s  %s\n", "errno", "count");
2172 		for (int e = 0; e < 256; e++) {
2173 			if (zcb.zcb_errors[e] != 0) {
2174 				(void) printf("\t%5d  %llu\n",
2175 				    e, (u_longlong_t)zcb.zcb_errors[e]);
2176 			}
2177 		}
2178 	}
2179 
2180 	/*
2181 	 * Report any leaked segments.
2182 	 */
2183 	zdb_leak_fini(spa);
2184 
2185 	tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
2186 
2187 	norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
2188 	norm_space = metaslab_class_get_space(spa_normal_class(spa));
2189 
2190 	total_alloc = norm_alloc + metaslab_class_get_alloc(spa_log_class(spa));
2191 	total_found = tzb->zb_asize - zcb.zcb_dedup_asize;
2192 
2193 	if (total_found == total_alloc) {
2194 		if (!dump_opt['L'])
2195 			(void) printf("\n\tNo leaks (block sum matches space"
2196 			    " maps exactly)\n");
2197 	} else {
2198 		(void) printf("block traversal size %llu != alloc %llu "
2199 		    "(%s %lld)\n",
2200 		    (u_longlong_t)total_found,
2201 		    (u_longlong_t)total_alloc,
2202 		    (dump_opt['L']) ? "unreachable" : "leaked",
2203 		    (longlong_t)(total_alloc - total_found));
2204 		leaks = 1;
2205 	}
2206 
2207 	if (tzb->zb_count == 0)
2208 		return (2);
2209 
2210 	(void) printf("\n");
2211 	(void) printf("\tbp count:      %10llu\n",
2212 	    (u_longlong_t)tzb->zb_count);
2213 	(void) printf("\tbp logical:    %10llu      avg: %6llu\n",
2214 	    (u_longlong_t)tzb->zb_lsize,
2215 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
2216 	(void) printf("\tbp physical:   %10llu      avg:"
2217 	    " %6llu     compression: %6.2f\n",
2218 	    (u_longlong_t)tzb->zb_psize,
2219 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
2220 	    (double)tzb->zb_lsize / tzb->zb_psize);
2221 	(void) printf("\tbp allocated:  %10llu      avg:"
2222 	    " %6llu     compression: %6.2f\n",
2223 	    (u_longlong_t)tzb->zb_asize,
2224 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
2225 	    (double)tzb->zb_lsize / tzb->zb_asize);
2226 	(void) printf("\tbp deduped:    %10llu    ref>1:"
2227 	    " %6llu   deduplication: %6.2f\n",
2228 	    (u_longlong_t)zcb.zcb_dedup_asize,
2229 	    (u_longlong_t)zcb.zcb_dedup_blocks,
2230 	    (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
2231 	(void) printf("\tSPA allocated: %10llu     used: %5.2f%%\n",
2232 	    (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
2233 
2234 	if (dump_opt['b'] >= 2) {
2235 		int l, t, level;
2236 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
2237 		    "\t  avg\t comp\t%%Total\tType\n");
2238 
2239 		for (t = 0; t <= ZDB_OT_TOTAL; t++) {
2240 			char csize[32], lsize[32], psize[32], asize[32];
2241 			char avg[32];
2242 			char *typename;
2243 
2244 			if (t < DMU_OT_NUMTYPES)
2245 				typename = dmu_ot[t].ot_name;
2246 			else
2247 				typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
2248 
2249 			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
2250 				(void) printf("%6s\t%5s\t%5s\t%5s"
2251 				    "\t%5s\t%5s\t%6s\t%s\n",
2252 				    "-",
2253 				    "-",
2254 				    "-",
2255 				    "-",
2256 				    "-",
2257 				    "-",
2258 				    "-",
2259 				    typename);
2260 				continue;
2261 			}
2262 
2263 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
2264 				level = (l == -1 ? ZB_TOTAL : l);
2265 				zb = &zcb.zcb_type[level][t];
2266 
2267 				if (zb->zb_asize == 0)
2268 					continue;
2269 
2270 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
2271 					continue;
2272 
2273 				if (level == 0 && zb->zb_asize ==
2274 				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
2275 					continue;
2276 
2277 				zdb_nicenum(zb->zb_count, csize);
2278 				zdb_nicenum(zb->zb_lsize, lsize);
2279 				zdb_nicenum(zb->zb_psize, psize);
2280 				zdb_nicenum(zb->zb_asize, asize);
2281 				zdb_nicenum(zb->zb_asize / zb->zb_count, avg);
2282 
2283 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
2284 				    "\t%5.2f\t%6.2f\t",
2285 				    csize, lsize, psize, asize, avg,
2286 				    (double)zb->zb_lsize / zb->zb_psize,
2287 				    100.0 * zb->zb_asize / tzb->zb_asize);
2288 
2289 				if (level == ZB_TOTAL)
2290 					(void) printf("%s\n", typename);
2291 				else
2292 					(void) printf("    L%d %s\n",
2293 					    level, typename);
2294 			}
2295 		}
2296 	}
2297 
2298 	(void) printf("\n");
2299 
2300 	if (leaks)
2301 		return (2);
2302 
2303 	if (zcb.zcb_haderrors)
2304 		return (3);
2305 
2306 	return (0);
2307 }
2308 
2309 typedef struct zdb_ddt_entry {
2310 	ddt_key_t	zdde_key;
2311 	uint64_t	zdde_ref_blocks;
2312 	uint64_t	zdde_ref_lsize;
2313 	uint64_t	zdde_ref_psize;
2314 	uint64_t	zdde_ref_dsize;
2315 	avl_node_t	zdde_node;
2316 } zdb_ddt_entry_t;
2317 
2318 /* ARGSUSED */
2319 static int
2320 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2321     arc_buf_t *pbuf, const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
2322 {
2323 	avl_tree_t *t = arg;
2324 	avl_index_t where;
2325 	zdb_ddt_entry_t *zdde, zdde_search;
2326 
2327 	if (bp == NULL)
2328 		return (0);
2329 
2330 	if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
2331 		(void) printf("traversing objset %llu, %llu objects, "
2332 		    "%lu blocks so far\n",
2333 		    (u_longlong_t)zb->zb_objset,
2334 		    (u_longlong_t)bp->blk_fill,
2335 		    avl_numnodes(t));
2336 	}
2337 
2338 	if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
2339 	    BP_GET_LEVEL(bp) > 0 || dmu_ot[BP_GET_TYPE(bp)].ot_metadata)
2340 		return (0);
2341 
2342 	ddt_key_fill(&zdde_search.zdde_key, bp);
2343 
2344 	zdde = avl_find(t, &zdde_search, &where);
2345 
2346 	if (zdde == NULL) {
2347 		zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
2348 		zdde->zdde_key = zdde_search.zdde_key;
2349 		avl_insert(t, zdde, where);
2350 	}
2351 
2352 	zdde->zdde_ref_blocks += 1;
2353 	zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
2354 	zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
2355 	zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
2356 
2357 	return (0);
2358 }
2359 
2360 static void
2361 dump_simulated_ddt(spa_t *spa)
2362 {
2363 	avl_tree_t t;
2364 	void *cookie = NULL;
2365 	zdb_ddt_entry_t *zdde;
2366 	ddt_histogram_t ddh_total = { 0 };
2367 	ddt_stat_t dds_total = { 0 };
2368 
2369 	avl_create(&t, ddt_entry_compare,
2370 	    sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
2371 
2372 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2373 
2374 	(void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2375 	    zdb_ddt_add_cb, &t);
2376 
2377 	spa_config_exit(spa, SCL_CONFIG, FTAG);
2378 
2379 	while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
2380 		ddt_stat_t dds;
2381 		uint64_t refcnt = zdde->zdde_ref_blocks;
2382 		ASSERT(refcnt != 0);
2383 
2384 		dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
2385 		dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
2386 		dds.dds_psize = zdde->zdde_ref_psize / refcnt;
2387 		dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
2388 
2389 		dds.dds_ref_blocks = zdde->zdde_ref_blocks;
2390 		dds.dds_ref_lsize = zdde->zdde_ref_lsize;
2391 		dds.dds_ref_psize = zdde->zdde_ref_psize;
2392 		dds.dds_ref_dsize = zdde->zdde_ref_dsize;
2393 
2394 		ddt_stat_add(&ddh_total.ddh_stat[highbit(refcnt) - 1], &dds, 0);
2395 
2396 		umem_free(zdde, sizeof (*zdde));
2397 	}
2398 
2399 	avl_destroy(&t);
2400 
2401 	ddt_histogram_stat(&dds_total, &ddh_total);
2402 
2403 	(void) printf("Simulated DDT histogram:\n");
2404 
2405 	zpool_dump_ddt(&dds_total, &ddh_total);
2406 
2407 	dump_dedup_ratio(&dds_total);
2408 }
2409 
2410 static void
2411 dump_zpool(spa_t *spa)
2412 {
2413 	dsl_pool_t *dp = spa_get_dsl(spa);
2414 	int rc = 0;
2415 
2416 	if (dump_opt['S']) {
2417 		dump_simulated_ddt(spa);
2418 		return;
2419 	}
2420 
2421 	if (!dump_opt['e'] && dump_opt['C'] > 1) {
2422 		(void) printf("\nCached configuration:\n");
2423 		dump_nvlist(spa->spa_config, 8);
2424 	}
2425 
2426 	if (dump_opt['C'])
2427 		dump_config(spa);
2428 
2429 	if (dump_opt['u'])
2430 		dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
2431 
2432 	if (dump_opt['D'])
2433 		dump_all_ddts(spa);
2434 
2435 	if (dump_opt['d'] > 2 || dump_opt['m'])
2436 		dump_metaslabs(spa);
2437 
2438 	if (dump_opt['d'] || dump_opt['i']) {
2439 		dump_dir(dp->dp_meta_objset);
2440 		if (dump_opt['d'] >= 3) {
2441 			dump_bplist(dp->dp_meta_objset,
2442 			    spa->spa_deferred_bplist_obj, "Deferred frees");
2443 			dump_dtl(spa->spa_root_vdev, 0);
2444 		}
2445 		(void) dmu_objset_find(spa_name(spa), dump_one_dir,
2446 		    NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
2447 	}
2448 	if (dump_opt['b'] || dump_opt['c'])
2449 		rc = dump_block_stats(spa);
2450 
2451 	if (dump_opt['s'])
2452 		show_pool_stats(spa);
2453 
2454 	if (dump_opt['h'])
2455 		dump_history(spa);
2456 
2457 	if (rc != 0)
2458 		exit(rc);
2459 }
2460 
2461 #define	ZDB_FLAG_CHECKSUM	0x0001
2462 #define	ZDB_FLAG_DECOMPRESS	0x0002
2463 #define	ZDB_FLAG_BSWAP		0x0004
2464 #define	ZDB_FLAG_GBH		0x0008
2465 #define	ZDB_FLAG_INDIRECT	0x0010
2466 #define	ZDB_FLAG_PHYS		0x0020
2467 #define	ZDB_FLAG_RAW		0x0040
2468 #define	ZDB_FLAG_PRINT_BLKPTR	0x0080
2469 
2470 int flagbits[256];
2471 
2472 static void
2473 zdb_print_blkptr(blkptr_t *bp, int flags)
2474 {
2475 	char blkbuf[BP_SPRINTF_LEN];
2476 
2477 	if (flags & ZDB_FLAG_BSWAP)
2478 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
2479 
2480 	sprintf_blkptr(blkbuf, bp);
2481 	(void) printf("%s\n", blkbuf);
2482 }
2483 
2484 static void
2485 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
2486 {
2487 	int i;
2488 
2489 	for (i = 0; i < nbps; i++)
2490 		zdb_print_blkptr(&bp[i], flags);
2491 }
2492 
2493 static void
2494 zdb_dump_gbh(void *buf, int flags)
2495 {
2496 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
2497 }
2498 
2499 static void
2500 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
2501 {
2502 	if (flags & ZDB_FLAG_BSWAP)
2503 		byteswap_uint64_array(buf, size);
2504 	(void) write(1, buf, size);
2505 }
2506 
2507 static void
2508 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
2509 {
2510 	uint64_t *d = (uint64_t *)buf;
2511 	int nwords = size / sizeof (uint64_t);
2512 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
2513 	int i, j;
2514 	char *hdr, *c;
2515 
2516 
2517 	if (do_bswap)
2518 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
2519 	else
2520 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
2521 
2522 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
2523 
2524 	for (i = 0; i < nwords; i += 2) {
2525 		(void) printf("%06llx:  %016llx  %016llx  ",
2526 		    (u_longlong_t)(i * sizeof (uint64_t)),
2527 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
2528 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
2529 
2530 		c = (char *)&d[i];
2531 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
2532 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
2533 		(void) printf("\n");
2534 	}
2535 }
2536 
2537 /*
2538  * There are two acceptable formats:
2539  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
2540  *	child[.child]*    - For example: 0.1.1
2541  *
2542  * The second form can be used to specify arbitrary vdevs anywhere
2543  * in the heirarchy.  For example, in a pool with a mirror of
2544  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
2545  */
2546 static vdev_t *
2547 zdb_vdev_lookup(vdev_t *vdev, char *path)
2548 {
2549 	char *s, *p, *q;
2550 	int i;
2551 
2552 	if (vdev == NULL)
2553 		return (NULL);
2554 
2555 	/* First, assume the x.x.x.x format */
2556 	i = (int)strtoul(path, &s, 10);
2557 	if (s == path || (s && *s != '.' && *s != '\0'))
2558 		goto name;
2559 	if (i < 0 || i >= vdev->vdev_children)
2560 		return (NULL);
2561 
2562 	vdev = vdev->vdev_child[i];
2563 	if (*s == '\0')
2564 		return (vdev);
2565 	return (zdb_vdev_lookup(vdev, s+1));
2566 
2567 name:
2568 	for (i = 0; i < vdev->vdev_children; i++) {
2569 		vdev_t *vc = vdev->vdev_child[i];
2570 
2571 		if (vc->vdev_path == NULL) {
2572 			vc = zdb_vdev_lookup(vc, path);
2573 			if (vc == NULL)
2574 				continue;
2575 			else
2576 				return (vc);
2577 		}
2578 
2579 		p = strrchr(vc->vdev_path, '/');
2580 		p = p ? p + 1 : vc->vdev_path;
2581 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2582 
2583 		if (strcmp(vc->vdev_path, path) == 0)
2584 			return (vc);
2585 		if (strcmp(p, path) == 0)
2586 			return (vc);
2587 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2588 			return (vc);
2589 	}
2590 
2591 	return (NULL);
2592 }
2593 
2594 /*
2595  * Read a block from a pool and print it out.  The syntax of the
2596  * block descriptor is:
2597  *
2598  *	pool:vdev_specifier:offset:size[:flags]
2599  *
2600  *	pool           - The name of the pool you wish to read from
2601  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2602  *	offset         - offset, in hex, in bytes
2603  *	size           - Amount of data to read, in hex, in bytes
2604  *	flags          - A string of characters specifying options
2605  *		 b: Decode a blkptr at given offset within block
2606  *		*c: Calculate and display checksums
2607  *		 d: Decompress data before dumping
2608  *		 e: Byteswap data before dumping
2609  *		 g: Display data as a gang block header
2610  *		 i: Display as an indirect block
2611  *		 p: Do I/O to physical offset
2612  *		 r: Dump raw data to stdout
2613  *
2614  *              * = not yet implemented
2615  */
2616 static void
2617 zdb_read_block(char *thing, spa_t *spa)
2618 {
2619 	blkptr_t blk, *bp = &blk;
2620 	dva_t *dva = bp->blk_dva;
2621 	int flags = 0;
2622 	uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
2623 	zio_t *zio;
2624 	vdev_t *vd;
2625 	void *pbuf, *lbuf, *buf;
2626 	char *s, *p, *dup, *vdev, *flagstr;
2627 	int i, error;
2628 
2629 	dup = strdup(thing);
2630 	s = strtok(dup, ":");
2631 	vdev = s ? s : "";
2632 	s = strtok(NULL, ":");
2633 	offset = strtoull(s ? s : "", NULL, 16);
2634 	s = strtok(NULL, ":");
2635 	size = strtoull(s ? s : "", NULL, 16);
2636 	s = strtok(NULL, ":");
2637 	flagstr = s ? s : "";
2638 
2639 	s = NULL;
2640 	if (size == 0)
2641 		s = "size must not be zero";
2642 	if (!IS_P2ALIGNED(size, DEV_BSIZE))
2643 		s = "size must be a multiple of sector size";
2644 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
2645 		s = "offset must be a multiple of sector size";
2646 	if (s) {
2647 		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
2648 		free(dup);
2649 		return;
2650 	}
2651 
2652 	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
2653 		for (i = 0; flagstr[i]; i++) {
2654 			int bit = flagbits[(uchar_t)flagstr[i]];
2655 
2656 			if (bit == 0) {
2657 				(void) printf("***Invalid flag: %c\n",
2658 				    flagstr[i]);
2659 				continue;
2660 			}
2661 			flags |= bit;
2662 
2663 			/* If it's not something with an argument, keep going */
2664 			if ((bit & (ZDB_FLAG_CHECKSUM |
2665 			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
2666 				continue;
2667 
2668 			p = &flagstr[i + 1];
2669 			if (bit == ZDB_FLAG_PRINT_BLKPTR)
2670 				blkptr_offset = strtoull(p, &p, 16);
2671 			if (*p != ':' && *p != '\0') {
2672 				(void) printf("***Invalid flag arg: '%s'\n", s);
2673 				free(dup);
2674 				return;
2675 			}
2676 		}
2677 	}
2678 
2679 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2680 	if (vd == NULL) {
2681 		(void) printf("***Invalid vdev: %s\n", vdev);
2682 		free(dup);
2683 		return;
2684 	} else {
2685 		if (vd->vdev_path)
2686 			(void) fprintf(stderr, "Found vdev: %s\n",
2687 			    vd->vdev_path);
2688 		else
2689 			(void) fprintf(stderr, "Found vdev type: %s\n",
2690 			    vd->vdev_ops->vdev_op_type);
2691 	}
2692 
2693 	psize = size;
2694 	lsize = size;
2695 
2696 	pbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2697 	lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2698 
2699 	BP_ZERO(bp);
2700 
2701 	DVA_SET_VDEV(&dva[0], vd->vdev_id);
2702 	DVA_SET_OFFSET(&dva[0], offset);
2703 	DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
2704 	DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
2705 
2706 	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
2707 
2708 	BP_SET_LSIZE(bp, lsize);
2709 	BP_SET_PSIZE(bp, psize);
2710 	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
2711 	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
2712 	BP_SET_TYPE(bp, DMU_OT_NONE);
2713 	BP_SET_LEVEL(bp, 0);
2714 	BP_SET_DEDUP(bp, 0);
2715 	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
2716 
2717 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
2718 	zio = zio_root(spa, NULL, NULL, 0);
2719 
2720 	if (vd == vd->vdev_top) {
2721 		/*
2722 		 * Treat this as a normal block read.
2723 		 */
2724 		zio_nowait(zio_read(zio, spa, bp, pbuf, psize, NULL, NULL,
2725 		    ZIO_PRIORITY_SYNC_READ,
2726 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
2727 	} else {
2728 		/*
2729 		 * Treat this as a vdev child I/O.
2730 		 */
2731 		zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pbuf, psize,
2732 		    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
2733 		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2734 		    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
2735 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL, NULL));
2736 	}
2737 
2738 	error = zio_wait(zio);
2739 	spa_config_exit(spa, SCL_STATE, FTAG);
2740 
2741 	if (error) {
2742 		(void) printf("Read of %s failed, error: %d\n", thing, error);
2743 		goto out;
2744 	}
2745 
2746 	if (flags & ZDB_FLAG_DECOMPRESS) {
2747 		/*
2748 		 * We don't know how the data was compressed, so just try
2749 		 * every decompress function at every inflated blocksize.
2750 		 */
2751 		enum zio_compress c;
2752 		void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2753 		void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2754 
2755 		bcopy(pbuf, pbuf2, psize);
2756 
2757 		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf + psize,
2758 		    SPA_MAXBLOCKSIZE - psize) == 0);
2759 
2760 		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
2761 		    SPA_MAXBLOCKSIZE - psize) == 0);
2762 
2763 		for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
2764 		    lsize -= SPA_MINBLOCKSIZE) {
2765 			for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
2766 				if (zio_decompress_data(c, pbuf, lbuf,
2767 				    psize, lsize) == 0 &&
2768 				    zio_decompress_data(c, pbuf2, lbuf2,
2769 				    psize, lsize) == 0 &&
2770 				    bcmp(lbuf, lbuf2, lsize) == 0)
2771 					break;
2772 			}
2773 			if (c != ZIO_COMPRESS_FUNCTIONS)
2774 				break;
2775 			lsize -= SPA_MINBLOCKSIZE;
2776 		}
2777 
2778 		umem_free(pbuf2, SPA_MAXBLOCKSIZE);
2779 		umem_free(lbuf2, SPA_MAXBLOCKSIZE);
2780 
2781 		if (lsize <= psize) {
2782 			(void) printf("Decompress of %s failed\n", thing);
2783 			goto out;
2784 		}
2785 		buf = lbuf;
2786 		size = lsize;
2787 	} else {
2788 		buf = pbuf;
2789 		size = psize;
2790 	}
2791 
2792 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2793 		zdb_print_blkptr((blkptr_t *)(void *)
2794 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2795 	else if (flags & ZDB_FLAG_RAW)
2796 		zdb_dump_block_raw(buf, size, flags);
2797 	else if (flags & ZDB_FLAG_INDIRECT)
2798 		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2799 		    flags);
2800 	else if (flags & ZDB_FLAG_GBH)
2801 		zdb_dump_gbh(buf, flags);
2802 	else
2803 		zdb_dump_block(thing, buf, size, flags);
2804 
2805 out:
2806 	umem_free(pbuf, SPA_MAXBLOCKSIZE);
2807 	umem_free(lbuf, SPA_MAXBLOCKSIZE);
2808 	free(dup);
2809 }
2810 
2811 static boolean_t
2812 pool_match(nvlist_t *cfg, char *tgt)
2813 {
2814 	uint64_t v, guid = strtoull(tgt, NULL, 0);
2815 	char *s;
2816 
2817 	if (guid != 0) {
2818 		if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
2819 			return (v == guid);
2820 	} else {
2821 		if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
2822 			return (strcmp(s, tgt) == 0);
2823 	}
2824 	return (B_FALSE);
2825 }
2826 
2827 static char *
2828 find_zpool(char **target, nvlist_t **configp, int dirc, char **dirv)
2829 {
2830 	nvlist_t *pools;
2831 	nvlist_t *match = NULL;
2832 	char *name = NULL;
2833 	char *sepp = NULL;
2834 	char sep;
2835 	int count = 0;
2836 	importargs_t args = { 0 };
2837 
2838 	args.paths = dirc;
2839 	args.path = dirv;
2840 	args.can_be_active = B_TRUE;
2841 
2842 	if ((sepp = strpbrk(*target, "/@")) != NULL) {
2843 		sep = *sepp;
2844 		*sepp = '\0';
2845 	}
2846 
2847 	pools = zpool_search_import(g_zfs, &args);
2848 
2849 	if (pools != NULL) {
2850 		nvpair_t *elem = NULL;
2851 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2852 			verify(nvpair_value_nvlist(elem, configp) == 0);
2853 			if (pool_match(*configp, *target)) {
2854 				count++;
2855 				if (match != NULL) {
2856 					/* print previously found config */
2857 					if (name != NULL) {
2858 						(void) printf("%s\n", name);
2859 						dump_nvlist(match, 8);
2860 						name = NULL;
2861 					}
2862 					(void) printf("%s\n",
2863 					    nvpair_name(elem));
2864 					dump_nvlist(*configp, 8);
2865 				} else {
2866 					match = *configp;
2867 					name = nvpair_name(elem);
2868 				}
2869 			}
2870 		}
2871 	}
2872 	if (count > 1)
2873 		(void) fatal("\tMatched %d pools - use pool GUID "
2874 		    "instead of pool name or \n"
2875 		    "\tpool name part of a dataset name to select pool", count);
2876 
2877 	if (sepp)
2878 		*sepp = sep;
2879 	/*
2880 	 * If pool GUID was specified for pool id, replace it with pool name
2881 	 */
2882 	if (name && (strstr(*target, name) != *target)) {
2883 		int sz = 1 + strlen(name) + ((sepp) ? strlen(sepp) : 0);
2884 
2885 		*target = umem_alloc(sz, UMEM_NOFAIL);
2886 		(void) snprintf(*target, sz, "%s%s", name, sepp ? sepp : "");
2887 	}
2888 
2889 	*configp = name ? match : NULL;
2890 
2891 	return (name);
2892 }
2893 
2894 int
2895 main(int argc, char **argv)
2896 {
2897 	int i, c;
2898 	struct rlimit rl = { 1024, 1024 };
2899 	spa_t *spa = NULL;
2900 	objset_t *os = NULL;
2901 	int dump_all = 1;
2902 	int verbose = 0;
2903 	int error = 0;
2904 	char **searchdirs = NULL;
2905 	int nsearch = 0;
2906 	char *target;
2907 	nvlist_t *policy = NULL;
2908 	uint64_t max_txg = UINT64_MAX;
2909 	int rewind = ZPOOL_NEVER_REWIND;
2910 
2911 	(void) setrlimit(RLIMIT_NOFILE, &rl);
2912 	(void) enable_extended_FILE_stdio(-1, -1);
2913 
2914 	dprintf_setup(&argc, argv);
2915 
2916 	while ((c = getopt(argc, argv, "bcdhilmsuCDRSAFLXevp:t:U:P")) != -1) {
2917 		switch (c) {
2918 		case 'b':
2919 		case 'c':
2920 		case 'd':
2921 		case 'h':
2922 		case 'i':
2923 		case 'l':
2924 		case 'm':
2925 		case 's':
2926 		case 'u':
2927 		case 'C':
2928 		case 'D':
2929 		case 'R':
2930 		case 'S':
2931 			dump_opt[c]++;
2932 			dump_all = 0;
2933 			break;
2934 		case 'A':
2935 		case 'F':
2936 		case 'L':
2937 		case 'X':
2938 		case 'e':
2939 		case 'P':
2940 			dump_opt[c]++;
2941 			break;
2942 		case 'v':
2943 			verbose++;
2944 			break;
2945 		case 'p':
2946 			if (searchdirs == NULL) {
2947 				searchdirs = umem_alloc(sizeof (char *),
2948 				    UMEM_NOFAIL);
2949 			} else {
2950 				char **tmp = umem_alloc((nsearch + 1) *
2951 				    sizeof (char *), UMEM_NOFAIL);
2952 				bcopy(searchdirs, tmp, nsearch *
2953 				    sizeof (char *));
2954 				umem_free(searchdirs,
2955 				    nsearch * sizeof (char *));
2956 				searchdirs = tmp;
2957 			}
2958 			searchdirs[nsearch++] = optarg;
2959 			break;
2960 		case 't':
2961 			max_txg = strtoull(optarg, NULL, 0);
2962 			if (max_txg < TXG_INITIAL) {
2963 				(void) fprintf(stderr, "incorrect txg "
2964 				    "specified: %s\n", optarg);
2965 				usage();
2966 			}
2967 			break;
2968 		case 'U':
2969 			spa_config_path = optarg;
2970 			break;
2971 		default:
2972 			usage();
2973 			break;
2974 		}
2975 	}
2976 
2977 	if (!dump_opt['e'] && searchdirs != NULL) {
2978 		(void) fprintf(stderr, "-p option requires use of -e\n");
2979 		usage();
2980 	}
2981 
2982 	kernel_init(FREAD);
2983 	g_zfs = libzfs_init();
2984 	ASSERT(g_zfs != NULL);
2985 
2986 	if (dump_all)
2987 		verbose = MAX(verbose, 1);
2988 
2989 	for (c = 0; c < 256; c++) {
2990 		if (dump_all && !strchr("elAFLRSXP", c))
2991 			dump_opt[c] = 1;
2992 		if (dump_opt[c])
2993 			dump_opt[c] += verbose;
2994 	}
2995 
2996 	aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
2997 	zfs_recover = (dump_opt['A'] > 1);
2998 
2999 	argc -= optind;
3000 	argv += optind;
3001 
3002 	if (argc < 2 && dump_opt['R'])
3003 		usage();
3004 	if (argc < 1) {
3005 		if (!dump_opt['e'] && dump_opt['C']) {
3006 			dump_cachefile(spa_config_path);
3007 			return (0);
3008 		}
3009 		usage();
3010 	}
3011 
3012 	if (dump_opt['l']) {
3013 		dump_label(argv[0]);
3014 		return (0);
3015 	}
3016 
3017 	if (dump_opt['X'] || dump_opt['F'])
3018 		rewind = ZPOOL_DO_REWIND |
3019 		    (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
3020 
3021 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
3022 	    nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, max_txg) != 0 ||
3023 	    nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind) != 0)
3024 		fatal("internal error: %s", strerror(ENOMEM));
3025 
3026 	error = 0;
3027 	target = argv[0];
3028 
3029 	if (dump_opt['e']) {
3030 		nvlist_t *cfg = NULL;
3031 		char *name = find_zpool(&target, &cfg, nsearch, searchdirs);
3032 
3033 		error = ENOENT;
3034 		if (name) {
3035 			if (dump_opt['C'] > 1) {
3036 				(void) printf("\nConfiguration for import:\n");
3037 				dump_nvlist(cfg, 8);
3038 			}
3039 			if (nvlist_add_nvlist(cfg,
3040 			    ZPOOL_REWIND_POLICY, policy) != 0) {
3041 				fatal("can't open '%s': %s",
3042 				    target, strerror(ENOMEM));
3043 			}
3044 			if ((error = spa_import(name, cfg, NULL)) != 0)
3045 				error = spa_import_verbatim(name, cfg, NULL);
3046 		}
3047 	}
3048 
3049 	if (error == 0) {
3050 		if (strpbrk(target, "/@") == NULL || dump_opt['R']) {
3051 			error = spa_open_rewind(target, &spa, FTAG, policy,
3052 			    NULL);
3053 			if (error) {
3054 				/*
3055 				 * If we're missing the log device then
3056 				 * try opening the pool after clearing the
3057 				 * log state.
3058 				 */
3059 				mutex_enter(&spa_namespace_lock);
3060 				if ((spa = spa_lookup(target)) != NULL &&
3061 				    spa->spa_log_state == SPA_LOG_MISSING) {
3062 					spa->spa_log_state = SPA_LOG_CLEAR;
3063 					error = 0;
3064 				}
3065 				mutex_exit(&spa_namespace_lock);
3066 
3067 				if (!error) {
3068 					error = spa_open_rewind(target, &spa,
3069 					    FTAG, policy, NULL);
3070 				}
3071 			}
3072 		} else {
3073 			error = dmu_objset_own(target, DMU_OST_ANY,
3074 			    B_TRUE, FTAG, &os);
3075 		}
3076 	}
3077 	nvlist_free(policy);
3078 
3079 	if (error)
3080 		fatal("can't open '%s': %s", target, strerror(error));
3081 
3082 	argv++;
3083 	argc--;
3084 	if (!dump_opt['R']) {
3085 		if (argc > 0) {
3086 			zopt_objects = argc;
3087 			zopt_object = calloc(zopt_objects, sizeof (uint64_t));
3088 			for (i = 0; i < zopt_objects; i++) {
3089 				errno = 0;
3090 				zopt_object[i] = strtoull(argv[i], NULL, 0);
3091 				if (zopt_object[i] == 0 && errno != 0)
3092 					fatal("bad number %s: %s",
3093 					    argv[i], strerror(errno));
3094 			}
3095 		}
3096 		(os != NULL) ? dump_dir(os) : dump_zpool(spa);
3097 	} else {
3098 		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
3099 		flagbits['c'] = ZDB_FLAG_CHECKSUM;
3100 		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
3101 		flagbits['e'] = ZDB_FLAG_BSWAP;
3102 		flagbits['g'] = ZDB_FLAG_GBH;
3103 		flagbits['i'] = ZDB_FLAG_INDIRECT;
3104 		flagbits['p'] = ZDB_FLAG_PHYS;
3105 		flagbits['r'] = ZDB_FLAG_RAW;
3106 
3107 		for (i = 0; i < argc; i++)
3108 			zdb_read_block(argv[i], spa);
3109 	}
3110 
3111 	(os != NULL) ? dmu_objset_disown(os, FTAG) : spa_close(spa, FTAG);
3112 
3113 	fuid_table_destroy();
3114 	sa_loaded = B_FALSE;
3115 
3116 	libzfs_fini(g_zfs);
3117 	kernel_fini();
3118 
3119 	return (0);
3120 }
3121