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