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