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