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