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