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