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