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