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