xref: /illumos-gate/usr/src/cmd/zdb/zdb.c (revision f0a05239)
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, 2019 by Delphix. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  * Copyright 2017 Nexenta Systems, Inc.
27  * Copyright (c) 2017, 2018 Lawrence Livermore National Security, LLC.
28  * Copyright 2017 RackTop Systems.
29  */
30 
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <stdio_ext.h>
34 #include <stdlib.h>
35 #include <ctype.h>
36 #include <sys/zfs_context.h>
37 #include <sys/spa.h>
38 #include <sys/spa_impl.h>
39 #include <sys/dmu.h>
40 #include <sys/zap.h>
41 #include <sys/fs/zfs.h>
42 #include <sys/zfs_znode.h>
43 #include <sys/zfs_sa.h>
44 #include <sys/sa.h>
45 #include <sys/sa_impl.h>
46 #include <sys/vdev.h>
47 #include <sys/vdev_impl.h>
48 #include <sys/metaslab_impl.h>
49 #include <sys/dmu_objset.h>
50 #include <sys/dsl_dir.h>
51 #include <sys/dsl_dataset.h>
52 #include <sys/dsl_pool.h>
53 #include <sys/dbuf.h>
54 #include <sys/zil.h>
55 #include <sys/zil_impl.h>
56 #include <sys/stat.h>
57 #include <sys/resource.h>
58 #include <sys/dmu_traverse.h>
59 #include <sys/zio_checksum.h>
60 #include <sys/zio_compress.h>
61 #include <zfs_fletcher.h>
62 #include <sys/zfs_fuid.h>
63 #include <sys/arc.h>
64 #include <sys/arc_impl.h>
65 #include <sys/ddt.h>
66 #include <sys/zfeature.h>
67 #include <sys/abd.h>
68 #include <sys/blkptr.h>
69 #include <sys/dsl_scan.h>
70 #include <sys/dsl_crypt.h>
71 #include <zfs_comutil.h>
72 #include <libcmdutils.h>
73 #undef verify
74 #include <libzfs.h>
75 
76 #include <libnvpair.h>
77 #include <libzutil.h>
78 
79 #include "zdb.h"
80 
81 #define	ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ?	\
82 	zio_compress_table[(idx)].ci_name : "UNKNOWN")
83 #define	ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ?	\
84 	zio_checksum_table[(idx)].ci_name : "UNKNOWN")
85 #define	ZDB_OT_NAME(idx) ((idx) < DMU_OT_NUMTYPES ?	\
86 	dmu_ot[(idx)].ot_name : DMU_OT_IS_VALID(idx) ?	\
87 	dmu_ot_byteswap[DMU_OT_BYTESWAP(idx)].ob_name : "UNKNOWN")
88 #define	ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) :		\
89 	(idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA ?	\
90 	DMU_OT_ZAP_OTHER : \
91 	(idx) == DMU_OTN_UINT64_DATA || (idx) == DMU_OTN_UINT64_METADATA ? \
92 	DMU_OT_UINT64_OTHER : DMU_OT_NUMTYPES)
93 
94 extern int reference_tracking_enable;
95 extern boolean_t zfs_recover;
96 extern uint64_t zfs_arc_max, zfs_arc_meta_limit;
97 extern int zfs_vdev_async_read_max_active;
98 extern int aok;
99 extern boolean_t spa_load_verify_dryrun;
100 extern int zfs_btree_verify_intensity;
101 
102 static const char cmdname[] = "zdb";
103 uint8_t dump_opt[256];
104 
105 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
106 
107 uint64_t *zopt_object = NULL;
108 static unsigned zopt_objects = 0;
109 uint64_t max_inflight = 1000;
110 static int leaked_objects = 0;
111 
112 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *);
113 static void mos_obj_refd(uint64_t);
114 
115 /*
116  * These libumem hooks provide a reasonable set of defaults for the allocator's
117  * debugging facilities.
118  */
119 const char *
_umem_debug_init()120 _umem_debug_init()
121 {
122 	return ("default,verbose"); /* $UMEM_DEBUG setting */
123 }
124 
125 const char *
_umem_logging_init(void)126 _umem_logging_init(void)
127 {
128 	return ("fail,contents"); /* $UMEM_LOGGING setting */
129 }
130 
131 static void
usage(void)132 usage(void)
133 {
134 	(void) fprintf(stderr,
135 	    "Usage:\t%s [-AbcdDFGhikLMPsvX] [-e [-V] [-p <path> ...]] "
136 	    "[-I <inflight I/Os>]\n"
137 	    "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
138 	    "\t\t[<poolname> [<object> ...]]\n"
139 	    "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>] <dataset> "
140 	    "[<object> ...]\n"
141 	    "\t%s -C [-A] [-U <cache>]\n"
142 	    "\t%s -l [-Aqu] <device>\n"
143 	    "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
144 	    "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
145 	    "\t%s -O <dataset> <path>\n"
146 	    "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
147 	    "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
148 	    "\t%s -E [-A] word0:word1:...:word15\n"
149 	    "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
150 	    "<poolname>\n\n",
151 	    cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
152 	    cmdname, cmdname);
153 
154 	(void) fprintf(stderr, "    Dataset name must include at least one "
155 	    "separator character '/' or '@'\n");
156 	(void) fprintf(stderr, "    If dataset name is specified, only that "
157 	    "dataset is dumped\n");
158 	(void) fprintf(stderr, "    If object numbers are specified, only "
159 	    "those objects are dumped\n\n");
160 	(void) fprintf(stderr, "    Options to control amount of output:\n");
161 	(void) fprintf(stderr, "        -b block statistics\n");
162 	(void) fprintf(stderr, "        -c checksum all metadata (twice for "
163 	    "all data) blocks\n");
164 	(void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
165 	(void) fprintf(stderr, "        -d dataset(s)\n");
166 	(void) fprintf(stderr, "        -D dedup statistics\n");
167 	(void) fprintf(stderr, "        -E decode and display block from an "
168 	    "embedded block pointer\n");
169 	(void) fprintf(stderr, "        -h pool history\n");
170 	(void) fprintf(stderr, "        -i intent logs\n");
171 	(void) fprintf(stderr, "        -l read label contents\n");
172 	(void) fprintf(stderr, "        -k examine the checkpointed state "
173 	    "of the pool\n");
174 	(void) fprintf(stderr, "        -L disable leak tracking (do not "
175 	    "load spacemaps)\n");
176 	(void) fprintf(stderr, "        -m metaslabs\n");
177 	(void) fprintf(stderr, "        -M metaslab groups\n");
178 	(void) fprintf(stderr, "        -O perform object lookups by path\n");
179 	(void) fprintf(stderr, "        -R read and display block from a "
180 	    "device\n");
181 	(void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
182 	(void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
183 	(void) fprintf(stderr, "        -v verbose (applies to all "
184 	    "others)\n\n");
185 	(void) fprintf(stderr, "    Below options are intended for use "
186 	    "with other options:\n");
187 	(void) fprintf(stderr, "        -A ignore assertions (-A), enable "
188 	    "panic recovery (-AA) or both (-AAA)\n");
189 	(void) fprintf(stderr, "        -e pool is exported/destroyed/"
190 	    "has altroot/not in a cachefile\n");
191 	(void) fprintf(stderr, "        -F attempt automatic rewind within "
192 	    "safe range of transaction groups\n");
193 	(void) fprintf(stderr, "        -G dump zfs_dbgmsg buffer before "
194 	    "exiting\n");
195 	(void) fprintf(stderr, "        -I <number of inflight I/Os> -- "
196 	    "specify the maximum number of "
197 	    "checksumming I/Os [default is 200]\n");
198 	(void) fprintf(stderr, "        -o <variable>=<value> set global "
199 	    "variable to an unsigned 32-bit integer value\n");
200 	(void) fprintf(stderr, "        -p <path> -- use one or more with "
201 	    "-e to specify path to vdev dir\n");
202 	(void) fprintf(stderr, "        -P print numbers in parseable form\n");
203 	(void) fprintf(stderr, "        -q don't print label contents\n");
204 	(void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
205 	    "searching for uberblocks\n");
206 	(void) fprintf(stderr, "        -u uberblock\n");
207 	(void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
208 	    "cachefile\n");
209 	(void) fprintf(stderr, "        -V do verbatim import\n");
210 	(void) fprintf(stderr, "        -x <dumpdir> -- "
211 	    "dump all read blocks into specified directory\n");
212 	(void) fprintf(stderr, "        -X attempt extreme rewind (does not "
213 	    "work with dataset)\n\n");
214 	(void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
215 	    "to make only that option verbose\n");
216 	(void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
217 	exit(1);
218 }
219 
220 static void
dump_debug_buffer()221 dump_debug_buffer()
222 {
223 	if (dump_opt['G']) {
224 		(void) printf("\n");
225 		zfs_dbgmsg_print("zdb");
226 	}
227 }
228 
229 /*
230  * Called for usage errors that are discovered after a call to spa_open(),
231  * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
232  */
233 
234 static void
fatal(const char * fmt,...)235 fatal(const char *fmt, ...)
236 {
237 	va_list ap;
238 
239 	va_start(ap, fmt);
240 	(void) fprintf(stderr, "%s: ", cmdname);
241 	(void) vfprintf(stderr, fmt, ap);
242 	va_end(ap);
243 	(void) fprintf(stderr, "\n");
244 
245 	dump_debug_buffer();
246 
247 	exit(1);
248 }
249 
250 /* ARGSUSED */
251 static void
dump_packed_nvlist(objset_t * os,uint64_t object,void * data,size_t size)252 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
253 {
254 	nvlist_t *nv;
255 	size_t nvsize = *(uint64_t *)data;
256 	char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
257 
258 	VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
259 
260 	VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
261 
262 	umem_free(packed, nvsize);
263 
264 	dump_nvlist(nv, 8);
265 
266 	nvlist_free(nv);
267 }
268 
269 /* ARGSUSED */
270 static void
dump_history_offsets(objset_t * os,uint64_t object,void * data,size_t size)271 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
272 {
273 	spa_history_phys_t *shp = data;
274 
275 	if (shp == NULL)
276 		return;
277 
278 	(void) printf("\t\tpool_create_len = %llu\n",
279 	    (u_longlong_t)shp->sh_pool_create_len);
280 	(void) printf("\t\tphys_max_off = %llu\n",
281 	    (u_longlong_t)shp->sh_phys_max_off);
282 	(void) printf("\t\tbof = %llu\n",
283 	    (u_longlong_t)shp->sh_bof);
284 	(void) printf("\t\teof = %llu\n",
285 	    (u_longlong_t)shp->sh_eof);
286 	(void) printf("\t\trecords_lost = %llu\n",
287 	    (u_longlong_t)shp->sh_records_lost);
288 }
289 
290 static void
zdb_nicenum(uint64_t num,char * buf,size_t buflen)291 zdb_nicenum(uint64_t num, char *buf, size_t buflen)
292 {
293 	if (dump_opt['P'])
294 		(void) snprintf(buf, buflen, "%llu", (longlong_t)num);
295 	else
296 		nicenum(num, buf, sizeof (buf));
297 }
298 
299 static const char histo_stars[] = "****************************************";
300 static const uint64_t histo_width = sizeof (histo_stars) - 1;
301 
302 static void
dump_histogram(const uint64_t * histo,int size,int offset)303 dump_histogram(const uint64_t *histo, int size, int offset)
304 {
305 	int i;
306 	int minidx = size - 1;
307 	int maxidx = 0;
308 	uint64_t max = 0;
309 
310 	for (i = 0; i < size; i++) {
311 		if (histo[i] > max)
312 			max = histo[i];
313 		if (histo[i] > 0 && i > maxidx)
314 			maxidx = i;
315 		if (histo[i] > 0 && i < minidx)
316 			minidx = i;
317 	}
318 
319 	if (max < histo_width)
320 		max = histo_width;
321 
322 	for (i = minidx; i <= maxidx; i++) {
323 		(void) printf("\t\t\t%3u: %6llu %s\n",
324 		    i + offset, (u_longlong_t)histo[i],
325 		    &histo_stars[(max - histo[i]) * histo_width / max]);
326 	}
327 }
328 
329 static void
dump_zap_stats(objset_t * os,uint64_t object)330 dump_zap_stats(objset_t *os, uint64_t object)
331 {
332 	int error;
333 	zap_stats_t zs;
334 
335 	error = zap_get_stats(os, object, &zs);
336 	if (error)
337 		return;
338 
339 	if (zs.zs_ptrtbl_len == 0) {
340 		ASSERT(zs.zs_num_blocks == 1);
341 		(void) printf("\tmicrozap: %llu bytes, %llu entries\n",
342 		    (u_longlong_t)zs.zs_blocksize,
343 		    (u_longlong_t)zs.zs_num_entries);
344 		return;
345 	}
346 
347 	(void) printf("\tFat ZAP stats:\n");
348 
349 	(void) printf("\t\tPointer table:\n");
350 	(void) printf("\t\t\t%llu elements\n",
351 	    (u_longlong_t)zs.zs_ptrtbl_len);
352 	(void) printf("\t\t\tzt_blk: %llu\n",
353 	    (u_longlong_t)zs.zs_ptrtbl_zt_blk);
354 	(void) printf("\t\t\tzt_numblks: %llu\n",
355 	    (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
356 	(void) printf("\t\t\tzt_shift: %llu\n",
357 	    (u_longlong_t)zs.zs_ptrtbl_zt_shift);
358 	(void) printf("\t\t\tzt_blks_copied: %llu\n",
359 	    (u_longlong_t)zs.zs_ptrtbl_blks_copied);
360 	(void) printf("\t\t\tzt_nextblk: %llu\n",
361 	    (u_longlong_t)zs.zs_ptrtbl_nextblk);
362 
363 	(void) printf("\t\tZAP entries: %llu\n",
364 	    (u_longlong_t)zs.zs_num_entries);
365 	(void) printf("\t\tLeaf blocks: %llu\n",
366 	    (u_longlong_t)zs.zs_num_leafs);
367 	(void) printf("\t\tTotal blocks: %llu\n",
368 	    (u_longlong_t)zs.zs_num_blocks);
369 	(void) printf("\t\tzap_block_type: 0x%llx\n",
370 	    (u_longlong_t)zs.zs_block_type);
371 	(void) printf("\t\tzap_magic: 0x%llx\n",
372 	    (u_longlong_t)zs.zs_magic);
373 	(void) printf("\t\tzap_salt: 0x%llx\n",
374 	    (u_longlong_t)zs.zs_salt);
375 
376 	(void) printf("\t\tLeafs with 2^n pointers:\n");
377 	dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
378 
379 	(void) printf("\t\tBlocks with n*5 entries:\n");
380 	dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
381 
382 	(void) printf("\t\tBlocks n/10 full:\n");
383 	dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
384 
385 	(void) printf("\t\tEntries with n chunks:\n");
386 	dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
387 
388 	(void) printf("\t\tBuckets with n entries:\n");
389 	dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
390 }
391 
392 /*ARGSUSED*/
393 static void
dump_none(objset_t * os,uint64_t object,void * data,size_t size)394 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
395 {
396 }
397 
398 /*ARGSUSED*/
399 static void
dump_unknown(objset_t * os,uint64_t object,void * data,size_t size)400 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
401 {
402 	(void) printf("\tUNKNOWN OBJECT TYPE\n");
403 }
404 
405 /*ARGSUSED*/
406 static void
dump_uint8(objset_t * os,uint64_t object,void * data,size_t size)407 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
408 {
409 }
410 
411 /*ARGSUSED*/
412 static void
dump_uint64(objset_t * os,uint64_t object,void * data,size_t size)413 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
414 {
415 }
416 
417 /*ARGSUSED*/
418 static void
dump_zap(objset_t * os,uint64_t object,void * data,size_t size)419 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
420 {
421 	zap_cursor_t zc;
422 	zap_attribute_t attr;
423 	void *prop;
424 	unsigned i;
425 
426 	dump_zap_stats(os, object);
427 	(void) printf("\n");
428 
429 	for (zap_cursor_init(&zc, os, object);
430 	    zap_cursor_retrieve(&zc, &attr) == 0;
431 	    zap_cursor_advance(&zc)) {
432 		(void) printf("\t\t%s = ", attr.za_name);
433 		if (attr.za_num_integers == 0) {
434 			(void) printf("\n");
435 			continue;
436 		}
437 		prop = umem_zalloc(attr.za_num_integers *
438 		    attr.za_integer_length, UMEM_NOFAIL);
439 		(void) zap_lookup(os, object, attr.za_name,
440 		    attr.za_integer_length, attr.za_num_integers, prop);
441 		if (attr.za_integer_length == 1) {
442 			if (strcmp(attr.za_name,
443 			    DSL_CRYPTO_KEY_MASTER_KEY) == 0 ||
444 			    strcmp(attr.za_name,
445 			    DSL_CRYPTO_KEY_HMAC_KEY) == 0 ||
446 			    strcmp(attr.za_name, DSL_CRYPTO_KEY_IV) == 0 ||
447 			    strcmp(attr.za_name, DSL_CRYPTO_KEY_MAC) == 0 ||
448 			    strcmp(attr.za_name, DMU_POOL_CHECKSUM_SALT) == 0) {
449 				uint8_t *u8 = prop;
450 
451 				for (i = 0; i < attr.za_num_integers; i++) {
452 					(void) printf("%02x", u8[i]);
453 				}
454 			} else {
455 				(void) printf("%s", (char *)prop);
456 			}
457 		} else {
458 			for (i = 0; i < attr.za_num_integers; i++) {
459 				switch (attr.za_integer_length) {
460 				case 2:
461 					(void) printf("%u ",
462 					    ((uint16_t *)prop)[i]);
463 					break;
464 				case 4:
465 					(void) printf("%u ",
466 					    ((uint32_t *)prop)[i]);
467 					break;
468 				case 8:
469 					(void) printf("%lld ",
470 					    (u_longlong_t)((int64_t *)prop)[i]);
471 					break;
472 				}
473 			}
474 		}
475 		(void) printf("\n");
476 		umem_free(prop, attr.za_num_integers * attr.za_integer_length);
477 	}
478 	zap_cursor_fini(&zc);
479 }
480 
481 static void
dump_bpobj(objset_t * os,uint64_t object,void * data,size_t size)482 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
483 {
484 	bpobj_phys_t *bpop = data;
485 	char bytes[32], comp[32], uncomp[32];
486 
487 	/* make sure the output won't get truncated */
488 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
489 	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
490 	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
491 
492 	if (bpop == NULL)
493 		return;
494 
495 	zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
496 	zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
497 	zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
498 
499 	(void) printf("\t\tnum_blkptrs = %llu\n",
500 	    (u_longlong_t)bpop->bpo_num_blkptrs);
501 	(void) printf("\t\tbytes = %s\n", bytes);
502 	if (size >= BPOBJ_SIZE_V1) {
503 		(void) printf("\t\tcomp = %s\n", comp);
504 		(void) printf("\t\tuncomp = %s\n", uncomp);
505 	}
506 	if (size >= sizeof (*bpop)) {
507 		(void) printf("\t\tsubobjs = %llu\n",
508 		    (u_longlong_t)bpop->bpo_subobjs);
509 		(void) printf("\t\tnum_subobjs = %llu\n",
510 		    (u_longlong_t)bpop->bpo_num_subobjs);
511 	}
512 
513 	if (dump_opt['d'] < 5)
514 		return;
515 
516 	for (uint64_t i = 0; i < bpop->bpo_num_blkptrs; i++) {
517 		char blkbuf[BP_SPRINTF_LEN];
518 		blkptr_t bp;
519 
520 		int err = dmu_read(os, object,
521 		    i * sizeof (bp), sizeof (bp), &bp, 0);
522 		if (err != 0) {
523 			(void) printf("got error %u from dmu_read\n", err);
524 			break;
525 		}
526 		snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp);
527 		(void) printf("\t%s\n", blkbuf);
528 	}
529 }
530 
531 /* ARGSUSED */
532 static void
dump_bpobj_subobjs(objset_t * os,uint64_t object,void * data,size_t size)533 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
534 {
535 	dmu_object_info_t doi;
536 
537 	VERIFY0(dmu_object_info(os, object, &doi));
538 	uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
539 
540 	int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
541 	if (err != 0) {
542 		(void) printf("got error %u from dmu_read\n", err);
543 		kmem_free(subobjs, doi.doi_max_offset);
544 		return;
545 	}
546 
547 	int64_t last_nonzero = -1;
548 	for (uint64_t i = 0; i < doi.doi_max_offset / 8; i++) {
549 		if (subobjs[i] != 0)
550 			last_nonzero = i;
551 	}
552 
553 	for (int64_t i = 0; i <= last_nonzero; i++) {
554 		(void) printf("\t%llu\n", (longlong_t)subobjs[i]);
555 	}
556 	kmem_free(subobjs, doi.doi_max_offset);
557 }
558 
559 /*ARGSUSED*/
560 static void
dump_ddt_zap(objset_t * os,uint64_t object,void * data,size_t size)561 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
562 {
563 	dump_zap_stats(os, object);
564 	/* contents are printed elsewhere, properly decoded */
565 }
566 
567 /*ARGSUSED*/
568 static void
dump_sa_attrs(objset_t * os,uint64_t object,void * data,size_t size)569 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
570 {
571 	zap_cursor_t zc;
572 	zap_attribute_t attr;
573 
574 	dump_zap_stats(os, object);
575 	(void) printf("\n");
576 
577 	for (zap_cursor_init(&zc, os, object);
578 	    zap_cursor_retrieve(&zc, &attr) == 0;
579 	    zap_cursor_advance(&zc)) {
580 		(void) printf("\t\t%s = ", attr.za_name);
581 		if (attr.za_num_integers == 0) {
582 			(void) printf("\n");
583 			continue;
584 		}
585 		(void) printf(" %llx : [%d:%d:%d]\n",
586 		    (u_longlong_t)attr.za_first_integer,
587 		    (int)ATTR_LENGTH(attr.za_first_integer),
588 		    (int)ATTR_BSWAP(attr.za_first_integer),
589 		    (int)ATTR_NUM(attr.za_first_integer));
590 	}
591 	zap_cursor_fini(&zc);
592 }
593 
594 /*ARGSUSED*/
595 static void
dump_sa_layouts(objset_t * os,uint64_t object,void * data,size_t size)596 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
597 {
598 	zap_cursor_t zc;
599 	zap_attribute_t attr;
600 	uint16_t *layout_attrs;
601 	unsigned i;
602 
603 	dump_zap_stats(os, object);
604 	(void) printf("\n");
605 
606 	for (zap_cursor_init(&zc, os, object);
607 	    zap_cursor_retrieve(&zc, &attr) == 0;
608 	    zap_cursor_advance(&zc)) {
609 		(void) printf("\t\t%s = [", attr.za_name);
610 		if (attr.za_num_integers == 0) {
611 			(void) printf("\n");
612 			continue;
613 		}
614 
615 		VERIFY(attr.za_integer_length == 2);
616 		layout_attrs = umem_zalloc(attr.za_num_integers *
617 		    attr.za_integer_length, UMEM_NOFAIL);
618 
619 		VERIFY(zap_lookup(os, object, attr.za_name,
620 		    attr.za_integer_length,
621 		    attr.za_num_integers, layout_attrs) == 0);
622 
623 		for (i = 0; i != attr.za_num_integers; i++)
624 			(void) printf(" %d ", (int)layout_attrs[i]);
625 		(void) printf("]\n");
626 		umem_free(layout_attrs,
627 		    attr.za_num_integers * attr.za_integer_length);
628 	}
629 	zap_cursor_fini(&zc);
630 }
631 
632 /*ARGSUSED*/
633 static void
dump_zpldir(objset_t * os,uint64_t object,void * data,size_t size)634 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
635 {
636 	zap_cursor_t zc;
637 	zap_attribute_t attr;
638 	const char *typenames[] = {
639 		/* 0 */ "not specified",
640 		/* 1 */ "FIFO",
641 		/* 2 */ "Character Device",
642 		/* 3 */ "3 (invalid)",
643 		/* 4 */ "Directory",
644 		/* 5 */ "5 (invalid)",
645 		/* 6 */ "Block Device",
646 		/* 7 */ "7 (invalid)",
647 		/* 8 */ "Regular File",
648 		/* 9 */ "9 (invalid)",
649 		/* 10 */ "Symbolic Link",
650 		/* 11 */ "11 (invalid)",
651 		/* 12 */ "Socket",
652 		/* 13 */ "Door",
653 		/* 14 */ "Event Port",
654 		/* 15 */ "15 (invalid)",
655 	};
656 
657 	dump_zap_stats(os, object);
658 	(void) printf("\n");
659 
660 	for (zap_cursor_init(&zc, os, object);
661 	    zap_cursor_retrieve(&zc, &attr) == 0;
662 	    zap_cursor_advance(&zc)) {
663 		(void) printf("\t\t%s = %lld (type: %s)\n",
664 		    attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
665 		    typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
666 	}
667 	zap_cursor_fini(&zc);
668 }
669 
670 static int
get_dtl_refcount(vdev_t * vd)671 get_dtl_refcount(vdev_t *vd)
672 {
673 	int refcount = 0;
674 
675 	if (vd->vdev_ops->vdev_op_leaf) {
676 		space_map_t *sm = vd->vdev_dtl_sm;
677 
678 		if (sm != NULL &&
679 		    sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
680 			return (1);
681 		return (0);
682 	}
683 
684 	for (unsigned c = 0; c < vd->vdev_children; c++)
685 		refcount += get_dtl_refcount(vd->vdev_child[c]);
686 	return (refcount);
687 }
688 
689 static int
get_metaslab_refcount(vdev_t * vd)690 get_metaslab_refcount(vdev_t *vd)
691 {
692 	int refcount = 0;
693 
694 	if (vd->vdev_top == vd) {
695 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
696 			space_map_t *sm = vd->vdev_ms[m]->ms_sm;
697 
698 			if (sm != NULL &&
699 			    sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
700 				refcount++;
701 		}
702 	}
703 	for (unsigned c = 0; c < vd->vdev_children; c++)
704 		refcount += get_metaslab_refcount(vd->vdev_child[c]);
705 
706 	return (refcount);
707 }
708 
709 static int
get_obsolete_refcount(vdev_t * vd)710 get_obsolete_refcount(vdev_t *vd)
711 {
712 	int refcount = 0;
713 
714 	uint64_t obsolete_sm_obj = vdev_obsolete_sm_object(vd);
715 	if (vd->vdev_top == vd && obsolete_sm_obj != 0) {
716 		dmu_object_info_t doi;
717 		VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
718 		    obsolete_sm_obj, &doi));
719 		if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
720 			refcount++;
721 		}
722 	} else {
723 		ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
724 		ASSERT3U(obsolete_sm_obj, ==, 0);
725 	}
726 	for (unsigned c = 0; c < vd->vdev_children; c++) {
727 		refcount += get_obsolete_refcount(vd->vdev_child[c]);
728 	}
729 
730 	return (refcount);
731 }
732 
733 static int
get_prev_obsolete_spacemap_refcount(spa_t * spa)734 get_prev_obsolete_spacemap_refcount(spa_t *spa)
735 {
736 	uint64_t prev_obj =
737 	    spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
738 	if (prev_obj != 0) {
739 		dmu_object_info_t doi;
740 		VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
741 		if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
742 			return (1);
743 		}
744 	}
745 	return (0);
746 }
747 
748 static int
get_checkpoint_refcount(vdev_t * vd)749 get_checkpoint_refcount(vdev_t *vd)
750 {
751 	int refcount = 0;
752 
753 	if (vd->vdev_top == vd && vd->vdev_top_zap != 0 &&
754 	    zap_contains(spa_meta_objset(vd->vdev_spa),
755 	    vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) == 0)
756 		refcount++;
757 
758 	for (uint64_t c = 0; c < vd->vdev_children; c++)
759 		refcount += get_checkpoint_refcount(vd->vdev_child[c]);
760 
761 	return (refcount);
762 }
763 
764 static int
get_log_spacemap_refcount(spa_t * spa)765 get_log_spacemap_refcount(spa_t *spa)
766 {
767 	return (avl_numnodes(&spa->spa_sm_logs_by_txg));
768 }
769 
770 static int
verify_spacemap_refcounts(spa_t * spa)771 verify_spacemap_refcounts(spa_t *spa)
772 {
773 	uint64_t expected_refcount = 0;
774 	uint64_t actual_refcount;
775 
776 	(void) feature_get_refcount(spa,
777 	    &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
778 	    &expected_refcount);
779 	actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
780 	actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
781 	actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
782 	actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
783 	actual_refcount += get_checkpoint_refcount(spa->spa_root_vdev);
784 	actual_refcount += get_log_spacemap_refcount(spa);
785 
786 	if (expected_refcount != actual_refcount) {
787 		(void) printf("space map refcount mismatch: expected %lld != "
788 		    "actual %lld\n",
789 		    (longlong_t)expected_refcount,
790 		    (longlong_t)actual_refcount);
791 		return (2);
792 	}
793 	return (0);
794 }
795 
796 static void
dump_spacemap(objset_t * os,space_map_t * sm)797 dump_spacemap(objset_t *os, space_map_t *sm)
798 {
799 	char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
800 	    "INVALID", "INVALID", "INVALID", "INVALID" };
801 
802 	if (sm == NULL)
803 		return;
804 
805 	(void) printf("space map object %llu:\n",
806 	    (longlong_t)sm->sm_object);
807 	(void) printf("  smp_length = 0x%llx\n",
808 	    (longlong_t)sm->sm_phys->smp_length);
809 	(void) printf("  smp_alloc = 0x%llx\n",
810 	    (longlong_t)sm->sm_phys->smp_alloc);
811 
812 	if (dump_opt['d'] < 6 && dump_opt['m'] < 4)
813 		return;
814 
815 	/*
816 	 * Print out the freelist entries in both encoded and decoded form.
817 	 */
818 	uint8_t mapshift = sm->sm_shift;
819 	int64_t alloc = 0;
820 	uint64_t word, entry_id = 0;
821 	for (uint64_t offset = 0; offset < space_map_length(sm);
822 	    offset += sizeof (word)) {
823 
824 		VERIFY0(dmu_read(os, space_map_object(sm), offset,
825 		    sizeof (word), &word, DMU_READ_PREFETCH));
826 
827 		if (sm_entry_is_debug(word)) {
828 			(void) printf("\t    [%6llu] %s: txg %llu pass %llu\n",
829 			    (u_longlong_t)entry_id,
830 			    ddata[SM_DEBUG_ACTION_DECODE(word)],
831 			    (u_longlong_t)SM_DEBUG_TXG_DECODE(word),
832 			    (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(word));
833 			entry_id++;
834 			continue;
835 		}
836 
837 		uint8_t words;
838 		char entry_type;
839 		uint64_t entry_off, entry_run, entry_vdev = SM_NO_VDEVID;
840 
841 		if (sm_entry_is_single_word(word)) {
842 			entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
843 			    'A' : 'F';
844 			entry_off = (SM_OFFSET_DECODE(word) << mapshift) +
845 			    sm->sm_start;
846 			entry_run = SM_RUN_DECODE(word) << mapshift;
847 			words = 1;
848 		} else {
849 			/* it is a two-word entry so we read another word */
850 			ASSERT(sm_entry_is_double_word(word));
851 
852 			uint64_t extra_word;
853 			offset += sizeof (extra_word);
854 			VERIFY0(dmu_read(os, space_map_object(sm), offset,
855 			    sizeof (extra_word), &extra_word,
856 			    DMU_READ_PREFETCH));
857 
858 			ASSERT3U(offset, <=, space_map_length(sm));
859 
860 			entry_run = SM2_RUN_DECODE(word) << mapshift;
861 			entry_vdev = SM2_VDEV_DECODE(word);
862 			entry_type = (SM2_TYPE_DECODE(extra_word) == SM_ALLOC) ?
863 			    'A' : 'F';
864 			entry_off = (SM2_OFFSET_DECODE(extra_word) <<
865 			    mapshift) + sm->sm_start;
866 			words = 2;
867 		}
868 
869 		(void) printf("\t    [%6llu]    %c  range:"
870 		    " %010llx-%010llx  size: %06llx vdev: %06llu words: %u\n",
871 		    (u_longlong_t)entry_id,
872 		    entry_type, (u_longlong_t)entry_off,
873 		    (u_longlong_t)(entry_off + entry_run),
874 		    (u_longlong_t)entry_run,
875 		    (u_longlong_t)entry_vdev, words);
876 
877 		if (entry_type == 'A')
878 			alloc += entry_run;
879 		else
880 			alloc -= entry_run;
881 		entry_id++;
882 	}
883 	if (alloc != space_map_allocated(sm)) {
884 		(void) printf("space_map_object alloc (%lld) INCONSISTENT "
885 		    "with space map summary (%lld)\n",
886 		    (longlong_t)space_map_allocated(sm), (longlong_t)alloc);
887 	}
888 }
889 
890 static void
dump_metaslab_stats(metaslab_t * msp)891 dump_metaslab_stats(metaslab_t *msp)
892 {
893 	char maxbuf[32];
894 	range_tree_t *rt = msp->ms_allocatable;
895 	zfs_btree_t *t = &msp->ms_allocatable_by_size;
896 	int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
897 
898 	/* max sure nicenum has enough space */
899 	CTASSERT(sizeof (maxbuf) >= NN_NUMBUF_SZ);
900 
901 	zdb_nicenum(metaslab_largest_allocatable(msp), maxbuf, sizeof (maxbuf));
902 
903 	(void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
904 	    "segments", zfs_btree_numnodes(t), "maxsize", maxbuf,
905 	    "freepct", free_pct);
906 	(void) printf("\tIn-memory histogram:\n");
907 	dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
908 }
909 
910 static void
dump_metaslab(metaslab_t * msp)911 dump_metaslab(metaslab_t *msp)
912 {
913 	vdev_t *vd = msp->ms_group->mg_vd;
914 	spa_t *spa = vd->vdev_spa;
915 	space_map_t *sm = msp->ms_sm;
916 	char freebuf[32];
917 
918 	zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
919 	    sizeof (freebuf));
920 
921 	(void) printf(
922 	    "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
923 	    (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
924 	    (u_longlong_t)space_map_object(sm), freebuf);
925 
926 	if (dump_opt['m'] > 2 && !dump_opt['L']) {
927 		mutex_enter(&msp->ms_lock);
928 		VERIFY0(metaslab_load(msp));
929 		range_tree_stat_verify(msp->ms_allocatable);
930 		dump_metaslab_stats(msp);
931 		metaslab_unload(msp);
932 		mutex_exit(&msp->ms_lock);
933 	}
934 
935 	if (dump_opt['m'] > 1 && sm != NULL &&
936 	    spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
937 		/*
938 		 * The space map histogram represents free space in chunks
939 		 * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
940 		 */
941 		(void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
942 		    (u_longlong_t)msp->ms_fragmentation);
943 		dump_histogram(sm->sm_phys->smp_histogram,
944 		    SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
945 	}
946 
947 	ASSERT(msp->ms_size == (1ULL << vd->vdev_ms_shift));
948 	dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
949 
950 	if (spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
951 		(void) printf("\tFlush data:\n\tunflushed txg=%llu\n\n",
952 		    (u_longlong_t)metaslab_unflushed_txg(msp));
953 	}
954 }
955 
956 static void
print_vdev_metaslab_header(vdev_t * vd)957 print_vdev_metaslab_header(vdev_t *vd)
958 {
959 	vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
960 	const char *bias_str = "";
961 
962 	if (alloc_bias == VDEV_BIAS_LOG || vd->vdev_islog) {
963 		bias_str = VDEV_ALLOC_BIAS_LOG;
964 	} else if (alloc_bias == VDEV_BIAS_SPECIAL) {
965 		bias_str = VDEV_ALLOC_BIAS_SPECIAL;
966 	} else if (alloc_bias == VDEV_BIAS_DEDUP) {
967 		bias_str = VDEV_ALLOC_BIAS_DEDUP;
968 	}
969 
970 	uint64_t ms_flush_data_obj = 0;
971 	if (vd->vdev_top_zap != 0) {
972 		int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
973 		    vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
974 		    sizeof (uint64_t), 1, &ms_flush_data_obj);
975 		if (error != ENOENT) {
976 			ASSERT0(error);
977 		}
978 	}
979 
980 	(void) printf("\tvdev %10llu   %s",
981 	    (u_longlong_t)vd->vdev_id, bias_str);
982 
983 	if (ms_flush_data_obj != 0) {
984 		(void) printf("   ms_unflushed_phys object %llu",
985 		    (u_longlong_t)ms_flush_data_obj);
986 	}
987 
988 	(void) printf("\n\t%-10s%5llu   %-19s   %-15s   %-12s\n",
989 	    "metaslabs", (u_longlong_t)vd->vdev_ms_count,
990 	    "offset", "spacemap", "free");
991 	(void) printf("\t%15s   %19s   %15s   %12s\n",
992 	    "---------------", "-------------------",
993 	    "---------------", "------------");
994 }
995 
996 static void
dump_metaslab_groups(spa_t * spa)997 dump_metaslab_groups(spa_t *spa)
998 {
999 	vdev_t *rvd = spa->spa_root_vdev;
1000 	metaslab_class_t *mc = spa_normal_class(spa);
1001 	uint64_t fragmentation;
1002 
1003 	metaslab_class_histogram_verify(mc);
1004 
1005 	for (unsigned c = 0; c < rvd->vdev_children; c++) {
1006 		vdev_t *tvd = rvd->vdev_child[c];
1007 		metaslab_group_t *mg = tvd->vdev_mg;
1008 
1009 		if (mg == NULL || mg->mg_class != mc)
1010 			continue;
1011 
1012 		metaslab_group_histogram_verify(mg);
1013 		mg->mg_fragmentation = metaslab_group_fragmentation(mg);
1014 
1015 		(void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
1016 		    "fragmentation",
1017 		    (u_longlong_t)tvd->vdev_id,
1018 		    (u_longlong_t)tvd->vdev_ms_count);
1019 		if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
1020 			(void) printf("%3s\n", "-");
1021 		} else {
1022 			(void) printf("%3llu%%\n",
1023 			    (u_longlong_t)mg->mg_fragmentation);
1024 		}
1025 		dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1026 	}
1027 
1028 	(void) printf("\tpool %s\tfragmentation", spa_name(spa));
1029 	fragmentation = metaslab_class_fragmentation(mc);
1030 	if (fragmentation == ZFS_FRAG_INVALID)
1031 		(void) printf("\t%3s\n", "-");
1032 	else
1033 		(void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
1034 	dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1035 }
1036 
1037 static void
print_vdev_indirect(vdev_t * vd)1038 print_vdev_indirect(vdev_t *vd)
1039 {
1040 	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1041 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1042 	vdev_indirect_births_t *vib = vd->vdev_indirect_births;
1043 
1044 	if (vim == NULL) {
1045 		ASSERT3P(vib, ==, NULL);
1046 		return;
1047 	}
1048 
1049 	ASSERT3U(vdev_indirect_mapping_object(vim), ==,
1050 	    vic->vic_mapping_object);
1051 	ASSERT3U(vdev_indirect_births_object(vib), ==,
1052 	    vic->vic_births_object);
1053 
1054 	(void) printf("indirect births obj %llu:\n",
1055 	    (longlong_t)vic->vic_births_object);
1056 	(void) printf("    vib_count = %llu\n",
1057 	    (longlong_t)vdev_indirect_births_count(vib));
1058 	for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
1059 		vdev_indirect_birth_entry_phys_t *cur_vibe =
1060 		    &vib->vib_entries[i];
1061 		(void) printf("\toffset %llx -> txg %llu\n",
1062 		    (longlong_t)cur_vibe->vibe_offset,
1063 		    (longlong_t)cur_vibe->vibe_phys_birth_txg);
1064 	}
1065 	(void) printf("\n");
1066 
1067 	(void) printf("indirect mapping obj %llu:\n",
1068 	    (longlong_t)vic->vic_mapping_object);
1069 	(void) printf("    vim_max_offset = 0x%llx\n",
1070 	    (longlong_t)vdev_indirect_mapping_max_offset(vim));
1071 	(void) printf("    vim_bytes_mapped = 0x%llx\n",
1072 	    (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
1073 	(void) printf("    vim_count = %llu\n",
1074 	    (longlong_t)vdev_indirect_mapping_num_entries(vim));
1075 
1076 	if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
1077 		return;
1078 
1079 	uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
1080 
1081 	for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
1082 		vdev_indirect_mapping_entry_phys_t *vimep =
1083 		    &vim->vim_entries[i];
1084 		(void) printf("\t<%llx:%llx:%llx> -> "
1085 		    "<%llx:%llx:%llx> (%x obsolete)\n",
1086 		    (longlong_t)vd->vdev_id,
1087 		    (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
1088 		    (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1089 		    (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
1090 		    (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
1091 		    (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1092 		    counts[i]);
1093 	}
1094 	(void) printf("\n");
1095 
1096 	uint64_t obsolete_sm_object = vdev_obsolete_sm_object(vd);
1097 	if (obsolete_sm_object != 0) {
1098 		objset_t *mos = vd->vdev_spa->spa_meta_objset;
1099 		(void) printf("obsolete space map object %llu:\n",
1100 		    (u_longlong_t)obsolete_sm_object);
1101 		ASSERT(vd->vdev_obsolete_sm != NULL);
1102 		ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
1103 		    obsolete_sm_object);
1104 		dump_spacemap(mos, vd->vdev_obsolete_sm);
1105 		(void) printf("\n");
1106 	}
1107 }
1108 
1109 static void
dump_metaslabs(spa_t * spa)1110 dump_metaslabs(spa_t *spa)
1111 {
1112 	vdev_t *vd, *rvd = spa->spa_root_vdev;
1113 	uint64_t m, c = 0, children = rvd->vdev_children;
1114 
1115 	(void) printf("\nMetaslabs:\n");
1116 
1117 	if (!dump_opt['d'] && zopt_objects > 0) {
1118 		c = zopt_object[0];
1119 
1120 		if (c >= children)
1121 			(void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1122 
1123 		if (zopt_objects > 1) {
1124 			vd = rvd->vdev_child[c];
1125 			print_vdev_metaslab_header(vd);
1126 
1127 			for (m = 1; m < zopt_objects; m++) {
1128 				if (zopt_object[m] < vd->vdev_ms_count)
1129 					dump_metaslab(
1130 					    vd->vdev_ms[zopt_object[m]]);
1131 				else
1132 					(void) fprintf(stderr, "bad metaslab "
1133 					    "number %llu\n",
1134 					    (u_longlong_t)zopt_object[m]);
1135 			}
1136 			(void) printf("\n");
1137 			return;
1138 		}
1139 		children = c + 1;
1140 	}
1141 	for (; c < children; c++) {
1142 		vd = rvd->vdev_child[c];
1143 		print_vdev_metaslab_header(vd);
1144 
1145 		print_vdev_indirect(vd);
1146 
1147 		for (m = 0; m < vd->vdev_ms_count; m++)
1148 			dump_metaslab(vd->vdev_ms[m]);
1149 		(void) printf("\n");
1150 	}
1151 }
1152 
1153 static void
dump_log_spacemaps(spa_t * spa)1154 dump_log_spacemaps(spa_t *spa)
1155 {
1156 	if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
1157 		return;
1158 
1159 	(void) printf("\nLog Space Maps in Pool:\n");
1160 	for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
1161 	    sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
1162 		space_map_t *sm = NULL;
1163 		VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
1164 		    sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
1165 
1166 		(void) printf("Log Spacemap object %llu txg %llu\n",
1167 		    (u_longlong_t)sls->sls_sm_obj, (u_longlong_t)sls->sls_txg);
1168 		dump_spacemap(spa->spa_meta_objset, sm);
1169 		space_map_close(sm);
1170 	}
1171 	(void) printf("\n");
1172 }
1173 
1174 static void
dump_dde(const ddt_t * ddt,const ddt_entry_t * dde,uint64_t index)1175 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
1176 {
1177 	const ddt_phys_t *ddp = dde->dde_phys;
1178 	const ddt_key_t *ddk = &dde->dde_key;
1179 	const char *types[4] = { "ditto", "single", "double", "triple" };
1180 	char blkbuf[BP_SPRINTF_LEN];
1181 	blkptr_t blk;
1182 
1183 	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1184 		if (ddp->ddp_phys_birth == 0)
1185 			continue;
1186 		ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
1187 		snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1188 		(void) printf("index %llx refcnt %llu %s %s\n",
1189 		    (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
1190 		    types[p], blkbuf);
1191 	}
1192 }
1193 
1194 static void
dump_dedup_ratio(const ddt_stat_t * dds)1195 dump_dedup_ratio(const ddt_stat_t *dds)
1196 {
1197 	double rL, rP, rD, D, dedup, compress, copies;
1198 
1199 	if (dds->dds_blocks == 0)
1200 		return;
1201 
1202 	rL = (double)dds->dds_ref_lsize;
1203 	rP = (double)dds->dds_ref_psize;
1204 	rD = (double)dds->dds_ref_dsize;
1205 	D = (double)dds->dds_dsize;
1206 
1207 	dedup = rD / D;
1208 	compress = rL / rP;
1209 	copies = rD / rP;
1210 
1211 	(void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
1212 	    "dedup * compress / copies = %.2f\n\n",
1213 	    dedup, compress, copies, dedup * compress / copies);
1214 }
1215 
1216 static void
dump_ddt(ddt_t * ddt,enum ddt_type type,enum ddt_class class)1217 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
1218 {
1219 	char name[DDT_NAMELEN];
1220 	ddt_entry_t dde;
1221 	uint64_t walk = 0;
1222 	dmu_object_info_t doi;
1223 	uint64_t count, dspace, mspace;
1224 	int error;
1225 
1226 	error = ddt_object_info(ddt, type, class, &doi);
1227 
1228 	if (error == ENOENT)
1229 		return;
1230 	ASSERT(error == 0);
1231 
1232 	if ((count = ddt_object_count(ddt, type, class)) == 0)
1233 		return;
1234 
1235 	dspace = doi.doi_physical_blocks_512 << 9;
1236 	mspace = doi.doi_fill_count * doi.doi_data_block_size;
1237 
1238 	ddt_object_name(ddt, type, class, name);
1239 
1240 	(void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
1241 	    name,
1242 	    (u_longlong_t)count,
1243 	    (u_longlong_t)(dspace / count),
1244 	    (u_longlong_t)(mspace / count));
1245 
1246 	if (dump_opt['D'] < 3)
1247 		return;
1248 
1249 	zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
1250 
1251 	if (dump_opt['D'] < 4)
1252 		return;
1253 
1254 	if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
1255 		return;
1256 
1257 	(void) printf("%s contents:\n\n", name);
1258 
1259 	while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
1260 		dump_dde(ddt, &dde, walk);
1261 
1262 	ASSERT3U(error, ==, ENOENT);
1263 
1264 	(void) printf("\n");
1265 }
1266 
1267 static void
dump_all_ddts(spa_t * spa)1268 dump_all_ddts(spa_t *spa)
1269 {
1270 	ddt_histogram_t ddh_total;
1271 	ddt_stat_t dds_total;
1272 
1273 	bzero(&ddh_total, sizeof (ddh_total));
1274 	bzero(&dds_total, sizeof (dds_total));
1275 
1276 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1277 		ddt_t *ddt = spa->spa_ddt[c];
1278 		for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
1279 			for (enum ddt_class class = 0; class < DDT_CLASSES;
1280 			    class++) {
1281 				dump_ddt(ddt, type, class);
1282 			}
1283 		}
1284 	}
1285 
1286 	ddt_get_dedup_stats(spa, &dds_total);
1287 
1288 	if (dds_total.dds_blocks == 0) {
1289 		(void) printf("All DDTs are empty\n");
1290 		return;
1291 	}
1292 
1293 	(void) printf("\n");
1294 
1295 	if (dump_opt['D'] > 1) {
1296 		(void) printf("DDT histogram (aggregated over all DDTs):\n");
1297 		ddt_get_dedup_histogram(spa, &ddh_total);
1298 		zpool_dump_ddt(&dds_total, &ddh_total);
1299 	}
1300 
1301 	dump_dedup_ratio(&dds_total);
1302 }
1303 
1304 static void
dump_dtl_seg(void * arg,uint64_t start,uint64_t size)1305 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
1306 {
1307 	char *prefix = arg;
1308 
1309 	(void) printf("%s [%llu,%llu) length %llu\n",
1310 	    prefix,
1311 	    (u_longlong_t)start,
1312 	    (u_longlong_t)(start + size),
1313 	    (u_longlong_t)(size));
1314 }
1315 
1316 static void
dump_dtl(vdev_t * vd,int indent)1317 dump_dtl(vdev_t *vd, int indent)
1318 {
1319 	spa_t *spa = vd->vdev_spa;
1320 	boolean_t required;
1321 	const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
1322 		"outage" };
1323 	char prefix[256];
1324 
1325 	spa_vdev_state_enter(spa, SCL_NONE);
1326 	required = vdev_dtl_required(vd);
1327 	(void) spa_vdev_state_exit(spa, NULL, 0);
1328 
1329 	if (indent == 0)
1330 		(void) printf("\nDirty time logs:\n\n");
1331 
1332 	(void) printf("\t%*s%s [%s]\n", indent, "",
1333 	    vd->vdev_path ? vd->vdev_path :
1334 	    vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
1335 	    required ? "DTL-required" : "DTL-expendable");
1336 
1337 	for (int t = 0; t < DTL_TYPES; t++) {
1338 		range_tree_t *rt = vd->vdev_dtl[t];
1339 		if (range_tree_space(rt) == 0)
1340 			continue;
1341 		(void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
1342 		    indent + 2, "", name[t]);
1343 		range_tree_walk(rt, dump_dtl_seg, prefix);
1344 		if (dump_opt['d'] > 5 && vd->vdev_children == 0)
1345 			dump_spacemap(spa->spa_meta_objset, vd->vdev_dtl_sm);
1346 	}
1347 
1348 	for (unsigned c = 0; c < vd->vdev_children; c++)
1349 		dump_dtl(vd->vdev_child[c], indent + 4);
1350 }
1351 
1352 static void
dump_history(spa_t * spa)1353 dump_history(spa_t *spa)
1354 {
1355 	nvlist_t **events = NULL;
1356 	uint64_t resid, len, off = 0;
1357 	uint_t num = 0;
1358 	int error;
1359 	time_t tsec;
1360 	struct tm t;
1361 	char tbuf[30];
1362 	char internalstr[MAXPATHLEN];
1363 
1364 	char *buf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
1365 	do {
1366 		len = SPA_MAXBLOCKSIZE;
1367 
1368 		if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
1369 			(void) fprintf(stderr, "Unable to read history: "
1370 			    "error %d\n", error);
1371 			umem_free(buf, SPA_MAXBLOCKSIZE);
1372 			return;
1373 		}
1374 
1375 		if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
1376 			break;
1377 
1378 		off -= resid;
1379 	} while (len != 0);
1380 	umem_free(buf, SPA_MAXBLOCKSIZE);
1381 
1382 	(void) printf("\nHistory:\n");
1383 	for (unsigned i = 0; i < num; i++) {
1384 		uint64_t time, txg, ievent;
1385 		char *cmd, *intstr;
1386 		boolean_t printed = B_FALSE;
1387 
1388 		if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
1389 		    &time) != 0)
1390 			goto next;
1391 		if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
1392 		    &cmd) != 0) {
1393 			if (nvlist_lookup_uint64(events[i],
1394 			    ZPOOL_HIST_INT_EVENT, &ievent) != 0)
1395 				goto next;
1396 			verify(nvlist_lookup_uint64(events[i],
1397 			    ZPOOL_HIST_TXG, &txg) == 0);
1398 			verify(nvlist_lookup_string(events[i],
1399 			    ZPOOL_HIST_INT_STR, &intstr) == 0);
1400 			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
1401 				goto next;
1402 
1403 			(void) snprintf(internalstr,
1404 			    sizeof (internalstr),
1405 			    "[internal %s txg:%ju] %s",
1406 			    zfs_history_event_names[ievent], (uintmax_t)txg,
1407 			    intstr);
1408 			cmd = internalstr;
1409 		}
1410 		tsec = time;
1411 		(void) localtime_r(&tsec, &t);
1412 		(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
1413 		(void) printf("%s %s\n", tbuf, cmd);
1414 		printed = B_TRUE;
1415 
1416 next:
1417 		if (dump_opt['h'] > 1) {
1418 			if (!printed)
1419 				(void) printf("unrecognized record:\n");
1420 			dump_nvlist(events[i], 2);
1421 		}
1422 	}
1423 }
1424 
1425 /*ARGSUSED*/
1426 static void
dump_dnode(objset_t * os,uint64_t object,void * data,size_t size)1427 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
1428 {
1429 }
1430 
1431 static uint64_t
blkid2offset(const dnode_phys_t * dnp,const blkptr_t * bp,const zbookmark_phys_t * zb)1432 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
1433     const zbookmark_phys_t *zb)
1434 {
1435 	if (dnp == NULL) {
1436 		ASSERT(zb->zb_level < 0);
1437 		if (zb->zb_object == 0)
1438 			return (zb->zb_blkid);
1439 		return (zb->zb_blkid * BP_GET_LSIZE(bp));
1440 	}
1441 
1442 	ASSERT(zb->zb_level >= 0);
1443 
1444 	return ((zb->zb_blkid <<
1445 	    (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
1446 	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
1447 }
1448 
1449 static void
snprintf_blkptr_compact(char * blkbuf,size_t buflen,const blkptr_t * bp)1450 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp)
1451 {
1452 	const dva_t *dva = bp->blk_dva;
1453 	unsigned int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
1454 
1455 	if (dump_opt['b'] >= 6) {
1456 		snprintf_blkptr(blkbuf, buflen, bp);
1457 		return;
1458 	}
1459 
1460 	if (BP_IS_EMBEDDED(bp)) {
1461 		(void) sprintf(blkbuf,
1462 		    "EMBEDDED et=%u %llxL/%llxP B=%llu",
1463 		    (int)BPE_GET_ETYPE(bp),
1464 		    (u_longlong_t)BPE_GET_LSIZE(bp),
1465 		    (u_longlong_t)BPE_GET_PSIZE(bp),
1466 		    (u_longlong_t)bp->blk_birth);
1467 		return;
1468 	}
1469 
1470 	blkbuf[0] = '\0';
1471 	for (unsigned int i = 0; i < ndvas; i++)
1472 		(void) snprintf(blkbuf + strlen(blkbuf),
1473 		    buflen - strlen(blkbuf), "%llu:%llx:%llx ",
1474 		    (u_longlong_t)DVA_GET_VDEV(&dva[i]),
1475 		    (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
1476 		    (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
1477 
1478 	if (BP_IS_HOLE(bp)) {
1479 		(void) snprintf(blkbuf + strlen(blkbuf),
1480 		    buflen - strlen(blkbuf),
1481 		    "%llxL B=%llu",
1482 		    (u_longlong_t)BP_GET_LSIZE(bp),
1483 		    (u_longlong_t)bp->blk_birth);
1484 	} else {
1485 		(void) snprintf(blkbuf + strlen(blkbuf),
1486 		    buflen - strlen(blkbuf),
1487 		    "%llxL/%llxP F=%llu B=%llu/%llu",
1488 		    (u_longlong_t)BP_GET_LSIZE(bp),
1489 		    (u_longlong_t)BP_GET_PSIZE(bp),
1490 		    (u_longlong_t)BP_GET_FILL(bp),
1491 		    (u_longlong_t)bp->blk_birth,
1492 		    (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
1493 	}
1494 }
1495 
1496 static void
print_indirect(blkptr_t * bp,const zbookmark_phys_t * zb,const dnode_phys_t * dnp)1497 print_indirect(blkptr_t *bp, const zbookmark_phys_t *zb,
1498     const dnode_phys_t *dnp)
1499 {
1500 	char blkbuf[BP_SPRINTF_LEN];
1501 	int l;
1502 
1503 	if (!BP_IS_EMBEDDED(bp)) {
1504 		ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
1505 		ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
1506 	}
1507 
1508 	(void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
1509 
1510 	ASSERT(zb->zb_level >= 0);
1511 
1512 	for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
1513 		if (l == zb->zb_level) {
1514 			(void) printf("L%llx", (u_longlong_t)zb->zb_level);
1515 		} else {
1516 			(void) printf(" ");
1517 		}
1518 	}
1519 
1520 	snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1521 	(void) printf("%s\n", blkbuf);
1522 }
1523 
1524 static int
visit_indirect(spa_t * spa,const dnode_phys_t * dnp,blkptr_t * bp,const zbookmark_phys_t * zb)1525 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
1526     blkptr_t *bp, const zbookmark_phys_t *zb)
1527 {
1528 	int err = 0;
1529 
1530 	if (bp->blk_birth == 0)
1531 		return (0);
1532 
1533 	print_indirect(bp, zb, dnp);
1534 
1535 	if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
1536 		arc_flags_t flags = ARC_FLAG_WAIT;
1537 		int i;
1538 		blkptr_t *cbp;
1539 		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1540 		arc_buf_t *buf;
1541 		uint64_t fill = 0;
1542 
1543 		err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
1544 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
1545 		if (err)
1546 			return (err);
1547 		ASSERT(buf->b_data);
1548 
1549 		/* recursively visit blocks below this */
1550 		cbp = buf->b_data;
1551 		for (i = 0; i < epb; i++, cbp++) {
1552 			zbookmark_phys_t czb;
1553 
1554 			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1555 			    zb->zb_level - 1,
1556 			    zb->zb_blkid * epb + i);
1557 			err = visit_indirect(spa, dnp, cbp, &czb);
1558 			if (err)
1559 				break;
1560 			fill += BP_GET_FILL(cbp);
1561 		}
1562 		if (!err)
1563 			ASSERT3U(fill, ==, BP_GET_FILL(bp));
1564 		arc_buf_destroy(buf, &buf);
1565 	}
1566 
1567 	return (err);
1568 }
1569 
1570 /*ARGSUSED*/
1571 static void
dump_indirect(dnode_t * dn)1572 dump_indirect(dnode_t *dn)
1573 {
1574 	dnode_phys_t *dnp = dn->dn_phys;
1575 	int j;
1576 	zbookmark_phys_t czb;
1577 
1578 	(void) printf("Indirect blocks:\n");
1579 
1580 	SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1581 	    dn->dn_object, dnp->dn_nlevels - 1, 0);
1582 	for (j = 0; j < dnp->dn_nblkptr; j++) {
1583 		czb.zb_blkid = j;
1584 		(void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1585 		    &dnp->dn_blkptr[j], &czb);
1586 	}
1587 
1588 	(void) printf("\n");
1589 }
1590 
1591 /*ARGSUSED*/
1592 static void
dump_dsl_dir(objset_t * os,uint64_t object,void * data,size_t size)1593 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1594 {
1595 	dsl_dir_phys_t *dd = data;
1596 	time_t crtime;
1597 	char nice[32];
1598 
1599 	/* make sure nicenum has enough space */
1600 	CTASSERT(sizeof (nice) >= NN_NUMBUF_SZ);
1601 
1602 	if (dd == NULL)
1603 		return;
1604 
1605 	ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1606 
1607 	crtime = dd->dd_creation_time;
1608 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1609 	(void) printf("\t\thead_dataset_obj = %llu\n",
1610 	    (u_longlong_t)dd->dd_head_dataset_obj);
1611 	(void) printf("\t\tparent_dir_obj = %llu\n",
1612 	    (u_longlong_t)dd->dd_parent_obj);
1613 	(void) printf("\t\torigin_obj = %llu\n",
1614 	    (u_longlong_t)dd->dd_origin_obj);
1615 	(void) printf("\t\tchild_dir_zapobj = %llu\n",
1616 	    (u_longlong_t)dd->dd_child_dir_zapobj);
1617 	zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
1618 	(void) printf("\t\tused_bytes = %s\n", nice);
1619 	zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
1620 	(void) printf("\t\tcompressed_bytes = %s\n", nice);
1621 	zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
1622 	(void) printf("\t\tuncompressed_bytes = %s\n", nice);
1623 	zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
1624 	(void) printf("\t\tquota = %s\n", nice);
1625 	zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
1626 	(void) printf("\t\treserved = %s\n", nice);
1627 	(void) printf("\t\tprops_zapobj = %llu\n",
1628 	    (u_longlong_t)dd->dd_props_zapobj);
1629 	(void) printf("\t\tdeleg_zapobj = %llu\n",
1630 	    (u_longlong_t)dd->dd_deleg_zapobj);
1631 	(void) printf("\t\tflags = %llx\n",
1632 	    (u_longlong_t)dd->dd_flags);
1633 
1634 #define	DO(which) \
1635 	zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
1636 	    sizeof (nice)); \
1637 	(void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1638 	DO(HEAD);
1639 	DO(SNAP);
1640 	DO(CHILD);
1641 	DO(CHILD_RSRV);
1642 	DO(REFRSRV);
1643 #undef DO
1644 	(void) printf("\t\tclones = %llu\n",
1645 	    (u_longlong_t)dd->dd_clones);
1646 }
1647 
1648 /*ARGSUSED*/
1649 static void
dump_dsl_dataset(objset_t * os,uint64_t object,void * data,size_t size)1650 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1651 {
1652 	dsl_dataset_phys_t *ds = data;
1653 	time_t crtime;
1654 	char used[32], compressed[32], uncompressed[32], unique[32];
1655 	char blkbuf[BP_SPRINTF_LEN];
1656 
1657 	/* make sure nicenum has enough space */
1658 	CTASSERT(sizeof (used) >= NN_NUMBUF_SZ);
1659 	CTASSERT(sizeof (compressed) >= NN_NUMBUF_SZ);
1660 	CTASSERT(sizeof (uncompressed) >= NN_NUMBUF_SZ);
1661 	CTASSERT(sizeof (unique) >= NN_NUMBUF_SZ);
1662 
1663 	if (ds == NULL)
1664 		return;
1665 
1666 	ASSERT(size == sizeof (*ds));
1667 	crtime = ds->ds_creation_time;
1668 	zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
1669 	zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
1670 	zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
1671 	    sizeof (uncompressed));
1672 	zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
1673 	snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
1674 
1675 	(void) printf("\t\tdir_obj = %llu\n",
1676 	    (u_longlong_t)ds->ds_dir_obj);
1677 	(void) printf("\t\tprev_snap_obj = %llu\n",
1678 	    (u_longlong_t)ds->ds_prev_snap_obj);
1679 	(void) printf("\t\tprev_snap_txg = %llu\n",
1680 	    (u_longlong_t)ds->ds_prev_snap_txg);
1681 	(void) printf("\t\tnext_snap_obj = %llu\n",
1682 	    (u_longlong_t)ds->ds_next_snap_obj);
1683 	(void) printf("\t\tsnapnames_zapobj = %llu\n",
1684 	    (u_longlong_t)ds->ds_snapnames_zapobj);
1685 	(void) printf("\t\tnum_children = %llu\n",
1686 	    (u_longlong_t)ds->ds_num_children);
1687 	(void) printf("\t\tuserrefs_obj = %llu\n",
1688 	    (u_longlong_t)ds->ds_userrefs_obj);
1689 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1690 	(void) printf("\t\tcreation_txg = %llu\n",
1691 	    (u_longlong_t)ds->ds_creation_txg);
1692 	(void) printf("\t\tdeadlist_obj = %llu\n",
1693 	    (u_longlong_t)ds->ds_deadlist_obj);
1694 	(void) printf("\t\tused_bytes = %s\n", used);
1695 	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
1696 	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1697 	(void) printf("\t\tunique = %s\n", unique);
1698 	(void) printf("\t\tfsid_guid = %llu\n",
1699 	    (u_longlong_t)ds->ds_fsid_guid);
1700 	(void) printf("\t\tguid = %llu\n",
1701 	    (u_longlong_t)ds->ds_guid);
1702 	(void) printf("\t\tflags = %llx\n",
1703 	    (u_longlong_t)ds->ds_flags);
1704 	(void) printf("\t\tnext_clones_obj = %llu\n",
1705 	    (u_longlong_t)ds->ds_next_clones_obj);
1706 	(void) printf("\t\tprops_obj = %llu\n",
1707 	    (u_longlong_t)ds->ds_props_obj);
1708 	(void) printf("\t\tbp = %s\n", blkbuf);
1709 }
1710 
1711 /* ARGSUSED */
1712 static int
dump_bptree_cb(void * arg,const blkptr_t * bp,dmu_tx_t * tx)1713 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1714 {
1715 	char blkbuf[BP_SPRINTF_LEN];
1716 
1717 	if (bp->blk_birth != 0) {
1718 		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
1719 		(void) printf("\t%s\n", blkbuf);
1720 	}
1721 	return (0);
1722 }
1723 
1724 static void
dump_bptree(objset_t * os,uint64_t obj,const char * name)1725 dump_bptree(objset_t *os, uint64_t obj, const char *name)
1726 {
1727 	char bytes[32];
1728 	bptree_phys_t *bt;
1729 	dmu_buf_t *db;
1730 
1731 	/* make sure nicenum has enough space */
1732 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1733 
1734 	if (dump_opt['d'] < 3)
1735 		return;
1736 
1737 	VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
1738 	bt = db->db_data;
1739 	zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
1740 	(void) printf("\n    %s: %llu datasets, %s\n",
1741 	    name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
1742 	dmu_buf_rele(db, FTAG);
1743 
1744 	if (dump_opt['d'] < 5)
1745 		return;
1746 
1747 	(void) printf("\n");
1748 
1749 	(void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
1750 }
1751 
1752 /* ARGSUSED */
1753 static int
dump_bpobj_cb(void * arg,const blkptr_t * bp,dmu_tx_t * tx)1754 dump_bpobj_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1755 {
1756 	char blkbuf[BP_SPRINTF_LEN];
1757 
1758 	ASSERT(bp->blk_birth != 0);
1759 	snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1760 	(void) printf("\t%s\n", blkbuf);
1761 	return (0);
1762 }
1763 
1764 static void
dump_full_bpobj(bpobj_t * bpo,const char * name,int indent)1765 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
1766 {
1767 	char bytes[32];
1768 	char comp[32];
1769 	char uncomp[32];
1770 
1771 	/* make sure nicenum has enough space */
1772 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1773 	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1774 	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1775 
1776 	if (dump_opt['d'] < 3)
1777 		return;
1778 
1779 	zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
1780 	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1781 		zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
1782 		zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
1783 		(void) printf("    %*s: object %llu, %llu local blkptrs, "
1784 		    "%llu subobjs in object %llu, %s (%s/%s comp)\n",
1785 		    indent * 8, name,
1786 		    (u_longlong_t)bpo->bpo_object,
1787 		    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1788 		    (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1789 		    (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
1790 		    bytes, comp, uncomp);
1791 
1792 		for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1793 			uint64_t subobj;
1794 			bpobj_t subbpo;
1795 			int error;
1796 			VERIFY0(dmu_read(bpo->bpo_os,
1797 			    bpo->bpo_phys->bpo_subobjs,
1798 			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1799 			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1800 			if (error != 0) {
1801 				(void) printf("ERROR %u while trying to open "
1802 				    "subobj id %llu\n",
1803 				    error, (u_longlong_t)subobj);
1804 				continue;
1805 			}
1806 			dump_full_bpobj(&subbpo, "subobj", indent + 1);
1807 			bpobj_close(&subbpo);
1808 		}
1809 	} else {
1810 		(void) printf("    %*s: object %llu, %llu blkptrs, %s\n",
1811 		    indent * 8, name,
1812 		    (u_longlong_t)bpo->bpo_object,
1813 		    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1814 		    bytes);
1815 	}
1816 
1817 	if (dump_opt['d'] < 5)
1818 		return;
1819 
1820 
1821 	if (indent == 0) {
1822 		(void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1823 		(void) printf("\n");
1824 	}
1825 }
1826 
1827 static void
bpobj_count_refd(bpobj_t * bpo)1828 bpobj_count_refd(bpobj_t *bpo)
1829 {
1830 	mos_obj_refd(bpo->bpo_object);
1831 
1832 	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1833 		mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
1834 		for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1835 			uint64_t subobj;
1836 			bpobj_t subbpo;
1837 			int error;
1838 			VERIFY0(dmu_read(bpo->bpo_os,
1839 			    bpo->bpo_phys->bpo_subobjs,
1840 			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1841 			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1842 			if (error != 0) {
1843 				(void) printf("ERROR %u while trying to open "
1844 				    "subobj id %llu\n",
1845 				    error, (u_longlong_t)subobj);
1846 				continue;
1847 			}
1848 			bpobj_count_refd(&subbpo);
1849 			bpobj_close(&subbpo);
1850 		}
1851 	}
1852 }
1853 
1854 static void
dump_deadlist(dsl_deadlist_t * dl)1855 dump_deadlist(dsl_deadlist_t *dl)
1856 {
1857 	dsl_deadlist_entry_t *dle;
1858 	uint64_t unused;
1859 	char bytes[32];
1860 	char comp[32];
1861 	char uncomp[32];
1862 	uint64_t empty_bpobj =
1863 	    dmu_objset_spa(dl->dl_os)->spa_dsl_pool->dp_empty_bpobj;
1864 
1865 	/* force the tree to be loaded */
1866 	dsl_deadlist_space_range(dl, 0, UINT64_MAX, &unused, &unused, &unused);
1867 
1868 	if (dl->dl_oldfmt) {
1869 		if (dl->dl_bpobj.bpo_object != empty_bpobj)
1870 			bpobj_count_refd(&dl->dl_bpobj);
1871 	} else {
1872 		mos_obj_refd(dl->dl_object);
1873 		for (dle = avl_first(&dl->dl_tree); dle;
1874 		    dle = AVL_NEXT(&dl->dl_tree, dle)) {
1875 			if (dle->dle_bpobj.bpo_object != empty_bpobj)
1876 				bpobj_count_refd(&dle->dle_bpobj);
1877 		}
1878 	}
1879 
1880 	/* make sure nicenum has enough space */
1881 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1882 	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1883 	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1884 
1885 	if (dump_opt['d'] < 3)
1886 		return;
1887 
1888 	if (dl->dl_oldfmt) {
1889 		dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
1890 		return;
1891 	}
1892 
1893 	zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
1894 	zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
1895 	zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
1896 	(void) printf("\n    Deadlist: %s (%s/%s comp)\n",
1897 	    bytes, comp, uncomp);
1898 
1899 	if (dump_opt['d'] < 4)
1900 		return;
1901 
1902 	(void) printf("\n");
1903 
1904 	for (dle = avl_first(&dl->dl_tree); dle;
1905 	    dle = AVL_NEXT(&dl->dl_tree, dle)) {
1906 		if (dump_opt['d'] >= 5) {
1907 			char buf[128];
1908 			(void) snprintf(buf, sizeof (buf),
1909 			    "mintxg %llu -> obj %llu",
1910 			    (longlong_t)dle->dle_mintxg,
1911 			    (longlong_t)dle->dle_bpobj.bpo_object);
1912 
1913 			dump_full_bpobj(&dle->dle_bpobj, buf, 0);
1914 		} else {
1915 			(void) printf("mintxg %llu -> obj %llu\n",
1916 			    (longlong_t)dle->dle_mintxg,
1917 			    (longlong_t)dle->dle_bpobj.bpo_object);
1918 		}
1919 	}
1920 }
1921 
1922 static avl_tree_t idx_tree;
1923 static avl_tree_t domain_tree;
1924 static boolean_t fuid_table_loaded;
1925 static objset_t *sa_os = NULL;
1926 static sa_attr_type_t *sa_attr_table = NULL;
1927 
1928 static int
open_objset(const char * path,dmu_objset_type_t type,void * tag,objset_t ** osp)1929 open_objset(const char *path, dmu_objset_type_t type, void *tag, objset_t **osp)
1930 {
1931 	int err;
1932 	uint64_t sa_attrs = 0;
1933 	uint64_t version = 0;
1934 
1935 	VERIFY3P(sa_os, ==, NULL);
1936 	err = dmu_objset_own(path, type, B_TRUE, B_FALSE, tag, osp);
1937 	if (err != 0) {
1938 		(void) fprintf(stderr, "failed to own dataset '%s': %s\n", path,
1939 		    strerror(err));
1940 		return (err);
1941 	}
1942 
1943 	if (dmu_objset_type(*osp) == DMU_OST_ZFS && !(*osp)->os_encrypted) {
1944 		(void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1945 		    8, 1, &version);
1946 		if (version >= ZPL_VERSION_SA) {
1947 			(void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1948 			    8, 1, &sa_attrs);
1949 		}
1950 		err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
1951 		    &sa_attr_table);
1952 		if (err != 0) {
1953 			(void) fprintf(stderr, "sa_setup failed: %s\n",
1954 			    strerror(err));
1955 			dmu_objset_disown(*osp, B_FALSE, tag);
1956 			*osp = NULL;
1957 		}
1958 	}
1959 	sa_os = *osp;
1960 
1961 	return (0);
1962 }
1963 
1964 static void
close_objset(objset_t * os,void * tag)1965 close_objset(objset_t *os, void *tag)
1966 {
1967 	VERIFY3P(os, ==, sa_os);
1968 	if (os->os_sa != NULL)
1969 		sa_tear_down(os);
1970 	dmu_objset_disown(os, B_FALSE, tag);
1971 	sa_attr_table = NULL;
1972 	sa_os = NULL;
1973 }
1974 
1975 static void
fuid_table_destroy()1976 fuid_table_destroy()
1977 {
1978 	if (fuid_table_loaded) {
1979 		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1980 		fuid_table_loaded = B_FALSE;
1981 	}
1982 }
1983 
1984 /*
1985  * print uid or gid information.
1986  * For normal POSIX id just the id is printed in decimal format.
1987  * For CIFS files with FUID the fuid is printed in hex followed by
1988  * the domain-rid string.
1989  */
1990 static void
print_idstr(uint64_t id,const char * id_type)1991 print_idstr(uint64_t id, const char *id_type)
1992 {
1993 	if (FUID_INDEX(id)) {
1994 		char *domain;
1995 
1996 		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1997 		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
1998 		    (u_longlong_t)id, domain, (int)FUID_RID(id));
1999 	} else {
2000 		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
2001 	}
2002 
2003 }
2004 
2005 static void
dump_uidgid(objset_t * os,uint64_t uid,uint64_t gid)2006 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
2007 {
2008 	uint32_t uid_idx, gid_idx;
2009 
2010 	uid_idx = FUID_INDEX(uid);
2011 	gid_idx = FUID_INDEX(gid);
2012 
2013 	/* Load domain table, if not already loaded */
2014 	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
2015 		uint64_t fuid_obj;
2016 
2017 		/* first find the fuid object.  It lives in the master node */
2018 		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
2019 		    8, 1, &fuid_obj) == 0);
2020 		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
2021 		(void) zfs_fuid_table_load(os, fuid_obj,
2022 		    &idx_tree, &domain_tree);
2023 		fuid_table_loaded = B_TRUE;
2024 	}
2025 
2026 	print_idstr(uid, "uid");
2027 	print_idstr(gid, "gid");
2028 }
2029 
2030 /*ARGSUSED*/
2031 static void
dump_znode(objset_t * os,uint64_t object,void * data,size_t size)2032 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
2033 {
2034 	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
2035 	sa_handle_t *hdl;
2036 	uint64_t xattr, rdev, gen;
2037 	uint64_t uid, gid, mode, fsize, parent, links;
2038 	uint64_t pflags;
2039 	uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
2040 	time_t z_crtime, z_atime, z_mtime, z_ctime;
2041 	sa_bulk_attr_t bulk[12];
2042 	int idx = 0;
2043 	int error;
2044 
2045 	VERIFY3P(os, ==, sa_os);
2046 	if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
2047 		(void) printf("Failed to get handle for SA znode\n");
2048 		return;
2049 	}
2050 
2051 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
2052 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
2053 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
2054 	    &links, 8);
2055 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
2056 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
2057 	    &mode, 8);
2058 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
2059 	    NULL, &parent, 8);
2060 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
2061 	    &fsize, 8);
2062 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
2063 	    acctm, 16);
2064 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
2065 	    modtm, 16);
2066 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
2067 	    crtm, 16);
2068 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
2069 	    chgtm, 16);
2070 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
2071 	    &pflags, 8);
2072 
2073 	if (sa_bulk_lookup(hdl, bulk, idx)) {
2074 		(void) sa_handle_destroy(hdl);
2075 		return;
2076 	}
2077 
2078 	z_crtime = (time_t)crtm[0];
2079 	z_atime = (time_t)acctm[0];
2080 	z_mtime = (time_t)modtm[0];
2081 	z_ctime = (time_t)chgtm[0];
2082 
2083 	if (dump_opt['d'] > 4) {
2084 		error = zfs_obj_to_path(os, object, path, sizeof (path));
2085 		if (error == ESTALE) {
2086 			(void) snprintf(path, sizeof (path), "on delete queue");
2087 		} else if (error != 0) {
2088 			leaked_objects++;
2089 			(void) snprintf(path, sizeof (path),
2090 			    "path not found, possibly leaked");
2091 		}
2092 		(void) printf("\tpath	%s\n", path);
2093 	}
2094 	dump_uidgid(os, uid, gid);
2095 	(void) printf("\tatime	%s", ctime(&z_atime));
2096 	(void) printf("\tmtime	%s", ctime(&z_mtime));
2097 	(void) printf("\tctime	%s", ctime(&z_ctime));
2098 	(void) printf("\tcrtime	%s", ctime(&z_crtime));
2099 	(void) printf("\tgen	%llu\n", (u_longlong_t)gen);
2100 	(void) printf("\tmode	%llo\n", (u_longlong_t)mode);
2101 	(void) printf("\tsize	%llu\n", (u_longlong_t)fsize);
2102 	(void) printf("\tparent	%llu\n", (u_longlong_t)parent);
2103 	(void) printf("\tlinks	%llu\n", (u_longlong_t)links);
2104 	(void) printf("\tpflags	%llx\n", (u_longlong_t)pflags);
2105 	if (dmu_objset_projectquota_enabled(os) && (pflags & ZFS_PROJID)) {
2106 		uint64_t projid;
2107 
2108 		if (sa_lookup(hdl, sa_attr_table[ZPL_PROJID], &projid,
2109 		    sizeof (uint64_t)) == 0)
2110 			(void) printf("\tprojid	%llu\n", (u_longlong_t)projid);
2111 	}
2112 	if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
2113 	    sizeof (uint64_t)) == 0)
2114 		(void) printf("\txattr	%llu\n", (u_longlong_t)xattr);
2115 	if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
2116 	    sizeof (uint64_t)) == 0)
2117 		(void) printf("\trdev	0x%016llx\n", (u_longlong_t)rdev);
2118 	sa_handle_destroy(hdl);
2119 }
2120 
2121 /*ARGSUSED*/
2122 static void
dump_acl(objset_t * os,uint64_t object,void * data,size_t size)2123 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
2124 {
2125 }
2126 
2127 /*ARGSUSED*/
2128 static void
dump_dmu_objset(objset_t * os,uint64_t object,void * data,size_t size)2129 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
2130 {
2131 }
2132 
2133 
2134 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
2135 	dump_none,		/* unallocated			*/
2136 	dump_zap,		/* object directory		*/
2137 	dump_uint64,		/* object array			*/
2138 	dump_none,		/* packed nvlist		*/
2139 	dump_packed_nvlist,	/* packed nvlist size		*/
2140 	dump_none,		/* bpobj			*/
2141 	dump_bpobj,		/* bpobj header			*/
2142 	dump_none,		/* SPA space map header		*/
2143 	dump_none,		/* SPA space map		*/
2144 	dump_none,		/* ZIL intent log		*/
2145 	dump_dnode,		/* DMU dnode			*/
2146 	dump_dmu_objset,	/* DMU objset			*/
2147 	dump_dsl_dir,		/* DSL directory		*/
2148 	dump_zap,		/* DSL directory child map	*/
2149 	dump_zap,		/* DSL dataset snap map		*/
2150 	dump_zap,		/* DSL props			*/
2151 	dump_dsl_dataset,	/* DSL dataset			*/
2152 	dump_znode,		/* ZFS znode			*/
2153 	dump_acl,		/* ZFS V0 ACL			*/
2154 	dump_uint8,		/* ZFS plain file		*/
2155 	dump_zpldir,		/* ZFS directory		*/
2156 	dump_zap,		/* ZFS master node		*/
2157 	dump_zap,		/* ZFS delete queue		*/
2158 	dump_uint8,		/* zvol object			*/
2159 	dump_zap,		/* zvol prop			*/
2160 	dump_uint8,		/* other uint8[]		*/
2161 	dump_uint64,		/* other uint64[]		*/
2162 	dump_zap,		/* other ZAP			*/
2163 	dump_zap,		/* persistent error log		*/
2164 	dump_uint8,		/* SPA history			*/
2165 	dump_history_offsets,	/* SPA history offsets		*/
2166 	dump_zap,		/* Pool properties		*/
2167 	dump_zap,		/* DSL permissions		*/
2168 	dump_acl,		/* ZFS ACL			*/
2169 	dump_uint8,		/* ZFS SYSACL			*/
2170 	dump_none,		/* FUID nvlist			*/
2171 	dump_packed_nvlist,	/* FUID nvlist size		*/
2172 	dump_zap,		/* DSL dataset next clones	*/
2173 	dump_zap,		/* DSL scrub queue		*/
2174 	dump_zap,		/* ZFS user/group/project used	*/
2175 	dump_zap,		/* ZFS user/group/project quota	*/
2176 	dump_zap,		/* snapshot refcount tags	*/
2177 	dump_ddt_zap,		/* DDT ZAP object		*/
2178 	dump_zap,		/* DDT statistics		*/
2179 	dump_znode,		/* SA object			*/
2180 	dump_zap,		/* SA Master Node		*/
2181 	dump_sa_attrs,		/* SA attribute registration	*/
2182 	dump_sa_layouts,	/* SA attribute layouts		*/
2183 	dump_zap,		/* DSL scrub translations	*/
2184 	dump_none,		/* fake dedup BP		*/
2185 	dump_zap,		/* deadlist			*/
2186 	dump_none,		/* deadlist hdr			*/
2187 	dump_zap,		/* dsl clones			*/
2188 	dump_bpobj_subobjs,	/* bpobj subobjs		*/
2189 	dump_unknown,		/* Unknown type, must be last	*/
2190 };
2191 
2192 static void
dump_object(objset_t * os,uint64_t object,int verbosity,int * print_header,uint64_t * dnode_slots_used)2193 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header,
2194     uint64_t *dnode_slots_used)
2195 {
2196 	dmu_buf_t *db = NULL;
2197 	dmu_object_info_t doi;
2198 	dnode_t *dn;
2199 	boolean_t dnode_held = B_FALSE;
2200 	void *bonus = NULL;
2201 	size_t bsize = 0;
2202 	char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
2203 	char bonus_size[32];
2204 	char aux[50];
2205 	int error;
2206 
2207 	/* make sure nicenum has enough space */
2208 	CTASSERT(sizeof (iblk) >= NN_NUMBUF_SZ);
2209 	CTASSERT(sizeof (dblk) >= NN_NUMBUF_SZ);
2210 	CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
2211 	CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
2212 	CTASSERT(sizeof (bonus_size) >= NN_NUMBUF_SZ);
2213 
2214 	if (*print_header) {
2215 		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %6s  %5s  %6s  %s\n",
2216 		    "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
2217 		    "lsize", "%full", "type");
2218 		*print_header = 0;
2219 	}
2220 
2221 	if (object == 0) {
2222 		dn = DMU_META_DNODE(os);
2223 		dmu_object_info_from_dnode(dn, &doi);
2224 	} else {
2225 		/*
2226 		 * Encrypted datasets will have sensitive bonus buffers
2227 		 * encrypted. Therefore we cannot hold the bonus buffer and
2228 		 * must hold the dnode itself instead.
2229 		 */
2230 		error = dmu_object_info(os, object, &doi);
2231 		if (error)
2232 			fatal("dmu_object_info() failed, errno %u", error);
2233 
2234 		if (os->os_encrypted &&
2235 		    DMU_OT_IS_ENCRYPTED(doi.doi_bonus_type)) {
2236 			error = dnode_hold(os, object, FTAG, &dn);
2237 			if (error)
2238 				fatal("dnode_hold() failed, errno %u", error);
2239 			dnode_held = B_TRUE;
2240 		} else {
2241 			error = dmu_bonus_hold(os, object, FTAG, &db);
2242 			if (error)
2243 				fatal("dmu_bonus_hold(%llu) failed, errno %u",
2244 				    object, error);
2245 			bonus = db->db_data;
2246 			bsize = db->db_size;
2247 			dn = DB_DNODE((dmu_buf_impl_t *)db);
2248 		}
2249 	}
2250 
2251 	if (dnode_slots_used != NULL)
2252 		*dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
2253 
2254 	zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
2255 	zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
2256 	zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
2257 	zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
2258 	zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
2259 	zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
2260 	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
2261 	    doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
2262 	    doi.doi_max_offset);
2263 
2264 	aux[0] = '\0';
2265 
2266 	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
2267 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
2268 		    ZDB_CHECKSUM_NAME(doi.doi_checksum));
2269 	}
2270 
2271 	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
2272 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
2273 		    ZDB_COMPRESS_NAME(doi.doi_compress));
2274 	}
2275 
2276 	(void) printf("%10" PRIu64
2277 	    "  %3u  %5s  %5s  %5s  %5s  %5s  %6s  %s%s\n",
2278 	    object, doi.doi_indirection, iblk, dblk,
2279 	    asize, dnsize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
2280 
2281 	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
2282 		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %5s  %6s  %s\n",
2283 		    "", "", "", "", "", "", bonus_size, "bonus",
2284 		    ZDB_OT_NAME(doi.doi_bonus_type));
2285 	}
2286 
2287 	if (verbosity >= 4) {
2288 		(void) printf("\tdnode flags: %s%s%s%s\n",
2289 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
2290 		    "USED_BYTES " : "",
2291 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
2292 		    "USERUSED_ACCOUNTED " : "",
2293 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) ?
2294 		    "USEROBJUSED_ACCOUNTED " : "",
2295 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
2296 		    "SPILL_BLKPTR" : "");
2297 		(void) printf("\tdnode maxblkid: %llu\n",
2298 		    (longlong_t)dn->dn_phys->dn_maxblkid);
2299 
2300 		if (!dnode_held) {
2301 			object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os,
2302 			    object, bonus, bsize);
2303 		} else {
2304 			(void) printf("\t\t(bonus encrypted)\n");
2305 		}
2306 
2307 		if (!os->os_encrypted || !DMU_OT_IS_ENCRYPTED(doi.doi_type)) {
2308 			object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object,
2309 			    NULL, 0);
2310 		} else {
2311 			(void) printf("\t\t(object encrypted)\n");
2312 		}
2313 
2314 		*print_header = 1;
2315 	}
2316 
2317 	if (verbosity >= 5)
2318 		dump_indirect(dn);
2319 
2320 	if (verbosity >= 5) {
2321 		/*
2322 		 * Report the list of segments that comprise the object.
2323 		 */
2324 		uint64_t start = 0;
2325 		uint64_t end;
2326 		uint64_t blkfill = 1;
2327 		int minlvl = 1;
2328 
2329 		if (dn->dn_type == DMU_OT_DNODE) {
2330 			minlvl = 0;
2331 			blkfill = DNODES_PER_BLOCK;
2332 		}
2333 
2334 		for (;;) {
2335 			char segsize[32];
2336 			/* make sure nicenum has enough space */
2337 			CTASSERT(sizeof (segsize) >= NN_NUMBUF_SZ);
2338 			error = dnode_next_offset(dn,
2339 			    0, &start, minlvl, blkfill, 0);
2340 			if (error)
2341 				break;
2342 			end = start;
2343 			error = dnode_next_offset(dn,
2344 			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
2345 			zdb_nicenum(end - start, segsize, sizeof (segsize));
2346 			(void) printf("\t\tsegment [%016llx, %016llx)"
2347 			    " size %5s\n", (u_longlong_t)start,
2348 			    (u_longlong_t)end, segsize);
2349 			if (error)
2350 				break;
2351 			start = end;
2352 		}
2353 	}
2354 
2355 	if (db != NULL)
2356 		dmu_buf_rele(db, FTAG);
2357 	if (dnode_held)
2358 		dnode_rele(dn, FTAG);
2359 }
2360 
2361 static void
count_dir_mos_objects(dsl_dir_t * dd)2362 count_dir_mos_objects(dsl_dir_t *dd)
2363 {
2364 	mos_obj_refd(dd->dd_object);
2365 	mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
2366 	mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
2367 	mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
2368 	mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
2369 }
2370 
2371 static void
count_ds_mos_objects(dsl_dataset_t * ds)2372 count_ds_mos_objects(dsl_dataset_t *ds)
2373 {
2374 	mos_obj_refd(ds->ds_object);
2375 	mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
2376 	mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
2377 	mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
2378 	mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
2379 
2380 	if (!dsl_dataset_is_snapshot(ds)) {
2381 		count_dir_mos_objects(ds->ds_dir);
2382 	}
2383 }
2384 
2385 static const char *objset_types[DMU_OST_NUMTYPES] = {
2386 	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
2387 
2388 static void
dump_dir(objset_t * os)2389 dump_dir(objset_t *os)
2390 {
2391 	dmu_objset_stats_t dds;
2392 	uint64_t object, object_count;
2393 	uint64_t refdbytes, usedobjs, scratch;
2394 	char numbuf[32];
2395 	char blkbuf[BP_SPRINTF_LEN + 20];
2396 	char osname[ZFS_MAX_DATASET_NAME_LEN];
2397 	const char *type = "UNKNOWN";
2398 	int verbosity = dump_opt['d'];
2399 	int print_header = 1;
2400 	unsigned i;
2401 	int error;
2402 	uint64_t total_slots_used = 0;
2403 	uint64_t max_slot_used = 0;
2404 	uint64_t dnode_slots;
2405 
2406 	/* make sure nicenum has enough space */
2407 	CTASSERT(sizeof (numbuf) >= NN_NUMBUF_SZ);
2408 
2409 	dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2410 	dmu_objset_fast_stat(os, &dds);
2411 	dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2412 
2413 	if (dds.dds_type < DMU_OST_NUMTYPES)
2414 		type = objset_types[dds.dds_type];
2415 
2416 	if (dds.dds_type == DMU_OST_META) {
2417 		dds.dds_creation_txg = TXG_INITIAL;
2418 		usedobjs = BP_GET_FILL(os->os_rootbp);
2419 		refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
2420 		    dd_used_bytes;
2421 	} else {
2422 		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
2423 	}
2424 
2425 	ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
2426 
2427 	zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
2428 
2429 	if (verbosity >= 4) {
2430 		(void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
2431 		(void) snprintf_blkptr(blkbuf + strlen(blkbuf),
2432 		    sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
2433 	} else {
2434 		blkbuf[0] = '\0';
2435 	}
2436 
2437 	dmu_objset_name(os, osname);
2438 
2439 	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
2440 	    "%s, %llu objects%s%s\n",
2441 	    osname, type, (u_longlong_t)dmu_objset_id(os),
2442 	    (u_longlong_t)dds.dds_creation_txg,
2443 	    numbuf, (u_longlong_t)usedobjs, blkbuf,
2444 	    (dds.dds_inconsistent) ? " (inconsistent)" : "");
2445 
2446 	if (zopt_objects != 0) {
2447 		for (i = 0; i < zopt_objects; i++)
2448 			dump_object(os, zopt_object[i], verbosity,
2449 			    &print_header, NULL);
2450 		(void) printf("\n");
2451 		return;
2452 	}
2453 
2454 	if (dump_opt['i'] != 0 || verbosity >= 2)
2455 		dump_intent_log(dmu_objset_zil(os));
2456 
2457 	if (dmu_objset_ds(os) != NULL) {
2458 		dsl_dataset_t *ds = dmu_objset_ds(os);
2459 		dump_deadlist(&ds->ds_deadlist);
2460 
2461 		if (dsl_dataset_remap_deadlist_exists(ds)) {
2462 			(void) printf("ds_remap_deadlist:\n");
2463 			dump_deadlist(&ds->ds_remap_deadlist);
2464 		}
2465 		count_ds_mos_objects(ds);
2466 	}
2467 
2468 	if (verbosity < 2)
2469 		return;
2470 
2471 	if (BP_IS_HOLE(os->os_rootbp))
2472 		return;
2473 
2474 	dump_object(os, 0, verbosity, &print_header, NULL);
2475 	object_count = 0;
2476 	if (DMU_USERUSED_DNODE(os) != NULL &&
2477 	    DMU_USERUSED_DNODE(os)->dn_type != 0) {
2478 		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
2479 		    NULL);
2480 		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
2481 		    NULL);
2482 	}
2483 
2484 	if (DMU_PROJECTUSED_DNODE(os) != NULL &&
2485 	    DMU_PROJECTUSED_DNODE(os)->dn_type != 0)
2486 		dump_object(os, DMU_PROJECTUSED_OBJECT, verbosity,
2487 		    &print_header, NULL);
2488 
2489 	object = 0;
2490 	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
2491 		dump_object(os, object, verbosity, &print_header, &dnode_slots);
2492 		object_count++;
2493 		total_slots_used += dnode_slots;
2494 		max_slot_used = object + dnode_slots - 1;
2495 	}
2496 
2497 	(void) printf("\n");
2498 
2499 	(void) printf("    Dnode slots:\n");
2500 	(void) printf("\tTotal used:    %10llu\n",
2501 	    (u_longlong_t)total_slots_used);
2502 	(void) printf("\tMax used:      %10llu\n",
2503 	    (u_longlong_t)max_slot_used);
2504 	(void) printf("\tPercent empty: %10lf\n",
2505 	    (double)(max_slot_used - total_slots_used)*100 /
2506 	    (double)max_slot_used);
2507 
2508 	(void) printf("\n");
2509 
2510 	if (error != ESRCH) {
2511 		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
2512 		abort();
2513 	}
2514 	if (leaked_objects != 0) {
2515 		(void) printf("%d potentially leaked objects detected\n",
2516 		    leaked_objects);
2517 		leaked_objects = 0;
2518 	}
2519 
2520 	ASSERT3U(object_count, ==, usedobjs);
2521 }
2522 
2523 static void
dump_uberblock(uberblock_t * ub,const char * header,const char * footer)2524 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
2525 {
2526 	time_t timestamp = ub->ub_timestamp;
2527 
2528 	(void) printf("%s", header ? header : "");
2529 	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
2530 	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
2531 	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
2532 	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
2533 	(void) printf("\ttimestamp = %llu UTC = %s",
2534 	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
2535 
2536 	(void) printf("\tmmp_magic = %016llx\n",
2537 	    (u_longlong_t)ub->ub_mmp_magic);
2538 	if (MMP_VALID(ub)) {
2539 		(void) printf("\tmmp_delay = %0llu\n",
2540 		    (u_longlong_t)ub->ub_mmp_delay);
2541 		if (MMP_SEQ_VALID(ub))
2542 			(void) printf("\tmmp_seq = %u\n",
2543 			    (unsigned int) MMP_SEQ(ub));
2544 		if (MMP_FAIL_INT_VALID(ub))
2545 			(void) printf("\tmmp_fail = %u\n",
2546 			    (unsigned int) MMP_FAIL_INT(ub));
2547 		if (MMP_INTERVAL_VALID(ub))
2548 			(void) printf("\tmmp_write = %u\n",
2549 			    (unsigned int) MMP_INTERVAL(ub));
2550 		/* After MMP_* to make summarize_uberblock_mmp cleaner */
2551 		(void) printf("\tmmp_valid = %x\n",
2552 		    (unsigned int) ub->ub_mmp_config & 0xFF);
2553 	}
2554 
2555 	if (dump_opt['u'] >= 4) {
2556 		char blkbuf[BP_SPRINTF_LEN];
2557 		snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
2558 		(void) printf("\trootbp = %s\n", blkbuf);
2559 	}
2560 	(void) printf("\tcheckpoint_txg = %llu\n",
2561 	    (u_longlong_t)ub->ub_checkpoint_txg);
2562 	(void) printf("%s", footer ? footer : "");
2563 }
2564 
2565 static void
dump_config(spa_t * spa)2566 dump_config(spa_t *spa)
2567 {
2568 	dmu_buf_t *db;
2569 	size_t nvsize = 0;
2570 	int error = 0;
2571 
2572 
2573 	error = dmu_bonus_hold(spa->spa_meta_objset,
2574 	    spa->spa_config_object, FTAG, &db);
2575 
2576 	if (error == 0) {
2577 		nvsize = *(uint64_t *)db->db_data;
2578 		dmu_buf_rele(db, FTAG);
2579 
2580 		(void) printf("\nMOS Configuration:\n");
2581 		dump_packed_nvlist(spa->spa_meta_objset,
2582 		    spa->spa_config_object, (void *)&nvsize, 1);
2583 	} else {
2584 		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
2585 		    (u_longlong_t)spa->spa_config_object, error);
2586 	}
2587 }
2588 
2589 static void
dump_cachefile(const char * cachefile)2590 dump_cachefile(const char *cachefile)
2591 {
2592 	int fd;
2593 	struct stat64 statbuf;
2594 	char *buf;
2595 	nvlist_t *config;
2596 
2597 	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
2598 		(void) printf("cannot open '%s': %s\n", cachefile,
2599 		    strerror(errno));
2600 		exit(1);
2601 	}
2602 
2603 	if (fstat64(fd, &statbuf) != 0) {
2604 		(void) printf("failed to stat '%s': %s\n", cachefile,
2605 		    strerror(errno));
2606 		exit(1);
2607 	}
2608 
2609 	if ((buf = malloc(statbuf.st_size)) == NULL) {
2610 		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
2611 		    (u_longlong_t)statbuf.st_size);
2612 		exit(1);
2613 	}
2614 
2615 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
2616 		(void) fprintf(stderr, "failed to read %llu bytes\n",
2617 		    (u_longlong_t)statbuf.st_size);
2618 		exit(1);
2619 	}
2620 
2621 	(void) close(fd);
2622 
2623 	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
2624 		(void) fprintf(stderr, "failed to unpack nvlist\n");
2625 		exit(1);
2626 	}
2627 
2628 	free(buf);
2629 
2630 	dump_nvlist(config, 0);
2631 
2632 	nvlist_free(config);
2633 }
2634 
2635 static void
print_l2arc_header(void)2636 print_l2arc_header(void)
2637 {
2638 	(void) printf("------------------------------------\n");
2639 	(void) printf("L2ARC device header\n");
2640 	(void) printf("------------------------------------\n");
2641 }
2642 
2643 static void
print_l2arc_log_blocks(void)2644 print_l2arc_log_blocks(void)
2645 {
2646 	(void) printf("------------------------------------\n");
2647 	(void) printf("L2ARC device log blocks\n");
2648 	(void) printf("------------------------------------\n");
2649 }
2650 
2651 static void
dump_l2arc_log_entries(uint64_t log_entries,l2arc_log_ent_phys_t * le,uint64_t i)2652 dump_l2arc_log_entries(uint64_t log_entries,
2653     l2arc_log_ent_phys_t *le, uint64_t i)
2654 {
2655 	for (uint64_t j = 0; j < log_entries; j++) {
2656 		dva_t dva = le[j].le_dva;
2657 		(void) printf("lb[%4llu]\tle[%4d]\tDVA asize: %llu, "
2658 		    "vdev: %llu, offset: %llu\n",
2659 		    (u_longlong_t)i, j + 1,
2660 		    (u_longlong_t)DVA_GET_ASIZE(&dva),
2661 		    (u_longlong_t)DVA_GET_VDEV(&dva),
2662 		    (u_longlong_t)DVA_GET_OFFSET(&dva));
2663 		(void) printf("|\t\t\t\tbirth: %llu\n",
2664 		    (u_longlong_t)le[j].le_birth);
2665 		(void) printf("|\t\t\t\tlsize: %llu\n",
2666 		    (u_longlong_t)L2BLK_GET_LSIZE((&le[j])->le_prop));
2667 		(void) printf("|\t\t\t\tpsize: %llu\n",
2668 		    (u_longlong_t)L2BLK_GET_PSIZE((&le[j])->le_prop));
2669 		(void) printf("|\t\t\t\tcompr: %llu\n",
2670 		    (u_longlong_t)L2BLK_GET_COMPRESS((&le[j])->le_prop));
2671 		(void) printf("|\t\t\t\ttype: %llu\n",
2672 		    (u_longlong_t)L2BLK_GET_TYPE((&le[j])->le_prop));
2673 		(void) printf("|\t\t\t\tprotected: %llu\n",
2674 		    (u_longlong_t)L2BLK_GET_PROTECTED((&le[j])->le_prop));
2675 		(void) printf("|\t\t\t\tprefetch: %llu\n",
2676 		    (u_longlong_t)L2BLK_GET_PREFETCH((&le[j])->le_prop));
2677 		(void) printf("|\t\t\t\taddress: %llu\n",
2678 		    (u_longlong_t)le[j].le_daddr);
2679 		(void) printf("|\n");
2680 	}
2681 	(void) printf("\n");
2682 }
2683 
2684 static void
dump_l2arc_log_blkptr(l2arc_log_blkptr_t lbps)2685 dump_l2arc_log_blkptr(l2arc_log_blkptr_t lbps)
2686 {
2687 	(void) printf("|\t\tdaddr: %llu\n", (u_longlong_t)lbps.lbp_daddr);
2688 	(void) printf("|\t\tpayload_asize: %llu\n",
2689 	    (u_longlong_t)lbps.lbp_payload_asize);
2690 	(void) printf("|\t\tpayload_start: %llu\n",
2691 	    (u_longlong_t)lbps.lbp_payload_start);
2692 	(void) printf("|\t\tlsize: %llu\n",
2693 	    (u_longlong_t)L2BLK_GET_LSIZE((&lbps)->lbp_prop));
2694 	(void) printf("|\t\tasize: %llu\n",
2695 	    (u_longlong_t)L2BLK_GET_PSIZE((&lbps)->lbp_prop));
2696 	(void) printf("|\t\tcompralgo: %llu\n",
2697 	    (u_longlong_t)L2BLK_GET_COMPRESS((&lbps)->lbp_prop));
2698 	(void) printf("|\t\tcksumalgo: %llu\n",
2699 	    (u_longlong_t)L2BLK_GET_CHECKSUM((&lbps)->lbp_prop));
2700 	(void) printf("|\n\n");
2701 }
2702 
2703 static void
dump_l2arc_log_blocks(int fd,l2arc_dev_hdr_phys_t l2dhdr,l2arc_dev_hdr_phys_t * rebuild)2704 dump_l2arc_log_blocks(int fd, l2arc_dev_hdr_phys_t l2dhdr,
2705     l2arc_dev_hdr_phys_t *rebuild)
2706 {
2707 	l2arc_log_blk_phys_t this_lb;
2708 	uint64_t asize;
2709 	l2arc_log_blkptr_t lbps[2];
2710 	abd_t *abd;
2711 	zio_cksum_t cksum;
2712 	int failed = 0;
2713 	l2arc_dev_t dev;
2714 
2715 	if (!dump_opt['q'])
2716 		print_l2arc_log_blocks();
2717 	bcopy((&l2dhdr)->dh_start_lbps, lbps, sizeof (lbps));
2718 
2719 	dev.l2ad_evict = l2dhdr.dh_evict;
2720 	dev.l2ad_start = l2dhdr.dh_start;
2721 	dev.l2ad_end = l2dhdr.dh_end;
2722 
2723 	if (l2dhdr.dh_start_lbps[0].lbp_daddr == 0) {
2724 		/* no log blocks to read */
2725 		if (!dump_opt['q']) {
2726 			(void) printf("No log blocks to read\n");
2727 			(void) printf("\n");
2728 		}
2729 		return;
2730 	} else {
2731 		dev.l2ad_hand = lbps[0].lbp_daddr +
2732 		    L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
2733 	}
2734 
2735 	dev.l2ad_first = !!(l2dhdr.dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
2736 
2737 	for (;;) {
2738 		if (!l2arc_log_blkptr_valid(&dev, &lbps[0]))
2739 			break;
2740 
2741 		/* L2BLK_GET_PSIZE returns aligned size for log blocks */
2742 		asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
2743 		if (pread64(fd, &this_lb, asize, lbps[0].lbp_daddr) !=
2744 		    (ssize_t)asize) {
2745 			if (!dump_opt['q']) {
2746 				(void) printf("Error while reading next log "
2747 				    "block\n\n");
2748 			}
2749 			break;
2750 		}
2751 
2752 		fletcher_4_native(&this_lb, asize, NULL, &cksum);
2753 		if (!ZIO_CHECKSUM_EQUAL(cksum, lbps[0].lbp_cksum)) {
2754 			failed++;
2755 			if (!dump_opt['q']) {
2756 				(void) printf("Invalid cksum\n");
2757 				dump_l2arc_log_blkptr(lbps[0]);
2758 			}
2759 			break;
2760 		}
2761 
2762 		switch (L2BLK_GET_COMPRESS((&lbps[0])->lbp_prop)) {
2763 		case ZIO_COMPRESS_OFF:
2764 			break;
2765 		case ZIO_COMPRESS_LZ4:
2766 			abd = abd_alloc_for_io(asize, B_TRUE);
2767 			abd_copy_from_buf_off(abd, &this_lb, 0, asize);
2768 			zio_decompress_data(L2BLK_GET_COMPRESS(
2769 			    (&lbps[0])->lbp_prop), abd, &this_lb,
2770 			    asize, sizeof (this_lb));
2771 			abd_free(abd);
2772 			break;
2773 		default:
2774 			break;
2775 		}
2776 
2777 		if (this_lb.lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
2778 			byteswap_uint64_array(&this_lb, sizeof (this_lb));
2779 		if (this_lb.lb_magic != L2ARC_LOG_BLK_MAGIC) {
2780 			if (!dump_opt['q'])
2781 				(void) printf("Invalid log block magic\n\n");
2782 			break;
2783 		}
2784 
2785 		rebuild->dh_lb_count++;
2786 		rebuild->dh_lb_asize += asize;
2787 		if (dump_opt['l'] > 1 && !dump_opt['q']) {
2788 			(void) printf("lb[%4llu]\tmagic: %llu\n",
2789 			    (u_longlong_t)rebuild->dh_lb_count,
2790 			    (u_longlong_t)this_lb.lb_magic);
2791 			dump_l2arc_log_blkptr(lbps[0]);
2792 		}
2793 
2794 		if (dump_opt['l'] > 2 && !dump_opt['q'])
2795 			dump_l2arc_log_entries(l2dhdr.dh_log_entries,
2796 			    this_lb.lb_entries,
2797 			    rebuild->dh_lb_count);
2798 
2799 		if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
2800 		    lbps[0].lbp_payload_start, dev.l2ad_evict) &&
2801 		    !dev.l2ad_first)
2802 			break;
2803 
2804 		lbps[0] = lbps[1];
2805 		lbps[1] = this_lb.lb_prev_lbp;
2806 	}
2807 
2808 	if (!dump_opt['q']) {
2809 		(void) printf("log_blk_count:\t %llu with valid cksum\n",
2810 		    (u_longlong_t)rebuild->dh_lb_count);
2811 		(void) printf("\t\t %d with invalid cksum\n", failed);
2812 		(void) printf("log_blk_asize:\t %llu\n\n",
2813 		    (u_longlong_t)rebuild->dh_lb_asize);
2814 	}
2815 }
2816 
2817 static int
dump_l2arc_header(int fd)2818 dump_l2arc_header(int fd)
2819 {
2820 	l2arc_dev_hdr_phys_t l2dhdr, rebuild;
2821 	int error = B_FALSE;
2822 
2823 	bzero(&l2dhdr, sizeof (l2dhdr));
2824 	bzero(&rebuild, sizeof (rebuild));
2825 
2826 	if (pread64(fd, &l2dhdr, sizeof (l2dhdr),
2827 	    VDEV_LABEL_START_SIZE) != sizeof (l2dhdr)) {
2828 		error = B_TRUE;
2829 	} else {
2830 		if (l2dhdr.dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
2831 			byteswap_uint64_array(&l2dhdr, sizeof (l2dhdr));
2832 
2833 		if (l2dhdr.dh_magic != L2ARC_DEV_HDR_MAGIC)
2834 			error = B_TRUE;
2835 	}
2836 
2837 	if (error) {
2838 		(void) printf("L2ARC device header not found\n\n");
2839 		/* Do not return an error here for backward compatibility */
2840 		return (0);
2841 	} else if (!dump_opt['q']) {
2842 		print_l2arc_header();
2843 
2844 		(void) printf("    magic: %llu\n",
2845 		    (u_longlong_t)l2dhdr.dh_magic);
2846 		(void) printf("    version: %llu\n",
2847 		    (u_longlong_t)l2dhdr.dh_version);
2848 		(void) printf("    pool_guid: %llu\n",
2849 		    (u_longlong_t)l2dhdr.dh_spa_guid);
2850 		(void) printf("    flags: %llu\n",
2851 		    (u_longlong_t)l2dhdr.dh_flags);
2852 		(void) printf("    start_lbps[0]: %llu\n",
2853 		    (u_longlong_t)
2854 		    l2dhdr.dh_start_lbps[0].lbp_daddr);
2855 		(void) printf("    start_lbps[1]: %llu\n",
2856 		    (u_longlong_t)
2857 		    l2dhdr.dh_start_lbps[1].lbp_daddr);
2858 		(void) printf("    log_blk_ent: %llu\n",
2859 		    (u_longlong_t)l2dhdr.dh_log_entries);
2860 		(void) printf("    start: %llu\n",
2861 		    (u_longlong_t)l2dhdr.dh_start);
2862 		(void) printf("    end: %llu\n",
2863 		    (u_longlong_t)l2dhdr.dh_end);
2864 		(void) printf("    evict: %llu\n",
2865 		    (u_longlong_t)l2dhdr.dh_evict);
2866 		(void) printf("    lb_asize_refcount: %llu\n",
2867 		    (u_longlong_t)l2dhdr.dh_lb_asize);
2868 		(void) printf("    lb_count_refcount: %llu\n\n",
2869 		    (u_longlong_t)l2dhdr.dh_lb_count);
2870 	}
2871 
2872 	dump_l2arc_log_blocks(fd, l2dhdr, &rebuild);
2873 	/*
2874 	 * The total aligned size of log blocks and the number of log blocks
2875 	 * reported in the header of the device may be less than what zdb
2876 	 * reports by dump_l2arc_log_blocks() which emulates l2arc_rebuild().
2877 	 * This happens because dump_l2arc_log_blocks() lacks the memory
2878 	 * pressure valve that l2arc_rebuild() has. Thus, if we are on a system
2879 	 * with low memory, l2arc_rebuild will exit prematurely and dh_lb_asize
2880 	 * and dh_lb_count will be lower to begin with than what exists on the
2881 	 * device. This is normal and zdb should not exit with an error. The
2882 	 * opposite case should never happen though, the values reported in the
2883 	 * header should never be higher than what dump_l2arc_log_blocks() and
2884 	 * l2arc_rebuild() report. If this happens there is a leak in the
2885 	 * accounting of log blocks.
2886 	 */
2887 	if (l2dhdr.dh_lb_asize > rebuild.dh_lb_asize ||
2888 	    l2dhdr.dh_lb_count > rebuild.dh_lb_count)
2889 		return (1);
2890 
2891 	return (0);
2892 }
2893 
2894 static char curpath[PATH_MAX];
2895 
2896 /*
2897  * Iterate through the path components, recursively passing
2898  * current one's obj and remaining path until we find the obj
2899  * for the last one.
2900  */
2901 static int
dump_path_impl(objset_t * os,uint64_t obj,char * name)2902 dump_path_impl(objset_t *os, uint64_t obj, char *name)
2903 {
2904 	int err;
2905 	int header = 1;
2906 	uint64_t child_obj;
2907 	char *s;
2908 	dmu_buf_t *db;
2909 	dmu_object_info_t doi;
2910 
2911 	if ((s = strchr(name, '/')) != NULL)
2912 		*s = '\0';
2913 	err = zap_lookup(os, obj, name, 8, 1, &child_obj);
2914 
2915 	(void) strlcat(curpath, name, sizeof (curpath));
2916 
2917 	if (err != 0) {
2918 		(void) fprintf(stderr, "failed to lookup %s: %s\n",
2919 		    curpath, strerror(err));
2920 		return (err);
2921 	}
2922 
2923 	child_obj = ZFS_DIRENT_OBJ(child_obj);
2924 	err = sa_buf_hold(os, child_obj, FTAG, &db);
2925 	if (err != 0) {
2926 		(void) fprintf(stderr,
2927 		    "failed to get SA dbuf for obj %llu: %s\n",
2928 		    (u_longlong_t)child_obj, strerror(err));
2929 		return (EINVAL);
2930 	}
2931 	dmu_object_info_from_db(db, &doi);
2932 	sa_buf_rele(db, FTAG);
2933 
2934 	if (doi.doi_bonus_type != DMU_OT_SA &&
2935 	    doi.doi_bonus_type != DMU_OT_ZNODE) {
2936 		(void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
2937 		    doi.doi_bonus_type, (u_longlong_t)child_obj);
2938 		return (EINVAL);
2939 	}
2940 
2941 	if (dump_opt['v'] > 6) {
2942 		(void) printf("obj=%llu %s type=%d bonustype=%d\n",
2943 		    (u_longlong_t)child_obj, curpath, doi.doi_type,
2944 		    doi.doi_bonus_type);
2945 	}
2946 
2947 	(void) strlcat(curpath, "/", sizeof (curpath));
2948 
2949 	switch (doi.doi_type) {
2950 	case DMU_OT_DIRECTORY_CONTENTS:
2951 		if (s != NULL && *(s + 1) != '\0')
2952 			return (dump_path_impl(os, child_obj, s + 1));
2953