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