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