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