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