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