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