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