]> bbs.cooldavid.org Git - net-next-2.6.git/blob - fs/ocfs2/xattr.c
ocfs2: Set xattr block entries with ocfs2_xa_set()
[net-next-2.6.git] / fs / ocfs2 / xattr.c
1 /* -*- mode: c; c-basic-offset: 8; -*-
2  * vim: noexpandtab sw=8 ts=8 sts=0:
3  *
4  * xattr.c
5  *
6  * Copyright (C) 2004, 2008 Oracle.  All rights reserved.
7  *
8  * CREDITS:
9  * Lots of code in this file is copy from linux/fs/ext3/xattr.c.
10  * Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public
14  * License version 2 as published by the Free Software Foundation.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * General Public License for more details.
20  */
21
22 #include <linux/capability.h>
23 #include <linux/fs.h>
24 #include <linux/types.h>
25 #include <linux/slab.h>
26 #include <linux/highmem.h>
27 #include <linux/pagemap.h>
28 #include <linux/uio.h>
29 #include <linux/sched.h>
30 #include <linux/splice.h>
31 #include <linux/mount.h>
32 #include <linux/writeback.h>
33 #include <linux/falloc.h>
34 #include <linux/sort.h>
35 #include <linux/init.h>
36 #include <linux/module.h>
37 #include <linux/string.h>
38 #include <linux/security.h>
39
40 #define MLOG_MASK_PREFIX ML_XATTR
41 #include <cluster/masklog.h>
42
43 #include "ocfs2.h"
44 #include "alloc.h"
45 #include "blockcheck.h"
46 #include "dlmglue.h"
47 #include "file.h"
48 #include "symlink.h"
49 #include "sysfile.h"
50 #include "inode.h"
51 #include "journal.h"
52 #include "ocfs2_fs.h"
53 #include "suballoc.h"
54 #include "uptodate.h"
55 #include "buffer_head_io.h"
56 #include "super.h"
57 #include "xattr.h"
58 #include "refcounttree.h"
59 #include "acl.h"
60
61 struct ocfs2_xattr_def_value_root {
62         struct ocfs2_xattr_value_root   xv;
63         struct ocfs2_extent_rec         er;
64 };
65
66 struct ocfs2_xattr_bucket {
67         /* The inode these xattrs are associated with */
68         struct inode *bu_inode;
69
70         /* The actual buffers that make up the bucket */
71         struct buffer_head *bu_bhs[OCFS2_XATTR_MAX_BLOCKS_PER_BUCKET];
72
73         /* How many blocks make up one bucket for this filesystem */
74         int bu_blocks;
75 };
76
77 struct ocfs2_xattr_set_ctxt {
78         handle_t *handle;
79         struct ocfs2_alloc_context *meta_ac;
80         struct ocfs2_alloc_context *data_ac;
81         struct ocfs2_cached_dealloc_ctxt dealloc;
82 };
83
84 #define OCFS2_XATTR_ROOT_SIZE   (sizeof(struct ocfs2_xattr_def_value_root))
85 #define OCFS2_XATTR_INLINE_SIZE 80
86 #define OCFS2_XATTR_HEADER_GAP  4
87 #define OCFS2_XATTR_FREE_IN_IBODY       (OCFS2_MIN_XATTR_INLINE_SIZE \
88                                          - sizeof(struct ocfs2_xattr_header) \
89                                          - OCFS2_XATTR_HEADER_GAP)
90 #define OCFS2_XATTR_FREE_IN_BLOCK(ptr)  ((ptr)->i_sb->s_blocksize \
91                                          - sizeof(struct ocfs2_xattr_block) \
92                                          - sizeof(struct ocfs2_xattr_header) \
93                                          - OCFS2_XATTR_HEADER_GAP)
94
95 static struct ocfs2_xattr_def_value_root def_xv = {
96         .xv.xr_list.l_count = cpu_to_le16(1),
97 };
98
99 struct xattr_handler *ocfs2_xattr_handlers[] = {
100         &ocfs2_xattr_user_handler,
101         &ocfs2_xattr_acl_access_handler,
102         &ocfs2_xattr_acl_default_handler,
103         &ocfs2_xattr_trusted_handler,
104         &ocfs2_xattr_security_handler,
105         NULL
106 };
107
108 static struct xattr_handler *ocfs2_xattr_handler_map[OCFS2_XATTR_MAX] = {
109         [OCFS2_XATTR_INDEX_USER]        = &ocfs2_xattr_user_handler,
110         [OCFS2_XATTR_INDEX_POSIX_ACL_ACCESS]
111                                         = &ocfs2_xattr_acl_access_handler,
112         [OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT]
113                                         = &ocfs2_xattr_acl_default_handler,
114         [OCFS2_XATTR_INDEX_TRUSTED]     = &ocfs2_xattr_trusted_handler,
115         [OCFS2_XATTR_INDEX_SECURITY]    = &ocfs2_xattr_security_handler,
116 };
117
118 struct ocfs2_xattr_info {
119         int             xi_name_index;
120         const char      *xi_name;
121         int             xi_name_len;
122         const void      *xi_value;
123         size_t          xi_value_len;
124 };
125
126 struct ocfs2_xattr_search {
127         struct buffer_head *inode_bh;
128         /*
129          * xattr_bh point to the block buffer head which has extended attribute
130          * when extended attribute in inode, xattr_bh is equal to inode_bh.
131          */
132         struct buffer_head *xattr_bh;
133         struct ocfs2_xattr_header *header;
134         struct ocfs2_xattr_bucket *bucket;
135         void *base;
136         void *end;
137         struct ocfs2_xattr_entry *here;
138         int not_found;
139 };
140
141 /* Operations on struct ocfs2_xa_entry */
142 struct ocfs2_xa_loc;
143 struct ocfs2_xa_loc_operations {
144         /*
145          * Journal functions
146          */
147         int (*xlo_journal_access)(handle_t *handle, struct ocfs2_xa_loc *loc,
148                                   int type);
149         void (*xlo_journal_dirty)(handle_t *handle, struct ocfs2_xa_loc *loc);
150
151         /*
152          * Return a pointer to the appropriate buffer in loc->xl_storage
153          * at the given offset from loc->xl_header.
154          */
155         void *(*xlo_offset_pointer)(struct ocfs2_xa_loc *loc, int offset);
156
157         /* Can we reuse the existing entry for the new value? */
158         int (*xlo_can_reuse)(struct ocfs2_xa_loc *loc,
159                              struct ocfs2_xattr_info *xi);
160
161         /* How much space is needed for the new value? */
162         int (*xlo_check_space)(struct ocfs2_xa_loc *loc,
163                                struct ocfs2_xattr_info *xi);
164
165         /*
166          * Return the offset of the first name+value pair.  This is
167          * the start of our downward-filling free space.
168          */
169         int (*xlo_get_free_start)(struct ocfs2_xa_loc *loc);
170
171         /*
172          * Remove the name+value at this location.  Do whatever is
173          * appropriate with the remaining name+value pairs.
174          */
175         void (*xlo_wipe_namevalue)(struct ocfs2_xa_loc *loc);
176
177         /* Fill xl_entry with a new entry */
178         void (*xlo_add_entry)(struct ocfs2_xa_loc *loc, u32 name_hash);
179
180         /* Add name+value storage to an entry */
181         void (*xlo_add_namevalue)(struct ocfs2_xa_loc *loc, int size);
182
183         /*
184          * Initialize the value buf's access and bh fields for this entry.
185          * ocfs2_xa_fill_value_buf() will handle the xv pointer.
186          */
187         void (*xlo_fill_value_buf)(struct ocfs2_xa_loc *loc,
188                                    struct ocfs2_xattr_value_buf *vb);
189 };
190
191 /*
192  * Describes an xattr entry location.  This is a memory structure
193  * tracking the on-disk structure.
194  */
195 struct ocfs2_xa_loc {
196         /* This xattr belongs to this inode */
197         struct inode *xl_inode;
198
199         /* The ocfs2_xattr_header inside the on-disk storage. Not NULL. */
200         struct ocfs2_xattr_header *xl_header;
201
202         /* Bytes from xl_header to the end of the storage */
203         int xl_size;
204
205         /*
206          * The ocfs2_xattr_entry this location describes.  If this is
207          * NULL, this location describes the on-disk structure where it
208          * would have been.
209          */
210         struct ocfs2_xattr_entry *xl_entry;
211
212         /*
213          * Internal housekeeping
214          */
215
216         /* Buffer(s) containing this entry */
217         void *xl_storage;
218
219         /* Operations on the storage backing this location */
220         const struct ocfs2_xa_loc_operations *xl_ops;
221 };
222
223 /*
224  * Convenience functions to calculate how much space is needed for a
225  * given name+value pair
226  */
227 static int namevalue_size(int name_len, uint64_t value_len)
228 {
229         if (value_len > OCFS2_XATTR_INLINE_SIZE)
230                 return OCFS2_XATTR_SIZE(name_len) + OCFS2_XATTR_ROOT_SIZE;
231         else
232                 return OCFS2_XATTR_SIZE(name_len) + OCFS2_XATTR_SIZE(value_len);
233 }
234
235 static int namevalue_size_xi(struct ocfs2_xattr_info *xi)
236 {
237         return namevalue_size(xi->xi_name_len, xi->xi_value_len);
238 }
239
240 static int namevalue_size_xe(struct ocfs2_xattr_entry *xe)
241 {
242         u64 value_len = le64_to_cpu(xe->xe_value_size);
243
244         BUG_ON((value_len > OCFS2_XATTR_INLINE_SIZE) &&
245                ocfs2_xattr_is_local(xe));
246         return namevalue_size(xe->xe_name_len, value_len);
247 }
248
249
250 static int ocfs2_xattr_bucket_get_name_value(struct super_block *sb,
251                                              struct ocfs2_xattr_header *xh,
252                                              int index,
253                                              int *block_off,
254                                              int *new_offset);
255
256 static int ocfs2_xattr_block_find(struct inode *inode,
257                                   int name_index,
258                                   const char *name,
259                                   struct ocfs2_xattr_search *xs);
260 static int ocfs2_xattr_index_block_find(struct inode *inode,
261                                         struct buffer_head *root_bh,
262                                         int name_index,
263                                         const char *name,
264                                         struct ocfs2_xattr_search *xs);
265
266 static int ocfs2_xattr_tree_list_index_block(struct inode *inode,
267                                         struct buffer_head *blk_bh,
268                                         char *buffer,
269                                         size_t buffer_size);
270
271 static int ocfs2_xattr_create_index_block(struct inode *inode,
272                                           struct ocfs2_xattr_search *xs,
273                                           struct ocfs2_xattr_set_ctxt *ctxt);
274
275 static int ocfs2_xattr_set_entry_index_block(struct inode *inode,
276                                              struct ocfs2_xattr_info *xi,
277                                              struct ocfs2_xattr_search *xs,
278                                              struct ocfs2_xattr_set_ctxt *ctxt);
279
280 typedef int (xattr_tree_rec_func)(struct inode *inode,
281                                   struct buffer_head *root_bh,
282                                   u64 blkno, u32 cpos, u32 len, void *para);
283 static int ocfs2_iterate_xattr_index_block(struct inode *inode,
284                                            struct buffer_head *root_bh,
285                                            xattr_tree_rec_func *rec_func,
286                                            void *para);
287 static int ocfs2_delete_xattr_in_bucket(struct inode *inode,
288                                         struct ocfs2_xattr_bucket *bucket,
289                                         void *para);
290 static int ocfs2_rm_xattr_cluster(struct inode *inode,
291                                   struct buffer_head *root_bh,
292                                   u64 blkno,
293                                   u32 cpos,
294                                   u32 len,
295                                   void *para);
296
297 static int ocfs2_mv_xattr_buckets(struct inode *inode, handle_t *handle,
298                                   u64 src_blk, u64 last_blk, u64 to_blk,
299                                   unsigned int start_bucket,
300                                   u32 *first_hash);
301 static int ocfs2_prepare_refcount_xattr(struct inode *inode,
302                                         struct ocfs2_dinode *di,
303                                         struct ocfs2_xattr_info *xi,
304                                         struct ocfs2_xattr_search *xis,
305                                         struct ocfs2_xattr_search *xbs,
306                                         struct ocfs2_refcount_tree **ref_tree,
307                                         int *meta_need,
308                                         int *credits);
309 static int ocfs2_get_xattr_tree_value_root(struct super_block *sb,
310                                            struct ocfs2_xattr_bucket *bucket,
311                                            int offset,
312                                            struct ocfs2_xattr_value_root **xv,
313                                            struct buffer_head **bh);
314
315 static inline u16 ocfs2_xattr_buckets_per_cluster(struct ocfs2_super *osb)
316 {
317         return (1 << osb->s_clustersize_bits) / OCFS2_XATTR_BUCKET_SIZE;
318 }
319
320 static inline u16 ocfs2_blocks_per_xattr_bucket(struct super_block *sb)
321 {
322         return OCFS2_XATTR_BUCKET_SIZE / (1 << sb->s_blocksize_bits);
323 }
324
325 #define bucket_blkno(_b) ((_b)->bu_bhs[0]->b_blocknr)
326 #define bucket_block(_b, _n) ((_b)->bu_bhs[(_n)]->b_data)
327 #define bucket_xh(_b) ((struct ocfs2_xattr_header *)bucket_block((_b), 0))
328
329 static struct ocfs2_xattr_bucket *ocfs2_xattr_bucket_new(struct inode *inode)
330 {
331         struct ocfs2_xattr_bucket *bucket;
332         int blks = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
333
334         BUG_ON(blks > OCFS2_XATTR_MAX_BLOCKS_PER_BUCKET);
335
336         bucket = kzalloc(sizeof(struct ocfs2_xattr_bucket), GFP_NOFS);
337         if (bucket) {
338                 bucket->bu_inode = inode;
339                 bucket->bu_blocks = blks;
340         }
341
342         return bucket;
343 }
344
345 static void ocfs2_xattr_bucket_relse(struct ocfs2_xattr_bucket *bucket)
346 {
347         int i;
348
349         for (i = 0; i < bucket->bu_blocks; i++) {
350                 brelse(bucket->bu_bhs[i]);
351                 bucket->bu_bhs[i] = NULL;
352         }
353 }
354
355 static void ocfs2_xattr_bucket_free(struct ocfs2_xattr_bucket *bucket)
356 {
357         if (bucket) {
358                 ocfs2_xattr_bucket_relse(bucket);
359                 bucket->bu_inode = NULL;
360                 kfree(bucket);
361         }
362 }
363
364 /*
365  * A bucket that has never been written to disk doesn't need to be
366  * read.  We just need the buffer_heads.  Don't call this for
367  * buckets that are already on disk.  ocfs2_read_xattr_bucket() initializes
368  * them fully.
369  */
370 static int ocfs2_init_xattr_bucket(struct ocfs2_xattr_bucket *bucket,
371                                    u64 xb_blkno)
372 {
373         int i, rc = 0;
374
375         for (i = 0; i < bucket->bu_blocks; i++) {
376                 bucket->bu_bhs[i] = sb_getblk(bucket->bu_inode->i_sb,
377                                               xb_blkno + i);
378                 if (!bucket->bu_bhs[i]) {
379                         rc = -EIO;
380                         mlog_errno(rc);
381                         break;
382                 }
383
384                 if (!ocfs2_buffer_uptodate(INODE_CACHE(bucket->bu_inode),
385                                            bucket->bu_bhs[i]))
386                         ocfs2_set_new_buffer_uptodate(INODE_CACHE(bucket->bu_inode),
387                                                       bucket->bu_bhs[i]);
388         }
389
390         if (rc)
391                 ocfs2_xattr_bucket_relse(bucket);
392         return rc;
393 }
394
395 /* Read the xattr bucket at xb_blkno */
396 static int ocfs2_read_xattr_bucket(struct ocfs2_xattr_bucket *bucket,
397                                    u64 xb_blkno)
398 {
399         int rc;
400
401         rc = ocfs2_read_blocks(INODE_CACHE(bucket->bu_inode), xb_blkno,
402                                bucket->bu_blocks, bucket->bu_bhs, 0,
403                                NULL);
404         if (!rc) {
405                 spin_lock(&OCFS2_SB(bucket->bu_inode->i_sb)->osb_xattr_lock);
406                 rc = ocfs2_validate_meta_ecc_bhs(bucket->bu_inode->i_sb,
407                                                  bucket->bu_bhs,
408                                                  bucket->bu_blocks,
409                                                  &bucket_xh(bucket)->xh_check);
410                 spin_unlock(&OCFS2_SB(bucket->bu_inode->i_sb)->osb_xattr_lock);
411                 if (rc)
412                         mlog_errno(rc);
413         }
414
415         if (rc)
416                 ocfs2_xattr_bucket_relse(bucket);
417         return rc;
418 }
419
420 static int ocfs2_xattr_bucket_journal_access(handle_t *handle,
421                                              struct ocfs2_xattr_bucket *bucket,
422                                              int type)
423 {
424         int i, rc = 0;
425
426         for (i = 0; i < bucket->bu_blocks; i++) {
427                 rc = ocfs2_journal_access(handle,
428                                           INODE_CACHE(bucket->bu_inode),
429                                           bucket->bu_bhs[i], type);
430                 if (rc) {
431                         mlog_errno(rc);
432                         break;
433                 }
434         }
435
436         return rc;
437 }
438
439 static void ocfs2_xattr_bucket_journal_dirty(handle_t *handle,
440                                              struct ocfs2_xattr_bucket *bucket)
441 {
442         int i;
443
444         spin_lock(&OCFS2_SB(bucket->bu_inode->i_sb)->osb_xattr_lock);
445         ocfs2_compute_meta_ecc_bhs(bucket->bu_inode->i_sb,
446                                    bucket->bu_bhs, bucket->bu_blocks,
447                                    &bucket_xh(bucket)->xh_check);
448         spin_unlock(&OCFS2_SB(bucket->bu_inode->i_sb)->osb_xattr_lock);
449
450         for (i = 0; i < bucket->bu_blocks; i++)
451                 ocfs2_journal_dirty(handle, bucket->bu_bhs[i]);
452 }
453
454 static void ocfs2_xattr_bucket_copy_data(struct ocfs2_xattr_bucket *dest,
455                                          struct ocfs2_xattr_bucket *src)
456 {
457         int i;
458         int blocksize = src->bu_inode->i_sb->s_blocksize;
459
460         BUG_ON(dest->bu_blocks != src->bu_blocks);
461         BUG_ON(dest->bu_inode != src->bu_inode);
462
463         for (i = 0; i < src->bu_blocks; i++) {
464                 memcpy(bucket_block(dest, i), bucket_block(src, i),
465                        blocksize);
466         }
467 }
468
469 static int ocfs2_validate_xattr_block(struct super_block *sb,
470                                       struct buffer_head *bh)
471 {
472         int rc;
473         struct ocfs2_xattr_block *xb =
474                 (struct ocfs2_xattr_block *)bh->b_data;
475
476         mlog(0, "Validating xattr block %llu\n",
477              (unsigned long long)bh->b_blocknr);
478
479         BUG_ON(!buffer_uptodate(bh));
480
481         /*
482          * If the ecc fails, we return the error but otherwise
483          * leave the filesystem running.  We know any error is
484          * local to this block.
485          */
486         rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &xb->xb_check);
487         if (rc)
488                 return rc;
489
490         /*
491          * Errors after here are fatal
492          */
493
494         if (!OCFS2_IS_VALID_XATTR_BLOCK(xb)) {
495                 ocfs2_error(sb,
496                             "Extended attribute block #%llu has bad "
497                             "signature %.*s",
498                             (unsigned long long)bh->b_blocknr, 7,
499                             xb->xb_signature);
500                 return -EINVAL;
501         }
502
503         if (le64_to_cpu(xb->xb_blkno) != bh->b_blocknr) {
504                 ocfs2_error(sb,
505                             "Extended attribute block #%llu has an "
506                             "invalid xb_blkno of %llu",
507                             (unsigned long long)bh->b_blocknr,
508                             (unsigned long long)le64_to_cpu(xb->xb_blkno));
509                 return -EINVAL;
510         }
511
512         if (le32_to_cpu(xb->xb_fs_generation) != OCFS2_SB(sb)->fs_generation) {
513                 ocfs2_error(sb,
514                             "Extended attribute block #%llu has an invalid "
515                             "xb_fs_generation of #%u",
516                             (unsigned long long)bh->b_blocknr,
517                             le32_to_cpu(xb->xb_fs_generation));
518                 return -EINVAL;
519         }
520
521         return 0;
522 }
523
524 static int ocfs2_read_xattr_block(struct inode *inode, u64 xb_blkno,
525                                   struct buffer_head **bh)
526 {
527         int rc;
528         struct buffer_head *tmp = *bh;
529
530         rc = ocfs2_read_block(INODE_CACHE(inode), xb_blkno, &tmp,
531                               ocfs2_validate_xattr_block);
532
533         /* If ocfs2_read_block() got us a new bh, pass it up. */
534         if (!rc && !*bh)
535                 *bh = tmp;
536
537         return rc;
538 }
539
540 static inline const char *ocfs2_xattr_prefix(int name_index)
541 {
542         struct xattr_handler *handler = NULL;
543
544         if (name_index > 0 && name_index < OCFS2_XATTR_MAX)
545                 handler = ocfs2_xattr_handler_map[name_index];
546
547         return handler ? handler->prefix : NULL;
548 }
549
550 static u32 ocfs2_xattr_name_hash(struct inode *inode,
551                                  const char *name,
552                                  int name_len)
553 {
554         /* Get hash value of uuid from super block */
555         u32 hash = OCFS2_SB(inode->i_sb)->uuid_hash;
556         int i;
557
558         /* hash extended attribute name */
559         for (i = 0; i < name_len; i++) {
560                 hash = (hash << OCFS2_HASH_SHIFT) ^
561                        (hash >> (8*sizeof(hash) - OCFS2_HASH_SHIFT)) ^
562                        *name++;
563         }
564
565         return hash;
566 }
567
568 static int ocfs2_xattr_entry_real_size(int name_len, size_t value_len)
569 {
570         return namevalue_size(name_len, value_len) +
571                 sizeof(struct ocfs2_xattr_entry);
572 }
573
574 static int ocfs2_xi_entry_usage(struct ocfs2_xattr_info *xi)
575 {
576         return namevalue_size_xi(xi) +
577                 sizeof(struct ocfs2_xattr_entry);
578 }
579
580 static int ocfs2_xe_entry_usage(struct ocfs2_xattr_entry *xe)
581 {
582         return namevalue_size_xe(xe) +
583                 sizeof(struct ocfs2_xattr_entry);
584 }
585
586 int ocfs2_calc_security_init(struct inode *dir,
587                              struct ocfs2_security_xattr_info *si,
588                              int *want_clusters,
589                              int *xattr_credits,
590                              struct ocfs2_alloc_context **xattr_ac)
591 {
592         int ret = 0;
593         struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
594         int s_size = ocfs2_xattr_entry_real_size(strlen(si->name),
595                                                  si->value_len);
596
597         /*
598          * The max space of security xattr taken inline is
599          * 256(name) + 80(value) + 16(entry) = 352 bytes,
600          * So reserve one metadata block for it is ok.
601          */
602         if (dir->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE ||
603             s_size > OCFS2_XATTR_FREE_IN_IBODY) {
604                 ret = ocfs2_reserve_new_metadata_blocks(osb, 1, xattr_ac);
605                 if (ret) {
606                         mlog_errno(ret);
607                         return ret;
608                 }
609                 *xattr_credits += OCFS2_XATTR_BLOCK_CREATE_CREDITS;
610         }
611
612         /* reserve clusters for xattr value which will be set in B tree*/
613         if (si->value_len > OCFS2_XATTR_INLINE_SIZE) {
614                 int new_clusters = ocfs2_clusters_for_bytes(dir->i_sb,
615                                                             si->value_len);
616
617                 *xattr_credits += ocfs2_clusters_to_blocks(dir->i_sb,
618                                                            new_clusters);
619                 *want_clusters += new_clusters;
620         }
621         return ret;
622 }
623
624 int ocfs2_calc_xattr_init(struct inode *dir,
625                           struct buffer_head *dir_bh,
626                           int mode,
627                           struct ocfs2_security_xattr_info *si,
628                           int *want_clusters,
629                           int *xattr_credits,
630                           int *want_meta)
631 {
632         int ret = 0;
633         struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
634         int s_size = 0, a_size = 0, acl_len = 0, new_clusters;
635
636         if (si->enable)
637                 s_size = ocfs2_xattr_entry_real_size(strlen(si->name),
638                                                      si->value_len);
639
640         if (osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL) {
641                 acl_len = ocfs2_xattr_get_nolock(dir, dir_bh,
642                                         OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT,
643                                         "", NULL, 0);
644                 if (acl_len > 0) {
645                         a_size = ocfs2_xattr_entry_real_size(0, acl_len);
646                         if (S_ISDIR(mode))
647                                 a_size <<= 1;
648                 } else if (acl_len != 0 && acl_len != -ENODATA) {
649                         mlog_errno(ret);
650                         return ret;
651                 }
652         }
653
654         if (!(s_size + a_size))
655                 return ret;
656
657         /*
658          * The max space of security xattr taken inline is
659          * 256(name) + 80(value) + 16(entry) = 352 bytes,
660          * The max space of acl xattr taken inline is
661          * 80(value) + 16(entry) * 2(if directory) = 192 bytes,
662          * when blocksize = 512, may reserve one more cluser for
663          * xattr bucket, otherwise reserve one metadata block
664          * for them is ok.
665          * If this is a new directory with inline data,
666          * we choose to reserve the entire inline area for
667          * directory contents and force an external xattr block.
668          */
669         if (dir->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE ||
670             (S_ISDIR(mode) && ocfs2_supports_inline_data(osb)) ||
671             (s_size + a_size) > OCFS2_XATTR_FREE_IN_IBODY) {
672                 *want_meta = *want_meta + 1;
673                 *xattr_credits += OCFS2_XATTR_BLOCK_CREATE_CREDITS;
674         }
675
676         if (dir->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE &&
677             (s_size + a_size) > OCFS2_XATTR_FREE_IN_BLOCK(dir)) {
678                 *want_clusters += 1;
679                 *xattr_credits += ocfs2_blocks_per_xattr_bucket(dir->i_sb);
680         }
681
682         /*
683          * reserve credits and clusters for xattrs which has large value
684          * and have to be set outside
685          */
686         if (si->enable && si->value_len > OCFS2_XATTR_INLINE_SIZE) {
687                 new_clusters = ocfs2_clusters_for_bytes(dir->i_sb,
688                                                         si->value_len);
689                 *xattr_credits += ocfs2_clusters_to_blocks(dir->i_sb,
690                                                            new_clusters);
691                 *want_clusters += new_clusters;
692         }
693         if (osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL &&
694             acl_len > OCFS2_XATTR_INLINE_SIZE) {
695                 /* for directory, it has DEFAULT and ACCESS two types of acls */
696                 new_clusters = (S_ISDIR(mode) ? 2 : 1) *
697                                 ocfs2_clusters_for_bytes(dir->i_sb, acl_len);
698                 *xattr_credits += ocfs2_clusters_to_blocks(dir->i_sb,
699                                                            new_clusters);
700                 *want_clusters += new_clusters;
701         }
702
703         return ret;
704 }
705
706 static int ocfs2_xattr_extend_allocation(struct inode *inode,
707                                          u32 clusters_to_add,
708                                          struct ocfs2_xattr_value_buf *vb,
709                                          struct ocfs2_xattr_set_ctxt *ctxt)
710 {
711         int status = 0;
712         handle_t *handle = ctxt->handle;
713         enum ocfs2_alloc_restarted why;
714         u32 prev_clusters, logical_start = le32_to_cpu(vb->vb_xv->xr_clusters);
715         struct ocfs2_extent_tree et;
716
717         mlog(0, "(clusters_to_add for xattr= %u)\n", clusters_to_add);
718
719         ocfs2_init_xattr_value_extent_tree(&et, INODE_CACHE(inode), vb);
720
721         status = vb->vb_access(handle, INODE_CACHE(inode), vb->vb_bh,
722                               OCFS2_JOURNAL_ACCESS_WRITE);
723         if (status < 0) {
724                 mlog_errno(status);
725                 goto leave;
726         }
727
728         prev_clusters = le32_to_cpu(vb->vb_xv->xr_clusters);
729         status = ocfs2_add_clusters_in_btree(handle,
730                                              &et,
731                                              &logical_start,
732                                              clusters_to_add,
733                                              0,
734                                              ctxt->data_ac,
735                                              ctxt->meta_ac,
736                                              &why);
737         if (status < 0) {
738                 mlog_errno(status);
739                 goto leave;
740         }
741
742         status = ocfs2_journal_dirty(handle, vb->vb_bh);
743         if (status < 0) {
744                 mlog_errno(status);
745                 goto leave;
746         }
747
748         clusters_to_add -= le32_to_cpu(vb->vb_xv->xr_clusters) - prev_clusters;
749
750         /*
751          * We should have already allocated enough space before the transaction,
752          * so no need to restart.
753          */
754         BUG_ON(why != RESTART_NONE || clusters_to_add);
755
756 leave:
757
758         return status;
759 }
760
761 static int __ocfs2_remove_xattr_range(struct inode *inode,
762                                       struct ocfs2_xattr_value_buf *vb,
763                                       u32 cpos, u32 phys_cpos, u32 len,
764                                       unsigned int ext_flags,
765                                       struct ocfs2_xattr_set_ctxt *ctxt)
766 {
767         int ret;
768         u64 phys_blkno = ocfs2_clusters_to_blocks(inode->i_sb, phys_cpos);
769         handle_t *handle = ctxt->handle;
770         struct ocfs2_extent_tree et;
771
772         ocfs2_init_xattr_value_extent_tree(&et, INODE_CACHE(inode), vb);
773
774         ret = vb->vb_access(handle, INODE_CACHE(inode), vb->vb_bh,
775                             OCFS2_JOURNAL_ACCESS_WRITE);
776         if (ret) {
777                 mlog_errno(ret);
778                 goto out;
779         }
780
781         ret = ocfs2_remove_extent(handle, &et, cpos, len, ctxt->meta_ac,
782                                   &ctxt->dealloc);
783         if (ret) {
784                 mlog_errno(ret);
785                 goto out;
786         }
787
788         le32_add_cpu(&vb->vb_xv->xr_clusters, -len);
789
790         ret = ocfs2_journal_dirty(handle, vb->vb_bh);
791         if (ret) {
792                 mlog_errno(ret);
793                 goto out;
794         }
795
796         if (ext_flags & OCFS2_EXT_REFCOUNTED)
797                 ret = ocfs2_decrease_refcount(inode, handle,
798                                         ocfs2_blocks_to_clusters(inode->i_sb,
799                                                                  phys_blkno),
800                                         len, ctxt->meta_ac, &ctxt->dealloc, 1);
801         else
802                 ret = ocfs2_cache_cluster_dealloc(&ctxt->dealloc,
803                                                   phys_blkno, len);
804         if (ret)
805                 mlog_errno(ret);
806
807 out:
808         return ret;
809 }
810
811 static int ocfs2_xattr_shrink_size(struct inode *inode,
812                                    u32 old_clusters,
813                                    u32 new_clusters,
814                                    struct ocfs2_xattr_value_buf *vb,
815                                    struct ocfs2_xattr_set_ctxt *ctxt)
816 {
817         int ret = 0;
818         unsigned int ext_flags;
819         u32 trunc_len, cpos, phys_cpos, alloc_size;
820         u64 block;
821
822         if (old_clusters <= new_clusters)
823                 return 0;
824
825         cpos = new_clusters;
826         trunc_len = old_clusters - new_clusters;
827         while (trunc_len) {
828                 ret = ocfs2_xattr_get_clusters(inode, cpos, &phys_cpos,
829                                                &alloc_size,
830                                                &vb->vb_xv->xr_list, &ext_flags);
831                 if (ret) {
832                         mlog_errno(ret);
833                         goto out;
834                 }
835
836                 if (alloc_size > trunc_len)
837                         alloc_size = trunc_len;
838
839                 ret = __ocfs2_remove_xattr_range(inode, vb, cpos,
840                                                  phys_cpos, alloc_size,
841                                                  ext_flags, ctxt);
842                 if (ret) {
843                         mlog_errno(ret);
844                         goto out;
845                 }
846
847                 block = ocfs2_clusters_to_blocks(inode->i_sb, phys_cpos);
848                 ocfs2_remove_xattr_clusters_from_cache(INODE_CACHE(inode),
849                                                        block, alloc_size);
850                 cpos += alloc_size;
851                 trunc_len -= alloc_size;
852         }
853
854 out:
855         return ret;
856 }
857
858 static int ocfs2_xattr_value_truncate(struct inode *inode,
859                                       struct ocfs2_xattr_value_buf *vb,
860                                       int len,
861                                       struct ocfs2_xattr_set_ctxt *ctxt)
862 {
863         int ret;
864         u32 new_clusters = ocfs2_clusters_for_bytes(inode->i_sb, len);
865         u32 old_clusters = le32_to_cpu(vb->vb_xv->xr_clusters);
866
867         if (new_clusters == old_clusters)
868                 return 0;
869
870         if (new_clusters > old_clusters)
871                 ret = ocfs2_xattr_extend_allocation(inode,
872                                                     new_clusters - old_clusters,
873                                                     vb, ctxt);
874         else
875                 ret = ocfs2_xattr_shrink_size(inode,
876                                               old_clusters, new_clusters,
877                                               vb, ctxt);
878
879         return ret;
880 }
881
882 static int ocfs2_xattr_list_entry(char *buffer, size_t size,
883                                   size_t *result, const char *prefix,
884                                   const char *name, int name_len)
885 {
886         char *p = buffer + *result;
887         int prefix_len = strlen(prefix);
888         int total_len = prefix_len + name_len + 1;
889
890         *result += total_len;
891
892         /* we are just looking for how big our buffer needs to be */
893         if (!size)
894                 return 0;
895
896         if (*result > size)
897                 return -ERANGE;
898
899         memcpy(p, prefix, prefix_len);
900         memcpy(p + prefix_len, name, name_len);
901         p[prefix_len + name_len] = '\0';
902
903         return 0;
904 }
905
906 static int ocfs2_xattr_list_entries(struct inode *inode,
907                                     struct ocfs2_xattr_header *header,
908                                     char *buffer, size_t buffer_size)
909 {
910         size_t result = 0;
911         int i, type, ret;
912         const char *prefix, *name;
913
914         for (i = 0 ; i < le16_to_cpu(header->xh_count); i++) {
915                 struct ocfs2_xattr_entry *entry = &header->xh_entries[i];
916                 type = ocfs2_xattr_get_type(entry);
917                 prefix = ocfs2_xattr_prefix(type);
918
919                 if (prefix) {
920                         name = (const char *)header +
921                                 le16_to_cpu(entry->xe_name_offset);
922
923                         ret = ocfs2_xattr_list_entry(buffer, buffer_size,
924                                                      &result, prefix, name,
925                                                      entry->xe_name_len);
926                         if (ret)
927                                 return ret;
928                 }
929         }
930
931         return result;
932 }
933
934 int ocfs2_has_inline_xattr_value_outside(struct inode *inode,
935                                          struct ocfs2_dinode *di)
936 {
937         struct ocfs2_xattr_header *xh;
938         int i;
939
940         xh = (struct ocfs2_xattr_header *)
941                  ((void *)di + inode->i_sb->s_blocksize -
942                  le16_to_cpu(di->i_xattr_inline_size));
943
944         for (i = 0; i < le16_to_cpu(xh->xh_count); i++)
945                 if (!ocfs2_xattr_is_local(&xh->xh_entries[i]))
946                         return 1;
947
948         return 0;
949 }
950
951 static int ocfs2_xattr_ibody_list(struct inode *inode,
952                                   struct ocfs2_dinode *di,
953                                   char *buffer,
954                                   size_t buffer_size)
955 {
956         struct ocfs2_xattr_header *header = NULL;
957         struct ocfs2_inode_info *oi = OCFS2_I(inode);
958         int ret = 0;
959
960         if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL))
961                 return ret;
962
963         header = (struct ocfs2_xattr_header *)
964                  ((void *)di + inode->i_sb->s_blocksize -
965                  le16_to_cpu(di->i_xattr_inline_size));
966
967         ret = ocfs2_xattr_list_entries(inode, header, buffer, buffer_size);
968
969         return ret;
970 }
971
972 static int ocfs2_xattr_block_list(struct inode *inode,
973                                   struct ocfs2_dinode *di,
974                                   char *buffer,
975                                   size_t buffer_size)
976 {
977         struct buffer_head *blk_bh = NULL;
978         struct ocfs2_xattr_block *xb;
979         int ret = 0;
980
981         if (!di->i_xattr_loc)
982                 return ret;
983
984         ret = ocfs2_read_xattr_block(inode, le64_to_cpu(di->i_xattr_loc),
985                                      &blk_bh);
986         if (ret < 0) {
987                 mlog_errno(ret);
988                 return ret;
989         }
990
991         xb = (struct ocfs2_xattr_block *)blk_bh->b_data;
992         if (!(le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED)) {
993                 struct ocfs2_xattr_header *header = &xb->xb_attrs.xb_header;
994                 ret = ocfs2_xattr_list_entries(inode, header,
995                                                buffer, buffer_size);
996         } else
997                 ret = ocfs2_xattr_tree_list_index_block(inode, blk_bh,
998                                                    buffer, buffer_size);
999
1000         brelse(blk_bh);
1001
1002         return ret;
1003 }
1004
1005 ssize_t ocfs2_listxattr(struct dentry *dentry,
1006                         char *buffer,
1007                         size_t size)
1008 {
1009         int ret = 0, i_ret = 0, b_ret = 0;
1010         struct buffer_head *di_bh = NULL;
1011         struct ocfs2_dinode *di = NULL;
1012         struct ocfs2_inode_info *oi = OCFS2_I(dentry->d_inode);
1013
1014         if (!ocfs2_supports_xattr(OCFS2_SB(dentry->d_sb)))
1015                 return -EOPNOTSUPP;
1016
1017         if (!(oi->ip_dyn_features & OCFS2_HAS_XATTR_FL))
1018                 return ret;
1019
1020         ret = ocfs2_inode_lock(dentry->d_inode, &di_bh, 0);
1021         if (ret < 0) {
1022                 mlog_errno(ret);
1023                 return ret;
1024         }
1025
1026         di = (struct ocfs2_dinode *)di_bh->b_data;
1027
1028         down_read(&oi->ip_xattr_sem);
1029         i_ret = ocfs2_xattr_ibody_list(dentry->d_inode, di, buffer, size);
1030         if (i_ret < 0)
1031                 b_ret = 0;
1032         else {
1033                 if (buffer) {
1034                         buffer += i_ret;
1035                         size -= i_ret;
1036                 }
1037                 b_ret = ocfs2_xattr_block_list(dentry->d_inode, di,
1038                                                buffer, size);
1039                 if (b_ret < 0)
1040                         i_ret = 0;
1041         }
1042         up_read(&oi->ip_xattr_sem);
1043         ocfs2_inode_unlock(dentry->d_inode, 0);
1044
1045         brelse(di_bh);
1046
1047         return i_ret + b_ret;
1048 }
1049
1050 static int ocfs2_xattr_find_entry(int name_index,
1051                                   const char *name,
1052                                   struct ocfs2_xattr_search *xs)
1053 {
1054         struct ocfs2_xattr_entry *entry;
1055         size_t name_len;
1056         int i, cmp = 1;
1057
1058         if (name == NULL)
1059                 return -EINVAL;
1060
1061         name_len = strlen(name);
1062         entry = xs->here;
1063         for (i = 0; i < le16_to_cpu(xs->header->xh_count); i++) {
1064                 cmp = name_index - ocfs2_xattr_get_type(entry);
1065                 if (!cmp)
1066                         cmp = name_len - entry->xe_name_len;
1067                 if (!cmp)
1068                         cmp = memcmp(name, (xs->base +
1069                                      le16_to_cpu(entry->xe_name_offset)),
1070                                      name_len);
1071                 if (cmp == 0)
1072                         break;
1073                 entry += 1;
1074         }
1075         xs->here = entry;
1076
1077         return cmp ? -ENODATA : 0;
1078 }
1079
1080 static int ocfs2_xattr_get_value_outside(struct inode *inode,
1081                                          struct ocfs2_xattr_value_root *xv,
1082                                          void *buffer,
1083                                          size_t len)
1084 {
1085         u32 cpos, p_cluster, num_clusters, bpc, clusters;
1086         u64 blkno;
1087         int i, ret = 0;
1088         size_t cplen, blocksize;
1089         struct buffer_head *bh = NULL;
1090         struct ocfs2_extent_list *el;
1091
1092         el = &xv->xr_list;
1093         clusters = le32_to_cpu(xv->xr_clusters);
1094         bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
1095         blocksize = inode->i_sb->s_blocksize;
1096
1097         cpos = 0;
1098         while (cpos < clusters) {
1099                 ret = ocfs2_xattr_get_clusters(inode, cpos, &p_cluster,
1100                                                &num_clusters, el, NULL);
1101                 if (ret) {
1102                         mlog_errno(ret);
1103                         goto out;
1104                 }
1105
1106                 blkno = ocfs2_clusters_to_blocks(inode->i_sb, p_cluster);
1107                 /* Copy ocfs2_xattr_value */
1108                 for (i = 0; i < num_clusters * bpc; i++, blkno++) {
1109                         ret = ocfs2_read_block(INODE_CACHE(inode), blkno,
1110                                                &bh, NULL);
1111                         if (ret) {
1112                                 mlog_errno(ret);
1113                                 goto out;
1114                         }
1115
1116                         cplen = len >= blocksize ? blocksize : len;
1117                         memcpy(buffer, bh->b_data, cplen);
1118                         len -= cplen;
1119                         buffer += cplen;
1120
1121                         brelse(bh);
1122                         bh = NULL;
1123                         if (len == 0)
1124                                 break;
1125                 }
1126                 cpos += num_clusters;
1127         }
1128 out:
1129         return ret;
1130 }
1131
1132 static int ocfs2_xattr_ibody_get(struct inode *inode,
1133                                  int name_index,
1134                                  const char *name,
1135                                  void *buffer,
1136                                  size_t buffer_size,
1137                                  struct ocfs2_xattr_search *xs)
1138 {
1139         struct ocfs2_inode_info *oi = OCFS2_I(inode);
1140         struct ocfs2_dinode *di = (struct ocfs2_dinode *)xs->inode_bh->b_data;
1141         struct ocfs2_xattr_value_root *xv;
1142         size_t size;
1143         int ret = 0;
1144
1145         if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL))
1146                 return -ENODATA;
1147
1148         xs->end = (void *)di + inode->i_sb->s_blocksize;
1149         xs->header = (struct ocfs2_xattr_header *)
1150                         (xs->end - le16_to_cpu(di->i_xattr_inline_size));
1151         xs->base = (void *)xs->header;
1152         xs->here = xs->header->xh_entries;
1153
1154         ret = ocfs2_xattr_find_entry(name_index, name, xs);
1155         if (ret)
1156                 return ret;
1157         size = le64_to_cpu(xs->here->xe_value_size);
1158         if (buffer) {
1159                 if (size > buffer_size)
1160                         return -ERANGE;
1161                 if (ocfs2_xattr_is_local(xs->here)) {
1162                         memcpy(buffer, (void *)xs->base +
1163                                le16_to_cpu(xs->here->xe_name_offset) +
1164                                OCFS2_XATTR_SIZE(xs->here->xe_name_len), size);
1165                 } else {
1166                         xv = (struct ocfs2_xattr_value_root *)
1167                                 (xs->base + le16_to_cpu(
1168                                  xs->here->xe_name_offset) +
1169                                 OCFS2_XATTR_SIZE(xs->here->xe_name_len));
1170                         ret = ocfs2_xattr_get_value_outside(inode, xv,
1171                                                             buffer, size);
1172                         if (ret < 0) {
1173                                 mlog_errno(ret);
1174                                 return ret;
1175                         }
1176                 }
1177         }
1178
1179         return size;
1180 }
1181
1182 static int ocfs2_xattr_block_get(struct inode *inode,
1183                                  int name_index,
1184                                  const char *name,
1185                                  void *buffer,
1186                                  size_t buffer_size,
1187                                  struct ocfs2_xattr_search *xs)
1188 {
1189         struct ocfs2_xattr_block *xb;
1190         struct ocfs2_xattr_value_root *xv;
1191         size_t size;
1192         int ret = -ENODATA, name_offset, name_len, i;
1193         int uninitialized_var(block_off);
1194
1195         xs->bucket = ocfs2_xattr_bucket_new(inode);
1196         if (!xs->bucket) {
1197                 ret = -ENOMEM;
1198                 mlog_errno(ret);
1199                 goto cleanup;
1200         }
1201
1202         ret = ocfs2_xattr_block_find(inode, name_index, name, xs);
1203         if (ret) {
1204                 mlog_errno(ret);
1205                 goto cleanup;
1206         }
1207
1208         if (xs->not_found) {
1209                 ret = -ENODATA;
1210                 goto cleanup;
1211         }
1212
1213         xb = (struct ocfs2_xattr_block *)xs->xattr_bh->b_data;
1214         size = le64_to_cpu(xs->here->xe_value_size);
1215         if (buffer) {
1216                 ret = -ERANGE;
1217                 if (size > buffer_size)
1218                         goto cleanup;
1219
1220                 name_offset = le16_to_cpu(xs->here->xe_name_offset);
1221                 name_len = OCFS2_XATTR_SIZE(xs->here->xe_name_len);
1222                 i = xs->here - xs->header->xh_entries;
1223
1224                 if (le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED) {
1225                         ret = ocfs2_xattr_bucket_get_name_value(inode->i_sb,
1226                                                                 bucket_xh(xs->bucket),
1227                                                                 i,
1228                                                                 &block_off,
1229                                                                 &name_offset);
1230                         xs->base = bucket_block(xs->bucket, block_off);
1231                 }
1232                 if (ocfs2_xattr_is_local(xs->here)) {
1233                         memcpy(buffer, (void *)xs->base +
1234                                name_offset + name_len, size);
1235                 } else {
1236                         xv = (struct ocfs2_xattr_value_root *)
1237                                 (xs->base + name_offset + name_len);
1238                         ret = ocfs2_xattr_get_value_outside(inode, xv,
1239                                                             buffer, size);
1240                         if (ret < 0) {
1241                                 mlog_errno(ret);
1242                                 goto cleanup;
1243                         }
1244                 }
1245         }
1246         ret = size;
1247 cleanup:
1248         ocfs2_xattr_bucket_free(xs->bucket);
1249
1250         brelse(xs->xattr_bh);
1251         xs->xattr_bh = NULL;
1252         return ret;
1253 }
1254
1255 int ocfs2_xattr_get_nolock(struct inode *inode,
1256                            struct buffer_head *di_bh,
1257                            int name_index,
1258                            const char *name,
1259                            void *buffer,
1260                            size_t buffer_size)
1261 {
1262         int ret;
1263         struct ocfs2_dinode *di = NULL;
1264         struct ocfs2_inode_info *oi = OCFS2_I(inode);
1265         struct ocfs2_xattr_search xis = {
1266                 .not_found = -ENODATA,
1267         };
1268         struct ocfs2_xattr_search xbs = {
1269                 .not_found = -ENODATA,
1270         };
1271
1272         if (!ocfs2_supports_xattr(OCFS2_SB(inode->i_sb)))
1273                 return -EOPNOTSUPP;
1274
1275         if (!(oi->ip_dyn_features & OCFS2_HAS_XATTR_FL))
1276                 ret = -ENODATA;
1277
1278         xis.inode_bh = xbs.inode_bh = di_bh;
1279         di = (struct ocfs2_dinode *)di_bh->b_data;
1280
1281         down_read(&oi->ip_xattr_sem);
1282         ret = ocfs2_xattr_ibody_get(inode, name_index, name, buffer,
1283                                     buffer_size, &xis);
1284         if (ret == -ENODATA && di->i_xattr_loc)
1285                 ret = ocfs2_xattr_block_get(inode, name_index, name, buffer,
1286                                             buffer_size, &xbs);
1287         up_read(&oi->ip_xattr_sem);
1288
1289         return ret;
1290 }
1291
1292 /* ocfs2_xattr_get()
1293  *
1294  * Copy an extended attribute into the buffer provided.
1295  * Buffer is NULL to compute the size of buffer required.
1296  */
1297 static int ocfs2_xattr_get(struct inode *inode,
1298                            int name_index,
1299                            const char *name,
1300                            void *buffer,
1301                            size_t buffer_size)
1302 {
1303         int ret;
1304         struct buffer_head *di_bh = NULL;
1305
1306         ret = ocfs2_inode_lock(inode, &di_bh, 0);
1307         if (ret < 0) {
1308                 mlog_errno(ret);
1309                 return ret;
1310         }
1311         ret = ocfs2_xattr_get_nolock(inode, di_bh, name_index,
1312                                      name, buffer, buffer_size);
1313
1314         ocfs2_inode_unlock(inode, 0);
1315
1316         brelse(di_bh);
1317
1318         return ret;
1319 }
1320
1321 static int __ocfs2_xattr_set_value_outside(struct inode *inode,
1322                                            handle_t *handle,
1323                                            struct ocfs2_xattr_value_buf *vb,
1324                                            const void *value,
1325                                            int value_len)
1326 {
1327         int ret = 0, i, cp_len;
1328         u16 blocksize = inode->i_sb->s_blocksize;
1329         u32 p_cluster, num_clusters;
1330         u32 cpos = 0, bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
1331         u32 clusters = ocfs2_clusters_for_bytes(inode->i_sb, value_len);
1332         u64 blkno;
1333         struct buffer_head *bh = NULL;
1334         unsigned int ext_flags;
1335         struct ocfs2_xattr_value_root *xv = vb->vb_xv;
1336
1337         BUG_ON(clusters > le32_to_cpu(xv->xr_clusters));
1338
1339         while (cpos < clusters) {
1340                 ret = ocfs2_xattr_get_clusters(inode, cpos, &p_cluster,
1341                                                &num_clusters, &xv->xr_list,
1342                                                &ext_flags);
1343                 if (ret) {
1344                         mlog_errno(ret);
1345                         goto out;
1346                 }
1347
1348                 BUG_ON(ext_flags & OCFS2_EXT_REFCOUNTED);
1349
1350                 blkno = ocfs2_clusters_to_blocks(inode->i_sb, p_cluster);
1351
1352                 for (i = 0; i < num_clusters * bpc; i++, blkno++) {
1353                         ret = ocfs2_read_block(INODE_CACHE(inode), blkno,
1354                                                &bh, NULL);
1355                         if (ret) {
1356                                 mlog_errno(ret);
1357                                 goto out;
1358                         }
1359
1360                         ret = ocfs2_journal_access(handle,
1361                                                    INODE_CACHE(inode),
1362                                                    bh,
1363                                                    OCFS2_JOURNAL_ACCESS_WRITE);
1364                         if (ret < 0) {
1365                                 mlog_errno(ret);
1366                                 goto out;
1367                         }
1368
1369                         cp_len = value_len > blocksize ? blocksize : value_len;
1370                         memcpy(bh->b_data, value, cp_len);
1371                         value_len -= cp_len;
1372                         value += cp_len;
1373                         if (cp_len < blocksize)
1374                                 memset(bh->b_data + cp_len, 0,
1375                                        blocksize - cp_len);
1376
1377                         ret = ocfs2_journal_dirty(handle, bh);
1378                         if (ret < 0) {
1379                                 mlog_errno(ret);
1380                                 goto out;
1381                         }
1382                         brelse(bh);
1383                         bh = NULL;
1384
1385                         /*
1386                          * XXX: do we need to empty all the following
1387                          * blocks in this cluster?
1388                          */
1389                         if (!value_len)
1390                                 break;
1391                 }
1392                 cpos += num_clusters;
1393         }
1394 out:
1395         brelse(bh);
1396
1397         return ret;
1398 }
1399
1400 static int ocfs2_xa_check_space_helper(int needed_space, int free_start,
1401                                        int num_entries)
1402 {
1403         int free_space;
1404
1405         if (!needed_space)
1406                 return 0;
1407
1408         free_space = free_start -
1409                 sizeof(struct ocfs2_xattr_header) -
1410                 (num_entries * sizeof(struct ocfs2_xattr_entry)) -
1411                 OCFS2_XATTR_HEADER_GAP;
1412         if (free_space < 0)
1413                 return -EIO;
1414         if (free_space < needed_space)
1415                 return -ENOSPC;
1416
1417         return 0;
1418 }
1419
1420 static int ocfs2_xa_journal_access(handle_t *handle, struct ocfs2_xa_loc *loc,
1421                                    int type)
1422 {
1423         return loc->xl_ops->xlo_journal_access(handle, loc, type);
1424 }
1425
1426 static void ocfs2_xa_journal_dirty(handle_t *handle, struct ocfs2_xa_loc *loc)
1427 {
1428         loc->xl_ops->xlo_journal_dirty(handle, loc);
1429 }
1430
1431 /* Give a pointer into the storage for the given offset */
1432 static void *ocfs2_xa_offset_pointer(struct ocfs2_xa_loc *loc, int offset)
1433 {
1434         BUG_ON(offset >= loc->xl_size);
1435         return loc->xl_ops->xlo_offset_pointer(loc, offset);
1436 }
1437
1438 /*
1439  * Wipe the name+value pair and allow the storage to reclaim it.  This
1440  * must be followed by either removal of the entry or a call to
1441  * ocfs2_xa_add_namevalue().
1442  */
1443 static void ocfs2_xa_wipe_namevalue(struct ocfs2_xa_loc *loc)
1444 {
1445         loc->xl_ops->xlo_wipe_namevalue(loc);
1446 }
1447
1448 /*
1449  * Find lowest offset to a name+value pair.  This is the start of our
1450  * downward-growing free space.
1451  */
1452 static int ocfs2_xa_get_free_start(struct ocfs2_xa_loc *loc)
1453 {
1454         return loc->xl_ops->xlo_get_free_start(loc);
1455 }
1456
1457 /* Can we reuse loc->xl_entry for xi? */
1458 static int ocfs2_xa_can_reuse_entry(struct ocfs2_xa_loc *loc,
1459                                     struct ocfs2_xattr_info *xi)
1460 {
1461         return loc->xl_ops->xlo_can_reuse(loc, xi);
1462 }
1463
1464 /* How much free space is needed to set the new value */
1465 static int ocfs2_xa_check_space(struct ocfs2_xa_loc *loc,
1466                                 struct ocfs2_xattr_info *xi)
1467 {
1468         return loc->xl_ops->xlo_check_space(loc, xi);
1469 }
1470
1471 static void ocfs2_xa_add_entry(struct ocfs2_xa_loc *loc, u32 name_hash)
1472 {
1473         loc->xl_ops->xlo_add_entry(loc, name_hash);
1474         loc->xl_entry->xe_name_hash = cpu_to_le32(name_hash);
1475         /*
1476          * We can't leave the new entry's xe_name_offset at zero or
1477          * add_namevalue() will go nuts.  We set it to the size of our
1478          * storage so that it can never be less than any other entry.
1479          */
1480         loc->xl_entry->xe_name_offset = cpu_to_le16(loc->xl_size);
1481 }
1482
1483 static void ocfs2_xa_add_namevalue(struct ocfs2_xa_loc *loc,
1484                                    struct ocfs2_xattr_info *xi)
1485 {
1486         int size = namevalue_size_xi(xi);
1487         int nameval_offset;
1488         char *nameval_buf;
1489
1490         loc->xl_ops->xlo_add_namevalue(loc, size);
1491         loc->xl_entry->xe_value_size = cpu_to_le64(xi->xi_value_len);
1492         loc->xl_entry->xe_name_len = xi->xi_name_len;
1493         ocfs2_xattr_set_type(loc->xl_entry, xi->xi_name_index);
1494         ocfs2_xattr_set_local(loc->xl_entry,
1495                               xi->xi_value_len <= OCFS2_XATTR_INLINE_SIZE);
1496
1497         nameval_offset = le16_to_cpu(loc->xl_entry->xe_name_offset);
1498         nameval_buf = ocfs2_xa_offset_pointer(loc, nameval_offset);
1499         memset(nameval_buf, 0, size);
1500         memcpy(nameval_buf, xi->xi_name, xi->xi_name_len);
1501 }
1502
1503 static void ocfs2_xa_fill_value_buf(struct ocfs2_xa_loc *loc,
1504                                     struct ocfs2_xattr_value_buf *vb)
1505 {
1506         int nameval_offset = le16_to_cpu(loc->xl_entry->xe_name_offset);
1507         int name_size = OCFS2_XATTR_SIZE(loc->xl_entry->xe_name_len);
1508
1509         /* Value bufs are for value trees */
1510         BUG_ON(ocfs2_xattr_is_local(loc->xl_entry));
1511         BUG_ON(namevalue_size_xe(loc->xl_entry) !=
1512                (name_size + OCFS2_XATTR_ROOT_SIZE));
1513
1514         loc->xl_ops->xlo_fill_value_buf(loc, vb);
1515         vb->vb_xv =
1516                 (struct ocfs2_xattr_value_root *)ocfs2_xa_offset_pointer(loc,
1517                                                         nameval_offset +
1518                                                         name_size);
1519 }
1520
1521 static int ocfs2_xa_block_journal_access(handle_t *handle,
1522                                          struct ocfs2_xa_loc *loc, int type)
1523 {
1524         struct buffer_head *bh = loc->xl_storage;
1525         ocfs2_journal_access_func access;
1526
1527         if (loc->xl_size == (bh->b_size -
1528                              offsetof(struct ocfs2_xattr_block,
1529                                       xb_attrs.xb_header)))
1530                 access = ocfs2_journal_access_xb;
1531         else
1532                 access = ocfs2_journal_access_di;
1533         return access(handle, INODE_CACHE(loc->xl_inode), bh, type);
1534 }
1535
1536 static void ocfs2_xa_block_journal_dirty(handle_t *handle,
1537                                          struct ocfs2_xa_loc *loc)
1538 {
1539         struct buffer_head *bh = loc->xl_storage;
1540
1541         ocfs2_journal_dirty(handle, bh);
1542 }
1543
1544 static void *ocfs2_xa_block_offset_pointer(struct ocfs2_xa_loc *loc,
1545                                            int offset)
1546 {
1547         return (char *)loc->xl_header + offset;
1548 }
1549
1550 static int ocfs2_xa_block_can_reuse(struct ocfs2_xa_loc *loc,
1551                                     struct ocfs2_xattr_info *xi)
1552 {
1553         /*
1554          * Block storage is strict.  If the sizes aren't exact, we will
1555          * remove the old one and reinsert the new.
1556          */
1557         return namevalue_size_xe(loc->xl_entry) ==
1558                 namevalue_size_xi(xi);
1559 }
1560
1561 static int ocfs2_xa_block_get_free_start(struct ocfs2_xa_loc *loc)
1562 {
1563         struct ocfs2_xattr_header *xh = loc->xl_header;
1564         int i, count = le16_to_cpu(xh->xh_count);
1565         int offset, free_start = loc->xl_size;
1566
1567         for (i = 0; i < count; i++) {
1568                 offset = le16_to_cpu(xh->xh_entries[i].xe_name_offset);
1569                 if (offset < free_start)
1570                         free_start = offset;
1571         }
1572
1573         return free_start;
1574 }
1575
1576 static int ocfs2_xa_block_check_space(struct ocfs2_xa_loc *loc,
1577                                       struct ocfs2_xattr_info *xi)
1578 {
1579         int count = le16_to_cpu(loc->xl_header->xh_count);
1580         int free_start = ocfs2_xa_get_free_start(loc);
1581         int needed_space = ocfs2_xi_entry_usage(xi);
1582
1583         /*
1584          * Block storage will reclaim the original entry before inserting
1585          * the new value, so we only need the difference.  If the new
1586          * entry is smaller than the old one, we don't need anything.
1587          */
1588         if (loc->xl_entry) {
1589                 /* Don't need space if we're reusing! */
1590                 if (ocfs2_xa_can_reuse_entry(loc, xi))
1591                         needed_space = 0;
1592                 else
1593                         needed_space -= ocfs2_xe_entry_usage(loc->xl_entry);
1594         }
1595         if (needed_space < 0)
1596                 needed_space = 0;
1597         return ocfs2_xa_check_space_helper(needed_space, free_start, count);
1598 }
1599
1600 /*
1601  * Block storage for xattrs keeps the name+value pairs compacted.  When
1602  * we remove one, we have to shift any that preceded it towards the end.
1603  */
1604 static void ocfs2_xa_block_wipe_namevalue(struct ocfs2_xa_loc *loc)
1605 {
1606         int i, offset;
1607         int namevalue_offset, first_namevalue_offset, namevalue_size;
1608         struct ocfs2_xattr_entry *entry = loc->xl_entry;
1609         struct ocfs2_xattr_header *xh = loc->xl_header;
1610         int count = le16_to_cpu(xh->xh_count);
1611
1612         namevalue_offset = le16_to_cpu(entry->xe_name_offset);
1613         namevalue_size = namevalue_size_xe(entry);
1614         first_namevalue_offset = ocfs2_xa_get_free_start(loc);
1615
1616         /* Shift the name+value pairs */
1617         memmove((char *)xh + first_namevalue_offset + namevalue_size,
1618                 (char *)xh + first_namevalue_offset,
1619                 namevalue_offset - first_namevalue_offset);
1620         memset((char *)xh + first_namevalue_offset, 0, namevalue_size);
1621
1622         /* Now tell xh->xh_entries about it */
1623         for (i = 0; i < count; i++) {
1624                 offset = le16_to_cpu(xh->xh_entries[i].xe_name_offset);
1625                 if (offset < namevalue_offset)
1626                         le16_add_cpu(&xh->xh_entries[i].xe_name_offset,
1627                                      namevalue_size);
1628         }
1629
1630         /*
1631          * Note that we don't update xh_free_start or xh_name_value_len
1632          * because they're not used in block-stored xattrs.
1633          */
1634 }
1635
1636 static void ocfs2_xa_block_add_entry(struct ocfs2_xa_loc *loc, u32 name_hash)
1637 {
1638         int count = le16_to_cpu(loc->xl_header->xh_count);
1639         loc->xl_entry = &(loc->xl_header->xh_entries[count]);
1640         le16_add_cpu(&loc->xl_header->xh_count, 1);
1641         memset(loc->xl_entry, 0, sizeof(struct ocfs2_xattr_entry));
1642 }
1643
1644 static void ocfs2_xa_block_add_namevalue(struct ocfs2_xa_loc *loc, int size)
1645 {
1646         int free_start = ocfs2_xa_get_free_start(loc);
1647
1648         loc->xl_entry->xe_name_offset = cpu_to_le16(free_start - size);
1649 }
1650
1651 static void ocfs2_xa_block_fill_value_buf(struct ocfs2_xa_loc *loc,
1652                                           struct ocfs2_xattr_value_buf *vb)
1653 {
1654         struct buffer_head *bh = loc->xl_storage;
1655
1656         if (loc->xl_size == (bh->b_size -
1657                              offsetof(struct ocfs2_xattr_block,
1658                                       xb_attrs.xb_header)))
1659                 vb->vb_access = ocfs2_journal_access_xb;
1660         else
1661                 vb->vb_access = ocfs2_journal_access_di;
1662         vb->vb_bh = bh;
1663 }
1664
1665 /*
1666  * Operations for xattrs stored in blocks.  This includes inline inode
1667  * storage and unindexed ocfs2_xattr_blocks.
1668  */
1669 static const struct ocfs2_xa_loc_operations ocfs2_xa_block_loc_ops = {
1670         .xlo_journal_access     = ocfs2_xa_block_journal_access,
1671         .xlo_journal_dirty      = ocfs2_xa_block_journal_dirty,
1672         .xlo_offset_pointer     = ocfs2_xa_block_offset_pointer,
1673         .xlo_check_space        = ocfs2_xa_block_check_space,
1674         .xlo_can_reuse          = ocfs2_xa_block_can_reuse,
1675         .xlo_get_free_start     = ocfs2_xa_block_get_free_start,
1676         .xlo_wipe_namevalue     = ocfs2_xa_block_wipe_namevalue,
1677         .xlo_add_entry          = ocfs2_xa_block_add_entry,
1678         .xlo_add_namevalue      = ocfs2_xa_block_add_namevalue,
1679         .xlo_fill_value_buf     = ocfs2_xa_block_fill_value_buf,
1680 };
1681
1682 static int ocfs2_xa_bucket_journal_access(handle_t *handle,
1683                                           struct ocfs2_xa_loc *loc, int type)
1684 {
1685         struct ocfs2_xattr_bucket *bucket = loc->xl_storage;
1686
1687         return ocfs2_xattr_bucket_journal_access(handle, bucket, type);
1688 }
1689
1690 static void ocfs2_xa_bucket_journal_dirty(handle_t *handle,
1691                                           struct ocfs2_xa_loc *loc)
1692 {
1693         struct ocfs2_xattr_bucket *bucket = loc->xl_storage;
1694
1695         ocfs2_xattr_bucket_journal_dirty(handle, bucket);
1696 }
1697
1698 static void *ocfs2_xa_bucket_offset_pointer(struct ocfs2_xa_loc *loc,
1699                                             int offset)
1700 {
1701         struct ocfs2_xattr_bucket *bucket = loc->xl_storage;
1702         int block, block_offset;
1703
1704         /* The header is at the front of the bucket */
1705         block = offset >> loc->xl_inode->i_sb->s_blocksize_bits;
1706         block_offset = offset % loc->xl_inode->i_sb->s_blocksize;
1707
1708         return bucket_block(bucket, block) + block_offset;
1709 }
1710
1711 static int ocfs2_xa_bucket_can_reuse(struct ocfs2_xa_loc *loc,
1712                                      struct ocfs2_xattr_info *xi)
1713 {
1714         return namevalue_size_xe(loc->xl_entry) >=
1715                 namevalue_size_xi(xi);
1716 }
1717
1718 static int ocfs2_xa_bucket_get_free_start(struct ocfs2_xa_loc *loc)
1719 {
1720         struct ocfs2_xattr_bucket *bucket = loc->xl_storage;
1721         return le16_to_cpu(bucket_xh(bucket)->xh_free_start);
1722 }
1723
1724 static int ocfs2_bucket_align_free_start(struct super_block *sb,
1725                                          int free_start, int size)
1726 {
1727         /*
1728          * We need to make sure that the name+value pair fits within
1729          * one block.
1730          */
1731         if (((free_start - size) >> sb->s_blocksize_bits) !=
1732             ((free_start - 1) >> sb->s_blocksize_bits))
1733                 free_start -= free_start % sb->s_blocksize;
1734
1735         return free_start;
1736 }
1737
1738 static int ocfs2_xa_bucket_check_space(struct ocfs2_xa_loc *loc,
1739                                        struct ocfs2_xattr_info *xi)
1740 {
1741         int rc;
1742         int count = le16_to_cpu(loc->xl_header->xh_count);
1743         int free_start = ocfs2_xa_get_free_start(loc);
1744         int needed_space = ocfs2_xi_entry_usage(xi);
1745         int size = namevalue_size_xi(xi);
1746         struct super_block *sb = loc->xl_inode->i_sb;
1747
1748         /*
1749          * Bucket storage does not reclaim name+value pairs it cannot
1750          * reuse.  They live as holes until the bucket fills, and then
1751          * the bucket is defragmented.  However, the bucket can reclaim
1752          * the ocfs2_xattr_entry.
1753          */
1754         if (loc->xl_entry) {
1755                 /* Don't need space if we're reusing! */
1756                 if (ocfs2_xa_can_reuse_entry(loc, xi))
1757                         needed_space = 0;
1758                 else
1759                         needed_space -= sizeof(struct ocfs2_xattr_entry);
1760         }
1761         BUG_ON(needed_space < 0);
1762
1763         if (free_start < size) {
1764                 if (needed_space)
1765                         return -ENOSPC;
1766         } else {
1767                 /*
1768                  * First we check if it would fit in the first place.
1769                  * Below, we align the free start to a block.  This may
1770                  * slide us below the minimum gap.  By checking unaligned
1771                  * first, we avoid that error.
1772                  */
1773                 rc = ocfs2_xa_check_space_helper(needed_space, free_start,
1774                                                  count);
1775                 if (rc)
1776                         return rc;
1777                 free_start = ocfs2_bucket_align_free_start(sb, free_start,
1778                                                            size);
1779         }
1780         return ocfs2_xa_check_space_helper(needed_space, free_start, count);
1781 }
1782
1783 static void ocfs2_xa_bucket_wipe_namevalue(struct ocfs2_xa_loc *loc)
1784 {
1785         le16_add_cpu(&loc->xl_header->xh_name_value_len,
1786                      -namevalue_size_xe(loc->xl_entry));
1787 }
1788
1789 static void ocfs2_xa_bucket_add_entry(struct ocfs2_xa_loc *loc, u32 name_hash)
1790 {
1791         struct ocfs2_xattr_header *xh = loc->xl_header;
1792         int count = le16_to_cpu(xh->xh_count);
1793         int low = 0, high = count - 1, tmp;
1794         struct ocfs2_xattr_entry *tmp_xe;
1795
1796         /*
1797          * We keep buckets sorted by name_hash, so we need to find
1798          * our insert place.
1799          */
1800         while (low <= high && count) {
1801                 tmp = (low + high) / 2;
1802                 tmp_xe = &xh->xh_entries[tmp];
1803
1804                 if (name_hash > le32_to_cpu(tmp_xe->xe_name_hash))
1805                         low = tmp + 1;
1806                 else if (name_hash < le32_to_cpu(tmp_xe->xe_name_hash))
1807                         high = tmp - 1;
1808                 else {
1809                         low = tmp;
1810                         break;
1811                 }
1812         }
1813
1814         if (low != count)
1815                 memmove(&xh->xh_entries[low + 1],
1816                         &xh->xh_entries[low],
1817                         ((count - low) * sizeof(struct ocfs2_xattr_entry)));
1818
1819         le16_add_cpu(&xh->xh_count, 1);
1820         loc->xl_entry = &xh->xh_entries[low];
1821         memset(loc->xl_entry, 0, sizeof(struct ocfs2_xattr_entry));
1822 }
1823
1824 static void ocfs2_xa_bucket_add_namevalue(struct ocfs2_xa_loc *loc, int size)
1825 {
1826         int free_start = ocfs2_xa_get_free_start(loc);
1827         struct ocfs2_xattr_header *xh = loc->xl_header;
1828         struct super_block *sb = loc->xl_inode->i_sb;
1829         int nameval_offset;
1830
1831         free_start = ocfs2_bucket_align_free_start(sb, free_start, size);
1832         nameval_offset = free_start - size;
1833         loc->xl_entry->xe_name_offset = cpu_to_le16(nameval_offset);
1834         xh->xh_free_start = cpu_to_le16(nameval_offset);
1835         le16_add_cpu(&xh->xh_name_value_len, size);
1836
1837 }
1838
1839 static void ocfs2_xa_bucket_fill_value_buf(struct ocfs2_xa_loc *loc,
1840                                            struct ocfs2_xattr_value_buf *vb)
1841 {
1842         struct ocfs2_xattr_bucket *bucket = loc->xl_storage;
1843         struct super_block *sb = loc->xl_inode->i_sb;
1844         int nameval_offset = le16_to_cpu(loc->xl_entry->xe_name_offset);
1845         int size = namevalue_size_xe(loc->xl_entry);
1846         int block_offset = nameval_offset >> sb->s_blocksize_bits;
1847
1848         /* Values are not allowed to straddle block boundaries */
1849         BUG_ON(block_offset !=
1850                ((nameval_offset + size - 1) >> sb->s_blocksize_bits));
1851         /* We expect the bucket to be filled in */
1852         BUG_ON(!bucket->bu_bhs[block_offset]);
1853
1854         vb->vb_access = ocfs2_journal_access;
1855         vb->vb_bh = bucket->bu_bhs[block_offset];
1856 }
1857
1858 /* Operations for xattrs stored in buckets. */
1859 static const struct ocfs2_xa_loc_operations ocfs2_xa_bucket_loc_ops = {
1860         .xlo_journal_access     = ocfs2_xa_bucket_journal_access,
1861         .xlo_journal_dirty      = ocfs2_xa_bucket_journal_dirty,
1862         .xlo_offset_pointer     = ocfs2_xa_bucket_offset_pointer,
1863         .xlo_check_space        = ocfs2_xa_bucket_check_space,
1864         .xlo_can_reuse          = ocfs2_xa_bucket_can_reuse,
1865         .xlo_get_free_start     = ocfs2_xa_bucket_get_free_start,
1866         .xlo_wipe_namevalue     = ocfs2_xa_bucket_wipe_namevalue,
1867         .xlo_add_entry          = ocfs2_xa_bucket_add_entry,
1868         .xlo_add_namevalue      = ocfs2_xa_bucket_add_namevalue,
1869         .xlo_fill_value_buf     = ocfs2_xa_bucket_fill_value_buf,
1870 };
1871
1872 static int ocfs2_xa_value_truncate(struct ocfs2_xa_loc *loc, u64 bytes,
1873                                    struct ocfs2_xattr_set_ctxt *ctxt)
1874 {
1875         int trunc_rc, access_rc;
1876         struct ocfs2_xattr_value_buf vb;
1877
1878         ocfs2_xa_fill_value_buf(loc, &vb);
1879         trunc_rc = ocfs2_xattr_value_truncate(loc->xl_inode, &vb, bytes,
1880                                               ctxt);
1881
1882         /*
1883          * The caller of ocfs2_xa_value_truncate() has already called
1884          * ocfs2_xa_journal_access on the loc.  However, The truncate code
1885          * calls ocfs2_extend_trans().  This may commit the previous
1886          * transaction and open a new one.  If this is a bucket, truncate
1887          * could leave only vb->vb_bh set up for journaling.  Meanwhile,
1888          * the caller is expecting to dirty the entire bucket.  So we must
1889          * reset the journal work.  We do this even if truncate has failed,
1890          * as it could have failed after committing the extend.
1891          */
1892         access_rc = ocfs2_xa_journal_access(ctxt->handle, loc,
1893                                             OCFS2_JOURNAL_ACCESS_WRITE);
1894
1895         /* Errors in truncate take precedence */
1896         return trunc_rc ? trunc_rc : access_rc;
1897 }
1898
1899 static void ocfs2_xa_remove_entry(struct ocfs2_xa_loc *loc)
1900 {
1901         int index, count;
1902         struct ocfs2_xattr_header *xh = loc->xl_header;
1903         struct ocfs2_xattr_entry *entry = loc->xl_entry;
1904
1905         ocfs2_xa_wipe_namevalue(loc);
1906         loc->xl_entry = NULL;
1907
1908         le16_add_cpu(&xh->xh_count, -1);
1909         count = le16_to_cpu(xh->xh_count);
1910
1911         /*
1912          * Only zero out the entry if there are more remaining.  This is
1913          * important for an empty bucket, as it keeps track of the
1914          * bucket's hash value.  It doesn't hurt empty block storage.
1915          */
1916         if (count) {
1917                 index = ((char *)entry - (char *)&xh->xh_entries) /
1918                         sizeof(struct ocfs2_xattr_entry);
1919                 memmove(&xh->xh_entries[index], &xh->xh_entries[index + 1],
1920                         (count - index) * sizeof(struct ocfs2_xattr_entry));
1921                 memset(&xh->xh_entries[count], 0,
1922                        sizeof(struct ocfs2_xattr_entry));
1923         }
1924 }
1925
1926 static int ocfs2_xa_remove(struct ocfs2_xa_loc *loc,
1927                            struct ocfs2_xattr_set_ctxt *ctxt)
1928 {
1929         int rc = 0;
1930
1931         if (!ocfs2_xattr_is_local(loc->xl_entry)) {
1932                 rc = ocfs2_xa_value_truncate(loc, 0, ctxt);
1933                 if (rc) {
1934                         mlog_errno(rc);
1935                         goto out;
1936                 }
1937         }
1938
1939         ocfs2_xa_remove_entry(loc);
1940
1941 out:
1942         return rc;
1943 }
1944
1945 static void ocfs2_xa_install_value_root(struct ocfs2_xa_loc *loc)
1946 {
1947         int name_size = OCFS2_XATTR_SIZE(loc->xl_entry->xe_name_len);
1948         char *nameval_buf;
1949
1950         nameval_buf = ocfs2_xa_offset_pointer(loc,
1951                                 le16_to_cpu(loc->xl_entry->xe_name_offset));
1952         memcpy(nameval_buf + name_size, &def_xv, OCFS2_XATTR_ROOT_SIZE);
1953 }
1954
1955 /*
1956  * Take an existing entry and make it ready for the new value.  This
1957  * won't allocate space, but it may free space.  It should be ready for
1958  * ocfs2_xa_prepare_entry() to finish the work.
1959  */
1960 static int ocfs2_xa_reuse_entry(struct ocfs2_xa_loc *loc,
1961                                 struct ocfs2_xattr_info *xi,
1962                                 struct ocfs2_xattr_set_ctxt *ctxt)
1963 {
1964         int rc = 0;
1965         int name_size = OCFS2_XATTR_SIZE(xi->xi_name_len);
1966         char *nameval_buf;
1967         int xe_local = ocfs2_xattr_is_local(loc->xl_entry);
1968         int xi_local = xi->xi_value_len <= OCFS2_XATTR_INLINE_SIZE;
1969
1970         BUG_ON(OCFS2_XATTR_SIZE(loc->xl_entry->xe_name_len) !=
1971                name_size);
1972
1973         nameval_buf = ocfs2_xa_offset_pointer(loc,
1974                                 le16_to_cpu(loc->xl_entry->xe_name_offset));
1975         if (xe_local) {
1976                 memset(nameval_buf + name_size, 0,
1977                        namevalue_size_xe(loc->xl_entry) - name_size);
1978                 if (!xi_local)
1979                         ocfs2_xa_install_value_root(loc);
1980         } else {
1981                 if (xi_local) {
1982                         rc = ocfs2_xa_value_truncate(loc, 0, ctxt);
1983                         if (rc < 0) {
1984                                 mlog_errno(rc);
1985                                 goto out;
1986                         }
1987                         memset(nameval_buf + name_size, 0,
1988                                namevalue_size_xe(loc->xl_entry) -
1989                                name_size);
1990                 } else if (le64_to_cpu(loc->xl_entry->xe_value_size) >
1991                            xi->xi_value_len) {
1992                         rc = ocfs2_xa_value_truncate(loc, xi->xi_value_len,
1993                                                      ctxt);
1994                         if (rc < 0) {
1995                                 mlog_errno(rc);
1996                                 goto out;
1997                         }
1998                 }
1999         }
2000
2001         loc->xl_entry->xe_value_size = cpu_to_le64(xi->xi_value_len);
2002         ocfs2_xattr_set_local(loc->xl_entry, xi_local);
2003
2004 out:
2005         return rc;
2006 }
2007
2008 /*
2009  * Prepares loc->xl_entry to receive the new xattr.  This includes
2010  * properly setting up the name+value pair region.  If loc->xl_entry
2011  * already exists, it will take care of modifying it appropriately.
2012  *
2013  * Note that this modifies the data.  You did journal_access already,
2014  * right?
2015  */
2016 static int ocfs2_xa_prepare_entry(struct ocfs2_xa_loc *loc,
2017                                   struct ocfs2_xattr_info *xi,
2018                                   u32 name_hash,
2019                                   struct ocfs2_xattr_set_ctxt *ctxt)
2020 {
2021         int rc = 0;
2022
2023         rc = ocfs2_xa_check_space(loc, xi);
2024         if (rc)
2025                 goto out;
2026
2027         if (loc->xl_entry) {
2028                 if (ocfs2_xa_can_reuse_entry(loc, xi)) {
2029                         rc = ocfs2_xa_reuse_entry(loc, xi, ctxt);
2030                         if (rc)
2031                                 goto out;
2032                         goto alloc_value;
2033                 }
2034
2035                 if (!ocfs2_xattr_is_local(loc->xl_entry)) {
2036                         rc = ocfs2_xa_value_truncate(loc, 0, ctxt);
2037                         if (rc) {
2038                                 mlog_errno(rc);
2039                                 goto out;
2040                         }
2041                 }
2042                 ocfs2_xa_wipe_namevalue(loc);
2043         } else
2044                 ocfs2_xa_add_entry(loc, name_hash);
2045
2046         /*
2047          * If we get here, we have a blank entry.  Fill it.  We grow our
2048          * name+value pair back from the end.
2049          */
2050         ocfs2_xa_add_namevalue(loc, xi);
2051         if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE)
2052                 ocfs2_xa_install_value_root(loc);
2053
2054 alloc_value:
2055         if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE) {
2056                 rc = ocfs2_xa_value_truncate(loc, xi->xi_value_len, ctxt);
2057                 if (rc < 0)
2058                         mlog_errno(rc);
2059         }
2060
2061 out:
2062         return rc;
2063 }
2064
2065 /*
2066  * Store the value portion of the name+value pair.  This will skip
2067  * values that are stored externally.  Their tree roots were set up
2068  * by ocfs2_xa_prepare_entry().
2069  */
2070 static int ocfs2_xa_store_value(struct ocfs2_xa_loc *loc,
2071                                 struct ocfs2_xattr_info *xi,
2072                                 struct ocfs2_xattr_set_ctxt *ctxt)
2073 {
2074         int rc = 0;
2075         int nameval_offset = le16_to_cpu(loc->xl_entry->xe_name_offset);
2076         int name_size = OCFS2_XATTR_SIZE(xi->xi_name_len);
2077         char *nameval_buf;
2078         struct ocfs2_xattr_value_buf vb;
2079
2080         nameval_buf = ocfs2_xa_offset_pointer(loc, nameval_offset);
2081         if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE) {
2082                 ocfs2_xa_fill_value_buf(loc, &vb);
2083                 rc = __ocfs2_xattr_set_value_outside(loc->xl_inode,
2084                                                      ctxt->handle, &vb,
2085                                                      xi->xi_value,
2086                                                      xi->xi_value_len);
2087         } else
2088                 memcpy(nameval_buf + name_size, xi->xi_value, xi->xi_value_len);
2089
2090         return rc;
2091 }
2092
2093 static int ocfs2_xa_set(struct ocfs2_xa_loc *loc,
2094                         struct ocfs2_xattr_info *xi,
2095                         struct ocfs2_xattr_set_ctxt *ctxt)
2096 {
2097         int ret;
2098         u32 name_hash = ocfs2_xattr_name_hash(loc->xl_inode, xi->xi_name,
2099                                               xi->xi_name_len);
2100
2101         ret = ocfs2_xa_journal_access(ctxt->handle, loc,
2102                                       OCFS2_JOURNAL_ACCESS_WRITE);
2103         if (ret) {
2104                 mlog_errno(ret);
2105                 goto out;
2106         }
2107
2108         /* Don't worry, we are never called with !xi_value and !xl_entry */
2109         if (!xi->xi_value) {
2110                 ret = ocfs2_xa_remove(loc, ctxt);
2111                 goto out;
2112         }
2113
2114         ret = ocfs2_xa_prepare_entry(loc, xi, name_hash, ctxt);
2115         if (ret) {
2116                 if (ret != -ENOSPC)
2117                         mlog_errno(ret);
2118                 goto out;
2119         }
2120
2121         ret = ocfs2_xa_store_value(loc, xi, ctxt);
2122         if (ret) {
2123                 mlog_errno(ret);
2124                 goto out;
2125         }
2126
2127         ocfs2_xa_journal_dirty(ctxt->handle, loc);
2128
2129 out:
2130         return ret;
2131 }
2132
2133 static void ocfs2_init_dinode_xa_loc(struct ocfs2_xa_loc *loc,
2134                                      struct inode *inode,
2135                                      struct buffer_head *bh,
2136                                      struct ocfs2_xattr_entry *entry)
2137 {
2138         struct ocfs2_dinode *di = (struct ocfs2_dinode *)bh->b_data;
2139
2140         loc->xl_inode = inode;
2141         loc->xl_ops = &ocfs2_xa_block_loc_ops;
2142         loc->xl_storage = bh;
2143         loc->xl_entry = entry;
2144
2145         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_XATTR_FL)
2146                 loc->xl_size = le16_to_cpu(di->i_xattr_inline_size);
2147         else {
2148                 BUG_ON(entry);
2149                 loc->xl_size = OCFS2_SB(inode->i_sb)->s_xattr_inline_size;
2150         }
2151         loc->xl_header =
2152                 (struct ocfs2_xattr_header *)(bh->b_data + bh->b_size -
2153                                               loc->xl_size);
2154 }
2155
2156 static void ocfs2_init_xattr_block_xa_loc(struct ocfs2_xa_loc *loc,
2157                                           struct inode *inode,
2158                                           struct buffer_head *bh,
2159                                           struct ocfs2_xattr_entry *entry)
2160 {
2161         struct ocfs2_xattr_block *xb =
2162                 (struct ocfs2_xattr_block *)bh->b_data;
2163
2164         BUG_ON(le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED);
2165
2166         loc->xl_inode = inode;
2167         loc->xl_ops = &ocfs2_xa_block_loc_ops;
2168         loc->xl_storage = bh;
2169         loc->xl_header = &(xb->xb_attrs.xb_header);
2170         loc->xl_entry = entry;
2171         loc->xl_size = bh->b_size - offsetof(struct ocfs2_xattr_block,
2172                                              xb_attrs.xb_header);
2173 }
2174
2175 static void ocfs2_init_xattr_bucket_xa_loc(struct ocfs2_xa_loc *loc,
2176                                            struct ocfs2_xattr_bucket *bucket,
2177                                            struct ocfs2_xattr_entry *entry)
2178 {
2179         loc->xl_inode = bucket->bu_inode;
2180         loc->xl_ops = &ocfs2_xa_bucket_loc_ops;
2181         loc->xl_storage = bucket;
2182         loc->xl_header = bucket_xh(bucket);
2183         loc->xl_entry = entry;
2184         loc->xl_size = OCFS2_XATTR_BUCKET_SIZE;
2185 }
2186
2187
2188 /*
2189  * ocfs2_xattr_set_entry()
2190  *
2191  * Set extended attribute entry into inode or block.
2192  *
2193  * If extended attribute value size > OCFS2_XATTR_INLINE_SIZE,
2194  * We first insert tree root(ocfs2_xattr_value_root) like a normal value,
2195  * then set value in B tree with set_value_outside().
2196  */
2197 static int ocfs2_xattr_set_entry(struct inode *inode,
2198                                  struct ocfs2_xattr_info *xi,
2199                                  struct ocfs2_xattr_search *xs,
2200                                  struct ocfs2_xattr_set_ctxt *ctxt,
2201                                  int flag)
2202 {
2203         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2204         struct ocfs2_dinode *di = (struct ocfs2_dinode *)xs->inode_bh->b_data;
2205         handle_t *handle = ctxt->handle;
2206         int ret;
2207         struct ocfs2_xa_loc loc;
2208
2209         BUG_ON(!(flag & OCFS2_INLINE_XATTR_FL));
2210         BUG_ON(xs->xattr_bh != xs->inode_bh);
2211
2212         ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), xs->inode_bh,
2213                                       OCFS2_JOURNAL_ACCESS_WRITE);
2214         if (ret) {
2215                 mlog_errno(ret);
2216                 goto out;
2217         }
2218
2219         ocfs2_init_dinode_xa_loc(&loc, inode, xs->inode_bh,
2220                                  xs->not_found ? NULL : xs->here);
2221         ret = ocfs2_xa_set(&loc, xi, ctxt);
2222         if (ret) {
2223                 if (ret != -ENOSPC)
2224                         mlog_errno(ret);
2225                 goto out;
2226         }
2227         xs->here = loc.xl_entry;
2228
2229         if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL)) {
2230                 struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2231                 unsigned int xattrsize = osb->s_xattr_inline_size;
2232
2233                 /*
2234                  * Adjust extent record count or inline data size
2235                  * to reserve space for extended attribute.
2236                  */
2237                 if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
2238                         struct ocfs2_inline_data *idata = &di->id2.i_data;
2239                         le16_add_cpu(&idata->id_count, -xattrsize);
2240                 } else if (!(ocfs2_inode_is_fast_symlink(inode))) {
2241                         struct ocfs2_extent_list *el = &di->id2.i_list;
2242                         le16_add_cpu(&el->l_count, -(xattrsize /
2243                                         sizeof(struct ocfs2_extent_rec)));
2244                 }
2245                 di->i_xattr_inline_size = cpu_to_le16(xattrsize);
2246         }
2247         /* Update xattr flag */
2248         spin_lock(&oi->ip_lock);
2249         oi->ip_dyn_features |= OCFS2_INLINE_XATTR_FL;
2250         di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
2251         spin_unlock(&oi->ip_lock);
2252
2253         ret = ocfs2_journal_dirty(handle, xs->inode_bh);
2254         if (ret < 0)
2255                 mlog_errno(ret);
2256
2257 out:
2258         return ret;
2259 }
2260
2261 /*
2262  * In xattr remove, if it is stored outside and refcounted, we may have
2263  * the chance to split the refcount tree. So need the allocators.
2264  */
2265 static int ocfs2_lock_xattr_remove_allocators(struct inode *inode,
2266                                         struct ocfs2_xattr_value_root *xv,
2267                                         struct ocfs2_caching_info *ref_ci,
2268                                         struct buffer_head *ref_root_bh,
2269                                         struct ocfs2_alloc_context **meta_ac,
2270                                         int *ref_credits)
2271 {
2272         int ret, meta_add = 0;
2273         u32 p_cluster, num_clusters;
2274         unsigned int ext_flags;
2275
2276         *ref_credits = 0;
2277         ret = ocfs2_xattr_get_clusters(inode, 0, &p_cluster,
2278                                        &num_clusters,
2279                                        &xv->xr_list,
2280                                        &ext_flags);
2281         if (ret) {
2282                 mlog_errno(ret);
2283                 goto out;
2284         }
2285
2286         if (!(ext_flags & OCFS2_EXT_REFCOUNTED))
2287                 goto out;
2288
2289         ret = ocfs2_refcounted_xattr_delete_need(inode, ref_ci,
2290                                                  ref_root_bh, xv,
2291                                                  &meta_add, ref_credits);
2292         if (ret) {
2293                 mlog_errno(ret);
2294                 goto out;
2295         }
2296
2297         ret = ocfs2_reserve_new_metadata_blocks(OCFS2_SB(inode->i_sb),
2298                                                 meta_add, meta_ac);
2299         if (ret)
2300                 mlog_errno(ret);
2301
2302 out:
2303         return ret;
2304 }
2305
2306 static int ocfs2_remove_value_outside(struct inode*inode,
2307                                       struct ocfs2_xattr_value_buf *vb,
2308                                       struct ocfs2_xattr_header *header,
2309                                       struct ocfs2_caching_info *ref_ci,
2310                                       struct buffer_head *ref_root_bh)
2311 {
2312         int ret = 0, i, ref_credits;
2313         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2314         struct ocfs2_xattr_set_ctxt ctxt = { NULL, NULL, };
2315         void *val;
2316
2317         ocfs2_init_dealloc_ctxt(&ctxt.dealloc);
2318
2319         for (i = 0; i < le16_to_cpu(header->xh_count); i++) {
2320                 struct ocfs2_xattr_entry *entry = &header->xh_entries[i];
2321
2322                 if (ocfs2_xattr_is_local(entry))
2323                         continue;
2324
2325                 val = (void *)header +
2326                         le16_to_cpu(entry->xe_name_offset);
2327                 vb->vb_xv = (struct ocfs2_xattr_value_root *)
2328                         (val + OCFS2_XATTR_SIZE(entry->xe_name_len));
2329
2330                 ret = ocfs2_lock_xattr_remove_allocators(inode, vb->vb_xv,
2331                                                          ref_ci, ref_root_bh,
2332                                                          &ctxt.meta_ac,
2333                                                          &ref_credits);
2334
2335                 ctxt.handle = ocfs2_start_trans(osb, ref_credits +
2336                                         ocfs2_remove_extent_credits(osb->sb));
2337                 if (IS_ERR(ctxt.handle)) {
2338                         ret = PTR_ERR(ctxt.handle);
2339                         mlog_errno(ret);
2340                         break;
2341                 }
2342
2343                 ret = ocfs2_xattr_value_truncate(inode, vb, 0, &ctxt);
2344                 if (ret < 0) {
2345                         mlog_errno(ret);
2346                         break;
2347                 }
2348
2349                 ocfs2_commit_trans(osb, ctxt.handle);
2350                 if (ctxt.meta_ac) {
2351                         ocfs2_free_alloc_context(ctxt.meta_ac);
2352                         ctxt.meta_ac = NULL;
2353                 }
2354         }
2355
2356         if (ctxt.meta_ac)
2357                 ocfs2_free_alloc_context(ctxt.meta_ac);
2358         ocfs2_schedule_truncate_log_flush(osb, 1);
2359         ocfs2_run_deallocs(osb, &ctxt.dealloc);
2360         return ret;
2361 }
2362
2363 static int ocfs2_xattr_ibody_remove(struct inode *inode,
2364                                     struct buffer_head *di_bh,
2365                                     struct ocfs2_caching_info *ref_ci,
2366                                     struct buffer_head *ref_root_bh)
2367 {
2368
2369         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
2370         struct ocfs2_xattr_header *header;
2371         int ret;
2372         struct ocfs2_xattr_value_buf vb = {
2373                 .vb_bh = di_bh,
2374                 .vb_access = ocfs2_journal_access_di,
2375         };
2376
2377         header = (struct ocfs2_xattr_header *)
2378                  ((void *)di + inode->i_sb->s_blocksize -
2379                  le16_to_cpu(di->i_xattr_inline_size));
2380
2381         ret = ocfs2_remove_value_outside(inode, &vb, header,
2382                                          ref_ci, ref_root_bh);
2383
2384         return ret;
2385 }
2386
2387 struct ocfs2_rm_xattr_bucket_para {
2388         struct ocfs2_caching_info *ref_ci;
2389         struct buffer_head *ref_root_bh;
2390 };
2391
2392 static int ocfs2_xattr_block_remove(struct inode *inode,
2393                                     struct buffer_head *blk_bh,
2394                                     struct ocfs2_caching_info *ref_ci,
2395                                     struct buffer_head *ref_root_bh)
2396 {
2397         struct ocfs2_xattr_block *xb;
2398         int ret = 0;
2399         struct ocfs2_xattr_value_buf vb = {
2400                 .vb_bh = blk_bh,
2401                 .vb_access = ocfs2_journal_access_xb,
2402         };
2403         struct ocfs2_rm_xattr_bucket_para args = {
2404                 .ref_ci = ref_ci,
2405                 .ref_root_bh = ref_root_bh,
2406         };
2407
2408         xb = (struct ocfs2_xattr_block *)blk_bh->b_data;
2409         if (!(le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED)) {
2410                 struct ocfs2_xattr_header *header = &(xb->xb_attrs.xb_header);
2411                 ret = ocfs2_remove_value_outside(inode, &vb, header,
2412                                                  ref_ci, ref_root_bh);
2413         } else
2414                 ret = ocfs2_iterate_xattr_index_block(inode,
2415                                                 blk_bh,
2416                                                 ocfs2_rm_xattr_cluster,
2417                                                 &args);
2418
2419         return ret;
2420 }
2421
2422 static int ocfs2_xattr_free_block(struct inode *inode,
2423                                   u64 block,
2424                                   struct ocfs2_caching_info *ref_ci,
2425                                   struct buffer_head *ref_root_bh)
2426 {
2427         struct inode *xb_alloc_inode;
2428         struct buffer_head *xb_alloc_bh = NULL;
2429         struct buffer_head *blk_bh = NULL;
2430         struct ocfs2_xattr_block *xb;
2431         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2432         handle_t *handle;
2433         int ret = 0;
2434         u64 blk, bg_blkno;
2435         u16 bit;
2436
2437         ret = ocfs2_read_xattr_block(inode, block, &blk_bh);
2438         if (ret < 0) {
2439                 mlog_errno(ret);
2440                 goto out;
2441         }
2442
2443         ret = ocfs2_xattr_block_remove(inode, blk_bh, ref_ci, ref_root_bh);
2444         if (ret < 0) {
2445                 mlog_errno(ret);
2446                 goto out;
2447         }
2448
2449         xb = (struct ocfs2_xattr_block *)blk_bh->b_data;
2450         blk = le64_to_cpu(xb->xb_blkno);
2451         bit = le16_to_cpu(xb->xb_suballoc_bit);
2452         bg_blkno = ocfs2_which_suballoc_group(blk, bit);
2453
2454         xb_alloc_inode = ocfs2_get_system_file_inode(osb,
2455                                 EXTENT_ALLOC_SYSTEM_INODE,
2456                                 le16_to_cpu(xb->xb_suballoc_slot));
2457         if (!xb_alloc_inode) {
2458                 ret = -ENOMEM;
2459                 mlog_errno(ret);
2460                 goto out;
2461         }
2462         mutex_lock(&xb_alloc_inode->i_mutex);
2463
2464         ret = ocfs2_inode_lock(xb_alloc_inode, &xb_alloc_bh, 1);
2465         if (ret < 0) {
2466                 mlog_errno(ret);
2467                 goto out_mutex;
2468         }
2469
2470         handle = ocfs2_start_trans(osb, OCFS2_SUBALLOC_FREE);
2471         if (IS_ERR(handle)) {
2472                 ret = PTR_ERR(handle);
2473                 mlog_errno(ret);
2474                 goto out_unlock;
2475         }
2476
2477         ret = ocfs2_free_suballoc_bits(handle, xb_alloc_inode, xb_alloc_bh,
2478                                        bit, bg_blkno, 1);
2479         if (ret < 0)
2480                 mlog_errno(ret);
2481
2482         ocfs2_commit_trans(osb, handle);
2483 out_unlock:
2484         ocfs2_inode_unlock(xb_alloc_inode, 1);
2485         brelse(xb_alloc_bh);
2486 out_mutex:
2487         mutex_unlock(&xb_alloc_inode->i_mutex);
2488         iput(xb_alloc_inode);
2489 out:
2490         brelse(blk_bh);
2491         return ret;
2492 }
2493
2494 /*
2495  * ocfs2_xattr_remove()
2496  *
2497  * Free extended attribute resources associated with this inode.
2498  */
2499 int ocfs2_xattr_remove(struct inode *inode, struct buffer_head *di_bh)
2500 {
2501         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2502         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
2503         struct ocfs2_refcount_tree *ref_tree = NULL;
2504         struct buffer_head *ref_root_bh = NULL;
2505         struct ocfs2_caching_info *ref_ci = NULL;
2506         handle_t *handle;
2507         int ret;
2508
2509         if (!ocfs2_supports_xattr(OCFS2_SB(inode->i_sb)))
2510                 return 0;
2511
2512         if (!(oi->ip_dyn_features & OCFS2_HAS_XATTR_FL))
2513                 return 0;
2514
2515         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL) {
2516                 ret = ocfs2_lock_refcount_tree(OCFS2_SB(inode->i_sb),
2517                                                le64_to_cpu(di->i_refcount_loc),
2518                                                1, &ref_tree, &ref_root_bh);
2519                 if (ret) {
2520                         mlog_errno(ret);
2521                         goto out;
2522                 }
2523                 ref_ci = &ref_tree->rf_ci;
2524
2525         }
2526
2527         if (oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL) {
2528                 ret = ocfs2_xattr_ibody_remove(inode, di_bh,
2529                                                ref_ci, ref_root_bh);
2530                 if (ret < 0) {
2531                         mlog_errno(ret);
2532                         goto out;
2533                 }
2534         }
2535
2536         if (di->i_xattr_loc) {
2537                 ret = ocfs2_xattr_free_block(inode,
2538                                              le64_to_cpu(di->i_xattr_loc),
2539                                              ref_ci, ref_root_bh);
2540                 if (ret < 0) {
2541                         mlog_errno(ret);
2542                         goto out;
2543                 }
2544         }
2545
2546         handle = ocfs2_start_trans((OCFS2_SB(inode->i_sb)),
2547                                    OCFS2_INODE_UPDATE_CREDITS);
2548         if (IS_ERR(handle)) {
2549                 ret = PTR_ERR(handle);
2550                 mlog_errno(ret);
2551                 goto out;
2552         }
2553         ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
2554                                       OCFS2_JOURNAL_ACCESS_WRITE);
2555         if (ret) {
2556                 mlog_errno(ret);
2557                 goto out_commit;
2558         }
2559
2560         di->i_xattr_loc = 0;
2561
2562         spin_lock(&oi->ip_lock);
2563         oi->ip_dyn_features &= ~(OCFS2_INLINE_XATTR_FL | OCFS2_HAS_XATTR_FL);
2564         di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
2565         spin_unlock(&oi->ip_lock);
2566
2567         ret = ocfs2_journal_dirty(handle, di_bh);
2568         if (ret < 0)
2569                 mlog_errno(ret);
2570 out_commit:
2571         ocfs2_commit_trans(OCFS2_SB(inode->i_sb), handle);
2572 out:
2573         if (ref_tree)
2574                 ocfs2_unlock_refcount_tree(OCFS2_SB(inode->i_sb), ref_tree, 1);
2575         brelse(ref_root_bh);
2576         return ret;
2577 }
2578
2579 static int ocfs2_xattr_has_space_inline(struct inode *inode,
2580                                         struct ocfs2_dinode *di)
2581 {
2582         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2583         unsigned int xattrsize = OCFS2_SB(inode->i_sb)->s_xattr_inline_size;
2584         int free;
2585
2586         if (xattrsize < OCFS2_MIN_XATTR_INLINE_SIZE)
2587                 return 0;
2588
2589         if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
2590                 struct ocfs2_inline_data *idata = &di->id2.i_data;
2591                 free = le16_to_cpu(idata->id_count) - le64_to_cpu(di->i_size);
2592         } else if (ocfs2_inode_is_fast_symlink(inode)) {
2593                 free = ocfs2_fast_symlink_chars(inode->i_sb) -
2594                         le64_to_cpu(di->i_size);
2595         } else {
2596                 struct ocfs2_extent_list *el = &di->id2.i_list;
2597                 free = (le16_to_cpu(el->l_count) -
2598                         le16_to_cpu(el->l_next_free_rec)) *
2599                         sizeof(struct ocfs2_extent_rec);
2600         }
2601         if (free >= xattrsize)
2602                 return 1;
2603
2604         return 0;
2605 }
2606
2607 /*
2608  * ocfs2_xattr_ibody_find()
2609  *
2610  * Find extended attribute in inode block and
2611  * fill search info into struct ocfs2_xattr_search.
2612  */
2613 static int ocfs2_xattr_ibody_find(struct inode *inode,
2614                                   int name_index,
2615                                   const char *name,
2616                                   struct ocfs2_xattr_search *xs)
2617 {
2618         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2619         struct ocfs2_dinode *di = (struct ocfs2_dinode *)xs->inode_bh->b_data;
2620         int ret;
2621         int has_space = 0;
2622
2623         if (inode->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE)
2624                 return 0;
2625
2626         if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL)) {
2627                 down_read(&oi->ip_alloc_sem);
2628                 has_space = ocfs2_xattr_has_space_inline(inode, di);
2629                 up_read(&oi->ip_alloc_sem);
2630                 if (!has_space)
2631                         return 0;
2632         }
2633
2634         xs->xattr_bh = xs->inode_bh;
2635         xs->end = (void *)di + inode->i_sb->s_blocksize;
2636         if (oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL)
2637                 xs->header = (struct ocfs2_xattr_header *)
2638                         (xs->end - le16_to_cpu(di->i_xattr_inline_size));
2639         else
2640                 xs->header = (struct ocfs2_xattr_header *)
2641                         (xs->end - OCFS2_SB(inode->i_sb)->s_xattr_inline_size);
2642         xs->base = (void *)xs->header;
2643         xs->here = xs->header->xh_entries;
2644
2645         /* Find the named attribute. */
2646         if (oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL) {
2647                 ret = ocfs2_xattr_find_entry(name_index, name, xs);
2648                 if (ret && ret != -ENODATA)
2649                         return ret;
2650                 xs->not_found = ret;
2651         }
2652
2653         return 0;
2654 }
2655
2656 /*
2657  * ocfs2_xattr_ibody_set()
2658  *
2659  * Set, replace or remove an extended attribute into inode block.
2660  *
2661  */
2662 static int ocfs2_xattr_ibody_set(struct inode *inode,
2663                                  struct ocfs2_xattr_info *xi,
2664                                  struct ocfs2_xattr_search *xs,
2665                                  struct ocfs2_xattr_set_ctxt *ctxt)
2666 {
2667         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2668         struct ocfs2_dinode *di = (struct ocfs2_dinode *)xs->inode_bh->b_data;
2669         int ret;
2670
2671         if (inode->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE)
2672                 return -ENOSPC;
2673
2674         down_write(&oi->ip_alloc_sem);
2675         if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL)) {
2676                 if (!ocfs2_xattr_has_space_inline(inode, di)) {
2677                         ret = -ENOSPC;
2678                         goto out;
2679                 }
2680         }
2681
2682         ret = ocfs2_xattr_set_entry(inode, xi, xs, ctxt,
2683                                 (OCFS2_INLINE_XATTR_FL | OCFS2_HAS_XATTR_FL));
2684 out:
2685         up_write(&oi->ip_alloc_sem);
2686
2687         return ret;
2688 }
2689
2690 /*
2691  * ocfs2_xattr_block_find()
2692  *
2693  * Find extended attribute in external block and
2694  * fill search info into struct ocfs2_xattr_search.
2695  */
2696 static int ocfs2_xattr_block_find(struct inode *inode,
2697                                   int name_index,
2698                                   const char *name,
2699                                   struct ocfs2_xattr_search *xs)
2700 {
2701         struct ocfs2_dinode *di = (struct ocfs2_dinode *)xs->inode_bh->b_data;
2702         struct buffer_head *blk_bh = NULL;
2703         struct ocfs2_xattr_block *xb;
2704         int ret = 0;
2705
2706         if (!di->i_xattr_loc)
2707                 return ret;
2708
2709         ret = ocfs2_read_xattr_block(inode, le64_to_cpu(di->i_xattr_loc),
2710                                      &blk_bh);
2711         if (ret < 0) {
2712                 mlog_errno(ret);
2713                 return ret;
2714         }
2715
2716         xs->xattr_bh = blk_bh;
2717         xb = (struct ocfs2_xattr_block *)blk_bh->b_data;
2718
2719         if (!(le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED)) {
2720                 xs->header = &xb->xb_attrs.xb_header;
2721                 xs->base = (void *)xs->header;
2722                 xs->end = (void *)(blk_bh->b_data) + blk_bh->b_size;
2723                 xs->here = xs->header->xh_entries;
2724
2725                 ret = ocfs2_xattr_find_entry(name_index, name, xs);
2726         } else
2727                 ret = ocfs2_xattr_index_block_find(inode, blk_bh,
2728                                                    name_index,
2729                                                    name, xs);
2730
2731         if (ret && ret != -ENODATA) {
2732                 xs->xattr_bh = NULL;
2733                 goto cleanup;
2734         }
2735         xs->not_found = ret;
2736         return 0;
2737 cleanup:
2738         brelse(blk_bh);
2739
2740         return ret;
2741 }
2742
2743 static int ocfs2_create_xattr_block(struct inode *inode,
2744                                     struct buffer_head *inode_bh,
2745                                     struct ocfs2_xattr_set_ctxt *ctxt,
2746                                     int indexed,
2747                                     struct buffer_head **ret_bh)
2748 {
2749         int ret;
2750         u16 suballoc_bit_start;
2751         u32 num_got;
2752         u64 first_blkno;
2753         struct ocfs2_dinode *di =  (struct ocfs2_dinode *)inode_bh->b_data;
2754         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2755         struct buffer_head *new_bh = NULL;
2756         struct ocfs2_xattr_block *xblk;
2757
2758         ret = ocfs2_journal_access_di(ctxt->handle, INODE_CACHE(inode),
2759                                       inode_bh, OCFS2_JOURNAL_ACCESS_CREATE);
2760         if (ret < 0) {
2761                 mlog_errno(ret);
2762                 goto end;
2763         }
2764
2765         ret = ocfs2_claim_metadata(osb, ctxt->handle, ctxt->meta_ac, 1,
2766                                    &suballoc_bit_start, &num_got,
2767                                    &first_blkno);
2768         if (ret < 0) {
2769                 mlog_errno(ret);
2770                 goto end;
2771         }
2772
2773         new_bh = sb_getblk(inode->i_sb, first_blkno);
2774         ocfs2_set_new_buffer_uptodate(INODE_CACHE(inode), new_bh);
2775
2776         ret = ocfs2_journal_access_xb(ctxt->handle, INODE_CACHE(inode),
2777                                       new_bh,
2778                                       OCFS2_JOURNAL_ACCESS_CREATE);
2779         if (ret < 0) {
2780                 mlog_errno(ret);
2781                 goto end;
2782         }
2783
2784         /* Initialize ocfs2_xattr_block */
2785         xblk = (struct ocfs2_xattr_block *)new_bh->b_data;
2786         memset(xblk, 0, inode->i_sb->s_blocksize);
2787         strcpy((void *)xblk, OCFS2_XATTR_BLOCK_SIGNATURE);
2788         xblk->xb_suballoc_slot = cpu_to_le16(ctxt->meta_ac->ac_alloc_slot);
2789         xblk->xb_suballoc_bit = cpu_to_le16(suballoc_bit_start);
2790         xblk->xb_fs_generation = cpu_to_le32(osb->fs_generation);
2791         xblk->xb_blkno = cpu_to_le64(first_blkno);
2792         if (indexed) {
2793                 struct ocfs2_xattr_tree_root *xr = &xblk->xb_attrs.xb_root;
2794                 xr->xt_clusters = cpu_to_le32(1);
2795                 xr->xt_last_eb_blk = 0;
2796                 xr->xt_list.l_tree_depth = 0;
2797                 xr->xt_list.l_count = cpu_to_le16(
2798                                         ocfs2_xattr_recs_per_xb(inode->i_sb));
2799                 xr->xt_list.l_next_free_rec = cpu_to_le16(1);
2800                 xblk->xb_flags = cpu_to_le16(OCFS2_XATTR_INDEXED);
2801         }
2802         ocfs2_journal_dirty(ctxt->handle, new_bh);
2803
2804         /* Add it to the inode */
2805         di->i_xattr_loc = cpu_to_le64(first_blkno);
2806
2807         spin_lock(&OCFS2_I(inode)->ip_lock);
2808         OCFS2_I(inode)->ip_dyn_features |= OCFS2_HAS_XATTR_FL;
2809         di->i_dyn_features = cpu_to_le16(OCFS2_I(inode)->ip_dyn_features);
2810         spin_unlock(&OCFS2_I(inode)->ip_lock);
2811
2812         ocfs2_journal_dirty(ctxt->handle, inode_bh);
2813
2814         *ret_bh = new_bh;
2815         new_bh = NULL;
2816
2817 end:
2818         brelse(new_bh);
2819         return ret;
2820 }
2821
2822 /*
2823  * ocfs2_xattr_block_set()
2824  *
2825  * Set, replace or remove an extended attribute into external block.
2826  *
2827  */
2828 static int ocfs2_xattr_block_set(struct inode *inode,
2829                                  struct ocfs2_xattr_info *xi,
2830                                  struct ocfs2_xattr_search *xs,
2831                                  struct ocfs2_xattr_set_ctxt *ctxt)
2832 {
2833         struct buffer_head *new_bh = NULL;
2834         struct ocfs2_xattr_block *xblk = NULL;
2835         int ret;
2836         struct ocfs2_xa_loc loc;
2837
2838         if (!xs->xattr_bh) {
2839                 ret = ocfs2_create_xattr_block(inode, xs->inode_bh, ctxt,
2840                                                0, &new_bh);
2841                 if (ret) {
2842                         mlog_errno(ret);
2843                         goto end;
2844                 }
2845
2846                 xs->xattr_bh = new_bh;
2847                 xblk = (struct ocfs2_xattr_block *)xs->xattr_bh->b_data;
2848                 xs->header = &xblk->xb_attrs.xb_header;
2849                 xs->base = (void *)xs->header;
2850                 xs->end = (void *)xblk + inode->i_sb->s_blocksize;
2851                 xs->here = xs->header->xh_entries;
2852         } else
2853                 xblk = (struct ocfs2_xattr_block *)xs->xattr_bh->b_data;
2854
2855         if (!(le16_to_cpu(xblk->xb_flags) & OCFS2_XATTR_INDEXED)) {
2856                 ocfs2_init_xattr_block_xa_loc(&loc, inode, xs->xattr_bh,
2857                                               xs->not_found ? NULL : xs->here);
2858
2859                 ret = ocfs2_xa_set(&loc, xi, ctxt);
2860                 if (!ret)
2861                         xs->here = loc.xl_entry;
2862                 else if (ret != -ENOSPC)
2863                         goto end;
2864                 else {
2865                         ret = ocfs2_xattr_create_index_block(inode, xs, ctxt);
2866                         if (ret)
2867                                 goto end;
2868                 }
2869         }
2870
2871         if (le16_to_cpu(xblk->xb_flags) & OCFS2_XATTR_INDEXED)
2872                 ret = ocfs2_xattr_set_entry_index_block(inode, xi, xs, ctxt);
2873
2874 end:
2875         return ret;
2876 }
2877
2878 /* Check whether the new xattr can be inserted into the inode. */
2879 static int ocfs2_xattr_can_be_in_inode(struct inode *inode,
2880                                        struct ocfs2_xattr_info *xi,
2881                                        struct ocfs2_xattr_search *xs)
2882 {
2883         struct ocfs2_xattr_entry *last;
2884         int free, i;
2885         size_t min_offs = xs->end - xs->base;
2886
2887         if (!xs->header)
2888                 return 0;
2889
2890         last = xs->header->xh_entries;
2891
2892         for (i = 0; i < le16_to_cpu(xs->header->xh_count); i++) {
2893                 size_t offs = le16_to_cpu(last->xe_name_offset);
2894                 if (offs < min_offs)
2895                         min_offs = offs;
2896                 last += 1;
2897         }
2898
2899         free = min_offs - ((void *)last - xs->base) - OCFS2_XATTR_HEADER_GAP;
2900         if (free < 0)
2901                 return 0;
2902
2903         BUG_ON(!xs->not_found);
2904
2905         if (free >= (sizeof(struct ocfs2_xattr_entry) + namevalue_size_xi(xi)))
2906                 return 1;
2907
2908         return 0;
2909 }
2910
2911 static int ocfs2_calc_xattr_set_need(struct inode *inode,
2912                                      struct ocfs2_dinode *di,
2913                                      struct ocfs2_xattr_info *xi,
2914                                      struct ocfs2_xattr_search *xis,
2915                                      struct ocfs2_xattr_search *xbs,
2916                                      int *clusters_need,
2917                                      int *meta_need,
2918                                      int *credits_need)
2919 {
2920         int ret = 0, old_in_xb = 0;
2921         int clusters_add = 0, meta_add = 0, credits = 0;
2922         struct buffer_head *bh = NULL;
2923         struct ocfs2_xattr_block *xb = NULL;
2924         struct ocfs2_xattr_entry *xe = NULL;
2925         struct ocfs2_xattr_value_root *xv = NULL;
2926         char *base = NULL;
2927         int name_offset, name_len = 0;
2928         u32 new_clusters = ocfs2_clusters_for_bytes(inode->i_sb,
2929                                                     xi->xi_value_len);
2930         u64 value_size;
2931
2932         /*
2933          * Calculate the clusters we need to write.
2934          * No matter whether we replace an old one or add a new one,
2935          * we need this for writing.
2936          */
2937         if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE)
2938                 credits += new_clusters *
2939                            ocfs2_clusters_to_blocks(inode->i_sb, 1);
2940
2941         if (xis->not_found && xbs->not_found) {
2942                 credits += ocfs2_blocks_per_xattr_bucket(inode->i_sb);
2943
2944                 if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE) {
2945                         clusters_add += new_clusters;
2946                         credits += ocfs2_calc_extend_credits(inode->i_sb,
2947                                                         &def_xv.xv.xr_list,
2948                                                         new_clusters);
2949                 }
2950
2951                 goto meta_guess;
2952         }
2953
2954         if (!xis->not_found) {
2955                 xe = xis->here;
2956                 name_offset = le16_to_cpu(xe->xe_name_offset);
2957                 name_len = OCFS2_XATTR_SIZE(xe->xe_name_len);
2958                 base = xis->base;
2959                 credits += OCFS2_INODE_UPDATE_CREDITS;
2960         } else {
2961                 int i, block_off = 0;
2962                 xb = (struct ocfs2_xattr_block *)xbs->xattr_bh->b_data;
2963                 xe = xbs->here;
2964                 name_offset = le16_to_cpu(xe->xe_name_offset);
2965                 name_len = OCFS2_XATTR_SIZE(xe->xe_name_len);
2966                 i = xbs->here - xbs->header->xh_entries;
2967                 old_in_xb = 1;
2968
2969                 if (le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED) {
2970                         ret = ocfs2_xattr_bucket_get_name_value(inode->i_sb,
2971                                                         bucket_xh(xbs->bucket),
2972                                                         i, &block_off,
2973                                                         &name_offset);
2974                         base = bucket_block(xbs->bucket, block_off);
2975                         credits += ocfs2_blocks_per_xattr_bucket(inode->i_sb);
2976                 } else {
2977                         base = xbs->base;
2978                         credits += OCFS2_XATTR_BLOCK_UPDATE_CREDITS;
2979                 }
2980         }
2981
2982         /*
2983          * delete a xattr doesn't need metadata and cluster allocation.
2984          * so just calculate the credits and return.
2985          *
2986          * The credits for removing the value tree will be extended
2987          * by ocfs2_remove_extent itself.
2988          */
2989         if (!xi->xi_value) {
2990                 if (!ocfs2_xattr_is_local(xe))
2991                         credits += ocfs2_remove_extent_credits(inode->i_sb);
2992
2993                 goto out;
2994         }
2995
2996         /* do cluster allocation guess first. */
2997         value_size = le64_to_cpu(xe->xe_value_size);
2998
2999         if (old_in_xb) {
3000                 /*
3001                  * In xattr set, we always try to set the xe in inode first,
3002                  * so if it can be inserted into inode successfully, the old
3003                  * one will be removed from the xattr block, and this xattr
3004                  * will be inserted into inode as a new xattr in inode.
3005                  */
3006                 if (ocfs2_xattr_can_be_in_inode(inode, xi, xis)) {
3007                         clusters_add += new_clusters;
3008                         credits += ocfs2_remove_extent_credits(inode->i_sb) +
3009                                     OCFS2_INODE_UPDATE_CREDITS;
3010                         if (!ocfs2_xattr_is_local(xe))
3011                                 credits += ocfs2_calc_extend_credits(
3012                                                         inode->i_sb,
3013                                                         &def_xv.xv.xr_list,
3014                                                         new_clusters);
3015                         goto out;
3016                 }
3017         }
3018
3019         if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE) {
3020                 /* the new values will be stored outside. */
3021                 u32 old_clusters = 0;
3022
3023                 if (!ocfs2_xattr_is_local(xe)) {
3024                         old_clusters =  ocfs2_clusters_for_bytes(inode->i_sb,
3025                                                                  value_size);
3026                         xv = (struct ocfs2_xattr_value_root *)
3027                              (base + name_offset + name_len);
3028                         value_size = OCFS2_XATTR_ROOT_SIZE;
3029                 } else
3030                         xv = &def_xv.xv;
3031
3032                 if (old_clusters >= new_clusters) {
3033                         credits += ocfs2_remove_extent_credits(inode->i_sb);
3034                         goto out;
3035                 } else {
3036                         meta_add += ocfs2_extend_meta_needed(&xv->xr_list);
3037                         clusters_add += new_clusters - old_clusters;
3038                         credits += ocfs2_calc_extend_credits(inode->i_sb,
3039                                                              &xv->xr_list,
3040                                                              new_clusters -
3041                                                              old_clusters);
3042                         if (value_size >= OCFS2_XATTR_ROOT_SIZE)
3043                                 goto out;
3044                 }
3045         } else {
3046                 /*
3047                  * Now the new value will be stored inside. So if the new
3048                  * value is smaller than the size of value root or the old
3049                  * value, we don't need any allocation, otherwise we have
3050                  * to guess metadata allocation.
3051                  */
3052                 if ((ocfs2_xattr_is_local(xe) &&
3053                      (value_size >= xi->xi_value_len)) ||
3054                     (!ocfs2_xattr_is_local(xe) &&
3055                      OCFS2_XATTR_ROOT_SIZE >= xi->xi_value_len))
3056                         goto out;
3057         }
3058
3059 meta_guess:
3060         /* calculate metadata allocation. */
3061         if (di->i_xattr_loc) {
3062                 if (!xbs->xattr_bh) {
3063                         ret = ocfs2_read_xattr_block(inode,
3064                                                      le64_to_cpu(di->i_xattr_loc),
3065                                                      &bh);
3066                         if (ret) {
3067                                 mlog_errno(ret);
3068                                 goto out;
3069                         }
3070
3071                         xb = (struct ocfs2_xattr_block *)bh->b_data;
3072                 } else
3073                         xb = (struct ocfs2_xattr_block *)xbs->xattr_bh->b_data;
3074
3075                 /*
3076                  * If there is already an xattr tree, good, we can calculate
3077                  * like other b-trees. Otherwise we may have the chance of
3078                  * create a tree, the credit calculation is borrowed from
3079                  * ocfs2_calc_extend_credits with root_el = NULL. And the
3080                  * new tree will be cluster based, so no meta is needed.
3081                  */
3082                 if (le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED) {
3083                         struct ocfs2_extent_list *el =
3084                                  &xb->xb_attrs.xb_root.xt_list;
3085                         meta_add += ocfs2_extend_meta_needed(el);
3086                         credits += ocfs2_calc_extend_credits(inode->i_sb,
3087                                                              el, 1);
3088                 } else
3089                         credits += OCFS2_SUBALLOC_ALLOC + 1;
3090
3091                 /*
3092                  * This cluster will be used either for new bucket or for
3093                  * new xattr block.
3094                  * If the cluster size is the same as the bucket size, one
3095                  * more is needed since we may need to extend the bucket
3096                  * also.
3097                  */
3098                 clusters_add += 1;
3099                 credits += ocfs2_blocks_per_xattr_bucket(inode->i_sb);
3100                 if (OCFS2_XATTR_BUCKET_SIZE ==
3101                         OCFS2_SB(inode->i_sb)->s_clustersize) {
3102                         credits += ocfs2_blocks_per_xattr_bucket(inode->i_sb);
3103                         clusters_add += 1;
3104                 }
3105         } else {
3106                 meta_add += 1;
3107                 credits += OCFS2_XATTR_BLOCK_CREATE_CREDITS;
3108         }
3109 out:
3110         if (clusters_need)
3111                 *clusters_need = clusters_add;
3112         if (meta_need)
3113                 *meta_need = meta_add;
3114         if (credits_need)
3115                 *credits_need = credits;
3116         brelse(bh);
3117         return ret;
3118 }
3119
3120 static int ocfs2_init_xattr_set_ctxt(struct inode *inode,
3121                                      struct ocfs2_dinode *di,
3122                                      struct ocfs2_xattr_info *xi,
3123                                      struct ocfs2_xattr_search *xis,
3124                                      struct ocfs2_xattr_search *xbs,
3125                                      struct ocfs2_xattr_set_ctxt *ctxt,
3126                                      int extra_meta,
3127                                      int *credits)
3128 {
3129         int clusters_add, meta_add, ret;
3130         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3131
3132         memset(ctxt, 0, sizeof(struct ocfs2_xattr_set_ctxt));
3133
3134         ocfs2_init_dealloc_ctxt(&ctxt->dealloc);
3135
3136         ret = ocfs2_calc_xattr_set_need(inode, di, xi, xis, xbs,
3137                                         &clusters_add, &meta_add, credits);
3138         if (ret) {
3139                 mlog_errno(ret);
3140                 return ret;
3141         }
3142
3143         meta_add += extra_meta;
3144         mlog(0, "Set xattr %s, reserve meta blocks = %d, clusters = %d, "
3145              "credits = %d\n", xi->xi_name, meta_add, clusters_add, *credits);
3146
3147         if (meta_add) {
3148                 ret = ocfs2_reserve_new_metadata_blocks(osb, meta_add,
3149                                                         &ctxt->meta_ac);
3150                 if (ret) {
3151                         mlog_errno(ret);
3152                         goto out;
3153                 }
3154         }
3155
3156         if (clusters_add) {
3157                 ret = ocfs2_reserve_clusters(osb, clusters_add, &ctxt->data_ac);
3158                 if (ret)
3159                         mlog_errno(ret);
3160         }
3161 out:
3162         if (ret) {
3163                 if (ctxt->meta_ac) {
3164                         ocfs2_free_alloc_context(ctxt->meta_ac);
3165                         ctxt->meta_ac = NULL;
3166                 }
3167
3168                 /*
3169                  * We cannot have an error and a non null ctxt->data_ac.
3170                  */
3171         }
3172
3173         return ret;
3174 }
3175
3176 static int __ocfs2_xattr_set_handle(struct inode *inode,
3177                                     struct ocfs2_dinode *di,
3178                                     struct ocfs2_xattr_info *xi,
3179                                     struct ocfs2_xattr_search *xis,
3180                                     struct ocfs2_xattr_search *xbs,
3181                                     struct ocfs2_xattr_set_ctxt *ctxt)
3182 {
3183         int ret = 0, credits, old_found;
3184
3185         if (!xi->xi_value) {
3186                 /* Remove existing extended attribute */
3187                 if (!xis->not_found)
3188                         ret = ocfs2_xattr_ibody_set(inode, xi, xis, ctxt);
3189                 else if (!xbs->not_found)
3190                         ret = ocfs2_xattr_block_set(inode, xi, xbs, ctxt);
3191         } else {
3192                 /* We always try to set extended attribute into inode first*/
3193                 ret = ocfs2_xattr_ibody_set(inode, xi, xis, ctxt);
3194                 if (!ret && !xbs->not_found) {
3195                         /*
3196                          * If succeed and that extended attribute existing in
3197                          * external block, then we will remove it.
3198                          */
3199                         xi->xi_value = NULL;
3200                         xi->xi_value_len = 0;
3201
3202                         old_found = xis->not_found;
3203                         xis->not_found = -ENODATA;
3204                         ret = ocfs2_calc_xattr_set_need(inode,
3205                                                         di,
3206                                                         xi,
3207                                                         xis,
3208                                                         xbs,
3209                                                         NULL,
3210                                                         NULL,
3211                                                         &credits);
3212                         xis->not_found = old_found;
3213                         if (ret) {
3214                                 mlog_errno(ret);
3215                                 goto out;
3216                         }
3217
3218                         ret = ocfs2_extend_trans(ctxt->handle, credits +
3219                                         ctxt->handle->h_buffer_credits);
3220                         if (ret) {
3221                                 mlog_errno(ret);
3222                                 goto out;
3223                         }
3224                         ret = ocfs2_xattr_block_set(inode, xi, xbs, ctxt);
3225                 } else if (ret == -ENOSPC) {
3226                         if (di->i_xattr_loc && !xbs->xattr_bh) {
3227                                 ret = ocfs2_xattr_block_find(inode,
3228                                                              xi->xi_name_index,
3229                                                              xi->xi_name, xbs);
3230                                 if (ret)
3231                                         goto out;
3232
3233                                 old_found = xis->not_found;
3234                                 xis->not_found = -ENODATA;
3235                                 ret = ocfs2_calc_xattr_set_need(inode,
3236                                                                 di,
3237                                                                 xi,
3238                                                                 xis,
3239                                                                 xbs,
3240                                                                 NULL,
3241                                                                 NULL,
3242                                                                 &credits);
3243                                 xis->not_found = old_found;
3244                                 if (ret) {
3245                                         mlog_errno(ret);
3246                                         goto out;
3247                                 }
3248
3249                                 ret = ocfs2_extend_trans(ctxt->handle, credits +
3250                                         ctxt->handle->h_buffer_credits);
3251                                 if (ret) {
3252                                         mlog_errno(ret);
3253                                         goto out;
3254                                 }
3255                         }
3256                         /*
3257                          * If no space in inode, we will set extended attribute
3258                          * into external block.
3259                          */
3260                         ret = ocfs2_xattr_block_set(inode, xi, xbs, ctxt);
3261                         if (ret)
3262                                 goto out;
3263                         if (!xis->not_found) {
3264                                 /*
3265                                  * If succeed and that extended attribute
3266                                  * existing in inode, we will remove it.
3267                                  */
3268                                 xi->xi_value = NULL;
3269                                 xi->xi_value_len = 0;
3270                                 xbs->not_found = -ENODATA;
3271                                 ret = ocfs2_calc_xattr_set_need(inode,
3272                                                                 di,
3273                                                                 xi,
3274                                                                 xis,
3275                                                                 xbs,
3276                                                                 NULL,
3277                                                                 NULL,
3278                                                                 &credits);
3279                                 if (ret) {
3280                                         mlog_errno(ret);
3281                                         goto out;
3282                                 }
3283
3284                                 ret = ocfs2_extend_trans(ctxt->handle, credits +
3285                                                 ctxt->handle->h_buffer_credits);
3286                                 if (ret) {
3287                                         mlog_errno(ret);
3288                                         goto out;
3289                                 }
3290                                 ret = ocfs2_xattr_ibody_set(inode, xi,
3291                                                             xis, ctxt);
3292                         }
3293                 }
3294         }
3295
3296         if (!ret) {
3297                 /* Update inode ctime. */
3298                 ret = ocfs2_journal_access_di(ctxt->handle, INODE_CACHE(inode),
3299                                               xis->inode_bh,
3300                                               OCFS2_JOURNAL_ACCESS_WRITE);
3301                 if (ret) {
3302                         mlog_errno(ret);
3303                         goto out;
3304                 }
3305
3306                 inode->i_ctime = CURRENT_TIME;
3307                 di->i_ctime = cpu_to_le64(inode->i_ctime.tv_sec);
3308                 di->i_ctime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
3309                 ocfs2_journal_dirty(ctxt->handle, xis->inode_bh);
3310         }
3311 out:
3312         return ret;
3313 }
3314
3315 /*
3316  * This function only called duing creating inode
3317  * for init security/acl xattrs of the new inode.
3318  * All transanction credits have been reserved in mknod.
3319  */
3320 int ocfs2_xattr_set_handle(handle_t *handle,
3321                            struct inode *inode,
3322                            struct buffer_head *di_bh,
3323                            int name_index,
3324                            const char *name,
3325                            const void *value,
3326                            size_t value_len,
3327                            int flags,
3328                            struct ocfs2_alloc_context *meta_ac,
3329                            struct ocfs2_alloc_context *data_ac)
3330 {
3331         struct ocfs2_dinode *di;
3332         int ret;
3333
3334         struct ocfs2_xattr_info xi = {
3335                 .xi_name_index = name_index,
3336                 .xi_name = name,
3337                 .xi_name_len = strlen(name),
3338                 .xi_value = value,
3339                 .xi_value_len = value_len,
3340         };
3341
3342         struct ocfs2_xattr_search xis = {
3343                 .not_found = -ENODATA,
3344         };
3345
3346         struct ocfs2_xattr_search xbs = {
3347                 .not_found = -ENODATA,
3348         };
3349
3350         struct ocfs2_xattr_set_ctxt ctxt = {
3351                 .handle = handle,
3352                 .meta_ac = meta_ac,
3353                 .data_ac = data_ac,
3354         };
3355
3356         if (!ocfs2_supports_xattr(OCFS2_SB(inode->i_sb)))
3357                 return -EOPNOTSUPP;
3358
3359         /*
3360          * In extreme situation, may need xattr bucket when
3361          * block size is too small. And we have already reserved
3362          * the credits for bucket in mknod.
3363          */
3364         if (inode->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE) {
3365                 xbs.bucket = ocfs2_xattr_bucket_new(inode);
3366                 if (!xbs.bucket) {
3367                         mlog_errno(-ENOMEM);
3368                         return -ENOMEM;
3369                 }
3370         }
3371
3372         xis.inode_bh = xbs.inode_bh = di_bh;
3373         di = (struct ocfs2_dinode *)di_bh->b_data;
3374
3375         down_write(&OCFS2_I(inode)->ip_xattr_sem);
3376
3377         ret = ocfs2_xattr_ibody_find(inode, name_index, name, &xis);
3378         if (ret)
3379                 goto cleanup;
3380         if (xis.not_found) {
3381                 ret = ocfs2_xattr_block_find(inode, name_index, name, &xbs);
3382                 if (ret)
3383                         goto cleanup;
3384         }
3385
3386         ret = __ocfs2_xattr_set_handle(inode, di, &xi, &xis, &xbs, &ctxt);
3387
3388 cleanup:
3389         up_write(&OCFS2_I(inode)->ip_xattr_sem);
3390         brelse(xbs.xattr_bh);
3391         ocfs2_xattr_bucket_free(xbs.bucket);
3392
3393         return ret;
3394 }
3395
3396 /*
3397  * ocfs2_xattr_set()
3398  *
3399  * Set, replace or remove an extended attribute for this inode.
3400  * value is NULL to remove an existing extended attribute, else either
3401  * create or replace an extended attribute.
3402  */
3403 int ocfs2_xattr_set(struct inode *inode,
3404                     int name_index,
3405                     const char *name,
3406                     const void *value,
3407                     size_t value_len,
3408                     int flags)
3409 {
3410         struct buffer_head *di_bh = NULL;
3411         struct ocfs2_dinode *di;
3412         int ret, credits, ref_meta = 0, ref_credits = 0;
3413         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3414         struct inode *tl_inode = osb->osb_tl_inode;
3415         struct ocfs2_xattr_set_ctxt ctxt = { NULL, NULL, };
3416         struct ocfs2_refcount_tree *ref_tree = NULL;
3417
3418         struct ocfs2_xattr_info xi = {
3419                 .xi_name_index = name_index,
3420                 .xi_name = name,
3421                 .xi_name_len = strlen(name),
3422                 .xi_value = value,
3423                 .xi_value_len = value_len,
3424         };
3425
3426         struct ocfs2_xattr_search xis = {
3427                 .not_found = -ENODATA,
3428         };
3429
3430         struct ocfs2_xattr_search xbs = {
3431                 .not_found = -ENODATA,
3432         };
3433
3434         if (!ocfs2_supports_xattr(OCFS2_SB(inode->i_sb)))
3435                 return -EOPNOTSUPP;
3436
3437         /*
3438          * Only xbs will be used on indexed trees.  xis doesn't need a
3439          * bucket.
3440          */
3441         xbs.bucket = ocfs2_xattr_bucket_new(inode);
3442         if (!xbs.bucket) {
3443                 mlog_errno(-ENOMEM);
3444                 return -ENOMEM;
3445         }
3446
3447         ret = ocfs2_inode_lock(inode, &di_bh, 1);
3448         if (ret < 0) {
3449                 mlog_errno(ret);
3450                 goto cleanup_nolock;
3451         }
3452         xis.inode_bh = xbs.inode_bh = di_bh;
3453         di = (struct ocfs2_dinode *)di_bh->b_data;
3454
3455         down_write(&OCFS2_I(inode)->ip_xattr_sem);
3456         /*
3457          * Scan inode and external block to find the same name
3458          * extended attribute and collect search infomation.
3459          */
3460         ret = ocfs2_xattr_ibody_find(inode, name_index, name, &xis);
3461         if (ret)
3462                 goto cleanup;
3463         if (xis.not_found) {
3464                 ret = ocfs2_xattr_block_find(inode, name_index, name, &xbs);
3465                 if (ret)
3466                         goto cleanup;
3467         }
3468
3469         if (xis.not_found && xbs.not_found) {
3470                 ret = -ENODATA;
3471                 if (flags & XATTR_REPLACE)
3472                         goto cleanup;
3473                 ret = 0;
3474                 if (!value)
3475                         goto cleanup;
3476         } else {
3477                 ret = -EEXIST;
3478                 if (flags & XATTR_CREATE)
3479                         goto cleanup;
3480         }
3481
3482         /* Check whether the value is refcounted and do some prepartion. */
3483         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL &&
3484             (!xis.not_found || !xbs.not_found)) {
3485                 ret = ocfs2_prepare_refcount_xattr(inode, di, &xi,
3486                                                    &xis, &xbs, &ref_tree,
3487                                                    &ref_meta, &ref_credits);
3488                 if (ret) {
3489                         mlog_errno(ret);
3490                         goto cleanup;
3491                 }
3492         }
3493
3494         mutex_lock(&tl_inode->i_mutex);
3495
3496         if (ocfs2_truncate_log_needs_flush(osb)) {
3497                 ret = __ocfs2_flush_truncate_log(osb);
3498                 if (ret < 0) {
3499                         mutex_unlock(&tl_inode->i_mutex);
3500                         mlog_errno(ret);
3501                         goto cleanup;
3502                 }
3503         }
3504         mutex_unlock(&tl_inode->i_mutex);
3505
3506         ret = ocfs2_init_xattr_set_ctxt(inode, di, &xi, &xis,
3507                                         &xbs, &ctxt, ref_meta, &credits);
3508         if (ret) {
3509                 mlog_errno(ret);
3510                 goto cleanup;
3511         }
3512
3513         /* we need to update inode's ctime field, so add credit for it. */
3514         credits += OCFS2_INODE_UPDATE_CREDITS;
3515         ctxt.handle = ocfs2_start_trans(osb, credits + ref_credits);
3516         if (IS_ERR(ctxt.handle)) {
3517                 ret = PTR_ERR(ctxt.handle);
3518                 mlog_errno(ret);
3519                 goto cleanup;
3520         }
3521
3522         ret = __ocfs2_xattr_set_handle(inode, di, &xi, &xis, &xbs, &ctxt);
3523
3524         ocfs2_commit_trans(osb, ctxt.handle);
3525
3526         if (ctxt.data_ac)
3527                 ocfs2_free_alloc_context(ctxt.data_ac);
3528         if (ctxt.meta_ac)
3529                 ocfs2_free_alloc_context(ctxt.meta_ac);
3530         if (ocfs2_dealloc_has_cluster(&ctxt.dealloc))
3531                 ocfs2_schedule_truncate_log_flush(osb, 1);
3532         ocfs2_run_deallocs(osb, &ctxt.dealloc);
3533
3534 cleanup:
3535         if (ref_tree)
3536                 ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
3537         up_write(&OCFS2_I(inode)->ip_xattr_sem);
3538         if (!value && !ret) {
3539                 ret = ocfs2_try_remove_refcount_tree(inode, di_bh);
3540                 if (ret)
3541                         mlog_errno(ret);
3542         }
3543         ocfs2_inode_unlock(inode, 1);
3544 cleanup_nolock:
3545         brelse(di_bh);
3546         brelse(xbs.xattr_bh);
3547         ocfs2_xattr_bucket_free(xbs.bucket);
3548
3549         return ret;
3550 }
3551
3552 /*
3553  * Find the xattr extent rec which may contains name_hash.
3554  * e_cpos will be the first name hash of the xattr rec.
3555  * el must be the ocfs2_xattr_header.xb_attrs.xb_root.xt_list.
3556  */
3557 static int ocfs2_xattr_get_rec(struct inode *inode,
3558                                u32 name_hash,
3559                                u64 *p_blkno,
3560                                u32 *e_cpos,
3561                                u32 *num_clusters,
3562                                struct ocfs2_extent_list *el)
3563 {
3564         int ret = 0, i;
3565         struct buffer_head *eb_bh = NULL;
3566         struct ocfs2_extent_block *eb;
3567         struct ocfs2_extent_rec *rec = NULL;
3568         u64 e_blkno = 0;
3569
3570         if (el->l_tree_depth) {
3571                 ret = ocfs2_find_leaf(INODE_CACHE(inode), el, name_hash,
3572                                       &eb_bh);
3573                 if (ret) {
3574                         mlog_errno(ret);
3575                         goto out;
3576                 }
3577
3578                 eb = (struct ocfs2_extent_block *) eb_bh->b_data;
3579                 el = &eb->h_list;
3580
3581                 if (el->l_tree_depth) {
3582                         ocfs2_error(inode->i_sb,
3583                                     "Inode %lu has non zero tree depth in "
3584                                     "xattr tree block %llu\n", inode->i_ino,
3585                                     (unsigned long long)eb_bh->b_blocknr);
3586                         ret = -EROFS;
3587                         goto out;
3588                 }
3589         }
3590
3591         for (i = le16_to_cpu(el->l_next_free_rec) - 1; i >= 0; i--) {
3592                 rec = &el->l_recs[i];
3593
3594                 if (le32_to_cpu(rec->e_cpos) <= name_hash) {
3595                         e_blkno = le64_to_cpu(rec->e_blkno);
3596                         break;
3597                 }
3598         }
3599
3600         if (!e_blkno) {
3601                 ocfs2_error(inode->i_sb, "Inode %lu has bad extent "
3602                             "record (%u, %u, 0) in xattr", inode->i_ino,
3603                             le32_to_cpu(rec->e_cpos),
3604                             ocfs2_rec_clusters(el, rec));
3605                 ret = -EROFS;
3606                 goto out;
3607         }
3608
3609         *p_blkno = le64_to_cpu(rec->e_blkno);
3610         *num_clusters = le16_to_cpu(rec->e_leaf_clusters);
3611         if (e_cpos)
3612                 *e_cpos = le32_to_cpu(rec->e_cpos);
3613 out:
3614         brelse(eb_bh);
3615         return ret;
3616 }
3617
3618 typedef int (xattr_bucket_func)(struct inode *inode,
3619                                 struct ocfs2_xattr_bucket *bucket,
3620                                 void *para);
3621
3622 static int ocfs2_find_xe_in_bucket(struct inode *inode,
3623                                    struct ocfs2_xattr_bucket *bucket,
3624                                    int name_index,
3625                                    const char *name,
3626                                    u32 name_hash,
3627                                    u16 *xe_index,
3628                                    int *found)
3629 {
3630         int i, ret = 0, cmp = 1, block_off, new_offset;
3631         struct ocfs2_xattr_header *xh = bucket_xh(bucket);
3632         size_t name_len = strlen(name);
3633         struct ocfs2_xattr_entry *xe = NULL;
3634         char *xe_name;
3635
3636         /*
3637          * We don't use binary search in the bucket because there
3638          * may be multiple entries with the same name hash.
3639          */
3640         for (i = 0; i < le16_to_cpu(xh->xh_count); i++) {
3641                 xe = &xh->xh_entries[i];
3642
3643                 if (name_hash > le32_to_cpu(xe->xe_name_hash))
3644                         continue;
3645                 else if (name_hash < le32_to_cpu(xe->xe_name_hash))
3646                         break;
3647
3648                 cmp = name_index - ocfs2_xattr_get_type(xe);
3649                 if (!cmp)
3650                         cmp = name_len - xe->xe_name_len;
3651                 if (cmp)
3652                         continue;
3653
3654                 ret = ocfs2_xattr_bucket_get_name_value(inode->i_sb,
3655                                                         xh,
3656                                                         i,
3657                                                         &block_off,
3658                                                         &new_offset);
3659                 if (ret) {
3660                         mlog_errno(ret);
3661                         break;
3662                 }
3663
3664
3665                 xe_name = bucket_block(bucket, block_off) + new_offset;
3666                 if (!memcmp(name, xe_name, name_len)) {
3667                         *xe_index = i;
3668                         *found = 1;
3669                         ret = 0;
3670                         break;
3671                 }
3672         }
3673
3674         return ret;
3675 }
3676
3677 /*
3678  * Find the specified xattr entry in a series of buckets.
3679  * This series start from p_blkno and last for num_clusters.
3680  * The ocfs2_xattr_header.xh_num_buckets of the first bucket contains
3681  * the num of the valid buckets.
3682  *
3683  * Return the buffer_head this xattr should reside in. And if the xattr's
3684  * hash is in the gap of 2 buckets, return the lower bucket.
3685  */
3686 static int ocfs2_xattr_bucket_find(struct inode *inode,
3687                                    int name_index,
3688                                    const char *name,
3689                                    u32 name_hash,
3690                                    u64 p_blkno,
3691                                    u32 first_hash,
3692                                    u32 num_clusters,
3693                                    struct ocfs2_xattr_search *xs)
3694 {
3695         int ret, found = 0;
3696         struct ocfs2_xattr_header *xh = NULL;
3697         struct ocfs2_xattr_entry *xe = NULL;
3698         u16 index = 0;
3699         u16 blk_per_bucket = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
3700         int low_bucket = 0, bucket, high_bucket;
3701         struct ocfs2_xattr_bucket *search;
3702         u32 last_hash;
3703         u64 blkno, lower_blkno = 0;
3704
3705         search = ocfs2_xattr_bucket_new(inode);
3706         if (!search) {
3707                 ret = -ENOMEM;
3708                 mlog_errno(ret);
3709                 goto out;
3710         }
3711
3712         ret = ocfs2_read_xattr_bucket(search, p_blkno);
3713         if (ret) {
3714                 mlog_errno(ret);
3715                 goto out;
3716         }
3717
3718         xh = bucket_xh(search);
3719         high_bucket = le16_to_cpu(xh->xh_num_buckets) - 1;
3720         while (low_bucket <= high_bucket) {
3721                 ocfs2_xattr_bucket_relse(search);
3722
3723                 bucket = (low_bucket + high_bucket) / 2;
3724                 blkno = p_blkno + bucket * blk_per_bucket;
3725                 ret = ocfs2_read_xattr_bucket(search, blkno);
3726                 if (ret) {
3727                         mlog_errno(ret);
3728                         goto out;
3729                 }
3730
3731                 xh = bucket_xh(search);
3732                 xe = &xh->xh_entries[0];
3733                 if (name_hash < le32_to_cpu(xe->xe_name_hash)) {
3734                         high_bucket = bucket - 1;
3735                         continue;
3736                 }
3737
3738                 /*
3739                  * Check whether the hash of the last entry in our
3740                  * bucket is larger than the search one. for an empty
3741                  * bucket, the last one is also the first one.
3742                  */
3743                 if (xh->xh_count)
3744                         xe = &xh->xh_entries[le16_to_cpu(xh->xh_count) - 1];
3745
3746                 last_hash = le32_to_cpu(xe->xe_name_hash);
3747
3748                 /* record lower_blkno which may be the insert place. */
3749                 lower_blkno = blkno;
3750
3751                 if (name_hash > le32_to_cpu(xe->xe_name_hash)) {
3752                         low_bucket = bucket + 1;
3753                         continue;
3754                 }
3755
3756                 /* the searched xattr should reside in this bucket if exists. */
3757                 ret = ocfs2_find_xe_in_bucket(inode, search,
3758                                               name_index, name, name_hash,
3759                                               &index, &found);
3760                 if (ret) {
3761                         mlog_errno(ret);
3762                         goto out;
3763                 }
3764                 break;
3765         }
3766
3767         /*
3768          * Record the bucket we have found.
3769          * When the xattr's hash value is in the gap of 2 buckets, we will
3770          * always set it to the previous bucket.
3771          */
3772         if (!lower_blkno)
3773                 lower_blkno = p_blkno;
3774
3775         /* This should be in cache - we just read it during the search */
3776         ret = ocfs2_read_xattr_bucket(xs->bucket, lower_blkno);
3777         if (ret) {
3778                 mlog_errno(ret);
3779                 goto out;
3780         }
3781
3782         xs->header = bucket_xh(xs->bucket);
3783         xs->base = bucket_block(xs->bucket, 0);
3784         xs->end = xs->base + inode->i_sb->s_blocksize;
3785
3786         if (found) {
3787                 xs->here = &xs->header->xh_entries[index];
3788                 mlog(0, "find xattr %s in bucket %llu, entry = %u\n", name,
3789                      (unsigned long long)bucket_blkno(xs->bucket), index);
3790         } else
3791                 ret = -ENODATA;
3792
3793 out:
3794         ocfs2_xattr_bucket_free(search);
3795         return ret;
3796 }
3797
3798 static int ocfs2_xattr_index_block_find(struct inode *inode,
3799                                         struct buffer_head *root_bh,
3800                                         int name_index,
3801                                         const char *name,
3802                                         struct ocfs2_xattr_search *xs)
3803 {
3804         int ret;
3805         struct ocfs2_xattr_block *xb =
3806                         (struct ocfs2_xattr_block *)root_bh->b_data;
3807         struct ocfs2_xattr_tree_root *xb_root = &xb->xb_attrs.xb_root;
3808         struct ocfs2_extent_list *el = &xb_root->xt_list;
3809         u64 p_blkno = 0;
3810         u32 first_hash, num_clusters = 0;
3811         u32 name_hash = ocfs2_xattr_name_hash(inode, name, strlen(name));
3812
3813         if (le16_to_cpu(el->l_next_free_rec) == 0)
3814                 return -ENODATA;
3815
3816         mlog(0, "find xattr %s, hash = %u, index = %d in xattr tree\n",
3817              name, name_hash, name_index);
3818
3819         ret = ocfs2_xattr_get_rec(inode, name_hash, &p_blkno, &first_hash,
3820                                   &num_clusters, el);
3821         if (ret) {
3822                 mlog_errno(ret);
3823                 goto out;
3824         }
3825
3826         BUG_ON(p_blkno == 0 || num_clusters == 0 || first_hash > name_hash);
3827
3828         mlog(0, "find xattr extent rec %u clusters from %llu, the first hash "
3829              "in the rec is %u\n", num_clusters, (unsigned long long)p_blkno,
3830              first_hash);
3831
3832         ret = ocfs2_xattr_bucket_find(inode, name_index, name, name_hash,
3833                                       p_blkno, first_hash, num_clusters, xs);
3834
3835 out:
3836         return ret;
3837 }
3838
3839 static int ocfs2_iterate_xattr_buckets(struct inode *inode,
3840                                        u64 blkno,
3841                                        u32 clusters,
3842                                        xattr_bucket_func *func,
3843                                        void *para)
3844 {
3845         int i, ret = 0;
3846         u32 bpc = ocfs2_xattr_buckets_per_cluster(OCFS2_SB(inode->i_sb));
3847         u32 num_buckets = clusters * bpc;
3848         struct ocfs2_xattr_bucket *bucket;
3849
3850         bucket = ocfs2_xattr_bucket_new(inode);
3851         if (!bucket) {
3852                 mlog_errno(-ENOMEM);
3853                 return -ENOMEM;
3854         }
3855
3856         mlog(0, "iterating xattr buckets in %u clusters starting from %llu\n",
3857              clusters, (unsigned long long)blkno);
3858
3859         for (i = 0; i < num_buckets; i++, blkno += bucket->bu_blocks) {
3860                 ret = ocfs2_read_xattr_bucket(bucket, blkno);
3861                 if (ret) {
3862                         mlog_errno(ret);
3863                         break;
3864                 }
3865
3866                 /*
3867                  * The real bucket num in this series of blocks is stored
3868                  * in the 1st bucket.
3869                  */
3870                 if (i == 0)
3871                         num_buckets = le16_to_cpu(bucket_xh(bucket)->xh_num_buckets);
3872
3873                 mlog(0, "iterating xattr bucket %llu, first hash %u\n",
3874                      (unsigned long long)blkno,
3875                      le32_to_cpu(bucket_xh(bucket)->xh_entries[0].xe_name_hash));
3876                 if (func) {
3877                         ret = func(inode, bucket, para);
3878                         if (ret && ret != -ERANGE)
3879                                 mlog_errno(ret);
3880                         /* Fall through to bucket_relse() */
3881                 }
3882
3883                 ocfs2_xattr_bucket_relse(bucket);
3884                 if (ret)
3885                         break;
3886         }
3887
3888         ocfs2_xattr_bucket_free(bucket);
3889         return ret;
3890 }
3891
3892 struct ocfs2_xattr_tree_list {
3893         char *buffer;
3894         size_t buffer_size;
3895         size_t result;
3896 };
3897
3898 static int ocfs2_xattr_bucket_get_name_value(struct super_block *sb,
3899                                              struct ocfs2_xattr_header *xh,
3900                                              int index,
3901                                              int *block_off,
3902                                              int *new_offset)
3903 {
3904         u16 name_offset;
3905
3906         if (index < 0 || index >= le16_to_cpu(xh->xh_count))
3907                 return -EINVAL;
3908
3909         name_offset = le16_to_cpu(xh->xh_entries[index].xe_name_offset);
3910
3911         *block_off = name_offset >> sb->s_blocksize_bits;
3912         *new_offset = name_offset % sb->s_blocksize;
3913
3914         return 0;
3915 }
3916
3917 static int ocfs2_list_xattr_bucket(struct inode *inode,
3918                                    struct ocfs2_xattr_bucket *bucket,
3919                                    void *para)
3920 {
3921         int ret = 0, type;
3922         struct ocfs2_xattr_tree_list *xl = (struct ocfs2_xattr_tree_list *)para;
3923         int i, block_off, new_offset;
3924         const char *prefix, *name;
3925
3926         for (i = 0 ; i < le16_to_cpu(bucket_xh(bucket)->xh_count); i++) {
3927                 struct ocfs2_xattr_entry *entry = &bucket_xh(bucket)->xh_entries[i];
3928                 type = ocfs2_xattr_get_type(entry);
3929                 prefix = ocfs2_xattr_prefix(type);
3930
3931                 if (prefix) {
3932                         ret = ocfs2_xattr_bucket_get_name_value(inode->i_sb,
3933                                                                 bucket_xh(bucket),
3934                                                                 i,
3935                                                                 &block_off,
3936                                                                 &new_offset);
3937                         if (ret)
3938                                 break;
3939
3940                         name = (const char *)bucket_block(bucket, block_off) +
3941                                 new_offset;
3942                         ret = ocfs2_xattr_list_entry(xl->buffer,
3943                                                      xl->buffer_size,
3944                                                      &xl->result,
3945                                                      prefix, name,
3946                                                      entry->xe_name_len);
3947                         if (ret)
3948                                 break;
3949                 }
3950         }
3951
3952         return ret;
3953 }
3954
3955 static int ocfs2_iterate_xattr_index_block(struct inode *inode,
3956                                            struct buffer_head *blk_bh,
3957                                            xattr_tree_rec_func *rec_func,
3958                                            void *para)
3959 {
3960         struct ocfs2_xattr_block *xb =
3961                         (struct ocfs2_xattr_block *)blk_bh->b_data;
3962         struct ocfs2_extent_list *el = &xb->xb_attrs.xb_root.xt_list;
3963         int ret = 0;
3964         u32 name_hash = UINT_MAX, e_cpos = 0, num_clusters = 0;
3965         u64 p_blkno = 0;
3966
3967         if (!el->l_next_free_rec || !rec_func)
3968                 return 0;
3969
3970         while (name_hash > 0) {
3971                 ret = ocfs2_xattr_get_rec(inode, name_hash, &p_blkno,
3972                                           &e_cpos, &num_clusters, el);
3973                 if (ret) {
3974                         mlog_errno(ret);
3975                         break;
3976                 }
3977
3978                 ret = rec_func(inode, blk_bh, p_blkno, e_cpos,
3979                                num_clusters, para);
3980                 if (ret) {
3981                         if (ret != -ERANGE)
3982                                 mlog_errno(ret);
3983                         break;
3984                 }
3985
3986                 if (e_cpos == 0)
3987                         break;
3988
3989                 name_hash = e_cpos - 1;
3990         }
3991
3992         return ret;
3993
3994 }
3995
3996 static int ocfs2_list_xattr_tree_rec(struct inode *inode,
3997                                      struct buffer_head *root_bh,
3998                                      u64 blkno, u32 cpos, u32 len, void *para)
3999 {
4000         return ocfs2_iterate_xattr_buckets(inode, blkno, len,
4001                                            ocfs2_list_xattr_bucket, para);
4002 }
4003
4004 static int ocfs2_xattr_tree_list_index_block(struct inode *inode,
4005                                              struct buffer_head *blk_bh,
4006                                              char *buffer,
4007                                              size_t buffer_size)
4008 {
4009         int ret;
4010         struct ocfs2_xattr_tree_list xl = {
4011                 .buffer = buffer,
4012                 .buffer_size = buffer_size,
4013                 .result = 0,
4014         };
4015
4016         ret = ocfs2_iterate_xattr_index_block(inode, blk_bh,
4017                                               ocfs2_list_xattr_tree_rec, &xl);
4018         if (ret) {
4019                 mlog_errno(ret);
4020                 goto out;
4021         }
4022
4023         ret = xl.result;
4024 out:
4025         return ret;
4026 }
4027
4028 static int cmp_xe(const void *a, const void *b)
4029 {
4030         const struct ocfs2_xattr_entry *l = a, *r = b;
4031         u32 l_hash = le32_to_cpu(l->xe_name_hash);
4032         u32 r_hash = le32_to_cpu(r->xe_name_hash);
4033
4034         if (l_hash > r_hash)
4035                 return 1;
4036         if (l_hash < r_hash)
4037                 return -1;
4038         return 0;
4039 }
4040
4041 static void swap_xe(void *a, void *b, int size)
4042 {
4043         struct ocfs2_xattr_entry *l = a, *r = b, tmp;
4044
4045         tmp = *l;
4046         memcpy(l, r, sizeof(struct ocfs2_xattr_entry));
4047         memcpy(r, &tmp, sizeof(struct ocfs2_xattr_entry));
4048 }
4049
4050 /*
4051  * When the ocfs2_xattr_block is filled up, new bucket will be created
4052  * and all the xattr entries will be moved to the new bucket.
4053  * The header goes at the start of the bucket, and the names+values are
4054  * filled from the end.  This is why *target starts as the last buffer.
4055  * Note: we need to sort the entries since they are not saved in order
4056  * in the ocfs2_xattr_block.
4057  */
4058 static void ocfs2_cp_xattr_block_to_bucket(struct inode *inode,
4059                                            struct buffer_head *xb_bh,
4060                                            struct ocfs2_xattr_bucket *bucket)
4061 {
4062         int i, blocksize = inode->i_sb->s_blocksize;
4063         int blks = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
4064         u16 offset, size, off_change;
4065         struct ocfs2_xattr_entry *xe;
4066         struct ocfs2_xattr_block *xb =
4067                                 (struct ocfs2_xattr_block *)xb_bh->b_data;
4068         struct ocfs2_xattr_header *xb_xh = &xb->xb_attrs.xb_header;
4069         struct ocfs2_xattr_header *xh = bucket_xh(bucket);
4070         u16 count = le16_to_cpu(xb_xh->xh_count);
4071         char *src = xb_bh->b_data;
4072         char *target = bucket_block(bucket, blks - 1);
4073
4074         mlog(0, "cp xattr from block %llu to bucket %llu\n",
4075              (unsigned long long)xb_bh->b_blocknr,
4076              (unsigned long long)bucket_blkno(bucket));
4077
4078         for (i = 0; i < blks; i++)
4079                 memset(bucket_block(bucket, i), 0, blocksize);
4080
4081         /*
4082          * Since the xe_name_offset is based on ocfs2_xattr_header,
4083          * there is a offset change corresponding to the change of
4084          * ocfs2_xattr_header's position.
4085          */
4086         off_change = offsetof(struct ocfs2_xattr_block, xb_attrs.xb_header);
4087         xe = &xb_xh->xh_entries[count - 1];
4088         offset = le16_to_cpu(xe->xe_name_offset) + off_change;
4089         size = blocksize - offset;
4090
4091         /* copy all the names and values. */
4092         memcpy(target + offset, src + offset, size);
4093
4094         /* Init new header now. */
4095         xh->xh_count = xb_xh->xh_count;
4096         xh->xh_num_buckets = cpu_to_le16(1);
4097         xh->xh_name_value_len = cpu_to_le16(size);
4098         xh->xh_free_start = cpu_to_le16(OCFS2_XATTR_BUCKET_SIZE - size);
4099
4100         /* copy all the entries. */
4101         target = bucket_block(bucket, 0);
4102         offset = offsetof(struct ocfs2_xattr_header, xh_entries);
4103         size = count * sizeof(struct ocfs2_xattr_entry);
4104         memcpy(target + offset, (char *)xb_xh + offset, size);
4105
4106         /* Change the xe offset for all the xe because of the move. */
4107         off_change = OCFS2_XATTR_BUCKET_SIZE - blocksize +
4108                  offsetof(struct ocfs2_xattr_block, xb_attrs.xb_header);
4109         for (i = 0; i < count; i++)
4110                 le16_add_cpu(&xh->xh_entries[i].xe_name_offset, off_change);
4111
4112         mlog(0, "copy entry: start = %u, size = %u, offset_change = %u\n",
4113              offset, size, off_change);
4114
4115         sort(target + offset, count, sizeof(struct ocfs2_xattr_entry),
4116              cmp_xe, swap_xe);
4117 }
4118
4119 /*
4120  * After we move xattr from block to index btree, we have to
4121  * update ocfs2_xattr_search to the new xe and base.
4122  *
4123  * When the entry is in xattr block, xattr_bh indicates the storage place.
4124  * While if the entry is in index b-tree, "bucket" indicates the
4125  * real place of the xattr.
4126  */
4127 static void ocfs2_xattr_update_xattr_search(struct inode *inode,
4128                                             struct ocfs2_xattr_search *xs,
4129                                             struct buffer_head *old_bh)
4130 {
4131         char *buf = old_bh->b_data;
4132         struct ocfs2_xattr_block *old_xb = (struct ocfs2_xattr_block *)buf;
4133         struct ocfs2_xattr_header *old_xh = &old_xb->xb_attrs.xb_header;
4134         int i;
4135
4136         xs->header = bucket_xh(xs->bucket);
4137         xs->base = bucket_block(xs->bucket, 0);
4138         xs->end = xs->base + inode->i_sb->s_blocksize;
4139
4140         if (xs->not_found)
4141                 return;
4142
4143         i = xs->here - old_xh->xh_entries;
4144         xs->here = &xs->header->xh_entries[i];
4145 }
4146
4147 static int ocfs2_xattr_create_index_block(struct inode *inode,
4148                                           struct ocfs2_xattr_search *xs,
4149                                           struct ocfs2_xattr_set_ctxt *ctxt)
4150 {
4151         int ret;
4152         u32 bit_off, len;
4153         u64 blkno;
4154         handle_t *handle = ctxt->handle;
4155         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
4156         struct ocfs2_inode_info *oi = OCFS2_I(inode);
4157         struct buffer_head *xb_bh = xs->xattr_bh;
4158         struct ocfs2_xattr_block *xb =
4159                         (struct ocfs2_xattr_block *)xb_bh->b_data;
4160         struct ocfs2_xattr_tree_root *xr;
4161         u16 xb_flags = le16_to_cpu(xb->xb_flags);
4162
4163         mlog(0, "create xattr index block for %llu\n",
4164              (unsigned long long)xb_bh->b_blocknr);
4165
4166         BUG_ON(xb_flags & OCFS2_XATTR_INDEXED);
4167         BUG_ON(!xs->bucket);
4168
4169         /*
4170          * XXX:
4171          * We can use this lock for now, and maybe move to a dedicated mutex
4172          * if performance becomes a problem later.
4173          */
4174         down_write(&oi->ip_alloc_sem);
4175
4176         ret = ocfs2_journal_access_xb(handle, INODE_CACHE(inode), xb_bh,
4177                                       OCFS2_JOURNAL_ACCESS_WRITE);
4178         if (ret) {
4179                 mlog_errno(ret);
4180                 goto out;
4181         }
4182
4183         ret = __ocfs2_claim_clusters(osb, handle, ctxt->data_ac,
4184                                      1, 1, &bit_off, &len);
4185         if (ret) {
4186                 mlog_errno(ret);
4187                 goto out;
4188         }
4189
4190         /*
4191          * The bucket may spread in many blocks, and
4192          * we will only touch the 1st block and the last block
4193          * in the whole bucket(one for entry and one for data).
4194          */
4195         blkno = ocfs2_clusters_to_blocks(inode->i_sb, bit_off);
4196
4197         mlog(0, "allocate 1 cluster from %llu to xattr block\n",
4198              (unsigned long long)blkno);
4199
4200         ret = ocfs2_init_xattr_bucket(xs->bucket, blkno);
4201         if (ret) {
4202                 mlog_errno(ret);
4203                 goto out;
4204         }
4205
4206         ret = ocfs2_xattr_bucket_journal_access(handle, xs->bucket,
4207                                                 OCFS2_JOURNAL_ACCESS_CREATE);
4208         if (ret) {
4209                 mlog_errno(ret);
4210                 goto out;
4211         }
4212
4213         ocfs2_cp_xattr_block_to_bucket(inode, xb_bh, xs->bucket);
4214         ocfs2_xattr_bucket_journal_dirty(handle, xs->bucket);
4215
4216         ocfs2_xattr_update_xattr_search(inode, xs, xb_bh);
4217
4218         /* Change from ocfs2_xattr_header to ocfs2_xattr_tree_root */
4219         memset(&xb->xb_attrs, 0, inode->i_sb->s_blocksize -
4220                offsetof(struct ocfs2_xattr_block, xb_attrs));
4221
4222         xr = &xb->xb_attrs.xb_root;
4223         xr->xt_clusters = cpu_to_le32(1);
4224         xr->xt_last_eb_blk = 0;
4225         xr->xt_list.l_tree_depth = 0;
4226         xr->xt_list.l_count = cpu_to_le16(ocfs2_xattr_recs_per_xb(inode->i_sb));
4227         xr->xt_list.l_next_free_rec = cpu_to_le16(1);
4228
4229         xr->xt_list.l_recs[0].e_cpos = 0;
4230         xr->xt_list.l_recs[0].e_blkno = cpu_to_le64(blkno);
4231         xr->xt_list.l_recs[0].e_leaf_clusters = cpu_to_le16(1);
4232
4233         xb->xb_flags = cpu_to_le16(xb_flags | OCFS2_XATTR_INDEXED);
4234
4235         ocfs2_journal_dirty(handle, xb_bh);
4236
4237 out:
4238         up_write(&oi->ip_alloc_sem);
4239
4240         return ret;
4241 }
4242
4243 static int cmp_xe_offset(const void *a, const void *b)
4244 {
4245         const struct ocfs2_xattr_entry *l = a, *r = b;
4246         u32 l_name_offset = le16_to_cpu(l->xe_name_offset);
4247         u32 r_name_offset = le16_to_cpu(r->xe_name_offset);
4248
4249         if (l_name_offset < r_name_offset)
4250                 return 1;
4251         if (l_name_offset > r_name_offset)
4252                 return -1;
4253         return 0;
4254 }
4255
4256 /*
4257  * defrag a xattr bucket if we find that the bucket has some
4258  * holes beteen name/value pairs.
4259  * We will move all the name/value pairs to the end of the bucket
4260  * so that we can spare some space for insertion.
4261  */
4262 static int ocfs2_defrag_xattr_bucket(struct inode *inode,
4263                                      handle_t *handle,
4264                                      struct ocfs2_xattr_bucket *bucket)
4265 {
4266         int ret, i;
4267         size_t end, offset, len;
4268         struct ocfs2_xattr_header *xh;
4269         char *entries, *buf, *bucket_buf = NULL;
4270         u64 blkno = bucket_blkno(bucket);
4271         u16 xh_free_start;
4272         size_t blocksize = inode->i_sb->s_blocksize;
4273         struct ocfs2_xattr_entry *xe;
4274
4275         /*
4276          * In order to make the operation more efficient and generic,
4277          * we copy all the blocks into a contiguous memory and do the
4278          * defragment there, so if anything is error, we will not touch
4279          * the real block.
4280          */
4281         bucket_buf = kmalloc(OCFS2_XATTR_BUCKET_SIZE, GFP_NOFS);
4282         if (!bucket_buf) {
4283                 ret = -EIO;
4284                 goto out;
4285         }
4286
4287         buf = bucket_buf;
4288         for (i = 0; i < bucket->bu_blocks; i++, buf += blocksize)
4289                 memcpy(buf, bucket_block(bucket, i), blocksize);
4290
4291         ret = ocfs2_xattr_bucket_journal_access(handle, bucket,
4292                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4293         if (ret < 0) {
4294                 mlog_errno(ret);
4295                 goto out;
4296         }
4297
4298         xh = (struct ocfs2_xattr_header *)bucket_buf;
4299         entries = (char *)xh->xh_entries;
4300         xh_free_start = le16_to_cpu(xh->xh_free_start);
4301
4302         mlog(0, "adjust xattr bucket in %llu, count = %u, "
4303              "xh_free_start = %u, xh_name_value_len = %u.\n",
4304              (unsigned long long)blkno, le16_to_cpu(xh->xh_count),
4305              xh_free_start, le16_to_cpu(xh->xh_name_value_len));
4306
4307         /*
4308          * sort all the entries by their offset.
4309          * the largest will be the first, so that we can
4310          * move them to the end one by one.
4311          */
4312         sort(entries, le16_to_cpu(xh->xh_count),
4313              sizeof(struct ocfs2_xattr_entry),
4314              cmp_xe_offset, swap_xe);
4315
4316         /* Move all name/values to the end of the bucket. */
4317         xe = xh->xh_entries;
4318         end = OCFS2_XATTR_BUCKET_SIZE;
4319         for (i = 0; i < le16_to_cpu(xh->xh_count); i++, xe++) {
4320                 offset = le16_to_cpu(xe->xe_name_offset);
4321                 len = namevalue_size_xe(xe);
4322
4323                 /*
4324                  * We must make sure that the name/value pair
4325                  * exist in the same block. So adjust end to
4326                  * the previous block end if needed.
4327                  */
4328                 if (((end - len) / blocksize !=
4329                         (end - 1) / blocksize))
4330                         end = end - end % blocksize;
4331
4332                 if (end > offset + len) {
4333                         memmove(bucket_buf + end - len,
4334                                 bucket_buf + offset, len);
4335                         xe->xe_name_offset = cpu_to_le16(end - len);
4336                 }
4337
4338                 mlog_bug_on_msg(end < offset + len, "Defrag check failed for "
4339                                 "bucket %llu\n", (unsigned long long)blkno);
4340
4341                 end -= len;
4342         }
4343
4344         mlog_bug_on_msg(xh_free_start > end, "Defrag check failed for "
4345                         "bucket %llu\n", (unsigned long long)blkno);
4346
4347         if (xh_free_start == end)
4348                 goto out;
4349
4350         memset(bucket_buf + xh_free_start, 0, end - xh_free_start);
4351         xh->xh_free_start = cpu_to_le16(end);
4352
4353         /* sort the entries by their name_hash. */
4354         sort(entries, le16_to_cpu(xh->xh_count),
4355              sizeof(struct ocfs2_xattr_entry),
4356              cmp_xe, swap_xe);
4357
4358         buf = bucket_buf;
4359         for (i = 0; i < bucket->bu_blocks; i++, buf += blocksize)
4360                 memcpy(bucket_block(bucket, i), buf, blocksize);
4361         ocfs2_xattr_bucket_journal_dirty(handle, bucket);
4362
4363 out:
4364         kfree(bucket_buf);
4365         return ret;
4366 }
4367
4368 /*
4369  * prev_blkno points to the start of an existing extent.  new_blkno
4370  * points to a newly allocated extent.  Because we know each of our
4371  * clusters contains more than bucket, we can easily split one cluster
4372  * at a bucket boundary.  So we take the last cluster of the existing
4373  * extent and split it down the middle.  We move the last half of the
4374  * buckets in the last cluster of the existing extent over to the new
4375  * extent.
4376  *
4377  * first_bh is the buffer at prev_blkno so we can update the existing
4378  * extent's bucket count.  header_bh is the bucket were we were hoping
4379  * to insert our xattr.  If the bucket move places the target in the new
4380  * extent, we'll update first_bh and header_bh after modifying the old
4381  * extent.
4382  *
4383  * first_hash will be set as the 1st xe's name_hash in the new extent.
4384  */
4385 static int ocfs2_mv_xattr_bucket_cross_cluster(struct inode *inode,
4386                                                handle_t *handle,
4387                                                struct ocfs2_xattr_bucket *first,
4388                                                struct ocfs2_xattr_bucket *target,
4389                                                u64 new_blkno,
4390                                                u32 num_clusters,
4391                                                u32 *first_hash)
4392 {
4393         int ret;
4394         struct super_block *sb = inode->i_sb;
4395         int blks_per_bucket = ocfs2_blocks_per_xattr_bucket(sb);
4396         int num_buckets = ocfs2_xattr_buckets_per_cluster(OCFS2_SB(sb));
4397         int to_move = num_buckets / 2;
4398         u64 src_blkno;
4399         u64 last_cluster_blkno = bucket_blkno(first) +
4400                 ((num_clusters - 1) * ocfs2_clusters_to_blocks(sb, 1));
4401
4402         BUG_ON(le16_to_cpu(bucket_xh(first)->xh_num_buckets) < num_buckets);
4403         BUG_ON(OCFS2_XATTR_BUCKET_SIZE == OCFS2_SB(sb)->s_clustersize);
4404
4405         mlog(0, "move half of xattrs in cluster %llu to %llu\n",
4406              (unsigned long long)last_cluster_blkno, (unsigned long long)new_blkno);
4407
4408         ret = ocfs2_mv_xattr_buckets(inode, handle, bucket_blkno(first),
4409                                      last_cluster_blkno, new_blkno,
4410                                      to_move, first_hash);
4411         if (ret) {
4412                 mlog_errno(ret);
4413                 goto out;
4414         }
4415
4416         /* This is the first bucket that got moved */
4417         src_blkno = last_cluster_blkno + (to_move * blks_per_bucket);
4418
4419         /*
4420          * If the target bucket was part of the moved buckets, we need to
4421          * update first and target.
4422          */
4423         if (bucket_blkno(target) >= src_blkno) {
4424                 /* Find the block for the new target bucket */
4425                 src_blkno = new_blkno +
4426                         (bucket_blkno(target) - src_blkno);
4427
4428                 ocfs2_xattr_bucket_relse(first);
4429                 ocfs2_xattr_bucket_relse(target);
4430
4431                 /*
4432                  * These shouldn't fail - the buffers are in the
4433                  * journal from ocfs2_cp_xattr_bucket().
4434                  */
4435                 ret = ocfs2_read_xattr_bucket(first, new_blkno);
4436                 if (ret) {
4437                         mlog_errno(ret);
4438                         goto out;
4439                 }
4440                 ret = ocfs2_read_xattr_bucket(target, src_blkno);
4441                 if (ret)
4442                         mlog_errno(ret);
4443
4444         }
4445
4446 out:
4447         return ret;
4448 }
4449
4450 /*
4451  * Find the suitable pos when we divide a bucket into 2.
4452  * We have to make sure the xattrs with the same hash value exist
4453  * in the same bucket.
4454  *
4455  * If this ocfs2_xattr_header covers more than one hash value, find a
4456  * place where the hash value changes.  Try to find the most even split.
4457  * The most common case is that all entries have different hash values,
4458  * and the first check we make will find a place to split.
4459  */
4460 static int ocfs2_xattr_find_divide_pos(struct ocfs2_xattr_header *xh)
4461 {
4462         struct ocfs2_xattr_entry *entries = xh->xh_entries;
4463         int count = le16_to_cpu(xh->xh_count);
4464         int delta, middle = count / 2;
4465
4466         /*
4467          * We start at the middle.  Each step gets farther away in both
4468          * directions.  We therefore hit the change in hash value
4469          * nearest to the middle.  Note that this loop does not execute for
4470          * count < 2.
4471          */
4472         for (delta = 0; delta < middle; delta++) {
4473                 /* Let's check delta earlier than middle */
4474                 if (cmp_xe(&entries[middle - delta - 1],
4475                            &entries[middle - delta]))
4476                         return middle - delta;
4477
4478                 /* For even counts, don't walk off the end */
4479                 if ((middle + delta + 1) == count)
4480                         continue;
4481
4482                 /* Now try delta past middle */
4483                 if (cmp_xe(&entries[middle + delta],
4484                            &entries[middle + delta + 1]))
4485                         return middle + delta + 1;
4486         }
4487
4488         /* Every entry had the same hash */
4489         return count;
4490 }
4491
4492 /*
4493  * Move some xattrs in old bucket(blk) to new bucket(new_blk).
4494  * first_hash will record the 1st hash of the new bucket.
4495  *
4496  * Normally half of the xattrs will be moved.  But we have to make
4497  * sure that the xattrs with the same hash value are stored in the
4498  * same bucket. If all the xattrs in this bucket have the same hash
4499  * value, the new bucket will be initialized as an empty one and the
4500  * first_hash will be initialized as (hash_value+1).
4501  */
4502 static int ocfs2_divide_xattr_bucket(struct inode *inode,
4503                                     handle_t *handle,
4504                                     u64 blk,
4505                                     u64 new_blk,
4506                                     u32 *first_hash,
4507                                     int new_bucket_head)
4508 {
4509         int ret, i;
4510         int count, start, len, name_value_len = 0, name_offset = 0;
4511         struct ocfs2_xattr_bucket *s_bucket = NULL, *t_bucket = NULL;
4512         struct ocfs2_xattr_header *xh;
4513         struct ocfs2_xattr_entry *xe;
4514         int blocksize = inode->i_sb->s_blocksize;
4515
4516         mlog(0, "move some of xattrs from bucket %llu to %llu\n",
4517              (unsigned long long)blk, (unsigned long long)new_blk);
4518
4519         s_bucket = ocfs2_xattr_bucket_new(inode);
4520         t_bucket = ocfs2_xattr_bucket_new(inode);
4521         if (!s_bucket || !t_bucket) {
4522                 ret = -ENOMEM;
4523                 mlog_errno(ret);
4524                 goto out;
4525         }
4526
4527         ret = ocfs2_read_xattr_bucket(s_bucket, blk);
4528         if (ret) {
4529                 mlog_errno(ret);
4530                 goto out;
4531         }
4532
4533         ret = ocfs2_xattr_bucket_journal_access(handle, s_bucket,
4534                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4535         if (ret) {
4536                 mlog_errno(ret);
4537                 goto out;
4538         }
4539
4540         /*
4541          * Even if !new_bucket_head, we're overwriting t_bucket.  Thus,
4542          * there's no need to read it.
4543          */
4544         ret = ocfs2_init_xattr_bucket(t_bucket, new_blk);
4545         if (ret) {
4546                 mlog_errno(ret);
4547                 goto out;
4548         }
4549
4550         /*
4551          * Hey, if we're overwriting t_bucket, what difference does
4552          * ACCESS_CREATE vs ACCESS_WRITE make?  See the comment in the
4553          * same part of ocfs2_cp_xattr_bucket().
4554          */
4555         ret = ocfs2_xattr_bucket_journal_access(handle, t_bucket,
4556                                                 new_bucket_head ?
4557                                                 OCFS2_JOURNAL_ACCESS_CREATE :
4558                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4559         if (ret) {
4560                 mlog_errno(ret);
4561                 goto out;
4562         }
4563
4564         xh = bucket_xh(s_bucket);
4565         count = le16_to_cpu(xh->xh_count);
4566         start = ocfs2_xattr_find_divide_pos(xh);
4567
4568         if (start == count) {
4569                 xe = &xh->xh_entries[start-1];
4570
4571                 /*
4572                  * initialized a new empty bucket here.
4573                  * The hash value is set as one larger than
4574                  * that of the last entry in the previous bucket.
4575                  */
4576                 for (i = 0; i < t_bucket->bu_blocks; i++)
4577                         memset(bucket_block(t_bucket, i), 0, blocksize);
4578
4579                 xh = bucket_xh(t_bucket);
4580                 xh->xh_free_start = cpu_to_le16(blocksize);
4581                 xh->xh_entries[0].xe_name_hash = xe->xe_name_hash;
4582                 le32_add_cpu(&xh->xh_entries[0].xe_name_hash, 1);
4583
4584                 goto set_num_buckets;
4585         }
4586
4587         /* copy the whole bucket to the new first. */
4588         ocfs2_xattr_bucket_copy_data(t_bucket, s_bucket);
4589
4590         /* update the new bucket. */
4591         xh = bucket_xh(t_bucket);
4592
4593         /*
4594          * Calculate the total name/value len and xh_free_start for
4595          * the old bucket first.
4596          */
4597         name_offset = OCFS2_XATTR_BUCKET_SIZE;
4598         name_value_len = 0;
4599         for (i = 0; i < start; i++) {
4600                 xe = &xh->xh_entries[i];
4601                 name_value_len += namevalue_size_xe(xe);
4602                 if (le16_to_cpu(xe->xe_name_offset) < name_offset)
4603                         name_offset = le16_to_cpu(xe->xe_name_offset);
4604         }
4605
4606         /*
4607          * Now begin the modification to the new bucket.
4608          *
4609          * In the new bucket, We just move the xattr entry to the beginning
4610          * and don't touch the name/value. So there will be some holes in the
4611          * bucket, and they will be removed when ocfs2_defrag_xattr_bucket is
4612          * called.
4613          */
4614         xe = &xh->xh_entries[start];
4615         len = sizeof(struct ocfs2_xattr_entry) * (count - start);
4616         mlog(0, "mv xattr entry len %d from %d to %d\n", len,
4617              (int)((char *)xe - (char *)xh),
4618              (int)((char *)xh->xh_entries - (char *)xh));
4619         memmove((char *)xh->xh_entries, (char *)xe, len);
4620         xe = &xh->xh_entries[count - start];
4621         len = sizeof(struct ocfs2_xattr_entry) * start;
4622         memset((char *)xe, 0, len);
4623
4624         le16_add_cpu(&xh->xh_count, -start);
4625         le16_add_cpu(&xh->xh_name_value_len, -name_value_len);
4626
4627         /* Calculate xh_free_start for the new bucket. */
4628         xh->xh_free_start = cpu_to_le16(OCFS2_XATTR_BUCKET_SIZE);
4629         for (i = 0; i < le16_to_cpu(xh->xh_count); i++) {
4630                 xe = &xh->xh_entries[i];
4631                 if (le16_to_cpu(xe->xe_name_offset) <
4632                     le16_to_cpu(xh->xh_free_start))
4633                         xh->xh_free_start = xe->xe_name_offset;
4634         }
4635
4636 set_num_buckets:
4637         /* set xh->xh_num_buckets for the new xh. */
4638         if (new_bucket_head)
4639                 xh->xh_num_buckets = cpu_to_le16(1);
4640         else
4641                 xh->xh_num_buckets = 0;
4642
4643         ocfs2_xattr_bucket_journal_dirty(handle, t_bucket);
4644
4645         /* store the first_hash of the new bucket. */
4646         if (first_hash)
4647                 *first_hash = le32_to_cpu(xh->xh_entries[0].xe_name_hash);
4648
4649         /*
4650          * Now only update the 1st block of the old bucket.  If we
4651          * just added a new empty bucket, there is no need to modify
4652          * it.
4653          */
4654         if (start == count)
4655                 goto out;
4656
4657         xh = bucket_xh(s_bucket);
4658         memset(&xh->xh_entries[start], 0,
4659                sizeof(struct ocfs2_xattr_entry) * (count - start));
4660         xh->xh_count = cpu_to_le16(start);
4661         xh->xh_free_start = cpu_to_le16(name_offset);
4662         xh->xh_name_value_len = cpu_to_le16(name_value_len);
4663
4664         ocfs2_xattr_bucket_journal_dirty(handle, s_bucket);
4665
4666 out:
4667         ocfs2_xattr_bucket_free(s_bucket);
4668         ocfs2_xattr_bucket_free(t_bucket);
4669
4670         return ret;
4671 }
4672
4673 /*
4674  * Copy xattr from one bucket to another bucket.
4675  *
4676  * The caller must make sure that the journal transaction
4677  * has enough space for journaling.
4678  */
4679 static int ocfs2_cp_xattr_bucket(struct inode *inode,
4680                                  handle_t *handle,
4681                                  u64 s_blkno,
4682                                  u64 t_blkno,
4683                                  int t_is_new)
4684 {
4685         int ret;
4686         struct ocfs2_xattr_bucket *s_bucket = NULL, *t_bucket = NULL;
4687
4688         BUG_ON(s_blkno == t_blkno);
4689
4690         mlog(0, "cp bucket %llu to %llu, target is %d\n",
4691              (unsigned long long)s_blkno, (unsigned long long)t_blkno,
4692              t_is_new);
4693
4694         s_bucket = ocfs2_xattr_bucket_new(inode);
4695         t_bucket = ocfs2_xattr_bucket_new(inode);
4696         if (!s_bucket || !t_bucket) {
4697                 ret = -ENOMEM;
4698                 mlog_errno(ret);
4699                 goto out;
4700         }
4701
4702         ret = ocfs2_read_xattr_bucket(s_bucket, s_blkno);
4703         if (ret)
4704                 goto out;
4705
4706         /*
4707          * Even if !t_is_new, we're overwriting t_bucket.  Thus,
4708          * there's no need to read it.
4709          */
4710         ret = ocfs2_init_xattr_bucket(t_bucket, t_blkno);
4711         if (ret)
4712                 goto out;
4713
4714         /*
4715          * Hey, if we're overwriting t_bucket, what difference does
4716          * ACCESS_CREATE vs ACCESS_WRITE make?  Well, if we allocated a new
4717          * cluster to fill, we came here from
4718          * ocfs2_mv_xattr_buckets(), and it is really new -
4719          * ACCESS_CREATE is required.  But we also might have moved data
4720          * out of t_bucket before extending back into it.
4721          * ocfs2_add_new_xattr_bucket() can do this - its call to
4722          * ocfs2_add_new_xattr_cluster() may have created a new extent
4723          * and copied out the end of the old extent.  Then it re-extends
4724          * the old extent back to create space for new xattrs.  That's
4725          * how we get here, and the bucket isn't really new.
4726          */
4727         ret = ocfs2_xattr_bucket_journal_access(handle, t_bucket,
4728                                                 t_is_new ?
4729                                                 OCFS2_JOURNAL_ACCESS_CREATE :
4730                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4731         if (ret)
4732                 goto out;
4733
4734         ocfs2_xattr_bucket_copy_data(t_bucket, s_bucket);
4735         ocfs2_xattr_bucket_journal_dirty(handle, t_bucket);
4736
4737 out:
4738         ocfs2_xattr_bucket_free(t_bucket);
4739         ocfs2_xattr_bucket_free(s_bucket);
4740
4741         return ret;
4742 }
4743
4744 /*
4745  * src_blk points to the start of an existing extent.  last_blk points to
4746  * last cluster in that extent.  to_blk points to a newly allocated
4747  * extent.  We copy the buckets from the cluster at last_blk to the new
4748  * extent.  If start_bucket is non-zero, we skip that many buckets before
4749  * we start copying.  The new extent's xh_num_buckets gets set to the
4750  * number of buckets we copied.  The old extent's xh_num_buckets shrinks
4751  * by the same amount.
4752  */
4753 static int ocfs2_mv_xattr_buckets(struct inode *inode, handle_t *handle,
4754                                   u64 src_blk, u64 last_blk, u64 to_blk,
4755                                   unsigned int start_bucket,
4756                                   u32 *first_hash)
4757 {
4758         int i, ret, credits;
4759         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
4760         int blks_per_bucket = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
4761         int num_buckets = ocfs2_xattr_buckets_per_cluster(osb);
4762         struct ocfs2_xattr_bucket *old_first, *new_first;
4763
4764         mlog(0, "mv xattrs from cluster %llu to %llu\n",
4765              (unsigned long long)last_blk, (unsigned long long)to_blk);
4766
4767         BUG_ON(start_bucket >= num_buckets);
4768         if (start_bucket) {
4769                 num_buckets -= start_bucket;
4770                 last_blk += (start_bucket * blks_per_bucket);
4771         }
4772
4773         /* The first bucket of the original extent */
4774         old_first = ocfs2_xattr_bucket_new(inode);
4775         /* The first bucket of the new extent */
4776         new_first = ocfs2_xattr_bucket_new(inode);
4777         if (!old_first || !new_first) {
4778                 ret = -ENOMEM;
4779                 mlog_errno(ret);
4780                 goto out;
4781         }
4782
4783         ret = ocfs2_read_xattr_bucket(old_first, src_blk);
4784         if (ret) {
4785                 mlog_errno(ret);
4786                 goto out;
4787         }
4788
4789         /*
4790          * We need to update the first bucket of the old extent and all
4791          * the buckets going to the new extent.
4792          */
4793         credits = ((num_buckets + 1) * blks_per_bucket) +
4794                 handle->h_buffer_credits;
4795         ret = ocfs2_extend_trans(handle, credits);
4796         if (ret) {
4797                 mlog_errno(ret);
4798                 goto out;
4799         }
4800
4801         ret = ocfs2_xattr_bucket_journal_access(handle, old_first,
4802                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4803         if (ret) {
4804                 mlog_errno(ret);
4805                 goto out;
4806         }
4807
4808         for (i = 0; i < num_buckets; i++) {
4809                 ret = ocfs2_cp_xattr_bucket(inode, handle,
4810                                             last_blk + (i * blks_per_bucket),
4811                                             to_blk + (i * blks_per_bucket),
4812                                             1);
4813                 if (ret) {
4814                         mlog_errno(ret);
4815                         goto out;
4816                 }
4817         }
4818
4819         /*
4820          * Get the new bucket ready before we dirty anything
4821          * (This actually shouldn't fail, because we already dirtied
4822          * it once in ocfs2_cp_xattr_bucket()).
4823          */
4824         ret = ocfs2_read_xattr_bucket(new_first, to_blk);
4825         if (ret) {
4826                 mlog_errno(ret);
4827                 goto out;
4828         }
4829         ret = ocfs2_xattr_bucket_journal_access(handle, new_first,
4830                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4831         if (ret) {
4832                 mlog_errno(ret);
4833                 goto out;
4834         }
4835
4836         /* Now update the headers */
4837         le16_add_cpu(&bucket_xh(old_first)->xh_num_buckets, -num_buckets);
4838         ocfs2_xattr_bucket_journal_dirty(handle, old_first);
4839
4840         bucket_xh(new_first)->xh_num_buckets = cpu_to_le16(num_buckets);
4841         ocfs2_xattr_bucket_journal_dirty(handle, new_first);
4842
4843         if (first_hash)
4844                 *first_hash = le32_to_cpu(bucket_xh(new_first)->xh_entries[0].xe_name_hash);
4845
4846 out:
4847         ocfs2_xattr_bucket_free(new_first);
4848         ocfs2_xattr_bucket_free(old_first);
4849         return ret;
4850 }
4851
4852 /*
4853  * Move some xattrs in this cluster to the new cluster.
4854  * This function should only be called when bucket size == cluster size.
4855  * Otherwise ocfs2_mv_xattr_bucket_cross_cluster should be used instead.
4856  */
4857 static int ocfs2_divide_xattr_cluster(struct inode *inode,
4858                                       handle_t *handle,
4859                                       u64 prev_blk,
4860                                       u64 new_blk,
4861                                       u32 *first_hash)
4862 {
4863         u16 blk_per_bucket = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
4864         int ret, credits = 2 * blk_per_bucket + handle->h_buffer_credits;
4865
4866         BUG_ON(OCFS2_XATTR_BUCKET_SIZE < OCFS2_SB(inode->i_sb)->s_clustersize);
4867
4868         ret = ocfs2_extend_trans(handle, credits);
4869         if (ret) {
4870                 mlog_errno(ret);
4871                 return ret;
4872         }
4873
4874         /* Move half of the xattr in start_blk to the next bucket. */
4875         return  ocfs2_divide_xattr_bucket(inode, handle, prev_blk,
4876                                           new_blk, first_hash, 1);
4877 }
4878
4879 /*
4880  * Move some xattrs from the old cluster to the new one since they are not
4881  * contiguous in ocfs2 xattr tree.
4882  *
4883  * new_blk starts a new separate cluster, and we will move some xattrs from
4884  * prev_blk to it. v_start will be set as the first name hash value in this
4885  * new cluster so that it can be used as e_cpos during tree insertion and
4886  * don't collide with our original b-tree operations. first_bh and header_bh
4887  * will also be updated since they will be used in ocfs2_extend_xattr_bucket
4888  * to extend the insert bucket.
4889  *
4890  * The problem is how much xattr should we move to the new one and when should
4891  * we update first_bh and header_bh?
4892  * 1. If cluster size > bucket size, that means the previous cluster has more
4893  *    than 1 bucket, so just move half nums of bucket into the new cluster and
4894  *    update the first_bh and header_bh if the insert bucket has been moved
4895  *    to the new cluster.
4896  * 2. If cluster_size == bucket_size:
4897  *    a) If the previous extent rec has more than one cluster and the insert
4898  *       place isn't in the last cluster, copy the entire last cluster to the
4899  *       new one. This time, we don't need to upate the first_bh and header_bh
4900  *       since they will not be moved into the new cluster.
4901  *    b) Otherwise, move the bottom half of the xattrs in the last cluster into
4902  *       the new one. And we set the extend flag to zero if the insert place is
4903  *       moved into the new allocated cluster since no extend is needed.
4904  */
4905 static int ocfs2_adjust_xattr_cross_cluster(struct inode *inode,
4906                                             handle_t *handle,
4907                                             struct ocfs2_xattr_bucket *first,
4908                                             struct ocfs2_xattr_bucket *target,
4909                                             u64 new_blk,
4910                                             u32 prev_clusters,
4911                                             u32 *v_start,
4912                                             int *extend)
4913 {
4914         int ret;
4915
4916         mlog(0, "adjust xattrs from cluster %llu len %u to %llu\n",
4917              (unsigned long long)bucket_blkno(first), prev_clusters,
4918              (unsigned long long)new_blk);
4919
4920         if (ocfs2_xattr_buckets_per_cluster(OCFS2_SB(inode->i_sb)) > 1) {
4921                 ret = ocfs2_mv_xattr_bucket_cross_cluster(inode,
4922                                                           handle,
4923                                                           first, target,
4924                                                           new_blk,
4925                                                           prev_clusters,
4926                                                           v_start);
4927                 if (ret)
4928                         mlog_errno(ret);
4929         } else {
4930                 /* The start of the last cluster in the first extent */
4931                 u64 last_blk = bucket_blkno(first) +
4932                         ((prev_clusters - 1) *
4933                          ocfs2_clusters_to_blocks(inode->i_sb, 1));
4934
4935                 if (prev_clusters > 1 && bucket_blkno(target) != last_blk) {
4936                         ret = ocfs2_mv_xattr_buckets(inode, handle,
4937                                                      bucket_blkno(first),
4938                                                      last_blk, new_blk, 0,
4939                                                      v_start);
4940                         if (ret)
4941                                 mlog_errno(ret);
4942                 } else {
4943                         ret = ocfs2_divide_xattr_cluster(inode, handle,
4944                                                          last_blk, new_blk,
4945                                                          v_start);
4946                         if (ret)
4947                                 mlog_errno(ret);
4948
4949                         if ((bucket_blkno(target) == last_blk) && extend)
4950                                 *extend = 0;
4951                 }
4952         }
4953
4954         return ret;
4955 }
4956
4957 /*
4958  * Add a new cluster for xattr storage.
4959  *
4960  * If the new cluster is contiguous with the previous one, it will be
4961  * appended to the same extent record, and num_clusters will be updated.
4962  * If not, we will insert a new extent for it and move some xattrs in
4963  * the last cluster into the new allocated one.
4964  * We also need to limit the maximum size of a btree leaf, otherwise we'll
4965  * lose the benefits of hashing because we'll have to search large leaves.
4966  * So now the maximum size is OCFS2_MAX_XATTR_TREE_LEAF_SIZE(or clustersize,
4967  * if it's bigger).
4968  *
4969  * first_bh is the first block of the previous extent rec and header_bh
4970  * indicates the bucket we will insert the new xattrs. They will be updated
4971  * when the header_bh is moved into the new cluster.
4972  */
4973 static int ocfs2_add_new_xattr_cluster(struct inode *inode,
4974                                        struct buffer_head *root_bh,
4975                                        struct ocfs2_xattr_bucket *first,
4976                                        struct ocfs2_xattr_bucket *target,
4977                                        u32 *num_clusters,
4978                                        u32 prev_cpos,
4979                                        int *extend,
4980                                        struct ocfs2_xattr_set_ctxt *ctxt)
4981 {
4982         int ret;
4983         u16 bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
4984         u32 prev_clusters = *num_clusters;
4985         u32 clusters_to_add = 1, bit_off, num_bits, v_start = 0;
4986         u64 block;
4987         handle_t *handle = ctxt->handle;
4988         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
4989         struct ocfs2_extent_tree et;
4990
4991         mlog(0, "Add new xattr cluster for %llu, previous xattr hash = %u, "
4992              "previous xattr blkno = %llu\n",
4993              (unsigned long long)OCFS2_I(inode)->ip_blkno,
4994              prev_cpos, (unsigned long long)bucket_blkno(first));
4995
4996         ocfs2_init_xattr_tree_extent_tree(&et, INODE_CACHE(inode), root_bh);
4997
4998         ret = ocfs2_journal_access_xb(handle, INODE_CACHE(inode), root_bh,
4999                                       OCFS2_JOURNAL_ACCESS_WRITE);
5000         if (ret < 0) {
5001                 mlog_errno(ret);
5002                 goto leave;
5003         }
5004
5005         ret = __ocfs2_claim_clusters(osb, handle, ctxt->data_ac, 1,
5006                                      clusters_to_add, &bit_off, &num_bits);
5007         if (ret < 0) {
5008                 if (ret != -ENOSPC)
5009                         mlog_errno(ret);
5010                 goto leave;
5011         }
5012
5013         BUG_ON(num_bits > clusters_to_add);
5014
5015         block = ocfs2_clusters_to_blocks(osb->sb, bit_off);
5016         mlog(0, "Allocating %u clusters at block %u for xattr in inode %llu\n",
5017              num_bits, bit_off, (unsigned long long)OCFS2_I(inode)->ip_blkno);
5018
5019         if (bucket_blkno(first) + (prev_clusters * bpc) == block &&
5020             (prev_clusters + num_bits) << osb->s_clustersize_bits <=
5021              OCFS2_MAX_XATTR_TREE_LEAF_SIZE) {
5022                 /*
5023                  * If this cluster is contiguous with the old one and
5024                  * adding this new cluster, we don't surpass the limit of
5025                  * OCFS2_MAX_XATTR_TREE_LEAF_SIZE, cool. We will let it be
5026                  * initialized and used like other buckets in the previous
5027                  * cluster.
5028                  * So add it as a contiguous one. The caller will handle
5029                  * its init process.
5030                  */
5031                 v_start = prev_cpos + prev_clusters;
5032                 *num_clusters = prev_clusters + num_bits;
5033                 mlog(0, "Add contiguous %u clusters to previous extent rec.\n",
5034                      num_bits);
5035         } else {
5036                 ret = ocfs2_adjust_xattr_cross_cluster(inode,
5037                                                        handle,
5038                                                        first,
5039                                                        target,
5040                                                        block,
5041                                                        prev_clusters,
5042                                                        &v_start,
5043                                                        extend);
5044                 if (ret) {
5045                         mlog_errno(ret);
5046                         goto leave;
5047                 }
5048         }
5049
5050         mlog(0, "Insert %u clusters at block %llu for xattr at %u\n",
5051              num_bits, (unsigned long long)block, v_start);
5052         ret = ocfs2_insert_extent(handle, &et, v_start, block,
5053                                   num_bits, 0, ctxt->meta_ac);
5054         if (ret < 0) {
5055                 mlog_errno(ret);
5056                 goto leave;
5057         }
5058
5059         ret = ocfs2_journal_dirty(handle, root_bh);
5060         if (ret < 0)
5061                 mlog_errno(ret);
5062
5063 leave:
5064         return ret;
5065 }
5066
5067 /*
5068  * We are given an extent.  'first' is the bucket at the very front of
5069  * the extent.  The extent has space for an additional bucket past
5070  * bucket_xh(first)->xh_num_buckets.  'target_blkno' is the block number
5071  * of the target bucket.  We wish to shift every bucket past the target
5072  * down one, filling in that additional space.  When we get back to the
5073  * target, we split the target between itself and the now-empty bucket
5074  * at target+1 (aka, target_blkno + blks_per_bucket).
5075  */
5076 static int ocfs2_extend_xattr_bucket(struct inode *inode,
5077                                      handle_t *handle,
5078                                      struct ocfs2_xattr_bucket *first,
5079                                      u64 target_blk,
5080                                      u32 num_clusters)
5081 {
5082         int ret, credits;
5083         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
5084         u16 blk_per_bucket = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
5085         u64 end_blk;
5086         u16 new_bucket = le16_to_cpu(bucket_xh(first)->xh_num_buckets);
5087
5088         mlog(0, "extend xattr bucket in %llu, xattr extend rec starting "
5089              "from %llu, len = %u\n", (unsigned long long)target_blk,
5090              (unsigned long long)bucket_blkno(first), num_clusters);
5091
5092         /* The extent must have room for an additional bucket */
5093         BUG_ON(new_bucket >=
5094                (num_clusters * ocfs2_xattr_buckets_per_cluster(osb)));
5095
5096         /* end_blk points to the last existing bucket */
5097         end_blk = bucket_blkno(first) + ((new_bucket - 1) * blk_per_bucket);
5098
5099         /*
5100          * end_blk is the start of the last existing bucket.
5101          * Thus, (end_blk - target_blk) covers the target bucket and
5102          * every bucket after it up to, but not including, the last
5103          * existing bucket.  Then we add the last existing bucket, the
5104          * new bucket, and the first bucket (3 * blk_per_bucket).
5105          */
5106         credits = (end_blk - target_blk) + (3 * blk_per_bucket) +
5107                   handle->h_buffer_credits;
5108         ret = ocfs2_extend_trans(handle, credits);
5109         if (ret) {
5110                 mlog_errno(ret);
5111                 goto out;
5112         }
5113
5114         ret = ocfs2_xattr_bucket_journal_access(handle, first,
5115                                                 OCFS2_JOURNAL_ACCESS_WRITE);
5116         if (ret) {
5117                 mlog_errno(ret);
5118                 goto out;
5119         }
5120
5121         while (end_blk != target_blk) {
5122                 ret = ocfs2_cp_xattr_bucket(inode, handle, end_blk,
5123                                             end_blk + blk_per_bucket, 0);
5124                 if (ret)
5125                         goto out;
5126                 end_blk -= blk_per_bucket;
5127         }
5128
5129         /* Move half of the xattr in target_blkno to the next bucket. */
5130         ret = ocfs2_divide_xattr_bucket(inode, handle, target_blk,
5131                                         target_blk + blk_per_bucket, NULL, 0);
5132
5133         le16_add_cpu(&bucket_xh(first)->xh_num_buckets, 1);
5134         ocfs2_xattr_bucket_journal_dirty(handle, first);
5135
5136 out:
5137         return ret;
5138 }
5139
5140 /*
5141  * Add new xattr bucket in an extent record and adjust the buckets
5142  * accordingly.  xb_bh is the ocfs2_xattr_block, and target is the
5143  * bucket we want to insert into.
5144  *
5145  * In the easy case, we will move all the buckets after target down by
5146  * one. Half of target's xattrs will be moved to the next bucket.
5147  *
5148  * If current cluster is full, we'll allocate a new one.  This may not
5149  * be contiguous.  The underlying calls will make sure that there is
5150  * space for the insert, shifting buckets around if necessary.
5151  * 'target' may be moved by those calls.
5152  */
5153 static int ocfs2_add_new_xattr_bucket(struct inode *inode,
5154                                       struct buffer_head *xb_bh,
5155                                       struct ocfs2_xattr_bucket *target,
5156                                       struct ocfs2_xattr_set_ctxt *ctxt)
5157 {
5158         struct ocfs2_xattr_block *xb =
5159                         (struct ocfs2_xattr_block *)xb_bh->b_data;
5160         struct ocfs2_xattr_tree_root *xb_root = &xb->xb_attrs.xb_root;
5161         struct ocfs2_extent_list *el = &xb_root->xt_list;
5162         u32 name_hash =
5163                 le32_to_cpu(bucket_xh(target)->xh_entries[0].xe_name_hash);
5164         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
5165         int ret, num_buckets, extend = 1;
5166         u64 p_blkno;
5167         u32 e_cpos, num_clusters;
5168         /* The bucket at the front of the extent */
5169         struct ocfs2_xattr_bucket *first;
5170
5171         mlog(0, "Add new xattr bucket starting from %llu\n",
5172              (unsigned long long)bucket_blkno(target));
5173
5174         /* The first bucket of the original extent */
5175         first = ocfs2_xattr_bucket_new(inode);
5176         if (!first) {
5177                 ret = -ENOMEM;
5178                 mlog_errno(ret);
5179                 goto out;
5180         }
5181
5182         ret = ocfs2_xattr_get_rec(inode, name_hash, &p_blkno, &e_cpos,
5183                                   &num_clusters, el);
5184         if (ret) {
5185                 mlog_errno(ret);
5186                 goto out;
5187         }
5188
5189         ret = ocfs2_read_xattr_bucket(first, p_blkno);
5190         if (ret) {
5191                 mlog_errno(ret);
5192                 goto out;
5193         }
5194
5195         num_buckets = ocfs2_xattr_buckets_per_cluster(osb) * num_clusters;
5196         if (num_buckets == le16_to_cpu(bucket_xh(first)->xh_num_buckets)) {
5197                 /*
5198                  * This can move first+target if the target bucket moves
5199                  * to the new extent.
5200                  */
5201                 ret = ocfs2_add_new_xattr_cluster(inode,
5202                                                   xb_bh,
5203                                                   first,
5204                                                   target,
5205                                                   &num_clusters,
5206                                                   e_cpos,
5207                                                   &extend,
5208                                                   ctxt);
5209                 if (ret) {
5210                         mlog_errno(ret);
5211                         goto out;
5212                 }
5213         }
5214
5215         if (extend) {
5216                 ret = ocfs2_extend_xattr_bucket(inode,
5217                                                 ctxt->handle,
5218                                                 first,
5219                                                 bucket_blkno(target),
5220                                                 num_clusters);
5221                 if (ret)
5222                         mlog_errno(ret);
5223         }
5224
5225 out:
5226         ocfs2_xattr_bucket_free(first);
5227
5228         return ret;
5229 }
5230
5231 static inline char *ocfs2_xattr_bucket_get_val(struct inode *inode,
5232                                         struct ocfs2_xattr_bucket *bucket,
5233                                         int offs)
5234 {
5235         int block_off = offs >> inode->i_sb->s_blocksize_bits;
5236
5237         offs = offs % inode->i_sb->s_blocksize;
5238         return bucket_block(bucket, block_off) + offs;
5239 }
5240
5241 /*
5242  * Truncate the specified xe_off entry in xattr bucket.
5243  * bucket is indicated by header_bh and len is the new length.
5244  * Both the ocfs2_xattr_value_root and the entry will be updated here.
5245  *
5246  * Copy the new updated xe and xe_value_root to new_xe and new_xv if needed.
5247  */
5248 static int ocfs2_xattr_bucket_value_truncate(struct inode *inode,
5249                                              struct ocfs2_xattr_bucket *bucket,
5250                                              int xe_off,
5251                                              int len,
5252                                              struct ocfs2_xattr_set_ctxt *ctxt)
5253 {
5254         int ret, offset;
5255         u64 value_blk;
5256         struct ocfs2_xattr_entry *xe;
5257         struct ocfs2_xattr_header *xh = bucket_xh(bucket);
5258         size_t blocksize = inode->i_sb->s_blocksize;
5259         struct ocfs2_xattr_value_buf vb = {
5260                 .vb_access = ocfs2_journal_access,
5261         };
5262
5263         xe = &xh->xh_entries[xe_off];
5264
5265         BUG_ON(!xe || ocfs2_xattr_is_local(xe));
5266
5267         offset = le16_to_cpu(xe->xe_name_offset) +
5268                  OCFS2_XATTR_SIZE(xe->xe_name_len);
5269
5270         value_blk = offset / blocksize;
5271
5272         /* We don't allow ocfs2_xattr_value to be stored in different block. */
5273         BUG_ON(value_blk != (offset + OCFS2_XATTR_ROOT_SIZE - 1) / blocksize);
5274
5275         vb.vb_bh = bucket->bu_bhs[value_blk];
5276         BUG_ON(!vb.vb_bh);
5277
5278         vb.vb_xv = (struct ocfs2_xattr_value_root *)
5279                 (vb.vb_bh->b_data + offset % blocksize);
5280
5281         /*
5282          * From here on out we have to dirty the bucket.  The generic
5283          * value calls only modify one of the bucket's bhs, but we need
5284          * to send the bucket at once.  So if they error, they *could* have
5285          * modified something.  We have to assume they did, and dirty
5286          * the whole bucket.  This leaves us in a consistent state.
5287          */
5288         mlog(0, "truncate %u in xattr bucket %llu to %d bytes.\n",
5289              xe_off, (unsigned long long)bucket_blkno(bucket), len);
5290         ret = ocfs2_xattr_value_truncate(inode, &vb, len, ctxt);
5291         if (ret) {
5292                 mlog_errno(ret);
5293                 goto out;
5294         }
5295
5296         ret = ocfs2_xattr_bucket_journal_access(ctxt->handle, bucket,
5297                                                 OCFS2_JOURNAL_ACCESS_WRITE);
5298         if (ret) {
5299                 mlog_errno(ret);
5300                 goto out;
5301         }
5302
5303         xe->xe_value_size = cpu_to_le64(len);
5304
5305         ocfs2_xattr_bucket_journal_dirty(ctxt->handle, bucket);
5306
5307 out:
5308         return ret;
5309 }
5310
5311 static int ocfs2_rm_xattr_cluster(struct inode *inode,
5312                                   struct buffer_head *root_bh,
5313                                   u64 blkno,
5314                                   u32 cpos,
5315                                   u32 len,
5316                                   void *para)
5317 {
5318         int ret;
5319         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
5320         struct inode *tl_inode = osb->osb_tl_inode;
5321         handle_t *handle;
5322         struct ocfs2_xattr_block *xb =
5323                         (struct ocfs2_xattr_block *)root_bh->b_data;
5324         struct ocfs2_alloc_context *meta_ac = NULL;
5325         struct ocfs2_cached_dealloc_ctxt dealloc;
5326         struct ocfs2_extent_tree et;
5327
5328         ret = ocfs2_iterate_xattr_buckets(inode, blkno, len,
5329                                           ocfs2_delete_xattr_in_bucket, para);
5330         if (ret) {
5331                 mlog_errno(ret);
5332                 return ret;
5333         }
5334
5335         ocfs2_init_xattr_tree_extent_tree(&et, INODE_CACHE(inode), root_bh);
5336
5337         ocfs2_init_dealloc_ctxt(&dealloc);
5338
5339         mlog(0, "rm xattr extent rec at %u len = %u, start from %llu\n",
5340              cpos, len, (unsigned long long)blkno);
5341
5342         ocfs2_remove_xattr_clusters_from_cache(INODE_CACHE(inode), blkno,
5343                                                len);
5344
5345         ret = ocfs2_lock_allocators(inode, &et, 0, 1, NULL, &meta_ac);
5346         if (ret) {
5347                 mlog_errno(ret);
5348                 return ret;
5349         }
5350
5351         mutex_lock(&tl_inode->i_mutex);
5352
5353         if (ocfs2_truncate_log_needs_flush(osb)) {
5354                 ret = __ocfs2_flush_truncate_log(osb);
5355                 if (ret < 0) {
5356                         mlog_errno(ret);
5357                         goto out;
5358                 }
5359         }
5360
5361         handle = ocfs2_start_trans(osb, ocfs2_remove_extent_credits(osb->sb));
5362         if (IS_ERR(handle)) {
5363                 ret = -ENOMEM;
5364                 mlog_errno(ret);
5365                 goto out;
5366         }
5367
5368         ret = ocfs2_journal_access_xb(handle, INODE_CACHE(inode), root_bh,
5369                                       OCFS2_JOURNAL_ACCESS_WRITE);
5370         if (ret) {
5371                 mlog_errno(ret);
5372                 goto out_commit;
5373         }
5374
5375         ret = ocfs2_remove_extent(handle, &et, cpos, len, meta_ac,
5376                                   &dealloc);
5377         if (ret) {
5378                 mlog_errno(ret);
5379                 goto out_commit;
5380         }
5381
5382         le32_add_cpu(&xb->xb_attrs.xb_root.xt_clusters, -len);
5383
5384         ret = ocfs2_journal_dirty(handle, root_bh);
5385         if (ret) {
5386                 mlog_errno(ret);
5387                 goto out_commit;
5388         }
5389
5390         ret = ocfs2_truncate_log_append(osb, handle, blkno, len);
5391         if (ret)
5392                 mlog_errno(ret);
5393
5394 out_commit:
5395         ocfs2_commit_trans(osb, handle);
5396 out:
5397         ocfs2_schedule_truncate_log_flush(osb, 1);
5398
5399         mutex_unlock(&tl_inode->i_mutex);
5400
5401         if (meta_ac)
5402                 ocfs2_free_alloc_context(meta_ac);
5403
5404         ocfs2_run_deallocs(osb, &dealloc);
5405
5406         return ret;
5407 }
5408
5409 /*
5410  * check whether the xattr bucket is filled up with the same hash value.
5411  * If we want to insert the xattr with the same hash, return -ENOSPC.
5412  * If we want to insert a xattr with different hash value, go ahead
5413  * and ocfs2_divide_xattr_bucket will handle this.
5414  */
5415 static int ocfs2_check_xattr_bucket_collision(struct inode *inode,
5416                                               struct ocfs2_xattr_bucket *bucket,
5417                                               const char *name)
5418 {
5419         struct ocfs2_xattr_header *xh = bucket_xh(bucket);
5420         u32 name_hash = ocfs2_xattr_name_hash(inode, name, strlen(name));
5421
5422         if (name_hash != le32_to_cpu(xh->xh_entries[0].xe_name_hash))
5423                 return 0;
5424
5425         if (xh->xh_entries[le16_to_cpu(xh->xh_count) - 1].xe_name_hash ==
5426             xh->xh_entries[0].xe_name_hash) {
5427                 mlog(ML_ERROR, "Too much hash collision in xattr bucket %llu, "
5428                      "hash = %u\n",
5429                      (unsigned long long)bucket_blkno(bucket),
5430                      le32_to_cpu(xh->xh_entries[0].xe_name_hash));
5431                 return -ENOSPC;
5432         }
5433
5434         return 0;
5435 }
5436
5437 /*
5438  * Try to set the entry in the current bucket.  If we fail, the caller
5439  * will handle getting us another bucket.
5440  */
5441 static int ocfs2_xattr_set_entry_bucket(struct inode *inode,
5442                                         struct ocfs2_xattr_info *xi,
5443                                         struct ocfs2_xattr_search *xs,
5444                                         struct ocfs2_xattr_set_ctxt *ctxt)
5445 {
5446         int ret;
5447         struct ocfs2_xa_loc loc;
5448
5449         mlog_entry("Set xattr %s in xattr bucket\n", xi->xi_name);
5450
5451         ocfs2_init_xattr_bucket_xa_loc(&loc, xs->bucket,
5452                                        xs->not_found ? NULL : xs->here);
5453         ret = ocfs2_xa_set(&loc, xi, ctxt);
5454         if (!ret) {
5455                 xs->here = loc.xl_entry;
5456                 goto out;
5457         }
5458         if (ret != -ENOSPC) {
5459                 mlog_errno(ret);
5460                 goto out;
5461         }
5462
5463         /* Ok, we need space.  Let's try defragmenting the bucket. */
5464         ret = ocfs2_defrag_xattr_bucket(inode, ctxt->handle,
5465                                         xs->bucket);
5466         if (ret) {
5467                 mlog_errno(ret);
5468                 goto out;
5469         }
5470
5471         ret = ocfs2_xa_set(&loc, xi, ctxt);
5472         if (!ret) {
5473                 xs->here = loc.xl_entry;
5474                 goto out;
5475         }
5476         if (ret != -ENOSPC)
5477                 mlog_errno(ret);
5478
5479
5480 out:
5481         mlog_exit(ret);
5482         return ret;
5483 }
5484
5485 static int ocfs2_xattr_set_entry_index_block(struct inode *inode,
5486                                              struct ocfs2_xattr_info *xi,
5487                                              struct ocfs2_xattr_search *xs,
5488                                              struct ocfs2_xattr_set_ctxt *ctxt)
5489 {
5490         int ret;
5491
5492         mlog_entry("Set xattr %s in xattr index block\n", xi->xi_name);
5493
5494         ret = ocfs2_xattr_set_entry_bucket(inode, xi, xs, ctxt);
5495         if (!ret)
5496                 goto out;
5497         if (ret != -ENOSPC) {
5498                 mlog_errno(ret);
5499                 goto out;
5500         }
5501
5502         /* Ack, need more space.  Let's try to get another bucket! */
5503
5504         /*
5505          * We do not allow for overlapping ranges between buckets. And
5506          * the maximum number of collisions we will allow for then is
5507          * one bucket's worth, so check it here whether we need to
5508          * add a new bucket for the insert.
5509          */
5510         ret = ocfs2_check_xattr_bucket_collision(inode,
5511                                                  xs->bucket,
5512                                                  xi->xi_name);
5513         if (ret) {
5514                 mlog_errno(ret);
5515                 goto out;
5516         }
5517
5518         ret = ocfs2_add_new_xattr_bucket(inode,
5519                                          xs->xattr_bh,
5520                                          xs->bucket,
5521                                          ctxt);
5522         if (ret) {
5523                 mlog_errno(ret);
5524                 goto out;
5525         }
5526
5527         /*
5528          * ocfs2_add_new_xattr_bucket() will have updated
5529          * xs->bucket if it moved, but it will not have updated
5530          * any of the other search fields.  Thus, we drop it and
5531          * re-search.  Everything should be cached, so it'll be
5532          * quick.
5533          */
5534         ocfs2_xattr_bucket_relse(xs->bucket);
5535         ret = ocfs2_xattr_index_block_find(inode, xs->xattr_bh,
5536                                            xi->xi_name_index,
5537                                            xi->xi_name, xs);
5538         if (ret && ret != -ENODATA)
5539                 goto out;
5540         xs->not_found = ret;
5541
5542         /* Ok, we have a new bucket, let's try again */
5543         ret = ocfs2_xattr_set_entry_bucket(inode, xi, xs, ctxt);
5544         if (ret && (ret != -ENOSPC))
5545                 mlog_errno(ret);
5546
5547 out:
5548         mlog_exit(ret);
5549         return ret;
5550 }
5551
5552 static int ocfs2_delete_xattr_in_bucket(struct inode *inode,
5553                                         struct ocfs2_xattr_bucket *bucket,
5554                                         void *para)
5555 {
5556         int ret = 0, ref_credits;
5557         struct ocfs2_xattr_header *xh = bucket_xh(bucket);
5558         u16 i;
5559         struct ocfs2_xattr_entry *xe;
5560         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
5561         struct ocfs2_xattr_set_ctxt ctxt = {NULL, NULL,};
5562         int credits = ocfs2_remove_extent_credits(osb->sb) +
5563                 ocfs2_blocks_per_xattr_bucket(inode->i_sb);
5564         struct ocfs2_xattr_value_root *xv;
5565         struct ocfs2_rm_xattr_bucket_para *args =
5566                         (struct ocfs2_rm_xattr_bucket_para *)para;
5567
5568         ocfs2_init_dealloc_ctxt(&ctxt.dealloc);
5569
5570         for (i = 0; i < le16_to_cpu(xh->xh_count); i++) {
5571                 xe = &xh->xh_entries[i];
5572                 if (ocfs2_xattr_is_local(xe))
5573                         continue;
5574
5575                 ret = ocfs2_get_xattr_tree_value_root(inode->i_sb, bucket,
5576                                                       i, &xv, NULL);
5577
5578                 ret = ocfs2_lock_xattr_remove_allocators(inode, xv,
5579                                                          args->ref_ci,
5580                                                          args->ref_root_bh,
5581                                                          &ctxt.meta_ac,
5582                                                          &ref_credits);
5583
5584                 ctxt.handle = ocfs2_start_trans(osb, credits + ref_credits);
5585                 if (IS_ERR(ctxt.handle)) {
5586                         ret = PTR_ERR(ctxt.handle);
5587                         mlog_errno(ret);
5588                         break;
5589                 }
5590
5591                 ret = ocfs2_xattr_bucket_value_truncate(inode, bucket,
5592                                                         i, 0, &ctxt);
5593
5594                 ocfs2_commit_trans(osb, ctxt.handle);
5595                 if (ctxt.meta_ac) {
5596                         ocfs2_free_alloc_context(ctxt.meta_ac);
5597                         ctxt.meta_ac = NULL;
5598                 }
5599                 if (ret) {
5600                         mlog_errno(ret);
5601                         break;
5602                 }
5603         }
5604
5605         if (ctxt.meta_ac)
5606                 ocfs2_free_alloc_context(ctxt.meta_ac);
5607         ocfs2_schedule_truncate_log_flush(osb, 1);
5608         ocfs2_run_deallocs(osb, &ctxt.dealloc);
5609         return ret;
5610 }
5611
5612 /*
5613  * Whenever we modify a xattr value root in the bucket(e.g, CoW
5614  * or change the extent record flag), we need to recalculate
5615  * the metaecc for the whole bucket. So it is done here.
5616  *
5617  * Note:
5618  * We have to give the extra credits for the caller.
5619  */
5620 static int ocfs2_xattr_bucket_post_refcount(struct inode *inode,
5621                                             handle_t *handle,
5622                                             void *para)
5623 {
5624         int ret;
5625         struct ocfs2_xattr_bucket *bucket =
5626                         (struct ocfs2_xattr_bucket *)para;
5627
5628         ret = ocfs2_xattr_bucket_journal_access(handle, bucket,
5629                                                 OCFS2_JOURNAL_ACCESS_WRITE);
5630         if (ret) {
5631                 mlog_errno(ret);
5632                 return ret;
5633         }
5634
5635         ocfs2_xattr_bucket_journal_dirty(handle, bucket);
5636
5637         return 0;
5638 }
5639
5640 /*
5641  * Special action we need if the xattr value is refcounted.
5642  *
5643  * 1. If the xattr is refcounted, lock the tree.
5644  * 2. CoW the xattr if we are setting the new value and the value
5645  *    will be stored outside.
5646  * 3. In other case, decrease_refcount will work for us, so just
5647  *    lock the refcount tree, calculate the meta and credits is OK.
5648  *
5649  * We have to do CoW before ocfs2_init_xattr_set_ctxt since
5650  * currently CoW is a completed transaction, while this function
5651  * will also lock the allocators and let us deadlock. So we will
5652  * CoW the whole xattr value.
5653  */
5654 static int ocfs2_prepare_refcount_xattr(struct inode *inode,
5655                                         struct ocfs2_dinode *di,
5656                                         struct ocfs2_xattr_info *xi,
5657                                         struct ocfs2_xattr_search *xis,
5658                                         struct ocfs2_xattr_search *xbs,
5659                                         struct ocfs2_refcount_tree **ref_tree,
5660                                         int *meta_add,
5661                                         int *credits)
5662 {
5663         int ret = 0;
5664         struct ocfs2_xattr_block *xb;
5665         struct ocfs2_xattr_entry *xe;
5666         char *base;
5667         u32 p_cluster, num_clusters;
5668         unsigned int ext_flags;
5669         int name_offset, name_len;
5670         struct ocfs2_xattr_value_buf vb;
5671         struct ocfs2_xattr_bucket *bucket = NULL;
5672         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
5673         struct ocfs2_post_refcount refcount;
5674         struct ocfs2_post_refcount *p = NULL;
5675         struct buffer_head *ref_root_bh = NULL;
5676
5677         if (!xis->not_found) {
5678                 xe = xis->here;
5679                 name_offset = le16_to_cpu(xe->xe_name_offset);
5680                 name_len = OCFS2_XATTR_SIZE(xe->xe_name_len);
5681                 base = xis->base;
5682                 vb.vb_bh = xis->inode_bh;
5683                 vb.vb_access = ocfs2_journal_access_di;
5684         } else {
5685                 int i, block_off = 0;
5686                 xb = (struct ocfs2_xattr_block *)xbs->xattr_bh->b_data;
5687                 xe = xbs->here;
5688                 name_offset = le16_to_cpu(xe->xe_name_offset);
5689                 name_len = OCFS2_XATTR_SIZE(xe->xe_name_len);
5690                 i = xbs->here - xbs->header->xh_entries;
5691
5692                 if (le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED) {
5693                         ret = ocfs2_xattr_bucket_get_name_value(inode->i_sb,
5694                                                         bucket_xh(xbs->bucket),
5695                                                         i, &block_off,
5696                                                         &name_offset);
5697                         if (ret) {
5698                                 mlog_errno(ret);
5699                                 goto out;
5700                         }
5701                         base = bucket_block(xbs->bucket, block_off);
5702                         vb.vb_bh = xbs->bucket->bu_bhs[block_off];
5703                         vb.vb_access = ocfs2_journal_access;
5704
5705                         if (ocfs2_meta_ecc(osb)) {
5706                                 /*create parameters for ocfs2_post_refcount. */
5707                                 bucket = xbs->bucket;
5708                                 refcount.credits = bucket->bu_blocks;
5709                                 refcount.para = bucket;
5710                                 refcount.func =
5711                                         ocfs2_xattr_bucket_post_refcount;
5712                                 p = &refcount;
5713                         }
5714                 } else {
5715                         base = xbs->base;
5716                         vb.vb_bh = xbs->xattr_bh;
5717                         vb.vb_access = ocfs2_journal_access_xb;
5718                 }
5719         }
5720
5721         if (ocfs2_xattr_is_local(xe))
5722                 goto out;
5723
5724         vb.vb_xv = (struct ocfs2_xattr_value_root *)
5725                                 (base + name_offset + name_len);
5726
5727         ret = ocfs2_xattr_get_clusters(inode, 0, &p_cluster,
5728                                        &num_clusters, &vb.vb_xv->xr_list,
5729                                        &ext_flags);
5730         if (ret) {
5731                 mlog_errno(ret);
5732                 goto out;
5733         }
5734
5735         /*
5736          * We just need to check the 1st extent record, since we always
5737          * CoW the whole xattr. So there shouldn't be a xattr with
5738          * some REFCOUNT extent recs after the 1st one.
5739          */
5740         if (!(ext_flags & OCFS2_EXT_REFCOUNTED))
5741                 goto out;
5742
5743         ret = ocfs2_lock_refcount_tree(osb, le64_to_cpu(di->i_refcount_loc),
5744                                        1, ref_tree, &ref_root_bh);
5745         if (ret) {
5746                 mlog_errno(ret);
5747                 goto out;
5748         }
5749
5750         /*
5751          * If we are deleting the xattr or the new size will be stored inside,
5752          * cool, leave it there, the xattr truncate process will remove them
5753          * for us(it still needs the refcount tree lock and the meta, credits).
5754          * And the worse case is that every cluster truncate will split the
5755          * refcount tree, and make the original extent become 3. So we will need
5756          * 2 * cluster more extent recs at most.
5757          */
5758         if (!xi->xi_value || xi->xi_value_len <= OCFS2_XATTR_INLINE_SIZE) {
5759
5760                 ret = ocfs2_refcounted_xattr_delete_need(inode,
5761                                                          &(*ref_tree)->rf_ci,
5762                                                          ref_root_bh, vb.vb_xv,
5763                                                          meta_add, credits);
5764                 if (ret)
5765                         mlog_errno(ret);
5766                 goto out;
5767         }
5768
5769         ret = ocfs2_refcount_cow_xattr(inode, di, &vb,
5770                                        *ref_tree, ref_root_bh, 0,
5771                                        le32_to_cpu(vb.vb_xv->xr_clusters), p);
5772         if (ret)
5773                 mlog_errno(ret);
5774
5775 out:
5776         brelse(ref_root_bh);
5777         return ret;
5778 }
5779
5780 /*
5781  * Add the REFCOUNTED flags for all the extent rec in ocfs2_xattr_value_root.
5782  * The physical clusters will be added to refcount tree.
5783  */
5784 static int ocfs2_xattr_value_attach_refcount(struct inode *inode,
5785                                 struct ocfs2_xattr_value_root *xv,
5786                                 struct ocfs2_extent_tree *value_et,
5787                                 struct ocfs2_caching_info *ref_ci,
5788                                 struct buffer_head *ref_root_bh,
5789                                 struct ocfs2_cached_dealloc_ctxt *dealloc,
5790                                 struct ocfs2_post_refcount *refcount)
5791 {
5792         int ret = 0;
5793         u32 clusters = le32_to_cpu(xv->xr_clusters);
5794         u32 cpos, p_cluster, num_clusters;
5795         struct ocfs2_extent_list *el = &xv->xr_list;
5796         unsigned int ext_flags;
5797
5798         cpos = 0;
5799         while (cpos < clusters) {
5800                 ret = ocfs2_xattr_get_clusters(inode, cpos, &p_cluster,
5801                                                &num_clusters, el, &ext_flags);
5802
5803                 cpos += num_clusters;
5804                 if ((ext_flags & OCFS2_EXT_REFCOUNTED))
5805                         continue;
5806
5807                 BUG_ON(!p_cluster);
5808
5809                 ret = ocfs2_add_refcount_flag(inode, value_et,
5810                                               ref_ci, ref_root_bh,
5811                                               cpos - num_clusters,
5812                                               p_cluster, num_clusters,
5813                                               dealloc, refcount);
5814                 if (ret) {
5815                         mlog_errno(ret);
5816                         break;
5817                 }
5818         }
5819
5820         return ret;
5821 }
5822
5823 /*
5824  * Given a normal ocfs2_xattr_header, refcount all the entries which
5825  * have value stored outside.
5826  * Used for xattrs stored in inode and ocfs2_xattr_block.
5827  */
5828 static int ocfs2_xattr_attach_refcount_normal(struct inode *inode,
5829                                 struct ocfs2_xattr_value_buf *vb,
5830                                 struct ocfs2_xattr_header *header,
5831                                 struct ocfs2_caching_info *ref_ci,
5832                                 struct buffer_head *ref_root_bh,
5833                                 struct ocfs2_cached_dealloc_ctxt *dealloc)
5834 {
5835
5836         struct ocfs2_xattr_entry *xe;
5837         struct ocfs2_xattr_value_root *xv;
5838         struct ocfs2_extent_tree et;
5839         int i, ret = 0;
5840
5841         for (i = 0; i < le16_to_cpu(header->xh_count); i++) {
5842                 xe = &header->xh_entries[i];
5843
5844                 if (ocfs2_xattr_is_local(xe))
5845                         continue;
5846
5847                 xv = (struct ocfs2_xattr_value_root *)((void *)header +
5848                         le16_to_cpu(xe->xe_name_offset) +
5849                         OCFS2_XATTR_SIZE(xe->xe_name_len));
5850
5851                 vb->vb_xv = xv;
5852                 ocfs2_init_xattr_value_extent_tree(&et, INODE_CACHE(inode), vb);
5853
5854                 ret = ocfs2_xattr_value_attach_refcount(inode, xv, &et,
5855                                                         ref_ci, ref_root_bh,
5856                                                         dealloc, NULL);
5857                 if (ret) {
5858                         mlog_errno(ret);
5859                         break;
5860                 }
5861         }
5862
5863         return ret;
5864 }
5865
5866 static int ocfs2_xattr_inline_attach_refcount(struct inode *inode,
5867                                 struct buffer_head *fe_bh,
5868                                 struct ocfs2_caching_info *ref_ci,
5869                                 struct buffer_head *ref_root_bh,
5870                                 struct ocfs2_cached_dealloc_ctxt *dealloc)
5871 {
5872         struct ocfs2_dinode *di = (struct ocfs2_dinode *)fe_bh->b_data;
5873         struct ocfs2_xattr_header *header = (struct ocfs2_xattr_header *)
5874                                 (fe_bh->b_data + inode->i_sb->s_blocksize -
5875                                 le16_to_cpu(di->i_xattr_inline_size));
5876         struct ocfs2_xattr_value_buf vb = {
5877                 .vb_bh = fe_bh,
5878                 .vb_access = ocfs2_journal_access_di,
5879         };
5880
5881         return ocfs2_xattr_attach_refcount_normal(inode, &vb, header,
5882                                                   ref_ci, ref_root_bh, dealloc);
5883 }
5884
5885 struct ocfs2_xattr_tree_value_refcount_para {
5886         struct ocfs2_caching_info *ref_ci;
5887         struct buffer_head *ref_root_bh;
5888         struct ocfs2_cached_dealloc_ctxt *dealloc;
5889 };
5890
5891 static int ocfs2_get_xattr_tree_value_root(struct super_block *sb,
5892                                            struct ocfs2_xattr_bucket *bucket,
5893                                            int offset,
5894                                            struct ocfs2_xattr_value_root **xv,
5895                                            struct buffer_head **bh)
5896 {
5897         int ret, block_off, name_offset;
5898         struct ocfs2_xattr_header *xh = bucket_xh(bucket);
5899         struct ocfs2_xattr_entry *xe = &xh->xh_entries[offset];
5900         void *base;
5901
5902         ret = ocfs2_xattr_bucket_get_name_value(sb,
5903                                                 bucket_xh(bucket),
5904                                                 offset,
5905                                                 &block_off,
5906                                                 &name_offset);
5907         if (ret) {
5908                 mlog_errno(ret);
5909                 goto out;
5910         }
5911
5912         base = bucket_block(bucket, block_off);
5913
5914         *xv = (struct ocfs2_xattr_value_root *)(base + name_offset +
5915                          OCFS2_XATTR_SIZE(xe->xe_name_len));
5916
5917         if (bh)
5918                 *bh = bucket->bu_bhs[block_off];
5919 out:
5920         return ret;
5921 }
5922
5923 /*
5924  * For a given xattr bucket, refcount all the entries which
5925  * have value stored outside.
5926  */
5927 static int ocfs2_xattr_bucket_value_refcount(struct inode *inode,
5928                                              struct ocfs2_xattr_bucket *bucket,
5929                                              void *para)
5930 {
5931         int i, ret = 0;
5932         struct ocfs2_extent_tree et;
5933         struct ocfs2_xattr_tree_value_refcount_para *ref =
5934                         (struct ocfs2_xattr_tree_value_refcount_para *)para;
5935         struct ocfs2_xattr_header *xh =
5936                         (struct ocfs2_xattr_header *)bucket->bu_bhs[0]->b_data;
5937         struct ocfs2_xattr_entry *xe;
5938         struct ocfs2_xattr_value_buf vb = {
5939                 .vb_access = ocfs2_journal_access,
5940         };
5941         struct ocfs2_post_refcount refcount = {
5942                 .credits = bucket->bu_blocks,
5943                 .para = bucket,
5944                 .func = ocfs2_xattr_bucket_post_refcount,
5945         };
5946         struct ocfs2_post_refcount *p = NULL;
5947
5948         /* We only need post_refcount if we support metaecc. */
5949         if (ocfs2_meta_ecc(OCFS2_SB(inode->i_sb)))
5950                 p = &refcount;
5951
5952         mlog(0, "refcount bucket %llu, count = %u\n",
5953              (unsigned long long)bucket_blkno(bucket),
5954              le16_to_cpu(xh->xh_count));
5955         for (i = 0; i < le16_to_cpu(xh->xh_count); i++) {
5956                 xe = &xh->xh_entries[i];
5957
5958                 if (ocfs2_xattr_is_local(xe))
5959                         continue;
5960
5961                 ret = ocfs2_get_xattr_tree_value_root(inode->i_sb, bucket, i,
5962                                                       &vb.vb_xv, &vb.vb_bh);
5963                 if (ret) {
5964                         mlog_errno(ret);
5965                         break;
5966                 }
5967
5968                 ocfs2_init_xattr_value_extent_tree(&et,
5969                                                    INODE_CACHE(inode), &vb);
5970
5971                 ret = ocfs2_xattr_value_attach_refcount(inode, vb.vb_xv,
5972                                                         &et, ref->ref_ci,
5973                                                         ref->ref_root_bh,
5974                                                         ref->dealloc, p);
5975                 if (ret) {
5976                         mlog_errno(ret);
5977                         break;
5978                 }
5979         }
5980
5981         return ret;
5982
5983 }
5984
5985 static int ocfs2_refcount_xattr_tree_rec(struct inode *inode,
5986                                      struct buffer_head *root_bh,
5987                                      u64 blkno, u32 cpos, u32 len, void *para)
5988 {
5989         return ocfs2_iterate_xattr_buckets(inode, blkno, len,
5990                                            ocfs2_xattr_bucket_value_refcount,
5991                                            para);
5992 }
5993
5994 static int ocfs2_xattr_block_attach_refcount(struct inode *inode,
5995                                 struct buffer_head *blk_bh,
5996                                 struct ocfs2_caching_info *ref_ci,
5997                                 struct buffer_head *ref_root_bh,
5998                                 struct ocfs2_cached_dealloc_ctxt *dealloc)
5999 {
6000         int ret = 0;
6001         struct ocfs2_xattr_block *xb =
6002                                 (struct ocfs2_xattr_block *)blk_bh->b_data;
6003
6004         if (!(le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED)) {
6005                 struct ocfs2_xattr_header *header = &xb->xb_attrs.xb_header;
6006                 struct ocfs2_xattr_value_buf vb = {
6007                         .vb_bh = blk_bh,
6008                         .vb_access = ocfs2_journal_access_xb,
6009                 };
6010
6011                 ret = ocfs2_xattr_attach_refcount_normal(inode, &vb, header,
6012                                                          ref_ci, ref_root_bh,
6013                                                          dealloc);
6014         } else {
6015                 struct ocfs2_xattr_tree_value_refcount_para para = {
6016                         .ref_ci = ref_ci,
6017                         .ref_root_bh = ref_root_bh,
6018                         .dealloc = dealloc,
6019                 };
6020
6021                 ret = ocfs2_iterate_xattr_index_block(inode, blk_bh,
6022                                                 ocfs2_refcount_xattr_tree_rec,
6023                                                 &para);
6024         }
6025
6026         return ret;
6027 }
6028
6029 int ocfs2_xattr_attach_refcount_tree(struct inode *inode,
6030                                      struct buffer_head *fe_bh,
6031                                      struct ocfs2_caching_info *ref_ci,
6032                                      struct buffer_head *ref_root_bh,
6033                                      struct ocfs2_cached_dealloc_ctxt *dealloc)
6034 {
6035         int ret = 0;
6036         struct ocfs2_inode_info *oi = OCFS2_I(inode);
6037         struct ocfs2_dinode *di = (struct ocfs2_dinode *)fe_bh->b_data;
6038         struct buffer_head *blk_bh = NULL;
6039
6040         if (oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL) {
6041                 ret = ocfs2_xattr_inline_attach_refcount(inode, fe_bh,
6042                                                          ref_ci, ref_root_bh,
6043                                                          dealloc);
6044                 if (ret) {
6045                         mlog_errno(ret);
6046                         goto out;
6047                 }
6048         }
6049
6050         if (!di->i_xattr_loc)
6051                 goto out;
6052
6053         ret = ocfs2_read_xattr_block(inode, le64_to_cpu(di->i_xattr_loc),
6054                                      &blk_bh);
6055         if (ret < 0) {
6056                 mlog_errno(ret);
6057                 goto out;
6058         }
6059
6060         ret = ocfs2_xattr_block_attach_refcount(inode, blk_bh, ref_ci,
6061                                                 ref_root_bh, dealloc);
6062         if (ret)
6063                 mlog_errno(ret);
6064
6065         brelse(blk_bh);
6066 out:
6067
6068         return ret;
6069 }
6070
6071 typedef int (should_xattr_reflinked)(struct ocfs2_xattr_entry *xe);
6072 /*
6073  * Store the information we need in xattr reflink.
6074  * old_bh and new_bh are inode bh for the old and new inode.
6075  */
6076 struct ocfs2_xattr_reflink {
6077         struct inode *old_inode;
6078         struct inode *new_inode;
6079         struct buffer_head *old_bh;
6080         struct buffer_head *new_bh;
6081         struct ocfs2_caching_info *ref_ci;
6082         struct buffer_head *ref_root_bh;
6083         struct ocfs2_cached_dealloc_ctxt *dealloc;
6084         should_xattr_reflinked *xattr_reflinked;
6085 };
6086
6087 /*
6088  * Given a xattr header and xe offset,
6089  * return the proper xv and the corresponding bh.
6090  * xattr in inode, block and xattr tree have different implementaions.
6091  */
6092 typedef int (get_xattr_value_root)(struct super_block *sb,
6093                                    struct buffer_head *bh,
6094                                    struct ocfs2_xattr_header *xh,
6095                                    int offset,
6096                                    struct ocfs2_xattr_value_root **xv,
6097                                    struct buffer_head **ret_bh,
6098                                    void *para);
6099
6100 /*
6101  * Calculate all the xattr value root metadata stored in this xattr header and
6102  * credits we need if we create them from the scratch.
6103  * We use get_xattr_value_root so that all types of xattr container can use it.
6104  */
6105 static int ocfs2_value_metas_in_xattr_header(struct super_block *sb,
6106                                              struct buffer_head *bh,
6107                                              struct ocfs2_xattr_header *xh,
6108                                              int *metas, int *credits,
6109                                              int *num_recs,
6110                                              get_xattr_value_root *func,
6111                                              void *para)
6112 {
6113         int i, ret = 0;
6114         struct ocfs2_xattr_value_root *xv;
6115         struct ocfs2_xattr_entry *xe;
6116
6117         for (i = 0; i < le16_to_cpu(xh->xh_count); i++) {
6118                 xe = &xh->xh_entries[i];
6119                 if (ocfs2_xattr_is_local(xe))
6120                         continue;
6121
6122                 ret = func(sb, bh, xh, i, &xv, NULL, para);
6123                 if (ret) {
6124                         mlog_errno(ret);
6125                         break;
6126                 }
6127
6128                 *metas += le16_to_cpu(xv->xr_list.l_tree_depth) *
6129                           le16_to_cpu(xv->xr_list.l_next_free_rec);
6130
6131                 *credits += ocfs2_calc_extend_credits(sb,
6132                                                 &def_xv.xv.xr_list,
6133                                                 le32_to_cpu(xv->xr_clusters));
6134
6135                 /*
6136                  * If the value is a tree with depth > 1, We don't go deep
6137                  * to the extent block, so just calculate a maximum record num.
6138                  */
6139                 if (!xv->xr_list.l_tree_depth)
6140                         *num_recs += le16_to_cpu(xv->xr_list.l_next_free_rec);
6141                 else
6142                         *num_recs += ocfs2_clusters_for_bytes(sb,
6143                                                               XATTR_SIZE_MAX);
6144         }
6145
6146         return ret;
6147 }
6148
6149 /* Used by xattr inode and block to return the right xv and buffer_head. */
6150 static int ocfs2_get_xattr_value_root(struct super_block *sb,
6151                                       struct buffer_head *bh,
6152                                       struct ocfs2_xattr_header *xh,
6153                                       int offset,
6154                                       struct ocfs2_xattr_value_root **xv,
6155                                       struct buffer_head **ret_bh,
6156                                       void *para)
6157 {
6158         struct ocfs2_xattr_entry *xe = &xh->xh_entries[offset];
6159
6160         *xv = (struct ocfs2_xattr_value_root *)((void *)xh +
6161                 le16_to_cpu(xe->xe_name_offset) +
6162                 OCFS2_XATTR_SIZE(xe->xe_name_len));
6163
6164         if (ret_bh)
6165                 *ret_bh = bh;
6166
6167         return 0;
6168 }
6169
6170 /*
6171  * Lock the meta_ac and caculate how much credits we need for reflink xattrs.
6172  * It is only used for inline xattr and xattr block.
6173  */
6174 static int ocfs2_reflink_lock_xattr_allocators(struct ocfs2_super *osb,
6175                                         struct ocfs2_xattr_header *xh,
6176                                         struct buffer_head *ref_root_bh,
6177                                         int *credits,
6178                                         struct ocfs2_alloc_context **meta_ac)
6179 {
6180         int ret, meta_add = 0, num_recs = 0;
6181         struct ocfs2_refcount_block *rb =
6182                         (struct ocfs2_refcount_block *)ref_root_bh->b_data;
6183
6184         *credits = 0;
6185
6186         ret = ocfs2_value_metas_in_xattr_header(osb->sb, NULL, xh,
6187                                                 &meta_add, credits, &num_recs,
6188                                                 ocfs2_get_xattr_value_root,
6189                                                 NULL);
6190         if (ret) {
6191                 mlog_errno(ret);
6192                 goto out;
6193         }
6194
6195         /*
6196          * We need to add/modify num_recs in refcount tree, so just calculate
6197          * an approximate number we need for refcount tree change.
6198          * Sometimes we need to split the tree, and after split,  half recs
6199          * will be moved to the new block, and a new block can only provide
6200          * half number of recs. So we multiple new blocks by 2.
6201          */
6202         num_recs = num_recs / ocfs2_refcount_recs_per_rb(osb->sb) * 2;
6203         meta_add += num_recs;
6204         *credits += num_recs + num_recs * OCFS2_EXPAND_REFCOUNT_TREE_CREDITS;
6205         if (le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL)
6206                 *credits += le16_to_cpu(rb->rf_list.l_tree_depth) *
6207                             le16_to_cpu(rb->rf_list.l_next_free_rec) + 1;
6208         else
6209                 *credits += 1;
6210
6211         ret = ocfs2_reserve_new_metadata_blocks(osb, meta_add, meta_ac);
6212         if (ret)
6213                 mlog_errno(ret);
6214
6215 out:
6216         return ret;
6217 }
6218
6219 /*
6220  * Given a xattr header, reflink all the xattrs in this container.
6221  * It can be used for inode, block and bucket.
6222  *
6223  * NOTE:
6224  * Before we call this function, the caller has memcpy the xattr in
6225  * old_xh to the new_xh.
6226  *
6227  * If args.xattr_reflinked is set, call it to decide whether the xe should
6228  * be reflinked or not. If not, remove it from the new xattr header.
6229  */
6230 static int ocfs2_reflink_xattr_header(handle_t *handle,
6231                                       struct ocfs2_xattr_reflink *args,
6232                                       struct buffer_head *old_bh,
6233                                       struct ocfs2_xattr_header *xh,
6234                                       struct buffer_head *new_bh,
6235                                       struct ocfs2_xattr_header *new_xh,
6236                                       struct ocfs2_xattr_value_buf *vb,
6237                                       struct ocfs2_alloc_context *meta_ac,
6238                                       get_xattr_value_root *func,
6239                                       void *para)
6240 {
6241         int ret = 0, i, j;
6242         struct super_block *sb = args->old_inode->i_sb;
6243         struct buffer_head *value_bh;
6244         struct ocfs2_xattr_entry *xe, *last;
6245         struct ocfs2_xattr_value_root *xv, *new_xv;
6246         struct ocfs2_extent_tree data_et;
6247         u32 clusters, cpos, p_cluster, num_clusters;
6248         unsigned int ext_flags = 0;
6249
6250         mlog(0, "reflink xattr in container %llu, count = %u\n",
6251              (unsigned long long)old_bh->b_blocknr, le16_to_cpu(xh->xh_count));
6252
6253         last = &new_xh->xh_entries[le16_to_cpu(new_xh->xh_count)];
6254         for (i = 0, j = 0; i < le16_to_cpu(xh->xh_count); i++, j++) {
6255                 xe = &xh->xh_entries[i];
6256
6257                 if (args->xattr_reflinked && !args->xattr_reflinked(xe)) {
6258                         xe = &new_xh->xh_entries[j];
6259
6260                         le16_add_cpu(&new_xh->xh_count, -1);
6261                         if (new_xh->xh_count) {
6262                                 memmove(xe, xe + 1,
6263                                         (void *)last - (void *)xe);
6264                                 memset(last, 0,
6265                                        sizeof(struct ocfs2_xattr_entry));
6266                         }
6267
6268                         /*
6269                          * We don't want j to increase in the next round since
6270                          * it is already moved ahead.
6271                          */
6272                         j--;
6273                         continue;
6274                 }
6275
6276                 if (ocfs2_xattr_is_local(xe))
6277                         continue;
6278
6279                 ret = func(sb, old_bh, xh, i, &xv, NULL, para);
6280                 if (ret) {
6281                         mlog_errno(ret);
6282                         break;
6283                 }
6284
6285                 ret = func(sb, new_bh, new_xh, j, &new_xv, &value_bh, para);
6286                 if (ret) {
6287                         mlog_errno(ret);
6288                         break;
6289                 }
6290
6291                 /*
6292                  * For the xattr which has l_tree_depth = 0, all the extent
6293                  * recs have already be copied to the new xh with the
6294                  * propriate OCFS2_EXT_REFCOUNTED flag we just need to
6295                  * increase the refount count int the refcount tree.
6296                  *
6297                  * For the xattr which has l_tree_depth > 0, we need
6298                  * to initialize it to the empty default value root,
6299                  * and then insert the extents one by one.
6300                  */
6301                 if (xv->xr_list.l_tree_depth) {
6302                         memcpy(new_xv, &def_xv, sizeof(def_xv));
6303                         vb->vb_xv = new_xv;
6304                         vb->vb_bh = value_bh;
6305                         ocfs2_init_xattr_value_extent_tree(&data_et,
6306                                         INODE_CACHE(args->new_inode), vb);
6307                 }
6308
6309                 clusters = le32_to_cpu(xv->xr_clusters);
6310                 cpos = 0;
6311                 while (cpos < clusters) {
6312                         ret = ocfs2_xattr_get_clusters(args->old_inode,
6313                                                        cpos,
6314                                                        &p_cluster,
6315                                                        &num_clusters,
6316                                                        &xv->xr_list,
6317                                                        &ext_flags);
6318                         if (ret) {
6319                                 mlog_errno(ret);
6320                                 goto out;
6321                         }
6322
6323                         BUG_ON(!p_cluster);
6324
6325                         if (xv->xr_list.l_tree_depth) {
6326                                 ret = ocfs2_insert_extent(handle,
6327                                                 &data_et, cpos,
6328                                                 ocfs2_clusters_to_blocks(
6329                                                         args->old_inode->i_sb,
6330                                                         p_cluster),
6331                                                 num_clusters, ext_flags,
6332                                                 meta_ac);
6333                                 if (ret) {
6334                                         mlog_errno(ret);
6335                                         goto out;
6336                                 }
6337                         }
6338
6339                         ret = ocfs2_increase_refcount(handle, args->ref_ci,
6340                                                       args->ref_root_bh,
6341                                                       p_cluster, num_clusters,
6342                                                       meta_ac, args->dealloc);
6343                         if (ret) {
6344                                 mlog_errno(ret);
6345                                 goto out;
6346                         }
6347
6348                         cpos += num_clusters;
6349                 }
6350         }
6351
6352 out:
6353         return ret;
6354 }
6355
6356 static int ocfs2_reflink_xattr_inline(struct ocfs2_xattr_reflink *args)
6357 {
6358         int ret = 0, credits = 0;
6359         handle_t *handle;
6360         struct ocfs2_super *osb = OCFS2_SB(args->old_inode->i_sb);
6361         struct ocfs2_dinode *di = (struct ocfs2_dinode *)args->old_bh->b_data;
6362         int inline_size = le16_to_cpu(di->i_xattr_inline_size);
6363         int header_off = osb->sb->s_blocksize - inline_size;
6364         struct ocfs2_xattr_header *xh = (struct ocfs2_xattr_header *)
6365                                         (args->old_bh->b_data + header_off);
6366         struct ocfs2_xattr_header *new_xh = (struct ocfs2_xattr_header *)
6367                                         (args->new_bh->b_data + header_off);
6368         struct ocfs2_alloc_context *meta_ac = NULL;
6369         struct ocfs2_inode_info *new_oi;
6370         struct ocfs2_dinode *new_di;
6371         struct ocfs2_xattr_value_buf vb = {
6372                 .vb_bh = args->new_bh,
6373                 .vb_access = ocfs2_journal_access_di,
6374         };
6375
6376         ret = ocfs2_reflink_lock_xattr_allocators(osb, xh, args->ref_root_bh,
6377                                                   &credits, &meta_ac);
6378         if (ret) {
6379                 mlog_errno(ret);
6380                 goto out;
6381         }
6382
6383         handle = ocfs2_start_trans(osb, credits);
6384         if (IS_ERR(handle)) {
6385                 ret = PTR_ERR(handle);
6386                 mlog_errno(ret);
6387                 goto out;
6388         }
6389
6390         ret = ocfs2_journal_access_di(handle, INODE_CACHE(args->new_inode),
6391                                       args->new_bh, OCFS2_JOURNAL_ACCESS_WRITE);
6392         if (ret) {
6393                 mlog_errno(ret);
6394                 goto out_commit;
6395         }
6396
6397         memcpy(args->new_bh->b_data + header_off,
6398                args->old_bh->b_data + header_off, inline_size);
6399
6400         new_di = (struct ocfs2_dinode *)args->new_bh->b_data;
6401         new_di->i_xattr_inline_size = cpu_to_le16(inline_size);
6402
6403         ret = ocfs2_reflink_xattr_header(handle, args, args->old_bh, xh,
6404                                          args->new_bh, new_xh, &vb, meta_ac,
6405                                          ocfs2_get_xattr_value_root, NULL);
6406         if (ret) {
6407                 mlog_errno(ret);
6408                 goto out_commit;
6409         }
6410
6411         new_oi = OCFS2_I(args->new_inode);
6412         spin_lock(&new_oi->ip_lock);
6413         new_oi->ip_dyn_features |= OCFS2_HAS_XATTR_FL | OCFS2_INLINE_XATTR_FL;
6414         new_di->i_dyn_features = cpu_to_le16(new_oi->ip_dyn_features);
6415         spin_unlock(&new_oi->ip_lock);
6416
6417         ocfs2_journal_dirty(handle, args->new_bh);
6418
6419 out_commit:
6420         ocfs2_commit_trans(osb, handle);
6421
6422 out:
6423         if (meta_ac)
6424                 ocfs2_free_alloc_context(meta_ac);
6425         return ret;
6426 }
6427
6428 static int ocfs2_create_empty_xattr_block(struct inode *inode,
6429                                           struct buffer_head *fe_bh,
6430                                           struct buffer_head **ret_bh,
6431                                           int indexed)
6432 {
6433         int ret;
6434         struct ocfs2_alloc_context *meta_ac;
6435         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
6436         struct ocfs2_xattr_set_ctxt ctxt = {
6437                 .meta_ac = meta_ac,
6438         };
6439
6440         ret = ocfs2_reserve_new_metadata_blocks(osb, 1, &meta_ac);
6441         if (ret < 0) {
6442                 mlog_errno(ret);
6443                 return ret;
6444         }
6445
6446         ctxt.handle = ocfs2_start_trans(osb, OCFS2_XATTR_BLOCK_CREATE_CREDITS);
6447         if (IS_ERR(ctxt.handle)) {
6448                 ret = PTR_ERR(ctxt.handle);
6449                 mlog_errno(ret);
6450                 goto out;
6451         }
6452
6453         mlog(0, "create new xattr block for inode %llu, index = %d\n",
6454              (unsigned long long)fe_bh->b_blocknr, indexed);
6455         ret = ocfs2_create_xattr_block(inode, fe_bh, &ctxt, indexed,
6456                                        ret_bh);
6457         if (ret)
6458                 mlog_errno(ret);
6459
6460         ocfs2_commit_trans(osb, ctxt.handle);
6461 out:
6462         ocfs2_free_alloc_context(meta_ac);
6463         return ret;
6464 }
6465
6466 static int ocfs2_reflink_xattr_block(struct ocfs2_xattr_reflink *args,
6467                                      struct buffer_head *blk_bh,
6468                                      struct buffer_head *new_blk_bh)
6469 {
6470         int ret = 0, credits = 0;
6471         handle_t *handle;
6472         struct ocfs2_inode_info *new_oi = OCFS2_I(args->new_inode);
6473         struct ocfs2_dinode *new_di;
6474         struct ocfs2_super *osb = OCFS2_SB(args->new_inode->i_sb);
6475         int header_off = offsetof(struct ocfs2_xattr_block, xb_attrs.xb_header);
6476         struct ocfs2_xattr_block *xb =
6477                         (struct ocfs2_xattr_block *)blk_bh->b_data;
6478         struct ocfs2_xattr_header *xh = &xb->xb_attrs.xb_header;
6479         struct ocfs2_xattr_block *new_xb =
6480                         (struct ocfs2_xattr_block *)new_blk_bh->b_data;
6481         struct ocfs2_xattr_header *new_xh = &new_xb->xb_attrs.xb_header;
6482         struct ocfs2_alloc_context *meta_ac;
6483         struct ocfs2_xattr_value_buf vb = {
6484                 .vb_bh = new_blk_bh,
6485                 .vb_access = ocfs2_journal_access_xb,
6486         };
6487
6488         ret = ocfs2_reflink_lock_xattr_allocators(osb, xh, args->ref_root_bh,
6489                                                   &credits, &meta_ac);
6490         if (ret) {
6491                 mlog_errno(ret);
6492                 return ret;
6493         }
6494
6495         /* One more credits in case we need to add xattr flags in new inode. */
6496         handle = ocfs2_start_trans(osb, credits + 1);
6497         if (IS_ERR(handle)) {
6498                 ret = PTR_ERR(handle);
6499                 mlog_errno(ret);
6500                 goto out;
6501         }
6502
6503         if (!(new_oi->ip_dyn_features & OCFS2_HAS_XATTR_FL)) {
6504                 ret = ocfs2_journal_access_di(handle,
6505                                               INODE_CACHE(args->new_inode),
6506                                               args->new_bh,
6507                                               OCFS2_JOURNAL_ACCESS_WRITE);
6508                 if (ret) {
6509                         mlog_errno(ret);
6510                         goto out_commit;
6511                 }
6512         }
6513
6514         ret = ocfs2_journal_access_xb(handle, INODE_CACHE(args->new_inode),
6515                                       new_blk_bh, OCFS2_JOURNAL_ACCESS_WRITE);
6516         if (ret) {
6517                 mlog_errno(ret);
6518                 goto out_commit;
6519         }
6520
6521         memcpy(new_blk_bh->b_data + header_off, blk_bh->b_data + header_off,
6522                osb->sb->s_blocksize - header_off);
6523
6524         ret = ocfs2_reflink_xattr_header(handle, args, blk_bh, xh,
6525                                          new_blk_bh, new_xh, &vb, meta_ac,
6526                                          ocfs2_get_xattr_value_root, NULL);
6527         if (ret) {
6528                 mlog_errno(ret);
6529                 goto out_commit;
6530         }
6531
6532         ocfs2_journal_dirty(handle, new_blk_bh);
6533
6534         if (!(new_oi->ip_dyn_features & OCFS2_HAS_XATTR_FL)) {
6535                 new_di = (struct ocfs2_dinode *)args->new_bh->b_data;
6536                 spin_lock(&new_oi->ip_lock);
6537                 new_oi->ip_dyn_features |= OCFS2_HAS_XATTR_FL;
6538                 new_di->i_dyn_features = cpu_to_le16(new_oi->ip_dyn_features);
6539                 spin_unlock(&new_oi->ip_lock);
6540
6541                 ocfs2_journal_dirty(handle, args->new_bh);
6542         }
6543
6544 out_commit:
6545         ocfs2_commit_trans(osb, handle);
6546
6547 out:
6548         ocfs2_free_alloc_context(meta_ac);
6549         return ret;
6550 }
6551
6552 struct ocfs2_reflink_xattr_tree_args {
6553         struct ocfs2_xattr_reflink *reflink;
6554         struct buffer_head *old_blk_bh;
6555         struct buffer_head *new_blk_bh;
6556         struct ocfs2_xattr_bucket *old_bucket;
6557         struct ocfs2_xattr_bucket *new_bucket;
6558 };
6559
6560 /*
6561  * NOTE:
6562  * We have to handle the case that both old bucket and new bucket
6563  * will call this function to get the right ret_bh.
6564  * So The caller must give us the right bh.
6565  */
6566 static int ocfs2_get_reflink_xattr_value_root(struct super_block *sb,
6567                                         struct buffer_head *bh,
6568                                         struct ocfs2_xattr_header *xh,
6569                                         int offset,
6570                                         struct ocfs2_xattr_value_root **xv,
6571                                         struct buffer_head **ret_bh,
6572                                         void *para)
6573 {
6574         struct ocfs2_reflink_xattr_tree_args *args =
6575                         (struct ocfs2_reflink_xattr_tree_args *)para;
6576         struct ocfs2_xattr_bucket *bucket;
6577
6578         if (bh == args->old_bucket->bu_bhs[0])
6579                 bucket = args->old_bucket;
6580         else
6581                 bucket = args->new_bucket;
6582
6583         return ocfs2_get_xattr_tree_value_root(sb, bucket, offset,
6584                                                xv, ret_bh);
6585 }
6586
6587 struct ocfs2_value_tree_metas {
6588         int num_metas;
6589         int credits;
6590         int num_recs;
6591 };
6592
6593 static int ocfs2_value_tree_metas_in_bucket(struct super_block *sb,
6594                                         struct buffer_head *bh,
6595                                         struct ocfs2_xattr_header *xh,
6596                                         int offset,
6597                                         struct ocfs2_xattr_value_root **xv,
6598                                         struct buffer_head **ret_bh,
6599                                         void *para)
6600 {
6601         struct ocfs2_xattr_bucket *bucket =
6602                                 (struct ocfs2_xattr_bucket *)para;
6603
6604         return ocfs2_get_xattr_tree_value_root(sb, bucket, offset,
6605                                                xv, ret_bh);
6606 }
6607
6608 static int ocfs2_calc_value_tree_metas(struct inode *inode,
6609                                       struct ocfs2_xattr_bucket *bucket,
6610                                       void *para)
6611 {
6612         struct ocfs2_value_tree_metas *metas =
6613                         (struct ocfs2_value_tree_metas *)para;
6614         struct ocfs2_xattr_header *xh =
6615                         (struct ocfs2_xattr_header *)bucket->bu_bhs[0]->b_data;
6616
6617         /* Add the credits for this bucket first. */
6618         metas->credits += bucket->bu_blocks;
6619         return ocfs2_value_metas_in_xattr_header(inode->i_sb, bucket->bu_bhs[0],
6620                                         xh, &metas->num_metas,
6621                                         &metas->credits, &metas->num_recs,
6622                                         ocfs2_value_tree_metas_in_bucket,
6623                                         bucket);
6624 }
6625
6626 /*
6627  * Given a xattr extent rec starting from blkno and having len clusters,
6628  * iterate all the buckets calculate how much metadata we need for reflinking
6629  * all the ocfs2_xattr_value_root and lock the allocators accordingly.
6630  */
6631 static int ocfs2_lock_reflink_xattr_rec_allocators(
6632                                 struct ocfs2_reflink_xattr_tree_args *args,
6633                                 struct ocfs2_extent_tree *xt_et,
6634                                 u64 blkno, u32 len, int *credits,
6635                                 struct ocfs2_alloc_context **meta_ac,
6636                                 struct ocfs2_alloc_context **data_ac)
6637 {
6638         int ret, num_free_extents;
6639         struct ocfs2_value_tree_metas metas;
6640         struct ocfs2_super *osb = OCFS2_SB(args->reflink->old_inode->i_sb);
6641         struct ocfs2_refcount_block *rb;
6642
6643         memset(&metas, 0, sizeof(metas));
6644
6645         ret = ocfs2_iterate_xattr_buckets(args->reflink->old_inode, blkno, len,
6646                                           ocfs2_calc_value_tree_metas, &metas);
6647         if (ret) {
6648                 mlog_errno(ret);
6649                 goto out;
6650         }
6651
6652         *credits = metas.credits;
6653
6654         /*
6655          * Calculate we need for refcount tree change.
6656          *
6657          * We need to add/modify num_recs in refcount tree, so just calculate
6658          * an approximate number we need for refcount tree change.
6659          * Sometimes we need to split the tree, and after split,  half recs
6660          * will be moved to the new block, and a new block can only provide
6661          * half number of recs. So we multiple new blocks by 2.
6662          * In the end, we have to add credits for modifying the already
6663          * existed refcount block.
6664          */
6665         rb = (struct ocfs2_refcount_block *)args->reflink->ref_root_bh->b_data;
6666         metas.num_recs =
6667                 (metas.num_recs + ocfs2_refcount_recs_per_rb(osb->sb) - 1) /
6668                  ocfs2_refcount_recs_per_rb(osb->sb) * 2;
6669         metas.num_metas += metas.num_recs;
6670         *credits += metas.num_recs +
6671                     metas.num_recs * OCFS2_EXPAND_REFCOUNT_TREE_CREDITS;
6672         if (le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL)
6673                 *credits += le16_to_cpu(rb->rf_list.l_tree_depth) *
6674                             le16_to_cpu(rb->rf_list.l_next_free_rec) + 1;
6675         else
6676                 *credits += 1;
6677
6678         /* count in the xattr tree change. */
6679         num_free_extents = ocfs2_num_free_extents(osb, xt_et);
6680         if (num_free_extents < 0) {
6681                 ret = num_free_extents;
6682                 mlog_errno(ret);
6683                 goto out;
6684         }
6685
6686         if (num_free_extents < len)
6687                 metas.num_metas += ocfs2_extend_meta_needed(xt_et->et_root_el);
6688
6689         *credits += ocfs2_calc_extend_credits(osb->sb,
6690                                               xt_et->et_root_el, len);
6691
6692         if (metas.num_metas) {
6693                 ret = ocfs2_reserve_new_metadata_blocks(osb, metas.num_metas,
6694                                                         meta_ac);
6695                 if (ret) {
6696                         mlog_errno(ret);
6697                         goto out;
6698                 }
6699         }
6700
6701         if (len) {
6702                 ret = ocfs2_reserve_clusters(osb, len, data_ac);
6703                 if (ret)
6704                         mlog_errno(ret);
6705         }
6706 out:
6707         if (ret) {
6708                 if (*meta_ac) {
6709                         ocfs2_free_alloc_context(*meta_ac);
6710                         meta_ac = NULL;
6711                 }
6712         }
6713
6714         return ret;
6715 }
6716
6717 static int ocfs2_reflink_xattr_buckets(handle_t *handle,
6718                                 u64 blkno, u64 new_blkno, u32 clusters,
6719                                 struct ocfs2_alloc_context *meta_ac,
6720                                 struct ocfs2_alloc_context *data_ac,
6721                                 struct ocfs2_reflink_xattr_tree_args *args)
6722 {
6723         int i, j, ret = 0;
6724         struct super_block *sb = args->reflink->old_inode->i_sb;
6725         u32 bpc = ocfs2_xattr_buckets_per_cluster(OCFS2_SB(sb));
6726         u32 num_buckets = clusters * bpc;
6727         int bpb = args->old_bucket->bu_blocks;
6728         struct ocfs2_xattr_value_buf vb = {
6729                 .vb_access = ocfs2_journal_access,
6730         };
6731
6732         for (i = 0; i < num_buckets; i++, blkno += bpb, new_blkno += bpb) {
6733                 ret = ocfs2_read_xattr_bucket(args->old_bucket, blkno);
6734                 if (ret) {
6735                         mlog_errno(ret);
6736                         break;
6737                 }
6738
6739                 ret = ocfs2_init_xattr_bucket(args->new_bucket, new_blkno);
6740                 if (ret) {
6741                         mlog_errno(ret);
6742                         break;
6743                 }
6744
6745                 /*
6746                  * The real bucket num in this series of blocks is stored
6747                  * in the 1st bucket.
6748                  */
6749                 if (i == 0)
6750                         num_buckets = le16_to_cpu(
6751                                 bucket_xh(args->old_bucket)->xh_num_buckets);
6752
6753                 ret = ocfs2_xattr_bucket_journal_access(handle,
6754                                                 args->new_bucket,
6755                                                 OCFS2_JOURNAL_ACCESS_CREATE);
6756                 if (ret) {
6757                         mlog_errno(ret);
6758                         break;
6759                 }
6760
6761                 for (j = 0; j < bpb; j++)
6762                         memcpy(bucket_block(args->new_bucket, j),
6763                                bucket_block(args->old_bucket, j),
6764                                sb->s_blocksize);
6765
6766                 ocfs2_xattr_bucket_journal_dirty(handle, args->new_bucket);
6767
6768                 ret = ocfs2_reflink_xattr_header(handle, args->reflink,
6769                                         args->old_bucket->bu_bhs[0],
6770                                         bucket_xh(args->old_bucket),
6771                                         args->new_bucket->bu_bhs[0],
6772                                         bucket_xh(args->new_bucket),
6773                                         &vb, meta_ac,
6774                                         ocfs2_get_reflink_xattr_value_root,
6775                                         args);
6776                 if (ret) {
6777                         mlog_errno(ret);
6778                         break;
6779                 }
6780
6781                 /*
6782                  * Re-access and dirty the bucket to calculate metaecc.
6783                  * Because we may extend the transaction in reflink_xattr_header
6784                  * which will let the already accessed block gone.
6785                  */
6786                 ret = ocfs2_xattr_bucket_journal_access(handle,
6787                                                 args->new_bucket,
6788                                                 OCFS2_JOURNAL_ACCESS_WRITE);
6789                 if (ret) {
6790                         mlog_errno(ret);
6791                         break;
6792                 }
6793
6794                 ocfs2_xattr_bucket_journal_dirty(handle, args->new_bucket);
6795                 ocfs2_xattr_bucket_relse(args->old_bucket);
6796                 ocfs2_xattr_bucket_relse(args->new_bucket);
6797         }
6798
6799         ocfs2_xattr_bucket_relse(args->old_bucket);
6800         ocfs2_xattr_bucket_relse(args->new_bucket);
6801         return ret;
6802 }
6803 /*
6804  * Create the same xattr extent record in the new inode's xattr tree.
6805  */
6806 static int ocfs2_reflink_xattr_rec(struct inode *inode,
6807                                    struct buffer_head *root_bh,
6808                                    u64 blkno,
6809                                    u32 cpos,
6810                                    u32 len,
6811                                    void *para)
6812 {
6813         int ret, credits = 0;
6814         u32 p_cluster, num_clusters;
6815         u64 new_blkno;
6816         handle_t *handle;
6817         struct ocfs2_reflink_xattr_tree_args *args =
6818                         (struct ocfs2_reflink_xattr_tree_args *)para;
6819         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
6820         struct ocfs2_alloc_context *meta_ac = NULL;
6821         struct ocfs2_alloc_context *data_ac = NULL;
6822         struct ocfs2_extent_tree et;
6823
6824         ocfs2_init_xattr_tree_extent_tree(&et,
6825                                           INODE_CACHE(args->reflink->new_inode),
6826                                           args->new_blk_bh);
6827
6828         ret = ocfs2_lock_reflink_xattr_rec_allocators(args, &et, blkno,
6829                                                       len, &credits,
6830                                                       &meta_ac, &data_ac);
6831         if (ret) {
6832                 mlog_errno(ret);
6833                 goto out;
6834         }
6835
6836         handle = ocfs2_start_trans(osb, credits);
6837         if (IS_ERR(handle)) {
6838                 ret = PTR_ERR(handle);
6839                 mlog_errno(ret);
6840                 goto out;
6841         }
6842
6843         ret = ocfs2_claim_clusters(osb, handle, data_ac,
6844                                    len, &p_cluster, &num_clusters);
6845         if (ret) {
6846                 mlog_errno(ret);
6847                 goto out_commit;
6848         }
6849
6850         new_blkno = ocfs2_clusters_to_blocks(osb->sb, p_cluster);
6851
6852         mlog(0, "reflink xattr buckets %llu to %llu, len %u\n",
6853              (unsigned long long)blkno, (unsigned long long)new_blkno, len);
6854         ret = ocfs2_reflink_xattr_buckets(handle, blkno, new_blkno, len,
6855                                           meta_ac, data_ac, args);
6856         if (ret) {
6857                 mlog_errno(ret);
6858                 goto out_commit;
6859         }
6860
6861         mlog(0, "insert new xattr extent rec start %llu len %u to %u\n",
6862              (unsigned long long)new_blkno, len, cpos);
6863         ret = ocfs2_insert_extent(handle, &et, cpos, new_blkno,
6864                                   len, 0, meta_ac);
6865         if (ret)
6866                 mlog_errno(ret);
6867
6868 out_commit:
6869         ocfs2_commit_trans(osb, handle);
6870
6871 out:
6872         if (meta_ac)
6873                 ocfs2_free_alloc_context(meta_ac);
6874         if (data_ac)
6875                 ocfs2_free_alloc_context(data_ac);
6876         return ret;
6877 }
6878
6879 /*
6880  * Create reflinked xattr buckets.
6881  * We will add bucket one by one, and refcount all the xattrs in the bucket
6882  * if they are stored outside.
6883  */
6884 static int ocfs2_reflink_xattr_tree(struct ocfs2_xattr_reflink *args,
6885                                     struct buffer_head *blk_bh,
6886                                     struct buffer_head *new_blk_bh)
6887 {
6888         int ret;
6889         struct ocfs2_reflink_xattr_tree_args para;
6890
6891         memset(&para, 0, sizeof(para));
6892         para.reflink = args;
6893         para.old_blk_bh = blk_bh;
6894         para.new_blk_bh = new_blk_bh;
6895
6896         para.old_bucket = ocfs2_xattr_bucket_new(args->old_inode);
6897         if (!para.old_bucket) {
6898                 mlog_errno(-ENOMEM);
6899                 return -ENOMEM;
6900         }
6901
6902         para.new_bucket = ocfs2_xattr_bucket_new(args->new_inode);
6903         if (!para.new_bucket) {
6904                 ret = -ENOMEM;
6905                 mlog_errno(ret);
6906                 goto out;
6907         }
6908
6909         ret = ocfs2_iterate_xattr_index_block(args->old_inode, blk_bh,
6910                                               ocfs2_reflink_xattr_rec,
6911                                               &para);
6912         if (ret)
6913                 mlog_errno(ret);
6914
6915 out:
6916         ocfs2_xattr_bucket_free(para.old_bucket);
6917         ocfs2_xattr_bucket_free(para.new_bucket);
6918         return ret;
6919 }
6920
6921 static int ocfs2_reflink_xattr_in_block(struct ocfs2_xattr_reflink *args,
6922                                         struct buffer_head *blk_bh)
6923 {
6924         int ret, indexed = 0;
6925         struct buffer_head *new_blk_bh = NULL;
6926         struct ocfs2_xattr_block *xb =
6927                         (struct ocfs2_xattr_block *)blk_bh->b_data;
6928
6929
6930         if (le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED)
6931                 indexed = 1;
6932
6933         ret = ocfs2_create_empty_xattr_block(args->new_inode, args->new_bh,
6934                                              &new_blk_bh, indexed);
6935         if (ret) {
6936                 mlog_errno(ret);
6937                 goto out;
6938         }
6939
6940         if (!(le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED))
6941                 ret = ocfs2_reflink_xattr_block(args, blk_bh, new_blk_bh);
6942         else
6943                 ret = ocfs2_reflink_xattr_tree(args, blk_bh, new_blk_bh);
6944         if (ret)
6945                 mlog_errno(ret);
6946
6947 out:
6948         brelse(new_blk_bh);
6949         return ret;
6950 }
6951
6952 static int ocfs2_reflink_xattr_no_security(struct ocfs2_xattr_entry *xe)
6953 {
6954         int type = ocfs2_xattr_get_type(xe);
6955
6956         return type != OCFS2_XATTR_INDEX_SECURITY &&
6957                type != OCFS2_XATTR_INDEX_POSIX_ACL_ACCESS &&
6958                type != OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT;
6959 }
6960
6961 int ocfs2_reflink_xattrs(struct inode *old_inode,
6962                          struct buffer_head *old_bh,
6963                          struct inode *new_inode,
6964                          struct buffer_head *new_bh,
6965                          bool preserve_security)
6966 {
6967         int ret;
6968         struct ocfs2_xattr_reflink args;
6969         struct ocfs2_inode_info *oi = OCFS2_I(old_inode);
6970         struct ocfs2_dinode *di = (struct ocfs2_dinode *)old_bh->b_data;
6971         struct buffer_head *blk_bh = NULL;
6972         struct ocfs2_cached_dealloc_ctxt dealloc;
6973         struct ocfs2_refcount_tree *ref_tree;
6974         struct buffer_head *ref_root_bh = NULL;
6975
6976         ret = ocfs2_lock_refcount_tree(OCFS2_SB(old_inode->i_sb),
6977                                        le64_to_cpu(di->i_refcount_loc),
6978                                        1, &ref_tree, &ref_root_bh);
6979         if (ret) {
6980                 mlog_errno(ret);
6981                 goto out;
6982         }
6983
6984         ocfs2_init_dealloc_ctxt(&dealloc);
6985
6986         args.old_inode = old_inode;
6987         args.new_inode = new_inode;
6988         args.old_bh = old_bh;
6989         args.new_bh = new_bh;
6990         args.ref_ci = &ref_tree->rf_ci;
6991         args.ref_root_bh = ref_root_bh;
6992         args.dealloc = &dealloc;
6993         if (preserve_security)
6994                 args.xattr_reflinked = NULL;
6995         else
6996                 args.xattr_reflinked = ocfs2_reflink_xattr_no_security;
6997
6998         if (oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL) {
6999                 ret = ocfs2_reflink_xattr_inline(&args);
7000                 if (ret) {
7001                         mlog_errno(ret);
7002                         goto out_unlock;
7003                 }
7004         }
7005
7006         if (!di->i_xattr_loc)
7007                 goto out_unlock;
7008
7009         ret = ocfs2_read_xattr_block(old_inode, le64_to_cpu(di->i_xattr_loc),
7010                                      &blk_bh);
7011         if (ret < 0) {
7012                 mlog_errno(ret);
7013                 goto out_unlock;
7014         }
7015
7016         ret = ocfs2_reflink_xattr_in_block(&args, blk_bh);
7017         if (ret)
7018                 mlog_errno(ret);
7019
7020         brelse(blk_bh);
7021
7022 out_unlock:
7023         ocfs2_unlock_refcount_tree(OCFS2_SB(old_inode->i_sb),
7024                                    ref_tree, 1);
7025         brelse(ref_root_bh);
7026
7027         if (ocfs2_dealloc_has_cluster(&dealloc)) {
7028                 ocfs2_schedule_truncate_log_flush(OCFS2_SB(old_inode->i_sb), 1);
7029                 ocfs2_run_deallocs(OCFS2_SB(old_inode->i_sb), &dealloc);
7030         }
7031
7032 out:
7033         return ret;
7034 }
7035
7036 /*
7037  * Initialize security and acl for a already created inode.
7038  * Used for reflink a non-preserve-security file.
7039  *
7040  * It uses common api like ocfs2_xattr_set, so the caller
7041  * must not hold any lock expect i_mutex.
7042  */
7043 int ocfs2_init_security_and_acl(struct inode *dir,
7044                                 struct inode *inode)
7045 {
7046         int ret = 0;
7047         struct buffer_head *dir_bh = NULL;
7048         struct ocfs2_security_xattr_info si = {
7049                 .enable = 1,
7050         };
7051
7052         ret = ocfs2_init_security_get(inode, dir, &si);
7053         if (!ret) {
7054                 ret = ocfs2_xattr_set(inode, OCFS2_XATTR_INDEX_SECURITY,
7055                                       si.name, si.value, si.value_len,
7056                                       XATTR_CREATE);
7057                 if (ret) {
7058                         mlog_errno(ret);
7059                         goto leave;
7060                 }
7061         } else if (ret != -EOPNOTSUPP) {
7062                 mlog_errno(ret);
7063                 goto leave;
7064         }
7065
7066         ret = ocfs2_inode_lock(dir, &dir_bh, 0);
7067         if (ret) {
7068                 mlog_errno(ret);
7069                 goto leave;
7070         }
7071
7072         ret = ocfs2_init_acl(NULL, inode, dir, NULL, dir_bh, NULL, NULL);
7073         if (ret)
7074                 mlog_errno(ret);
7075
7076         ocfs2_inode_unlock(dir, 0);
7077         brelse(dir_bh);
7078 leave:
7079         return ret;
7080 }
7081 /*
7082  * 'security' attributes support
7083  */
7084 static size_t ocfs2_xattr_security_list(struct dentry *dentry, char *list,
7085                                         size_t list_size, const char *name,
7086                                         size_t name_len, int type)
7087 {
7088         const size_t prefix_len = XATTR_SECURITY_PREFIX_LEN;
7089         const size_t total_len = prefix_len + name_len + 1;
7090
7091         if (list && total_len <= list_size) {
7092                 memcpy(list, XATTR_SECURITY_PREFIX, prefix_len);
7093                 memcpy(list + prefix_len, name, name_len);
7094                 list[prefix_len + name_len] = '\0';
7095         }
7096         return total_len;
7097 }
7098
7099 static int ocfs2_xattr_security_get(struct dentry *dentry, const char *name,
7100                                     void *buffer, size_t size, int type)
7101 {
7102         if (strcmp(name, "") == 0)
7103                 return -EINVAL;
7104         return ocfs2_xattr_get(dentry->d_inode, OCFS2_XATTR_INDEX_SECURITY,
7105                                name, buffer, size);
7106 }
7107
7108 static int ocfs2_xattr_security_set(struct dentry *dentry, const char *name,
7109                 const void *value, size_t size, int flags, int type)
7110 {
7111         if (strcmp(name, "") == 0)
7112                 return -EINVAL;
7113
7114         return ocfs2_xattr_set(dentry->d_inode, OCFS2_XATTR_INDEX_SECURITY,
7115                                name, value, size, flags);
7116 }
7117
7118 int ocfs2_init_security_get(struct inode *inode,
7119                             struct inode *dir,
7120                             struct ocfs2_security_xattr_info *si)
7121 {
7122         /* check whether ocfs2 support feature xattr */
7123         if (!ocfs2_supports_xattr(OCFS2_SB(dir->i_sb)))
7124                 return -EOPNOTSUPP;
7125         return security_inode_init_security(inode, dir, &si->name, &si->value,
7126                                             &si->value_len);
7127 }
7128
7129 int ocfs2_init_security_set(handle_t *handle,
7130                             struct inode *inode,
7131                             struct buffer_head *di_bh,
7132                             struct ocfs2_security_xattr_info *si,
7133                             struct ocfs2_alloc_context *xattr_ac,
7134                             struct ocfs2_alloc_context *data_ac)
7135 {
7136         return ocfs2_xattr_set_handle(handle, inode, di_bh,
7137                                      OCFS2_XATTR_INDEX_SECURITY,
7138                                      si->name, si->value, si->value_len, 0,
7139                                      xattr_ac, data_ac);
7140 }
7141
7142 struct xattr_handler ocfs2_xattr_security_handler = {
7143         .prefix = XATTR_SECURITY_PREFIX,
7144         .list   = ocfs2_xattr_security_list,
7145         .get    = ocfs2_xattr_security_get,
7146         .set    = ocfs2_xattr_security_set,
7147 };
7148
7149 /*
7150  * 'trusted' attributes support
7151  */
7152 static size_t ocfs2_xattr_trusted_list(struct dentry *dentry, char *list,
7153                                        size_t list_size, const char *name,
7154                                        size_t name_len, int type)
7155 {
7156         const size_t prefix_len = XATTR_TRUSTED_PREFIX_LEN;
7157         const size_t total_len = prefix_len + name_len + 1;
7158
7159         if (list && total_len <= list_size) {
7160                 memcpy(list, XATTR_TRUSTED_PREFIX, prefix_len);
7161                 memcpy(list + prefix_len, name, name_len);
7162                 list[prefix_len + name_len] = '\0';
7163         }
7164         return total_len;
7165 }
7166
7167 static int ocfs2_xattr_trusted_get(struct dentry *dentry, const char *name,
7168                 void *buffer, size_t size, int type)
7169 {
7170         if (strcmp(name, "") == 0)
7171                 return -EINVAL;
7172         return ocfs2_xattr_get(dentry->d_inode, OCFS2_XATTR_INDEX_TRUSTED,
7173                                name, buffer, size);
7174 }
7175
7176 static int ocfs2_xattr_trusted_set(struct dentry *dentry, const char *name,
7177                 const void *value, size_t size, int flags, int type)
7178 {
7179         if (strcmp(name, "") == 0)
7180                 return -EINVAL;
7181
7182         return ocfs2_xattr_set(dentry->d_inode, OCFS2_XATTR_INDEX_TRUSTED,
7183                                name, value, size, flags);
7184 }
7185
7186 struct xattr_handler ocfs2_xattr_trusted_handler = {
7187         .prefix = XATTR_TRUSTED_PREFIX,
7188         .list   = ocfs2_xattr_trusted_list,
7189         .get    = ocfs2_xattr_trusted_get,
7190         .set    = ocfs2_xattr_trusted_set,
7191 };
7192
7193 /*
7194  * 'user' attributes support
7195  */
7196 static size_t ocfs2_xattr_user_list(struct dentry *dentry, char *list,
7197                                     size_t list_size, const char *name,
7198                                     size_t name_len, int type)
7199 {
7200         const size_t prefix_len = XATTR_USER_PREFIX_LEN;
7201         const size_t total_len = prefix_len + name_len + 1;
7202         struct ocfs2_super *osb = OCFS2_SB(dentry->d_sb);
7203
7204         if (osb->s_mount_opt & OCFS2_MOUNT_NOUSERXATTR)
7205                 return 0;
7206
7207         if (list && total_len <= list_size) {
7208                 memcpy(list, XATTR_USER_PREFIX, prefix_len);
7209                 memcpy(list + prefix_len, name, name_len);
7210                 list[prefix_len + name_len] = '\0';
7211         }
7212         return total_len;
7213 }
7214
7215 static int ocfs2_xattr_user_get(struct dentry *dentry, const char *name,
7216                 void *buffer, size_t size, int type)
7217 {
7218         struct ocfs2_super *osb = OCFS2_SB(dentry->d_sb);
7219
7220         if (strcmp(name, "") == 0)
7221                 return -EINVAL;
7222         if (osb->s_mount_opt & OCFS2_MOUNT_NOUSERXATTR)
7223                 return -EOPNOTSUPP;
7224         return ocfs2_xattr_get(dentry->d_inode, OCFS2_XATTR_INDEX_USER, name,
7225                                buffer, size);
7226 }
7227
7228 static int ocfs2_xattr_user_set(struct dentry *dentry, const char *name,
7229                 const void *value, size_t size, int flags, int type)
7230 {
7231         struct ocfs2_super *osb = OCFS2_SB(dentry->d_sb);
7232
7233         if (strcmp(name, "") == 0)
7234                 return -EINVAL;
7235         if (osb->s_mount_opt & OCFS2_MOUNT_NOUSERXATTR)
7236                 return -EOPNOTSUPP;
7237
7238         return ocfs2_xattr_set(dentry->d_inode, OCFS2_XATTR_INDEX_USER,
7239                                name, value, size, flags);
7240 }
7241
7242 struct xattr_handler ocfs2_xattr_user_handler = {
7243         .prefix = XATTR_USER_PREFIX,
7244         .list   = ocfs2_xattr_user_list,
7245         .get    = ocfs2_xattr_user_get,
7246         .set    = ocfs2_xattr_user_set,
7247 };