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