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