xref: /titanic_41/usr/src/cmd/zdb/zdb.c (revision fad1d7055df96950837a53ae555fcf0d85aa4d19)
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->os),
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->os), 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->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->os_rootbp->blk_fill;
1195 		refdbytes = os->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->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->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->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->os_userused_dnode &&
1244 	    os->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_open(dsname, DMU_OST_ANY,
1402 	    DS_MODE_USER | DS_MODE_READONLY, &os);
1403 	if (error) {
1404 		(void) printf("Could not open %s\n", dsname);
1405 		return (0);
1406 	}
1407 	dump_dir(os);
1408 	dmu_objset_close(os);
1409 	fuid_table_destroy();
1410 	return (0);
1411 }
1412 
1413 static void
1414 zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
1415 {
1416 	vdev_t *vd = sm->sm_ppd;
1417 
1418 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
1419 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
1420 }
1421 
1422 /* ARGSUSED */
1423 static void
1424 zdb_space_map_load(space_map_t *sm)
1425 {
1426 }
1427 
1428 static void
1429 zdb_space_map_unload(space_map_t *sm)
1430 {
1431 	space_map_vacate(sm, zdb_leak, sm);
1432 }
1433 
1434 /* ARGSUSED */
1435 static void
1436 zdb_space_map_claim(space_map_t *sm, uint64_t start, uint64_t size)
1437 {
1438 }
1439 
1440 static space_map_ops_t zdb_space_map_ops = {
1441 	zdb_space_map_load,
1442 	zdb_space_map_unload,
1443 	NULL,	/* alloc */
1444 	zdb_space_map_claim,
1445 	NULL,	/* free */
1446 	NULL	/* maxsize */
1447 };
1448 
1449 static void
1450 zdb_leak_init(spa_t *spa)
1451 {
1452 	vdev_t *rvd = spa->spa_root_vdev;
1453 
1454 	for (int c = 0; c < rvd->vdev_children; c++) {
1455 		vdev_t *vd = rvd->vdev_child[c];
1456 		for (int m = 0; m < vd->vdev_ms_count; m++) {
1457 			metaslab_t *msp = vd->vdev_ms[m];
1458 			mutex_enter(&msp->ms_lock);
1459 			VERIFY(space_map_load(&msp->ms_map, &zdb_space_map_ops,
1460 			    SM_ALLOC, &msp->ms_smo, spa->spa_meta_objset) == 0);
1461 			msp->ms_map.sm_ppd = vd;
1462 			mutex_exit(&msp->ms_lock);
1463 		}
1464 	}
1465 }
1466 
1467 static void
1468 zdb_leak_fini(spa_t *spa)
1469 {
1470 	vdev_t *rvd = spa->spa_root_vdev;
1471 
1472 	for (int c = 0; c < rvd->vdev_children; c++) {
1473 		vdev_t *vd = rvd->vdev_child[c];
1474 		for (int m = 0; m < vd->vdev_ms_count; m++) {
1475 			metaslab_t *msp = vd->vdev_ms[m];
1476 			mutex_enter(&msp->ms_lock);
1477 			space_map_unload(&msp->ms_map);
1478 			mutex_exit(&msp->ms_lock);
1479 		}
1480 	}
1481 }
1482 
1483 /*
1484  * Verify that the sum of the sizes of all blocks in the pool adds up
1485  * to the SPA's sa_alloc total.
1486  */
1487 typedef struct zdb_blkstats {
1488 	uint64_t	zb_asize;
1489 	uint64_t	zb_lsize;
1490 	uint64_t	zb_psize;
1491 	uint64_t	zb_count;
1492 } zdb_blkstats_t;
1493 
1494 #define	DMU_OT_DEFERRED	DMU_OT_NONE
1495 #define	DMU_OT_TOTAL	DMU_OT_NUMTYPES
1496 
1497 #define	ZB_TOTAL	DN_MAX_LEVELS
1498 
1499 typedef struct zdb_cb {
1500 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][DMU_OT_TOTAL + 1];
1501 	uint64_t	zcb_errors[256];
1502 	int		zcb_readfails;
1503 	int		zcb_haderrors;
1504 } zdb_cb_t;
1505 
1506 static void
1507 zdb_count_block(spa_t *spa, zdb_cb_t *zcb, blkptr_t *bp, dmu_object_type_t type)
1508 {
1509 	for (int i = 0; i < 4; i++) {
1510 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
1511 		int t = (i & 1) ? type : DMU_OT_TOTAL;
1512 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
1513 
1514 		zb->zb_asize += BP_GET_ASIZE(bp);
1515 		zb->zb_lsize += BP_GET_LSIZE(bp);
1516 		zb->zb_psize += BP_GET_PSIZE(bp);
1517 		zb->zb_count++;
1518 	}
1519 
1520 	if (dump_opt['S']) {
1521 		boolean_t print_sig;
1522 
1523 		print_sig = !zdb_sig_user_data || (BP_GET_LEVEL(bp) == 0 &&
1524 		    BP_GET_TYPE(bp) == DMU_OT_PLAIN_FILE_CONTENTS);
1525 
1526 		if (BP_GET_CHECKSUM(bp) < zdb_sig_cksumalg)
1527 			print_sig = B_FALSE;
1528 
1529 		if (print_sig) {
1530 			(void) printf("%llu\t%lld\t%lld\t%s\t%s\t%s\t"
1531 			    "%llx:%llx:%llx:%llx\n",
1532 			    (u_longlong_t)BP_GET_LEVEL(bp),
1533 			    (longlong_t)BP_GET_PSIZE(bp),
1534 			    (longlong_t)BP_GET_NDVAS(bp),
1535 			    dmu_ot[BP_GET_TYPE(bp)].ot_name,
1536 			    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
1537 			    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name,
1538 			    (u_longlong_t)bp->blk_cksum.zc_word[0],
1539 			    (u_longlong_t)bp->blk_cksum.zc_word[1],
1540 			    (u_longlong_t)bp->blk_cksum.zc_word[2],
1541 			    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1542 		}
1543 	}
1544 
1545 	if (!dump_opt['L'])
1546 		VERIFY(zio_wait(zio_claim(NULL, spa, spa_first_txg(spa), bp,
1547 		    NULL, NULL, ZIO_FLAG_MUSTSUCCEED)) == 0);
1548 }
1549 
1550 static int
1551 zdb_blkptr_cb(spa_t *spa, blkptr_t *bp, const zbookmark_t *zb,
1552     const dnode_phys_t *dnp, void *arg)
1553 {
1554 	zdb_cb_t *zcb = arg;
1555 	char blkbuf[BP_SPRINTF_LEN];
1556 	dmu_object_type_t type;
1557 	boolean_t is_l0_metadata;
1558 
1559 	if (bp == NULL)
1560 		return (0);
1561 
1562 	type = BP_GET_TYPE(bp);
1563 
1564 	zdb_count_block(spa, zcb, bp, type);
1565 
1566 	/*
1567 	 * if we do metadata-only checksumming there's no need to checksum
1568 	 * indirect blocks here because it is done during traverse
1569 	 */
1570 	is_l0_metadata = (BP_GET_LEVEL(bp) == 0 && type < DMU_OT_NUMTYPES &&
1571 	    dmu_ot[type].ot_metadata);
1572 
1573 	if (dump_opt['c'] > 1 || dump_opt['S'] ||
1574 	    (dump_opt['c'] && is_l0_metadata)) {
1575 		int ioerr, size;
1576 		void *data;
1577 
1578 		size = BP_GET_LSIZE(bp);
1579 		data = malloc(size);
1580 		ioerr = zio_wait(zio_read(NULL, spa, bp, data, size,
1581 		    NULL, NULL, ZIO_PRIORITY_ASYNC_READ,
1582 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB, zb));
1583 		free(data);
1584 
1585 		/* We expect io errors on intent log */
1586 		if (ioerr && type != DMU_OT_INTENT_LOG) {
1587 			zcb->zcb_haderrors = 1;
1588 			zcb->zcb_errors[ioerr]++;
1589 
1590 			if (dump_opt['b'] >= 2)
1591 				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1592 			else
1593 				blkbuf[0] = '\0';
1594 
1595 			if (!dump_opt['S']) {
1596 				(void) printf("zdb_blkptr_cb: "
1597 				    "Got error %d reading "
1598 				    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
1599 				    ioerr,
1600 				    (u_longlong_t)zb->zb_objset,
1601 				    (u_longlong_t)zb->zb_object,
1602 				    (u_longlong_t)zb->zb_level,
1603 				    (u_longlong_t)zb->zb_blkid,
1604 				    blkbuf);
1605 			}
1606 		}
1607 	}
1608 
1609 	zcb->zcb_readfails = 0;
1610 
1611 	if (dump_opt['b'] >= 4) {
1612 		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1613 		(void) printf("objset %llu object %llu offset 0x%llx %s\n",
1614 		    (u_longlong_t)zb->zb_objset,
1615 		    (u_longlong_t)zb->zb_object,
1616 		    (u_longlong_t)blkid2offset(dnp, zb->zb_level, zb->zb_blkid),
1617 		    blkbuf);
1618 	}
1619 
1620 	return (0);
1621 }
1622 
1623 static int
1624 dump_block_stats(spa_t *spa)
1625 {
1626 	zdb_cb_t zcb = { 0 };
1627 	zdb_blkstats_t *zb, *tzb;
1628 	uint64_t alloc, space, logalloc;
1629 	vdev_t *rvd = spa->spa_root_vdev;
1630 	int leaks = 0;
1631 	int c, e;
1632 
1633 	if (!dump_opt['S']) {
1634 		(void) printf("\nTraversing all blocks %s%s%s%s%s...\n",
1635 		    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
1636 		    (dump_opt['c'] == 1) ? "metadata " : "",
1637 		    dump_opt['c'] ? "checksums " : "",
1638 		    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
1639 		    !dump_opt['L'] ? "nothing leaked " : "");
1640 	}
1641 
1642 	/*
1643 	 * Load all space maps as SM_ALLOC maps, then traverse the pool
1644 	 * claiming each block we discover.  If the pool is perfectly
1645 	 * consistent, the space maps will be empty when we're done.
1646 	 * Anything left over is a leak; any block we can't claim (because
1647 	 * it's not part of any space map) is a double allocation,
1648 	 * reference to a freed block, or an unclaimed log block.
1649 	 */
1650 	if (!dump_opt['L'])
1651 		zdb_leak_init(spa);
1652 
1653 	/*
1654 	 * If there's a deferred-free bplist, process that first.
1655 	 */
1656 	if (spa->spa_sync_bplist_obj != 0) {
1657 		bplist_t *bpl = &spa->spa_sync_bplist;
1658 		blkptr_t blk;
1659 		uint64_t itor = 0;
1660 
1661 		VERIFY(0 == bplist_open(bpl, spa->spa_meta_objset,
1662 		    spa->spa_sync_bplist_obj));
1663 
1664 		while (bplist_iterate(bpl, &itor, &blk) == 0) {
1665 			if (dump_opt['b'] >= 4) {
1666 				char blkbuf[BP_SPRINTF_LEN];
1667 				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &blk);
1668 				(void) printf("[%s] %s\n",
1669 				    "deferred free", blkbuf);
1670 			}
1671 			zdb_count_block(spa, &zcb, &blk, DMU_OT_DEFERRED);
1672 		}
1673 
1674 		bplist_close(bpl);
1675 	}
1676 
1677 	zcb.zcb_haderrors |= traverse_pool(spa, zdb_blkptr_cb, &zcb);
1678 
1679 	if (zcb.zcb_haderrors && !dump_opt['S']) {
1680 		(void) printf("\nError counts:\n\n");
1681 		(void) printf("\t%5s  %s\n", "errno", "count");
1682 		for (e = 0; e < 256; e++) {
1683 			if (zcb.zcb_errors[e] != 0) {
1684 				(void) printf("\t%5d  %llu\n",
1685 				    e, (u_longlong_t)zcb.zcb_errors[e]);
1686 			}
1687 		}
1688 	}
1689 
1690 	/*
1691 	 * Report any leaked segments.
1692 	 */
1693 	if (!dump_opt['L'])
1694 		zdb_leak_fini(spa);
1695 
1696 	/*
1697 	 * If we're interested in printing out the blkptr signatures,
1698 	 * return now as we don't print out anything else (including
1699 	 * errors and leaks).
1700 	 */
1701 	if (dump_opt['S'])
1702 		return (zcb.zcb_haderrors ? 3 : 0);
1703 
1704 	alloc = spa_get_alloc(spa);
1705 	space = spa_get_space(spa);
1706 
1707 	/*
1708 	 * Log blocks allocated from a separate log device don't count
1709 	 * as part of the normal pool space; factor them in here.
1710 	 */
1711 	logalloc = 0;
1712 
1713 	for (c = 0; c < rvd->vdev_children; c++)
1714 		if (rvd->vdev_child[c]->vdev_islog)
1715 			logalloc += rvd->vdev_child[c]->vdev_stat.vs_alloc;
1716 
1717 	tzb = &zcb.zcb_type[ZB_TOTAL][DMU_OT_TOTAL];
1718 
1719 	if (tzb->zb_asize == alloc + logalloc) {
1720 		if (!dump_opt['L'])
1721 			(void) printf("\n\tNo leaks (block sum matches space"
1722 			    " maps exactly)\n");
1723 	} else {
1724 		(void) printf("block traversal size %llu != alloc %llu "
1725 		    "(%s %lld)\n",
1726 		    (u_longlong_t)tzb->zb_asize,
1727 		    (u_longlong_t)alloc + logalloc,
1728 		    (dump_opt['L']) ? "unreachable" : "leaked",
1729 		    (longlong_t)(alloc + logalloc - tzb->zb_asize));
1730 		leaks = 1;
1731 	}
1732 
1733 	if (tzb->zb_count == 0)
1734 		return (2);
1735 
1736 	(void) printf("\n");
1737 	(void) printf("\tbp count:      %10llu\n",
1738 	    (u_longlong_t)tzb->zb_count);
1739 	(void) printf("\tbp logical:    %10llu\t avg: %6llu\n",
1740 	    (u_longlong_t)tzb->zb_lsize,
1741 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
1742 	(void) printf("\tbp physical:   %10llu\t avg:"
1743 	    " %6llu\tcompression: %6.2f\n",
1744 	    (u_longlong_t)tzb->zb_psize,
1745 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
1746 	    (double)tzb->zb_lsize / tzb->zb_psize);
1747 	(void) printf("\tbp allocated:  %10llu\t avg:"
1748 	    " %6llu\tcompression: %6.2f\n",
1749 	    (u_longlong_t)tzb->zb_asize,
1750 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
1751 	    (double)tzb->zb_lsize / tzb->zb_asize);
1752 	(void) printf("\tSPA allocated: %10llu\tused: %5.2f%%\n",
1753 	    (u_longlong_t)alloc, 100.0 * alloc / space);
1754 
1755 	if (dump_opt['b'] >= 2) {
1756 		int l, t, level;
1757 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
1758 		    "\t  avg\t comp\t%%Total\tType\n");
1759 
1760 		for (t = 0; t <= DMU_OT_NUMTYPES; t++) {
1761 			char csize[6], lsize[6], psize[6], asize[6], avg[6];
1762 			char *typename;
1763 
1764 			typename = t == DMU_OT_DEFERRED ? "deferred free" :
1765 			    t == DMU_OT_TOTAL ? "Total" : dmu_ot[t].ot_name;
1766 
1767 			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
1768 				(void) printf("%6s\t%5s\t%5s\t%5s"
1769 				    "\t%5s\t%5s\t%6s\t%s\n",
1770 				    "-",
1771 				    "-",
1772 				    "-",
1773 				    "-",
1774 				    "-",
1775 				    "-",
1776 				    "-",
1777 				    typename);
1778 				continue;
1779 			}
1780 
1781 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
1782 				level = (l == -1 ? ZB_TOTAL : l);
1783 				zb = &zcb.zcb_type[level][t];
1784 
1785 				if (zb->zb_asize == 0)
1786 					continue;
1787 
1788 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
1789 					continue;
1790 
1791 				if (level == 0 && zb->zb_asize ==
1792 				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
1793 					continue;
1794 
1795 				nicenum(zb->zb_count, csize);
1796 				nicenum(zb->zb_lsize, lsize);
1797 				nicenum(zb->zb_psize, psize);
1798 				nicenum(zb->zb_asize, asize);
1799 				nicenum(zb->zb_asize / zb->zb_count, avg);
1800 
1801 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
1802 				    "\t%5.2f\t%6.2f\t",
1803 				    csize, lsize, psize, asize, avg,
1804 				    (double)zb->zb_lsize / zb->zb_psize,
1805 				    100.0 * zb->zb_asize / tzb->zb_asize);
1806 
1807 				if (level == ZB_TOTAL)
1808 					(void) printf("%s\n", typename);
1809 				else
1810 					(void) printf("    L%d %s\n",
1811 					    level, typename);
1812 			}
1813 		}
1814 	}
1815 
1816 	(void) printf("\n");
1817 
1818 	if (leaks)
1819 		return (2);
1820 
1821 	if (zcb.zcb_haderrors)
1822 		return (3);
1823 
1824 	return (0);
1825 }
1826 
1827 static void
1828 dump_zpool(spa_t *spa)
1829 {
1830 	dsl_pool_t *dp = spa_get_dsl(spa);
1831 	int rc = 0;
1832 
1833 	if (dump_opt['u'])
1834 		dump_uberblock(&spa->spa_uberblock);
1835 
1836 	if (dump_opt['d'] || dump_opt['i'] || dump_opt['m']) {
1837 		dump_dir(dp->dp_meta_objset);
1838 		if (dump_opt['d'] >= 3) {
1839 			dump_bplist(dp->dp_meta_objset,
1840 			    spa->spa_sync_bplist_obj, "Deferred frees");
1841 			dump_dtl(spa->spa_root_vdev, 0);
1842 		}
1843 
1844 		if (dump_opt['d'] >= 3 || dump_opt['m'])
1845 			dump_metaslabs(spa);
1846 
1847 		(void) dmu_objset_find(spa_name(spa), dump_one_dir, NULL,
1848 		    DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
1849 	}
1850 
1851 	if (dump_opt['b'] || dump_opt['c'] || dump_opt['S'])
1852 		rc = dump_block_stats(spa);
1853 
1854 	if (dump_opt['s'])
1855 		show_pool_stats(spa);
1856 
1857 	if (rc != 0)
1858 		exit(rc);
1859 }
1860 
1861 #define	ZDB_FLAG_CHECKSUM	0x0001
1862 #define	ZDB_FLAG_DECOMPRESS	0x0002
1863 #define	ZDB_FLAG_BSWAP		0x0004
1864 #define	ZDB_FLAG_GBH		0x0008
1865 #define	ZDB_FLAG_INDIRECT	0x0010
1866 #define	ZDB_FLAG_PHYS		0x0020
1867 #define	ZDB_FLAG_RAW		0x0040
1868 #define	ZDB_FLAG_PRINT_BLKPTR	0x0080
1869 
1870 int flagbits[256];
1871 
1872 static void
1873 zdb_print_blkptr(blkptr_t *bp, int flags)
1874 {
1875 	dva_t *dva = bp->blk_dva;
1876 	int d;
1877 
1878 	if (flags & ZDB_FLAG_BSWAP)
1879 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
1880 	/*
1881 	 * Super-ick warning:  This code is also duplicated in
1882 	 * cmd/mdb/common/modules/zfs/zfs.c .  Yeah, I hate code
1883 	 * replication, too.
1884 	 */
1885 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1886 		(void) printf("\tDVA[%d]: vdev_id %lld / %llx\n", d,
1887 		    (longlong_t)DVA_GET_VDEV(&dva[d]),
1888 		    (longlong_t)DVA_GET_OFFSET(&dva[d]));
1889 		(void) printf("\tDVA[%d]:       GANG: %-5s  GRID:  %04llx\t"
1890 		    "ASIZE: %llx\n", d,
1891 		    DVA_GET_GANG(&dva[d]) ? "TRUE" : "FALSE",
1892 		    (longlong_t)DVA_GET_GRID(&dva[d]),
1893 		    (longlong_t)DVA_GET_ASIZE(&dva[d]));
1894 		(void) printf("\tDVA[%d]: :%llu:%llx:%llx:%s%s%s%s\n", d,
1895 		    (u_longlong_t)DVA_GET_VDEV(&dva[d]),
1896 		    (longlong_t)DVA_GET_OFFSET(&dva[d]),
1897 		    (longlong_t)BP_GET_PSIZE(bp),
1898 		    BP_SHOULD_BYTESWAP(bp) ? "e" : "",
1899 		    !DVA_GET_GANG(&dva[d]) && BP_GET_LEVEL(bp) != 0 ?
1900 		    "d" : "",
1901 		    DVA_GET_GANG(&dva[d]) ? "g" : "",
1902 		    BP_GET_COMPRESS(bp) != 0 ? "d" : "");
1903 	}
1904 	(void) printf("\tLSIZE:  %-16llx\t\tPSIZE: %llx\n",
1905 	    (longlong_t)BP_GET_LSIZE(bp), (longlong_t)BP_GET_PSIZE(bp));
1906 	(void) printf("\tENDIAN: %6s\t\t\t\t\tTYPE:  %s\n",
1907 	    BP_GET_BYTEORDER(bp) ? "LITTLE" : "BIG",
1908 	    dmu_ot[BP_GET_TYPE(bp)].ot_name);
1909 	(void) printf("\tBIRTH:  %-16llx   LEVEL: %-2llu\tFILL:  %llx\n",
1910 	    (u_longlong_t)bp->blk_birth, (u_longlong_t)BP_GET_LEVEL(bp),
1911 	    (u_longlong_t)bp->blk_fill);
1912 	(void) printf("\tCKFUNC: %-16s\t\tCOMP:  %s\n",
1913 	    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
1914 	    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name);
1915 	(void) printf("\tCKSUM:  %llx:%llx:%llx:%llx\n",
1916 	    (u_longlong_t)bp->blk_cksum.zc_word[0],
1917 	    (u_longlong_t)bp->blk_cksum.zc_word[1],
1918 	    (u_longlong_t)bp->blk_cksum.zc_word[2],
1919 	    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1920 }
1921 
1922 static void
1923 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
1924 {
1925 	int i;
1926 
1927 	for (i = 0; i < nbps; i++)
1928 		zdb_print_blkptr(&bp[i], flags);
1929 }
1930 
1931 static void
1932 zdb_dump_gbh(void *buf, int flags)
1933 {
1934 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
1935 }
1936 
1937 static void
1938 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
1939 {
1940 	if (flags & ZDB_FLAG_BSWAP)
1941 		byteswap_uint64_array(buf, size);
1942 	(void) write(2, buf, size);
1943 }
1944 
1945 static void
1946 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
1947 {
1948 	uint64_t *d = (uint64_t *)buf;
1949 	int nwords = size / sizeof (uint64_t);
1950 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
1951 	int i, j;
1952 	char *hdr, *c;
1953 
1954 
1955 	if (do_bswap)
1956 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
1957 	else
1958 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
1959 
1960 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
1961 
1962 	for (i = 0; i < nwords; i += 2) {
1963 		(void) printf("%06llx:  %016llx  %016llx  ",
1964 		    (u_longlong_t)(i * sizeof (uint64_t)),
1965 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
1966 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
1967 
1968 		c = (char *)&d[i];
1969 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
1970 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
1971 		(void) printf("\n");
1972 	}
1973 }
1974 
1975 /*
1976  * There are two acceptable formats:
1977  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
1978  *	child[.child]*    - For example: 0.1.1
1979  *
1980  * The second form can be used to specify arbitrary vdevs anywhere
1981  * in the heirarchy.  For example, in a pool with a mirror of
1982  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
1983  */
1984 static vdev_t *
1985 zdb_vdev_lookup(vdev_t *vdev, char *path)
1986 {
1987 	char *s, *p, *q;
1988 	int i;
1989 
1990 	if (vdev == NULL)
1991 		return (NULL);
1992 
1993 	/* First, assume the x.x.x.x format */
1994 	i = (int)strtoul(path, &s, 10);
1995 	if (s == path || (s && *s != '.' && *s != '\0'))
1996 		goto name;
1997 	if (i < 0 || i >= vdev->vdev_children)
1998 		return (NULL);
1999 
2000 	vdev = vdev->vdev_child[i];
2001 	if (*s == '\0')
2002 		return (vdev);
2003 	return (zdb_vdev_lookup(vdev, s+1));
2004 
2005 name:
2006 	for (i = 0; i < vdev->vdev_children; i++) {
2007 		vdev_t *vc = vdev->vdev_child[i];
2008 
2009 		if (vc->vdev_path == NULL) {
2010 			vc = zdb_vdev_lookup(vc, path);
2011 			if (vc == NULL)
2012 				continue;
2013 			else
2014 				return (vc);
2015 		}
2016 
2017 		p = strrchr(vc->vdev_path, '/');
2018 		p = p ? p + 1 : vc->vdev_path;
2019 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2020 
2021 		if (strcmp(vc->vdev_path, path) == 0)
2022 			return (vc);
2023 		if (strcmp(p, path) == 0)
2024 			return (vc);
2025 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2026 			return (vc);
2027 	}
2028 
2029 	return (NULL);
2030 }
2031 
2032 /*
2033  * Read a block from a pool and print it out.  The syntax of the
2034  * block descriptor is:
2035  *
2036  *	pool:vdev_specifier:offset:size[:flags]
2037  *
2038  *	pool           - The name of the pool you wish to read from
2039  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2040  *	offset         - offset, in hex, in bytes
2041  *	size           - Amount of data to read, in hex, in bytes
2042  *	flags          - A string of characters specifying options
2043  *		 b: Decode a blkptr at given offset within block
2044  *		*c: Calculate and display checksums
2045  *		*d: Decompress data before dumping
2046  *		 e: Byteswap data before dumping
2047  *		*g: Display data as a gang block header
2048  *		*i: Display as an indirect block
2049  *		 p: Do I/O to physical offset
2050  *		 r: Dump raw data to stdout
2051  *
2052  *              * = not yet implemented
2053  */
2054 static void
2055 zdb_read_block(char *thing, spa_t **spap)
2056 {
2057 	spa_t *spa = *spap;
2058 	int flags = 0;
2059 	uint64_t offset = 0, size = 0, blkptr_offset = 0;
2060 	zio_t *zio;
2061 	vdev_t *vd;
2062 	void *buf;
2063 	char *s, *p, *dup, *pool, *vdev, *flagstr;
2064 	int i, error, zio_flags;
2065 
2066 	dup = strdup(thing);
2067 	s = strtok(dup, ":");
2068 	pool = s ? s : "";
2069 	s = strtok(NULL, ":");
2070 	vdev = s ? s : "";
2071 	s = strtok(NULL, ":");
2072 	offset = strtoull(s ? s : "", NULL, 16);
2073 	s = strtok(NULL, ":");
2074 	size = strtoull(s ? s : "", NULL, 16);
2075 	s = strtok(NULL, ":");
2076 	flagstr = s ? s : "";
2077 
2078 	s = NULL;
2079 	if (size == 0)
2080 		s = "size must not be zero";
2081 	if (!IS_P2ALIGNED(size, DEV_BSIZE))
2082 		s = "size must be a multiple of sector size";
2083 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
2084 		s = "offset must be a multiple of sector size";
2085 	if (s) {
2086 		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
2087 		free(dup);
2088 		return;
2089 	}
2090 
2091 	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
2092 		for (i = 0; flagstr[i]; i++) {
2093 			int bit = flagbits[(uchar_t)flagstr[i]];
2094 
2095 			if (bit == 0) {
2096 				(void) printf("***Invalid flag: %c\n",
2097 				    flagstr[i]);
2098 				continue;
2099 			}
2100 			flags |= bit;
2101 
2102 			/* If it's not something with an argument, keep going */
2103 			if ((bit & (ZDB_FLAG_CHECKSUM | ZDB_FLAG_DECOMPRESS |
2104 			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
2105 				continue;
2106 
2107 			p = &flagstr[i + 1];
2108 			if (bit == ZDB_FLAG_PRINT_BLKPTR)
2109 				blkptr_offset = strtoull(p, &p, 16);
2110 			if (*p != ':' && *p != '\0') {
2111 				(void) printf("***Invalid flag arg: '%s'\n", s);
2112 				free(dup);
2113 				return;
2114 			}
2115 		}
2116 	}
2117 
2118 	if (spa == NULL || strcmp(spa_name(spa), pool) != 0) {
2119 		if (spa)
2120 			spa_close(spa, (void *)zdb_read_block);
2121 		error = spa_open(pool, spap, (void *)zdb_read_block);
2122 		if (error)
2123 			fatal("Failed to open pool '%s': %s",
2124 			    pool, strerror(error));
2125 		spa = *spap;
2126 	}
2127 
2128 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2129 	if (vd == NULL) {
2130 		(void) printf("***Invalid vdev: %s\n", vdev);
2131 		free(dup);
2132 		return;
2133 	} else {
2134 		if (vd->vdev_path)
2135 			(void) printf("Found vdev: %s\n", vd->vdev_path);
2136 		else
2137 			(void) printf("Found vdev type: %s\n",
2138 			    vd->vdev_ops->vdev_op_type);
2139 	}
2140 
2141 	buf = umem_alloc(size, UMEM_NOFAIL);
2142 
2143 	zio_flags = ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2144 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY;
2145 
2146 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
2147 	zio = zio_root(spa, NULL, NULL, 0);
2148 	/* XXX todo - cons up a BP so RAID-Z will be happy */
2149 	zio_nowait(zio_vdev_child_io(zio, NULL, vd, offset, buf, size,
2150 	    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ, zio_flags, NULL, NULL));
2151 	error = zio_wait(zio);
2152 	spa_config_exit(spa, SCL_STATE, FTAG);
2153 
2154 	if (error) {
2155 		(void) printf("Read of %s failed, error: %d\n", thing, error);
2156 		goto out;
2157 	}
2158 
2159 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2160 		zdb_print_blkptr((blkptr_t *)(void *)
2161 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2162 	else if (flags & ZDB_FLAG_RAW)
2163 		zdb_dump_block_raw(buf, size, flags);
2164 	else if (flags & ZDB_FLAG_INDIRECT)
2165 		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2166 		    flags);
2167 	else if (flags & ZDB_FLAG_GBH)
2168 		zdb_dump_gbh(buf, flags);
2169 	else
2170 		zdb_dump_block(thing, buf, size, flags);
2171 
2172 out:
2173 	umem_free(buf, size);
2174 	free(dup);
2175 }
2176 
2177 static boolean_t
2178 nvlist_string_match(nvlist_t *config, char *name, char *tgt)
2179 {
2180 	char *s;
2181 
2182 	if (nvlist_lookup_string(config, name, &s) != 0)
2183 		return (B_FALSE);
2184 
2185 	return (strcmp(s, tgt) == 0);
2186 }
2187 
2188 static boolean_t
2189 nvlist_uint64_match(nvlist_t *config, char *name, uint64_t tgt)
2190 {
2191 	uint64_t val;
2192 
2193 	if (nvlist_lookup_uint64(config, name, &val) != 0)
2194 		return (B_FALSE);
2195 
2196 	return (val == tgt);
2197 }
2198 
2199 static boolean_t
2200 vdev_child_guid_match(nvlist_t *vdev, uint64_t guid)
2201 {
2202 	nvlist_t **child;
2203 	uint_t c, children;
2204 
2205 	verify(nvlist_lookup_nvlist_array(vdev, ZPOOL_CONFIG_CHILDREN,
2206 	    &child, &children) == 0);
2207 	for (c = 0; c < children; ++c)
2208 		if (nvlist_uint64_match(child[c], ZPOOL_CONFIG_GUID, guid))
2209 			return (B_TRUE);
2210 	return (B_FALSE);
2211 }
2212 
2213 static boolean_t
2214 vdev_child_string_match(nvlist_t *vdev, char *tgt)
2215 {
2216 	nvlist_t **child;
2217 	uint_t c, children;
2218 
2219 	verify(nvlist_lookup_nvlist_array(vdev, ZPOOL_CONFIG_CHILDREN,
2220 	    &child, &children) == 0);
2221 	for (c = 0; c < children; ++c) {
2222 		if (nvlist_string_match(child[c], ZPOOL_CONFIG_PATH, tgt) ||
2223 		    nvlist_string_match(child[c], ZPOOL_CONFIG_DEVID, tgt))
2224 			return (B_TRUE);
2225 	}
2226 	return (B_FALSE);
2227 }
2228 
2229 static boolean_t
2230 vdev_guid_match(nvlist_t *config, uint64_t guid)
2231 {
2232 	nvlist_t *nvroot;
2233 
2234 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2235 	    &nvroot) == 0);
2236 
2237 	return (nvlist_uint64_match(nvroot, ZPOOL_CONFIG_GUID, guid) ||
2238 	    vdev_child_guid_match(nvroot, guid));
2239 }
2240 
2241 static boolean_t
2242 vdev_string_match(nvlist_t *config, char *tgt)
2243 {
2244 	nvlist_t *nvroot;
2245 
2246 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2247 	    &nvroot) == 0);
2248 
2249 	return (vdev_child_string_match(nvroot, tgt));
2250 }
2251 
2252 static boolean_t
2253 pool_match(nvlist_t *config, char *tgt)
2254 {
2255 	uint64_t guid = strtoull(tgt, NULL, 0);
2256 
2257 	if (guid != 0) {
2258 		return (
2259 		    nvlist_uint64_match(config, ZPOOL_CONFIG_POOL_GUID, guid) ||
2260 		    vdev_guid_match(config, guid));
2261 	} else {
2262 		return (
2263 		    nvlist_string_match(config, ZPOOL_CONFIG_POOL_NAME, tgt) ||
2264 		    vdev_string_match(config, tgt));
2265 	}
2266 }
2267 
2268 static int
2269 find_exported_zpool(char *pool_id, nvlist_t **configp, char *vdev_dir)
2270 {
2271 	nvlist_t *pools;
2272 	int error = ENOENT;
2273 	nvlist_t *match = NULL;
2274 
2275 	if (vdev_dir != NULL)
2276 		pools = zpool_find_import_activeok(g_zfs, 1, &vdev_dir);
2277 	else
2278 		pools = zpool_find_import_activeok(g_zfs, 0, NULL);
2279 
2280 	if (pools != NULL) {
2281 		nvpair_t *elem = NULL;
2282 
2283 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2284 			verify(nvpair_value_nvlist(elem, configp) == 0);
2285 			if (pool_match(*configp, pool_id)) {
2286 				if (match != NULL) {
2287 					(void) fatal(
2288 					    "More than one matching pool - "
2289 					    "specify guid/devid/device path.");
2290 				} else {
2291 					match = *configp;
2292 					error = 0;
2293 				}
2294 			}
2295 		}
2296 	}
2297 
2298 	*configp = error ? NULL : match;
2299 
2300 	return (error);
2301 }
2302 
2303 int
2304 main(int argc, char **argv)
2305 {
2306 	int i, c;
2307 	struct rlimit rl = { 1024, 1024 };
2308 	spa_t *spa;
2309 	objset_t *os = NULL;
2310 	char *endstr;
2311 	int dump_all = 1;
2312 	int verbose = 0;
2313 	int error;
2314 	int exported = 0;
2315 	char *vdev_dir = NULL;
2316 
2317 	(void) setrlimit(RLIMIT_NOFILE, &rl);
2318 	(void) enable_extended_FILE_stdio(-1, -1);
2319 
2320 	dprintf_setup(&argc, argv);
2321 
2322 	while ((c = getopt(argc, argv, "udibcmsvCLS:U:lRep:t:")) != -1) {
2323 		switch (c) {
2324 		case 'u':
2325 		case 'd':
2326 		case 'i':
2327 		case 'b':
2328 		case 'c':
2329 		case 'm':
2330 		case 's':
2331 		case 'C':
2332 		case 'l':
2333 		case 'R':
2334 			dump_opt[c]++;
2335 			dump_all = 0;
2336 			break;
2337 		case 'L':
2338 			dump_opt[c]++;
2339 			break;
2340 		case 'v':
2341 			verbose++;
2342 			break;
2343 		case 'U':
2344 			spa_config_path = optarg;
2345 			break;
2346 		case 'e':
2347 			exported = 1;
2348 			break;
2349 		case 'p':
2350 			vdev_dir = optarg;
2351 			break;
2352 		case 'S':
2353 			dump_opt[c]++;
2354 			dump_all = 0;
2355 			zdb_sig_user_data = (strncmp(optarg, "user:", 5) == 0);
2356 			if (!zdb_sig_user_data && strncmp(optarg, "all:", 4))
2357 				usage();
2358 			endstr = strchr(optarg, ':') + 1;
2359 			if (strcmp(endstr, "fletcher2") == 0)
2360 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_2;
2361 			else if (strcmp(endstr, "fletcher4") == 0)
2362 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_4;
2363 			else if (strcmp(endstr, "sha256") == 0)
2364 				zdb_sig_cksumalg = ZIO_CHECKSUM_SHA256;
2365 			else if (strcmp(endstr, "all") == 0)
2366 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_2;
2367 			else
2368 				usage();
2369 			break;
2370 		case 't':
2371 			ub_max_txg = strtoull(optarg, NULL, 0);
2372 			if (ub_max_txg < TXG_INITIAL) {
2373 				(void) fprintf(stderr, "incorrect txg "
2374 				    "specified: %s\n", optarg);
2375 				usage();
2376 			}
2377 			break;
2378 		default:
2379 			usage();
2380 			break;
2381 		}
2382 	}
2383 
2384 	if (vdev_dir != NULL && exported == 0) {
2385 		(void) fprintf(stderr, "-p option requires use of -e\n");
2386 		usage();
2387 	}
2388 
2389 	kernel_init(FREAD);
2390 	g_zfs = libzfs_init();
2391 	ASSERT(g_zfs != NULL);
2392 
2393 	for (c = 0; c < 256; c++) {
2394 		if (dump_all && c != 'l' && c != 'R')
2395 			dump_opt[c] = 1;
2396 		if (dump_opt[c])
2397 			dump_opt[c] += verbose;
2398 	}
2399 
2400 	argc -= optind;
2401 	argv += optind;
2402 
2403 	if (argc < 1) {
2404 		if (dump_opt['C']) {
2405 			dump_cachefile(spa_config_path);
2406 			return (0);
2407 		}
2408 		usage();
2409 	}
2410 
2411 	if (dump_opt['l']) {
2412 		dump_label(argv[0]);
2413 		return (0);
2414 	}
2415 
2416 	if (dump_opt['R']) {
2417 		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
2418 		flagbits['c'] = ZDB_FLAG_CHECKSUM;
2419 		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
2420 		flagbits['e'] = ZDB_FLAG_BSWAP;
2421 		flagbits['g'] = ZDB_FLAG_GBH;
2422 		flagbits['i'] = ZDB_FLAG_INDIRECT;
2423 		flagbits['p'] = ZDB_FLAG_PHYS;
2424 		flagbits['r'] = ZDB_FLAG_RAW;
2425 
2426 		spa = NULL;
2427 		while (argv[0]) {
2428 			zdb_read_block(argv[0], &spa);
2429 			argv++;
2430 			argc--;
2431 		}
2432 		if (spa)
2433 			spa_close(spa, (void *)zdb_read_block);
2434 		return (0);
2435 	}
2436 
2437 	if (dump_opt['C'])
2438 		dump_config(argv[0]);
2439 
2440 	error = 0;
2441 	if (exported) {
2442 		/*
2443 		 * Check to see if the name refers to an exported zpool
2444 		 */
2445 		char *slash;
2446 		nvlist_t *exported_conf = NULL;
2447 
2448 		if ((slash = strchr(argv[0], '/')) != NULL)
2449 			*slash = '\0';
2450 
2451 		error = find_exported_zpool(argv[0], &exported_conf, vdev_dir);
2452 		if (error == 0) {
2453 			nvlist_t *nvl = NULL;
2454 
2455 			if (vdev_dir != NULL) {
2456 				if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
2457 					error = ENOMEM;
2458 				else if (nvlist_add_string(nvl,
2459 				    zpool_prop_to_name(ZPOOL_PROP_ALTROOT),
2460 				    vdev_dir) != 0)
2461 					error = ENOMEM;
2462 			}
2463 
2464 			if (error == 0)
2465 				error = spa_import_verbatim(argv[0],
2466 				    exported_conf, nvl);
2467 
2468 			nvlist_free(nvl);
2469 		}
2470 
2471 		if (slash != NULL)
2472 			*slash = '/';
2473 	}
2474 
2475 	if (error == 0) {
2476 		if (strchr(argv[0], '/') != NULL) {
2477 			error = dmu_objset_open(argv[0], DMU_OST_ANY,
2478 			    DS_MODE_USER | DS_MODE_READONLY, &os);
2479 		} else {
2480 			error = spa_open(argv[0], &spa, FTAG);
2481 		}
2482 	}
2483 
2484 	if (error)
2485 		fatal("can't open %s: %s", argv[0], strerror(error));
2486 
2487 	argv++;
2488 	if (--argc > 0) {
2489 		zopt_objects = argc;
2490 		zopt_object = calloc(zopt_objects, sizeof (uint64_t));
2491 		for (i = 0; i < zopt_objects; i++) {
2492 			errno = 0;
2493 			zopt_object[i] = strtoull(argv[i], NULL, 0);
2494 			if (zopt_object[i] == 0 && errno != 0)
2495 				fatal("bad object number %s: %s",
2496 				    argv[i], strerror(errno));
2497 		}
2498 	}
2499 
2500 	if (os != NULL) {
2501 		dump_dir(os);
2502 		dmu_objset_close(os);
2503 	} else {
2504 		dump_zpool(spa);
2505 		spa_close(spa, FTAG);
2506 	}
2507 
2508 	fuid_table_destroy();
2509 
2510 	libzfs_fini(g_zfs);
2511 	kernel_fini();
2512 
2513 	return (0);
2514 }
2515