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