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