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