zdb.c revision e690fb27a7d1483f052505e1ff373d205f9dee99
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_nolock(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)
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) {
1236		zdb_nicenum(bpo->bpo_phys->bpo_comp, comp);
1237		zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp);
1238		(void) printf("\n    %s: %llu local blkptrs, %llu subobjs, "
1239		    "%s (%s/%s comp)\n",
1240		    name, (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1241		    (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1242		    bytes, comp, uncomp);
1243	} else {
1244		(void) printf("\n    %s: %llu blkptrs, %s\n",
1245		    name, (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs, bytes);
1246	}
1247
1248	if (dump_opt['d'] < 5)
1249		return;
1250
1251	(void) printf("\n");
1252
1253	(void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1254}
1255
1256static void
1257dump_deadlist(dsl_deadlist_t *dl)
1258{
1259	dsl_deadlist_entry_t *dle;
1260	char bytes[32];
1261	char comp[32];
1262	char uncomp[32];
1263
1264	if (dump_opt['d'] < 3)
1265		return;
1266
1267	zdb_nicenum(dl->dl_phys->dl_used, bytes);
1268	zdb_nicenum(dl->dl_phys->dl_comp, comp);
1269	zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp);
1270	(void) printf("\n    Deadlist: %s (%s/%s comp)\n",
1271	    bytes, comp, uncomp);
1272
1273	if (dump_opt['d'] < 4)
1274		return;
1275
1276	(void) printf("\n");
1277
1278	for (dle = avl_first(&dl->dl_tree); dle;
1279	    dle = AVL_NEXT(&dl->dl_tree, dle)) {
1280		(void) printf("      mintxg %llu -> obj %llu\n",
1281		    (longlong_t)dle->dle_mintxg,
1282		    (longlong_t)dle->dle_bpobj.bpo_object);
1283
1284		if (dump_opt['d'] >= 5)
1285			dump_bpobj(&dle->dle_bpobj, "");
1286	}
1287}
1288
1289static avl_tree_t idx_tree;
1290static avl_tree_t domain_tree;
1291static boolean_t fuid_table_loaded;
1292static boolean_t sa_loaded;
1293sa_attr_type_t *sa_attr_table;
1294
1295static void
1296fuid_table_destroy()
1297{
1298	if (fuid_table_loaded) {
1299		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1300		fuid_table_loaded = B_FALSE;
1301	}
1302}
1303
1304/*
1305 * print uid or gid information.
1306 * For normal POSIX id just the id is printed in decimal format.
1307 * For CIFS files with FUID the fuid is printed in hex followed by
1308 * the doman-rid string.
1309 */
1310static void
1311print_idstr(uint64_t id, const char *id_type)
1312{
1313	if (FUID_INDEX(id)) {
1314		char *domain;
1315
1316		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1317		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
1318		    (u_longlong_t)id, domain, (int)FUID_RID(id));
1319	} else {
1320		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1321	}
1322
1323}
1324
1325static void
1326dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
1327{
1328	uint32_t uid_idx, gid_idx;
1329
1330	uid_idx = FUID_INDEX(uid);
1331	gid_idx = FUID_INDEX(gid);
1332
1333	/* Load domain table, if not already loaded */
1334	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1335		uint64_t fuid_obj;
1336
1337		/* first find the fuid object.  It lives in the master node */
1338		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1339		    8, 1, &fuid_obj) == 0);
1340		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1341		(void) zfs_fuid_table_load(os, fuid_obj,
1342		    &idx_tree, &domain_tree);
1343		fuid_table_loaded = B_TRUE;
1344	}
1345
1346	print_idstr(uid, "uid");
1347	print_idstr(gid, "gid");
1348}
1349
1350/*ARGSUSED*/
1351static void
1352dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
1353{
1354	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
1355	sa_handle_t *hdl;
1356	uint64_t xattr, rdev, gen;
1357	uint64_t uid, gid, mode, fsize, parent, links;
1358	uint64_t pflags;
1359	uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
1360	time_t z_crtime, z_atime, z_mtime, z_ctime;
1361	sa_bulk_attr_t bulk[12];
1362	int idx = 0;
1363	int error;
1364
1365	if (!sa_loaded) {
1366		uint64_t sa_attrs = 0;
1367		uint64_t version;
1368
1369		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1370		    8, 1, &version) == 0);
1371		if (version >= ZPL_VERSION_SA) {
1372			VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1373			    8, 1, &sa_attrs) == 0);
1374		}
1375		if ((error = sa_setup(os, sa_attrs, zfs_attr_table,
1376		    ZPL_END, &sa_attr_table)) != 0) {
1377			(void) printf("sa_setup failed errno %d, can't "
1378			    "display znode contents\n", error);
1379			return;
1380		}
1381		sa_loaded = B_TRUE;
1382	}
1383
1384	if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
1385		(void) printf("Failed to get handle for SA znode\n");
1386		return;
1387	}
1388
1389	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
1390	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
1391	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
1392	    &links, 8);
1393	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
1394	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
1395	    &mode, 8);
1396	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
1397	    NULL, &parent, 8);
1398	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
1399	    &fsize, 8);
1400	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
1401	    acctm, 16);
1402	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
1403	    modtm, 16);
1404	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
1405	    crtm, 16);
1406	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
1407	    chgtm, 16);
1408	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
1409	    &pflags, 8);
1410
1411	if (sa_bulk_lookup(hdl, bulk, idx)) {
1412		(void) sa_handle_destroy(hdl);
1413		return;
1414	}
1415
1416	error = zfs_obj_to_path(os, object, path, sizeof (path));
1417	if (error != 0) {
1418		(void) snprintf(path, sizeof (path), "\?\?\?<object#%llu>",
1419		    (u_longlong_t)object);
1420	}
1421	if (dump_opt['d'] < 3) {
1422		(void) printf("\t%s\n", path);
1423		(void) sa_handle_destroy(hdl);
1424		return;
1425	}
1426
1427	z_crtime = (time_t)crtm[0];
1428	z_atime = (time_t)acctm[0];
1429	z_mtime = (time_t)modtm[0];
1430	z_ctime = (time_t)chgtm[0];
1431
1432	(void) printf("\tpath	%s\n", path);
1433	dump_uidgid(os, uid, gid);
1434	(void) printf("\tatime	%s", ctime(&z_atime));
1435	(void) printf("\tmtime	%s", ctime(&z_mtime));
1436	(void) printf("\tctime	%s", ctime(&z_ctime));
1437	(void) printf("\tcrtime	%s", ctime(&z_crtime));
1438	(void) printf("\tgen	%llu\n", (u_longlong_t)gen);
1439	(void) printf("\tmode	%llo\n", (u_longlong_t)mode);
1440	(void) printf("\tsize	%llu\n", (u_longlong_t)fsize);
1441	(void) printf("\tparent	%llu\n", (u_longlong_t)parent);
1442	(void) printf("\tlinks	%llu\n", (u_longlong_t)links);
1443	(void) printf("\tpflags	%llx\n", (u_longlong_t)pflags);
1444	if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
1445	    sizeof (uint64_t)) == 0)
1446		(void) printf("\txattr	%llu\n", (u_longlong_t)xattr);
1447	if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
1448	    sizeof (uint64_t)) == 0)
1449		(void) printf("\trdev	0x%016llx\n", (u_longlong_t)rdev);
1450	sa_handle_destroy(hdl);
1451}
1452
1453/*ARGSUSED*/
1454static void
1455dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
1456{
1457}
1458
1459/*ARGSUSED*/
1460static void
1461dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
1462{
1463}
1464
1465static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
1466	dump_none,		/* unallocated			*/
1467	dump_zap,		/* object directory		*/
1468	dump_uint64,		/* object array			*/
1469	dump_none,		/* packed nvlist		*/
1470	dump_packed_nvlist,	/* packed nvlist size		*/
1471	dump_none,		/* bplist			*/
1472	dump_none,		/* bplist header		*/
1473	dump_none,		/* SPA space map header		*/
1474	dump_none,		/* SPA space map		*/
1475	dump_none,		/* ZIL intent log		*/
1476	dump_dnode,		/* DMU dnode			*/
1477	dump_dmu_objset,	/* DMU objset			*/
1478	dump_dsl_dir,		/* DSL directory		*/
1479	dump_zap,		/* DSL directory child map	*/
1480	dump_zap,		/* DSL dataset snap map		*/
1481	dump_zap,		/* DSL props			*/
1482	dump_dsl_dataset,	/* DSL dataset			*/
1483	dump_znode,		/* ZFS znode			*/
1484	dump_acl,		/* ZFS V0 ACL			*/
1485	dump_uint8,		/* ZFS plain file		*/
1486	dump_zpldir,		/* ZFS directory		*/
1487	dump_zap,		/* ZFS master node		*/
1488	dump_zap,		/* ZFS delete queue		*/
1489	dump_uint8,		/* zvol object			*/
1490	dump_zap,		/* zvol prop			*/
1491	dump_uint8,		/* other uint8[]		*/
1492	dump_uint64,		/* other uint64[]		*/
1493	dump_zap,		/* other ZAP			*/
1494	dump_zap,		/* persistent error log		*/
1495	dump_uint8,		/* SPA history			*/
1496	dump_history_offsets,	/* SPA history offsets		*/
1497	dump_zap,		/* Pool properties		*/
1498	dump_zap,		/* DSL permissions		*/
1499	dump_acl,		/* ZFS ACL			*/
1500	dump_uint8,		/* ZFS SYSACL			*/
1501	dump_none,		/* FUID nvlist			*/
1502	dump_packed_nvlist,	/* FUID nvlist size		*/
1503	dump_zap,		/* DSL dataset next clones	*/
1504	dump_zap,		/* DSL scrub queue		*/
1505	dump_zap,		/* ZFS user/group used		*/
1506	dump_zap,		/* ZFS user/group quota		*/
1507	dump_zap,		/* snapshot refcount tags	*/
1508	dump_ddt_zap,		/* DDT ZAP object		*/
1509	dump_zap,		/* DDT statistics		*/
1510	dump_znode,		/* SA object			*/
1511	dump_zap,		/* SA Master Node		*/
1512	dump_sa_attrs,		/* SA attribute registration	*/
1513	dump_sa_layouts,	/* SA attribute layouts		*/
1514	dump_zap,		/* DSL scrub translations	*/
1515	dump_none,		/* fake dedup BP		*/
1516	dump_zap,		/* deadlist			*/
1517	dump_none,		/* deadlist hdr			*/
1518	dump_zap,		/* dsl clones			*/
1519	dump_none,		/* bpobj subobjs		*/
1520	dump_unknown,		/* Unknown type, must be last	*/
1521};
1522
1523static void
1524dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1525{
1526	dmu_buf_t *db = NULL;
1527	dmu_object_info_t doi;
1528	dnode_t *dn;
1529	void *bonus = NULL;
1530	size_t bsize = 0;
1531	char iblk[32], dblk[32], lsize[32], asize[32], fill[32];
1532	char bonus_size[32];
1533	char aux[50];
1534	int error;
1535
1536	if (*print_header) {
1537		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1538		    "Object", "lvl", "iblk", "dblk", "dsize", "lsize",
1539		    "%full", "type");
1540		*print_header = 0;
1541	}
1542
1543	if (object == 0) {
1544		dn = DMU_META_DNODE(os);
1545	} else {
1546		error = dmu_bonus_hold(os, object, FTAG, &db);
1547		if (error)
1548			fatal("dmu_bonus_hold(%llu) failed, errno %u",
1549			    object, error);
1550		bonus = db->db_data;
1551		bsize = db->db_size;
1552		dn = DB_DNODE((dmu_buf_impl_t *)db);
1553	}
1554	dmu_object_info_from_dnode(dn, &doi);
1555
1556	zdb_nicenum(doi.doi_metadata_block_size, iblk);
1557	zdb_nicenum(doi.doi_data_block_size, dblk);
1558	zdb_nicenum(doi.doi_max_offset, lsize);
1559	zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize);
1560	zdb_nicenum(doi.doi_bonus_size, bonus_size);
1561	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
1562	    doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
1563	    doi.doi_max_offset);
1564
1565	aux[0] = '\0';
1566
1567	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1568		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1569		    ZDB_CHECKSUM_NAME(doi.doi_checksum));
1570	}
1571
1572	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1573		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1574		    ZDB_COMPRESS_NAME(doi.doi_compress));
1575	}
1576
1577	(void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %6s  %s%s\n",
1578	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
1579	    asize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
1580
1581	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1582		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1583		    "", "", "", "", "", bonus_size, "bonus",
1584		    ZDB_OT_NAME(doi.doi_bonus_type));
1585	}
1586
1587	if (verbosity >= 4) {
1588		(void) printf("\tdnode flags: %s%s%s\n",
1589		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
1590		    "USED_BYTES " : "",
1591		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
1592		    "USERUSED_ACCOUNTED " : "",
1593		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
1594		    "SPILL_BLKPTR" : "");
1595		(void) printf("\tdnode maxblkid: %llu\n",
1596		    (longlong_t)dn->dn_phys->dn_maxblkid);
1597
1598		object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os, object,
1599		    bonus, bsize);
1600		object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object, NULL, 0);
1601		*print_header = 1;
1602	}
1603
1604	if (verbosity >= 5)
1605		dump_indirect(dn);
1606
1607	if (verbosity >= 5) {
1608		/*
1609		 * Report the list of segments that comprise the object.
1610		 */
1611		uint64_t start = 0;
1612		uint64_t end;
1613		uint64_t blkfill = 1;
1614		int minlvl = 1;
1615
1616		if (dn->dn_type == DMU_OT_DNODE) {
1617			minlvl = 0;
1618			blkfill = DNODES_PER_BLOCK;
1619		}
1620
1621		for (;;) {
1622			char segsize[32];
1623			error = dnode_next_offset(dn,
1624			    0, &start, minlvl, blkfill, 0);
1625			if (error)
1626				break;
1627			end = start;
1628			error = dnode_next_offset(dn,
1629			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
1630			zdb_nicenum(end - start, segsize);
1631			(void) printf("\t\tsegment [%016llx, %016llx)"
1632			    " size %5s\n", (u_longlong_t)start,
1633			    (u_longlong_t)end, segsize);
1634			if (error)
1635				break;
1636			start = end;
1637		}
1638	}
1639
1640	if (db != NULL)
1641		dmu_buf_rele(db, FTAG);
1642}
1643
1644static char *objset_types[DMU_OST_NUMTYPES] = {
1645	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1646
1647static void
1648dump_dir(objset_t *os)
1649{
1650	dmu_objset_stats_t dds;
1651	uint64_t object, object_count;
1652	uint64_t refdbytes, usedobjs, scratch;
1653	char numbuf[32];
1654	char blkbuf[BP_SPRINTF_LEN + 20];
1655	char osname[MAXNAMELEN];
1656	char *type = "UNKNOWN";
1657	int verbosity = dump_opt['d'];
1658	int print_header = 1;
1659	int i, error;
1660
1661	dmu_objset_fast_stat(os, &dds);
1662
1663	if (dds.dds_type < DMU_OST_NUMTYPES)
1664		type = objset_types[dds.dds_type];
1665
1666	if (dds.dds_type == DMU_OST_META) {
1667		dds.dds_creation_txg = TXG_INITIAL;
1668		usedobjs = os->os_rootbp->blk_fill;
1669		refdbytes = os->os_spa->spa_dsl_pool->
1670		    dp_mos_dir->dd_phys->dd_used_bytes;
1671	} else {
1672		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
1673	}
1674
1675	ASSERT3U(usedobjs, ==, os->os_rootbp->blk_fill);
1676
1677	zdb_nicenum(refdbytes, numbuf);
1678
1679	if (verbosity >= 4) {
1680		(void) sprintf(blkbuf, ", rootbp ");
1681		(void) sprintf_blkptr(blkbuf + strlen(blkbuf), os->os_rootbp);
1682	} else {
1683		blkbuf[0] = '\0';
1684	}
1685
1686	dmu_objset_name(os, osname);
1687
1688	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
1689	    "%s, %llu objects%s\n",
1690	    osname, type, (u_longlong_t)dmu_objset_id(os),
1691	    (u_longlong_t)dds.dds_creation_txg,
1692	    numbuf, (u_longlong_t)usedobjs, blkbuf);
1693
1694	if (zopt_objects != 0) {
1695		for (i = 0; i < zopt_objects; i++)
1696			dump_object(os, zopt_object[i], verbosity,
1697			    &print_header);
1698		(void) printf("\n");
1699		return;
1700	}
1701
1702	if (dump_opt['i'] != 0 || verbosity >= 2)
1703		dump_intent_log(dmu_objset_zil(os));
1704
1705	if (dmu_objset_ds(os) != NULL)
1706		dump_deadlist(&dmu_objset_ds(os)->ds_deadlist);
1707
1708	if (verbosity < 2)
1709		return;
1710
1711	if (os->os_rootbp->blk_birth == 0)
1712		return;
1713
1714	dump_object(os, 0, verbosity, &print_header);
1715	object_count = 0;
1716	if (DMU_USERUSED_DNODE(os) != NULL &&
1717	    DMU_USERUSED_DNODE(os)->dn_type != 0) {
1718		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header);
1719		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header);
1720	}
1721
1722	object = 0;
1723	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1724		dump_object(os, object, verbosity, &print_header);
1725		object_count++;
1726	}
1727
1728	ASSERT3U(object_count, ==, usedobjs);
1729
1730	(void) printf("\n");
1731
1732	if (error != ESRCH) {
1733		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
1734		abort();
1735	}
1736}
1737
1738static void
1739dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
1740{
1741	time_t timestamp = ub->ub_timestamp;
1742
1743	(void) printf(header ? header : "");
1744	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
1745	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
1746	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
1747	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
1748	(void) printf("\ttimestamp = %llu UTC = %s",
1749	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
1750	if (dump_opt['u'] >= 3) {
1751		char blkbuf[BP_SPRINTF_LEN];
1752		sprintf_blkptr(blkbuf, &ub->ub_rootbp);
1753		(void) printf("\trootbp = %s\n", blkbuf);
1754	}
1755	(void) printf(footer ? footer : "");
1756}
1757
1758static void
1759dump_config(spa_t *spa)
1760{
1761	dmu_buf_t *db;
1762	size_t nvsize = 0;
1763	int error = 0;
1764
1765
1766	error = dmu_bonus_hold(spa->spa_meta_objset,
1767	    spa->spa_config_object, FTAG, &db);
1768
1769	if (error == 0) {
1770		nvsize = *(uint64_t *)db->db_data;
1771		dmu_buf_rele(db, FTAG);
1772
1773		(void) printf("\nMOS Configuration:\n");
1774		dump_packed_nvlist(spa->spa_meta_objset,
1775		    spa->spa_config_object, (void *)&nvsize, 1);
1776	} else {
1777		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
1778		    (u_longlong_t)spa->spa_config_object, error);
1779	}
1780}
1781
1782static void
1783dump_cachefile(const char *cachefile)
1784{
1785	int fd;
1786	struct stat64 statbuf;
1787	char *buf;
1788	nvlist_t *config;
1789
1790	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
1791		(void) printf("cannot open '%s': %s\n", cachefile,
1792		    strerror(errno));
1793		exit(1);
1794	}
1795
1796	if (fstat64(fd, &statbuf) != 0) {
1797		(void) printf("failed to stat '%s': %s\n", cachefile,
1798		    strerror(errno));
1799		exit(1);
1800	}
1801
1802	if ((buf = malloc(statbuf.st_size)) == NULL) {
1803		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
1804		    (u_longlong_t)statbuf.st_size);
1805		exit(1);
1806	}
1807
1808	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1809		(void) fprintf(stderr, "failed to read %llu bytes\n",
1810		    (u_longlong_t)statbuf.st_size);
1811		exit(1);
1812	}
1813
1814	(void) close(fd);
1815
1816	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
1817		(void) fprintf(stderr, "failed to unpack nvlist\n");
1818		exit(1);
1819	}
1820
1821	free(buf);
1822
1823	dump_nvlist(config, 0);
1824
1825	nvlist_free(config);
1826}
1827
1828#define	ZDB_MAX_UB_HEADER_SIZE 32
1829
1830static void
1831dump_label_uberblocks(vdev_label_t *lbl, uint64_t ashift)
1832{
1833	vdev_t vd;
1834	vdev_t *vdp = &vd;
1835	char header[ZDB_MAX_UB_HEADER_SIZE];
1836
1837	vd.vdev_ashift = ashift;
1838	vdp->vdev_top = vdp;
1839
1840	for (int i = 0; i < VDEV_UBERBLOCK_COUNT(vdp); i++) {
1841		uint64_t uoff = VDEV_UBERBLOCK_OFFSET(vdp, i);
1842		uberblock_t *ub = (void *)((char *)lbl + uoff);
1843
1844		if (uberblock_verify(ub))
1845			continue;
1846		(void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
1847		    "Uberblock[%d]\n", i);
1848		dump_uberblock(ub, header, "");
1849	}
1850}
1851
1852static void
1853dump_label(const char *dev)
1854{
1855	int fd;
1856	vdev_label_t label;
1857	char *path, *buf = label.vl_vdev_phys.vp_nvlist;
1858	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1859	struct stat64 statbuf;
1860	uint64_t psize, ashift;
1861	int len = strlen(dev) + 1;
1862
1863	if (strncmp(dev, "/dev/dsk/", 9) == 0) {
1864		len++;
1865		path = malloc(len);
1866		(void) snprintf(path, len, "%s%s", "/dev/rdsk/", dev + 9);
1867	} else {
1868		path = strdup(dev);
1869	}
1870
1871	if ((fd = open64(path, O_RDONLY)) < 0) {
1872		(void) printf("cannot open '%s': %s\n", path, strerror(errno));
1873		free(path);
1874		exit(1);
1875	}
1876
1877	if (fstat64(fd, &statbuf) != 0) {
1878		(void) printf("failed to stat '%s': %s\n", path,
1879		    strerror(errno));
1880		free(path);
1881		(void) close(fd);
1882		exit(1);
1883	}
1884
1885	if (S_ISBLK(statbuf.st_mode)) {
1886		(void) printf("cannot use '%s': character device required\n",
1887		    path);
1888		free(path);
1889		(void) close(fd);
1890		exit(1);
1891	}
1892
1893	psize = statbuf.st_size;
1894	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
1895
1896	for (int l = 0; l < VDEV_LABELS; l++) {
1897		nvlist_t *config = NULL;
1898
1899		(void) printf("--------------------------------------------\n");
1900		(void) printf("LABEL %d\n", l);
1901		(void) printf("--------------------------------------------\n");
1902
1903		if (pread64(fd, &label, sizeof (label),
1904		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
1905			(void) printf("failed to read label %d\n", l);
1906			continue;
1907		}
1908
1909		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
1910			(void) printf("failed to unpack label %d\n", l);
1911			ashift = SPA_MINBLOCKSHIFT;
1912		} else {
1913			nvlist_t *vdev_tree = NULL;
1914
1915			dump_nvlist(config, 4);
1916			if ((nvlist_lookup_nvlist(config,
1917			    ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
1918			    (nvlist_lookup_uint64(vdev_tree,
1919			    ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
1920				ashift = SPA_MINBLOCKSHIFT;
1921			nvlist_free(config);
1922		}
1923		if (dump_opt['u'])
1924			dump_label_uberblocks(&label, ashift);
1925	}
1926
1927	free(path);
1928	(void) close(fd);
1929}
1930
1931/*ARGSUSED*/
1932static int
1933dump_one_dir(const char *dsname, void *arg)
1934{
1935	int error;
1936	objset_t *os;
1937
1938	error = dmu_objset_own(dsname, DMU_OST_ANY, B_TRUE, FTAG, &os);
1939	if (error) {
1940		(void) printf("Could not open %s, error %d\n", dsname, error);
1941		return (0);
1942	}
1943	dump_dir(os);
1944	dmu_objset_disown(os, FTAG);
1945	fuid_table_destroy();
1946	sa_loaded = B_FALSE;
1947	return (0);
1948}
1949
1950/*
1951 * Block statistics.
1952 */
1953typedef struct zdb_blkstats {
1954	uint64_t	zb_asize;
1955	uint64_t	zb_lsize;
1956	uint64_t	zb_psize;
1957	uint64_t	zb_count;
1958} zdb_blkstats_t;
1959
1960/*
1961 * Extended object types to report deferred frees and dedup auto-ditto blocks.
1962 */
1963#define	ZDB_OT_DEFERRED	(DMU_OT_NUMTYPES + 0)
1964#define	ZDB_OT_DITTO	(DMU_OT_NUMTYPES + 1)
1965#define	ZDB_OT_OTHER	(DMU_OT_NUMTYPES + 2)
1966#define	ZDB_OT_TOTAL	(DMU_OT_NUMTYPES + 3)
1967
1968static char *zdb_ot_extname[] = {
1969	"deferred free",
1970	"dedup ditto",
1971	"other",
1972	"Total",
1973};
1974
1975#define	ZB_TOTAL	DN_MAX_LEVELS
1976
1977typedef struct zdb_cb {
1978	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
1979	uint64_t	zcb_dedup_asize;
1980	uint64_t	zcb_dedup_blocks;
1981	uint64_t	zcb_errors[256];
1982	int		zcb_readfails;
1983	int		zcb_haderrors;
1984	spa_t		*zcb_spa;
1985} zdb_cb_t;
1986
1987static void
1988zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
1989    dmu_object_type_t type)
1990{
1991	uint64_t refcnt = 0;
1992
1993	ASSERT(type < ZDB_OT_TOTAL);
1994
1995	if (zilog && zil_bp_tree_add(zilog, bp) != 0)
1996		return;
1997
1998	for (int i = 0; i < 4; i++) {
1999		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
2000		int t = (i & 1) ? type : ZDB_OT_TOTAL;
2001		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
2002
2003		zb->zb_asize += BP_GET_ASIZE(bp);
2004		zb->zb_lsize += BP_GET_LSIZE(bp);
2005		zb->zb_psize += BP_GET_PSIZE(bp);
2006		zb->zb_count++;
2007	}
2008
2009	if (dump_opt['L'])
2010		return;
2011
2012	if (BP_GET_DEDUP(bp)) {
2013		ddt_t *ddt;
2014		ddt_entry_t *dde;
2015
2016		ddt = ddt_select(zcb->zcb_spa, bp);
2017		ddt_enter(ddt);
2018		dde = ddt_lookup(ddt, bp, B_FALSE);
2019
2020		if (dde == NULL) {
2021			refcnt = 0;
2022		} else {
2023			ddt_phys_t *ddp = ddt_phys_select(dde, bp);
2024			ddt_phys_decref(ddp);
2025			refcnt = ddp->ddp_refcnt;
2026			if (ddt_phys_total_refcnt(dde) == 0)
2027				ddt_remove(ddt, dde);
2028		}
2029		ddt_exit(ddt);
2030	}
2031
2032	VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
2033	    refcnt ? 0 : spa_first_txg(zcb->zcb_spa),
2034	    bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
2035}
2036
2037static void
2038zdb_blkptr_done(zio_t *zio)
2039{
2040	spa_t *spa = zio->io_spa;
2041	blkptr_t *bp = zio->io_bp;
2042	int ioerr = zio->io_error;
2043	zdb_cb_t *zcb = zio->io_private;
2044	zbookmark_t *zb = &zio->io_bookmark;
2045
2046	zio_data_buf_free(zio->io_data, zio->io_size);
2047
2048	mutex_enter(&spa->spa_scrub_lock);
2049	spa->spa_scrub_inflight--;
2050	cv_broadcast(&spa->spa_scrub_io_cv);
2051
2052	if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
2053		char blkbuf[BP_SPRINTF_LEN];
2054
2055		zcb->zcb_haderrors = 1;
2056		zcb->zcb_errors[ioerr]++;
2057
2058		if (dump_opt['b'] >= 2)
2059			sprintf_blkptr(blkbuf, bp);
2060		else
2061			blkbuf[0] = '\0';
2062
2063		(void) printf("zdb_blkptr_cb: "
2064		    "Got error %d reading "
2065		    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
2066		    ioerr,
2067		    (u_longlong_t)zb->zb_objset,
2068		    (u_longlong_t)zb->zb_object,
2069		    (u_longlong_t)zb->zb_level,
2070		    (u_longlong_t)zb->zb_blkid,
2071		    blkbuf);
2072	}
2073	mutex_exit(&spa->spa_scrub_lock);
2074}
2075
2076/* ARGSUSED */
2077static int
2078zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp, arc_buf_t *pbuf,
2079    const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
2080{
2081	zdb_cb_t *zcb = arg;
2082	char blkbuf[BP_SPRINTF_LEN];
2083	dmu_object_type_t type;
2084	boolean_t is_metadata;
2085
2086	if (bp == NULL)
2087		return (0);
2088
2089	type = BP_GET_TYPE(bp);
2090
2091	zdb_count_block(zcb, zilog, bp,
2092	    (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
2093
2094	is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
2095
2096	if (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata)) {
2097		size_t size = BP_GET_PSIZE(bp);
2098		void *data = zio_data_buf_alloc(size);
2099		int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
2100
2101		/* If it's an intent log block, failure is expected. */
2102		if (zb->zb_level == ZB_ZIL_LEVEL)
2103			flags |= ZIO_FLAG_SPECULATIVE;
2104
2105		mutex_enter(&spa->spa_scrub_lock);
2106		while (spa->spa_scrub_inflight > max_inflight)
2107			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2108		spa->spa_scrub_inflight++;
2109		mutex_exit(&spa->spa_scrub_lock);
2110
2111		zio_nowait(zio_read(NULL, spa, bp, data, size,
2112		    zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
2113
2114	}
2115
2116	zcb->zcb_readfails = 0;
2117
2118	if (dump_opt['b'] >= 4) {
2119		sprintf_blkptr(blkbuf, bp);
2120		(void) printf("objset %llu object %llu "
2121		    "level %lld offset 0x%llx %s\n",
2122		    (u_longlong_t)zb->zb_objset,
2123		    (u_longlong_t)zb->zb_object,
2124		    (longlong_t)zb->zb_level,
2125		    (u_longlong_t)blkid2offset(dnp, bp, zb),
2126		    blkbuf);
2127	}
2128
2129	return (0);
2130}
2131
2132static void
2133zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
2134{
2135	vdev_t *vd = sm->sm_ppd;
2136
2137	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
2138	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
2139}
2140
2141/* ARGSUSED */
2142static void
2143zdb_space_map_load(space_map_t *sm)
2144{
2145}
2146
2147static void
2148zdb_space_map_unload(space_map_t *sm)
2149{
2150	space_map_vacate(sm, zdb_leak, sm);
2151}
2152
2153/* ARGSUSED */
2154static void
2155zdb_space_map_claim(space_map_t *sm, uint64_t start, uint64_t size)
2156{
2157}
2158
2159static space_map_ops_t zdb_space_map_ops = {
2160	zdb_space_map_load,
2161	zdb_space_map_unload,
2162	NULL,	/* alloc */
2163	zdb_space_map_claim,
2164	NULL,	/* free */
2165	NULL	/* maxsize */
2166};
2167
2168static void
2169zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
2170{
2171	ddt_bookmark_t ddb = { 0 };
2172	ddt_entry_t dde;
2173	int error;
2174
2175	while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
2176		blkptr_t blk;
2177		ddt_phys_t *ddp = dde.dde_phys;
2178
2179		if (ddb.ddb_class == DDT_CLASS_UNIQUE)
2180			return;
2181
2182		ASSERT(ddt_phys_total_refcnt(&dde) > 1);
2183
2184		for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2185			if (ddp->ddp_phys_birth == 0)
2186				continue;
2187			ddt_bp_create(ddb.ddb_checksum,
2188			    &dde.dde_key, ddp, &blk);
2189			if (p == DDT_PHYS_DITTO) {
2190				zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
2191			} else {
2192				zcb->zcb_dedup_asize +=
2193				    BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
2194				zcb->zcb_dedup_blocks++;
2195			}
2196		}
2197		if (!dump_opt['L']) {
2198			ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
2199			ddt_enter(ddt);
2200			VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
2201			ddt_exit(ddt);
2202		}
2203	}
2204
2205	ASSERT(error == ENOENT);
2206}
2207
2208static void
2209zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
2210{
2211	zcb->zcb_spa = spa;
2212
2213	if (!dump_opt['L']) {
2214		vdev_t *rvd = spa->spa_root_vdev;
2215		for (int c = 0; c < rvd->vdev_children; c++) {
2216			vdev_t *vd = rvd->vdev_child[c];
2217			for (int m = 0; m < vd->vdev_ms_count; m++) {
2218				metaslab_t *msp = vd->vdev_ms[m];
2219				mutex_enter(&msp->ms_lock);
2220				space_map_unload(&msp->ms_map);
2221				VERIFY(space_map_load(&msp->ms_map,
2222				    &zdb_space_map_ops, SM_ALLOC, &msp->ms_smo,
2223				    spa->spa_meta_objset) == 0);
2224				msp->ms_map.sm_ppd = vd;
2225				mutex_exit(&msp->ms_lock);
2226			}
2227		}
2228	}
2229
2230	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2231
2232	zdb_ddt_leak_init(spa, zcb);
2233
2234	spa_config_exit(spa, SCL_CONFIG, FTAG);
2235}
2236
2237static void
2238zdb_leak_fini(spa_t *spa)
2239{
2240	if (!dump_opt['L']) {
2241		vdev_t *rvd = spa->spa_root_vdev;
2242		for (int c = 0; c < rvd->vdev_children; c++) {
2243			vdev_t *vd = rvd->vdev_child[c];
2244			for (int m = 0; m < vd->vdev_ms_count; m++) {
2245				metaslab_t *msp = vd->vdev_ms[m];
2246				mutex_enter(&msp->ms_lock);
2247				space_map_unload(&msp->ms_map);
2248				mutex_exit(&msp->ms_lock);
2249			}
2250		}
2251	}
2252}
2253
2254/* ARGSUSED */
2255static int
2256count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2257{
2258	zdb_cb_t *zcb = arg;
2259
2260	if (dump_opt['b'] >= 4) {
2261		char blkbuf[BP_SPRINTF_LEN];
2262		sprintf_blkptr(blkbuf, bp);
2263		(void) printf("[%s] %s\n",
2264		    "deferred free", blkbuf);
2265	}
2266	zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
2267	return (0);
2268}
2269
2270static int
2271dump_block_stats(spa_t *spa)
2272{
2273	zdb_cb_t zcb = { 0 };
2274	zdb_blkstats_t *zb, *tzb;
2275	uint64_t norm_alloc, norm_space, total_alloc, total_found;
2276	int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA | TRAVERSE_HARD;
2277	int leaks = 0;
2278
2279	(void) printf("\nTraversing all blocks %s%s%s%s%s...\n",
2280	    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
2281	    (dump_opt['c'] == 1) ? "metadata " : "",
2282	    dump_opt['c'] ? "checksums " : "",
2283	    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
2284	    !dump_opt['L'] ? "nothing leaked " : "");
2285
2286	/*
2287	 * Load all space maps as SM_ALLOC maps, then traverse the pool
2288	 * claiming each block we discover.  If the pool is perfectly
2289	 * consistent, the space maps will be empty when we're done.
2290	 * Anything left over is a leak; any block we can't claim (because
2291	 * it's not part of any space map) is a double allocation,
2292	 * reference to a freed block, or an unclaimed log block.
2293	 */
2294	zdb_leak_init(spa, &zcb);
2295
2296	/*
2297	 * If there's a deferred-free bplist, process that first.
2298	 */
2299	(void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
2300	    count_block_cb, &zcb, NULL);
2301	(void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
2302	    count_block_cb, &zcb, NULL);
2303	if (spa_feature_is_active(spa,
2304	    &spa_feature_table[SPA_FEATURE_ASYNC_DESTROY])) {
2305		VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
2306		    spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
2307		    &zcb, NULL));
2308	}
2309
2310	if (dump_opt['c'] > 1)
2311		flags |= TRAVERSE_PREFETCH_DATA;
2312
2313	zcb.zcb_haderrors |= traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
2314
2315	/*
2316	 * If we've traversed the data blocks then we need to wait for those
2317	 * I/Os to complete. We leverage "The Godfather" zio to wait on
2318	 * all async I/Os to complete.
2319	 */
2320	if (dump_opt['c']) {
2321		(void) zio_wait(spa->spa_async_zio_root);
2322		spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
2323		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2324		    ZIO_FLAG_GODFATHER);
2325	}
2326
2327	if (zcb.zcb_haderrors) {
2328		(void) printf("\nError counts:\n\n");
2329		(void) printf("\t%5s  %s\n", "errno", "count");
2330		for (int e = 0; e < 256; e++) {
2331			if (zcb.zcb_errors[e] != 0) {
2332				(void) printf("\t%5d  %llu\n",
2333				    e, (u_longlong_t)zcb.zcb_errors[e]);
2334			}
2335		}
2336	}
2337
2338	/*
2339	 * Report any leaked segments.
2340	 */
2341	zdb_leak_fini(spa);
2342
2343	tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
2344
2345	norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
2346	norm_space = metaslab_class_get_space(spa_normal_class(spa));
2347
2348	total_alloc = norm_alloc + metaslab_class_get_alloc(spa_log_class(spa));
2349	total_found = tzb->zb_asize - zcb.zcb_dedup_asize;
2350
2351	if (total_found == total_alloc) {
2352		if (!dump_opt['L'])
2353			(void) printf("\n\tNo leaks (block sum matches space"
2354			    " maps exactly)\n");
2355	} else {
2356		(void) printf("block traversal size %llu != alloc %llu "
2357		    "(%s %lld)\n",
2358		    (u_longlong_t)total_found,
2359		    (u_longlong_t)total_alloc,
2360		    (dump_opt['L']) ? "unreachable" : "leaked",
2361		    (longlong_t)(total_alloc - total_found));
2362		leaks = 1;
2363	}
2364
2365	if (tzb->zb_count == 0)
2366		return (2);
2367
2368	(void) printf("\n");
2369	(void) printf("\tbp count:      %10llu\n",
2370	    (u_longlong_t)tzb->zb_count);
2371	(void) printf("\tbp logical:    %10llu      avg: %6llu\n",
2372	    (u_longlong_t)tzb->zb_lsize,
2373	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
2374	(void) printf("\tbp physical:   %10llu      avg:"
2375	    " %6llu     compression: %6.2f\n",
2376	    (u_longlong_t)tzb->zb_psize,
2377	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
2378	    (double)tzb->zb_lsize / tzb->zb_psize);
2379	(void) printf("\tbp allocated:  %10llu      avg:"
2380	    " %6llu     compression: %6.2f\n",
2381	    (u_longlong_t)tzb->zb_asize,
2382	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
2383	    (double)tzb->zb_lsize / tzb->zb_asize);
2384	(void) printf("\tbp deduped:    %10llu    ref>1:"
2385	    " %6llu   deduplication: %6.2f\n",
2386	    (u_longlong_t)zcb.zcb_dedup_asize,
2387	    (u_longlong_t)zcb.zcb_dedup_blocks,
2388	    (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
2389	(void) printf("\tSPA allocated: %10llu     used: %5.2f%%\n",
2390	    (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
2391
2392	if (dump_opt['b'] >= 2) {
2393		int l, t, level;
2394		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
2395		    "\t  avg\t comp\t%%Total\tType\n");
2396
2397		for (t = 0; t <= ZDB_OT_TOTAL; t++) {
2398			char csize[32], lsize[32], psize[32], asize[32];
2399			char avg[32];
2400			char *typename;
2401
2402			if (t < DMU_OT_NUMTYPES)
2403				typename = dmu_ot[t].ot_name;
2404			else
2405				typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
2406
2407			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
2408				(void) printf("%6s\t%5s\t%5s\t%5s"
2409				    "\t%5s\t%5s\t%6s\t%s\n",
2410				    "-",
2411				    "-",
2412				    "-",
2413				    "-",
2414				    "-",
2415				    "-",
2416				    "-",
2417				    typename);
2418				continue;
2419			}
2420
2421			for (l = ZB_TOTAL - 1; l >= -1; l--) {
2422				level = (l == -1 ? ZB_TOTAL : l);
2423				zb = &zcb.zcb_type[level][t];
2424
2425				if (zb->zb_asize == 0)
2426					continue;
2427
2428				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
2429					continue;
2430
2431				if (level == 0 && zb->zb_asize ==
2432				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
2433					continue;
2434
2435				zdb_nicenum(zb->zb_count, csize);
2436				zdb_nicenum(zb->zb_lsize, lsize);
2437				zdb_nicenum(zb->zb_psize, psize);
2438				zdb_nicenum(zb->zb_asize, asize);
2439				zdb_nicenum(zb->zb_asize / zb->zb_count, avg);
2440
2441				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
2442				    "\t%5.2f\t%6.2f\t",
2443				    csize, lsize, psize, asize, avg,
2444				    (double)zb->zb_lsize / zb->zb_psize,
2445				    100.0 * zb->zb_asize / tzb->zb_asize);
2446
2447				if (level == ZB_TOTAL)
2448					(void) printf("%s\n", typename);
2449				else
2450					(void) printf("    L%d %s\n",
2451					    level, typename);
2452			}
2453		}
2454	}
2455
2456	(void) printf("\n");
2457
2458	if (leaks)
2459		return (2);
2460
2461	if (zcb.zcb_haderrors)
2462		return (3);
2463
2464	return (0);
2465}
2466
2467typedef struct zdb_ddt_entry {
2468	ddt_key_t	zdde_key;
2469	uint64_t	zdde_ref_blocks;
2470	uint64_t	zdde_ref_lsize;
2471	uint64_t	zdde_ref_psize;
2472	uint64_t	zdde_ref_dsize;
2473	avl_node_t	zdde_node;
2474} zdb_ddt_entry_t;
2475
2476/* ARGSUSED */
2477static int
2478zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2479    arc_buf_t *pbuf, const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
2480{
2481	avl_tree_t *t = arg;
2482	avl_index_t where;
2483	zdb_ddt_entry_t *zdde, zdde_search;
2484
2485	if (bp == NULL)
2486		return (0);
2487
2488	if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
2489		(void) printf("traversing objset %llu, %llu objects, "
2490		    "%lu blocks so far\n",
2491		    (u_longlong_t)zb->zb_objset,
2492		    (u_longlong_t)bp->blk_fill,
2493		    avl_numnodes(t));
2494	}
2495
2496	if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
2497	    BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
2498		return (0);
2499
2500	ddt_key_fill(&zdde_search.zdde_key, bp);
2501
2502	zdde = avl_find(t, &zdde_search, &where);
2503
2504	if (zdde == NULL) {
2505		zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
2506		zdde->zdde_key = zdde_search.zdde_key;
2507		avl_insert(t, zdde, where);
2508	}
2509
2510	zdde->zdde_ref_blocks += 1;
2511	zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
2512	zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
2513	zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
2514
2515	return (0);
2516}
2517
2518static void
2519dump_simulated_ddt(spa_t *spa)
2520{
2521	avl_tree_t t;
2522	void *cookie = NULL;
2523	zdb_ddt_entry_t *zdde;
2524	ddt_histogram_t ddh_total = { 0 };
2525	ddt_stat_t dds_total = { 0 };
2526
2527	avl_create(&t, ddt_entry_compare,
2528	    sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
2529
2530	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2531
2532	(void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2533	    zdb_ddt_add_cb, &t);
2534
2535	spa_config_exit(spa, SCL_CONFIG, FTAG);
2536
2537	while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
2538		ddt_stat_t dds;
2539		uint64_t refcnt = zdde->zdde_ref_blocks;
2540		ASSERT(refcnt != 0);
2541
2542		dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
2543		dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
2544		dds.dds_psize = zdde->zdde_ref_psize / refcnt;
2545		dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
2546
2547		dds.dds_ref_blocks = zdde->zdde_ref_blocks;
2548		dds.dds_ref_lsize = zdde->zdde_ref_lsize;
2549		dds.dds_ref_psize = zdde->zdde_ref_psize;
2550		dds.dds_ref_dsize = zdde->zdde_ref_dsize;
2551
2552		ddt_stat_add(&ddh_total.ddh_stat[highbit(refcnt) - 1], &dds, 0);
2553
2554		umem_free(zdde, sizeof (*zdde));
2555	}
2556
2557	avl_destroy(&t);
2558
2559	ddt_histogram_stat(&dds_total, &ddh_total);
2560
2561	(void) printf("Simulated DDT histogram:\n");
2562
2563	zpool_dump_ddt(&dds_total, &ddh_total);
2564
2565	dump_dedup_ratio(&dds_total);
2566}
2567
2568static void
2569dump_zpool(spa_t *spa)
2570{
2571	dsl_pool_t *dp = spa_get_dsl(spa);
2572	int rc = 0;
2573
2574	if (dump_opt['S']) {
2575		dump_simulated_ddt(spa);
2576		return;
2577	}
2578
2579	if (!dump_opt['e'] && dump_opt['C'] > 1) {
2580		(void) printf("\nCached configuration:\n");
2581		dump_nvlist(spa->spa_config, 8);
2582	}
2583
2584	if (dump_opt['C'])
2585		dump_config(spa);
2586
2587	if (dump_opt['u'])
2588		dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
2589
2590	if (dump_opt['D'])
2591		dump_all_ddts(spa);
2592
2593	if (dump_opt['d'] > 2 || dump_opt['m'])
2594		dump_metaslabs(spa);
2595
2596	if (dump_opt['d'] || dump_opt['i']) {
2597		dump_dir(dp->dp_meta_objset);
2598		if (dump_opt['d'] >= 3) {
2599			dump_bpobj(&spa->spa_deferred_bpobj, "Deferred frees");
2600			if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
2601				dump_bpobj(&spa->spa_dsl_pool->dp_free_bpobj,
2602				    "Pool snapshot frees");
2603			}
2604
2605			if (spa_feature_is_active(spa,
2606			    &spa_feature_table[SPA_FEATURE_ASYNC_DESTROY])) {
2607				dump_bptree(spa->spa_meta_objset,
2608				    spa->spa_dsl_pool->dp_bptree_obj,
2609				    "Pool dataset frees");
2610			}
2611			dump_dtl(spa->spa_root_vdev, 0);
2612		}
2613		(void) dmu_objset_find(spa_name(spa), dump_one_dir,
2614		    NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
2615	}
2616	if (dump_opt['b'] || dump_opt['c'])
2617		rc = dump_block_stats(spa);
2618
2619	if (dump_opt['s'])
2620		show_pool_stats(spa);
2621
2622	if (dump_opt['h'])
2623		dump_history(spa);
2624
2625	if (rc != 0)
2626		exit(rc);
2627}
2628
2629#define	ZDB_FLAG_CHECKSUM	0x0001
2630#define	ZDB_FLAG_DECOMPRESS	0x0002
2631#define	ZDB_FLAG_BSWAP		0x0004
2632#define	ZDB_FLAG_GBH		0x0008
2633#define	ZDB_FLAG_INDIRECT	0x0010
2634#define	ZDB_FLAG_PHYS		0x0020
2635#define	ZDB_FLAG_RAW		0x0040
2636#define	ZDB_FLAG_PRINT_BLKPTR	0x0080
2637
2638int flagbits[256];
2639
2640static void
2641zdb_print_blkptr(blkptr_t *bp, int flags)
2642{
2643	char blkbuf[BP_SPRINTF_LEN];
2644
2645	if (flags & ZDB_FLAG_BSWAP)
2646		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
2647
2648	sprintf_blkptr(blkbuf, bp);
2649	(void) printf("%s\n", blkbuf);
2650}
2651
2652static void
2653zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
2654{
2655	int i;
2656
2657	for (i = 0; i < nbps; i++)
2658		zdb_print_blkptr(&bp[i], flags);
2659}
2660
2661static void
2662zdb_dump_gbh(void *buf, int flags)
2663{
2664	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
2665}
2666
2667static void
2668zdb_dump_block_raw(void *buf, uint64_t size, int flags)
2669{
2670	if (flags & ZDB_FLAG_BSWAP)
2671		byteswap_uint64_array(buf, size);
2672	(void) write(1, buf, size);
2673}
2674
2675static void
2676zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
2677{
2678	uint64_t *d = (uint64_t *)buf;
2679	int nwords = size / sizeof (uint64_t);
2680	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
2681	int i, j;
2682	char *hdr, *c;
2683
2684
2685	if (do_bswap)
2686		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
2687	else
2688		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
2689
2690	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
2691
2692	for (i = 0; i < nwords; i += 2) {
2693		(void) printf("%06llx:  %016llx  %016llx  ",
2694		    (u_longlong_t)(i * sizeof (uint64_t)),
2695		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
2696		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
2697
2698		c = (char *)&d[i];
2699		for (j = 0; j < 2 * sizeof (uint64_t); j++)
2700			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
2701		(void) printf("\n");
2702	}
2703}
2704
2705/*
2706 * There are two acceptable formats:
2707 *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
2708 *	child[.child]*    - For example: 0.1.1
2709 *
2710 * The second form can be used to specify arbitrary vdevs anywhere
2711 * in the heirarchy.  For example, in a pool with a mirror of
2712 * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
2713 */
2714static vdev_t *
2715zdb_vdev_lookup(vdev_t *vdev, char *path)
2716{
2717	char *s, *p, *q;
2718	int i;
2719
2720	if (vdev == NULL)
2721		return (NULL);
2722
2723	/* First, assume the x.x.x.x format */
2724	i = (int)strtoul(path, &s, 10);
2725	if (s == path || (s && *s != '.' && *s != '\0'))
2726		goto name;
2727	if (i < 0 || i >= vdev->vdev_children)
2728		return (NULL);
2729
2730	vdev = vdev->vdev_child[i];
2731	if (*s == '\0')
2732		return (vdev);
2733	return (zdb_vdev_lookup(vdev, s+1));
2734
2735name:
2736	for (i = 0; i < vdev->vdev_children; i++) {
2737		vdev_t *vc = vdev->vdev_child[i];
2738
2739		if (vc->vdev_path == NULL) {
2740			vc = zdb_vdev_lookup(vc, path);
2741			if (vc == NULL)
2742				continue;
2743			else
2744				return (vc);
2745		}
2746
2747		p = strrchr(vc->vdev_path, '/');
2748		p = p ? p + 1 : vc->vdev_path;
2749		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2750
2751		if (strcmp(vc->vdev_path, path) == 0)
2752			return (vc);
2753		if (strcmp(p, path) == 0)
2754			return (vc);
2755		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2756			return (vc);
2757	}
2758
2759	return (NULL);
2760}
2761
2762/*
2763 * Read a block from a pool and print it out.  The syntax of the
2764 * block descriptor is:
2765 *
2766 *	pool:vdev_specifier:offset:size[:flags]
2767 *
2768 *	pool           - The name of the pool you wish to read from
2769 *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2770 *	offset         - offset, in hex, in bytes
2771 *	size           - Amount of data to read, in hex, in bytes
2772 *	flags          - A string of characters specifying options
2773 *		 b: Decode a blkptr at given offset within block
2774 *		*c: Calculate and display checksums
2775 *		 d: Decompress data before dumping
2776 *		 e: Byteswap data before dumping
2777 *		 g: Display data as a gang block header
2778 *		 i: Display as an indirect block
2779 *		 p: Do I/O to physical offset
2780 *		 r: Dump raw data to stdout
2781 *
2782 *              * = not yet implemented
2783 */
2784static void
2785zdb_read_block(char *thing, spa_t *spa)
2786{
2787	blkptr_t blk, *bp = &blk;
2788	dva_t *dva = bp->blk_dva;
2789	int flags = 0;
2790	uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
2791	zio_t *zio;
2792	vdev_t *vd;
2793	void *pbuf, *lbuf, *buf;
2794	char *s, *p, *dup, *vdev, *flagstr;
2795	int i, error;
2796
2797	dup = strdup(thing);
2798	s = strtok(dup, ":");
2799	vdev = s ? s : "";
2800	s = strtok(NULL, ":");
2801	offset = strtoull(s ? s : "", NULL, 16);
2802	s = strtok(NULL, ":");
2803	size = strtoull(s ? s : "", NULL, 16);
2804	s = strtok(NULL, ":");
2805	flagstr = s ? s : "";
2806
2807	s = NULL;
2808	if (size == 0)
2809		s = "size must not be zero";
2810	if (!IS_P2ALIGNED(size, DEV_BSIZE))
2811		s = "size must be a multiple of sector size";
2812	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
2813		s = "offset must be a multiple of sector size";
2814	if (s) {
2815		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
2816		free(dup);
2817		return;
2818	}
2819
2820	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
2821		for (i = 0; flagstr[i]; i++) {
2822			int bit = flagbits[(uchar_t)flagstr[i]];
2823
2824			if (bit == 0) {
2825				(void) printf("***Invalid flag: %c\n",
2826				    flagstr[i]);
2827				continue;
2828			}
2829			flags |= bit;
2830
2831			/* If it's not something with an argument, keep going */
2832			if ((bit & (ZDB_FLAG_CHECKSUM |
2833			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
2834				continue;
2835
2836			p = &flagstr[i + 1];
2837			if (bit == ZDB_FLAG_PRINT_BLKPTR)
2838				blkptr_offset = strtoull(p, &p, 16);
2839			if (*p != ':' && *p != '\0') {
2840				(void) printf("***Invalid flag arg: '%s'\n", s);
2841				free(dup);
2842				return;
2843			}
2844		}
2845	}
2846
2847	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2848	if (vd == NULL) {
2849		(void) printf("***Invalid vdev: %s\n", vdev);
2850		free(dup);
2851		return;
2852	} else {
2853		if (vd->vdev_path)
2854			(void) fprintf(stderr, "Found vdev: %s\n",
2855			    vd->vdev_path);
2856		else
2857			(void) fprintf(stderr, "Found vdev type: %s\n",
2858			    vd->vdev_ops->vdev_op_type);
2859	}
2860
2861	psize = size;
2862	lsize = size;
2863
2864	pbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2865	lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2866
2867	BP_ZERO(bp);
2868
2869	DVA_SET_VDEV(&dva[0], vd->vdev_id);
2870	DVA_SET_OFFSET(&dva[0], offset);
2871	DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
2872	DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
2873
2874	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
2875
2876	BP_SET_LSIZE(bp, lsize);
2877	BP_SET_PSIZE(bp, psize);
2878	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
2879	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
2880	BP_SET_TYPE(bp, DMU_OT_NONE);
2881	BP_SET_LEVEL(bp, 0);
2882	BP_SET_DEDUP(bp, 0);
2883	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
2884
2885	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
2886	zio = zio_root(spa, NULL, NULL, 0);
2887
2888	if (vd == vd->vdev_top) {
2889		/*
2890		 * Treat this as a normal block read.
2891		 */
2892		zio_nowait(zio_read(zio, spa, bp, pbuf, psize, NULL, NULL,
2893		    ZIO_PRIORITY_SYNC_READ,
2894		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
2895	} else {
2896		/*
2897		 * Treat this as a vdev child I/O.
2898		 */
2899		zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pbuf, psize,
2900		    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
2901		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2902		    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
2903		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL, NULL));
2904	}
2905
2906	error = zio_wait(zio);
2907	spa_config_exit(spa, SCL_STATE, FTAG);
2908
2909	if (error) {
2910		(void) printf("Read of %s failed, error: %d\n", thing, error);
2911		goto out;
2912	}
2913
2914	if (flags & ZDB_FLAG_DECOMPRESS) {
2915		/*
2916		 * We don't know how the data was compressed, so just try
2917		 * every decompress function at every inflated blocksize.
2918		 */
2919		enum zio_compress c;
2920		void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2921		void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
2922
2923		bcopy(pbuf, pbuf2, psize);
2924
2925		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf + psize,
2926		    SPA_MAXBLOCKSIZE - psize) == 0);
2927
2928		VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
2929		    SPA_MAXBLOCKSIZE - psize) == 0);
2930
2931		for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
2932		    lsize -= SPA_MINBLOCKSIZE) {
2933			for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
2934				if (zio_decompress_data(c, pbuf, lbuf,
2935				    psize, lsize) == 0 &&
2936				    zio_decompress_data(c, pbuf2, lbuf2,
2937				    psize, lsize) == 0 &&
2938				    bcmp(lbuf, lbuf2, lsize) == 0)
2939					break;
2940			}
2941			if (c != ZIO_COMPRESS_FUNCTIONS)
2942				break;
2943			lsize -= SPA_MINBLOCKSIZE;
2944		}
2945
2946		umem_free(pbuf2, SPA_MAXBLOCKSIZE);
2947		umem_free(lbuf2, SPA_MAXBLOCKSIZE);
2948
2949		if (lsize <= psize) {
2950			(void) printf("Decompress of %s failed\n", thing);
2951			goto out;
2952		}
2953		buf = lbuf;
2954		size = lsize;
2955	} else {
2956		buf = pbuf;
2957		size = psize;
2958	}
2959
2960	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2961		zdb_print_blkptr((blkptr_t *)(void *)
2962		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2963	else if (flags & ZDB_FLAG_RAW)
2964		zdb_dump_block_raw(buf, size, flags);
2965	else if (flags & ZDB_FLAG_INDIRECT)
2966		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2967		    flags);
2968	else if (flags & ZDB_FLAG_GBH)
2969		zdb_dump_gbh(buf, flags);
2970	else
2971		zdb_dump_block(thing, buf, size, flags);
2972
2973out:
2974	umem_free(pbuf, SPA_MAXBLOCKSIZE);
2975	umem_free(lbuf, SPA_MAXBLOCKSIZE);
2976	free(dup);
2977}
2978
2979static boolean_t
2980pool_match(nvlist_t *cfg, char *tgt)
2981{
2982	uint64_t v, guid = strtoull(tgt, NULL, 0);
2983	char *s;
2984
2985	if (guid != 0) {
2986		if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
2987			return (v == guid);
2988	} else {
2989		if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
2990			return (strcmp(s, tgt) == 0);
2991	}
2992	return (B_FALSE);
2993}
2994
2995static char *
2996find_zpool(char **target, nvlist_t **configp, int dirc, char **dirv)
2997{
2998	nvlist_t *pools;
2999	nvlist_t *match = NULL;
3000	char *name = NULL;
3001	char *sepp = NULL;
3002	char sep;
3003	int count = 0;
3004	importargs_t args = { 0 };
3005
3006	args.paths = dirc;
3007	args.path = dirv;
3008	args.can_be_active = B_TRUE;
3009
3010	if ((sepp = strpbrk(*target, "/@")) != NULL) {
3011		sep = *sepp;
3012		*sepp = '\0';
3013	}
3014
3015	pools = zpool_search_import(g_zfs, &args);
3016
3017	if (pools != NULL) {
3018		nvpair_t *elem = NULL;
3019		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3020			verify(nvpair_value_nvlist(elem, configp) == 0);
3021			if (pool_match(*configp, *target)) {
3022				count++;
3023				if (match != NULL) {
3024					/* print previously found config */
3025					if (name != NULL) {
3026						(void) printf("%s\n", name);
3027						dump_nvlist(match, 8);
3028						name = NULL;
3029					}
3030					(void) printf("%s\n",
3031					    nvpair_name(elem));
3032					dump_nvlist(*configp, 8);
3033				} else {
3034					match = *configp;
3035					name = nvpair_name(elem);
3036				}
3037			}
3038		}
3039	}
3040	if (count > 1)
3041		(void) fatal("\tMatched %d pools - use pool GUID "
3042		    "instead of pool name or \n"
3043		    "\tpool name part of a dataset name to select pool", count);
3044
3045	if (sepp)
3046		*sepp = sep;
3047	/*
3048	 * If pool GUID was specified for pool id, replace it with pool name
3049	 */
3050	if (name && (strstr(*target, name) != *target)) {
3051		int sz = 1 + strlen(name) + ((sepp) ? strlen(sepp) : 0);
3052
3053		*target = umem_alloc(sz, UMEM_NOFAIL);
3054		(void) snprintf(*target, sz, "%s%s", name, sepp ? sepp : "");
3055	}
3056
3057	*configp = name ? match : NULL;
3058
3059	return (name);
3060}
3061
3062int
3063main(int argc, char **argv)
3064{
3065	int i, c;
3066	struct rlimit rl = { 1024, 1024 };
3067	spa_t *spa = NULL;
3068	objset_t *os = NULL;
3069	int dump_all = 1;
3070	int verbose = 0;
3071	int error = 0;
3072	char **searchdirs = NULL;
3073	int nsearch = 0;
3074	char *target;
3075	nvlist_t *policy = NULL;
3076	uint64_t max_txg = UINT64_MAX;
3077	int rewind = ZPOOL_NEVER_REWIND;
3078
3079	(void) setrlimit(RLIMIT_NOFILE, &rl);
3080	(void) enable_extended_FILE_stdio(-1, -1);
3081
3082	dprintf_setup(&argc, argv);
3083
3084	while ((c = getopt(argc, argv, "bcdhilmM:suCDRSAFLXevp:t:U:P")) != -1) {
3085		switch (c) {
3086		case 'b':
3087		case 'c':
3088		case 'd':
3089		case 'h':
3090		case 'i':
3091		case 'l':
3092		case 'm':
3093		case 's':
3094		case 'u':
3095		case 'C':
3096		case 'D':
3097		case 'R':
3098		case 'S':
3099			dump_opt[c]++;
3100			dump_all = 0;
3101			break;
3102		case 'A':
3103		case 'F':
3104		case 'L':
3105		case 'X':
3106		case 'e':
3107		case 'P':
3108			dump_opt[c]++;
3109			break;
3110		case 'v':
3111			verbose++;
3112			break;
3113		case 'M':
3114			max_inflight = strtoull(optarg, NULL, 0);
3115			if (max_inflight == 0) {
3116				(void) fprintf(stderr, "maximum number "
3117				    "of inflight I/Os must be greater "
3118				    "than 0\n");
3119				usage();
3120			}
3121			break;
3122		case 'p':
3123			if (searchdirs == NULL) {
3124				searchdirs = umem_alloc(sizeof (char *),
3125				    UMEM_NOFAIL);
3126			} else {
3127				char **tmp = umem_alloc((nsearch + 1) *
3128				    sizeof (char *), UMEM_NOFAIL);
3129				bcopy(searchdirs, tmp, nsearch *
3130				    sizeof (char *));
3131				umem_free(searchdirs,
3132				    nsearch * sizeof (char *));
3133				searchdirs = tmp;
3134			}
3135			searchdirs[nsearch++] = optarg;
3136			break;
3137		case 't':
3138			max_txg = strtoull(optarg, NULL, 0);
3139			if (max_txg < TXG_INITIAL) {
3140				(void) fprintf(stderr, "incorrect txg "
3141				    "specified: %s\n", optarg);
3142				usage();
3143			}
3144			break;
3145		case 'U':
3146			spa_config_path = optarg;
3147			break;
3148		default:
3149			usage();
3150			break;
3151		}
3152	}
3153
3154	if (!dump_opt['e'] && searchdirs != NULL) {
3155		(void) fprintf(stderr, "-p option requires use of -e\n");
3156		usage();
3157	}
3158
3159	kernel_init(FREAD);
3160	g_zfs = libzfs_init();
3161	ASSERT(g_zfs != NULL);
3162
3163	if (dump_all)
3164		verbose = MAX(verbose, 1);
3165
3166	for (c = 0; c < 256; c++) {
3167		if (dump_all && !strchr("elAFLRSXP", c))
3168			dump_opt[c] = 1;
3169		if (dump_opt[c])
3170			dump_opt[c] += verbose;
3171	}
3172
3173	aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
3174	zfs_recover = (dump_opt['A'] > 1);
3175
3176	argc -= optind;
3177	argv += optind;
3178
3179	if (argc < 2 && dump_opt['R'])
3180		usage();
3181	if (argc < 1) {
3182		if (!dump_opt['e'] && dump_opt['C']) {
3183			dump_cachefile(spa_config_path);
3184			return (0);
3185		}
3186		usage();
3187	}
3188
3189	if (dump_opt['l']) {
3190		dump_label(argv[0]);
3191		return (0);
3192	}
3193
3194	if (dump_opt['X'] || dump_opt['F'])
3195		rewind = ZPOOL_DO_REWIND |
3196		    (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
3197
3198	if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
3199	    nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, max_txg) != 0 ||
3200	    nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind) != 0)
3201		fatal("internal error: %s", strerror(ENOMEM));
3202
3203	error = 0;
3204	target = argv[0];
3205
3206	if (dump_opt['e']) {
3207		nvlist_t *cfg = NULL;
3208		char *name = find_zpool(&target, &cfg, nsearch, searchdirs);
3209
3210		error = ENOENT;
3211		if (name) {
3212			if (dump_opt['C'] > 1) {
3213				(void) printf("\nConfiguration for import:\n");
3214				dump_nvlist(cfg, 8);
3215			}
3216			if (nvlist_add_nvlist(cfg,
3217			    ZPOOL_REWIND_POLICY, policy) != 0) {
3218				fatal("can't open '%s': %s",
3219				    target, strerror(ENOMEM));
3220			}
3221			if ((error = spa_import(name, cfg, NULL,
3222			    ZFS_IMPORT_MISSING_LOG)) != 0) {
3223				error = spa_import(name, cfg, NULL,
3224				    ZFS_IMPORT_VERBATIM);
3225			}
3226		}
3227	}
3228
3229	if (error == 0) {
3230		if (strpbrk(target, "/@") == NULL || dump_opt['R']) {
3231			error = spa_open_rewind(target, &spa, FTAG, policy,
3232			    NULL);
3233			if (error) {
3234				/*
3235				 * If we're missing the log device then
3236				 * try opening the pool after clearing the
3237				 * log state.
3238				 */
3239				mutex_enter(&spa_namespace_lock);
3240				if ((spa = spa_lookup(target)) != NULL &&
3241				    spa->spa_log_state == SPA_LOG_MISSING) {
3242					spa->spa_log_state = SPA_LOG_CLEAR;
3243					error = 0;
3244				}
3245				mutex_exit(&spa_namespace_lock);
3246
3247				if (!error) {
3248					error = spa_open_rewind(target, &spa,
3249					    FTAG, policy, NULL);
3250				}
3251			}
3252		} else {
3253			error = dmu_objset_own(target, DMU_OST_ANY,
3254			    B_TRUE, FTAG, &os);
3255		}
3256	}
3257	nvlist_free(policy);
3258
3259	if (error)
3260		fatal("can't open '%s': %s", target, strerror(error));
3261
3262	argv++;
3263	argc--;
3264	if (!dump_opt['R']) {
3265		if (argc > 0) {
3266			zopt_objects = argc;
3267			zopt_object = calloc(zopt_objects, sizeof (uint64_t));
3268			for (i = 0; i < zopt_objects; i++) {
3269				errno = 0;
3270				zopt_object[i] = strtoull(argv[i], NULL, 0);
3271				if (zopt_object[i] == 0 && errno != 0)
3272					fatal("bad number %s: %s",
3273					    argv[i], strerror(errno));
3274			}
3275		}
3276		if (os != NULL) {
3277			dump_dir(os);
3278		} else if (zopt_objects > 0 && !dump_opt['m']) {
3279			dump_dir(spa->spa_meta_objset);
3280		} else {
3281			dump_zpool(spa);
3282		}
3283	} else {
3284		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
3285		flagbits['c'] = ZDB_FLAG_CHECKSUM;
3286		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
3287		flagbits['e'] = ZDB_FLAG_BSWAP;
3288		flagbits['g'] = ZDB_FLAG_GBH;
3289		flagbits['i'] = ZDB_FLAG_INDIRECT;
3290		flagbits['p'] = ZDB_FLAG_PHYS;
3291		flagbits['r'] = ZDB_FLAG_RAW;
3292
3293		for (i = 0; i < argc; i++)
3294			zdb_read_block(argv[i], spa);
3295	}
3296
3297	(os != NULL) ? dmu_objset_disown(os, FTAG) : spa_close(spa, FTAG);
3298
3299	fuid_table_destroy();
3300	sa_loaded = B_FALSE;
3301
3302	libzfs_fini(g_zfs);
3303	kernel_fini();
3304
3305	return (0);
3306}
3307