xref: /freebsd/sys/contrib/openzfs/module/zfs/zap.c (revision 61145dc2b94f12f6a47344fb9aac702321880e43)
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)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 {
883 	zap_leaf_t *l;
884 	zap_entry_handle_t zeh;
885 
886 	int err = fzap_checkname(zn);
887 	if (err != 0)
888 		return (err);
889 
890 	err = zap_deref_leaf(zn->zn_zap, zn->zn_hash, NULL, RW_READER, &l);
891 	if (err != 0)
892 		return (err);
893 	err = zap_leaf_lookup(l, zn, &zeh);
894 	if (err == 0) {
895 		if ((err = fzap_checksize(integer_size, num_integers)) != 0) {
896 			zap_put_leaf(l);
897 			return (err);
898 		}
899 
900 		err = zap_entry_read(&zeh, integer_size, num_integers, buf);
901 		(void) zap_entry_read_name(zn->zn_zap, &zeh, rn_len, realname);
902 		if (ncp) {
903 			*ncp = zap_entry_normalization_conflict(&zeh,
904 			    zn, NULL, zn->zn_zap);
905 		}
906 	}
907 
908 	zap_put_leaf(l);
909 	return (err);
910 }
911 
912 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)913 fzap_add_cd(zap_name_t *zn,
914     uint64_t integer_size, uint64_t num_integers,
915     const void *val, uint32_t cd, const void *tag, dmu_tx_t *tx)
916 {
917 	zap_leaf_t *l;
918 	int err;
919 	zap_entry_handle_t zeh;
920 	zap_t *zap = zn->zn_zap;
921 
922 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
923 	ASSERT(!zap->zap_ismicro);
924 	ASSERT(fzap_check(zn, integer_size, num_integers) == 0);
925 
926 	err = zap_deref_leaf(zap, zn->zn_hash, tx, RW_WRITER, &l);
927 	if (err != 0)
928 		return (err);
929 retry:
930 	err = zap_leaf_lookup(l, zn, &zeh);
931 	if (err == 0) {
932 		err = SET_ERROR(EEXIST);
933 		goto out;
934 	}
935 	if (err != ENOENT)
936 		goto out;
937 
938 	err = zap_entry_create(l, zn, cd,
939 	    integer_size, num_integers, val, &zeh);
940 
941 	if (err == 0) {
942 		zap_increment_num_entries(zap, 1, tx);
943 	} else if (err == EAGAIN) {
944 		err = zap_expand_leaf(zn, l, tag, tx, &l);
945 		zap = zn->zn_zap;	/* zap_expand_leaf() may change zap */
946 		if (err == 0)
947 			goto retry;
948 	}
949 
950 out:
951 	if (l != NULL) {
952 		if (err == ENOSPC)
953 			zap_put_leaf(l);
954 		else
955 			zap_put_leaf_maybe_grow_ptrtbl(zn, l, tag, tx);
956 	}
957 	return (err);
958 }
959 
960 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)961 fzap_add(zap_name_t *zn,
962     uint64_t integer_size, uint64_t num_integers,
963     const void *val, const void *tag, dmu_tx_t *tx)
964 {
965 	int err = fzap_check(zn, integer_size, num_integers);
966 	if (err != 0)
967 		return (err);
968 
969 	return (fzap_add_cd(zn, integer_size, num_integers,
970 	    val, ZAP_NEED_CD, tag, tx));
971 }
972 
973 int
fzap_update(zap_name_t * zn,int integer_size,uint64_t num_integers,const void * val,const void * tag,dmu_tx_t * tx)974 fzap_update(zap_name_t *zn,
975     int integer_size, uint64_t num_integers, const void *val,
976     const void *tag, dmu_tx_t *tx)
977 {
978 	zap_leaf_t *l;
979 	int err;
980 	boolean_t create;
981 	zap_entry_handle_t zeh;
982 	zap_t *zap = zn->zn_zap;
983 
984 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
985 	err = fzap_check(zn, integer_size, num_integers);
986 	if (err != 0)
987 		return (err);
988 
989 	err = zap_deref_leaf(zap, zn->zn_hash, tx, RW_WRITER, &l);
990 	if (err != 0)
991 		return (err);
992 retry:
993 	err = zap_leaf_lookup(l, zn, &zeh);
994 	create = (err == ENOENT);
995 	ASSERT(err == 0 || err == ENOENT);
996 
997 	if (create) {
998 		err = zap_entry_create(l, zn, ZAP_NEED_CD,
999 		    integer_size, num_integers, val, &zeh);
1000 		if (err == 0)
1001 			zap_increment_num_entries(zap, 1, tx);
1002 	} else {
1003 		err = zap_entry_update(&zeh, integer_size, num_integers, val);
1004 	}
1005 
1006 	if (err == EAGAIN) {
1007 		err = zap_expand_leaf(zn, l, tag, tx, &l);
1008 		zap = zn->zn_zap;	/* zap_expand_leaf() may change zap */
1009 		if (err == 0)
1010 			goto retry;
1011 	}
1012 
1013 	if (l != NULL) {
1014 		if (err == ENOSPC)
1015 			zap_put_leaf(l);
1016 		else
1017 			zap_put_leaf_maybe_grow_ptrtbl(zn, l, tag, tx);
1018 	}
1019 	return (err);
1020 }
1021 
1022 int
fzap_length(zap_name_t * zn,uint64_t * integer_size,uint64_t * num_integers)1023 fzap_length(zap_name_t *zn,
1024     uint64_t *integer_size, uint64_t *num_integers)
1025 {
1026 	zap_leaf_t *l;
1027 	int err;
1028 	zap_entry_handle_t zeh;
1029 
1030 	err = zap_deref_leaf(zn->zn_zap, zn->zn_hash, NULL, RW_READER, &l);
1031 	if (err != 0)
1032 		return (err);
1033 	err = zap_leaf_lookup(l, zn, &zeh);
1034 	if (err != 0)
1035 		goto out;
1036 
1037 	if (integer_size != NULL)
1038 		*integer_size = zeh.zeh_integer_size;
1039 	if (num_integers != NULL)
1040 		*num_integers = zeh.zeh_num_integers;
1041 out:
1042 	zap_put_leaf(l);
1043 	return (err);
1044 }
1045 
1046 int
fzap_remove(zap_name_t * zn,dmu_tx_t * tx)1047 fzap_remove(zap_name_t *zn, dmu_tx_t *tx)
1048 {
1049 	zap_leaf_t *l;
1050 	int err;
1051 	zap_entry_handle_t zeh;
1052 
1053 	err = zap_deref_leaf(zn->zn_zap, zn->zn_hash, tx, RW_WRITER, &l);
1054 	if (err != 0)
1055 		return (err);
1056 	err = zap_leaf_lookup(l, zn, &zeh);
1057 	if (err == 0) {
1058 		zap_entry_remove(&zeh);
1059 		zap_increment_num_entries(zn->zn_zap, -1, tx);
1060 
1061 		if (zap_leaf_phys(l)->l_hdr.lh_nentries == 0 &&
1062 		    zap_shrink_enabled)
1063 			return (zap_shrink(zn, l, tx));
1064 	}
1065 	zap_put_leaf(l);
1066 	return (err);
1067 }
1068 
1069 void
fzap_prefetch(zap_name_t * zn)1070 fzap_prefetch(zap_name_t *zn)
1071 {
1072 	uint64_t blk;
1073 	zap_t *zap = zn->zn_zap;
1074 
1075 	uint64_t idx = ZAP_HASH_IDX(zn->zn_hash,
1076 	    zap_f_phys(zap)->zap_ptrtbl.zt_shift);
1077 	if (zap_idx_to_blk(zap, idx, &blk) != 0)
1078 		return;
1079 	int bs = FZAP_BLOCK_SHIFT(zap);
1080 	dmu_prefetch_by_dnode(zap->zap_dnode, 0, blk << bs, 1 << bs,
1081 	    ZIO_PRIORITY_SYNC_READ);
1082 }
1083 
1084 /*
1085  * Helper functions for consumers.
1086  */
1087 
1088 uint64_t
zap_create_link(objset_t * os,dmu_object_type_t ot,uint64_t parent_obj,const char * name,dmu_tx_t * tx)1089 zap_create_link(objset_t *os, dmu_object_type_t ot, uint64_t parent_obj,
1090     const char *name, dmu_tx_t *tx)
1091 {
1092 	return (zap_create_link_dnsize(os, ot, parent_obj, name, 0, tx));
1093 }
1094 
1095 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)1096 zap_create_link_dnsize(objset_t *os, dmu_object_type_t ot, uint64_t parent_obj,
1097     const char *name, int dnodesize, dmu_tx_t *tx)
1098 {
1099 	uint64_t new_obj;
1100 
1101 	new_obj = zap_create_dnsize(os, ot, DMU_OT_NONE, 0, dnodesize, tx);
1102 	VERIFY(new_obj != 0);
1103 	VERIFY0(zap_add(os, parent_obj, name, sizeof (uint64_t), 1, &new_obj,
1104 	    tx));
1105 
1106 	return (new_obj);
1107 }
1108 
1109 int
zap_value_search(objset_t * os,uint64_t zapobj,uint64_t value,uint64_t mask,char * name,uint64_t namelen)1110 zap_value_search(objset_t *os, uint64_t zapobj, uint64_t value, uint64_t mask,
1111     char *name, uint64_t namelen)
1112 {
1113 	zap_cursor_t zc;
1114 	int err;
1115 
1116 	if (mask == 0)
1117 		mask = -1ULL;
1118 
1119 	zap_attribute_t *za = zap_attribute_long_alloc();
1120 	for (zap_cursor_init(&zc, os, zapobj);
1121 	    (err = zap_cursor_retrieve(&zc, za)) == 0;
1122 	    zap_cursor_advance(&zc)) {
1123 		if ((za->za_first_integer & mask) == (value & mask)) {
1124 			if (strlcpy(name, za->za_name, namelen) >= namelen)
1125 				err = SET_ERROR(ENAMETOOLONG);
1126 			break;
1127 		}
1128 	}
1129 	zap_cursor_fini(&zc);
1130 	zap_attribute_free(za);
1131 	return (err);
1132 }
1133 
1134 int
zap_join(objset_t * os,uint64_t fromobj,uint64_t intoobj,dmu_tx_t * tx)1135 zap_join(objset_t *os, uint64_t fromobj, uint64_t intoobj, dmu_tx_t *tx)
1136 {
1137 	zap_cursor_t zc;
1138 	int err = 0;
1139 
1140 	zap_attribute_t *za = zap_attribute_long_alloc();
1141 	for (zap_cursor_init(&zc, os, fromobj);
1142 	    zap_cursor_retrieve(&zc, za) == 0;
1143 	    (void) zap_cursor_advance(&zc)) {
1144 		if (za->za_integer_length != 8 || za->za_num_integers != 1) {
1145 			err = SET_ERROR(EINVAL);
1146 			break;
1147 		}
1148 		err = zap_add(os, intoobj, za->za_name,
1149 		    8, 1, &za->za_first_integer, tx);
1150 		if (err != 0)
1151 			break;
1152 	}
1153 	zap_cursor_fini(&zc);
1154 	zap_attribute_free(za);
1155 	return (err);
1156 }
1157 
1158 int
zap_join_key(objset_t * os,uint64_t fromobj,uint64_t intoobj,uint64_t value,dmu_tx_t * tx)1159 zap_join_key(objset_t *os, uint64_t fromobj, uint64_t intoobj,
1160     uint64_t value, dmu_tx_t *tx)
1161 {
1162 	zap_cursor_t zc;
1163 	int err = 0;
1164 
1165 	zap_attribute_t *za = zap_attribute_long_alloc();
1166 	for (zap_cursor_init(&zc, os, fromobj);
1167 	    zap_cursor_retrieve(&zc, za) == 0;
1168 	    (void) zap_cursor_advance(&zc)) {
1169 		if (za->za_integer_length != 8 || za->za_num_integers != 1) {
1170 			err = SET_ERROR(EINVAL);
1171 			break;
1172 		}
1173 		err = zap_add(os, intoobj, za->za_name,
1174 		    8, 1, &value, tx);
1175 		if (err != 0)
1176 			break;
1177 	}
1178 	zap_cursor_fini(&zc);
1179 	zap_attribute_free(za);
1180 	return (err);
1181 }
1182 
1183 int
zap_join_increment(objset_t * os,uint64_t fromobj,uint64_t intoobj,dmu_tx_t * tx)1184 zap_join_increment(objset_t *os, uint64_t fromobj, uint64_t intoobj,
1185     dmu_tx_t *tx)
1186 {
1187 	zap_cursor_t zc;
1188 	int err = 0;
1189 
1190 	zap_attribute_t *za = zap_attribute_long_alloc();
1191 	for (zap_cursor_init(&zc, os, fromobj);
1192 	    zap_cursor_retrieve(&zc, za) == 0;
1193 	    (void) zap_cursor_advance(&zc)) {
1194 		uint64_t delta = 0;
1195 
1196 		if (za->za_integer_length != 8 || za->za_num_integers != 1) {
1197 			err = SET_ERROR(EINVAL);
1198 			break;
1199 		}
1200 
1201 		err = zap_lookup(os, intoobj, za->za_name, 8, 1, &delta);
1202 		if (err != 0 && err != ENOENT)
1203 			break;
1204 		delta += za->za_first_integer;
1205 		err = zap_update(os, intoobj, za->za_name, 8, 1, &delta, tx);
1206 		if (err != 0)
1207 			break;
1208 	}
1209 	zap_cursor_fini(&zc);
1210 	zap_attribute_free(za);
1211 	return (err);
1212 }
1213 
1214 int
zap_add_int(objset_t * os,uint64_t obj,uint64_t value,dmu_tx_t * tx)1215 zap_add_int(objset_t *os, uint64_t obj, uint64_t value, dmu_tx_t *tx)
1216 {
1217 	char name[20];
1218 
1219 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)value);
1220 	return (zap_add(os, obj, name, 8, 1, &value, tx));
1221 }
1222 
1223 int
zap_remove_int(objset_t * os,uint64_t obj,uint64_t value,dmu_tx_t * tx)1224 zap_remove_int(objset_t *os, uint64_t obj, uint64_t value, dmu_tx_t *tx)
1225 {
1226 	char name[20];
1227 
1228 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)value);
1229 	return (zap_remove(os, obj, name, tx));
1230 }
1231 
1232 int
zap_lookup_int(objset_t * os,uint64_t obj,uint64_t value)1233 zap_lookup_int(objset_t *os, uint64_t obj, uint64_t value)
1234 {
1235 	char name[20];
1236 
1237 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)value);
1238 	return (zap_lookup(os, obj, name, 8, 1, &value));
1239 }
1240 
1241 int
zap_add_int_key(objset_t * os,uint64_t obj,uint64_t key,uint64_t value,dmu_tx_t * tx)1242 zap_add_int_key(objset_t *os, uint64_t obj,
1243     uint64_t key, uint64_t value, dmu_tx_t *tx)
1244 {
1245 	char name[20];
1246 
1247 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)key);
1248 	return (zap_add(os, obj, name, 8, 1, &value, tx));
1249 }
1250 
1251 int
zap_update_int_key(objset_t * os,uint64_t obj,uint64_t key,uint64_t value,dmu_tx_t * tx)1252 zap_update_int_key(objset_t *os, uint64_t obj,
1253     uint64_t key, uint64_t value, dmu_tx_t *tx)
1254 {
1255 	char name[20];
1256 
1257 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)key);
1258 	return (zap_update(os, obj, name, 8, 1, &value, tx));
1259 }
1260 
1261 int
zap_lookup_int_key(objset_t * os,uint64_t obj,uint64_t key,uint64_t * valuep)1262 zap_lookup_int_key(objset_t *os, uint64_t obj, uint64_t key, uint64_t *valuep)
1263 {
1264 	char name[20];
1265 
1266 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)key);
1267 	return (zap_lookup(os, obj, name, 8, 1, valuep));
1268 }
1269 
1270 int
zap_increment(objset_t * os,uint64_t obj,const char * name,int64_t delta,dmu_tx_t * tx)1271 zap_increment(objset_t *os, uint64_t obj, const char *name, int64_t delta,
1272     dmu_tx_t *tx)
1273 {
1274 	uint64_t value = 0;
1275 
1276 	if (delta == 0)
1277 		return (0);
1278 
1279 	int err = zap_lookup(os, obj, name, 8, 1, &value);
1280 	if (err != 0 && err != ENOENT)
1281 		return (err);
1282 	value += delta;
1283 	if (value == 0)
1284 		err = zap_remove(os, obj, name, tx);
1285 	else
1286 		err = zap_update(os, obj, name, 8, 1, &value, tx);
1287 	return (err);
1288 }
1289 
1290 int
zap_increment_int(objset_t * os,uint64_t obj,uint64_t key,int64_t delta,dmu_tx_t * tx)1291 zap_increment_int(objset_t *os, uint64_t obj, uint64_t key, int64_t delta,
1292     dmu_tx_t *tx)
1293 {
1294 	char name[20];
1295 
1296 	(void) snprintf(name, sizeof (name), "%llx", (longlong_t)key);
1297 	return (zap_increment(os, obj, name, delta, tx));
1298 }
1299 
1300 /*
1301  * Routines for iterating over the attributes.
1302  */
1303 
1304 int
fzap_cursor_retrieve(zap_t * zap,zap_cursor_t * zc,zap_attribute_t * za)1305 fzap_cursor_retrieve(zap_t *zap, zap_cursor_t *zc, zap_attribute_t *za)
1306 {
1307 	int err = ENOENT;
1308 	zap_entry_handle_t zeh;
1309 	zap_leaf_t *l;
1310 
1311 	/* retrieve the next entry at or after zc_hash/zc_cd */
1312 	/* if no entry, return ENOENT */
1313 
1314 	/*
1315 	 * If we are reading from the beginning, we're almost certain to
1316 	 * iterate over the entire ZAP object.  If there are multiple leaf
1317 	 * blocks (freeblk > 2), prefetch the whole object (up to
1318 	 * dmu_prefetch_max bytes), so that we read the leaf blocks
1319 	 * concurrently. (Unless noprefetch was requested via
1320 	 * zap_cursor_init_noprefetch()).
1321 	 */
1322 	if (zc->zc_hash == 0 && zap_iterate_prefetch &&
1323 	    zc->zc_prefetch && zap_f_phys(zap)->zap_freeblk > 2) {
1324 		dmu_prefetch_by_dnode(zap->zap_dnode, 0, 0,
1325 		    zap_f_phys(zap)->zap_freeblk << FZAP_BLOCK_SHIFT(zap),
1326 		    ZIO_PRIORITY_ASYNC_READ);
1327 	}
1328 
1329 	if (zc->zc_leaf) {
1330 		rw_enter(&zc->zc_leaf->l_rwlock, RW_READER);
1331 
1332 		/*
1333 		 * The leaf was either shrunk or split.
1334 		 */
1335 		if ((zap_leaf_phys(zc->zc_leaf)->l_hdr.lh_block_type == 0) ||
1336 		    (ZAP_HASH_IDX(zc->zc_hash,
1337 		    zap_leaf_phys(zc->zc_leaf)->l_hdr.lh_prefix_len) !=
1338 		    zap_leaf_phys(zc->zc_leaf)->l_hdr.lh_prefix)) {
1339 			zap_put_leaf(zc->zc_leaf);
1340 			zc->zc_leaf = NULL;
1341 		}
1342 	}
1343 
1344 again:
1345 	if (zc->zc_leaf == NULL) {
1346 		err = zap_deref_leaf(zap, zc->zc_hash, NULL, RW_READER,
1347 		    &zc->zc_leaf);
1348 		if (err != 0)
1349 			return (err);
1350 	}
1351 	l = zc->zc_leaf;
1352 
1353 	err = zap_leaf_lookup_closest(l, zc->zc_hash, zc->zc_cd, &zeh);
1354 
1355 	if (err == ENOENT) {
1356 		if (zap_leaf_phys(l)->l_hdr.lh_prefix_len == 0) {
1357 			zc->zc_hash = -1ULL;
1358 			zc->zc_cd = 0;
1359 		} else {
1360 			uint64_t nocare = (1ULL <<
1361 			    (64 - zap_leaf_phys(l)->l_hdr.lh_prefix_len)) - 1;
1362 
1363 			zc->zc_hash = (zc->zc_hash & ~nocare) + nocare + 1;
1364 			zc->zc_cd = 0;
1365 
1366 			if (zc->zc_hash == 0) {
1367 				zc->zc_hash = -1ULL;
1368 			} else {
1369 				zap_put_leaf(zc->zc_leaf);
1370 				zc->zc_leaf = NULL;
1371 				goto again;
1372 			}
1373 		}
1374 	}
1375 
1376 	if (err == 0) {
1377 		zc->zc_hash = zeh.zeh_hash;
1378 		zc->zc_cd = zeh.zeh_cd;
1379 		za->za_integer_length = zeh.zeh_integer_size;
1380 		za->za_num_integers = zeh.zeh_num_integers;
1381 		if (zeh.zeh_num_integers == 0) {
1382 			za->za_first_integer = 0;
1383 		} else {
1384 			err = zap_entry_read(&zeh, 8, 1, &za->za_first_integer);
1385 			ASSERT(err == 0 || err == EOVERFLOW);
1386 		}
1387 		err = zap_entry_read_name(zap, &zeh,
1388 		    za->za_name_len, za->za_name);
1389 		ASSERT(err == 0);
1390 
1391 		za->za_normalization_conflict =
1392 		    zap_entry_normalization_conflict(&zeh,
1393 		    NULL, za->za_name, zap);
1394 	}
1395 	rw_exit(&zc->zc_leaf->l_rwlock);
1396 	return (err);
1397 }
1398 
1399 static void
zap_stats_ptrtbl(zap_t * zap,uint64_t * tbl,int len,zap_stats_t * zs)1400 zap_stats_ptrtbl(zap_t *zap, uint64_t *tbl, int len, zap_stats_t *zs)
1401 {
1402 	uint64_t lastblk = 0;
1403 
1404 	/*
1405 	 * NB: if a leaf has more pointers than an entire ptrtbl block
1406 	 * can hold, then it'll be accounted for more than once, since
1407 	 * we won't have lastblk.
1408 	 */
1409 	for (int i = 0; i < len; i++) {
1410 		zap_leaf_t *l;
1411 
1412 		if (tbl[i] == lastblk)
1413 			continue;
1414 		lastblk = tbl[i];
1415 
1416 		int err = zap_get_leaf_byblk(zap, tbl[i], NULL, RW_READER, &l);
1417 		if (err == 0) {
1418 			zap_leaf_stats(zap, l, zs);
1419 			zap_put_leaf(l);
1420 		}
1421 	}
1422 }
1423 
1424 void
fzap_get_stats(zap_t * zap,zap_stats_t * zs)1425 fzap_get_stats(zap_t *zap, zap_stats_t *zs)
1426 {
1427 	int bs = FZAP_BLOCK_SHIFT(zap);
1428 	zs->zs_blocksize = 1ULL << bs;
1429 
1430 	/*
1431 	 * Set zap_phys_t fields
1432 	 */
1433 	zs->zs_num_leafs = zap_f_phys(zap)->zap_num_leafs;
1434 	zs->zs_num_entries = zap_f_phys(zap)->zap_num_entries;
1435 	zs->zs_num_blocks = zap_f_phys(zap)->zap_freeblk;
1436 	zs->zs_block_type = zap_f_phys(zap)->zap_block_type;
1437 	zs->zs_magic = zap_f_phys(zap)->zap_magic;
1438 	zs->zs_salt = zap_f_phys(zap)->zap_salt;
1439 
1440 	/*
1441 	 * Set zap_ptrtbl fields
1442 	 */
1443 	zs->zs_ptrtbl_len = 1ULL << zap_f_phys(zap)->zap_ptrtbl.zt_shift;
1444 	zs->zs_ptrtbl_nextblk = zap_f_phys(zap)->zap_ptrtbl.zt_nextblk;
1445 	zs->zs_ptrtbl_blks_copied =
1446 	    zap_f_phys(zap)->zap_ptrtbl.zt_blks_copied;
1447 	zs->zs_ptrtbl_zt_blk = zap_f_phys(zap)->zap_ptrtbl.zt_blk;
1448 	zs->zs_ptrtbl_zt_numblks = zap_f_phys(zap)->zap_ptrtbl.zt_numblks;
1449 	zs->zs_ptrtbl_zt_shift = zap_f_phys(zap)->zap_ptrtbl.zt_shift;
1450 
1451 	if (zap_f_phys(zap)->zap_ptrtbl.zt_numblks == 0) {
1452 		/* the ptrtbl is entirely in the header block. */
1453 		zap_stats_ptrtbl(zap, &ZAP_EMBEDDED_PTRTBL_ENT(zap, 0),
1454 		    1 << ZAP_EMBEDDED_PTRTBL_SHIFT(zap), zs);
1455 	} else {
1456 		dmu_prefetch_by_dnode(zap->zap_dnode, 0,
1457 		    zap_f_phys(zap)->zap_ptrtbl.zt_blk << bs,
1458 		    zap_f_phys(zap)->zap_ptrtbl.zt_numblks << bs,
1459 		    ZIO_PRIORITY_SYNC_READ);
1460 
1461 		for (int b = 0; b < zap_f_phys(zap)->zap_ptrtbl.zt_numblks;
1462 		    b++) {
1463 			dmu_buf_t *db;
1464 			int err;
1465 
1466 			err = dmu_buf_hold_by_dnode(zap->zap_dnode,
1467 			    (zap_f_phys(zap)->zap_ptrtbl.zt_blk + b) << bs,
1468 			    FTAG, &db, DMU_READ_NO_PREFETCH);
1469 			if (err == 0) {
1470 				zap_stats_ptrtbl(zap, db->db_data,
1471 				    1<<(bs-3), zs);
1472 				dmu_buf_rele(db, FTAG);
1473 			}
1474 		}
1475 	}
1476 }
1477 
1478 /*
1479  * Find last allocated block and update freeblk.
1480  */
1481 static void
zap_trunc(zap_t * zap)1482 zap_trunc(zap_t *zap)
1483 {
1484 	uint64_t nentries;
1485 	uint64_t lastblk;
1486 
1487 	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
1488 
1489 	if (zap_f_phys(zap)->zap_ptrtbl.zt_blk > 0) {
1490 		/* External ptrtbl */
1491 		nentries = (1 << zap_f_phys(zap)->zap_ptrtbl.zt_shift);
1492 		lastblk = zap_f_phys(zap)->zap_ptrtbl.zt_blk +
1493 		    zap_f_phys(zap)->zap_ptrtbl.zt_numblks - 1;
1494 	} else {
1495 		/* Embedded ptrtbl */
1496 		nentries = (1 << ZAP_EMBEDDED_PTRTBL_SHIFT(zap));
1497 		lastblk = 0;
1498 	}
1499 
1500 	for (uint64_t idx = 0; idx < nentries; idx++) {
1501 		uint64_t blk;
1502 		if (zap_idx_to_blk(zap, idx, &blk) != 0)
1503 			return;
1504 		if (blk > lastblk)
1505 			lastblk = blk;
1506 	}
1507 
1508 	ASSERT3U(lastblk, <, zap_f_phys(zap)->zap_freeblk);
1509 
1510 	zap_f_phys(zap)->zap_freeblk = lastblk + 1;
1511 }
1512 
1513 /*
1514  * ZAP shrinking algorithm.
1515  *
1516  * We shrink ZAP recuresively removing empty leaves. We can remove an empty leaf
1517  * only if it has a sibling. Sibling leaves have the same prefix length and
1518  * their prefixes differ only by the least significant (sibling) bit. We require
1519  * both siblings to be empty. This eliminates a need to rehash the non-empty
1520  * remaining leaf. When we have removed one of two empty sibling, we set ptrtbl
1521  * entries of the removed leaf to point out to the remaining leaf. Prefix length
1522  * of the remaining leaf is decremented. As a result, it has a new prefix and it
1523  * might have a new sibling. So, we repeat the process.
1524  *
1525  * Steps:
1526  * 1. Check if a sibling leaf (sl) exists and it is empty.
1527  * 2. Release the leaf (l) if it has the sibling bit (slbit) equal to 1.
1528  * 3. Release the sibling (sl) to derefer it again with WRITER lock.
1529  * 4. Upgrade zapdir lock to WRITER (once).
1530  * 5. Derefer released leaves again.
1531  * 6. If it is needed, recheck whether both leaves are still siblings and empty.
1532  * 7. Set ptrtbl pointers of the removed leaf (slbit 1) to point out to blkid of
1533  * the remaining leaf (slbit 0).
1534  * 8. Free disk block of the removed leaf (dmu_free_range).
1535  * 9. Decrement prefix_len of the remaining leaf.
1536  * 10. Repeat the steps.
1537  */
1538 static int
zap_shrink(zap_name_t * zn,zap_leaf_t * l,dmu_tx_t * tx)1539 zap_shrink(zap_name_t *zn, zap_leaf_t *l, dmu_tx_t *tx)
1540 {
1541 	zap_t *zap = zn->zn_zap;
1542 	int64_t zt_shift = zap_f_phys(zap)->zap_ptrtbl.zt_shift;
1543 	uint64_t hash = zn->zn_hash;
1544 	uint64_t prefix = zap_leaf_phys(l)->l_hdr.lh_prefix;
1545 	uint64_t prefix_len = zap_leaf_phys(l)->l_hdr.lh_prefix_len;
1546 	boolean_t trunc = B_FALSE;
1547 	int err = 0;
1548 
1549 	ASSERT3U(zap_leaf_phys(l)->l_hdr.lh_nentries, ==, 0);
1550 	ASSERT3U(prefix_len, <=, zap_f_phys(zap)->zap_ptrtbl.zt_shift);
1551 	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
1552 	ASSERT3U(ZAP_HASH_IDX(hash, prefix_len), ==, prefix);
1553 
1554 	boolean_t writer = B_FALSE;
1555 
1556 	/*
1557 	 * To avoid deadlock always deref leaves in the same order -
1558 	 * sibling 0 first, then sibling 1.
1559 	 */
1560 	while (prefix_len) {
1561 		zap_leaf_t *sl;
1562 		int64_t prefix_diff = zt_shift - prefix_len;
1563 		uint64_t sl_prefix = prefix ^ 1;
1564 		uint64_t sl_hash = ZAP_PREFIX_HASH(sl_prefix, prefix_len);
1565 		int slbit = prefix & 1;
1566 
1567 		ASSERT3U(zap_leaf_phys(l)->l_hdr.lh_nentries, ==, 0);
1568 
1569 		/*
1570 		 * Check if there is a sibling by reading ptrtbl ptrs.
1571 		 */
1572 		if (check_sibling_ptrtbl_range(zap, sl_prefix, prefix_len) == 0)
1573 			break;
1574 
1575 		/*
1576 		 * sibling 1, unlock it - we haven't yet dereferenced sibling 0.
1577 		 */
1578 		if (slbit == 1) {
1579 			zap_put_leaf(l);
1580 			l = NULL;
1581 		}
1582 
1583 		/*
1584 		 * Dereference sibling leaf and check if it is empty.
1585 		 */
1586 		if ((err = zap_deref_leaf(zap, sl_hash, tx, RW_READER,
1587 		    &sl)) != 0)
1588 			break;
1589 
1590 		ASSERT3U(ZAP_HASH_IDX(sl_hash, prefix_len), ==, sl_prefix);
1591 
1592 		/*
1593 		 * Check if we have a sibling and it is empty.
1594 		 */
1595 		if (zap_leaf_phys(sl)->l_hdr.lh_prefix_len != prefix_len ||
1596 		    zap_leaf_phys(sl)->l_hdr.lh_nentries != 0) {
1597 			zap_put_leaf(sl);
1598 			break;
1599 		}
1600 
1601 		zap_put_leaf(sl);
1602 
1603 		/*
1604 		 * If there two empty sibling, we have work to do, so
1605 		 * we need to lock ZAP ptrtbl as WRITER.
1606 		 */
1607 		if (!writer && (writer = zap_tryupgradedir(zap, tx)) == 0) {
1608 			/* We failed to upgrade */
1609 			if (l != NULL) {
1610 				zap_put_leaf(l);
1611 				l = NULL;
1612 			}
1613 
1614 			/*
1615 			 * Usually, the right way to upgrade from a READER lock
1616 			 * to a WRITER lock is to call zap_unlockdir() and
1617 			 * zap_lockdir(), but we do not have a tag. Instead,
1618 			 * we do it in more sophisticated way.
1619 			 */
1620 			rw_exit(&zap->zap_rwlock);
1621 			rw_enter(&zap->zap_rwlock, RW_WRITER);
1622 			dmu_buf_will_dirty(zap->zap_dbuf, tx);
1623 
1624 			zt_shift = zap_f_phys(zap)->zap_ptrtbl.zt_shift;
1625 			writer = B_TRUE;
1626 		}
1627 
1628 		/*
1629 		 * Here we have WRITER lock for ptrtbl.
1630 		 * Now, we need a WRITER lock for both siblings leaves.
1631 		 * Also, we have to recheck if the leaves are still siblings
1632 		 * and still empty.
1633 		 */
1634 		if (l == NULL) {
1635 			/* sibling 0 */
1636 			if ((err = zap_deref_leaf(zap, (slbit ? sl_hash : hash),
1637 			    tx, RW_WRITER, &l)) != 0)
1638 				break;
1639 
1640 			/*
1641 			 * The leaf isn't empty anymore or
1642 			 * it was shrunk/split while our locks were down.
1643 			 */
1644 			if (zap_leaf_phys(l)->l_hdr.lh_nentries != 0 ||
1645 			    zap_leaf_phys(l)->l_hdr.lh_prefix_len != prefix_len)
1646 				break;
1647 		}
1648 
1649 		/* sibling 1 */
1650 		if ((err = zap_deref_leaf(zap, (slbit ? hash : sl_hash), tx,
1651 		    RW_WRITER, &sl)) != 0)
1652 			break;
1653 
1654 		/*
1655 		 * The leaf isn't empty anymore or
1656 		 * it was shrunk/split while our locks were down.
1657 		 */
1658 		if (zap_leaf_phys(sl)->l_hdr.lh_nentries != 0 ||
1659 		    zap_leaf_phys(sl)->l_hdr.lh_prefix_len != prefix_len) {
1660 			zap_put_leaf(sl);
1661 			break;
1662 		}
1663 
1664 		/* If we have gotten here, we have a leaf to collapse */
1665 		uint64_t idx = (slbit ? prefix : sl_prefix) << prefix_diff;
1666 		uint64_t nptrs = (1ULL << prefix_diff);
1667 		uint64_t sl_blkid = sl->l_blkid;
1668 
1669 		/*
1670 		 * Set ptrtbl entries to point out to the slibling 0 blkid
1671 		 */
1672 		if ((err = zap_set_idx_range_to_blk(zap, idx, nptrs, l->l_blkid,
1673 		    tx)) != 0) {
1674 			zap_put_leaf(sl);
1675 			break;
1676 		}
1677 
1678 		/*
1679 		 * Free sibling 1 disk block.
1680 		 */
1681 		int bs = FZAP_BLOCK_SHIFT(zap);
1682 		if (sl_blkid == zap_f_phys(zap)->zap_freeblk - 1)
1683 			trunc = B_TRUE;
1684 
1685 		(void) dmu_free_range(zap->zap_objset, zap->zap_object,
1686 		    sl_blkid << bs, 1 << bs, tx);
1687 		zap_put_leaf(sl);
1688 
1689 		zap_f_phys(zap)->zap_num_leafs--;
1690 
1691 		/*
1692 		 * Update prefix and prefix_len.
1693 		 */
1694 		zap_leaf_phys(l)->l_hdr.lh_prefix >>= 1;
1695 		zap_leaf_phys(l)->l_hdr.lh_prefix_len--;
1696 
1697 		prefix = zap_leaf_phys(l)->l_hdr.lh_prefix;
1698 		prefix_len = zap_leaf_phys(l)->l_hdr.lh_prefix_len;
1699 	}
1700 
1701 	if (trunc)
1702 		zap_trunc(zap);
1703 
1704 	if (l != NULL)
1705 		zap_put_leaf(l);
1706 
1707 	return (err);
1708 }
1709 
1710 ZFS_MODULE_PARAM(zfs, , zap_iterate_prefetch, INT, ZMOD_RW,
1711 	"When iterating ZAP object, prefetch it");
1712 
1713 ZFS_MODULE_PARAM(zfs, , zap_shrink_enabled, INT, ZMOD_RW,
1714 	"Enable ZAP shrinking");
1715