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