xref: /titanic_41/usr/src/cmd/zdb/zdb.c (revision a563a037ee1e9e7c39304f3775eb7327ab86b914)
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  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <stdio.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/vdev.h>
40 #include <sys/vdev_impl.h>
41 #include <sys/metaslab_impl.h>
42 #include <sys/dmu_objset.h>
43 #include <sys/dsl_dir.h>
44 #include <sys/dsl_dataset.h>
45 #include <sys/dsl_pool.h>
46 #include <sys/dbuf.h>
47 #include <sys/zil.h>
48 #include <sys/zil_impl.h>
49 #include <sys/stat.h>
50 #include <sys/resource.h>
51 #include <sys/dmu_traverse.h>
52 #include <sys/zio_checksum.h>
53 #include <sys/zio_compress.h>
54 #include <sys/zfs_fuid.h>
55 #undef ZFS_MAXNAMELEN
56 #undef verify
57 #include <libzfs.h>
58 
59 const char cmdname[] = "zdb";
60 uint8_t dump_opt[256];
61 
62 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
63 
64 extern void dump_intent_log(zilog_t *);
65 uint64_t *zopt_object = NULL;
66 int zopt_objects = 0;
67 int zdb_advance = ADVANCE_PRE;
68 zbookmark_t zdb_noread = { 0, 0, ZB_NO_LEVEL, 0 };
69 libzfs_handle_t *g_zfs;
70 boolean_t zdb_sig_user_data = B_TRUE;
71 int zdb_sig_cksumalg = ZIO_CHECKSUM_SHA256;
72 
73 /*
74  * These libumem hooks provide a reasonable set of defaults for the allocator's
75  * debugging facilities.
76  */
77 const char *
78 _umem_debug_init()
79 {
80 	return ("default,verbose"); /* $UMEM_DEBUG setting */
81 }
82 
83 const char *
84 _umem_logging_init(void)
85 {
86 	return ("fail,contents"); /* $UMEM_LOGGING setting */
87 }
88 
89 static void
90 usage(void)
91 {
92 	(void) fprintf(stderr,
93 	    "Usage: %s [-udibcsvL] [-U cachefile_path] [-O order] "
94 	    "[-B os:obj:level:blkid] [-S user:cksumalg] "
95 	    "dataset [object...]\n"
96 	    "       %s -C [pool]\n"
97 	    "       %s -l dev\n"
98 	    "       %s -R vdev:offset:size:flags\n"
99 	    "       %s [-p path_to_vdev_dir]\n"
100 	    "       %s -e pool | GUID | devid ...\n",
101 	    cmdname, cmdname, cmdname, cmdname, cmdname, cmdname);
102 
103 	(void) fprintf(stderr, "	-u uberblock\n");
104 	(void) fprintf(stderr, "	-d datasets\n");
105 	(void) fprintf(stderr, "        -C cached pool configuration\n");
106 	(void) fprintf(stderr, "	-i intent logs\n");
107 	(void) fprintf(stderr, "	-b block statistics\n");
108 	(void) fprintf(stderr, "	-c checksum all data blocks\n");
109 	(void) fprintf(stderr, "	-s report stats on zdb's I/O\n");
110 	(void) fprintf(stderr, "	-S <user|all>:<cksum_alg|all> -- "
111 	    "dump blkptr signatures\n");
112 	(void) fprintf(stderr, "	-v verbose (applies to all others)\n");
113 	(void) fprintf(stderr, "        -l dump label contents\n");
114 	(void) fprintf(stderr, "	-L live pool (allows some errors)\n");
115 	(void) fprintf(stderr, "	-O [!]<pre|post|prune|data|holes> "
116 	    "visitation order\n");
117 	(void) fprintf(stderr, "	-U cachefile_path -- use alternate "
118 	    "cachefile\n");
119 	(void) fprintf(stderr, "	-B objset:object:level:blkid -- "
120 	    "simulate bad block\n");
121 	(void) fprintf(stderr, "        -R read and display block from a "
122 	    "device\n");
123 	(void) fprintf(stderr, "        -e Pool is exported/destroyed/"
124 	    "has altroot\n");
125 	(void) fprintf(stderr, "	-p <Path to vdev dir> (use with -e)\n");
126 	(void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
127 	    "to make only that option verbose\n");
128 	(void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
129 	exit(1);
130 }
131 
132 static void
133 fatal(const char *fmt, ...)
134 {
135 	va_list ap;
136 
137 	va_start(ap, fmt);
138 	(void) fprintf(stderr, "%s: ", cmdname);
139 	(void) vfprintf(stderr, fmt, ap);
140 	va_end(ap);
141 	(void) fprintf(stderr, "\n");
142 
143 	exit(1);
144 }
145 
146 static void
147 dump_nvlist(nvlist_t *list, int indent)
148 {
149 	nvpair_t *elem = NULL;
150 
151 	while ((elem = nvlist_next_nvpair(list, elem)) != NULL) {
152 		switch (nvpair_type(elem)) {
153 		case DATA_TYPE_STRING:
154 			{
155 				char *value;
156 
157 				VERIFY(nvpair_value_string(elem, &value) == 0);
158 				(void) printf("%*s%s='%s'\n", indent, "",
159 				    nvpair_name(elem), value);
160 			}
161 			break;
162 
163 		case DATA_TYPE_UINT64:
164 			{
165 				uint64_t value;
166 
167 				VERIFY(nvpair_value_uint64(elem, &value) == 0);
168 				(void) printf("%*s%s=%llu\n", indent, "",
169 				    nvpair_name(elem), (u_longlong_t)value);
170 			}
171 			break;
172 
173 		case DATA_TYPE_NVLIST:
174 			{
175 				nvlist_t *value;
176 
177 				VERIFY(nvpair_value_nvlist(elem, &value) == 0);
178 				(void) printf("%*s%s\n", indent, "",
179 				    nvpair_name(elem));
180 				dump_nvlist(value, indent + 4);
181 			}
182 			break;
183 
184 		case DATA_TYPE_NVLIST_ARRAY:
185 			{
186 				nvlist_t **value;
187 				uint_t c, count;
188 
189 				VERIFY(nvpair_value_nvlist_array(elem, &value,
190 				    &count) == 0);
191 
192 				for (c = 0; c < count; c++) {
193 					(void) printf("%*s%s[%u]\n", indent, "",
194 					    nvpair_name(elem), c);
195 					dump_nvlist(value[c], indent + 8);
196 				}
197 			}
198 			break;
199 
200 		default:
201 
202 			(void) printf("bad config type %d for %s\n",
203 			    nvpair_type(elem), nvpair_name(elem));
204 		}
205 	}
206 }
207 
208 /* ARGSUSED */
209 static void
210 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
211 {
212 	nvlist_t *nv;
213 	size_t nvsize = *(uint64_t *)data;
214 	char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
215 
216 	VERIFY(0 == dmu_read(os, object, 0, nvsize, packed));
217 
218 	VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
219 
220 	umem_free(packed, nvsize);
221 
222 	dump_nvlist(nv, 8);
223 
224 	nvlist_free(nv);
225 }
226 
227 const char dump_zap_stars[] = "****************************************";
228 const int dump_zap_width = sizeof (dump_zap_stars) - 1;
229 
230 static void
231 dump_zap_histogram(uint64_t histo[ZAP_HISTOGRAM_SIZE])
232 {
233 	int i;
234 	int minidx = ZAP_HISTOGRAM_SIZE - 1;
235 	int maxidx = 0;
236 	uint64_t max = 0;
237 
238 	for (i = 0; i < ZAP_HISTOGRAM_SIZE; i++) {
239 		if (histo[i] > max)
240 			max = histo[i];
241 		if (histo[i] > 0 && i > maxidx)
242 			maxidx = i;
243 		if (histo[i] > 0 && i < minidx)
244 			minidx = i;
245 	}
246 
247 	if (max < dump_zap_width)
248 		max = dump_zap_width;
249 
250 	for (i = minidx; i <= maxidx; i++)
251 		(void) printf("\t\t\t%u: %6llu %s\n", i, (u_longlong_t)histo[i],
252 		    &dump_zap_stars[(max - histo[i]) * dump_zap_width / max]);
253 }
254 
255 static void
256 dump_zap_stats(objset_t *os, uint64_t object)
257 {
258 	int error;
259 	zap_stats_t zs;
260 
261 	error = zap_get_stats(os, object, &zs);
262 	if (error)
263 		return;
264 
265 	if (zs.zs_ptrtbl_len == 0) {
266 		ASSERT(zs.zs_num_blocks == 1);
267 		(void) printf("\tmicrozap: %llu bytes, %llu entries\n",
268 		    (u_longlong_t)zs.zs_blocksize,
269 		    (u_longlong_t)zs.zs_num_entries);
270 		return;
271 	}
272 
273 	(void) printf("\tFat ZAP stats:\n");
274 
275 	(void) printf("\t\tPointer table:\n");
276 	(void) printf("\t\t\t%llu elements\n",
277 	    (u_longlong_t)zs.zs_ptrtbl_len);
278 	(void) printf("\t\t\tzt_blk: %llu\n",
279 	    (u_longlong_t)zs.zs_ptrtbl_zt_blk);
280 	(void) printf("\t\t\tzt_numblks: %llu\n",
281 	    (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
282 	(void) printf("\t\t\tzt_shift: %llu\n",
283 	    (u_longlong_t)zs.zs_ptrtbl_zt_shift);
284 	(void) printf("\t\t\tzt_blks_copied: %llu\n",
285 	    (u_longlong_t)zs.zs_ptrtbl_blks_copied);
286 	(void) printf("\t\t\tzt_nextblk: %llu\n",
287 	    (u_longlong_t)zs.zs_ptrtbl_nextblk);
288 
289 	(void) printf("\t\tZAP entries: %llu\n",
290 	    (u_longlong_t)zs.zs_num_entries);
291 	(void) printf("\t\tLeaf blocks: %llu\n",
292 	    (u_longlong_t)zs.zs_num_leafs);
293 	(void) printf("\t\tTotal blocks: %llu\n",
294 	    (u_longlong_t)zs.zs_num_blocks);
295 	(void) printf("\t\tzap_block_type: 0x%llx\n",
296 	    (u_longlong_t)zs.zs_block_type);
297 	(void) printf("\t\tzap_magic: 0x%llx\n",
298 	    (u_longlong_t)zs.zs_magic);
299 	(void) printf("\t\tzap_salt: 0x%llx\n",
300 	    (u_longlong_t)zs.zs_salt);
301 
302 	(void) printf("\t\tLeafs with 2^n pointers:\n");
303 	dump_zap_histogram(zs.zs_leafs_with_2n_pointers);
304 
305 	(void) printf("\t\tBlocks with n*5 entries:\n");
306 	dump_zap_histogram(zs.zs_blocks_with_n5_entries);
307 
308 	(void) printf("\t\tBlocks n/10 full:\n");
309 	dump_zap_histogram(zs.zs_blocks_n_tenths_full);
310 
311 	(void) printf("\t\tEntries with n chunks:\n");
312 	dump_zap_histogram(zs.zs_entries_using_n_chunks);
313 
314 	(void) printf("\t\tBuckets with n entries:\n");
315 	dump_zap_histogram(zs.zs_buckets_with_n_entries);
316 }
317 
318 /*ARGSUSED*/
319 static void
320 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
321 {
322 }
323 
324 /*ARGSUSED*/
325 void
326 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
327 {
328 }
329 
330 /*ARGSUSED*/
331 static void
332 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
333 {
334 }
335 
336 /*ARGSUSED*/
337 static void
338 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
339 {
340 	zap_cursor_t zc;
341 	zap_attribute_t attr;
342 	void *prop;
343 	int i;
344 
345 	dump_zap_stats(os, object);
346 	(void) printf("\n");
347 
348 	for (zap_cursor_init(&zc, os, object);
349 	    zap_cursor_retrieve(&zc, &attr) == 0;
350 	    zap_cursor_advance(&zc)) {
351 		(void) printf("\t\t%s = ", attr.za_name);
352 		if (attr.za_num_integers == 0) {
353 			(void) printf("\n");
354 			continue;
355 		}
356 		prop = umem_zalloc(attr.za_num_integers *
357 		    attr.za_integer_length, UMEM_NOFAIL);
358 		(void) zap_lookup(os, object, attr.za_name,
359 		    attr.za_integer_length, attr.za_num_integers, prop);
360 		if (attr.za_integer_length == 1) {
361 			(void) printf("%s", (char *)prop);
362 		} else {
363 			for (i = 0; i < attr.za_num_integers; i++) {
364 				switch (attr.za_integer_length) {
365 				case 2:
366 					(void) printf("%u ",
367 					    ((uint16_t *)prop)[i]);
368 					break;
369 				case 4:
370 					(void) printf("%u ",
371 					    ((uint32_t *)prop)[i]);
372 					break;
373 				case 8:
374 					(void) printf("%lld ",
375 					    (u_longlong_t)((int64_t *)prop)[i]);
376 					break;
377 				}
378 			}
379 		}
380 		(void) printf("\n");
381 		umem_free(prop, attr.za_num_integers * attr.za_integer_length);
382 	}
383 	zap_cursor_fini(&zc);
384 }
385 
386 /*ARGSUSED*/
387 static void
388 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
389 {
390 	zap_cursor_t zc;
391 	zap_attribute_t attr;
392 	const char *typenames[] = {
393 		/* 0 */ "not specified",
394 		/* 1 */ "FIFO",
395 		/* 2 */ "Character Device",
396 		/* 3 */ "3 (invalid)",
397 		/* 4 */ "Directory",
398 		/* 5 */ "5 (invalid)",
399 		/* 6 */ "Block Device",
400 		/* 7 */ "7 (invalid)",
401 		/* 8 */ "Regular File",
402 		/* 9 */ "9 (invalid)",
403 		/* 10 */ "Symbolic Link",
404 		/* 11 */ "11 (invalid)",
405 		/* 12 */ "Socket",
406 		/* 13 */ "Door",
407 		/* 14 */ "Event Port",
408 		/* 15 */ "15 (invalid)",
409 	};
410 
411 	dump_zap_stats(os, object);
412 	(void) printf("\n");
413 
414 	for (zap_cursor_init(&zc, os, object);
415 	    zap_cursor_retrieve(&zc, &attr) == 0;
416 	    zap_cursor_advance(&zc)) {
417 		(void) printf("\t\t%s = %lld (type: %s)\n",
418 		    attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
419 		    typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
420 	}
421 	zap_cursor_fini(&zc);
422 }
423 
424 static void
425 dump_spacemap(objset_t *os, space_map_obj_t *smo, space_map_t *sm)
426 {
427 	uint64_t alloc, offset, entry;
428 	uint8_t mapshift = sm->sm_shift;
429 	uint64_t mapstart = sm->sm_start;
430 	char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
431 			    "INVALID", "INVALID", "INVALID", "INVALID" };
432 
433 	if (smo->smo_object == 0)
434 		return;
435 
436 	/*
437 	 * Print out the freelist entries in both encoded and decoded form.
438 	 */
439 	alloc = 0;
440 	for (offset = 0; offset < smo->smo_objsize; offset += sizeof (entry)) {
441 		VERIFY(0 == dmu_read(os, smo->smo_object, offset,
442 		    sizeof (entry), &entry));
443 		if (SM_DEBUG_DECODE(entry)) {
444 			(void) printf("\t\t[%4llu] %s: txg %llu, pass %llu\n",
445 			    (u_longlong_t)(offset / sizeof (entry)),
446 			    ddata[SM_DEBUG_ACTION_DECODE(entry)],
447 			    (u_longlong_t)SM_DEBUG_TXG_DECODE(entry),
448 			    (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(entry));
449 		} else {
450 			(void) printf("\t\t[%4llu]    %c  range:"
451 			    " %08llx-%08llx  size: %06llx\n",
452 			    (u_longlong_t)(offset / sizeof (entry)),
453 			    SM_TYPE_DECODE(entry) == SM_ALLOC ? 'A' : 'F',
454 			    (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
455 			    mapshift) + mapstart),
456 			    (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
457 			    mapshift) + mapstart + (SM_RUN_DECODE(entry) <<
458 			    mapshift)),
459 			    (u_longlong_t)(SM_RUN_DECODE(entry) << mapshift));
460 			if (SM_TYPE_DECODE(entry) == SM_ALLOC)
461 				alloc += SM_RUN_DECODE(entry) << mapshift;
462 			else
463 				alloc -= SM_RUN_DECODE(entry) << mapshift;
464 		}
465 	}
466 	if (alloc != smo->smo_alloc) {
467 		(void) printf("space_map_object alloc (%llu) INCONSISTENT "
468 		    "with space map summary (%llu)\n",
469 		    (u_longlong_t)smo->smo_alloc, (u_longlong_t)alloc);
470 	}
471 }
472 
473 static void
474 dump_metaslab(metaslab_t *msp)
475 {
476 	char freebuf[5];
477 	space_map_obj_t *smo = &msp->ms_smo;
478 	vdev_t *vd = msp->ms_group->mg_vd;
479 	spa_t *spa = vd->vdev_spa;
480 
481 	nicenum(msp->ms_map.sm_size - smo->smo_alloc, freebuf);
482 
483 	if (dump_opt['d'] <= 5) {
484 		(void) printf("\t%10llx   %10llu   %5s\n",
485 		    (u_longlong_t)msp->ms_map.sm_start,
486 		    (u_longlong_t)smo->smo_object,
487 		    freebuf);
488 		return;
489 	}
490 
491 	(void) printf(
492 	    "\tvdev %llu   offset %08llx   spacemap %4llu   free %5s\n",
493 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)msp->ms_map.sm_start,
494 	    (u_longlong_t)smo->smo_object, freebuf);
495 
496 	ASSERT(msp->ms_map.sm_size == (1ULL << vd->vdev_ms_shift));
497 
498 	dump_spacemap(spa->spa_meta_objset, smo, &msp->ms_map);
499 }
500 
501 static void
502 dump_metaslabs(spa_t *spa)
503 {
504 	vdev_t *rvd = spa->spa_root_vdev;
505 	vdev_t *vd;
506 	int c, m;
507 
508 	(void) printf("\nMetaslabs:\n");
509 
510 	for (c = 0; c < rvd->vdev_children; c++) {
511 		vd = rvd->vdev_child[c];
512 
513 		(void) printf("\n    vdev %llu = %s\n\n",
514 		    (u_longlong_t)vd->vdev_id, vdev_description(vd));
515 
516 		if (dump_opt['d'] <= 5) {
517 			(void) printf("\t%10s   %10s   %5s\n",
518 			    "offset", "spacemap", "free");
519 			(void) printf("\t%10s   %10s   %5s\n",
520 			    "------", "--------", "----");
521 		}
522 		for (m = 0; m < vd->vdev_ms_count; m++)
523 			dump_metaslab(vd->vdev_ms[m]);
524 		(void) printf("\n");
525 	}
526 }
527 
528 static void
529 dump_dtl(vdev_t *vd, int indent)
530 {
531 	avl_tree_t *t = &vd->vdev_dtl_map.sm_root;
532 	space_seg_t *ss;
533 	vdev_t *pvd;
534 	int c;
535 
536 	if (indent == 0)
537 		(void) printf("\nDirty time logs:\n\n");
538 
539 	(void) printf("\t%*s%s\n", indent, "", vdev_description(vd));
540 
541 	for (ss = avl_first(t); ss; ss = AVL_NEXT(t, ss)) {
542 		/*
543 		 * Everything in this DTL must appear in all parent DTL unions.
544 		 */
545 		for (pvd = vd; pvd; pvd = pvd->vdev_parent)
546 			ASSERT(vdev_dtl_contains(&pvd->vdev_dtl_map,
547 			    ss->ss_start, ss->ss_end - ss->ss_start));
548 		(void) printf("\t%*soutage [%llu,%llu] length %llu\n",
549 		    indent, "",
550 		    (u_longlong_t)ss->ss_start,
551 		    (u_longlong_t)ss->ss_end - 1,
552 		    (u_longlong_t)(ss->ss_end - ss->ss_start));
553 	}
554 
555 	(void) printf("\n");
556 
557 	if (dump_opt['d'] > 5 && vd->vdev_children == 0) {
558 		dump_spacemap(vd->vdev_spa->spa_meta_objset, &vd->vdev_dtl,
559 		    &vd->vdev_dtl_map);
560 		(void) printf("\n");
561 	}
562 
563 	for (c = 0; c < vd->vdev_children; c++)
564 		dump_dtl(vd->vdev_child[c], indent + 4);
565 }
566 
567 /*ARGSUSED*/
568 static void
569 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
570 {
571 }
572 
573 static uint64_t
574 blkid2offset(dnode_phys_t *dnp, int level, uint64_t blkid)
575 {
576 	if (level < 0)
577 		return (blkid);
578 
579 	return ((blkid << (level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
580 	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
581 }
582 
583 static void
584 sprintf_blkptr_compact(char *blkbuf, blkptr_t *bp, int alldvas)
585 {
586 	dva_t *dva = bp->blk_dva;
587 	int ndvas = alldvas ? BP_GET_NDVAS(bp) : 1;
588 	int i;
589 
590 	blkbuf[0] = '\0';
591 
592 	for (i = 0; i < ndvas; i++)
593 		(void) sprintf(blkbuf + strlen(blkbuf), "%llu:%llx:%llx ",
594 		    (u_longlong_t)DVA_GET_VDEV(&dva[i]),
595 		    (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
596 		    (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
597 
598 	(void) sprintf(blkbuf + strlen(blkbuf), "%llxL/%llxP F=%llu B=%llu",
599 	    (u_longlong_t)BP_GET_LSIZE(bp),
600 	    (u_longlong_t)BP_GET_PSIZE(bp),
601 	    (u_longlong_t)bp->blk_fill,
602 	    (u_longlong_t)bp->blk_birth);
603 }
604 
605 /* ARGSUSED */
606 static int
607 zdb_indirect_cb(traverse_blk_cache_t *bc, spa_t *spa, void *a)
608 {
609 	zbookmark_t *zb = &bc->bc_bookmark;
610 	blkptr_t *bp = &bc->bc_blkptr;
611 	void *data = bc->bc_data;
612 	dnode_phys_t *dnp = bc->bc_dnode;
613 	char blkbuf[BP_SPRINTF_LEN + 80];
614 	int l;
615 
616 	if (bc->bc_errno) {
617 		(void) sprintf(blkbuf,
618 		    "Error %d reading <%llu, %llu, %lld, %llu>: ",
619 		    bc->bc_errno,
620 		    (u_longlong_t)zb->zb_objset,
621 		    (u_longlong_t)zb->zb_object,
622 		    (u_longlong_t)zb->zb_level,
623 		    (u_longlong_t)zb->zb_blkid);
624 		goto out;
625 	}
626 
627 	if (zb->zb_level == -1) {
628 		ASSERT3U(BP_GET_TYPE(bp), ==, DMU_OT_OBJSET);
629 		ASSERT3U(BP_GET_LEVEL(bp), ==, 0);
630 	} else {
631 		ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
632 		ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
633 	}
634 
635 	if (zb->zb_level > 0) {
636 		uint64_t fill = 0;
637 		blkptr_t *bpx, *bpend;
638 
639 		for (bpx = data, bpend = bpx + BP_GET_LSIZE(bp) / sizeof (*bpx);
640 		    bpx < bpend; bpx++) {
641 			if (bpx->blk_birth != 0) {
642 				fill += bpx->blk_fill;
643 			} else {
644 				ASSERT(bpx->blk_fill == 0);
645 			}
646 		}
647 		ASSERT3U(fill, ==, bp->blk_fill);
648 	}
649 
650 	if (zb->zb_level == 0 && dnp->dn_type == DMU_OT_DNODE) {
651 		uint64_t fill = 0;
652 		dnode_phys_t *dnx, *dnend;
653 
654 		for (dnx = data, dnend = dnx + (BP_GET_LSIZE(bp)>>DNODE_SHIFT);
655 		    dnx < dnend; dnx++) {
656 			if (dnx->dn_type != DMU_OT_NONE)
657 				fill++;
658 		}
659 		ASSERT3U(fill, ==, bp->blk_fill);
660 	}
661 
662 	(void) sprintf(blkbuf, "%16llx ",
663 	    (u_longlong_t)blkid2offset(dnp, zb->zb_level, zb->zb_blkid));
664 
665 	ASSERT(zb->zb_level >= 0);
666 
667 	for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
668 		if (l == zb->zb_level) {
669 			(void) sprintf(blkbuf + strlen(blkbuf), "L%llx",
670 			    (u_longlong_t)zb->zb_level);
671 		} else {
672 			(void) sprintf(blkbuf + strlen(blkbuf), " ");
673 		}
674 	}
675 
676 out:
677 	if (bp->blk_birth == 0) {
678 		(void) sprintf(blkbuf + strlen(blkbuf), "<hole>");
679 		(void) printf("%s\n", blkbuf);
680 	} else {
681 		sprintf_blkptr_compact(blkbuf + strlen(blkbuf), bp,
682 		    dump_opt['d'] > 5 ? 1 : 0);
683 		(void) printf("%s\n", blkbuf);
684 	}
685 
686 	return (bc->bc_errno ? ERESTART : 0);
687 }
688 
689 /*ARGSUSED*/
690 static void
691 dump_indirect(objset_t *os, uint64_t object, void *data, size_t size)
692 {
693 	traverse_handle_t *th;
694 	uint64_t objset = dmu_objset_id(os);
695 	int advance = zdb_advance;
696 
697 	(void) printf("Indirect blocks:\n");
698 
699 	if (object == 0)
700 		advance |= ADVANCE_DATA;
701 
702 	th = traverse_init(dmu_objset_spa(os), zdb_indirect_cb, NULL, advance,
703 	    ZIO_FLAG_CANFAIL);
704 	th->th_noread = zdb_noread;
705 
706 	traverse_add_dnode(th, 0, -1ULL, objset, object);
707 
708 	while (traverse_more(th) == EAGAIN)
709 		continue;
710 
711 	(void) printf("\n");
712 
713 	traverse_fini(th);
714 }
715 
716 /*ARGSUSED*/
717 static void
718 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
719 {
720 	dsl_dir_phys_t *dd = data;
721 	time_t crtime;
722 	char used[6], compressed[6], uncompressed[6], quota[6], resv[6];
723 
724 	if (dd == NULL)
725 		return;
726 
727 	ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
728 
729 	crtime = dd->dd_creation_time;
730 	nicenum(dd->dd_used_bytes, used);
731 	nicenum(dd->dd_compressed_bytes, compressed);
732 	nicenum(dd->dd_uncompressed_bytes, uncompressed);
733 	nicenum(dd->dd_quota, quota);
734 	nicenum(dd->dd_reserved, resv);
735 
736 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
737 	(void) printf("\t\thead_dataset_obj = %llu\n",
738 	    (u_longlong_t)dd->dd_head_dataset_obj);
739 	(void) printf("\t\tparent_dir_obj = %llu\n",
740 	    (u_longlong_t)dd->dd_parent_obj);
741 	(void) printf("\t\torigin_obj = %llu\n",
742 	    (u_longlong_t)dd->dd_origin_obj);
743 	(void) printf("\t\tchild_dir_zapobj = %llu\n",
744 	    (u_longlong_t)dd->dd_child_dir_zapobj);
745 	(void) printf("\t\tused_bytes = %s\n", used);
746 	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
747 	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
748 	(void) printf("\t\tquota = %s\n", quota);
749 	(void) printf("\t\treserved = %s\n", resv);
750 	(void) printf("\t\tprops_zapobj = %llu\n",
751 	    (u_longlong_t)dd->dd_props_zapobj);
752 	(void) printf("\t\tdeleg_zapobj = %llu\n",
753 	    (u_longlong_t)dd->dd_deleg_zapobj);
754 }
755 
756 /*ARGSUSED*/
757 static void
758 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
759 {
760 	dsl_dataset_phys_t *ds = data;
761 	time_t crtime;
762 	char used[6], compressed[6], uncompressed[6], unique[6];
763 	char blkbuf[BP_SPRINTF_LEN];
764 
765 	if (ds == NULL)
766 		return;
767 
768 	ASSERT(size == sizeof (*ds));
769 	crtime = ds->ds_creation_time;
770 	nicenum(ds->ds_used_bytes, used);
771 	nicenum(ds->ds_compressed_bytes, compressed);
772 	nicenum(ds->ds_uncompressed_bytes, uncompressed);
773 	nicenum(ds->ds_unique_bytes, unique);
774 	sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &ds->ds_bp);
775 
776 	(void) printf("\t\tdataset_obj = %llu\n",
777 	    (u_longlong_t)ds->ds_dir_obj);
778 	(void) printf("\t\tprev_snap_obj = %llu\n",
779 	    (u_longlong_t)ds->ds_prev_snap_obj);
780 	(void) printf("\t\tprev_snap_txg = %llu\n",
781 	    (u_longlong_t)ds->ds_prev_snap_txg);
782 	(void) printf("\t\tnext_snap_obj = %llu\n",
783 	    (u_longlong_t)ds->ds_next_snap_obj);
784 	(void) printf("\t\tsnapnames_zapobj = %llu\n",
785 	    (u_longlong_t)ds->ds_snapnames_zapobj);
786 	(void) printf("\t\tnum_children = %llu\n",
787 	    (u_longlong_t)ds->ds_num_children);
788 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
789 	(void) printf("\t\tcreation_txg = %llu\n",
790 	    (u_longlong_t)ds->ds_creation_txg);
791 	(void) printf("\t\tdeadlist_obj = %llu\n",
792 	    (u_longlong_t)ds->ds_deadlist_obj);
793 	(void) printf("\t\tused_bytes = %s\n", used);
794 	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
795 	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
796 	(void) printf("\t\tunique = %s\n", unique);
797 	(void) printf("\t\tfsid_guid = %llu\n",
798 	    (u_longlong_t)ds->ds_fsid_guid);
799 	(void) printf("\t\tguid = %llu\n",
800 	    (u_longlong_t)ds->ds_guid);
801 	(void) printf("\t\tflags = %llx\n",
802 	    (u_longlong_t)ds->ds_flags);
803 	(void) printf("\t\tbp = %s\n", blkbuf);
804 }
805 
806 static void
807 dump_bplist(objset_t *mos, uint64_t object, char *name)
808 {
809 	bplist_t bpl = { 0 };
810 	blkptr_t blk, *bp = &blk;
811 	uint64_t itor = 0;
812 	char bytes[6];
813 	char comp[6];
814 	char uncomp[6];
815 
816 	if (dump_opt['d'] < 3)
817 		return;
818 
819 	mutex_init(&bpl.bpl_lock, NULL, MUTEX_DEFAULT, NULL);
820 	VERIFY(0 == bplist_open(&bpl, mos, object));
821 	if (bplist_empty(&bpl)) {
822 		bplist_close(&bpl);
823 		mutex_destroy(&bpl.bpl_lock);
824 		return;
825 	}
826 
827 	nicenum(bpl.bpl_phys->bpl_bytes, bytes);
828 	if (bpl.bpl_dbuf->db_size == sizeof (bplist_phys_t)) {
829 		nicenum(bpl.bpl_phys->bpl_comp, comp);
830 		nicenum(bpl.bpl_phys->bpl_uncomp, uncomp);
831 		(void) printf("\n    %s: %llu entries, %s (%s/%s comp)\n",
832 		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries,
833 		    bytes, comp, uncomp);
834 	} else {
835 		(void) printf("\n    %s: %llu entries, %s\n",
836 		    name, (u_longlong_t)bpl.bpl_phys->bpl_entries, bytes);
837 	}
838 
839 	if (dump_opt['d'] < 5) {
840 		bplist_close(&bpl);
841 		mutex_destroy(&bpl.bpl_lock);
842 		return;
843 	}
844 
845 	(void) printf("\n");
846 
847 	while (bplist_iterate(&bpl, &itor, bp) == 0) {
848 		char blkbuf[BP_SPRINTF_LEN];
849 
850 		ASSERT(bp->blk_birth != 0);
851 		sprintf_blkptr_compact(blkbuf, bp, dump_opt['d'] > 5 ? 1 : 0);
852 		(void) printf("\tItem %3llu: %s\n",
853 		    (u_longlong_t)itor - 1, blkbuf);
854 	}
855 
856 	bplist_close(&bpl);
857 	mutex_destroy(&bpl.bpl_lock);
858 }
859 
860 static avl_tree_t idx_tree;
861 static avl_tree_t domain_tree;
862 static boolean_t fuid_table_loaded;
863 
864 static void
865 fuid_table_destroy()
866 {
867 	if (fuid_table_loaded) {
868 		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
869 		fuid_table_loaded = B_FALSE;
870 	}
871 }
872 
873 /*
874  * print uid or gid information.
875  * For normal POSIX id just the id is printed in decimal format.
876  * For CIFS files with FUID the fuid is printed in hex followed by
877  * the doman-rid string.
878  */
879 static void
880 print_idstr(uint64_t id, const char *id_type)
881 {
882 	if (FUID_INDEX(id)) {
883 		char *domain;
884 
885 		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
886 		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
887 		    (u_longlong_t)id, domain, (int)FUID_RID(id));
888 	} else {
889 		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
890 	}
891 
892 }
893 
894 static void
895 dump_uidgid(objset_t *os, znode_phys_t *zp)
896 {
897 	uint32_t uid_idx, gid_idx;
898 
899 	uid_idx = FUID_INDEX(zp->zp_uid);
900 	gid_idx = FUID_INDEX(zp->zp_gid);
901 
902 	/* Load domain table, if not already loaded */
903 	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
904 		uint64_t fuid_obj;
905 
906 		/* first find the fuid object.  It lives in the master node */
907 		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
908 		    8, 1, &fuid_obj) == 0);
909 		(void) zfs_fuid_table_load(os, fuid_obj,
910 		    &idx_tree, &domain_tree);
911 		fuid_table_loaded = B_TRUE;
912 	}
913 
914 	print_idstr(zp->zp_uid, "uid");
915 	print_idstr(zp->zp_gid, "gid");
916 }
917 
918 /*ARGSUSED*/
919 static void
920 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
921 {
922 	znode_phys_t *zp = data;
923 	time_t z_crtime, z_atime, z_mtime, z_ctime;
924 	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
925 	int error;
926 
927 	ASSERT(size >= sizeof (znode_phys_t));
928 
929 	error = zfs_obj_to_path(os, object, path, sizeof (path));
930 	if (error != 0) {
931 		(void) snprintf(path, sizeof (path), "\?\?\?<object#%llu>",
932 		    (u_longlong_t)object);
933 	}
934 
935 	if (dump_opt['d'] < 3) {
936 		(void) printf("\t%s\n", path);
937 		return;
938 	}
939 
940 	z_crtime = (time_t)zp->zp_crtime[0];
941 	z_atime = (time_t)zp->zp_atime[0];
942 	z_mtime = (time_t)zp->zp_mtime[0];
943 	z_ctime = (time_t)zp->zp_ctime[0];
944 
945 	(void) printf("\tpath	%s\n", path);
946 	dump_uidgid(os, zp);
947 	(void) printf("\tatime	%s", ctime(&z_atime));
948 	(void) printf("\tmtime	%s", ctime(&z_mtime));
949 	(void) printf("\tctime	%s", ctime(&z_ctime));
950 	(void) printf("\tcrtime	%s", ctime(&z_crtime));
951 	(void) printf("\tgen	%llu\n", (u_longlong_t)zp->zp_gen);
952 	(void) printf("\tmode	%llo\n", (u_longlong_t)zp->zp_mode);
953 	(void) printf("\tsize	%llu\n", (u_longlong_t)zp->zp_size);
954 	(void) printf("\tparent	%llu\n", (u_longlong_t)zp->zp_parent);
955 	(void) printf("\tlinks	%llu\n", (u_longlong_t)zp->zp_links);
956 	(void) printf("\txattr	%llu\n", (u_longlong_t)zp->zp_xattr);
957 	(void) printf("\trdev	0x%016llx\n", (u_longlong_t)zp->zp_rdev);
958 }
959 
960 /*ARGSUSED*/
961 static void
962 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
963 {
964 }
965 
966 /*ARGSUSED*/
967 static void
968 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
969 {
970 }
971 
972 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES] = {
973 	dump_none,		/* unallocated			*/
974 	dump_zap,		/* object directory		*/
975 	dump_uint64,		/* object array			*/
976 	dump_none,		/* packed nvlist		*/
977 	dump_packed_nvlist,	/* packed nvlist size		*/
978 	dump_none,		/* bplist			*/
979 	dump_none,		/* bplist header		*/
980 	dump_none,		/* SPA space map header		*/
981 	dump_none,		/* SPA space map		*/
982 	dump_none,		/* ZIL intent log		*/
983 	dump_dnode,		/* DMU dnode			*/
984 	dump_dmu_objset,	/* DMU objset			*/
985 	dump_dsl_dir,		/* DSL directory		*/
986 	dump_zap,		/* DSL directory child map	*/
987 	dump_zap,		/* DSL dataset snap map		*/
988 	dump_zap,		/* DSL props			*/
989 	dump_dsl_dataset,	/* DSL dataset			*/
990 	dump_znode,		/* ZFS znode			*/
991 	dump_acl,		/* ZFS V0 ACL			*/
992 	dump_uint8,		/* ZFS plain file		*/
993 	dump_zpldir,		/* ZFS directory		*/
994 	dump_zap,		/* ZFS master node		*/
995 	dump_zap,		/* ZFS delete queue		*/
996 	dump_uint8,		/* zvol object			*/
997 	dump_zap,		/* zvol prop			*/
998 	dump_uint8,		/* other uint8[]		*/
999 	dump_uint64,		/* other uint64[]		*/
1000 	dump_zap,		/* other ZAP			*/
1001 	dump_zap,		/* persistent error log		*/
1002 	dump_uint8,		/* SPA history			*/
1003 	dump_uint64,		/* SPA history offsets		*/
1004 	dump_zap,		/* Pool properties		*/
1005 	dump_zap,		/* DSL permissions		*/
1006 	dump_acl,		/* ZFS ACL			*/
1007 	dump_uint8,		/* ZFS SYSACL			*/
1008 	dump_none,		/* FUID nvlist			*/
1009 	dump_packed_nvlist,	/* FUID nvlist size		*/
1010 };
1011 
1012 static void
1013 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1014 {
1015 	dmu_buf_t *db = NULL;
1016 	dmu_object_info_t doi;
1017 	dnode_t *dn;
1018 	void *bonus = NULL;
1019 	size_t bsize = 0;
1020 	char iblk[6], dblk[6], lsize[6], asize[6], bonus_size[6], segsize[6];
1021 	char aux[50];
1022 	int error;
1023 
1024 	if (*print_header) {
1025 		(void) printf("\n    Object  lvl   iblk   dblk  lsize"
1026 		    "  asize  type\n");
1027 		*print_header = 0;
1028 	}
1029 
1030 	if (object == 0) {
1031 		dn = os->os->os_meta_dnode;
1032 	} else {
1033 		error = dmu_bonus_hold(os, object, FTAG, &db);
1034 		if (error)
1035 			fatal("dmu_bonus_hold(%llu) failed, errno %u",
1036 			    object, error);
1037 		bonus = db->db_data;
1038 		bsize = db->db_size;
1039 		dn = ((dmu_buf_impl_t *)db)->db_dnode;
1040 	}
1041 	dmu_object_info_from_dnode(dn, &doi);
1042 
1043 	nicenum(doi.doi_metadata_block_size, iblk);
1044 	nicenum(doi.doi_data_block_size, dblk);
1045 	nicenum(doi.doi_data_block_size * (doi.doi_max_block_offset + 1),
1046 	    lsize);
1047 	nicenum(doi.doi_physical_blks << 9, asize);
1048 	nicenum(doi.doi_bonus_size, bonus_size);
1049 
1050 	aux[0] = '\0';
1051 
1052 	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1053 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1054 		    zio_checksum_table[doi.doi_checksum].ci_name);
1055 	}
1056 
1057 	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1058 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1059 		    zio_compress_table[doi.doi_compress].ci_name);
1060 	}
1061 
1062 	(void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %s%s\n",
1063 	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk, lsize,
1064 	    asize, dmu_ot[doi.doi_type].ot_name, aux);
1065 
1066 	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1067 		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %s\n",
1068 		    "", "", "", "", bonus_size, "bonus",
1069 		    dmu_ot[doi.doi_bonus_type].ot_name);
1070 	}
1071 
1072 	if (verbosity >= 4) {
1073 		object_viewer[doi.doi_bonus_type](os, object, bonus, bsize);
1074 		object_viewer[doi.doi_type](os, object, NULL, 0);
1075 		*print_header = 1;
1076 	}
1077 
1078 	if (verbosity >= 5)
1079 		dump_indirect(os, object, NULL, 0);
1080 
1081 	if (verbosity >= 5) {
1082 		/*
1083 		 * Report the list of segments that comprise the object.
1084 		 */
1085 		uint64_t start = 0;
1086 		uint64_t end;
1087 		uint64_t blkfill = 1;
1088 		int minlvl = 1;
1089 
1090 		if (dn->dn_type == DMU_OT_DNODE) {
1091 			minlvl = 0;
1092 			blkfill = DNODES_PER_BLOCK;
1093 		}
1094 
1095 		for (;;) {
1096 			error = dnode_next_offset(dn, B_FALSE, &start, minlvl,
1097 			    blkfill, 0);
1098 			if (error)
1099 				break;
1100 			end = start;
1101 			error = dnode_next_offset(dn, B_TRUE, &end, minlvl,
1102 			    blkfill, 0);
1103 			nicenum(end - start, segsize);
1104 			(void) printf("\t\tsegment [%016llx, %016llx)"
1105 			    " size %5s\n", (u_longlong_t)start,
1106 			    (u_longlong_t)end, segsize);
1107 			if (error)
1108 				break;
1109 			start = end;
1110 		}
1111 	}
1112 
1113 	if (db != NULL)
1114 		dmu_buf_rele(db, FTAG);
1115 }
1116 
1117 static char *objset_types[DMU_OST_NUMTYPES] = {
1118 	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1119 
1120 /*ARGSUSED*/
1121 static void
1122 dump_dir(objset_t *os)
1123 {
1124 	dmu_objset_stats_t dds;
1125 	uint64_t object, object_count;
1126 	uint64_t refdbytes, usedobjs, scratch;
1127 	char numbuf[8];
1128 	char blkbuf[BP_SPRINTF_LEN];
1129 	char osname[MAXNAMELEN];
1130 	char *type = "UNKNOWN";
1131 	int verbosity = dump_opt['d'];
1132 	int print_header = 1;
1133 	int i, error;
1134 
1135 	dmu_objset_fast_stat(os, &dds);
1136 
1137 	if (dds.dds_type < DMU_OST_NUMTYPES)
1138 		type = objset_types[dds.dds_type];
1139 
1140 	if (dds.dds_type == DMU_OST_META) {
1141 		dds.dds_creation_txg = TXG_INITIAL;
1142 		usedobjs = os->os->os_rootbp->blk_fill;
1143 		refdbytes =
1144 		    os->os->os_spa->spa_dsl_pool->dp_mos_dir->dd_used_bytes;
1145 	} else {
1146 		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
1147 	}
1148 
1149 	ASSERT3U(usedobjs, ==, os->os->os_rootbp->blk_fill);
1150 
1151 	nicenum(refdbytes, numbuf);
1152 
1153 	if (verbosity >= 4) {
1154 		(void) strcpy(blkbuf, ", rootbp ");
1155 		sprintf_blkptr(blkbuf + strlen(blkbuf),
1156 		    BP_SPRINTF_LEN - strlen(blkbuf), os->os->os_rootbp);
1157 	} else {
1158 		blkbuf[0] = '\0';
1159 	}
1160 
1161 	dmu_objset_name(os, osname);
1162 
1163 	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
1164 	    "%s, %llu objects%s\n",
1165 	    osname, type, (u_longlong_t)dmu_objset_id(os),
1166 	    (u_longlong_t)dds.dds_creation_txg,
1167 	    numbuf, (u_longlong_t)usedobjs, blkbuf);
1168 
1169 	dump_intent_log(dmu_objset_zil(os));
1170 
1171 	if (dmu_objset_ds(os) != NULL)
1172 		dump_bplist(dmu_objset_pool(os)->dp_meta_objset,
1173 		    dmu_objset_ds(os)->ds_phys->ds_deadlist_obj, "Deadlist");
1174 
1175 	if (verbosity < 2)
1176 		return;
1177 
1178 	if (zopt_objects != 0) {
1179 		for (i = 0; i < zopt_objects; i++)
1180 			dump_object(os, zopt_object[i], verbosity,
1181 			    &print_header);
1182 		(void) printf("\n");
1183 		return;
1184 	}
1185 
1186 	dump_object(os, 0, verbosity, &print_header);
1187 	object_count = 1;
1188 
1189 	object = 0;
1190 	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1191 		dump_object(os, object, verbosity, &print_header);
1192 		object_count++;
1193 	}
1194 
1195 	ASSERT3U(object_count, ==, usedobjs);
1196 
1197 	(void) printf("\n");
1198 
1199 	if (error != ESRCH)
1200 		fatal("dmu_object_next() = %d", error);
1201 }
1202 
1203 static void
1204 dump_uberblock(uberblock_t *ub)
1205 {
1206 	time_t timestamp = ub->ub_timestamp;
1207 
1208 	(void) printf("Uberblock\n\n");
1209 	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
1210 	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
1211 	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
1212 	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
1213 	(void) printf("\ttimestamp = %llu UTC = %s",
1214 	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
1215 	if (dump_opt['u'] >= 3) {
1216 		char blkbuf[BP_SPRINTF_LEN];
1217 		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &ub->ub_rootbp);
1218 		(void) printf("\trootbp = %s\n", blkbuf);
1219 	}
1220 	(void) printf("\n");
1221 }
1222 
1223 static void
1224 dump_config(const char *pool)
1225 {
1226 	spa_t *spa = NULL;
1227 
1228 	mutex_enter(&spa_namespace_lock);
1229 	while ((spa = spa_next(spa)) != NULL) {
1230 		if (pool == NULL)
1231 			(void) printf("%s\n", spa_name(spa));
1232 		if (pool == NULL || strcmp(pool, spa_name(spa)) == 0)
1233 			dump_nvlist(spa->spa_config, 4);
1234 	}
1235 	mutex_exit(&spa_namespace_lock);
1236 }
1237 
1238 static void
1239 dump_label(const char *dev)
1240 {
1241 	int fd;
1242 	vdev_label_t label;
1243 	char *buf = label.vl_vdev_phys.vp_nvlist;
1244 	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1245 	struct stat64 statbuf;
1246 	uint64_t psize;
1247 	int l;
1248 
1249 	if ((fd = open64(dev, O_RDONLY)) < 0) {
1250 		(void) printf("cannot open '%s': %s\n", dev, strerror(errno));
1251 		exit(1);
1252 	}
1253 
1254 	if (fstat64(fd, &statbuf) != 0) {
1255 		(void) printf("failed to stat '%s': %s\n", dev,
1256 		    strerror(errno));
1257 		exit(1);
1258 	}
1259 
1260 	psize = statbuf.st_size;
1261 	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
1262 
1263 	for (l = 0; l < VDEV_LABELS; l++) {
1264 
1265 		nvlist_t *config = NULL;
1266 
1267 		(void) printf("--------------------------------------------\n");
1268 		(void) printf("LABEL %d\n", l);
1269 		(void) printf("--------------------------------------------\n");
1270 
1271 		if (pread64(fd, &label, sizeof (label),
1272 		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
1273 			(void) printf("failed to read label %d\n", l);
1274 			continue;
1275 		}
1276 
1277 		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
1278 			(void) printf("failed to unpack label %d\n", l);
1279 			continue;
1280 		}
1281 		dump_nvlist(config, 4);
1282 		nvlist_free(config);
1283 	}
1284 }
1285 
1286 /*ARGSUSED*/
1287 static int
1288 dump_one_dir(char *dsname, void *arg)
1289 {
1290 	int error;
1291 	objset_t *os;
1292 
1293 	error = dmu_objset_open(dsname, DMU_OST_ANY,
1294 	    DS_MODE_STANDARD | DS_MODE_READONLY, &os);
1295 	if (error) {
1296 		(void) printf("Could not open %s\n", dsname);
1297 		return (0);
1298 	}
1299 	dump_dir(os);
1300 	dmu_objset_close(os);
1301 	fuid_table_destroy();
1302 	return (0);
1303 }
1304 
1305 static void
1306 zdb_space_map_load(spa_t *spa)
1307 {
1308 	vdev_t *rvd = spa->spa_root_vdev;
1309 	vdev_t *vd;
1310 	int c, m, error;
1311 
1312 	for (c = 0; c < rvd->vdev_children; c++) {
1313 		vd = rvd->vdev_child[c];
1314 		for (m = 0; m < vd->vdev_ms_count; m++) {
1315 			metaslab_t *msp = vd->vdev_ms[m];
1316 			mutex_enter(&msp->ms_lock);
1317 			error = space_map_load(&msp->ms_allocmap[0], NULL,
1318 			    SM_ALLOC, &msp->ms_smo, spa->spa_meta_objset);
1319 			mutex_exit(&msp->ms_lock);
1320 			if (error)
1321 				fatal("%s bad space map #%d, error %d",
1322 				    spa->spa_name, c, error);
1323 		}
1324 	}
1325 }
1326 
1327 static int
1328 zdb_space_map_claim(spa_t *spa, blkptr_t *bp, zbookmark_t *zb)
1329 {
1330 	dva_t *dva = bp->blk_dva;
1331 	vdev_t *vd;
1332 	metaslab_t *msp;
1333 	space_map_t *allocmap, *freemap;
1334 	int error;
1335 	int d;
1336 	blkptr_t blk = *bp;
1337 
1338 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1339 		uint64_t vdev = DVA_GET_VDEV(&dva[d]);
1340 		uint64_t offset = DVA_GET_OFFSET(&dva[d]);
1341 		uint64_t size = DVA_GET_ASIZE(&dva[d]);
1342 
1343 		if ((vd = vdev_lookup_top(spa, vdev)) == NULL)
1344 			return (ENXIO);
1345 
1346 		if ((offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
1347 			return (ENXIO);
1348 
1349 		msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
1350 		allocmap = &msp->ms_allocmap[0];
1351 		freemap = &msp->ms_freemap[0];
1352 
1353 		/* Prepare our copy of the bp in case we need to read GBHs */
1354 		if (DVA_GET_GANG(&dva[d])) {
1355 			size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
1356 			DVA_SET_ASIZE(&blk.blk_dva[d], size);
1357 			DVA_SET_GANG(&blk.blk_dva[d], 0);
1358 		}
1359 
1360 		mutex_enter(&msp->ms_lock);
1361 		if (space_map_contains(freemap, offset, size)) {
1362 			mutex_exit(&msp->ms_lock);
1363 			return (EAGAIN);	/* allocated more than once */
1364 		}
1365 
1366 		if (!space_map_contains(allocmap, offset, size)) {
1367 			mutex_exit(&msp->ms_lock);
1368 			return (ESTALE);	/* not allocated at all */
1369 		}
1370 
1371 		space_map_remove(allocmap, offset, size);
1372 		space_map_add(freemap, offset, size);
1373 
1374 		mutex_exit(&msp->ms_lock);
1375 	}
1376 
1377 	if (BP_IS_GANG(bp)) {
1378 		zio_gbh_phys_t gbh;
1379 		int g;
1380 
1381 		/* LINTED - compile time assert */
1382 		ASSERT(sizeof (zio_gbh_phys_t) == SPA_GANGBLOCKSIZE);
1383 
1384 		BP_SET_CHECKSUM(&blk, ZIO_CHECKSUM_GANG_HEADER);
1385 		BP_SET_PSIZE(&blk, SPA_GANGBLOCKSIZE);
1386 		BP_SET_LSIZE(&blk, SPA_GANGBLOCKSIZE);
1387 		BP_SET_COMPRESS(&blk, ZIO_COMPRESS_OFF);
1388 		error = zio_wait(zio_read(NULL, spa, &blk, &gbh,
1389 		    SPA_GANGBLOCKSIZE, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
1390 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_CONFIG_HELD, zb));
1391 		if (error)
1392 			return (error);
1393 		if (BP_SHOULD_BYTESWAP(&blk))
1394 			byteswap_uint64_array(&gbh, SPA_GANGBLOCKSIZE);
1395 		for (g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1396 			if (BP_IS_HOLE(&gbh.zg_blkptr[g]))
1397 				break;
1398 			error = zdb_space_map_claim(spa, &gbh.zg_blkptr[g], zb);
1399 			if (error)
1400 				return (error);
1401 		}
1402 	}
1403 
1404 	return (0);
1405 }
1406 
1407 static void
1408 zdb_leak(space_map_t *sm, uint64_t start, uint64_t size)
1409 {
1410 	metaslab_t *msp;
1411 
1412 	/* LINTED */
1413 	msp = (metaslab_t *)((char *)sm - offsetof(metaslab_t, ms_allocmap[0]));
1414 
1415 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
1416 	    (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
1417 	    (u_longlong_t)start,
1418 	    (u_longlong_t)size);
1419 }
1420 
1421 static void
1422 zdb_space_map_unload(spa_t *spa)
1423 {
1424 	vdev_t *rvd = spa->spa_root_vdev;
1425 	vdev_t *vd;
1426 	int c, m;
1427 
1428 	for (c = 0; c < rvd->vdev_children; c++) {
1429 		vd = rvd->vdev_child[c];
1430 		for (m = 0; m < vd->vdev_ms_count; m++) {
1431 			metaslab_t *msp = vd->vdev_ms[m];
1432 			mutex_enter(&msp->ms_lock);
1433 			space_map_vacate(&msp->ms_allocmap[0], zdb_leak,
1434 			    &msp->ms_allocmap[0]);
1435 			space_map_unload(&msp->ms_allocmap[0]);
1436 			space_map_vacate(&msp->ms_freemap[0], NULL, NULL);
1437 			mutex_exit(&msp->ms_lock);
1438 		}
1439 	}
1440 }
1441 
1442 static void
1443 zdb_refresh_ubsync(spa_t *spa)
1444 {
1445 	uberblock_t ub = { 0 };
1446 	vdev_t *rvd = spa->spa_root_vdev;
1447 	zio_t *zio;
1448 
1449 	/*
1450 	 * Reload the uberblock.
1451 	 */
1452 	zio = zio_root(spa, NULL, NULL,
1453 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
1454 	vdev_uberblock_load(zio, rvd, &ub);
1455 	(void) zio_wait(zio);
1456 
1457 	if (ub.ub_txg != 0)
1458 		spa->spa_ubsync = ub;
1459 }
1460 
1461 /*
1462  * Verify that the sum of the sizes of all blocks in the pool adds up
1463  * to the SPA's sa_alloc total.
1464  */
1465 typedef struct zdb_blkstats {
1466 	uint64_t	zb_asize;
1467 	uint64_t	zb_lsize;
1468 	uint64_t	zb_psize;
1469 	uint64_t	zb_count;
1470 } zdb_blkstats_t;
1471 
1472 #define	DMU_OT_DEFERRED	DMU_OT_NONE
1473 #define	DMU_OT_TOTAL	DMU_OT_NUMTYPES
1474 
1475 #define	ZB_TOTAL	ZB_MAXLEVEL
1476 
1477 typedef struct zdb_cb {
1478 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][DMU_OT_TOTAL + 1];
1479 	uint64_t	zcb_errors[256];
1480 	traverse_blk_cache_t *zcb_cache;
1481 	int		zcb_readfails;
1482 	int		zcb_haderrors;
1483 } zdb_cb_t;
1484 
1485 static void
1486 zdb_count_block(spa_t *spa, zdb_cb_t *zcb, blkptr_t *bp, int type)
1487 {
1488 	int i, error;
1489 
1490 	for (i = 0; i < 4; i++) {
1491 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
1492 		int t = (i & 1) ? type : DMU_OT_TOTAL;
1493 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
1494 
1495 		zb->zb_asize += BP_GET_ASIZE(bp);
1496 		zb->zb_lsize += BP_GET_LSIZE(bp);
1497 		zb->zb_psize += BP_GET_PSIZE(bp);
1498 		zb->zb_count++;
1499 	}
1500 
1501 	if (dump_opt['S']) {
1502 		boolean_t print_sig;
1503 
1504 		print_sig  = !zdb_sig_user_data || (BP_GET_LEVEL(bp) == 0 &&
1505 		    BP_GET_TYPE(bp) == DMU_OT_PLAIN_FILE_CONTENTS);
1506 
1507 		if (BP_GET_CHECKSUM(bp) < zdb_sig_cksumalg)
1508 			print_sig = B_FALSE;
1509 
1510 		if (print_sig) {
1511 			(void) printf("%llu\t%lld\t%lld\t%s\t%s\t%s\t"
1512 			    "%llx:%llx:%llx:%llx\n",
1513 			    (u_longlong_t)BP_GET_LEVEL(bp),
1514 			    (longlong_t)BP_GET_PSIZE(bp),
1515 			    (longlong_t)BP_GET_NDVAS(bp),
1516 			    dmu_ot[BP_GET_TYPE(bp)].ot_name,
1517 			    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
1518 			    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name,
1519 			    (u_longlong_t)bp->blk_cksum.zc_word[0],
1520 			    (u_longlong_t)bp->blk_cksum.zc_word[1],
1521 			    (u_longlong_t)bp->blk_cksum.zc_word[2],
1522 			    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1523 		}
1524 	}
1525 
1526 	if (dump_opt['L'])
1527 		return;
1528 
1529 	error = zdb_space_map_claim(spa, bp, &zcb->zcb_cache->bc_bookmark);
1530 
1531 	if (error == 0)
1532 		return;
1533 
1534 	if (error == EAGAIN)
1535 		(void) fatal("double-allocation, bp=%p", bp);
1536 
1537 	if (error == ESTALE)
1538 		(void) fatal("reference to freed block, bp=%p", bp);
1539 
1540 	(void) fatal("fatal error %d in bp %p", error, bp);
1541 }
1542 
1543 static int
1544 zdb_blkptr_cb(traverse_blk_cache_t *bc, spa_t *spa, void *arg)
1545 {
1546 	zbookmark_t *zb = &bc->bc_bookmark;
1547 	zdb_cb_t *zcb = arg;
1548 	blkptr_t *bp = &bc->bc_blkptr;
1549 	dmu_object_type_t type = BP_GET_TYPE(bp);
1550 	char blkbuf[BP_SPRINTF_LEN];
1551 	int error = 0;
1552 
1553 	if (bc->bc_errno) {
1554 		if (zcb->zcb_readfails++ < 10 && dump_opt['L']) {
1555 			zdb_refresh_ubsync(spa);
1556 			error = EAGAIN;
1557 		} else {
1558 			zcb->zcb_haderrors = 1;
1559 			zcb->zcb_errors[bc->bc_errno]++;
1560 			error = ERESTART;
1561 		}
1562 
1563 		if (dump_opt['b'] >= 3 || (dump_opt['b'] >= 2 && bc->bc_errno))
1564 			sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1565 		else
1566 			blkbuf[0] = '\0';
1567 
1568 		if (!dump_opt['S']) {
1569 			(void) printf("zdb_blkptr_cb: Got error %d reading "
1570 			    "<%llu, %llu, %lld, %llx> %s -- %s\n",
1571 			    bc->bc_errno,
1572 			    (u_longlong_t)zb->zb_objset,
1573 			    (u_longlong_t)zb->zb_object,
1574 			    (u_longlong_t)zb->zb_level,
1575 			    (u_longlong_t)zb->zb_blkid,
1576 			    blkbuf,
1577 			    error == EAGAIN ? "retrying" : "skipping");
1578 		}
1579 
1580 		return (error);
1581 	}
1582 
1583 	zcb->zcb_readfails = 0;
1584 
1585 	ASSERT(!BP_IS_HOLE(bp));
1586 
1587 	if (dump_opt['b'] >= 4) {
1588 		sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, bp);
1589 		(void) printf("objset %llu object %llu offset 0x%llx %s\n",
1590 		    (u_longlong_t)zb->zb_objset,
1591 		    (u_longlong_t)zb->zb_object,
1592 		    (u_longlong_t)blkid2offset(bc->bc_dnode,
1593 		    zb->zb_level, zb->zb_blkid), blkbuf);
1594 	}
1595 
1596 	zdb_count_block(spa, zcb, bp, type);
1597 
1598 	return (0);
1599 }
1600 
1601 static int
1602 dump_block_stats(spa_t *spa)
1603 {
1604 	traverse_handle_t *th;
1605 	zdb_cb_t zcb = { 0 };
1606 	traverse_blk_cache_t dummy_cache = { 0 };
1607 	zdb_blkstats_t *zb, *tzb;
1608 	uint64_t alloc, space, logalloc;
1609 	vdev_t *rvd = spa->spa_root_vdev;
1610 	int leaks = 0;
1611 	int advance = zdb_advance;
1612 	int c, e, flags;
1613 
1614 	zcb.zcb_cache = &dummy_cache;
1615 
1616 	if (dump_opt['c'] || dump_opt['S'])
1617 		advance |= ADVANCE_DATA;
1618 
1619 	advance |= ADVANCE_PRUNE | ADVANCE_ZIL;
1620 
1621 	if (!dump_opt['S']) {
1622 		(void) printf("\nTraversing all blocks to %sverify"
1623 		    " nothing leaked ...\n",
1624 		    dump_opt['c'] ? "verify checksums and " : "");
1625 	}
1626 
1627 	/*
1628 	 * Load all space maps.  As we traverse the pool, if we find a block
1629 	 * that's not in its space map, that indicates a double-allocation,
1630 	 * reference to a freed block, or an unclaimed block.  Otherwise we
1631 	 * remove the block from the space map.  If the space maps are not
1632 	 * empty when we're done, that indicates leaked blocks.
1633 	 */
1634 	if (!dump_opt['L'])
1635 		zdb_space_map_load(spa);
1636 
1637 	/*
1638 	 * If there's a deferred-free bplist, process that first.
1639 	 */
1640 	if (spa->spa_sync_bplist_obj != 0) {
1641 		bplist_t *bpl = &spa->spa_sync_bplist;
1642 		blkptr_t blk;
1643 		uint64_t itor = 0;
1644 
1645 		VERIFY(0 == bplist_open(bpl, spa->spa_meta_objset,
1646 		    spa->spa_sync_bplist_obj));
1647 
1648 		while (bplist_iterate(bpl, &itor, &blk) == 0) {
1649 			if (dump_opt['b'] >= 4) {
1650 				char blkbuf[BP_SPRINTF_LEN];
1651 				sprintf_blkptr(blkbuf, BP_SPRINTF_LEN, &blk);
1652 				(void) printf("[%s] %s\n",
1653 				    "deferred free", blkbuf);
1654 			}
1655 			zdb_count_block(spa, &zcb, &blk, DMU_OT_DEFERRED);
1656 		}
1657 
1658 		bplist_close(bpl);
1659 	}
1660 
1661 	/*
1662 	 * Now traverse the pool.  If we're reading all data to verify
1663 	 * checksums, do a scrubbing read so that we validate all copies.
1664 	 */
1665 	flags = ZIO_FLAG_CANFAIL;
1666 	if (advance & ADVANCE_DATA)
1667 		flags |= ZIO_FLAG_SCRUB;
1668 	th = traverse_init(spa, zdb_blkptr_cb, &zcb, advance, flags);
1669 	th->th_noread = zdb_noread;
1670 
1671 	traverse_add_pool(th, 0, spa_first_txg(spa) + TXG_CONCURRENT_STATES);
1672 
1673 	while (traverse_more(th) == EAGAIN)
1674 		continue;
1675 
1676 	traverse_fini(th);
1677 
1678 	if (zcb.zcb_haderrors && !dump_opt['S']) {
1679 		(void) printf("\nError counts:\n\n");
1680 		(void) printf("\t%5s  %s\n", "errno", "count");
1681 		for (e = 0; e < 256; e++) {
1682 			if (zcb.zcb_errors[e] != 0) {
1683 				(void) printf("\t%5d  %llu\n",
1684 				    e, (u_longlong_t)zcb.zcb_errors[e]);
1685 			}
1686 		}
1687 	}
1688 
1689 	/*
1690 	 * Report any leaked segments.
1691 	 */
1692 	if (!dump_opt['L'])
1693 		zdb_space_map_unload(spa);
1694 
1695 	/*
1696 	 * If we're interested in printing out the blkptr signatures,
1697 	 * return now as we don't print out anything else (including
1698 	 * errors and leaks).
1699 	 */
1700 	if (dump_opt['S'])
1701 		return (zcb.zcb_haderrors ? 3 : 0);
1702 
1703 	if (dump_opt['L'])
1704 		(void) printf("\n\n *** Live pool traversal; "
1705 		    "block counts are only approximate ***\n\n");
1706 
1707 	alloc = spa_get_alloc(spa);
1708 	space = spa_get_space(spa);
1709 
1710 	/*
1711 	 * Log blocks allocated from a separate log device don't count
1712 	 * as part of the normal pool space; factor them in here.
1713 	 */
1714 	logalloc = 0;
1715 
1716 	for (c = 0; c < rvd->vdev_children; c++)
1717 		if (rvd->vdev_child[c]->vdev_islog)
1718 			logalloc += rvd->vdev_child[c]->vdev_stat.vs_alloc;
1719 
1720 	tzb = &zcb.zcb_type[ZB_TOTAL][DMU_OT_TOTAL];
1721 
1722 	if (tzb->zb_asize == alloc + logalloc) {
1723 		(void) printf("\n\tNo leaks (block sum matches space"
1724 		    " maps exactly)\n");
1725 	} else {
1726 		(void) printf("block traversal size %llu != alloc %llu "
1727 		    "(leaked %lld)\n",
1728 		    (u_longlong_t)tzb->zb_asize,
1729 		    (u_longlong_t)alloc + logalloc,
1730 		    (u_longlong_t)(alloc + logalloc - tzb->zb_asize));
1731 		leaks = 1;
1732 	}
1733 
1734 	if (tzb->zb_count == 0)
1735 		return (2);
1736 
1737 	(void) printf("\n");
1738 	(void) printf("\tbp count:      %10llu\n",
1739 	    (u_longlong_t)tzb->zb_count);
1740 	(void) printf("\tbp logical:    %10llu\t avg: %6llu\n",
1741 	    (u_longlong_t)tzb->zb_lsize,
1742 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
1743 	(void) printf("\tbp physical:   %10llu\t avg:"
1744 	    " %6llu\tcompression: %6.2f\n",
1745 	    (u_longlong_t)tzb->zb_psize,
1746 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
1747 	    (double)tzb->zb_lsize / tzb->zb_psize);
1748 	(void) printf("\tbp allocated:  %10llu\t avg:"
1749 	    " %6llu\tcompression: %6.2f\n",
1750 	    (u_longlong_t)tzb->zb_asize,
1751 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
1752 	    (double)tzb->zb_lsize / tzb->zb_asize);
1753 	(void) printf("\tSPA allocated: %10llu\tused: %5.2f%%\n",
1754 	    (u_longlong_t)alloc, 100.0 * alloc / space);
1755 
1756 	if (dump_opt['b'] >= 2) {
1757 		int l, t, level;
1758 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
1759 		    "\t  avg\t comp\t%%Total\tType\n");
1760 
1761 		for (t = 0; t <= DMU_OT_NUMTYPES; t++) {
1762 			char csize[6], lsize[6], psize[6], asize[6], avg[6];
1763 			char *typename;
1764 
1765 			typename = t == DMU_OT_DEFERRED ? "deferred free" :
1766 			    t == DMU_OT_TOTAL ? "Total" : dmu_ot[t].ot_name;
1767 
1768 			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
1769 				(void) printf("%6s\t%5s\t%5s\t%5s"
1770 				    "\t%5s\t%5s\t%6s\t%s\n",
1771 				    "-",
1772 				    "-",
1773 				    "-",
1774 				    "-",
1775 				    "-",
1776 				    "-",
1777 				    "-",
1778 				    typename);
1779 				continue;
1780 			}
1781 
1782 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
1783 				level = (l == -1 ? ZB_TOTAL : l);
1784 				zb = &zcb.zcb_type[level][t];
1785 
1786 				if (zb->zb_asize == 0)
1787 					continue;
1788 
1789 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
1790 					continue;
1791 
1792 				if (level == 0 && zb->zb_asize ==
1793 				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
1794 					continue;
1795 
1796 				nicenum(zb->zb_count, csize);
1797 				nicenum(zb->zb_lsize, lsize);
1798 				nicenum(zb->zb_psize, psize);
1799 				nicenum(zb->zb_asize, asize);
1800 				nicenum(zb->zb_asize / zb->zb_count, avg);
1801 
1802 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
1803 				    "\t%5.2f\t%6.2f\t",
1804 				    csize, lsize, psize, asize, avg,
1805 				    (double)zb->zb_lsize / zb->zb_psize,
1806 				    100.0 * zb->zb_asize / tzb->zb_asize);
1807 
1808 				if (level == ZB_TOTAL)
1809 					(void) printf("%s\n", typename);
1810 				else
1811 					(void) printf("    L%d %s\n",
1812 					    level, typename);
1813 			}
1814 		}
1815 	}
1816 
1817 	(void) printf("\n");
1818 
1819 	if (leaks)
1820 		return (2);
1821 
1822 	if (zcb.zcb_haderrors)
1823 		return (3);
1824 
1825 	return (0);
1826 }
1827 
1828 static void
1829 dump_zpool(spa_t *spa)
1830 {
1831 	dsl_pool_t *dp = spa_get_dsl(spa);
1832 	int rc = 0;
1833 
1834 	spa_config_enter(spa, RW_READER, FTAG);
1835 
1836 	if (dump_opt['u'])
1837 		dump_uberblock(&spa->spa_uberblock);
1838 
1839 	if (dump_opt['d'] || dump_opt['i']) {
1840 		dump_dir(dp->dp_meta_objset);
1841 		if (dump_opt['d'] >= 3) {
1842 			dump_bplist(dp->dp_meta_objset,
1843 			    spa->spa_sync_bplist_obj, "Deferred frees");
1844 			dump_dtl(spa->spa_root_vdev, 0);
1845 			dump_metaslabs(spa);
1846 		}
1847 		(void) dmu_objset_find(spa->spa_name, dump_one_dir, NULL,
1848 		    DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
1849 	}
1850 
1851 	if (dump_opt['b'] || dump_opt['c'] || dump_opt['S'])
1852 		rc = dump_block_stats(spa);
1853 
1854 	if (dump_opt['s'])
1855 		show_pool_stats(spa);
1856 
1857 	spa_config_exit(spa, FTAG);
1858 
1859 	if (rc != 0)
1860 		exit(rc);
1861 }
1862 
1863 #define	ZDB_FLAG_CHECKSUM	0x0001
1864 #define	ZDB_FLAG_DECOMPRESS	0x0002
1865 #define	ZDB_FLAG_BSWAP		0x0004
1866 #define	ZDB_FLAG_GBH		0x0008
1867 #define	ZDB_FLAG_INDIRECT	0x0010
1868 #define	ZDB_FLAG_PHYS		0x0020
1869 #define	ZDB_FLAG_RAW		0x0040
1870 #define	ZDB_FLAG_PRINT_BLKPTR	0x0080
1871 
1872 int flagbits[256];
1873 
1874 static void
1875 zdb_print_blkptr(blkptr_t *bp, int flags)
1876 {
1877 	dva_t *dva = bp->blk_dva;
1878 	int d;
1879 
1880 	if (flags & ZDB_FLAG_BSWAP)
1881 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
1882 	/*
1883 	 * Super-ick warning:  This code is also duplicated in
1884 	 * cmd/mdb/common/modules/zfs/zfs.c .  Yeah, I hate code
1885 	 * replication, too.
1886 	 */
1887 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
1888 		(void) printf("\tDVA[%d]: vdev_id %lld / %llx\n", d,
1889 		    (longlong_t)DVA_GET_VDEV(&dva[d]),
1890 		    (longlong_t)DVA_GET_OFFSET(&dva[d]));
1891 		(void) printf("\tDVA[%d]:       GANG: %-5s  GRID:  %04llx\t"
1892 		    "ASIZE: %llx\n", d,
1893 		    DVA_GET_GANG(&dva[d]) ? "TRUE" : "FALSE",
1894 		    (longlong_t)DVA_GET_GRID(&dva[d]),
1895 		    (longlong_t)DVA_GET_ASIZE(&dva[d]));
1896 		(void) printf("\tDVA[%d]: :%llu:%llx:%llx:%s%s%s%s\n", d,
1897 		    (u_longlong_t)DVA_GET_VDEV(&dva[d]),
1898 		    (longlong_t)DVA_GET_OFFSET(&dva[d]),
1899 		    (longlong_t)BP_GET_PSIZE(bp),
1900 		    BP_SHOULD_BYTESWAP(bp) ? "e" : "",
1901 		    !DVA_GET_GANG(&dva[d]) && BP_GET_LEVEL(bp) != 0 ?
1902 		    "d" : "",
1903 		    DVA_GET_GANG(&dva[d]) ? "g" : "",
1904 		    BP_GET_COMPRESS(bp) != 0 ? "d" : "");
1905 	}
1906 	(void) printf("\tLSIZE:  %-16llx\t\tPSIZE: %llx\n",
1907 	    (longlong_t)BP_GET_LSIZE(bp), (longlong_t)BP_GET_PSIZE(bp));
1908 	(void) printf("\tENDIAN: %6s\t\t\t\t\tTYPE:  %s\n",
1909 	    BP_GET_BYTEORDER(bp) ? "LITTLE" : "BIG",
1910 	    dmu_ot[BP_GET_TYPE(bp)].ot_name);
1911 	(void) printf("\tBIRTH:  %-16llx   LEVEL: %-2llu\tFILL:  %llx\n",
1912 	    (u_longlong_t)bp->blk_birth, (u_longlong_t)BP_GET_LEVEL(bp),
1913 	    (u_longlong_t)bp->blk_fill);
1914 	(void) printf("\tCKFUNC: %-16s\t\tCOMP:  %s\n",
1915 	    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
1916 	    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name);
1917 	(void) printf("\tCKSUM:  %llx:%llx:%llx:%llx\n",
1918 	    (u_longlong_t)bp->blk_cksum.zc_word[0],
1919 	    (u_longlong_t)bp->blk_cksum.zc_word[1],
1920 	    (u_longlong_t)bp->blk_cksum.zc_word[2],
1921 	    (u_longlong_t)bp->blk_cksum.zc_word[3]);
1922 }
1923 
1924 static void
1925 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
1926 {
1927 	int i;
1928 
1929 	for (i = 0; i < nbps; i++)
1930 		zdb_print_blkptr(&bp[i], flags);
1931 }
1932 
1933 static void
1934 zdb_dump_gbh(void *buf, int flags)
1935 {
1936 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
1937 }
1938 
1939 static void
1940 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
1941 {
1942 	if (flags & ZDB_FLAG_BSWAP)
1943 		byteswap_uint64_array(buf, size);
1944 	(void) write(2, buf, size);
1945 }
1946 
1947 static void
1948 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
1949 {
1950 	uint64_t *d = (uint64_t *)buf;
1951 	int nwords = size / sizeof (uint64_t);
1952 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
1953 	int i, j;
1954 	char *hdr, *c;
1955 
1956 
1957 	if (do_bswap)
1958 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
1959 	else
1960 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
1961 
1962 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
1963 
1964 	for (i = 0; i < nwords; i += 2) {
1965 		(void) printf("%06llx:  %016llx  %016llx  ",
1966 		    (u_longlong_t)(i * sizeof (uint64_t)),
1967 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
1968 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
1969 
1970 		c = (char *)&d[i];
1971 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
1972 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
1973 		(void) printf("\n");
1974 	}
1975 }
1976 
1977 /*
1978  * There are two acceptable formats:
1979  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
1980  *	child[.child]*    - For example: 0.1.1
1981  *
1982  * The second form can be used to specify arbitrary vdevs anywhere
1983  * in the heirarchy.  For example, in a pool with a mirror of
1984  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
1985  */
1986 static vdev_t *
1987 zdb_vdev_lookup(vdev_t *vdev, char *path)
1988 {
1989 	char *s, *p, *q;
1990 	int i;
1991 
1992 	if (vdev == NULL)
1993 		return (NULL);
1994 
1995 	/* First, assume the x.x.x.x format */
1996 	i = (int)strtoul(path, &s, 10);
1997 	if (s == path || (s && *s != '.' && *s != '\0'))
1998 		goto name;
1999 	if (i < 0 || i >= vdev->vdev_children)
2000 		return (NULL);
2001 
2002 	vdev = vdev->vdev_child[i];
2003 	if (*s == '\0')
2004 		return (vdev);
2005 	return (zdb_vdev_lookup(vdev, s+1));
2006 
2007 name:
2008 	for (i = 0; i < vdev->vdev_children; i++) {
2009 		vdev_t *vc = vdev->vdev_child[i];
2010 
2011 		if (vc->vdev_path == NULL) {
2012 			vc = zdb_vdev_lookup(vc, path);
2013 			if (vc == NULL)
2014 				continue;
2015 			else
2016 				return (vc);
2017 		}
2018 
2019 		p = strrchr(vc->vdev_path, '/');
2020 		p = p ? p + 1 : vc->vdev_path;
2021 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2022 
2023 		if (strcmp(vc->vdev_path, path) == 0)
2024 			return (vc);
2025 		if (strcmp(p, path) == 0)
2026 			return (vc);
2027 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2028 			return (vc);
2029 	}
2030 
2031 	return (NULL);
2032 }
2033 
2034 /*
2035  * Read a block from a pool and print it out.  The syntax of the
2036  * block descriptor is:
2037  *
2038  *	pool:vdev_specifier:offset:size[:flags]
2039  *
2040  *	pool           - The name of the pool you wish to read from
2041  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2042  *	offset         - offset, in hex, in bytes
2043  *	size           - Amount of data to read, in hex, in bytes
2044  *	flags          - A string of characters specifying options
2045  *		 b: Decode a blkptr at given offset within block
2046  *		*c: Calculate and display checksums
2047  *		*d: Decompress data before dumping
2048  *		 e: Byteswap data before dumping
2049  *		*g: Display data as a gang block header
2050  *		*i: Display as an indirect block
2051  *		 p: Do I/O to physical offset
2052  *		 r: Dump raw data to stdout
2053  *
2054  *              * = not yet implemented
2055  */
2056 static void
2057 zdb_read_block(char *thing, spa_t **spap)
2058 {
2059 	spa_t *spa = *spap;
2060 	int flags = 0;
2061 	uint64_t offset = 0, size = 0, blkptr_offset = 0;
2062 	zio_t *zio;
2063 	vdev_t *vd;
2064 	void *buf;
2065 	char *s, *p, *dup, *spa_name, *vdev, *flagstr;
2066 	int i, error, zio_flags;
2067 
2068 	dup = strdup(thing);
2069 	s = strtok(dup, ":");
2070 	spa_name = s ? s : "";
2071 	s = strtok(NULL, ":");
2072 	vdev = s ? s : "";
2073 	s = strtok(NULL, ":");
2074 	offset = strtoull(s ? s : "", NULL, 16);
2075 	s = strtok(NULL, ":");
2076 	size = strtoull(s ? s : "", NULL, 16);
2077 	s = strtok(NULL, ":");
2078 	flagstr = s ? s : "";
2079 
2080 	s = NULL;
2081 	if (size == 0)
2082 		s = "size must not be zero";
2083 	if (!IS_P2ALIGNED(size, DEV_BSIZE))
2084 		s = "size must be a multiple of sector size";
2085 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
2086 		s = "offset must be a multiple of sector size";
2087 	if (s) {
2088 		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
2089 		free(dup);
2090 		return;
2091 	}
2092 
2093 	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
2094 		for (i = 0; flagstr[i]; i++) {
2095 			int bit = flagbits[(uchar_t)flagstr[i]];
2096 
2097 			if (bit == 0) {
2098 				(void) printf("***Invalid flag: %c\n",
2099 				    flagstr[i]);
2100 				continue;
2101 			}
2102 			flags |= bit;
2103 
2104 			/* If it's not something with an argument, keep going */
2105 			if ((bit & (ZDB_FLAG_CHECKSUM | ZDB_FLAG_DECOMPRESS |
2106 			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
2107 				continue;
2108 
2109 			p = &flagstr[i + 1];
2110 			if (bit == ZDB_FLAG_PRINT_BLKPTR)
2111 				blkptr_offset = strtoull(p, &p, 16);
2112 			if (*p != ':' && *p != '\0') {
2113 				(void) printf("***Invalid flag arg: '%s'\n", s);
2114 				free(dup);
2115 				return;
2116 			}
2117 		}
2118 	}
2119 
2120 	if (spa == NULL || spa->spa_name == NULL ||
2121 	    strcmp(spa->spa_name, spa_name)) {
2122 		if (spa && spa->spa_name)
2123 			spa_close(spa, (void *)zdb_read_block);
2124 		error = spa_open(spa_name, spap, (void *)zdb_read_block);
2125 		if (error)
2126 			fatal("Failed to open pool '%s': %s",
2127 			    spa_name, strerror(error));
2128 		spa = *spap;
2129 	}
2130 
2131 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
2132 	if (vd == NULL) {
2133 		(void) printf("***Invalid vdev: %s\n", vdev);
2134 		free(dup);
2135 		return;
2136 	} else {
2137 		if (vd->vdev_path)
2138 			(void) printf("Found vdev: %s\n", vd->vdev_path);
2139 		else
2140 			(void) printf("Found vdev type: %s\n",
2141 			    vd->vdev_ops->vdev_op_type);
2142 	}
2143 
2144 	buf = umem_alloc(size, UMEM_NOFAIL);
2145 
2146 	zio_flags = ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
2147 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY | ZIO_FLAG_NOBOOKMARK;
2148 
2149 	if (flags & ZDB_FLAG_PHYS)
2150 		zio_flags |= ZIO_FLAG_PHYSICAL;
2151 
2152 	zio = zio_root(spa, NULL, NULL, 0);
2153 	/* XXX todo - cons up a BP so RAID-Z will be happy */
2154 	zio_nowait(zio_vdev_child_io(zio, NULL, vd, offset, buf, size,
2155 	    ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ, zio_flags, NULL, NULL));
2156 	error = zio_wait(zio);
2157 
2158 	if (error) {
2159 		(void) printf("Read of %s failed, error: %d\n", thing, error);
2160 		goto out;
2161 	}
2162 
2163 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
2164 		zdb_print_blkptr((blkptr_t *)(void *)
2165 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
2166 	else if (flags & ZDB_FLAG_RAW)
2167 		zdb_dump_block_raw(buf, size, flags);
2168 	else if (flags & ZDB_FLAG_INDIRECT)
2169 		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
2170 		    flags);
2171 	else if (flags & ZDB_FLAG_GBH)
2172 		zdb_dump_gbh(buf, flags);
2173 	else
2174 		zdb_dump_block(thing, buf, size, flags);
2175 
2176 out:
2177 	umem_free(buf, size);
2178 	free(dup);
2179 }
2180 
2181 static boolean_t
2182 nvlist_string_match(nvlist_t *config, char *name, char *tgt)
2183 {
2184 	char *s;
2185 
2186 	verify(nvlist_lookup_string(config, name, &s) == 0);
2187 	return (strcmp(s, tgt) == 0);
2188 }
2189 
2190 static boolean_t
2191 nvlist_uint64_match(nvlist_t *config, char *name, uint64_t tgt)
2192 {
2193 	uint64_t val;
2194 
2195 	verify(nvlist_lookup_uint64(config, name, &val) == 0);
2196 	return (val == tgt);
2197 }
2198 
2199 static boolean_t
2200 vdev_child_guid_match(nvlist_t *vdev, uint64_t guid)
2201 {
2202 	nvlist_t **child;
2203 	uint_t c, children;
2204 
2205 	verify(nvlist_lookup_nvlist_array(vdev, ZPOOL_CONFIG_CHILDREN,
2206 	    &child, &children) == 0);
2207 	for (c = 0; c < children; ++c)
2208 		if (nvlist_uint64_match(child[c], ZPOOL_CONFIG_GUID, guid))
2209 			return (B_TRUE);
2210 	return (B_FALSE);
2211 }
2212 
2213 static boolean_t
2214 vdev_child_string_match(nvlist_t *vdev, char *tgt)
2215 {
2216 	nvlist_t **child;
2217 	uint_t c, children;
2218 
2219 	verify(nvlist_lookup_nvlist_array(vdev, ZPOOL_CONFIG_CHILDREN,
2220 	    &child, &children) == 0);
2221 	for (c = 0; c < children; ++c) {
2222 		if (nvlist_string_match(child[c], ZPOOL_CONFIG_PATH, tgt) ||
2223 		    nvlist_string_match(child[c], ZPOOL_CONFIG_DEVID, tgt))
2224 			return (B_TRUE);
2225 	}
2226 	return (B_FALSE);
2227 }
2228 
2229 static boolean_t
2230 vdev_guid_match(nvlist_t *config, uint64_t guid)
2231 {
2232 	nvlist_t *nvroot;
2233 
2234 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2235 	    &nvroot) == 0);
2236 
2237 	return (nvlist_uint64_match(nvroot, ZPOOL_CONFIG_GUID, guid) ||
2238 	    vdev_child_guid_match(nvroot, guid));
2239 }
2240 
2241 static boolean_t
2242 vdev_string_match(nvlist_t *config, char *tgt)
2243 {
2244 	nvlist_t *nvroot;
2245 
2246 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2247 	    &nvroot) == 0);
2248 
2249 	return (vdev_child_string_match(nvroot, tgt));
2250 }
2251 
2252 static boolean_t
2253 pool_match(nvlist_t *config, char *tgt)
2254 {
2255 	uint64_t guid = strtoull(tgt, NULL, 0);
2256 
2257 	if (guid != 0) {
2258 		return (
2259 		    nvlist_uint64_match(config, ZPOOL_CONFIG_POOL_GUID, guid) ||
2260 		    vdev_guid_match(config, guid));
2261 	} else {
2262 		return (
2263 		    nvlist_string_match(config, ZPOOL_CONFIG_POOL_NAME, tgt) ||
2264 		    vdev_string_match(config, tgt));
2265 	}
2266 }
2267 
2268 static int
2269 find_exported_zpool(char *pool_id, nvlist_t **configp, char *vdev_dir,
2270     char *cachefile)
2271 {
2272 	nvlist_t *pools;
2273 	int error = ENOENT;
2274 	nvlist_t *match = NULL;
2275 
2276 	if (vdev_dir != NULL)
2277 		pools = zpool_find_import(g_zfs, 1, &vdev_dir, B_TRUE);
2278 	else if (cachefile != NULL)
2279 		pools = zpool_find_import_cached(g_zfs, cachefile, B_TRUE);
2280 	else
2281 		pools = zpool_find_import(g_zfs, 0, NULL, B_TRUE);
2282 
2283 	if (pools != NULL) {
2284 		nvpair_t *elem = NULL;
2285 
2286 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
2287 			verify(nvpair_value_nvlist(elem, configp) == 0);
2288 			if (pool_match(*configp, pool_id)) {
2289 				if (match != NULL) {
2290 					(void) fatal(
2291 					    "More than one matching pool - "
2292 					    "specify guid/devid/device path.");
2293 				} else {
2294 					match = *configp;
2295 					error = 0;
2296 				}
2297 			}
2298 		}
2299 	}
2300 
2301 	*configp = error ? NULL : match;
2302 
2303 	return (error);
2304 }
2305 
2306 int
2307 main(int argc, char **argv)
2308 {
2309 	int i, c;
2310 	struct rlimit rl = { 1024, 1024 };
2311 	spa_t *spa;
2312 	objset_t *os = NULL;
2313 	char *endstr;
2314 	int dump_all = 1;
2315 	int verbose = 0;
2316 	int error;
2317 	int flag, set;
2318 	int exported = 0;
2319 	char *vdev_dir = NULL;
2320 	char *cachefile = NULL;
2321 
2322 	(void) setrlimit(RLIMIT_NOFILE, &rl);
2323 	(void) enable_extended_FILE_stdio(-1, -1);
2324 
2325 	dprintf_setup(&argc, argv);
2326 
2327 	while ((c = getopt(argc, argv, "udibcsvCLO:B:S:U:lRep:")) != -1) {
2328 		switch (c) {
2329 		case 'u':
2330 		case 'd':
2331 		case 'i':
2332 		case 'b':
2333 		case 'c':
2334 		case 's':
2335 		case 'C':
2336 		case 'l':
2337 		case 'R':
2338 			dump_opt[c]++;
2339 			dump_all = 0;
2340 			break;
2341 		case 'L':
2342 			dump_opt[c]++;
2343 			break;
2344 		case 'O':
2345 			endstr = optarg;
2346 			if (endstr[0] == '!') {
2347 				endstr++;
2348 				set = 0;
2349 			} else {
2350 				set = 1;
2351 			}
2352 			if (strcmp(endstr, "post") == 0) {
2353 				flag = ADVANCE_PRE;
2354 				set = !set;
2355 			} else if (strcmp(endstr, "pre") == 0) {
2356 				flag = ADVANCE_PRE;
2357 			} else if (strcmp(endstr, "prune") == 0) {
2358 				flag = ADVANCE_PRUNE;
2359 			} else if (strcmp(endstr, "data") == 0) {
2360 				flag = ADVANCE_DATA;
2361 			} else if (strcmp(endstr, "holes") == 0) {
2362 				flag = ADVANCE_HOLES;
2363 			} else {
2364 				usage();
2365 			}
2366 			if (set)
2367 				zdb_advance |= flag;
2368 			else
2369 				zdb_advance &= ~flag;
2370 			break;
2371 		case 'B':
2372 			endstr = optarg - 1;
2373 			zdb_noread.zb_objset = strtoull(endstr + 1, &endstr, 0);
2374 			zdb_noread.zb_object = strtoull(endstr + 1, &endstr, 0);
2375 			zdb_noread.zb_level = strtol(endstr + 1, &endstr, 0);
2376 			zdb_noread.zb_blkid = strtoull(endstr + 1, &endstr, 16);
2377 			(void) printf("simulating bad block "
2378 			    "<%llu, %llu, %lld, %llx>\n",
2379 			    (u_longlong_t)zdb_noread.zb_objset,
2380 			    (u_longlong_t)zdb_noread.zb_object,
2381 			    (u_longlong_t)zdb_noread.zb_level,
2382 			    (u_longlong_t)zdb_noread.zb_blkid);
2383 			break;
2384 		case 'v':
2385 			verbose++;
2386 			break;
2387 		case 'U':
2388 			cachefile = optarg;
2389 			break;
2390 		case 'e':
2391 			exported = 1;
2392 			break;
2393 		case 'p':
2394 			vdev_dir = optarg;
2395 			break;
2396 		case 'S':
2397 			dump_opt[c]++;
2398 			dump_all = 0;
2399 			zdb_sig_user_data = (strncmp(optarg, "user:", 5) == 0);
2400 			if (!zdb_sig_user_data && strncmp(optarg, "all:", 4))
2401 				usage();
2402 			endstr = strchr(optarg, ':') + 1;
2403 			if (strcmp(endstr, "fletcher2") == 0)
2404 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_2;
2405 			else if (strcmp(endstr, "fletcher4") == 0)
2406 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_4;
2407 			else if (strcmp(endstr, "sha256") == 0)
2408 				zdb_sig_cksumalg = ZIO_CHECKSUM_SHA256;
2409 			else if (strcmp(endstr, "all") == 0)
2410 				zdb_sig_cksumalg = ZIO_CHECKSUM_FLETCHER_2;
2411 			else
2412 				usage();
2413 			break;
2414 		default:
2415 			usage();
2416 			break;
2417 		}
2418 	}
2419 
2420 	if (vdev_dir != NULL && exported == 0)
2421 		(void) fatal("-p option requires use of -e\n");
2422 
2423 	kernel_init(FREAD);
2424 	g_zfs = libzfs_init();
2425 	ASSERT(g_zfs != NULL);
2426 
2427 	/*
2428 	 * Disable vdev caching.  If we don't do this, live pool traversal
2429 	 * won't make progress because it will never see disk updates.
2430 	 */
2431 	zfs_vdev_cache_size = 0;
2432 
2433 	for (c = 0; c < 256; c++) {
2434 		if (dump_all && c != 'L' && c != 'l' && c != 'R')
2435 			dump_opt[c] = 1;
2436 		if (dump_opt[c])
2437 			dump_opt[c] += verbose;
2438 	}
2439 
2440 	argc -= optind;
2441 	argv += optind;
2442 
2443 	if (argc < 1) {
2444 		if (dump_opt['C']) {
2445 			dump_config(NULL);
2446 			return (0);
2447 		}
2448 		usage();
2449 	}
2450 
2451 	if (dump_opt['l']) {
2452 		dump_label(argv[0]);
2453 		return (0);
2454 	}
2455 
2456 	if (dump_opt['R']) {
2457 		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
2458 		flagbits['c'] = ZDB_FLAG_CHECKSUM;
2459 		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
2460 		flagbits['e'] = ZDB_FLAG_BSWAP;
2461 		flagbits['g'] = ZDB_FLAG_GBH;
2462 		flagbits['i'] = ZDB_FLAG_INDIRECT;
2463 		flagbits['p'] = ZDB_FLAG_PHYS;
2464 		flagbits['r'] = ZDB_FLAG_RAW;
2465 
2466 		spa = NULL;
2467 		while (argv[0]) {
2468 			zdb_read_block(argv[0], &spa);
2469 			argv++;
2470 			argc--;
2471 		}
2472 		if (spa)
2473 			spa_close(spa, (void *)zdb_read_block);
2474 		return (0);
2475 	}
2476 
2477 	if (dump_opt['C'])
2478 		dump_config(argv[0]);
2479 
2480 	if (exported == 0 && cachefile == NULL) {
2481 		if (strchr(argv[0], '/') != NULL) {
2482 			error = dmu_objset_open(argv[0], DMU_OST_ANY,
2483 			    DS_MODE_STANDARD | DS_MODE_READONLY, &os);
2484 		} else {
2485 			error = spa_open(argv[0], &spa, FTAG);
2486 		}
2487 	} else {
2488 		/*
2489 		 * Check to see if the name refers to an exported zpool
2490 		 */
2491 		nvlist_t *exported_conf = NULL;
2492 
2493 		error = find_exported_zpool(argv[0], &exported_conf, vdev_dir,
2494 		    cachefile);
2495 		if (error == 0) {
2496 			nvlist_t *nvl = NULL;
2497 
2498 			if (vdev_dir != NULL) {
2499 				if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
2500 					error = ENOMEM;
2501 				else if (nvlist_add_string(nvl,
2502 				    zpool_prop_to_name(ZPOOL_PROP_ALTROOT),
2503 				    vdev_dir) != 0)
2504 					error = ENOMEM;
2505 			}
2506 
2507 			if (error == 0)
2508 				error = spa_import(argv[0], exported_conf, nvl);
2509 			if (error == 0)
2510 				error = spa_open(argv[0], &spa, FTAG);
2511 
2512 			nvlist_free(nvl);
2513 		}
2514 	}
2515 
2516 	if (error)
2517 		fatal("can't open %s: %s", argv[0], strerror(error));
2518 
2519 	argv++;
2520 	if (--argc > 0) {
2521 		zopt_objects = argc;
2522 		zopt_object = calloc(zopt_objects, sizeof (uint64_t));
2523 		for (i = 0; i < zopt_objects; i++) {
2524 			errno = 0;
2525 			zopt_object[i] = strtoull(argv[i], NULL, 0);
2526 			if (zopt_object[i] == 0 && errno != 0)
2527 				fatal("bad object number %s: %s",
2528 				    argv[i], strerror(errno));
2529 		}
2530 	}
2531 
2532 	if (os != NULL) {
2533 		dump_dir(os);
2534 		dmu_objset_close(os);
2535 	} else {
2536 		dump_zpool(spa);
2537 		spa_close(spa, FTAG);
2538 	}
2539 
2540 	fuid_table_destroy();
2541 
2542 	libzfs_fini(g_zfs);
2543 	kernel_fini();
2544 
2545 	return (0);
2546 }
2547