]> git.proxmox.com Git - mirror_zfs.git/blob - cmd/zdb/zdb.c
MMP interval and fail_intervals in uberblock
[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, 2018 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 */
30
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <stdio_ext.h>
34 #include <stdlib.h>
35 #include <ctype.h>
36 #include <sys/zfs_context.h>
37 #include <sys/spa.h>
38 #include <sys/spa_impl.h>
39 #include <sys/dmu.h>
40 #include <sys/zap.h>
41 #include <sys/fs/zfs.h>
42 #include <sys/zfs_znode.h>
43 #include <sys/zfs_sa.h>
44 #include <sys/sa.h>
45 #include <sys/sa_impl.h>
46 #include <sys/vdev.h>
47 #include <sys/vdev_impl.h>
48 #include <sys/metaslab_impl.h>
49 #include <sys/dmu_objset.h>
50 #include <sys/dsl_dir.h>
51 #include <sys/dsl_dataset.h>
52 #include <sys/dsl_pool.h>
53 #include <sys/dbuf.h>
54 #include <sys/zil.h>
55 #include <sys/zil_impl.h>
56 #include <sys/stat.h>
57 #include <sys/resource.h>
58 #include <sys/dmu_traverse.h>
59 #include <sys/zio_checksum.h>
60 #include <sys/zio_compress.h>
61 #include <sys/zfs_fuid.h>
62 #include <sys/arc.h>
63 #include <sys/ddt.h>
64 #include <sys/zfeature.h>
65 #include <sys/abd.h>
66 #include <sys/blkptr.h>
67 #include <sys/dsl_crypt.h>
68 #include <sys/dsl_scan.h>
69 #include <zfs_comutil.h>
70
71 #include <libnvpair.h>
72 #include <libzutil.h>
73
74 #include "zdb.h"
75
76 #define ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ? \
77 zio_compress_table[(idx)].ci_name : "UNKNOWN")
78 #define ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ? \
79 zio_checksum_table[(idx)].ci_name : "UNKNOWN")
80 #define ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) : \
81 (idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA ? \
82 DMU_OT_ZAP_OTHER : \
83 (idx) == DMU_OTN_UINT64_DATA || (idx) == DMU_OTN_UINT64_METADATA ? \
84 DMU_OT_UINT64_OTHER : DMU_OT_NUMTYPES)
85
86 static char *
87 zdb_ot_name(dmu_object_type_t type)
88 {
89 if (type < DMU_OT_NUMTYPES)
90 return (dmu_ot[type].ot_name);
91 else if ((type & DMU_OT_NEWTYPE) &&
92 ((type & DMU_OT_BYTESWAP_MASK) < DMU_BSWAP_NUMFUNCS))
93 return (dmu_ot_byteswap[type & DMU_OT_BYTESWAP_MASK].ob_name);
94 else
95 return ("UNKNOWN");
96 }
97
98 extern int reference_tracking_enable;
99 extern int zfs_recover;
100 extern uint64_t zfs_arc_max, zfs_arc_meta_limit;
101 extern int zfs_vdev_async_read_max_active;
102 extern boolean_t spa_load_verify_dryrun;
103 extern int zfs_reconstruct_indirect_combinations_max;
104
105 static const char cmdname[] = "zdb";
106 uint8_t dump_opt[256];
107
108 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
109
110 uint64_t *zopt_object = NULL;
111 static unsigned zopt_objects = 0;
112 uint64_t max_inflight = 1000;
113 static int leaked_objects = 0;
114 static range_tree_t *mos_refd_objs;
115
116 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *);
117 static void mos_obj_refd(uint64_t);
118 static void mos_obj_refd_multiple(uint64_t);
119
120 /*
121 * These libumem hooks provide a reasonable set of defaults for the allocator's
122 * debugging facilities.
123 */
124 const char *
125 _umem_debug_init(void)
126 {
127 return ("default,verbose"); /* $UMEM_DEBUG setting */
128 }
129
130 const char *
131 _umem_logging_init(void)
132 {
133 return ("fail,contents"); /* $UMEM_LOGGING setting */
134 }
135
136 static void
137 usage(void)
138 {
139 (void) fprintf(stderr,
140 "Usage:\t%s [-AbcdDFGhikLMPsvX] [-e [-V] [-p <path> ...]] "
141 "[-I <inflight I/Os>]\n"
142 "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
143 "\t\t[<poolname> [<object> ...]]\n"
144 "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>] <dataset>\n"
145 "\t\t[<object> ...]\n"
146 "\t%s -C [-A] [-U <cache>]\n"
147 "\t%s -l [-Aqu] <device>\n"
148 "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
149 "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
150 "\t%s -O <dataset> <path>\n"
151 "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
152 "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
153 "\t%s -E [-A] word0:word1:...:word15\n"
154 "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
155 "<poolname>\n\n",
156 cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
157 cmdname, cmdname);
158
159 (void) fprintf(stderr, " Dataset name must include at least one "
160 "separator character '/' or '@'\n");
161 (void) fprintf(stderr, " If dataset name is specified, only that "
162 "dataset is dumped\n");
163 (void) fprintf(stderr, " If object numbers are specified, only "
164 "those objects are dumped\n\n");
165 (void) fprintf(stderr, " Options to control amount of output:\n");
166 (void) fprintf(stderr, " -b block statistics\n");
167 (void) fprintf(stderr, " -c checksum all metadata (twice for "
168 "all data) blocks\n");
169 (void) fprintf(stderr, " -C config (or cachefile if alone)\n");
170 (void) fprintf(stderr, " -d dataset(s)\n");
171 (void) fprintf(stderr, " -D dedup statistics\n");
172 (void) fprintf(stderr, " -E decode and display block from an "
173 "embedded block pointer\n");
174 (void) fprintf(stderr, " -h pool history\n");
175 (void) fprintf(stderr, " -i intent logs\n");
176 (void) fprintf(stderr, " -l read label contents\n");
177 (void) fprintf(stderr, " -k examine the checkpointed state "
178 "of the pool\n");
179 (void) fprintf(stderr, " -L disable leak tracking (do not "
180 "load spacemaps)\n");
181 (void) fprintf(stderr, " -m metaslabs\n");
182 (void) fprintf(stderr, " -M metaslab groups\n");
183 (void) fprintf(stderr, " -O perform object lookups by path\n");
184 (void) fprintf(stderr, " -R read and display block from a "
185 "device\n");
186 (void) fprintf(stderr, " -s report stats on zdb's I/O\n");
187 (void) fprintf(stderr, " -S simulate dedup to measure effect\n");
188 (void) fprintf(stderr, " -v verbose (applies to all "
189 "others)\n\n");
190 (void) fprintf(stderr, " Below options are intended for use "
191 "with other options:\n");
192 (void) fprintf(stderr, " -A ignore assertions (-A), enable "
193 "panic recovery (-AA) or both (-AAA)\n");
194 (void) fprintf(stderr, " -e pool is exported/destroyed/"
195 "has altroot/not in a cachefile\n");
196 (void) fprintf(stderr, " -F attempt automatic rewind within "
197 "safe range of transaction groups\n");
198 (void) fprintf(stderr, " -G dump zfs_dbgmsg buffer before "
199 "exiting\n");
200 (void) fprintf(stderr, " -I <number of inflight I/Os> -- "
201 "specify the maximum number of\n "
202 "checksumming I/Os [default is 200]\n");
203 (void) fprintf(stderr, " -o <variable>=<value> set global "
204 "variable to an unsigned 32-bit integer\n");
205 (void) fprintf(stderr, " -p <path> -- use one or more with "
206 "-e to specify path to vdev dir\n");
207 (void) fprintf(stderr, " -P print numbers in parseable form\n");
208 (void) fprintf(stderr, " -q don't print label contents\n");
209 (void) fprintf(stderr, " -t <txg> -- highest txg to use when "
210 "searching for uberblocks\n");
211 (void) fprintf(stderr, " -u uberblock\n");
212 (void) fprintf(stderr, " -U <cachefile_path> -- use alternate "
213 "cachefile\n");
214 (void) fprintf(stderr, " -V do verbatim import\n");
215 (void) fprintf(stderr, " -x <dumpdir> -- "
216 "dump all read blocks into specified directory\n");
217 (void) fprintf(stderr, " -X attempt extreme rewind (does not "
218 "work with dataset)\n");
219 (void) fprintf(stderr, " -Y attempt all reconstruction "
220 "combinations for split blocks\n");
221 (void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
222 "to make only that option verbose\n");
223 (void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
224 exit(1);
225 }
226
227 static void
228 dump_debug_buffer(void)
229 {
230 if (dump_opt['G']) {
231 (void) printf("\n");
232 (void) fflush(stdout);
233 zfs_dbgmsg_print("zdb");
234 }
235 }
236
237 /*
238 * Called for usage errors that are discovered after a call to spa_open(),
239 * dmu_bonus_hold(), or pool_match(). abort() is called for other errors.
240 */
241
242 static void
243 fatal(const char *fmt, ...)
244 {
245 va_list ap;
246
247 va_start(ap, fmt);
248 (void) fprintf(stderr, "%s: ", cmdname);
249 (void) vfprintf(stderr, fmt, ap);
250 va_end(ap);
251 (void) fprintf(stderr, "\n");
252
253 dump_debug_buffer();
254
255 exit(1);
256 }
257
258 /* ARGSUSED */
259 static void
260 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
261 {
262 nvlist_t *nv;
263 size_t nvsize = *(uint64_t *)data;
264 char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
265
266 VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
267
268 VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
269
270 umem_free(packed, nvsize);
271
272 dump_nvlist(nv, 8);
273
274 nvlist_free(nv);
275 }
276
277 /* ARGSUSED */
278 static void
279 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
280 {
281 spa_history_phys_t *shp = data;
282
283 if (shp == NULL)
284 return;
285
286 (void) printf("\t\tpool_create_len = %llu\n",
287 (u_longlong_t)shp->sh_pool_create_len);
288 (void) printf("\t\tphys_max_off = %llu\n",
289 (u_longlong_t)shp->sh_phys_max_off);
290 (void) printf("\t\tbof = %llu\n",
291 (u_longlong_t)shp->sh_bof);
292 (void) printf("\t\teof = %llu\n",
293 (u_longlong_t)shp->sh_eof);
294 (void) printf("\t\trecords_lost = %llu\n",
295 (u_longlong_t)shp->sh_records_lost);
296 }
297
298 static void
299 zdb_nicenum(uint64_t num, char *buf, size_t buflen)
300 {
301 if (dump_opt['P'])
302 (void) snprintf(buf, buflen, "%llu", (longlong_t)num);
303 else
304 nicenum(num, buf, sizeof (buf));
305 }
306
307 static const char histo_stars[] = "****************************************";
308 static const uint64_t histo_width = sizeof (histo_stars) - 1;
309
310 static void
311 dump_histogram(const uint64_t *histo, int size, int offset)
312 {
313 int i;
314 int minidx = size - 1;
315 int maxidx = 0;
316 uint64_t max = 0;
317
318 for (i = 0; i < size; i++) {
319 if (histo[i] > max)
320 max = histo[i];
321 if (histo[i] > 0 && i > maxidx)
322 maxidx = i;
323 if (histo[i] > 0 && i < minidx)
324 minidx = i;
325 }
326
327 if (max < histo_width)
328 max = histo_width;
329
330 for (i = minidx; i <= maxidx; i++) {
331 (void) printf("\t\t\t%3u: %6llu %s\n",
332 i + offset, (u_longlong_t)histo[i],
333 &histo_stars[(max - histo[i]) * histo_width / max]);
334 }
335 }
336
337 static void
338 dump_zap_stats(objset_t *os, uint64_t object)
339 {
340 int error;
341 zap_stats_t zs;
342
343 error = zap_get_stats(os, object, &zs);
344 if (error)
345 return;
346
347 if (zs.zs_ptrtbl_len == 0) {
348 ASSERT(zs.zs_num_blocks == 1);
349 (void) printf("\tmicrozap: %llu bytes, %llu entries\n",
350 (u_longlong_t)zs.zs_blocksize,
351 (u_longlong_t)zs.zs_num_entries);
352 return;
353 }
354
355 (void) printf("\tFat ZAP stats:\n");
356
357 (void) printf("\t\tPointer table:\n");
358 (void) printf("\t\t\t%llu elements\n",
359 (u_longlong_t)zs.zs_ptrtbl_len);
360 (void) printf("\t\t\tzt_blk: %llu\n",
361 (u_longlong_t)zs.zs_ptrtbl_zt_blk);
362 (void) printf("\t\t\tzt_numblks: %llu\n",
363 (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
364 (void) printf("\t\t\tzt_shift: %llu\n",
365 (u_longlong_t)zs.zs_ptrtbl_zt_shift);
366 (void) printf("\t\t\tzt_blks_copied: %llu\n",
367 (u_longlong_t)zs.zs_ptrtbl_blks_copied);
368 (void) printf("\t\t\tzt_nextblk: %llu\n",
369 (u_longlong_t)zs.zs_ptrtbl_nextblk);
370
371 (void) printf("\t\tZAP entries: %llu\n",
372 (u_longlong_t)zs.zs_num_entries);
373 (void) printf("\t\tLeaf blocks: %llu\n",
374 (u_longlong_t)zs.zs_num_leafs);
375 (void) printf("\t\tTotal blocks: %llu\n",
376 (u_longlong_t)zs.zs_num_blocks);
377 (void) printf("\t\tzap_block_type: 0x%llx\n",
378 (u_longlong_t)zs.zs_block_type);
379 (void) printf("\t\tzap_magic: 0x%llx\n",
380 (u_longlong_t)zs.zs_magic);
381 (void) printf("\t\tzap_salt: 0x%llx\n",
382 (u_longlong_t)zs.zs_salt);
383
384 (void) printf("\t\tLeafs with 2^n pointers:\n");
385 dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
386
387 (void) printf("\t\tBlocks with n*5 entries:\n");
388 dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
389
390 (void) printf("\t\tBlocks n/10 full:\n");
391 dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
392
393 (void) printf("\t\tEntries with n chunks:\n");
394 dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
395
396 (void) printf("\t\tBuckets with n entries:\n");
397 dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
398 }
399
400 /*ARGSUSED*/
401 static void
402 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
403 {
404 }
405
406 /*ARGSUSED*/
407 static void
408 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
409 {
410 (void) printf("\tUNKNOWN OBJECT TYPE\n");
411 }
412
413 /*ARGSUSED*/
414 static void
415 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
416 {
417 }
418
419 /*ARGSUSED*/
420 static void
421 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
422 {
423 }
424
425 /*ARGSUSED*/
426 static void
427 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
428 {
429 zap_cursor_t zc;
430 zap_attribute_t attr;
431 void *prop;
432 unsigned i;
433
434 dump_zap_stats(os, object);
435 (void) printf("\n");
436
437 for (zap_cursor_init(&zc, os, object);
438 zap_cursor_retrieve(&zc, &attr) == 0;
439 zap_cursor_advance(&zc)) {
440 (void) printf("\t\t%s = ", attr.za_name);
441 if (attr.za_num_integers == 0) {
442 (void) printf("\n");
443 continue;
444 }
445 prop = umem_zalloc(attr.za_num_integers *
446 attr.za_integer_length, UMEM_NOFAIL);
447 (void) zap_lookup(os, object, attr.za_name,
448 attr.za_integer_length, attr.za_num_integers, prop);
449 if (attr.za_integer_length == 1) {
450 (void) printf("%s", (char *)prop);
451 } else {
452 for (i = 0; i < attr.za_num_integers; i++) {
453 switch (attr.za_integer_length) {
454 case 2:
455 (void) printf("%u ",
456 ((uint16_t *)prop)[i]);
457 break;
458 case 4:
459 (void) printf("%u ",
460 ((uint32_t *)prop)[i]);
461 break;
462 case 8:
463 (void) printf("%lld ",
464 (u_longlong_t)((int64_t *)prop)[i]);
465 break;
466 }
467 }
468 }
469 (void) printf("\n");
470 umem_free(prop, attr.za_num_integers * attr.za_integer_length);
471 }
472 zap_cursor_fini(&zc);
473 }
474
475 static void
476 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
477 {
478 bpobj_phys_t *bpop = data;
479 uint64_t i;
480 char bytes[32], comp[32], uncomp[32];
481
482 /* make sure the output won't get truncated */
483 CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
484 CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
485 CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
486
487 if (bpop == NULL)
488 return;
489
490 zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
491 zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
492 zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
493
494 (void) printf("\t\tnum_blkptrs = %llu\n",
495 (u_longlong_t)bpop->bpo_num_blkptrs);
496 (void) printf("\t\tbytes = %s\n", bytes);
497 if (size >= BPOBJ_SIZE_V1) {
498 (void) printf("\t\tcomp = %s\n", comp);
499 (void) printf("\t\tuncomp = %s\n", uncomp);
500 }
501 if (size >= sizeof (*bpop)) {
502 (void) printf("\t\tsubobjs = %llu\n",
503 (u_longlong_t)bpop->bpo_subobjs);
504 (void) printf("\t\tnum_subobjs = %llu\n",
505 (u_longlong_t)bpop->bpo_num_subobjs);
506 }
507
508 if (dump_opt['d'] < 5)
509 return;
510
511 for (i = 0; i < bpop->bpo_num_blkptrs; i++) {
512 char blkbuf[BP_SPRINTF_LEN];
513 blkptr_t bp;
514
515 int err = dmu_read(os, object,
516 i * sizeof (bp), sizeof (bp), &bp, 0);
517 if (err != 0) {
518 (void) printf("got error %u from dmu_read\n", err);
519 break;
520 }
521 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp);
522 (void) printf("\t%s\n", blkbuf);
523 }
524 }
525
526 /* ARGSUSED */
527 static void
528 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
529 {
530 dmu_object_info_t doi;
531 int64_t i;
532
533 VERIFY0(dmu_object_info(os, object, &doi));
534 uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
535
536 int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
537 if (err != 0) {
538 (void) printf("got error %u from dmu_read\n", err);
539 kmem_free(subobjs, doi.doi_max_offset);
540 return;
541 }
542
543 int64_t last_nonzero = -1;
544 for (i = 0; i < doi.doi_max_offset / 8; i++) {
545 if (subobjs[i] != 0)
546 last_nonzero = i;
547 }
548
549 for (i = 0; i <= last_nonzero; i++) {
550 (void) printf("\t%llu\n", (u_longlong_t)subobjs[i]);
551 }
552 kmem_free(subobjs, doi.doi_max_offset);
553 }
554
555 /*ARGSUSED*/
556 static void
557 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
558 {
559 dump_zap_stats(os, object);
560 /* contents are printed elsewhere, properly decoded */
561 }
562
563 /*ARGSUSED*/
564 static void
565 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
566 {
567 zap_cursor_t zc;
568 zap_attribute_t attr;
569
570 dump_zap_stats(os, object);
571 (void) printf("\n");
572
573 for (zap_cursor_init(&zc, os, object);
574 zap_cursor_retrieve(&zc, &attr) == 0;
575 zap_cursor_advance(&zc)) {
576 (void) printf("\t\t%s = ", attr.za_name);
577 if (attr.za_num_integers == 0) {
578 (void) printf("\n");
579 continue;
580 }
581 (void) printf(" %llx : [%d:%d:%d]\n",
582 (u_longlong_t)attr.za_first_integer,
583 (int)ATTR_LENGTH(attr.za_first_integer),
584 (int)ATTR_BSWAP(attr.za_first_integer),
585 (int)ATTR_NUM(attr.za_first_integer));
586 }
587 zap_cursor_fini(&zc);
588 }
589
590 /*ARGSUSED*/
591 static void
592 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
593 {
594 zap_cursor_t zc;
595 zap_attribute_t attr;
596 uint16_t *layout_attrs;
597 unsigned i;
598
599 dump_zap_stats(os, object);
600 (void) printf("\n");
601
602 for (zap_cursor_init(&zc, os, object);
603 zap_cursor_retrieve(&zc, &attr) == 0;
604 zap_cursor_advance(&zc)) {
605 (void) printf("\t\t%s = [", attr.za_name);
606 if (attr.za_num_integers == 0) {
607 (void) printf("\n");
608 continue;
609 }
610
611 VERIFY(attr.za_integer_length == 2);
612 layout_attrs = umem_zalloc(attr.za_num_integers *
613 attr.za_integer_length, UMEM_NOFAIL);
614
615 VERIFY(zap_lookup(os, object, attr.za_name,
616 attr.za_integer_length,
617 attr.za_num_integers, layout_attrs) == 0);
618
619 for (i = 0; i != attr.za_num_integers; i++)
620 (void) printf(" %d ", (int)layout_attrs[i]);
621 (void) printf("]\n");
622 umem_free(layout_attrs,
623 attr.za_num_integers * attr.za_integer_length);
624 }
625 zap_cursor_fini(&zc);
626 }
627
628 /*ARGSUSED*/
629 static void
630 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
631 {
632 zap_cursor_t zc;
633 zap_attribute_t attr;
634 const char *typenames[] = {
635 /* 0 */ "not specified",
636 /* 1 */ "FIFO",
637 /* 2 */ "Character Device",
638 /* 3 */ "3 (invalid)",
639 /* 4 */ "Directory",
640 /* 5 */ "5 (invalid)",
641 /* 6 */ "Block Device",
642 /* 7 */ "7 (invalid)",
643 /* 8 */ "Regular File",
644 /* 9 */ "9 (invalid)",
645 /* 10 */ "Symbolic Link",
646 /* 11 */ "11 (invalid)",
647 /* 12 */ "Socket",
648 /* 13 */ "Door",
649 /* 14 */ "Event Port",
650 /* 15 */ "15 (invalid)",
651 };
652
653 dump_zap_stats(os, object);
654 (void) printf("\n");
655
656 for (zap_cursor_init(&zc, os, object);
657 zap_cursor_retrieve(&zc, &attr) == 0;
658 zap_cursor_advance(&zc)) {
659 (void) printf("\t\t%s = %lld (type: %s)\n",
660 attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
661 typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
662 }
663 zap_cursor_fini(&zc);
664 }
665
666 static int
667 get_dtl_refcount(vdev_t *vd)
668 {
669 int refcount = 0;
670
671 if (vd->vdev_ops->vdev_op_leaf) {
672 space_map_t *sm = vd->vdev_dtl_sm;
673
674 if (sm != NULL &&
675 sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
676 return (1);
677 return (0);
678 }
679
680 for (unsigned c = 0; c < vd->vdev_children; c++)
681 refcount += get_dtl_refcount(vd->vdev_child[c]);
682 return (refcount);
683 }
684
685 static int
686 get_metaslab_refcount(vdev_t *vd)
687 {
688 int refcount = 0;
689
690 if (vd->vdev_top == vd) {
691 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
692 space_map_t *sm = vd->vdev_ms[m]->ms_sm;
693
694 if (sm != NULL &&
695 sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
696 refcount++;
697 }
698 }
699 for (unsigned c = 0; c < vd->vdev_children; c++)
700 refcount += get_metaslab_refcount(vd->vdev_child[c]);
701
702 return (refcount);
703 }
704
705 static int
706 get_obsolete_refcount(vdev_t *vd)
707 {
708 uint64_t obsolete_sm_object;
709 int refcount = 0;
710
711 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
712 if (vd->vdev_top == vd && obsolete_sm_object != 0) {
713 dmu_object_info_t doi;
714 VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
715 obsolete_sm_object, &doi));
716 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
717 refcount++;
718 }
719 } else {
720 ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
721 ASSERT3U(obsolete_sm_object, ==, 0);
722 }
723 for (unsigned c = 0; c < vd->vdev_children; c++) {
724 refcount += get_obsolete_refcount(vd->vdev_child[c]);
725 }
726
727 return (refcount);
728 }
729
730 static int
731 get_prev_obsolete_spacemap_refcount(spa_t *spa)
732 {
733 uint64_t prev_obj =
734 spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
735 if (prev_obj != 0) {
736 dmu_object_info_t doi;
737 VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
738 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
739 return (1);
740 }
741 }
742 return (0);
743 }
744
745 static int
746 get_checkpoint_refcount(vdev_t *vd)
747 {
748 int refcount = 0;
749
750 if (vd->vdev_top == vd && vd->vdev_top_zap != 0 &&
751 zap_contains(spa_meta_objset(vd->vdev_spa),
752 vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) == 0)
753 refcount++;
754
755 for (uint64_t c = 0; c < vd->vdev_children; c++)
756 refcount += get_checkpoint_refcount(vd->vdev_child[c]);
757
758 return (refcount);
759 }
760
761 static int
762 verify_spacemap_refcounts(spa_t *spa)
763 {
764 uint64_t expected_refcount = 0;
765 uint64_t actual_refcount;
766
767 (void) feature_get_refcount(spa,
768 &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
769 &expected_refcount);
770 actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
771 actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
772 actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
773 actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
774 actual_refcount += get_checkpoint_refcount(spa->spa_root_vdev);
775
776 if (expected_refcount != actual_refcount) {
777 (void) printf("space map refcount mismatch: expected %lld != "
778 "actual %lld\n",
779 (longlong_t)expected_refcount,
780 (longlong_t)actual_refcount);
781 return (2);
782 }
783 return (0);
784 }
785
786 static void
787 dump_spacemap(objset_t *os, space_map_t *sm)
788 {
789 const char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
790 "INVALID", "INVALID", "INVALID", "INVALID" };
791
792 if (sm == NULL)
793 return;
794
795 (void) printf("space map object %llu:\n",
796 (longlong_t)sm->sm_object);
797 (void) printf(" smp_length = 0x%llx\n",
798 (longlong_t)sm->sm_phys->smp_length);
799 (void) printf(" smp_alloc = 0x%llx\n",
800 (longlong_t)sm->sm_phys->smp_alloc);
801
802 if (dump_opt['d'] < 6 && dump_opt['m'] < 4)
803 return;
804
805 /*
806 * Print out the freelist entries in both encoded and decoded form.
807 */
808 uint8_t mapshift = sm->sm_shift;
809 int64_t alloc = 0;
810 uint64_t word, entry_id = 0;
811 for (uint64_t offset = 0; offset < space_map_length(sm);
812 offset += sizeof (word)) {
813
814 VERIFY0(dmu_read(os, space_map_object(sm), offset,
815 sizeof (word), &word, DMU_READ_PREFETCH));
816
817 if (sm_entry_is_debug(word)) {
818 (void) printf("\t [%6llu] %s: txg %llu pass %llu\n",
819 (u_longlong_t)entry_id,
820 ddata[SM_DEBUG_ACTION_DECODE(word)],
821 (u_longlong_t)SM_DEBUG_TXG_DECODE(word),
822 (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(word));
823 entry_id++;
824 continue;
825 }
826
827 uint8_t words;
828 char entry_type;
829 uint64_t entry_off, entry_run, entry_vdev = SM_NO_VDEVID;
830
831 if (sm_entry_is_single_word(word)) {
832 entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
833 'A' : 'F';
834 entry_off = (SM_OFFSET_DECODE(word) << mapshift) +
835 sm->sm_start;
836 entry_run = SM_RUN_DECODE(word) << mapshift;
837 words = 1;
838 } else {
839 /* it is a two-word entry so we read another word */
840 ASSERT(sm_entry_is_double_word(word));
841
842 uint64_t extra_word;
843 offset += sizeof (extra_word);
844 VERIFY0(dmu_read(os, space_map_object(sm), offset,
845 sizeof (extra_word), &extra_word,
846 DMU_READ_PREFETCH));
847
848 ASSERT3U(offset, <=, space_map_length(sm));
849
850 entry_run = SM2_RUN_DECODE(word) << mapshift;
851 entry_vdev = SM2_VDEV_DECODE(word);
852 entry_type = (SM2_TYPE_DECODE(extra_word) == SM_ALLOC) ?
853 'A' : 'F';
854 entry_off = (SM2_OFFSET_DECODE(extra_word) <<
855 mapshift) + sm->sm_start;
856 words = 2;
857 }
858
859 (void) printf("\t [%6llu] %c range:"
860 " %010llx-%010llx size: %06llx vdev: %06llu words: %u\n",
861 (u_longlong_t)entry_id,
862 entry_type, (u_longlong_t)entry_off,
863 (u_longlong_t)(entry_off + entry_run),
864 (u_longlong_t)entry_run,
865 (u_longlong_t)entry_vdev, words);
866
867 if (entry_type == 'A')
868 alloc += entry_run;
869 else
870 alloc -= entry_run;
871 entry_id++;
872 }
873 if ((uint64_t)alloc != space_map_allocated(sm)) {
874 (void) printf("space_map_object alloc (%lld) INCONSISTENT "
875 "with space map summary (%lld)\n",
876 (longlong_t)space_map_allocated(sm), (longlong_t)alloc);
877 }
878 }
879
880 static void
881 dump_metaslab_stats(metaslab_t *msp)
882 {
883 char maxbuf[32];
884 range_tree_t *rt = msp->ms_allocatable;
885 avl_tree_t *t = &msp->ms_allocatable_by_size;
886 int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
887
888 /* max sure nicenum has enough space */
889 CTASSERT(sizeof (maxbuf) >= NN_NUMBUF_SZ);
890
891 zdb_nicenum(metaslab_block_maxsize(msp), maxbuf, sizeof (maxbuf));
892
893 (void) printf("\t %25s %10lu %7s %6s %4s %4d%%\n",
894 "segments", avl_numnodes(t), "maxsize", maxbuf,
895 "freepct", free_pct);
896 (void) printf("\tIn-memory histogram:\n");
897 dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
898 }
899
900 static void
901 dump_metaslab(metaslab_t *msp)
902 {
903 vdev_t *vd = msp->ms_group->mg_vd;
904 spa_t *spa = vd->vdev_spa;
905 space_map_t *sm = msp->ms_sm;
906 char freebuf[32];
907
908 zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
909 sizeof (freebuf));
910
911 (void) printf(
912 "\tmetaslab %6llu offset %12llx spacemap %6llu free %5s\n",
913 (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
914 (u_longlong_t)space_map_object(sm), freebuf);
915
916 if (dump_opt['m'] > 2 && !dump_opt['L']) {
917 mutex_enter(&msp->ms_lock);
918 VERIFY0(metaslab_load(msp));
919 range_tree_stat_verify(msp->ms_allocatable);
920 dump_metaslab_stats(msp);
921 metaslab_unload(msp);
922 mutex_exit(&msp->ms_lock);
923 }
924
925 if (dump_opt['m'] > 1 && sm != NULL &&
926 spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
927 /*
928 * The space map histogram represents free space in chunks
929 * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
930 */
931 (void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
932 (u_longlong_t)msp->ms_fragmentation);
933 dump_histogram(sm->sm_phys->smp_histogram,
934 SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
935 }
936
937 ASSERT(msp->ms_size == (1ULL << vd->vdev_ms_shift));
938 dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
939 }
940
941 static void
942 print_vdev_metaslab_header(vdev_t *vd)
943 {
944 vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
945 const char *bias_str;
946
947 bias_str = (alloc_bias == VDEV_BIAS_LOG || vd->vdev_islog) ?
948 VDEV_ALLOC_BIAS_LOG :
949 (alloc_bias == VDEV_BIAS_SPECIAL) ? VDEV_ALLOC_BIAS_SPECIAL :
950 (alloc_bias == VDEV_BIAS_DEDUP) ? VDEV_ALLOC_BIAS_DEDUP :
951 vd->vdev_islog ? "log" : "";
952
953 (void) printf("\tvdev %10llu %s\n"
954 "\t%-10s%5llu %-19s %-15s %-12s\n",
955 (u_longlong_t)vd->vdev_id, bias_str,
956 "metaslabs", (u_longlong_t)vd->vdev_ms_count,
957 "offset", "spacemap", "free");
958 (void) printf("\t%15s %19s %15s %12s\n",
959 "---------------", "-------------------",
960 "---------------", "------------");
961 }
962
963 static void
964 dump_metaslab_groups(spa_t *spa)
965 {
966 vdev_t *rvd = spa->spa_root_vdev;
967 metaslab_class_t *mc = spa_normal_class(spa);
968 uint64_t fragmentation;
969
970 metaslab_class_histogram_verify(mc);
971
972 for (unsigned c = 0; c < rvd->vdev_children; c++) {
973 vdev_t *tvd = rvd->vdev_child[c];
974 metaslab_group_t *mg = tvd->vdev_mg;
975
976 if (mg == NULL || mg->mg_class != mc)
977 continue;
978
979 metaslab_group_histogram_verify(mg);
980 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
981
982 (void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
983 "fragmentation",
984 (u_longlong_t)tvd->vdev_id,
985 (u_longlong_t)tvd->vdev_ms_count);
986 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
987 (void) printf("%3s\n", "-");
988 } else {
989 (void) printf("%3llu%%\n",
990 (u_longlong_t)mg->mg_fragmentation);
991 }
992 dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
993 }
994
995 (void) printf("\tpool %s\tfragmentation", spa_name(spa));
996 fragmentation = metaslab_class_fragmentation(mc);
997 if (fragmentation == ZFS_FRAG_INVALID)
998 (void) printf("\t%3s\n", "-");
999 else
1000 (void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
1001 dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1002 }
1003
1004 static void
1005 print_vdev_indirect(vdev_t *vd)
1006 {
1007 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1008 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1009 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
1010
1011 if (vim == NULL) {
1012 ASSERT3P(vib, ==, NULL);
1013 return;
1014 }
1015
1016 ASSERT3U(vdev_indirect_mapping_object(vim), ==,
1017 vic->vic_mapping_object);
1018 ASSERT3U(vdev_indirect_births_object(vib), ==,
1019 vic->vic_births_object);
1020
1021 (void) printf("indirect births obj %llu:\n",
1022 (longlong_t)vic->vic_births_object);
1023 (void) printf(" vib_count = %llu\n",
1024 (longlong_t)vdev_indirect_births_count(vib));
1025 for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
1026 vdev_indirect_birth_entry_phys_t *cur_vibe =
1027 &vib->vib_entries[i];
1028 (void) printf("\toffset %llx -> txg %llu\n",
1029 (longlong_t)cur_vibe->vibe_offset,
1030 (longlong_t)cur_vibe->vibe_phys_birth_txg);
1031 }
1032 (void) printf("\n");
1033
1034 (void) printf("indirect mapping obj %llu:\n",
1035 (longlong_t)vic->vic_mapping_object);
1036 (void) printf(" vim_max_offset = 0x%llx\n",
1037 (longlong_t)vdev_indirect_mapping_max_offset(vim));
1038 (void) printf(" vim_bytes_mapped = 0x%llx\n",
1039 (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
1040 (void) printf(" vim_count = %llu\n",
1041 (longlong_t)vdev_indirect_mapping_num_entries(vim));
1042
1043 if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
1044 return;
1045
1046 uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
1047
1048 for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
1049 vdev_indirect_mapping_entry_phys_t *vimep =
1050 &vim->vim_entries[i];
1051 (void) printf("\t<%llx:%llx:%llx> -> "
1052 "<%llx:%llx:%llx> (%x obsolete)\n",
1053 (longlong_t)vd->vdev_id,
1054 (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
1055 (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1056 (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
1057 (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
1058 (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1059 counts[i]);
1060 }
1061 (void) printf("\n");
1062
1063 uint64_t obsolete_sm_object;
1064 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1065 if (obsolete_sm_object != 0) {
1066 objset_t *mos = vd->vdev_spa->spa_meta_objset;
1067 (void) printf("obsolete space map object %llu:\n",
1068 (u_longlong_t)obsolete_sm_object);
1069 ASSERT(vd->vdev_obsolete_sm != NULL);
1070 ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
1071 obsolete_sm_object);
1072 dump_spacemap(mos, vd->vdev_obsolete_sm);
1073 (void) printf("\n");
1074 }
1075 }
1076
1077 static void
1078 dump_metaslabs(spa_t *spa)
1079 {
1080 vdev_t *vd, *rvd = spa->spa_root_vdev;
1081 uint64_t m, c = 0, children = rvd->vdev_children;
1082
1083 (void) printf("\nMetaslabs:\n");
1084
1085 if (!dump_opt['d'] && zopt_objects > 0) {
1086 c = zopt_object[0];
1087
1088 if (c >= children)
1089 (void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1090
1091 if (zopt_objects > 1) {
1092 vd = rvd->vdev_child[c];
1093 print_vdev_metaslab_header(vd);
1094
1095 for (m = 1; m < zopt_objects; m++) {
1096 if (zopt_object[m] < vd->vdev_ms_count)
1097 dump_metaslab(
1098 vd->vdev_ms[zopt_object[m]]);
1099 else
1100 (void) fprintf(stderr, "bad metaslab "
1101 "number %llu\n",
1102 (u_longlong_t)zopt_object[m]);
1103 }
1104 (void) printf("\n");
1105 return;
1106 }
1107 children = c + 1;
1108 }
1109 for (; c < children; c++) {
1110 vd = rvd->vdev_child[c];
1111 print_vdev_metaslab_header(vd);
1112
1113 print_vdev_indirect(vd);
1114
1115 for (m = 0; m < vd->vdev_ms_count; m++)
1116 dump_metaslab(vd->vdev_ms[m]);
1117 (void) printf("\n");
1118 }
1119 }
1120
1121 static void
1122 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
1123 {
1124 const ddt_phys_t *ddp = dde->dde_phys;
1125 const ddt_key_t *ddk = &dde->dde_key;
1126 const char *types[4] = { "ditto", "single", "double", "triple" };
1127 char blkbuf[BP_SPRINTF_LEN];
1128 blkptr_t blk;
1129 int p;
1130
1131 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1132 if (ddp->ddp_phys_birth == 0)
1133 continue;
1134 ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
1135 snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1136 (void) printf("index %llx refcnt %llu %s %s\n",
1137 (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
1138 types[p], blkbuf);
1139 }
1140 }
1141
1142 static void
1143 dump_dedup_ratio(const ddt_stat_t *dds)
1144 {
1145 double rL, rP, rD, D, dedup, compress, copies;
1146
1147 if (dds->dds_blocks == 0)
1148 return;
1149
1150 rL = (double)dds->dds_ref_lsize;
1151 rP = (double)dds->dds_ref_psize;
1152 rD = (double)dds->dds_ref_dsize;
1153 D = (double)dds->dds_dsize;
1154
1155 dedup = rD / D;
1156 compress = rL / rP;
1157 copies = rD / rP;
1158
1159 (void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
1160 "dedup * compress / copies = %.2f\n\n",
1161 dedup, compress, copies, dedup * compress / copies);
1162 }
1163
1164 static void
1165 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
1166 {
1167 char name[DDT_NAMELEN];
1168 ddt_entry_t dde;
1169 uint64_t walk = 0;
1170 dmu_object_info_t doi;
1171 uint64_t count, dspace, mspace;
1172 int error;
1173
1174 error = ddt_object_info(ddt, type, class, &doi);
1175
1176 if (error == ENOENT)
1177 return;
1178 ASSERT(error == 0);
1179
1180 error = ddt_object_count(ddt, type, class, &count);
1181 ASSERT(error == 0);
1182 if (count == 0)
1183 return;
1184
1185 dspace = doi.doi_physical_blocks_512 << 9;
1186 mspace = doi.doi_fill_count * doi.doi_data_block_size;
1187
1188 ddt_object_name(ddt, type, class, name);
1189
1190 (void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
1191 name,
1192 (u_longlong_t)count,
1193 (u_longlong_t)(dspace / count),
1194 (u_longlong_t)(mspace / count));
1195
1196 if (dump_opt['D'] < 3)
1197 return;
1198
1199 zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
1200
1201 if (dump_opt['D'] < 4)
1202 return;
1203
1204 if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
1205 return;
1206
1207 (void) printf("%s contents:\n\n", name);
1208
1209 while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
1210 dump_dde(ddt, &dde, walk);
1211
1212 ASSERT3U(error, ==, ENOENT);
1213
1214 (void) printf("\n");
1215 }
1216
1217 static void
1218 dump_all_ddts(spa_t *spa)
1219 {
1220 ddt_histogram_t ddh_total;
1221 ddt_stat_t dds_total;
1222
1223 bzero(&ddh_total, sizeof (ddh_total));
1224 bzero(&dds_total, sizeof (dds_total));
1225
1226 for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1227 ddt_t *ddt = spa->spa_ddt[c];
1228 for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
1229 for (enum ddt_class class = 0; class < DDT_CLASSES;
1230 class++) {
1231 dump_ddt(ddt, type, class);
1232 }
1233 }
1234 }
1235
1236 ddt_get_dedup_stats(spa, &dds_total);
1237
1238 if (dds_total.dds_blocks == 0) {
1239 (void) printf("All DDTs are empty\n");
1240 return;
1241 }
1242
1243 (void) printf("\n");
1244
1245 if (dump_opt['D'] > 1) {
1246 (void) printf("DDT histogram (aggregated over all DDTs):\n");
1247 ddt_get_dedup_histogram(spa, &ddh_total);
1248 zpool_dump_ddt(&dds_total, &ddh_total);
1249 }
1250
1251 dump_dedup_ratio(&dds_total);
1252 }
1253
1254 static void
1255 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
1256 {
1257 char *prefix = arg;
1258
1259 (void) printf("%s [%llu,%llu) length %llu\n",
1260 prefix,
1261 (u_longlong_t)start,
1262 (u_longlong_t)(start + size),
1263 (u_longlong_t)(size));
1264 }
1265
1266 static void
1267 dump_dtl(vdev_t *vd, int indent)
1268 {
1269 spa_t *spa = vd->vdev_spa;
1270 boolean_t required;
1271 const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
1272 "outage" };
1273 char prefix[256];
1274
1275 spa_vdev_state_enter(spa, SCL_NONE);
1276 required = vdev_dtl_required(vd);
1277 (void) spa_vdev_state_exit(spa, NULL, 0);
1278
1279 if (indent == 0)
1280 (void) printf("\nDirty time logs:\n\n");
1281
1282 (void) printf("\t%*s%s [%s]\n", indent, "",
1283 vd->vdev_path ? vd->vdev_path :
1284 vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
1285 required ? "DTL-required" : "DTL-expendable");
1286
1287 for (int t = 0; t < DTL_TYPES; t++) {
1288 range_tree_t *rt = vd->vdev_dtl[t];
1289 if (range_tree_space(rt) == 0)
1290 continue;
1291 (void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
1292 indent + 2, "", name[t]);
1293 range_tree_walk(rt, dump_dtl_seg, prefix);
1294 if (dump_opt['d'] > 5 && vd->vdev_children == 0)
1295 dump_spacemap(spa->spa_meta_objset,
1296 vd->vdev_dtl_sm);
1297 }
1298
1299 for (unsigned c = 0; c < vd->vdev_children; c++)
1300 dump_dtl(vd->vdev_child[c], indent + 4);
1301 }
1302
1303 static void
1304 dump_history(spa_t *spa)
1305 {
1306 nvlist_t **events = NULL;
1307 char *buf;
1308 uint64_t resid, len, off = 0;
1309 uint_t num = 0;
1310 int error;
1311 time_t tsec;
1312 struct tm t;
1313 char tbuf[30];
1314 char internalstr[MAXPATHLEN];
1315
1316 if ((buf = malloc(SPA_OLD_MAXBLOCKSIZE)) == NULL) {
1317 (void) fprintf(stderr, "%s: unable to allocate I/O buffer\n",
1318 __func__);
1319 return;
1320 }
1321
1322 do {
1323 len = SPA_OLD_MAXBLOCKSIZE;
1324
1325 if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
1326 (void) fprintf(stderr, "Unable to read history: "
1327 "error %d\n", error);
1328 free(buf);
1329 return;
1330 }
1331
1332 if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
1333 break;
1334
1335 off -= resid;
1336 } while (len != 0);
1337
1338 (void) printf("\nHistory:\n");
1339 for (unsigned i = 0; i < num; i++) {
1340 uint64_t time, txg, ievent;
1341 char *cmd, *intstr;
1342 boolean_t printed = B_FALSE;
1343
1344 if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
1345 &time) != 0)
1346 goto next;
1347 if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
1348 &cmd) != 0) {
1349 if (nvlist_lookup_uint64(events[i],
1350 ZPOOL_HIST_INT_EVENT, &ievent) != 0)
1351 goto next;
1352 verify(nvlist_lookup_uint64(events[i],
1353 ZPOOL_HIST_TXG, &txg) == 0);
1354 verify(nvlist_lookup_string(events[i],
1355 ZPOOL_HIST_INT_STR, &intstr) == 0);
1356 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
1357 goto next;
1358
1359 (void) snprintf(internalstr,
1360 sizeof (internalstr),
1361 "[internal %s txg:%lld] %s",
1362 zfs_history_event_names[ievent],
1363 (longlong_t)txg, intstr);
1364 cmd = internalstr;
1365 }
1366 tsec = time;
1367 (void) localtime_r(&tsec, &t);
1368 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
1369 (void) printf("%s %s\n", tbuf, cmd);
1370 printed = B_TRUE;
1371
1372 next:
1373 if (dump_opt['h'] > 1) {
1374 if (!printed)
1375 (void) printf("unrecognized record:\n");
1376 dump_nvlist(events[i], 2);
1377 }
1378 }
1379 free(buf);
1380 }
1381
1382 /*ARGSUSED*/
1383 static void
1384 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
1385 {
1386 }
1387
1388 static uint64_t
1389 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
1390 const zbookmark_phys_t *zb)
1391 {
1392 if (dnp == NULL) {
1393 ASSERT(zb->zb_level < 0);
1394 if (zb->zb_object == 0)
1395 return (zb->zb_blkid);
1396 return (zb->zb_blkid * BP_GET_LSIZE(bp));
1397 }
1398
1399 ASSERT(zb->zb_level >= 0);
1400
1401 return ((zb->zb_blkid <<
1402 (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
1403 dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
1404 }
1405
1406 static void
1407 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp)
1408 {
1409 const dva_t *dva = bp->blk_dva;
1410 int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
1411 int i;
1412
1413 if (dump_opt['b'] >= 6) {
1414 snprintf_blkptr(blkbuf, buflen, bp);
1415 return;
1416 }
1417
1418 if (BP_IS_EMBEDDED(bp)) {
1419 (void) sprintf(blkbuf,
1420 "EMBEDDED et=%u %llxL/%llxP B=%llu",
1421 (int)BPE_GET_ETYPE(bp),
1422 (u_longlong_t)BPE_GET_LSIZE(bp),
1423 (u_longlong_t)BPE_GET_PSIZE(bp),
1424 (u_longlong_t)bp->blk_birth);
1425 return;
1426 }
1427
1428 blkbuf[0] = '\0';
1429
1430 for (i = 0; i < ndvas; i++)
1431 (void) snprintf(blkbuf + strlen(blkbuf),
1432 buflen - strlen(blkbuf), "%llu:%llx:%llx ",
1433 (u_longlong_t)DVA_GET_VDEV(&dva[i]),
1434 (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
1435 (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
1436
1437 if (BP_IS_HOLE(bp)) {
1438 (void) snprintf(blkbuf + strlen(blkbuf),
1439 buflen - strlen(blkbuf),
1440 "%llxL B=%llu",
1441 (u_longlong_t)BP_GET_LSIZE(bp),
1442 (u_longlong_t)bp->blk_birth);
1443 } else {
1444 (void) snprintf(blkbuf + strlen(blkbuf),
1445 buflen - strlen(blkbuf),
1446 "%llxL/%llxP F=%llu B=%llu/%llu",
1447 (u_longlong_t)BP_GET_LSIZE(bp),
1448 (u_longlong_t)BP_GET_PSIZE(bp),
1449 (u_longlong_t)BP_GET_FILL(bp),
1450 (u_longlong_t)bp->blk_birth,
1451 (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
1452 }
1453 }
1454
1455 static void
1456 print_indirect(blkptr_t *bp, const zbookmark_phys_t *zb,
1457 const dnode_phys_t *dnp)
1458 {
1459 char blkbuf[BP_SPRINTF_LEN];
1460 int l;
1461
1462 if (!BP_IS_EMBEDDED(bp)) {
1463 ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
1464 ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
1465 }
1466
1467 (void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
1468
1469 ASSERT(zb->zb_level >= 0);
1470
1471 for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
1472 if (l == zb->zb_level) {
1473 (void) printf("L%llx", (u_longlong_t)zb->zb_level);
1474 } else {
1475 (void) printf(" ");
1476 }
1477 }
1478
1479 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1480 (void) printf("%s\n", blkbuf);
1481 }
1482
1483 static int
1484 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
1485 blkptr_t *bp, const zbookmark_phys_t *zb)
1486 {
1487 int err = 0;
1488
1489 if (bp->blk_birth == 0)
1490 return (0);
1491
1492 print_indirect(bp, zb, dnp);
1493
1494 if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
1495 arc_flags_t flags = ARC_FLAG_WAIT;
1496 int i;
1497 blkptr_t *cbp;
1498 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1499 arc_buf_t *buf;
1500 uint64_t fill = 0;
1501
1502 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
1503 ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
1504 if (err)
1505 return (err);
1506 ASSERT(buf->b_data);
1507
1508 /* recursively visit blocks below this */
1509 cbp = buf->b_data;
1510 for (i = 0; i < epb; i++, cbp++) {
1511 zbookmark_phys_t czb;
1512
1513 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1514 zb->zb_level - 1,
1515 zb->zb_blkid * epb + i);
1516 err = visit_indirect(spa, dnp, cbp, &czb);
1517 if (err)
1518 break;
1519 fill += BP_GET_FILL(cbp);
1520 }
1521 if (!err)
1522 ASSERT3U(fill, ==, BP_GET_FILL(bp));
1523 arc_buf_destroy(buf, &buf);
1524 }
1525
1526 return (err);
1527 }
1528
1529 /*ARGSUSED*/
1530 static void
1531 dump_indirect(dnode_t *dn)
1532 {
1533 dnode_phys_t *dnp = dn->dn_phys;
1534 int j;
1535 zbookmark_phys_t czb;
1536
1537 (void) printf("Indirect blocks:\n");
1538
1539 SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1540 dn->dn_object, dnp->dn_nlevels - 1, 0);
1541 for (j = 0; j < dnp->dn_nblkptr; j++) {
1542 czb.zb_blkid = j;
1543 (void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1544 &dnp->dn_blkptr[j], &czb);
1545 }
1546
1547 (void) printf("\n");
1548 }
1549
1550 /*ARGSUSED*/
1551 static void
1552 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1553 {
1554 dsl_dir_phys_t *dd = data;
1555 time_t crtime;
1556 char nice[32];
1557
1558 /* make sure nicenum has enough space */
1559 CTASSERT(sizeof (nice) >= NN_NUMBUF_SZ);
1560
1561 if (dd == NULL)
1562 return;
1563
1564 ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1565
1566 crtime = dd->dd_creation_time;
1567 (void) printf("\t\tcreation_time = %s", ctime(&crtime));
1568 (void) printf("\t\thead_dataset_obj = %llu\n",
1569 (u_longlong_t)dd->dd_head_dataset_obj);
1570 (void) printf("\t\tparent_dir_obj = %llu\n",
1571 (u_longlong_t)dd->dd_parent_obj);
1572 (void) printf("\t\torigin_obj = %llu\n",
1573 (u_longlong_t)dd->dd_origin_obj);
1574 (void) printf("\t\tchild_dir_zapobj = %llu\n",
1575 (u_longlong_t)dd->dd_child_dir_zapobj);
1576 zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
1577 (void) printf("\t\tused_bytes = %s\n", nice);
1578 zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
1579 (void) printf("\t\tcompressed_bytes = %s\n", nice);
1580 zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
1581 (void) printf("\t\tuncompressed_bytes = %s\n", nice);
1582 zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
1583 (void) printf("\t\tquota = %s\n", nice);
1584 zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
1585 (void) printf("\t\treserved = %s\n", nice);
1586 (void) printf("\t\tprops_zapobj = %llu\n",
1587 (u_longlong_t)dd->dd_props_zapobj);
1588 (void) printf("\t\tdeleg_zapobj = %llu\n",
1589 (u_longlong_t)dd->dd_deleg_zapobj);
1590 (void) printf("\t\tflags = %llx\n",
1591 (u_longlong_t)dd->dd_flags);
1592
1593 #define DO(which) \
1594 zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
1595 sizeof (nice)); \
1596 (void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1597 DO(HEAD);
1598 DO(SNAP);
1599 DO(CHILD);
1600 DO(CHILD_RSRV);
1601 DO(REFRSRV);
1602 #undef DO
1603 (void) printf("\t\tclones = %llu\n",
1604 (u_longlong_t)dd->dd_clones);
1605 }
1606
1607 /*ARGSUSED*/
1608 static void
1609 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1610 {
1611 dsl_dataset_phys_t *ds = data;
1612 time_t crtime;
1613 char used[32], compressed[32], uncompressed[32], unique[32];
1614 char blkbuf[BP_SPRINTF_LEN];
1615
1616 /* make sure nicenum has enough space */
1617 CTASSERT(sizeof (used) >= NN_NUMBUF_SZ);
1618 CTASSERT(sizeof (compressed) >= NN_NUMBUF_SZ);
1619 CTASSERT(sizeof (uncompressed) >= NN_NUMBUF_SZ);
1620 CTASSERT(sizeof (unique) >= NN_NUMBUF_SZ);
1621
1622 if (ds == NULL)
1623 return;
1624
1625 ASSERT(size == sizeof (*ds));
1626 crtime = ds->ds_creation_time;
1627 zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
1628 zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
1629 zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
1630 sizeof (uncompressed));
1631 zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
1632 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
1633
1634 (void) printf("\t\tdir_obj = %llu\n",
1635 (u_longlong_t)ds->ds_dir_obj);
1636 (void) printf("\t\tprev_snap_obj = %llu\n",
1637 (u_longlong_t)ds->ds_prev_snap_obj);
1638 (void) printf("\t\tprev_snap_txg = %llu\n",
1639 (u_longlong_t)ds->ds_prev_snap_txg);
1640 (void) printf("\t\tnext_snap_obj = %llu\n",
1641 (u_longlong_t)ds->ds_next_snap_obj);
1642 (void) printf("\t\tsnapnames_zapobj = %llu\n",
1643 (u_longlong_t)ds->ds_snapnames_zapobj);
1644 (void) printf("\t\tnum_children = %llu\n",
1645 (u_longlong_t)ds->ds_num_children);
1646 (void) printf("\t\tuserrefs_obj = %llu\n",
1647 (u_longlong_t)ds->ds_userrefs_obj);
1648 (void) printf("\t\tcreation_time = %s", ctime(&crtime));
1649 (void) printf("\t\tcreation_txg = %llu\n",
1650 (u_longlong_t)ds->ds_creation_txg);
1651 (void) printf("\t\tdeadlist_obj = %llu\n",
1652 (u_longlong_t)ds->ds_deadlist_obj);
1653 (void) printf("\t\tused_bytes = %s\n", used);
1654 (void) printf("\t\tcompressed_bytes = %s\n", compressed);
1655 (void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1656 (void) printf("\t\tunique = %s\n", unique);
1657 (void) printf("\t\tfsid_guid = %llu\n",
1658 (u_longlong_t)ds->ds_fsid_guid);
1659 (void) printf("\t\tguid = %llu\n",
1660 (u_longlong_t)ds->ds_guid);
1661 (void) printf("\t\tflags = %llx\n",
1662 (u_longlong_t)ds->ds_flags);
1663 (void) printf("\t\tnext_clones_obj = %llu\n",
1664 (u_longlong_t)ds->ds_next_clones_obj);
1665 (void) printf("\t\tprops_obj = %llu\n",
1666 (u_longlong_t)ds->ds_props_obj);
1667 (void) printf("\t\tbp = %s\n", blkbuf);
1668 }
1669
1670 /* ARGSUSED */
1671 static int
1672 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1673 {
1674 char blkbuf[BP_SPRINTF_LEN];
1675
1676 if (bp->blk_birth != 0) {
1677 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
1678 (void) printf("\t%s\n", blkbuf);
1679 }
1680 return (0);
1681 }
1682
1683 static void
1684 dump_bptree(objset_t *os, uint64_t obj, const char *name)
1685 {
1686 char bytes[32];
1687 bptree_phys_t *bt;
1688 dmu_buf_t *db;
1689
1690 /* make sure nicenum has enough space */
1691 CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1692
1693 if (dump_opt['d'] < 3)
1694 return;
1695
1696 VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
1697 bt = db->db_data;
1698 zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
1699 (void) printf("\n %s: %llu datasets, %s\n",
1700 name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
1701 dmu_buf_rele(db, FTAG);
1702
1703 if (dump_opt['d'] < 5)
1704 return;
1705
1706 (void) printf("\n");
1707
1708 (void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
1709 }
1710
1711 /* ARGSUSED */
1712 static int
1713 dump_bpobj_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1714 {
1715 char blkbuf[BP_SPRINTF_LEN];
1716
1717 ASSERT(bp->blk_birth != 0);
1718 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1719 (void) printf("\t%s\n", blkbuf);
1720 return (0);
1721 }
1722
1723 static void
1724 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
1725 {
1726 char bytes[32];
1727 char comp[32];
1728 char uncomp[32];
1729 uint64_t i;
1730
1731 /* make sure nicenum has enough space */
1732 CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1733 CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1734 CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1735
1736 if (dump_opt['d'] < 3)
1737 return;
1738
1739 zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
1740 if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1741 zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
1742 zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
1743 (void) printf(" %*s: object %llu, %llu local blkptrs, "
1744 "%llu subobjs in object, %llu, %s (%s/%s comp)\n",
1745 indent * 8, name,
1746 (u_longlong_t)bpo->bpo_object,
1747 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1748 (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1749 (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
1750 bytes, comp, uncomp);
1751
1752 for (i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1753 uint64_t subobj;
1754 bpobj_t subbpo;
1755 int error;
1756 VERIFY0(dmu_read(bpo->bpo_os,
1757 bpo->bpo_phys->bpo_subobjs,
1758 i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1759 error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1760 if (error != 0) {
1761 (void) printf("ERROR %u while trying to open "
1762 "subobj id %llu\n",
1763 error, (u_longlong_t)subobj);
1764 continue;
1765 }
1766 dump_full_bpobj(&subbpo, "subobj", indent + 1);
1767 bpobj_close(&subbpo);
1768 }
1769 } else {
1770 (void) printf(" %*s: object %llu, %llu blkptrs, %s\n",
1771 indent * 8, name,
1772 (u_longlong_t)bpo->bpo_object,
1773 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1774 bytes);
1775 }
1776
1777 if (dump_opt['d'] < 5)
1778 return;
1779
1780
1781 if (indent == 0) {
1782 (void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1783 (void) printf("\n");
1784 }
1785 }
1786
1787 static void
1788 bpobj_count_refd(bpobj_t *bpo)
1789 {
1790 mos_obj_refd(bpo->bpo_object);
1791
1792 if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1793 mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
1794 for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1795 uint64_t subobj;
1796 bpobj_t subbpo;
1797 int error;
1798 VERIFY0(dmu_read(bpo->bpo_os,
1799 bpo->bpo_phys->bpo_subobjs,
1800 i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1801 error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1802 if (error != 0) {
1803 (void) printf("ERROR %u while trying to open "
1804 "subobj id %llu\n",
1805 error, (u_longlong_t)subobj);
1806 continue;
1807 }
1808 bpobj_count_refd(&subbpo);
1809 bpobj_close(&subbpo);
1810 }
1811 }
1812 }
1813
1814 static void
1815 dump_deadlist(dsl_deadlist_t *dl)
1816 {
1817 dsl_deadlist_entry_t *dle;
1818 uint64_t unused;
1819 char bytes[32];
1820 char comp[32];
1821 char uncomp[32];
1822 uint64_t empty_bpobj =
1823 dmu_objset_spa(dl->dl_os)->spa_dsl_pool->dp_empty_bpobj;
1824
1825 /* force the tree to be loaded */
1826 dsl_deadlist_space_range(dl, 0, UINT64_MAX, &unused, &unused, &unused);
1827
1828 if (dl->dl_oldfmt) {
1829 if (dl->dl_bpobj.bpo_object != empty_bpobj)
1830 bpobj_count_refd(&dl->dl_bpobj);
1831 } else {
1832 mos_obj_refd(dl->dl_object);
1833 for (dle = avl_first(&dl->dl_tree); dle;
1834 dle = AVL_NEXT(&dl->dl_tree, dle)) {
1835 if (dle->dle_bpobj.bpo_object != empty_bpobj)
1836 bpobj_count_refd(&dle->dle_bpobj);
1837 }
1838 }
1839
1840 /* make sure nicenum has enough space */
1841 CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1842 CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1843 CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1844
1845 if (dump_opt['d'] < 3)
1846 return;
1847
1848 if (dl->dl_oldfmt) {
1849 dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
1850 return;
1851 }
1852
1853 zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
1854 zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
1855 zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
1856 (void) printf("\n Deadlist: %s (%s/%s comp)\n",
1857 bytes, comp, uncomp);
1858
1859 if (dump_opt['d'] < 4)
1860 return;
1861
1862 (void) printf("\n");
1863
1864 for (dle = avl_first(&dl->dl_tree); dle;
1865 dle = AVL_NEXT(&dl->dl_tree, dle)) {
1866 if (dump_opt['d'] >= 5) {
1867 char buf[128];
1868 (void) snprintf(buf, sizeof (buf),
1869 "mintxg %llu -> obj %llu",
1870 (longlong_t)dle->dle_mintxg,
1871 (longlong_t)dle->dle_bpobj.bpo_object);
1872
1873 dump_full_bpobj(&dle->dle_bpobj, buf, 0);
1874 } else {
1875 (void) printf("mintxg %llu -> obj %llu\n",
1876 (longlong_t)dle->dle_mintxg,
1877 (longlong_t)dle->dle_bpobj.bpo_object);
1878 }
1879 }
1880 }
1881
1882 static avl_tree_t idx_tree;
1883 static avl_tree_t domain_tree;
1884 static boolean_t fuid_table_loaded;
1885 static objset_t *sa_os = NULL;
1886 static sa_attr_type_t *sa_attr_table = NULL;
1887
1888 static int
1889 open_objset(const char *path, dmu_objset_type_t type, void *tag, objset_t **osp)
1890 {
1891 int err;
1892 uint64_t sa_attrs = 0;
1893 uint64_t version = 0;
1894
1895 VERIFY3P(sa_os, ==, NULL);
1896 err = dmu_objset_own(path, type, B_TRUE, B_FALSE, tag, osp);
1897 if (err != 0) {
1898 (void) fprintf(stderr, "failed to own dataset '%s': %s\n", path,
1899 strerror(err));
1900 return (err);
1901 }
1902
1903 if (dmu_objset_type(*osp) == DMU_OST_ZFS && !(*osp)->os_encrypted) {
1904 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1905 8, 1, &version);
1906 if (version >= ZPL_VERSION_SA) {
1907 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1908 8, 1, &sa_attrs);
1909 }
1910 err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
1911 &sa_attr_table);
1912 if (err != 0) {
1913 (void) fprintf(stderr, "sa_setup failed: %s\n",
1914 strerror(err));
1915 dmu_objset_disown(*osp, B_FALSE, tag);
1916 *osp = NULL;
1917 }
1918 }
1919 sa_os = *osp;
1920
1921 return (0);
1922 }
1923
1924 static void
1925 close_objset(objset_t *os, void *tag)
1926 {
1927 VERIFY3P(os, ==, sa_os);
1928 if (os->os_sa != NULL)
1929 sa_tear_down(os);
1930 dmu_objset_disown(os, B_FALSE, tag);
1931 sa_attr_table = NULL;
1932 sa_os = NULL;
1933 }
1934
1935 static void
1936 fuid_table_destroy(void)
1937 {
1938 if (fuid_table_loaded) {
1939 zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1940 fuid_table_loaded = B_FALSE;
1941 }
1942 }
1943
1944 /*
1945 * print uid or gid information.
1946 * For normal POSIX id just the id is printed in decimal format.
1947 * For CIFS files with FUID the fuid is printed in hex followed by
1948 * the domain-rid string.
1949 */
1950 static void
1951 print_idstr(uint64_t id, const char *id_type)
1952 {
1953 if (FUID_INDEX(id)) {
1954 char *domain;
1955
1956 domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1957 (void) printf("\t%s %llx [%s-%d]\n", id_type,
1958 (u_longlong_t)id, domain, (int)FUID_RID(id));
1959 } else {
1960 (void) printf("\t%s %llu\n", id_type, (u_longlong_t)id);
1961 }
1962
1963 }
1964
1965 static void
1966 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
1967 {
1968 uint32_t uid_idx, gid_idx;
1969
1970 uid_idx = FUID_INDEX(uid);
1971 gid_idx = FUID_INDEX(gid);
1972
1973 /* Load domain table, if not already loaded */
1974 if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1975 uint64_t fuid_obj;
1976
1977 /* first find the fuid object. It lives in the master node */
1978 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1979 8, 1, &fuid_obj) == 0);
1980 zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1981 (void) zfs_fuid_table_load(os, fuid_obj,
1982 &idx_tree, &domain_tree);
1983 fuid_table_loaded = B_TRUE;
1984 }
1985
1986 print_idstr(uid, "uid");
1987 print_idstr(gid, "gid");
1988 }
1989
1990 static void
1991 dump_znode_sa_xattr(sa_handle_t *hdl)
1992 {
1993 nvlist_t *sa_xattr;
1994 nvpair_t *elem = NULL;
1995 int sa_xattr_size = 0;
1996 int sa_xattr_entries = 0;
1997 int error;
1998 char *sa_xattr_packed;
1999
2000 error = sa_size(hdl, sa_attr_table[ZPL_DXATTR], &sa_xattr_size);
2001 if (error || sa_xattr_size == 0)
2002 return;
2003
2004 sa_xattr_packed = malloc(sa_xattr_size);
2005 if (sa_xattr_packed == NULL)
2006 return;
2007
2008 error = sa_lookup(hdl, sa_attr_table[ZPL_DXATTR],
2009 sa_xattr_packed, sa_xattr_size);
2010 if (error) {
2011 free(sa_xattr_packed);
2012 return;
2013 }
2014
2015 error = nvlist_unpack(sa_xattr_packed, sa_xattr_size, &sa_xattr, 0);
2016 if (error) {
2017 free(sa_xattr_packed);
2018 return;
2019 }
2020
2021 while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL)
2022 sa_xattr_entries++;
2023
2024 (void) printf("\tSA xattrs: %d bytes, %d entries\n\n",
2025 sa_xattr_size, sa_xattr_entries);
2026 while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL) {
2027 uchar_t *value;
2028 uint_t cnt, idx;
2029
2030 (void) printf("\t\t%s = ", nvpair_name(elem));
2031 nvpair_value_byte_array(elem, &value, &cnt);
2032 for (idx = 0; idx < cnt; ++idx) {
2033 if (isprint(value[idx]))
2034 (void) putchar(value[idx]);
2035 else
2036 (void) printf("\\%3.3o", value[idx]);
2037 }
2038 (void) putchar('\n');
2039 }
2040
2041 nvlist_free(sa_xattr);
2042 free(sa_xattr_packed);
2043 }
2044
2045 /*ARGSUSED*/
2046 static void
2047 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
2048 {
2049 char path[MAXPATHLEN * 2]; /* allow for xattr and failure prefix */
2050 sa_handle_t *hdl;
2051 uint64_t xattr, rdev, gen;
2052 uint64_t uid, gid, mode, fsize, parent, links;
2053 uint64_t pflags;
2054 uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
2055 time_t z_crtime, z_atime, z_mtime, z_ctime;
2056 sa_bulk_attr_t bulk[12];
2057 int idx = 0;
2058 int error;
2059
2060 VERIFY3P(os, ==, sa_os);
2061 if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
2062 (void) printf("Failed to get handle for SA znode\n");
2063 return;
2064 }
2065
2066 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
2067 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
2068 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
2069 &links, 8);
2070 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
2071 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
2072 &mode, 8);
2073 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
2074 NULL, &parent, 8);
2075 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
2076 &fsize, 8);
2077 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
2078 acctm, 16);
2079 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
2080 modtm, 16);
2081 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
2082 crtm, 16);
2083 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
2084 chgtm, 16);
2085 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
2086 &pflags, 8);
2087
2088 if (sa_bulk_lookup(hdl, bulk, idx)) {
2089 (void) sa_handle_destroy(hdl);
2090 return;
2091 }
2092
2093 z_crtime = (time_t)crtm[0];
2094 z_atime = (time_t)acctm[0];
2095 z_mtime = (time_t)modtm[0];
2096 z_ctime = (time_t)chgtm[0];
2097
2098 if (dump_opt['d'] > 4) {
2099 error = zfs_obj_to_path(os, object, path, sizeof (path));
2100 if (error == ESTALE) {
2101 (void) snprintf(path, sizeof (path), "on delete queue");
2102 } else if (error != 0) {
2103 leaked_objects++;
2104 (void) snprintf(path, sizeof (path),
2105 "path not found, possibly leaked");
2106 }
2107 (void) printf("\tpath %s\n", path);
2108 }
2109 dump_uidgid(os, uid, gid);
2110 (void) printf("\tatime %s", ctime(&z_atime));
2111 (void) printf("\tmtime %s", ctime(&z_mtime));
2112 (void) printf("\tctime %s", ctime(&z_ctime));
2113 (void) printf("\tcrtime %s", ctime(&z_crtime));
2114 (void) printf("\tgen %llu\n", (u_longlong_t)gen);
2115 (void) printf("\tmode %llo\n", (u_longlong_t)mode);
2116 (void) printf("\tsize %llu\n", (u_longlong_t)fsize);
2117 (void) printf("\tparent %llu\n", (u_longlong_t)parent);
2118 (void) printf("\tlinks %llu\n", (u_longlong_t)links);
2119 (void) printf("\tpflags %llx\n", (u_longlong_t)pflags);
2120 if (dmu_objset_projectquota_enabled(os) && (pflags & ZFS_PROJID)) {
2121 uint64_t projid;
2122
2123 if (sa_lookup(hdl, sa_attr_table[ZPL_PROJID], &projid,
2124 sizeof (uint64_t)) == 0)
2125 (void) printf("\tprojid %llu\n", (u_longlong_t)projid);
2126 }
2127 if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
2128 sizeof (uint64_t)) == 0)
2129 (void) printf("\txattr %llu\n", (u_longlong_t)xattr);
2130 if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
2131 sizeof (uint64_t)) == 0)
2132 (void) printf("\trdev 0x%016llx\n", (u_longlong_t)rdev);
2133 dump_znode_sa_xattr(hdl);
2134 sa_handle_destroy(hdl);
2135 }
2136
2137 /*ARGSUSED*/
2138 static void
2139 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
2140 {
2141 }
2142
2143 /*ARGSUSED*/
2144 static void
2145 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
2146 {
2147 }
2148
2149 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
2150 dump_none, /* unallocated */
2151 dump_zap, /* object directory */
2152 dump_uint64, /* object array */
2153 dump_none, /* packed nvlist */
2154 dump_packed_nvlist, /* packed nvlist size */
2155 dump_none, /* bpobj */
2156 dump_bpobj, /* bpobj header */
2157 dump_none, /* SPA space map header */
2158 dump_none, /* SPA space map */
2159 dump_none, /* ZIL intent log */
2160 dump_dnode, /* DMU dnode */
2161 dump_dmu_objset, /* DMU objset */
2162 dump_dsl_dir, /* DSL directory */
2163 dump_zap, /* DSL directory child map */
2164 dump_zap, /* DSL dataset snap map */
2165 dump_zap, /* DSL props */
2166 dump_dsl_dataset, /* DSL dataset */
2167 dump_znode, /* ZFS znode */
2168 dump_acl, /* ZFS V0 ACL */
2169 dump_uint8, /* ZFS plain file */
2170 dump_zpldir, /* ZFS directory */
2171 dump_zap, /* ZFS master node */
2172 dump_zap, /* ZFS delete queue */
2173 dump_uint8, /* zvol object */
2174 dump_zap, /* zvol prop */
2175 dump_uint8, /* other uint8[] */
2176 dump_uint64, /* other uint64[] */
2177 dump_zap, /* other ZAP */
2178 dump_zap, /* persistent error log */
2179 dump_uint8, /* SPA history */
2180 dump_history_offsets, /* SPA history offsets */
2181 dump_zap, /* Pool properties */
2182 dump_zap, /* DSL permissions */
2183 dump_acl, /* ZFS ACL */
2184 dump_uint8, /* ZFS SYSACL */
2185 dump_none, /* FUID nvlist */
2186 dump_packed_nvlist, /* FUID nvlist size */
2187 dump_zap, /* DSL dataset next clones */
2188 dump_zap, /* DSL scrub queue */
2189 dump_zap, /* ZFS user/group/project used */
2190 dump_zap, /* ZFS user/group/project quota */
2191 dump_zap, /* snapshot refcount tags */
2192 dump_ddt_zap, /* DDT ZAP object */
2193 dump_zap, /* DDT statistics */
2194 dump_znode, /* SA object */
2195 dump_zap, /* SA Master Node */
2196 dump_sa_attrs, /* SA attribute registration */
2197 dump_sa_layouts, /* SA attribute layouts */
2198 dump_zap, /* DSL scrub translations */
2199 dump_none, /* fake dedup BP */
2200 dump_zap, /* deadlist */
2201 dump_none, /* deadlist hdr */
2202 dump_zap, /* dsl clones */
2203 dump_bpobj_subobjs, /* bpobj subobjs */
2204 dump_unknown, /* Unknown type, must be last */
2205 };
2206
2207 static void
2208 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header,
2209 uint64_t *dnode_slots_used)
2210 {
2211 dmu_buf_t *db = NULL;
2212 dmu_object_info_t doi;
2213 dnode_t *dn;
2214 boolean_t dnode_held = B_FALSE;
2215 void *bonus = NULL;
2216 size_t bsize = 0;
2217 char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
2218 char bonus_size[32];
2219 char aux[50];
2220 int error;
2221
2222 /* make sure nicenum has enough space */
2223 CTASSERT(sizeof (iblk) >= NN_NUMBUF_SZ);
2224 CTASSERT(sizeof (dblk) >= NN_NUMBUF_SZ);
2225 CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
2226 CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
2227 CTASSERT(sizeof (bonus_size) >= NN_NUMBUF_SZ);
2228
2229 if (*print_header) {
2230 (void) printf("\n%10s %3s %5s %5s %5s %6s %5s %6s %s\n",
2231 "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
2232 "lsize", "%full", "type");
2233 *print_header = 0;
2234 }
2235
2236 if (object == 0) {
2237 dn = DMU_META_DNODE(os);
2238 dmu_object_info_from_dnode(dn, &doi);
2239 } else {
2240 /*
2241 * Encrypted datasets will have sensitive bonus buffers
2242 * encrypted. Therefore we cannot hold the bonus buffer and
2243 * must hold the dnode itself instead.
2244 */
2245 error = dmu_object_info(os, object, &doi);
2246 if (error)
2247 fatal("dmu_object_info() failed, errno %u", error);
2248
2249 if (os->os_encrypted &&
2250 DMU_OT_IS_ENCRYPTED(doi.doi_bonus_type)) {
2251 error = dnode_hold(os, object, FTAG, &dn);
2252 if (error)
2253 fatal("dnode_hold() failed, errno %u", error);
2254 dnode_held = B_TRUE;
2255 } else {
2256 error = dmu_bonus_hold(os, object, FTAG, &db);
2257 if (error)
2258 fatal("dmu_bonus_hold(%llu) failed, errno %u",
2259 object, error);
2260 bonus = db->db_data;
2261 bsize = db->db_size;
2262 dn = DB_DNODE((dmu_buf_impl_t *)db);
2263 }
2264 }
2265
2266 if (dnode_slots_used)
2267 *dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
2268
2269 zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
2270 zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
2271 zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
2272 zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
2273 zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
2274 zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
2275 (void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
2276 doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
2277 doi.doi_max_offset);
2278
2279 aux[0] = '\0';
2280
2281 if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
2282 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
2283 " (K=%s)", ZDB_CHECKSUM_NAME(doi.doi_checksum));
2284 }
2285
2286 if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
2287 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
2288 " (Z=%s)", ZDB_COMPRESS_NAME(doi.doi_compress));
2289 }
2290
2291 (void) printf("%10lld %3u %5s %5s %5s %6s %5s %6s %s%s\n",
2292 (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
2293 asize, dnsize, lsize, fill, zdb_ot_name(doi.doi_type), aux);
2294
2295 if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
2296 (void) printf("%10s %3s %5s %5s %5s %5s %5s %6s %s\n",
2297 "", "", "", "", "", "", bonus_size, "bonus",
2298 zdb_ot_name(doi.doi_bonus_type));
2299 }
2300
2301 if (verbosity >= 4) {
2302 (void) printf("\tdnode flags: %s%s%s%s\n",
2303 (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
2304 "USED_BYTES " : "",
2305 (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
2306 "USERUSED_ACCOUNTED " : "",
2307 (dn->dn_phys->dn_flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) ?
2308 "USEROBJUSED_ACCOUNTED " : "",
2309 (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
2310 "SPILL_BLKPTR" : "");
2311 (void) printf("\tdnode maxblkid: %llu\n",
2312 (longlong_t)dn->dn_phys->dn_maxblkid);
2313
2314 if (!dnode_held) {
2315 object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os,
2316 object, bonus, bsize);
2317 } else {
2318 (void) printf("\t\t(bonus encrypted)\n");
2319 }
2320
2321 if (!os->os_encrypted || !DMU_OT_IS_ENCRYPTED(doi.doi_type)) {
2322 object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object,
2323 NULL, 0);
2324 } else {
2325 (void) printf("\t\t(object encrypted)\n");
2326 }
2327
2328 *print_header = 1;
2329 }
2330
2331 if (verbosity >= 5)
2332 dump_indirect(dn);
2333
2334 if (verbosity >= 5) {
2335 /*
2336 * Report the list of segments that comprise the object.
2337 */
2338 uint64_t start = 0;
2339 uint64_t end;
2340 uint64_t blkfill = 1;
2341 int minlvl = 1;
2342
2343 if (dn->dn_type == DMU_OT_DNODE) {
2344 minlvl = 0;
2345 blkfill = DNODES_PER_BLOCK;
2346 }
2347
2348 for (;;) {
2349 char segsize[32];
2350 /* make sure nicenum has enough space */
2351 CTASSERT(sizeof (segsize) >= NN_NUMBUF_SZ);
2352 error = dnode_next_offset(dn,
2353 0, &start, minlvl, blkfill, 0);
2354 if (error)
2355 break;
2356 end = start;
2357 error = dnode_next_offset(dn,
2358 DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
2359 zdb_nicenum(end - start, segsize, sizeof (segsize));
2360 (void) printf("\t\tsegment [%016llx, %016llx)"
2361 " size %5s\n", (u_longlong_t)start,
2362 (u_longlong_t)end, segsize);
2363 if (error)
2364 break;
2365 start = end;
2366 }
2367 }
2368
2369 if (db != NULL)
2370 dmu_buf_rele(db, FTAG);
2371 if (dnode_held)
2372 dnode_rele(dn, FTAG);
2373 }
2374
2375 static void
2376 count_dir_mos_objects(dsl_dir_t *dd)
2377 {
2378 mos_obj_refd(dd->dd_object);
2379 mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
2380 mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
2381 mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
2382 mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
2383
2384 /*
2385 * The dd_crypto_obj can be referenced by multiple dsl_dir's.
2386 * Ignore the references after the first one.
2387 */
2388 mos_obj_refd_multiple(dd->dd_crypto_obj);
2389 }
2390
2391 static void
2392 count_ds_mos_objects(dsl_dataset_t *ds)
2393 {
2394 mos_obj_refd(ds->ds_object);
2395 mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
2396 mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
2397 mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
2398 mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
2399
2400 if (!dsl_dataset_is_snapshot(ds)) {
2401 count_dir_mos_objects(ds->ds_dir);
2402 }
2403 }
2404
2405 static const char *objset_types[DMU_OST_NUMTYPES] = {
2406 "NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
2407
2408 static void
2409 dump_dir(objset_t *os)
2410 {
2411 dmu_objset_stats_t dds;
2412 uint64_t object, object_count;
2413 uint64_t refdbytes, usedobjs, scratch;
2414 char numbuf[32];
2415 char blkbuf[BP_SPRINTF_LEN + 20];
2416 char osname[ZFS_MAX_DATASET_NAME_LEN];
2417 const char *type = "UNKNOWN";
2418 int verbosity = dump_opt['d'];
2419 int print_header = 1;
2420 unsigned i;
2421 int error;
2422 uint64_t total_slots_used = 0;
2423 uint64_t max_slot_used = 0;
2424 uint64_t dnode_slots;
2425
2426 /* make sure nicenum has enough space */
2427 CTASSERT(sizeof (numbuf) >= NN_NUMBUF_SZ);
2428
2429 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2430 dmu_objset_fast_stat(os, &dds);
2431 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2432
2433 if (dds.dds_type < DMU_OST_NUMTYPES)
2434 type = objset_types[dds.dds_type];
2435
2436 if (dds.dds_type == DMU_OST_META) {
2437 dds.dds_creation_txg = TXG_INITIAL;
2438 usedobjs = BP_GET_FILL(os->os_rootbp);
2439 refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
2440 dd_used_bytes;
2441 } else {
2442 dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
2443 }
2444
2445 ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
2446
2447 zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
2448
2449 if (verbosity >= 4) {
2450 (void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
2451 (void) snprintf_blkptr(blkbuf + strlen(blkbuf),
2452 sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
2453 } else {
2454 blkbuf[0] = '\0';
2455 }
2456
2457 dmu_objset_name(os, osname);
2458
2459 (void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
2460 "%s, %llu objects%s%s\n",
2461 osname, type, (u_longlong_t)dmu_objset_id(os),
2462 (u_longlong_t)dds.dds_creation_txg,
2463 numbuf, (u_longlong_t)usedobjs, blkbuf,
2464 (dds.dds_inconsistent) ? " (inconsistent)" : "");
2465
2466 if (zopt_objects != 0) {
2467 for (i = 0; i < zopt_objects; i++)
2468 dump_object(os, zopt_object[i], verbosity,
2469 &print_header, NULL);
2470 (void) printf("\n");
2471 return;
2472 }
2473
2474 if (dump_opt['i'] != 0 || verbosity >= 2)
2475 dump_intent_log(dmu_objset_zil(os));
2476
2477 if (dmu_objset_ds(os) != NULL) {
2478 dsl_dataset_t *ds = dmu_objset_ds(os);
2479 dump_deadlist(&ds->ds_deadlist);
2480
2481 if (dsl_dataset_remap_deadlist_exists(ds)) {
2482 (void) printf("ds_remap_deadlist:\n");
2483 dump_deadlist(&ds->ds_remap_deadlist);
2484 }
2485 count_ds_mos_objects(ds);
2486 }
2487
2488 if (verbosity < 2)
2489 return;
2490
2491 if (BP_IS_HOLE(os->os_rootbp))
2492 return;
2493
2494 dump_object(os, 0, verbosity, &print_header, NULL);
2495 object_count = 0;
2496 if (DMU_USERUSED_DNODE(os) != NULL &&
2497 DMU_USERUSED_DNODE(os)->dn_type != 0) {
2498 dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
2499 NULL);
2500 dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
2501 NULL);
2502 }
2503
2504 if (DMU_PROJECTUSED_DNODE(os) != NULL &&
2505 DMU_PROJECTUSED_DNODE(os)->dn_type != 0)
2506 dump_object(os, DMU_PROJECTUSED_OBJECT, verbosity,
2507 &print_header, NULL);
2508
2509 object = 0;
2510 while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
2511 dump_object(os, object, verbosity, &print_header, &dnode_slots);
2512 object_count++;
2513 total_slots_used += dnode_slots;
2514 max_slot_used = object + dnode_slots - 1;
2515 }
2516
2517 (void) printf("\n");
2518
2519 (void) printf(" Dnode slots:\n");
2520 (void) printf("\tTotal used: %10llu\n",
2521 (u_longlong_t)total_slots_used);
2522 (void) printf("\tMax used: %10llu\n",
2523 (u_longlong_t)max_slot_used);
2524 (void) printf("\tPercent empty: %10lf\n",
2525 (double)(max_slot_used - total_slots_used)*100 /
2526 (double)max_slot_used);
2527 (void) printf("\n");
2528
2529 if (error != ESRCH) {
2530 (void) fprintf(stderr, "dmu_object_next() = %d\n", error);
2531 abort();
2532 }
2533
2534 ASSERT3U(object_count, ==, usedobjs);
2535
2536 if (leaked_objects != 0) {
2537 (void) printf("%d potentially leaked objects detected\n",
2538 leaked_objects);
2539 leaked_objects = 0;
2540 }
2541 }
2542
2543 static void
2544 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
2545 {
2546 time_t timestamp = ub->ub_timestamp;
2547
2548 (void) printf("%s", header ? header : "");
2549 (void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
2550 (void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
2551 (void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
2552 (void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
2553 (void) printf("\ttimestamp = %llu UTC = %s",
2554 (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
2555
2556 (void) printf("\tmmp_magic = %016llx\n",
2557 (u_longlong_t)ub->ub_mmp_magic);
2558 if (MMP_VALID(ub)) {
2559 (void) printf("\tmmp_delay = %0llu\n",
2560 (u_longlong_t)ub->ub_mmp_delay);
2561 if (MMP_SEQ_VALID(ub))
2562 (void) printf("\tmmp_seq = %u\n",
2563 (unsigned int) MMP_SEQ(ub));
2564 if (MMP_FAIL_INT_VALID(ub))
2565 (void) printf("\tmmp_fail = %u\n",
2566 (unsigned int) MMP_FAIL_INT(ub));
2567 if (MMP_INTERVAL_VALID(ub))
2568 (void) printf("\tmmp_write = %u\n",
2569 (unsigned int) MMP_INTERVAL(ub));
2570 /* After MMP_* to make summarize_uberblock_mmp cleaner */
2571 (void) printf("\tmmp_valid = %x\n",
2572 (unsigned int) ub->ub_mmp_config & 0xFF);
2573 }
2574
2575 if (dump_opt['u'] >= 4) {
2576 char blkbuf[BP_SPRINTF_LEN];
2577 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
2578 (void) printf("\trootbp = %s\n", blkbuf);
2579 }
2580 (void) printf("\tcheckpoint_txg = %llu\n",
2581 (u_longlong_t)ub->ub_checkpoint_txg);
2582 (void) printf("%s", footer ? footer : "");
2583 }
2584
2585 static void
2586 dump_config(spa_t *spa)
2587 {
2588 dmu_buf_t *db;
2589 size_t nvsize = 0;
2590 int error = 0;
2591
2592
2593 error = dmu_bonus_hold(spa->spa_meta_objset,
2594 spa->spa_config_object, FTAG, &db);
2595
2596 if (error == 0) {
2597 nvsize = *(uint64_t *)db->db_data;
2598 dmu_buf_rele(db, FTAG);
2599
2600 (void) printf("\nMOS Configuration:\n");
2601 dump_packed_nvlist(spa->spa_meta_objset,
2602 spa->spa_config_object, (void *)&nvsize, 1);
2603 } else {
2604 (void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
2605 (u_longlong_t)spa->spa_config_object, error);
2606 }
2607 }
2608
2609 static void
2610 dump_cachefile(const char *cachefile)
2611 {
2612 int fd;
2613 struct stat64 statbuf;
2614 char *buf;
2615 nvlist_t *config;
2616
2617 if ((fd = open64(cachefile, O_RDONLY)) < 0) {
2618 (void) printf("cannot open '%s': %s\n", cachefile,
2619 strerror(errno));
2620 exit(1);
2621 }
2622
2623 if (fstat64(fd, &statbuf) != 0) {
2624 (void) printf("failed to stat '%s': %s\n", cachefile,
2625 strerror(errno));
2626 exit(1);
2627 }
2628
2629 if ((buf = malloc(statbuf.st_size)) == NULL) {
2630 (void) fprintf(stderr, "failed to allocate %llu bytes\n",
2631 (u_longlong_t)statbuf.st_size);
2632 exit(1);
2633 }
2634
2635 if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
2636 (void) fprintf(stderr, "failed to read %llu bytes\n",
2637 (u_longlong_t)statbuf.st_size);
2638 exit(1);
2639 }
2640
2641 (void) close(fd);
2642
2643 if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
2644 (void) fprintf(stderr, "failed to unpack nvlist\n");
2645 exit(1);
2646 }
2647
2648 free(buf);
2649
2650 dump_nvlist(config, 0);
2651
2652 nvlist_free(config);
2653 }
2654
2655 /*
2656 * ZFS label nvlist stats
2657 */
2658 typedef struct zdb_nvl_stats {
2659 int zns_list_count;
2660 int zns_leaf_count;
2661 size_t zns_leaf_largest;
2662 size_t zns_leaf_total;
2663 nvlist_t *zns_string;
2664 nvlist_t *zns_uint64;
2665 nvlist_t *zns_boolean;
2666 } zdb_nvl_stats_t;
2667
2668 static void
2669 collect_nvlist_stats(nvlist_t *nvl, zdb_nvl_stats_t *stats)
2670 {
2671 nvlist_t *list, **array;
2672 nvpair_t *nvp = NULL;
2673 char *name;
2674 uint_t i, items;
2675
2676 stats->zns_list_count++;
2677
2678 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2679 name = nvpair_name(nvp);
2680
2681 switch (nvpair_type(nvp)) {
2682 case DATA_TYPE_STRING:
2683 fnvlist_add_string(stats->zns_string, name,
2684 fnvpair_value_string(nvp));
2685 break;
2686 case DATA_TYPE_UINT64:
2687 fnvlist_add_uint64(stats->zns_uint64, name,
2688 fnvpair_value_uint64(nvp));
2689 break;
2690 case DATA_TYPE_BOOLEAN:
2691 fnvlist_add_boolean(stats->zns_boolean, name);
2692 break;
2693 case DATA_TYPE_NVLIST:
2694 if (nvpair_value_nvlist(nvp, &list) == 0)
2695 collect_nvlist_stats(list, stats);
2696 break;
2697 case DATA_TYPE_NVLIST_ARRAY:
2698 if (nvpair_value_nvlist_array(nvp, &array, &items) != 0)
2699 break;
2700
2701 for (i = 0; i < items; i++) {
2702 collect_nvlist_stats(array[i], stats);
2703
2704 /* collect stats on leaf vdev */
2705 if (strcmp(name, "children") == 0) {
2706 size_t size;
2707
2708 (void) nvlist_size(array[i], &size,
2709 NV_ENCODE_XDR);
2710 stats->zns_leaf_total += size;
2711 if (size > stats->zns_leaf_largest)
2712 stats->zns_leaf_largest = size;
2713 stats->zns_leaf_count++;
2714 }
2715 }
2716 break;
2717 default:
2718 (void) printf("skip type %d!\n", (int)nvpair_type(nvp));
2719 }
2720 }
2721 }
2722
2723 static void
2724 dump_nvlist_stats(nvlist_t *nvl, size_t cap)
2725 {
2726 zdb_nvl_stats_t stats = { 0 };
2727 size_t size, sum = 0, total;
2728 size_t noise;
2729
2730 /* requires nvlist with non-unique names for stat collection */
2731 VERIFY0(nvlist_alloc(&stats.zns_string, 0, 0));
2732 VERIFY0(nvlist_alloc(&stats.zns_uint64, 0, 0));
2733 VERIFY0(nvlist_alloc(&stats.zns_boolean, 0, 0));
2734 VERIFY0(nvlist_size(stats.zns_boolean, &noise, NV_ENCODE_XDR));
2735
2736 (void) printf("\n\nZFS Label NVList Config Stats:\n");
2737
2738 VERIFY0(nvlist_size(nvl, &total, NV_ENCODE_XDR));
2739 (void) printf(" %d bytes used, %d bytes free (using %4.1f%%)\n\n",
2740 (int)total, (int)(cap - total), 100.0 * total / cap);
2741
2742 collect_nvlist_stats(nvl, &stats);
2743
2744 VERIFY0(nvlist_size(stats.zns_uint64, &size, NV_ENCODE_XDR));
2745 size -= noise;
2746 sum += size;
2747 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "integers:",
2748 (int)fnvlist_num_pairs(stats.zns_uint64),
2749 (int)size, 100.0 * size / total);
2750
2751 VERIFY0(nvlist_size(stats.zns_string, &size, NV_ENCODE_XDR));
2752 size -= noise;
2753 sum += size;
2754 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "strings:",
2755 (int)fnvlist_num_pairs(stats.zns_string),
2756 (int)size, 100.0 * size / total);
2757
2758 VERIFY0(nvlist_size(stats.zns_boolean, &size, NV_ENCODE_XDR));
2759 size -= noise;
2760 sum += size;
2761 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "booleans:",
2762 (int)fnvlist_num_pairs(stats.zns_boolean),
2763 (int)size, 100.0 * size / total);
2764
2765 size = total - sum; /* treat remainder as nvlist overhead */
2766 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n\n", "nvlists:",
2767 stats.zns_list_count, (int)size, 100.0 * size / total);
2768
2769 if (stats.zns_leaf_count > 0) {
2770 size_t average = stats.zns_leaf_total / stats.zns_leaf_count;
2771
2772 (void) printf("%12s %4d %6d bytes average\n", "leaf vdevs:",
2773 stats.zns_leaf_count, (int)average);
2774 (void) printf("%24d bytes largest\n",
2775 (int)stats.zns_leaf_largest);
2776
2777 if (dump_opt['l'] >= 3 && average > 0)
2778 (void) printf(" space for %d additional leaf vdevs\n",
2779 (int)((cap - total) / average));
2780 }
2781 (void) printf("\n");
2782
2783 nvlist_free(stats.zns_string);
2784 nvlist_free(stats.zns_uint64);
2785 nvlist_free(stats.zns_boolean);
2786 }
2787
2788 typedef struct cksum_record {
2789 zio_cksum_t cksum;
2790 boolean_t labels[VDEV_LABELS];
2791 avl_node_t link;
2792 } cksum_record_t;
2793
2794 static int
2795 cksum_record_compare(const void *x1, const void *x2)
2796 {
2797 const cksum_record_t *l = (cksum_record_t *)x1;
2798 const cksum_record_t *r = (cksum_record_t *)x2;
2799 int arraysize = ARRAY_SIZE(l->cksum.zc_word);
2800 int difference;
2801
2802 for (int i = 0; i < arraysize; i++) {
2803 difference = AVL_CMP(l->cksum.zc_word[i], r->cksum.zc_word[i]);
2804 if (difference)
2805 break;
2806 }
2807
2808 return (difference);
2809 }
2810
2811 static cksum_record_t *
2812 cksum_record_alloc(zio_cksum_t *cksum, int l)
2813 {
2814 cksum_record_t *rec;
2815
2816 rec = umem_zalloc(sizeof (*rec), UMEM_NOFAIL);
2817 rec->cksum = *cksum;
2818 rec->labels[l] = B_TRUE;
2819
2820 return (rec);
2821 }
2822
2823 static cksum_record_t *
2824 cksum_record_lookup(avl_tree_t *tree, zio_cksum_t *cksum)
2825 {
2826 cksum_record_t lookup = { .cksum = *cksum };
2827 avl_index_t where;
2828
2829 return (avl_find(tree, &lookup, &where));
2830 }
2831
2832 static cksum_record_t *
2833 cksum_record_insert(avl_tree_t *tree, zio_cksum_t *cksum, int l)
2834 {
2835 cksum_record_t *rec;
2836
2837 rec = cksum_record_lookup(tree, cksum);
2838 if (rec) {
2839 rec->labels[l] = B_TRUE;
2840 } else {
2841 rec = cksum_record_alloc(cksum, l);
2842 avl_add(tree, rec);
2843 }
2844
2845 return (rec);
2846 }
2847
2848 static int
2849 first_label(cksum_record_t *rec)
2850 {
2851 for (int i = 0; i < VDEV_LABELS; i++)
2852 if (rec->labels[i])
2853 return (i);
2854
2855 return (-1);
2856 }
2857
2858 static void
2859 print_label_numbers(char *prefix, cksum_record_t *rec)
2860 {
2861 printf("%s", prefix);
2862 for (int i = 0; i < VDEV_LABELS; i++)
2863 if (rec->labels[i] == B_TRUE)
2864 printf("%d ", i);
2865 printf("\n");
2866 }
2867
2868 #define MAX_UBERBLOCK_COUNT (VDEV_UBERBLOCK_RING >> UBERBLOCK_SHIFT)
2869
2870 typedef struct zdb_label {
2871 vdev_label_t label;
2872 nvlist_t *config_nv;
2873 cksum_record_t *config;
2874 cksum_record_t *uberblocks[MAX_UBERBLOCK_COUNT];
2875 boolean_t header_printed;
2876 boolean_t read_failed;
2877 } zdb_label_t;
2878
2879 static void
2880 print_label_header(zdb_label_t *label, int l)
2881 {
2882
2883 if (dump_opt['q'])
2884 return;
2885
2886 if (label->header_printed == B_TRUE)
2887 return;
2888
2889 (void) printf("------------------------------------\n");
2890 (void) printf("LABEL %d\n", l);
2891 (void) printf("------------------------------------\n");
2892
2893 label->header_printed = B_TRUE;
2894 }
2895
2896 static void
2897 dump_config_from_label(zdb_label_t *label, size_t buflen, int l)
2898 {
2899 if (dump_opt['q'])
2900 return;
2901
2902 if ((dump_opt['l'] < 3) && (first_label(label->config) != l))
2903 return;
2904
2905 print_label_header(label, l);
2906 dump_nvlist(label->config_nv, 4);
2907 print_label_numbers(" labels = ", label->config);
2908
2909 if (dump_opt['l'] >= 2)
2910 dump_nvlist_stats(label->config_nv, buflen);
2911 }
2912
2913 #define ZDB_MAX_UB_HEADER_SIZE 32
2914
2915 static void
2916 dump_label_uberblocks(zdb_label_t *label, uint64_t ashift, int label_num)
2917 {
2918
2919 vdev_t vd;
2920 char header[ZDB_MAX_UB_HEADER_SIZE];
2921
2922 vd.vdev_ashift = ashift;
2923 vd.vdev_top = &vd;
2924
2925 for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
2926 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
2927 uberblock_t *ub = (void *)((char *)&label->label + uoff);
2928 cksum_record_t *rec = label->uberblocks[i];
2929
2930 if (rec == NULL) {
2931 if (dump_opt['u'] >= 2) {
2932 print_label_header(label, label_num);
2933 (void) printf(" Uberblock[%d] invalid\n", i);
2934 }
2935 continue;
2936 }
2937
2938 if ((dump_opt['u'] < 3) && (first_label(rec) != label_num))
2939 continue;
2940
2941 if ((dump_opt['u'] < 4) &&
2942 (ub->ub_mmp_magic == MMP_MAGIC) && ub->ub_mmp_delay &&
2943 (i >= VDEV_UBERBLOCK_COUNT(&vd) - MMP_BLOCKS_PER_LABEL))
2944 continue;
2945
2946 print_label_header(label, label_num);
2947 (void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
2948 " Uberblock[%d]\n", i);
2949 dump_uberblock(ub, header, "");
2950 print_label_numbers(" labels = ", rec);
2951 }
2952 }
2953
2954 static char curpath[PATH_MAX];
2955
2956 /*
2957 * Iterate through the path components, recursively passing
2958 * current one's obj and remaining path until we find the obj
2959 * for the last one.
2960 */
2961 static int
2962 dump_path_impl(objset_t *os, uint64_t obj, char *name)
2963 {
2964 int err;
2965 int header = 1;
2966 uint64_t child_obj;
2967 char *s;
2968 dmu_buf_t *db;
2969 dmu_object_info_t doi;
2970
2971 if ((s = strchr(name, '/')) != NULL)
2972 *s = '\0';
2973 err = zap_lookup(os, obj, name, 8, 1, &child_obj);
2974
2975 (void) strlcat(curpath, name, sizeof (curpath));
2976
2977 if (err != 0) {
2978 (void) fprintf(stderr, "failed to lookup %s: %s\n",
2979 curpath, strerror(err));
2980 return (err);
2981 }
2982
2983 child_obj = ZFS_DIRENT_OBJ(child_obj);
2984 err = sa_buf_hold(os, child_obj, FTAG, &db);
2985 if (err != 0) {
2986 (void) fprintf(stderr,
2987 "failed to get SA dbuf for obj %llu: %s\n",
2988 (u_longlong_t)child_obj, strerror(err));
2989 return (EINVAL);
2990 }
2991 dmu_object_info_from_db(db, &doi);
2992 sa_buf_rele(db, FTAG);
2993
2994 if (doi.doi_bonus_type != DMU_OT_SA &&
2995 doi.doi_bonus_type != DMU_OT_ZNODE) {
2996 (void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
2997 doi.doi_bonus_type, (u_longlong_t)child_obj);
2998 return (EINVAL);
2999 }
3000
3001 if (dump_opt['v'] > 6) {
3002 (void) printf("obj=%llu %s type=%d bonustype=%d\n",
3003 (u_longlong_t)child_obj, curpath, doi.doi_type,
3004 doi.doi_bonus_type);
3005 }
3006
3007 (void) strlcat(curpath, "/", sizeof (curpath));
3008
3009 switch (doi.doi_type) {
3010 case DMU_OT_DIRECTORY_CONTENTS:
3011 if (s != NULL && *(s + 1) != '\0')
3012 return (dump_path_impl(os, child_obj, s + 1));
3013 /*FALLTHROUGH*/
3014 case DMU_OT_PLAIN_FILE_CONTENTS:
3015 dump_object(os, child_obj, dump_opt['v'], &header, NULL);
3016 return (0);
3017 default:
3018 (void) fprintf(stderr, "object %llu has non-file/directory "
3019 "type %d\n", (u_longlong_t)obj, doi.doi_type);
3020 break;
3021 }
3022
3023 return (EINVAL);
3024 }
3025
3026 /*
3027 * Dump the blocks for the object specified by path inside the dataset.
3028 */
3029 static int
3030 dump_path(char *ds, char *path)
3031 {
3032 int err;
3033 objset_t *os;
3034 uint64_t root_obj;
3035
3036 err = open_objset(ds, DMU_OST_ZFS, FTAG, &os);
3037 if (err != 0)
3038 return (err);
3039
3040 err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
3041 if (err != 0) {
3042 (void) fprintf(stderr, "can't lookup root znode: %s\n",
3043 strerror(err));
3044 dmu_objset_disown(os, B_FALSE, FTAG);
3045 return (EINVAL);
3046 }
3047
3048 (void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
3049
3050 err = dump_path_impl(os, root_obj, path);
3051
3052 close_objset(os, FTAG);
3053 return (err);
3054 }
3055
3056 static int
3057 dump_label(const char *dev)
3058 {
3059 char path[MAXPATHLEN];
3060 zdb_label_t labels[VDEV_LABELS];
3061 uint64_t psize, ashift;
3062 struct stat64 statbuf;
3063 boolean_t config_found = B_FALSE;
3064 boolean_t error = B_FALSE;
3065 avl_tree_t config_tree;
3066 avl_tree_t uberblock_tree;
3067 void *node, *cookie;
3068 int fd;
3069
3070 bzero(labels, sizeof (labels));
3071
3072 /*
3073 * Check if we were given absolute path and use it as is.
3074 * Otherwise if the provided vdev name doesn't point to a file,
3075 * try prepending expected disk paths and partition numbers.
3076 */
3077 (void) strlcpy(path, dev, sizeof (path));
3078 if (dev[0] != '/' && stat64(path, &statbuf) != 0) {
3079 int error;
3080
3081 error = zfs_resolve_shortname(dev, path, MAXPATHLEN);
3082 if (error == 0 && zfs_dev_is_whole_disk(path)) {
3083 if (zfs_append_partition(path, MAXPATHLEN) == -1)
3084 error = ENOENT;
3085 }
3086
3087 if (error || (stat64(path, &statbuf) != 0)) {
3088 (void) printf("failed to find device %s, try "
3089 "specifying absolute path instead\n", dev);
3090 return (1);
3091 }
3092 }
3093
3094 if ((fd = open64(path, O_RDONLY)) < 0) {
3095 (void) printf("cannot open '%s': %s\n", path, strerror(errno));
3096 exit(1);
3097 }
3098
3099 if (fstat64_blk(fd, &statbuf) != 0) {
3100 (void) printf("failed to stat '%s': %s\n", path,
3101 strerror(errno));
3102 (void) close(fd);
3103 exit(1);
3104 }
3105
3106 if (S_ISBLK(statbuf.st_mode) && ioctl(fd, BLKFLSBUF) != 0)
3107 (void) printf("failed to invalidate cache '%s' : %s\n", path,
3108 strerror(errno));
3109
3110 avl_create(&config_tree, cksum_record_compare,
3111 sizeof (cksum_record_t), offsetof(cksum_record_t, link));
3112 avl_create(&uberblock_tree, cksum_record_compare,
3113 sizeof (cksum_record_t), offsetof(cksum_record_t, link));
3114
3115 psize = statbuf.st_size;
3116 psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
3117 ashift = SPA_MINBLOCKSHIFT;
3118
3119 /*
3120 * 1. Read the label from disk
3121 * 2. Unpack the configuration and insert in config tree.
3122 * 3. Traverse all uberblocks and insert in uberblock tree.
3123 */
3124 for (int l = 0; l < VDEV_LABELS; l++) {
3125 zdb_label_t *label = &labels[l];
3126 char *buf = label->label.vl_vdev_phys.vp_nvlist;
3127 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
3128 nvlist_t *config;
3129 cksum_record_t *rec;
3130 zio_cksum_t cksum;
3131 vdev_t vd;
3132
3133 if (pread64(fd, &label->label, sizeof (label->label),
3134 vdev_label_offset(psize, l, 0)) != sizeof (label->label)) {
3135 if (!dump_opt['q'])
3136 (void) printf("failed to read label %d\n", l);
3137 label->read_failed = B_TRUE;
3138 error = B_TRUE;
3139 continue;
3140 }
3141
3142 label->read_failed = B_FALSE;
3143
3144 if (nvlist_unpack(buf, buflen, &config, 0) == 0) {
3145 nvlist_t *vdev_tree = NULL;
3146 size_t size;
3147
3148 if ((nvlist_lookup_nvlist(config,
3149 ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
3150 (nvlist_lookup_uint64(vdev_tree,
3151 ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
3152 ashift = SPA_MINBLOCKSHIFT;
3153
3154 if (nvlist_size(config, &size, NV_ENCODE_XDR) != 0)
3155 size = buflen;
3156
3157 fletcher_4_native_varsize(buf, size, &cksum);
3158 rec = cksum_record_insert(&config_tree, &cksum, l);
3159
3160 label->config = rec;
3161 label->config_nv = config;
3162 config_found = B_TRUE;
3163 } else {
3164 error = B_TRUE;
3165 }
3166
3167 vd.vdev_ashift = ashift;
3168 vd.vdev_top = &vd;
3169
3170 for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
3171 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
3172 uberblock_t *ub = (void *)((char *)label + uoff);
3173
3174 if (uberblock_verify(ub))
3175 continue;
3176
3177 fletcher_4_native_varsize(ub, sizeof (*ub), &cksum);
3178 rec = cksum_record_insert(&uberblock_tree, &cksum, l);
3179
3180 label->uberblocks[i] = rec;
3181 }
3182 }
3183
3184 /*
3185 * Dump the label and uberblocks.
3186 */
3187 for (int l = 0; l < VDEV_LABELS; l++) {
3188 zdb_label_t *label = &labels[l];
3189 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
3190
3191 if (label->read_failed == B_TRUE)
3192 continue;
3193
3194 if (label->config_nv) {
3195 dump_config_from_label(label, buflen, l);
3196 } else {
3197 if (!dump_opt['q'])
3198 (void) printf("failed to unpack label %d\n", l);
3199 }
3200
3201 if (dump_opt['u'])
3202 dump_label_uberblocks(label, ashift, l);
3203
3204 nvlist_free(label->config_nv);
3205 }
3206
3207 cookie = NULL;
3208 while ((node = avl_destroy_nodes(&config_tree, &cookie)) != NULL)
3209 umem_free(node, sizeof (cksum_record_t));
3210
3211 cookie = NULL;
3212 while ((node = avl_destroy_nodes(&uberblock_tree, &cookie)) != NULL)
3213 umem_free(node, sizeof (cksum_record_t));
3214
3215 avl_destroy(&config_tree);
3216 avl_destroy(&uberblock_tree);
3217
3218 (void) close(fd);
3219
3220 return (config_found == B_FALSE ? 2 :
3221 (error == B_TRUE ? 1 : 0));
3222 }
3223
3224 static uint64_t dataset_feature_count[SPA_FEATURES];
3225 static uint64_t remap_deadlist_count = 0;
3226
3227 /*ARGSUSED*/
3228 static int
3229 dump_one_dir(const char *dsname, void *arg)
3230 {
3231 int error;
3232 objset_t *os;
3233 spa_feature_t f;
3234
3235 error = open_objset(dsname, DMU_OST_ANY, FTAG, &os);
3236 if (error != 0)
3237 return (0);
3238
3239 for (f = 0; f < SPA_FEATURES; f++) {
3240 if (!dsl_dataset_feature_is_active(dmu_objset_ds(os), f))
3241 continue;
3242 ASSERT(spa_feature_table[f].fi_flags &
3243 ZFEATURE_FLAG_PER_DATASET);
3244 dataset_feature_count[f]++;
3245 }
3246
3247 if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
3248 remap_deadlist_count++;
3249 }
3250
3251 dump_dir(os);
3252 close_objset(os, FTAG);
3253 fuid_table_destroy();
3254 return (0);
3255 }
3256
3257 /*
3258 * Block statistics.
3259 */
3260 #define PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
3261 typedef struct zdb_blkstats {
3262 uint64_t zb_asize;
3263 uint64_t zb_lsize;
3264 uint64_t zb_psize;
3265 uint64_t zb_count;
3266 uint64_t zb_gangs;
3267 uint64_t zb_ditto_samevdev;
3268 uint64_t zb_ditto_same_ms;
3269 uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
3270 } zdb_blkstats_t;
3271
3272 /*
3273 * Extended object types to report deferred frees and dedup auto-ditto blocks.
3274 */
3275 #define ZDB_OT_DEFERRED (DMU_OT_NUMTYPES + 0)
3276 #define ZDB_OT_DITTO (DMU_OT_NUMTYPES + 1)
3277 #define ZDB_OT_OTHER (DMU_OT_NUMTYPES + 2)
3278 #define ZDB_OT_TOTAL (DMU_OT_NUMTYPES + 3)
3279
3280 static const char *zdb_ot_extname[] = {
3281 "deferred free",
3282 "dedup ditto",
3283 "other",
3284 "Total",
3285 };
3286
3287 #define ZB_TOTAL DN_MAX_LEVELS
3288
3289 typedef struct zdb_cb {
3290 zdb_blkstats_t zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
3291 uint64_t zcb_removing_size;
3292 uint64_t zcb_checkpoint_size;
3293 uint64_t zcb_dedup_asize;
3294 uint64_t zcb_dedup_blocks;
3295 uint64_t zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
3296 uint64_t zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
3297 [BPE_PAYLOAD_SIZE + 1];
3298 uint64_t zcb_start;
3299 hrtime_t zcb_lastprint;
3300 uint64_t zcb_totalasize;
3301 uint64_t zcb_errors[256];
3302 int zcb_readfails;
3303 int zcb_haderrors;
3304 spa_t *zcb_spa;
3305 uint32_t **zcb_vd_obsolete_counts;
3306 } zdb_cb_t;
3307
3308 /* test if two DVA offsets from same vdev are within the same metaslab */
3309 static boolean_t
3310 same_metaslab(spa_t *spa, uint64_t vdev, uint64_t off1, uint64_t off2)
3311 {
3312 vdev_t *vd = vdev_lookup_top(spa, vdev);
3313 uint64_t ms_shift = vd->vdev_ms_shift;
3314
3315 return ((off1 >> ms_shift) == (off2 >> ms_shift));
3316 }
3317
3318 static void
3319 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
3320 dmu_object_type_t type)
3321 {
3322 uint64_t refcnt = 0;
3323 int i;
3324
3325 ASSERT(type < ZDB_OT_TOTAL);
3326
3327 if (zilog && zil_bp_tree_add(zilog, bp) != 0)
3328 return;
3329
3330 spa_config_enter(zcb->zcb_spa, SCL_CONFIG, FTAG, RW_READER);
3331
3332 for (i = 0; i < 4; i++) {
3333 int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
3334 int t = (i & 1) ? type : ZDB_OT_TOTAL;
3335 int equal;
3336 zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
3337
3338 zb->zb_asize += BP_GET_ASIZE(bp);
3339 zb->zb_lsize += BP_GET_LSIZE(bp);
3340 zb->zb_psize += BP_GET_PSIZE(bp);
3341 zb->zb_count++;
3342
3343 /*
3344 * The histogram is only big enough to record blocks up to
3345 * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
3346 * "other", bucket.
3347 */
3348 unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
3349 idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
3350 zb->zb_psize_histogram[idx]++;
3351
3352 zb->zb_gangs += BP_COUNT_GANG(bp);
3353
3354 switch (BP_GET_NDVAS(bp)) {
3355 case 2:
3356 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3357 DVA_GET_VDEV(&bp->blk_dva[1])) {
3358 zb->zb_ditto_samevdev++;
3359
3360 if (same_metaslab(zcb->zcb_spa,
3361 DVA_GET_VDEV(&bp->blk_dva[0]),
3362 DVA_GET_OFFSET(&bp->blk_dva[0]),
3363 DVA_GET_OFFSET(&bp->blk_dva[1])))
3364 zb->zb_ditto_same_ms++;
3365 }
3366 break;
3367 case 3:
3368 equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3369 DVA_GET_VDEV(&bp->blk_dva[1])) +
3370 (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3371 DVA_GET_VDEV(&bp->blk_dva[2])) +
3372 (DVA_GET_VDEV(&bp->blk_dva[1]) ==
3373 DVA_GET_VDEV(&bp->blk_dva[2]));
3374 if (equal != 0) {
3375 zb->zb_ditto_samevdev++;
3376
3377 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3378 DVA_GET_VDEV(&bp->blk_dva[1]) &&
3379 same_metaslab(zcb->zcb_spa,
3380 DVA_GET_VDEV(&bp->blk_dva[0]),
3381 DVA_GET_OFFSET(&bp->blk_dva[0]),
3382 DVA_GET_OFFSET(&bp->blk_dva[1])))
3383 zb->zb_ditto_same_ms++;
3384 else if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3385 DVA_GET_VDEV(&bp->blk_dva[2]) &&
3386 same_metaslab(zcb->zcb_spa,
3387 DVA_GET_VDEV(&bp->blk_dva[0]),
3388 DVA_GET_OFFSET(&bp->blk_dva[0]),
3389 DVA_GET_OFFSET(&bp->blk_dva[2])))
3390 zb->zb_ditto_same_ms++;
3391 else if (DVA_GET_VDEV(&bp->blk_dva[1]) ==
3392 DVA_GET_VDEV(&bp->blk_dva[2]) &&
3393 same_metaslab(zcb->zcb_spa,
3394 DVA_GET_VDEV(&bp->blk_dva[1]),
3395 DVA_GET_OFFSET(&bp->blk_dva[1]),
3396 DVA_GET_OFFSET(&bp->blk_dva[2])))
3397 zb->zb_ditto_same_ms++;
3398 }
3399 break;
3400 }
3401 }
3402
3403 spa_config_exit(zcb->zcb_spa, SCL_CONFIG, FTAG);
3404
3405 if (BP_IS_EMBEDDED(bp)) {
3406 zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
3407 zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
3408 [BPE_GET_PSIZE(bp)]++;
3409 return;
3410 }
3411
3412 if (dump_opt['L'])
3413 return;
3414
3415 if (BP_GET_DEDUP(bp)) {
3416 ddt_t *ddt;
3417 ddt_entry_t *dde;
3418
3419 ddt = ddt_select(zcb->zcb_spa, bp);
3420 ddt_enter(ddt);
3421 dde = ddt_lookup(ddt, bp, B_FALSE);
3422
3423 if (dde == NULL) {
3424 refcnt = 0;
3425 } else {
3426 ddt_phys_t *ddp = ddt_phys_select(dde, bp);
3427 ddt_phys_decref(ddp);
3428 refcnt = ddp->ddp_refcnt;
3429 if (ddt_phys_total_refcnt(dde) == 0)
3430 ddt_remove(ddt, dde);
3431 }
3432 ddt_exit(ddt);
3433 }
3434
3435 VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
3436 refcnt ? 0 : spa_min_claim_txg(zcb->zcb_spa),
3437 bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
3438 }
3439
3440 static void
3441 zdb_blkptr_done(zio_t *zio)
3442 {
3443 spa_t *spa = zio->io_spa;
3444 blkptr_t *bp = zio->io_bp;
3445 int ioerr = zio->io_error;
3446 zdb_cb_t *zcb = zio->io_private;
3447 zbookmark_phys_t *zb = &zio->io_bookmark;
3448
3449 abd_free(zio->io_abd);
3450
3451 mutex_enter(&spa->spa_scrub_lock);
3452 spa->spa_load_verify_ios--;
3453 cv_broadcast(&spa->spa_scrub_io_cv);
3454
3455 if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
3456 char blkbuf[BP_SPRINTF_LEN];
3457
3458 zcb->zcb_haderrors = 1;
3459 zcb->zcb_errors[ioerr]++;
3460
3461 if (dump_opt['b'] >= 2)
3462 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3463 else
3464 blkbuf[0] = '\0';
3465
3466 (void) printf("zdb_blkptr_cb: "
3467 "Got error %d reading "
3468 "<%llu, %llu, %lld, %llx> %s -- skipping\n",
3469 ioerr,
3470 (u_longlong_t)zb->zb_objset,
3471 (u_longlong_t)zb->zb_object,
3472 (u_longlong_t)zb->zb_level,
3473 (u_longlong_t)zb->zb_blkid,
3474 blkbuf);
3475 }
3476 mutex_exit(&spa->spa_scrub_lock);
3477 }
3478
3479 static int
3480 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
3481 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
3482 {
3483 zdb_cb_t *zcb = arg;
3484 dmu_object_type_t type;
3485 boolean_t is_metadata;
3486
3487 if (bp == NULL)
3488 return (0);
3489
3490 if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
3491 char blkbuf[BP_SPRINTF_LEN];
3492 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3493 (void) printf("objset %llu object %llu "
3494 "level %lld offset 0x%llx %s\n",
3495 (u_longlong_t)zb->zb_objset,
3496 (u_longlong_t)zb->zb_object,
3497 (longlong_t)zb->zb_level,
3498 (u_longlong_t)blkid2offset(dnp, bp, zb),
3499 blkbuf);
3500 }
3501
3502 if (BP_IS_HOLE(bp))
3503 return (0);
3504
3505 type = BP_GET_TYPE(bp);
3506
3507 zdb_count_block(zcb, zilog, bp,
3508 (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
3509
3510 is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
3511
3512 if (!BP_IS_EMBEDDED(bp) &&
3513 (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
3514 size_t size = BP_GET_PSIZE(bp);
3515 abd_t *abd = abd_alloc(size, B_FALSE);
3516 int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
3517
3518 /* If it's an intent log block, failure is expected. */
3519 if (zb->zb_level == ZB_ZIL_LEVEL)
3520 flags |= ZIO_FLAG_SPECULATIVE;
3521
3522 mutex_enter(&spa->spa_scrub_lock);
3523 while (spa->spa_load_verify_ios > max_inflight)
3524 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
3525 spa->spa_load_verify_ios++;
3526 mutex_exit(&spa->spa_scrub_lock);
3527
3528 zio_nowait(zio_read(NULL, spa, bp, abd, size,
3529 zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
3530 }
3531
3532 zcb->zcb_readfails = 0;
3533
3534 /* only call gethrtime() every 100 blocks */
3535 static int iters;
3536 if (++iters > 100)
3537 iters = 0;
3538 else
3539 return (0);
3540
3541 if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
3542 uint64_t now = gethrtime();
3543 char buf[10];
3544 uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
3545 int kb_per_sec =
3546 1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
3547 int sec_remaining =
3548 (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
3549
3550 /* make sure nicenum has enough space */
3551 CTASSERT(sizeof (buf) >= NN_NUMBUF_SZ);
3552
3553 zfs_nicebytes(bytes, buf, sizeof (buf));
3554 (void) fprintf(stderr,
3555 "\r%5s completed (%4dMB/s) "
3556 "estimated time remaining: %uhr %02umin %02usec ",
3557 buf, kb_per_sec / 1024,
3558 sec_remaining / 60 / 60,
3559 sec_remaining / 60 % 60,
3560 sec_remaining % 60);
3561
3562 zcb->zcb_lastprint = now;
3563 }
3564
3565 return (0);
3566 }
3567
3568 static void
3569 zdb_leak(void *arg, uint64_t start, uint64_t size)
3570 {
3571 vdev_t *vd = arg;
3572
3573 (void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
3574 (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
3575 }
3576
3577 static metaslab_ops_t zdb_metaslab_ops = {
3578 NULL /* alloc */
3579 };
3580
3581 /* ARGSUSED */
3582 static void
3583 claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
3584 uint64_t size, void *arg)
3585 {
3586 /*
3587 * This callback was called through a remap from
3588 * a device being removed. Therefore, the vdev that
3589 * this callback is applied to is a concrete
3590 * vdev.
3591 */
3592 ASSERT(vdev_is_concrete(vd));
3593
3594 VERIFY0(metaslab_claim_impl(vd, offset, size,
3595 spa_min_claim_txg(vd->vdev_spa)));
3596 }
3597
3598 static void
3599 claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
3600 {
3601 vdev_t *vd = arg;
3602
3603 vdev_indirect_ops.vdev_op_remap(vd, offset, size,
3604 claim_segment_impl_cb, NULL);
3605 }
3606
3607 /*
3608 * After accounting for all allocated blocks that are directly referenced,
3609 * we might have missed a reference to a block from a partially complete
3610 * (and thus unused) indirect mapping object. We perform a secondary pass
3611 * through the metaslabs we have already mapped and claim the destination
3612 * blocks.
3613 */
3614 static void
3615 zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
3616 {
3617 if (dump_opt['L'])
3618 return;
3619
3620 if (spa->spa_vdev_removal == NULL)
3621 return;
3622
3623 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3624
3625 spa_vdev_removal_t *svr = spa->spa_vdev_removal;
3626 vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
3627 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3628
3629 for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
3630 metaslab_t *msp = vd->vdev_ms[msi];
3631
3632 if (msp->ms_start >= vdev_indirect_mapping_max_offset(vim))
3633 break;
3634
3635 ASSERT0(range_tree_space(svr->svr_allocd_segs));
3636
3637 if (msp->ms_sm != NULL) {
3638 VERIFY0(space_map_load(msp->ms_sm,
3639 svr->svr_allocd_segs, SM_ALLOC));
3640
3641 /*
3642 * Clear everything past what has been synced unless
3643 * it's past the spacemap, because we have not allocated
3644 * mappings for it yet.
3645 */
3646 uint64_t vim_max_offset =
3647 vdev_indirect_mapping_max_offset(vim);
3648 uint64_t sm_end = msp->ms_sm->sm_start +
3649 msp->ms_sm->sm_size;
3650 if (sm_end > vim_max_offset)
3651 range_tree_clear(svr->svr_allocd_segs,
3652 vim_max_offset, sm_end - vim_max_offset);
3653 }
3654
3655 zcb->zcb_removing_size +=
3656 range_tree_space(svr->svr_allocd_segs);
3657 range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
3658 }
3659
3660 spa_config_exit(spa, SCL_CONFIG, FTAG);
3661 }
3662
3663 /* ARGSUSED */
3664 static int
3665 increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3666 {
3667 zdb_cb_t *zcb = arg;
3668 spa_t *spa = zcb->zcb_spa;
3669 vdev_t *vd;
3670 const dva_t *dva = &bp->blk_dva[0];
3671
3672 ASSERT(!dump_opt['L']);
3673 ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
3674
3675 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3676 vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
3677 ASSERT3P(vd, !=, NULL);
3678 spa_config_exit(spa, SCL_VDEV, FTAG);
3679
3680 ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
3681 ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
3682
3683 vdev_indirect_mapping_increment_obsolete_count(
3684 vd->vdev_indirect_mapping,
3685 DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
3686 zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
3687
3688 return (0);
3689 }
3690
3691 static uint32_t *
3692 zdb_load_obsolete_counts(vdev_t *vd)
3693 {
3694 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3695 spa_t *spa = vd->vdev_spa;
3696 spa_condensing_indirect_phys_t *scip =
3697 &spa->spa_condensing_indirect_phys;
3698 uint64_t obsolete_sm_object;
3699 uint32_t *counts;
3700
3701 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
3702 EQUIV(obsolete_sm_object != 0, vd->vdev_obsolete_sm != NULL);
3703 counts = vdev_indirect_mapping_load_obsolete_counts(vim);
3704 if (vd->vdev_obsolete_sm != NULL) {
3705 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
3706 vd->vdev_obsolete_sm);
3707 }
3708 if (scip->scip_vdev == vd->vdev_id &&
3709 scip->scip_prev_obsolete_sm_object != 0) {
3710 space_map_t *prev_obsolete_sm = NULL;
3711 VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
3712 scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
3713 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
3714 prev_obsolete_sm);
3715 space_map_close(prev_obsolete_sm);
3716 }
3717 return (counts);
3718 }
3719
3720 static void
3721 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
3722 {
3723 ddt_bookmark_t ddb;
3724 ddt_entry_t dde;
3725 int error;
3726 int p;
3727
3728 ASSERT(!dump_opt['L']);
3729
3730 bzero(&ddb, sizeof (ddb));
3731 while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
3732 blkptr_t blk;
3733 ddt_phys_t *ddp = dde.dde_phys;
3734
3735 if (ddb.ddb_class == DDT_CLASS_UNIQUE)
3736 return;
3737
3738 ASSERT(ddt_phys_total_refcnt(&dde) > 1);
3739
3740 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
3741 if (ddp->ddp_phys_birth == 0)
3742 continue;
3743 ddt_bp_create(ddb.ddb_checksum,
3744 &dde.dde_key, ddp, &blk);
3745 if (p == DDT_PHYS_DITTO) {
3746 zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
3747 } else {
3748 zcb->zcb_dedup_asize +=
3749 BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
3750 zcb->zcb_dedup_blocks++;
3751 }
3752 }
3753 ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
3754 ddt_enter(ddt);
3755 VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
3756 ddt_exit(ddt);
3757 }
3758
3759 ASSERT(error == ENOENT);
3760 }
3761
3762 typedef struct checkpoint_sm_exclude_entry_arg {
3763 vdev_t *cseea_vd;
3764 uint64_t cseea_checkpoint_size;
3765 } checkpoint_sm_exclude_entry_arg_t;
3766
3767 static int
3768 checkpoint_sm_exclude_entry_cb(space_map_entry_t *sme, void *arg)
3769 {
3770 checkpoint_sm_exclude_entry_arg_t *cseea = arg;
3771 vdev_t *vd = cseea->cseea_vd;
3772 metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
3773 uint64_t end = sme->sme_offset + sme->sme_run;
3774
3775 ASSERT(sme->sme_type == SM_FREE);
3776
3777 /*
3778 * Since the vdev_checkpoint_sm exists in the vdev level
3779 * and the ms_sm space maps exist in the metaslab level,
3780 * an entry in the checkpoint space map could theoretically
3781 * cross the boundaries of the metaslab that it belongs.
3782 *
3783 * In reality, because of the way that we populate and
3784 * manipulate the checkpoint's space maps currently,
3785 * there shouldn't be any entries that cross metaslabs.
3786 * Hence the assertion below.
3787 *
3788 * That said, there is no fundamental requirement that
3789 * the checkpoint's space map entries should not cross
3790 * metaslab boundaries. So if needed we could add code
3791 * that handles metaslab-crossing segments in the future.
3792 */
3793 VERIFY3U(sme->sme_offset, >=, ms->ms_start);
3794 VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
3795
3796 /*
3797 * By removing the entry from the allocated segments we
3798 * also verify that the entry is there to begin with.
3799 */
3800 mutex_enter(&ms->ms_lock);
3801 range_tree_remove(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
3802 mutex_exit(&ms->ms_lock);
3803
3804 cseea->cseea_checkpoint_size += sme->sme_run;
3805 return (0);
3806 }
3807
3808 static void
3809 zdb_leak_init_vdev_exclude_checkpoint(vdev_t *vd, zdb_cb_t *zcb)
3810 {
3811 spa_t *spa = vd->vdev_spa;
3812 space_map_t *checkpoint_sm = NULL;
3813 uint64_t checkpoint_sm_obj;
3814
3815 /*
3816 * If there is no vdev_top_zap, we are in a pool whose
3817 * version predates the pool checkpoint feature.
3818 */
3819 if (vd->vdev_top_zap == 0)
3820 return;
3821
3822 /*
3823 * If there is no reference of the vdev_checkpoint_sm in
3824 * the vdev_top_zap, then one of the following scenarios
3825 * is true:
3826 *
3827 * 1] There is no checkpoint
3828 * 2] There is a checkpoint, but no checkpointed blocks
3829 * have been freed yet
3830 * 3] The current vdev is indirect
3831 *
3832 * In these cases we return immediately.
3833 */
3834 if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
3835 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
3836 return;
3837
3838 VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
3839 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1,
3840 &checkpoint_sm_obj));
3841
3842 checkpoint_sm_exclude_entry_arg_t cseea;
3843 cseea.cseea_vd = vd;
3844 cseea.cseea_checkpoint_size = 0;
3845
3846 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
3847 checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
3848
3849 VERIFY0(space_map_iterate(checkpoint_sm,
3850 space_map_length(checkpoint_sm),
3851 checkpoint_sm_exclude_entry_cb, &cseea));
3852 space_map_close(checkpoint_sm);
3853
3854 zcb->zcb_checkpoint_size += cseea.cseea_checkpoint_size;
3855 }
3856
3857 static void
3858 zdb_leak_init_exclude_checkpoint(spa_t *spa, zdb_cb_t *zcb)
3859 {
3860 ASSERT(!dump_opt['L']);
3861
3862 vdev_t *rvd = spa->spa_root_vdev;
3863 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
3864 ASSERT3U(c, ==, rvd->vdev_child[c]->vdev_id);
3865 zdb_leak_init_vdev_exclude_checkpoint(rvd->vdev_child[c], zcb);
3866 }
3867 }
3868
3869 static void
3870 load_concrete_ms_allocatable_trees(spa_t *spa, maptype_t maptype)
3871 {
3872 vdev_t *rvd = spa->spa_root_vdev;
3873 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
3874 vdev_t *vd = rvd->vdev_child[i];
3875
3876 ASSERT3U(i, ==, vd->vdev_id);
3877
3878 if (vd->vdev_ops == &vdev_indirect_ops)
3879 continue;
3880
3881 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3882 metaslab_t *msp = vd->vdev_ms[m];
3883
3884 (void) fprintf(stderr,
3885 "\rloading concrete vdev %llu, "
3886 "metaslab %llu of %llu ...",
3887 (longlong_t)vd->vdev_id,
3888 (longlong_t)msp->ms_id,
3889 (longlong_t)vd->vdev_ms_count);
3890
3891 mutex_enter(&msp->ms_lock);
3892 metaslab_unload(msp);
3893
3894 /*
3895 * We don't want to spend the CPU manipulating the
3896 * size-ordered tree, so clear the range_tree ops.
3897 */
3898 msp->ms_allocatable->rt_ops = NULL;
3899
3900 if (msp->ms_sm != NULL) {
3901 VERIFY0(space_map_load(msp->ms_sm,
3902 msp->ms_allocatable, maptype));
3903 }
3904 if (!msp->ms_loaded)
3905 msp->ms_loaded = B_TRUE;
3906 mutex_exit(&msp->ms_lock);
3907 }
3908 }
3909 }
3910
3911 /*
3912 * vm_idxp is an in-out parameter which (for indirect vdevs) is the
3913 * index in vim_entries that has the first entry in this metaslab.
3914 * On return, it will be set to the first entry after this metaslab.
3915 */
3916 static void
3917 load_indirect_ms_allocatable_tree(vdev_t *vd, metaslab_t *msp,
3918 uint64_t *vim_idxp)
3919 {
3920 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3921
3922 mutex_enter(&msp->ms_lock);
3923 metaslab_unload(msp);
3924
3925 /*
3926 * We don't want to spend the CPU manipulating the
3927 * size-ordered tree, so clear the range_tree ops.
3928 */
3929 msp->ms_allocatable->rt_ops = NULL;
3930
3931 for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
3932 (*vim_idxp)++) {
3933 vdev_indirect_mapping_entry_phys_t *vimep =
3934 &vim->vim_entries[*vim_idxp];
3935 uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
3936 uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
3937 ASSERT3U(ent_offset, >=, msp->ms_start);
3938 if (ent_offset >= msp->ms_start + msp->ms_size)
3939 break;
3940
3941 /*
3942 * Mappings do not cross metaslab boundaries,
3943 * because we create them by walking the metaslabs.
3944 */
3945 ASSERT3U(ent_offset + ent_len, <=,
3946 msp->ms_start + msp->ms_size);
3947 range_tree_add(msp->ms_allocatable, ent_offset, ent_len);
3948 }
3949
3950 if (!msp->ms_loaded)
3951 msp->ms_loaded = B_TRUE;
3952 mutex_exit(&msp->ms_lock);
3953 }
3954
3955 static void
3956 zdb_leak_init_prepare_indirect_vdevs(spa_t *spa, zdb_cb_t *zcb)
3957 {
3958 ASSERT(!dump_opt['L']);
3959
3960 vdev_t *rvd = spa->spa_root_vdev;
3961 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
3962 vdev_t *vd = rvd->vdev_child[c];
3963
3964 ASSERT3U(c, ==, vd->vdev_id);
3965
3966 if (vd->vdev_ops != &vdev_indirect_ops)
3967 continue;
3968
3969 /*
3970 * Note: we don't check for mapping leaks on
3971 * removing vdevs because their ms_allocatable's
3972 * are used to look for leaks in allocated space.
3973 */
3974 zcb->zcb_vd_obsolete_counts[c] = zdb_load_obsolete_counts(vd);
3975
3976 /*
3977 * Normally, indirect vdevs don't have any
3978 * metaslabs. We want to set them up for
3979 * zio_claim().
3980 */
3981 VERIFY0(vdev_metaslab_init(vd, 0));
3982
3983 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3984 uint64_t vim_idx = 0;
3985 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3986
3987 (void) fprintf(stderr,
3988 "\rloading indirect vdev %llu, "
3989 "metaslab %llu of %llu ...",
3990 (longlong_t)vd->vdev_id,
3991 (longlong_t)vd->vdev_ms[m]->ms_id,
3992 (longlong_t)vd->vdev_ms_count);
3993
3994 load_indirect_ms_allocatable_tree(vd, vd->vdev_ms[m],
3995 &vim_idx);
3996 }
3997 ASSERT3U(vim_idx, ==, vdev_indirect_mapping_num_entries(vim));
3998 }
3999 }
4000
4001 static void
4002 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
4003 {
4004 zcb->zcb_spa = spa;
4005
4006 if (dump_opt['L'])
4007 return;
4008
4009 dsl_pool_t *dp = spa->spa_dsl_pool;
4010 vdev_t *rvd = spa->spa_root_vdev;
4011
4012 /*
4013 * We are going to be changing the meaning of the metaslab's
4014 * ms_allocatable. Ensure that the allocator doesn't try to
4015 * use the tree.
4016 */
4017 spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
4018 spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
4019
4020 zcb->zcb_vd_obsolete_counts =
4021 umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
4022 UMEM_NOFAIL);
4023
4024 /*
4025 * For leak detection, we overload the ms_allocatable trees
4026 * to contain allocated segments instead of free segments.
4027 * As a result, we can't use the normal metaslab_load/unload
4028 * interfaces.
4029 */
4030 zdb_leak_init_prepare_indirect_vdevs(spa, zcb);
4031 load_concrete_ms_allocatable_trees(spa, SM_ALLOC);
4032
4033 /*
4034 * On load_concrete_ms_allocatable_trees() we loaded all the
4035 * allocated entries from the ms_sm to the ms_allocatable for
4036 * each metaslab. If the pool has a checkpoint or is in the
4037 * middle of discarding a checkpoint, some of these blocks
4038 * may have been freed but their ms_sm may not have been
4039 * updated because they are referenced by the checkpoint. In
4040 * order to avoid false-positives during leak-detection, we
4041 * go through the vdev's checkpoint space map and exclude all
4042 * its entries from their relevant ms_allocatable.
4043 *
4044 * We also aggregate the space held by the checkpoint and add
4045 * it to zcb_checkpoint_size.
4046 *
4047 * Note that at this point we are also verifying that all the
4048 * entries on the checkpoint_sm are marked as allocated in
4049 * the ms_sm of their relevant metaslab.
4050 * [see comment in checkpoint_sm_exclude_entry_cb()]
4051 */
4052 zdb_leak_init_exclude_checkpoint(spa, zcb);
4053 ASSERT3U(zcb->zcb_checkpoint_size, ==, spa_get_checkpoint_space(spa));
4054
4055 /* for cleaner progress output */
4056 (void) fprintf(stderr, "\n");
4057
4058 if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
4059 ASSERT(spa_feature_is_enabled(spa,
4060 SPA_FEATURE_DEVICE_REMOVAL));
4061 (void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
4062 increment_indirect_mapping_cb, zcb, NULL);
4063 }
4064
4065 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4066 zdb_ddt_leak_init(spa, zcb);
4067 spa_config_exit(spa, SCL_CONFIG, FTAG);
4068 }
4069
4070 static boolean_t
4071 zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
4072 {
4073 boolean_t leaks = B_FALSE;
4074 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
4075 uint64_t total_leaked = 0;
4076 boolean_t are_precise = B_FALSE;
4077
4078 ASSERT(vim != NULL);
4079
4080 for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
4081 vdev_indirect_mapping_entry_phys_t *vimep =
4082 &vim->vim_entries[i];
4083 uint64_t obsolete_bytes = 0;
4084 uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
4085 metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
4086
4087 /*
4088 * This is not very efficient but it's easy to
4089 * verify correctness.
4090 */
4091 for (uint64_t inner_offset = 0;
4092 inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
4093 inner_offset += 1 << vd->vdev_ashift) {
4094 if (range_tree_contains(msp->ms_allocatable,
4095 offset + inner_offset, 1 << vd->vdev_ashift)) {
4096 obsolete_bytes += 1 << vd->vdev_ashift;
4097 }
4098 }
4099
4100 int64_t bytes_leaked = obsolete_bytes -
4101 zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
4102 ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
4103 zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
4104
4105 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
4106 if (bytes_leaked != 0 && (are_precise || dump_opt['d'] >= 5)) {
4107 (void) printf("obsolete indirect mapping count "
4108 "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
4109 (u_longlong_t)vd->vdev_id,
4110 (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
4111 (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
4112 (u_longlong_t)bytes_leaked);
4113 }
4114 total_leaked += ABS(bytes_leaked);
4115 }
4116
4117 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
4118 if (!are_precise && total_leaked > 0) {
4119 int pct_leaked = total_leaked * 100 /
4120 vdev_indirect_mapping_bytes_mapped(vim);
4121 (void) printf("cannot verify obsolete indirect mapping "
4122 "counts of vdev %llu because precise feature was not "
4123 "enabled when it was removed: %d%% (%llx bytes) of mapping"
4124 "unreferenced\n",
4125 (u_longlong_t)vd->vdev_id, pct_leaked,
4126 (u_longlong_t)total_leaked);
4127 } else if (total_leaked > 0) {
4128 (void) printf("obsolete indirect mapping count mismatch "
4129 "for vdev %llu -- %llx total bytes mismatched\n",
4130 (u_longlong_t)vd->vdev_id,
4131 (u_longlong_t)total_leaked);
4132 leaks |= B_TRUE;
4133 }
4134
4135 vdev_indirect_mapping_free_obsolete_counts(vim,
4136 zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
4137 zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
4138
4139 return (leaks);
4140 }
4141
4142 static boolean_t
4143 zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
4144 {
4145 if (dump_opt['L'])
4146 return (B_FALSE);
4147
4148 boolean_t leaks = B_FALSE;
4149 vdev_t *rvd = spa->spa_root_vdev;
4150 for (unsigned c = 0; c < rvd->vdev_children; c++) {
4151 vdev_t *vd = rvd->vdev_child[c];
4152 ASSERTV(metaslab_group_t *mg = vd->vdev_mg);
4153
4154 if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
4155 leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
4156 }
4157
4158 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
4159 metaslab_t *msp = vd->vdev_ms[m];
4160 ASSERT3P(mg, ==, msp->ms_group);
4161
4162 /*
4163 * ms_allocatable has been overloaded
4164 * to contain allocated segments. Now that
4165 * we finished traversing all blocks, any
4166 * block that remains in the ms_allocatable
4167 * represents an allocated block that we
4168 * did not claim during the traversal.
4169 * Claimed blocks would have been removed
4170 * from the ms_allocatable. For indirect
4171 * vdevs, space remaining in the tree
4172 * represents parts of the mapping that are
4173 * not referenced, which is not a bug.
4174 */
4175 if (vd->vdev_ops == &vdev_indirect_ops) {
4176 range_tree_vacate(msp->ms_allocatable,
4177 NULL, NULL);
4178 } else {
4179 range_tree_vacate(msp->ms_allocatable,
4180 zdb_leak, vd);
4181 }
4182
4183 if (msp->ms_loaded) {
4184 msp->ms_loaded = B_FALSE;
4185 }
4186 }
4187 }
4188
4189 umem_free(zcb->zcb_vd_obsolete_counts,
4190 rvd->vdev_children * sizeof (uint32_t *));
4191 zcb->zcb_vd_obsolete_counts = NULL;
4192
4193 return (leaks);
4194 }
4195
4196 /* ARGSUSED */
4197 static int
4198 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
4199 {
4200 zdb_cb_t *zcb = arg;
4201
4202 if (dump_opt['b'] >= 5) {
4203 char blkbuf[BP_SPRINTF_LEN];
4204 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
4205 (void) printf("[%s] %s\n",
4206 "deferred free", blkbuf);
4207 }
4208 zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
4209 return (0);
4210 }
4211
4212 static int
4213 dump_block_stats(spa_t *spa)
4214 {
4215 zdb_cb_t zcb;
4216 zdb_blkstats_t *zb, *tzb;
4217 uint64_t norm_alloc, norm_space, total_alloc, total_found;
4218 int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
4219 TRAVERSE_NO_DECRYPT | TRAVERSE_HARD;
4220 boolean_t leaks = B_FALSE;
4221 int e, c, err;
4222 bp_embedded_type_t i;
4223
4224 bzero(&zcb, sizeof (zcb));
4225 (void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
4226 (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
4227 (dump_opt['c'] == 1) ? "metadata " : "",
4228 dump_opt['c'] ? "checksums " : "",
4229 (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
4230 !dump_opt['L'] ? "nothing leaked " : "");
4231
4232 /*
4233 * When leak detection is enabled we load all space maps as SM_ALLOC
4234 * maps, then traverse the pool claiming each block we discover. If
4235 * the pool is perfectly consistent, the segment trees will be empty
4236 * when we're done. Anything left over is a leak; any block we can't
4237 * claim (because it's not part of any space map) is a double
4238 * allocation, reference to a freed block, or an unclaimed log block.
4239 *
4240 * When leak detection is disabled (-L option) we still traverse the
4241 * pool claiming each block we discover, but we skip opening any space
4242 * maps.
4243 */
4244 bzero(&zcb, sizeof (zdb_cb_t));
4245 zdb_leak_init(spa, &zcb);
4246
4247 /*
4248 * If there's a deferred-free bplist, process that first.
4249 */
4250 (void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
4251 count_block_cb, &zcb, NULL);
4252
4253 if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
4254 (void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
4255 count_block_cb, &zcb, NULL);
4256 }
4257
4258 zdb_claim_removing(spa, &zcb);
4259
4260 if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
4261 VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
4262 spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
4263 &zcb, NULL));
4264 }
4265
4266 if (dump_opt['c'] > 1)
4267 flags |= TRAVERSE_PREFETCH_DATA;
4268
4269 zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
4270 zcb.zcb_totalasize += metaslab_class_get_alloc(spa_special_class(spa));
4271 zcb.zcb_totalasize += metaslab_class_get_alloc(spa_dedup_class(spa));
4272 zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
4273 err = traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
4274
4275 /*
4276 * If we've traversed the data blocks then we need to wait for those
4277 * I/Os to complete. We leverage "The Godfather" zio to wait on
4278 * all async I/Os to complete.
4279 */
4280 if (dump_opt['c']) {
4281 for (c = 0; c < max_ncpus; c++) {
4282 (void) zio_wait(spa->spa_async_zio_root[c]);
4283 spa->spa_async_zio_root[c] = zio_root(spa, NULL, NULL,
4284 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4285 ZIO_FLAG_GODFATHER);
4286 }
4287 }
4288
4289 /*
4290 * Done after zio_wait() since zcb_haderrors is modified in
4291 * zdb_blkptr_done()
4292 */
4293 zcb.zcb_haderrors |= err;
4294
4295 if (zcb.zcb_haderrors) {
4296 (void) printf("\nError counts:\n\n");
4297 (void) printf("\t%5s %s\n", "errno", "count");
4298 for (e = 0; e < 256; e++) {
4299 if (zcb.zcb_errors[e] != 0) {
4300 (void) printf("\t%5d %llu\n",
4301 e, (u_longlong_t)zcb.zcb_errors[e]);
4302 }
4303 }
4304 }
4305
4306 /*
4307 * Report any leaked segments.
4308 */
4309 leaks |= zdb_leak_fini(spa, &zcb);
4310
4311 tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
4312
4313 norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
4314 norm_space = metaslab_class_get_space(spa_normal_class(spa));
4315
4316 total_alloc = norm_alloc +
4317 metaslab_class_get_alloc(spa_log_class(spa)) +
4318 metaslab_class_get_alloc(spa_special_class(spa)) +
4319 metaslab_class_get_alloc(spa_dedup_class(spa));
4320 total_found = tzb->zb_asize - zcb.zcb_dedup_asize +
4321 zcb.zcb_removing_size + zcb.zcb_checkpoint_size;
4322
4323 if (total_found == total_alloc && !dump_opt['L']) {
4324 (void) printf("\n\tNo leaks (block sum matches space"
4325 " maps exactly)\n");
4326 } else if (!dump_opt['L']) {
4327 (void) printf("block traversal size %llu != alloc %llu "
4328 "(%s %lld)\n",
4329 (u_longlong_t)total_found,
4330 (u_longlong_t)total_alloc,
4331 (dump_opt['L']) ? "unreachable" : "leaked",
4332 (longlong_t)(total_alloc - total_found));
4333 leaks = B_TRUE;
4334 }
4335
4336 if (tzb->zb_count == 0)
4337 return (2);
4338
4339 (void) printf("\n");
4340 (void) printf("\t%-16s %14llu\n", "bp count:",
4341 (u_longlong_t)tzb->zb_count);
4342 (void) printf("\t%-16s %14llu\n", "ganged count:",
4343 (longlong_t)tzb->zb_gangs);
4344 (void) printf("\t%-16s %14llu avg: %6llu\n", "bp logical:",
4345 (u_longlong_t)tzb->zb_lsize,
4346 (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
4347 (void) printf("\t%-16s %14llu avg: %6llu compression: %6.2f\n",
4348 "bp physical:", (u_longlong_t)tzb->zb_psize,
4349 (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
4350 (double)tzb->zb_lsize / tzb->zb_psize);
4351 (void) printf("\t%-16s %14llu avg: %6llu compression: %6.2f\n",
4352 "bp allocated:", (u_longlong_t)tzb->zb_asize,
4353 (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
4354 (double)tzb->zb_lsize / tzb->zb_asize);
4355 (void) printf("\t%-16s %14llu ref>1: %6llu deduplication: %6.2f\n",
4356 "bp deduped:", (u_longlong_t)zcb.zcb_dedup_asize,
4357 (u_longlong_t)zcb.zcb_dedup_blocks,
4358 (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
4359 (void) printf("\t%-16s %14llu used: %5.2f%%\n", "Normal class:",
4360 (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
4361
4362 if (spa_special_class(spa)->mc_rotor != NULL) {
4363 uint64_t alloc = metaslab_class_get_alloc(
4364 spa_special_class(spa));
4365 uint64_t space = metaslab_class_get_space(
4366 spa_special_class(spa));
4367
4368 (void) printf("\t%-16s %14llu used: %5.2f%%\n",
4369 "Special class", (u_longlong_t)alloc,
4370 100.0 * alloc / space);
4371 }
4372
4373 if (spa_dedup_class(spa)->mc_rotor != NULL) {
4374 uint64_t alloc = metaslab_class_get_alloc(
4375 spa_dedup_class(spa));
4376 uint64_t space = metaslab_class_get_space(
4377 spa_dedup_class(spa));
4378
4379 (void) printf("\t%-16s %14llu used: %5.2f%%\n",
4380 "Dedup class", (u_longlong_t)alloc,
4381 100.0 * alloc / space);
4382 }
4383
4384 for (i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
4385 if (zcb.zcb_embedded_blocks[i] == 0)
4386 continue;
4387 (void) printf("\n");
4388 (void) printf("\tadditional, non-pointer bps of type %u: "
4389 "%10llu\n",
4390 i, (u_longlong_t)zcb.zcb_embedded_blocks[i]);
4391
4392 if (dump_opt['b'] >= 3) {
4393 (void) printf("\t number of (compressed) bytes: "
4394 "number of bps\n");
4395 dump_histogram(zcb.zcb_embedded_histogram[i],
4396 sizeof (zcb.zcb_embedded_histogram[i]) /
4397 sizeof (zcb.zcb_embedded_histogram[i][0]), 0);
4398 }
4399 }
4400
4401 if (tzb->zb_ditto_samevdev != 0) {
4402 (void) printf("\tDittoed blocks on same vdev: %llu\n",
4403 (longlong_t)tzb->zb_ditto_samevdev);
4404 }
4405 if (tzb->zb_ditto_same_ms != 0) {
4406 (void) printf("\tDittoed blocks in same metaslab: %llu\n",
4407 (longlong_t)tzb->zb_ditto_same_ms);
4408 }
4409
4410 for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
4411 vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
4412 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
4413
4414 if (vim == NULL) {
4415 continue;
4416 }
4417
4418 char mem[32];
4419 zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
4420 mem, vdev_indirect_mapping_size(vim));
4421
4422 (void) printf("\tindirect vdev id %llu has %llu segments "
4423 "(%s in memory)\n",
4424 (longlong_t)vd->vdev_id,
4425 (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
4426 }
4427
4428 if (dump_opt['b'] >= 2) {
4429 int l, t, level;
4430 (void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
4431 "\t avg\t comp\t%%Total\tType\n");
4432
4433 for (t = 0; t <= ZDB_OT_TOTAL; t++) {
4434 char csize[32], lsize[32], psize[32], asize[32];
4435 char avg[32], gang[32];
4436 const char *typename;
4437
4438 /* make sure nicenum has enough space */
4439 CTASSERT(sizeof (csize) >= NN_NUMBUF_SZ);
4440 CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
4441 CTASSERT(sizeof (psize) >= NN_NUMBUF_SZ);
4442 CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
4443 CTASSERT(sizeof (avg) >= NN_NUMBUF_SZ);
4444 CTASSERT(sizeof (gang) >= NN_NUMBUF_SZ);
4445
4446 if (t < DMU_OT_NUMTYPES)
4447 typename = dmu_ot[t].ot_name;
4448 else
4449 typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
4450
4451 if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
4452 (void) printf("%6s\t%5s\t%5s\t%5s"
4453 "\t%5s\t%5s\t%6s\t%s\n",
4454 "-",
4455 "-",
4456 "-",
4457 "-",
4458 "-",
4459 "-",
4460 "-",
4461 typename);
4462 continue;
4463 }
4464
4465 for (l = ZB_TOTAL - 1; l >= -1; l--) {
4466 level = (l == -1 ? ZB_TOTAL : l);
4467 zb = &zcb.zcb_type[level][t];
4468
4469 if (zb->zb_asize == 0)
4470 continue;
4471
4472 if (dump_opt['b'] < 3 && level != ZB_TOTAL)
4473 continue;
4474
4475 if (level == 0 && zb->zb_asize ==
4476 zcb.zcb_type[ZB_TOTAL][t].zb_asize)
4477 continue;
4478
4479 zdb_nicenum(zb->zb_count, csize,
4480 sizeof (csize));
4481 zdb_nicenum(zb->zb_lsize, lsize,
4482 sizeof (lsize));
4483 zdb_nicenum(zb->zb_psize, psize,
4484 sizeof (psize));
4485 zdb_nicenum(zb->zb_asize, asize,
4486 sizeof (asize));
4487 zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
4488 sizeof (avg));
4489 zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
4490
4491 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
4492 "\t%5.2f\t%6.2f\t",
4493 csize, lsize, psize, asize, avg,
4494 (double)zb->zb_lsize / zb->zb_psize,
4495 100.0 * zb->zb_asize / tzb->zb_asize);
4496
4497 if (level == ZB_TOTAL)
4498 (void) printf("%s\n", typename);
4499 else
4500 (void) printf(" L%d %s\n",
4501 level, typename);
4502
4503 if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
4504 (void) printf("\t number of ganged "
4505 "blocks: %s\n", gang);
4506 }
4507
4508 if (dump_opt['b'] >= 4) {
4509 (void) printf("psize "
4510 "(in 512-byte sectors): "
4511 "number of blocks\n");
4512 dump_histogram(zb->zb_psize_histogram,
4513 PSIZE_HISTO_SIZE, 0);
4514 }
4515 }
4516 }
4517 }
4518
4519 (void) printf("\n");
4520
4521 if (leaks)
4522 return (2);
4523
4524 if (zcb.zcb_haderrors)
4525 return (3);
4526
4527 return (0);
4528 }
4529
4530 typedef struct zdb_ddt_entry {
4531 ddt_key_t zdde_key;
4532 uint64_t zdde_ref_blocks;
4533 uint64_t zdde_ref_lsize;
4534 uint64_t zdde_ref_psize;
4535 uint64_t zdde_ref_dsize;
4536 avl_node_t zdde_node;
4537 } zdb_ddt_entry_t;
4538
4539 /* ARGSUSED */
4540 static int
4541 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
4542 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
4543 {
4544 avl_tree_t *t = arg;
4545 avl_index_t where;
4546 zdb_ddt_entry_t *zdde, zdde_search;
4547
4548 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
4549 return (0);
4550
4551 if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
4552 (void) printf("traversing objset %llu, %llu objects, "
4553 "%lu blocks so far\n",
4554 (u_longlong_t)zb->zb_objset,
4555 (u_longlong_t)BP_GET_FILL(bp),
4556 avl_numnodes(t));
4557 }
4558
4559 if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
4560 BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
4561 return (0);
4562
4563 ddt_key_fill(&zdde_search.zdde_key, bp);
4564
4565 zdde = avl_find(t, &zdde_search, &where);
4566
4567 if (zdde == NULL) {
4568 zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
4569 zdde->zdde_key = zdde_search.zdde_key;
4570 avl_insert(t, zdde, where);
4571 }
4572
4573 zdde->zdde_ref_blocks += 1;
4574 zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
4575 zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
4576 zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
4577
4578 return (0);
4579 }
4580
4581 static void
4582 dump_simulated_ddt(spa_t *spa)
4583 {
4584 avl_tree_t t;
4585 void *cookie = NULL;
4586 zdb_ddt_entry_t *zdde;
4587 ddt_histogram_t ddh_total;
4588 ddt_stat_t dds_total;
4589
4590 bzero(&ddh_total, sizeof (ddh_total));
4591 bzero(&dds_total, sizeof (dds_total));
4592 avl_create(&t, ddt_entry_compare,
4593 sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
4594
4595 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4596
4597 (void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
4598 TRAVERSE_NO_DECRYPT, zdb_ddt_add_cb, &t);
4599
4600 spa_config_exit(spa, SCL_CONFIG, FTAG);
4601
4602 while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
4603 ddt_stat_t dds;
4604 uint64_t refcnt = zdde->zdde_ref_blocks;
4605 ASSERT(refcnt != 0);
4606
4607 dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
4608 dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
4609 dds.dds_psize = zdde->zdde_ref_psize / refcnt;
4610 dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
4611
4612 dds.dds_ref_blocks = zdde->zdde_ref_blocks;
4613 dds.dds_ref_lsize = zdde->zdde_ref_lsize;
4614 dds.dds_ref_psize = zdde->zdde_ref_psize;
4615 dds.dds_ref_dsize = zdde->zdde_ref_dsize;
4616
4617 ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
4618 &dds, 0);
4619
4620 umem_free(zdde, sizeof (*zdde));
4621 }
4622
4623 avl_destroy(&t);
4624
4625 ddt_histogram_stat(&dds_total, &ddh_total);
4626
4627 (void) printf("Simulated DDT histogram:\n");
4628
4629 zpool_dump_ddt(&dds_total, &ddh_total);
4630
4631 dump_dedup_ratio(&dds_total);
4632 }
4633
4634 static int
4635 verify_device_removal_feature_counts(spa_t *spa)
4636 {
4637 uint64_t dr_feature_refcount = 0;
4638 uint64_t oc_feature_refcount = 0;
4639 uint64_t indirect_vdev_count = 0;
4640 uint64_t precise_vdev_count = 0;
4641 uint64_t obsolete_counts_object_count = 0;
4642 uint64_t obsolete_sm_count = 0;
4643 uint64_t obsolete_counts_count = 0;
4644 uint64_t scip_count = 0;
4645 uint64_t obsolete_bpobj_count = 0;
4646 int ret = 0;
4647
4648 spa_condensing_indirect_phys_t *scip =
4649 &spa->spa_condensing_indirect_phys;
4650 if (scip->scip_next_mapping_object != 0) {
4651 vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
4652 ASSERT(scip->scip_prev_obsolete_sm_object != 0);
4653 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
4654
4655 (void) printf("Condensing indirect vdev %llu: new mapping "
4656 "object %llu, prev obsolete sm %llu\n",
4657 (u_longlong_t)scip->scip_vdev,
4658 (u_longlong_t)scip->scip_next_mapping_object,
4659 (u_longlong_t)scip->scip_prev_obsolete_sm_object);
4660 if (scip->scip_prev_obsolete_sm_object != 0) {
4661 space_map_t *prev_obsolete_sm = NULL;
4662 VERIFY0(space_map_open(&prev_obsolete_sm,
4663 spa->spa_meta_objset,
4664 scip->scip_prev_obsolete_sm_object,
4665 0, vd->vdev_asize, 0));
4666 dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
4667 (void) printf("\n");
4668 space_map_close(prev_obsolete_sm);
4669 }
4670
4671 scip_count += 2;
4672 }
4673
4674 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
4675 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
4676 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
4677
4678 if (vic->vic_mapping_object != 0) {
4679 ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
4680 vd->vdev_removing);
4681 indirect_vdev_count++;
4682
4683 if (vd->vdev_indirect_mapping->vim_havecounts) {
4684 obsolete_counts_count++;
4685 }
4686 }
4687
4688 boolean_t are_precise;
4689 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
4690 if (are_precise) {
4691 ASSERT(vic->vic_mapping_object != 0);
4692 precise_vdev_count++;
4693 }
4694
4695 uint64_t obsolete_sm_object;
4696 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
4697 if (obsolete_sm_object != 0) {
4698 ASSERT(vic->vic_mapping_object != 0);
4699 obsolete_sm_count++;
4700 }
4701 }
4702
4703 (void) feature_get_refcount(spa,
4704 &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
4705 &dr_feature_refcount);
4706 (void) feature_get_refcount(spa,
4707 &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
4708 &oc_feature_refcount);
4709
4710 if (dr_feature_refcount != indirect_vdev_count) {
4711 ret = 1;
4712 (void) printf("Number of indirect vdevs (%llu) " \
4713 "does not match feature count (%llu)\n",
4714 (u_longlong_t)indirect_vdev_count,
4715 (u_longlong_t)dr_feature_refcount);
4716 } else {
4717 (void) printf("Verified device_removal feature refcount " \
4718 "of %llu is correct\n",
4719 (u_longlong_t)dr_feature_refcount);
4720 }
4721
4722 if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
4723 DMU_POOL_OBSOLETE_BPOBJ) == 0) {
4724 obsolete_bpobj_count++;
4725 }
4726
4727
4728 obsolete_counts_object_count = precise_vdev_count;
4729 obsolete_counts_object_count += obsolete_sm_count;
4730 obsolete_counts_object_count += obsolete_counts_count;
4731 obsolete_counts_object_count += scip_count;
4732 obsolete_counts_object_count += obsolete_bpobj_count;
4733 obsolete_counts_object_count += remap_deadlist_count;
4734
4735 if (oc_feature_refcount != obsolete_counts_object_count) {
4736 ret = 1;
4737 (void) printf("Number of obsolete counts objects (%llu) " \
4738 "does not match feature count (%llu)\n",
4739 (u_longlong_t)obsolete_counts_object_count,
4740 (u_longlong_t)oc_feature_refcount);
4741 (void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
4742 "ob:%llu rd:%llu\n",
4743 (u_longlong_t)precise_vdev_count,
4744 (u_longlong_t)obsolete_sm_count,
4745 (u_longlong_t)obsolete_counts_count,
4746 (u_longlong_t)scip_count,
4747 (u_longlong_t)obsolete_bpobj_count,
4748 (u_longlong_t)remap_deadlist_count);
4749 } else {
4750 (void) printf("Verified indirect_refcount feature refcount " \
4751 "of %llu is correct\n",
4752 (u_longlong_t)oc_feature_refcount);
4753 }
4754 return (ret);
4755 }
4756
4757 static void
4758 zdb_set_skip_mmp(char *target)
4759 {
4760 spa_t *spa;
4761
4762 /*
4763 * Disable the activity check to allow examination of
4764 * active pools.
4765 */
4766 mutex_enter(&spa_namespace_lock);
4767 if ((spa = spa_lookup(target)) != NULL) {
4768 spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
4769 }
4770 mutex_exit(&spa_namespace_lock);
4771 }
4772
4773 #define BOGUS_SUFFIX "_CHECKPOINTED_UNIVERSE"
4774 /*
4775 * Import the checkpointed state of the pool specified by the target
4776 * parameter as readonly. The function also accepts a pool config
4777 * as an optional parameter, else it attempts to infer the config by
4778 * the name of the target pool.
4779 *
4780 * Note that the checkpointed state's pool name will be the name of
4781 * the original pool with the above suffix appened to it. In addition,
4782 * if the target is not a pool name (e.g. a path to a dataset) then
4783 * the new_path parameter is populated with the updated path to
4784 * reflect the fact that we are looking into the checkpointed state.
4785 *
4786 * The function returns a newly-allocated copy of the name of the
4787 * pool containing the checkpointed state. When this copy is no
4788 * longer needed it should be freed with free(3C). Same thing
4789 * applies to the new_path parameter if allocated.
4790 */
4791 static char *
4792 import_checkpointed_state(char *target, nvlist_t *cfg, char **new_path)
4793 {
4794 int error = 0;
4795 char *poolname, *bogus_name = NULL;
4796
4797 /* If the target is not a pool, the extract the pool name */
4798 char *path_start = strchr(target, '/');
4799 if (path_start != NULL) {
4800 size_t poolname_len = path_start - target;
4801 poolname = strndup(target, poolname_len);
4802 } else {
4803 poolname = target;
4804 }
4805
4806 if (cfg == NULL) {
4807 zdb_set_skip_mmp(poolname);
4808 error = spa_get_stats(poolname, &cfg, NULL, 0);
4809 if (error != 0) {
4810 fatal("Tried to read config of pool \"%s\" but "
4811 "spa_get_stats() failed with error %d\n",
4812 poolname, error);
4813 }
4814 }
4815
4816 if (asprintf(&bogus_name, "%s%s", poolname, BOGUS_SUFFIX) == -1)
4817 return (NULL);
4818 fnvlist_add_string(cfg, ZPOOL_CONFIG_POOL_NAME, bogus_name);
4819
4820 error = spa_import(bogus_name, cfg, NULL,
4821 ZFS_IMPORT_MISSING_LOG | ZFS_IMPORT_CHECKPOINT |
4822 ZFS_IMPORT_SKIP_MMP);
4823 if (error != 0) {
4824 fatal("Tried to import pool \"%s\" but spa_import() failed "
4825 "with error %d\n", bogus_name, error);
4826 }
4827
4828 if (new_path != NULL && path_start != NULL) {
4829 if (asprintf(new_path, "%s%s", bogus_name, path_start) == -1) {
4830 if (path_start != NULL)
4831 free(poolname);
4832 return (NULL);
4833 }
4834 }
4835
4836 if (target != poolname)
4837 free(poolname);
4838
4839 return (bogus_name);
4840 }
4841
4842 typedef struct verify_checkpoint_sm_entry_cb_arg {
4843 vdev_t *vcsec_vd;
4844
4845 /* the following fields are only used for printing progress */
4846 uint64_t vcsec_entryid;
4847 uint64_t vcsec_num_entries;
4848 } verify_checkpoint_sm_entry_cb_arg_t;
4849
4850 #define ENTRIES_PER_PROGRESS_UPDATE 10000
4851
4852 static int
4853 verify_checkpoint_sm_entry_cb(space_map_entry_t *sme, void *arg)
4854 {
4855 verify_checkpoint_sm_entry_cb_arg_t *vcsec = arg;
4856 vdev_t *vd = vcsec->vcsec_vd;
4857 metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
4858 uint64_t end = sme->sme_offset + sme->sme_run;
4859
4860 ASSERT(sme->sme_type == SM_FREE);
4861
4862 if ((vcsec->vcsec_entryid % ENTRIES_PER_PROGRESS_UPDATE) == 0) {
4863 (void) fprintf(stderr,
4864 "\rverifying vdev %llu, space map entry %llu of %llu ...",
4865 (longlong_t)vd->vdev_id,
4866 (longlong_t)vcsec->vcsec_entryid,
4867 (longlong_t)vcsec->vcsec_num_entries);
4868 }
4869 vcsec->vcsec_entryid++;
4870
4871 /*
4872 * See comment in checkpoint_sm_exclude_entry_cb()
4873 */
4874 VERIFY3U(sme->sme_offset, >=, ms->ms_start);
4875 VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
4876
4877 /*
4878 * The entries in the vdev_checkpoint_sm should be marked as
4879 * allocated in the checkpointed state of the pool, therefore
4880 * their respective ms_allocateable trees should not contain them.
4881 */
4882 mutex_enter(&ms->ms_lock);
4883 range_tree_verify_not_present(ms->ms_allocatable,
4884 sme->sme_offset, sme->sme_run);
4885 mutex_exit(&ms->ms_lock);
4886
4887 return (0);
4888 }
4889
4890 /*
4891 * Verify that all segments in the vdev_checkpoint_sm are allocated
4892 * according to the checkpoint's ms_sm (i.e. are not in the checkpoint's
4893 * ms_allocatable).
4894 *
4895 * Do so by comparing the checkpoint space maps (vdev_checkpoint_sm) of
4896 * each vdev in the current state of the pool to the metaslab space maps
4897 * (ms_sm) of the checkpointed state of the pool.
4898 *
4899 * Note that the function changes the state of the ms_allocatable
4900 * trees of the current spa_t. The entries of these ms_allocatable
4901 * trees are cleared out and then repopulated from with the free
4902 * entries of their respective ms_sm space maps.
4903 */
4904 static void
4905 verify_checkpoint_vdev_spacemaps(spa_t *checkpoint, spa_t *current)
4906 {
4907 vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
4908 vdev_t *current_rvd = current->spa_root_vdev;
4909
4910 load_concrete_ms_allocatable_trees(checkpoint, SM_FREE);
4911
4912 for (uint64_t c = 0; c < ckpoint_rvd->vdev_children; c++) {
4913 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[c];
4914 vdev_t *current_vd = current_rvd->vdev_child[c];
4915
4916 space_map_t *checkpoint_sm = NULL;
4917 uint64_t checkpoint_sm_obj;
4918
4919 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
4920 /*
4921 * Since we don't allow device removal in a pool
4922 * that has a checkpoint, we expect that all removed
4923 * vdevs were removed from the pool before the
4924 * checkpoint.
4925 */
4926 ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
4927 continue;
4928 }
4929
4930 /*
4931 * If the checkpoint space map doesn't exist, then nothing
4932 * here is checkpointed so there's nothing to verify.
4933 */
4934 if (current_vd->vdev_top_zap == 0 ||
4935 zap_contains(spa_meta_objset(current),
4936 current_vd->vdev_top_zap,
4937 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
4938 continue;
4939
4940 VERIFY0(zap_lookup(spa_meta_objset(current),
4941 current_vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
4942 sizeof (uint64_t), 1, &checkpoint_sm_obj));
4943
4944 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(current),
4945 checkpoint_sm_obj, 0, current_vd->vdev_asize,
4946 current_vd->vdev_ashift));
4947
4948 verify_checkpoint_sm_entry_cb_arg_t vcsec;
4949 vcsec.vcsec_vd = ckpoint_vd;
4950 vcsec.vcsec_entryid = 0;
4951 vcsec.vcsec_num_entries =
4952 space_map_length(checkpoint_sm) / sizeof (uint64_t);
4953 VERIFY0(space_map_iterate(checkpoint_sm,
4954 space_map_length(checkpoint_sm),
4955 verify_checkpoint_sm_entry_cb, &vcsec));
4956 if (dump_opt['m'] > 3)
4957 dump_spacemap(current->spa_meta_objset, checkpoint_sm);
4958 space_map_close(checkpoint_sm);
4959 }
4960
4961 /*
4962 * If we've added vdevs since we took the checkpoint, ensure
4963 * that their checkpoint space maps are empty.
4964 */
4965 if (ckpoint_rvd->vdev_children < current_rvd->vdev_children) {
4966 for (uint64_t c = ckpoint_rvd->vdev_children;
4967 c < current_rvd->vdev_children; c++) {
4968 vdev_t *current_vd = current_rvd->vdev_child[c];
4969 ASSERT3P(current_vd->vdev_checkpoint_sm, ==, NULL);
4970 }
4971 }
4972
4973 /* for cleaner progress output */
4974 (void) fprintf(stderr, "\n");
4975 }
4976
4977 /*
4978 * Verifies that all space that's allocated in the checkpoint is
4979 * still allocated in the current version, by checking that everything
4980 * in checkpoint's ms_allocatable (which is actually allocated, not
4981 * allocatable/free) is not present in current's ms_allocatable.
4982 *
4983 * Note that the function changes the state of the ms_allocatable
4984 * trees of both spas when called. The entries of all ms_allocatable
4985 * trees are cleared out and then repopulated from their respective
4986 * ms_sm space maps. In the checkpointed state we load the allocated
4987 * entries, and in the current state we load the free entries.
4988 */
4989 static void
4990 verify_checkpoint_ms_spacemaps(spa_t *checkpoint, spa_t *current)
4991 {
4992 vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
4993 vdev_t *current_rvd = current->spa_root_vdev;
4994
4995 load_concrete_ms_allocatable_trees(checkpoint, SM_ALLOC);
4996 load_concrete_ms_allocatable_trees(current, SM_FREE);
4997
4998 for (uint64_t i = 0; i < ckpoint_rvd->vdev_children; i++) {
4999 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[i];
5000 vdev_t *current_vd = current_rvd->vdev_child[i];
5001
5002 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
5003 /*
5004 * See comment in verify_checkpoint_vdev_spacemaps()
5005 */
5006 ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
5007 continue;
5008 }
5009
5010 for (uint64_t m = 0; m < ckpoint_vd->vdev_ms_count; m++) {
5011 metaslab_t *ckpoint_msp = ckpoint_vd->vdev_ms[m];
5012 metaslab_t *current_msp = current_vd->vdev_ms[m];
5013
5014 (void) fprintf(stderr,
5015 "\rverifying vdev %llu of %llu, "
5016 "metaslab %llu of %llu ...",
5017 (longlong_t)current_vd->vdev_id,
5018 (longlong_t)current_rvd->vdev_children,
5019 (longlong_t)current_vd->vdev_ms[m]->ms_id,
5020 (longlong_t)current_vd->vdev_ms_count);
5021
5022 /*
5023 * We walk through the ms_allocatable trees that
5024 * are loaded with the allocated blocks from the
5025 * ms_sm spacemaps of the checkpoint. For each
5026 * one of these ranges we ensure that none of them
5027 * exists in the ms_allocatable trees of the
5028 * current state which are loaded with the ranges
5029 * that are currently free.
5030 *
5031 * This way we ensure that none of the blocks that
5032 * are part of the checkpoint were freed by mistake.
5033 */
5034 range_tree_walk(ckpoint_msp->ms_allocatable,
5035 (range_tree_func_t *)range_tree_verify_not_present,
5036 current_msp->ms_allocatable);
5037 }
5038 }
5039
5040 /* for cleaner progress output */
5041 (void) fprintf(stderr, "\n");
5042 }
5043
5044 static void
5045 verify_checkpoint_blocks(spa_t *spa)
5046 {
5047 ASSERT(!dump_opt['L']);
5048
5049 spa_t *checkpoint_spa;
5050 char *checkpoint_pool;
5051 nvlist_t *config = NULL;
5052 int error = 0;
5053
5054 /*
5055 * We import the checkpointed state of the pool (under a different
5056 * name) so we can do verification on it against the current state
5057 * of the pool.
5058 */
5059 checkpoint_pool = import_checkpointed_state(spa->spa_name, config,
5060 NULL);
5061 ASSERT(strcmp(spa->spa_name, checkpoint_pool) != 0);
5062
5063 error = spa_open(checkpoint_pool, &checkpoint_spa, FTAG);
5064 if (error != 0) {
5065 fatal("Tried to open pool \"%s\" but spa_open() failed with "
5066 "error %d\n", checkpoint_pool, error);
5067 }
5068
5069 /*
5070 * Ensure that ranges in the checkpoint space maps of each vdev
5071 * are allocated according to the checkpointed state's metaslab
5072 * space maps.
5073 */
5074 verify_checkpoint_vdev_spacemaps(checkpoint_spa, spa);
5075
5076 /*
5077 * Ensure that allocated ranges in the checkpoint's metaslab
5078 * space maps remain allocated in the metaslab space maps of
5079 * the current state.
5080 */
5081 verify_checkpoint_ms_spacemaps(checkpoint_spa, spa);
5082
5083 /*
5084 * Once we are done, we get rid of the checkpointed state.
5085 */
5086 spa_close(checkpoint_spa, FTAG);
5087 free(checkpoint_pool);
5088 }
5089
5090 static void
5091 dump_leftover_checkpoint_blocks(spa_t *spa)
5092 {
5093 vdev_t *rvd = spa->spa_root_vdev;
5094
5095 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
5096 vdev_t *vd = rvd->vdev_child[i];
5097
5098 space_map_t *checkpoint_sm = NULL;
5099 uint64_t checkpoint_sm_obj;
5100
5101 if (vd->vdev_top_zap == 0)
5102 continue;
5103
5104 if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
5105 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
5106 continue;
5107
5108 VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
5109 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
5110 sizeof (uint64_t), 1, &checkpoint_sm_obj));
5111
5112 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
5113 checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
5114 dump_spacemap(spa->spa_meta_objset, checkpoint_sm);
5115 space_map_close(checkpoint_sm);
5116 }
5117 }
5118
5119 static int
5120 verify_checkpoint(spa_t *spa)
5121 {
5122 uberblock_t checkpoint;
5123 int error;
5124
5125 if (!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT))
5126 return (0);
5127
5128 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
5129 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
5130 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
5131
5132 if (error == ENOENT && !dump_opt['L']) {
5133 /*
5134 * If the feature is active but the uberblock is missing
5135 * then we must be in the middle of discarding the
5136 * checkpoint.
5137 */
5138 (void) printf("\nPartially discarded checkpoint "
5139 "state found:\n");
5140 if (dump_opt['m'] > 3)
5141 dump_leftover_checkpoint_blocks(spa);
5142 return (0);
5143 } else if (error != 0) {
5144 (void) printf("lookup error %d when looking for "
5145 "checkpointed uberblock in MOS\n", error);
5146 return (error);
5147 }
5148 dump_uberblock(&checkpoint, "\nCheckpointed uberblock found:\n", "\n");
5149
5150 if (checkpoint.ub_checkpoint_txg == 0) {
5151 (void) printf("\nub_checkpoint_txg not set in checkpointed "
5152 "uberblock\n");
5153 error = 3;
5154 }
5155
5156 if (error == 0 && !dump_opt['L'])
5157 verify_checkpoint_blocks(spa);
5158
5159 return (error);
5160 }
5161
5162 /* ARGSUSED */
5163 static void
5164 mos_leaks_cb(void *arg, uint64_t start, uint64_t size)
5165 {
5166 for (uint64_t i = start; i < size; i++) {
5167 (void) printf("MOS object %llu referenced but not allocated\n",
5168 (u_longlong_t)i);
5169 }
5170 }
5171
5172 static void
5173 mos_obj_refd(uint64_t obj)
5174 {
5175 if (obj != 0 && mos_refd_objs != NULL)
5176 range_tree_add(mos_refd_objs, obj, 1);
5177 }
5178
5179 /*
5180 * Call on a MOS object that may already have been referenced.
5181 */
5182 static void
5183 mos_obj_refd_multiple(uint64_t obj)
5184 {
5185 if (obj != 0 && mos_refd_objs != NULL &&
5186 !range_tree_contains(mos_refd_objs, obj, 1))
5187 range_tree_add(mos_refd_objs, obj, 1);
5188 }
5189
5190 static void
5191 mos_leak_vdev(vdev_t *vd)
5192 {
5193 mos_obj_refd(vd->vdev_dtl_object);
5194 mos_obj_refd(vd->vdev_ms_array);
5195 mos_obj_refd(vd->vdev_top_zap);
5196 mos_obj_refd(vd->vdev_indirect_config.vic_births_object);
5197 mos_obj_refd(vd->vdev_indirect_config.vic_mapping_object);
5198 mos_obj_refd(vd->vdev_leaf_zap);
5199 if (vd->vdev_checkpoint_sm != NULL)
5200 mos_obj_refd(vd->vdev_checkpoint_sm->sm_object);
5201 if (vd->vdev_indirect_mapping != NULL) {
5202 mos_obj_refd(vd->vdev_indirect_mapping->
5203 vim_phys->vimp_counts_object);
5204 }
5205 if (vd->vdev_obsolete_sm != NULL)
5206 mos_obj_refd(vd->vdev_obsolete_sm->sm_object);
5207
5208 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
5209 metaslab_t *ms = vd->vdev_ms[m];
5210 mos_obj_refd(space_map_object(ms->ms_sm));
5211 }
5212
5213 for (uint64_t c = 0; c < vd->vdev_children; c++) {
5214 mos_leak_vdev(vd->vdev_child[c]);
5215 }
5216 }
5217
5218 static int
5219 dump_mos_leaks(spa_t *spa)
5220 {
5221 int rv = 0;
5222 objset_t *mos = spa->spa_meta_objset;
5223 dsl_pool_t *dp = spa->spa_dsl_pool;
5224
5225 /* Visit and mark all referenced objects in the MOS */
5226
5227 mos_obj_refd(DMU_POOL_DIRECTORY_OBJECT);
5228 mos_obj_refd(spa->spa_pool_props_object);
5229 mos_obj_refd(spa->spa_config_object);
5230 mos_obj_refd(spa->spa_ddt_stat_object);
5231 mos_obj_refd(spa->spa_feat_desc_obj);
5232 mos_obj_refd(spa->spa_feat_enabled_txg_obj);
5233 mos_obj_refd(spa->spa_feat_for_read_obj);
5234 mos_obj_refd(spa->spa_feat_for_write_obj);
5235 mos_obj_refd(spa->spa_history);
5236 mos_obj_refd(spa->spa_errlog_last);
5237 mos_obj_refd(spa->spa_errlog_scrub);
5238 mos_obj_refd(spa->spa_all_vdev_zaps);
5239 mos_obj_refd(spa->spa_dsl_pool->dp_bptree_obj);
5240 mos_obj_refd(spa->spa_dsl_pool->dp_tmp_userrefs_obj);
5241 mos_obj_refd(spa->spa_dsl_pool->dp_scan->scn_phys.scn_queue_obj);
5242 bpobj_count_refd(&spa->spa_deferred_bpobj);
5243 mos_obj_refd(dp->dp_empty_bpobj);
5244 bpobj_count_refd(&dp->dp_obsolete_bpobj);
5245 bpobj_count_refd(&dp->dp_free_bpobj);
5246 mos_obj_refd(spa->spa_l2cache.sav_object);
5247 mos_obj_refd(spa->spa_spares.sav_object);
5248
5249 mos_obj_refd(spa->spa_condensing_indirect_phys.
5250 scip_next_mapping_object);
5251 mos_obj_refd(spa->spa_condensing_indirect_phys.
5252 scip_prev_obsolete_sm_object);
5253 if (spa->spa_condensing_indirect_phys.scip_next_mapping_object != 0) {
5254 vdev_indirect_mapping_t *vim =
5255 vdev_indirect_mapping_open(mos,
5256 spa->spa_condensing_indirect_phys.scip_next_mapping_object);
5257 mos_obj_refd(vim->vim_phys->vimp_counts_object);
5258 vdev_indirect_mapping_close(vim);
5259 }
5260
5261 if (dp->dp_origin_snap != NULL) {
5262 dsl_dataset_t *ds;
5263
5264 dsl_pool_config_enter(dp, FTAG);
5265 VERIFY0(dsl_dataset_hold_obj(dp,
5266 dsl_dataset_phys(dp->dp_origin_snap)->ds_next_snap_obj,
5267 FTAG, &ds));
5268 count_ds_mos_objects(ds);
5269 dump_deadlist(&ds->ds_deadlist);
5270 dsl_dataset_rele(ds, FTAG);
5271 dsl_pool_config_exit(dp, FTAG);
5272
5273 count_ds_mos_objects(dp->dp_origin_snap);
5274 dump_deadlist(&dp->dp_origin_snap->ds_deadlist);
5275 }
5276 count_dir_mos_objects(dp->dp_mos_dir);
5277 if (dp->dp_free_dir != NULL)
5278 count_dir_mos_objects(dp->dp_free_dir);
5279 if (dp->dp_leak_dir != NULL)
5280 count_dir_mos_objects(dp->dp_leak_dir);
5281
5282 mos_leak_vdev(spa->spa_root_vdev);
5283
5284 for (uint64_t class = 0; class < DDT_CLASSES; class++) {
5285 for (uint64_t type = 0; type < DDT_TYPES; type++) {
5286 for (uint64_t cksum = 0;
5287 cksum < ZIO_CHECKSUM_FUNCTIONS; cksum++) {
5288 ddt_t *ddt = spa->spa_ddt[cksum];
5289 mos_obj_refd(ddt->ddt_object[type][class]);
5290 }
5291 }
5292 }
5293
5294 /*
5295 * Visit all allocated objects and make sure they are referenced.
5296 */
5297 uint64_t object = 0;
5298 while (dmu_object_next(mos, &object, B_FALSE, 0) == 0) {
5299 if (range_tree_contains(mos_refd_objs, object, 1)) {
5300 range_tree_remove(mos_refd_objs, object, 1);
5301 } else {
5302 dmu_object_info_t doi;
5303 const char *name;
5304 dmu_object_info(mos, object, &doi);
5305 if (doi.doi_type & DMU_OT_NEWTYPE) {
5306 dmu_object_byteswap_t bswap =
5307 DMU_OT_BYTESWAP(doi.doi_type);
5308 name = dmu_ot_byteswap[bswap].ob_name;
5309 } else {
5310 name = dmu_ot[doi.doi_type].ot_name;
5311 }
5312
5313 (void) printf("MOS object %llu (%s) leaked\n",
5314 (u_longlong_t)object, name);
5315 rv = 2;
5316 }
5317 }
5318 (void) range_tree_walk(mos_refd_objs, mos_leaks_cb, NULL);
5319 if (!range_tree_is_empty(mos_refd_objs))
5320 rv = 2;
5321 range_tree_vacate(mos_refd_objs, NULL, NULL);
5322 range_tree_destroy(mos_refd_objs);
5323 return (rv);
5324 }
5325
5326 static void
5327 dump_zpool(spa_t *spa)
5328 {
5329 dsl_pool_t *dp = spa_get_dsl(spa);
5330 int rc = 0;
5331
5332 if (dump_opt['S']) {
5333 dump_simulated_ddt(spa);
5334 return;
5335 }
5336
5337 if (!dump_opt['e'] && dump_opt['C'] > 1) {
5338 (void) printf("\nCached configuration:\n");
5339 dump_nvlist(spa->spa_config, 8);
5340 }
5341
5342 if (dump_opt['C'])
5343 dump_config(spa);
5344
5345 if (dump_opt['u'])
5346 dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
5347
5348 if (dump_opt['D'])
5349 dump_all_ddts(spa);
5350
5351 if (dump_opt['d'] > 2 || dump_opt['m'])
5352 dump_metaslabs(spa);
5353 if (dump_opt['M'])
5354 dump_metaslab_groups(spa);
5355
5356 if (dump_opt['d'] || dump_opt['i']) {
5357 spa_feature_t f;
5358 mos_refd_objs = range_tree_create(NULL, NULL);
5359 dump_dir(dp->dp_meta_objset);
5360
5361 if (dump_opt['d'] >= 3) {
5362 dsl_pool_t *dp = spa->spa_dsl_pool;
5363 dump_full_bpobj(&spa->spa_deferred_bpobj,
5364 "Deferred frees", 0);
5365 if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
5366 dump_full_bpobj(&dp->dp_free_bpobj,
5367 "Pool snapshot frees", 0);
5368 }
5369 if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
5370 ASSERT(spa_feature_is_enabled(spa,
5371 SPA_FEATURE_DEVICE_REMOVAL));
5372 dump_full_bpobj(&dp->dp_obsolete_bpobj,
5373 "Pool obsolete blocks", 0);
5374 }
5375
5376 if (spa_feature_is_active(spa,
5377 SPA_FEATURE_ASYNC_DESTROY)) {
5378 dump_bptree(spa->spa_meta_objset,
5379 dp->dp_bptree_obj,
5380 "Pool dataset frees");
5381 }
5382 dump_dtl(spa->spa_root_vdev, 0);
5383 }
5384 (void) dmu_objset_find(spa_name(spa), dump_one_dir,
5385 NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
5386
5387 if (rc == 0 && !dump_opt['L'])
5388 rc = dump_mos_leaks(spa);
5389
5390 for (f = 0; f < SPA_FEATURES; f++) {
5391 uint64_t refcount;
5392
5393 if (!(spa_feature_table[f].fi_flags &
5394 ZFEATURE_FLAG_PER_DATASET) ||
5395 !spa_feature_is_enabled(spa, f)) {
5396 ASSERT0(dataset_feature_count[f]);
5397 continue;
5398 }
5399 if (feature_get_refcount(spa, &spa_feature_table[f],
5400 &refcount) == ENOTSUP)
5401 continue;
5402 if (dataset_feature_count[f] != refcount) {
5403 (void) printf("%s feature refcount mismatch: "
5404 "%lld datasets != %lld refcount\n",
5405 spa_feature_table[f].fi_uname,
5406 (longlong_t)dataset_feature_count[f],
5407 (longlong_t)refcount);
5408 rc = 2;
5409 } else {
5410 (void) printf("Verified %s feature refcount "
5411 "of %llu is correct\n",
5412 spa_feature_table[f].fi_uname,
5413 (longlong_t)refcount);
5414 }
5415 }
5416
5417 if (rc == 0) {
5418 rc = verify_device_removal_feature_counts(spa);
5419 }
5420 }
5421
5422 if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
5423 rc = dump_block_stats(spa);
5424
5425 if (rc == 0)
5426 rc = verify_spacemap_refcounts(spa);
5427
5428 if (dump_opt['s'])
5429 show_pool_stats(spa);
5430
5431 if (dump_opt['h'])
5432 dump_history(spa);
5433
5434 if (rc == 0)
5435 rc = verify_checkpoint(spa);
5436
5437 if (rc != 0) {
5438 dump_debug_buffer();
5439 exit(rc);
5440 }
5441 }
5442
5443 #define ZDB_FLAG_CHECKSUM 0x0001
5444 #define ZDB_FLAG_DECOMPRESS 0x0002
5445 #define ZDB_FLAG_BSWAP 0x0004
5446 #define ZDB_FLAG_GBH 0x0008
5447 #define ZDB_FLAG_INDIRECT 0x0010
5448 #define ZDB_FLAG_PHYS 0x0020
5449 #define ZDB_FLAG_RAW 0x0040
5450 #define ZDB_FLAG_PRINT_BLKPTR 0x0080
5451
5452 static int flagbits[256];
5453
5454 static void
5455 zdb_print_blkptr(blkptr_t *bp, int flags)
5456 {
5457 char blkbuf[BP_SPRINTF_LEN];
5458
5459 if (flags & ZDB_FLAG_BSWAP)
5460 byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
5461
5462 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5463 (void) printf("%s\n", blkbuf);
5464 }
5465
5466 static void
5467 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
5468 {
5469 int i;
5470
5471 for (i = 0; i < nbps; i++)
5472 zdb_print_blkptr(&bp[i], flags);
5473 }
5474
5475 static void
5476 zdb_dump_gbh(void *buf, int flags)
5477 {
5478 zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
5479 }
5480
5481 static void
5482 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
5483 {
5484 if (flags & ZDB_FLAG_BSWAP)
5485 byteswap_uint64_array(buf, size);
5486 VERIFY(write(fileno(stdout), buf, size) == size);
5487 }
5488
5489 static void
5490 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
5491 {
5492 uint64_t *d = (uint64_t *)buf;
5493 unsigned nwords = size / sizeof (uint64_t);
5494 int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
5495 unsigned i, j;
5496 const char *hdr;
5497 char *c;
5498
5499
5500 if (do_bswap)
5501 hdr = " 7 6 5 4 3 2 1 0 f e d c b a 9 8";
5502 else
5503 hdr = " 0 1 2 3 4 5 6 7 8 9 a b c d e f";
5504
5505 (void) printf("\n%s\n%6s %s 0123456789abcdef\n", label, "", hdr);
5506
5507 #ifdef _LITTLE_ENDIAN
5508 /* correct the endianness */
5509 do_bswap = !do_bswap;
5510 #endif
5511 for (i = 0; i < nwords; i += 2) {
5512 (void) printf("%06llx: %016llx %016llx ",
5513 (u_longlong_t)(i * sizeof (uint64_t)),
5514 (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
5515 (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
5516
5517 c = (char *)&d[i];
5518 for (j = 0; j < 2 * sizeof (uint64_t); j++)
5519 (void) printf("%c", isprint(c[j]) ? c[j] : '.');
5520 (void) printf("\n");
5521 }
5522 }
5523
5524 /*
5525 * There are two acceptable formats:
5526 * leaf_name - For example: c1t0d0 or /tmp/ztest.0a
5527 * child[.child]* - For example: 0.1.1
5528 *
5529 * The second form can be used to specify arbitrary vdevs anywhere
5530 * in the hierarchy. For example, in a pool with a mirror of
5531 * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
5532 */
5533 static vdev_t *
5534 zdb_vdev_lookup(vdev_t *vdev, const char *path)
5535 {
5536 char *s, *p, *q;
5537 unsigned i;
5538
5539 if (vdev == NULL)
5540 return (NULL);
5541
5542 /* First, assume the x.x.x.x format */
5543 i = strtoul(path, &s, 10);
5544 if (s == path || (s && *s != '.' && *s != '\0'))
5545 goto name;
5546 if (i >= vdev->vdev_children)
5547 return (NULL);
5548
5549 vdev = vdev->vdev_child[i];
5550 if (s && *s == '\0')
5551 return (vdev);
5552 return (zdb_vdev_lookup(vdev, s+1));
5553
5554 name:
5555 for (i = 0; i < vdev->vdev_children; i++) {
5556 vdev_t *vc = vdev->vdev_child[i];
5557
5558 if (vc->vdev_path == NULL) {
5559 vc = zdb_vdev_lookup(vc, path);
5560 if (vc == NULL)
5561 continue;
5562 else
5563 return (vc);
5564 }
5565
5566 p = strrchr(vc->vdev_path, '/');
5567 p = p ? p + 1 : vc->vdev_path;
5568 q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
5569
5570 if (strcmp(vc->vdev_path, path) == 0)
5571 return (vc);
5572 if (strcmp(p, path) == 0)
5573 return (vc);
5574 if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
5575 return (vc);
5576 }
5577
5578 return (NULL);
5579 }
5580
5581 /*
5582 * Read a block from a pool and print it out. The syntax of the
5583 * block descriptor is:
5584 *
5585 * pool:vdev_specifier:offset:size[:flags]
5586 *
5587 * pool - The name of the pool you wish to read from
5588 * vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
5589 * offset - offset, in hex, in bytes
5590 * size - Amount of data to read, in hex, in bytes
5591 * flags - A string of characters specifying options
5592 * b: Decode a blkptr at given offset within block
5593 * *c: Calculate and display checksums
5594 * d: Decompress data before dumping
5595 * e: Byteswap data before dumping
5596 * g: Display data as a gang block header
5597 * i: Display as an indirect block
5598 * p: Do I/O to physical offset
5599 * r: Dump raw data to stdout
5600 *
5601 * * = not yet implemented
5602 */
5603 static void
5604 zdb_read_block(char *thing, spa_t *spa)
5605 {
5606 blkptr_t blk, *bp = &blk;
5607 dva_t *dva = bp->blk_dva;
5608 int flags = 0;
5609 uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
5610 zio_t *zio;
5611 vdev_t *vd;
5612 abd_t *pabd;
5613 void *lbuf, *buf;
5614 const char *s, *vdev;
5615 char *p, *dup, *flagstr;
5616 int i, error;
5617 boolean_t borrowed = B_FALSE;
5618
5619 dup = strdup(thing);
5620 s = strtok(dup, ":");
5621 vdev = s ? s : "";
5622 s = strtok(NULL, ":");
5623 offset = strtoull(s ? s : "", NULL, 16);
5624 s = strtok(NULL, ":");
5625 size = strtoull(s ? s : "", NULL, 16);
5626 s = strtok(NULL, ":");
5627 if (s)
5628 flagstr = strdup(s);
5629 else
5630 flagstr = strdup("");
5631
5632 s = NULL;
5633 if (size == 0)
5634 s = "size must not be zero";
5635 if (!IS_P2ALIGNED(size, DEV_BSIZE))
5636 s = "size must be a multiple of sector size";
5637 if (!IS_P2ALIGNED(offset, DEV_BSIZE))
5638 s = "offset must be a multiple of sector size";
5639 if (s) {
5640 (void) printf("Invalid block specifier: %s - %s\n", thing, s);
5641 free(flagstr);
5642 free(dup);
5643 return;
5644 }
5645
5646 for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
5647 for (i = 0; flagstr[i]; i++) {
5648 int bit = flagbits[(uchar_t)flagstr[i]];
5649
5650 if (bit == 0) {
5651 (void) printf("***Invalid flag: %c\n",
5652 flagstr[i]);
5653 continue;
5654 }
5655 flags |= bit;
5656
5657 /* If it's not something with an argument, keep going */
5658 if ((bit & (ZDB_FLAG_CHECKSUM |
5659 ZDB_FLAG_PRINT_BLKPTR)) == 0)
5660 continue;
5661
5662 p = &flagstr[i + 1];
5663 if (bit == ZDB_FLAG_PRINT_BLKPTR) {
5664 blkptr_offset = strtoull(p, &p, 16);
5665 i = p - &flagstr[i + 1];
5666 }
5667 if (*p != ':' && *p != '\0') {
5668 (void) printf("***Invalid flag arg: '%s'\n", s);
5669 free(flagstr);
5670 free(dup);
5671 return;
5672 }
5673 }
5674 }
5675 free(flagstr);
5676
5677 vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
5678 if (vd == NULL) {
5679 (void) printf("***Invalid vdev: %s\n", vdev);
5680 free(dup);
5681 return;
5682 } else {
5683 if (vd->vdev_path)
5684 (void) fprintf(stderr, "Found vdev: %s\n",
5685 vd->vdev_path);
5686 else
5687 (void) fprintf(stderr, "Found vdev type: %s\n",
5688 vd->vdev_ops->vdev_op_type);
5689 }
5690
5691 psize = size;
5692 lsize = size;
5693
5694 pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
5695 lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
5696
5697 BP_ZERO(bp);
5698
5699 DVA_SET_VDEV(&dva[0], vd->vdev_id);
5700 DVA_SET_OFFSET(&dva[0], offset);
5701 DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
5702 DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
5703
5704 BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
5705
5706 BP_SET_LSIZE(bp, lsize);
5707 BP_SET_PSIZE(bp, psize);
5708 BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
5709 BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
5710 BP_SET_TYPE(bp, DMU_OT_NONE);
5711 BP_SET_LEVEL(bp, 0);
5712 BP_SET_DEDUP(bp, 0);
5713 BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
5714
5715 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5716 zio = zio_root(spa, NULL, NULL, 0);
5717
5718 if (vd == vd->vdev_top) {
5719 /*
5720 * Treat this as a normal block read.
5721 */
5722 zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
5723 ZIO_PRIORITY_SYNC_READ,
5724 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
5725 } else {
5726 /*
5727 * Treat this as a vdev child I/O.
5728 */
5729 zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
5730 psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
5731 ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
5732 ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
5733 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW | ZIO_FLAG_OPTIONAL,
5734 NULL, NULL));
5735 }
5736
5737 error = zio_wait(zio);
5738 spa_config_exit(spa, SCL_STATE, FTAG);
5739
5740 if (error) {
5741 (void) printf("Read of %s failed, error: %d\n", thing, error);
5742 goto out;
5743 }
5744
5745 if (flags & ZDB_FLAG_DECOMPRESS) {
5746 /*
5747 * We don't know how the data was compressed, so just try
5748 * every decompress function at every inflated blocksize.
5749 */
5750 enum zio_compress c;
5751 void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
5752
5753 /*
5754 * XXX - On the one hand, with SPA_MAXBLOCKSIZE at 16MB,
5755 * this could take a while and we should let the user know
5756 * we are not stuck. On the other hand, printing progress
5757 * info gets old after a while. What to do?
5758 */
5759 for (lsize = psize + SPA_MINBLOCKSIZE;
5760 lsize <= SPA_MAXBLOCKSIZE; lsize += SPA_MINBLOCKSIZE) {
5761 for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
5762 /*
5763 * ZLE can easily decompress non zle stream.
5764 * So have an option to disable it.
5765 */
5766 if (c == ZIO_COMPRESS_ZLE &&
5767 getenv("ZDB_NO_ZLE"))
5768 continue;
5769
5770 (void) fprintf(stderr,
5771 "Trying %05llx -> %05llx (%s)\n",
5772 (u_longlong_t)psize, (u_longlong_t)lsize,
5773 zio_compress_table[c].ci_name);
5774
5775 /*
5776 * We randomize lbuf2, and decompress to both
5777 * lbuf and lbuf2. This way, we will know if
5778 * decompression fill exactly to lsize.
5779 */
5780 VERIFY0(random_get_pseudo_bytes(lbuf2, lsize));
5781
5782 if (zio_decompress_data(c, pabd,
5783 lbuf, psize, lsize) == 0 &&
5784 zio_decompress_data(c, pabd,
5785 lbuf2, psize, lsize) == 0 &&
5786 bcmp(lbuf, lbuf2, lsize) == 0)
5787 break;
5788 }
5789 if (c != ZIO_COMPRESS_FUNCTIONS)
5790 break;
5791 }
5792 umem_free(lbuf2, SPA_MAXBLOCKSIZE);
5793
5794 if (lsize > SPA_MAXBLOCKSIZE) {
5795 (void) printf("Decompress of %s failed\n", thing);
5796 goto out;
5797 }
5798 buf = lbuf;
5799 size = lsize;
5800 } else {
5801 size = psize;
5802 buf = abd_borrow_buf_copy(pabd, size);
5803 borrowed = B_TRUE;
5804 }
5805
5806 if (flags & ZDB_FLAG_PRINT_BLKPTR)
5807 zdb_print_blkptr((blkptr_t *)(void *)
5808 ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
5809 else if (flags & ZDB_FLAG_RAW)
5810 zdb_dump_block_raw(buf, size, flags);
5811 else if (flags & ZDB_FLAG_INDIRECT)
5812 zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
5813 flags);
5814 else if (flags & ZDB_FLAG_GBH)
5815 zdb_dump_gbh(buf, flags);
5816 else
5817 zdb_dump_block(thing, buf, size, flags);
5818
5819 if (borrowed)
5820 abd_return_buf_copy(pabd, buf, size);
5821
5822 out:
5823 abd_free(pabd);
5824 umem_free(lbuf, SPA_MAXBLOCKSIZE);
5825 free(dup);
5826 }
5827
5828 static void
5829 zdb_embedded_block(char *thing)
5830 {
5831 blkptr_t bp;
5832 unsigned long long *words = (void *)&bp;
5833 char *buf;
5834 int err;
5835
5836 bzero(&bp, sizeof (bp));
5837 err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
5838 "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
5839 words + 0, words + 1, words + 2, words + 3,
5840 words + 4, words + 5, words + 6, words + 7,
5841 words + 8, words + 9, words + 10, words + 11,
5842 words + 12, words + 13, words + 14, words + 15);
5843 if (err != 16) {
5844 (void) fprintf(stderr, "invalid input format\n");
5845 exit(1);
5846 }
5847 ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
5848 buf = malloc(SPA_MAXBLOCKSIZE);
5849 if (buf == NULL) {
5850 (void) fprintf(stderr, "out of memory\n");
5851 exit(1);
5852 }
5853 err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
5854 if (err != 0) {
5855 (void) fprintf(stderr, "decode failed: %u\n", err);
5856 exit(1);
5857 }
5858 zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
5859 free(buf);
5860 }
5861
5862 int
5863 main(int argc, char **argv)
5864 {
5865 int c;
5866 struct rlimit rl = { 1024, 1024 };
5867 spa_t *spa = NULL;
5868 objset_t *os = NULL;
5869 int dump_all = 1;
5870 int verbose = 0;
5871 int error = 0;
5872 char **searchdirs = NULL;
5873 int nsearch = 0;
5874 char *target, *target_pool;
5875 nvlist_t *policy = NULL;
5876 uint64_t max_txg = UINT64_MAX;
5877 int flags = ZFS_IMPORT_MISSING_LOG;
5878 int rewind = ZPOOL_NEVER_REWIND;
5879 char *spa_config_path_env;
5880 boolean_t target_is_spa = B_TRUE;
5881 nvlist_t *cfg = NULL;
5882
5883 (void) setrlimit(RLIMIT_NOFILE, &rl);
5884 (void) enable_extended_FILE_stdio(-1, -1);
5885
5886 dprintf_setup(&argc, argv);
5887
5888 /*
5889 * If there is an environment variable SPA_CONFIG_PATH it overrides
5890 * default spa_config_path setting. If -U flag is specified it will
5891 * override this environment variable settings once again.
5892 */
5893 spa_config_path_env = getenv("SPA_CONFIG_PATH");
5894 if (spa_config_path_env != NULL)
5895 spa_config_path = spa_config_path_env;
5896
5897 while ((c = getopt(argc, argv,
5898 "AbcCdDeEFGhiI:klLmMo:Op:PqRsSt:uU:vVx:XY")) != -1) {
5899 switch (c) {
5900 case 'b':
5901 case 'c':
5902 case 'C':
5903 case 'd':
5904 case 'D':
5905 case 'E':
5906 case 'G':
5907 case 'h':
5908 case 'i':
5909 case 'l':
5910 case 'm':
5911 case 'M':
5912 case 'O':
5913 case 'R':
5914 case 's':
5915 case 'S':
5916 case 'u':
5917 dump_opt[c]++;
5918 dump_all = 0;
5919 break;
5920 case 'A':
5921 case 'e':
5922 case 'F':
5923 case 'k':
5924 case 'L':
5925 case 'P':
5926 case 'q':
5927 case 'X':
5928 dump_opt[c]++;
5929 break;
5930 case 'Y':
5931 zfs_reconstruct_indirect_combinations_max = INT_MAX;
5932 zfs_deadman_enabled = 0;
5933 break;
5934 /* NB: Sort single match options below. */
5935 case 'I':
5936 max_inflight = strtoull(optarg, NULL, 0);
5937 if (max_inflight == 0) {
5938 (void) fprintf(stderr, "maximum number "
5939 "of inflight I/Os must be greater "
5940 "than 0\n");
5941 usage();
5942 }
5943 break;
5944 case 'o':
5945 error = set_global_var(optarg);
5946 if (error != 0)
5947 usage();
5948 break;
5949 case 'p':
5950 if (searchdirs == NULL) {
5951 searchdirs = umem_alloc(sizeof (char *),
5952 UMEM_NOFAIL);
5953 } else {
5954 char **tmp = umem_alloc((nsearch + 1) *
5955 sizeof (char *), UMEM_NOFAIL);
5956 bcopy(searchdirs, tmp, nsearch *
5957 sizeof (char *));
5958 umem_free(searchdirs,
5959 nsearch * sizeof (char *));
5960 searchdirs = tmp;
5961 }
5962 searchdirs[nsearch++] = optarg;
5963 break;
5964 case 't':
5965 max_txg = strtoull(optarg, NULL, 0);
5966 if (max_txg < TXG_INITIAL) {
5967 (void) fprintf(stderr, "incorrect txg "
5968 "specified: %s\n", optarg);
5969 usage();
5970 }
5971 break;
5972 case 'U':
5973 spa_config_path = optarg;
5974 if (spa_config_path[0] != '/') {
5975 (void) fprintf(stderr,
5976 "cachefile must be an absolute path "
5977 "(i.e. start with a slash)\n");
5978 usage();
5979 }
5980 break;
5981 case 'v':
5982 verbose++;
5983 break;
5984 case 'V':
5985 flags = ZFS_IMPORT_VERBATIM;
5986 break;
5987 case 'x':
5988 vn_dumpdir = optarg;
5989 break;
5990 default:
5991 usage();
5992 break;
5993 }
5994 }
5995
5996 if (!dump_opt['e'] && searchdirs != NULL) {
5997 (void) fprintf(stderr, "-p option requires use of -e\n");
5998 usage();
5999 }
6000
6001 #if defined(_LP64)
6002 /*
6003 * ZDB does not typically re-read blocks; therefore limit the ARC
6004 * to 256 MB, which can be used entirely for metadata.
6005 */
6006 zfs_arc_max = zfs_arc_meta_limit = 256 * 1024 * 1024;
6007 #endif
6008
6009 /*
6010 * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
6011 * "zdb -b" uses traversal prefetch which uses async reads.
6012 * For good performance, let several of them be active at once.
6013 */
6014 zfs_vdev_async_read_max_active = 10;
6015
6016 /*
6017 * Disable reference tracking for better performance.
6018 */
6019 reference_tracking_enable = B_FALSE;
6020
6021 /*
6022 * Do not fail spa_load when spa_load_verify fails. This is needed
6023 * to load non-idle pools.
6024 */
6025 spa_load_verify_dryrun = B_TRUE;
6026
6027 kernel_init(FREAD);
6028
6029 if (dump_all)
6030 verbose = MAX(verbose, 1);
6031
6032 for (c = 0; c < 256; c++) {
6033 if (dump_all && strchr("AeEFklLOPRSX", c) == NULL)
6034 dump_opt[c] = 1;
6035 if (dump_opt[c])
6036 dump_opt[c] += verbose;
6037 }
6038
6039 aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
6040 zfs_recover = (dump_opt['A'] > 1);
6041
6042 argc -= optind;
6043 argv += optind;
6044
6045 if (argc < 2 && dump_opt['R'])
6046 usage();
6047
6048 if (dump_opt['E']) {
6049 if (argc != 1)
6050 usage();
6051 zdb_embedded_block(argv[0]);
6052 return (0);
6053 }
6054
6055 if (argc < 1) {
6056 if (!dump_opt['e'] && dump_opt['C']) {
6057 dump_cachefile(spa_config_path);
6058 return (0);
6059 }
6060 usage();
6061 }
6062
6063 if (dump_opt['l'])
6064 return (dump_label(argv[0]));
6065
6066 if (dump_opt['O']) {
6067 if (argc != 2)
6068 usage();
6069 dump_opt['v'] = verbose + 3;
6070 return (dump_path(argv[0], argv[1]));
6071 }
6072
6073 if (dump_opt['X'] || dump_opt['F'])
6074 rewind = ZPOOL_DO_REWIND |
6075 (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
6076
6077 if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
6078 nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, max_txg) != 0 ||
6079 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY, rewind) != 0)
6080 fatal("internal error: %s", strerror(ENOMEM));
6081
6082 error = 0;
6083 target = argv[0];
6084
6085 if (strpbrk(target, "/@") != NULL) {
6086 size_t targetlen;
6087
6088 target_pool = strdup(target);
6089 *strpbrk(target_pool, "/@") = '\0';
6090
6091 target_is_spa = B_FALSE;
6092 targetlen = strlen(target);
6093 if (targetlen && target[targetlen - 1] == '/')
6094 target[targetlen - 1] = '\0';
6095 } else {
6096 target_pool = target;
6097 }
6098
6099 if (dump_opt['e']) {
6100 importargs_t args = { 0 };
6101
6102 args.paths = nsearch;
6103 args.path = searchdirs;
6104 args.can_be_active = B_TRUE;
6105
6106 error = zpool_find_config(NULL, target_pool, &cfg, &args,
6107 &libzpool_config_ops);
6108
6109 if (error == 0) {
6110
6111 if (nvlist_add_nvlist(cfg,
6112 ZPOOL_LOAD_POLICY, policy) != 0) {
6113 fatal("can't open '%s': %s",
6114 target, strerror(ENOMEM));
6115 }
6116
6117 if (dump_opt['C'] > 1) {
6118 (void) printf("\nConfiguration for import:\n");
6119 dump_nvlist(cfg, 8);
6120 }
6121
6122 /*
6123 * Disable the activity check to allow examination of
6124 * active pools.
6125 */
6126 error = spa_import(target_pool, cfg, NULL,
6127 flags | ZFS_IMPORT_SKIP_MMP);
6128 }
6129 }
6130
6131 /*
6132 * import_checkpointed_state makes the assumption that the
6133 * target pool that we pass it is already part of the spa
6134 * namespace. Because of that we need to make sure to call
6135 * it always after the -e option has been processed, which
6136 * imports the pool to the namespace if it's not in the
6137 * cachefile.
6138 */
6139 char *checkpoint_pool = NULL;
6140 char *checkpoint_target = NULL;
6141 if (dump_opt['k']) {
6142 checkpoint_pool = import_checkpointed_state(target, cfg,
6143 &checkpoint_target);
6144
6145 if (checkpoint_target != NULL)
6146 target = checkpoint_target;
6147 }
6148
6149 if (target_pool != target)
6150 free(target_pool);
6151
6152 if (error == 0) {
6153 if (dump_opt['k'] && (target_is_spa || dump_opt['R'])) {
6154 ASSERT(checkpoint_pool != NULL);
6155 ASSERT(checkpoint_target == NULL);
6156
6157 error = spa_open(checkpoint_pool, &spa, FTAG);
6158 if (error != 0) {
6159 fatal("Tried to open pool \"%s\" but "
6160 "spa_open() failed with error %d\n",
6161 checkpoint_pool, error);
6162 }
6163
6164 } else if (target_is_spa || dump_opt['R']) {
6165 zdb_set_skip_mmp(target);
6166 error = spa_open_rewind(target, &spa, FTAG, policy,
6167 NULL);
6168 if (error) {
6169 /*
6170 * If we're missing the log device then
6171 * try opening the pool after clearing the
6172 * log state.
6173 */
6174 mutex_enter(&spa_namespace_lock);
6175 if ((spa = spa_lookup(target)) != NULL &&
6176 spa->spa_log_state == SPA_LOG_MISSING) {
6177 spa->spa_log_state = SPA_LOG_CLEAR;
6178 error = 0;
6179 }
6180 mutex_exit(&spa_namespace_lock);
6181
6182 if (!error) {
6183 error = spa_open_rewind(target, &spa,
6184 FTAG, policy, NULL);
6185 }
6186 }
6187 } else {
6188 zdb_set_skip_mmp(target);
6189 error = open_objset(target, DMU_OST_ANY, FTAG, &os);
6190 if (error == 0)
6191 spa = dmu_objset_spa(os);
6192 }
6193 }
6194 nvlist_free(policy);
6195
6196 if (error)
6197 fatal("can't open '%s': %s", target, strerror(error));
6198
6199 /*
6200 * Set the pool failure mode to panic in order to prevent the pool
6201 * from suspending. A suspended I/O will have no way to resume and
6202 * can prevent the zdb(8) command from terminating as expected.
6203 */
6204 if (spa != NULL)
6205 spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
6206
6207 argv++;
6208 argc--;
6209 if (!dump_opt['R']) {
6210 if (argc > 0) {
6211 zopt_objects = argc;
6212 zopt_object = calloc(zopt_objects, sizeof (uint64_t));
6213 for (unsigned i = 0; i < zopt_objects; i++) {
6214 errno = 0;
6215 zopt_object[i] = strtoull(argv[i], NULL, 0);
6216 if (zopt_object[i] == 0 && errno != 0)
6217 fatal("bad number %s: %s",
6218 argv[i], strerror(errno));
6219 }
6220 }
6221 if (os != NULL) {
6222 dump_dir(os);
6223 } else if (zopt_objects > 0 && !dump_opt['m']) {
6224 dump_dir(spa->spa_meta_objset);
6225 } else {
6226 dump_zpool(spa);
6227 }
6228 } else {
6229 flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
6230 flagbits['c'] = ZDB_FLAG_CHECKSUM;
6231 flagbits['d'] = ZDB_FLAG_DECOMPRESS;
6232 flagbits['e'] = ZDB_FLAG_BSWAP;
6233 flagbits['g'] = ZDB_FLAG_GBH;
6234 flagbits['i'] = ZDB_FLAG_INDIRECT;
6235 flagbits['p'] = ZDB_FLAG_PHYS;
6236 flagbits['r'] = ZDB_FLAG_RAW;
6237
6238 for (int i = 0; i < argc; i++)
6239 zdb_read_block(argv[i], spa);
6240 }
6241
6242 if (dump_opt['k']) {
6243 free(checkpoint_pool);
6244 if (!target_is_spa)
6245 free(checkpoint_target);
6246 }
6247
6248 if (os != NULL)
6249 close_objset(os, FTAG);
6250 else
6251 spa_close(spa, FTAG);
6252
6253 fuid_table_destroy();
6254
6255 dump_debug_buffer();
6256
6257 kernel_fini();
6258
6259 return (error);
6260 }