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