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