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