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