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