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