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