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