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