1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21/*
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2016 by Delphix. All rights reserved.
24 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
25 * Copyright (c) 2014 Integros [integros.com]
26 */
27
28#include <sys/zio.h>
29#include <sys/spa.h>
30#include <sys/dmu.h>
31#include <sys/zfs_context.h>
32#include <sys/zap.h>
33#include <sys/refcount.h>
34#include <sys/zap_impl.h>
35#include <sys/zap_leaf.h>
36#include <sys/avl.h>
37#include <sys/arc.h>
38#include <sys/dmu_objset.h>
39
40#ifdef _KERNEL
41#include <sys/sunddi.h>
42#endif
43
44extern inline mzap_phys_t *zap_m_phys(zap_t *zap);
45
46static int mzap_upgrade(zap_t **zapp,
47    void *tag, dmu_tx_t *tx, zap_flags_t flags);
48
49uint64_t
50zap_getflags(zap_t *zap)
51{
52	if (zap->zap_ismicro)
53		return (0);
54	return (zap_f_phys(zap)->zap_flags);
55}
56
57int
58zap_hashbits(zap_t *zap)
59{
60	if (zap_getflags(zap) & ZAP_FLAG_HASH64)
61		return (48);
62	else
63		return (28);
64}
65
66uint32_t
67zap_maxcd(zap_t *zap)
68{
69	if (zap_getflags(zap) & ZAP_FLAG_HASH64)
70		return ((1<<16)-1);
71	else
72		return (-1U);
73}
74
75static uint64_t
76zap_hash(zap_name_t *zn)
77{
78	zap_t *zap = zn->zn_zap;
79	uint64_t h = 0;
80
81	if (zap_getflags(zap) & ZAP_FLAG_PRE_HASHED_KEY) {
82		ASSERT(zap_getflags(zap) & ZAP_FLAG_UINT64_KEY);
83		h = *(uint64_t *)zn->zn_key_orig;
84	} else {
85		h = zap->zap_salt;
86		ASSERT(h != 0);
87		ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
88
89		if (zap_getflags(zap) & ZAP_FLAG_UINT64_KEY) {
90			int i;
91			const uint64_t *wp = zn->zn_key_norm;
92
93			ASSERT(zn->zn_key_intlen == 8);
94			for (i = 0; i < zn->zn_key_norm_numints; wp++, i++) {
95				int j;
96				uint64_t word = *wp;
97
98				for (j = 0; j < zn->zn_key_intlen; j++) {
99					h = (h >> 8) ^
100					    zfs_crc64_table[(h ^ word) & 0xFF];
101					word >>= NBBY;
102				}
103			}
104		} else {
105			int i, len;
106			const uint8_t *cp = zn->zn_key_norm;
107
108			/*
109			 * We previously stored the terminating null on
110			 * disk, but didn't hash it, so we need to
111			 * continue to not hash it.  (The
112			 * zn_key_*_numints includes the terminating
113			 * null for non-binary keys.)
114			 */
115			len = zn->zn_key_norm_numints - 1;
116
117			ASSERT(zn->zn_key_intlen == 1);
118			for (i = 0; i < len; cp++, i++) {
119				h = (h >> 8) ^
120				    zfs_crc64_table[(h ^ *cp) & 0xFF];
121			}
122		}
123	}
124	/*
125	 * Don't use all 64 bits, since we need some in the cookie for
126	 * the collision differentiator.  We MUST use the high bits,
127	 * since those are the ones that we first pay attention to when
128	 * chosing the bucket.
129	 */
130	h &= ~((1ULL << (64 - zap_hashbits(zap))) - 1);
131
132	return (h);
133}
134
135static int
136zap_normalize(zap_t *zap, const char *name, char *namenorm)
137{
138	size_t inlen, outlen;
139	int err;
140
141	ASSERT(!(zap_getflags(zap) & ZAP_FLAG_UINT64_KEY));
142
143	inlen = strlen(name) + 1;
144	outlen = ZAP_MAXNAMELEN;
145
146	err = 0;
147	(void) u8_textprep_str((char *)name, &inlen, namenorm, &outlen,
148	    zap->zap_normflags | U8_TEXTPREP_IGNORE_NULL |
149	    U8_TEXTPREP_IGNORE_INVALID, U8_UNICODE_LATEST, &err);
150
151	return (err);
152}
153
154boolean_t
155zap_match(zap_name_t *zn, const char *matchname)
156{
157	ASSERT(!(zap_getflags(zn->zn_zap) & ZAP_FLAG_UINT64_KEY));
158
159	if (zn->zn_matchtype == MT_FIRST) {
160		char norm[ZAP_MAXNAMELEN];
161
162		if (zap_normalize(zn->zn_zap, matchname, norm) != 0)
163			return (B_FALSE);
164
165		return (strcmp(zn->zn_key_norm, norm) == 0);
166	} else {
167		/* MT_BEST or MT_EXACT */
168		return (strcmp(zn->zn_key_orig, matchname) == 0);
169	}
170}
171
172void
173zap_name_free(zap_name_t *zn)
174{
175	kmem_free(zn, sizeof (zap_name_t));
176}
177
178zap_name_t *
179zap_name_alloc(zap_t *zap, const char *key, matchtype_t mt)
180{
181	zap_name_t *zn = kmem_alloc(sizeof (zap_name_t), KM_SLEEP);
182
183	zn->zn_zap = zap;
184	zn->zn_key_intlen = sizeof (*key);
185	zn->zn_key_orig = key;
186	zn->zn_key_orig_numints = strlen(zn->zn_key_orig) + 1;
187	zn->zn_matchtype = mt;
188	if (zap->zap_normflags) {
189		if (zap_normalize(zap, key, zn->zn_normbuf) != 0) {
190			zap_name_free(zn);
191			return (NULL);
192		}
193		zn->zn_key_norm = zn->zn_normbuf;
194		zn->zn_key_norm_numints = strlen(zn->zn_key_norm) + 1;
195	} else {
196		if (mt != MT_EXACT) {
197			zap_name_free(zn);
198			return (NULL);
199		}
200		zn->zn_key_norm = zn->zn_key_orig;
201		zn->zn_key_norm_numints = zn->zn_key_orig_numints;
202	}
203
204	zn->zn_hash = zap_hash(zn);
205	return (zn);
206}
207
208zap_name_t *
209zap_name_alloc_uint64(zap_t *zap, const uint64_t *key, int numints)
210{
211	zap_name_t *zn = kmem_alloc(sizeof (zap_name_t), KM_SLEEP);
212
213	ASSERT(zap->zap_normflags == 0);
214	zn->zn_zap = zap;
215	zn->zn_key_intlen = sizeof (*key);
216	zn->zn_key_orig = zn->zn_key_norm = key;
217	zn->zn_key_orig_numints = zn->zn_key_norm_numints = numints;
218	zn->zn_matchtype = MT_EXACT;
219
220	zn->zn_hash = zap_hash(zn);
221	return (zn);
222}
223
224static void
225mzap_byteswap(mzap_phys_t *buf, size_t size)
226{
227	int i, max;
228	buf->mz_block_type = BSWAP_64(buf->mz_block_type);
229	buf->mz_salt = BSWAP_64(buf->mz_salt);
230	buf->mz_normflags = BSWAP_64(buf->mz_normflags);
231	max = (size / MZAP_ENT_LEN) - 1;
232	for (i = 0; i < max; i++) {
233		buf->mz_chunk[i].mze_value =
234		    BSWAP_64(buf->mz_chunk[i].mze_value);
235		buf->mz_chunk[i].mze_cd =
236		    BSWAP_32(buf->mz_chunk[i].mze_cd);
237	}
238}
239
240void
241zap_byteswap(void *buf, size_t size)
242{
243	uint64_t block_type;
244
245	block_type = *(uint64_t *)buf;
246
247	if (block_type == ZBT_MICRO || block_type == BSWAP_64(ZBT_MICRO)) {
248		/* ASSERT(magic == ZAP_LEAF_MAGIC); */
249		mzap_byteswap(buf, size);
250	} else {
251		fzap_byteswap(buf, size);
252	}
253}
254
255static int
256mze_compare(const void *arg1, const void *arg2)
257{
258	const mzap_ent_t *mze1 = arg1;
259	const mzap_ent_t *mze2 = arg2;
260
261	if (mze1->mze_hash > mze2->mze_hash)
262		return (+1);
263	if (mze1->mze_hash < mze2->mze_hash)
264		return (-1);
265	if (mze1->mze_cd > mze2->mze_cd)
266		return (+1);
267	if (mze1->mze_cd < mze2->mze_cd)
268		return (-1);
269	return (0);
270}
271
272static int
273mze_insert(zap_t *zap, int chunkid, uint64_t hash)
274{
275	mzap_ent_t *mze;
276	avl_index_t idx;
277
278	ASSERT(zap->zap_ismicro);
279	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
280
281	mze = kmem_alloc(sizeof (mzap_ent_t), KM_SLEEP);
282	mze->mze_chunkid = chunkid;
283	mze->mze_hash = hash;
284	mze->mze_cd = MZE_PHYS(zap, mze)->mze_cd;
285	ASSERT(MZE_PHYS(zap, mze)->mze_name[0] != 0);
286	if (avl_find(&zap->zap_m.zap_avl, mze, &idx) != NULL) {
287		kmem_free(mze, sizeof (mzap_ent_t));
288		return (EEXIST);
289	}
290	avl_insert(&zap->zap_m.zap_avl, mze, idx);
291	return (0);
292}
293
294static mzap_ent_t *
295mze_find(zap_name_t *zn)
296{
297	mzap_ent_t mze_tofind;
298	mzap_ent_t *mze;
299	avl_index_t idx;
300	avl_tree_t *avl = &zn->zn_zap->zap_m.zap_avl;
301
302	ASSERT(zn->zn_zap->zap_ismicro);
303	ASSERT(RW_LOCK_HELD(&zn->zn_zap->zap_rwlock));
304
305	mze_tofind.mze_hash = zn->zn_hash;
306	mze_tofind.mze_cd = 0;
307
308again:
309	mze = avl_find(avl, &mze_tofind, &idx);
310	if (mze == NULL)
311		mze = avl_nearest(avl, idx, AVL_AFTER);
312	for (; mze && mze->mze_hash == zn->zn_hash; mze = AVL_NEXT(avl, mze)) {
313		ASSERT3U(mze->mze_cd, ==, MZE_PHYS(zn->zn_zap, mze)->mze_cd);
314		if (zap_match(zn, MZE_PHYS(zn->zn_zap, mze)->mze_name))
315			return (mze);
316	}
317	if (zn->zn_matchtype == MT_BEST) {
318		zn->zn_matchtype = MT_FIRST;
319		goto again;
320	}
321	return (NULL);
322}
323
324static uint32_t
325mze_find_unused_cd(zap_t *zap, uint64_t hash)
326{
327	mzap_ent_t mze_tofind;
328	mzap_ent_t *mze;
329	avl_index_t idx;
330	avl_tree_t *avl = &zap->zap_m.zap_avl;
331	uint32_t cd;
332
333	ASSERT(zap->zap_ismicro);
334	ASSERT(RW_LOCK_HELD(&zap->zap_rwlock));
335
336	mze_tofind.mze_hash = hash;
337	mze_tofind.mze_cd = 0;
338
339	cd = 0;
340	for (mze = avl_find(avl, &mze_tofind, &idx);
341	    mze && mze->mze_hash == hash; mze = AVL_NEXT(avl, mze)) {
342		if (mze->mze_cd != cd)
343			break;
344		cd++;
345	}
346
347	return (cd);
348}
349
350static void
351mze_remove(zap_t *zap, mzap_ent_t *mze)
352{
353	ASSERT(zap->zap_ismicro);
354	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
355
356	avl_remove(&zap->zap_m.zap_avl, mze);
357	kmem_free(mze, sizeof (mzap_ent_t));
358}
359
360static void
361mze_destroy(zap_t *zap)
362{
363	mzap_ent_t *mze;
364	void *avlcookie = NULL;
365
366	while (mze = avl_destroy_nodes(&zap->zap_m.zap_avl, &avlcookie))
367		kmem_free(mze, sizeof (mzap_ent_t));
368	avl_destroy(&zap->zap_m.zap_avl);
369}
370
371static zap_t *
372mzap_open(objset_t *os, uint64_t obj, dmu_buf_t *db)
373{
374	zap_t *winner;
375	zap_t *zap;
376	int i;
377	uint64_t *zap_hdr = (uint64_t *)db->db_data;
378	uint64_t zap_block_type = zap_hdr[0];
379	uint64_t zap_magic = zap_hdr[1];
380
381	ASSERT3U(MZAP_ENT_LEN, ==, sizeof (mzap_ent_phys_t));
382
383	zap = kmem_zalloc(sizeof (zap_t), KM_SLEEP);
384	rw_init(&zap->zap_rwlock, 0, 0, 0);
385	rw_enter(&zap->zap_rwlock, RW_WRITER);
386	zap->zap_objset = os;
387	zap->zap_object = obj;
388	zap->zap_dbuf = db;
389
390	if (zap_block_type != ZBT_MICRO) {
391		mutex_init(&zap->zap_f.zap_num_entries_mtx, 0, 0, 0);
392		zap->zap_f.zap_block_shift = highbit64(db->db_size) - 1;
393		if (zap_block_type != ZBT_HEADER || zap_magic != ZAP_MAGIC) {
394			winner = NULL;	/* No actual winner here... */
395			goto handle_winner;
396		}
397	} else {
398		zap->zap_ismicro = TRUE;
399	}
400
401	/*
402	 * Make sure that zap_ismicro is set before we let others see
403	 * it, because zap_lockdir() checks zap_ismicro without the lock
404	 * held.
405	 */
406	dmu_buf_init_user(&zap->zap_dbu, zap_evict_sync, NULL, &zap->zap_dbuf);
407	winner = dmu_buf_set_user(db, &zap->zap_dbu);
408
409	if (winner != NULL)
410		goto handle_winner;
411
412	if (zap->zap_ismicro) {
413		zap->zap_salt = zap_m_phys(zap)->mz_salt;
414		zap->zap_normflags = zap_m_phys(zap)->mz_normflags;
415		zap->zap_m.zap_num_chunks = db->db_size / MZAP_ENT_LEN - 1;
416		avl_create(&zap->zap_m.zap_avl, mze_compare,
417		    sizeof (mzap_ent_t), offsetof(mzap_ent_t, mze_node));
418
419		for (i = 0; i < zap->zap_m.zap_num_chunks; i++) {
420			mzap_ent_phys_t *mze =
421			    &zap_m_phys(zap)->mz_chunk[i];
422			if (mze->mze_name[0]) {
423				zap_name_t *zn;
424
425				zn = zap_name_alloc(zap, mze->mze_name,
426				    MT_EXACT);
427				if (mze_insert(zap, i, zn->zn_hash) == 0)
428					zap->zap_m.zap_num_entries++;
429				else {
430					printf("ZFS WARNING: Duplicated ZAP "
431					    "entry detected (%s).\n",
432					    mze->mze_name);
433				}
434				zap_name_free(zn);
435			}
436		}
437	} else {
438		zap->zap_salt = zap_f_phys(zap)->zap_salt;
439		zap->zap_normflags = zap_f_phys(zap)->zap_normflags;
440
441		ASSERT3U(sizeof (struct zap_leaf_header), ==,
442		    2*ZAP_LEAF_CHUNKSIZE);
443
444		/*
445		 * The embedded pointer table should not overlap the
446		 * other members.
447		 */
448		ASSERT3P(&ZAP_EMBEDDED_PTRTBL_ENT(zap, 0), >,
449		    &zap_f_phys(zap)->zap_salt);
450
451		/*
452		 * The embedded pointer table should end at the end of
453		 * the block
454		 */
455		ASSERT3U((uintptr_t)&ZAP_EMBEDDED_PTRTBL_ENT(zap,
456		    1<<ZAP_EMBEDDED_PTRTBL_SHIFT(zap)) -
457		    (uintptr_t)zap_f_phys(zap), ==,
458		    zap->zap_dbuf->db_size);
459	}
460	rw_exit(&zap->zap_rwlock);
461	return (zap);
462
463handle_winner:
464	rw_exit(&zap->zap_rwlock);
465	rw_destroy(&zap->zap_rwlock);
466	if (!zap->zap_ismicro)
467		mutex_destroy(&zap->zap_f.zap_num_entries_mtx);
468	kmem_free(zap, sizeof (zap_t));
469	return (winner);
470}
471
472static int
473zap_lockdir_impl(dmu_buf_t *db, void *tag, dmu_tx_t *tx,
474    krw_t lti, boolean_t fatreader, boolean_t adding, zap_t **zapp)
475{
476	zap_t *zap;
477	krw_t lt;
478
479	ASSERT0(db->db_offset);
480	objset_t *os = dmu_buf_get_objset(db);
481	uint64_t obj = db->db_object;
482
483	*zapp = NULL;
484
485#ifdef ZFS_DEBUG
486	{
487		dmu_object_info_t doi;
488		dmu_object_info_from_db(db, &doi);
489		ASSERT3U(DMU_OT_BYTESWAP(doi.doi_type), ==, DMU_BSWAP_ZAP);
490	}
491#endif
492
493	zap = dmu_buf_get_user(db);
494	if (zap == NULL) {
495		zap = mzap_open(os, obj, db);
496		if (zap == NULL) {
497			/*
498			 * mzap_open() didn't like what it saw on-disk.
499			 * Check for corruption!
500			 */
501			return (SET_ERROR(EIO));
502		}
503	}
504
505	/*
506	 * We're checking zap_ismicro without the lock held, in order to
507	 * tell what type of lock we want.  Once we have some sort of
508	 * lock, see if it really is the right type.  In practice this
509	 * can only be different if it was upgraded from micro to fat,
510	 * and micro wanted WRITER but fat only needs READER.
511	 */
512	lt = (!zap->zap_ismicro && fatreader) ? RW_READER : lti;
513	rw_enter(&zap->zap_rwlock, lt);
514	if (lt != ((!zap->zap_ismicro && fatreader) ? RW_READER : lti)) {
515		/* it was upgraded, now we only need reader */
516		ASSERT(lt == RW_WRITER);
517		ASSERT(RW_READER ==
518		    (!zap->zap_ismicro && fatreader) ? RW_READER : lti);
519		rw_downgrade(&zap->zap_rwlock);
520		lt = RW_READER;
521	}
522
523	zap->zap_objset = os;
524
525	if (lt == RW_WRITER)
526		dmu_buf_will_dirty(db, tx);
527
528	ASSERT3P(zap->zap_dbuf, ==, db);
529
530	ASSERT(!zap->zap_ismicro ||
531	    zap->zap_m.zap_num_entries <= zap->zap_m.zap_num_chunks);
532	if (zap->zap_ismicro && tx && adding &&
533	    zap->zap_m.zap_num_entries == zap->zap_m.zap_num_chunks) {
534		uint64_t newsz = db->db_size + SPA_MINBLOCKSIZE;
535		if (newsz > MZAP_MAX_BLKSZ) {
536			dprintf("upgrading obj %llu: num_entries=%u\n",
537			    obj, zap->zap_m.zap_num_entries);
538			*zapp = zap;
539			int err = mzap_upgrade(zapp, tag, tx, 0);
540			if (err != 0)
541				rw_exit(&zap->zap_rwlock);
542			return (err);
543		}
544		VERIFY0(dmu_object_set_blocksize(os, obj, newsz, 0, tx));
545		zap->zap_m.zap_num_chunks =
546		    db->db_size / MZAP_ENT_LEN - 1;
547	}
548
549	*zapp = zap;
550	return (0);
551}
552
553static int
554zap_lockdir_by_dnode(dnode_t *dn, dmu_tx_t *tx,
555    krw_t lti, boolean_t fatreader, boolean_t adding, void *tag, zap_t **zapp)
556{
557	dmu_buf_t *db;
558	int err;
559
560	err = dmu_buf_hold_by_dnode(dn, 0, tag, &db, DMU_READ_NO_PREFETCH);
561	if (err != 0) {
562		return (err);
563	}
564	err = zap_lockdir_impl(db, tag, tx, lti, fatreader, adding, zapp);
565	if (err != 0) {
566		dmu_buf_rele(db, tag);
567	}
568	return (err);
569}
570
571int
572zap_lockdir(objset_t *os, uint64_t obj, dmu_tx_t *tx,
573    krw_t lti, boolean_t fatreader, boolean_t adding, void *tag, zap_t **zapp)
574{
575	dmu_buf_t *db;
576	int err;
577
578	err = dmu_buf_hold(os, obj, 0, tag, &db, DMU_READ_NO_PREFETCH);
579	if (err != 0)
580		return (err);
581	err = zap_lockdir_impl(db, tag, tx, lti, fatreader, adding, zapp);
582	if (err != 0)
583		dmu_buf_rele(db, tag);
584	return (err);
585}
586
587void
588zap_unlockdir(zap_t *zap, void *tag)
589{
590	rw_exit(&zap->zap_rwlock);
591	dmu_buf_rele(zap->zap_dbuf, tag);
592}
593
594static int
595mzap_upgrade(zap_t **zapp, void *tag, dmu_tx_t *tx, zap_flags_t flags)
596{
597	mzap_phys_t *mzp;
598	int i, sz, nchunks;
599	int err = 0;
600	zap_t *zap = *zapp;
601
602	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
603
604	sz = zap->zap_dbuf->db_size;
605	mzp = zio_buf_alloc(sz);
606	bcopy(zap->zap_dbuf->db_data, mzp, sz);
607	nchunks = zap->zap_m.zap_num_chunks;
608
609	if (!flags) {
610		err = dmu_object_set_blocksize(zap->zap_objset, zap->zap_object,
611		    1ULL << fzap_default_block_shift, 0, tx);
612		if (err) {
613			zio_buf_free(mzp, sz);
614			return (err);
615		}
616	}
617
618	dprintf("upgrading obj=%llu with %u chunks\n",
619	    zap->zap_object, nchunks);
620	/* XXX destroy the avl later, so we can use the stored hash value */
621	mze_destroy(zap);
622
623	fzap_upgrade(zap, tx, flags);
624
625	for (i = 0; i < nchunks; i++) {
626		mzap_ent_phys_t *mze = &mzp->mz_chunk[i];
627		zap_name_t *zn;
628		if (mze->mze_name[0] == 0)
629			continue;
630		dprintf("adding %s=%llu\n",
631		    mze->mze_name, mze->mze_value);
632		zn = zap_name_alloc(zap, mze->mze_name, MT_EXACT);
633		err = fzap_add_cd(zn, 8, 1, &mze->mze_value, mze->mze_cd,
634		    tag, tx);
635		zap = zn->zn_zap;	/* fzap_add_cd() may change zap */
636		zap_name_free(zn);
637		if (err)
638			break;
639	}
640	zio_buf_free(mzp, sz);
641	*zapp = zap;
642	return (err);
643}
644
645void
646mzap_create_impl(objset_t *os, uint64_t obj, int normflags, zap_flags_t flags,
647    dmu_tx_t *tx)
648{
649	dmu_buf_t *db;
650	mzap_phys_t *zp;
651
652	VERIFY(0 == dmu_buf_hold(os, obj, 0, FTAG, &db, DMU_READ_NO_PREFETCH));
653
654#ifdef ZFS_DEBUG
655	{
656		dmu_object_info_t doi;
657		dmu_object_info_from_db(db, &doi);
658		ASSERT3U(DMU_OT_BYTESWAP(doi.doi_type), ==, DMU_BSWAP_ZAP);
659	}
660#endif
661
662	dmu_buf_will_dirty(db, tx);
663	zp = db->db_data;
664	zp->mz_block_type = ZBT_MICRO;
665	zp->mz_salt = ((uintptr_t)db ^ (uintptr_t)tx ^ (obj << 1)) | 1ULL;
666	zp->mz_normflags = normflags;
667	dmu_buf_rele(db, FTAG);
668
669	if (flags != 0) {
670		zap_t *zap;
671		/* Only fat zap supports flags; upgrade immediately. */
672		VERIFY(0 == zap_lockdir(os, obj, tx, RW_WRITER,
673		    B_FALSE, B_FALSE, FTAG, &zap));
674		VERIFY3U(0, ==, mzap_upgrade(&zap, FTAG, tx, flags));
675		zap_unlockdir(zap, FTAG);
676	}
677}
678
679int
680zap_create_claim(objset_t *os, uint64_t obj, dmu_object_type_t ot,
681    dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
682{
683	return (zap_create_claim_norm(os, obj,
684	    0, ot, bonustype, bonuslen, tx));
685}
686
687int
688zap_create_claim_norm(objset_t *os, uint64_t obj, int normflags,
689    dmu_object_type_t ot,
690    dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
691{
692	int err;
693
694	err = dmu_object_claim(os, obj, ot, 0, bonustype, bonuslen, tx);
695	if (err != 0)
696		return (err);
697	mzap_create_impl(os, obj, normflags, 0, tx);
698	return (0);
699}
700
701uint64_t
702zap_create(objset_t *os, dmu_object_type_t ot,
703    dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
704{
705	return (zap_create_norm(os, 0, ot, bonustype, bonuslen, tx));
706}
707
708uint64_t
709zap_create_norm(objset_t *os, int normflags, dmu_object_type_t ot,
710    dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
711{
712	uint64_t obj = dmu_object_alloc(os, ot, 0, bonustype, bonuslen, tx);
713
714	mzap_create_impl(os, obj, normflags, 0, tx);
715	return (obj);
716}
717
718uint64_t
719zap_create_flags(objset_t *os, int normflags, zap_flags_t flags,
720    dmu_object_type_t ot, int leaf_blockshift, int indirect_blockshift,
721    dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
722{
723	uint64_t obj = dmu_object_alloc(os, ot, 0, bonustype, bonuslen, tx);
724
725	ASSERT(leaf_blockshift >= SPA_MINBLOCKSHIFT &&
726	    leaf_blockshift <= SPA_OLD_MAXBLOCKSHIFT &&
727	    indirect_blockshift >= SPA_MINBLOCKSHIFT &&
728	    indirect_blockshift <= SPA_OLD_MAXBLOCKSHIFT);
729
730	VERIFY(dmu_object_set_blocksize(os, obj,
731	    1ULL << leaf_blockshift, indirect_blockshift, tx) == 0);
732
733	mzap_create_impl(os, obj, normflags, flags, tx);
734	return (obj);
735}
736
737int
738zap_destroy(objset_t *os, uint64_t zapobj, dmu_tx_t *tx)
739{
740	/*
741	 * dmu_object_free will free the object number and free the
742	 * data.  Freeing the data will cause our pageout function to be
743	 * called, which will destroy our data (zap_leaf_t's and zap_t).
744	 */
745
746	return (dmu_object_free(os, zapobj, tx));
747}
748
749void
750zap_evict_sync(void *dbu)
751{
752	zap_t *zap = dbu;
753
754	rw_destroy(&zap->zap_rwlock);
755
756	if (zap->zap_ismicro)
757		mze_destroy(zap);
758	else
759		mutex_destroy(&zap->zap_f.zap_num_entries_mtx);
760
761	kmem_free(zap, sizeof (zap_t));
762}
763
764int
765zap_count(objset_t *os, uint64_t zapobj, uint64_t *count)
766{
767	zap_t *zap;
768	int err;
769
770	err = zap_lockdir(os, zapobj, NULL, RW_READER, TRUE, FALSE, FTAG, &zap);
771	if (err)
772		return (err);
773	if (!zap->zap_ismicro) {
774		err = fzap_count(zap, count);
775	} else {
776		*count = zap->zap_m.zap_num_entries;
777	}
778	zap_unlockdir(zap, FTAG);
779	return (err);
780}
781
782/*
783 * zn may be NULL; if not specified, it will be computed if needed.
784 * See also the comment above zap_entry_normalization_conflict().
785 */
786static boolean_t
787mzap_normalization_conflict(zap_t *zap, zap_name_t *zn, mzap_ent_t *mze)
788{
789	mzap_ent_t *other;
790	int direction = AVL_BEFORE;
791	boolean_t allocdzn = B_FALSE;
792
793	if (zap->zap_normflags == 0)
794		return (B_FALSE);
795
796again:
797	for (other = avl_walk(&zap->zap_m.zap_avl, mze, direction);
798	    other && other->mze_hash == mze->mze_hash;
799	    other = avl_walk(&zap->zap_m.zap_avl, other, direction)) {
800
801		if (zn == NULL) {
802			zn = zap_name_alloc(zap, MZE_PHYS(zap, mze)->mze_name,
803			    MT_FIRST);
804			allocdzn = B_TRUE;
805		}
806		if (zap_match(zn, MZE_PHYS(zap, other)->mze_name)) {
807			if (allocdzn)
808				zap_name_free(zn);
809			return (B_TRUE);
810		}
811	}
812
813	if (direction == AVL_BEFORE) {
814		direction = AVL_AFTER;
815		goto again;
816	}
817
818	if (allocdzn)
819		zap_name_free(zn);
820	return (B_FALSE);
821}
822
823/*
824 * Routines for manipulating attributes.
825 */
826
827int
828zap_lookup(objset_t *os, uint64_t zapobj, const char *name,
829    uint64_t integer_size, uint64_t num_integers, void *buf)
830{
831	return (zap_lookup_norm(os, zapobj, name, integer_size,
832	    num_integers, buf, MT_EXACT, NULL, 0, NULL));
833}
834
835static int
836zap_lookup_impl(zap_t *zap, const char *name,
837    uint64_t integer_size, uint64_t num_integers, void *buf,
838    matchtype_t mt, char *realname, int rn_len,
839    boolean_t *ncp)
840{
841	int err = 0;
842	mzap_ent_t *mze;
843	zap_name_t *zn;
844
845	zn = zap_name_alloc(zap, name, mt);
846	if (zn == NULL)
847		return (SET_ERROR(ENOTSUP));
848
849	if (!zap->zap_ismicro) {
850		err = fzap_lookup(zn, integer_size, num_integers, buf,
851		    realname, rn_len, ncp);
852	} else {
853		mze = mze_find(zn);
854		if (mze == NULL) {
855			err = SET_ERROR(ENOENT);
856		} else {
857			if (num_integers < 1) {
858				err = SET_ERROR(EOVERFLOW);
859			} else if (integer_size != 8) {
860				err = SET_ERROR(EINVAL);
861			} else {
862				*(uint64_t *)buf =
863				    MZE_PHYS(zap, mze)->mze_value;
864				if (realname != NULL)
865					(void) strlcpy(realname,
866					    MZE_PHYS(zap, mze)->mze_name, rn_len);
867				if (ncp) {
868					*ncp = mzap_normalization_conflict(zap,
869					    zn, mze);
870				}
871			}
872		}
873	}
874	zap_name_free(zn);
875	return (err);
876}
877
878int
879zap_lookup_norm(objset_t *os, uint64_t zapobj, const char *name,
880    uint64_t integer_size, uint64_t num_integers, void *buf,
881    matchtype_t mt, char *realname, int rn_len,
882    boolean_t *ncp)
883{
884	zap_t *zap;
885	int err;
886
887	err = zap_lockdir(os, zapobj, NULL, RW_READER, TRUE, FALSE, FTAG, &zap);
888	if (err != 0)
889		return (err);
890	err = zap_lookup_impl(zap, name, integer_size,
891	    num_integers, buf, mt, realname, rn_len, ncp);
892	zap_unlockdir(zap, FTAG);
893	return (err);
894}
895
896int
897zap_lookup_by_dnode(dnode_t *dn, const char *name,
898    uint64_t integer_size, uint64_t num_integers, void *buf)
899{
900	return (zap_lookup_norm_by_dnode(dn, name, integer_size,
901	    num_integers, buf, MT_EXACT, NULL, 0, NULL));
902}
903
904int
905zap_lookup_norm_by_dnode(dnode_t *dn, const char *name,
906    uint64_t integer_size, uint64_t num_integers, void *buf,
907    matchtype_t mt, char *realname, int rn_len,
908    boolean_t *ncp)
909{
910	zap_t *zap;
911	int err;
912
913	err = zap_lockdir_by_dnode(dn, NULL, RW_READER, TRUE, FALSE,
914	    FTAG, &zap);
915	if (err != 0)
916		return (err);
917	err = zap_lookup_impl(zap, name, integer_size,
918	    num_integers, buf, mt, realname, rn_len, ncp);
919	zap_unlockdir(zap, FTAG);
920	return (err);
921}
922
923int
924zap_prefetch_uint64(objset_t *os, uint64_t zapobj, const uint64_t *key,
925    int key_numints)
926{
927	zap_t *zap;
928	int err;
929	zap_name_t *zn;
930
931	err = zap_lockdir(os, zapobj, NULL, RW_READER, TRUE, FALSE, FTAG, &zap);
932	if (err)
933		return (err);
934	zn = zap_name_alloc_uint64(zap, key, key_numints);
935	if (zn == NULL) {
936		zap_unlockdir(zap, FTAG);
937		return (SET_ERROR(ENOTSUP));
938	}
939
940	fzap_prefetch(zn);
941	zap_name_free(zn);
942	zap_unlockdir(zap, FTAG);
943	return (err);
944}
945
946int
947zap_lookup_uint64(objset_t *os, uint64_t zapobj, const uint64_t *key,
948    int key_numints, uint64_t integer_size, uint64_t num_integers, void *buf)
949{
950	zap_t *zap;
951	int err;
952	zap_name_t *zn;
953
954	err = zap_lockdir(os, zapobj, NULL, RW_READER, TRUE, FALSE, FTAG, &zap);
955	if (err)
956		return (err);
957	zn = zap_name_alloc_uint64(zap, key, key_numints);
958	if (zn == NULL) {
959		zap_unlockdir(zap, FTAG);
960		return (SET_ERROR(ENOTSUP));
961	}
962
963	err = fzap_lookup(zn, integer_size, num_integers, buf,
964	    NULL, 0, NULL);
965	zap_name_free(zn);
966	zap_unlockdir(zap, FTAG);
967	return (err);
968}
969
970int
971zap_contains(objset_t *os, uint64_t zapobj, const char *name)
972{
973	int err = zap_lookup_norm(os, zapobj, name, 0,
974	    0, NULL, MT_EXACT, NULL, 0, NULL);
975	if (err == EOVERFLOW || err == EINVAL)
976		err = 0; /* found, but skipped reading the value */
977	return (err);
978}
979
980int
981zap_length(objset_t *os, uint64_t zapobj, const char *name,
982    uint64_t *integer_size, uint64_t *num_integers)
983{
984	zap_t *zap;
985	int err;
986	mzap_ent_t *mze;
987	zap_name_t *zn;
988
989	err = zap_lockdir(os, zapobj, NULL, RW_READER, TRUE, FALSE, FTAG, &zap);
990	if (err)
991		return (err);
992	zn = zap_name_alloc(zap, name, MT_EXACT);
993	if (zn == NULL) {
994		zap_unlockdir(zap, FTAG);
995		return (SET_ERROR(ENOTSUP));
996	}
997	if (!zap->zap_ismicro) {
998		err = fzap_length(zn, integer_size, num_integers);
999	} else {
1000		mze = mze_find(zn);
1001		if (mze == NULL) {
1002			err = SET_ERROR(ENOENT);
1003		} else {
1004			if (integer_size)
1005				*integer_size = 8;
1006			if (num_integers)
1007				*num_integers = 1;
1008		}
1009	}
1010	zap_name_free(zn);
1011	zap_unlockdir(zap, FTAG);
1012	return (err);
1013}
1014
1015int
1016zap_length_uint64(objset_t *os, uint64_t zapobj, const uint64_t *key,
1017    int key_numints, uint64_t *integer_size, uint64_t *num_integers)
1018{
1019	zap_t *zap;
1020	int err;
1021	zap_name_t *zn;
1022
1023	err = zap_lockdir(os, zapobj, NULL, RW_READER, TRUE, FALSE, FTAG, &zap);
1024	if (err)
1025		return (err);
1026	zn = zap_name_alloc_uint64(zap, key, key_numints);
1027	if (zn == NULL) {
1028		zap_unlockdir(zap, FTAG);
1029		return (SET_ERROR(ENOTSUP));
1030	}
1031	err = fzap_length(zn, integer_size, num_integers);
1032	zap_name_free(zn);
1033	zap_unlockdir(zap, FTAG);
1034	return (err);
1035}
1036
1037static void
1038mzap_addent(zap_name_t *zn, uint64_t value)
1039{
1040	int i;
1041	zap_t *zap = zn->zn_zap;
1042	int start = zap->zap_m.zap_alloc_next;
1043	uint32_t cd;
1044
1045	ASSERT(RW_WRITE_HELD(&zap->zap_rwlock));
1046
1047#ifdef ZFS_DEBUG
1048	for (i = 0; i < zap->zap_m.zap_num_chunks; i++) {
1049		mzap_ent_phys_t *mze = &zap_m_phys(zap)->mz_chunk[i];
1050		ASSERT(strcmp(zn->zn_key_orig, mze->mze_name) != 0);
1051	}
1052#endif
1053
1054	cd = mze_find_unused_cd(zap, zn->zn_hash);
1055	/* given the limited size of the microzap, this can't happen */
1056	ASSERT(cd < zap_maxcd(zap));
1057
1058again:
1059	for (i = start; i < zap->zap_m.zap_num_chunks; i++) {
1060		mzap_ent_phys_t *mze = &zap_m_phys(zap)->mz_chunk[i];
1061		if (mze->mze_name[0] == 0) {
1062			mze->mze_value = value;
1063			mze->mze_cd = cd;
1064			(void) strcpy(mze->mze_name, zn->zn_key_orig);
1065			zap->zap_m.zap_num_entries++;
1066			zap->zap_m.zap_alloc_next = i+1;
1067			if (zap->zap_m.zap_alloc_next ==
1068			    zap->zap_m.zap_num_chunks)
1069				zap->zap_m.zap_alloc_next = 0;
1070			VERIFY(0 == mze_insert(zap, i, zn->zn_hash));
1071			return;
1072		}
1073	}
1074	if (start != 0) {
1075		start = 0;
1076		goto again;
1077	}
1078	ASSERT(!"out of entries!");
1079}
1080
1081int
1082zap_add(objset_t *os, uint64_t zapobj, const char *key,
1083    int integer_size, uint64_t num_integers,
1084    const void *val, dmu_tx_t *tx)
1085{
1086	zap_t *zap;
1087	int err;
1088	mzap_ent_t *mze;
1089	const uint64_t *intval = val;
1090	zap_name_t *zn;
1091
1092	err = zap_lockdir(os, zapobj, tx, RW_WRITER, TRUE, TRUE, FTAG, &zap);
1093	if (err)
1094		return (err);
1095	zn = zap_name_alloc(zap, key, MT_EXACT);
1096	if (zn == NULL) {
1097		zap_unlockdir(zap, FTAG);
1098		return (SET_ERROR(ENOTSUP));
1099	}
1100	if (!zap->zap_ismicro) {
1101		err = fzap_add(zn, integer_size, num_integers, val, FTAG, tx);
1102		zap = zn->zn_zap;	/* fzap_add() may change zap */
1103	} else if (integer_size != 8 || num_integers != 1 ||
1104	    strlen(key) >= MZAP_NAME_LEN) {
1105		err = mzap_upgrade(&zn->zn_zap, FTAG, tx, 0);
1106		if (err == 0) {
1107			err = fzap_add(zn, integer_size, num_integers, val,
1108			    FTAG, tx);
1109		}
1110		zap = zn->zn_zap;	/* fzap_add() may change zap */
1111	} else {
1112		mze = mze_find(zn);
1113		if (mze != NULL) {
1114			err = SET_ERROR(EEXIST);
1115		} else {
1116			mzap_addent(zn, *intval);
1117		}
1118	}
1119	ASSERT(zap == zn->zn_zap);
1120	zap_name_free(zn);
1121	if (zap != NULL)	/* may be NULL if fzap_add() failed */
1122		zap_unlockdir(zap, FTAG);
1123	return (err);
1124}
1125
1126int
1127zap_add_uint64(objset_t *os, uint64_t zapobj, const uint64_t *key,
1128    int key_numints, int integer_size, uint64_t num_integers,
1129    const void *val, dmu_tx_t *tx)
1130{
1131	zap_t *zap;
1132	int err;
1133	zap_name_t *zn;
1134
1135	err = zap_lockdir(os, zapobj, tx, RW_WRITER, TRUE, TRUE, FTAG, &zap);
1136	if (err)
1137		return (err);
1138	zn = zap_name_alloc_uint64(zap, key, key_numints);
1139	if (zn == NULL) {
1140		zap_unlockdir(zap, FTAG);
1141		return (SET_ERROR(ENOTSUP));
1142	}
1143	err = fzap_add(zn, integer_size, num_integers, val, FTAG, tx);
1144	zap = zn->zn_zap;	/* fzap_add() may change zap */
1145	zap_name_free(zn);
1146	if (zap != NULL)	/* may be NULL if fzap_add() failed */
1147		zap_unlockdir(zap, FTAG);
1148	return (err);
1149}
1150
1151int
1152zap_update(objset_t *os, uint64_t zapobj, const char *name,
1153    int integer_size, uint64_t num_integers, const void *val, dmu_tx_t *tx)
1154{
1155	zap_t *zap;
1156	mzap_ent_t *mze;
1157	uint64_t oldval;
1158	const uint64_t *intval = val;
1159	zap_name_t *zn;
1160	int err;
1161
1162#ifdef ZFS_DEBUG
1163	/*
1164	 * If there is an old value, it shouldn't change across the
1165	 * lockdir (eg, due to bprewrite's xlation).
1166	 */
1167	if (integer_size == 8 && num_integers == 1)
1168		(void) zap_lookup(os, zapobj, name, 8, 1, &oldval);
1169#endif
1170
1171	err = zap_lockdir(os, zapobj, tx, RW_WRITER, TRUE, TRUE, FTAG, &zap);
1172	if (err)
1173		return (err);
1174	zn = zap_name_alloc(zap, name, MT_EXACT);
1175	if (zn == NULL) {
1176		zap_unlockdir(zap, FTAG);
1177		return (SET_ERROR(ENOTSUP));
1178	}
1179	if (!zap->zap_ismicro) {
1180		err = fzap_update(zn, integer_size, num_integers, val,
1181		    FTAG, tx);
1182		zap = zn->zn_zap;	/* fzap_update() may change zap */
1183	} else if (integer_size != 8 || num_integers != 1 ||
1184	    strlen(name) >= MZAP_NAME_LEN) {
1185		dprintf("upgrading obj %llu: intsz=%u numint=%llu name=%s\n",
1186		    zapobj, integer_size, num_integers, name);
1187		err = mzap_upgrade(&zn->zn_zap, FTAG, tx, 0);
1188		if (err == 0) {
1189			err = fzap_update(zn, integer_size, num_integers,
1190			    val, FTAG, tx);
1191		}
1192		zap = zn->zn_zap;	/* fzap_update() may change zap */
1193	} else {
1194		mze = mze_find(zn);
1195		if (mze != NULL) {
1196			ASSERT3U(MZE_PHYS(zap, mze)->mze_value, ==, oldval);
1197			MZE_PHYS(zap, mze)->mze_value = *intval;
1198		} else {
1199			mzap_addent(zn, *intval);
1200		}
1201	}
1202	ASSERT(zap == zn->zn_zap);
1203	zap_name_free(zn);
1204	if (zap != NULL)	/* may be NULL if fzap_upgrade() failed */
1205		zap_unlockdir(zap, FTAG);
1206	return (err);
1207}
1208
1209int
1210zap_update_uint64(objset_t *os, uint64_t zapobj, const uint64_t *key,
1211    int key_numints,
1212    int integer_size, uint64_t num_integers, const void *val, dmu_tx_t *tx)
1213{
1214	zap_t *zap;
1215	zap_name_t *zn;
1216	int err;
1217
1218	err = zap_lockdir(os, zapobj, tx, RW_WRITER, TRUE, TRUE, FTAG, &zap);
1219	if (err)
1220		return (err);
1221	zn = zap_name_alloc_uint64(zap, key, key_numints);
1222	if (zn == NULL) {
1223		zap_unlockdir(zap, FTAG);
1224		return (SET_ERROR(ENOTSUP));
1225	}
1226	err = fzap_update(zn, integer_size, num_integers, val, FTAG, tx);
1227	zap = zn->zn_zap;	/* fzap_update() may change zap */
1228	zap_name_free(zn);
1229	if (zap != NULL)	/* may be NULL if fzap_upgrade() failed */
1230		zap_unlockdir(zap, FTAG);
1231	return (err);
1232}
1233
1234int
1235zap_remove(objset_t *os, uint64_t zapobj, const char *name, dmu_tx_t *tx)
1236{
1237	return (zap_remove_norm(os, zapobj, name, MT_EXACT, tx));
1238}
1239
1240int
1241zap_remove_norm(objset_t *os, uint64_t zapobj, const char *name,
1242    matchtype_t mt, dmu_tx_t *tx)
1243{
1244	zap_t *zap;
1245	int err;
1246	mzap_ent_t *mze;
1247	zap_name_t *zn;
1248
1249	err = zap_lockdir(os, zapobj, tx, RW_WRITER, TRUE, FALSE, FTAG, &zap);
1250	if (err)
1251		return (err);
1252	zn = zap_name_alloc(zap, name, mt);
1253	if (zn == NULL) {
1254		zap_unlockdir(zap, FTAG);
1255		return (SET_ERROR(ENOTSUP));
1256	}
1257	if (!zap->zap_ismicro) {
1258		err = fzap_remove(zn, tx);
1259	} else {
1260		mze = mze_find(zn);
1261		if (mze == NULL) {
1262			err = SET_ERROR(ENOENT);
1263		} else {
1264			zap->zap_m.zap_num_entries--;
1265			bzero(&zap_m_phys(zap)->mz_chunk[mze->mze_chunkid],
1266			    sizeof (mzap_ent_phys_t));
1267			mze_remove(zap, mze);
1268		}
1269	}
1270	zap_name_free(zn);
1271	zap_unlockdir(zap, FTAG);
1272	return (err);
1273}
1274
1275int
1276zap_remove_uint64(objset_t *os, uint64_t zapobj, const uint64_t *key,
1277    int key_numints, dmu_tx_t *tx)
1278{
1279	zap_t *zap;
1280	int err;
1281	zap_name_t *zn;
1282
1283	err = zap_lockdir(os, zapobj, tx, RW_WRITER, TRUE, FALSE, FTAG, &zap);
1284	if (err)
1285		return (err);
1286	zn = zap_name_alloc_uint64(zap, key, key_numints);
1287	if (zn == NULL) {
1288		zap_unlockdir(zap, FTAG);
1289		return (SET_ERROR(ENOTSUP));
1290	}
1291	err = fzap_remove(zn, tx);
1292	zap_name_free(zn);
1293	zap_unlockdir(zap, FTAG);
1294	return (err);
1295}
1296
1297/*
1298 * Routines for iterating over the attributes.
1299 */
1300
1301void
1302zap_cursor_init_serialized(zap_cursor_t *zc, objset_t *os, uint64_t zapobj,
1303    uint64_t serialized)
1304{
1305	zc->zc_objset = os;
1306	zc->zc_zap = NULL;
1307	zc->zc_leaf = NULL;
1308	zc->zc_zapobj = zapobj;
1309	zc->zc_serialized = serialized;
1310	zc->zc_hash = 0;
1311	zc->zc_cd = 0;
1312}
1313
1314void
1315zap_cursor_init(zap_cursor_t *zc, objset_t *os, uint64_t zapobj)
1316{
1317	zap_cursor_init_serialized(zc, os, zapobj, 0);
1318}
1319
1320void
1321zap_cursor_fini(zap_cursor_t *zc)
1322{
1323	if (zc->zc_zap) {
1324		rw_enter(&zc->zc_zap->zap_rwlock, RW_READER);
1325		zap_unlockdir(zc->zc_zap, NULL);
1326		zc->zc_zap = NULL;
1327	}
1328	if (zc->zc_leaf) {
1329		rw_enter(&zc->zc_leaf->l_rwlock, RW_READER);
1330		zap_put_leaf(zc->zc_leaf);
1331		zc->zc_leaf = NULL;
1332	}
1333	zc->zc_objset = NULL;
1334}
1335
1336uint64_t
1337zap_cursor_serialize(zap_cursor_t *zc)
1338{
1339	if (zc->zc_hash == -1ULL)
1340		return (-1ULL);
1341	if (zc->zc_zap == NULL)
1342		return (zc->zc_serialized);
1343	ASSERT((zc->zc_hash & zap_maxcd(zc->zc_zap)) == 0);
1344	ASSERT(zc->zc_cd < zap_maxcd(zc->zc_zap));
1345
1346	/*
1347	 * We want to keep the high 32 bits of the cursor zero if we can, so
1348	 * that 32-bit programs can access this.  So usually use a small
1349	 * (28-bit) hash value so we can fit 4 bits of cd into the low 32-bits
1350	 * of the cursor.
1351	 *
1352	 * [ collision differentiator | zap_hashbits()-bit hash value ]
1353	 */
1354	return ((zc->zc_hash >> (64 - zap_hashbits(zc->zc_zap))) |
1355	    ((uint64_t)zc->zc_cd << zap_hashbits(zc->zc_zap)));
1356}
1357
1358int
1359zap_cursor_retrieve(zap_cursor_t *zc, zap_attribute_t *za)
1360{
1361	int err;
1362	avl_index_t idx;
1363	mzap_ent_t mze_tofind;
1364	mzap_ent_t *mze;
1365
1366	if (zc->zc_hash == -1ULL)
1367		return (SET_ERROR(ENOENT));
1368
1369	if (zc->zc_zap == NULL) {
1370		int hb;
1371		err = zap_lockdir(zc->zc_objset, zc->zc_zapobj, NULL,
1372		    RW_READER, TRUE, FALSE, NULL, &zc->zc_zap);
1373		if (err)
1374			return (err);
1375
1376		/*
1377		 * To support zap_cursor_init_serialized, advance, retrieve,
1378		 * we must add to the existing zc_cd, which may already
1379		 * be 1 due to the zap_cursor_advance.
1380		 */
1381		ASSERT(zc->zc_hash == 0);
1382		hb = zap_hashbits(zc->zc_zap);
1383		zc->zc_hash = zc->zc_serialized << (64 - hb);
1384		zc->zc_cd += zc->zc_serialized >> hb;
1385		if (zc->zc_cd >= zap_maxcd(zc->zc_zap)) /* corrupt serialized */
1386			zc->zc_cd = 0;
1387	} else {
1388		rw_enter(&zc->zc_zap->zap_rwlock, RW_READER);
1389	}
1390	if (!zc->zc_zap->zap_ismicro) {
1391		err = fzap_cursor_retrieve(zc->zc_zap, zc, za);
1392	} else {
1393		mze_tofind.mze_hash = zc->zc_hash;
1394		mze_tofind.mze_cd = zc->zc_cd;
1395
1396		mze = avl_find(&zc->zc_zap->zap_m.zap_avl, &mze_tofind, &idx);
1397		if (mze == NULL) {
1398			mze = avl_nearest(&zc->zc_zap->zap_m.zap_avl,
1399			    idx, AVL_AFTER);
1400		}
1401		if (mze) {
1402			mzap_ent_phys_t *mzep = MZE_PHYS(zc->zc_zap, mze);
1403			ASSERT3U(mze->mze_cd, ==, mzep->mze_cd);
1404			za->za_normalization_conflict =
1405			    mzap_normalization_conflict(zc->zc_zap, NULL, mze);
1406			za->za_integer_length = 8;
1407			za->za_num_integers = 1;
1408			za->za_first_integer = mzep->mze_value;
1409			(void) strcpy(za->za_name, mzep->mze_name);
1410			zc->zc_hash = mze->mze_hash;
1411			zc->zc_cd = mze->mze_cd;
1412			err = 0;
1413		} else {
1414			zc->zc_hash = -1ULL;
1415			err = SET_ERROR(ENOENT);
1416		}
1417	}
1418	rw_exit(&zc->zc_zap->zap_rwlock);
1419	return (err);
1420}
1421
1422void
1423zap_cursor_advance(zap_cursor_t *zc)
1424{
1425	if (zc->zc_hash == -1ULL)
1426		return;
1427	zc->zc_cd++;
1428}
1429
1430int
1431zap_cursor_move_to_key(zap_cursor_t *zc, const char *name, matchtype_t mt)
1432{
1433	int err = 0;
1434	mzap_ent_t *mze;
1435	zap_name_t *zn;
1436
1437	if (zc->zc_zap == NULL) {
1438		err = zap_lockdir(zc->zc_objset, zc->zc_zapobj, NULL,
1439		    RW_READER, TRUE, FALSE, FTAG, &zc->zc_zap);
1440		if (err)
1441			return (err);
1442	} else {
1443		rw_enter(&zc->zc_zap->zap_rwlock, RW_READER);
1444	}
1445
1446	zn = zap_name_alloc(zc->zc_zap, name, mt);
1447	if (zn == NULL) {
1448		rw_exit(&zc->zc_zap->zap_rwlock);
1449		return (SET_ERROR(ENOTSUP));
1450	}
1451
1452	if (!zc->zc_zap->zap_ismicro) {
1453		err = fzap_cursor_move_to_key(zc, zn);
1454	} else {
1455		mze = mze_find(zn);
1456		if (mze == NULL) {
1457			err = SET_ERROR(ENOENT);
1458			goto out;
1459		}
1460		zc->zc_hash = mze->mze_hash;
1461		zc->zc_cd = mze->mze_cd;
1462	}
1463
1464out:
1465	zap_name_free(zn);
1466	rw_exit(&zc->zc_zap->zap_rwlock);
1467	return (err);
1468}
1469
1470int
1471zap_get_stats(objset_t *os, uint64_t zapobj, zap_stats_t *zs)
1472{
1473	int err;
1474	zap_t *zap;
1475
1476	err = zap_lockdir(os, zapobj, NULL, RW_READER, TRUE, FALSE, FTAG, &zap);
1477	if (err)
1478		return (err);
1479
1480	bzero(zs, sizeof (zap_stats_t));
1481
1482	if (zap->zap_ismicro) {
1483		zs->zs_blocksize = zap->zap_dbuf->db_size;
1484		zs->zs_num_entries = zap->zap_m.zap_num_entries;
1485		zs->zs_num_blocks = 1;
1486	} else {
1487		fzap_get_stats(zap, zs);
1488	}
1489	zap_unlockdir(zap, FTAG);
1490	return (0);
1491}
1492
1493int
1494zap_count_write_by_dnode(dnode_t *dn, const char *name, int add,
1495    refcount_t *towrite, refcount_t *tooverwrite)
1496{
1497	zap_t *zap;
1498	int err = 0;
1499
1500	/*
1501	 * Since, we don't have a name, we cannot figure out which blocks will
1502	 * be affected in this operation. So, account for the worst case :
1503	 * - 3 blocks overwritten: target leaf, ptrtbl block, header block
1504	 * - 4 new blocks written if adding:
1505	 *    - 2 blocks for possibly split leaves,
1506	 *    - 2 grown ptrtbl blocks
1507	 *
1508	 * This also accommodates the case where an add operation to a fairly
1509	 * large microzap results in a promotion to fatzap.
1510	 */
1511	if (name == NULL) {
1512		(void) refcount_add_many(towrite,
1513		    (3 + (add ? 4 : 0)) * SPA_OLD_MAXBLOCKSIZE, FTAG);
1514		return (err);
1515	}
1516
1517	/*
1518	 * We lock the zap with adding == FALSE. Because, if we pass
1519	 * the actual value of add, it could trigger a mzap_upgrade().
1520	 * At present we are just evaluating the possibility of this operation
1521	 * and hence we do not want to trigger an upgrade.
1522	 */
1523	err = zap_lockdir_by_dnode(dn, NULL, RW_READER, TRUE, FALSE,
1524	    FTAG, &zap);
1525	if (err != 0)
1526		return (err);
1527
1528	if (!zap->zap_ismicro) {
1529		zap_name_t *zn = zap_name_alloc(zap, name, MT_EXACT);
1530		if (zn) {
1531			err = fzap_count_write(zn, add, towrite,
1532			    tooverwrite);
1533			zap_name_free(zn);
1534		} else {
1535			/*
1536			 * We treat this case as similar to (name == NULL)
1537			 */
1538			(void) refcount_add_many(towrite,
1539			    (3 + (add ? 4 : 0)) * SPA_OLD_MAXBLOCKSIZE, FTAG);
1540		}
1541	} else {
1542		/*
1543		 * We are here if (name != NULL) and this is a micro-zap.
1544		 * We account for the header block depending on whether it
1545		 * is freeable.
1546		 *
1547		 * Incase of an add-operation it is hard to find out
1548		 * if this add will promote this microzap to fatzap.
1549		 * Hence, we consider the worst case and account for the
1550		 * blocks assuming this microzap would be promoted to a
1551		 * fatzap.
1552		 *
1553		 * 1 block overwritten  : header block
1554		 * 4 new blocks written : 2 new split leaf, 2 grown
1555		 *			ptrtbl blocks
1556		 */
1557		if (dmu_buf_freeable(zap->zap_dbuf)) {
1558			(void) refcount_add_many(tooverwrite,
1559			    MZAP_MAX_BLKSZ, FTAG);
1560		} else {
1561			(void) refcount_add_many(towrite,
1562			    MZAP_MAX_BLKSZ, FTAG);
1563		}
1564
1565		if (add) {
1566			(void) refcount_add_many(towrite,
1567			    4 * MZAP_MAX_BLKSZ, FTAG);
1568		}
1569	}
1570
1571	zap_unlockdir(zap, FTAG);
1572	return (err);
1573}
1574