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