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