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