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