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