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