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