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