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