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