xref: /titanic_51/usr/src/cmd/zdb/zdb.c (revision f4a94ada79e5d2be49a574fa7fba9364c57b05d9)
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\tcreation_time = %s", ctime(&crtime));
822 	(void) printf("\t\tcreation_txg = %llu\n",
823 	    (u_longlong_t)ds->ds_creation_txg);
824 	(void) printf("\t\tdeadlist_obj = %llu\n",
825 	    (u_longlong_t)ds->ds_deadlist_obj);
826 	(void) printf("\t\tused_bytes = %s\n", used);
827 	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
828 	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
829 	(void) printf("\t\tunique = %s\n", unique);
830 	(void) printf("\t\tfsid_guid = %llu\n",
831 	    (u_longlong_t)ds->ds_fsid_guid);
832 	(void) printf("\t\tguid = %llu\n",
833 	    (u_longlong_t)ds->ds_guid);
834 	(void) printf("\t\tflags = %llx\n",
835 	    (u_longlong_t)ds->ds_flags);
836 	(void) printf("\t\tnext_clones_obj = %llu\n",
837 	    (u_longlong_t)ds->ds_next_clones_obj);
838 	(void) printf("\t\tprops_obj = %llu\n",
839 	    (u_longlong_t)ds->ds_props_obj);
840 	(void) printf("\t\tbp = %s\n", blkbuf);
841 }
842 
843 static void
844 dump_bplist(objset_t *mos, uint64_t object, char *name)
845 {
846 	bplist_t bpl = { 0 };
847 	blkptr_t blk, *bp = &blk;
848 	uint64_t itor = 0;
849 	char bytes[6];
850 	char comp[6];
851 	char uncomp[6];
852 
853 	if (dump_opt['d'] < 3)
854 		return;
855 
856 	mutex_init(&bpl.bpl_lock, NULL, MUTEX_DEFAULT, NULL);
857 	VERIFY(0 == bplist_open(&bpl, mos, object));
858 	if (bplist_empty(&bpl)) {
859 		bplist_close(&bpl);
860 		mutex_destroy(&bpl.bpl_lock);
861 		return;
862 	}
863 
864 	nicenum(bpl.bpl_phys->bpl_bytes, bytes);
865 	if (bpl.bpl_dbuf->db_size == sizeof (bplist_phys_t)) {
866 		nicenum(bpl.bpl_phys->bpl_comp, comp);
867 		nicenum(bpl.bpl_phys->bpl_uncomp, uncomp);
868 		(void) printf("\n    %s: %llu entries, %s (%s/%s comp)\n",
869 		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries,
870 		    bytes, comp, uncomp);
871 	} else {
872 		(void) printf("\n    %s: %llu entries, %s\n",
873 		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries, bytes);
874 	}
875 
876 	if (dump_opt['d'] < 5) {
877 		bplist_close(&bpl);
878 		mutex_destroy(&bpl.bpl_lock);
879 		return;
880 	}
881 
882 	(void) printf("\n");
883 
884 	while (bplist_iterate(&bpl, &itor, bp) == 0) {
885 		char blkbuf[BP_SPRINTF_LEN];
886 
887 		ASSERT(bp->blk_birth != 0);
888 		sprintf_blkptr_compact(blkbuf, bp, dump_opt['d'] > 5 ? 1 : 0);
889 		(void) printf("\tItem %3llu: %s\n",
890 		    (u_longlong_t)itor - 1, blkbuf);
891 	}
892 
893 	bplist_close(&bpl);
894 	mutex_destroy(&bpl.bpl_lock);
895 }
896 
897 static avl_tree_t idx_tree;
898 static avl_tree_t domain_tree;
899 static boolean_t fuid_table_loaded;
900 
901 static void
902 fuid_table_destroy()
903 {
904 	if (fuid_table_loaded) {
905 		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
906 		fuid_table_loaded = B_FALSE;
907 	}
908 }
909 
910 /*
911  * print uid or gid information.
912  * For normal POSIX id just the id is printed in decimal format.
913  * For CIFS files with FUID the fuid is printed in hex followed by
914  * the doman-rid string.
915  */
916 static void
917 print_idstr(uint64_t id, const char *id_type)
918 {
919 	if (FUID_INDEX(id)) {
920 		char *domain;
921 
922 		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
923 		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
924 		    (u_longlong_t)id, domain, (int)FUID_RID(id));
925 	} else {
926 		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
927 	}
928 
929 }
930 
931 static void
932 dump_uidgid(objset_t *os, znode_phys_t *zp)
933 {
934 	uint32_t uid_idx, gid_idx;
935 
936 	uid_idx = FUID_INDEX(zp->zp_uid);
937 	gid_idx = FUID_INDEX(zp->zp_gid);
938 
939 	/* Load domain table, if not already loaded */
940 	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
941 		uint64_t fuid_obj;
942 
943 		/* first find the fuid object.  It lives in the master node */
944 		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
945 		    8, 1, &fuid_obj) == 0);
946 		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
947 		(void) zfs_fuid_table_load(os, fuid_obj,
948 		    &idx_tree, &domain_tree);
949 		fuid_table_loaded = B_TRUE;
950 	}
951 
952 	print_idstr(zp->zp_uid, "uid");
953 	print_idstr(zp->zp_gid, "gid");
954 }
955 
956 /*ARGSUSED*/
957 static void
958 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
959 {
960 	znode_phys_t *zp = data;
961 	time_t z_crtime, z_atime, z_mtime, z_ctime;
962 	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
963 	int error;
964 
965 	ASSERT(size >= sizeof (znode_phys_t));
966 
967 	error = zfs_obj_to_path(os, object, path, sizeof (path));
968 	if (error != 0) {
969 		(void) snprintf(path, sizeof (path), "\?\?\?<object#%llu>",
970 		    (u_longlong_t)object);
971 	}
972 
973 	if (dump_opt['d'] < 3) {
974 		(void) printf("\t%s\n", path);
975 		return;
976 	}
977 
978 	z_crtime = (time_t)zp->zp_crtime[0];
979 	z_atime = (time_t)zp->zp_atime[0];
980 	z_mtime = (time_t)zp->zp_mtime[0];
981 	z_ctime = (time_t)zp->zp_ctime[0];
982 
983 	(void) printf("\tpath	%s\n", path);
984 	dump_uidgid(os, zp);
985 	(void) printf("\tatime	%s", ctime(&z_atime));
986 	(void) printf("\tmtime	%s", ctime(&z_mtime));
987 	(void) printf("\tctime	%s", ctime(&z_ctime));
988 	(void) printf("\tcrtime	%s", ctime(&z_crtime));
989 	(void) printf("\tgen	%llu\n", (u_longlong_t)zp->zp_gen);
990 	(void) printf("\tmode	%llo\n", (u_longlong_t)zp->zp_mode);
991 	(void) printf("\tsize	%llu\n", (u_longlong_t)zp->zp_size);
992 	(void) printf("\tparent	%llu\n", (u_longlong_t)zp->zp_parent);
993 	(void) printf("\tlinks	%llu\n", (u_longlong_t)zp->zp_links);
994 	(void) printf("\txattr	%llu\n", (u_longlong_t)zp->zp_xattr);
995 	(void) printf("\trdev	0x%016llx\n", (u_longlong_t)zp->zp_rdev);
996 }
997 
998 /*ARGSUSED*/
999 static void
1000 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
1001 {
1002 }
1003 
1004 /*ARGSUSED*/
1005 static void
1006 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
1007 {
1008 }
1009 
1010 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES] = {
1011 	dump_none,		/* unallocated			*/
1012 	dump_zap,		/* object directory		*/
1013 	dump_uint64,		/* object array			*/
1014 	dump_none,		/* packed nvlist		*/
1015 	dump_packed_nvlist,	/* packed nvlist size		*/
1016 	dump_none,		/* bplist			*/
1017 	dump_none,		/* bplist header		*/
1018 	dump_none,		/* SPA space map header		*/
1019 	dump_none,		/* SPA space map		*/
1020 	dump_none,		/* ZIL intent log		*/
1021 	dump_dnode,		/* DMU dnode			*/
1022 	dump_dmu_objset,	/* DMU objset			*/
1023 	dump_dsl_dir,		/* DSL directory		*/
1024 	dump_zap,		/* DSL directory child map	*/
1025 	dump_zap,		/* DSL dataset snap map		*/
1026 	dump_zap,		/* DSL props			*/
1027 	dump_dsl_dataset,	/* DSL dataset			*/
1028 	dump_znode,		/* ZFS znode			*/
1029 	dump_acl,		/* ZFS V0 ACL			*/
1030 	dump_uint8,		/* ZFS plain file		*/
1031 	dump_zpldir,		/* ZFS directory		*/
1032 	dump_zap,		/* ZFS master node		*/
1033 	dump_zap,		/* ZFS delete queue		*/
1034 	dump_uint8,		/* zvol object			*/
1035 	dump_zap,		/* zvol prop			*/
1036 	dump_uint8,		/* other uint8[]		*/
1037 	dump_uint64,		/* other uint64[]		*/
1038 	dump_zap,		/* other ZAP			*/
1039 	dump_zap,		/* persistent error log		*/
1040 	dump_uint8,		/* SPA history			*/
1041 	dump_uint64,		/* SPA history offsets		*/
1042 	dump_zap,		/* Pool properties		*/
1043 	dump_zap,		/* DSL permissions		*/
1044 	dump_acl,		/* ZFS ACL			*/
1045 	dump_uint8,		/* ZFS SYSACL			*/
1046 	dump_none,		/* FUID nvlist			*/
1047 	dump_packed_nvlist,	/* FUID nvlist size		*/
1048 	dump_zap,		/* DSL dataset next clones	*/
1049 	dump_zap,		/* DSL scrub queue		*/
1050 	dump_zap,		/* ZFS user/group used		*/
1051 	dump_zap,		/* ZFS user/group quota		*/
1052 };
1053 
1054 static void
1055 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1056 {
1057 	dmu_buf_t *db = NULL;
1058 	dmu_object_info_t doi;
1059 	dnode_t *dn;
1060 	void *bonus = NULL;
1061 	size_t bsize = 0;
1062 	char iblk[6], dblk[6], lsize[6], asize[6], bonus_size[6], segsize[6];
1063 	char aux[50];
1064 	int error;
1065 
1066 	if (*print_header) {
1067 		(void) printf("\n    Object  lvl   iblk   dblk  lsize"
1068 		    "  asize  type\n");
1069 		*print_header = 0;
1070 	}
1071 
1072 	if (object == 0) {
1073 		dn = os->os->os_meta_dnode;
1074 	} else {
1075 		error = dmu_bonus_hold(os, object, FTAG, &db);
1076 		if (error)
1077 			fatal("dmu_bonus_hold(%llu) failed, errno %u",
1078 			    object, error);
1079 		bonus = db->db_data;
1080 		bsize = db->db_size;
1081 		dn = ((dmu_buf_impl_t *)db)->db_dnode;
1082 	}
1083 	dmu_object_info_from_dnode(dn, &doi);
1084 
1085 	nicenum(doi.doi_metadata_block_size, iblk);
1086 	nicenum(doi.doi_data_block_size, dblk);
1087 	nicenum(doi.doi_data_block_size * (doi.doi_max_block_offset + 1),
1088 	    lsize);
1089 	nicenum(doi.doi_physical_blks << 9, asize);
1090 	nicenum(doi.doi_bonus_size, bonus_size);
1091 
1092 	aux[0] = '\0';
1093 
1094 	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1095 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1096 		    zio_checksum_table[doi.doi_checksum].ci_name);
1097 	}
1098 
1099 	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1100 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1101 		    zio_compress_table[doi.doi_compress].ci_name);
1102 	}
1103 
1104 	(void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %s%s\n",
1105 	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk, lsize,
1106 	    asize, dmu_ot[doi.doi_type].ot_name, aux);
1107 
1108 	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1109 		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %s\n",
1110 		    "", "", "", "", bonus_size, "bonus",
1111 		    dmu_ot[doi.doi_bonus_type].ot_name);
1112 	}
1113 
1114 	if (verbosity >= 4) {
1115 		(void) printf("\tdnode flags: %s%s\n",
1116 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
1117 		    "USED_BYTES " : "",
1118 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
1119 		    "USERUSED_ACCOUNTED " : "");
1120 		(void) printf("\tdnode maxblkid: %llu\n",
1121 		    (longlong_t)dn->dn_phys->dn_maxblkid);
1122 
1123 		object_viewer[doi.doi_bonus_type](os, object, bonus, bsize);
1124 		object_viewer[doi.doi_type](os, object, NULL, 0);
1125 		*print_header = 1;
1126 	}
1127 
1128 	if (verbosity >= 5)
1129 		dump_indirect(dn);
1130 
1131 	if (verbosity >= 5) {
1132 		/*
1133 		 * Report the list of segments that comprise the object.
1134 		 */
1135 		uint64_t start = 0;
1136 		uint64_t end;
1137 		uint64_t blkfill = 1;
1138 		int minlvl = 1;
1139 
1140 		if (dn->dn_type == DMU_OT_DNODE) {
1141 			minlvl = 0;
1142 			blkfill = DNODES_PER_BLOCK;
1143 		}
1144 
1145 		for (;;) {
1146 			error = dnode_next_offset(dn,
1147 			    0, &start, minlvl, blkfill, 0);
1148 			if (error)
1149 				break;
1150 			end = start;
1151 			error = dnode_next_offset(dn,
1152 			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
1153 			nicenum(end - start, segsize);
1154 			(void) printf("\t\tsegment [%016llx, %016llx)"
1155 			    " size %5s\n", (u_longlong_t)start,
1156 			    (u_longlong_t)end, segsize);
1157 			if (error)
1158 				break;
1159 			start = end;
1160 		}
1161 	}
1162 
1163 	if (db != NULL)
1164 		dmu_buf_rele(db, FTAG);
1165 }
1166 
1167 static char *objset_types[DMU_OST_NUMTYPES] = {
1168 	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1169 
1170 static void
1171 dump_dir(objset_t *os)
1172 {
1173 	dmu_objset_stats_t dds;
1174 	uint64_t object, object_count;
1175 	uint64_t refdbytes, usedobjs, scratch;
1176 	char numbuf[8];
1177 	char blkbuf[BP_SPRINTF_LEN + 20];
1178 	char osname[MAXNAMELEN];
1179 	char *type = "UNKNOWN";
1180 	int verbosity = dump_opt['d'];
1181 	int print_header = 1;
1182 	int i, error;
1183 
1184 	dmu_objset_fast_stat(os, &dds);
1185 
1186 	if (dds.dds_type < DMU_OST_NUMTYPES)
1187 		type = objset_types[dds.dds_type];
1188 
1189 	if (dds.dds_type == DMU_OST_META) {
1190 		dds.dds_creation_txg = TXG_INITIAL;
1191 		usedobjs = os->os->os_rootbp->blk_fill;
1192 		refdbytes = os->os->os_spa->spa_dsl_pool->
1193 		    dp_mos_dir->dd_phys->dd_used_bytes;
1194 	} else {
1195 		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
1196 	}
1197 
1198 	ASSERT3U(usedobjs, ==, os->os->os_rootbp->blk_fill);
1199 
1200 	nicenum(refdbytes, numbuf);
1201 
1202 	if (verbosity >= 4) {
1203 		(void) sprintf(blkbuf + strlen(blkbuf), ", rootbp ");
1204 		(void) sprintf_blkptr(blkbuf + strlen(blkbuf),
1205 		    BP_SPRINTF_LEN - strlen(blkbuf), os->os->os_rootbp);
1206 	} else {
1207 		blkbuf[0] = '\0';
1208 	}
1209 
1210 	dmu_objset_name(os, osname);
1211 
1212 	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
1213 	    "%s, %llu objects%s\n",
1214 	    osname, type, (u_longlong_t)dmu_objset_id(os),
1215 	    (u_longlong_t)dds.dds_creation_txg,
1216 	    numbuf, (u_longlong_t)usedobjs, blkbuf);
1217 
1218 	dump_intent_log(dmu_objset_zil(os));
1219 
1220 	if (dmu_objset_ds(os) != NULL)
1221 		dump_bplist(dmu_objset_pool(os)->dp_meta_objset,
1222 		    dmu_objset_ds(os)->ds_phys->ds_deadlist_obj, "Deadlist");
1223 
1224 	if (verbosity < 2)
1225 		return;
1226 
1227 	if (os->os->os_rootbp->blk_birth == 0)
1228 		return;
1229 
1230 	if (zopt_objects != 0) {
1231 		for (i = 0; i < zopt_objects; i++)
1232 			dump_object(os, zopt_object[i], verbosity,
1233 			    &print_header);
1234 		(void) printf("\n");
1235 		return;
1236 	}
1237 
1238 	dump_object(os, 0, verbosity, &print_header);
1239 	object_count = 0;
1240 	if (os->os->os_userused_dnode &&
1241 	    os->os->os_userused_dnode->dn_type != 0) {
1242 		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header);
1243 		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header);
1244 	}
1245 
1246 	object = 0;
1247 	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1248 		dump_object(os, object, verbosity, &print_header);
1249 		object_count++;
1250 	}
1251 
1252 	ASSERT3U(object_count, ==, usedobjs);
1253 
1254 	(void) printf("\n");
1255 
1256 	if (error != ESRCH) {
1257 		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
1258 		abort();
1259 	}
1260 }
1261 
1262 static void
1263 dump_uberblock(uberblock_t *ub)
1264 {
1265 	time_t timestamp = ub->ub_timestamp;
1266 
1267 	(void) printf("Uberblock\n\n");
1268 	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
1269 	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
1270 	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
1271 	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
1272 	(void) printf("\ttimestamp = %llu UTC = %s",
1273 	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
1274 	if (dump_opt['u'] >= 3) {
1275 		char blkbuf[BP_SPRINTF_LEN];
1276 		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &ub->ub_rootbp);
1277 		(void) printf("\trootbp = %s\n", blkbuf);
1278 	}
1279 	(void) printf("\n");
1280 }
1281 
1282 static void
1283 dump_config(const char *pool)
1284 {
1285 	spa_t *spa = NULL;
1286 
1287 	mutex_enter(&spa_namespace_lock);
1288 	while ((spa = spa_next(spa)) != NULL) {
1289 		if (pool == NULL)
1290 			(void) printf("%s\n", spa_name(spa));
1291 		if (pool == NULL || strcmp(pool, spa_name(spa)) == 0)
1292 			dump_nvlist(spa->spa_config, 4);
1293 	}
1294 	mutex_exit(&spa_namespace_lock);
1295 }
1296 
1297 static void
1298 dump_cachefile(const char *cachefile)
1299 {
1300 	int fd;
1301 	struct stat64 statbuf;
1302 	char *buf;
1303 	nvlist_t *config;
1304 
1305 	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
1306 		(void) printf("cannot open '%s': %s\n", cachefile,
1307 		    strerror(errno));
1308 		exit(1);
1309 	}
1310 
1311 	if (fstat64(fd, &statbuf) != 0) {
1312 		(void) printf("failed to stat '%s': %s\n", cachefile,
1313 		    strerror(errno));
1314 		exit(1);
1315 	}
1316 
1317 	if ((buf = malloc(statbuf.st_size)) == NULL) {
1318 		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
1319 		    (u_longlong_t)statbuf.st_size);
1320 		exit(1);
1321 	}
1322 
1323 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1324 		(void) fprintf(stderr, "failed to read %llu bytes\n",
1325 		    (u_longlong_t)statbuf.st_size);
1326 		exit(1);
1327 	}
1328 
1329 	(void) close(fd);
1330 
1331 	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
1332 		(void) fprintf(stderr, "failed to unpack nvlist\n");
1333 		exit(1);
1334 	}
1335 
1336 	free(buf);
1337 
1338 	dump_nvlist(config, 0);
1339 
1340 	nvlist_free(config);
1341 }
1342 
1343 static void
1344 dump_label(const char *dev)
1345 {
1346 	int fd;
1347 	vdev_label_t label;
1348 	char *buf = label.vl_vdev_phys.vp_nvlist;
1349 	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1350 	struct stat64 statbuf;
1351 	uint64_t psize;
1352 	int l;
1353 
1354 	if ((fd = open64(dev, O_RDONLY)) < 0) {
1355 		(void) printf("cannot open '%s': %s\n", dev, strerror(errno));
1356 		exit(1);
1357 	}
1358 
1359 	if (fstat64(fd, &statbuf) != 0) {
1360 		(void) printf("failed to stat '%s': %s\n", dev,
1361 		    strerror(errno));
1362 		exit(1);
1363 	}
1364 
1365 	psize = statbuf.st_size;
1366 	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
1367 
1368 	for (l = 0; l < VDEV_LABELS; l++) {
1369 
1370 		nvlist_t *config = NULL;
1371 
1372 		(void) printf("--------------------------------------------\n");
1373 		(void) printf("LABEL %d\n", l);
1374 		(void) printf("--------------------------------------------\n");
1375 
1376 		if (pread64(fd, &label, sizeof (label),
1377 		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
1378 			(void) printf("failed to read label %d\n", l);
1379 			continue;
1380 		}
1381 
1382 		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
1383 			(void) printf("failed to unpack label %d\n", l);
1384 			continue;
1385 		}
1386 		dump_nvlist(config, 4);
1387 		nvlist_free(config);
1388 	}
1389 }
1390 
1391 /*ARGSUSED*/
1392 static int
1393 dump_one_dir(char *dsname, void *arg)
1394 {
1395 	int error;
1396 	objset_t *os;
1397 
1398 	error = dmu_objset_open(dsname, DMU_OST_ANY,
1399 	    DS_MODE_USER | DS_MODE_READONLY, &os);
1400 	if (error) {
1401 		(void) printf("Could not open %s\n", dsname);
1402 		return (0);
1403 	}
1404 	dump_dir(os);
1405 	dmu_objset_close(os);
1406 	fuid_table_destroy();
1407 	return (0);
1408 }
1409 
1410 static void
1411 zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
1412 {
1413 	vdev_t *vd = sm->sm_ppd;
1414 
1415 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
1416 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
1417 }
1418 
1419 /* ARGSUSED */
1420 static void
1421 zdb_space_map_load(space_map_t *sm)
1422 {
1423 }
1424 
1425 static void
1426 zdb_space_map_unload(space_map_t *sm)
1427 {
1428 	space_map_vacate(sm, zdb_leak, sm);
1429 }
1430 
1431 /* ARGSUSED */
1432 static void
1433 zdb_space_map_claim(space_map_t *sm, uint64_t start, uint64_t size)
1434 {
1435 }
1436 
1437 static space_map_ops_t zdb_space_map_ops = {
1438 	zdb_space_map_load,
1439 	zdb_space_map_unload,
1440 	NULL,	/* alloc */
1441 	zdb_space_map_claim,
1442 	NULL,	/* free */
1443 	NULL	/* maxsize */
1444 };
1445 
1446 static void
1447 zdb_leak_init(spa_t *spa)
1448 {
1449 	vdev_t *rvd = spa->spa_root_vdev;
1450 
1451 	for (int c = 0; c < rvd->vdev_children; c++) {
1452 		vdev_t *vd = rvd->vdev_child[c];
1453 		for (int m = 0; m < vd->vdev_ms_count; m++) {
1454 			metaslab_t *msp = vd->vdev_ms[m];
1455 			mutex_enter(&msp->ms_lock);
1456 			VERIFY(space_map_load(&msp->ms_map, &zdb_space_map_ops,
1457 			    SM_ALLOC, &msp->ms_smo, spa->spa_meta_objset) == 0);
1458 			msp->ms_map.sm_ppd = vd;
1459 			mutex_exit(&msp->ms_lock);
1460 		}
1461 	}
1462 }
1463 
1464 static void
1465 zdb_leak_fini(spa_t *spa)
1466 {
1467 	vdev_t *rvd = spa->spa_root_vdev;
1468 
1469 	for (int c = 0; c < rvd->vdev_children; c++) {
1470 		vdev_t *vd = rvd->vdev_child[c];
1471 		for (int m = 0; m < vd->vdev_ms_count; m++) {
1472 			metaslab_t *msp = vd->vdev_ms[m];
1473 			mutex_enter(&msp->ms_lock);
1474 			space_map_unload(&msp->ms_map);
1475 			mutex_exit(&msp->ms_lock);
1476 		}
1477 	}
1478 }
1479 
1480 /*
1481  * Verify that the sum of the sizes of all blocks in the pool adds up
1482  * to the SPA's sa_alloc total.
1483  */
1484 typedef struct zdb_blkstats {
1485 	uint64_t	zb_asize;
1486 	uint64_t	zb_lsize;
1487 	uint64_t	zb_psize;
1488 	uint64_t	zb_count;
1489 } zdb_blkstats_t;
1490 
1491 #define	DMU_OT_DEFERRED	DMU_OT_NONE
1492 #define	DMU_OT_TOTAL	DMU_OT_NUMTYPES
1493 
1494 #define	ZB_TOTAL	DN_MAX_LEVELS
1495 
1496 typedef struct zdb_cb {
1497 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][DMU_OT_TOTAL + 1];
1498 	uint64_t	zcb_errors[256];
1499 	int		zcb_readfails;
1500 	int		zcb_haderrors;
1501 } zdb_cb_t;
1502 
1503 static void
1504 zdb_count_block(spa_t *spa, zdb_cb_t *zcb, blkptr_t *bp, dmu_object_type_t type)
1505 {
1506 	for (int i = 0; i < 4; i++) {
1507 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
1508 		int t = (i & 1) ? type : DMU_OT_TOTAL;
1509 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
1510 
1511 		zb->zb_asize += BP_GET_ASIZE(bp);
1512 		zb->zb_lsize += BP_GET_LSIZE(bp);
1513 		zb->zb_psize += BP_GET_PSIZE(bp);
1514 		zb->zb_count++;
1515 	}
1516 
1517 	if (dump_opt['S']) {
1518 		boolean_t print_sig;
1519 
1520 		print_sig = !zdb_sig_user_data || (BP_GET_LEVEL(bp) == 0 &&
1521 		    BP_GET_TYPE(bp) == DMU_OT_PLAIN_FILE_CONTENTS);
1522 
1523 		if (BP_GET_CHECKSUM(bp) < zdb_sig_cksumalg)
1524 			print_sig = B_FALSE;
1525 
1526 		if (print_sig) {
1527 			(void) printf("%llu\t%lld\t%lld\t%s\t%s\t%s\t"
1528 			    "%llx:%llx:%llx:%llx\n",
1529 			    (u_longlong_t)BP_GET_LEVEL(bp),
1530 			    (longlong_t)BP_GET_PSIZE(bp),
1531 			    (longlong_t)BP_GET_NDVAS(bp),
1532 			    dmu_ot[BP_GET_TYPE(bp)].ot_name,
1533 			    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
1534 			    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name,
1535 			    (u_longlong_t)bp->blk_cksum.zc_word[0],
1536 			    (u_longlong_t)bp->blk_cksum.zc_word[1],
1537 			    (u_longlong_t)bp->blk_cksum.zc_word[2],
1538 			    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1539 		}
1540 	}
1541 
1542 	if (!dump_opt['L'])
1543 		VERIFY(zio_wait(zio_claim(NULL, spa, spa_first_txg(spa), bp,
1544 		    NULL, NULL, ZIO_FLAG_MUSTSUCCEED)) == 0);
1545 }
1546 
1547 static int
1548 zdb_blkptr_cb(spa_t *spa, blkptr_t *bp, const zbookmark_t *zb,
1549     const dnode_phys_t *dnp, void *arg)
1550 {
1551 	zdb_cb_t *zcb = arg;
1552 	char blkbuf[BP_SPRINTF_LEN];
1553 	dmu_object_type_t type;
1554 	boolean_t is_l0_metadata;
1555 
1556 	if (bp == NULL)
1557 		return (0);
1558 
1559 	type = BP_GET_TYPE(bp);
1560 
1561 	zdb_count_block(spa, zcb, bp, type);
1562 
1563 	/*
1564 	 * if we do metadata-only checksumming there's no need to checksum
1565 	 * indirect blocks here because it is done during traverse
1566 	 */
1567 	is_l0_metadata = (BP_GET_LEVEL(bp) == 0 && type < DMU_OT_NUMTYPES &&
1568 	    dmu_ot[type].ot_metadata);
1569 
1570 	if (dump_opt['c'] > 1 || dump_opt['S'] ||
1571 	    (dump_opt['c'] && is_l0_metadata)) {
1572 		int ioerr, size;
1573 		void *data;
1574 
1575 		size = BP_GET_LSIZE(bp);
1576 		data = malloc(size);
1577 		ioerr = zio_wait(zio_read(NULL, spa, bp, data, size,
1578 		    NULL, NULL, ZIO_PRIORITY_ASYNC_READ,
1579 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB, zb));
1580 		free(data);
1581 
1582 		/* We expect io errors on intent log */
1583 		if (ioerr && type != DMU_OT_INTENT_LOG) {
1584 			zcb->zcb_haderrors = 1;
1585 			zcb->zcb_errors[ioerr]++;
1586 
1587 			if (dump_opt['b'] >= 2)
1588 				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1589 			else
1590 				blkbuf[0] = '\0';
1591 
1592 			if (!dump_opt['S']) {
1593 				(void) printf("zdb_blkptr_cb: "
1594 				    "Got error %d reading "
1595 				    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
1596 				    ioerr,
1597 				    (u_longlong_t)zb->zb_objset,
1598 				    (u_longlong_t)zb->zb_object,
1599 				    (u_longlong_t)zb->zb_level,
1600 				    (u_longlong_t)zb->zb_blkid,
1601 				    blkbuf);
1602 			}
1603 		}
1604 	}
1605 
1606 	zcb->zcb_readfails = 0;
1607 
1608 	if (dump_opt['b'] >= 4) {
1609 		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1610 		(void) printf("objset %llu object %llu offset 0x%llx %s\n",
1611 		    (u_longlong_t)zb->zb_objset,
1612 		    (u_longlong_t)zb->zb_object,
1613 		    (u_longlong_t)blkid2offset(dnp, zb->zb_level, zb->zb_blkid),
1614 		    blkbuf);
1615 	}
1616 
1617 	return (0);
1618 }
1619 
1620 static int
1621 dump_block_stats(spa_t *spa)
1622 {
1623 	zdb_cb_t zcb = { 0 };
1624 	zdb_blkstats_t *zb, *tzb;
1625 	uint64_t alloc, space, logalloc;
1626 	vdev_t *rvd = spa->spa_root_vdev;
1627 	int leaks = 0;
1628 	int c, e;
1629 
1630 	if (!dump_opt['S']) {
1631 		(void) printf("\nTraversing all blocks %s%s%s%s%s...\n",
1632 		    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
1633 		    (dump_opt['c'] == 1) ? "metadata " : "",
1634 		    dump_opt['c'] ? "checksums " : "",
1635 		    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
1636 		    !dump_opt['L'] ? "nothing leaked " : "");
1637 	}
1638 
1639 	/*
1640 	 * Load all space maps as SM_ALLOC maps, then traverse the pool
1641 	 * claiming each block we discover.  If the pool is perfectly
1642 	 * consistent, the space maps will be empty when we're done.
1643 	 * Anything left over is a leak; any block we can't claim (because
1644 	 * it's not part of any space map) is a double allocation,
1645 	 * reference to a freed block, or an unclaimed log block.
1646 	 */
1647 	if (!dump_opt['L'])
1648 		zdb_leak_init(spa);
1649 
1650 	/*
1651 	 * If there's a deferred-free bplist, process that first.
1652 	 */
1653 	if (spa->spa_sync_bplist_obj != 0) {
1654 		bplist_t *bpl = &spa->spa_sync_bplist;
1655 		blkptr_t blk;
1656 		uint64_t itor = 0;
1657 
1658 		VERIFY(0 == bplist_open(bpl, spa->spa_meta_objset,
1659 		    spa->spa_sync_bplist_obj));
1660 
1661 		while (bplist_iterate(bpl, &itor, &blk) == 0) {
1662 			if (dump_opt['b'] >= 4) {
1663 				char blkbuf[BP_SPRINTF_LEN];
1664 				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &blk);
1665 				(void) printf("[%s] %s\n",
1666 				    "deferred free", blkbuf);
1667 			}
1668 			zdb_count_block(spa, &zcb, &blk, DMU_OT_DEFERRED);
1669 		}
1670 
1671 		bplist_close(bpl);
1672 	}
1673 
1674 	zcb.zcb_haderrors |= traverse_pool(spa, zdb_blkptr_cb, &zcb);
1675 
1676 	if (zcb.zcb_haderrors && !dump_opt['S']) {
1677 		(void) printf("\nError counts:\n\n");
1678 		(void) printf("\t%5s  %s\n", "errno", "count");
1679 		for (e = 0; e < 256; e++) {
1680 			if (zcb.zcb_errors[e] != 0) {
1681 				(void) printf("\t%5d  %llu\n",
1682 				    e, (u_longlong_t)zcb.zcb_errors[e]);
1683 			}
1684 		}
1685 	}
1686 
1687 	/*
1688 	 * Report any leaked segments.
1689 	 */
1690 	if (!dump_opt['L'])
1691 		zdb_leak_fini(spa);
1692 
1693 	/*
1694 	 * If we're interested in printing out the blkptr signatures,
1695 	 * return now as we don't print out anything else (including
1696 	 * errors and leaks).
1697 	 */
1698 	if (dump_opt['S'])
1699 		return (zcb.zcb_haderrors ? 3 : 0);
1700 
1701 	alloc = spa_get_alloc(spa);
1702 	space = spa_get_space(spa);
1703 
1704 	/*
1705 	 * Log blocks allocated from a separate log device don't count
1706 	 * as part of the normal pool space; factor them in here.
1707 	 */
1708 	logalloc = 0;
1709 
1710 	for (c = 0; c < rvd->vdev_children; c++)
1711 		if (rvd->vdev_child[c]->vdev_islog)
1712 			logalloc += rvd->vdev_child[c]->vdev_stat.vs_alloc;
1713 
1714 	tzb = &zcb.zcb_type[ZB_TOTAL][DMU_OT_TOTAL];
1715 
1716 	if (tzb->zb_asize == alloc + logalloc) {
1717 		if (!dump_opt['L'])
1718 			(void) printf("\n\tNo leaks (block sum matches space"
1719 			    " maps exactly)\n");
1720 	} else {
1721 		(void) printf("block traversal size %llu != alloc %llu "
1722 		    "(%s %lld)\n",
1723 		    (u_longlong_t)tzb->zb_asize,
1724 		    (u_longlong_t)alloc + logalloc,
1725 		    (dump_opt['L']) ? "unreachable" : "leaked",
1726 		    (longlong_t)(alloc + logalloc - tzb->zb_asize));
1727 		leaks = 1;
1728 	}
1729 
1730 	if (tzb->zb_count == 0)
1731 		return (2);
1732 
1733 	(void) printf("\n");
1734 	(void) printf("\tbp count:      %10llu\n",
1735 	    (u_longlong_t)tzb->zb_count);
1736 	(void) printf("\tbp logical:    %10llu\t avg: %6llu\n",
1737 	    (u_longlong_t)tzb->zb_lsize,
1738 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
1739 	(void) printf("\tbp physical:   %10llu\t avg:"
1740 	    " %6llu\tcompression: %6.2f\n",
1741 	    (u_longlong_t)tzb->zb_psize,
1742 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
1743 	    (double)tzb->zb_lsize / tzb->zb_psize);
1744 	(void) printf("\tbp allocated:  %10llu\t avg:"
1745 	    " %6llu\tcompression: %6.2f\n",
1746 	    (u_longlong_t)tzb->zb_asize,
1747 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
1748 	    (double)tzb->zb_lsize / tzb->zb_asize);
1749 	(void) printf("\tSPA allocated: %10llu\tused: %5.2f%%\n",
1750 	    (u_longlong_t)alloc, 100.0 * alloc / space);
1751 
1752 	if (dump_opt['b'] >= 2) {
1753 		int l, t, level;
1754 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
1755 		    "\t  avg\t comp\t%%Total\tType\n");
1756 
1757 		for (t = 0; t <= DMU_OT_NUMTYPES; t++) {
1758 			char csize[6], lsize[6], psize[6], asize[6], avg[6];
1759 			char *typename;
1760 
1761 			typename = t == DMU_OT_DEFERRED ? "deferred free" :
1762 			    t == DMU_OT_TOTAL ? "Total" : dmu_ot[t].ot_name;
1763 
1764 			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
1765 				(void) printf("%6s\t%5s\t%5s\t%5s"
1766 				    "\t%5s\t%5s\t%6s\t%s\n",
1767 				    "-",
1768 				    "-",
1769 				    "-",
1770 				    "-",
1771 				    "-",
1772 				    "-",
1773 				    "-",
1774 				    typename);
1775 				continue;
1776 			}
1777 
1778 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
1779 				level = (l == -1 ? ZB_TOTAL : l);
1780 				zb = &zcb.zcb_type[level][t];
1781 
1782 				if (zb->zb_asize == 0)
1783 					continue;
1784 
1785 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
1786 					continue;
1787 
1788 				if (level == 0 && zb->zb_asize ==
1789 				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
1790 					continue;
1791 
1792 				nicenum(zb->zb_count, csize);
1793 				nicenum(zb->zb_lsize, lsize);
1794 				nicenum(zb->zb_psize, psize);
1795 				nicenum(zb->zb_asize, asize);
1796 				nicenum(zb->zb_asize / zb->zb_count, avg);
1797 
1798 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
1799 				    "\t%5.2f\t%6.2f\t",
1800 				    csize, lsize, psize, asize, avg,
1801 				    (double)zb->zb_lsize / zb->zb_psize,
1802 				    100.0 * zb->zb_asize / tzb->zb_asize);
1803 
1804 				if (level == ZB_TOTAL)
1805 					(void) printf("%s\n", typename);
1806 				else
1807 					(void) printf("    L%d %s\n",
1808 					    level, typename);
1809 			}
1810 		}
1811 	}
1812 
1813 	(void) printf("\n");
1814 
1815 	if (leaks)
1816 		return (2);
1817 
1818 	if (zcb.zcb_haderrors)
1819 		return (3);
1820 
1821 	return (0);
1822 }
1823 
1824 static void
1825 dump_zpool(spa_t *spa)
1826 {
1827 	dsl_pool_t *dp = spa_get_dsl(spa);
1828 	int rc = 0;
1829 
1830 	if (dump_opt['u'])
1831 		dump_uberblock(&spa->spa_uberblock);
1832 
1833 	if (dump_opt['d'] || dump_opt['i'] || dump_opt['m']) {
1834 		dump_dir(dp->dp_meta_objset);
1835 		if (dump_opt['d'] >= 3) {
1836 			dump_bplist(dp->dp_meta_objset,
1837 			    spa->spa_sync_bplist_obj, "Deferred frees");
1838 			dump_dtl(spa->spa_root_vdev, 0);
1839 		}
1840 
1841 		if (dump_opt['d'] >= 3 || dump_opt['m'])
1842 			dump_metaslabs(spa);
1843 
1844 		(void) dmu_objset_find(spa_name(spa), dump_one_dir, NULL,
1845 		    DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
1846 	}
1847 
1848 	if (dump_opt['b'] || dump_opt['c'] || dump_opt['S'])
1849 		rc = dump_block_stats(spa);
1850 
1851 	if (dump_opt['s'])
1852 		show_pool_stats(spa);
1853 
1854 	if (rc != 0)
1855 		exit(rc);
1856 }
1857 
1858 #define	ZDB_FLAG_CHECKSUM	0x0001
1859 #define	ZDB_FLAG_DECOMPRESS	0x0002
1860 #define	ZDB_FLAG_BSWAP		0x0004
1861 #define	ZDB_FLAG_GBH		0x0008
1862 #define	ZDB_FLAG_INDIRECT	0x0010
1863 #define	ZDB_FLAG_PHYS		0x0020
1864 #define	ZDB_FLAG_RAW		0x0040
1865 #define	ZDB_FLAG_PRINT_BLKPTR	0x0080
1866 
1867 int flagbits[256];
1868 
1869 static void
1870 zdb_print_blkptr(blkptr_t *bp, int flags)
1871 {
1872 	dva_t *dva = bp->blk_dva;
1873 	int d;
1874 
1875 	if (flags & ZDB_FLAG_BSWAP)
1876 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
1877 	/*
1878 	 * Super-ick warning:  This code is also duplicated in
1879 	 * cmd/mdb/common/modules/zfs/zfs.c .  Yeah, I hate code
1880 	 * replication, too.
1881 	 */
1882 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1883 		(void) printf("\tDVA[%d]: vdev_id %lld / %llx\n", d,
1884 		    (longlong_t)DVA_GET_VDEV(&dva[d]),
1885 		    (longlong_t)DVA_GET_OFFSET(&dva[d]));
1886 		(void) printf("\tDVA[%d]:       GANG: %-5s  GRID:  %04llx\t"
1887 		    "ASIZE: %llx\n", d,
1888 		    DVA_GET_GANG(&dva[d]) ? "TRUE" : "FALSE",
1889 		    (longlong_t)DVA_GET_GRID(&dva[d]),
1890 		    (longlong_t)DVA_GET_ASIZE(&dva[d]));
1891 		(void) printf("\tDVA[%d]: :%llu:%llx:%llx:%s%s%s%s\n", d,
1892 		    (u_longlong_t)DVA_GET_VDEV(&dva[d]),
1893 		    (longlong_t)DVA_GET_OFFSET(&dva[d]),
1894 		    (longlong_t)BP_GET_PSIZE(bp),
1895 		    BP_SHOULD_BYTESWAP(bp) ? "e" : "",
1896 		    !DVA_GET_GANG(&dva[d]) && BP_GET_LEVEL(bp) != 0 ?
1897 		    "d" : "",
1898 		    DVA_GET_GANG(&dva[d]) ? "g" : "",
1899 		    BP_GET_COMPRESS(bp) != 0 ? "d" : "");
1900 	}
1901 	(void) printf("\tLSIZE:  %-16llx\t\tPSIZE: %llx\n",
1902 	    (longlong_t)BP_GET_LSIZE(bp), (longlong_t)BP_GET_PSIZE(bp));
1903 	(void) printf("\tENDIAN: %6s\t\t\t\t\tTYPE:  %s\n",
1904 	    BP_GET_BYTEORDER(bp) ? "LITTLE" : "BIG",
1905 	    dmu_ot[BP_GET_TYPE(bp)].ot_name);
1906 	(void) printf("\tBIRTH:  %-16llx   LEVEL: %-2llu\tFILL:  %llx\n",
1907 	    (u_longlong_t)bp->blk_birth, (u_longlong_t)BP_GET_LEVEL(bp),
1908 	    (u_longlong_t)bp->blk_fill);
1909 	(void) printf("\tCKFUNC: %-16s\t\tCOMP:  %s\n",
1910 	    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
1911 	    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name);
1912 	(void) printf("\tCKSUM:  %llx:%llx:%llx:%llx\n",
1913 	    (u_longlong_t)bp->blk_cksum.zc_word[0],
1914 	    (u_longlong_t)bp->blk_cksum.zc_word[1],
1915 	    (u_longlong_t)bp->blk_cksum.zc_word[2],
1916 	    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1917 }
1918 
1919 static void
1920 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
1921 {
1922 	int i;
1923 
1924 	for (i = 0; i < nbps; i++)
1925 		zdb_print_blkptr(&bp[i], flags);
1926 }
1927 
1928 static void
1929 zdb_dump_gbh(void *buf, int flags)
1930 {
1931 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
1932 }
1933 
1934 static void
1935 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
1936 {
1937 	if (flags & ZDB_FLAG_BSWAP)
1938 		byteswap_uint64_array(buf, size);
1939 	(void) write(2, buf, size);
1940 }
1941 
1942 static void
1943 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
1944 {
1945 	uint64_t *d = (uint64_t *)buf;
1946 	int nwords = size / sizeof (uint64_t);
1947 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
1948 	int i, j;
1949 	char *hdr, *c;
1950 
1951 
1952 	if (do_bswap)
1953 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
1954 	else
1955 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
1956 
1957 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
1958 
1959 	for (i = 0; i < nwords; i += 2) {
1960 		(void) printf("%06llx:  %016llx  %016llx  ",
1961 		    (u_longlong_t)(i * sizeof (uint64_t)),
1962 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
1963 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
1964 
1965 		c = (char *)&d[i];
1966 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
1967 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
1968 		(void) printf("\n");
1969 	}
1970 }
1971 
1972 /*
1973  * There are two acceptable formats:
1974  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
1975  *	child[.child]*    - For example: 0.1.1
1976  *
1977  * The second form can be used to specify arbitrary vdevs anywhere
1978  * in the heirarchy.  For example, in a pool with a mirror of
1979  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
1980  */
1981 static vdev_t *
1982 zdb_vdev_lookup(vdev_t *vdev, char *path)
1983 {
1984 	char *s, *p, *q;
1985 	int i;
1986 
1987 	if (vdev == NULL)
1988 		return (NULL);
1989 
1990 	/* First, assume the x.x.x.x format */
1991 	i = (int)strtoul(path, &s, 10);
1992 	if (s == path || (s && *s != '.' && *s != '\0'))
1993 		goto name;
1994 	if (i < 0 || i >= vdev->vdev_children)
1995 		return (NULL);
1996 
1997 	vdev = vdev->vdev_child[i];
1998 	if (*s == '\0')
1999 		return (vdev);
2000 	return (zdb_vdev_lookup(vdev, s+1));
2001 
2002 name:
2003 	for (i = 0; i < vdev->vdev_children; i++) {
2004 		vdev_t *vc = vdev->vdev_child[i];
2005 
2006 		if (vc->vdev_path == NULL) {
2007 			vc = zdb_vdev_lookup(vc, path);
2008 			if (vc == NULL)
2009 				continue;
2010 			else
2011 				return (vc);
2012 		}
2013 
2014 		p = strrchr(vc->vdev_path, '/');
2015 		p = p ? p + 1 : vc->vdev_path;
2016 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2017 
2018 		if (strcmp(vc->vdev_path, path) == 0)
2019 			return (vc);
2020 		if (strcmp(p, path) == 0)
2021 			return (vc);
2022 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2023 			return (vc);
2024 	}
2025 
2026 	return (NULL);
2027 }
2028 
2029 /*
2030  * Read a block from a pool and print it out.  The syntax of the
2031  * block descriptor is:
2032  *
2033  *	pool:vdev_specifier:offset:size[:flags]
2034  *
2035  *	pool           - The name of the pool you wish to read from
2036  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2037  *	offset         - offset, in hex, in bytes
2038  *	size           - Amount of data to read, in hex, in bytes
2039  *	flags          - A string of characters specifying options
2040  *		 b: Decode a blkptr at given offset within block
2041  *		*c: Calculate and display checksums
2042  *		*d: Decompress data before dumping
2043  *		 e: Byteswap data before dumping
2044  *		*g: Display data as a gang block header
2045  *		*i: Display as an indirect block
2046  *		 p: Do I/O to physical offset
2047  *		 r: Dump raw data to stdout
2048  *
2049  *              * = not yet implemented
2050  */
2051 static void
2052 zdb_read_block(char *thing, spa_t **spap)
2053 {
2054 	spa_t *spa = *spap;
2055 	int flags = 0;
2056 	uint64_t offset = 0, size = 0, blkptr_offset = 0;
2057 	zio_t *zio;
2058 	vdev_t *vd;
2059 	void *buf;
2060 	char *s, *p, *dup, *pool, *vdev, *flagstr;
2061 	int i, error, zio_flags;
2062 
2063 	dup = strdup(thing);
2064 	s = strtok(dup, ":");
2065 	pool = s ? s : "";
2066 	s = strtok(NULL, ":");
2067 	vdev = s ? s : "";
2068 	s = strtok(NULL, ":");
2069 	offset = strtoull(s ? s : "", NULL, 16);
2070 	s = strtok(NULL, ":");
2071 	size = strtoull(s ? s : "", NULL, 16);
2072 	s = strtok(NULL, ":");
2073 	flagstr = s ? s : "";
2074 
2075 	s = NULL;
2076 	if (size == 0)
2077 		s = "size must not be zero";
2078 	if (!IS_P2ALIGNED(size, DEV_BSIZE))
2079 		s = "size must be a multiple of sector size";
2080 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
2081 		s = "offset must be a multiple of sector size";
2082 	if (s) {
2083 		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
2084 		free(dup);
2085 		return;
2086 	}
2087 
2088 	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
2089 		for (i = 0; flagstr[i]; i++) {
2090 			int bit = flagbits[(uchar_t)flagstr[i]];
2091 
2092 			if (bit == 0) {
2093 				(void) printf("***Invalid flag: %c\n",
2094 				    flagstr[i]);
2095 				continue;
2096 			}
2097 			flags |= bit;
2098 
2099 			/* If it's not something with an argument, keep going */
2100 			if ((bit & (ZDB_FLAG_CHECKSUM | ZDB_FLAG_DECOMPRESS |
2101 			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
2102 				continue;
2103 
2104 			p = &flagstr[i + 1];
2105 			if (bit == ZDB_FLAG_PRINT_BLKPTR)
2106 				blkptr_offset = strtoull(p, &p, 16);
2107 			if (*p != ':' && *p != '\0') {
2108 				(void) printf("***Invalid flag arg: '%s'\n", s);
2109 				free(dup);
2110 				return;
2111 			}
2112 		}
2113 	}
2114 
2115 	if (spa == NULL || strcmp(spa_name(spa), pool) != 0) {
2116 		if (spa)
2117 			spa_close(spa, (void *)zdb_read_block);
2118 		error = spa_open(pool, spap, (void *)zdb_read_block);
2119 		if (error)
2120 			fatal("Failed to open pool '%s': %s",
2121 			    pool, strerror(error));
2122 		spa = *spap;
2123 	}
2124 
2125 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2126 	if (vd == NULL) {
2127 		(void) printf("***Invalid vdev: %s\n", vdev);
2128 		free(dup);
2129 		return;
2130 	} else {
2131 		if (vd->vdev_path)
2132 			(void) printf("Found vdev: %s\n", vd->vdev_path);
2133 		else
2134 			(void) printf("Found vdev type: %s\n",
2135 			    vd->vdev_ops->vdev_op_type);
2136 	}
2137 
2138 	buf = umem_alloc(size, UMEM_NOFAIL);
2139 
2140 	zio_flags = ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2141 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY;
2142 
2143 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
2144 	zio = zio_root(spa, NULL, NULL, 0);
2145 	/* XXX todo - cons up a BP so RAID-Z will be happy */
2146 	zio_nowait(zio_vdev_child_io(zio, NULL, vd, offset, buf, size,
2147 	    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ, zio_flags, NULL, NULL));
2148 	error = zio_wait(zio);
2149 	spa_config_exit(spa, SCL_STATE, FTAG);
2150 
2151 	if (error) {
2152 		(void) printf("Read of %s failed, error: %d\n", thing, error);
2153 		goto out;
2154 	}
2155 
2156 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2157 		zdb_print_blkptr((blkptr_t *)(void *)
2158 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2159 	else if (flags & ZDB_FLAG_RAW)
2160 		zdb_dump_block_raw(buf, size, flags);
2161 	else if (flags & ZDB_FLAG_INDIRECT)
2162 		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2163 		    flags);
2164 	else if (flags & ZDB_FLAG_GBH)
2165 		zdb_dump_gbh(buf, flags);
2166 	else
2167 		zdb_dump_block(thing, buf, size, flags);
2168 
2169 out:
2170 	umem_free(buf, size);
2171 	free(dup);
2172 }
2173 
2174 static boolean_t
2175 nvlist_string_match(nvlist_t *config, char *name, char *tgt)
2176 {
2177 	char *s;
2178 
2179 	if (nvlist_lookup_string(config, name, &s) != 0)
2180 		return (B_FALSE);
2181 
2182 	return (strcmp(s, tgt) == 0);
2183 }
2184 
2185 static boolean_t
2186 nvlist_uint64_match(nvlist_t *config, char *name, uint64_t tgt)
2187 {
2188 	uint64_t val;
2189 
2190 	if (nvlist_lookup_uint64(config, name, &val) != 0)
2191 		return (B_FALSE);
2192 
2193 	return (val == tgt);
2194 }
2195 
2196 static boolean_t
2197 vdev_child_guid_match(nvlist_t *vdev, uint64_t guid)
2198 {
2199 	nvlist_t **child;
2200 	uint_t c, children;
2201 
2202 	verify(nvlist_lookup_nvlist_array(vdev, ZPOOL_CONFIG_CHILDREN,
2203 	    &child, &children) == 0);
2204 	for (c = 0; c < children; ++c)
2205 		if (nvlist_uint64_match(child[c], ZPOOL_CONFIG_GUID, guid))
2206 			return (B_TRUE);
2207 	return (B_FALSE);
2208 }
2209 
2210 static boolean_t
2211 vdev_child_string_match(nvlist_t *vdev, char *tgt)
2212 {
2213 	nvlist_t **child;
2214 	uint_t c, children;
2215 
2216 	verify(nvlist_lookup_nvlist_array(vdev, ZPOOL_CONFIG_CHILDREN,
2217 	    &child, &children) == 0);
2218 	for (c = 0; c < children; ++c) {
2219 		if (nvlist_string_match(child[c], ZPOOL_CONFIG_PATH, tgt) ||
2220 		    nvlist_string_match(child[c], ZPOOL_CONFIG_DEVID, tgt))
2221 			return (B_TRUE);
2222 	}
2223 	return (B_FALSE);
2224 }
2225 
2226 static boolean_t
2227 vdev_guid_match(nvlist_t *config, uint64_t guid)
2228 {
2229 	nvlist_t *nvroot;
2230 
2231 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2232 	    &nvroot) == 0);
2233 
2234 	return (nvlist_uint64_match(nvroot, ZPOOL_CONFIG_GUID, guid) ||
2235 	    vdev_child_guid_match(nvroot, guid));
2236 }
2237 
2238 static boolean_t
2239 vdev_string_match(nvlist_t *config, char *tgt)
2240 {
2241 	nvlist_t *nvroot;
2242 
2243 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2244 	    &nvroot) == 0);
2245 
2246 	return (vdev_child_string_match(nvroot, tgt));
2247 }
2248 
2249 static boolean_t
2250 pool_match(nvlist_t *config, char *tgt)
2251 {
2252 	uint64_t guid = strtoull(tgt, NULL, 0);
2253 
2254 	if (guid != 0) {
2255 		return (
2256 		    nvlist_uint64_match(config, ZPOOL_CONFIG_POOL_GUID, guid) ||
2257 		    vdev_guid_match(config, guid));
2258 	} else {
2259 		return (
2260 		    nvlist_string_match(config, ZPOOL_CONFIG_POOL_NAME, tgt) ||
2261 		    vdev_string_match(config, tgt));
2262 	}
2263 }
2264 
2265 static int
2266 find_exported_zpool(char *pool_id, nvlist_t **configp, char *vdev_dir)
2267 {
2268 	nvlist_t *pools;
2269 	int error = ENOENT;
2270 	nvlist_t *match = NULL;
2271 
2272 	if (vdev_dir != NULL)
2273 		pools = zpool_find_import_activeok(g_zfs, 1, &vdev_dir);
2274 	else
2275 		pools = zpool_find_import_activeok(g_zfs, 0, NULL);
2276 
2277 	if (pools != NULL) {
2278 		nvpair_t *elem = NULL;
2279 
2280 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2281 			verify(nvpair_value_nvlist(elem, configp) == 0);
2282 			if (pool_match(*configp, pool_id)) {
2283 				if (match != NULL) {
2284 					(void) fatal(
2285 					    "More than one matching pool - "
2286 					    "specify guid/devid/device path.");
2287 				} else {
2288 					match = *configp;
2289 					error = 0;
2290 				}
2291 			}
2292 		}
2293 	}
2294 
2295 	*configp = error ? NULL : match;
2296 
2297 	return (error);
2298 }
2299 
2300 int
2301 main(int argc, char **argv)
2302 {
2303 	int i, c;
2304 	struct rlimit rl = { 1024, 1024 };
2305 	spa_t *spa;
2306 	objset_t *os = NULL;
2307 	char *endstr;
2308 	int dump_all = 1;
2309 	int verbose = 0;
2310 	int error;
2311 	int exported = 0;
2312 	char *vdev_dir = NULL;
2313 
2314 	(void) setrlimit(RLIMIT_NOFILE, &rl);
2315 	(void) enable_extended_FILE_stdio(-1, -1);
2316 
2317 	dprintf_setup(&argc, argv);
2318 
2319 	while ((c = getopt(argc, argv, "udibcmsvCLS:U:lRep:t:")) != -1) {
2320 		switch (c) {
2321 		case 'u':
2322 		case 'd':
2323 		case 'i':
2324 		case 'b':
2325 		case 'c':
2326 		case 'm':
2327 		case 's':
2328 		case 'C':
2329 		case 'l':
2330 		case 'R':
2331 			dump_opt[c]++;
2332 			dump_all = 0;
2333 			break;
2334 		case 'L':
2335 			dump_opt[c]++;
2336 			break;
2337 		case 'v':
2338 			verbose++;
2339 			break;
2340 		case 'U':
2341 			spa_config_path = optarg;
2342 			break;
2343 		case 'e':
2344 			exported = 1;
2345 			break;
2346 		case 'p':
2347 			vdev_dir = optarg;
2348 			break;
2349 		case 'S':
2350 			dump_opt[c]++;
2351 			dump_all = 0;
2352 			zdb_sig_user_data = (strncmp(optarg, "user:", 5) == 0);
2353 			if (!zdb_sig_user_data && strncmp(optarg, "all:", 4))
2354 				usage();
2355 			endstr = strchr(optarg, ':') + 1;
2356 			if (strcmp(endstr, "fletcher2") == 0)
2357 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_2;
2358 			else if (strcmp(endstr, "fletcher4") == 0)
2359 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_4;
2360 			else if (strcmp(endstr, "sha256") == 0)
2361 				zdb_sig_cksumalg = ZIO_CHECKSUM_SHA256;
2362 			else if (strcmp(endstr, "all") == 0)
2363 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_2;
2364 			else
2365 				usage();
2366 			break;
2367 		case 't':
2368 			ub_max_txg = strtoull(optarg, NULL, 0);
2369 			if (ub_max_txg < TXG_INITIAL) {
2370 				(void) fprintf(stderr, "incorrect txg "
2371 				    "specified: %s\n", optarg);
2372 				usage();
2373 			}
2374 			break;
2375 		default:
2376 			usage();
2377 			break;
2378 		}
2379 	}
2380 
2381 	if (vdev_dir != NULL && exported == 0) {
2382 		(void) fprintf(stderr, "-p option requires use of -e\n");
2383 		usage();
2384 	}
2385 
2386 	kernel_init(FREAD);
2387 	g_zfs = libzfs_init();
2388 	ASSERT(g_zfs != NULL);
2389 
2390 	for (c = 0; c < 256; c++) {
2391 		if (dump_all && c != 'l' && c != 'R')
2392 			dump_opt[c] = 1;
2393 		if (dump_opt[c])
2394 			dump_opt[c] += verbose;
2395 	}
2396 
2397 	argc -= optind;
2398 	argv += optind;
2399 
2400 	if (argc < 1) {
2401 		if (dump_opt['C']) {
2402 			dump_cachefile(spa_config_path);
2403 			return (0);
2404 		}
2405 		usage();
2406 	}
2407 
2408 	if (dump_opt['l']) {
2409 		dump_label(argv[0]);
2410 		return (0);
2411 	}
2412 
2413 	if (dump_opt['R']) {
2414 		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
2415 		flagbits['c'] = ZDB_FLAG_CHECKSUM;
2416 		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
2417 		flagbits['e'] = ZDB_FLAG_BSWAP;
2418 		flagbits['g'] = ZDB_FLAG_GBH;
2419 		flagbits['i'] = ZDB_FLAG_INDIRECT;
2420 		flagbits['p'] = ZDB_FLAG_PHYS;
2421 		flagbits['r'] = ZDB_FLAG_RAW;
2422 
2423 		spa = NULL;
2424 		while (argv[0]) {
2425 			zdb_read_block(argv[0], &spa);
2426 			argv++;
2427 			argc--;
2428 		}
2429 		if (spa)
2430 			spa_close(spa, (void *)zdb_read_block);
2431 		return (0);
2432 	}
2433 
2434 	if (dump_opt['C'])
2435 		dump_config(argv[0]);
2436 
2437 	error = 0;
2438 	if (exported) {
2439 		/*
2440 		 * Check to see if the name refers to an exported zpool
2441 		 */
2442 		char *slash;
2443 		nvlist_t *exported_conf = NULL;
2444 
2445 		if ((slash = strchr(argv[0], '/')) != NULL)
2446 			*slash = '\0';
2447 
2448 		error = find_exported_zpool(argv[0], &exported_conf, vdev_dir);
2449 		if (error == 0) {
2450 			nvlist_t *nvl = NULL;
2451 
2452 			if (vdev_dir != NULL) {
2453 				if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
2454 					error = ENOMEM;
2455 				else if (nvlist_add_string(nvl,
2456 				    zpool_prop_to_name(ZPOOL_PROP_ALTROOT),
2457 				    vdev_dir) != 0)
2458 					error = ENOMEM;
2459 			}
2460 
2461 			if (error == 0)
2462 				error = spa_import_verbatim(argv[0],
2463 				    exported_conf, nvl);
2464 
2465 			nvlist_free(nvl);
2466 		}
2467 
2468 		if (slash != NULL)
2469 			*slash = '/';
2470 	}
2471 
2472 	if (error == 0) {
2473 		if (strchr(argv[0], '/') != NULL) {
2474 			error = dmu_objset_open(argv[0], DMU_OST_ANY,
2475 			    DS_MODE_USER | DS_MODE_READONLY, &os);
2476 		} else {
2477 			error = spa_open(argv[0], &spa, FTAG);
2478 		}
2479 	}
2480 
2481 	if (error)
2482 		fatal("can't open %s: %s", argv[0], strerror(error));
2483 
2484 	argv++;
2485 	if (--argc > 0) {
2486 		zopt_objects = argc;
2487 		zopt_object = calloc(zopt_objects, sizeof (uint64_t));
2488 		for (i = 0; i < zopt_objects; i++) {
2489 			errno = 0;
2490 			zopt_object[i] = strtoull(argv[i], NULL, 0);
2491 			if (zopt_object[i] == 0 && errno != 0)
2492 				fatal("bad object number %s: %s",
2493 				    argv[i], strerror(errno));
2494 		}
2495 	}
2496 
2497 	if (os != NULL) {
2498 		dump_dir(os);
2499 		dmu_objset_close(os);
2500 	} else {
2501 		dump_zpool(spa);
2502 		spa_close(spa, FTAG);
2503 	}
2504 
2505 	fuid_table_destroy();
2506 
2507 	libzfs_fini(g_zfs);
2508 	kernel_fini();
2509 
2510 	return (0);
2511 }
2512