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