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