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