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