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