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