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