]> git.proxmox.com Git - mirror_zfs.git/blob - cmd/zdb/zdb.c
Memory leak in zdb:import_checkpointed_state()
[mirror_zfs.git] / cmd / zdb / zdb.c
1 /*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22 /*
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2019 by Delphix. All rights reserved.
25 * Copyright (c) 2014 Integros [integros.com]
26 * Copyright 2016 Nexenta Systems, Inc.
27 * Copyright (c) 2017, 2018 Lawrence Livermore National Security, LLC.
28 * Copyright (c) 2015, 2017, Intel Corporation.
29 * Copyright (c) 2020 Datto Inc.
30 * Copyright (c) 2020, The FreeBSD Foundation [1]
31 *
32 * [1] Portions of this software were developed by Allan Jude
33 * under sponsorship from the FreeBSD Foundation.
34 */
35
36 #include <stdio.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39 #include <ctype.h>
40 #include <sys/zfs_context.h>
41 #include <sys/spa.h>
42 #include <sys/spa_impl.h>
43 #include <sys/dmu.h>
44 #include <sys/zap.h>
45 #include <sys/fs/zfs.h>
46 #include <sys/zfs_znode.h>
47 #include <sys/zfs_sa.h>
48 #include <sys/sa.h>
49 #include <sys/sa_impl.h>
50 #include <sys/vdev.h>
51 #include <sys/vdev_impl.h>
52 #include <sys/metaslab_impl.h>
53 #include <sys/dmu_objset.h>
54 #include <sys/dsl_dir.h>
55 #include <sys/dsl_dataset.h>
56 #include <sys/dsl_pool.h>
57 #include <sys/dsl_bookmark.h>
58 #include <sys/dbuf.h>
59 #include <sys/zil.h>
60 #include <sys/zil_impl.h>
61 #include <sys/stat.h>
62 #include <sys/resource.h>
63 #include <sys/dmu_send.h>
64 #include <sys/dmu_traverse.h>
65 #include <sys/zio_checksum.h>
66 #include <sys/zio_compress.h>
67 #include <sys/zfs_fuid.h>
68 #include <sys/arc.h>
69 #include <sys/arc_impl.h>
70 #include <sys/ddt.h>
71 #include <sys/zfeature.h>
72 #include <sys/abd.h>
73 #include <sys/blkptr.h>
74 #include <sys/dsl_crypt.h>
75 #include <sys/dsl_scan.h>
76 #include <sys/btree.h>
77 #include <zfs_comutil.h>
78 #include <sys/zstd/zstd.h>
79
80 #include <libnvpair.h>
81 #include <libzutil.h>
82
83 #include "zdb.h"
84
85 #define ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ? \
86 zio_compress_table[(idx)].ci_name : "UNKNOWN")
87 #define ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ? \
88 zio_checksum_table[(idx)].ci_name : "UNKNOWN")
89 #define ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) : \
90 (idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA ? \
91 DMU_OT_ZAP_OTHER : \
92 (idx) == DMU_OTN_UINT64_DATA || (idx) == DMU_OTN_UINT64_METADATA ? \
93 DMU_OT_UINT64_OTHER : DMU_OT_NUMTYPES)
94
95 static char *
96 zdb_ot_name(dmu_object_type_t type)
97 {
98 if (type < DMU_OT_NUMTYPES)
99 return (dmu_ot[type].ot_name);
100 else if ((type & DMU_OT_NEWTYPE) &&
101 ((type & DMU_OT_BYTESWAP_MASK) < DMU_BSWAP_NUMFUNCS))
102 return (dmu_ot_byteswap[type & DMU_OT_BYTESWAP_MASK].ob_name);
103 else
104 return ("UNKNOWN");
105 }
106
107 extern int reference_tracking_enable;
108 extern int zfs_recover;
109 extern unsigned long zfs_arc_meta_min, zfs_arc_meta_limit;
110 extern int zfs_vdev_async_read_max_active;
111 extern boolean_t spa_load_verify_dryrun;
112 extern int zfs_reconstruct_indirect_combinations_max;
113 extern int zfs_btree_verify_intensity;
114
115 static const char cmdname[] = "zdb";
116 uint8_t dump_opt[256];
117
118 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
119
120 uint64_t *zopt_metaslab = NULL;
121 static unsigned zopt_metaslab_args = 0;
122
123 typedef struct zopt_object_range {
124 uint64_t zor_obj_start;
125 uint64_t zor_obj_end;
126 uint64_t zor_flags;
127 } zopt_object_range_t;
128 zopt_object_range_t *zopt_object_ranges = NULL;
129 static unsigned zopt_object_args = 0;
130
131 static int flagbits[256];
132
133 #define ZOR_FLAG_PLAIN_FILE 0x0001
134 #define ZOR_FLAG_DIRECTORY 0x0002
135 #define ZOR_FLAG_SPACE_MAP 0x0004
136 #define ZOR_FLAG_ZAP 0x0008
137 #define ZOR_FLAG_ALL_TYPES -1
138 #define ZOR_SUPPORTED_FLAGS (ZOR_FLAG_PLAIN_FILE | \
139 ZOR_FLAG_DIRECTORY | \
140 ZOR_FLAG_SPACE_MAP | \
141 ZOR_FLAG_ZAP)
142
143 #define ZDB_FLAG_CHECKSUM 0x0001
144 #define ZDB_FLAG_DECOMPRESS 0x0002
145 #define ZDB_FLAG_BSWAP 0x0004
146 #define ZDB_FLAG_GBH 0x0008
147 #define ZDB_FLAG_INDIRECT 0x0010
148 #define ZDB_FLAG_RAW 0x0020
149 #define ZDB_FLAG_PRINT_BLKPTR 0x0040
150 #define ZDB_FLAG_VERBOSE 0x0080
151
152 uint64_t max_inflight_bytes = 256 * 1024 * 1024; /* 256MB */
153 static int leaked_objects = 0;
154 static range_tree_t *mos_refd_objs;
155
156 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *,
157 boolean_t);
158 static void mos_obj_refd(uint64_t);
159 static void mos_obj_refd_multiple(uint64_t);
160 static int dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t free,
161 dmu_tx_t *tx);
162
163 typedef struct sublivelist_verify {
164 /* all ALLOC'd blkptr_t in one sub-livelist */
165 zfs_btree_t sv_all_allocs;
166
167 /* all FREE'd blkptr_t in one sub-livelist */
168 zfs_btree_t sv_all_frees;
169
170 /* FREE's that haven't yet matched to an ALLOC, in one sub-livelist */
171 zfs_btree_t sv_pair;
172
173 /* ALLOC's without a matching FREE, accumulates across sub-livelists */
174 zfs_btree_t sv_leftover;
175 } sublivelist_verify_t;
176
177 static int
178 livelist_compare(const void *larg, const void *rarg)
179 {
180 const blkptr_t *l = larg;
181 const blkptr_t *r = rarg;
182
183 /* Sort them according to dva[0] */
184 uint64_t l_dva0_vdev, r_dva0_vdev;
185 l_dva0_vdev = DVA_GET_VDEV(&l->blk_dva[0]);
186 r_dva0_vdev = DVA_GET_VDEV(&r->blk_dva[0]);
187 if (l_dva0_vdev < r_dva0_vdev)
188 return (-1);
189 else if (l_dva0_vdev > r_dva0_vdev)
190 return (+1);
191
192 /* if vdevs are equal, sort by offsets. */
193 uint64_t l_dva0_offset;
194 uint64_t r_dva0_offset;
195 l_dva0_offset = DVA_GET_OFFSET(&l->blk_dva[0]);
196 r_dva0_offset = DVA_GET_OFFSET(&r->blk_dva[0]);
197 if (l_dva0_offset < r_dva0_offset) {
198 return (-1);
199 } else if (l_dva0_offset > r_dva0_offset) {
200 return (+1);
201 }
202
203 /*
204 * Since we're storing blkptrs without cancelling FREE/ALLOC pairs,
205 * it's possible the offsets are equal. In that case, sort by txg
206 */
207 if (l->blk_birth < r->blk_birth) {
208 return (-1);
209 } else if (l->blk_birth > r->blk_birth) {
210 return (+1);
211 }
212 return (0);
213 }
214
215 typedef struct sublivelist_verify_block {
216 dva_t svb_dva;
217
218 /*
219 * We need this to check if the block marked as allocated
220 * in the livelist was freed (and potentially reallocated)
221 * in the metaslab spacemaps at a later TXG.
222 */
223 uint64_t svb_allocated_txg;
224 } sublivelist_verify_block_t;
225
226 static void zdb_print_blkptr(const blkptr_t *bp, int flags);
227
228 static int
229 sublivelist_verify_blkptr(void *arg, const blkptr_t *bp, boolean_t free,
230 dmu_tx_t *tx)
231 {
232 ASSERT3P(tx, ==, NULL);
233 struct sublivelist_verify *sv = arg;
234 char blkbuf[BP_SPRINTF_LEN];
235 zfs_btree_index_t where;
236 if (free) {
237 zfs_btree_add(&sv->sv_pair, bp);
238 /* Check if the FREE is a duplicate */
239 if (zfs_btree_find(&sv->sv_all_frees, bp, &where) != NULL) {
240 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp,
241 free);
242 (void) printf("\tERROR: Duplicate FREE: %s\n", blkbuf);
243 } else {
244 zfs_btree_add_idx(&sv->sv_all_frees, bp, &where);
245 }
246 } else {
247 /* Check if the ALLOC has been freed */
248 if (zfs_btree_find(&sv->sv_pair, bp, &where) != NULL) {
249 zfs_btree_remove_idx(&sv->sv_pair, &where);
250 } else {
251 for (int i = 0; i < SPA_DVAS_PER_BP; i++) {
252 if (DVA_IS_EMPTY(&bp->blk_dva[i]))
253 break;
254 sublivelist_verify_block_t svb = {
255 .svb_dva = bp->blk_dva[i],
256 .svb_allocated_txg = bp->blk_birth
257 };
258
259 if (zfs_btree_find(&sv->sv_leftover, &svb,
260 &where) == NULL) {
261 zfs_btree_add_idx(&sv->sv_leftover,
262 &svb, &where);
263 }
264 }
265 }
266 /* Check if the ALLOC is a duplicate */
267 if (zfs_btree_find(&sv->sv_all_allocs, bp, &where) != NULL) {
268 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp,
269 free);
270 (void) printf("\tERROR: Duplicate ALLOC: %s\n", blkbuf);
271 } else {
272 zfs_btree_add_idx(&sv->sv_all_allocs, bp, &where);
273 }
274 }
275 return (0);
276 }
277
278 static int
279 sublivelist_verify_func(void *args, dsl_deadlist_entry_t *dle)
280 {
281 int err;
282 char blkbuf[BP_SPRINTF_LEN];
283 struct sublivelist_verify *sv = args;
284
285 zfs_btree_create(&sv->sv_all_allocs, livelist_compare,
286 sizeof (blkptr_t));
287
288 zfs_btree_create(&sv->sv_all_frees, livelist_compare,
289 sizeof (blkptr_t));
290
291 zfs_btree_create(&sv->sv_pair, livelist_compare,
292 sizeof (blkptr_t));
293
294 err = bpobj_iterate_nofree(&dle->dle_bpobj, sublivelist_verify_blkptr,
295 sv, NULL);
296
297 zfs_btree_clear(&sv->sv_all_allocs);
298 zfs_btree_destroy(&sv->sv_all_allocs);
299
300 zfs_btree_clear(&sv->sv_all_frees);
301 zfs_btree_destroy(&sv->sv_all_frees);
302
303 blkptr_t *e;
304 zfs_btree_index_t *cookie = NULL;
305 while ((e = zfs_btree_destroy_nodes(&sv->sv_pair, &cookie)) != NULL) {
306 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), e, B_TRUE);
307 (void) printf("\tERROR: Unmatched FREE: %s\n", blkbuf);
308 }
309 zfs_btree_destroy(&sv->sv_pair);
310
311 return (err);
312 }
313
314 static int
315 livelist_block_compare(const void *larg, const void *rarg)
316 {
317 const sublivelist_verify_block_t *l = larg;
318 const sublivelist_verify_block_t *r = rarg;
319
320 if (DVA_GET_VDEV(&l->svb_dva) < DVA_GET_VDEV(&r->svb_dva))
321 return (-1);
322 else if (DVA_GET_VDEV(&l->svb_dva) > DVA_GET_VDEV(&r->svb_dva))
323 return (+1);
324
325 if (DVA_GET_OFFSET(&l->svb_dva) < DVA_GET_OFFSET(&r->svb_dva))
326 return (-1);
327 else if (DVA_GET_OFFSET(&l->svb_dva) > DVA_GET_OFFSET(&r->svb_dva))
328 return (+1);
329
330 if (DVA_GET_ASIZE(&l->svb_dva) < DVA_GET_ASIZE(&r->svb_dva))
331 return (-1);
332 else if (DVA_GET_ASIZE(&l->svb_dva) > DVA_GET_ASIZE(&r->svb_dva))
333 return (+1);
334
335 return (0);
336 }
337
338 /*
339 * Check for errors in a livelist while tracking all unfreed ALLOCs in the
340 * sublivelist_verify_t: sv->sv_leftover
341 */
342 static void
343 livelist_verify(dsl_deadlist_t *dl, void *arg)
344 {
345 sublivelist_verify_t *sv = arg;
346 dsl_deadlist_iterate(dl, sublivelist_verify_func, sv);
347 }
348
349 /*
350 * Check for errors in the livelist entry and discard the intermediary
351 * data structures
352 */
353 /* ARGSUSED */
354 static int
355 sublivelist_verify_lightweight(void *args, dsl_deadlist_entry_t *dle)
356 {
357 sublivelist_verify_t sv;
358 zfs_btree_create(&sv.sv_leftover, livelist_block_compare,
359 sizeof (sublivelist_verify_block_t));
360 int err = sublivelist_verify_func(&sv, dle);
361 zfs_btree_clear(&sv.sv_leftover);
362 zfs_btree_destroy(&sv.sv_leftover);
363 return (err);
364 }
365
366 typedef struct metaslab_verify {
367 /*
368 * Tree containing all the leftover ALLOCs from the livelists
369 * that are part of this metaslab.
370 */
371 zfs_btree_t mv_livelist_allocs;
372
373 /*
374 * Metaslab information.
375 */
376 uint64_t mv_vdid;
377 uint64_t mv_msid;
378 uint64_t mv_start;
379 uint64_t mv_end;
380
381 /*
382 * What's currently allocated for this metaslab.
383 */
384 range_tree_t *mv_allocated;
385 } metaslab_verify_t;
386
387 typedef void ll_iter_t(dsl_deadlist_t *ll, void *arg);
388
389 typedef int (*zdb_log_sm_cb_t)(spa_t *spa, space_map_entry_t *sme, uint64_t txg,
390 void *arg);
391
392 typedef struct unflushed_iter_cb_arg {
393 spa_t *uic_spa;
394 uint64_t uic_txg;
395 void *uic_arg;
396 zdb_log_sm_cb_t uic_cb;
397 } unflushed_iter_cb_arg_t;
398
399 static int
400 iterate_through_spacemap_logs_cb(space_map_entry_t *sme, void *arg)
401 {
402 unflushed_iter_cb_arg_t *uic = arg;
403 return (uic->uic_cb(uic->uic_spa, sme, uic->uic_txg, uic->uic_arg));
404 }
405
406 static void
407 iterate_through_spacemap_logs(spa_t *spa, zdb_log_sm_cb_t cb, void *arg)
408 {
409 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
410 return;
411
412 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
413 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
414 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
415 space_map_t *sm = NULL;
416 VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
417 sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
418
419 unflushed_iter_cb_arg_t uic = {
420 .uic_spa = spa,
421 .uic_txg = sls->sls_txg,
422 .uic_arg = arg,
423 .uic_cb = cb
424 };
425 VERIFY0(space_map_iterate(sm, space_map_length(sm),
426 iterate_through_spacemap_logs_cb, &uic));
427 space_map_close(sm);
428 }
429 spa_config_exit(spa, SCL_CONFIG, FTAG);
430 }
431
432 static void
433 verify_livelist_allocs(metaslab_verify_t *mv, uint64_t txg,
434 uint64_t offset, uint64_t size)
435 {
436 sublivelist_verify_block_t svb;
437 DVA_SET_VDEV(&svb.svb_dva, mv->mv_vdid);
438 DVA_SET_OFFSET(&svb.svb_dva, offset);
439 DVA_SET_ASIZE(&svb.svb_dva, size);
440 zfs_btree_index_t where;
441 uint64_t end_offset = offset + size;
442
443 /*
444 * Look for an exact match for spacemap entry in the livelist entries.
445 * Then, look for other livelist entries that fall within the range
446 * of the spacemap entry as it may have been condensed
447 */
448 sublivelist_verify_block_t *found =
449 zfs_btree_find(&mv->mv_livelist_allocs, &svb, &where);
450 if (found == NULL) {
451 found = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where);
452 }
453 for (; found != NULL && DVA_GET_VDEV(&found->svb_dva) == mv->mv_vdid &&
454 DVA_GET_OFFSET(&found->svb_dva) < end_offset;
455 found = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where)) {
456 if (found->svb_allocated_txg <= txg) {
457 (void) printf("ERROR: Livelist ALLOC [%llx:%llx] "
458 "from TXG %llx FREED at TXG %llx\n",
459 (u_longlong_t)DVA_GET_OFFSET(&found->svb_dva),
460 (u_longlong_t)DVA_GET_ASIZE(&found->svb_dva),
461 (u_longlong_t)found->svb_allocated_txg,
462 (u_longlong_t)txg);
463 }
464 }
465 }
466
467 static int
468 metaslab_spacemap_validation_cb(space_map_entry_t *sme, void *arg)
469 {
470 metaslab_verify_t *mv = arg;
471 uint64_t offset = sme->sme_offset;
472 uint64_t size = sme->sme_run;
473 uint64_t txg = sme->sme_txg;
474
475 if (sme->sme_type == SM_ALLOC) {
476 if (range_tree_contains(mv->mv_allocated,
477 offset, size)) {
478 (void) printf("ERROR: DOUBLE ALLOC: "
479 "%llu [%llx:%llx] "
480 "%llu:%llu LOG_SM\n",
481 (u_longlong_t)txg, (u_longlong_t)offset,
482 (u_longlong_t)size, (u_longlong_t)mv->mv_vdid,
483 (u_longlong_t)mv->mv_msid);
484 } else {
485 range_tree_add(mv->mv_allocated,
486 offset, size);
487 }
488 } else {
489 if (!range_tree_contains(mv->mv_allocated,
490 offset, size)) {
491 (void) printf("ERROR: DOUBLE FREE: "
492 "%llu [%llx:%llx] "
493 "%llu:%llu LOG_SM\n",
494 (u_longlong_t)txg, (u_longlong_t)offset,
495 (u_longlong_t)size, (u_longlong_t)mv->mv_vdid,
496 (u_longlong_t)mv->mv_msid);
497 } else {
498 range_tree_remove(mv->mv_allocated,
499 offset, size);
500 }
501 }
502
503 if (sme->sme_type != SM_ALLOC) {
504 /*
505 * If something is freed in the spacemap, verify that
506 * it is not listed as allocated in the livelist.
507 */
508 verify_livelist_allocs(mv, txg, offset, size);
509 }
510 return (0);
511 }
512
513 static int
514 spacemap_check_sm_log_cb(spa_t *spa, space_map_entry_t *sme,
515 uint64_t txg, void *arg)
516 {
517 metaslab_verify_t *mv = arg;
518 uint64_t offset = sme->sme_offset;
519 uint64_t vdev_id = sme->sme_vdev;
520
521 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
522
523 /* skip indirect vdevs */
524 if (!vdev_is_concrete(vd))
525 return (0);
526
527 if (vdev_id != mv->mv_vdid)
528 return (0);
529
530 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
531 if (ms->ms_id != mv->mv_msid)
532 return (0);
533
534 if (txg < metaslab_unflushed_txg(ms))
535 return (0);
536
537
538 ASSERT3U(txg, ==, sme->sme_txg);
539 return (metaslab_spacemap_validation_cb(sme, mv));
540 }
541
542 static void
543 spacemap_check_sm_log(spa_t *spa, metaslab_verify_t *mv)
544 {
545 iterate_through_spacemap_logs(spa, spacemap_check_sm_log_cb, mv);
546 }
547
548 static void
549 spacemap_check_ms_sm(space_map_t *sm, metaslab_verify_t *mv)
550 {
551 if (sm == NULL)
552 return;
553
554 VERIFY0(space_map_iterate(sm, space_map_length(sm),
555 metaslab_spacemap_validation_cb, mv));
556 }
557
558 static void iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg);
559
560 /*
561 * Transfer blocks from sv_leftover tree to the mv_livelist_allocs if
562 * they are part of that metaslab (mv_msid).
563 */
564 static void
565 mv_populate_livelist_allocs(metaslab_verify_t *mv, sublivelist_verify_t *sv)
566 {
567 zfs_btree_index_t where;
568 sublivelist_verify_block_t *svb;
569 ASSERT3U(zfs_btree_numnodes(&mv->mv_livelist_allocs), ==, 0);
570 for (svb = zfs_btree_first(&sv->sv_leftover, &where);
571 svb != NULL;
572 svb = zfs_btree_next(&sv->sv_leftover, &where, &where)) {
573 if (DVA_GET_VDEV(&svb->svb_dva) != mv->mv_vdid)
574 continue;
575
576 if (DVA_GET_OFFSET(&svb->svb_dva) < mv->mv_start &&
577 (DVA_GET_OFFSET(&svb->svb_dva) +
578 DVA_GET_ASIZE(&svb->svb_dva)) > mv->mv_start) {
579 (void) printf("ERROR: Found block that crosses "
580 "metaslab boundary: <%llu:%llx:%llx>\n",
581 (u_longlong_t)DVA_GET_VDEV(&svb->svb_dva),
582 (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
583 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva));
584 continue;
585 }
586
587 if (DVA_GET_OFFSET(&svb->svb_dva) < mv->mv_start)
588 continue;
589
590 if (DVA_GET_OFFSET(&svb->svb_dva) >= mv->mv_end)
591 continue;
592
593 if ((DVA_GET_OFFSET(&svb->svb_dva) +
594 DVA_GET_ASIZE(&svb->svb_dva)) > mv->mv_end) {
595 (void) printf("ERROR: Found block that crosses "
596 "metaslab boundary: <%llu:%llx:%llx>\n",
597 (u_longlong_t)DVA_GET_VDEV(&svb->svb_dva),
598 (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
599 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva));
600 continue;
601 }
602
603 zfs_btree_add(&mv->mv_livelist_allocs, svb);
604 }
605
606 for (svb = zfs_btree_first(&mv->mv_livelist_allocs, &where);
607 svb != NULL;
608 svb = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where)) {
609 zfs_btree_remove(&sv->sv_leftover, svb);
610 }
611 }
612
613 /*
614 * [Livelist Check]
615 * Iterate through all the sublivelists and:
616 * - report leftover frees
617 * - report double ALLOCs/FREEs
618 * - record leftover ALLOCs together with their TXG [see Cross Check]
619 *
620 * [Spacemap Check]
621 * for each metaslab:
622 * - iterate over spacemap and then the metaslab's entries in the
623 * spacemap log, then report any double FREEs and ALLOCs (do not
624 * blow up).
625 *
626 * [Cross Check]
627 * After finishing the Livelist Check phase and while being in the
628 * Spacemap Check phase, we find all the recorded leftover ALLOCs
629 * of the livelist check that are part of the metaslab that we are
630 * currently looking at in the Spacemap Check. We report any entries
631 * that are marked as ALLOCs in the livelists but have been actually
632 * freed (and potentially allocated again) after their TXG stamp in
633 * the spacemaps. Also report any ALLOCs from the livelists that
634 * belong to indirect vdevs (e.g. their vdev completed removal).
635 *
636 * Note that this will miss Log Spacemap entries that cancelled each other
637 * out before being flushed to the metaslab, so we are not guaranteed
638 * to match all erroneous ALLOCs.
639 */
640 static void
641 livelist_metaslab_validate(spa_t *spa)
642 {
643 (void) printf("Verifying deleted livelist entries\n");
644
645 sublivelist_verify_t sv;
646 zfs_btree_create(&sv.sv_leftover, livelist_block_compare,
647 sizeof (sublivelist_verify_block_t));
648 iterate_deleted_livelists(spa, livelist_verify, &sv);
649
650 (void) printf("Verifying metaslab entries\n");
651 vdev_t *rvd = spa->spa_root_vdev;
652 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
653 vdev_t *vd = rvd->vdev_child[c];
654
655 if (!vdev_is_concrete(vd))
656 continue;
657
658 for (uint64_t mid = 0; mid < vd->vdev_ms_count; mid++) {
659 metaslab_t *m = vd->vdev_ms[mid];
660
661 (void) fprintf(stderr,
662 "\rverifying concrete vdev %llu, "
663 "metaslab %llu of %llu ...",
664 (longlong_t)vd->vdev_id,
665 (longlong_t)mid,
666 (longlong_t)vd->vdev_ms_count);
667
668 uint64_t shift, start;
669 range_seg_type_t type =
670 metaslab_calculate_range_tree_type(vd, m,
671 &start, &shift);
672 metaslab_verify_t mv;
673 mv.mv_allocated = range_tree_create(NULL,
674 type, NULL, start, shift);
675 mv.mv_vdid = vd->vdev_id;
676 mv.mv_msid = m->ms_id;
677 mv.mv_start = m->ms_start;
678 mv.mv_end = m->ms_start + m->ms_size;
679 zfs_btree_create(&mv.mv_livelist_allocs,
680 livelist_block_compare,
681 sizeof (sublivelist_verify_block_t));
682
683 mv_populate_livelist_allocs(&mv, &sv);
684
685 spacemap_check_ms_sm(m->ms_sm, &mv);
686 spacemap_check_sm_log(spa, &mv);
687
688 range_tree_vacate(mv.mv_allocated, NULL, NULL);
689 range_tree_destroy(mv.mv_allocated);
690 zfs_btree_clear(&mv.mv_livelist_allocs);
691 zfs_btree_destroy(&mv.mv_livelist_allocs);
692 }
693 }
694 (void) fprintf(stderr, "\n");
695
696 /*
697 * If there are any segments in the leftover tree after we walked
698 * through all the metaslabs in the concrete vdevs then this means
699 * that we have segments in the livelists that belong to indirect
700 * vdevs and are marked as allocated.
701 */
702 if (zfs_btree_numnodes(&sv.sv_leftover) == 0) {
703 zfs_btree_destroy(&sv.sv_leftover);
704 return;
705 }
706 (void) printf("ERROR: Found livelist blocks marked as allocated "
707 "for indirect vdevs:\n");
708
709 zfs_btree_index_t *where = NULL;
710 sublivelist_verify_block_t *svb;
711 while ((svb = zfs_btree_destroy_nodes(&sv.sv_leftover, &where)) !=
712 NULL) {
713 int vdev_id = DVA_GET_VDEV(&svb->svb_dva);
714 ASSERT3U(vdev_id, <, rvd->vdev_children);
715 vdev_t *vd = rvd->vdev_child[vdev_id];
716 ASSERT(!vdev_is_concrete(vd));
717 (void) printf("<%d:%llx:%llx> TXG %llx\n",
718 vdev_id, (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
719 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva),
720 (u_longlong_t)svb->svb_allocated_txg);
721 }
722 (void) printf("\n");
723 zfs_btree_destroy(&sv.sv_leftover);
724 }
725
726 /*
727 * These libumem hooks provide a reasonable set of defaults for the allocator's
728 * debugging facilities.
729 */
730 const char *
731 _umem_debug_init(void)
732 {
733 return ("default,verbose"); /* $UMEM_DEBUG setting */
734 }
735
736 const char *
737 _umem_logging_init(void)
738 {
739 return ("fail,contents"); /* $UMEM_LOGGING setting */
740 }
741
742 static void
743 usage(void)
744 {
745 (void) fprintf(stderr,
746 "Usage:\t%s [-AbcdDFGhikLMPsvXy] [-e [-V] [-p <path> ...]] "
747 "[-I <inflight I/Os>]\n"
748 "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
749 "\t\t[<poolname>[/<dataset | objset id>] [<object | range> ...]]\n"
750 "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
751 "\t\t[<poolname>[/<dataset | objset id>] [<object | range> ...]\n"
752 "\t%s [-v] <bookmark>\n"
753 "\t%s -C [-A] [-U <cache>]\n"
754 "\t%s -l [-Aqu] <device>\n"
755 "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
756 "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
757 "\t%s -O <dataset> <path>\n"
758 "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
759 "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
760 "\t%s -E [-A] word0:word1:...:word15\n"
761 "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
762 "<poolname>\n\n",
763 cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
764 cmdname, cmdname, cmdname);
765
766 (void) fprintf(stderr, " Dataset name must include at least one "
767 "separator character '/' or '@'\n");
768 (void) fprintf(stderr, " If dataset name is specified, only that "
769 "dataset is dumped\n");
770 (void) fprintf(stderr, " If object numbers or object number "
771 "ranges are specified, only those\n"
772 " objects or ranges are dumped.\n\n");
773 (void) fprintf(stderr,
774 " Object ranges take the form <start>:<end>[:<flags>]\n"
775 " start Starting object number\n"
776 " end Ending object number, or -1 for no upper bound\n"
777 " flags Optional flags to select object types:\n"
778 " A All objects (this is the default)\n"
779 " d ZFS directories\n"
780 " f ZFS files \n"
781 " m SPA space maps\n"
782 " z ZAPs\n"
783 " - Negate effect of next flag\n\n");
784 (void) fprintf(stderr, " Options to control amount of output:\n");
785 (void) fprintf(stderr, " -b block statistics\n");
786 (void) fprintf(stderr, " -c checksum all metadata (twice for "
787 "all data) blocks\n");
788 (void) fprintf(stderr, " -C config (or cachefile if alone)\n");
789 (void) fprintf(stderr, " -d dataset(s)\n");
790 (void) fprintf(stderr, " -D dedup statistics\n");
791 (void) fprintf(stderr, " -E decode and display block from an "
792 "embedded block pointer\n");
793 (void) fprintf(stderr, " -h pool history\n");
794 (void) fprintf(stderr, " -i intent logs\n");
795 (void) fprintf(stderr, " -l read label contents\n");
796 (void) fprintf(stderr, " -k examine the checkpointed state "
797 "of the pool\n");
798 (void) fprintf(stderr, " -L disable leak tracking (do not "
799 "load spacemaps)\n");
800 (void) fprintf(stderr, " -m metaslabs\n");
801 (void) fprintf(stderr, " -M metaslab groups\n");
802 (void) fprintf(stderr, " -O perform object lookups by path\n");
803 (void) fprintf(stderr, " -R read and display block from a "
804 "device\n");
805 (void) fprintf(stderr, " -s report stats on zdb's I/O\n");
806 (void) fprintf(stderr, " -S simulate dedup to measure effect\n");
807 (void) fprintf(stderr, " -v verbose (applies to all "
808 "others)\n");
809 (void) fprintf(stderr, " -y perform livelist and metaslab "
810 "validation on any livelists being deleted\n\n");
811 (void) fprintf(stderr, " Below options are intended for use "
812 "with other options:\n");
813 (void) fprintf(stderr, " -A ignore assertions (-A), enable "
814 "panic recovery (-AA) or both (-AAA)\n");
815 (void) fprintf(stderr, " -e pool is exported/destroyed/"
816 "has altroot/not in a cachefile\n");
817 (void) fprintf(stderr, " -F attempt automatic rewind within "
818 "safe range of transaction groups\n");
819 (void) fprintf(stderr, " -G dump zfs_dbgmsg buffer before "
820 "exiting\n");
821 (void) fprintf(stderr, " -I <number of inflight I/Os> -- "
822 "specify the maximum number of\n "
823 "checksumming I/Os [default is 200]\n");
824 (void) fprintf(stderr, " -o <variable>=<value> set global "
825 "variable to an unsigned 32-bit integer\n");
826 (void) fprintf(stderr, " -p <path> -- use one or more with "
827 "-e to specify path to vdev dir\n");
828 (void) fprintf(stderr, " -P print numbers in parseable form\n");
829 (void) fprintf(stderr, " -q don't print label contents\n");
830 (void) fprintf(stderr, " -t <txg> -- highest txg to use when "
831 "searching for uberblocks\n");
832 (void) fprintf(stderr, " -u uberblock\n");
833 (void) fprintf(stderr, " -U <cachefile_path> -- use alternate "
834 "cachefile\n");
835 (void) fprintf(stderr, " -V do verbatim import\n");
836 (void) fprintf(stderr, " -x <dumpdir> -- "
837 "dump all read blocks into specified directory\n");
838 (void) fprintf(stderr, " -X attempt extreme rewind (does not "
839 "work with dataset)\n");
840 (void) fprintf(stderr, " -Y attempt all reconstruction "
841 "combinations for split blocks\n");
842 (void) fprintf(stderr, " -Z show ZSTD headers \n");
843 (void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
844 "to make only that option verbose\n");
845 (void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
846 exit(1);
847 }
848
849 static void
850 dump_debug_buffer(void)
851 {
852 if (dump_opt['G']) {
853 (void) printf("\n");
854 (void) fflush(stdout);
855 zfs_dbgmsg_print("zdb");
856 }
857 }
858
859 /*
860 * Called for usage errors that are discovered after a call to spa_open(),
861 * dmu_bonus_hold(), or pool_match(). abort() is called for other errors.
862 */
863
864 static void
865 fatal(const char *fmt, ...)
866 {
867 va_list ap;
868
869 va_start(ap, fmt);
870 (void) fprintf(stderr, "%s: ", cmdname);
871 (void) vfprintf(stderr, fmt, ap);
872 va_end(ap);
873 (void) fprintf(stderr, "\n");
874
875 dump_debug_buffer();
876
877 exit(1);
878 }
879
880 /* ARGSUSED */
881 static void
882 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
883 {
884 nvlist_t *nv;
885 size_t nvsize = *(uint64_t *)data;
886 char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
887
888 VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
889
890 VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
891
892 umem_free(packed, nvsize);
893
894 dump_nvlist(nv, 8);
895
896 nvlist_free(nv);
897 }
898
899 /* ARGSUSED */
900 static void
901 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
902 {
903 spa_history_phys_t *shp = data;
904
905 if (shp == NULL)
906 return;
907
908 (void) printf("\t\tpool_create_len = %llu\n",
909 (u_longlong_t)shp->sh_pool_create_len);
910 (void) printf("\t\tphys_max_off = %llu\n",
911 (u_longlong_t)shp->sh_phys_max_off);
912 (void) printf("\t\tbof = %llu\n",
913 (u_longlong_t)shp->sh_bof);
914 (void) printf("\t\teof = %llu\n",
915 (u_longlong_t)shp->sh_eof);
916 (void) printf("\t\trecords_lost = %llu\n",
917 (u_longlong_t)shp->sh_records_lost);
918 }
919
920 static void
921 zdb_nicenum(uint64_t num, char *buf, size_t buflen)
922 {
923 if (dump_opt['P'])
924 (void) snprintf(buf, buflen, "%llu", (longlong_t)num);
925 else
926 nicenum(num, buf, sizeof (buf));
927 }
928
929 static const char histo_stars[] = "****************************************";
930 static const uint64_t histo_width = sizeof (histo_stars) - 1;
931
932 static void
933 dump_histogram(const uint64_t *histo, int size, int offset)
934 {
935 int i;
936 int minidx = size - 1;
937 int maxidx = 0;
938 uint64_t max = 0;
939
940 for (i = 0; i < size; i++) {
941 if (histo[i] > max)
942 max = histo[i];
943 if (histo[i] > 0 && i > maxidx)
944 maxidx = i;
945 if (histo[i] > 0 && i < minidx)
946 minidx = i;
947 }
948
949 if (max < histo_width)
950 max = histo_width;
951
952 for (i = minidx; i <= maxidx; i++) {
953 (void) printf("\t\t\t%3u: %6llu %s\n",
954 i + offset, (u_longlong_t)histo[i],
955 &histo_stars[(max - histo[i]) * histo_width / max]);
956 }
957 }
958
959 static void
960 dump_zap_stats(objset_t *os, uint64_t object)
961 {
962 int error;
963 zap_stats_t zs;
964
965 error = zap_get_stats(os, object, &zs);
966 if (error)
967 return;
968
969 if (zs.zs_ptrtbl_len == 0) {
970 ASSERT(zs.zs_num_blocks == 1);
971 (void) printf("\tmicrozap: %llu bytes, %llu entries\n",
972 (u_longlong_t)zs.zs_blocksize,
973 (u_longlong_t)zs.zs_num_entries);
974 return;
975 }
976
977 (void) printf("\tFat ZAP stats:\n");
978
979 (void) printf("\t\tPointer table:\n");
980 (void) printf("\t\t\t%llu elements\n",
981 (u_longlong_t)zs.zs_ptrtbl_len);
982 (void) printf("\t\t\tzt_blk: %llu\n",
983 (u_longlong_t)zs.zs_ptrtbl_zt_blk);
984 (void) printf("\t\t\tzt_numblks: %llu\n",
985 (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
986 (void) printf("\t\t\tzt_shift: %llu\n",
987 (u_longlong_t)zs.zs_ptrtbl_zt_shift);
988 (void) printf("\t\t\tzt_blks_copied: %llu\n",
989 (u_longlong_t)zs.zs_ptrtbl_blks_copied);
990 (void) printf("\t\t\tzt_nextblk: %llu\n",
991 (u_longlong_t)zs.zs_ptrtbl_nextblk);
992
993 (void) printf("\t\tZAP entries: %llu\n",
994 (u_longlong_t)zs.zs_num_entries);
995 (void) printf("\t\tLeaf blocks: %llu\n",
996 (u_longlong_t)zs.zs_num_leafs);
997 (void) printf("\t\tTotal blocks: %llu\n",
998 (u_longlong_t)zs.zs_num_blocks);
999 (void) printf("\t\tzap_block_type: 0x%llx\n",
1000 (u_longlong_t)zs.zs_block_type);
1001 (void) printf("\t\tzap_magic: 0x%llx\n",
1002 (u_longlong_t)zs.zs_magic);
1003 (void) printf("\t\tzap_salt: 0x%llx\n",
1004 (u_longlong_t)zs.zs_salt);
1005
1006 (void) printf("\t\tLeafs with 2^n pointers:\n");
1007 dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
1008
1009 (void) printf("\t\tBlocks with n*5 entries:\n");
1010 dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
1011
1012 (void) printf("\t\tBlocks n/10 full:\n");
1013 dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
1014
1015 (void) printf("\t\tEntries with n chunks:\n");
1016 dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
1017
1018 (void) printf("\t\tBuckets with n entries:\n");
1019 dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
1020 }
1021
1022 /*ARGSUSED*/
1023 static void
1024 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
1025 {
1026 }
1027
1028 /*ARGSUSED*/
1029 static void
1030 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
1031 {
1032 (void) printf("\tUNKNOWN OBJECT TYPE\n");
1033 }
1034
1035 /*ARGSUSED*/
1036 static void
1037 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
1038 {
1039 }
1040
1041 /*ARGSUSED*/
1042 static void
1043 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
1044 {
1045 uint64_t *arr;
1046 uint64_t oursize;
1047 if (dump_opt['d'] < 6)
1048 return;
1049
1050 if (data == NULL) {
1051 dmu_object_info_t doi;
1052
1053 VERIFY0(dmu_object_info(os, object, &doi));
1054 size = doi.doi_max_offset;
1055 /*
1056 * We cap the size at 1 mebibyte here to prevent
1057 * allocation failures and nigh-infinite printing if the
1058 * object is extremely large.
1059 */
1060 oursize = MIN(size, 1 << 20);
1061 arr = kmem_alloc(oursize, KM_SLEEP);
1062
1063 int err = dmu_read(os, object, 0, oursize, arr, 0);
1064 if (err != 0) {
1065 (void) printf("got error %u from dmu_read\n", err);
1066 kmem_free(arr, oursize);
1067 return;
1068 }
1069 } else {
1070 /*
1071 * Even though the allocation is already done in this code path,
1072 * we still cap the size to prevent excessive printing.
1073 */
1074 oursize = MIN(size, 1 << 20);
1075 arr = data;
1076 }
1077
1078 if (size == 0) {
1079 (void) printf("\t\t[]\n");
1080 return;
1081 }
1082
1083 (void) printf("\t\t[%0llx", (u_longlong_t)arr[0]);
1084 for (size_t i = 1; i * sizeof (uint64_t) < oursize; i++) {
1085 if (i % 4 != 0)
1086 (void) printf(", %0llx", (u_longlong_t)arr[i]);
1087 else
1088 (void) printf(",\n\t\t%0llx", (u_longlong_t)arr[i]);
1089 }
1090 if (oursize != size)
1091 (void) printf(", ... ");
1092 (void) printf("]\n");
1093
1094 if (data == NULL)
1095 kmem_free(arr, oursize);
1096 }
1097
1098 /*ARGSUSED*/
1099 static void
1100 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
1101 {
1102 zap_cursor_t zc;
1103 zap_attribute_t attr;
1104 void *prop;
1105 unsigned i;
1106
1107 dump_zap_stats(os, object);
1108 (void) printf("\n");
1109
1110 for (zap_cursor_init(&zc, os, object);
1111 zap_cursor_retrieve(&zc, &attr) == 0;
1112 zap_cursor_advance(&zc)) {
1113 (void) printf("\t\t%s = ", attr.za_name);
1114 if (attr.za_num_integers == 0) {
1115 (void) printf("\n");
1116 continue;
1117 }
1118 prop = umem_zalloc(attr.za_num_integers *
1119 attr.za_integer_length, UMEM_NOFAIL);
1120 (void) zap_lookup(os, object, attr.za_name,
1121 attr.za_integer_length, attr.za_num_integers, prop);
1122 if (attr.za_integer_length == 1) {
1123 if (strcmp(attr.za_name,
1124 DSL_CRYPTO_KEY_MASTER_KEY) == 0 ||
1125 strcmp(attr.za_name,
1126 DSL_CRYPTO_KEY_HMAC_KEY) == 0 ||
1127 strcmp(attr.za_name, DSL_CRYPTO_KEY_IV) == 0 ||
1128 strcmp(attr.za_name, DSL_CRYPTO_KEY_MAC) == 0 ||
1129 strcmp(attr.za_name, DMU_POOL_CHECKSUM_SALT) == 0) {
1130 uint8_t *u8 = prop;
1131
1132 for (i = 0; i < attr.za_num_integers; i++) {
1133 (void) printf("%02x", u8[i]);
1134 }
1135 } else {
1136 (void) printf("%s", (char *)prop);
1137 }
1138 } else {
1139 for (i = 0; i < attr.za_num_integers; i++) {
1140 switch (attr.za_integer_length) {
1141 case 2:
1142 (void) printf("%u ",
1143 ((uint16_t *)prop)[i]);
1144 break;
1145 case 4:
1146 (void) printf("%u ",
1147 ((uint32_t *)prop)[i]);
1148 break;
1149 case 8:
1150 (void) printf("%lld ",
1151 (u_longlong_t)((int64_t *)prop)[i]);
1152 break;
1153 }
1154 }
1155 }
1156 (void) printf("\n");
1157 umem_free(prop, attr.za_num_integers * attr.za_integer_length);
1158 }
1159 zap_cursor_fini(&zc);
1160 }
1161
1162 static void
1163 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
1164 {
1165 bpobj_phys_t *bpop = data;
1166 uint64_t i;
1167 char bytes[32], comp[32], uncomp[32];
1168
1169 /* make sure the output won't get truncated */
1170 CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1171 CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1172 CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1173
1174 if (bpop == NULL)
1175 return;
1176
1177 zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
1178 zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
1179 zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
1180
1181 (void) printf("\t\tnum_blkptrs = %llu\n",
1182 (u_longlong_t)bpop->bpo_num_blkptrs);
1183 (void) printf("\t\tbytes = %s\n", bytes);
1184 if (size >= BPOBJ_SIZE_V1) {
1185 (void) printf("\t\tcomp = %s\n", comp);
1186 (void) printf("\t\tuncomp = %s\n", uncomp);
1187 }
1188 if (size >= BPOBJ_SIZE_V2) {
1189 (void) printf("\t\tsubobjs = %llu\n",
1190 (u_longlong_t)bpop->bpo_subobjs);
1191 (void) printf("\t\tnum_subobjs = %llu\n",
1192 (u_longlong_t)bpop->bpo_num_subobjs);
1193 }
1194 if (size >= sizeof (*bpop)) {
1195 (void) printf("\t\tnum_freed = %llu\n",
1196 (u_longlong_t)bpop->bpo_num_freed);
1197 }
1198
1199 if (dump_opt['d'] < 5)
1200 return;
1201
1202 for (i = 0; i < bpop->bpo_num_blkptrs; i++) {
1203 char blkbuf[BP_SPRINTF_LEN];
1204 blkptr_t bp;
1205
1206 int err = dmu_read(os, object,
1207 i * sizeof (bp), sizeof (bp), &bp, 0);
1208 if (err != 0) {
1209 (void) printf("got error %u from dmu_read\n", err);
1210 break;
1211 }
1212 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp,
1213 BP_GET_FREE(&bp));
1214 (void) printf("\t%s\n", blkbuf);
1215 }
1216 }
1217
1218 /* ARGSUSED */
1219 static void
1220 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
1221 {
1222 dmu_object_info_t doi;
1223 int64_t i;
1224
1225 VERIFY0(dmu_object_info(os, object, &doi));
1226 uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
1227
1228 int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
1229 if (err != 0) {
1230 (void) printf("got error %u from dmu_read\n", err);
1231 kmem_free(subobjs, doi.doi_max_offset);
1232 return;
1233 }
1234
1235 int64_t last_nonzero = -1;
1236 for (i = 0; i < doi.doi_max_offset / 8; i++) {
1237 if (subobjs[i] != 0)
1238 last_nonzero = i;
1239 }
1240
1241 for (i = 0; i <= last_nonzero; i++) {
1242 (void) printf("\t%llu\n", (u_longlong_t)subobjs[i]);
1243 }
1244 kmem_free(subobjs, doi.doi_max_offset);
1245 }
1246
1247 /*ARGSUSED*/
1248 static void
1249 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
1250 {
1251 dump_zap_stats(os, object);
1252 /* contents are printed elsewhere, properly decoded */
1253 }
1254
1255 /*ARGSUSED*/
1256 static void
1257 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
1258 {
1259 zap_cursor_t zc;
1260 zap_attribute_t attr;
1261
1262 dump_zap_stats(os, object);
1263 (void) printf("\n");
1264
1265 for (zap_cursor_init(&zc, os, object);
1266 zap_cursor_retrieve(&zc, &attr) == 0;
1267 zap_cursor_advance(&zc)) {
1268 (void) printf("\t\t%s = ", attr.za_name);
1269 if (attr.za_num_integers == 0) {
1270 (void) printf("\n");
1271 continue;
1272 }
1273 (void) printf(" %llx : [%d:%d:%d]\n",
1274 (u_longlong_t)attr.za_first_integer,
1275 (int)ATTR_LENGTH(attr.za_first_integer),
1276 (int)ATTR_BSWAP(attr.za_first_integer),
1277 (int)ATTR_NUM(attr.za_first_integer));
1278 }
1279 zap_cursor_fini(&zc);
1280 }
1281
1282 /*ARGSUSED*/
1283 static void
1284 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
1285 {
1286 zap_cursor_t zc;
1287 zap_attribute_t attr;
1288 uint16_t *layout_attrs;
1289 unsigned i;
1290
1291 dump_zap_stats(os, object);
1292 (void) printf("\n");
1293
1294 for (zap_cursor_init(&zc, os, object);
1295 zap_cursor_retrieve(&zc, &attr) == 0;
1296 zap_cursor_advance(&zc)) {
1297 (void) printf("\t\t%s = [", attr.za_name);
1298 if (attr.za_num_integers == 0) {
1299 (void) printf("\n");
1300 continue;
1301 }
1302
1303 VERIFY(attr.za_integer_length == 2);
1304 layout_attrs = umem_zalloc(attr.za_num_integers *
1305 attr.za_integer_length, UMEM_NOFAIL);
1306
1307 VERIFY(zap_lookup(os, object, attr.za_name,
1308 attr.za_integer_length,
1309 attr.za_num_integers, layout_attrs) == 0);
1310
1311 for (i = 0; i != attr.za_num_integers; i++)
1312 (void) printf(" %d ", (int)layout_attrs[i]);
1313 (void) printf("]\n");
1314 umem_free(layout_attrs,
1315 attr.za_num_integers * attr.za_integer_length);
1316 }
1317 zap_cursor_fini(&zc);
1318 }
1319
1320 /*ARGSUSED*/
1321 static void
1322 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
1323 {
1324 zap_cursor_t zc;
1325 zap_attribute_t attr;
1326 const char *typenames[] = {
1327 /* 0 */ "not specified",
1328 /* 1 */ "FIFO",
1329 /* 2 */ "Character Device",
1330 /* 3 */ "3 (invalid)",
1331 /* 4 */ "Directory",
1332 /* 5 */ "5 (invalid)",
1333 /* 6 */ "Block Device",
1334 /* 7 */ "7 (invalid)",
1335 /* 8 */ "Regular File",
1336 /* 9 */ "9 (invalid)",
1337 /* 10 */ "Symbolic Link",
1338 /* 11 */ "11 (invalid)",
1339 /* 12 */ "Socket",
1340 /* 13 */ "Door",
1341 /* 14 */ "Event Port",
1342 /* 15 */ "15 (invalid)",
1343 };
1344
1345 dump_zap_stats(os, object);
1346 (void) printf("\n");
1347
1348 for (zap_cursor_init(&zc, os, object);
1349 zap_cursor_retrieve(&zc, &attr) == 0;
1350 zap_cursor_advance(&zc)) {
1351 (void) printf("\t\t%s = %lld (type: %s)\n",
1352 attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
1353 typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
1354 }
1355 zap_cursor_fini(&zc);
1356 }
1357
1358 static int
1359 get_dtl_refcount(vdev_t *vd)
1360 {
1361 int refcount = 0;
1362
1363 if (vd->vdev_ops->vdev_op_leaf) {
1364 space_map_t *sm = vd->vdev_dtl_sm;
1365
1366 if (sm != NULL &&
1367 sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
1368 return (1);
1369 return (0);
1370 }
1371
1372 for (unsigned c = 0; c < vd->vdev_children; c++)
1373 refcount += get_dtl_refcount(vd->vdev_child[c]);
1374 return (refcount);
1375 }
1376
1377 static int
1378 get_metaslab_refcount(vdev_t *vd)
1379 {
1380 int refcount = 0;
1381
1382 if (vd->vdev_top == vd) {
1383 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
1384 space_map_t *sm = vd->vdev_ms[m]->ms_sm;
1385
1386 if (sm != NULL &&
1387 sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
1388 refcount++;
1389 }
1390 }
1391 for (unsigned c = 0; c < vd->vdev_children; c++)
1392 refcount += get_metaslab_refcount(vd->vdev_child[c]);
1393
1394 return (refcount);
1395 }
1396
1397 static int
1398 get_obsolete_refcount(vdev_t *vd)
1399 {
1400 uint64_t obsolete_sm_object;
1401 int refcount = 0;
1402
1403 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1404 if (vd->vdev_top == vd && obsolete_sm_object != 0) {
1405 dmu_object_info_t doi;
1406 VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
1407 obsolete_sm_object, &doi));
1408 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
1409 refcount++;
1410 }
1411 } else {
1412 ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
1413 ASSERT3U(obsolete_sm_object, ==, 0);
1414 }
1415 for (unsigned c = 0; c < vd->vdev_children; c++) {
1416 refcount += get_obsolete_refcount(vd->vdev_child[c]);
1417 }
1418
1419 return (refcount);
1420 }
1421
1422 static int
1423 get_prev_obsolete_spacemap_refcount(spa_t *spa)
1424 {
1425 uint64_t prev_obj =
1426 spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
1427 if (prev_obj != 0) {
1428 dmu_object_info_t doi;
1429 VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
1430 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
1431 return (1);
1432 }
1433 }
1434 return (0);
1435 }
1436
1437 static int
1438 get_checkpoint_refcount(vdev_t *vd)
1439 {
1440 int refcount = 0;
1441
1442 if (vd->vdev_top == vd && vd->vdev_top_zap != 0 &&
1443 zap_contains(spa_meta_objset(vd->vdev_spa),
1444 vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) == 0)
1445 refcount++;
1446
1447 for (uint64_t c = 0; c < vd->vdev_children; c++)
1448 refcount += get_checkpoint_refcount(vd->vdev_child[c]);
1449
1450 return (refcount);
1451 }
1452
1453 static int
1454 get_log_spacemap_refcount(spa_t *spa)
1455 {
1456 return (avl_numnodes(&spa->spa_sm_logs_by_txg));
1457 }
1458
1459 static int
1460 verify_spacemap_refcounts(spa_t *spa)
1461 {
1462 uint64_t expected_refcount = 0;
1463 uint64_t actual_refcount;
1464
1465 (void) feature_get_refcount(spa,
1466 &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
1467 &expected_refcount);
1468 actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
1469 actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
1470 actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
1471 actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
1472 actual_refcount += get_checkpoint_refcount(spa->spa_root_vdev);
1473 actual_refcount += get_log_spacemap_refcount(spa);
1474
1475 if (expected_refcount != actual_refcount) {
1476 (void) printf("space map refcount mismatch: expected %lld != "
1477 "actual %lld\n",
1478 (longlong_t)expected_refcount,
1479 (longlong_t)actual_refcount);
1480 return (2);
1481 }
1482 return (0);
1483 }
1484
1485 static void
1486 dump_spacemap(objset_t *os, space_map_t *sm)
1487 {
1488 const char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
1489 "INVALID", "INVALID", "INVALID", "INVALID" };
1490
1491 if (sm == NULL)
1492 return;
1493
1494 (void) printf("space map object %llu:\n",
1495 (longlong_t)sm->sm_object);
1496 (void) printf(" smp_length = 0x%llx\n",
1497 (longlong_t)sm->sm_phys->smp_length);
1498 (void) printf(" smp_alloc = 0x%llx\n",
1499 (longlong_t)sm->sm_phys->smp_alloc);
1500
1501 if (dump_opt['d'] < 6 && dump_opt['m'] < 4)
1502 return;
1503
1504 /*
1505 * Print out the freelist entries in both encoded and decoded form.
1506 */
1507 uint8_t mapshift = sm->sm_shift;
1508 int64_t alloc = 0;
1509 uint64_t word, entry_id = 0;
1510 for (uint64_t offset = 0; offset < space_map_length(sm);
1511 offset += sizeof (word)) {
1512
1513 VERIFY0(dmu_read(os, space_map_object(sm), offset,
1514 sizeof (word), &word, DMU_READ_PREFETCH));
1515
1516 if (sm_entry_is_debug(word)) {
1517 uint64_t de_txg = SM_DEBUG_TXG_DECODE(word);
1518 uint64_t de_sync_pass = SM_DEBUG_SYNCPASS_DECODE(word);
1519 if (de_txg == 0) {
1520 (void) printf(
1521 "\t [%6llu] PADDING\n",
1522 (u_longlong_t)entry_id);
1523 } else {
1524 (void) printf(
1525 "\t [%6llu] %s: txg %llu pass %llu\n",
1526 (u_longlong_t)entry_id,
1527 ddata[SM_DEBUG_ACTION_DECODE(word)],
1528 (u_longlong_t)de_txg,
1529 (u_longlong_t)de_sync_pass);
1530 }
1531 entry_id++;
1532 continue;
1533 }
1534
1535 uint8_t words;
1536 char entry_type;
1537 uint64_t entry_off, entry_run, entry_vdev = SM_NO_VDEVID;
1538
1539 if (sm_entry_is_single_word(word)) {
1540 entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
1541 'A' : 'F';
1542 entry_off = (SM_OFFSET_DECODE(word) << mapshift) +
1543 sm->sm_start;
1544 entry_run = SM_RUN_DECODE(word) << mapshift;
1545 words = 1;
1546 } else {
1547 /* it is a two-word entry so we read another word */
1548 ASSERT(sm_entry_is_double_word(word));
1549
1550 uint64_t extra_word;
1551 offset += sizeof (extra_word);
1552 VERIFY0(dmu_read(os, space_map_object(sm), offset,
1553 sizeof (extra_word), &extra_word,
1554 DMU_READ_PREFETCH));
1555
1556 ASSERT3U(offset, <=, space_map_length(sm));
1557
1558 entry_run = SM2_RUN_DECODE(word) << mapshift;
1559 entry_vdev = SM2_VDEV_DECODE(word);
1560 entry_type = (SM2_TYPE_DECODE(extra_word) == SM_ALLOC) ?
1561 'A' : 'F';
1562 entry_off = (SM2_OFFSET_DECODE(extra_word) <<
1563 mapshift) + sm->sm_start;
1564 words = 2;
1565 }
1566
1567 (void) printf("\t [%6llu] %c range:"
1568 " %010llx-%010llx size: %06llx vdev: %06llu words: %u\n",
1569 (u_longlong_t)entry_id,
1570 entry_type, (u_longlong_t)entry_off,
1571 (u_longlong_t)(entry_off + entry_run),
1572 (u_longlong_t)entry_run,
1573 (u_longlong_t)entry_vdev, words);
1574
1575 if (entry_type == 'A')
1576 alloc += entry_run;
1577 else
1578 alloc -= entry_run;
1579 entry_id++;
1580 }
1581 if (alloc != space_map_allocated(sm)) {
1582 (void) printf("space_map_object alloc (%lld) INCONSISTENT "
1583 "with space map summary (%lld)\n",
1584 (longlong_t)space_map_allocated(sm), (longlong_t)alloc);
1585 }
1586 }
1587
1588 static void
1589 dump_metaslab_stats(metaslab_t *msp)
1590 {
1591 char maxbuf[32];
1592 range_tree_t *rt = msp->ms_allocatable;
1593 zfs_btree_t *t = &msp->ms_allocatable_by_size;
1594 int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1595
1596 /* max sure nicenum has enough space */
1597 CTASSERT(sizeof (maxbuf) >= NN_NUMBUF_SZ);
1598
1599 zdb_nicenum(metaslab_largest_allocatable(msp), maxbuf, sizeof (maxbuf));
1600
1601 (void) printf("\t %25s %10lu %7s %6s %4s %4d%%\n",
1602 "segments", zfs_btree_numnodes(t), "maxsize", maxbuf,
1603 "freepct", free_pct);
1604 (void) printf("\tIn-memory histogram:\n");
1605 dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1606 }
1607
1608 static void
1609 dump_metaslab(metaslab_t *msp)
1610 {
1611 vdev_t *vd = msp->ms_group->mg_vd;
1612 spa_t *spa = vd->vdev_spa;
1613 space_map_t *sm = msp->ms_sm;
1614 char freebuf[32];
1615
1616 zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
1617 sizeof (freebuf));
1618
1619 (void) printf(
1620 "\tmetaslab %6llu offset %12llx spacemap %6llu free %5s\n",
1621 (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
1622 (u_longlong_t)space_map_object(sm), freebuf);
1623
1624 if (dump_opt['m'] > 2 && !dump_opt['L']) {
1625 mutex_enter(&msp->ms_lock);
1626 VERIFY0(metaslab_load(msp));
1627 range_tree_stat_verify(msp->ms_allocatable);
1628 dump_metaslab_stats(msp);
1629 metaslab_unload(msp);
1630 mutex_exit(&msp->ms_lock);
1631 }
1632
1633 if (dump_opt['m'] > 1 && sm != NULL &&
1634 spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
1635 /*
1636 * The space map histogram represents free space in chunks
1637 * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
1638 */
1639 (void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
1640 (u_longlong_t)msp->ms_fragmentation);
1641 dump_histogram(sm->sm_phys->smp_histogram,
1642 SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
1643 }
1644
1645 if (vd->vdev_ops == &vdev_draid_ops)
1646 ASSERT3U(msp->ms_size, <=, 1ULL << vd->vdev_ms_shift);
1647 else
1648 ASSERT3U(msp->ms_size, ==, 1ULL << vd->vdev_ms_shift);
1649
1650 dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
1651
1652 if (spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
1653 (void) printf("\tFlush data:\n\tunflushed txg=%llu\n\n",
1654 (u_longlong_t)metaslab_unflushed_txg(msp));
1655 }
1656 }
1657
1658 static void
1659 print_vdev_metaslab_header(vdev_t *vd)
1660 {
1661 vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
1662 const char *bias_str = "";
1663 if (alloc_bias == VDEV_BIAS_LOG || vd->vdev_islog) {
1664 bias_str = VDEV_ALLOC_BIAS_LOG;
1665 } else if (alloc_bias == VDEV_BIAS_SPECIAL) {
1666 bias_str = VDEV_ALLOC_BIAS_SPECIAL;
1667 } else if (alloc_bias == VDEV_BIAS_DEDUP) {
1668 bias_str = VDEV_ALLOC_BIAS_DEDUP;
1669 }
1670
1671 uint64_t ms_flush_data_obj = 0;
1672 if (vd->vdev_top_zap != 0) {
1673 int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
1674 vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
1675 sizeof (uint64_t), 1, &ms_flush_data_obj);
1676 if (error != ENOENT) {
1677 ASSERT0(error);
1678 }
1679 }
1680
1681 (void) printf("\tvdev %10llu %s",
1682 (u_longlong_t)vd->vdev_id, bias_str);
1683
1684 if (ms_flush_data_obj != 0) {
1685 (void) printf(" ms_unflushed_phys object %llu",
1686 (u_longlong_t)ms_flush_data_obj);
1687 }
1688
1689 (void) printf("\n\t%-10s%5llu %-19s %-15s %-12s\n",
1690 "metaslabs", (u_longlong_t)vd->vdev_ms_count,
1691 "offset", "spacemap", "free");
1692 (void) printf("\t%15s %19s %15s %12s\n",
1693 "---------------", "-------------------",
1694 "---------------", "------------");
1695 }
1696
1697 static void
1698 dump_metaslab_groups(spa_t *spa)
1699 {
1700 vdev_t *rvd = spa->spa_root_vdev;
1701 metaslab_class_t *mc = spa_normal_class(spa);
1702 uint64_t fragmentation;
1703
1704 metaslab_class_histogram_verify(mc);
1705
1706 for (unsigned c = 0; c < rvd->vdev_children; c++) {
1707 vdev_t *tvd = rvd->vdev_child[c];
1708 metaslab_group_t *mg = tvd->vdev_mg;
1709
1710 if (mg == NULL || mg->mg_class != mc)
1711 continue;
1712
1713 metaslab_group_histogram_verify(mg);
1714 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
1715
1716 (void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
1717 "fragmentation",
1718 (u_longlong_t)tvd->vdev_id,
1719 (u_longlong_t)tvd->vdev_ms_count);
1720 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
1721 (void) printf("%3s\n", "-");
1722 } else {
1723 (void) printf("%3llu%%\n",
1724 (u_longlong_t)mg->mg_fragmentation);
1725 }
1726 dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1727 }
1728
1729 (void) printf("\tpool %s\tfragmentation", spa_name(spa));
1730 fragmentation = metaslab_class_fragmentation(mc);
1731 if (fragmentation == ZFS_FRAG_INVALID)
1732 (void) printf("\t%3s\n", "-");
1733 else
1734 (void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
1735 dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1736 }
1737
1738 static void
1739 print_vdev_indirect(vdev_t *vd)
1740 {
1741 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1742 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1743 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
1744
1745 if (vim == NULL) {
1746 ASSERT3P(vib, ==, NULL);
1747 return;
1748 }
1749
1750 ASSERT3U(vdev_indirect_mapping_object(vim), ==,
1751 vic->vic_mapping_object);
1752 ASSERT3U(vdev_indirect_births_object(vib), ==,
1753 vic->vic_births_object);
1754
1755 (void) printf("indirect births obj %llu:\n",
1756 (longlong_t)vic->vic_births_object);
1757 (void) printf(" vib_count = %llu\n",
1758 (longlong_t)vdev_indirect_births_count(vib));
1759 for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
1760 vdev_indirect_birth_entry_phys_t *cur_vibe =
1761 &vib->vib_entries[i];
1762 (void) printf("\toffset %llx -> txg %llu\n",
1763 (longlong_t)cur_vibe->vibe_offset,
1764 (longlong_t)cur_vibe->vibe_phys_birth_txg);
1765 }
1766 (void) printf("\n");
1767
1768 (void) printf("indirect mapping obj %llu:\n",
1769 (longlong_t)vic->vic_mapping_object);
1770 (void) printf(" vim_max_offset = 0x%llx\n",
1771 (longlong_t)vdev_indirect_mapping_max_offset(vim));
1772 (void) printf(" vim_bytes_mapped = 0x%llx\n",
1773 (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
1774 (void) printf(" vim_count = %llu\n",
1775 (longlong_t)vdev_indirect_mapping_num_entries(vim));
1776
1777 if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
1778 return;
1779
1780 uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
1781
1782 for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
1783 vdev_indirect_mapping_entry_phys_t *vimep =
1784 &vim->vim_entries[i];
1785 (void) printf("\t<%llx:%llx:%llx> -> "
1786 "<%llx:%llx:%llx> (%x obsolete)\n",
1787 (longlong_t)vd->vdev_id,
1788 (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
1789 (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1790 (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
1791 (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
1792 (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1793 counts[i]);
1794 }
1795 (void) printf("\n");
1796
1797 uint64_t obsolete_sm_object;
1798 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1799 if (obsolete_sm_object != 0) {
1800 objset_t *mos = vd->vdev_spa->spa_meta_objset;
1801 (void) printf("obsolete space map object %llu:\n",
1802 (u_longlong_t)obsolete_sm_object);
1803 ASSERT(vd->vdev_obsolete_sm != NULL);
1804 ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
1805 obsolete_sm_object);
1806 dump_spacemap(mos, vd->vdev_obsolete_sm);
1807 (void) printf("\n");
1808 }
1809 }
1810
1811 static void
1812 dump_metaslabs(spa_t *spa)
1813 {
1814 vdev_t *vd, *rvd = spa->spa_root_vdev;
1815 uint64_t m, c = 0, children = rvd->vdev_children;
1816
1817 (void) printf("\nMetaslabs:\n");
1818
1819 if (!dump_opt['d'] && zopt_metaslab_args > 0) {
1820 c = zopt_metaslab[0];
1821
1822 if (c >= children)
1823 (void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1824
1825 if (zopt_metaslab_args > 1) {
1826 vd = rvd->vdev_child[c];
1827 print_vdev_metaslab_header(vd);
1828
1829 for (m = 1; m < zopt_metaslab_args; m++) {
1830 if (zopt_metaslab[m] < vd->vdev_ms_count)
1831 dump_metaslab(
1832 vd->vdev_ms[zopt_metaslab[m]]);
1833 else
1834 (void) fprintf(stderr, "bad metaslab "
1835 "number %llu\n",
1836 (u_longlong_t)zopt_metaslab[m]);
1837 }
1838 (void) printf("\n");
1839 return;
1840 }
1841 children = c + 1;
1842 }
1843 for (; c < children; c++) {
1844 vd = rvd->vdev_child[c];
1845 print_vdev_metaslab_header(vd);
1846
1847 print_vdev_indirect(vd);
1848
1849 for (m = 0; m < vd->vdev_ms_count; m++)
1850 dump_metaslab(vd->vdev_ms[m]);
1851 (void) printf("\n");
1852 }
1853 }
1854
1855 static void
1856 dump_log_spacemaps(spa_t *spa)
1857 {
1858 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
1859 return;
1860
1861 (void) printf("\nLog Space Maps in Pool:\n");
1862 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
1863 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
1864 space_map_t *sm = NULL;
1865 VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
1866 sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
1867
1868 (void) printf("Log Spacemap object %llu txg %llu\n",
1869 (u_longlong_t)sls->sls_sm_obj, (u_longlong_t)sls->sls_txg);
1870 dump_spacemap(spa->spa_meta_objset, sm);
1871 space_map_close(sm);
1872 }
1873 (void) printf("\n");
1874 }
1875
1876 static void
1877 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
1878 {
1879 const ddt_phys_t *ddp = dde->dde_phys;
1880 const ddt_key_t *ddk = &dde->dde_key;
1881 const char *types[4] = { "ditto", "single", "double", "triple" };
1882 char blkbuf[BP_SPRINTF_LEN];
1883 blkptr_t blk;
1884 int p;
1885
1886 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1887 if (ddp->ddp_phys_birth == 0)
1888 continue;
1889 ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
1890 snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1891 (void) printf("index %llx refcnt %llu %s %s\n",
1892 (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
1893 types[p], blkbuf);
1894 }
1895 }
1896
1897 static void
1898 dump_dedup_ratio(const ddt_stat_t *dds)
1899 {
1900 double rL, rP, rD, D, dedup, compress, copies;
1901
1902 if (dds->dds_blocks == 0)
1903 return;
1904
1905 rL = (double)dds->dds_ref_lsize;
1906 rP = (double)dds->dds_ref_psize;
1907 rD = (double)dds->dds_ref_dsize;
1908 D = (double)dds->dds_dsize;
1909
1910 dedup = rD / D;
1911 compress = rL / rP;
1912 copies = rD / rP;
1913
1914 (void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
1915 "dedup * compress / copies = %.2f\n\n",
1916 dedup, compress, copies, dedup * compress / copies);
1917 }
1918
1919 static void
1920 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
1921 {
1922 char name[DDT_NAMELEN];
1923 ddt_entry_t dde;
1924 uint64_t walk = 0;
1925 dmu_object_info_t doi;
1926 uint64_t count, dspace, mspace;
1927 int error;
1928
1929 error = ddt_object_info(ddt, type, class, &doi);
1930
1931 if (error == ENOENT)
1932 return;
1933 ASSERT(error == 0);
1934
1935 error = ddt_object_count(ddt, type, class, &count);
1936 ASSERT(error == 0);
1937 if (count == 0)
1938 return;
1939
1940 dspace = doi.doi_physical_blocks_512 << 9;
1941 mspace = doi.doi_fill_count * doi.doi_data_block_size;
1942
1943 ddt_object_name(ddt, type, class, name);
1944
1945 (void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
1946 name,
1947 (u_longlong_t)count,
1948 (u_longlong_t)(dspace / count),
1949 (u_longlong_t)(mspace / count));
1950
1951 if (dump_opt['D'] < 3)
1952 return;
1953
1954 zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
1955
1956 if (dump_opt['D'] < 4)
1957 return;
1958
1959 if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
1960 return;
1961
1962 (void) printf("%s contents:\n\n", name);
1963
1964 while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
1965 dump_dde(ddt, &dde, walk);
1966
1967 ASSERT3U(error, ==, ENOENT);
1968
1969 (void) printf("\n");
1970 }
1971
1972 static void
1973 dump_all_ddts(spa_t *spa)
1974 {
1975 ddt_histogram_t ddh_total;
1976 ddt_stat_t dds_total;
1977
1978 bzero(&ddh_total, sizeof (ddh_total));
1979 bzero(&dds_total, sizeof (dds_total));
1980
1981 for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1982 ddt_t *ddt = spa->spa_ddt[c];
1983 for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
1984 for (enum ddt_class class = 0; class < DDT_CLASSES;
1985 class++) {
1986 dump_ddt(ddt, type, class);
1987 }
1988 }
1989 }
1990
1991 ddt_get_dedup_stats(spa, &dds_total);
1992
1993 if (dds_total.dds_blocks == 0) {
1994 (void) printf("All DDTs are empty\n");
1995 return;
1996 }
1997
1998 (void) printf("\n");
1999
2000 if (dump_opt['D'] > 1) {
2001 (void) printf("DDT histogram (aggregated over all DDTs):\n");
2002 ddt_get_dedup_histogram(spa, &ddh_total);
2003 zpool_dump_ddt(&dds_total, &ddh_total);
2004 }
2005
2006 dump_dedup_ratio(&dds_total);
2007 }
2008
2009 static void
2010 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
2011 {
2012 char *prefix = arg;
2013
2014 (void) printf("%s [%llu,%llu) length %llu\n",
2015 prefix,
2016 (u_longlong_t)start,
2017 (u_longlong_t)(start + size),
2018 (u_longlong_t)(size));
2019 }
2020
2021 static void
2022 dump_dtl(vdev_t *vd, int indent)
2023 {
2024 spa_t *spa = vd->vdev_spa;
2025 boolean_t required;
2026 const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
2027 "outage" };
2028 char prefix[256];
2029
2030 spa_vdev_state_enter(spa, SCL_NONE);
2031 required = vdev_dtl_required(vd);
2032 (void) spa_vdev_state_exit(spa, NULL, 0);
2033
2034 if (indent == 0)
2035 (void) printf("\nDirty time logs:\n\n");
2036
2037 (void) printf("\t%*s%s [%s]\n", indent, "",
2038 vd->vdev_path ? vd->vdev_path :
2039 vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
2040 required ? "DTL-required" : "DTL-expendable");
2041
2042 for (int t = 0; t < DTL_TYPES; t++) {
2043 range_tree_t *rt = vd->vdev_dtl[t];
2044 if (range_tree_space(rt) == 0)
2045 continue;
2046 (void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
2047 indent + 2, "", name[t]);
2048 range_tree_walk(rt, dump_dtl_seg, prefix);
2049 if (dump_opt['d'] > 5 && vd->vdev_children == 0)
2050 dump_spacemap(spa->spa_meta_objset,
2051 vd->vdev_dtl_sm);
2052 }
2053
2054 for (unsigned c = 0; c < vd->vdev_children; c++)
2055 dump_dtl(vd->vdev_child[c], indent + 4);
2056 }
2057
2058 static void
2059 dump_history(spa_t *spa)
2060 {
2061 nvlist_t **events = NULL;
2062 char *buf;
2063 uint64_t resid, len, off = 0;
2064 uint_t num = 0;
2065 int error;
2066 time_t tsec;
2067 struct tm t;
2068 char tbuf[30];
2069 char internalstr[MAXPATHLEN];
2070
2071 if ((buf = malloc(SPA_OLD_MAXBLOCKSIZE)) == NULL) {
2072 (void) fprintf(stderr, "%s: unable to allocate I/O buffer\n",
2073 __func__);
2074 return;
2075 }
2076
2077 do {
2078 len = SPA_OLD_MAXBLOCKSIZE;
2079
2080 if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
2081 (void) fprintf(stderr, "Unable to read history: "
2082 "error %d\n", error);
2083 free(buf);
2084 return;
2085 }
2086
2087 if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
2088 break;
2089
2090 off -= resid;
2091 } while (len != 0);
2092
2093 (void) printf("\nHistory:\n");
2094 for (unsigned i = 0; i < num; i++) {
2095 uint64_t time, txg, ievent;
2096 char *cmd, *intstr;
2097 boolean_t printed = B_FALSE;
2098
2099 if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
2100 &time) != 0)
2101 goto next;
2102 if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
2103 &cmd) != 0) {
2104 if (nvlist_lookup_uint64(events[i],
2105 ZPOOL_HIST_INT_EVENT, &ievent) != 0)
2106 goto next;
2107 verify(nvlist_lookup_uint64(events[i],
2108 ZPOOL_HIST_TXG, &txg) == 0);
2109 verify(nvlist_lookup_string(events[i],
2110 ZPOOL_HIST_INT_STR, &intstr) == 0);
2111 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
2112 goto next;
2113
2114 (void) snprintf(internalstr,
2115 sizeof (internalstr),
2116 "[internal %s txg:%lld] %s",
2117 zfs_history_event_names[ievent],
2118 (longlong_t)txg, intstr);
2119 cmd = internalstr;
2120 }
2121 tsec = time;
2122 (void) localtime_r(&tsec, &t);
2123 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
2124 (void) printf("%s %s\n", tbuf, cmd);
2125 printed = B_TRUE;
2126
2127 next:
2128 if (dump_opt['h'] > 1) {
2129 if (!printed)
2130 (void) printf("unrecognized record:\n");
2131 dump_nvlist(events[i], 2);
2132 }
2133 }
2134 free(buf);
2135 }
2136
2137 /*ARGSUSED*/
2138 static void
2139 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
2140 {
2141 }
2142
2143 static uint64_t
2144 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
2145 const zbookmark_phys_t *zb)
2146 {
2147 if (dnp == NULL) {
2148 ASSERT(zb->zb_level < 0);
2149 if (zb->zb_object == 0)
2150 return (zb->zb_blkid);
2151 return (zb->zb_blkid * BP_GET_LSIZE(bp));
2152 }
2153
2154 ASSERT(zb->zb_level >= 0);
2155
2156 return ((zb->zb_blkid <<
2157 (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
2158 dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
2159 }
2160
2161 static void
2162 snprintf_zstd_header(spa_t *spa, char *blkbuf, size_t buflen,
2163 const blkptr_t *bp)
2164 {
2165 abd_t *pabd;
2166 void *buf;
2167 zio_t *zio;
2168 zfs_zstdhdr_t zstd_hdr;
2169 int error;
2170
2171 if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_ZSTD)
2172 return;
2173
2174 if (BP_IS_HOLE(bp))
2175 return;
2176
2177 if (BP_IS_EMBEDDED(bp)) {
2178 buf = malloc(SPA_MAXBLOCKSIZE);
2179 if (buf == NULL) {
2180 (void) fprintf(stderr, "out of memory\n");
2181 exit(1);
2182 }
2183 decode_embedded_bp_compressed(bp, buf);
2184 memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2185 free(buf);
2186 zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2187 zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2188 (void) snprintf(blkbuf + strlen(blkbuf),
2189 buflen - strlen(blkbuf),
2190 " ZSTD:size=%u:version=%u:level=%u:EMBEDDED",
2191 zstd_hdr.c_len, zstd_hdr.version, zstd_hdr.level);
2192 return;
2193 }
2194
2195 pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
2196 zio = zio_root(spa, NULL, NULL, 0);
2197
2198 /* Decrypt but don't decompress so we can read the compression header */
2199 zio_nowait(zio_read(zio, spa, bp, pabd, BP_GET_PSIZE(bp), NULL, NULL,
2200 ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW_COMPRESS,
2201 NULL));
2202 error = zio_wait(zio);
2203 if (error) {
2204 (void) fprintf(stderr, "read failed: %d\n", error);
2205 return;
2206 }
2207 buf = abd_borrow_buf_copy(pabd, BP_GET_LSIZE(bp));
2208 memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2209 zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2210 zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2211
2212 (void) snprintf(blkbuf + strlen(blkbuf),
2213 buflen - strlen(blkbuf),
2214 " ZSTD:size=%u:version=%u:level=%u:NORMAL",
2215 zstd_hdr.c_len, zstd_hdr.version, zstd_hdr.level);
2216
2217 abd_return_buf_copy(pabd, buf, BP_GET_LSIZE(bp));
2218 }
2219
2220 static void
2221 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp,
2222 boolean_t bp_freed)
2223 {
2224 const dva_t *dva = bp->blk_dva;
2225 int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
2226 int i;
2227
2228 if (dump_opt['b'] >= 6) {
2229 snprintf_blkptr(blkbuf, buflen, bp);
2230 if (bp_freed) {
2231 (void) snprintf(blkbuf + strlen(blkbuf),
2232 buflen - strlen(blkbuf), " %s", "FREE");
2233 }
2234 return;
2235 }
2236
2237 if (BP_IS_EMBEDDED(bp)) {
2238 (void) sprintf(blkbuf,
2239 "EMBEDDED et=%u %llxL/%llxP B=%llu",
2240 (int)BPE_GET_ETYPE(bp),
2241 (u_longlong_t)BPE_GET_LSIZE(bp),
2242 (u_longlong_t)BPE_GET_PSIZE(bp),
2243 (u_longlong_t)bp->blk_birth);
2244 return;
2245 }
2246
2247 blkbuf[0] = '\0';
2248
2249 for (i = 0; i < ndvas; i++)
2250 (void) snprintf(blkbuf + strlen(blkbuf),
2251 buflen - strlen(blkbuf), "%llu:%llx:%llx ",
2252 (u_longlong_t)DVA_GET_VDEV(&dva[i]),
2253 (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
2254 (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
2255
2256 if (BP_IS_HOLE(bp)) {
2257 (void) snprintf(blkbuf + strlen(blkbuf),
2258 buflen - strlen(blkbuf),
2259 "%llxL B=%llu",
2260 (u_longlong_t)BP_GET_LSIZE(bp),
2261 (u_longlong_t)bp->blk_birth);
2262 } else {
2263 (void) snprintf(blkbuf + strlen(blkbuf),
2264 buflen - strlen(blkbuf),
2265 "%llxL/%llxP F=%llu B=%llu/%llu",
2266 (u_longlong_t)BP_GET_LSIZE(bp),
2267 (u_longlong_t)BP_GET_PSIZE(bp),
2268 (u_longlong_t)BP_GET_FILL(bp),
2269 (u_longlong_t)bp->blk_birth,
2270 (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
2271 if (bp_freed)
2272 (void) snprintf(blkbuf + strlen(blkbuf),
2273 buflen - strlen(blkbuf), " %s", "FREE");
2274 (void) snprintf(blkbuf + strlen(blkbuf),
2275 buflen - strlen(blkbuf), " cksum=%llx:%llx:%llx:%llx",
2276 (u_longlong_t)bp->blk_cksum.zc_word[0],
2277 (u_longlong_t)bp->blk_cksum.zc_word[1],
2278 (u_longlong_t)bp->blk_cksum.zc_word[2],
2279 (u_longlong_t)bp->blk_cksum.zc_word[3]);
2280 }
2281 }
2282
2283 static void
2284 print_indirect(spa_t *spa, blkptr_t *bp, const zbookmark_phys_t *zb,
2285 const dnode_phys_t *dnp)
2286 {
2287 char blkbuf[BP_SPRINTF_LEN];
2288 int l;
2289
2290 if (!BP_IS_EMBEDDED(bp)) {
2291 ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
2292 ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
2293 }
2294
2295 (void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
2296
2297 ASSERT(zb->zb_level >= 0);
2298
2299 for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
2300 if (l == zb->zb_level) {
2301 (void) printf("L%llx", (u_longlong_t)zb->zb_level);
2302 } else {
2303 (void) printf(" ");
2304 }
2305 }
2306
2307 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, B_FALSE);
2308 if (dump_opt['Z'] && BP_GET_COMPRESS(bp) == ZIO_COMPRESS_ZSTD)
2309 snprintf_zstd_header(spa, blkbuf, sizeof (blkbuf), bp);
2310 (void) printf("%s\n", blkbuf);
2311 }
2312
2313 static int
2314 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
2315 blkptr_t *bp, const zbookmark_phys_t *zb)
2316 {
2317 int err = 0;
2318
2319 if (bp->blk_birth == 0)
2320 return (0);
2321
2322 print_indirect(spa, bp, zb, dnp);
2323
2324 if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
2325 arc_flags_t flags = ARC_FLAG_WAIT;
2326 int i;
2327 blkptr_t *cbp;
2328 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
2329 arc_buf_t *buf;
2330 uint64_t fill = 0;
2331 ASSERT(!BP_IS_REDACTED(bp));
2332
2333 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2334 ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
2335 if (err)
2336 return (err);
2337 ASSERT(buf->b_data);
2338
2339 /* recursively visit blocks below this */
2340 cbp = buf->b_data;
2341 for (i = 0; i < epb; i++, cbp++) {
2342 zbookmark_phys_t czb;
2343
2344 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
2345 zb->zb_level - 1,
2346 zb->zb_blkid * epb + i);
2347 err = visit_indirect(spa, dnp, cbp, &czb);
2348 if (err)
2349 break;
2350 fill += BP_GET_FILL(cbp);
2351 }
2352 if (!err)
2353 ASSERT3U(fill, ==, BP_GET_FILL(bp));
2354 arc_buf_destroy(buf, &buf);
2355 }
2356
2357 return (err);
2358 }
2359
2360 /*ARGSUSED*/
2361 static void
2362 dump_indirect(dnode_t *dn)
2363 {
2364 dnode_phys_t *dnp = dn->dn_phys;
2365 int j;
2366 zbookmark_phys_t czb;
2367
2368 (void) printf("Indirect blocks:\n");
2369
2370 SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
2371 dn->dn_object, dnp->dn_nlevels - 1, 0);
2372 for (j = 0; j < dnp->dn_nblkptr; j++) {
2373 czb.zb_blkid = j;
2374 (void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
2375 &dnp->dn_blkptr[j], &czb);
2376 }
2377
2378 (void) printf("\n");
2379 }
2380
2381 /*ARGSUSED*/
2382 static void
2383 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
2384 {
2385 dsl_dir_phys_t *dd = data;
2386 time_t crtime;
2387 char nice[32];
2388
2389 /* make sure nicenum has enough space */
2390 CTASSERT(sizeof (nice) >= NN_NUMBUF_SZ);
2391
2392 if (dd == NULL)
2393 return;
2394
2395 ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
2396
2397 crtime = dd->dd_creation_time;
2398 (void) printf("\t\tcreation_time = %s", ctime(&crtime));
2399 (void) printf("\t\thead_dataset_obj = %llu\n",
2400 (u_longlong_t)dd->dd_head_dataset_obj);
2401 (void) printf("\t\tparent_dir_obj = %llu\n",
2402 (u_longlong_t)dd->dd_parent_obj);
2403 (void) printf("\t\torigin_obj = %llu\n",
2404 (u_longlong_t)dd->dd_origin_obj);
2405 (void) printf("\t\tchild_dir_zapobj = %llu\n",
2406 (u_longlong_t)dd->dd_child_dir_zapobj);
2407 zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
2408 (void) printf("\t\tused_bytes = %s\n", nice);
2409 zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
2410 (void) printf("\t\tcompressed_bytes = %s\n", nice);
2411 zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
2412 (void) printf("\t\tuncompressed_bytes = %s\n", nice);
2413 zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
2414 (void) printf("\t\tquota = %s\n", nice);
2415 zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
2416 (void) printf("\t\treserved = %s\n", nice);
2417 (void) printf("\t\tprops_zapobj = %llu\n",
2418 (u_longlong_t)dd->dd_props_zapobj);
2419 (void) printf("\t\tdeleg_zapobj = %llu\n",
2420 (u_longlong_t)dd->dd_deleg_zapobj);
2421 (void) printf("\t\tflags = %llx\n",
2422 (u_longlong_t)dd->dd_flags);
2423
2424 #define DO(which) \
2425 zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
2426 sizeof (nice)); \
2427 (void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
2428 DO(HEAD);
2429 DO(SNAP);
2430 DO(CHILD);
2431 DO(CHILD_RSRV);
2432 DO(REFRSRV);
2433 #undef DO
2434 (void) printf("\t\tclones = %llu\n",
2435 (u_longlong_t)dd->dd_clones);
2436 }
2437
2438 /*ARGSUSED*/
2439 static void
2440 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
2441 {
2442 dsl_dataset_phys_t *ds = data;
2443 time_t crtime;
2444 char used[32], compressed[32], uncompressed[32], unique[32];
2445 char blkbuf[BP_SPRINTF_LEN];
2446
2447 /* make sure nicenum has enough space */
2448 CTASSERT(sizeof (used) >= NN_NUMBUF_SZ);
2449 CTASSERT(sizeof (compressed) >= NN_NUMBUF_SZ);
2450 CTASSERT(sizeof (uncompressed) >= NN_NUMBUF_SZ);
2451 CTASSERT(sizeof (unique) >= NN_NUMBUF_SZ);
2452
2453 if (ds == NULL)
2454 return;
2455
2456 ASSERT(size == sizeof (*ds));
2457 crtime = ds->ds_creation_time;
2458 zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
2459 zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
2460 zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
2461 sizeof (uncompressed));
2462 zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
2463 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
2464
2465 (void) printf("\t\tdir_obj = %llu\n",
2466 (u_longlong_t)ds->ds_dir_obj);
2467 (void) printf("\t\tprev_snap_obj = %llu\n",
2468 (u_longlong_t)ds->ds_prev_snap_obj);
2469 (void) printf("\t\tprev_snap_txg = %llu\n",
2470 (u_longlong_t)ds->ds_prev_snap_txg);
2471 (void) printf("\t\tnext_snap_obj = %llu\n",
2472 (u_longlong_t)ds->ds_next_snap_obj);
2473 (void) printf("\t\tsnapnames_zapobj = %llu\n",
2474 (u_longlong_t)ds->ds_snapnames_zapobj);
2475 (void) printf("\t\tnum_children = %llu\n",
2476 (u_longlong_t)ds->ds_num_children);
2477 (void) printf("\t\tuserrefs_obj = %llu\n",
2478 (u_longlong_t)ds->ds_userrefs_obj);
2479 (void) printf("\t\tcreation_time = %s", ctime(&crtime));
2480 (void) printf("\t\tcreation_txg = %llu\n",
2481 (u_longlong_t)ds->ds_creation_txg);
2482 (void) printf("\t\tdeadlist_obj = %llu\n",
2483 (u_longlong_t)ds->ds_deadlist_obj);
2484 (void) printf("\t\tused_bytes = %s\n", used);
2485 (void) printf("\t\tcompressed_bytes = %s\n", compressed);
2486 (void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
2487 (void) printf("\t\tunique = %s\n", unique);
2488 (void) printf("\t\tfsid_guid = %llu\n",
2489 (u_longlong_t)ds->ds_fsid_guid);
2490 (void) printf("\t\tguid = %llu\n",
2491 (u_longlong_t)ds->ds_guid);
2492 (void) printf("\t\tflags = %llx\n",
2493 (u_longlong_t)ds->ds_flags);
2494 (void) printf("\t\tnext_clones_obj = %llu\n",
2495 (u_longlong_t)ds->ds_next_clones_obj);
2496 (void) printf("\t\tprops_obj = %llu\n",
2497 (u_longlong_t)ds->ds_props_obj);
2498 (void) printf("\t\tbp = %s\n", blkbuf);
2499 }
2500
2501 /* ARGSUSED */
2502 static int
2503 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2504 {
2505 char blkbuf[BP_SPRINTF_LEN];
2506
2507 if (bp->blk_birth != 0) {
2508 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2509 (void) printf("\t%s\n", blkbuf);
2510 }
2511 return (0);
2512 }
2513
2514 static void
2515 dump_bptree(objset_t *os, uint64_t obj, const char *name)
2516 {
2517 char bytes[32];
2518 bptree_phys_t *bt;
2519 dmu_buf_t *db;
2520
2521 /* make sure nicenum has enough space */
2522 CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
2523
2524 if (dump_opt['d'] < 3)
2525 return;
2526
2527 VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
2528 bt = db->db_data;
2529 zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
2530 (void) printf("\n %s: %llu datasets, %s\n",
2531 name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
2532 dmu_buf_rele(db, FTAG);
2533
2534 if (dump_opt['d'] < 5)
2535 return;
2536
2537 (void) printf("\n");
2538
2539 (void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
2540 }
2541
2542 /* ARGSUSED */
2543 static int
2544 dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed, dmu_tx_t *tx)
2545 {
2546 char blkbuf[BP_SPRINTF_LEN];
2547
2548 ASSERT(bp->blk_birth != 0);
2549 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, bp_freed);
2550 (void) printf("\t%s\n", blkbuf);
2551 return (0);
2552 }
2553
2554 static void
2555 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
2556 {
2557 char bytes[32];
2558 char comp[32];
2559 char uncomp[32];
2560 uint64_t i;
2561
2562 /* make sure nicenum has enough space */
2563 CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
2564 CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
2565 CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
2566
2567 if (dump_opt['d'] < 3)
2568 return;
2569
2570 zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
2571 if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2572 zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
2573 zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
2574 if (bpo->bpo_havefreed) {
2575 (void) printf(" %*s: object %llu, %llu local "
2576 "blkptrs, %llu freed, %llu subobjs in object %llu, "
2577 "%s (%s/%s comp)\n",
2578 indent * 8, name,
2579 (u_longlong_t)bpo->bpo_object,
2580 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2581 (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2582 (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2583 (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2584 bytes, comp, uncomp);
2585 } else {
2586 (void) printf(" %*s: object %llu, %llu local "
2587 "blkptrs, %llu subobjs in object %llu, "
2588 "%s (%s/%s comp)\n",
2589 indent * 8, name,
2590 (u_longlong_t)bpo->bpo_object,
2591 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2592 (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2593 (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2594 bytes, comp, uncomp);
2595 }
2596
2597 for (i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2598 uint64_t subobj;
2599 bpobj_t subbpo;
2600 int error;
2601 VERIFY0(dmu_read(bpo->bpo_os,
2602 bpo->bpo_phys->bpo_subobjs,
2603 i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2604 error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2605 if (error != 0) {
2606 (void) printf("ERROR %u while trying to open "
2607 "subobj id %llu\n",
2608 error, (u_longlong_t)subobj);
2609 continue;
2610 }
2611 dump_full_bpobj(&subbpo, "subobj", indent + 1);
2612 bpobj_close(&subbpo);
2613 }
2614 } else {
2615 if (bpo->bpo_havefreed) {
2616 (void) printf(" %*s: object %llu, %llu blkptrs, "
2617 "%llu freed, %s\n",
2618 indent * 8, name,
2619 (u_longlong_t)bpo->bpo_object,
2620 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2621 (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2622 bytes);
2623 } else {
2624 (void) printf(" %*s: object %llu, %llu blkptrs, "
2625 "%s\n",
2626 indent * 8, name,
2627 (u_longlong_t)bpo->bpo_object,
2628 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2629 bytes);
2630 }
2631 }
2632
2633 if (dump_opt['d'] < 5)
2634 return;
2635
2636
2637 if (indent == 0) {
2638 (void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
2639 (void) printf("\n");
2640 }
2641 }
2642
2643 static int
2644 dump_bookmark(dsl_pool_t *dp, char *name, boolean_t print_redact,
2645 boolean_t print_list)
2646 {
2647 int err = 0;
2648 zfs_bookmark_phys_t prop;
2649 objset_t *mos = dp->dp_spa->spa_meta_objset;
2650 err = dsl_bookmark_lookup(dp, name, NULL, &prop);
2651
2652 if (err != 0) {
2653 return (err);
2654 }
2655
2656 (void) printf("\t#%s: ", strchr(name, '#') + 1);
2657 (void) printf("{guid: %llx creation_txg: %llu creation_time: "
2658 "%llu redaction_obj: %llu}\n", (u_longlong_t)prop.zbm_guid,
2659 (u_longlong_t)prop.zbm_creation_txg,
2660 (u_longlong_t)prop.zbm_creation_time,
2661 (u_longlong_t)prop.zbm_redaction_obj);
2662
2663 IMPLY(print_list, print_redact);
2664 if (!print_redact || prop.zbm_redaction_obj == 0)
2665 return (0);
2666
2667 redaction_list_t *rl;
2668 VERIFY0(dsl_redaction_list_hold_obj(dp,
2669 prop.zbm_redaction_obj, FTAG, &rl));
2670
2671 redaction_list_phys_t *rlp = rl->rl_phys;
2672 (void) printf("\tRedacted:\n\t\tProgress: ");
2673 if (rlp->rlp_last_object != UINT64_MAX ||
2674 rlp->rlp_last_blkid != UINT64_MAX) {
2675 (void) printf("%llu %llu (incomplete)\n",
2676 (u_longlong_t)rlp->rlp_last_object,
2677 (u_longlong_t)rlp->rlp_last_blkid);
2678 } else {
2679 (void) printf("complete\n");
2680 }
2681 (void) printf("\t\tSnapshots: [");
2682 for (unsigned int i = 0; i < rlp->rlp_num_snaps; i++) {
2683 if (i > 0)
2684 (void) printf(", ");
2685 (void) printf("%0llu",
2686 (u_longlong_t)rlp->rlp_snaps[i]);
2687 }
2688 (void) printf("]\n\t\tLength: %llu\n",
2689 (u_longlong_t)rlp->rlp_num_entries);
2690
2691 if (!print_list) {
2692 dsl_redaction_list_rele(rl, FTAG);
2693 return (0);
2694 }
2695
2696 if (rlp->rlp_num_entries == 0) {
2697 dsl_redaction_list_rele(rl, FTAG);
2698 (void) printf("\t\tRedaction List: []\n\n");
2699 return (0);
2700 }
2701
2702 redact_block_phys_t *rbp_buf;
2703 uint64_t size;
2704 dmu_object_info_t doi;
2705
2706 VERIFY0(dmu_object_info(mos, prop.zbm_redaction_obj, &doi));
2707 size = doi.doi_max_offset;
2708 rbp_buf = kmem_alloc(size, KM_SLEEP);
2709
2710 err = dmu_read(mos, prop.zbm_redaction_obj, 0, size,
2711 rbp_buf, 0);
2712 if (err != 0) {
2713 dsl_redaction_list_rele(rl, FTAG);
2714 kmem_free(rbp_buf, size);
2715 return (err);
2716 }
2717
2718 (void) printf("\t\tRedaction List: [{object: %llx, offset: "
2719 "%llx, blksz: %x, count: %llx}",
2720 (u_longlong_t)rbp_buf[0].rbp_object,
2721 (u_longlong_t)rbp_buf[0].rbp_blkid,
2722 (uint_t)(redact_block_get_size(&rbp_buf[0])),
2723 (u_longlong_t)redact_block_get_count(&rbp_buf[0]));
2724
2725 for (size_t i = 1; i < rlp->rlp_num_entries; i++) {
2726 (void) printf(",\n\t\t{object: %llx, offset: %llx, "
2727 "blksz: %x, count: %llx}",
2728 (u_longlong_t)rbp_buf[i].rbp_object,
2729 (u_longlong_t)rbp_buf[i].rbp_blkid,
2730 (uint_t)(redact_block_get_size(&rbp_buf[i])),
2731 (u_longlong_t)redact_block_get_count(&rbp_buf[i]));
2732 }
2733 dsl_redaction_list_rele(rl, FTAG);
2734 kmem_free(rbp_buf, size);
2735 (void) printf("]\n\n");
2736 return (0);
2737 }
2738
2739 static void
2740 dump_bookmarks(objset_t *os, int verbosity)
2741 {
2742 zap_cursor_t zc;
2743 zap_attribute_t attr;
2744 dsl_dataset_t *ds = dmu_objset_ds(os);
2745 dsl_pool_t *dp = spa_get_dsl(os->os_spa);
2746 objset_t *mos = os->os_spa->spa_meta_objset;
2747 if (verbosity < 4)
2748 return;
2749 dsl_pool_config_enter(dp, FTAG);
2750
2751 for (zap_cursor_init(&zc, mos, ds->ds_bookmarks_obj);
2752 zap_cursor_retrieve(&zc, &attr) == 0;
2753 zap_cursor_advance(&zc)) {
2754 char osname[ZFS_MAX_DATASET_NAME_LEN];
2755 char buf[ZFS_MAX_DATASET_NAME_LEN];
2756 dmu_objset_name(os, osname);
2757 VERIFY3S(0, <=, snprintf(buf, sizeof (buf), "%s#%s", osname,
2758 attr.za_name));
2759 (void) dump_bookmark(dp, buf, verbosity >= 5, verbosity >= 6);
2760 }
2761 zap_cursor_fini(&zc);
2762 dsl_pool_config_exit(dp, FTAG);
2763 }
2764
2765 static void
2766 bpobj_count_refd(bpobj_t *bpo)
2767 {
2768 mos_obj_refd(bpo->bpo_object);
2769
2770 if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2771 mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
2772 for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2773 uint64_t subobj;
2774 bpobj_t subbpo;
2775 int error;
2776 VERIFY0(dmu_read(bpo->bpo_os,
2777 bpo->bpo_phys->bpo_subobjs,
2778 i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2779 error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2780 if (error != 0) {
2781 (void) printf("ERROR %u while trying to open "
2782 "subobj id %llu\n",
2783 error, (u_longlong_t)subobj);
2784 continue;
2785 }
2786 bpobj_count_refd(&subbpo);
2787 bpobj_close(&subbpo);
2788 }
2789 }
2790 }
2791
2792 static int
2793 dsl_deadlist_entry_count_refd(void *arg, dsl_deadlist_entry_t *dle)
2794 {
2795 spa_t *spa = arg;
2796 uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
2797 if (dle->dle_bpobj.bpo_object != empty_bpobj)
2798 bpobj_count_refd(&dle->dle_bpobj);
2799 return (0);
2800 }
2801
2802 static int
2803 dsl_deadlist_entry_dump(void *arg, dsl_deadlist_entry_t *dle)
2804 {
2805 ASSERT(arg == NULL);
2806 if (dump_opt['d'] >= 5) {
2807 char buf[128];
2808 (void) snprintf(buf, sizeof (buf),
2809 "mintxg %llu -> obj %llu",
2810 (longlong_t)dle->dle_mintxg,
2811 (longlong_t)dle->dle_bpobj.bpo_object);
2812
2813 dump_full_bpobj(&dle->dle_bpobj, buf, 0);
2814 } else {
2815 (void) printf("mintxg %llu -> obj %llu\n",
2816 (longlong_t)dle->dle_mintxg,
2817 (longlong_t)dle->dle_bpobj.bpo_object);
2818 }
2819 return (0);
2820 }
2821
2822 static void
2823 dump_blkptr_list(dsl_deadlist_t *dl, char *name)
2824 {
2825 char bytes[32];
2826 char comp[32];
2827 char uncomp[32];
2828 char entries[32];
2829 spa_t *spa = dmu_objset_spa(dl->dl_os);
2830 uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
2831
2832 if (dl->dl_oldfmt) {
2833 if (dl->dl_bpobj.bpo_object != empty_bpobj)
2834 bpobj_count_refd(&dl->dl_bpobj);
2835 } else {
2836 mos_obj_refd(dl->dl_object);
2837 dsl_deadlist_iterate(dl, dsl_deadlist_entry_count_refd, spa);
2838 }
2839
2840 /* make sure nicenum has enough space */
2841 CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
2842 CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
2843 CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
2844 CTASSERT(sizeof (entries) >= NN_NUMBUF_SZ);
2845
2846 if (dump_opt['d'] < 3)
2847 return;
2848
2849 if (dl->dl_oldfmt) {
2850 dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
2851 return;
2852 }
2853
2854 zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
2855 zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
2856 zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
2857 zdb_nicenum(avl_numnodes(&dl->dl_tree), entries, sizeof (entries));
2858 (void) printf("\n %s: %s (%s/%s comp), %s entries\n",
2859 name, bytes, comp, uncomp, entries);
2860
2861 if (dump_opt['d'] < 4)
2862 return;
2863
2864 (void) printf("\n");
2865
2866 dsl_deadlist_iterate(dl, dsl_deadlist_entry_dump, NULL);
2867 }
2868
2869 static int
2870 verify_dd_livelist(objset_t *os)
2871 {
2872 uint64_t ll_used, used, ll_comp, comp, ll_uncomp, uncomp;
2873 dsl_pool_t *dp = spa_get_dsl(os->os_spa);
2874 dsl_dir_t *dd = os->os_dsl_dataset->ds_dir;
2875
2876 ASSERT(!dmu_objset_is_snapshot(os));
2877 if (!dsl_deadlist_is_open(&dd->dd_livelist))
2878 return (0);
2879
2880 /* Iterate through the livelist to check for duplicates */
2881 dsl_deadlist_iterate(&dd->dd_livelist, sublivelist_verify_lightweight,
2882 NULL);
2883
2884 dsl_pool_config_enter(dp, FTAG);
2885 dsl_deadlist_space(&dd->dd_livelist, &ll_used,
2886 &ll_comp, &ll_uncomp);
2887
2888 dsl_dataset_t *origin_ds;
2889 ASSERT(dsl_pool_config_held(dp));
2890 VERIFY0(dsl_dataset_hold_obj(dp,
2891 dsl_dir_phys(dd)->dd_origin_obj, FTAG, &origin_ds));
2892 VERIFY0(dsl_dataset_space_written(origin_ds, os->os_dsl_dataset,
2893 &used, &comp, &uncomp));
2894 dsl_dataset_rele(origin_ds, FTAG);
2895 dsl_pool_config_exit(dp, FTAG);
2896 /*
2897 * It's possible that the dataset's uncomp space is larger than the
2898 * livelist's because livelists do not track embedded block pointers
2899 */
2900 if (used != ll_used || comp != ll_comp || uncomp < ll_uncomp) {
2901 char nice_used[32], nice_comp[32], nice_uncomp[32];
2902 (void) printf("Discrepancy in space accounting:\n");
2903 zdb_nicenum(used, nice_used, sizeof (nice_used));
2904 zdb_nicenum(comp, nice_comp, sizeof (nice_comp));
2905 zdb_nicenum(uncomp, nice_uncomp, sizeof (nice_uncomp));
2906 (void) printf("dir: used %s, comp %s, uncomp %s\n",
2907 nice_used, nice_comp, nice_uncomp);
2908 zdb_nicenum(ll_used, nice_used, sizeof (nice_used));
2909 zdb_nicenum(ll_comp, nice_comp, sizeof (nice_comp));
2910 zdb_nicenum(ll_uncomp, nice_uncomp, sizeof (nice_uncomp));
2911 (void) printf("livelist: used %s, comp %s, uncomp %s\n",
2912 nice_used, nice_comp, nice_uncomp);
2913 return (1);
2914 }
2915 return (0);
2916 }
2917
2918 static avl_tree_t idx_tree;
2919 static avl_tree_t domain_tree;
2920 static boolean_t fuid_table_loaded;
2921 static objset_t *sa_os = NULL;
2922 static sa_attr_type_t *sa_attr_table = NULL;
2923
2924 static int
2925 open_objset(const char *path, void *tag, objset_t **osp)
2926 {
2927 int err;
2928 uint64_t sa_attrs = 0;
2929 uint64_t version = 0;
2930
2931 VERIFY3P(sa_os, ==, NULL);
2932 /*
2933 * We can't own an objset if it's redacted. Therefore, we do this
2934 * dance: hold the objset, then acquire a long hold on its dataset, then
2935 * release the pool (which is held as part of holding the objset).
2936 */
2937 err = dmu_objset_hold(path, tag, osp);
2938 if (err != 0) {
2939 (void) fprintf(stderr, "failed to hold dataset '%s': %s\n",
2940 path, strerror(err));
2941 return (err);
2942 }
2943 dsl_dataset_long_hold(dmu_objset_ds(*osp), tag);
2944 dsl_pool_rele(dmu_objset_pool(*osp), tag);
2945
2946 if (dmu_objset_type(*osp) == DMU_OST_ZFS && !(*osp)->os_encrypted) {
2947 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
2948 8, 1, &version);
2949 if (version >= ZPL_VERSION_SA) {
2950 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
2951 8, 1, &sa_attrs);
2952 }
2953 err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
2954 &sa_attr_table);
2955 if (err != 0) {
2956 (void) fprintf(stderr, "sa_setup failed: %s\n",
2957 strerror(err));
2958 dsl_dataset_long_rele(dmu_objset_ds(*osp), tag);
2959 dsl_dataset_rele(dmu_objset_ds(*osp), tag);
2960 *osp = NULL;
2961 }
2962 }
2963 sa_os = *osp;
2964
2965 return (0);
2966 }
2967
2968 static void
2969 close_objset(objset_t *os, void *tag)
2970 {
2971 VERIFY3P(os, ==, sa_os);
2972 if (os->os_sa != NULL)
2973 sa_tear_down(os);
2974 dsl_dataset_long_rele(dmu_objset_ds(os), tag);
2975 dsl_dataset_rele(dmu_objset_ds(os), tag);
2976 sa_attr_table = NULL;
2977 sa_os = NULL;
2978 }
2979
2980 static void
2981 fuid_table_destroy(void)
2982 {
2983 if (fuid_table_loaded) {
2984 zfs_fuid_table_destroy(&idx_tree, &domain_tree);
2985 fuid_table_loaded = B_FALSE;
2986 }
2987 }
2988
2989 /*
2990 * print uid or gid information.
2991 * For normal POSIX id just the id is printed in decimal format.
2992 * For CIFS files with FUID the fuid is printed in hex followed by
2993 * the domain-rid string.
2994 */
2995 static void
2996 print_idstr(uint64_t id, const char *id_type)
2997 {
2998 if (FUID_INDEX(id)) {
2999 char *domain;
3000
3001 domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
3002 (void) printf("\t%s %llx [%s-%d]\n", id_type,
3003 (u_longlong_t)id, domain, (int)FUID_RID(id));
3004 } else {
3005 (void) printf("\t%s %llu\n", id_type, (u_longlong_t)id);
3006 }
3007
3008 }
3009
3010 static void
3011 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
3012 {
3013 uint32_t uid_idx, gid_idx;
3014
3015 uid_idx = FUID_INDEX(uid);
3016 gid_idx = FUID_INDEX(gid);
3017
3018 /* Load domain table, if not already loaded */
3019 if (!fuid_table_loaded && (uid_idx || gid_idx)) {
3020 uint64_t fuid_obj;
3021
3022 /* first find the fuid object. It lives in the master node */
3023 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
3024 8, 1, &fuid_obj) == 0);
3025 zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
3026 (void) zfs_fuid_table_load(os, fuid_obj,
3027 &idx_tree, &domain_tree);
3028 fuid_table_loaded = B_TRUE;
3029 }
3030
3031 print_idstr(uid, "uid");
3032 print_idstr(gid, "gid");
3033 }
3034
3035 static void
3036 dump_znode_sa_xattr(sa_handle_t *hdl)
3037 {
3038 nvlist_t *sa_xattr;
3039 nvpair_t *elem = NULL;
3040 int sa_xattr_size = 0;
3041 int sa_xattr_entries = 0;
3042 int error;
3043 char *sa_xattr_packed;
3044
3045 error = sa_size(hdl, sa_attr_table[ZPL_DXATTR], &sa_xattr_size);
3046 if (error || sa_xattr_size == 0)
3047 return;
3048
3049 sa_xattr_packed = malloc(sa_xattr_size);
3050 if (sa_xattr_packed == NULL)
3051 return;
3052
3053 error = sa_lookup(hdl, sa_attr_table[ZPL_DXATTR],
3054 sa_xattr_packed, sa_xattr_size);
3055 if (error) {
3056 free(sa_xattr_packed);
3057 return;
3058 }
3059
3060 error = nvlist_unpack(sa_xattr_packed, sa_xattr_size, &sa_xattr, 0);
3061 if (error) {
3062 free(sa_xattr_packed);
3063 return;
3064 }
3065
3066 while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL)
3067 sa_xattr_entries++;
3068
3069 (void) printf("\tSA xattrs: %d bytes, %d entries\n\n",
3070 sa_xattr_size, sa_xattr_entries);
3071 while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL) {
3072 uchar_t *value;
3073 uint_t cnt, idx;
3074
3075 (void) printf("\t\t%s = ", nvpair_name(elem));
3076 nvpair_value_byte_array(elem, &value, &cnt);
3077 for (idx = 0; idx < cnt; ++idx) {
3078 if (isprint(value[idx]))
3079 (void) putchar(value[idx]);
3080 else
3081 (void) printf("\\%3.3o", value[idx]);
3082 }
3083 (void) putchar('\n');
3084 }
3085
3086 nvlist_free(sa_xattr);
3087 free(sa_xattr_packed);
3088 }
3089
3090 static void
3091 dump_znode_symlink(sa_handle_t *hdl)
3092 {
3093 int sa_symlink_size = 0;
3094 char linktarget[MAXPATHLEN];
3095 linktarget[0] = '\0';
3096 int error;
3097
3098 error = sa_size(hdl, sa_attr_table[ZPL_SYMLINK], &sa_symlink_size);
3099 if (error || sa_symlink_size == 0) {
3100 return;
3101 }
3102 if (sa_lookup(hdl, sa_attr_table[ZPL_SYMLINK],
3103 &linktarget, sa_symlink_size) == 0)
3104 (void) printf("\ttarget %s\n", linktarget);
3105 }
3106
3107 /*ARGSUSED*/
3108 static void
3109 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
3110 {
3111 char path[MAXPATHLEN * 2]; /* allow for xattr and failure prefix */
3112 sa_handle_t *hdl;
3113 uint64_t xattr, rdev, gen;
3114 uint64_t uid, gid, mode, fsize, parent, links;
3115 uint64_t pflags;
3116 uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
3117 time_t z_crtime, z_atime, z_mtime, z_ctime;
3118 sa_bulk_attr_t bulk[12];
3119 int idx = 0;
3120 int error;
3121
3122 VERIFY3P(os, ==, sa_os);
3123 if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
3124 (void) printf("Failed to get handle for SA znode\n");
3125 return;
3126 }
3127
3128 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
3129 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
3130 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
3131 &links, 8);
3132 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
3133 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
3134 &mode, 8);
3135 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
3136 NULL, &parent, 8);
3137 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
3138 &fsize, 8);
3139 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
3140 acctm, 16);
3141 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
3142 modtm, 16);
3143 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
3144 crtm, 16);
3145 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
3146 chgtm, 16);
3147 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
3148 &pflags, 8);
3149
3150 if (sa_bulk_lookup(hdl, bulk, idx)) {
3151 (void) sa_handle_destroy(hdl);
3152 return;
3153 }
3154
3155 z_crtime = (time_t)crtm[0];
3156 z_atime = (time_t)acctm[0];
3157 z_mtime = (time_t)modtm[0];
3158 z_ctime = (time_t)chgtm[0];
3159
3160 if (dump_opt['d'] > 4) {
3161 error = zfs_obj_to_path(os, object, path, sizeof (path));
3162 if (error == ESTALE) {
3163 (void) snprintf(path, sizeof (path), "on delete queue");
3164 } else if (error != 0) {
3165 leaked_objects++;
3166 (void) snprintf(path, sizeof (path),
3167 "path not found, possibly leaked");
3168 }
3169 (void) printf("\tpath %s\n", path);
3170 }
3171
3172 if (S_ISLNK(mode))
3173 dump_znode_symlink(hdl);
3174 dump_uidgid(os, uid, gid);
3175 (void) printf("\tatime %s", ctime(&z_atime));
3176 (void) printf("\tmtime %s", ctime(&z_mtime));
3177 (void) printf("\tctime %s", ctime(&z_ctime));
3178 (void) printf("\tcrtime %s", ctime(&z_crtime));
3179 (void) printf("\tgen %llu\n", (u_longlong_t)gen);
3180 (void) printf("\tmode %llo\n", (u_longlong_t)mode);
3181 (void) printf("\tsize %llu\n", (u_longlong_t)fsize);
3182 (void) printf("\tparent %llu\n", (u_longlong_t)parent);
3183 (void) printf("\tlinks %llu\n", (u_longlong_t)links);
3184 (void) printf("\tpflags %llx\n", (u_longlong_t)pflags);
3185 if (dmu_objset_projectquota_enabled(os) && (pflags & ZFS_PROJID)) {
3186 uint64_t projid;
3187
3188 if (sa_lookup(hdl, sa_attr_table[ZPL_PROJID], &projid,
3189 sizeof (uint64_t)) == 0)
3190 (void) printf("\tprojid %llu\n", (u_longlong_t)projid);
3191 }
3192 if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
3193 sizeof (uint64_t)) == 0)
3194 (void) printf("\txattr %llu\n", (u_longlong_t)xattr);
3195 if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
3196 sizeof (uint64_t)) == 0)
3197 (void) printf("\trdev 0x%016llx\n", (u_longlong_t)rdev);
3198 dump_znode_sa_xattr(hdl);
3199 sa_handle_destroy(hdl);
3200 }
3201
3202 /*ARGSUSED*/
3203 static void
3204 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
3205 {
3206 }
3207
3208 /*ARGSUSED*/
3209 static void
3210 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
3211 {
3212 }
3213
3214 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
3215 dump_none, /* unallocated */
3216 dump_zap, /* object directory */
3217 dump_uint64, /* object array */
3218 dump_none, /* packed nvlist */
3219 dump_packed_nvlist, /* packed nvlist size */
3220 dump_none, /* bpobj */
3221 dump_bpobj, /* bpobj header */
3222 dump_none, /* SPA space map header */
3223 dump_none, /* SPA space map */
3224 dump_none, /* ZIL intent log */
3225 dump_dnode, /* DMU dnode */
3226 dump_dmu_objset, /* DMU objset */
3227 dump_dsl_dir, /* DSL directory */
3228 dump_zap, /* DSL directory child map */
3229 dump_zap, /* DSL dataset snap map */
3230 dump_zap, /* DSL props */
3231 dump_dsl_dataset, /* DSL dataset */
3232 dump_znode, /* ZFS znode */
3233 dump_acl, /* ZFS V0 ACL */
3234 dump_uint8, /* ZFS plain file */
3235 dump_zpldir, /* ZFS directory */
3236 dump_zap, /* ZFS master node */
3237 dump_zap, /* ZFS delete queue */
3238 dump_uint8, /* zvol object */
3239 dump_zap, /* zvol prop */
3240 dump_uint8, /* other uint8[] */
3241 dump_uint64, /* other uint64[] */
3242 dump_zap, /* other ZAP */
3243 dump_zap, /* persistent error log */
3244 dump_uint8, /* SPA history */
3245 dump_history_offsets, /* SPA history offsets */
3246 dump_zap, /* Pool properties */
3247 dump_zap, /* DSL permissions */
3248 dump_acl, /* ZFS ACL */
3249 dump_uint8, /* ZFS SYSACL */
3250 dump_none, /* FUID nvlist */
3251 dump_packed_nvlist, /* FUID nvlist size */
3252 dump_zap, /* DSL dataset next clones */
3253 dump_zap, /* DSL scrub queue */
3254 dump_zap, /* ZFS user/group/project used */
3255 dump_zap, /* ZFS user/group/project quota */
3256 dump_zap, /* snapshot refcount tags */
3257 dump_ddt_zap, /* DDT ZAP object */
3258 dump_zap, /* DDT statistics */
3259 dump_znode, /* SA object */
3260 dump_zap, /* SA Master Node */
3261 dump_sa_attrs, /* SA attribute registration */
3262 dump_sa_layouts, /* SA attribute layouts */
3263 dump_zap, /* DSL scrub translations */
3264 dump_none, /* fake dedup BP */
3265 dump_zap, /* deadlist */
3266 dump_none, /* deadlist hdr */
3267 dump_zap, /* dsl clones */
3268 dump_bpobj_subobjs, /* bpobj subobjs */
3269 dump_unknown, /* Unknown type, must be last */
3270 };
3271
3272 static boolean_t
3273 match_object_type(dmu_object_type_t obj_type, uint64_t flags)
3274 {
3275 boolean_t match = B_TRUE;
3276
3277 switch (obj_type) {
3278 case DMU_OT_DIRECTORY_CONTENTS:
3279 if (!(flags & ZOR_FLAG_DIRECTORY))
3280 match = B_FALSE;
3281 break;
3282 case DMU_OT_PLAIN_FILE_CONTENTS:
3283 if (!(flags & ZOR_FLAG_PLAIN_FILE))
3284 match = B_FALSE;
3285 break;
3286 case DMU_OT_SPACE_MAP:
3287 if (!(flags & ZOR_FLAG_SPACE_MAP))
3288 match = B_FALSE;
3289 break;
3290 default:
3291 if (strcmp(zdb_ot_name(obj_type), "zap") == 0) {
3292 if (!(flags & ZOR_FLAG_ZAP))
3293 match = B_FALSE;
3294 break;
3295 }
3296
3297 /*
3298 * If all bits except some of the supported flags are
3299 * set, the user combined the all-types flag (A) with
3300 * a negated flag to exclude some types (e.g. A-f to
3301 * show all object types except plain files).
3302 */
3303 if ((flags | ZOR_SUPPORTED_FLAGS) != ZOR_FLAG_ALL_TYPES)
3304 match = B_FALSE;
3305
3306 break;
3307 }
3308
3309 return (match);
3310 }
3311
3312 static void
3313 dump_object(objset_t *os, uint64_t object, int verbosity,
3314 boolean_t *print_header, uint64_t *dnode_slots_used, uint64_t flags)
3315 {
3316 dmu_buf_t *db = NULL;
3317 dmu_object_info_t doi;
3318 dnode_t *dn;
3319 boolean_t dnode_held = B_FALSE;
3320 void *bonus = NULL;
3321 size_t bsize = 0;
3322 char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
3323 char bonus_size[32];
3324 char aux[50];
3325 int error;
3326
3327 /* make sure nicenum has enough space */
3328 CTASSERT(sizeof (iblk) >= NN_NUMBUF_SZ);
3329 CTASSERT(sizeof (dblk) >= NN_NUMBUF_SZ);
3330 CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
3331 CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
3332 CTASSERT(sizeof (bonus_size) >= NN_NUMBUF_SZ);
3333
3334 if (*print_header) {
3335 (void) printf("\n%10s %3s %5s %5s %5s %6s %5s %6s %s\n",
3336 "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
3337 "lsize", "%full", "type");
3338 *print_header = 0;
3339 }
3340
3341 if (object == 0) {
3342 dn = DMU_META_DNODE(os);
3343 dmu_object_info_from_dnode(dn, &doi);
3344 } else {
3345 /*
3346 * Encrypted datasets will have sensitive bonus buffers
3347 * encrypted. Therefore we cannot hold the bonus buffer and
3348 * must hold the dnode itself instead.
3349 */
3350 error = dmu_object_info(os, object, &doi);
3351 if (error)
3352 fatal("dmu_object_info() failed, errno %u", error);
3353
3354 if (os->os_encrypted &&
3355 DMU_OT_IS_ENCRYPTED(doi.doi_bonus_type)) {
3356 error = dnode_hold(os, object, FTAG, &dn);
3357 if (error)
3358 fatal("dnode_hold() failed, errno %u", error);
3359 dnode_held = B_TRUE;
3360 } else {
3361 error = dmu_bonus_hold(os, object, FTAG, &db);
3362 if (error)
3363 fatal("dmu_bonus_hold(%llu) failed, errno %u",
3364 object, error);
3365 bonus = db->db_data;
3366 bsize = db->db_size;
3367 dn = DB_DNODE((dmu_buf_impl_t *)db);
3368 }
3369 }
3370
3371 /*
3372 * Default to showing all object types if no flags were specified.
3373 */
3374 if (flags != 0 && flags != ZOR_FLAG_ALL_TYPES &&
3375 !match_object_type(doi.doi_type, flags))
3376 goto out;
3377
3378 if (dnode_slots_used)
3379 *dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
3380
3381 zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
3382 zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
3383 zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
3384 zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
3385 zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
3386 zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
3387 (void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
3388 doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
3389 doi.doi_max_offset);
3390
3391 aux[0] = '\0';
3392
3393 if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
3394 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3395 " (K=%s)", ZDB_CHECKSUM_NAME(doi.doi_checksum));
3396 }
3397
3398 if (doi.doi_compress == ZIO_COMPRESS_INHERIT &&
3399 ZIO_COMPRESS_HASLEVEL(os->os_compress) && verbosity >= 6) {
3400 const char *compname = NULL;
3401 if (zfs_prop_index_to_string(ZFS_PROP_COMPRESSION,
3402 ZIO_COMPRESS_RAW(os->os_compress, os->os_complevel),
3403 &compname) == 0) {
3404 (void) snprintf(aux + strlen(aux),
3405 sizeof (aux) - strlen(aux), " (Z=inherit=%s)",
3406 compname);
3407 } else {
3408 (void) snprintf(aux + strlen(aux),
3409 sizeof (aux) - strlen(aux),
3410 " (Z=inherit=%s-unknown)",
3411 ZDB_COMPRESS_NAME(os->os_compress));
3412 }
3413 } else if (doi.doi_compress == ZIO_COMPRESS_INHERIT && verbosity >= 6) {
3414 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3415 " (Z=inherit=%s)", ZDB_COMPRESS_NAME(os->os_compress));
3416 } else if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
3417 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3418 " (Z=%s)", ZDB_COMPRESS_NAME(doi.doi_compress));
3419 }
3420
3421 (void) printf("%10lld %3u %5s %5s %5s %6s %5s %6s %s%s\n",
3422 (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
3423 asize, dnsize, lsize, fill, zdb_ot_name(doi.doi_type), aux);
3424
3425 if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
3426 (void) printf("%10s %3s %5s %5s %5s %5s %5s %6s %s\n",
3427 "", "", "", "", "", "", bonus_size, "bonus",
3428 zdb_ot_name(doi.doi_bonus_type));
3429 }
3430
3431 if (verbosity >= 4) {
3432 (void) printf("\tdnode flags: %s%s%s%s\n",
3433 (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
3434 "USED_BYTES " : "",
3435 (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
3436 "USERUSED_ACCOUNTED " : "",
3437 (dn->dn_phys->dn_flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) ?
3438 "USEROBJUSED_ACCOUNTED " : "",
3439 (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
3440 "SPILL_BLKPTR" : "");
3441 (void) printf("\tdnode maxblkid: %llu\n",
3442 (longlong_t)dn->dn_phys->dn_maxblkid);
3443
3444 if (!dnode_held) {
3445 object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os,
3446 object, bonus, bsize);
3447 } else {
3448 (void) printf("\t\t(bonus encrypted)\n");
3449 }
3450
3451 if (!os->os_encrypted || !DMU_OT_IS_ENCRYPTED(doi.doi_type)) {
3452 object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object,
3453 NULL, 0);
3454 } else {
3455 (void) printf("\t\t(object encrypted)\n");
3456 }
3457
3458 *print_header = B_TRUE;
3459 }
3460
3461 if (verbosity >= 5)
3462 dump_indirect(dn);
3463
3464 if (verbosity >= 5) {
3465 /*
3466 * Report the list of segments that comprise the object.
3467 */
3468 uint64_t start = 0;
3469 uint64_t end;
3470 uint64_t blkfill = 1;
3471 int minlvl = 1;
3472
3473 if (dn->dn_type == DMU_OT_DNODE) {
3474 minlvl = 0;
3475 blkfill = DNODES_PER_BLOCK;
3476 }
3477
3478 for (;;) {
3479 char segsize[32];
3480 /* make sure nicenum has enough space */
3481 CTASSERT(sizeof (segsize) >= NN_NUMBUF_SZ);
3482 error = dnode_next_offset(dn,
3483 0, &start, minlvl, blkfill, 0);
3484 if (error)
3485 break;
3486 end = start;
3487 error = dnode_next_offset(dn,
3488 DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
3489 zdb_nicenum(end - start, segsize, sizeof (segsize));
3490 (void) printf("\t\tsegment [%016llx, %016llx)"
3491 " size %5s\n", (u_longlong_t)start,
3492 (u_longlong_t)end, segsize);
3493 if (error)
3494 break;
3495 start = end;
3496 }
3497 }
3498
3499 out:
3500 if (db != NULL)
3501 dmu_buf_rele(db, FTAG);
3502 if (dnode_held)
3503 dnode_rele(dn, FTAG);
3504 }
3505
3506 static void
3507 count_dir_mos_objects(dsl_dir_t *dd)
3508 {
3509 mos_obj_refd(dd->dd_object);
3510 mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
3511 mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
3512 mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
3513 mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
3514
3515 /*
3516 * The dd_crypto_obj can be referenced by multiple dsl_dir's.
3517 * Ignore the references after the first one.
3518 */
3519 mos_obj_refd_multiple(dd->dd_crypto_obj);
3520 }
3521
3522 static void
3523 count_ds_mos_objects(dsl_dataset_t *ds)
3524 {
3525 mos_obj_refd(ds->ds_object);
3526 mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
3527 mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
3528 mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
3529 mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
3530 mos_obj_refd(ds->ds_bookmarks_obj);
3531
3532 if (!dsl_dataset_is_snapshot(ds)) {
3533 count_dir_mos_objects(ds->ds_dir);
3534 }
3535 }
3536
3537 static const char *objset_types[DMU_OST_NUMTYPES] = {
3538 "NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
3539
3540 /*
3541 * Parse a string denoting a range of object IDs of the form
3542 * <start>[:<end>[:flags]], and store the results in zor.
3543 * Return 0 on success. On error, return 1 and update the msg
3544 * pointer to point to a descriptive error message.
3545 */
3546 static int
3547 parse_object_range(char *range, zopt_object_range_t *zor, char **msg)
3548 {
3549 uint64_t flags = 0;
3550 char *p, *s, *dup, *flagstr;
3551 size_t len;
3552 int i;
3553 int rc = 0;
3554
3555 if (strchr(range, ':') == NULL) {
3556 zor->zor_obj_start = strtoull(range, &p, 0);
3557 if (*p != '\0') {
3558 *msg = "Invalid characters in object ID";
3559 rc = 1;
3560 }
3561 zor->zor_obj_end = zor->zor_obj_start;
3562 return (rc);
3563 }
3564
3565 if (strchr(range, ':') == range) {
3566 *msg = "Invalid leading colon";
3567 rc = 1;
3568 return (rc);
3569 }
3570
3571 len = strlen(range);
3572 if (range[len - 1] == ':') {
3573 *msg = "Invalid trailing colon";
3574 rc = 1;
3575 return (rc);
3576 }
3577
3578 dup = strdup(range);
3579 s = strtok(dup, ":");
3580 zor->zor_obj_start = strtoull(s, &p, 0);
3581
3582 if (*p != '\0') {
3583 *msg = "Invalid characters in start object ID";
3584 rc = 1;
3585 goto out;
3586 }
3587
3588 s = strtok(NULL, ":");
3589 zor->zor_obj_end = strtoull(s, &p, 0);
3590
3591 if (*p != '\0') {
3592 *msg = "Invalid characters in end object ID";
3593 rc = 1;
3594 goto out;
3595 }
3596
3597 if (zor->zor_obj_start > zor->zor_obj_end) {
3598 *msg = "Start object ID may not exceed end object ID";
3599 rc = 1;
3600 goto out;
3601 }
3602
3603 s = strtok(NULL, ":");
3604 if (s == NULL) {
3605 zor->zor_flags = ZOR_FLAG_ALL_TYPES;
3606 goto out;
3607 } else if (strtok(NULL, ":") != NULL) {
3608 *msg = "Invalid colon-delimited field after flags";
3609 rc = 1;
3610 goto out;
3611 }
3612
3613 flagstr = s;
3614 for (i = 0; flagstr[i]; i++) {
3615 int bit;
3616 boolean_t negation = (flagstr[i] == '-');
3617
3618 if (negation) {
3619 i++;
3620 if (flagstr[i] == '\0') {
3621 *msg = "Invalid trailing negation operator";
3622 rc = 1;
3623 goto out;
3624 }
3625 }
3626 bit = flagbits[(uchar_t)flagstr[i]];
3627 if (bit == 0) {
3628 *msg = "Invalid flag";
3629 rc = 1;
3630 goto out;
3631 }
3632 if (negation)
3633 flags &= ~bit;
3634 else
3635 flags |= bit;
3636 }
3637 zor->zor_flags = flags;
3638
3639 out:
3640 free(dup);
3641 return (rc);
3642 }
3643
3644 static void
3645 dump_objset(objset_t *os)
3646 {
3647 dmu_objset_stats_t dds = { 0 };
3648 uint64_t object, object_count;
3649 uint64_t refdbytes, usedobjs, scratch;
3650 char numbuf[32];
3651 char blkbuf[BP_SPRINTF_LEN + 20];
3652 char osname[ZFS_MAX_DATASET_NAME_LEN];
3653 const char *type = "UNKNOWN";
3654 int verbosity = dump_opt['d'];
3655 boolean_t print_header;
3656 unsigned i;
3657 int error;
3658 uint64_t total_slots_used = 0;
3659 uint64_t max_slot_used = 0;
3660 uint64_t dnode_slots;
3661 uint64_t obj_start;
3662 uint64_t obj_end;
3663 uint64_t flags;
3664
3665 /* make sure nicenum has enough space */
3666 CTASSERT(sizeof (numbuf) >= NN_NUMBUF_SZ);
3667
3668 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
3669 dmu_objset_fast_stat(os, &dds);
3670 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
3671
3672 print_header = B_TRUE;
3673
3674 if (dds.dds_type < DMU_OST_NUMTYPES)
3675 type = objset_types[dds.dds_type];
3676
3677 if (dds.dds_type == DMU_OST_META) {
3678 dds.dds_creation_txg = TXG_INITIAL;
3679 usedobjs = BP_GET_FILL(os->os_rootbp);
3680 refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
3681 dd_used_bytes;
3682 } else {
3683 dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
3684 }
3685
3686 ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
3687
3688 zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
3689
3690 if (verbosity >= 4) {
3691 (void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
3692 (void) snprintf_blkptr(blkbuf + strlen(blkbuf),
3693 sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
3694 } else {
3695 blkbuf[0] = '\0';
3696 }
3697
3698 dmu_objset_name(os, osname);
3699
3700 (void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
3701 "%s, %llu objects%s%s\n",
3702 osname, type, (u_longlong_t)dmu_objset_id(os),
3703 (u_longlong_t)dds.dds_creation_txg,
3704 numbuf, (u_longlong_t)usedobjs, blkbuf,
3705 (dds.dds_inconsistent) ? " (inconsistent)" : "");
3706
3707 for (i = 0; i < zopt_object_args; i++) {
3708 obj_start = zopt_object_ranges[i].zor_obj_start;
3709 obj_end = zopt_object_ranges[i].zor_obj_end;
3710 flags = zopt_object_ranges[i].zor_flags;
3711
3712 object = obj_start;
3713 if (object == 0 || obj_start == obj_end)
3714 dump_object(os, object, verbosity, &print_header, NULL,
3715 flags);
3716 else
3717 object--;
3718
3719 while ((dmu_object_next(os, &object, B_FALSE, 0) == 0) &&
3720 object <= obj_end) {
3721 dump_object(os, object, verbosity, &print_header, NULL,
3722 flags);
3723 }
3724 }
3725
3726 if (zopt_object_args > 0) {
3727 (void) printf("\n");
3728 return;
3729 }
3730
3731 if (dump_opt['i'] != 0 || verbosity >= 2)
3732 dump_intent_log(dmu_objset_zil(os));
3733
3734 if (dmu_objset_ds(os) != NULL) {
3735 dsl_dataset_t *ds = dmu_objset_ds(os);
3736 dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
3737 if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
3738 !dmu_objset_is_snapshot(os)) {
3739 dump_blkptr_list(&ds->ds_dir->dd_livelist, "Livelist");
3740 if (verify_dd_livelist(os) != 0)
3741 fatal("livelist is incorrect");
3742 }
3743
3744 if (dsl_dataset_remap_deadlist_exists(ds)) {
3745 (void) printf("ds_remap_deadlist:\n");
3746 dump_blkptr_list(&ds->ds_remap_deadlist, "Deadlist");
3747 }
3748 count_ds_mos_objects(ds);
3749 }
3750
3751 if (dmu_objset_ds(os) != NULL)
3752 dump_bookmarks(os, verbosity);
3753
3754 if (verbosity < 2)
3755 return;
3756
3757 if (BP_IS_HOLE(os->os_rootbp))
3758 return;
3759
3760 dump_object(os, 0, verbosity, &print_header, NULL, 0);
3761 object_count = 0;
3762 if (DMU_USERUSED_DNODE(os) != NULL &&
3763 DMU_USERUSED_DNODE(os)->dn_type != 0) {
3764 dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
3765 NULL, 0);
3766 dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
3767 NULL, 0);
3768 }
3769
3770 if (DMU_PROJECTUSED_DNODE(os) != NULL &&
3771 DMU_PROJECTUSED_DNODE(os)->dn_type != 0)
3772 dump_object(os, DMU_PROJECTUSED_OBJECT, verbosity,
3773 &print_header, NULL, 0);
3774
3775 object = 0;
3776 while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
3777 dump_object(os, object, verbosity, &print_header, &dnode_slots,
3778 0);
3779 object_count++;
3780 total_slots_used += dnode_slots;
3781 max_slot_used = object + dnode_slots - 1;
3782 }
3783
3784 (void) printf("\n");
3785
3786 (void) printf(" Dnode slots:\n");
3787 (void) printf("\tTotal used: %10llu\n",
3788 (u_longlong_t)total_slots_used);
3789 (void) printf("\tMax used: %10llu\n",
3790 (u_longlong_t)max_slot_used);
3791 (void) printf("\tPercent empty: %10lf\n",
3792 (double)(max_slot_used - total_slots_used)*100 /
3793 (double)max_slot_used);
3794 (void) printf("\n");
3795
3796 if (error != ESRCH) {
3797 (void) fprintf(stderr, "dmu_object_next() = %d\n", error);
3798 abort();
3799 }
3800
3801 ASSERT3U(object_count, ==, usedobjs);
3802
3803 if (leaked_objects != 0) {
3804 (void) printf("%d potentially leaked objects detected\n",
3805 leaked_objects);
3806 leaked_objects = 0;
3807 }
3808 }
3809
3810 static void
3811 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
3812 {
3813 time_t timestamp = ub->ub_timestamp;
3814
3815 (void) printf("%s", header ? header : "");
3816 (void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
3817 (void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
3818 (void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
3819 (void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
3820 (void) printf("\ttimestamp = %llu UTC = %s",
3821 (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
3822
3823 (void) printf("\tmmp_magic = %016llx\n",
3824 (u_longlong_t)ub->ub_mmp_magic);
3825 if (MMP_VALID(ub)) {
3826 (void) printf("\tmmp_delay = %0llu\n",
3827 (u_longlong_t)ub->ub_mmp_delay);
3828 if (MMP_SEQ_VALID(ub))
3829 (void) printf("\tmmp_seq = %u\n",
3830 (unsigned int) MMP_SEQ(ub));
3831 if (MMP_FAIL_INT_VALID(ub))
3832 (void) printf("\tmmp_fail = %u\n",
3833 (unsigned int) MMP_FAIL_INT(ub));
3834 if (MMP_INTERVAL_VALID(ub))
3835 (void) printf("\tmmp_write = %u\n",
3836 (unsigned int) MMP_INTERVAL(ub));
3837 /* After MMP_* to make summarize_uberblock_mmp cleaner */
3838 (void) printf("\tmmp_valid = %x\n",
3839 (unsigned int) ub->ub_mmp_config & 0xFF);
3840 }
3841
3842 if (dump_opt['u'] >= 4) {
3843 char blkbuf[BP_SPRINTF_LEN];
3844 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
3845 (void) printf("\trootbp = %s\n", blkbuf);
3846 }
3847 (void) printf("\tcheckpoint_txg = %llu\n",
3848 (u_longlong_t)ub->ub_checkpoint_txg);
3849 (void) printf("%s", footer ? footer : "");
3850 }
3851
3852 static void
3853 dump_config(spa_t *spa)
3854 {
3855 dmu_buf_t *db;
3856 size_t nvsize = 0;
3857 int error = 0;
3858
3859
3860 error = dmu_bonus_hold(spa->spa_meta_objset,
3861 spa->spa_config_object, FTAG, &db);
3862
3863 if (error == 0) {
3864 nvsize = *(uint64_t *)db->db_data;
3865 dmu_buf_rele(db, FTAG);
3866
3867 (void) printf("\nMOS Configuration:\n");
3868 dump_packed_nvlist(spa->spa_meta_objset,
3869 spa->spa_config_object, (void *)&nvsize, 1);
3870 } else {
3871 (void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
3872 (u_longlong_t)spa->spa_config_object, error);
3873 }
3874 }
3875
3876 static void
3877 dump_cachefile(const char *cachefile)
3878 {
3879 int fd;
3880 struct stat64 statbuf;
3881 char *buf;
3882 nvlist_t *config;
3883
3884 if ((fd = open64(cachefile, O_RDONLY)) < 0) {
3885 (void) printf("cannot open '%s': %s\n", cachefile,
3886 strerror(errno));
3887 exit(1);
3888 }
3889
3890 if (fstat64(fd, &statbuf) != 0) {
3891 (void) printf("failed to stat '%s': %s\n", cachefile,
3892 strerror(errno));
3893 exit(1);
3894 }
3895
3896 if ((buf = malloc(statbuf.st_size)) == NULL) {
3897 (void) fprintf(stderr, "failed to allocate %llu bytes\n",
3898 (u_longlong_t)statbuf.st_size);
3899 exit(1);
3900 }
3901
3902 if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
3903 (void) fprintf(stderr, "failed to read %llu bytes\n",
3904 (u_longlong_t)statbuf.st_size);
3905 exit(1);
3906 }
3907
3908 (void) close(fd);
3909
3910 if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
3911 (void) fprintf(stderr, "failed to unpack nvlist\n");
3912 exit(1);
3913 }
3914
3915 free(buf);
3916
3917 dump_nvlist(config, 0);
3918
3919 nvlist_free(config);
3920 }
3921
3922 /*
3923 * ZFS label nvlist stats
3924 */
3925 typedef struct zdb_nvl_stats {
3926 int zns_list_count;
3927 int zns_leaf_count;
3928 size_t zns_leaf_largest;
3929 size_t zns_leaf_total;
3930 nvlist_t *zns_string;
3931 nvlist_t *zns_uint64;
3932 nvlist_t *zns_boolean;
3933 } zdb_nvl_stats_t;
3934
3935 static void
3936 collect_nvlist_stats(nvlist_t *nvl, zdb_nvl_stats_t *stats)
3937 {
3938 nvlist_t *list, **array;
3939 nvpair_t *nvp = NULL;
3940 char *name;
3941 uint_t i, items;
3942
3943 stats->zns_list_count++;
3944
3945 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
3946 name = nvpair_name(nvp);
3947
3948 switch (nvpair_type(nvp)) {
3949 case DATA_TYPE_STRING:
3950 fnvlist_add_string(stats->zns_string, name,
3951 fnvpair_value_string(nvp));
3952 break;
3953 case DATA_TYPE_UINT64:
3954 fnvlist_add_uint64(stats->zns_uint64, name,
3955 fnvpair_value_uint64(nvp));
3956 break;
3957 case DATA_TYPE_BOOLEAN:
3958 fnvlist_add_boolean(stats->zns_boolean, name);
3959 break;
3960 case DATA_TYPE_NVLIST:
3961 if (nvpair_value_nvlist(nvp, &list) == 0)
3962 collect_nvlist_stats(list, stats);
3963 break;
3964 case DATA_TYPE_NVLIST_ARRAY:
3965 if (nvpair_value_nvlist_array(nvp, &array, &items) != 0)
3966 break;
3967
3968 for (i = 0; i < items; i++) {
3969 collect_nvlist_stats(array[i], stats);
3970
3971 /* collect stats on leaf vdev */
3972 if (strcmp(name, "children") == 0) {
3973 size_t size;
3974
3975 (void) nvlist_size(array[i], &size,
3976 NV_ENCODE_XDR);
3977 stats->zns_leaf_total += size;
3978 if (size > stats->zns_leaf_largest)
3979 stats->zns_leaf_largest = size;
3980 stats->zns_leaf_count++;
3981 }
3982 }
3983 break;
3984 default:
3985 (void) printf("skip type %d!\n", (int)nvpair_type(nvp));
3986 }
3987 }
3988 }
3989
3990 static void
3991 dump_nvlist_stats(nvlist_t *nvl, size_t cap)
3992 {
3993 zdb_nvl_stats_t stats = { 0 };
3994 size_t size, sum = 0, total;
3995 size_t noise;
3996
3997 /* requires nvlist with non-unique names for stat collection */
3998 VERIFY0(nvlist_alloc(&stats.zns_string, 0, 0));
3999 VERIFY0(nvlist_alloc(&stats.zns_uint64, 0, 0));
4000 VERIFY0(nvlist_alloc(&stats.zns_boolean, 0, 0));
4001 VERIFY0(nvlist_size(stats.zns_boolean, &noise, NV_ENCODE_XDR));
4002
4003 (void) printf("\n\nZFS Label NVList Config Stats:\n");
4004
4005 VERIFY0(nvlist_size(nvl, &total, NV_ENCODE_XDR));
4006 (void) printf(" %d bytes used, %d bytes free (using %4.1f%%)\n\n",
4007 (int)total, (int)(cap - total), 100.0 * total / cap);
4008
4009 collect_nvlist_stats(nvl, &stats);
4010
4011 VERIFY0(nvlist_size(stats.zns_uint64, &size, NV_ENCODE_XDR));
4012 size -= noise;
4013 sum += size;
4014 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "integers:",
4015 (int)fnvlist_num_pairs(stats.zns_uint64),
4016 (int)size, 100.0 * size / total);
4017
4018 VERIFY0(nvlist_size(stats.zns_string, &size, NV_ENCODE_XDR));
4019 size -= noise;
4020 sum += size;
4021 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "strings:",
4022 (int)fnvlist_num_pairs(stats.zns_string),
4023 (int)size, 100.0 * size / total);
4024
4025 VERIFY0(nvlist_size(stats.zns_boolean, &size, NV_ENCODE_XDR));
4026 size -= noise;
4027 sum += size;
4028 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "booleans:",
4029 (int)fnvlist_num_pairs(stats.zns_boolean),
4030 (int)size, 100.0 * size / total);
4031
4032 size = total - sum; /* treat remainder as nvlist overhead */
4033 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n\n", "nvlists:",
4034 stats.zns_list_count, (int)size, 100.0 * size / total);
4035
4036 if (stats.zns_leaf_count > 0) {
4037 size_t average = stats.zns_leaf_total / stats.zns_leaf_count;
4038
4039 (void) printf("%12s %4d %6d bytes average\n", "leaf vdevs:",
4040 stats.zns_leaf_count, (int)average);
4041 (void) printf("%24d bytes largest\n",
4042 (int)stats.zns_leaf_largest);
4043
4044 if (dump_opt['l'] >= 3 && average > 0)
4045 (void) printf(" space for %d additional leaf vdevs\n",
4046 (int)((cap - total) / average));
4047 }
4048 (void) printf("\n");
4049
4050 nvlist_free(stats.zns_string);
4051 nvlist_free(stats.zns_uint64);
4052 nvlist_free(stats.zns_boolean);
4053 }
4054
4055 typedef struct cksum_record {
4056 zio_cksum_t cksum;
4057 boolean_t labels[VDEV_LABELS];
4058 avl_node_t link;
4059 } cksum_record_t;
4060
4061 static int
4062 cksum_record_compare(const void *x1, const void *x2)
4063 {
4064 const cksum_record_t *l = (cksum_record_t *)x1;
4065 const cksum_record_t *r = (cksum_record_t *)x2;
4066 int arraysize = ARRAY_SIZE(l->cksum.zc_word);
4067 int difference;
4068
4069 for (int i = 0; i < arraysize; i++) {
4070 difference = TREE_CMP(l->cksum.zc_word[i], r->cksum.zc_word[i]);
4071 if (difference)
4072 break;
4073 }
4074
4075 return (difference);
4076 }
4077
4078 static cksum_record_t *
4079 cksum_record_alloc(zio_cksum_t *cksum, int l)
4080 {
4081 cksum_record_t *rec;
4082
4083 rec = umem_zalloc(sizeof (*rec), UMEM_NOFAIL);
4084 rec->cksum = *cksum;
4085 rec->labels[l] = B_TRUE;
4086
4087 return (rec);
4088 }
4089
4090 static cksum_record_t *
4091 cksum_record_lookup(avl_tree_t *tree, zio_cksum_t *cksum)
4092 {
4093 cksum_record_t lookup = { .cksum = *cksum };
4094 avl_index_t where;
4095
4096 return (avl_find(tree, &lookup, &where));
4097 }
4098
4099 static cksum_record_t *
4100 cksum_record_insert(avl_tree_t *tree, zio_cksum_t *cksum, int l)
4101 {
4102 cksum_record_t *rec;
4103
4104 rec = cksum_record_lookup(tree, cksum);
4105 if (rec) {
4106 rec->labels[l] = B_TRUE;
4107 } else {
4108 rec = cksum_record_alloc(cksum, l);
4109 avl_add(tree, rec);
4110 }
4111
4112 return (rec);
4113 }
4114
4115 static int
4116 first_label(cksum_record_t *rec)
4117 {
4118 for (int i = 0; i < VDEV_LABELS; i++)
4119 if (rec->labels[i])
4120 return (i);
4121
4122 return (-1);
4123 }
4124
4125 static void
4126 print_label_numbers(char *prefix, cksum_record_t *rec)
4127 {
4128 printf("%s", prefix);
4129 for (int i = 0; i < VDEV_LABELS; i++)
4130 if (rec->labels[i] == B_TRUE)
4131 printf("%d ", i);
4132 printf("\n");
4133 }
4134
4135 #define MAX_UBERBLOCK_COUNT (VDEV_UBERBLOCK_RING >> UBERBLOCK_SHIFT)
4136
4137 typedef struct zdb_label {
4138 vdev_label_t label;
4139 nvlist_t *config_nv;
4140 cksum_record_t *config;
4141 cksum_record_t *uberblocks[MAX_UBERBLOCK_COUNT];
4142 boolean_t header_printed;
4143 boolean_t read_failed;
4144 } zdb_label_t;
4145
4146 static void
4147 print_label_header(zdb_label_t *label, int l)
4148 {
4149
4150 if (dump_opt['q'])
4151 return;
4152
4153 if (label->header_printed == B_TRUE)
4154 return;
4155
4156 (void) printf("------------------------------------\n");
4157 (void) printf("LABEL %d\n", l);
4158 (void) printf("------------------------------------\n");
4159
4160 label->header_printed = B_TRUE;
4161 }
4162
4163 static void
4164 print_l2arc_header(void)
4165 {
4166 (void) printf("------------------------------------\n");
4167 (void) printf("L2ARC device header\n");
4168 (void) printf("------------------------------------\n");
4169 }
4170
4171 static void
4172 print_l2arc_log_blocks(void)
4173 {
4174 (void) printf("------------------------------------\n");
4175 (void) printf("L2ARC device log blocks\n");
4176 (void) printf("------------------------------------\n");
4177 }
4178
4179 static void
4180 dump_l2arc_log_entries(uint64_t log_entries,
4181 l2arc_log_ent_phys_t *le, uint64_t i)
4182 {
4183 for (int j = 0; j < log_entries; j++) {
4184 dva_t dva = le[j].le_dva;
4185 (void) printf("lb[%4llu]\tle[%4d]\tDVA asize: %llu, "
4186 "vdev: %llu, offset: %llu\n",
4187 (u_longlong_t)i, j + 1,
4188 (u_longlong_t)DVA_GET_ASIZE(&dva),
4189 (u_longlong_t)DVA_GET_VDEV(&dva),
4190 (u_longlong_t)DVA_GET_OFFSET(&dva));
4191 (void) printf("|\t\t\t\tbirth: %llu\n",
4192 (u_longlong_t)le[j].le_birth);
4193 (void) printf("|\t\t\t\tlsize: %llu\n",
4194 (u_longlong_t)L2BLK_GET_LSIZE((&le[j])->le_prop));
4195 (void) printf("|\t\t\t\tpsize: %llu\n",
4196 (u_longlong_t)L2BLK_GET_PSIZE((&le[j])->le_prop));
4197 (void) printf("|\t\t\t\tcompr: %llu\n",
4198 (u_longlong_t)L2BLK_GET_COMPRESS((&le[j])->le_prop));
4199 (void) printf("|\t\t\t\tcomplevel: %llu\n",
4200 (u_longlong_t)(&le[j])->le_complevel);
4201 (void) printf("|\t\t\t\ttype: %llu\n",
4202 (u_longlong_t)L2BLK_GET_TYPE((&le[j])->le_prop));
4203 (void) printf("|\t\t\t\tprotected: %llu\n",
4204 (u_longlong_t)L2BLK_GET_PROTECTED((&le[j])->le_prop));
4205 (void) printf("|\t\t\t\tprefetch: %llu\n",
4206 (u_longlong_t)L2BLK_GET_PREFETCH((&le[j])->le_prop));
4207 (void) printf("|\t\t\t\taddress: %llu\n",
4208 (u_longlong_t)le[j].le_daddr);
4209 (void) printf("|\t\t\t\tARC state: %llu\n",
4210 (u_longlong_t)L2BLK_GET_STATE((&le[j])->le_prop));
4211 (void) printf("|\n");
4212 }
4213 (void) printf("\n");
4214 }
4215
4216 static void
4217 dump_l2arc_log_blkptr(l2arc_log_blkptr_t lbps)
4218 {
4219 (void) printf("|\t\tdaddr: %llu\n", (u_longlong_t)lbps.lbp_daddr);
4220 (void) printf("|\t\tpayload_asize: %llu\n",
4221 (u_longlong_t)lbps.lbp_payload_asize);
4222 (void) printf("|\t\tpayload_start: %llu\n",
4223 (u_longlong_t)lbps.lbp_payload_start);
4224 (void) printf("|\t\tlsize: %llu\n",
4225 (u_longlong_t)L2BLK_GET_LSIZE((&lbps)->lbp_prop));
4226 (void) printf("|\t\tasize: %llu\n",
4227 (u_longlong_t)L2BLK_GET_PSIZE((&lbps)->lbp_prop));
4228 (void) printf("|\t\tcompralgo: %llu\n",
4229 (u_longlong_t)L2BLK_GET_COMPRESS((&lbps)->lbp_prop));
4230 (void) printf("|\t\tcksumalgo: %llu\n",
4231 (u_longlong_t)L2BLK_GET_CHECKSUM((&lbps)->lbp_prop));
4232 (void) printf("|\n\n");
4233 }
4234
4235 static void
4236 dump_l2arc_log_blocks(int fd, l2arc_dev_hdr_phys_t l2dhdr,
4237 l2arc_dev_hdr_phys_t *rebuild)
4238 {
4239 l2arc_log_blk_phys_t this_lb;
4240 uint64_t asize;
4241 l2arc_log_blkptr_t lbps[2];
4242 abd_t *abd;
4243 zio_cksum_t cksum;
4244 int failed = 0;
4245 l2arc_dev_t dev;
4246
4247 if (!dump_opt['q'])
4248 print_l2arc_log_blocks();
4249 bcopy((&l2dhdr)->dh_start_lbps, lbps, sizeof (lbps));
4250
4251 dev.l2ad_evict = l2dhdr.dh_evict;
4252 dev.l2ad_start = l2dhdr.dh_start;
4253 dev.l2ad_end = l2dhdr.dh_end;
4254
4255 if (l2dhdr.dh_start_lbps[0].lbp_daddr == 0) {
4256 /* no log blocks to read */
4257 if (!dump_opt['q']) {
4258 (void) printf("No log blocks to read\n");
4259 (void) printf("\n");
4260 }
4261 return;
4262 } else {
4263 dev.l2ad_hand = lbps[0].lbp_daddr +
4264 L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4265 }
4266
4267 dev.l2ad_first = !!(l2dhdr.dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
4268
4269 for (;;) {
4270 if (!l2arc_log_blkptr_valid(&dev, &lbps[0]))
4271 break;
4272
4273 /* L2BLK_GET_PSIZE returns aligned size for log blocks */
4274 asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4275 if (pread64(fd, &this_lb, asize, lbps[0].lbp_daddr) != asize) {
4276 if (!dump_opt['q']) {
4277 (void) printf("Error while reading next log "
4278 "block\n\n");
4279 }
4280 break;
4281 }
4282
4283 fletcher_4_native_varsize(&this_lb, asize, &cksum);
4284 if (!ZIO_CHECKSUM_EQUAL(cksum, lbps[0].lbp_cksum)) {
4285 failed++;
4286 if (!dump_opt['q']) {
4287 (void) printf("Invalid cksum\n");
4288 dump_l2arc_log_blkptr(lbps[0]);
4289 }
4290 break;
4291 }
4292
4293 switch (L2BLK_GET_COMPRESS((&lbps[0])->lbp_prop)) {
4294 case ZIO_COMPRESS_OFF:
4295 break;
4296 default:
4297 abd = abd_alloc_for_io(asize, B_TRUE);
4298 abd_copy_from_buf_off(abd, &this_lb, 0, asize);
4299 zio_decompress_data(L2BLK_GET_COMPRESS(
4300 (&lbps[0])->lbp_prop), abd, &this_lb,
4301 asize, sizeof (this_lb), NULL);
4302 abd_free(abd);
4303 break;
4304 }
4305
4306 if (this_lb.lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
4307 byteswap_uint64_array(&this_lb, sizeof (this_lb));
4308 if (this_lb.lb_magic != L2ARC_LOG_BLK_MAGIC) {
4309 if (!dump_opt['q'])
4310 (void) printf("Invalid log block magic\n\n");
4311 break;
4312 }
4313
4314 rebuild->dh_lb_count++;
4315 rebuild->dh_lb_asize += asize;
4316 if (dump_opt['l'] > 1 && !dump_opt['q']) {
4317 (void) printf("lb[%4llu]\tmagic: %llu\n",
4318 (u_longlong_t)rebuild->dh_lb_count,
4319 (u_longlong_t)this_lb.lb_magic);
4320 dump_l2arc_log_blkptr(lbps[0]);
4321 }
4322
4323 if (dump_opt['l'] > 2 && !dump_opt['q'])
4324 dump_l2arc_log_entries(l2dhdr.dh_log_entries,
4325 this_lb.lb_entries,
4326 rebuild->dh_lb_count);
4327
4328 if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
4329 lbps[0].lbp_payload_start, dev.l2ad_evict) &&
4330 !dev.l2ad_first)
4331 break;
4332
4333 lbps[0] = lbps[1];
4334 lbps[1] = this_lb.lb_prev_lbp;
4335 }
4336
4337 if (!dump_opt['q']) {
4338 (void) printf("log_blk_count:\t %llu with valid cksum\n",
4339 (u_longlong_t)rebuild->dh_lb_count);
4340 (void) printf("\t\t %d with invalid cksum\n", failed);
4341 (void) printf("log_blk_asize:\t %llu\n\n",
4342 (u_longlong_t)rebuild->dh_lb_asize);
4343 }
4344 }
4345
4346 static int
4347 dump_l2arc_header(int fd)
4348 {
4349 l2arc_dev_hdr_phys_t l2dhdr, rebuild;
4350 int error = B_FALSE;
4351
4352 bzero(&l2dhdr, sizeof (l2dhdr));
4353 bzero(&rebuild, sizeof (rebuild));
4354
4355 if (pread64(fd, &l2dhdr, sizeof (l2dhdr),
4356 VDEV_LABEL_START_SIZE) != sizeof (l2dhdr)) {
4357 error = B_TRUE;
4358 } else {
4359 if (l2dhdr.dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
4360 byteswap_uint64_array(&l2dhdr, sizeof (l2dhdr));
4361
4362 if (l2dhdr.dh_magic != L2ARC_DEV_HDR_MAGIC)
4363 error = B_TRUE;
4364 }
4365
4366 if (error) {
4367 (void) printf("L2ARC device header not found\n\n");
4368 /* Do not return an error here for backward compatibility */
4369 return (0);
4370 } else if (!dump_opt['q']) {
4371 print_l2arc_header();
4372
4373 (void) printf(" magic: %llu\n",
4374 (u_longlong_t)l2dhdr.dh_magic);
4375 (void) printf(" version: %llu\n",
4376 (u_longlong_t)l2dhdr.dh_version);
4377 (void) printf(" pool_guid: %llu\n",
4378 (u_longlong_t)l2dhdr.dh_spa_guid);
4379 (void) printf(" flags: %llu\n",
4380 (u_longlong_t)l2dhdr.dh_flags);
4381 (void) printf(" start_lbps[0]: %llu\n",
4382 (u_longlong_t)
4383 l2dhdr.dh_start_lbps[0].lbp_daddr);
4384 (void) printf(" start_lbps[1]: %llu\n",
4385 (u_longlong_t)
4386 l2dhdr.dh_start_lbps[1].lbp_daddr);
4387 (void) printf(" log_blk_ent: %llu\n",
4388 (u_longlong_t)l2dhdr.dh_log_entries);
4389 (void) printf(" start: %llu\n",
4390 (u_longlong_t)l2dhdr.dh_start);
4391 (void) printf(" end: %llu\n",
4392 (u_longlong_t)l2dhdr.dh_end);
4393 (void) printf(" evict: %llu\n",
4394 (u_longlong_t)l2dhdr.dh_evict);
4395 (void) printf(" lb_asize_refcount: %llu\n",
4396 (u_longlong_t)l2dhdr.dh_lb_asize);
4397 (void) printf(" lb_count_refcount: %llu\n",
4398 (u_longlong_t)l2dhdr.dh_lb_count);
4399 (void) printf(" trim_action_time: %llu\n",
4400 (u_longlong_t)l2dhdr.dh_trim_action_time);
4401 (void) printf(" trim_state: %llu\n\n",
4402 (u_longlong_t)l2dhdr.dh_trim_state);
4403 }
4404
4405 dump_l2arc_log_blocks(fd, l2dhdr, &rebuild);
4406 /*
4407 * The total aligned size of log blocks and the number of log blocks
4408 * reported in the header of the device may be less than what zdb
4409 * reports by dump_l2arc_log_blocks() which emulates l2arc_rebuild().
4410 * This happens because dump_l2arc_log_blocks() lacks the memory
4411 * pressure valve that l2arc_rebuild() has. Thus, if we are on a system
4412 * with low memory, l2arc_rebuild will exit prematurely and dh_lb_asize
4413 * and dh_lb_count will be lower to begin with than what exists on the
4414 * device. This is normal and zdb should not exit with an error. The
4415 * opposite case should never happen though, the values reported in the
4416 * header should never be higher than what dump_l2arc_log_blocks() and
4417 * l2arc_rebuild() report. If this happens there is a leak in the
4418 * accounting of log blocks.
4419 */
4420 if (l2dhdr.dh_lb_asize > rebuild.dh_lb_asize ||
4421 l2dhdr.dh_lb_count > rebuild.dh_lb_count)
4422 return (1);
4423
4424 return (0);
4425 }
4426
4427 static void
4428 dump_config_from_label(zdb_label_t *label, size_t buflen, int l)
4429 {
4430 if (dump_opt['q'])
4431 return;
4432
4433 if ((dump_opt['l'] < 3) && (first_label(label->config) != l))
4434 return;
4435
4436 print_label_header(label, l);
4437 dump_nvlist(label->config_nv, 4);
4438 print_label_numbers(" labels = ", label->config);
4439
4440 if (dump_opt['l'] >= 2)
4441 dump_nvlist_stats(label->config_nv, buflen);
4442 }
4443
4444 #define ZDB_MAX_UB_HEADER_SIZE 32
4445
4446 static void
4447 dump_label_uberblocks(zdb_label_t *label, uint64_t ashift, int label_num)
4448 {
4449
4450 vdev_t vd;
4451 char header[ZDB_MAX_UB_HEADER_SIZE];
4452
4453 vd.vdev_ashift = ashift;
4454 vd.vdev_top = &vd;
4455
4456 for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
4457 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
4458 uberblock_t *ub = (void *)((char *)&label->label + uoff);
4459 cksum_record_t *rec = label->uberblocks[i];
4460
4461 if (rec == NULL) {
4462 if (dump_opt['u'] >= 2) {
4463 print_label_header(label, label_num);
4464 (void) printf(" Uberblock[%d] invalid\n", i);
4465 }
4466 continue;
4467 }
4468
4469 if ((dump_opt['u'] < 3) && (first_label(rec) != label_num))
4470 continue;
4471
4472 if ((dump_opt['u'] < 4) &&
4473 (ub->ub_mmp_magic == MMP_MAGIC) && ub->ub_mmp_delay &&
4474 (i >= VDEV_UBERBLOCK_COUNT(&vd) - MMP_BLOCKS_PER_LABEL))
4475 continue;
4476
4477 print_label_header(label, label_num);
4478 (void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
4479 " Uberblock[%d]\n", i);
4480 dump_uberblock(ub, header, "");
4481 print_label_numbers(" labels = ", rec);
4482 }
4483 }
4484
4485 static char curpath[PATH_MAX];
4486
4487 /*
4488 * Iterate through the path components, recursively passing
4489 * current one's obj and remaining path until we find the obj
4490 * for the last one.
4491 */
4492 static int
4493 dump_path_impl(objset_t *os, uint64_t obj, char *name)
4494 {
4495 int err;
4496 boolean_t header = B_TRUE;
4497 uint64_t child_obj;
4498 char *s;
4499 dmu_buf_t *db;
4500 dmu_object_info_t doi;
4501
4502 if ((s = strchr(name, '/')) != NULL)
4503 *s = '\0';
4504 err = zap_lookup(os, obj, name, 8, 1, &child_obj);
4505
4506 (void) strlcat(curpath, name, sizeof (curpath));
4507
4508 if (err != 0) {
4509 (void) fprintf(stderr, "failed to lookup %s: %s\n",
4510 curpath, strerror(err));
4511 return (err);
4512 }
4513
4514 child_obj = ZFS_DIRENT_OBJ(child_obj);
4515 err = sa_buf_hold(os, child_obj, FTAG, &db);
4516 if (err != 0) {
4517 (void) fprintf(stderr,
4518 "failed to get SA dbuf for obj %llu: %s\n",
4519 (u_longlong_t)child_obj, strerror(err));
4520 return (EINVAL);
4521 }
4522 dmu_object_info_from_db(db, &doi);
4523 sa_buf_rele(db, FTAG);
4524
4525 if (doi.doi_bonus_type != DMU_OT_SA &&
4526 doi.doi_bonus_type != DMU_OT_ZNODE) {
4527 (void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
4528 doi.doi_bonus_type, (u_longlong_t)child_obj);
4529 return (EINVAL);
4530 }
4531
4532 if (dump_opt['v'] > 6) {
4533 (void) printf("obj=%llu %s type=%d bonustype=%d\n",
4534 (u_longlong_t)child_obj, curpath, doi.doi_type,
4535 doi.doi_bonus_type);
4536 }
4537
4538 (void) strlcat(curpath, "/", sizeof (curpath));
4539
4540 switch (doi.doi_type) {
4541 case DMU_OT_DIRECTORY_CONTENTS:
4542 if (s != NULL && *(s + 1) != '\0')
4543 return (dump_path_impl(os, child_obj, s + 1));
4544 /*FALLTHROUGH*/
4545 case DMU_OT_PLAIN_FILE_CONTENTS:
4546 dump_object(os, child_obj, dump_opt['v'], &header, NULL, 0);
4547 return (0);
4548 default:
4549 (void) fprintf(stderr, "object %llu has non-file/directory "
4550 "type %d\n", (u_longlong_t)obj, doi.doi_type);
4551 break;
4552 }
4553
4554 return (EINVAL);
4555 }
4556
4557 /*
4558 * Dump the blocks for the object specified by path inside the dataset.
4559 */
4560 static int
4561 dump_path(char *ds, char *path)
4562 {
4563 int err;
4564 objset_t *os;
4565 uint64_t root_obj;
4566
4567 err = open_objset(ds, FTAG, &os);
4568 if (err != 0)
4569 return (err);
4570
4571 err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
4572 if (err != 0) {
4573 (void) fprintf(stderr, "can't lookup root znode: %s\n",
4574 strerror(err));
4575 close_objset(os, FTAG);
4576 return (EINVAL);
4577 }
4578
4579 (void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
4580
4581 err = dump_path_impl(os, root_obj, path);
4582
4583 close_objset(os, FTAG);
4584 return (err);
4585 }
4586
4587 static int
4588 dump_label(const char *dev)
4589 {
4590 char path[MAXPATHLEN];
4591 zdb_label_t labels[VDEV_LABELS];
4592 uint64_t psize, ashift, l2cache;
4593 struct stat64 statbuf;
4594 boolean_t config_found = B_FALSE;
4595 boolean_t error = B_FALSE;
4596 boolean_t read_l2arc_header = B_FALSE;
4597 avl_tree_t config_tree;
4598 avl_tree_t uberblock_tree;
4599 void *node, *cookie;
4600 int fd;
4601
4602 bzero(labels, sizeof (labels));
4603
4604 /*
4605 * Check if we were given absolute path and use it as is.
4606 * Otherwise if the provided vdev name doesn't point to a file,
4607 * try prepending expected disk paths and partition numbers.
4608 */
4609 (void) strlcpy(path, dev, sizeof (path));
4610 if (dev[0] != '/' && stat64(path, &statbuf) != 0) {
4611 int error;
4612
4613 error = zfs_resolve_shortname(dev, path, MAXPATHLEN);
4614 if (error == 0 && zfs_dev_is_whole_disk(path)) {
4615 if (zfs_append_partition(path, MAXPATHLEN) == -1)
4616 error = ENOENT;
4617 }
4618
4619 if (error || (stat64(path, &statbuf) != 0)) {
4620 (void) printf("failed to find device %s, try "
4621 "specifying absolute path instead\n", dev);
4622 return (1);
4623 }
4624 }
4625
4626 if ((fd = open64(path, O_RDONLY)) < 0) {
4627 (void) printf("cannot open '%s': %s\n", path, strerror(errno));
4628 exit(1);
4629 }
4630
4631 if (fstat64_blk(fd, &statbuf) != 0) {
4632 (void) printf("failed to stat '%s': %s\n", path,
4633 strerror(errno));
4634 (void) close(fd);
4635 exit(1);
4636 }
4637
4638 if (S_ISBLK(statbuf.st_mode) && zfs_dev_flush(fd) != 0)
4639 (void) printf("failed to invalidate cache '%s' : %s\n", path,
4640 strerror(errno));
4641
4642 avl_create(&config_tree, cksum_record_compare,
4643 sizeof (cksum_record_t), offsetof(cksum_record_t, link));
4644 avl_create(&uberblock_tree, cksum_record_compare,
4645 sizeof (cksum_record_t), offsetof(cksum_record_t, link));
4646
4647 psize = statbuf.st_size;
4648 psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
4649 ashift = SPA_MINBLOCKSHIFT;
4650
4651 /*
4652 * 1. Read the label from disk
4653 * 2. Unpack the configuration and insert in config tree.
4654 * 3. Traverse all uberblocks and insert in uberblock tree.
4655 */
4656 for (int l = 0; l < VDEV_LABELS; l++) {
4657 zdb_label_t *label = &labels[l];
4658 char *buf = label->label.vl_vdev_phys.vp_nvlist;
4659 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
4660 nvlist_t *config;
4661 cksum_record_t *rec;
4662 zio_cksum_t cksum;
4663 vdev_t vd;
4664
4665 if (pread64(fd, &label->label, sizeof (label->label),
4666 vdev_label_offset(psize, l, 0)) != sizeof (label->label)) {
4667 if (!dump_opt['q'])
4668 (void) printf("failed to read label %d\n", l);
4669 label->read_failed = B_TRUE;
4670 error = B_TRUE;
4671 continue;
4672 }
4673
4674 label->read_failed = B_FALSE;
4675
4676 if (nvlist_unpack(buf, buflen, &config, 0) == 0) {
4677 nvlist_t *vdev_tree = NULL;
4678 size_t size;
4679
4680 if ((nvlist_lookup_nvlist(config,
4681 ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
4682 (nvlist_lookup_uint64(vdev_tree,
4683 ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
4684 ashift = SPA_MINBLOCKSHIFT;
4685
4686 if (nvlist_size(config, &size, NV_ENCODE_XDR) != 0)
4687 size = buflen;
4688
4689 /* If the device is a cache device clear the header. */
4690 if (!read_l2arc_header) {
4691 if (nvlist_lookup_uint64(config,
4692 ZPOOL_CONFIG_POOL_STATE, &l2cache) == 0 &&
4693 l2cache == POOL_STATE_L2CACHE) {
4694 read_l2arc_header = B_TRUE;
4695 }
4696 }
4697
4698 fletcher_4_native_varsize(buf, size, &cksum);
4699 rec = cksum_record_insert(&config_tree, &cksum, l);
4700
4701 label->config = rec;
4702 label->config_nv = config;
4703 config_found = B_TRUE;
4704 } else {
4705 error = B_TRUE;
4706 }
4707
4708 vd.vdev_ashift = ashift;
4709 vd.vdev_top = &vd;
4710
4711 for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
4712 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
4713 uberblock_t *ub = (void *)((char *)label + uoff);
4714
4715 if (uberblock_verify(ub))
4716 continue;
4717
4718 fletcher_4_native_varsize(ub, sizeof (*ub), &cksum);
4719 rec = cksum_record_insert(&uberblock_tree, &cksum, l);
4720
4721 label->uberblocks[i] = rec;
4722 }
4723 }
4724
4725 /*
4726 * Dump the label and uberblocks.
4727 */
4728 for (int l = 0; l < VDEV_LABELS; l++) {
4729 zdb_label_t *label = &labels[l];
4730 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
4731
4732 if (label->read_failed == B_TRUE)
4733 continue;
4734
4735 if (label->config_nv) {
4736 dump_config_from_label(label, buflen, l);
4737 } else {
4738 if (!dump_opt['q'])
4739 (void) printf("failed to unpack label %d\n", l);
4740 }
4741
4742 if (dump_opt['u'])
4743 dump_label_uberblocks(label, ashift, l);
4744
4745 nvlist_free(label->config_nv);
4746 }
4747
4748 /*
4749 * Dump the L2ARC header, if existent.
4750 */
4751 if (read_l2arc_header)
4752 error |= dump_l2arc_header(fd);
4753
4754 cookie = NULL;
4755 while ((node = avl_destroy_nodes(&config_tree, &cookie)) != NULL)
4756 umem_free(node, sizeof (cksum_record_t));
4757
4758 cookie = NULL;
4759 while ((node = avl_destroy_nodes(&uberblock_tree, &cookie)) != NULL)
4760 umem_free(node, sizeof (cksum_record_t));
4761
4762 avl_destroy(&config_tree);
4763 avl_destroy(&uberblock_tree);
4764
4765 (void) close(fd);
4766
4767 return (config_found == B_FALSE ? 2 :
4768 (error == B_TRUE ? 1 : 0));
4769 }
4770
4771 static uint64_t dataset_feature_count[SPA_FEATURES];
4772 static uint64_t global_feature_count[SPA_FEATURES];
4773 static uint64_t remap_deadlist_count = 0;
4774
4775 /*ARGSUSED*/
4776 static int
4777 dump_one_objset(const char *dsname, void *arg)
4778 {
4779 int error;
4780 objset_t *os;
4781 spa_feature_t f;
4782
4783 error = open_objset(dsname, FTAG, &os);
4784 if (error != 0)
4785 return (0);
4786
4787 for (f = 0; f < SPA_FEATURES; f++) {
4788 if (!dsl_dataset_feature_is_active(dmu_objset_ds(os), f))
4789 continue;
4790 ASSERT(spa_feature_table[f].fi_flags &
4791 ZFEATURE_FLAG_PER_DATASET);
4792 dataset_feature_count[f]++;
4793 }
4794
4795 if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
4796 remap_deadlist_count++;
4797 }
4798
4799 for (dsl_bookmark_node_t *dbn =
4800 avl_first(&dmu_objset_ds(os)->ds_bookmarks); dbn != NULL;
4801 dbn = AVL_NEXT(&dmu_objset_ds(os)->ds_bookmarks, dbn)) {
4802 mos_obj_refd(dbn->dbn_phys.zbm_redaction_obj);
4803 if (dbn->dbn_phys.zbm_redaction_obj != 0)
4804 global_feature_count[SPA_FEATURE_REDACTION_BOOKMARKS]++;
4805 if (dbn->dbn_phys.zbm_flags & ZBM_FLAG_HAS_FBN)
4806 global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN]++;
4807 }
4808
4809 if (dsl_deadlist_is_open(&dmu_objset_ds(os)->ds_dir->dd_livelist) &&
4810 !dmu_objset_is_snapshot(os)) {
4811 global_feature_count[SPA_FEATURE_LIVELIST]++;
4812 }
4813
4814 dump_objset(os);
4815 close_objset(os, FTAG);
4816 fuid_table_destroy();
4817 return (0);
4818 }
4819
4820 /*
4821 * Block statistics.
4822 */
4823 #define PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
4824 typedef struct zdb_blkstats {
4825 uint64_t zb_asize;
4826 uint64_t zb_lsize;
4827 uint64_t zb_psize;
4828 uint64_t zb_count;
4829 uint64_t zb_gangs;
4830 uint64_t zb_ditto_samevdev;
4831 uint64_t zb_ditto_same_ms;
4832 uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
4833 } zdb_blkstats_t;
4834
4835 /*
4836 * Extended object types to report deferred frees and dedup auto-ditto blocks.
4837 */
4838 #define ZDB_OT_DEFERRED (DMU_OT_NUMTYPES + 0)
4839 #define ZDB_OT_DITTO (DMU_OT_NUMTYPES + 1)
4840 #define ZDB_OT_OTHER (DMU_OT_NUMTYPES + 2)
4841 #define ZDB_OT_TOTAL (DMU_OT_NUMTYPES + 3)
4842
4843 static const char *zdb_ot_extname[] = {
4844 "deferred free",
4845 "dedup ditto",
4846 "other",
4847 "Total",
4848 };
4849
4850 #define ZB_TOTAL DN_MAX_LEVELS
4851 #define SPA_MAX_FOR_16M (SPA_MAXBLOCKSHIFT+1)
4852
4853 typedef struct zdb_cb {
4854 zdb_blkstats_t zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
4855 uint64_t zcb_removing_size;
4856 uint64_t zcb_checkpoint_size;
4857 uint64_t zcb_dedup_asize;
4858 uint64_t zcb_dedup_blocks;
4859 uint64_t zcb_psize_count[SPA_MAX_FOR_16M];
4860 uint64_t zcb_lsize_count[SPA_MAX_FOR_16M];
4861 uint64_t zcb_asize_count[SPA_MAX_FOR_16M];
4862 uint64_t zcb_psize_len[SPA_MAX_FOR_16M];
4863 uint64_t zcb_lsize_len[SPA_MAX_FOR_16M];
4864 uint64_t zcb_asize_len[SPA_MAX_FOR_16M];
4865 uint64_t zcb_psize_total;
4866 uint64_t zcb_lsize_total;
4867 uint64_t zcb_asize_total;
4868 uint64_t zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
4869 uint64_t zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
4870 [BPE_PAYLOAD_SIZE + 1];
4871 uint64_t zcb_start;
4872 hrtime_t zcb_lastprint;
4873 uint64_t zcb_totalasize;
4874 uint64_t zcb_errors[256];
4875 int zcb_readfails;
4876 int zcb_haderrors;
4877 spa_t *zcb_spa;
4878 uint32_t **zcb_vd_obsolete_counts;
4879 } zdb_cb_t;
4880
4881 /* test if two DVA offsets from same vdev are within the same metaslab */
4882 static boolean_t
4883 same_metaslab(spa_t *spa, uint64_t vdev, uint64_t off1, uint64_t off2)
4884 {
4885 vdev_t *vd = vdev_lookup_top(spa, vdev);
4886 uint64_t ms_shift = vd->vdev_ms_shift;
4887
4888 return ((off1 >> ms_shift) == (off2 >> ms_shift));
4889 }
4890
4891 /*
4892 * Used to simplify reporting of the histogram data.
4893 */
4894 typedef struct one_histo {
4895 char *name;
4896 uint64_t *count;
4897 uint64_t *len;
4898 uint64_t cumulative;
4899 } one_histo_t;
4900
4901 /*
4902 * The number of separate histograms processed for psize, lsize and asize.
4903 */
4904 #define NUM_HISTO 3
4905
4906 /*
4907 * This routine will create a fixed column size output of three different
4908 * histograms showing by blocksize of 512 - 2^ SPA_MAX_FOR_16M
4909 * the count, length and cumulative length of the psize, lsize and
4910 * asize blocks.
4911 *
4912 * All three types of blocks are listed on a single line
4913 *
4914 * By default the table is printed in nicenumber format (e.g. 123K) but
4915 * if the '-P' parameter is specified then the full raw number (parseable)
4916 * is printed out.
4917 */
4918 static void
4919 dump_size_histograms(zdb_cb_t *zcb)
4920 {
4921 /*
4922 * A temporary buffer that allows us to convert a number into
4923 * a string using zdb_nicenumber to allow either raw or human
4924 * readable numbers to be output.
4925 */
4926 char numbuf[32];
4927
4928 /*
4929 * Define titles which are used in the headers of the tables
4930 * printed by this routine.
4931 */
4932 const char blocksize_title1[] = "block";
4933 const char blocksize_title2[] = "size";
4934 const char count_title[] = "Count";
4935 const char length_title[] = "Size";
4936 const char cumulative_title[] = "Cum.";
4937
4938 /*
4939 * Setup the histogram arrays (psize, lsize, and asize).
4940 */
4941 one_histo_t parm_histo[NUM_HISTO];
4942
4943 parm_histo[0].name = "psize";
4944 parm_histo[0].count = zcb->zcb_psize_count;
4945 parm_histo[0].len = zcb->zcb_psize_len;
4946 parm_histo[0].cumulative = 0;
4947
4948 parm_histo[1].name = "lsize";
4949 parm_histo[1].count = zcb->zcb_lsize_count;
4950 parm_histo[1].len = zcb->zcb_lsize_len;
4951 parm_histo[1].cumulative = 0;
4952
4953 parm_histo[2].name = "asize";
4954 parm_histo[2].count = zcb->zcb_asize_count;
4955 parm_histo[2].len = zcb->zcb_asize_len;
4956 parm_histo[2].cumulative = 0;
4957
4958
4959 (void) printf("\nBlock Size Histogram\n");
4960 /*
4961 * Print the first line titles
4962 */
4963 if (dump_opt['P'])
4964 (void) printf("\n%s\t", blocksize_title1);
4965 else
4966 (void) printf("\n%7s ", blocksize_title1);
4967
4968 for (int j = 0; j < NUM_HISTO; j++) {
4969 if (dump_opt['P']) {
4970 if (j < NUM_HISTO - 1) {
4971 (void) printf("%s\t\t\t", parm_histo[j].name);
4972 } else {
4973 /* Don't print trailing spaces */
4974 (void) printf(" %s", parm_histo[j].name);
4975 }
4976 } else {
4977 if (j < NUM_HISTO - 1) {
4978 /* Left aligned strings in the output */
4979 (void) printf("%-7s ",
4980 parm_histo[j].name);
4981 } else {
4982 /* Don't print trailing spaces */
4983 (void) printf("%s", parm_histo[j].name);
4984 }
4985 }
4986 }
4987 (void) printf("\n");
4988
4989 /*
4990 * Print the second line titles
4991 */
4992 if (dump_opt['P']) {
4993 (void) printf("%s\t", blocksize_title2);
4994 } else {
4995 (void) printf("%7s ", blocksize_title2);
4996 }
4997
4998 for (int i = 0; i < NUM_HISTO; i++) {
4999 if (dump_opt['P']) {
5000 (void) printf("%s\t%s\t%s\t",
5001 count_title, length_title, cumulative_title);
5002 } else {
5003 (void) printf("%7s%7s%7s",
5004 count_title, length_title, cumulative_title);
5005 }
5006 }
5007 (void) printf("\n");
5008
5009 /*
5010 * Print the rows
5011 */
5012 for (int i = SPA_MINBLOCKSHIFT; i < SPA_MAX_FOR_16M; i++) {
5013
5014 /*
5015 * Print the first column showing the blocksize
5016 */
5017 zdb_nicenum((1ULL << i), numbuf, sizeof (numbuf));
5018
5019 if (dump_opt['P']) {
5020 printf("%s", numbuf);
5021 } else {
5022 printf("%7s:", numbuf);
5023 }
5024
5025 /*
5026 * Print the remaining set of 3 columns per size:
5027 * for psize, lsize and asize
5028 */
5029 for (int j = 0; j < NUM_HISTO; j++) {
5030 parm_histo[j].cumulative += parm_histo[j].len[i];
5031
5032 zdb_nicenum(parm_histo[j].count[i],
5033 numbuf, sizeof (numbuf));
5034 if (dump_opt['P'])
5035 (void) printf("\t%s", numbuf);
5036 else
5037 (void) printf("%7s", numbuf);
5038
5039 zdb_nicenum(parm_histo[j].len[i],
5040 numbuf, sizeof (numbuf));
5041 if (dump_opt['P'])
5042 (void) printf("\t%s", numbuf);
5043 else
5044 (void) printf("%7s", numbuf);
5045
5046 zdb_nicenum(parm_histo[j].cumulative,
5047 numbuf, sizeof (numbuf));
5048 if (dump_opt['P'])
5049 (void) printf("\t%s", numbuf);
5050 else
5051 (void) printf("%7s", numbuf);
5052 }
5053 (void) printf("\n");
5054 }
5055 }
5056
5057 static void
5058 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
5059 dmu_object_type_t type)
5060 {
5061 uint64_t refcnt = 0;
5062 int i;
5063
5064 ASSERT(type < ZDB_OT_TOTAL);
5065
5066 if (zilog && zil_bp_tree_add(zilog, bp) != 0)
5067 return;
5068
5069 spa_config_enter(zcb->zcb_spa, SCL_CONFIG, FTAG, RW_READER);
5070
5071 for (i = 0; i < 4; i++) {
5072 int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
5073 int t = (i & 1) ? type : ZDB_OT_TOTAL;
5074 int equal;
5075 zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
5076
5077 zb->zb_asize += BP_GET_ASIZE(bp);
5078 zb->zb_lsize += BP_GET_LSIZE(bp);
5079 zb->zb_psize += BP_GET_PSIZE(bp);
5080 zb->zb_count++;
5081
5082 /*
5083 * The histogram is only big enough to record blocks up to
5084 * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
5085 * "other", bucket.
5086 */
5087 unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
5088 idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
5089 zb->zb_psize_histogram[idx]++;
5090
5091 zb->zb_gangs += BP_COUNT_GANG(bp);
5092
5093 switch (BP_GET_NDVAS(bp)) {
5094 case 2:
5095 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5096 DVA_GET_VDEV(&bp->blk_dva[1])) {
5097 zb->zb_ditto_samevdev++;
5098
5099 if (same_metaslab(zcb->zcb_spa,
5100 DVA_GET_VDEV(&bp->blk_dva[0]),
5101 DVA_GET_OFFSET(&bp->blk_dva[0]),
5102 DVA_GET_OFFSET(&bp->blk_dva[1])))
5103 zb->zb_ditto_same_ms++;
5104 }
5105 break;
5106 case 3:
5107 equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5108 DVA_GET_VDEV(&bp->blk_dva[1])) +
5109 (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5110 DVA_GET_VDEV(&bp->blk_dva[2])) +
5111 (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5112 DVA_GET_VDEV(&bp->blk_dva[2]));
5113 if (equal != 0) {
5114 zb->zb_ditto_samevdev++;
5115
5116 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5117 DVA_GET_VDEV(&bp->blk_dva[1]) &&
5118 same_metaslab(zcb->zcb_spa,
5119 DVA_GET_VDEV(&bp->blk_dva[0]),
5120 DVA_GET_OFFSET(&bp->blk_dva[0]),
5121 DVA_GET_OFFSET(&bp->blk_dva[1])))
5122 zb->zb_ditto_same_ms++;
5123 else if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5124 DVA_GET_VDEV(&bp->blk_dva[2]) &&
5125 same_metaslab(zcb->zcb_spa,
5126 DVA_GET_VDEV(&bp->blk_dva[0]),
5127 DVA_GET_OFFSET(&bp->blk_dva[0]),
5128 DVA_GET_OFFSET(&bp->blk_dva[2])))
5129 zb->zb_ditto_same_ms++;
5130 else if (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5131 DVA_GET_VDEV(&bp->blk_dva[2]) &&
5132 same_metaslab(zcb->zcb_spa,
5133 DVA_GET_VDEV(&bp->blk_dva[1]),
5134 DVA_GET_OFFSET(&bp->blk_dva[1]),
5135 DVA_GET_OFFSET(&bp->blk_dva[2])))
5136 zb->zb_ditto_same_ms++;
5137 }
5138 break;
5139 }
5140 }
5141
5142 spa_config_exit(zcb->zcb_spa, SCL_CONFIG, FTAG);
5143
5144 if (BP_IS_EMBEDDED(bp)) {
5145 zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
5146 zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
5147 [BPE_GET_PSIZE(bp)]++;
5148 return;
5149 }
5150 /*
5151 * The binning histogram bins by powers of two up to
5152 * SPA_MAXBLOCKSIZE rather than creating bins for
5153 * every possible blocksize found in the pool.
5154 */
5155 int bin = highbit64(BP_GET_PSIZE(bp)) - 1;
5156
5157 zcb->zcb_psize_count[bin]++;
5158 zcb->zcb_psize_len[bin] += BP_GET_PSIZE(bp);
5159 zcb->zcb_psize_total += BP_GET_PSIZE(bp);
5160
5161 bin = highbit64(BP_GET_LSIZE(bp)) - 1;
5162
5163 zcb->zcb_lsize_count[bin]++;
5164 zcb->zcb_lsize_len[bin] += BP_GET_LSIZE(bp);
5165 zcb->zcb_lsize_total += BP_GET_LSIZE(bp);
5166
5167 bin = highbit64(BP_GET_ASIZE(bp)) - 1;
5168
5169 zcb->zcb_asize_count[bin]++;
5170 zcb->zcb_asize_len[bin] += BP_GET_ASIZE(bp);
5171 zcb->zcb_asize_total += BP_GET_ASIZE(bp);
5172
5173 if (dump_opt['L'])
5174 return;
5175
5176 if (BP_GET_DEDUP(bp)) {
5177 ddt_t *ddt;
5178 ddt_entry_t *dde;
5179
5180 ddt = ddt_select(zcb->zcb_spa, bp);
5181 ddt_enter(ddt);
5182 dde = ddt_lookup(ddt, bp, B_FALSE);
5183
5184 if (dde == NULL) {
5185 refcnt = 0;
5186 } else {
5187 ddt_phys_t *ddp = ddt_phys_select(dde, bp);
5188 ddt_phys_decref(ddp);
5189 refcnt = ddp->ddp_refcnt;
5190 if (ddt_phys_total_refcnt(dde) == 0)
5191 ddt_remove(ddt, dde);
5192 }
5193 ddt_exit(ddt);
5194 }
5195
5196 VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
5197 refcnt ? 0 : spa_min_claim_txg(zcb->zcb_spa),
5198 bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
5199 }
5200
5201 static void
5202 zdb_blkptr_done(zio_t *zio)
5203 {
5204 spa_t *spa = zio->io_spa;
5205 blkptr_t *bp = zio->io_bp;
5206 int ioerr = zio->io_error;
5207 zdb_cb_t *zcb = zio->io_private;
5208 zbookmark_phys_t *zb = &zio->io_bookmark;
5209
5210 mutex_enter(&spa->spa_scrub_lock);
5211 spa->spa_load_verify_bytes -= BP_GET_PSIZE(bp);
5212 cv_broadcast(&spa->spa_scrub_io_cv);
5213
5214 if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
5215 char blkbuf[BP_SPRINTF_LEN];
5216
5217 zcb->zcb_haderrors = 1;
5218 zcb->zcb_errors[ioerr]++;
5219
5220 if (dump_opt['b'] >= 2)
5221 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5222 else
5223 blkbuf[0] = '\0';
5224
5225 (void) printf("zdb_blkptr_cb: "
5226 "Got error %d reading "
5227 "<%llu, %llu, %lld, %llx> %s -- skipping\n",
5228 ioerr,
5229 (u_longlong_t)zb->zb_objset,
5230 (u_longlong_t)zb->zb_object,
5231 (u_longlong_t)zb->zb_level,
5232 (u_longlong_t)zb->zb_blkid,
5233 blkbuf);
5234 }
5235 mutex_exit(&spa->spa_scrub_lock);
5236
5237 abd_free(zio->io_abd);
5238 }
5239
5240 static int
5241 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
5242 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
5243 {
5244 zdb_cb_t *zcb = arg;
5245 dmu_object_type_t type;
5246 boolean_t is_metadata;
5247
5248 if (zb->zb_level == ZB_DNODE_LEVEL)
5249 return (0);
5250
5251 if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
5252 char blkbuf[BP_SPRINTF_LEN];
5253 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5254 (void) printf("objset %llu object %llu "
5255 "level %lld offset 0x%llx %s\n",
5256 (u_longlong_t)zb->zb_objset,
5257 (u_longlong_t)zb->zb_object,
5258 (longlong_t)zb->zb_level,
5259 (u_longlong_t)blkid2offset(dnp, bp, zb),
5260 blkbuf);
5261 }
5262
5263 if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
5264 return (0);
5265
5266 type = BP_GET_TYPE(bp);
5267
5268 zdb_count_block(zcb, zilog, bp,
5269 (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
5270
5271 is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
5272
5273 if (!BP_IS_EMBEDDED(bp) &&
5274 (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
5275 size_t size = BP_GET_PSIZE(bp);
5276 abd_t *abd = abd_alloc(size, B_FALSE);
5277 int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
5278
5279 /* If it's an intent log block, failure is expected. */
5280 if (zb->zb_level == ZB_ZIL_LEVEL)
5281 flags |= ZIO_FLAG_SPECULATIVE;
5282
5283 mutex_enter(&spa->spa_scrub_lock);
5284 while (spa->spa_load_verify_bytes > max_inflight_bytes)
5285 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
5286 spa->spa_load_verify_bytes += size;
5287 mutex_exit(&spa->spa_scrub_lock);
5288
5289 zio_nowait(zio_read(NULL, spa, bp, abd, size,
5290 zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
5291 }
5292
5293 zcb->zcb_readfails = 0;
5294
5295 /* only call gethrtime() every 100 blocks */
5296 static int iters;
5297 if (++iters > 100)
5298 iters = 0;
5299 else
5300 return (0);
5301
5302 if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
5303 uint64_t now = gethrtime();
5304 char buf[10];
5305 uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
5306 int kb_per_sec =
5307 1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
5308 int sec_remaining =
5309 (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
5310
5311 /* make sure nicenum has enough space */
5312 CTASSERT(sizeof (buf) >= NN_NUMBUF_SZ);
5313
5314 zfs_nicebytes(bytes, buf, sizeof (buf));
5315 (void) fprintf(stderr,
5316 "\r%5s completed (%4dMB/s) "
5317 "estimated time remaining: %uhr %02umin %02usec ",
5318 buf, kb_per_sec / 1024,
5319 sec_remaining / 60 / 60,
5320 sec_remaining / 60 % 60,
5321 sec_remaining % 60);
5322
5323 zcb->zcb_lastprint = now;
5324 }
5325
5326 return (0);
5327 }
5328
5329 static void
5330 zdb_leak(void *arg, uint64_t start, uint64_t size)
5331 {
5332 vdev_t *vd = arg;
5333
5334 (void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
5335 (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
5336 }
5337
5338 static metaslab_ops_t zdb_metaslab_ops = {
5339 NULL /* alloc */
5340 };
5341
5342 /* ARGSUSED */
5343 static int
5344 load_unflushed_svr_segs_cb(spa_t *spa, space_map_entry_t *sme,
5345 uint64_t txg, void *arg)
5346 {
5347 spa_vdev_removal_t *svr = arg;
5348
5349 uint64_t offset = sme->sme_offset;
5350 uint64_t size = sme->sme_run;
5351
5352 /* skip vdevs we don't care about */
5353 if (sme->sme_vdev != svr->svr_vdev_id)
5354 return (0);
5355
5356 vdev_t *vd = vdev_lookup_top(spa, sme->sme_vdev);
5357 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5358 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5359
5360 if (txg < metaslab_unflushed_txg(ms))
5361 return (0);
5362
5363 if (sme->sme_type == SM_ALLOC)
5364 range_tree_add(svr->svr_allocd_segs, offset, size);
5365 else
5366 range_tree_remove(svr->svr_allocd_segs, offset, size);
5367
5368 return (0);
5369 }
5370
5371 /* ARGSUSED */
5372 static void
5373 claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5374 uint64_t size, void *arg)
5375 {
5376 /*
5377 * This callback was called through a remap from
5378 * a device being removed. Therefore, the vdev that
5379 * this callback is applied to is a concrete
5380 * vdev.
5381 */
5382 ASSERT(vdev_is_concrete(vd));
5383
5384 VERIFY0(metaslab_claim_impl(vd, offset, size,
5385 spa_min_claim_txg(vd->vdev_spa)));
5386 }
5387
5388 static void
5389 claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
5390 {
5391 vdev_t *vd = arg;
5392
5393 vdev_indirect_ops.vdev_op_remap(vd, offset, size,
5394 claim_segment_impl_cb, NULL);
5395 }
5396
5397 /*
5398 * After accounting for all allocated blocks that are directly referenced,
5399 * we might have missed a reference to a block from a partially complete
5400 * (and thus unused) indirect mapping object. We perform a secondary pass
5401 * through the metaslabs we have already mapped and claim the destination
5402 * blocks.
5403 */
5404 static void
5405 zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
5406 {
5407 if (dump_opt['L'])
5408 return;
5409
5410 if (spa->spa_vdev_removal == NULL)
5411 return;
5412
5413 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5414
5415 spa_vdev_removal_t *svr = spa->spa_vdev_removal;
5416 vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
5417 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5418
5419 ASSERT0(range_tree_space(svr->svr_allocd_segs));
5420
5421 range_tree_t *allocs = range_tree_create(NULL, RANGE_SEG64, NULL, 0, 0);
5422 for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
5423 metaslab_t *msp = vd->vdev_ms[msi];
5424
5425 ASSERT0(range_tree_space(allocs));
5426 if (msp->ms_sm != NULL)
5427 VERIFY0(space_map_load(msp->ms_sm, allocs, SM_ALLOC));
5428 range_tree_vacate(allocs, range_tree_add, svr->svr_allocd_segs);
5429 }
5430 range_tree_destroy(allocs);
5431
5432 iterate_through_spacemap_logs(spa, load_unflushed_svr_segs_cb, svr);
5433
5434 /*
5435 * Clear everything past what has been synced,
5436 * because we have not allocated mappings for
5437 * it yet.
5438 */
5439 range_tree_clear(svr->svr_allocd_segs,
5440 vdev_indirect_mapping_max_offset(vim),
5441 vd->vdev_asize - vdev_indirect_mapping_max_offset(vim));
5442
5443 zcb->zcb_removing_size += range_tree_space(svr->svr_allocd_segs);
5444 range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
5445
5446 spa_config_exit(spa, SCL_CONFIG, FTAG);
5447 }
5448
5449 /* ARGSUSED */
5450 static int
5451 increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
5452 dmu_tx_t *tx)
5453 {
5454 zdb_cb_t *zcb = arg;
5455 spa_t *spa = zcb->zcb_spa;
5456 vdev_t *vd;
5457 const dva_t *dva = &bp->blk_dva[0];
5458
5459 ASSERT(!bp_freed);
5460 ASSERT(!dump_opt['L']);
5461 ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
5462
5463 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
5464 vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
5465 ASSERT3P(vd, !=, NULL);
5466 spa_config_exit(spa, SCL_VDEV, FTAG);
5467
5468 ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
5469 ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
5470
5471 vdev_indirect_mapping_increment_obsolete_count(
5472 vd->vdev_indirect_mapping,
5473 DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
5474 zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
5475
5476 return (0);
5477 }
5478
5479 static uint32_t *
5480 zdb_load_obsolete_counts(vdev_t *vd)
5481 {
5482 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5483 spa_t *spa = vd->vdev_spa;
5484 spa_condensing_indirect_phys_t *scip =
5485 &spa->spa_condensing_indirect_phys;
5486 uint64_t obsolete_sm_object;
5487 uint32_t *counts;
5488
5489 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
5490 EQUIV(obsolete_sm_object != 0, vd->vdev_obsolete_sm != NULL);
5491 counts = vdev_indirect_mapping_load_obsolete_counts(vim);
5492 if (vd->vdev_obsolete_sm != NULL) {
5493 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
5494 vd->vdev_obsolete_sm);
5495 }
5496 if (scip->scip_vdev == vd->vdev_id &&
5497 scip->scip_prev_obsolete_sm_object != 0) {
5498 space_map_t *prev_obsolete_sm = NULL;
5499 VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
5500 scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
5501 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
5502 prev_obsolete_sm);
5503 space_map_close(prev_obsolete_sm);
5504 }
5505 return (counts);
5506 }
5507
5508 static void
5509 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
5510 {
5511 ddt_bookmark_t ddb;
5512 ddt_entry_t dde;
5513 int error;
5514 int p;
5515
5516 ASSERT(!dump_opt['L']);
5517
5518 bzero(&ddb, sizeof (ddb));
5519 while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
5520 blkptr_t blk;
5521 ddt_phys_t *ddp = dde.dde_phys;
5522
5523 if (ddb.ddb_class == DDT_CLASS_UNIQUE)
5524 return;
5525
5526 ASSERT(ddt_phys_total_refcnt(&dde) > 1);
5527
5528 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
5529 if (ddp->ddp_phys_birth == 0)
5530 continue;
5531 ddt_bp_create(ddb.ddb_checksum,
5532 &dde.dde_key, ddp, &blk);
5533 if (p == DDT_PHYS_DITTO) {
5534 zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
5535 } else {
5536 zcb->zcb_dedup_asize +=
5537 BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
5538 zcb->zcb_dedup_blocks++;
5539 }
5540 }
5541 ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
5542 ddt_enter(ddt);
5543 VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
5544 ddt_exit(ddt);
5545 }
5546
5547 ASSERT(error == ENOENT);
5548 }
5549
5550 typedef struct checkpoint_sm_exclude_entry_arg {
5551 vdev_t *cseea_vd;
5552 uint64_t cseea_checkpoint_size;
5553 } checkpoint_sm_exclude_entry_arg_t;
5554
5555 static int
5556 checkpoint_sm_exclude_entry_cb(space_map_entry_t *sme, void *arg)
5557 {
5558 checkpoint_sm_exclude_entry_arg_t *cseea = arg;
5559 vdev_t *vd = cseea->cseea_vd;
5560 metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
5561 uint64_t end = sme->sme_offset + sme->sme_run;
5562
5563 ASSERT(sme->sme_type == SM_FREE);
5564
5565 /*
5566 * Since the vdev_checkpoint_sm exists in the vdev level
5567 * and the ms_sm space maps exist in the metaslab level,
5568 * an entry in the checkpoint space map could theoretically
5569 * cross the boundaries of the metaslab that it belongs.
5570 *
5571 * In reality, because of the way that we populate and
5572 * manipulate the checkpoint's space maps currently,
5573 * there shouldn't be any entries that cross metaslabs.
5574 * Hence the assertion below.
5575 *
5576 * That said, there is no fundamental requirement that
5577 * the checkpoint's space map entries should not cross
5578 * metaslab boundaries. So if needed we could add code
5579 * that handles metaslab-crossing segments in the future.
5580 */
5581 VERIFY3U(sme->sme_offset, >=, ms->ms_start);
5582 VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
5583
5584 /*
5585 * By removing the entry from the allocated segments we
5586 * also verify that the entry is there to begin with.
5587 */
5588 mutex_enter(&ms->ms_lock);
5589 range_tree_remove(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
5590 mutex_exit(&ms->ms_lock);
5591
5592 cseea->cseea_checkpoint_size += sme->sme_run;
5593 return (0);
5594 }
5595
5596 static void
5597 zdb_leak_init_vdev_exclude_checkpoint(vdev_t *vd, zdb_cb_t *zcb)
5598 {
5599 spa_t *spa = vd->vdev_spa;
5600 space_map_t *checkpoint_sm = NULL;
5601 uint64_t checkpoint_sm_obj;
5602
5603 /*
5604 * If there is no vdev_top_zap, we are in a pool whose
5605 * version predates the pool checkpoint feature.
5606 */
5607 if (vd->vdev_top_zap == 0)
5608 return;
5609
5610 /*
5611 * If there is no reference of the vdev_checkpoint_sm in
5612 * the vdev_top_zap, then one of the following scenarios
5613 * is true:
5614 *
5615 * 1] There is no checkpoint
5616 * 2] There is a checkpoint, but no checkpointed blocks
5617 * have been freed yet
5618 * 3] The current vdev is indirect
5619 *
5620 * In these cases we return immediately.
5621 */
5622 if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
5623 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
5624 return;
5625
5626 VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
5627 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1,
5628 &checkpoint_sm_obj));
5629
5630 checkpoint_sm_exclude_entry_arg_t cseea;
5631 cseea.cseea_vd = vd;
5632 cseea.cseea_checkpoint_size = 0;
5633
5634 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
5635 checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
5636
5637 VERIFY0(space_map_iterate(checkpoint_sm,
5638 space_map_length(checkpoint_sm),
5639 checkpoint_sm_exclude_entry_cb, &cseea));
5640 space_map_close(checkpoint_sm);
5641
5642 zcb->zcb_checkpoint_size += cseea.cseea_checkpoint_size;
5643 }
5644
5645 static void
5646 zdb_leak_init_exclude_checkpoint(spa_t *spa, zdb_cb_t *zcb)
5647 {
5648 ASSERT(!dump_opt['L']);
5649
5650 vdev_t *rvd = spa->spa_root_vdev;
5651 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
5652 ASSERT3U(c, ==, rvd->vdev_child[c]->vdev_id);
5653 zdb_leak_init_vdev_exclude_checkpoint(rvd->vdev_child[c], zcb);
5654 }
5655 }
5656
5657 static int
5658 count_unflushed_space_cb(spa_t *spa, space_map_entry_t *sme,
5659 uint64_t txg, void *arg)
5660 {
5661 int64_t *ualloc_space = arg;
5662
5663 uint64_t offset = sme->sme_offset;
5664 uint64_t vdev_id = sme->sme_vdev;
5665
5666 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
5667 if (!vdev_is_concrete(vd))
5668 return (0);
5669
5670 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5671 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5672
5673 if (txg < metaslab_unflushed_txg(ms))
5674 return (0);
5675
5676 if (sme->sme_type == SM_ALLOC)
5677 *ualloc_space += sme->sme_run;
5678 else
5679 *ualloc_space -= sme->sme_run;
5680
5681 return (0);
5682 }
5683
5684 static int64_t
5685 get_unflushed_alloc_space(spa_t *spa)
5686 {
5687 if (dump_opt['L'])
5688 return (0);
5689
5690 int64_t ualloc_space = 0;
5691 iterate_through_spacemap_logs(spa, count_unflushed_space_cb,
5692 &ualloc_space);
5693 return (ualloc_space);
5694 }
5695
5696 static int
5697 load_unflushed_cb(spa_t *spa, space_map_entry_t *sme, uint64_t txg, void *arg)
5698 {
5699 maptype_t *uic_maptype = arg;
5700
5701 uint64_t offset = sme->sme_offset;
5702 uint64_t size = sme->sme_run;
5703 uint64_t vdev_id = sme->sme_vdev;
5704
5705 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
5706
5707 /* skip indirect vdevs */
5708 if (!vdev_is_concrete(vd))
5709 return (0);
5710
5711 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5712
5713 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5714 ASSERT(*uic_maptype == SM_ALLOC || *uic_maptype == SM_FREE);
5715
5716 if (txg < metaslab_unflushed_txg(ms))
5717 return (0);
5718
5719 if (*uic_maptype == sme->sme_type)
5720 range_tree_add(ms->ms_allocatable, offset, size);
5721 else
5722 range_tree_remove(ms->ms_allocatable, offset, size);
5723
5724 return (0);
5725 }
5726
5727 static void
5728 load_unflushed_to_ms_allocatables(spa_t *spa, maptype_t maptype)
5729 {
5730 iterate_through_spacemap_logs(spa, load_unflushed_cb, &maptype);
5731 }
5732
5733 static void
5734 load_concrete_ms_allocatable_trees(spa_t *spa, maptype_t maptype)
5735 {
5736 vdev_t *rvd = spa->spa_root_vdev;
5737 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
5738 vdev_t *vd = rvd->vdev_child[i];
5739
5740 ASSERT3U(i, ==, vd->vdev_id);
5741
5742 if (vd->vdev_ops == &vdev_indirect_ops)
5743 continue;
5744
5745 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
5746 metaslab_t *msp = vd->vdev_ms[m];
5747
5748 (void) fprintf(stderr,
5749 "\rloading concrete vdev %llu, "
5750 "metaslab %llu of %llu ...",
5751 (longlong_t)vd->vdev_id,
5752 (longlong_t)msp->ms_id,
5753 (longlong_t)vd->vdev_ms_count);
5754
5755 mutex_enter(&msp->ms_lock);
5756 range_tree_vacate(msp->ms_allocatable, NULL, NULL);
5757
5758 /*
5759 * We don't want to spend the CPU manipulating the
5760 * size-ordered tree, so clear the range_tree ops.
5761 */
5762 msp->ms_allocatable->rt_ops = NULL;
5763
5764 if (msp->ms_sm != NULL) {
5765 VERIFY0(space_map_load(msp->ms_sm,
5766 msp->ms_allocatable, maptype));
5767 }
5768 if (!msp->ms_loaded)
5769 msp->ms_loaded = B_TRUE;
5770 mutex_exit(&msp->ms_lock);
5771 }
5772 }
5773
5774 load_unflushed_to_ms_allocatables(spa, maptype);
5775 }
5776
5777 /*
5778 * vm_idxp is an in-out parameter which (for indirect vdevs) is the
5779 * index in vim_entries that has the first entry in this metaslab.
5780 * On return, it will be set to the first entry after this metaslab.
5781 */
5782 static void
5783 load_indirect_ms_allocatable_tree(vdev_t *vd, metaslab_t *msp,
5784 uint64_t *vim_idxp)
5785 {
5786 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5787
5788 mutex_enter(&msp->ms_lock);
5789 range_tree_vacate(msp->ms_allocatable, NULL, NULL);
5790
5791 /*
5792 * We don't want to spend the CPU manipulating the
5793 * size-ordered tree, so clear the range_tree ops.
5794 */
5795 msp->ms_allocatable->rt_ops = NULL;
5796
5797 for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
5798 (*vim_idxp)++) {
5799 vdev_indirect_mapping_entry_phys_t *vimep =
5800 &vim->vim_entries[*vim_idxp];
5801 uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
5802 uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
5803 ASSERT3U(ent_offset, >=, msp->ms_start);
5804 if (ent_offset >= msp->ms_start + msp->ms_size)
5805 break;
5806
5807 /*
5808 * Mappings do not cross metaslab boundaries,
5809 * because we create them by walking the metaslabs.
5810 */
5811 ASSERT3U(ent_offset + ent_len, <=,
5812 msp->ms_start + msp->ms_size);
5813 range_tree_add(msp->ms_allocatable, ent_offset, ent_len);
5814 }
5815
5816 if (!msp->ms_loaded)
5817 msp->ms_loaded = B_TRUE;
5818 mutex_exit(&msp->ms_lock);
5819 }
5820
5821 static void
5822 zdb_leak_init_prepare_indirect_vdevs(spa_t *spa, zdb_cb_t *zcb)
5823 {
5824 ASSERT(!dump_opt['L']);
5825
5826 vdev_t *rvd = spa->spa_root_vdev;
5827 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
5828 vdev_t *vd = rvd->vdev_child[c];
5829
5830 ASSERT3U(c, ==, vd->vdev_id);
5831
5832 if (vd->vdev_ops != &vdev_indirect_ops)
5833 continue;
5834
5835 /*
5836 * Note: we don't check for mapping leaks on
5837 * removing vdevs because their ms_allocatable's
5838 * are used to look for leaks in allocated space.
5839 */
5840 zcb->zcb_vd_obsolete_counts[c] = zdb_load_obsolete_counts(vd);
5841
5842 /*
5843 * Normally, indirect vdevs don't have any
5844 * metaslabs. We want to set them up for
5845 * zio_claim().
5846 */
5847 VERIFY0(vdev_metaslab_init(vd, 0));
5848
5849 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5850 uint64_t vim_idx = 0;
5851 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
5852
5853 (void) fprintf(stderr,
5854 "\rloading indirect vdev %llu, "
5855 "metaslab %llu of %llu ...",
5856 (longlong_t)vd->vdev_id,
5857 (longlong_t)vd->vdev_ms[m]->ms_id,
5858 (longlong_t)vd->vdev_ms_count);
5859
5860 load_indirect_ms_allocatable_tree(vd, vd->vdev_ms[m],
5861 &vim_idx);
5862 }
5863 ASSERT3U(vim_idx, ==, vdev_indirect_mapping_num_entries(vim));
5864 }
5865 }
5866
5867 static void
5868 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
5869 {
5870 zcb->zcb_spa = spa;
5871
5872 if (dump_opt['L'])
5873 return;
5874
5875 dsl_pool_t *dp = spa->spa_dsl_pool;
5876 vdev_t *rvd = spa->spa_root_vdev;
5877
5878 /*
5879 * We are going to be changing the meaning of the metaslab's
5880 * ms_allocatable. Ensure that the allocator doesn't try to
5881 * use the tree.
5882 */
5883 spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
5884 spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
5885
5886 zcb->zcb_vd_obsolete_counts =
5887 umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
5888 UMEM_NOFAIL);
5889
5890 /*
5891 * For leak detection, we overload the ms_allocatable trees
5892 * to contain allocated segments instead of free segments.
5893 * As a result, we can't use the normal metaslab_load/unload
5894 * interfaces.
5895 */
5896 zdb_leak_init_prepare_indirect_vdevs(spa, zcb);
5897 load_concrete_ms_allocatable_trees(spa, SM_ALLOC);
5898
5899 /*
5900 * On load_concrete_ms_allocatable_trees() we loaded all the
5901 * allocated entries from the ms_sm to the ms_allocatable for
5902 * each metaslab. If the pool has a checkpoint or is in the
5903 * middle of discarding a checkpoint, some of these blocks
5904 * may have been freed but their ms_sm may not have been
5905 * updated because they are referenced by the checkpoint. In
5906 * order to avoid false-positives during leak-detection, we
5907 * go through the vdev's checkpoint space map and exclude all
5908 * its entries from their relevant ms_allocatable.
5909 *
5910 * We also aggregate the space held by the checkpoint and add
5911 * it to zcb_checkpoint_size.
5912 *
5913 * Note that at this point we are also verifying that all the
5914 * entries on the checkpoint_sm are marked as allocated in
5915 * the ms_sm of their relevant metaslab.
5916 * [see comment in checkpoint_sm_exclude_entry_cb()]
5917 */
5918 zdb_leak_init_exclude_checkpoint(spa, zcb);
5919 ASSERT3U(zcb->zcb_checkpoint_size, ==, spa_get_checkpoint_space(spa));
5920
5921 /* for cleaner progress output */
5922 (void) fprintf(stderr, "\n");
5923
5924 if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
5925 ASSERT(spa_feature_is_enabled(spa,
5926 SPA_FEATURE_DEVICE_REMOVAL));
5927 (void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
5928 increment_indirect_mapping_cb, zcb, NULL);
5929 }
5930
5931 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5932 zdb_ddt_leak_init(spa, zcb);
5933 spa_config_exit(spa, SCL_CONFIG, FTAG);
5934 }
5935
5936 static boolean_t
5937 zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
5938 {
5939 boolean_t leaks = B_FALSE;
5940 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5941 uint64_t total_leaked = 0;
5942 boolean_t are_precise = B_FALSE;
5943
5944 ASSERT(vim != NULL);
5945
5946 for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
5947 vdev_indirect_mapping_entry_phys_t *vimep =
5948 &vim->vim_entries[i];
5949 uint64_t obsolete_bytes = 0;
5950 uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
5951 metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5952
5953 /*
5954 * This is not very efficient but it's easy to
5955 * verify correctness.
5956 */
5957 for (uint64_t inner_offset = 0;
5958 inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
5959 inner_offset += 1 << vd->vdev_ashift) {
5960 if (range_tree_contains(msp->ms_allocatable,
5961 offset + inner_offset, 1 << vd->vdev_ashift)) {
5962 obsolete_bytes += 1 << vd->vdev_ashift;
5963 }
5964 }
5965
5966 int64_t bytes_leaked = obsolete_bytes -
5967 zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
5968 ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
5969 zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
5970
5971 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
5972 if (bytes_leaked != 0 && (are_precise || dump_opt['d'] >= 5)) {
5973 (void) printf("obsolete indirect mapping count "
5974 "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
5975 (u_longlong_t)vd->vdev_id,
5976 (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
5977 (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
5978 (u_longlong_t)bytes_leaked);
5979 }
5980 total_leaked += ABS(bytes_leaked);
5981 }
5982
5983 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
5984 if (!are_precise && total_leaked > 0) {
5985 int pct_leaked = total_leaked * 100 /
5986 vdev_indirect_mapping_bytes_mapped(vim);
5987 (void) printf("cannot verify obsolete indirect mapping "
5988 "counts of vdev %llu because precise feature was not "
5989 "enabled when it was removed: %d%% (%llx bytes) of mapping"
5990 "unreferenced\n",
5991 (u_longlong_t)vd->vdev_id, pct_leaked,
5992 (u_longlong_t)total_leaked);
5993 } else if (total_leaked > 0) {
5994 (void) printf("obsolete indirect mapping count mismatch "
5995 "for vdev %llu -- %llx total bytes mismatched\n",
5996 (u_longlong_t)vd->vdev_id,
5997 (u_longlong_t)total_leaked);
5998 leaks |= B_TRUE;
5999 }
6000
6001 vdev_indirect_mapping_free_obsolete_counts(vim,
6002 zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
6003 zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
6004
6005 return (leaks);
6006 }
6007
6008 static boolean_t
6009 zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
6010 {
6011 if (dump_opt['L'])
6012 return (B_FALSE);
6013
6014 boolean_t leaks = B_FALSE;
6015 vdev_t *rvd = spa->spa_root_vdev;
6016 for (unsigned c = 0; c < rvd->vdev_children; c++) {
6017 vdev_t *vd = rvd->vdev_child[c];
6018 metaslab_group_t *mg __maybe_unused = vd->vdev_mg;
6019
6020 if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
6021 leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
6022 }
6023
6024 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6025 metaslab_t *msp = vd->vdev_ms[m];
6026 ASSERT3P(mg, ==, msp->ms_group);
6027
6028 /*
6029 * ms_allocatable has been overloaded
6030 * to contain allocated segments. Now that
6031 * we finished traversing all blocks, any
6032 * block that remains in the ms_allocatable
6033 * represents an allocated block that we
6034 * did not claim during the traversal.
6035 * Claimed blocks would have been removed
6036 * from the ms_allocatable. For indirect
6037 * vdevs, space remaining in the tree
6038 * represents parts of the mapping that are
6039 * not referenced, which is not a bug.
6040 */
6041 if (vd->vdev_ops == &vdev_indirect_ops) {
6042 range_tree_vacate(msp->ms_allocatable,
6043 NULL, NULL);
6044 } else {
6045 range_tree_vacate(msp->ms_allocatable,
6046 zdb_leak, vd);
6047 }
6048 if (msp->ms_loaded) {
6049 msp->ms_loaded = B_FALSE;
6050 }
6051 }
6052 }
6053
6054 umem_free(zcb->zcb_vd_obsolete_counts,
6055 rvd->vdev_children * sizeof (uint32_t *));
6056 zcb->zcb_vd_obsolete_counts = NULL;
6057
6058 return (leaks);
6059 }
6060
6061 /* ARGSUSED */
6062 static int
6063 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6064 {
6065 zdb_cb_t *zcb = arg;
6066
6067 if (dump_opt['b'] >= 5) {
6068 char blkbuf[BP_SPRINTF_LEN];
6069 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
6070 (void) printf("[%s] %s\n",
6071 "deferred free", blkbuf);
6072 }
6073 zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
6074 return (0);
6075 }
6076
6077 /*
6078 * Iterate over livelists which have been destroyed by the user but
6079 * are still present in the MOS, waiting to be freed
6080 */
6081 static void
6082 iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg)
6083 {
6084 objset_t *mos = spa->spa_meta_objset;
6085 uint64_t zap_obj;
6086 int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6087 DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6088 if (err == ENOENT)
6089 return;
6090 ASSERT0(err);
6091
6092 zap_cursor_t zc;
6093 zap_attribute_t attr;
6094 dsl_deadlist_t ll;
6095 /* NULL out os prior to dsl_deadlist_open in case it's garbage */
6096 ll.dl_os = NULL;
6097 for (zap_cursor_init(&zc, mos, zap_obj);
6098 zap_cursor_retrieve(&zc, &attr) == 0;
6099 (void) zap_cursor_advance(&zc)) {
6100 dsl_deadlist_open(&ll, mos, attr.za_first_integer);
6101 func(&ll, arg);
6102 dsl_deadlist_close(&ll);
6103 }
6104 zap_cursor_fini(&zc);
6105 }
6106
6107 static int
6108 bpobj_count_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
6109 dmu_tx_t *tx)
6110 {
6111 ASSERT(!bp_freed);
6112 return (count_block_cb(arg, bp, tx));
6113 }
6114
6115 static int
6116 livelist_entry_count_blocks_cb(void *args, dsl_deadlist_entry_t *dle)
6117 {
6118 zdb_cb_t *zbc = args;
6119 bplist_t blks;
6120 bplist_create(&blks);
6121 /* determine which blocks have been alloc'd but not freed */
6122 VERIFY0(dsl_process_sub_livelist(&dle->dle_bpobj, &blks, NULL, NULL));
6123 /* count those blocks */
6124 (void) bplist_iterate(&blks, count_block_cb, zbc, NULL);
6125 bplist_destroy(&blks);
6126 return (0);
6127 }
6128
6129 static void
6130 livelist_count_blocks(dsl_deadlist_t *ll, void *arg)
6131 {
6132 dsl_deadlist_iterate(ll, livelist_entry_count_blocks_cb, arg);
6133 }
6134
6135 /*
6136 * Count the blocks in the livelists that have been destroyed by the user
6137 * but haven't yet been freed.
6138 */
6139 static void
6140 deleted_livelists_count_blocks(spa_t *spa, zdb_cb_t *zbc)
6141 {
6142 iterate_deleted_livelists(spa, livelist_count_blocks, zbc);
6143 }
6144
6145 static void
6146 dump_livelist_cb(dsl_deadlist_t *ll, void *arg)
6147 {
6148 ASSERT3P(arg, ==, NULL);
6149 global_feature_count[SPA_FEATURE_LIVELIST]++;
6150 dump_blkptr_list(ll, "Deleted Livelist");
6151 dsl_deadlist_iterate(ll, sublivelist_verify_lightweight, NULL);
6152 }
6153
6154 /*
6155 * Print out, register object references to, and increment feature counts for
6156 * livelists that have been destroyed by the user but haven't yet been freed.
6157 */
6158 static void
6159 deleted_livelists_dump_mos(spa_t *spa)
6160 {
6161 uint64_t zap_obj;
6162 objset_t *mos = spa->spa_meta_objset;
6163 int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6164 DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6165 if (err == ENOENT)
6166 return;
6167 mos_obj_refd(zap_obj);
6168 iterate_deleted_livelists(spa, dump_livelist_cb, NULL);
6169 }
6170
6171 static int
6172 dump_block_stats(spa_t *spa)
6173 {
6174 zdb_cb_t zcb;
6175 zdb_blkstats_t *zb, *tzb;
6176 uint64_t norm_alloc, norm_space, total_alloc, total_found;
6177 int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
6178 TRAVERSE_NO_DECRYPT | TRAVERSE_HARD;
6179 boolean_t leaks = B_FALSE;
6180 int e, c, err;
6181 bp_embedded_type_t i;
6182
6183 bzero(&zcb, sizeof (zcb));
6184 (void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
6185 (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
6186 (dump_opt['c'] == 1) ? "metadata " : "",
6187 dump_opt['c'] ? "checksums " : "",
6188 (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
6189 !dump_opt['L'] ? "nothing leaked " : "");
6190
6191 /*
6192 * When leak detection is enabled we load all space maps as SM_ALLOC
6193 * maps, then traverse the pool claiming each block we discover. If
6194 * the pool is perfectly consistent, the segment trees will be empty
6195 * when we're done. Anything left over is a leak; any block we can't
6196 * claim (because it's not part of any space map) is a double
6197 * allocation, reference to a freed block, or an unclaimed log block.
6198 *
6199 * When leak detection is disabled (-L option) we still traverse the
6200 * pool claiming each block we discover, but we skip opening any space
6201 * maps.
6202 */
6203 bzero(&zcb, sizeof (zdb_cb_t));
6204 zdb_leak_init(spa, &zcb);
6205
6206 /*
6207 * If there's a deferred-free bplist, process that first.
6208 */
6209 (void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
6210 bpobj_count_block_cb, &zcb, NULL);
6211
6212 if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
6213 (void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
6214 bpobj_count_block_cb, &zcb, NULL);
6215 }
6216
6217 zdb_claim_removing(spa, &zcb);
6218
6219 if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
6220 VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
6221 spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
6222 &zcb, NULL));
6223 }
6224
6225 deleted_livelists_count_blocks(spa, &zcb);
6226
6227 if (dump_opt['c'] > 1)
6228 flags |= TRAVERSE_PREFETCH_DATA;
6229
6230 zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
6231 zcb.zcb_totalasize += metaslab_class_get_alloc(spa_special_class(spa));
6232 zcb.zcb_totalasize += metaslab_class_get_alloc(spa_dedup_class(spa));
6233 zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
6234 err = traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
6235
6236 /*
6237 * If we've traversed the data blocks then we need to wait for those
6238 * I/Os to complete. We leverage "The Godfather" zio to wait on
6239 * all async I/Os to complete.
6240 */
6241 if (dump_opt['c']) {
6242 for (c = 0; c < max_ncpus; c++) {
6243 (void) zio_wait(spa->spa_async_zio_root[c]);
6244 spa->spa_async_zio_root[c] = zio_root(spa, NULL, NULL,
6245 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
6246 ZIO_FLAG_GODFATHER);
6247 }
6248 }
6249 ASSERT0(spa->spa_load_verify_bytes);
6250
6251 /*
6252 * Done after zio_wait() since zcb_haderrors is modified in
6253 * zdb_blkptr_done()
6254 */
6255 zcb.zcb_haderrors |= err;
6256
6257 if (zcb.zcb_haderrors) {
6258 (void) printf("\nError counts:\n\n");
6259 (void) printf("\t%5s %s\n", "errno", "count");
6260 for (e = 0; e < 256; e++) {
6261 if (zcb.zcb_errors[e] != 0) {
6262 (void) printf("\t%5d %llu\n",
6263 e, (u_longlong_t)zcb.zcb_errors[e]);
6264 }
6265 }
6266 }
6267
6268 /*
6269 * Report any leaked segments.
6270 */
6271 leaks |= zdb_leak_fini(spa, &zcb);
6272
6273 tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
6274
6275 norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
6276 norm_space = metaslab_class_get_space(spa_normal_class(spa));
6277
6278 total_alloc = norm_alloc +
6279 metaslab_class_get_alloc(spa_log_class(spa)) +
6280 metaslab_class_get_alloc(spa_special_class(spa)) +
6281 metaslab_class_get_alloc(spa_dedup_class(spa)) +
6282 get_unflushed_alloc_space(spa);
6283 total_found = tzb->zb_asize - zcb.zcb_dedup_asize +
6284 zcb.zcb_removing_size + zcb.zcb_checkpoint_size;
6285
6286 if (total_found == total_alloc && !dump_opt['L']) {
6287 (void) printf("\n\tNo leaks (block sum matches space"
6288 " maps exactly)\n");
6289 } else if (!dump_opt['L']) {
6290 (void) printf("block traversal size %llu != alloc %llu "
6291 "(%s %lld)\n",
6292 (u_longlong_t)total_found,
6293 (u_longlong_t)total_alloc,
6294 (dump_opt['L']) ? "unreachable" : "leaked",
6295 (longlong_t)(total_alloc - total_found));
6296 leaks = B_TRUE;
6297 }
6298
6299 if (tzb->zb_count == 0)
6300 return (2);
6301
6302 (void) printf("\n");
6303 (void) printf("\t%-16s %14llu\n", "bp count:",
6304 (u_longlong_t)tzb->zb_count);
6305 (void) printf("\t%-16s %14llu\n", "ganged count:",
6306 (longlong_t)tzb->zb_gangs);
6307 (void) printf("\t%-16s %14llu avg: %6llu\n", "bp logical:",
6308 (u_longlong_t)tzb->zb_lsize,
6309 (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
6310 (void) printf("\t%-16s %14llu avg: %6llu compression: %6.2f\n",
6311 "bp physical:", (u_longlong_t)tzb->zb_psize,
6312 (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
6313 (double)tzb->zb_lsize / tzb->zb_psize);
6314 (void) printf("\t%-16s %14llu avg: %6llu compression: %6.2f\n",
6315 "bp allocated:", (u_longlong_t)tzb->zb_asize,
6316 (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
6317 (double)tzb->zb_lsize / tzb->zb_asize);
6318 (void) printf("\t%-16s %14llu ref>1: %6llu deduplication: %6.2f\n",
6319 "bp deduped:", (u_longlong_t)zcb.zcb_dedup_asize,
6320 (u_longlong_t)zcb.zcb_dedup_blocks,
6321 (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
6322 (void) printf("\t%-16s %14llu used: %5.2f%%\n", "Normal class:",
6323 (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
6324
6325 if (spa_special_class(spa)->mc_allocator[0].mca_rotor != NULL) {
6326 uint64_t alloc = metaslab_class_get_alloc(
6327 spa_special_class(spa));
6328 uint64_t space = metaslab_class_get_space(
6329 spa_special_class(spa));
6330
6331 (void) printf("\t%-16s %14llu used: %5.2f%%\n",
6332 "Special class", (u_longlong_t)alloc,
6333 100.0 * alloc / space);
6334 }
6335
6336 if (spa_dedup_class(spa)->mc_allocator[0].mca_rotor != NULL) {
6337 uint64_t alloc = metaslab_class_get_alloc(
6338 spa_dedup_class(spa));
6339 uint64_t space = metaslab_class_get_space(
6340 spa_dedup_class(spa));
6341
6342 (void) printf("\t%-16s %14llu used: %5.2f%%\n",
6343 "Dedup class", (u_longlong_t)alloc,
6344 100.0 * alloc / space);
6345 }
6346
6347 for (i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
6348 if (zcb.zcb_embedded_blocks[i] == 0)
6349 continue;
6350 (void) printf("\n");
6351 (void) printf("\tadditional, non-pointer bps of type %u: "
6352 "%10llu\n",
6353 i, (u_longlong_t)zcb.zcb_embedded_blocks[i]);
6354
6355 if (dump_opt['b'] >= 3) {
6356 (void) printf("\t number of (compressed) bytes: "
6357 "number of bps\n");
6358 dump_histogram(zcb.zcb_embedded_histogram[i],
6359 sizeof (zcb.zcb_embedded_histogram[i]) /
6360 sizeof (zcb.zcb_embedded_histogram[i][0]), 0);
6361 }
6362 }
6363
6364 if (tzb->zb_ditto_samevdev != 0) {
6365 (void) printf("\tDittoed blocks on same vdev: %llu\n",
6366 (longlong_t)tzb->zb_ditto_samevdev);
6367 }
6368 if (tzb->zb_ditto_same_ms != 0) {
6369 (void) printf("\tDittoed blocks in same metaslab: %llu\n",
6370 (longlong_t)tzb->zb_ditto_same_ms);
6371 }
6372
6373 for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
6374 vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
6375 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6376
6377 if (vim == NULL) {
6378 continue;
6379 }
6380
6381 char mem[32];
6382 zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
6383 mem, vdev_indirect_mapping_size(vim));
6384
6385 (void) printf("\tindirect vdev id %llu has %llu segments "
6386 "(%s in memory)\n",
6387 (longlong_t)vd->vdev_id,
6388 (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
6389 }
6390
6391 if (dump_opt['b'] >= 2) {
6392 int l, t, level;
6393 (void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
6394 "\t avg\t comp\t%%Total\tType\n");
6395
6396 for (t = 0; t <= ZDB_OT_TOTAL; t++) {
6397 char csize[32], lsize[32], psize[32], asize[32];
6398 char avg[32], gang[32];
6399 const char *typename;
6400
6401 /* make sure nicenum has enough space */
6402 CTASSERT(sizeof (csize) >= NN_NUMBUF_SZ);
6403 CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
6404 CTASSERT(sizeof (psize) >= NN_NUMBUF_SZ);
6405 CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
6406 CTASSERT(sizeof (avg) >= NN_NUMBUF_SZ);
6407 CTASSERT(sizeof (gang) >= NN_NUMBUF_SZ);
6408
6409 if (t < DMU_OT_NUMTYPES)
6410 typename = dmu_ot[t].ot_name;
6411 else
6412 typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
6413
6414 if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
6415 (void) printf("%6s\t%5s\t%5s\t%5s"
6416 "\t%5s\t%5s\t%6s\t%s\n",
6417 "-",
6418 "-",
6419 "-",
6420 "-",
6421 "-",
6422 "-",
6423 "-",
6424 typename);
6425 continue;
6426 }
6427
6428 for (l = ZB_TOTAL - 1; l >= -1; l--) {
6429 level = (l == -1 ? ZB_TOTAL : l);
6430 zb = &zcb.zcb_type[level][t];
6431
6432 if (zb->zb_asize == 0)
6433 continue;
6434
6435 if (dump_opt['b'] < 3 && level != ZB_TOTAL)
6436 continue;
6437
6438 if (level == 0 && zb->zb_asize ==
6439 zcb.zcb_type[ZB_TOTAL][t].zb_asize)
6440 continue;
6441
6442 zdb_nicenum(zb->zb_count, csize,
6443 sizeof (csize));
6444 zdb_nicenum(zb->zb_lsize, lsize,
6445 sizeof (lsize));
6446 zdb_nicenum(zb->zb_psize, psize,
6447 sizeof (psize));
6448 zdb_nicenum(zb->zb_asize, asize,
6449 sizeof (asize));
6450 zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
6451 sizeof (avg));
6452 zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
6453
6454 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
6455 "\t%5.2f\t%6.2f\t",
6456 csize, lsize, psize, asize, avg,
6457 (double)zb->zb_lsize / zb->zb_psize,
6458 100.0 * zb->zb_asize / tzb->zb_asize);
6459
6460 if (level == ZB_TOTAL)
6461 (void) printf("%s\n", typename);
6462 else
6463 (void) printf(" L%d %s\n",
6464 level, typename);
6465
6466 if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
6467 (void) printf("\t number of ganged "
6468 "blocks: %s\n", gang);
6469 }
6470
6471 if (dump_opt['b'] >= 4) {
6472 (void) printf("psize "
6473 "(in 512-byte sectors): "
6474 "number of blocks\n");
6475 dump_histogram(zb->zb_psize_histogram,
6476 PSIZE_HISTO_SIZE, 0);
6477 }
6478 }
6479 }
6480
6481 /* Output a table summarizing block sizes in the pool */
6482 if (dump_opt['b'] >= 2) {
6483 dump_size_histograms(&zcb);
6484 }
6485 }
6486
6487 (void) printf("\n");
6488
6489 if (leaks)
6490 return (2);
6491
6492 if (zcb.zcb_haderrors)
6493 return (3);
6494
6495 return (0);
6496 }
6497
6498 typedef struct zdb_ddt_entry {
6499 ddt_key_t zdde_key;
6500 uint64_t zdde_ref_blocks;
6501 uint64_t zdde_ref_lsize;
6502 uint64_t zdde_ref_psize;
6503 uint64_t zdde_ref_dsize;
6504 avl_node_t zdde_node;
6505 } zdb_ddt_entry_t;
6506
6507 /* ARGSUSED */
6508 static int
6509 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
6510 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
6511 {
6512 avl_tree_t *t = arg;
6513 avl_index_t where;
6514 zdb_ddt_entry_t *zdde, zdde_search;
6515
6516 if (zb->zb_level == ZB_DNODE_LEVEL || BP_IS_HOLE(bp) ||
6517 BP_IS_EMBEDDED(bp))
6518 return (0);
6519
6520 if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
6521 (void) printf("traversing objset %llu, %llu objects, "
6522 "%lu blocks so far\n",
6523 (u_longlong_t)zb->zb_objset,
6524 (u_longlong_t)BP_GET_FILL(bp),
6525 avl_numnodes(t));
6526 }
6527
6528 if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
6529 BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
6530 return (0);
6531
6532 ddt_key_fill(&zdde_search.zdde_key, bp);
6533
6534 zdde = avl_find(t, &zdde_search, &where);
6535
6536 if (zdde == NULL) {
6537 zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
6538 zdde->zdde_key = zdde_search.zdde_key;
6539 avl_insert(t, zdde, where);
6540 }
6541
6542 zdde->zdde_ref_blocks += 1;
6543 zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
6544 zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
6545 zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
6546
6547 return (0);
6548 }
6549
6550 static void
6551 dump_simulated_ddt(spa_t *spa)
6552 {
6553 avl_tree_t t;
6554 void *cookie = NULL;
6555 zdb_ddt_entry_t *zdde;
6556 ddt_histogram_t ddh_total;
6557 ddt_stat_t dds_total;
6558
6559 bzero(&ddh_total, sizeof (ddh_total));
6560 bzero(&dds_total, sizeof (dds_total));
6561 avl_create(&t, ddt_entry_compare,
6562 sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
6563
6564 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6565
6566 (void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
6567 TRAVERSE_NO_DECRYPT, zdb_ddt_add_cb, &t);
6568
6569 spa_config_exit(spa, SCL_CONFIG, FTAG);
6570
6571 while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
6572 ddt_stat_t dds;
6573 uint64_t refcnt = zdde->zdde_ref_blocks;
6574 ASSERT(refcnt != 0);
6575
6576 dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
6577 dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
6578 dds.dds_psize = zdde->zdde_ref_psize / refcnt;
6579 dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
6580
6581 dds.dds_ref_blocks = zdde->zdde_ref_blocks;
6582 dds.dds_ref_lsize = zdde->zdde_ref_lsize;
6583 dds.dds_ref_psize = zdde->zdde_ref_psize;
6584 dds.dds_ref_dsize = zdde->zdde_ref_dsize;
6585
6586 ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
6587 &dds, 0);
6588
6589 umem_free(zdde, sizeof (*zdde));
6590 }
6591
6592 avl_destroy(&t);
6593
6594 ddt_histogram_stat(&dds_total, &ddh_total);
6595
6596 (void) printf("Simulated DDT histogram:\n");
6597
6598 zpool_dump_ddt(&dds_total, &ddh_total);
6599
6600 dump_dedup_ratio(&dds_total);
6601 }
6602
6603 static int
6604 verify_device_removal_feature_counts(spa_t *spa)
6605 {
6606 uint64_t dr_feature_refcount = 0;
6607 uint64_t oc_feature_refcount = 0;
6608 uint64_t indirect_vdev_count = 0;
6609 uint64_t precise_vdev_count = 0;
6610 uint64_t obsolete_counts_object_count = 0;
6611 uint64_t obsolete_sm_count = 0;
6612 uint64_t obsolete_counts_count = 0;
6613 uint64_t scip_count = 0;
6614 uint64_t obsolete_bpobj_count = 0;
6615 int ret = 0;
6616
6617 spa_condensing_indirect_phys_t *scip =
6618 &spa->spa_condensing_indirect_phys;
6619 if (scip->scip_next_mapping_object != 0) {
6620 vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
6621 ASSERT(scip->scip_prev_obsolete_sm_object != 0);
6622 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
6623
6624 (void) printf("Condensing indirect vdev %llu: new mapping "
6625 "object %llu, prev obsolete sm %llu\n",
6626 (u_longlong_t)scip->scip_vdev,
6627 (u_longlong_t)scip->scip_next_mapping_object,
6628 (u_longlong_t)scip->scip_prev_obsolete_sm_object);
6629 if (scip->scip_prev_obsolete_sm_object != 0) {
6630 space_map_t *prev_obsolete_sm = NULL;
6631 VERIFY0(space_map_open(&prev_obsolete_sm,
6632 spa->spa_meta_objset,
6633 scip->scip_prev_obsolete_sm_object,
6634 0, vd->vdev_asize, 0));
6635 dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
6636 (void) printf("\n");
6637 space_map_close(prev_obsolete_sm);
6638 }
6639
6640 scip_count += 2;
6641 }
6642
6643 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
6644 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
6645 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
6646
6647 if (vic->vic_mapping_object != 0) {
6648 ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
6649 vd->vdev_removing);
6650 indirect_vdev_count++;
6651
6652 if (vd->vdev_indirect_mapping->vim_havecounts) {
6653 obsolete_counts_count++;
6654 }
6655 }
6656
6657 boolean_t are_precise;
6658 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6659 if (are_precise) {
6660 ASSERT(vic->vic_mapping_object != 0);
6661 precise_vdev_count++;
6662 }
6663
6664 uint64_t obsolete_sm_object;
6665 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
6666 if (obsolete_sm_object != 0) {
6667 ASSERT(vic->vic_mapping_object != 0);
6668 obsolete_sm_count++;
6669 }
6670 }
6671
6672 (void) feature_get_refcount(spa,
6673 &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
6674 &dr_feature_refcount);
6675 (void) feature_get_refcount(spa,
6676 &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
6677 &oc_feature_refcount);
6678
6679 if (dr_feature_refcount != indirect_vdev_count) {
6680 ret = 1;
6681 (void) printf("Number of indirect vdevs (%llu) " \
6682 "does not match feature count (%llu)\n",
6683 (u_longlong_t)indirect_vdev_count,
6684 (u_longlong_t)dr_feature_refcount);
6685 } else {
6686 (void) printf("Verified device_removal feature refcount " \
6687 "of %llu is correct\n",
6688 (u_longlong_t)dr_feature_refcount);
6689 }
6690
6691 if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
6692 DMU_POOL_OBSOLETE_BPOBJ) == 0) {
6693 obsolete_bpobj_count++;
6694 }
6695
6696
6697 obsolete_counts_object_count = precise_vdev_count;
6698 obsolete_counts_object_count += obsolete_sm_count;
6699 obsolete_counts_object_count += obsolete_counts_count;
6700 obsolete_counts_object_count += scip_count;
6701 obsolete_counts_object_count += obsolete_bpobj_count;
6702 obsolete_counts_object_count += remap_deadlist_count;
6703
6704 if (oc_feature_refcount != obsolete_counts_object_count) {
6705 ret = 1;
6706 (void) printf("Number of obsolete counts objects (%llu) " \
6707 "does not match feature count (%llu)\n",
6708 (u_longlong_t)obsolete_counts_object_count,
6709 (u_longlong_t)oc_feature_refcount);
6710 (void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
6711 "ob:%llu rd:%llu\n",
6712 (u_longlong_t)precise_vdev_count,
6713 (u_longlong_t)obsolete_sm_count,
6714 (u_longlong_t)obsolete_counts_count,
6715 (u_longlong_t)scip_count,
6716 (u_longlong_t)obsolete_bpobj_count,
6717 (u_longlong_t)remap_deadlist_count);
6718 } else {
6719 (void) printf("Verified indirect_refcount feature refcount " \
6720 "of %llu is correct\n",
6721 (u_longlong_t)oc_feature_refcount);
6722 }
6723 return (ret);
6724 }
6725
6726 static void
6727 zdb_set_skip_mmp(char *target)
6728 {
6729 spa_t *spa;
6730
6731 /*
6732 * Disable the activity check to allow examination of
6733 * active pools.
6734 */
6735 mutex_enter(&spa_namespace_lock);
6736 if ((spa = spa_lookup(target)) != NULL) {
6737 spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
6738 }
6739 mutex_exit(&spa_namespace_lock);
6740 }
6741
6742 #define BOGUS_SUFFIX "_CHECKPOINTED_UNIVERSE"
6743 /*
6744 * Import the checkpointed state of the pool specified by the target
6745 * parameter as readonly. The function also accepts a pool config
6746 * as an optional parameter, else it attempts to infer the config by
6747 * the name of the target pool.
6748 *
6749 * Note that the checkpointed state's pool name will be the name of
6750 * the original pool with the above suffix appended to it. In addition,
6751 * if the target is not a pool name (e.g. a path to a dataset) then
6752 * the new_path parameter is populated with the updated path to
6753 * reflect the fact that we are looking into the checkpointed state.
6754 *
6755 * The function returns a newly-allocated copy of the name of the
6756 * pool containing the checkpointed state. When this copy is no
6757 * longer needed it should be freed with free(3C). Same thing
6758 * applies to the new_path parameter if allocated.
6759 */
6760 static char *
6761 import_checkpointed_state(char *target, nvlist_t *cfg, char **new_path)
6762 {
6763 int error = 0;
6764 char *poolname, *bogus_name = NULL;
6765 boolean_t freecfg = B_FALSE;
6766
6767 /* If the target is not a pool, the extract the pool name */
6768 char *path_start = strchr(target, '/');
6769 if (path_start != NULL) {
6770 size_t poolname_len = path_start - target;
6771 poolname = strndup(target, poolname_len);
6772 } else {
6773 poolname = target;
6774 }
6775
6776 if (cfg == NULL) {
6777 zdb_set_skip_mmp(poolname);
6778 error = spa_get_stats(poolname, &cfg, NULL, 0);
6779 if (error != 0) {
6780 fatal("Tried to read config of pool \"%s\" but "
6781 "spa_get_stats() failed with error %d\n",
6782 poolname, error);
6783 }
6784 freecfg = B_TRUE;
6785 }
6786
6787 if (asprintf(&bogus_name, "%s%s", poolname, BOGUS_SUFFIX) == -1)
6788 return (NULL);
6789 fnvlist_add_string(cfg, ZPOOL_CONFIG_POOL_NAME, bogus_name);
6790
6791 error = spa_import(bogus_name, cfg, NULL,
6792 ZFS_IMPORT_MISSING_LOG | ZFS_IMPORT_CHECKPOINT |
6793 ZFS_IMPORT_SKIP_MMP);
6794 if (freecfg)
6795 nvlist_free(cfg);
6796 if (error != 0) {
6797 fatal("Tried to import pool \"%s\" but spa_import() failed "
6798 "with error %d\n", bogus_name, error);
6799 }
6800
6801 if (new_path != NULL && path_start != NULL) {
6802 if (asprintf(new_path, "%s%s", bogus_name, path_start) == -1) {
6803 if (path_start != NULL)
6804 free(poolname);
6805 return (NULL);
6806 }
6807 }
6808
6809 if (target != poolname)
6810 free(poolname);
6811
6812 return (bogus_name);
6813 }
6814
6815 typedef struct verify_checkpoint_sm_entry_cb_arg {
6816 vdev_t *vcsec_vd;
6817
6818 /* the following fields are only used for printing progress */
6819 uint64_t vcsec_entryid;
6820 uint64_t vcsec_num_entries;
6821 } verify_checkpoint_sm_entry_cb_arg_t;
6822
6823 #define ENTRIES_PER_PROGRESS_UPDATE 10000
6824
6825 static int
6826 verify_checkpoint_sm_entry_cb(space_map_entry_t *sme, void *arg)
6827 {
6828 verify_checkpoint_sm_entry_cb_arg_t *vcsec = arg;
6829 vdev_t *vd = vcsec->vcsec_vd;
6830 metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
6831 uint64_t end = sme->sme_offset + sme->sme_run;
6832
6833 ASSERT(sme->sme_type == SM_FREE);
6834
6835 if ((vcsec->vcsec_entryid % ENTRIES_PER_PROGRESS_UPDATE) == 0) {
6836 (void) fprintf(stderr,
6837 "\rverifying vdev %llu, space map entry %llu of %llu ...",
6838 (longlong_t)vd->vdev_id,
6839 (longlong_t)vcsec->vcsec_entryid,
6840 (longlong_t)vcsec->vcsec_num_entries);
6841 }
6842 vcsec->vcsec_entryid++;
6843
6844 /*
6845 * See comment in checkpoint_sm_exclude_entry_cb()
6846 */
6847 VERIFY3U(sme->sme_offset, >=, ms->ms_start);
6848 VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
6849
6850 /*
6851 * The entries in the vdev_checkpoint_sm should be marked as
6852 * allocated in the checkpointed state of the pool, therefore
6853 * their respective ms_allocateable trees should not contain them.
6854 */
6855 mutex_enter(&ms->ms_lock);
6856 range_tree_verify_not_present(ms->ms_allocatable,
6857 sme->sme_offset, sme->sme_run);
6858 mutex_exit(&ms->ms_lock);
6859
6860 return (0);
6861 }
6862
6863 /*
6864 * Verify that all segments in the vdev_checkpoint_sm are allocated
6865 * according to the checkpoint's ms_sm (i.e. are not in the checkpoint's
6866 * ms_allocatable).
6867 *
6868 * Do so by comparing the checkpoint space maps (vdev_checkpoint_sm) of
6869 * each vdev in the current state of the pool to the metaslab space maps
6870 * (ms_sm) of the checkpointed state of the pool.
6871 *
6872 * Note that the function changes the state of the ms_allocatable
6873 * trees of the current spa_t. The entries of these ms_allocatable
6874 * trees are cleared out and then repopulated from with the free
6875 * entries of their respective ms_sm space maps.
6876 */
6877 static void
6878 verify_checkpoint_vdev_spacemaps(spa_t *checkpoint, spa_t *current)
6879 {
6880 vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
6881 vdev_t *current_rvd = current->spa_root_vdev;
6882
6883 load_concrete_ms_allocatable_trees(checkpoint, SM_FREE);
6884
6885 for (uint64_t c = 0; c < ckpoint_rvd->vdev_children; c++) {
6886 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[c];
6887 vdev_t *current_vd = current_rvd->vdev_child[c];
6888
6889 space_map_t *checkpoint_sm = NULL;
6890 uint64_t checkpoint_sm_obj;
6891
6892 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
6893 /*
6894 * Since we don't allow device removal in a pool
6895 * that has a checkpoint, we expect that all removed
6896 * vdevs were removed from the pool before the
6897 * checkpoint.
6898 */
6899 ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
6900 continue;
6901 }
6902
6903 /*
6904 * If the checkpoint space map doesn't exist, then nothing
6905 * here is checkpointed so there's nothing to verify.
6906 */
6907 if (current_vd->vdev_top_zap == 0 ||
6908 zap_contains(spa_meta_objset(current),
6909 current_vd->vdev_top_zap,
6910 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
6911 continue;
6912
6913 VERIFY0(zap_lookup(spa_meta_objset(current),
6914 current_vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
6915 sizeof (uint64_t), 1, &checkpoint_sm_obj));
6916
6917 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(current),
6918 checkpoint_sm_obj, 0, current_vd->vdev_asize,
6919 current_vd->vdev_ashift));
6920
6921 verify_checkpoint_sm_entry_cb_arg_t vcsec;
6922 vcsec.vcsec_vd = ckpoint_vd;
6923 vcsec.vcsec_entryid = 0;
6924 vcsec.vcsec_num_entries =
6925 space_map_length(checkpoint_sm) / sizeof (uint64_t);
6926 VERIFY0(space_map_iterate(checkpoint_sm,
6927 space_map_length(checkpoint_sm),
6928 verify_checkpoint_sm_entry_cb, &vcsec));
6929 if (dump_opt['m'] > 3)
6930 dump_spacemap(current->spa_meta_objset, checkpoint_sm);
6931 space_map_close(checkpoint_sm);
6932 }
6933
6934 /*
6935 * If we've added vdevs since we took the checkpoint, ensure
6936 * that their checkpoint space maps are empty.
6937 */
6938 if (ckpoint_rvd->vdev_children < current_rvd->vdev_children) {
6939 for (uint64_t c = ckpoint_rvd->vdev_children;
6940 c < current_rvd->vdev_children; c++) {
6941 vdev_t *current_vd = current_rvd->vdev_child[c];
6942 ASSERT3P(current_vd->vdev_checkpoint_sm, ==, NULL);
6943 }
6944 }
6945
6946 /* for cleaner progress output */
6947 (void) fprintf(stderr, "\n");
6948 }
6949
6950 /*
6951 * Verifies that all space that's allocated in the checkpoint is
6952 * still allocated in the current version, by checking that everything
6953 * in checkpoint's ms_allocatable (which is actually allocated, not
6954 * allocatable/free) is not present in current's ms_allocatable.
6955 *
6956 * Note that the function changes the state of the ms_allocatable
6957 * trees of both spas when called. The entries of all ms_allocatable
6958 * trees are cleared out and then repopulated from their respective
6959 * ms_sm space maps. In the checkpointed state we load the allocated
6960 * entries, and in the current state we load the free entries.
6961 */
6962 static void
6963 verify_checkpoint_ms_spacemaps(spa_t *checkpoint, spa_t *current)
6964 {
6965 vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
6966 vdev_t *current_rvd = current->spa_root_vdev;
6967
6968 load_concrete_ms_allocatable_trees(checkpoint, SM_ALLOC);
6969 load_concrete_ms_allocatable_trees(current, SM_FREE);
6970
6971 for (uint64_t i = 0; i < ckpoint_rvd->vdev_children; i++) {
6972 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[i];
6973 vdev_t *current_vd = current_rvd->vdev_child[i];
6974
6975 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
6976 /*
6977 * See comment in verify_checkpoint_vdev_spacemaps()
6978 */
6979 ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
6980 continue;
6981 }
6982
6983 for (uint64_t m = 0; m < ckpoint_vd->vdev_ms_count; m++) {
6984 metaslab_t *ckpoint_msp = ckpoint_vd->vdev_ms[m];
6985 metaslab_t *current_msp = current_vd->vdev_ms[m];
6986
6987 (void) fprintf(stderr,
6988 "\rverifying vdev %llu of %llu, "
6989 "metaslab %llu of %llu ...",
6990 (longlong_t)current_vd->vdev_id,
6991 (longlong_t)current_rvd->vdev_children,
6992 (longlong_t)current_vd->vdev_ms[m]->ms_id,
6993 (longlong_t)current_vd->vdev_ms_count);
6994
6995 /*
6996 * We walk through the ms_allocatable trees that
6997 * are loaded with the allocated blocks from the
6998 * ms_sm spacemaps of the checkpoint. For each
6999 * one of these ranges we ensure that none of them
7000 * exists in the ms_allocatable trees of the
7001 * current state which are loaded with the ranges
7002 * that are currently free.
7003 *
7004 * This way we ensure that none of the blocks that
7005 * are part of the checkpoint were freed by mistake.
7006 */
7007 range_tree_walk(ckpoint_msp->ms_allocatable,
7008 (range_tree_func_t *)range_tree_verify_not_present,
7009 current_msp->ms_allocatable);
7010 }
7011 }
7012
7013 /* for cleaner progress output */
7014 (void) fprintf(stderr, "\n");
7015 }
7016
7017 static void
7018 verify_checkpoint_blocks(spa_t *spa)
7019 {
7020 ASSERT(!dump_opt['L']);
7021
7022 spa_t *checkpoint_spa;
7023 char *checkpoint_pool;
7024 int error = 0;
7025
7026 /*
7027 * We import the checkpointed state of the pool (under a different
7028 * name) so we can do verification on it against the current state
7029 * of the pool.
7030 */
7031 checkpoint_pool = import_checkpointed_state(spa->spa_name, NULL,
7032 NULL);
7033 ASSERT(strcmp(spa->spa_name, checkpoint_pool) != 0);
7034
7035 error = spa_open(checkpoint_pool, &checkpoint_spa, FTAG);
7036 if (error != 0) {
7037 fatal("Tried to open pool \"%s\" but spa_open() failed with "
7038 "error %d\n", checkpoint_pool, error);
7039 }
7040
7041 /*
7042 * Ensure that ranges in the checkpoint space maps of each vdev
7043 * are allocated according to the checkpointed state's metaslab
7044 * space maps.
7045 */
7046 verify_checkpoint_vdev_spacemaps(checkpoint_spa, spa);
7047
7048 /*
7049 * Ensure that allocated ranges in the checkpoint's metaslab
7050 * space maps remain allocated in the metaslab space maps of
7051 * the current state.
7052 */
7053 verify_checkpoint_ms_spacemaps(checkpoint_spa, spa);
7054
7055 /*
7056 * Once we are done, we get rid of the checkpointed state.
7057 */
7058 spa_close(checkpoint_spa, FTAG);
7059 free(checkpoint_pool);
7060 }
7061
7062 static void
7063 dump_leftover_checkpoint_blocks(spa_t *spa)
7064 {
7065 vdev_t *rvd = spa->spa_root_vdev;
7066
7067 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
7068 vdev_t *vd = rvd->vdev_child[i];
7069
7070 space_map_t *checkpoint_sm = NULL;
7071 uint64_t checkpoint_sm_obj;
7072
7073 if (vd->vdev_top_zap == 0)
7074 continue;
7075
7076 if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
7077 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
7078 continue;
7079
7080 VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
7081 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
7082 sizeof (uint64_t), 1, &checkpoint_sm_obj));
7083
7084 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
7085 checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
7086 dump_spacemap(spa->spa_meta_objset, checkpoint_sm);
7087 space_map_close(checkpoint_sm);
7088 }
7089 }
7090
7091 static int
7092 verify_checkpoint(spa_t *spa)
7093 {
7094 uberblock_t checkpoint;
7095 int error;
7096
7097 if (!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT))
7098 return (0);
7099
7100 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7101 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
7102 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
7103
7104 if (error == ENOENT && !dump_opt['L']) {
7105 /*
7106 * If the feature is active but the uberblock is missing
7107 * then we must be in the middle of discarding the
7108 * checkpoint.
7109 */
7110 (void) printf("\nPartially discarded checkpoint "
7111 "state found:\n");
7112 if (dump_opt['m'] > 3)
7113 dump_leftover_checkpoint_blocks(spa);
7114 return (0);
7115 } else if (error != 0) {
7116 (void) printf("lookup error %d when looking for "
7117 "checkpointed uberblock in MOS\n", error);
7118 return (error);
7119 }
7120 dump_uberblock(&checkpoint, "\nCheckpointed uberblock found:\n", "\n");
7121
7122 if (checkpoint.ub_checkpoint_txg == 0) {
7123 (void) printf("\nub_checkpoint_txg not set in checkpointed "
7124 "uberblock\n");
7125 error = 3;
7126 }
7127
7128 if (error == 0 && !dump_opt['L'])
7129 verify_checkpoint_blocks(spa);
7130
7131 return (error);
7132 }
7133
7134 /* ARGSUSED */
7135 static void
7136 mos_leaks_cb(void *arg, uint64_t start, uint64_t size)
7137 {
7138 for (uint64_t i = start; i < size; i++) {
7139 (void) printf("MOS object %llu referenced but not allocated\n",
7140 (u_longlong_t)i);
7141 }
7142 }
7143
7144 static void
7145 mos_obj_refd(uint64_t obj)
7146 {
7147 if (obj != 0 && mos_refd_objs != NULL)
7148 range_tree_add(mos_refd_objs, obj, 1);
7149 }
7150
7151 /*
7152 * Call on a MOS object that may already have been referenced.
7153 */
7154 static void
7155 mos_obj_refd_multiple(uint64_t obj)
7156 {
7157 if (obj != 0 && mos_refd_objs != NULL &&
7158 !range_tree_contains(mos_refd_objs, obj, 1))
7159 range_tree_add(mos_refd_objs, obj, 1);
7160 }
7161
7162 static void
7163 mos_leak_vdev_top_zap(vdev_t *vd)
7164 {
7165 uint64_t ms_flush_data_obj;
7166 int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
7167 vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
7168 sizeof (ms_flush_data_obj), 1, &ms_flush_data_obj);
7169 if (error == ENOENT)
7170 return;
7171 ASSERT0(error);
7172
7173 mos_obj_refd(ms_flush_data_obj);
7174 }
7175
7176 static void
7177 mos_leak_vdev(vdev_t *vd)
7178 {
7179 mos_obj_refd(vd->vdev_dtl_object);
7180 mos_obj_refd(vd->vdev_ms_array);
7181 mos_obj_refd(vd->vdev_indirect_config.vic_births_object);
7182 mos_obj_refd(vd->vdev_indirect_config.vic_mapping_object);
7183 mos_obj_refd(vd->vdev_leaf_zap);
7184 if (vd->vdev_checkpoint_sm != NULL)
7185 mos_obj_refd(vd->vdev_checkpoint_sm->sm_object);
7186 if (vd->vdev_indirect_mapping != NULL) {
7187 mos_obj_refd(vd->vdev_indirect_mapping->
7188 vim_phys->vimp_counts_object);
7189 }
7190 if (vd->vdev_obsolete_sm != NULL)
7191 mos_obj_refd(vd->vdev_obsolete_sm->sm_object);
7192
7193 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
7194 metaslab_t *ms = vd->vdev_ms[m];
7195 mos_obj_refd(space_map_object(ms->ms_sm));
7196 }
7197
7198 if (vd->vdev_top_zap != 0) {
7199 mos_obj_refd(vd->vdev_top_zap);
7200 mos_leak_vdev_top_zap(vd);
7201 }
7202
7203 for (uint64_t c = 0; c < vd->vdev_children; c++) {
7204 mos_leak_vdev(vd->vdev_child[c]);
7205 }
7206 }
7207
7208 static void
7209 mos_leak_log_spacemaps(spa_t *spa)
7210 {
7211 uint64_t spacemap_zap;
7212 int error = zap_lookup(spa_meta_objset(spa),
7213 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_LOG_SPACEMAP_ZAP,
7214 sizeof (spacemap_zap), 1, &spacemap_zap);
7215 if (error == ENOENT)
7216 return;
7217 ASSERT0(error);
7218
7219 mos_obj_refd(spacemap_zap);
7220 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
7221 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls))
7222 mos_obj_refd(sls->sls_sm_obj);
7223 }
7224
7225 static int
7226 dump_mos_leaks(spa_t *spa)
7227 {
7228 int rv = 0;
7229 objset_t *mos = spa->spa_meta_objset;
7230 dsl_pool_t *dp = spa->spa_dsl_pool;
7231
7232 /* Visit and mark all referenced objects in the MOS */
7233
7234 mos_obj_refd(DMU_POOL_DIRECTORY_OBJECT);
7235 mos_obj_refd(spa->spa_pool_props_object);
7236 mos_obj_refd(spa->spa_config_object);
7237 mos_obj_refd(spa->spa_ddt_stat_object);
7238 mos_obj_refd(spa->spa_feat_desc_obj);
7239 mos_obj_refd(spa->spa_feat_enabled_txg_obj);
7240 mos_obj_refd(spa->spa_feat_for_read_obj);
7241 mos_obj_refd(spa->spa_feat_for_write_obj);
7242 mos_obj_refd(spa->spa_history);
7243 mos_obj_refd(spa->spa_errlog_last);
7244 mos_obj_refd(spa->spa_errlog_scrub);
7245 mos_obj_refd(spa->spa_all_vdev_zaps);
7246 mos_obj_refd(spa->spa_dsl_pool->dp_bptree_obj);
7247 mos_obj_refd(spa->spa_dsl_pool->dp_tmp_userrefs_obj);
7248 mos_obj_refd(spa->spa_dsl_pool->dp_scan->scn_phys.scn_queue_obj);
7249 bpobj_count_refd(&spa->spa_deferred_bpobj);
7250 mos_obj_refd(dp->dp_empty_bpobj);
7251 bpobj_count_refd(&dp->dp_obsolete_bpobj);
7252 bpobj_count_refd(&dp->dp_free_bpobj);
7253 mos_obj_refd(spa->spa_l2cache.sav_object);
7254 mos_obj_refd(spa->spa_spares.sav_object);
7255
7256 if (spa->spa_syncing_log_sm != NULL)
7257 mos_obj_refd(spa->spa_syncing_log_sm->sm_object);
7258 mos_leak_log_spacemaps(spa);
7259
7260 mos_obj_refd(spa->spa_condensing_indirect_phys.
7261 scip_next_mapping_object);
7262 mos_obj_refd(spa->spa_condensing_indirect_phys.
7263 scip_prev_obsolete_sm_object);
7264 if (spa->spa_condensing_indirect_phys.scip_next_mapping_object != 0) {
7265 vdev_indirect_mapping_t *vim =
7266 vdev_indirect_mapping_open(mos,
7267 spa->spa_condensing_indirect_phys.scip_next_mapping_object);
7268 mos_obj_refd(vim->vim_phys->vimp_counts_object);
7269 vdev_indirect_mapping_close(vim);
7270 }
7271 deleted_livelists_dump_mos(spa);
7272
7273 if (dp->dp_origin_snap != NULL) {
7274 dsl_dataset_t *ds;
7275
7276 dsl_pool_config_enter(dp, FTAG);
7277 VERIFY0(dsl_dataset_hold_obj(dp,
7278 dsl_dataset_phys(dp->dp_origin_snap)->ds_next_snap_obj,
7279 FTAG, &ds));
7280 count_ds_mos_objects(ds);
7281 dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
7282 dsl_dataset_rele(ds, FTAG);
7283 dsl_pool_config_exit(dp, FTAG);
7284
7285 count_ds_mos_objects(dp->dp_origin_snap);
7286 dump_blkptr_list(&dp->dp_origin_snap->ds_deadlist, "Deadlist");
7287 }
7288 count_dir_mos_objects(dp->dp_mos_dir);
7289 if (dp->dp_free_dir != NULL)
7290 count_dir_mos_objects(dp->dp_free_dir);
7291 if (dp->dp_leak_dir != NULL)
7292 count_dir_mos_objects(dp->dp_leak_dir);
7293
7294 mos_leak_vdev(spa->spa_root_vdev);
7295
7296 for (uint64_t class = 0; class < DDT_CLASSES; class++) {
7297 for (uint64_t type = 0; type < DDT_TYPES; type++) {
7298 for (uint64_t cksum = 0;
7299 cksum < ZIO_CHECKSUM_FUNCTIONS; cksum++) {
7300 ddt_t *ddt = spa->spa_ddt[cksum];
7301 mos_obj_refd(ddt->ddt_object[type][class]);
7302 }
7303 }
7304 }
7305
7306 /*
7307 * Visit all allocated objects and make sure they are referenced.
7308 */
7309 uint64_t object = 0;
7310 while (dmu_object_next(mos, &object, B_FALSE, 0) == 0) {
7311 if (range_tree_contains(mos_refd_objs, object, 1)) {
7312 range_tree_remove(mos_refd_objs, object, 1);
7313 } else {
7314 dmu_object_info_t doi;
7315 const char *name;
7316 dmu_object_info(mos, object, &doi);
7317 if (doi.doi_type & DMU_OT_NEWTYPE) {
7318 dmu_object_byteswap_t bswap =
7319 DMU_OT_BYTESWAP(doi.doi_type);
7320 name = dmu_ot_byteswap[bswap].ob_name;
7321 } else {
7322 name = dmu_ot[doi.doi_type].ot_name;
7323 }
7324
7325 (void) printf("MOS object %llu (%s) leaked\n",
7326 (u_longlong_t)object, name);
7327 rv = 2;
7328 }
7329 }
7330 (void) range_tree_walk(mos_refd_objs, mos_leaks_cb, NULL);
7331 if (!range_tree_is_empty(mos_refd_objs))
7332 rv = 2;
7333 range_tree_vacate(mos_refd_objs, NULL, NULL);
7334 range_tree_destroy(mos_refd_objs);
7335 return (rv);
7336 }
7337
7338 typedef struct log_sm_obsolete_stats_arg {
7339 uint64_t lsos_current_txg;
7340
7341 uint64_t lsos_total_entries;
7342 uint64_t lsos_valid_entries;
7343
7344 uint64_t lsos_sm_entries;
7345 uint64_t lsos_valid_sm_entries;
7346 } log_sm_obsolete_stats_arg_t;
7347
7348 static int
7349 log_spacemap_obsolete_stats_cb(spa_t *spa, space_map_entry_t *sme,
7350 uint64_t txg, void *arg)
7351 {
7352 log_sm_obsolete_stats_arg_t *lsos = arg;
7353
7354 uint64_t offset = sme->sme_offset;
7355 uint64_t vdev_id = sme->sme_vdev;
7356
7357 if (lsos->lsos_current_txg == 0) {
7358 /* this is the first log */
7359 lsos->lsos_current_txg = txg;
7360 } else if (lsos->lsos_current_txg < txg) {
7361 /* we just changed log - print stats and reset */
7362 (void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
7363 (u_longlong_t)lsos->lsos_valid_sm_entries,
7364 (u_longlong_t)lsos->lsos_sm_entries,
7365 (u_longlong_t)lsos->lsos_current_txg);
7366 lsos->lsos_valid_sm_entries = 0;
7367 lsos->lsos_sm_entries = 0;
7368 lsos->lsos_current_txg = txg;
7369 }
7370 ASSERT3U(lsos->lsos_current_txg, ==, txg);
7371
7372 lsos->lsos_sm_entries++;
7373 lsos->lsos_total_entries++;
7374
7375 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
7376 if (!vdev_is_concrete(vd))
7377 return (0);
7378
7379 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
7380 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
7381
7382 if (txg < metaslab_unflushed_txg(ms))
7383 return (0);
7384 lsos->lsos_valid_sm_entries++;
7385 lsos->lsos_valid_entries++;
7386 return (0);
7387 }
7388
7389 static void
7390 dump_log_spacemap_obsolete_stats(spa_t *spa)
7391 {
7392 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
7393 return;
7394
7395 log_sm_obsolete_stats_arg_t lsos;
7396 bzero(&lsos, sizeof (lsos));
7397
7398 (void) printf("Log Space Map Obsolete Entry Statistics:\n");
7399
7400 iterate_through_spacemap_logs(spa,
7401 log_spacemap_obsolete_stats_cb, &lsos);
7402
7403 /* print stats for latest log */
7404 (void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
7405 (u_longlong_t)lsos.lsos_valid_sm_entries,
7406 (u_longlong_t)lsos.lsos_sm_entries,
7407 (u_longlong_t)lsos.lsos_current_txg);
7408
7409 (void) printf("%-8llu valid entries out of %-8llu - total\n\n",
7410 (u_longlong_t)lsos.lsos_valid_entries,
7411 (u_longlong_t)lsos.lsos_total_entries);
7412 }
7413
7414 static void
7415 dump_zpool(spa_t *spa)
7416 {
7417 dsl_pool_t *dp = spa_get_dsl(spa);
7418 int rc = 0;
7419
7420 if (dump_opt['y']) {
7421 livelist_metaslab_validate(spa);
7422 }
7423
7424 if (dump_opt['S']) {
7425 dump_simulated_ddt(spa);
7426 return;
7427 }
7428
7429 if (!dump_opt['e'] && dump_opt['C'] > 1) {
7430 (void) printf("\nCached configuration:\n");
7431 dump_nvlist(spa->spa_config, 8);
7432 }
7433
7434 if (dump_opt['C'])
7435 dump_config(spa);
7436
7437 if (dump_opt['u'])
7438 dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
7439
7440 if (dump_opt['D'])
7441 dump_all_ddts(spa);
7442
7443 if (dump_opt['d'] > 2 || dump_opt['m'])
7444 dump_metaslabs(spa);
7445 if (dump_opt['M'])
7446 dump_metaslab_groups(spa);
7447 if (dump_opt['d'] > 2 || dump_opt['m']) {
7448 dump_log_spacemaps(spa);
7449 dump_log_spacemap_obsolete_stats(spa);
7450 }
7451
7452 if (dump_opt['d'] || dump_opt['i']) {
7453 spa_feature_t f;
7454 mos_refd_objs = range_tree_create(NULL, RANGE_SEG64, NULL, 0,
7455 0);
7456 dump_objset(dp->dp_meta_objset);
7457
7458 if (dump_opt['d'] >= 3) {
7459 dsl_pool_t *dp = spa->spa_dsl_pool;
7460 dump_full_bpobj(&spa->spa_deferred_bpobj,
7461 "Deferred frees", 0);
7462 if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
7463 dump_full_bpobj(&dp->dp_free_bpobj,
7464 "Pool snapshot frees", 0);
7465 }
7466 if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
7467 ASSERT(spa_feature_is_enabled(spa,
7468 SPA_FEATURE_DEVICE_REMOVAL));
7469 dump_full_bpobj(&dp->dp_obsolete_bpobj,
7470 "Pool obsolete blocks", 0);
7471 }
7472
7473 if (spa_feature_is_active(spa,
7474 SPA_FEATURE_ASYNC_DESTROY)) {
7475 dump_bptree(spa->spa_meta_objset,
7476 dp->dp_bptree_obj,
7477 "Pool dataset frees");
7478 }
7479 dump_dtl(spa->spa_root_vdev, 0);
7480 }
7481
7482 for (spa_feature_t f = 0; f < SPA_FEATURES; f++)
7483 global_feature_count[f] = UINT64_MAX;
7484 global_feature_count[SPA_FEATURE_REDACTION_BOOKMARKS] = 0;
7485 global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN] = 0;
7486 global_feature_count[SPA_FEATURE_LIVELIST] = 0;
7487
7488 (void) dmu_objset_find(spa_name(spa), dump_one_objset,
7489 NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
7490
7491 if (rc == 0 && !dump_opt['L'])
7492 rc = dump_mos_leaks(spa);
7493
7494 for (f = 0; f < SPA_FEATURES; f++) {
7495 uint64_t refcount;
7496
7497 uint64_t *arr;
7498 if (!(spa_feature_table[f].fi_flags &
7499 ZFEATURE_FLAG_PER_DATASET)) {
7500 if (global_feature_count[f] == UINT64_MAX)
7501 continue;
7502 if (!spa_feature_is_enabled(spa, f)) {
7503 ASSERT0(global_feature_count[f]);
7504 continue;
7505 }
7506 arr = global_feature_count;
7507 } else {
7508 if (!spa_feature_is_enabled(spa, f)) {
7509 ASSERT0(dataset_feature_count[f]);
7510 continue;
7511 }
7512 arr = dataset_feature_count;
7513 }
7514 if (feature_get_refcount(spa, &spa_feature_table[f],
7515 &refcount) == ENOTSUP)
7516 continue;
7517 if (arr[f] != refcount) {
7518 (void) printf("%s feature refcount mismatch: "
7519 "%lld consumers != %lld refcount\n",
7520 spa_feature_table[f].fi_uname,
7521 (longlong_t)arr[f], (longlong_t)refcount);
7522 rc = 2;
7523 } else {
7524 (void) printf("Verified %s feature refcount "
7525 "of %llu is correct\n",
7526 spa_feature_table[f].fi_uname,
7527 (longlong_t)refcount);
7528 }
7529 }
7530
7531 if (rc == 0)
7532 rc = verify_device_removal_feature_counts(spa);
7533 }
7534
7535 if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
7536 rc = dump_block_stats(spa);
7537
7538 if (rc == 0)
7539 rc = verify_spacemap_refcounts(spa);
7540
7541 if (dump_opt['s'])
7542 show_pool_stats(spa);
7543
7544 if (dump_opt['h'])
7545 dump_history(spa);
7546
7547 if (rc == 0)
7548 rc = verify_checkpoint(spa);
7549
7550 if (rc != 0) {
7551 dump_debug_buffer();
7552 exit(rc);
7553 }
7554 }
7555
7556 #define ZDB_FLAG_CHECKSUM 0x0001
7557 #define ZDB_FLAG_DECOMPRESS 0x0002
7558 #define ZDB_FLAG_BSWAP 0x0004
7559 #define ZDB_FLAG_GBH 0x0008
7560 #define ZDB_FLAG_INDIRECT 0x0010
7561 #define ZDB_FLAG_RAW 0x0020
7562 #define ZDB_FLAG_PRINT_BLKPTR 0x0040
7563 #define ZDB_FLAG_VERBOSE 0x0080
7564
7565 static int flagbits[256];
7566 static char flagbitstr[16];
7567
7568 static void
7569 zdb_print_blkptr(const blkptr_t *bp, int flags)
7570 {
7571 char blkbuf[BP_SPRINTF_LEN];
7572
7573 if (flags & ZDB_FLAG_BSWAP)
7574 byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
7575
7576 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
7577 (void) printf("%s\n", blkbuf);
7578 }
7579
7580 static void
7581 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
7582 {
7583 int i;
7584
7585 for (i = 0; i < nbps; i++)
7586 zdb_print_blkptr(&bp[i], flags);
7587 }
7588
7589 static void
7590 zdb_dump_gbh(void *buf, int flags)
7591 {
7592 zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
7593 }
7594
7595 static void
7596 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
7597 {
7598 if (flags & ZDB_FLAG_BSWAP)
7599 byteswap_uint64_array(buf, size);
7600 VERIFY(write(fileno(stdout), buf, size) == size);
7601 }
7602
7603 static void
7604 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
7605 {
7606 uint64_t *d = (uint64_t *)buf;
7607 unsigned nwords = size / sizeof (uint64_t);
7608 int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
7609 unsigned i, j;
7610 const char *hdr;
7611 char *c;
7612
7613
7614 if (do_bswap)
7615 hdr = " 7 6 5 4 3 2 1 0 f e d c b a 9 8";
7616 else
7617 hdr = " 0 1 2 3 4 5 6 7 8 9 a b c d e f";
7618
7619 (void) printf("\n%s\n%6s %s 0123456789abcdef\n", label, "", hdr);
7620
7621 #ifdef _LITTLE_ENDIAN
7622 /* correct the endianness */
7623 do_bswap = !do_bswap;
7624 #endif
7625 for (i = 0; i < nwords; i += 2) {
7626 (void) printf("%06llx: %016llx %016llx ",
7627 (u_longlong_t)(i * sizeof (uint64_t)),
7628 (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
7629 (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
7630
7631 c = (char *)&d[i];
7632 for (j = 0; j < 2 * sizeof (uint64_t); j++)
7633 (void) printf("%c", isprint(c[j]) ? c[j] : '.');
7634 (void) printf("\n");
7635 }
7636 }
7637
7638 /*
7639 * There are two acceptable formats:
7640 * leaf_name - For example: c1t0d0 or /tmp/ztest.0a
7641 * child[.child]* - For example: 0.1.1
7642 *
7643 * The second form can be used to specify arbitrary vdevs anywhere
7644 * in the hierarchy. For example, in a pool with a mirror of
7645 * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
7646 */
7647 static vdev_t *
7648 zdb_vdev_lookup(vdev_t *vdev, const char *path)
7649 {
7650 char *s, *p, *q;
7651 unsigned i;
7652
7653 if (vdev == NULL)
7654 return (NULL);
7655
7656 /* First, assume the x.x.x.x format */
7657 i = strtoul(path, &s, 10);
7658 if (s == path || (s && *s != '.' && *s != '\0'))
7659 goto name;
7660 if (i >= vdev->vdev_children)
7661 return (NULL);
7662
7663 vdev = vdev->vdev_child[i];
7664 if (s && *s == '\0')
7665 return (vdev);
7666 return (zdb_vdev_lookup(vdev, s+1));
7667
7668 name:
7669 for (i = 0; i < vdev->vdev_children; i++) {
7670 vdev_t *vc = vdev->vdev_child[i];
7671
7672 if (vc->vdev_path == NULL) {
7673 vc = zdb_vdev_lookup(vc, path);
7674 if (vc == NULL)
7675 continue;
7676 else
7677 return (vc);
7678 }
7679
7680 p = strrchr(vc->vdev_path, '/');
7681 p = p ? p + 1 : vc->vdev_path;
7682 q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
7683
7684 if (strcmp(vc->vdev_path, path) == 0)
7685 return (vc);
7686 if (strcmp(p, path) == 0)
7687 return (vc);
7688 if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
7689 return (vc);
7690 }
7691
7692 return (NULL);
7693 }
7694
7695 static int
7696 name_from_objset_id(spa_t *spa, uint64_t objset_id, char *outstr)
7697 {
7698 dsl_dataset_t *ds;
7699
7700 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
7701 int error = dsl_dataset_hold_obj(spa->spa_dsl_pool, objset_id,
7702 NULL, &ds);
7703 if (error != 0) {
7704 (void) fprintf(stderr, "failed to hold objset %llu: %s\n",
7705 (u_longlong_t)objset_id, strerror(error));
7706 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
7707 return (error);
7708 }
7709 dsl_dataset_name(ds, outstr);
7710 dsl_dataset_rele(ds, NULL);
7711 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
7712 return (0);
7713 }
7714
7715 static boolean_t
7716 zdb_parse_block_sizes(char *sizes, uint64_t *lsize, uint64_t *psize)
7717 {
7718 char *s0, *s1;
7719
7720 if (sizes == NULL)
7721 return (B_FALSE);
7722
7723 s0 = strtok(sizes, "/");
7724 if (s0 == NULL)
7725 return (B_FALSE);
7726 s1 = strtok(NULL, "/");
7727 *lsize = strtoull(s0, NULL, 16);
7728 *psize = s1 ? strtoull(s1, NULL, 16) : *lsize;
7729 return (*lsize >= *psize && *psize > 0);
7730 }
7731
7732 #define ZIO_COMPRESS_MASK(alg) (1ULL << (ZIO_COMPRESS_##alg))
7733
7734 static boolean_t
7735 zdb_decompress_block(abd_t *pabd, void *buf, void *lbuf, uint64_t lsize,
7736 uint64_t psize, int flags)
7737 {
7738 boolean_t exceeded = B_FALSE;
7739 /*
7740 * We don't know how the data was compressed, so just try
7741 * every decompress function at every inflated blocksize.
7742 */
7743 void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
7744 int cfuncs[ZIO_COMPRESS_FUNCTIONS] = { 0 };
7745 int *cfuncp = cfuncs;
7746 uint64_t maxlsize = SPA_MAXBLOCKSIZE;
7747 uint64_t mask = ZIO_COMPRESS_MASK(ON) | ZIO_COMPRESS_MASK(OFF) |
7748 ZIO_COMPRESS_MASK(INHERIT) | ZIO_COMPRESS_MASK(EMPTY) |
7749 (getenv("ZDB_NO_ZLE") ? ZIO_COMPRESS_MASK(ZLE) : 0);
7750 *cfuncp++ = ZIO_COMPRESS_LZ4;
7751 *cfuncp++ = ZIO_COMPRESS_LZJB;
7752 mask |= ZIO_COMPRESS_MASK(LZ4) | ZIO_COMPRESS_MASK(LZJB);
7753 for (int c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++)
7754 if (((1ULL << c) & mask) == 0)
7755 *cfuncp++ = c;
7756
7757 /*
7758 * On the one hand, with SPA_MAXBLOCKSIZE at 16MB, this
7759 * could take a while and we should let the user know
7760 * we are not stuck. On the other hand, printing progress
7761 * info gets old after a while. User can specify 'v' flag
7762 * to see the progression.
7763 */
7764 if (lsize == psize)
7765 lsize += SPA_MINBLOCKSIZE;
7766 else
7767 maxlsize = lsize;
7768 for (; lsize <= maxlsize; lsize += SPA_MINBLOCKSIZE) {
7769 for (cfuncp = cfuncs; *cfuncp; cfuncp++) {
7770 if (flags & ZDB_FLAG_VERBOSE) {
7771 (void) fprintf(stderr,
7772 "Trying %05llx -> %05llx (%s)\n",
7773 (u_longlong_t)psize,
7774 (u_longlong_t)lsize,
7775 zio_compress_table[*cfuncp].\
7776 ci_name);
7777 }
7778
7779 /*
7780 * We randomize lbuf2, and decompress to both
7781 * lbuf and lbuf2. This way, we will know if
7782 * decompression fill exactly to lsize.
7783 */
7784 VERIFY0(random_get_pseudo_bytes(lbuf2, lsize));
7785
7786 if (zio_decompress_data(*cfuncp, pabd,
7787 lbuf, psize, lsize, NULL) == 0 &&
7788 zio_decompress_data(*cfuncp, pabd,
7789 lbuf2, psize, lsize, NULL) == 0 &&
7790 bcmp(lbuf, lbuf2, lsize) == 0)
7791 break;
7792 }
7793 if (*cfuncp != 0)
7794 break;
7795 }
7796 umem_free(lbuf2, SPA_MAXBLOCKSIZE);
7797
7798 if (lsize > maxlsize) {
7799 exceeded = B_TRUE;
7800 }
7801 buf = lbuf;
7802 if (*cfuncp == ZIO_COMPRESS_ZLE) {
7803 printf("\nZLE decompression was selected. If you "
7804 "suspect the results are wrong,\ntry avoiding ZLE "
7805 "by setting and exporting ZDB_NO_ZLE=\"true\"\n");
7806 }
7807
7808 return (exceeded);
7809 }
7810
7811 /*
7812 * Read a block from a pool and print it out. The syntax of the
7813 * block descriptor is:
7814 *
7815 * pool:vdev_specifier:offset:[lsize/]psize[:flags]
7816 *
7817 * pool - The name of the pool you wish to read from
7818 * vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
7819 * offset - offset, in hex, in bytes
7820 * size - Amount of data to read, in hex, in bytes
7821 * flags - A string of characters specifying options
7822 * b: Decode a blkptr at given offset within block
7823 * c: Calculate and display checksums
7824 * d: Decompress data before dumping
7825 * e: Byteswap data before dumping
7826 * g: Display data as a gang block header
7827 * i: Display as an indirect block
7828 * r: Dump raw data to stdout
7829 * v: Verbose
7830 *
7831 */
7832 static void
7833 zdb_read_block(char *thing, spa_t *spa)
7834 {
7835 blkptr_t blk, *bp = &blk;
7836 dva_t *dva = bp->blk_dva;
7837 int flags = 0;
7838 uint64_t offset = 0, psize = 0, lsize = 0, blkptr_offset = 0;
7839 zio_t *zio;
7840 vdev_t *vd;
7841 abd_t *pabd;
7842 void *lbuf, *buf;
7843 char *s, *p, *dup, *vdev, *flagstr, *sizes;
7844 int i, error;
7845 boolean_t borrowed = B_FALSE, found = B_FALSE;
7846
7847 dup = strdup(thing);
7848 s = strtok(dup, ":");
7849 vdev = s ? s : "";
7850 s = strtok(NULL, ":");
7851 offset = strtoull(s ? s : "", NULL, 16);
7852 sizes = strtok(NULL, ":");
7853 s = strtok(NULL, ":");
7854 flagstr = strdup(s ? s : "");
7855
7856 s = NULL;
7857 if (!zdb_parse_block_sizes(sizes, &lsize, &psize))
7858 s = "invalid size(s)";
7859 if (!IS_P2ALIGNED(psize, DEV_BSIZE) || !IS_P2ALIGNED(lsize, DEV_BSIZE))
7860 s = "size must be a multiple of sector size";
7861 if (!IS_P2ALIGNED(offset, DEV_BSIZE))
7862 s = "offset must be a multiple of sector size";
7863 if (s) {
7864 (void) printf("Invalid block specifier: %s - %s\n", thing, s);
7865 goto done;
7866 }
7867
7868 for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
7869 for (i = 0; i < strlen(flagstr); i++) {
7870 int bit = flagbits[(uchar_t)flagstr[i]];
7871
7872 if (bit == 0) {
7873 (void) printf("***Ignoring flag: %c\n",
7874 (uchar_t)flagstr[i]);
7875 continue;
7876 }
7877 found = B_TRUE;
7878 flags |= bit;
7879
7880 p = &flagstr[i + 1];
7881 if (*p != ':' && *p != '\0') {
7882 int j = 0, nextbit = flagbits[(uchar_t)*p];
7883 char *end, offstr[8] = { 0 };
7884 if ((bit == ZDB_FLAG_PRINT_BLKPTR) &&
7885 (nextbit == 0)) {
7886 /* look ahead to isolate the offset */
7887 while (nextbit == 0 &&
7888 strchr(flagbitstr, *p) == NULL) {
7889 offstr[j] = *p;
7890 j++;
7891 if (i + j > strlen(flagstr))
7892 break;
7893 p++;
7894 nextbit = flagbits[(uchar_t)*p];
7895 }
7896 blkptr_offset = strtoull(offstr, &end,
7897 16);
7898 i += j;
7899 } else if (nextbit == 0) {
7900 (void) printf("***Ignoring flag arg:"
7901 " '%c'\n", (uchar_t)*p);
7902 }
7903 }
7904 }
7905 }
7906 if (blkptr_offset % sizeof (blkptr_t)) {
7907 printf("Block pointer offset 0x%llx "
7908 "must be divisible by 0x%x\n",
7909 (longlong_t)blkptr_offset, (int)sizeof (blkptr_t));
7910 goto done;
7911 }
7912 if (found == B_FALSE && strlen(flagstr) > 0) {
7913 printf("Invalid flag arg: '%s'\n", flagstr);
7914 goto done;
7915 }
7916
7917 vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
7918 if (vd == NULL) {
7919 (void) printf("***Invalid vdev: %s\n", vdev);
7920 free(dup);
7921 return;
7922 } else {
7923 if (vd->vdev_path)
7924 (void) fprintf(stderr, "Found vdev: %s\n",
7925 vd->vdev_path);
7926 else
7927 (void) fprintf(stderr, "Found vdev type: %s\n",
7928 vd->vdev_ops->vdev_op_type);
7929 }
7930
7931 pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
7932 lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
7933
7934 BP_ZERO(bp);
7935
7936 DVA_SET_VDEV(&dva[0], vd->vdev_id);
7937 DVA_SET_OFFSET(&dva[0], offset);
7938 DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
7939 DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
7940
7941 BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
7942
7943 BP_SET_LSIZE(bp, lsize);
7944 BP_SET_PSIZE(bp, psize);
7945 BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
7946 BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
7947 BP_SET_TYPE(bp, DMU_OT_NONE);
7948 BP_SET_LEVEL(bp, 0);
7949 BP_SET_DEDUP(bp, 0);
7950 BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
7951
7952 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7953 zio = zio_root(spa, NULL, NULL, 0);
7954
7955 if (vd == vd->vdev_top) {
7956 /*
7957 * Treat this as a normal block read.
7958 */
7959 zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
7960 ZIO_PRIORITY_SYNC_READ,
7961 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
7962 } else {
7963 /*
7964 * Treat this as a vdev child I/O.
7965 */
7966 zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
7967 psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
7968 ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_PROPAGATE |
7969 ZIO_FLAG_DONT_RETRY | ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
7970 ZIO_FLAG_OPTIONAL, NULL, NULL));
7971 }
7972
7973 error = zio_wait(zio);
7974 spa_config_exit(spa, SCL_STATE, FTAG);
7975
7976 if (error) {
7977 (void) printf("Read of %s failed, error: %d\n", thing, error);
7978 goto out;
7979 }
7980
7981 uint64_t orig_lsize = lsize;
7982 buf = lbuf;
7983 if (flags & ZDB_FLAG_DECOMPRESS) {
7984 boolean_t failed = zdb_decompress_block(pabd, buf, lbuf,
7985 lsize, psize, flags);
7986 if (failed) {
7987 (void) printf("Decompress of %s failed\n", thing);
7988 goto out;
7989 }
7990 } else {
7991 buf = abd_borrow_buf_copy(pabd, lsize);
7992 borrowed = B_TRUE;
7993 }
7994 /*
7995 * Try to detect invalid block pointer. If invalid, try
7996 * decompressing.
7997 */
7998 if ((flags & ZDB_FLAG_PRINT_BLKPTR || flags & ZDB_FLAG_INDIRECT) &&
7999 !(flags & ZDB_FLAG_DECOMPRESS)) {
8000 const blkptr_t *b = (const blkptr_t *)(void *)
8001 ((uintptr_t)buf + (uintptr_t)blkptr_offset);
8002 if (zfs_blkptr_verify(spa, b, B_FALSE, BLK_VERIFY_ONLY) ==
8003 B_FALSE) {
8004 abd_return_buf_copy(pabd, buf, lsize);
8005 borrowed = B_FALSE;
8006 buf = lbuf;
8007 boolean_t failed = zdb_decompress_block(pabd, buf,
8008 lbuf, lsize, psize, flags);
8009 b = (const blkptr_t *)(void *)
8010 ((uintptr_t)buf + (uintptr_t)blkptr_offset);
8011 if (failed || zfs_blkptr_verify(spa, b, B_FALSE,
8012 BLK_VERIFY_LOG) == B_FALSE) {
8013 printf("invalid block pointer at this DVA\n");
8014 goto out;
8015 }
8016 }
8017 }
8018
8019 if (flags & ZDB_FLAG_PRINT_BLKPTR)
8020 zdb_print_blkptr((blkptr_t *)(void *)
8021 ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
8022 else if (flags & ZDB_FLAG_RAW)
8023 zdb_dump_block_raw(buf, lsize, flags);
8024 else if (flags & ZDB_FLAG_INDIRECT)
8025 zdb_dump_indirect((blkptr_t *)buf,
8026 orig_lsize / sizeof (blkptr_t), flags);
8027 else if (flags & ZDB_FLAG_GBH)
8028 zdb_dump_gbh(buf, flags);
8029 else
8030 zdb_dump_block(thing, buf, lsize, flags);
8031
8032 /*
8033 * If :c was specified, iterate through the checksum table to
8034 * calculate and display each checksum for our specified
8035 * DVA and length.
8036 */
8037 if ((flags & ZDB_FLAG_CHECKSUM) && !(flags & ZDB_FLAG_RAW) &&
8038 !(flags & ZDB_FLAG_GBH)) {
8039 zio_t *czio;
8040 (void) printf("\n");
8041 for (enum zio_checksum ck = ZIO_CHECKSUM_LABEL;
8042 ck < ZIO_CHECKSUM_FUNCTIONS; ck++) {
8043
8044 if ((zio_checksum_table[ck].ci_flags &
8045 ZCHECKSUM_FLAG_EMBEDDED) ||
8046 ck == ZIO_CHECKSUM_NOPARITY) {
8047 continue;
8048 }
8049 BP_SET_CHECKSUM(bp, ck);
8050 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8051 czio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
8052 czio->io_bp = bp;
8053
8054 if (vd == vd->vdev_top) {
8055 zio_nowait(zio_read(czio, spa, bp, pabd, psize,
8056 NULL, NULL,
8057 ZIO_PRIORITY_SYNC_READ,
8058 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8059 ZIO_FLAG_DONT_RETRY, NULL));
8060 } else {
8061 zio_nowait(zio_vdev_child_io(czio, bp, vd,
8062 offset, pabd, psize, ZIO_TYPE_READ,
8063 ZIO_PRIORITY_SYNC_READ,
8064 ZIO_FLAG_DONT_CACHE |
8065 ZIO_FLAG_DONT_PROPAGATE |
8066 ZIO_FLAG_DONT_RETRY |
8067 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8068 ZIO_FLAG_SPECULATIVE |
8069 ZIO_FLAG_OPTIONAL, NULL, NULL));
8070 }
8071 error = zio_wait(czio);
8072 if (error == 0 || error == ECKSUM) {
8073 zio_t *ck_zio = zio_root(spa, NULL, NULL, 0);
8074 ck_zio->io_offset =
8075 DVA_GET_OFFSET(&bp->blk_dva[0]);
8076 ck_zio->io_bp = bp;
8077 zio_checksum_compute(ck_zio, ck, pabd, lsize);
8078 printf("%12s\tcksum=%llx:%llx:%llx:%llx\n",
8079 zio_checksum_table[ck].ci_name,
8080 (u_longlong_t)bp->blk_cksum.zc_word[0],
8081 (u_longlong_t)bp->blk_cksum.zc_word[1],
8082 (u_longlong_t)bp->blk_cksum.zc_word[2],
8083 (u_longlong_t)bp->blk_cksum.zc_word[3]);
8084 zio_wait(ck_zio);
8085 } else {
8086 printf("error %d reading block\n", error);
8087 }
8088 spa_config_exit(spa, SCL_STATE, FTAG);
8089 }
8090 }
8091
8092 if (borrowed)
8093 abd_return_buf_copy(pabd, buf, lsize);
8094
8095 out:
8096 abd_free(pabd);
8097 umem_free(lbuf, SPA_MAXBLOCKSIZE);
8098 done:
8099 free(flagstr);
8100 free(dup);
8101 }
8102
8103 static void
8104 zdb_embedded_block(char *thing)
8105 {
8106 blkptr_t bp;
8107 unsigned long long *words = (void *)&bp;
8108 char *buf;
8109 int err;
8110
8111 bzero(&bp, sizeof (bp));
8112 err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
8113 "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
8114 words + 0, words + 1, words + 2, words + 3,
8115 words + 4, words + 5, words + 6, words + 7,
8116 words + 8, words + 9, words + 10, words + 11,
8117 words + 12, words + 13, words + 14, words + 15);
8118 if (err != 16) {
8119 (void) fprintf(stderr, "invalid input format\n");
8120 exit(1);
8121 }
8122 ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
8123 buf = malloc(SPA_MAXBLOCKSIZE);
8124 if (buf == NULL) {
8125 (void) fprintf(stderr, "out of memory\n");
8126 exit(1);
8127 }
8128 err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
8129 if (err != 0) {
8130 (void) fprintf(stderr, "decode failed: %u\n", err);
8131 exit(1);
8132 }
8133 zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
8134 free(buf);
8135 }
8136
8137 int
8138 main(int argc, char **argv)
8139 {
8140 int c;
8141 struct rlimit rl = { 1024, 1024 };
8142 spa_t *spa = NULL;
8143 objset_t *os = NULL;
8144 int dump_all = 1;
8145 int verbose = 0;
8146 int error = 0;
8147 char **searchdirs = NULL;
8148 int nsearch = 0;
8149 char *target, *target_pool, dsname[ZFS_MAX_DATASET_NAME_LEN];
8150 nvlist_t *policy = NULL;
8151 uint64_t max_txg = UINT64_MAX;
8152 int64_t objset_id = -1;
8153 int flags = ZFS_IMPORT_MISSING_LOG;
8154 int rewind = ZPOOL_NEVER_REWIND;
8155 char *spa_config_path_env, *objset_str;
8156 boolean_t target_is_spa = B_TRUE, dataset_lookup = B_FALSE;
8157 nvlist_t *cfg = NULL;
8158
8159 (void) setrlimit(RLIMIT_NOFILE, &rl);
8160 (void) enable_extended_FILE_stdio(-1, -1);
8161
8162 dprintf_setup(&argc, argv);
8163
8164 /*
8165 * If there is an environment variable SPA_CONFIG_PATH it overrides
8166 * default spa_config_path setting. If -U flag is specified it will
8167 * override this environment variable settings once again.
8168 */
8169 spa_config_path_env = getenv("SPA_CONFIG_PATH");
8170 if (spa_config_path_env != NULL)
8171 spa_config_path = spa_config_path_env;
8172
8173 /*
8174 * For performance reasons, we set this tunable down. We do so before
8175 * the arg parsing section so that the user can override this value if
8176 * they choose.
8177 */
8178 zfs_btree_verify_intensity = 3;
8179
8180 while ((c = getopt(argc, argv,
8181 "AbcCdDeEFGhiI:klLmMo:Op:PqRsSt:uU:vVx:XYyZ")) != -1) {
8182 switch (c) {
8183 case 'b':
8184 case 'c':
8185 case 'C':
8186 case 'd':
8187 case 'D':
8188 case 'E':
8189 case 'G':
8190 case 'h':
8191 case 'i':
8192 case 'l':
8193 case 'm':
8194 case 'M':
8195 case 'O':
8196 case 'R':
8197 case 's':
8198 case 'S':
8199 case 'u':
8200 case 'y':
8201 case 'Z':
8202 dump_opt[c]++;
8203 dump_all = 0;
8204 break;
8205 case 'A':
8206 case 'e':
8207 case 'F':
8208 case 'k':
8209 case 'L':
8210 case 'P':
8211 case 'q':
8212 case 'X':
8213 dump_opt[c]++;
8214 break;
8215 case 'Y':
8216 zfs_reconstruct_indirect_combinations_max = INT_MAX;
8217 zfs_deadman_enabled = 0;
8218 break;
8219 /* NB: Sort single match options below. */
8220 case 'I':
8221 max_inflight_bytes = strtoull(optarg, NULL, 0);
8222 if (max_inflight_bytes == 0) {
8223 (void) fprintf(stderr, "maximum number "
8224 "of inflight bytes must be greater "
8225 "than 0\n");
8226 usage();
8227 }
8228 break;
8229 case 'o':
8230 error = set_global_var(optarg);
8231 if (error != 0)
8232 usage();
8233 break;
8234 case 'p':
8235 if (searchdirs == NULL) {
8236 searchdirs = umem_alloc(sizeof (char *),
8237 UMEM_NOFAIL);
8238 } else {
8239 char **tmp = umem_alloc((nsearch + 1) *
8240 sizeof (char *), UMEM_NOFAIL);
8241 bcopy(searchdirs, tmp, nsearch *
8242 sizeof (char *));
8243 umem_free(searchdirs,
8244 nsearch * sizeof (char *));
8245 searchdirs = tmp;
8246 }
8247 searchdirs[nsearch++] = optarg;
8248 break;
8249 case 't':
8250 max_txg = strtoull(optarg, NULL, 0);
8251 if (max_txg < TXG_INITIAL) {
8252 (void) fprintf(stderr, "incorrect txg "
8253 "specified: %s\n", optarg);
8254 usage();
8255 }
8256 break;
8257 case 'U':
8258 spa_config_path = optarg;
8259 if (spa_config_path[0] != '/') {
8260 (void) fprintf(stderr,
8261 "cachefile must be an absolute path "
8262 "(i.e. start with a slash)\n");
8263 usage();
8264 }
8265 break;
8266 case 'v':
8267 verbose++;
8268 break;
8269 case 'V':
8270 flags = ZFS_IMPORT_VERBATIM;
8271 break;
8272 case 'x':
8273 vn_dumpdir = optarg;
8274 break;
8275 default:
8276 usage();
8277 break;
8278 }
8279 }
8280
8281 if (!dump_opt['e'] && searchdirs != NULL) {
8282 (void) fprintf(stderr, "-p option requires use of -e\n");
8283 usage();
8284 }
8285 if (dump_opt['d']) {
8286 /* <pool>[/<dataset | objset id> is accepted */
8287 if (argv[2] && (objset_str = strchr(argv[2], '/')) != NULL &&
8288 objset_str++ != NULL) {
8289 char *endptr;
8290 errno = 0;
8291 objset_id = strtoull(objset_str, &endptr, 0);
8292 /* dataset 0 is the same as opening the pool */
8293 if (errno == 0 && endptr != objset_str &&
8294 objset_id != 0) {
8295 target_is_spa = B_FALSE;
8296 dataset_lookup = B_TRUE;
8297 } else if (objset_id != 0) {
8298 printf("failed to open objset %s "
8299 "%llu %s", objset_str,
8300 (u_longlong_t)objset_id,
8301 strerror(errno));
8302 exit(1);
8303 }
8304 /* normal dataset name not an objset ID */
8305 if (endptr == objset_str) {
8306 objset_id = -1;
8307 }
8308 }
8309 }
8310
8311 #if defined(_LP64)
8312 /*
8313 * ZDB does not typically re-read blocks; therefore limit the ARC
8314 * to 256 MB, which can be used entirely for metadata.
8315 */
8316 zfs_arc_min = zfs_arc_meta_min = 2ULL << SPA_MAXBLOCKSHIFT;
8317 zfs_arc_max = zfs_arc_meta_limit = 256 * 1024 * 1024;
8318 #endif
8319
8320 /*
8321 * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
8322 * "zdb -b" uses traversal prefetch which uses async reads.
8323 * For good performance, let several of them be active at once.
8324 */
8325 zfs_vdev_async_read_max_active = 10;
8326
8327 /*
8328 * Disable reference tracking for better performance.
8329 */
8330 reference_tracking_enable = B_FALSE;
8331
8332 /*
8333 * Do not fail spa_load when spa_load_verify fails. This is needed
8334 * to load non-idle pools.
8335 */
8336 spa_load_verify_dryrun = B_TRUE;
8337
8338 kernel_init(SPA_MODE_READ);
8339
8340 if (dump_all)
8341 verbose = MAX(verbose, 1);
8342
8343 for (c = 0; c < 256; c++) {
8344 if (dump_all && strchr("AeEFklLOPRSXy", c) == NULL)
8345 dump_opt[c] = 1;
8346 if (dump_opt[c])
8347 dump_opt[c] += verbose;
8348 }
8349
8350 aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
8351 zfs_recover = (dump_opt['A'] > 1);
8352
8353 argc -= optind;
8354 argv += optind;
8355 if (argc < 2 && dump_opt['R'])
8356 usage();
8357
8358 if (dump_opt['E']) {
8359 if (argc != 1)
8360 usage();
8361 zdb_embedded_block(argv[0]);
8362 return (0);
8363 }
8364
8365 if (argc < 1) {
8366 if (!dump_opt['e'] && dump_opt['C']) {
8367 dump_cachefile(spa_config_path);
8368 return (0);
8369 }
8370 usage();
8371 }
8372
8373 if (dump_opt['l'])
8374 return (dump_label(argv[0]));
8375
8376 if (dump_opt['O']) {
8377 if (argc != 2)
8378 usage();
8379 dump_opt['v'] = verbose + 3;
8380 return (dump_path(argv[0], argv[1]));
8381 }
8382
8383 if (dump_opt['X'] || dump_opt['F'])
8384 rewind = ZPOOL_DO_REWIND |
8385 (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
8386
8387 if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
8388 nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, max_txg) != 0 ||
8389 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY, rewind) != 0)
8390 fatal("internal error: %s", strerror(ENOMEM));
8391
8392 error = 0;
8393 target = argv[0];
8394
8395 if (strpbrk(target, "/@") != NULL) {
8396 size_t targetlen;
8397
8398 target_pool = strdup(target);
8399 *strpbrk(target_pool, "/@") = '\0';
8400
8401 target_is_spa = B_FALSE;
8402 targetlen = strlen(target);
8403 if (targetlen && target[targetlen - 1] == '/')
8404 target[targetlen - 1] = '\0';
8405 } else {
8406 target_pool = target;
8407 }
8408
8409 if (dump_opt['e']) {
8410 importargs_t args = { 0 };
8411
8412 args.paths = nsearch;
8413 args.path = searchdirs;
8414 args.can_be_active = B_TRUE;
8415
8416 error = zpool_find_config(NULL, target_pool, &cfg, &args,
8417 &libzpool_config_ops);
8418
8419 if (error == 0) {
8420
8421 if (nvlist_add_nvlist(cfg,
8422 ZPOOL_LOAD_POLICY, policy) != 0) {
8423 fatal("can't open '%s': %s",
8424 target, strerror(ENOMEM));
8425 }
8426
8427 if (dump_opt['C'] > 1) {
8428 (void) printf("\nConfiguration for import:\n");
8429 dump_nvlist(cfg, 8);
8430 }
8431
8432 /*
8433 * Disable the activity check to allow examination of
8434 * active pools.
8435 */
8436 error = spa_import(target_pool, cfg, NULL,
8437 flags | ZFS_IMPORT_SKIP_MMP);
8438 }
8439 }
8440
8441 if (searchdirs != NULL) {
8442 umem_free(searchdirs, nsearch * sizeof (char *));
8443 searchdirs = NULL;
8444 }
8445
8446 /*
8447 * import_checkpointed_state makes the assumption that the
8448 * target pool that we pass it is already part of the spa
8449 * namespace. Because of that we need to make sure to call
8450 * it always after the -e option has been processed, which
8451 * imports the pool to the namespace if it's not in the
8452 * cachefile.
8453 */
8454 char *checkpoint_pool = NULL;
8455 char *checkpoint_target = NULL;
8456 if (dump_opt['k']) {
8457 checkpoint_pool = import_checkpointed_state(target, cfg,
8458 &checkpoint_target);
8459
8460 if (checkpoint_target != NULL)
8461 target = checkpoint_target;
8462 }
8463
8464 if (cfg != NULL) {
8465 nvlist_free(cfg);
8466 cfg = NULL;
8467 }
8468
8469 if (target_pool != target)
8470 free(target_pool);
8471
8472 if (error == 0) {
8473 if (dump_opt['k'] && (target_is_spa || dump_opt['R'])) {
8474 ASSERT(checkpoint_pool != NULL);
8475 ASSERT(checkpoint_target == NULL);
8476
8477 error = spa_open(checkpoint_pool, &spa, FTAG);
8478 if (error != 0) {
8479 fatal("Tried to open pool \"%s\" but "
8480 "spa_open() failed with error %d\n",
8481 checkpoint_pool, error);
8482 }
8483
8484 } else if (target_is_spa || dump_opt['R'] || objset_id == 0) {
8485 zdb_set_skip_mmp(target);
8486 error = spa_open_rewind(target, &spa, FTAG, policy,
8487 NULL);
8488 if (error) {
8489 /*
8490 * If we're missing the log device then
8491 * try opening the pool after clearing the
8492 * log state.
8493 */
8494 mutex_enter(&spa_namespace_lock);
8495 if ((spa = spa_lookup(target)) != NULL &&
8496 spa->spa_log_state == SPA_LOG_MISSING) {
8497 spa->spa_log_state = SPA_LOG_CLEAR;
8498 error = 0;
8499 }
8500 mutex_exit(&spa_namespace_lock);
8501
8502 if (!error) {
8503 error = spa_open_rewind(target, &spa,
8504 FTAG, policy, NULL);
8505 }
8506 }
8507 } else if (strpbrk(target, "#") != NULL) {
8508 dsl_pool_t *dp;
8509 error = dsl_pool_hold(target, FTAG, &dp);
8510 if (error != 0) {
8511 fatal("can't dump '%s': %s", target,
8512 strerror(error));
8513 }
8514 error = dump_bookmark(dp, target, B_TRUE, verbose > 1);
8515 dsl_pool_rele(dp, FTAG);
8516 if (error != 0) {
8517 fatal("can't dump '%s': %s", target,
8518 strerror(error));
8519 }
8520 return (error);
8521 } else {
8522 zdb_set_skip_mmp(target);
8523 if (dataset_lookup == B_TRUE) {
8524 /*
8525 * Use the supplied id to get the name
8526 * for open_objset.
8527 */
8528 error = spa_open(target, &spa, FTAG);
8529 if (error == 0) {
8530 error = name_from_objset_id(spa,
8531 objset_id, dsname);
8532 spa_close(spa, FTAG);
8533 if (error == 0)
8534 target = dsname;
8535 }
8536 }
8537 if (error == 0)
8538 error = open_objset(target, FTAG, &os);
8539 if (error == 0)
8540 spa = dmu_objset_spa(os);
8541 }
8542 }
8543 nvlist_free(policy);
8544
8545 if (error)
8546 fatal("can't open '%s': %s", target, strerror(error));
8547
8548 /*
8549 * Set the pool failure mode to panic in order to prevent the pool
8550 * from suspending. A suspended I/O will have no way to resume and
8551 * can prevent the zdb(8) command from terminating as expected.
8552 */
8553 if (spa != NULL)
8554 spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
8555
8556 argv++;
8557 argc--;
8558 if (!dump_opt['R']) {
8559 flagbits['d'] = ZOR_FLAG_DIRECTORY;
8560 flagbits['f'] = ZOR_FLAG_PLAIN_FILE;
8561 flagbits['m'] = ZOR_FLAG_SPACE_MAP;
8562 flagbits['z'] = ZOR_FLAG_ZAP;
8563 flagbits['A'] = ZOR_FLAG_ALL_TYPES;
8564
8565 if (argc > 0 && dump_opt['d']) {
8566 zopt_object_args = argc;
8567 zopt_object_ranges = calloc(zopt_object_args,
8568 sizeof (zopt_object_range_t));
8569 for (unsigned i = 0; i < zopt_object_args; i++) {
8570 int err;
8571 char *msg = NULL;
8572
8573 err = parse_object_range(argv[i],
8574 &zopt_object_ranges[i], &msg);
8575 if (err != 0)
8576 fatal("Bad object or range: '%s': %s\n",
8577 argv[i], msg ? msg : "");
8578 }
8579 } else if (argc > 0 && dump_opt['m']) {
8580 zopt_metaslab_args = argc;
8581 zopt_metaslab = calloc(zopt_metaslab_args,
8582 sizeof (uint64_t));
8583 for (unsigned i = 0; i < zopt_metaslab_args; i++) {
8584 errno = 0;
8585 zopt_metaslab[i] = strtoull(argv[i], NULL, 0);
8586 if (zopt_metaslab[i] == 0 && errno != 0)
8587 fatal("bad number %s: %s", argv[i],
8588 strerror(errno));
8589 }
8590 }
8591 if (os != NULL) {
8592 dump_objset(os);
8593 } else if (zopt_object_args > 0 && !dump_opt['m']) {
8594 dump_objset(spa->spa_meta_objset);
8595 } else {
8596 dump_zpool(spa);
8597 }
8598 } else {
8599 flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
8600 flagbits['c'] = ZDB_FLAG_CHECKSUM;
8601 flagbits['d'] = ZDB_FLAG_DECOMPRESS;
8602 flagbits['e'] = ZDB_FLAG_BSWAP;
8603 flagbits['g'] = ZDB_FLAG_GBH;
8604 flagbits['i'] = ZDB_FLAG_INDIRECT;
8605 flagbits['r'] = ZDB_FLAG_RAW;
8606 flagbits['v'] = ZDB_FLAG_VERBOSE;
8607
8608 for (int i = 0; i < argc; i++)
8609 zdb_read_block(argv[i], spa);
8610 }
8611
8612 if (dump_opt['k']) {
8613 free(checkpoint_pool);
8614 if (!target_is_spa)
8615 free(checkpoint_target);
8616 }
8617
8618 if (os != NULL) {
8619 close_objset(os, FTAG);
8620 } else {
8621 spa_close(spa, FTAG);
8622 }
8623
8624 fuid_table_destroy();
8625
8626 dump_debug_buffer();
8627
8628 kernel_fini();
8629
8630 return (error);
8631 }