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