zdb.c revision d04756377ddd1cf28ebcf652541094e17b03c889
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/*
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2012 by Delphix. All rights reserved.
25 */
26
27#include <stdio.h>
28#include <stdio_ext.h>
29#include <stdlib.h>
30#include <ctype.h>
31#include <sys/zfs_context.h>
32#include <sys/spa.h>
33#include <sys/spa_impl.h>
34#include <sys/dmu.h>
35#include <sys/zap.h>
36#include <sys/fs/zfs.h>
37#include <sys/zfs_znode.h>
38#include <sys/zfs_sa.h>
39#include <sys/sa.h>
40#include <sys/sa_impl.h>
41#include <sys/vdev.h>
42#include <sys/vdev_impl.h>
43#include <sys/metaslab_impl.h>
44#include <sys/dmu_objset.h>
45#include <sys/dsl_dir.h>
46#include <sys/dsl_dataset.h>
47#include <sys/dsl_pool.h>
48#include <sys/dbuf.h>
49#include <sys/zil.h>
50#include <sys/zil_impl.h>
51#include <sys/stat.h>
52#include <sys/resource.h>
53#include <sys/dmu_traverse.h>
54#include <sys/zio_checksum.h>
55#include <sys/zio_compress.h>
56#include <sys/zfs_fuid.h>
57#include <sys/arc.h>
58#include <sys/ddt.h>
59#include <sys/zfeature.h>
60#include <zfs_comutil.h>
61#undef ZFS_MAXNAMELEN
62#undef verify
63#include <libzfs.h>
64
65#define	ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ?	\
66	zio_compress_table[(idx)].ci_name : "UNKNOWN")
67#define	ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ?	\
68	zio_checksum_table[(idx)].ci_name : "UNKNOWN")
69#define	ZDB_OT_NAME(idx) ((idx) < DMU_OT_NUMTYPES ?	\
70	dmu_ot[(idx)].ot_name : DMU_OT_IS_VALID(idx) ?	\
71	dmu_ot_byteswap[DMU_OT_BYTESWAP(idx)].ob_name : "UNKNOWN")
72#define	ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) :		\
73	(((idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA) ?	\
74	DMU_OT_ZAP_OTHER : DMU_OT_NUMTYPES))
75
76#ifndef lint
77extern int zfs_recover;
78#else
79int zfs_recover;
80#endif
81
82const char cmdname[] = "zdb";
83uint8_t dump_opt[256];
84
85typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
86
87extern void dump_intent_log(zilog_t *);
88uint64_t *zopt_object = NULL;
89int zopt_objects = 0;
90libzfs_handle_t *g_zfs;
91uint64_t max_inflight = 200;
92
93/*
94 * These libumem hooks provide a reasonable set of defaults for the allocator's
95 * debugging facilities.
96 */
97const char *
98_umem_debug_init()
99{
100	return ("default,verbose"); /* $UMEM_DEBUG setting */
101}
102
103const char *
104_umem_logging_init(void)
105{
106	return ("fail,contents"); /* $UMEM_LOGGING setting */
107}
108
109static void
110usage(void)
111{
112	(void) fprintf(stderr,
113	    "Usage: %s [-CumdibcsDvhLXFPA] [-t txg] [-e [-p path...]] "
114	    "[-U config] [-M inflight I/Os] poolname [object...]\n"
115	    "       %s [-divPA] [-e -p path...] [-U config] dataset "
116	    "[object...]\n"
117	    "       %s -m [-LXFPA] [-t txg] [-e [-p path...]] [-U config] "
118	    "poolname [vdev [metaslab...]]\n"
119	    "       %s -R [-A] [-e [-p path...]] poolname "
120	    "vdev:offset:size[:flags]\n"
121	    "       %s -S [-PA] [-e [-p path...]] [-U config] poolname\n"
122	    "       %s -l [-uA] device\n"
123	    "       %s -C [-A] [-U config]\n\n",
124	    cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname);
125
126	(void) fprintf(stderr, "    Dataset name must include at least one "
127	    "separator character '/' or '@'\n");
128	(void) fprintf(stderr, "    If dataset name is specified, only that "
129	    "dataset is dumped\n");
130	(void) fprintf(stderr, "    If object numbers are specified, only "
131	    "those objects are dumped\n\n");
132	(void) fprintf(stderr, "    Options to control amount of output:\n");
133	(void) fprintf(stderr, "        -u uberblock\n");
134	(void) fprintf(stderr, "        -d dataset(s)\n");
135	(void) fprintf(stderr, "        -i intent logs\n");
136	(void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
137	(void) fprintf(stderr, "        -h pool history\n");
138	(void) fprintf(stderr, "        -b block statistics\n");
139	(void) fprintf(stderr, "        -m metaslabs\n");
140	(void) fprintf(stderr, "        -c checksum all metadata (twice for "
141	    "all data) blocks\n");
142	(void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
143	(void) fprintf(stderr, "        -D dedup statistics\n");
144	(void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
145	(void) fprintf(stderr, "        -v verbose (applies to all others)\n");
146	(void) fprintf(stderr, "        -l dump label contents\n");
147	(void) fprintf(stderr, "        -L disable leak tracking (do not "
148	    "load spacemaps)\n");
149	(void) fprintf(stderr, "        -R read and display block from a "
150	    "device\n\n");
151	(void) fprintf(stderr, "    Below options are intended for use "
152	    "with other options (except -l):\n");
153	(void) fprintf(stderr, "        -A ignore assertions (-A), enable "
154	    "panic recovery (-AA) or both (-AAA)\n");
155	(void) fprintf(stderr, "        -F attempt automatic rewind within "
156	    "safe range of transaction groups\n");
157	(void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
158	    "cachefile\n");
159	(void) fprintf(stderr, "        -X attempt extreme rewind (does not "
160	    "work with dataset)\n");
161	(void) fprintf(stderr, "        -e pool is exported/destroyed/"
162	    "has altroot/not in a cachefile\n");
163	(void) fprintf(stderr, "        -p <path> -- use one or more with "
164	    "-e to specify path to vdev dir\n");
165	(void) fprintf(stderr, "        -P print numbers in parseable form\n");
166	(void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
167	    "searching for uberblocks\n");
168	(void) fprintf(stderr, "        -M <number of inflight I/Os> -- "
169	    "specify the maximum number of checksumming I/Os [default is 200]");
170	(void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
171	    "to make only that option verbose\n");
172	(void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
173	exit(1);
174}
175
176/*
177 * Called for usage errors that are discovered after a call to spa_open(),
178 * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
179 */
180
181static void
182fatal(const char *fmt, ...)
183{
184	va_list ap;
185
186	va_start(ap, fmt);
187	(void) fprintf(stderr, "%s: ", cmdname);
188	(void) vfprintf(stderr, fmt, ap);
189	va_end(ap);
190	(void) fprintf(stderr, "\n");
191
192	exit(1);
193}
194
195/* ARGSUSED */
196static void
197dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
198{
199	nvlist_t *nv;
200	size_t nvsize = *(uint64_t *)data;
201	char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
202
203	VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
204
205	VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
206
207	umem_free(packed, nvsize);
208
209	dump_nvlist(nv, 8);
210
211	nvlist_free(nv);
212}
213
214/* ARGSUSED */
215static void
216dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
217{
218	spa_history_phys_t *shp = data;
219
220	if (shp == NULL)
221		return;
222
223	(void) printf("\t\tpool_create_len = %llu\n",
224	    (u_longlong_t)shp->sh_pool_create_len);
225	(void) printf("\t\tphys_max_off = %llu\n",
226	    (u_longlong_t)shp->sh_phys_max_off);
227	(void) printf("\t\tbof = %llu\n",
228	    (u_longlong_t)shp->sh_bof);
229	(void) printf("\t\teof = %llu\n",
230	    (u_longlong_t)shp->sh_eof);
231	(void) printf("\t\trecords_lost = %llu\n",
232	    (u_longlong_t)shp->sh_records_lost);
233}
234
235static void
236zdb_nicenum(uint64_t num, char *buf)
237{
238	if (dump_opt['P'])
239		(void) sprintf(buf, "%llu", (longlong_t)num);
240	else
241		nicenum(num, buf);
242}
243
244const char dump_zap_stars[] = "****************************************";
245const int dump_zap_width = sizeof (dump_zap_stars) - 1;
246
247static void
248dump_zap_histogram(uint64_t histo[ZAP_HISTOGRAM_SIZE])
249{
250	int i;
251	int minidx = ZAP_HISTOGRAM_SIZE - 1;
252	int maxidx = 0;
253	uint64_t max = 0;
254
255	for (i = 0; i < ZAP_HISTOGRAM_SIZE; i++) {
256		if (histo[i] > max)
257			max = histo[i];
258		if (histo[i] > 0 && i > maxidx)
259			maxidx = i;
260		if (histo[i] > 0 && i < minidx)
261			minidx = i;
262	}
263
264	if (max < dump_zap_width)
265		max = dump_zap_width;
266
267	for (i = minidx; i <= maxidx; i++)
268		(void) printf("\t\t\t%u: %6llu %s\n", i, (u_longlong_t)histo[i],
269		    &dump_zap_stars[(max - histo[i]) * dump_zap_width / max]);
270}
271
272static void
273dump_zap_stats(objset_t *os, uint64_t object)
274{
275	int error;
276	zap_stats_t zs;
277
278	error = zap_get_stats(os, object, &zs);
279	if (error)
280		return;
281
282	if (zs.zs_ptrtbl_len == 0) {
283		ASSERT(zs.zs_num_blocks == 1);
284		(void) printf("\tmicrozap: %llu bytes, %llu entries\n",
285		    (u_longlong_t)zs.zs_blocksize,
286		    (u_longlong_t)zs.zs_num_entries);
287		return;
288	}
289
290	(void) printf("\tFat ZAP stats:\n");
291
292	(void) printf("\t\tPointer table:\n");
293	(void) printf("\t\t\t%llu elements\n",
294	    (u_longlong_t)zs.zs_ptrtbl_len);
295	(void) printf("\t\t\tzt_blk: %llu\n",
296	    (u_longlong_t)zs.zs_ptrtbl_zt_blk);
297	(void) printf("\t\t\tzt_numblks: %llu\n",
298	    (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
299	(void) printf("\t\t\tzt_shift: %llu\n",
300	    (u_longlong_t)zs.zs_ptrtbl_zt_shift);
301	(void) printf("\t\t\tzt_blks_copied: %llu\n",
302	    (u_longlong_t)zs.zs_ptrtbl_blks_copied);
303	(void) printf("\t\t\tzt_nextblk: %llu\n",
304	    (u_longlong_t)zs.zs_ptrtbl_nextblk);
305
306	(void) printf("\t\tZAP entries: %llu\n",
307	    (u_longlong_t)zs.zs_num_entries);
308	(void) printf("\t\tLeaf blocks: %llu\n",
309	    (u_longlong_t)zs.zs_num_leafs);
310	(void) printf("\t\tTotal blocks: %llu\n",
311	    (u_longlong_t)zs.zs_num_blocks);
312	(void) printf("\t\tzap_block_type: 0x%llx\n",
313	    (u_longlong_t)zs.zs_block_type);
314	(void) printf("\t\tzap_magic: 0x%llx\n",
315	    (u_longlong_t)zs.zs_magic);
316	(void) printf("\t\tzap_salt: 0x%llx\n",
317	    (u_longlong_t)zs.zs_salt);
318
319	(void) printf("\t\tLeafs with 2^n pointers:\n");
320	dump_zap_histogram(zs.zs_leafs_with_2n_pointers);
321
322	(void) printf("\t\tBlocks with n*5 entries:\n");
323	dump_zap_histogram(zs.zs_blocks_with_n5_entries);
324
325	(void) printf("\t\tBlocks n/10 full:\n");
326	dump_zap_histogram(zs.zs_blocks_n_tenths_full);
327
328	(void) printf("\t\tEntries with n chunks:\n");
329	dump_zap_histogram(zs.zs_entries_using_n_chunks);
330
331	(void) printf("\t\tBuckets with n entries:\n");
332	dump_zap_histogram(zs.zs_buckets_with_n_entries);
333}
334
335/*ARGSUSED*/
336static void
337dump_none(objset_t *os, uint64_t object, void *data, size_t size)
338{
339}
340
341/*ARGSUSED*/
342static void
343dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
344{
345	(void) printf("\tUNKNOWN OBJECT TYPE\n");
346}
347
348/*ARGSUSED*/
349void
350dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
351{
352}
353
354/*ARGSUSED*/
355static void
356dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
357{
358}
359
360/*ARGSUSED*/
361static void
362dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
363{
364	zap_cursor_t zc;
365	zap_attribute_t attr;
366	void *prop;
367	int i;
368
369	dump_zap_stats(os, object);
370	(void) printf("\n");
371
372	for (zap_cursor_init(&zc, os, object);
373	    zap_cursor_retrieve(&zc, &attr) == 0;
374	    zap_cursor_advance(&zc)) {
375		(void) printf("\t\t%s = ", attr.za_name);
376		if (attr.za_num_integers == 0) {
377			(void) printf("\n");
378			continue;
379		}
380		prop = umem_zalloc(attr.za_num_integers *
381		    attr.za_integer_length, UMEM_NOFAIL);
382		(void) zap_lookup(os, object, attr.za_name,
383		    attr.za_integer_length, attr.za_num_integers, prop);
384		if (attr.za_integer_length == 1) {
385			(void) printf("%s", (char *)prop);
386		} else {
387			for (i = 0; i < attr.za_num_integers; i++) {
388				switch (attr.za_integer_length) {
389				case 2:
390					(void) printf("%u ",
391					    ((uint16_t *)prop)[i]);
392					break;
393				case 4:
394					(void) printf("%u ",
395					    ((uint32_t *)prop)[i]);
396					break;
397				case 8:
398					(void) printf("%lld ",
399					    (u_longlong_t)((int64_t *)prop)[i]);
400					break;
401				}
402			}
403		}
404		(void) printf("\n");
405		umem_free(prop, attr.za_num_integers * attr.za_integer_length);
406	}
407	zap_cursor_fini(&zc);
408}
409
410/*ARGSUSED*/
411static void
412dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
413{
414	dump_zap_stats(os, object);
415	/* contents are printed elsewhere, properly decoded */
416}
417
418/*ARGSUSED*/
419static void
420dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
421{
422	zap_cursor_t zc;
423	zap_attribute_t attr;
424
425	dump_zap_stats(os, object);
426	(void) printf("\n");
427
428	for (zap_cursor_init(&zc, os, object);
429	    zap_cursor_retrieve(&zc, &attr) == 0;
430	    zap_cursor_advance(&zc)) {
431		(void) printf("\t\t%s = ", attr.za_name);
432		if (attr.za_num_integers == 0) {
433			(void) printf("\n");
434			continue;
435		}
436		(void) printf(" %llx : [%d:%d:%d]\n",
437		    (u_longlong_t)attr.za_first_integer,
438		    (int)ATTR_LENGTH(attr.za_first_integer),
439		    (int)ATTR_BSWAP(attr.za_first_integer),
440		    (int)ATTR_NUM(attr.za_first_integer));
441	}
442	zap_cursor_fini(&zc);
443}
444
445/*ARGSUSED*/
446static void
447dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
448{
449	zap_cursor_t zc;
450	zap_attribute_t attr;
451	uint16_t *layout_attrs;
452	int i;
453
454	dump_zap_stats(os, object);
455	(void) printf("\n");
456
457	for (zap_cursor_init(&zc, os, object);
458	    zap_cursor_retrieve(&zc, &attr) == 0;
459	    zap_cursor_advance(&zc)) {
460		(void) printf("\t\t%s = [", attr.za_name);
461		if (attr.za_num_integers == 0) {
462			(void) printf("\n");
463			continue;
464		}
465
466		VERIFY(attr.za_integer_length == 2);
467		layout_attrs = umem_zalloc(attr.za_num_integers *
468		    attr.za_integer_length, UMEM_NOFAIL);
469
470		VERIFY(zap_lookup(os, object, attr.za_name,
471		    attr.za_integer_length,
472		    attr.za_num_integers, layout_attrs) == 0);
473
474		for (i = 0; i != attr.za_num_integers; i++)
475			(void) printf(" %d ", (int)layout_attrs[i]);
476		(void) printf("]\n");
477		umem_free(layout_attrs,
478		    attr.za_num_integers * attr.za_integer_length);
479	}
480	zap_cursor_fini(&zc);
481}
482
483/*ARGSUSED*/
484static void
485dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
486{
487	zap_cursor_t zc;
488	zap_attribute_t attr;
489	const char *typenames[] = {
490		/* 0 */ "not specified",
491		/* 1 */ "FIFO",
492		/* 2 */ "Character Device",
493		/* 3 */ "3 (invalid)",
494		/* 4 */ "Directory",
495		/* 5 */ "5 (invalid)",
496		/* 6 */ "Block Device",
497		/* 7 */ "7 (invalid)",
498		/* 8 */ "Regular File",
499		/* 9 */ "9 (invalid)",
500		/* 10 */ "Symbolic Link",
501		/* 11 */ "11 (invalid)",
502		/* 12 */ "Socket",
503		/* 13 */ "Door",
504		/* 14 */ "Event Port",
505		/* 15 */ "15 (invalid)",
506	};
507
508	dump_zap_stats(os, object);
509	(void) printf("\n");
510
511	for (zap_cursor_init(&zc, os, object);
512	    zap_cursor_retrieve(&zc, &attr) == 0;
513	    zap_cursor_advance(&zc)) {
514		(void) printf("\t\t%s = %lld (type: %s)\n",
515		    attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
516		    typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
517	}
518	zap_cursor_fini(&zc);
519}
520
521static void
522dump_spacemap(objset_t *os, space_map_obj_t *smo, space_map_t *sm)
523{
524	uint64_t alloc, offset, entry;
525	uint8_t mapshift = sm->sm_shift;
526	uint64_t mapstart = sm->sm_start;
527	char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
528			    "INVALID", "INVALID", "INVALID", "INVALID" };
529
530	if (smo->smo_object == 0)
531		return;
532
533	/*
534	 * Print out the freelist entries in both encoded and decoded form.
535	 */
536	alloc = 0;
537	for (offset = 0; offset < smo->smo_objsize; offset += sizeof (entry)) {
538		VERIFY3U(0, ==, dmu_read(os, smo->smo_object, offset,
539		    sizeof (entry), &entry, DMU_READ_PREFETCH));
540		if (SM_DEBUG_DECODE(entry)) {
541			(void) printf("\t    [%6llu] %s: txg %llu, pass %llu\n",
542			    (u_longlong_t)(offset / sizeof (entry)),
543			    ddata[SM_DEBUG_ACTION_DECODE(entry)],
544			    (u_longlong_t)SM_DEBUG_TXG_DECODE(entry),
545			    (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(entry));
546		} else {
547			(void) printf("\t    [%6llu]    %c  range:"
548			    " %010llx-%010llx  size: %06llx\n",
549			    (u_longlong_t)(offset / sizeof (entry)),
550			    SM_TYPE_DECODE(entry) == SM_ALLOC ? 'A' : 'F',
551			    (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
552			    mapshift) + mapstart),
553			    (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
554			    mapshift) + mapstart + (SM_RUN_DECODE(entry) <<
555			    mapshift)),
556			    (u_longlong_t)(SM_RUN_DECODE(entry) << mapshift));
557			if (SM_TYPE_DECODE(entry) == SM_ALLOC)
558				alloc += SM_RUN_DECODE(entry) << mapshift;
559			else
560				alloc -= SM_RUN_DECODE(entry) << mapshift;
561		}
562	}
563	if (alloc != smo->smo_alloc) {
564		(void) printf("space_map_object alloc (%llu) INCONSISTENT "
565		    "with space map summary (%llu)\n",
566		    (u_longlong_t)smo->smo_alloc, (u_longlong_t)alloc);
567	}
568}
569
570static void
571dump_metaslab_stats(metaslab_t *msp)
572{
573	char maxbuf[32];
574	space_map_t *sm = msp->ms_map;
575	avl_tree_t *t = sm->sm_pp_root;
576	int free_pct = sm->sm_space * 100 / sm->sm_size;
577
578	zdb_nicenum(space_map_maxsize(sm), maxbuf);
579
580	(void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
581	    "segments", avl_numnodes(t), "maxsize", maxbuf,
582	    "freepct", free_pct);
583}
584
585static void
586dump_metaslab(metaslab_t *msp)
587{
588	vdev_t *vd = msp->ms_group->mg_vd;
589	spa_t *spa = vd->vdev_spa;
590	space_map_t *sm = msp->ms_map;
591	space_map_obj_t *smo = &msp->ms_smo;
592	char freebuf[32];
593
594	zdb_nicenum(sm->sm_size - smo->smo_alloc, freebuf);
595
596	(void) printf(
597	    "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
598	    (u_longlong_t)(sm->sm_start / sm->sm_size),
599	    (u_longlong_t)sm->sm_start, (u_longlong_t)smo->smo_object, freebuf);
600
601	if (dump_opt['m'] > 1 && !dump_opt['L']) {
602		mutex_enter(&msp->ms_lock);
603		space_map_load_wait(sm);
604		if (!sm->sm_loaded)
605			VERIFY(space_map_load(sm, zfs_metaslab_ops,
606			    SM_FREE, smo, spa->spa_meta_objset) == 0);
607		dump_metaslab_stats(msp);
608		space_map_unload(sm);
609		mutex_exit(&msp->ms_lock);
610	}
611
612	if (dump_opt['d'] > 5 || dump_opt['m'] > 2) {
613		ASSERT(sm->sm_size == (1ULL << vd->vdev_ms_shift));
614
615		mutex_enter(&msp->ms_lock);
616		dump_spacemap(spa->spa_meta_objset, smo, sm);
617		mutex_exit(&msp->ms_lock);
618	}
619}
620
621static void
622print_vdev_metaslab_header(vdev_t *vd)
623{
624	(void) printf("\tvdev %10llu\n\t%-10s%5llu   %-19s   %-15s   %-10s\n",
625	    (u_longlong_t)vd->vdev_id,
626	    "metaslabs", (u_longlong_t)vd->vdev_ms_count,
627	    "offset", "spacemap", "free");
628	(void) printf("\t%15s   %19s   %15s   %10s\n",
629	    "---------------", "-------------------",
630	    "---------------", "-------------");
631}
632
633static void
634dump_metaslabs(spa_t *spa)
635{
636	vdev_t *vd, *rvd = spa->spa_root_vdev;
637	uint64_t m, c = 0, children = rvd->vdev_children;
638
639	(void) printf("\nMetaslabs:\n");
640
641	if (!dump_opt['d'] && zopt_objects > 0) {
642		c = zopt_object[0];
643
644		if (c >= children)
645			(void) fatal("bad vdev id: %llu", (u_longlong_t)c);
646
647		if (zopt_objects > 1) {
648			vd = rvd->vdev_child[c];
649			print_vdev_metaslab_header(vd);
650
651			for (m = 1; m < zopt_objects; m++) {
652				if (zopt_object[m] < vd->vdev_ms_count)
653					dump_metaslab(
654					    vd->vdev_ms[zopt_object[m]]);
655				else
656					(void) fprintf(stderr, "bad metaslab "
657					    "number %llu\n",
658					    (u_longlong_t)zopt_object[m]);
659			}
660			(void) printf("\n");
661			return;
662		}
663		children = c + 1;
664	}
665	for (; c < children; c++) {
666		vd = rvd->vdev_child[c];
667		print_vdev_metaslab_header(vd);
668
669		for (m = 0; m < vd->vdev_ms_count; m++)
670			dump_metaslab(vd->vdev_ms[m]);
671		(void) printf("\n");
672	}
673}
674
675static void
676dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
677{
678	const ddt_phys_t *ddp = dde->dde_phys;
679	const ddt_key_t *ddk = &dde->dde_key;
680	char *types[4] = { "ditto", "single", "double", "triple" };
681	char blkbuf[BP_SPRINTF_LEN];
682	blkptr_t blk;
683
684	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
685		if (ddp->ddp_phys_birth == 0)
686			continue;
687		ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
688		sprintf_blkptr(blkbuf, &blk);
689		(void) printf("index %llx refcnt %llu %s %s\n",
690		    (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
691		    types[p], blkbuf);
692	}
693}
694
695static void
696dump_dedup_ratio(const ddt_stat_t *dds)
697{
698	double rL, rP, rD, D, dedup, compress, copies;
699
700	if (dds->dds_blocks == 0)
701		return;
702
703	rL = (double)dds->dds_ref_lsize;
704	rP = (double)dds->dds_ref_psize;
705	rD = (double)dds->dds_ref_dsize;
706	D = (double)dds->dds_dsize;
707
708	dedup = rD / D;
709	compress = rL / rP;
710	copies = rD / rP;
711
712	(void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
713	    "dedup * compress / copies = %.2f\n\n",
714	    dedup, compress, copies, dedup * compress / copies);
715}
716
717static void
718dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
719{
720	char name[DDT_NAMELEN];
721	ddt_entry_t dde;
722	uint64_t walk = 0;
723	dmu_object_info_t doi;
724	uint64_t count, dspace, mspace;
725	int error;
726
727	error = ddt_object_info(ddt, type, class, &doi);
728
729	if (error == ENOENT)
730		return;
731	ASSERT(error == 0);
732
733	if ((count = ddt_object_count(ddt, type, class)) == 0)
734		return;
735
736	dspace = doi.doi_physical_blocks_512 << 9;
737	mspace = doi.doi_fill_count * doi.doi_data_block_size;
738
739	ddt_object_name(ddt, type, class, name);
740
741	(void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
742	    name,
743	    (u_longlong_t)count,
744	    (u_longlong_t)(dspace / count),
745	    (u_longlong_t)(mspace / count));
746
747	if (dump_opt['D'] < 3)
748		return;
749
750	zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
751
752	if (dump_opt['D'] < 4)
753		return;
754
755	if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
756		return;
757
758	(void) printf("%s contents:\n\n", name);
759
760	while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
761		dump_dde(ddt, &dde, walk);
762
763	ASSERT(error == ENOENT);
764
765	(void) printf("\n");
766}
767
768static void
769dump_all_ddts(spa_t *spa)
770{
771	ddt_histogram_t ddh_total = { 0 };
772	ddt_stat_t dds_total = { 0 };
773
774	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
775		ddt_t *ddt = spa->spa_ddt[c];
776		for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
777			for (enum ddt_class class = 0; class < DDT_CLASSES;
778			    class++) {
779				dump_ddt(ddt, type, class);
780			}
781		}
782	}
783
784	ddt_get_dedup_stats(spa, &dds_total);
785
786	if (dds_total.dds_blocks == 0) {
787		(void) printf("All DDTs are empty\n");
788		return;
789	}
790
791	(void) printf("\n");
792
793	if (dump_opt['D'] > 1) {
794		(void) printf("DDT histogram (aggregated over all DDTs):\n");
795		ddt_get_dedup_histogram(spa, &ddh_total);
796		zpool_dump_ddt(&dds_total, &ddh_total);
797	}
798
799	dump_dedup_ratio(&dds_total);
800}
801
802static void
803dump_dtl_seg(space_map_t *sm, uint64_t start, uint64_t size)
804{
805	char *prefix = (void *)sm;
806
807	(void) printf("%s [%llu,%llu) length %llu\n",
808	    prefix,
809	    (u_longlong_t)start,
810	    (u_longlong_t)(start + size),
811	    (u_longlong_t)(size));
812}
813
814static void
815dump_dtl(vdev_t *vd, int indent)
816{
817	spa_t *spa = vd->vdev_spa;
818	boolean_t required;
819	char *name[DTL_TYPES] = { "missing", "partial", "scrub", "outage" };
820	char prefix[256];
821
822	spa_vdev_state_enter(spa, SCL_NONE);
823	required = vdev_dtl_required(vd);
824	(void) spa_vdev_state_exit(spa, NULL, 0);
825
826	if (indent == 0)
827		(void) printf("\nDirty time logs:\n\n");
828
829	(void) printf("\t%*s%s [%s]\n", indent, "",
830	    vd->vdev_path ? vd->vdev_path :
831	    vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
832	    required ? "DTL-required" : "DTL-expendable");
833
834	for (int t = 0; t < DTL_TYPES; t++) {
835		space_map_t *sm = &vd->vdev_dtl[t];
836		if (sm->sm_space == 0)
837			continue;
838		(void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
839		    indent + 2, "", name[t]);
840		mutex_enter(sm->sm_lock);
841		space_map_walk(sm, dump_dtl_seg, (void *)prefix);
842		mutex_exit(sm->sm_lock);
843		if (dump_opt['d'] > 5 && vd->vdev_children == 0)
844			dump_spacemap(spa->spa_meta_objset,
845			    &vd->vdev_dtl_smo, sm);
846	}
847
848	for (int c = 0; c < vd->vdev_children; c++)
849		dump_dtl(vd->vdev_child[c], indent + 4);
850}
851
852static void
853dump_history(spa_t *spa)
854{
855	nvlist_t **events = NULL;
856	char buf[SPA_MAXBLOCKSIZE];
857	uint64_t resid, len, off = 0;
858	uint_t num = 0;
859	int error;
860	time_t tsec;
861	struct tm t;
862	char tbuf[30];
863	char internalstr[MAXPATHLEN];
864
865	do {
866		len = sizeof (buf);
867
868		if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
869			(void) fprintf(stderr, "Unable to read history: "
870			    "error %d\n", error);
871			return;
872		}
873
874		if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
875			break;
876
877		off -= resid;
878	} while (len != 0);
879
880	(void) printf("\nHistory:\n");
881	for (int i = 0; i < num; i++) {
882		uint64_t time, txg, ievent;
883		char *cmd, *intstr;
884		boolean_t printed = B_FALSE;
885
886		if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
887		    &time) != 0)
888			goto next;
889		if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
890		    &cmd) != 0) {
891			if (nvlist_lookup_uint64(events[i],
892			    ZPOOL_HIST_INT_EVENT, &ievent) != 0)
893				goto next;
894			verify(nvlist_lookup_uint64(events[i],
895			    ZPOOL_HIST_TXG, &txg) == 0);
896			verify(nvlist_lookup_string(events[i],
897			    ZPOOL_HIST_INT_STR, &intstr) == 0);
898			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
899				goto next;
900
901			(void) snprintf(internalstr,
902			    sizeof (internalstr),
903			    "[internal %s txg:%lld] %s",
904			    zfs_history_event_names[ievent], txg,
905			    intstr);
906			cmd = internalstr;
907		}
908		tsec = time;
909		(void) localtime_r(&tsec, &t);
910		(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
911		(void) printf("%s %s\n", tbuf, cmd);
912		printed = B_TRUE;
913
914next:
915		if (dump_opt['h'] > 1) {
916			if (!printed)
917				(void) printf("unrecognized record:\n");
918			dump_nvlist(events[i], 2);
919		}
920	}
921}
922
923/*ARGSUSED*/
924static void
925dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
926{
927}
928
929static uint64_t
930blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp, const zbookmark_t *zb)
931{
932	if (dnp == NULL) {
933		ASSERT(zb->zb_level < 0);
934		if (zb->zb_object == 0)
935			return (zb->zb_blkid);
936		return (zb->zb_blkid * BP_GET_LSIZE(bp));
937	}
938
939	ASSERT(zb->zb_level >= 0);
940
941	return ((zb->zb_blkid <<
942	    (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
943	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
944}
945
946static void
947sprintf_blkptr_compact(char *blkbuf, const blkptr_t *bp)
948{
949	const dva_t *dva = bp->blk_dva;
950	int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
951
952	if (dump_opt['b'] >= 5) {
953		sprintf_blkptr(blkbuf, bp);
954		return;
955	}
956
957	blkbuf[0] = '\0';
958
959	for (int i = 0; i < ndvas; i++)
960		(void) sprintf(blkbuf + strlen(blkbuf), "%llu:%llx:%llx ",
961		    (u_longlong_t)DVA_GET_VDEV(&dva[i]),
962		    (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
963		    (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
964
965	(void) sprintf(blkbuf + strlen(blkbuf),
966	    "%llxL/%llxP F=%llu B=%llu/%llu",
967	    (u_longlong_t)BP_GET_LSIZE(bp),
968	    (u_longlong_t)BP_GET_PSIZE(bp),
969	    (u_longlong_t)bp->blk_fill,
970	    (u_longlong_t)bp->blk_birth,
971	    (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
972}
973
974static void
975print_indirect(blkptr_t *bp, const zbookmark_t *zb,
976    const dnode_phys_t *dnp)
977{
978	char blkbuf[BP_SPRINTF_LEN];
979	int l;
980
981	ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
982	ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
983
984	(void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
985
986	ASSERT(zb->zb_level >= 0);
987
988	for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
989		if (l == zb->zb_level) {
990			(void) printf("L%llx", (u_longlong_t)zb->zb_level);
991		} else {
992			(void) printf(" ");
993		}
994	}
995
996	sprintf_blkptr_compact(blkbuf, bp);
997	(void) printf("%s\n", blkbuf);
998}
999
1000static int
1001visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
1002    blkptr_t *bp, const zbookmark_t *zb)
1003{
1004	int err = 0;
1005
1006	if (bp->blk_birth == 0)
1007		return (0);
1008
1009	print_indirect(bp, zb, dnp);
1010
1011	if (BP_GET_LEVEL(bp) > 0) {
1012		uint32_t flags = ARC_WAIT;
1013		int i;
1014		blkptr_t *cbp;
1015		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1016		arc_buf_t *buf;
1017		uint64_t fill = 0;
1018
1019		err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
1020		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
1021		if (err)
1022			return (err);
1023		ASSERT(buf->b_data);
1024
1025		/* recursively visit blocks below this */
1026		cbp = buf->b_data;
1027		for (i = 0; i < epb; i++, cbp++) {
1028			zbookmark_t czb;
1029
1030			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1031			    zb->zb_level - 1,
1032			    zb->zb_blkid * epb + i);
1033			err = visit_indirect(spa, dnp, cbp, &czb);
1034			if (err)
1035				break;
1036			fill += cbp->blk_fill;
1037		}
1038		if (!err)
1039			ASSERT3U(fill, ==, bp->blk_fill);
1040		(void) arc_buf_remove_ref(buf, &buf);
1041	}
1042
1043	return (err);
1044}
1045
1046/*ARGSUSED*/
1047static void
1048dump_indirect(dnode_t *dn)
1049{
1050	dnode_phys_t *dnp = dn->dn_phys;
1051	int j;
1052	zbookmark_t czb;
1053
1054	(void) printf("Indirect blocks:\n");
1055
1056	SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1057	    dn->dn_object, dnp->dn_nlevels - 1, 0);
1058	for (j = 0; j < dnp->dn_nblkptr; j++) {
1059		czb.zb_blkid = j;
1060		(void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1061		    &dnp->dn_blkptr[j], &czb);
1062	}
1063
1064	(void) printf("\n");
1065}
1066
1067/*ARGSUSED*/
1068static void
1069dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1070{
1071	dsl_dir_phys_t *dd = data;
1072	time_t crtime;
1073	char nice[32];
1074
1075	if (dd == NULL)
1076		return;
1077
1078	ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1079
1080	crtime = dd->dd_creation_time;
1081	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1082	(void) printf("\t\thead_dataset_obj = %llu\n",
1083	    (u_longlong_t)dd->dd_head_dataset_obj);
1084	(void) printf("\t\tparent_dir_obj = %llu\n",
1085	    (u_longlong_t)dd->dd_parent_obj);
1086	(void) printf("\t\torigin_obj = %llu\n",
1087	    (u_longlong_t)dd->dd_origin_obj);
1088	(void) printf("\t\tchild_dir_zapobj = %llu\n",
1089	    (u_longlong_t)dd->dd_child_dir_zapobj);
1090	zdb_nicenum(dd->dd_used_bytes, nice);
1091	(void) printf("\t\tused_bytes = %s\n", nice);
1092	zdb_nicenum(dd->dd_compressed_bytes, nice);
1093	(void) printf("\t\tcompressed_bytes = %s\n", nice);
1094	zdb_nicenum(dd->dd_uncompressed_bytes, nice);
1095	(void) printf("\t\tuncompressed_bytes = %s\n", nice);
1096	zdb_nicenum(dd->dd_quota, nice);
1097	(void) printf("\t\tquota = %s\n", nice);
1098	zdb_nicenum(dd->dd_reserved, nice);
1099	(void) printf("\t\treserved = %s\n", nice);
1100	(void) printf("\t\tprops_zapobj = %llu\n",
1101	    (u_longlong_t)dd->dd_props_zapobj);
1102	(void) printf("\t\tdeleg_zapobj = %llu\n",
1103	    (u_longlong_t)dd->dd_deleg_zapobj);
1104	(void) printf("\t\tflags = %llx\n",
1105	    (u_longlong_t)dd->dd_flags);
1106
1107#define	DO(which) \
1108	zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice); \
1109	(void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1110	DO(HEAD);
1111	DO(SNAP);
1112	DO(CHILD);
1113	DO(CHILD_RSRV);
1114	DO(REFRSRV);
1115#undef DO
1116}
1117
1118/*ARGSUSED*/
1119static void
1120dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1121{
1122	dsl_dataset_phys_t *ds = data;
1123	time_t crtime;
1124	char used[32], compressed[32], uncompressed[32], unique[32];
1125	char blkbuf[BP_SPRINTF_LEN];
1126
1127	if (ds == NULL)
1128		return;
1129
1130	ASSERT(size == sizeof (*ds));
1131	crtime = ds->ds_creation_time;
1132	zdb_nicenum(ds->ds_referenced_bytes, used);
1133	zdb_nicenum(ds->ds_compressed_bytes, compressed);
1134	zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed);
1135	zdb_nicenum(ds->ds_unique_bytes, unique);
1136	sprintf_blkptr(blkbuf, &ds->ds_bp);
1137
1138	(void) printf("\t\tdir_obj = %llu\n",
1139	    (u_longlong_t)ds->ds_dir_obj);
1140	(void) printf("\t\tprev_snap_obj = %llu\n",
1141	    (u_longlong_t)ds->ds_prev_snap_obj);
1142	(void) printf("\t\tprev_snap_txg = %llu\n",
1143	    (u_longlong_t)ds->ds_prev_snap_txg);
1144	(void) printf("\t\tnext_snap_obj = %llu\n",
1145	    (u_longlong_t)ds->ds_next_snap_obj);
1146	(void) printf("\t\tsnapnames_zapobj = %llu\n",
1147	    (u_longlong_t)ds->ds_snapnames_zapobj);
1148	(void) printf("\t\tnum_children = %llu\n",
1149	    (u_longlong_t)ds->ds_num_children);
1150	(void) printf("\t\tuserrefs_obj = %llu\n",
1151	    (u_longlong_t)ds->ds_userrefs_obj);
1152	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1153	(void) printf("\t\tcreation_txg = %llu\n",
1154	    (u_longlong_t)ds->ds_creation_txg);
1155	(void) printf("\t\tdeadlist_obj = %llu\n",
1156	    (u_longlong_t)ds->ds_deadlist_obj);
1157	(void) printf("\t\tused_bytes = %s\n", used);
1158	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
1159	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1160	(void) printf("\t\tunique = %s\n", unique);
1161	(void) printf("\t\tfsid_guid = %llu\n",
1162	    (u_longlong_t)ds->ds_fsid_guid);
1163	(void) printf("\t\tguid = %llu\n",
1164	    (u_longlong_t)ds->ds_guid);
1165	(void) printf("\t\tflags = %llx\n",
1166	    (u_longlong_t)ds->ds_flags);
1167	(void) printf("\t\tnext_clones_obj = %llu\n",
1168	    (u_longlong_t)ds->ds_next_clones_obj);
1169	(void) printf("\t\tprops_obj = %llu\n",
1170	    (u_longlong_t)ds->ds_props_obj);
1171	(void) printf("\t\tbp = %s\n", blkbuf);
1172}
1173
1174/* ARGSUSED */
1175static int
1176dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1177{
1178	char blkbuf[BP_SPRINTF_LEN];
1179
1180	if (bp->blk_birth != 0) {
1181		sprintf_blkptr(blkbuf, bp);
1182		(void) printf("\t%s\n", blkbuf);
1183	}
1184	return (0);
1185}
1186
1187static void
1188dump_bptree(objset_t *os, uint64_t obj, char *name)
1189{
1190	char bytes[32];
1191	bptree_phys_t *bt;
1192	dmu_buf_t *db;
1193
1194	if (dump_opt['d'] < 3)
1195		return;
1196
1197	VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
1198	bt = db->db_data;
1199	zdb_nicenum(bt->bt_bytes, bytes);
1200	(void) printf("\n    %s: %llu datasets, %s\n",
1201	    name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
1202	dmu_buf_rele(db, FTAG);
1203
1204	if (dump_opt['d'] < 5)
1205		return;
1206
1207	(void) printf("\n");
1208
1209	(void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
1210}
1211
1212/* ARGSUSED */
1213static int
1214dump_bpobj_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1215{
1216	char blkbuf[BP_SPRINTF_LEN];
1217
1218	ASSERT(bp->blk_birth != 0);
1219	sprintf_blkptr_compact(blkbuf, bp);
1220	(void) printf("\t%s\n", blkbuf);
1221	return (0);
1222}
1223
1224static void
1225dump_bpobj(bpobj_t *bpo, char *name, int indent)
1226{
1227	char bytes[32];
1228	char comp[32];
1229	char uncomp[32];
1230
1231	if (dump_opt['d'] < 3)
1232		return;
1233
1234	zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes);
1235	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1236		zdb_nicenum(bpo->bpo_phys->bpo_comp, comp);
1237		zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp);
1238		(void) printf("    %*s: object %llu, %llu local blkptrs, "
1239		    "%llu subobjs, %s (%s/%s comp)\n",
1240		    indent * 8, name,
1241		    (u_longlong_t)bpo->bpo_object,
1242		    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1243		    (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1244		    bytes, comp, uncomp);
1245
1246		for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1247			uint64_t subobj;
1248			bpobj_t subbpo;
1249			int error;
1250			VERIFY0(dmu_read(bpo->bpo_os,
1251			    bpo->bpo_phys->bpo_subobjs,
1252			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1253			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1254			if (error != 0) {
1255				(void) printf("ERROR %u while trying to open "
1256				    "subobj id %llu\n",
1257				    error, (u_longlong_t)subobj);
1258				continue;
1259			}
1260			dump_bpobj(&subbpo, "subobj", indent + 1);
1261		}
1262	} else {
1263		(void) printf("    %*s: object %llu, %llu blkptrs, %s\n",
1264		    indent * 8, name,
1265		    (u_longlong_t)bpo->bpo_object,
1266		    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1267		    bytes);
1268	}
1269
1270	if (dump_opt['d'] < 5)
1271		return;
1272
1273
1274	if (indent == 0) {
1275		(void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1276		(void) printf("\n");
1277	}
1278}
1279
1280static void
1281dump_deadlist(dsl_deadlist_t *dl)
1282{
1283	dsl_deadlist_entry_t *dle;
1284	uint64_t unused;
1285	char bytes[32];
1286	char comp[32];
1287	char uncomp[32];
1288
1289	if (dump_opt['d'] < 3)
1290		return;
1291
1292	zdb_nicenum(dl->dl_phys->dl_used, bytes);
1293	zdb_nicenum(dl->dl_phys->dl_comp, comp);
1294	zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp);
1295	(void) printf("\n    Deadlist: %s (%s/%s comp)\n",
1296	    bytes, comp, uncomp);
1297
1298	if (dump_opt['d'] < 4)
1299		return;
1300
1301	(void) printf("\n");
1302
1303	/* force the tree to be loaded */
1304	dsl_deadlist_space_range(dl, 0, UINT64_MAX, &unused, &unused, &unused);
1305
1306	for (dle = avl_first(&dl->dl_tree); dle;
1307	    dle = AVL_NEXT(&dl->dl_tree, dle)) {
1308		if (dump_opt['d'] >= 5) {
1309			char buf[128];
1310			(void) snprintf(buf, sizeof (buf), "mintxg %llu -> ",
1311			    (longlong_t)dle->dle_mintxg,
1312			    (longlong_t)dle->dle_bpobj.bpo_object);
1313
1314			dump_bpobj(&dle->dle_bpobj, buf, 0);
1315		} else {
1316			(void) printf("mintxg %llu -> obj %llu\n",
1317			    (longlong_t)dle->dle_mintxg,
1318			    (longlong_t)dle->dle_bpobj.bpo_object);
1319
1320		}
1321	}
1322}
1323
1324static avl_tree_t idx_tree;
1325static avl_tree_t domain_tree;
1326static boolean_t fuid_table_loaded;
1327static boolean_t sa_loaded;
1328sa_attr_type_t *sa_attr_table;
1329
1330static void
1331fuid_table_destroy()
1332{
1333	if (fuid_table_loaded) {
1334		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1335		fuid_table_loaded = B_FALSE;
1336	}
1337}
1338
1339/*
1340 * print uid or gid information.
1341 * For normal POSIX id just the id is printed in decimal format.
1342 * For CIFS files with FUID the fuid is printed in hex followed by
1343 * the domain-rid string.
1344 */
1345static void
1346print_idstr(uint64_t id, const char *id_type)
1347{
1348	if (FUID_INDEX(id)) {
1349		char *domain;
1350
1351		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1352		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
1353		    (u_longlong_t)id, domain, (int)FUID_RID(id));
1354	} else {
1355		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1356	}
1357
1358}
1359
1360static void
1361dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
1362{
1363	uint32_t uid_idx, gid_idx;
1364
1365	uid_idx = FUID_INDEX(uid);
1366	gid_idx = FUID_INDEX(gid);
1367
1368	/* Load domain table, if not already loaded */
1369	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1370		uint64_t fuid_obj;
1371
1372		/* first find the fuid object.  It lives in the master node */
1373		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1374		    8, 1, &fuid_obj) == 0);
1375		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1376		(void) zfs_fuid_table_load(os, fuid_obj,
1377		    &idx_tree, &domain_tree);
1378		fuid_table_loaded = B_TRUE;
1379	}
1380
1381	print_idstr(uid, "uid");
1382	print_idstr(gid, "gid");
1383}
1384
1385/*ARGSUSED*/
1386static void
1387dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
1388{
1389	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
1390	sa_handle_t *hdl;
1391	uint64_t xattr, rdev, gen;
1392	uint64_t uid, gid, mode, fsize, parent, links;
1393	uint64_t pflags;
1394	uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
1395	time_t z_crtime, z_atime, z_mtime, z_ctime;
1396	sa_bulk_attr_t bulk[12];
1397	int idx = 0;
1398	int error;
1399
1400	if (!sa_loaded) {
1401		uint64_t sa_attrs = 0;
1402		uint64_t version;
1403
1404		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1405		    8, 1, &version) == 0);
1406		if (version >= ZPL_VERSION_SA) {
1407			VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1408			    8, 1, &sa_attrs) == 0);
1409		}
1410		if ((error = sa_setup(os, sa_attrs, zfs_attr_table,
1411		    ZPL_END, &sa_attr_table)) != 0) {
1412			(void) printf("sa_setup failed errno %d, can't "
1413			    "display znode contents\n", error);
1414			return;
1415		}
1416		sa_loaded = B_TRUE;
1417	}
1418
1419	if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
1420		(void) printf("Failed to get handle for SA znode\n");
1421		return;
1422	}
1423
1424	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
1425	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
1426	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
1427	    &links, 8);
1428	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
1429	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
1430	    &mode, 8);
1431	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
1432	    NULL, &parent, 8);
1433	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
1434	    &fsize, 8);
1435	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
1436	    acctm, 16);
1437	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
1438	    modtm, 16);
1439	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
1440	    crtm, 16);
1441	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
1442	    chgtm, 16);
1443	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
1444	    &pflags, 8);
1445
1446	if (sa_bulk_lookup(hdl, bulk, idx)) {
1447		(void) sa_handle_destroy(hdl);
1448		return;
1449	}
1450
1451	error = zfs_obj_to_path(os, object, path, sizeof (path));
1452	if (error != 0) {
1453		(void) snprintf(path, sizeof (path), "\?\?\?<object#%llu>",
1454		    (u_longlong_t)object);
1455	}
1456	if (dump_opt['d'] < 3) {
1457		(void) printf("\t%s\n", path);
1458		(void) sa_handle_destroy(hdl);
1459		return;
1460	}
1461
1462	z_crtime = (time_t)crtm[0];
1463	z_atime = (time_t)acctm[0];
1464	z_mtime = (time_t)modtm[0];
1465	z_ctime = (time_t)chgtm[0];
1466
1467	(void) printf("\tpath	%s\n", path);
1468	dump_uidgid(os, uid, gid);
1469	(void) printf("\tatime	%s", ctime(&z_atime));
1470	(void) printf("\tmtime	%s", ctime(&z_mtime));
1471	(void) printf("\tctime	%s", ctime(&z_ctime));
1472	(void) printf("\tcrtime	%s", ctime(&z_crtime));
1473	(void) printf("\tgen	%llu\n", (u_longlong_t)gen);
1474	(void) printf("\tmode	%llo\n", (u_longlong_t)mode);
1475	(void) printf("\tsize	%llu\n", (u_longlong_t)fsize);
1476	(void) printf("\tparent	%llu\n", (u_longlong_t)parent);
1477	(void) printf("\tlinks	%llu\n", (u_longlong_t)links);
1478	(void) printf("\tpflags	%llx\n", (u_longlong_t)pflags);
1479	if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
1480	    sizeof (uint64_t)) == 0)
1481		(void) printf("\txattr	%llu\n", (u_longlong_t)xattr);
1482	if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
1483	    sizeof (uint64_t)) == 0)
1484		(void) printf("\trdev	0x%016llx\n", (u_longlong_t)rdev);
1485	sa_handle_destroy(hdl);
1486}
1487
1488/*ARGSUSED*/
1489static void
1490dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
1491{
1492}
1493
1494/*ARGSUSED*/
1495static void
1496dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
1497{
1498}
1499
1500static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
1501	dump_none,		/* unallocated			*/
1502	dump_zap,		/* object directory		*/
1503	dump_uint64,		/* object array			*/
1504	dump_none,		/* packed nvlist		*/
1505	dump_packed_nvlist,	/* packed nvlist size		*/
1506	dump_none,		/* bplist			*/
1507	dump_none,		/* bplist header		*/
1508	dump_none,		/* SPA space map header		*/
1509	dump_none,		/* SPA space map		*/
1510	dump_none,		/* ZIL intent log		*/
1511	dump_dnode,		/* DMU dnode			*/
1512	dump_dmu_objset,	/* DMU objset			*/
1513	dump_dsl_dir,		/* DSL directory		*/
1514	dump_zap,		/* DSL directory child map	*/
1515	dump_zap,		/* DSL dataset snap map		*/
1516	dump_zap,		/* DSL props			*/
1517	dump_dsl_dataset,	/* DSL dataset			*/
1518	dump_znode,		/* ZFS znode			*/
1519	dump_acl,		/* ZFS V0 ACL			*/
1520	dump_uint8,		/* ZFS plain file		*/
1521	dump_zpldir,		/* ZFS directory		*/
1522	dump_zap,		/* ZFS master node		*/
1523	dump_zap,		/* ZFS delete queue		*/
1524	dump_uint8,		/* zvol object			*/
1525	dump_zap,		/* zvol prop			*/
1526	dump_uint8,		/* other uint8[]		*/
1527	dump_uint64,		/* other uint64[]		*/
1528	dump_zap,		/* other ZAP			*/
1529	dump_zap,		/* persistent error log		*/
1530	dump_uint8,		/* SPA history			*/
1531	dump_history_offsets,	/* SPA history offsets		*/
1532	dump_zap,		/* Pool properties		*/
1533	dump_zap,		/* DSL permissions		*/
1534	dump_acl,		/* ZFS ACL			*/
1535	dump_uint8,		/* ZFS SYSACL			*/
1536	dump_none,		/* FUID nvlist			*/
1537	dump_packed_nvlist,	/* FUID nvlist size		*/
1538	dump_zap,		/* DSL dataset next clones	*/
1539	dump_zap,		/* DSL scrub queue		*/
1540	dump_zap,		/* ZFS user/group used		*/
1541	dump_zap,		/* ZFS user/group quota		*/
1542	dump_zap,		/* snapshot refcount tags	*/
1543	dump_ddt_zap,		/* DDT ZAP object		*/
1544	dump_zap,		/* DDT statistics		*/
1545	dump_znode,		/* SA object			*/
1546	dump_zap,		/* SA Master Node		*/
1547	dump_sa_attrs,		/* SA attribute registration	*/
1548	dump_sa_layouts,	/* SA attribute layouts		*/
1549	dump_zap,		/* DSL scrub translations	*/
1550	dump_none,		/* fake dedup BP		*/
1551	dump_zap,		/* deadlist			*/
1552	dump_none,		/* deadlist hdr			*/
1553	dump_zap,		/* dsl clones			*/
1554	dump_none,		/* bpobj subobjs		*/
1555	dump_unknown,		/* Unknown type, must be last	*/
1556};
1557
1558static void
1559dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1560{
1561	dmu_buf_t *db = NULL;
1562	dmu_object_info_t doi;
1563	dnode_t *dn;
1564	void *bonus = NULL;
1565	size_t bsize = 0;
1566	char iblk[32], dblk[32], lsize[32], asize[32], fill[32];
1567	char bonus_size[32];
1568	char aux[50];
1569	int error;
1570
1571	if (*print_header) {
1572		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1573		    "Object", "lvl", "iblk", "dblk", "dsize", "lsize",
1574		    "%full", "type");
1575		*print_header = 0;
1576	}
1577
1578	if (object == 0) {
1579		dn = DMU_META_DNODE(os);
1580	} else {
1581		error = dmu_bonus_hold(os, object, FTAG, &db);
1582		if (error)
1583			fatal("dmu_bonus_hold(%llu) failed, errno %u",
1584			    object, error);
1585		bonus = db->db_data;
1586		bsize = db->db_size;
1587		dn = DB_DNODE((dmu_buf_impl_t *)db);
1588	}
1589	dmu_object_info_from_dnode(dn, &doi);
1590
1591	zdb_nicenum(doi.doi_metadata_block_size, iblk);
1592	zdb_nicenum(doi.doi_data_block_size, dblk);
1593	zdb_nicenum(doi.doi_max_offset, lsize);
1594	zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize);
1595	zdb_nicenum(doi.doi_bonus_size, bonus_size);
1596	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
1597	    doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
1598	    doi.doi_max_offset);
1599
1600	aux[0] = '\0';
1601
1602	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1603		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1604		    ZDB_CHECKSUM_NAME(doi.doi_checksum));
1605	}
1606
1607	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1608		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1609		    ZDB_COMPRESS_NAME(doi.doi_compress));
1610	}
1611
1612	(void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %6s  %s%s\n",
1613	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
1614	    asize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
1615
1616	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1617		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1618		    "", "", "", "", "", bonus_size, "bonus",
1619		    ZDB_OT_NAME(doi.doi_bonus_type));
1620	}
1621
1622	if (verbosity >= 4) {
1623		(void) printf("\tdnode flags: %s%s%s\n",
1624		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
1625		    "USED_BYTES " : "",
1626		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
1627		    "USERUSED_ACCOUNTED " : "",
1628		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
1629		    "SPILL_BLKPTR" : "");
1630		(void) printf("\tdnode maxblkid: %llu\n",
1631		    (longlong_t)dn->dn_phys->dn_maxblkid);
1632
1633		object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os, object,
1634		    bonus, bsize);
1635		object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object, NULL, 0);
1636		*print_header = 1;
1637	}
1638
1639	if (verbosity >= 5)
1640		dump_indirect(dn);
1641
1642	if (verbosity >= 5) {
1643		/*
1644		 * Report the list of segments that comprise the object.
1645		 */
1646		uint64_t start = 0;
1647		uint64_t end;
1648		uint64_t blkfill = 1;
1649		int minlvl = 1;
1650
1651		if (dn->dn_type == DMU_OT_DNODE) {
1652			minlvl = 0;
1653			blkfill = DNODES_PER_BLOCK;
1654		}
1655
1656		for (;;) {
1657			char segsize[32];
1658			error = dnode_next_offset(dn,
1659			    0, &start, minlvl, blkfill, 0);
1660			if (error)
1661				break;
1662			end = start;
1663			error = dnode_next_offset(dn,
1664			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
1665			zdb_nicenum(end - start, segsize);
1666			(void) printf("\t\tsegment [%016llx, %016llx)"
1667			    " size %5s\n", (u_longlong_t)start,
1668			    (u_longlong_t)end, segsize);
1669			if (error)
1670				break;
1671			start = end;
1672		}
1673	}
1674
1675	if (db != NULL)
1676		dmu_buf_rele(db, FTAG);
1677}
1678
1679static char *objset_types[DMU_OST_NUMTYPES] = {
1680	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1681
1682static void
1683dump_dir(objset_t *os)
1684{
1685	dmu_objset_stats_t dds;
1686	uint64_t object, object_count;
1687	uint64_t refdbytes, usedobjs, scratch;
1688	char numbuf[32];
1689	char blkbuf[BP_SPRINTF_LEN + 20];
1690	char osname[MAXNAMELEN];
1691	char *type = "UNKNOWN";
1692	int verbosity = dump_opt['d'];
1693	int print_header = 1;
1694	int i, error;
1695
1696	dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
1697	dmu_objset_fast_stat(os, &dds);
1698	dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
1699
1700	if (dds.dds_type < DMU_OST_NUMTYPES)
1701		type = objset_types[dds.dds_type];
1702
1703	if (dds.dds_type == DMU_OST_META) {
1704		dds.dds_creation_txg = TXG_INITIAL;
1705		usedobjs = os->os_rootbp->blk_fill;
1706		refdbytes = os->os_spa->spa_dsl_pool->
1707		    dp_mos_dir->dd_phys->dd_used_bytes;
1708	} else {
1709		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
1710	}
1711
1712	ASSERT3U(usedobjs, ==, os->os_rootbp->blk_fill);
1713
1714	zdb_nicenum(refdbytes, numbuf);
1715
1716	if (verbosity >= 4) {
1717		(void) sprintf(blkbuf, ", rootbp ");
1718		(void) sprintf_blkptr(blkbuf + strlen(blkbuf), os->os_rootbp);
1719	} else {
1720		blkbuf[0] = '\0';
1721	}
1722
1723	dmu_objset_name(os, osname);
1724
1725	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
1726	    "%s, %llu objects%s\n",
1727	    osname, type, (u_longlong_t)dmu_objset_id(os),
1728	    (u_longlong_t)dds.dds_creation_txg,
1729	    numbuf, (u_longlong_t)usedobjs, blkbuf);
1730
1731	if (zopt_objects != 0) {
1732		for (i = 0; i < zopt_objects; i++)
1733			dump_object(os, zopt_object[i], verbosity,
1734			    &print_header);
1735		(void) printf("\n");
1736		return;
1737	}
1738
1739	if (dump_opt['i'] != 0 || verbosity >= 2)
1740		dump_intent_log(dmu_objset_zil(os));
1741
1742	if (dmu_objset_ds(os) != NULL)
1743		dump_deadlist(&dmu_objset_ds(os)->ds_deadlist);
1744
1745	if (verbosity < 2)
1746		return;
1747
1748	if (os->os_rootbp->blk_birth == 0)
1749		return;
1750
1751	dump_object(os, 0, verbosity, &print_header);
1752	object_count = 0;
1753	if (DMU_USERUSED_DNODE(os) != NULL &&
1754	    DMU_USERUSED_DNODE(os)->dn_type != 0) {
1755		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header);
1756		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header);
1757	}
1758
1759	object = 0;
1760	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1761		dump_object(os, object, verbosity, &print_header);
1762		object_count++;
1763	}
1764
1765	ASSERT3U(object_count, ==, usedobjs);
1766
1767	(void) printf("\n");
1768
1769	if (error != ESRCH) {
1770		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
1771		abort();
1772	}
1773}
1774
1775static void
1776dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
1777{
1778	time_t timestamp = ub->ub_timestamp;
1779
1780	(void) printf(header ? header : "");
1781	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
1782	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
1783	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
1784	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
1785	(void) printf("\ttimestamp = %llu UTC = %s",
1786	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
1787	if (dump_opt['u'] >= 3) {
1788		char blkbuf[BP_SPRINTF_LEN];
1789		sprintf_blkptr(blkbuf, &ub->ub_rootbp);
1790		(void) printf("\trootbp = %s\n", blkbuf);
1791	}
1792	(void) printf(footer ? footer : "");
1793}
1794
1795static void
1796dump_config(spa_t *spa)
1797{
1798	dmu_buf_t *db;
1799	size_t nvsize = 0;
1800	int error = 0;
1801
1802
1803	error = dmu_bonus_hold(spa->spa_meta_objset,
1804	    spa->spa_config_object, FTAG, &db);
1805
1806	if (error == 0) {
1807		nvsize = *(uint64_t *)db->db_data;
1808		dmu_buf_rele(db, FTAG);
1809
1810		(void) printf("\nMOS Configuration:\n");
1811		dump_packed_nvlist(spa->spa_meta_objset,
1812		    spa->spa_config_object, (void *)&nvsize, 1);
1813	} else {
1814		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
1815		    (u_longlong_t)spa->spa_config_object, error);
1816	}
1817}
1818
1819static void
1820dump_cachefile(const char *cachefile)
1821{
1822	int fd;
1823	struct stat64 statbuf;
1824	char *buf;
1825	nvlist_t *config;
1826
1827	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
1828		(void) printf("cannot open '%s': %s\n", cachefile,
1829		    strerror(errno));
1830		exit(1);
1831	}
1832
1833	if (fstat64(fd, &statbuf) != 0) {
1834		(void) printf("failed to stat '%s': %s\n", cachefile,
1835		    strerror(errno));
1836		exit(1);
1837	}
1838
1839	if ((buf = malloc(statbuf.st_size)) == NULL) {
1840		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
1841		    (u_longlong_t)statbuf.st_size);
1842		exit(1);
1843	}
1844
1845	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1846		(void) fprintf(stderr, "failed to read %llu bytes\n",
1847		    (u_longlong_t)statbuf.st_size);
1848		exit(1);
1849	}
1850
1851	(void) close(fd);
1852
1853	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
1854		(void) fprintf(stderr, "failed to unpack nvlist\n");
1855		exit(1);
1856	}
1857
1858	free(buf);
1859
1860	dump_nvlist(config, 0);
1861
1862	nvlist_free(config);
1863}
1864
1865#define	ZDB_MAX_UB_HEADER_SIZE 32
1866
1867static void
1868dump_label_uberblocks(vdev_label_t *lbl, uint64_t ashift)
1869{
1870	vdev_t vd;
1871	vdev_t *vdp = &vd;
1872	char header[ZDB_MAX_UB_HEADER_SIZE];
1873
1874	vd.vdev_ashift = ashift;
1875	vdp->vdev_top = vdp;
1876
1877	for (int i = 0; i < VDEV_UBERBLOCK_COUNT(vdp); i++) {
1878		uint64_t uoff = VDEV_UBERBLOCK_OFFSET(vdp, i);
1879		uberblock_t *ub = (void *)((char *)lbl + uoff);
1880
1881		if (uberblock_verify(ub))
1882			continue;
1883		(void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
1884		    "Uberblock[%d]\n", i);
1885		dump_uberblock(ub, header, "");
1886	}
1887}
1888
1889static void
1890dump_label(const char *dev)
1891{
1892	int fd;
1893	vdev_label_t label;
1894	char *path, *buf = label.vl_vdev_phys.vp_nvlist;
1895	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1896	struct stat64 statbuf;
1897	uint64_t psize, ashift;
1898	int len = strlen(dev) + 1;
1899
1900	if (strncmp(dev, "/dev/dsk/", 9) == 0) {
1901		len++;
1902		path = malloc(len);
1903		(void) snprintf(path, len, "%s%s", "/dev/rdsk/", dev + 9);
1904	} else {
1905		path = strdup(dev);
1906	}
1907
1908	if ((fd = open64(path, O_RDONLY)) < 0) {
1909		(void) printf("cannot open '%s': %s\n", path, strerror(errno));
1910		free(path);
1911		exit(1);
1912	}
1913
1914	if (fstat64(fd, &statbuf) != 0) {
1915		(void) printf("failed to stat '%s': %s\n", path,
1916		    strerror(errno));
1917		free(path);
1918		(void) close(fd);
1919		exit(1);
1920	}
1921
1922	if (S_ISBLK(statbuf.st_mode)) {
1923		(void) printf("cannot use '%s': character device required\n",
1924		    path);
1925		free(path);
1926		(void) close(fd);
1927		exit(1);
1928	}
1929
1930	psize = statbuf.st_size;
1931	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
1932
1933	for (int l = 0; l < VDEV_LABELS; l++) {
1934		nvlist_t *config = NULL;
1935
1936		(void) printf("--------------------------------------------\n");
1937		(void) printf("LABEL %d\n", l);
1938		(void) printf("--------------------------------------------\n");
1939
1940		if (pread64(fd, &label, sizeof (label),
1941		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
1942			(void) printf("failed to read label %d\n", l);
1943			continue;
1944		}
1945
1946		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
1947			(void) printf("failed to unpack label %d\n", l);
1948			ashift = SPA_MINBLOCKSHIFT;
1949		} else {
1950			nvlist_t *vdev_tree = NULL;
1951
1952			dump_nvlist(config, 4);
1953			if ((nvlist_lookup_nvlist(config,
1954			    ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
1955			    (nvlist_lookup_uint64(vdev_tree,
1956			    ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
1957				ashift = SPA_MINBLOCKSHIFT;
1958			nvlist_free(config);
1959		}
1960		if (dump_opt['u'])
1961			dump_label_uberblocks(&label, ashift);
1962	}
1963
1964	free(path);
1965	(void) close(fd);
1966}
1967
1968/*ARGSUSED*/
1969static int
1970dump_one_dir(const char *dsname, void *arg)
1971{
1972	int error;
1973	objset_t *os;
1974
1975	error = dmu_objset_own(dsname, DMU_OST_ANY, B_TRUE, FTAG, &os);
1976	if (error) {
1977		(void) printf("Could not open %s, error %d\n", dsname, error);
1978		return (0);
1979	}
1980	dump_dir(os);
1981	dmu_objset_disown(os, FTAG);
1982	fuid_table_destroy();
1983	sa_loaded = B_FALSE;
1984	return (0);
1985}
1986
1987/*
1988 * Block statistics.
1989 */
1990typedef struct zdb_blkstats {
1991	uint64_t	zb_asize;
1992	uint64_t	zb_lsize;
1993	uint64_t	zb_psize;
1994	uint64_t	zb_count;
1995} zdb_blkstats_t;
1996
1997/*
1998 * Extended object types to report deferred frees and dedup auto-ditto blocks.
1999 */
2000#define	ZDB_OT_DEFERRED	(DMU_OT_NUMTYPES + 0)
2001#define	ZDB_OT_DITTO	(DMU_OT_NUMTYPES + 1)
2002#define	ZDB_OT_OTHER	(DMU_OT_NUMTYPES + 2)
2003#define	ZDB_OT_TOTAL	(DMU_OT_NUMTYPES + 3)
2004
2005static char *zdb_ot_extname[] = {
2006	"deferred free",
2007	"dedup ditto",
2008	"other",
2009	"Total",
2010};
2011
2012#define	ZB_TOTAL	DN_MAX_LEVELS
2013
2014typedef struct zdb_cb {
2015	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
2016	uint64_t	zcb_dedup_asize;
2017	uint64_t	zcb_dedup_blocks;
2018	uint64_t	zcb_errors[256];
2019	int		zcb_readfails;
2020	int		zcb_haderrors;
2021	spa_t		*zcb_spa;
2022} zdb_cb_t;
2023
2024static void
2025zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
2026    dmu_object_type_t type)
2027{
2028	uint64_t refcnt = 0;
2029
2030	ASSERT(type < ZDB_OT_TOTAL);
2031
2032	if (zilog && zil_bp_tree_add(zilog, bp) != 0)
2033		return;
2034
2035	for (int i = 0; i < 4; i++) {
2036		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
2037		int t = (i & 1) ? type : ZDB_OT_TOTAL;
2038		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
2039
2040		zb->zb_asize += BP_GET_ASIZE(bp);
2041		zb->zb_lsize += BP_GET_LSIZE(bp);
2042		zb->zb_psize += BP_GET_PSIZE(bp);
2043		zb->zb_count++;
2044	}
2045
2046	if (dump_opt['L'])
2047		return;
2048
2049	if (BP_GET_DEDUP(bp)) {
2050		ddt_t *ddt;
2051		ddt_entry_t *dde;
2052
2053		ddt = ddt_select(zcb->zcb_spa, bp);
2054		ddt_enter(ddt);
2055		dde = ddt_lookup(ddt, bp, B_FALSE);
2056
2057		if (dde == NULL) {
2058			refcnt = 0;
2059		} else {
2060			ddt_phys_t *ddp = ddt_phys_select(dde, bp);
2061			ddt_phys_decref(ddp);
2062			refcnt = ddp->ddp_refcnt;
2063			if (ddt_phys_total_refcnt(dde) == 0)
2064				ddt_remove(ddt, dde);
2065		}
2066		ddt_exit(ddt);
2067	}
2068
2069	VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
2070	    refcnt ? 0 : spa_first_txg(zcb->zcb_spa),
2071	    bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
2072}
2073
2074static void
2075zdb_blkptr_done(zio_t *zio)
2076{
2077	spa_t *spa = zio->io_spa;
2078	blkptr_t *bp = zio->io_bp;
2079	int ioerr = zio->io_error;
2080	zdb_cb_t *zcb = zio->io_private;
2081	zbookmark_t *zb = &zio->io_bookmark;
2082
2083	zio_data_buf_free(zio->io_data, zio->io_size);
2084
2085	mutex_enter(&spa->spa_scrub_lock);
2086	spa->spa_scrub_inflight--;
2087	cv_broadcast(&spa->spa_scrub_io_cv);
2088
2089	if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
2090		char blkbuf[BP_SPRINTF_LEN];
2091
2092		zcb->zcb_haderrors = 1;
2093		zcb->zcb_errors[ioerr]++;
2094
2095		if (dump_opt['b'] >= 2)
2096			sprintf_blkptr(blkbuf, bp);
2097		else
2098			blkbuf[0] = '\0';
2099
2100		(void) printf("zdb_blkptr_cb: "
2101		    "Got error %d reading "
2102		    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
2103		    ioerr,
2104		    (u_longlong_t)zb->zb_objset,
2105		    (u_longlong_t)zb->zb_object,
2106		    (u_longlong_t)zb->zb_level,
2107		    (u_longlong_t)zb->zb_blkid,
2108		    blkbuf);
2109	}
2110	mutex_exit(&spa->spa_scrub_lock);
2111}
2112
2113static int
2114zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2115    const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
2116{
2117	zdb_cb_t *zcb = arg;
2118	char blkbuf[BP_SPRINTF_LEN];
2119	dmu_object_type_t type;
2120	boolean_t is_metadata;
2121
2122	if (bp == NULL)
2123		return (0);
2124
2125	type = BP_GET_TYPE(bp);
2126
2127	zdb_count_block(zcb, zilog, bp,
2128	    (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
2129
2130	is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
2131
2132	if (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata)) {
2133		size_t size = BP_GET_PSIZE(bp);
2134		void *data = zio_data_buf_alloc(size);
2135		int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
2136
2137		/* If it's an intent log block, failure is expected. */
2138		if (zb->zb_level == ZB_ZIL_LEVEL)
2139			flags |= ZIO_FLAG_SPECULATIVE;
2140
2141		mutex_enter(&spa->spa_scrub_lock);
2142		while (spa->spa_scrub_inflight > max_inflight)
2143			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2144		spa->spa_scrub_inflight++;
2145		mutex_exit(&spa->spa_scrub_lock);
2146
2147		zio_nowait(zio_read(NULL, spa, bp, data, size,
2148		    zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
2149	}
2150
2151	zcb->zcb_readfails = 0;
2152
2153	if (dump_opt['b'] >= 4) {
2154		sprintf_blkptr(blkbuf, bp);
2155		(void) printf("objset %llu object %llu "
2156		    "level %lld offset 0x%llx %s\n",
2157		    (u_longlong_t)zb->zb_objset,
2158		    (u_longlong_t)zb->zb_object,
2159		    (longlong_t)zb->zb_level,
2160		    (u_longlong_t)blkid2offset(dnp, bp, zb),
2161		    blkbuf);
2162	}
2163
2164	return (0);
2165}
2166
2167static void
2168zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
2169{
2170	vdev_t *vd = sm->sm_ppd;
2171
2172	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
2173	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
2174}
2175
2176/* ARGSUSED */
2177static void
2178zdb_space_map_load(space_map_t *sm)
2179{
2180}
2181
2182static void
2183zdb_space_map_unload(space_map_t *sm)
2184{
2185	space_map_vacate(sm, zdb_leak, sm);
2186}
2187
2188/* ARGSUSED */
2189static void
2190zdb_space_map_claim(space_map_t *sm, uint64_t start, uint64_t size)
2191{
2192}
2193
2194static space_map_ops_t zdb_space_map_ops = {
2195	zdb_space_map_load,
2196	zdb_space_map_unload,
2197	NULL,	/* alloc */
2198	zdb_space_map_claim,
2199	NULL,	/* free */
2200	NULL	/* maxsize */
2201};
2202
2203static void
2204zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
2205{
2206	ddt_bookmark_t ddb = { 0 };
2207	ddt_entry_t dde;
2208	int error;
2209
2210	while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
2211		blkptr_t blk;
2212		ddt_phys_t *ddp = dde.dde_phys;
2213
2214		if (ddb.ddb_class == DDT_CLASS_UNIQUE)
2215			return;
2216
2217		ASSERT(ddt_phys_total_refcnt(&dde) > 1);
2218
2219		for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2220			if (ddp->ddp_phys_birth == 0)
2221				continue;
2222			ddt_bp_create(ddb.ddb_checksum,
2223			    &dde.dde_key, ddp, &blk);
2224			if (p == DDT_PHYS_DITTO) {
2225				zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
2226			} else {
2227				zcb->zcb_dedup_asize +=
2228				    BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
2229				zcb->zcb_dedup_blocks++;
2230			}
2231		}
2232		if (!dump_opt['L']) {
2233			ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
2234			ddt_enter(ddt);
2235			VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
2236			ddt_exit(ddt);
2237		}
2238	}
2239
2240	ASSERT(error == ENOENT);
2241}
2242
2243static void
2244zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
2245{
2246	zcb->zcb_spa = spa;
2247
2248	if (!dump_opt['L']) {
2249		vdev_t *rvd = spa->spa_root_vdev;
2250		for (int c = 0; c < rvd->vdev_children; c++) {
2251			vdev_t *vd = rvd->vdev_child[c];
2252			for (int m = 0; m < vd->vdev_ms_count; m++) {
2253				metaslab_t *msp = vd->vdev_ms[m];
2254				mutex_enter(&msp->ms_lock);
2255				space_map_unload(msp->ms_map);
2256				VERIFY(space_map_load(msp->ms_map,
2257				    &zdb_space_map_ops, SM_ALLOC, &msp->ms_smo,
2258				    spa->spa_meta_objset) == 0);
2259				msp->ms_map->sm_ppd = vd;
2260				mutex_exit(&msp->ms_lock);
2261			}
2262		}
2263	}
2264
2265	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2266
2267	zdb_ddt_leak_init(spa, zcb);
2268
2269	spa_config_exit(spa, SCL_CONFIG, FTAG);
2270}
2271
2272static void
2273zdb_leak_fini(spa_t *spa)
2274{
2275	if (!dump_opt['L']) {
2276		vdev_t *rvd = spa->spa_root_vdev;
2277		for (int c = 0; c < rvd->vdev_children; c++) {
2278			vdev_t *vd = rvd->vdev_child[c];
2279			for (int m = 0; m < vd->vdev_ms_count; m++) {
2280				metaslab_t *msp = vd->vdev_ms[m];
2281				mutex_enter(&msp->ms_lock);
2282				space_map_unload(msp->ms_map);
2283				mutex_exit(&msp->ms_lock);
2284			}
2285		}
2286	}
2287}
2288
2289/* ARGSUSED */
2290static int
2291count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2292{
2293	zdb_cb_t *zcb = arg;
2294
2295	if (dump_opt['b'] >= 4) {
2296		char blkbuf[BP_SPRINTF_LEN];
2297		sprintf_blkptr(blkbuf, bp);
2298		(void) printf("[%s] %s\n",
2299		    "deferred free", blkbuf);
2300	}
2301	zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
2302	return (0);
2303}
2304
2305static int
2306dump_block_stats(spa_t *spa)
2307{
2308	zdb_cb_t zcb = { 0 };
2309	zdb_blkstats_t *zb, *tzb;
2310	uint64_t norm_alloc, norm_space, total_alloc, total_found;
2311	int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA | TRAVERSE_HARD;
2312	int leaks = 0;
2313
2314	(void) printf("\nTraversing all blocks %s%s%s%s%s...\n",
2315	    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
2316	    (dump_opt['c'] == 1) ? "metadata " : "",
2317	    dump_opt['c'] ? "checksums " : "",
2318	    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
2319	    !dump_opt['L'] ? "nothing leaked " : "");
2320
2321	/*
2322	 * Load all space maps as SM_ALLOC maps, then traverse the pool
2323	 * claiming each block we discover.  If the pool is perfectly
2324	 * consistent, the space maps will be empty when we're done.
2325	 * Anything left over is a leak; any block we can't claim (because
2326	 * it's not part of any space map) is a double allocation,
2327	 * reference to a freed block, or an unclaimed log block.
2328	 */
2329	zdb_leak_init(spa, &zcb);
2330
2331	/*
2332	 * If there's a deferred-free bplist, process that first.
2333	 */
2334	(void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
2335	    count_block_cb, &zcb, NULL);
2336	if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
2337		(void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
2338		    count_block_cb, &zcb, NULL);
2339	}
2340	if (spa_feature_is_active(spa,
2341	    &spa_feature_table[SPA_FEATURE_ASYNC_DESTROY])) {
2342		VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
2343		    spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
2344		    &zcb, NULL));
2345	}
2346
2347	if (dump_opt['c'] > 1)
2348		flags |= TRAVERSE_PREFETCH_DATA;
2349
2350	zcb.zcb_haderrors |= traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
2351
2352	/*
2353	 * If we've traversed the data blocks then we need to wait for those
2354	 * I/Os to complete. We leverage "The Godfather" zio to wait on
2355	 * all async I/Os to complete.
2356	 */
2357	if (dump_opt['c']) {
2358		(void) zio_wait(spa->spa_async_zio_root);
2359		spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
2360		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2361		    ZIO_FLAG_GODFATHER);
2362	}
2363
2364	if (zcb.zcb_haderrors) {
2365		(void) printf("\nError counts:\n\n");
2366		(void) printf("\t%5s  %s\n", "errno", "count");
2367		for (int e = 0; e < 256; e++) {
2368			if (zcb.zcb_errors[e] != 0) {
2369				(void) printf("\t%5d  %llu\n",
2370				    e, (u_longlong_t)zcb.zcb_errors[e]);
2371			}
2372		}
2373	}
2374
2375	/*
2376	 * Report any leaked segments.
2377	 */
2378	zdb_leak_fini(spa);
2379
2380	tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
2381
2382	norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
2383	norm_space = metaslab_class_get_space(spa_normal_class(spa));
2384
2385	total_alloc = norm_alloc + metaslab_class_get_alloc(spa_log_class(spa));
2386	total_found = tzb->zb_asize - zcb.zcb_dedup_asize;
2387
2388	if (total_found == total_alloc) {
2389		if (!dump_opt['L'])
2390			(void) printf("\n\tNo leaks (block sum matches space"
2391			    " maps exactly)\n");
2392	} else {
2393		(void) printf("block traversal size %llu != alloc %llu "
2394		    "(%s %lld)\n",
2395		    (u_longlong_t)total_found,
2396		    (u_longlong_t)total_alloc,
2397		    (dump_opt['L']) ? "unreachable" : "leaked",
2398		    (longlong_t)(total_alloc - total_found));
2399		leaks = 1;
2400	}
2401
2402	if (tzb->zb_count == 0)
2403		return (2);
2404
2405	(void) printf("\n");
2406	(void) printf("\tbp count:      %10llu\n",
2407	    (u_longlong_t)tzb->zb_count);
2408	(void) printf("\tbp logical:    %10llu      avg: %6llu\n",
2409	    (u_longlong_t)tzb->zb_lsize,
2410	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
2411	(void) printf("\tbp physical:   %10llu      avg:"
2412	    " %6llu     compression: %6.2f\n",
2413	    (u_longlong_t)tzb->zb_psize,
2414	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
2415	    (double)tzb->zb_lsize / tzb->zb_psize);
2416	(void) printf("\tbp allocated:  %10llu      avg:"
2417	    " %6llu     compression: %6.2f\n",
2418	    (u_longlong_t)tzb->zb_asize,
2419	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
2420	    (double)tzb->zb_lsize / tzb->zb_asize);
2421	(void) printf("\tbp deduped:    %10llu    ref>1:"
2422	    " %6llu   deduplication: %6.2f\n",
2423	    (u_longlong_t)zcb.zcb_dedup_asize,
2424	    (u_longlong_t)zcb.zcb_dedup_blocks,
2425	    (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
2426	(void) printf("\tSPA allocated: %10llu     used: %5.2f%%\n",
2427	    (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
2428
2429	if (dump_opt['b'] >= 2) {
2430		int l, t, level;
2431		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
2432		    "\t  avg\t comp\t%%Total\tType\n");
2433
2434		for (t = 0; t <= ZDB_OT_TOTAL; t++) {
2435			char csize[32], lsize[32], psize[32], asize[32];
2436			char avg[32];
2437			char *typename;
2438
2439			if (t < DMU_OT_NUMTYPES)
2440				typename = dmu_ot[t].ot_name;
2441			else
2442				typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
2443
2444			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
2445				(void) printf("%6s\t%5s\t%5s\t%5s"
2446				    "\t%5s\t%5s\t%6s\t%s\n",
2447				    "-",
2448				    "-",
2449				    "-",
2450				    "-",
2451				    "-",
2452				    "-",
2453				    "-",
2454				    typename);
2455				continue;
2456			}
2457
2458			for (l = ZB_TOTAL - 1; l >= -1; l--) {
2459				level = (l == -1 ? ZB_TOTAL : l);
2460				zb = &zcb.zcb_type[level][t];
2461
2462				if (zb->zb_asize == 0)
2463					continue;
2464
2465				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
2466					continue;
2467
2468				if (level == 0 && zb->zb_asize ==
2469				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
2470					continue;
2471
2472				zdb_nicenum(zb->zb_count, csize);
2473				zdb_nicenum(zb->zb_lsize, lsize);
2474				zdb_nicenum(zb->zb_psize, psize);
2475				zdb_nicenum(zb->zb_asize, asize);
2476				zdb_nicenum(zb->zb_asize / zb->zb_count, avg);
2477
2478				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
2479				    "\t%5.2f\t%6.2f\t",
2480				    csize, lsize, psize, asize, avg,
2481				    (double)zb->zb_lsize / zb->zb_psize,
2482				    100.0 * zb->zb_asize / tzb->zb_asize);
2483
2484				if (level == ZB_TOTAL)
2485					(void) printf("%s\n", typename);
2486				else
2487					(void) printf("    L%d %s\n",
2488					    level, typename);
2489			}
2490		}
2491	}
2492
2493	(void) printf("\n");
2494
2495	if (leaks)
2496		return (2);
2497
2498	if (zcb.zcb_haderrors)
2499		return (3);
2500
2501	return (0);
2502}
2503
2504typedef struct zdb_ddt_entry {
2505	ddt_key_t	zdde_key;
2506	uint64_t	zdde_ref_blocks;
2507	uint64_t	zdde_ref_lsize;
2508	uint64_t	zdde_ref_psize;
2509	uint64_t	zdde_ref_dsize;
2510	avl_node_t	zdde_node;
2511} zdb_ddt_entry_t;
2512
2513/* ARGSUSED */
2514static int
2515zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2516    const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
2517{
2518	avl_tree_t *t = arg;
2519	avl_index_t where;
2520	zdb_ddt_entry_t *zdde, zdde_search;
2521
2522	if (bp == NULL)
2523		return (0);
2524
2525	if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
2526		(void) printf("traversing objset %llu, %llu objects, "
2527		    "%lu blocks so far\n",
2528		    (u_longlong_t)zb->zb_objset,
2529		    (u_longlong_t)bp->blk_fill,
2530		    avl_numnodes(t));
2531	}
2532
2533	if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
2534	    BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
2535		return (0);
2536
2537	ddt_key_fill(&zdde_search.zdde_key, bp);
2538
2539	zdde = avl_find(t, &zdde_search, &where);
2540
2541	if (zdde == NULL) {
2542		zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
2543		zdde->zdde_key = zdde_search.zdde_key;
2544		avl_insert(t, zdde, where);
2545	}
2546
2547	zdde->zdde_ref_blocks += 1;
2548	zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
2549	zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
2550	zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
2551
2552	return (0);
2553}
2554
2555static void
2556dump_simulated_ddt(spa_t *spa)
2557{
2558	avl_tree_t t;
2559	void *cookie = NULL;
2560	zdb_ddt_entry_t *zdde;
2561	ddt_histogram_t ddh_total = { 0 };
2562	ddt_stat_t dds_total = { 0 };
2563
2564	avl_create(&t, ddt_entry_compare,
2565	    sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
2566
2567	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2568
2569	(void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2570	    zdb_ddt_add_cb, &t);
2571
2572	spa_config_exit(spa, SCL_CONFIG, FTAG);
2573
2574	while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
2575		ddt_stat_t dds;
2576		uint64_t refcnt = zdde->zdde_ref_blocks;
2577		ASSERT(refcnt != 0);
2578
2579		dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
2580		dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
2581		dds.dds_psize = zdde->zdde_ref_psize / refcnt;
2582		dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
2583
2584		dds.dds_ref_blocks = zdde->zdde_ref_blocks;
2585		dds.dds_ref_lsize = zdde->zdde_ref_lsize;
2586		dds.dds_ref_psize = zdde->zdde_ref_psize;
2587		dds.dds_ref_dsize = zdde->zdde_ref_dsize;
2588
2589		ddt_stat_add(&ddh_total.ddh_stat[highbit(refcnt) - 1], &dds, 0);
2590
2591		umem_free(zdde, sizeof (*zdde));
2592	}
2593
2594	avl_destroy(&t);
2595
2596	ddt_histogram_stat(&dds_total, &ddh_total);
2597
2598	(void) printf("Simulated DDT histogram:\n");
2599
2600	zpool_dump_ddt(&dds_total, &ddh_total);
2601
2602	dump_dedup_ratio(&dds_total);
2603}
2604
2605static void
2606dump_zpool(spa_t *spa)
2607{
2608	dsl_pool_t *dp = spa_get_dsl(spa);
2609	int rc = 0;
2610
2611	if (dump_opt['S']) {
2612		dump_simulated_ddt(spa);
2613		return;
2614	}
2615
2616	if (!dump_opt['e'] && dump_opt['C'] > 1) {
2617		(void) printf("\nCached configuration:\n");
2618		dump_nvlist(spa->spa_config, 8);
2619	}
2620
2621	if (dump_opt['C'])
2622		dump_config(spa);
2623
2624	if (dump_opt['u'])
2625		dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
2626
2627	if (dump_opt['D'])
2628		dump_all_ddts(spa);
2629
2630	if (dump_opt['d'] > 2 || dump_opt['m'])
2631		dump_metaslabs(spa);
2632
2633	if (dump_opt['d'] || dump_opt['i']) {
2634		dump_dir(dp->dp_meta_objset);
2635		if (dump_opt['d'] >= 3) {
2636			dump_bpobj(&spa->spa_deferred_bpobj,
2637			    "Deferred frees", 0);
2638			if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
2639				dump_bpobj(&spa->spa_dsl_pool->dp_free_bpobj,
2640				    "Pool snapshot frees", 0);
2641			}
2642
2643			if (spa_feature_is_active(spa,
2644			    &spa_feature_table[SPA_FEATURE_ASYNC_DESTROY])) {
2645				dump_bptree(spa->spa_meta_objset,
2646				    spa->spa_dsl_pool->dp_bptree_obj,
2647				    "Pool dataset frees");
2648			}
2649			dump_dtl(spa->spa_root_vdev, 0);
2650		}
2651		(void) dmu_objset_find(spa_name(spa), dump_one_dir,
2652		    NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
2653	}
2654	if (dump_opt['b'] || dump_opt['c'])
2655		rc = dump_block_stats(spa);
2656
2657	if (dump_opt['s'])
2658		show_pool_stats(spa);
2659
2660	if (dump_opt['h'])
2661		dump_history(spa);
2662
2663	if (rc != 0)
2664		exit(rc);
2665}
2666
2667#define	ZDB_FLAG_CHECKSUM	0x0001
2668#define	ZDB_FLAG_DECOMPRESS	0x0002
2669#define	ZDB_FLAG_BSWAP		0x0004
2670#define	ZDB_FLAG_GBH		0x0008
2671#define	ZDB_FLAG_INDIRECT	0x0010
2672#define	ZDB_FLAG_PHYS		0x0020
2673#define	ZDB_FLAG_RAW		0x0040
2674#define	ZDB_FLAG_PRINT_BLKPTR	0x0080
2675
2676int flagbits[256];
2677
2678static void
2679zdb_print_blkptr(blkptr_t *bp, int flags)
2680{
2681	char blkbuf[BP_SPRINTF_LEN];
2682
2683	if (flags & ZDB_FLAG_BSWAP)
2684		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
2685
2686	sprintf_blkptr(blkbuf, bp);
2687	(void) printf("%s\n", blkbuf);
2688}
2689
2690static void
2691zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
2692{
2693	int i;
2694
2695	for (i = 0; i < nbps; i++)
2696		zdb_print_blkptr(&bp[i], flags);
2697}
2698
2699static void
2700zdb_dump_gbh(void *buf, int flags)
2701{
2702	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
2703}
2704
2705static void
2706zdb_dump_block_raw(void *buf, uint64_t size, int flags)
2707{
2708	if (flags & ZDB_FLAG_BSWAP)
2709		byteswap_uint64_array(buf, size);
2710	(void) write(1, buf, size);
2711}
2712
2713static void
2714zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
2715{
2716	uint64_t *d = (uint64_t *)buf;
2717	int nwords = size / sizeof (uint64_t);
2718	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
2719	int i, j;
2720	char *hdr, *c;
2721
2722
2723	if (do_bswap)
2724		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
2725	else
2726		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
2727
2728	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
2729
2730	for (i = 0; i < nwords; i += 2) {
2731		(void) printf("%06llx:  %016llx  %016llx  ",
2732		    (u_longlong_t)(i * sizeof (uint64_t)),
2733		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
2734		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
2735
2736		c = (char *)&d[i];
2737		for (j = 0; j < 2 * sizeof (uint64_t); j++)
2738			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
2739		(void) printf("\n");
2740	}
2741}
2742
2743/*
2744 * There are two acceptable formats:
2745 *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
2746 *	child[.child]*    - For example: 0.1.1
2747 *
2748 * The second form can be used to specify arbitrary vdevs anywhere
2749 * in the heirarchy.  For example, in a pool with a mirror of
2750 * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
2751 */
2752static vdev_t *
2753zdb_vdev_lookup(vdev_t *vdev, char *path)
2754{
2755	char *s, *p, *q;
2756	int i;
2757
2758	if (vdev == NULL)
2759		return (NULL);
2760
2761	/* First, assume the x.x.x.x format */
2762	i = (int)strtoul(path, &s, 10);
2763	if (s == path || (s && *s != '.' && *s != '\0'))
2764		goto name;
2765	if (i < 0 || i >= vdev->vdev_children)
2766		return (NULL);
2767
2768	vdev = vdev->vdev_child[i];
2769	if (*s == '\0')
2770		return (vdev);
2771	return (zdb_vdev_lookup(vdev, s+1));
2772
2773name:
2774	for (i = 0; i < vdev->vdev_children; i++) {
2775		vdev_t *vc = vdev->vdev_child[i];
2776
2777		if (vc->vdev_path == NULL) {
2778			vc = zdb_vdev_lookup(vc, path);
2779			if (vc == NULL)
2780				continue;
2781			else
2782				return (vc);
2783		}
2784
2785		p = strrchr(vc->vdev_path, '/');
2786		p = p ? p + 1 : vc->vdev_path;
2787		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2788
2789		if (strcmp(vc->vdev_path, path) == 0)
2790			return (vc);
2791		if (strcmp(p, path) == 0)
2792			return (vc);
2793		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2794			return (vc);
2795	}
2796
2797	return (NULL);
2798}
2799
2800/*
2801 * Read a block from a pool and print it out.  The syntax of the
2802 * block descriptor is:
2803 *
2804 *	pool:vdev_specifier:offset:size[:flags]
2805 *
2806 *	pool           - The name of the pool you wish to read from
2807 *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2808 *	offset         - offset, in hex, in bytes
2809 *	size           - Amount of data to read, in hex, in bytes
2810 *	flags          - A string of characters specifying options
2811 *		 b: Decode a blkptr at given offset within block
2812 *		*c: Calculate and display checksums
2813 *		 d: Decompress data before dumping
2814 *		 e: Byteswap data before dumping
2815 *		 g: Display data as a gang block header
2816 *		 i: Display as an indirect block
2817 *		 p: Do I/O to physical offset
2818 *		 r: Dump raw data to stdout
2819 *
2820 *              * = not yet implemented
2821 */
2822static void
2823zdb_read_block(char *thing, spa_t *spa)
2824{
2825	blkptr_t blk, *bp = &blk;
2826	dva_t *dva = bp->blk_dva;
2827	int flags = 0;
2828	uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
2829	zio_t *zio;
2830	vdev_t *vd;
2831	void *pbuf, *lbuf, *buf;
2832	char *s, *p, *dup, *vdev, *flagstr;
2833	int i, error;
2834
2835	dup = strdup(thing);
2836	s = strtok(dup, ":");
2837	vdev = s ? s : "";
2838	s = strtok(NULL, ":");
2839	offset = strtoull(s ? s : "", NULL, 16);
2840	s = strtok(NULL, ":");
2841	size = strtoull(s ? s : "", NULL, 16);
2842	s = strtok(NULL, ":");
2843	flagstr = s ? s : "";
2844
2845	s = NULL;
2846	if (size == 0)
2847		s = "size must not be zero";
2848	if (!IS_P2ALIGNED(size, DEV_BSIZE))
2849		s = "size must be a multiple of sector size";
2850	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
2851		s = "offset must be a multiple of sector size";
2852	if (s) {
2853		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
2854		free(dup);
2855		return;
2856	}
2857
2858	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
2859		for (i = 0; flagstr[i]; i++) {
2860			int bit = flagbits[(uchar_t)flagstr[i]];
2861
2862			if (bit == 0) {
2863				(void) printf("***Invalid flag: %c\n",
2864				    flagstr[i]);
2865				continue;
2866			}
2867			flags |= bit;
2868
2869			/* If it's not something with an argument, keep going */
2870			if ((bit & (ZDB_FLAG_CHECKSUM |
2871			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
2872				continue;
2873
2874			p = &flagstr[i + 1];
2875			if (bit == ZDB_FLAG_PRINT_BLKPTR)
2876				blkptr_offset = strtoull(p, &p, 16);
2877			if (*p != ':' && *p != '\0') {
2878				(void) printf("***Invalid flag arg: '%s'\n", s);
2879				free(dup);
2880				return;
2881			}
2882		}
2883	}
2884
2885	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2886	if (vd == NULL) {
2887		(void) printf("***Invalid vdev: %s\n", vdev);
2888		free(dup);
2889		return;
2890	} else {
2891		if (vd->vdev_path)
2892			(void) fprintf(stderr, "Found vdev: %s\n",
2893			    vd->vdev_path);
2894		else
2895			(void) fprintf(stderr, "Found vdev type: %s\n",
2896			    vd->vdev_ops->vdev_op_type);
2897	}
2898
2899	psize = size;
2900	lsize = size;
2901
2902	pbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2903	lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2904
2905	BP_ZERO(bp);
2906
2907	DVA_SET_VDEV(&dva[0], vd->vdev_id);
2908	DVA_SET_OFFSET(&dva[0], offset);
2909	DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
2910	DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
2911
2912	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
2913
2914	BP_SET_LSIZE(bp, lsize);
2915	BP_SET_PSIZE(bp, psize);
2916	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
2917	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
2918	BP_SET_TYPE(bp, DMU_OT_NONE);
2919	BP_SET_LEVEL(bp, 0);
2920	BP_SET_DEDUP(bp, 0);
2921	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
2922
2923	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
2924	zio = zio_root(spa, NULL, NULL, 0);
2925
2926	if (vd == vd->vdev_top) {
2927		/*
2928		 * Treat this as a normal block read.
2929		 */
2930		zio_nowait(zio_read(zio, spa, bp, pbuf, psize, NULL, NULL,
2931		    ZIO_PRIORITY_SYNC_READ,
2932		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
2933	} else {
2934		/*
2935		 * Treat this as a vdev child I/O.
2936		 */
2937		zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pbuf, psize,
2938		    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
2939		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2940		    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
2941		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL, NULL));
2942	}
2943
2944	error = zio_wait(zio);
2945	spa_config_exit(spa, SCL_STATE, FTAG);
2946
2947	if (error) {
2948		(void) printf("Read of %s failed, error: %d\n", thing, error);
2949		goto out;
2950	}
2951
2952	if (flags & ZDB_FLAG_DECOMPRESS) {
2953		/*
2954		 * We don't know how the data was compressed, so just try
2955		 * every decompress function at every inflated blocksize.
2956		 */
2957		enum zio_compress c;
2958		void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2959		void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2960
2961		bcopy(pbuf, pbuf2, psize);
2962
2963		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf + psize,
2964		    SPA_MAXBLOCKSIZE - psize) == 0);
2965
2966		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
2967		    SPA_MAXBLOCKSIZE - psize) == 0);
2968
2969		for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
2970		    lsize -= SPA_MINBLOCKSIZE) {
2971			for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
2972				if (zio_decompress_data(c, pbuf, lbuf,
2973				    psize, lsize) == 0 &&
2974				    zio_decompress_data(c, pbuf2, lbuf2,
2975				    psize, lsize) == 0 &&
2976				    bcmp(lbuf, lbuf2, lsize) == 0)
2977					break;
2978			}
2979			if (c != ZIO_COMPRESS_FUNCTIONS)
2980				break;
2981			lsize -= SPA_MINBLOCKSIZE;
2982		}
2983
2984		umem_free(pbuf2, SPA_MAXBLOCKSIZE);
2985		umem_free(lbuf2, SPA_MAXBLOCKSIZE);
2986
2987		if (lsize <= psize) {
2988			(void) printf("Decompress of %s failed\n", thing);
2989			goto out;
2990		}
2991		buf = lbuf;
2992		size = lsize;
2993	} else {
2994		buf = pbuf;
2995		size = psize;
2996	}
2997
2998	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2999		zdb_print_blkptr((blkptr_t *)(void *)
3000		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
3001	else if (flags & ZDB_FLAG_RAW)
3002		zdb_dump_block_raw(buf, size, flags);
3003	else if (flags & ZDB_FLAG_INDIRECT)
3004		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
3005		    flags);
3006	else if (flags & ZDB_FLAG_GBH)
3007		zdb_dump_gbh(buf, flags);
3008	else
3009		zdb_dump_block(thing, buf, size, flags);
3010
3011out:
3012	umem_free(pbuf, SPA_MAXBLOCKSIZE);
3013	umem_free(lbuf, SPA_MAXBLOCKSIZE);
3014	free(dup);
3015}
3016
3017static boolean_t
3018pool_match(nvlist_t *cfg, char *tgt)
3019{
3020	uint64_t v, guid = strtoull(tgt, NULL, 0);
3021	char *s;
3022
3023	if (guid != 0) {
3024		if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
3025			return (v == guid);
3026	} else {
3027		if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
3028			return (strcmp(s, tgt) == 0);
3029	}
3030	return (B_FALSE);
3031}
3032
3033static char *
3034find_zpool(char **target, nvlist_t **configp, int dirc, char **dirv)
3035{
3036	nvlist_t *pools;
3037	nvlist_t *match = NULL;
3038	char *name = NULL;
3039	char *sepp = NULL;
3040	char sep;
3041	int count = 0;
3042	importargs_t args = { 0 };
3043
3044	args.paths = dirc;
3045	args.path = dirv;
3046	args.can_be_active = B_TRUE;
3047
3048	if ((sepp = strpbrk(*target, "/@")) != NULL) {
3049		sep = *sepp;
3050		*sepp = '\0';
3051	}
3052
3053	pools = zpool_search_import(g_zfs, &args);
3054
3055	if (pools != NULL) {
3056		nvpair_t *elem = NULL;
3057		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3058			verify(nvpair_value_nvlist(elem, configp) == 0);
3059			if (pool_match(*configp, *target)) {
3060				count++;
3061				if (match != NULL) {
3062					/* print previously found config */
3063					if (name != NULL) {
3064						(void) printf("%s\n", name);
3065						dump_nvlist(match, 8);
3066						name = NULL;
3067					}
3068					(void) printf("%s\n",
3069					    nvpair_name(elem));
3070					dump_nvlist(*configp, 8);
3071				} else {
3072					match = *configp;
3073					name = nvpair_name(elem);
3074				}
3075			}
3076		}
3077	}
3078	if (count > 1)
3079		(void) fatal("\tMatched %d pools - use pool GUID "
3080		    "instead of pool name or \n"
3081		    "\tpool name part of a dataset name to select pool", count);
3082
3083	if (sepp)
3084		*sepp = sep;
3085	/*
3086	 * If pool GUID was specified for pool id, replace it with pool name
3087	 */
3088	if (name && (strstr(*target, name) != *target)) {
3089		int sz = 1 + strlen(name) + ((sepp) ? strlen(sepp) : 0);
3090
3091		*target = umem_alloc(sz, UMEM_NOFAIL);
3092		(void) snprintf(*target, sz, "%s%s", name, sepp ? sepp : "");
3093	}
3094
3095	*configp = name ? match : NULL;
3096
3097	return (name);
3098}
3099
3100int
3101main(int argc, char **argv)
3102{
3103	int i, c;
3104	struct rlimit rl = { 1024, 1024 };
3105	spa_t *spa = NULL;
3106	objset_t *os = NULL;
3107	int dump_all = 1;
3108	int verbose = 0;
3109	int error = 0;
3110	char **searchdirs = NULL;
3111	int nsearch = 0;
3112	char *target;
3113	nvlist_t *policy = NULL;
3114	uint64_t max_txg = UINT64_MAX;
3115	int rewind = ZPOOL_NEVER_REWIND;
3116
3117	(void) setrlimit(RLIMIT_NOFILE, &rl);
3118	(void) enable_extended_FILE_stdio(-1, -1);
3119
3120	dprintf_setup(&argc, argv);
3121
3122	while ((c = getopt(argc, argv, "bcdhilmM:suCDRSAFLXevp:t:U:P")) != -1) {
3123		switch (c) {
3124		case 'b':
3125		case 'c':
3126		case 'd':
3127		case 'h':
3128		case 'i':
3129		case 'l':
3130		case 'm':
3131		case 's':
3132		case 'u':
3133		case 'C':
3134		case 'D':
3135		case 'R':
3136		case 'S':
3137			dump_opt[c]++;
3138			dump_all = 0;
3139			break;
3140		case 'A':
3141		case 'F':
3142		case 'L':
3143		case 'X':
3144		case 'e':
3145		case 'P':
3146			dump_opt[c]++;
3147			break;
3148		case 'v':
3149			verbose++;
3150			break;
3151		case 'M':
3152			max_inflight = strtoull(optarg, NULL, 0);
3153			if (max_inflight == 0) {
3154				(void) fprintf(stderr, "maximum number "
3155				    "of inflight I/Os must be greater "
3156				    "than 0\n");
3157				usage();
3158			}
3159			break;
3160		case 'p':
3161			if (searchdirs == NULL) {
3162				searchdirs = umem_alloc(sizeof (char *),
3163				    UMEM_NOFAIL);
3164			} else {
3165				char **tmp = umem_alloc((nsearch + 1) *
3166				    sizeof (char *), UMEM_NOFAIL);
3167				bcopy(searchdirs, tmp, nsearch *
3168				    sizeof (char *));
3169				umem_free(searchdirs,
3170				    nsearch * sizeof (char *));
3171				searchdirs = tmp;
3172			}
3173			searchdirs[nsearch++] = optarg;
3174			break;
3175		case 't':
3176			max_txg = strtoull(optarg, NULL, 0);
3177			if (max_txg < TXG_INITIAL) {
3178				(void) fprintf(stderr, "incorrect txg "
3179				    "specified: %s\n", optarg);
3180				usage();
3181			}
3182			break;
3183		case 'U':
3184			spa_config_path = optarg;
3185			break;
3186		default:
3187			usage();
3188			break;
3189		}
3190	}
3191
3192	if (!dump_opt['e'] && searchdirs != NULL) {
3193		(void) fprintf(stderr, "-p option requires use of -e\n");
3194		usage();
3195	}
3196
3197	kernel_init(FREAD);
3198	g_zfs = libzfs_init();
3199	ASSERT(g_zfs != NULL);
3200
3201	if (dump_all)
3202		verbose = MAX(verbose, 1);
3203
3204	for (c = 0; c < 256; c++) {
3205		if (dump_all && !strchr("elAFLRSXP", c))
3206			dump_opt[c] = 1;
3207		if (dump_opt[c])
3208			dump_opt[c] += verbose;
3209	}
3210
3211	aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
3212	zfs_recover = (dump_opt['A'] > 1);
3213
3214	argc -= optind;
3215	argv += optind;
3216
3217	if (argc < 2 && dump_opt['R'])
3218		usage();
3219	if (argc < 1) {
3220		if (!dump_opt['e'] && dump_opt['C']) {
3221			dump_cachefile(spa_config_path);
3222			return (0);
3223		}
3224		usage();
3225	}
3226
3227	if (dump_opt['l']) {
3228		dump_label(argv[0]);
3229		return (0);
3230	}
3231
3232	if (dump_opt['X'] || dump_opt['F'])
3233		rewind = ZPOOL_DO_REWIND |
3234		    (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
3235
3236	if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
3237	    nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, max_txg) != 0 ||
3238	    nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind) != 0)
3239		fatal("internal error: %s", strerror(ENOMEM));
3240
3241	error = 0;
3242	target = argv[0];
3243
3244	if (dump_opt['e']) {
3245		nvlist_t *cfg = NULL;
3246		char *name = find_zpool(&target, &cfg, nsearch, searchdirs);
3247
3248		error = ENOENT;
3249		if (name) {
3250			if (dump_opt['C'] > 1) {
3251				(void) printf("\nConfiguration for import:\n");
3252				dump_nvlist(cfg, 8);
3253			}
3254			if (nvlist_add_nvlist(cfg,
3255			    ZPOOL_REWIND_POLICY, policy) != 0) {
3256				fatal("can't open '%s': %s",
3257				    target, strerror(ENOMEM));
3258			}
3259			if ((error = spa_import(name, cfg, NULL,
3260			    ZFS_IMPORT_MISSING_LOG)) != 0) {
3261				error = spa_import(name, cfg, NULL,
3262				    ZFS_IMPORT_VERBATIM);
3263			}
3264		}
3265	}
3266
3267	if (error == 0) {
3268		if (strpbrk(target, "/@") == NULL || dump_opt['R']) {
3269			error = spa_open_rewind(target, &spa, FTAG, policy,
3270			    NULL);
3271			if (error) {
3272				/*
3273				 * If we're missing the log device then
3274				 * try opening the pool after clearing the
3275				 * log state.
3276				 */
3277				mutex_enter(&spa_namespace_lock);
3278				if ((spa = spa_lookup(target)) != NULL &&
3279				    spa->spa_log_state == SPA_LOG_MISSING) {
3280					spa->spa_log_state = SPA_LOG_CLEAR;
3281					error = 0;
3282				}
3283				mutex_exit(&spa_namespace_lock);
3284
3285				if (!error) {
3286					error = spa_open_rewind(target, &spa,
3287					    FTAG, policy, NULL);
3288				}
3289			}
3290		} else {
3291			error = dmu_objset_own(target, DMU_OST_ANY,
3292			    B_TRUE, FTAG, &os);
3293		}
3294	}
3295	nvlist_free(policy);
3296
3297	if (error)
3298		fatal("can't open '%s': %s", target, strerror(error));
3299
3300	argv++;
3301	argc--;
3302	if (!dump_opt['R']) {
3303		if (argc > 0) {
3304			zopt_objects = argc;
3305			zopt_object = calloc(zopt_objects, sizeof (uint64_t));
3306			for (i = 0; i < zopt_objects; i++) {
3307				errno = 0;
3308				zopt_object[i] = strtoull(argv[i], NULL, 0);
3309				if (zopt_object[i] == 0 && errno != 0)
3310					fatal("bad number %s: %s",
3311					    argv[i], strerror(errno));
3312			}
3313		}
3314		if (os != NULL) {
3315			dump_dir(os);
3316		} else if (zopt_objects > 0 && !dump_opt['m']) {
3317			dump_dir(spa->spa_meta_objset);
3318		} else {
3319			dump_zpool(spa);
3320		}
3321	} else {
3322		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
3323		flagbits['c'] = ZDB_FLAG_CHECKSUM;
3324		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
3325		flagbits['e'] = ZDB_FLAG_BSWAP;
3326		flagbits['g'] = ZDB_FLAG_GBH;
3327		flagbits['i'] = ZDB_FLAG_INDIRECT;
3328		flagbits['p'] = ZDB_FLAG_PHYS;
3329		flagbits['r'] = ZDB_FLAG_RAW;
3330
3331		for (i = 0; i < argc; i++)
3332			zdb_read_block(argv[i], spa);
3333	}
3334
3335	(os != NULL) ? dmu_objset_disown(os, FTAG) : spa_close(spa, FTAG);
3336
3337	fuid_table_destroy();
3338	sa_loaded = B_FALSE;
3339
3340	libzfs_fini(g_zfs);
3341	kernel_fini();
3342
3343	return (0);
3344}
3345