xref: /freebsd/sys/contrib/openzfs/module/zfs/zap.c (revision a90b9d0159070121c221b966469c3e36d912bf82)
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 https://opensource.org/licenses/CDDL-1.0.
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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
24  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
25  * Copyright 2023 Alexander Stetsenko <alex.stetsenko@gmail.com>
26  * Copyright (c) 2023, Klara Inc.
27  */
28 
29 /*
30  * This file contains the top half of the zfs directory structure
31  * implementation. The bottom half is in zap_leaf.c.
32  *
33  * The zdir is an extendable hash data structure. There is a table of
34  * pointers to buckets (zap_t->zd_data->zd_leafs). The buckets are
35  * each a constant size and hold a variable number of directory entries.
36  * The buckets (aka "leaf nodes") are implemented in zap_leaf.c.
37  *
38  * The pointer table holds a power of 2 number of pointers.
39  * (1<<zap_t->zd_data->zd_phys->zd_prefix_len).  The bucket pointed to
40  * by the pointer at index i in the table holds entries whose hash value
41  * has a zd_prefix_len - bit prefix
42  */
43 
44 #include <sys/spa.h>
45 #include <sys/dmu.h>
46 #include <sys/dnode.h>
47 #include <sys/zfs_context.h>
48 #include <sys/zfs_znode.h>
49 #include <sys/fs/zfs.h>
50 #include <sys/zap.h>
51 #include <sys/zap_impl.h>
52 #include <sys/zap_leaf.h>
53 
54 /*
55  * If zap_iterate_prefetch is set, we will prefetch the entire ZAP object
56  * (all leaf blocks) when we start iterating over it.
57  *
58  * For zap_cursor_init(), the callers all intend to iterate through all the
59  * entries.  There are a few cases where an error (typically i/o error) could
60  * cause it to bail out early.
61  *
62  * For zap_cursor_init_serialized(), there are callers that do the iteration
63  * outside of ZFS.  Typically they would iterate over everything, but we
64  * don't have control of that.  E.g. zfs_ioc_snapshot_list_next(),
65  * zcp_snapshots_iter(), and other iterators over things in the MOS - these
66  * are called by /sbin/zfs and channel programs.  The other example is
67  * zfs_readdir() which iterates over directory entries for the getdents()
68  * syscall.  /sbin/ls iterates to the end (unless it receives a signal), but
69  * userland doesn't have to.
70  *
71  * Given that the ZAP entries aren't returned in a specific order, the only
72  * legitimate use cases for partial iteration would be:
73  *
74  * 1. Pagination: e.g. you only want to display 100 entries at a time, so you
75  *    get the first 100 and then wait for the user to hit "next page", which
76  *    they may never do).
77  *
78  * 2. You want to know if there are more than X entries, without relying on
79  *    the zfs-specific implementation of the directory's st_size (which is
80  *    the number of entries).
81  */
82 static int zap_iterate_prefetch = B_TRUE;
83 
84 /*
85  * Enable ZAP shrinking. When enabled, empty sibling leaf blocks will be
86  * collapsed into a single block.
87  */
88 int zap_shrink_enabled = B_TRUE;
89 
90 int fzap_default_block_shift = 14; /* 16k blocksize */
91 
92 static uint64_t zap_allocate_blocks(zap_t *zap, int nblocks);
93 static int zap_shrink(zap_name_t *zn, zap_leaf_t *l, dmu_tx_t *tx);
94 
95 void
96 fzap_byteswap(void *vbuf, size_t size)
97 {
98 	uint64_t block_type = *(uint64_t *)vbuf;
99 
100 	if (block_type == ZBT_LEAF || block_type == BSWAP_64(ZBT_LEAF))
101 		zap_leaf_byteswap(vbuf, size);
102 	else {
103 		/* it's a ptrtbl block */
104 		byteswap_uint64_array(vbuf, size);
105 	}
106 }
107 
108 void
109 fzap_upgrade(zap_t *zap, dmu_tx_t *tx, zap_flags_t flags)
110 {
111 	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
112 	zap->zap_ismicro = FALSE;
113 
114 	zap->zap_dbu.dbu_evict_func_sync = zap_evict_sync;
115 	zap->zap_dbu.dbu_evict_func_async = NULL;
116 
117 	mutex_init(&zap->zap_f.zap_num_entries_mtx, 0, MUTEX_DEFAULT, 0);
118 	zap->zap_f.zap_block_shift = highbit64(zap->zap_dbuf->db_size) - 1;
119 
120 	zap_phys_t *zp = zap_f_phys(zap);
121 	/*
122 	 * explicitly zero it since it might be coming from an
123 	 * initialized microzap
124 	 */
125 	memset(zap->zap_dbuf->db_data, 0, zap->zap_dbuf->db_size);
126 	zp->zap_block_type = ZBT_HEADER;
127 	zp->zap_magic = ZAP_MAGIC;
128 
129 	zp->zap_ptrtbl.zt_shift = ZAP_EMBEDDED_PTRTBL_SHIFT(zap);
130 
131 	zp->zap_freeblk = 2;		/* block 1 will be the first leaf */
132 	zp->zap_num_leafs = 1;
133 	zp->zap_num_entries = 0;
134 	zp->zap_salt = zap->zap_salt;
135 	zp->zap_normflags = zap->zap_normflags;
136 	zp->zap_flags = flags;
137 
138 	/* block 1 will be the first leaf */
139 	for (int i = 0; i < (1<<zp->zap_ptrtbl.zt_shift); i++)
140 		ZAP_EMBEDDED_PTRTBL_ENT(zap, i) = 1;
141 
142 	/*
143 	 * set up block 1 - the first leaf
144 	 */
145 	dmu_buf_t *db;
146 	VERIFY0(dmu_buf_hold_by_dnode(zap->zap_dnode,
147 	    1<<FZAP_BLOCK_SHIFT(zap), FTAG, &db, DMU_READ_NO_PREFETCH));
148 	dmu_buf_will_dirty(db, tx);
149 
150 	zap_leaf_t *l = kmem_zalloc(sizeof (zap_leaf_t), KM_SLEEP);
151 	l->l_dbuf = db;
152 
153 	zap_leaf_init(l, zp->zap_normflags != 0);
154 
155 	kmem_free(l, sizeof (zap_leaf_t));
156 	dmu_buf_rele(db, FTAG);
157 }
158 
159 static int
160 zap_tryupgradedir(zap_t *zap, dmu_tx_t *tx)
161 {
162 	if (RW_WRITE_HELD(&zap->zap_rwlock))
163 		return (1);
164 	if (rw_tryupgrade(&zap->zap_rwlock)) {
165 		dmu_buf_will_dirty(zap->zap_dbuf, tx);
166 		return (1);
167 	}
168 	return (0);
169 }
170 
171 /*
172  * Generic routines for dealing with the pointer & cookie tables.
173  */
174 
175 static int
176 zap_table_grow(zap_t *zap, zap_table_phys_t *tbl,
177     void (*transfer_func)(const uint64_t *src, uint64_t *dst, int n),
178     dmu_tx_t *tx)
179 {
180 	uint64_t newblk;
181 	int bs = FZAP_BLOCK_SHIFT(zap);
182 	int hepb = 1<<(bs-4);
183 	/* hepb = half the number of entries in a block */
184 
185 	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
186 	ASSERT(tbl->zt_blk != 0);
187 	ASSERT(tbl->zt_numblks > 0);
188 
189 	if (tbl->zt_nextblk != 0) {
190 		newblk = tbl->zt_nextblk;
191 	} else {
192 		newblk = zap_allocate_blocks(zap, tbl->zt_numblks * 2);
193 		tbl->zt_nextblk = newblk;
194 		ASSERT0(tbl->zt_blks_copied);
195 		dmu_prefetch_by_dnode(zap->zap_dnode, 0,
196 		    tbl->zt_blk << bs, tbl->zt_numblks << bs,
197 		    ZIO_PRIORITY_SYNC_READ);
198 	}
199 
200 	/*
201 	 * Copy the ptrtbl from the old to new location.
202 	 */
203 
204 	uint64_t b = tbl->zt_blks_copied;
205 	dmu_buf_t *db_old;
206 	int err = dmu_buf_hold_by_dnode(zap->zap_dnode,
207 	    (tbl->zt_blk + b) << bs, FTAG, &db_old, DMU_READ_NO_PREFETCH);
208 	if (err != 0)
209 		return (err);
210 
211 	/* first half of entries in old[b] go to new[2*b+0] */
212 	dmu_buf_t *db_new;
213 	VERIFY0(dmu_buf_hold_by_dnode(zap->zap_dnode,
214 	    (newblk + 2*b+0) << bs, FTAG, &db_new, DMU_READ_NO_PREFETCH));
215 	dmu_buf_will_dirty(db_new, tx);
216 	transfer_func(db_old->db_data, db_new->db_data, hepb);
217 	dmu_buf_rele(db_new, FTAG);
218 
219 	/* second half of entries in old[b] go to new[2*b+1] */
220 	VERIFY0(dmu_buf_hold_by_dnode(zap->zap_dnode,
221 	    (newblk + 2*b+1) << bs, FTAG, &db_new, DMU_READ_NO_PREFETCH));
222 	dmu_buf_will_dirty(db_new, tx);
223 	transfer_func((uint64_t *)db_old->db_data + hepb,
224 	    db_new->db_data, hepb);
225 	dmu_buf_rele(db_new, FTAG);
226 
227 	dmu_buf_rele(db_old, FTAG);
228 
229 	tbl->zt_blks_copied++;
230 
231 	dprintf("copied block %llu of %llu\n",
232 	    (u_longlong_t)tbl->zt_blks_copied,
233 	    (u_longlong_t)tbl->zt_numblks);
234 
235 	if (tbl->zt_blks_copied == tbl->zt_numblks) {
236 		(void) dmu_free_range(zap->zap_objset, zap->zap_object,
237 		    tbl->zt_blk << bs, tbl->zt_numblks << bs, tx);
238 
239 		tbl->zt_blk = newblk;
240 		tbl->zt_numblks *= 2;
241 		tbl->zt_shift++;
242 		tbl->zt_nextblk = 0;
243 		tbl->zt_blks_copied = 0;
244 
245 		dprintf("finished; numblocks now %llu (%uk entries)\n",
246 		    (u_longlong_t)tbl->zt_numblks, 1<<(tbl->zt_shift-10));
247 	}
248 
249 	return (0);
250 }
251 
252 static int
253 zap_table_store(zap_t *zap, zap_table_phys_t *tbl, uint64_t idx, uint64_t val,
254     dmu_tx_t *tx)
255 {
256 	int bs = FZAP_BLOCK_SHIFT(zap);
257 
258 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
259 	ASSERT(tbl->zt_blk != 0);
260 
261 	dprintf("storing %llx at index %llx\n", (u_longlong_t)val,
262 	    (u_longlong_t)idx);
263 
264 	uint64_t blk = idx >> (bs-3);
265 	uint64_t off = idx & ((1<<(bs-3))-1);
266 
267 	dmu_buf_t *db;
268 	int err = dmu_buf_hold_by_dnode(zap->zap_dnode,
269 	    (tbl->zt_blk + blk) << bs, FTAG, &db, DMU_READ_NO_PREFETCH);
270 	if (err != 0)
271 		return (err);
272 	dmu_buf_will_dirty(db, tx);
273 
274 	if (tbl->zt_nextblk != 0) {
275 		uint64_t idx2 = idx * 2;
276 		uint64_t blk2 = idx2 >> (bs-3);
277 		uint64_t off2 = idx2 & ((1<<(bs-3))-1);
278 		dmu_buf_t *db2;
279 
280 		err = dmu_buf_hold_by_dnode(zap->zap_dnode,
281 		    (tbl->zt_nextblk + blk2) << bs, FTAG, &db2,
282 		    DMU_READ_NO_PREFETCH);
283 		if (err != 0) {
284 			dmu_buf_rele(db, FTAG);
285 			return (err);
286 		}
287 		dmu_buf_will_dirty(db2, tx);
288 		((uint64_t *)db2->db_data)[off2] = val;
289 		((uint64_t *)db2->db_data)[off2+1] = val;
290 		dmu_buf_rele(db2, FTAG);
291 	}
292 
293 	((uint64_t *)db->db_data)[off] = val;
294 	dmu_buf_rele(db, FTAG);
295 
296 	return (0);
297 }
298 
299 static int
300 zap_table_load(zap_t *zap, zap_table_phys_t *tbl, uint64_t idx, uint64_t *valp)
301 {
302 	int bs = FZAP_BLOCK_SHIFT(zap);
303 
304 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
305 
306 	uint64_t blk = idx >> (bs-3);
307 	uint64_t off = idx & ((1<<(bs-3))-1);
308 
309 	dmu_buf_t *db;
310 	int err = dmu_buf_hold_by_dnode(zap->zap_dnode,
311 	    (tbl->zt_blk + blk) << bs, FTAG, &db, DMU_READ_NO_PREFETCH);
312 	if (err != 0)
313 		return (err);
314 	*valp = ((uint64_t *)db->db_data)[off];
315 	dmu_buf_rele(db, FTAG);
316 
317 	if (tbl->zt_nextblk != 0) {
318 		/*
319 		 * read the nextblk for the sake of i/o error checking,
320 		 * so that zap_table_load() will catch errors for
321 		 * zap_table_store.
322 		 */
323 		blk = (idx*2) >> (bs-3);
324 
325 		err = dmu_buf_hold_by_dnode(zap->zap_dnode,
326 		    (tbl->zt_nextblk + blk) << bs, FTAG, &db,
327 		    DMU_READ_NO_PREFETCH);
328 		if (err == 0)
329 			dmu_buf_rele(db, FTAG);
330 	}
331 	return (err);
332 }
333 
334 /*
335  * Routines for growing the ptrtbl.
336  */
337 
338 static void
339 zap_ptrtbl_transfer(const uint64_t *src, uint64_t *dst, int n)
340 {
341 	for (int i = 0; i < n; i++) {
342 		uint64_t lb = src[i];
343 		dst[2 * i + 0] = lb;
344 		dst[2 * i + 1] = lb;
345 	}
346 }
347 
348 static int
349 zap_grow_ptrtbl(zap_t *zap, dmu_tx_t *tx)
350 {
351 	/*
352 	 * The pointer table should never use more hash bits than we
353 	 * have (otherwise we'd be using useless zero bits to index it).
354 	 * If we are within 2 bits of running out, stop growing, since
355 	 * this is already an aberrant condition.
356 	 */
357 	if (zap_f_phys(zap)->zap_ptrtbl.zt_shift >= zap_hashbits(zap) - 2)
358 		return (SET_ERROR(ENOSPC));
359 
360 	if (zap_f_phys(zap)->zap_ptrtbl.zt_numblks == 0) {
361 		/*
362 		 * We are outgrowing the "embedded" ptrtbl (the one
363 		 * stored in the header block).  Give it its own entire
364 		 * block, which will double the size of the ptrtbl.
365 		 */
366 		ASSERT3U(zap_f_phys(zap)->zap_ptrtbl.zt_shift, ==,
367 		    ZAP_EMBEDDED_PTRTBL_SHIFT(zap));
368 		ASSERT0(zap_f_phys(zap)->zap_ptrtbl.zt_blk);
369 
370 		uint64_t newblk = zap_allocate_blocks(zap, 1);
371 		dmu_buf_t *db_new;
372 		int err = dmu_buf_hold_by_dnode(zap->zap_dnode,
373 		    newblk << FZAP_BLOCK_SHIFT(zap), FTAG, &db_new,
374 		    DMU_READ_NO_PREFETCH);
375 		if (err != 0)
376 			return (err);
377 		dmu_buf_will_dirty(db_new, tx);
378 		zap_ptrtbl_transfer(&ZAP_EMBEDDED_PTRTBL_ENT(zap, 0),
379 		    db_new->db_data, 1 << ZAP_EMBEDDED_PTRTBL_SHIFT(zap));
380 		dmu_buf_rele(db_new, FTAG);
381 
382 		zap_f_phys(zap)->zap_ptrtbl.zt_blk = newblk;
383 		zap_f_phys(zap)->zap_ptrtbl.zt_numblks = 1;
384 		zap_f_phys(zap)->zap_ptrtbl.zt_shift++;
385 
386 		ASSERT3U(1ULL << zap_f_phys(zap)->zap_ptrtbl.zt_shift, ==,
387 		    zap_f_phys(zap)->zap_ptrtbl.zt_numblks <<
388 		    (FZAP_BLOCK_SHIFT(zap)-3));
389 
390 		return (0);
391 	} else {
392 		return (zap_table_grow(zap, &zap_f_phys(zap)->zap_ptrtbl,
393 		    zap_ptrtbl_transfer, tx));
394 	}
395 }
396 
397 static void
398 zap_increment_num_entries(zap_t *zap, int delta, dmu_tx_t *tx)
399 {
400 	dmu_buf_will_dirty(zap->zap_dbuf, tx);
401 	mutex_enter(&zap->zap_f.zap_num_entries_mtx);
402 	ASSERT(delta > 0 || zap_f_phys(zap)->zap_num_entries >= -delta);
403 	zap_f_phys(zap)->zap_num_entries += delta;
404 	mutex_exit(&zap->zap_f.zap_num_entries_mtx);
405 }
406 
407 static uint64_t
408 zap_allocate_blocks(zap_t *zap, int nblocks)
409 {
410 	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
411 	uint64_t newblk = zap_f_phys(zap)->zap_freeblk;
412 	zap_f_phys(zap)->zap_freeblk += nblocks;
413 	return (newblk);
414 }
415 
416 static void
417 zap_leaf_evict_sync(void *dbu)
418 {
419 	zap_leaf_t *l = dbu;
420 
421 	rw_destroy(&l->l_rwlock);
422 	kmem_free(l, sizeof (zap_leaf_t));
423 }
424 
425 static zap_leaf_t *
426 zap_create_leaf(zap_t *zap, dmu_tx_t *tx)
427 {
428 	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
429 
430 	uint64_t blkid = zap_allocate_blocks(zap, 1);
431 	dmu_buf_t *db = NULL;
432 
433 	VERIFY0(dmu_buf_hold_by_dnode(zap->zap_dnode,
434 	    blkid << FZAP_BLOCK_SHIFT(zap), NULL, &db,
435 	    DMU_READ_NO_PREFETCH));
436 
437 	/*
438 	 * Create the leaf structure and stash it on the dbuf. If zap was
439 	 * recent shrunk or truncated, the dbuf might have been sitting in the
440 	 * cache waiting to be evicted, and so still have the old leaf attached
441 	 * to it. If so, just reuse it.
442 	 */
443 	zap_leaf_t *l = dmu_buf_get_user(db);
444 	if (l == NULL) {
445 		l = kmem_zalloc(sizeof (zap_leaf_t), KM_SLEEP);
446 		l->l_blkid = blkid;
447 		l->l_dbuf = db;
448 		rw_init(&l->l_rwlock, NULL, RW_NOLOCKDEP, NULL);
449 		dmu_buf_init_user(&l->l_dbu, zap_leaf_evict_sync, NULL,
450 		    &l->l_dbuf);
451 		dmu_buf_set_user(l->l_dbuf, &l->l_dbu);
452 	} else {
453 		ASSERT3U(l->l_blkid, ==, blkid);
454 		ASSERT3P(l->l_dbuf, ==, db);
455 	}
456 
457 	rw_enter(&l->l_rwlock, RW_WRITER);
458 	dmu_buf_will_dirty(l->l_dbuf, tx);
459 
460 	zap_leaf_init(l, zap->zap_normflags != 0);
461 
462 	zap_f_phys(zap)->zap_num_leafs++;
463 
464 	return (l);
465 }
466 
467 int
468 fzap_count(zap_t *zap, uint64_t *count)
469 {
470 	ASSERT(!zap->zap_ismicro);
471 	mutex_enter(&zap->zap_f.zap_num_entries_mtx); /* unnecessary */
472 	*count = zap_f_phys(zap)->zap_num_entries;
473 	mutex_exit(&zap->zap_f.zap_num_entries_mtx);
474 	return (0);
475 }
476 
477 /*
478  * Routines for obtaining zap_leaf_t's
479  */
480 
481 void
482 zap_put_leaf(zap_leaf_t *l)
483 {
484 	rw_exit(&l->l_rwlock);
485 	dmu_buf_rele(l->l_dbuf, NULL);
486 }
487 
488 static zap_leaf_t *
489 zap_open_leaf(uint64_t blkid, dmu_buf_t *db)
490 {
491 	ASSERT(blkid != 0);
492 
493 	zap_leaf_t *l = kmem_zalloc(sizeof (zap_leaf_t), KM_SLEEP);
494 	rw_init(&l->l_rwlock, NULL, RW_DEFAULT, NULL);
495 	rw_enter(&l->l_rwlock, RW_WRITER);
496 	l->l_blkid = blkid;
497 	l->l_bs = highbit64(db->db_size) - 1;
498 	l->l_dbuf = db;
499 
500 	dmu_buf_init_user(&l->l_dbu, zap_leaf_evict_sync, NULL, &l->l_dbuf);
501 	zap_leaf_t *winner = dmu_buf_set_user(db, &l->l_dbu);
502 
503 	rw_exit(&l->l_rwlock);
504 	if (winner != NULL) {
505 		/* someone else set it first */
506 		zap_leaf_evict_sync(&l->l_dbu);
507 		l = winner;
508 	}
509 
510 	/*
511 	 * lhr_pad was previously used for the next leaf in the leaf
512 	 * chain.  There should be no chained leafs (as we have removed
513 	 * support for them).
514 	 */
515 	ASSERT0(zap_leaf_phys(l)->l_hdr.lh_pad1);
516 
517 	/*
518 	 * There should be more hash entries than there can be
519 	 * chunks to put in the hash table
520 	 */
521 	ASSERT3U(ZAP_LEAF_HASH_NUMENTRIES(l), >, ZAP_LEAF_NUMCHUNKS(l) / 3);
522 
523 	/* The chunks should begin at the end of the hash table */
524 	ASSERT3P(&ZAP_LEAF_CHUNK(l, 0), ==, (zap_leaf_chunk_t *)
525 	    &zap_leaf_phys(l)->l_hash[ZAP_LEAF_HASH_NUMENTRIES(l)]);
526 
527 	/* The chunks should end at the end of the block */
528 	ASSERT3U((uintptr_t)&ZAP_LEAF_CHUNK(l, ZAP_LEAF_NUMCHUNKS(l)) -
529 	    (uintptr_t)zap_leaf_phys(l), ==, l->l_dbuf->db_size);
530 
531 	return (l);
532 }
533 
534 static int
535 zap_get_leaf_byblk(zap_t *zap, uint64_t blkid, dmu_tx_t *tx, krw_t lt,
536     zap_leaf_t **lp)
537 {
538 	dmu_buf_t *db;
539 
540 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
541 
542 	/*
543 	 * If system crashed just after dmu_free_long_range in zfs_rmnode, we
544 	 * would be left with an empty xattr dir in delete queue. blkid=0
545 	 * would be passed in when doing zfs_purgedir. If that's the case we
546 	 * should just return immediately. The underlying objects should
547 	 * already be freed, so this should be perfectly fine.
548 	 */
549 	if (blkid == 0)
550 		return (SET_ERROR(ENOENT));
551 
552 	int bs = FZAP_BLOCK_SHIFT(zap);
553 	int err = dmu_buf_hold_by_dnode(zap->zap_dnode,
554 	    blkid << bs, NULL, &db, DMU_READ_NO_PREFETCH);
555 	if (err != 0)
556 		return (err);
557 
558 	ASSERT3U(db->db_object, ==, zap->zap_object);
559 	ASSERT3U(db->db_offset, ==, blkid << bs);
560 	ASSERT3U(db->db_size, ==, 1 << bs);
561 	ASSERT(blkid != 0);
562 
563 	zap_leaf_t *l = dmu_buf_get_user(db);
564 
565 	if (l == NULL)
566 		l = zap_open_leaf(blkid, db);
567 
568 	rw_enter(&l->l_rwlock, lt);
569 	/*
570 	 * Must lock before dirtying, otherwise zap_leaf_phys(l) could change,
571 	 * causing ASSERT below to fail.
572 	 */
573 	if (lt == RW_WRITER)
574 		dmu_buf_will_dirty(db, tx);
575 	ASSERT3U(l->l_blkid, ==, blkid);
576 	ASSERT3P(l->l_dbuf, ==, db);
577 	ASSERT3U(zap_leaf_phys(l)->l_hdr.lh_block_type, ==, ZBT_LEAF);
578 	ASSERT3U(zap_leaf_phys(l)->l_hdr.lh_magic, ==, ZAP_LEAF_MAGIC);
579 
580 	*lp = l;
581 	return (0);
582 }
583 
584 static int
585 zap_idx_to_blk(zap_t *zap, uint64_t idx, uint64_t *valp)
586 {
587 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
588 
589 	if (zap_f_phys(zap)->zap_ptrtbl.zt_numblks == 0) {
590 		ASSERT3U(idx, <,
591 		    (1ULL << zap_f_phys(zap)->zap_ptrtbl.zt_shift));
592 		*valp = ZAP_EMBEDDED_PTRTBL_ENT(zap, idx);
593 		return (0);
594 	} else {
595 		return (zap_table_load(zap, &zap_f_phys(zap)->zap_ptrtbl,
596 		    idx, valp));
597 	}
598 }
599 
600 static int
601 zap_set_idx_to_blk(zap_t *zap, uint64_t idx, uint64_t blk, dmu_tx_t *tx)
602 {
603 	ASSERT(tx != NULL);
604 	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
605 
606 	if (zap_f_phys(zap)->zap_ptrtbl.zt_blk == 0) {
607 		ZAP_EMBEDDED_PTRTBL_ENT(zap, idx) = blk;
608 		return (0);
609 	} else {
610 		return (zap_table_store(zap, &zap_f_phys(zap)->zap_ptrtbl,
611 		    idx, blk, tx));
612 	}
613 }
614 
615 static int
616 zap_set_idx_range_to_blk(zap_t *zap, uint64_t idx, uint64_t nptrs, uint64_t blk,
617     dmu_tx_t *tx)
618 {
619 	int bs = FZAP_BLOCK_SHIFT(zap);
620 	int epb = bs >> 3; /* entries per block */
621 	int err = 0;
622 
623 	ASSERT(tx != NULL);
624 	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
625 
626 	/*
627 	 * Check for i/o errors
628 	 */
629 	for (int i = 0; i < nptrs; i += epb) {
630 		uint64_t blk;
631 		err = zap_idx_to_blk(zap, idx + i, &blk);
632 		if (err != 0) {
633 			return (err);
634 		}
635 	}
636 
637 	for (int i = 0; i < nptrs; i++) {
638 		err = zap_set_idx_to_blk(zap, idx + i, blk, tx);
639 		ASSERT0(err); /* we checked for i/o errors above */
640 		if (err != 0)
641 			break;
642 	}
643 
644 	return (err);
645 }
646 
647 #define	ZAP_PREFIX_HASH(pref, pref_len)	((pref) << (64 - (pref_len)))
648 
649 /*
650  * Each leaf has single range of entries (block pointers) in the ZAP ptrtbl.
651  * If two leaves are siblings, their ranges are adjecent and contain the same
652  * number of entries. In order to find out if a leaf has a sibling, we need to
653  * check the range corresponding to the sibling leaf. There is no need to check
654  * all entries in the range, we only need to check the frist and the last one.
655  */
656 static uint64_t
657 check_sibling_ptrtbl_range(zap_t *zap, uint64_t prefix, uint64_t prefix_len)
658 {
659 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
660 
661 	uint64_t h = ZAP_PREFIX_HASH(prefix, prefix_len);
662 	uint64_t idx = ZAP_HASH_IDX(h, zap_f_phys(zap)->zap_ptrtbl.zt_shift);
663 	uint64_t pref_diff = zap_f_phys(zap)->zap_ptrtbl.zt_shift - prefix_len;
664 	uint64_t nptrs = (1 << pref_diff);
665 	uint64_t first;
666 	uint64_t last;
667 
668 	ASSERT3U(idx+nptrs, <=, (1UL << zap_f_phys(zap)->zap_ptrtbl.zt_shift));
669 
670 	if (zap_idx_to_blk(zap, idx, &first) != 0)
671 		return (0);
672 
673 	if (zap_idx_to_blk(zap, idx + nptrs - 1, &last) != 0)
674 		return (0);
675 
676 	if (first != last)
677 		return (0);
678 	return (first);
679 }
680 
681 static int
682 zap_deref_leaf(zap_t *zap, uint64_t h, dmu_tx_t *tx, krw_t lt, zap_leaf_t **lp)
683 {
684 	uint64_t blk;
685 
686 	ASSERT(zap->zap_dbuf == NULL ||
687 	    zap_f_phys(zap) == zap->zap_dbuf->db_data);
688 
689 	/* Reality check for corrupt zap objects (leaf or header). */
690 	if ((zap_f_phys(zap)->zap_block_type != ZBT_LEAF &&
691 	    zap_f_phys(zap)->zap_block_type != ZBT_HEADER) ||
692 	    zap_f_phys(zap)->zap_magic != ZAP_MAGIC) {
693 		return (SET_ERROR(EIO));
694 	}
695 
696 	uint64_t idx = ZAP_HASH_IDX(h, zap_f_phys(zap)->zap_ptrtbl.zt_shift);
697 	int err = zap_idx_to_blk(zap, idx, &blk);
698 	if (err != 0)
699 		return (err);
700 	err = zap_get_leaf_byblk(zap, blk, tx, lt, lp);
701 
702 	ASSERT(err ||
703 	    ZAP_HASH_IDX(h, zap_leaf_phys(*lp)->l_hdr.lh_prefix_len) ==
704 	    zap_leaf_phys(*lp)->l_hdr.lh_prefix);
705 	return (err);
706 }
707 
708 static int
709 zap_expand_leaf(zap_name_t *zn, zap_leaf_t *l,
710     const void *tag, dmu_tx_t *tx, zap_leaf_t **lp)
711 {
712 	zap_t *zap = zn->zn_zap;
713 	uint64_t hash = zn->zn_hash;
714 	int err;
715 	int old_prefix_len = zap_leaf_phys(l)->l_hdr.lh_prefix_len;
716 
717 	ASSERT3U(old_prefix_len, <=, zap_f_phys(zap)->zap_ptrtbl.zt_shift);
718 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
719 
720 	ASSERT3U(ZAP_HASH_IDX(hash, old_prefix_len), ==,
721 	    zap_leaf_phys(l)->l_hdr.lh_prefix);
722 
723 	if (zap_tryupgradedir(zap, tx) == 0 ||
724 	    old_prefix_len == zap_f_phys(zap)->zap_ptrtbl.zt_shift) {
725 		/* We failed to upgrade, or need to grow the pointer table */
726 		objset_t *os = zap->zap_objset;
727 		uint64_t object = zap->zap_object;
728 
729 		zap_put_leaf(l);
730 		*lp = l = NULL;
731 		zap_unlockdir(zap, tag);
732 		err = zap_lockdir(os, object, tx, RW_WRITER,
733 		    FALSE, FALSE, tag, &zn->zn_zap);
734 		zap = zn->zn_zap;
735 		if (err != 0)
736 			return (err);
737 		ASSERT(!zap->zap_ismicro);
738 
739 		while (old_prefix_len ==
740 		    zap_f_phys(zap)->zap_ptrtbl.zt_shift) {
741 			err = zap_grow_ptrtbl(zap, tx);
742 			if (err != 0)
743 				return (err);
744 		}
745 
746 		err = zap_deref_leaf(zap, hash, tx, RW_WRITER, &l);
747 		if (err != 0)
748 			return (err);
749 
750 		if (zap_leaf_phys(l)->l_hdr.lh_prefix_len != old_prefix_len) {
751 			/* it split while our locks were down */
752 			*lp = l;
753 			return (0);
754 		}
755 	}
756 	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
757 	ASSERT3U(old_prefix_len, <, zap_f_phys(zap)->zap_ptrtbl.zt_shift);
758 	ASSERT3U(ZAP_HASH_IDX(hash, old_prefix_len), ==,
759 	    zap_leaf_phys(l)->l_hdr.lh_prefix);
760 
761 	int prefix_diff = zap_f_phys(zap)->zap_ptrtbl.zt_shift -
762 	    (old_prefix_len + 1);
763 	uint64_t sibling =
764 	    (ZAP_HASH_IDX(hash, old_prefix_len + 1) | 1) << prefix_diff;
765 
766 	/* check for i/o errors before doing zap_leaf_split */
767 	for (int i = 0; i < (1ULL << prefix_diff); i++) {
768 		uint64_t blk;
769 		err = zap_idx_to_blk(zap, sibling + i, &blk);
770 		if (err != 0)
771 			return (err);
772 		ASSERT3U(blk, ==, l->l_blkid);
773 	}
774 
775 	zap_leaf_t *nl = zap_create_leaf(zap, tx);
776 	zap_leaf_split(l, nl, zap->zap_normflags != 0);
777 
778 	/* set sibling pointers */
779 	for (int i = 0; i < (1ULL << prefix_diff); i++) {
780 		err = zap_set_idx_to_blk(zap, sibling + i, nl->l_blkid, tx);
781 		ASSERT0(err); /* we checked for i/o errors above */
782 	}
783 
784 	ASSERT3U(zap_leaf_phys(l)->l_hdr.lh_prefix_len, >, 0);
785 
786 	if (hash & (1ULL << (64 - zap_leaf_phys(l)->l_hdr.lh_prefix_len))) {
787 		/* we want the sibling */
788 		zap_put_leaf(l);
789 		*lp = nl;
790 	} else {
791 		zap_put_leaf(nl);
792 		*lp = l;
793 	}
794 
795 	return (0);
796 }
797 
798 static void
799 zap_put_leaf_maybe_grow_ptrtbl(zap_name_t *zn, zap_leaf_t *l,
800     const void *tag, dmu_tx_t *tx)
801 {
802 	zap_t *zap = zn->zn_zap;
803 	int shift = zap_f_phys(zap)->zap_ptrtbl.zt_shift;
804 	int leaffull = (zap_leaf_phys(l)->l_hdr.lh_prefix_len == shift &&
805 	    zap_leaf_phys(l)->l_hdr.lh_nfree < ZAP_LEAF_LOW_WATER);
806 
807 	zap_put_leaf(l);
808 
809 	if (leaffull || zap_f_phys(zap)->zap_ptrtbl.zt_nextblk) {
810 		/*
811 		 * We are in the middle of growing the pointer table, or
812 		 * this leaf will soon make us grow it.
813 		 */
814 		if (zap_tryupgradedir(zap, tx) == 0) {
815 			objset_t *os = zap->zap_objset;
816 			uint64_t zapobj = zap->zap_object;
817 
818 			zap_unlockdir(zap, tag);
819 			int err = zap_lockdir(os, zapobj, tx,
820 			    RW_WRITER, FALSE, FALSE, tag, &zn->zn_zap);
821 			zap = zn->zn_zap;
822 			if (err != 0)
823 				return;
824 		}
825 
826 		/* could have finished growing while our locks were down */
827 		if (zap_f_phys(zap)->zap_ptrtbl.zt_shift == shift)
828 			(void) zap_grow_ptrtbl(zap, tx);
829 	}
830 }
831 
832 static int
833 fzap_checkname(zap_name_t *zn)
834 {
835 	if (zn->zn_key_orig_numints * zn->zn_key_intlen > ZAP_MAXNAMELEN)
836 		return (SET_ERROR(ENAMETOOLONG));
837 	return (0);
838 }
839 
840 static int
841 fzap_checksize(uint64_t integer_size, uint64_t num_integers)
842 {
843 	/* Only integer sizes supported by C */
844 	switch (integer_size) {
845 	case 1:
846 	case 2:
847 	case 4:
848 	case 8:
849 		break;
850 	default:
851 		return (SET_ERROR(EINVAL));
852 	}
853 
854 	if (integer_size * num_integers > ZAP_MAXVALUELEN)
855 		return (SET_ERROR(E2BIG));
856 
857 	return (0);
858 }
859 
860 static int
861 fzap_check(zap_name_t *zn, uint64_t integer_size, uint64_t num_integers)
862 {
863 	int err = fzap_checkname(zn);
864 	if (err != 0)
865 		return (err);
866 	return (fzap_checksize(integer_size, num_integers));
867 }
868 
869 /*
870  * Routines for manipulating attributes.
871  */
872 int
873 fzap_lookup(zap_name_t *zn,
874     uint64_t integer_size, uint64_t num_integers, void *buf,
875     char *realname, int rn_len, boolean_t *ncp)
876 {
877 	zap_leaf_t *l;
878 	zap_entry_handle_t zeh;
879 
880 	int err = fzap_checkname(zn);
881 	if (err != 0)
882 		return (err);
883 
884 	err = zap_deref_leaf(zn->zn_zap, zn->zn_hash, NULL, RW_READER, &l);
885 	if (err != 0)
886 		return (err);
887 	err = zap_leaf_lookup(l, zn, &zeh);
888 	if (err == 0) {
889 		if ((err = fzap_checksize(integer_size, num_integers)) != 0) {
890 			zap_put_leaf(l);
891 			return (err);
892 		}
893 
894 		err = zap_entry_read(&zeh, integer_size, num_integers, buf);
895 		(void) zap_entry_read_name(zn->zn_zap, &zeh, rn_len, realname);
896 		if (ncp) {
897 			*ncp = zap_entry_normalization_conflict(&zeh,
898 			    zn, NULL, zn->zn_zap);
899 		}
900 	}
901 
902 	zap_put_leaf(l);
903 	return (err);
904 }
905 
906 int
907 fzap_add_cd(zap_name_t *zn,
908     uint64_t integer_size, uint64_t num_integers,
909     const void *val, uint32_t cd, const void *tag, dmu_tx_t *tx)
910 {
911 	zap_leaf_t *l;
912 	int err;
913 	zap_entry_handle_t zeh;
914 	zap_t *zap = zn->zn_zap;
915 
916 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
917 	ASSERT(!zap->zap_ismicro);
918 	ASSERT(fzap_check(zn, integer_size, num_integers) == 0);
919 
920 	err = zap_deref_leaf(zap, zn->zn_hash, tx, RW_WRITER, &l);
921 	if (err != 0)
922 		return (err);
923 retry:
924 	err = zap_leaf_lookup(l, zn, &zeh);
925 	if (err == 0) {
926 		err = SET_ERROR(EEXIST);
927 		goto out;
928 	}
929 	if (err != ENOENT)
930 		goto out;
931 
932 	err = zap_entry_create(l, zn, cd,
933 	    integer_size, num_integers, val, &zeh);
934 
935 	if (err == 0) {
936 		zap_increment_num_entries(zap, 1, tx);
937 	} else if (err == EAGAIN) {
938 		err = zap_expand_leaf(zn, l, tag, tx, &l);
939 		zap = zn->zn_zap;	/* zap_expand_leaf() may change zap */
940 		if (err == 0)
941 			goto retry;
942 	}
943 
944 out:
945 	if (l != NULL) {
946 		if (err == ENOSPC)
947 			zap_put_leaf(l);
948 		else
949 			zap_put_leaf_maybe_grow_ptrtbl(zn, l, tag, tx);
950 	}
951 	return (err);
952 }
953 
954 int
955 fzap_add(zap_name_t *zn,
956     uint64_t integer_size, uint64_t num_integers,
957     const void *val, const void *tag, dmu_tx_t *tx)
958 {
959 	int err = fzap_check(zn, integer_size, num_integers);
960 	if (err != 0)
961 		return (err);
962 
963 	return (fzap_add_cd(zn, integer_size, num_integers,
964 	    val, ZAP_NEED_CD, tag, tx));
965 }
966 
967 int
968 fzap_update(zap_name_t *zn,
969     int integer_size, uint64_t num_integers, const void *val,
970     const void *tag, dmu_tx_t *tx)
971 {
972 	zap_leaf_t *l;
973 	int err;
974 	boolean_t create;
975 	zap_entry_handle_t zeh;
976 	zap_t *zap = zn->zn_zap;
977 
978 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
979 	err = fzap_check(zn, integer_size, num_integers);
980 	if (err != 0)
981 		return (err);
982 
983 	err = zap_deref_leaf(zap, zn->zn_hash, tx, RW_WRITER, &l);
984 	if (err != 0)
985 		return (err);
986 retry:
987 	err = zap_leaf_lookup(l, zn, &zeh);
988 	create = (err == ENOENT);
989 	ASSERT(err == 0 || err == ENOENT);
990 
991 	if (create) {
992 		err = zap_entry_create(l, zn, ZAP_NEED_CD,
993 		    integer_size, num_integers, val, &zeh);
994 		if (err == 0)
995 			zap_increment_num_entries(zap, 1, tx);
996 	} else {
997 		err = zap_entry_update(&zeh, integer_size, num_integers, val);
998 	}
999 
1000 	if (err == EAGAIN) {
1001 		err = zap_expand_leaf(zn, l, tag, tx, &l);
1002 		zap = zn->zn_zap;	/* zap_expand_leaf() may change zap */
1003 		if (err == 0)
1004 			goto retry;
1005 	}
1006 
1007 	if (l != NULL) {
1008 		if (err == ENOSPC)
1009 			zap_put_leaf(l);
1010 		else
1011 			zap_put_leaf_maybe_grow_ptrtbl(zn, l, tag, tx);
1012 	}
1013 	return (err);
1014 }
1015 
1016 int
1017 fzap_length(zap_name_t *zn,
1018     uint64_t *integer_size, uint64_t *num_integers)
1019 {
1020 	zap_leaf_t *l;
1021 	int err;
1022 	zap_entry_handle_t zeh;
1023 
1024 	err = zap_deref_leaf(zn->zn_zap, zn->zn_hash, NULL, RW_READER, &l);
1025 	if (err != 0)
1026 		return (err);
1027 	err = zap_leaf_lookup(l, zn, &zeh);
1028 	if (err != 0)
1029 		goto out;
1030 
1031 	if (integer_size != NULL)
1032 		*integer_size = zeh.zeh_integer_size;
1033 	if (num_integers != NULL)
1034 		*num_integers = zeh.zeh_num_integers;
1035 out:
1036 	zap_put_leaf(l);
1037 	return (err);
1038 }
1039 
1040 int
1041 fzap_remove(zap_name_t *zn, dmu_tx_t *tx)
1042 {
1043 	zap_leaf_t *l;
1044 	int err;
1045 	zap_entry_handle_t zeh;
1046 
1047 	err = zap_deref_leaf(zn->zn_zap, zn->zn_hash, tx, RW_WRITER, &l);
1048 	if (err != 0)
1049 		return (err);
1050 	err = zap_leaf_lookup(l, zn, &zeh);
1051 	if (err == 0) {
1052 		zap_entry_remove(&zeh);
1053 		zap_increment_num_entries(zn->zn_zap, -1, tx);
1054 
1055 		if (zap_leaf_phys(l)->l_hdr.lh_nentries == 0 &&
1056 		    zap_shrink_enabled)
1057 			return (zap_shrink(zn, l, tx));
1058 	}
1059 	zap_put_leaf(l);
1060 	return (err);
1061 }
1062 
1063 void
1064 fzap_prefetch(zap_name_t *zn)
1065 {
1066 	uint64_t blk;
1067 	zap_t *zap = zn->zn_zap;
1068 
1069 	uint64_t idx = ZAP_HASH_IDX(zn->zn_hash,
1070 	    zap_f_phys(zap)->zap_ptrtbl.zt_shift);
1071 	if (zap_idx_to_blk(zap, idx, &blk) != 0)
1072 		return;
1073 	int bs = FZAP_BLOCK_SHIFT(zap);
1074 	dmu_prefetch_by_dnode(zap->zap_dnode, 0, blk << bs, 1 << bs,
1075 	    ZIO_PRIORITY_SYNC_READ);
1076 }
1077 
1078 /*
1079  * Helper functions for consumers.
1080  */
1081 
1082 uint64_t
1083 zap_create_link(objset_t *os, dmu_object_type_t ot, uint64_t parent_obj,
1084     const char *name, dmu_tx_t *tx)
1085 {
1086 	return (zap_create_link_dnsize(os, ot, parent_obj, name, 0, tx));
1087 }
1088 
1089 uint64_t
1090 zap_create_link_dnsize(objset_t *os, dmu_object_type_t ot, uint64_t parent_obj,
1091     const char *name, int dnodesize, dmu_tx_t *tx)
1092 {
1093 	uint64_t new_obj;
1094 
1095 	new_obj = zap_create_dnsize(os, ot, DMU_OT_NONE, 0, dnodesize, tx);
1096 	VERIFY(new_obj != 0);
1097 	VERIFY0(zap_add(os, parent_obj, name, sizeof (uint64_t), 1, &new_obj,
1098 	    tx));
1099 
1100 	return (new_obj);
1101 }
1102 
1103 int
1104 zap_value_search(objset_t *os, uint64_t zapobj, uint64_t value, uint64_t mask,
1105     char *name)
1106 {
1107 	zap_cursor_t zc;
1108 	int err;
1109 
1110 	if (mask == 0)
1111 		mask = -1ULL;
1112 
1113 	zap_attribute_t *za = kmem_alloc(sizeof (*za), KM_SLEEP);
1114 	for (zap_cursor_init(&zc, os, zapobj);
1115 	    (err = zap_cursor_retrieve(&zc, za)) == 0;
1116 	    zap_cursor_advance(&zc)) {
1117 		if ((za->za_first_integer & mask) == (value & mask)) {
1118 			(void) strlcpy(name, za->za_name, MAXNAMELEN);
1119 			break;
1120 		}
1121 	}
1122 	zap_cursor_fini(&zc);
1123 	kmem_free(za, sizeof (*za));
1124 	return (err);
1125 }
1126 
1127 int
1128 zap_join(objset_t *os, uint64_t fromobj, uint64_t intoobj, dmu_tx_t *tx)
1129 {
1130 	zap_cursor_t zc;
1131 	int err = 0;
1132 
1133 	zap_attribute_t *za = kmem_alloc(sizeof (*za), KM_SLEEP);
1134 	for (zap_cursor_init(&zc, os, fromobj);
1135 	    zap_cursor_retrieve(&zc, za) == 0;
1136 	    (void) zap_cursor_advance(&zc)) {
1137 		if (za->za_integer_length != 8 || za->za_num_integers != 1) {
1138 			err = SET_ERROR(EINVAL);
1139 			break;
1140 		}
1141 		err = zap_add(os, intoobj, za->za_name,
1142 		    8, 1, &za->za_first_integer, tx);
1143 		if (err != 0)
1144 			break;
1145 	}
1146 	zap_cursor_fini(&zc);
1147 	kmem_free(za, sizeof (*za));
1148 	return (err);
1149 }
1150 
1151 int
1152 zap_join_key(objset_t *os, uint64_t fromobj, uint64_t intoobj,
1153     uint64_t value, dmu_tx_t *tx)
1154 {
1155 	zap_cursor_t zc;
1156 	int err = 0;
1157 
1158 	zap_attribute_t *za = kmem_alloc(sizeof (*za), KM_SLEEP);
1159 	for (zap_cursor_init(&zc, os, fromobj);
1160 	    zap_cursor_retrieve(&zc, za) == 0;
1161 	    (void) zap_cursor_advance(&zc)) {
1162 		if (za->za_integer_length != 8 || za->za_num_integers != 1) {
1163 			err = SET_ERROR(EINVAL);
1164 			break;
1165 		}
1166 		err = zap_add(os, intoobj, za->za_name,
1167 		    8, 1, &value, tx);
1168 		if (err != 0)
1169 			break;
1170 	}
1171 	zap_cursor_fini(&zc);
1172 	kmem_free(za, sizeof (*za));
1173 	return (err);
1174 }
1175 
1176 int
1177 zap_join_increment(objset_t *os, uint64_t fromobj, uint64_t intoobj,
1178     dmu_tx_t *tx)
1179 {
1180 	zap_cursor_t zc;
1181 	int err = 0;
1182 
1183 	zap_attribute_t *za = kmem_alloc(sizeof (*za), KM_SLEEP);
1184 	for (zap_cursor_init(&zc, os, fromobj);
1185 	    zap_cursor_retrieve(&zc, za) == 0;
1186 	    (void) zap_cursor_advance(&zc)) {
1187 		uint64_t delta = 0;
1188 
1189 		if (za->za_integer_length != 8 || za->za_num_integers != 1) {
1190 			err = SET_ERROR(EINVAL);
1191 			break;
1192 		}
1193 
1194 		err = zap_lookup(os, intoobj, za->za_name, 8, 1, &delta);
1195 		if (err != 0 && err != ENOENT)
1196 			break;
1197 		delta += za->za_first_integer;
1198 		err = zap_update(os, intoobj, za->za_name, 8, 1, &delta, tx);
1199 		if (err != 0)
1200 			break;
1201 	}
1202 	zap_cursor_fini(&zc);
1203 	kmem_free(za, sizeof (*za));
1204 	return (err);
1205 }
1206 
1207 int
1208 zap_add_int(objset_t *os, uint64_t obj, uint64_t value, dmu_tx_t *tx)
1209 {
1210 	char name[20];
1211 
1212 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)value);
1213 	return (zap_add(os, obj, name, 8, 1, &value, tx));
1214 }
1215 
1216 int
1217 zap_remove_int(objset_t *os, uint64_t obj, uint64_t value, dmu_tx_t *tx)
1218 {
1219 	char name[20];
1220 
1221 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)value);
1222 	return (zap_remove(os, obj, name, tx));
1223 }
1224 
1225 int
1226 zap_lookup_int(objset_t *os, uint64_t obj, uint64_t value)
1227 {
1228 	char name[20];
1229 
1230 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)value);
1231 	return (zap_lookup(os, obj, name, 8, 1, &value));
1232 }
1233 
1234 int
1235 zap_add_int_key(objset_t *os, uint64_t obj,
1236     uint64_t key, uint64_t value, dmu_tx_t *tx)
1237 {
1238 	char name[20];
1239 
1240 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)key);
1241 	return (zap_add(os, obj, name, 8, 1, &value, tx));
1242 }
1243 
1244 int
1245 zap_update_int_key(objset_t *os, uint64_t obj,
1246     uint64_t key, uint64_t value, dmu_tx_t *tx)
1247 {
1248 	char name[20];
1249 
1250 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)key);
1251 	return (zap_update(os, obj, name, 8, 1, &value, tx));
1252 }
1253 
1254 int
1255 zap_lookup_int_key(objset_t *os, uint64_t obj, uint64_t key, uint64_t *valuep)
1256 {
1257 	char name[20];
1258 
1259 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)key);
1260 	return (zap_lookup(os, obj, name, 8, 1, valuep));
1261 }
1262 
1263 int
1264 zap_increment(objset_t *os, uint64_t obj, const char *name, int64_t delta,
1265     dmu_tx_t *tx)
1266 {
1267 	uint64_t value = 0;
1268 
1269 	if (delta == 0)
1270 		return (0);
1271 
1272 	int err = zap_lookup(os, obj, name, 8, 1, &value);
1273 	if (err != 0 && err != ENOENT)
1274 		return (err);
1275 	value += delta;
1276 	if (value == 0)
1277 		err = zap_remove(os, obj, name, tx);
1278 	else
1279 		err = zap_update(os, obj, name, 8, 1, &value, tx);
1280 	return (err);
1281 }
1282 
1283 int
1284 zap_increment_int(objset_t *os, uint64_t obj, uint64_t key, int64_t delta,
1285     dmu_tx_t *tx)
1286 {
1287 	char name[20];
1288 
1289 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)key);
1290 	return (zap_increment(os, obj, name, delta, tx));
1291 }
1292 
1293 /*
1294  * Routines for iterating over the attributes.
1295  */
1296 
1297 int
1298 fzap_cursor_retrieve(zap_t *zap, zap_cursor_t *zc, zap_attribute_t *za)
1299 {
1300 	int err = ENOENT;
1301 	zap_entry_handle_t zeh;
1302 	zap_leaf_t *l;
1303 
1304 	/* retrieve the next entry at or after zc_hash/zc_cd */
1305 	/* if no entry, return ENOENT */
1306 
1307 	/*
1308 	 * If we are reading from the beginning, we're almost certain to
1309 	 * iterate over the entire ZAP object.  If there are multiple leaf
1310 	 * blocks (freeblk > 2), prefetch the whole object (up to
1311 	 * dmu_prefetch_max bytes), so that we read the leaf blocks
1312 	 * concurrently. (Unless noprefetch was requested via
1313 	 * zap_cursor_init_noprefetch()).
1314 	 */
1315 	if (zc->zc_hash == 0 && zap_iterate_prefetch &&
1316 	    zc->zc_prefetch && zap_f_phys(zap)->zap_freeblk > 2) {
1317 		dmu_prefetch_by_dnode(zap->zap_dnode, 0, 0,
1318 		    zap_f_phys(zap)->zap_freeblk << FZAP_BLOCK_SHIFT(zap),
1319 		    ZIO_PRIORITY_ASYNC_READ);
1320 	}
1321 
1322 	if (zc->zc_leaf) {
1323 		rw_enter(&zc->zc_leaf->l_rwlock, RW_READER);
1324 
1325 		/*
1326 		 * The leaf was either shrunk or split.
1327 		 */
1328 		if ((zap_leaf_phys(zc->zc_leaf)->l_hdr.lh_block_type == 0) ||
1329 		    (ZAP_HASH_IDX(zc->zc_hash,
1330 		    zap_leaf_phys(zc->zc_leaf)->l_hdr.lh_prefix_len) !=
1331 		    zap_leaf_phys(zc->zc_leaf)->l_hdr.lh_prefix)) {
1332 			zap_put_leaf(zc->zc_leaf);
1333 			zc->zc_leaf = NULL;
1334 		}
1335 	}
1336 
1337 again:
1338 	if (zc->zc_leaf == NULL) {
1339 		err = zap_deref_leaf(zap, zc->zc_hash, NULL, RW_READER,
1340 		    &zc->zc_leaf);
1341 		if (err != 0)
1342 			return (err);
1343 	}
1344 	l = zc->zc_leaf;
1345 
1346 	err = zap_leaf_lookup_closest(l, zc->zc_hash, zc->zc_cd, &zeh);
1347 
1348 	if (err == ENOENT) {
1349 		if (zap_leaf_phys(l)->l_hdr.lh_prefix_len == 0) {
1350 			zc->zc_hash = -1ULL;
1351 			zc->zc_cd = 0;
1352 		} else {
1353 			uint64_t nocare = (1ULL <<
1354 			    (64 - zap_leaf_phys(l)->l_hdr.lh_prefix_len)) - 1;
1355 
1356 			zc->zc_hash = (zc->zc_hash & ~nocare) + nocare + 1;
1357 			zc->zc_cd = 0;
1358 
1359 			if (zc->zc_hash == 0) {
1360 				zc->zc_hash = -1ULL;
1361 			} else {
1362 				zap_put_leaf(zc->zc_leaf);
1363 				zc->zc_leaf = NULL;
1364 				goto again;
1365 			}
1366 		}
1367 	}
1368 
1369 	if (err == 0) {
1370 		zc->zc_hash = zeh.zeh_hash;
1371 		zc->zc_cd = zeh.zeh_cd;
1372 		za->za_integer_length = zeh.zeh_integer_size;
1373 		za->za_num_integers = zeh.zeh_num_integers;
1374 		if (zeh.zeh_num_integers == 0) {
1375 			za->za_first_integer = 0;
1376 		} else {
1377 			err = zap_entry_read(&zeh, 8, 1, &za->za_first_integer);
1378 			ASSERT(err == 0 || err == EOVERFLOW);
1379 		}
1380 		err = zap_entry_read_name(zap, &zeh,
1381 		    sizeof (za->za_name), za->za_name);
1382 		ASSERT(err == 0);
1383 
1384 		za->za_normalization_conflict =
1385 		    zap_entry_normalization_conflict(&zeh,
1386 		    NULL, za->za_name, zap);
1387 	}
1388 	rw_exit(&zc->zc_leaf->l_rwlock);
1389 	return (err);
1390 }
1391 
1392 static void
1393 zap_stats_ptrtbl(zap_t *zap, uint64_t *tbl, int len, zap_stats_t *zs)
1394 {
1395 	uint64_t lastblk = 0;
1396 
1397 	/*
1398 	 * NB: if a leaf has more pointers than an entire ptrtbl block
1399 	 * can hold, then it'll be accounted for more than once, since
1400 	 * we won't have lastblk.
1401 	 */
1402 	for (int i = 0; i < len; i++) {
1403 		zap_leaf_t *l;
1404 
1405 		if (tbl[i] == lastblk)
1406 			continue;
1407 		lastblk = tbl[i];
1408 
1409 		int err = zap_get_leaf_byblk(zap, tbl[i], NULL, RW_READER, &l);
1410 		if (err == 0) {
1411 			zap_leaf_stats(zap, l, zs);
1412 			zap_put_leaf(l);
1413 		}
1414 	}
1415 }
1416 
1417 void
1418 fzap_get_stats(zap_t *zap, zap_stats_t *zs)
1419 {
1420 	int bs = FZAP_BLOCK_SHIFT(zap);
1421 	zs->zs_blocksize = 1ULL << bs;
1422 
1423 	/*
1424 	 * Set zap_phys_t fields
1425 	 */
1426 	zs->zs_num_leafs = zap_f_phys(zap)->zap_num_leafs;
1427 	zs->zs_num_entries = zap_f_phys(zap)->zap_num_entries;
1428 	zs->zs_num_blocks = zap_f_phys(zap)->zap_freeblk;
1429 	zs->zs_block_type = zap_f_phys(zap)->zap_block_type;
1430 	zs->zs_magic = zap_f_phys(zap)->zap_magic;
1431 	zs->zs_salt = zap_f_phys(zap)->zap_salt;
1432 
1433 	/*
1434 	 * Set zap_ptrtbl fields
1435 	 */
1436 	zs->zs_ptrtbl_len = 1ULL << zap_f_phys(zap)->zap_ptrtbl.zt_shift;
1437 	zs->zs_ptrtbl_nextblk = zap_f_phys(zap)->zap_ptrtbl.zt_nextblk;
1438 	zs->zs_ptrtbl_blks_copied =
1439 	    zap_f_phys(zap)->zap_ptrtbl.zt_blks_copied;
1440 	zs->zs_ptrtbl_zt_blk = zap_f_phys(zap)->zap_ptrtbl.zt_blk;
1441 	zs->zs_ptrtbl_zt_numblks = zap_f_phys(zap)->zap_ptrtbl.zt_numblks;
1442 	zs->zs_ptrtbl_zt_shift = zap_f_phys(zap)->zap_ptrtbl.zt_shift;
1443 
1444 	if (zap_f_phys(zap)->zap_ptrtbl.zt_numblks == 0) {
1445 		/* the ptrtbl is entirely in the header block. */
1446 		zap_stats_ptrtbl(zap, &ZAP_EMBEDDED_PTRTBL_ENT(zap, 0),
1447 		    1 << ZAP_EMBEDDED_PTRTBL_SHIFT(zap), zs);
1448 	} else {
1449 		dmu_prefetch_by_dnode(zap->zap_dnode, 0,
1450 		    zap_f_phys(zap)->zap_ptrtbl.zt_blk << bs,
1451 		    zap_f_phys(zap)->zap_ptrtbl.zt_numblks << bs,
1452 		    ZIO_PRIORITY_SYNC_READ);
1453 
1454 		for (int b = 0; b < zap_f_phys(zap)->zap_ptrtbl.zt_numblks;
1455 		    b++) {
1456 			dmu_buf_t *db;
1457 			int err;
1458 
1459 			err = dmu_buf_hold_by_dnode(zap->zap_dnode,
1460 			    (zap_f_phys(zap)->zap_ptrtbl.zt_blk + b) << bs,
1461 			    FTAG, &db, DMU_READ_NO_PREFETCH);
1462 			if (err == 0) {
1463 				zap_stats_ptrtbl(zap, db->db_data,
1464 				    1<<(bs-3), zs);
1465 				dmu_buf_rele(db, FTAG);
1466 			}
1467 		}
1468 	}
1469 }
1470 
1471 /*
1472  * Find last allocated block and update freeblk.
1473  */
1474 static void
1475 zap_trunc(zap_t *zap)
1476 {
1477 	uint64_t nentries;
1478 	uint64_t lastblk;
1479 
1480 	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
1481 
1482 	if (zap_f_phys(zap)->zap_ptrtbl.zt_blk > 0) {
1483 		/* External ptrtbl */
1484 		nentries = (1 << zap_f_phys(zap)->zap_ptrtbl.zt_shift);
1485 		lastblk = zap_f_phys(zap)->zap_ptrtbl.zt_blk +
1486 		    zap_f_phys(zap)->zap_ptrtbl.zt_numblks - 1;
1487 	} else {
1488 		/* Embedded ptrtbl */
1489 		nentries = (1 << ZAP_EMBEDDED_PTRTBL_SHIFT(zap));
1490 		lastblk = 0;
1491 	}
1492 
1493 	for (uint64_t idx = 0; idx < nentries; idx++) {
1494 		uint64_t blk;
1495 		if (zap_idx_to_blk(zap, idx, &blk) != 0)
1496 			return;
1497 		if (blk > lastblk)
1498 			lastblk = blk;
1499 	}
1500 
1501 	ASSERT3U(lastblk, <, zap_f_phys(zap)->zap_freeblk);
1502 
1503 	zap_f_phys(zap)->zap_freeblk = lastblk + 1;
1504 }
1505 
1506 /*
1507  * ZAP shrinking algorithm.
1508  *
1509  * We shrink ZAP recuresively removing empty leaves. We can remove an empty leaf
1510  * only if it has a sibling. Sibling leaves have the same prefix length and
1511  * their prefixes differ only by the least significant (sibling) bit. We require
1512  * both siblings to be empty. This eliminates a need to rehash the non-empty
1513  * remaining leaf. When we have removed one of two empty sibling, we set ptrtbl
1514  * entries of the removed leaf to point out to the remaining leaf. Prefix length
1515  * of the remaining leaf is decremented. As a result, it has a new prefix and it
1516  * might have a new sibling. So, we repeat the process.
1517  *
1518  * Steps:
1519  * 1. Check if a sibling leaf (sl) exists and it is empty.
1520  * 2. Release the leaf (l) if it has the sibling bit (slbit) equal to 1.
1521  * 3. Release the sibling (sl) to derefer it again with WRITER lock.
1522  * 4. Upgrade zapdir lock to WRITER (once).
1523  * 5. Derefer released leaves again.
1524  * 6. If it is needed, recheck whether both leaves are still siblings and empty.
1525  * 7. Set ptrtbl pointers of the removed leaf (slbit 1) to point out to blkid of
1526  * the remaining leaf (slbit 0).
1527  * 8. Free disk block of the removed leaf (dmu_free_range).
1528  * 9. Decrement prefix_len of the remaining leaf.
1529  * 10. Repeat the steps.
1530  */
1531 static int
1532 zap_shrink(zap_name_t *zn, zap_leaf_t *l, dmu_tx_t *tx)
1533 {
1534 	zap_t *zap = zn->zn_zap;
1535 	int64_t zt_shift = zap_f_phys(zap)->zap_ptrtbl.zt_shift;
1536 	uint64_t hash = zn->zn_hash;
1537 	uint64_t prefix = zap_leaf_phys(l)->l_hdr.lh_prefix;
1538 	uint64_t prefix_len = zap_leaf_phys(l)->l_hdr.lh_prefix_len;
1539 	boolean_t trunc = B_FALSE;
1540 	int err = 0;
1541 
1542 	ASSERT3U(zap_leaf_phys(l)->l_hdr.lh_nentries, ==, 0);
1543 	ASSERT3U(prefix_len, <=, zap_f_phys(zap)->zap_ptrtbl.zt_shift);
1544 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
1545 	ASSERT3U(ZAP_HASH_IDX(hash, prefix_len), ==, prefix);
1546 
1547 	boolean_t writer = B_FALSE;
1548 
1549 	/*
1550 	 * To avoid deadlock always deref leaves in the same order -
1551 	 * sibling 0 first, then sibling 1.
1552 	 */
1553 	while (prefix_len) {
1554 		zap_leaf_t *sl;
1555 		int64_t prefix_diff = zt_shift - prefix_len;
1556 		uint64_t sl_prefix = prefix ^ 1;
1557 		uint64_t sl_hash = ZAP_PREFIX_HASH(sl_prefix, prefix_len);
1558 		int slbit = prefix & 1;
1559 
1560 		ASSERT3U(zap_leaf_phys(l)->l_hdr.lh_nentries, ==, 0);
1561 
1562 		/*
1563 		 * Check if there is a sibling by reading ptrtbl ptrs.
1564 		 */
1565 		if (check_sibling_ptrtbl_range(zap, sl_prefix, prefix_len) == 0)
1566 			break;
1567 
1568 		/*
1569 		 * sibling 1, unlock it - we haven't yet dereferenced sibling 0.
1570 		 */
1571 		if (slbit == 1) {
1572 			zap_put_leaf(l);
1573 			l = NULL;
1574 		}
1575 
1576 		/*
1577 		 * Dereference sibling leaf and check if it is empty.
1578 		 */
1579 		if ((err = zap_deref_leaf(zap, sl_hash, tx, RW_READER,
1580 		    &sl)) != 0)
1581 			break;
1582 
1583 		ASSERT3U(ZAP_HASH_IDX(sl_hash, prefix_len), ==, sl_prefix);
1584 
1585 		/*
1586 		 * Check if we have a sibling and it is empty.
1587 		 */
1588 		if (zap_leaf_phys(sl)->l_hdr.lh_prefix_len != prefix_len ||
1589 		    zap_leaf_phys(sl)->l_hdr.lh_nentries != 0) {
1590 			zap_put_leaf(sl);
1591 			break;
1592 		}
1593 
1594 		zap_put_leaf(sl);
1595 
1596 		/*
1597 		 * If there two empty sibling, we have work to do, so
1598 		 * we need to lock ZAP ptrtbl as WRITER.
1599 		 */
1600 		if (!writer && (writer = zap_tryupgradedir(zap, tx)) == 0) {
1601 			/* We failed to upgrade */
1602 			if (l != NULL) {
1603 				zap_put_leaf(l);
1604 				l = NULL;
1605 			}
1606 
1607 			/*
1608 			 * Usually, the right way to upgrade from a READER lock
1609 			 * to a WRITER lock is to call zap_unlockdir() and
1610 			 * zap_lockdir(), but we do not have a tag. Instead,
1611 			 * we do it in more sophisticated way.
1612 			 */
1613 			rw_exit(&zap->zap_rwlock);
1614 			rw_enter(&zap->zap_rwlock, RW_WRITER);
1615 			dmu_buf_will_dirty(zap->zap_dbuf, tx);
1616 
1617 			zt_shift = zap_f_phys(zap)->zap_ptrtbl.zt_shift;
1618 			writer = B_TRUE;
1619 		}
1620 
1621 		/*
1622 		 * Here we have WRITER lock for ptrtbl.
1623 		 * Now, we need a WRITER lock for both siblings leaves.
1624 		 * Also, we have to recheck if the leaves are still siblings
1625 		 * and still empty.
1626 		 */
1627 		if (l == NULL) {
1628 			/* sibling 0 */
1629 			if ((err = zap_deref_leaf(zap, (slbit ? sl_hash : hash),
1630 			    tx, RW_WRITER, &l)) != 0)
1631 				break;
1632 
1633 			/*
1634 			 * The leaf isn't empty anymore or
1635 			 * it was shrunk/split while our locks were down.
1636 			 */
1637 			if (zap_leaf_phys(l)->l_hdr.lh_nentries != 0 ||
1638 			    zap_leaf_phys(l)->l_hdr.lh_prefix_len != prefix_len)
1639 				break;
1640 		}
1641 
1642 		/* sibling 1 */
1643 		if ((err = zap_deref_leaf(zap, (slbit ? hash : sl_hash), tx,
1644 		    RW_WRITER, &sl)) != 0)
1645 			break;
1646 
1647 		/*
1648 		 * The leaf isn't empty anymore or
1649 		 * it was shrunk/split while our locks were down.
1650 		 */
1651 		if (zap_leaf_phys(sl)->l_hdr.lh_nentries != 0 ||
1652 		    zap_leaf_phys(sl)->l_hdr.lh_prefix_len != prefix_len) {
1653 			zap_put_leaf(sl);
1654 			break;
1655 		}
1656 
1657 		/* If we have gotten here, we have a leaf to collapse */
1658 		uint64_t idx = (slbit ? prefix : sl_prefix) << prefix_diff;
1659 		uint64_t nptrs = (1ULL << prefix_diff);
1660 		uint64_t sl_blkid = sl->l_blkid;
1661 
1662 		/*
1663 		 * Set ptrtbl entries to point out to the slibling 0 blkid
1664 		 */
1665 		if ((err = zap_set_idx_range_to_blk(zap, idx, nptrs, l->l_blkid,
1666 		    tx)) != 0) {
1667 			zap_put_leaf(sl);
1668 			break;
1669 		}
1670 
1671 		/*
1672 		 * Free sibling 1 disk block.
1673 		 */
1674 		int bs = FZAP_BLOCK_SHIFT(zap);
1675 		if (sl_blkid == zap_f_phys(zap)->zap_freeblk - 1)
1676 			trunc = B_TRUE;
1677 
1678 		(void) dmu_free_range(zap->zap_objset, zap->zap_object,
1679 		    sl_blkid << bs, 1 << bs, tx);
1680 		zap_put_leaf(sl);
1681 
1682 		zap_f_phys(zap)->zap_num_leafs--;
1683 
1684 		/*
1685 		 * Update prefix and prefix_len.
1686 		 */
1687 		zap_leaf_phys(l)->l_hdr.lh_prefix >>= 1;
1688 		zap_leaf_phys(l)->l_hdr.lh_prefix_len--;
1689 
1690 		prefix = zap_leaf_phys(l)->l_hdr.lh_prefix;
1691 		prefix_len = zap_leaf_phys(l)->l_hdr.lh_prefix_len;
1692 	}
1693 
1694 	if (trunc)
1695 		zap_trunc(zap);
1696 
1697 	if (l != NULL)
1698 		zap_put_leaf(l);
1699 
1700 	return (err);
1701 }
1702 
1703 /* CSTYLED */
1704 ZFS_MODULE_PARAM(zfs, , zap_iterate_prefetch, INT, ZMOD_RW,
1705 	"When iterating ZAP object, prefetch it");
1706 
1707 /* CSTYLED */
1708 ZFS_MODULE_PARAM(zfs, , zap_shrink_enabled, INT, ZMOD_RW,
1709 	"Enable ZAP shrinking");
1710