xref: /illumos-gate/usr/src/cmd/mdb/common/modules/zfs/zfs.c (revision aee1cac845a0ba98d9e3fd84dcf769f75e47c95b)
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  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
24  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25  * Copyright 2020 Joyent, Inc.
26  * Copyright 2024 Oxide Computer Company
27  */
28 
29 /* Portions Copyright 2010 Robert Milkowski */
30 
31 /*
32  * ZFS_MDB lets dmu.h know that we don't have dmu_ot, and we will define our
33  * own macros to access the target's dmu_ot.  Therefore it must be defined
34  * before including any ZFS headers.  Note that we don't define
35  * DMU_OT_IS_ENCRYPTED_IMPL() or DMU_OT_BYTESWAP_IMPL(), therefore using them
36  * will result in a compilation error.  If they are needed in the future, we
37  * can implement them similarly to mdb_dmu_ot_is_encrypted_impl().
38  */
39 #define	ZFS_MDB
40 #define	DMU_OT_IS_ENCRYPTED_IMPL(ot) mdb_dmu_ot_is_encrypted_impl(ot)
41 
42 #include <mdb/mdb_ctf.h>
43 #include <sys/zfs_context.h>
44 #include <sys/mdb_modapi.h>
45 #include <sys/dbuf.h>
46 #include <sys/dmu_objset.h>
47 #include <sys/dsl_dir.h>
48 #include <sys/dsl_pool.h>
49 #include <sys/metaslab_impl.h>
50 #include <sys/space_map.h>
51 #include <sys/list.h>
52 #include <sys/vdev_impl.h>
53 #include <sys/zap_leaf.h>
54 #include <sys/zap_impl.h>
55 #include <ctype.h>
56 #include <sys/zfs_acl.h>
57 #include <sys/sa_impl.h>
58 #include <sys/multilist.h>
59 #include <sys/btree.h>
60 
61 #ifdef _KERNEL
62 #define	ZFS_OBJ_NAME	"zfs"
63 #else
64 #define	ZFS_OBJ_NAME	"libzpool.so.1"
65 #endif
66 extern int64_t mdb_gethrtime(void);
67 
68 #define	ZFS_STRUCT	"struct " ZFS_OBJ_NAME "`"
69 
70 #ifndef _KERNEL
71 int aok;
72 #endif
73 
74 enum spa_flags {
75 	SPA_FLAG_CONFIG			= 1 << 0,
76 	SPA_FLAG_VDEVS			= 1 << 1,
77 	SPA_FLAG_ERRORS			= 1 << 2,
78 	SPA_FLAG_METASLAB_GROUPS	= 1 << 3,
79 	SPA_FLAG_METASLABS		= 1 << 4,
80 	SPA_FLAG_HISTOGRAMS		= 1 << 5
81 };
82 
83 /*
84  * If any of these flags are set, call spa_vdevs in spa_print
85  */
86 #define	SPA_FLAG_ALL_VDEV	\
87 	(SPA_FLAG_VDEVS | SPA_FLAG_ERRORS | SPA_FLAG_METASLAB_GROUPS | \
88 	SPA_FLAG_METASLABS)
89 
90 static int
getmember(uintptr_t addr,const char * type,mdb_ctf_id_t * idp,const char * member,int len,void * buf)91 getmember(uintptr_t addr, const char *type, mdb_ctf_id_t *idp,
92     const char *member, int len, void *buf)
93 {
94 	mdb_ctf_id_t id;
95 	ulong_t off;
96 	char name[64];
97 
98 	if (idp == NULL) {
99 		if (mdb_ctf_lookup_by_name(type, &id) == -1) {
100 			mdb_warn("couldn't find type %s", type);
101 			return (DCMD_ERR);
102 		}
103 		idp = &id;
104 	} else {
105 		type = name;
106 		mdb_ctf_type_name(*idp, name, sizeof (name));
107 	}
108 
109 	if (mdb_ctf_offsetof(*idp, member, &off) == -1) {
110 		mdb_warn("couldn't find member %s of type %s\n", member, type);
111 		return (DCMD_ERR);
112 	}
113 	if (off % 8 != 0) {
114 		mdb_warn("member %s of type %s is unsupported bitfield",
115 		    member, type);
116 		return (DCMD_ERR);
117 	}
118 	off /= 8;
119 
120 	if (mdb_vread(buf, len, addr + off) == -1) {
121 		mdb_warn("failed to read %s from %s at %p",
122 		    member, type, addr + off);
123 		return (DCMD_ERR);
124 	}
125 	/* mdb_warn("read %s from %s at %p+%llx\n", member, type, addr, off); */
126 
127 	return (0);
128 }
129 
130 #define	GETMEMB(addr, structname, member, dest) \
131 	getmember(addr, ZFS_STRUCT structname, NULL, #member, \
132 	sizeof (dest), &(dest))
133 
134 #define	GETMEMBID(addr, ctfid, member, dest) \
135 	getmember(addr, NULL, ctfid, #member, sizeof (dest), &(dest))
136 
137 static boolean_t
strisprint(const char * cp)138 strisprint(const char *cp)
139 {
140 	for (; *cp; cp++) {
141 		if (!isprint(*cp))
142 			return (B_FALSE);
143 	}
144 	return (B_TRUE);
145 }
146 
147 /*
148  * <addr>::sm_entries <buffer length in bytes>
149  *
150  * Treat the buffer specified by the given address as a buffer that contains
151  * space map entries. Iterate over the specified number of entries and print
152  * them in both encoded and decoded form.
153  */
154 /* ARGSUSED */
155 static int
sm_entries(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)156 sm_entries(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
157 {
158 	uint64_t bufsz = 0;
159 	boolean_t preview = B_FALSE;
160 
161 	if (!(flags & DCMD_ADDRSPEC))
162 		return (DCMD_USAGE);
163 
164 	if (argc < 1) {
165 		preview = B_TRUE;
166 		bufsz = 2;
167 	} else if (argc != 1) {
168 		return (DCMD_USAGE);
169 	} else {
170 		switch (argv[0].a_type) {
171 		case MDB_TYPE_STRING:
172 			bufsz = mdb_strtoull(argv[0].a_un.a_str);
173 			break;
174 		case MDB_TYPE_IMMEDIATE:
175 			bufsz = argv[0].a_un.a_val;
176 			break;
177 		default:
178 			return (DCMD_USAGE);
179 		}
180 	}
181 
182 	char *actions[] = { "ALLOC", "FREE", "INVALID" };
183 	for (uintptr_t bufend = addr + bufsz; addr < bufend;
184 	    addr += sizeof (uint64_t)) {
185 		uint64_t nwords;
186 		uint64_t start_addr = addr;
187 
188 		uint64_t word = 0;
189 		if (mdb_vread(&word, sizeof (word), addr) == -1) {
190 			mdb_warn("failed to read space map entry %p", addr);
191 			return (DCMD_ERR);
192 		}
193 
194 		if (SM_PREFIX_DECODE(word) == SM_DEBUG_PREFIX) {
195 			(void) mdb_printf("\t    [%6llu] %s: txg %llu, "
196 			    "pass %llu\n",
197 			    (u_longlong_t)(addr),
198 			    actions[SM_DEBUG_ACTION_DECODE(word)],
199 			    (u_longlong_t)SM_DEBUG_TXG_DECODE(word),
200 			    (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(word));
201 			continue;
202 		}
203 
204 		char entry_type;
205 		uint64_t raw_offset, raw_run, vdev_id = SM_NO_VDEVID;
206 
207 		if (SM_PREFIX_DECODE(word) != SM2_PREFIX) {
208 			entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
209 			    'A' : 'F';
210 			raw_offset = SM_OFFSET_DECODE(word);
211 			raw_run = SM_RUN_DECODE(word);
212 			nwords = 1;
213 		} else {
214 			ASSERT3U(SM_PREFIX_DECODE(word), ==, SM2_PREFIX);
215 
216 			raw_run = SM2_RUN_DECODE(word);
217 			vdev_id = SM2_VDEV_DECODE(word);
218 
219 			/* it is a two-word entry so we read another word */
220 			addr += sizeof (uint64_t);
221 			if (addr >= bufend) {
222 				mdb_warn("buffer ends in the middle of a two "
223 				    "word entry\n", addr);
224 				return (DCMD_ERR);
225 			}
226 
227 			if (mdb_vread(&word, sizeof (word), addr) == -1) {
228 				mdb_warn("failed to read space map entry %p",
229 				    addr);
230 				return (DCMD_ERR);
231 			}
232 
233 			entry_type = (SM2_TYPE_DECODE(word) == SM_ALLOC) ?
234 			    'A' : 'F';
235 			raw_offset = SM2_OFFSET_DECODE(word);
236 			nwords = 2;
237 		}
238 
239 		(void) mdb_printf("\t    [%6llx]    %c  range:"
240 		    " %010llx-%010llx  size: %06llx vdev: %06llu words: %llu\n",
241 		    (u_longlong_t)start_addr,
242 		    entry_type, (u_longlong_t)raw_offset,
243 		    (u_longlong_t)(raw_offset + raw_run),
244 		    (u_longlong_t)raw_run,
245 		    (u_longlong_t)vdev_id, (u_longlong_t)nwords);
246 
247 		if (preview)
248 			break;
249 	}
250 	return (DCMD_OK);
251 }
252 
253 static int
mdb_dsl_dir_name(uintptr_t addr,char * buf)254 mdb_dsl_dir_name(uintptr_t addr, char *buf)
255 {
256 	static int gotid;
257 	static mdb_ctf_id_t dd_id;
258 	uintptr_t dd_parent;
259 	char dd_myname[ZFS_MAX_DATASET_NAME_LEN];
260 
261 	if (!gotid) {
262 		if (mdb_ctf_lookup_by_name(ZFS_STRUCT "dsl_dir",
263 		    &dd_id) == -1) {
264 			mdb_warn("couldn't find struct dsl_dir");
265 			return (DCMD_ERR);
266 		}
267 		gotid = TRUE;
268 	}
269 	if (GETMEMBID(addr, &dd_id, dd_parent, dd_parent) ||
270 	    GETMEMBID(addr, &dd_id, dd_myname, dd_myname)) {
271 		return (DCMD_ERR);
272 	}
273 
274 	if (dd_parent) {
275 		if (mdb_dsl_dir_name(dd_parent, buf))
276 			return (DCMD_ERR);
277 		strcat(buf, "/");
278 	}
279 
280 	if (dd_myname[0])
281 		strcat(buf, dd_myname);
282 	else
283 		strcat(buf, "???");
284 
285 	return (0);
286 }
287 
288 static int
objset_name(uintptr_t addr,char * buf)289 objset_name(uintptr_t addr, char *buf)
290 {
291 	static int gotid;
292 	static mdb_ctf_id_t os_id, ds_id;
293 	uintptr_t os_dsl_dataset;
294 	char ds_snapname[ZFS_MAX_DATASET_NAME_LEN];
295 	uintptr_t ds_dir;
296 
297 	buf[0] = '\0';
298 
299 	if (!gotid) {
300 		if (mdb_ctf_lookup_by_name(ZFS_STRUCT "objset",
301 		    &os_id) == -1) {
302 			mdb_warn("couldn't find struct objset");
303 			return (DCMD_ERR);
304 		}
305 		if (mdb_ctf_lookup_by_name(ZFS_STRUCT "dsl_dataset",
306 		    &ds_id) == -1) {
307 			mdb_warn("couldn't find struct dsl_dataset");
308 			return (DCMD_ERR);
309 		}
310 
311 		gotid = TRUE;
312 	}
313 
314 	if (GETMEMBID(addr, &os_id, os_dsl_dataset, os_dsl_dataset))
315 		return (DCMD_ERR);
316 
317 	if (os_dsl_dataset == 0) {
318 		strcat(buf, "mos");
319 		return (0);
320 	}
321 
322 	if (GETMEMBID(os_dsl_dataset, &ds_id, ds_snapname, ds_snapname) ||
323 	    GETMEMBID(os_dsl_dataset, &ds_id, ds_dir, ds_dir)) {
324 		return (DCMD_ERR);
325 	}
326 
327 	if (ds_dir && mdb_dsl_dir_name(ds_dir, buf))
328 		return (DCMD_ERR);
329 
330 	if (ds_snapname[0]) {
331 		strcat(buf, "@");
332 		strcat(buf, ds_snapname);
333 	}
334 	return (0);
335 }
336 
337 static int
enum_lookup(char * type,int val,const char * prefix,size_t size,char * out)338 enum_lookup(char *type, int val, const char *prefix, size_t size, char *out)
339 {
340 	const char *cp;
341 	size_t len = strlen(prefix);
342 	mdb_ctf_id_t enum_type;
343 
344 	if (mdb_ctf_lookup_by_name(type, &enum_type) != 0) {
345 		mdb_warn("Could not find enum for %s", type);
346 		return (-1);
347 	}
348 
349 	if ((cp = mdb_ctf_enum_name(enum_type, val)) != NULL) {
350 		if (strncmp(cp, prefix, len) == 0)
351 			cp += len;
352 		(void) strncpy(out, cp, size);
353 	} else {
354 		mdb_snprintf(out, size, "? (%d)", val);
355 	}
356 	return (0);
357 }
358 
359 /* ARGSUSED */
360 static int
zfs_params(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)361 zfs_params(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
362 {
363 	/*
364 	 * This table can be approximately generated by running:
365 	 * egrep "^[a-z0-9_]+ [a-z0-9_]+( =.*)?;" *.c | cut -d ' ' -f 2
366 	 */
367 	static const char *params[] = {
368 		"arc_lotsfree_percent",
369 		"arc_pages_pp_reserve",
370 		"arc_reduce_dnlc_percent",
371 		"arc_swapfs_reserve",
372 		"arc_zio_arena_free_shift",
373 		"dbuf_cache_hiwater_pct",
374 		"dbuf_cache_lowater_pct",
375 		"dbuf_cache_max_bytes",
376 		"dbuf_cache_max_shift",
377 		"ddt_zap_indirect_blockshift",
378 		"ddt_zap_leaf_blockshift",
379 		"ditto_same_vdev_distance_shift",
380 		"dmu_find_threads",
381 		"dmu_rescan_dnode_threshold",
382 		"dsl_scan_delay_completion",
383 		"fzap_default_block_shift",
384 		"l2arc_feed_again",
385 		"l2arc_feed_min_ms",
386 		"l2arc_feed_secs",
387 		"l2arc_headroom",
388 		"l2arc_headroom_boost",
389 		"l2arc_noprefetch",
390 		"l2arc_norw",
391 		"l2arc_write_boost",
392 		"l2arc_write_max",
393 		"metaslab_aliquot",
394 		"metaslab_bias_enabled",
395 		"metaslab_debug_load",
396 		"metaslab_debug_unload",
397 		"metaslab_df_alloc_threshold",
398 		"metaslab_df_free_pct",
399 		"metaslab_fragmentation_factor_enabled",
400 		"metaslab_force_ganging",
401 		"metaslab_lba_weighting_enabled",
402 		"metaslab_load_pct",
403 		"metaslab_min_alloc_size",
404 		"metaslab_ndf_clump_shift",
405 		"metaslab_preload_enabled",
406 		"metaslab_preload_limit",
407 		"metaslab_trace_enabled",
408 		"metaslab_trace_max_entries",
409 		"metaslab_unload_delay",
410 		"metaslabs_per_vdev",
411 		"reference_history",
412 		"reference_tracking_enable",
413 		"send_holes_without_birth_time",
414 		"spa_asize_inflation",
415 		"spa_load_verify_data",
416 		"spa_load_verify_maxinflight",
417 		"spa_load_verify_metadata",
418 		"spa_max_replication_override",
419 		"spa_min_slop",
420 		"spa_mode_global",
421 		"spa_slop_shift",
422 		"space_map_blksz",
423 		"vdev_mirror_shift",
424 		"zfetch_max_distance",
425 		"zfs_abd_chunk_size",
426 		"zfs_abd_scatter_enabled",
427 		"zfs_arc_average_blocksize",
428 		"zfs_arc_evict_batch_limit",
429 		"zfs_arc_grow_retry",
430 		"zfs_arc_max",
431 		"zfs_arc_meta_limit",
432 		"zfs_arc_meta_min",
433 		"zfs_arc_min",
434 		"zfs_arc_p_min_shift",
435 		"zfs_arc_shrink_shift",
436 		"zfs_async_block_max_blocks",
437 		"zfs_ccw_retry_interval",
438 		"zfs_commit_timeout_pct",
439 		"zfs_compressed_arc_enabled",
440 		"zfs_condense_indirect_commit_entry_delay_ticks",
441 		"zfs_condense_indirect_vdevs_enable",
442 		"zfs_condense_max_obsolete_bytes",
443 		"zfs_condense_min_mapping_bytes",
444 		"zfs_condense_pct",
445 		"zfs_dbgmsg_maxsize",
446 		"zfs_deadman_checktime_ms",
447 		"zfs_deadman_enabled",
448 		"zfs_deadman_synctime_ms",
449 		"zfs_dedup_prefetch",
450 		"zfs_default_bs",
451 		"zfs_default_ibs",
452 		"zfs_delay_max_ns",
453 		"zfs_delay_min_dirty_percent",
454 		"zfs_delay_resolution_ns",
455 		"zfs_delay_scale",
456 		"zfs_dirty_data_max",
457 		"zfs_dirty_data_max_max",
458 		"zfs_dirty_data_max_percent",
459 		"zfs_dirty_data_sync",
460 		"zfs_flags",
461 		"zfs_free_bpobj_enabled",
462 		"zfs_free_leak_on_eio",
463 		"zfs_free_min_time_ms",
464 		"zfs_fsync_sync_cnt",
465 		"zfs_immediate_write_sz",
466 		"zfs_indirect_condense_obsolete_pct",
467 		"zfs_lua_check_instrlimit_interval",
468 		"zfs_lua_max_instrlimit",
469 		"zfs_lua_max_memlimit",
470 		"zfs_max_recordsize",
471 		"zfs_mdcomp_disable",
472 		"zfs_metaslab_condense_block_threshold",
473 		"zfs_metaslab_fragmentation_threshold",
474 		"zfs_metaslab_segment_weight_enabled",
475 		"zfs_metaslab_switch_threshold",
476 		"zfs_mg_fragmentation_threshold",
477 		"zfs_mg_noalloc_threshold",
478 		"zfs_multilist_num_sublists",
479 		"zfs_no_scrub_io",
480 		"zfs_no_scrub_prefetch",
481 		"zfs_nocacheflush",
482 		"zfs_nopwrite_enabled",
483 		"zfs_object_remap_one_indirect_delay_ticks",
484 		"zfs_obsolete_min_time_ms",
485 		"zfs_pd_bytes_max",
486 		"zfs_per_txg_dirty_frees_percent",
487 		"zfs_prefetch_disable",
488 		"zfs_read_chunk_size",
489 		"zfs_recover",
490 		"zfs_recv_queue_length",
491 		"zfs_redundant_metadata_most_ditto_level",
492 		"zfs_remap_blkptr_enable",
493 		"zfs_remove_max_copy_bytes",
494 		"zfs_remove_max_segment",
495 		"zfs_resilver_delay",
496 		"zfs_resilver_min_time_ms",
497 		"zfs_scan_idle",
498 		"zfs_scan_min_time_ms",
499 		"zfs_scrub_delay",
500 		"zfs_scrub_limit",
501 		"zfs_send_corrupt_data",
502 		"zfs_send_queue_length",
503 		"zfs_send_set_freerecords_bit",
504 		"zfs_sync_pass_deferred_free",
505 		"zfs_sync_pass_dont_compress",
506 		"zfs_sync_pass_rewrite",
507 		"zfs_sync_taskq_batch_pct",
508 		"zfs_top_maxinflight",
509 		"zfs_txg_timeout",
510 		"zfs_vdev_aggregation_limit",
511 		"zfs_vdev_async_read_max_active",
512 		"zfs_vdev_async_read_min_active",
513 		"zfs_vdev_async_write_active_max_dirty_percent",
514 		"zfs_vdev_async_write_active_min_dirty_percent",
515 		"zfs_vdev_async_write_max_active",
516 		"zfs_vdev_async_write_min_active",
517 		"zfs_vdev_cache_bshift",
518 		"zfs_vdev_cache_max",
519 		"zfs_vdev_cache_size",
520 		"zfs_vdev_max_active",
521 		"zfs_vdev_queue_depth_pct",
522 		"zfs_vdev_read_gap_limit",
523 		"zfs_vdev_removal_max_active",
524 		"zfs_vdev_removal_min_active",
525 		"zfs_vdev_scrub_max_active",
526 		"zfs_vdev_scrub_min_active",
527 		"zfs_vdev_sync_read_max_active",
528 		"zfs_vdev_sync_read_min_active",
529 		"zfs_vdev_sync_write_max_active",
530 		"zfs_vdev_sync_write_min_active",
531 		"zfs_vdev_write_gap_limit",
532 		"zfs_write_implies_delete_child",
533 		"zfs_zil_clean_taskq_maxalloc",
534 		"zfs_zil_clean_taskq_minalloc",
535 		"zfs_zil_clean_taskq_nthr_pct",
536 		"zil_replay_disable",
537 		"zil_slog_bulk",
538 		"zio_buf_debug_limit",
539 		"zio_dva_throttle_enabled",
540 		"zio_injection_enabled",
541 		"zvol_immediate_write_sz",
542 		"zvol_maxphys",
543 		"zvol_unmap_enabled",
544 		"zvol_unmap_sync_enabled",
545 		"zfs_max_dataset_nesting",
546 	};
547 
548 	for (int i = 0; i < sizeof (params) / sizeof (params[0]); i++) {
549 		int sz;
550 		uint64_t val64;
551 		uint32_t *val32p = (uint32_t *)&val64;
552 
553 		sz = mdb_readvar(&val64, params[i]);
554 		if (sz == 4) {
555 			mdb_printf("%s = 0x%x\n", params[i], *val32p);
556 		} else if (sz == 8) {
557 			mdb_printf("%s = 0x%llx\n", params[i], val64);
558 		} else {
559 			mdb_warn("variable %s not found", params[i]);
560 		}
561 	}
562 
563 	return (DCMD_OK);
564 }
565 
566 /* ARGSUSED */
567 static int
dva(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)568 dva(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
569 {
570 	dva_t dva;
571 	if (mdb_vread(&dva, sizeof (dva_t), addr) == -1) {
572 		mdb_warn("failed to read dva_t");
573 		return (DCMD_ERR);
574 	}
575 	mdb_printf("<%llu:%llx:%llx>\n",
576 	    (u_longlong_t)DVA_GET_VDEV(&dva),
577 	    (u_longlong_t)DVA_GET_OFFSET(&dva),
578 	    (u_longlong_t)DVA_GET_ASIZE(&dva));
579 
580 	return (DCMD_OK);
581 }
582 
583 typedef struct mdb_dmu_object_type_info {
584 	boolean_t ot_encrypt;
585 } mdb_dmu_object_type_info_t;
586 
587 static boolean_t
mdb_dmu_ot_is_encrypted_impl(dmu_object_type_t ot)588 mdb_dmu_ot_is_encrypted_impl(dmu_object_type_t ot)
589 {
590 	mdb_dmu_object_type_info_t mdoti;
591 	GElf_Sym sym;
592 	size_t sz = mdb_ctf_sizeof_by_name("dmu_object_type_info_t");
593 
594 	if (mdb_lookup_by_obj(ZFS_OBJ_NAME, "dmu_ot", &sym)) {
595 		mdb_warn("failed to find " ZFS_OBJ_NAME "`dmu_ot");
596 		return (B_FALSE);
597 	}
598 
599 	if (mdb_ctf_vread(&mdoti, "dmu_object_type_info_t",
600 	    "mdb_dmu_object_type_info_t", sym.st_value + sz * ot, 0) != 0) {
601 		return (B_FALSE);
602 	}
603 
604 	return (mdoti.ot_encrypt);
605 }
606 
607 /* ARGSUSED */
608 static int
blkptr(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)609 blkptr(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
610 {
611 	char type[80], checksum[80], compress[80];
612 	blkptr_t blk, *bp = &blk;
613 	char buf[BP_SPRINTF_LEN];
614 
615 	if (mdb_vread(&blk, sizeof (blkptr_t), addr) == -1) {
616 		mdb_warn("failed to read blkptr_t");
617 		return (DCMD_ERR);
618 	}
619 
620 	if (enum_lookup("enum dmu_object_type", BP_GET_TYPE(bp), "DMU_OT_",
621 	    sizeof (type), type) == -1 ||
622 	    enum_lookup("enum zio_checksum", BP_GET_CHECKSUM(bp),
623 	    "ZIO_CHECKSUM_", sizeof (checksum), checksum) == -1 ||
624 	    enum_lookup("enum zio_compress", BP_GET_COMPRESS(bp),
625 	    "ZIO_COMPRESS_", sizeof (compress), compress) == -1) {
626 		mdb_warn("Could not find blkptr enumerated types");
627 		return (DCMD_ERR);
628 	}
629 
630 	SNPRINTF_BLKPTR(mdb_snprintf, '\n', buf, sizeof (buf), bp, type,
631 	    checksum, compress);
632 
633 	mdb_printf("%s\n", buf);
634 
635 	return (DCMD_OK);
636 }
637 
638 typedef struct mdb_dmu_buf_impl {
639 	struct {
640 		uint64_t db_object;
641 		uintptr_t db_data;
642 	} db;
643 	uintptr_t db_objset;
644 	uint64_t db_level;
645 	uint64_t db_blkid;
646 	struct {
647 		uint64_t rc_count;
648 	} db_holds;
649 } mdb_dmu_buf_impl_t;
650 
651 /* ARGSUSED */
652 static int
dbuf(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)653 dbuf(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
654 {
655 	mdb_dmu_buf_impl_t db;
656 	char objectname[32];
657 	char blkidname[32];
658 	char path[ZFS_MAX_DATASET_NAME_LEN];
659 	int ptr_width = (int)(sizeof (void *)) * 2;
660 
661 	if (DCMD_HDRSPEC(flags))
662 		mdb_printf("%*s %8s %3s %9s %5s %s\n",
663 		    ptr_width, "addr", "object", "lvl", "blkid", "holds", "os");
664 
665 	if (mdb_ctf_vread(&db, ZFS_STRUCT "dmu_buf_impl", "mdb_dmu_buf_impl_t",
666 	    addr, 0) == -1)
667 		return (DCMD_ERR);
668 
669 	if (db.db.db_object == DMU_META_DNODE_OBJECT)
670 		(void) strcpy(objectname, "mdn");
671 	else
672 		(void) mdb_snprintf(objectname, sizeof (objectname), "%llx",
673 		    (u_longlong_t)db.db.db_object);
674 
675 	if (db.db_blkid == DMU_BONUS_BLKID)
676 		(void) strcpy(blkidname, "bonus");
677 	else
678 		(void) mdb_snprintf(blkidname, sizeof (blkidname), "%llx",
679 		    (u_longlong_t)db.db_blkid);
680 
681 	if (objset_name(db.db_objset, path)) {
682 		return (DCMD_ERR);
683 	}
684 
685 	mdb_printf("%*p %8s %3u %9s %5llu %s\n", ptr_width, addr,
686 	    objectname, (int)db.db_level, blkidname,
687 	    db.db_holds.rc_count, path);
688 
689 	return (DCMD_OK);
690 }
691 
692 /* ARGSUSED */
693 static int
dbuf_stats(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)694 dbuf_stats(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
695 {
696 #define	HISTOSZ 32
697 	uintptr_t dbp;
698 	dmu_buf_impl_t db;
699 	dbuf_hash_table_t ht;
700 	uint64_t bucket, ndbufs;
701 	uint64_t histo[HISTOSZ];
702 	uint64_t histo2[HISTOSZ];
703 	int i, maxidx;
704 
705 	if (mdb_readvar(&ht, "dbuf_hash_table") == -1) {
706 		mdb_warn("failed to read 'dbuf_hash_table'");
707 		return (DCMD_ERR);
708 	}
709 
710 	for (i = 0; i < HISTOSZ; i++) {
711 		histo[i] = 0;
712 		histo2[i] = 0;
713 	}
714 
715 	ndbufs = 0;
716 	for (bucket = 0; bucket < ht.hash_table_mask+1; bucket++) {
717 		int len;
718 
719 		if (mdb_vread(&dbp, sizeof (void *),
720 		    (uintptr_t)(ht.hash_table+bucket)) == -1) {
721 			mdb_warn("failed to read hash bucket %u at %p",
722 			    bucket, ht.hash_table+bucket);
723 			return (DCMD_ERR);
724 		}
725 
726 		len = 0;
727 		while (dbp != 0) {
728 			if (mdb_vread(&db, sizeof (dmu_buf_impl_t),
729 			    dbp) == -1) {
730 				mdb_warn("failed to read dbuf at %p", dbp);
731 				return (DCMD_ERR);
732 			}
733 			dbp = (uintptr_t)db.db_hash_next;
734 			for (i = MIN(len, HISTOSZ - 1); i >= 0; i--)
735 				histo2[i]++;
736 			len++;
737 			ndbufs++;
738 		}
739 
740 		if (len >= HISTOSZ)
741 			len = HISTOSZ-1;
742 		histo[len]++;
743 	}
744 
745 	mdb_printf("hash table has %llu buckets, %llu dbufs "
746 	    "(avg %llu buckets/dbuf)\n",
747 	    ht.hash_table_mask+1, ndbufs,
748 	    (ht.hash_table_mask+1)/ndbufs);
749 
750 	mdb_printf("\n");
751 	maxidx = 0;
752 	for (i = 0; i < HISTOSZ; i++)
753 		if (histo[i] > 0)
754 			maxidx = i;
755 	mdb_printf("hash chain length	number of buckets\n");
756 	for (i = 0; i <= maxidx; i++)
757 		mdb_printf("%u			%llu\n", i, histo[i]);
758 
759 	mdb_printf("\n");
760 	maxidx = 0;
761 	for (i = 0; i < HISTOSZ; i++)
762 		if (histo2[i] > 0)
763 			maxidx = i;
764 	mdb_printf("hash chain depth	number of dbufs\n");
765 	for (i = 0; i <= maxidx; i++)
766 		mdb_printf("%u or more		%llu	%llu%%\n",
767 		    i, histo2[i], histo2[i]*100/ndbufs);
768 
769 
770 	return (DCMD_OK);
771 }
772 
773 #define	CHAIN_END 0xffff
774 /*
775  * ::zap_leaf [-v]
776  *
777  * Print a zap_leaf_phys_t, assumed to be 16k
778  */
779 /* ARGSUSED */
780 static int
zap_leaf(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)781 zap_leaf(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
782 {
783 	char buf[16*1024];
784 	int verbose = B_FALSE;
785 	int four = B_FALSE;
786 	dmu_buf_t l_dbuf;
787 	zap_leaf_t l;
788 	zap_leaf_phys_t *zlp = (void *)buf;
789 	int i;
790 
791 	if (mdb_getopts(argc, argv,
792 	    'v', MDB_OPT_SETBITS, TRUE, &verbose,
793 	    '4', MDB_OPT_SETBITS, TRUE, &four,
794 	    NULL) != argc)
795 		return (DCMD_USAGE);
796 
797 	l_dbuf.db_data = zlp;
798 	l.l_dbuf = &l_dbuf;
799 	l.l_bs = 14; /* assume 16k blocks */
800 	if (four)
801 		l.l_bs = 12;
802 
803 	if (!(flags & DCMD_ADDRSPEC)) {
804 		return (DCMD_USAGE);
805 	}
806 
807 	if (mdb_vread(buf, sizeof (buf), addr) == -1) {
808 		mdb_warn("failed to read zap_leaf_phys_t at %p", addr);
809 		return (DCMD_ERR);
810 	}
811 
812 	if (zlp->l_hdr.lh_block_type != ZBT_LEAF ||
813 	    zlp->l_hdr.lh_magic != ZAP_LEAF_MAGIC) {
814 		mdb_warn("This does not appear to be a zap_leaf_phys_t");
815 		return (DCMD_ERR);
816 	}
817 
818 	mdb_printf("zap_leaf_phys_t at %p:\n", addr);
819 	mdb_printf("    lh_prefix_len = %u\n", zlp->l_hdr.lh_prefix_len);
820 	mdb_printf("    lh_prefix = %llx\n", zlp->l_hdr.lh_prefix);
821 	mdb_printf("    lh_nentries = %u\n", zlp->l_hdr.lh_nentries);
822 	mdb_printf("    lh_nfree = %u\n", zlp->l_hdr.lh_nfree,
823 	    zlp->l_hdr.lh_nfree * 100 / (ZAP_LEAF_NUMCHUNKS(&l)));
824 	mdb_printf("    lh_freelist = %u\n", zlp->l_hdr.lh_freelist);
825 	mdb_printf("    lh_flags = %x (%s)\n", zlp->l_hdr.lh_flags,
826 	    zlp->l_hdr.lh_flags & ZLF_ENTRIES_CDSORTED ?
827 	    "ENTRIES_CDSORTED" : "");
828 
829 	if (verbose) {
830 		mdb_printf(" hash table:\n");
831 		for (i = 0; i < ZAP_LEAF_HASH_NUMENTRIES(&l); i++) {
832 			if (zlp->l_hash[i] != CHAIN_END)
833 				mdb_printf("    %u: %u\n", i, zlp->l_hash[i]);
834 		}
835 	}
836 
837 	mdb_printf(" chunks:\n");
838 	for (i = 0; i < ZAP_LEAF_NUMCHUNKS(&l); i++) {
839 		/* LINTED: alignment */
840 		zap_leaf_chunk_t *zlc = &ZAP_LEAF_CHUNK(&l, i);
841 		switch (zlc->l_entry.le_type) {
842 		case ZAP_CHUNK_FREE:
843 			if (verbose) {
844 				mdb_printf("    %u: free; lf_next = %u\n",
845 				    i, zlc->l_free.lf_next);
846 			}
847 			break;
848 		case ZAP_CHUNK_ENTRY:
849 			mdb_printf("    %u: entry\n", i);
850 			if (verbose) {
851 				mdb_printf("        le_next = %u\n",
852 				    zlc->l_entry.le_next);
853 			}
854 			mdb_printf("        le_name_chunk = %u\n",
855 			    zlc->l_entry.le_name_chunk);
856 			mdb_printf("        le_name_numints = %u\n",
857 			    zlc->l_entry.le_name_numints);
858 			mdb_printf("        le_value_chunk = %u\n",
859 			    zlc->l_entry.le_value_chunk);
860 			mdb_printf("        le_value_intlen = %u\n",
861 			    zlc->l_entry.le_value_intlen);
862 			mdb_printf("        le_value_numints = %u\n",
863 			    zlc->l_entry.le_value_numints);
864 			mdb_printf("        le_cd = %u\n",
865 			    zlc->l_entry.le_cd);
866 			mdb_printf("        le_hash = %llx\n",
867 			    zlc->l_entry.le_hash);
868 			break;
869 		case ZAP_CHUNK_ARRAY:
870 			mdb_printf("    %u: array", i);
871 			if (strisprint((char *)zlc->l_array.la_array))
872 				mdb_printf(" \"%s\"", zlc->l_array.la_array);
873 			mdb_printf("\n");
874 			if (verbose) {
875 				int j;
876 				mdb_printf("        ");
877 				for (j = 0; j < ZAP_LEAF_ARRAY_BYTES; j++) {
878 					mdb_printf("%02x ",
879 					    zlc->l_array.la_array[j]);
880 				}
881 				mdb_printf("\n");
882 			}
883 			if (zlc->l_array.la_next != CHAIN_END) {
884 				mdb_printf("        lf_next = %u\n",
885 				    zlc->l_array.la_next);
886 			}
887 			break;
888 		default:
889 			mdb_printf("    %u: undefined type %u\n",
890 			    zlc->l_entry.le_type);
891 		}
892 	}
893 
894 	return (DCMD_OK);
895 }
896 
897 typedef struct dbufs_data {
898 	mdb_ctf_id_t id;
899 	uint64_t objset;
900 	uint64_t object;
901 	uint64_t level;
902 	uint64_t blkid;
903 	char *osname;
904 } dbufs_data_t;
905 
906 #define	DBUFS_UNSET	(0xbaddcafedeadbeefULL)
907 
908 /* ARGSUSED */
909 static int
dbufs_cb(uintptr_t addr,const void * unknown,void * arg)910 dbufs_cb(uintptr_t addr, const void *unknown, void *arg)
911 {
912 	dbufs_data_t *data = arg;
913 	uintptr_t objset;
914 	dmu_buf_t db;
915 	uint8_t level;
916 	uint64_t blkid;
917 	char osname[ZFS_MAX_DATASET_NAME_LEN];
918 
919 	if (GETMEMBID(addr, &data->id, db_objset, objset) ||
920 	    GETMEMBID(addr, &data->id, db, db) ||
921 	    GETMEMBID(addr, &data->id, db_level, level) ||
922 	    GETMEMBID(addr, &data->id, db_blkid, blkid)) {
923 		return (WALK_ERR);
924 	}
925 
926 	if ((data->objset == DBUFS_UNSET || data->objset == objset) &&
927 	    (data->osname == NULL || (objset_name(objset, osname) == 0 &&
928 	    strcmp(data->osname, osname) == 0)) &&
929 	    (data->object == DBUFS_UNSET || data->object == db.db_object) &&
930 	    (data->level == DBUFS_UNSET || data->level == level) &&
931 	    (data->blkid == DBUFS_UNSET || data->blkid == blkid)) {
932 		mdb_printf("%#lr\n", addr);
933 	}
934 	return (WALK_NEXT);
935 }
936 
937 /* ARGSUSED */
938 static int
dbufs(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)939 dbufs(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
940 {
941 	dbufs_data_t data;
942 	char *object = NULL;
943 	char *blkid = NULL;
944 
945 	data.objset = data.object = data.level = data.blkid = DBUFS_UNSET;
946 	data.osname = NULL;
947 
948 	if (mdb_getopts(argc, argv,
949 	    'O', MDB_OPT_UINT64, &data.objset,
950 	    'n', MDB_OPT_STR, &data.osname,
951 	    'o', MDB_OPT_STR, &object,
952 	    'l', MDB_OPT_UINT64, &data.level,
953 	    'b', MDB_OPT_STR, &blkid,
954 	    NULL) != argc) {
955 		return (DCMD_USAGE);
956 	}
957 
958 	if (object) {
959 		if (strcmp(object, "mdn") == 0) {
960 			data.object = DMU_META_DNODE_OBJECT;
961 		} else {
962 			data.object = mdb_strtoull(object);
963 		}
964 	}
965 
966 	if (blkid) {
967 		if (strcmp(blkid, "bonus") == 0) {
968 			data.blkid = DMU_BONUS_BLKID;
969 		} else {
970 			data.blkid = mdb_strtoull(blkid);
971 		}
972 	}
973 
974 	if (mdb_ctf_lookup_by_name(ZFS_STRUCT "dmu_buf_impl", &data.id) == -1) {
975 		mdb_warn("couldn't find struct dmu_buf_impl_t");
976 		return (DCMD_ERR);
977 	}
978 
979 	if (mdb_walk("dmu_buf_impl_t", dbufs_cb, &data) != 0) {
980 		mdb_warn("can't walk dbufs");
981 		return (DCMD_ERR);
982 	}
983 
984 	return (DCMD_OK);
985 }
986 
987 typedef struct abuf_find_data {
988 	dva_t dva;
989 	mdb_ctf_id_t id;
990 } abuf_find_data_t;
991 
992 /* ARGSUSED */
993 static int
abuf_find_cb(uintptr_t addr,const void * unknown,void * arg)994 abuf_find_cb(uintptr_t addr, const void *unknown, void *arg)
995 {
996 	abuf_find_data_t *data = arg;
997 	dva_t dva;
998 
999 	if (GETMEMBID(addr, &data->id, b_dva, dva)) {
1000 		return (WALK_ERR);
1001 	}
1002 
1003 	if (dva.dva_word[0] == data->dva.dva_word[0] &&
1004 	    dva.dva_word[1] == data->dva.dva_word[1]) {
1005 		mdb_printf("%#lr\n", addr);
1006 	}
1007 	return (WALK_NEXT);
1008 }
1009 
1010 typedef struct mdb_arc_state {
1011 	uintptr_t	arcs_list[ARC_BUFC_NUMTYPES];
1012 } mdb_arc_state_t;
1013 
1014 /* ARGSUSED */
1015 static int
abuf_find(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)1016 abuf_find(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1017 {
1018 	abuf_find_data_t data;
1019 	GElf_Sym sym;
1020 	int i, j;
1021 	const char *syms[] = {
1022 		"ARC_mru",
1023 		"ARC_mru_ghost",
1024 		"ARC_mfu",
1025 		"ARC_mfu_ghost",
1026 	};
1027 
1028 	if (argc != 2)
1029 		return (DCMD_USAGE);
1030 
1031 	for (i = 0; i < 2; i ++) {
1032 		switch (argv[i].a_type) {
1033 		case MDB_TYPE_STRING:
1034 			data.dva.dva_word[i] = mdb_strtoull(argv[i].a_un.a_str);
1035 			break;
1036 		case MDB_TYPE_IMMEDIATE:
1037 			data.dva.dva_word[i] = argv[i].a_un.a_val;
1038 			break;
1039 		default:
1040 			return (DCMD_USAGE);
1041 		}
1042 	}
1043 
1044 	if (mdb_ctf_lookup_by_name(ZFS_STRUCT "arc_buf_hdr", &data.id) == -1) {
1045 		mdb_warn("couldn't find struct arc_buf_hdr");
1046 		return (DCMD_ERR);
1047 	}
1048 
1049 	for (i = 0; i < sizeof (syms) / sizeof (syms[0]); i++) {
1050 		mdb_arc_state_t mas;
1051 
1052 		if (mdb_lookup_by_obj(ZFS_OBJ_NAME, syms[i], &sym)) {
1053 			mdb_warn("can't find symbol %s", syms[i]);
1054 			return (DCMD_ERR);
1055 		}
1056 
1057 		if (mdb_ctf_vread(&mas, "arc_state_t", "mdb_arc_state_t",
1058 		    sym.st_value, 0) != 0) {
1059 			mdb_warn("can't read arcs_list of %s", syms[i]);
1060 			return (DCMD_ERR);
1061 		}
1062 
1063 		for (j = 0; j < ARC_BUFC_NUMTYPES; j++) {
1064 			uintptr_t addr = mas.arcs_list[j];
1065 
1066 			if (addr == 0)
1067 				continue;
1068 
1069 			if (mdb_pwalk("multilist", abuf_find_cb, &data,
1070 			    addr) != 0) {
1071 				mdb_warn("can't walk %s", syms[i]);
1072 				return (DCMD_ERR);
1073 			}
1074 		}
1075 	}
1076 
1077 	return (DCMD_OK);
1078 }
1079 
1080 typedef struct dbgmsg_arg {
1081 	boolean_t da_address;
1082 	boolean_t da_hrtime;
1083 	boolean_t da_timedelta;
1084 	boolean_t da_time;
1085 	boolean_t da_whatis;
1086 
1087 	hrtime_t da_curtime;
1088 } dbgmsg_arg_t;
1089 
1090 static int
dbgmsg_cb(uintptr_t addr,const void * unknown __unused,void * arg)1091 dbgmsg_cb(uintptr_t addr, const void *unknown __unused, void *arg)
1092 {
1093 	static mdb_ctf_id_t id;
1094 	static boolean_t gotid;
1095 	static ulong_t off;
1096 
1097 	dbgmsg_arg_t *da = arg;
1098 	time_t timestamp;
1099 	hrtime_t hrtime;
1100 	char buf[1024];
1101 
1102 	if (!gotid) {
1103 		if (mdb_ctf_lookup_by_name(ZFS_STRUCT "zfs_dbgmsg", &id) ==
1104 		    -1) {
1105 			mdb_warn("couldn't find struct zfs_dbgmsg");
1106 			return (WALK_ERR);
1107 		}
1108 		gotid = TRUE;
1109 		if (mdb_ctf_offsetof(id, "zdm_msg", &off) == -1) {
1110 			mdb_warn("couldn't find zdm_msg");
1111 			return (WALK_ERR);
1112 		}
1113 		off /= 8;
1114 	}
1115 
1116 	if (GETMEMBID(addr, &id, zdm_timestamp, timestamp)) {
1117 		return (WALK_ERR);
1118 	}
1119 
1120 	if (da->da_hrtime || da->da_timedelta) {
1121 		if (GETMEMBID(addr, &id, zdm_hrtime, hrtime)) {
1122 			return (WALK_ERR);
1123 		}
1124 	}
1125 
1126 	if (mdb_readstr(buf, sizeof (buf), addr + off) == -1) {
1127 		mdb_warn("failed to read zdm_msg at %p\n", addr + off);
1128 		return (DCMD_ERR);
1129 	}
1130 
1131 	if (da->da_address)
1132 		mdb_printf("%p ", addr);
1133 
1134 	if (da->da_timedelta) {
1135 		int64_t		diff;
1136 		char		dbuf[32] = { 0 };
1137 
1138 		if (da->da_curtime == 0)
1139 			da->da_curtime = mdb_gethrtime();
1140 
1141 		diff = (int64_t)hrtime - da->da_curtime;
1142 		mdb_nicetime(diff, dbuf, sizeof (dbuf));
1143 		mdb_printf("%-20s ", dbuf);
1144 	} else if (da->da_hrtime) {
1145 		mdb_printf("%016x ", hrtime);
1146 	} else if (da->da_time) {
1147 		mdb_printf("%Y ", timestamp);
1148 	}
1149 
1150 	mdb_printf("%s\n", buf);
1151 
1152 	if (da->da_whatis)
1153 		(void) mdb_call_dcmd("whatis", addr, DCMD_ADDRSPEC, 0, NULL);
1154 
1155 	return (WALK_NEXT);
1156 }
1157 
1158 static int
dbgmsg(uintptr_t addr,uint_t flags __unused,int argc,const mdb_arg_t * argv)1159 dbgmsg(uintptr_t addr, uint_t flags __unused, int argc, const mdb_arg_t *argv)
1160 {
1161 	GElf_Sym sym;
1162 	dbgmsg_arg_t da = { 0 };
1163 	boolean_t verbose = B_FALSE;
1164 
1165 	if (mdb_getopts(argc, argv,
1166 	    'a', MDB_OPT_SETBITS, B_TRUE, &da.da_address,
1167 	    'r', MDB_OPT_SETBITS, B_TRUE, &da.da_hrtime,
1168 	    't', MDB_OPT_SETBITS, B_TRUE, &da.da_timedelta,
1169 	    'T', MDB_OPT_SETBITS, B_TRUE, &da.da_time,
1170 	    'v', MDB_OPT_SETBITS, B_TRUE, &verbose,
1171 	    'w', MDB_OPT_SETBITS, B_TRUE, &da.da_whatis,
1172 	    NULL) != argc) {
1173 		return (DCMD_USAGE);
1174 	}
1175 
1176 	if (verbose)
1177 		da.da_address = da.da_time = B_TRUE;
1178 
1179 	if (mdb_lookup_by_obj(ZFS_OBJ_NAME, "zfs_dbgmsgs", &sym)) {
1180 		mdb_warn("can't find zfs_dbgmsgs");
1181 		return (DCMD_ERR);
1182 	}
1183 
1184 	if (mdb_pwalk("list", dbgmsg_cb, &da, sym.st_value) != 0) {
1185 		mdb_warn("can't walk zfs_dbgmsgs");
1186 		return (DCMD_ERR);
1187 	}
1188 
1189 	return (DCMD_OK);
1190 }
1191 
1192 
1193 static void
dbgmsg_help(void)1194 dbgmsg_help(void)
1195 {
1196 	mdb_printf("Print entries from the ZFS debug log.\n\n"
1197 	    "%<b>OPTIONS%</b>\n"
1198 	    "\t-a\tInclude the address of each zfs_dbgmsg_t.\n"
1199 	    "\t-r\tDisplay high-resolution timestamps.\n"
1200 	    "\t-t\tInclude the age of the message.\n"
1201 	    "\t-T\tInclude the date/time of the message.\n"
1202 	    "\t-v\tEquivalent to -aT.\n"
1203 	    "\t-w\tRun ::whatis on each zfs_dbgmsg_t. Useful in DEBUG kernels\n"
1204 	    "\t\tto show the origin of the message.\n");
1205 }
1206 
1207 /*ARGSUSED*/
1208 static int
arc_print(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)1209 arc_print(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1210 {
1211 	kstat_named_t *stats;
1212 	GElf_Sym sym;
1213 	int nstats, i;
1214 	uint_t opt_a = FALSE;
1215 	uint_t opt_b = FALSE;
1216 	uint_t shift = 0;
1217 	const char *suffix;
1218 
1219 	static const char *bytestats[] = {
1220 		"p", "c", "c_min", "c_max", "size", "duplicate_buffers_size",
1221 		"arc_meta_used", "arc_meta_limit", "arc_meta_max",
1222 		"arc_meta_min", "hdr_size", "data_size", "metadata_size",
1223 		"other_size", "anon_size", "anon_evictable_data",
1224 		"anon_evictable_metadata", "mru_size", "mru_evictable_data",
1225 		"mru_evictable_metadata", "mru_ghost_size",
1226 		"mru_ghost_evictable_data", "mru_ghost_evictable_metadata",
1227 		"mfu_size", "mfu_evictable_data", "mfu_evictable_metadata",
1228 		"mfu_ghost_size", "mfu_ghost_evictable_data",
1229 		"mfu_ghost_evictable_metadata", "evict_l2_cached",
1230 		"evict_l2_eligible", "evict_l2_ineligible", "l2_read_bytes",
1231 		"l2_write_bytes", "l2_size", "l2_asize", "l2_hdr_size",
1232 		"compressed_size", "uncompressed_size", "overhead_size",
1233 		NULL
1234 	};
1235 
1236 	static const char *extras[] = {
1237 		"arc_no_grow", "arc_tempreserve",
1238 		NULL
1239 	};
1240 
1241 	if (mdb_lookup_by_obj(ZFS_OBJ_NAME, "arc_stats", &sym) == -1) {
1242 		mdb_warn("failed to find 'arc_stats'");
1243 		return (DCMD_ERR);
1244 	}
1245 
1246 	stats = mdb_zalloc(sym.st_size, UM_SLEEP | UM_GC);
1247 
1248 	if (mdb_vread(stats, sym.st_size, sym.st_value) == -1) {
1249 		mdb_warn("couldn't read 'arc_stats' at %p", sym.st_value);
1250 		return (DCMD_ERR);
1251 	}
1252 
1253 	nstats = sym.st_size / sizeof (kstat_named_t);
1254 
1255 	/* NB: -a / opt_a are ignored for backwards compatability */
1256 	if (mdb_getopts(argc, argv,
1257 	    'a', MDB_OPT_SETBITS, TRUE, &opt_a,
1258 	    'b', MDB_OPT_SETBITS, TRUE, &opt_b,
1259 	    'k', MDB_OPT_SETBITS, 10, &shift,
1260 	    'm', MDB_OPT_SETBITS, 20, &shift,
1261 	    'g', MDB_OPT_SETBITS, 30, &shift,
1262 	    NULL) != argc)
1263 		return (DCMD_USAGE);
1264 
1265 	if (!opt_b && !shift)
1266 		shift = 20;
1267 
1268 	switch (shift) {
1269 	case 0:
1270 		suffix = "B";
1271 		break;
1272 	case 10:
1273 		suffix = "KB";
1274 		break;
1275 	case 20:
1276 		suffix = "MB";
1277 		break;
1278 	case 30:
1279 		suffix = "GB";
1280 		break;
1281 	default:
1282 		suffix = "XX";
1283 	}
1284 
1285 	for (i = 0; i < nstats; i++) {
1286 		int j;
1287 		boolean_t bytes = B_FALSE;
1288 
1289 		for (j = 0; bytestats[j]; j++) {
1290 			if (strcmp(stats[i].name, bytestats[j]) == 0) {
1291 				bytes = B_TRUE;
1292 				break;
1293 			}
1294 		}
1295 
1296 		if (bytes) {
1297 			mdb_printf("%-25s = %9llu %s\n", stats[i].name,
1298 			    stats[i].value.ui64 >> shift, suffix);
1299 		} else {
1300 			mdb_printf("%-25s = %9llu\n", stats[i].name,
1301 			    stats[i].value.ui64);
1302 		}
1303 	}
1304 
1305 	for (i = 0; extras[i]; i++) {
1306 		uint64_t buf;
1307 
1308 		if (mdb_lookup_by_obj(ZFS_OBJ_NAME, extras[i], &sym) == -1) {
1309 			mdb_warn("failed to find '%s'", extras[i]);
1310 			return (DCMD_ERR);
1311 		}
1312 
1313 		if (sym.st_size != sizeof (uint64_t) &&
1314 		    sym.st_size != sizeof (uint32_t)) {
1315 			mdb_warn("expected scalar for variable '%s'\n",
1316 			    extras[i]);
1317 			return (DCMD_ERR);
1318 		}
1319 
1320 		if (mdb_vread(&buf, sym.st_size, sym.st_value) == -1) {
1321 			mdb_warn("couldn't read '%s'", extras[i]);
1322 			return (DCMD_ERR);
1323 		}
1324 
1325 		mdb_printf("%-25s = ", extras[i]);
1326 
1327 		/* NB: all the 64-bit extras happen to be byte counts */
1328 		if (sym.st_size == sizeof (uint64_t))
1329 			mdb_printf("%9llu %s\n", buf >> shift, suffix);
1330 
1331 		if (sym.st_size == sizeof (uint32_t))
1332 			mdb_printf("%9d\n", *((uint32_t *)&buf));
1333 	}
1334 	return (DCMD_OK);
1335 }
1336 
1337 typedef struct mdb_spa_print {
1338 	pool_state_t spa_state;
1339 	char spa_name[ZFS_MAX_DATASET_NAME_LEN];
1340 	uintptr_t spa_normal_class;
1341 } mdb_spa_print_t;
1342 
1343 
1344 const char histo_stars[] = "****************************************";
1345 const int histo_width = sizeof (histo_stars) - 1;
1346 
1347 static void
dump_histogram(const uint64_t * histo,int size,int offset)1348 dump_histogram(const uint64_t *histo, int size, int offset)
1349 {
1350 	int i;
1351 	int minidx = size - 1;
1352 	int maxidx = 0;
1353 	uint64_t max = 0;
1354 
1355 	for (i = 0; i < size; i++) {
1356 		if (histo[i] > max)
1357 			max = histo[i];
1358 		if (histo[i] > 0 && i > maxidx)
1359 			maxidx = i;
1360 		if (histo[i] > 0 && i < minidx)
1361 			minidx = i;
1362 	}
1363 
1364 	if (max < histo_width)
1365 		max = histo_width;
1366 
1367 	for (i = minidx; i <= maxidx; i++) {
1368 		mdb_printf("%3u: %6llu %s\n",
1369 		    i + offset, (u_longlong_t)histo[i],
1370 		    &histo_stars[(max - histo[i]) * histo_width / max]);
1371 	}
1372 }
1373 
1374 typedef struct mdb_metaslab_class {
1375 	uint64_t mc_histogram[RANGE_TREE_HISTOGRAM_SIZE];
1376 } mdb_metaslab_class_t;
1377 
1378 /*
1379  * spa_class_histogram(uintptr_t class_addr)
1380  *
1381  * Prints free space histogram for a device class
1382  *
1383  * Returns DCMD_OK, or DCMD_ERR.
1384  */
1385 static int
spa_class_histogram(uintptr_t class_addr)1386 spa_class_histogram(uintptr_t class_addr)
1387 {
1388 	mdb_metaslab_class_t mc;
1389 	if (mdb_ctf_vread(&mc, "metaslab_class_t",
1390 	    "mdb_metaslab_class_t", class_addr, 0) == -1)
1391 		return (DCMD_ERR);
1392 
1393 	mdb_inc_indent(4);
1394 	dump_histogram(mc.mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1395 	mdb_dec_indent(4);
1396 	return (DCMD_OK);
1397 }
1398 
1399 /*
1400  * ::spa
1401  *
1402  *	-c	Print configuration information as well
1403  *	-v	Print vdev state
1404  *	-e	Print vdev error stats
1405  *	-m	Print vdev metaslab info
1406  *	-M	print vdev metaslab group info
1407  *	-h	Print histogram info (must be combined with -m or -M)
1408  *
1409  * Print a summarized spa_t.  When given no arguments, prints out a table of all
1410  * active pools on the system.
1411  */
1412 /* ARGSUSED */
1413 static int
spa_print(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)1414 spa_print(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1415 {
1416 	const char *statetab[] = { "ACTIVE", "EXPORTED", "DESTROYED",
1417 		"SPARE", "L2CACHE", "UNINIT", "UNAVAIL", "POTENTIAL" };
1418 	const char *state;
1419 	int spa_flags = 0;
1420 
1421 	if (mdb_getopts(argc, argv,
1422 	    'c', MDB_OPT_SETBITS, SPA_FLAG_CONFIG, &spa_flags,
1423 	    'v', MDB_OPT_SETBITS, SPA_FLAG_VDEVS, &spa_flags,
1424 	    'e', MDB_OPT_SETBITS, SPA_FLAG_ERRORS, &spa_flags,
1425 	    'M', MDB_OPT_SETBITS, SPA_FLAG_METASLAB_GROUPS, &spa_flags,
1426 	    'm', MDB_OPT_SETBITS, SPA_FLAG_METASLABS, &spa_flags,
1427 	    'h', MDB_OPT_SETBITS, SPA_FLAG_HISTOGRAMS, &spa_flags,
1428 	    NULL) != argc)
1429 		return (DCMD_USAGE);
1430 
1431 	if (!(flags & DCMD_ADDRSPEC)) {
1432 		if (mdb_walk_dcmd("spa", "spa", argc, argv) == -1) {
1433 			mdb_warn("can't walk spa");
1434 			return (DCMD_ERR);
1435 		}
1436 
1437 		return (DCMD_OK);
1438 	}
1439 
1440 	if (flags & DCMD_PIPE_OUT) {
1441 		mdb_printf("%#lr\n", addr);
1442 		return (DCMD_OK);
1443 	}
1444 
1445 	if (DCMD_HDRSPEC(flags))
1446 		mdb_printf("%<u>%-?s %9s %-*s%</u>\n", "ADDR", "STATE",
1447 		    sizeof (uintptr_t) == 4 ? 60 : 52, "NAME");
1448 
1449 	mdb_spa_print_t spa;
1450 	if (mdb_ctf_vread(&spa, "spa_t", "mdb_spa_print_t", addr, 0) == -1)
1451 		return (DCMD_ERR);
1452 
1453 	if (spa.spa_state < 0 || spa.spa_state > POOL_STATE_UNAVAIL)
1454 		state = "UNKNOWN";
1455 	else
1456 		state = statetab[spa.spa_state];
1457 
1458 	mdb_printf("%0?p %9s %s\n", addr, state, spa.spa_name);
1459 	if (spa_flags & SPA_FLAG_HISTOGRAMS)
1460 		spa_class_histogram(spa.spa_normal_class);
1461 
1462 	if (spa_flags & SPA_FLAG_CONFIG) {
1463 		mdb_printf("\n");
1464 		mdb_inc_indent(4);
1465 		if (mdb_call_dcmd("spa_config", addr, flags, 0,
1466 		    NULL) != DCMD_OK)
1467 			return (DCMD_ERR);
1468 		mdb_dec_indent(4);
1469 	}
1470 
1471 	if (spa_flags & SPA_FLAG_ALL_VDEV) {
1472 		mdb_arg_t v;
1473 		char opts[100] = "-";
1474 		int args =
1475 		    (spa_flags | SPA_FLAG_VDEVS) == SPA_FLAG_VDEVS ? 0 : 1;
1476 
1477 		if (spa_flags & SPA_FLAG_ERRORS)
1478 			strcat(opts, "e");
1479 		if (spa_flags & SPA_FLAG_METASLABS)
1480 			strcat(opts, "m");
1481 		if (spa_flags & SPA_FLAG_METASLAB_GROUPS)
1482 			strcat(opts, "M");
1483 		if (spa_flags & SPA_FLAG_HISTOGRAMS)
1484 			strcat(opts, "h");
1485 
1486 		v.a_type = MDB_TYPE_STRING;
1487 		v.a_un.a_str = opts;
1488 
1489 		mdb_printf("\n");
1490 		mdb_inc_indent(4);
1491 		if (mdb_call_dcmd("spa_vdevs", addr, flags, args,
1492 		    &v) != DCMD_OK)
1493 			return (DCMD_ERR);
1494 		mdb_dec_indent(4);
1495 	}
1496 
1497 	return (DCMD_OK);
1498 }
1499 
1500 typedef struct mdb_spa_config_spa {
1501 	uintptr_t spa_config;
1502 } mdb_spa_config_spa_t;
1503 
1504 /*
1505  * ::spa_config
1506  *
1507  * Given a spa_t, print the configuration information stored in spa_config.
1508  * Since it's just an nvlist, format it as an indented list of name=value pairs.
1509  * We simply read the value of spa_config and pass off to ::nvlist.
1510  */
1511 /* ARGSUSED */
1512 static int
spa_print_config(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)1513 spa_print_config(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1514 {
1515 	mdb_spa_config_spa_t spa;
1516 
1517 	if (argc != 0 || !(flags & DCMD_ADDRSPEC))
1518 		return (DCMD_USAGE);
1519 
1520 	if (mdb_ctf_vread(&spa, ZFS_STRUCT "spa", "mdb_spa_config_spa_t",
1521 	    addr, 0) == -1)
1522 		return (DCMD_ERR);
1523 
1524 	if (spa.spa_config == 0) {
1525 		mdb_printf("(none)\n");
1526 		return (DCMD_OK);
1527 	}
1528 
1529 	return (mdb_call_dcmd("nvlist", spa.spa_config, flags,
1530 	    0, NULL));
1531 }
1532 
1533 typedef struct mdb_range_tree {
1534 	struct {
1535 		uint64_t bt_num_elems;
1536 		uint64_t bt_num_nodes;
1537 	} rt_root;
1538 	uint64_t rt_space;
1539 	range_seg_type_t rt_type;
1540 	uint8_t		rt_shift;
1541 	uint64_t	rt_start;
1542 } mdb_range_tree_t;
1543 
1544 typedef struct mdb_metaslab_group {
1545 	uint64_t mg_fragmentation;
1546 	uint64_t mg_histogram[RANGE_TREE_HISTOGRAM_SIZE];
1547 	uintptr_t mg_vd;
1548 } mdb_metaslab_group_t;
1549 
1550 typedef struct mdb_metaslab {
1551 	uint64_t ms_id;
1552 	uint64_t ms_start;
1553 	uint64_t ms_size;
1554 	int64_t ms_deferspace;
1555 	uint64_t ms_fragmentation;
1556 	uint64_t ms_weight;
1557 	uintptr_t ms_allocating[TXG_SIZE];
1558 	uintptr_t ms_checkpointing;
1559 	uintptr_t ms_freeing;
1560 	uintptr_t ms_freed;
1561 	uintptr_t ms_allocatable;
1562 	uintptr_t ms_unflushed_frees;
1563 	uintptr_t ms_unflushed_allocs;
1564 	uintptr_t ms_sm;
1565 } mdb_metaslab_t;
1566 
1567 typedef struct mdb_space_map_phys_t {
1568 	int64_t smp_alloc;
1569 	uint64_t smp_histogram[SPACE_MAP_HISTOGRAM_SIZE];
1570 } mdb_space_map_phys_t;
1571 
1572 typedef struct mdb_space_map {
1573 	uint64_t sm_size;
1574 	uint8_t sm_shift;
1575 	uintptr_t sm_phys;
1576 } mdb_space_map_t;
1577 
1578 typedef struct mdb_vdev {
1579 	uint64_t vdev_id;
1580 	uint64_t vdev_state;
1581 	uintptr_t vdev_ops;
1582 	struct {
1583 		uint64_t vs_aux;
1584 		uint64_t vs_ops[VS_ZIO_TYPES];
1585 		uint64_t vs_bytes[VS_ZIO_TYPES];
1586 		uint64_t vs_read_errors;
1587 		uint64_t vs_write_errors;
1588 		uint64_t vs_checksum_errors;
1589 	} vdev_stat;
1590 	uintptr_t vdev_child;
1591 	uint64_t vdev_children;
1592 	uint64_t vdev_ms_count;
1593 	uintptr_t vdev_mg;
1594 	uintptr_t vdev_ms;
1595 	uintptr_t vdev_path;
1596 } mdb_vdev_t;
1597 
1598 typedef struct mdb_vdev_ops {
1599 	char vdev_op_type[16];
1600 } mdb_vdev_ops_t;
1601 
1602 static int
metaslab_stats(mdb_vdev_t * vd,int spa_flags)1603 metaslab_stats(mdb_vdev_t *vd, int spa_flags)
1604 {
1605 	mdb_inc_indent(4);
1606 	mdb_printf("%<u>%-?s %6s %20s %10s %10s %10s%</u>\n", "ADDR", "ID",
1607 	    "OFFSET", "FREE", "FRAG", "UCMU");
1608 
1609 	uintptr_t *vdev_ms = mdb_alloc(vd->vdev_ms_count * sizeof (vdev_ms),
1610 	    UM_SLEEP | UM_GC);
1611 	if (mdb_vread(vdev_ms, vd->vdev_ms_count * sizeof (uintptr_t),
1612 	    vd->vdev_ms) == -1) {
1613 		mdb_warn("failed to read vdev_ms at %p\n", vd->vdev_ms);
1614 		return (DCMD_ERR);
1615 	}
1616 
1617 	for (int m = 0; m < vd->vdev_ms_count; m++) {
1618 		mdb_metaslab_t ms;
1619 		mdb_space_map_t sm = { 0 };
1620 		mdb_space_map_phys_t smp = { 0 };
1621 		mdb_range_tree_t rt;
1622 		uint64_t uallocs, ufrees, raw_free, raw_uchanges_mem;
1623 		char free[MDB_NICENUM_BUFLEN];
1624 		char uchanges_mem[MDB_NICENUM_BUFLEN];
1625 
1626 		if (mdb_ctf_vread(&ms, "metaslab_t", "mdb_metaslab_t",
1627 		    vdev_ms[m], 0) == -1)
1628 			return (DCMD_ERR);
1629 
1630 		if (ms.ms_sm != 0 &&
1631 		    mdb_ctf_vread(&sm, "space_map_t", "mdb_space_map_t",
1632 		    ms.ms_sm, 0) == -1)
1633 			return (DCMD_ERR);
1634 
1635 		if (mdb_ctf_vread(&rt, "range_tree_t", "mdb_range_tree_t",
1636 		    ms.ms_unflushed_frees, 0) == -1)
1637 			return (DCMD_ERR);
1638 		ufrees = rt.rt_space;
1639 		raw_uchanges_mem = rt.rt_root.bt_num_nodes * BTREE_LEAF_SIZE;
1640 
1641 		if (mdb_ctf_vread(&rt, "range_tree_t", "mdb_range_tree_t",
1642 		    ms.ms_unflushed_allocs, 0) == -1)
1643 			return (DCMD_ERR);
1644 		uallocs = rt.rt_space;
1645 		raw_uchanges_mem += rt.rt_root.bt_num_nodes * BTREE_LEAF_SIZE;
1646 		mdb_nicenum(raw_uchanges_mem, uchanges_mem);
1647 
1648 		raw_free = ms.ms_size;
1649 		if (ms.ms_sm != 0 && sm.sm_phys != 0) {
1650 			(void) mdb_ctf_vread(&smp, "space_map_phys_t",
1651 			    "mdb_space_map_phys_t", sm.sm_phys, 0);
1652 			raw_free -= smp.smp_alloc;
1653 		}
1654 		raw_free += ufrees - uallocs;
1655 		mdb_nicenum(raw_free, free);
1656 
1657 		mdb_printf("%0?p %6llu %20llx %10s ", vdev_ms[m], ms.ms_id,
1658 		    ms.ms_start, free);
1659 		if (ms.ms_fragmentation == ZFS_FRAG_INVALID)
1660 			mdb_printf("%9s ", "-");
1661 		else
1662 			mdb_printf("%9llu%% ", ms.ms_fragmentation);
1663 		mdb_printf("%10s\n", uchanges_mem);
1664 
1665 		if ((spa_flags & SPA_FLAG_HISTOGRAMS) && ms.ms_sm != 0 &&
1666 		    sm.sm_phys != 0) {
1667 			dump_histogram(smp.smp_histogram,
1668 			    SPACE_MAP_HISTOGRAM_SIZE, sm.sm_shift);
1669 		}
1670 	}
1671 	mdb_dec_indent(4);
1672 	return (DCMD_OK);
1673 }
1674 
1675 static int
metaslab_group_stats(mdb_vdev_t * vd,int spa_flags)1676 metaslab_group_stats(mdb_vdev_t *vd, int spa_flags)
1677 {
1678 	mdb_metaslab_group_t mg;
1679 	if (mdb_ctf_vread(&mg, "metaslab_group_t", "mdb_metaslab_group_t",
1680 	    vd->vdev_mg, 0) == -1) {
1681 		mdb_warn("failed to read vdev_mg at %p\n", vd->vdev_mg);
1682 		return (DCMD_ERR);
1683 	}
1684 
1685 	mdb_inc_indent(4);
1686 	mdb_printf("%<u>%-?s %7s %9s%</u>\n", "ADDR", "FRAG", "UCMU");
1687 
1688 	if (mg.mg_fragmentation == ZFS_FRAG_INVALID)
1689 		mdb_printf("%0?p %6s\n", vd->vdev_mg, "-");
1690 	else
1691 		mdb_printf("%0?p %6llu%%", vd->vdev_mg, mg.mg_fragmentation);
1692 
1693 
1694 	uintptr_t *vdev_ms = mdb_alloc(vd->vdev_ms_count * sizeof (vdev_ms),
1695 	    UM_SLEEP | UM_GC);
1696 	if (mdb_vread(vdev_ms, vd->vdev_ms_count * sizeof (uintptr_t),
1697 	    vd->vdev_ms) == -1) {
1698 		mdb_warn("failed to read vdev_ms at %p\n", vd->vdev_ms);
1699 		return (DCMD_ERR);
1700 	}
1701 
1702 	uint64_t raw_uchanges_mem = 0;
1703 	char uchanges_mem[MDB_NICENUM_BUFLEN];
1704 	for (int m = 0; m < vd->vdev_ms_count; m++) {
1705 		mdb_metaslab_t ms;
1706 		mdb_range_tree_t rt;
1707 
1708 		if (mdb_ctf_vread(&ms, "metaslab_t", "mdb_metaslab_t",
1709 		    vdev_ms[m], 0) == -1)
1710 			return (DCMD_ERR);
1711 
1712 		if (mdb_ctf_vread(&rt, "range_tree_t", "mdb_range_tree_t",
1713 		    ms.ms_unflushed_frees, 0) == -1)
1714 			return (DCMD_ERR);
1715 		raw_uchanges_mem += rt.rt_root.bt_num_nodes * BTREE_LEAF_SIZE;
1716 
1717 		if (mdb_ctf_vread(&rt, "range_tree_t", "mdb_range_tree_t",
1718 		    ms.ms_unflushed_allocs, 0) == -1)
1719 			return (DCMD_ERR);
1720 		raw_uchanges_mem += rt.rt_root.bt_num_nodes * BTREE_LEAF_SIZE;
1721 	}
1722 	mdb_nicenum(raw_uchanges_mem, uchanges_mem);
1723 	mdb_printf("%10s\n", uchanges_mem);
1724 
1725 	if (spa_flags & SPA_FLAG_HISTOGRAMS)
1726 		dump_histogram(mg.mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1727 	mdb_dec_indent(4);
1728 	return (DCMD_OK);
1729 }
1730 
1731 /*
1732  * ::vdev
1733  *
1734  * Print out a summarized vdev_t, in the following form:
1735  *
1736  * ADDR             STATE	AUX            DESC
1737  * fffffffbcde23df0 HEALTHY	-              /dev/dsk/c0t0d0
1738  *
1739  * If '-r' is specified, recursively visit all children.
1740  *
1741  * With '-e', the statistics associated with the vdev are printed as well.
1742  */
1743 static int
do_print_vdev(uintptr_t addr,int flags,int depth,boolean_t recursive,int spa_flags)1744 do_print_vdev(uintptr_t addr, int flags, int depth, boolean_t recursive,
1745     int spa_flags)
1746 {
1747 	mdb_vdev_t vd;
1748 	if (mdb_ctf_vread(&vd, "vdev_t", "mdb_vdev_t",
1749 	    (uintptr_t)addr, 0) == -1)
1750 		return (DCMD_ERR);
1751 
1752 	if (flags & DCMD_PIPE_OUT) {
1753 		mdb_printf("%#lr\n", addr);
1754 	} else {
1755 		char desc[MAXNAMELEN];
1756 		if (vd.vdev_path != 0) {
1757 			if (mdb_readstr(desc, sizeof (desc),
1758 			    (uintptr_t)vd.vdev_path) == -1) {
1759 				mdb_warn("failed to read vdev_path at %p\n",
1760 				    vd.vdev_path);
1761 				return (DCMD_ERR);
1762 			}
1763 		} else if (vd.vdev_ops != 0) {
1764 			vdev_ops_t ops;
1765 			if (mdb_vread(&ops, sizeof (ops),
1766 			    (uintptr_t)vd.vdev_ops) == -1) {
1767 				mdb_warn("failed to read vdev_ops at %p\n",
1768 				    vd.vdev_ops);
1769 				return (DCMD_ERR);
1770 			}
1771 			(void) strcpy(desc, ops.vdev_op_type);
1772 		} else {
1773 			(void) strcpy(desc, "<unknown>");
1774 		}
1775 
1776 		if (depth == 0 && DCMD_HDRSPEC(flags))
1777 			mdb_printf("%<u>%-?s %-9s %-12s %-*s%</u>\n",
1778 			    "ADDR", "STATE", "AUX",
1779 			    sizeof (uintptr_t) == 4 ? 43 : 35,
1780 			    "DESCRIPTION");
1781 
1782 		mdb_printf("%0?p ", addr);
1783 
1784 		const char *state, *aux;
1785 		switch (vd.vdev_state) {
1786 		case VDEV_STATE_CLOSED:
1787 			state = "CLOSED";
1788 			break;
1789 		case VDEV_STATE_OFFLINE:
1790 			state = "OFFLINE";
1791 			break;
1792 		case VDEV_STATE_CANT_OPEN:
1793 			state = "CANT_OPEN";
1794 			break;
1795 		case VDEV_STATE_DEGRADED:
1796 			state = "DEGRADED";
1797 			break;
1798 		case VDEV_STATE_HEALTHY:
1799 			state = "HEALTHY";
1800 			break;
1801 		case VDEV_STATE_REMOVED:
1802 			state = "REMOVED";
1803 			break;
1804 		case VDEV_STATE_FAULTED:
1805 			state = "FAULTED";
1806 			break;
1807 		default:
1808 			state = "UNKNOWN";
1809 			break;
1810 		}
1811 
1812 		switch (vd.vdev_stat.vs_aux) {
1813 		case VDEV_AUX_NONE:
1814 			aux = "-";
1815 			break;
1816 		case VDEV_AUX_OPEN_FAILED:
1817 			aux = "OPEN_FAILED";
1818 			break;
1819 		case VDEV_AUX_CORRUPT_DATA:
1820 			aux = "CORRUPT_DATA";
1821 			break;
1822 		case VDEV_AUX_NO_REPLICAS:
1823 			aux = "NO_REPLICAS";
1824 			break;
1825 		case VDEV_AUX_BAD_GUID_SUM:
1826 			aux = "BAD_GUID_SUM";
1827 			break;
1828 		case VDEV_AUX_TOO_SMALL:
1829 			aux = "TOO_SMALL";
1830 			break;
1831 		case VDEV_AUX_BAD_LABEL:
1832 			aux = "BAD_LABEL";
1833 			break;
1834 		case VDEV_AUX_VERSION_NEWER:
1835 			aux = "VERS_NEWER";
1836 			break;
1837 		case VDEV_AUX_VERSION_OLDER:
1838 			aux = "VERS_OLDER";
1839 			break;
1840 		case VDEV_AUX_UNSUP_FEAT:
1841 			aux = "UNSUP_FEAT";
1842 			break;
1843 		case VDEV_AUX_SPARED:
1844 			aux = "SPARED";
1845 			break;
1846 		case VDEV_AUX_ERR_EXCEEDED:
1847 			aux = "ERR_EXCEEDED";
1848 			break;
1849 		case VDEV_AUX_IO_FAILURE:
1850 			aux = "IO_FAILURE";
1851 			break;
1852 		case VDEV_AUX_BAD_LOG:
1853 			aux = "BAD_LOG";
1854 			break;
1855 		case VDEV_AUX_EXTERNAL:
1856 			aux = "EXTERNAL";
1857 			break;
1858 		case VDEV_AUX_SPLIT_POOL:
1859 			aux = "SPLIT_POOL";
1860 			break;
1861 		case VDEV_AUX_CHILDREN_OFFLINE:
1862 			aux = "CHILDREN_OFFLINE";
1863 			break;
1864 		default:
1865 			aux = "UNKNOWN";
1866 			break;
1867 		}
1868 
1869 		mdb_printf("%-9s %-12s %*s%s\n", state, aux, depth, "", desc);
1870 
1871 		if (spa_flags & SPA_FLAG_ERRORS) {
1872 			int i;
1873 
1874 			mdb_inc_indent(4);
1875 			mdb_printf("\n");
1876 			mdb_printf("%<u>       %12s %12s %12s %12s "
1877 			    "%12s%</u>\n", "READ", "WRITE", "FREE", "CLAIM",
1878 			    "IOCTL");
1879 			mdb_printf("OPS     ");
1880 			for (i = 1; i < VS_ZIO_TYPES; i++)
1881 				mdb_printf("%11#llx%s",
1882 				    vd.vdev_stat.vs_ops[i],
1883 				    i == VS_ZIO_TYPES - 1 ? "" : "  ");
1884 			mdb_printf("\n");
1885 			mdb_printf("BYTES   ");
1886 			for (i = 1; i < VS_ZIO_TYPES; i++)
1887 				mdb_printf("%11#llx%s",
1888 				    vd.vdev_stat.vs_bytes[i],
1889 				    i == VS_ZIO_TYPES - 1 ? "" : "  ");
1890 
1891 
1892 			mdb_printf("\n");
1893 			mdb_printf("EREAD    %10#llx\n",
1894 			    vd.vdev_stat.vs_read_errors);
1895 			mdb_printf("EWRITE   %10#llx\n",
1896 			    vd.vdev_stat.vs_write_errors);
1897 			mdb_printf("ECKSUM   %10#llx\n",
1898 			    vd.vdev_stat.vs_checksum_errors);
1899 			mdb_dec_indent(4);
1900 			mdb_printf("\n");
1901 		}
1902 
1903 		if ((spa_flags & SPA_FLAG_METASLAB_GROUPS) &&
1904 		    vd.vdev_mg != 0) {
1905 			metaslab_group_stats(&vd, spa_flags);
1906 		}
1907 		if ((spa_flags & SPA_FLAG_METASLABS) && vd.vdev_ms != 0) {
1908 			metaslab_stats(&vd, spa_flags);
1909 		}
1910 	}
1911 
1912 	uint64_t children = vd.vdev_children;
1913 	if (children == 0 || !recursive)
1914 		return (DCMD_OK);
1915 
1916 	uintptr_t *child = mdb_alloc(children * sizeof (child),
1917 	    UM_SLEEP | UM_GC);
1918 	if (mdb_vread(child, children * sizeof (void *), vd.vdev_child) == -1) {
1919 		mdb_warn("failed to read vdev children at %p", vd.vdev_child);
1920 		return (DCMD_ERR);
1921 	}
1922 
1923 	for (uint64_t c = 0; c < children; c++) {
1924 		if (do_print_vdev(child[c], flags, depth + 2, recursive,
1925 		    spa_flags)) {
1926 			return (DCMD_ERR);
1927 		}
1928 	}
1929 
1930 	return (DCMD_OK);
1931 }
1932 
1933 static int
vdev_print(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)1934 vdev_print(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1935 {
1936 	uint64_t depth = 0;
1937 	boolean_t recursive = B_FALSE;
1938 	int spa_flags = 0;
1939 
1940 	if (mdb_getopts(argc, argv,
1941 	    'e', MDB_OPT_SETBITS, SPA_FLAG_ERRORS, &spa_flags,
1942 	    'm', MDB_OPT_SETBITS, SPA_FLAG_METASLABS, &spa_flags,
1943 	    'M', MDB_OPT_SETBITS, SPA_FLAG_METASLAB_GROUPS, &spa_flags,
1944 	    'h', MDB_OPT_SETBITS, SPA_FLAG_HISTOGRAMS, &spa_flags,
1945 	    'r', MDB_OPT_SETBITS, TRUE, &recursive,
1946 	    'd', MDB_OPT_UINT64, &depth, NULL) != argc)
1947 		return (DCMD_USAGE);
1948 
1949 	if (!(flags & DCMD_ADDRSPEC)) {
1950 		mdb_warn("no vdev_t address given\n");
1951 		return (DCMD_ERR);
1952 	}
1953 
1954 	return (do_print_vdev(addr, flags, (int)depth, recursive, spa_flags));
1955 }
1956 
1957 typedef struct mdb_metaslab_alloc_trace {
1958 	uintptr_t mat_mg;
1959 	uintptr_t mat_msp;
1960 	uint64_t mat_size;
1961 	uint64_t mat_weight;
1962 	uint64_t mat_offset;
1963 	uint32_t mat_dva_id;
1964 	int mat_allocator;
1965 } mdb_metaslab_alloc_trace_t;
1966 
1967 static void
metaslab_print_weight(uint64_t weight)1968 metaslab_print_weight(uint64_t weight)
1969 {
1970 	char buf[100];
1971 
1972 	if (WEIGHT_IS_SPACEBASED(weight)) {
1973 		mdb_nicenum(
1974 		    weight & ~(METASLAB_ACTIVE_MASK | METASLAB_WEIGHT_TYPE),
1975 		    buf);
1976 	} else {
1977 		char size[MDB_NICENUM_BUFLEN];
1978 		mdb_nicenum(1ULL << WEIGHT_GET_INDEX(weight), size);
1979 		(void) mdb_snprintf(buf, sizeof (buf), "%llu x %s",
1980 		    WEIGHT_GET_COUNT(weight), size);
1981 	}
1982 	mdb_printf("%11s ", buf);
1983 }
1984 
1985 /* ARGSUSED */
1986 static int
metaslab_weight(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)1987 metaslab_weight(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1988 {
1989 	uint64_t weight = 0;
1990 	char active;
1991 
1992 	if (argc == 0 && (flags & DCMD_ADDRSPEC)) {
1993 		if (mdb_vread(&weight, sizeof (uint64_t), addr) == -1) {
1994 			mdb_warn("failed to read weight at %p\n", addr);
1995 			return (DCMD_ERR);
1996 		}
1997 	} else if (argc == 1 && !(flags & DCMD_ADDRSPEC)) {
1998 		weight = (argv[0].a_type == MDB_TYPE_IMMEDIATE) ?
1999 		    argv[0].a_un.a_val : mdb_strtoull(argv[0].a_un.a_str);
2000 	} else {
2001 		return (DCMD_USAGE);
2002 	}
2003 
2004 	if (DCMD_HDRSPEC(flags)) {
2005 		mdb_printf("%<u>%-6s %9s %9s%</u>\n",
2006 		    "ACTIVE", "ALGORITHM", "WEIGHT");
2007 	}
2008 
2009 	if (weight & METASLAB_WEIGHT_PRIMARY)
2010 		active = 'P';
2011 	else if (weight & METASLAB_WEIGHT_SECONDARY)
2012 		active = 'S';
2013 	else
2014 		active = '-';
2015 	mdb_printf("%6c %8s ", active,
2016 	    WEIGHT_IS_SPACEBASED(weight) ? "SPACE" : "SEGMENT");
2017 	metaslab_print_weight(weight);
2018 	mdb_printf("\n");
2019 
2020 	return (DCMD_OK);
2021 }
2022 
2023 /* ARGSUSED */
2024 static int
metaslab_trace(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)2025 metaslab_trace(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2026 {
2027 	mdb_metaslab_alloc_trace_t mat;
2028 	mdb_metaslab_group_t mg = { 0 };
2029 	char result_type[100];
2030 
2031 	if (mdb_ctf_vread(&mat, "metaslab_alloc_trace_t",
2032 	    "mdb_metaslab_alloc_trace_t", addr, 0) == -1) {
2033 		return (DCMD_ERR);
2034 	}
2035 
2036 	if (!(flags & DCMD_PIPE_OUT) && DCMD_HDRSPEC(flags)) {
2037 		mdb_printf("%<u>%6s %6s %8s %11s %11s %18s %18s%</u>\n",
2038 		    "MSID", "DVA", "ASIZE", "ALLOCATOR", "WEIGHT", "RESULT",
2039 		    "VDEV");
2040 	}
2041 
2042 	if (mat.mat_msp != 0) {
2043 		mdb_metaslab_t ms;
2044 
2045 		if (mdb_ctf_vread(&ms, "metaslab_t", "mdb_metaslab_t",
2046 		    mat.mat_msp, 0) == -1) {
2047 			return (DCMD_ERR);
2048 		}
2049 		mdb_printf("%6llu ", ms.ms_id);
2050 	} else {
2051 		mdb_printf("%6s ", "-");
2052 	}
2053 
2054 	mdb_printf("%6d %8llx %11llx ", mat.mat_dva_id, mat.mat_size,
2055 	    mat.mat_allocator);
2056 
2057 	metaslab_print_weight(mat.mat_weight);
2058 
2059 	if ((int64_t)mat.mat_offset < 0) {
2060 		if (enum_lookup("enum trace_alloc_type", mat.mat_offset,
2061 		    "TRACE_", sizeof (result_type), result_type) == -1) {
2062 			mdb_warn("Could not find enum for trace_alloc_type");
2063 			return (DCMD_ERR);
2064 		}
2065 		mdb_printf("%18s ", result_type);
2066 	} else {
2067 		mdb_printf("%<b>%18llx%</b> ", mat.mat_offset);
2068 	}
2069 
2070 	if (mat.mat_mg != 0 &&
2071 	    mdb_ctf_vread(&mg, "metaslab_group_t", "mdb_metaslab_group_t",
2072 	    mat.mat_mg, 0) == -1) {
2073 		return (DCMD_ERR);
2074 	}
2075 
2076 	if (mg.mg_vd != 0) {
2077 		mdb_vdev_t vdev;
2078 		char desc[MAXNAMELEN];
2079 
2080 		if (mdb_ctf_vread(&vdev, "vdev_t", "mdb_vdev_t",
2081 		    mg.mg_vd, 0) == -1) {
2082 			return (DCMD_ERR);
2083 		}
2084 
2085 		if (vdev.vdev_path != 0) {
2086 			char path[MAXNAMELEN];
2087 
2088 			if (mdb_readstr(path, sizeof (path),
2089 			    vdev.vdev_path) == -1) {
2090 				mdb_warn("failed to read vdev_path at %p\n",
2091 				    vdev.vdev_path);
2092 				return (DCMD_ERR);
2093 			}
2094 			char *slash;
2095 			if ((slash = strrchr(path, '/')) != NULL) {
2096 				strcpy(desc, slash + 1);
2097 			} else {
2098 				strcpy(desc, path);
2099 			}
2100 		} else if (vdev.vdev_ops != 0) {
2101 			mdb_vdev_ops_t ops;
2102 			if (mdb_ctf_vread(&ops, "vdev_ops_t", "mdb_vdev_ops_t",
2103 			    vdev.vdev_ops, 0) == -1) {
2104 				mdb_warn("failed to read vdev_ops at %p\n",
2105 				    vdev.vdev_ops);
2106 				return (DCMD_ERR);
2107 			}
2108 			(void) mdb_snprintf(desc, sizeof (desc),
2109 			    "%s-%llu", ops.vdev_op_type, vdev.vdev_id);
2110 		} else {
2111 			(void) strcpy(desc, "<unknown>");
2112 		}
2113 		mdb_printf("%18s\n", desc);
2114 	}
2115 
2116 	return (DCMD_OK);
2117 }
2118 
2119 typedef struct metaslab_walk_data {
2120 	uint64_t mw_numvdevs;
2121 	uintptr_t *mw_vdevs;
2122 	int mw_curvdev;
2123 	uint64_t mw_nummss;
2124 	uintptr_t *mw_mss;
2125 	int mw_curms;
2126 } metaslab_walk_data_t;
2127 
2128 static int
metaslab_walk_step(mdb_walk_state_t * wsp)2129 metaslab_walk_step(mdb_walk_state_t *wsp)
2130 {
2131 	metaslab_walk_data_t *mw = wsp->walk_data;
2132 	metaslab_t ms;
2133 	uintptr_t msp;
2134 
2135 	if (mw->mw_curvdev >= mw->mw_numvdevs)
2136 		return (WALK_DONE);
2137 
2138 	if (mw->mw_mss == NULL) {
2139 		uintptr_t mssp;
2140 		uintptr_t vdevp;
2141 
2142 		ASSERT(mw->mw_curms == 0);
2143 		ASSERT(mw->mw_nummss == 0);
2144 
2145 		vdevp = mw->mw_vdevs[mw->mw_curvdev];
2146 		if (GETMEMB(vdevp, "vdev", vdev_ms, mssp) ||
2147 		    GETMEMB(vdevp, "vdev", vdev_ms_count, mw->mw_nummss)) {
2148 			return (WALK_ERR);
2149 		}
2150 
2151 		mw->mw_mss = mdb_alloc(mw->mw_nummss * sizeof (void*),
2152 		    UM_SLEEP | UM_GC);
2153 		if (mdb_vread(mw->mw_mss, mw->mw_nummss * sizeof (void*),
2154 		    mssp) == -1) {
2155 			mdb_warn("failed to read vdev_ms at %p", mssp);
2156 			return (WALK_ERR);
2157 		}
2158 	}
2159 
2160 	if (mw->mw_curms >= mw->mw_nummss) {
2161 		mw->mw_mss = NULL;
2162 		mw->mw_curms = 0;
2163 		mw->mw_nummss = 0;
2164 		mw->mw_curvdev++;
2165 		return (WALK_NEXT);
2166 	}
2167 
2168 	msp = mw->mw_mss[mw->mw_curms];
2169 	if (mdb_vread(&ms, sizeof (metaslab_t), msp) == -1) {
2170 		mdb_warn("failed to read metaslab_t at %p", msp);
2171 		return (WALK_ERR);
2172 	}
2173 
2174 	mw->mw_curms++;
2175 
2176 	return (wsp->walk_callback(msp, &ms, wsp->walk_cbdata));
2177 }
2178 
2179 static int
metaslab_walk_init(mdb_walk_state_t * wsp)2180 metaslab_walk_init(mdb_walk_state_t *wsp)
2181 {
2182 	metaslab_walk_data_t *mw;
2183 	uintptr_t root_vdevp;
2184 	uintptr_t childp;
2185 
2186 	if (wsp->walk_addr == 0) {
2187 		mdb_warn("must supply address of spa_t\n");
2188 		return (WALK_ERR);
2189 	}
2190 
2191 	mw = mdb_zalloc(sizeof (metaslab_walk_data_t), UM_SLEEP | UM_GC);
2192 
2193 	if (GETMEMB(wsp->walk_addr, "spa", spa_root_vdev, root_vdevp) ||
2194 	    GETMEMB(root_vdevp, "vdev", vdev_children, mw->mw_numvdevs) ||
2195 	    GETMEMB(root_vdevp, "vdev", vdev_child, childp)) {
2196 		return (DCMD_ERR);
2197 	}
2198 
2199 	mw->mw_vdevs = mdb_alloc(mw->mw_numvdevs * sizeof (void *),
2200 	    UM_SLEEP | UM_GC);
2201 	if (mdb_vread(mw->mw_vdevs, mw->mw_numvdevs * sizeof (void *),
2202 	    childp) == -1) {
2203 		mdb_warn("failed to read root vdev children at %p", childp);
2204 		return (DCMD_ERR);
2205 	}
2206 
2207 	wsp->walk_data = mw;
2208 
2209 	return (WALK_NEXT);
2210 }
2211 
2212 typedef struct mdb_spa {
2213 	uintptr_t spa_dsl_pool;
2214 	uintptr_t spa_root_vdev;
2215 } mdb_spa_t;
2216 
2217 typedef struct mdb_dsl_pool {
2218 	uintptr_t dp_root_dir;
2219 } mdb_dsl_pool_t;
2220 
2221 typedef struct mdb_dsl_dir {
2222 	uintptr_t dd_dbuf;
2223 	int64_t dd_space_towrite[TXG_SIZE];
2224 } mdb_dsl_dir_t;
2225 
2226 typedef struct mdb_dsl_dir_phys {
2227 	uint64_t dd_used_bytes;
2228 	uint64_t dd_compressed_bytes;
2229 	uint64_t dd_uncompressed_bytes;
2230 } mdb_dsl_dir_phys_t;
2231 
2232 typedef struct space_data {
2233 	uint64_t ms_allocating[TXG_SIZE];
2234 	uint64_t ms_checkpointing;
2235 	uint64_t ms_freeing;
2236 	uint64_t ms_freed;
2237 	uint64_t ms_unflushed_frees;
2238 	uint64_t ms_unflushed_allocs;
2239 	uint64_t ms_allocatable;
2240 	int64_t ms_deferspace;
2241 	uint64_t avail;
2242 } space_data_t;
2243 
2244 /* ARGSUSED */
2245 static int
space_cb(uintptr_t addr,const void * unknown,void * arg)2246 space_cb(uintptr_t addr, const void *unknown, void *arg)
2247 {
2248 	space_data_t *sd = arg;
2249 	mdb_metaslab_t ms;
2250 	mdb_range_tree_t rt;
2251 	mdb_space_map_t sm = { 0 };
2252 	mdb_space_map_phys_t smp = { 0 };
2253 	uint64_t uallocs, ufrees;
2254 	int i;
2255 
2256 	if (mdb_ctf_vread(&ms, "metaslab_t", "mdb_metaslab_t",
2257 	    addr, 0) == -1)
2258 		return (WALK_ERR);
2259 
2260 	for (i = 0; i < TXG_SIZE; i++) {
2261 		if (mdb_ctf_vread(&rt, "range_tree_t",
2262 		    "mdb_range_tree_t", ms.ms_allocating[i], 0) == -1)
2263 			return (WALK_ERR);
2264 		sd->ms_allocating[i] += rt.rt_space;
2265 	}
2266 
2267 	if (mdb_ctf_vread(&rt, "range_tree_t",
2268 	    "mdb_range_tree_t", ms.ms_checkpointing, 0) == -1)
2269 		return (WALK_ERR);
2270 	sd->ms_checkpointing += rt.rt_space;
2271 
2272 	if (mdb_ctf_vread(&rt, "range_tree_t",
2273 	    "mdb_range_tree_t", ms.ms_freeing, 0) == -1)
2274 		return (WALK_ERR);
2275 	sd->ms_freeing += rt.rt_space;
2276 
2277 	if (mdb_ctf_vread(&rt, "range_tree_t",
2278 	    "mdb_range_tree_t", ms.ms_freed, 0) == -1)
2279 		return (WALK_ERR);
2280 	sd->ms_freed += rt.rt_space;
2281 
2282 	if (mdb_ctf_vread(&rt, "range_tree_t",
2283 	    "mdb_range_tree_t", ms.ms_allocatable, 0) == -1)
2284 		return (WALK_ERR);
2285 	sd->ms_allocatable += rt.rt_space;
2286 
2287 	if (mdb_ctf_vread(&rt, "range_tree_t",
2288 	    "mdb_range_tree_t", ms.ms_unflushed_frees, 0) == -1)
2289 		return (WALK_ERR);
2290 	sd->ms_unflushed_frees += rt.rt_space;
2291 	ufrees = rt.rt_space;
2292 
2293 	if (mdb_ctf_vread(&rt, "range_tree_t",
2294 	    "mdb_range_tree_t", ms.ms_unflushed_allocs, 0) == -1)
2295 		return (WALK_ERR);
2296 	sd->ms_unflushed_allocs += rt.rt_space;
2297 	uallocs = rt.rt_space;
2298 
2299 	if (ms.ms_sm != 0 &&
2300 	    mdb_ctf_vread(&sm, "space_map_t",
2301 	    "mdb_space_map_t", ms.ms_sm, 0) == -1)
2302 		return (WALK_ERR);
2303 
2304 	if (sm.sm_phys != 0) {
2305 		(void) mdb_ctf_vread(&smp, "space_map_phys_t",
2306 		    "mdb_space_map_phys_t", sm.sm_phys, 0);
2307 	}
2308 
2309 	sd->ms_deferspace += ms.ms_deferspace;
2310 	sd->avail += sm.sm_size - smp.smp_alloc + ufrees - uallocs;
2311 
2312 	return (WALK_NEXT);
2313 }
2314 
2315 /*
2316  * ::spa_space [-b]
2317  *
2318  * Given a spa_t, print out it's on-disk space usage and in-core
2319  * estimates of future usage.  If -b is given, print space in bytes.
2320  * Otherwise print in megabytes.
2321  */
2322 /* ARGSUSED */
2323 static int
spa_space(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)2324 spa_space(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2325 {
2326 	mdb_spa_t spa;
2327 	mdb_dsl_pool_t dp;
2328 	mdb_dsl_dir_t dd;
2329 	mdb_dmu_buf_impl_t db;
2330 	mdb_dsl_dir_phys_t dsp;
2331 	space_data_t sd;
2332 	int shift = 20;
2333 	char *suffix = "M";
2334 	int bytes = B_FALSE;
2335 
2336 	if (mdb_getopts(argc, argv, 'b', MDB_OPT_SETBITS, TRUE, &bytes, NULL) !=
2337 	    argc)
2338 		return (DCMD_USAGE);
2339 	if (!(flags & DCMD_ADDRSPEC))
2340 		return (DCMD_USAGE);
2341 
2342 	if (bytes) {
2343 		shift = 0;
2344 		suffix = "";
2345 	}
2346 
2347 	if (mdb_ctf_vread(&spa, ZFS_STRUCT "spa", "mdb_spa_t",
2348 	    addr, 0) == -1 ||
2349 	    mdb_ctf_vread(&dp, ZFS_STRUCT "dsl_pool", "mdb_dsl_pool_t",
2350 	    spa.spa_dsl_pool, 0) == -1 ||
2351 	    mdb_ctf_vread(&dd, ZFS_STRUCT "dsl_dir", "mdb_dsl_dir_t",
2352 	    dp.dp_root_dir, 0) == -1 ||
2353 	    mdb_ctf_vread(&db, ZFS_STRUCT "dmu_buf_impl", "mdb_dmu_buf_impl_t",
2354 	    dd.dd_dbuf, 0) == -1 ||
2355 	    mdb_ctf_vread(&dsp, ZFS_STRUCT "dsl_dir_phys",
2356 	    "mdb_dsl_dir_phys_t", db.db.db_data, 0) == -1) {
2357 		return (DCMD_ERR);
2358 	}
2359 
2360 	mdb_printf("dd_space_towrite = %llu%s %llu%s %llu%s %llu%s\n",
2361 	    dd.dd_space_towrite[0] >> shift, suffix,
2362 	    dd.dd_space_towrite[1] >> shift, suffix,
2363 	    dd.dd_space_towrite[2] >> shift, suffix,
2364 	    dd.dd_space_towrite[3] >> shift, suffix);
2365 
2366 	mdb_printf("dd_phys.dd_used_bytes = %llu%s\n",
2367 	    dsp.dd_used_bytes >> shift, suffix);
2368 	mdb_printf("dd_phys.dd_compressed_bytes = %llu%s\n",
2369 	    dsp.dd_compressed_bytes >> shift, suffix);
2370 	mdb_printf("dd_phys.dd_uncompressed_bytes = %llu%s\n",
2371 	    dsp.dd_uncompressed_bytes >> shift, suffix);
2372 
2373 	bzero(&sd, sizeof (sd));
2374 	if (mdb_pwalk("metaslab", space_cb, &sd, addr) != 0) {
2375 		mdb_warn("can't walk metaslabs");
2376 		return (DCMD_ERR);
2377 	}
2378 
2379 	mdb_printf("ms_allocmap = %llu%s %llu%s %llu%s %llu%s\n",
2380 	    sd.ms_allocating[0] >> shift, suffix,
2381 	    sd.ms_allocating[1] >> shift, suffix,
2382 	    sd.ms_allocating[2] >> shift, suffix,
2383 	    sd.ms_allocating[3] >> shift, suffix);
2384 	mdb_printf("ms_checkpointing = %llu%s\n",
2385 	    sd.ms_checkpointing >> shift, suffix);
2386 	mdb_printf("ms_freeing = %llu%s\n",
2387 	    sd.ms_freeing >> shift, suffix);
2388 	mdb_printf("ms_freed = %llu%s\n",
2389 	    sd.ms_freed >> shift, suffix);
2390 	mdb_printf("ms_unflushed_frees = %llu%s\n",
2391 	    sd.ms_unflushed_frees >> shift, suffix);
2392 	mdb_printf("ms_unflushed_allocs = %llu%s\n",
2393 	    sd.ms_unflushed_allocs >> shift, suffix);
2394 	mdb_printf("ms_allocatable = %llu%s\n",
2395 	    sd.ms_allocatable >> shift, suffix);
2396 	mdb_printf("ms_deferspace = %llu%s\n",
2397 	    sd.ms_deferspace >> shift, suffix);
2398 	mdb_printf("current avail = %llu%s\n",
2399 	    sd.avail >> shift, suffix);
2400 
2401 	return (DCMD_OK);
2402 }
2403 
2404 typedef struct mdb_spa_aux_vdev {
2405 	int sav_count;
2406 	uintptr_t sav_vdevs;
2407 } mdb_spa_aux_vdev_t;
2408 
2409 typedef struct mdb_spa_vdevs {
2410 	uintptr_t spa_root_vdev;
2411 	mdb_spa_aux_vdev_t spa_l2cache;
2412 	mdb_spa_aux_vdev_t spa_spares;
2413 } mdb_spa_vdevs_t;
2414 
2415 static int
spa_print_aux(mdb_spa_aux_vdev_t * sav,uint_t flags,mdb_arg_t * v,const char * name)2416 spa_print_aux(mdb_spa_aux_vdev_t *sav, uint_t flags, mdb_arg_t *v,
2417     const char *name)
2418 {
2419 	uintptr_t *aux;
2420 	size_t len;
2421 	int ret, i;
2422 
2423 	/*
2424 	 * Iterate over aux vdevs and print those out as well.  This is a
2425 	 * little annoying because we don't have a root vdev to pass to ::vdev.
2426 	 * Instead, we print a single line and then call it for each child
2427 	 * vdev.
2428 	 */
2429 	if (sav->sav_count != 0) {
2430 		v[1].a_type = MDB_TYPE_STRING;
2431 		v[1].a_un.a_str = "-d";
2432 		v[2].a_type = MDB_TYPE_IMMEDIATE;
2433 		v[2].a_un.a_val = 2;
2434 
2435 		len = sav->sav_count * sizeof (uintptr_t);
2436 		aux = mdb_alloc(len, UM_SLEEP);
2437 		if (mdb_vread(aux, len, sav->sav_vdevs) == -1) {
2438 			mdb_free(aux, len);
2439 			mdb_warn("failed to read l2cache vdevs at %p",
2440 			    sav->sav_vdevs);
2441 			return (DCMD_ERR);
2442 		}
2443 
2444 		mdb_printf("%-?s %-9s %-12s %s\n", "-", "-", "-", name);
2445 
2446 		for (i = 0; i < sav->sav_count; i++) {
2447 			ret = mdb_call_dcmd("vdev", aux[i], flags, 3, v);
2448 			if (ret != DCMD_OK) {
2449 				mdb_free(aux, len);
2450 				return (ret);
2451 			}
2452 		}
2453 
2454 		mdb_free(aux, len);
2455 	}
2456 
2457 	return (0);
2458 }
2459 
2460 /*
2461  * ::spa_vdevs
2462  *
2463  *	-e	Include error stats
2464  *	-m	Include metaslab information
2465  *	-M	Include metaslab group information
2466  *	-h	Include histogram information (requires -m or -M)
2467  *
2468  * Print out a summarized list of vdevs for the given spa_t.
2469  * This is accomplished by invoking "::vdev -re" on the root vdev, as well as
2470  * iterating over the cache devices.
2471  */
2472 /* ARGSUSED */
2473 static int
spa_vdevs(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)2474 spa_vdevs(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2475 {
2476 	mdb_arg_t v[3];
2477 	int ret;
2478 	char opts[100] = "-r";
2479 	int spa_flags = 0;
2480 
2481 	if (mdb_getopts(argc, argv,
2482 	    'e', MDB_OPT_SETBITS, SPA_FLAG_ERRORS, &spa_flags,
2483 	    'm', MDB_OPT_SETBITS, SPA_FLAG_METASLABS, &spa_flags,
2484 	    'M', MDB_OPT_SETBITS, SPA_FLAG_METASLAB_GROUPS, &spa_flags,
2485 	    'h', MDB_OPT_SETBITS, SPA_FLAG_HISTOGRAMS, &spa_flags,
2486 	    NULL) != argc)
2487 		return (DCMD_USAGE);
2488 
2489 	if (!(flags & DCMD_ADDRSPEC))
2490 		return (DCMD_USAGE);
2491 
2492 	mdb_spa_vdevs_t spa;
2493 	if (mdb_ctf_vread(&spa, "spa_t", "mdb_spa_vdevs_t", addr, 0) == -1)
2494 		return (DCMD_ERR);
2495 
2496 	/*
2497 	 * Unitialized spa_t structures can have a NULL root vdev.
2498 	 */
2499 	if (spa.spa_root_vdev == 0) {
2500 		mdb_printf("no associated vdevs\n");
2501 		return (DCMD_OK);
2502 	}
2503 
2504 	if (spa_flags & SPA_FLAG_ERRORS)
2505 		strcat(opts, "e");
2506 	if (spa_flags & SPA_FLAG_METASLABS)
2507 		strcat(opts, "m");
2508 	if (spa_flags & SPA_FLAG_METASLAB_GROUPS)
2509 		strcat(opts, "M");
2510 	if (spa_flags & SPA_FLAG_HISTOGRAMS)
2511 		strcat(opts, "h");
2512 
2513 	v[0].a_type = MDB_TYPE_STRING;
2514 	v[0].a_un.a_str = opts;
2515 
2516 	ret = mdb_call_dcmd("vdev", (uintptr_t)spa.spa_root_vdev,
2517 	    flags, 1, v);
2518 	if (ret != DCMD_OK)
2519 		return (ret);
2520 
2521 	if (spa_print_aux(&spa.spa_l2cache, flags, v, "cache") != 0 ||
2522 	    spa_print_aux(&spa.spa_spares, flags, v, "spares") != 0)
2523 		return (DCMD_ERR);
2524 
2525 	return (DCMD_OK);
2526 }
2527 
2528 /*
2529  * ::zio
2530  *
2531  * Print a summary of zio_t and all its children.  This is intended to display a
2532  * zio tree, and hence we only pick the most important pieces of information for
2533  * the main summary.  More detailed information can always be found by doing a
2534  * '::print zio' on the underlying zio_t.  The columns we display are:
2535  *
2536  *	ADDRESS  TYPE  STAGE  WAITER  TIME_ELAPSED
2537  *
2538  * The 'address' column is indented by one space for each depth level as we
2539  * descend down the tree.
2540  */
2541 
2542 #define	ZIO_MAXINDENT	7
2543 #define	ZIO_MAXWIDTH	(sizeof (uintptr_t) * 2 + ZIO_MAXINDENT)
2544 #define	ZIO_WALK_SELF	0
2545 #define	ZIO_WALK_CHILD	1
2546 #define	ZIO_WALK_PARENT	2
2547 
2548 typedef struct zio_print_args {
2549 	int	zpa_current_depth;
2550 	int	zpa_min_depth;
2551 	int	zpa_max_depth;
2552 	int	zpa_type;
2553 	uint_t	zpa_flags;
2554 } zio_print_args_t;
2555 
2556 typedef struct mdb_zio {
2557 	enum zio_type io_type;
2558 	enum zio_stage io_stage;
2559 	uintptr_t io_waiter;
2560 	uintptr_t io_spa;
2561 	struct {
2562 		struct {
2563 			uintptr_t list_next;
2564 		} list_head;
2565 	} io_parent_list;
2566 	int io_error;
2567 } mdb_zio_t;
2568 
2569 typedef struct mdb_zio_timestamp {
2570 	hrtime_t io_timestamp;
2571 } mdb_zio_timestamp_t;
2572 
2573 static int zio_child_cb(uintptr_t addr, const void *unknown, void *arg);
2574 
2575 static int
zio_print_cb(uintptr_t addr,zio_print_args_t * zpa)2576 zio_print_cb(uintptr_t addr, zio_print_args_t *zpa)
2577 {
2578 	mdb_ctf_id_t type_enum, stage_enum;
2579 	int indent = zpa->zpa_current_depth;
2580 	const char *type, *stage;
2581 	uintptr_t laddr;
2582 	mdb_zio_t zio;
2583 	mdb_zio_timestamp_t zio_timestamp = { 0 };
2584 
2585 	if (mdb_ctf_vread(&zio, ZFS_STRUCT "zio", "mdb_zio_t", addr, 0) == -1)
2586 		return (WALK_ERR);
2587 	(void) mdb_ctf_vread(&zio_timestamp, ZFS_STRUCT "zio",
2588 	    "mdb_zio_timestamp_t", addr, MDB_CTF_VREAD_QUIET);
2589 
2590 	if (indent > ZIO_MAXINDENT)
2591 		indent = ZIO_MAXINDENT;
2592 
2593 	if (mdb_ctf_lookup_by_name("enum zio_type", &type_enum) == -1 ||
2594 	    mdb_ctf_lookup_by_name("enum zio_stage", &stage_enum) == -1) {
2595 		mdb_warn("failed to lookup zio enums");
2596 		return (WALK_ERR);
2597 	}
2598 
2599 	if ((type = mdb_ctf_enum_name(type_enum, zio.io_type)) != NULL)
2600 		type += sizeof ("ZIO_TYPE_") - 1;
2601 	else
2602 		type = "?";
2603 
2604 	if (zio.io_error == 0) {
2605 		stage = mdb_ctf_enum_name(stage_enum, zio.io_stage);
2606 		if (stage != NULL)
2607 			stage += sizeof ("ZIO_STAGE_") - 1;
2608 		else
2609 			stage = "?";
2610 	} else {
2611 		stage = "FAILED";
2612 	}
2613 
2614 	if (zpa->zpa_current_depth >= zpa->zpa_min_depth) {
2615 		if (zpa->zpa_flags & DCMD_PIPE_OUT) {
2616 			mdb_printf("%?p\n", addr);
2617 		} else {
2618 			mdb_printf("%*s%-*p %-5s %-16s ", indent, "",
2619 			    ZIO_MAXWIDTH - indent, addr, type, stage);
2620 			if (zio.io_waiter != 0)
2621 				mdb_printf("%-16lx ", zio.io_waiter);
2622 			else
2623 				mdb_printf("%-16s ", "-");
2624 #ifdef _KERNEL
2625 			if (zio_timestamp.io_timestamp != 0) {
2626 				mdb_printf("%llums", (mdb_gethrtime() -
2627 				    zio_timestamp.io_timestamp) /
2628 				    1000000);
2629 			} else {
2630 				mdb_printf("%-12s ", "-");
2631 			}
2632 #else
2633 			mdb_printf("%-12s ", "-");
2634 #endif
2635 			mdb_printf("\n");
2636 		}
2637 	}
2638 
2639 	if (zpa->zpa_current_depth >= zpa->zpa_max_depth)
2640 		return (WALK_NEXT);
2641 
2642 	if (zpa->zpa_type == ZIO_WALK_PARENT)
2643 		laddr = addr + mdb_ctf_offsetof_by_name(ZFS_STRUCT "zio",
2644 		    "io_parent_list");
2645 	else
2646 		laddr = addr + mdb_ctf_offsetof_by_name(ZFS_STRUCT "zio",
2647 		    "io_child_list");
2648 
2649 	zpa->zpa_current_depth++;
2650 	if (mdb_pwalk("list", zio_child_cb, zpa, laddr) != 0) {
2651 		mdb_warn("failed to walk zio_t children at %p\n", laddr);
2652 		return (WALK_ERR);
2653 	}
2654 	zpa->zpa_current_depth--;
2655 
2656 	return (WALK_NEXT);
2657 }
2658 
2659 /* ARGSUSED */
2660 static int
zio_child_cb(uintptr_t addr,const void * unknown,void * arg)2661 zio_child_cb(uintptr_t addr, const void *unknown, void *arg)
2662 {
2663 	zio_link_t zl;
2664 	uintptr_t ziop;
2665 	zio_print_args_t *zpa = arg;
2666 
2667 	if (mdb_vread(&zl, sizeof (zl), addr) == -1) {
2668 		mdb_warn("failed to read zio_link_t at %p", addr);
2669 		return (WALK_ERR);
2670 	}
2671 
2672 	if (zpa->zpa_type == ZIO_WALK_PARENT)
2673 		ziop = (uintptr_t)zl.zl_parent;
2674 	else
2675 		ziop = (uintptr_t)zl.zl_child;
2676 
2677 	return (zio_print_cb(ziop, zpa));
2678 }
2679 
2680 /* ARGSUSED */
2681 static int
zio_print(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)2682 zio_print(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2683 {
2684 	zio_print_args_t zpa = { 0 };
2685 
2686 	if (!(flags & DCMD_ADDRSPEC))
2687 		return (DCMD_USAGE);
2688 
2689 	if (mdb_getopts(argc, argv,
2690 	    'r', MDB_OPT_SETBITS, INT_MAX, &zpa.zpa_max_depth,
2691 	    'c', MDB_OPT_SETBITS, ZIO_WALK_CHILD, &zpa.zpa_type,
2692 	    'p', MDB_OPT_SETBITS, ZIO_WALK_PARENT, &zpa.zpa_type,
2693 	    NULL) != argc)
2694 		return (DCMD_USAGE);
2695 
2696 	zpa.zpa_flags = flags;
2697 	if (zpa.zpa_max_depth != 0) {
2698 		if (zpa.zpa_type == ZIO_WALK_SELF)
2699 			zpa.zpa_type = ZIO_WALK_CHILD;
2700 	} else if (zpa.zpa_type != ZIO_WALK_SELF) {
2701 		zpa.zpa_min_depth = 1;
2702 		zpa.zpa_max_depth = 1;
2703 	}
2704 
2705 	if (!(flags & DCMD_PIPE_OUT) && DCMD_HDRSPEC(flags)) {
2706 		mdb_printf("%<u>%-*s %-5s %-16s %-16s %-12s%</u>\n",
2707 		    ZIO_MAXWIDTH, "ADDRESS", "TYPE", "STAGE", "WAITER",
2708 		    "TIME_ELAPSED");
2709 	}
2710 
2711 	if (zio_print_cb(addr, &zpa) != WALK_NEXT)
2712 		return (DCMD_ERR);
2713 
2714 	return (DCMD_OK);
2715 }
2716 
2717 /*
2718  * [addr]::zio_state
2719  *
2720  * Print a summary of all zio_t structures on the system, or for a particular
2721  * pool.  This is equivalent to '::walk zio_root | ::zio'.
2722  */
2723 /*ARGSUSED*/
2724 static int
zio_state(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)2725 zio_state(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2726 {
2727 	/*
2728 	 * MDB will remember the last address of the pipeline, so if we don't
2729 	 * zero this we'll end up trying to walk zio structures for a
2730 	 * non-existent spa_t.
2731 	 */
2732 	if (!(flags & DCMD_ADDRSPEC))
2733 		addr = 0;
2734 
2735 	return (mdb_pwalk_dcmd("zio_root", "zio", argc, argv, addr));
2736 }
2737 
2738 
2739 typedef struct mdb_zfs_btree_hdr {
2740 	uintptr_t		bth_parent;
2741 	boolean_t		bth_core;
2742 	/*
2743 	 * For both leaf and core nodes, represents the number of elements in
2744 	 * the node. For core nodes, they will have bth_count + 1 children.
2745 	 */
2746 	uint32_t		bth_count;
2747 } mdb_zfs_btree_hdr_t;
2748 
2749 typedef struct mdb_zfs_btree_core {
2750 	mdb_zfs_btree_hdr_t	btc_hdr;
2751 	uintptr_t		btc_children[BTREE_CORE_ELEMS + 1];
2752 	uint8_t			btc_elems[];
2753 } mdb_zfs_btree_core_t;
2754 
2755 typedef struct mdb_zfs_btree_leaf {
2756 	mdb_zfs_btree_hdr_t	btl_hdr;
2757 	uint8_t			btl_elems[];
2758 } mdb_zfs_btree_leaf_t;
2759 
2760 typedef struct mdb_zfs_btree {
2761 	uintptr_t		bt_root;
2762 	size_t			bt_elem_size;
2763 } mdb_zfs_btree_t;
2764 
2765 typedef struct btree_walk_data {
2766 	mdb_zfs_btree_t		bwd_btree;
2767 	mdb_zfs_btree_hdr_t	*bwd_node;
2768 	uint64_t		bwd_offset; // In units of bt_node_size
2769 } btree_walk_data_t;
2770 
2771 static uintptr_t
btree_leftmost_child(uintptr_t addr,mdb_zfs_btree_hdr_t * buf)2772 btree_leftmost_child(uintptr_t addr, mdb_zfs_btree_hdr_t *buf)
2773 {
2774 	size_t size = offsetof(zfs_btree_core_t, btc_children) +
2775 	    sizeof (uintptr_t);
2776 	for (;;) {
2777 		if (mdb_vread(buf, size, addr) == -1) {
2778 			mdb_warn("failed to read at %p\n", addr);
2779 			return ((uintptr_t)0ULL);
2780 		}
2781 		if (!buf->bth_core)
2782 			return (addr);
2783 		mdb_zfs_btree_core_t *node = (mdb_zfs_btree_core_t *)buf;
2784 		addr = node->btc_children[0];
2785 	}
2786 }
2787 
2788 static int
btree_walk_step(mdb_walk_state_t * wsp)2789 btree_walk_step(mdb_walk_state_t *wsp)
2790 {
2791 	btree_walk_data_t *bwd = wsp->walk_data;
2792 	size_t elem_size = bwd->bwd_btree.bt_elem_size;
2793 	if (wsp->walk_addr == 0ULL)
2794 		return (WALK_DONE);
2795 
2796 	if (!bwd->bwd_node->bth_core) {
2797 		/*
2798 		 * For the first element in a leaf node, read in the full
2799 		 * leaf, since we only had part of it read in before.
2800 		 */
2801 		if (bwd->bwd_offset == 0) {
2802 			if (mdb_vread(bwd->bwd_node, BTREE_LEAF_SIZE,
2803 			    wsp->walk_addr) == -1) {
2804 				mdb_warn("failed to read at %p\n",
2805 				    wsp->walk_addr);
2806 				return (WALK_ERR);
2807 			}
2808 		}
2809 
2810 		int status = wsp->walk_callback((uintptr_t)(wsp->walk_addr +
2811 		    offsetof(mdb_zfs_btree_leaf_t, btl_elems) +
2812 		    bwd->bwd_offset * elem_size), bwd->bwd_node,
2813 		    wsp->walk_cbdata);
2814 		if (status != WALK_NEXT)
2815 			return (status);
2816 		bwd->bwd_offset++;
2817 
2818 		/* Find the next element, if we're at the end of the leaf. */
2819 		while (bwd->bwd_offset == bwd->bwd_node->bth_count) {
2820 			uintptr_t par = bwd->bwd_node->bth_parent;
2821 			uintptr_t cur = wsp->walk_addr;
2822 			wsp->walk_addr = par;
2823 			if (par == 0ULL)
2824 				return (WALK_NEXT);
2825 
2826 			size_t size = sizeof (zfs_btree_core_t) +
2827 			    BTREE_CORE_ELEMS * elem_size;
2828 			if (mdb_vread(bwd->bwd_node, size, wsp->walk_addr) ==
2829 			    -1) {
2830 				mdb_warn("failed to read at %p\n",
2831 				    wsp->walk_addr);
2832 				return (WALK_ERR);
2833 			}
2834 			mdb_zfs_btree_core_t *node =
2835 			    (mdb_zfs_btree_core_t *)bwd->bwd_node;
2836 			int i;
2837 			for (i = 0; i <= bwd->bwd_node->bth_count; i++) {
2838 				if (node->btc_children[i] == cur)
2839 					break;
2840 			}
2841 			if (i > bwd->bwd_node->bth_count) {
2842 				mdb_warn("btree parent/child mismatch at "
2843 				    "%#lx\n", cur);
2844 				return (WALK_ERR);
2845 			}
2846 			bwd->bwd_offset = i;
2847 		}
2848 		return (WALK_NEXT);
2849 	}
2850 
2851 	if (!bwd->bwd_node->bth_core) {
2852 		mdb_warn("Invalid btree node at %#lx\n", wsp->walk_addr);
2853 		return (WALK_ERR);
2854 	}
2855 	mdb_zfs_btree_core_t *node = (mdb_zfs_btree_core_t *)bwd->bwd_node;
2856 	int status = wsp->walk_callback((uintptr_t)(wsp->walk_addr +
2857 	    offsetof(mdb_zfs_btree_core_t, btc_elems) + bwd->bwd_offset *
2858 	    elem_size), bwd->bwd_node, wsp->walk_cbdata);
2859 	if (status != WALK_NEXT)
2860 		return (status);
2861 
2862 	uintptr_t new_child = node->btc_children[bwd->bwd_offset + 1];
2863 	wsp->walk_addr = btree_leftmost_child(new_child, bwd->bwd_node);
2864 	if (wsp->walk_addr == 0ULL)
2865 		return (WALK_ERR);
2866 
2867 	bwd->bwd_offset = 0;
2868 	return (WALK_NEXT);
2869 }
2870 
2871 static int
btree_walk_init(mdb_walk_state_t * wsp)2872 btree_walk_init(mdb_walk_state_t *wsp)
2873 {
2874 	btree_walk_data_t *bwd;
2875 
2876 	if (wsp->walk_addr == 0ULL) {
2877 		mdb_warn("must supply address of zfs_btree_t\n");
2878 		return (WALK_ERR);
2879 	}
2880 
2881 	bwd = mdb_zalloc(sizeof (btree_walk_data_t), UM_SLEEP);
2882 	if (mdb_ctf_vread(&bwd->bwd_btree, "zfs_btree_t", "mdb_zfs_btree_t",
2883 	    wsp->walk_addr, 0) == -1) {
2884 		mdb_free(bwd, sizeof (*bwd));
2885 		return (WALK_ERR);
2886 	}
2887 
2888 	if (bwd->bwd_btree.bt_elem_size == 0) {
2889 		mdb_warn("invalid or uninitialized btree at %#lx\n",
2890 		    wsp->walk_addr);
2891 		mdb_free(bwd, sizeof (*bwd));
2892 		return (WALK_ERR);
2893 	}
2894 
2895 	size_t size = MAX(BTREE_LEAF_SIZE, sizeof (zfs_btree_core_t) +
2896 	    BTREE_CORE_ELEMS * bwd->bwd_btree.bt_elem_size);
2897 	bwd->bwd_node = mdb_zalloc(size, UM_SLEEP);
2898 
2899 	uintptr_t node = (uintptr_t)bwd->bwd_btree.bt_root;
2900 	if (node == 0ULL) {
2901 		wsp->walk_addr = 0ULL;
2902 		wsp->walk_data = bwd;
2903 		return (WALK_NEXT);
2904 	}
2905 	node = btree_leftmost_child(node, bwd->bwd_node);
2906 	if (node == 0ULL) {
2907 		mdb_free(bwd->bwd_node, size);
2908 		mdb_free(bwd, sizeof (*bwd));
2909 		return (WALK_ERR);
2910 	}
2911 	bwd->bwd_offset = 0;
2912 
2913 	wsp->walk_addr = node;
2914 	wsp->walk_data = bwd;
2915 	return (WALK_NEXT);
2916 }
2917 
2918 static void
btree_walk_fini(mdb_walk_state_t * wsp)2919 btree_walk_fini(mdb_walk_state_t *wsp)
2920 {
2921 	btree_walk_data_t *bwd = (btree_walk_data_t *)wsp->walk_data;
2922 
2923 	if (bwd == NULL)
2924 		return;
2925 
2926 	size_t size = MAX(BTREE_LEAF_SIZE, sizeof (zfs_btree_core_t) +
2927 	    BTREE_CORE_ELEMS * bwd->bwd_btree.bt_elem_size);
2928 	if (bwd->bwd_node != NULL)
2929 		mdb_free(bwd->bwd_node, size);
2930 
2931 	mdb_free(bwd, sizeof (*bwd));
2932 }
2933 
2934 typedef struct mdb_multilist {
2935 	uint64_t ml_num_sublists;
2936 	uintptr_t ml_sublists;
2937 } mdb_multilist_t;
2938 
2939 static int
multilist_walk_step(mdb_walk_state_t * wsp)2940 multilist_walk_step(mdb_walk_state_t *wsp)
2941 {
2942 	return (wsp->walk_callback(wsp->walk_addr, wsp->walk_layer,
2943 	    wsp->walk_cbdata));
2944 }
2945 
2946 static int
multilist_walk_init(mdb_walk_state_t * wsp)2947 multilist_walk_init(mdb_walk_state_t *wsp)
2948 {
2949 	mdb_multilist_t ml;
2950 	ssize_t sublist_sz;
2951 	int list_offset;
2952 	size_t i;
2953 
2954 	if (wsp->walk_addr == 0) {
2955 		mdb_warn("must supply address of multilist_t\n");
2956 		return (WALK_ERR);
2957 	}
2958 
2959 	if (mdb_ctf_vread(&ml, "multilist_t", "mdb_multilist_t",
2960 	    wsp->walk_addr, 0) == -1) {
2961 		return (WALK_ERR);
2962 	}
2963 
2964 	if (ml.ml_num_sublists == 0 || ml.ml_sublists == 0) {
2965 		mdb_warn("invalid or uninitialized multilist at %#lx\n",
2966 		    wsp->walk_addr);
2967 		return (WALK_ERR);
2968 	}
2969 
2970 	/* mdb_ctf_sizeof_by_name() will print an error for us */
2971 	sublist_sz = mdb_ctf_sizeof_by_name("multilist_sublist_t");
2972 	if (sublist_sz == -1)
2973 		return (WALK_ERR);
2974 
2975 	/* mdb_ctf_offsetof_by_name will print an error for us */
2976 	list_offset = mdb_ctf_offsetof_by_name("multilist_sublist_t",
2977 	    "mls_list");
2978 	if (list_offset == -1)
2979 		return (WALK_ERR);
2980 
2981 	for (i = 0; i < ml.ml_num_sublists; i++) {
2982 		wsp->walk_addr = ml.ml_sublists + i * sublist_sz + list_offset;
2983 
2984 		if (mdb_layered_walk("list", wsp) == -1) {
2985 			mdb_warn("can't walk multilist sublist");
2986 			return (WALK_ERR);
2987 		}
2988 	}
2989 
2990 	return (WALK_NEXT);
2991 }
2992 
2993 typedef struct mdb_txg_list {
2994 	size_t		tl_offset;
2995 	uintptr_t	tl_head[TXG_SIZE];
2996 } mdb_txg_list_t;
2997 
2998 typedef struct txg_list_walk_data {
2999 	uintptr_t lw_head[TXG_SIZE];
3000 	int	lw_txgoff;
3001 	int	lw_maxoff;
3002 	size_t	lw_offset;
3003 	void	*lw_obj;
3004 } txg_list_walk_data_t;
3005 
3006 static int
txg_list_walk_init_common(mdb_walk_state_t * wsp,int txg,int maxoff)3007 txg_list_walk_init_common(mdb_walk_state_t *wsp, int txg, int maxoff)
3008 {
3009 	txg_list_walk_data_t *lwd;
3010 	mdb_txg_list_t list;
3011 	int i;
3012 
3013 	lwd = mdb_alloc(sizeof (txg_list_walk_data_t), UM_SLEEP | UM_GC);
3014 	if (mdb_ctf_vread(&list, "txg_list_t", "mdb_txg_list_t", wsp->walk_addr,
3015 	    0) == -1) {
3016 		mdb_warn("failed to read txg_list_t at %#lx", wsp->walk_addr);
3017 		return (WALK_ERR);
3018 	}
3019 
3020 	for (i = 0; i < TXG_SIZE; i++)
3021 		lwd->lw_head[i] = list.tl_head[i];
3022 	lwd->lw_offset = list.tl_offset;
3023 	lwd->lw_obj = mdb_alloc(lwd->lw_offset + sizeof (txg_node_t),
3024 	    UM_SLEEP | UM_GC);
3025 	lwd->lw_txgoff = txg;
3026 	lwd->lw_maxoff = maxoff;
3027 
3028 	wsp->walk_addr = lwd->lw_head[lwd->lw_txgoff];
3029 	wsp->walk_data = lwd;
3030 
3031 	return (WALK_NEXT);
3032 }
3033 
3034 static int
txg_list_walk_init(mdb_walk_state_t * wsp)3035 txg_list_walk_init(mdb_walk_state_t *wsp)
3036 {
3037 	return (txg_list_walk_init_common(wsp, 0, TXG_SIZE-1));
3038 }
3039 
3040 static int
txg_list0_walk_init(mdb_walk_state_t * wsp)3041 txg_list0_walk_init(mdb_walk_state_t *wsp)
3042 {
3043 	return (txg_list_walk_init_common(wsp, 0, 0));
3044 }
3045 
3046 static int
txg_list1_walk_init(mdb_walk_state_t * wsp)3047 txg_list1_walk_init(mdb_walk_state_t *wsp)
3048 {
3049 	return (txg_list_walk_init_common(wsp, 1, 1));
3050 }
3051 
3052 static int
txg_list2_walk_init(mdb_walk_state_t * wsp)3053 txg_list2_walk_init(mdb_walk_state_t *wsp)
3054 {
3055 	return (txg_list_walk_init_common(wsp, 2, 2));
3056 }
3057 
3058 static int
txg_list3_walk_init(mdb_walk_state_t * wsp)3059 txg_list3_walk_init(mdb_walk_state_t *wsp)
3060 {
3061 	return (txg_list_walk_init_common(wsp, 3, 3));
3062 }
3063 
3064 static int
txg_list_walk_step(mdb_walk_state_t * wsp)3065 txg_list_walk_step(mdb_walk_state_t *wsp)
3066 {
3067 	txg_list_walk_data_t *lwd = wsp->walk_data;
3068 	uintptr_t addr;
3069 	txg_node_t *node;
3070 	int status;
3071 
3072 	while (wsp->walk_addr == 0 && lwd->lw_txgoff < lwd->lw_maxoff) {
3073 		lwd->lw_txgoff++;
3074 		wsp->walk_addr = lwd->lw_head[lwd->lw_txgoff];
3075 	}
3076 
3077 	if (wsp->walk_addr == 0)
3078 		return (WALK_DONE);
3079 
3080 	addr = wsp->walk_addr - lwd->lw_offset;
3081 
3082 	if (mdb_vread(lwd->lw_obj,
3083 	    lwd->lw_offset + sizeof (txg_node_t), addr) == -1) {
3084 		mdb_warn("failed to read list element at %#lx", addr);
3085 		return (WALK_ERR);
3086 	}
3087 
3088 	status = wsp->walk_callback(addr, lwd->lw_obj, wsp->walk_cbdata);
3089 	node = (txg_node_t *)((uintptr_t)lwd->lw_obj + lwd->lw_offset);
3090 	wsp->walk_addr = (uintptr_t)node->tn_next[lwd->lw_txgoff];
3091 
3092 	return (status);
3093 }
3094 
3095 /*
3096  * ::walk spa
3097  *
3098  * Walk all named spa_t structures in the namespace.  This is nothing more than
3099  * a layered avl walk.
3100  */
3101 static int
spa_walk_init(mdb_walk_state_t * wsp)3102 spa_walk_init(mdb_walk_state_t *wsp)
3103 {
3104 	GElf_Sym sym;
3105 
3106 	if (wsp->walk_addr != 0) {
3107 		mdb_warn("spa walk only supports global walks\n");
3108 		return (WALK_ERR);
3109 	}
3110 
3111 	if (mdb_lookup_by_obj(ZFS_OBJ_NAME, "spa_namespace_avl", &sym) == -1) {
3112 		mdb_warn("failed to find symbol 'spa_namespace_avl'");
3113 		return (WALK_ERR);
3114 	}
3115 
3116 	wsp->walk_addr = (uintptr_t)sym.st_value;
3117 
3118 	if (mdb_layered_walk("avl", wsp) == -1) {
3119 		mdb_warn("failed to walk 'avl'\n");
3120 		return (WALK_ERR);
3121 	}
3122 
3123 	return (WALK_NEXT);
3124 }
3125 
3126 static int
spa_walk_step(mdb_walk_state_t * wsp)3127 spa_walk_step(mdb_walk_state_t *wsp)
3128 {
3129 	return (wsp->walk_callback(wsp->walk_addr, NULL, wsp->walk_cbdata));
3130 }
3131 
3132 /*
3133  * [addr]::walk zio
3134  *
3135  * Walk all active zio_t structures on the system.  This is simply a layered
3136  * walk on top of ::walk zio_cache, with the optional ability to limit the
3137  * structures to a particular pool.
3138  */
3139 static int
zio_walk_init(mdb_walk_state_t * wsp)3140 zio_walk_init(mdb_walk_state_t *wsp)
3141 {
3142 	wsp->walk_data = (void *)wsp->walk_addr;
3143 
3144 	if (mdb_layered_walk("zio_cache", wsp) == -1) {
3145 		mdb_warn("failed to walk 'zio_cache'\n");
3146 		return (WALK_ERR);
3147 	}
3148 
3149 	return (WALK_NEXT);
3150 }
3151 
3152 static int
zio_walk_step(mdb_walk_state_t * wsp)3153 zio_walk_step(mdb_walk_state_t *wsp)
3154 {
3155 	mdb_zio_t zio;
3156 	uintptr_t spa = (uintptr_t)wsp->walk_data;
3157 
3158 	if (mdb_ctf_vread(&zio, ZFS_STRUCT "zio", "mdb_zio_t",
3159 	    wsp->walk_addr, 0) == -1)
3160 		return (WALK_ERR);
3161 
3162 	if (spa != 0 && spa != zio.io_spa)
3163 		return (WALK_NEXT);
3164 
3165 	return (wsp->walk_callback(wsp->walk_addr, &zio, wsp->walk_cbdata));
3166 }
3167 
3168 /*
3169  * [addr]::walk zio_root
3170  *
3171  * Walk only root zio_t structures, optionally for a particular spa_t.
3172  */
3173 static int
zio_walk_root_step(mdb_walk_state_t * wsp)3174 zio_walk_root_step(mdb_walk_state_t *wsp)
3175 {
3176 	mdb_zio_t zio;
3177 	uintptr_t spa = (uintptr_t)wsp->walk_data;
3178 
3179 	if (mdb_ctf_vread(&zio, ZFS_STRUCT "zio", "mdb_zio_t",
3180 	    wsp->walk_addr, 0) == -1)
3181 		return (WALK_ERR);
3182 
3183 	if (spa != 0 && spa != zio.io_spa)
3184 		return (WALK_NEXT);
3185 
3186 	/* If the parent list is not empty, ignore */
3187 	if (zio.io_parent_list.list_head.list_next !=
3188 	    wsp->walk_addr +
3189 	    mdb_ctf_offsetof_by_name(ZFS_STRUCT "zio", "io_parent_list") +
3190 	    mdb_ctf_offsetof_by_name("struct list", "list_head"))
3191 		return (WALK_NEXT);
3192 
3193 	return (wsp->walk_callback(wsp->walk_addr, &zio, wsp->walk_cbdata));
3194 }
3195 
3196 /*
3197  * ::zfs_blkstats
3198  *
3199  *	-v	print verbose per-level information
3200  *
3201  */
3202 static int
zfs_blkstats(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)3203 zfs_blkstats(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
3204 {
3205 	boolean_t verbose = B_FALSE;
3206 	zfs_all_blkstats_t stats;
3207 	dmu_object_type_t t;
3208 	zfs_blkstat_t *tzb;
3209 	uint64_t ditto;
3210 
3211 	if (mdb_getopts(argc, argv,
3212 	    'v', MDB_OPT_SETBITS, TRUE, &verbose,
3213 	    NULL) != argc)
3214 		return (DCMD_USAGE);
3215 
3216 	if (!(flags & DCMD_ADDRSPEC))
3217 		return (DCMD_USAGE);
3218 
3219 	if (GETMEMB(addr, "spa", spa_dsl_pool, addr) ||
3220 	    GETMEMB(addr, "dsl_pool", dp_blkstats, addr) ||
3221 	    mdb_vread(&stats, sizeof (zfs_all_blkstats_t), addr) == -1) {
3222 		mdb_warn("failed to read data at %p;", addr);
3223 		mdb_printf("maybe no stats? run \"zpool scrub\" first.");
3224 		return (DCMD_ERR);
3225 	}
3226 
3227 	tzb = &stats.zab_type[DN_MAX_LEVELS][DMU_OT_TOTAL];
3228 	if (tzb->zb_gangs != 0) {
3229 		mdb_printf("Ganged blocks: %llu\n",
3230 		    (longlong_t)tzb->zb_gangs);
3231 	}
3232 
3233 	ditto = tzb->zb_ditto_2_of_2_samevdev + tzb->zb_ditto_2_of_3_samevdev +
3234 	    tzb->zb_ditto_3_of_3_samevdev;
3235 	if (ditto != 0) {
3236 		mdb_printf("Dittoed blocks on same vdev: %llu\n",
3237 		    (longlong_t)ditto);
3238 	}
3239 
3240 	mdb_printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
3241 	    "\t  avg\t comp\t%%Total\tType\n");
3242 
3243 	for (t = 0; t <= DMU_OT_TOTAL; t++) {
3244 		char csize[MDB_NICENUM_BUFLEN], lsize[MDB_NICENUM_BUFLEN];
3245 		char psize[MDB_NICENUM_BUFLEN], asize[MDB_NICENUM_BUFLEN];
3246 		char avg[MDB_NICENUM_BUFLEN];
3247 		char comp[MDB_NICENUM_BUFLEN], pct[MDB_NICENUM_BUFLEN];
3248 		char typename[64];
3249 		int l;
3250 
3251 
3252 		if (t == DMU_OT_DEFERRED)
3253 			strcpy(typename, "deferred free");
3254 		else if (t == DMU_OT_OTHER)
3255 			strcpy(typename, "other");
3256 		else if (t == DMU_OT_TOTAL)
3257 			strcpy(typename, "Total");
3258 		else if (enum_lookup("enum dmu_object_type",
3259 		    t, "DMU_OT_", sizeof (typename), typename) == -1) {
3260 			mdb_warn("failed to read type name");
3261 			return (DCMD_ERR);
3262 		}
3263 
3264 		if (stats.zab_type[DN_MAX_LEVELS][t].zb_asize == 0)
3265 			continue;
3266 
3267 		for (l = -1; l < DN_MAX_LEVELS; l++) {
3268 			int level = (l == -1 ? DN_MAX_LEVELS : l);
3269 			zfs_blkstat_t *zb = &stats.zab_type[level][t];
3270 
3271 			if (zb->zb_asize == 0)
3272 				continue;
3273 
3274 			/*
3275 			 * Don't print each level unless requested.
3276 			 */
3277 			if (!verbose && level != DN_MAX_LEVELS)
3278 				continue;
3279 
3280 			/*
3281 			 * If all the space is level 0, don't print the
3282 			 * level 0 separately.
3283 			 */
3284 			if (level == 0 && zb->zb_asize ==
3285 			    stats.zab_type[DN_MAX_LEVELS][t].zb_asize)
3286 				continue;
3287 
3288 			mdb_nicenum(zb->zb_count, csize);
3289 			mdb_nicenum(zb->zb_lsize, lsize);
3290 			mdb_nicenum(zb->zb_psize, psize);
3291 			mdb_nicenum(zb->zb_asize, asize);
3292 			mdb_nicenum(zb->zb_asize / zb->zb_count, avg);
3293 			(void) mdb_snprintfrac(comp, MDB_NICENUM_BUFLEN,
3294 			    zb->zb_lsize, zb->zb_psize, 2);
3295 			(void) mdb_snprintfrac(pct, MDB_NICENUM_BUFLEN,
3296 			    100 * zb->zb_asize, tzb->zb_asize, 2);
3297 
3298 			mdb_printf("%6s\t%5s\t%5s\t%5s\t%5s"
3299 			    "\t%5s\t%6s\t",
3300 			    csize, lsize, psize, asize, avg, comp, pct);
3301 
3302 			if (level == DN_MAX_LEVELS)
3303 				mdb_printf("%s\n", typename);
3304 			else
3305 				mdb_printf("  L%d %s\n",
3306 				    level, typename);
3307 		}
3308 	}
3309 
3310 	return (DCMD_OK);
3311 }
3312 
3313 typedef struct mdb_reference {
3314 	uintptr_t ref_holder;
3315 	uintptr_t ref_removed;
3316 	uint64_t ref_number;
3317 } mdb_reference_t;
3318 
3319 /* ARGSUSED */
3320 static int
reference_cb(uintptr_t addr,const void * ignored,void * arg)3321 reference_cb(uintptr_t addr, const void *ignored, void *arg)
3322 {
3323 	mdb_reference_t ref;
3324 	boolean_t holder_is_str = B_FALSE;
3325 	char holder_str[128];
3326 	boolean_t removed = (boolean_t)arg;
3327 
3328 	if (mdb_ctf_vread(&ref, "reference_t", "mdb_reference_t", addr,
3329 	    0) == -1)
3330 		return (DCMD_ERR);
3331 
3332 	if (mdb_readstr(holder_str, sizeof (holder_str),
3333 	    ref.ref_holder) != -1)
3334 		holder_is_str = strisprint(holder_str);
3335 
3336 	if (removed)
3337 		mdb_printf("removed ");
3338 	mdb_printf("reference ");
3339 	if (ref.ref_number != 1)
3340 		mdb_printf("with count=%llu ", ref.ref_number);
3341 	mdb_printf("with tag %lx", ref.ref_holder);
3342 	if (holder_is_str)
3343 		mdb_printf(" \"%s\"", holder_str);
3344 	mdb_printf(", held at:\n");
3345 
3346 	(void) mdb_call_dcmd("whatis", addr, DCMD_ADDRSPEC, 0, NULL);
3347 
3348 	if (removed) {
3349 		mdb_printf("removed at:\n");
3350 		(void) mdb_call_dcmd("whatis", ref.ref_removed,
3351 		    DCMD_ADDRSPEC, 0, NULL);
3352 	}
3353 
3354 	mdb_printf("\n");
3355 
3356 	return (WALK_NEXT);
3357 }
3358 
3359 typedef struct mdb_zfs_refcount {
3360 	uint64_t rc_count;
3361 } mdb_zfs_refcount_t;
3362 
3363 typedef struct mdb_zfs_refcount_removed {
3364 	uint_t rc_removed_count;
3365 } mdb_zfs_refcount_removed_t;
3366 
3367 typedef struct mdb_zfs_refcount_tracked {
3368 	boolean_t rc_tracked;
3369 } mdb_zfs_refcount_tracked_t;
3370 
3371 /* ARGSUSED */
3372 static int
zfs_refcount(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)3373 zfs_refcount(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
3374 {
3375 	mdb_zfs_refcount_t rc;
3376 	mdb_zfs_refcount_removed_t rcr;
3377 	mdb_zfs_refcount_tracked_t rct;
3378 	int off;
3379 	boolean_t released = B_FALSE;
3380 
3381 	if (!(flags & DCMD_ADDRSPEC))
3382 		return (DCMD_USAGE);
3383 
3384 	if (mdb_getopts(argc, argv,
3385 	    'r', MDB_OPT_SETBITS, B_TRUE, &released,
3386 	    NULL) != argc)
3387 		return (DCMD_USAGE);
3388 
3389 	if (mdb_ctf_vread(&rc, "zfs_refcount_t", "mdb_zfs_refcount_t", addr,
3390 	    0) == -1)
3391 		return (DCMD_ERR);
3392 
3393 	if (mdb_ctf_vread(&rcr, "zfs_refcount_t", "mdb_zfs_refcount_removed_t",
3394 	    addr, MDB_CTF_VREAD_QUIET) == -1) {
3395 		mdb_printf("zfs_refcount_t at %p has %llu holds (untracked)\n",
3396 		    addr, (longlong_t)rc.rc_count);
3397 		return (DCMD_OK);
3398 	}
3399 
3400 	if (mdb_ctf_vread(&rct, "zfs_refcount_t", "mdb_zfs_refcount_tracked_t",
3401 	    addr, MDB_CTF_VREAD_QUIET) == -1) {
3402 		/* If this is an old target, it might be tracked. */
3403 		rct.rc_tracked = B_TRUE;
3404 	}
3405 
3406 	mdb_printf("zfs_refcount_t at %p has %llu current holds, "
3407 	    "%llu recently released holds\n",
3408 	    addr, (longlong_t)rc.rc_count, (longlong_t)rcr.rc_removed_count);
3409 
3410 	if (rct.rc_tracked && rc.rc_count > 0)
3411 		mdb_printf("current holds:\n");
3412 	off = mdb_ctf_offsetof_by_name("zfs_refcount_t", "rc_tree");
3413 	if (off == -1)
3414 		return (DCMD_ERR);
3415 	mdb_pwalk("avl", reference_cb, (void *)B_FALSE, addr + off);
3416 
3417 	if (released && rcr.rc_removed_count > 0) {
3418 		mdb_printf("released holds:\n");
3419 
3420 		off = mdb_ctf_offsetof_by_name("zfs_refcount_t", "rc_removed");
3421 		if (off == -1)
3422 			return (DCMD_ERR);
3423 		mdb_pwalk("list", reference_cb, (void *)B_TRUE, addr + off);
3424 	}
3425 
3426 	return (DCMD_OK);
3427 }
3428 
3429 /* ARGSUSED */
3430 static int
sa_attr_table(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)3431 sa_attr_table(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
3432 {
3433 	sa_attr_table_t *table;
3434 	sa_os_t sa_os;
3435 	char *name;
3436 	int i;
3437 
3438 	if (mdb_vread(&sa_os, sizeof (sa_os_t), addr) == -1) {
3439 		mdb_warn("failed to read sa_os at %p", addr);
3440 		return (DCMD_ERR);
3441 	}
3442 
3443 	table = mdb_alloc(sizeof (sa_attr_table_t) * sa_os.sa_num_attrs,
3444 	    UM_SLEEP | UM_GC);
3445 	name = mdb_alloc(MAXPATHLEN, UM_SLEEP | UM_GC);
3446 
3447 	if (mdb_vread(table, sizeof (sa_attr_table_t) * sa_os.sa_num_attrs,
3448 	    (uintptr_t)sa_os.sa_attr_table) == -1) {
3449 		mdb_warn("failed to read sa_os at %p", addr);
3450 		return (DCMD_ERR);
3451 	}
3452 
3453 	mdb_printf("%<u>%-10s %-10s %-10s %-10s %s%</u>\n",
3454 	    "ATTR ID", "REGISTERED", "LENGTH", "BSWAP", "NAME");
3455 	for (i = 0; i != sa_os.sa_num_attrs; i++) {
3456 		mdb_readstr(name, MAXPATHLEN, (uintptr_t)table[i].sa_name);
3457 		mdb_printf("%5x   %8x %8x %8x          %-s\n",
3458 		    (int)table[i].sa_attr, (int)table[i].sa_registered,
3459 		    (int)table[i].sa_length, table[i].sa_byteswap, name);
3460 	}
3461 
3462 	return (DCMD_OK);
3463 }
3464 
3465 static int
sa_get_off_table(uintptr_t addr,uint32_t ** off_tab,int attr_count)3466 sa_get_off_table(uintptr_t addr, uint32_t **off_tab, int attr_count)
3467 {
3468 	uintptr_t idx_table;
3469 
3470 	if (GETMEMB(addr, "sa_idx_tab", sa_idx_tab, idx_table)) {
3471 		mdb_printf("can't find offset table in sa_idx_tab\n");
3472 		return (-1);
3473 	}
3474 
3475 	*off_tab = mdb_alloc(attr_count * sizeof (uint32_t),
3476 	    UM_SLEEP | UM_GC);
3477 
3478 	if (mdb_vread(*off_tab,
3479 	    attr_count * sizeof (uint32_t), idx_table) == -1) {
3480 		mdb_warn("failed to attribute offset table %p", idx_table);
3481 		return (-1);
3482 	}
3483 
3484 	return (DCMD_OK);
3485 }
3486 
3487 /*ARGSUSED*/
3488 static int
sa_attr_print(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)3489 sa_attr_print(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
3490 {
3491 	uint32_t *offset_tab;
3492 	int attr_count;
3493 	uint64_t attr_id;
3494 	uintptr_t attr_addr;
3495 	uintptr_t bonus_tab, spill_tab;
3496 	uintptr_t db_bonus, db_spill;
3497 	uintptr_t os, os_sa;
3498 	uintptr_t db_data;
3499 
3500 	if (argc != 1)
3501 		return (DCMD_USAGE);
3502 
3503 	if (argv[0].a_type == MDB_TYPE_STRING)
3504 		attr_id = mdb_strtoull(argv[0].a_un.a_str);
3505 	else
3506 		return (DCMD_USAGE);
3507 
3508 	if (GETMEMB(addr, "sa_handle", sa_bonus_tab, bonus_tab) ||
3509 	    GETMEMB(addr, "sa_handle", sa_spill_tab, spill_tab) ||
3510 	    GETMEMB(addr, "sa_handle", sa_os, os) ||
3511 	    GETMEMB(addr, "sa_handle", sa_bonus, db_bonus) ||
3512 	    GETMEMB(addr, "sa_handle", sa_spill, db_spill)) {
3513 		mdb_printf("Can't find necessary information in sa_handle "
3514 		    "in sa_handle\n");
3515 		return (DCMD_ERR);
3516 	}
3517 
3518 	if (GETMEMB(os, "objset", os_sa, os_sa)) {
3519 		mdb_printf("Can't find os_sa in objset\n");
3520 		return (DCMD_ERR);
3521 	}
3522 
3523 	if (GETMEMB(os_sa, "sa_os", sa_num_attrs, attr_count)) {
3524 		mdb_printf("Can't find sa_num_attrs\n");
3525 		return (DCMD_ERR);
3526 	}
3527 
3528 	if (attr_id > attr_count) {
3529 		mdb_printf("attribute id number is out of range\n");
3530 		return (DCMD_ERR);
3531 	}
3532 
3533 	if (bonus_tab) {
3534 		if (sa_get_off_table(bonus_tab, &offset_tab,
3535 		    attr_count) == -1) {
3536 			return (DCMD_ERR);
3537 		}
3538 
3539 		if (GETMEMB(db_bonus, "dmu_buf", db_data, db_data)) {
3540 			mdb_printf("can't find db_data in bonus dbuf\n");
3541 			return (DCMD_ERR);
3542 		}
3543 	}
3544 
3545 	if (bonus_tab && !TOC_ATTR_PRESENT(offset_tab[attr_id]) &&
3546 	    spill_tab == 0) {
3547 		mdb_printf("Attribute does not exist\n");
3548 		return (DCMD_ERR);
3549 	} else if (!TOC_ATTR_PRESENT(offset_tab[attr_id]) && spill_tab) {
3550 		if (sa_get_off_table(spill_tab, &offset_tab,
3551 		    attr_count) == -1) {
3552 			return (DCMD_ERR);
3553 		}
3554 		if (GETMEMB(db_spill, "dmu_buf", db_data, db_data)) {
3555 			mdb_printf("can't find db_data in spill dbuf\n");
3556 			return (DCMD_ERR);
3557 		}
3558 		if (!TOC_ATTR_PRESENT(offset_tab[attr_id])) {
3559 			mdb_printf("Attribute does not exist\n");
3560 			return (DCMD_ERR);
3561 		}
3562 	}
3563 	attr_addr = db_data + TOC_OFF(offset_tab[attr_id]);
3564 	mdb_printf("%p\n", attr_addr);
3565 	return (DCMD_OK);
3566 }
3567 
3568 /* ARGSUSED */
3569 static int
zfs_ace_print_common(uintptr_t addr,uint_t flags,uint64_t id,uint32_t access_mask,uint16_t ace_flags,uint16_t ace_type,int verbose)3570 zfs_ace_print_common(uintptr_t addr, uint_t flags,
3571     uint64_t id, uint32_t access_mask, uint16_t ace_flags,
3572     uint16_t ace_type, int verbose)
3573 {
3574 	if (DCMD_HDRSPEC(flags) && !verbose)
3575 		mdb_printf("%<u>%-?s %-8s %-8s %-8s %s%</u>\n",
3576 		    "ADDR", "FLAGS", "MASK", "TYPE", "ID");
3577 
3578 	if (!verbose) {
3579 		mdb_printf("%0?p %-8x %-8x %-8x %-llx\n", addr,
3580 		    ace_flags, access_mask, ace_type, id);
3581 		return (DCMD_OK);
3582 	}
3583 
3584 	switch (ace_flags & ACE_TYPE_FLAGS) {
3585 	case ACE_OWNER:
3586 		mdb_printf("owner@:");
3587 		break;
3588 	case (ACE_IDENTIFIER_GROUP | ACE_GROUP):
3589 		mdb_printf("group@:");
3590 		break;
3591 	case ACE_EVERYONE:
3592 		mdb_printf("everyone@:");
3593 		break;
3594 	case ACE_IDENTIFIER_GROUP:
3595 		mdb_printf("group:%llx:", (u_longlong_t)id);
3596 		break;
3597 	case 0: /* User entry */
3598 		mdb_printf("user:%llx:", (u_longlong_t)id);
3599 		break;
3600 	}
3601 
3602 	/* print out permission mask */
3603 	if (access_mask & ACE_READ_DATA)
3604 		mdb_printf("r");
3605 	else
3606 		mdb_printf("-");
3607 	if (access_mask & ACE_WRITE_DATA)
3608 		mdb_printf("w");
3609 	else
3610 		mdb_printf("-");
3611 	if (access_mask & ACE_EXECUTE)
3612 		mdb_printf("x");
3613 	else
3614 		mdb_printf("-");
3615 	if (access_mask & ACE_APPEND_DATA)
3616 		mdb_printf("p");
3617 	else
3618 		mdb_printf("-");
3619 	if (access_mask & ACE_DELETE)
3620 		mdb_printf("d");
3621 	else
3622 		mdb_printf("-");
3623 	if (access_mask & ACE_DELETE_CHILD)
3624 		mdb_printf("D");
3625 	else
3626 		mdb_printf("-");
3627 	if (access_mask & ACE_READ_ATTRIBUTES)
3628 		mdb_printf("a");
3629 	else
3630 		mdb_printf("-");
3631 	if (access_mask & ACE_WRITE_ATTRIBUTES)
3632 		mdb_printf("A");
3633 	else
3634 		mdb_printf("-");
3635 	if (access_mask & ACE_READ_NAMED_ATTRS)
3636 		mdb_printf("R");
3637 	else
3638 		mdb_printf("-");
3639 	if (access_mask & ACE_WRITE_NAMED_ATTRS)
3640 		mdb_printf("W");
3641 	else
3642 		mdb_printf("-");
3643 	if (access_mask & ACE_READ_ACL)
3644 		mdb_printf("c");
3645 	else
3646 		mdb_printf("-");
3647 	if (access_mask & ACE_WRITE_ACL)
3648 		mdb_printf("C");
3649 	else
3650 		mdb_printf("-");
3651 	if (access_mask & ACE_WRITE_OWNER)
3652 		mdb_printf("o");
3653 	else
3654 		mdb_printf("-");
3655 	if (access_mask & ACE_SYNCHRONIZE)
3656 		mdb_printf("s");
3657 	else
3658 		mdb_printf("-");
3659 
3660 	mdb_printf(":");
3661 
3662 	/* Print out inheritance flags */
3663 	if (ace_flags & ACE_FILE_INHERIT_ACE)
3664 		mdb_printf("f");
3665 	else
3666 		mdb_printf("-");
3667 	if (ace_flags & ACE_DIRECTORY_INHERIT_ACE)
3668 		mdb_printf("d");
3669 	else
3670 		mdb_printf("-");
3671 	if (ace_flags & ACE_INHERIT_ONLY_ACE)
3672 		mdb_printf("i");
3673 	else
3674 		mdb_printf("-");
3675 	if (ace_flags & ACE_NO_PROPAGATE_INHERIT_ACE)
3676 		mdb_printf("n");
3677 	else
3678 		mdb_printf("-");
3679 	if (ace_flags & ACE_SUCCESSFUL_ACCESS_ACE_FLAG)
3680 		mdb_printf("S");
3681 	else
3682 		mdb_printf("-");
3683 	if (ace_flags & ACE_FAILED_ACCESS_ACE_FLAG)
3684 		mdb_printf("F");
3685 	else
3686 		mdb_printf("-");
3687 	if (ace_flags & ACE_INHERITED_ACE)
3688 		mdb_printf("I");
3689 	else
3690 		mdb_printf("-");
3691 
3692 	switch (ace_type) {
3693 	case ACE_ACCESS_ALLOWED_ACE_TYPE:
3694 		mdb_printf(":allow\n");
3695 		break;
3696 	case ACE_ACCESS_DENIED_ACE_TYPE:
3697 		mdb_printf(":deny\n");
3698 		break;
3699 	case ACE_SYSTEM_AUDIT_ACE_TYPE:
3700 		mdb_printf(":audit\n");
3701 		break;
3702 	case ACE_SYSTEM_ALARM_ACE_TYPE:
3703 		mdb_printf(":alarm\n");
3704 		break;
3705 	default:
3706 		mdb_printf(":?\n");
3707 	}
3708 	return (DCMD_OK);
3709 }
3710 
3711 /* ARGSUSED */
3712 static int
zfs_ace_print(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)3713 zfs_ace_print(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
3714 {
3715 	zfs_ace_t zace;
3716 	int verbose = FALSE;
3717 	uint64_t id;
3718 
3719 	if (!(flags & DCMD_ADDRSPEC))
3720 		return (DCMD_USAGE);
3721 
3722 	if (mdb_getopts(argc, argv,
3723 	    'v', MDB_OPT_SETBITS, TRUE, &verbose, TRUE, NULL) != argc)
3724 		return (DCMD_USAGE);
3725 
3726 	if (mdb_vread(&zace, sizeof (zfs_ace_t), addr) == -1) {
3727 		mdb_warn("failed to read zfs_ace_t");
3728 		return (DCMD_ERR);
3729 	}
3730 
3731 	if ((zace.z_hdr.z_flags & ACE_TYPE_FLAGS) == 0 ||
3732 	    (zace.z_hdr.z_flags & ACE_TYPE_FLAGS) == ACE_IDENTIFIER_GROUP)
3733 		id = zace.z_fuid;
3734 	else
3735 		id = -1;
3736 
3737 	return (zfs_ace_print_common(addr, flags, id, zace.z_hdr.z_access_mask,
3738 	    zace.z_hdr.z_flags, zace.z_hdr.z_type, verbose));
3739 }
3740 
3741 /* ARGSUSED */
3742 static int
zfs_ace0_print(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)3743 zfs_ace0_print(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
3744 {
3745 	ace_t ace;
3746 	uint64_t id;
3747 	int verbose = FALSE;
3748 
3749 	if (!(flags & DCMD_ADDRSPEC))
3750 		return (DCMD_USAGE);
3751 
3752 	if (mdb_getopts(argc, argv,
3753 	    'v', MDB_OPT_SETBITS, TRUE, &verbose, TRUE, NULL) != argc)
3754 		return (DCMD_USAGE);
3755 
3756 	if (mdb_vread(&ace, sizeof (ace_t), addr) == -1) {
3757 		mdb_warn("failed to read ace_t");
3758 		return (DCMD_ERR);
3759 	}
3760 
3761 	if ((ace.a_flags & ACE_TYPE_FLAGS) == 0 ||
3762 	    (ace.a_flags & ACE_TYPE_FLAGS) == ACE_IDENTIFIER_GROUP)
3763 		id = ace.a_who;
3764 	else
3765 		id = -1;
3766 
3767 	return (zfs_ace_print_common(addr, flags, id, ace.a_access_mask,
3768 	    ace.a_flags, ace.a_type, verbose));
3769 }
3770 
3771 typedef struct acl_dump_args {
3772 	int a_argc;
3773 	const mdb_arg_t *a_argv;
3774 	uint16_t a_version;
3775 	int a_flags;
3776 } acl_dump_args_t;
3777 
3778 /* ARGSUSED */
3779 static int
acl_aces_cb(uintptr_t addr,const void * unknown,void * arg)3780 acl_aces_cb(uintptr_t addr, const void *unknown, void *arg)
3781 {
3782 	acl_dump_args_t *acl_args = (acl_dump_args_t *)arg;
3783 
3784 	if (acl_args->a_version == 1) {
3785 		if (mdb_call_dcmd("zfs_ace", addr,
3786 		    DCMD_ADDRSPEC|acl_args->a_flags, acl_args->a_argc,
3787 		    acl_args->a_argv) != DCMD_OK) {
3788 			return (WALK_ERR);
3789 		}
3790 	} else {
3791 		if (mdb_call_dcmd("zfs_ace0", addr,
3792 		    DCMD_ADDRSPEC|acl_args->a_flags, acl_args->a_argc,
3793 		    acl_args->a_argv) != DCMD_OK) {
3794 			return (WALK_ERR);
3795 		}
3796 	}
3797 	acl_args->a_flags = DCMD_LOOP;
3798 	return (WALK_NEXT);
3799 }
3800 
3801 /* ARGSUSED */
3802 static int
acl_cb(uintptr_t addr,const void * unknown,void * arg)3803 acl_cb(uintptr_t addr, const void *unknown, void *arg)
3804 {
3805 	acl_dump_args_t *acl_args = (acl_dump_args_t *)arg;
3806 
3807 	if (acl_args->a_version == 1) {
3808 		if (mdb_pwalk("zfs_acl_node_aces", acl_aces_cb,
3809 		    arg, addr) != 0) {
3810 			mdb_warn("can't walk ACEs");
3811 			return (DCMD_ERR);
3812 		}
3813 	} else {
3814 		if (mdb_pwalk("zfs_acl_node_aces0", acl_aces_cb,
3815 		    arg, addr) != 0) {
3816 			mdb_warn("can't walk ACEs");
3817 			return (DCMD_ERR);
3818 		}
3819 	}
3820 	return (WALK_NEXT);
3821 }
3822 
3823 /* ARGSUSED */
3824 static int
zfs_acl_dump(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)3825 zfs_acl_dump(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
3826 {
3827 	zfs_acl_t zacl;
3828 	int verbose = FALSE;
3829 	acl_dump_args_t acl_args;
3830 
3831 	if (!(flags & DCMD_ADDRSPEC))
3832 		return (DCMD_USAGE);
3833 
3834 	if (mdb_getopts(argc, argv,
3835 	    'v', MDB_OPT_SETBITS, TRUE, &verbose, NULL) != argc)
3836 		return (DCMD_USAGE);
3837 
3838 	if (mdb_vread(&zacl, sizeof (zfs_acl_t), addr) == -1) {
3839 		mdb_warn("failed to read zfs_acl_t");
3840 		return (DCMD_ERR);
3841 	}
3842 
3843 	acl_args.a_argc = argc;
3844 	acl_args.a_argv = argv;
3845 	acl_args.a_version = zacl.z_version;
3846 	acl_args.a_flags = DCMD_LOOPFIRST;
3847 
3848 	if (mdb_pwalk("zfs_acl_node", acl_cb, &acl_args, addr) != 0) {
3849 		mdb_warn("can't walk ACL");
3850 		return (DCMD_ERR);
3851 	}
3852 
3853 	return (DCMD_OK);
3854 }
3855 
3856 /* ARGSUSED */
3857 static int
zfs_acl_node_walk_init(mdb_walk_state_t * wsp)3858 zfs_acl_node_walk_init(mdb_walk_state_t *wsp)
3859 {
3860 	if (wsp->walk_addr == 0) {
3861 		mdb_warn("must supply address of zfs_acl_node_t\n");
3862 		return (WALK_ERR);
3863 	}
3864 
3865 	wsp->walk_addr +=
3866 	    mdb_ctf_offsetof_by_name(ZFS_STRUCT "zfs_acl", "z_acl");
3867 
3868 	if (mdb_layered_walk("list", wsp) == -1) {
3869 		mdb_warn("failed to walk 'list'\n");
3870 		return (WALK_ERR);
3871 	}
3872 
3873 	return (WALK_NEXT);
3874 }
3875 
3876 static int
zfs_acl_node_walk_step(mdb_walk_state_t * wsp)3877 zfs_acl_node_walk_step(mdb_walk_state_t *wsp)
3878 {
3879 	zfs_acl_node_t	aclnode;
3880 
3881 	if (mdb_vread(&aclnode, sizeof (zfs_acl_node_t),
3882 	    wsp->walk_addr) == -1) {
3883 		mdb_warn("failed to read zfs_acl_node at %p", wsp->walk_addr);
3884 		return (WALK_ERR);
3885 	}
3886 
3887 	return (wsp->walk_callback(wsp->walk_addr, &aclnode, wsp->walk_cbdata));
3888 }
3889 
3890 typedef struct ace_walk_data {
3891 	int		ace_count;
3892 	int		ace_version;
3893 } ace_walk_data_t;
3894 
3895 static int
zfs_aces_walk_init_common(mdb_walk_state_t * wsp,int version,int ace_count,uintptr_t ace_data)3896 zfs_aces_walk_init_common(mdb_walk_state_t *wsp, int version,
3897     int ace_count, uintptr_t ace_data)
3898 {
3899 	ace_walk_data_t *ace_walk_data;
3900 
3901 	if (wsp->walk_addr == 0) {
3902 		mdb_warn("must supply address of zfs_acl_node_t\n");
3903 		return (WALK_ERR);
3904 	}
3905 
3906 	ace_walk_data = mdb_alloc(sizeof (ace_walk_data_t), UM_SLEEP | UM_GC);
3907 
3908 	ace_walk_data->ace_count = ace_count;
3909 	ace_walk_data->ace_version = version;
3910 
3911 	wsp->walk_addr = ace_data;
3912 	wsp->walk_data = ace_walk_data;
3913 
3914 	return (WALK_NEXT);
3915 }
3916 
3917 static int
zfs_acl_node_aces_walk_init_common(mdb_walk_state_t * wsp,int version)3918 zfs_acl_node_aces_walk_init_common(mdb_walk_state_t *wsp, int version)
3919 {
3920 	static int gotid;
3921 	static mdb_ctf_id_t acl_id;
3922 	int z_ace_count;
3923 	uintptr_t z_acldata;
3924 
3925 	if (!gotid) {
3926 		if (mdb_ctf_lookup_by_name("struct zfs_acl_node",
3927 		    &acl_id) == -1) {
3928 			mdb_warn("couldn't find struct zfs_acl_node");
3929 			return (DCMD_ERR);
3930 		}
3931 		gotid = TRUE;
3932 	}
3933 
3934 	if (GETMEMBID(wsp->walk_addr, &acl_id, z_ace_count, z_ace_count)) {
3935 		return (DCMD_ERR);
3936 	}
3937 	if (GETMEMBID(wsp->walk_addr, &acl_id, z_acldata, z_acldata)) {
3938 		return (DCMD_ERR);
3939 	}
3940 
3941 	return (zfs_aces_walk_init_common(wsp, version,
3942 	    z_ace_count, z_acldata));
3943 }
3944 
3945 /* ARGSUSED */
3946 static int
zfs_acl_node_aces_walk_init(mdb_walk_state_t * wsp)3947 zfs_acl_node_aces_walk_init(mdb_walk_state_t *wsp)
3948 {
3949 	return (zfs_acl_node_aces_walk_init_common(wsp, 1));
3950 }
3951 
3952 /* ARGSUSED */
3953 static int
zfs_acl_node_aces0_walk_init(mdb_walk_state_t * wsp)3954 zfs_acl_node_aces0_walk_init(mdb_walk_state_t *wsp)
3955 {
3956 	return (zfs_acl_node_aces_walk_init_common(wsp, 0));
3957 }
3958 
3959 static int
zfs_aces_walk_step(mdb_walk_state_t * wsp)3960 zfs_aces_walk_step(mdb_walk_state_t *wsp)
3961 {
3962 	ace_walk_data_t *ace_data = wsp->walk_data;
3963 	zfs_ace_t zace;
3964 	ace_t *acep;
3965 	int status;
3966 	int entry_type;
3967 	int allow_type;
3968 	uintptr_t ptr;
3969 
3970 	if (ace_data->ace_count == 0)
3971 		return (WALK_DONE);
3972 
3973 	if (mdb_vread(&zace, sizeof (zfs_ace_t), wsp->walk_addr) == -1) {
3974 		mdb_warn("failed to read zfs_ace_t at %#lx",
3975 		    wsp->walk_addr);
3976 		return (WALK_ERR);
3977 	}
3978 
3979 	switch (ace_data->ace_version) {
3980 	case 0:
3981 		acep = (ace_t *)&zace;
3982 		entry_type = acep->a_flags & ACE_TYPE_FLAGS;
3983 		allow_type = acep->a_type;
3984 		break;
3985 	case 1:
3986 		entry_type = zace.z_hdr.z_flags & ACE_TYPE_FLAGS;
3987 		allow_type = zace.z_hdr.z_type;
3988 		break;
3989 	default:
3990 		return (WALK_ERR);
3991 	}
3992 
3993 	ptr = (uintptr_t)wsp->walk_addr;
3994 	switch (entry_type) {
3995 	case ACE_OWNER:
3996 	case ACE_EVERYONE:
3997 	case (ACE_IDENTIFIER_GROUP | ACE_GROUP):
3998 		ptr += ace_data->ace_version == 0 ?
3999 		    sizeof (ace_t) : sizeof (zfs_ace_hdr_t);
4000 		break;
4001 	case ACE_IDENTIFIER_GROUP:
4002 	default:
4003 		switch (allow_type) {
4004 		case ACE_ACCESS_ALLOWED_OBJECT_ACE_TYPE:
4005 		case ACE_ACCESS_DENIED_OBJECT_ACE_TYPE:
4006 		case ACE_SYSTEM_AUDIT_OBJECT_ACE_TYPE:
4007 		case ACE_SYSTEM_ALARM_OBJECT_ACE_TYPE:
4008 			ptr += ace_data->ace_version == 0 ?
4009 			    sizeof (ace_t) : sizeof (zfs_object_ace_t);
4010 			break;
4011 		default:
4012 			ptr += ace_data->ace_version == 0 ?
4013 			    sizeof (ace_t) : sizeof (zfs_ace_t);
4014 			break;
4015 		}
4016 	}
4017 
4018 	ace_data->ace_count--;
4019 	status = wsp->walk_callback(wsp->walk_addr,
4020 	    (void *)(uintptr_t)&zace, wsp->walk_cbdata);
4021 
4022 	wsp->walk_addr = ptr;
4023 	return (status);
4024 }
4025 
4026 typedef struct mdb_zfs_rrwlock {
4027 	uintptr_t	rr_writer;
4028 	boolean_t	rr_writer_wanted;
4029 } mdb_zfs_rrwlock_t;
4030 
4031 static uint_t rrw_key;
4032 
4033 /* ARGSUSED */
4034 static int
rrwlock(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)4035 rrwlock(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
4036 {
4037 	mdb_zfs_rrwlock_t rrw;
4038 
4039 	if (rrw_key == 0) {
4040 		if (mdb_ctf_readsym(&rrw_key, "uint_t", "rrw_tsd_key", 0) == -1)
4041 			return (DCMD_ERR);
4042 	}
4043 
4044 	if (mdb_ctf_vread(&rrw, "rrwlock_t", "mdb_zfs_rrwlock_t", addr,
4045 	    0) == -1)
4046 		return (DCMD_ERR);
4047 
4048 	if (rrw.rr_writer != 0) {
4049 		mdb_printf("write lock held by thread %lx\n", rrw.rr_writer);
4050 		return (DCMD_OK);
4051 	}
4052 
4053 	if (rrw.rr_writer_wanted) {
4054 		mdb_printf("writer wanted\n");
4055 	}
4056 
4057 	mdb_printf("anonymous references:\n");
4058 	(void) mdb_call_dcmd("zfs_refcount", addr +
4059 	    mdb_ctf_offsetof_by_name(ZFS_STRUCT "rrwlock", "rr_anon_rcount"),
4060 	    DCMD_ADDRSPEC, 0, NULL);
4061 
4062 	mdb_printf("linked references:\n");
4063 	(void) mdb_call_dcmd("zfs_refcount", addr +
4064 	    mdb_ctf_offsetof_by_name(ZFS_STRUCT "rrwlock", "rr_linked_rcount"),
4065 	    DCMD_ADDRSPEC, 0, NULL);
4066 
4067 	/*
4068 	 * XXX This should find references from
4069 	 * "::walk thread | ::tsd -v <rrw_key>", but there is no support
4070 	 * for programmatic consumption of dcmds, so this would be
4071 	 * difficult, potentially requiring reimplementing ::tsd (both
4072 	 * user and kernel versions) in this MDB module.
4073 	 */
4074 
4075 	return (DCMD_OK);
4076 }
4077 
4078 typedef struct mdb_arc_buf_hdr_t {
4079 	uint16_t b_psize;
4080 	uint16_t b_lsize;
4081 	struct {
4082 		uint32_t	b_bufcnt;
4083 		uintptr_t	b_state;
4084 	} b_l1hdr;
4085 } mdb_arc_buf_hdr_t;
4086 
4087 enum arc_cflags {
4088 	ARC_CFLAG_VERBOSE		= 1 << 0,
4089 	ARC_CFLAG_ANON			= 1 << 1,
4090 	ARC_CFLAG_MRU			= 1 << 2,
4091 	ARC_CFLAG_MFU			= 1 << 3,
4092 	ARC_CFLAG_BUFS			= 1 << 4,
4093 };
4094 
4095 typedef struct arc_compression_stats_data {
4096 	GElf_Sym anon_sym;	/* ARC_anon symbol */
4097 	GElf_Sym mru_sym;	/* ARC_mru symbol */
4098 	GElf_Sym mrug_sym;	/* ARC_mru_ghost symbol */
4099 	GElf_Sym mfu_sym;	/* ARC_mfu symbol */
4100 	GElf_Sym mfug_sym;	/* ARC_mfu_ghost symbol */
4101 	GElf_Sym l2c_sym;	/* ARC_l2c_only symbol */
4102 	uint64_t *anon_c_hist;	/* histogram of compressed sizes in anon */
4103 	uint64_t *anon_u_hist;	/* histogram of uncompressed sizes in anon */
4104 	uint64_t *anon_bufs;	/* histogram of buffer counts in anon state */
4105 	uint64_t *mru_c_hist;	/* histogram of compressed sizes in mru */
4106 	uint64_t *mru_u_hist;	/* histogram of uncompressed sizes in mru */
4107 	uint64_t *mru_bufs;	/* histogram of buffer counts in mru */
4108 	uint64_t *mfu_c_hist;	/* histogram of compressed sizes in mfu */
4109 	uint64_t *mfu_u_hist;	/* histogram of uncompressed sizes in mfu */
4110 	uint64_t *mfu_bufs;	/* histogram of buffer counts in mfu */
4111 	uint64_t *all_c_hist;	/* histogram of compressed anon + mru + mfu */
4112 	uint64_t *all_u_hist;	/* histogram of uncompressed anon + mru + mfu */
4113 	uint64_t *all_bufs;	/* histogram of buffer counts in all states  */
4114 	int arc_cflags;		/* arc compression flags, specified by user */
4115 	int hist_nbuckets;	/* number of buckets in each histogram */
4116 
4117 	ulong_t l1hdr_off;	/* offset of b_l1hdr in arc_buf_hdr_t */
4118 } arc_compression_stats_data_t;
4119 
4120 int
highbit64(uint64_t i)4121 highbit64(uint64_t i)
4122 {
4123 	int h = 1;
4124 
4125 	if (i == 0)
4126 		return (0);
4127 	if (i & 0xffffffff00000000ULL) {
4128 		h += 32; i >>= 32;
4129 	}
4130 	if (i & 0xffff0000) {
4131 		h += 16; i >>= 16;
4132 	}
4133 	if (i & 0xff00) {
4134 		h += 8; i >>= 8;
4135 	}
4136 	if (i & 0xf0) {
4137 		h += 4; i >>= 4;
4138 	}
4139 	if (i & 0xc) {
4140 		h += 2; i >>= 2;
4141 	}
4142 	if (i & 0x2) {
4143 		h += 1;
4144 	}
4145 	return (h);
4146 }
4147 
4148 /* ARGSUSED */
4149 static int
arc_compression_stats_cb(uintptr_t addr,const void * unknown,void * arg)4150 arc_compression_stats_cb(uintptr_t addr, const void *unknown, void *arg)
4151 {
4152 	arc_compression_stats_data_t *data = arg;
4153 	arc_flags_t flags;
4154 	mdb_arc_buf_hdr_t hdr;
4155 	int cbucket, ubucket, bufcnt;
4156 
4157 	/*
4158 	 * mdb_ctf_vread() uses the sizeof the target type (e.g.
4159 	 * sizeof (arc_buf_hdr_t) in the target) to read in the entire contents
4160 	 * of the target type into a buffer and then copy the values of the
4161 	 * desired members from the mdb typename (e.g. mdb_arc_buf_hdr_t) from
4162 	 * this buffer. Unfortunately, the way arc_buf_hdr_t is used by zfs,
4163 	 * the actual size allocated by the kernel for arc_buf_hdr_t is often
4164 	 * smaller than `sizeof (arc_buf_hdr_t)` (see the definitions of
4165 	 * l1arc_buf_hdr_t and arc_buf_hdr_t in
4166 	 * usr/src/uts/common/fs/zfs/arc.c). Attempting to read the entire
4167 	 * contents of arc_buf_hdr_t from the target (as mdb_ctf_vread() does)
4168 	 * can cause an error if the allocated size is indeed smaller--it's
4169 	 * possible that the 'missing' trailing members of arc_buf_hdr_t
4170 	 * (l1arc_buf_hdr_t and/or arc_buf_hdr_crypt_t) may fall into unmapped
4171 	 * memory.
4172 	 *
4173 	 * We use the GETMEMB macro instead which performs an mdb_vread()
4174 	 * but only reads enough of the target to retrieve the desired struct
4175 	 * member instead of the entire struct.
4176 	 */
4177 	if (GETMEMB(addr, "arc_buf_hdr", b_flags, flags) == -1)
4178 		return (WALK_ERR);
4179 
4180 	/*
4181 	 * We only count headers that have data loaded in the kernel.
4182 	 * This means an L1 header must be present as well as the data
4183 	 * that corresponds to the L1 header. If there's no L1 header,
4184 	 * we can skip the arc_buf_hdr_t completely. If it's present, we
4185 	 * must look at the ARC state (b_l1hdr.b_state) to determine if
4186 	 * the data is present.
4187 	 */
4188 	if ((flags & ARC_FLAG_HAS_L1HDR) == 0)
4189 		return (WALK_NEXT);
4190 
4191 	if (GETMEMB(addr, "arc_buf_hdr", b_psize, hdr.b_psize) == -1 ||
4192 	    GETMEMB(addr, "arc_buf_hdr", b_lsize, hdr.b_lsize) == -1 ||
4193 	    GETMEMB(addr + data->l1hdr_off, "l1arc_buf_hdr", b_bufcnt,
4194 	    hdr.b_l1hdr.b_bufcnt) == -1 ||
4195 	    GETMEMB(addr + data->l1hdr_off, "l1arc_buf_hdr", b_state,
4196 	    hdr.b_l1hdr.b_state) == -1)
4197 		return (WALK_ERR);
4198 
4199 	/*
4200 	 * Headers in the ghost states, or the l2c_only state don't have
4201 	 * arc buffers linked off of them. Thus, their compressed size
4202 	 * is meaningless, so we skip these from the stats.
4203 	 */
4204 	if (hdr.b_l1hdr.b_state == data->mrug_sym.st_value ||
4205 	    hdr.b_l1hdr.b_state == data->mfug_sym.st_value ||
4206 	    hdr.b_l1hdr.b_state == data->l2c_sym.st_value) {
4207 		return (WALK_NEXT);
4208 	}
4209 
4210 	/*
4211 	 * The physical size (compressed) and logical size
4212 	 * (uncompressed) are in units of SPA_MINBLOCKSIZE. By default,
4213 	 * we use the log2 of this value (rounded down to the nearest
4214 	 * integer) to determine the bucket to assign this header to.
4215 	 * Thus, the histogram is logarithmic with respect to the size
4216 	 * of the header. For example, the following is a mapping of the
4217 	 * bucket numbers and the range of header sizes they correspond to:
4218 	 *
4219 	 *	0: 0 byte headers
4220 	 *	1: 512 byte headers
4221 	 *	2: [1024 - 2048) byte headers
4222 	 *	3: [2048 - 4096) byte headers
4223 	 *	4: [4096 - 8192) byte headers
4224 	 *	5: [8192 - 16394) byte headers
4225 	 *	6: [16384 - 32768) byte headers
4226 	 *	7: [32768 - 65536) byte headers
4227 	 *	8: [65536 - 131072) byte headers
4228 	 *	9: 131072 byte headers
4229 	 *
4230 	 * If the ARC_CFLAG_VERBOSE flag was specified, we use the
4231 	 * physical and logical sizes directly. Thus, the histogram will
4232 	 * no longer be logarithmic; instead it will be linear with
4233 	 * respect to the size of the header. The following is a mapping
4234 	 * of the first many bucket numbers and the header size they
4235 	 * correspond to:
4236 	 *
4237 	 *	0: 0 byte headers
4238 	 *	1: 512 byte headers
4239 	 *	2: 1024 byte headers
4240 	 *	3: 1536 byte headers
4241 	 *	4: 2048 byte headers
4242 	 *	5: 2560 byte headers
4243 	 *	6: 3072 byte headers
4244 	 *
4245 	 * And so on. Keep in mind that a range of sizes isn't used in
4246 	 * the case of linear scale because the headers can only
4247 	 * increment or decrement in sizes of 512 bytes. So, it's not
4248 	 * possible for a header to be sized in between whats listed
4249 	 * above.
4250 	 *
4251 	 * Also, the above mapping values were calculated assuming a
4252 	 * SPA_MINBLOCKSHIFT of 512 bytes and a SPA_MAXBLOCKSIZE of 128K.
4253 	 */
4254 
4255 	if (data->arc_cflags & ARC_CFLAG_VERBOSE) {
4256 		cbucket = hdr.b_psize;
4257 		ubucket = hdr.b_lsize;
4258 	} else {
4259 		cbucket = highbit64(hdr.b_psize);
4260 		ubucket = highbit64(hdr.b_lsize);
4261 	}
4262 
4263 	bufcnt = hdr.b_l1hdr.b_bufcnt;
4264 	if (bufcnt >= data->hist_nbuckets)
4265 		bufcnt = data->hist_nbuckets - 1;
4266 
4267 	/* Ensure we stay within the bounds of the histogram array */
4268 	ASSERT3U(cbucket, <, data->hist_nbuckets);
4269 	ASSERT3U(ubucket, <, data->hist_nbuckets);
4270 
4271 	if (hdr.b_l1hdr.b_state == data->anon_sym.st_value) {
4272 		data->anon_c_hist[cbucket]++;
4273 		data->anon_u_hist[ubucket]++;
4274 		data->anon_bufs[bufcnt]++;
4275 	} else if (hdr.b_l1hdr.b_state == data->mru_sym.st_value) {
4276 		data->mru_c_hist[cbucket]++;
4277 		data->mru_u_hist[ubucket]++;
4278 		data->mru_bufs[bufcnt]++;
4279 	} else if (hdr.b_l1hdr.b_state == data->mfu_sym.st_value) {
4280 		data->mfu_c_hist[cbucket]++;
4281 		data->mfu_u_hist[ubucket]++;
4282 		data->mfu_bufs[bufcnt]++;
4283 	}
4284 
4285 	data->all_c_hist[cbucket]++;
4286 	data->all_u_hist[ubucket]++;
4287 	data->all_bufs[bufcnt]++;
4288 
4289 	return (WALK_NEXT);
4290 }
4291 
4292 /* ARGSUSED */
4293 static int
arc_compression_stats(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)4294 arc_compression_stats(uintptr_t addr, uint_t flags, int argc,
4295     const mdb_arg_t *argv)
4296 {
4297 	arc_compression_stats_data_t data = { 0 };
4298 	unsigned int max_shifted = SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT;
4299 	unsigned int hist_size;
4300 	char range[32];
4301 	int rc = DCMD_OK;
4302 	int off;
4303 
4304 	if (mdb_getopts(argc, argv,
4305 	    'v', MDB_OPT_SETBITS, ARC_CFLAG_VERBOSE, &data.arc_cflags,
4306 	    'a', MDB_OPT_SETBITS, ARC_CFLAG_ANON, &data.arc_cflags,
4307 	    'b', MDB_OPT_SETBITS, ARC_CFLAG_BUFS, &data.arc_cflags,
4308 	    'r', MDB_OPT_SETBITS, ARC_CFLAG_MRU, &data.arc_cflags,
4309 	    'f', MDB_OPT_SETBITS, ARC_CFLAG_MFU, &data.arc_cflags,
4310 	    NULL) != argc)
4311 		return (DCMD_USAGE);
4312 
4313 	if (mdb_lookup_by_obj(ZFS_OBJ_NAME, "ARC_anon", &data.anon_sym) ||
4314 	    mdb_lookup_by_obj(ZFS_OBJ_NAME, "ARC_mru", &data.mru_sym) ||
4315 	    mdb_lookup_by_obj(ZFS_OBJ_NAME, "ARC_mru_ghost", &data.mrug_sym) ||
4316 	    mdb_lookup_by_obj(ZFS_OBJ_NAME, "ARC_mfu", &data.mfu_sym) ||
4317 	    mdb_lookup_by_obj(ZFS_OBJ_NAME, "ARC_mfu_ghost", &data.mfug_sym) ||
4318 	    mdb_lookup_by_obj(ZFS_OBJ_NAME, "ARC_l2c_only", &data.l2c_sym)) {
4319 		mdb_warn("can't find arc state symbol");
4320 		return (DCMD_ERR);
4321 	}
4322 
4323 	/*
4324 	 * Determine the maximum expected size for any header, and use
4325 	 * this to determine the number of buckets needed for each
4326 	 * histogram. If ARC_CFLAG_VERBOSE is specified, this value is
4327 	 * used directly; otherwise the log2 of the maximum size is
4328 	 * used. Thus, if using a log2 scale there's a maximum of 10
4329 	 * possible buckets, while the linear scale (when using
4330 	 * ARC_CFLAG_VERBOSE) has a maximum of 257 buckets.
4331 	 */
4332 	if (data.arc_cflags & ARC_CFLAG_VERBOSE)
4333 		data.hist_nbuckets = max_shifted + 1;
4334 	else
4335 		data.hist_nbuckets = highbit64(max_shifted) + 1;
4336 
4337 	hist_size = sizeof (uint64_t) * data.hist_nbuckets;
4338 
4339 	data.anon_c_hist = mdb_zalloc(hist_size, UM_SLEEP);
4340 	data.anon_u_hist = mdb_zalloc(hist_size, UM_SLEEP);
4341 	data.anon_bufs = mdb_zalloc(hist_size, UM_SLEEP);
4342 
4343 	data.mru_c_hist = mdb_zalloc(hist_size, UM_SLEEP);
4344 	data.mru_u_hist = mdb_zalloc(hist_size, UM_SLEEP);
4345 	data.mru_bufs = mdb_zalloc(hist_size, UM_SLEEP);
4346 
4347 	data.mfu_c_hist = mdb_zalloc(hist_size, UM_SLEEP);
4348 	data.mfu_u_hist = mdb_zalloc(hist_size, UM_SLEEP);
4349 	data.mfu_bufs = mdb_zalloc(hist_size, UM_SLEEP);
4350 
4351 	data.all_c_hist = mdb_zalloc(hist_size, UM_SLEEP);
4352 	data.all_u_hist = mdb_zalloc(hist_size, UM_SLEEP);
4353 	data.all_bufs = mdb_zalloc(hist_size, UM_SLEEP);
4354 
4355 	if ((off = mdb_ctf_offsetof_by_name(ZFS_STRUCT "arc_buf_hdr",
4356 	    "b_l1hdr")) == -1) {
4357 		mdb_warn("could not get offset of b_l1hdr from arc_buf_hdr_t");
4358 		rc = DCMD_ERR;
4359 		goto out;
4360 	}
4361 	data.l1hdr_off = off;
4362 
4363 	if (mdb_walk("arc_buf_hdr_t_full", arc_compression_stats_cb,
4364 	    &data) != 0) {
4365 		mdb_warn("can't walk arc_buf_hdr's");
4366 		rc = DCMD_ERR;
4367 		goto out;
4368 	}
4369 
4370 	if (data.arc_cflags & ARC_CFLAG_VERBOSE) {
4371 		rc = mdb_snprintf(range, sizeof (range),
4372 		    "[n*%llu, (n+1)*%llu)", SPA_MINBLOCKSIZE,
4373 		    SPA_MINBLOCKSIZE);
4374 	} else {
4375 		rc = mdb_snprintf(range, sizeof (range),
4376 		    "[2^(n-1)*%llu, 2^n*%llu)", SPA_MINBLOCKSIZE,
4377 		    SPA_MINBLOCKSIZE);
4378 	}
4379 
4380 	if (rc < 0) {
4381 		/* snprintf failed, abort the dcmd */
4382 		rc = DCMD_ERR;
4383 		goto out;
4384 	} else {
4385 		/* snprintf succeeded above, reset return code */
4386 		rc = DCMD_OK;
4387 	}
4388 
4389 	if (data.arc_cflags & ARC_CFLAG_ANON) {
4390 		if (data.arc_cflags & ARC_CFLAG_BUFS) {
4391 			mdb_printf("Histogram of the number of anon buffers "
4392 			    "that are associated with an arc hdr.\n");
4393 			dump_histogram(data.anon_bufs, data.hist_nbuckets, 0);
4394 			mdb_printf("\n");
4395 		}
4396 		mdb_printf("Histogram of compressed anon buffers.\n"
4397 		    "Each bucket represents buffers of size: %s.\n", range);
4398 		dump_histogram(data.anon_c_hist, data.hist_nbuckets, 0);
4399 		mdb_printf("\n");
4400 
4401 		mdb_printf("Histogram of uncompressed anon buffers.\n"
4402 		    "Each bucket represents buffers of size: %s.\n", range);
4403 		dump_histogram(data.anon_u_hist, data.hist_nbuckets, 0);
4404 		mdb_printf("\n");
4405 	}
4406 
4407 	if (data.arc_cflags & ARC_CFLAG_MRU) {
4408 		if (data.arc_cflags & ARC_CFLAG_BUFS) {
4409 			mdb_printf("Histogram of the number of mru buffers "
4410 			    "that are associated with an arc hdr.\n");
4411 			dump_histogram(data.mru_bufs, data.hist_nbuckets, 0);
4412 			mdb_printf("\n");
4413 		}
4414 		mdb_printf("Histogram of compressed mru buffers.\n"
4415 		    "Each bucket represents buffers of size: %s.\n", range);
4416 		dump_histogram(data.mru_c_hist, data.hist_nbuckets, 0);
4417 		mdb_printf("\n");
4418 
4419 		mdb_printf("Histogram of uncompressed mru buffers.\n"
4420 		    "Each bucket represents buffers of size: %s.\n", range);
4421 		dump_histogram(data.mru_u_hist, data.hist_nbuckets, 0);
4422 		mdb_printf("\n");
4423 	}
4424 
4425 	if (data.arc_cflags & ARC_CFLAG_MFU) {
4426 		if (data.arc_cflags & ARC_CFLAG_BUFS) {
4427 			mdb_printf("Histogram of the number of mfu buffers "
4428 			    "that are associated with an arc hdr.\n");
4429 			dump_histogram(data.mfu_bufs, data.hist_nbuckets, 0);
4430 			mdb_printf("\n");
4431 		}
4432 
4433 		mdb_printf("Histogram of compressed mfu buffers.\n"
4434 		    "Each bucket represents buffers of size: %s.\n", range);
4435 		dump_histogram(data.mfu_c_hist, data.hist_nbuckets, 0);
4436 		mdb_printf("\n");
4437 
4438 		mdb_printf("Histogram of uncompressed mfu buffers.\n"
4439 		    "Each bucket represents buffers of size: %s.\n", range);
4440 		dump_histogram(data.mfu_u_hist, data.hist_nbuckets, 0);
4441 		mdb_printf("\n");
4442 	}
4443 
4444 	if (data.arc_cflags & ARC_CFLAG_BUFS) {
4445 		mdb_printf("Histogram of all buffers that "
4446 		    "are associated with an arc hdr.\n");
4447 		dump_histogram(data.all_bufs, data.hist_nbuckets, 0);
4448 		mdb_printf("\n");
4449 	}
4450 
4451 	mdb_printf("Histogram of all compressed buffers.\n"
4452 	    "Each bucket represents buffers of size: %s.\n", range);
4453 	dump_histogram(data.all_c_hist, data.hist_nbuckets, 0);
4454 	mdb_printf("\n");
4455 
4456 	mdb_printf("Histogram of all uncompressed buffers.\n"
4457 	    "Each bucket represents buffers of size: %s.\n", range);
4458 	dump_histogram(data.all_u_hist, data.hist_nbuckets, 0);
4459 
4460 out:
4461 	mdb_free(data.anon_c_hist, hist_size);
4462 	mdb_free(data.anon_u_hist, hist_size);
4463 	mdb_free(data.anon_bufs, hist_size);
4464 
4465 	mdb_free(data.mru_c_hist, hist_size);
4466 	mdb_free(data.mru_u_hist, hist_size);
4467 	mdb_free(data.mru_bufs, hist_size);
4468 
4469 	mdb_free(data.mfu_c_hist, hist_size);
4470 	mdb_free(data.mfu_u_hist, hist_size);
4471 	mdb_free(data.mfu_bufs, hist_size);
4472 
4473 	mdb_free(data.all_c_hist, hist_size);
4474 	mdb_free(data.all_u_hist, hist_size);
4475 	mdb_free(data.all_bufs, hist_size);
4476 
4477 	return (rc);
4478 }
4479 
4480 typedef struct mdb_range_seg64 {
4481 	uint64_t rs_start;
4482 	uint64_t rs_end;
4483 } mdb_range_seg64_t;
4484 
4485 typedef struct mdb_range_seg32 {
4486 	uint32_t rs_start;
4487 	uint32_t rs_end;
4488 } mdb_range_seg32_t;
4489 
4490 /* ARGSUSED */
4491 static int
range_tree_cb(uintptr_t addr,const void * unknown,void * arg)4492 range_tree_cb(uintptr_t addr, const void *unknown, void *arg)
4493 {
4494 	mdb_range_tree_t *rt = (mdb_range_tree_t *)arg;
4495 	uint64_t start, end;
4496 
4497 	if (rt->rt_type == RANGE_SEG64) {
4498 		mdb_range_seg64_t rs;
4499 
4500 		if (mdb_ctf_vread(&rs, ZFS_STRUCT "range_seg64",
4501 		    "mdb_range_seg64_t", addr, 0) == -1)
4502 			return (DCMD_ERR);
4503 		start = rs.rs_start;
4504 		end = rs.rs_end;
4505 	} else {
4506 		ASSERT3U(rt->rt_type, ==, RANGE_SEG32);
4507 		mdb_range_seg32_t rs;
4508 
4509 		if (mdb_ctf_vread(&rs, ZFS_STRUCT "range_seg32",
4510 		    "mdb_range_seg32_t", addr, 0) == -1)
4511 			return (DCMD_ERR);
4512 		start = ((uint64_t)rs.rs_start << rt->rt_shift) + rt->rt_start;
4513 		end = ((uint64_t)rs.rs_end << rt->rt_shift) + rt->rt_start;
4514 	}
4515 
4516 	mdb_printf("\t[%llx %llx) (length %llx)\n", start, end, end - start);
4517 
4518 	return (0);
4519 }
4520 
4521 /* ARGSUSED */
4522 static int
range_tree(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)4523 range_tree(uintptr_t addr, uint_t flags, int argc,
4524     const mdb_arg_t *argv)
4525 {
4526 	mdb_range_tree_t rt;
4527 	uintptr_t btree_addr;
4528 
4529 	if (!(flags & DCMD_ADDRSPEC))
4530 		return (DCMD_USAGE);
4531 
4532 	if (mdb_ctf_vread(&rt, ZFS_STRUCT "range_tree", "mdb_range_tree_t",
4533 	    addr, 0) == -1)
4534 		return (DCMD_ERR);
4535 
4536 	mdb_printf("%p: range tree of %llu entries, %llu bytes\n",
4537 	    addr, rt.rt_root.bt_num_elems, rt.rt_space);
4538 
4539 	btree_addr = addr +
4540 	    mdb_ctf_offsetof_by_name(ZFS_STRUCT "range_tree", "rt_root");
4541 
4542 	if (mdb_pwalk("zfs_btree", range_tree_cb, &rt, btree_addr) != 0) {
4543 		mdb_warn("can't walk range_tree segments");
4544 		return (DCMD_ERR);
4545 	}
4546 	return (DCMD_OK);
4547 }
4548 
4549 typedef struct mdb_spa_log_sm {
4550 	uint64_t sls_sm_obj;
4551 	uint64_t sls_txg;
4552 	uint64_t sls_nblocks;
4553 	uint64_t sls_mscount;
4554 } mdb_spa_log_sm_t;
4555 
4556 /* ARGSUSED */
4557 static int
logsm_stats_cb(uintptr_t addr,const void * unknown,void * arg)4558 logsm_stats_cb(uintptr_t addr, const void *unknown, void *arg)
4559 {
4560 	mdb_spa_log_sm_t sls;
4561 	if (mdb_ctf_vread(&sls, ZFS_STRUCT "spa_log_sm", "mdb_spa_log_sm_t",
4562 	    addr, 0) == -1)
4563 		return (WALK_ERR);
4564 
4565 	mdb_printf("%7lld %7lld %7lld %7lld\n",
4566 	    sls.sls_txg, sls.sls_nblocks, sls.sls_mscount, sls.sls_sm_obj);
4567 
4568 	return (WALK_NEXT);
4569 }
4570 typedef struct mdb_log_summary_entry {
4571 	uint64_t lse_start;
4572 	uint64_t lse_blkcount;
4573 	uint64_t lse_mscount;
4574 } mdb_log_summary_entry_t;
4575 
4576 /* ARGSUSED */
4577 static int
logsm_summary_cb(uintptr_t addr,const void * unknown,void * arg)4578 logsm_summary_cb(uintptr_t addr, const void *unknown, void *arg)
4579 {
4580 	mdb_log_summary_entry_t lse;
4581 	if (mdb_ctf_vread(&lse, ZFS_STRUCT "log_summary_entry",
4582 	    "mdb_log_summary_entry_t", addr, 0) == -1)
4583 		return (WALK_ERR);
4584 
4585 	mdb_printf("%7lld %7lld %7lld\n",
4586 	    lse.lse_start, lse.lse_blkcount, lse.lse_mscount);
4587 	return (WALK_NEXT);
4588 }
4589 
4590 /* ARGSUSED */
4591 static int
logsm_stats(uintptr_t addr,uint_t flags,int argc,const mdb_arg_t * argv)4592 logsm_stats(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
4593 {
4594 	if (!(flags & DCMD_ADDRSPEC))
4595 		return (DCMD_USAGE);
4596 
4597 	uintptr_t sls_avl_addr = addr +
4598 	    mdb_ctf_offsetof_by_name(ZFS_STRUCT "spa", "spa_sm_logs_by_txg");
4599 	uintptr_t summary_addr = addr +
4600 	    mdb_ctf_offsetof_by_name(ZFS_STRUCT "spa", "spa_log_summary");
4601 
4602 	mdb_printf("Log Entries:\n");
4603 	mdb_printf("%7s %7s %7s %7s\n", "txg", "blk", "ms", "obj");
4604 	if (mdb_pwalk("avl", logsm_stats_cb, NULL, sls_avl_addr) != 0)
4605 		return (DCMD_ERR);
4606 
4607 	mdb_printf("\nSummary Entries:\n");
4608 	mdb_printf("%7s %7s %7s\n", "txg", "blk", "ms");
4609 	if (mdb_pwalk("list", logsm_summary_cb, NULL, summary_addr) != 0)
4610 		return (DCMD_ERR);
4611 
4612 	return (DCMD_OK);
4613 }
4614 
4615 /*
4616  * MDB module linkage information:
4617  *
4618  * We declare a list of structures describing our dcmds, and a function
4619  * named _mdb_init to return a pointer to our module information.
4620  */
4621 
4622 static const mdb_dcmd_t dcmds[] = {
4623 	{ "arc", "[-bkmg]", "print ARC variables", arc_print },
4624 	{ "blkptr", ":", "print blkptr_t", blkptr },
4625 	{ "dva", ":", "print dva_t", dva },
4626 	{ "dbuf", ":", "print dmu_buf_impl_t", dbuf },
4627 	{ "dbuf_stats", ":", "dbuf stats", dbuf_stats },
4628 	{ "dbufs",
4629 	    "\t[-O objset_t*] [-n objset_name | \"mos\"] "
4630 	    "[-o object | \"mdn\"] \n"
4631 	    "\t[-l level] [-b blkid | \"bonus\"]",
4632 	    "find dmu_buf_impl_t's that match specified criteria", dbufs },
4633 	{ "abuf_find", "dva_word[0] dva_word[1]",
4634 	    "find arc_buf_hdr_t of a specified DVA",
4635 	    abuf_find },
4636 	{ "logsm_stats", ":", "print log space map statistics of a spa_t",
4637 	    logsm_stats},
4638 	{ "spa", "?[-cevmMh]\n"
4639 	    "\t-c display spa config\n"
4640 	    "\t-e display vdev statistics\n"
4641 	    "\t-v display vdev information\n"
4642 	    "\t-m display metaslab statistics\n"
4643 	    "\t-M display metaslab group statistics\n"
4644 	    "\t-h display histogram (requires -m or -M)\n",
4645 	    "spa_t summary", spa_print },
4646 	{ "spa_config", ":", "print spa_t configuration", spa_print_config },
4647 	{ "spa_space", ":[-b]", "print spa_t on-disk space usage", spa_space },
4648 	{ "spa_vdevs", ":[-emMh]\n"
4649 	    "\t-e display vdev statistics\n"
4650 	    "\t-m dispaly metaslab statistics\n"
4651 	    "\t-M display metaslab group statistic\n"
4652 	    "\t-h display histogram (requires -m or -M)\n",
4653 	    "given a spa_t, print vdev summary", spa_vdevs },
4654 	{ "sm_entries", "<buffer length in bytes>",
4655 	    "print out space map entries from a buffer decoded",
4656 	    sm_entries},
4657 	{ "vdev", ":[-remMh]\n"
4658 	    "\t-r display recursively\n"
4659 	    "\t-e display statistics\n"
4660 	    "\t-m display metaslab statistics (top level vdev only)\n"
4661 	    "\t-M display metaslab group statistics (top level vdev only)\n"
4662 	    "\t-h display histogram (requires -m or -M)\n",
4663 	    "vdev_t summary", vdev_print },
4664 	{ "zio", ":[-cpr]\n"
4665 	    "\t-c display children\n"
4666 	    "\t-p display parents\n"
4667 	    "\t-r display recursively",
4668 	    "zio_t summary", zio_print },
4669 	{ "zio_state", "?", "print out all zio_t structures on system or "
4670 	    "for a particular pool", zio_state },
4671 	{ "zfs_blkstats", ":[-v]",
4672 	    "given a spa_t, print block type stats from last scrub",
4673 	    zfs_blkstats },
4674 	{ "zfs_params", "", "print zfs tunable parameters", zfs_params },
4675 	{ "zfs_refcount", ":[-r]\n"
4676 	    "\t-r display recently removed references",
4677 	    "print zfs_refcount_t holders", zfs_refcount },
4678 	{ "zap_leaf", "", "print zap_leaf_phys_t", zap_leaf },
4679 	{ "zfs_aces", ":[-v]", "print all ACEs from a zfs_acl_t",
4680 	    zfs_acl_dump },
4681 	{ "zfs_ace", ":[-v]", "print zfs_ace", zfs_ace_print },
4682 	{ "zfs_ace0", ":[-v]", "print zfs_ace0", zfs_ace0_print },
4683 	{ "sa_attr_table", ":", "print SA attribute table from sa_os_t",
4684 	    sa_attr_table},
4685 	{ "sa_attr", ": attr_id",
4686 	    "print SA attribute address when given sa_handle_t", sa_attr_print},
4687 	{ "zfs_dbgmsg", ":[-artTvw]",
4688 	    "print zfs debug log", dbgmsg, dbgmsg_help},
4689 	{ "rrwlock", ":",
4690 	    "print rrwlock_t, including readers", rrwlock},
4691 	{ "metaslab_weight", "weight",
4692 	    "print metaslab weight", metaslab_weight},
4693 	{ "metaslab_trace", ":",
4694 	    "print metaslab allocation trace records", metaslab_trace},
4695 	{ "arc_compression_stats", ":[-vabrf]\n"
4696 	    "\t-v verbose, display a linearly scaled histogram\n"
4697 	    "\t-a display ARC_anon state statistics individually\n"
4698 	    "\t-r display ARC_mru state statistics individually\n"
4699 	    "\t-f display ARC_mfu state statistics individually\n"
4700 	    "\t-b display histogram of buffer counts\n",
4701 	    "print a histogram of compressed arc buffer sizes",
4702 	    arc_compression_stats},
4703 	{ "range_tree", ":",
4704 	    "print entries in range_tree_t", range_tree},
4705 	{ NULL }
4706 };
4707 
4708 static const mdb_walker_t walkers[] = {
4709 	{ "txg_list", "given any txg_list_t *, walk all entries in all txgs",
4710 	    txg_list_walk_init, txg_list_walk_step, NULL },
4711 	{ "txg_list0", "given any txg_list_t *, walk all entries in txg 0",
4712 	    txg_list0_walk_init, txg_list_walk_step, NULL },
4713 	{ "txg_list1", "given any txg_list_t *, walk all entries in txg 1",
4714 	    txg_list1_walk_init, txg_list_walk_step, NULL },
4715 	{ "txg_list2", "given any txg_list_t *, walk all entries in txg 2",
4716 	    txg_list2_walk_init, txg_list_walk_step, NULL },
4717 	{ "txg_list3", "given any txg_list_t *, walk all entries in txg 3",
4718 	    txg_list3_walk_init, txg_list_walk_step, NULL },
4719 	{ "zio", "walk all zio structures, optionally for a particular spa_t",
4720 	    zio_walk_init, zio_walk_step, NULL },
4721 	{ "zio_root",
4722 	    "walk all root zio_t structures, optionally for a particular spa_t",
4723 	    zio_walk_init, zio_walk_root_step, NULL },
4724 	{ "spa", "walk all spa_t entries in the namespace",
4725 	    spa_walk_init, spa_walk_step, NULL },
4726 	{ "metaslab", "given a spa_t *, walk all metaslab_t structures",
4727 	    metaslab_walk_init, metaslab_walk_step, NULL },
4728 	{ "multilist", "given a multilist_t *, walk all list_t structures",
4729 	    multilist_walk_init, multilist_walk_step, NULL },
4730 	{ "zfs_acl_node", "given a zfs_acl_t, walk all zfs_acl_nodes",
4731 	    zfs_acl_node_walk_init, zfs_acl_node_walk_step, NULL },
4732 	{ "zfs_acl_node_aces", "given a zfs_acl_node_t, walk all ACEs",
4733 	    zfs_acl_node_aces_walk_init, zfs_aces_walk_step, NULL },
4734 	{ "zfs_acl_node_aces0",
4735 	    "given a zfs_acl_node_t, walk all ACEs as ace_t",
4736 	    zfs_acl_node_aces0_walk_init, zfs_aces_walk_step, NULL },
4737 	{ "zfs_btree", "given a zfs_btree_t *, walk all entries",
4738 	    btree_walk_init, btree_walk_step, btree_walk_fini },
4739 	{ NULL }
4740 };
4741 
4742 static const mdb_modinfo_t modinfo = {
4743 	MDB_API_VERSION, dcmds, walkers
4744 };
4745 
4746 const mdb_modinfo_t *
_mdb_init(void)4747 _mdb_init(void)
4748 {
4749 	return (&modinfo);
4750 }
4751