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