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