]> granicus.if.org Git - zfs/blob - cmd/zdb/zdb.c
zdb -d has false positive warning when feature@large_blocks=disabled
[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, 2014 by Delphix. All rights reserved.
25  * Copyright (c) 2015, Intel Corporation.
26  */
27
28 #include <stdio.h>
29 #include <unistd.h>
30 #include <stdio_ext.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33 #include <sys/zfs_context.h>
34 #include <sys/spa.h>
35 #include <sys/spa_impl.h>
36 #include <sys/dmu.h>
37 #include <sys/zap.h>
38 #include <sys/fs/zfs.h>
39 #include <sys/zfs_znode.h>
40 #include <sys/zfs_sa.h>
41 #include <sys/sa.h>
42 #include <sys/sa_impl.h>
43 #include <sys/vdev.h>
44 #include <sys/vdev_impl.h>
45 #include <sys/metaslab_impl.h>
46 #include <sys/dmu_objset.h>
47 #include <sys/dsl_dir.h>
48 #include <sys/dsl_dataset.h>
49 #include <sys/dsl_pool.h>
50 #include <sys/dbuf.h>
51 #include <sys/zil.h>
52 #include <sys/zil_impl.h>
53 #include <sys/stat.h>
54 #include <sys/resource.h>
55 #include <sys/dmu_traverse.h>
56 #include <sys/zio_checksum.h>
57 #include <sys/zio_compress.h>
58 #include <sys/zfs_fuid.h>
59 #include <sys/arc.h>
60 #include <sys/ddt.h>
61 #include <sys/zfeature.h>
62 #include <zfs_comutil.h>
63 #undef ZFS_MAXNAMELEN
64 #include <libzfs.h>
65
66 #define ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ?        \
67         zio_compress_table[(idx)].ci_name : "UNKNOWN")
68 #define ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ?        \
69         zio_checksum_table[(idx)].ci_name : "UNKNOWN")
70 #define ZDB_OT_NAME(idx) ((idx) < DMU_OT_NUMTYPES ?     \
71         dmu_ot[(idx)].ot_name : DMU_OT_IS_VALID(idx) ?  \
72         dmu_ot_byteswap[DMU_OT_BYTESWAP(idx)].ob_name : "UNKNOWN")
73 #define ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) :             \
74         (((idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA) ? \
75         DMU_OT_ZAP_OTHER : DMU_OT_NUMTYPES))
76
77 #ifndef lint
78 extern int zfs_recover;
79 extern uint64_t zfs_arc_max, zfs_arc_meta_limit;
80 extern int zfs_vdev_async_read_max_active;
81 #else
82 int zfs_recover;
83 uint64_t zfs_arc_max, zfs_arc_meta_limit;
84 int zfs_vdev_async_read_max_active;
85 #endif
86
87 const char cmdname[] = "zdb";
88 uint8_t dump_opt[256];
89
90 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
91
92 extern void dump_intent_log(zilog_t *);
93 uint64_t *zopt_object = NULL;
94 int zopt_objects = 0;
95 libzfs_handle_t *g_zfs;
96 uint64_t max_inflight = 1000;
97
98 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *);
99
100 /*
101  * These libumem hooks provide a reasonable set of defaults for the allocator's
102  * debugging facilities.
103  */
104 const char *
105 _umem_debug_init(void)
106 {
107         return ("default,verbose"); /* $UMEM_DEBUG setting */
108 }
109
110 const char *
111 _umem_logging_init(void)
112 {
113         return ("fail,contents"); /* $UMEM_LOGGING setting */
114 }
115
116 static void
117 usage(void)
118 {
119         (void) fprintf(stderr,
120             "Usage: %s [-CumMdibcsDvhLXFPA] [-t txg] [-e [-p path...]] "
121             "[-U config] [-I inflight I/Os] poolname [object...]\n"
122             "       %s [-divPA] [-e -p path...] [-U config] dataset "
123             "[object...]\n"
124             "       %s -mM [-LXFPA] [-t txg] [-e [-p path...]] [-U config] "
125             "poolname [vdev [metaslab...]]\n"
126             "       %s -R [-A] [-e [-p path...]] poolname "
127             "vdev:offset:size[:flags]\n"
128             "       %s -S [-PA] [-e [-p path...]] [-U config] poolname\n"
129             "       %s -l [-uA] device\n"
130             "       %s -C [-A] [-U config]\n\n",
131             cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname);
132
133         (void) fprintf(stderr, "    Dataset name must include at least one "
134             "separator character '/' or '@'\n");
135         (void) fprintf(stderr, "    If dataset name is specified, only that "
136             "dataset is dumped\n");
137         (void) fprintf(stderr, "    If object numbers are specified, only "
138             "those objects are dumped\n\n");
139         (void) fprintf(stderr, "    Options to control amount of output:\n");
140         (void) fprintf(stderr, "        -u uberblock\n");
141         (void) fprintf(stderr, "        -d dataset(s)\n");
142         (void) fprintf(stderr, "        -i intent logs\n");
143         (void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
144         (void) fprintf(stderr, "        -h pool history\n");
145         (void) fprintf(stderr, "        -b block statistics\n");
146         (void) fprintf(stderr, "        -m metaslabs\n");
147         (void) fprintf(stderr, "        -M metaslab groups\n");
148         (void) fprintf(stderr, "        -c checksum all metadata (twice for "
149             "all data) blocks\n");
150         (void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
151         (void) fprintf(stderr, "        -D dedup statistics\n");
152         (void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
153         (void) fprintf(stderr, "        -v verbose (applies to all others)\n");
154         (void) fprintf(stderr, "        -l dump label contents\n");
155         (void) fprintf(stderr, "        -L disable leak tracking (do not "
156             "load spacemaps)\n");
157         (void) fprintf(stderr, "        -R read and display block from a "
158             "device\n\n");
159         (void) fprintf(stderr, "    Below options are intended for use "
160             "with other options (except -l):\n");
161         (void) fprintf(stderr, "        -A ignore assertions (-A), enable "
162             "panic recovery (-AA) or both (-AAA)\n");
163         (void) fprintf(stderr, "        -F attempt automatic rewind within "
164             "safe range of transaction groups\n");
165         (void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
166             "cachefile\n");
167         (void) fprintf(stderr, "        -X attempt extreme rewind (does not "
168             "work with dataset)\n");
169         (void) fprintf(stderr, "        -e pool is exported/destroyed/"
170             "has altroot/not in a cachefile\n");
171         (void) fprintf(stderr, "        -p <path> -- use one or more with "
172             "-e to specify path to vdev dir\n");
173         (void) fprintf(stderr, "        -P print numbers in parseable form\n");
174         (void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
175             "searching for uberblocks\n");
176         (void) fprintf(stderr, "        -I <number of inflight I/Os> -- "
177             "specify the maximum number of checksumming I/Os "
178             "[default is 200]\n");
179         (void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
180             "to make only that option verbose\n");
181         (void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
182         exit(1);
183 }
184
185 /*
186  * Called for usage errors that are discovered after a call to spa_open(),
187  * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
188  */
189
190 static void
191 fatal(const char *fmt, ...)
192 {
193         va_list ap;
194
195         va_start(ap, fmt);
196         (void) fprintf(stderr, "%s: ", cmdname);
197         (void) vfprintf(stderr, fmt, ap);
198         va_end(ap);
199         (void) fprintf(stderr, "\n");
200
201         exit(1);
202 }
203
204 /* ARGSUSED */
205 static void
206 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
207 {
208         nvlist_t *nv;
209         size_t nvsize = *(uint64_t *)data;
210         char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
211
212         VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
213
214         VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
215
216         umem_free(packed, nvsize);
217
218         dump_nvlist(nv, 8);
219
220         nvlist_free(nv);
221 }
222
223 /* ARGSUSED */
224 static void
225 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
226 {
227         spa_history_phys_t *shp = data;
228
229         if (shp == NULL)
230                 return;
231
232         (void) printf("\t\tpool_create_len = %llu\n",
233             (u_longlong_t)shp->sh_pool_create_len);
234         (void) printf("\t\tphys_max_off = %llu\n",
235             (u_longlong_t)shp->sh_phys_max_off);
236         (void) printf("\t\tbof = %llu\n",
237             (u_longlong_t)shp->sh_bof);
238         (void) printf("\t\teof = %llu\n",
239             (u_longlong_t)shp->sh_eof);
240         (void) printf("\t\trecords_lost = %llu\n",
241             (u_longlong_t)shp->sh_records_lost);
242 }
243
244 static void
245 zdb_nicenum(uint64_t num, char *buf)
246 {
247         if (dump_opt['P'])
248                 (void) sprintf(buf, "%llu", (longlong_t)num);
249         else
250                 nicenum(num, buf);
251 }
252
253 const char histo_stars[] = "****************************************";
254 const int histo_width = sizeof (histo_stars) - 1;
255
256 static void
257 dump_histogram(const uint64_t *histo, int size, int offset)
258 {
259         int i;
260         int minidx = size - 1;
261         int maxidx = 0;
262         uint64_t max = 0;
263
264         for (i = 0; i < size; i++) {
265                 if (histo[i] > max)
266                         max = histo[i];
267                 if (histo[i] > 0 && i > maxidx)
268                         maxidx = i;
269                 if (histo[i] > 0 && i < minidx)
270                         minidx = i;
271         }
272
273         if (max < histo_width)
274                 max = histo_width;
275
276         for (i = minidx; i <= maxidx; i++) {
277                 (void) printf("\t\t\t%3u: %6llu %s\n",
278                     i + offset, (u_longlong_t)histo[i],
279                     &histo_stars[(max - histo[i]) * histo_width / max]);
280         }
281 }
282
283 static void
284 dump_zap_stats(objset_t *os, uint64_t object)
285 {
286         int error;
287         zap_stats_t zs;
288
289         error = zap_get_stats(os, object, &zs);
290         if (error)
291                 return;
292
293         if (zs.zs_ptrtbl_len == 0) {
294                 ASSERT(zs.zs_num_blocks == 1);
295                 (void) printf("\tmicrozap: %llu bytes, %llu entries\n",
296                     (u_longlong_t)zs.zs_blocksize,
297                     (u_longlong_t)zs.zs_num_entries);
298                 return;
299         }
300
301         (void) printf("\tFat ZAP stats:\n");
302
303         (void) printf("\t\tPointer table:\n");
304         (void) printf("\t\t\t%llu elements\n",
305             (u_longlong_t)zs.zs_ptrtbl_len);
306         (void) printf("\t\t\tzt_blk: %llu\n",
307             (u_longlong_t)zs.zs_ptrtbl_zt_blk);
308         (void) printf("\t\t\tzt_numblks: %llu\n",
309             (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
310         (void) printf("\t\t\tzt_shift: %llu\n",
311             (u_longlong_t)zs.zs_ptrtbl_zt_shift);
312         (void) printf("\t\t\tzt_blks_copied: %llu\n",
313             (u_longlong_t)zs.zs_ptrtbl_blks_copied);
314         (void) printf("\t\t\tzt_nextblk: %llu\n",
315             (u_longlong_t)zs.zs_ptrtbl_nextblk);
316
317         (void) printf("\t\tZAP entries: %llu\n",
318             (u_longlong_t)zs.zs_num_entries);
319         (void) printf("\t\tLeaf blocks: %llu\n",
320             (u_longlong_t)zs.zs_num_leafs);
321         (void) printf("\t\tTotal blocks: %llu\n",
322             (u_longlong_t)zs.zs_num_blocks);
323         (void) printf("\t\tzap_block_type: 0x%llx\n",
324             (u_longlong_t)zs.zs_block_type);
325         (void) printf("\t\tzap_magic: 0x%llx\n",
326             (u_longlong_t)zs.zs_magic);
327         (void) printf("\t\tzap_salt: 0x%llx\n",
328             (u_longlong_t)zs.zs_salt);
329
330         (void) printf("\t\tLeafs with 2^n pointers:\n");
331         dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
332
333         (void) printf("\t\tBlocks with n*5 entries:\n");
334         dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
335
336         (void) printf("\t\tBlocks n/10 full:\n");
337         dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
338
339         (void) printf("\t\tEntries with n chunks:\n");
340         dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
341
342         (void) printf("\t\tBuckets with n entries:\n");
343         dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
344 }
345
346 /*ARGSUSED*/
347 static void
348 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
349 {
350 }
351
352 /*ARGSUSED*/
353 static void
354 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
355 {
356         (void) printf("\tUNKNOWN OBJECT TYPE\n");
357 }
358
359 /*ARGSUSED*/
360 void
361 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
362 {
363 }
364
365 /*ARGSUSED*/
366 static void
367 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
368 {
369 }
370
371 /*ARGSUSED*/
372 static void
373 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
374 {
375         zap_cursor_t zc;
376         zap_attribute_t attr;
377         void *prop;
378         int i;
379
380         dump_zap_stats(os, object);
381         (void) printf("\n");
382
383         for (zap_cursor_init(&zc, os, object);
384             zap_cursor_retrieve(&zc, &attr) == 0;
385             zap_cursor_advance(&zc)) {
386                 (void) printf("\t\t%s = ", attr.za_name);
387                 if (attr.za_num_integers == 0) {
388                         (void) printf("\n");
389                         continue;
390                 }
391                 prop = umem_zalloc(attr.za_num_integers *
392                     attr.za_integer_length, UMEM_NOFAIL);
393                 (void) zap_lookup(os, object, attr.za_name,
394                     attr.za_integer_length, attr.za_num_integers, prop);
395                 if (attr.za_integer_length == 1) {
396                         (void) printf("%s", (char *)prop);
397                 } else {
398                         for (i = 0; i < attr.za_num_integers; i++) {
399                                 switch (attr.za_integer_length) {
400                                 case 2:
401                                         (void) printf("%u ",
402                                             ((uint16_t *)prop)[i]);
403                                         break;
404                                 case 4:
405                                         (void) printf("%u ",
406                                             ((uint32_t *)prop)[i]);
407                                         break;
408                                 case 8:
409                                         (void) printf("%lld ",
410                                             (u_longlong_t)((int64_t *)prop)[i]);
411                                         break;
412                                 }
413                         }
414                 }
415                 (void) printf("\n");
416                 umem_free(prop, attr.za_num_integers * attr.za_integer_length);
417         }
418         zap_cursor_fini(&zc);
419 }
420
421 static void
422 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
423 {
424         bpobj_phys_t *bpop = data;
425         uint64_t i;
426         char bytes[32], comp[32], uncomp[32];
427
428         if (bpop == NULL)
429                 return;
430
431         zdb_nicenum(bpop->bpo_bytes, bytes);
432         zdb_nicenum(bpop->bpo_comp, comp);
433         zdb_nicenum(bpop->bpo_uncomp, uncomp);
434
435         (void) printf("\t\tnum_blkptrs = %llu\n",
436             (u_longlong_t)bpop->bpo_num_blkptrs);
437         (void) printf("\t\tbytes = %s\n", bytes);
438         if (size >= BPOBJ_SIZE_V1) {
439                 (void) printf("\t\tcomp = %s\n", comp);
440                 (void) printf("\t\tuncomp = %s\n", uncomp);
441         }
442         if (size >= sizeof (*bpop)) {
443                 (void) printf("\t\tsubobjs = %llu\n",
444                     (u_longlong_t)bpop->bpo_subobjs);
445                 (void) printf("\t\tnum_subobjs = %llu\n",
446                     (u_longlong_t)bpop->bpo_num_subobjs);
447         }
448
449         if (dump_opt['d'] < 5)
450                 return;
451
452         for (i = 0; i < bpop->bpo_num_blkptrs; i++) {
453                 char blkbuf[BP_SPRINTF_LEN];
454                 blkptr_t bp;
455
456                 int err = dmu_read(os, object,
457                     i * sizeof (bp), sizeof (bp), &bp, 0);
458                 if (err != 0) {
459                         (void) printf("got error %u from dmu_read\n", err);
460                         break;
461                 }
462                 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp);
463                 (void) printf("\t%s\n", blkbuf);
464         }
465 }
466
467 /* ARGSUSED */
468 static void
469 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
470 {
471         dmu_object_info_t doi;
472         uint64_t i;
473
474         VERIFY0(dmu_object_info(os, object, &doi));
475         uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
476
477         int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
478         if (err != 0) {
479                 (void) printf("got error %u from dmu_read\n", err);
480                 kmem_free(subobjs, doi.doi_max_offset);
481                 return;
482         }
483
484         int64_t last_nonzero = -1;
485         for (i = 0; i < doi.doi_max_offset / 8; i++) {
486                 if (subobjs[i] != 0)
487                         last_nonzero = i;
488         }
489
490         for (i = 0; i <= last_nonzero; i++) {
491                 (void) printf("\t%llu\n", (longlong_t)subobjs[i]);
492         }
493         kmem_free(subobjs, doi.doi_max_offset);
494 }
495
496 /*ARGSUSED*/
497 static void
498 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
499 {
500         dump_zap_stats(os, object);
501         /* contents are printed elsewhere, properly decoded */
502 }
503
504 /*ARGSUSED*/
505 static void
506 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
507 {
508         zap_cursor_t zc;
509         zap_attribute_t attr;
510
511         dump_zap_stats(os, object);
512         (void) printf("\n");
513
514         for (zap_cursor_init(&zc, os, object);
515             zap_cursor_retrieve(&zc, &attr) == 0;
516             zap_cursor_advance(&zc)) {
517                 (void) printf("\t\t%s = ", attr.za_name);
518                 if (attr.za_num_integers == 0) {
519                         (void) printf("\n");
520                         continue;
521                 }
522                 (void) printf(" %llx : [%d:%d:%d]\n",
523                     (u_longlong_t)attr.za_first_integer,
524                     (int)ATTR_LENGTH(attr.za_first_integer),
525                     (int)ATTR_BSWAP(attr.za_first_integer),
526                     (int)ATTR_NUM(attr.za_first_integer));
527         }
528         zap_cursor_fini(&zc);
529 }
530
531 /*ARGSUSED*/
532 static void
533 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
534 {
535         zap_cursor_t zc;
536         zap_attribute_t attr;
537         uint16_t *layout_attrs;
538         int i;
539
540         dump_zap_stats(os, object);
541         (void) printf("\n");
542
543         for (zap_cursor_init(&zc, os, object);
544             zap_cursor_retrieve(&zc, &attr) == 0;
545             zap_cursor_advance(&zc)) {
546                 (void) printf("\t\t%s = [", attr.za_name);
547                 if (attr.za_num_integers == 0) {
548                         (void) printf("\n");
549                         continue;
550                 }
551
552                 VERIFY(attr.za_integer_length == 2);
553                 layout_attrs = umem_zalloc(attr.za_num_integers *
554                     attr.za_integer_length, UMEM_NOFAIL);
555
556                 VERIFY(zap_lookup(os, object, attr.za_name,
557                     attr.za_integer_length,
558                     attr.za_num_integers, layout_attrs) == 0);
559
560                 for (i = 0; i != attr.za_num_integers; i++)
561                         (void) printf(" %d ", (int)layout_attrs[i]);
562                 (void) printf("]\n");
563                 umem_free(layout_attrs,
564                     attr.za_num_integers * attr.za_integer_length);
565         }
566         zap_cursor_fini(&zc);
567 }
568
569 /*ARGSUSED*/
570 static void
571 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
572 {
573         zap_cursor_t zc;
574         zap_attribute_t attr;
575         const char *typenames[] = {
576                 /* 0 */ "not specified",
577                 /* 1 */ "FIFO",
578                 /* 2 */ "Character Device",
579                 /* 3 */ "3 (invalid)",
580                 /* 4 */ "Directory",
581                 /* 5 */ "5 (invalid)",
582                 /* 6 */ "Block Device",
583                 /* 7 */ "7 (invalid)",
584                 /* 8 */ "Regular File",
585                 /* 9 */ "9 (invalid)",
586                 /* 10 */ "Symbolic Link",
587                 /* 11 */ "11 (invalid)",
588                 /* 12 */ "Socket",
589                 /* 13 */ "Door",
590                 /* 14 */ "Event Port",
591                 /* 15 */ "15 (invalid)",
592         };
593
594         dump_zap_stats(os, object);
595         (void) printf("\n");
596
597         for (zap_cursor_init(&zc, os, object);
598             zap_cursor_retrieve(&zc, &attr) == 0;
599             zap_cursor_advance(&zc)) {
600                 (void) printf("\t\t%s = %lld (type: %s)\n",
601                     attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
602                     typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
603         }
604         zap_cursor_fini(&zc);
605 }
606
607 int
608 get_dtl_refcount(vdev_t *vd)
609 {
610         int refcount = 0;
611         int c;
612
613         if (vd->vdev_ops->vdev_op_leaf) {
614                 space_map_t *sm = vd->vdev_dtl_sm;
615
616                 if (sm != NULL &&
617                     sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
618                         return (1);
619                 return (0);
620         }
621
622         for (c = 0; c < vd->vdev_children; c++)
623                 refcount += get_dtl_refcount(vd->vdev_child[c]);
624         return (refcount);
625 }
626
627 int
628 get_metaslab_refcount(vdev_t *vd)
629 {
630         int refcount = 0;
631         int c, m;
632
633         if (vd->vdev_top == vd && !vd->vdev_removing) {
634                 for (m = 0; m < vd->vdev_ms_count; m++) {
635                         space_map_t *sm = vd->vdev_ms[m]->ms_sm;
636
637                         if (sm != NULL &&
638                             sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
639                                 refcount++;
640                 }
641         }
642         for (c = 0; c < vd->vdev_children; c++)
643                 refcount += get_metaslab_refcount(vd->vdev_child[c]);
644
645         return (refcount);
646 }
647
648 static int
649 verify_spacemap_refcounts(spa_t *spa)
650 {
651         uint64_t expected_refcount = 0;
652         uint64_t actual_refcount;
653
654         (void) feature_get_refcount(spa,
655             &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
656             &expected_refcount);
657         actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
658         actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
659
660         if (expected_refcount != actual_refcount) {
661                 (void) printf("space map refcount mismatch: expected %lld != "
662                     "actual %lld\n",
663                     (longlong_t)expected_refcount,
664                     (longlong_t)actual_refcount);
665                 return (2);
666         }
667         return (0);
668 }
669
670 static void
671 dump_spacemap(objset_t *os, space_map_t *sm)
672 {
673         uint64_t alloc, offset, entry;
674         char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
675                             "INVALID", "INVALID", "INVALID", "INVALID" };
676
677         if (sm == NULL)
678                 return;
679
680         /*
681          * Print out the freelist entries in both encoded and decoded form.
682          */
683         alloc = 0;
684         for (offset = 0; offset < space_map_length(sm);
685             offset += sizeof (entry)) {
686                 uint8_t mapshift = sm->sm_shift;
687
688                 VERIFY0(dmu_read(os, space_map_object(sm), offset,
689                     sizeof (entry), &entry, DMU_READ_PREFETCH));
690                 if (SM_DEBUG_DECODE(entry)) {
691
692                         (void) printf("\t    [%6llu] %s: txg %llu, pass %llu\n",
693                             (u_longlong_t)(offset / sizeof (entry)),
694                             ddata[SM_DEBUG_ACTION_DECODE(entry)],
695                             (u_longlong_t)SM_DEBUG_TXG_DECODE(entry),
696                             (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(entry));
697                 } else {
698                         (void) printf("\t    [%6llu]    %c  range:"
699                             " %010llx-%010llx  size: %06llx\n",
700                             (u_longlong_t)(offset / sizeof (entry)),
701                             SM_TYPE_DECODE(entry) == SM_ALLOC ? 'A' : 'F',
702                             (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
703                             mapshift) + sm->sm_start),
704                             (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
705                             mapshift) + sm->sm_start +
706                             (SM_RUN_DECODE(entry) << mapshift)),
707                             (u_longlong_t)(SM_RUN_DECODE(entry) << mapshift));
708                         if (SM_TYPE_DECODE(entry) == SM_ALLOC)
709                                 alloc += SM_RUN_DECODE(entry) << mapshift;
710                         else
711                                 alloc -= SM_RUN_DECODE(entry) << mapshift;
712                 }
713         }
714         if (alloc != space_map_allocated(sm)) {
715                 (void) printf("space_map_object alloc (%llu) INCONSISTENT "
716                     "with space map summary (%llu)\n",
717                     (u_longlong_t)space_map_allocated(sm), (u_longlong_t)alloc);
718         }
719 }
720
721 static void
722 dump_metaslab_stats(metaslab_t *msp)
723 {
724         char maxbuf[32];
725         range_tree_t *rt = msp->ms_tree;
726         avl_tree_t *t = &msp->ms_size_tree;
727         int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
728
729         zdb_nicenum(metaslab_block_maxsize(msp), maxbuf);
730
731         (void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
732             "segments", avl_numnodes(t), "maxsize", maxbuf,
733             "freepct", free_pct);
734         (void) printf("\tIn-memory histogram:\n");
735         dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
736 }
737
738 static void
739 dump_metaslab(metaslab_t *msp)
740 {
741         vdev_t *vd = msp->ms_group->mg_vd;
742         spa_t *spa = vd->vdev_spa;
743         space_map_t *sm = msp->ms_sm;
744         char freebuf[32];
745
746         zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf);
747
748         (void) printf(
749             "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
750             (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
751             (u_longlong_t)space_map_object(sm), freebuf);
752
753         if (dump_opt['m'] > 2 && !dump_opt['L']) {
754                 mutex_enter(&msp->ms_lock);
755                 metaslab_load_wait(msp);
756                 if (!msp->ms_loaded) {
757                         VERIFY0(metaslab_load(msp));
758                         range_tree_stat_verify(msp->ms_tree);
759                 }
760                 dump_metaslab_stats(msp);
761                 metaslab_unload(msp);
762                 mutex_exit(&msp->ms_lock);
763         }
764
765         if (dump_opt['m'] > 1 && sm != NULL &&
766             spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
767                 /*
768                  * The space map histogram represents free space in chunks
769                  * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
770                  */
771                 (void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
772                     (u_longlong_t)msp->ms_fragmentation);
773                 dump_histogram(sm->sm_phys->smp_histogram,
774                     SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
775         }
776
777         if (dump_opt['d'] > 5 || dump_opt['m'] > 3) {
778                 ASSERT(msp->ms_size == (1ULL << vd->vdev_ms_shift));
779
780                 mutex_enter(&msp->ms_lock);
781                 dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
782                 mutex_exit(&msp->ms_lock);
783         }
784 }
785
786 static void
787 print_vdev_metaslab_header(vdev_t *vd)
788 {
789         (void) printf("\tvdev %10llu\n\t%-10s%5llu   %-19s   %-15s   %-10s\n",
790             (u_longlong_t)vd->vdev_id,
791             "metaslabs", (u_longlong_t)vd->vdev_ms_count,
792             "offset", "spacemap", "free");
793         (void) printf("\t%15s   %19s   %15s   %10s\n",
794             "---------------", "-------------------",
795             "---------------", "-------------");
796 }
797
798 static void
799 dump_metaslab_groups(spa_t *spa)
800 {
801         vdev_t *rvd = spa->spa_root_vdev;
802         metaslab_class_t *mc = spa_normal_class(spa);
803         uint64_t fragmentation;
804         int c;
805
806         metaslab_class_histogram_verify(mc);
807
808         for (c = 0; c < rvd->vdev_children; c++) {
809                 vdev_t *tvd = rvd->vdev_child[c];
810                 metaslab_group_t *mg = tvd->vdev_mg;
811
812                 if (mg->mg_class != mc)
813                         continue;
814
815                 metaslab_group_histogram_verify(mg);
816                 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
817
818                 (void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
819                     "fragmentation",
820                     (u_longlong_t)tvd->vdev_id,
821                     (u_longlong_t)tvd->vdev_ms_count);
822                 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
823                         (void) printf("%3s\n", "-");
824                 } else {
825                         (void) printf("%3llu%%\n",
826                             (u_longlong_t)mg->mg_fragmentation);
827                 }
828                 dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
829         }
830
831         (void) printf("\tpool %s\tfragmentation", spa_name(spa));
832         fragmentation = metaslab_class_fragmentation(mc);
833         if (fragmentation == ZFS_FRAG_INVALID)
834                 (void) printf("\t%3s\n", "-");
835         else
836                 (void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
837         dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
838 }
839
840 static void
841 dump_metaslabs(spa_t *spa)
842 {
843         vdev_t *vd, *rvd = spa->spa_root_vdev;
844         uint64_t m, c = 0, children = rvd->vdev_children;
845
846         (void) printf("\nMetaslabs:\n");
847
848         if (!dump_opt['d'] && zopt_objects > 0) {
849                 c = zopt_object[0];
850
851                 if (c >= children)
852                         (void) fatal("bad vdev id: %llu", (u_longlong_t)c);
853
854                 if (zopt_objects > 1) {
855                         vd = rvd->vdev_child[c];
856                         print_vdev_metaslab_header(vd);
857
858                         for (m = 1; m < zopt_objects; m++) {
859                                 if (zopt_object[m] < vd->vdev_ms_count)
860                                         dump_metaslab(
861                                             vd->vdev_ms[zopt_object[m]]);
862                                 else
863                                         (void) fprintf(stderr, "bad metaslab "
864                                             "number %llu\n",
865                                             (u_longlong_t)zopt_object[m]);
866                         }
867                         (void) printf("\n");
868                         return;
869                 }
870                 children = c + 1;
871         }
872         for (; c < children; c++) {
873                 vd = rvd->vdev_child[c];
874                 print_vdev_metaslab_header(vd);
875
876                 for (m = 0; m < vd->vdev_ms_count; m++)
877                         dump_metaslab(vd->vdev_ms[m]);
878                 (void) printf("\n");
879         }
880 }
881
882 static void
883 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
884 {
885         const ddt_phys_t *ddp = dde->dde_phys;
886         const ddt_key_t *ddk = &dde->dde_key;
887         char *types[4] = { "ditto", "single", "double", "triple" };
888         char blkbuf[BP_SPRINTF_LEN];
889         blkptr_t blk;
890         int p;
891
892         for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
893                 if (ddp->ddp_phys_birth == 0)
894                         continue;
895                 ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
896                 snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
897                 (void) printf("index %llx refcnt %llu %s %s\n",
898                     (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
899                     types[p], blkbuf);
900         }
901 }
902
903 static void
904 dump_dedup_ratio(const ddt_stat_t *dds)
905 {
906         double rL, rP, rD, D, dedup, compress, copies;
907
908         if (dds->dds_blocks == 0)
909                 return;
910
911         rL = (double)dds->dds_ref_lsize;
912         rP = (double)dds->dds_ref_psize;
913         rD = (double)dds->dds_ref_dsize;
914         D = (double)dds->dds_dsize;
915
916         dedup = rD / D;
917         compress = rL / rP;
918         copies = rD / rP;
919
920         (void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
921             "dedup * compress / copies = %.2f\n\n",
922             dedup, compress, copies, dedup * compress / copies);
923 }
924
925 static void
926 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
927 {
928         char name[DDT_NAMELEN];
929         ddt_entry_t dde;
930         uint64_t walk = 0;
931         dmu_object_info_t doi;
932         uint64_t count, dspace, mspace;
933         int error;
934
935         error = ddt_object_info(ddt, type, class, &doi);
936
937         if (error == ENOENT)
938                 return;
939         ASSERT(error == 0);
940
941         error = ddt_object_count(ddt, type, class, &count);
942         ASSERT(error == 0);
943         if (count == 0)
944                 return;
945
946         dspace = doi.doi_physical_blocks_512 << 9;
947         mspace = doi.doi_fill_count * doi.doi_data_block_size;
948
949         ddt_object_name(ddt, type, class, name);
950
951         (void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
952             name,
953             (u_longlong_t)count,
954             (u_longlong_t)(dspace / count),
955             (u_longlong_t)(mspace / count));
956
957         if (dump_opt['D'] < 3)
958                 return;
959
960         zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
961
962         if (dump_opt['D'] < 4)
963                 return;
964
965         if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
966                 return;
967
968         (void) printf("%s contents:\n\n", name);
969
970         while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
971                 dump_dde(ddt, &dde, walk);
972
973         ASSERT(error == ENOENT);
974
975         (void) printf("\n");
976 }
977
978 static void
979 dump_all_ddts(spa_t *spa)
980 {
981         ddt_histogram_t ddh_total;
982         ddt_stat_t dds_total;
983         enum zio_checksum c;
984         enum ddt_type type;
985         enum ddt_class class;
986
987         bzero(&ddh_total, sizeof (ddt_histogram_t));
988         bzero(&dds_total, sizeof (ddt_stat_t));
989
990         for (c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
991                 ddt_t *ddt = spa->spa_ddt[c];
992                 for (type = 0; type < DDT_TYPES; type++) {
993                         for (class = 0; class < DDT_CLASSES;
994                             class++) {
995                                 dump_ddt(ddt, type, class);
996                         }
997                 }
998         }
999
1000         ddt_get_dedup_stats(spa, &dds_total);
1001
1002         if (dds_total.dds_blocks == 0) {
1003                 (void) printf("All DDTs are empty\n");
1004                 return;
1005         }
1006
1007         (void) printf("\n");
1008
1009         if (dump_opt['D'] > 1) {
1010                 (void) printf("DDT histogram (aggregated over all DDTs):\n");
1011                 ddt_get_dedup_histogram(spa, &ddh_total);
1012                 zpool_dump_ddt(&dds_total, &ddh_total);
1013         }
1014
1015         dump_dedup_ratio(&dds_total);
1016 }
1017
1018 static void
1019 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
1020 {
1021         char *prefix = arg;
1022
1023         (void) printf("%s [%llu,%llu) length %llu\n",
1024             prefix,
1025             (u_longlong_t)start,
1026             (u_longlong_t)(start + size),
1027             (u_longlong_t)(size));
1028 }
1029
1030 static void
1031 dump_dtl(vdev_t *vd, int indent)
1032 {
1033         spa_t *spa = vd->vdev_spa;
1034         boolean_t required;
1035         char *name[DTL_TYPES] = { "missing", "partial", "scrub", "outage" };
1036         char prefix[256];
1037         int c, t;
1038
1039         spa_vdev_state_enter(spa, SCL_NONE);
1040         required = vdev_dtl_required(vd);
1041         (void) spa_vdev_state_exit(spa, NULL, 0);
1042
1043         if (indent == 0)
1044                 (void) printf("\nDirty time logs:\n\n");
1045
1046         (void) printf("\t%*s%s [%s]\n", indent, "",
1047             vd->vdev_path ? vd->vdev_path :
1048             vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
1049             required ? "DTL-required" : "DTL-expendable");
1050
1051         for (t = 0; t < DTL_TYPES; t++) {
1052                 range_tree_t *rt = vd->vdev_dtl[t];
1053                 if (range_tree_space(rt) == 0)
1054                         continue;
1055                 (void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
1056                     indent + 2, "", name[t]);
1057                 mutex_enter(rt->rt_lock);
1058                 range_tree_walk(rt, dump_dtl_seg, prefix);
1059                 mutex_exit(rt->rt_lock);
1060                 if (dump_opt['d'] > 5 && vd->vdev_children == 0)
1061                         dump_spacemap(spa->spa_meta_objset,
1062                             vd->vdev_dtl_sm);
1063         }
1064
1065         for (c = 0; c < vd->vdev_children; c++)
1066                 dump_dtl(vd->vdev_child[c], indent + 4);
1067 }
1068
1069 static void
1070 dump_history(spa_t *spa)
1071 {
1072         nvlist_t **events = NULL;
1073         char buf[SPA_MAXBLOCKSIZE];
1074         uint64_t resid, len, off = 0;
1075         uint_t num = 0;
1076         int error;
1077         time_t tsec;
1078         struct tm t;
1079         char tbuf[30];
1080         char internalstr[MAXPATHLEN];
1081         int i;
1082
1083         do {
1084                 len = sizeof (buf);
1085
1086                 if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
1087                         (void) fprintf(stderr, "Unable to read history: "
1088                             "error %d\n", error);
1089                         return;
1090                 }
1091
1092                 if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
1093                         break;
1094
1095                 off -= resid;
1096         } while (len != 0);
1097
1098         (void) printf("\nHistory:\n");
1099         for (i = 0; i < num; i++) {
1100                 uint64_t time, txg, ievent;
1101                 char *cmd, *intstr;
1102                 boolean_t printed = B_FALSE;
1103
1104                 if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
1105                     &time) != 0)
1106                         goto next;
1107                 if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
1108                     &cmd) != 0) {
1109                         if (nvlist_lookup_uint64(events[i],
1110                             ZPOOL_HIST_INT_EVENT, &ievent) != 0)
1111                                 goto next;
1112                         verify(nvlist_lookup_uint64(events[i],
1113                             ZPOOL_HIST_TXG, &txg) == 0);
1114                         verify(nvlist_lookup_string(events[i],
1115                             ZPOOL_HIST_INT_STR, &intstr) == 0);
1116                         if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
1117                                 goto next;
1118
1119                         (void) snprintf(internalstr,
1120                             sizeof (internalstr),
1121                             "[internal %s txg:%lld] %s",
1122                             zfs_history_event_names[ievent],
1123                             (longlong_t)txg, intstr);
1124                         cmd = internalstr;
1125                 }
1126                 tsec = time;
1127                 (void) localtime_r(&tsec, &t);
1128                 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
1129                 (void) printf("%s %s\n", tbuf, cmd);
1130                 printed = B_TRUE;
1131
1132 next:
1133                 if (dump_opt['h'] > 1) {
1134                         if (!printed)
1135                                 (void) printf("unrecognized record:\n");
1136                         dump_nvlist(events[i], 2);
1137                 }
1138         }
1139 }
1140
1141 /*ARGSUSED*/
1142 static void
1143 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
1144 {
1145 }
1146
1147 static uint64_t
1148 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
1149     const zbookmark_phys_t *zb)
1150 {
1151         if (dnp == NULL) {
1152                 ASSERT(zb->zb_level < 0);
1153                 if (zb->zb_object == 0)
1154                         return (zb->zb_blkid);
1155                 return (zb->zb_blkid * BP_GET_LSIZE(bp));
1156         }
1157
1158         ASSERT(zb->zb_level >= 0);
1159
1160         return ((zb->zb_blkid <<
1161             (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
1162             dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
1163 }
1164
1165 static void
1166 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp)
1167 {
1168         const dva_t *dva = bp->blk_dva;
1169         int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
1170         int i;
1171
1172         if (dump_opt['b'] >= 6) {
1173                 snprintf_blkptr(blkbuf, buflen, bp);
1174                 return;
1175         }
1176
1177         if (BP_IS_EMBEDDED(bp)) {
1178                 (void) sprintf(blkbuf,
1179                     "EMBEDDED et=%u %llxL/%llxP B=%llu",
1180                     (int)BPE_GET_ETYPE(bp),
1181                     (u_longlong_t)BPE_GET_LSIZE(bp),
1182                     (u_longlong_t)BPE_GET_PSIZE(bp),
1183                     (u_longlong_t)bp->blk_birth);
1184                 return;
1185         }
1186
1187         blkbuf[0] = '\0';
1188
1189         for (i = 0; i < ndvas; i++)
1190                 (void) snprintf(blkbuf + strlen(blkbuf),
1191                     buflen - strlen(blkbuf), "%llu:%llx:%llx ",
1192                     (u_longlong_t)DVA_GET_VDEV(&dva[i]),
1193                     (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
1194                     (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
1195
1196         if (BP_IS_HOLE(bp)) {
1197                 (void) snprintf(blkbuf + strlen(blkbuf),
1198                     buflen - strlen(blkbuf),
1199                     "%llxL B=%llu",
1200                     (u_longlong_t)BP_GET_LSIZE(bp),
1201                     (u_longlong_t)bp->blk_birth);
1202         } else {
1203                 (void) snprintf(blkbuf + strlen(blkbuf),
1204                     buflen - strlen(blkbuf),
1205                     "%llxL/%llxP F=%llu B=%llu/%llu",
1206                     (u_longlong_t)BP_GET_LSIZE(bp),
1207                     (u_longlong_t)BP_GET_PSIZE(bp),
1208                     (u_longlong_t)BP_GET_FILL(bp),
1209                     (u_longlong_t)bp->blk_birth,
1210                     (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
1211         }
1212 }
1213
1214 static void
1215 print_indirect(blkptr_t *bp, const zbookmark_phys_t *zb,
1216     const dnode_phys_t *dnp)
1217 {
1218         char blkbuf[BP_SPRINTF_LEN];
1219         int l;
1220
1221         if (!BP_IS_EMBEDDED(bp)) {
1222                 ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
1223                 ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
1224         }
1225
1226         (void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
1227
1228         ASSERT(zb->zb_level >= 0);
1229
1230         for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
1231                 if (l == zb->zb_level) {
1232                         (void) printf("L%llx", (u_longlong_t)zb->zb_level);
1233                 } else {
1234                         (void) printf(" ");
1235                 }
1236         }
1237
1238         snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1239         (void) printf("%s\n", blkbuf);
1240 }
1241
1242 static int
1243 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
1244     blkptr_t *bp, const zbookmark_phys_t *zb)
1245 {
1246         int err = 0;
1247
1248         if (bp->blk_birth == 0)
1249                 return (0);
1250
1251         print_indirect(bp, zb, dnp);
1252
1253         if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
1254                 arc_flags_t flags = ARC_FLAG_WAIT;
1255                 int i;
1256                 blkptr_t *cbp;
1257                 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1258                 arc_buf_t *buf;
1259                 uint64_t fill = 0;
1260
1261                 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
1262                     ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
1263                 if (err)
1264                         return (err);
1265                 ASSERT(buf->b_data);
1266
1267                 /* recursively visit blocks below this */
1268                 cbp = buf->b_data;
1269                 for (i = 0; i < epb; i++, cbp++) {
1270                         zbookmark_phys_t czb;
1271
1272                         SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1273                             zb->zb_level - 1,
1274                             zb->zb_blkid * epb + i);
1275                         err = visit_indirect(spa, dnp, cbp, &czb);
1276                         if (err)
1277                                 break;
1278                         fill += BP_GET_FILL(cbp);
1279                 }
1280                 if (!err)
1281                         ASSERT3U(fill, ==, BP_GET_FILL(bp));
1282                 (void) arc_buf_remove_ref(buf, &buf);
1283         }
1284
1285         return (err);
1286 }
1287
1288 /*ARGSUSED*/
1289 static void
1290 dump_indirect(dnode_t *dn)
1291 {
1292         dnode_phys_t *dnp = dn->dn_phys;
1293         int j;
1294         zbookmark_phys_t czb;
1295
1296         (void) printf("Indirect blocks:\n");
1297
1298         SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1299             dn->dn_object, dnp->dn_nlevels - 1, 0);
1300         for (j = 0; j < dnp->dn_nblkptr; j++) {
1301                 czb.zb_blkid = j;
1302                 (void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1303                     &dnp->dn_blkptr[j], &czb);
1304         }
1305
1306         (void) printf("\n");
1307 }
1308
1309 /*ARGSUSED*/
1310 static void
1311 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1312 {
1313         dsl_dir_phys_t *dd = data;
1314         time_t crtime;
1315         char nice[32];
1316
1317         if (dd == NULL)
1318                 return;
1319
1320         ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1321
1322         crtime = dd->dd_creation_time;
1323         (void) printf("\t\tcreation_time = %s", ctime(&crtime));
1324         (void) printf("\t\thead_dataset_obj = %llu\n",
1325             (u_longlong_t)dd->dd_head_dataset_obj);
1326         (void) printf("\t\tparent_dir_obj = %llu\n",
1327             (u_longlong_t)dd->dd_parent_obj);
1328         (void) printf("\t\torigin_obj = %llu\n",
1329             (u_longlong_t)dd->dd_origin_obj);
1330         (void) printf("\t\tchild_dir_zapobj = %llu\n",
1331             (u_longlong_t)dd->dd_child_dir_zapobj);
1332         zdb_nicenum(dd->dd_used_bytes, nice);
1333         (void) printf("\t\tused_bytes = %s\n", nice);
1334         zdb_nicenum(dd->dd_compressed_bytes, nice);
1335         (void) printf("\t\tcompressed_bytes = %s\n", nice);
1336         zdb_nicenum(dd->dd_uncompressed_bytes, nice);
1337         (void) printf("\t\tuncompressed_bytes = %s\n", nice);
1338         zdb_nicenum(dd->dd_quota, nice);
1339         (void) printf("\t\tquota = %s\n", nice);
1340         zdb_nicenum(dd->dd_reserved, nice);
1341         (void) printf("\t\treserved = %s\n", nice);
1342         (void) printf("\t\tprops_zapobj = %llu\n",
1343             (u_longlong_t)dd->dd_props_zapobj);
1344         (void) printf("\t\tdeleg_zapobj = %llu\n",
1345             (u_longlong_t)dd->dd_deleg_zapobj);
1346         (void) printf("\t\tflags = %llx\n",
1347             (u_longlong_t)dd->dd_flags);
1348
1349 #define DO(which) \
1350         zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice); \
1351         (void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1352         DO(HEAD);
1353         DO(SNAP);
1354         DO(CHILD);
1355         DO(CHILD_RSRV);
1356         DO(REFRSRV);
1357 #undef DO
1358 }
1359
1360 /*ARGSUSED*/
1361 static void
1362 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1363 {
1364         dsl_dataset_phys_t *ds = data;
1365         time_t crtime;
1366         char used[32], compressed[32], uncompressed[32], unique[32];
1367         char blkbuf[BP_SPRINTF_LEN];
1368
1369         if (ds == NULL)
1370                 return;
1371
1372         ASSERT(size == sizeof (*ds));
1373         crtime = ds->ds_creation_time;
1374         zdb_nicenum(ds->ds_referenced_bytes, used);
1375         zdb_nicenum(ds->ds_compressed_bytes, compressed);
1376         zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed);
1377         zdb_nicenum(ds->ds_unique_bytes, unique);
1378         snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
1379
1380         (void) printf("\t\tdir_obj = %llu\n",
1381             (u_longlong_t)ds->ds_dir_obj);
1382         (void) printf("\t\tprev_snap_obj = %llu\n",
1383             (u_longlong_t)ds->ds_prev_snap_obj);
1384         (void) printf("\t\tprev_snap_txg = %llu\n",
1385             (u_longlong_t)ds->ds_prev_snap_txg);
1386         (void) printf("\t\tnext_snap_obj = %llu\n",
1387             (u_longlong_t)ds->ds_next_snap_obj);
1388         (void) printf("\t\tsnapnames_zapobj = %llu\n",
1389             (u_longlong_t)ds->ds_snapnames_zapobj);
1390         (void) printf("\t\tnum_children = %llu\n",
1391             (u_longlong_t)ds->ds_num_children);
1392         (void) printf("\t\tuserrefs_obj = %llu\n",
1393             (u_longlong_t)ds->ds_userrefs_obj);
1394         (void) printf("\t\tcreation_time = %s", ctime(&crtime));
1395         (void) printf("\t\tcreation_txg = %llu\n",
1396             (u_longlong_t)ds->ds_creation_txg);
1397         (void) printf("\t\tdeadlist_obj = %llu\n",
1398             (u_longlong_t)ds->ds_deadlist_obj);
1399         (void) printf("\t\tused_bytes = %s\n", used);
1400         (void) printf("\t\tcompressed_bytes = %s\n", compressed);
1401         (void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1402         (void) printf("\t\tunique = %s\n", unique);
1403         (void) printf("\t\tfsid_guid = %llu\n",
1404             (u_longlong_t)ds->ds_fsid_guid);
1405         (void) printf("\t\tguid = %llu\n",
1406             (u_longlong_t)ds->ds_guid);
1407         (void) printf("\t\tflags = %llx\n",
1408             (u_longlong_t)ds->ds_flags);
1409         (void) printf("\t\tnext_clones_obj = %llu\n",
1410             (u_longlong_t)ds->ds_next_clones_obj);
1411         (void) printf("\t\tprops_obj = %llu\n",
1412             (u_longlong_t)ds->ds_props_obj);
1413         (void) printf("\t\tbp = %s\n", blkbuf);
1414 }
1415
1416 /* ARGSUSED */
1417 static int
1418 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1419 {
1420         char blkbuf[BP_SPRINTF_LEN];
1421
1422         if (bp->blk_birth != 0) {
1423                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
1424                 (void) printf("\t%s\n", blkbuf);
1425         }
1426         return (0);
1427 }
1428
1429 static void
1430 dump_bptree(objset_t *os, uint64_t obj, char *name)
1431 {
1432         char bytes[32];
1433         bptree_phys_t *bt;
1434         dmu_buf_t *db;
1435
1436         if (dump_opt['d'] < 3)
1437                 return;
1438
1439         VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
1440         bt = db->db_data;
1441         zdb_nicenum(bt->bt_bytes, bytes);
1442         (void) printf("\n    %s: %llu datasets, %s\n",
1443             name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
1444         dmu_buf_rele(db, FTAG);
1445
1446         if (dump_opt['d'] < 5)
1447                 return;
1448
1449         (void) printf("\n");
1450
1451         (void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
1452 }
1453
1454 /* ARGSUSED */
1455 static int
1456 dump_bpobj_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1457 {
1458         char blkbuf[BP_SPRINTF_LEN];
1459
1460         ASSERT(bp->blk_birth != 0);
1461         snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1462         (void) printf("\t%s\n", blkbuf);
1463         return (0);
1464 }
1465
1466 static void
1467 dump_full_bpobj(bpobj_t *bpo, char *name, int indent)
1468 {
1469         char bytes[32];
1470         char comp[32];
1471         char uncomp[32];
1472         uint64_t i;
1473
1474         if (dump_opt['d'] < 3)
1475                 return;
1476
1477         zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes);
1478         if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1479                 zdb_nicenum(bpo->bpo_phys->bpo_comp, comp);
1480                 zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp);
1481                 (void) printf("    %*s: object %llu, %llu local blkptrs, "
1482                     "%llu subobjs in object, %llu, %s (%s/%s comp)\n",
1483                     indent * 8, name,
1484                     (u_longlong_t)bpo->bpo_object,
1485                     (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1486                     (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1487                     (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
1488                     bytes, comp, uncomp);
1489
1490                 for (i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1491                         uint64_t subobj;
1492                         bpobj_t subbpo;
1493                         int error;
1494                         VERIFY0(dmu_read(bpo->bpo_os,
1495                             bpo->bpo_phys->bpo_subobjs,
1496                             i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1497                         error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1498                         if (error != 0) {
1499                                 (void) printf("ERROR %u while trying to open "
1500                                     "subobj id %llu\n",
1501                                     error, (u_longlong_t)subobj);
1502                                 continue;
1503                         }
1504                         dump_full_bpobj(&subbpo, "subobj", indent + 1);
1505                 }
1506         } else {
1507                 (void) printf("    %*s: object %llu, %llu blkptrs, %s\n",
1508                     indent * 8, name,
1509                     (u_longlong_t)bpo->bpo_object,
1510                     (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1511                     bytes);
1512         }
1513
1514         if (dump_opt['d'] < 5)
1515                 return;
1516
1517
1518         if (indent == 0) {
1519                 (void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1520                 (void) printf("\n");
1521         }
1522 }
1523
1524 static void
1525 dump_deadlist(dsl_deadlist_t *dl)
1526 {
1527         dsl_deadlist_entry_t *dle;
1528         uint64_t unused;
1529         char bytes[32];
1530         char comp[32];
1531         char uncomp[32];
1532
1533         if (dump_opt['d'] < 3)
1534                 return;
1535
1536         if (dl->dl_oldfmt) {
1537                 dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
1538                 return;
1539         }
1540
1541         zdb_nicenum(dl->dl_phys->dl_used, bytes);
1542         zdb_nicenum(dl->dl_phys->dl_comp, comp);
1543         zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp);
1544         (void) printf("\n    Deadlist: %s (%s/%s comp)\n",
1545             bytes, comp, uncomp);
1546
1547         if (dump_opt['d'] < 4)
1548                 return;
1549
1550         (void) printf("\n");
1551
1552         /* force the tree to be loaded */
1553         dsl_deadlist_space_range(dl, 0, UINT64_MAX, &unused, &unused, &unused);
1554
1555         for (dle = avl_first(&dl->dl_tree); dle;
1556             dle = AVL_NEXT(&dl->dl_tree, dle)) {
1557                 if (dump_opt['d'] >= 5) {
1558                         char buf[128];
1559                         (void) snprintf(buf, sizeof (buf),
1560                             "mintxg %llu -> obj %llu",
1561                             (longlong_t)dle->dle_mintxg,
1562                             (longlong_t)dle->dle_bpobj.bpo_object);
1563
1564                         dump_full_bpobj(&dle->dle_bpobj, buf, 0);
1565                 } else {
1566                         (void) printf("mintxg %llu -> obj %llu\n",
1567                             (longlong_t)dle->dle_mintxg,
1568                             (longlong_t)dle->dle_bpobj.bpo_object);
1569
1570                 }
1571         }
1572 }
1573
1574 static avl_tree_t idx_tree;
1575 static avl_tree_t domain_tree;
1576 static boolean_t fuid_table_loaded;
1577 static boolean_t sa_loaded;
1578 sa_attr_type_t *sa_attr_table;
1579
1580 static void
1581 fuid_table_destroy(void)
1582 {
1583         if (fuid_table_loaded) {
1584                 zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1585                 fuid_table_loaded = B_FALSE;
1586         }
1587 }
1588
1589 /*
1590  * print uid or gid information.
1591  * For normal POSIX id just the id is printed in decimal format.
1592  * For CIFS files with FUID the fuid is printed in hex followed by
1593  * the domain-rid string.
1594  */
1595 static void
1596 print_idstr(uint64_t id, const char *id_type)
1597 {
1598         if (FUID_INDEX(id)) {
1599                 char *domain;
1600
1601                 domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1602                 (void) printf("\t%s     %llx [%s-%d]\n", id_type,
1603                     (u_longlong_t)id, domain, (int)FUID_RID(id));
1604         } else {
1605                 (void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1606         }
1607
1608 }
1609
1610 static void
1611 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
1612 {
1613         uint32_t uid_idx, gid_idx;
1614
1615         uid_idx = FUID_INDEX(uid);
1616         gid_idx = FUID_INDEX(gid);
1617
1618         /* Load domain table, if not already loaded */
1619         if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1620                 uint64_t fuid_obj;
1621
1622                 /* first find the fuid object.  It lives in the master node */
1623                 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1624                     8, 1, &fuid_obj) == 0);
1625                 zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1626                 (void) zfs_fuid_table_load(os, fuid_obj,
1627                     &idx_tree, &domain_tree);
1628                 fuid_table_loaded = B_TRUE;
1629         }
1630
1631         print_idstr(uid, "uid");
1632         print_idstr(gid, "gid");
1633 }
1634
1635 static void
1636 dump_znode_sa_xattr(sa_handle_t *hdl)
1637 {
1638         nvlist_t *sa_xattr;
1639         nvpair_t *elem = NULL;
1640         int sa_xattr_size = 0;
1641         int sa_xattr_entries = 0;
1642         int error;
1643         char *sa_xattr_packed;
1644
1645         error = sa_size(hdl, sa_attr_table[ZPL_DXATTR], &sa_xattr_size);
1646         if (error || sa_xattr_size == 0)
1647                 return;
1648
1649         sa_xattr_packed = malloc(sa_xattr_size);
1650         if (sa_xattr_packed == NULL)
1651                 return;
1652
1653         error = sa_lookup(hdl, sa_attr_table[ZPL_DXATTR],
1654             sa_xattr_packed, sa_xattr_size);
1655         if (error) {
1656                 free(sa_xattr_packed);
1657                 return;
1658         }
1659
1660         error = nvlist_unpack(sa_xattr_packed, sa_xattr_size, &sa_xattr, 0);
1661         if (error) {
1662                 free(sa_xattr_packed);
1663                 return;
1664         }
1665
1666         while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL)
1667                 sa_xattr_entries++;
1668
1669         (void) printf("\tSA xattrs: %d bytes, %d entries\n\n",
1670             sa_xattr_size, sa_xattr_entries);
1671         while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL) {
1672                 uchar_t *value;
1673                 uint_t cnt, idx;
1674
1675                 (void) printf("\t\t%s = ", nvpair_name(elem));
1676                 nvpair_value_byte_array(elem, &value, &cnt);
1677                 for (idx = 0; idx < cnt; ++idx) {
1678                         if (isprint(value[idx]))
1679                                 (void) putchar(value[idx]);
1680                         else
1681                                 (void) printf("\\%3.3o", value[idx]);
1682                 }
1683                 (void) putchar('\n');
1684         }
1685
1686         nvlist_free(sa_xattr);
1687         free(sa_xattr_packed);
1688 }
1689
1690 /*ARGSUSED*/
1691 static void
1692 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
1693 {
1694         char path[MAXPATHLEN * 2];      /* allow for xattr and failure prefix */
1695         sa_handle_t *hdl;
1696         uint64_t xattr, rdev, gen;
1697         uint64_t uid, gid, mode, fsize, parent, links;
1698         uint64_t pflags;
1699         uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
1700         time_t z_crtime, z_atime, z_mtime, z_ctime;
1701         sa_bulk_attr_t bulk[12];
1702         int idx = 0;
1703         int error;
1704
1705         if (!sa_loaded) {
1706                 uint64_t sa_attrs = 0;
1707                 uint64_t version;
1708
1709                 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1710                     8, 1, &version) == 0);
1711                 if (version >= ZPL_VERSION_SA) {
1712                         VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1713                             8, 1, &sa_attrs) == 0);
1714                 }
1715                 if ((error = sa_setup(os, sa_attrs, zfs_attr_table,
1716                     ZPL_END, &sa_attr_table)) != 0) {
1717                         (void) printf("sa_setup failed errno %d, can't "
1718                             "display znode contents\n", error);
1719                         return;
1720                 }
1721                 sa_loaded = B_TRUE;
1722         }
1723
1724         if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
1725                 (void) printf("Failed to get handle for SA znode\n");
1726                 return;
1727         }
1728
1729         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
1730         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
1731         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
1732             &links, 8);
1733         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
1734         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
1735             &mode, 8);
1736         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
1737             NULL, &parent, 8);
1738         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
1739             &fsize, 8);
1740         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
1741             acctm, 16);
1742         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
1743             modtm, 16);
1744         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
1745             crtm, 16);
1746         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
1747             chgtm, 16);
1748         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
1749             &pflags, 8);
1750
1751         if (sa_bulk_lookup(hdl, bulk, idx)) {
1752                 (void) sa_handle_destroy(hdl);
1753                 return;
1754         }
1755
1756         error = zfs_obj_to_path(os, object, path, sizeof (path));
1757         if (error != 0) {
1758                 (void) snprintf(path, sizeof (path), "\?\?\?<object#%llu>",
1759                     (u_longlong_t)object);
1760         }
1761         if (dump_opt['d'] < 3) {
1762                 (void) printf("\t%s\n", path);
1763                 (void) sa_handle_destroy(hdl);
1764                 return;
1765         }
1766
1767         z_crtime = (time_t)crtm[0];
1768         z_atime = (time_t)acctm[0];
1769         z_mtime = (time_t)modtm[0];
1770         z_ctime = (time_t)chgtm[0];
1771
1772         (void) printf("\tpath   %s\n", path);
1773         dump_uidgid(os, uid, gid);
1774         (void) printf("\tatime  %s", ctime(&z_atime));
1775         (void) printf("\tmtime  %s", ctime(&z_mtime));
1776         (void) printf("\tctime  %s", ctime(&z_ctime));
1777         (void) printf("\tcrtime %s", ctime(&z_crtime));
1778         (void) printf("\tgen    %llu\n", (u_longlong_t)gen);
1779         (void) printf("\tmode   %llo\n", (u_longlong_t)mode);
1780         (void) printf("\tsize   %llu\n", (u_longlong_t)fsize);
1781         (void) printf("\tparent %llu\n", (u_longlong_t)parent);
1782         (void) printf("\tlinks  %llu\n", (u_longlong_t)links);
1783         (void) printf("\tpflags %llx\n", (u_longlong_t)pflags);
1784         if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
1785             sizeof (uint64_t)) == 0)
1786                 (void) printf("\txattr  %llu\n", (u_longlong_t)xattr);
1787         if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
1788             sizeof (uint64_t)) == 0)
1789                 (void) printf("\trdev   0x%016llx\n", (u_longlong_t)rdev);
1790         dump_znode_sa_xattr(hdl);
1791         sa_handle_destroy(hdl);
1792 }
1793
1794 /*ARGSUSED*/
1795 static void
1796 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
1797 {
1798 }
1799
1800 /*ARGSUSED*/
1801 static void
1802 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
1803 {
1804 }
1805
1806 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
1807         dump_none,              /* unallocated                  */
1808         dump_zap,               /* object directory             */
1809         dump_uint64,            /* object array                 */
1810         dump_none,              /* packed nvlist                */
1811         dump_packed_nvlist,     /* packed nvlist size           */
1812         dump_none,              /* bpobj                        */
1813         dump_bpobj,             /* bpobj header                 */
1814         dump_none,              /* SPA space map header         */
1815         dump_none,              /* SPA space map                */
1816         dump_none,              /* ZIL intent log               */
1817         dump_dnode,             /* DMU dnode                    */
1818         dump_dmu_objset,        /* DMU objset                   */
1819         dump_dsl_dir,           /* DSL directory                */
1820         dump_zap,               /* DSL directory child map      */
1821         dump_zap,               /* DSL dataset snap map         */
1822         dump_zap,               /* DSL props                    */
1823         dump_dsl_dataset,       /* DSL dataset                  */
1824         dump_znode,             /* ZFS znode                    */
1825         dump_acl,               /* ZFS V0 ACL                   */
1826         dump_uint8,             /* ZFS plain file               */
1827         dump_zpldir,            /* ZFS directory                */
1828         dump_zap,               /* ZFS master node              */
1829         dump_zap,               /* ZFS delete queue             */
1830         dump_uint8,             /* zvol object                  */
1831         dump_zap,               /* zvol prop                    */
1832         dump_uint8,             /* other uint8[]                */
1833         dump_uint64,            /* other uint64[]               */
1834         dump_zap,               /* other ZAP                    */
1835         dump_zap,               /* persistent error log         */
1836         dump_uint8,             /* SPA history                  */
1837         dump_history_offsets,   /* SPA history offsets          */
1838         dump_zap,               /* Pool properties              */
1839         dump_zap,               /* DSL permissions              */
1840         dump_acl,               /* ZFS ACL                      */
1841         dump_uint8,             /* ZFS SYSACL                   */
1842         dump_none,              /* FUID nvlist                  */
1843         dump_packed_nvlist,     /* FUID nvlist size             */
1844         dump_zap,               /* DSL dataset next clones      */
1845         dump_zap,               /* DSL scrub queue              */
1846         dump_zap,               /* ZFS user/group used          */
1847         dump_zap,               /* ZFS user/group quota         */
1848         dump_zap,               /* snapshot refcount tags       */
1849         dump_ddt_zap,           /* DDT ZAP object               */
1850         dump_zap,               /* DDT statistics               */
1851         dump_znode,             /* SA object                    */
1852         dump_zap,               /* SA Master Node               */
1853         dump_sa_attrs,          /* SA attribute registration    */
1854         dump_sa_layouts,        /* SA attribute layouts         */
1855         dump_zap,               /* DSL scrub translations       */
1856         dump_none,              /* fake dedup BP                */
1857         dump_zap,               /* deadlist                     */
1858         dump_none,              /* deadlist hdr                 */
1859         dump_zap,               /* dsl clones                   */
1860         dump_bpobj_subobjs,     /* bpobj subobjs                */
1861         dump_unknown,           /* Unknown type, must be last   */
1862 };
1863
1864 static void
1865 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1866 {
1867         dmu_buf_t *db = NULL;
1868         dmu_object_info_t doi;
1869         dnode_t *dn;
1870         void *bonus = NULL;
1871         size_t bsize = 0;
1872         char iblk[32], dblk[32], lsize[32], asize[32], fill[32];
1873         char bonus_size[32];
1874         char aux[50];
1875         int error;
1876
1877         if (*print_header) {
1878                 (void) printf("\n%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1879                     "Object", "lvl", "iblk", "dblk", "dsize", "lsize",
1880                     "%full", "type");
1881                 *print_header = 0;
1882         }
1883
1884         if (object == 0) {
1885                 dn = DMU_META_DNODE(os);
1886         } else {
1887                 error = dmu_bonus_hold(os, object, FTAG, &db);
1888                 if (error)
1889                         fatal("dmu_bonus_hold(%llu) failed, errno %u",
1890                             object, error);
1891                 bonus = db->db_data;
1892                 bsize = db->db_size;
1893                 dn = DB_DNODE((dmu_buf_impl_t *)db);
1894         }
1895         dmu_object_info_from_dnode(dn, &doi);
1896
1897         zdb_nicenum(doi.doi_metadata_block_size, iblk);
1898         zdb_nicenum(doi.doi_data_block_size, dblk);
1899         zdb_nicenum(doi.doi_max_offset, lsize);
1900         zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize);
1901         zdb_nicenum(doi.doi_bonus_size, bonus_size);
1902         (void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
1903             doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
1904             doi.doi_max_offset);
1905
1906         aux[0] = '\0';
1907
1908         if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1909                 (void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1910                     ZDB_CHECKSUM_NAME(doi.doi_checksum));
1911         }
1912
1913         if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1914                 (void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1915                     ZDB_COMPRESS_NAME(doi.doi_compress));
1916         }
1917
1918         (void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %6s  %s%s\n",
1919             (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
1920             asize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
1921
1922         if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1923                 (void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1924                     "", "", "", "", "", bonus_size, "bonus",
1925                     ZDB_OT_NAME(doi.doi_bonus_type));
1926         }
1927
1928         if (verbosity >= 4) {
1929                 (void) printf("\tdnode flags: %s%s%s\n",
1930                     (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
1931                     "USED_BYTES " : "",
1932                     (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
1933                     "USERUSED_ACCOUNTED " : "",
1934                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
1935                     "SPILL_BLKPTR" : "");
1936                 (void) printf("\tdnode maxblkid: %llu\n",
1937                     (longlong_t)dn->dn_phys->dn_maxblkid);
1938
1939                 object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os, object,
1940                     bonus, bsize);
1941                 object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object, NULL, 0);
1942                 *print_header = 1;
1943         }
1944
1945         if (verbosity >= 5)
1946                 dump_indirect(dn);
1947
1948         if (verbosity >= 5) {
1949                 /*
1950                  * Report the list of segments that comprise the object.
1951                  */
1952                 uint64_t start = 0;
1953                 uint64_t end;
1954                 uint64_t blkfill = 1;
1955                 int minlvl = 1;
1956
1957                 if (dn->dn_type == DMU_OT_DNODE) {
1958                         minlvl = 0;
1959                         blkfill = DNODES_PER_BLOCK;
1960                 }
1961
1962                 for (;;) {
1963                         char segsize[32];
1964                         error = dnode_next_offset(dn,
1965                             0, &start, minlvl, blkfill, 0);
1966                         if (error)
1967                                 break;
1968                         end = start;
1969                         error = dnode_next_offset(dn,
1970                             DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
1971                         zdb_nicenum(end - start, segsize);
1972                         (void) printf("\t\tsegment [%016llx, %016llx)"
1973                             " size %5s\n", (u_longlong_t)start,
1974                             (u_longlong_t)end, segsize);
1975                         if (error)
1976                                 break;
1977                         start = end;
1978                 }
1979         }
1980
1981         if (db != NULL)
1982                 dmu_buf_rele(db, FTAG);
1983 }
1984
1985 static char *objset_types[DMU_OST_NUMTYPES] = {
1986         "NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1987
1988 static void
1989 dump_dir(objset_t *os)
1990 {
1991         dmu_objset_stats_t dds;
1992         uint64_t object, object_count;
1993         uint64_t refdbytes, usedobjs, scratch;
1994         char numbuf[32];
1995         char blkbuf[BP_SPRINTF_LEN + 20];
1996         char osname[MAXNAMELEN];
1997         char *type = "UNKNOWN";
1998         int verbosity = dump_opt['d'];
1999         int print_header = 1;
2000         int i, error;
2001
2002         dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2003         dmu_objset_fast_stat(os, &dds);
2004         dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2005
2006         if (dds.dds_type < DMU_OST_NUMTYPES)
2007                 type = objset_types[dds.dds_type];
2008
2009         if (dds.dds_type == DMU_OST_META) {
2010                 dds.dds_creation_txg = TXG_INITIAL;
2011                 usedobjs = BP_GET_FILL(os->os_rootbp);
2012                 refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
2013                     dd_used_bytes;
2014         } else {
2015                 dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
2016         }
2017
2018         ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
2019
2020         zdb_nicenum(refdbytes, numbuf);
2021
2022         if (verbosity >= 4) {
2023                 (void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
2024                 (void) snprintf_blkptr(blkbuf + strlen(blkbuf),
2025                     sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
2026         } else {
2027                 blkbuf[0] = '\0';
2028         }
2029
2030         dmu_objset_name(os, osname);
2031
2032         (void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
2033             "%s, %llu objects%s\n",
2034             osname, type, (u_longlong_t)dmu_objset_id(os),
2035             (u_longlong_t)dds.dds_creation_txg,
2036             numbuf, (u_longlong_t)usedobjs, blkbuf);
2037
2038         if (zopt_objects != 0) {
2039                 for (i = 0; i < zopt_objects; i++)
2040                         dump_object(os, zopt_object[i], verbosity,
2041                             &print_header);
2042                 (void) printf("\n");
2043                 return;
2044         }
2045
2046         if (dump_opt['i'] != 0 || verbosity >= 2)
2047                 dump_intent_log(dmu_objset_zil(os));
2048
2049         if (dmu_objset_ds(os) != NULL)
2050                 dump_deadlist(&dmu_objset_ds(os)->ds_deadlist);
2051
2052         if (verbosity < 2)
2053                 return;
2054
2055         if (BP_IS_HOLE(os->os_rootbp))
2056                 return;
2057
2058         dump_object(os, 0, verbosity, &print_header);
2059         object_count = 0;
2060         if (DMU_USERUSED_DNODE(os) != NULL &&
2061             DMU_USERUSED_DNODE(os)->dn_type != 0) {
2062                 dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header);
2063                 dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header);
2064         }
2065
2066         object = 0;
2067         while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
2068                 dump_object(os, object, verbosity, &print_header);
2069                 object_count++;
2070         }
2071
2072         ASSERT3U(object_count, ==, usedobjs);
2073
2074         (void) printf("\n");
2075
2076         if (error != ESRCH) {
2077                 (void) fprintf(stderr, "dmu_object_next() = %d\n", error);
2078                 abort();
2079         }
2080 }
2081
2082 static void
2083 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
2084 {
2085         time_t timestamp = ub->ub_timestamp;
2086
2087         (void) printf("%s", header ? header : "");
2088         (void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
2089         (void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
2090         (void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
2091         (void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
2092         (void) printf("\ttimestamp = %llu UTC = %s",
2093             (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
2094         if (dump_opt['u'] >= 3) {
2095                 char blkbuf[BP_SPRINTF_LEN];
2096                 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
2097                 (void) printf("\trootbp = %s\n", blkbuf);
2098         }
2099         (void) printf("%s", footer ? footer : "");
2100 }
2101
2102 static void
2103 dump_config(spa_t *spa)
2104 {
2105         dmu_buf_t *db;
2106         size_t nvsize = 0;
2107         int error = 0;
2108
2109
2110         error = dmu_bonus_hold(spa->spa_meta_objset,
2111             spa->spa_config_object, FTAG, &db);
2112
2113         if (error == 0) {
2114                 nvsize = *(uint64_t *)db->db_data;
2115                 dmu_buf_rele(db, FTAG);
2116
2117                 (void) printf("\nMOS Configuration:\n");
2118                 dump_packed_nvlist(spa->spa_meta_objset,
2119                     spa->spa_config_object, (void *)&nvsize, 1);
2120         } else {
2121                 (void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
2122                     (u_longlong_t)spa->spa_config_object, error);
2123         }
2124 }
2125
2126 static void
2127 dump_cachefile(const char *cachefile)
2128 {
2129         int fd;
2130         struct stat64 statbuf;
2131         char *buf;
2132         nvlist_t *config;
2133
2134         if ((fd = open64(cachefile, O_RDONLY)) < 0) {
2135                 (void) printf("cannot open '%s': %s\n", cachefile,
2136                     strerror(errno));
2137                 exit(1);
2138         }
2139
2140         if (fstat64(fd, &statbuf) != 0) {
2141                 (void) printf("failed to stat '%s': %s\n", cachefile,
2142                     strerror(errno));
2143                 exit(1);
2144         }
2145
2146         if ((buf = malloc(statbuf.st_size)) == NULL) {
2147                 (void) fprintf(stderr, "failed to allocate %llu bytes\n",
2148                     (u_longlong_t)statbuf.st_size);
2149                 exit(1);
2150         }
2151
2152         if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
2153                 (void) fprintf(stderr, "failed to read %llu bytes\n",
2154                     (u_longlong_t)statbuf.st_size);
2155                 exit(1);
2156         }
2157
2158         (void) close(fd);
2159
2160         if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
2161                 (void) fprintf(stderr, "failed to unpack nvlist\n");
2162                 exit(1);
2163         }
2164
2165         free(buf);
2166
2167         dump_nvlist(config, 0);
2168
2169         nvlist_free(config);
2170 }
2171
2172 #define ZDB_MAX_UB_HEADER_SIZE 32
2173
2174 static void
2175 dump_label_uberblocks(vdev_label_t *lbl, uint64_t ashift)
2176 {
2177         vdev_t vd;
2178         vdev_t *vdp = &vd;
2179         char header[ZDB_MAX_UB_HEADER_SIZE];
2180         int i;
2181
2182         vd.vdev_ashift = ashift;
2183         vdp->vdev_top = vdp;
2184
2185         for (i = 0; i < VDEV_UBERBLOCK_COUNT(vdp); i++) {
2186                 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(vdp, i);
2187                 uberblock_t *ub = (void *)((char *)lbl + uoff);
2188
2189                 if (uberblock_verify(ub))
2190                         continue;
2191                 (void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
2192                     "Uberblock[%d]\n", i);
2193                 dump_uberblock(ub, header, "");
2194         }
2195 }
2196
2197 static void
2198 dump_label(const char *dev)
2199 {
2200         int fd;
2201         vdev_label_t label;
2202         char *path, *buf = label.vl_vdev_phys.vp_nvlist;
2203         size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
2204         struct stat64 statbuf;
2205         uint64_t psize, ashift;
2206         int len = strlen(dev) + 1;
2207         int l;
2208
2209         if (strncmp(dev, "/dev/dsk/", 9) == 0) {
2210                 len++;
2211                 path = malloc(len);
2212                 (void) snprintf(path, len, "%s%s", "/dev/rdsk/", dev + 9);
2213         } else {
2214                 path = strdup(dev);
2215         }
2216
2217         if ((fd = open64(path, O_RDONLY)) < 0) {
2218                 (void) printf("cannot open '%s': %s\n", path, strerror(errno));
2219                 free(path);
2220                 exit(1);
2221         }
2222
2223         if (fstat64_blk(fd, &statbuf) != 0) {
2224                 (void) printf("failed to stat '%s': %s\n", path,
2225                     strerror(errno));
2226                 free(path);
2227                 (void) close(fd);
2228                 exit(1);
2229         }
2230
2231         psize = statbuf.st_size;
2232         psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
2233
2234         for (l = 0; l < VDEV_LABELS; l++) {
2235                 nvlist_t *config = NULL;
2236
2237                 (void) printf("--------------------------------------------\n");
2238                 (void) printf("LABEL %d\n", l);
2239                 (void) printf("--------------------------------------------\n");
2240
2241                 if (pread64(fd, &label, sizeof (label),
2242                     vdev_label_offset(psize, l, 0)) != sizeof (label)) {
2243                         (void) printf("failed to read label %d\n", l);
2244                         continue;
2245                 }
2246
2247                 if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
2248                         (void) printf("failed to unpack label %d\n", l);
2249                         ashift = SPA_MINBLOCKSHIFT;
2250                 } else {
2251                         nvlist_t *vdev_tree = NULL;
2252
2253                         dump_nvlist(config, 4);
2254                         if ((nvlist_lookup_nvlist(config,
2255                             ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
2256                             (nvlist_lookup_uint64(vdev_tree,
2257                             ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
2258                                 ashift = SPA_MINBLOCKSHIFT;
2259                         nvlist_free(config);
2260                 }
2261                 if (dump_opt['u'])
2262                         dump_label_uberblocks(&label, ashift);
2263         }
2264
2265         free(path);
2266         (void) close(fd);
2267 }
2268
2269 static uint64_t num_large_blocks;
2270
2271 /*ARGSUSED*/
2272 static int
2273 dump_one_dir(const char *dsname, void *arg)
2274 {
2275         int error;
2276         objset_t *os;
2277
2278         error = dmu_objset_own(dsname, DMU_OST_ANY, B_TRUE, FTAG, &os);
2279         if (error) {
2280                 (void) printf("Could not open %s, error %d\n", dsname, error);
2281                 return (0);
2282         }
2283         if (dmu_objset_ds(os)->ds_large_blocks)
2284                 num_large_blocks++;
2285         dump_dir(os);
2286         dmu_objset_disown(os, FTAG);
2287         fuid_table_destroy();
2288         sa_loaded = B_FALSE;
2289         return (0);
2290 }
2291
2292 /*
2293  * Block statistics.
2294  */
2295 #define PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
2296 typedef struct zdb_blkstats {
2297         uint64_t zb_asize;
2298         uint64_t zb_lsize;
2299         uint64_t zb_psize;
2300         uint64_t zb_count;
2301         uint64_t zb_gangs;
2302         uint64_t zb_ditto_samevdev;
2303         uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
2304 } zdb_blkstats_t;
2305
2306 /*
2307  * Extended object types to report deferred frees and dedup auto-ditto blocks.
2308  */
2309 #define ZDB_OT_DEFERRED (DMU_OT_NUMTYPES + 0)
2310 #define ZDB_OT_DITTO    (DMU_OT_NUMTYPES + 1)
2311 #define ZDB_OT_OTHER    (DMU_OT_NUMTYPES + 2)
2312 #define ZDB_OT_TOTAL    (DMU_OT_NUMTYPES + 3)
2313
2314 static char *zdb_ot_extname[] = {
2315         "deferred free",
2316         "dedup ditto",
2317         "other",
2318         "Total",
2319 };
2320
2321 #define ZB_TOTAL        DN_MAX_LEVELS
2322
2323 typedef struct zdb_cb {
2324         zdb_blkstats_t  zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
2325         uint64_t        zcb_dedup_asize;
2326         uint64_t        zcb_dedup_blocks;
2327         uint64_t        zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
2328         uint64_t        zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
2329             [BPE_PAYLOAD_SIZE];
2330         uint64_t        zcb_start;
2331         uint64_t        zcb_lastprint;
2332         uint64_t        zcb_totalasize;
2333         uint64_t        zcb_errors[256];
2334         int             zcb_readfails;
2335         int             zcb_haderrors;
2336         spa_t           *zcb_spa;
2337 } zdb_cb_t;
2338
2339 static void
2340 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
2341     dmu_object_type_t type)
2342 {
2343         uint64_t refcnt = 0;
2344         int i;
2345
2346         ASSERT(type < ZDB_OT_TOTAL);
2347
2348         if (zilog && zil_bp_tree_add(zilog, bp) != 0)
2349                 return;
2350
2351         for (i = 0; i < 4; i++) {
2352                 int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
2353                 int t = (i & 1) ? type : ZDB_OT_TOTAL;
2354                 int equal;
2355                 zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
2356
2357                 zb->zb_asize += BP_GET_ASIZE(bp);
2358                 zb->zb_lsize += BP_GET_LSIZE(bp);
2359                 zb->zb_psize += BP_GET_PSIZE(bp);
2360                 zb->zb_count++;
2361
2362                 /*
2363                  * The histogram is only big enough to record blocks up to
2364                  * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
2365                  * "other", bucket.
2366                  */
2367                 int idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
2368                 idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
2369                 zb->zb_psize_histogram[idx]++;
2370
2371                 zb->zb_gangs += BP_COUNT_GANG(bp);
2372
2373                 switch (BP_GET_NDVAS(bp)) {
2374                 case 2:
2375                         if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2376                             DVA_GET_VDEV(&bp->blk_dva[1]))
2377                                 zb->zb_ditto_samevdev++;
2378                         break;
2379                 case 3:
2380                         equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2381                             DVA_GET_VDEV(&bp->blk_dva[1])) +
2382                             (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2383                             DVA_GET_VDEV(&bp->blk_dva[2])) +
2384                             (DVA_GET_VDEV(&bp->blk_dva[1]) ==
2385                             DVA_GET_VDEV(&bp->blk_dva[2]));
2386                         if (equal != 0)
2387                                 zb->zb_ditto_samevdev++;
2388                         break;
2389                 }
2390
2391         }
2392
2393         if (BP_IS_EMBEDDED(bp)) {
2394                 zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
2395                 zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
2396                     [BPE_GET_PSIZE(bp)]++;
2397                 return;
2398         }
2399
2400         if (dump_opt['L'])
2401                 return;
2402
2403         if (BP_GET_DEDUP(bp)) {
2404                 ddt_t *ddt;
2405                 ddt_entry_t *dde;
2406
2407                 ddt = ddt_select(zcb->zcb_spa, bp);
2408                 ddt_enter(ddt);
2409                 dde = ddt_lookup(ddt, bp, B_FALSE);
2410
2411                 if (dde == NULL) {
2412                         refcnt = 0;
2413                 } else {
2414                         ddt_phys_t *ddp = ddt_phys_select(dde, bp);
2415                         ddt_phys_decref(ddp);
2416                         refcnt = ddp->ddp_refcnt;
2417                         if (ddt_phys_total_refcnt(dde) == 0)
2418                                 ddt_remove(ddt, dde);
2419                 }
2420                 ddt_exit(ddt);
2421         }
2422
2423         VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
2424             refcnt ? 0 : spa_first_txg(zcb->zcb_spa),
2425             bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
2426 }
2427
2428 static void
2429 zdb_blkptr_done(zio_t *zio)
2430 {
2431         spa_t *spa = zio->io_spa;
2432         blkptr_t *bp = zio->io_bp;
2433         int ioerr = zio->io_error;
2434         zdb_cb_t *zcb = zio->io_private;
2435         zbookmark_phys_t *zb = &zio->io_bookmark;
2436
2437         zio_data_buf_free(zio->io_data, zio->io_size);
2438
2439         mutex_enter(&spa->spa_scrub_lock);
2440         spa->spa_scrub_inflight--;
2441         cv_broadcast(&spa->spa_scrub_io_cv);
2442
2443         if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
2444                 char blkbuf[BP_SPRINTF_LEN];
2445
2446                 zcb->zcb_haderrors = 1;
2447                 zcb->zcb_errors[ioerr]++;
2448
2449                 if (dump_opt['b'] >= 2)
2450                         snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2451                 else
2452                         blkbuf[0] = '\0';
2453
2454                 (void) printf("zdb_blkptr_cb: "
2455                     "Got error %d reading "
2456                     "<%llu, %llu, %lld, %llx> %s -- skipping\n",
2457                     ioerr,
2458                     (u_longlong_t)zb->zb_objset,
2459                     (u_longlong_t)zb->zb_object,
2460                     (u_longlong_t)zb->zb_level,
2461                     (u_longlong_t)zb->zb_blkid,
2462                     blkbuf);
2463         }
2464         mutex_exit(&spa->spa_scrub_lock);
2465 }
2466
2467 static int
2468 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2469     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2470 {
2471         zdb_cb_t *zcb = arg;
2472         dmu_object_type_t type;
2473         boolean_t is_metadata;
2474
2475         if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
2476                 char blkbuf[BP_SPRINTF_LEN];
2477                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2478                 (void) printf("objset %llu object %llu "
2479                     "level %lld offset 0x%llx %s\n",
2480                     (u_longlong_t)zb->zb_objset,
2481                     (u_longlong_t)zb->zb_object,
2482                     (longlong_t)zb->zb_level,
2483                     (u_longlong_t)blkid2offset(dnp, bp, zb),
2484                     blkbuf);
2485         }
2486
2487         if (BP_IS_HOLE(bp))
2488                 return (0);
2489
2490         type = BP_GET_TYPE(bp);
2491
2492         zdb_count_block(zcb, zilog, bp,
2493             (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
2494
2495         is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
2496
2497         if (!BP_IS_EMBEDDED(bp) &&
2498             (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
2499                 size_t size = BP_GET_PSIZE(bp);
2500                 void *data = zio_data_buf_alloc(size);
2501                 int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
2502
2503                 /* If it's an intent log block, failure is expected. */
2504                 if (zb->zb_level == ZB_ZIL_LEVEL)
2505                         flags |= ZIO_FLAG_SPECULATIVE;
2506
2507                 mutex_enter(&spa->spa_scrub_lock);
2508                 while (spa->spa_scrub_inflight > max_inflight)
2509                         cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2510                 spa->spa_scrub_inflight++;
2511                 mutex_exit(&spa->spa_scrub_lock);
2512
2513                 zio_nowait(zio_read(NULL, spa, bp, data, size,
2514                     zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
2515         }
2516
2517         zcb->zcb_readfails = 0;
2518
2519         /* only call gethrtime() every 100 blocks */
2520         static int iters;
2521         if (++iters > 100)
2522                 iters = 0;
2523         else
2524                 return (0);
2525
2526         if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
2527                 uint64_t now = gethrtime();
2528                 char buf[10];
2529                 uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
2530                 int kb_per_sec =
2531                     1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
2532                 int sec_remaining =
2533                     (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
2534
2535                 zfs_nicenum(bytes, buf, sizeof (buf));
2536                 (void) fprintf(stderr,
2537                     "\r%5s completed (%4dMB/s) "
2538                     "estimated time remaining: %uhr %02umin %02usec        ",
2539                     buf, kb_per_sec / 1024,
2540                     sec_remaining / 60 / 60,
2541                     sec_remaining / 60 % 60,
2542                     sec_remaining % 60);
2543
2544                 zcb->zcb_lastprint = now;
2545         }
2546
2547         return (0);
2548 }
2549
2550 static void
2551 zdb_leak(void *arg, uint64_t start, uint64_t size)
2552 {
2553         vdev_t *vd = arg;
2554
2555         (void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
2556             (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
2557 }
2558
2559 static metaslab_ops_t zdb_metaslab_ops = {
2560         NULL    /* alloc */
2561 };
2562
2563 static void
2564 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
2565 {
2566         ddt_bookmark_t ddb = { 0 };
2567         ddt_entry_t dde;
2568         int error;
2569         int p;
2570
2571         while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
2572                 blkptr_t blk;
2573                 ddt_phys_t *ddp = dde.dde_phys;
2574
2575                 if (ddb.ddb_class == DDT_CLASS_UNIQUE)
2576                         return;
2577
2578                 ASSERT(ddt_phys_total_refcnt(&dde) > 1);
2579
2580                 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2581                         if (ddp->ddp_phys_birth == 0)
2582                                 continue;
2583                         ddt_bp_create(ddb.ddb_checksum,
2584                             &dde.dde_key, ddp, &blk);
2585                         if (p == DDT_PHYS_DITTO) {
2586                                 zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
2587                         } else {
2588                                 zcb->zcb_dedup_asize +=
2589                                     BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
2590                                 zcb->zcb_dedup_blocks++;
2591                         }
2592                 }
2593                 if (!dump_opt['L']) {
2594                         ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
2595                         ddt_enter(ddt);
2596                         VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
2597                         ddt_exit(ddt);
2598                 }
2599         }
2600
2601         ASSERT(error == ENOENT);
2602 }
2603
2604 static void
2605 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
2606 {
2607         zcb->zcb_spa = spa;
2608         uint64_t c, m;
2609
2610         if (!dump_opt['L']) {
2611                 vdev_t *rvd = spa->spa_root_vdev;
2612                 for (c = 0; c < rvd->vdev_children; c++) {
2613                         vdev_t *vd = rvd->vdev_child[c];
2614                         for (m = 0; m < vd->vdev_ms_count; m++) {
2615                                 metaslab_t *msp = vd->vdev_ms[m];
2616                                 mutex_enter(&msp->ms_lock);
2617                                 metaslab_unload(msp);
2618
2619                                 /*
2620                                  * For leak detection, we overload the metaslab
2621                                  * ms_tree to contain allocated segments
2622                                  * instead of free segments. As a result,
2623                                  * we can't use the normal metaslab_load/unload
2624                                  * interfaces.
2625                                  */
2626                                 if (msp->ms_sm != NULL) {
2627                                         (void) fprintf(stderr,
2628                                             "\rloading space map for "
2629                                             "vdev %llu of %llu, "
2630                                             "metaslab %llu of %llu ...",
2631                                             (longlong_t)c,
2632                                             (longlong_t)rvd->vdev_children,
2633                                             (longlong_t)m,
2634                                             (longlong_t)vd->vdev_ms_count);
2635
2636                                         msp->ms_ops = &zdb_metaslab_ops;
2637
2638                                         /*
2639                                          * We don't want to spend the CPU
2640                                          * manipulating the size-ordered
2641                                          * tree, so clear the range_tree
2642                                          * ops.
2643                                          */
2644                                         msp->ms_tree->rt_ops = NULL;
2645                                         VERIFY0(space_map_load(msp->ms_sm,
2646                                             msp->ms_tree, SM_ALLOC));
2647                                         msp->ms_loaded = B_TRUE;
2648                                 }
2649                                 mutex_exit(&msp->ms_lock);
2650                         }
2651                 }
2652                 (void) fprintf(stderr, "\n");
2653         }
2654
2655         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2656
2657         zdb_ddt_leak_init(spa, zcb);
2658
2659         spa_config_exit(spa, SCL_CONFIG, FTAG);
2660 }
2661
2662 static void
2663 zdb_leak_fini(spa_t *spa)
2664 {
2665         int c, m;
2666
2667         if (!dump_opt['L']) {
2668                 vdev_t *rvd = spa->spa_root_vdev;
2669                 for (c = 0; c < rvd->vdev_children; c++) {
2670                         vdev_t *vd = rvd->vdev_child[c];
2671                         for (m = 0; m < vd->vdev_ms_count; m++) {
2672                                 metaslab_t *msp = vd->vdev_ms[m];
2673                                 mutex_enter(&msp->ms_lock);
2674
2675                                 /*
2676                                  * The ms_tree has been overloaded to
2677                                  * contain allocated segments. Now that we
2678                                  * finished traversing all blocks, any
2679                                  * block that remains in the ms_tree
2680                                  * represents an allocated block that we
2681                                  * did not claim during the traversal.
2682                                  * Claimed blocks would have been removed
2683                                  * from the ms_tree.
2684                                  */
2685                                 range_tree_vacate(msp->ms_tree, zdb_leak, vd);
2686                                 msp->ms_loaded = B_FALSE;
2687
2688                                 mutex_exit(&msp->ms_lock);
2689                         }
2690                 }
2691         }
2692 }
2693
2694 /* ARGSUSED */
2695 static int
2696 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2697 {
2698         zdb_cb_t *zcb = arg;
2699
2700         if (dump_opt['b'] >= 5) {
2701                 char blkbuf[BP_SPRINTF_LEN];
2702                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2703                 (void) printf("[%s] %s\n",
2704                     "deferred free", blkbuf);
2705         }
2706         zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
2707         return (0);
2708 }
2709
2710 static int
2711 dump_block_stats(spa_t *spa)
2712 {
2713         zdb_cb_t zcb;
2714         zdb_blkstats_t *zb, *tzb;
2715         uint64_t norm_alloc, norm_space, total_alloc, total_found;
2716         int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA | TRAVERSE_HARD;
2717         boolean_t leaks = B_FALSE;
2718         int e, c;
2719         bp_embedded_type_t i;
2720
2721         (void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
2722             (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
2723             (dump_opt['c'] == 1) ? "metadata " : "",
2724             dump_opt['c'] ? "checksums " : "",
2725             (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
2726             !dump_opt['L'] ? "nothing leaked " : "");
2727
2728         /*
2729          * Load all space maps as SM_ALLOC maps, then traverse the pool
2730          * claiming each block we discover.  If the pool is perfectly
2731          * consistent, the space maps will be empty when we're done.
2732          * Anything left over is a leak; any block we can't claim (because
2733          * it's not part of any space map) is a double allocation,
2734          * reference to a freed block, or an unclaimed log block.
2735          */
2736         bzero(&zcb, sizeof (zdb_cb_t));
2737         zdb_leak_init(spa, &zcb);
2738
2739         /*
2740          * If there's a deferred-free bplist, process that first.
2741          */
2742         (void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
2743             count_block_cb, &zcb, NULL);
2744         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
2745                 (void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
2746                     count_block_cb, &zcb, NULL);
2747         }
2748         if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
2749                 VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
2750                     spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
2751                     &zcb, NULL));
2752         }
2753
2754         if (dump_opt['c'] > 1)
2755                 flags |= TRAVERSE_PREFETCH_DATA;
2756
2757         zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
2758         zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
2759         zcb.zcb_haderrors |= traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
2760
2761         /*
2762          * If we've traversed the data blocks then we need to wait for those
2763          * I/Os to complete. We leverage "The Godfather" zio to wait on
2764          * all async I/Os to complete.
2765          */
2766         if (dump_opt['c']) {
2767                 for (c = 0; c < max_ncpus; c++) {
2768                         (void) zio_wait(spa->spa_async_zio_root[c]);
2769                         spa->spa_async_zio_root[c] = zio_root(spa, NULL, NULL,
2770                             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2771                             ZIO_FLAG_GODFATHER);
2772                 }
2773         }
2774
2775         if (zcb.zcb_haderrors) {
2776                 (void) printf("\nError counts:\n\n");
2777                 (void) printf("\t%5s  %s\n", "errno", "count");
2778                 for (e = 0; e < 256; e++) {
2779                         if (zcb.zcb_errors[e] != 0) {
2780                                 (void) printf("\t%5d  %llu\n",
2781                                     e, (u_longlong_t)zcb.zcb_errors[e]);
2782                         }
2783                 }
2784         }
2785
2786         /*
2787          * Report any leaked segments.
2788          */
2789         zdb_leak_fini(spa);
2790
2791         tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
2792
2793         norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
2794         norm_space = metaslab_class_get_space(spa_normal_class(spa));
2795
2796         total_alloc = norm_alloc + metaslab_class_get_alloc(spa_log_class(spa));
2797         total_found = tzb->zb_asize - zcb.zcb_dedup_asize;
2798
2799         if (total_found == total_alloc) {
2800                 if (!dump_opt['L'])
2801                         (void) printf("\n\tNo leaks (block sum matches space"
2802                             " maps exactly)\n");
2803         } else {
2804                 (void) printf("block traversal size %llu != alloc %llu "
2805                     "(%s %lld)\n",
2806                     (u_longlong_t)total_found,
2807                     (u_longlong_t)total_alloc,
2808                     (dump_opt['L']) ? "unreachable" : "leaked",
2809                     (longlong_t)(total_alloc - total_found));
2810                 leaks = B_TRUE;
2811         }
2812
2813         if (tzb->zb_count == 0)
2814                 return (2);
2815
2816         (void) printf("\n");
2817         (void) printf("\tbp count:      %10llu\n",
2818             (u_longlong_t)tzb->zb_count);
2819         (void) printf("\tganged count:  %10llu\n",
2820             (longlong_t)tzb->zb_gangs);
2821         (void) printf("\tbp logical:    %10llu      avg: %6llu\n",
2822             (u_longlong_t)tzb->zb_lsize,
2823             (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
2824         (void) printf("\tbp physical:   %10llu      avg:"
2825             " %6llu     compression: %6.2f\n",
2826             (u_longlong_t)tzb->zb_psize,
2827             (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
2828             (double)tzb->zb_lsize / tzb->zb_psize);
2829         (void) printf("\tbp allocated:  %10llu      avg:"
2830             " %6llu     compression: %6.2f\n",
2831             (u_longlong_t)tzb->zb_asize,
2832             (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
2833             (double)tzb->zb_lsize / tzb->zb_asize);
2834         (void) printf("\tbp deduped:    %10llu    ref>1:"
2835             " %6llu   deduplication: %6.2f\n",
2836             (u_longlong_t)zcb.zcb_dedup_asize,
2837             (u_longlong_t)zcb.zcb_dedup_blocks,
2838             (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
2839         (void) printf("\tSPA allocated: %10llu     used: %5.2f%%\n",
2840             (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
2841
2842         for (i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
2843                 if (zcb.zcb_embedded_blocks[i] == 0)
2844                         continue;
2845                 (void) printf("\n");
2846                 (void) printf("\tadditional, non-pointer bps of type %u: "
2847                     "%10llu\n",
2848                     i, (u_longlong_t)zcb.zcb_embedded_blocks[i]);
2849
2850                 if (dump_opt['b'] >= 3) {
2851                         (void) printf("\t number of (compressed) bytes:  "
2852                             "number of bps\n");
2853                         dump_histogram(zcb.zcb_embedded_histogram[i],
2854                             sizeof (zcb.zcb_embedded_histogram[i]) /
2855                             sizeof (zcb.zcb_embedded_histogram[i][0]), 0);
2856                 }
2857         }
2858
2859         if (tzb->zb_ditto_samevdev != 0) {
2860                 (void) printf("\tDittoed blocks on same vdev: %llu\n",
2861                     (longlong_t)tzb->zb_ditto_samevdev);
2862         }
2863
2864         if (dump_opt['b'] >= 2) {
2865                 int l, t, level;
2866                 (void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
2867                     "\t  avg\t comp\t%%Total\tType\n");
2868
2869                 for (t = 0; t <= ZDB_OT_TOTAL; t++) {
2870                         char csize[32], lsize[32], psize[32], asize[32];
2871                         char avg[32], gang[32];
2872                         char *typename;
2873
2874                         if (t < DMU_OT_NUMTYPES)
2875                                 typename = dmu_ot[t].ot_name;
2876                         else
2877                                 typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
2878
2879                         if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
2880                                 (void) printf("%6s\t%5s\t%5s\t%5s"
2881                                     "\t%5s\t%5s\t%6s\t%s\n",
2882                                     "-",
2883                                     "-",
2884                                     "-",
2885                                     "-",
2886                                     "-",
2887                                     "-",
2888                                     "-",
2889                                     typename);
2890                                 continue;
2891                         }
2892
2893                         for (l = ZB_TOTAL - 1; l >= -1; l--) {
2894                                 level = (l == -1 ? ZB_TOTAL : l);
2895                                 zb = &zcb.zcb_type[level][t];
2896
2897                                 if (zb->zb_asize == 0)
2898                                         continue;
2899
2900                                 if (dump_opt['b'] < 3 && level != ZB_TOTAL)
2901                                         continue;
2902
2903                                 if (level == 0 && zb->zb_asize ==
2904                                     zcb.zcb_type[ZB_TOTAL][t].zb_asize)
2905                                         continue;
2906
2907                                 zdb_nicenum(zb->zb_count, csize);
2908                                 zdb_nicenum(zb->zb_lsize, lsize);
2909                                 zdb_nicenum(zb->zb_psize, psize);
2910                                 zdb_nicenum(zb->zb_asize, asize);
2911                                 zdb_nicenum(zb->zb_asize / zb->zb_count, avg);
2912                                 zdb_nicenum(zb->zb_gangs, gang);
2913
2914                                 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
2915                                     "\t%5.2f\t%6.2f\t",
2916                                     csize, lsize, psize, asize, avg,
2917                                     (double)zb->zb_lsize / zb->zb_psize,
2918                                     100.0 * zb->zb_asize / tzb->zb_asize);
2919
2920                                 if (level == ZB_TOTAL)
2921                                         (void) printf("%s\n", typename);
2922                                 else
2923                                         (void) printf("    L%d %s\n",
2924                                             level, typename);
2925
2926                                 if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
2927                                         (void) printf("\t number of ganged "
2928                                             "blocks: %s\n", gang);
2929                                 }
2930
2931                                 if (dump_opt['b'] >= 4) {
2932                                         (void) printf("psize "
2933                                             "(in 512-byte sectors): "
2934                                             "number of blocks\n");
2935                                         dump_histogram(zb->zb_psize_histogram,
2936                                             PSIZE_HISTO_SIZE, 0);
2937                                 }
2938                         }
2939                 }
2940         }
2941
2942         (void) printf("\n");
2943
2944         if (leaks)
2945                 return (2);
2946
2947         if (zcb.zcb_haderrors)
2948                 return (3);
2949
2950         return (0);
2951 }
2952
2953 typedef struct zdb_ddt_entry {
2954         ddt_key_t       zdde_key;
2955         uint64_t        zdde_ref_blocks;
2956         uint64_t        zdde_ref_lsize;
2957         uint64_t        zdde_ref_psize;
2958         uint64_t        zdde_ref_dsize;
2959         avl_node_t      zdde_node;
2960 } zdb_ddt_entry_t;
2961
2962 /* ARGSUSED */
2963 static int
2964 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2965     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2966 {
2967         avl_tree_t *t = arg;
2968         avl_index_t where;
2969         zdb_ddt_entry_t *zdde, zdde_search;
2970
2971         if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2972                 return (0);
2973
2974         if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
2975                 (void) printf("traversing objset %llu, %llu objects, "
2976                     "%lu blocks so far\n",
2977                     (u_longlong_t)zb->zb_objset,
2978                     (u_longlong_t)BP_GET_FILL(bp),
2979                     avl_numnodes(t));
2980         }
2981
2982         if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
2983             BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
2984                 return (0);
2985
2986         ddt_key_fill(&zdde_search.zdde_key, bp);
2987
2988         zdde = avl_find(t, &zdde_search, &where);
2989
2990         if (zdde == NULL) {
2991                 zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
2992                 zdde->zdde_key = zdde_search.zdde_key;
2993                 avl_insert(t, zdde, where);
2994         }
2995
2996         zdde->zdde_ref_blocks += 1;
2997         zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
2998         zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
2999         zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
3000
3001         return (0);
3002 }
3003
3004 static void
3005 dump_simulated_ddt(spa_t *spa)
3006 {
3007         avl_tree_t t;
3008         void *cookie = NULL;
3009         zdb_ddt_entry_t *zdde;
3010         ddt_histogram_t ddh_total;
3011         ddt_stat_t dds_total;
3012
3013         bzero(&ddh_total, sizeof (ddt_histogram_t));
3014         bzero(&dds_total, sizeof (ddt_stat_t));
3015
3016         avl_create(&t, ddt_entry_compare,
3017             sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
3018
3019         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3020
3021         (void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
3022             zdb_ddt_add_cb, &t);
3023
3024         spa_config_exit(spa, SCL_CONFIG, FTAG);
3025
3026         while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
3027                 ddt_stat_t dds;
3028                 uint64_t refcnt = zdde->zdde_ref_blocks;
3029                 ASSERT(refcnt != 0);
3030
3031                 dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
3032                 dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
3033                 dds.dds_psize = zdde->zdde_ref_psize / refcnt;
3034                 dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
3035
3036                 dds.dds_ref_blocks = zdde->zdde_ref_blocks;
3037                 dds.dds_ref_lsize = zdde->zdde_ref_lsize;
3038                 dds.dds_ref_psize = zdde->zdde_ref_psize;
3039                 dds.dds_ref_dsize = zdde->zdde_ref_dsize;
3040
3041                 ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
3042                     &dds, 0);
3043
3044                 umem_free(zdde, sizeof (*zdde));
3045         }
3046
3047         avl_destroy(&t);
3048
3049         ddt_histogram_stat(&dds_total, &ddh_total);
3050
3051         (void) printf("Simulated DDT histogram:\n");
3052
3053         zpool_dump_ddt(&dds_total, &ddh_total);
3054
3055         dump_dedup_ratio(&dds_total);
3056 }
3057
3058 static void
3059 dump_zpool(spa_t *spa)
3060 {
3061         dsl_pool_t *dp = spa_get_dsl(spa);
3062         int rc = 0;
3063
3064         if (dump_opt['S']) {
3065                 dump_simulated_ddt(spa);
3066                 return;
3067         }
3068
3069         if (!dump_opt['e'] && dump_opt['C'] > 1) {
3070                 (void) printf("\nCached configuration:\n");
3071                 dump_nvlist(spa->spa_config, 8);
3072         }
3073
3074         if (dump_opt['C'])
3075                 dump_config(spa);
3076
3077         if (dump_opt['u'])
3078                 dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
3079
3080         if (dump_opt['D'])
3081                 dump_all_ddts(spa);
3082
3083         if (dump_opt['d'] > 2 || dump_opt['m'])
3084                 dump_metaslabs(spa);
3085         if (dump_opt['M'])
3086                 dump_metaslab_groups(spa);
3087
3088         if (dump_opt['d'] || dump_opt['i']) {
3089                 uint64_t refcount;
3090
3091                 dump_dir(dp->dp_meta_objset);
3092                 if (dump_opt['d'] >= 3) {
3093                         dump_full_bpobj(&spa->spa_deferred_bpobj,
3094                             "Deferred frees", 0);
3095                         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
3096                                 dump_full_bpobj(
3097                                     &spa->spa_dsl_pool->dp_free_bpobj,
3098                                     "Pool snapshot frees", 0);
3099                         }
3100
3101                         if (spa_feature_is_active(spa,
3102                             SPA_FEATURE_ASYNC_DESTROY)) {
3103                                 dump_bptree(spa->spa_meta_objset,
3104                                     spa->spa_dsl_pool->dp_bptree_obj,
3105                                     "Pool dataset frees");
3106                         }
3107                         dump_dtl(spa->spa_root_vdev, 0);
3108                 }
3109                 (void) dmu_objset_find(spa_name(spa), dump_one_dir,
3110                     NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
3111
3112                 if (feature_get_refcount(spa,
3113                     &spa_feature_table[SPA_FEATURE_LARGE_BLOCKS],
3114                     &refcount) != ENOTSUP) {
3115                         if (num_large_blocks != refcount) {
3116                                 (void) printf("large_blocks feature refcount "
3117                                     "mismatch: expected %lld != actual %lld\n",
3118                                     (longlong_t)num_large_blocks,
3119                                     (longlong_t)refcount);
3120                                 rc = 2;
3121                         } else {
3122                                 (void) printf("Verified large_blocks feature "
3123                                     "refcount is correct (%llu)\n",
3124                                     (longlong_t)refcount);
3125                         }
3126                 }
3127         }
3128         if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
3129                 rc = dump_block_stats(spa);
3130
3131         if (rc == 0)
3132                 rc = verify_spacemap_refcounts(spa);
3133
3134         if (dump_opt['s'])
3135                 show_pool_stats(spa);
3136
3137         if (dump_opt['h'])
3138                 dump_history(spa);
3139
3140         if (rc != 0)
3141                 exit(rc);
3142 }
3143
3144 #define ZDB_FLAG_CHECKSUM       0x0001
3145 #define ZDB_FLAG_DECOMPRESS     0x0002
3146 #define ZDB_FLAG_BSWAP          0x0004
3147 #define ZDB_FLAG_GBH            0x0008
3148 #define ZDB_FLAG_INDIRECT       0x0010
3149 #define ZDB_FLAG_PHYS           0x0020
3150 #define ZDB_FLAG_RAW            0x0040
3151 #define ZDB_FLAG_PRINT_BLKPTR   0x0080
3152
3153 int flagbits[256];
3154
3155 static void
3156 zdb_print_blkptr(blkptr_t *bp, int flags)
3157 {
3158         char blkbuf[BP_SPRINTF_LEN];
3159
3160         if (flags & ZDB_FLAG_BSWAP)
3161                 byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
3162
3163         snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3164         (void) printf("%s\n", blkbuf);
3165 }
3166
3167 static void
3168 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
3169 {
3170         int i;
3171
3172         for (i = 0; i < nbps; i++)
3173                 zdb_print_blkptr(&bp[i], flags);
3174 }
3175
3176 static void
3177 zdb_dump_gbh(void *buf, int flags)
3178 {
3179         zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
3180 }
3181
3182 static void
3183 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
3184 {
3185         if (flags & ZDB_FLAG_BSWAP)
3186                 byteswap_uint64_array(buf, size);
3187         VERIFY(write(fileno(stdout), buf, size) == size);
3188 }
3189
3190 static void
3191 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
3192 {
3193         uint64_t *d = (uint64_t *)buf;
3194         int nwords = size / sizeof (uint64_t);
3195         int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
3196         int i, j;
3197         char *hdr, *c;
3198
3199
3200         if (do_bswap)
3201                 hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
3202         else
3203                 hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
3204
3205         (void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
3206
3207         for (i = 0; i < nwords; i += 2) {
3208                 (void) printf("%06llx:  %016llx  %016llx  ",
3209                     (u_longlong_t)(i * sizeof (uint64_t)),
3210                     (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
3211                     (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
3212
3213                 c = (char *)&d[i];
3214                 for (j = 0; j < 2 * sizeof (uint64_t); j++)
3215                         (void) printf("%c", isprint(c[j]) ? c[j] : '.');
3216                 (void) printf("\n");
3217         }
3218 }
3219
3220 /*
3221  * There are two acceptable formats:
3222  *      leaf_name         - For example: c1t0d0 or /tmp/ztest.0a
3223  *      child[.child]*    - For example: 0.1.1
3224  *
3225  * The second form can be used to specify arbitrary vdevs anywhere
3226  * in the heirarchy.  For example, in a pool with a mirror of
3227  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
3228  */
3229 static vdev_t *
3230 zdb_vdev_lookup(vdev_t *vdev, char *path)
3231 {
3232         char *s, *p, *q;
3233         int i;
3234
3235         if (vdev == NULL)
3236                 return (NULL);
3237
3238         /* First, assume the x.x.x.x format */
3239         i = (int)strtoul(path, &s, 10);
3240         if (s == path || (s && *s != '.' && *s != '\0'))
3241                 goto name;
3242         if (i < 0 || i >= vdev->vdev_children)
3243                 return (NULL);
3244
3245         vdev = vdev->vdev_child[i];
3246         if (*s == '\0')
3247                 return (vdev);
3248         return (zdb_vdev_lookup(vdev, s+1));
3249
3250 name:
3251         for (i = 0; i < vdev->vdev_children; i++) {
3252                 vdev_t *vc = vdev->vdev_child[i];
3253
3254                 if (vc->vdev_path == NULL) {
3255                         vc = zdb_vdev_lookup(vc, path);
3256                         if (vc == NULL)
3257                                 continue;
3258                         else
3259                                 return (vc);
3260                 }
3261
3262                 p = strrchr(vc->vdev_path, '/');
3263                 p = p ? p + 1 : vc->vdev_path;
3264                 q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
3265
3266                 if (strcmp(vc->vdev_path, path) == 0)
3267                         return (vc);
3268                 if (strcmp(p, path) == 0)
3269                         return (vc);
3270                 if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
3271                         return (vc);
3272         }
3273
3274         return (NULL);
3275 }
3276
3277 /*
3278  * Read a block from a pool and print it out.  The syntax of the
3279  * block descriptor is:
3280  *
3281  *      pool:vdev_specifier:offset:size[:flags]
3282  *
3283  *      pool           - The name of the pool you wish to read from
3284  *      vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
3285  *      offset         - offset, in hex, in bytes
3286  *      size           - Amount of data to read, in hex, in bytes
3287  *      flags          - A string of characters specifying options
3288  *               b: Decode a blkptr at given offset within block
3289  *              *c: Calculate and display checksums
3290  *               d: Decompress data before dumping
3291  *               e: Byteswap data before dumping
3292  *               g: Display data as a gang block header
3293  *               i: Display as an indirect block
3294  *               p: Do I/O to physical offset
3295  *               r: Dump raw data to stdout
3296  *
3297  *              * = not yet implemented
3298  */
3299 static void
3300 zdb_read_block(char *thing, spa_t *spa)
3301 {
3302         blkptr_t blk, *bp = &blk;
3303         dva_t *dva = bp->blk_dva;
3304         int flags = 0;
3305         uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
3306         zio_t *zio;
3307         vdev_t *vd;
3308         void *pbuf, *lbuf, *buf;
3309         char *s, *p, *dup, *vdev, *flagstr;
3310         int i, error;
3311
3312         dup = strdup(thing);
3313         s = strtok(dup, ":");
3314         vdev = s ? s : "";
3315         s = strtok(NULL, ":");
3316         offset = strtoull(s ? s : "", NULL, 16);
3317         s = strtok(NULL, ":");
3318         size = strtoull(s ? s : "", NULL, 16);
3319         s = strtok(NULL, ":");
3320         flagstr = s ? s : "";
3321
3322         s = NULL;
3323         if (size == 0)
3324                 s = "size must not be zero";
3325         if (!IS_P2ALIGNED(size, DEV_BSIZE))
3326                 s = "size must be a multiple of sector size";
3327         if (!IS_P2ALIGNED(offset, DEV_BSIZE))
3328                 s = "offset must be a multiple of sector size";
3329         if (s) {
3330                 (void) printf("Invalid block specifier: %s  - %s\n", thing, s);
3331                 free(dup);
3332                 return;
3333         }
3334
3335         for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
3336                 for (i = 0; flagstr[i]; i++) {
3337                         int bit = flagbits[(uchar_t)flagstr[i]];
3338
3339                         if (bit == 0) {
3340                                 (void) printf("***Invalid flag: %c\n",
3341                                     flagstr[i]);
3342                                 continue;
3343                         }
3344                         flags |= bit;
3345
3346                         /* If it's not something with an argument, keep going */
3347                         if ((bit & (ZDB_FLAG_CHECKSUM |
3348                             ZDB_FLAG_PRINT_BLKPTR)) == 0)
3349                                 continue;
3350
3351                         p = &flagstr[i + 1];
3352                         if (bit == ZDB_FLAG_PRINT_BLKPTR)
3353                                 blkptr_offset = strtoull(p, &p, 16);
3354                         if (*p != ':' && *p != '\0') {
3355                                 (void) printf("***Invalid flag arg: '%s'\n", s);
3356                                 free(dup);
3357                                 return;
3358                         }
3359                 }
3360         }
3361
3362         vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
3363         if (vd == NULL) {
3364                 (void) printf("***Invalid vdev: %s\n", vdev);
3365                 free(dup);
3366                 return;
3367         } else {
3368                 if (vd->vdev_path)
3369                         (void) fprintf(stderr, "Found vdev: %s\n",
3370                             vd->vdev_path);
3371                 else
3372                         (void) fprintf(stderr, "Found vdev type: %s\n",
3373                             vd->vdev_ops->vdev_op_type);
3374         }
3375
3376         psize = size;
3377         lsize = size;
3378
3379         pbuf = umem_alloc_aligned(SPA_MAXBLOCKSIZE, 512, UMEM_NOFAIL);
3380         lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3381
3382         BP_ZERO(bp);
3383
3384         DVA_SET_VDEV(&dva[0], vd->vdev_id);
3385         DVA_SET_OFFSET(&dva[0], offset);
3386         DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
3387         DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
3388
3389         BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
3390
3391         BP_SET_LSIZE(bp, lsize);
3392         BP_SET_PSIZE(bp, psize);
3393         BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
3394         BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
3395         BP_SET_TYPE(bp, DMU_OT_NONE);
3396         BP_SET_LEVEL(bp, 0);
3397         BP_SET_DEDUP(bp, 0);
3398         BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
3399
3400         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
3401         zio = zio_root(spa, NULL, NULL, 0);
3402
3403         if (vd == vd->vdev_top) {
3404                 /*
3405                  * Treat this as a normal block read.
3406                  */
3407                 zio_nowait(zio_read(zio, spa, bp, pbuf, psize, NULL, NULL,
3408                     ZIO_PRIORITY_SYNC_READ,
3409                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
3410         } else {
3411                 /*
3412                  * Treat this as a vdev child I/O.
3413                  */
3414                 zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pbuf, psize,
3415                     ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
3416                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
3417                     ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
3418                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL, NULL));
3419         }
3420
3421         error = zio_wait(zio);
3422         spa_config_exit(spa, SCL_STATE, FTAG);
3423
3424         if (error) {
3425                 (void) printf("Read of %s failed, error: %d\n", thing, error);
3426                 goto out;
3427         }
3428
3429         if (flags & ZDB_FLAG_DECOMPRESS) {
3430                 /*
3431                  * We don't know how the data was compressed, so just try
3432                  * every decompress function at every inflated blocksize.
3433                  */
3434                 enum zio_compress c;
3435                 void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3436                 void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3437
3438                 bcopy(pbuf, pbuf2, psize);
3439
3440                 VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf + psize,
3441                     SPA_MAXBLOCKSIZE - psize) == 0);
3442
3443                 VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
3444                     SPA_MAXBLOCKSIZE - psize) == 0);
3445
3446                 for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
3447                     lsize -= SPA_MINBLOCKSIZE) {
3448                         for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
3449                                 if (zio_decompress_data(c, pbuf, lbuf,
3450                                     psize, lsize) == 0 &&
3451                                     zio_decompress_data(c, pbuf2, lbuf2,
3452                                     psize, lsize) == 0 &&
3453                                     bcmp(lbuf, lbuf2, lsize) == 0)
3454                                         break;
3455                         }
3456                         if (c != ZIO_COMPRESS_FUNCTIONS)
3457                                 break;
3458                         lsize -= SPA_MINBLOCKSIZE;
3459                 }
3460
3461                 umem_free(pbuf2, SPA_MAXBLOCKSIZE);
3462                 umem_free(lbuf2, SPA_MAXBLOCKSIZE);
3463
3464                 if (lsize <= psize) {
3465                         (void) printf("Decompress of %s failed\n", thing);
3466                         goto out;
3467                 }
3468                 buf = lbuf;
3469                 size = lsize;
3470         } else {
3471                 buf = pbuf;
3472                 size = psize;
3473         }
3474
3475         if (flags & ZDB_FLAG_PRINT_BLKPTR)
3476                 zdb_print_blkptr((blkptr_t *)(void *)
3477                     ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
3478         else if (flags & ZDB_FLAG_RAW)
3479                 zdb_dump_block_raw(buf, size, flags);
3480         else if (flags & ZDB_FLAG_INDIRECT)
3481                 zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
3482                     flags);
3483         else if (flags & ZDB_FLAG_GBH)
3484                 zdb_dump_gbh(buf, flags);
3485         else
3486                 zdb_dump_block(thing, buf, size, flags);
3487
3488 out:
3489         umem_free(pbuf, SPA_MAXBLOCKSIZE);
3490         umem_free(lbuf, SPA_MAXBLOCKSIZE);
3491         free(dup);
3492 }
3493
3494 static boolean_t
3495 pool_match(nvlist_t *cfg, char *tgt)
3496 {
3497         uint64_t v, guid = strtoull(tgt, NULL, 0);
3498         char *s;
3499
3500         if (guid != 0) {
3501                 if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
3502                         return (v == guid);
3503         } else {
3504                 if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
3505                         return (strcmp(s, tgt) == 0);
3506         }
3507         return (B_FALSE);
3508 }
3509
3510 static char *
3511 find_zpool(char **target, nvlist_t **configp, int dirc, char **dirv)
3512 {
3513         nvlist_t *pools;
3514         nvlist_t *match = NULL;
3515         char *name = NULL;
3516         char *sepp = NULL;
3517         char sep = 0;
3518         int count = 0;
3519         importargs_t args = { 0 };
3520
3521         args.paths = dirc;
3522         args.path = dirv;
3523         args.can_be_active = B_TRUE;
3524
3525         if ((sepp = strpbrk(*target, "/@")) != NULL) {
3526                 sep = *sepp;
3527                 *sepp = '\0';
3528         }
3529
3530         pools = zpool_search_import(g_zfs, &args);
3531
3532         if (pools != NULL) {
3533                 nvpair_t *elem = NULL;
3534                 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3535                         verify(nvpair_value_nvlist(elem, configp) == 0);
3536                         if (pool_match(*configp, *target)) {
3537                                 count++;
3538                                 if (match != NULL) {
3539                                         /* print previously found config */
3540                                         if (name != NULL) {
3541                                                 (void) printf("%s\n", name);
3542                                                 dump_nvlist(match, 8);
3543                                                 name = NULL;
3544                                         }
3545                                         (void) printf("%s\n",
3546                                             nvpair_name(elem));
3547                                         dump_nvlist(*configp, 8);
3548                                 } else {
3549                                         match = *configp;
3550                                         name = nvpair_name(elem);
3551                                 }
3552                         }
3553                 }
3554         }
3555         if (count > 1)
3556                 (void) fatal("\tMatched %d pools - use pool GUID "
3557                     "instead of pool name or \n"
3558                     "\tpool name part of a dataset name to select pool", count);
3559
3560         if (sepp)
3561                 *sepp = sep;
3562         /*
3563          * If pool GUID was specified for pool id, replace it with pool name
3564          */
3565         if (name && (strstr(*target, name) != *target)) {
3566                 int sz = 1 + strlen(name) + ((sepp) ? strlen(sepp) : 0);
3567
3568                 *target = umem_alloc(sz, UMEM_NOFAIL);
3569                 (void) snprintf(*target, sz, "%s%s", name, sepp ? sepp : "");
3570         }
3571
3572         *configp = name ? match : NULL;
3573
3574         return (name);
3575 }
3576
3577 int
3578 main(int argc, char **argv)
3579 {
3580         int i, c;
3581         struct rlimit rl = { 1024, 1024 };
3582         spa_t *spa = NULL;
3583         objset_t *os = NULL;
3584         int dump_all = 1;
3585         int verbose = 0;
3586         int error = 0;
3587         char **searchdirs = NULL;
3588         int nsearch = 0;
3589         char *target;
3590         nvlist_t *policy = NULL;
3591         uint64_t max_txg = UINT64_MAX;
3592         int flags = ZFS_IMPORT_MISSING_LOG;
3593         int rewind = ZPOOL_NEVER_REWIND;
3594         char *spa_config_path_env;
3595         const char *opts = "bcdhilmMI:suCDRSAFLXevp:t:U:P";
3596         boolean_t target_is_spa = B_TRUE;
3597
3598         (void) setrlimit(RLIMIT_NOFILE, &rl);
3599         (void) enable_extended_FILE_stdio(-1, -1);
3600
3601         dprintf_setup(&argc, argv);
3602
3603         /*
3604          * If there is an environment variable SPA_CONFIG_PATH it overrides
3605          * default spa_config_path setting. If -U flag is specified it will
3606          * override this environment variable settings once again.
3607          */
3608         spa_config_path_env = getenv("SPA_CONFIG_PATH");
3609         if (spa_config_path_env != NULL)
3610                 spa_config_path = spa_config_path_env;
3611
3612         while ((c = getopt(argc, argv, opts)) != -1) {
3613                 switch (c) {
3614                 case 'b':
3615                 case 'c':
3616                 case 'd':
3617                 case 'h':
3618                 case 'i':
3619                 case 'l':
3620                 case 'm':
3621                 case 's':
3622                 case 'u':
3623                 case 'C':
3624                 case 'D':
3625                 case 'M':
3626                 case 'R':
3627                 case 'S':
3628                         dump_opt[c]++;
3629                         dump_all = 0;
3630                         break;
3631                 case 'A':
3632                 case 'F':
3633                 case 'L':
3634                 case 'X':
3635                 case 'e':
3636                 case 'P':
3637                         dump_opt[c]++;
3638                         break;
3639                 case 'V':
3640                         flags = ZFS_IMPORT_VERBATIM;
3641                         break;
3642                 case 'I':
3643                         max_inflight = strtoull(optarg, NULL, 0);
3644                         if (max_inflight == 0) {
3645                                 (void) fprintf(stderr, "maximum number "
3646                                     "of inflight I/Os must be greater "
3647                                     "than 0\n");
3648                                 usage();
3649                         }
3650                         break;
3651                 case 'p':
3652                         if (searchdirs == NULL) {
3653                                 searchdirs = umem_alloc(sizeof (char *),
3654                                     UMEM_NOFAIL);
3655                         } else {
3656                                 char **tmp = umem_alloc((nsearch + 1) *
3657                                     sizeof (char *), UMEM_NOFAIL);
3658                                 bcopy(searchdirs, tmp, nsearch *
3659                                     sizeof (char *));
3660                                 umem_free(searchdirs,
3661                                     nsearch * sizeof (char *));
3662                                 searchdirs = tmp;
3663                         }
3664                         searchdirs[nsearch++] = optarg;
3665                         break;
3666                 case 't':
3667                         max_txg = strtoull(optarg, NULL, 0);
3668                         if (max_txg < TXG_INITIAL) {
3669                                 (void) fprintf(stderr, "incorrect txg "
3670                                     "specified: %s\n", optarg);
3671                                 usage();
3672                         }
3673                         break;
3674                 case 'U':
3675                         spa_config_path = optarg;
3676                         break;
3677                 case 'v':
3678                         verbose++;
3679                         break;
3680                 default:
3681                         usage();
3682                         break;
3683                 }
3684         }
3685
3686         if (!dump_opt['e'] && searchdirs != NULL) {
3687                 (void) fprintf(stderr, "-p option requires use of -e\n");
3688                 usage();
3689         }
3690
3691 #if defined(_LP64)
3692         /*
3693          * ZDB does not typically re-read blocks; therefore limit the ARC
3694          * to 256 MB, which can be used entirely for metadata.
3695          */
3696         zfs_arc_max = zfs_arc_meta_limit = 256 * 1024 * 1024;
3697 #endif
3698
3699         /*
3700          * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
3701          * "zdb -b" uses traversal prefetch which uses async reads.
3702          * For good performance, let several of them be active at once.
3703          */
3704         zfs_vdev_async_read_max_active = 10;
3705
3706         kernel_init(FREAD);
3707         if ((g_zfs = libzfs_init()) == NULL) {
3708                 (void) fprintf(stderr, "%s", libzfs_error_init(errno));
3709                 return (1);
3710         }
3711
3712         if (dump_all)
3713                 verbose = MAX(verbose, 1);
3714
3715         for (c = 0; c < 256; c++) {
3716                 if (dump_all && !strchr("elAFLRSXP", c))
3717                         dump_opt[c] = 1;
3718                 if (dump_opt[c])
3719                         dump_opt[c] += verbose;
3720         }
3721
3722         aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
3723         zfs_recover = (dump_opt['A'] > 1);
3724
3725         argc -= optind;
3726         argv += optind;
3727
3728         if (argc < 2 && dump_opt['R'])
3729                 usage();
3730         if (argc < 1) {
3731                 if (!dump_opt['e'] && dump_opt['C']) {
3732                         dump_cachefile(spa_config_path);
3733                         return (0);
3734                 }
3735                 usage();
3736         }
3737
3738         if (dump_opt['l']) {
3739                 dump_label(argv[0]);
3740                 return (0);
3741         }
3742
3743         if (dump_opt['X'] || dump_opt['F'])
3744                 rewind = ZPOOL_DO_REWIND |
3745                     (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
3746
3747         if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
3748             nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, max_txg) != 0 ||
3749             nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind) != 0)
3750                 fatal("internal error: %s", strerror(ENOMEM));
3751
3752         error = 0;
3753         target = argv[0];
3754
3755         if (dump_opt['e']) {
3756                 nvlist_t *cfg = NULL;
3757                 char *name = find_zpool(&target, &cfg, nsearch, searchdirs);
3758
3759                 error = ENOENT;
3760                 if (name) {
3761                         if (dump_opt['C'] > 1) {
3762                                 (void) printf("\nConfiguration for import:\n");
3763                                 dump_nvlist(cfg, 8);
3764                         }
3765                         if (nvlist_add_nvlist(cfg,
3766                             ZPOOL_REWIND_POLICY, policy) != 0) {
3767                                 fatal("can't open '%s': %s",
3768                                     target, strerror(ENOMEM));
3769                         }
3770                         error = spa_import(name, cfg, NULL, flags);
3771                 }
3772         }
3773
3774         if (strpbrk(target, "/@") != NULL) {
3775                 size_t targetlen;
3776
3777                 target_is_spa = B_FALSE;
3778                 targetlen = strlen(target);
3779                 if (targetlen && target[targetlen - 1] == '/')
3780                         target[targetlen - 1] = '\0';
3781         }
3782
3783         if (error == 0) {
3784                 if (target_is_spa || dump_opt['R']) {
3785                         error = spa_open_rewind(target, &spa, FTAG, policy,
3786                             NULL);
3787                         if (error) {
3788                                 /*
3789                                  * If we're missing the log device then
3790                                  * try opening the pool after clearing the
3791                                  * log state.
3792                                  */
3793                                 mutex_enter(&spa_namespace_lock);
3794                                 if ((spa = spa_lookup(target)) != NULL &&
3795                                     spa->spa_log_state == SPA_LOG_MISSING) {
3796                                         spa->spa_log_state = SPA_LOG_CLEAR;
3797                                         error = 0;
3798                                 }
3799                                 mutex_exit(&spa_namespace_lock);
3800
3801                                 if (!error) {
3802                                         error = spa_open_rewind(target, &spa,
3803                                             FTAG, policy, NULL);
3804                                 }
3805                         }
3806                 } else {
3807                         error = dmu_objset_own(target, DMU_OST_ANY,
3808                             B_TRUE, FTAG, &os);
3809                 }
3810         }
3811         nvlist_free(policy);
3812
3813         if (error)
3814                 fatal("can't open '%s': %s", target, strerror(error));
3815
3816         argv++;
3817         argc--;
3818         if (!dump_opt['R']) {
3819                 if (argc > 0) {
3820                         zopt_objects = argc;
3821                         zopt_object = calloc(zopt_objects, sizeof (uint64_t));
3822                         for (i = 0; i < zopt_objects; i++) {
3823                                 errno = 0;
3824                                 zopt_object[i] = strtoull(argv[i], NULL, 0);
3825                                 if (zopt_object[i] == 0 && errno != 0)
3826                                         fatal("bad number %s: %s",
3827                                             argv[i], strerror(errno));
3828                         }
3829                 }
3830                 if (os != NULL) {
3831                         dump_dir(os);
3832                 } else if (zopt_objects > 0 && !dump_opt['m']) {
3833                         dump_dir(spa->spa_meta_objset);
3834                 } else {
3835                         dump_zpool(spa);
3836                 }
3837         } else {
3838                 flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
3839                 flagbits['c'] = ZDB_FLAG_CHECKSUM;
3840                 flagbits['d'] = ZDB_FLAG_DECOMPRESS;
3841                 flagbits['e'] = ZDB_FLAG_BSWAP;
3842                 flagbits['g'] = ZDB_FLAG_GBH;
3843                 flagbits['i'] = ZDB_FLAG_INDIRECT;
3844                 flagbits['p'] = ZDB_FLAG_PHYS;
3845                 flagbits['r'] = ZDB_FLAG_RAW;
3846
3847                 for (i = 0; i < argc; i++)
3848                         zdb_read_block(argv[i], spa);
3849         }
3850
3851         (os != NULL) ? dmu_objset_disown(os, FTAG) : spa_close(spa, FTAG);
3852
3853         fuid_table_destroy();
3854         sa_loaded = B_FALSE;
3855
3856         libzfs_fini(g_zfs);
3857         kernel_fini();
3858
3859         return (0);
3860 }