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