xref: /illumos-gate/usr/src/uts/common/fs/zfs/sa.c (revision c3d26abc9ee97b4f60233556aadeb57e0bd30bb9)
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 /*
23  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
24  * Portions Copyright 2011 iXsystems, Inc
25  * Copyright (c) 2013 by Delphix. All rights reserved.
26  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27  * Copyright (c) 2014 Integros [integros.com]
28  */
29 
30 #include <sys/zfs_context.h>
31 #include <sys/types.h>
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/sysmacros.h>
35 #include <sys/dmu.h>
36 #include <sys/dmu_impl.h>
37 #include <sys/dmu_objset.h>
38 #include <sys/dbuf.h>
39 #include <sys/dnode.h>
40 #include <sys/zap.h>
41 #include <sys/sa.h>
42 #include <sys/sunddi.h>
43 #include <sys/sa_impl.h>
44 #include <sys/dnode.h>
45 #include <sys/errno.h>
46 #include <sys/zfs_context.h>
47 
48 /*
49  * ZFS System attributes:
50  *
51  * A generic mechanism to allow for arbitrary attributes
52  * to be stored in a dnode.  The data will be stored in the bonus buffer of
53  * the dnode and if necessary a special "spill" block will be used to handle
54  * overflow situations.  The spill block will be sized to fit the data
55  * from 512 - 128K.  When a spill block is used the BP (blkptr_t) for the
56  * spill block is stored at the end of the current bonus buffer.  Any
57  * attributes that would be in the way of the blkptr_t will be relocated
58  * into the spill block.
59  *
60  * Attribute registration:
61  *
62  * Stored persistently on a per dataset basis
63  * a mapping between attribute "string" names and their actual attribute
64  * numeric values, length, and byteswap function.  The names are only used
65  * during registration.  All  attributes are known by their unique attribute
66  * id value.  If an attribute can have a variable size then the value
67  * 0 will be used to indicate this.
68  *
69  * Attribute Layout:
70  *
71  * Attribute layouts are a way to compactly store multiple attributes, but
72  * without taking the overhead associated with managing each attribute
73  * individually.  Since you will typically have the same set of attributes
74  * stored in the same order a single table will be used to represent that
75  * layout.  The ZPL for example will usually have only about 10 different
76  * layouts (regular files, device files, symlinks,
77  * regular files + scanstamp, files/dir with extended attributes, and then
78  * you have the possibility of all of those minus ACL, because it would
79  * be kicked out into the spill block)
80  *
81  * Layouts are simply an array of the attributes and their
82  * ordering i.e. [0, 1, 4, 5, 2]
83  *
84  * Each distinct layout is given a unique layout number and that is whats
85  * stored in the header at the beginning of the SA data buffer.
86  *
87  * A layout only covers a single dbuf (bonus or spill).  If a set of
88  * attributes is split up between the bonus buffer and a spill buffer then
89  * two different layouts will be used.  This allows us to byteswap the
90  * spill without looking at the bonus buffer and keeps the on disk format of
91  * the bonus and spill buffer the same.
92  *
93  * Adding a single attribute will cause the entire set of attributes to
94  * be rewritten and could result in a new layout number being constructed
95  * as part of the rewrite if no such layout exists for the new set of
96  * attribues.  The new attribute will be appended to the end of the already
97  * existing attributes.
98  *
99  * Both the attribute registration and attribute layout information are
100  * stored in normal ZAP attributes.  Their should be a small number of
101  * known layouts and the set of attributes is assumed to typically be quite
102  * small.
103  *
104  * The registered attributes and layout "table" information is maintained
105  * in core and a special "sa_os_t" is attached to the objset_t.
106  *
107  * A special interface is provided to allow for quickly applying
108  * a large set of attributes at once.  sa_replace_all_by_template() is
109  * used to set an array of attributes.  This is used by the ZPL when
110  * creating a brand new file.  The template that is passed into the function
111  * specifies the attribute, size for variable length attributes, location of
112  * data and special "data locator" function if the data isn't in a contiguous
113  * location.
114  *
115  * Byteswap implications:
116  *
117  * Since the SA attributes are not entirely self describing we can't do
118  * the normal byteswap processing.  The special ZAP layout attribute and
119  * attribute registration attributes define the byteswap function and the
120  * size of the attributes, unless it is variable sized.
121  * The normal ZFS byteswapping infrastructure assumes you don't need
122  * to read any objects in order to do the necessary byteswapping.  Whereas
123  * SA attributes can only be properly byteswapped if the dataset is opened
124  * and the layout/attribute ZAP attributes are available.  Because of this
125  * the SA attributes will be byteswapped when they are first accessed by
126  * the SA code that will read the SA data.
127  */
128 
129 typedef void (sa_iterfunc_t)(void *hdr, void *addr, sa_attr_type_t,
130     uint16_t length, int length_idx, boolean_t, void *userp);
131 
132 static int sa_build_index(sa_handle_t *hdl, sa_buf_type_t buftype);
133 static void sa_idx_tab_hold(objset_t *os, sa_idx_tab_t *idx_tab);
134 static void *sa_find_idx_tab(objset_t *os, dmu_object_type_t bonustype,
135     void *data);
136 static void sa_idx_tab_rele(objset_t *os, void *arg);
137 static void sa_copy_data(sa_data_locator_t *func, void *start, void *target,
138     int buflen);
139 static int sa_modify_attrs(sa_handle_t *hdl, sa_attr_type_t newattr,
140     sa_data_op_t action, sa_data_locator_t *locator, void *datastart,
141     uint16_t buflen, dmu_tx_t *tx);
142 
143 arc_byteswap_func_t *sa_bswap_table[] = {
144 	byteswap_uint64_array,
145 	byteswap_uint32_array,
146 	byteswap_uint16_array,
147 	byteswap_uint8_array,
148 	zfs_acl_byteswap,
149 };
150 
151 #define	SA_COPY_DATA(f, s, t, l) \
152 	{ \
153 		if (f == NULL) { \
154 			if (l == 8) { \
155 				*(uint64_t *)t = *(uint64_t *)s; \
156 			} else if (l == 16) { \
157 				*(uint64_t *)t = *(uint64_t *)s; \
158 				*(uint64_t *)((uintptr_t)t + 8) = \
159 				    *(uint64_t *)((uintptr_t)s + 8); \
160 			} else { \
161 				bcopy(s, t, l); \
162 			} \
163 		} else \
164 			sa_copy_data(f, s, t, l); \
165 	}
166 
167 /*
168  * This table is fixed and cannot be changed.  Its purpose is to
169  * allow the SA code to work with both old/new ZPL file systems.
170  * It contains the list of legacy attributes.  These attributes aren't
171  * stored in the "attribute" registry zap objects, since older ZPL file systems
172  * won't have the registry.  Only objsets of type ZFS_TYPE_FILESYSTEM will
173  * use this static table.
174  */
175 sa_attr_reg_t sa_legacy_attrs[] = {
176 	{"ZPL_ATIME", sizeof (uint64_t) * 2, SA_UINT64_ARRAY, 0},
177 	{"ZPL_MTIME", sizeof (uint64_t) * 2, SA_UINT64_ARRAY, 1},
178 	{"ZPL_CTIME", sizeof (uint64_t) * 2, SA_UINT64_ARRAY, 2},
179 	{"ZPL_CRTIME", sizeof (uint64_t) * 2, SA_UINT64_ARRAY, 3},
180 	{"ZPL_GEN", sizeof (uint64_t), SA_UINT64_ARRAY, 4},
181 	{"ZPL_MODE", sizeof (uint64_t), SA_UINT64_ARRAY, 5},
182 	{"ZPL_SIZE", sizeof (uint64_t), SA_UINT64_ARRAY, 6},
183 	{"ZPL_PARENT", sizeof (uint64_t), SA_UINT64_ARRAY, 7},
184 	{"ZPL_LINKS", sizeof (uint64_t), SA_UINT64_ARRAY, 8},
185 	{"ZPL_XATTR", sizeof (uint64_t), SA_UINT64_ARRAY, 9},
186 	{"ZPL_RDEV", sizeof (uint64_t), SA_UINT64_ARRAY, 10},
187 	{"ZPL_FLAGS", sizeof (uint64_t), SA_UINT64_ARRAY, 11},
188 	{"ZPL_UID", sizeof (uint64_t), SA_UINT64_ARRAY, 12},
189 	{"ZPL_GID", sizeof (uint64_t), SA_UINT64_ARRAY, 13},
190 	{"ZPL_PAD", sizeof (uint64_t) * 4, SA_UINT64_ARRAY, 14},
191 	{"ZPL_ZNODE_ACL", 88, SA_UINT8_ARRAY, 15},
192 };
193 
194 /*
195  * This is only used for objects of type DMU_OT_ZNODE
196  */
197 sa_attr_type_t sa_legacy_zpl_layout[] = {
198     0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
199 };
200 
201 /*
202  * Special dummy layout used for buffers with no attributes.
203  */
204 sa_attr_type_t sa_dummy_zpl_layout[] = { 0 };
205 
206 static int sa_legacy_attr_count = 16;
207 static kmem_cache_t *sa_cache = NULL;
208 
209 /*ARGSUSED*/
210 static int
211 sa_cache_constructor(void *buf, void *unused, int kmflag)
212 {
213 	sa_handle_t *hdl = buf;
214 
215 	mutex_init(&hdl->sa_lock, NULL, MUTEX_DEFAULT, NULL);
216 	return (0);
217 }
218 
219 /*ARGSUSED*/
220 static void
221 sa_cache_destructor(void *buf, void *unused)
222 {
223 	sa_handle_t *hdl = buf;
224 	mutex_destroy(&hdl->sa_lock);
225 }
226 
227 void
228 sa_cache_init(void)
229 {
230 	sa_cache = kmem_cache_create("sa_cache",
231 	    sizeof (sa_handle_t), 0, sa_cache_constructor,
232 	    sa_cache_destructor, NULL, NULL, NULL, 0);
233 }
234 
235 void
236 sa_cache_fini(void)
237 {
238 	if (sa_cache)
239 		kmem_cache_destroy(sa_cache);
240 }
241 
242 static int
243 layout_num_compare(const void *arg1, const void *arg2)
244 {
245 	const sa_lot_t *node1 = arg1;
246 	const sa_lot_t *node2 = arg2;
247 
248 	if (node1->lot_num > node2->lot_num)
249 		return (1);
250 	else if (node1->lot_num < node2->lot_num)
251 		return (-1);
252 	return (0);
253 }
254 
255 static int
256 layout_hash_compare(const void *arg1, const void *arg2)
257 {
258 	const sa_lot_t *node1 = arg1;
259 	const sa_lot_t *node2 = arg2;
260 
261 	if (node1->lot_hash > node2->lot_hash)
262 		return (1);
263 	if (node1->lot_hash < node2->lot_hash)
264 		return (-1);
265 	if (node1->lot_instance > node2->lot_instance)
266 		return (1);
267 	if (node1->lot_instance < node2->lot_instance)
268 		return (-1);
269 	return (0);
270 }
271 
272 boolean_t
273 sa_layout_equal(sa_lot_t *tbf, sa_attr_type_t *attrs, int count)
274 {
275 	int i;
276 
277 	if (count != tbf->lot_attr_count)
278 		return (1);
279 
280 	for (i = 0; i != count; i++) {
281 		if (attrs[i] != tbf->lot_attrs[i])
282 			return (1);
283 	}
284 	return (0);
285 }
286 
287 #define	SA_ATTR_HASH(attr) (zfs_crc64_table[(-1ULL ^ attr) & 0xFF])
288 
289 static uint64_t
290 sa_layout_info_hash(sa_attr_type_t *attrs, int attr_count)
291 {
292 	int i;
293 	uint64_t crc = -1ULL;
294 
295 	for (i = 0; i != attr_count; i++)
296 		crc ^= SA_ATTR_HASH(attrs[i]);
297 
298 	return (crc);
299 }
300 
301 static int
302 sa_get_spill(sa_handle_t *hdl)
303 {
304 	int rc;
305 	if (hdl->sa_spill == NULL) {
306 		if ((rc = dmu_spill_hold_existing(hdl->sa_bonus, NULL,
307 		    &hdl->sa_spill)) == 0)
308 			VERIFY(0 == sa_build_index(hdl, SA_SPILL));
309 	} else {
310 		rc = 0;
311 	}
312 
313 	return (rc);
314 }
315 
316 /*
317  * Main attribute lookup/update function
318  * returns 0 for success or non zero for failures
319  *
320  * Operates on bulk array, first failure will abort further processing
321  */
322 int
323 sa_attr_op(sa_handle_t *hdl, sa_bulk_attr_t *bulk, int count,
324     sa_data_op_t data_op, dmu_tx_t *tx)
325 {
326 	sa_os_t *sa = hdl->sa_os->os_sa;
327 	int i;
328 	int error = 0;
329 	sa_buf_type_t buftypes;
330 
331 	buftypes = 0;
332 
333 	ASSERT(count > 0);
334 	for (i = 0; i != count; i++) {
335 		ASSERT(bulk[i].sa_attr <= hdl->sa_os->os_sa->sa_num_attrs);
336 
337 		bulk[i].sa_addr = NULL;
338 		/* First check the bonus buffer */
339 
340 		if (hdl->sa_bonus_tab && TOC_ATTR_PRESENT(
341 		    hdl->sa_bonus_tab->sa_idx_tab[bulk[i].sa_attr])) {
342 			SA_ATTR_INFO(sa, hdl->sa_bonus_tab,
343 			    SA_GET_HDR(hdl, SA_BONUS),
344 			    bulk[i].sa_attr, bulk[i], SA_BONUS, hdl);
345 			if (tx && !(buftypes & SA_BONUS)) {
346 				dmu_buf_will_dirty(hdl->sa_bonus, tx);
347 				buftypes |= SA_BONUS;
348 			}
349 		}
350 		if (bulk[i].sa_addr == NULL &&
351 		    ((error = sa_get_spill(hdl)) == 0)) {
352 			if (TOC_ATTR_PRESENT(
353 			    hdl->sa_spill_tab->sa_idx_tab[bulk[i].sa_attr])) {
354 				SA_ATTR_INFO(sa, hdl->sa_spill_tab,
355 				    SA_GET_HDR(hdl, SA_SPILL),
356 				    bulk[i].sa_attr, bulk[i], SA_SPILL, hdl);
357 				if (tx && !(buftypes & SA_SPILL) &&
358 				    bulk[i].sa_size == bulk[i].sa_length) {
359 					dmu_buf_will_dirty(hdl->sa_spill, tx);
360 					buftypes |= SA_SPILL;
361 				}
362 			}
363 		}
364 		if (error && error != ENOENT) {
365 			return ((error == ECKSUM) ? EIO : error);
366 		}
367 
368 		switch (data_op) {
369 		case SA_LOOKUP:
370 			if (bulk[i].sa_addr == NULL)
371 				return (SET_ERROR(ENOENT));
372 			if (bulk[i].sa_data) {
373 				SA_COPY_DATA(bulk[i].sa_data_func,
374 				    bulk[i].sa_addr, bulk[i].sa_data,
375 				    bulk[i].sa_size);
376 			}
377 			continue;
378 
379 		case SA_UPDATE:
380 			/* existing rewrite of attr */
381 			if (bulk[i].sa_addr &&
382 			    bulk[i].sa_size == bulk[i].sa_length) {
383 				SA_COPY_DATA(bulk[i].sa_data_func,
384 				    bulk[i].sa_data, bulk[i].sa_addr,
385 				    bulk[i].sa_length);
386 				continue;
387 			} else if (bulk[i].sa_addr) { /* attr size change */
388 				error = sa_modify_attrs(hdl, bulk[i].sa_attr,
389 				    SA_REPLACE, bulk[i].sa_data_func,
390 				    bulk[i].sa_data, bulk[i].sa_length, tx);
391 			} else { /* adding new attribute */
392 				error = sa_modify_attrs(hdl, bulk[i].sa_attr,
393 				    SA_ADD, bulk[i].sa_data_func,
394 				    bulk[i].sa_data, bulk[i].sa_length, tx);
395 			}
396 			if (error)
397 				return (error);
398 			break;
399 		}
400 	}
401 	return (error);
402 }
403 
404 static sa_lot_t *
405 sa_add_layout_entry(objset_t *os, sa_attr_type_t *attrs, int attr_count,
406     uint64_t lot_num, uint64_t hash, boolean_t zapadd, dmu_tx_t *tx)
407 {
408 	sa_os_t *sa = os->os_sa;
409 	sa_lot_t *tb, *findtb;
410 	int i;
411 	avl_index_t loc;
412 
413 	ASSERT(MUTEX_HELD(&sa->sa_lock));
414 	tb = kmem_zalloc(sizeof (sa_lot_t), KM_SLEEP);
415 	tb->lot_attr_count = attr_count;
416 	tb->lot_attrs = kmem_alloc(sizeof (sa_attr_type_t) * attr_count,
417 	    KM_SLEEP);
418 	bcopy(attrs, tb->lot_attrs, sizeof (sa_attr_type_t) * attr_count);
419 	tb->lot_num = lot_num;
420 	tb->lot_hash = hash;
421 	tb->lot_instance = 0;
422 
423 	if (zapadd) {
424 		char attr_name[8];
425 
426 		if (sa->sa_layout_attr_obj == 0) {
427 			sa->sa_layout_attr_obj = zap_create_link(os,
428 			    DMU_OT_SA_ATTR_LAYOUTS,
429 			    sa->sa_master_obj, SA_LAYOUTS, tx);
430 		}
431 
432 		(void) snprintf(attr_name, sizeof (attr_name),
433 		    "%d", (int)lot_num);
434 		VERIFY(0 == zap_update(os, os->os_sa->sa_layout_attr_obj,
435 		    attr_name, 2, attr_count, attrs, tx));
436 	}
437 
438 	list_create(&tb->lot_idx_tab, sizeof (sa_idx_tab_t),
439 	    offsetof(sa_idx_tab_t, sa_next));
440 
441 	for (i = 0; i != attr_count; i++) {
442 		if (sa->sa_attr_table[tb->lot_attrs[i]].sa_length == 0)
443 			tb->lot_var_sizes++;
444 	}
445 
446 	avl_add(&sa->sa_layout_num_tree, tb);
447 
448 	/* verify we don't have a hash collision */
449 	if ((findtb = avl_find(&sa->sa_layout_hash_tree, tb, &loc)) != NULL) {
450 		for (; findtb && findtb->lot_hash == hash;
451 		    findtb = AVL_NEXT(&sa->sa_layout_hash_tree, findtb)) {
452 			if (findtb->lot_instance != tb->lot_instance)
453 				break;
454 			tb->lot_instance++;
455 		}
456 	}
457 	avl_add(&sa->sa_layout_hash_tree, tb);
458 	return (tb);
459 }
460 
461 static void
462 sa_find_layout(objset_t *os, uint64_t hash, sa_attr_type_t *attrs,
463     int count, dmu_tx_t *tx, sa_lot_t **lot)
464 {
465 	sa_lot_t *tb, tbsearch;
466 	avl_index_t loc;
467 	sa_os_t *sa = os->os_sa;
468 	boolean_t found = B_FALSE;
469 
470 	mutex_enter(&sa->sa_lock);
471 	tbsearch.lot_hash = hash;
472 	tbsearch.lot_instance = 0;
473 	tb = avl_find(&sa->sa_layout_hash_tree, &tbsearch, &loc);
474 	if (tb) {
475 		for (; tb && tb->lot_hash == hash;
476 		    tb = AVL_NEXT(&sa->sa_layout_hash_tree, tb)) {
477 			if (sa_layout_equal(tb, attrs, count) == 0) {
478 				found = B_TRUE;
479 				break;
480 			}
481 		}
482 	}
483 	if (!found) {
484 		tb = sa_add_layout_entry(os, attrs, count,
485 		    avl_numnodes(&sa->sa_layout_num_tree), hash, B_TRUE, tx);
486 	}
487 	mutex_exit(&sa->sa_lock);
488 	*lot = tb;
489 }
490 
491 static int
492 sa_resize_spill(sa_handle_t *hdl, uint32_t size, dmu_tx_t *tx)
493 {
494 	int error;
495 	uint32_t blocksize;
496 
497 	if (size == 0) {
498 		blocksize = SPA_MINBLOCKSIZE;
499 	} else if (size > SPA_OLD_MAXBLOCKSIZE) {
500 		ASSERT(0);
501 		return (SET_ERROR(EFBIG));
502 	} else {
503 		blocksize = P2ROUNDUP_TYPED(size, SPA_MINBLOCKSIZE, uint32_t);
504 	}
505 
506 	error = dbuf_spill_set_blksz(hdl->sa_spill, blocksize, tx);
507 	ASSERT(error == 0);
508 	return (error);
509 }
510 
511 static void
512 sa_copy_data(sa_data_locator_t *func, void *datastart, void *target, int buflen)
513 {
514 	if (func == NULL) {
515 		bcopy(datastart, target, buflen);
516 	} else {
517 		boolean_t start;
518 		int bytes;
519 		void *dataptr;
520 		void *saptr = target;
521 		uint32_t length;
522 
523 		start = B_TRUE;
524 		bytes = 0;
525 		while (bytes < buflen) {
526 			func(&dataptr, &length, buflen, start, datastart);
527 			bcopy(dataptr, saptr, length);
528 			saptr = (void *)((caddr_t)saptr + length);
529 			bytes += length;
530 			start = B_FALSE;
531 		}
532 	}
533 }
534 
535 /*
536  * Determine several different sizes
537  * first the sa header size
538  * the number of bytes to be stored
539  * if spill would occur the index in the attribute array is returned
540  *
541  * the boolean will_spill will be set when spilling is necessary.  It
542  * is only set when the buftype is SA_BONUS
543  */
544 static int
545 sa_find_sizes(sa_os_t *sa, sa_bulk_attr_t *attr_desc, int attr_count,
546     dmu_buf_t *db, sa_buf_type_t buftype, int *index, int *total,
547     boolean_t *will_spill)
548 {
549 	int var_size = 0;
550 	int i;
551 	int full_space;
552 	int hdrsize;
553 	int extra_hdrsize;
554 
555 	if (buftype == SA_BONUS && sa->sa_force_spill) {
556 		*total = 0;
557 		*index = 0;
558 		*will_spill = B_TRUE;
559 		return (0);
560 	}
561 
562 	*index = -1;
563 	*total = 0;
564 	*will_spill = B_FALSE;
565 
566 	extra_hdrsize = 0;
567 	hdrsize = (SA_BONUSTYPE_FROM_DB(db) == DMU_OT_ZNODE) ? 0 :
568 	    sizeof (sa_hdr_phys_t);
569 
570 	full_space = (buftype == SA_BONUS) ? DN_MAX_BONUSLEN : db->db_size;
571 	ASSERT(IS_P2ALIGNED(full_space, 8));
572 
573 	for (i = 0; i != attr_count; i++) {
574 		boolean_t is_var_sz;
575 
576 		*total = P2ROUNDUP(*total, 8);
577 		*total += attr_desc[i].sa_length;
578 		if (*will_spill)
579 			continue;
580 
581 		is_var_sz = (SA_REGISTERED_LEN(sa, attr_desc[i].sa_attr) == 0);
582 		if (is_var_sz) {
583 			var_size++;
584 		}
585 
586 		if (is_var_sz && var_size > 1) {
587 			/*
588 			 * Don't worry that the spill block might overflow.
589 			 * It will be resized if needed in sa_build_layouts().
590 			 */
591 			if (buftype == SA_SPILL ||
592 			    P2ROUNDUP(hdrsize + sizeof (uint16_t), 8) +
593 			    *total < full_space) {
594 				/*
595 				 * Account for header space used by array of
596 				 * optional sizes of variable-length attributes.
597 				 * Record the extra header size in case this
598 				 * increase needs to be reversed due to
599 				 * spill-over.
600 				 */
601 				hdrsize += sizeof (uint16_t);
602 				if (*index != -1)
603 					extra_hdrsize += sizeof (uint16_t);
604 			} else {
605 				ASSERT(buftype == SA_BONUS);
606 				if (*index == -1)
607 					*index = i;
608 				*will_spill = B_TRUE;
609 				continue;
610 			}
611 		}
612 
613 		/*
614 		 * find index of where spill *could* occur.
615 		 * Then continue to count of remainder attribute
616 		 * space.  The sum is used later for sizing bonus
617 		 * and spill buffer.
618 		 */
619 		if (buftype == SA_BONUS && *index == -1 &&
620 		    *total + P2ROUNDUP(hdrsize, 8) >
621 		    (full_space - sizeof (blkptr_t))) {
622 			*index = i;
623 		}
624 
625 		if (*total + P2ROUNDUP(hdrsize, 8) > full_space &&
626 		    buftype == SA_BONUS)
627 			*will_spill = B_TRUE;
628 	}
629 
630 	if (*will_spill)
631 		hdrsize -= extra_hdrsize;
632 
633 	hdrsize = P2ROUNDUP(hdrsize, 8);
634 	return (hdrsize);
635 }
636 
637 #define	BUF_SPACE_NEEDED(total, header) (total + header)
638 
639 /*
640  * Find layout that corresponds to ordering of attributes
641  * If not found a new layout number is created and added to
642  * persistent layout tables.
643  */
644 static int
645 sa_build_layouts(sa_handle_t *hdl, sa_bulk_attr_t *attr_desc, int attr_count,
646     dmu_tx_t *tx)
647 {
648 	sa_os_t *sa = hdl->sa_os->os_sa;
649 	uint64_t hash;
650 	sa_buf_type_t buftype;
651 	sa_hdr_phys_t *sahdr;
652 	void *data_start;
653 	int buf_space;
654 	sa_attr_type_t *attrs, *attrs_start;
655 	int i, lot_count;
656 	int hdrsize;
657 	int spillhdrsize = 0;
658 	int used;
659 	dmu_object_type_t bonustype;
660 	sa_lot_t *lot;
661 	int len_idx;
662 	int spill_used;
663 	boolean_t spilling;
664 
665 	dmu_buf_will_dirty(hdl->sa_bonus, tx);
666 	bonustype = SA_BONUSTYPE_FROM_DB(hdl->sa_bonus);
667 
668 	/* first determine bonus header size and sum of all attributes */
669 	hdrsize = sa_find_sizes(sa, attr_desc, attr_count, hdl->sa_bonus,
670 	    SA_BONUS, &i, &used, &spilling);
671 
672 	if (used > SPA_OLD_MAXBLOCKSIZE)
673 		return (SET_ERROR(EFBIG));
674 
675 	VERIFY(0 == dmu_set_bonus(hdl->sa_bonus, spilling ?
676 	    MIN(DN_MAX_BONUSLEN - sizeof (blkptr_t), used + hdrsize) :
677 	    used + hdrsize, tx));
678 
679 	ASSERT((bonustype == DMU_OT_ZNODE && spilling == 0) ||
680 	    bonustype == DMU_OT_SA);
681 
682 	/* setup and size spill buffer when needed */
683 	if (spilling) {
684 		boolean_t dummy;
685 
686 		if (hdl->sa_spill == NULL) {
687 			VERIFY(dmu_spill_hold_by_bonus(hdl->sa_bonus, NULL,
688 			    &hdl->sa_spill) == 0);
689 		}
690 		dmu_buf_will_dirty(hdl->sa_spill, tx);
691 
692 		spillhdrsize = sa_find_sizes(sa, &attr_desc[i],
693 		    attr_count - i, hdl->sa_spill, SA_SPILL, &i,
694 		    &spill_used, &dummy);
695 
696 		if (spill_used > SPA_OLD_MAXBLOCKSIZE)
697 			return (SET_ERROR(EFBIG));
698 
699 		buf_space = hdl->sa_spill->db_size - spillhdrsize;
700 		if (BUF_SPACE_NEEDED(spill_used, spillhdrsize) >
701 		    hdl->sa_spill->db_size)
702 			VERIFY(0 == sa_resize_spill(hdl,
703 			    BUF_SPACE_NEEDED(spill_used, spillhdrsize), tx));
704 	}
705 
706 	/* setup starting pointers to lay down data */
707 	data_start = (void *)((uintptr_t)hdl->sa_bonus->db_data + hdrsize);
708 	sahdr = (sa_hdr_phys_t *)hdl->sa_bonus->db_data;
709 	buftype = SA_BONUS;
710 
711 	if (spilling)
712 		buf_space = (sa->sa_force_spill) ?
713 		    0 : SA_BLKPTR_SPACE - hdrsize;
714 	else
715 		buf_space = hdl->sa_bonus->db_size - hdrsize;
716 
717 	attrs_start = attrs = kmem_alloc(sizeof (sa_attr_type_t) * attr_count,
718 	    KM_SLEEP);
719 	lot_count = 0;
720 
721 	for (i = 0, len_idx = 0, hash = -1ULL; i != attr_count; i++) {
722 		uint16_t length;
723 
724 		ASSERT(IS_P2ALIGNED(data_start, 8));
725 		ASSERT(IS_P2ALIGNED(buf_space, 8));
726 		attrs[i] = attr_desc[i].sa_attr;
727 		length = SA_REGISTERED_LEN(sa, attrs[i]);
728 		if (length == 0)
729 			length = attr_desc[i].sa_length;
730 
731 		if (buf_space < length) {  /* switch to spill buffer */
732 			VERIFY(spilling);
733 			VERIFY(bonustype == DMU_OT_SA);
734 			if (buftype == SA_BONUS && !sa->sa_force_spill) {
735 				sa_find_layout(hdl->sa_os, hash, attrs_start,
736 				    lot_count, tx, &lot);
737 				SA_SET_HDR(sahdr, lot->lot_num, hdrsize);
738 			}
739 
740 			buftype = SA_SPILL;
741 			hash = -1ULL;
742 			len_idx = 0;
743 
744 			sahdr = (sa_hdr_phys_t *)hdl->sa_spill->db_data;
745 			sahdr->sa_magic = SA_MAGIC;
746 			data_start = (void *)((uintptr_t)sahdr +
747 			    spillhdrsize);
748 			attrs_start = &attrs[i];
749 			buf_space = hdl->sa_spill->db_size - spillhdrsize;
750 			lot_count = 0;
751 		}
752 		hash ^= SA_ATTR_HASH(attrs[i]);
753 		attr_desc[i].sa_addr = data_start;
754 		attr_desc[i].sa_size = length;
755 		SA_COPY_DATA(attr_desc[i].sa_data_func, attr_desc[i].sa_data,
756 		    data_start, length);
757 		if (sa->sa_attr_table[attrs[i]].sa_length == 0) {
758 			sahdr->sa_lengths[len_idx++] = length;
759 		}
760 		data_start = (void *)P2ROUNDUP(((uintptr_t)data_start +
761 		    length), 8);
762 		buf_space -= P2ROUNDUP(length, 8);
763 		lot_count++;
764 	}
765 
766 	sa_find_layout(hdl->sa_os, hash, attrs_start, lot_count, tx, &lot);
767 
768 	/*
769 	 * Verify that old znodes always have layout number 0.
770 	 * Must be DMU_OT_SA for arbitrary layouts
771 	 */
772 	VERIFY((bonustype == DMU_OT_ZNODE && lot->lot_num == 0) ||
773 	    (bonustype == DMU_OT_SA && lot->lot_num > 1));
774 
775 	if (bonustype == DMU_OT_SA) {
776 		SA_SET_HDR(sahdr, lot->lot_num,
777 		    buftype == SA_BONUS ? hdrsize : spillhdrsize);
778 	}
779 
780 	kmem_free(attrs, sizeof (sa_attr_type_t) * attr_count);
781 	if (hdl->sa_bonus_tab) {
782 		sa_idx_tab_rele(hdl->sa_os, hdl->sa_bonus_tab);
783 		hdl->sa_bonus_tab = NULL;
784 	}
785 	if (!sa->sa_force_spill)
786 		VERIFY(0 == sa_build_index(hdl, SA_BONUS));
787 	if (hdl->sa_spill) {
788 		sa_idx_tab_rele(hdl->sa_os, hdl->sa_spill_tab);
789 		if (!spilling) {
790 			/*
791 			 * remove spill block that is no longer needed.
792 			 */
793 			dmu_buf_rele(hdl->sa_spill, NULL);
794 			hdl->sa_spill = NULL;
795 			hdl->sa_spill_tab = NULL;
796 			VERIFY(0 == dmu_rm_spill(hdl->sa_os,
797 			    sa_handle_object(hdl), tx));
798 		} else {
799 			VERIFY(0 == sa_build_index(hdl, SA_SPILL));
800 		}
801 	}
802 
803 	return (0);
804 }
805 
806 static void
807 sa_free_attr_table(sa_os_t *sa)
808 {
809 	int i;
810 
811 	if (sa->sa_attr_table == NULL)
812 		return;
813 
814 	for (i = 0; i != sa->sa_num_attrs; i++) {
815 		if (sa->sa_attr_table[i].sa_name)
816 			kmem_free(sa->sa_attr_table[i].sa_name,
817 			    strlen(sa->sa_attr_table[i].sa_name) + 1);
818 	}
819 
820 	kmem_free(sa->sa_attr_table,
821 	    sizeof (sa_attr_table_t) * sa->sa_num_attrs);
822 
823 	sa->sa_attr_table = NULL;
824 }
825 
826 static int
827 sa_attr_table_setup(objset_t *os, sa_attr_reg_t *reg_attrs, int count)
828 {
829 	sa_os_t *sa = os->os_sa;
830 	uint64_t sa_attr_count = 0;
831 	uint64_t sa_reg_count = 0;
832 	int error = 0;
833 	uint64_t attr_value;
834 	sa_attr_table_t *tb;
835 	zap_cursor_t zc;
836 	zap_attribute_t za;
837 	int registered_count = 0;
838 	int i;
839 	dmu_objset_type_t ostype = dmu_objset_type(os);
840 
841 	sa->sa_user_table =
842 	    kmem_zalloc(count * sizeof (sa_attr_type_t), KM_SLEEP);
843 	sa->sa_user_table_sz = count * sizeof (sa_attr_type_t);
844 
845 	if (sa->sa_reg_attr_obj != 0) {
846 		error = zap_count(os, sa->sa_reg_attr_obj,
847 		    &sa_attr_count);
848 
849 		/*
850 		 * Make sure we retrieved a count and that it isn't zero
851 		 */
852 		if (error || (error == 0 && sa_attr_count == 0)) {
853 			if (error == 0)
854 				error = SET_ERROR(EINVAL);
855 			goto bail;
856 		}
857 		sa_reg_count = sa_attr_count;
858 	}
859 
860 	if (ostype == DMU_OST_ZFS && sa_attr_count == 0)
861 		sa_attr_count += sa_legacy_attr_count;
862 
863 	/* Allocate attribute numbers for attributes that aren't registered */
864 	for (i = 0; i != count; i++) {
865 		boolean_t found = B_FALSE;
866 		int j;
867 
868 		if (ostype == DMU_OST_ZFS) {
869 			for (j = 0; j != sa_legacy_attr_count; j++) {
870 				if (strcmp(reg_attrs[i].sa_name,
871 				    sa_legacy_attrs[j].sa_name) == 0) {
872 					sa->sa_user_table[i] =
873 					    sa_legacy_attrs[j].sa_attr;
874 					found = B_TRUE;
875 				}
876 			}
877 		}
878 		if (found)
879 			continue;
880 
881 		if (sa->sa_reg_attr_obj)
882 			error = zap_lookup(os, sa->sa_reg_attr_obj,
883 			    reg_attrs[i].sa_name, 8, 1, &attr_value);
884 		else
885 			error = SET_ERROR(ENOENT);
886 		switch (error) {
887 		case ENOENT:
888 			sa->sa_user_table[i] = (sa_attr_type_t)sa_attr_count;
889 			sa_attr_count++;
890 			break;
891 		case 0:
892 			sa->sa_user_table[i] = ATTR_NUM(attr_value);
893 			break;
894 		default:
895 			goto bail;
896 		}
897 	}
898 
899 	sa->sa_num_attrs = sa_attr_count;
900 	tb = sa->sa_attr_table =
901 	    kmem_zalloc(sizeof (sa_attr_table_t) * sa_attr_count, KM_SLEEP);
902 
903 	/*
904 	 * Attribute table is constructed from requested attribute list,
905 	 * previously foreign registered attributes, and also the legacy
906 	 * ZPL set of attributes.
907 	 */
908 
909 	if (sa->sa_reg_attr_obj) {
910 		for (zap_cursor_init(&zc, os, sa->sa_reg_attr_obj);
911 		    (error = zap_cursor_retrieve(&zc, &za)) == 0;
912 		    zap_cursor_advance(&zc)) {
913 			uint64_t value;
914 			value  = za.za_first_integer;
915 
916 			registered_count++;
917 			tb[ATTR_NUM(value)].sa_attr = ATTR_NUM(value);
918 			tb[ATTR_NUM(value)].sa_length = ATTR_LENGTH(value);
919 			tb[ATTR_NUM(value)].sa_byteswap = ATTR_BSWAP(value);
920 			tb[ATTR_NUM(value)].sa_registered = B_TRUE;
921 
922 			if (tb[ATTR_NUM(value)].sa_name) {
923 				continue;
924 			}
925 			tb[ATTR_NUM(value)].sa_name =
926 			    kmem_zalloc(strlen(za.za_name) +1, KM_SLEEP);
927 			(void) strlcpy(tb[ATTR_NUM(value)].sa_name, za.za_name,
928 			    strlen(za.za_name) +1);
929 		}
930 		zap_cursor_fini(&zc);
931 		/*
932 		 * Make sure we processed the correct number of registered
933 		 * attributes
934 		 */
935 		if (registered_count != sa_reg_count) {
936 			ASSERT(error != 0);
937 			goto bail;
938 		}
939 
940 	}
941 
942 	if (ostype == DMU_OST_ZFS) {
943 		for (i = 0; i != sa_legacy_attr_count; i++) {
944 			if (tb[i].sa_name)
945 				continue;
946 			tb[i].sa_attr = sa_legacy_attrs[i].sa_attr;
947 			tb[i].sa_length = sa_legacy_attrs[i].sa_length;
948 			tb[i].sa_byteswap = sa_legacy_attrs[i].sa_byteswap;
949 			tb[i].sa_registered = B_FALSE;
950 			tb[i].sa_name =
951 			    kmem_zalloc(strlen(sa_legacy_attrs[i].sa_name) +1,
952 			    KM_SLEEP);
953 			(void) strlcpy(tb[i].sa_name,
954 			    sa_legacy_attrs[i].sa_name,
955 			    strlen(sa_legacy_attrs[i].sa_name) + 1);
956 		}
957 	}
958 
959 	for (i = 0; i != count; i++) {
960 		sa_attr_type_t attr_id;
961 
962 		attr_id = sa->sa_user_table[i];
963 		if (tb[attr_id].sa_name)
964 			continue;
965 
966 		tb[attr_id].sa_length = reg_attrs[i].sa_length;
967 		tb[attr_id].sa_byteswap = reg_attrs[i].sa_byteswap;
968 		tb[attr_id].sa_attr = attr_id;
969 		tb[attr_id].sa_name =
970 		    kmem_zalloc(strlen(reg_attrs[i].sa_name) + 1, KM_SLEEP);
971 		(void) strlcpy(tb[attr_id].sa_name, reg_attrs[i].sa_name,
972 		    strlen(reg_attrs[i].sa_name) + 1);
973 	}
974 
975 	sa->sa_need_attr_registration =
976 	    (sa_attr_count != registered_count);
977 
978 	return (0);
979 bail:
980 	kmem_free(sa->sa_user_table, count * sizeof (sa_attr_type_t));
981 	sa->sa_user_table = NULL;
982 	sa_free_attr_table(sa);
983 	return ((error != 0) ? error : EINVAL);
984 }
985 
986 int
987 sa_setup(objset_t *os, uint64_t sa_obj, sa_attr_reg_t *reg_attrs, int count,
988     sa_attr_type_t **user_table)
989 {
990 	zap_cursor_t zc;
991 	zap_attribute_t za;
992 	sa_os_t *sa;
993 	dmu_objset_type_t ostype = dmu_objset_type(os);
994 	sa_attr_type_t *tb;
995 	int error;
996 
997 	mutex_enter(&os->os_user_ptr_lock);
998 	if (os->os_sa) {
999 		mutex_enter(&os->os_sa->sa_lock);
1000 		mutex_exit(&os->os_user_ptr_lock);
1001 		tb = os->os_sa->sa_user_table;
1002 		mutex_exit(&os->os_sa->sa_lock);
1003 		*user_table = tb;
1004 		return (0);
1005 	}
1006 
1007 	sa = kmem_zalloc(sizeof (sa_os_t), KM_SLEEP);
1008 	mutex_init(&sa->sa_lock, NULL, MUTEX_DEFAULT, NULL);
1009 	sa->sa_master_obj = sa_obj;
1010 
1011 	os->os_sa = sa;
1012 	mutex_enter(&sa->sa_lock);
1013 	mutex_exit(&os->os_user_ptr_lock);
1014 	avl_create(&sa->sa_layout_num_tree, layout_num_compare,
1015 	    sizeof (sa_lot_t), offsetof(sa_lot_t, lot_num_node));
1016 	avl_create(&sa->sa_layout_hash_tree, layout_hash_compare,
1017 	    sizeof (sa_lot_t), offsetof(sa_lot_t, lot_hash_node));
1018 
1019 	if (sa_obj) {
1020 		error = zap_lookup(os, sa_obj, SA_LAYOUTS,
1021 		    8, 1, &sa->sa_layout_attr_obj);
1022 		if (error != 0 && error != ENOENT)
1023 			goto fail;
1024 		error = zap_lookup(os, sa_obj, SA_REGISTRY,
1025 		    8, 1, &sa->sa_reg_attr_obj);
1026 		if (error != 0 && error != ENOENT)
1027 			goto fail;
1028 	}
1029 
1030 	if ((error = sa_attr_table_setup(os, reg_attrs, count)) != 0)
1031 		goto fail;
1032 
1033 	if (sa->sa_layout_attr_obj != 0) {
1034 		uint64_t layout_count;
1035 
1036 		error = zap_count(os, sa->sa_layout_attr_obj,
1037 		    &layout_count);
1038 
1039 		/*
1040 		 * Layout number count should be > 0
1041 		 */
1042 		if (error || (error == 0 && layout_count == 0)) {
1043 			if (error == 0)
1044 				error = SET_ERROR(EINVAL);
1045 			goto fail;
1046 		}
1047 
1048 		for (zap_cursor_init(&zc, os, sa->sa_layout_attr_obj);
1049 		    (error = zap_cursor_retrieve(&zc, &za)) == 0;
1050 		    zap_cursor_advance(&zc)) {
1051 			sa_attr_type_t *lot_attrs;
1052 			uint64_t lot_num;
1053 
1054 			lot_attrs = kmem_zalloc(sizeof (sa_attr_type_t) *
1055 			    za.za_num_integers, KM_SLEEP);
1056 
1057 			if ((error = (zap_lookup(os, sa->sa_layout_attr_obj,
1058 			    za.za_name, 2, za.za_num_integers,
1059 			    lot_attrs))) != 0) {
1060 				kmem_free(lot_attrs, sizeof (sa_attr_type_t) *
1061 				    za.za_num_integers);
1062 				break;
1063 			}
1064 			VERIFY(ddi_strtoull(za.za_name, NULL, 10,
1065 			    (unsigned long long *)&lot_num) == 0);
1066 
1067 			(void) sa_add_layout_entry(os, lot_attrs,
1068 			    za.za_num_integers, lot_num,
1069 			    sa_layout_info_hash(lot_attrs,
1070 			    za.za_num_integers), B_FALSE, NULL);
1071 			kmem_free(lot_attrs, sizeof (sa_attr_type_t) *
1072 			    za.za_num_integers);
1073 		}
1074 		zap_cursor_fini(&zc);
1075 
1076 		/*
1077 		 * Make sure layout count matches number of entries added
1078 		 * to AVL tree
1079 		 */
1080 		if (avl_numnodes(&sa->sa_layout_num_tree) != layout_count) {
1081 			ASSERT(error != 0);
1082 			goto fail;
1083 		}
1084 	}
1085 
1086 	/* Add special layout number for old ZNODES */
1087 	if (ostype == DMU_OST_ZFS) {
1088 		(void) sa_add_layout_entry(os, sa_legacy_zpl_layout,
1089 		    sa_legacy_attr_count, 0,
1090 		    sa_layout_info_hash(sa_legacy_zpl_layout,
1091 		    sa_legacy_attr_count), B_FALSE, NULL);
1092 
1093 		(void) sa_add_layout_entry(os, sa_dummy_zpl_layout, 0, 1,
1094 		    0, B_FALSE, NULL);
1095 	}
1096 	*user_table = os->os_sa->sa_user_table;
1097 	mutex_exit(&sa->sa_lock);
1098 	return (0);
1099 fail:
1100 	os->os_sa = NULL;
1101 	sa_free_attr_table(sa);
1102 	if (sa->sa_user_table)
1103 		kmem_free(sa->sa_user_table, sa->sa_user_table_sz);
1104 	mutex_exit(&sa->sa_lock);
1105 	avl_destroy(&sa->sa_layout_hash_tree);
1106 	avl_destroy(&sa->sa_layout_num_tree);
1107 	mutex_destroy(&sa->sa_lock);
1108 	kmem_free(sa, sizeof (sa_os_t));
1109 	return ((error == ECKSUM) ? EIO : error);
1110 }
1111 
1112 void
1113 sa_tear_down(objset_t *os)
1114 {
1115 	sa_os_t *sa = os->os_sa;
1116 	sa_lot_t *layout;
1117 	void *cookie;
1118 
1119 	kmem_free(sa->sa_user_table, sa->sa_user_table_sz);
1120 
1121 	/* Free up attr table */
1122 
1123 	sa_free_attr_table(sa);
1124 
1125 	cookie = NULL;
1126 	while (layout = avl_destroy_nodes(&sa->sa_layout_hash_tree, &cookie)) {
1127 		sa_idx_tab_t *tab;
1128 		while (tab = list_head(&layout->lot_idx_tab)) {
1129 			ASSERT(refcount_count(&tab->sa_refcount));
1130 			sa_idx_tab_rele(os, tab);
1131 		}
1132 	}
1133 
1134 	cookie = NULL;
1135 	while (layout = avl_destroy_nodes(&sa->sa_layout_num_tree, &cookie)) {
1136 		kmem_free(layout->lot_attrs,
1137 		    sizeof (sa_attr_type_t) * layout->lot_attr_count);
1138 		kmem_free(layout, sizeof (sa_lot_t));
1139 	}
1140 
1141 	avl_destroy(&sa->sa_layout_hash_tree);
1142 	avl_destroy(&sa->sa_layout_num_tree);
1143 	mutex_destroy(&sa->sa_lock);
1144 
1145 	kmem_free(sa, sizeof (sa_os_t));
1146 	os->os_sa = NULL;
1147 }
1148 
1149 void
1150 sa_build_idx_tab(void *hdr, void *attr_addr, sa_attr_type_t attr,
1151     uint16_t length, int length_idx, boolean_t var_length, void *userp)
1152 {
1153 	sa_idx_tab_t *idx_tab = userp;
1154 
1155 	if (var_length) {
1156 		ASSERT(idx_tab->sa_variable_lengths);
1157 		idx_tab->sa_variable_lengths[length_idx] = length;
1158 	}
1159 	TOC_ATTR_ENCODE(idx_tab->sa_idx_tab[attr], length_idx,
1160 	    (uint32_t)((uintptr_t)attr_addr - (uintptr_t)hdr));
1161 }
1162 
1163 static void
1164 sa_attr_iter(objset_t *os, sa_hdr_phys_t *hdr, dmu_object_type_t type,
1165     sa_iterfunc_t func, sa_lot_t *tab, void *userp)
1166 {
1167 	void *data_start;
1168 	sa_lot_t *tb = tab;
1169 	sa_lot_t search;
1170 	avl_index_t loc;
1171 	sa_os_t *sa = os->os_sa;
1172 	int i;
1173 	uint16_t *length_start = NULL;
1174 	uint8_t length_idx = 0;
1175 
1176 	if (tab == NULL) {
1177 		search.lot_num = SA_LAYOUT_NUM(hdr, type);
1178 		tb = avl_find(&sa->sa_layout_num_tree, &search, &loc);
1179 		ASSERT(tb);
1180 	}
1181 
1182 	if (IS_SA_BONUSTYPE(type)) {
1183 		data_start = (void *)P2ROUNDUP(((uintptr_t)hdr +
1184 		    offsetof(sa_hdr_phys_t, sa_lengths) +
1185 		    (sizeof (uint16_t) * tb->lot_var_sizes)), 8);
1186 		length_start = hdr->sa_lengths;
1187 	} else {
1188 		data_start = hdr;
1189 	}
1190 
1191 	for (i = 0; i != tb->lot_attr_count; i++) {
1192 		int attr_length, reg_length;
1193 		uint8_t idx_len;
1194 
1195 		reg_length = sa->sa_attr_table[tb->lot_attrs[i]].sa_length;
1196 		if (reg_length) {
1197 			attr_length = reg_length;
1198 			idx_len = 0;
1199 		} else {
1200 			attr_length = length_start[length_idx];
1201 			idx_len = length_idx++;
1202 		}
1203 
1204 		func(hdr, data_start, tb->lot_attrs[i], attr_length,
1205 		    idx_len, reg_length == 0 ? B_TRUE : B_FALSE, userp);
1206 
1207 		data_start = (void *)P2ROUNDUP(((uintptr_t)data_start +
1208 		    attr_length), 8);
1209 	}
1210 }
1211 
1212 /*ARGSUSED*/
1213 void
1214 sa_byteswap_cb(void *hdr, void *attr_addr, sa_attr_type_t attr,
1215     uint16_t length, int length_idx, boolean_t variable_length, void *userp)
1216 {
1217 	sa_handle_t *hdl = userp;
1218 	sa_os_t *sa = hdl->sa_os->os_sa;
1219 
1220 	sa_bswap_table[sa->sa_attr_table[attr].sa_byteswap](attr_addr, length);
1221 }
1222 
1223 void
1224 sa_byteswap(sa_handle_t *hdl, sa_buf_type_t buftype)
1225 {
1226 	sa_hdr_phys_t *sa_hdr_phys = SA_GET_HDR(hdl, buftype);
1227 	dmu_buf_impl_t *db;
1228 	sa_os_t *sa = hdl->sa_os->os_sa;
1229 	int num_lengths = 1;
1230 	int i;
1231 
1232 	ASSERT(MUTEX_HELD(&sa->sa_lock));
1233 	if (sa_hdr_phys->sa_magic == SA_MAGIC)
1234 		return;
1235 
1236 	db = SA_GET_DB(hdl, buftype);
1237 
1238 	if (buftype == SA_SPILL) {
1239 		arc_release(db->db_buf, NULL);
1240 		arc_buf_thaw(db->db_buf);
1241 	}
1242 
1243 	sa_hdr_phys->sa_magic = BSWAP_32(sa_hdr_phys->sa_magic);
1244 	sa_hdr_phys->sa_layout_info = BSWAP_16(sa_hdr_phys->sa_layout_info);
1245 
1246 	/*
1247 	 * Determine number of variable lenghts in header
1248 	 * The standard 8 byte header has one for free and a
1249 	 * 16 byte header would have 4 + 1;
1250 	 */
1251 	if (SA_HDR_SIZE(sa_hdr_phys) > 8)
1252 		num_lengths += (SA_HDR_SIZE(sa_hdr_phys) - 8) >> 1;
1253 	for (i = 0; i != num_lengths; i++)
1254 		sa_hdr_phys->sa_lengths[i] =
1255 		    BSWAP_16(sa_hdr_phys->sa_lengths[i]);
1256 
1257 	sa_attr_iter(hdl->sa_os, sa_hdr_phys, DMU_OT_SA,
1258 	    sa_byteswap_cb, NULL, hdl);
1259 
1260 	if (buftype == SA_SPILL)
1261 		arc_buf_freeze(((dmu_buf_impl_t *)hdl->sa_spill)->db_buf);
1262 }
1263 
1264 static int
1265 sa_build_index(sa_handle_t *hdl, sa_buf_type_t buftype)
1266 {
1267 	sa_hdr_phys_t *sa_hdr_phys;
1268 	dmu_buf_impl_t *db = SA_GET_DB(hdl, buftype);
1269 	dmu_object_type_t bonustype = SA_BONUSTYPE_FROM_DB(db);
1270 	sa_os_t *sa = hdl->sa_os->os_sa;
1271 	sa_idx_tab_t *idx_tab;
1272 
1273 	sa_hdr_phys = SA_GET_HDR(hdl, buftype);
1274 
1275 	mutex_enter(&sa->sa_lock);
1276 
1277 	/* Do we need to byteswap? */
1278 
1279 	/* only check if not old znode */
1280 	if (IS_SA_BONUSTYPE(bonustype) && sa_hdr_phys->sa_magic != SA_MAGIC &&
1281 	    sa_hdr_phys->sa_magic != 0) {
1282 		VERIFY(BSWAP_32(sa_hdr_phys->sa_magic) == SA_MAGIC);
1283 		sa_byteswap(hdl, buftype);
1284 	}
1285 
1286 	idx_tab = sa_find_idx_tab(hdl->sa_os, bonustype, sa_hdr_phys);
1287 
1288 	if (buftype == SA_BONUS)
1289 		hdl->sa_bonus_tab = idx_tab;
1290 	else
1291 		hdl->sa_spill_tab = idx_tab;
1292 
1293 	mutex_exit(&sa->sa_lock);
1294 	return (0);
1295 }
1296 
1297 /*ARGSUSED*/
1298 static void
1299 sa_evict(void *dbu)
1300 {
1301 	panic("evicting sa dbuf\n");
1302 }
1303 
1304 static void
1305 sa_idx_tab_rele(objset_t *os, void *arg)
1306 {
1307 	sa_os_t *sa = os->os_sa;
1308 	sa_idx_tab_t *idx_tab = arg;
1309 
1310 	if (idx_tab == NULL)
1311 		return;
1312 
1313 	mutex_enter(&sa->sa_lock);
1314 	if (refcount_remove(&idx_tab->sa_refcount, NULL) == 0) {
1315 		list_remove(&idx_tab->sa_layout->lot_idx_tab, idx_tab);
1316 		if (idx_tab->sa_variable_lengths)
1317 			kmem_free(idx_tab->sa_variable_lengths,
1318 			    sizeof (uint16_t) *
1319 			    idx_tab->sa_layout->lot_var_sizes);
1320 		refcount_destroy(&idx_tab->sa_refcount);
1321 		kmem_free(idx_tab->sa_idx_tab,
1322 		    sizeof (uint32_t) * sa->sa_num_attrs);
1323 		kmem_free(idx_tab, sizeof (sa_idx_tab_t));
1324 	}
1325 	mutex_exit(&sa->sa_lock);
1326 }
1327 
1328 static void
1329 sa_idx_tab_hold(objset_t *os, sa_idx_tab_t *idx_tab)
1330 {
1331 	sa_os_t *sa = os->os_sa;
1332 
1333 	ASSERT(MUTEX_HELD(&sa->sa_lock));
1334 	(void) refcount_add(&idx_tab->sa_refcount, NULL);
1335 }
1336 
1337 void
1338 sa_handle_destroy(sa_handle_t *hdl)
1339 {
1340 	dmu_buf_t *db = hdl->sa_bonus;
1341 
1342 	mutex_enter(&hdl->sa_lock);
1343 	(void) dmu_buf_remove_user(db, &hdl->sa_dbu);
1344 
1345 	if (hdl->sa_bonus_tab)
1346 		sa_idx_tab_rele(hdl->sa_os, hdl->sa_bonus_tab);
1347 
1348 	if (hdl->sa_spill_tab)
1349 		sa_idx_tab_rele(hdl->sa_os, hdl->sa_spill_tab);
1350 
1351 	dmu_buf_rele(hdl->sa_bonus, NULL);
1352 
1353 	if (hdl->sa_spill)
1354 		dmu_buf_rele((dmu_buf_t *)hdl->sa_spill, NULL);
1355 	mutex_exit(&hdl->sa_lock);
1356 
1357 	kmem_cache_free(sa_cache, hdl);
1358 }
1359 
1360 int
1361 sa_handle_get_from_db(objset_t *os, dmu_buf_t *db, void *userp,
1362     sa_handle_type_t hdl_type, sa_handle_t **handlepp)
1363 {
1364 	int error = 0;
1365 	dmu_object_info_t doi;
1366 	sa_handle_t *handle = NULL;
1367 
1368 #ifdef ZFS_DEBUG
1369 	dmu_object_info_from_db(db, &doi);
1370 	ASSERT(doi.doi_bonus_type == DMU_OT_SA ||
1371 	    doi.doi_bonus_type == DMU_OT_ZNODE);
1372 #endif
1373 	/* find handle, if it exists */
1374 	/* if one doesn't exist then create a new one, and initialize it */
1375 
1376 	if (hdl_type == SA_HDL_SHARED)
1377 		handle = dmu_buf_get_user(db);
1378 
1379 	if (handle == NULL) {
1380 		sa_handle_t *winner = NULL;
1381 
1382 		handle = kmem_cache_alloc(sa_cache, KM_SLEEP);
1383 		handle->sa_dbu.dbu_evict_func = NULL;
1384 		handle->sa_userp = userp;
1385 		handle->sa_bonus = db;
1386 		handle->sa_os = os;
1387 		handle->sa_spill = NULL;
1388 		handle->sa_bonus_tab = NULL;
1389 		handle->sa_spill_tab = NULL;
1390 
1391 		error = sa_build_index(handle, SA_BONUS);
1392 
1393 		if (hdl_type == SA_HDL_SHARED) {
1394 			dmu_buf_init_user(&handle->sa_dbu, sa_evict, NULL);
1395 			winner = dmu_buf_set_user_ie(db, &handle->sa_dbu);
1396 		}
1397 
1398 		if (winner != NULL) {
1399 			kmem_cache_free(sa_cache, handle);
1400 			handle = winner;
1401 		}
1402 	}
1403 	*handlepp = handle;
1404 
1405 	return (error);
1406 }
1407 
1408 int
1409 sa_handle_get(objset_t *objset, uint64_t objid, void *userp,
1410     sa_handle_type_t hdl_type, sa_handle_t **handlepp)
1411 {
1412 	dmu_buf_t *db;
1413 	int error;
1414 
1415 	if (error = dmu_bonus_hold(objset, objid, NULL, &db))
1416 		return (error);
1417 
1418 	return (sa_handle_get_from_db(objset, db, userp, hdl_type,
1419 	    handlepp));
1420 }
1421 
1422 int
1423 sa_buf_hold(objset_t *objset, uint64_t obj_num, void *tag, dmu_buf_t **db)
1424 {
1425 	return (dmu_bonus_hold(objset, obj_num, tag, db));
1426 }
1427 
1428 void
1429 sa_buf_rele(dmu_buf_t *db, void *tag)
1430 {
1431 	dmu_buf_rele(db, tag);
1432 }
1433 
1434 int
1435 sa_lookup_impl(sa_handle_t *hdl, sa_bulk_attr_t *bulk, int count)
1436 {
1437 	ASSERT(hdl);
1438 	ASSERT(MUTEX_HELD(&hdl->sa_lock));
1439 	return (sa_attr_op(hdl, bulk, count, SA_LOOKUP, NULL));
1440 }
1441 
1442 int
1443 sa_lookup(sa_handle_t *hdl, sa_attr_type_t attr, void *buf, uint32_t buflen)
1444 {
1445 	int error;
1446 	sa_bulk_attr_t bulk;
1447 
1448 	bulk.sa_attr = attr;
1449 	bulk.sa_data = buf;
1450 	bulk.sa_length = buflen;
1451 	bulk.sa_data_func = NULL;
1452 
1453 	ASSERT(hdl);
1454 	mutex_enter(&hdl->sa_lock);
1455 	error = sa_lookup_impl(hdl, &bulk, 1);
1456 	mutex_exit(&hdl->sa_lock);
1457 	return (error);
1458 }
1459 
1460 #ifdef _KERNEL
1461 int
1462 sa_lookup_uio(sa_handle_t *hdl, sa_attr_type_t attr, uio_t *uio)
1463 {
1464 	int error;
1465 	sa_bulk_attr_t bulk;
1466 
1467 	bulk.sa_data = NULL;
1468 	bulk.sa_attr = attr;
1469 	bulk.sa_data_func = NULL;
1470 
1471 	ASSERT(hdl);
1472 
1473 	mutex_enter(&hdl->sa_lock);
1474 	if ((error = sa_attr_op(hdl, &bulk, 1, SA_LOOKUP, NULL)) == 0) {
1475 		error = uiomove((void *)bulk.sa_addr, MIN(bulk.sa_size,
1476 		    uio->uio_resid), UIO_READ, uio);
1477 	}
1478 	mutex_exit(&hdl->sa_lock);
1479 	return (error);
1480 
1481 }
1482 #endif
1483 
1484 void *
1485 sa_find_idx_tab(objset_t *os, dmu_object_type_t bonustype, void *data)
1486 {
1487 	sa_idx_tab_t *idx_tab;
1488 	sa_hdr_phys_t *hdr = (sa_hdr_phys_t *)data;
1489 	sa_os_t *sa = os->os_sa;
1490 	sa_lot_t *tb, search;
1491 	avl_index_t loc;
1492 
1493 	/*
1494 	 * Deterimine layout number.  If SA node and header == 0 then
1495 	 * force the index table to the dummy "1" empty layout.
1496 	 *
1497 	 * The layout number would only be zero for a newly created file
1498 	 * that has not added any attributes yet, or with crypto enabled which
1499 	 * doesn't write any attributes to the bonus buffer.
1500 	 */
1501 
1502 	search.lot_num = SA_LAYOUT_NUM(hdr, bonustype);
1503 
1504 	tb = avl_find(&sa->sa_layout_num_tree, &search, &loc);
1505 
1506 	/* Verify header size is consistent with layout information */
1507 	ASSERT(tb);
1508 	ASSERT(IS_SA_BONUSTYPE(bonustype) &&
1509 	    SA_HDR_SIZE_MATCH_LAYOUT(hdr, tb) || !IS_SA_BONUSTYPE(bonustype) ||
1510 	    (IS_SA_BONUSTYPE(bonustype) && hdr->sa_layout_info == 0));
1511 
1512 	/*
1513 	 * See if any of the already existing TOC entries can be reused?
1514 	 */
1515 
1516 	for (idx_tab = list_head(&tb->lot_idx_tab); idx_tab;
1517 	    idx_tab = list_next(&tb->lot_idx_tab, idx_tab)) {
1518 		boolean_t valid_idx = B_TRUE;
1519 		int i;
1520 
1521 		if (tb->lot_var_sizes != 0 &&
1522 		    idx_tab->sa_variable_lengths != NULL) {
1523 			for (i = 0; i != tb->lot_var_sizes; i++) {
1524 				if (hdr->sa_lengths[i] !=
1525 				    idx_tab->sa_variable_lengths[i]) {
1526 					valid_idx = B_FALSE;
1527 					break;
1528 				}
1529 			}
1530 		}
1531 		if (valid_idx) {
1532 			sa_idx_tab_hold(os, idx_tab);
1533 			return (idx_tab);
1534 		}
1535 	}
1536 
1537 	/* No such luck, create a new entry */
1538 	idx_tab = kmem_zalloc(sizeof (sa_idx_tab_t), KM_SLEEP);
1539 	idx_tab->sa_idx_tab =
1540 	    kmem_zalloc(sizeof (uint32_t) * sa->sa_num_attrs, KM_SLEEP);
1541 	idx_tab->sa_layout = tb;
1542 	refcount_create(&idx_tab->sa_refcount);
1543 	if (tb->lot_var_sizes)
1544 		idx_tab->sa_variable_lengths = kmem_alloc(sizeof (uint16_t) *
1545 		    tb->lot_var_sizes, KM_SLEEP);
1546 
1547 	sa_attr_iter(os, hdr, bonustype, sa_build_idx_tab,
1548 	    tb, idx_tab);
1549 	sa_idx_tab_hold(os, idx_tab);   /* one hold for consumer */
1550 	sa_idx_tab_hold(os, idx_tab);	/* one for layout */
1551 	list_insert_tail(&tb->lot_idx_tab, idx_tab);
1552 	return (idx_tab);
1553 }
1554 
1555 void
1556 sa_default_locator(void **dataptr, uint32_t *len, uint32_t total_len,
1557     boolean_t start, void *userdata)
1558 {
1559 	ASSERT(start);
1560 
1561 	*dataptr = userdata;
1562 	*len = total_len;
1563 }
1564 
1565 static void
1566 sa_attr_register_sync(sa_handle_t *hdl, dmu_tx_t *tx)
1567 {
1568 	uint64_t attr_value = 0;
1569 	sa_os_t *sa = hdl->sa_os->os_sa;
1570 	sa_attr_table_t *tb = sa->sa_attr_table;
1571 	int i;
1572 
1573 	mutex_enter(&sa->sa_lock);
1574 
1575 	if (!sa->sa_need_attr_registration || sa->sa_master_obj == NULL) {
1576 		mutex_exit(&sa->sa_lock);
1577 		return;
1578 	}
1579 
1580 	if (sa->sa_reg_attr_obj == NULL) {
1581 		sa->sa_reg_attr_obj = zap_create_link(hdl->sa_os,
1582 		    DMU_OT_SA_ATTR_REGISTRATION,
1583 		    sa->sa_master_obj, SA_REGISTRY, tx);
1584 	}
1585 	for (i = 0; i != sa->sa_num_attrs; i++) {
1586 		if (sa->sa_attr_table[i].sa_registered)
1587 			continue;
1588 		ATTR_ENCODE(attr_value, tb[i].sa_attr, tb[i].sa_length,
1589 		    tb[i].sa_byteswap);
1590 		VERIFY(0 == zap_update(hdl->sa_os, sa->sa_reg_attr_obj,
1591 		    tb[i].sa_name, 8, 1, &attr_value, tx));
1592 		tb[i].sa_registered = B_TRUE;
1593 	}
1594 	sa->sa_need_attr_registration = B_FALSE;
1595 	mutex_exit(&sa->sa_lock);
1596 }
1597 
1598 /*
1599  * Replace all attributes with attributes specified in template.
1600  * If dnode had a spill buffer then those attributes will be
1601  * also be replaced, possibly with just an empty spill block
1602  *
1603  * This interface is intended to only be used for bulk adding of
1604  * attributes for a new file.  It will also be used by the ZPL
1605  * when converting and old formatted znode to native SA support.
1606  */
1607 int
1608 sa_replace_all_by_template_locked(sa_handle_t *hdl, sa_bulk_attr_t *attr_desc,
1609     int attr_count, dmu_tx_t *tx)
1610 {
1611 	sa_os_t *sa = hdl->sa_os->os_sa;
1612 
1613 	if (sa->sa_need_attr_registration)
1614 		sa_attr_register_sync(hdl, tx);
1615 	return (sa_build_layouts(hdl, attr_desc, attr_count, tx));
1616 }
1617 
1618 int
1619 sa_replace_all_by_template(sa_handle_t *hdl, sa_bulk_attr_t *attr_desc,
1620     int attr_count, dmu_tx_t *tx)
1621 {
1622 	int error;
1623 
1624 	mutex_enter(&hdl->sa_lock);
1625 	error = sa_replace_all_by_template_locked(hdl, attr_desc,
1626 	    attr_count, tx);
1627 	mutex_exit(&hdl->sa_lock);
1628 	return (error);
1629 }
1630 
1631 /*
1632  * Add/remove a single attribute or replace a variable-sized attribute value
1633  * with a value of a different size, and then rewrite the entire set
1634  * of attributes.
1635  * Same-length attribute value replacement (including fixed-length attributes)
1636  * is handled more efficiently by the upper layers.
1637  */
1638 static int
1639 sa_modify_attrs(sa_handle_t *hdl, sa_attr_type_t newattr,
1640     sa_data_op_t action, sa_data_locator_t *locator, void *datastart,
1641     uint16_t buflen, dmu_tx_t *tx)
1642 {
1643 	sa_os_t *sa = hdl->sa_os->os_sa;
1644 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)hdl->sa_bonus;
1645 	dnode_t *dn;
1646 	sa_bulk_attr_t *attr_desc;
1647 	void *old_data[2];
1648 	int bonus_attr_count = 0;
1649 	int bonus_data_size = 0;
1650 	int spill_data_size = 0;
1651 	int spill_attr_count = 0;
1652 	int error;
1653 	uint16_t length, reg_length;
1654 	int i, j, k, length_idx;
1655 	sa_hdr_phys_t *hdr;
1656 	sa_idx_tab_t *idx_tab;
1657 	int attr_count;
1658 	int count;
1659 
1660 	ASSERT(MUTEX_HELD(&hdl->sa_lock));
1661 
1662 	/* First make of copy of the old data */
1663 
1664 	DB_DNODE_ENTER(db);
1665 	dn = DB_DNODE(db);
1666 	if (dn->dn_bonuslen != 0) {
1667 		bonus_data_size = hdl->sa_bonus->db_size;
1668 		old_data[0] = kmem_alloc(bonus_data_size, KM_SLEEP);
1669 		bcopy(hdl->sa_bonus->db_data, old_data[0],
1670 		    hdl->sa_bonus->db_size);
1671 		bonus_attr_count = hdl->sa_bonus_tab->sa_layout->lot_attr_count;
1672 	} else {
1673 		old_data[0] = NULL;
1674 	}
1675 	DB_DNODE_EXIT(db);
1676 
1677 	/* Bring spill buffer online if it isn't currently */
1678 
1679 	if ((error = sa_get_spill(hdl)) == 0) {
1680 		spill_data_size = hdl->sa_spill->db_size;
1681 		old_data[1] = kmem_alloc(spill_data_size, KM_SLEEP);
1682 		bcopy(hdl->sa_spill->db_data, old_data[1],
1683 		    hdl->sa_spill->db_size);
1684 		spill_attr_count =
1685 		    hdl->sa_spill_tab->sa_layout->lot_attr_count;
1686 	} else if (error && error != ENOENT) {
1687 		if (old_data[0])
1688 			kmem_free(old_data[0], bonus_data_size);
1689 		return (error);
1690 	} else {
1691 		old_data[1] = NULL;
1692 	}
1693 
1694 	/* build descriptor of all attributes */
1695 
1696 	attr_count = bonus_attr_count + spill_attr_count;
1697 	if (action == SA_ADD)
1698 		attr_count++;
1699 	else if (action == SA_REMOVE)
1700 		attr_count--;
1701 
1702 	attr_desc = kmem_zalloc(sizeof (sa_bulk_attr_t) * attr_count, KM_SLEEP);
1703 
1704 	/*
1705 	 * loop through bonus and spill buffer if it exists, and
1706 	 * build up new attr_descriptor to reset the attributes
1707 	 */
1708 	k = j = 0;
1709 	count = bonus_attr_count;
1710 	hdr = SA_GET_HDR(hdl, SA_BONUS);
1711 	idx_tab = SA_IDX_TAB_GET(hdl, SA_BONUS);
1712 	for (; k != 2; k++) {
1713 		/*
1714 		 * Iterate over each attribute in layout.  Fetch the
1715 		 * size of variable-length attributes needing rewrite
1716 		 * from sa_lengths[].
1717 		 */
1718 		for (i = 0, length_idx = 0; i != count; i++) {
1719 			sa_attr_type_t attr;
1720 
1721 			attr = idx_tab->sa_layout->lot_attrs[i];
1722 			reg_length = SA_REGISTERED_LEN(sa, attr);
1723 			if (reg_length == 0) {
1724 				length = hdr->sa_lengths[length_idx];
1725 				length_idx++;
1726 			} else {
1727 				length = reg_length;
1728 			}
1729 			if (attr == newattr) {
1730 				/*
1731 				 * There is nothing to do for SA_REMOVE,
1732 				 * so it is just skipped.
1733 				 */
1734 				if (action == SA_REMOVE)
1735 					continue;
1736 
1737 				/*
1738 				 * Duplicate attributes are not allowed, so the
1739 				 * action can not be SA_ADD here.
1740 				 */
1741 				ASSERT3S(action, ==, SA_REPLACE);
1742 
1743 				/*
1744 				 * Only a variable-sized attribute can be
1745 				 * replaced here, and its size must be changing.
1746 				 */
1747 				ASSERT3U(reg_length, ==, 0);
1748 				ASSERT3U(length, !=, buflen);
1749 				SA_ADD_BULK_ATTR(attr_desc, j, attr,
1750 				    locator, datastart, buflen);
1751 			} else {
1752 				SA_ADD_BULK_ATTR(attr_desc, j, attr,
1753 				    NULL, (void *)
1754 				    (TOC_OFF(idx_tab->sa_idx_tab[attr]) +
1755 				    (uintptr_t)old_data[k]), length);
1756 			}
1757 		}
1758 		if (k == 0 && hdl->sa_spill) {
1759 			hdr = SA_GET_HDR(hdl, SA_SPILL);
1760 			idx_tab = SA_IDX_TAB_GET(hdl, SA_SPILL);
1761 			count = spill_attr_count;
1762 		} else {
1763 			break;
1764 		}
1765 	}
1766 	if (action == SA_ADD) {
1767 		reg_length = SA_REGISTERED_LEN(sa, newattr);
1768 		IMPLY(reg_length != 0, reg_length == buflen);
1769 		SA_ADD_BULK_ATTR(attr_desc, j, newattr, locator,
1770 		    datastart, buflen);
1771 	}
1772 	ASSERT3U(j, ==, attr_count);
1773 
1774 	error = sa_build_layouts(hdl, attr_desc, attr_count, tx);
1775 
1776 	if (old_data[0])
1777 		kmem_free(old_data[0], bonus_data_size);
1778 	if (old_data[1])
1779 		kmem_free(old_data[1], spill_data_size);
1780 	kmem_free(attr_desc, sizeof (sa_bulk_attr_t) * attr_count);
1781 
1782 	return (error);
1783 }
1784 
1785 static int
1786 sa_bulk_update_impl(sa_handle_t *hdl, sa_bulk_attr_t *bulk, int count,
1787     dmu_tx_t *tx)
1788 {
1789 	int error;
1790 	sa_os_t *sa = hdl->sa_os->os_sa;
1791 	dmu_object_type_t bonustype;
1792 
1793 	bonustype = SA_BONUSTYPE_FROM_DB(SA_GET_DB(hdl, SA_BONUS));
1794 
1795 	ASSERT(hdl);
1796 	ASSERT(MUTEX_HELD(&hdl->sa_lock));
1797 
1798 	/* sync out registration table if necessary */
1799 	if (sa->sa_need_attr_registration)
1800 		sa_attr_register_sync(hdl, tx);
1801 
1802 	error = sa_attr_op(hdl, bulk, count, SA_UPDATE, tx);
1803 	if (error == 0 && !IS_SA_BONUSTYPE(bonustype) && sa->sa_update_cb)
1804 		sa->sa_update_cb(hdl, tx);
1805 
1806 	return (error);
1807 }
1808 
1809 /*
1810  * update or add new attribute
1811  */
1812 int
1813 sa_update(sa_handle_t *hdl, sa_attr_type_t type,
1814     void *buf, uint32_t buflen, dmu_tx_t *tx)
1815 {
1816 	int error;
1817 	sa_bulk_attr_t bulk;
1818 
1819 	bulk.sa_attr = type;
1820 	bulk.sa_data_func = NULL;
1821 	bulk.sa_length = buflen;
1822 	bulk.sa_data = buf;
1823 
1824 	mutex_enter(&hdl->sa_lock);
1825 	error = sa_bulk_update_impl(hdl, &bulk, 1, tx);
1826 	mutex_exit(&hdl->sa_lock);
1827 	return (error);
1828 }
1829 
1830 int
1831 sa_update_from_cb(sa_handle_t *hdl, sa_attr_type_t attr,
1832     uint32_t buflen, sa_data_locator_t *locator, void *userdata, dmu_tx_t *tx)
1833 {
1834 	int error;
1835 	sa_bulk_attr_t bulk;
1836 
1837 	bulk.sa_attr = attr;
1838 	bulk.sa_data = userdata;
1839 	bulk.sa_data_func = locator;
1840 	bulk.sa_length = buflen;
1841 
1842 	mutex_enter(&hdl->sa_lock);
1843 	error = sa_bulk_update_impl(hdl, &bulk, 1, tx);
1844 	mutex_exit(&hdl->sa_lock);
1845 	return (error);
1846 }
1847 
1848 /*
1849  * Return size of an attribute
1850  */
1851 
1852 int
1853 sa_size(sa_handle_t *hdl, sa_attr_type_t attr, int *size)
1854 {
1855 	sa_bulk_attr_t bulk;
1856 	int error;
1857 
1858 	bulk.sa_data = NULL;
1859 	bulk.sa_attr = attr;
1860 	bulk.sa_data_func = NULL;
1861 
1862 	ASSERT(hdl);
1863 	mutex_enter(&hdl->sa_lock);
1864 	if ((error = sa_attr_op(hdl, &bulk, 1, SA_LOOKUP, NULL)) != 0) {
1865 		mutex_exit(&hdl->sa_lock);
1866 		return (error);
1867 	}
1868 	*size = bulk.sa_size;
1869 
1870 	mutex_exit(&hdl->sa_lock);
1871 	return (0);
1872 }
1873 
1874 int
1875 sa_bulk_lookup_locked(sa_handle_t *hdl, sa_bulk_attr_t *attrs, int count)
1876 {
1877 	ASSERT(hdl);
1878 	ASSERT(MUTEX_HELD(&hdl->sa_lock));
1879 	return (sa_lookup_impl(hdl, attrs, count));
1880 }
1881 
1882 int
1883 sa_bulk_lookup(sa_handle_t *hdl, sa_bulk_attr_t *attrs, int count)
1884 {
1885 	int error;
1886 
1887 	ASSERT(hdl);
1888 	mutex_enter(&hdl->sa_lock);
1889 	error = sa_bulk_lookup_locked(hdl, attrs, count);
1890 	mutex_exit(&hdl->sa_lock);
1891 	return (error);
1892 }
1893 
1894 int
1895 sa_bulk_update(sa_handle_t *hdl, sa_bulk_attr_t *attrs, int count, dmu_tx_t *tx)
1896 {
1897 	int error;
1898 
1899 	ASSERT(hdl);
1900 	mutex_enter(&hdl->sa_lock);
1901 	error = sa_bulk_update_impl(hdl, attrs, count, tx);
1902 	mutex_exit(&hdl->sa_lock);
1903 	return (error);
1904 }
1905 
1906 int
1907 sa_remove(sa_handle_t *hdl, sa_attr_type_t attr, dmu_tx_t *tx)
1908 {
1909 	int error;
1910 
1911 	mutex_enter(&hdl->sa_lock);
1912 	error = sa_modify_attrs(hdl, attr, SA_REMOVE, NULL,
1913 	    NULL, 0, tx);
1914 	mutex_exit(&hdl->sa_lock);
1915 	return (error);
1916 }
1917 
1918 void
1919 sa_object_info(sa_handle_t *hdl, dmu_object_info_t *doi)
1920 {
1921 	dmu_object_info_from_db((dmu_buf_t *)hdl->sa_bonus, doi);
1922 }
1923 
1924 void
1925 sa_object_size(sa_handle_t *hdl, uint32_t *blksize, u_longlong_t *nblocks)
1926 {
1927 	dmu_object_size_from_db((dmu_buf_t *)hdl->sa_bonus,
1928 	    blksize, nblocks);
1929 }
1930 
1931 void
1932 sa_set_userp(sa_handle_t *hdl, void *ptr)
1933 {
1934 	hdl->sa_userp = ptr;
1935 }
1936 
1937 dmu_buf_t *
1938 sa_get_db(sa_handle_t *hdl)
1939 {
1940 	return ((dmu_buf_t *)hdl->sa_bonus);
1941 }
1942 
1943 void *
1944 sa_get_userdata(sa_handle_t *hdl)
1945 {
1946 	return (hdl->sa_userp);
1947 }
1948 
1949 void
1950 sa_register_update_callback_locked(objset_t *os, sa_update_cb_t *func)
1951 {
1952 	ASSERT(MUTEX_HELD(&os->os_sa->sa_lock));
1953 	os->os_sa->sa_update_cb = func;
1954 }
1955 
1956 void
1957 sa_register_update_callback(objset_t *os, sa_update_cb_t *func)
1958 {
1959 
1960 	mutex_enter(&os->os_sa->sa_lock);
1961 	sa_register_update_callback_locked(os, func);
1962 	mutex_exit(&os->os_sa->sa_lock);
1963 }
1964 
1965 uint64_t
1966 sa_handle_object(sa_handle_t *hdl)
1967 {
1968 	return (hdl->sa_bonus->db_object);
1969 }
1970 
1971 boolean_t
1972 sa_enabled(objset_t *os)
1973 {
1974 	return (os->os_sa == NULL);
1975 }
1976 
1977 int
1978 sa_set_sa_object(objset_t *os, uint64_t sa_object)
1979 {
1980 	sa_os_t *sa = os->os_sa;
1981 
1982 	if (sa->sa_master_obj)
1983 		return (1);
1984 
1985 	sa->sa_master_obj = sa_object;
1986 
1987 	return (0);
1988 }
1989 
1990 int
1991 sa_hdrsize(void *arg)
1992 {
1993 	sa_hdr_phys_t *hdr = arg;
1994 
1995 	return (SA_HDR_SIZE(hdr));
1996 }
1997 
1998 void
1999 sa_handle_lock(sa_handle_t *hdl)
2000 {
2001 	ASSERT(hdl);
2002 	mutex_enter(&hdl->sa_lock);
2003 }
2004 
2005 void
2006 sa_handle_unlock(sa_handle_t *hdl)
2007 {
2008 	ASSERT(hdl);
2009 	mutex_exit(&hdl->sa_lock);
2010 }
2011