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