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