xref: /titanic_51/usr/src/cmd/zdb/zdb.c (revision ad601a0502a167436cd68b185fff0eb78c34777b)
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  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <stdio.h>
27 #include <stdio_ext.h>
28 #include <stdlib.h>
29 #include <ctype.h>
30 #include <sys/zfs_context.h>
31 #include <sys/spa.h>
32 #include <sys/spa_impl.h>
33 #include <sys/dmu.h>
34 #include <sys/zap.h>
35 #include <sys/fs/zfs.h>
36 #include <sys/zfs_znode.h>
37 #include <sys/vdev.h>
38 #include <sys/vdev_impl.h>
39 #include <sys/metaslab_impl.h>
40 #include <sys/dmu_objset.h>
41 #include <sys/dsl_dir.h>
42 #include <sys/dsl_dataset.h>
43 #include <sys/dsl_pool.h>
44 #include <sys/dbuf.h>
45 #include <sys/zil.h>
46 #include <sys/zil_impl.h>
47 #include <sys/stat.h>
48 #include <sys/resource.h>
49 #include <sys/dmu_traverse.h>
50 #include <sys/zio_checksum.h>
51 #include <sys/zio_compress.h>
52 #include <sys/zfs_fuid.h>
53 #include <sys/arc.h>
54 #include <sys/ddt.h>
55 #undef ZFS_MAXNAMELEN
56 #undef verify
57 #include <libzfs.h>
58 
59 #define	ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ? \
60     zio_compress_table[(idx)].ci_name : "UNKNOWN")
61 #define	ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ? \
62     zio_checksum_table[(idx)].ci_name : "UNKNOWN")
63 #define	ZDB_OT_NAME(idx) ((idx) < DMU_OT_NUMTYPES ? \
64     dmu_ot[(idx)].ot_name : "UNKNOWN")
65 #define	ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) : DMU_OT_NUMTYPES)
66 
67 const char cmdname[] = "zdb";
68 uint8_t dump_opt[256];
69 
70 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
71 
72 extern void dump_intent_log(zilog_t *);
73 uint64_t *zopt_object = NULL;
74 int zopt_objects = 0;
75 libzfs_handle_t *g_zfs;
76 
77 /*
78  * These libumem hooks provide a reasonable set of defaults for the allocator's
79  * debugging facilities.
80  */
81 const char *
82 _umem_debug_init()
83 {
84 	return ("default,verbose"); /* $UMEM_DEBUG setting */
85 }
86 
87 const char *
88 _umem_logging_init(void)
89 {
90 	return ("fail,contents"); /* $UMEM_LOGGING setting */
91 }
92 
93 static void
94 usage(void)
95 {
96 	(void) fprintf(stderr,
97 	    "Usage: %s [-CumdibcsvhL] [-S user:cksumalg] "
98 	    "poolname [object...]\n"
99 	    "       %s [-div] dataset [object...]\n"
100 	    "       %s -m [-L] poolname [vdev [metaslab...]]\n"
101 	    "       %s -R poolname vdev:offset:size[:flags]\n"
102 	    "       %s -l device\n"
103 	    "       %s -C\n\n",
104 	    cmdname, cmdname, cmdname, cmdname, cmdname, cmdname);
105 
106 	(void) fprintf(stderr, "    Dataset name must include at least one "
107 	    "separator character '/' or '@'\n");
108 	(void) fprintf(stderr, "    If dataset name is specified, only that "
109 	    "dataset is dumped\n");
110 	(void) fprintf(stderr, "    If object numbers are specified, only "
111 	    "those objects are dumped\n\n");
112 	(void) fprintf(stderr, "    Options to control amount of output:\n");
113 	(void) fprintf(stderr, "        -u uberblock\n");
114 	(void) fprintf(stderr, "        -d dataset(s)\n");
115 	(void) fprintf(stderr, "        -i intent logs\n");
116 	(void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
117 	(void) fprintf(stderr, "        -h pool history\n");
118 	(void) fprintf(stderr, "        -b block statistics\n");
119 	(void) fprintf(stderr, "        -m metaslabs\n");
120 	(void) fprintf(stderr, "        -c checksum all metadata (twice for "
121 	    "all data) blocks\n");
122 	(void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
123 	(void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
124 	(void) fprintf(stderr, "        -v verbose (applies to all others)\n");
125 	(void) fprintf(stderr, "        -l dump label contents\n");
126 	(void) fprintf(stderr, "        -L disable leak tracking (do not "
127 	    "load spacemaps)\n");
128 	(void) fprintf(stderr, "        -R read and display block from a "
129 	    "device\n\n");
130 	(void) fprintf(stderr, "    Below options are intended for use "
131 	    "with other options (except -l):\n");
132 	(void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
133 	    "cachefile\n");
134 	(void) fprintf(stderr, "        -e pool is exported/destroyed/"
135 	    "has altroot/not in a cachefile\n");
136 	(void) fprintf(stderr, "        -p <path> -- use one or more with "
137 	    "-e to specify path to vdev dir\n");
138 	(void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
139 	    "searching for uberblocks\n");
140 	(void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
141 	    "to make only that option verbose\n");
142 	(void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
143 	exit(1);
144 }
145 
146 /*
147  * Called for usage errors that are discovered after a call to spa_open(),
148  * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
149  */
150 
151 static void
152 fatal(const char *fmt, ...)
153 {
154 	va_list ap;
155 
156 	va_start(ap, fmt);
157 	(void) fprintf(stderr, "%s: ", cmdname);
158 	(void) vfprintf(stderr, fmt, ap);
159 	va_end(ap);
160 	(void) fprintf(stderr, "\n");
161 
162 	exit(1);
163 }
164 
165 /* ARGSUSED */
166 static void
167 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
168 {
169 	nvlist_t *nv;
170 	size_t nvsize = *(uint64_t *)data;
171 	char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
172 
173 	VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
174 
175 	VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
176 
177 	umem_free(packed, nvsize);
178 
179 	dump_nvlist(nv, 8);
180 
181 	nvlist_free(nv);
182 }
183 
184 const char dump_zap_stars[] = "****************************************";
185 const int dump_zap_width = sizeof (dump_zap_stars) - 1;
186 
187 static void
188 dump_zap_histogram(uint64_t histo[ZAP_HISTOGRAM_SIZE])
189 {
190 	int i;
191 	int minidx = ZAP_HISTOGRAM_SIZE - 1;
192 	int maxidx = 0;
193 	uint64_t max = 0;
194 
195 	for (i = 0; i < ZAP_HISTOGRAM_SIZE; i++) {
196 		if (histo[i] > max)
197 			max = histo[i];
198 		if (histo[i] > 0 && i > maxidx)
199 			maxidx = i;
200 		if (histo[i] > 0 && i < minidx)
201 			minidx = i;
202 	}
203 
204 	if (max < dump_zap_width)
205 		max = dump_zap_width;
206 
207 	for (i = minidx; i <= maxidx; i++)
208 		(void) printf("\t\t\t%u: %6llu %s\n", i, (u_longlong_t)histo[i],
209 		    &dump_zap_stars[(max - histo[i]) * dump_zap_width / max]);
210 }
211 
212 static void
213 dump_zap_stats(objset_t *os, uint64_t object)
214 {
215 	int error;
216 	zap_stats_t zs;
217 
218 	error = zap_get_stats(os, object, &zs);
219 	if (error)
220 		return;
221 
222 	if (zs.zs_ptrtbl_len == 0) {
223 		ASSERT(zs.zs_num_blocks == 1);
224 		(void) printf("\tmicrozap: %llu bytes, %llu entries\n",
225 		    (u_longlong_t)zs.zs_blocksize,
226 		    (u_longlong_t)zs.zs_num_entries);
227 		return;
228 	}
229 
230 	(void) printf("\tFat ZAP stats:\n");
231 
232 	(void) printf("\t\tPointer table:\n");
233 	(void) printf("\t\t\t%llu elements\n",
234 	    (u_longlong_t)zs.zs_ptrtbl_len);
235 	(void) printf("\t\t\tzt_blk: %llu\n",
236 	    (u_longlong_t)zs.zs_ptrtbl_zt_blk);
237 	(void) printf("\t\t\tzt_numblks: %llu\n",
238 	    (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
239 	(void) printf("\t\t\tzt_shift: %llu\n",
240 	    (u_longlong_t)zs.zs_ptrtbl_zt_shift);
241 	(void) printf("\t\t\tzt_blks_copied: %llu\n",
242 	    (u_longlong_t)zs.zs_ptrtbl_blks_copied);
243 	(void) printf("\t\t\tzt_nextblk: %llu\n",
244 	    (u_longlong_t)zs.zs_ptrtbl_nextblk);
245 
246 	(void) printf("\t\tZAP entries: %llu\n",
247 	    (u_longlong_t)zs.zs_num_entries);
248 	(void) printf("\t\tLeaf blocks: %llu\n",
249 	    (u_longlong_t)zs.zs_num_leafs);
250 	(void) printf("\t\tTotal blocks: %llu\n",
251 	    (u_longlong_t)zs.zs_num_blocks);
252 	(void) printf("\t\tzap_block_type: 0x%llx\n",
253 	    (u_longlong_t)zs.zs_block_type);
254 	(void) printf("\t\tzap_magic: 0x%llx\n",
255 	    (u_longlong_t)zs.zs_magic);
256 	(void) printf("\t\tzap_salt: 0x%llx\n",
257 	    (u_longlong_t)zs.zs_salt);
258 
259 	(void) printf("\t\tLeafs with 2^n pointers:\n");
260 	dump_zap_histogram(zs.zs_leafs_with_2n_pointers);
261 
262 	(void) printf("\t\tBlocks with n*5 entries:\n");
263 	dump_zap_histogram(zs.zs_blocks_with_n5_entries);
264 
265 	(void) printf("\t\tBlocks n/10 full:\n");
266 	dump_zap_histogram(zs.zs_blocks_n_tenths_full);
267 
268 	(void) printf("\t\tEntries with n chunks:\n");
269 	dump_zap_histogram(zs.zs_entries_using_n_chunks);
270 
271 	(void) printf("\t\tBuckets with n entries:\n");
272 	dump_zap_histogram(zs.zs_buckets_with_n_entries);
273 }
274 
275 /*ARGSUSED*/
276 static void
277 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
278 {
279 }
280 
281 /*ARGSUSED*/
282 static void
283 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
284 {
285 	(void) printf("\tUNKNOWN OBJECT TYPE\n");
286 }
287 
288 /*ARGSUSED*/
289 void
290 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
291 {
292 }
293 
294 /*ARGSUSED*/
295 static void
296 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
297 {
298 }
299 
300 /*ARGSUSED*/
301 static void
302 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
303 {
304 	zap_cursor_t zc;
305 	zap_attribute_t attr;
306 	void *prop;
307 	int i;
308 
309 	dump_zap_stats(os, object);
310 	(void) printf("\n");
311 
312 	for (zap_cursor_init(&zc, os, object);
313 	    zap_cursor_retrieve(&zc, &attr) == 0;
314 	    zap_cursor_advance(&zc)) {
315 		(void) printf("\t\t%s = ", attr.za_name);
316 		if (attr.za_num_integers == 0) {
317 			(void) printf("\n");
318 			continue;
319 		}
320 		prop = umem_zalloc(attr.za_num_integers *
321 		    attr.za_integer_length, UMEM_NOFAIL);
322 		(void) zap_lookup(os, object, attr.za_name,
323 		    attr.za_integer_length, attr.za_num_integers, prop);
324 		if (attr.za_integer_length == 1) {
325 			(void) printf("%s", (char *)prop);
326 		} else {
327 			for (i = 0; i < attr.za_num_integers; i++) {
328 				switch (attr.za_integer_length) {
329 				case 2:
330 					(void) printf("%u ",
331 					    ((uint16_t *)prop)[i]);
332 					break;
333 				case 4:
334 					(void) printf("%u ",
335 					    ((uint32_t *)prop)[i]);
336 					break;
337 				case 8:
338 					(void) printf("%lld ",
339 					    (u_longlong_t)((int64_t *)prop)[i]);
340 					break;
341 				}
342 			}
343 		}
344 		(void) printf("\n");
345 		umem_free(prop, attr.za_num_integers * attr.za_integer_length);
346 	}
347 	zap_cursor_fini(&zc);
348 }
349 
350 /*ARGSUSED*/
351 static void
352 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
353 {
354 	zap_cursor_t zc;
355 	zap_attribute_t attr;
356 	const char *typenames[] = {
357 		/* 0 */ "not specified",
358 		/* 1 */ "FIFO",
359 		/* 2 */ "Character Device",
360 		/* 3 */ "3 (invalid)",
361 		/* 4 */ "Directory",
362 		/* 5 */ "5 (invalid)",
363 		/* 6 */ "Block Device",
364 		/* 7 */ "7 (invalid)",
365 		/* 8 */ "Regular File",
366 		/* 9 */ "9 (invalid)",
367 		/* 10 */ "Symbolic Link",
368 		/* 11 */ "11 (invalid)",
369 		/* 12 */ "Socket",
370 		/* 13 */ "Door",
371 		/* 14 */ "Event Port",
372 		/* 15 */ "15 (invalid)",
373 	};
374 
375 	dump_zap_stats(os, object);
376 	(void) printf("\n");
377 
378 	for (zap_cursor_init(&zc, os, object);
379 	    zap_cursor_retrieve(&zc, &attr) == 0;
380 	    zap_cursor_advance(&zc)) {
381 		(void) printf("\t\t%s = %lld (type: %s)\n",
382 		    attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
383 		    typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
384 	}
385 	zap_cursor_fini(&zc);
386 }
387 
388 static void
389 dump_spacemap(objset_t *os, space_map_obj_t *smo, space_map_t *sm)
390 {
391 	uint64_t alloc, offset, entry;
392 	uint8_t mapshift = sm->sm_shift;
393 	uint64_t mapstart = sm->sm_start;
394 	char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
395 			    "INVALID", "INVALID", "INVALID", "INVALID" };
396 
397 	if (smo->smo_object == 0)
398 		return;
399 
400 	/*
401 	 * Print out the freelist entries in both encoded and decoded form.
402 	 */
403 	alloc = 0;
404 	for (offset = 0; offset < smo->smo_objsize; offset += sizeof (entry)) {
405 		VERIFY(0 == dmu_read(os, smo->smo_object, offset,
406 		    sizeof (entry), &entry, DMU_READ_PREFETCH));
407 		if (SM_DEBUG_DECODE(entry)) {
408 			(void) printf("\t    [%6llu] %s: txg %llu, pass %llu\n",
409 			    (u_longlong_t)(offset / sizeof (entry)),
410 			    ddata[SM_DEBUG_ACTION_DECODE(entry)],
411 			    (u_longlong_t)SM_DEBUG_TXG_DECODE(entry),
412 			    (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(entry));
413 		} else {
414 			(void) printf("\t    [%6llu]    %c  range:"
415 			    " %010llx-%010llx  size: %06llx\n",
416 			    (u_longlong_t)(offset / sizeof (entry)),
417 			    SM_TYPE_DECODE(entry) == SM_ALLOC ? 'A' : 'F',
418 			    (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
419 			    mapshift) + mapstart),
420 			    (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
421 			    mapshift) + mapstart + (SM_RUN_DECODE(entry) <<
422 			    mapshift)),
423 			    (u_longlong_t)(SM_RUN_DECODE(entry) << mapshift));
424 			if (SM_TYPE_DECODE(entry) == SM_ALLOC)
425 				alloc += SM_RUN_DECODE(entry) << mapshift;
426 			else
427 				alloc -= SM_RUN_DECODE(entry) << mapshift;
428 		}
429 	}
430 	if (alloc != smo->smo_alloc) {
431 		(void) printf("space_map_object alloc (%llu) INCONSISTENT "
432 		    "with space map summary (%llu)\n",
433 		    (u_longlong_t)smo->smo_alloc, (u_longlong_t)alloc);
434 	}
435 }
436 
437 static void
438 dump_metaslab_stats(metaslab_t *msp)
439 {
440 	char maxbuf[5];
441 	space_map_t *sm = &msp->ms_map;
442 	avl_tree_t *t = sm->sm_pp_root;
443 	int free_pct = sm->sm_space * 100 / sm->sm_size;
444 
445 	nicenum(space_map_maxsize(sm), maxbuf);
446 
447 	(void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
448 	    "segments", avl_numnodes(t), "maxsize", maxbuf,
449 	    "freepct", free_pct);
450 }
451 
452 static void
453 dump_metaslab(metaslab_t *msp)
454 {
455 	char freebuf[5];
456 	space_map_obj_t *smo = &msp->ms_smo;
457 	vdev_t *vd = msp->ms_group->mg_vd;
458 	spa_t *spa = vd->vdev_spa;
459 
460 	nicenum(msp->ms_map.sm_size - smo->smo_alloc, freebuf);
461 
462 	(void) printf(
463 	    "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
464 	    (u_longlong_t)(msp->ms_map.sm_start / msp->ms_map.sm_size),
465 	    (u_longlong_t)msp->ms_map.sm_start, (u_longlong_t)smo->smo_object,
466 	    freebuf);
467 
468 	if (dump_opt['m'] > 1 && !dump_opt['L']) {
469 		mutex_enter(&msp->ms_lock);
470 		VERIFY(space_map_load(&msp->ms_map, zfs_metaslab_ops,
471 		    SM_FREE, &msp->ms_smo, spa->spa_meta_objset) == 0);
472 		dump_metaslab_stats(msp);
473 		space_map_unload(&msp->ms_map);
474 		mutex_exit(&msp->ms_lock);
475 	}
476 
477 	if (dump_opt['d'] > 5 || dump_opt['m'] > 2) {
478 		ASSERT(msp->ms_map.sm_size == (1ULL << vd->vdev_ms_shift));
479 
480 		mutex_enter(&msp->ms_lock);
481 		dump_spacemap(spa->spa_meta_objset, smo, &msp->ms_map);
482 		mutex_exit(&msp->ms_lock);
483 	}
484 }
485 
486 static void
487 print_vdev_metaslab_header(vdev_t *vd)
488 {
489 	(void) printf("\tvdev %10llu\n\t%-10s%5llu   %-19s   %-15s   %-10s\n",
490 	    (u_longlong_t)vd->vdev_id,
491 	    "metaslabs", (u_longlong_t)vd->vdev_ms_count,
492 	    "offset", "spacemap", "free");
493 	(void) printf("\t%15s   %19s   %15s   %10s\n",
494 	    "---------------", "-------------------",
495 	    "---------------", "-------------");
496 }
497 
498 static void
499 dump_metaslabs(spa_t *spa)
500 {
501 	vdev_t *vd, *rvd = spa->spa_root_vdev;
502 	uint64_t m, c = 0, children = rvd->vdev_children;
503 
504 	(void) printf("\nMetaslabs:\n");
505 
506 	if (!dump_opt['d'] && zopt_objects > 0) {
507 		c = zopt_object[0];
508 
509 		if (c >= children)
510 			(void) fatal("bad vdev id: %llu", (u_longlong_t)c);
511 
512 		if (zopt_objects > 1) {
513 			vd = rvd->vdev_child[c];
514 			print_vdev_metaslab_header(vd);
515 
516 			for (m = 1; m < zopt_objects; m++) {
517 				if (zopt_object[m] < vd->vdev_ms_count)
518 					dump_metaslab(
519 					    vd->vdev_ms[zopt_object[m]]);
520 				else
521 					(void) fprintf(stderr, "bad metaslab "
522 					    "number %llu\n",
523 					    (u_longlong_t)zopt_object[m]);
524 			}
525 			(void) printf("\n");
526 			return;
527 		}
528 		children = c + 1;
529 	}
530 	for (; c < children; c++) {
531 		vd = rvd->vdev_child[c];
532 		print_vdev_metaslab_header(vd);
533 
534 		for (m = 0; m < vd->vdev_ms_count; m++)
535 			dump_metaslab(vd->vdev_ms[m]);
536 		(void) printf("\n");
537 	}
538 }
539 
540 static void
541 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
542 {
543 	const ddt_phys_t *ddp = dde->dde_phys;
544 	const ddt_key_t *ddk = &dde->dde_key;
545 	char *types[4] = { "ditto", "single", "double", "triple" };
546 	char blkbuf[BP_SPRINTF_LEN];
547 	blkptr_t blk;
548 
549 	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
550 		if (ddp->ddp_phys_birth == 0)
551 			continue;
552 		ddt_bp_create(ddt, ddk, ddp, &blk);
553 		sprintf_blkptr(blkbuf, &blk);
554 		(void) printf("index %llx refcnt %llu %s %s\n",
555 		    (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
556 		    types[p], blkbuf);
557 	}
558 }
559 
560 static void
561 dump_dedup_ratio(const ddt_stat_t *dds)
562 {
563 	double rL, rP, rD, D, dedup, compress, copies;
564 
565 	if (dds->dds_blocks == 0)
566 		return;
567 
568 	rL = (double)dds->dds_ref_lsize;
569 	rP = (double)dds->dds_ref_psize;
570 	rD = (double)dds->dds_ref_dsize;
571 	D = (double)dds->dds_dsize;
572 
573 	dedup = rD / D;
574 	compress = rL / rP;
575 	copies = rD / rP;
576 
577 	(void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
578 	    "dedup * compress / copies = %.2f\n\n",
579 	    dedup, compress, copies, dedup * compress / copies);
580 }
581 
582 static void
583 dump_ddt_stat(const ddt_stat_t *dds, int h)
584 {
585 	char refcnt[6];
586 	char blocks[6], lsize[6], psize[6], dsize[6];
587 	char ref_blocks[6], ref_lsize[6], ref_psize[6], ref_dsize[6];
588 
589 	if (dds->dds_blocks == 0)
590 		return;
591 
592 	if (h == -1)
593 		(void) strcpy(refcnt, "Total");
594 	else
595 		nicenum(1ULL << h, refcnt);
596 
597 	nicenum(dds->dds_blocks, blocks);
598 	nicenum(dds->dds_lsize, lsize);
599 	nicenum(dds->dds_psize, psize);
600 	nicenum(dds->dds_dsize, dsize);
601 	nicenum(dds->dds_ref_blocks, ref_blocks);
602 	nicenum(dds->dds_ref_lsize, ref_lsize);
603 	nicenum(dds->dds_ref_psize, ref_psize);
604 	nicenum(dds->dds_ref_dsize, ref_dsize);
605 
606 	(void) printf("%6s   %6s   %5s   %5s   %5s   %6s   %5s   %5s   %5s\n",
607 	    refcnt,
608 	    blocks, lsize, psize, dsize,
609 	    ref_blocks, ref_lsize, ref_psize, ref_dsize);
610 }
611 
612 static void
613 dump_ddt_histogram(const ddt_histogram_t *ddh)
614 {
615 	ddt_stat_t dds_total = { 0 };
616 
617 	ddt_histogram_stat(&dds_total, ddh);
618 
619 	(void) printf("\n");
620 
621 	(void) printf("bucket   "
622 	    "           allocated             "
623 	    "          referenced          \n");
624 	(void) printf("______   "
625 	    "______________________________   "
626 	    "______________________________\n");
627 
628 	(void) printf("%6s   %6s   %5s   %5s   %5s   %6s   %5s   %5s   %5s\n",
629 	    "refcnt",
630 	    "blocks", "LSIZE", "PSIZE", "DSIZE",
631 	    "blocks", "LSIZE", "PSIZE", "DSIZE");
632 
633 	(void) printf("%6s   %6s   %5s   %5s   %5s   %6s   %5s   %5s   %5s\n",
634 	    "------",
635 	    "------", "-----", "-----", "-----",
636 	    "------", "-----", "-----", "-----");
637 
638 	for (int h = 0; h < 64; h++)
639 		dump_ddt_stat(&ddh->ddh_stat[h], h);
640 
641 	dump_ddt_stat(&dds_total, -1);
642 
643 	(void) printf("\n");
644 }
645 
646 static void
647 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
648 {
649 	char name[DDT_NAMELEN];
650 	ddt_entry_t dde;
651 	uint64_t walk = 0;
652 	dmu_object_info_t doi;
653 	uint64_t count, dspace, mspace;
654 	int error;
655 
656 	error = ddt_object_info(ddt, type, class, &doi);
657 
658 	if (error == ENOENT)
659 		return;
660 	ASSERT(error == 0);
661 
662 	count = ddt_object_count(ddt, type, class);
663 	dspace = doi.doi_physical_blocks_512 << 9;
664 	mspace = doi.doi_fill_count * doi.doi_data_block_size;
665 
666 	ASSERT(count != 0);	/* we should have destroyed it */
667 
668 	ddt_object_name(ddt, type, class, name);
669 
670 	(void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
671 	    name,
672 	    (u_longlong_t)count,
673 	    (u_longlong_t)(dspace / count),
674 	    (u_longlong_t)(mspace / count));
675 
676 	if (dump_opt['D'] < 3)
677 		return;
678 
679 	dump_ddt_histogram(&ddt->ddt_histogram[type][class]);
680 
681 	if (dump_opt['D'] < 4)
682 		return;
683 
684 	if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
685 		return;
686 
687 	(void) printf("%s contents:\n\n", name);
688 
689 	while ((error = ddt_object_walk(ddt, type, class, &dde, &walk)) == 0)
690 		dump_dde(ddt, &dde, walk);
691 
692 	ASSERT(error == ENOENT);
693 
694 	(void) printf("\n");
695 }
696 
697 static void
698 dump_all_ddts(spa_t *spa)
699 {
700 	ddt_histogram_t ddh_total = { 0 };
701 	ddt_stat_t dds_total = { 0 };
702 
703 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
704 		ddt_t *ddt = spa->spa_ddt[c];
705 		for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
706 			for (enum ddt_class class = 0; class < DDT_CLASSES;
707 			    class++) {
708 				ddt_histogram_add(&ddh_total,
709 				    &ddt->ddt_histogram[type][class]);
710 				dump_ddt(ddt, type, class);
711 			}
712 		}
713 	}
714 
715 	ddt_histogram_stat(&dds_total, &ddh_total);
716 
717 	if (dds_total.dds_blocks == 0) {
718 		(void) printf("All DDTs are empty\n");
719 		return;
720 	}
721 
722 	(void) printf("\n");
723 
724 	if (dump_opt['D'] > 1) {
725 		(void) printf("DDT histogram (aggregated over all DDTs):\n");
726 		dump_ddt_histogram(&ddh_total);
727 	}
728 
729 	dump_dedup_ratio(&dds_total);
730 }
731 
732 static void
733 dump_dtl_seg(space_map_t *sm, uint64_t start, uint64_t size)
734 {
735 	char *prefix = (void *)sm;
736 
737 	(void) printf("%s [%llu,%llu) length %llu\n",
738 	    prefix,
739 	    (u_longlong_t)start,
740 	    (u_longlong_t)(start + size),
741 	    (u_longlong_t)(size));
742 }
743 
744 static void
745 dump_dtl(vdev_t *vd, int indent)
746 {
747 	spa_t *spa = vd->vdev_spa;
748 	boolean_t required;
749 	char *name[DTL_TYPES] = { "missing", "partial", "scrub", "outage" };
750 	char prefix[256];
751 
752 	spa_vdev_state_enter(spa, SCL_NONE);
753 	required = vdev_dtl_required(vd);
754 	(void) spa_vdev_state_exit(spa, NULL, 0);
755 
756 	if (indent == 0)
757 		(void) printf("\nDirty time logs:\n\n");
758 
759 	(void) printf("\t%*s%s [%s]\n", indent, "",
760 	    vd->vdev_path ? vd->vdev_path :
761 	    vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
762 	    required ? "DTL-required" : "DTL-expendable");
763 
764 	for (int t = 0; t < DTL_TYPES; t++) {
765 		space_map_t *sm = &vd->vdev_dtl[t];
766 		if (sm->sm_space == 0)
767 			continue;
768 		(void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
769 		    indent + 2, "", name[t]);
770 		mutex_enter(sm->sm_lock);
771 		space_map_walk(sm, dump_dtl_seg, (void *)prefix);
772 		mutex_exit(sm->sm_lock);
773 		if (dump_opt['d'] > 5 && vd->vdev_children == 0)
774 			dump_spacemap(spa->spa_meta_objset,
775 			    &vd->vdev_dtl_smo, sm);
776 	}
777 
778 	for (int c = 0; c < vd->vdev_children; c++)
779 		dump_dtl(vd->vdev_child[c], indent + 4);
780 }
781 
782 static void
783 dump_history(spa_t *spa)
784 {
785 	nvlist_t **events = NULL;
786 	char buf[SPA_MAXBLOCKSIZE];
787 	uint64_t resid, len, off = 0;
788 	uint_t num = 0;
789 	int error;
790 	time_t tsec;
791 	struct tm t;
792 	char tbuf[30];
793 	char internalstr[MAXPATHLEN];
794 
795 	do {
796 		len = sizeof (buf);
797 
798 		if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
799 			(void) fprintf(stderr, "Unable to read history: "
800 			    "error %d\n", error);
801 			return;
802 		}
803 
804 		if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
805 			break;
806 
807 		off -= resid;
808 	} while (len != 0);
809 
810 	(void) printf("\nHistory:\n");
811 	for (int i = 0; i < num; i++) {
812 		uint64_t time, txg, ievent;
813 		char *cmd, *intstr;
814 
815 		if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
816 		    &time) != 0)
817 			continue;
818 		if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
819 		    &cmd) != 0) {
820 			if (nvlist_lookup_uint64(events[i],
821 			    ZPOOL_HIST_INT_EVENT, &ievent) != 0)
822 				continue;
823 			verify(nvlist_lookup_uint64(events[i],
824 			    ZPOOL_HIST_TXG, &txg) == 0);
825 			verify(nvlist_lookup_string(events[i],
826 			    ZPOOL_HIST_INT_STR, &intstr) == 0);
827 			if (ievent >= LOG_END)
828 				continue;
829 
830 			(void) snprintf(internalstr,
831 			    sizeof (internalstr),
832 			    "[internal %s txg:%lld] %s",
833 			    hist_event_table[ievent], txg,
834 			    intstr);
835 			cmd = internalstr;
836 		}
837 		tsec = time;
838 		(void) localtime_r(&tsec, &t);
839 		(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
840 		(void) printf("%s %s\n", tbuf, cmd);
841 	}
842 }
843 
844 /*ARGSUSED*/
845 static void
846 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
847 {
848 }
849 
850 static uint64_t
851 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp, const zbookmark_t *zb)
852 {
853 	if (dnp == NULL) {
854 		ASSERT(zb->zb_level < 0);
855 		if (zb->zb_object == 0)
856 			return (zb->zb_blkid);
857 		return (zb->zb_blkid * BP_GET_LSIZE(bp));
858 	}
859 
860 	ASSERT(zb->zb_level >= 0);
861 
862 	return ((zb->zb_blkid <<
863 	    (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
864 	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
865 }
866 
867 static void
868 sprintf_blkptr_compact(char *blkbuf, blkptr_t *bp)
869 {
870 	dva_t *dva = bp->blk_dva;
871 	int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
872 
873 	if (dump_opt['b'] >= 5) {
874 		sprintf_blkptr(blkbuf, bp);
875 		return;
876 	}
877 
878 	blkbuf[0] = '\0';
879 
880 	for (int i = 0; i < ndvas; i++)
881 		(void) sprintf(blkbuf + strlen(blkbuf), "%llu:%llx:%llx ",
882 		    (u_longlong_t)DVA_GET_VDEV(&dva[i]),
883 		    (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
884 		    (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
885 
886 	(void) sprintf(blkbuf + strlen(blkbuf),
887 	    "%llxL/%llxP F=%llu B=%llu/%llu",
888 	    (u_longlong_t)BP_GET_LSIZE(bp),
889 	    (u_longlong_t)BP_GET_PSIZE(bp),
890 	    (u_longlong_t)bp->blk_fill,
891 	    (u_longlong_t)bp->blk_birth,
892 	    (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
893 }
894 
895 static void
896 print_indirect(blkptr_t *bp, const zbookmark_t *zb,
897     const dnode_phys_t *dnp)
898 {
899 	char blkbuf[BP_SPRINTF_LEN];
900 	int l;
901 
902 	ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
903 	ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
904 
905 	(void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
906 
907 	ASSERT(zb->zb_level >= 0);
908 
909 	for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
910 		if (l == zb->zb_level) {
911 			(void) printf("L%llx", (u_longlong_t)zb->zb_level);
912 		} else {
913 			(void) printf(" ");
914 		}
915 	}
916 
917 	sprintf_blkptr_compact(blkbuf, bp);
918 	(void) printf("%s\n", blkbuf);
919 }
920 
921 static int
922 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
923     blkptr_t *bp, const zbookmark_t *zb)
924 {
925 	int err = 0;
926 
927 	if (bp->blk_birth == 0)
928 		return (0);
929 
930 	print_indirect(bp, zb, dnp);
931 
932 	if (BP_GET_LEVEL(bp) > 0) {
933 		uint32_t flags = ARC_WAIT;
934 		int i;
935 		blkptr_t *cbp;
936 		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
937 		arc_buf_t *buf;
938 		uint64_t fill = 0;
939 
940 		err = arc_read_nolock(NULL, spa, bp, arc_getbuf_func, &buf,
941 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
942 		if (err)
943 			return (err);
944 
945 		/* recursively visit blocks below this */
946 		cbp = buf->b_data;
947 		for (i = 0; i < epb; i++, cbp++) {
948 			zbookmark_t czb;
949 
950 			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
951 			    zb->zb_level - 1,
952 			    zb->zb_blkid * epb + i);
953 			err = visit_indirect(spa, dnp, cbp, &czb);
954 			if (err)
955 				break;
956 			fill += cbp->blk_fill;
957 		}
958 		if (!err)
959 			ASSERT3U(fill, ==, bp->blk_fill);
960 		(void) arc_buf_remove_ref(buf, &buf);
961 	}
962 
963 	return (err);
964 }
965 
966 /*ARGSUSED*/
967 static void
968 dump_indirect(dnode_t *dn)
969 {
970 	dnode_phys_t *dnp = dn->dn_phys;
971 	int j;
972 	zbookmark_t czb;
973 
974 	(void) printf("Indirect blocks:\n");
975 
976 	SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
977 	    dn->dn_object, dnp->dn_nlevels - 1, 0);
978 	for (j = 0; j < dnp->dn_nblkptr; j++) {
979 		czb.zb_blkid = j;
980 		(void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
981 		    &dnp->dn_blkptr[j], &czb);
982 	}
983 
984 	(void) printf("\n");
985 }
986 
987 /*ARGSUSED*/
988 static void
989 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
990 {
991 	dsl_dir_phys_t *dd = data;
992 	time_t crtime;
993 	char nice[6];
994 
995 	if (dd == NULL)
996 		return;
997 
998 	ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
999 
1000 	crtime = dd->dd_creation_time;
1001 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1002 	(void) printf("\t\thead_dataset_obj = %llu\n",
1003 	    (u_longlong_t)dd->dd_head_dataset_obj);
1004 	(void) printf("\t\tparent_dir_obj = %llu\n",
1005 	    (u_longlong_t)dd->dd_parent_obj);
1006 	(void) printf("\t\torigin_obj = %llu\n",
1007 	    (u_longlong_t)dd->dd_origin_obj);
1008 	(void) printf("\t\tchild_dir_zapobj = %llu\n",
1009 	    (u_longlong_t)dd->dd_child_dir_zapobj);
1010 	nicenum(dd->dd_used_bytes, nice);
1011 	(void) printf("\t\tused_bytes = %s\n", nice);
1012 	nicenum(dd->dd_compressed_bytes, nice);
1013 	(void) printf("\t\tcompressed_bytes = %s\n", nice);
1014 	nicenum(dd->dd_uncompressed_bytes, nice);
1015 	(void) printf("\t\tuncompressed_bytes = %s\n", nice);
1016 	nicenum(dd->dd_quota, nice);
1017 	(void) printf("\t\tquota = %s\n", nice);
1018 	nicenum(dd->dd_reserved, nice);
1019 	(void) printf("\t\treserved = %s\n", nice);
1020 	(void) printf("\t\tprops_zapobj = %llu\n",
1021 	    (u_longlong_t)dd->dd_props_zapobj);
1022 	(void) printf("\t\tdeleg_zapobj = %llu\n",
1023 	    (u_longlong_t)dd->dd_deleg_zapobj);
1024 	(void) printf("\t\tflags = %llx\n",
1025 	    (u_longlong_t)dd->dd_flags);
1026 
1027 #define	DO(which) \
1028 	nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice); \
1029 	(void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1030 	DO(HEAD);
1031 	DO(SNAP);
1032 	DO(CHILD);
1033 	DO(CHILD_RSRV);
1034 	DO(REFRSRV);
1035 #undef DO
1036 }
1037 
1038 /*ARGSUSED*/
1039 static void
1040 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1041 {
1042 	dsl_dataset_phys_t *ds = data;
1043 	time_t crtime;
1044 	char used[6], compressed[6], uncompressed[6], unique[6];
1045 	char blkbuf[BP_SPRINTF_LEN];
1046 
1047 	if (ds == NULL)
1048 		return;
1049 
1050 	ASSERT(size == sizeof (*ds));
1051 	crtime = ds->ds_creation_time;
1052 	nicenum(ds->ds_used_bytes, used);
1053 	nicenum(ds->ds_compressed_bytes, compressed);
1054 	nicenum(ds->ds_uncompressed_bytes, uncompressed);
1055 	nicenum(ds->ds_unique_bytes, unique);
1056 	sprintf_blkptr(blkbuf, &ds->ds_bp);
1057 
1058 	(void) printf("\t\tdir_obj = %llu\n",
1059 	    (u_longlong_t)ds->ds_dir_obj);
1060 	(void) printf("\t\tprev_snap_obj = %llu\n",
1061 	    (u_longlong_t)ds->ds_prev_snap_obj);
1062 	(void) printf("\t\tprev_snap_txg = %llu\n",
1063 	    (u_longlong_t)ds->ds_prev_snap_txg);
1064 	(void) printf("\t\tnext_snap_obj = %llu\n",
1065 	    (u_longlong_t)ds->ds_next_snap_obj);
1066 	(void) printf("\t\tsnapnames_zapobj = %llu\n",
1067 	    (u_longlong_t)ds->ds_snapnames_zapobj);
1068 	(void) printf("\t\tnum_children = %llu\n",
1069 	    (u_longlong_t)ds->ds_num_children);
1070 	(void) printf("\t\tuserrefs_obj = %llu\n",
1071 	    (u_longlong_t)ds->ds_userrefs_obj);
1072 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1073 	(void) printf("\t\tcreation_txg = %llu\n",
1074 	    (u_longlong_t)ds->ds_creation_txg);
1075 	(void) printf("\t\tdeadlist_obj = %llu\n",
1076 	    (u_longlong_t)ds->ds_deadlist_obj);
1077 	(void) printf("\t\tused_bytes = %s\n", used);
1078 	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
1079 	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1080 	(void) printf("\t\tunique = %s\n", unique);
1081 	(void) printf("\t\tfsid_guid = %llu\n",
1082 	    (u_longlong_t)ds->ds_fsid_guid);
1083 	(void) printf("\t\tguid = %llu\n",
1084 	    (u_longlong_t)ds->ds_guid);
1085 	(void) printf("\t\tflags = %llx\n",
1086 	    (u_longlong_t)ds->ds_flags);
1087 	(void) printf("\t\tnext_clones_obj = %llu\n",
1088 	    (u_longlong_t)ds->ds_next_clones_obj);
1089 	(void) printf("\t\tprops_obj = %llu\n",
1090 	    (u_longlong_t)ds->ds_props_obj);
1091 	(void) printf("\t\tbp = %s\n", blkbuf);
1092 }
1093 
1094 static void
1095 dump_bplist(objset_t *mos, uint64_t object, char *name)
1096 {
1097 	bplist_t bpl = { 0 };
1098 	blkptr_t blk, *bp = &blk;
1099 	uint64_t itor = 0;
1100 	char bytes[6];
1101 	char comp[6];
1102 	char uncomp[6];
1103 
1104 	if (dump_opt['d'] < 3)
1105 		return;
1106 
1107 	bplist_init(&bpl);
1108 	VERIFY(0 == bplist_open(&bpl, mos, object));
1109 	if (bplist_empty(&bpl)) {
1110 		bplist_close(&bpl);
1111 		bplist_fini(&bpl);
1112 		return;
1113 	}
1114 
1115 	nicenum(bpl.bpl_phys->bpl_bytes, bytes);
1116 	if (bpl.bpl_dbuf->db_size == sizeof (bplist_phys_t)) {
1117 		nicenum(bpl.bpl_phys->bpl_comp, comp);
1118 		nicenum(bpl.bpl_phys->bpl_uncomp, uncomp);
1119 		(void) printf("\n    %s: %llu entries, %s (%s/%s comp)\n",
1120 		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries,
1121 		    bytes, comp, uncomp);
1122 	} else {
1123 		(void) printf("\n    %s: %llu entries, %s\n",
1124 		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries, bytes);
1125 	}
1126 
1127 	if (dump_opt['d'] < 5) {
1128 		bplist_close(&bpl);
1129 		bplist_fini(&bpl);
1130 		return;
1131 	}
1132 
1133 	(void) printf("\n");
1134 
1135 	while (bplist_iterate(&bpl, &itor, bp) == 0) {
1136 		char blkbuf[BP_SPRINTF_LEN];
1137 
1138 		ASSERT(bp->blk_birth != 0);
1139 		sprintf_blkptr_compact(blkbuf, bp);
1140 		(void) printf("\tItem %3llu: %s\n",
1141 		    (u_longlong_t)itor - 1, blkbuf);
1142 	}
1143 
1144 	bplist_close(&bpl);
1145 	bplist_fini(&bpl);
1146 }
1147 
1148 static avl_tree_t idx_tree;
1149 static avl_tree_t domain_tree;
1150 static boolean_t fuid_table_loaded;
1151 
1152 static void
1153 fuid_table_destroy()
1154 {
1155 	if (fuid_table_loaded) {
1156 		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1157 		fuid_table_loaded = B_FALSE;
1158 	}
1159 }
1160 
1161 /*
1162  * print uid or gid information.
1163  * For normal POSIX id just the id is printed in decimal format.
1164  * For CIFS files with FUID the fuid is printed in hex followed by
1165  * the doman-rid string.
1166  */
1167 static void
1168 print_idstr(uint64_t id, const char *id_type)
1169 {
1170 	if (FUID_INDEX(id)) {
1171 		char *domain;
1172 
1173 		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1174 		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
1175 		    (u_longlong_t)id, domain, (int)FUID_RID(id));
1176 	} else {
1177 		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1178 	}
1179 
1180 }
1181 
1182 static void
1183 dump_uidgid(objset_t *os, znode_phys_t *zp)
1184 {
1185 	uint32_t uid_idx, gid_idx;
1186 
1187 	uid_idx = FUID_INDEX(zp->zp_uid);
1188 	gid_idx = FUID_INDEX(zp->zp_gid);
1189 
1190 	/* Load domain table, if not already loaded */
1191 	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1192 		uint64_t fuid_obj;
1193 
1194 		/* first find the fuid object.  It lives in the master node */
1195 		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1196 		    8, 1, &fuid_obj) == 0);
1197 		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1198 		(void) zfs_fuid_table_load(os, fuid_obj,
1199 		    &idx_tree, &domain_tree);
1200 		fuid_table_loaded = B_TRUE;
1201 	}
1202 
1203 	print_idstr(zp->zp_uid, "uid");
1204 	print_idstr(zp->zp_gid, "gid");
1205 }
1206 
1207 /*ARGSUSED*/
1208 static void
1209 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
1210 {
1211 	znode_phys_t *zp = data;
1212 	time_t z_crtime, z_atime, z_mtime, z_ctime;
1213 	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
1214 	int error;
1215 
1216 	ASSERT(size >= sizeof (znode_phys_t));
1217 
1218 	error = zfs_obj_to_path(os, object, path, sizeof (path));
1219 	if (error != 0) {
1220 		(void) snprintf(path, sizeof (path), "\?\?\?<object#%llu>",
1221 		    (u_longlong_t)object);
1222 	}
1223 
1224 	if (dump_opt['d'] < 3) {
1225 		(void) printf("\t%s\n", path);
1226 		return;
1227 	}
1228 
1229 	z_crtime = (time_t)zp->zp_crtime[0];
1230 	z_atime = (time_t)zp->zp_atime[0];
1231 	z_mtime = (time_t)zp->zp_mtime[0];
1232 	z_ctime = (time_t)zp->zp_ctime[0];
1233 
1234 	(void) printf("\tpath	%s\n", path);
1235 	dump_uidgid(os, zp);
1236 	(void) printf("\tatime	%s", ctime(&z_atime));
1237 	(void) printf("\tmtime	%s", ctime(&z_mtime));
1238 	(void) printf("\tctime	%s", ctime(&z_ctime));
1239 	(void) printf("\tcrtime	%s", ctime(&z_crtime));
1240 	(void) printf("\tgen	%llu\n", (u_longlong_t)zp->zp_gen);
1241 	(void) printf("\tmode	%llo\n", (u_longlong_t)zp->zp_mode);
1242 	(void) printf("\tsize	%llu\n", (u_longlong_t)zp->zp_size);
1243 	(void) printf("\tparent	%llu\n", (u_longlong_t)zp->zp_parent);
1244 	(void) printf("\tlinks	%llu\n", (u_longlong_t)zp->zp_links);
1245 	(void) printf("\txattr	%llu\n", (u_longlong_t)zp->zp_xattr);
1246 	(void) printf("\trdev	0x%016llx\n", (u_longlong_t)zp->zp_rdev);
1247 }
1248 
1249 /*ARGSUSED*/
1250 static void
1251 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
1252 {
1253 }
1254 
1255 /*ARGSUSED*/
1256 static void
1257 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
1258 {
1259 }
1260 
1261 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
1262 	dump_none,		/* unallocated			*/
1263 	dump_zap,		/* object directory		*/
1264 	dump_uint64,		/* object array			*/
1265 	dump_none,		/* packed nvlist		*/
1266 	dump_packed_nvlist,	/* packed nvlist size		*/
1267 	dump_none,		/* bplist			*/
1268 	dump_none,		/* bplist header		*/
1269 	dump_none,		/* SPA space map header		*/
1270 	dump_none,		/* SPA space map		*/
1271 	dump_none,		/* ZIL intent log		*/
1272 	dump_dnode,		/* DMU dnode			*/
1273 	dump_dmu_objset,	/* DMU objset			*/
1274 	dump_dsl_dir,		/* DSL directory		*/
1275 	dump_zap,		/* DSL directory child map	*/
1276 	dump_zap,		/* DSL dataset snap map		*/
1277 	dump_zap,		/* DSL props			*/
1278 	dump_dsl_dataset,	/* DSL dataset			*/
1279 	dump_znode,		/* ZFS znode			*/
1280 	dump_acl,		/* ZFS V0 ACL			*/
1281 	dump_uint8,		/* ZFS plain file		*/
1282 	dump_zpldir,		/* ZFS directory		*/
1283 	dump_zap,		/* ZFS master node		*/
1284 	dump_zap,		/* ZFS delete queue		*/
1285 	dump_uint8,		/* zvol object			*/
1286 	dump_zap,		/* zvol prop			*/
1287 	dump_uint8,		/* other uint8[]		*/
1288 	dump_uint64,		/* other uint64[]		*/
1289 	dump_zap,		/* other ZAP			*/
1290 	dump_zap,		/* persistent error log		*/
1291 	dump_uint8,		/* SPA history			*/
1292 	dump_uint64,		/* SPA history offsets		*/
1293 	dump_zap,		/* Pool properties		*/
1294 	dump_zap,		/* DSL permissions		*/
1295 	dump_acl,		/* ZFS ACL			*/
1296 	dump_uint8,		/* ZFS SYSACL			*/
1297 	dump_none,		/* FUID nvlist			*/
1298 	dump_packed_nvlist,	/* FUID nvlist size		*/
1299 	dump_zap,		/* DSL dataset next clones	*/
1300 	dump_zap,		/* DSL scrub queue		*/
1301 	dump_zap,		/* ZFS user/group used		*/
1302 	dump_zap,		/* ZFS user/group quota		*/
1303 	dump_zap,		/* snapshot refcount tags	*/
1304 	dump_none,		/* DDT ZAP object		*/
1305 	dump_zap,		/* DDT statistics		*/
1306 	dump_unknown		/* Unknown type, must be last	*/
1307 };
1308 
1309 static void
1310 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1311 {
1312 	dmu_buf_t *db = NULL;
1313 	dmu_object_info_t doi;
1314 	dnode_t *dn;
1315 	void *bonus = NULL;
1316 	size_t bsize = 0;
1317 	char iblk[6], dblk[6], lsize[6], asize[6], bonus_size[6], fill[7];
1318 	char aux[50];
1319 	int error;
1320 
1321 	if (*print_header) {
1322 		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1323 		    "Object", "lvl", "iblk", "dblk", "dsize", "lsize",
1324 		    "%full", "type");
1325 		*print_header = 0;
1326 	}
1327 
1328 	if (object == 0) {
1329 		dn = os->os_meta_dnode;
1330 	} else {
1331 		error = dmu_bonus_hold(os, object, FTAG, &db);
1332 		if (error)
1333 			fatal("dmu_bonus_hold(%llu) failed, errno %u",
1334 			    object, error);
1335 		bonus = db->db_data;
1336 		bsize = db->db_size;
1337 		dn = ((dmu_buf_impl_t *)db)->db_dnode;
1338 	}
1339 	dmu_object_info_from_dnode(dn, &doi);
1340 
1341 	nicenum(doi.doi_metadata_block_size, iblk);
1342 	nicenum(doi.doi_data_block_size, dblk);
1343 	nicenum(doi.doi_max_offset, lsize);
1344 	nicenum(doi.doi_physical_blocks_512 << 9, asize);
1345 	nicenum(doi.doi_bonus_size, bonus_size);
1346 	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
1347 	    doi.doi_data_block_size / doi.doi_max_offset);
1348 
1349 	aux[0] = '\0';
1350 
1351 	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1352 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1353 		    ZDB_CHECKSUM_NAME(doi.doi_checksum));
1354 	}
1355 
1356 	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1357 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1358 		    ZDB_COMPRESS_NAME(doi.doi_compress));
1359 	}
1360 
1361 	(void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %6s  %s%s\n",
1362 	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
1363 	    asize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
1364 
1365 	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1366 		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1367 		    "", "", "", "", "", bonus_size, "bonus",
1368 		    ZDB_OT_NAME(doi.doi_bonus_type));
1369 	}
1370 
1371 	if (verbosity >= 4) {
1372 		(void) printf("\tdnode flags: %s%s\n",
1373 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
1374 		    "USED_BYTES " : "",
1375 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
1376 		    "USERUSED_ACCOUNTED " : "");
1377 		(void) printf("\tdnode maxblkid: %llu\n",
1378 		    (longlong_t)dn->dn_phys->dn_maxblkid);
1379 
1380 		object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os, object,
1381 		    bonus, bsize);
1382 		object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object, NULL, 0);
1383 		*print_header = 1;
1384 	}
1385 
1386 	if (verbosity >= 5)
1387 		dump_indirect(dn);
1388 
1389 	if (verbosity >= 5) {
1390 		/*
1391 		 * Report the list of segments that comprise the object.
1392 		 */
1393 		uint64_t start = 0;
1394 		uint64_t end;
1395 		uint64_t blkfill = 1;
1396 		int minlvl = 1;
1397 
1398 		if (dn->dn_type == DMU_OT_DNODE) {
1399 			minlvl = 0;
1400 			blkfill = DNODES_PER_BLOCK;
1401 		}
1402 
1403 		for (;;) {
1404 			char segsize[6];
1405 			error = dnode_next_offset(dn,
1406 			    0, &start, minlvl, blkfill, 0);
1407 			if (error)
1408 				break;
1409 			end = start;
1410 			error = dnode_next_offset(dn,
1411 			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
1412 			nicenum(end - start, segsize);
1413 			(void) printf("\t\tsegment [%016llx, %016llx)"
1414 			    " size %5s\n", (u_longlong_t)start,
1415 			    (u_longlong_t)end, segsize);
1416 			if (error)
1417 				break;
1418 			start = end;
1419 		}
1420 	}
1421 
1422 	if (db != NULL)
1423 		dmu_buf_rele(db, FTAG);
1424 }
1425 
1426 static char *objset_types[DMU_OST_NUMTYPES] = {
1427 	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1428 
1429 static void
1430 dump_dir(objset_t *os)
1431 {
1432 	dmu_objset_stats_t dds;
1433 	uint64_t object, object_count;
1434 	uint64_t refdbytes, usedobjs, scratch;
1435 	char numbuf[8];
1436 	char blkbuf[BP_SPRINTF_LEN + 20];
1437 	char osname[MAXNAMELEN];
1438 	char *type = "UNKNOWN";
1439 	int verbosity = dump_opt['d'];
1440 	int print_header = 1;
1441 	int i, error;
1442 
1443 	dmu_objset_fast_stat(os, &dds);
1444 
1445 	if (dds.dds_type < DMU_OST_NUMTYPES)
1446 		type = objset_types[dds.dds_type];
1447 
1448 	if (dds.dds_type == DMU_OST_META) {
1449 		dds.dds_creation_txg = TXG_INITIAL;
1450 		usedobjs = os->os_rootbp->blk_fill;
1451 		refdbytes = os->os_spa->spa_dsl_pool->
1452 		    dp_mos_dir->dd_phys->dd_used_bytes;
1453 	} else {
1454 		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
1455 	}
1456 
1457 	ASSERT3U(usedobjs, ==, os->os_rootbp->blk_fill);
1458 
1459 	nicenum(refdbytes, numbuf);
1460 
1461 	if (verbosity >= 4) {
1462 		(void) sprintf(blkbuf, ", rootbp ");
1463 		(void) sprintf_blkptr(blkbuf + strlen(blkbuf), os->os_rootbp);
1464 	} else {
1465 		blkbuf[0] = '\0';
1466 	}
1467 
1468 	dmu_objset_name(os, osname);
1469 
1470 	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
1471 	    "%s, %llu objects%s\n",
1472 	    osname, type, (u_longlong_t)dmu_objset_id(os),
1473 	    (u_longlong_t)dds.dds_creation_txg,
1474 	    numbuf, (u_longlong_t)usedobjs, blkbuf);
1475 
1476 	if (zopt_objects != 0) {
1477 		for (i = 0; i < zopt_objects; i++)
1478 			dump_object(os, zopt_object[i], verbosity,
1479 			    &print_header);
1480 		(void) printf("\n");
1481 		return;
1482 	}
1483 
1484 	if (dump_opt['i'] != 0 || verbosity >= 2)
1485 		dump_intent_log(dmu_objset_zil(os));
1486 
1487 	if (dmu_objset_ds(os) != NULL)
1488 		dump_bplist(dmu_objset_pool(os)->dp_meta_objset,
1489 		    dmu_objset_ds(os)->ds_phys->ds_deadlist_obj, "Deadlist");
1490 
1491 	if (verbosity < 2)
1492 		return;
1493 
1494 	if (os->os_rootbp->blk_birth == 0)
1495 		return;
1496 
1497 	dump_object(os, 0, verbosity, &print_header);
1498 	object_count = 0;
1499 	if (os->os_userused_dnode &&
1500 	    os->os_userused_dnode->dn_type != 0) {
1501 		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header);
1502 		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header);
1503 	}
1504 
1505 	object = 0;
1506 	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1507 		dump_object(os, object, verbosity, &print_header);
1508 		object_count++;
1509 	}
1510 
1511 	ASSERT3U(object_count, ==, usedobjs);
1512 
1513 	(void) printf("\n");
1514 
1515 	if (error != ESRCH) {
1516 		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
1517 		abort();
1518 	}
1519 }
1520 
1521 static void
1522 dump_uberblock(uberblock_t *ub)
1523 {
1524 	time_t timestamp = ub->ub_timestamp;
1525 
1526 	(void) printf("\nUberblock:\n");
1527 	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
1528 	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
1529 	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
1530 	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
1531 	(void) printf("\ttimestamp = %llu UTC = %s",
1532 	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
1533 	if (dump_opt['u'] >= 3) {
1534 		char blkbuf[BP_SPRINTF_LEN];
1535 		sprintf_blkptr(blkbuf, &ub->ub_rootbp);
1536 		(void) printf("\trootbp = %s\n", blkbuf);
1537 	}
1538 	(void) printf("\n");
1539 }
1540 
1541 static void
1542 dump_config(spa_t *spa)
1543 {
1544 	dmu_buf_t *db;
1545 	size_t nvsize = 0;
1546 	int error = 0;
1547 
1548 
1549 	error = dmu_bonus_hold(spa->spa_meta_objset,
1550 	    spa->spa_config_object, FTAG, &db);
1551 
1552 	if (error == 0) {
1553 		nvsize = *(uint64_t *)db->db_data;
1554 		dmu_buf_rele(db, FTAG);
1555 
1556 		(void) printf("\nMOS Configuration:\n");
1557 		dump_packed_nvlist(spa->spa_meta_objset,
1558 		    spa->spa_config_object, (void *)&nvsize, 1);
1559 	} else {
1560 		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
1561 		    (u_longlong_t)spa->spa_config_object, error);
1562 	}
1563 }
1564 
1565 static void
1566 dump_cachefile(const char *cachefile)
1567 {
1568 	int fd;
1569 	struct stat64 statbuf;
1570 	char *buf;
1571 	nvlist_t *config;
1572 
1573 	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
1574 		(void) printf("cannot open '%s': %s\n", cachefile,
1575 		    strerror(errno));
1576 		exit(1);
1577 	}
1578 
1579 	if (fstat64(fd, &statbuf) != 0) {
1580 		(void) printf("failed to stat '%s': %s\n", cachefile,
1581 		    strerror(errno));
1582 		exit(1);
1583 	}
1584 
1585 	if ((buf = malloc(statbuf.st_size)) == NULL) {
1586 		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
1587 		    (u_longlong_t)statbuf.st_size);
1588 		exit(1);
1589 	}
1590 
1591 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1592 		(void) fprintf(stderr, "failed to read %llu bytes\n",
1593 		    (u_longlong_t)statbuf.st_size);
1594 		exit(1);
1595 	}
1596 
1597 	(void) close(fd);
1598 
1599 	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
1600 		(void) fprintf(stderr, "failed to unpack nvlist\n");
1601 		exit(1);
1602 	}
1603 
1604 	free(buf);
1605 
1606 	dump_nvlist(config, 0);
1607 
1608 	nvlist_free(config);
1609 }
1610 
1611 static void
1612 dump_label(const char *dev)
1613 {
1614 	int fd;
1615 	vdev_label_t label;
1616 	char *buf = label.vl_vdev_phys.vp_nvlist;
1617 	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1618 	struct stat64 statbuf;
1619 	uint64_t psize;
1620 	int l;
1621 
1622 	if ((fd = open64(dev, O_RDONLY)) < 0) {
1623 		(void) printf("cannot open '%s': %s\n", dev, strerror(errno));
1624 		exit(1);
1625 	}
1626 
1627 	if (fstat64(fd, &statbuf) != 0) {
1628 		(void) printf("failed to stat '%s': %s\n", dev,
1629 		    strerror(errno));
1630 		exit(1);
1631 	}
1632 
1633 	psize = statbuf.st_size;
1634 	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
1635 
1636 	for (l = 0; l < VDEV_LABELS; l++) {
1637 
1638 		nvlist_t *config = NULL;
1639 
1640 		(void) printf("--------------------------------------------\n");
1641 		(void) printf("LABEL %d\n", l);
1642 		(void) printf("--------------------------------------------\n");
1643 
1644 		if (pread64(fd, &label, sizeof (label),
1645 		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
1646 			(void) printf("failed to read label %d\n", l);
1647 			continue;
1648 		}
1649 
1650 		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
1651 			(void) printf("failed to unpack label %d\n", l);
1652 			continue;
1653 		}
1654 		dump_nvlist(config, 4);
1655 		nvlist_free(config);
1656 	}
1657 }
1658 
1659 /*ARGSUSED*/
1660 static int
1661 dump_one_dir(char *dsname, void *arg)
1662 {
1663 	int error;
1664 	objset_t *os;
1665 
1666 	error = dmu_objset_own(dsname, DMU_OST_ANY, B_TRUE, FTAG, &os);
1667 	if (error) {
1668 		(void) printf("Could not open %s, error %d\n", dsname, error);
1669 		return (0);
1670 	}
1671 	dump_dir(os);
1672 	dmu_objset_disown(os, FTAG);
1673 	fuid_table_destroy();
1674 	return (0);
1675 }
1676 
1677 /*
1678  * Block statistics.
1679  */
1680 typedef struct zdb_blkstats {
1681 	uint64_t	zb_asize;
1682 	uint64_t	zb_lsize;
1683 	uint64_t	zb_psize;
1684 	uint64_t	zb_count;
1685 } zdb_blkstats_t;
1686 
1687 /*
1688  * Extended object types to report deferred frees and dedup auto-ditto blocks.
1689  */
1690 #define	ZDB_OT_DEFERRED	(DMU_OT_NUMTYPES + 0)
1691 #define	ZDB_OT_DITTO	(DMU_OT_NUMTYPES + 1)
1692 #define	ZDB_OT_TOTAL	(DMU_OT_NUMTYPES + 2)
1693 
1694 static char *zdb_ot_extname[] = {
1695 	"deferred free",
1696 	"dedup ditto",
1697 	"Total",
1698 };
1699 
1700 #define	ZB_TOTAL	DN_MAX_LEVELS
1701 
1702 typedef struct zdb_cb {
1703 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
1704 	uint64_t	zcb_dedup_asize;
1705 	uint64_t	zcb_dedup_blocks;
1706 	uint64_t	zcb_errors[256];
1707 	int		zcb_readfails;
1708 	int		zcb_haderrors;
1709 } zdb_cb_t;
1710 
1711 static void
1712 zdb_count_block(spa_t *spa, zilog_t *zilog, zdb_cb_t *zcb, const blkptr_t *bp,
1713     dmu_object_type_t type)
1714 {
1715 	uint64_t refcnt = 0;
1716 
1717 	ASSERT(type < ZDB_OT_TOTAL);
1718 
1719 	if (zilog && zil_bp_tree_add(zilog, bp) != 0)
1720 		return;
1721 
1722 	for (int i = 0; i < 4; i++) {
1723 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
1724 		int t = (i & 1) ? type : ZDB_OT_TOTAL;
1725 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
1726 
1727 		zb->zb_asize += BP_GET_ASIZE(bp);
1728 		zb->zb_lsize += BP_GET_LSIZE(bp);
1729 		zb->zb_psize += BP_GET_PSIZE(bp);
1730 		zb->zb_count++;
1731 	}
1732 
1733 	if (dump_opt['L'])
1734 		return;
1735 
1736 	if (BP_GET_DEDUP(bp)) {
1737 		ddt_t *ddt;
1738 		ddt_entry_t *dde;
1739 
1740 		ddt = ddt_select(spa, bp);
1741 		ddt_enter(ddt);
1742 		dde = ddt_lookup(ddt, bp, B_FALSE);
1743 
1744 		if (dde == NULL) {
1745 			refcnt = 0;
1746 		} else {
1747 			ddt_phys_t *ddp = ddt_phys_select(dde, bp);
1748 			ddt_phys_decref(ddp);
1749 			refcnt = ddp->ddp_refcnt;
1750 			if (ddt_phys_total_refcnt(dde) == 0)
1751 				ddt_remove(ddt, dde);
1752 		}
1753 		ddt_exit(ddt);
1754 	}
1755 
1756 	VERIFY3U(zio_wait(zio_claim(NULL, spa,
1757 	    refcnt ? 0 : spa_first_txg(spa),
1758 	    bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
1759 }
1760 
1761 static int
1762 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1763     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
1764 {
1765 	zdb_cb_t *zcb = arg;
1766 	char blkbuf[BP_SPRINTF_LEN];
1767 	dmu_object_type_t type;
1768 	boolean_t is_metadata;
1769 
1770 	if (bp == NULL)
1771 		return (0);
1772 
1773 	type = BP_GET_TYPE(bp);
1774 
1775 	zdb_count_block(spa, zilog, zcb, bp, type);
1776 
1777 	is_metadata = (BP_GET_LEVEL(bp) != 0 || dmu_ot[type].ot_metadata);
1778 
1779 	if (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata)) {
1780 		int ioerr;
1781 		size_t size = BP_GET_PSIZE(bp);
1782 		void *data = malloc(size);
1783 		int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
1784 
1785 		/* If it's an intent log block, failure is expected. */
1786 		if (zb->zb_level == ZB_ZIL_LEVEL)
1787 			flags |= ZIO_FLAG_SPECULATIVE;
1788 
1789 		ioerr = zio_wait(zio_read(NULL, spa, bp, data, size,
1790 		    NULL, NULL, ZIO_PRIORITY_ASYNC_READ, flags, zb));
1791 
1792 		free(data);
1793 
1794 		if (ioerr && !(flags & ZIO_FLAG_SPECULATIVE)) {
1795 			zcb->zcb_haderrors = 1;
1796 			zcb->zcb_errors[ioerr]++;
1797 
1798 			if (dump_opt['b'] >= 2)
1799 				sprintf_blkptr(blkbuf, bp);
1800 			else
1801 				blkbuf[0] = '\0';
1802 
1803 			(void) printf("zdb_blkptr_cb: "
1804 			    "Got error %d reading "
1805 			    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
1806 			    ioerr,
1807 			    (u_longlong_t)zb->zb_objset,
1808 			    (u_longlong_t)zb->zb_object,
1809 			    (u_longlong_t)zb->zb_level,
1810 			    (u_longlong_t)zb->zb_blkid,
1811 			    blkbuf);
1812 		}
1813 	}
1814 
1815 	zcb->zcb_readfails = 0;
1816 
1817 	if (dump_opt['b'] >= 4) {
1818 		sprintf_blkptr(blkbuf, bp);
1819 		(void) printf("objset %llu object %llu "
1820 		    "level %lld offset 0x%llx %s\n",
1821 		    (u_longlong_t)zb->zb_objset,
1822 		    (u_longlong_t)zb->zb_object,
1823 		    (longlong_t)zb->zb_level,
1824 		    (u_longlong_t)blkid2offset(dnp, bp, zb),
1825 		    blkbuf);
1826 	}
1827 
1828 	return (0);
1829 }
1830 
1831 static void
1832 zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
1833 {
1834 	vdev_t *vd = sm->sm_ppd;
1835 
1836 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
1837 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
1838 }
1839 
1840 /* ARGSUSED */
1841 static void
1842 zdb_space_map_load(space_map_t *sm)
1843 {
1844 }
1845 
1846 static void
1847 zdb_space_map_unload(space_map_t *sm)
1848 {
1849 	space_map_vacate(sm, zdb_leak, sm);
1850 }
1851 
1852 /* ARGSUSED */
1853 static void
1854 zdb_space_map_claim(space_map_t *sm, uint64_t start, uint64_t size)
1855 {
1856 }
1857 
1858 static space_map_ops_t zdb_space_map_ops = {
1859 	zdb_space_map_load,
1860 	zdb_space_map_unload,
1861 	NULL,	/* alloc */
1862 	zdb_space_map_claim,
1863 	NULL,	/* free */
1864 	NULL	/* maxsize */
1865 };
1866 
1867 static void
1868 zdb_ddt_leak_init(ddt_t *ddt, enum ddt_type type, enum ddt_class class,
1869     zdb_cb_t *zcb)
1870 {
1871 	uint64_t walk = 0;
1872 	ddt_entry_t dde;
1873 	int error;
1874 
1875 	if (class == DDT_CLASS_UNIQUE || !ddt_object_exists(ddt, type, class))
1876 		return;
1877 
1878 	while ((error = ddt_object_walk(ddt, type, class, &dde, &walk)) == 0) {
1879 		blkptr_t blk;
1880 		ddt_phys_t *ddp = dde.dde_phys;
1881 		ASSERT(ddt_phys_total_refcnt(&dde) > 1);
1882 		for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1883 			if (ddp->ddp_phys_birth == 0)
1884 				continue;
1885 			ddt_bp_create(ddt, &dde.dde_key, ddp, &blk);
1886 			if (p == DDT_PHYS_DITTO) {
1887 				zdb_count_block(ddt->ddt_spa, NULL, zcb, &blk,
1888 				    ZDB_OT_DITTO);
1889 			} else {
1890 				zcb->zcb_dedup_asize +=
1891 				    BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
1892 				zcb->zcb_dedup_blocks++;
1893 			}
1894 		}
1895 		if (!dump_opt['L']) {
1896 			ddt_enter(ddt);
1897 			VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
1898 			ddt_exit(ddt);
1899 		}
1900 	}
1901 
1902 	ASSERT(error == ENOENT);
1903 }
1904 
1905 static void
1906 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
1907 {
1908 	if (!dump_opt['L']) {
1909 		vdev_t *rvd = spa->spa_root_vdev;
1910 		for (int c = 0; c < rvd->vdev_children; c++) {
1911 			vdev_t *vd = rvd->vdev_child[c];
1912 			for (int m = 0; m < vd->vdev_ms_count; m++) {
1913 				metaslab_t *msp = vd->vdev_ms[m];
1914 				mutex_enter(&msp->ms_lock);
1915 				space_map_unload(&msp->ms_map);
1916 				VERIFY(space_map_load(&msp->ms_map,
1917 				    &zdb_space_map_ops, SM_ALLOC, &msp->ms_smo,
1918 				    spa->spa_meta_objset) == 0);
1919 				msp->ms_map.sm_ppd = vd;
1920 				mutex_exit(&msp->ms_lock);
1921 			}
1922 		}
1923 	}
1924 
1925 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1926 
1927 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++)
1928 		for (enum ddt_type type = 0; type < DDT_TYPES; type++)
1929 			for (enum ddt_class class = 0; class < DDT_CLASSES;
1930 			    class++)
1931 				zdb_ddt_leak_init(spa->spa_ddt[c],
1932 				    type, class, zcb);
1933 
1934 	spa_config_exit(spa, SCL_CONFIG, FTAG);
1935 }
1936 
1937 static void
1938 zdb_leak_fini(spa_t *spa)
1939 {
1940 	if (!dump_opt['L']) {
1941 		vdev_t *rvd = spa->spa_root_vdev;
1942 		for (int c = 0; c < rvd->vdev_children; c++) {
1943 			vdev_t *vd = rvd->vdev_child[c];
1944 			for (int m = 0; m < vd->vdev_ms_count; m++) {
1945 				metaslab_t *msp = vd->vdev_ms[m];
1946 				mutex_enter(&msp->ms_lock);
1947 				space_map_unload(&msp->ms_map);
1948 				mutex_exit(&msp->ms_lock);
1949 			}
1950 		}
1951 	}
1952 }
1953 
1954 static int
1955 dump_block_stats(spa_t *spa)
1956 {
1957 	zdb_cb_t zcb = { 0 };
1958 	zdb_blkstats_t *zb, *tzb;
1959 	uint64_t norm_alloc, norm_space, total_alloc, total_found;
1960 	int leaks = 0;
1961 
1962 	(void) printf("\nTraversing all blocks %s%s%s%s%s...\n",
1963 	    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
1964 	    (dump_opt['c'] == 1) ? "metadata " : "",
1965 	    dump_opt['c'] ? "checksums " : "",
1966 	    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
1967 	    !dump_opt['L'] ? "nothing leaked " : "");
1968 
1969 	/*
1970 	 * Load all space maps as SM_ALLOC maps, then traverse the pool
1971 	 * claiming each block we discover.  If the pool is perfectly
1972 	 * consistent, the space maps will be empty when we're done.
1973 	 * Anything left over is a leak; any block we can't claim (because
1974 	 * it's not part of any space map) is a double allocation,
1975 	 * reference to a freed block, or an unclaimed log block.
1976 	 */
1977 	zdb_leak_init(spa, &zcb);
1978 
1979 	/*
1980 	 * If there's a deferred-free bplist, process that first.
1981 	 */
1982 	if (spa->spa_deferred_bplist_obj != 0) {
1983 		bplist_t *bpl = &spa->spa_deferred_bplist;
1984 		blkptr_t blk;
1985 		uint64_t itor = 0;
1986 
1987 		VERIFY(0 == bplist_open(bpl, spa->spa_meta_objset,
1988 		    spa->spa_deferred_bplist_obj));
1989 
1990 		while (bplist_iterate(bpl, &itor, &blk) == 0) {
1991 			if (dump_opt['b'] >= 4) {
1992 				char blkbuf[BP_SPRINTF_LEN];
1993 				sprintf_blkptr(blkbuf, &blk);
1994 				(void) printf("[%s] %s\n",
1995 				    "deferred free", blkbuf);
1996 			}
1997 			zdb_count_block(spa, NULL, &zcb, &blk, ZDB_OT_DEFERRED);
1998 		}
1999 
2000 		bplist_close(bpl);
2001 	}
2002 
2003 	zcb.zcb_haderrors |= traverse_pool(spa, zdb_blkptr_cb, &zcb, 0);
2004 
2005 	if (zcb.zcb_haderrors) {
2006 		(void) printf("\nError counts:\n\n");
2007 		(void) printf("\t%5s  %s\n", "errno", "count");
2008 		for (int e = 0; e < 256; e++) {
2009 			if (zcb.zcb_errors[e] != 0) {
2010 				(void) printf("\t%5d  %llu\n",
2011 				    e, (u_longlong_t)zcb.zcb_errors[e]);
2012 			}
2013 		}
2014 	}
2015 
2016 	/*
2017 	 * Report any leaked segments.
2018 	 */
2019 	zdb_leak_fini(spa);
2020 
2021 	tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
2022 
2023 	norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
2024 	norm_space = metaslab_class_get_space(spa_normal_class(spa));
2025 
2026 	total_alloc = norm_alloc + metaslab_class_get_alloc(spa_log_class(spa));
2027 	total_found = tzb->zb_asize - zcb.zcb_dedup_asize;
2028 
2029 	if (total_found == total_alloc) {
2030 		if (!dump_opt['L'])
2031 			(void) printf("\n\tNo leaks (block sum matches space"
2032 			    " maps exactly)\n");
2033 	} else {
2034 		(void) printf("block traversal size %llu != alloc %llu "
2035 		    "(%s %lld)\n",
2036 		    (u_longlong_t)total_found,
2037 		    (u_longlong_t)total_alloc,
2038 		    (dump_opt['L']) ? "unreachable" : "leaked",
2039 		    (longlong_t)(total_alloc - total_found));
2040 		leaks = 1;
2041 	}
2042 
2043 	if (tzb->zb_count == 0)
2044 		return (2);
2045 
2046 	(void) printf("\n");
2047 	(void) printf("\tbp count:      %10llu\n",
2048 	    (u_longlong_t)tzb->zb_count);
2049 	(void) printf("\tbp logical:    %10llu      avg: %6llu\n",
2050 	    (u_longlong_t)tzb->zb_lsize,
2051 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
2052 	(void) printf("\tbp physical:   %10llu      avg:"
2053 	    " %6llu     compression: %6.2f\n",
2054 	    (u_longlong_t)tzb->zb_psize,
2055 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
2056 	    (double)tzb->zb_lsize / tzb->zb_psize);
2057 	(void) printf("\tbp allocated:  %10llu      avg:"
2058 	    " %6llu     compression: %6.2f\n",
2059 	    (u_longlong_t)tzb->zb_asize,
2060 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
2061 	    (double)tzb->zb_lsize / tzb->zb_asize);
2062 	(void) printf("\tbp deduped:    %10llu    ref>1:"
2063 	    " %6llu   deduplication: %6.2f\n",
2064 	    (u_longlong_t)zcb.zcb_dedup_asize,
2065 	    (u_longlong_t)zcb.zcb_dedup_blocks,
2066 	    (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
2067 	(void) printf("\tSPA allocated: %10llu     used: %5.2f%%\n",
2068 	    (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
2069 
2070 	if (dump_opt['b'] >= 2) {
2071 		int l, t, level;
2072 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
2073 		    "\t  avg\t comp\t%%Total\tType\n");
2074 
2075 		for (t = 0; t <= ZDB_OT_TOTAL; t++) {
2076 			char csize[6], lsize[6], psize[6], asize[6], avg[6];
2077 			char *typename;
2078 
2079 			if (t < DMU_OT_NUMTYPES)
2080 				typename = dmu_ot[t].ot_name;
2081 			else
2082 				typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
2083 
2084 			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
2085 				(void) printf("%6s\t%5s\t%5s\t%5s"
2086 				    "\t%5s\t%5s\t%6s\t%s\n",
2087 				    "-",
2088 				    "-",
2089 				    "-",
2090 				    "-",
2091 				    "-",
2092 				    "-",
2093 				    "-",
2094 				    typename);
2095 				continue;
2096 			}
2097 
2098 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
2099 				level = (l == -1 ? ZB_TOTAL : l);
2100 				zb = &zcb.zcb_type[level][t];
2101 
2102 				if (zb->zb_asize == 0)
2103 					continue;
2104 
2105 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
2106 					continue;
2107 
2108 				if (level == 0 && zb->zb_asize ==
2109 				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
2110 					continue;
2111 
2112 				nicenum(zb->zb_count, csize);
2113 				nicenum(zb->zb_lsize, lsize);
2114 				nicenum(zb->zb_psize, psize);
2115 				nicenum(zb->zb_asize, asize);
2116 				nicenum(zb->zb_asize / zb->zb_count, avg);
2117 
2118 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
2119 				    "\t%5.2f\t%6.2f\t",
2120 				    csize, lsize, psize, asize, avg,
2121 				    (double)zb->zb_lsize / zb->zb_psize,
2122 				    100.0 * zb->zb_asize / tzb->zb_asize);
2123 
2124 				if (level == ZB_TOTAL)
2125 					(void) printf("%s\n", typename);
2126 				else
2127 					(void) printf("    L%d %s\n",
2128 					    level, typename);
2129 			}
2130 		}
2131 	}
2132 
2133 	(void) printf("\n");
2134 
2135 	if (leaks)
2136 		return (2);
2137 
2138 	if (zcb.zcb_haderrors)
2139 		return (3);
2140 
2141 	return (0);
2142 }
2143 
2144 typedef struct zdb_ddt_entry {
2145 	ddt_key_t	zdde_key;
2146 	uint64_t	zdde_ref_blocks;
2147 	uint64_t	zdde_ref_lsize;
2148 	uint64_t	zdde_ref_psize;
2149 	uint64_t	zdde_ref_dsize;
2150 	avl_node_t	zdde_node;
2151 } zdb_ddt_entry_t;
2152 
2153 /* ARGSUSED */
2154 static int
2155 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2156     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
2157 {
2158 	avl_tree_t *t = arg;
2159 	avl_index_t where;
2160 	zdb_ddt_entry_t *zdde, zdde_search;
2161 
2162 	if (bp == NULL)
2163 		return (0);
2164 
2165 	if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
2166 		(void) printf("traversing objset %llu, %llu objects, "
2167 		    "%lu blocks so far\n",
2168 		    (u_longlong_t)zb->zb_objset,
2169 		    (u_longlong_t)bp->blk_fill,
2170 		    avl_numnodes(t));
2171 	}
2172 
2173 	if (BP_GET_LEVEL(bp) > 0 || dmu_ot[BP_GET_TYPE(bp)].ot_metadata)
2174 		return (0);
2175 
2176 	ddt_key_fill(&zdde_search.zdde_key, bp);
2177 
2178 	zdde = avl_find(t, &zdde_search, &where);
2179 
2180 	if (zdde == NULL) {
2181 		zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
2182 		zdde->zdde_key = zdde_search.zdde_key;
2183 		avl_insert(t, zdde, where);
2184 	}
2185 
2186 	zdde->zdde_ref_blocks += 1;
2187 	zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
2188 	zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
2189 	zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
2190 
2191 	return (0);
2192 }
2193 
2194 static void
2195 dump_simulated_ddt(spa_t *spa)
2196 {
2197 	avl_tree_t t;
2198 	void *cookie = NULL;
2199 	zdb_ddt_entry_t *zdde;
2200 	ddt_histogram_t ddh_total = { 0 };
2201 	ddt_stat_t dds_total = { 0 };
2202 
2203 	avl_create(&t, ddt_entry_compare,
2204 	    sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
2205 
2206 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2207 
2208 	(void) traverse_pool(spa, zdb_ddt_add_cb, &t, 0);
2209 
2210 	spa_config_exit(spa, SCL_CONFIG, FTAG);
2211 
2212 	while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
2213 		ddt_stat_t dds;
2214 		uint64_t refcnt = zdde->zdde_ref_blocks;
2215 		ASSERT(refcnt != 0);
2216 
2217 		dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
2218 		dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
2219 		dds.dds_psize = zdde->zdde_ref_psize / refcnt;
2220 		dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
2221 
2222 		dds.dds_ref_blocks = zdde->zdde_ref_blocks;
2223 		dds.dds_ref_lsize = zdde->zdde_ref_lsize;
2224 		dds.dds_ref_psize = zdde->zdde_ref_psize;
2225 		dds.dds_ref_dsize = zdde->zdde_ref_dsize;
2226 
2227 		ddt_stat_add(&ddh_total.ddh_stat[highbit(refcnt) - 1], &dds, 0);
2228 
2229 		umem_free(zdde, sizeof (*zdde));
2230 	}
2231 
2232 	avl_destroy(&t);
2233 
2234 	ddt_histogram_stat(&dds_total, &ddh_total);
2235 
2236 	(void) printf("Simulated DDT histogram:\n");
2237 
2238 	dump_ddt_histogram(&ddh_total);
2239 
2240 	dump_dedup_ratio(&dds_total);
2241 }
2242 
2243 static void
2244 dump_zpool(spa_t *spa)
2245 {
2246 	dsl_pool_t *dp = spa_get_dsl(spa);
2247 	int rc = 0;
2248 
2249 	if (dump_opt['S']) {
2250 		dump_simulated_ddt(spa);
2251 		return;
2252 	}
2253 
2254 	if (!dump_opt['e'] && dump_opt['C'] > 1) {
2255 		(void) printf("\nCached configuration:\n");
2256 		dump_nvlist(spa->spa_config, 8);
2257 	}
2258 
2259 	if (dump_opt['C'])
2260 		dump_config(spa);
2261 
2262 	if (dump_opt['u'])
2263 		dump_uberblock(&spa->spa_uberblock);
2264 
2265 	if (dump_opt['D'])
2266 		dump_all_ddts(spa);
2267 
2268 	if (dump_opt['d'] > 2 || dump_opt['m'])
2269 		dump_metaslabs(spa);
2270 
2271 	if (dump_opt['d'] || dump_opt['i']) {
2272 		dump_dir(dp->dp_meta_objset);
2273 		if (dump_opt['d'] >= 3) {
2274 			dump_bplist(dp->dp_meta_objset,
2275 			    spa->spa_deferred_bplist_obj, "Deferred frees");
2276 			dump_dtl(spa->spa_root_vdev, 0);
2277 		}
2278 		(void) dmu_objset_find(spa_name(spa), dump_one_dir,
2279 		    NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
2280 	}
2281 	if (dump_opt['b'] || dump_opt['c'])
2282 		rc = dump_block_stats(spa);
2283 
2284 	if (dump_opt['s'])
2285 		show_pool_stats(spa);
2286 
2287 	if (dump_opt['h'])
2288 		dump_history(spa);
2289 
2290 	if (rc != 0)
2291 		exit(rc);
2292 }
2293 
2294 #define	ZDB_FLAG_CHECKSUM	0x0001
2295 #define	ZDB_FLAG_DECOMPRESS	0x0002
2296 #define	ZDB_FLAG_BSWAP		0x0004
2297 #define	ZDB_FLAG_GBH		0x0008
2298 #define	ZDB_FLAG_INDIRECT	0x0010
2299 #define	ZDB_FLAG_PHYS		0x0020
2300 #define	ZDB_FLAG_RAW		0x0040
2301 #define	ZDB_FLAG_PRINT_BLKPTR	0x0080
2302 
2303 int flagbits[256];
2304 
2305 static void
2306 zdb_print_blkptr(blkptr_t *bp, int flags)
2307 {
2308 	char blkbuf[BP_SPRINTF_LEN];
2309 
2310 	if (flags & ZDB_FLAG_BSWAP)
2311 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
2312 
2313 	sprintf_blkptr(blkbuf, bp);
2314 	(void) printf("%s\n", blkbuf);
2315 }
2316 
2317 static void
2318 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
2319 {
2320 	int i;
2321 
2322 	for (i = 0; i < nbps; i++)
2323 		zdb_print_blkptr(&bp[i], flags);
2324 }
2325 
2326 static void
2327 zdb_dump_gbh(void *buf, int flags)
2328 {
2329 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
2330 }
2331 
2332 static void
2333 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
2334 {
2335 	if (flags & ZDB_FLAG_BSWAP)
2336 		byteswap_uint64_array(buf, size);
2337 	(void) write(1, buf, size);
2338 }
2339 
2340 static void
2341 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
2342 {
2343 	uint64_t *d = (uint64_t *)buf;
2344 	int nwords = size / sizeof (uint64_t);
2345 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
2346 	int i, j;
2347 	char *hdr, *c;
2348 
2349 
2350 	if (do_bswap)
2351 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
2352 	else
2353 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
2354 
2355 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
2356 
2357 	for (i = 0; i < nwords; i += 2) {
2358 		(void) printf("%06llx:  %016llx  %016llx  ",
2359 		    (u_longlong_t)(i * sizeof (uint64_t)),
2360 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
2361 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
2362 
2363 		c = (char *)&d[i];
2364 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
2365 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
2366 		(void) printf("\n");
2367 	}
2368 }
2369 
2370 /*
2371  * There are two acceptable formats:
2372  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
2373  *	child[.child]*    - For example: 0.1.1
2374  *
2375  * The second form can be used to specify arbitrary vdevs anywhere
2376  * in the heirarchy.  For example, in a pool with a mirror of
2377  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
2378  */
2379 static vdev_t *
2380 zdb_vdev_lookup(vdev_t *vdev, char *path)
2381 {
2382 	char *s, *p, *q;
2383 	int i;
2384 
2385 	if (vdev == NULL)
2386 		return (NULL);
2387 
2388 	/* First, assume the x.x.x.x format */
2389 	i = (int)strtoul(path, &s, 10);
2390 	if (s == path || (s && *s != '.' && *s != '\0'))
2391 		goto name;
2392 	if (i < 0 || i >= vdev->vdev_children)
2393 		return (NULL);
2394 
2395 	vdev = vdev->vdev_child[i];
2396 	if (*s == '\0')
2397 		return (vdev);
2398 	return (zdb_vdev_lookup(vdev, s+1));
2399 
2400 name:
2401 	for (i = 0; i < vdev->vdev_children; i++) {
2402 		vdev_t *vc = vdev->vdev_child[i];
2403 
2404 		if (vc->vdev_path == NULL) {
2405 			vc = zdb_vdev_lookup(vc, path);
2406 			if (vc == NULL)
2407 				continue;
2408 			else
2409 				return (vc);
2410 		}
2411 
2412 		p = strrchr(vc->vdev_path, '/');
2413 		p = p ? p + 1 : vc->vdev_path;
2414 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2415 
2416 		if (strcmp(vc->vdev_path, path) == 0)
2417 			return (vc);
2418 		if (strcmp(p, path) == 0)
2419 			return (vc);
2420 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2421 			return (vc);
2422 	}
2423 
2424 	return (NULL);
2425 }
2426 
2427 /*
2428  * Read a block from a pool and print it out.  The syntax of the
2429  * block descriptor is:
2430  *
2431  *	pool:vdev_specifier:offset:size[:flags]
2432  *
2433  *	pool           - The name of the pool you wish to read from
2434  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2435  *	offset         - offset, in hex, in bytes
2436  *	size           - Amount of data to read, in hex, in bytes
2437  *	flags          - A string of characters specifying options
2438  *		 b: Decode a blkptr at given offset within block
2439  *		*c: Calculate and display checksums
2440  *		 d: Decompress data before dumping
2441  *		 e: Byteswap data before dumping
2442  *		 g: Display data as a gang block header
2443  *		 i: Display as an indirect block
2444  *		 p: Do I/O to physical offset
2445  *		 r: Dump raw data to stdout
2446  *
2447  *              * = not yet implemented
2448  */
2449 static void
2450 zdb_read_block(char *thing, spa_t *spa)
2451 {
2452 	blkptr_t blk, *bp = &blk;
2453 	dva_t *dva = bp->blk_dva;
2454 	int flags = 0;
2455 	uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
2456 	zio_t *zio;
2457 	vdev_t *vd;
2458 	void *pbuf, *lbuf, *buf;
2459 	char *s, *p, *dup, *vdev, *flagstr;
2460 	int i, error;
2461 
2462 	dup = strdup(thing);
2463 	s = strtok(dup, ":");
2464 	vdev = s ? s : "";
2465 	s = strtok(NULL, ":");
2466 	offset = strtoull(s ? s : "", NULL, 16);
2467 	s = strtok(NULL, ":");
2468 	size = strtoull(s ? s : "", NULL, 16);
2469 	s = strtok(NULL, ":");
2470 	flagstr = s ? s : "";
2471 
2472 	s = NULL;
2473 	if (size == 0)
2474 		s = "size must not be zero";
2475 	if (!IS_P2ALIGNED(size, DEV_BSIZE))
2476 		s = "size must be a multiple of sector size";
2477 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
2478 		s = "offset must be a multiple of sector size";
2479 	if (s) {
2480 		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
2481 		free(dup);
2482 		return;
2483 	}
2484 
2485 	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
2486 		for (i = 0; flagstr[i]; i++) {
2487 			int bit = flagbits[(uchar_t)flagstr[i]];
2488 
2489 			if (bit == 0) {
2490 				(void) printf("***Invalid flag: %c\n",
2491 				    flagstr[i]);
2492 				continue;
2493 			}
2494 			flags |= bit;
2495 
2496 			/* If it's not something with an argument, keep going */
2497 			if ((bit & (ZDB_FLAG_CHECKSUM |
2498 			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
2499 				continue;
2500 
2501 			p = &flagstr[i + 1];
2502 			if (bit == ZDB_FLAG_PRINT_BLKPTR)
2503 				blkptr_offset = strtoull(p, &p, 16);
2504 			if (*p != ':' && *p != '\0') {
2505 				(void) printf("***Invalid flag arg: '%s'\n", s);
2506 				free(dup);
2507 				return;
2508 			}
2509 		}
2510 	}
2511 
2512 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2513 	if (vd == NULL) {
2514 		(void) printf("***Invalid vdev: %s\n", vdev);
2515 		free(dup);
2516 		return;
2517 	} else {
2518 		if (vd->vdev_path)
2519 			(void) fprintf(stderr, "Found vdev: %s\n",
2520 			    vd->vdev_path);
2521 		else
2522 			(void) fprintf(stderr, "Found vdev type: %s\n",
2523 			    vd->vdev_ops->vdev_op_type);
2524 	}
2525 
2526 	psize = size;
2527 	lsize = size;
2528 
2529 	pbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2530 	lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2531 
2532 	BP_ZERO(bp);
2533 
2534 	DVA_SET_VDEV(&dva[0], vd->vdev_id);
2535 	DVA_SET_OFFSET(&dva[0], offset);
2536 	DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
2537 	DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
2538 
2539 	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
2540 
2541 	BP_SET_LSIZE(bp, lsize);
2542 	BP_SET_PSIZE(bp, psize);
2543 	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
2544 	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
2545 	BP_SET_TYPE(bp, DMU_OT_NONE);
2546 	BP_SET_LEVEL(bp, 0);
2547 	BP_SET_DEDUP(bp, 0);
2548 	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
2549 
2550 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
2551 	zio = zio_root(spa, NULL, NULL, 0);
2552 
2553 	if (vd == vd->vdev_top) {
2554 		/*
2555 		 * Treat this as a normal block read.
2556 		 */
2557 		zio_nowait(zio_read(zio, spa, bp, pbuf, psize, NULL, NULL,
2558 		    ZIO_PRIORITY_SYNC_READ,
2559 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
2560 	} else {
2561 		/*
2562 		 * Treat this as a vdev child I/O.
2563 		 */
2564 		zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pbuf, psize,
2565 		    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
2566 		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2567 		    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
2568 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL, NULL));
2569 	}
2570 
2571 	error = zio_wait(zio);
2572 	spa_config_exit(spa, SCL_STATE, FTAG);
2573 
2574 	if (error) {
2575 		(void) printf("Read of %s failed, error: %d\n", thing, error);
2576 		goto out;
2577 	}
2578 
2579 	if (flags & ZDB_FLAG_DECOMPRESS) {
2580 		/*
2581 		 * We don't know how the data was compressed, so just try
2582 		 * every decompress function at every inflated blocksize.
2583 		 */
2584 		enum zio_compress c;
2585 		void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2586 		void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2587 
2588 		bcopy(pbuf, pbuf2, psize);
2589 
2590 		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf + psize,
2591 		    SPA_MAXBLOCKSIZE - psize) == 0);
2592 
2593 		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
2594 		    SPA_MAXBLOCKSIZE - psize) == 0);
2595 
2596 		for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
2597 		    lsize -= SPA_MINBLOCKSIZE) {
2598 			for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
2599 				if (zio_decompress_data(c, pbuf, lbuf,
2600 				    psize, lsize) == 0 &&
2601 				    zio_decompress_data(c, pbuf2, lbuf2,
2602 				    psize, lsize) == 0 &&
2603 				    bcmp(lbuf, lbuf2, lsize) == 0)
2604 					break;
2605 			}
2606 			if (c != ZIO_COMPRESS_FUNCTIONS)
2607 				break;
2608 			lsize -= SPA_MINBLOCKSIZE;
2609 		}
2610 
2611 		umem_free(pbuf2, SPA_MAXBLOCKSIZE);
2612 		umem_free(lbuf2, SPA_MAXBLOCKSIZE);
2613 
2614 		if (lsize <= psize) {
2615 			(void) printf("Decompress of %s failed\n", thing);
2616 			goto out;
2617 		}
2618 		buf = lbuf;
2619 		size = lsize;
2620 	} else {
2621 		buf = pbuf;
2622 		size = psize;
2623 	}
2624 
2625 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2626 		zdb_print_blkptr((blkptr_t *)(void *)
2627 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2628 	else if (flags & ZDB_FLAG_RAW)
2629 		zdb_dump_block_raw(buf, size, flags);
2630 	else if (flags & ZDB_FLAG_INDIRECT)
2631 		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2632 		    flags);
2633 	else if (flags & ZDB_FLAG_GBH)
2634 		zdb_dump_gbh(buf, flags);
2635 	else
2636 		zdb_dump_block(thing, buf, size, flags);
2637 
2638 out:
2639 	umem_free(pbuf, SPA_MAXBLOCKSIZE);
2640 	umem_free(lbuf, SPA_MAXBLOCKSIZE);
2641 	free(dup);
2642 }
2643 
2644 static boolean_t
2645 pool_match(nvlist_t *cfg, char *tgt)
2646 {
2647 	uint64_t v, guid = strtoull(tgt, NULL, 0);
2648 	char *s;
2649 
2650 	if (guid != 0) {
2651 		if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
2652 			return (v == guid);
2653 	} else {
2654 		if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
2655 			return (strcmp(s, tgt) == 0);
2656 	}
2657 	return (B_FALSE);
2658 }
2659 
2660 static char *
2661 find_zpool(char **target, nvlist_t **configp, int dirc, char **dirv)
2662 {
2663 	nvlist_t *pools;
2664 	nvlist_t *match = NULL;
2665 	char *name = NULL;
2666 	char *sepp = NULL;
2667 	char sep;
2668 	int count = 0;
2669 
2670 	if ((sepp = strpbrk(*target, "/@")) != NULL) {
2671 		sep = *sepp;
2672 		*sepp = '\0';
2673 	}
2674 
2675 	pools = zpool_find_import_activeok(g_zfs, dirc, dirv);
2676 
2677 	if (pools != NULL) {
2678 		nvpair_t *elem = NULL;
2679 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2680 			verify(nvpair_value_nvlist(elem, configp) == 0);
2681 			if (pool_match(*configp, *target)) {
2682 				count++;
2683 				if (match != NULL) {
2684 					/* print previously found config */
2685 					if (name != NULL) {
2686 						(void) printf("%s\n", name);
2687 						dump_nvlist(match, 8);
2688 						name = NULL;
2689 					}
2690 					(void) printf("%s\n",
2691 					    nvpair_name(elem));
2692 					dump_nvlist(*configp, 8);
2693 				} else {
2694 					match = *configp;
2695 					name = nvpair_name(elem);
2696 				}
2697 			}
2698 		}
2699 	}
2700 	if (count > 1)
2701 		(void) fatal("\tMatched %d pools - use pool GUID "
2702 		    "instead of pool name or \n"
2703 		    "\tpool name part of a dataset name to select pool", count);
2704 
2705 	if (sepp)
2706 		*sepp = sep;
2707 	/*
2708 	 * If pool GUID was specified for pool id, replace it with pool name
2709 	 */
2710 	if (name && (strstr(*target, name) != *target)) {
2711 		int sz = 1 + strlen(name) + ((sepp) ? strlen(sepp) : 0);
2712 
2713 		*target = umem_alloc(sz, UMEM_NOFAIL);
2714 		(void) snprintf(*target, sz, "%s%s", name, sepp ? sepp : "");
2715 	}
2716 
2717 	*configp = name ? match : NULL;
2718 
2719 	return (name);
2720 }
2721 
2722 int
2723 main(int argc, char **argv)
2724 {
2725 	int i, c;
2726 	struct rlimit rl = { 1024, 1024 };
2727 	spa_t *spa = NULL;
2728 	objset_t *os = NULL;
2729 	int dump_all = 1;
2730 	int verbose = 0;
2731 	int error;
2732 	char **searchdirs = NULL;
2733 	int nsearch = 0;
2734 	char *target;
2735 	nvlist_t *policy = NULL;
2736 	uint64_t max_txg = UINT64_MAX;
2737 
2738 	(void) setrlimit(RLIMIT_NOFILE, &rl);
2739 	(void) enable_extended_FILE_stdio(-1, -1);
2740 
2741 	dprintf_setup(&argc, argv);
2742 
2743 	while ((c = getopt(argc, argv, "bcdhilmsuCDRSLevp:t:U:")) != -1) {
2744 		switch (c) {
2745 		case 'b':
2746 		case 'c':
2747 		case 'd':
2748 		case 'h':
2749 		case 'i':
2750 		case 'l':
2751 		case 'm':
2752 		case 's':
2753 		case 'u':
2754 		case 'C':
2755 		case 'D':
2756 		case 'R':
2757 		case 'S':
2758 			dump_opt[c]++;
2759 			dump_all = 0;
2760 			break;
2761 		case 'L':
2762 		case 'e':
2763 			dump_opt[c]++;
2764 			break;
2765 		case 'v':
2766 			verbose++;
2767 			break;
2768 		case 'p':
2769 			if (searchdirs == NULL) {
2770 				searchdirs = umem_alloc(sizeof (char *),
2771 				    UMEM_NOFAIL);
2772 			} else {
2773 				char **tmp = umem_alloc((nsearch + 1) *
2774 				    sizeof (char *), UMEM_NOFAIL);
2775 				bcopy(searchdirs, tmp, nsearch *
2776 				    sizeof (char *));
2777 				umem_free(searchdirs,
2778 				    nsearch * sizeof (char *));
2779 				searchdirs = tmp;
2780 			}
2781 			searchdirs[nsearch++] = optarg;
2782 			break;
2783 		case 't':
2784 			max_txg = strtoull(optarg, NULL, 0);
2785 			if (max_txg < TXG_INITIAL) {
2786 				(void) fprintf(stderr, "incorrect txg "
2787 				    "specified: %s\n", optarg);
2788 				usage();
2789 			}
2790 			break;
2791 		case 'U':
2792 			spa_config_path = optarg;
2793 			break;
2794 		default:
2795 			usage();
2796 			break;
2797 		}
2798 	}
2799 
2800 	if (!dump_opt['e'] && searchdirs != NULL) {
2801 		(void) fprintf(stderr, "-p option requires use of -e\n");
2802 		usage();
2803 	}
2804 
2805 	kernel_init(FREAD);
2806 	g_zfs = libzfs_init();
2807 	ASSERT(g_zfs != NULL);
2808 
2809 	if (dump_all)
2810 		verbose = MAX(verbose, 1);
2811 
2812 	for (c = 0; c < 256; c++) {
2813 		if (dump_all && !strchr("elLRS", c))
2814 			dump_opt[c] = 1;
2815 		if (dump_opt[c])
2816 			dump_opt[c] += verbose;
2817 	}
2818 
2819 	argc -= optind;
2820 	argv += optind;
2821 
2822 	if (argc < 2 && dump_opt['R'])
2823 		usage();
2824 	if (argc < 1) {
2825 		if (!dump_opt['e'] && dump_opt['C']) {
2826 			dump_cachefile(spa_config_path);
2827 			return (0);
2828 		}
2829 		usage();
2830 	}
2831 
2832 	if (dump_opt['l']) {
2833 		dump_label(argv[0]);
2834 		return (0);
2835 	}
2836 
2837 	error = 0;
2838 	target = argv[0];
2839 
2840 	if (dump_opt['e']) {
2841 		nvlist_t *cfg = NULL;
2842 		char *name = find_zpool(&target, &cfg, nsearch, searchdirs);
2843 
2844 		error = ENOENT;
2845 		if (name) {
2846 			if (dump_opt['C'] > 1) {
2847 				(void) printf("\nConfiguration for import:\n");
2848 				dump_nvlist(cfg, 8);
2849 			}
2850 			if (nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) != 0 ||
2851 			    nvlist_add_uint64(policy,
2852 			    ZPOOL_REWIND_REQUEST_TXG, max_txg) != 0 ||
2853 			    nvlist_add_nvlist(cfg,
2854 			    ZPOOL_REWIND_POLICY, policy) != 0) {
2855 				fatal("can't open '%s': %s",
2856 				    target, strerror(ENOMEM));
2857 			}
2858 			if ((error = spa_import(name, cfg, NULL)) != 0)
2859 				error = spa_import_verbatim(name, cfg, NULL);
2860 			nvlist_free(policy);
2861 		}
2862 	}
2863 
2864 	if (error == 0) {
2865 		if (strpbrk(target, "/@") == NULL || dump_opt['R']) {
2866 			error = spa_open(target, &spa, FTAG);
2867 			if (error) {
2868 				/*
2869 				 * If we're missing the log device then
2870 				 * try opening the pool after clearing the
2871 				 * log state.
2872 				 */
2873 				mutex_enter(&spa_namespace_lock);
2874 				if ((spa = spa_lookup(target)) != NULL &&
2875 				    spa->spa_log_state == SPA_LOG_MISSING) {
2876 					spa->spa_log_state = SPA_LOG_CLEAR;
2877 					error = 0;
2878 				}
2879 				mutex_exit(&spa_namespace_lock);
2880 
2881 				if (!error)
2882 					error = spa_open(target, &spa, FTAG);
2883 			}
2884 		} else {
2885 			error = dmu_objset_own(target, DMU_OST_ANY,
2886 			    B_TRUE, FTAG, &os);
2887 		}
2888 	}
2889 	if (error)
2890 		fatal("can't open '%s': %s", target, strerror(error));
2891 
2892 	argv++;
2893 	argc--;
2894 	if (!dump_opt['R']) {
2895 		if (argc > 0) {
2896 			zopt_objects = argc;
2897 			zopt_object = calloc(zopt_objects, sizeof (uint64_t));
2898 			for (i = 0; i < zopt_objects; i++) {
2899 				errno = 0;
2900 				zopt_object[i] = strtoull(argv[i], NULL, 0);
2901 				if (zopt_object[i] == 0 && errno != 0)
2902 					fatal("bad number %s: %s",
2903 					    argv[i], strerror(errno));
2904 			}
2905 		}
2906 		(os != NULL) ? dump_dir(os) : dump_zpool(spa);
2907 	} else {
2908 		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
2909 		flagbits['c'] = ZDB_FLAG_CHECKSUM;
2910 		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
2911 		flagbits['e'] = ZDB_FLAG_BSWAP;
2912 		flagbits['g'] = ZDB_FLAG_GBH;
2913 		flagbits['i'] = ZDB_FLAG_INDIRECT;
2914 		flagbits['p'] = ZDB_FLAG_PHYS;
2915 		flagbits['r'] = ZDB_FLAG_RAW;
2916 
2917 		for (i = 0; i < argc; i++)
2918 			zdb_read_block(argv[i], spa);
2919 	}
2920 
2921 	(os != NULL) ? dmu_objset_disown(os, FTAG) : spa_close(spa, FTAG);
2922 
2923 	fuid_table_destroy();
2924 
2925 	libzfs_fini(g_zfs);
2926 	kernel_fini();
2927 
2928 	return (0);
2929 }
2930