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