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