xref: /illumos-gate/usr/src/cmd/zdb/zdb.c (revision b0ab67fe)
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 	char tbuf[30];
1360 
1361 	char *buf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
1362 	do {
1363 		len = SPA_MAXBLOCKSIZE;
1364 
1365 		if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
1366 			(void) fprintf(stderr, "Unable to read history: "
1367 			    "error %d\n", error);
1368 			umem_free(buf, SPA_MAXBLOCKSIZE);
1369 			return;
1370 		}
1371 
1372 		if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
1373 			break;
1374 
1375 		off -= resid;
1376 	} while (len != 0);
1377 	umem_free(buf, SPA_MAXBLOCKSIZE);
1378 
1379 	(void) printf("\nHistory:\n");
1380 	for (unsigned i = 0; i < num; i++) {
1381 		boolean_t printed = B_FALSE;
1382 
1383 		if (nvlist_exists(events[i], ZPOOL_HIST_TIME)) {
1384 			time_t tsec;
1385 			struct tm t;
1386 
1387 			tsec = fnvlist_lookup_uint64(events[i],
1388 			    ZPOOL_HIST_TIME);
1389 			(void) localtime_r(&tsec, &t);
1390 			(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
1391 		} else {
1392 			tbuf[0] = '\0';
1393 		}
1394 
1395 		if (nvlist_exists(events[i], ZPOOL_HIST_CMD)) {
1396 			(void) printf("%s %s\n", tbuf,
1397 			    fnvlist_lookup_string(events[i], ZPOOL_HIST_CMD));
1398 		} else if (nvlist_exists(events[i], ZPOOL_HIST_INT_EVENT)) {
1399 			uint64_t ievent;
1400 
1401 			ievent = fnvlist_lookup_uint64(events[i],
1402 			    ZPOOL_HIST_INT_EVENT);
1403 			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
1404 				goto next;
1405 
1406 			(void) printf(" %s [internal %s txg:%ju] %s\n",
1407 			    tbuf,
1408 			    zfs_history_event_names[ievent],
1409 			    fnvlist_lookup_uint64(events[i],
1410 			    ZPOOL_HIST_TXG),
1411 			    fnvlist_lookup_string(events[i],
1412 			    ZPOOL_HIST_INT_STR));
1413 		} else if (nvlist_exists(events[i], ZPOOL_HIST_INT_NAME)) {
1414 			(void) printf("%s [txg:%ju] %s", tbuf,
1415 			    fnvlist_lookup_uint64(events[i],
1416 			    ZPOOL_HIST_TXG),
1417 			    fnvlist_lookup_string(events[i],
1418 			    ZPOOL_HIST_INT_NAME));
1419 
1420 			if (nvlist_exists(events[i], ZPOOL_HIST_DSNAME)) {
1421 				(void) printf(" %s (%llu)",
1422 				    fnvlist_lookup_string(events[i],
1423 				    ZPOOL_HIST_DSNAME),
1424 				    (u_longlong_t)fnvlist_lookup_uint64(
1425 				    events[i],
1426 				    ZPOOL_HIST_DSID));
1427 			}
1428 
1429 			(void) printf(" %s\n", fnvlist_lookup_string(events[i],
1430 			    ZPOOL_HIST_INT_STR));
1431 		} else if (nvlist_exists(events[i], ZPOOL_HIST_IOCTL)) {
1432 			(void) printf("%s ioctl %s\n", tbuf,
1433 			    fnvlist_lookup_string(events[i],
1434 			    ZPOOL_HIST_IOCTL));
1435 
1436 			if (nvlist_exists(events[i], ZPOOL_HIST_INPUT_NVL)) {
1437 				(void) printf("    input:\n");
1438 				dump_nvlist(fnvlist_lookup_nvlist(events[i],
1439 				    ZPOOL_HIST_INPUT_NVL), 8);
1440 			}
1441 			if (nvlist_exists(events[i], ZPOOL_HIST_OUTPUT_NVL)) {
1442 				(void) printf("    output:\n");
1443 				dump_nvlist(fnvlist_lookup_nvlist(events[i],
1444 				    ZPOOL_HIST_OUTPUT_NVL), 8);
1445 			}
1446 			if (nvlist_exists(events[i], ZPOOL_HIST_ERRNO)) {
1447 				(void) printf("    errno: %lld\n",
1448 				    (longlong_t)fnvlist_lookup_int64(events[i],
1449 				    ZPOOL_HIST_ERRNO));
1450 			}
1451 		} else {
1452 			goto next;
1453 		}
1454 
1455 		printed = B_TRUE;
1456 next:
1457 		if (dump_opt['h'] > 1) {
1458 			if (!printed)
1459 				(void) printf("unrecognized record:\n");
1460 			dump_nvlist(events[i], 2);
1461 		}
1462 	}
1463 }
1464 
1465 /*ARGSUSED*/
1466 static void
dump_dnode(objset_t * os,uint64_t object,void * data,size_t size)1467 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
1468 {
1469 }
1470 
1471 static uint64_t
blkid2offset(const dnode_phys_t * dnp,const blkptr_t * bp,const zbookmark_phys_t * zb)1472 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
1473     const zbookmark_phys_t *zb)
1474 {
1475 	if (dnp == NULL) {
1476 		ASSERT(zb->zb_level < 0);
1477 		if (zb->zb_object == 0)
1478 			return (zb->zb_blkid);
1479 		return (zb->zb_blkid * BP_GET_LSIZE(bp));
1480 	}
1481 
1482 	ASSERT(zb->zb_level >= 0);
1483 
1484 	return ((zb->zb_blkid <<
1485 	    (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
1486 	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
1487 }
1488 
1489 static void
snprintf_blkptr_compact(char * blkbuf,size_t buflen,const blkptr_t * bp)1490 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp)
1491 {
1492 	const dva_t *dva = bp->blk_dva;
1493 	unsigned int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
1494 
1495 	if (dump_opt['b'] >= 6) {
1496 		snprintf_blkptr(blkbuf, buflen, bp);
1497 		return;
1498 	}
1499 
1500 	if (BP_IS_EMBEDDED(bp)) {
1501 		(void) sprintf(blkbuf,
1502 		    "EMBEDDED et=%u %llxL/%llxP B=%llu",
1503 		    (int)BPE_GET_ETYPE(bp),
1504 		    (u_longlong_t)BPE_GET_LSIZE(bp),
1505 		    (u_longlong_t)BPE_GET_PSIZE(bp),
1506 		    (u_longlong_t)bp->blk_birth);
1507 		return;
1508 	}
1509 
1510 	blkbuf[0] = '\0';
1511 	for (unsigned int i = 0; i < ndvas; i++)
1512 		(void) snprintf(blkbuf + strlen(blkbuf),
1513 		    buflen - strlen(blkbuf), "%llu:%llx:%llx ",
1514 		    (u_longlong_t)DVA_GET_VDEV(&dva[i]),
1515 		    (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
1516 		    (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
1517 
1518 	if (BP_IS_HOLE(bp)) {
1519 		(void) snprintf(blkbuf + strlen(blkbuf),
1520 		    buflen - strlen(blkbuf),
1521 		    "%llxL B=%llu",
1522 		    (u_longlong_t)BP_GET_LSIZE(bp),
1523 		    (u_longlong_t)bp->blk_birth);
1524 	} else {
1525 		(void) snprintf(blkbuf + strlen(blkbuf),
1526 		    buflen - strlen(blkbuf),
1527 		    "%llxL/%llxP F=%llu B=%llu/%llu",
1528 		    (u_longlong_t)BP_GET_LSIZE(bp),
1529 		    (u_longlong_t)BP_GET_PSIZE(bp),
1530 		    (u_longlong_t)BP_GET_FILL(bp),
1531 		    (u_longlong_t)bp->blk_birth,
1532 		    (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
1533 	}
1534 }
1535 
1536 static void
print_indirect(blkptr_t * bp,const zbookmark_phys_t * zb,const dnode_phys_t * dnp)1537 print_indirect(blkptr_t *bp, const zbookmark_phys_t *zb,
1538     const dnode_phys_t *dnp)
1539 {
1540 	char blkbuf[BP_SPRINTF_LEN];
1541 	int l;
1542 
1543 	if (!BP_IS_EMBEDDED(bp)) {
1544 		ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
1545 		ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
1546 	}
1547 
1548 	(void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
1549 
1550 	ASSERT(zb->zb_level >= 0);
1551 
1552 	for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
1553 		if (l == zb->zb_level) {
1554 			(void) printf("L%llx", (u_longlong_t)zb->zb_level);
1555 		} else {
1556 			(void) printf(" ");
1557 		}
1558 	}
1559 
1560 	snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1561 	(void) printf("%s\n", blkbuf);
1562 }
1563 
1564 static int
visit_indirect(spa_t * spa,const dnode_phys_t * dnp,blkptr_t * bp,const zbookmark_phys_t * zb)1565 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
1566     blkptr_t *bp, const zbookmark_phys_t *zb)
1567 {
1568 	int err = 0;
1569 
1570 	if (bp->blk_birth == 0)
1571 		return (0);
1572 
1573 	print_indirect(bp, zb, dnp);
1574 
1575 	if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
1576 		arc_flags_t flags = ARC_FLAG_WAIT;
1577 		int i;
1578 		blkptr_t *cbp;
1579 		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1580 		arc_buf_t *buf;
1581 		uint64_t fill = 0;
1582 
1583 		err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
1584 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
1585 		if (err)
1586 			return (err);
1587 		ASSERT(buf->b_data);
1588 
1589 		/* recursively visit blocks below this */
1590 		cbp = buf->b_data;
1591 		for (i = 0; i < epb; i++, cbp++) {
1592 			zbookmark_phys_t czb;
1593 
1594 			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1595 			    zb->zb_level - 1,
1596 			    zb->zb_blkid * epb + i);
1597 			err = visit_indirect(spa, dnp, cbp, &czb);
1598 			if (err)
1599 				break;
1600 			fill += BP_GET_FILL(cbp);
1601 		}
1602 		if (!err)
1603 			ASSERT3U(fill, ==, BP_GET_FILL(bp));
1604 		arc_buf_destroy(buf, &buf);
1605 	}
1606 
1607 	return (err);
1608 }
1609 
1610 /*ARGSUSED*/
1611 static void
dump_indirect(dnode_t * dn)1612 dump_indirect(dnode_t *dn)
1613 {
1614 	dnode_phys_t *dnp = dn->dn_phys;
1615 	int j;
1616 	zbookmark_phys_t czb;
1617 
1618 	(void) printf("Indirect blocks:\n");
1619 
1620 	SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1621 	    dn->dn_object, dnp->dn_nlevels - 1, 0);
1622 	for (j = 0; j < dnp->dn_nblkptr; j++) {
1623 		czb.zb_blkid = j;
1624 		(void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1625 		    &dnp->dn_blkptr[j], &czb);
1626 	}
1627 
1628 	(void) printf("\n");
1629 }
1630 
1631 /*ARGSUSED*/
1632 static void
dump_dsl_dir(objset_t * os,uint64_t object,void * data,size_t size)1633 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1634 {
1635 	dsl_dir_phys_t *dd = data;
1636 	time_t crtime;
1637 	char nice[32];
1638 
1639 	/* make sure nicenum has enough space */
1640 	CTASSERT(sizeof (nice) >= NN_NUMBUF_SZ);
1641 
1642 	if (dd == NULL)
1643 		return;
1644 
1645 	ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1646 
1647 	crtime = dd->dd_creation_time;
1648 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1649 	(void) printf("\t\thead_dataset_obj = %llu\n",
1650 	    (u_longlong_t)dd->dd_head_dataset_obj);
1651 	(void) printf("\t\tparent_dir_obj = %llu\n",
1652 	    (u_longlong_t)dd->dd_parent_obj);
1653 	(void) printf("\t\torigin_obj = %llu\n",
1654 	    (u_longlong_t)dd->dd_origin_obj);
1655 	(void) printf("\t\tchild_dir_zapobj = %llu\n",
1656 	    (u_longlong_t)dd->dd_child_dir_zapobj);
1657 	zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
1658 	(void) printf("\t\tused_bytes = %s\n", nice);
1659 	zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
1660 	(void) printf("\t\tcompressed_bytes = %s\n", nice);
1661 	zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
1662 	(void) printf("\t\tuncompressed_bytes = %s\n", nice);
1663 	zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
1664 	(void) printf("\t\tquota = %s\n", nice);
1665 	zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
1666 	(void) printf("\t\treserved = %s\n", nice);
1667 	(void) printf("\t\tprops_zapobj = %llu\n",
1668 	    (u_longlong_t)dd->dd_props_zapobj);
1669 	(void) printf("\t\tdeleg_zapobj = %llu\n",
1670 	    (u_longlong_t)dd->dd_deleg_zapobj);
1671 	(void) printf("\t\tflags = %llx\n",
1672 	    (u_longlong_t)dd->dd_flags);
1673 
1674 #define	DO(which) \
1675 	zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
1676 	    sizeof (nice)); \
1677 	(void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1678 	DO(HEAD);
1679 	DO(SNAP);
1680 	DO(CHILD);
1681 	DO(CHILD_RSRV);
1682 	DO(REFRSRV);
1683 #undef DO
1684 	(void) printf("\t\tclones = %llu\n",
1685 	    (u_longlong_t)dd->dd_clones);
1686 }
1687 
1688 /*ARGSUSED*/
1689 static void
dump_dsl_dataset(objset_t * os,uint64_t object,void * data,size_t size)1690 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1691 {
1692 	dsl_dataset_phys_t *ds = data;
1693 	time_t crtime;
1694 	char used[32], compressed[32], uncompressed[32], unique[32];
1695 	char blkbuf[BP_SPRINTF_LEN];
1696 
1697 	/* make sure nicenum has enough space */
1698 	CTASSERT(sizeof (used) >= NN_NUMBUF_SZ);
1699 	CTASSERT(sizeof (compressed) >= NN_NUMBUF_SZ);
1700 	CTASSERT(sizeof (uncompressed) >= NN_NUMBUF_SZ);
1701 	CTASSERT(sizeof (unique) >= NN_NUMBUF_SZ);
1702 
1703 	if (ds == NULL)
1704 		return;
1705 
1706 	ASSERT(size == sizeof (*ds));
1707 	crtime = ds->ds_creation_time;
1708 	zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
1709 	zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
1710 	zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
1711 	    sizeof (uncompressed));
1712 	zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
1713 	snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
1714 
1715 	(void) printf("\t\tdir_obj = %llu\n",
1716 	    (u_longlong_t)ds->ds_dir_obj);
1717 	(void) printf("\t\tprev_snap_obj = %llu\n",
1718 	    (u_longlong_t)ds->ds_prev_snap_obj);
1719 	(void) printf("\t\tprev_snap_txg = %llu\n",
1720 	    (u_longlong_t)ds->ds_prev_snap_txg);
1721 	(void) printf("\t\tnext_snap_obj = %llu\n",
1722 	    (u_longlong_t)ds->ds_next_snap_obj);
1723 	(void) printf("\t\tsnapnames_zapobj = %llu\n",
1724 	    (u_longlong_t)ds->ds_snapnames_zapobj);
1725 	(void) printf("\t\tnum_children = %llu\n",
1726 	    (u_longlong_t)ds->ds_num_children);
1727 	(void) printf("\t\tuserrefs_obj = %llu\n",
1728 	    (u_longlong_t)ds->ds_userrefs_obj);
1729 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1730 	(void) printf("\t\tcreation_txg = %llu\n",
1731 	    (u_longlong_t)ds->ds_creation_txg);
1732 	(void) printf("\t\tdeadlist_obj = %llu\n",
1733 	    (u_longlong_t)ds->ds_deadlist_obj);
1734 	(void) printf("\t\tused_bytes = %s\n", used);
1735 	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
1736 	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1737 	(void) printf("\t\tunique = %s\n", unique);
1738 	(void) printf("\t\tfsid_guid = %llu\n",
1739 	    (u_longlong_t)ds->ds_fsid_guid);
1740 	(void) printf("\t\tguid = %llu\n",
1741 	    (u_longlong_t)ds->ds_guid);
1742 	(void) printf("\t\tflags = %llx\n",
1743 	    (u_longlong_t)ds->ds_flags);
1744 	(void) printf("\t\tnext_clones_obj = %llu\n",
1745 	    (u_longlong_t)ds->ds_next_clones_obj);
1746 	(void) printf("\t\tprops_obj = %llu\n",
1747 	    (u_longlong_t)ds->ds_props_obj);
1748 	(void) printf("\t\tbp = %s\n", blkbuf);
1749 }
1750 
1751 /* ARGSUSED */
1752 static int
dump_bptree_cb(void * arg,const blkptr_t * bp,dmu_tx_t * tx)1753 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1754 {
1755 	char blkbuf[BP_SPRINTF_LEN];
1756 
1757 	if (bp->blk_birth != 0) {
1758 		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
1759 		(void) printf("\t%s\n", blkbuf);
1760 	}
1761 	return (0);
1762 }
1763 
1764 static void
dump_bptree(objset_t * os,uint64_t obj,const char * name)1765 dump_bptree(objset_t *os, uint64_t obj, const char *name)
1766 {
1767 	char bytes[32];
1768 	bptree_phys_t *bt;
1769 	dmu_buf_t *db;
1770 
1771 	/* make sure nicenum has enough space */
1772 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1773 
1774 	if (dump_opt['d'] < 3)
1775 		return;
1776 
1777 	VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
1778 	bt = db->db_data;
1779 	zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
1780 	(void) printf("\n    %s: %llu datasets, %s\n",
1781 	    name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
1782 	dmu_buf_rele(db, FTAG);
1783 
1784 	if (dump_opt['d'] < 5)
1785 		return;
1786 
1787 	(void) printf("\n");
1788 
1789 	(void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
1790 }
1791 
1792 /* ARGSUSED */
1793 static int
dump_bpobj_cb(void * arg,const blkptr_t * bp,dmu_tx_t * tx)1794 dump_bpobj_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1795 {
1796 	char blkbuf[BP_SPRINTF_LEN];
1797 
1798 	ASSERT(bp->blk_birth != 0);
1799 	snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1800 	(void) printf("\t%s\n", blkbuf);
1801 	return (0);
1802 }
1803 
1804 static void
dump_full_bpobj(bpobj_t * bpo,const char * name,int indent)1805 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
1806 {
1807 	char bytes[32];
1808 	char comp[32];
1809 	char uncomp[32];
1810 
1811 	/* make sure nicenum has enough space */
1812 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1813 	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1814 	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1815 
1816 	if (dump_opt['d'] < 3)
1817 		return;
1818 
1819 	zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
1820 	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1821 		zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
1822 		zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
1823 		(void) printf("    %*s: object %llu, %llu local blkptrs, "
1824 		    "%llu subobjs in object %llu, %s (%s/%s comp)\n",
1825 		    indent * 8, name,
1826 		    (u_longlong_t)bpo->bpo_object,
1827 		    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1828 		    (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1829 		    (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
1830 		    bytes, comp, uncomp);
1831 
1832 		for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1833 			uint64_t subobj;
1834 			bpobj_t subbpo;
1835 			int error;
1836 			VERIFY0(dmu_read(bpo->bpo_os,
1837 			    bpo->bpo_phys->bpo_subobjs,
1838 			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1839 			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1840 			if (error != 0) {
1841 				(void) printf("ERROR %u while trying to open "
1842 				    "subobj id %llu\n",
1843 				    error, (u_longlong_t)subobj);
1844 				continue;
1845 			}
1846 			dump_full_bpobj(&subbpo, "subobj", indent + 1);
1847 			bpobj_close(&subbpo);
1848 		}
1849 	} else {
1850 		(void) printf("    %*s: object %llu, %llu blkptrs, %s\n",
1851 		    indent * 8, name,
1852 		    (u_longlong_t)bpo->bpo_object,
1853 		    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1854 		    bytes);
1855 	}
1856 
1857 	if (dump_opt['d'] < 5)
1858 		return;
1859 
1860 
1861 	if (indent == 0) {
1862 		(void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1863 		(void) printf("\n");
1864 	}
1865 }
1866 
1867 static void
bpobj_count_refd(bpobj_t * bpo)1868 bpobj_count_refd(bpobj_t *bpo)
1869 {
1870 	mos_obj_refd(bpo->bpo_object);
1871 
1872 	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1873 		mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
1874 		for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1875 			uint64_t subobj;
1876 			bpobj_t subbpo;
1877 			int error;
1878 			VERIFY0(dmu_read(bpo->bpo_os,
1879 			    bpo->bpo_phys->bpo_subobjs,
1880 			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1881 			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1882 			if (error != 0) {
1883 				(void) printf("ERROR %u while trying to open "
1884 				    "subobj id %llu\n",
1885 				    error, (u_longlong_t)subobj);
1886 				continue;
1887 			}
1888 			bpobj_count_refd(&subbpo);
1889 			bpobj_close(&subbpo);
1890 		}
1891 	}
1892 }
1893 
1894 static void
dump_deadlist(dsl_deadlist_t * dl)1895 dump_deadlist(dsl_deadlist_t *dl)
1896 {
1897 	dsl_deadlist_entry_t *dle;
1898 	uint64_t unused;
1899 	char bytes[32];
1900 	char comp[32];
1901 	char uncomp[32];
1902 	uint64_t empty_bpobj =
1903 	    dmu_objset_spa(dl->dl_os)->spa_dsl_pool->dp_empty_bpobj;
1904 
1905 	/* force the tree to be loaded */
1906 	dsl_deadlist_space_range(dl, 0, UINT64_MAX, &unused, &unused, &unused);
1907 
1908 	if (dl->dl_oldfmt) {
1909 		if (dl->dl_bpobj.bpo_object != empty_bpobj)
1910 			bpobj_count_refd(&dl->dl_bpobj);
1911 	} else {
1912 		mos_obj_refd(dl->dl_object);
1913 		for (dle = avl_first(&dl->dl_tree); dle;
1914 		    dle = AVL_NEXT(&dl->dl_tree, dle)) {
1915 			if (dle->dle_bpobj.bpo_object != empty_bpobj)
1916 				bpobj_count_refd(&dle->dle_bpobj);
1917 		}
1918 	}
1919 
1920 	/* make sure nicenum has enough space */
1921 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1922 	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1923 	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1924 
1925 	if (dump_opt['d'] < 3)
1926 		return;
1927 
1928 	if (dl->dl_oldfmt) {
1929 		dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
1930 		return;
1931 	}
1932 
1933 	zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
1934 	zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
1935 	zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
1936 	(void) printf("\n    Deadlist: %s (%s/%s comp)\n",
1937 	    bytes, comp, uncomp);
1938 
1939 	if (dump_opt['d'] < 4)
1940 		return;
1941 
1942 	(void) printf("\n");
1943 
1944 	for (dle = avl_first(&dl->dl_tree); dle;
1945 	    dle = AVL_NEXT(&dl->dl_tree, dle)) {
1946 		if (dump_opt['d'] >= 5) {
1947 			char buf[128];
1948 			(void) snprintf(buf, sizeof (buf),
1949 			    "mintxg %llu -> obj %llu",
1950 			    (longlong_t)dle->dle_mintxg,
1951 			    (longlong_t)dle->dle_bpobj.bpo_object);
1952 
1953 			dump_full_bpobj(&dle->dle_bpobj, buf, 0);
1954 		} else {
1955 			(void) printf("mintxg %llu -> obj %llu\n",
1956 			    (longlong_t)dle->dle_mintxg,
1957 			    (longlong_t)dle->dle_bpobj.bpo_object);
1958 		}
1959 	}
1960 }
1961 
1962 static avl_tree_t idx_tree;
1963 static avl_tree_t domain_tree;
1964 static boolean_t fuid_table_loaded;
1965 static objset_t *sa_os = NULL;
1966 static sa_attr_type_t *sa_attr_table = NULL;
1967 
1968 static int
open_objset(const char * path,dmu_objset_type_t type,void * tag,objset_t ** osp)1969 open_objset(const char *path, dmu_objset_type_t type, void *tag, objset_t **osp)
1970 {
1971 	int err;
1972 	uint64_t sa_attrs = 0;
1973 	uint64_t version = 0;
1974 
1975 	VERIFY3P(sa_os, ==, NULL);
1976 	err = dmu_objset_own(path, type, B_TRUE, B_FALSE, tag, osp);
1977 	if (err != 0) {
1978 		(void) fprintf(stderr, "failed to own dataset '%s': %s\n", path,
1979 		    strerror(err));
1980 		return (err);
1981 	}
1982 
1983 	if (dmu_objset_type(*osp) == DMU_OST_ZFS && !(*osp)->os_encrypted) {
1984 		(void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1985 		    8, 1, &version);
1986 		if (version >= ZPL_VERSION_SA) {
1987 			(void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1988 			    8, 1, &sa_attrs);
1989 		}
1990 		err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
1991 		    &sa_attr_table);
1992 		if (err != 0) {
1993 			(void) fprintf(stderr, "sa_setup failed: %s\n",
1994 			    strerror(err));
1995 			dmu_objset_disown(*osp, B_FALSE, tag);
1996 			*osp = NULL;
1997 		}
1998 	}
1999 	sa_os = *osp;
2000 
2001 	return (0);
2002 }
2003 
2004 static void
close_objset(objset_t * os,void * tag)2005 close_objset(objset_t *os, void *tag)
2006 {
2007 	VERIFY3P(os, ==, sa_os);
2008 	if (os->os_sa != NULL)
2009 		sa_tear_down(os);
2010 	dmu_objset_disown(os, B_FALSE, tag);
2011 	sa_attr_table = NULL;
2012 	sa_os = NULL;
2013 }
2014 
2015 static void
fuid_table_destroy()2016 fuid_table_destroy()
2017 {
2018 	if (fuid_table_loaded) {
2019 		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
2020 		fuid_table_loaded = B_FALSE;
2021 	}
2022 }
2023 
2024 /*
2025  * print uid or gid information.
2026  * For normal POSIX id just the id is printed in decimal format.
2027  * For CIFS files with FUID the fuid is printed in hex followed by
2028  * the domain-rid string.
2029  */
2030 static void
print_idstr(uint64_t id,const char * id_type)2031 print_idstr(uint64_t id, const char *id_type)
2032 {
2033 	if (FUID_INDEX(id)) {
2034 		char *domain;
2035 
2036 		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
2037 		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
2038 		    (u_longlong_t)id, domain, (int)FUID_RID(id));
2039 	} else {
2040 		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
2041 	}
2042 
2043 }
2044 
2045 static void
dump_uidgid(objset_t * os,uint64_t uid,uint64_t gid)2046 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
2047 {
2048 	uint32_t uid_idx, gid_idx;
2049 
2050 	uid_idx = FUID_INDEX(uid);
2051 	gid_idx = FUID_INDEX(gid);
2052 
2053 	/* Load domain table, if not already loaded */
2054 	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
2055 		uint64_t fuid_obj;
2056 
2057 		/* first find the fuid object.  It lives in the master node */
2058 		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
2059 		    8, 1, &fuid_obj) == 0);
2060 		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
2061 		(void) zfs_fuid_table_load(os, fuid_obj,
2062 		    &idx_tree, &domain_tree);
2063 		fuid_table_loaded = B_TRUE;
2064 	}
2065 
2066 	print_idstr(uid, "uid");
2067 	print_idstr(gid, "gid");
2068 }
2069 
2070 /*ARGSUSED*/
2071 static void
dump_znode(objset_t * os,uint64_t object,void * data,size_t size)2072 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
2073 {
2074 	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
2075 	sa_handle_t *hdl;
2076 	uint64_t xattr, rdev, gen;
2077 	uint64_t uid, gid, mode, fsize, parent, links;
2078 	uint64_t pflags;
2079 	uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
2080 	time_t z_crtime, z_atime, z_mtime, z_ctime;
2081 	sa_bulk_attr_t bulk[12];
2082 	int idx = 0;
2083 	int error;
2084 
2085 	VERIFY3P(os, ==, sa_os);
2086 	if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
2087 		(void) printf("Failed to get handle for SA znode\n");
2088 		return;
2089 	}
2090 
2091 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
2092 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
2093 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
2094 	    &links, 8);
2095 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
2096 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
2097 	    &mode, 8);
2098 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
2099 	    NULL, &parent, 8);
2100 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
2101 	    &fsize, 8);
2102 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
2103 	    acctm, 16);
2104 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
2105 	    modtm, 16);
2106 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
2107 	    crtm, 16);
2108 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
2109 	    chgtm, 16);
2110 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
2111 	    &pflags, 8);
2112 
2113 	if (sa_bulk_lookup(hdl, bulk, idx)) {
2114 		(void) sa_handle_destroy(hdl);
2115 		return;
2116 	}
2117 
2118 	z_crtime = (time_t)crtm[0];
2119 	z_atime = (time_t)acctm[0];
2120 	z_mtime = (time_t)modtm[0];
2121 	z_ctime = (time_t)chgtm[0];
2122 
2123 	if (dump_opt['d'] > 4) {
2124 		error = zfs_obj_to_path(os, object, path, sizeof (path));
2125 		if (error == ESTALE) {
2126 			(void) snprintf(path, sizeof (path), "on delete queue");
2127 		} else if (error != 0) {
2128 			leaked_objects++;
2129 			(void) snprintf(path, sizeof (path),
2130 			    "path not found, possibly leaked");
2131 		}
2132 		(void) printf("\tpath	%s\n", path);
2133 	}
2134 	dump_uidgid(os, uid, gid);
2135 	(void) printf("\tatime	%s", ctime(&z_atime));
2136 	(void) printf("\tmtime	%s", ctime(&z_mtime));
2137 	(void) printf("\tctime	%s", ctime(&z_ctime));
2138 	(void) printf("\tcrtime	%s", ctime(&z_crtime));
2139 	(void) printf("\tgen	%llu\n", (u_longlong_t)gen);
2140 	(void) printf("\tmode	%llo\n", (u_longlong_t)mode);
2141 	(void) printf("\tsize	%llu\n", (u_longlong_t)fsize);
2142 	(void) printf("\tparent	%llu\n", (u_longlong_t)parent);
2143 	(void) printf("\tlinks	%llu\n", (u_longlong_t)links);
2144 	(void) printf("\tpflags	%llx\n", (u_longlong_t)pflags);
2145 	if (dmu_objset_projectquota_enabled(os) && (pflags & ZFS_PROJID)) {
2146 		uint64_t projid;
2147 
2148 		if (sa_lookup(hdl, sa_attr_table[ZPL_PROJID], &projid,
2149 		    sizeof (uint64_t)) == 0)
2150 			(void) printf("\tprojid	%llu\n", (u_longlong_t)projid);
2151 	}
2152 	if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
2153 	    sizeof (uint64_t)) == 0)
2154 		(void) printf("\txattr	%llu\n", (u_longlong_t)xattr);
2155 	if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
2156 	    sizeof (uint64_t)) == 0)
2157 		(void) printf("\trdev	0x%016llx\n", (u_longlong_t)rdev);
2158 	sa_handle_destroy(hdl);
2159 }
2160 
2161 /*ARGSUSED*/
2162 static void
dump_acl(objset_t * os,uint64_t object,void * data,size_t size)2163 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
2164 {
2165 }
2166 
2167 /*ARGSUSED*/
2168 static void
dump_dmu_objset(objset_t * os,uint64_t object,void * data,size_t size)2169 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
2170 {
2171 }
2172 
2173 
2174 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
2175 	dump_none,		/* unallocated			*/
2176 	dump_zap,		/* object directory		*/
2177 	dump_uint64,		/* object array			*/
2178 	dump_none,		/* packed nvlist		*/
2179 	dump_packed_nvlist,	/* packed nvlist size		*/
2180 	dump_none,		/* bpobj			*/
2181 	dump_bpobj,		/* bpobj header			*/
2182 	dump_none,		/* SPA space map header		*/
2183 	dump_none,		/* SPA space map		*/
2184 	dump_none,		/* ZIL intent log		*/
2185 	dump_dnode,		/* DMU dnode			*/
2186 	dump_dmu_objset,	/* DMU objset			*/
2187 	dump_dsl_dir,		/* DSL directory		*/
2188 	dump_zap,		/* DSL directory child map	*/
2189 	dump_zap,		/* DSL dataset snap map		*/
2190 	dump_zap,		/* DSL props			*/
2191 	dump_dsl_dataset,	/* DSL dataset			*/
2192 	dump_znode,		/* ZFS znode			*/
2193 	dump_acl,		/* ZFS V0 ACL			*/
2194 	dump_uint8,		/* ZFS plain file		*/
2195 	dump_zpldir,		/* ZFS directory		*/
2196 	dump_zap,		/* ZFS master node		*/
2197 	dump_zap,		/* ZFS delete queue		*/
2198 	dump_uint8,		/* zvol object			*/
2199 	dump_zap,		/* zvol prop			*/
2200 	dump_uint8,		/* other uint8[]		*/
2201 	dump_uint64,		/* other uint64[]		*/
2202 	dump_zap,		/* other ZAP			*/
2203 	dump_zap,		/* persistent error log		*/
2204 	dump_uint8,		/* SPA history			*/
2205 	dump_history_offsets,	/* SPA history offsets		*/
2206 	dump_zap,		/* Pool properties		*/
2207 	dump_zap,		/* DSL permissions		*/
2208 	dump_acl,		/* ZFS ACL			*/
2209 	dump_uint8,		/* ZFS SYSACL			*/
2210 	dump_none,		/* FUID nvlist			*/
2211 	dump_packed_nvlist,	/* FUID nvlist size		*/
2212 	dump_zap,		/* DSL dataset next clones	*/
2213 	dump_zap,		/* DSL scrub queue		*/
2214 	dump_zap,		/* ZFS user/group/project used	*/
2215 	dump_zap,		/* ZFS user/group/project quota	*/
2216 	dump_zap,		/* snapshot refcount tags	*/
2217 	dump_ddt_zap,		/* DDT ZAP object		*/
2218 	dump_zap,		/* DDT statistics		*/
2219 	dump_znode,		/* SA object			*/
2220 	dump_zap,		/* SA Master Node		*/
2221 	dump_sa_attrs,		/* SA attribute registration	*/
2222 	dump_sa_layouts,	/* SA attribute layouts		*/
2223 	dump_zap,		/* DSL scrub translations	*/
2224 	dump_none,		/* fake dedup BP		*/
2225 	dump_zap,		/* deadlist			*/
2226 	dump_none,		/* deadlist hdr			*/
2227 	dump_zap,		/* dsl clones			*/
2228 	dump_bpobj_subobjs,	/* bpobj subobjs		*/
2229 	dump_unknown,		/* Unknown type, must be last	*/
2230 };
2231 
2232 static void
dump_object(objset_t * os,uint64_t object,int verbosity,int * print_header,uint64_t * dnode_slots_used)2233 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header,
2234     uint64_t *dnode_slots_used)
2235 {
2236 	dmu_buf_t *db = NULL;
2237 	dmu_object_info_t doi;
2238 	dnode_t *dn;
2239 	boolean_t dnode_held = B_FALSE;
2240 	void *bonus = NULL;
2241 	size_t bsize = 0;
2242 	char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
2243 	char bonus_size[32];
2244 	char aux[50];
2245 	int error;
2246 
2247 	/* make sure nicenum has enough space */
2248 	CTASSERT(sizeof (iblk) >= NN_NUMBUF_SZ);
2249 	CTASSERT(sizeof (dblk) >= NN_NUMBUF_SZ);
2250 	CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
2251 	CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
2252 	CTASSERT(sizeof (bonus_size) >= NN_NUMBUF_SZ);
2253 
2254 	if (*print_header) {
2255 		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %6s  %5s  %6s  %s\n",
2256 		    "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
2257 		    "lsize", "%full", "type");
2258 		*print_header = 0;
2259 	}
2260 
2261 	if (object == 0) {
2262 		dn = DMU_META_DNODE(os);
2263 		dmu_object_info_from_dnode(dn, &doi);
2264 	} else {
2265 		/*
2266 		 * Encrypted datasets will have sensitive bonus buffers
2267 		 * encrypted. Therefore we cannot hold the bonus buffer and
2268 		 * must hold the dnode itself instead.
2269 		 */
2270 		error = dmu_object_info(os, object, &doi);
2271 		if (error)
2272 			fatal("dmu_object_info() failed, errno %u", error);
2273 
2274 		if (os->os_encrypted &&
2275 		    DMU_OT_IS_ENCRYPTED(doi.doi_bonus_type)) {
2276 			error = dnode_hold(os, object, FTAG, &dn);
2277 			if (error)
2278 				fatal("dnode_hold() failed, errno %u", error);
2279 			dnode_held = B_TRUE;
2280 		} else {
2281 			error = dmu_bonus_hold(os, object, FTAG, &db);
2282 			if (error)
2283 				fatal("dmu_bonus_hold(%llu) failed, errno %u",
2284 				    object, error);
2285 			bonus = db->db_data;
2286 			bsize = db->db_size;
2287 			dn = DB_DNODE((dmu_buf_impl_t *)db);
2288 		}
2289 	}
2290 
2291 	if (dnode_slots_used != NULL)
2292 		*dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
2293 
2294 	zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
2295 	zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
2296 	zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
2297 	zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
2298 	zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
2299 	zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
2300 	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
2301 	    doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
2302 	    doi.doi_max_offset);
2303 
2304 	aux[0] = '\0';
2305 
2306 	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
2307 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
2308 		    ZDB_CHECKSUM_NAME(doi.doi_checksum));
2309 	}
2310 
2311 	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
2312 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
2313 		    ZDB_COMPRESS_NAME(doi.doi_compress));
2314 	}
2315 
2316 	(void) printf("%10" PRIu64
2317 	    "  %3u  %5s  %5s  %5s  %5s  %5s  %6s  %s%s\n",
2318 	    object, doi.doi_indirection, iblk, dblk,
2319 	    asize, dnsize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
2320 
2321 	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
2322 		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %5s  %6s  %s\n",
2323 		    "", "", "", "", "", "", bonus_size, "bonus",
2324 		    ZDB_OT_NAME(doi.doi_bonus_type));
2325 	}
2326 
2327 	if (verbosity >= 4) {
2328 		(void) printf("\tdnode flags: %s%s%s%s\n",
2329 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
2330 		    "USED_BYTES " : "",
2331 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
2332 		    "USERUSED_ACCOUNTED " : "",
2333 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) ?
2334 		    "USEROBJUSED_ACCOUNTED " : "",
2335 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
2336 		    "SPILL_BLKPTR" : "");
2337 		(void) printf("\tdnode maxblkid: %llu\n",
2338 		    (longlong_t)dn->dn_phys->dn_maxblkid);
2339 
2340 		if (!dnode_held) {
2341 			object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os,
2342 			    object, bonus, bsize);
2343 		} else {
2344 			(void) printf("\t\t(bonus encrypted)\n");
2345 		}
2346 
2347 		if (!os->os_encrypted || !DMU_OT_IS_ENCRYPTED(doi.doi_type)) {
2348 			object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object,
2349 			    NULL, 0);
2350 		} else {
2351 			(void) printf("\t\t(object encrypted)\n");
2352 		}
2353 
2354 		*print_header = 1;
2355 	}
2356 
2357 	if (verbosity >= 5)
2358 		dump_indirect(dn);
2359 
2360 	if (verbosity >= 5) {
2361 		/*
2362 		 * Report the list of segments that comprise the object.
2363 		 */
2364 		uint64_t start = 0;
2365 		uint64_t end;
2366 		uint64_t blkfill = 1;
2367 		int minlvl = 1;
2368 
2369 		if (dn->dn_type == DMU_OT_DNODE) {
2370 			minlvl = 0;
2371 			blkfill = DNODES_PER_BLOCK;
2372 		}
2373 
2374 		for (;;) {
2375 			char segsize[32];
2376 			/* make sure nicenum has enough space */
2377 			CTASSERT(sizeof (segsize) >= NN_NUMBUF_SZ);
2378 			error = dnode_next_offset(dn,
2379 			    0, &start, minlvl, blkfill, 0);
2380 			if (error)
2381 				break;
2382 			end = start;
2383 			error = dnode_next_offset(dn,
2384 			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
2385 			zdb_nicenum(end - start, segsize, sizeof (segsize));
2386 			(void) printf("\t\tsegment [%016llx, %016llx)"
2387 			    " size %5s\n", (u_longlong_t)start,
2388 			    (u_longlong_t)end, segsize);
2389 			if (error)
2390 				break;
2391 			start = end;
2392 		}
2393 	}
2394 
2395 	if (db != NULL)
2396 		dmu_buf_rele(db, FTAG);
2397 	if (dnode_held)
2398 		dnode_rele(dn, FTAG);
2399 }
2400 
2401 static void
count_dir_mos_objects(dsl_dir_t * dd)2402 count_dir_mos_objects(dsl_dir_t *dd)
2403 {
2404 	mos_obj_refd(dd->dd_object);
2405 	mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
2406 	mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
2407 	mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
2408 	mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
2409 }
2410 
2411 static void
count_ds_mos_objects(dsl_dataset_t * ds)2412 count_ds_mos_objects(dsl_dataset_t *ds)
2413 {
2414 	mos_obj_refd(ds->ds_object);
2415 	mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
2416 	mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
2417 	mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
2418 	mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
2419 
2420 	if (!dsl_dataset_is_snapshot(ds)) {
2421 		count_dir_mos_objects(ds->ds_dir);
2422 	}
2423 }
2424 
2425 static const char *objset_types[DMU_OST_NUMTYPES] = {
2426 	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
2427 
2428 static void
dump_dir(objset_t * os)2429 dump_dir(objset_t *os)
2430 {
2431 	dmu_objset_stats_t dds;
2432 	uint64_t object, object_count;
2433 	uint64_t refdbytes, usedobjs, scratch;
2434 	char numbuf[32];
2435 	char blkbuf[BP_SPRINTF_LEN + 20];
2436 	char osname[ZFS_MAX_DATASET_NAME_LEN];
2437 	const char *type = "UNKNOWN";
2438 	int verbosity = dump_opt['d'];
2439 	int print_header = 1;
2440 	unsigned i;
2441 	int error;
2442 	uint64_t total_slots_used = 0;
2443 	uint64_t max_slot_used = 0;
2444 	uint64_t dnode_slots;
2445 
2446 	/* make sure nicenum has enough space */
2447 	CTASSERT(sizeof (numbuf) >= NN_NUMBUF_SZ);
2448 
2449 	dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2450 	dmu_objset_fast_stat(os, &dds);
2451 	dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2452 
2453 	if (dds.dds_type < DMU_OST_NUMTYPES)
2454 		type = objset_types[dds.dds_type];
2455 
2456 	if (dds.dds_type == DMU_OST_META) {
2457 		dds.dds_creation_txg = TXG_INITIAL;
2458 		usedobjs = BP_GET_FILL(os->os_rootbp);
2459 		refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
2460 		    dd_used_bytes;
2461 	} else {
2462 		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
2463 	}
2464 
2465 	ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
2466 
2467 	zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
2468 
2469 	if (verbosity >= 4) {
2470 		(void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
2471 		(void) snprintf_blkptr(blkbuf + strlen(blkbuf),
2472 		    sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
2473 	} else {
2474 		blkbuf[0] = '\0';
2475 	}
2476 
2477 	dmu_objset_name(os, osname);
2478 
2479 	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
2480 	    "%s, %llu objects%s%s\n",
2481 	    osname, type, (u_longlong_t)dmu_objset_id(os),
2482 	    (u_longlong_t)dds.dds_creation_txg,
2483 	    numbuf, (u_longlong_t)usedobjs, blkbuf,
2484 	    (dds.dds_inconsistent) ? " (inconsistent)" : "");
2485 
2486 	if (zopt_objects != 0) {
2487 		for (i = 0; i < zopt_objects; i++)
2488 			dump_object(os, zopt_object[i], verbosity,
2489 			    &print_header, NULL);
2490 		(void) printf("\n");
2491 		return;
2492 	}
2493 
2494 	if (dump_opt['i'] != 0 || verbosity >= 2)
2495 		dump_intent_log(dmu_objset_zil(os));
2496 
2497 	if (dmu_objset_ds(os) != NULL) {
2498 		dsl_dataset_t *ds = dmu_objset_ds(os);
2499 		dump_deadlist(&ds->ds_deadlist);
2500 
2501 		if (dsl_dataset_remap_deadlist_exists(ds)) {
2502 			(void) printf("ds_remap_deadlist:\n");
2503 			dump_deadlist(&ds->ds_remap_deadlist);
2504 		}
2505 		count_ds_mos_objects(ds);
2506 	}
2507 
2508 	if (verbosity < 2)
2509 		return;
2510 
2511 	if (BP_IS_HOLE(os->os_rootbp))
2512 		return;
2513 
2514 	dump_object(os, 0, verbosity, &print_header, NULL);
2515 	object_count = 0;
2516 	if (DMU_USERUSED_DNODE(os) != NULL &&
2517 	    DMU_USERUSED_DNODE(os)->dn_type != 0) {
2518 		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
2519 		    NULL);
2520 		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
2521 		    NULL);
2522 	}
2523 
2524 	if (DMU_PROJECTUSED_DNODE(os) != NULL &&
2525 	    DMU_PROJECTUSED_DNODE(os)->dn_type != 0)
2526 		dump_object(os, DMU_PROJECTUSED_OBJECT, verbosity,
2527 		    &print_header, NULL);
2528 
2529 	object = 0;
2530 	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
2531 		dump_object(os, object, verbosity, &print_header, &dnode_slots);
2532 		object_count++;
2533 		total_slots_used += dnode_slots;
2534 		max_slot_used = object + dnode_slots - 1;
2535 	}
2536 
2537 	(void) printf("\n");
2538 
2539 	(void) printf("    Dnode slots:\n");
2540 	(void) printf("\tTotal used:    %10llu\n",
2541 	    (u_longlong_t)total_slots_used);
2542 	(void) printf("\tMax used:      %10llu\n",
2543 	    (u_longlong_t)max_slot_used);
2544 	(void) printf("\tPercent empty: %10lf\n",
2545 	    (double)(max_slot_used - total_slots_used)*100 /
2546 	    (double)max_slot_used);
2547 
2548 	(void) printf("\n");
2549 
2550 	if (error != ESRCH) {
2551 		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
2552 		abort();
2553 	}
2554 	if (leaked_objects != 0) {
2555 		(void) printf("%d potentially leaked objects detected\n",
2556 		    leaked_objects);
2557 		leaked_objects = 0;
2558 	}
2559 
2560 	ASSERT3U(object_count, ==, usedobjs);
2561 }
2562 
2563 static void
dump_uberblock(uberblock_t * ub,const char * header,const char * footer)2564 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
2565 {
2566 	time_t timestamp = ub->ub_timestamp;
2567 
2568 	(void) printf("%s", header ? header : "");
2569 	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
2570 	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
2571 	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
2572 	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
2573 	(void) printf("\ttimestamp = %llu UTC = %s",
2574 	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
2575 
2576 	(void) printf("\tmmp_magic = %016llx\n",
2577 	    (u_longlong_t)ub->ub_mmp_magic);
2578 	if (MMP_VALID(ub)) {
2579 		(void) printf("\tmmp_delay = %0llu\n",
2580 		    (u_longlong_t)ub->ub_mmp_delay);
2581 		if (MMP_SEQ_VALID(ub))
2582 			(void) printf("\tmmp_seq = %u\n",
2583 			    (unsigned int) MMP_SEQ(ub));
2584 		if (MMP_FAIL_INT_VALID(ub))
2585 			(void) printf("\tmmp_fail = %u\n",
2586 			    (unsigned int) MMP_FAIL_INT(ub));
2587 		if (MMP_INTERVAL_VALID(ub))
2588 			(void) printf("\tmmp_write = %u\n",
2589 			    (unsigned int) MMP_INTERVAL(ub));
2590 		/* After MMP_* to make summarize_uberblock_mmp cleaner */
2591 		(void) printf("\tmmp_valid = %x\n",
2592 		    (unsigned int) ub->ub_mmp_config & 0xFF);
2593 	}
2594 
2595 	if (dump_opt['u'] >= 4) {
2596 		char blkbuf[BP_SPRINTF_LEN];
2597 		snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
2598 		(void) printf("\trootbp = %s\n", blkbuf);
2599 	}
2600 	(void) printf("\tcheckpoint_txg = %llu\n",
2601 	    (u_longlong_t)ub->ub_checkpoint_txg);
2602 	(void) printf("%s", footer ? footer : "");
2603 }
2604 
2605 static void
dump_config(spa_t * spa)2606 dump_config(spa_t *spa)
2607 {
2608 	dmu_buf_t *db;
2609 	size_t nvsize = 0;
2610 	int error = 0;
2611 
2612 
2613 	error = dmu_bonus_hold(spa->spa_meta_objset,
2614 	    spa->spa_config_object, FTAG, &db);
2615 
2616 	if (error == 0) {
2617 		nvsize = *(uint64_t *)db->db_data;
2618 		dmu_buf_rele(db, FTAG);
2619 
2620 		(void) printf("\nMOS Configuration:\n");
2621 		dump_packed_nvlist(spa->spa_meta_objset,
2622 		    spa->spa_config_object, (void *)&nvsize, 1);
2623 	} else {
2624 		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
2625 		    (u_longlong_t)spa->spa_config_object, error);
2626 	}
2627 }
2628 
2629 static void
dump_cachefile(const char * cachefile)2630 dump_cachefile(const char *cachefile)
2631 {
2632 	int fd;
2633 	struct stat64 statbuf;
2634 	char *buf;
2635 	nvlist_t *config;
2636 
2637 	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
2638 		(void) printf("cannot open '%s': %s\n", cachefile,
2639 		    strerror(errno));
2640 		exit(1);
2641 	}
2642 
2643 	if (fstat64(fd, &statbuf) != 0) {
2644 		(void) printf("failed to stat '%s': %s\n", cachefile,
2645 		    strerror(errno));
2646 		exit(1);
2647 	}
2648 
2649 	if ((buf = malloc(statbuf.st_size)) == NULL) {
2650 		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
2651 		    (u_longlong_t)statbuf.st_size);
2652 		exit(1);
2653 	}
2654 
2655 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
2656 		(void) fprintf(stderr, "failed to read %llu bytes\n",
2657 		    (u_longlong_t)statbuf.st_size);
2658 		exit(1);
2659 	}
2660 
2661 	(void) close(fd);
2662 
2663 	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
2664 		(void) fprintf(stderr, "failed to unpack nvlist\n");
2665 		exit(1);
2666 	}
2667 
2668 	free(buf);
2669 
2670 	dump_nvlist(config, 0);
2671 
2672 	nvlist_free(config);
2673 }
2674 
2675 static void
print_l2arc_header(void)2676 print_l2arc_header(void)
2677 {
2678 	(void) printf("------------------------------------\n");
2679 	(void) printf("L2ARC device header\n");
2680 	(void) printf("------------------------------------\n");
2681 }
2682 
2683 static void
print_l2arc_log_blocks(void)2684 print_l2arc_log_blocks(void)
2685 {
2686 	(void) printf("------------------------------------\n");
2687 	(void) printf("L2ARC device log blocks\n");
2688 	(void) printf("------------------------------------\n");
2689 }
2690 
2691 static void
dump_l2arc_log_entries(uint64_t log_entries,l2arc_log_ent_phys_t * le,uint64_t i)2692 dump_l2arc_log_entries(uint64_t log_entries,
2693     l2arc_log_ent_phys_t *le, uint64_t i)
2694 {
2695 	for (uint64_t j = 0; j < log_entries; j++) {
2696 		dva_t dva = le[j].le_dva;
2697 		(void) printf("lb[%4llu]\tle[%4d]\tDVA asize: %llu, "
2698 		    "vdev: %llu, offset: %llu\n",
2699 		    (u_longlong_t)i, j + 1,
2700 		    (u_longlong_t)DVA_GET_ASIZE(&dva),
2701 		    (u_longlong_t)DVA_GET_VDEV(&dva),
2702 		    (u_longlong_t)DVA_GET_OFFSET(&dva));
2703 		(void) printf("|\t\t\t\tbirth: %llu\n",
2704 		    (u_longlong_t)le[j].le_birth);
2705 		(void) printf("|\t\t\t\tlsize: %llu\n",
2706 		    (u_longlong_t)L2BLK_GET_LSIZE((&le[j])->le_prop));
2707 		(void) printf("|\t\t\t\tpsize: %llu\n",
2708 		    (u_longlong_t)L2BLK_GET_PSIZE((&le[j])->le_prop));
2709 		(void) printf("|\t\t\t\tcompr: %llu\n",
2710 		    (u_longlong_t)L2BLK_GET_COMPRESS((&le[j])->le_prop));
2711 		(void) printf("|\t\t\t\ttype: %llu\n",
2712 		    (u_longlong_t)L2BLK_GET_TYPE((&le[j])->le_prop));
2713 		(void) printf("|\t\t\t\tprotected: %llu\n",
2714 		    (u_longlong_t)L2BLK_GET_PROTECTED((&le[j])->le_prop));
2715 		(void) printf("|\t\t\t\tprefetch: %llu\n",
2716 		    (u_longlong_t)L2BLK_GET_PREFETCH((&le[j])->le_prop));
2717 		(void) printf("|\t\t\t\taddress: %llu\n",
2718 		    (u_longlong_t)le[j].le_daddr);
2719 		(void) printf("|\t\t\t\tARC state: %llu\n",
2720 		    (u_longlong_t)L2BLK_GET_STATE((&le[j])->le_prop));
2721 		(void) printf("|\n");
2722 	}
2723 	(void) printf("\n");
2724 }
2725 
2726 static void
dump_l2arc_log_blkptr(l2arc_log_blkptr_t lbps)2727 dump_l2arc_log_blkptr(l2arc_log_blkptr_t lbps)
2728 {
2729 	(void) printf("|\t\tdaddr: %llu\n", (u_longlong_t)lbps.lbp_daddr);
2730 	(void) printf("|\t\tpayload_asize: %llu\n",
2731 	    (u_longlong_t)lbps.lbp_payload_asize);
2732 	(void) printf("|\t\tpayload_start: %llu\n",
2733 	    (u_longlong_t)lbps.lbp_payload_start);
2734 	(void) printf("|\t\tlsize: %llu\n",
2735 	    (u_longlong_t)L2BLK_GET_LSIZE((&lbps)->lbp_prop));
2736 	(void) printf("|\t\tasize: %llu\n",
2737 	    (u_longlong_t)L2BLK_GET_PSIZE((&lbps)->lbp_prop));
2738 	(void) printf("|\t\tcompralgo: %llu\n",
2739 	    (u_longlong_t)L2BLK_GET_COMPRESS((&lbps)->lbp_prop));
2740 	(void) printf("|\t\tcksumalgo: %llu\n",
2741 	    (u_longlong_t)L2BLK_GET_CHECKSUM((&lbps)->lbp_prop));
2742 	(void) printf("|\n\n");
2743 }
2744 
2745 static void
dump_l2arc_log_blocks(int fd,l2arc_dev_hdr_phys_t l2dhdr,l2arc_dev_hdr_phys_t * rebuild)2746 dump_l2arc_log_blocks(int fd, l2arc_dev_hdr_phys_t l2dhdr,
2747     l2arc_dev_hdr_phys_t *rebuild)
2748 {
2749 	l2arc_log_blk_phys_t this_lb;
2750 	uint64_t asize;
2751 	l2arc_log_blkptr_t lbps[2];
2752 	abd_t *abd;
2753 	zio_cksum_t cksum;
2754 	int failed = 0;
2755 	l2arc_dev_t dev;
2756 
2757 	if (!dump_opt['q'])
2758 		print_l2arc_log_blocks();
2759 	bcopy((&l2dhdr)->dh_start_lbps, lbps, sizeof (lbps));
2760 
2761 	dev.l2ad_evict = l2dhdr.dh_evict;
2762 	dev.l2ad_start = l2dhdr.dh_start;
2763 	dev.l2ad_end = l2dhdr.dh_end;
2764 
2765 	if (l2dhdr.dh_start_lbps[0].lbp_daddr == 0) {
2766 		/* no log blocks to read */
2767 		if (!dump_opt['q']) {
2768 			(void) printf("No log blocks to read\n");
2769 			(void) printf("\n");
2770 		}
2771 		return;
2772 	} else {
2773 		dev.l2ad_hand = lbps[0].lbp_daddr +
2774 		    L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
2775 	}
2776 
2777 	dev.l2ad_first = !!(l2dhdr.dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
2778 
2779 	for (;;) {
2780 		if (!l2arc_log_blkptr_valid(&dev, &lbps[0]))
2781 			break;
2782 
2783 		/* L2BLK_GET_PSIZE returns aligned size for log blocks */
2784 		asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
2785 		if (pread64(fd, &this_lb, asize, lbps[0].lbp_daddr) !=
2786 		    (ssize_t)asize) {
2787 			if (!dump_opt['q']) {
2788 				(void) printf("Error while reading next log "
2789 				    "block\n\n");
2790 			}
2791 			break;
2792 		}
2793 
2794 		fletcher_4_native(&this_lb, asize, NULL, &cksum);
2795 		if (!ZIO_CHECKSUM_EQUAL(cksum, lbps[0].lbp_cksum)) {
2796 			failed++;
2797 			if (!dump_opt['q']) {
2798 				(void) printf("Invalid cksum\n");
2799 				dump_l2arc_log_blkptr(lbps[0]);
2800 			}
2801 			break;
2802 		}
2803 
2804 		switch (L2BLK_GET_COMPRESS((&lbps[0])->lbp_prop)) {
2805 		case ZIO_COMPRESS_OFF:
2806 			break;
2807 		case ZIO_COMPRESS_LZ4:
2808 			abd = abd_alloc_for_io(asize, B_TRUE);
2809 			abd_copy_from_buf_off(abd, &this_lb, 0, asize);
2810 			zio_decompress_data(L2BLK_GET_COMPRESS(
2811 			    (&lbps[0])->lbp_prop), abd, &this_lb,
2812 			    asize, sizeof (this_lb));
2813 			abd_free(abd);
2814 			break;
2815 		default:
2816 			break;
2817 		}
2818 
2819 		if (this_lb.lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
2820 			byteswap_uint64_array(&this_lb, sizeof (this_lb));
2821 		if (this_lb.lb_magic != L2ARC_LOG_BLK_MAGIC) {
2822 			if (!dump_opt['q'])
2823 				(void) printf("Invalid log block magic\n\n");
2824 			break;
2825 		}
2826 
2827 		rebuild->dh_lb_count++;
2828 		rebuild->dh_lb_asize += asize;
2829 		if (dump_opt['l'] > 1 && !dump_opt['q']) {
2830 			(void) printf("lb[%4llu]\tmagic: %llu\n",
2831 			    (u_longlong_t)rebuild->dh_lb_count,
2832 			    (u_longlong_t)this_lb.lb_magic);
2833 			dump_l2arc_log_blkptr(lbps[0]);
2834 		}
2835 
2836 		if (dump_opt['l'] > 2 && !dump_opt['q'])
2837 			dump_l2arc_log_entries(l2dhdr.dh_log_entries,
2838 			    this_lb.lb_entries,
2839 			    rebuild->dh_lb_count);
2840 
2841 		if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
2842 		    lbps[0].lbp_payload_start, dev.l2ad_evict) &&
2843 		    !dev.l2ad_first)
2844 			break;
2845 
2846 		lbps[0] = lbps[1];
2847 		lbps[1] = this_lb.lb_prev_lbp;
2848 	}
2849 
2850 	if (!dump_opt['q']) {
2851 		(void) printf("log_blk_count:\t %llu with valid cksum\n",
2852 		    (u_longlong_t)rebuild->dh_lb_count);
2853 		(void) printf("\t\t %d with invalid cksum\n", failed);
2854 		(void) printf("log_blk_asize:\t %llu\n\n",
2855 		    (u_longlong_t)rebuild->dh_lb_asize);
2856 	}
2857 }
2858 
2859 static int
dump_l2arc_header(int fd)2860 dump_l2arc_header(int fd)
2861 {
2862 	l2arc_dev_hdr_phys_t l2dhdr, rebuild;
2863 	int error = B_FALSE;
2864 
2865 	bzero(&l2dhdr, sizeof (l2dhdr));
2866 	bzero(&rebuild, sizeof (rebuild));
2867 
2868 	if (pread64(fd, &l2dhdr, sizeof (l2dhdr),
2869 	    VDEV_LABEL_START_SIZE) != sizeof (l2dhdr)) {
2870 		error = B_TRUE;
2871 	} else {
2872 		if (l2dhdr.dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
2873 			byteswap_uint64_array(&l2dhdr, sizeof (l2dhdr));
2874 
2875 		if (l2dhdr.dh_magic != L2ARC_DEV_HDR_MAGIC)
2876 			error = B_TRUE;
2877 	}
2878 
2879 	if (error) {
2880 		(void) printf("L2ARC device header not found\n\n");
2881 		/* Do not return an error here for backward compatibility */
2882 		return (0);
2883 	} else if (!dump_opt['q']) {
2884 		print_l2arc_header();
2885 
2886 		(void) printf("    magic: %llu\n",
2887 		    (u_longlong_t)l2dhdr.dh_magic);
2888 		(void) printf("    version: %llu\n",
2889 		    (u_longlong_t)l2dhdr.dh_version);
2890 		(void) printf("    pool_guid: %llu\n",
2891 		    (u_longlong_t)l2dhdr.dh_spa_guid);
2892 		(void) printf("    flags: %llu\n",
2893 		    (u_longlong_t)l2dhdr.dh_flags);
2894 		(void) printf("    start_lbps[0]: %llu\n",
2895 		    (u_longlong_t)
2896 		    l2dhdr.dh_start_lbps[0].lbp_daddr);
2897 		(void) printf("    start_lbps[1]: %llu\n",
2898 		    (u_longlong_t)
2899 		    l2dhdr.dh_start_lbps[1].lbp_daddr);
2900 		(void) printf("    log_blk_ent: %llu\n",
2901 		    (u_longlong_t)l2dhdr.dh_log_entries);
2902 		(void) printf("    start: %llu\n",
2903 		    (u_longlong_t)l2dhdr.dh_start);
2904 		(void) printf("    end: %llu\n",
2905 		    (u_longlong_t)l2dhdr.dh_end);
2906 		(void) printf("    evict: %llu\n",
2907 		    (u_longlong_t)l2dhdr.dh_evict);
2908 		(void) printf("    lb_asize_refcount: %llu\n",
2909 		    (u_longlong_t)l2dhdr.dh_lb_asize);
2910 		(void) printf("    lb_count_refcount: %llu\n\n",
2911 		    (u_longlong_t)l2dhdr.dh_lb_count);
2912 	}
2913 
2914 	dump_l2arc_log_blocks(fd, l2dhdr, &rebuild);
2915 	/*
2916 	 * The total aligned size of log blocks and the number of log blocks
2917 	 * reported in the header of the device may be less than what zdb
2918 	 * reports by dump_l2arc_log_blocks() which emulates l2arc_rebuild().
2919 	 * This happens because dump_l2arc_log_blocks() lacks the memory
2920 	 * pressure valve that l2arc_rebuild() has. Thus, if we are on a system
2921 	 * with low memory, l2arc_rebuild will exit prematurely and dh_lb_asize
2922 	 * and dh_lb_count will be lower to begin with than what exists on the
2923 	 * device. This is normal and zdb should not exit with an error. The
2924 	 * opposite case should never happen though, the values reported in the
2925 	 * header should never be higher than what dump_l2arc_log_blocks() and
2926 	 * l2arc_rebuild() report. If this happens there is a leak in the
2927 	 * accounting of log blocks.
2928 	 */
2929 	if (l2dhdr.dh_lb_asize > rebuild.dh_lb_asize ||
2930 	    l2dhdr.dh_lb_count > rebuild.dh_lb_count)
2931 		return (1);
2932 
2933 	return (0);
2934 }
2935 
2936 static char curpath[PATH_MAX];
2937 
2938 /*
2939  * Iterate through the path components, recursively passing
2940  * current one's obj and remaining path until we find the obj
2941  * for the last one.
2942  */
2943 static int
dump_path_impl(objset_t * os,uint64_t obj,char * name)2944 dump_path_impl(objset_t *os, uint64_t obj, char *name)
2945 {
2946 	int err;
2947 	int header = 1;
2948 	uint64_t child_obj;
2949 	char *s;
2950 	dmu_buf_t *db;
2951 	dmu_object_info_t doi;
2952 
2953 	if ((s = strchr(name, '/')) != NULL)
2954 		*