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