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