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, 2018 by Delphix. All rights reserved.
25 * Copyright (c) 2014 Integros [integros.com]
26 * Copyright 2017 Nexenta Systems, Inc.
27 * Copyright (c) 2017, 2018 Lawrence Livermore National Security, LLC.
28 * Copyright 2017 RackTop Systems.
29 */
30
31#include <stdio.h>
32#include <unistd.h>
33#include <stdio_ext.h>
34#include <stdlib.h>
35#include <ctype.h>
36#include <sys/zfs_context.h>
37#include <sys/spa.h>
38#include <sys/spa_impl.h>
39#include <sys/dmu.h>
40#include <sys/zap.h>
41#include <sys/fs/zfs.h>
42#include <sys/zfs_znode.h>
43#include <sys/zfs_sa.h>
44#include <sys/sa.h>
45#include <sys/sa_impl.h>
46#include <sys/vdev.h>
47#include <sys/vdev_impl.h>
48#include <sys/metaslab_impl.h>
49#include <sys/dmu_objset.h>
50#include <sys/dsl_dir.h>
51#include <sys/dsl_dataset.h>
52#include <sys/dsl_pool.h>
53#include <sys/dbuf.h>
54#include <sys/zil.h>
55#include <sys/zil_impl.h>
56#include <sys/stat.h>
57#include <sys/resource.h>
58#include <sys/dmu_traverse.h>
59#include <sys/zio_checksum.h>
60#include <sys/zio_compress.h>
61#include <sys/zfs_fuid.h>
62#include <sys/arc.h>
63#include <sys/ddt.h>
64#include <sys/zfeature.h>
65#include <sys/abd.h>
66#include <sys/blkptr.h>
67#include <sys/dsl_scan.h>
68#include <zfs_comutil.h>
69#include <libcmdutils.h>
70#undef verify
71#include <libzfs.h>
72
73#include "zdb.h"
74
75#define	ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ?	\
76	zio_compress_table[(idx)].ci_name : "UNKNOWN")
77#define	ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ?	\
78	zio_checksum_table[(idx)].ci_name : "UNKNOWN")
79#define	ZDB_OT_NAME(idx) ((idx) < DMU_OT_NUMTYPES ?	\
80	dmu_ot[(idx)].ot_name : DMU_OT_IS_VALID(idx) ?	\
81	dmu_ot_byteswap[DMU_OT_BYTESWAP(idx)].ob_name : "UNKNOWN")
82#define	ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) :		\
83	(idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA ?	\
84	DMU_OT_ZAP_OTHER : \
85	(idx) == DMU_OTN_UINT64_DATA || (idx) == DMU_OTN_UINT64_METADATA ? \
86	DMU_OT_UINT64_OTHER : DMU_OT_NUMTYPES)
87
88#ifndef lint
89extern int reference_tracking_enable;
90extern boolean_t zfs_recover;
91extern uint64_t zfs_arc_max, zfs_arc_meta_limit;
92extern int zfs_vdev_async_read_max_active;
93extern boolean_t spa_load_verify_dryrun;
94extern int aok;
95#else
96int reference_tracking_enable;
97boolean_t zfs_recover;
98uint64_t zfs_arc_max, zfs_arc_meta_limit;
99int zfs_vdev_async_read_max_active;
100boolean_t spa_load_verify_dryrun;
101int aok;
102#endif
103
104static const char cmdname[] = "zdb";
105uint8_t dump_opt[256];
106
107typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
108
109static uint64_t *zopt_object = NULL;
110static unsigned zopt_objects = 0;
111static libzfs_handle_t *g_zfs;
112static uint64_t max_inflight = 1000;
113static int leaked_objects = 0;
114
115static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *);
116static void mos_obj_refd(uint64_t);
117
118/*
119 * These libumem hooks provide a reasonable set of defaults for the allocator's
120 * debugging facilities.
121 */
122const char *
123_umem_debug_init()
124{
125	return ("default,verbose"); /* $UMEM_DEBUG setting */
126}
127
128const char *
129_umem_logging_init(void)
130{
131	return ("fail,contents"); /* $UMEM_LOGGING setting */
132}
133
134static void
135usage(void)
136{
137	(void) fprintf(stderr,
138	    "Usage:\t%s [-AbcdDFGhikLMPsvX] [-e [-V] [-p <path> ...]] "
139	    "[-I <inflight I/Os>]\n"
140	    "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
141	    "\t\t[<poolname> [<object> ...]]\n"
142	    "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>] <dataset> "
143	    "[<object> ...]\n"
144	    "\t%s -C [-A] [-U <cache>]\n"
145	    "\t%s -l [-Aqu] <device>\n"
146	    "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
147	    "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
148	    "\t%s -O <dataset> <path>\n"
149	    "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
150	    "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
151	    "\t%s -E [-A] word0:word1:...:word15\n"
152	    "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
153	    "<poolname>\n\n",
154	    cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
155	    cmdname, cmdname);
156
157	(void) fprintf(stderr, "    Dataset name must include at least one "
158	    "separator character '/' or '@'\n");
159	(void) fprintf(stderr, "    If dataset name is specified, only that "
160	    "dataset is dumped\n");
161	(void) fprintf(stderr, "    If object numbers are specified, only "
162	    "those objects are dumped\n\n");
163	(void) fprintf(stderr, "    Options to control amount of output:\n");
164	(void) fprintf(stderr, "        -b block statistics\n");
165	(void) fprintf(stderr, "        -c checksum all metadata (twice for "
166	    "all data) blocks\n");
167	(void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
168	(void) fprintf(stderr, "        -d dataset(s)\n");
169	(void) fprintf(stderr, "        -D dedup statistics\n");
170	(void) fprintf(stderr, "        -E decode and display block from an "
171	    "embedded block pointer\n");
172	(void) fprintf(stderr, "        -h pool history\n");
173	(void) fprintf(stderr, "        -i intent logs\n");
174	(void) fprintf(stderr, "        -l read label contents\n");
175	(void) fprintf(stderr, "        -k examine the checkpointed state "
176	    "of the pool\n");
177	(void) fprintf(stderr, "        -L disable leak tracking (do not "
178	    "load spacemaps)\n");
179	(void) fprintf(stderr, "        -m metaslabs\n");
180	(void) fprintf(stderr, "        -M metaslab groups\n");
181	(void) fprintf(stderr, "        -O perform object lookups by path\n");
182	(void) fprintf(stderr, "        -R read and display block from a "
183	    "device\n");
184	(void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
185	(void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
186	(void) fprintf(stderr, "        -v verbose (applies to all "
187	    "others)\n\n");
188	(void) fprintf(stderr, "    Below options are intended for use "
189	    "with other options:\n");
190	(void) fprintf(stderr, "        -A ignore assertions (-A), enable "
191	    "panic recovery (-AA) or both (-AAA)\n");
192	(void) fprintf(stderr, "        -e pool is exported/destroyed/"
193	    "has altroot/not in a cachefile\n");
194	(void) fprintf(stderr, "        -F attempt automatic rewind within "
195	    "safe range of transaction groups\n");
196	(void) fprintf(stderr, "        -G dump zfs_dbgmsg buffer before "
197	    "exiting\n");
198	(void) fprintf(stderr, "        -I <number of inflight I/Os> -- "
199	    "specify the maximum number of "
200	    "checksumming I/Os [default is 200]\n");
201	(void) fprintf(stderr, "        -o <variable>=<value> set global "
202	    "variable to an unsigned 32-bit integer value\n");
203	(void) fprintf(stderr, "        -p <path> -- use one or more with "
204	    "-e to specify path to vdev dir\n");
205	(void) fprintf(stderr, "        -P print numbers in parseable form\n");
206	(void) fprintf(stderr, "        -q don't print label contents\n");
207	(void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
208	    "searching for uberblocks\n");
209	(void) fprintf(stderr, "        -u uberblock\n");
210	(void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
211	    "cachefile\n");
212	(void) fprintf(stderr, "        -V do verbatim import\n");
213	(void) fprintf(stderr, "        -x <dumpdir> -- "
214	    "dump all read blocks into specified directory\n");
215	(void) fprintf(stderr, "        -X attempt extreme rewind (does not "
216	    "work with dataset)\n\n");
217	(void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
218	    "to make only that option verbose\n");
219	(void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
220	exit(1);
221}
222
223static void
224dump_debug_buffer()
225{
226	if (dump_opt['G']) {
227		(void) printf("\n");
228		zfs_dbgmsg_print("zdb");
229	}
230}
231
232/*
233 * Called for usage errors that are discovered after a call to spa_open(),
234 * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
235 */
236
237static void
238fatal(const char *fmt, ...)
239{
240	va_list ap;
241
242	va_start(ap, fmt);
243	(void) fprintf(stderr, "%s: ", cmdname);
244	(void) vfprintf(stderr, fmt, ap);
245	va_end(ap);
246	(void) fprintf(stderr, "\n");
247
248	dump_debug_buffer();
249
250	exit(1);
251}
252
253/* ARGSUSED */
254static void
255dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
256{
257	nvlist_t *nv;
258	size_t nvsize = *(uint64_t *)data;
259	char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
260
261	VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
262
263	VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
264
265	umem_free(packed, nvsize);
266
267	dump_nvlist(nv, 8);
268
269	nvlist_free(nv);
270}
271
272/* ARGSUSED */
273static void
274dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
275{
276	spa_history_phys_t *shp = data;
277
278	if (shp == NULL)
279		return;
280
281	(void) printf("\t\tpool_create_len = %llu\n",
282	    (u_longlong_t)shp->sh_pool_create_len);
283	(void) printf("\t\tphys_max_off = %llu\n",
284	    (u_longlong_t)shp->sh_phys_max_off);
285	(void) printf("\t\tbof = %llu\n",
286	    (u_longlong_t)shp->sh_bof);
287	(void) printf("\t\teof = %llu\n",
288	    (u_longlong_t)shp->sh_eof);
289	(void) printf("\t\trecords_lost = %llu\n",
290	    (u_longlong_t)shp->sh_records_lost);
291}
292
293static void
294zdb_nicenum(uint64_t num, char *buf, size_t buflen)
295{
296	if (dump_opt['P'])
297		(void) snprintf(buf, buflen, "%llu", (longlong_t)num);
298	else
299		nicenum(num, buf, sizeof (buf));
300}
301
302static const char histo_stars[] = "****************************************";
303static const uint64_t histo_width = sizeof (histo_stars) - 1;
304
305static void
306dump_histogram(const uint64_t *histo, int size, int offset)
307{
308	int i;
309	int minidx = size - 1;
310	int maxidx = 0;
311	uint64_t max = 0;
312
313	for (i = 0; i < size; i++) {
314		if (histo[i] > max)
315			max = histo[i];
316		if (histo[i] > 0 && i > maxidx)
317			maxidx = i;
318		if (histo[i] > 0 && i < minidx)
319			minidx = i;
320	}
321
322	if (max < histo_width)
323		max = histo_width;
324
325	for (i = minidx; i <= maxidx; i++) {
326		(void) printf("\t\t\t%3u: %6llu %s\n",
327		    i + offset, (u_longlong_t)histo[i],
328		    &histo_stars[(max - histo[i]) * histo_width / max]);
329	}
330}
331
332static void
333dump_zap_stats(objset_t *os, uint64_t object)
334{
335	int error;
336	zap_stats_t zs;
337
338	error = zap_get_stats(os, object, &zs);
339	if (error)
340		return;
341
342	if (zs.zs_ptrtbl_len == 0) {
343		ASSERT(zs.zs_num_blocks == 1);
344		(void) printf("\tmicrozap: %llu bytes, %llu entries\n",
345		    (u_longlong_t)zs.zs_blocksize,
346		    (u_longlong_t)zs.zs_num_entries);
347		return;
348	}
349
350	(void) printf("\tFat ZAP stats:\n");
351
352	(void) printf("\t\tPointer table:\n");
353	(void) printf("\t\t\t%llu elements\n",
354	    (u_longlong_t)zs.zs_ptrtbl_len);
355	(void) printf("\t\t\tzt_blk: %llu\n",
356	    (u_longlong_t)zs.zs_ptrtbl_zt_blk);
357	(void) printf("\t\t\tzt_numblks: %llu\n",
358	    (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
359	(void) printf("\t\t\tzt_shift: %llu\n",
360	    (u_longlong_t)zs.zs_ptrtbl_zt_shift);
361	(void) printf("\t\t\tzt_blks_copied: %llu\n",
362	    (u_longlong_t)zs.zs_ptrtbl_blks_copied);
363	(void) printf("\t\t\tzt_nextblk: %llu\n",
364	    (u_longlong_t)zs.zs_ptrtbl_nextblk);
365
366	(void) printf("\t\tZAP entries: %llu\n",
367	    (u_longlong_t)zs.zs_num_entries);
368	(void) printf("\t\tLeaf blocks: %llu\n",
369	    (u_longlong_t)zs.zs_num_leafs);
370	(void) printf("\t\tTotal blocks: %llu\n",
371	    (u_longlong_t)zs.zs_num_blocks);
372	(void) printf("\t\tzap_block_type: 0x%llx\n",
373	    (u_longlong_t)zs.zs_block_type);
374	(void) printf("\t\tzap_magic: 0x%llx\n",
375	    (u_longlong_t)zs.zs_magic);
376	(void) printf("\t\tzap_salt: 0x%llx\n",
377	    (u_longlong_t)zs.zs_salt);
378
379	(void) printf("\t\tLeafs with 2^n pointers:\n");
380	dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
381
382	(void) printf("\t\tBlocks with n*5 entries:\n");
383	dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
384
385	(void) printf("\t\tBlocks n/10 full:\n");
386	dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
387
388	(void) printf("\t\tEntries with n chunks:\n");
389	dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
390
391	(void) printf("\t\tBuckets with n entries:\n");
392	dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
393}
394
395/*ARGSUSED*/
396static void
397dump_none(objset_t *os, uint64_t object, void *data, size_t size)
398{
399}
400
401/*ARGSUSED*/
402static void
403dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
404{
405	(void) printf("\tUNKNOWN OBJECT TYPE\n");
406}
407
408/*ARGSUSED*/
409static void
410dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
411{
412}
413
414/*ARGSUSED*/
415static void
416dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
417{
418}
419
420/*ARGSUSED*/
421static void
422dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
423{
424	zap_cursor_t zc;
425	zap_attribute_t attr;
426	void *prop;
427	unsigned i;
428
429	dump_zap_stats(os, object);
430	(void) printf("\n");
431
432	for (zap_cursor_init(&zc, os, object);
433	    zap_cursor_retrieve(&zc, &attr) == 0;
434	    zap_cursor_advance(&zc)) {
435		(void) printf("\t\t%s = ", attr.za_name);
436		if (attr.za_num_integers == 0) {
437			(void) printf("\n");
438			continue;
439		}
440		prop = umem_zalloc(attr.za_num_integers *
441		    attr.za_integer_length, UMEM_NOFAIL);
442		(void) zap_lookup(os, object, attr.za_name,
443		    attr.za_integer_length, attr.za_num_integers, prop);
444		if (attr.za_integer_length == 1) {
445			(void) printf("%s", (char *)prop);
446		} else {
447			for (i = 0; i < attr.za_num_integers; i++) {
448				switch (attr.za_integer_length) {
449				case 2:
450					(void) printf("%u ",
451					    ((uint16_t *)prop)[i]);
452					break;
453				case 4:
454					(void) printf("%u ",
455					    ((uint32_t *)prop)[i]);
456					break;
457				case 8:
458					(void) printf("%lld ",
459					    (u_longlong_t)((int64_t *)prop)[i]);
460					break;
461				}
462			}
463		}
464		(void) printf("\n");
465		umem_free(prop, attr.za_num_integers * attr.za_integer_length);
466	}
467	zap_cursor_fini(&zc);
468}
469
470static void
471dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
472{
473	bpobj_phys_t *bpop = data;
474	char bytes[32], comp[32], uncomp[32];
475
476	/* make sure the output won't get truncated */
477	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
478	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
479	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
480
481	if (bpop == NULL)
482		return;
483
484	zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
485	zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
486	zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
487
488	(void) printf("\t\tnum_blkptrs = %llu\n",
489	    (u_longlong_t)bpop->bpo_num_blkptrs);
490	(void) printf("\t\tbytes = %s\n", bytes);
491	if (size >= BPOBJ_SIZE_V1) {
492		(void) printf("\t\tcomp = %s\n", comp);
493		(void) printf("\t\tuncomp = %s\n", uncomp);
494	}
495	if (size >= sizeof (*bpop)) {
496		(void) printf("\t\tsubobjs = %llu\n",
497		    (u_longlong_t)bpop->bpo_subobjs);
498		(void) printf("\t\tnum_subobjs = %llu\n",
499		    (u_longlong_t)bpop->bpo_num_subobjs);
500	}
501
502	if (dump_opt['d'] < 5)
503		return;
504
505	for (uint64_t i = 0; i < bpop->bpo_num_blkptrs; i++) {
506		char blkbuf[BP_SPRINTF_LEN];
507		blkptr_t bp;
508
509		int err = dmu_read(os, object,
510		    i * sizeof (bp), sizeof (bp), &bp, 0);
511		if (err != 0) {
512			(void) printf("got error %u from dmu_read\n", err);
513			break;
514		}
515		snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp);
516		(void) printf("\t%s\n", blkbuf);
517	}
518}
519
520/* ARGSUSED */
521static void
522dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
523{
524	dmu_object_info_t doi;
525
526	VERIFY0(dmu_object_info(os, object, &doi));
527	uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
528
529	int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
530	if (err != 0) {
531		(void) printf("got error %u from dmu_read\n", err);
532		kmem_free(subobjs, doi.doi_max_offset);
533		return;
534	}
535
536	int64_t last_nonzero = -1;
537	for (uint64_t i = 0; i < doi.doi_max_offset / 8; i++) {
538		if (subobjs[i] != 0)
539			last_nonzero = i;
540	}
541
542	for (int64_t i = 0; i <= last_nonzero; i++) {
543		(void) printf("\t%llu\n", (longlong_t)subobjs[i]);
544	}
545	kmem_free(subobjs, doi.doi_max_offset);
546}
547
548/*ARGSUSED*/
549static void
550dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
551{
552	dump_zap_stats(os, object);
553	/* contents are printed elsewhere, properly decoded */
554}
555
556/*ARGSUSED*/
557static void
558dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
559{
560	zap_cursor_t zc;
561	zap_attribute_t attr;
562
563	dump_zap_stats(os, object);
564	(void) printf("\n");
565
566	for (zap_cursor_init(&zc, os, object);
567	    zap_cursor_retrieve(&zc, &attr) == 0;
568	    zap_cursor_advance(&zc)) {
569		(void) printf("\t\t%s = ", attr.za_name);
570		if (attr.za_num_integers == 0) {
571			(void) printf("\n");
572			continue;
573		}
574		(void) printf(" %llx : [%d:%d:%d]\n",
575		    (u_longlong_t)attr.za_first_integer,
576		    (int)ATTR_LENGTH(attr.za_first_integer),
577		    (int)ATTR_BSWAP(attr.za_first_integer),
578		    (int)ATTR_NUM(attr.za_first_integer));
579	}
580	zap_cursor_fini(&zc);
581}
582
583/*ARGSUSED*/
584static void
585dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
586{
587	zap_cursor_t zc;
588	zap_attribute_t attr;
589	uint16_t *layout_attrs;
590	unsigned i;
591
592	dump_zap_stats(os, object);
593	(void) printf("\n");
594
595	for (zap_cursor_init(&zc, os, object);
596	    zap_cursor_retrieve(&zc, &attr) == 0;
597	    zap_cursor_advance(&zc)) {
598		(void) printf("\t\t%s = [", attr.za_name);
599		if (attr.za_num_integers == 0) {
600			(void) printf("\n");
601			continue;
602		}
603
604		VERIFY(attr.za_integer_length == 2);
605		layout_attrs = umem_zalloc(attr.za_num_integers *
606		    attr.za_integer_length, UMEM_NOFAIL);
607
608		VERIFY(zap_lookup(os, object, attr.za_name,
609		    attr.za_integer_length,
610		    attr.za_num_integers, layout_attrs) == 0);
611
612		for (i = 0; i != attr.za_num_integers; i++)
613			(void) printf(" %d ", (int)layout_attrs[i]);
614		(void) printf("]\n");
615		umem_free(layout_attrs,
616		    attr.za_num_integers * attr.za_integer_length);
617	}
618	zap_cursor_fini(&zc);
619}
620
621/*ARGSUSED*/
622static void
623dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
624{
625	zap_cursor_t zc;
626	zap_attribute_t attr;
627	const char *typenames[] = {
628		/* 0 */ "not specified",
629		/* 1 */ "FIFO",
630		/* 2 */ "Character Device",
631		/* 3 */ "3 (invalid)",
632		/* 4 */ "Directory",
633		/* 5 */ "5 (invalid)",
634		/* 6 */ "Block Device",
635		/* 7 */ "7 (invalid)",
636		/* 8 */ "Regular File",
637		/* 9 */ "9 (invalid)",
638		/* 10 */ "Symbolic Link",
639		/* 11 */ "11 (invalid)",
640		/* 12 */ "Socket",
641		/* 13 */ "Door",
642		/* 14 */ "Event Port",
643		/* 15 */ "15 (invalid)",
644	};
645
646	dump_zap_stats(os, object);
647	(void) printf("\n");
648
649	for (zap_cursor_init(&zc, os, object);
650	    zap_cursor_retrieve(&zc, &attr) == 0;
651	    zap_cursor_advance(&zc)) {
652		(void) printf("\t\t%s = %lld (type: %s)\n",
653		    attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
654		    typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
655	}
656	zap_cursor_fini(&zc);
657}
658
659static int
660get_dtl_refcount(vdev_t *vd)
661{
662	int refcount = 0;
663
664	if (vd->vdev_ops->vdev_op_leaf) {
665		space_map_t *sm = vd->vdev_dtl_sm;
666
667		if (sm != NULL &&
668		    sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
669			return (1);
670		return (0);
671	}
672
673	for (unsigned c = 0; c < vd->vdev_children; c++)
674		refcount += get_dtl_refcount(vd->vdev_child[c]);
675	return (refcount);
676}
677
678static int
679get_metaslab_refcount(vdev_t *vd)
680{
681	int refcount = 0;
682
683	if (vd->vdev_top == vd) {
684		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
685			space_map_t *sm = vd->vdev_ms[m]->ms_sm;
686
687			if (sm != NULL &&
688			    sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
689				refcount++;
690		}
691	}
692	for (unsigned c = 0; c < vd->vdev_children; c++)
693		refcount += get_metaslab_refcount(vd->vdev_child[c]);
694
695	return (refcount);
696}
697
698static int
699get_obsolete_refcount(vdev_t *vd)
700{
701	int refcount = 0;
702
703	uint64_t obsolete_sm_obj = vdev_obsolete_sm_object(vd);
704	if (vd->vdev_top == vd && obsolete_sm_obj != 0) {
705		dmu_object_info_t doi;
706		VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
707		    obsolete_sm_obj, &doi));
708		if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
709			refcount++;
710		}
711	} else {
712		ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
713		ASSERT3U(obsolete_sm_obj, ==, 0);
714	}
715	for (unsigned c = 0; c < vd->vdev_children; c++) {
716		refcount += get_obsolete_refcount(vd->vdev_child[c]);
717	}
718
719	return (refcount);
720}
721
722static int
723get_prev_obsolete_spacemap_refcount(spa_t *spa)
724{
725	uint64_t prev_obj =
726	    spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
727	if (prev_obj != 0) {
728		dmu_object_info_t doi;
729		VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
730		if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
731			return (1);
732		}
733	}
734	return (0);
735}
736
737static int
738get_checkpoint_refcount(vdev_t *vd)
739{
740	int refcount = 0;
741
742	if (vd->vdev_top == vd && vd->vdev_top_zap != 0 &&
743	    zap_contains(spa_meta_objset(vd->vdev_spa),
744	    vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) == 0)
745		refcount++;
746
747	for (uint64_t c = 0; c < vd->vdev_children; c++)
748		refcount += get_checkpoint_refcount(vd->vdev_child[c]);
749
750	return (refcount);
751}
752
753static int
754verify_spacemap_refcounts(spa_t *spa)
755{
756	uint64_t expected_refcount = 0;
757	uint64_t actual_refcount;
758
759	(void) feature_get_refcount(spa,
760	    &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
761	    &expected_refcount);
762	actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
763	actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
764	actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
765	actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
766	actual_refcount += get_checkpoint_refcount(spa->spa_root_vdev);
767
768	if (expected_refcount != actual_refcount) {
769		(void) printf("space map refcount mismatch: expected %lld != "
770		    "actual %lld\n",
771		    (longlong_t)expected_refcount,
772		    (longlong_t)actual_refcount);
773		return (2);
774	}
775	return (0);
776}
777
778static void
779dump_spacemap(objset_t *os, space_map_t *sm)
780{
781	char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
782	    "INVALID", "INVALID", "INVALID", "INVALID" };
783
784	if (sm == NULL)
785		return;
786
787	(void) printf("space map object %llu:\n",
788	    (longlong_t)sm->sm_object);
789	(void) printf("  smp_length = 0x%llx\n",
790	    (longlong_t)sm->sm_phys->smp_length);
791	(void) printf("  smp_alloc = 0x%llx\n",
792	    (longlong_t)sm->sm_phys->smp_alloc);
793
794	if (dump_opt['d'] < 6 && dump_opt['m'] < 4)
795		return;
796
797	/*
798	 * Print out the freelist entries in both encoded and decoded form.
799	 */
800	uint8_t mapshift = sm->sm_shift;
801	int64_t alloc = 0;
802	uint64_t word, entry_id = 0;
803	for (uint64_t offset = 0; offset < space_map_length(sm);
804	    offset += sizeof (word)) {
805
806		VERIFY0(dmu_read(os, space_map_object(sm), offset,
807		    sizeof (word), &word, DMU_READ_PREFETCH));
808
809		if (sm_entry_is_debug(word)) {
810			(void) printf("\t    [%6llu] %s: txg %llu pass %llu\n",
811			    (u_longlong_t)entry_id,
812			    ddata[SM_DEBUG_ACTION_DECODE(word)],
813			    (u_longlong_t)SM_DEBUG_TXG_DECODE(word),
814			    (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(word));
815			entry_id++;
816			continue;
817		}
818
819		uint8_t words;
820		char entry_type;
821		uint64_t entry_off, entry_run, entry_vdev = SM_NO_VDEVID;
822
823		if (sm_entry_is_single_word(word)) {
824			entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
825			    'A' : 'F';
826			entry_off = (SM_OFFSET_DECODE(word) << mapshift) +
827			    sm->sm_start;
828			entry_run = SM_RUN_DECODE(word) << mapshift;
829			words = 1;
830		} else {
831			/* it is a two-word entry so we read another word */
832			ASSERT(sm_entry_is_double_word(word));
833
834			uint64_t extra_word;
835			offset += sizeof (extra_word);
836			VERIFY0(dmu_read(os, space_map_object(sm), offset,
837			    sizeof (extra_word), &extra_word,
838			    DMU_READ_PREFETCH));
839
840			ASSERT3U(offset, <=, space_map_length(sm));
841
842			entry_run = SM2_RUN_DECODE(word) << mapshift;
843			entry_vdev = SM2_VDEV_DECODE(word);
844			entry_type = (SM2_TYPE_DECODE(extra_word) == SM_ALLOC) ?
845			    'A' : 'F';
846			entry_off = (SM2_OFFSET_DECODE(extra_word) <<
847			    mapshift) + sm->sm_start;
848			words = 2;
849		}
850
851		(void) printf("\t    [%6llu]    %c  range:"
852		    " %010llx-%010llx  size: %06llx vdev: %06llu words: %u\n",
853		    (u_longlong_t)entry_id,
854		    entry_type, (u_longlong_t)entry_off,
855		    (u_longlong_t)(entry_off + entry_run),
856		    (u_longlong_t)entry_run,
857		    (u_longlong_t)entry_vdev, words);
858
859		if (entry_type == 'A')
860			alloc += entry_run;
861		else
862			alloc -= entry_run;
863		entry_id++;
864	}
865	if (alloc != space_map_allocated(sm)) {
866		(void) printf("space_map_object alloc (%lld) INCONSISTENT "
867		    "with space map summary (%lld)\n",
868		    (longlong_t)space_map_allocated(sm), (longlong_t)alloc);
869	}
870}
871
872static void
873dump_metaslab_stats(metaslab_t *msp)
874{
875	char maxbuf[32];
876	range_tree_t *rt = msp->ms_allocatable;
877	avl_tree_t *t = &msp->ms_allocatable_by_size;
878	int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
879
880	/* max sure nicenum has enough space */
881	CTASSERT(sizeof (maxbuf) >= NN_NUMBUF_SZ);
882
883	zdb_nicenum(metaslab_block_maxsize(msp), maxbuf, sizeof (maxbuf));
884
885	(void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
886	    "segments", avl_numnodes(t), "maxsize", maxbuf,
887	    "freepct", free_pct);
888	(void) printf("\tIn-memory histogram:\n");
889	dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
890}
891
892static void
893dump_metaslab(metaslab_t *msp)
894{
895	vdev_t *vd = msp->ms_group->mg_vd;
896	spa_t *spa = vd->vdev_spa;
897	space_map_t *sm = msp->ms_sm;
898	char freebuf[32];
899
900	zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
901	    sizeof (freebuf));
902
903	(void) printf(
904	    "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
905	    (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
906	    (u_longlong_t)space_map_object(sm), freebuf);
907
908	if (dump_opt['m'] > 2 && !dump_opt['L']) {
909		mutex_enter(&msp->ms_lock);
910		VERIFY0(metaslab_load(msp));
911		range_tree_stat_verify(msp->ms_allocatable);
912		dump_metaslab_stats(msp);
913		metaslab_unload(msp);
914		mutex_exit(&msp->ms_lock);
915	}
916
917	if (dump_opt['m'] > 1 && sm != NULL &&
918	    spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
919		/*
920		 * The space map histogram represents free space in chunks
921		 * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
922		 */
923		(void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
924		    (u_longlong_t)msp->ms_fragmentation);
925		dump_histogram(sm->sm_phys->smp_histogram,
926		    SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
927	}
928
929	ASSERT(msp->ms_size == (1ULL << vd->vdev_ms_shift));
930	dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
931}
932
933static void
934print_vdev_metaslab_header(vdev_t *vd)
935{
936	vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
937	const char *bias_str;
938
939	bias_str = (alloc_bias == VDEV_BIAS_LOG || vd->vdev_islog) ?
940	    VDEV_ALLOC_BIAS_LOG :
941	    (alloc_bias == VDEV_BIAS_SPECIAL) ? VDEV_ALLOC_BIAS_SPECIAL :
942	    (alloc_bias == VDEV_BIAS_DEDUP) ? VDEV_ALLOC_BIAS_DEDUP :
943	    vd->vdev_islog ? "log" : "";
944
945	(void) printf("\tvdev %10llu   %s\n"
946	    "\t%-10s%5llu   %-19s   %-15s   %-12s\n",
947	    (u_longlong_t)vd->vdev_id, bias_str,
948	    "metaslabs", (u_longlong_t)vd->vdev_ms_count,
949	    "offset", "spacemap", "free");
950	(void) printf("\t%15s   %19s   %15s   %12s\n",
951	    "---------------", "-------------------",
952	    "---------------", "------------");
953}
954
955static void
956dump_metaslab_groups(spa_t *spa)
957{
958	vdev_t *rvd = spa->spa_root_vdev;
959	metaslab_class_t *mc = spa_normal_class(spa);
960	uint64_t fragmentation;
961
962	metaslab_class_histogram_verify(mc);
963
964	for (unsigned c = 0; c < rvd->vdev_children; c++) {
965		vdev_t *tvd = rvd->vdev_child[c];
966		metaslab_group_t *mg = tvd->vdev_mg;
967
968		if (mg == NULL || mg->mg_class != mc)
969			continue;
970
971		metaslab_group_histogram_verify(mg);
972		mg->mg_fragmentation = metaslab_group_fragmentation(mg);
973
974		(void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
975		    "fragmentation",
976		    (u_longlong_t)tvd->vdev_id,
977		    (u_longlong_t)tvd->vdev_ms_count);
978		if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
979			(void) printf("%3s\n", "-");
980		} else {
981			(void) printf("%3llu%%\n",
982			    (u_longlong_t)mg->mg_fragmentation);
983		}
984		dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
985	}
986
987	(void) printf("\tpool %s\tfragmentation", spa_name(spa));
988	fragmentation = metaslab_class_fragmentation(mc);
989	if (fragmentation == ZFS_FRAG_INVALID)
990		(void) printf("\t%3s\n", "-");
991	else
992		(void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
993	dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
994}
995
996static void
997print_vdev_indirect(vdev_t *vd)
998{
999	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1000	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1001	vdev_indirect_births_t *vib = vd->vdev_indirect_births;
1002
1003	if (vim == NULL) {
1004		ASSERT3P(vib, ==, NULL);
1005		return;
1006	}
1007
1008	ASSERT3U(vdev_indirect_mapping_object(vim), ==,
1009	    vic->vic_mapping_object);
1010	ASSERT3U(vdev_indirect_births_object(vib), ==,
1011	    vic->vic_births_object);
1012
1013	(void) printf("indirect births obj %llu:\n",
1014	    (longlong_t)vic->vic_births_object);
1015	(void) printf("    vib_count = %llu\n",
1016	    (longlong_t)vdev_indirect_births_count(vib));
1017	for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
1018		vdev_indirect_birth_entry_phys_t *cur_vibe =
1019		    &vib->vib_entries[i];
1020		(void) printf("\toffset %llx -> txg %llu\n",
1021		    (longlong_t)cur_vibe->vibe_offset,
1022		    (longlong_t)cur_vibe->vibe_phys_birth_txg);
1023	}
1024	(void) printf("\n");
1025
1026	(void) printf("indirect mapping obj %llu:\n",
1027	    (longlong_t)vic->vic_mapping_object);
1028	(void) printf("    vim_max_offset = 0x%llx\n",
1029	    (longlong_t)vdev_indirect_mapping_max_offset(vim));
1030	(void) printf("    vim_bytes_mapped = 0x%llx\n",
1031	    (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
1032	(void) printf("    vim_count = %llu\n",
1033	    (longlong_t)vdev_indirect_mapping_num_entries(vim));
1034
1035	if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
1036		return;
1037
1038	uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
1039
1040	for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
1041		vdev_indirect_mapping_entry_phys_t *vimep =
1042		    &vim->vim_entries[i];
1043		(void) printf("\t<%llx:%llx:%llx> -> "
1044		    "<%llx:%llx:%llx> (%x obsolete)\n",
1045		    (longlong_t)vd->vdev_id,
1046		    (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
1047		    (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1048		    (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
1049		    (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
1050		    (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1051		    counts[i]);
1052	}
1053	(void) printf("\n");
1054
1055	uint64_t obsolete_sm_object = vdev_obsolete_sm_object(vd);
1056	if (obsolete_sm_object != 0) {
1057		objset_t *mos = vd->vdev_spa->spa_meta_objset;
1058		(void) printf("obsolete space map object %llu:\n",
1059		    (u_longlong_t)obsolete_sm_object);
1060		ASSERT(vd->vdev_obsolete_sm != NULL);
1061		ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
1062		    obsolete_sm_object);
1063		dump_spacemap(mos, vd->vdev_obsolete_sm);
1064		(void) printf("\n");
1065	}
1066}
1067
1068static void
1069dump_metaslabs(spa_t *spa)
1070{
1071	vdev_t *vd, *rvd = spa->spa_root_vdev;
1072	uint64_t m, c = 0, children = rvd->vdev_children;
1073
1074	(void) printf("\nMetaslabs:\n");
1075
1076	if (!dump_opt['d'] && zopt_objects > 0) {
1077		c = zopt_object[0];
1078
1079		if (c >= children)
1080			(void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1081
1082		if (zopt_objects > 1) {
1083			vd = rvd->vdev_child[c];
1084			print_vdev_metaslab_header(vd);
1085
1086			for (m = 1; m < zopt_objects; m++) {
1087				if (zopt_object[m] < vd->vdev_ms_count)
1088					dump_metaslab(
1089					    vd->vdev_ms[zopt_object[m]]);
1090				else
1091					(void) fprintf(stderr, "bad metaslab "
1092					    "number %llu\n",
1093					    (u_longlong_t)zopt_object[m]);
1094			}
1095			(void) printf("\n");
1096			return;
1097		}
1098		children = c + 1;
1099	}
1100	for (; c < children; c++) {
1101		vd = rvd->vdev_child[c];
1102		print_vdev_metaslab_header(vd);
1103
1104		print_vdev_indirect(vd);
1105
1106		for (m = 0; m < vd->vdev_ms_count; m++)
1107			dump_metaslab(vd->vdev_ms[m]);
1108		(void) printf("\n");
1109	}
1110}
1111
1112static void
1113dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
1114{
1115	const ddt_phys_t *ddp = dde->dde_phys;
1116	const ddt_key_t *ddk = &dde->dde_key;
1117	const char *types[4] = { "ditto", "single", "double", "triple" };
1118	char blkbuf[BP_SPRINTF_LEN];
1119	blkptr_t blk;
1120
1121	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1122		if (ddp->ddp_phys_birth == 0)
1123			continue;
1124		ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
1125		snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1126		(void) printf("index %llx refcnt %llu %s %s\n",
1127		    (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
1128		    types[p], blkbuf);
1129	}
1130}
1131
1132static void
1133dump_dedup_ratio(const ddt_stat_t *dds)
1134{
1135	double rL, rP, rD, D, dedup, compress, copies;
1136
1137	if (dds->dds_blocks == 0)
1138		return;
1139
1140	rL = (double)dds->dds_ref_lsize;
1141	rP = (double)dds->dds_ref_psize;
1142	rD = (double)dds->dds_ref_dsize;
1143	D = (double)dds->dds_dsize;
1144
1145	dedup = rD / D;
1146	compress = rL / rP;
1147	copies = rD / rP;
1148
1149	(void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
1150	    "dedup * compress / copies = %.2f\n\n",
1151	    dedup, compress, copies, dedup * compress / copies);
1152}
1153
1154static void
1155dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
1156{
1157	char name[DDT_NAMELEN];
1158	ddt_entry_t dde;
1159	uint64_t walk = 0;
1160	dmu_object_info_t doi;
1161	uint64_t count, dspace, mspace;
1162	int error;
1163
1164	error = ddt_object_info(ddt, type, class, &doi);
1165
1166	if (error == ENOENT)
1167		return;
1168	ASSERT(error == 0);
1169
1170	error = ddt_object_count(ddt, type, class, &count);
1171	ASSERT(error == 0);
1172	if (count == 0)
1173		return;
1174
1175	dspace = doi.doi_physical_blocks_512 << 9;
1176	mspace = doi.doi_fill_count * doi.doi_data_block_size;
1177
1178	ddt_object_name(ddt, type, class, name);
1179
1180	(void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
1181	    name,
1182	    (u_longlong_t)count,
1183	    (u_longlong_t)(dspace / count),
1184	    (u_longlong_t)(mspace / count));
1185
1186	if (dump_opt['D'] < 3)
1187		return;
1188
1189	zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
1190
1191	if (dump_opt['D'] < 4)
1192		return;
1193
1194	if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
1195		return;
1196
1197	(void) printf("%s contents:\n\n", name);
1198
1199	while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
1200		dump_dde(ddt, &dde, walk);
1201
1202	ASSERT3U(error, ==, ENOENT);
1203
1204	(void) printf("\n");
1205}
1206
1207static void
1208dump_all_ddts(spa_t *spa)
1209{
1210	ddt_histogram_t ddh_total;
1211	ddt_stat_t dds_total;
1212
1213	bzero(&ddh_total, sizeof (ddh_total));
1214	bzero(&dds_total, sizeof (dds_total));
1215
1216	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1217		ddt_t *ddt = spa->spa_ddt[c];
1218		for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
1219			for (enum ddt_class class = 0; class < DDT_CLASSES;
1220			    class++) {
1221				dump_ddt(ddt, type, class);
1222			}
1223		}
1224	}
1225
1226	ddt_get_dedup_stats(spa, &dds_total);
1227
1228	if (dds_total.dds_blocks == 0) {
1229		(void) printf("All DDTs are empty\n");
1230		return;
1231	}
1232
1233	(void) printf("\n");
1234
1235	if (dump_opt['D'] > 1) {
1236		(void) printf("DDT histogram (aggregated over all DDTs):\n");
1237		ddt_get_dedup_histogram(spa, &ddh_total);
1238		zpool_dump_ddt(&dds_total, &ddh_total);
1239	}
1240
1241	dump_dedup_ratio(&dds_total);
1242}
1243
1244static void
1245dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
1246{
1247	char *prefix = arg;
1248
1249	(void) printf("%s [%llu,%llu) length %llu\n",
1250	    prefix,
1251	    (u_longlong_t)start,
1252	    (u_longlong_t)(start + size),
1253	    (u_longlong_t)(size));
1254}
1255
1256static void
1257dump_dtl(vdev_t *vd, int indent)
1258{
1259	spa_t *spa = vd->vdev_spa;
1260	boolean_t required;
1261	const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
1262		"outage" };
1263	char prefix[256];
1264
1265	spa_vdev_state_enter(spa, SCL_NONE);
1266	required = vdev_dtl_required(vd);
1267	(void) spa_vdev_state_exit(spa, NULL, 0);
1268
1269	if (indent == 0)
1270		(void) printf("\nDirty time logs:\n\n");
1271
1272	(void) printf("\t%*s%s [%s]\n", indent, "",
1273	    vd->vdev_path ? vd->vdev_path :
1274	    vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
1275	    required ? "DTL-required" : "DTL-expendable");
1276
1277	for (int t = 0; t < DTL_TYPES; t++) {
1278		range_tree_t *rt = vd->vdev_dtl[t];
1279		if (range_tree_space(rt) == 0)
1280			continue;
1281		(void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
1282		    indent + 2, "", name[t]);
1283		range_tree_walk(rt, dump_dtl_seg, prefix);
1284		if (dump_opt['d'] > 5 && vd->vdev_children == 0)
1285			dump_spacemap(spa->spa_meta_objset, vd->vdev_dtl_sm);
1286	}
1287
1288	for (unsigned c = 0; c < vd->vdev_children; c++)
1289		dump_dtl(vd->vdev_child[c], indent + 4);
1290}
1291
1292/* from spa_history.c: spa_history_create_obj() */
1293#define	HIS_BUF_LEN_DEF	(128 << 10)
1294#define	HIS_BUF_LEN_MAX	(1 << 30)
1295
1296static void
1297dump_history(spa_t *spa)
1298{
1299	nvlist_t **events = NULL;
1300	char *buf = NULL;
1301	uint64_t bufsize = HIS_BUF_LEN_DEF;
1302	uint64_t resid, len, off = 0;
1303	uint_t num = 0;
1304	int error;
1305	time_t tsec;
1306	struct tm t;
1307	char tbuf[30];
1308	char internalstr[MAXPATHLEN];
1309
1310	if ((buf = malloc(bufsize)) == NULL)
1311		(void) fprintf(stderr, "Unable to read history: "
1312		    "out of memory\n");
1313	do {
1314		len = bufsize;
1315
1316		if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
1317			(void) fprintf(stderr, "Unable to read history: "
1318			    "error %d\n", error);
1319			return;
1320		}
1321
1322		if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
1323			break;
1324		off -= resid;
1325
1326		/*
1327		 * If the history block is too big, double the buffer
1328		 * size and try again.
1329		 */
1330		if (resid == len) {
1331			free(buf);
1332			buf = NULL;
1333
1334			bufsize <<= 1;
1335			if ((bufsize >= HIS_BUF_LEN_MAX) ||
1336			    ((buf = malloc(bufsize)) == NULL)) {
1337				(void) fprintf(stderr, "Unable to read history: "
1338				    "out of memory\n");
1339				return;
1340			}
1341		}
1342	} while (len != 0);
1343	free(buf);
1344
1345	(void) printf("\nHistory:\n");
1346	for (unsigned i = 0; i < num; i++) {
1347		uint64_t time, txg, ievent;
1348		char *cmd, *intstr;
1349		boolean_t printed = B_FALSE;
1350
1351		if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
1352		    &time) != 0)
1353			goto next;
1354		if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
1355		    &cmd) != 0) {
1356			if (nvlist_lookup_uint64(events[i],
1357			    ZPOOL_HIST_INT_EVENT, &ievent) != 0)
1358				goto next;
1359			verify(nvlist_lookup_uint64(events[i],
1360			    ZPOOL_HIST_TXG, &txg) == 0);
1361			verify(nvlist_lookup_string(events[i],
1362			    ZPOOL_HIST_INT_STR, &intstr) == 0);
1363			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
1364				goto next;
1365
1366			(void) snprintf(internalstr,
1367			    sizeof (internalstr),
1368			    "[internal %s txg:%ju] %s",
1369			    zfs_history_event_names[ievent], (uintmax_t)txg,
1370			    intstr);
1371			cmd = internalstr;
1372		}
1373		tsec = time;
1374		(void) localtime_r(&tsec, &t);
1375		(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
1376		(void) printf("%s %s\n", tbuf, cmd);
1377		printed = B_TRUE;
1378
1379next:
1380		if (dump_opt['h'] > 1) {
1381			if (!printed)
1382				(void) printf("unrecognized record:\n");
1383			dump_nvlist(events[i], 2);
1384		}
1385	}
1386}
1387
1388/*ARGSUSED*/
1389static void
1390dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
1391{
1392}
1393
1394static uint64_t
1395blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
1396    const zbookmark_phys_t *zb)
1397{
1398	if (dnp == NULL) {
1399		ASSERT(zb->zb_level < 0);
1400		if (zb->zb_object == 0)
1401			return (zb->zb_blkid);
1402		return (zb->zb_blkid * BP_GET_LSIZE(bp));
1403	}
1404
1405	ASSERT(zb->zb_level >= 0);
1406
1407	return ((zb->zb_blkid <<
1408	    (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
1409	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
1410}
1411
1412static void
1413snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp)
1414{
1415	const dva_t *dva = bp->blk_dva;
1416	int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
1417
1418	if (dump_opt['b'] >= 6) {
1419		snprintf_blkptr(blkbuf, buflen, bp);
1420		return;
1421	}
1422
1423	if (BP_IS_EMBEDDED(bp)) {
1424		(void) sprintf(blkbuf,
1425		    "EMBEDDED et=%u %llxL/%llxP B=%llu",
1426		    (int)BPE_GET_ETYPE(bp),
1427		    (u_longlong_t)BPE_GET_LSIZE(bp),
1428		    (u_longlong_t)BPE_GET_PSIZE(bp),
1429		    (u_longlong_t)bp->blk_birth);
1430		return;
1431	}
1432
1433	blkbuf[0] = '\0';
1434	for (int i = 0; i < ndvas; i++)
1435		(void) snprintf(blkbuf + strlen(blkbuf),
1436		    buflen - strlen(blkbuf), "%llu:%llx:%llx ",
1437		    (u_longlong_t)DVA_GET_VDEV(&dva[i]),
1438		    (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
1439		    (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
1440
1441	if (BP_IS_HOLE(bp)) {
1442		(void) snprintf(blkbuf + strlen(blkbuf),
1443		    buflen - strlen(blkbuf),
1444		    "%llxL B=%llu",
1445		    (u_longlong_t)BP_GET_LSIZE(bp),
1446		    (u_longlong_t)bp->blk_birth);
1447	} else {
1448		(void) snprintf(blkbuf + strlen(blkbuf),
1449		    buflen - strlen(blkbuf),
1450		    "%llxL/%llxP F=%llu B=%llu/%llu",
1451		    (u_longlong_t)BP_GET_LSIZE(bp),
1452		    (u_longlong_t)BP_GET_PSIZE(bp),
1453		    (u_longlong_t)BP_GET_FILL(bp),
1454		    (u_longlong_t)bp->blk_birth,
1455		    (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
1456	}
1457}
1458
1459static void
1460print_indirect(blkptr_t *bp, const zbookmark_phys_t *zb,
1461    const dnode_phys_t *dnp)
1462{
1463	char blkbuf[BP_SPRINTF_LEN];
1464	int l;
1465
1466	if (!BP_IS_EMBEDDED(bp)) {
1467		ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
1468		ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
1469	}
1470
1471	(void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
1472
1473	ASSERT(zb->zb_level >= 0);
1474
1475	for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
1476		if (l == zb->zb_level) {
1477			(void) printf("L%llx", (u_longlong_t)zb->zb_level);
1478		} else {
1479			(void) printf(" ");
1480		}
1481	}
1482
1483	snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1484	(void) printf("%s\n", blkbuf);
1485}
1486
1487static int
1488visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
1489    blkptr_t *bp, const zbookmark_phys_t *zb)
1490{
1491	int err = 0;
1492
1493	if (bp->blk_birth == 0)
1494		return (0);
1495
1496	print_indirect(bp, zb, dnp);
1497
1498	if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
1499		arc_flags_t flags = ARC_FLAG_WAIT;
1500		int i;
1501		blkptr_t *cbp;
1502		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1503		arc_buf_t *buf;
1504		uint64_t fill = 0;
1505
1506		err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
1507		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
1508		if (err)
1509			return (err);
1510		ASSERT(buf->b_data);
1511
1512		/* recursively visit blocks below this */
1513		cbp = buf->b_data;
1514		for (i = 0; i < epb; i++, cbp++) {
1515			zbookmark_phys_t czb;
1516
1517			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1518			    zb->zb_level - 1,
1519			    zb->zb_blkid * epb + i);
1520			err = visit_indirect(spa, dnp, cbp, &czb);
1521			if (err)
1522				break;
1523			fill += BP_GET_FILL(cbp);
1524		}
1525		if (!err)
1526			ASSERT3U(fill, ==, BP_GET_FILL(bp));
1527		arc_buf_destroy(buf, &buf);
1528	}
1529
1530	return (err);
1531}
1532
1533/*ARGSUSED*/
1534static void
1535dump_indirect(dnode_t *dn)
1536{
1537	dnode_phys_t *dnp = dn->dn_phys;
1538	int j;
1539	zbookmark_phys_t czb;
1540
1541	(void) printf("Indirect blocks:\n");
1542
1543	SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1544	    dn->dn_object, dnp->dn_nlevels - 1, 0);
1545	for (j = 0; j < dnp->dn_nblkptr; j++) {
1546		czb.zb_blkid = j;
1547		(void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1548		    &dnp->dn_blkptr[j], &czb);
1549	}
1550
1551	(void) printf("\n");
1552}
1553
1554/*ARGSUSED*/
1555static void
1556dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1557{
1558	dsl_dir_phys_t *dd = data;
1559	time_t crtime;
1560	char nice[32];
1561
1562	/* make sure nicenum has enough space */
1563	CTASSERT(sizeof (nice) >= NN_NUMBUF_SZ);
1564
1565	if (dd == NULL)
1566		return;
1567
1568	ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1569
1570	crtime = dd->dd_creation_time;
1571	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1572	(void) printf("\t\thead_dataset_obj = %llu\n",
1573	    (u_longlong_t)dd->dd_head_dataset_obj);
1574	(void) printf("\t\tparent_dir_obj = %llu\n",
1575	    (u_longlong_t)dd->dd_parent_obj);
1576	(void) printf("\t\torigin_obj = %llu\n",
1577	    (u_longlong_t)dd->dd_origin_obj);
1578	(void) printf("\t\tchild_dir_zapobj = %llu\n",
1579	    (u_longlong_t)dd->dd_child_dir_zapobj);
1580	zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
1581	(void) printf("\t\tused_bytes = %s\n", nice);
1582	zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
1583	(void) printf("\t\tcompressed_bytes = %s\n", nice);
1584	zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
1585	(void) printf("\t\tuncompressed_bytes = %s\n", nice);
1586	zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
1587	(void) printf("\t\tquota = %s\n", nice);
1588	zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
1589	(void) printf("\t\treserved = %s\n", nice);
1590	(void) printf("\t\tprops_zapobj = %llu\n",
1591	    (u_longlong_t)dd->dd_props_zapobj);
1592	(void) printf("\t\tdeleg_zapobj = %llu\n",
1593	    (u_longlong_t)dd->dd_deleg_zapobj);
1594	(void) printf("\t\tflags = %llx\n",
1595	    (u_longlong_t)dd->dd_flags);
1596
1597#define	DO(which) \
1598	zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
1599	    sizeof (nice)); \
1600	(void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1601	DO(HEAD);
1602	DO(SNAP);
1603	DO(CHILD);
1604	DO(CHILD_RSRV);
1605	DO(REFRSRV);
1606#undef DO
1607	(void) printf("\t\tclones = %llu\n",
1608	    (u_longlong_t)dd->dd_clones);
1609}
1610
1611/*ARGSUSED*/
1612static void
1613dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1614{
1615	dsl_dataset_phys_t *ds = data;
1616	time_t crtime;
1617	char used[32], compressed[32], uncompressed[32], unique[32];
1618	char blkbuf[BP_SPRINTF_LEN];
1619
1620	/* make sure nicenum has enough space */
1621	CTASSERT(sizeof (used) >= NN_NUMBUF_SZ);
1622	CTASSERT(sizeof (compressed) >= NN_NUMBUF_SZ);
1623	CTASSERT(sizeof (uncompressed) >= NN_NUMBUF_SZ);
1624	CTASSERT(sizeof (unique) >= NN_NUMBUF_SZ);
1625
1626	if (ds == NULL)
1627		return;
1628
1629	ASSERT(size == sizeof (*ds));
1630	crtime = ds->ds_creation_time;
1631	zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
1632	zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
1633	zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
1634	    sizeof (uncompressed));
1635	zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
1636	snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
1637
1638	(void) printf("\t\tdir_obj = %llu\n",
1639	    (u_longlong_t)ds->ds_dir_obj);
1640	(void) printf("\t\tprev_snap_obj = %llu\n",
1641	    (u_longlong_t)ds->ds_prev_snap_obj);
1642	(void) printf("\t\tprev_snap_txg = %llu\n",
1643	    (u_longlong_t)ds->ds_prev_snap_txg);
1644	(void) printf("\t\tnext_snap_obj = %llu\n",
1645	    (u_longlong_t)ds->ds_next_snap_obj);
1646	(void) printf("\t\tsnapnames_zapobj = %llu\n",
1647	    (u_longlong_t)ds->ds_snapnames_zapobj);
1648	(void) printf("\t\tnum_children = %llu\n",
1649	    (u_longlong_t)ds->ds_num_children);
1650	(void) printf("\t\tuserrefs_obj = %llu\n",
1651	    (u_longlong_t)ds->ds_userrefs_obj);
1652	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1653	(void) printf("\t\tcreation_txg = %llu\n",
1654	    (u_longlong_t)ds->ds_creation_txg);
1655	(void) printf("\t\tdeadlist_obj = %llu\n",
1656	    (u_longlong_t)ds->ds_deadlist_obj);
1657	(void) printf("\t\tused_bytes = %s\n", used);
1658	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
1659	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1660	(void) printf("\t\tunique = %s\n", unique);
1661	(void) printf("\t\tfsid_guid = %llu\n",
1662	    (u_longlong_t)ds->ds_fsid_guid);
1663	(void) printf("\t\tguid = %llu\n",
1664	    (u_longlong_t)ds->ds_guid);
1665	(void) printf("\t\tflags = %llx\n",
1666	    (u_longlong_t)ds->ds_flags);
1667	(void) printf("\t\tnext_clones_obj = %llu\n",
1668	    (u_longlong_t)ds->ds_next_clones_obj);
1669	(void) printf("\t\tprops_obj = %llu\n",
1670	    (u_longlong_t)ds->ds_props_obj);
1671	(void) printf("\t\tbp = %s\n", blkbuf);
1672}
1673
1674/* ARGSUSED */
1675static int
1676dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1677{
1678	char blkbuf[BP_SPRINTF_LEN];
1679
1680	if (bp->blk_birth != 0) {
1681		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
1682		(void) printf("\t%s\n", blkbuf);
1683	}
1684	return (0);
1685}
1686
1687static void
1688dump_bptree(objset_t *os, uint64_t obj, const char *name)
1689{
1690	char bytes[32];
1691	bptree_phys_t *bt;
1692	dmu_buf_t *db;
1693
1694	/* make sure nicenum has enough space */
1695	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1696
1697	if (dump_opt['d'] < 3)
1698		return;
1699
1700	VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
1701	bt = db->db_data;
1702	zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
1703	(void) printf("\n    %s: %llu datasets, %s\n",
1704	    name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
1705	dmu_buf_rele(db, FTAG);
1706
1707	if (dump_opt['d'] < 5)
1708		return;
1709
1710	(void) printf("\n");
1711
1712	(void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
1713}
1714
1715/* ARGSUSED */
1716static int
1717dump_bpobj_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1718{
1719	char blkbuf[BP_SPRINTF_LEN];
1720
1721	ASSERT(bp->blk_birth != 0);
1722	snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1723	(void) printf("\t%s\n", blkbuf);
1724	return (0);
1725}
1726
1727static void
1728dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
1729{
1730	char bytes[32];
1731	char comp[32];
1732	char uncomp[32];
1733
1734	/* make sure nicenum has enough space */
1735	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1736	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1737	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1738
1739	if (dump_opt['d'] < 3)
1740		return;
1741
1742	zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
1743	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1744		zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
1745		zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
1746		(void) printf("    %*s: object %llu, %llu local blkptrs, "
1747		    "%llu subobjs in object %llu, %s (%s/%s comp)\n",
1748		    indent * 8, name,
1749		    (u_longlong_t)bpo->bpo_object,
1750		    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1751		    (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1752		    (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
1753		    bytes, comp, uncomp);
1754
1755		for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1756			uint64_t subobj;
1757			bpobj_t subbpo;
1758			int error;
1759			VERIFY0(dmu_read(bpo->bpo_os,
1760			    bpo->bpo_phys->bpo_subobjs,
1761			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1762			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1763			if (error != 0) {
1764				(void) printf("ERROR %u while trying to open "
1765				    "subobj id %llu\n",
1766				    error, (u_longlong_t)subobj);
1767				continue;
1768			}
1769			dump_full_bpobj(&subbpo, "subobj", indent + 1);
1770			bpobj_close(&subbpo);
1771		}
1772	} else {
1773		(void) printf("    %*s: object %llu, %llu blkptrs, %s\n",
1774		    indent * 8, name,
1775		    (u_longlong_t)bpo->bpo_object,
1776		    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1777		    bytes);
1778	}
1779
1780	if (dump_opt['d'] < 5)
1781		return;
1782
1783
1784	if (indent == 0) {
1785		(void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1786		(void) printf("\n");
1787	}
1788}
1789
1790static void
1791bpobj_count_refd(bpobj_t *bpo)
1792{
1793	mos_obj_refd(bpo->bpo_object);
1794
1795	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1796		mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
1797		for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1798			uint64_t subobj;
1799			bpobj_t subbpo;
1800			int error;
1801			VERIFY0(dmu_read(bpo->bpo_os,
1802			    bpo->bpo_phys->bpo_subobjs,
1803			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1804			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1805			if (error != 0) {
1806				(void) printf("ERROR %u while trying to open "
1807				    "subobj id %llu\n",
1808				    error, (u_longlong_t)subobj);
1809				continue;
1810			}
1811			bpobj_count_refd(&subbpo);
1812			bpobj_close(&subbpo);
1813		}
1814	}
1815}
1816
1817static void
1818dump_deadlist(dsl_deadlist_t *dl)
1819{
1820	dsl_deadlist_entry_t *dle;
1821	uint64_t unused;
1822	char bytes[32];
1823	char comp[32];
1824	char uncomp[32];
1825	uint64_t empty_bpobj =
1826	    dmu_objset_spa(dl->dl_os)->spa_dsl_pool->dp_empty_bpobj;
1827
1828	/* force the tree to be loaded */
1829	dsl_deadlist_space_range(dl, 0, UINT64_MAX, &unused, &unused, &unused);
1830
1831	if (dl->dl_oldfmt) {
1832		if (dl->dl_bpobj.bpo_object != empty_bpobj)
1833			bpobj_count_refd(&dl->dl_bpobj);
1834	} else {
1835		mos_obj_refd(dl->dl_object);
1836		for (dle = avl_first(&dl->dl_tree); dle;
1837		    dle = AVL_NEXT(&dl->dl_tree, dle)) {
1838			if (dle->dle_bpobj.bpo_object != empty_bpobj)
1839				bpobj_count_refd(&dle->dle_bpobj);
1840		}
1841	}
1842
1843	/* make sure nicenum has enough space */
1844	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1845	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1846	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1847
1848	if (dump_opt['d'] < 3)
1849		return;
1850
1851	if (dl->dl_oldfmt) {
1852		dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
1853		return;
1854	}
1855
1856	zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
1857	zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
1858	zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
1859	(void) printf("\n    Deadlist: %s (%s/%s comp)\n",
1860	    bytes, comp, uncomp);
1861
1862	if (dump_opt['d'] < 4)
1863		return;
1864
1865	(void) printf("\n");
1866
1867	for (dle = avl_first(&dl->dl_tree); dle;
1868	    dle = AVL_NEXT(&dl->dl_tree, dle)) {
1869		if (dump_opt['d'] >= 5) {
1870			char buf[128];
1871			(void) snprintf(buf, sizeof (buf),
1872			    "mintxg %llu -> obj %llu",
1873			    (longlong_t)dle->dle_mintxg,
1874			    (longlong_t)dle->dle_bpobj.bpo_object);
1875			dump_full_bpobj(&dle->dle_bpobj, buf, 0);
1876		} else {
1877			(void) printf("mintxg %llu -> obj %llu\n",
1878			    (longlong_t)dle->dle_mintxg,
1879			    (longlong_t)dle->dle_bpobj.bpo_object);
1880		}
1881	}
1882}
1883
1884static avl_tree_t idx_tree;
1885static avl_tree_t domain_tree;
1886static boolean_t fuid_table_loaded;
1887static objset_t *sa_os = NULL;
1888static sa_attr_type_t *sa_attr_table = NULL;
1889
1890static int
1891open_objset(const char *path, dmu_objset_type_t type, void *tag, objset_t **osp)
1892{
1893	int err;
1894	uint64_t sa_attrs = 0;
1895	uint64_t version = 0;
1896
1897	VERIFY3P(sa_os, ==, NULL);
1898	err = dmu_objset_own(path, type, B_TRUE, tag, osp);
1899	if (err != 0) {
1900		(void) fprintf(stderr, "failed to own dataset '%s': %s\n", path,
1901		    strerror(err));
1902		return (err);
1903	}
1904
1905	if (dmu_objset_type(*osp) == DMU_OST_ZFS) {
1906		(void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1907		    8, 1, &version);
1908		if (version >= ZPL_VERSION_SA) {
1909			(void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1910			    8, 1, &sa_attrs);
1911		}
1912		err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
1913		    &sa_attr_table);
1914		if (err != 0) {
1915			(void) fprintf(stderr, "sa_setup failed: %s\n",
1916			    strerror(err));
1917			dmu_objset_disown(*osp, tag);
1918			*osp = NULL;
1919		}
1920	}
1921	sa_os = *osp;
1922
1923	return (0);
1924}
1925
1926static void
1927close_objset(objset_t *os, void *tag)
1928{
1929	VERIFY3P(os, ==, sa_os);
1930	if (os->os_sa != NULL)
1931		sa_tear_down(os);
1932	dmu_objset_disown(os, tag);
1933	sa_attr_table = NULL;
1934	sa_os = NULL;
1935}
1936
1937static void
1938fuid_table_destroy()
1939{
1940	if (fuid_table_loaded) {
1941		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1942		fuid_table_loaded = B_FALSE;
1943	}
1944}
1945
1946/*
1947 * print uid or gid information.
1948 * For normal POSIX id just the id is printed in decimal format.
1949 * For CIFS files with FUID the fuid is printed in hex followed by
1950 * the domain-rid string.
1951 */
1952static void
1953print_idstr(uint64_t id, const char *id_type)
1954{
1955	if (FUID_INDEX(id)) {
1956		char *domain;
1957
1958		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1959		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
1960		    (u_longlong_t)id, domain, (int)FUID_RID(id));
1961	} else {
1962		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1963	}
1964
1965}
1966
1967static void
1968dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
1969{
1970	uint32_t uid_idx, gid_idx;
1971
1972	uid_idx = FUID_INDEX(uid);
1973	gid_idx = FUID_INDEX(gid);
1974
1975	/* Load domain table, if not already loaded */
1976	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1977		uint64_t fuid_obj;
1978
1979		/* first find the fuid object.  It lives in the master node */
1980		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1981		    8, 1, &fuid_obj) == 0);
1982		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1983		(void) zfs_fuid_table_load(os, fuid_obj,
1984		    &idx_tree, &domain_tree);
1985		fuid_table_loaded = B_TRUE;
1986	}
1987
1988	print_idstr(uid, "uid");
1989	print_idstr(gid, "gid");
1990}
1991
1992/*ARGSUSED*/
1993static void
1994dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
1995{
1996	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
1997	sa_handle_t *hdl;
1998	uint64_t xattr, rdev, gen;
1999	uint64_t uid, gid, mode, fsize, parent, links;
2000	uint64_t pflags;
2001	uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
2002	time_t z_crtime, z_atime, z_mtime, z_ctime;
2003	sa_bulk_attr_t bulk[12];
2004	int idx = 0;
2005	int error;
2006
2007	VERIFY3P(os, ==, sa_os);
2008	if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
2009		(void) printf("Failed to get handle for SA znode\n");
2010		return;
2011	}
2012
2013	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
2014	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
2015	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
2016	    &links, 8);
2017	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
2018	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
2019	    &mode, 8);
2020	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
2021	    NULL, &parent, 8);
2022	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
2023	    &fsize, 8);
2024	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
2025	    acctm, 16);
2026	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
2027	    modtm, 16);
2028	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
2029	    crtm, 16);
2030	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
2031	    chgtm, 16);
2032	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
2033	    &pflags, 8);
2034
2035	if (sa_bulk_lookup(hdl, bulk, idx)) {
2036		(void) sa_handle_destroy(hdl);
2037		return;
2038	}
2039
2040	z_crtime = (time_t)crtm[0];
2041	z_atime = (time_t)acctm[0];
2042	z_mtime = (time_t)modtm[0];
2043	z_ctime = (time_t)chgtm[0];
2044
2045	if (dump_opt['d'] > 4) {
2046		error = zfs_obj_to_path(os, object, path, sizeof (path));
2047		if (error == ESTALE) {
2048			(void) snprintf(path, sizeof (path), "on delete queue");
2049		} else if (error != 0) {
2050			leaked_objects++;
2051			(void) snprintf(path, sizeof (path),
2052			    "path not found, possibly leaked");
2053		}
2054		(void) printf("\tpath	%s\n", path);
2055	}
2056	dump_uidgid(os, uid, gid);
2057	(void) printf("\tatime	%s", ctime(&z_atime));
2058	(void) printf("\tmtime	%s", ctime(&z_mtime));
2059	(void) printf("\tctime	%s", ctime(&z_ctime));
2060	(void) printf("\tcrtime	%s", ctime(&z_crtime));
2061	(void) printf("\tgen	%llu\n", (u_longlong_t)gen);
2062	(void) printf("\tmode	%llo\n", (u_longlong_t)mode);
2063	(void) printf("\tsize	%llu\n", (u_longlong_t)fsize);
2064	(void) printf("\tparent	%llu\n", (u_longlong_t)parent);
2065	(void) printf("\tlinks	%llu\n", (u_longlong_t)links);
2066	(void) printf("\tpflags	%llx\n", (u_longlong_t)pflags);
2067	if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
2068	    sizeof (uint64_t)) == 0)
2069		(void) printf("\txattr	%llu\n", (u_longlong_t)xattr);
2070	if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
2071	    sizeof (uint64_t)) == 0)
2072		(void) printf("\trdev	0x%016llx\n", (u_longlong_t)rdev);
2073	sa_handle_destroy(hdl);
2074}
2075
2076/*ARGSUSED*/
2077static void
2078dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
2079{
2080}
2081
2082/*ARGSUSED*/
2083static void
2084dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
2085{
2086}
2087
2088static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
2089	dump_none,		/* unallocated			*/
2090	dump_zap,		/* object directory		*/
2091	dump_uint64,		/* object array			*/
2092	dump_none,		/* packed nvlist		*/
2093	dump_packed_nvlist,	/* packed nvlist size		*/
2094	dump_none,		/* bpobj			*/
2095	dump_bpobj,		/* bpobj header			*/
2096	dump_none,		/* SPA space map header		*/
2097	dump_none,		/* SPA space map		*/
2098	dump_none,		/* ZIL intent log		*/
2099	dump_dnode,		/* DMU dnode			*/
2100	dump_dmu_objset,	/* DMU objset			*/
2101	dump_dsl_dir,		/* DSL directory		*/
2102	dump_zap,		/* DSL directory child map	*/
2103	dump_zap,		/* DSL dataset snap map		*/
2104	dump_zap,		/* DSL props			*/
2105	dump_dsl_dataset,	/* DSL dataset			*/
2106	dump_znode,		/* ZFS znode			*/
2107	dump_acl,		/* ZFS V0 ACL			*/
2108	dump_uint8,		/* ZFS plain file		*/
2109	dump_zpldir,		/* ZFS directory		*/
2110	dump_zap,		/* ZFS master node		*/
2111	dump_zap,		/* ZFS delete queue		*/
2112	dump_uint8,		/* zvol object			*/
2113	dump_zap,		/* zvol prop			*/
2114	dump_uint8,		/* other uint8[]		*/
2115	dump_uint64,		/* other uint64[]		*/
2116	dump_zap,		/* other ZAP			*/
2117	dump_zap,		/* persistent error log		*/
2118	dump_uint8,		/* SPA history			*/
2119	dump_history_offsets,	/* SPA history offsets		*/
2120	dump_zap,		/* Pool properties		*/
2121	dump_zap,		/* DSL permissions		*/
2122	dump_acl,		/* ZFS ACL			*/
2123	dump_uint8,		/* ZFS SYSACL			*/
2124	dump_none,		/* FUID nvlist			*/
2125	dump_packed_nvlist,	/* FUID nvlist size		*/
2126	dump_zap,		/* DSL dataset next clones	*/
2127	dump_zap,		/* DSL scrub queue		*/
2128	dump_zap,		/* ZFS user/group used		*/
2129	dump_zap,		/* ZFS user/group quota		*/
2130	dump_zap,		/* snapshot refcount tags	*/
2131	dump_ddt_zap,		/* DDT ZAP object		*/
2132	dump_zap,		/* DDT statistics		*/
2133	dump_znode,		/* SA object			*/
2134	dump_zap,		/* SA Master Node		*/
2135	dump_sa_attrs,		/* SA attribute registration	*/
2136	dump_sa_layouts,	/* SA attribute layouts		*/
2137	dump_zap,		/* DSL scrub translations	*/
2138	dump_none,		/* fake dedup BP		*/
2139	dump_zap,		/* deadlist			*/
2140	dump_none,		/* deadlist hdr			*/
2141	dump_zap,		/* dsl clones			*/
2142	dump_bpobj_subobjs,	/* bpobj subobjs		*/
2143	dump_unknown,		/* Unknown type, must be last	*/
2144};
2145
2146static void
2147dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header,
2148    uint64_t *dnode_slots_used)
2149{
2150	dmu_buf_t *db = NULL;
2151	dmu_object_info_t doi;
2152	dnode_t *dn;
2153	void *bonus = NULL;
2154	size_t bsize = 0;
2155	char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
2156	char bonus_size[32];
2157	char aux[50];
2158	int error;
2159
2160	/* make sure nicenum has enough space */
2161	CTASSERT(sizeof (iblk) >= NN_NUMBUF_SZ);
2162	CTASSERT(sizeof (dblk) >= NN_NUMBUF_SZ);
2163	CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
2164	CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
2165	CTASSERT(sizeof (bonus_size) >= NN_NUMBUF_SZ);
2166
2167	if (*print_header) {
2168		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %6s  %5s  %6s  %s\n",
2169		    "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
2170		    "lsize", "%full", "type");
2171		*print_header = 0;
2172	}
2173
2174	if (object == 0) {
2175		dn = DMU_META_DNODE(os);
2176	} else {
2177		error = dmu_bonus_hold(os, object, FTAG, &db);
2178		if (error)
2179			fatal("dmu_bonus_hold(%llu) failed, errno %u",
2180			    object, error);
2181		bonus = db->db_data;
2182		bsize = db->db_size;
2183		dn = DB_DNODE((dmu_buf_impl_t *)db);
2184	}
2185	dmu_object_info_from_dnode(dn, &doi);
2186
2187	if (dnode_slots_used != NULL)
2188		*dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
2189
2190	zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
2191	zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
2192	zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
2193	zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
2194	zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
2195	zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
2196	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
2197	    doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
2198	    doi.doi_max_offset);
2199
2200	aux[0] = '\0';
2201
2202	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
2203		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
2204		    ZDB_CHECKSUM_NAME(doi.doi_checksum));
2205	}
2206
2207	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
2208		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
2209		    ZDB_COMPRESS_NAME(doi.doi_compress));
2210	}
2211
2212	(void) printf("%10" PRIu64
2213	    "  %3u  %5s  %5s  %5s  %5s  %5s  %6s  %s%s\n",
2214	    object, doi.doi_indirection, iblk, dblk,
2215	    asize, dnsize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
2216
2217	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
2218		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %5s  %6s  %s\n",
2219		    "", "", "", "", "", "", bonus_size, "bonus",
2220		    ZDB_OT_NAME(doi.doi_bonus_type));
2221	}
2222
2223	if (verbosity >= 4) {
2224		(void) printf("\tdnode flags: %s%s%s\n",
2225		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
2226		    "USED_BYTES " : "",
2227		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
2228		    "USERUSED_ACCOUNTED " : "",
2229		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
2230		    "SPILL_BLKPTR" : "");
2231		(void) printf("\tdnode maxblkid: %llu\n",
2232		    (longlong_t)dn->dn_phys->dn_maxblkid);
2233
2234		object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os, object,
2235		    bonus, bsize);
2236		object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object, NULL, 0);
2237		*print_header = 1;
2238	}
2239
2240	if (verbosity >= 5)
2241		dump_indirect(dn);
2242
2243	if (verbosity >= 5) {
2244		/*
2245		 * Report the list of segments that comprise the object.
2246		 */
2247		uint64_t start = 0;
2248		uint64_t end;
2249		uint64_t blkfill = 1;
2250		int minlvl = 1;
2251
2252		if (dn->dn_type == DMU_OT_DNODE) {
2253			minlvl = 0;
2254			blkfill = DNODES_PER_BLOCK;
2255		}
2256
2257		for (;;) {
2258			char segsize[32];
2259			/* make sure nicenum has enough space */
2260			CTASSERT(sizeof (segsize) >= NN_NUMBUF_SZ);
2261			error = dnode_next_offset(dn,
2262			    0, &start, minlvl, blkfill, 0);
2263			if (error)
2264				break;
2265			end = start;
2266			error = dnode_next_offset(dn,
2267			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
2268			zdb_nicenum(end - start, segsize, sizeof (segsize));
2269			(void) printf("\t\tsegment [%016llx, %016llx)"
2270			    " size %5s\n", (u_longlong_t)start,
2271			    (u_longlong_t)end, segsize);
2272			if (error)
2273				break;
2274			start = end;
2275		}
2276	}
2277
2278	if (db != NULL)
2279		dmu_buf_rele(db, FTAG);
2280}
2281
2282static void
2283count_dir_mos_objects(dsl_dir_t *dd)
2284{
2285	mos_obj_refd(dd->dd_object);
2286	mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
2287	mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
2288	mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
2289	mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
2290}
2291
2292static void
2293count_ds_mos_objects(dsl_dataset_t *ds)
2294{
2295	mos_obj_refd(ds->ds_object);
2296	mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
2297	mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
2298	mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
2299	mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
2300
2301	if (!dsl_dataset_is_snapshot(ds)) {
2302		count_dir_mos_objects(ds->ds_dir);
2303	}
2304}
2305
2306static const char *objset_types[DMU_OST_NUMTYPES] = {
2307	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
2308
2309static void
2310dump_dir(objset_t *os)
2311{
2312	dmu_objset_stats_t dds;
2313	uint64_t object, object_count;
2314	uint64_t refdbytes, usedobjs, scratch;
2315	char numbuf[32];
2316	char blkbuf[BP_SPRINTF_LEN + 20];
2317	char osname[ZFS_MAX_DATASET_NAME_LEN];
2318	const char *type = "UNKNOWN";
2319	int verbosity = dump_opt['d'];
2320	int print_header = 1;
2321	unsigned i;
2322	int error;
2323	uint64_t total_slots_used = 0;
2324	uint64_t max_slot_used = 0;
2325	uint64_t dnode_slots;
2326
2327	/* make sure nicenum has enough space */
2328	CTASSERT(sizeof (numbuf) >= NN_NUMBUF_SZ);
2329
2330	dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2331	dmu_objset_fast_stat(os, &dds);
2332	dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2333
2334	if (dds.dds_type < DMU_OST_NUMTYPES)
2335		type = objset_types[dds.dds_type];
2336
2337	if (dds.dds_type == DMU_OST_META) {
2338		dds.dds_creation_txg = TXG_INITIAL;
2339		usedobjs = BP_GET_FILL(os->os_rootbp);
2340		refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
2341		    dd_used_bytes;
2342	} else {
2343		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
2344	}
2345
2346	ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
2347
2348	zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
2349
2350	if (verbosity >= 4) {
2351		(void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
2352		(void) snprintf_blkptr(blkbuf + strlen(blkbuf),
2353		    sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
2354	} else {
2355		blkbuf[0] = '\0';
2356	}
2357
2358	dmu_objset_name(os, osname);
2359
2360	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
2361	    "%s, %llu objects%s%s\n",
2362	    osname, type, (u_longlong_t)dmu_objset_id(os),
2363	    (u_longlong_t)dds.dds_creation_txg,
2364	    numbuf, (u_longlong_t)usedobjs, blkbuf,
2365	    (dds.dds_inconsistent) ? " (inconsistent)" : "");
2366
2367	if (zopt_objects != 0) {
2368		for (i = 0; i < zopt_objects; i++)
2369			dump_object(os, zopt_object[i], verbosity,
2370			    &print_header, NULL);
2371		(void) printf("\n");
2372		return;
2373	}
2374
2375	if (dump_opt['i'] != 0 || verbosity >= 2)
2376		dump_intent_log(dmu_objset_zil(os));
2377
2378	if (dmu_objset_ds(os) != NULL) {
2379		dsl_dataset_t *ds = dmu_objset_ds(os);
2380		dump_deadlist(&ds->ds_deadlist);
2381
2382		if (dsl_dataset_remap_deadlist_exists(ds)) {
2383			(void) printf("ds_remap_deadlist:\n");
2384			dump_deadlist(&ds->ds_remap_deadlist);
2385		}
2386		count_ds_mos_objects(ds);
2387	}
2388
2389	if (verbosity < 2)
2390		return;
2391
2392	if (BP_IS_HOLE(os->os_rootbp))
2393		return;
2394
2395	dump_object(os, 0, verbosity, &print_header, NULL);
2396	object_count = 0;
2397	if (DMU_USERUSED_DNODE(os) != NULL &&
2398	    DMU_USERUSED_DNODE(os)->dn_type != 0) {
2399		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
2400		    NULL);
2401		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
2402		    NULL);
2403	}
2404
2405	object = 0;
2406	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
2407		dump_object(os, object, verbosity, &print_header, &dnode_slots);
2408		object_count++;
2409		total_slots_used += dnode_slots;
2410		max_slot_used = object + dnode_slots - 1;
2411	}
2412
2413	(void) printf("\n");
2414
2415	(void) printf("    Dnode slots:\n");
2416	(void) printf("\tTotal used:    %10llu\n",
2417	    (u_longlong_t)total_slots_used);
2418	(void) printf("\tMax used:      %10llu\n",
2419	    (u_longlong_t)max_slot_used);
2420	(void) printf("\tPercent empty: %10lf\n",
2421	    (double)(max_slot_used - total_slots_used)*100 /
2422	    (double)max_slot_used);
2423
2424	(void) printf("\n");
2425
2426	if (error != ESRCH) {
2427		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
2428		abort();
2429	}
2430
2431	ASSERT3U(object_count, ==, usedobjs);
2432
2433	if (leaked_objects != 0) {
2434		(void) printf("%d potentially leaked objects detected\n",
2435		    leaked_objects);
2436		leaked_objects = 0;
2437	}
2438}
2439
2440static void
2441dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
2442{
2443	time_t timestamp = ub->ub_timestamp;
2444
2445	(void) printf("%s", header ? header : "");
2446	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
2447	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
2448	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
2449	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
2450	(void) printf("\ttimestamp = %llu UTC = %s",
2451	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
2452
2453	(void) printf("\tmmp_magic = %016llx\n",
2454	    (u_longlong_t)ub->ub_mmp_magic);
2455	if (MMP_VALID(ub)) {
2456		(void) printf("\tmmp_delay = %0llu\n",
2457		    (u_longlong_t)ub->ub_mmp_delay);
2458		if (MMP_SEQ_VALID(ub))
2459			(void) printf("\tmmp_seq = %u\n",
2460			    (unsigned int) MMP_SEQ(ub));
2461		if (MMP_FAIL_INT_VALID(ub))
2462			(void) printf("\tmmp_fail = %u\n",
2463			    (unsigned int) MMP_FAIL_INT(ub));
2464		if (MMP_INTERVAL_VALID(ub))
2465			(void) printf("\tmmp_write = %u\n",
2466			    (unsigned int) MMP_INTERVAL(ub));
2467		/* After MMP_* to make summarize_uberblock_mmp cleaner */
2468		(void) printf("\tmmp_valid = %x\n",
2469		    (unsigned int) ub->ub_mmp_config & 0xFF);
2470	}
2471
2472	if (dump_opt['u'] >= 3) {
2473		char blkbuf[BP_SPRINTF_LEN];
2474		snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
2475		(void) printf("\trootbp = %s\n", blkbuf);
2476	}
2477	(void) printf("\tcheckpoint_txg = %llu\n",
2478	    (u_longlong_t)ub->ub_checkpoint_txg);
2479	(void) printf("%s", footer ? footer : "");
2480}
2481
2482static void
2483dump_config(spa_t *spa)
2484{
2485	dmu_buf_t *db;
2486	size_t nvsize = 0;
2487	int error = 0;
2488
2489
2490	error = dmu_bonus_hold(spa->spa_meta_objset,
2491	    spa->spa_config_object, FTAG, &db);
2492
2493	if (error == 0) {
2494		nvsize = *(uint64_t *)db->db_data;
2495		dmu_buf_rele(db, FTAG);
2496
2497		(void) printf("\nMOS Configuration:\n");
2498		dump_packed_nvlist(spa->spa_meta_objset,
2499		    spa->spa_config_object, (void *)&nvsize, 1);
2500	} else {
2501		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
2502		    (u_longlong_t)spa->spa_config_object, error);
2503	}
2504}
2505
2506static void
2507dump_cachefile(const char *cachefile)
2508{
2509	int fd;
2510	struct stat64 statbuf;
2511	char *buf;
2512	nvlist_t *config;
2513
2514	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
2515		(void) fprintf(stderr, "cannot open '%s': %s\n", cachefile,
2516		    strerror(errno));
2517		exit(1);
2518	}
2519
2520	if (fstat64(fd, &statbuf) != 0) {
2521		(void) fprintf(stderr, "failed to stat '%s': %s\n", cachefile,
2522		    strerror(errno));
2523		exit(1);
2524	}
2525
2526	if ((buf = malloc(statbuf.st_size)) == NULL) {
2527		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
2528		    (u_longlong_t)statbuf.st_size);
2529		exit(1);
2530	}
2531
2532	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
2533		(void) fprintf(stderr, "failed to read %llu bytes\n",
2534		    (u_longlong_t)statbuf.st_size);
2535		exit(1);
2536	}
2537
2538	(void) close(fd);
2539
2540	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
2541		(void) fprintf(stderr, "failed to unpack nvlist\n");
2542		exit(1);
2543	}
2544
2545	free(buf);
2546
2547	dump_nvlist(config, 0);
2548
2549	nvlist_free(config);
2550}
2551
2552#define	ZDB_MAX_UB_HEADER_SIZE 32
2553
2554static void
2555dump_label_uberblocks(vdev_label_t *lbl, uint64_t ashift)
2556{
2557	vdev_t vd;
2558	vdev_t *vdp = &vd;
2559	char header[ZDB_MAX_UB_HEADER_SIZE];
2560
2561	vd.vdev_ashift = ashift;
2562	vdp->vdev_top = vdp;
2563
2564	for (int i = 0; i < VDEV_UBERBLOCK_COUNT(vdp); i++) {
2565		uint64_t uoff = VDEV_UBERBLOCK_OFFSET(vdp, i);
2566		uberblock_t *ub = (void *)((char *)lbl + uoff);
2567
2568		if (uberblock_verify(ub))
2569			continue;
2570
2571		if ((dump_opt['u'] < 4) &&
2572		    (ub->ub_mmp_magic == MMP_MAGIC) && ub->ub_mmp_delay &&
2573		    (i >= VDEV_UBERBLOCK_COUNT(&vd) - MMP_BLOCKS_PER_LABEL))
2574			continue;
2575
2576		(void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
2577		    "Uberblock[%d]\n", i);
2578		dump_uberblock(ub, header, "");
2579	}
2580}
2581
2582static char curpath[PATH_MAX];
2583
2584/*
2585 * Iterate through the path components, recursively passing
2586 * current one's obj and remaining path until we find the obj
2587 * for the last one.
2588 */
2589static int
2590dump_path_impl(objset_t *os, uint64_t obj, char *name)
2591{
2592	int err;
2593	int header = 1;
2594	uint64_t child_obj;
2595	char *s;
2596	dmu_buf_t *db;
2597	dmu_object_info_t doi;
2598
2599	if ((s = strchr(name, '/')) != NULL)
2600		*s = '\0';
2601	err = zap_lookup(os, obj, name, 8, 1, &child_obj);
2602
2603	(void) strlcat(curpath, name, sizeof (curpath));
2604
2605	if (err != 0) {
2606		(void) fprintf(stderr, "failed to lookup %s: %s\n",
2607		    curpath, strerror(err));
2608		return (err);
2609	}
2610
2611	child_obj = ZFS_DIRENT_OBJ(child_obj);
2612	err = sa_buf_hold(os, child_obj, FTAG, &db);
2613	if (err != 0) {
2614		(void) fprintf(stderr,
2615		    "failed to get SA dbuf for obj %llu: %s\n",
2616		    (u_longlong_t)child_obj, strerror(err));
2617		return (EINVAL);
2618	}
2619	dmu_object_info_from_db(db, &doi);
2620	sa_buf_rele(db, FTAG);
2621
2622	if (doi.doi_bonus_type != DMU_OT_SA &&
2623	    doi.doi_bonus_type != DMU_OT_ZNODE) {
2624		(void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
2625		    doi.doi_bonus_type, (u_longlong_t)child_obj);
2626		return (EINVAL);
2627	}
2628
2629	if (dump_opt['v'] > 6) {
2630		(void) printf("obj=%llu %s type=%d bonustype=%d\n",
2631		    (u_longlong_t)child_obj, curpath, doi.doi_type,
2632		    doi.doi_bonus_type);
2633	}
2634
2635	(void) strlcat(curpath, "/", sizeof (curpath));
2636
2637	switch (doi.doi_type) {
2638	case DMU_OT_DIRECTORY_CONTENTS:
2639		if (s != NULL && *(s + 1) != '\0')
2640			return (dump_path_impl(os, child_obj, s + 1));
2641		/*FALLTHROUGH*/
2642	case DMU_OT_PLAIN_FILE_CONTENTS:
2643		dump_object(os, child_obj, dump_opt['v'], &header, NULL);
2644		return (0);
2645	default:
2646		(void) fprintf(stderr, "object %llu has non-file/directory "
2647		    "type %d\n", (u_longlong_t)obj, doi.doi_type);
2648		break;
2649	}
2650
2651	return (EINVAL);
2652}
2653
2654/*
2655 * Dump the blocks for the object specified by path inside the dataset.
2656 */
2657static int
2658dump_path(char *ds, char *path)
2659{
2660	int err;
2661	objset_t *os;
2662	uint64_t root_obj;
2663
2664	err = open_objset(ds, DMU_OST_ZFS, FTAG, &os);
2665	if (err != 0)
2666		return (err);
2667
2668	err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
2669	if (err != 0) {
2670		(void) fprintf(stderr, "can't lookup root znode: %s\n",
2671		    strerror(err));
2672		dmu_objset_disown(os, FTAG);
2673		return (EINVAL);
2674	}
2675
2676	(void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
2677
2678	err = dump_path_impl(os, root_obj, path);
2679
2680	close_objset(os, FTAG);
2681	return (err);
2682}
2683
2684static int
2685dump_label(const char *dev)
2686{
2687	int fd;
2688	vdev_label_t label;
2689	char path[MAXPATHLEN];
2690	char *buf = label.vl_vdev_phys.vp_nvlist;
2691	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
2692	struct stat64 statbuf;
2693	uint64_t psize, ashift;
2694	boolean_t label_found = B_FALSE;
2695
2696	(void) strlcpy(path, dev, sizeof (path));
2697	if (dev[0] == '/') {
2698		if (strncmp(dev, ZFS_DISK_ROOTD,
2699		    strlen(ZFS_DISK_ROOTD)) == 0) {
2700			(void) snprintf(path, sizeof (path), "%s%s",
2701			    ZFS_RDISK_ROOTD, dev + strlen(ZFS_DISK_ROOTD));
2702		}
2703	} else if (stat64(path, &statbuf) != 0) {
2704		char *s;
2705
2706		(void) snprintf(path, sizeof (path), "%s%s", ZFS_RDISK_ROOTD,
2707		    dev);
2708		if (((s = strrchr(dev, 's')) == NULL &&
2709		    (s = strchr(dev, 'p')) == NULL) ||
2710		    !isdigit(*(s + 1)))
2711			(void) strlcat(path, "s0", sizeof (path));
2712	}
2713
2714	if ((fd = open64(path, O_RDONLY)) < 0) {
2715		(void) fprintf(stderr, "cannot open '%s': %s\n", path,
2716		    strerror(errno));
2717		exit(1);
2718	}
2719
2720	if (fstat64(fd, &statbuf) != 0) {
2721		(void) fprintf(stderr, "failed to stat '%s': %s\n", path,
2722		    strerror(errno));
2723		(void) close(fd);
2724		exit(1);
2725	}
2726
2727	if (S_ISBLK(statbuf.st_mode)) {
2728		(void) fprintf(stderr,
2729		    "cannot use '%s': character device required\n", path);
2730		(void) close(fd);
2731		exit(1);
2732	}
2733
2734	psize = statbuf.st_size;
2735	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
2736
2737	for (int l = 0; l < VDEV_LABELS; l++) {
2738		nvlist_t *config = NULL;
2739
2740		if (!dump_opt['q']) {
2741			(void) printf("------------------------------------\n");
2742			(void) printf("LABEL %d\n", l);
2743			(void) printf("------------------------------------\n");
2744		}
2745
2746		if (pread64(fd, &label, sizeof (label),
2747		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
2748			if (!dump_opt['q'])
2749				(void) printf("failed to read label %d\n", l);
2750			continue;
2751		}
2752
2753		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
2754			if (!dump_opt['q'])
2755				(void) printf("failed to unpack label %d\n", l);
2756			ashift = SPA_MINBLOCKSHIFT;
2757		} else {
2758			nvlist_t *vdev_tree = NULL;
2759
2760			if (!dump_opt['q'])
2761				dump_nvlist(config, 4);
2762			if ((nvlist_lookup_nvlist(config,
2763			    ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
2764			    (nvlist_lookup_uint64(vdev_tree,
2765			    ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
2766				ashift = SPA_MINBLOCKSHIFT;
2767			nvlist_free(config);
2768			label_found = B_TRUE;
2769		}
2770		if (dump_opt['u'])
2771			dump_label_uberblocks(&label, ashift);
2772	}
2773
2774	(void) close(fd);
2775
2776	return (label_found ? 0 : 2);
2777}
2778
2779static uint64_t dataset_feature_count[SPA_FEATURES];
2780static uint64_t remap_deadlist_count = 0;
2781
2782/*ARGSUSED*/
2783static int
2784dump_one_dir(const char *dsname, void *arg)
2785{
2786	int error;
2787	objset_t *os;
2788
2789	error = open_objset(dsname, DMU_OST_ANY, FTAG, &os);
2790	if (error != 0)
2791		return (0);
2792
2793	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
2794		if (!dmu_objset_ds(os)->ds_feature_inuse[f])
2795			continue;
2796		ASSERT(spa_feature_table[f].fi_flags &
2797		    ZFEATURE_FLAG_PER_DATASET);
2798		dataset_feature_count[f]++;
2799	}
2800
2801	if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
2802		remap_deadlist_count++;
2803	}
2804
2805	dump_dir(os);
2806	close_objset(os, FTAG);
2807	fuid_table_destroy();
2808	return (0);
2809}
2810
2811/*
2812 * Block statistics.
2813 */
2814#define	PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
2815typedef struct zdb_blkstats {
2816	uint64_t zb_asize;
2817	uint64_t zb_lsize;
2818	uint64_t zb_psize;
2819	uint64_t zb_count;
2820	uint64_t zb_gangs;
2821	uint64_t zb_ditto_samevdev;
2822	uint64_t zb_ditto_same_ms;
2823	uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
2824} zdb_blkstats_t;
2825
2826/*
2827 * Extended object types to report deferred frees and dedup auto-ditto blocks.
2828 */
2829#define	ZDB_OT_DEFERRED	(DMU_OT_NUMTYPES + 0)
2830#define	ZDB_OT_DITTO	(DMU_OT_NUMTYPES + 1)
2831#define	ZDB_OT_OTHER	(DMU_OT_NUMTYPES + 2)
2832#define	ZDB_OT_TOTAL	(DMU_OT_NUMTYPES + 3)
2833
2834static const char *zdb_ot_extname[] = {
2835	"deferred free",
2836	"dedup ditto",
2837	"other",
2838	"Total",
2839};
2840
2841#define	ZB_TOTAL	DN_MAX_LEVELS
2842
2843typedef struct zdb_cb {
2844	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
2845	uint64_t	zcb_removing_size;
2846	uint64_t	zcb_checkpoint_size;
2847	uint64_t	zcb_dedup_asize;
2848	uint64_t	zcb_dedup_blocks;
2849	uint64_t	zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
2850	uint64_t	zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
2851	    [BPE_PAYLOAD_SIZE];
2852	uint64_t	zcb_start;
2853	hrtime_t	zcb_lastprint;
2854	uint64_t	zcb_totalasize;
2855	uint64_t	zcb_errors[256];
2856	int		zcb_readfails;
2857	int		zcb_haderrors;
2858	spa_t		*zcb_spa;
2859	uint32_t	**zcb_vd_obsolete_counts;
2860} zdb_cb_t;
2861
2862/* test if two DVA offsets from same vdev are within the same metaslab */
2863static boolean_t
2864same_metaslab(spa_t *spa, uint64_t vdev, uint64_t off1, uint64_t off2)
2865{
2866	vdev_t *vd = vdev_lookup_top(spa, vdev);
2867	uint64_t ms_shift = vd->vdev_ms_shift;
2868
2869	return ((off1 >> ms_shift) == (off2 >> ms_shift));
2870}
2871
2872static void
2873zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
2874    dmu_object_type_t type)
2875{
2876	uint64_t refcnt = 0;
2877
2878	ASSERT(type < ZDB_OT_TOTAL);
2879
2880	if (zilog && zil_bp_tree_add(zilog, bp) != 0)
2881		return;
2882
2883	spa_config_enter(zcb->zcb_spa, SCL_CONFIG, FTAG, RW_READER);
2884
2885	for (int i = 0; i < 4; i++) {
2886		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
2887		int t = (i & 1) ? type : ZDB_OT_TOTAL;
2888		int equal;
2889		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
2890
2891		zb->zb_asize += BP_GET_ASIZE(bp);
2892		zb->zb_lsize += BP_GET_LSIZE(bp);
2893		zb->zb_psize += BP_GET_PSIZE(bp);
2894		zb->zb_count++;
2895
2896		/*
2897		 * The histogram is only big enough to record blocks up to
2898		 * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
2899		 * "other", bucket.
2900		 */
2901		unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
2902		idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
2903		zb->zb_psize_histogram[idx]++;
2904
2905		zb->zb_gangs += BP_COUNT_GANG(bp);
2906
2907		switch (BP_GET_NDVAS(bp)) {
2908		case 2:
2909			if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2910			    DVA_GET_VDEV(&bp->blk_dva[1])) {
2911				zb->zb_ditto_samevdev++;
2912
2913				if (same_metaslab(zcb->zcb_spa,
2914				    DVA_GET_VDEV(&bp->blk_dva[0]),
2915				    DVA_GET_OFFSET(&bp->blk_dva[0]),
2916				    DVA_GET_OFFSET(&bp->blk_dva[1])))
2917					zb->zb_ditto_same_ms++;
2918			}
2919			break;
2920		case 3:
2921			equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2922			    DVA_GET_VDEV(&bp->blk_dva[1])) +
2923			    (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2924			    DVA_GET_VDEV(&bp->blk_dva[2])) +
2925			    (DVA_GET_VDEV(&bp->blk_dva[1]) ==
2926			    DVA_GET_VDEV(&bp->blk_dva[2]));
2927			if (equal != 0) {
2928				zb->zb_ditto_samevdev++;
2929
2930				if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2931				    DVA_GET_VDEV(&bp->blk_dva[1]) &&
2932				    same_metaslab(zcb->zcb_spa,
2933				    DVA_GET_VDEV(&bp->blk_dva[0]),
2934				    DVA_GET_OFFSET(&bp->blk_dva[0]),
2935				    DVA_GET_OFFSET(&bp->blk_dva[1])))
2936					zb->zb_ditto_same_ms++;
2937				else if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2938				    DVA_GET_VDEV(&bp->blk_dva[2]) &&
2939				    same_metaslab(zcb->zcb_spa,
2940				    DVA_GET_VDEV(&bp->blk_dva[0]),
2941				    DVA_GET_OFFSET(&bp->blk_dva[0]),
2942				    DVA_GET_OFFSET(&bp->blk_dva[2])))
2943					zb->zb_ditto_same_ms++;
2944				else if (DVA_GET_VDEV(&bp->blk_dva[1]) ==
2945				    DVA_GET_VDEV(&bp->blk_dva[2]) &&
2946				    same_metaslab(zcb->zcb_spa,
2947				    DVA_GET_VDEV(&bp->blk_dva[1]),
2948				    DVA_GET_OFFSET(&bp->blk_dva[1]),
2949				    DVA_GET_OFFSET(&bp->blk_dva[2])))
2950					zb->zb_ditto_same_ms++;
2951			}
2952			break;
2953		}
2954	}
2955
2956	spa_config_exit(zcb->zcb_spa, SCL_CONFIG, FTAG);
2957
2958	if (BP_IS_EMBEDDED(bp)) {
2959		zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
2960		zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
2961		    [BPE_GET_PSIZE(bp)]++;
2962		return;
2963	}
2964
2965	if (dump_opt['L'])
2966		return;
2967
2968	if (BP_GET_DEDUP(bp)) {
2969		ddt_t *ddt;
2970		ddt_entry_t *dde;
2971
2972		ddt = ddt_select(zcb->zcb_spa, bp);
2973		ddt_enter(ddt);
2974		dde = ddt_lookup(ddt, bp, B_FALSE);
2975
2976		if (dde == NULL) {
2977			refcnt = 0;
2978		} else {
2979			ddt_phys_t *ddp = ddt_phys_select(dde, bp);
2980			ddt_phys_decref(ddp);
2981			refcnt = ddp->ddp_refcnt;
2982			if (ddt_phys_total_refcnt(dde) == 0)
2983				ddt_remove(ddt, dde);
2984		}
2985		ddt_exit(ddt);
2986	}
2987
2988	VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
2989	    refcnt ? 0 : spa_min_claim_txg(zcb->zcb_spa),
2990	    bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
2991}
2992
2993/* ARGSUSED */
2994static void
2995zdb_blkptr_done(zio_t *zio)
2996{
2997	spa_t *spa = zio->io_spa;
2998	blkptr_t *bp = zio->io_bp;
2999	int ioerr = zio->io_error;
3000	zdb_cb_t *zcb = zio->io_private;
3001	zbookmark_phys_t *zb = &zio->io_bookmark;
3002
3003	abd_free(zio->io_abd);
3004
3005	mutex_enter(&spa->spa_scrub_lock);
3006	spa->spa_scrub_inflight--;
3007	spa->spa_load_verify_ios--;
3008	cv_broadcast(&spa->spa_scrub_io_cv);
3009
3010	if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
3011		char blkbuf[BP_SPRINTF_LEN];
3012
3013		zcb->zcb_haderrors = 1;
3014		zcb->zcb_errors[ioerr]++;
3015
3016		if (dump_opt['b'] >= 2)
3017			snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3018		else
3019			blkbuf[0] = '\0';
3020
3021		(void) printf("zdb_blkptr_cb: "
3022		    "Got error %d reading "
3023		    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
3024		    ioerr,
3025		    (u_longlong_t)zb->zb_objset,
3026		    (u_longlong_t)zb->zb_object,
3027		    (u_longlong_t)zb->zb_level,
3028		    (u_longlong_t)zb->zb_blkid,
3029		    blkbuf);
3030	}
3031	mutex_exit(&spa->spa_scrub_lock);
3032}
3033
3034/* ARGSUSED */
3035static int
3036zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
3037    const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
3038{
3039	zdb_cb_t *zcb = arg;
3040	dmu_object_type_t type;
3041	boolean_t is_metadata;
3042
3043	if (bp == NULL)
3044		return (0);
3045
3046	if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
3047		char blkbuf[BP_SPRINTF_LEN];
3048		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3049		(void) printf("objset %llu object %llu "
3050		    "level %lld offset 0x%llx %s\n",
3051		    (u_longlong_t)zb->zb_objset,
3052		    (u_longlong_t)zb->zb_object,
3053		    (longlong_t)zb->zb_level,
3054		    (u_longlong_t)blkid2offset(dnp, bp, zb),
3055		    blkbuf);
3056	}
3057
3058	if (BP_IS_HOLE(bp))
3059		return (0);
3060
3061	type = BP_GET_TYPE(bp);
3062
3063	zdb_count_block(zcb, zilog, bp,
3064	    (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
3065
3066	is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
3067
3068	if (!BP_IS_EMBEDDED(bp) &&
3069	    (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
3070		size_t size = BP_GET_PSIZE(bp);
3071		abd_t *abd = abd_alloc(size, B_FALSE);
3072		int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
3073
3074		/* If it's an intent log block, failure is expected. */
3075		if (zb->zb_level == ZB_ZIL_LEVEL)
3076			flags |= ZIO_FLAG_SPECULATIVE;
3077
3078		mutex_enter(&spa->spa_scrub_lock);
3079		while (spa->spa_load_verify_ios > max_inflight)
3080			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
3081		spa->spa_scrub_inflight++;
3082		spa->spa_load_verify_ios++;
3083		mutex_exit(&spa->spa_scrub_lock);
3084
3085		zio_nowait(zio_read(NULL, spa, bp, abd, size,
3086		    zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
3087	}
3088
3089	zcb->zcb_readfails = 0;
3090
3091	/* only call gethrtime() every 100 blocks */
3092	static int iters;
3093	if (++iters > 100)
3094		iters = 0;
3095	else
3096		return (0);
3097
3098	if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
3099		uint64_t now = gethrtime();
3100		char buf[10];
3101		uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
3102		int kb_per_sec =
3103		    1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
3104		int sec_remaining =
3105		    (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
3106
3107		/* make sure nicenum has enough space */
3108		CTASSERT(sizeof (buf) >= NN_NUMBUF_SZ);
3109
3110		zfs_nicenum(bytes, buf, sizeof (buf));
3111		(void) fprintf(stderr,
3112		    "\r%5s completed (%4dMB/s) "
3113		    "estimated time remaining: %uhr %02umin %02usec        ",
3114		    buf, kb_per_sec / 1024,
3115		    sec_remaining / 60 / 60,
3116		    sec_remaining / 60 % 60,
3117		    sec_remaining % 60);
3118
3119		zcb->zcb_lastprint = now;
3120	}
3121
3122	return (0);
3123}
3124
3125static void
3126zdb_leak(void *arg, uint64_t start, uint64_t size)
3127{
3128	vdev_t *vd = arg;
3129
3130	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
3131	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
3132}
3133
3134static metaslab_ops_t zdb_metaslab_ops = {
3135	NULL	/* alloc */
3136};
3137
3138static void
3139zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
3140{
3141	ddt_bookmark_t ddb;
3142	ddt_entry_t dde;
3143	int error;
3144
3145	ASSERT(!dump_opt['L']);
3146
3147	bzero(&ddb, sizeof (ddb));
3148	while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
3149		blkptr_t blk;
3150		ddt_phys_t *ddp = dde.dde_phys;
3151
3152		if (ddb.ddb_class == DDT_CLASS_UNIQUE)
3153			return;
3154
3155		ASSERT(ddt_phys_total_refcnt(&dde) > 1);
3156
3157		for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
3158			if (ddp->ddp_phys_birth == 0)
3159				continue;
3160			ddt_bp_create(ddb.ddb_checksum,
3161			    &dde.dde_key, ddp, &blk);
3162			if (p == DDT_PHYS_DITTO) {
3163				zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
3164			} else {
3165				zcb->zcb_dedup_asize +=
3166				    BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
3167				zcb->zcb_dedup_blocks++;
3168			}
3169		}
3170		ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
3171		ddt_enter(ddt);
3172		VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
3173		ddt_exit(ddt);
3174	}
3175
3176	ASSERT(error == ENOENT);
3177}
3178
3179/* ARGSUSED */
3180static void
3181claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
3182    uint64_t size, void *arg)
3183{
3184	/*
3185	 * This callback was called through a remap from
3186	 * a device being removed. Therefore, the vdev that
3187	 * this callback is applied to is a concrete
3188	 * vdev.
3189	 */
3190	ASSERT(vdev_is_concrete(vd));
3191
3192	VERIFY0(metaslab_claim_impl(vd, offset, size,
3193	    spa_min_claim_txg(vd->vdev_spa)));
3194}
3195
3196static void
3197claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
3198{
3199	vdev_t *vd = arg;
3200
3201	vdev_indirect_ops.vdev_op_remap(vd, offset, size,
3202	    claim_segment_impl_cb, NULL);
3203}
3204
3205/*
3206 * After accounting for all allocated blocks that are directly referenced,
3207 * we might have missed a reference to a block from a partially complete
3208 * (and thus unused) indirect mapping object. We perform a secondary pass
3209 * through the metaslabs we have already mapped and claim the destination
3210 * blocks.
3211 */
3212static void
3213zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
3214{
3215	if (dump_opt['L'])
3216		return;
3217
3218	if (spa->spa_vdev_removal == NULL)
3219		return;
3220
3221	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3222
3223	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
3224	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
3225	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3226
3227	for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
3228		metaslab_t *msp = vd->vdev_ms[msi];
3229
3230		if (msp->ms_start >= vdev_indirect_mapping_max_offset(vim))
3231			break;
3232
3233		ASSERT0(range_tree_space(svr->svr_allocd_segs));
3234
3235		if (msp->ms_sm != NULL) {
3236			VERIFY0(space_map_load(msp->ms_sm,
3237			    svr->svr_allocd_segs, SM_ALLOC));
3238
3239			/*
3240			 * Clear everything past what has been synced unless
3241			 * it's past the spacemap, because we have not allocated
3242			 * mappings for it yet.
3243			 */
3244			uint64_t vim_max_offset =
3245			    vdev_indirect_mapping_max_offset(vim);
3246			uint64_t sm_end = msp->ms_sm->sm_start +
3247			    msp->ms_sm->sm_size;
3248			if (sm_end > vim_max_offset)
3249				range_tree_clear(svr->svr_allocd_segs,
3250				    vim_max_offset, sm_end - vim_max_offset);
3251		}
3252
3253		zcb->zcb_removing_size +=
3254		    range_tree_space(svr->svr_allocd_segs);
3255		range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
3256	}
3257
3258	spa_config_exit(spa, SCL_CONFIG, FTAG);
3259}
3260
3261/* ARGSUSED */
3262static int
3263increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3264{
3265	zdb_cb_t *zcb = arg;
3266	spa_t *spa = zcb->zcb_spa;
3267	vdev_t *vd;
3268	const dva_t *dva = &bp->blk_dva[0];
3269
3270	ASSERT(!dump_opt['L']);
3271	ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
3272
3273	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3274	vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
3275	ASSERT3P(vd, !=, NULL);
3276	spa_config_exit(spa, SCL_VDEV, FTAG);
3277
3278	ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
3279	ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
3280
3281	vdev_indirect_mapping_increment_obsolete_count(
3282	    vd->vdev_indirect_mapping,
3283	    DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
3284	    zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
3285
3286	return (0);
3287}
3288
3289static uint32_t *
3290zdb_load_obsolete_counts(vdev_t *vd)
3291{
3292	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3293	spa_t *spa = vd->vdev_spa;
3294	spa_condensing_indirect_phys_t *scip =
3295	    &spa->spa_condensing_indirect_phys;
3296	uint32_t *counts;
3297
3298	EQUIV(vdev_obsolete_sm_object(vd) != 0, vd->vdev_obsolete_sm != NULL);
3299	counts = vdev_indirect_mapping_load_obsolete_counts(vim);
3300	if (vd->vdev_obsolete_sm != NULL) {
3301		vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
3302		    vd->vdev_obsolete_sm);
3303	}
3304	if (scip->scip_vdev == vd->vdev_id &&
3305	    scip->scip_prev_obsolete_sm_object != 0) {
3306		space_map_t *prev_obsolete_sm = NULL;
3307		VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
3308		    scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
3309		vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
3310		    prev_obsolete_sm);
3311		space_map_close(prev_obsolete_sm);
3312	}
3313	return (counts);
3314}
3315
3316typedef struct checkpoint_sm_exclude_entry_arg {
3317	vdev_t *cseea_vd;
3318	uint64_t cseea_checkpoint_size;
3319} checkpoint_sm_exclude_entry_arg_t;
3320
3321static int
3322checkpoint_sm_exclude_entry_cb(space_map_entry_t *sme, void *arg)
3323{
3324	checkpoint_sm_exclude_entry_arg_t *cseea = arg;
3325	vdev_t *vd = cseea->cseea_vd;
3326	metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
3327	uint64_t end = sme->sme_offset + sme->sme_run;
3328
3329	ASSERT(sme->sme_type == SM_FREE);
3330
3331	/*
3332	 * Since the vdev_checkpoint_sm exists in the vdev level
3333	 * and the ms_sm space maps exist in the metaslab level,
3334	 * an entry in the checkpoint space map could theoretically
3335	 * cross the boundaries of the metaslab that it belongs.
3336	 *
3337	 * In reality, because of the way that we populate and
3338	 * manipulate the checkpoint's space maps currently,
3339	 * there shouldn't be any entries that cross metaslabs.
3340	 * Hence the assertion below.
3341	 *
3342	 * That said, there is no fundamental requirement that
3343	 * the checkpoint's space map entries should not cross
3344	 * metaslab boundaries. So if needed we could add code
3345	 * that handles metaslab-crossing segments in the future.
3346	 */
3347	VERIFY3U(sme->sme_offset, >=, ms->ms_start);
3348	VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
3349
3350	/*
3351	 * By removing the entry from the allocated segments we
3352	 * also verify that the entry is there to begin with.
3353	 */
3354	mutex_enter(&ms->ms_lock);
3355	range_tree_remove(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
3356	mutex_exit(&ms->ms_lock);
3357
3358	cseea->cseea_checkpoint_size += sme->sme_run;
3359	return (0);
3360}
3361
3362static void
3363zdb_leak_init_vdev_exclude_checkpoint(vdev_t *vd, zdb_cb_t *zcb)
3364{
3365	spa_t *spa = vd->vdev_spa;
3366	space_map_t *checkpoint_sm = NULL;
3367	uint64_t checkpoint_sm_obj;
3368
3369	/*
3370	 * If there is no vdev_top_zap, we are in a pool whose
3371	 * version predates the pool checkpoint feature.
3372	 */
3373	if (vd->vdev_top_zap == 0)
3374		return;
3375
3376	/*
3377	 * If there is no reference of the vdev_checkpoint_sm in
3378	 * the vdev_top_zap, then one of the following scenarios
3379	 * is true:
3380	 *
3381	 * 1] There is no checkpoint
3382	 * 2] There is a checkpoint, but no checkpointed blocks
3383	 *    have been freed yet
3384	 * 3] The current vdev is indirect
3385	 *
3386	 * In these cases we return immediately.
3387	 */
3388	if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
3389	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
3390		return;
3391
3392	VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
3393	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1,
3394	    &checkpoint_sm_obj));
3395
3396	checkpoint_sm_exclude_entry_arg_t cseea;
3397	cseea.cseea_vd = vd;
3398	cseea.cseea_checkpoint_size = 0;
3399
3400	VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
3401	    checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
3402
3403	VERIFY0(space_map_iterate(checkpoint_sm,
3404	    space_map_length(checkpoint_sm),
3405	    checkpoint_sm_exclude_entry_cb, &cseea));
3406	space_map_close(checkpoint_sm);
3407
3408	zcb->zcb_checkpoint_size += cseea.cseea_checkpoint_size;
3409}
3410
3411static void
3412zdb_leak_init_exclude_checkpoint(spa_t *spa, zdb_cb_t *zcb)
3413{
3414	ASSERT(!dump_opt['L']);
3415
3416	vdev_t *rvd = spa->spa_root_vdev;
3417	for (uint64_t c = 0; c < rvd->vdev_children; c++) {
3418		ASSERT3U(c, ==, rvd->vdev_child[c]->vdev_id);
3419		zdb_leak_init_vdev_exclude_checkpoint(rvd->vdev_child[c], zcb);
3420	}
3421}
3422
3423static void
3424load_concrete_ms_allocatable_trees(spa_t *spa, maptype_t maptype)
3425{
3426	vdev_t *rvd = spa->spa_root_vdev;
3427	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
3428		vdev_t *vd = rvd->vdev_child[i];
3429
3430		ASSERT3U(i, ==, vd->vdev_id);
3431
3432		if (vd->vdev_ops == &vdev_indirect_ops)
3433			continue;
3434
3435		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3436			metaslab_t *msp = vd->vdev_ms[m];
3437
3438			(void) fprintf(stderr,
3439			    "\rloading concrete vdev %llu, "
3440			    "metaslab %llu of %llu ...",
3441			    (longlong_t)vd->vdev_id,
3442			    (longlong_t)msp->ms_id,
3443			    (longlong_t)vd->vdev_ms_count);
3444
3445			mutex_enter(&msp->ms_lock);
3446			metaslab_unload(msp);
3447
3448			/*
3449			 * We don't want to spend the CPU manipulating the
3450			 * size-ordered tree, so clear the range_tree ops.
3451			 */
3452			msp->ms_allocatable->rt_ops = NULL;
3453
3454			if (msp->ms_sm != NULL) {
3455				VERIFY0(space_map_load(msp->ms_sm,
3456				    msp->ms_allocatable, maptype));
3457			}
3458			if (!msp->ms_loaded)
3459				msp->ms_loaded = B_TRUE;
3460			mutex_exit(&msp->ms_lock);
3461		}
3462	}
3463}
3464
3465/*
3466 * vm_idxp is an in-out parameter which (for indirect vdevs) is the
3467 * index in vim_entries that has the first entry in this metaslab.
3468 * On return, it will be set to the first entry after this metaslab.
3469 */
3470static void
3471load_indirect_ms_allocatable_tree(vdev_t *vd, metaslab_t *msp,
3472    uint64_t *vim_idxp)
3473{
3474	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3475
3476	mutex_enter(&msp->ms_lock);
3477	metaslab_unload(msp);
3478
3479	/*
3480	 * We don't want to spend the CPU manipulating the
3481	 * size-ordered tree, so clear the range_tree ops.
3482	 */
3483	msp->ms_allocatable->rt_ops = NULL;
3484
3485	for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
3486	    (*vim_idxp)++) {
3487		vdev_indirect_mapping_entry_phys_t *vimep =
3488		    &vim->vim_entries[*vim_idxp];
3489		uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
3490		uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
3491		ASSERT3U(ent_offset, >=, msp->ms_start);
3492		if (ent_offset >= msp->ms_start + msp->ms_size)
3493			break;
3494
3495		/*
3496		 * Mappings do not cross metaslab boundaries,
3497		 * because we create them by walking the metaslabs.
3498		 */
3499		ASSERT3U(ent_offset + ent_len, <=,
3500		    msp->ms_start + msp->ms_size);
3501		range_tree_add(msp->ms_allocatable, ent_offset, ent_len);
3502	}
3503
3504	if (!msp->ms_loaded)
3505		msp->ms_loaded = B_TRUE;
3506	mutex_exit(&msp->ms_lock);
3507}
3508
3509static void
3510zdb_leak_init_prepare_indirect_vdevs(spa_t *spa, zdb_cb_t *zcb)
3511{
3512	ASSERT(!dump_opt['L']);
3513
3514	vdev_t *rvd = spa->spa_root_vdev;
3515	for (uint64_t c = 0; c < rvd->vdev_children; c++) {
3516		vdev_t *vd = rvd->vdev_child[c];
3517
3518		ASSERT3U(c, ==, vd->vdev_id);
3519
3520		if (vd->vdev_ops != &vdev_indirect_ops)
3521			continue;
3522
3523		/*
3524		 * Note: we don't check for mapping leaks on
3525		 * removing vdevs because their ms_allocatable's
3526		 * are used to look for leaks in allocated space.
3527		 */
3528		zcb->zcb_vd_obsolete_counts[c] = zdb_load_obsolete_counts(vd);
3529
3530		/*
3531		 * Normally, indirect vdevs don't have any
3532		 * metaslabs.  We want to set them up for
3533		 * zio_claim().
3534		 */
3535		VERIFY0(vdev_metaslab_init(vd, 0));
3536
3537		vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3538		uint64_t vim_idx = 0;
3539		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3540
3541			(void) fprintf(stderr,
3542			    "\rloading indirect vdev %llu, "
3543			    "metaslab %llu of %llu ...",
3544			    (longlong_t)vd->vdev_id,
3545			    (longlong_t)vd->vdev_ms[m]->ms_id,
3546			    (longlong_t)vd->vdev_ms_count);
3547
3548			load_indirect_ms_allocatable_tree(vd, vd->vdev_ms[m],
3549			    &vim_idx);
3550		}
3551		ASSERT3U(vim_idx, ==, vdev_indirect_mapping_num_entries(vim));
3552	}
3553}
3554
3555static void
3556zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
3557{
3558	zcb->zcb_spa = spa;
3559
3560	if (dump_opt['L'])
3561		return;
3562
3563	dsl_pool_t *dp = spa->spa_dsl_pool;
3564	vdev_t *rvd = spa->spa_root_vdev;
3565
3566	/*
3567	 * We are going to be changing the meaning of the metaslab's
3568	 * ms_allocatable.  Ensure that the allocator doesn't try to
3569	 * use the tree.
3570	 */
3571	spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
3572	spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
3573
3574	zcb->zcb_vd_obsolete_counts =
3575	    umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
3576	    UMEM_NOFAIL);
3577
3578	/*
3579	 * For leak detection, we overload the ms_allocatable trees
3580	 * to contain allocated segments instead of free segments.
3581	 * As a result, we can't use the normal metaslab_load/unload
3582	 * interfaces.
3583	 */
3584	zdb_leak_init_prepare_indirect_vdevs(spa, zcb);
3585	load_concrete_ms_allocatable_trees(spa, SM_ALLOC);
3586
3587	/*
3588	 * On load_concrete_ms_allocatable_trees() we loaded all the
3589	 * allocated entries from the ms_sm to the ms_allocatable for
3590	 * each metaslab. If the pool has a checkpoint or is in the
3591	 * middle of discarding a checkpoint, some of these blocks
3592	 * may have been freed but their ms_sm may not have been
3593	 * updated because they are referenced by the checkpoint. In
3594	 * order to avoid false-positives during leak-detection, we
3595	 * go through the vdev's checkpoint space map and exclude all
3596	 * its entries from their relevant ms_allocatable.
3597	 *
3598	 * We also aggregate the space held by the checkpoint and add
3599	 * it to zcb_checkpoint_size.
3600	 *
3601	 * Note that at this point we are also verifying that all the
3602	 * entries on the checkpoint_sm are marked as allocated in
3603	 * the ms_sm of their relevant metaslab.
3604	 * [see comment in checkpoint_sm_exclude_entry_cb()]
3605	 */
3606	zdb_leak_init_exclude_checkpoint(spa, zcb);
3607	ASSERT3U(zcb->zcb_checkpoint_size, ==, spa_get_checkpoint_space(spa));
3608
3609	/* for cleaner progress output */
3610	(void) fprintf(stderr, "\n");
3611
3612	if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
3613		ASSERT(spa_feature_is_enabled(spa,
3614		    SPA_FEATURE_DEVICE_REMOVAL));
3615		(void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
3616		    increment_indirect_mapping_cb, zcb, NULL);
3617	}
3618
3619	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3620	zdb_ddt_leak_init(spa, zcb);
3621	spa_config_exit(spa, SCL_CONFIG, FTAG);
3622}
3623
3624static boolean_t
3625zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
3626{
3627	boolean_t leaks = B_FALSE;
3628	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3629	uint64_t total_leaked = 0;
3630
3631	ASSERT(vim != NULL);
3632
3633	for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
3634		vdev_indirect_mapping_entry_phys_t *vimep =
3635		    &vim->vim_entries[i];
3636		uint64_t obsolete_bytes = 0;
3637		uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
3638		metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3639
3640		/*
3641		 * This is not very efficient but it's easy to
3642		 * verify correctness.
3643		 */
3644		for (uint64_t inner_offset = 0;
3645		    inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
3646		    inner_offset += 1 << vd->vdev_ashift) {
3647			if (range_tree_contains(msp->ms_allocatable,
3648			    offset + inner_offset, 1 << vd->vdev_ashift)) {
3649				obsolete_bytes += 1 << vd->vdev_ashift;
3650			}
3651		}
3652
3653		int64_t bytes_leaked = obsolete_bytes -
3654		    zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
3655		ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
3656		    zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
3657		if (bytes_leaked != 0 &&
3658		    (vdev_obsolete_counts_are_precise(vd) ||
3659		    dump_opt['d'] >= 5)) {
3660			(void) printf("obsolete indirect mapping count "
3661			    "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
3662			    (u_longlong_t)vd->vdev_id,
3663			    (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
3664			    (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
3665			    (u_longlong_t)bytes_leaked);
3666		}
3667		total_leaked += ABS(bytes_leaked);
3668	}
3669
3670	if (!vdev_obsolete_counts_are_precise(vd) && total_leaked > 0) {
3671		int pct_leaked = total_leaked * 100 /
3672		    vdev_indirect_mapping_bytes_mapped(vim);
3673		(void) printf("cannot verify obsolete indirect mapping "
3674		    "counts of vdev %llu because precise feature was not "
3675		    "enabled when it was removed: %d%% (%llx bytes) of mapping"
3676		    "unreferenced\n",
3677		    (u_longlong_t)vd->vdev_id, pct_leaked,
3678		    (u_longlong_t)total_leaked);
3679	} else if (total_leaked > 0) {
3680		(void) printf("obsolete indirect mapping count mismatch "
3681		    "for vdev %llu -- %llx total bytes mismatched\n",
3682		    (u_longlong_t)vd->vdev_id,
3683		    (u_longlong_t)total_leaked);
3684		leaks |= B_TRUE;
3685	}
3686
3687	vdev_indirect_mapping_free_obsolete_counts(vim,
3688	    zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
3689	zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
3690
3691	return (leaks);
3692}
3693
3694static boolean_t
3695zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
3696{
3697	if (dump_opt['L'])
3698		return (B_FALSE);
3699
3700	boolean_t leaks = B_FALSE;
3701
3702	vdev_t *rvd = spa->spa_root_vdev;
3703	for (unsigned c = 0; c < rvd->vdev_children; c++) {
3704		vdev_t *vd = rvd->vdev_child[c];
3705#if DEBUG
3706		metaslab_group_t *mg = vd->vdev_mg;
3707#endif
3708
3709		if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
3710			leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
3711		}
3712
3713		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3714			metaslab_t *msp = vd->vdev_ms[m];
3715			ASSERT3P(mg, ==, msp->ms_group);
3716
3717			/*
3718			 * ms_allocatable has been overloaded
3719			 * to contain allocated segments. Now that
3720			 * we finished traversing all blocks, any
3721			 * block that remains in the ms_allocatable
3722			 * represents an allocated block that we
3723			 * did not claim during the traversal.
3724			 * Claimed blocks would have been removed
3725			 * from the ms_allocatable.  For indirect
3726			 * vdevs, space remaining in the tree
3727			 * represents parts of the mapping that are
3728			 * not referenced, which is not a bug.
3729			 */
3730			if (vd->vdev_ops == &vdev_indirect_ops) {
3731				range_tree_vacate(msp->ms_allocatable,
3732				    NULL, NULL);
3733			} else {
3734				range_tree_vacate(msp->ms_allocatable,
3735				    zdb_leak, vd);
3736			}
3737
3738			if (msp->ms_loaded) {
3739				msp->ms_loaded = B_FALSE;
3740			}
3741		}
3742
3743	}
3744
3745	umem_free(zcb->zcb_vd_obsolete_counts,
3746	    rvd->vdev_children * sizeof (uint32_t *));
3747	zcb->zcb_vd_obsolete_counts = NULL;
3748
3749	return (leaks);
3750}
3751
3752/* ARGSUSED */
3753static int
3754count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3755{
3756	zdb_cb_t *zcb = arg;
3757
3758	if (dump_opt['b'] >= 5) {
3759		char blkbuf[BP_SPRINTF_LEN];
3760		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3761		(void) printf("[%s] %s\n",
3762		    "deferred free", blkbuf);
3763	}
3764	zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
3765	return (0);
3766}
3767
3768static int
3769dump_block_stats(spa_t *spa)
3770{
3771	zdb_cb_t zcb;
3772	zdb_blkstats_t *zb, *tzb;
3773	uint64_t norm_alloc, norm_space, total_alloc, total_found;
3774	int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA | TRAVERSE_HARD;
3775	boolean_t leaks = B_FALSE;
3776	int err;
3777
3778	bzero(&zcb, sizeof (zcb));
3779	(void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
3780	    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
3781	    (dump_opt['c'] == 1) ? "metadata " : "",
3782	    dump_opt['c'] ? "checksums " : "",
3783	    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
3784	    !dump_opt['L'] ? "nothing leaked " : "");
3785
3786	/*
3787	 * When leak detection is enabled we load all space maps as SM_ALLOC
3788	 * maps, then traverse the pool claiming each block we discover. If
3789	 * the pool is perfectly consistent, the segment trees will be empty
3790	 * when we're done. Anything left over is a leak; any block we can't
3791	 * claim (because it's not part of any space map) is a double
3792	 * allocation, reference to a freed block, or an unclaimed log block.
3793	 *
3794	 * When leak detection is disabled (-L option) we still traverse the
3795	 * pool claiming each block we discover, but we skip opening any space
3796	 * maps.
3797	 */
3798	bzero(&zcb, sizeof (zdb_cb_t));
3799	zdb_leak_init(spa, &zcb);
3800
3801	/*
3802	 * If there's a deferred-free bplist, process that first.
3803	 */
3804	(void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
3805	    count_block_cb, &zcb, NULL);
3806
3807	if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
3808		(void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
3809		    count_block_cb, &zcb, NULL);
3810	}
3811
3812	zdb_claim_removing(spa, &zcb);
3813
3814	if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
3815		VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
3816		    spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
3817		    &zcb, NULL));
3818	}
3819
3820	if (dump_opt['c'] > 1)
3821		flags |= TRAVERSE_PREFETCH_DATA;
3822
3823	zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
3824	zcb.zcb_totalasize += metaslab_class_get_alloc(spa_special_class(spa));
3825	zcb.zcb_totalasize += metaslab_class_get_alloc(spa_dedup_class(spa));
3826	zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
3827	err = traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
3828
3829	/*
3830	 * If we've traversed the data blocks then we need to wait for those
3831	 * I/Os to complete. We leverage "The Godfather" zio to wait on
3832	 * all async I/Os to complete.
3833	 */
3834	if (dump_opt['c']) {
3835		for (int i = 0; i < max_ncpus; i++) {
3836			(void) zio_wait(spa->spa_async_zio_root[i]);
3837			spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
3838			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
3839			    ZIO_FLAG_GODFATHER);
3840		}
3841	}
3842
3843	/*
3844	 * Done after zio_wait() since zcb_haderrors is modified in
3845	 * zdb_blkptr_done()
3846	 */
3847	zcb.zcb_haderrors |= err;
3848
3849	if (zcb.zcb_haderrors) {
3850		(void) printf("\nError counts:\n\n");
3851		(void) printf("\t%5s  %s\n", "errno", "count");
3852		for (int e = 0; e < 256; e++) {
3853			if (zcb.zcb_errors[e] != 0) {
3854				(void) printf("\t%5d  %llu\n",
3855				    e, (u_longlong_t)zcb.zcb_errors[e]);
3856			}
3857		}
3858	}
3859
3860	/*
3861	 * Report any leaked segments.
3862	 */
3863	leaks |= zdb_leak_fini(spa, &zcb);
3864
3865	tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
3866
3867	norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
3868	norm_space = metaslab_class_get_space(spa_normal_class(spa));
3869
3870	total_alloc = norm_alloc +
3871	    metaslab_class_get_alloc(spa_log_class(spa)) +
3872	    metaslab_class_get_alloc(spa_special_class(spa)) +
3873	    metaslab_class_get_alloc(spa_dedup_class(spa));
3874	total_found = tzb->zb_asize - zcb.zcb_dedup_asize +
3875	    zcb.zcb_removing_size + zcb.zcb_checkpoint_size;
3876
3877	if (total_found == total_alloc && !dump_opt['L']) {
3878		(void) printf("\n\tNo leaks (block sum matches space"
3879		    " maps exactly)\n");
3880	} else if (!dump_opt['L']) {
3881		(void) printf("block traversal size %llu != alloc %llu "
3882		    "(%s %lld)\n",
3883		    (u_longlong_t)total_found,
3884		    (u_longlong_t)total_alloc,
3885		    (dump_opt['L']) ? "unreachable" : "leaked",
3886		    (longlong_t)(total_alloc - total_found));
3887		leaks = B_TRUE;
3888	}
3889
3890	if (tzb->zb_count == 0)
3891		return (2);
3892
3893	(void) printf("\n");
3894	(void) printf("\t%-16s %14llu\n", "bp count:",
3895	    (u_longlong_t)tzb->zb_count);
3896	(void) printf("\t%-16s %14llu\n", "ganged count:",
3897	    (longlong_t)tzb->zb_gangs);
3898	(void) printf("\t%-16s %14llu      avg: %6llu\n", "bp logical:",
3899	    (u_longlong_t)tzb->zb_lsize,
3900	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
3901	(void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
3902	    "bp physical:", (u_longlong_t)tzb->zb_psize,
3903	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
3904	    (double)tzb->zb_lsize / tzb->zb_psize);
3905	(void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
3906	    "bp allocated:", (u_longlong_t)tzb->zb_asize,
3907	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
3908	    (double)tzb->zb_lsize / tzb->zb_asize);
3909	(void) printf("\t%-16s %14llu    ref>1: %6llu   deduplication: %6.2f\n",
3910	    "bp deduped:", (u_longlong_t)zcb.zcb_dedup_asize,
3911	    (u_longlong_t)zcb.zcb_dedup_blocks,
3912	    (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
3913	(void) printf("\t%-16s %14llu     used: %5.2f%%\n", "Normal class:",
3914	    (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
3915
3916	if (spa_special_class(spa)->mc_rotor != NULL) {
3917		uint64_t alloc = metaslab_class_get_alloc(
3918		    spa_special_class(spa));
3919		uint64_t space = metaslab_class_get_space(
3920		    spa_special_class(spa));
3921
3922		(void) printf("\t%-16s %14llu     used: %5.2f%%\n",
3923		    "Special class", (u_longlong_t)alloc,
3924		    100.0 * alloc / space);
3925	}
3926
3927	if (spa_dedup_class(spa)->mc_rotor != NULL) {
3928		uint64_t alloc = metaslab_class_get_alloc(
3929		    spa_dedup_class(spa));
3930		uint64_t space = metaslab_class_get_space(
3931		    spa_dedup_class(spa));
3932
3933		(void) printf("\t%-16s %14llu     used: %5.2f%%\n",
3934		    "Dedup class", (u_longlong_t)alloc,
3935		    100.0 * alloc / space);
3936	}
3937
3938	for (bp_embedded_type_t i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
3939		if (zcb.zcb_embedded_blocks[i] == 0)
3940			continue;
3941		(void) printf("\n");
3942		(void) printf("\tadditional, non-pointer bps of type %u: "
3943		    "%10llu\n",
3944		    i, (u_longlong_t)zcb.zcb_embedded_blocks[i]);
3945
3946		if (dump_opt['b'] >= 3) {
3947			(void) printf("\t number of (compressed) bytes:  "
3948			    "number of bps\n");
3949			dump_histogram(zcb.zcb_embedded_histogram[i],
3950			    sizeof (zcb.zcb_embedded_histogram[i]) /
3951			    sizeof (zcb.zcb_embedded_histogram[i][0]), 0);
3952		}
3953	}
3954
3955	if (tzb->zb_ditto_samevdev != 0) {
3956		(void) printf("\tDittoed blocks on same vdev: %llu\n",
3957		    (longlong_t)tzb->zb_ditto_samevdev);
3958	}
3959	if (tzb->zb_ditto_same_ms != 0) {
3960		(void) printf("\tDittoed blocks in same metaslab: %llu\n",
3961		    (longlong_t)tzb->zb_ditto_same_ms);
3962	}
3963
3964	for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
3965		vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
3966		vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3967
3968		if (vim == NULL) {
3969			continue;
3970		}
3971
3972		char mem[32];
3973		zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
3974		    mem, vdev_indirect_mapping_size(vim));
3975
3976		(void) printf("\tindirect vdev id %llu has %llu segments "
3977		    "(%s in memory)\n",
3978		    (longlong_t)vd->vdev_id,
3979		    (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
3980	}
3981
3982	if (dump_opt['b'] >= 2) {
3983		int l, t, level;
3984		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
3985		    "\t  avg\t comp\t%%Total\tType\n");
3986
3987		for (t = 0; t <= ZDB_OT_TOTAL; t++) {
3988			char csize[32], lsize[32], psize[32], asize[32];
3989			char avg[32], gang[32];
3990			const char *typename;
3991
3992			/* make sure nicenum has enough space */
3993			CTASSERT(sizeof (csize) >= NN_NUMBUF_SZ);
3994			CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
3995			CTASSERT(sizeof (psize) >= NN_NUMBUF_SZ);
3996			CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
3997			CTASSERT(sizeof (avg) >= NN_NUMBUF_SZ);
3998			CTASSERT(sizeof (gang) >= NN_NUMBUF_SZ);
3999
4000			if (t < DMU_OT_NUMTYPES)
4001				typename = dmu_ot[t].ot_name;
4002			else
4003				typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
4004
4005			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
4006				(void) printf("%6s\t%5s\t%5s\t%5s"
4007				    "\t%5s\t%5s\t%6s\t%s\n",
4008				    "-",
4009				    "-",
4010				    "-",
4011				    "-",
4012				    "-",
4013				    "-",
4014				    "-",
4015				    typename);
4016				continue;
4017			}
4018
4019			for (l = ZB_TOTAL - 1; l >= -1; l--) {
4020				level = (l == -1 ? ZB_TOTAL : l);
4021				zb = &zcb.zcb_type[level][t];
4022
4023				if (zb->zb_asize == 0)
4024					continue;
4025
4026				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
4027					continue;
4028
4029				if (level == 0 && zb->zb_asize ==
4030				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
4031					continue;
4032
4033				zdb_nicenum(zb->zb_count, csize,
4034				    sizeof (csize));
4035				zdb_nicenum(zb->zb_lsize, lsize,
4036				    sizeof (lsize));
4037				zdb_nicenum(zb->zb_psize, psize,
4038				    sizeof (psize));
4039				zdb_nicenum(zb->zb_asize, asize,
4040				    sizeof (asize));
4041				zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
4042				    sizeof (avg));
4043				zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
4044
4045				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
4046				    "\t%5.2f\t%6.2f\t",
4047				    csize, lsize, psize, asize, avg,
4048				    (double)zb->zb_lsize / zb->zb_psize,
4049				    100.0 * zb->zb_asize / tzb->zb_asize);
4050
4051				if (level == ZB_TOTAL)
4052					(void) printf("%s\n", typename);
4053				else
4054					(void) printf("    L%d %s\n",
4055					    level, typename);
4056
4057				if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
4058					(void) printf("\t number of ganged "
4059					    "blocks: %s\n", gang);
4060				}
4061
4062				if (dump_opt['b'] >= 4) {
4063					(void) printf("psize "
4064					    "(in 512-byte sectors): "
4065					    "number of blocks\n");
4066					dump_histogram(zb->zb_psize_histogram,
4067					    PSIZE_HISTO_SIZE, 0);
4068				}
4069			}
4070		}
4071	}
4072
4073	(void) printf("\n");
4074
4075	if (leaks)
4076		return (2);
4077
4078	if (zcb.zcb_haderrors)
4079		return (3);
4080
4081	return (0);
4082}
4083
4084typedef struct zdb_ddt_entry {
4085	ddt_key_t	zdde_key;
4086	uint64_t	zdde_ref_blocks;
4087	uint64_t	zdde_ref_lsize;
4088	uint64_t	zdde_ref_psize;
4089	uint64_t	zdde_ref_dsize;
4090	avl_node_t	zdde_node;
4091} zdb_ddt_entry_t;
4092
4093/* ARGSUSED */
4094static int
4095zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
4096    const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
4097{
4098	avl_tree_t *t = arg;
4099	avl_index_t where;
4100	zdb_ddt_entry_t *zdde, zdde_search;
4101
4102	if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
4103		return (0);
4104
4105	if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
4106		(void) printf("traversing objset %llu, %llu objects, "
4107		    "%lu blocks so far\n",
4108		    (u_longlong_t)zb->zb_objset,
4109		    (u_longlong_t)BP_GET_FILL(bp),
4110		    avl_numnodes(t));
4111	}
4112
4113	if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
4114	    BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
4115		return (0);
4116
4117	ddt_key_fill(&zdde_search.zdde_key, bp);
4118
4119	zdde = avl_find(t, &zdde_search, &where);
4120
4121	if (zdde == NULL) {
4122		zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
4123		zdde->zdde_key = zdde_search.zdde_key;
4124		avl_insert(t, zdde, where);
4125	}
4126
4127	zdde->zdde_ref_blocks += 1;
4128	zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
4129	zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
4130	zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
4131
4132	return (0);
4133}
4134
4135static void
4136dump_simulated_ddt(spa_t *spa)
4137{
4138	avl_tree_t t;
4139	void *cookie = NULL;
4140	zdb_ddt_entry_t *zdde;
4141	ddt_histogram_t ddh_total;
4142	ddt_stat_t dds_total;
4143
4144	bzero(&ddh_total, sizeof (ddh_total));
4145	bzero(&dds_total, sizeof (dds_total));
4146	avl_create(&t, ddt_entry_compare,
4147	    sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
4148
4149	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4150
4151	(void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
4152	    zdb_ddt_add_cb, &t);
4153
4154	spa_config_exit(spa, SCL_CONFIG, FTAG);
4155
4156	while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
4157		ddt_stat_t dds;
4158		uint64_t refcnt = zdde->zdde_ref_blocks;
4159		ASSERT(refcnt != 0);
4160
4161		dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
4162		dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
4163		dds.dds_psize = zdde->zdde_ref_psize / refcnt;
4164		dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
4165
4166		dds.dds_ref_blocks = zdde->zdde_ref_blocks;
4167		dds.dds_ref_lsize = zdde->zdde_ref_lsize;
4168		dds.dds_ref_psize = zdde->zdde_ref_psize;
4169		dds.dds_ref_dsize = zdde->zdde_ref_dsize;
4170
4171		ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
4172		    &dds, 0);
4173
4174		umem_free(zdde, sizeof (*zdde));
4175	}
4176
4177	avl_destroy(&t);
4178
4179	ddt_histogram_stat(&dds_total, &ddh_total);
4180
4181	(void) printf("Simulated DDT histogram:\n");
4182
4183	zpool_dump_ddt(&dds_total, &ddh_total);
4184
4185	dump_dedup_ratio(&dds_total);
4186}
4187
4188static int
4189verify_device_removal_feature_counts(spa_t *spa)
4190{
4191	uint64_t dr_feature_refcount = 0;
4192	uint64_t oc_feature_refcount = 0;
4193	uint64_t indirect_vdev_count = 0;
4194	uint64_t precise_vdev_count = 0;
4195	uint64_t obsolete_counts_object_count = 0;
4196	uint64_t obsolete_sm_count = 0;
4197	uint64_t obsolete_counts_count = 0;
4198	uint64_t scip_count = 0;
4199	uint64_t obsolete_bpobj_count = 0;
4200	int ret = 0;
4201
4202	spa_condensing_indirect_phys_t *scip =
4203	    &spa->spa_condensing_indirect_phys;
4204	if (scip->scip_next_mapping_object != 0) {
4205		vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
4206		ASSERT(scip->scip_prev_obsolete_sm_object != 0);
4207		ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
4208
4209		(void) printf("Condensing indirect vdev %llu: new mapping "
4210		    "object %llu, prev obsolete sm %llu\n",
4211		    (u_longlong_t)scip->scip_vdev,
4212		    (u_longlong_t)scip->scip_next_mapping_object,
4213		    (u_longlong_t)scip->scip_prev_obsolete_sm_object);
4214		if (scip->scip_prev_obsolete_sm_object != 0) {
4215			space_map_t *prev_obsolete_sm = NULL;
4216			VERIFY0(space_map_open(&prev_obsolete_sm,
4217			    spa->spa_meta_objset,
4218			    scip->scip_prev_obsolete_sm_object,
4219			    0, vd->vdev_asize, 0));
4220			dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
4221			(void) printf("\n");
4222			space_map_close(prev_obsolete_sm);
4223		}
4224
4225		scip_count += 2;
4226	}
4227
4228	for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
4229		vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
4230		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
4231
4232		if (vic->vic_mapping_object != 0) {
4233			ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
4234			    vd->vdev_removing);
4235			indirect_vdev_count++;
4236
4237			if (vd->vdev_indirect_mapping->vim_havecounts) {
4238				obsolete_counts_count++;
4239			}
4240		}
4241		if (vdev_obsolete_counts_are_precise(vd)) {
4242			ASSERT(vic->vic_mapping_object != 0);
4243			precise_vdev_count++;
4244		}
4245		if (vdev_obsolete_sm_object(vd) != 0) {
4246			ASSERT(vic->vic_mapping_object != 0);
4247			obsolete_sm_count++;
4248		}
4249	}
4250
4251	(void) feature_get_refcount(spa,
4252	    &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
4253	    &dr_feature_refcount);
4254	(void) feature_get_refcount(spa,
4255	    &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
4256	    &oc_feature_refcount);
4257
4258	if (dr_feature_refcount != indirect_vdev_count) {
4259		ret = 1;
4260		(void) printf("Number of indirect vdevs (%llu) " \
4261		    "does not match feature count (%llu)\n",
4262		    (u_longlong_t)indirect_vdev_count,
4263		    (u_longlong_t)dr_feature_refcount);
4264	} else {
4265		(void) printf("Verified device_removal feature refcount " \
4266		    "of %llu is correct\n",
4267		    (u_longlong_t)dr_feature_refcount);
4268	}
4269
4270	if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
4271	    DMU_POOL_OBSOLETE_BPOBJ) == 0) {
4272		obsolete_bpobj_count++;
4273	}
4274
4275
4276	obsolete_counts_object_count = precise_vdev_count;
4277	obsolete_counts_object_count += obsolete_sm_count;
4278	obsolete_counts_object_count += obsolete_counts_count;
4279	obsolete_counts_object_count += scip_count;
4280	obsolete_counts_object_count += obsolete_bpobj_count;
4281	obsolete_counts_object_count += remap_deadlist_count;
4282
4283	if (oc_feature_refcount != obsolete_counts_object_count) {
4284		ret = 1;
4285		(void) printf("Number of obsolete counts objects (%llu) " \
4286		    "does not match feature count (%llu)\n",
4287		    (u_longlong_t)obsolete_counts_object_count,
4288		    (u_longlong_t)oc_feature_refcount);
4289		(void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
4290		    "ob:%llu rd:%llu\n",
4291		    (u_longlong_t)precise_vdev_count,
4292		    (u_longlong_t)obsolete_sm_count,
4293		    (u_longlong_t)obsolete_counts_count,
4294		    (u_longlong_t)scip_count,
4295		    (u_longlong_t)obsolete_bpobj_count,
4296		    (u_longlong_t)remap_deadlist_count);
4297	} else {
4298		(void) printf("Verified indirect_refcount feature refcount " \
4299		    "of %llu is correct\n",
4300		    (u_longlong_t)oc_feature_refcount);
4301	}
4302	return (ret);
4303}
4304
4305static void
4306zdb_set_skip_mmp(char *target)
4307{
4308	spa_t *spa;
4309
4310	/*
4311	 * Disable the activity check to allow examination of
4312	 * active pools.
4313	 */
4314	mutex_enter(&spa_namespace_lock);
4315	if ((spa = spa_lookup(target)) != NULL) {
4316		spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
4317	}
4318	mutex_exit(&spa_namespace_lock);
4319}
4320
4321#define	BOGUS_SUFFIX "_CHECKPOINTED_UNIVERSE"
4322/*
4323 * Import the checkpointed state of the pool specified by the target
4324 * parameter as readonly. The function also accepts a pool config
4325 * as an optional parameter, else it attempts to infer the config by
4326 * the name of the target pool.
4327 *
4328 * Note that the checkpointed state's pool name will be the name of
4329 * the original pool with the above suffix appened to it. In addition,
4330 * if the target is not a pool name (e.g. a path to a dataset) then
4331 * the new_path parameter is populated with the updated path to
4332 * reflect the fact that we are looking into the checkpointed state.
4333 *
4334 * The function returns a newly-allocated copy of the name of the
4335 * pool containing the checkpointed state. When this copy is no
4336 * longer needed it should be freed with free(3C). Same thing
4337 * applies to the new_path parameter if allocated.
4338 */
4339static char *
4340import_checkpointed_state(char *target, nvlist_t *cfg, char **new_path)
4341{
4342	int error = 0;
4343	char *poolname, *bogus_name;
4344
4345	/* If the target is not a pool, the extract the pool name */
4346	char *path_start = strchr(target, '/');
4347	if (path_start != NULL) {
4348		size_t poolname_len = path_start - target;
4349		poolname = strndup(target, poolname_len);
4350	} else {
4351		poolname = target;
4352	}
4353
4354	if (cfg == NULL) {
4355		zdb_set_skip_mmp(poolname);
4356		error = spa_get_stats(poolname, &cfg, NULL, 0);
4357		if (error != 0) {
4358			fatal("Tried to read config of pool \"%s\" but "
4359			    "spa_get_stats() failed with error %d\n",
4360			    poolname, error);
4361		}
4362	}
4363
4364	(void) asprintf(&bogus_name, "%s%s", poolname, BOGUS_SUFFIX);
4365	fnvlist_add_string(cfg, ZPOOL_CONFIG_POOL_NAME, bogus_name);
4366
4367	error = spa_import(bogus_name, cfg, NULL,
4368	    ZFS_IMPORT_MISSING_LOG | ZFS_IMPORT_CHECKPOINT |
4369	    ZFS_IMPORT_SKIP_MMP);
4370	if (error != 0) {
4371		fatal("Tried to import pool \"%s\" but spa_import() failed "
4372		    "with error %d\n", bogus_name, error);
4373	}
4374
4375	if (new_path != NULL && path_start != NULL)
4376		(void) asprintf(new_path, "%s%s", bogus_name, path_start);
4377
4378	if (target != poolname)
4379		free(poolname);
4380
4381	return (bogus_name);
4382}
4383
4384typedef struct verify_checkpoint_sm_entry_cb_arg {
4385	vdev_t *vcsec_vd;
4386
4387	/* the following fields are only used for printing progress */
4388	uint64_t vcsec_entryid;
4389	uint64_t vcsec_num_entries;
4390} verify_checkpoint_sm_entry_cb_arg_t;
4391
4392#define	ENTRIES_PER_PROGRESS_UPDATE 10000
4393
4394static int
4395verify_checkpoint_sm_entry_cb(space_map_entry_t *sme, void *arg)
4396{
4397	verify_checkpoint_sm_entry_cb_arg_t *vcsec = arg;
4398	vdev_t *vd = vcsec->vcsec_vd;
4399	metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
4400	uint64_t end = sme->sme_offset + sme->sme_run;
4401
4402	ASSERT(sme->sme_type == SM_FREE);
4403
4404	if ((vcsec->vcsec_entryid % ENTRIES_PER_PROGRESS_UPDATE) == 0) {
4405		(void) fprintf(stderr,
4406		    "\rverifying vdev %llu, space map entry %llu of %llu ...",
4407		    (longlong_t)vd->vdev_id,
4408		    (longlong_t)vcsec->vcsec_entryid,
4409		    (longlong_t)vcsec->vcsec_num_entries);
4410	}
4411	vcsec->vcsec_entryid++;
4412
4413	/*
4414	 * See comment in checkpoint_sm_exclude_entry_cb()
4415	 */
4416	VERIFY3U(sme->sme_offset, >=, ms->ms_start);
4417	VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
4418
4419	/*
4420	 * The entries in the vdev_checkpoint_sm should be marked as
4421	 * allocated in the checkpointed state of the pool, therefore
4422	 * their respective ms_allocateable trees should not contain them.
4423	 */
4424	mutex_enter(&ms->ms_lock);
4425	range_tree_verify_not_present(ms->ms_allocatable,
4426	    sme->sme_offset, sme->sme_run);
4427	mutex_exit(&ms->ms_lock);
4428
4429	return (0);
4430}
4431
4432/*
4433 * Verify that all segments in the vdev_checkpoint_sm are allocated
4434 * according to the checkpoint's ms_sm (i.e. are not in the checkpoint's
4435 * ms_allocatable).
4436 *
4437 * Do so by comparing the checkpoint space maps (vdev_checkpoint_sm) of
4438 * each vdev in the current state of the pool to the metaslab space maps
4439 * (ms_sm) of the checkpointed state of the pool.
4440 *
4441 * Note that the function changes the state of the ms_allocatable
4442 * trees of the current spa_t. The entries of these ms_allocatable
4443 * trees are cleared out and then repopulated from with the free
4444 * entries of their respective ms_sm space maps.
4445 */
4446static void
4447verify_checkpoint_vdev_spacemaps(spa_t *checkpoint, spa_t *current)
4448{
4449	vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
4450	vdev_t *current_rvd = current->spa_root_vdev;
4451
4452	load_concrete_ms_allocatable_trees(checkpoint, SM_FREE);
4453
4454	for (uint64_t c = 0; c < ckpoint_rvd->vdev_children; c++) {
4455		vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[c];
4456		vdev_t *current_vd = current_rvd->vdev_child[c];
4457
4458		space_map_t *checkpoint_sm = NULL;
4459		uint64_t checkpoint_sm_obj;
4460
4461		if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
4462			/*
4463			 * Since we don't allow device removal in a pool
4464			 * that has a checkpoint, we expect that all removed
4465			 * vdevs were removed from the pool before the
4466			 * checkpoint.
4467			 */
4468			ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
4469			continue;
4470		}
4471
4472		/*
4473		 * If the checkpoint space map doesn't exist, then nothing
4474		 * here is checkpointed so there's nothing to verify.
4475		 */
4476		if (current_vd->vdev_top_zap == 0 ||
4477		    zap_contains(spa_meta_objset(current),
4478		    current_vd->vdev_top_zap,
4479		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
4480			continue;
4481
4482		VERIFY0(zap_lookup(spa_meta_objset(current),
4483		    current_vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
4484		    sizeof (uint64_t), 1, &checkpoint_sm_obj));
4485
4486		VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(current),
4487		    checkpoint_sm_obj, 0, current_vd->vdev_asize,
4488		    current_vd->vdev_ashift));
4489
4490		verify_checkpoint_sm_entry_cb_arg_t vcsec;
4491		vcsec.vcsec_vd = ckpoint_vd;
4492		vcsec.vcsec_entryid = 0;
4493		vcsec.vcsec_num_entries =
4494		    space_map_length(checkpoint_sm) / sizeof (uint64_t);
4495		VERIFY0(space_map_iterate(checkpoint_sm,
4496		    space_map_length(checkpoint_sm),
4497		    verify_checkpoint_sm_entry_cb, &vcsec));
4498		dump_spacemap(current->spa_meta_objset, checkpoint_sm);
4499		space_map_close(checkpoint_sm);
4500	}
4501
4502	/*
4503	 * If we've added vdevs since we took the checkpoint, ensure
4504	 * that their checkpoint space maps are empty.
4505	 */
4506	if (ckpoint_rvd->vdev_children < current_rvd->vdev_children) {
4507		for (uint64_t c = ckpoint_rvd->vdev_children;
4508		    c < current_rvd->vdev_children; c++) {
4509			vdev_t *current_vd = current_rvd->vdev_child[c];
4510			ASSERT3P(current_vd->vdev_checkpoint_sm, ==, NULL);
4511		}
4512	}
4513
4514	/* for cleaner progress output */
4515	(void) fprintf(stderr, "\n");
4516}
4517
4518/*
4519 * Verifies that all space that's allocated in the checkpoint is
4520 * still allocated in the current version, by checking that everything
4521 * in checkpoint's ms_allocatable (which is actually allocated, not
4522 * allocatable/free) is not present in current's ms_allocatable.
4523 *
4524 * Note that the function changes the state of the ms_allocatable
4525 * trees of both spas when called. The entries of all ms_allocatable
4526 * trees are cleared out and then repopulated from their respective
4527 * ms_sm space maps. In the checkpointed state we load the allocated
4528 * entries, and in the current state we load the free entries.
4529 */
4530static void
4531verify_checkpoint_ms_spacemaps(spa_t *checkpoint, spa_t *current)
4532{
4533	vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
4534	vdev_t *current_rvd = current->spa_root_vdev;
4535
4536	load_concrete_ms_allocatable_trees(checkpoint, SM_ALLOC);
4537	load_concrete_ms_allocatable_trees(current, SM_FREE);
4538
4539	for (uint64_t i = 0; i < ckpoint_rvd->vdev_children; i++) {
4540		vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[i];
4541		vdev_t *current_vd = current_rvd->vdev_child[i];
4542
4543		if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
4544			/*
4545			 * See comment in verify_checkpoint_vdev_spacemaps()
4546			 */
4547			ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
4548			continue;
4549		}
4550
4551		for (uint64_t m = 0; m < ckpoint_vd->vdev_ms_count; m++) {
4552			metaslab_t *ckpoint_msp = ckpoint_vd->vdev_ms[m];
4553			metaslab_t *current_msp = current_vd->vdev_ms[m];
4554
4555			(void) fprintf(stderr,
4556			    "\rverifying vdev %llu of %llu, "
4557			    "metaslab %llu of %llu ...",
4558			    (longlong_t)current_vd->vdev_id,
4559			    (longlong_t)current_rvd->vdev_children,
4560			    (longlong_t)current_vd->vdev_ms[m]->ms_id,
4561			    (longlong_t)current_vd->vdev_ms_count);
4562
4563			/*
4564			 * We walk through the ms_allocatable trees that
4565			 * are loaded with the allocated blocks from the
4566			 * ms_sm spacemaps of the checkpoint. For each
4567			 * one of these ranges we ensure that none of them
4568			 * exists in the ms_allocatable trees of the
4569			 * current state which are loaded with the ranges
4570			 * that are currently free.
4571			 *
4572			 * This way we ensure that none of the blocks that
4573			 * are part of the checkpoint were freed by mistake.
4574			 */
4575			range_tree_walk(ckpoint_msp->ms_allocatable,
4576			    (range_tree_func_t *)range_tree_verify_not_present,
4577			    current_msp->ms_allocatable);
4578		}
4579	}
4580
4581	/* for cleaner progress output */
4582	(void) fprintf(stderr, "\n");
4583}
4584
4585static void
4586verify_checkpoint_blocks(spa_t *spa)
4587{
4588	ASSERT(!dump_opt['L']);
4589
4590	spa_t *checkpoint_spa;
4591	char *checkpoint_pool;
4592	nvlist_t *config = NULL;
4593	int error = 0;
4594
4595	/*
4596	 * We import the checkpointed state of the pool (under a different
4597	 * name) so we can do verification on it against the current state
4598	 * of the pool.
4599	 */
4600	checkpoint_pool = import_checkpointed_state(spa->spa_name, config,
4601	    NULL);
4602	ASSERT(strcmp(spa->spa_name, checkpoint_pool) != 0);
4603
4604	error = spa_open(checkpoint_pool, &checkpoint_spa, FTAG);
4605	if (error != 0) {
4606		fatal("Tried to open pool \"%s\" but spa_open() failed with "
4607		    "error %d\n", checkpoint_pool, error);
4608	}
4609
4610	/*
4611	 * Ensure that ranges in the checkpoint space maps of each vdev
4612	 * are allocated according to the checkpointed state's metaslab
4613	 * space maps.
4614	 */
4615	verify_checkpoint_vdev_spacemaps(checkpoint_spa, spa);
4616
4617	/*
4618	 * Ensure that allocated ranges in the checkpoint's metaslab
4619	 * space maps remain allocated in the metaslab space maps of
4620	 * the current state.
4621	 */
4622	verify_checkpoint_ms_spacemaps(checkpoint_spa, spa);
4623
4624	/*
4625	 * Once we are done, we get rid of the checkpointed state.
4626	 */
4627	spa_close(checkpoint_spa, FTAG);
4628	free(checkpoint_pool);
4629}
4630
4631static void
4632dump_leftover_checkpoint_blocks(spa_t *spa)
4633{
4634	vdev_t *rvd = spa->spa_root_vdev;
4635
4636	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
4637		vdev_t *vd = rvd->vdev_child[i];
4638
4639		space_map_t *checkpoint_sm = NULL;
4640		uint64_t checkpoint_sm_obj;
4641
4642		if (vd->vdev_top_zap == 0)
4643			continue;
4644
4645		if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
4646		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
4647			continue;
4648
4649		VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
4650		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
4651		    sizeof (uint64_t), 1, &checkpoint_sm_obj));
4652
4653		VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
4654		    checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
4655		dump_spacemap(spa->spa_meta_objset, checkpoint_sm);
4656		space_map_close(checkpoint_sm);
4657	}
4658}
4659
4660static int
4661verify_checkpoint(spa_t *spa)
4662{
4663	uberblock_t checkpoint;
4664	int error;
4665
4666	if (!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT))
4667		return (0);
4668
4669	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
4670	    DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
4671	    sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
4672
4673	if (error == ENOENT && !dump_opt['L']) {
4674		/*
4675		 * If the feature is active but the uberblock is missing
4676		 * then we must be in the middle of discarding the
4677		 * checkpoint.
4678		 */
4679		(void) printf("\nPartially discarded checkpoint "
4680		    "state found:\n");
4681		dump_leftover_checkpoint_blocks(spa);
4682		return (0);
4683	} else if (error != 0) {
4684		(void) printf("lookup error %d when looking for "
4685		    "checkpointed uberblock in MOS\n", error);
4686		return (error);
4687	}
4688	dump_uberblock(&checkpoint, "\nCheckpointed uberblock found:\n", "\n");
4689
4690	if (checkpoint.ub_checkpoint_txg == 0) {
4691		(void) printf("\nub_checkpoint_txg not set in checkpointed "
4692		    "uberblock\n");
4693		error = 3;
4694	}
4695
4696	if (error == 0 && !dump_opt['L'])
4697		verify_checkpoint_blocks(spa);
4698
4699	return (error);
4700}
4701
4702/* ARGSUSED */
4703static void
4704mos_leaks_cb(void *arg, uint64_t start, uint64_t size)
4705{
4706	for (uint64_t i = start; i < size; i++) {
4707		(void) printf("MOS object %llu referenced but not allocated\n",
4708		    (u_longlong_t)i);
4709	}
4710}
4711
4712static range_tree_t *mos_refd_objs;
4713
4714static void
4715mos_obj_refd(uint64_t obj)
4716{
4717	if (obj != 0 && mos_refd_objs != NULL)
4718		range_tree_add(mos_refd_objs, obj, 1);
4719}
4720
4721static void
4722mos_leak_vdev(vdev_t *vd)
4723{
4724	mos_obj_refd(vd->vdev_dtl_object);
4725	mos_obj_refd(vd->vdev_ms_array);
4726	mos_obj_refd(vd->vdev_top_zap);
4727	mos_obj_refd(vd->vdev_indirect_config.vic_births_object);
4728	mos_obj_refd(vd->vdev_indirect_config.vic_mapping_object);
4729	mos_obj_refd(vd->vdev_leaf_zap);
4730	if (vd->vdev_checkpoint_sm != NULL)
4731		mos_obj_refd(vd->vdev_checkpoint_sm->sm_object);
4732	if (vd->vdev_indirect_mapping != NULL) {
4733		mos_obj_refd(vd->vdev_indirect_mapping->
4734		    vim_phys->vimp_counts_object);
4735	}
4736	if (vd->vdev_obsolete_sm != NULL)
4737		mos_obj_refd(vd->vdev_obsolete_sm->sm_object);
4738
4739	for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
4740		metaslab_t *ms = vd->vdev_ms[m];
4741		mos_obj_refd(space_map_object(ms->ms_sm));
4742	}
4743
4744	for (uint64_t c = 0; c < vd->vdev_children; c++) {
4745		mos_leak_vdev(vd->vdev_child[c]);
4746	}
4747}
4748
4749static int
4750dump_mos_leaks(spa_t *spa)
4751{
4752	int rv = 0;
4753	objset_t *mos = spa->spa_meta_objset;
4754	dsl_pool_t *dp = spa->spa_dsl_pool;
4755
4756	/* Visit and mark all referenced objects in the MOS */
4757
4758	mos_obj_refd(DMU_POOL_DIRECTORY_OBJECT);
4759	mos_obj_refd(spa->spa_pool_props_object);
4760	mos_obj_refd(spa->spa_config_object);
4761	mos_obj_refd(spa->spa_ddt_stat_object);
4762	mos_obj_refd(spa->spa_feat_desc_obj);
4763	mos_obj_refd(spa->spa_feat_enabled_txg_obj);
4764	mos_obj_refd(spa->spa_feat_for_read_obj);
4765	mos_obj_refd(spa->spa_feat_for_write_obj);
4766	mos_obj_refd(spa->spa_history);
4767	mos_obj_refd(spa->spa_errlog_last);
4768	mos_obj_refd(spa->spa_errlog_scrub);
4769	mos_obj_refd(spa->spa_all_vdev_zaps);
4770	mos_obj_refd(spa->spa_dsl_pool->dp_bptree_obj);
4771	mos_obj_refd(spa->spa_dsl_pool->dp_tmp_userrefs_obj);
4772	mos_obj_refd(spa->spa_dsl_pool->dp_scan->scn_phys.scn_queue_obj);
4773	bpobj_count_refd(&spa->spa_deferred_bpobj);
4774	mos_obj_refd(dp->dp_empty_bpobj);
4775	bpobj_count_refd(&dp->dp_obsolete_bpobj);
4776	bpobj_count_refd(&dp->dp_free_bpobj);
4777	mos_obj_refd(spa->spa_l2cache.sav_object);
4778	mos_obj_refd(spa->spa_spares.sav_object);
4779
4780	mos_obj_refd(spa->spa_condensing_indirect_phys.
4781	    scip_next_mapping_object);
4782	mos_obj_refd(spa->spa_condensing_indirect_phys.
4783	    scip_prev_obsolete_sm_object);
4784	if (spa->spa_condensing_indirect_phys.scip_next_mapping_object != 0) {
4785		vdev_indirect_mapping_t *vim =
4786		    vdev_indirect_mapping_open(mos,
4787		    spa->spa_condensing_indirect_phys.scip_next_mapping_object);
4788		mos_obj_refd(vim->vim_phys->vimp_counts_object);
4789		vdev_indirect_mapping_close(vim);
4790	}
4791
4792	if (dp->dp_origin_snap != NULL) {
4793		dsl_dataset_t *ds;
4794
4795		dsl_pool_config_enter(dp, FTAG);
4796		VERIFY0(dsl_dataset_hold_obj(dp,
4797		    dsl_dataset_phys(dp->dp_origin_snap)->ds_next_snap_obj,
4798		    FTAG, &ds));
4799		count_ds_mos_objects(ds);
4800		dump_deadlist(&ds->ds_deadlist);
4801		dsl_dataset_rele(ds, FTAG);
4802		dsl_pool_config_exit(dp, FTAG);
4803
4804		count_ds_mos_objects(dp->dp_origin_snap);
4805		dump_deadlist(&dp->dp_origin_snap->ds_deadlist);
4806	}
4807	count_dir_mos_objects(dp->dp_mos_dir);
4808	if (dp->dp_free_dir != NULL)
4809		count_dir_mos_objects(dp->dp_free_dir);
4810	if (dp->dp_leak_dir != NULL)
4811		count_dir_mos_objects(dp->dp_leak_dir);
4812
4813	mos_leak_vdev(spa->spa_root_vdev);
4814
4815	for (uint64_t class = 0; class < DDT_CLASSES; class++) {
4816		for (uint64_t type = 0; type < DDT_TYPES; type++) {
4817			for (uint64_t cksum = 0;
4818			    cksum < ZIO_CHECKSUM_FUNCTIONS; cksum++) {
4819				ddt_t *ddt = spa->spa_ddt[cksum];
4820				mos_obj_refd(ddt->ddt_object[type][class]);
4821			}
4822		}
4823	}
4824
4825	/*
4826	 * Visit all allocated objects and make sure they are referenced.
4827	 */
4828	uint64_t object = 0;
4829	while (dmu_object_next(mos, &object, B_FALSE, 0) == 0) {
4830		if (range_tree_contains(mos_refd_objs, object, 1)) {
4831			range_tree_remove(mos_refd_objs, object, 1);
4832		} else {
4833			dmu_object_info_t doi;
4834			const char *name;
4835			dmu_object_info(mos, object, &doi);
4836			if (doi.doi_type & DMU_OT_NEWTYPE) {
4837				dmu_object_byteswap_t bswap =
4838				    DMU_OT_BYTESWAP(doi.doi_type);
4839				name = dmu_ot_byteswap[bswap].ob_name;
4840			} else {
4841				name = dmu_ot[doi.doi_type].ot_name;
4842			}
4843
4844			(void) printf("MOS object %llu (%s) leaked\n",
4845			    (u_longlong_t)object, name);
4846			rv = 2;
4847		}
4848	}
4849	(void) range_tree_walk(mos_refd_objs, mos_leaks_cb, NULL);
4850	if (!range_tree_is_empty(mos_refd_objs))
4851		rv = 2;
4852	range_tree_vacate(mos_refd_objs, NULL, NULL);
4853	range_tree_destroy(mos_refd_objs);
4854	return (rv);
4855}
4856
4857static void
4858dump_zpool(spa_t *spa)
4859{
4860	dsl_pool_t *dp = spa_get_dsl(spa);
4861	int rc = 0;
4862
4863	if (dump_opt['S']) {
4864		dump_simulated_ddt(spa);
4865		return;
4866	}
4867
4868	if (!dump_opt['e'] && dump_opt['C'] > 1) {
4869		(void) printf("\nCached configuration:\n");
4870		dump_nvlist(spa->spa_config, 8);
4871	}
4872
4873	if (dump_opt['C'])
4874		dump_config(spa);
4875
4876	if (dump_opt['u'])
4877		dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
4878
4879	if (dump_opt['D'])
4880		dump_all_ddts(spa);
4881
4882	if (dump_opt['d'] > 2 || dump_opt['m'])
4883		dump_metaslabs(spa);
4884	if (dump_opt['M'])
4885		dump_metaslab_groups(spa);
4886
4887	if (dump_opt['d'] || dump_opt['i']) {
4888		mos_refd_objs = range_tree_create(NULL, NULL);
4889		dump_dir(dp->dp_meta_objset);
4890
4891		if (dump_opt['d'] >= 3) {
4892			dsl_pool_t *dp = spa->spa_dsl_pool;
4893			dump_full_bpobj(&spa->spa_deferred_bpobj,
4894			    "Deferred frees", 0);
4895			if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
4896				dump_full_bpobj(&dp->dp_free_bpobj,
4897				    "Pool snapshot frees", 0);
4898			}
4899			if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
4900				ASSERT(spa_feature_is_enabled(spa,
4901				    SPA_FEATURE_DEVICE_REMOVAL));
4902				dump_full_bpobj(&dp->dp_obsolete_bpobj,
4903				    "Pool obsolete blocks", 0);
4904			}
4905
4906			if (spa_feature_is_active(spa,
4907			    SPA_FEATURE_ASYNC_DESTROY)) {
4908				dump_bptree(spa->spa_meta_objset,
4909				    dp->dp_bptree_obj,
4910				    "Pool dataset frees");
4911			}
4912			dump_dtl(spa->spa_root_vdev, 0);
4913		}
4914		(void) dmu_objset_find(spa_name(spa), dump_one_dir,
4915		    NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
4916
4917		if (rc == 0 && !dump_opt['L'])
4918			rc = dump_mos_leaks(spa);
4919
4920		for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
4921			uint64_t refcount;
4922
4923			if (!(spa_feature_table[f].fi_flags &
4924			    ZFEATURE_FLAG_PER_DATASET)) {
4925				ASSERT0(dataset_feature_count[f]);
4926				continue;
4927			}
4928			(void) feature_get_refcount(spa,
4929			    &spa_feature_table[f], &refcount);
4930			if (dataset_feature_count[f] != refcount) {
4931				(void) printf("%s feature refcount mismatch: "
4932				    "%lld datasets != %lld refcount\n",
4933				    spa_feature_table[f].fi_uname,
4934				    (longlong_t)dataset_feature_count[f],
4935				    (longlong_t)refcount);
4936				rc = 2;
4937			} else {
4938				(void) printf("Verified %s feature refcount "
4939				    "of %llu is correct\n",
4940				    spa_feature_table[f].fi_uname,
4941				    (longlong_t)refcount);
4942			}
4943		}
4944
4945		if (rc == 0) {
4946			rc = verify_device_removal_feature_counts(spa);
4947		}
4948	}
4949
4950	if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
4951		rc = dump_block_stats(spa);
4952
4953	if (rc == 0)
4954		rc = verify_spacemap_refcounts(spa);
4955
4956	if (dump_opt['s'])
4957		show_pool_stats(spa);
4958
4959	if (dump_opt['h'])
4960		dump_history(spa);
4961
4962	if (rc == 0)
4963		rc = verify_checkpoint(spa);
4964
4965	if (rc != 0) {
4966		dump_debug_buffer();
4967		exit(rc);
4968	}
4969}
4970
4971#define	ZDB_FLAG_CHECKSUM	0x0001
4972#define	ZDB_FLAG_DECOMPRESS	0x0002
4973#define	ZDB_FLAG_BSWAP		0x0004
4974#define	ZDB_FLAG_GBH		0x0008
4975#define	ZDB_FLAG_INDIRECT	0x0010
4976#define	ZDB_FLAG_PHYS		0x0020
4977#define	ZDB_FLAG_RAW		0x0040
4978#define	ZDB_FLAG_PRINT_BLKPTR	0x0080
4979
4980static int flagbits[256];
4981
4982static void
4983zdb_print_blkptr(blkptr_t *bp, int flags)
4984{
4985	char blkbuf[BP_SPRINTF_LEN];
4986
4987	if (flags & ZDB_FLAG_BSWAP)
4988		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
4989
4990	snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
4991	(void) printf("%s\n", blkbuf);
4992}
4993
4994static void
4995zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
4996{
4997	int i;
4998
4999	for (i = 0; i < nbps; i++)
5000		zdb_print_blkptr(&bp[i], flags);
5001}
5002
5003static void
5004zdb_dump_gbh(void *buf, int flags)
5005{
5006	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
5007}
5008
5009static void
5010zdb_dump_block_raw(void *buf, uint64_t size, int flags)
5011{
5012	if (flags & ZDB_FLAG_BSWAP)
5013		byteswap_uint64_array(buf, size);
5014	(void) write(1, buf, size);
5015}
5016
5017static void
5018zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
5019{
5020	uint64_t *d = (uint64_t *)buf;
5021	unsigned nwords = size / sizeof (uint64_t);
5022	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
5023	unsigned i, j;
5024	const char *hdr;
5025	char *c;
5026
5027
5028	if (do_bswap)
5029		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
5030	else
5031		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
5032
5033	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
5034
5035	for (i = 0; i < nwords; i += 2) {
5036		(void) printf("%06llx:  %016llx  %016llx  ",
5037		    (u_longlong_t)(i * sizeof (uint64_t)),
5038		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
5039		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
5040
5041		c = (char *)&d[i];
5042		for (j = 0; j < 2 * sizeof (uint64_t); j++)
5043			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
5044		(void) printf("\n");
5045	}
5046}
5047
5048/*
5049 * There are two acceptable formats:
5050 *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
5051 *	child[.child]*    - For example: 0.1.1
5052 *
5053 * The second form can be used to specify arbitrary vdevs anywhere
5054 * in the heirarchy.  For example, in a pool with a mirror of
5055 * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
5056 */
5057static vdev_t *
5058zdb_vdev_lookup(vdev_t *vdev, const char *path)
5059{
5060	char *s, *p, *q;
5061	unsigned i;
5062
5063	if (vdev == NULL)
5064		return (NULL);
5065
5066	/* First, assume the x.x.x.x format */
5067	i = strtoul(path, &s, 10);
5068	if (s == path || (s && *s != '.' && *s != '\0'))
5069		goto name;
5070	if (i >= vdev->vdev_children)
5071		return (NULL);
5072
5073	vdev = vdev->vdev_child[i];
5074	if (*s == '\0')
5075		return (vdev);
5076	return (zdb_vdev_lookup(vdev, s+1));
5077
5078name:
5079	for (i = 0; i < vdev->vdev_children; i++) {
5080		vdev_t *vc = vdev->vdev_child[i];
5081
5082		if (vc->vdev_path == NULL) {
5083			vc = zdb_vdev_lookup(vc, path);
5084			if (vc == NULL)
5085				continue;
5086			else
5087				return (vc);
5088		}
5089
5090		p = strrchr(vc->vdev_path, '/');
5091		p = p ? p + 1 : vc->vdev_path;
5092		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
5093
5094		if (strcmp(vc->vdev_path, path) == 0)
5095			return (vc);
5096		if (strcmp(p, path) == 0)
5097			return (vc);
5098		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
5099			return (vc);
5100	}
5101
5102	return (NULL);
5103}
5104
5105/* ARGSUSED */
5106static int
5107random_get_pseudo_bytes_cb(void *buf, size_t len, void *unused)
5108{
5109	return (random_get_pseudo_bytes(buf, len));
5110}
5111
5112/*
5113 * Read a block from a pool and print it out.  The syntax of the
5114 * block descriptor is:
5115 *
5116 *	pool:vdev_specifier:offset:size[:flags]
5117 *
5118 *	pool           - The name of the pool you wish to read from
5119 *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
5120 *	offset         - offset, in hex, in bytes
5121 *	size           - Amount of data to read, in hex, in bytes
5122 *	flags          - A string of characters specifying options
5123 *		 b: Decode a blkptr at given offset within block
5124 *		*c: Calculate and display checksums
5125 *		 d: Decompress data before dumping
5126 *		 e: Byteswap data before dumping
5127 *		 g: Display data as a gang block header
5128 *		 i: Display as an indirect block
5129 *		 p: Do I/O to physical offset
5130 *		 r: Dump raw data to stdout
5131 *
5132 *              * = not yet implemented
5133 */
5134static void
5135zdb_read_block(char *thing, spa_t *spa)
5136{
5137	blkptr_t blk, *bp = &blk;
5138	dva_t *dva = bp->blk_dva;
5139	int flags = 0;
5140	uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
5141	zio_t *zio;
5142	vdev_t *vd;
5143	abd_t *pabd;
5144	void *lbuf, *buf;
5145	const char *s, *vdev;
5146	char *p, *dup, *flagstr;
5147	int i, error;
5148
5149	dup = strdup(thing);
5150	s = strtok(dup, ":");
5151	vdev = s ? s : "";
5152	s = strtok(NULL, ":");
5153	offset = strtoull(s ? s : "", NULL, 16);
5154	s = strtok(NULL, ":");
5155	size = strtoull(s ? s : "", NULL, 16);
5156	s = strtok(NULL, ":");
5157	if (s)
5158		flagstr = strdup(s);
5159	else
5160		flagstr = strdup("");
5161
5162	s = NULL;
5163	if (size == 0)
5164		s = "size must not be zero";
5165	if (!IS_P2ALIGNED(size, DEV_BSIZE))
5166		s = "size must be a multiple of sector size";
5167	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
5168		s = "offset must be a multiple of sector size";
5169	if (s) {
5170		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
5171		free(flagstr);
5172		free(dup);
5173		return;
5174	}
5175
5176	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
5177		for (i = 0; flagstr[i]; i++) {
5178			int bit = flagbits[(uchar_t)flagstr[i]];
5179
5180			if (bit == 0) {
5181				(void) printf("***Invalid flag: %c\n",
5182				    flagstr[i]);
5183				continue;
5184			}
5185			flags |= bit;
5186
5187			/* If it's not something with an argument, keep going */
5188			if ((bit & (ZDB_FLAG_CHECKSUM |
5189			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
5190				continue;
5191
5192			p = &flagstr[i + 1];
5193			if (bit == ZDB_FLAG_PRINT_BLKPTR)
5194				blkptr_offset = strtoull(p, &p, 16);
5195			if (*p != ':' && *p != '\0') {
5196				(void) printf("***Invalid flag arg: '%s'\n", s);
5197				free(flagstr);
5198				free(dup);
5199				return;
5200			}
5201			i += p - &flagstr[i + 1]; /* skip over the number */
5202		}
5203	}
5204	free(flagstr);
5205
5206	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
5207	if (vd == NULL) {
5208		(void) printf("***Invalid vdev: %s\n", vdev);
5209		free(dup);
5210		return;
5211	} else {
5212		if (vd->vdev_path)
5213			(void) fprintf(stderr, "Found vdev: %s\n",
5214			    vd->vdev_path);
5215		else
5216			(void) fprintf(stderr, "Found vdev type: %s\n",
5217			    vd->vdev_ops->vdev_op_type);
5218	}
5219
5220	psize = size;
5221	lsize = size;
5222
5223	pabd = abd_alloc_linear(SPA_MAXBLOCKSIZE, B_FALSE);
5224	lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
5225
5226	BP_ZERO(bp);
5227
5228	DVA_SET_VDEV(&dva[0], vd->vdev_id);
5229	DVA_SET_OFFSET(&dva[0], offset);
5230	DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
5231	DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
5232
5233	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
5234
5235	BP_SET_LSIZE(bp, lsize);
5236	BP_SET_PSIZE(bp, psize);
5237	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
5238	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
5239	BP_SET_TYPE(bp, DMU_OT_NONE);
5240	BP_SET_LEVEL(bp, 0);
5241	BP_SET_DEDUP(bp, 0);
5242	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
5243
5244	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5245	zio = zio_root(spa, NULL, NULL, 0);
5246
5247	if (vd == vd->vdev_top) {
5248		/*
5249		 * Treat this as a normal block read.
5250		 */
5251		zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
5252		    ZIO_PRIORITY_SYNC_READ,
5253		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
5254	} else {
5255		/*
5256		 * Treat this as a vdev child I/O.
5257		 */
5258		zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
5259		    psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
5260		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
5261		    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
5262		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW | ZIO_FLAG_OPTIONAL,
5263		    NULL, NULL));
5264	}
5265
5266	error = zio_wait(zio);
5267	spa_config_exit(spa, SCL_STATE, FTAG);
5268
5269	if (error) {
5270		(void) printf("Read of %s failed, error: %d\n", thing, error);
5271		goto out;
5272	}
5273
5274	if (flags & ZDB_FLAG_DECOMPRESS) {
5275		/*
5276		 * We don't know how the data was compressed, so just try
5277		 * every decompress function at every inflated blocksize.
5278		 */
5279		enum zio_compress c;
5280		void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
5281		void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
5282
5283		abd_copy_to_buf(pbuf2, pabd, psize);
5284
5285		VERIFY0(abd_iterate_func(pabd, psize, SPA_MAXBLOCKSIZE - psize,
5286		    random_get_pseudo_bytes_cb, NULL));
5287
5288		VERIFY0(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
5289		    SPA_MAXBLOCKSIZE - psize));
5290
5291		for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
5292		    lsize -= SPA_MINBLOCKSIZE) {
5293			for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
5294				if (zio_decompress_data(c, pabd,
5295				    lbuf, psize, lsize) == 0 &&
5296				    zio_decompress_data_buf(c, pbuf2,
5297				    lbuf2, psize, lsize) == 0 &&
5298				    bcmp(lbuf, lbuf2, lsize) == 0)
5299					break;
5300			}
5301			if (c != ZIO_COMPRESS_FUNCTIONS)
5302				break;
5303			lsize -= SPA_MINBLOCKSIZE;
5304		}
5305
5306		umem_free(pbuf2, SPA_MAXBLOCKSIZE);
5307		umem_free(lbuf2, SPA_MAXBLOCKSIZE);
5308
5309		if (lsize <= psize) {
5310			(void) printf("Decompress of %s failed\n", thing);
5311			goto out;
5312		}
5313		buf = lbuf;
5314		size = lsize;
5315	} else {
5316		buf = abd_to_buf(pabd);
5317		size = psize;
5318	}
5319
5320	if (flags & ZDB_FLAG_PRINT_BLKPTR)
5321		zdb_print_blkptr((blkptr_t *)(void *)
5322		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
5323	else if (flags & ZDB_FLAG_RAW)
5324		zdb_dump_block_raw(buf, size, flags);
5325	else if (flags & ZDB_FLAG_INDIRECT)
5326		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
5327		    flags);
5328	else if (flags & ZDB_FLAG_GBH)
5329		zdb_dump_gbh(buf, flags);
5330	else
5331		zdb_dump_block(thing, buf, size, flags);
5332
5333out:
5334	abd_free(pabd);
5335	umem_free(lbuf, SPA_MAXBLOCKSIZE);
5336	free(dup);
5337}
5338
5339static void
5340zdb_embedded_block(char *thing)
5341{
5342	blkptr_t bp;
5343	unsigned long long *words = (void *)&bp;
5344	char *buf;
5345	int err;
5346
5347	bzero(&bp, sizeof (bp));
5348	err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
5349	    "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
5350	    words + 0, words + 1, words + 2, words + 3,
5351	    words + 4, words + 5, words + 6, words + 7,
5352	    words + 8, words + 9, words + 10, words + 11,
5353	    words + 12, words + 13, words + 14, words + 15);
5354	if (err != 16) {
5355		(void) fprintf(stderr, "invalid input format\n");
5356		exit(1);
5357	}
5358	ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
5359	buf = malloc(SPA_MAXBLOCKSIZE);
5360	if (buf == NULL) {
5361		(void) fprintf(stderr, "out of memory\n");
5362		exit(1);
5363	}
5364	err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
5365	if (err != 0) {
5366		(void) fprintf(stderr, "decode failed: %u\n", err);
5367		free(buf);
5368		exit(1);
5369	}
5370	zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
5371	free(buf);
5372}
5373
5374int
5375main(int argc, char **argv)
5376{
5377	int c;
5378	struct rlimit rl = { 1024, 1024 };
5379	spa_t *spa = NULL;
5380	objset_t *os = NULL;
5381	int dump_all = 1;
5382	int verbose = 0;
5383	int error = 0;
5384	char **searchdirs = NULL;
5385	int nsearch = 0;
5386	char *target, *target_pool;
5387	nvlist_t *policy = NULL;
5388	uint64_t max_txg = UINT64_MAX;
5389	int flags = ZFS_IMPORT_MISSING_LOG;
5390	int rewind = ZPOOL_NEVER_REWIND;
5391	char *spa_config_path_env;
5392	boolean_t target_is_spa = B_TRUE;
5393	nvlist_t *cfg = NULL;
5394
5395	(void) setrlimit(RLIMIT_NOFILE, &rl);
5396	(void) enable_extended_FILE_stdio(-1, -1);
5397
5398	dprintf_setup(&argc, argv);
5399
5400	/*
5401	 * If there is an environment variable SPA_CONFIG_PATH it overrides
5402	 * default spa_config_path setting. If -U flag is specified it will
5403	 * override this environment variable settings once again.
5404	 */
5405	spa_config_path_env = getenv("SPA_CONFIG_PATH");
5406	if (spa_config_path_env != NULL)
5407		spa_config_path = spa_config_path_env;
5408
5409	while ((c = getopt(argc, argv,
5410	    "AbcCdDeEFGhiI:klLmMo:Op:PqRsSt:uU:vVx:X")) != -1) {
5411		switch (c) {
5412		case 'b':
5413		case 'c':
5414		case 'C':
5415		case 'd':
5416		case 'D':
5417		case 'E':
5418		case 'G':
5419		case 'h':
5420		case 'i':
5421		case 'l':
5422		case 'm':
5423		case 'M':
5424		case 'O':
5425		case 'R':
5426		case 's':
5427		case 'S':
5428		case 'u':
5429			dump_opt[c]++;
5430			dump_all = 0;
5431			break;
5432		case 'A':
5433		case 'e':
5434		case 'F':
5435		case 'k':
5436		case 'L':
5437		case 'P':
5438		case 'q':
5439		case 'X':
5440			dump_opt[c]++;
5441			break;
5442		/* NB: Sort single match options below. */
5443		case 'I':
5444			max_inflight = strtoull(optarg, NULL, 0);
5445			if (max_inflight == 0) {
5446				(void) fprintf(stderr, "maximum number "
5447				    "of inflight I/Os must be greater "
5448				    "than 0\n");
5449				usage();
5450			}
5451			break;
5452		case 'o':
5453			error = set_global_var(optarg);
5454			if (error != 0)
5455				usage();
5456			break;
5457		case 'p':
5458			if (searchdirs == NULL) {
5459				searchdirs = umem_alloc(sizeof (char *),
5460				    UMEM_NOFAIL);
5461			} else {
5462				char **tmp = umem_alloc((nsearch + 1) *
5463				    sizeof (char *), UMEM_NOFAIL);
5464				bcopy(searchdirs, tmp, nsearch *
5465				    sizeof (char *));
5466				umem_free(searchdirs,
5467				    nsearch * sizeof (char *));
5468				searchdirs = tmp;
5469			}
5470			searchdirs[nsearch++] = optarg;
5471			break;
5472		case 't':
5473			max_txg = strtoull(optarg, NULL, 0);
5474			if (max_txg < TXG_INITIAL) {
5475				(void) fprintf(stderr, "incorrect txg "
5476				    "specified: %s\n", optarg);
5477				usage();
5478			}
5479			break;
5480		case 'U':
5481			spa_config_path = optarg;
5482			if (spa_config_path[0] != '/') {
5483				(void) fprintf(stderr,
5484				    "cachefile must be an absolute path "
5485				    "(i.e. start with a slash)\n");
5486				usage();
5487			}
5488			break;
5489		case 'v':
5490			verbose++;
5491			break;
5492		case 'V':
5493			flags = ZFS_IMPORT_VERBATIM;
5494			break;
5495		case 'x':
5496			vn_dumpdir = optarg;
5497			break;
5498		default:
5499			usage();
5500			break;
5501		}
5502	}
5503
5504	if (!dump_opt['e'] && searchdirs != NULL) {
5505		(void) fprintf(stderr, "-p option requires use of -e\n");
5506		usage();
5507	}
5508
5509	/*
5510	 * ZDB does not typically re-read blocks; therefore limit the ARC
5511	 * to 256 MB, which can be used entirely for metadata.
5512	 */
5513	zfs_arc_max = zfs_arc_meta_limit = 256 * 1024 * 1024;
5514
5515	/*
5516	 * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
5517	 * "zdb -b" uses traversal prefetch which uses async reads.
5518	 * For good performance, let several of them be active at once.
5519	 */
5520	zfs_vdev_async_read_max_active = 10;
5521
5522	/*
5523	 * Disable reference tracking for better performance.
5524	 */
5525	reference_tracking_enable = B_FALSE;
5526
5527	/*
5528	 * Do not fail spa_load when spa_load_verify fails. This is needed
5529	 * to load non-idle pools.
5530	 */
5531	spa_load_verify_dryrun = B_TRUE;
5532
5533	kernel_init(FREAD);
5534	g_zfs = libzfs_init();
5535	if (g_zfs == NULL)
5536		fatal("Fail to initialize zfs");
5537
5538	if (dump_all)
5539		verbose = MAX(verbose, 1);
5540
5541	for (c = 0; c < 256; c++) {
5542		if (dump_all && strchr("AeEFklLOPRSX", c) == NULL)
5543			dump_opt[c] = 1;
5544		if (dump_opt[c])
5545			dump_opt[c] += verbose;
5546	}
5547
5548	aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
5549	zfs_recover = (dump_opt['A'] > 1);
5550
5551	argc -= optind;
5552	argv += optind;
5553
5554	if (argc < 2 && dump_opt['R'])
5555		usage();
5556
5557	if (dump_opt['E']) {
5558		if (argc != 1)
5559			usage();
5560		zdb_embedded_block(argv[0]);
5561		return (0);
5562	}
5563
5564	if (argc < 1) {
5565		if (!dump_opt['e'] && dump_opt['C']) {
5566			dump_cachefile(spa_config_path);
5567			return (0);
5568		}
5569		usage();
5570	}
5571
5572	if (dump_opt['l'])
5573		return (dump_label(argv[0]));
5574
5575	if (dump_opt['O']) {
5576		if (argc != 2)
5577			usage();
5578		dump_opt['v'] = verbose + 3;
5579		return (dump_path(argv[0], argv[1]));
5580	}
5581
5582	if (dump_opt['X'] || dump_opt['F'])
5583		rewind = ZPOOL_DO_REWIND |
5584		    (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
5585
5586	if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
5587	    nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, max_txg) != 0 ||
5588	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY, rewind) != 0)
5589		fatal("internal error: %s", strerror(ENOMEM));
5590
5591	error = 0;
5592	target = argv[0];
5593
5594	if (strpbrk(target, "/@") != NULL) {
5595		size_t targetlen;
5596
5597		target_pool = strdup(target);
5598		*strpbrk(target_pool, "/@") = '\0';
5599
5600		target_is_spa = B_FALSE;
5601		targetlen = strlen(target);
5602		if (targetlen && target[targetlen - 1] == '/')
5603			target[targetlen - 1] = '\0';
5604	} else {
5605		target_pool = target;
5606	}
5607
5608	if (dump_opt['e']) {
5609		importargs_t args = { 0 };
5610
5611		args.paths = nsearch;
5612		args.path = searchdirs;
5613		args.can_be_active = B_TRUE;
5614
5615		error = zpool_tryimport(g_zfs, target_pool, &cfg, &args);
5616
5617		if (error == 0) {
5618
5619			if (nvlist_add_nvlist(cfg,
5620			    ZPOOL_LOAD_POLICY, policy) != 0) {
5621				fatal("can't open '%s': %s",
5622				    target, strerror(ENOMEM));
5623			}
5624
5625			if (dump_opt['C'] > 1) {
5626				(void) printf("\nConfiguration for import:\n");
5627				dump_nvlist(cfg, 8);
5628			}
5629
5630			/*
5631			 * Disable the activity check to allow examination of
5632			 * active pools.
5633			 */
5634			error = spa_import(target_pool, cfg, NULL,
5635			    flags | ZFS_IMPORT_SKIP_MMP);
5636		}
5637	}
5638
5639	char *checkpoint_pool = NULL;
5640	char *checkpoint_target = NULL;
5641	if (dump_opt['k']) {
5642		checkpoint_pool = import_checkpointed_state(target, cfg,
5643		    &checkpoint_target);
5644
5645		if (checkpoint_target != NULL)
5646			target = checkpoint_target;
5647
5648	}
5649
5650	if (error == 0) {
5651		if (dump_opt['k'] && (target_is_spa || dump_opt['R'])) {
5652			ASSERT(checkpoint_pool != NULL);
5653			ASSERT(checkpoint_target == NULL);
5654
5655			error = spa_open(checkpoint_pool, &spa, FTAG);
5656			if (error != 0) {
5657				fatal("Tried to open pool \"%s\" but "
5658				    "spa_open() failed with error %d\n",
5659				    checkpoint_pool, error);
5660			}
5661
5662		} else if (target_is_spa || dump_opt['R']) {
5663			zdb_set_skip_mmp(target);
5664			error = spa_open_rewind(target, &spa, FTAG, policy,
5665			    NULL);
5666			if (error) {
5667				/*
5668				 * If we're missing the log device then
5669				 * try opening the pool after clearing the
5670				 * log state.
5671				 */
5672				mutex_enter(&spa_namespace_lock);
5673				if ((spa = spa_lookup(target)) != NULL &&
5674				    spa->spa_log_state == SPA_LOG_MISSING) {
5675					spa->spa_log_state = SPA_LOG_CLEAR;
5676					error = 0;
5677				}
5678				mutex_exit(&spa_namespace_lock);
5679
5680				if (!error) {
5681					error = spa_open_rewind(target, &spa,
5682					    FTAG, policy, NULL);
5683				}
5684			}
5685		} else {
5686			zdb_set_skip_mmp(target);
5687			error = open_objset(target, DMU_OST_ANY, FTAG, &os);
5688		}
5689	}
5690	nvlist_free(policy);
5691
5692	if (error)
5693		fatal("can't open '%s': %s", target, strerror(error));
5694
5695	argv++;
5696	argc--;
5697	if (!dump_opt['R']) {
5698		if (argc > 0) {
5699			zopt_objects = argc;
5700			zopt_object = calloc(zopt_objects, sizeof (uint64_t));
5701			for (unsigned i = 0; i < zopt_objects; i++) {
5702				errno = 0;
5703				zopt_object[i] = strtoull(argv[i], NULL, 0);
5704				if (zopt_object[i] == 0 && errno != 0)
5705					fatal("bad number %s: %s",
5706					    argv[i], strerror(errno));
5707			}
5708		}
5709		if (os != NULL) {
5710			dump_dir(os);
5711		} else if (zopt_objects > 0 && !dump_opt['m']) {
5712			dump_dir(spa->spa_meta_objset);
5713		} else {
5714			dump_zpool(spa);
5715		}
5716	} else {
5717		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
5718		flagbits['c'] = ZDB_FLAG_CHECKSUM;
5719		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
5720		flagbits['e'] = ZDB_FLAG_BSWAP;
5721		flagbits['g'] = ZDB_FLAG_GBH;
5722		flagbits['i'] = ZDB_FLAG_INDIRECT;
5723		flagbits['p'] = ZDB_FLAG_PHYS;
5724		flagbits['r'] = ZDB_FLAG_RAW;
5725
5726		for (int i = 0; i < argc; i++)
5727			zdb_read_block(argv[i], spa);
5728	}
5729
5730	if (dump_opt['k']) {
5731		free(checkpoint_pool);
5732		if (!target_is_spa)
5733			free(checkpoint_target);
5734	}
5735
5736	if (os != NULL)
5737		close_objset(os, FTAG);
5738	else
5739		spa_close(spa, FTAG);
5740
5741	fuid_table_destroy();
5742
5743	dump_debug_buffer();
5744
5745	libzfs_fini(g_zfs);
5746	kernel_fini();
5747
5748	return (error);
5749}
5750