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