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