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