zdb.c revision 319263
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	z_crtime = (time_t)crtm[0];
1723	z_atime = (time_t)acctm[0];
1724	z_mtime = (time_t)modtm[0];
1725	z_ctime = (time_t)chgtm[0];
1726
1727	if (dump_opt['d'] > 4) {
1728		error = zfs_obj_to_path(os, object, path, sizeof (path));
1729		if (error != 0) {
1730			(void) snprintf(path, sizeof (path),
1731			    "\?\?\?<object#%llu>", (u_longlong_t)object);
1732		}
1733		(void) printf("\tpath	%s\n", path);
1734	}
1735	dump_uidgid(os, uid, gid);
1736	(void) printf("\tatime	%s", ctime(&z_atime));
1737	(void) printf("\tmtime	%s", ctime(&z_mtime));
1738	(void) printf("\tctime	%s", ctime(&z_ctime));
1739	(void) printf("\tcrtime	%s", ctime(&z_crtime));
1740	(void) printf("\tgen	%llu\n", (u_longlong_t)gen);
1741	(void) printf("\tmode	%llo\n", (u_longlong_t)mode);
1742	(void) printf("\tsize	%llu\n", (u_longlong_t)fsize);
1743	(void) printf("\tparent	%llu\n", (u_longlong_t)parent);
1744	(void) printf("\tlinks	%llu\n", (u_longlong_t)links);
1745	(void) printf("\tpflags	%llx\n", (u_longlong_t)pflags);
1746	if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
1747	    sizeof (uint64_t)) == 0)
1748		(void) printf("\txattr	%llu\n", (u_longlong_t)xattr);
1749	if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
1750	    sizeof (uint64_t)) == 0)
1751		(void) printf("\trdev	0x%016llx\n", (u_longlong_t)rdev);
1752	sa_handle_destroy(hdl);
1753}
1754
1755/*ARGSUSED*/
1756static void
1757dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
1758{
1759}
1760
1761/*ARGSUSED*/
1762static void
1763dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
1764{
1765}
1766
1767static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
1768	dump_none,		/* unallocated			*/
1769	dump_zap,		/* object directory		*/
1770	dump_uint64,		/* object array			*/
1771	dump_none,		/* packed nvlist		*/
1772	dump_packed_nvlist,	/* packed nvlist size		*/
1773	dump_none,		/* bpobj			*/
1774	dump_bpobj,		/* bpobj header			*/
1775	dump_none,		/* SPA space map header		*/
1776	dump_none,		/* SPA space map		*/
1777	dump_none,		/* ZIL intent log		*/
1778	dump_dnode,		/* DMU dnode			*/
1779	dump_dmu_objset,	/* DMU objset			*/
1780	dump_dsl_dir,		/* DSL directory		*/
1781	dump_zap,		/* DSL directory child map	*/
1782	dump_zap,		/* DSL dataset snap map		*/
1783	dump_zap,		/* DSL props			*/
1784	dump_dsl_dataset,	/* DSL dataset			*/
1785	dump_znode,		/* ZFS znode			*/
1786	dump_acl,		/* ZFS V0 ACL			*/
1787	dump_uint8,		/* ZFS plain file		*/
1788	dump_zpldir,		/* ZFS directory		*/
1789	dump_zap,		/* ZFS master node		*/
1790	dump_zap,		/* ZFS delete queue		*/
1791	dump_uint8,		/* zvol object			*/
1792	dump_zap,		/* zvol prop			*/
1793	dump_uint8,		/* other uint8[]		*/
1794	dump_uint64,		/* other uint64[]		*/
1795	dump_zap,		/* other ZAP			*/
1796	dump_zap,		/* persistent error log		*/
1797	dump_uint8,		/* SPA history			*/
1798	dump_history_offsets,	/* SPA history offsets		*/
1799	dump_zap,		/* Pool properties		*/
1800	dump_zap,		/* DSL permissions		*/
1801	dump_acl,		/* ZFS ACL			*/
1802	dump_uint8,		/* ZFS SYSACL			*/
1803	dump_none,		/* FUID nvlist			*/
1804	dump_packed_nvlist,	/* FUID nvlist size		*/
1805	dump_zap,		/* DSL dataset next clones	*/
1806	dump_zap,		/* DSL scrub queue		*/
1807	dump_zap,		/* ZFS user/group used		*/
1808	dump_zap,		/* ZFS user/group quota		*/
1809	dump_zap,		/* snapshot refcount tags	*/
1810	dump_ddt_zap,		/* DDT ZAP object		*/
1811	dump_zap,		/* DDT statistics		*/
1812	dump_znode,		/* SA object			*/
1813	dump_zap,		/* SA Master Node		*/
1814	dump_sa_attrs,		/* SA attribute registration	*/
1815	dump_sa_layouts,	/* SA attribute layouts		*/
1816	dump_zap,		/* DSL scrub translations	*/
1817	dump_none,		/* fake dedup BP		*/
1818	dump_zap,		/* deadlist			*/
1819	dump_none,		/* deadlist hdr			*/
1820	dump_zap,		/* dsl clones			*/
1821	dump_bpobj_subobjs,	/* bpobj subobjs		*/
1822	dump_unknown,		/* Unknown type, must be last	*/
1823};
1824
1825static void
1826dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1827{
1828	dmu_buf_t *db = NULL;
1829	dmu_object_info_t doi;
1830	dnode_t *dn;
1831	void *bonus = NULL;
1832	size_t bsize = 0;
1833	char iblk[32], dblk[32], lsize[32], asize[32], fill[32];
1834	char bonus_size[32];
1835	char aux[50];
1836	int error;
1837
1838	if (*print_header) {
1839		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1840		    "Object", "lvl", "iblk", "dblk", "dsize", "lsize",
1841		    "%full", "type");
1842		*print_header = 0;
1843	}
1844
1845	if (object == 0) {
1846		dn = DMU_META_DNODE(os);
1847	} else {
1848		error = dmu_bonus_hold(os, object, FTAG, &db);
1849		if (error)
1850			fatal("dmu_bonus_hold(%llu) failed, errno %u",
1851			    object, error);
1852		bonus = db->db_data;
1853		bsize = db->db_size;
1854		dn = DB_DNODE((dmu_buf_impl_t *)db);
1855	}
1856	dmu_object_info_from_dnode(dn, &doi);
1857
1858	zdb_nicenum(doi.doi_metadata_block_size, iblk);
1859	zdb_nicenum(doi.doi_data_block_size, dblk);
1860	zdb_nicenum(doi.doi_max_offset, lsize);
1861	zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize);
1862	zdb_nicenum(doi.doi_bonus_size, bonus_size);
1863	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
1864	    doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
1865	    doi.doi_max_offset);
1866
1867	aux[0] = '\0';
1868
1869	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1870		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1871		    ZDB_CHECKSUM_NAME(doi.doi_checksum));
1872	}
1873
1874	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1875		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1876		    ZDB_COMPRESS_NAME(doi.doi_compress));
1877	}
1878
1879	(void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %6s  %s%s\n",
1880	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
1881	    asize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
1882
1883	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1884		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1885		    "", "", "", "", "", bonus_size, "bonus",
1886		    ZDB_OT_NAME(doi.doi_bonus_type));
1887	}
1888
1889	if (verbosity >= 4) {
1890		(void) printf("\tdnode flags: %s%s%s\n",
1891		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
1892		    "USED_BYTES " : "",
1893		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
1894		    "USERUSED_ACCOUNTED " : "",
1895		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
1896		    "SPILL_BLKPTR" : "");
1897		(void) printf("\tdnode maxblkid: %llu\n",
1898		    (longlong_t)dn->dn_phys->dn_maxblkid);
1899
1900		object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os, object,
1901		    bonus, bsize);
1902		object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object, NULL, 0);
1903		*print_header = 1;
1904	}
1905
1906	if (verbosity >= 5)
1907		dump_indirect(dn);
1908
1909	if (verbosity >= 5) {
1910		/*
1911		 * Report the list of segments that comprise the object.
1912		 */
1913		uint64_t start = 0;
1914		uint64_t end;
1915		uint64_t blkfill = 1;
1916		int minlvl = 1;
1917
1918		if (dn->dn_type == DMU_OT_DNODE) {
1919			minlvl = 0;
1920			blkfill = DNODES_PER_BLOCK;
1921		}
1922
1923		for (;;) {
1924			char segsize[32];
1925			error = dnode_next_offset(dn,
1926			    0, &start, minlvl, blkfill, 0);
1927			if (error)
1928				break;
1929			end = start;
1930			error = dnode_next_offset(dn,
1931			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
1932			zdb_nicenum(end - start, segsize);
1933			(void) printf("\t\tsegment [%016llx, %016llx)"
1934			    " size %5s\n", (u_longlong_t)start,
1935			    (u_longlong_t)end, segsize);
1936			if (error)
1937				break;
1938			start = end;
1939		}
1940	}
1941
1942	if (db != NULL)
1943		dmu_buf_rele(db, FTAG);
1944}
1945
1946static char *objset_types[DMU_OST_NUMTYPES] = {
1947	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1948
1949static void
1950dump_dir(objset_t *os)
1951{
1952	dmu_objset_stats_t dds;
1953	uint64_t object, object_count;
1954	uint64_t refdbytes, usedobjs, scratch;
1955	char numbuf[32];
1956	char blkbuf[BP_SPRINTF_LEN + 20];
1957	char osname[ZFS_MAX_DATASET_NAME_LEN];
1958	char *type = "UNKNOWN";
1959	int verbosity = dump_opt['d'];
1960	int print_header = 1;
1961	int i, error;
1962
1963	dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
1964	dmu_objset_fast_stat(os, &dds);
1965	dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
1966
1967	if (dds.dds_type < DMU_OST_NUMTYPES)
1968		type = objset_types[dds.dds_type];
1969
1970	if (dds.dds_type == DMU_OST_META) {
1971		dds.dds_creation_txg = TXG_INITIAL;
1972		usedobjs = BP_GET_FILL(os->os_rootbp);
1973		refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
1974		    dd_used_bytes;
1975	} else {
1976		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
1977	}
1978
1979	ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
1980
1981	zdb_nicenum(refdbytes, numbuf);
1982
1983	if (verbosity >= 4) {
1984		(void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
1985		(void) snprintf_blkptr(blkbuf + strlen(blkbuf),
1986		    sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
1987	} else {
1988		blkbuf[0] = '\0';
1989	}
1990
1991	dmu_objset_name(os, osname);
1992
1993	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
1994	    "%s, %llu objects%s\n",
1995	    osname, type, (u_longlong_t)dmu_objset_id(os),
1996	    (u_longlong_t)dds.dds_creation_txg,
1997	    numbuf, (u_longlong_t)usedobjs, blkbuf);
1998
1999	if (zopt_objects != 0) {
2000		for (i = 0; i < zopt_objects; i++)
2001			dump_object(os, zopt_object[i], verbosity,
2002			    &print_header);
2003		(void) printf("\n");
2004		return;
2005	}
2006
2007	if (dump_opt['i'] != 0 || verbosity >= 2)
2008		dump_intent_log(dmu_objset_zil(os));
2009
2010	if (dmu_objset_ds(os) != NULL)
2011		dump_deadlist(&dmu_objset_ds(os)->ds_deadlist);
2012
2013	if (verbosity < 2)
2014		return;
2015
2016	if (BP_IS_HOLE(os->os_rootbp))
2017		return;
2018
2019	dump_object(os, 0, verbosity, &print_header);
2020	object_count = 0;
2021	if (DMU_USERUSED_DNODE(os) != NULL &&
2022	    DMU_USERUSED_DNODE(os)->dn_type != 0) {
2023		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header);
2024		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header);
2025	}
2026
2027	object = 0;
2028	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
2029		dump_object(os, object, verbosity, &print_header);
2030		object_count++;
2031	}
2032
2033	ASSERT3U(object_count, ==, usedobjs);
2034
2035	(void) printf("\n");
2036
2037	if (error != ESRCH) {
2038		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
2039		abort();
2040	}
2041}
2042
2043static void
2044dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
2045{
2046	time_t timestamp = ub->ub_timestamp;
2047
2048	(void) printf(header ? header : "");
2049	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
2050	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
2051	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
2052	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
2053	(void) printf("\ttimestamp = %llu UTC = %s",
2054	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
2055	if (dump_opt['u'] >= 3) {
2056		char blkbuf[BP_SPRINTF_LEN];
2057		snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
2058		(void) printf("\trootbp = %s\n", blkbuf);
2059	}
2060	(void) printf(footer ? footer : "");
2061}
2062
2063static void
2064dump_config(spa_t *spa)
2065{
2066	dmu_buf_t *db;
2067	size_t nvsize = 0;
2068	int error = 0;
2069
2070
2071	error = dmu_bonus_hold(spa->spa_meta_objset,
2072	    spa->spa_config_object, FTAG, &db);
2073
2074	if (error == 0) {
2075		nvsize = *(uint64_t *)db->db_data;
2076		dmu_buf_rele(db, FTAG);
2077
2078		(void) printf("\nMOS Configuration:\n");
2079		dump_packed_nvlist(spa->spa_meta_objset,
2080		    spa->spa_config_object, (void *)&nvsize, 1);
2081	} else {
2082		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
2083		    (u_longlong_t)spa->spa_config_object, error);
2084	}
2085}
2086
2087static void
2088dump_cachefile(const char *cachefile)
2089{
2090	int fd;
2091	struct stat64 statbuf;
2092	char *buf;
2093	nvlist_t *config;
2094
2095	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
2096		(void) printf("cannot open '%s': %s\n", cachefile,
2097		    strerror(errno));
2098		exit(1);
2099	}
2100
2101	if (fstat64(fd, &statbuf) != 0) {
2102		(void) printf("failed to stat '%s': %s\n", cachefile,
2103		    strerror(errno));
2104		exit(1);
2105	}
2106
2107	if ((buf = malloc(statbuf.st_size)) == NULL) {
2108		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
2109		    (u_longlong_t)statbuf.st_size);
2110		exit(1);
2111	}
2112
2113	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
2114		(void) fprintf(stderr, "failed to read %llu bytes\n",
2115		    (u_longlong_t)statbuf.st_size);
2116		exit(1);
2117	}
2118
2119	(void) close(fd);
2120
2121	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
2122		(void) fprintf(stderr, "failed to unpack nvlist\n");
2123		exit(1);
2124	}
2125
2126	free(buf);
2127
2128	dump_nvlist(config, 0);
2129
2130	nvlist_free(config);
2131}
2132
2133#define	ZDB_MAX_UB_HEADER_SIZE 32
2134
2135static void
2136dump_label_uberblocks(vdev_label_t *lbl, uint64_t ashift)
2137{
2138	vdev_t vd;
2139	vdev_t *vdp = &vd;
2140	char header[ZDB_MAX_UB_HEADER_SIZE];
2141
2142	vd.vdev_ashift = ashift;
2143	vdp->vdev_top = vdp;
2144
2145	for (int i = 0; i < VDEV_UBERBLOCK_COUNT(vdp); i++) {
2146		uint64_t uoff = VDEV_UBERBLOCK_OFFSET(vdp, i);
2147		uberblock_t *ub = (void *)((char *)lbl + uoff);
2148
2149		if (uberblock_verify(ub))
2150			continue;
2151		(void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
2152		    "Uberblock[%d]\n", i);
2153		dump_uberblock(ub, header, "");
2154	}
2155}
2156
2157static void
2158dump_label(const char *dev)
2159{
2160	int fd;
2161	vdev_label_t label;
2162	char *path, *buf = label.vl_vdev_phys.vp_nvlist;
2163	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
2164	struct stat64 statbuf;
2165	uint64_t psize, ashift;
2166	int len = strlen(dev) + 1;
2167
2168	if (strncmp(dev, ZFS_DISK_ROOTD, strlen(ZFS_DISK_ROOTD)) == 0) {
2169		len++;
2170		path = malloc(len);
2171		(void) snprintf(path, len, "%s%s", ZFS_RDISK_ROOTD,
2172		    dev + strlen(ZFS_DISK_ROOTD));
2173	} else {
2174		path = strdup(dev);
2175	}
2176
2177	if ((fd = open64(path, O_RDONLY)) < 0) {
2178		(void) printf("cannot open '%s': %s\n", path, strerror(errno));
2179		free(path);
2180		exit(1);
2181	}
2182
2183	if (fstat64(fd, &statbuf) != 0) {
2184		(void) printf("failed to stat '%s': %s\n", path,
2185		    strerror(errno));
2186		free(path);
2187		(void) close(fd);
2188		exit(1);
2189	}
2190
2191	if (S_ISBLK(statbuf.st_mode)) {
2192		(void) printf("cannot use '%s': character device required\n",
2193		    path);
2194		free(path);
2195		(void) close(fd);
2196		exit(1);
2197	}
2198
2199	psize = statbuf.st_size;
2200	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
2201
2202	for (int l = 0; l < VDEV_LABELS; l++) {
2203		nvlist_t *config = NULL;
2204
2205		(void) printf("--------------------------------------------\n");
2206		(void) printf("LABEL %d\n", l);
2207		(void) printf("--------------------------------------------\n");
2208
2209		if (pread64(fd, &label, sizeof (label),
2210		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
2211			(void) printf("failed to read label %d\n", l);
2212			continue;
2213		}
2214
2215		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
2216			(void) printf("failed to unpack label %d\n", l);
2217			ashift = SPA_MINBLOCKSHIFT;
2218		} else {
2219			nvlist_t *vdev_tree = NULL;
2220
2221			dump_nvlist(config, 4);
2222			if ((nvlist_lookup_nvlist(config,
2223			    ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
2224			    (nvlist_lookup_uint64(vdev_tree,
2225			    ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
2226				ashift = SPA_MINBLOCKSHIFT;
2227			nvlist_free(config);
2228		}
2229		if (dump_opt['u'])
2230			dump_label_uberblocks(&label, ashift);
2231	}
2232
2233	free(path);
2234	(void) close(fd);
2235}
2236
2237static uint64_t dataset_feature_count[SPA_FEATURES];
2238
2239/*ARGSUSED*/
2240static int
2241dump_one_dir(const char *dsname, void *arg)
2242{
2243	int error;
2244	objset_t *os;
2245
2246	error = dmu_objset_own(dsname, DMU_OST_ANY, B_TRUE, FTAG, &os);
2247	if (error) {
2248		(void) printf("Could not open %s, error %d\n", dsname, error);
2249		return (0);
2250	}
2251
2252	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
2253		if (!dmu_objset_ds(os)->ds_feature_inuse[f])
2254			continue;
2255		ASSERT(spa_feature_table[f].fi_flags &
2256		    ZFEATURE_FLAG_PER_DATASET);
2257		dataset_feature_count[f]++;
2258	}
2259
2260	dump_dir(os);
2261	dmu_objset_disown(os, FTAG);
2262	fuid_table_destroy();
2263	sa_loaded = B_FALSE;
2264	return (0);
2265}
2266
2267/*
2268 * Block statistics.
2269 */
2270#define	PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
2271typedef struct zdb_blkstats {
2272	uint64_t zb_asize;
2273	uint64_t zb_lsize;
2274	uint64_t zb_psize;
2275	uint64_t zb_count;
2276	uint64_t zb_gangs;
2277	uint64_t zb_ditto_samevdev;
2278	uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
2279} zdb_blkstats_t;
2280
2281/*
2282 * Extended object types to report deferred frees and dedup auto-ditto blocks.
2283 */
2284#define	ZDB_OT_DEFERRED	(DMU_OT_NUMTYPES + 0)
2285#define	ZDB_OT_DITTO	(DMU_OT_NUMTYPES + 1)
2286#define	ZDB_OT_OTHER	(DMU_OT_NUMTYPES + 2)
2287#define	ZDB_OT_TOTAL	(DMU_OT_NUMTYPES + 3)
2288
2289static char *zdb_ot_extname[] = {
2290	"deferred free",
2291	"dedup ditto",
2292	"other",
2293	"Total",
2294};
2295
2296#define	ZB_TOTAL	DN_MAX_LEVELS
2297
2298typedef struct zdb_cb {
2299	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
2300	uint64_t	zcb_dedup_asize;
2301	uint64_t	zcb_dedup_blocks;
2302	uint64_t	zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
2303	uint64_t	zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
2304	    [BPE_PAYLOAD_SIZE];
2305	uint64_t	zcb_start;
2306	uint64_t	zcb_lastprint;
2307	uint64_t	zcb_totalasize;
2308	uint64_t	zcb_errors[256];
2309	int		zcb_readfails;
2310	int		zcb_haderrors;
2311	spa_t		*zcb_spa;
2312} zdb_cb_t;
2313
2314static void
2315zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
2316    dmu_object_type_t type)
2317{
2318	uint64_t refcnt = 0;
2319
2320	ASSERT(type < ZDB_OT_TOTAL);
2321
2322	if (zilog && zil_bp_tree_add(zilog, bp) != 0)
2323		return;
2324
2325	for (int i = 0; i < 4; i++) {
2326		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
2327		int t = (i & 1) ? type : ZDB_OT_TOTAL;
2328		int equal;
2329		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
2330
2331		zb->zb_asize += BP_GET_ASIZE(bp);
2332		zb->zb_lsize += BP_GET_LSIZE(bp);
2333		zb->zb_psize += BP_GET_PSIZE(bp);
2334		zb->zb_count++;
2335
2336		/*
2337		 * The histogram is only big enough to record blocks up to
2338		 * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
2339		 * "other", bucket.
2340		 */
2341		int idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
2342		idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
2343		zb->zb_psize_histogram[idx]++;
2344
2345		zb->zb_gangs += BP_COUNT_GANG(bp);
2346
2347		switch (BP_GET_NDVAS(bp)) {
2348		case 2:
2349			if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2350			    DVA_GET_VDEV(&bp->blk_dva[1]))
2351				zb->zb_ditto_samevdev++;
2352			break;
2353		case 3:
2354			equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2355			    DVA_GET_VDEV(&bp->blk_dva[1])) +
2356			    (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2357			    DVA_GET_VDEV(&bp->blk_dva[2])) +
2358			    (DVA_GET_VDEV(&bp->blk_dva[1]) ==
2359			    DVA_GET_VDEV(&bp->blk_dva[2]));
2360			if (equal != 0)
2361				zb->zb_ditto_samevdev++;
2362			break;
2363		}
2364
2365	}
2366
2367	if (BP_IS_EMBEDDED(bp)) {
2368		zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
2369		zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
2370		    [BPE_GET_PSIZE(bp)]++;
2371		return;
2372	}
2373
2374	if (dump_opt['L'])
2375		return;
2376
2377	if (BP_GET_DEDUP(bp)) {
2378		ddt_t *ddt;
2379		ddt_entry_t *dde;
2380
2381		ddt = ddt_select(zcb->zcb_spa, bp);
2382		ddt_enter(ddt);
2383		dde = ddt_lookup(ddt, bp, B_FALSE);
2384
2385		if (dde == NULL) {
2386			refcnt = 0;
2387		} else {
2388			ddt_phys_t *ddp = ddt_phys_select(dde, bp);
2389			ddt_phys_decref(ddp);
2390			refcnt = ddp->ddp_refcnt;
2391			if (ddt_phys_total_refcnt(dde) == 0)
2392				ddt_remove(ddt, dde);
2393		}
2394		ddt_exit(ddt);
2395	}
2396
2397	VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
2398	    refcnt ? 0 : spa_first_txg(zcb->zcb_spa),
2399	    bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
2400}
2401
2402/* ARGSUSED */
2403static void
2404zdb_blkptr_done(zio_t *zio)
2405{
2406	spa_t *spa = zio->io_spa;
2407	blkptr_t *bp = zio->io_bp;
2408	int ioerr = zio->io_error;
2409	zdb_cb_t *zcb = zio->io_private;
2410	zbookmark_phys_t *zb = &zio->io_bookmark;
2411
2412	zio_data_buf_free(zio->io_data, zio->io_size);
2413
2414	mutex_enter(&spa->spa_scrub_lock);
2415	spa->spa_scrub_inflight--;
2416	cv_broadcast(&spa->spa_scrub_io_cv);
2417
2418	if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
2419		char blkbuf[BP_SPRINTF_LEN];
2420
2421		zcb->zcb_haderrors = 1;
2422		zcb->zcb_errors[ioerr]++;
2423
2424		if (dump_opt['b'] >= 2)
2425			snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2426		else
2427			blkbuf[0] = '\0';
2428
2429		(void) printf("zdb_blkptr_cb: "
2430		    "Got error %d reading "
2431		    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
2432		    ioerr,
2433		    (u_longlong_t)zb->zb_objset,
2434		    (u_longlong_t)zb->zb_object,
2435		    (u_longlong_t)zb->zb_level,
2436		    (u_longlong_t)zb->zb_blkid,
2437		    blkbuf);
2438	}
2439	mutex_exit(&spa->spa_scrub_lock);
2440}
2441
2442/* ARGSUSED */
2443static int
2444zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2445    const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2446{
2447	zdb_cb_t *zcb = arg;
2448	dmu_object_type_t type;
2449	boolean_t is_metadata;
2450
2451	if (bp == NULL)
2452		return (0);
2453
2454	if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
2455		char blkbuf[BP_SPRINTF_LEN];
2456		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2457		(void) printf("objset %llu object %llu "
2458		    "level %lld offset 0x%llx %s\n",
2459		    (u_longlong_t)zb->zb_objset,
2460		    (u_longlong_t)zb->zb_object,
2461		    (longlong_t)zb->zb_level,
2462		    (u_longlong_t)blkid2offset(dnp, bp, zb),
2463		    blkbuf);
2464	}
2465
2466	if (BP_IS_HOLE(bp))
2467		return (0);
2468
2469	type = BP_GET_TYPE(bp);
2470
2471	zdb_count_block(zcb, zilog, bp,
2472	    (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
2473
2474	is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
2475
2476	if (!BP_IS_EMBEDDED(bp) &&
2477	    (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
2478		size_t size = BP_GET_PSIZE(bp);
2479		void *data = zio_data_buf_alloc(size);
2480		int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
2481
2482		/* If it's an intent log block, failure is expected. */
2483		if (zb->zb_level == ZB_ZIL_LEVEL)
2484			flags |= ZIO_FLAG_SPECULATIVE;
2485
2486		mutex_enter(&spa->spa_scrub_lock);
2487		while (spa->spa_scrub_inflight > max_inflight)
2488			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2489		spa->spa_scrub_inflight++;
2490		mutex_exit(&spa->spa_scrub_lock);
2491
2492		zio_nowait(zio_read(NULL, spa, bp, data, size,
2493		    zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
2494	}
2495
2496	zcb->zcb_readfails = 0;
2497
2498	/* only call gethrtime() every 100 blocks */
2499	static int iters;
2500	if (++iters > 100)
2501		iters = 0;
2502	else
2503		return (0);
2504
2505	if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
2506		uint64_t now = gethrtime();
2507		char buf[10];
2508		uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
2509		int kb_per_sec =
2510		    1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
2511		int sec_remaining =
2512		    (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
2513
2514		zfs_nicenum(bytes, buf, sizeof (buf));
2515		(void) fprintf(stderr,
2516		    "\r%5s completed (%4dMB/s) "
2517		    "estimated time remaining: %uhr %02umin %02usec        ",
2518		    buf, kb_per_sec / 1024,
2519		    sec_remaining / 60 / 60,
2520		    sec_remaining / 60 % 60,
2521		    sec_remaining % 60);
2522
2523		zcb->zcb_lastprint = now;
2524	}
2525
2526	return (0);
2527}
2528
2529static void
2530zdb_leak(void *arg, uint64_t start, uint64_t size)
2531{
2532	vdev_t *vd = arg;
2533
2534	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
2535	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
2536}
2537
2538static metaslab_ops_t zdb_metaslab_ops = {
2539	NULL	/* alloc */
2540};
2541
2542static void
2543zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
2544{
2545	ddt_bookmark_t ddb = { 0 };
2546	ddt_entry_t dde;
2547	int error;
2548
2549	while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
2550		blkptr_t blk;
2551		ddt_phys_t *ddp = dde.dde_phys;
2552
2553		if (ddb.ddb_class == DDT_CLASS_UNIQUE)
2554			return;
2555
2556		ASSERT(ddt_phys_total_refcnt(&dde) > 1);
2557
2558		for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2559			if (ddp->ddp_phys_birth == 0)
2560				continue;
2561			ddt_bp_create(ddb.ddb_checksum,
2562			    &dde.dde_key, ddp, &blk);
2563			if (p == DDT_PHYS_DITTO) {
2564				zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
2565			} else {
2566				zcb->zcb_dedup_asize +=
2567				    BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
2568				zcb->zcb_dedup_blocks++;
2569			}
2570		}
2571		if (!dump_opt['L']) {
2572			ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
2573			ddt_enter(ddt);
2574			VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
2575			ddt_exit(ddt);
2576		}
2577	}
2578
2579	ASSERT(error == ENOENT);
2580}
2581
2582static void
2583zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
2584{
2585	zcb->zcb_spa = spa;
2586
2587	if (!dump_opt['L']) {
2588		vdev_t *rvd = spa->spa_root_vdev;
2589		for (uint64_t c = 0; c < rvd->vdev_children; c++) {
2590			vdev_t *vd = rvd->vdev_child[c];
2591			for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
2592				metaslab_t *msp = vd->vdev_ms[m];
2593				mutex_enter(&msp->ms_lock);
2594				metaslab_unload(msp);
2595
2596				/*
2597				 * For leak detection, we overload the metaslab
2598				 * ms_tree to contain allocated segments
2599				 * instead of free segments. As a result,
2600				 * we can't use the normal metaslab_load/unload
2601				 * interfaces.
2602				 */
2603				if (msp->ms_sm != NULL) {
2604					(void) fprintf(stderr,
2605					    "\rloading space map for "
2606					    "vdev %llu of %llu, "
2607					    "metaslab %llu of %llu ...",
2608					    (longlong_t)c,
2609					    (longlong_t)rvd->vdev_children,
2610					    (longlong_t)m,
2611					    (longlong_t)vd->vdev_ms_count);
2612
2613					msp->ms_ops = &zdb_metaslab_ops;
2614
2615					/*
2616					 * We don't want to spend the CPU
2617					 * manipulating the size-ordered
2618					 * tree, so clear the range_tree
2619					 * ops.
2620					 */
2621					msp->ms_tree->rt_ops = NULL;
2622					VERIFY0(space_map_load(msp->ms_sm,
2623					    msp->ms_tree, SM_ALLOC));
2624					msp->ms_loaded = B_TRUE;
2625				}
2626				mutex_exit(&msp->ms_lock);
2627			}
2628		}
2629		(void) fprintf(stderr, "\n");
2630	}
2631
2632	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2633
2634	zdb_ddt_leak_init(spa, zcb);
2635
2636	spa_config_exit(spa, SCL_CONFIG, FTAG);
2637}
2638
2639static void
2640zdb_leak_fini(spa_t *spa)
2641{
2642	if (!dump_opt['L']) {
2643		vdev_t *rvd = spa->spa_root_vdev;
2644		for (int c = 0; c < rvd->vdev_children; c++) {
2645			vdev_t *vd = rvd->vdev_child[c];
2646			for (int m = 0; m < vd->vdev_ms_count; m++) {
2647				metaslab_t *msp = vd->vdev_ms[m];
2648				mutex_enter(&msp->ms_lock);
2649
2650				/*
2651				 * The ms_tree has been overloaded to
2652				 * contain allocated segments. Now that we
2653				 * finished traversing all blocks, any
2654				 * block that remains in the ms_tree
2655				 * represents an allocated block that we
2656				 * did not claim during the traversal.
2657				 * Claimed blocks would have been removed
2658				 * from the ms_tree.
2659				 */
2660				range_tree_vacate(msp->ms_tree, zdb_leak, vd);
2661				msp->ms_loaded = B_FALSE;
2662
2663				mutex_exit(&msp->ms_lock);
2664			}
2665		}
2666	}
2667}
2668
2669/* ARGSUSED */
2670static int
2671count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2672{
2673	zdb_cb_t *zcb = arg;
2674
2675	if (dump_opt['b'] >= 5) {
2676		char blkbuf[BP_SPRINTF_LEN];
2677		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2678		(void) printf("[%s] %s\n",
2679		    "deferred free", blkbuf);
2680	}
2681	zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
2682	return (0);
2683}
2684
2685static int
2686dump_block_stats(spa_t *spa)
2687{
2688	zdb_cb_t zcb = { 0 };
2689	zdb_blkstats_t *zb, *tzb;
2690	uint64_t norm_alloc, norm_space, total_alloc, total_found;
2691	int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA | TRAVERSE_HARD;
2692	boolean_t leaks = B_FALSE;
2693
2694	(void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
2695	    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
2696	    (dump_opt['c'] == 1) ? "metadata " : "",
2697	    dump_opt['c'] ? "checksums " : "",
2698	    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
2699	    !dump_opt['L'] ? "nothing leaked " : "");
2700
2701	/*
2702	 * Load all space maps as SM_ALLOC maps, then traverse the pool
2703	 * claiming each block we discover.  If the pool is perfectly
2704	 * consistent, the space maps will be empty when we're done.
2705	 * Anything left over is a leak; any block we can't claim (because
2706	 * it's not part of any space map) is a double allocation,
2707	 * reference to a freed block, or an unclaimed log block.
2708	 */
2709	zdb_leak_init(spa, &zcb);
2710
2711	/*
2712	 * If there's a deferred-free bplist, process that first.
2713	 */
2714	(void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
2715	    count_block_cb, &zcb, NULL);
2716	if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
2717		(void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
2718		    count_block_cb, &zcb, NULL);
2719	}
2720	if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
2721		VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
2722		    spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
2723		    &zcb, NULL));
2724	}
2725
2726	if (dump_opt['c'] > 1)
2727		flags |= TRAVERSE_PREFETCH_DATA;
2728
2729	zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
2730	zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
2731	zcb.zcb_haderrors |= traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
2732
2733	/*
2734	 * If we've traversed the data blocks then we need to wait for those
2735	 * I/Os to complete. We leverage "The Godfather" zio to wait on
2736	 * all async I/Os to complete.
2737	 */
2738	if (dump_opt['c']) {
2739		for (int i = 0; i < max_ncpus; i++) {
2740			(void) zio_wait(spa->spa_async_zio_root[i]);
2741			spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2742			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2743			    ZIO_FLAG_GODFATHER);
2744		}
2745	}
2746
2747	if (zcb.zcb_haderrors) {
2748		(void) printf("\nError counts:\n\n");
2749		(void) printf("\t%5s  %s\n", "errno", "count");
2750		for (int e = 0; e < 256; e++) {
2751			if (zcb.zcb_errors[e] != 0) {
2752				(void) printf("\t%5d  %llu\n",
2753				    e, (u_longlong_t)zcb.zcb_errors[e]);
2754			}
2755		}
2756	}
2757
2758	/*
2759	 * Report any leaked segments.
2760	 */
2761	zdb_leak_fini(spa);
2762
2763	tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
2764
2765	norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
2766	norm_space = metaslab_class_get_space(spa_normal_class(spa));
2767
2768	total_alloc = norm_alloc + metaslab_class_get_alloc(spa_log_class(spa));
2769	total_found = tzb->zb_asize - zcb.zcb_dedup_asize;
2770
2771	if (total_found == total_alloc) {
2772		if (!dump_opt['L'])
2773			(void) printf("\n\tNo leaks (block sum matches space"
2774			    " maps exactly)\n");
2775	} else {
2776		(void) printf("block traversal size %llu != alloc %llu "
2777		    "(%s %lld)\n",
2778		    (u_longlong_t)total_found,
2779		    (u_longlong_t)total_alloc,
2780		    (dump_opt['L']) ? "unreachable" : "leaked",
2781		    (longlong_t)(total_alloc - total_found));
2782		leaks = B_TRUE;
2783	}
2784
2785	if (tzb->zb_count == 0)
2786		return (2);
2787
2788	(void) printf("\n");
2789	(void) printf("\tbp count:      %10llu\n",
2790	    (u_longlong_t)tzb->zb_count);
2791	(void) printf("\tganged count:  %10llu\n",
2792	    (longlong_t)tzb->zb_gangs);
2793	(void) printf("\tbp logical:    %10llu      avg: %6llu\n",
2794	    (u_longlong_t)tzb->zb_lsize,
2795	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
2796	(void) printf("\tbp physical:   %10llu      avg:"
2797	    " %6llu     compression: %6.2f\n",
2798	    (u_longlong_t)tzb->zb_psize,
2799	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
2800	    (double)tzb->zb_lsize / tzb->zb_psize);
2801	(void) printf("\tbp allocated:  %10llu      avg:"
2802	    " %6llu     compression: %6.2f\n",
2803	    (u_longlong_t)tzb->zb_asize,
2804	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
2805	    (double)tzb->zb_lsize / tzb->zb_asize);
2806	(void) printf("\tbp deduped:    %10llu    ref>1:"
2807	    " %6llu   deduplication: %6.2f\n",
2808	    (u_longlong_t)zcb.zcb_dedup_asize,
2809	    (u_longlong_t)zcb.zcb_dedup_blocks,
2810	    (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
2811	(void) printf("\tSPA allocated: %10llu     used: %5.2f%%\n",
2812	    (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
2813
2814	for (bp_embedded_type_t i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
2815		if (zcb.zcb_embedded_blocks[i] == 0)
2816			continue;
2817		(void) printf("\n");
2818		(void) printf("\tadditional, non-pointer bps of type %u: "
2819		    "%10llu\n",
2820		    i, (u_longlong_t)zcb.zcb_embedded_blocks[i]);
2821
2822		if (dump_opt['b'] >= 3) {
2823			(void) printf("\t number of (compressed) bytes:  "
2824			    "number of bps\n");
2825			dump_histogram(zcb.zcb_embedded_histogram[i],
2826			    sizeof (zcb.zcb_embedded_histogram[i]) /
2827			    sizeof (zcb.zcb_embedded_histogram[i][0]), 0);
2828		}
2829	}
2830
2831	if (tzb->zb_ditto_samevdev != 0) {
2832		(void) printf("\tDittoed blocks on same vdev: %llu\n",
2833		    (longlong_t)tzb->zb_ditto_samevdev);
2834	}
2835
2836	if (dump_opt['b'] >= 2) {
2837		int l, t, level;
2838		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
2839		    "\t  avg\t comp\t%%Total\tType\n");
2840
2841		for (t = 0; t <= ZDB_OT_TOTAL; t++) {
2842			char csize[32], lsize[32], psize[32], asize[32];
2843			char avg[32], gang[32];
2844			char *typename;
2845
2846			if (t < DMU_OT_NUMTYPES)
2847				typename = dmu_ot[t].ot_name;
2848			else
2849				typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
2850
2851			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
2852				(void) printf("%6s\t%5s\t%5s\t%5s"
2853				    "\t%5s\t%5s\t%6s\t%s\n",
2854				    "-",
2855				    "-",
2856				    "-",
2857				    "-",
2858				    "-",
2859				    "-",
2860				    "-",
2861				    typename);
2862				continue;
2863			}
2864
2865			for (l = ZB_TOTAL - 1; l >= -1; l--) {
2866				level = (l == -1 ? ZB_TOTAL : l);
2867				zb = &zcb.zcb_type[level][t];
2868
2869				if (zb->zb_asize == 0)
2870					continue;
2871
2872				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
2873					continue;
2874
2875				if (level == 0 && zb->zb_asize ==
2876				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
2877					continue;
2878
2879				zdb_nicenum(zb->zb_count, csize);
2880				zdb_nicenum(zb->zb_lsize, lsize);
2881				zdb_nicenum(zb->zb_psize, psize);
2882				zdb_nicenum(zb->zb_asize, asize);
2883				zdb_nicenum(zb->zb_asize / zb->zb_count, avg);
2884				zdb_nicenum(zb->zb_gangs, gang);
2885
2886				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
2887				    "\t%5.2f\t%6.2f\t",
2888				    csize, lsize, psize, asize, avg,
2889				    (double)zb->zb_lsize / zb->zb_psize,
2890				    100.0 * zb->zb_asize / tzb->zb_asize);
2891
2892				if (level == ZB_TOTAL)
2893					(void) printf("%s\n", typename);
2894				else
2895					(void) printf("    L%d %s\n",
2896					    level, typename);
2897
2898				if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
2899					(void) printf("\t number of ganged "
2900					    "blocks: %s\n", gang);
2901				}
2902
2903				if (dump_opt['b'] >= 4) {
2904					(void) printf("psize "
2905					    "(in 512-byte sectors): "
2906					    "number of blocks\n");
2907					dump_histogram(zb->zb_psize_histogram,
2908					    PSIZE_HISTO_SIZE, 0);
2909				}
2910			}
2911		}
2912	}
2913
2914	(void) printf("\n");
2915
2916	if (leaks)
2917		return (2);
2918
2919	if (zcb.zcb_haderrors)
2920		return (3);
2921
2922	return (0);
2923}
2924
2925typedef struct zdb_ddt_entry {
2926	ddt_key_t	zdde_key;
2927	uint64_t	zdde_ref_blocks;
2928	uint64_t	zdde_ref_lsize;
2929	uint64_t	zdde_ref_psize;
2930	uint64_t	zdde_ref_dsize;
2931	avl_node_t	zdde_node;
2932} zdb_ddt_entry_t;
2933
2934/* ARGSUSED */
2935static int
2936zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2937    const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2938{
2939	avl_tree_t *t = arg;
2940	avl_index_t where;
2941	zdb_ddt_entry_t *zdde, zdde_search;
2942
2943	if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2944		return (0);
2945
2946	if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
2947		(void) printf("traversing objset %llu, %llu objects, "
2948		    "%lu blocks so far\n",
2949		    (u_longlong_t)zb->zb_objset,
2950		    (u_longlong_t)BP_GET_FILL(bp),
2951		    avl_numnodes(t));
2952	}
2953
2954	if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
2955	    BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
2956		return (0);
2957
2958	ddt_key_fill(&zdde_search.zdde_key, bp);
2959
2960	zdde = avl_find(t, &zdde_search, &where);
2961
2962	if (zdde == NULL) {
2963		zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
2964		zdde->zdde_key = zdde_search.zdde_key;
2965		avl_insert(t, zdde, where);
2966	}
2967
2968	zdde->zdde_ref_blocks += 1;
2969	zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
2970	zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
2971	zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
2972
2973	return (0);
2974}
2975
2976static void
2977dump_simulated_ddt(spa_t *spa)
2978{
2979	avl_tree_t t;
2980	void *cookie = NULL;
2981	zdb_ddt_entry_t *zdde;
2982	ddt_histogram_t ddh_total = { 0 };
2983	ddt_stat_t dds_total = { 0 };
2984
2985	avl_create(&t, ddt_entry_compare,
2986	    sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
2987
2988	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2989
2990	(void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2991	    zdb_ddt_add_cb, &t);
2992
2993	spa_config_exit(spa, SCL_CONFIG, FTAG);
2994
2995	while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
2996		ddt_stat_t dds;
2997		uint64_t refcnt = zdde->zdde_ref_blocks;
2998		ASSERT(refcnt != 0);
2999
3000		dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
3001		dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
3002		dds.dds_psize = zdde->zdde_ref_psize / refcnt;
3003		dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
3004
3005		dds.dds_ref_blocks = zdde->zdde_ref_blocks;
3006		dds.dds_ref_lsize = zdde->zdde_ref_lsize;
3007		dds.dds_ref_psize = zdde->zdde_ref_psize;
3008		dds.dds_ref_dsize = zdde->zdde_ref_dsize;
3009
3010		ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
3011		    &dds, 0);
3012
3013		umem_free(zdde, sizeof (*zdde));
3014	}
3015
3016	avl_destroy(&t);
3017
3018	ddt_histogram_stat(&dds_total, &ddh_total);
3019
3020	(void) printf("Simulated DDT histogram:\n");
3021
3022	zpool_dump_ddt(&dds_total, &ddh_total);
3023
3024	dump_dedup_ratio(&dds_total);
3025}
3026
3027static void
3028dump_zpool(spa_t *spa)
3029{
3030	dsl_pool_t *dp = spa_get_dsl(spa);
3031	int rc = 0;
3032
3033	if (dump_opt['S']) {
3034		dump_simulated_ddt(spa);
3035		return;
3036	}
3037
3038	if (!dump_opt['e'] && dump_opt['C'] > 1) {
3039		(void) printf("\nCached configuration:\n");
3040		dump_nvlist(spa->spa_config, 8);
3041	}
3042
3043	if (dump_opt['C'])
3044		dump_config(spa);
3045
3046	if (dump_opt['u'])
3047		dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
3048
3049	if (dump_opt['D'])
3050		dump_all_ddts(spa);
3051
3052	if (dump_opt['d'] > 2 || dump_opt['m'])
3053		dump_metaslabs(spa);
3054	if (dump_opt['M'])
3055		dump_metaslab_groups(spa);
3056
3057	if (dump_opt['d'] || dump_opt['i']) {
3058		dump_dir(dp->dp_meta_objset);
3059		if (dump_opt['d'] >= 3) {
3060			dump_full_bpobj(&spa->spa_deferred_bpobj,
3061			    "Deferred frees", 0);
3062			if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
3063				dump_full_bpobj(
3064				    &spa->spa_dsl_pool->dp_free_bpobj,
3065				    "Pool snapshot frees", 0);
3066			}
3067
3068			if (spa_feature_is_active(spa,
3069			    SPA_FEATURE_ASYNC_DESTROY)) {
3070				dump_bptree(spa->spa_meta_objset,
3071				    spa->spa_dsl_pool->dp_bptree_obj,
3072				    "Pool dataset frees");
3073			}
3074			dump_dtl(spa->spa_root_vdev, 0);
3075		}
3076		(void) dmu_objset_find(spa_name(spa), dump_one_dir,
3077		    NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
3078
3079		for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
3080			uint64_t refcount;
3081
3082			if (!(spa_feature_table[f].fi_flags &
3083			    ZFEATURE_FLAG_PER_DATASET)) {
3084				ASSERT0(dataset_feature_count[f]);
3085				continue;
3086			}
3087			(void) feature_get_refcount(spa,
3088			    &spa_feature_table[f], &refcount);
3089			if (dataset_feature_count[f] != refcount) {
3090				(void) printf("%s feature refcount mismatch: "
3091				    "%lld datasets != %lld refcount\n",
3092				    spa_feature_table[f].fi_uname,
3093				    (longlong_t)dataset_feature_count[f],
3094				    (longlong_t)refcount);
3095				rc = 2;
3096			} else {
3097				(void) printf("Verified %s feature refcount "
3098				    "of %llu is correct\n",
3099				    spa_feature_table[f].fi_uname,
3100				    (longlong_t)refcount);
3101			}
3102		}
3103	}
3104	if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
3105		rc = dump_block_stats(spa);
3106
3107	if (rc == 0)
3108		rc = verify_spacemap_refcounts(spa);
3109
3110	if (dump_opt['s'])
3111		show_pool_stats(spa);
3112
3113	if (dump_opt['h'])
3114		dump_history(spa);
3115
3116	if (rc != 0) {
3117		dump_debug_buffer();
3118		exit(rc);
3119	}
3120}
3121
3122#define	ZDB_FLAG_CHECKSUM	0x0001
3123#define	ZDB_FLAG_DECOMPRESS	0x0002
3124#define	ZDB_FLAG_BSWAP		0x0004
3125#define	ZDB_FLAG_GBH		0x0008
3126#define	ZDB_FLAG_INDIRECT	0x0010
3127#define	ZDB_FLAG_PHYS		0x0020
3128#define	ZDB_FLAG_RAW		0x0040
3129#define	ZDB_FLAG_PRINT_BLKPTR	0x0080
3130
3131int flagbits[256];
3132
3133static void
3134zdb_print_blkptr(blkptr_t *bp, int flags)
3135{
3136	char blkbuf[BP_SPRINTF_LEN];
3137
3138	if (flags & ZDB_FLAG_BSWAP)
3139		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
3140
3141	snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3142	(void) printf("%s\n", blkbuf);
3143}
3144
3145static void
3146zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
3147{
3148	int i;
3149
3150	for (i = 0; i < nbps; i++)
3151		zdb_print_blkptr(&bp[i], flags);
3152}
3153
3154static void
3155zdb_dump_gbh(void *buf, int flags)
3156{
3157	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
3158}
3159
3160static void
3161zdb_dump_block_raw(void *buf, uint64_t size, int flags)
3162{
3163	if (flags & ZDB_FLAG_BSWAP)
3164		byteswap_uint64_array(buf, size);
3165	(void) write(1, buf, size);
3166}
3167
3168static void
3169zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
3170{
3171	uint64_t *d = (uint64_t *)buf;
3172	int nwords = size / sizeof (uint64_t);
3173	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
3174	int i, j;
3175	char *hdr, *c;
3176
3177
3178	if (do_bswap)
3179		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
3180	else
3181		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
3182
3183	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
3184
3185	for (i = 0; i < nwords; i += 2) {
3186		(void) printf("%06llx:  %016llx  %016llx  ",
3187		    (u_longlong_t)(i * sizeof (uint64_t)),
3188		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
3189		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
3190
3191		c = (char *)&d[i];
3192		for (j = 0; j < 2 * sizeof (uint64_t); j++)
3193			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
3194		(void) printf("\n");
3195	}
3196}
3197
3198/*
3199 * There are two acceptable formats:
3200 *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
3201 *	child[.child]*    - For example: 0.1.1
3202 *
3203 * The second form can be used to specify arbitrary vdevs anywhere
3204 * in the heirarchy.  For example, in a pool with a mirror of
3205 * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
3206 */
3207static vdev_t *
3208zdb_vdev_lookup(vdev_t *vdev, char *path)
3209{
3210	char *s, *p, *q;
3211	int i;
3212
3213	if (vdev == NULL)
3214		return (NULL);
3215
3216	/* First, assume the x.x.x.x format */
3217	i = (int)strtoul(path, &s, 10);
3218	if (s == path || (s && *s != '.' && *s != '\0'))
3219		goto name;
3220	if (i < 0 || i >= vdev->vdev_children)
3221		return (NULL);
3222
3223	vdev = vdev->vdev_child[i];
3224	if (*s == '\0')
3225		return (vdev);
3226	return (zdb_vdev_lookup(vdev, s+1));
3227
3228name:
3229	for (i = 0; i < vdev->vdev_children; i++) {
3230		vdev_t *vc = vdev->vdev_child[i];
3231
3232		if (vc->vdev_path == NULL) {
3233			vc = zdb_vdev_lookup(vc, path);
3234			if (vc == NULL)
3235				continue;
3236			else
3237				return (vc);
3238		}
3239
3240		p = strrchr(vc->vdev_path, '/');
3241		p = p ? p + 1 : vc->vdev_path;
3242		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
3243
3244		if (strcmp(vc->vdev_path, path) == 0)
3245			return (vc);
3246		if (strcmp(p, path) == 0)
3247			return (vc);
3248		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
3249			return (vc);
3250	}
3251
3252	return (NULL);
3253}
3254
3255/*
3256 * Read a block from a pool and print it out.  The syntax of the
3257 * block descriptor is:
3258 *
3259 *	pool:vdev_specifier:offset:size[:flags]
3260 *
3261 *	pool           - The name of the pool you wish to read from
3262 *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
3263 *	offset         - offset, in hex, in bytes
3264 *	size           - Amount of data to read, in hex, in bytes
3265 *	flags          - A string of characters specifying options
3266 *		 b: Decode a blkptr at given offset within block
3267 *		*c: Calculate and display checksums
3268 *		 d: Decompress data before dumping
3269 *		 e: Byteswap data before dumping
3270 *		 g: Display data as a gang block header
3271 *		 i: Display as an indirect block
3272 *		 p: Do I/O to physical offset
3273 *		 r: Dump raw data to stdout
3274 *
3275 *              * = not yet implemented
3276 */
3277static void
3278zdb_read_block(char *thing, spa_t *spa)
3279{
3280	blkptr_t blk, *bp = &blk;
3281	dva_t *dva = bp->blk_dva;
3282	int flags = 0;
3283	uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
3284	zio_t *zio;
3285	vdev_t *vd;
3286	void *pbuf, *lbuf, *buf;
3287	char *s, *p, *dup, *vdev, *flagstr;
3288	int i, error;
3289
3290	dup = strdup(thing);
3291	s = strtok(dup, ":");
3292	vdev = s ? s : "";
3293	s = strtok(NULL, ":");
3294	offset = strtoull(s ? s : "", NULL, 16);
3295	s = strtok(NULL, ":");
3296	size = strtoull(s ? s : "", NULL, 16);
3297	s = strtok(NULL, ":");
3298	flagstr = s ? s : "";
3299
3300	s = NULL;
3301	if (size == 0)
3302		s = "size must not be zero";
3303	if (!IS_P2ALIGNED(size, DEV_BSIZE))
3304		s = "size must be a multiple of sector size";
3305	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
3306		s = "offset must be a multiple of sector size";
3307	if (s) {
3308		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
3309		free(dup);
3310		return;
3311	}
3312
3313	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
3314		for (i = 0; flagstr[i]; i++) {
3315			int bit = flagbits[(uchar_t)flagstr[i]];
3316
3317			if (bit == 0) {
3318				(void) printf("***Invalid flag: %c\n",
3319				    flagstr[i]);
3320				continue;
3321			}
3322			flags |= bit;
3323
3324			/* If it's not something with an argument, keep going */
3325			if ((bit & (ZDB_FLAG_CHECKSUM |
3326			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
3327				continue;
3328
3329			p = &flagstr[i + 1];
3330			if (bit == ZDB_FLAG_PRINT_BLKPTR)
3331				blkptr_offset = strtoull(p, &p, 16);
3332			if (*p != ':' && *p != '\0') {
3333				(void) printf("***Invalid flag arg: '%s'\n", s);
3334				free(dup);
3335				return;
3336			}
3337			i += p - &flagstr[i + 1]; /* skip over the number */
3338		}
3339	}
3340
3341	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
3342	if (vd == NULL) {
3343		(void) printf("***Invalid vdev: %s\n", vdev);
3344		free(dup);
3345		return;
3346	} else {
3347		if (vd->vdev_path)
3348			(void) fprintf(stderr, "Found vdev: %s\n",
3349			    vd->vdev_path);
3350		else
3351			(void) fprintf(stderr, "Found vdev type: %s\n",
3352			    vd->vdev_ops->vdev_op_type);
3353	}
3354
3355	psize = size;
3356	lsize = size;
3357
3358	pbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3359	lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3360
3361	BP_ZERO(bp);
3362
3363	DVA_SET_VDEV(&dva[0], vd->vdev_id);
3364	DVA_SET_OFFSET(&dva[0], offset);
3365	DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
3366	DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
3367
3368	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
3369
3370	BP_SET_LSIZE(bp, lsize);
3371	BP_SET_PSIZE(bp, psize);
3372	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
3373	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
3374	BP_SET_TYPE(bp, DMU_OT_NONE);
3375	BP_SET_LEVEL(bp, 0);
3376	BP_SET_DEDUP(bp, 0);
3377	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
3378
3379	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
3380	zio = zio_root(spa, NULL, NULL, 0);
3381
3382	if (vd == vd->vdev_top) {
3383		/*
3384		 * Treat this as a normal block read.
3385		 */
3386		zio_nowait(zio_read(zio, spa, bp, pbuf, psize, NULL, NULL,
3387		    ZIO_PRIORITY_SYNC_READ,
3388		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
3389	} else {
3390		/*
3391		 * Treat this as a vdev child I/O.
3392		 */
3393		zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pbuf, psize,
3394		    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
3395		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
3396		    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
3397		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL, NULL));
3398	}
3399
3400	error = zio_wait(zio);
3401	spa_config_exit(spa, SCL_STATE, FTAG);
3402
3403	if (error) {
3404		(void) printf("Read of %s failed, error: %d\n", thing, error);
3405		goto out;
3406	}
3407
3408	if (flags & ZDB_FLAG_DECOMPRESS) {
3409		/*
3410		 * We don't know how the data was compressed, so just try
3411		 * every decompress function at every inflated blocksize.
3412		 */
3413		enum zio_compress c;
3414		void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3415		void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3416
3417		bcopy(pbuf, pbuf2, psize);
3418
3419		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf + psize,
3420		    SPA_MAXBLOCKSIZE - psize) == 0);
3421
3422		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
3423		    SPA_MAXBLOCKSIZE - psize) == 0);
3424
3425		for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
3426		    lsize -= SPA_MINBLOCKSIZE) {
3427			for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
3428				if (zio_decompress_data(c, pbuf, lbuf,
3429				    psize, lsize) == 0 &&
3430				    zio_decompress_data(c, pbuf2, lbuf2,
3431				    psize, lsize) == 0 &&
3432				    bcmp(lbuf, lbuf2, lsize) == 0)
3433					break;
3434			}
3435			if (c != ZIO_COMPRESS_FUNCTIONS)
3436				break;
3437			lsize -= SPA_MINBLOCKSIZE;
3438		}
3439
3440		umem_free(pbuf2, SPA_MAXBLOCKSIZE);
3441		umem_free(lbuf2, SPA_MAXBLOCKSIZE);
3442
3443		if (lsize <= psize) {
3444			(void) printf("Decompress of %s failed\n", thing);
3445			goto out;
3446		}
3447		buf = lbuf;
3448		size = lsize;
3449	} else {
3450		buf = pbuf;
3451		size = psize;
3452	}
3453
3454	if (flags & ZDB_FLAG_PRINT_BLKPTR)
3455		zdb_print_blkptr((blkptr_t *)(void *)
3456		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
3457	else if (flags & ZDB_FLAG_RAW)
3458		zdb_dump_block_raw(buf, size, flags);
3459	else if (flags & ZDB_FLAG_INDIRECT)
3460		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
3461		    flags);
3462	else if (flags & ZDB_FLAG_GBH)
3463		zdb_dump_gbh(buf, flags);
3464	else
3465		zdb_dump_block(thing, buf, size, flags);
3466
3467out:
3468	umem_free(pbuf, SPA_MAXBLOCKSIZE);
3469	umem_free(lbuf, SPA_MAXBLOCKSIZE);
3470	free(dup);
3471}
3472
3473static boolean_t
3474pool_match(nvlist_t *cfg, char *tgt)
3475{
3476	uint64_t v, guid = strtoull(tgt, NULL, 0);
3477	char *s;
3478
3479	if (guid != 0) {
3480		if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
3481			return (v == guid);
3482	} else {
3483		if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
3484			return (strcmp(s, tgt) == 0);
3485	}
3486	return (B_FALSE);
3487}
3488
3489static char *
3490find_zpool(char **target, nvlist_t **configp, int dirc, char **dirv)
3491{
3492	nvlist_t *pools;
3493	nvlist_t *match = NULL;
3494	char *name = NULL;
3495	char *sepp = NULL;
3496	char sep = '\0';
3497	int count = 0;
3498	importargs_t args = { 0 };
3499
3500	args.paths = dirc;
3501	args.path = dirv;
3502	args.can_be_active = B_TRUE;
3503
3504	if ((sepp = strpbrk(*target, "/@")) != NULL) {
3505		sep = *sepp;
3506		*sepp = '\0';
3507	}
3508
3509	pools = zpool_search_import(g_zfs, &args);
3510
3511	if (pools != NULL) {
3512		nvpair_t *elem = NULL;
3513		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3514			verify(nvpair_value_nvlist(elem, configp) == 0);
3515			if (pool_match(*configp, *target)) {
3516				count++;
3517				if (match != NULL) {
3518					/* print previously found config */
3519					if (name != NULL) {
3520						(void) printf("%s\n", name);
3521						dump_nvlist(match, 8);
3522						name = NULL;
3523					}
3524					(void) printf("%s\n",
3525					    nvpair_name(elem));
3526					dump_nvlist(*configp, 8);
3527				} else {
3528					match = *configp;
3529					name = nvpair_name(elem);
3530				}
3531			}
3532		}
3533	}
3534	if (count > 1)
3535		(void) fatal("\tMatched %d pools - use pool GUID "
3536		    "instead of pool name or \n"
3537		    "\tpool name part of a dataset name to select pool", count);
3538
3539	if (sepp)
3540		*sepp = sep;
3541	/*
3542	 * If pool GUID was specified for pool id, replace it with pool name
3543	 */
3544	if (name && (strstr(*target, name) != *target)) {
3545		int sz = 1 + strlen(name) + ((sepp) ? strlen(sepp) : 0);
3546
3547		*target = umem_alloc(sz, UMEM_NOFAIL);
3548		(void) snprintf(*target, sz, "%s%s", name, sepp ? sepp : "");
3549	}
3550
3551	*configp = name ? match : NULL;
3552
3553	return (name);
3554}
3555
3556int
3557main(int argc, char **argv)
3558{
3559	int i, c;
3560	struct rlimit rl = { 1024, 1024 };
3561	spa_t *spa = NULL;
3562	objset_t *os = NULL;
3563	int dump_all = 1;
3564	int verbose = 0;
3565	int error = 0;
3566	char **searchdirs = NULL;
3567	int nsearch = 0;
3568	char *target;
3569	nvlist_t *policy = NULL;
3570	uint64_t max_txg = UINT64_MAX;
3571	int rewind = ZPOOL_NEVER_REWIND;
3572	char *spa_config_path_env;
3573	boolean_t target_is_spa = B_TRUE;
3574
3575	(void) setrlimit(RLIMIT_NOFILE, &rl);
3576	(void) enable_extended_FILE_stdio(-1, -1);
3577
3578	dprintf_setup(&argc, argv);
3579
3580	/*
3581	 * If there is an environment variable SPA_CONFIG_PATH it overrides
3582	 * default spa_config_path setting. If -U flag is specified it will
3583	 * override this environment variable settings once again.
3584	 */
3585	spa_config_path_env = getenv("SPA_CONFIG_PATH");
3586	if (spa_config_path_env != NULL)
3587		spa_config_path = spa_config_path_env;
3588
3589	while ((c = getopt(argc, argv,
3590	    "bcdhilmMI:suCDRSAFLXx:evp:t:U:PG")) != -1) {
3591		switch (c) {
3592		case 'b':
3593		case 'c':
3594		case 'd':
3595		case 'h':
3596		case 'i':
3597		case 'l':
3598		case 'm':
3599		case 's':
3600		case 'u':
3601		case 'C':
3602		case 'D':
3603		case 'M':
3604		case 'R':
3605		case 'S':
3606		case 'G':
3607			dump_opt[c]++;
3608			dump_all = 0;
3609			break;
3610		case 'A':
3611		case 'F':
3612		case 'L':
3613		case 'X':
3614		case 'e':
3615		case 'P':
3616			dump_opt[c]++;
3617			break;
3618		case 'I':
3619			max_inflight = strtoull(optarg, NULL, 0);
3620			if (max_inflight == 0) {
3621				(void) fprintf(stderr, "maximum number "
3622				    "of inflight I/Os must be greater "
3623				    "than 0\n");
3624				usage();
3625			}
3626			break;
3627		case 'p':
3628			if (searchdirs == NULL) {
3629				searchdirs = umem_alloc(sizeof (char *),
3630				    UMEM_NOFAIL);
3631			} else {
3632				char **tmp = umem_alloc((nsearch + 1) *
3633				    sizeof (char *), UMEM_NOFAIL);
3634				bcopy(searchdirs, tmp, nsearch *
3635				    sizeof (char *));
3636				umem_free(searchdirs,
3637				    nsearch * sizeof (char *));
3638				searchdirs = tmp;
3639			}
3640			searchdirs[nsearch++] = optarg;
3641			break;
3642		case 't':
3643			max_txg = strtoull(optarg, NULL, 0);
3644			if (max_txg < TXG_INITIAL) {
3645				(void) fprintf(stderr, "incorrect txg "
3646				    "specified: %s\n", optarg);
3647				usage();
3648			}
3649			break;
3650		case 'U':
3651			spa_config_path = optarg;
3652			break;
3653		case 'v':
3654			verbose++;
3655			break;
3656		case 'x':
3657			vn_dumpdir = optarg;
3658			break;
3659		default:
3660			usage();
3661			break;
3662		}
3663	}
3664
3665	if (!dump_opt['e'] && searchdirs != NULL) {
3666		(void) fprintf(stderr, "-p option requires use of -e\n");
3667		usage();
3668	}
3669
3670	/*
3671	 * ZDB does not typically re-read blocks; therefore limit the ARC
3672	 * to 256 MB, which can be used entirely for metadata.
3673	 */
3674	zfs_arc_max = zfs_arc_meta_limit = 256 * 1024 * 1024;
3675
3676	/*
3677	 * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
3678	 * "zdb -b" uses traversal prefetch which uses async reads.
3679	 * For good performance, let several of them be active at once.
3680	 */
3681	zfs_vdev_async_read_max_active = 10;
3682
3683	kernel_init(FREAD);
3684	g_zfs = libzfs_init();
3685	if (g_zfs == NULL)
3686		fatal("Fail to initialize zfs");
3687
3688	if (dump_all)
3689		verbose = MAX(verbose, 1);
3690
3691	for (c = 0; c < 256; c++) {
3692		if (dump_all && !strchr("elAFLRSXP", c))
3693			dump_opt[c] = 1;
3694		if (dump_opt[c])
3695			dump_opt[c] += verbose;
3696	}
3697
3698	aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
3699	zfs_recover = (dump_opt['A'] > 1);
3700
3701	argc -= optind;
3702	argv += optind;
3703
3704	if (argc < 2 && dump_opt['R'])
3705		usage();
3706	if (argc < 1) {
3707		if (!dump_opt['e'] && dump_opt['C']) {
3708			dump_cachefile(spa_config_path);
3709			return (0);
3710		}
3711		usage();
3712	}
3713
3714	if (dump_opt['l']) {
3715		dump_label(argv[0]);
3716		return (0);
3717	}
3718
3719	if (dump_opt['X'] || dump_opt['F'])
3720		rewind = ZPOOL_DO_REWIND |
3721		    (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
3722
3723	if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
3724	    nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, max_txg) != 0 ||
3725	    nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind) != 0)
3726		fatal("internal error: %s", strerror(ENOMEM));
3727
3728	error = 0;
3729	target = argv[0];
3730
3731	if (dump_opt['e']) {
3732		nvlist_t *cfg = NULL;
3733		char *name = find_zpool(&target, &cfg, nsearch, searchdirs);
3734
3735		error = ENOENT;
3736		if (name) {
3737			if (dump_opt['C'] > 1) {
3738				(void) printf("\nConfiguration for import:\n");
3739				dump_nvlist(cfg, 8);
3740			}
3741			if (nvlist_add_nvlist(cfg,
3742			    ZPOOL_REWIND_POLICY, policy) != 0) {
3743				fatal("can't open '%s': %s",
3744				    target, strerror(ENOMEM));
3745			}
3746			if ((error = spa_import(name, cfg, NULL,
3747			    ZFS_IMPORT_MISSING_LOG)) != 0) {
3748				error = spa_import(name, cfg, NULL,
3749				    ZFS_IMPORT_VERBATIM);
3750			}
3751		}
3752	}
3753
3754	if (strpbrk(target, "/@") != NULL) {
3755		size_t targetlen;
3756
3757		target_is_spa = B_FALSE;
3758		/*
3759		 * Remove any trailing slash.  Later code would get confused
3760		 * by it, but we want to allow it so that "pool/" can
3761		 * indicate that we want to dump the topmost filesystem,
3762		 * rather than the whole pool.
3763		 */
3764		targetlen = strlen(target);
3765		if (targetlen != 0 && target[targetlen - 1] == '/')
3766			target[targetlen - 1] = '\0';
3767	}
3768
3769	if (error == 0) {
3770		if (target_is_spa || dump_opt['R']) {
3771			error = spa_open_rewind(target, &spa, FTAG, policy,
3772			    NULL);
3773			if (error) {
3774				/*
3775				 * If we're missing the log device then
3776				 * try opening the pool after clearing the
3777				 * log state.
3778				 */
3779				mutex_enter(&spa_namespace_lock);
3780				if ((spa = spa_lookup(target)) != NULL &&
3781				    spa->spa_log_state == SPA_LOG_MISSING) {
3782					spa->spa_log_state = SPA_LOG_CLEAR;
3783					error = 0;
3784				}
3785				mutex_exit(&spa_namespace_lock);
3786
3787				if (!error) {
3788					error = spa_open_rewind(target, &spa,
3789					    FTAG, policy, NULL);
3790				}
3791			}
3792		} else {
3793			error = dmu_objset_own(target, DMU_OST_ANY,
3794			    B_TRUE, FTAG, &os);
3795		}
3796	}
3797	nvlist_free(policy);
3798
3799	if (error)
3800		fatal("can't open '%s': %s", target, strerror(error));
3801
3802	argv++;
3803	argc--;
3804	if (!dump_opt['R']) {
3805		if (argc > 0) {
3806			zopt_objects = argc;
3807			zopt_object = calloc(zopt_objects, sizeof (uint64_t));
3808			for (i = 0; i < zopt_objects; i++) {
3809				errno = 0;
3810				zopt_object[i] = strtoull(argv[i], NULL, 0);
3811				if (zopt_object[i] == 0 && errno != 0)
3812					fatal("bad number %s: %s",
3813					    argv[i], strerror(errno));
3814			}
3815		}
3816		if (os != NULL) {
3817			dump_dir(os);
3818		} else if (zopt_objects > 0 && !dump_opt['m']) {
3819			dump_dir(spa->spa_meta_objset);
3820		} else {
3821			dump_zpool(spa);
3822		}
3823	} else {
3824		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
3825		flagbits['c'] = ZDB_FLAG_CHECKSUM;
3826		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
3827		flagbits['e'] = ZDB_FLAG_BSWAP;
3828		flagbits['g'] = ZDB_FLAG_GBH;
3829		flagbits['i'] = ZDB_FLAG_INDIRECT;
3830		flagbits['p'] = ZDB_FLAG_PHYS;
3831		flagbits['r'] = ZDB_FLAG_RAW;
3832
3833		for (i = 0; i < argc; i++)
3834			zdb_read_block(argv[i], spa);
3835	}
3836
3837	(os != NULL) ? dmu_objset_disown(os, FTAG) : spa_close(spa, FTAG);
3838
3839	fuid_table_destroy();
3840	sa_loaded = B_FALSE;
3841
3842	dump_debug_buffer();
3843
3844	libzfs_fini(g_zfs);
3845	kernel_fini();
3846
3847	return (0);
3848}
3849