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