xref: /titanic_51/usr/src/cmd/zdb/zdb.c (revision 1cc553493b17fa6a6770261bbfeb258f354ebf48)
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 void
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;
1221 	}
1222 	dump_dir(os);
1223 	dmu_objset_close(os);
1224 }
1225 
1226 static void
1227 zdb_space_map_load(spa_t *spa)
1228 {
1229 	vdev_t *rvd = spa->spa_root_vdev;
1230 	vdev_t *vd;
1231 	int c, m, error;
1232 
1233 	for (c = 0; c < rvd->vdev_children; c++) {
1234 		vd = rvd->vdev_child[c];
1235 		for (m = 0; m < vd->vdev_ms_count; m++) {
1236 			metaslab_t *msp = vd->vdev_ms[m];
1237 			mutex_enter(&msp->ms_lock);
1238 			error = space_map_load(&msp->ms_allocmap[0], NULL,
1239 			    SM_ALLOC, &msp->ms_smo, spa->spa_meta_objset);
1240 			mutex_exit(&msp->ms_lock);
1241 			if (error)
1242 				fatal("%s bad space map #%d, error %d",
1243 				    spa->spa_name, c, error);
1244 		}
1245 	}
1246 }
1247 
1248 static int
1249 zdb_space_map_claim(spa_t *spa, blkptr_t *bp, zbookmark_t *zb)
1250 {
1251 	dva_t *dva = bp->blk_dva;
1252 	vdev_t *vd;
1253 	metaslab_t *msp;
1254 	space_map_t *allocmap, *freemap;
1255 	int error;
1256 	int d;
1257 	blkptr_t blk = *bp;
1258 
1259 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1260 		uint64_t vdev = DVA_GET_VDEV(&dva[d]);
1261 		uint64_t offset = DVA_GET_OFFSET(&dva[d]);
1262 		uint64_t size = DVA_GET_ASIZE(&dva[d]);
1263 
1264 		if ((vd = vdev_lookup_top(spa, vdev)) == NULL)
1265 			return (ENXIO);
1266 
1267 		if ((offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
1268 			return (ENXIO);
1269 
1270 		msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
1271 		allocmap = &msp->ms_allocmap[0];
1272 		freemap = &msp->ms_freemap[0];
1273 
1274 		/* Prepare our copy of the bp in case we need to read GBHs */
1275 		if (DVA_GET_GANG(&dva[d])) {
1276 			size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
1277 			DVA_SET_ASIZE(&blk.blk_dva[d], size);
1278 			DVA_SET_GANG(&blk.blk_dva[d], 0);
1279 		}
1280 
1281 		mutex_enter(&msp->ms_lock);
1282 		if (space_map_contains(freemap, offset, size)) {
1283 			mutex_exit(&msp->ms_lock);
1284 			return (EAGAIN);	/* allocated more than once */
1285 		}
1286 
1287 		if (!space_map_contains(allocmap, offset, size)) {
1288 			mutex_exit(&msp->ms_lock);
1289 			return (ESTALE);	/* not allocated at all */
1290 		}
1291 
1292 		space_map_remove(allocmap, offset, size);
1293 		space_map_add(freemap, offset, size);
1294 
1295 		mutex_exit(&msp->ms_lock);
1296 	}
1297 
1298 	if (BP_IS_GANG(bp)) {
1299 		zio_gbh_phys_t gbh;
1300 		int g;
1301 
1302 		/* LINTED - compile time assert */
1303 		ASSERT(sizeof (zio_gbh_phys_t) == SPA_GANGBLOCKSIZE);
1304 
1305 		BP_SET_CHECKSUM(&blk, ZIO_CHECKSUM_GANG_HEADER);
1306 		BP_SET_PSIZE(&blk, SPA_GANGBLOCKSIZE);
1307 		BP_SET_LSIZE(&blk, SPA_GANGBLOCKSIZE);
1308 		BP_SET_COMPRESS(&blk, ZIO_COMPRESS_OFF);
1309 		error = zio_wait(zio_read(NULL, spa, &blk, &gbh,
1310 		    SPA_GANGBLOCKSIZE, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
1311 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_CONFIG_HELD, zb));
1312 		if (error)
1313 			return (error);
1314 		if (BP_SHOULD_BYTESWAP(&blk))
1315 			byteswap_uint64_array(&gbh, SPA_GANGBLOCKSIZE);
1316 		for (g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1317 			if (BP_IS_HOLE(&gbh.zg_blkptr[g]))
1318 				break;
1319 			error = zdb_space_map_claim(spa, &gbh.zg_blkptr[g], zb);
1320 			if (error)
1321 				return (error);
1322 		}
1323 	}
1324 
1325 	return (0);
1326 }
1327 
1328 static void
1329 zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
1330 {
1331 	metaslab_t *msp;
1332 
1333 	/* LINTED */
1334 	msp = (metaslab_t *)((char *)sm - offsetof(metaslab_t, ms_allocmap[0]));
1335 
1336 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
1337 	    (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
1338 	    (u_longlong_t)start,
1339 	    (u_longlong_t)size);
1340 }
1341 
1342 static void
1343 zdb_space_map_unload(spa_t *spa)
1344 {
1345 	vdev_t *rvd = spa->spa_root_vdev;
1346 	vdev_t *vd;
1347 	int c, m;
1348 
1349 	for (c = 0; c < rvd->vdev_children; c++) {
1350 		vd = rvd->vdev_child[c];
1351 		for (m = 0; m < vd->vdev_ms_count; m++) {
1352 			metaslab_t *msp = vd->vdev_ms[m];
1353 			mutex_enter(&msp->ms_lock);
1354 			space_map_vacate(&msp->ms_allocmap[0], zdb_leak,
1355 			    &msp->ms_allocmap[0]);
1356 			space_map_unload(&msp->ms_allocmap[0]);
1357 			space_map_vacate(&msp->ms_freemap[0], NULL, NULL);
1358 			mutex_exit(&msp->ms_lock);
1359 		}
1360 	}
1361 }
1362 
1363 static void
1364 zdb_refresh_ubsync(spa_t *spa)
1365 {
1366 	uberblock_t ub = { 0 };
1367 	vdev_t *rvd = spa->spa_root_vdev;
1368 	zio_t *zio;
1369 
1370 	/*
1371 	 * Reload the uberblock.
1372 	 */
1373 	zio = zio_root(spa, NULL, NULL,
1374 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
1375 	vdev_uberblock_load(zio, rvd, &ub);
1376 	(void) zio_wait(zio);
1377 
1378 	if (ub.ub_txg != 0)
1379 		spa->spa_ubsync = ub;
1380 }
1381 
1382 /*
1383  * Verify that the sum of the sizes of all blocks in the pool adds up
1384  * to the SPA's sa_alloc total.
1385  */
1386 typedef struct zdb_blkstats {
1387 	uint64_t	zb_asize;
1388 	uint64_t	zb_lsize;
1389 	uint64_t	zb_psize;
1390 	uint64_t	zb_count;
1391 } zdb_blkstats_t;
1392 
1393 #define	DMU_OT_DEFERRED	DMU_OT_NONE
1394 #define	DMU_OT_TOTAL	DMU_OT_NUMTYPES
1395 
1396 #define	ZB_TOTAL	ZB_MAXLEVEL
1397 
1398 typedef struct zdb_cb {
1399 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][DMU_OT_TOTAL + 1];
1400 	uint64_t	zcb_errors[256];
1401 	traverse_blk_cache_t *zcb_cache;
1402 	int		zcb_readfails;
1403 	int		zcb_haderrors;
1404 } zdb_cb_t;
1405 
1406 static void
1407 zdb_count_block(spa_t *spa, zdb_cb_t *zcb, blkptr_t *bp, int type)
1408 {
1409 	int i, error;
1410 
1411 	for (i = 0; i < 4; i++) {
1412 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
1413 		int t = (i & 1) ? type : DMU_OT_TOTAL;
1414 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
1415 
1416 		zb->zb_asize += BP_GET_ASIZE(bp);
1417 		zb->zb_lsize += BP_GET_LSIZE(bp);
1418 		zb->zb_psize += BP_GET_PSIZE(bp);
1419 		zb->zb_count++;
1420 	}
1421 
1422 	if (dump_opt['L'])
1423 		return;
1424 
1425 	error = zdb_space_map_claim(spa, bp, &zcb->zcb_cache->bc_bookmark);
1426 
1427 	if (error == 0)
1428 		return;
1429 
1430 	if (error == EAGAIN)
1431 		(void) fatal("double-allocation, bp=%p", bp);
1432 
1433 	if (error == ESTALE)
1434 		(void) fatal("reference to freed block, bp=%p", bp);
1435 
1436 	(void) fatal("fatal error %d in bp %p", error, bp);
1437 }
1438 
1439 static int
1440 zdb_blkptr_cb(traverse_blk_cache_t *bc, spa_t *spa, void *arg)
1441 {
1442 	zbookmark_t *zb = &bc->bc_bookmark;
1443 	zdb_cb_t *zcb = arg;
1444 	blkptr_t *bp = &bc->bc_blkptr;
1445 	dmu_object_type_t type = BP_GET_TYPE(bp);
1446 	char blkbuf[BP_SPRINTF_LEN];
1447 	int error = 0;
1448 
1449 	if (bc->bc_errno) {
1450 		if (zcb->zcb_readfails++ < 10 && dump_opt['L']) {
1451 			zdb_refresh_ubsync(spa);
1452 			error = EAGAIN;
1453 		} else {
1454 			zcb->zcb_haderrors = 1;
1455 			zcb->zcb_errors[bc->bc_errno]++;
1456 			error = ERESTART;
1457 		}
1458 
1459 		if (dump_opt['b'] >= 3 || (dump_opt['b'] >= 2 && bc->bc_errno))
1460 			sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1461 		else
1462 			blkbuf[0] = '\0';
1463 
1464 		(void) printf("zdb_blkptr_cb: Got error %d reading "
1465 		    "<%llu, %llu, %lld, %llx> %s -- %s\n",
1466 		    bc->bc_errno,
1467 		    (u_longlong_t)zb->zb_objset,
1468 		    (u_longlong_t)zb->zb_object,
1469 		    (u_longlong_t)zb->zb_level,
1470 		    (u_longlong_t)zb->zb_blkid,
1471 		    blkbuf,
1472 		    error == EAGAIN ? "retrying" : "skipping");
1473 
1474 		return (error);
1475 	}
1476 
1477 	zcb->zcb_readfails = 0;
1478 
1479 	ASSERT(!BP_IS_HOLE(bp));
1480 
1481 	if (dump_opt['b'] >= 4) {
1482 		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1483 		(void) printf("objset %llu object %llu offset 0x%llx %s\n",
1484 		    (u_longlong_t)zb->zb_objset,
1485 		    (u_longlong_t)zb->zb_object,
1486 		    (u_longlong_t)blkid2offset(bc->bc_dnode,
1487 			zb->zb_level, zb->zb_blkid),
1488 		    blkbuf);
1489 	}
1490 
1491 	zdb_count_block(spa, zcb, bp, type);
1492 
1493 	return (0);
1494 }
1495 
1496 static int
1497 dump_block_stats(spa_t *spa)
1498 {
1499 	traverse_handle_t *th;
1500 	zdb_cb_t zcb = { 0 };
1501 	traverse_blk_cache_t dummy_cache = { 0 };
1502 	zdb_blkstats_t *zb, *tzb;
1503 	uint64_t alloc, space;
1504 	int leaks = 0;
1505 	int advance = zdb_advance;
1506 	int flags;
1507 	int e;
1508 
1509 	zcb.zcb_cache = &dummy_cache;
1510 
1511 	if (dump_opt['c'])
1512 		advance |= ADVANCE_DATA;
1513 
1514 	advance |= ADVANCE_PRUNE | ADVANCE_ZIL;
1515 
1516 	(void) printf("\nTraversing all blocks to %sverify"
1517 	    " nothing leaked ...\n",
1518 	    dump_opt['c'] ? "verify checksums and " : "");
1519 
1520 	/*
1521 	 * Load all space maps.  As we traverse the pool, if we find a block
1522 	 * that's not in its space map, that indicates a double-allocation,
1523 	 * reference to a freed block, or an unclaimed block.  Otherwise we
1524 	 * remove the block from the space map.  If the space maps are not
1525 	 * empty when we're done, that indicates leaked blocks.
1526 	 */
1527 	if (!dump_opt['L'])
1528 		zdb_space_map_load(spa);
1529 
1530 	/*
1531 	 * If there's a deferred-free bplist, process that first.
1532 	 */
1533 	if (spa->spa_sync_bplist_obj != 0) {
1534 		bplist_t *bpl = &spa->spa_sync_bplist;
1535 		blkptr_t blk;
1536 		uint64_t itor = 0;
1537 
1538 		VERIFY(0 == bplist_open(bpl, spa->spa_meta_objset,
1539 		    spa->spa_sync_bplist_obj));
1540 
1541 		while (bplist_iterate(bpl, &itor, &blk) == 0) {
1542 			if (dump_opt['b'] >= 4) {
1543 				char blkbuf[BP_SPRINTF_LEN];
1544 				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &blk);
1545 				(void) printf("[%s] %s\n",
1546 				    "deferred free", blkbuf);
1547 			}
1548 			zdb_count_block(spa, &zcb, &blk, DMU_OT_DEFERRED);
1549 		}
1550 
1551 		bplist_close(bpl);
1552 	}
1553 
1554 	/*
1555 	 * Now traverse the pool.  If we're reading all data to verify
1556 	 * checksums, do a scrubbing read so that we validate all copies.
1557 	 */
1558 	flags = ZIO_FLAG_CANFAIL;
1559 	if (advance & ADVANCE_DATA)
1560 		flags |= ZIO_FLAG_SCRUB;
1561 	th = traverse_init(spa, zdb_blkptr_cb, &zcb, advance, flags);
1562 	th->th_noread = zdb_noread;
1563 
1564 	traverse_add_pool(th, 0, spa_first_txg(spa) + TXG_CONCURRENT_STATES);
1565 
1566 	while (traverse_more(th) == EAGAIN)
1567 		continue;
1568 
1569 	traverse_fini(th);
1570 
1571 	if (zcb.zcb_haderrors) {
1572 		(void) printf("\nError counts:\n\n");
1573 		(void) printf("\t%5s  %s\n", "errno", "count");
1574 		for (e = 0; e < 256; e++) {
1575 			if (zcb.zcb_errors[e] != 0) {
1576 				(void) printf("\t%5d  %llu\n",
1577 				    e, (u_longlong_t)zcb.zcb_errors[e]);
1578 			}
1579 		}
1580 	}
1581 
1582 	/*
1583 	 * Report any leaked segments.
1584 	 */
1585 	if (!dump_opt['L'])
1586 		zdb_space_map_unload(spa);
1587 
1588 	if (dump_opt['L'])
1589 		(void) printf("\n\n *** Live pool traversal; "
1590 		    "block counts are only approximate ***\n\n");
1591 
1592 	alloc = spa_get_alloc(spa);
1593 	space = spa_get_space(spa);
1594 
1595 	tzb = &zcb.zcb_type[ZB_TOTAL][DMU_OT_TOTAL];
1596 
1597 	if (tzb->zb_asize == alloc) {
1598 		(void) printf("\n\tNo leaks (block sum matches space"
1599 		    " maps exactly)\n");
1600 	} else {
1601 		(void) printf("block traversal size %llu != alloc %llu "
1602 		    "(leaked %lld)\n",
1603 		    (u_longlong_t)tzb->zb_asize,
1604 		    (u_longlong_t)alloc,
1605 		    (u_longlong_t)(alloc - tzb->zb_asize));
1606 		leaks = 1;
1607 	}
1608 
1609 	if (tzb->zb_count == 0)
1610 		return (2);
1611 
1612 	(void) printf("\n");
1613 	(void) printf("\tbp count:      %10llu\n",
1614 	    (u_longlong_t)tzb->zb_count);
1615 	(void) printf("\tbp logical:    %10llu\t avg: %6llu\n",
1616 	    (u_longlong_t)tzb->zb_lsize,
1617 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
1618 	(void) printf("\tbp physical:   %10llu\t avg:"
1619 	    " %6llu\tcompression: %6.2f\n",
1620 	    (u_longlong_t)tzb->zb_psize,
1621 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
1622 	    (double)tzb->zb_lsize / tzb->zb_psize);
1623 	(void) printf("\tbp allocated:  %10llu\t avg:"
1624 	    " %6llu\tcompression: %6.2f\n",
1625 	    (u_longlong_t)tzb->zb_asize,
1626 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
1627 	    (double)tzb->zb_lsize / tzb->zb_asize);
1628 	(void) printf("\tSPA allocated: %10llu\tused: %5.2f%%\n",
1629 	    (u_longlong_t)alloc, 100.0 * alloc / space);
1630 
1631 	if (dump_opt['b'] >= 2) {
1632 		int l, t, level;
1633 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
1634 		    "\t  avg\t comp\t%%Total\tType\n");
1635 
1636 		for (t = 0; t <= DMU_OT_NUMTYPES; t++) {
1637 			char csize[6], lsize[6], psize[6], asize[6], avg[6];
1638 			char *typename;
1639 
1640 			typename = t == DMU_OT_DEFERRED ? "deferred free" :
1641 			    t == DMU_OT_TOTAL ? "Total" : dmu_ot[t].ot_name;
1642 
1643 			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
1644 				(void) printf("%6s\t%5s\t%5s\t%5s"
1645 				    "\t%5s\t%5s\t%6s\t%s\n",
1646 				    "-",
1647 				    "-",
1648 				    "-",
1649 				    "-",
1650 				    "-",
1651 				    "-",
1652 				    "-",
1653 				    typename);
1654 				continue;
1655 			}
1656 
1657 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
1658 				level = (l == -1 ? ZB_TOTAL : l);
1659 				zb = &zcb.zcb_type[level][t];
1660 
1661 				if (zb->zb_asize == 0)
1662 					continue;
1663 
1664 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
1665 					continue;
1666 
1667 				if (level == 0 && zb->zb_asize ==
1668 				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
1669 					continue;
1670 
1671 				nicenum(zb->zb_count, csize);
1672 				nicenum(zb->zb_lsize, lsize);
1673 				nicenum(zb->zb_psize, psize);
1674 				nicenum(zb->zb_asize, asize);
1675 				nicenum(zb->zb_asize / zb->zb_count, avg);
1676 
1677 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
1678 				    "\t%5.2f\t%6.2f\t",
1679 				    csize, lsize, psize, asize, avg,
1680 				    (double)zb->zb_lsize / zb->zb_psize,
1681 				    100.0 * zb->zb_asize / tzb->zb_asize);
1682 
1683 				if (level == ZB_TOTAL)
1684 					(void) printf("%s\n", typename);
1685 				else
1686 					(void) printf("    L%d %s\n",
1687 					    level, typename);
1688 			}
1689 		}
1690 	}
1691 
1692 	(void) printf("\n");
1693 
1694 	if (leaks)
1695 		return (2);
1696 
1697 	if (zcb.zcb_haderrors)
1698 		return (3);
1699 
1700 	return (0);
1701 }
1702 
1703 static void
1704 dump_zpool(spa_t *spa)
1705 {
1706 	dsl_pool_t *dp = spa_get_dsl(spa);
1707 	int rc = 0;
1708 
1709 	if (dump_opt['u'])
1710 		dump_uberblock(&spa->spa_uberblock);
1711 
1712 	if (dump_opt['d'] || dump_opt['i']) {
1713 		dump_dir(dp->dp_meta_objset);
1714 		if (dump_opt['d'] >= 3) {
1715 			dump_bplist(dp->dp_meta_objset,
1716 			    spa->spa_sync_bplist_obj, "Deferred frees");
1717 			dump_dtl(spa->spa_root_vdev, 0);
1718 			dump_metaslabs(spa);
1719 		}
1720 		dmu_objset_find(spa->spa_name, dump_one_dir, NULL,
1721 		    DS_FIND_SNAPSHOTS);
1722 	}
1723 
1724 	if (dump_opt['b'] || dump_opt['c'])
1725 		rc = dump_block_stats(spa);
1726 
1727 	if (dump_opt['s'])
1728 		show_pool_stats(spa);
1729 
1730 	if (rc != 0)
1731 		exit(rc);
1732 }
1733 
1734 #define	ZDB_FLAG_CHECKSUM	0x0001
1735 #define	ZDB_FLAG_DECOMPRESS	0x0002
1736 #define	ZDB_FLAG_BSWAP		0x0004
1737 #define	ZDB_FLAG_GBH		0x0008
1738 #define	ZDB_FLAG_INDIRECT	0x0010
1739 #define	ZDB_FLAG_PHYS		0x0020
1740 #define	ZDB_FLAG_RAW		0x0040
1741 #define	ZDB_FLAG_PRINT_BLKPTR	0x0080
1742 
1743 int flagbits[256];
1744 
1745 static void
1746 zdb_print_blkptr(blkptr_t *bp, int flags)
1747 {
1748 	dva_t *dva = bp->blk_dva;
1749 	int d;
1750 
1751 	if (flags & ZDB_FLAG_BSWAP)
1752 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
1753 	/*
1754 	 * Super-ick warning:  This code is also duplicated in
1755 	 * cmd/mdb/common/modules/zfs/zfs.c .  Yeah, I hate code
1756 	 * replication, too.
1757 	 */
1758 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1759 		(void) printf("\tDVA[%d]: vdev_id %lld / %llx\n", d,
1760 		    DVA_GET_VDEV(&dva[d]), DVA_GET_OFFSET(&dva[d]));
1761 		(void) printf("\tDVA[%d]:       GANG: %-5s  GRID:  %04llx\t"
1762 		    "ASIZE: %llx\n", d,
1763 		    DVA_GET_GANG(&dva[d]) ? "TRUE" : "FALSE",
1764 		    DVA_GET_GRID(&dva[d]), DVA_GET_ASIZE(&dva[d]));
1765 		(void) printf("\tDVA[%d]: :%llu:%llx:%llx:%s%s%s%s\n", d,
1766 		    DVA_GET_VDEV(&dva[d]), DVA_GET_OFFSET(&dva[d]),
1767 		    BP_GET_PSIZE(bp),
1768 		    BP_SHOULD_BYTESWAP(bp) ? "e" : "",
1769 		    !DVA_GET_GANG(&dva[d]) && BP_GET_LEVEL(bp) != 0 ?
1770 		    "d" : "",
1771 		    DVA_GET_GANG(&dva[d]) ? "g" : "",
1772 		    BP_GET_COMPRESS(bp) != 0 ? "d" : "");
1773 	}
1774 	(void) printf("\tLSIZE:  %-16llx\t\tPSIZE: %llx\n",
1775 	    BP_GET_LSIZE(bp), BP_GET_PSIZE(bp));
1776 	(void) printf("\tENDIAN: %6s\t\t\t\t\tTYPE:  %s\n",
1777 	    BP_GET_BYTEORDER(bp) ? "LITTLE" : "BIG",
1778 	    dmu_ot[BP_GET_TYPE(bp)].ot_name);
1779 	(void) printf("\tBIRTH:  %-16llx   LEVEL: %-2llu\tFILL:  %llx\n",
1780 	    (u_longlong_t)bp->blk_birth, BP_GET_LEVEL(bp),
1781 	    (u_longlong_t)bp->blk_fill);
1782 	(void) printf("\tCKFUNC: %-16s\t\tCOMP:  %s\n",
1783 	    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
1784 	    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name);
1785 	(void) printf("\tCKSUM:  %llx:%llx:%llx:%llx\n",
1786 	    (u_longlong_t)bp->blk_cksum.zc_word[0],
1787 	    (u_longlong_t)bp->blk_cksum.zc_word[1],
1788 	    (u_longlong_t)bp->blk_cksum.zc_word[2],
1789 	    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1790 }
1791 
1792 static void
1793 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
1794 {
1795 	int i;
1796 
1797 	for (i = 0; i < nbps; i++)
1798 		zdb_print_blkptr(&bp[i], flags);
1799 }
1800 
1801 static void
1802 zdb_dump_gbh(void *buf, int flags)
1803 {
1804 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
1805 }
1806 
1807 static void
1808 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
1809 {
1810 	if (flags & ZDB_FLAG_BSWAP)
1811 		byteswap_uint64_array(buf, size);
1812 	(void) write(2, buf, size);
1813 }
1814 
1815 static void
1816 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
1817 {
1818 	uint64_t *d = (uint64_t *)buf;
1819 	int nwords = size / sizeof (uint64_t);
1820 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
1821 	int i, j;
1822 	char *hdr, *c;
1823 
1824 
1825 	if (do_bswap)
1826 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
1827 	else
1828 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
1829 
1830 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
1831 
1832 	for (i = 0; i < nwords; i += 2) {
1833 		(void) printf("%06llx:  %016llx  %016llx  ",
1834 		    (u_longlong_t)(i * sizeof (uint64_t)),
1835 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
1836 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
1837 
1838 		c = (char *)&d[i];
1839 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
1840 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
1841 		(void) printf("\n");
1842 	}
1843 }
1844 
1845 /*
1846  * There are two acceptable formats:
1847  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
1848  *	child[.child]*    - For example: 0.1.1
1849  *
1850  * The second form can be used to specify arbitrary vdevs anywhere
1851  * in the heirarchy.  For example, in a pool with a mirror of
1852  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
1853  */
1854 static vdev_t *
1855 zdb_vdev_lookup(vdev_t *vdev, char *path)
1856 {
1857 	char *s, *p, *q;
1858 	int i;
1859 
1860 	if (vdev == NULL)
1861 		return (NULL);
1862 
1863 	/* First, assume the x.x.x.x format */
1864 	i = (int)strtoul(path, &s, 10);
1865 	if (s == path || (s && *s != '.' && *s != '\0'))
1866 		goto name;
1867 	if (i < 0 || i >= vdev->vdev_children)
1868 		return (NULL);
1869 
1870 	vdev = vdev->vdev_child[i];
1871 	if (*s == '\0')
1872 		return (vdev);
1873 	return (zdb_vdev_lookup(vdev, s+1));
1874 
1875 name:
1876 	for (i = 0; i < vdev->vdev_children; i++) {
1877 		vdev_t *vc = vdev->vdev_child[i];
1878 
1879 		if (vc->vdev_path == NULL) {
1880 			vc = zdb_vdev_lookup(vc, path);
1881 			if (vc == NULL)
1882 				continue;
1883 			else
1884 				return (vc);
1885 		}
1886 
1887 		p = strrchr(vc->vdev_path, '/');
1888 		p = p ? p + 1 : vc->vdev_path;
1889 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
1890 
1891 		if (strcmp(vc->vdev_path, path) == 0)
1892 			return (vc);
1893 		if (strcmp(p, path) == 0)
1894 			return (vc);
1895 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
1896 			return (vc);
1897 	}
1898 
1899 	return (NULL);
1900 }
1901 
1902 /*
1903  * Read a block from a pool and print it out.  The syntax of the
1904  * block descriptor is:
1905  *
1906  *	pool:vdev_specifier:offset:size[:flags]
1907  *
1908  *	pool           - The name of the pool you wish to read from
1909  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
1910  *	offset         - offset, in hex, in bytes
1911  *	size           - Amount of data to read, in hex, in bytes
1912  *	flags          - A string of characters specifying options
1913  *		 b: Decode a blkptr at given offset within block
1914  *		*c: Calculate and display checksums
1915  *		*d: Decompress data before dumping
1916  *		 e: Byteswap data before dumping
1917  *		*g: Display data as a gang block header
1918  *		*i: Display as an indirect block
1919  *		 p: Do I/O to physical offset
1920  *		 r: Dump raw data to stdout
1921  *
1922  *              * = not yet implemented
1923  */
1924 static void
1925 zdb_read_block(char *thing, spa_t **spap)
1926 {
1927 	spa_t *spa = *spap;
1928 	int flags = 0;
1929 	uint64_t offset = 0, size = 0, blkptr_offset = 0;
1930 	zio_t *zio;
1931 	vdev_t *vd;
1932 	void *buf;
1933 	char *s, *p, *dup, *spa_name, *vdev, *flagstr;
1934 	int i, error, zio_flags;
1935 
1936 	dup = strdup(thing);
1937 	s = strtok(dup, ":");
1938 	spa_name = s ? s : "";
1939 	s = strtok(NULL, ":");
1940 	vdev = s ? s : "";
1941 	s = strtok(NULL, ":");
1942 	offset = strtoull(s ? s : "", NULL, 16);
1943 	s = strtok(NULL, ":");
1944 	size = strtoull(s ? s : "", NULL, 16);
1945 	s = strtok(NULL, ":");
1946 	flagstr = s ? s : "";
1947 
1948 	s = NULL;
1949 	if (size == 0)
1950 		s = "size must not be zero";
1951 	if (!IS_P2ALIGNED(size, DEV_BSIZE))
1952 		s = "size must be a multiple of sector size";
1953 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
1954 		s = "offset must be a multiple of sector size";
1955 	if (s) {
1956 		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
1957 		free(dup);
1958 		return;
1959 	}
1960 
1961 	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
1962 		for (i = 0; flagstr[i]; i++) {
1963 			int bit = flagbits[flagstr[i]];
1964 
1965 			if (bit == 0) {
1966 				(void) printf("***Invalid flag: %c\n",
1967 				    flagstr[i]);
1968 				continue;
1969 			}
1970 			flags |= bit;
1971 
1972 			/* If it's not something with an argument, keep going */
1973 			if ((bit & (ZDB_FLAG_CHECKSUM | ZDB_FLAG_DECOMPRESS |
1974 			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
1975 				continue;
1976 
1977 			p = &flagstr[i + 1];
1978 			if (bit == ZDB_FLAG_PRINT_BLKPTR)
1979 				blkptr_offset = strtoull(p, &p, 16);
1980 			if (*p != ':' && *p != '\0') {
1981 				(void) printf("***Invalid flag arg: '%s'\n", s);
1982 				free(dup);
1983 				return;
1984 			}
1985 		}
1986 	}
1987 
1988 	if (spa == NULL || spa->spa_name == NULL ||
1989 	    strcmp(spa->spa_name, spa_name)) {
1990 		if (spa && spa->spa_name)
1991 			spa_close(spa, (void *)zdb_read_block);
1992 		error = spa_open(spa_name, spap, (void *)zdb_read_block);
1993 		if (error)
1994 			fatal("Failed to open pool '%s': errno = %d\n",
1995 			    spa_name, error);
1996 		spa = *spap;
1997 	}
1998 
1999 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2000 	if (vd == NULL) {
2001 		(void) printf("***Invalid vdev: %s\n", vdev);
2002 		free(dup);
2003 		return;
2004 	} else {
2005 		if (vd->vdev_path)
2006 			(void) printf("Found vdev: %s\n", vd->vdev_path);
2007 		else
2008 			(void) printf("Found vdev type: %s\n",
2009 			    vd->vdev_ops->vdev_op_type);
2010 	}
2011 
2012 	buf = umem_alloc(size, UMEM_NOFAIL);
2013 
2014 	zio_flags = ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2015 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY | ZIO_FLAG_NOBOOKMARK;
2016 
2017 	if (flags & ZDB_FLAG_PHYS)
2018 		zio_flags |= ZIO_FLAG_PHYSICAL;
2019 
2020 	zio = zio_root(spa, NULL, NULL, 0);
2021 	/* XXX todo - cons up a BP so RAID-Z will be happy */
2022 	zio_nowait(zio_vdev_child_io(zio, NULL, vd, offset, buf, size,
2023 	    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ, zio_flags, NULL, NULL));
2024 	error = zio_wait(zio);
2025 
2026 	if (error) {
2027 		(void) printf("Read of %s failed, error: %d\n", thing, error);
2028 		goto out;
2029 	}
2030 
2031 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2032 		zdb_print_blkptr((blkptr_t *)(void *)
2033 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2034 	else if (flags & ZDB_FLAG_RAW)
2035 		zdb_dump_block_raw(buf, size, flags);
2036 	else if (flags & ZDB_FLAG_INDIRECT)
2037 		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2038 		    flags);
2039 	else if (flags & ZDB_FLAG_GBH)
2040 		zdb_dump_gbh(buf, flags);
2041 	else
2042 		zdb_dump_block(thing, buf, size, flags);
2043 
2044 out:
2045 	umem_free(buf, size);
2046 	free(dup);
2047 }
2048 
2049 int
2050 main(int argc, char **argv)
2051 {
2052 	int i, c;
2053 	struct rlimit rl = { 1024, 1024 };
2054 	spa_t *spa;
2055 	objset_t *os = NULL;
2056 	char *endstr;
2057 	int dump_all = 1;
2058 	int verbose = 0;
2059 	int error;
2060 	int flag, set;
2061 	vdev_knob_t *vk;
2062 
2063 	(void) setrlimit(RLIMIT_NOFILE, &rl);
2064 	(void) enable_extended_FILE_stdio(-1, -1);
2065 
2066 	dprintf_setup(&argc, argv);
2067 
2068 	while ((c = getopt(argc, argv, "udibcsvCLO:B:UlR")) != -1) {
2069 		switch (c) {
2070 		case 'u':
2071 		case 'd':
2072 		case 'i':
2073 		case 'b':
2074 		case 'c':
2075 		case 's':
2076 		case 'C':
2077 		case 'l':
2078 		case 'R':
2079 			dump_opt[c]++;
2080 			dump_all = 0;
2081 			break;
2082 		case 'L':
2083 			dump_opt[c]++;
2084 			break;
2085 		case 'O':
2086 			endstr = optarg;
2087 			if (endstr[0] == '!') {
2088 				endstr++;
2089 				set = 0;
2090 			} else {
2091 				set = 1;
2092 			}
2093 			if (strcmp(endstr, "post") == 0) {
2094 				flag = ADVANCE_PRE;
2095 				set = !set;
2096 			} else if (strcmp(endstr, "pre") == 0) {
2097 				flag = ADVANCE_PRE;
2098 			} else if (strcmp(endstr, "prune") == 0) {
2099 				flag = ADVANCE_PRUNE;
2100 			} else if (strcmp(endstr, "data") == 0) {
2101 				flag = ADVANCE_DATA;
2102 			} else if (strcmp(endstr, "holes") == 0) {
2103 				flag = ADVANCE_HOLES;
2104 			} else {
2105 				usage();
2106 			}
2107 			if (set)
2108 				zdb_advance |= flag;
2109 			else
2110 				zdb_advance &= ~flag;
2111 			break;
2112 		case 'B':
2113 			endstr = optarg - 1;
2114 			zdb_noread.zb_objset = strtoull(endstr + 1, &endstr, 0);
2115 			zdb_noread.zb_object = strtoull(endstr + 1, &endstr, 0);
2116 			zdb_noread.zb_level = strtol(endstr + 1, &endstr, 0);
2117 			zdb_noread.zb_blkid = strtoull(endstr + 1, &endstr, 16);
2118 			(void) printf("simulating bad block "
2119 			    "<%llu, %llu, %lld, %llx>\n",
2120 			    (u_longlong_t)zdb_noread.zb_objset,
2121 			    (u_longlong_t)zdb_noread.zb_object,
2122 			    (u_longlong_t)zdb_noread.zb_level,
2123 			    (u_longlong_t)zdb_noread.zb_blkid);
2124 			break;
2125 		case 'v':
2126 			verbose++;
2127 			break;
2128 		case 'U':
2129 			spa_config_dir = "/tmp";
2130 			break;
2131 		default:
2132 			usage();
2133 			break;
2134 		}
2135 	}
2136 
2137 	kernel_init(FREAD);
2138 
2139 	/*
2140 	 * Disable vdev caching.  If we don't do this, live pool traversal
2141 	 * won't make progress because it will never see disk updates.
2142 	 */
2143 	for (vk = vdev_knob_next(NULL); vk != NULL; vk = vdev_knob_next(vk)) {
2144 		if (strcmp(vk->vk_name, "cache_size") == 0)
2145 			vk->vk_default = 0;
2146 	}
2147 
2148 	for (c = 0; c < 256; c++) {
2149 		if (dump_all && c != 'L' && c != 'l' && c != 'R')
2150 			dump_opt[c] = 1;
2151 		if (dump_opt[c])
2152 			dump_opt[c] += verbose;
2153 	}
2154 
2155 	argc -= optind;
2156 	argv += optind;
2157 
2158 	if (argc < 1) {
2159 		if (dump_opt['C']) {
2160 			dump_config(NULL);
2161 			return (0);
2162 		}
2163 		usage();
2164 	}
2165 
2166 	if (dump_opt['l']) {
2167 		dump_label(argv[0]);
2168 		return (0);
2169 	}
2170 
2171 	if (dump_opt['R']) {
2172 		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
2173 		flagbits['c'] = ZDB_FLAG_CHECKSUM;
2174 		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
2175 		flagbits['e'] = ZDB_FLAG_BSWAP;
2176 		flagbits['g'] = ZDB_FLAG_GBH;
2177 		flagbits['i'] = ZDB_FLAG_INDIRECT;
2178 		flagbits['p'] = ZDB_FLAG_PHYS;
2179 		flagbits['r'] = ZDB_FLAG_RAW;
2180 
2181 		spa = NULL;
2182 		while (argv[0]) {
2183 			zdb_read_block(argv[0], &spa);
2184 			argv++;
2185 			argc--;
2186 		}
2187 		if (spa)
2188 			spa_close(spa, (void *)zdb_read_block);
2189 		return (0);
2190 	}
2191 
2192 	if (dump_opt['C'])
2193 		dump_config(argv[0]);
2194 
2195 	if (strchr(argv[0], '/') != NULL) {
2196 		error = dmu_objset_open(argv[0], DMU_OST_ANY,
2197 		    DS_MODE_STANDARD | DS_MODE_READONLY, &os);
2198 	} else {
2199 		error = spa_open(argv[0], &spa, FTAG);
2200 	}
2201 
2202 	if (error)
2203 		fatal("can't open %s: error %d", argv[0], error);
2204 
2205 	argv++;
2206 	if (--argc > 0) {
2207 		zopt_objects = argc;
2208 		zopt_object = calloc(zopt_objects, sizeof (uint64_t));
2209 		for (i = 0; i < zopt_objects; i++) {
2210 			errno = 0;
2211 			zopt_object[i] = strtoull(argv[i], NULL, 0);
2212 			if (zopt_object[i] == 0 && errno != 0)
2213 				fatal("bad object number %s: %s",
2214 				    argv[i], strerror(errno));
2215 		}
2216 	}
2217 
2218 	if (os != NULL) {
2219 		dump_dir(os);
2220 		dmu_objset_close(os);
2221 	} else {
2222 		dump_zpool(spa);
2223 		spa_close(spa, FTAG);
2224 	}
2225 
2226 	kernel_fini();
2227 
2228 	return (0);
2229 }
2230