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