xref: /titanic_50/usr/src/cmd/zdb/zdb.c (revision 1ae0874509b6811fdde1dfd46f0d93fd09867a3f)
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\tinconsistent = %llu\n",
748 	    (u_longlong_t)ds->ds_inconsistent);
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 numbuf[6];
759 
760 	if (dump_opt['d'] < 3)
761 		return;
762 
763 	VERIFY(0 == bplist_open(&bpl, mos, object));
764 	if (bplist_empty(&bpl)) {
765 		bplist_close(&bpl);
766 		return;
767 	}
768 
769 	nicenum(bpl.bpl_phys->bpl_bytes, numbuf);
770 
771 	(void) printf("\n    %s: %llu entries, %s\n",
772 	    name, (u_longlong_t)bpl.bpl_phys->bpl_entries, numbuf);
773 
774 	if (dump_opt['d'] < 5) {
775 		bplist_close(&bpl);
776 		return;
777 	}
778 
779 	(void) printf("\n");
780 
781 	while (bplist_iterate(&bpl, &itor, bp) == 0) {
782 		char blkbuf[BP_SPRINTF_LEN];
783 
784 		ASSERT(bp->blk_birth != 0);
785 		sprintf_blkptr_compact(blkbuf, bp, dump_opt['d'] > 5 ? 1 : 0);
786 		(void) printf("\tItem %3llu: %s\n",
787 		    (u_longlong_t)itor - 1, blkbuf);
788 	}
789 
790 	bplist_close(&bpl);
791 }
792 
793 static char *
794 znode_path(objset_t *os, uint64_t object, char *pathbuf, size_t size)
795 {
796 	dmu_buf_t *db;
797 	dmu_object_info_t doi;
798 	znode_phys_t *zp;
799 	uint64_t parent = 0;
800 	size_t complen;
801 	char component[MAXNAMELEN + 1];
802 	char *path;
803 	int error;
804 
805 	path = pathbuf + size;
806 	*--path = '\0';
807 
808 	for (;;) {
809 		error = dmu_bonus_hold(os, object, FTAG, &db);
810 		if (error)
811 			break;
812 
813 		dmu_object_info_from_db(db, &doi);
814 		zp = db->db_data;
815 		parent = zp->zp_parent;
816 		dmu_buf_rele(db, FTAG);
817 
818 		if (doi.doi_bonus_type != DMU_OT_ZNODE)
819 			break;
820 
821 		if (parent == object) {
822 			if (path[0] != '/')
823 				*--path = '/';
824 			return (path);
825 		}
826 
827 		if (zap_value_search(os, parent, object, component) != 0)
828 			break;
829 
830 		complen = strlen(component);
831 		path -= complen;
832 		bcopy(component, path, complen);
833 		*--path = '/';
834 
835 		object = parent;
836 	}
837 
838 	(void) sprintf(component, "???<object#%llu>", (u_longlong_t)object);
839 
840 	complen = strlen(component);
841 	path -= complen;
842 	bcopy(component, path, complen);
843 
844 	return (path);
845 }
846 
847 /*ARGSUSED*/
848 static void
849 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
850 {
851 	znode_phys_t *zp = data;
852 	time_t z_crtime, z_atime, z_mtime, z_ctime;
853 	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
854 
855 	ASSERT(size >= sizeof (znode_phys_t));
856 
857 	if (dump_opt['d'] < 3) {
858 		(void) printf("\t%s\n",
859 		    znode_path(os, object, path, sizeof (path)));
860 		return;
861 	}
862 
863 	z_crtime = (time_t)zp->zp_crtime[0];
864 	z_atime = (time_t)zp->zp_atime[0];
865 	z_mtime = (time_t)zp->zp_mtime[0];
866 	z_ctime = (time_t)zp->zp_ctime[0];
867 
868 	(void) printf("\tpath	%s\n",
869 	    znode_path(os, object, path, sizeof (path)));
870 	(void) printf("\tatime	%s", ctime(&z_atime));
871 	(void) printf("\tmtime	%s", ctime(&z_mtime));
872 	(void) printf("\tctime	%s", ctime(&z_ctime));
873 	(void) printf("\tcrtime	%s", ctime(&z_crtime));
874 	(void) printf("\tgen	%llu\n", (u_longlong_t)zp->zp_gen);
875 	(void) printf("\tmode	%llo\n", (u_longlong_t)zp->zp_mode);
876 	(void) printf("\tsize	%llu\n", (u_longlong_t)zp->zp_size);
877 	(void) printf("\tparent	%llu\n", (u_longlong_t)zp->zp_parent);
878 	(void) printf("\tlinks	%llu\n", (u_longlong_t)zp->zp_links);
879 	(void) printf("\txattr	%llu\n", (u_longlong_t)zp->zp_xattr);
880 	(void) printf("\trdev	0x%016llx\n", (u_longlong_t)zp->zp_rdev);
881 }
882 
883 /*ARGSUSED*/
884 static void
885 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
886 {
887 }
888 
889 /*ARGSUSED*/
890 static void
891 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
892 {
893 }
894 
895 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES] = {
896 	dump_none,		/* unallocated			*/
897 	dump_zap,		/* object directory		*/
898 	dump_uint64,		/* object array			*/
899 	dump_none,		/* packed nvlist		*/
900 	dump_packed_nvlist,	/* packed nvlist size		*/
901 	dump_none,		/* bplist			*/
902 	dump_none,		/* bplist header		*/
903 	dump_none,		/* SPA space map header		*/
904 	dump_none,		/* SPA space map		*/
905 	dump_none,		/* ZIL intent log		*/
906 	dump_dnode,		/* DMU dnode			*/
907 	dump_dmu_objset,	/* DMU objset			*/
908 	dump_dsl_dir,		/* DSL directory		*/
909 	dump_zap,		/* DSL directory child map	*/
910 	dump_zap,		/* DSL dataset snap map		*/
911 	dump_zap,		/* DSL props			*/
912 	dump_dsl_dataset,	/* DSL dataset			*/
913 	dump_znode,		/* ZFS znode			*/
914 	dump_acl,		/* ZFS ACL			*/
915 	dump_uint8,		/* ZFS plain file		*/
916 	dump_zap,		/* ZFS directory		*/
917 	dump_zap,		/* ZFS master node		*/
918 	dump_zap,		/* ZFS delete queue		*/
919 	dump_uint8,		/* zvol object			*/
920 	dump_zap,		/* zvol prop			*/
921 	dump_uint8,		/* other uint8[]		*/
922 	dump_uint64,		/* other uint64[]		*/
923 	dump_zap,		/* other ZAP			*/
924 	dump_zap,		/* persistent error log		*/
925 };
926 
927 static void
928 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
929 {
930 	dmu_buf_t *db = NULL;
931 	dmu_object_info_t doi;
932 	dnode_t *dn;
933 	void *bonus = NULL;
934 	size_t bsize = 0;
935 	char iblk[6], dblk[6], lsize[6], asize[6], bonus_size[6], segsize[6];
936 	char aux[50];
937 	int error;
938 
939 	if (*print_header) {
940 		(void) printf("\n    Object  lvl   iblk   dblk  lsize"
941 		    "  asize  type\n");
942 		*print_header = 0;
943 	}
944 
945 	if (object == 0) {
946 		dn = os->os->os_meta_dnode;
947 	} else {
948 		error = dmu_bonus_hold(os, object, FTAG, &db);
949 		if (error)
950 			fatal("dmu_bonus_hold(%llu) failed, errno %u",
951 			    object, error);
952 		bonus = db->db_data;
953 		bsize = db->db_size;
954 		dn = ((dmu_buf_impl_t *)db)->db_dnode;
955 	}
956 	dmu_object_info_from_dnode(dn, &doi);
957 
958 	nicenum(doi.doi_metadata_block_size, iblk);
959 	nicenum(doi.doi_data_block_size, dblk);
960 	nicenum(doi.doi_data_block_size * (doi.doi_max_block_offset + 1),
961 	    lsize);
962 	nicenum(doi.doi_physical_blks << 9, asize);
963 	nicenum(doi.doi_bonus_size, bonus_size);
964 
965 	aux[0] = '\0';
966 
967 	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6)
968 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
969 		zio_checksum_table[doi.doi_checksum].ci_name);
970 
971 	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6)
972 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
973 		zio_compress_table[doi.doi_compress].ci_name);
974 
975 	(void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %s%s\n",
976 	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk, lsize,
977 	    asize, dmu_ot[doi.doi_type].ot_name, aux);
978 
979 	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
980 		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %s\n",
981 		    "", "", "", "", bonus_size, "bonus",
982 		    dmu_ot[doi.doi_bonus_type].ot_name);
983 	}
984 
985 	if (verbosity >= 4) {
986 		object_viewer[doi.doi_bonus_type](os, object, bonus, bsize);
987 		object_viewer[doi.doi_type](os, object, NULL, 0);
988 		*print_header = 1;
989 	}
990 
991 	if (verbosity >= 5)
992 		dump_indirect(os, object, NULL, 0);
993 
994 	if (verbosity >= 5) {
995 		/*
996 		 * Report the list of segments that comprise the object.
997 		 */
998 		uint64_t start = 0;
999 		uint64_t end;
1000 		uint64_t blkfill = 1;
1001 		int minlvl = 1;
1002 
1003 		if (dn->dn_type == DMU_OT_DNODE) {
1004 			minlvl = 0;
1005 			blkfill = DNODES_PER_BLOCK;
1006 		}
1007 
1008 		for (;;) {
1009 			error = dnode_next_offset(dn, B_FALSE, &start, minlvl,
1010 			    blkfill);
1011 			if (error)
1012 				break;
1013 			end = start;
1014 			error = dnode_next_offset(dn, B_TRUE, &end, minlvl,
1015 			    blkfill);
1016 			nicenum(end - start, segsize);
1017 			(void) printf("\t\tsegment [%016llx, %016llx)"
1018 			    " size %5s\n", (u_longlong_t)start,
1019 			    (u_longlong_t)end, segsize);
1020 			if (error)
1021 				break;
1022 			start = end;
1023 		}
1024 	}
1025 
1026 	if (db != NULL)
1027 		dmu_buf_rele(db, FTAG);
1028 }
1029 
1030 static char *objset_types[DMU_OST_NUMTYPES] = {
1031 	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1032 
1033 /*ARGSUSED*/
1034 static void
1035 dump_dir(objset_t *os)
1036 {
1037 	dmu_objset_stats_t dds;
1038 	uint64_t object, object_count;
1039 	char numbuf[8];
1040 	char blkbuf[BP_SPRINTF_LEN];
1041 	char osname[MAXNAMELEN];
1042 	char *type = "UNKNOWN";
1043 	int verbosity = dump_opt['d'];
1044 	int print_header = 1;
1045 	int i, error;
1046 
1047 	dmu_objset_stats(os, &dds);
1048 
1049 	if (dds.dds_type < DMU_OST_NUMTYPES)
1050 		type = objset_types[dds.dds_type];
1051 
1052 	if (dds.dds_type == DMU_OST_META) {
1053 		dds.dds_creation_txg = TXG_INITIAL;
1054 		dds.dds_last_txg = os->os->os_rootbp.blk_birth;
1055 		dds.dds_objects_used = os->os->os_rootbp.blk_fill;
1056 		dds.dds_space_refd =
1057 		    os->os->os_spa->spa_dsl_pool->dp_mos_dir->dd_used_bytes;
1058 	}
1059 
1060 	ASSERT3U(dds.dds_objects_used, ==, os->os->os_rootbp.blk_fill);
1061 
1062 	nicenum(dds.dds_space_refd, numbuf);
1063 
1064 	if (verbosity >= 4) {
1065 		(void) strcpy(blkbuf, ", rootbp ");
1066 		sprintf_blkptr(blkbuf + strlen(blkbuf),
1067 		    BP_SPRINTF_LEN - strlen(blkbuf), &os->os->os_rootbp);
1068 	} else {
1069 		blkbuf[0] = '\0';
1070 	}
1071 
1072 	dmu_objset_name(os, osname);
1073 
1074 	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, last_txg %llu, "
1075 	    "%s, %llu objects%s\n",
1076 	    osname, type, (u_longlong_t)dmu_objset_id(os),
1077 	    (u_longlong_t)dds.dds_creation_txg,
1078 	    (u_longlong_t)dds.dds_last_txg,
1079 	    numbuf,
1080 	    (u_longlong_t)dds.dds_objects_used,
1081 	    blkbuf);
1082 
1083 	dump_intent_log(dmu_objset_zil(os));
1084 
1085 	if (dmu_objset_ds(os) != NULL)
1086 		dump_bplist(dmu_objset_pool(os)->dp_meta_objset,
1087 		    dmu_objset_ds(os)->ds_phys->ds_deadlist_obj, "Deadlist");
1088 
1089 	if (verbosity < 2)
1090 		return;
1091 
1092 	if (zopt_objects != 0) {
1093 		for (i = 0; i < zopt_objects; i++)
1094 			dump_object(os, zopt_object[i], verbosity,
1095 			    &print_header);
1096 		(void) printf("\n");
1097 		return;
1098 	}
1099 
1100 	dump_object(os, 0, verbosity, &print_header);
1101 	object_count = 1;
1102 
1103 	object = 0;
1104 	while ((error = dmu_object_next(os, &object, B_FALSE)) == 0) {
1105 		dump_object(os, object, verbosity, &print_header);
1106 		object_count++;
1107 	}
1108 
1109 	ASSERT3U(object_count, ==, dds.dds_objects_used);
1110 
1111 	(void) printf("\n");
1112 
1113 	if (error != ESRCH)
1114 		fatal("dmu_object_next() = %d", error);
1115 }
1116 
1117 static void
1118 dump_uberblock(uberblock_t *ub)
1119 {
1120 	time_t timestamp = ub->ub_timestamp;
1121 
1122 	(void) printf("Uberblock\n\n");
1123 	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
1124 	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
1125 	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
1126 	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
1127 	(void) printf("\ttimestamp = %llu UTC = %s",
1128 	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
1129 	if (dump_opt['u'] >= 3) {
1130 		char blkbuf[BP_SPRINTF_LEN];
1131 		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &ub->ub_rootbp);
1132 		(void) printf("\trootbp = %s\n", blkbuf);
1133 	}
1134 	(void) printf("\n");
1135 }
1136 
1137 static void
1138 dump_config(const char *pool)
1139 {
1140 	spa_t *spa = NULL;
1141 
1142 	mutex_enter(&spa_namespace_lock);
1143 	while ((spa = spa_next(spa)) != NULL) {
1144 		if (pool == NULL)
1145 			(void) printf("%s\n", spa_name(spa));
1146 		if (pool == NULL || strcmp(pool, spa_name(spa)) == 0)
1147 			dump_nvlist(spa->spa_config, 4);
1148 	}
1149 	mutex_exit(&spa_namespace_lock);
1150 }
1151 
1152 static void
1153 dump_label(const char *dev)
1154 {
1155 	int fd;
1156 	vdev_label_t label;
1157 	char *buf = label.vl_vdev_phys.vp_nvlist;
1158 	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1159 	struct stat64 statbuf;
1160 	uint64_t psize;
1161 	int l;
1162 
1163 	if ((fd = open64(dev, O_RDONLY)) < 0) {
1164 		(void) printf("cannot open '%s': %s\n", dev, strerror(errno));
1165 		exit(1);
1166 	}
1167 
1168 	if (fstat64(fd, &statbuf) != 0) {
1169 		(void) printf("failed to stat '%s': %s\n", dev,
1170 		    strerror(errno));
1171 		exit(1);
1172 	}
1173 
1174 	psize = statbuf.st_size;
1175 	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
1176 
1177 	for (l = 0; l < VDEV_LABELS; l++) {
1178 
1179 		nvlist_t *config = NULL;
1180 
1181 		(void) printf("--------------------------------------------\n");
1182 		(void) printf("LABEL %d\n", l);
1183 		(void) printf("--------------------------------------------\n");
1184 
1185 		if (pread64(fd, &label, sizeof (label),
1186 		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
1187 			(void) printf("failed to read label %d\n", l);
1188 			continue;
1189 		}
1190 
1191 		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
1192 			(void) printf("failed to unpack label %d\n", l);
1193 			continue;
1194 		}
1195 		dump_nvlist(config, 4);
1196 		nvlist_free(config);
1197 	}
1198 }
1199 
1200 /*ARGSUSED*/
1201 static void
1202 dump_one_dir(char *dsname, void *arg)
1203 {
1204 	int error;
1205 	objset_t *os;
1206 
1207 	error = dmu_objset_open(dsname, DMU_OST_ANY,
1208 	    DS_MODE_STANDARD | DS_MODE_READONLY, &os);
1209 	if (error) {
1210 		(void) printf("Could not open %s\n", dsname);
1211 		return;
1212 	}
1213 	dump_dir(os);
1214 	dmu_objset_close(os);
1215 }
1216 
1217 static void
1218 zdb_space_map_load(spa_t *spa)
1219 {
1220 	vdev_t *rvd = spa->spa_root_vdev;
1221 	vdev_t *vd;
1222 	int c, m, error;
1223 
1224 	for (c = 0; c < rvd->vdev_children; c++) {
1225 		vd = rvd->vdev_child[c];
1226 		for (m = 0; m < vd->vdev_ms_count; m++) {
1227 			metaslab_t *msp = vd->vdev_ms[m];
1228 			mutex_enter(&msp->ms_lock);
1229 			error = space_map_load(&msp->ms_allocmap[0], NULL,
1230 			    SM_ALLOC, &msp->ms_smo, spa->spa_meta_objset);
1231 			mutex_exit(&msp->ms_lock);
1232 			if (error)
1233 				fatal("%s bad space map #%d, error %d",
1234 				    spa->spa_name, c, error);
1235 		}
1236 	}
1237 }
1238 
1239 static int
1240 zdb_space_map_claim(spa_t *spa, blkptr_t *bp, zbookmark_t *zb)
1241 {
1242 	dva_t *dva = bp->blk_dva;
1243 	vdev_t *vd;
1244 	metaslab_t *msp;
1245 	space_map_t *allocmap, *freemap;
1246 	int error;
1247 	int d;
1248 	blkptr_t blk = *bp;
1249 
1250 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1251 		uint64_t vdev = DVA_GET_VDEV(&dva[d]);
1252 		uint64_t offset = DVA_GET_OFFSET(&dva[d]);
1253 		uint64_t size = DVA_GET_ASIZE(&dva[d]);
1254 
1255 		if ((vd = vdev_lookup_top(spa, vdev)) == NULL)
1256 			return (ENXIO);
1257 
1258 		if ((offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
1259 			return (ENXIO);
1260 
1261 		msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
1262 		allocmap = &msp->ms_allocmap[0];
1263 		freemap = &msp->ms_freemap[0];
1264 
1265 		/* Prepare our copy of the bp in case we need to read GBHs */
1266 		if (DVA_GET_GANG(&dva[d])) {
1267 			size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
1268 			DVA_SET_ASIZE(&blk.blk_dva[d], size);
1269 			DVA_SET_GANG(&blk.blk_dva[d], 0);
1270 		}
1271 
1272 		mutex_enter(&msp->ms_lock);
1273 		if (space_map_contains(freemap, offset, size)) {
1274 			mutex_exit(&msp->ms_lock);
1275 			return (EAGAIN);	/* allocated more than once */
1276 		}
1277 
1278 		if (!space_map_contains(allocmap, offset, size)) {
1279 			mutex_exit(&msp->ms_lock);
1280 			return (ESTALE);	/* not allocated at all */
1281 		}
1282 
1283 		space_map_remove(allocmap, offset, size);
1284 		space_map_add(freemap, offset, size);
1285 
1286 		mutex_exit(&msp->ms_lock);
1287 	}
1288 
1289 	if (BP_IS_GANG(bp)) {
1290 		zio_gbh_phys_t gbh;
1291 		int g;
1292 
1293 		/* LINTED - compile time assert */
1294 		ASSERT(sizeof (zio_gbh_phys_t) == SPA_GANGBLOCKSIZE);
1295 
1296 		BP_SET_CHECKSUM(&blk, ZIO_CHECKSUM_GANG_HEADER);
1297 		BP_SET_PSIZE(&blk, SPA_GANGBLOCKSIZE);
1298 		BP_SET_LSIZE(&blk, SPA_GANGBLOCKSIZE);
1299 		BP_SET_COMPRESS(&blk, ZIO_COMPRESS_OFF);
1300 		error = zio_wait(zio_read(NULL, spa, &blk, &gbh,
1301 		    SPA_GANGBLOCKSIZE, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
1302 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_CONFIG_HELD, zb));
1303 		if (error)
1304 			return (error);
1305 		if (BP_SHOULD_BYTESWAP(&blk))
1306 			byteswap_uint64_array(&gbh, SPA_GANGBLOCKSIZE);
1307 		for (g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1308 			if (BP_IS_HOLE(&gbh.zg_blkptr[g]))
1309 				break;
1310 			error = zdb_space_map_claim(spa, &gbh.zg_blkptr[g], zb);
1311 			if (error)
1312 				return (error);
1313 		}
1314 	}
1315 
1316 	return (0);
1317 }
1318 
1319 static void
1320 zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
1321 {
1322 	metaslab_t *msp;
1323 
1324 	/* LINTED */
1325 	msp = (metaslab_t *)((char *)sm - offsetof(metaslab_t, ms_allocmap[0]));
1326 
1327 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
1328 	    (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
1329 	    (u_longlong_t)start,
1330 	    (u_longlong_t)size);
1331 }
1332 
1333 static void
1334 zdb_space_map_unload(spa_t *spa)
1335 {
1336 	vdev_t *rvd = spa->spa_root_vdev;
1337 	vdev_t *vd;
1338 	int c, m;
1339 
1340 	for (c = 0; c < rvd->vdev_children; c++) {
1341 		vd = rvd->vdev_child[c];
1342 		for (m = 0; m < vd->vdev_ms_count; m++) {
1343 			metaslab_t *msp = vd->vdev_ms[m];
1344 			mutex_enter(&msp->ms_lock);
1345 			space_map_vacate(&msp->ms_allocmap[0], zdb_leak,
1346 			    &msp->ms_allocmap[0]);
1347 			space_map_unload(&msp->ms_allocmap[0]);
1348 			space_map_vacate(&msp->ms_freemap[0], NULL, NULL);
1349 			mutex_exit(&msp->ms_lock);
1350 		}
1351 	}
1352 }
1353 
1354 static void
1355 zdb_refresh_ubsync(spa_t *spa)
1356 {
1357 	uberblock_t ub = { 0 };
1358 	vdev_t *rvd = spa->spa_root_vdev;
1359 	zio_t *zio;
1360 
1361 	/*
1362 	 * Reload the uberblock.
1363 	 */
1364 	zio = zio_root(spa, NULL, NULL,
1365 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
1366 	vdev_uberblock_load(zio, rvd, &ub);
1367 	(void) zio_wait(zio);
1368 
1369 	if (ub.ub_txg != 0)
1370 		spa->spa_ubsync = ub;
1371 }
1372 
1373 /*
1374  * Verify that the sum of the sizes of all blocks in the pool adds up
1375  * to the SPA's sa_alloc total.
1376  */
1377 typedef struct zdb_blkstats {
1378 	uint64_t	zb_asize;
1379 	uint64_t	zb_lsize;
1380 	uint64_t	zb_psize;
1381 	uint64_t	zb_count;
1382 } zdb_blkstats_t;
1383 
1384 #define	DMU_OT_DEFERRED	DMU_OT_NONE
1385 #define	DMU_OT_TOTAL	DMU_OT_NUMTYPES
1386 
1387 #define	ZB_TOTAL	ZB_MAXLEVEL
1388 
1389 typedef struct zdb_cb {
1390 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][DMU_OT_TOTAL + 1];
1391 	uint64_t	zcb_errors[256];
1392 	traverse_blk_cache_t *zcb_cache;
1393 	int		zcb_readfails;
1394 	int		zcb_haderrors;
1395 } zdb_cb_t;
1396 
1397 static void
1398 zdb_count_block(spa_t *spa, zdb_cb_t *zcb, blkptr_t *bp, int type)
1399 {
1400 	int i, error;
1401 
1402 	for (i = 0; i < 4; i++) {
1403 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
1404 		int t = (i & 1) ? type : DMU_OT_TOTAL;
1405 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
1406 
1407 		zb->zb_asize += BP_GET_ASIZE(bp);
1408 		zb->zb_lsize += BP_GET_LSIZE(bp);
1409 		zb->zb_psize += BP_GET_PSIZE(bp);
1410 		zb->zb_count++;
1411 	}
1412 
1413 	if (dump_opt['L'])
1414 		return;
1415 
1416 	error = zdb_space_map_claim(spa, bp, &zcb->zcb_cache->bc_bookmark);
1417 
1418 	if (error == 0)
1419 		return;
1420 
1421 	if (error == EAGAIN)
1422 		(void) fatal("double-allocation, bp=%p", bp);
1423 
1424 	if (error == ESTALE)
1425 		(void) fatal("reference to freed block, bp=%p", bp);
1426 
1427 	(void) fatal("fatal error %d in bp %p", error, bp);
1428 }
1429 
1430 static int
1431 zdb_blkptr_cb(traverse_blk_cache_t *bc, spa_t *spa, void *arg)
1432 {
1433 	zbookmark_t *zb = &bc->bc_bookmark;
1434 	zdb_cb_t *zcb = arg;
1435 	blkptr_t *bp = &bc->bc_blkptr;
1436 	dmu_object_type_t type = BP_GET_TYPE(bp);
1437 	char blkbuf[BP_SPRINTF_LEN];
1438 	int error = 0;
1439 
1440 	if (bc->bc_errno) {
1441 		if (zcb->zcb_readfails++ < 10 && dump_opt['L']) {
1442 			zdb_refresh_ubsync(spa);
1443 			error = EAGAIN;
1444 		} else {
1445 			zcb->zcb_haderrors = 1;
1446 			zcb->zcb_errors[bc->bc_errno]++;
1447 			error = ERESTART;
1448 		}
1449 
1450 		if (dump_opt['b'] >= 3 || (dump_opt['b'] >= 2 && bc->bc_errno))
1451 			sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1452 		else
1453 			blkbuf[0] = '\0';
1454 
1455 		(void) printf("zdb_blkptr_cb: Got error %d reading "
1456 		    "<%llu, %llu, %lld, %llx> %s -- %s\n",
1457 		    bc->bc_errno,
1458 		    (u_longlong_t)zb->zb_objset,
1459 		    (u_longlong_t)zb->zb_object,
1460 		    (u_longlong_t)zb->zb_level,
1461 		    (u_longlong_t)zb->zb_blkid,
1462 		    blkbuf,
1463 		    error == EAGAIN ? "retrying" : "skipping");
1464 
1465 		return (error);
1466 	}
1467 
1468 	zcb->zcb_readfails = 0;
1469 
1470 	ASSERT(!BP_IS_HOLE(bp));
1471 
1472 	if (dump_opt['b'] >= 4) {
1473 		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1474 		(void) printf("objset %llu object %llu offset 0x%llx %s\n",
1475 		    (u_longlong_t)zb->zb_objset,
1476 		    (u_longlong_t)zb->zb_object,
1477 		    (u_longlong_t)blkid2offset(bc->bc_dnode,
1478 			zb->zb_level, zb->zb_blkid),
1479 		    blkbuf);
1480 	}
1481 
1482 	zdb_count_block(spa, zcb, bp, type);
1483 
1484 	return (0);
1485 }
1486 
1487 static int
1488 dump_block_stats(spa_t *spa)
1489 {
1490 	traverse_handle_t *th;
1491 	zdb_cb_t zcb = { 0 };
1492 	traverse_blk_cache_t dummy_cache = { 0 };
1493 	zdb_blkstats_t *zb, *tzb;
1494 	uint64_t alloc, space;
1495 	int leaks = 0;
1496 	int advance = zdb_advance;
1497 	int flags;
1498 	int e;
1499 
1500 	zcb.zcb_cache = &dummy_cache;
1501 
1502 	if (dump_opt['c'])
1503 		advance |= ADVANCE_DATA;
1504 
1505 	advance |= ADVANCE_PRUNE | ADVANCE_ZIL;
1506 
1507 	(void) printf("\nTraversing all blocks to %sverify"
1508 	    " nothing leaked ...\n",
1509 	    dump_opt['c'] ? "verify checksums and " : "");
1510 
1511 	/*
1512 	 * Load all space maps.  As we traverse the pool, if we find a block
1513 	 * that's not in its space map, that indicates a double-allocation,
1514 	 * reference to a freed block, or an unclaimed block.  Otherwise we
1515 	 * remove the block from the space map.  If the space maps are not
1516 	 * empty when we're done, that indicates leaked blocks.
1517 	 */
1518 	if (!dump_opt['L'])
1519 		zdb_space_map_load(spa);
1520 
1521 	/*
1522 	 * If there's a deferred-free bplist, process that first.
1523 	 */
1524 	if (spa->spa_sync_bplist_obj != 0) {
1525 		bplist_t *bpl = &spa->spa_sync_bplist;
1526 		blkptr_t blk;
1527 		uint64_t itor = 0;
1528 
1529 		VERIFY(0 == bplist_open(bpl, spa->spa_meta_objset,
1530 		    spa->spa_sync_bplist_obj));
1531 
1532 		while (bplist_iterate(bpl, &itor, &blk) == 0) {
1533 			if (dump_opt['b'] >= 4) {
1534 				char blkbuf[BP_SPRINTF_LEN];
1535 				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &blk);
1536 				(void) printf("[%s] %s\n",
1537 				    "deferred free", blkbuf);
1538 			}
1539 			zdb_count_block(spa, &zcb, &blk, DMU_OT_DEFERRED);
1540 		}
1541 
1542 		bplist_close(bpl);
1543 	}
1544 
1545 	/*
1546 	 * Now traverse the pool.  If we're reading all data to verify
1547 	 * checksums, do a scrubbing read so that we validate all copies.
1548 	 */
1549 	flags = ZIO_FLAG_CANFAIL;
1550 	if (advance & ADVANCE_DATA)
1551 		flags |= ZIO_FLAG_SCRUB;
1552 	th = traverse_init(spa, zdb_blkptr_cb, &zcb, advance, flags);
1553 	th->th_noread = zdb_noread;
1554 
1555 	traverse_add_pool(th, 0, spa_first_txg(spa) + TXG_CONCURRENT_STATES);
1556 
1557 	while (traverse_more(th) == EAGAIN)
1558 		continue;
1559 
1560 	traverse_fini(th);
1561 
1562 	if (zcb.zcb_haderrors) {
1563 		(void) printf("\nError counts:\n\n");
1564 		(void) printf("\t%5s  %s\n", "errno", "count");
1565 		for (e = 0; e < 256; e++) {
1566 			if (zcb.zcb_errors[e] != 0) {
1567 				(void) printf("\t%5d  %llu\n",
1568 				    e, (u_longlong_t)zcb.zcb_errors[e]);
1569 			}
1570 		}
1571 	}
1572 
1573 	/*
1574 	 * Report any leaked segments.
1575 	 */
1576 	if (!dump_opt['L'])
1577 		zdb_space_map_unload(spa);
1578 
1579 	if (dump_opt['L'])
1580 		(void) printf("\n\n *** Live pool traversal; "
1581 		    "block counts are only approximate ***\n\n");
1582 
1583 	alloc = spa_get_alloc(spa);
1584 	space = spa_get_space(spa);
1585 
1586 	tzb = &zcb.zcb_type[ZB_TOTAL][DMU_OT_TOTAL];
1587 
1588 	if (tzb->zb_asize == alloc) {
1589 		(void) printf("\n\tNo leaks (block sum matches space"
1590 		    " maps exactly)\n");
1591 	} else {
1592 		(void) printf("block traversal size %llu != alloc %llu "
1593 		    "(leaked %lld)\n",
1594 		    (u_longlong_t)tzb->zb_asize,
1595 		    (u_longlong_t)alloc,
1596 		    (u_longlong_t)(alloc - tzb->zb_asize));
1597 		leaks = 1;
1598 	}
1599 
1600 	if (tzb->zb_count == 0)
1601 		return (2);
1602 
1603 	(void) printf("\n");
1604 	(void) printf("\tbp count:      %10llu\n",
1605 	    (u_longlong_t)tzb->zb_count);
1606 	(void) printf("\tbp logical:    %10llu\t avg: %6llu\n",
1607 	    (u_longlong_t)tzb->zb_lsize,
1608 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
1609 	(void) printf("\tbp physical:   %10llu\t avg:"
1610 	    " %6llu\tcompression: %6.2f\n",
1611 	    (u_longlong_t)tzb->zb_psize,
1612 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
1613 	    (double)tzb->zb_lsize / tzb->zb_psize);
1614 	(void) printf("\tbp allocated:  %10llu\t avg:"
1615 	    " %6llu\tcompression: %6.2f\n",
1616 	    (u_longlong_t)tzb->zb_asize,
1617 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
1618 	    (double)tzb->zb_lsize / tzb->zb_asize);
1619 	(void) printf("\tSPA allocated: %10llu\tused: %5.2f%%\n",
1620 	    (u_longlong_t)alloc, 100.0 * alloc / space);
1621 
1622 	if (dump_opt['b'] >= 2) {
1623 		int l, t, level;
1624 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
1625 		    "\t  avg\t comp\t%%Total\tType\n");
1626 
1627 		for (t = 0; t <= DMU_OT_NUMTYPES; t++) {
1628 			char csize[6], lsize[6], psize[6], asize[6], avg[6];
1629 			char *typename;
1630 
1631 			typename = t == DMU_OT_DEFERRED ? "deferred free" :
1632 			    t == DMU_OT_TOTAL ? "Total" : dmu_ot[t].ot_name;
1633 
1634 			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
1635 				(void) printf("%6s\t%5s\t%5s\t%5s"
1636 				    "\t%5s\t%5s\t%6s\t%s\n",
1637 				    "-",
1638 				    "-",
1639 				    "-",
1640 				    "-",
1641 				    "-",
1642 				    "-",
1643 				    "-",
1644 				    typename);
1645 				continue;
1646 			}
1647 
1648 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
1649 				level = (l == -1 ? ZB_TOTAL : l);
1650 				zb = &zcb.zcb_type[level][t];
1651 
1652 				if (zb->zb_asize == 0)
1653 					continue;
1654 
1655 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
1656 					continue;
1657 
1658 				if (level == 0 && zb->zb_asize ==
1659 				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
1660 					continue;
1661 
1662 				nicenum(zb->zb_count, csize);
1663 				nicenum(zb->zb_lsize, lsize);
1664 				nicenum(zb->zb_psize, psize);
1665 				nicenum(zb->zb_asize, asize);
1666 				nicenum(zb->zb_asize / zb->zb_count, avg);
1667 
1668 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
1669 				    "\t%5.2f\t%6.2f\t",
1670 				    csize, lsize, psize, asize, avg,
1671 				    (double)zb->zb_lsize / zb->zb_psize,
1672 				    100.0 * zb->zb_asize / tzb->zb_asize);
1673 
1674 				if (level == ZB_TOTAL)
1675 					(void) printf("%s\n", typename);
1676 				else
1677 					(void) printf("    L%d %s\n",
1678 					    level, typename);
1679 			}
1680 		}
1681 	}
1682 
1683 	(void) printf("\n");
1684 
1685 	if (leaks)
1686 		return (2);
1687 
1688 	if (zcb.zcb_haderrors)
1689 		return (3);
1690 
1691 	return (0);
1692 }
1693 
1694 static void
1695 dump_zpool(spa_t *spa)
1696 {
1697 	dsl_pool_t *dp = spa_get_dsl(spa);
1698 	int rc = 0;
1699 
1700 	if (dump_opt['u'])
1701 		dump_uberblock(&spa->spa_uberblock);
1702 
1703 	if (dump_opt['d'] || dump_opt['i']) {
1704 		dump_dir(dp->dp_meta_objset);
1705 		if (dump_opt['d'] >= 3) {
1706 			dump_bplist(dp->dp_meta_objset,
1707 			    spa->spa_sync_bplist_obj, "Deferred frees");
1708 			dump_dtl(spa->spa_root_vdev, 0);
1709 			dump_metaslabs(spa);
1710 		}
1711 		dmu_objset_find(spa->spa_name, dump_one_dir, NULL,
1712 		    DS_FIND_SNAPSHOTS);
1713 	}
1714 
1715 	if (dump_opt['b'] || dump_opt['c'])
1716 		rc = dump_block_stats(spa);
1717 
1718 	if (dump_opt['s'])
1719 		show_pool_stats(spa);
1720 
1721 	if (rc != 0)
1722 		exit(rc);
1723 }
1724 
1725 #define	ZDB_FLAG_CHECKSUM	0x0001
1726 #define	ZDB_FLAG_DECOMPRESS	0x0002
1727 #define	ZDB_FLAG_BSWAP		0x0004
1728 #define	ZDB_FLAG_GBH		0x0008
1729 #define	ZDB_FLAG_INDIRECT	0x0010
1730 #define	ZDB_FLAG_PHYS		0x0020
1731 #define	ZDB_FLAG_RAW		0x0040
1732 #define	ZDB_FLAG_PRINT_BLKPTR	0x0080
1733 
1734 int flagbits[256];
1735 
1736 static void
1737 zdb_print_blkptr(blkptr_t *bp, int flags)
1738 {
1739 	dva_t *dva = bp->blk_dva;
1740 	int d;
1741 
1742 	if (flags & ZDB_FLAG_BSWAP)
1743 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
1744 	/*
1745 	 * Super-ick warning:  This code is also duplicated in
1746 	 * cmd/mdb/common/modules/zfs/zfs.c .  Yeah, I hate code
1747 	 * replication, too.
1748 	 */
1749 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1750 		(void) printf("\tDVA[%d]: vdev_id %lld / %llx\n", d,
1751 		    DVA_GET_VDEV(&dva[d]), DVA_GET_OFFSET(&dva[d]));
1752 		(void) printf("\tDVA[%d]:       GANG: %-5s  GRID:  %04llx\t"
1753 		    "ASIZE: %llx\n", d,
1754 		    DVA_GET_GANG(&dva[d]) ? "TRUE" : "FALSE",
1755 		    DVA_GET_GRID(&dva[d]), DVA_GET_ASIZE(&dva[d]));
1756 		(void) printf("\tDVA[%d]: :%llu:%llx:%llx:%s%s%s%s\n", d,
1757 		    DVA_GET_VDEV(&dva[d]), DVA_GET_OFFSET(&dva[d]),
1758 		    BP_GET_PSIZE(bp),
1759 		    BP_SHOULD_BYTESWAP(bp) ? "e" : "",
1760 		    !DVA_GET_GANG(&dva[d]) && BP_GET_LEVEL(bp) != 0 ?
1761 		    "d" : "",
1762 		    DVA_GET_GANG(&dva[d]) ? "g" : "",
1763 		    BP_GET_COMPRESS(bp) != 0 ? "d" : "");
1764 	}
1765 	(void) printf("\tLSIZE:  %-16llx\t\tPSIZE: %llx\n",
1766 	    BP_GET_LSIZE(bp), BP_GET_PSIZE(bp));
1767 	(void) printf("\tENDIAN: %6s\t\t\t\t\tTYPE:  %s\n",
1768 	    BP_GET_BYTEORDER(bp) ? "LITTLE" : "BIG",
1769 	    dmu_ot[BP_GET_TYPE(bp)].ot_name);
1770 	(void) printf("\tBIRTH:  %-16llx   LEVEL: %-2llu\tFILL:  %llx\n",
1771 	    (u_longlong_t)bp->blk_birth, BP_GET_LEVEL(bp),
1772 	    (u_longlong_t)bp->blk_fill);
1773 	(void) printf("\tCKFUNC: %-16s\t\tCOMP:  %s\n",
1774 	    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
1775 	    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name);
1776 	(void) printf("\tCKSUM:  %llx:%llx:%llx:%llx\n",
1777 	    (u_longlong_t)bp->blk_cksum.zc_word[0],
1778 	    (u_longlong_t)bp->blk_cksum.zc_word[1],
1779 	    (u_longlong_t)bp->blk_cksum.zc_word[2],
1780 	    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1781 }
1782 
1783 static void
1784 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
1785 {
1786 	int i;
1787 
1788 	for (i = 0; i < nbps; i++)
1789 		zdb_print_blkptr(&bp[i], flags);
1790 }
1791 
1792 static void
1793 zdb_dump_gbh(void *buf, int flags)
1794 {
1795 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
1796 }
1797 
1798 static void
1799 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
1800 {
1801 	if (flags & ZDB_FLAG_BSWAP)
1802 		byteswap_uint64_array(buf, size);
1803 	(void) write(2, buf, size);
1804 }
1805 
1806 static void
1807 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
1808 {
1809 	uint64_t *d = (uint64_t *)buf;
1810 	int nwords = size / sizeof (uint64_t);
1811 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
1812 	int i, j;
1813 	char *hdr, *c;
1814 
1815 
1816 	if (do_bswap)
1817 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
1818 	else
1819 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
1820 
1821 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
1822 
1823 	for (i = 0; i < nwords; i += 2) {
1824 		(void) printf("%06llx:  %016llx  %016llx  ",
1825 		    (u_longlong_t)(i * sizeof (uint64_t)),
1826 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
1827 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
1828 
1829 		c = (char *)&d[i];
1830 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
1831 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
1832 		(void) printf("\n");
1833 	}
1834 }
1835 
1836 /*
1837  * There are two acceptable formats:
1838  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
1839  *	child[.child]*    - For example: 0.1.1
1840  *
1841  * The second form can be used to specify arbitrary vdevs anywhere
1842  * in the heirarchy.  For example, in a pool with a mirror of
1843  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
1844  */
1845 static vdev_t *
1846 zdb_vdev_lookup(vdev_t *vdev, char *path)
1847 {
1848 	char *s, *p, *q;
1849 	int i;
1850 
1851 	if (vdev == NULL)
1852 		return (NULL);
1853 
1854 	/* First, assume the x.x.x.x format */
1855 	i = (int)strtoul(path, &s, 10);
1856 	if (s == path || (s && *s != '.' && *s != '\0'))
1857 		goto name;
1858 	if (i < 0 || i >= vdev->vdev_children)
1859 		return (NULL);
1860 
1861 	vdev = vdev->vdev_child[i];
1862 	if (*s == '\0')
1863 		return (vdev);
1864 	return (zdb_vdev_lookup(vdev, s+1));
1865 
1866 name:
1867 	for (i = 0; i < vdev->vdev_children; i++) {
1868 		vdev_t *vc = vdev->vdev_child[i];
1869 
1870 		if (vc->vdev_path == NULL) {
1871 			vc = zdb_vdev_lookup(vc, path);
1872 			if (vc == NULL)
1873 				continue;
1874 			else
1875 				return (vc);
1876 		}
1877 
1878 		p = strrchr(vc->vdev_path, '/');
1879 		p = p ? p + 1 : vc->vdev_path;
1880 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
1881 
1882 		if (strcmp(vc->vdev_path, path) == 0)
1883 			return (vc);
1884 		if (strcmp(p, path) == 0)
1885 			return (vc);
1886 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
1887 			return (vc);
1888 	}
1889 
1890 	return (NULL);
1891 }
1892 
1893 /*
1894  * Read a block from a pool and print it out.  The syntax of the
1895  * block descriptor is:
1896  *
1897  *	pool:vdev_specifier:offset:size[:flags]
1898  *
1899  *	pool           - The name of the pool you wish to read from
1900  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
1901  *	offset         - offset, in hex, in bytes
1902  *	size           - Amount of data to read, in hex, in bytes
1903  *	flags          - A string of characters specifying options
1904  *		 b: Decode a blkptr at given offset within block
1905  *		*c: Calculate and display checksums
1906  *		*d: Decompress data before dumping
1907  *		 e: Byteswap data before dumping
1908  *		*g: Display data as a gang block header
1909  *		*i: Display as an indirect block
1910  *		 p: Do I/O to physical offset
1911  *		 r: Dump raw data to stdout
1912  *
1913  *              * = not yet implemented
1914  */
1915 static void
1916 zdb_read_block(char *thing, spa_t **spap)
1917 {
1918 	spa_t *spa = *spap;
1919 	int flags = 0;
1920 	uint64_t offset = 0, size = 0, blkptr_offset = 0;
1921 	zio_t *zio;
1922 	vdev_t *vd;
1923 	void *buf;
1924 	char *s, *p, *dup, *spa_name, *vdev, *flagstr;
1925 	int i, error, zio_flags;
1926 
1927 	dup = strdup(thing);
1928 	s = strtok(dup, ":");
1929 	spa_name = s ? s : "";
1930 	s = strtok(NULL, ":");
1931 	vdev = s ? s : "";
1932 	s = strtok(NULL, ":");
1933 	offset = strtoull(s ? s : "", NULL, 16);
1934 	s = strtok(NULL, ":");
1935 	size = strtoull(s ? s : "", NULL, 16);
1936 	s = strtok(NULL, ":");
1937 	flagstr = s ? s : "";
1938 
1939 	s = NULL;
1940 	if (size == 0)
1941 		s = "size must not be zero";
1942 	if (!IS_P2ALIGNED(size, DEV_BSIZE))
1943 		s = "size must be a multiple of sector size";
1944 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
1945 		s = "offset must be a multiple of sector size";
1946 	if (s) {
1947 		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
1948 		free(dup);
1949 		return;
1950 	}
1951 
1952 	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
1953 		for (i = 0; flagstr[i]; i++) {
1954 			int bit = flagbits[flagstr[i]];
1955 
1956 			if (bit == 0) {
1957 				(void) printf("***Invalid flag: %c\n",
1958 				    flagstr[i]);
1959 				continue;
1960 			}
1961 			flags |= bit;
1962 
1963 			/* If it's not something with an argument, keep going */
1964 			if ((bit & (ZDB_FLAG_CHECKSUM | ZDB_FLAG_DECOMPRESS |
1965 			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
1966 				continue;
1967 
1968 			p = &flagstr[i + 1];
1969 			if (bit == ZDB_FLAG_PRINT_BLKPTR)
1970 				blkptr_offset = strtoull(p, &p, 16);
1971 			if (*p != ':' && *p != '\0') {
1972 				(void) printf("***Invalid flag arg: '%s'\n", s);
1973 				free(dup);
1974 				return;
1975 			}
1976 		}
1977 	}
1978 
1979 	if (spa == NULL || spa->spa_name == NULL ||
1980 	    strcmp(spa->spa_name, spa_name)) {
1981 		if (spa && spa->spa_name)
1982 			spa_close(spa, (void *)zdb_read_block);
1983 		error = spa_open(spa_name, spap, (void *)zdb_read_block);
1984 		if (error)
1985 			fatal("Failed to open pool '%s': errno = %d\n",
1986 			    spa_name, error);
1987 		spa = *spap;
1988 	}
1989 
1990 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
1991 	if (vd == NULL) {
1992 		(void) printf("***Invalid vdev: %s\n", vdev);
1993 		free(dup);
1994 		return;
1995 	} else {
1996 		if (vd->vdev_path)
1997 			(void) printf("Found vdev: %s\n", vd->vdev_path);
1998 		else
1999 			(void) printf("Found vdev type: %s\n",
2000 			    vd->vdev_ops->vdev_op_type);
2001 	}
2002 
2003 	buf = umem_alloc(size, UMEM_NOFAIL);
2004 
2005 	zio_flags = ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2006 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY | ZIO_FLAG_NOBOOKMARK;
2007 
2008 	if (flags & ZDB_FLAG_PHYS)
2009 		zio_flags |= ZIO_FLAG_PHYSICAL;
2010 
2011 	zio = zio_root(spa, NULL, NULL, 0);
2012 	/* XXX todo - cons up a BP so RAID-Z will be happy */
2013 	zio_nowait(zio_vdev_child_io(zio, NULL, vd, offset, buf, size,
2014 	    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ, zio_flags, NULL, NULL));
2015 	error = zio_wait(zio);
2016 
2017 	if (error) {
2018 		(void) printf("Read of %s failed, error: %d\n", thing, error);
2019 		goto out;
2020 	}
2021 
2022 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2023 		zdb_print_blkptr((blkptr_t *)(void *)
2024 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2025 	else if (flags & ZDB_FLAG_RAW)
2026 		zdb_dump_block_raw(buf, size, flags);
2027 	else if (flags & ZDB_FLAG_INDIRECT)
2028 		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2029 		    flags);
2030 	else if (flags & ZDB_FLAG_GBH)
2031 		zdb_dump_gbh(buf, flags);
2032 	else
2033 		zdb_dump_block(thing, buf, size, flags);
2034 
2035 out:
2036 	umem_free(buf, size);
2037 	free(dup);
2038 }
2039 
2040 int
2041 main(int argc, char **argv)
2042 {
2043 	int i, c;
2044 	struct rlimit rl = { 1024, 1024 };
2045 	spa_t *spa;
2046 	objset_t *os = NULL;
2047 	char *endstr;
2048 	int dump_all = 1;
2049 	int verbose = 0;
2050 	int error;
2051 	int flag, set;
2052 	vdev_knob_t *vk;
2053 
2054 	(void) setrlimit(RLIMIT_NOFILE, &rl);
2055 	(void) enable_extended_FILE_stdio(-1, -1);
2056 
2057 	dprintf_setup(&argc, argv);
2058 
2059 	while ((c = getopt(argc, argv, "udibcsvCLO:B:UlR")) != -1) {
2060 		switch (c) {
2061 		case 'u':
2062 		case 'd':
2063 		case 'i':
2064 		case 'b':
2065 		case 'c':
2066 		case 's':
2067 		case 'C':
2068 		case 'l':
2069 		case 'R':
2070 			dump_opt[c]++;
2071 			dump_all = 0;
2072 			break;
2073 		case 'L':
2074 			dump_opt[c]++;
2075 			break;
2076 		case 'O':
2077 			endstr = optarg;
2078 			if (endstr[0] == '!') {
2079 				endstr++;
2080 				set = 0;
2081 			} else {
2082 				set = 1;
2083 			}
2084 			if (strcmp(endstr, "post") == 0) {
2085 				flag = ADVANCE_PRE;
2086 				set = !set;
2087 			} else if (strcmp(endstr, "pre") == 0) {
2088 				flag = ADVANCE_PRE;
2089 			} else if (strcmp(endstr, "prune") == 0) {
2090 				flag = ADVANCE_PRUNE;
2091 			} else if (strcmp(endstr, "data") == 0) {
2092 				flag = ADVANCE_DATA;
2093 			} else if (strcmp(endstr, "holes") == 0) {
2094 				flag = ADVANCE_HOLES;
2095 			} else {
2096 				usage();
2097 			}
2098 			if (set)
2099 				zdb_advance |= flag;
2100 			else
2101 				zdb_advance &= ~flag;
2102 			break;
2103 		case 'B':
2104 			endstr = optarg - 1;
2105 			zdb_noread.zb_objset = strtoull(endstr + 1, &endstr, 0);
2106 			zdb_noread.zb_object = strtoull(endstr + 1, &endstr, 0);
2107 			zdb_noread.zb_level = strtol(endstr + 1, &endstr, 0);
2108 			zdb_noread.zb_blkid = strtoull(endstr + 1, &endstr, 16);
2109 			(void) printf("simulating bad block "
2110 			    "<%llu, %llu, %lld, %llx>\n",
2111 			    (u_longlong_t)zdb_noread.zb_objset,
2112 			    (u_longlong_t)zdb_noread.zb_object,
2113 			    (u_longlong_t)zdb_noread.zb_level,
2114 			    (u_longlong_t)zdb_noread.zb_blkid);
2115 			break;
2116 		case 'v':
2117 			verbose++;
2118 			break;
2119 		case 'U':
2120 			spa_config_dir = "/tmp";
2121 			break;
2122 		default:
2123 			usage();
2124 			break;
2125 		}
2126 	}
2127 
2128 	kernel_init(FREAD);
2129 
2130 	/*
2131 	 * Disable vdev caching.  If we don't do this, live pool traversal
2132 	 * won't make progress because it will never see disk updates.
2133 	 */
2134 	for (vk = vdev_knob_next(NULL); vk != NULL; vk = vdev_knob_next(vk)) {
2135 		if (strcmp(vk->vk_name, "cache_size") == 0)
2136 			vk->vk_default = 0;
2137 	}
2138 
2139 	for (c = 0; c < 256; c++) {
2140 		if (dump_all && c != 'L' && c != 'l' && c != 'R')
2141 			dump_opt[c] = 1;
2142 		if (dump_opt[c])
2143 			dump_opt[c] += verbose;
2144 	}
2145 
2146 	argc -= optind;
2147 	argv += optind;
2148 
2149 	if (argc < 1) {
2150 		if (dump_opt['C']) {
2151 			dump_config(NULL);
2152 			return (0);
2153 		}
2154 		usage();
2155 	}
2156 
2157 	if (dump_opt['l']) {
2158 		dump_label(argv[0]);
2159 		return (0);
2160 	}
2161 
2162 	if (dump_opt['R']) {
2163 		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
2164 		flagbits['c'] = ZDB_FLAG_CHECKSUM;
2165 		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
2166 		flagbits['e'] = ZDB_FLAG_BSWAP;
2167 		flagbits['g'] = ZDB_FLAG_GBH;
2168 		flagbits['i'] = ZDB_FLAG_INDIRECT;
2169 		flagbits['p'] = ZDB_FLAG_PHYS;
2170 		flagbits['r'] = ZDB_FLAG_RAW;
2171 
2172 		spa = NULL;
2173 		while (argv[0]) {
2174 			zdb_read_block(argv[0], &spa);
2175 			argv++;
2176 			argc--;
2177 		}
2178 		if (spa)
2179 			spa_close(spa, (void *)zdb_read_block);
2180 		return (0);
2181 	}
2182 
2183 	if (dump_opt['C'])
2184 		dump_config(argv[0]);
2185 
2186 	if (strchr(argv[0], '/') != NULL) {
2187 		error = dmu_objset_open(argv[0], DMU_OST_ANY,
2188 		    DS_MODE_STANDARD | DS_MODE_READONLY, &os);
2189 	} else {
2190 		error = spa_open(argv[0], &spa, FTAG);
2191 	}
2192 
2193 	if (error)
2194 		fatal("can't open %s: error %d", argv[0], error);
2195 
2196 	argv++;
2197 	if (--argc > 0) {
2198 		zopt_objects = argc;
2199 		zopt_object = calloc(zopt_objects, sizeof (uint64_t));
2200 		for (i = 0; i < zopt_objects; i++) {
2201 			errno = 0;
2202 			zopt_object[i] = strtoull(argv[i], NULL, 0);
2203 			if (zopt_object[i] == 0 && errno != 0)
2204 				fatal("bad object number %s: %s",
2205 				    argv[i], strerror(errno));
2206 		}
2207 	}
2208 
2209 	if (os != NULL) {
2210 		dump_dir(os);
2211 		dmu_objset_close(os);
2212 	} else {
2213 		dump_zpool(spa);
2214 		spa_close(spa, FTAG);
2215 	}
2216 
2217 	kernel_fini();
2218 
2219 	return (0);
2220 }
2221