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