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