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