xref: /titanic_50/usr/src/cmd/zdb/zdb.c (revision b5d3ab78446c645a1150b57b7a58b535229ee742)
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\tdir_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\tnext_clones_obj = %llu\n",
804 	    (u_longlong_t)ds->ds_next_clones_obj);
805 	(void) printf("\t\tbp = %s\n", blkbuf);
806 }
807 
808 static void
809 dump_bplist(objset_t *mos, uint64_t object, char *name)
810 {
811 	bplist_t bpl = { 0 };
812 	blkptr_t blk, *bp = &blk;
813 	uint64_t itor = 0;
814 	char bytes[6];
815 	char comp[6];
816 	char uncomp[6];
817 
818 	if (dump_opt['d'] < 3)
819 		return;
820 
821 	mutex_init(&bpl.bpl_lock, NULL, MUTEX_DEFAULT, NULL);
822 	VERIFY(0 == bplist_open(&bpl, mos, object));
823 	if (bplist_empty(&bpl)) {
824 		bplist_close(&bpl);
825 		mutex_destroy(&bpl.bpl_lock);
826 		return;
827 	}
828 
829 	nicenum(bpl.bpl_phys->bpl_bytes, bytes);
830 	if (bpl.bpl_dbuf->db_size == sizeof (bplist_phys_t)) {
831 		nicenum(bpl.bpl_phys->bpl_comp, comp);
832 		nicenum(bpl.bpl_phys->bpl_uncomp, uncomp);
833 		(void) printf("\n    %s: %llu entries, %s (%s/%s comp)\n",
834 		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries,
835 		    bytes, comp, uncomp);
836 	} else {
837 		(void) printf("\n    %s: %llu entries, %s\n",
838 		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries, bytes);
839 	}
840 
841 	if (dump_opt['d'] < 5) {
842 		bplist_close(&bpl);
843 		mutex_destroy(&bpl.bpl_lock);
844 		return;
845 	}
846 
847 	(void) printf("\n");
848 
849 	while (bplist_iterate(&bpl, &itor, bp) == 0) {
850 		char blkbuf[BP_SPRINTF_LEN];
851 
852 		ASSERT(bp->blk_birth != 0);
853 		sprintf_blkptr_compact(blkbuf, bp, dump_opt['d'] > 5 ? 1 : 0);
854 		(void) printf("\tItem %3llu: %s\n",
855 		    (u_longlong_t)itor - 1, blkbuf);
856 	}
857 
858 	bplist_close(&bpl);
859 	mutex_destroy(&bpl.bpl_lock);
860 }
861 
862 static avl_tree_t idx_tree;
863 static avl_tree_t domain_tree;
864 static boolean_t fuid_table_loaded;
865 
866 static void
867 fuid_table_destroy()
868 {
869 	if (fuid_table_loaded) {
870 		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
871 		fuid_table_loaded = B_FALSE;
872 	}
873 }
874 
875 /*
876  * print uid or gid information.
877  * For normal POSIX id just the id is printed in decimal format.
878  * For CIFS files with FUID the fuid is printed in hex followed by
879  * the doman-rid string.
880  */
881 static void
882 print_idstr(uint64_t id, const char *id_type)
883 {
884 	if (FUID_INDEX(id)) {
885 		char *domain;
886 
887 		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
888 		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
889 		    (u_longlong_t)id, domain, (int)FUID_RID(id));
890 	} else {
891 		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
892 	}
893 
894 }
895 
896 static void
897 dump_uidgid(objset_t *os, znode_phys_t *zp)
898 {
899 	uint32_t uid_idx, gid_idx;
900 
901 	uid_idx = FUID_INDEX(zp->zp_uid);
902 	gid_idx = FUID_INDEX(zp->zp_gid);
903 
904 	/* Load domain table, if not already loaded */
905 	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
906 		uint64_t fuid_obj;
907 
908 		/* first find the fuid object.  It lives in the master node */
909 		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
910 		    8, 1, &fuid_obj) == 0);
911 		(void) zfs_fuid_table_load(os, fuid_obj,
912 		    &idx_tree, &domain_tree);
913 		fuid_table_loaded = B_TRUE;
914 	}
915 
916 	print_idstr(zp->zp_uid, "uid");
917 	print_idstr(zp->zp_gid, "gid");
918 }
919 
920 /*ARGSUSED*/
921 static void
922 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
923 {
924 	znode_phys_t *zp = data;
925 	time_t z_crtime, z_atime, z_mtime, z_ctime;
926 	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
927 	int error;
928 
929 	ASSERT(size >= sizeof (znode_phys_t));
930 
931 	error = zfs_obj_to_path(os, object, path, sizeof (path));
932 	if (error != 0) {
933 		(void) snprintf(path, sizeof (path), "\?\?\?<object#%llu>",
934 		    (u_longlong_t)object);
935 	}
936 
937 	if (dump_opt['d'] < 3) {
938 		(void) printf("\t%s\n", path);
939 		return;
940 	}
941 
942 	z_crtime = (time_t)zp->zp_crtime[0];
943 	z_atime = (time_t)zp->zp_atime[0];
944 	z_mtime = (time_t)zp->zp_mtime[0];
945 	z_ctime = (time_t)zp->zp_ctime[0];
946 
947 	(void) printf("\tpath	%s\n", path);
948 	dump_uidgid(os, zp);
949 	(void) printf("\tatime	%s", ctime(&z_atime));
950 	(void) printf("\tmtime	%s", ctime(&z_mtime));
951 	(void) printf("\tctime	%s", ctime(&z_ctime));
952 	(void) printf("\tcrtime	%s", ctime(&z_crtime));
953 	(void) printf("\tgen	%llu\n", (u_longlong_t)zp->zp_gen);
954 	(void) printf("\tmode	%llo\n", (u_longlong_t)zp->zp_mode);
955 	(void) printf("\tsize	%llu\n", (u_longlong_t)zp->zp_size);
956 	(void) printf("\tparent	%llu\n", (u_longlong_t)zp->zp_parent);
957 	(void) printf("\tlinks	%llu\n", (u_longlong_t)zp->zp_links);
958 	(void) printf("\txattr	%llu\n", (u_longlong_t)zp->zp_xattr);
959 	(void) printf("\trdev	0x%016llx\n", (u_longlong_t)zp->zp_rdev);
960 }
961 
962 /*ARGSUSED*/
963 static void
964 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
965 {
966 }
967 
968 /*ARGSUSED*/
969 static void
970 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
971 {
972 }
973 
974 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES] = {
975 	dump_none,		/* unallocated			*/
976 	dump_zap,		/* object directory		*/
977 	dump_uint64,		/* object array			*/
978 	dump_none,		/* packed nvlist		*/
979 	dump_packed_nvlist,	/* packed nvlist size		*/
980 	dump_none,		/* bplist			*/
981 	dump_none,		/* bplist header		*/
982 	dump_none,		/* SPA space map header		*/
983 	dump_none,		/* SPA space map		*/
984 	dump_none,		/* ZIL intent log		*/
985 	dump_dnode,		/* DMU dnode			*/
986 	dump_dmu_objset,	/* DMU objset			*/
987 	dump_dsl_dir,		/* DSL directory		*/
988 	dump_zap,		/* DSL directory child map	*/
989 	dump_zap,		/* DSL dataset snap map		*/
990 	dump_zap,		/* DSL props			*/
991 	dump_dsl_dataset,	/* DSL dataset			*/
992 	dump_znode,		/* ZFS znode			*/
993 	dump_acl,		/* ZFS V0 ACL			*/
994 	dump_uint8,		/* ZFS plain file		*/
995 	dump_zpldir,		/* ZFS directory		*/
996 	dump_zap,		/* ZFS master node		*/
997 	dump_zap,		/* ZFS delete queue		*/
998 	dump_uint8,		/* zvol object			*/
999 	dump_zap,		/* zvol prop			*/
1000 	dump_uint8,		/* other uint8[]		*/
1001 	dump_uint64,		/* other uint64[]		*/
1002 	dump_zap,		/* other ZAP			*/
1003 	dump_zap,		/* persistent error log		*/
1004 	dump_uint8,		/* SPA history			*/
1005 	dump_uint64,		/* SPA history offsets		*/
1006 	dump_zap,		/* Pool properties		*/
1007 	dump_zap,		/* DSL permissions		*/
1008 	dump_acl,		/* ZFS ACL			*/
1009 	dump_uint8,		/* ZFS SYSACL			*/
1010 	dump_none,		/* FUID nvlist			*/
1011 	dump_packed_nvlist,	/* FUID nvlist size		*/
1012 	dump_zap,		/* DSL dataset next clones	*/
1013 	dump_zap,		/* DSL scrub queue		*/
1014 };
1015 
1016 static void
1017 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1018 {
1019 	dmu_buf_t *db = NULL;
1020 	dmu_object_info_t doi;
1021 	dnode_t *dn;
1022 	void *bonus = NULL;
1023 	size_t bsize = 0;
1024 	char iblk[6], dblk[6], lsize[6], asize[6], bonus_size[6], segsize[6];
1025 	char aux[50];
1026 	int error;
1027 
1028 	if (*print_header) {
1029 		(void) printf("\n    Object  lvl   iblk   dblk  lsize"
1030 		    "  asize  type\n");
1031 		*print_header = 0;
1032 	}
1033 
1034 	if (object == 0) {
1035 		dn = os->os->os_meta_dnode;
1036 	} else {
1037 		error = dmu_bonus_hold(os, object, FTAG, &db);
1038 		if (error)
1039 			fatal("dmu_bonus_hold(%llu) failed, errno %u",
1040 			    object, error);
1041 		bonus = db->db_data;
1042 		bsize = db->db_size;
1043 		dn = ((dmu_buf_impl_t *)db)->db_dnode;
1044 	}
1045 	dmu_object_info_from_dnode(dn, &doi);
1046 
1047 	nicenum(doi.doi_metadata_block_size, iblk);
1048 	nicenum(doi.doi_data_block_size, dblk);
1049 	nicenum(doi.doi_data_block_size * (doi.doi_max_block_offset + 1),
1050 	    lsize);
1051 	nicenum(doi.doi_physical_blks << 9, asize);
1052 	nicenum(doi.doi_bonus_size, bonus_size);
1053 
1054 	aux[0] = '\0';
1055 
1056 	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1057 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1058 		    zio_checksum_table[doi.doi_checksum].ci_name);
1059 	}
1060 
1061 	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1062 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1063 		    zio_compress_table[doi.doi_compress].ci_name);
1064 	}
1065 
1066 	(void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %s%s\n",
1067 	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk, lsize,
1068 	    asize, dmu_ot[doi.doi_type].ot_name, aux);
1069 
1070 	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1071 		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %s\n",
1072 		    "", "", "", "", bonus_size, "bonus",
1073 		    dmu_ot[doi.doi_bonus_type].ot_name);
1074 	}
1075 
1076 	if (verbosity >= 4) {
1077 		object_viewer[doi.doi_bonus_type](os, object, bonus, bsize);
1078 		object_viewer[doi.doi_type](os, object, NULL, 0);
1079 		*print_header = 1;
1080 	}
1081 
1082 	if (verbosity >= 5)
1083 		dump_indirect(os, object, NULL, 0);
1084 
1085 	if (verbosity >= 5) {
1086 		/*
1087 		 * Report the list of segments that comprise the object.
1088 		 */
1089 		uint64_t start = 0;
1090 		uint64_t end;
1091 		uint64_t blkfill = 1;
1092 		int minlvl = 1;
1093 
1094 		if (dn->dn_type == DMU_OT_DNODE) {
1095 			minlvl = 0;
1096 			blkfill = DNODES_PER_BLOCK;
1097 		}
1098 
1099 		for (;;) {
1100 			error = dnode_next_offset(dn,
1101 			    0, &start, minlvl, blkfill, 0);
1102 			if (error)
1103 				break;
1104 			end = start;
1105 			error = dnode_next_offset(dn,
1106 			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
1107 			nicenum(end - start, segsize);
1108 			(void) printf("\t\tsegment [%016llx, %016llx)"
1109 			    " size %5s\n", (u_longlong_t)start,
1110 			    (u_longlong_t)end, segsize);
1111 			if (error)
1112 				break;
1113 			start = end;
1114 		}
1115 	}
1116 
1117 	if (db != NULL)
1118 		dmu_buf_rele(db, FTAG);
1119 }
1120 
1121 static char *objset_types[DMU_OST_NUMTYPES] = {
1122 	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1123 
1124 static void
1125 dump_dir(objset_t *os)
1126 {
1127 	dmu_objset_stats_t dds;
1128 	uint64_t object, object_count;
1129 	uint64_t refdbytes, usedobjs, scratch;
1130 	char numbuf[8];
1131 	char blkbuf[BP_SPRINTF_LEN];
1132 	char osname[MAXNAMELEN];
1133 	char *type = "UNKNOWN";
1134 	int verbosity = dump_opt['d'];
1135 	int print_header = 1;
1136 	int i, error;
1137 
1138 	dmu_objset_fast_stat(os, &dds);
1139 
1140 	if (dds.dds_type < DMU_OST_NUMTYPES)
1141 		type = objset_types[dds.dds_type];
1142 
1143 	if (dds.dds_type == DMU_OST_META) {
1144 		dds.dds_creation_txg = TXG_INITIAL;
1145 		usedobjs = os->os->os_rootbp->blk_fill;
1146 		refdbytes =
1147 		    os->os->os_spa->spa_dsl_pool->dp_mos_dir->dd_used_bytes;
1148 	} else {
1149 		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
1150 	}
1151 
1152 	ASSERT3U(usedobjs, ==, os->os->os_rootbp->blk_fill);
1153 
1154 	nicenum(refdbytes, numbuf);
1155 
1156 	if (verbosity >= 4) {
1157 		(void) strcpy(blkbuf, ", rootbp ");
1158 		sprintf_blkptr(blkbuf + strlen(blkbuf),
1159 		    BP_SPRINTF_LEN - strlen(blkbuf), os->os->os_rootbp);
1160 	} else {
1161 		blkbuf[0] = '\0';
1162 	}
1163 
1164 	dmu_objset_name(os, osname);
1165 
1166 	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
1167 	    "%s, %llu objects%s\n",
1168 	    osname, type, (u_longlong_t)dmu_objset_id(os),
1169 	    (u_longlong_t)dds.dds_creation_txg,
1170 	    numbuf, (u_longlong_t)usedobjs, blkbuf);
1171 
1172 	dump_intent_log(dmu_objset_zil(os));
1173 
1174 	if (dmu_objset_ds(os) != NULL)
1175 		dump_bplist(dmu_objset_pool(os)->dp_meta_objset,
1176 		    dmu_objset_ds(os)->ds_phys->ds_deadlist_obj, "Deadlist");
1177 
1178 	if (verbosity < 2)
1179 		return;
1180 
1181 	if (os->os->os_rootbp->blk_birth == 0)
1182 		return;
1183 
1184 	if (zopt_objects != 0) {
1185 		for (i = 0; i < zopt_objects; i++)
1186 			dump_object(os, zopt_object[i], verbosity,
1187 			    &print_header);
1188 		(void) printf("\n");
1189 		return;
1190 	}
1191 
1192 	dump_object(os, 0, verbosity, &print_header);
1193 	object_count = 1;
1194 
1195 	object = 0;
1196 	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1197 		dump_object(os, object, verbosity, &print_header);
1198 		object_count++;
1199 	}
1200 
1201 	ASSERT3U(object_count, ==, usedobjs);
1202 
1203 	(void) printf("\n");
1204 
1205 	if (error != ESRCH)
1206 		fatal("dmu_object_next() = %d", error);
1207 }
1208 
1209 static void
1210 dump_uberblock(uberblock_t *ub)
1211 {
1212 	time_t timestamp = ub->ub_timestamp;
1213 
1214 	(void) printf("Uberblock\n\n");
1215 	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
1216 	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
1217 	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
1218 	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
1219 	(void) printf("\ttimestamp = %llu UTC = %s",
1220 	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
1221 	if (dump_opt['u'] >= 3) {
1222 		char blkbuf[BP_SPRINTF_LEN];
1223 		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &ub->ub_rootbp);
1224 		(void) printf("\trootbp = %s\n", blkbuf);
1225 	}
1226 	(void) printf("\n");
1227 }
1228 
1229 static void
1230 dump_config(const char *pool)
1231 {
1232 	spa_t *spa = NULL;
1233 
1234 	mutex_enter(&spa_namespace_lock);
1235 	while ((spa = spa_next(spa)) != NULL) {
1236 		if (pool == NULL)
1237 			(void) printf("%s\n", spa_name(spa));
1238 		if (pool == NULL || strcmp(pool, spa_name(spa)) == 0)
1239 			dump_nvlist(spa->spa_config, 4);
1240 	}
1241 	mutex_exit(&spa_namespace_lock);
1242 }
1243 
1244 static void
1245 dump_cachefile(const char *cachefile)
1246 {
1247 	int fd;
1248 	struct stat64 statbuf;
1249 	char *buf;
1250 	nvlist_t *config;
1251 
1252 	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
1253 		(void) printf("cannot open '%s': %s\n", cachefile,
1254 		    strerror(errno));
1255 		exit(1);
1256 	}
1257 
1258 	if (fstat64(fd, &statbuf) != 0) {
1259 		(void) printf("failed to stat '%s': %s\n", cachefile,
1260 		    strerror(errno));
1261 		exit(1);
1262 	}
1263 
1264 	if ((buf = malloc(statbuf.st_size)) == NULL) {
1265 		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
1266 		    (u_longlong_t)statbuf.st_size);
1267 		exit(1);
1268 	}
1269 
1270 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1271 		(void) fprintf(stderr, "failed to read %llu bytes\n",
1272 		    (u_longlong_t)statbuf.st_size);
1273 		exit(1);
1274 	}
1275 
1276 	(void) close(fd);
1277 
1278 	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
1279 		(void) fprintf(stderr, "failed to unpack nvlist\n");
1280 		exit(1);
1281 	}
1282 
1283 	free(buf);
1284 
1285 	dump_nvlist(config, 0);
1286 
1287 	nvlist_free(config);
1288 }
1289 
1290 static void
1291 dump_label(const char *dev)
1292 {
1293 	int fd;
1294 	vdev_label_t label;
1295 	char *buf = label.vl_vdev_phys.vp_nvlist;
1296 	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1297 	struct stat64 statbuf;
1298 	uint64_t psize;
1299 	int l;
1300 
1301 	if ((fd = open64(dev, O_RDONLY)) < 0) {
1302 		(void) printf("cannot open '%s': %s\n", dev, strerror(errno));
1303 		exit(1);
1304 	}
1305 
1306 	if (fstat64(fd, &statbuf) != 0) {
1307 		(void) printf("failed to stat '%s': %s\n", dev,
1308 		    strerror(errno));
1309 		exit(1);
1310 	}
1311 
1312 	psize = statbuf.st_size;
1313 	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
1314 
1315 	for (l = 0; l < VDEV_LABELS; l++) {
1316 
1317 		nvlist_t *config = NULL;
1318 
1319 		(void) printf("--------------------------------------------\n");
1320 		(void) printf("LABEL %d\n", l);
1321 		(void) printf("--------------------------------------------\n");
1322 
1323 		if (pread64(fd, &label, sizeof (label),
1324 		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
1325 			(void) printf("failed to read label %d\n", l);
1326 			continue;
1327 		}
1328 
1329 		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
1330 			(void) printf("failed to unpack label %d\n", l);
1331 			continue;
1332 		}
1333 		dump_nvlist(config, 4);
1334 		nvlist_free(config);
1335 	}
1336 }
1337 
1338 /*ARGSUSED*/
1339 static int
1340 dump_one_dir(char *dsname, void *arg)
1341 {
1342 	int error;
1343 	objset_t *os;
1344 
1345 	error = dmu_objset_open(dsname, DMU_OST_ANY,
1346 	    DS_MODE_USER | DS_MODE_READONLY, &os);
1347 	if (error) {
1348 		(void) printf("Could not open %s\n", dsname);
1349 		return (0);
1350 	}
1351 	dump_dir(os);
1352 	dmu_objset_close(os);
1353 	fuid_table_destroy();
1354 	return (0);
1355 }
1356 
1357 static void
1358 zdb_space_map_load(spa_t *spa)
1359 {
1360 	vdev_t *rvd = spa->spa_root_vdev;
1361 	vdev_t *vd;
1362 	int c, m, error;
1363 
1364 	for (c = 0; c < rvd->vdev_children; c++) {
1365 		vd = rvd->vdev_child[c];
1366 		for (m = 0; m < vd->vdev_ms_count; m++) {
1367 			metaslab_t *msp = vd->vdev_ms[m];
1368 			mutex_enter(&msp->ms_lock);
1369 			error = space_map_load(&msp->ms_allocmap[0], NULL,
1370 			    SM_ALLOC, &msp->ms_smo, spa->spa_meta_objset);
1371 			mutex_exit(&msp->ms_lock);
1372 			if (error)
1373 				fatal("%s bad space map #%d, error %d",
1374 				    spa->spa_name, c, error);
1375 		}
1376 	}
1377 }
1378 
1379 static int
1380 zdb_space_map_claim(spa_t *spa, blkptr_t *bp, zbookmark_t *zb)
1381 {
1382 	dva_t *dva = bp->blk_dva;
1383 	vdev_t *vd;
1384 	metaslab_t *msp;
1385 	space_map_t *allocmap, *freemap;
1386 	int error;
1387 	int d;
1388 	blkptr_t blk = *bp;
1389 
1390 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1391 		uint64_t vdev = DVA_GET_VDEV(&dva[d]);
1392 		uint64_t offset = DVA_GET_OFFSET(&dva[d]);
1393 		uint64_t size = DVA_GET_ASIZE(&dva[d]);
1394 
1395 		if ((vd = vdev_lookup_top(spa, vdev)) == NULL)
1396 			return (ENXIO);
1397 
1398 		if ((offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
1399 			return (ENXIO);
1400 
1401 		msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
1402 		allocmap = &msp->ms_allocmap[0];
1403 		freemap = &msp->ms_freemap[0];
1404 
1405 		/* Prepare our copy of the bp in case we need to read GBHs */
1406 		if (DVA_GET_GANG(&dva[d])) {
1407 			size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
1408 			DVA_SET_ASIZE(&blk.blk_dva[d], size);
1409 			DVA_SET_GANG(&blk.blk_dva[d], 0);
1410 		}
1411 
1412 		mutex_enter(&msp->ms_lock);
1413 		if (space_map_contains(freemap, offset, size)) {
1414 			mutex_exit(&msp->ms_lock);
1415 			return (EAGAIN);	/* allocated more than once */
1416 		}
1417 
1418 		if (!space_map_contains(allocmap, offset, size)) {
1419 			mutex_exit(&msp->ms_lock);
1420 			return (ESTALE);	/* not allocated at all */
1421 		}
1422 
1423 		space_map_remove(allocmap, offset, size);
1424 		space_map_add(freemap, offset, size);
1425 
1426 		mutex_exit(&msp->ms_lock);
1427 	}
1428 
1429 	if (BP_IS_GANG(bp)) {
1430 		zio_gbh_phys_t gbh;
1431 		int g;
1432 
1433 		/* LINTED - compile time assert */
1434 		ASSERT(sizeof (zio_gbh_phys_t) == SPA_GANGBLOCKSIZE);
1435 
1436 		BP_SET_CHECKSUM(&blk, ZIO_CHECKSUM_GANG_HEADER);
1437 		BP_SET_PSIZE(&blk, SPA_GANGBLOCKSIZE);
1438 		BP_SET_LSIZE(&blk, SPA_GANGBLOCKSIZE);
1439 		BP_SET_COMPRESS(&blk, ZIO_COMPRESS_OFF);
1440 		error = zio_wait(zio_read(NULL, spa, &blk, &gbh,
1441 		    SPA_GANGBLOCKSIZE, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
1442 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_CONFIG_HELD, zb));
1443 		if (error)
1444 			return (error);
1445 		if (BP_SHOULD_BYTESWAP(&blk))
1446 			byteswap_uint64_array(&gbh, SPA_GANGBLOCKSIZE);
1447 		for (g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1448 			if (BP_IS_HOLE(&gbh.zg_blkptr[g]))
1449 				break;
1450 			error = zdb_space_map_claim(spa, &gbh.zg_blkptr[g], zb);
1451 			if (error)
1452 				return (error);
1453 		}
1454 	}
1455 
1456 	return (0);
1457 }
1458 
1459 static void
1460 zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
1461 {
1462 	metaslab_t *msp;
1463 
1464 	/* LINTED */
1465 	msp = (metaslab_t *)((char *)sm - offsetof(metaslab_t, ms_allocmap[0]));
1466 
1467 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
1468 	    (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
1469 	    (u_longlong_t)start,
1470 	    (u_longlong_t)size);
1471 }
1472 
1473 static void
1474 zdb_space_map_unload(spa_t *spa)
1475 {
1476 	vdev_t *rvd = spa->spa_root_vdev;
1477 	vdev_t *vd;
1478 	int c, m;
1479 
1480 	for (c = 0; c < rvd->vdev_children; c++) {
1481 		vd = rvd->vdev_child[c];
1482 		for (m = 0; m < vd->vdev_ms_count; m++) {
1483 			metaslab_t *msp = vd->vdev_ms[m];
1484 			mutex_enter(&msp->ms_lock);
1485 			space_map_vacate(&msp->ms_allocmap[0], zdb_leak,
1486 			    &msp->ms_allocmap[0]);
1487 			space_map_unload(&msp->ms_allocmap[0]);
1488 			space_map_vacate(&msp->ms_freemap[0], NULL, NULL);
1489 			mutex_exit(&msp->ms_lock);
1490 		}
1491 	}
1492 }
1493 
1494 static void
1495 zdb_refresh_ubsync(spa_t *spa)
1496 {
1497 	uberblock_t ub = { 0 };
1498 	vdev_t *rvd = spa->spa_root_vdev;
1499 	zio_t *zio;
1500 
1501 	/*
1502 	 * Reload the uberblock.
1503 	 */
1504 	zio = zio_root(spa, NULL, NULL,
1505 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
1506 	vdev_uberblock_load(zio, rvd, &ub);
1507 	(void) zio_wait(zio);
1508 
1509 	if (ub.ub_txg != 0)
1510 		spa->spa_ubsync = ub;
1511 }
1512 
1513 /*
1514  * Verify that the sum of the sizes of all blocks in the pool adds up
1515  * to the SPA's sa_alloc total.
1516  */
1517 typedef struct zdb_blkstats {
1518 	uint64_t	zb_asize;
1519 	uint64_t	zb_lsize;
1520 	uint64_t	zb_psize;
1521 	uint64_t	zb_count;
1522 } zdb_blkstats_t;
1523 
1524 #define	DMU_OT_DEFERRED	DMU_OT_NONE
1525 #define	DMU_OT_TOTAL	DMU_OT_NUMTYPES
1526 
1527 #define	ZB_TOTAL	ZB_MAXLEVEL
1528 
1529 typedef struct zdb_cb {
1530 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][DMU_OT_TOTAL + 1];
1531 	uint64_t	zcb_errors[256];
1532 	traverse_blk_cache_t *zcb_cache;
1533 	int		zcb_readfails;
1534 	int		zcb_haderrors;
1535 } zdb_cb_t;
1536 
1537 static void
1538 zdb_count_block(spa_t *spa, zdb_cb_t *zcb, blkptr_t *bp, int type)
1539 {
1540 	int i, error;
1541 
1542 	for (i = 0; i < 4; i++) {
1543 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
1544 		int t = (i & 1) ? type : DMU_OT_TOTAL;
1545 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
1546 
1547 		zb->zb_asize += BP_GET_ASIZE(bp);
1548 		zb->zb_lsize += BP_GET_LSIZE(bp);
1549 		zb->zb_psize += BP_GET_PSIZE(bp);
1550 		zb->zb_count++;
1551 	}
1552 
1553 	if (dump_opt['S']) {
1554 		boolean_t print_sig;
1555 
1556 		print_sig  = !zdb_sig_user_data || (BP_GET_LEVEL(bp) == 0 &&
1557 		    BP_GET_TYPE(bp) == DMU_OT_PLAIN_FILE_CONTENTS);
1558 
1559 		if (BP_GET_CHECKSUM(bp) < zdb_sig_cksumalg)
1560 			print_sig = B_FALSE;
1561 
1562 		if (print_sig) {
1563 			(void) printf("%llu\t%lld\t%lld\t%s\t%s\t%s\t"
1564 			    "%llx:%llx:%llx:%llx\n",
1565 			    (u_longlong_t)BP_GET_LEVEL(bp),
1566 			    (longlong_t)BP_GET_PSIZE(bp),
1567 			    (longlong_t)BP_GET_NDVAS(bp),
1568 			    dmu_ot[BP_GET_TYPE(bp)].ot_name,
1569 			    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
1570 			    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name,
1571 			    (u_longlong_t)bp->blk_cksum.zc_word[0],
1572 			    (u_longlong_t)bp->blk_cksum.zc_word[1],
1573 			    (u_longlong_t)bp->blk_cksum.zc_word[2],
1574 			    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1575 		}
1576 	}
1577 
1578 	if (dump_opt['L'])
1579 		return;
1580 
1581 	error = zdb_space_map_claim(spa, bp, &zcb->zcb_cache->bc_bookmark);
1582 
1583 	if (error == 0)
1584 		return;
1585 
1586 	if (error == EAGAIN)
1587 		(void) fatal("double-allocation, bp=%p", bp);
1588 
1589 	if (error == ESTALE)
1590 		(void) fatal("reference to freed block, bp=%p", bp);
1591 
1592 	(void) fatal("fatal error %d in bp %p", error, bp);
1593 }
1594 
1595 static int
1596 zdb_blkptr_cb(traverse_blk_cache_t *bc, spa_t *spa, void *arg)
1597 {
1598 	zbookmark_t *zb = &bc->bc_bookmark;
1599 	zdb_cb_t *zcb = arg;
1600 	blkptr_t *bp = &bc->bc_blkptr;
1601 	dmu_object_type_t type = BP_GET_TYPE(bp);
1602 	char blkbuf[BP_SPRINTF_LEN];
1603 	int error = 0;
1604 
1605 	if (bc->bc_errno) {
1606 		if (zcb->zcb_readfails++ < 10 && dump_opt['L']) {
1607 			zdb_refresh_ubsync(spa);
1608 			error = EAGAIN;
1609 		} else {
1610 			zcb->zcb_haderrors = 1;
1611 			zcb->zcb_errors[bc->bc_errno]++;
1612 			error = ERESTART;
1613 		}
1614 
1615 		if (dump_opt['b'] >= 3 || (dump_opt['b'] >= 2 && bc->bc_errno))
1616 			sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1617 		else
1618 			blkbuf[0] = '\0';
1619 
1620 		if (!dump_opt['S']) {
1621 			(void) printf("zdb_blkptr_cb: Got error %d reading "
1622 			    "<%llu, %llu, %lld, %llx> %s -- %s\n",
1623 			    bc->bc_errno,
1624 			    (u_longlong_t)zb->zb_objset,
1625 			    (u_longlong_t)zb->zb_object,
1626 			    (u_longlong_t)zb->zb_level,
1627 			    (u_longlong_t)zb->zb_blkid,
1628 			    blkbuf,
1629 			    error == EAGAIN ? "retrying" : "skipping");
1630 		}
1631 
1632 		return (error);
1633 	}
1634 
1635 	zcb->zcb_readfails = 0;
1636 
1637 	ASSERT(!BP_IS_HOLE(bp));
1638 
1639 	if (dump_opt['b'] >= 4) {
1640 		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1641 		(void) printf("objset %llu object %llu offset 0x%llx %s\n",
1642 		    (u_longlong_t)zb->zb_objset,
1643 		    (u_longlong_t)zb->zb_object,
1644 		    (u_longlong_t)blkid2offset(bc->bc_dnode,
1645 		    zb->zb_level, zb->zb_blkid), blkbuf);
1646 	}
1647 
1648 	zdb_count_block(spa, zcb, bp, type);
1649 
1650 	return (0);
1651 }
1652 
1653 static int
1654 dump_block_stats(spa_t *spa)
1655 {
1656 	traverse_handle_t *th;
1657 	zdb_cb_t zcb = { 0 };
1658 	traverse_blk_cache_t dummy_cache = { 0 };
1659 	zdb_blkstats_t *zb, *tzb;
1660 	uint64_t alloc, space, logalloc;
1661 	vdev_t *rvd = spa->spa_root_vdev;
1662 	int leaks = 0;
1663 	int advance = zdb_advance;
1664 	int c, e, flags;
1665 
1666 	zcb.zcb_cache = &dummy_cache;
1667 
1668 	if (dump_opt['c'] || dump_opt['S'])
1669 		advance |= ADVANCE_DATA;
1670 
1671 	advance |= ADVANCE_PRUNE | ADVANCE_ZIL;
1672 
1673 	if (!dump_opt['S']) {
1674 		(void) printf("\nTraversing all blocks to %sverify"
1675 		    " nothing leaked ...\n",
1676 		    dump_opt['c'] ? "verify checksums and " : "");
1677 	}
1678 
1679 	/*
1680 	 * Load all space maps.  As we traverse the pool, if we find a block
1681 	 * that's not in its space map, that indicates a double-allocation,
1682 	 * reference to a freed block, or an unclaimed block.  Otherwise we
1683 	 * remove the block from the space map.  If the space maps are not
1684 	 * empty when we're done, that indicates leaked blocks.
1685 	 */
1686 	if (!dump_opt['L'])
1687 		zdb_space_map_load(spa);
1688 
1689 	/*
1690 	 * If there's a deferred-free bplist, process that first.
1691 	 */
1692 	if (spa->spa_sync_bplist_obj != 0) {
1693 		bplist_t *bpl = &spa->spa_sync_bplist;
1694 		blkptr_t blk;
1695 		uint64_t itor = 0;
1696 
1697 		VERIFY(0 == bplist_open(bpl, spa->spa_meta_objset,
1698 		    spa->spa_sync_bplist_obj));
1699 
1700 		while (bplist_iterate(bpl, &itor, &blk) == 0) {
1701 			if (dump_opt['b'] >= 4) {
1702 				char blkbuf[BP_SPRINTF_LEN];
1703 				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &blk);
1704 				(void) printf("[%s] %s\n",
1705 				    "deferred free", blkbuf);
1706 			}
1707 			zdb_count_block(spa, &zcb, &blk, DMU_OT_DEFERRED);
1708 		}
1709 
1710 		bplist_close(bpl);
1711 	}
1712 
1713 	/*
1714 	 * Now traverse the pool.  If we're reading all data to verify
1715 	 * checksums, do a scrubbing read so that we validate all copies.
1716 	 */
1717 	flags = ZIO_FLAG_CANFAIL;
1718 	if (advance & ADVANCE_DATA)
1719 		flags |= ZIO_FLAG_SCRUB;
1720 	th = traverse_init(spa, zdb_blkptr_cb, &zcb, advance, flags);
1721 	th->th_noread = zdb_noread;
1722 
1723 	traverse_add_pool(th, 0, spa_first_txg(spa) + TXG_CONCURRENT_STATES);
1724 
1725 	while (traverse_more(th) == EAGAIN)
1726 		continue;
1727 
1728 	traverse_fini(th);
1729 
1730 	if (zcb.zcb_haderrors && !dump_opt['S']) {
1731 		(void) printf("\nError counts:\n\n");
1732 		(void) printf("\t%5s  %s\n", "errno", "count");
1733 		for (e = 0; e < 256; e++) {
1734 			if (zcb.zcb_errors[e] != 0) {
1735 				(void) printf("\t%5d  %llu\n",
1736 				    e, (u_longlong_t)zcb.zcb_errors[e]);
1737 			}
1738 		}
1739 	}
1740 
1741 	/*
1742 	 * Report any leaked segments.
1743 	 */
1744 	if (!dump_opt['L'])
1745 		zdb_space_map_unload(spa);
1746 
1747 	/*
1748 	 * If we're interested in printing out the blkptr signatures,
1749 	 * return now as we don't print out anything else (including
1750 	 * errors and leaks).
1751 	 */
1752 	if (dump_opt['S'])
1753 		return (zcb.zcb_haderrors ? 3 : 0);
1754 
1755 	if (dump_opt['L'])
1756 		(void) printf("\n\n *** Live pool traversal; "
1757 		    "block counts are only approximate ***\n\n");
1758 
1759 	alloc = spa_get_alloc(spa);
1760 	space = spa_get_space(spa);
1761 
1762 	/*
1763 	 * Log blocks allocated from a separate log device don't count
1764 	 * as part of the normal pool space; factor them in here.
1765 	 */
1766 	logalloc = 0;
1767 
1768 	for (c = 0; c < rvd->vdev_children; c++)
1769 		if (rvd->vdev_child[c]->vdev_islog)
1770 			logalloc += rvd->vdev_child[c]->vdev_stat.vs_alloc;
1771 
1772 	tzb = &zcb.zcb_type[ZB_TOTAL][DMU_OT_TOTAL];
1773 
1774 	if (tzb->zb_asize == alloc + logalloc) {
1775 		(void) printf("\n\tNo leaks (block sum matches space"
1776 		    " maps exactly)\n");
1777 	} else {
1778 		(void) printf("block traversal size %llu != alloc %llu "
1779 		    "(leaked %lld)\n",
1780 		    (u_longlong_t)tzb->zb_asize,
1781 		    (u_longlong_t)alloc + logalloc,
1782 		    (u_longlong_t)(alloc + logalloc - tzb->zb_asize));
1783 		leaks = 1;
1784 	}
1785 
1786 	if (tzb->zb_count == 0)
1787 		return (2);
1788 
1789 	(void) printf("\n");
1790 	(void) printf("\tbp count:      %10llu\n",
1791 	    (u_longlong_t)tzb->zb_count);
1792 	(void) printf("\tbp logical:    %10llu\t avg: %6llu\n",
1793 	    (u_longlong_t)tzb->zb_lsize,
1794 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
1795 	(void) printf("\tbp physical:   %10llu\t avg:"
1796 	    " %6llu\tcompression: %6.2f\n",
1797 	    (u_longlong_t)tzb->zb_psize,
1798 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
1799 	    (double)tzb->zb_lsize / tzb->zb_psize);
1800 	(void) printf("\tbp allocated:  %10llu\t avg:"
1801 	    " %6llu\tcompression: %6.2f\n",
1802 	    (u_longlong_t)tzb->zb_asize,
1803 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
1804 	    (double)tzb->zb_lsize / tzb->zb_asize);
1805 	(void) printf("\tSPA allocated: %10llu\tused: %5.2f%%\n",
1806 	    (u_longlong_t)alloc, 100.0 * alloc / space);
1807 
1808 	if (dump_opt['b'] >= 2) {
1809 		int l, t, level;
1810 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
1811 		    "\t  avg\t comp\t%%Total\tType\n");
1812 
1813 		for (t = 0; t <= DMU_OT_NUMTYPES; t++) {
1814 			char csize[6], lsize[6], psize[6], asize[6], avg[6];
1815 			char *typename;
1816 
1817 			typename = t == DMU_OT_DEFERRED ? "deferred free" :
1818 			    t == DMU_OT_TOTAL ? "Total" : dmu_ot[t].ot_name;
1819 
1820 			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
1821 				(void) printf("%6s\t%5s\t%5s\t%5s"
1822 				    "\t%5s\t%5s\t%6s\t%s\n",
1823 				    "-",
1824 				    "-",
1825 				    "-",
1826 				    "-",
1827 				    "-",
1828 				    "-",
1829 				    "-",
1830 				    typename);
1831 				continue;
1832 			}
1833 
1834 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
1835 				level = (l == -1 ? ZB_TOTAL : l);
1836 				zb = &zcb.zcb_type[level][t];
1837 
1838 				if (zb->zb_asize == 0)
1839 					continue;
1840 
1841 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
1842 					continue;
1843 
1844 				if (level == 0 && zb->zb_asize ==
1845 				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
1846 					continue;
1847 
1848 				nicenum(zb->zb_count, csize);
1849 				nicenum(zb->zb_lsize, lsize);
1850 				nicenum(zb->zb_psize, psize);
1851 				nicenum(zb->zb_asize, asize);
1852 				nicenum(zb->zb_asize / zb->zb_count, avg);
1853 
1854 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
1855 				    "\t%5.2f\t%6.2f\t",
1856 				    csize, lsize, psize, asize, avg,
1857 				    (double)zb->zb_lsize / zb->zb_psize,
1858 				    100.0 * zb->zb_asize / tzb->zb_asize);
1859 
1860 				if (level == ZB_TOTAL)
1861 					(void) printf("%s\n", typename);
1862 				else
1863 					(void) printf("    L%d %s\n",
1864 					    level, typename);
1865 			}
1866 		}
1867 	}
1868 
1869 	(void) printf("\n");
1870 
1871 	if (leaks)
1872 		return (2);
1873 
1874 	if (zcb.zcb_haderrors)
1875 		return (3);
1876 
1877 	return (0);
1878 }
1879 
1880 static void
1881 dump_zpool(spa_t *spa)
1882 {
1883 	dsl_pool_t *dp = spa_get_dsl(spa);
1884 	int rc = 0;
1885 
1886 	spa_config_enter(spa, RW_READER, FTAG);
1887 
1888 	if (dump_opt['u'])
1889 		dump_uberblock(&spa->spa_uberblock);
1890 
1891 	if (dump_opt['d'] || dump_opt['i']) {
1892 		dump_dir(dp->dp_meta_objset);
1893 		if (dump_opt['d'] >= 3) {
1894 			dump_bplist(dp->dp_meta_objset,
1895 			    spa->spa_sync_bplist_obj, "Deferred frees");
1896 			dump_dtl(spa->spa_root_vdev, 0);
1897 			dump_metaslabs(spa);
1898 		}
1899 		(void) dmu_objset_find(spa->spa_name, dump_one_dir, NULL,
1900 		    DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
1901 	}
1902 
1903 	if (dump_opt['b'] || dump_opt['c'] || dump_opt['S'])
1904 		rc = dump_block_stats(spa);
1905 
1906 	if (dump_opt['s'])
1907 		show_pool_stats(spa);
1908 
1909 	spa_config_exit(spa, FTAG);
1910 
1911 	if (rc != 0)
1912 		exit(rc);
1913 }
1914 
1915 #define	ZDB_FLAG_CHECKSUM	0x0001
1916 #define	ZDB_FLAG_DECOMPRESS	0x0002
1917 #define	ZDB_FLAG_BSWAP		0x0004
1918 #define	ZDB_FLAG_GBH		0x0008
1919 #define	ZDB_FLAG_INDIRECT	0x0010
1920 #define	ZDB_FLAG_PHYS		0x0020
1921 #define	ZDB_FLAG_RAW		0x0040
1922 #define	ZDB_FLAG_PRINT_BLKPTR	0x0080
1923 
1924 int flagbits[256];
1925 
1926 static void
1927 zdb_print_blkptr(blkptr_t *bp, int flags)
1928 {
1929 	dva_t *dva = bp->blk_dva;
1930 	int d;
1931 
1932 	if (flags & ZDB_FLAG_BSWAP)
1933 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
1934 	/*
1935 	 * Super-ick warning:  This code is also duplicated in
1936 	 * cmd/mdb/common/modules/zfs/zfs.c .  Yeah, I hate code
1937 	 * replication, too.
1938 	 */
1939 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1940 		(void) printf("\tDVA[%d]: vdev_id %lld / %llx\n", d,
1941 		    (longlong_t)DVA_GET_VDEV(&dva[d]),
1942 		    (longlong_t)DVA_GET_OFFSET(&dva[d]));
1943 		(void) printf("\tDVA[%d]:       GANG: %-5s  GRID:  %04llx\t"
1944 		    "ASIZE: %llx\n", d,
1945 		    DVA_GET_GANG(&dva[d]) ? "TRUE" : "FALSE",
1946 		    (longlong_t)DVA_GET_GRID(&dva[d]),
1947 		    (longlong_t)DVA_GET_ASIZE(&dva[d]));
1948 		(void) printf("\tDVA[%d]: :%llu:%llx:%llx:%s%s%s%s\n", d,
1949 		    (u_longlong_t)DVA_GET_VDEV(&dva[d]),
1950 		    (longlong_t)DVA_GET_OFFSET(&dva[d]),
1951 		    (longlong_t)BP_GET_PSIZE(bp),
1952 		    BP_SHOULD_BYTESWAP(bp) ? "e" : "",
1953 		    !DVA_GET_GANG(&dva[d]) && BP_GET_LEVEL(bp) != 0 ?
1954 		    "d" : "",
1955 		    DVA_GET_GANG(&dva[d]) ? "g" : "",
1956 		    BP_GET_COMPRESS(bp) != 0 ? "d" : "");
1957 	}
1958 	(void) printf("\tLSIZE:  %-16llx\t\tPSIZE: %llx\n",
1959 	    (longlong_t)BP_GET_LSIZE(bp), (longlong_t)BP_GET_PSIZE(bp));
1960 	(void) printf("\tENDIAN: %6s\t\t\t\t\tTYPE:  %s\n",
1961 	    BP_GET_BYTEORDER(bp) ? "LITTLE" : "BIG",
1962 	    dmu_ot[BP_GET_TYPE(bp)].ot_name);
1963 	(void) printf("\tBIRTH:  %-16llx   LEVEL: %-2llu\tFILL:  %llx\n",
1964 	    (u_longlong_t)bp->blk_birth, (u_longlong_t)BP_GET_LEVEL(bp),
1965 	    (u_longlong_t)bp->blk_fill);
1966 	(void) printf("\tCKFUNC: %-16s\t\tCOMP:  %s\n",
1967 	    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
1968 	    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name);
1969 	(void) printf("\tCKSUM:  %llx:%llx:%llx:%llx\n",
1970 	    (u_longlong_t)bp->blk_cksum.zc_word[0],
1971 	    (u_longlong_t)bp->blk_cksum.zc_word[1],
1972 	    (u_longlong_t)bp->blk_cksum.zc_word[2],
1973 	    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1974 }
1975 
1976 static void
1977 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
1978 {
1979 	int i;
1980 
1981 	for (i = 0; i < nbps; i++)
1982 		zdb_print_blkptr(&bp[i], flags);
1983 }
1984 
1985 static void
1986 zdb_dump_gbh(void *buf, int flags)
1987 {
1988 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
1989 }
1990 
1991 static void
1992 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
1993 {
1994 	if (flags & ZDB_FLAG_BSWAP)
1995 		byteswap_uint64_array(buf, size);
1996 	(void) write(2, buf, size);
1997 }
1998 
1999 static void
2000 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
2001 {
2002 	uint64_t *d = (uint64_t *)buf;
2003 	int nwords = size / sizeof (uint64_t);
2004 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
2005 	int i, j;
2006 	char *hdr, *c;
2007 
2008 
2009 	if (do_bswap)
2010 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
2011 	else
2012 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
2013 
2014 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
2015 
2016 	for (i = 0; i < nwords; i += 2) {
2017 		(void) printf("%06llx:  %016llx  %016llx  ",
2018 		    (u_longlong_t)(i * sizeof (uint64_t)),
2019 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
2020 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
2021 
2022 		c = (char *)&d[i];
2023 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
2024 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
2025 		(void) printf("\n");
2026 	}
2027 }
2028 
2029 /*
2030  * There are two acceptable formats:
2031  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
2032  *	child[.child]*    - For example: 0.1.1
2033  *
2034  * The second form can be used to specify arbitrary vdevs anywhere
2035  * in the heirarchy.  For example, in a pool with a mirror of
2036  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
2037  */
2038 static vdev_t *
2039 zdb_vdev_lookup(vdev_t *vdev, char *path)
2040 {
2041 	char *s, *p, *q;
2042 	int i;
2043 
2044 	if (vdev == NULL)
2045 		return (NULL);
2046 
2047 	/* First, assume the x.x.x.x format */
2048 	i = (int)strtoul(path, &s, 10);
2049 	if (s == path || (s && *s != '.' && *s != '\0'))
2050 		goto name;
2051 	if (i < 0 || i >= vdev->vdev_children)
2052 		return (NULL);
2053 
2054 	vdev = vdev->vdev_child[i];
2055 	if (*s == '\0')
2056 		return (vdev);
2057 	return (zdb_vdev_lookup(vdev, s+1));
2058 
2059 name:
2060 	for (i = 0; i < vdev->vdev_children; i++) {
2061 		vdev_t *vc = vdev->vdev_child[i];
2062 
2063 		if (vc->vdev_path == NULL) {
2064 			vc = zdb_vdev_lookup(vc, path);
2065 			if (vc == NULL)
2066 				continue;
2067 			else
2068 				return (vc);
2069 		}
2070 
2071 		p = strrchr(vc->vdev_path, '/');
2072 		p = p ? p + 1 : vc->vdev_path;
2073 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2074 
2075 		if (strcmp(vc->vdev_path, path) == 0)
2076 			return (vc);
2077 		if (strcmp(p, path) == 0)
2078 			return (vc);
2079 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2080 			return (vc);
2081 	}
2082 
2083 	return (NULL);
2084 }
2085 
2086 /*
2087  * Read a block from a pool and print it out.  The syntax of the
2088  * block descriptor is:
2089  *
2090  *	pool:vdev_specifier:offset:size[:flags]
2091  *
2092  *	pool           - The name of the pool you wish to read from
2093  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2094  *	offset         - offset, in hex, in bytes
2095  *	size           - Amount of data to read, in hex, in bytes
2096  *	flags          - A string of characters specifying options
2097  *		 b: Decode a blkptr at given offset within block
2098  *		*c: Calculate and display checksums
2099  *		*d: Decompress data before dumping
2100  *		 e: Byteswap data before dumping
2101  *		*g: Display data as a gang block header
2102  *		*i: Display as an indirect block
2103  *		 p: Do I/O to physical offset
2104  *		 r: Dump raw data to stdout
2105  *
2106  *              * = not yet implemented
2107  */
2108 static void
2109 zdb_read_block(char *thing, spa_t **spap)
2110 {
2111 	spa_t *spa = *spap;
2112 	int flags = 0;
2113 	uint64_t offset = 0, size = 0, blkptr_offset = 0;
2114 	zio_t *zio;
2115 	vdev_t *vd;
2116 	void *buf;
2117 	char *s, *p, *dup, *spa_name, *vdev, *flagstr;
2118 	int i, error, zio_flags;
2119 
2120 	dup = strdup(thing);
2121 	s = strtok(dup, ":");
2122 	spa_name = s ? s : "";
2123 	s = strtok(NULL, ":");
2124 	vdev = s ? s : "";
2125 	s = strtok(NULL, ":");
2126 	offset = strtoull(s ? s : "", NULL, 16);
2127 	s = strtok(NULL, ":");
2128 	size = strtoull(s ? s : "", NULL, 16);
2129 	s = strtok(NULL, ":");
2130 	flagstr = s ? s : "";
2131 
2132 	s = NULL;
2133 	if (size == 0)
2134 		s = "size must not be zero";
2135 	if (!IS_P2ALIGNED(size, DEV_BSIZE))
2136 		s = "size must be a multiple of sector size";
2137 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
2138 		s = "offset must be a multiple of sector size";
2139 	if (s) {
2140 		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
2141 		free(dup);
2142 		return;
2143 	}
2144 
2145 	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
2146 		for (i = 0; flagstr[i]; i++) {
2147 			int bit = flagbits[(uchar_t)flagstr[i]];
2148 
2149 			if (bit == 0) {
2150 				(void) printf("***Invalid flag: %c\n",
2151 				    flagstr[i]);
2152 				continue;
2153 			}
2154 			flags |= bit;
2155 
2156 			/* If it's not something with an argument, keep going */
2157 			if ((bit & (ZDB_FLAG_CHECKSUM | ZDB_FLAG_DECOMPRESS |
2158 			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
2159 				continue;
2160 
2161 			p = &flagstr[i + 1];
2162 			if (bit == ZDB_FLAG_PRINT_BLKPTR)
2163 				blkptr_offset = strtoull(p, &p, 16);
2164 			if (*p != ':' && *p != '\0') {
2165 				(void) printf("***Invalid flag arg: '%s'\n", s);
2166 				free(dup);
2167 				return;
2168 			}
2169 		}
2170 	}
2171 
2172 	if (spa == NULL || spa->spa_name == NULL ||
2173 	    strcmp(spa->spa_name, spa_name)) {
2174 		if (spa && spa->spa_name)
2175 			spa_close(spa, (void *)zdb_read_block);
2176 		error = spa_open(spa_name, spap, (void *)zdb_read_block);
2177 		if (error)
2178 			fatal("Failed to open pool '%s': %s",
2179 			    spa_name, strerror(error));
2180 		spa = *spap;
2181 	}
2182 
2183 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2184 	if (vd == NULL) {
2185 		(void) printf("***Invalid vdev: %s\n", vdev);
2186 		free(dup);
2187 		return;
2188 	} else {
2189 		if (vd->vdev_path)
2190 			(void) printf("Found vdev: %s\n", vd->vdev_path);
2191 		else
2192 			(void) printf("Found vdev type: %s\n",
2193 			    vd->vdev_ops->vdev_op_type);
2194 	}
2195 
2196 	buf = umem_alloc(size, UMEM_NOFAIL);
2197 
2198 	zio_flags = ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2199 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY | ZIO_FLAG_NOBOOKMARK;
2200 
2201 	if (flags & ZDB_FLAG_PHYS)
2202 		zio_flags |= ZIO_FLAG_PHYSICAL;
2203 
2204 	zio = zio_root(spa, NULL, NULL, 0);
2205 	/* XXX todo - cons up a BP so RAID-Z will be happy */
2206 	zio_nowait(zio_vdev_child_io(zio, NULL, vd, offset, buf, size,
2207 	    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ, zio_flags, NULL, NULL));
2208 	error = zio_wait(zio);
2209 
2210 	if (error) {
2211 		(void) printf("Read of %s failed, error: %d\n", thing, error);
2212 		goto out;
2213 	}
2214 
2215 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2216 		zdb_print_blkptr((blkptr_t *)(void *)
2217 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2218 	else if (flags & ZDB_FLAG_RAW)
2219 		zdb_dump_block_raw(buf, size, flags);
2220 	else if (flags & ZDB_FLAG_INDIRECT)
2221 		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2222 		    flags);
2223 	else if (flags & ZDB_FLAG_GBH)
2224 		zdb_dump_gbh(buf, flags);
2225 	else
2226 		zdb_dump_block(thing, buf, size, flags);
2227 
2228 out:
2229 	umem_free(buf, size);
2230 	free(dup);
2231 }
2232 
2233 static boolean_t
2234 nvlist_string_match(nvlist_t *config, char *name, char *tgt)
2235 {
2236 	char *s;
2237 
2238 	if (nvlist_lookup_string(config, name, &s) != 0)
2239 		return (B_FALSE);
2240 
2241 	return (strcmp(s, tgt) == 0);
2242 }
2243 
2244 static boolean_t
2245 nvlist_uint64_match(nvlist_t *config, char *name, uint64_t tgt)
2246 {
2247 	uint64_t val;
2248 
2249 	if (nvlist_lookup_uint64(config, name, &val) != 0)
2250 		return (B_FALSE);
2251 
2252 	return (val == tgt);
2253 }
2254 
2255 static boolean_t
2256 vdev_child_guid_match(nvlist_t *vdev, uint64_t guid)
2257 {
2258 	nvlist_t **child;
2259 	uint_t c, children;
2260 
2261 	verify(nvlist_lookup_nvlist_array(vdev, ZPOOL_CONFIG_CHILDREN,
2262 	    &child, &children) == 0);
2263 	for (c = 0; c < children; ++c)
2264 		if (nvlist_uint64_match(child[c], ZPOOL_CONFIG_GUID, guid))
2265 			return (B_TRUE);
2266 	return (B_FALSE);
2267 }
2268 
2269 static boolean_t
2270 vdev_child_string_match(nvlist_t *vdev, char *tgt)
2271 {
2272 	nvlist_t **child;
2273 	uint_t c, children;
2274 
2275 	verify(nvlist_lookup_nvlist_array(vdev, ZPOOL_CONFIG_CHILDREN,
2276 	    &child, &children) == 0);
2277 	for (c = 0; c < children; ++c) {
2278 		if (nvlist_string_match(child[c], ZPOOL_CONFIG_PATH, tgt) ||
2279 		    nvlist_string_match(child[c], ZPOOL_CONFIG_DEVID, tgt))
2280 			return (B_TRUE);
2281 	}
2282 	return (B_FALSE);
2283 }
2284 
2285 static boolean_t
2286 vdev_guid_match(nvlist_t *config, uint64_t guid)
2287 {
2288 	nvlist_t *nvroot;
2289 
2290 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2291 	    &nvroot) == 0);
2292 
2293 	return (nvlist_uint64_match(nvroot, ZPOOL_CONFIG_GUID, guid) ||
2294 	    vdev_child_guid_match(nvroot, guid));
2295 }
2296 
2297 static boolean_t
2298 vdev_string_match(nvlist_t *config, char *tgt)
2299 {
2300 	nvlist_t *nvroot;
2301 
2302 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2303 	    &nvroot) == 0);
2304 
2305 	return (vdev_child_string_match(nvroot, tgt));
2306 }
2307 
2308 static boolean_t
2309 pool_match(nvlist_t *config, char *tgt)
2310 {
2311 	uint64_t guid = strtoull(tgt, NULL, 0);
2312 
2313 	if (guid != 0) {
2314 		return (
2315 		    nvlist_uint64_match(config, ZPOOL_CONFIG_POOL_GUID, guid) ||
2316 		    vdev_guid_match(config, guid));
2317 	} else {
2318 		return (
2319 		    nvlist_string_match(config, ZPOOL_CONFIG_POOL_NAME, tgt) ||
2320 		    vdev_string_match(config, tgt));
2321 	}
2322 }
2323 
2324 static int
2325 find_exported_zpool(char *pool_id, nvlist_t **configp, char *vdev_dir)
2326 {
2327 	nvlist_t *pools;
2328 	int error = ENOENT;
2329 	nvlist_t *match = NULL;
2330 
2331 	if (vdev_dir != NULL)
2332 		pools = zpool_find_import_activeok(g_zfs, 1, &vdev_dir);
2333 	else
2334 		pools = zpool_find_import_activeok(g_zfs, 0, NULL);
2335 
2336 	if (pools != NULL) {
2337 		nvpair_t *elem = NULL;
2338 
2339 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2340 			verify(nvpair_value_nvlist(elem, configp) == 0);
2341 			if (pool_match(*configp, pool_id)) {
2342 				if (match != NULL) {
2343 					(void) fatal(
2344 					    "More than one matching pool - "
2345 					    "specify guid/devid/device path.");
2346 				} else {
2347 					match = *configp;
2348 					error = 0;
2349 				}
2350 			}
2351 		}
2352 	}
2353 
2354 	*configp = error ? NULL : match;
2355 
2356 	return (error);
2357 }
2358 
2359 int
2360 main(int argc, char **argv)
2361 {
2362 	int i, c;
2363 	struct rlimit rl = { 1024, 1024 };
2364 	spa_t *spa;
2365 	objset_t *os = NULL;
2366 	char *endstr;
2367 	int dump_all = 1;
2368 	int verbose = 0;
2369 	int error;
2370 	int flag, set;
2371 	int exported = 0;
2372 	char *vdev_dir = NULL;
2373 
2374 	(void) setrlimit(RLIMIT_NOFILE, &rl);
2375 	(void) enable_extended_FILE_stdio(-1, -1);
2376 
2377 	dprintf_setup(&argc, argv);
2378 
2379 	while ((c = getopt(argc, argv, "udibcsvCLO:B:S:U:lRep:")) != -1) {
2380 		switch (c) {
2381 		case 'u':
2382 		case 'd':
2383 		case 'i':
2384 		case 'b':
2385 		case 'c':
2386 		case 's':
2387 		case 'C':
2388 		case 'l':
2389 		case 'R':
2390 			dump_opt[c]++;
2391 			dump_all = 0;
2392 			break;
2393 		case 'L':
2394 			dump_opt[c]++;
2395 			break;
2396 		case 'O':
2397 			endstr = optarg;
2398 			if (endstr[0] == '!') {
2399 				endstr++;
2400 				set = 0;
2401 			} else {
2402 				set = 1;
2403 			}
2404 			if (strcmp(endstr, "post") == 0) {
2405 				flag = ADVANCE_PRE;
2406 				set = !set;
2407 			} else if (strcmp(endstr, "pre") == 0) {
2408 				flag = ADVANCE_PRE;
2409 			} else if (strcmp(endstr, "prune") == 0) {
2410 				flag = ADVANCE_PRUNE;
2411 			} else if (strcmp(endstr, "data") == 0) {
2412 				flag = ADVANCE_DATA;
2413 			} else if (strcmp(endstr, "holes") == 0) {
2414 				flag = ADVANCE_HOLES;
2415 			} else {
2416 				usage();
2417 			}
2418 			if (set)
2419 				zdb_advance |= flag;
2420 			else
2421 				zdb_advance &= ~flag;
2422 			break;
2423 		case 'B':
2424 			endstr = optarg - 1;
2425 			zdb_noread.zb_objset = strtoull(endstr + 1, &endstr, 0);
2426 			zdb_noread.zb_object = strtoull(endstr + 1, &endstr, 0);
2427 			zdb_noread.zb_level = strtol(endstr + 1, &endstr, 0);
2428 			zdb_noread.zb_blkid = strtoull(endstr + 1, &endstr, 16);
2429 			(void) printf("simulating bad block "
2430 			    "<%llu, %llu, %lld, %llx>\n",
2431 			    (u_longlong_t)zdb_noread.zb_objset,
2432 			    (u_longlong_t)zdb_noread.zb_object,
2433 			    (u_longlong_t)zdb_noread.zb_level,
2434 			    (u_longlong_t)zdb_noread.zb_blkid);
2435 			break;
2436 		case 'v':
2437 			verbose++;
2438 			break;
2439 		case 'U':
2440 			spa_config_path = optarg;
2441 			break;
2442 		case 'e':
2443 			exported = 1;
2444 			break;
2445 		case 'p':
2446 			vdev_dir = optarg;
2447 			break;
2448 		case 'S':
2449 			dump_opt[c]++;
2450 			dump_all = 0;
2451 			zdb_sig_user_data = (strncmp(optarg, "user:", 5) == 0);
2452 			if (!zdb_sig_user_data && strncmp(optarg, "all:", 4))
2453 				usage();
2454 			endstr = strchr(optarg, ':') + 1;
2455 			if (strcmp(endstr, "fletcher2") == 0)
2456 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_2;
2457 			else if (strcmp(endstr, "fletcher4") == 0)
2458 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_4;
2459 			else if (strcmp(endstr, "sha256") == 0)
2460 				zdb_sig_cksumalg = ZIO_CHECKSUM_SHA256;
2461 			else if (strcmp(endstr, "all") == 0)
2462 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_2;
2463 			else
2464 				usage();
2465 			break;
2466 		default:
2467 			usage();
2468 			break;
2469 		}
2470 	}
2471 
2472 	if (vdev_dir != NULL && exported == 0)
2473 		(void) fatal("-p option requires use of -e\n");
2474 
2475 	kernel_init(FREAD);
2476 	g_zfs = libzfs_init();
2477 	ASSERT(g_zfs != NULL);
2478 
2479 	/*
2480 	 * Disable vdev caching.  If we don't do this, live pool traversal
2481 	 * won't make progress because it will never see disk updates.
2482 	 */
2483 	zfs_vdev_cache_size = 0;
2484 
2485 	for (c = 0; c < 256; c++) {
2486 		if (dump_all && c != 'L' && c != 'l' && c != 'R')
2487 			dump_opt[c] = 1;
2488 		if (dump_opt[c])
2489 			dump_opt[c] += verbose;
2490 	}
2491 
2492 	argc -= optind;
2493 	argv += optind;
2494 
2495 	if (argc < 1) {
2496 		if (dump_opt['C']) {
2497 			dump_cachefile(spa_config_path);
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) {
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 		if (error == 0) {
2545 			nvlist_t *nvl = NULL;
2546 
2547 			if (vdev_dir != NULL) {
2548 				if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
2549 					error = ENOMEM;
2550 				else if (nvlist_add_string(nvl,
2551 				    zpool_prop_to_name(ZPOOL_PROP_ALTROOT),
2552 				    vdev_dir) != 0)
2553 					error = ENOMEM;
2554 			}
2555 
2556 			if (error == 0)
2557 				error = spa_import_faulted(argv[0],
2558 				    exported_conf, nvl);
2559 
2560 			nvlist_free(nvl);
2561 		}
2562 
2563 		if (slash != NULL)
2564 			*slash = '/';
2565 	}
2566 
2567 	if (error == 0) {
2568 		if (strchr(argv[0], '/') != NULL) {
2569 			error = dmu_objset_open(argv[0], DMU_OST_ANY,
2570 			    DS_MODE_USER | DS_MODE_READONLY, &os);
2571 		} else {
2572 			error = spa_open(argv[0], &spa, FTAG);
2573 		}
2574 	}
2575 
2576 	if (error)
2577 		fatal("can't open %s: %s", argv[0], strerror(error));
2578 
2579 	argv++;
2580 	if (--argc > 0) {
2581 		zopt_objects = argc;
2582 		zopt_object = calloc(zopt_objects, sizeof (uint64_t));
2583 		for (i = 0; i < zopt_objects; i++) {
2584 			errno = 0;
2585 			zopt_object[i] = strtoull(argv[i], NULL, 0);
2586 			if (zopt_object[i] == 0 && errno != 0)
2587 				fatal("bad object number %s: %s",
2588 				    argv[i], strerror(errno));
2589 		}
2590 	}
2591 
2592 	if (os != NULL) {
2593 		dump_dir(os);
2594 		dmu_objset_close(os);
2595 	} else {
2596 		dump_zpool(spa);
2597 		spa_close(spa, FTAG);
2598 	}
2599 
2600 	fuid_table_destroy();
2601 
2602 	libzfs_fini(g_zfs);
2603 	kernel_fini();
2604 
2605 	return (0);
2606 }
2607