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