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