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