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