zdb.c revision 9eb19f4d61679ca0382def038665019234458edd
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 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23 * Use is subject to license terms.
24 */
25
26#include <stdio.h>
27#include <stdio_ext.h>
28#include <stdlib.h>
29#include <ctype.h>
30#include <sys/zfs_context.h>
31#include <sys/spa.h>
32#include <sys/spa_impl.h>
33#include <sys/dmu.h>
34#include <sys/zap.h>
35#include <sys/fs/zfs.h>
36#include <sys/zfs_znode.h>
37#include <sys/vdev.h>
38#include <sys/vdev_impl.h>
39#include <sys/metaslab_impl.h>
40#include <sys/dmu_objset.h>
41#include <sys/dsl_dir.h>
42#include <sys/dsl_dataset.h>
43#include <sys/dsl_pool.h>
44#include <sys/dbuf.h>
45#include <sys/zil.h>
46#include <sys/zil_impl.h>
47#include <sys/stat.h>
48#include <sys/resource.h>
49#include <sys/dmu_traverse.h>
50#include <sys/zio_checksum.h>
51#include <sys/zio_compress.h>
52#include <sys/zfs_fuid.h>
53#include <sys/arc.h>
54#include <sys/ddt.h>
55#undef ZFS_MAXNAMELEN
56#undef verify
57#include <libzfs.h>
58
59#define	ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ? \
60    zio_compress_table[(idx)].ci_name : "UNKNOWN")
61#define	ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ? \
62    zio_checksum_table[(idx)].ci_name : "UNKNOWN")
63#define	ZDB_OT_NAME(idx) ((idx) < DMU_OT_NUMTYPES ? \
64    dmu_ot[(idx)].ot_name : "UNKNOWN")
65#define	ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) : DMU_OT_NUMTYPES)
66
67const char cmdname[] = "zdb";
68uint8_t dump_opt[256];
69
70typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
71
72extern void dump_intent_log(zilog_t *);
73uint64_t *zopt_object = NULL;
74int zopt_objects = 0;
75libzfs_handle_t *g_zfs;
76
77/*
78 * These libumem hooks provide a reasonable set of defaults for the allocator's
79 * debugging facilities.
80 */
81const char *
82_umem_debug_init()
83{
84	return ("default,verbose"); /* $UMEM_DEBUG setting */
85}
86
87const char *
88_umem_logging_init(void)
89{
90	return ("fail,contents"); /* $UMEM_LOGGING setting */
91}
92
93static void
94usage(void)
95{
96	(void) fprintf(stderr,
97	    "Usage: %s [-CumdibcsvhL] "
98	    "poolname [object...]\n"
99	    "       %s [-div] dataset [object...]\n"
100	    "       %s -m [-L] poolname [vdev [metaslab...]]\n"
101	    "       %s -R poolname vdev:offset:size[:flags]\n"
102	    "       %s -S poolname\n"
103	    "       %s -l device\n"
104	    "       %s -C\n\n",
105	    cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname);
106
107	(void) fprintf(stderr, "    Dataset name must include at least one "
108	    "separator character '/' or '@'\n");
109	(void) fprintf(stderr, "    If dataset name is specified, only that "
110	    "dataset is dumped\n");
111	(void) fprintf(stderr, "    If object numbers are specified, only "
112	    "those objects are dumped\n\n");
113	(void) fprintf(stderr, "    Options to control amount of output:\n");
114	(void) fprintf(stderr, "        -u uberblock\n");
115	(void) fprintf(stderr, "        -d dataset(s)\n");
116	(void) fprintf(stderr, "        -i intent logs\n");
117	(void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
118	(void) fprintf(stderr, "        -h pool history\n");
119	(void) fprintf(stderr, "        -b block statistics\n");
120	(void) fprintf(stderr, "        -m metaslabs\n");
121	(void) fprintf(stderr, "        -c checksum all metadata (twice for "
122	    "all data) blocks\n");
123	(void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
124	(void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
125	(void) fprintf(stderr, "        -v verbose (applies to all others)\n");
126	(void) fprintf(stderr, "        -l dump label contents\n");
127	(void) fprintf(stderr, "        -L disable leak tracking (do not "
128	    "load spacemaps)\n");
129	(void) fprintf(stderr, "        -R read and display block from a "
130	    "device\n\n");
131	(void) fprintf(stderr, "    Below options are intended for use "
132	    "with other options (except -l):\n");
133	(void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
134	    "cachefile\n");
135	(void) fprintf(stderr, "        -e pool is exported/destroyed/"
136	    "has altroot/not in a cachefile\n");
137	(void) fprintf(stderr, "        -p <path> -- use one or more with "
138	    "-e to specify path to vdev dir\n");
139	(void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
140	    "searching for uberblocks\n");
141	(void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
142	    "to make only that option verbose\n");
143	(void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
144	exit(1);
145}
146
147/*
148 * Called for usage errors that are discovered after a call to spa_open(),
149 * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
150 */
151
152static void
153fatal(const char *fmt, ...)
154{
155	va_list ap;
156
157	va_start(ap, fmt);
158	(void) fprintf(stderr, "%s: ", cmdname);
159	(void) vfprintf(stderr, fmt, ap);
160	va_end(ap);
161	(void) fprintf(stderr, "\n");
162
163	exit(1);
164}
165
166/* ARGSUSED */
167static void
168dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
169{
170	nvlist_t *nv;
171	size_t nvsize = *(uint64_t *)data;
172	char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
173
174	VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
175
176	VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
177
178	umem_free(packed, nvsize);
179
180	dump_nvlist(nv, 8);
181
182	nvlist_free(nv);
183}
184
185const char dump_zap_stars[] = "****************************************";
186const int dump_zap_width = sizeof (dump_zap_stars) - 1;
187
188static void
189dump_zap_histogram(uint64_t histo[ZAP_HISTOGRAM_SIZE])
190{
191	int i;
192	int minidx = ZAP_HISTOGRAM_SIZE - 1;
193	int maxidx = 0;
194	uint64_t max = 0;
195
196	for (i = 0; i < ZAP_HISTOGRAM_SIZE; i++) {
197		if (histo[i] > max)
198			max = histo[i];
199		if (histo[i] > 0 && i > maxidx)
200			maxidx = i;
201		if (histo[i] > 0 && i < minidx)
202			minidx = i;
203	}
204
205	if (max < dump_zap_width)
206		max = dump_zap_width;
207
208	for (i = minidx; i <= maxidx; i++)
209		(void) printf("\t\t\t%u: %6llu %s\n", i, (u_longlong_t)histo[i],
210		    &dump_zap_stars[(max - histo[i]) * dump_zap_width / max]);
211}
212
213static void
214dump_zap_stats(objset_t *os, uint64_t object)
215{
216	int error;
217	zap_stats_t zs;
218
219	error = zap_get_stats(os, object, &zs);
220	if (error)
221		return;
222
223	if (zs.zs_ptrtbl_len == 0) {
224		ASSERT(zs.zs_num_blocks == 1);
225		(void) printf("\tmicrozap: %llu bytes, %llu entries\n",
226		    (u_longlong_t)zs.zs_blocksize,
227		    (u_longlong_t)zs.zs_num_entries);
228		return;
229	}
230
231	(void) printf("\tFat ZAP stats:\n");
232
233	(void) printf("\t\tPointer table:\n");
234	(void) printf("\t\t\t%llu elements\n",
235	    (u_longlong_t)zs.zs_ptrtbl_len);
236	(void) printf("\t\t\tzt_blk: %llu\n",
237	    (u_longlong_t)zs.zs_ptrtbl_zt_blk);
238	(void) printf("\t\t\tzt_numblks: %llu\n",
239	    (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
240	(void) printf("\t\t\tzt_shift: %llu\n",
241	    (u_longlong_t)zs.zs_ptrtbl_zt_shift);
242	(void) printf("\t\t\tzt_blks_copied: %llu\n",
243	    (u_longlong_t)zs.zs_ptrtbl_blks_copied);
244	(void) printf("\t\t\tzt_nextblk: %llu\n",
245	    (u_longlong_t)zs.zs_ptrtbl_nextblk);
246
247	(void) printf("\t\tZAP entries: %llu\n",
248	    (u_longlong_t)zs.zs_num_entries);
249	(void) printf("\t\tLeaf blocks: %llu\n",
250	    (u_longlong_t)zs.zs_num_leafs);
251	(void) printf("\t\tTotal blocks: %llu\n",
252	    (u_longlong_t)zs.zs_num_blocks);
253	(void) printf("\t\tzap_block_type: 0x%llx\n",
254	    (u_longlong_t)zs.zs_block_type);
255	(void) printf("\t\tzap_magic: 0x%llx\n",
256	    (u_longlong_t)zs.zs_magic);
257	(void) printf("\t\tzap_salt: 0x%llx\n",
258	    (u_longlong_t)zs.zs_salt);
259
260	(void) printf("\t\tLeafs with 2^n pointers:\n");
261	dump_zap_histogram(zs.zs_leafs_with_2n_pointers);
262
263	(void) printf("\t\tBlocks with n*5 entries:\n");
264	dump_zap_histogram(zs.zs_blocks_with_n5_entries);
265
266	(void) printf("\t\tBlocks n/10 full:\n");
267	dump_zap_histogram(zs.zs_blocks_n_tenths_full);
268
269	(void) printf("\t\tEntries with n chunks:\n");
270	dump_zap_histogram(zs.zs_entries_using_n_chunks);
271
272	(void) printf("\t\tBuckets with n entries:\n");
273	dump_zap_histogram(zs.zs_buckets_with_n_entries);
274}
275
276/*ARGSUSED*/
277static void
278dump_none(objset_t *os, uint64_t object, void *data, size_t size)
279{
280}
281
282/*ARGSUSED*/
283static void
284dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
285{
286	(void) printf("\tUNKNOWN OBJECT TYPE\n");
287}
288
289/*ARGSUSED*/
290void
291dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
292{
293}
294
295/*ARGSUSED*/
296static void
297dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
298{
299}
300
301/*ARGSUSED*/
302static void
303dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
304{
305	zap_cursor_t zc;
306	zap_attribute_t attr;
307	void *prop;
308	int i;
309
310	dump_zap_stats(os, object);
311	(void) printf("\n");
312
313	for (zap_cursor_init(&zc, os, object);
314	    zap_cursor_retrieve(&zc, &attr) == 0;
315	    zap_cursor_advance(&zc)) {
316		(void) printf("\t\t%s = ", attr.za_name);
317		if (attr.za_num_integers == 0) {
318			(void) printf("\n");
319			continue;
320		}
321		prop = umem_zalloc(attr.za_num_integers *
322		    attr.za_integer_length, UMEM_NOFAIL);
323		(void) zap_lookup(os, object, attr.za_name,
324		    attr.za_integer_length, attr.za_num_integers, prop);
325		if (attr.za_integer_length == 1) {
326			(void) printf("%s", (char *)prop);
327		} else {
328			for (i = 0; i < attr.za_num_integers; i++) {
329				switch (attr.za_integer_length) {
330				case 2:
331					(void) printf("%u ",
332					    ((uint16_t *)prop)[i]);
333					break;
334				case 4:
335					(void) printf("%u ",
336					    ((uint32_t *)prop)[i]);
337					break;
338				case 8:
339					(void) printf("%lld ",
340					    (u_longlong_t)((int64_t *)prop)[i]);
341					break;
342				}
343			}
344		}
345		(void) printf("\n");
346		umem_free(prop, attr.za_num_integers * attr.za_integer_length);
347	}
348	zap_cursor_fini(&zc);
349}
350
351/*ARGSUSED*/
352static void
353dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
354{
355	zap_cursor_t zc;
356	zap_attribute_t attr;
357	const char *typenames[] = {
358		/* 0 */ "not specified",
359		/* 1 */ "FIFO",
360		/* 2 */ "Character Device",
361		/* 3 */ "3 (invalid)",
362		/* 4 */ "Directory",
363		/* 5 */ "5 (invalid)",
364		/* 6 */ "Block Device",
365		/* 7 */ "7 (invalid)",
366		/* 8 */ "Regular File",
367		/* 9 */ "9 (invalid)",
368		/* 10 */ "Symbolic Link",
369		/* 11 */ "11 (invalid)",
370		/* 12 */ "Socket",
371		/* 13 */ "Door",
372		/* 14 */ "Event Port",
373		/* 15 */ "15 (invalid)",
374	};
375
376	dump_zap_stats(os, object);
377	(void) printf("\n");
378
379	for (zap_cursor_init(&zc, os, object);
380	    zap_cursor_retrieve(&zc, &attr) == 0;
381	    zap_cursor_advance(&zc)) {
382		(void) printf("\t\t%s = %lld (type: %s)\n",
383		    attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
384		    typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
385	}
386	zap_cursor_fini(&zc);
387}
388
389static void
390dump_spacemap(objset_t *os, space_map_obj_t *smo, space_map_t *sm)
391{
392	uint64_t alloc, offset, entry;
393	uint8_t mapshift = sm->sm_shift;
394	uint64_t mapstart = sm->sm_start;
395	char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
396			    "INVALID", "INVALID", "INVALID", "INVALID" };
397
398	if (smo->smo_object == 0)
399		return;
400
401	/*
402	 * Print out the freelist entries in both encoded and decoded form.
403	 */
404	alloc = 0;
405	for (offset = 0; offset < smo->smo_objsize; offset += sizeof (entry)) {
406		VERIFY(0 == dmu_read(os, smo->smo_object, offset,
407		    sizeof (entry), &entry, DMU_READ_PREFETCH));
408		if (SM_DEBUG_DECODE(entry)) {
409			(void) printf("\t    [%6llu] %s: txg %llu, pass %llu\n",
410			    (u_longlong_t)(offset / sizeof (entry)),
411			    ddata[SM_DEBUG_ACTION_DECODE(entry)],
412			    (u_longlong_t)SM_DEBUG_TXG_DECODE(entry),
413			    (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(entry));
414		} else {
415			(void) printf("\t    [%6llu]    %c  range:"
416			    " %010llx-%010llx  size: %06llx\n",
417			    (u_longlong_t)(offset / sizeof (entry)),
418			    SM_TYPE_DECODE(entry) == SM_ALLOC ? 'A' : 'F',
419			    (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
420			    mapshift) + mapstart),
421			    (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
422			    mapshift) + mapstart + (SM_RUN_DECODE(entry) <<
423			    mapshift)),
424			    (u_longlong_t)(SM_RUN_DECODE(entry) << mapshift));
425			if (SM_TYPE_DECODE(entry) == SM_ALLOC)
426				alloc += SM_RUN_DECODE(entry) << mapshift;
427			else
428				alloc -= SM_RUN_DECODE(entry) << mapshift;
429		}
430	}
431	if (alloc != smo->smo_alloc) {
432		(void) printf("space_map_object alloc (%llu) INCONSISTENT "
433		    "with space map summary (%llu)\n",
434		    (u_longlong_t)smo->smo_alloc, (u_longlong_t)alloc);
435	}
436}
437
438static void
439dump_metaslab_stats(metaslab_t *msp)
440{
441	char maxbuf[5];
442	space_map_t *sm = &msp->ms_map;
443	avl_tree_t *t = sm->sm_pp_root;
444	int free_pct = sm->sm_space * 100 / sm->sm_size;
445
446	nicenum(space_map_maxsize(sm), maxbuf);
447
448	(void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
449	    "segments", avl_numnodes(t), "maxsize", maxbuf,
450	    "freepct", free_pct);
451}
452
453static void
454dump_metaslab(metaslab_t *msp)
455{
456	vdev_t *vd = msp->ms_group->mg_vd;
457	spa_t *spa = vd->vdev_spa;
458	space_map_t *sm = &msp->ms_map;
459	space_map_obj_t *smo = &msp->ms_smo;
460	char freebuf[5];
461
462	nicenum(sm->sm_size - smo->smo_alloc, freebuf);
463
464	(void) printf(
465	    "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
466	    (u_longlong_t)(sm->sm_start / sm->sm_size),
467	    (u_longlong_t)sm->sm_start, (u_longlong_t)smo->smo_object, freebuf);
468
469	if (dump_opt['m'] > 1 && !dump_opt['L']) {
470		mutex_enter(&msp->ms_lock);
471		space_map_load_wait(sm);
472		if (!sm->sm_loaded &&
473		    (smo->smo_object != 0 || dump_opt['m'] > 2)) {
474			VERIFY(space_map_load(sm, zfs_metaslab_ops,
475			    SM_FREE, smo, spa->spa_meta_objset) == 0);
476			dump_metaslab_stats(msp);
477			space_map_unload(sm);
478		}
479		mutex_exit(&msp->ms_lock);
480	}
481
482	if (dump_opt['d'] > 5 || dump_opt['m'] > 2) {
483		ASSERT(sm->sm_size == (1ULL << vd->vdev_ms_shift));
484
485		mutex_enter(&msp->ms_lock);
486		dump_spacemap(spa->spa_meta_objset, smo, sm);
487		mutex_exit(&msp->ms_lock);
488	}
489}
490
491static void
492print_vdev_metaslab_header(vdev_t *vd)
493{
494	(void) printf("\tvdev %10llu\n\t%-10s%5llu   %-19s   %-15s   %-10s\n",
495	    (u_longlong_t)vd->vdev_id,
496	    "metaslabs", (u_longlong_t)vd->vdev_ms_count,
497	    "offset", "spacemap", "free");
498	(void) printf("\t%15s   %19s   %15s   %10s\n",
499	    "---------------", "-------------------",
500	    "---------------", "-------------");
501}
502
503static void
504dump_metaslabs(spa_t *spa)
505{
506	vdev_t *vd, *rvd = spa->spa_root_vdev;
507	uint64_t m, c = 0, children = rvd->vdev_children;
508
509	(void) printf("\nMetaslabs:\n");
510
511	if (!dump_opt['d'] && zopt_objects > 0) {
512		c = zopt_object[0];
513
514		if (c >= children)
515			(void) fatal("bad vdev id: %llu", (u_longlong_t)c);
516
517		if (zopt_objects > 1) {
518			vd = rvd->vdev_child[c];
519			print_vdev_metaslab_header(vd);
520
521			for (m = 1; m < zopt_objects; m++) {
522				if (zopt_object[m] < vd->vdev_ms_count)
523					dump_metaslab(
524					    vd->vdev_ms[zopt_object[m]]);
525				else
526					(void) fprintf(stderr, "bad metaslab "
527					    "number %llu\n",
528					    (u_longlong_t)zopt_object[m]);
529			}
530			(void) printf("\n");
531			return;
532		}
533		children = c + 1;
534	}
535	for (; c < children; c++) {
536		vd = rvd->vdev_child[c];
537		print_vdev_metaslab_header(vd);
538
539		for (m = 0; m < vd->vdev_ms_count; m++)
540			dump_metaslab(vd->vdev_ms[m]);
541		(void) printf("\n");
542	}
543}
544
545static void
546dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
547{
548	const ddt_phys_t *ddp = dde->dde_phys;
549	const ddt_key_t *ddk = &dde->dde_key;
550	char *types[4] = { "ditto", "single", "double", "triple" };
551	char blkbuf[BP_SPRINTF_LEN];
552	blkptr_t blk;
553
554	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
555		if (ddp->ddp_phys_birth == 0)
556			continue;
557		ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
558		sprintf_blkptr(blkbuf, &blk);
559		(void) printf("index %llx refcnt %llu %s %s\n",
560		    (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
561		    types[p], blkbuf);
562	}
563}
564
565static void
566dump_dedup_ratio(const ddt_stat_t *dds)
567{
568	double rL, rP, rD, D, dedup, compress, copies;
569
570	if (dds->dds_blocks == 0)
571		return;
572
573	rL = (double)dds->dds_ref_lsize;
574	rP = (double)dds->dds_ref_psize;
575	rD = (double)dds->dds_ref_dsize;
576	D = (double)dds->dds_dsize;
577
578	dedup = rD / D;
579	compress = rL / rP;
580	copies = rD / rP;
581
582	(void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
583	    "dedup * compress / copies = %.2f\n\n",
584	    dedup, compress, copies, dedup * compress / copies);
585}
586
587static void
588dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
589{
590	char name[DDT_NAMELEN];
591	ddt_entry_t dde;
592	uint64_t walk = 0;
593	dmu_object_info_t doi;
594	uint64_t count, dspace, mspace;
595	int error;
596
597	error = ddt_object_info(ddt, type, class, &doi);
598
599	if (error == ENOENT)
600		return;
601	ASSERT(error == 0);
602
603	count = ddt_object_count(ddt, type, class);
604	dspace = doi.doi_physical_blocks_512 << 9;
605	mspace = doi.doi_fill_count * doi.doi_data_block_size;
606
607	ASSERT(count != 0);	/* we should have destroyed it */
608
609	ddt_object_name(ddt, type, class, name);
610
611	(void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
612	    name,
613	    (u_longlong_t)count,
614	    (u_longlong_t)(dspace / count),
615	    (u_longlong_t)(mspace / count));
616
617	if (dump_opt['D'] < 3)
618		return;
619
620	zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
621
622	if (dump_opt['D'] < 4)
623		return;
624
625	if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
626		return;
627
628	(void) printf("%s contents:\n\n", name);
629
630	while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
631		dump_dde(ddt, &dde, walk);
632
633	ASSERT(error == ENOENT);
634
635	(void) printf("\n");
636}
637
638static void
639dump_all_ddts(spa_t *spa)
640{
641	ddt_histogram_t ddh_total = { 0 };
642	ddt_stat_t dds_total = { 0 };
643
644	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
645		ddt_t *ddt = spa->spa_ddt[c];
646		for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
647			for (enum ddt_class class = 0; class < DDT_CLASSES;
648			    class++) {
649				dump_ddt(ddt, type, class);
650			}
651		}
652	}
653
654	ddt_get_dedup_stats(spa, &dds_total);
655
656	if (dds_total.dds_blocks == 0) {
657		(void) printf("All DDTs are empty\n");
658		return;
659	}
660
661	(void) printf("\n");
662
663	if (dump_opt['D'] > 1) {
664		(void) printf("DDT histogram (aggregated over all DDTs):\n");
665		ddt_get_dedup_histogram(spa, &ddh_total);
666		zpool_dump_ddt(&dds_total, &ddh_total);
667	}
668
669	dump_dedup_ratio(&dds_total);
670}
671
672static void
673dump_dtl_seg(space_map_t *sm, uint64_t start, uint64_t size)
674{
675	char *prefix = (void *)sm;
676
677	(void) printf("%s [%llu,%llu) length %llu\n",
678	    prefix,
679	    (u_longlong_t)start,
680	    (u_longlong_t)(start + size),
681	    (u_longlong_t)(size));
682}
683
684static void
685dump_dtl(vdev_t *vd, int indent)
686{
687	spa_t *spa = vd->vdev_spa;
688	boolean_t required;
689	char *name[DTL_TYPES] = { "missing", "partial", "scrub", "outage" };
690	char prefix[256];
691
692	spa_vdev_state_enter(spa, SCL_NONE);
693	required = vdev_dtl_required(vd);
694	(void) spa_vdev_state_exit(spa, NULL, 0);
695
696	if (indent == 0)
697		(void) printf("\nDirty time logs:\n\n");
698
699	(void) printf("\t%*s%s [%s]\n", indent, "",
700	    vd->vdev_path ? vd->vdev_path :
701	    vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
702	    required ? "DTL-required" : "DTL-expendable");
703
704	for (int t = 0; t < DTL_TYPES; t++) {
705		space_map_t *sm = &vd->vdev_dtl[t];
706		if (sm->sm_space == 0)
707			continue;
708		(void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
709		    indent + 2, "", name[t]);
710		mutex_enter(sm->sm_lock);
711		space_map_walk(sm, dump_dtl_seg, (void *)prefix);
712		mutex_exit(sm->sm_lock);
713		if (dump_opt['d'] > 5 && vd->vdev_children == 0)
714			dump_spacemap(spa->spa_meta_objset,
715			    &vd->vdev_dtl_smo, sm);
716	}
717
718	for (int c = 0; c < vd->vdev_children; c++)
719		dump_dtl(vd->vdev_child[c], indent + 4);
720}
721
722static void
723dump_history(spa_t *spa)
724{
725	nvlist_t **events = NULL;
726	char buf[SPA_MAXBLOCKSIZE];
727	uint64_t resid, len, off = 0;
728	uint_t num = 0;
729	int error;
730	time_t tsec;
731	struct tm t;
732	char tbuf[30];
733	char internalstr[MAXPATHLEN];
734
735	do {
736		len = sizeof (buf);
737
738		if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
739			(void) fprintf(stderr, "Unable to read history: "
740			    "error %d\n", error);
741			return;
742		}
743
744		if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
745			break;
746
747		off -= resid;
748	} while (len != 0);
749
750	(void) printf("\nHistory:\n");
751	for (int i = 0; i < num; i++) {
752		uint64_t time, txg, ievent;
753		char *cmd, *intstr;
754
755		if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
756		    &time) != 0)
757			continue;
758		if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
759		    &cmd) != 0) {
760			if (nvlist_lookup_uint64(events[i],
761			    ZPOOL_HIST_INT_EVENT, &ievent) != 0)
762				continue;
763			verify(nvlist_lookup_uint64(events[i],
764			    ZPOOL_HIST_TXG, &txg) == 0);
765			verify(nvlist_lookup_string(events[i],
766			    ZPOOL_HIST_INT_STR, &intstr) == 0);
767			if (ievent >= LOG_END)
768				continue;
769
770			(void) snprintf(internalstr,
771			    sizeof (internalstr),
772			    "[internal %s txg:%lld] %s",
773			    hist_event_table[ievent], txg,
774			    intstr);
775			cmd = internalstr;
776		}
777		tsec = time;
778		(void) localtime_r(&tsec, &t);
779		(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
780		(void) printf("%s %s\n", tbuf, cmd);
781	}
782}
783
784/*ARGSUSED*/
785static void
786dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
787{
788}
789
790static uint64_t
791blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp, const zbookmark_t *zb)
792{
793	if (dnp == NULL) {
794		ASSERT(zb->zb_level < 0);
795		if (zb->zb_object == 0)
796			return (zb->zb_blkid);
797		return (zb->zb_blkid * BP_GET_LSIZE(bp));
798	}
799
800	ASSERT(zb->zb_level >= 0);
801
802	return ((zb->zb_blkid <<
803	    (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
804	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
805}
806
807static void
808sprintf_blkptr_compact(char *blkbuf, blkptr_t *bp)
809{
810	dva_t *dva = bp->blk_dva;
811	int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
812
813	if (dump_opt['b'] >= 5) {
814		sprintf_blkptr(blkbuf, bp);
815		return;
816	}
817
818	blkbuf[0] = '\0';
819
820	for (int i = 0; i < ndvas; i++)
821		(void) sprintf(blkbuf + strlen(blkbuf), "%llu:%llx:%llx ",
822		    (u_longlong_t)DVA_GET_VDEV(&dva[i]),
823		    (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
824		    (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
825
826	(void) sprintf(blkbuf + strlen(blkbuf),
827	    "%llxL/%llxP F=%llu B=%llu/%llu",
828	    (u_longlong_t)BP_GET_LSIZE(bp),
829	    (u_longlong_t)BP_GET_PSIZE(bp),
830	    (u_longlong_t)bp->blk_fill,
831	    (u_longlong_t)bp->blk_birth,
832	    (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
833}
834
835static void
836print_indirect(blkptr_t *bp, const zbookmark_t *zb,
837    const dnode_phys_t *dnp)
838{
839	char blkbuf[BP_SPRINTF_LEN];
840	int l;
841
842	ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
843	ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
844
845	(void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
846
847	ASSERT(zb->zb_level >= 0);
848
849	for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
850		if (l == zb->zb_level) {
851			(void) printf("L%llx", (u_longlong_t)zb->zb_level);
852		} else {
853			(void) printf(" ");
854		}
855	}
856
857	sprintf_blkptr_compact(blkbuf, bp);
858	(void) printf("%s\n", blkbuf);
859}
860
861static int
862visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
863    blkptr_t *bp, const zbookmark_t *zb)
864{
865	int err = 0;
866
867	if (bp->blk_birth == 0)
868		return (0);
869
870	print_indirect(bp, zb, dnp);
871
872	if (BP_GET_LEVEL(bp) > 0) {
873		uint32_t flags = ARC_WAIT;
874		int i;
875		blkptr_t *cbp;
876		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
877		arc_buf_t *buf;
878		uint64_t fill = 0;
879
880		err = arc_read_nolock(NULL, spa, bp, arc_getbuf_func, &buf,
881		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
882		if (err)
883			return (err);
884
885		/* recursively visit blocks below this */
886		cbp = buf->b_data;
887		for (i = 0; i < epb; i++, cbp++) {
888			zbookmark_t czb;
889
890			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
891			    zb->zb_level - 1,
892			    zb->zb_blkid * epb + i);
893			err = visit_indirect(spa, dnp, cbp, &czb);
894			if (err)
895				break;
896			fill += cbp->blk_fill;
897		}
898		if (!err)
899			ASSERT3U(fill, ==, bp->blk_fill);
900		(void) arc_buf_remove_ref(buf, &buf);
901	}
902
903	return (err);
904}
905
906/*ARGSUSED*/
907static void
908dump_indirect(dnode_t *dn)
909{
910	dnode_phys_t *dnp = dn->dn_phys;
911	int j;
912	zbookmark_t czb;
913
914	(void) printf("Indirect blocks:\n");
915
916	SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
917	    dn->dn_object, dnp->dn_nlevels - 1, 0);
918	for (j = 0; j < dnp->dn_nblkptr; j++) {
919		czb.zb_blkid = j;
920		(void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
921		    &dnp->dn_blkptr[j], &czb);
922	}
923
924	(void) printf("\n");
925}
926
927/*ARGSUSED*/
928static void
929dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
930{
931	dsl_dir_phys_t *dd = data;
932	time_t crtime;
933	char nice[6];
934
935	if (dd == NULL)
936		return;
937
938	ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
939
940	crtime = dd->dd_creation_time;
941	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
942	(void) printf("\t\thead_dataset_obj = %llu\n",
943	    (u_longlong_t)dd->dd_head_dataset_obj);
944	(void) printf("\t\tparent_dir_obj = %llu\n",
945	    (u_longlong_t)dd->dd_parent_obj);
946	(void) printf("\t\torigin_obj = %llu\n",
947	    (u_longlong_t)dd->dd_origin_obj);
948	(void) printf("\t\tchild_dir_zapobj = %llu\n",
949	    (u_longlong_t)dd->dd_child_dir_zapobj);
950	nicenum(dd->dd_used_bytes, nice);
951	(void) printf("\t\tused_bytes = %s\n", nice);
952	nicenum(dd->dd_compressed_bytes, nice);
953	(void) printf("\t\tcompressed_bytes = %s\n", nice);
954	nicenum(dd->dd_uncompressed_bytes, nice);
955	(void) printf("\t\tuncompressed_bytes = %s\n", nice);
956	nicenum(dd->dd_quota, nice);
957	(void) printf("\t\tquota = %s\n", nice);
958	nicenum(dd->dd_reserved, nice);
959	(void) printf("\t\treserved = %s\n", nice);
960	(void) printf("\t\tprops_zapobj = %llu\n",
961	    (u_longlong_t)dd->dd_props_zapobj);
962	(void) printf("\t\tdeleg_zapobj = %llu\n",
963	    (u_longlong_t)dd->dd_deleg_zapobj);
964	(void) printf("\t\tflags = %llx\n",
965	    (u_longlong_t)dd->dd_flags);
966
967#define	DO(which) \
968	nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice); \
969	(void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
970	DO(HEAD);
971	DO(SNAP);
972	DO(CHILD);
973	DO(CHILD_RSRV);
974	DO(REFRSRV);
975#undef DO
976}
977
978/*ARGSUSED*/
979static void
980dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
981{
982	dsl_dataset_phys_t *ds = data;
983	time_t crtime;
984	char used[6], compressed[6], uncompressed[6], unique[6];
985	char blkbuf[BP_SPRINTF_LEN];
986
987	if (ds == NULL)
988		return;
989
990	ASSERT(size == sizeof (*ds));
991	crtime = ds->ds_creation_time;
992	nicenum(ds->ds_used_bytes, used);
993	nicenum(ds->ds_compressed_bytes, compressed);
994	nicenum(ds->ds_uncompressed_bytes, uncompressed);
995	nicenum(ds->ds_unique_bytes, unique);
996	sprintf_blkptr(blkbuf, &ds->ds_bp);
997
998	(void) printf("\t\tdir_obj = %llu\n",
999	    (u_longlong_t)ds->ds_dir_obj);
1000	(void) printf("\t\tprev_snap_obj = %llu\n",
1001	    (u_longlong_t)ds->ds_prev_snap_obj);
1002	(void) printf("\t\tprev_snap_txg = %llu\n",
1003	    (u_longlong_t)ds->ds_prev_snap_txg);
1004	(void) printf("\t\tnext_snap_obj = %llu\n",
1005	    (u_longlong_t)ds->ds_next_snap_obj);
1006	(void) printf("\t\tsnapnames_zapobj = %llu\n",
1007	    (u_longlong_t)ds->ds_snapnames_zapobj);
1008	(void) printf("\t\tnum_children = %llu\n",
1009	    (u_longlong_t)ds->ds_num_children);
1010	(void) printf("\t\tuserrefs_obj = %llu\n",
1011	    (u_longlong_t)ds->ds_userrefs_obj);
1012	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1013	(void) printf("\t\tcreation_txg = %llu\n",
1014	    (u_longlong_t)ds->ds_creation_txg);
1015	(void) printf("\t\tdeadlist_obj = %llu\n",
1016	    (u_longlong_t)ds->ds_deadlist_obj);
1017	(void) printf("\t\tused_bytes = %s\n", used);
1018	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
1019	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1020	(void) printf("\t\tunique = %s\n", unique);
1021	(void) printf("\t\tfsid_guid = %llu\n",
1022	    (u_longlong_t)ds->ds_fsid_guid);
1023	(void) printf("\t\tguid = %llu\n",
1024	    (u_longlong_t)ds->ds_guid);
1025	(void) printf("\t\tflags = %llx\n",
1026	    (u_longlong_t)ds->ds_flags);
1027	(void) printf("\t\tnext_clones_obj = %llu\n",
1028	    (u_longlong_t)ds->ds_next_clones_obj);
1029	(void) printf("\t\tprops_obj = %llu\n",
1030	    (u_longlong_t)ds->ds_props_obj);
1031	(void) printf("\t\tbp = %s\n", blkbuf);
1032}
1033
1034static void
1035dump_bplist(objset_t *mos, uint64_t object, char *name)
1036{
1037	bplist_t bpl = { 0 };
1038	blkptr_t blk, *bp = &blk;
1039	uint64_t itor = 0;
1040	char bytes[6];
1041	char comp[6];
1042	char uncomp[6];
1043
1044	if (dump_opt['d'] < 3)
1045		return;
1046
1047	bplist_init(&bpl);
1048	VERIFY(0 == bplist_open(&bpl, mos, object));
1049	if (bplist_empty(&bpl)) {
1050		bplist_close(&bpl);
1051		bplist_fini(&bpl);
1052		return;
1053	}
1054
1055	nicenum(bpl.bpl_phys->bpl_bytes, bytes);
1056	if (bpl.bpl_dbuf->db_size == sizeof (bplist_phys_t)) {
1057		nicenum(bpl.bpl_phys->bpl_comp, comp);
1058		nicenum(bpl.bpl_phys->bpl_uncomp, uncomp);
1059		(void) printf("\n    %s: %llu entries, %s (%s/%s comp)\n",
1060		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries,
1061		    bytes, comp, uncomp);
1062	} else {
1063		(void) printf("\n    %s: %llu entries, %s\n",
1064		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries, bytes);
1065	}
1066
1067	if (dump_opt['d'] < 5) {
1068		bplist_close(&bpl);
1069		bplist_fini(&bpl);
1070		return;
1071	}
1072
1073	(void) printf("\n");
1074
1075	while (bplist_iterate(&bpl, &itor, bp) == 0) {
1076		char blkbuf[BP_SPRINTF_LEN];
1077
1078		ASSERT(bp->blk_birth != 0);
1079		sprintf_blkptr_compact(blkbuf, bp);
1080		(void) printf("\tItem %3llu: %s\n",
1081		    (u_longlong_t)itor - 1, blkbuf);
1082	}
1083
1084	bplist_close(&bpl);
1085	bplist_fini(&bpl);
1086}
1087
1088static avl_tree_t idx_tree;
1089static avl_tree_t domain_tree;
1090static boolean_t fuid_table_loaded;
1091
1092static void
1093fuid_table_destroy()
1094{
1095	if (fuid_table_loaded) {
1096		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1097		fuid_table_loaded = B_FALSE;
1098	}
1099}
1100
1101/*
1102 * print uid or gid information.
1103 * For normal POSIX id just the id is printed in decimal format.
1104 * For CIFS files with FUID the fuid is printed in hex followed by
1105 * the doman-rid string.
1106 */
1107static void
1108print_idstr(uint64_t id, const char *id_type)
1109{
1110	if (FUID_INDEX(id)) {
1111		char *domain;
1112
1113		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1114		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
1115		    (u_longlong_t)id, domain, (int)FUID_RID(id));
1116	} else {
1117		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1118	}
1119
1120}
1121
1122static void
1123dump_uidgid(objset_t *os, znode_phys_t *zp)
1124{
1125	uint32_t uid_idx, gid_idx;
1126
1127	uid_idx = FUID_INDEX(zp->zp_uid);
1128	gid_idx = FUID_INDEX(zp->zp_gid);
1129
1130	/* Load domain table, if not already loaded */
1131	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1132		uint64_t fuid_obj;
1133
1134		/* first find the fuid object.  It lives in the master node */
1135		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1136		    8, 1, &fuid_obj) == 0);
1137		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1138		(void) zfs_fuid_table_load(os, fuid_obj,
1139		    &idx_tree, &domain_tree);
1140		fuid_table_loaded = B_TRUE;
1141	}
1142
1143	print_idstr(zp->zp_uid, "uid");
1144	print_idstr(zp->zp_gid, "gid");
1145}
1146
1147/*ARGSUSED*/
1148static void
1149dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
1150{
1151	znode_phys_t *zp = data;
1152	time_t z_crtime, z_atime, z_mtime, z_ctime;
1153	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
1154	int error;
1155
1156	ASSERT(size >= sizeof (znode_phys_t));
1157
1158	error = zfs_obj_to_path(os, object, path, sizeof (path));
1159	if (error != 0) {
1160		(void) snprintf(path, sizeof (path), "\?\?\?<object#%llu>",
1161		    (u_longlong_t)object);
1162	}
1163
1164	if (dump_opt['d'] < 3) {
1165		(void) printf("\t%s\n", path);
1166		return;
1167	}
1168
1169	z_crtime = (time_t)zp->zp_crtime[0];
1170	z_atime = (time_t)zp->zp_atime[0];
1171	z_mtime = (time_t)zp->zp_mtime[0];
1172	z_ctime = (time_t)zp->zp_ctime[0];
1173
1174	(void) printf("\tpath	%s\n", path);
1175	dump_uidgid(os, zp);
1176	(void) printf("\tatime	%s", ctime(&z_atime));
1177	(void) printf("\tmtime	%s", ctime(&z_mtime));
1178	(void) printf("\tctime	%s", ctime(&z_ctime));
1179	(void) printf("\tcrtime	%s", ctime(&z_crtime));
1180	(void) printf("\tgen	%llu\n", (u_longlong_t)zp->zp_gen);
1181	(void) printf("\tmode	%llo\n", (u_longlong_t)zp->zp_mode);
1182	(void) printf("\tsize	%llu\n", (u_longlong_t)zp->zp_size);
1183	(void) printf("\tparent	%llu\n", (u_longlong_t)zp->zp_parent);
1184	(void) printf("\tlinks	%llu\n", (u_longlong_t)zp->zp_links);
1185	(void) printf("\txattr	%llu\n", (u_longlong_t)zp->zp_xattr);
1186	(void) printf("\trdev	0x%016llx\n", (u_longlong_t)zp->zp_rdev);
1187}
1188
1189/*ARGSUSED*/
1190static void
1191dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
1192{
1193}
1194
1195/*ARGSUSED*/
1196static void
1197dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
1198{
1199}
1200
1201static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
1202	dump_none,		/* unallocated			*/
1203	dump_zap,		/* object directory		*/
1204	dump_uint64,		/* object array			*/
1205	dump_none,		/* packed nvlist		*/
1206	dump_packed_nvlist,	/* packed nvlist size		*/
1207	dump_none,		/* bplist			*/
1208	dump_none,		/* bplist header		*/
1209	dump_none,		/* SPA space map header		*/
1210	dump_none,		/* SPA space map		*/
1211	dump_none,		/* ZIL intent log		*/
1212	dump_dnode,		/* DMU dnode			*/
1213	dump_dmu_objset,	/* DMU objset			*/
1214	dump_dsl_dir,		/* DSL directory		*/
1215	dump_zap,		/* DSL directory child map	*/
1216	dump_zap,		/* DSL dataset snap map		*/
1217	dump_zap,		/* DSL props			*/
1218	dump_dsl_dataset,	/* DSL dataset			*/
1219	dump_znode,		/* ZFS znode			*/
1220	dump_acl,		/* ZFS V0 ACL			*/
1221	dump_uint8,		/* ZFS plain file		*/
1222	dump_zpldir,		/* ZFS directory		*/
1223	dump_zap,		/* ZFS master node		*/
1224	dump_zap,		/* ZFS delete queue		*/
1225	dump_uint8,		/* zvol object			*/
1226	dump_zap,		/* zvol prop			*/
1227	dump_uint8,		/* other uint8[]		*/
1228	dump_uint64,		/* other uint64[]		*/
1229	dump_zap,		/* other ZAP			*/
1230	dump_zap,		/* persistent error log		*/
1231	dump_uint8,		/* SPA history			*/
1232	dump_uint64,		/* SPA history offsets		*/
1233	dump_zap,		/* Pool properties		*/
1234	dump_zap,		/* DSL permissions		*/
1235	dump_acl,		/* ZFS ACL			*/
1236	dump_uint8,		/* ZFS SYSACL			*/
1237	dump_none,		/* FUID nvlist			*/
1238	dump_packed_nvlist,	/* FUID nvlist size		*/
1239	dump_zap,		/* DSL dataset next clones	*/
1240	dump_zap,		/* DSL scrub queue		*/
1241	dump_zap,		/* ZFS user/group used		*/
1242	dump_zap,		/* ZFS user/group quota		*/
1243	dump_zap,		/* snapshot refcount tags	*/
1244	dump_none,		/* DDT ZAP object		*/
1245	dump_zap,		/* DDT statistics		*/
1246	dump_unknown		/* Unknown type, must be last	*/
1247};
1248
1249static void
1250dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1251{
1252	dmu_buf_t *db = NULL;
1253	dmu_object_info_t doi;
1254	dnode_t *dn;
1255	void *bonus = NULL;
1256	size_t bsize = 0;
1257	char iblk[6], dblk[6], lsize[6], asize[6], bonus_size[6], fill[7];
1258	char aux[50];
1259	int error;
1260
1261	if (*print_header) {
1262		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1263		    "Object", "lvl", "iblk", "dblk", "dsize", "lsize",
1264		    "%full", "type");
1265		*print_header = 0;
1266	}
1267
1268	if (object == 0) {
1269		dn = os->os_meta_dnode;
1270	} else {
1271		error = dmu_bonus_hold(os, object, FTAG, &db);
1272		if (error)
1273			fatal("dmu_bonus_hold(%llu) failed, errno %u",
1274			    object, error);
1275		bonus = db->db_data;
1276		bsize = db->db_size;
1277		dn = ((dmu_buf_impl_t *)db)->db_dnode;
1278	}
1279	dmu_object_info_from_dnode(dn, &doi);
1280
1281	nicenum(doi.doi_metadata_block_size, iblk);
1282	nicenum(doi.doi_data_block_size, dblk);
1283	nicenum(doi.doi_max_offset, lsize);
1284	nicenum(doi.doi_physical_blocks_512 << 9, asize);
1285	nicenum(doi.doi_bonus_size, bonus_size);
1286	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
1287	    doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
1288	    doi.doi_max_offset);
1289
1290	aux[0] = '\0';
1291
1292	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1293		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1294		    ZDB_CHECKSUM_NAME(doi.doi_checksum));
1295	}
1296
1297	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1298		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1299		    ZDB_COMPRESS_NAME(doi.doi_compress));
1300	}
1301
1302	(void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %6s  %s%s\n",
1303	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
1304	    asize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
1305
1306	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1307		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1308		    "", "", "", "", "", bonus_size, "bonus",
1309		    ZDB_OT_NAME(doi.doi_bonus_type));
1310	}
1311
1312	if (verbosity >= 4) {
1313		(void) printf("\tdnode flags: %s%s\n",
1314		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
1315		    "USED_BYTES " : "",
1316		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
1317		    "USERUSED_ACCOUNTED " : "");
1318		(void) printf("\tdnode maxblkid: %llu\n",
1319		    (longlong_t)dn->dn_phys->dn_maxblkid);
1320
1321		object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os, object,
1322		    bonus, bsize);
1323		object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object, NULL, 0);
1324		*print_header = 1;
1325	}
1326
1327	if (verbosity >= 5)
1328		dump_indirect(dn);
1329
1330	if (verbosity >= 5) {
1331		/*
1332		 * Report the list of segments that comprise the object.
1333		 */
1334		uint64_t start = 0;
1335		uint64_t end;
1336		uint64_t blkfill = 1;
1337		int minlvl = 1;
1338
1339		if (dn->dn_type == DMU_OT_DNODE) {
1340			minlvl = 0;
1341			blkfill = DNODES_PER_BLOCK;
1342		}
1343
1344		for (;;) {
1345			char segsize[6];
1346			error = dnode_next_offset(dn,
1347			    0, &start, minlvl, blkfill, 0);
1348			if (error)
1349				break;
1350			end = start;
1351			error = dnode_next_offset(dn,
1352			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
1353			nicenum(end - start, segsize);
1354			(void) printf("\t\tsegment [%016llx, %016llx)"
1355			    " size %5s\n", (u_longlong_t)start,
1356			    (u_longlong_t)end, segsize);
1357			if (error)
1358				break;
1359			start = end;
1360		}
1361	}
1362
1363	if (db != NULL)
1364		dmu_buf_rele(db, FTAG);
1365}
1366
1367static char *objset_types[DMU_OST_NUMTYPES] = {
1368	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1369
1370static void
1371dump_dir(objset_t *os)
1372{
1373	dmu_objset_stats_t dds;
1374	uint64_t object, object_count;
1375	uint64_t refdbytes, usedobjs, scratch;
1376	char numbuf[8];
1377	char blkbuf[BP_SPRINTF_LEN + 20];
1378	char osname[MAXNAMELEN];
1379	char *type = "UNKNOWN";
1380	int verbosity = dump_opt['d'];
1381	int print_header = 1;
1382	int i, error;
1383
1384	dmu_objset_fast_stat(os, &dds);
1385
1386	if (dds.dds_type < DMU_OST_NUMTYPES)
1387		type = objset_types[dds.dds_type];
1388
1389	if (dds.dds_type == DMU_OST_META) {
1390		dds.dds_creation_txg = TXG_INITIAL;
1391		usedobjs = os->os_rootbp->blk_fill;
1392		refdbytes = os->os_spa->spa_dsl_pool->
1393		    dp_mos_dir->dd_phys->dd_used_bytes;
1394	} else {
1395		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
1396	}
1397
1398	ASSERT3U(usedobjs, ==, os->os_rootbp->blk_fill);
1399
1400	nicenum(refdbytes, numbuf);
1401
1402	if (verbosity >= 4) {
1403		(void) sprintf(blkbuf, ", rootbp ");
1404		(void) sprintf_blkptr(blkbuf + strlen(blkbuf), os->os_rootbp);
1405	} else {
1406		blkbuf[0] = '\0';
1407	}
1408
1409	dmu_objset_name(os, osname);
1410
1411	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
1412	    "%s, %llu objects%s\n",
1413	    osname, type, (u_longlong_t)dmu_objset_id(os),
1414	    (u_longlong_t)dds.dds_creation_txg,
1415	    numbuf, (u_longlong_t)usedobjs, blkbuf);
1416
1417	if (zopt_objects != 0) {
1418		for (i = 0; i < zopt_objects; i++)
1419			dump_object(os, zopt_object[i], verbosity,
1420			    &print_header);
1421		(void) printf("\n");
1422		return;
1423	}
1424
1425	if (dump_opt['i'] != 0 || verbosity >= 2)
1426		dump_intent_log(dmu_objset_zil(os));
1427
1428	if (dmu_objset_ds(os) != NULL)
1429		dump_bplist(dmu_objset_pool(os)->dp_meta_objset,
1430		    dmu_objset_ds(os)->ds_phys->ds_deadlist_obj, "Deadlist");
1431
1432	if (verbosity < 2)
1433		return;
1434
1435	if (os->os_rootbp->blk_birth == 0)
1436		return;
1437
1438	dump_object(os, 0, verbosity, &print_header);
1439	object_count = 0;
1440	if (os->os_userused_dnode &&
1441	    os->os_userused_dnode->dn_type != 0) {
1442		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header);
1443		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header);
1444	}
1445
1446	object = 0;
1447	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1448		dump_object(os, object, verbosity, &print_header);
1449		object_count++;
1450	}
1451
1452	ASSERT3U(object_count, ==, usedobjs);
1453
1454	(void) printf("\n");
1455
1456	if (error != ESRCH) {
1457		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
1458		abort();
1459	}
1460}
1461
1462static void
1463dump_uberblock(uberblock_t *ub)
1464{
1465	time_t timestamp = ub->ub_timestamp;
1466
1467	(void) printf("\nUberblock:\n");
1468	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
1469	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
1470	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
1471	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
1472	(void) printf("\ttimestamp = %llu UTC = %s",
1473	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
1474	if (dump_opt['u'] >= 3) {
1475		char blkbuf[BP_SPRINTF_LEN];
1476		sprintf_blkptr(blkbuf, &ub->ub_rootbp);
1477		(void) printf("\trootbp = %s\n", blkbuf);
1478	}
1479	(void) printf("\n");
1480}
1481
1482static void
1483dump_config(spa_t *spa)
1484{
1485	dmu_buf_t *db;
1486	size_t nvsize = 0;
1487	int error = 0;
1488
1489
1490	error = dmu_bonus_hold(spa->spa_meta_objset,
1491	    spa->spa_config_object, FTAG, &db);
1492
1493	if (error == 0) {
1494		nvsize = *(uint64_t *)db->db_data;
1495		dmu_buf_rele(db, FTAG);
1496
1497		(void) printf("\nMOS Configuration:\n");
1498		dump_packed_nvlist(spa->spa_meta_objset,
1499		    spa->spa_config_object, (void *)&nvsize, 1);
1500	} else {
1501		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
1502		    (u_longlong_t)spa->spa_config_object, error);
1503	}
1504}
1505
1506static void
1507dump_cachefile(const char *cachefile)
1508{
1509	int fd;
1510	struct stat64 statbuf;
1511	char *buf;
1512	nvlist_t *config;
1513
1514	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
1515		(void) printf("cannot open '%s': %s\n", cachefile,
1516		    strerror(errno));
1517		exit(1);
1518	}
1519
1520	if (fstat64(fd, &statbuf) != 0) {
1521		(void) printf("failed to stat '%s': %s\n", cachefile,
1522		    strerror(errno));
1523		exit(1);
1524	}
1525
1526	if ((buf = malloc(statbuf.st_size)) == NULL) {
1527		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
1528		    (u_longlong_t)statbuf.st_size);
1529		exit(1);
1530	}
1531
1532	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1533		(void) fprintf(stderr, "failed to read %llu bytes\n",
1534		    (u_longlong_t)statbuf.st_size);
1535		exit(1);
1536	}
1537
1538	(void) close(fd);
1539
1540	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
1541		(void) fprintf(stderr, "failed to unpack nvlist\n");
1542		exit(1);
1543	}
1544
1545	free(buf);
1546
1547	dump_nvlist(config, 0);
1548
1549	nvlist_free(config);
1550}
1551
1552static void
1553dump_label(const char *dev)
1554{
1555	int fd;
1556	vdev_label_t label;
1557	char *buf = label.vl_vdev_phys.vp_nvlist;
1558	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1559	struct stat64 statbuf;
1560	uint64_t psize;
1561	int l;
1562
1563	if ((fd = open64(dev, O_RDONLY)) < 0) {
1564		(void) printf("cannot open '%s': %s\n", dev, strerror(errno));
1565		exit(1);
1566	}
1567
1568	if (fstat64(fd, &statbuf) != 0) {
1569		(void) printf("failed to stat '%s': %s\n", dev,
1570		    strerror(errno));
1571		exit(1);
1572	}
1573
1574	psize = statbuf.st_size;
1575	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
1576
1577	for (l = 0; l < VDEV_LABELS; l++) {
1578
1579		nvlist_t *config = NULL;
1580
1581		(void) printf("--------------------------------------------\n");
1582		(void) printf("LABEL %d\n", l);
1583		(void) printf("--------------------------------------------\n");
1584
1585		if (pread64(fd, &label, sizeof (label),
1586		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
1587			(void) printf("failed to read label %d\n", l);
1588			continue;
1589		}
1590
1591		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
1592			(void) printf("failed to unpack label %d\n", l);
1593			continue;
1594		}
1595		dump_nvlist(config, 4);
1596		nvlist_free(config);
1597	}
1598}
1599
1600/*ARGSUSED*/
1601static int
1602dump_one_dir(char *dsname, void *arg)
1603{
1604	int error;
1605	objset_t *os;
1606
1607	error = dmu_objset_own(dsname, DMU_OST_ANY, B_TRUE, FTAG, &os);
1608	if (error) {
1609		(void) printf("Could not open %s, error %d\n", dsname, error);
1610		return (0);
1611	}
1612	dump_dir(os);
1613	dmu_objset_disown(os, FTAG);
1614	fuid_table_destroy();
1615	return (0);
1616}
1617
1618/*
1619 * Block statistics.
1620 */
1621typedef struct zdb_blkstats {
1622	uint64_t	zb_asize;
1623	uint64_t	zb_lsize;
1624	uint64_t	zb_psize;
1625	uint64_t	zb_count;
1626} zdb_blkstats_t;
1627
1628/*
1629 * Extended object types to report deferred frees and dedup auto-ditto blocks.
1630 */
1631#define	ZDB_OT_DEFERRED	(DMU_OT_NUMTYPES + 0)
1632#define	ZDB_OT_DITTO	(DMU_OT_NUMTYPES + 1)
1633#define	ZDB_OT_TOTAL	(DMU_OT_NUMTYPES + 2)
1634
1635static char *zdb_ot_extname[] = {
1636	"deferred free",
1637	"dedup ditto",
1638	"Total",
1639};
1640
1641#define	ZB_TOTAL	DN_MAX_LEVELS
1642
1643typedef struct zdb_cb {
1644	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
1645	uint64_t	zcb_dedup_asize;
1646	uint64_t	zcb_dedup_blocks;
1647	uint64_t	zcb_errors[256];
1648	int		zcb_readfails;
1649	int		zcb_haderrors;
1650} zdb_cb_t;
1651
1652static void
1653zdb_count_block(spa_t *spa, zilog_t *zilog, zdb_cb_t *zcb, const blkptr_t *bp,
1654    dmu_object_type_t type)
1655{
1656	uint64_t refcnt = 0;
1657
1658	ASSERT(type < ZDB_OT_TOTAL);
1659
1660	if (zilog && zil_bp_tree_add(zilog, bp) != 0)
1661		return;
1662
1663	for (int i = 0; i < 4; i++) {
1664		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
1665		int t = (i & 1) ? type : ZDB_OT_TOTAL;
1666		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
1667
1668		zb->zb_asize += BP_GET_ASIZE(bp);
1669		zb->zb_lsize += BP_GET_LSIZE(bp);
1670		zb->zb_psize += BP_GET_PSIZE(bp);
1671		zb->zb_count++;
1672	}
1673
1674	if (dump_opt['L'])
1675		return;
1676
1677	if (BP_GET_DEDUP(bp)) {
1678		ddt_t *ddt;
1679		ddt_entry_t *dde;
1680
1681		ddt = ddt_select(spa, bp);
1682		ddt_enter(ddt);
1683		dde = ddt_lookup(ddt, bp, B_FALSE);
1684
1685		if (dde == NULL) {
1686			refcnt = 0;
1687		} else {
1688			ddt_phys_t *ddp = ddt_phys_select(dde, bp);
1689			ddt_phys_decref(ddp);
1690			refcnt = ddp->ddp_refcnt;
1691			if (ddt_phys_total_refcnt(dde) == 0)
1692				ddt_remove(ddt, dde);
1693		}
1694		ddt_exit(ddt);
1695	}
1696
1697	VERIFY3U(zio_wait(zio_claim(NULL, spa,
1698	    refcnt ? 0 : spa_first_txg(spa),
1699	    bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
1700}
1701
1702static int
1703zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1704    const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
1705{
1706	zdb_cb_t *zcb = arg;
1707	char blkbuf[BP_SPRINTF_LEN];
1708	dmu_object_type_t type;
1709	boolean_t is_metadata;
1710
1711	if (bp == NULL)
1712		return (0);
1713
1714	type = BP_GET_TYPE(bp);
1715
1716	zdb_count_block(spa, zilog, zcb, bp, type);
1717
1718	is_metadata = (BP_GET_LEVEL(bp) != 0 || dmu_ot[type].ot_metadata);
1719
1720	if (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata)) {
1721		int ioerr;
1722		size_t size = BP_GET_PSIZE(bp);
1723		void *data = malloc(size);
1724		int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
1725
1726		/* If it's an intent log block, failure is expected. */
1727		if (zb->zb_level == ZB_ZIL_LEVEL)
1728			flags |= ZIO_FLAG_SPECULATIVE;
1729
1730		ioerr = zio_wait(zio_read(NULL, spa, bp, data, size,
1731		    NULL, NULL, ZIO_PRIORITY_ASYNC_READ, flags, zb));
1732
1733		free(data);
1734
1735		if (ioerr && !(flags & ZIO_FLAG_SPECULATIVE)) {
1736			zcb->zcb_haderrors = 1;
1737			zcb->zcb_errors[ioerr]++;
1738
1739			if (dump_opt['b'] >= 2)
1740				sprintf_blkptr(blkbuf, bp);
1741			else
1742				blkbuf[0] = '\0';
1743
1744			(void) printf("zdb_blkptr_cb: "
1745			    "Got error %d reading "
1746			    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
1747			    ioerr,
1748			    (u_longlong_t)zb->zb_objset,
1749			    (u_longlong_t)zb->zb_object,
1750			    (u_longlong_t)zb->zb_level,
1751			    (u_longlong_t)zb->zb_blkid,
1752			    blkbuf);
1753		}
1754	}
1755
1756	zcb->zcb_readfails = 0;
1757
1758	if (dump_opt['b'] >= 4) {
1759		sprintf_blkptr(blkbuf, bp);
1760		(void) printf("objset %llu object %llu "
1761		    "level %lld offset 0x%llx %s\n",
1762		    (u_longlong_t)zb->zb_objset,
1763		    (u_longlong_t)zb->zb_object,
1764		    (longlong_t)zb->zb_level,
1765		    (u_longlong_t)blkid2offset(dnp, bp, zb),
1766		    blkbuf);
1767	}
1768
1769	return (0);
1770}
1771
1772static void
1773zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
1774{
1775	vdev_t *vd = sm->sm_ppd;
1776
1777	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
1778	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
1779}
1780
1781/* ARGSUSED */
1782static void
1783zdb_space_map_load(space_map_t *sm)
1784{
1785}
1786
1787static void
1788zdb_space_map_unload(space_map_t *sm)
1789{
1790	space_map_vacate(sm, zdb_leak, sm);
1791}
1792
1793/* ARGSUSED */
1794static void
1795zdb_space_map_claim(space_map_t *sm, uint64_t start, uint64_t size)
1796{
1797}
1798
1799static space_map_ops_t zdb_space_map_ops = {
1800	zdb_space_map_load,
1801	zdb_space_map_unload,
1802	NULL,	/* alloc */
1803	zdb_space_map_claim,
1804	NULL,	/* free */
1805	NULL	/* maxsize */
1806};
1807
1808static void
1809zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
1810{
1811	ddt_bookmark_t ddb = { 0 };
1812	ddt_entry_t dde;
1813	int error;
1814
1815	while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
1816		blkptr_t blk;
1817		ddt_phys_t *ddp = dde.dde_phys;
1818
1819		if (ddb.ddb_class == DDT_CLASS_UNIQUE)
1820			return;
1821
1822		ASSERT(ddt_phys_total_refcnt(&dde) > 1);
1823
1824		for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1825			if (ddp->ddp_phys_birth == 0)
1826				continue;
1827			ddt_bp_create(ddb.ddb_checksum,
1828			    &dde.dde_key, ddp, &blk);
1829			if (p == DDT_PHYS_DITTO) {
1830				zdb_count_block(spa, NULL, zcb, &blk,
1831				    ZDB_OT_DITTO);
1832			} else {
1833				zcb->zcb_dedup_asize +=
1834				    BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
1835				zcb->zcb_dedup_blocks++;
1836			}
1837		}
1838		if (!dump_opt['L']) {
1839			ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
1840			ddt_enter(ddt);
1841			VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
1842			ddt_exit(ddt);
1843		}
1844	}
1845
1846	ASSERT(error == ENOENT);
1847}
1848
1849static void
1850zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
1851{
1852	if (!dump_opt['L']) {
1853		vdev_t *rvd = spa->spa_root_vdev;
1854		for (int c = 0; c < rvd->vdev_children; c++) {
1855			vdev_t *vd = rvd->vdev_child[c];
1856			for (int m = 0; m < vd->vdev_ms_count; m++) {
1857				metaslab_t *msp = vd->vdev_ms[m];
1858				mutex_enter(&msp->ms_lock);
1859				space_map_unload(&msp->ms_map);
1860				VERIFY(space_map_load(&msp->ms_map,
1861				    &zdb_space_map_ops, SM_ALLOC, &msp->ms_smo,
1862				    spa->spa_meta_objset) == 0);
1863				msp->ms_map.sm_ppd = vd;
1864				mutex_exit(&msp->ms_lock);
1865			}
1866		}
1867	}
1868
1869	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1870
1871	zdb_ddt_leak_init(spa, zcb);
1872
1873	spa_config_exit(spa, SCL_CONFIG, FTAG);
1874}
1875
1876static void
1877zdb_leak_fini(spa_t *spa)
1878{
1879	if (!dump_opt['L']) {
1880		vdev_t *rvd = spa->spa_root_vdev;
1881		for (int c = 0; c < rvd->vdev_children; c++) {
1882			vdev_t *vd = rvd->vdev_child[c];
1883			for (int m = 0; m < vd->vdev_ms_count; m++) {
1884				metaslab_t *msp = vd->vdev_ms[m];
1885				mutex_enter(&msp->ms_lock);
1886				space_map_unload(&msp->ms_map);
1887				mutex_exit(&msp->ms_lock);
1888			}
1889		}
1890	}
1891}
1892
1893static int
1894dump_block_stats(spa_t *spa)
1895{
1896	zdb_cb_t zcb = { 0 };
1897	zdb_blkstats_t *zb, *tzb;
1898	uint64_t norm_alloc, norm_space, total_alloc, total_found;
1899	int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA;
1900	int leaks = 0;
1901
1902	(void) printf("\nTraversing all blocks %s%s%s%s%s...\n",
1903	    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
1904	    (dump_opt['c'] == 1) ? "metadata " : "",
1905	    dump_opt['c'] ? "checksums " : "",
1906	    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
1907	    !dump_opt['L'] ? "nothing leaked " : "");
1908
1909	/*
1910	 * Load all space maps as SM_ALLOC maps, then traverse the pool
1911	 * claiming each block we discover.  If the pool is perfectly
1912	 * consistent, the space maps will be empty when we're done.
1913	 * Anything left over is a leak; any block we can't claim (because
1914	 * it's not part of any space map) is a double allocation,
1915	 * reference to a freed block, or an unclaimed log block.
1916	 */
1917	zdb_leak_init(spa, &zcb);
1918
1919	/*
1920	 * If there's a deferred-free bplist, process that first.
1921	 */
1922	if (spa->spa_deferred_bplist_obj != 0) {
1923		bplist_t *bpl = &spa->spa_deferred_bplist;
1924		blkptr_t blk;
1925		uint64_t itor = 0;
1926
1927		VERIFY(0 == bplist_open(bpl, spa->spa_meta_objset,
1928		    spa->spa_deferred_bplist_obj));
1929
1930		while (bplist_iterate(bpl, &itor, &blk) == 0) {
1931			if (dump_opt['b'] >= 4) {
1932				char blkbuf[BP_SPRINTF_LEN];
1933				sprintf_blkptr(blkbuf, &blk);
1934				(void) printf("[%s] %s\n",
1935				    "deferred free", blkbuf);
1936			}
1937			zdb_count_block(spa, NULL, &zcb, &blk, ZDB_OT_DEFERRED);
1938		}
1939
1940		bplist_close(bpl);
1941	}
1942
1943	if (dump_opt['c'] > 1)
1944		flags |= TRAVERSE_PREFETCH_DATA;
1945
1946	zcb.zcb_haderrors |= traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
1947
1948	if (zcb.zcb_haderrors) {
1949		(void) printf("\nError counts:\n\n");
1950		(void) printf("\t%5s  %s\n", "errno", "count");
1951		for (int e = 0; e < 256; e++) {
1952			if (zcb.zcb_errors[e] != 0) {
1953				(void) printf("\t%5d  %llu\n",
1954				    e, (u_longlong_t)zcb.zcb_errors[e]);
1955			}
1956		}
1957	}
1958
1959	/*
1960	 * Report any leaked segments.
1961	 */
1962	zdb_leak_fini(spa);
1963
1964	tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
1965
1966	norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
1967	norm_space = metaslab_class_get_space(spa_normal_class(spa));
1968
1969	total_alloc = norm_alloc + metaslab_class_get_alloc(spa_log_class(spa));
1970	total_found = tzb->zb_asize - zcb.zcb_dedup_asize;
1971
1972	if (total_found == total_alloc) {
1973		if (!dump_opt['L'])
1974			(void) printf("\n\tNo leaks (block sum matches space"
1975			    " maps exactly)\n");
1976	} else {
1977		(void) printf("block traversal size %llu != alloc %llu "
1978		    "(%s %lld)\n",
1979		    (u_longlong_t)total_found,
1980		    (u_longlong_t)total_alloc,
1981		    (dump_opt['L']) ? "unreachable" : "leaked",
1982		    (longlong_t)(total_alloc - total_found));
1983		leaks = 1;
1984	}
1985
1986	if (tzb->zb_count == 0)
1987		return (2);
1988
1989	(void) printf("\n");
1990	(void) printf("\tbp count:      %10llu\n",
1991	    (u_longlong_t)tzb->zb_count);
1992	(void) printf("\tbp logical:    %10llu      avg: %6llu\n",
1993	    (u_longlong_t)tzb->zb_lsize,
1994	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
1995	(void) printf("\tbp physical:   %10llu      avg:"
1996	    " %6llu     compression: %6.2f\n",
1997	    (u_longlong_t)tzb->zb_psize,
1998	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
1999	    (double)tzb->zb_lsize / tzb->zb_psize);
2000	(void) printf("\tbp allocated:  %10llu      avg:"
2001	    " %6llu     compression: %6.2f\n",
2002	    (u_longlong_t)tzb->zb_asize,
2003	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
2004	    (double)tzb->zb_lsize / tzb->zb_asize);
2005	(void) printf("\tbp deduped:    %10llu    ref>1:"
2006	    " %6llu   deduplication: %6.2f\n",
2007	    (u_longlong_t)zcb.zcb_dedup_asize,
2008	    (u_longlong_t)zcb.zcb_dedup_blocks,
2009	    (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
2010	(void) printf("\tSPA allocated: %10llu     used: %5.2f%%\n",
2011	    (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
2012
2013	if (dump_opt['b'] >= 2) {
2014		int l, t, level;
2015		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
2016		    "\t  avg\t comp\t%%Total\tType\n");
2017
2018		for (t = 0; t <= ZDB_OT_TOTAL; t++) {
2019			char csize[6], lsize[6], psize[6], asize[6], avg[6];
2020			char *typename;
2021
2022			if (t < DMU_OT_NUMTYPES)
2023				typename = dmu_ot[t].ot_name;
2024			else
2025				typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
2026
2027			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
2028				(void) printf("%6s\t%5s\t%5s\t%5s"
2029				    "\t%5s\t%5s\t%6s\t%s\n",
2030				    "-",
2031				    "-",
2032				    "-",
2033				    "-",
2034				    "-",
2035				    "-",
2036				    "-",
2037				    typename);
2038				continue;
2039			}
2040
2041			for (l = ZB_TOTAL - 1; l >= -1; l--) {
2042				level = (l == -1 ? ZB_TOTAL : l);
2043				zb = &zcb.zcb_type[level][t];
2044
2045				if (zb->zb_asize == 0)
2046					continue;
2047
2048				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
2049					continue;
2050
2051				if (level == 0 && zb->zb_asize ==
2052				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
2053					continue;
2054
2055				nicenum(zb->zb_count, csize);
2056				nicenum(zb->zb_lsize, lsize);
2057				nicenum(zb->zb_psize, psize);
2058				nicenum(zb->zb_asize, asize);
2059				nicenum(zb->zb_asize / zb->zb_count, avg);
2060
2061				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
2062				    "\t%5.2f\t%6.2f\t",
2063				    csize, lsize, psize, asize, avg,
2064				    (double)zb->zb_lsize / zb->zb_psize,
2065				    100.0 * zb->zb_asize / tzb->zb_asize);
2066
2067				if (level == ZB_TOTAL)
2068					(void) printf("%s\n", typename);
2069				else
2070					(void) printf("    L%d %s\n",
2071					    level, typename);
2072			}
2073		}
2074	}
2075
2076	(void) printf("\n");
2077
2078	if (leaks)
2079		return (2);
2080
2081	if (zcb.zcb_haderrors)
2082		return (3);
2083
2084	return (0);
2085}
2086
2087typedef struct zdb_ddt_entry {
2088	ddt_key_t	zdde_key;
2089	uint64_t	zdde_ref_blocks;
2090	uint64_t	zdde_ref_lsize;
2091	uint64_t	zdde_ref_psize;
2092	uint64_t	zdde_ref_dsize;
2093	avl_node_t	zdde_node;
2094} zdb_ddt_entry_t;
2095
2096/* ARGSUSED */
2097static int
2098zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2099    const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
2100{
2101	avl_tree_t *t = arg;
2102	avl_index_t where;
2103	zdb_ddt_entry_t *zdde, zdde_search;
2104
2105	if (bp == NULL)
2106		return (0);
2107
2108	if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
2109		(void) printf("traversing objset %llu, %llu objects, "
2110		    "%lu blocks so far\n",
2111		    (u_longlong_t)zb->zb_objset,
2112		    (u_longlong_t)bp->blk_fill,
2113		    avl_numnodes(t));
2114	}
2115
2116	if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
2117	    BP_GET_LEVEL(bp) > 0 || dmu_ot[BP_GET_TYPE(bp)].ot_metadata)
2118		return (0);
2119
2120	ddt_key_fill(&zdde_search.zdde_key, bp);
2121
2122	zdde = avl_find(t, &zdde_search, &where);
2123
2124	if (zdde == NULL) {
2125		zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
2126		zdde->zdde_key = zdde_search.zdde_key;
2127		avl_insert(t, zdde, where);
2128	}
2129
2130	zdde->zdde_ref_blocks += 1;
2131	zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
2132	zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
2133	zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
2134
2135	return (0);
2136}
2137
2138static void
2139dump_simulated_ddt(spa_t *spa)
2140{
2141	avl_tree_t t;
2142	void *cookie = NULL;
2143	zdb_ddt_entry_t *zdde;
2144	ddt_histogram_t ddh_total = { 0 };
2145	ddt_stat_t dds_total = { 0 };
2146
2147	avl_create(&t, ddt_entry_compare,
2148	    sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
2149
2150	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2151
2152	(void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2153	    zdb_ddt_add_cb, &t);
2154
2155	spa_config_exit(spa, SCL_CONFIG, FTAG);
2156
2157	while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
2158		ddt_stat_t dds;
2159		uint64_t refcnt = zdde->zdde_ref_blocks;
2160		ASSERT(refcnt != 0);
2161
2162		dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
2163		dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
2164		dds.dds_psize = zdde->zdde_ref_psize / refcnt;
2165		dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
2166
2167		dds.dds_ref_blocks = zdde->zdde_ref_blocks;
2168		dds.dds_ref_lsize = zdde->zdde_ref_lsize;
2169		dds.dds_ref_psize = zdde->zdde_ref_psize;
2170		dds.dds_ref_dsize = zdde->zdde_ref_dsize;
2171
2172		ddt_stat_add(&ddh_total.ddh_stat[highbit(refcnt) - 1], &dds, 0);
2173
2174		umem_free(zdde, sizeof (*zdde));
2175	}
2176
2177	avl_destroy(&t);
2178
2179	ddt_histogram_stat(&dds_total, &ddh_total);
2180
2181	(void) printf("Simulated DDT histogram:\n");
2182
2183	zpool_dump_ddt(&dds_total, &ddh_total);
2184
2185	dump_dedup_ratio(&dds_total);
2186}
2187
2188static void
2189dump_zpool(spa_t *spa)
2190{
2191	dsl_pool_t *dp = spa_get_dsl(spa);
2192	int rc = 0;
2193
2194	if (dump_opt['S']) {
2195		dump_simulated_ddt(spa);
2196		return;
2197	}
2198
2199	if (!dump_opt['e'] && dump_opt['C'] > 1) {
2200		(void) printf("\nCached configuration:\n");
2201		dump_nvlist(spa->spa_config, 8);
2202	}
2203
2204	if (dump_opt['C'])
2205		dump_config(spa);
2206
2207	if (dump_opt['u'])
2208		dump_uberblock(&spa->spa_uberblock);
2209
2210	if (dump_opt['D'])
2211		dump_all_ddts(spa);
2212
2213	if (dump_opt['d'] > 2 || dump_opt['m'])
2214		dump_metaslabs(spa);
2215
2216	if (dump_opt['d'] || dump_opt['i']) {
2217		dump_dir(dp->dp_meta_objset);
2218		if (dump_opt['d'] >= 3) {
2219			dump_bplist(dp->dp_meta_objset,
2220			    spa->spa_deferred_bplist_obj, "Deferred frees");
2221			dump_dtl(spa->spa_root_vdev, 0);
2222		}
2223		(void) dmu_objset_find(spa_name(spa), dump_one_dir,
2224		    NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
2225	}
2226	if (dump_opt['b'] || dump_opt['c'])
2227		rc = dump_block_stats(spa);
2228
2229	if (dump_opt['s'])
2230		show_pool_stats(spa);
2231
2232	if (dump_opt['h'])
2233		dump_history(spa);
2234
2235	if (rc != 0)
2236		exit(rc);
2237}
2238
2239#define	ZDB_FLAG_CHECKSUM	0x0001
2240#define	ZDB_FLAG_DECOMPRESS	0x0002
2241#define	ZDB_FLAG_BSWAP		0x0004
2242#define	ZDB_FLAG_GBH		0x0008
2243#define	ZDB_FLAG_INDIRECT	0x0010
2244#define	ZDB_FLAG_PHYS		0x0020
2245#define	ZDB_FLAG_RAW		0x0040
2246#define	ZDB_FLAG_PRINT_BLKPTR	0x0080
2247
2248int flagbits[256];
2249
2250static void
2251zdb_print_blkptr(blkptr_t *bp, int flags)
2252{
2253	char blkbuf[BP_SPRINTF_LEN];
2254
2255	if (flags & ZDB_FLAG_BSWAP)
2256		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
2257
2258	sprintf_blkptr(blkbuf, bp);
2259	(void) printf("%s\n", blkbuf);
2260}
2261
2262static void
2263zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
2264{
2265	int i;
2266
2267	for (i = 0; i < nbps; i++)
2268		zdb_print_blkptr(&bp[i], flags);
2269}
2270
2271static void
2272zdb_dump_gbh(void *buf, int flags)
2273{
2274	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
2275}
2276
2277static void
2278zdb_dump_block_raw(void *buf, uint64_t size, int flags)
2279{
2280	if (flags & ZDB_FLAG_BSWAP)
2281		byteswap_uint64_array(buf, size);
2282	(void) write(1, buf, size);
2283}
2284
2285static void
2286zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
2287{
2288	uint64_t *d = (uint64_t *)buf;
2289	int nwords = size / sizeof (uint64_t);
2290	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
2291	int i, j;
2292	char *hdr, *c;
2293
2294
2295	if (do_bswap)
2296		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
2297	else
2298		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
2299
2300	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
2301
2302	for (i = 0; i < nwords; i += 2) {
2303		(void) printf("%06llx:  %016llx  %016llx  ",
2304		    (u_longlong_t)(i * sizeof (uint64_t)),
2305		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
2306		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
2307
2308		c = (char *)&d[i];
2309		for (j = 0; j < 2 * sizeof (uint64_t); j++)
2310			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
2311		(void) printf("\n");
2312	}
2313}
2314
2315/*
2316 * There are two acceptable formats:
2317 *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
2318 *	child[.child]*    - For example: 0.1.1
2319 *
2320 * The second form can be used to specify arbitrary vdevs anywhere
2321 * in the heirarchy.  For example, in a pool with a mirror of
2322 * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
2323 */
2324static vdev_t *
2325zdb_vdev_lookup(vdev_t *vdev, char *path)
2326{
2327	char *s, *p, *q;
2328	int i;
2329
2330	if (vdev == NULL)
2331		return (NULL);
2332
2333	/* First, assume the x.x.x.x format */
2334	i = (int)strtoul(path, &s, 10);
2335	if (s == path || (s && *s != '.' && *s != '\0'))
2336		goto name;
2337	if (i < 0 || i >= vdev->vdev_children)
2338		return (NULL);
2339
2340	vdev = vdev->vdev_child[i];
2341	if (*s == '\0')
2342		return (vdev);
2343	return (zdb_vdev_lookup(vdev, s+1));
2344
2345name:
2346	for (i = 0; i < vdev->vdev_children; i++) {
2347		vdev_t *vc = vdev->vdev_child[i];
2348
2349		if (vc->vdev_path == NULL) {
2350			vc = zdb_vdev_lookup(vc, path);
2351			if (vc == NULL)
2352				continue;
2353			else
2354				return (vc);
2355		}
2356
2357		p = strrchr(vc->vdev_path, '/');
2358		p = p ? p + 1 : vc->vdev_path;
2359		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2360
2361		if (strcmp(vc->vdev_path, path) == 0)
2362			return (vc);
2363		if (strcmp(p, path) == 0)
2364			return (vc);
2365		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2366			return (vc);
2367	}
2368
2369	return (NULL);
2370}
2371
2372/*
2373 * Read a block from a pool and print it out.  The syntax of the
2374 * block descriptor is:
2375 *
2376 *	pool:vdev_specifier:offset:size[:flags]
2377 *
2378 *	pool           - The name of the pool you wish to read from
2379 *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2380 *	offset         - offset, in hex, in bytes
2381 *	size           - Amount of data to read, in hex, in bytes
2382 *	flags          - A string of characters specifying options
2383 *		 b: Decode a blkptr at given offset within block
2384 *		*c: Calculate and display checksums
2385 *		 d: Decompress data before dumping
2386 *		 e: Byteswap data before dumping
2387 *		 g: Display data as a gang block header
2388 *		 i: Display as an indirect block
2389 *		 p: Do I/O to physical offset
2390 *		 r: Dump raw data to stdout
2391 *
2392 *              * = not yet implemented
2393 */
2394static void
2395zdb_read_block(char *thing, spa_t *spa)
2396{
2397	blkptr_t blk, *bp = &blk;
2398	dva_t *dva = bp->blk_dva;
2399	int flags = 0;
2400	uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
2401	zio_t *zio;
2402	vdev_t *vd;
2403	void *pbuf, *lbuf, *buf;
2404	char *s, *p, *dup, *vdev, *flagstr;
2405	int i, error;
2406
2407	dup = strdup(thing);
2408	s = strtok(dup, ":");
2409	vdev = s ? s : "";
2410	s = strtok(NULL, ":");
2411	offset = strtoull(s ? s : "", NULL, 16);
2412	s = strtok(NULL, ":");
2413	size = strtoull(s ? s : "", NULL, 16);
2414	s = strtok(NULL, ":");
2415	flagstr = s ? s : "";
2416
2417	s = NULL;
2418	if (size == 0)
2419		s = "size must not be zero";
2420	if (!IS_P2ALIGNED(size, DEV_BSIZE))
2421		s = "size must be a multiple of sector size";
2422	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
2423		s = "offset must be a multiple of sector size";
2424	if (s) {
2425		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
2426		free(dup);
2427		return;
2428	}
2429
2430	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
2431		for (i = 0; flagstr[i]; i++) {
2432			int bit = flagbits[(uchar_t)flagstr[i]];
2433
2434			if (bit == 0) {
2435				(void) printf("***Invalid flag: %c\n",
2436				    flagstr[i]);
2437				continue;
2438			}
2439			flags |= bit;
2440
2441			/* If it's not something with an argument, keep going */
2442			if ((bit & (ZDB_FLAG_CHECKSUM |
2443			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
2444				continue;
2445
2446			p = &flagstr[i + 1];
2447			if (bit == ZDB_FLAG_PRINT_BLKPTR)
2448				blkptr_offset = strtoull(p, &p, 16);
2449			if (*p != ':' && *p != '\0') {
2450				(void) printf("***Invalid flag arg: '%s'\n", s);
2451				free(dup);
2452				return;
2453			}
2454		}
2455	}
2456
2457	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2458	if (vd == NULL) {
2459		(void) printf("***Invalid vdev: %s\n", vdev);
2460		free(dup);
2461		return;
2462	} else {
2463		if (vd->vdev_path)
2464			(void) fprintf(stderr, "Found vdev: %s\n",
2465			    vd->vdev_path);
2466		else
2467			(void) fprintf(stderr, "Found vdev type: %s\n",
2468			    vd->vdev_ops->vdev_op_type);
2469	}
2470
2471	psize = size;
2472	lsize = size;
2473
2474	pbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2475	lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2476
2477	BP_ZERO(bp);
2478
2479	DVA_SET_VDEV(&dva[0], vd->vdev_id);
2480	DVA_SET_OFFSET(&dva[0], offset);
2481	DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
2482	DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
2483
2484	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
2485
2486	BP_SET_LSIZE(bp, lsize);
2487	BP_SET_PSIZE(bp, psize);
2488	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
2489	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
2490	BP_SET_TYPE(bp, DMU_OT_NONE);
2491	BP_SET_LEVEL(bp, 0);
2492	BP_SET_DEDUP(bp, 0);
2493	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
2494
2495	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
2496	zio = zio_root(spa, NULL, NULL, 0);
2497
2498	if (vd == vd->vdev_top) {
2499		/*
2500		 * Treat this as a normal block read.
2501		 */
2502		zio_nowait(zio_read(zio, spa, bp, pbuf, psize, NULL, NULL,
2503		    ZIO_PRIORITY_SYNC_READ,
2504		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
2505	} else {
2506		/*
2507		 * Treat this as a vdev child I/O.
2508		 */
2509		zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pbuf, psize,
2510		    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
2511		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2512		    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
2513		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL, NULL));
2514	}
2515
2516	error = zio_wait(zio);
2517	spa_config_exit(spa, SCL_STATE, FTAG);
2518
2519	if (error) {
2520		(void) printf("Read of %s failed, error: %d\n", thing, error);
2521		goto out;
2522	}
2523
2524	if (flags & ZDB_FLAG_DECOMPRESS) {
2525		/*
2526		 * We don't know how the data was compressed, so just try
2527		 * every decompress function at every inflated blocksize.
2528		 */
2529		enum zio_compress c;
2530		void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2531		void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2532
2533		bcopy(pbuf, pbuf2, psize);
2534
2535		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf + psize,
2536		    SPA_MAXBLOCKSIZE - psize) == 0);
2537
2538		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
2539		    SPA_MAXBLOCKSIZE - psize) == 0);
2540
2541		for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
2542		    lsize -= SPA_MINBLOCKSIZE) {
2543			for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
2544				if (zio_decompress_data(c, pbuf, lbuf,
2545				    psize, lsize) == 0 &&
2546				    zio_decompress_data(c, pbuf2, lbuf2,
2547				    psize, lsize) == 0 &&
2548				    bcmp(lbuf, lbuf2, lsize) == 0)
2549					break;
2550			}
2551			if (c != ZIO_COMPRESS_FUNCTIONS)
2552				break;
2553			lsize -= SPA_MINBLOCKSIZE;
2554		}
2555
2556		umem_free(pbuf2, SPA_MAXBLOCKSIZE);
2557		umem_free(lbuf2, SPA_MAXBLOCKSIZE);
2558
2559		if (lsize <= psize) {
2560			(void) printf("Decompress of %s failed\n", thing);
2561			goto out;
2562		}
2563		buf = lbuf;
2564		size = lsize;
2565	} else {
2566		buf = pbuf;
2567		size = psize;
2568	}
2569
2570	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2571		zdb_print_blkptr((blkptr_t *)(void *)
2572		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2573	else if (flags & ZDB_FLAG_RAW)
2574		zdb_dump_block_raw(buf, size, flags);
2575	else if (flags & ZDB_FLAG_INDIRECT)
2576		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2577		    flags);
2578	else if (flags & ZDB_FLAG_GBH)
2579		zdb_dump_gbh(buf, flags);
2580	else
2581		zdb_dump_block(thing, buf, size, flags);
2582
2583out:
2584	umem_free(pbuf, SPA_MAXBLOCKSIZE);
2585	umem_free(lbuf, SPA_MAXBLOCKSIZE);
2586	free(dup);
2587}
2588
2589static boolean_t
2590pool_match(nvlist_t *cfg, char *tgt)
2591{
2592	uint64_t v, guid = strtoull(tgt, NULL, 0);
2593	char *s;
2594
2595	if (guid != 0) {
2596		if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
2597			return (v == guid);
2598	} else {
2599		if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
2600			return (strcmp(s, tgt) == 0);
2601	}
2602	return (B_FALSE);
2603}
2604
2605static char *
2606find_zpool(char **target, nvlist_t **configp, int dirc, char **dirv)
2607{
2608	nvlist_t *pools;
2609	nvlist_t *match = NULL;
2610	char *name = NULL;
2611	char *sepp = NULL;
2612	char sep;
2613	int count = 0;
2614
2615	if ((sepp = strpbrk(*target, "/@")) != NULL) {
2616		sep = *sepp;
2617		*sepp = '\0';
2618	}
2619
2620	pools = zpool_find_import_activeok(g_zfs, dirc, dirv);
2621
2622	if (pools != NULL) {
2623		nvpair_t *elem = NULL;
2624		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2625			verify(nvpair_value_nvlist(elem, configp) == 0);
2626			if (pool_match(*configp, *target)) {
2627				count++;
2628				if (match != NULL) {
2629					/* print previously found config */
2630					if (name != NULL) {
2631						(void) printf("%s\n", name);
2632						dump_nvlist(match, 8);
2633						name = NULL;
2634					}
2635					(void) printf("%s\n",
2636					    nvpair_name(elem));
2637					dump_nvlist(*configp, 8);
2638				} else {
2639					match = *configp;
2640					name = nvpair_name(elem);
2641				}
2642			}
2643		}
2644	}
2645	if (count > 1)
2646		(void) fatal("\tMatched %d pools - use pool GUID "
2647		    "instead of pool name or \n"
2648		    "\tpool name part of a dataset name to select pool", count);
2649
2650	if (sepp)
2651		*sepp = sep;
2652	/*
2653	 * If pool GUID was specified for pool id, replace it with pool name
2654	 */
2655	if (name && (strstr(*target, name) != *target)) {
2656		int sz = 1 + strlen(name) + ((sepp) ? strlen(sepp) : 0);
2657
2658		*target = umem_alloc(sz, UMEM_NOFAIL);
2659		(void) snprintf(*target, sz, "%s%s", name, sepp ? sepp : "");
2660	}
2661
2662	*configp = name ? match : NULL;
2663
2664	return (name);
2665}
2666
2667int
2668main(int argc, char **argv)
2669{
2670	int i, c;
2671	struct rlimit rl = { 1024, 1024 };
2672	spa_t *spa = NULL;
2673	objset_t *os = NULL;
2674	int dump_all = 1;
2675	int verbose = 0;
2676	int error;
2677	char **searchdirs = NULL;
2678	int nsearch = 0;
2679	char *target;
2680	nvlist_t *policy = NULL;
2681	uint64_t max_txg = UINT64_MAX;
2682
2683	(void) setrlimit(RLIMIT_NOFILE, &rl);
2684	(void) enable_extended_FILE_stdio(-1, -1);
2685
2686	dprintf_setup(&argc, argv);
2687
2688	while ((c = getopt(argc, argv, "bcdhilmsuCDRSLevp:t:U:")) != -1) {
2689		switch (c) {
2690		case 'b':
2691		case 'c':
2692		case 'd':
2693		case 'h':
2694		case 'i':
2695		case 'l':
2696		case 'm':
2697		case 's':
2698		case 'u':
2699		case 'C':
2700		case 'D':
2701		case 'R':
2702		case 'S':
2703			dump_opt[c]++;
2704			dump_all = 0;
2705			break;
2706		case 'L':
2707		case 'e':
2708			dump_opt[c]++;
2709			break;
2710		case 'v':
2711			verbose++;
2712			break;
2713		case 'p':
2714			if (searchdirs == NULL) {
2715				searchdirs = umem_alloc(sizeof (char *),
2716				    UMEM_NOFAIL);
2717			} else {
2718				char **tmp = umem_alloc((nsearch + 1) *
2719				    sizeof (char *), UMEM_NOFAIL);
2720				bcopy(searchdirs, tmp, nsearch *
2721				    sizeof (char *));
2722				umem_free(searchdirs,
2723				    nsearch * sizeof (char *));
2724				searchdirs = tmp;
2725			}
2726			searchdirs[nsearch++] = optarg;
2727			break;
2728		case 't':
2729			max_txg = strtoull(optarg, NULL, 0);
2730			if (max_txg < TXG_INITIAL) {
2731				(void) fprintf(stderr, "incorrect txg "
2732				    "specified: %s\n", optarg);
2733				usage();
2734			}
2735			break;
2736		case 'U':
2737			spa_config_path = optarg;
2738			break;
2739		default:
2740			usage();
2741			break;
2742		}
2743	}
2744
2745	if (!dump_opt['e'] && searchdirs != NULL) {
2746		(void) fprintf(stderr, "-p option requires use of -e\n");
2747		usage();
2748	}
2749
2750	kernel_init(FREAD);
2751	g_zfs = libzfs_init();
2752	ASSERT(g_zfs != NULL);
2753
2754	if (dump_all)
2755		verbose = MAX(verbose, 1);
2756
2757	for (c = 0; c < 256; c++) {
2758		if (dump_all && !strchr("elLRS", c))
2759			dump_opt[c] = 1;
2760		if (dump_opt[c])
2761			dump_opt[c] += verbose;
2762	}
2763
2764	argc -= optind;
2765	argv += optind;
2766
2767	if (argc < 2 && dump_opt['R'])
2768		usage();
2769	if (argc < 1) {
2770		if (!dump_opt['e'] && dump_opt['C']) {
2771			dump_cachefile(spa_config_path);
2772			return (0);
2773		}
2774		usage();
2775	}
2776
2777	if (dump_opt['l']) {
2778		dump_label(argv[0]);
2779		return (0);
2780	}
2781
2782	error = 0;
2783	target = argv[0];
2784
2785	VERIFY(nvlist_alloc(&policy, NV_UNIQUE_NAME, 0) == 0);
2786
2787	if (dump_opt['e']) {
2788		nvlist_t *cfg = NULL;
2789		char *name = find_zpool(&target, &cfg, nsearch, searchdirs);
2790
2791		error = ENOENT;
2792		if (name) {
2793			if (dump_opt['C'] > 1) {
2794				(void) printf("\nConfiguration for import:\n");
2795				dump_nvlist(cfg, 8);
2796			}
2797			if (nvlist_add_uint64(policy,
2798			    ZPOOL_REWIND_REQUEST_TXG, max_txg) != 0 ||
2799			    nvlist_add_nvlist(cfg,
2800			    ZPOOL_REWIND_POLICY, policy) != 0) {
2801				fatal("can't open '%s': %s",
2802				    target, strerror(ENOMEM));
2803			}
2804			if ((error = spa_import(name, cfg, NULL)) != 0)
2805				error = spa_import_verbatim(name, cfg, NULL);
2806		}
2807	} else {
2808		VERIFY(nvlist_add_uint64(policy, ZPOOL_REWIND_META_THRESH,
2809		    UINT64_MAX) == 0);
2810	}
2811
2812	if (error == 0) {
2813		if (strpbrk(target, "/@") == NULL || dump_opt['R']) {
2814			error = spa_open_rewind(target, &spa, FTAG, policy,
2815			    NULL);
2816			if (error) {
2817				/*
2818				 * If we're missing the log device then
2819				 * try opening the pool after clearing the
2820				 * log state.
2821				 */
2822				mutex_enter(&spa_namespace_lock);
2823				if ((spa = spa_lookup(target)) != NULL &&
2824				    spa->spa_log_state == SPA_LOG_MISSING) {
2825					spa->spa_log_state = SPA_LOG_CLEAR;
2826					error = 0;
2827				}
2828				mutex_exit(&spa_namespace_lock);
2829
2830				if (!error) {
2831					error = spa_open_rewind(target, &spa,
2832					    FTAG, policy, NULL);
2833				}
2834			}
2835		} else {
2836			error = dmu_objset_own(target, DMU_OST_ANY,
2837			    B_TRUE, FTAG, &os);
2838		}
2839	}
2840	nvlist_free(policy);
2841
2842	if (error)
2843		fatal("can't open '%s': %s", target, strerror(error));
2844
2845	argv++;
2846	argc--;
2847	if (!dump_opt['R']) {
2848		if (argc > 0) {
2849			zopt_objects = argc;
2850			zopt_object = calloc(zopt_objects, sizeof (uint64_t));
2851			for (i = 0; i < zopt_objects; i++) {
2852				errno = 0;
2853				zopt_object[i] = strtoull(argv[i], NULL, 0);
2854				if (zopt_object[i] == 0 && errno != 0)
2855					fatal("bad number %s: %s",
2856					    argv[i], strerror(errno));
2857			}
2858		}
2859		(os != NULL) ? dump_dir(os) : dump_zpool(spa);
2860	} else {
2861		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
2862		flagbits['c'] = ZDB_FLAG_CHECKSUM;
2863		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
2864		flagbits['e'] = ZDB_FLAG_BSWAP;
2865		flagbits['g'] = ZDB_FLAG_GBH;
2866		flagbits['i'] = ZDB_FLAG_INDIRECT;
2867		flagbits['p'] = ZDB_FLAG_PHYS;
2868		flagbits['r'] = ZDB_FLAG_RAW;
2869
2870		for (i = 0; i < argc; i++)
2871			zdb_read_block(argv[i], spa);
2872	}
2873
2874	(os != NULL) ? dmu_objset_disown(os, FTAG) : spa_close(spa, FTAG);
2875
2876	fuid_table_destroy();
2877
2878	libzfs_fini(g_zfs);
2879	kernel_fini();
2880
2881	return (0);
2882}
2883