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