zdb.c revision 6de8f417ed556c30c2c5d24961e26ca586e636a1
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 -C [pool]\n"
102	    "       %s -l dev\n"
103	    "       %s -R pool:vdev:offset:size:flags\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 cached pool configuration\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("Uberblock\n\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(const char *pool)
1313{
1314	spa_t *spa = NULL;
1315
1316	mutex_enter(&spa_namespace_lock);
1317	while ((spa = spa_next(spa)) != NULL) {
1318		if (pool == NULL)
1319			(void) printf("%s\n", spa_name(spa));
1320		if (pool == NULL || strcmp(pool, spa_name(spa)) == 0)
1321			dump_nvlist(spa->spa_config, 4);
1322	}
1323	mutex_exit(&spa_namespace_lock);
1324}
1325
1326static void
1327dump_cachefile(const char *cachefile)
1328{
1329	int fd;
1330	struct stat64 statbuf;
1331	char *buf;
1332	nvlist_t *config;
1333
1334	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
1335		(void) printf("cannot open '%s': %s\n", cachefile,
1336		    strerror(errno));
1337		exit(1);
1338	}
1339
1340	if (fstat64(fd, &statbuf) != 0) {
1341		(void) printf("failed to stat '%s': %s\n", cachefile,
1342		    strerror(errno));
1343		exit(1);
1344	}
1345
1346	if ((buf = malloc(statbuf.st_size)) == NULL) {
1347		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
1348		    (u_longlong_t)statbuf.st_size);
1349		exit(1);
1350	}
1351
1352	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1353		(void) fprintf(stderr, "failed to read %llu bytes\n",
1354		    (u_longlong_t)statbuf.st_size);
1355		exit(1);
1356	}
1357
1358	(void) close(fd);
1359
1360	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
1361		(void) fprintf(stderr, "failed to unpack nvlist\n");
1362		exit(1);
1363	}
1364
1365	free(buf);
1366
1367	dump_nvlist(config, 0);
1368
1369	nvlist_free(config);
1370}
1371
1372static void
1373dump_label(const char *dev)
1374{
1375	int fd;
1376	vdev_label_t label;
1377	char *buf = label.vl_vdev_phys.vp_nvlist;
1378	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1379	struct stat64 statbuf;
1380	uint64_t psize;
1381	int l;
1382
1383	if ((fd = open64(dev, O_RDONLY)) < 0) {
1384		(void) printf("cannot open '%s': %s\n", dev, strerror(errno));
1385		exit(1);
1386	}
1387
1388	if (fstat64(fd, &statbuf) != 0) {
1389		(void) printf("failed to stat '%s': %s\n", dev,
1390		    strerror(errno));
1391		exit(1);
1392	}
1393
1394	psize = statbuf.st_size;
1395	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
1396
1397	for (l = 0; l < VDEV_LABELS; l++) {
1398
1399		nvlist_t *config = NULL;
1400
1401		(void) printf("--------------------------------------------\n");
1402		(void) printf("LABEL %d\n", l);
1403		(void) printf("--------------------------------------------\n");
1404
1405		if (pread64(fd, &label, sizeof (label),
1406		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
1407			(void) printf("failed to read label %d\n", l);
1408			continue;
1409		}
1410
1411		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
1412			(void) printf("failed to unpack label %d\n", l);
1413			continue;
1414		}
1415		dump_nvlist(config, 4);
1416		nvlist_free(config);
1417	}
1418}
1419
1420/*ARGSUSED*/
1421static int
1422dump_one_dir(char *dsname, void *arg)
1423{
1424	int error;
1425	objset_t *os;
1426
1427	error = dmu_objset_own(dsname, DMU_OST_ANY, B_TRUE, FTAG, &os);
1428	if (error) {
1429		(void) printf("Could not open %s\n", dsname);
1430		return (0);
1431	}
1432	dump_dir(os);
1433	dmu_objset_disown(os, FTAG);
1434	fuid_table_destroy();
1435	return (0);
1436}
1437
1438static void
1439zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
1440{
1441	vdev_t *vd = sm->sm_ppd;
1442
1443	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
1444	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
1445}
1446
1447/* ARGSUSED */
1448static void
1449zdb_space_map_load(space_map_t *sm)
1450{
1451}
1452
1453static void
1454zdb_space_map_unload(space_map_t *sm)
1455{
1456	space_map_vacate(sm, zdb_leak, sm);
1457}
1458
1459/* ARGSUSED */
1460static void
1461zdb_space_map_claim(space_map_t *sm, uint64_t start, uint64_t size)
1462{
1463}
1464
1465static space_map_ops_t zdb_space_map_ops = {
1466	zdb_space_map_load,
1467	zdb_space_map_unload,
1468	NULL,	/* alloc */
1469	zdb_space_map_claim,
1470	NULL,	/* free */
1471	NULL	/* maxsize */
1472};
1473
1474static void
1475zdb_leak_init(spa_t *spa)
1476{
1477	vdev_t *rvd = spa->spa_root_vdev;
1478
1479	for (int c = 0; c < rvd->vdev_children; c++) {
1480		vdev_t *vd = rvd->vdev_child[c];
1481		for (int m = 0; m < vd->vdev_ms_count; m++) {
1482			metaslab_t *msp = vd->vdev_ms[m];
1483			mutex_enter(&msp->ms_lock);
1484			VERIFY(space_map_load(&msp->ms_map, &zdb_space_map_ops,
1485			    SM_ALLOC, &msp->ms_smo, spa->spa_meta_objset) == 0);
1486			msp->ms_map.sm_ppd = vd;
1487			mutex_exit(&msp->ms_lock);
1488		}
1489	}
1490}
1491
1492static void
1493zdb_leak_fini(spa_t *spa)
1494{
1495	vdev_t *rvd = spa->spa_root_vdev;
1496
1497	for (int c = 0; c < rvd->vdev_children; c++) {
1498		vdev_t *vd = rvd->vdev_child[c];
1499		for (int m = 0; m < vd->vdev_ms_count; m++) {
1500			metaslab_t *msp = vd->vdev_ms[m];
1501			mutex_enter(&msp->ms_lock);
1502			space_map_unload(&msp->ms_map);
1503			mutex_exit(&msp->ms_lock);
1504		}
1505	}
1506}
1507
1508/*
1509 * Verify that the sum of the sizes of all blocks in the pool adds up
1510 * to the SPA's sa_alloc total.
1511 */
1512typedef struct zdb_blkstats {
1513	uint64_t	zb_asize;
1514	uint64_t	zb_lsize;
1515	uint64_t	zb_psize;
1516	uint64_t	zb_count;
1517} zdb_blkstats_t;
1518
1519#define	DMU_OT_DEFERRED	DMU_OT_NONE
1520#define	DMU_OT_TOTAL	DMU_OT_NUMTYPES
1521
1522#define	ZB_TOTAL	DN_MAX_LEVELS
1523
1524typedef struct zdb_cb {
1525	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][DMU_OT_TOTAL + 1];
1526	uint64_t	zcb_errors[256];
1527	int		zcb_readfails;
1528	int		zcb_haderrors;
1529} zdb_cb_t;
1530
1531static void
1532zdb_count_block(spa_t *spa, zdb_cb_t *zcb, blkptr_t *bp, dmu_object_type_t type)
1533{
1534	for (int i = 0; i < 4; i++) {
1535		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
1536		int t = (i & 1) ? type : DMU_OT_TOTAL;
1537		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
1538
1539		zb->zb_asize += BP_GET_ASIZE(bp);
1540		zb->zb_lsize += BP_GET_LSIZE(bp);
1541		zb->zb_psize += BP_GET_PSIZE(bp);
1542		zb->zb_count++;
1543	}
1544
1545	if (dump_opt['S']) {
1546		boolean_t print_sig;
1547
1548		print_sig = !zdb_sig_user_data || (BP_GET_LEVEL(bp) == 0 &&
1549		    BP_GET_TYPE(bp) == DMU_OT_PLAIN_FILE_CONTENTS);
1550
1551		if (BP_GET_CHECKSUM(bp) < zdb_sig_cksumalg)
1552			print_sig = B_FALSE;
1553
1554		if (print_sig) {
1555			(void) printf("%llu\t%lld\t%lld\t%s\t%s\t%s\t"
1556			    "%llx:%llx:%llx:%llx\n",
1557			    (u_longlong_t)BP_GET_LEVEL(bp),
1558			    (longlong_t)BP_GET_PSIZE(bp),
1559			    (longlong_t)BP_GET_NDVAS(bp),
1560			    ZDB_OT_NAME(BP_GET_TYPE(bp)),
1561			    ZDB_CHECKSUM_NAME(BP_GET_CHECKSUM(bp)),
1562			    ZDB_COMPRESS_NAME(BP_GET_COMPRESS(bp)),
1563			    (u_longlong_t)bp->blk_cksum.zc_word[0],
1564			    (u_longlong_t)bp->blk_cksum.zc_word[1],
1565			    (u_longlong_t)bp->blk_cksum.zc_word[2],
1566			    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1567		}
1568	}
1569
1570	if (!dump_opt['L'])
1571		VERIFY(zio_wait(zio_claim(NULL, spa, spa_first_txg(spa), bp,
1572		    NULL, NULL, ZIO_FLAG_MUSTSUCCEED)) == 0);
1573}
1574
1575static int
1576zdb_blkptr_cb(spa_t *spa, blkptr_t *bp, const zbookmark_t *zb,
1577    const dnode_phys_t *dnp, void *arg)
1578{
1579	zdb_cb_t *zcb = arg;
1580	char blkbuf[BP_SPRINTF_LEN];
1581	dmu_object_type_t type;
1582	boolean_t is_l0_metadata;
1583
1584	if (bp == NULL)
1585		return (0);
1586
1587	type = BP_GET_TYPE(bp);
1588
1589	zdb_count_block(spa, zcb, bp, type);
1590
1591	/*
1592	 * if we do metadata-only checksumming there's no need to checksum
1593	 * indirect blocks here because it is done during traverse
1594	 */
1595	is_l0_metadata = (BP_GET_LEVEL(bp) == 0 && type < DMU_OT_NUMTYPES &&
1596	    dmu_ot[type].ot_metadata);
1597
1598	if (dump_opt['c'] > 1 || dump_opt['S'] ||
1599	    (dump_opt['c'] && is_l0_metadata)) {
1600		int ioerr, size;
1601		void *data;
1602
1603		size = BP_GET_LSIZE(bp);
1604		data = malloc(size);
1605		ioerr = zio_wait(zio_read(NULL, spa, bp, data, size,
1606		    NULL, NULL, ZIO_PRIORITY_ASYNC_READ,
1607		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB, zb));
1608		free(data);
1609
1610		/* We expect io errors on intent log */
1611		if (ioerr && type != DMU_OT_INTENT_LOG) {
1612			zcb->zcb_haderrors = 1;
1613			zcb->zcb_errors[ioerr]++;
1614
1615			if (dump_opt['b'] >= 2)
1616				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1617			else
1618				blkbuf[0] = '\0';
1619
1620			if (!dump_opt['S']) {
1621				(void) printf("zdb_blkptr_cb: "
1622				    "Got error %d reading "
1623				    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
1624				    ioerr,
1625				    (u_longlong_t)zb->zb_objset,
1626				    (u_longlong_t)zb->zb_object,
1627				    (u_longlong_t)zb->zb_level,
1628				    (u_longlong_t)zb->zb_blkid,
1629				    blkbuf);
1630			}
1631		}
1632	}
1633
1634	zcb->zcb_readfails = 0;
1635
1636	if (dump_opt['b'] >= 4) {
1637		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1638		(void) printf("objset %llu object %llu offset 0x%llx %s\n",
1639		    (u_longlong_t)zb->zb_objset,
1640		    (u_longlong_t)zb->zb_object,
1641		    (u_longlong_t)blkid2offset(dnp, zb->zb_level, zb->zb_blkid),
1642		    blkbuf);
1643	}
1644
1645	return (0);
1646}
1647
1648static int
1649dump_block_stats(spa_t *spa)
1650{
1651	zdb_cb_t zcb = { 0 };
1652	zdb_blkstats_t *zb, *tzb;
1653	uint64_t alloc, space, logalloc;
1654	vdev_t *rvd = spa->spa_root_vdev;
1655	int leaks = 0;
1656	int c, e;
1657
1658	if (!dump_opt['S']) {
1659		(void) printf("\nTraversing all blocks %s%s%s%s%s...\n",
1660		    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
1661		    (dump_opt['c'] == 1) ? "metadata " : "",
1662		    dump_opt['c'] ? "checksums " : "",
1663		    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
1664		    !dump_opt['L'] ? "nothing leaked " : "");
1665	}
1666
1667	/*
1668	 * Load all space maps as SM_ALLOC maps, then traverse the pool
1669	 * claiming each block we discover.  If the pool is perfectly
1670	 * consistent, the space maps will be empty when we're done.
1671	 * Anything left over is a leak; any block we can't claim (because
1672	 * it's not part of any space map) is a double allocation,
1673	 * reference to a freed block, or an unclaimed log block.
1674	 */
1675	if (!dump_opt['L'])
1676		zdb_leak_init(spa);
1677
1678	/*
1679	 * If there's a deferred-free bplist, process that first.
1680	 */
1681	if (spa->spa_sync_bplist_obj != 0) {
1682		bplist_t *bpl = &spa->spa_sync_bplist;
1683		blkptr_t blk;
1684		uint64_t itor = 0;
1685
1686		VERIFY(0 == bplist_open(bpl, spa->spa_meta_objset,
1687		    spa->spa_sync_bplist_obj));
1688
1689		while (bplist_iterate(bpl, &itor, &blk) == 0) {
1690			if (dump_opt['b'] >= 4) {
1691				char blkbuf[BP_SPRINTF_LEN];
1692				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &blk);
1693				(void) printf("[%s] %s\n",
1694				    "deferred free", blkbuf);
1695			}
1696			zdb_count_block(spa, &zcb, &blk, DMU_OT_DEFERRED);
1697		}
1698
1699		bplist_close(bpl);
1700	}
1701
1702	zcb.zcb_haderrors |= traverse_pool(spa, zdb_blkptr_cb, &zcb);
1703
1704	if (zcb.zcb_haderrors && !dump_opt['S']) {
1705		(void) printf("\nError counts:\n\n");
1706		(void) printf("\t%5s  %s\n", "errno", "count");
1707		for (e = 0; e < 256; e++) {
1708			if (zcb.zcb_errors[e] != 0) {
1709				(void) printf("\t%5d  %llu\n",
1710				    e, (u_longlong_t)zcb.zcb_errors[e]);
1711			}
1712		}
1713	}
1714
1715	/*
1716	 * Report any leaked segments.
1717	 */
1718	if (!dump_opt['L'])
1719		zdb_leak_fini(spa);
1720
1721	/*
1722	 * If we're interested in printing out the blkptr signatures,
1723	 * return now as we don't print out anything else (including
1724	 * errors and leaks).
1725	 */
1726	if (dump_opt['S'])
1727		return (zcb.zcb_haderrors ? 3 : 0);
1728
1729	alloc = spa_get_alloc(spa);
1730	space = spa_get_space(spa);
1731
1732	/*
1733	 * Log blocks allocated from a separate log device don't count
1734	 * as part of the normal pool space; factor them in here.
1735	 */
1736	logalloc = 0;
1737
1738	for (c = 0; c < rvd->vdev_children; c++)
1739		if (rvd->vdev_child[c]->vdev_islog)
1740			logalloc += rvd->vdev_child[c]->vdev_stat.vs_alloc;
1741
1742	tzb = &zcb.zcb_type[ZB_TOTAL][DMU_OT_TOTAL];
1743
1744	if (tzb->zb_asize == alloc + logalloc) {
1745		if (!dump_opt['L'])
1746			(void) printf("\n\tNo leaks (block sum matches space"
1747			    " maps exactly)\n");
1748	} else {
1749		(void) printf("block traversal size %llu != alloc %llu "
1750		    "(%s %lld)\n",
1751		    (u_longlong_t)tzb->zb_asize,
1752		    (u_longlong_t)alloc + logalloc,
1753		    (dump_opt['L']) ? "unreachable" : "leaked",
1754		    (longlong_t)(alloc + logalloc - tzb->zb_asize));
1755		leaks = 1;
1756	}
1757
1758	if (tzb->zb_count == 0)
1759		return (2);
1760
1761	(void) printf("\n");
1762	(void) printf("\tbp count:      %10llu\n",
1763	    (u_longlong_t)tzb->zb_count);
1764	(void) printf("\tbp logical:    %10llu\t avg: %6llu\n",
1765	    (u_longlong_t)tzb->zb_lsize,
1766	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
1767	(void) printf("\tbp physical:   %10llu\t avg:"
1768	    " %6llu\tcompression: %6.2f\n",
1769	    (u_longlong_t)tzb->zb_psize,
1770	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
1771	    (double)tzb->zb_lsize / tzb->zb_psize);
1772	(void) printf("\tbp allocated:  %10llu\t avg:"
1773	    " %6llu\tcompression: %6.2f\n",
1774	    (u_longlong_t)tzb->zb_asize,
1775	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
1776	    (double)tzb->zb_lsize / tzb->zb_asize);
1777	(void) printf("\tSPA allocated: %10llu\tused: %5.2f%%\n",
1778	    (u_longlong_t)alloc, 100.0 * alloc / space);
1779
1780	if (dump_opt['b'] >= 2) {
1781		int l, t, level;
1782		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
1783		    "\t  avg\t comp\t%%Total\tType\n");
1784
1785		for (t = 0; t <= DMU_OT_NUMTYPES; t++) {
1786			char csize[6], lsize[6], psize[6], asize[6], avg[6];
1787			char *typename;
1788
1789			typename = t == DMU_OT_DEFERRED ? "deferred free" :
1790			    t == DMU_OT_TOTAL ? "Total" : dmu_ot[t].ot_name;
1791
1792			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
1793				(void) printf("%6s\t%5s\t%5s\t%5s"
1794				    "\t%5s\t%5s\t%6s\t%s\n",
1795				    "-",
1796				    "-",
1797				    "-",
1798				    "-",
1799				    "-",
1800				    "-",
1801				    "-",
1802				    typename);
1803				continue;
1804			}
1805
1806			for (l = ZB_TOTAL - 1; l >= -1; l--) {
1807				level = (l == -1 ? ZB_TOTAL : l);
1808				zb = &zcb.zcb_type[level][t];
1809
1810				if (zb->zb_asize == 0)
1811					continue;
1812
1813				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
1814					continue;
1815
1816				if (level == 0 && zb->zb_asize ==
1817				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
1818					continue;
1819
1820				nicenum(zb->zb_count, csize);
1821				nicenum(zb->zb_lsize, lsize);
1822				nicenum(zb->zb_psize, psize);
1823				nicenum(zb->zb_asize, asize);
1824				nicenum(zb->zb_asize / zb->zb_count, avg);
1825
1826				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
1827				    "\t%5.2f\t%6.2f\t",
1828				    csize, lsize, psize, asize, avg,
1829				    (double)zb->zb_lsize / zb->zb_psize,
1830				    100.0 * zb->zb_asize / tzb->zb_asize);
1831
1832				if (level == ZB_TOTAL)
1833					(void) printf("%s\n", typename);
1834				else
1835					(void) printf("    L%d %s\n",
1836					    level, typename);
1837			}
1838		}
1839	}
1840
1841	(void) printf("\n");
1842
1843	if (leaks)
1844		return (2);
1845
1846	if (zcb.zcb_haderrors)
1847		return (3);
1848
1849	return (0);
1850}
1851
1852static void
1853dump_zpool(spa_t *spa)
1854{
1855	dsl_pool_t *dp = spa_get_dsl(spa);
1856	int rc = 0;
1857
1858	if (dump_opt['u'])
1859		dump_uberblock(&spa->spa_uberblock);
1860
1861	if (dump_opt['d'] || dump_opt['i'] || dump_opt['m']) {
1862		dump_dir(dp->dp_meta_objset);
1863		if (dump_opt['d'] >= 3) {
1864			dump_bplist(dp->dp_meta_objset,
1865			    spa->spa_sync_bplist_obj, "Deferred frees");
1866			dump_dtl(spa->spa_root_vdev, 0);
1867		}
1868
1869		if (dump_opt['d'] >= 3 || dump_opt['m'])
1870			dump_metaslabs(spa);
1871
1872		(void) dmu_objset_find(spa_name(spa), dump_one_dir, NULL,
1873		    DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
1874	}
1875
1876	if (dump_opt['b'] || dump_opt['c'] || dump_opt['S'])
1877		rc = dump_block_stats(spa);
1878
1879	if (dump_opt['s'])
1880		show_pool_stats(spa);
1881
1882	if (dump_opt['h'])
1883		dump_history(spa);
1884
1885	if (rc != 0)
1886		exit(rc);
1887}
1888
1889#define	ZDB_FLAG_CHECKSUM	0x0001
1890#define	ZDB_FLAG_DECOMPRESS	0x0002
1891#define	ZDB_FLAG_BSWAP		0x0004
1892#define	ZDB_FLAG_GBH		0x0008
1893#define	ZDB_FLAG_INDIRECT	0x0010
1894#define	ZDB_FLAG_PHYS		0x0020
1895#define	ZDB_FLAG_RAW		0x0040
1896#define	ZDB_FLAG_PRINT_BLKPTR	0x0080
1897
1898int flagbits[256];
1899
1900static void
1901zdb_print_blkptr(blkptr_t *bp, int flags)
1902{
1903	dva_t *dva = bp->blk_dva;
1904	int d;
1905
1906	if (flags & ZDB_FLAG_BSWAP)
1907		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
1908	/*
1909	 * Super-ick warning:  This code is also duplicated in
1910	 * cmd/mdb/common/modules/zfs/zfs.c .  Yeah, I hate code
1911	 * replication, too.
1912	 */
1913	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1914		(void) printf("\tDVA[%d]: vdev_id %lld / %llx\n", d,
1915		    (longlong_t)DVA_GET_VDEV(&dva[d]),
1916		    (longlong_t)DVA_GET_OFFSET(&dva[d]));
1917		(void) printf("\tDVA[%d]:       GANG: %-5s  GRID:  %04llx\t"
1918		    "ASIZE: %llx\n", d,
1919		    DVA_GET_GANG(&dva[d]) ? "TRUE" : "FALSE",
1920		    (longlong_t)DVA_GET_GRID(&dva[d]),
1921		    (longlong_t)DVA_GET_ASIZE(&dva[d]));
1922		(void) printf("\tDVA[%d]: :%llu:%llx:%llx:%s%s%s%s\n", d,
1923		    (u_longlong_t)DVA_GET_VDEV(&dva[d]),
1924		    (longlong_t)DVA_GET_OFFSET(&dva[d]),
1925		    (longlong_t)BP_GET_PSIZE(bp),
1926		    BP_SHOULD_BYTESWAP(bp) ? "e" : "",
1927		    !DVA_GET_GANG(&dva[d]) && BP_GET_LEVEL(bp) != 0 ?
1928		    "d" : "",
1929		    DVA_GET_GANG(&dva[d]) ? "g" : "",
1930		    BP_GET_COMPRESS(bp) != 0 ? "d" : "");
1931	}
1932	(void) printf("\tLSIZE:  %-16llx\t\tPSIZE: %llx\n",
1933	    (longlong_t)BP_GET_LSIZE(bp), (longlong_t)BP_GET_PSIZE(bp));
1934	(void) printf("\tENDIAN: %6s\t\t\t\t\tTYPE:  %s\n",
1935	    BP_GET_BYTEORDER(bp) ? "LITTLE" : "BIG",
1936	    ZDB_OT_NAME(BP_GET_TYPE(bp)));
1937	(void) printf("\tBIRTH:  %-16llx   LEVEL: %-2llu\tFILL:  %llx\n",
1938	    (u_longlong_t)bp->blk_birth, (u_longlong_t)BP_GET_LEVEL(bp),
1939	    (u_longlong_t)bp->blk_fill);
1940	(void) printf("\tCKFUNC: %-16s\t\tCOMP:  %s\n",
1941	    ZDB_CHECKSUM_NAME(BP_GET_CHECKSUM(bp)),
1942	    ZDB_COMPRESS_NAME(BP_GET_COMPRESS(bp)));
1943	(void) printf("\tCKSUM:  %llx:%llx:%llx:%llx\n",
1944	    (u_longlong_t)bp->blk_cksum.zc_word[0],
1945	    (u_longlong_t)bp->blk_cksum.zc_word[1],
1946	    (u_longlong_t)bp->blk_cksum.zc_word[2],
1947	    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1948}
1949
1950static void
1951zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
1952{
1953	int i;
1954
1955	for (i = 0; i < nbps; i++)
1956		zdb_print_blkptr(&bp[i], flags);
1957}
1958
1959static void
1960zdb_dump_gbh(void *buf, int flags)
1961{
1962	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
1963}
1964
1965static void
1966zdb_dump_block_raw(void *buf, uint64_t size, int flags)
1967{
1968	if (flags & ZDB_FLAG_BSWAP)
1969		byteswap_uint64_array(buf, size);
1970	(void) write(2, buf, size);
1971}
1972
1973static void
1974zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
1975{
1976	uint64_t *d = (uint64_t *)buf;
1977	int nwords = size / sizeof (uint64_t);
1978	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
1979	int i, j;
1980	char *hdr, *c;
1981
1982
1983	if (do_bswap)
1984		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
1985	else
1986		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
1987
1988	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
1989
1990	for (i = 0; i < nwords; i += 2) {
1991		(void) printf("%06llx:  %016llx  %016llx  ",
1992		    (u_longlong_t)(i * sizeof (uint64_t)),
1993		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
1994		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
1995
1996		c = (char *)&d[i];
1997		for (j = 0; j < 2 * sizeof (uint64_t); j++)
1998			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
1999		(void) printf("\n");
2000	}
2001}
2002
2003/*
2004 * There are two acceptable formats:
2005 *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
2006 *	child[.child]*    - For example: 0.1.1
2007 *
2008 * The second form can be used to specify arbitrary vdevs anywhere
2009 * in the heirarchy.  For example, in a pool with a mirror of
2010 * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
2011 */
2012static vdev_t *
2013zdb_vdev_lookup(vdev_t *vdev, char *path)
2014{
2015	char *s, *p, *q;
2016	int i;
2017
2018	if (vdev == NULL)
2019		return (NULL);
2020
2021	/* First, assume the x.x.x.x format */
2022	i = (int)strtoul(path, &s, 10);
2023	if (s == path || (s && *s != '.' && *s != '\0'))
2024		goto name;
2025	if (i < 0 || i >= vdev->vdev_children)
2026		return (NULL);
2027
2028	vdev = vdev->vdev_child[i];
2029	if (*s == '\0')
2030		return (vdev);
2031	return (zdb_vdev_lookup(vdev, s+1));
2032
2033name:
2034	for (i = 0; i < vdev->vdev_children; i++) {
2035		vdev_t *vc = vdev->vdev_child[i];
2036
2037		if (vc->vdev_path == NULL) {
2038			vc = zdb_vdev_lookup(vc, path);
2039			if (vc == NULL)
2040				continue;
2041			else
2042				return (vc);
2043		}
2044
2045		p = strrchr(vc->vdev_path, '/');
2046		p = p ? p + 1 : vc->vdev_path;
2047		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2048
2049		if (strcmp(vc->vdev_path, path) == 0)
2050			return (vc);
2051		if (strcmp(p, path) == 0)
2052			return (vc);
2053		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2054			return (vc);
2055	}
2056
2057	return (NULL);
2058}
2059
2060/*
2061 * Read a block from a pool and print it out.  The syntax of the
2062 * block descriptor is:
2063 *
2064 *	pool:vdev_specifier:offset:size[:flags]
2065 *
2066 *	pool           - The name of the pool you wish to read from
2067 *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2068 *	offset         - offset, in hex, in bytes
2069 *	size           - Amount of data to read, in hex, in bytes
2070 *	flags          - A string of characters specifying options
2071 *		 b: Decode a blkptr at given offset within block
2072 *		*c: Calculate and display checksums
2073 *		*d: Decompress data before dumping
2074 *		 e: Byteswap data before dumping
2075 *		*g: Display data as a gang block header
2076 *		*i: Display as an indirect block
2077 *		 p: Do I/O to physical offset
2078 *		 r: Dump raw data to stdout
2079 *
2080 *              * = not yet implemented
2081 */
2082static void
2083zdb_read_block(char *thing, spa_t **spap)
2084{
2085	spa_t *spa = *spap;
2086	int flags = 0;
2087	uint64_t offset = 0, size = 0, blkptr_offset = 0;
2088	zio_t *zio;
2089	vdev_t *vd;
2090	void *buf;
2091	char *s, *p, *dup, *pool, *vdev, *flagstr;
2092	int i, error, zio_flags;
2093
2094	dup = strdup(thing);
2095	s = strtok(dup, ":");
2096	pool = s ? s : "";
2097	s = strtok(NULL, ":");
2098	vdev = s ? s : "";
2099	s = strtok(NULL, ":");
2100	offset = strtoull(s ? s : "", NULL, 16);
2101	s = strtok(NULL, ":");
2102	size = strtoull(s ? s : "", NULL, 16);
2103	s = strtok(NULL, ":");
2104	flagstr = s ? s : "";
2105
2106	s = NULL;
2107	if (size == 0)
2108		s = "size must not be zero";
2109	if (!IS_P2ALIGNED(size, DEV_BSIZE))
2110		s = "size must be a multiple of sector size";
2111	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
2112		s = "offset must be a multiple of sector size";
2113	if (s) {
2114		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
2115		free(dup);
2116		return;
2117	}
2118
2119	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
2120		for (i = 0; flagstr[i]; i++) {
2121			int bit = flagbits[(uchar_t)flagstr[i]];
2122
2123			if (bit == 0) {
2124				(void) printf("***Invalid flag: %c\n",
2125				    flagstr[i]);
2126				continue;
2127			}
2128			flags |= bit;
2129
2130			/* If it's not something with an argument, keep going */
2131			if ((bit & (ZDB_FLAG_CHECKSUM | ZDB_FLAG_DECOMPRESS |
2132			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
2133				continue;
2134
2135			p = &flagstr[i + 1];
2136			if (bit == ZDB_FLAG_PRINT_BLKPTR)
2137				blkptr_offset = strtoull(p, &p, 16);
2138			if (*p != ':' && *p != '\0') {
2139				(void) printf("***Invalid flag arg: '%s'\n", s);
2140				free(dup);
2141				return;
2142			}
2143		}
2144	}
2145
2146	if (spa == NULL || strcmp(spa_name(spa), pool) != 0) {
2147		if (spa)
2148			spa_close(spa, (void *)zdb_read_block);
2149		error = spa_open(pool, spap, (void *)zdb_read_block);
2150		if (error)
2151			fatal("Failed to open pool '%s': %s",
2152			    pool, strerror(error));
2153		spa = *spap;
2154	}
2155
2156	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2157	if (vd == NULL) {
2158		(void) printf("***Invalid vdev: %s\n", vdev);
2159		free(dup);
2160		return;
2161	} else {
2162		if (vd->vdev_path)
2163			(void) printf("Found vdev: %s\n", vd->vdev_path);
2164		else
2165			(void) printf("Found vdev type: %s\n",
2166			    vd->vdev_ops->vdev_op_type);
2167	}
2168
2169	buf = umem_alloc(size, UMEM_NOFAIL);
2170
2171	zio_flags = ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2172	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY;
2173
2174	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
2175	zio = zio_root(spa, NULL, NULL, 0);
2176	/* XXX todo - cons up a BP so RAID-Z will be happy */
2177	zio_nowait(zio_vdev_child_io(zio, NULL, vd, offset, buf, size,
2178	    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ, zio_flags, NULL, NULL));
2179	error = zio_wait(zio);
2180	spa_config_exit(spa, SCL_STATE, FTAG);
2181
2182	if (error) {
2183		(void) printf("Read of %s failed, error: %d\n", thing, error);
2184		goto out;
2185	}
2186
2187	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2188		zdb_print_blkptr((blkptr_t *)(void *)
2189		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2190	else if (flags & ZDB_FLAG_RAW)
2191		zdb_dump_block_raw(buf, size, flags);
2192	else if (flags & ZDB_FLAG_INDIRECT)
2193		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2194		    flags);
2195	else if (flags & ZDB_FLAG_GBH)
2196		zdb_dump_gbh(buf, flags);
2197	else
2198		zdb_dump_block(thing, buf, size, flags);
2199
2200out:
2201	umem_free(buf, size);
2202	free(dup);
2203}
2204
2205static boolean_t
2206pool_match(nvlist_t *cfg, char *tgt)
2207{
2208	uint64_t v, guid = strtoull(tgt, NULL, 0);
2209	char *s;
2210
2211	if (guid != 0) {
2212		if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
2213			return (v == guid);
2214	} else {
2215		if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
2216			return (strcmp(s, tgt) == 0);
2217	}
2218	return (B_FALSE);
2219}
2220
2221static char *
2222find_zpool(char **target, nvlist_t **configp, int dirc, char **dirv)
2223{
2224	nvlist_t *pools;
2225	nvlist_t *match = NULL;
2226	char *name = NULL;
2227	char *sepp = NULL;
2228	char sep;
2229	int count = 0;
2230
2231	if ((sepp = strpbrk(*target, "/@")) != NULL) {
2232		sep = *sepp;
2233		*sepp = '\0';
2234	}
2235
2236	pools = zpool_find_import_activeok(g_zfs, dirc, dirv);
2237
2238	if (pools != NULL) {
2239		nvpair_t *elem = NULL;
2240		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2241			verify(nvpair_value_nvlist(elem, configp) == 0);
2242			if (pool_match(*configp, *target)) {
2243				count++;
2244				if (match != NULL) {
2245					/* print previously found config */
2246					if (name != NULL) {
2247						(void) printf("%s\n", name);
2248						dump_nvlist(match, 8);
2249						name = NULL;
2250					}
2251					(void) printf("%s\n",
2252					    nvpair_name(elem));
2253					dump_nvlist(*configp, 8);
2254				} else {
2255					match = *configp;
2256					name = nvpair_name(elem);
2257				}
2258			}
2259		}
2260	}
2261	if (count > 1)
2262		(void) fatal("\tMatched %d pools - use pool GUID "
2263		    "instead of pool name or \n"
2264		    "\tpool name part of a dataset name to select pool", count);
2265
2266	if (sepp)
2267		*sepp = sep;
2268	/*
2269	 * If pool GUID was specified for pool id, replace it with pool name
2270	 */
2271	if (name && (strstr(*target, name) != *target)) {
2272		int sz = 1 + strlen(name) + ((sepp) ? strlen(sepp) : 0);
2273
2274		*target = umem_alloc(sz, UMEM_NOFAIL);
2275		(void) snprintf(*target, sz, "%s%s", name, sepp ? sepp : "");
2276	}
2277
2278	*configp = name ? match : NULL;
2279
2280	return (name);
2281}
2282
2283int
2284main(int argc, char **argv)
2285{
2286	int i, c;
2287	struct rlimit rl = { 1024, 1024 };
2288	spa_t *spa = NULL;
2289	objset_t *os = NULL;
2290	char *endstr;
2291	int dump_all = 1;
2292	int verbose = 0;
2293	int error;
2294	char **searchdirs = NULL;
2295	int nsearch = 0;
2296	char *target;
2297
2298	(void) setrlimit(RLIMIT_NOFILE, &rl);
2299	(void) enable_extended_FILE_stdio(-1, -1);
2300
2301	dprintf_setup(&argc, argv);
2302
2303	while ((c = getopt(argc, argv, "udhibcmsvCLS:U:lRep:t:")) != -1) {
2304		switch (c) {
2305		case 'u':
2306		case 'd':
2307		case 'i':
2308		case 'h':
2309		case 'b':
2310		case 'c':
2311		case 'm':
2312		case 's':
2313		case 'C':
2314		case 'l':
2315		case 'R':
2316			dump_opt[c]++;
2317			dump_all = 0;
2318			break;
2319		case 'L':
2320		case 'e':
2321			dump_opt[c]++;
2322			break;
2323		case 'v':
2324			verbose++;
2325			break;
2326		case 'U':
2327			spa_config_path = optarg;
2328			break;
2329		case 'p':
2330			if (searchdirs == NULL) {
2331				searchdirs = umem_alloc(sizeof (char *),
2332				    UMEM_NOFAIL);
2333			} else {
2334				char **tmp = umem_alloc((nsearch + 1) *
2335				    sizeof (char *), UMEM_NOFAIL);
2336				bcopy(searchdirs, tmp, nsearch *
2337				    sizeof (char *));
2338				umem_free(searchdirs,
2339				    nsearch * sizeof (char *));
2340				searchdirs = tmp;
2341			}
2342			searchdirs[nsearch++] = optarg;
2343			break;
2344		case 'S':
2345			dump_opt[c]++;
2346			dump_all = 0;
2347			zdb_sig_user_data = (strncmp(optarg, "user:", 5) == 0);
2348			if (!zdb_sig_user_data && strncmp(optarg, "all:", 4))
2349				usage();
2350			endstr = strchr(optarg, ':') + 1;
2351			if (strcmp(endstr, "fletcher2") == 0)
2352				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_2;
2353			else if (strcmp(endstr, "fletcher4") == 0)
2354				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_4;
2355			else if (strcmp(endstr, "sha256") == 0)
2356				zdb_sig_cksumalg = ZIO_CHECKSUM_SHA256;
2357			else if (strcmp(endstr, "all") == 0)
2358				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_2;
2359			else
2360				usage();
2361			break;
2362		case 't':
2363			ub_max_txg = strtoull(optarg, NULL, 0);
2364			if (ub_max_txg < TXG_INITIAL) {
2365				(void) fprintf(stderr, "incorrect txg "
2366				    "specified: %s\n", optarg);
2367				usage();
2368			}
2369			break;
2370		default:
2371			usage();
2372			break;
2373		}
2374	}
2375
2376	if (!dump_opt['e'] && searchdirs != NULL) {
2377		(void) fprintf(stderr, "-p option requires use of -e\n");
2378		usage();
2379	}
2380
2381	kernel_init(FREAD);
2382	g_zfs = libzfs_init();
2383	ASSERT(g_zfs != NULL);
2384
2385	for (c = 0; c < 256; c++) {
2386		if (dump_all && !strchr("elLR", c))
2387			dump_opt[c] = 1;
2388		if (dump_opt[c])
2389			dump_opt[c] += verbose;
2390	}
2391
2392	argc -= optind;
2393	argv += optind;
2394
2395	if (argc < 1) {
2396		if (!dump_opt['e'] && dump_opt['C']) {
2397			dump_cachefile(spa_config_path);
2398			return (0);
2399		}
2400		usage();
2401	}
2402
2403	if (dump_opt['l']) {
2404		dump_label(argv[0]);
2405		return (0);
2406	}
2407
2408	if (dump_opt['R']) {
2409		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
2410		flagbits['c'] = ZDB_FLAG_CHECKSUM;
2411		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
2412		flagbits['e'] = ZDB_FLAG_BSWAP;
2413		flagbits['g'] = ZDB_FLAG_GBH;
2414		flagbits['i'] = ZDB_FLAG_INDIRECT;
2415		flagbits['p'] = ZDB_FLAG_PHYS;
2416		flagbits['r'] = ZDB_FLAG_RAW;
2417
2418		spa = NULL;
2419		while (argv[0]) {
2420			zdb_read_block(argv[0], &spa);
2421			argv++;
2422			argc--;
2423		}
2424		if (spa)
2425			spa_close(spa, (void *)zdb_read_block);
2426		return (0);
2427	}
2428
2429	if (dump_opt['C'])
2430		dump_config(argv[0]);
2431
2432	error = 0;
2433	target = argv[0];
2434
2435	if (dump_opt['e']) {
2436		nvlist_t *cfg = NULL;
2437		char *name = find_zpool(&target, &cfg, nsearch, searchdirs);
2438
2439		error = ENOENT;
2440		if (name) {
2441			if ((error = spa_import(name, cfg, NULL)) != 0)
2442				error = spa_import_verbatim(name, cfg, NULL);
2443		}
2444	}
2445
2446	if (error == 0) {
2447		if (strpbrk(target, "/@") != NULL) {
2448			error = dmu_objset_own(target, DMU_OST_ANY,
2449			    B_TRUE, FTAG, &os);
2450		} else {
2451			error = spa_open(target, &spa, FTAG);
2452			if (error) {
2453				/*
2454				 * If we're missing the log device then
2455				 * try opening the pool after clearing the
2456				 * log state.
2457				 */
2458				mutex_enter(&spa_namespace_lock);
2459				if ((spa = spa_lookup(target)) != NULL &&
2460				    spa->spa_log_state == SPA_LOG_MISSING) {
2461					spa->spa_log_state = SPA_LOG_CLEAR;
2462					error = 0;
2463				}
2464				mutex_exit(&spa_namespace_lock);
2465
2466				if (!error)
2467					error = spa_open(target, &spa, FTAG);
2468			}
2469		}
2470	}
2471
2472	if (error)
2473		fatal("can't open '%s': %s", target, strerror(error));
2474
2475	argv++;
2476	if (--argc > 0) {
2477		zopt_objects = argc;
2478		zopt_object = calloc(zopt_objects, sizeof (uint64_t));
2479		for (i = 0; i < zopt_objects; i++) {
2480			errno = 0;
2481			zopt_object[i] = strtoull(argv[i], NULL, 0);
2482			if (zopt_object[i] == 0 && errno != 0)
2483				fatal("bad object number %s: %s",
2484				    argv[i], strerror(errno));
2485		}
2486	}
2487
2488	if (os != NULL) {
2489		dump_dir(os);
2490		dmu_objset_disown(os, FTAG);
2491	} else {
2492		dump_zpool(spa);
2493		spa_close(spa, FTAG);
2494	}
2495
2496	fuid_table_destroy();
2497
2498	libzfs_fini(g_zfs);
2499	kernel_fini();
2500
2501	return (0);
2502}
2503