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