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