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