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