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