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