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