sanitize xattr handler prototypes
[linux-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 #ifdef CONFIG_OCFS2_FS_POSIX_ACL
102         &ocfs2_xattr_acl_access_handler,
103         &ocfs2_xattr_acl_default_handler,
104 #endif
105         &ocfs2_xattr_trusted_handler,
106         &ocfs2_xattr_security_handler,
107         NULL
108 };
109
110 static struct xattr_handler *ocfs2_xattr_handler_map[OCFS2_XATTR_MAX] = {
111         [OCFS2_XATTR_INDEX_USER]        = &ocfs2_xattr_user_handler,
112 #ifdef CONFIG_OCFS2_FS_POSIX_ACL
113         [OCFS2_XATTR_INDEX_POSIX_ACL_ACCESS]
114                                         = &ocfs2_xattr_acl_access_handler,
115         [OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT]
116                                         = &ocfs2_xattr_acl_default_handler,
117 #endif
118         [OCFS2_XATTR_INDEX_TRUSTED]     = &ocfs2_xattr_trusted_handler,
119         [OCFS2_XATTR_INDEX_SECURITY]    = &ocfs2_xattr_security_handler,
120 };
121
122 struct ocfs2_xattr_info {
123         int name_index;
124         const char *name;
125         const void *value;
126         size_t value_len;
127 };
128
129 struct ocfs2_xattr_search {
130         struct buffer_head *inode_bh;
131         /*
132          * xattr_bh point to the block buffer head which has extended attribute
133          * when extended attribute in inode, xattr_bh is equal to inode_bh.
134          */
135         struct buffer_head *xattr_bh;
136         struct ocfs2_xattr_header *header;
137         struct ocfs2_xattr_bucket *bucket;
138         void *base;
139         void *end;
140         struct ocfs2_xattr_entry *here;
141         int not_found;
142 };
143
144 static int ocfs2_xattr_bucket_get_name_value(struct super_block *sb,
145                                              struct ocfs2_xattr_header *xh,
146                                              int index,
147                                              int *block_off,
148                                              int *new_offset);
149
150 static int ocfs2_xattr_block_find(struct inode *inode,
151                                   int name_index,
152                                   const char *name,
153                                   struct ocfs2_xattr_search *xs);
154 static int ocfs2_xattr_index_block_find(struct inode *inode,
155                                         struct buffer_head *root_bh,
156                                         int name_index,
157                                         const char *name,
158                                         struct ocfs2_xattr_search *xs);
159
160 static int ocfs2_xattr_tree_list_index_block(struct inode *inode,
161                                         struct buffer_head *blk_bh,
162                                         char *buffer,
163                                         size_t buffer_size);
164
165 static int ocfs2_xattr_create_index_block(struct inode *inode,
166                                           struct ocfs2_xattr_search *xs,
167                                           struct ocfs2_xattr_set_ctxt *ctxt);
168
169 static int ocfs2_xattr_set_entry_index_block(struct inode *inode,
170                                              struct ocfs2_xattr_info *xi,
171                                              struct ocfs2_xattr_search *xs,
172                                              struct ocfs2_xattr_set_ctxt *ctxt);
173
174 typedef int (xattr_tree_rec_func)(struct inode *inode,
175                                   struct buffer_head *root_bh,
176                                   u64 blkno, u32 cpos, u32 len, void *para);
177 static int ocfs2_iterate_xattr_index_block(struct inode *inode,
178                                            struct buffer_head *root_bh,
179                                            xattr_tree_rec_func *rec_func,
180                                            void *para);
181 static int ocfs2_delete_xattr_in_bucket(struct inode *inode,
182                                         struct ocfs2_xattr_bucket *bucket,
183                                         void *para);
184 static int ocfs2_rm_xattr_cluster(struct inode *inode,
185                                   struct buffer_head *root_bh,
186                                   u64 blkno,
187                                   u32 cpos,
188                                   u32 len,
189                                   void *para);
190
191 static int ocfs2_mv_xattr_buckets(struct inode *inode, handle_t *handle,
192                                   u64 src_blk, u64 last_blk, u64 to_blk,
193                                   unsigned int start_bucket,
194                                   u32 *first_hash);
195 static int ocfs2_prepare_refcount_xattr(struct inode *inode,
196                                         struct ocfs2_dinode *di,
197                                         struct ocfs2_xattr_info *xi,
198                                         struct ocfs2_xattr_search *xis,
199                                         struct ocfs2_xattr_search *xbs,
200                                         struct ocfs2_refcount_tree **ref_tree,
201                                         int *meta_need,
202                                         int *credits);
203 static int ocfs2_get_xattr_tree_value_root(struct super_block *sb,
204                                            struct ocfs2_xattr_bucket *bucket,
205                                            int offset,
206                                            struct ocfs2_xattr_value_root **xv,
207                                            struct buffer_head **bh);
208
209 static inline u16 ocfs2_xattr_buckets_per_cluster(struct ocfs2_super *osb)
210 {
211         return (1 << osb->s_clustersize_bits) / OCFS2_XATTR_BUCKET_SIZE;
212 }
213
214 static inline u16 ocfs2_blocks_per_xattr_bucket(struct super_block *sb)
215 {
216         return OCFS2_XATTR_BUCKET_SIZE / (1 << sb->s_blocksize_bits);
217 }
218
219 static inline u16 ocfs2_xattr_max_xe_in_bucket(struct super_block *sb)
220 {
221         u16 len = sb->s_blocksize -
222                  offsetof(struct ocfs2_xattr_header, xh_entries);
223
224         return len / sizeof(struct ocfs2_xattr_entry);
225 }
226
227 #define bucket_blkno(_b) ((_b)->bu_bhs[0]->b_blocknr)
228 #define bucket_block(_b, _n) ((_b)->bu_bhs[(_n)]->b_data)
229 #define bucket_xh(_b) ((struct ocfs2_xattr_header *)bucket_block((_b), 0))
230
231 static struct ocfs2_xattr_bucket *ocfs2_xattr_bucket_new(struct inode *inode)
232 {
233         struct ocfs2_xattr_bucket *bucket;
234         int blks = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
235
236         BUG_ON(blks > OCFS2_XATTR_MAX_BLOCKS_PER_BUCKET);
237
238         bucket = kzalloc(sizeof(struct ocfs2_xattr_bucket), GFP_NOFS);
239         if (bucket) {
240                 bucket->bu_inode = inode;
241                 bucket->bu_blocks = blks;
242         }
243
244         return bucket;
245 }
246
247 static void ocfs2_xattr_bucket_relse(struct ocfs2_xattr_bucket *bucket)
248 {
249         int i;
250
251         for (i = 0; i < bucket->bu_blocks; i++) {
252                 brelse(bucket->bu_bhs[i]);
253                 bucket->bu_bhs[i] = NULL;
254         }
255 }
256
257 static void ocfs2_xattr_bucket_free(struct ocfs2_xattr_bucket *bucket)
258 {
259         if (bucket) {
260                 ocfs2_xattr_bucket_relse(bucket);
261                 bucket->bu_inode = NULL;
262                 kfree(bucket);
263         }
264 }
265
266 /*
267  * A bucket that has never been written to disk doesn't need to be
268  * read.  We just need the buffer_heads.  Don't call this for
269  * buckets that are already on disk.  ocfs2_read_xattr_bucket() initializes
270  * them fully.
271  */
272 static int ocfs2_init_xattr_bucket(struct ocfs2_xattr_bucket *bucket,
273                                    u64 xb_blkno)
274 {
275         int i, rc = 0;
276
277         for (i = 0; i < bucket->bu_blocks; i++) {
278                 bucket->bu_bhs[i] = sb_getblk(bucket->bu_inode->i_sb,
279                                               xb_blkno + i);
280                 if (!bucket->bu_bhs[i]) {
281                         rc = -EIO;
282                         mlog_errno(rc);
283                         break;
284                 }
285
286                 if (!ocfs2_buffer_uptodate(INODE_CACHE(bucket->bu_inode),
287                                            bucket->bu_bhs[i]))
288                         ocfs2_set_new_buffer_uptodate(INODE_CACHE(bucket->bu_inode),
289                                                       bucket->bu_bhs[i]);
290         }
291
292         if (rc)
293                 ocfs2_xattr_bucket_relse(bucket);
294         return rc;
295 }
296
297 /* Read the xattr bucket at xb_blkno */
298 static int ocfs2_read_xattr_bucket(struct ocfs2_xattr_bucket *bucket,
299                                    u64 xb_blkno)
300 {
301         int rc;
302
303         rc = ocfs2_read_blocks(INODE_CACHE(bucket->bu_inode), xb_blkno,
304                                bucket->bu_blocks, bucket->bu_bhs, 0,
305                                NULL);
306         if (!rc) {
307                 spin_lock(&OCFS2_SB(bucket->bu_inode->i_sb)->osb_xattr_lock);
308                 rc = ocfs2_validate_meta_ecc_bhs(bucket->bu_inode->i_sb,
309                                                  bucket->bu_bhs,
310                                                  bucket->bu_blocks,
311                                                  &bucket_xh(bucket)->xh_check);
312                 spin_unlock(&OCFS2_SB(bucket->bu_inode->i_sb)->osb_xattr_lock);
313                 if (rc)
314                         mlog_errno(rc);
315         }
316
317         if (rc)
318                 ocfs2_xattr_bucket_relse(bucket);
319         return rc;
320 }
321
322 static int ocfs2_xattr_bucket_journal_access(handle_t *handle,
323                                              struct ocfs2_xattr_bucket *bucket,
324                                              int type)
325 {
326         int i, rc = 0;
327
328         for (i = 0; i < bucket->bu_blocks; i++) {
329                 rc = ocfs2_journal_access(handle,
330                                           INODE_CACHE(bucket->bu_inode),
331                                           bucket->bu_bhs[i], type);
332                 if (rc) {
333                         mlog_errno(rc);
334                         break;
335                 }
336         }
337
338         return rc;
339 }
340
341 static void ocfs2_xattr_bucket_journal_dirty(handle_t *handle,
342                                              struct ocfs2_xattr_bucket *bucket)
343 {
344         int i;
345
346         spin_lock(&OCFS2_SB(bucket->bu_inode->i_sb)->osb_xattr_lock);
347         ocfs2_compute_meta_ecc_bhs(bucket->bu_inode->i_sb,
348                                    bucket->bu_bhs, bucket->bu_blocks,
349                                    &bucket_xh(bucket)->xh_check);
350         spin_unlock(&OCFS2_SB(bucket->bu_inode->i_sb)->osb_xattr_lock);
351
352         for (i = 0; i < bucket->bu_blocks; i++)
353                 ocfs2_journal_dirty(handle, bucket->bu_bhs[i]);
354 }
355
356 static void ocfs2_xattr_bucket_copy_data(struct ocfs2_xattr_bucket *dest,
357                                          struct ocfs2_xattr_bucket *src)
358 {
359         int i;
360         int blocksize = src->bu_inode->i_sb->s_blocksize;
361
362         BUG_ON(dest->bu_blocks != src->bu_blocks);
363         BUG_ON(dest->bu_inode != src->bu_inode);
364
365         for (i = 0; i < src->bu_blocks; i++) {
366                 memcpy(bucket_block(dest, i), bucket_block(src, i),
367                        blocksize);
368         }
369 }
370
371 static int ocfs2_validate_xattr_block(struct super_block *sb,
372                                       struct buffer_head *bh)
373 {
374         int rc;
375         struct ocfs2_xattr_block *xb =
376                 (struct ocfs2_xattr_block *)bh->b_data;
377
378         mlog(0, "Validating xattr block %llu\n",
379              (unsigned long long)bh->b_blocknr);
380
381         BUG_ON(!buffer_uptodate(bh));
382
383         /*
384          * If the ecc fails, we return the error but otherwise
385          * leave the filesystem running.  We know any error is
386          * local to this block.
387          */
388         rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &xb->xb_check);
389         if (rc)
390                 return rc;
391
392         /*
393          * Errors after here are fatal
394          */
395
396         if (!OCFS2_IS_VALID_XATTR_BLOCK(xb)) {
397                 ocfs2_error(sb,
398                             "Extended attribute block #%llu has bad "
399                             "signature %.*s",
400                             (unsigned long long)bh->b_blocknr, 7,
401                             xb->xb_signature);
402                 return -EINVAL;
403         }
404
405         if (le64_to_cpu(xb->xb_blkno) != bh->b_blocknr) {
406                 ocfs2_error(sb,
407                             "Extended attribute block #%llu has an "
408                             "invalid xb_blkno of %llu",
409                             (unsigned long long)bh->b_blocknr,
410                             (unsigned long long)le64_to_cpu(xb->xb_blkno));
411                 return -EINVAL;
412         }
413
414         if (le32_to_cpu(xb->xb_fs_generation) != OCFS2_SB(sb)->fs_generation) {
415                 ocfs2_error(sb,
416                             "Extended attribute block #%llu has an invalid "
417                             "xb_fs_generation of #%u",
418                             (unsigned long long)bh->b_blocknr,
419                             le32_to_cpu(xb->xb_fs_generation));
420                 return -EINVAL;
421         }
422
423         return 0;
424 }
425
426 static int ocfs2_read_xattr_block(struct inode *inode, u64 xb_blkno,
427                                   struct buffer_head **bh)
428 {
429         int rc;
430         struct buffer_head *tmp = *bh;
431
432         rc = ocfs2_read_block(INODE_CACHE(inode), xb_blkno, &tmp,
433                               ocfs2_validate_xattr_block);
434
435         /* If ocfs2_read_block() got us a new bh, pass it up. */
436         if (!rc && !*bh)
437                 *bh = tmp;
438
439         return rc;
440 }
441
442 static inline const char *ocfs2_xattr_prefix(int name_index)
443 {
444         struct xattr_handler *handler = NULL;
445
446         if (name_index > 0 && name_index < OCFS2_XATTR_MAX)
447                 handler = ocfs2_xattr_handler_map[name_index];
448
449         return handler ? handler->prefix : NULL;
450 }
451
452 static u32 ocfs2_xattr_name_hash(struct inode *inode,
453                                  const char *name,
454                                  int name_len)
455 {
456         /* Get hash value of uuid from super block */
457         u32 hash = OCFS2_SB(inode->i_sb)->uuid_hash;
458         int i;
459
460         /* hash extended attribute name */
461         for (i = 0; i < name_len; i++) {
462                 hash = (hash << OCFS2_HASH_SHIFT) ^
463                        (hash >> (8*sizeof(hash) - OCFS2_HASH_SHIFT)) ^
464                        *name++;
465         }
466
467         return hash;
468 }
469
470 /*
471  * ocfs2_xattr_hash_entry()
472  *
473  * Compute the hash of an extended attribute.
474  */
475 static void ocfs2_xattr_hash_entry(struct inode *inode,
476                                    struct ocfs2_xattr_header *header,
477                                    struct ocfs2_xattr_entry *entry)
478 {
479         u32 hash = 0;
480         char *name = (char *)header + le16_to_cpu(entry->xe_name_offset);
481
482         hash = ocfs2_xattr_name_hash(inode, name, entry->xe_name_len);
483         entry->xe_name_hash = cpu_to_le32(hash);
484
485         return;
486 }
487
488 static int ocfs2_xattr_entry_real_size(int name_len, size_t value_len)
489 {
490         int size = 0;
491
492         if (value_len <= OCFS2_XATTR_INLINE_SIZE)
493                 size = OCFS2_XATTR_SIZE(name_len) + OCFS2_XATTR_SIZE(value_len);
494         else
495                 size = OCFS2_XATTR_SIZE(name_len) + OCFS2_XATTR_ROOT_SIZE;
496         size += sizeof(struct ocfs2_xattr_entry);
497
498         return size;
499 }
500
501 int ocfs2_calc_security_init(struct inode *dir,
502                              struct ocfs2_security_xattr_info *si,
503                              int *want_clusters,
504                              int *xattr_credits,
505                              struct ocfs2_alloc_context **xattr_ac)
506 {
507         int ret = 0;
508         struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
509         int s_size = ocfs2_xattr_entry_real_size(strlen(si->name),
510                                                  si->value_len);
511
512         /*
513          * The max space of security xattr taken inline is
514          * 256(name) + 80(value) + 16(entry) = 352 bytes,
515          * So reserve one metadata block for it is ok.
516          */
517         if (dir->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE ||
518             s_size > OCFS2_XATTR_FREE_IN_IBODY) {
519                 ret = ocfs2_reserve_new_metadata_blocks(osb, 1, xattr_ac);
520                 if (ret) {
521                         mlog_errno(ret);
522                         return ret;
523                 }
524                 *xattr_credits += OCFS2_XATTR_BLOCK_CREATE_CREDITS;
525         }
526
527         /* reserve clusters for xattr value which will be set in B tree*/
528         if (si->value_len > OCFS2_XATTR_INLINE_SIZE) {
529                 int new_clusters = ocfs2_clusters_for_bytes(dir->i_sb,
530                                                             si->value_len);
531
532                 *xattr_credits += ocfs2_clusters_to_blocks(dir->i_sb,
533                                                            new_clusters);
534                 *want_clusters += new_clusters;
535         }
536         return ret;
537 }
538
539 int ocfs2_calc_xattr_init(struct inode *dir,
540                           struct buffer_head *dir_bh,
541                           int mode,
542                           struct ocfs2_security_xattr_info *si,
543                           int *want_clusters,
544                           int *xattr_credits,
545                           int *want_meta)
546 {
547         int ret = 0;
548         struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
549         int s_size = 0, a_size = 0, acl_len = 0, new_clusters;
550
551         if (si->enable)
552                 s_size = ocfs2_xattr_entry_real_size(strlen(si->name),
553                                                      si->value_len);
554
555         if (osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL) {
556                 acl_len = ocfs2_xattr_get_nolock(dir, dir_bh,
557                                         OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT,
558                                         "", NULL, 0);
559                 if (acl_len > 0) {
560                         a_size = ocfs2_xattr_entry_real_size(0, acl_len);
561                         if (S_ISDIR(mode))
562                                 a_size <<= 1;
563                 } else if (acl_len != 0 && acl_len != -ENODATA) {
564                         mlog_errno(ret);
565                         return ret;
566                 }
567         }
568
569         if (!(s_size + a_size))
570                 return ret;
571
572         /*
573          * The max space of security xattr taken inline is
574          * 256(name) + 80(value) + 16(entry) = 352 bytes,
575          * The max space of acl xattr taken inline is
576          * 80(value) + 16(entry) * 2(if directory) = 192 bytes,
577          * when blocksize = 512, may reserve one more cluser for
578          * xattr bucket, otherwise reserve one metadata block
579          * for them is ok.
580          * If this is a new directory with inline data,
581          * we choose to reserve the entire inline area for
582          * directory contents and force an external xattr block.
583          */
584         if (dir->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE ||
585             (S_ISDIR(mode) && ocfs2_supports_inline_data(osb)) ||
586             (s_size + a_size) > OCFS2_XATTR_FREE_IN_IBODY) {
587                 *want_meta = *want_meta + 1;
588                 *xattr_credits += OCFS2_XATTR_BLOCK_CREATE_CREDITS;
589         }
590
591         if (dir->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE &&
592             (s_size + a_size) > OCFS2_XATTR_FREE_IN_BLOCK(dir)) {
593                 *want_clusters += 1;
594                 *xattr_credits += ocfs2_blocks_per_xattr_bucket(dir->i_sb);
595         }
596
597         /*
598          * reserve credits and clusters for xattrs which has large value
599          * and have to be set outside
600          */
601         if (si->enable && si->value_len > OCFS2_XATTR_INLINE_SIZE) {
602                 new_clusters = ocfs2_clusters_for_bytes(dir->i_sb,
603                                                         si->value_len);
604                 *xattr_credits += ocfs2_clusters_to_blocks(dir->i_sb,
605                                                            new_clusters);
606                 *want_clusters += new_clusters;
607         }
608         if (osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL &&
609             acl_len > OCFS2_XATTR_INLINE_SIZE) {
610                 /* for directory, it has DEFAULT and ACCESS two types of acls */
611                 new_clusters = (S_ISDIR(mode) ? 2 : 1) *
612                                 ocfs2_clusters_for_bytes(dir->i_sb, acl_len);
613                 *xattr_credits += ocfs2_clusters_to_blocks(dir->i_sb,
614                                                            new_clusters);
615                 *want_clusters += new_clusters;
616         }
617
618         return ret;
619 }
620
621 static int ocfs2_xattr_extend_allocation(struct inode *inode,
622                                          u32 clusters_to_add,
623                                          struct ocfs2_xattr_value_buf *vb,
624                                          struct ocfs2_xattr_set_ctxt *ctxt)
625 {
626         int status = 0;
627         handle_t *handle = ctxt->handle;
628         enum ocfs2_alloc_restarted why;
629         u32 prev_clusters, logical_start = le32_to_cpu(vb->vb_xv->xr_clusters);
630         struct ocfs2_extent_tree et;
631
632         mlog(0, "(clusters_to_add for xattr= %u)\n", clusters_to_add);
633
634         ocfs2_init_xattr_value_extent_tree(&et, INODE_CACHE(inode), vb);
635
636         status = vb->vb_access(handle, INODE_CACHE(inode), vb->vb_bh,
637                               OCFS2_JOURNAL_ACCESS_WRITE);
638         if (status < 0) {
639                 mlog_errno(status);
640                 goto leave;
641         }
642
643         prev_clusters = le32_to_cpu(vb->vb_xv->xr_clusters);
644         status = ocfs2_add_clusters_in_btree(handle,
645                                              &et,
646                                              &logical_start,
647                                              clusters_to_add,
648                                              0,
649                                              ctxt->data_ac,
650                                              ctxt->meta_ac,
651                                              &why);
652         if (status < 0) {
653                 mlog_errno(status);
654                 goto leave;
655         }
656
657         status = ocfs2_journal_dirty(handle, vb->vb_bh);
658         if (status < 0) {
659                 mlog_errno(status);
660                 goto leave;
661         }
662
663         clusters_to_add -= le32_to_cpu(vb->vb_xv->xr_clusters) - prev_clusters;
664
665         /*
666          * We should have already allocated enough space before the transaction,
667          * so no need to restart.
668          */
669         BUG_ON(why != RESTART_NONE || clusters_to_add);
670
671 leave:
672
673         return status;
674 }
675
676 static int __ocfs2_remove_xattr_range(struct inode *inode,
677                                       struct ocfs2_xattr_value_buf *vb,
678                                       u32 cpos, u32 phys_cpos, u32 len,
679                                       unsigned int ext_flags,
680                                       struct ocfs2_xattr_set_ctxt *ctxt)
681 {
682         int ret;
683         u64 phys_blkno = ocfs2_clusters_to_blocks(inode->i_sb, phys_cpos);
684         handle_t *handle = ctxt->handle;
685         struct ocfs2_extent_tree et;
686
687         ocfs2_init_xattr_value_extent_tree(&et, INODE_CACHE(inode), vb);
688
689         ret = vb->vb_access(handle, INODE_CACHE(inode), vb->vb_bh,
690                             OCFS2_JOURNAL_ACCESS_WRITE);
691         if (ret) {
692                 mlog_errno(ret);
693                 goto out;
694         }
695
696         ret = ocfs2_remove_extent(handle, &et, cpos, len, ctxt->meta_ac,
697                                   &ctxt->dealloc);
698         if (ret) {
699                 mlog_errno(ret);
700                 goto out;
701         }
702
703         le32_add_cpu(&vb->vb_xv->xr_clusters, -len);
704
705         ret = ocfs2_journal_dirty(handle, vb->vb_bh);
706         if (ret) {
707                 mlog_errno(ret);
708                 goto out;
709         }
710
711         if (ext_flags & OCFS2_EXT_REFCOUNTED)
712                 ret = ocfs2_decrease_refcount(inode, handle,
713                                         ocfs2_blocks_to_clusters(inode->i_sb,
714                                                                  phys_blkno),
715                                         len, ctxt->meta_ac, &ctxt->dealloc, 1);
716         else
717                 ret = ocfs2_cache_cluster_dealloc(&ctxt->dealloc,
718                                                   phys_blkno, len);
719         if (ret)
720                 mlog_errno(ret);
721
722 out:
723         return ret;
724 }
725
726 static int ocfs2_xattr_shrink_size(struct inode *inode,
727                                    u32 old_clusters,
728                                    u32 new_clusters,
729                                    struct ocfs2_xattr_value_buf *vb,
730                                    struct ocfs2_xattr_set_ctxt *ctxt)
731 {
732         int ret = 0;
733         unsigned int ext_flags;
734         u32 trunc_len, cpos, phys_cpos, alloc_size;
735         u64 block;
736
737         if (old_clusters <= new_clusters)
738                 return 0;
739
740         cpos = new_clusters;
741         trunc_len = old_clusters - new_clusters;
742         while (trunc_len) {
743                 ret = ocfs2_xattr_get_clusters(inode, cpos, &phys_cpos,
744                                                &alloc_size,
745                                                &vb->vb_xv->xr_list, &ext_flags);
746                 if (ret) {
747                         mlog_errno(ret);
748                         goto out;
749                 }
750
751                 if (alloc_size > trunc_len)
752                         alloc_size = trunc_len;
753
754                 ret = __ocfs2_remove_xattr_range(inode, vb, cpos,
755                                                  phys_cpos, alloc_size,
756                                                  ext_flags, ctxt);
757                 if (ret) {
758                         mlog_errno(ret);
759                         goto out;
760                 }
761
762                 block = ocfs2_clusters_to_blocks(inode->i_sb, phys_cpos);
763                 ocfs2_remove_xattr_clusters_from_cache(INODE_CACHE(inode),
764                                                        block, alloc_size);
765                 cpos += alloc_size;
766                 trunc_len -= alloc_size;
767         }
768
769 out:
770         return ret;
771 }
772
773 static int ocfs2_xattr_value_truncate(struct inode *inode,
774                                       struct ocfs2_xattr_value_buf *vb,
775                                       int len,
776                                       struct ocfs2_xattr_set_ctxt *ctxt)
777 {
778         int ret;
779         u32 new_clusters = ocfs2_clusters_for_bytes(inode->i_sb, len);
780         u32 old_clusters = le32_to_cpu(vb->vb_xv->xr_clusters);
781
782         if (new_clusters == old_clusters)
783                 return 0;
784
785         if (new_clusters > old_clusters)
786                 ret = ocfs2_xattr_extend_allocation(inode,
787                                                     new_clusters - old_clusters,
788                                                     vb, ctxt);
789         else
790                 ret = ocfs2_xattr_shrink_size(inode,
791                                               old_clusters, new_clusters,
792                                               vb, ctxt);
793
794         return ret;
795 }
796
797 static int ocfs2_xattr_list_entry(char *buffer, size_t size,
798                                   size_t *result, const char *prefix,
799                                   const char *name, int name_len)
800 {
801         char *p = buffer + *result;
802         int prefix_len = strlen(prefix);
803         int total_len = prefix_len + name_len + 1;
804
805         *result += total_len;
806
807         /* we are just looking for how big our buffer needs to be */
808         if (!size)
809                 return 0;
810
811         if (*result > size)
812                 return -ERANGE;
813
814         memcpy(p, prefix, prefix_len);
815         memcpy(p + prefix_len, name, name_len);
816         p[prefix_len + name_len] = '\0';
817
818         return 0;
819 }
820
821 static int ocfs2_xattr_list_entries(struct inode *inode,
822                                     struct ocfs2_xattr_header *header,
823                                     char *buffer, size_t buffer_size)
824 {
825         size_t result = 0;
826         int i, type, ret;
827         const char *prefix, *name;
828
829         for (i = 0 ; i < le16_to_cpu(header->xh_count); i++) {
830                 struct ocfs2_xattr_entry *entry = &header->xh_entries[i];
831                 type = ocfs2_xattr_get_type(entry);
832                 prefix = ocfs2_xattr_prefix(type);
833
834                 if (prefix) {
835                         name = (const char *)header +
836                                 le16_to_cpu(entry->xe_name_offset);
837
838                         ret = ocfs2_xattr_list_entry(buffer, buffer_size,
839                                                      &result, prefix, name,
840                                                      entry->xe_name_len);
841                         if (ret)
842                                 return ret;
843                 }
844         }
845
846         return result;
847 }
848
849 int ocfs2_has_inline_xattr_value_outside(struct inode *inode,
850                                          struct ocfs2_dinode *di)
851 {
852         struct ocfs2_xattr_header *xh;
853         int i;
854
855         xh = (struct ocfs2_xattr_header *)
856                  ((void *)di + inode->i_sb->s_blocksize -
857                  le16_to_cpu(di->i_xattr_inline_size));
858
859         for (i = 0; i < le16_to_cpu(xh->xh_count); i++)
860                 if (!ocfs2_xattr_is_local(&xh->xh_entries[i]))
861                         return 1;
862
863         return 0;
864 }
865
866 static int ocfs2_xattr_ibody_list(struct inode *inode,
867                                   struct ocfs2_dinode *di,
868                                   char *buffer,
869                                   size_t buffer_size)
870 {
871         struct ocfs2_xattr_header *header = NULL;
872         struct ocfs2_inode_info *oi = OCFS2_I(inode);
873         int ret = 0;
874
875         if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL))
876                 return ret;
877
878         header = (struct ocfs2_xattr_header *)
879                  ((void *)di + inode->i_sb->s_blocksize -
880                  le16_to_cpu(di->i_xattr_inline_size));
881
882         ret = ocfs2_xattr_list_entries(inode, header, buffer, buffer_size);
883
884         return ret;
885 }
886
887 static int ocfs2_xattr_block_list(struct inode *inode,
888                                   struct ocfs2_dinode *di,
889                                   char *buffer,
890                                   size_t buffer_size)
891 {
892         struct buffer_head *blk_bh = NULL;
893         struct ocfs2_xattr_block *xb;
894         int ret = 0;
895
896         if (!di->i_xattr_loc)
897                 return ret;
898
899         ret = ocfs2_read_xattr_block(inode, le64_to_cpu(di->i_xattr_loc),
900                                      &blk_bh);
901         if (ret < 0) {
902                 mlog_errno(ret);
903                 return ret;
904         }
905
906         xb = (struct ocfs2_xattr_block *)blk_bh->b_data;
907         if (!(le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED)) {
908                 struct ocfs2_xattr_header *header = &xb->xb_attrs.xb_header;
909                 ret = ocfs2_xattr_list_entries(inode, header,
910                                                buffer, buffer_size);
911         } else
912                 ret = ocfs2_xattr_tree_list_index_block(inode, blk_bh,
913                                                    buffer, buffer_size);
914
915         brelse(blk_bh);
916
917         return ret;
918 }
919
920 ssize_t ocfs2_listxattr(struct dentry *dentry,
921                         char *buffer,
922                         size_t size)
923 {
924         int ret = 0, i_ret = 0, b_ret = 0;
925         struct buffer_head *di_bh = NULL;
926         struct ocfs2_dinode *di = NULL;
927         struct ocfs2_inode_info *oi = OCFS2_I(dentry->d_inode);
928
929         if (!ocfs2_supports_xattr(OCFS2_SB(dentry->d_sb)))
930                 return -EOPNOTSUPP;
931
932         if (!(oi->ip_dyn_features & OCFS2_HAS_XATTR_FL))
933                 return ret;
934
935         ret = ocfs2_inode_lock(dentry->d_inode, &di_bh, 0);
936         if (ret < 0) {
937                 mlog_errno(ret);
938                 return ret;
939         }
940
941         di = (struct ocfs2_dinode *)di_bh->b_data;
942
943         down_read(&oi->ip_xattr_sem);
944         i_ret = ocfs2_xattr_ibody_list(dentry->d_inode, di, buffer, size);
945         if (i_ret < 0)
946                 b_ret = 0;
947         else {
948                 if (buffer) {
949                         buffer += i_ret;
950                         size -= i_ret;
951                 }
952                 b_ret = ocfs2_xattr_block_list(dentry->d_inode, di,
953                                                buffer, size);
954                 if (b_ret < 0)
955                         i_ret = 0;
956         }
957         up_read(&oi->ip_xattr_sem);
958         ocfs2_inode_unlock(dentry->d_inode, 0);
959
960         brelse(di_bh);
961
962         return i_ret + b_ret;
963 }
964
965 static int ocfs2_xattr_find_entry(int name_index,
966                                   const char *name,
967                                   struct ocfs2_xattr_search *xs)
968 {
969         struct ocfs2_xattr_entry *entry;
970         size_t name_len;
971         int i, cmp = 1;
972
973         if (name == NULL)
974                 return -EINVAL;
975
976         name_len = strlen(name);
977         entry = xs->here;
978         for (i = 0; i < le16_to_cpu(xs->header->xh_count); i++) {
979                 cmp = name_index - ocfs2_xattr_get_type(entry);
980                 if (!cmp)
981                         cmp = name_len - entry->xe_name_len;
982                 if (!cmp)
983                         cmp = memcmp(name, (xs->base +
984                                      le16_to_cpu(entry->xe_name_offset)),
985                                      name_len);
986                 if (cmp == 0)
987                         break;
988                 entry += 1;
989         }
990         xs->here = entry;
991
992         return cmp ? -ENODATA : 0;
993 }
994
995 static int ocfs2_xattr_get_value_outside(struct inode *inode,
996                                          struct ocfs2_xattr_value_root *xv,
997                                          void *buffer,
998                                          size_t len)
999 {
1000         u32 cpos, p_cluster, num_clusters, bpc, clusters;
1001         u64 blkno;
1002         int i, ret = 0;
1003         size_t cplen, blocksize;
1004         struct buffer_head *bh = NULL;
1005         struct ocfs2_extent_list *el;
1006
1007         el = &xv->xr_list;
1008         clusters = le32_to_cpu(xv->xr_clusters);
1009         bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
1010         blocksize = inode->i_sb->s_blocksize;
1011
1012         cpos = 0;
1013         while (cpos < clusters) {
1014                 ret = ocfs2_xattr_get_clusters(inode, cpos, &p_cluster,
1015                                                &num_clusters, el, NULL);
1016                 if (ret) {
1017                         mlog_errno(ret);
1018                         goto out;
1019                 }
1020
1021                 blkno = ocfs2_clusters_to_blocks(inode->i_sb, p_cluster);
1022                 /* Copy ocfs2_xattr_value */
1023                 for (i = 0; i < num_clusters * bpc; i++, blkno++) {
1024                         ret = ocfs2_read_block(INODE_CACHE(inode), blkno,
1025                                                &bh, NULL);
1026                         if (ret) {
1027                                 mlog_errno(ret);
1028                                 goto out;
1029                         }
1030
1031                         cplen = len >= blocksize ? blocksize : len;
1032                         memcpy(buffer, bh->b_data, cplen);
1033                         len -= cplen;
1034                         buffer += cplen;
1035
1036                         brelse(bh);
1037                         bh = NULL;
1038                         if (len == 0)
1039                                 break;
1040                 }
1041                 cpos += num_clusters;
1042         }
1043 out:
1044         return ret;
1045 }
1046
1047 static int ocfs2_xattr_ibody_get(struct inode *inode,
1048                                  int name_index,
1049                                  const char *name,
1050                                  void *buffer,
1051                                  size_t buffer_size,
1052                                  struct ocfs2_xattr_search *xs)
1053 {
1054         struct ocfs2_inode_info *oi = OCFS2_I(inode);
1055         struct ocfs2_dinode *di = (struct ocfs2_dinode *)xs->inode_bh->b_data;
1056         struct ocfs2_xattr_value_root *xv;
1057         size_t size;
1058         int ret = 0;
1059
1060         if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL))
1061                 return -ENODATA;
1062
1063         xs->end = (void *)di + inode->i_sb->s_blocksize;
1064         xs->header = (struct ocfs2_xattr_header *)
1065                         (xs->end - le16_to_cpu(di->i_xattr_inline_size));
1066         xs->base = (void *)xs->header;
1067         xs->here = xs->header->xh_entries;
1068
1069         ret = ocfs2_xattr_find_entry(name_index, name, xs);
1070         if (ret)
1071                 return ret;
1072         size = le64_to_cpu(xs->here->xe_value_size);
1073         if (buffer) {
1074                 if (size > buffer_size)
1075                         return -ERANGE;
1076                 if (ocfs2_xattr_is_local(xs->here)) {
1077                         memcpy(buffer, (void *)xs->base +
1078                                le16_to_cpu(xs->here->xe_name_offset) +
1079                                OCFS2_XATTR_SIZE(xs->here->xe_name_len), size);
1080                 } else {
1081                         xv = (struct ocfs2_xattr_value_root *)
1082                                 (xs->base + le16_to_cpu(
1083                                  xs->here->xe_name_offset) +
1084                                 OCFS2_XATTR_SIZE(xs->here->xe_name_len));
1085                         ret = ocfs2_xattr_get_value_outside(inode, xv,
1086                                                             buffer, size);
1087                         if (ret < 0) {
1088                                 mlog_errno(ret);
1089                                 return ret;
1090                         }
1091                 }
1092         }
1093
1094         return size;
1095 }
1096
1097 static int ocfs2_xattr_block_get(struct inode *inode,
1098                                  int name_index,
1099                                  const char *name,
1100                                  void *buffer,
1101                                  size_t buffer_size,
1102                                  struct ocfs2_xattr_search *xs)
1103 {
1104         struct ocfs2_xattr_block *xb;
1105         struct ocfs2_xattr_value_root *xv;
1106         size_t size;
1107         int ret = -ENODATA, name_offset, name_len, i;
1108         int uninitialized_var(block_off);
1109
1110         xs->bucket = ocfs2_xattr_bucket_new(inode);
1111         if (!xs->bucket) {
1112                 ret = -ENOMEM;
1113                 mlog_errno(ret);
1114                 goto cleanup;
1115         }
1116
1117         ret = ocfs2_xattr_block_find(inode, name_index, name, xs);
1118         if (ret) {
1119                 mlog_errno(ret);
1120                 goto cleanup;
1121         }
1122
1123         if (xs->not_found) {
1124                 ret = -ENODATA;
1125                 goto cleanup;
1126         }
1127
1128         xb = (struct ocfs2_xattr_block *)xs->xattr_bh->b_data;
1129         size = le64_to_cpu(xs->here->xe_value_size);
1130         if (buffer) {
1131                 ret = -ERANGE;
1132                 if (size > buffer_size)
1133                         goto cleanup;
1134
1135                 name_offset = le16_to_cpu(xs->here->xe_name_offset);
1136                 name_len = OCFS2_XATTR_SIZE(xs->here->xe_name_len);
1137                 i = xs->here - xs->header->xh_entries;
1138
1139                 if (le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED) {
1140                         ret = ocfs2_xattr_bucket_get_name_value(inode->i_sb,
1141                                                                 bucket_xh(xs->bucket),
1142                                                                 i,
1143                                                                 &block_off,
1144                                                                 &name_offset);
1145                         xs->base = bucket_block(xs->bucket, block_off);
1146                 }
1147                 if (ocfs2_xattr_is_local(xs->here)) {
1148                         memcpy(buffer, (void *)xs->base +
1149                                name_offset + name_len, size);
1150                 } else {
1151                         xv = (struct ocfs2_xattr_value_root *)
1152                                 (xs->base + name_offset + name_len);
1153                         ret = ocfs2_xattr_get_value_outside(inode, xv,
1154                                                             buffer, size);
1155                         if (ret < 0) {
1156                                 mlog_errno(ret);
1157                                 goto cleanup;
1158                         }
1159                 }
1160         }
1161         ret = size;
1162 cleanup:
1163         ocfs2_xattr_bucket_free(xs->bucket);
1164
1165         brelse(xs->xattr_bh);
1166         xs->xattr_bh = NULL;
1167         return ret;
1168 }
1169
1170 int ocfs2_xattr_get_nolock(struct inode *inode,
1171                            struct buffer_head *di_bh,
1172                            int name_index,
1173                            const char *name,
1174                            void *buffer,
1175                            size_t buffer_size)
1176 {
1177         int ret;
1178         struct ocfs2_dinode *di = NULL;
1179         struct ocfs2_inode_info *oi = OCFS2_I(inode);
1180         struct ocfs2_xattr_search xis = {
1181                 .not_found = -ENODATA,
1182         };
1183         struct ocfs2_xattr_search xbs = {
1184                 .not_found = -ENODATA,
1185         };
1186
1187         if (!ocfs2_supports_xattr(OCFS2_SB(inode->i_sb)))
1188                 return -EOPNOTSUPP;
1189
1190         if (!(oi->ip_dyn_features & OCFS2_HAS_XATTR_FL))
1191                 ret = -ENODATA;
1192
1193         xis.inode_bh = xbs.inode_bh = di_bh;
1194         di = (struct ocfs2_dinode *)di_bh->b_data;
1195
1196         down_read(&oi->ip_xattr_sem);
1197         ret = ocfs2_xattr_ibody_get(inode, name_index, name, buffer,
1198                                     buffer_size, &xis);
1199         if (ret == -ENODATA && di->i_xattr_loc)
1200                 ret = ocfs2_xattr_block_get(inode, name_index, name, buffer,
1201                                             buffer_size, &xbs);
1202         up_read(&oi->ip_xattr_sem);
1203
1204         return ret;
1205 }
1206
1207 /* ocfs2_xattr_get()
1208  *
1209  * Copy an extended attribute into the buffer provided.
1210  * Buffer is NULL to compute the size of buffer required.
1211  */
1212 static int ocfs2_xattr_get(struct inode *inode,
1213                            int name_index,
1214                            const char *name,
1215                            void *buffer,
1216                            size_t buffer_size)
1217 {
1218         int ret;
1219         struct buffer_head *di_bh = NULL;
1220
1221         ret = ocfs2_inode_lock(inode, &di_bh, 0);
1222         if (ret < 0) {
1223                 mlog_errno(ret);
1224                 return ret;
1225         }
1226         ret = ocfs2_xattr_get_nolock(inode, di_bh, name_index,
1227                                      name, buffer, buffer_size);
1228
1229         ocfs2_inode_unlock(inode, 0);
1230
1231         brelse(di_bh);
1232
1233         return ret;
1234 }
1235
1236 static int __ocfs2_xattr_set_value_outside(struct inode *inode,
1237                                            handle_t *handle,
1238                                            struct ocfs2_xattr_value_buf *vb,
1239                                            const void *value,
1240                                            int value_len)
1241 {
1242         int ret = 0, i, cp_len;
1243         u16 blocksize = inode->i_sb->s_blocksize;
1244         u32 p_cluster, num_clusters;
1245         u32 cpos = 0, bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
1246         u32 clusters = ocfs2_clusters_for_bytes(inode->i_sb, value_len);
1247         u64 blkno;
1248         struct buffer_head *bh = NULL;
1249         unsigned int ext_flags;
1250         struct ocfs2_xattr_value_root *xv = vb->vb_xv;
1251
1252         BUG_ON(clusters > le32_to_cpu(xv->xr_clusters));
1253
1254         while (cpos < clusters) {
1255                 ret = ocfs2_xattr_get_clusters(inode, cpos, &p_cluster,
1256                                                &num_clusters, &xv->xr_list,
1257                                                &ext_flags);
1258                 if (ret) {
1259                         mlog_errno(ret);
1260                         goto out;
1261                 }
1262
1263                 BUG_ON(ext_flags & OCFS2_EXT_REFCOUNTED);
1264
1265                 blkno = ocfs2_clusters_to_blocks(inode->i_sb, p_cluster);
1266
1267                 for (i = 0; i < num_clusters * bpc; i++, blkno++) {
1268                         ret = ocfs2_read_block(INODE_CACHE(inode), blkno,
1269                                                &bh, NULL);
1270                         if (ret) {
1271                                 mlog_errno(ret);
1272                                 goto out;
1273                         }
1274
1275                         ret = ocfs2_journal_access(handle,
1276                                                    INODE_CACHE(inode),
1277                                                    bh,
1278                                                    OCFS2_JOURNAL_ACCESS_WRITE);
1279                         if (ret < 0) {
1280                                 mlog_errno(ret);
1281                                 goto out;
1282                         }
1283
1284                         cp_len = value_len > blocksize ? blocksize : value_len;
1285                         memcpy(bh->b_data, value, cp_len);
1286                         value_len -= cp_len;
1287                         value += cp_len;
1288                         if (cp_len < blocksize)
1289                                 memset(bh->b_data + cp_len, 0,
1290                                        blocksize - cp_len);
1291
1292                         ret = ocfs2_journal_dirty(handle, bh);
1293                         if (ret < 0) {
1294                                 mlog_errno(ret);
1295                                 goto out;
1296                         }
1297                         brelse(bh);
1298                         bh = NULL;
1299
1300                         /*
1301                          * XXX: do we need to empty all the following
1302                          * blocks in this cluster?
1303                          */
1304                         if (!value_len)
1305                                 break;
1306                 }
1307                 cpos += num_clusters;
1308         }
1309 out:
1310         brelse(bh);
1311
1312         return ret;
1313 }
1314
1315 static int ocfs2_xattr_cleanup(struct inode *inode,
1316                                handle_t *handle,
1317                                struct ocfs2_xattr_info *xi,
1318                                struct ocfs2_xattr_search *xs,
1319                                struct ocfs2_xattr_value_buf *vb,
1320                                size_t offs)
1321 {
1322         int ret = 0;
1323         size_t name_len = strlen(xi->name);
1324         void *val = xs->base + offs;
1325         size_t size = OCFS2_XATTR_SIZE(name_len) + OCFS2_XATTR_ROOT_SIZE;
1326
1327         ret = vb->vb_access(handle, INODE_CACHE(inode), vb->vb_bh,
1328                             OCFS2_JOURNAL_ACCESS_WRITE);
1329         if (ret) {
1330                 mlog_errno(ret);
1331                 goto out;
1332         }
1333         /* Decrease xattr count */
1334         le16_add_cpu(&xs->header->xh_count, -1);
1335         /* Remove the xattr entry and tree root which has already be set*/
1336         memset((void *)xs->here, 0, sizeof(struct ocfs2_xattr_entry));
1337         memset(val, 0, size);
1338
1339         ret = ocfs2_journal_dirty(handle, vb->vb_bh);
1340         if (ret < 0)
1341                 mlog_errno(ret);
1342 out:
1343         return ret;
1344 }
1345
1346 static int ocfs2_xattr_update_entry(struct inode *inode,
1347                                     handle_t *handle,
1348                                     struct ocfs2_xattr_info *xi,
1349                                     struct ocfs2_xattr_search *xs,
1350                                     struct ocfs2_xattr_value_buf *vb,
1351                                     size_t offs)
1352 {
1353         int ret;
1354
1355         ret = vb->vb_access(handle, INODE_CACHE(inode), vb->vb_bh,
1356                             OCFS2_JOURNAL_ACCESS_WRITE);
1357         if (ret) {
1358                 mlog_errno(ret);
1359                 goto out;
1360         }
1361
1362         xs->here->xe_name_offset = cpu_to_le16(offs);
1363         xs->here->xe_value_size = cpu_to_le64(xi->value_len);
1364         if (xi->value_len <= OCFS2_XATTR_INLINE_SIZE)
1365                 ocfs2_xattr_set_local(xs->here, 1);
1366         else
1367                 ocfs2_xattr_set_local(xs->here, 0);
1368         ocfs2_xattr_hash_entry(inode, xs->header, xs->here);
1369
1370         ret = ocfs2_journal_dirty(handle, vb->vb_bh);
1371         if (ret < 0)
1372                 mlog_errno(ret);
1373 out:
1374         return ret;
1375 }
1376
1377 /*
1378  * ocfs2_xattr_set_value_outside()
1379  *
1380  * Set large size value in B tree.
1381  */
1382 static int ocfs2_xattr_set_value_outside(struct inode *inode,
1383                                          struct ocfs2_xattr_info *xi,
1384                                          struct ocfs2_xattr_search *xs,
1385                                          struct ocfs2_xattr_set_ctxt *ctxt,
1386                                          struct ocfs2_xattr_value_buf *vb,
1387                                          size_t offs)
1388 {
1389         size_t name_len = strlen(xi->name);
1390         void *val = xs->base + offs;
1391         struct ocfs2_xattr_value_root *xv = NULL;
1392         size_t size = OCFS2_XATTR_SIZE(name_len) + OCFS2_XATTR_ROOT_SIZE;
1393         int ret = 0;
1394
1395         memset(val, 0, size);
1396         memcpy(val, xi->name, name_len);
1397         xv = (struct ocfs2_xattr_value_root *)
1398                 (val + OCFS2_XATTR_SIZE(name_len));
1399         xv->xr_clusters = 0;
1400         xv->xr_last_eb_blk = 0;
1401         xv->xr_list.l_tree_depth = 0;
1402         xv->xr_list.l_count = cpu_to_le16(1);
1403         xv->xr_list.l_next_free_rec = 0;
1404         vb->vb_xv = xv;
1405
1406         ret = ocfs2_xattr_value_truncate(inode, vb, xi->value_len, ctxt);
1407         if (ret < 0) {
1408                 mlog_errno(ret);
1409                 return ret;
1410         }
1411         ret = ocfs2_xattr_update_entry(inode, ctxt->handle, xi, xs, vb, offs);
1412         if (ret < 0) {
1413                 mlog_errno(ret);
1414                 return ret;
1415         }
1416         ret = __ocfs2_xattr_set_value_outside(inode, ctxt->handle, vb,
1417                                               xi->value, xi->value_len);
1418         if (ret < 0)
1419                 mlog_errno(ret);
1420
1421         return ret;
1422 }
1423
1424 /*
1425  * ocfs2_xattr_set_entry_local()
1426  *
1427  * Set, replace or remove extended attribute in local.
1428  */
1429 static void ocfs2_xattr_set_entry_local(struct inode *inode,
1430                                         struct ocfs2_xattr_info *xi,
1431                                         struct ocfs2_xattr_search *xs,
1432                                         struct ocfs2_xattr_entry *last,
1433                                         size_t min_offs)
1434 {
1435         size_t name_len = strlen(xi->name);
1436         int i;
1437
1438         if (xi->value && xs->not_found) {
1439                 /* Insert the new xattr entry. */
1440                 le16_add_cpu(&xs->header->xh_count, 1);
1441                 ocfs2_xattr_set_type(last, xi->name_index);
1442                 ocfs2_xattr_set_local(last, 1);
1443                 last->xe_name_len = name_len;
1444         } else {
1445                 void *first_val;
1446                 void *val;
1447                 size_t offs, size;
1448
1449                 first_val = xs->base + min_offs;
1450                 offs = le16_to_cpu(xs->here->xe_name_offset);
1451                 val = xs->base + offs;
1452
1453                 if (le64_to_cpu(xs->here->xe_value_size) >
1454                     OCFS2_XATTR_INLINE_SIZE)
1455                         size = OCFS2_XATTR_SIZE(name_len) +
1456                                 OCFS2_XATTR_ROOT_SIZE;
1457                 else
1458                         size = OCFS2_XATTR_SIZE(name_len) +
1459                         OCFS2_XATTR_SIZE(le64_to_cpu(xs->here->xe_value_size));
1460
1461                 if (xi->value && size == OCFS2_XATTR_SIZE(name_len) +
1462                                 OCFS2_XATTR_SIZE(xi->value_len)) {
1463                         /* The old and the new value have the
1464                            same size. Just replace the value. */
1465                         ocfs2_xattr_set_local(xs->here, 1);
1466                         xs->here->xe_value_size = cpu_to_le64(xi->value_len);
1467                         /* Clear value bytes. */
1468                         memset(val + OCFS2_XATTR_SIZE(name_len),
1469                                0,
1470                                OCFS2_XATTR_SIZE(xi->value_len));
1471                         memcpy(val + OCFS2_XATTR_SIZE(name_len),
1472                                xi->value,
1473                                xi->value_len);
1474                         return;
1475                 }
1476                 /* Remove the old name+value. */
1477                 memmove(first_val + size, first_val, val - first_val);
1478                 memset(first_val, 0, size);
1479                 xs->here->xe_name_hash = 0;
1480                 xs->here->xe_name_offset = 0;
1481                 ocfs2_xattr_set_local(xs->here, 1);
1482                 xs->here->xe_value_size = 0;
1483
1484                 min_offs += size;
1485
1486                 /* Adjust all value offsets. */
1487                 last = xs->header->xh_entries;
1488                 for (i = 0 ; i < le16_to_cpu(xs->header->xh_count); i++) {
1489                         size_t o = le16_to_cpu(last->xe_name_offset);
1490
1491                         if (o < offs)
1492                                 last->xe_name_offset = cpu_to_le16(o + size);
1493                         last += 1;
1494                 }
1495
1496                 if (!xi->value) {
1497                         /* Remove the old entry. */
1498                         last -= 1;
1499                         memmove(xs->here, xs->here + 1,
1500                                 (void *)last - (void *)xs->here);
1501                         memset(last, 0, sizeof(struct ocfs2_xattr_entry));
1502                         le16_add_cpu(&xs->header->xh_count, -1);
1503                 }
1504         }
1505         if (xi->value) {
1506                 /* Insert the new name+value. */
1507                 size_t size = OCFS2_XATTR_SIZE(name_len) +
1508                                 OCFS2_XATTR_SIZE(xi->value_len);
1509                 void *val = xs->base + min_offs - size;
1510
1511                 xs->here->xe_name_offset = cpu_to_le16(min_offs - size);
1512                 memset(val, 0, size);
1513                 memcpy(val, xi->name, name_len);
1514                 memcpy(val + OCFS2_XATTR_SIZE(name_len),
1515                        xi->value,
1516                        xi->value_len);
1517                 xs->here->xe_value_size = cpu_to_le64(xi->value_len);
1518                 ocfs2_xattr_set_local(xs->here, 1);
1519                 ocfs2_xattr_hash_entry(inode, xs->header, xs->here);
1520         }
1521
1522         return;
1523 }
1524
1525 /*
1526  * ocfs2_xattr_set_entry()
1527  *
1528  * Set extended attribute entry into inode or block.
1529  *
1530  * If extended attribute value size > OCFS2_XATTR_INLINE_SIZE,
1531  * We first insert tree root(ocfs2_xattr_value_root) with set_entry_local(),
1532  * then set value in B tree with set_value_outside().
1533  */
1534 static int ocfs2_xattr_set_entry(struct inode *inode,
1535                                  struct ocfs2_xattr_info *xi,
1536                                  struct ocfs2_xattr_search *xs,
1537                                  struct ocfs2_xattr_set_ctxt *ctxt,
1538                                  int flag)
1539 {
1540         struct ocfs2_xattr_entry *last;
1541         struct ocfs2_inode_info *oi = OCFS2_I(inode);
1542         struct ocfs2_dinode *di = (struct ocfs2_dinode *)xs->inode_bh->b_data;
1543         size_t min_offs = xs->end - xs->base, name_len = strlen(xi->name);
1544         size_t size_l = 0;
1545         handle_t *handle = ctxt->handle;
1546         int free, i, ret;
1547         struct ocfs2_xattr_info xi_l = {
1548                 .name_index = xi->name_index,
1549                 .name = xi->name,
1550                 .value = xi->value,
1551                 .value_len = xi->value_len,
1552         };
1553         struct ocfs2_xattr_value_buf vb = {
1554                 .vb_bh = xs->xattr_bh,
1555                 .vb_access = ocfs2_journal_access_di,
1556         };
1557
1558         if (!(flag & OCFS2_INLINE_XATTR_FL)) {
1559                 BUG_ON(xs->xattr_bh == xs->inode_bh);
1560                 vb.vb_access = ocfs2_journal_access_xb;
1561         } else
1562                 BUG_ON(xs->xattr_bh != xs->inode_bh);
1563
1564         /* Compute min_offs, last and free space. */
1565         last = xs->header->xh_entries;
1566
1567         for (i = 0 ; i < le16_to_cpu(xs->header->xh_count); i++) {
1568                 size_t offs = le16_to_cpu(last->xe_name_offset);
1569                 if (offs < min_offs)
1570                         min_offs = offs;
1571                 last += 1;
1572         }
1573
1574         free = min_offs - ((void *)last - xs->base) - OCFS2_XATTR_HEADER_GAP;
1575         if (free < 0)
1576                 return -EIO;
1577
1578         if (!xs->not_found) {
1579                 size_t size = 0;
1580                 if (ocfs2_xattr_is_local(xs->here))
1581                         size = OCFS2_XATTR_SIZE(name_len) +
1582                         OCFS2_XATTR_SIZE(le64_to_cpu(xs->here->xe_value_size));
1583                 else
1584                         size = OCFS2_XATTR_SIZE(name_len) +
1585                                 OCFS2_XATTR_ROOT_SIZE;
1586                 free += (size + sizeof(struct ocfs2_xattr_entry));
1587         }
1588         /* Check free space in inode or block */
1589         if (xi->value && xi->value_len > OCFS2_XATTR_INLINE_SIZE) {
1590                 if (free < sizeof(struct ocfs2_xattr_entry) +
1591                            OCFS2_XATTR_SIZE(name_len) +
1592                            OCFS2_XATTR_ROOT_SIZE) {
1593                         ret = -ENOSPC;
1594                         goto out;
1595                 }
1596                 size_l = OCFS2_XATTR_SIZE(name_len) + OCFS2_XATTR_ROOT_SIZE;
1597                 xi_l.value = (void *)&def_xv;
1598                 xi_l.value_len = OCFS2_XATTR_ROOT_SIZE;
1599         } else if (xi->value) {
1600                 if (free < sizeof(struct ocfs2_xattr_entry) +
1601                            OCFS2_XATTR_SIZE(name_len) +
1602                            OCFS2_XATTR_SIZE(xi->value_len)) {
1603                         ret = -ENOSPC;
1604                         goto out;
1605                 }
1606         }
1607
1608         if (!xs->not_found) {
1609                 /* For existing extended attribute */
1610                 size_t size = OCFS2_XATTR_SIZE(name_len) +
1611                         OCFS2_XATTR_SIZE(le64_to_cpu(xs->here->xe_value_size));
1612                 size_t offs = le16_to_cpu(xs->here->xe_name_offset);
1613                 void *val = xs->base + offs;
1614
1615                 if (ocfs2_xattr_is_local(xs->here) && size == size_l) {
1616                         /* Replace existing local xattr with tree root */
1617                         ret = ocfs2_xattr_set_value_outside(inode, xi, xs,
1618                                                             ctxt, &vb, offs);
1619                         if (ret < 0)
1620                                 mlog_errno(ret);
1621                         goto out;
1622                 } else if (!ocfs2_xattr_is_local(xs->here)) {
1623                         /* For existing xattr which has value outside */
1624                         vb.vb_xv = (struct ocfs2_xattr_value_root *)
1625                                 (val + OCFS2_XATTR_SIZE(name_len));
1626
1627                         if (xi->value_len > OCFS2_XATTR_INLINE_SIZE) {
1628                                 /*
1629                                  * If new value need set outside also,
1630                                  * first truncate old value to new value,
1631                                  * then set new value with set_value_outside().
1632                                  */
1633                                 ret = ocfs2_xattr_value_truncate(inode,
1634                                                                  &vb,
1635                                                                  xi->value_len,
1636                                                                  ctxt);
1637                                 if (ret < 0) {
1638                                         mlog_errno(ret);
1639                                         goto out;
1640                                 }
1641
1642                                 ret = ocfs2_xattr_update_entry(inode,
1643                                                                handle,
1644                                                                xi,
1645                                                                xs,
1646                                                                &vb,
1647                                                                offs);
1648                                 if (ret < 0) {
1649                                         mlog_errno(ret);
1650                                         goto out;
1651                                 }
1652
1653                                 ret = __ocfs2_xattr_set_value_outside(inode,
1654                                                                 handle,
1655                                                                 &vb,
1656                                                                 xi->value,
1657                                                                 xi->value_len);
1658                                 if (ret < 0)
1659                                         mlog_errno(ret);
1660                                 goto out;
1661                         } else {
1662                                 /*
1663                                  * If new value need set in local,
1664                                  * just trucate old value to zero.
1665                                  */
1666                                  ret = ocfs2_xattr_value_truncate(inode,
1667                                                                   &vb,
1668                                                                   0,
1669                                                                   ctxt);
1670                                 if (ret < 0)
1671                                         mlog_errno(ret);
1672                         }
1673                 }
1674         }
1675
1676         ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), xs->inode_bh,
1677                                       OCFS2_JOURNAL_ACCESS_WRITE);
1678         if (ret) {
1679                 mlog_errno(ret);
1680                 goto out;
1681         }
1682
1683         if (!(flag & OCFS2_INLINE_XATTR_FL)) {
1684                 ret = vb.vb_access(handle, INODE_CACHE(inode), vb.vb_bh,
1685                                    OCFS2_JOURNAL_ACCESS_WRITE);
1686                 if (ret) {
1687                         mlog_errno(ret);
1688                         goto out;
1689                 }
1690         }
1691
1692         /*
1693          * Set value in local, include set tree root in local.
1694          * This is the first step for value size >INLINE_SIZE.
1695          */
1696         ocfs2_xattr_set_entry_local(inode, &xi_l, xs, last, min_offs);
1697
1698         if (!(flag & OCFS2_INLINE_XATTR_FL)) {
1699                 ret = ocfs2_journal_dirty(handle, xs->xattr_bh);
1700                 if (ret < 0) {
1701                         mlog_errno(ret);
1702                         goto out;
1703                 }
1704         }
1705
1706         if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL) &&
1707             (flag & OCFS2_INLINE_XATTR_FL)) {
1708                 struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1709                 unsigned int xattrsize = osb->s_xattr_inline_size;
1710
1711                 /*
1712                  * Adjust extent record count or inline data size
1713                  * to reserve space for extended attribute.
1714                  */
1715                 if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1716                         struct ocfs2_inline_data *idata = &di->id2.i_data;
1717                         le16_add_cpu(&idata->id_count, -xattrsize);
1718                 } else if (!(ocfs2_inode_is_fast_symlink(inode))) {
1719                         struct ocfs2_extent_list *el = &di->id2.i_list;
1720                         le16_add_cpu(&el->l_count, -(xattrsize /
1721                                         sizeof(struct ocfs2_extent_rec)));
1722                 }
1723                 di->i_xattr_inline_size = cpu_to_le16(xattrsize);
1724         }
1725         /* Update xattr flag */
1726         spin_lock(&oi->ip_lock);
1727         oi->ip_dyn_features |= flag;
1728         di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
1729         spin_unlock(&oi->ip_lock);
1730
1731         ret = ocfs2_journal_dirty(handle, xs->inode_bh);
1732         if (ret < 0)
1733                 mlog_errno(ret);
1734
1735         if (!ret && xi->value_len > OCFS2_XATTR_INLINE_SIZE) {
1736                 /*
1737                  * Set value outside in B tree.
1738                  * This is the second step for value size > INLINE_SIZE.
1739                  */
1740                 size_t offs = le16_to_cpu(xs->here->xe_name_offset);
1741                 ret = ocfs2_xattr_set_value_outside(inode, xi, xs, ctxt,
1742                                                     &vb, offs);
1743                 if (ret < 0) {
1744                         int ret2;
1745
1746                         mlog_errno(ret);
1747                         /*
1748                          * If set value outside failed, we have to clean
1749                          * the junk tree root we have already set in local.
1750                          */
1751                         ret2 = ocfs2_xattr_cleanup(inode, ctxt->handle,
1752                                                    xi, xs, &vb, offs);
1753                         if (ret2 < 0)
1754                                 mlog_errno(ret2);
1755                 }
1756         }
1757 out:
1758         return ret;
1759 }
1760
1761 /*
1762  * In xattr remove, if it is stored outside and refcounted, we may have
1763  * the chance to split the refcount tree. So need the allocators.
1764  */
1765 static int ocfs2_lock_xattr_remove_allocators(struct inode *inode,
1766                                         struct ocfs2_xattr_value_root *xv,
1767                                         struct ocfs2_caching_info *ref_ci,
1768                                         struct buffer_head *ref_root_bh,
1769                                         struct ocfs2_alloc_context **meta_ac,
1770                                         int *ref_credits)
1771 {
1772         int ret, meta_add = 0;
1773         u32 p_cluster, num_clusters;
1774         unsigned int ext_flags;
1775
1776         *ref_credits = 0;
1777         ret = ocfs2_xattr_get_clusters(inode, 0, &p_cluster,
1778                                        &num_clusters,
1779                                        &xv->xr_list,
1780                                        &ext_flags);
1781         if (ret) {
1782                 mlog_errno(ret);
1783                 goto out;
1784         }
1785
1786         if (!(ext_flags & OCFS2_EXT_REFCOUNTED))
1787                 goto out;
1788
1789         ret = ocfs2_refcounted_xattr_delete_need(inode, ref_ci,
1790                                                  ref_root_bh, xv,
1791                                                  &meta_add, ref_credits);
1792         if (ret) {
1793                 mlog_errno(ret);
1794                 goto out;
1795         }
1796
1797         ret = ocfs2_reserve_new_metadata_blocks(OCFS2_SB(inode->i_sb),
1798                                                 meta_add, meta_ac);
1799         if (ret)
1800                 mlog_errno(ret);
1801
1802 out:
1803         return ret;
1804 }
1805
1806 static int ocfs2_remove_value_outside(struct inode*inode,
1807                                       struct ocfs2_xattr_value_buf *vb,
1808                                       struct ocfs2_xattr_header *header,
1809                                       struct ocfs2_caching_info *ref_ci,
1810                                       struct buffer_head *ref_root_bh)
1811 {
1812         int ret = 0, i, ref_credits;
1813         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1814         struct ocfs2_xattr_set_ctxt ctxt = { NULL, NULL, };
1815         void *val;
1816
1817         ocfs2_init_dealloc_ctxt(&ctxt.dealloc);
1818
1819         for (i = 0; i < le16_to_cpu(header->xh_count); i++) {
1820                 struct ocfs2_xattr_entry *entry = &header->xh_entries[i];
1821
1822                 if (ocfs2_xattr_is_local(entry))
1823                         continue;
1824
1825                 val = (void *)header +
1826                         le16_to_cpu(entry->xe_name_offset);
1827                 vb->vb_xv = (struct ocfs2_xattr_value_root *)
1828                         (val + OCFS2_XATTR_SIZE(entry->xe_name_len));
1829
1830                 ret = ocfs2_lock_xattr_remove_allocators(inode, vb->vb_xv,
1831                                                          ref_ci, ref_root_bh,
1832                                                          &ctxt.meta_ac,
1833                                                          &ref_credits);
1834
1835                 ctxt.handle = ocfs2_start_trans(osb, ref_credits +
1836                                         ocfs2_remove_extent_credits(osb->sb));
1837                 if (IS_ERR(ctxt.handle)) {
1838                         ret = PTR_ERR(ctxt.handle);
1839                         mlog_errno(ret);
1840                         break;
1841                 }
1842
1843                 ret = ocfs2_xattr_value_truncate(inode, vb, 0, &ctxt);
1844                 if (ret < 0) {
1845                         mlog_errno(ret);
1846                         break;
1847                 }
1848
1849                 ocfs2_commit_trans(osb, ctxt.handle);
1850                 if (ctxt.meta_ac) {
1851                         ocfs2_free_alloc_context(ctxt.meta_ac);
1852                         ctxt.meta_ac = NULL;
1853                 }
1854         }
1855
1856         if (ctxt.meta_ac)
1857                 ocfs2_free_alloc_context(ctxt.meta_ac);
1858         ocfs2_schedule_truncate_log_flush(osb, 1);
1859         ocfs2_run_deallocs(osb, &ctxt.dealloc);
1860         return ret;
1861 }
1862
1863 static int ocfs2_xattr_ibody_remove(struct inode *inode,
1864                                     struct buffer_head *di_bh,
1865                                     struct ocfs2_caching_info *ref_ci,
1866                                     struct buffer_head *ref_root_bh)
1867 {
1868
1869         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
1870         struct ocfs2_xattr_header *header;
1871         int ret;
1872         struct ocfs2_xattr_value_buf vb = {
1873                 .vb_bh = di_bh,
1874                 .vb_access = ocfs2_journal_access_di,
1875         };
1876
1877         header = (struct ocfs2_xattr_header *)
1878                  ((void *)di + inode->i_sb->s_blocksize -
1879                  le16_to_cpu(di->i_xattr_inline_size));
1880
1881         ret = ocfs2_remove_value_outside(inode, &vb, header,
1882                                          ref_ci, ref_root_bh);
1883
1884         return ret;
1885 }
1886
1887 struct ocfs2_rm_xattr_bucket_para {
1888         struct ocfs2_caching_info *ref_ci;
1889         struct buffer_head *ref_root_bh;
1890 };
1891
1892 static int ocfs2_xattr_block_remove(struct inode *inode,
1893                                     struct buffer_head *blk_bh,
1894                                     struct ocfs2_caching_info *ref_ci,
1895                                     struct buffer_head *ref_root_bh)
1896 {
1897         struct ocfs2_xattr_block *xb;
1898         int ret = 0;
1899         struct ocfs2_xattr_value_buf vb = {
1900                 .vb_bh = blk_bh,
1901                 .vb_access = ocfs2_journal_access_xb,
1902         };
1903         struct ocfs2_rm_xattr_bucket_para args = {
1904                 .ref_ci = ref_ci,
1905                 .ref_root_bh = ref_root_bh,
1906         };
1907
1908         xb = (struct ocfs2_xattr_block *)blk_bh->b_data;
1909         if (!(le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED)) {
1910                 struct ocfs2_xattr_header *header = &(xb->xb_attrs.xb_header);
1911                 ret = ocfs2_remove_value_outside(inode, &vb, header,
1912                                                  ref_ci, ref_root_bh);
1913         } else
1914                 ret = ocfs2_iterate_xattr_index_block(inode,
1915                                                 blk_bh,
1916                                                 ocfs2_rm_xattr_cluster,
1917                                                 &args);
1918
1919         return ret;
1920 }
1921
1922 static int ocfs2_xattr_free_block(struct inode *inode,
1923                                   u64 block,
1924                                   struct ocfs2_caching_info *ref_ci,
1925                                   struct buffer_head *ref_root_bh)
1926 {
1927         struct inode *xb_alloc_inode;
1928         struct buffer_head *xb_alloc_bh = NULL;
1929         struct buffer_head *blk_bh = NULL;
1930         struct ocfs2_xattr_block *xb;
1931         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1932         handle_t *handle;
1933         int ret = 0;
1934         u64 blk, bg_blkno;
1935         u16 bit;
1936
1937         ret = ocfs2_read_xattr_block(inode, block, &blk_bh);
1938         if (ret < 0) {
1939                 mlog_errno(ret);
1940                 goto out;
1941         }
1942
1943         ret = ocfs2_xattr_block_remove(inode, blk_bh, ref_ci, ref_root_bh);
1944         if (ret < 0) {
1945                 mlog_errno(ret);
1946                 goto out;
1947         }
1948
1949         xb = (struct ocfs2_xattr_block *)blk_bh->b_data;
1950         blk = le64_to_cpu(xb->xb_blkno);
1951         bit = le16_to_cpu(xb->xb_suballoc_bit);
1952         bg_blkno = ocfs2_which_suballoc_group(blk, bit);
1953
1954         xb_alloc_inode = ocfs2_get_system_file_inode(osb,
1955                                 EXTENT_ALLOC_SYSTEM_INODE,
1956                                 le16_to_cpu(xb->xb_suballoc_slot));
1957         if (!xb_alloc_inode) {
1958                 ret = -ENOMEM;
1959                 mlog_errno(ret);
1960                 goto out;
1961         }
1962         mutex_lock(&xb_alloc_inode->i_mutex);
1963
1964         ret = ocfs2_inode_lock(xb_alloc_inode, &xb_alloc_bh, 1);
1965         if (ret < 0) {
1966                 mlog_errno(ret);
1967                 goto out_mutex;
1968         }
1969
1970         handle = ocfs2_start_trans(osb, OCFS2_SUBALLOC_FREE);
1971         if (IS_ERR(handle)) {
1972                 ret = PTR_ERR(handle);
1973                 mlog_errno(ret);
1974                 goto out_unlock;
1975         }
1976
1977         ret = ocfs2_free_suballoc_bits(handle, xb_alloc_inode, xb_alloc_bh,
1978                                        bit, bg_blkno, 1);
1979         if (ret < 0)
1980                 mlog_errno(ret);
1981
1982         ocfs2_commit_trans(osb, handle);
1983 out_unlock:
1984         ocfs2_inode_unlock(xb_alloc_inode, 1);
1985         brelse(xb_alloc_bh);
1986 out_mutex:
1987         mutex_unlock(&xb_alloc_inode->i_mutex);
1988         iput(xb_alloc_inode);
1989 out:
1990         brelse(blk_bh);
1991         return ret;
1992 }
1993
1994 /*
1995  * ocfs2_xattr_remove()
1996  *
1997  * Free extended attribute resources associated with this inode.
1998  */
1999 int ocfs2_xattr_remove(struct inode *inode, struct buffer_head *di_bh)
2000 {
2001         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2002         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
2003         struct ocfs2_refcount_tree *ref_tree = NULL;
2004         struct buffer_head *ref_root_bh = NULL;
2005         struct ocfs2_caching_info *ref_ci = NULL;
2006         handle_t *handle;
2007         int ret;
2008
2009         if (!ocfs2_supports_xattr(OCFS2_SB(inode->i_sb)))
2010                 return 0;
2011
2012         if (!(oi->ip_dyn_features & OCFS2_HAS_XATTR_FL))
2013                 return 0;
2014
2015         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL) {
2016                 ret = ocfs2_lock_refcount_tree(OCFS2_SB(inode->i_sb),
2017                                                le64_to_cpu(di->i_refcount_loc),
2018                                                1, &ref_tree, &ref_root_bh);
2019                 if (ret) {
2020                         mlog_errno(ret);
2021                         goto out;
2022                 }
2023                 ref_ci = &ref_tree->rf_ci;
2024
2025         }
2026
2027         if (oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL) {
2028                 ret = ocfs2_xattr_ibody_remove(inode, di_bh,
2029                                                ref_ci, ref_root_bh);
2030                 if (ret < 0) {
2031                         mlog_errno(ret);
2032                         goto out;
2033                 }
2034         }
2035
2036         if (di->i_xattr_loc) {
2037                 ret = ocfs2_xattr_free_block(inode,
2038                                              le64_to_cpu(di->i_xattr_loc),
2039                                              ref_ci, ref_root_bh);
2040                 if (ret < 0) {
2041                         mlog_errno(ret);
2042                         goto out;
2043                 }
2044         }
2045
2046         handle = ocfs2_start_trans((OCFS2_SB(inode->i_sb)),
2047                                    OCFS2_INODE_UPDATE_CREDITS);
2048         if (IS_ERR(handle)) {
2049                 ret = PTR_ERR(handle);
2050                 mlog_errno(ret);
2051                 goto out;
2052         }
2053         ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
2054                                       OCFS2_JOURNAL_ACCESS_WRITE);
2055         if (ret) {
2056                 mlog_errno(ret);
2057                 goto out_commit;
2058         }
2059
2060         di->i_xattr_loc = 0;
2061
2062         spin_lock(&oi->ip_lock);
2063         oi->ip_dyn_features &= ~(OCFS2_INLINE_XATTR_FL | OCFS2_HAS_XATTR_FL);
2064         di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
2065         spin_unlock(&oi->ip_lock);
2066
2067         ret = ocfs2_journal_dirty(handle, di_bh);
2068         if (ret < 0)
2069                 mlog_errno(ret);
2070 out_commit:
2071         ocfs2_commit_trans(OCFS2_SB(inode->i_sb), handle);
2072 out:
2073         if (ref_tree)
2074                 ocfs2_unlock_refcount_tree(OCFS2_SB(inode->i_sb), ref_tree, 1);
2075         brelse(ref_root_bh);
2076         return ret;
2077 }
2078
2079 static int ocfs2_xattr_has_space_inline(struct inode *inode,
2080                                         struct ocfs2_dinode *di)
2081 {
2082         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2083         unsigned int xattrsize = OCFS2_SB(inode->i_sb)->s_xattr_inline_size;
2084         int free;
2085
2086         if (xattrsize < OCFS2_MIN_XATTR_INLINE_SIZE)
2087                 return 0;
2088
2089         if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
2090                 struct ocfs2_inline_data *idata = &di->id2.i_data;
2091                 free = le16_to_cpu(idata->id_count) - le64_to_cpu(di->i_size);
2092         } else if (ocfs2_inode_is_fast_symlink(inode)) {
2093                 free = ocfs2_fast_symlink_chars(inode->i_sb) -
2094                         le64_to_cpu(di->i_size);
2095         } else {
2096                 struct ocfs2_extent_list *el = &di->id2.i_list;
2097                 free = (le16_to_cpu(el->l_count) -
2098                         le16_to_cpu(el->l_next_free_rec)) *
2099                         sizeof(struct ocfs2_extent_rec);
2100         }
2101         if (free >= xattrsize)
2102                 return 1;
2103
2104         return 0;
2105 }
2106
2107 /*
2108  * ocfs2_xattr_ibody_find()
2109  *
2110  * Find extended attribute in inode block and
2111  * fill search info into struct ocfs2_xattr_search.
2112  */
2113 static int ocfs2_xattr_ibody_find(struct inode *inode,
2114                                   int name_index,
2115                                   const char *name,
2116                                   struct ocfs2_xattr_search *xs)
2117 {
2118         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2119         struct ocfs2_dinode *di = (struct ocfs2_dinode *)xs->inode_bh->b_data;
2120         int ret;
2121         int has_space = 0;
2122
2123         if (inode->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE)
2124                 return 0;
2125
2126         if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL)) {
2127                 down_read(&oi->ip_alloc_sem);
2128                 has_space = ocfs2_xattr_has_space_inline(inode, di);
2129                 up_read(&oi->ip_alloc_sem);
2130                 if (!has_space)
2131                         return 0;
2132         }
2133
2134         xs->xattr_bh = xs->inode_bh;
2135         xs->end = (void *)di + inode->i_sb->s_blocksize;
2136         if (oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL)
2137                 xs->header = (struct ocfs2_xattr_header *)
2138                         (xs->end - le16_to_cpu(di->i_xattr_inline_size));
2139         else
2140                 xs->header = (struct ocfs2_xattr_header *)
2141                         (xs->end - OCFS2_SB(inode->i_sb)->s_xattr_inline_size);
2142         xs->base = (void *)xs->header;
2143         xs->here = xs->header->xh_entries;
2144
2145         /* Find the named attribute. */
2146         if (oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL) {
2147                 ret = ocfs2_xattr_find_entry(name_index, name, xs);
2148                 if (ret && ret != -ENODATA)
2149                         return ret;
2150                 xs->not_found = ret;
2151         }
2152
2153         return 0;
2154 }
2155
2156 /*
2157  * ocfs2_xattr_ibody_set()
2158  *
2159  * Set, replace or remove an extended attribute into inode block.
2160  *
2161  */
2162 static int ocfs2_xattr_ibody_set(struct inode *inode,
2163                                  struct ocfs2_xattr_info *xi,
2164                                  struct ocfs2_xattr_search *xs,
2165                                  struct ocfs2_xattr_set_ctxt *ctxt)
2166 {
2167         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2168         struct ocfs2_dinode *di = (struct ocfs2_dinode *)xs->inode_bh->b_data;
2169         int ret;
2170
2171         if (inode->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE)
2172                 return -ENOSPC;
2173
2174         down_write(&oi->ip_alloc_sem);
2175         if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL)) {
2176                 if (!ocfs2_xattr_has_space_inline(inode, di)) {
2177                         ret = -ENOSPC;
2178                         goto out;
2179                 }
2180         }
2181
2182         ret = ocfs2_xattr_set_entry(inode, xi, xs, ctxt,
2183                                 (OCFS2_INLINE_XATTR_FL | OCFS2_HAS_XATTR_FL));
2184 out:
2185         up_write(&oi->ip_alloc_sem);
2186
2187         return ret;
2188 }
2189
2190 /*
2191  * ocfs2_xattr_block_find()
2192  *
2193  * Find extended attribute in external block and
2194  * fill search info into struct ocfs2_xattr_search.
2195  */
2196 static int ocfs2_xattr_block_find(struct inode *inode,
2197                                   int name_index,
2198                                   const char *name,
2199                                   struct ocfs2_xattr_search *xs)
2200 {
2201         struct ocfs2_dinode *di = (struct ocfs2_dinode *)xs->inode_bh->b_data;
2202         struct buffer_head *blk_bh = NULL;
2203         struct ocfs2_xattr_block *xb;
2204         int ret = 0;
2205
2206         if (!di->i_xattr_loc)
2207                 return ret;
2208
2209         ret = ocfs2_read_xattr_block(inode, le64_to_cpu(di->i_xattr_loc),
2210                                      &blk_bh);
2211         if (ret < 0) {
2212                 mlog_errno(ret);
2213                 return ret;
2214         }
2215
2216         xs->xattr_bh = blk_bh;
2217         xb = (struct ocfs2_xattr_block *)blk_bh->b_data;
2218
2219         if (!(le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED)) {
2220                 xs->header = &xb->xb_attrs.xb_header;
2221                 xs->base = (void *)xs->header;
2222                 xs->end = (void *)(blk_bh->b_data) + blk_bh->b_size;
2223                 xs->here = xs->header->xh_entries;
2224
2225                 ret = ocfs2_xattr_find_entry(name_index, name, xs);
2226         } else
2227                 ret = ocfs2_xattr_index_block_find(inode, blk_bh,
2228                                                    name_index,
2229                                                    name, xs);
2230
2231         if (ret && ret != -ENODATA) {
2232                 xs->xattr_bh = NULL;
2233                 goto cleanup;
2234         }
2235         xs->not_found = ret;
2236         return 0;
2237 cleanup:
2238         brelse(blk_bh);
2239
2240         return ret;
2241 }
2242
2243 static int ocfs2_create_xattr_block(handle_t *handle,
2244                                     struct inode *inode,
2245                                     struct buffer_head *inode_bh,
2246                                     struct ocfs2_alloc_context *meta_ac,
2247                                     struct buffer_head **ret_bh,
2248                                     int indexed)
2249 {
2250         int ret;
2251         u16 suballoc_bit_start;
2252         u32 num_got;
2253         u64 first_blkno;
2254         struct ocfs2_dinode *di =  (struct ocfs2_dinode *)inode_bh->b_data;
2255         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2256         struct buffer_head *new_bh = NULL;
2257         struct ocfs2_xattr_block *xblk;
2258
2259         ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), inode_bh,
2260                                       OCFS2_JOURNAL_ACCESS_CREATE);
2261         if (ret < 0) {
2262                 mlog_errno(ret);
2263                 goto end;
2264         }
2265
2266         ret = ocfs2_claim_metadata(osb, handle, meta_ac, 1,
2267                                    &suballoc_bit_start, &num_got,
2268                                    &first_blkno);
2269         if (ret < 0) {
2270                 mlog_errno(ret);
2271                 goto end;
2272         }
2273
2274         new_bh = sb_getblk(inode->i_sb, first_blkno);
2275         ocfs2_set_new_buffer_uptodate(INODE_CACHE(inode), new_bh);
2276
2277         ret = ocfs2_journal_access_xb(handle, INODE_CACHE(inode),
2278                                       new_bh,
2279                                       OCFS2_JOURNAL_ACCESS_CREATE);
2280         if (ret < 0) {
2281                 mlog_errno(ret);
2282                 goto end;
2283         }
2284
2285         /* Initialize ocfs2_xattr_block */
2286         xblk = (struct ocfs2_xattr_block *)new_bh->b_data;
2287         memset(xblk, 0, inode->i_sb->s_blocksize);
2288         strcpy((void *)xblk, OCFS2_XATTR_BLOCK_SIGNATURE);
2289         xblk->xb_suballoc_slot = cpu_to_le16(osb->slot_num);
2290         xblk->xb_suballoc_bit = cpu_to_le16(suballoc_bit_start);
2291         xblk->xb_fs_generation = cpu_to_le32(osb->fs_generation);
2292         xblk->xb_blkno = cpu_to_le64(first_blkno);
2293
2294         if (indexed) {
2295                 struct ocfs2_xattr_tree_root *xr = &xblk->xb_attrs.xb_root;
2296                 xr->xt_clusters = cpu_to_le32(1);
2297                 xr->xt_last_eb_blk = 0;
2298                 xr->xt_list.l_tree_depth = 0;
2299                 xr->xt_list.l_count = cpu_to_le16(
2300                                         ocfs2_xattr_recs_per_xb(inode->i_sb));
2301                 xr->xt_list.l_next_free_rec = cpu_to_le16(1);
2302                 xblk->xb_flags = cpu_to_le16(OCFS2_XATTR_INDEXED);
2303         }
2304
2305         ret = ocfs2_journal_dirty(handle, new_bh);
2306         if (ret < 0) {
2307                 mlog_errno(ret);
2308                 goto end;
2309         }
2310         di->i_xattr_loc = cpu_to_le64(first_blkno);
2311         ocfs2_journal_dirty(handle, inode_bh);
2312
2313         *ret_bh = new_bh;
2314         new_bh = NULL;
2315
2316 end:
2317         brelse(new_bh);
2318         return ret;
2319 }
2320
2321 /*
2322  * ocfs2_xattr_block_set()
2323  *
2324  * Set, replace or remove an extended attribute into external block.
2325  *
2326  */
2327 static int ocfs2_xattr_block_set(struct inode *inode,
2328                                  struct ocfs2_xattr_info *xi,
2329                                  struct ocfs2_xattr_search *xs,
2330                                  struct ocfs2_xattr_set_ctxt *ctxt)
2331 {
2332         struct buffer_head *new_bh = NULL;
2333         handle_t *handle = ctxt->handle;
2334         struct ocfs2_xattr_block *xblk = NULL;
2335         int ret;
2336
2337         if (!xs->xattr_bh) {
2338                 ret = ocfs2_create_xattr_block(handle, inode, xs->inode_bh,
2339                                                ctxt->meta_ac, &new_bh, 0);
2340                 if (ret) {
2341                         mlog_errno(ret);
2342                         goto end;
2343                 }
2344
2345                 xs->xattr_bh = new_bh;
2346                 xblk = (struct ocfs2_xattr_block *)xs->xattr_bh->b_data;
2347                 xs->header = &xblk->xb_attrs.xb_header;
2348                 xs->base = (void *)xs->header;
2349                 xs->end = (void *)xblk + inode->i_sb->s_blocksize;
2350                 xs->here = xs->header->xh_entries;
2351         } else
2352                 xblk = (struct ocfs2_xattr_block *)xs->xattr_bh->b_data;
2353
2354         if (!(le16_to_cpu(xblk->xb_flags) & OCFS2_XATTR_INDEXED)) {
2355                 /* Set extended attribute into external block */
2356                 ret = ocfs2_xattr_set_entry(inode, xi, xs, ctxt,
2357                                             OCFS2_HAS_XATTR_FL);
2358                 if (!ret || ret != -ENOSPC)
2359                         goto end;
2360
2361                 ret = ocfs2_xattr_create_index_block(inode, xs, ctxt);
2362                 if (ret)
2363                         goto end;
2364         }
2365
2366         ret = ocfs2_xattr_set_entry_index_block(inode, xi, xs, ctxt);
2367
2368 end:
2369
2370         return ret;
2371 }
2372
2373 /* Check whether the new xattr can be inserted into the inode. */
2374 static int ocfs2_xattr_can_be_in_inode(struct inode *inode,
2375                                        struct ocfs2_xattr_info *xi,
2376                                        struct ocfs2_xattr_search *xs)
2377 {
2378         u64 value_size;
2379         struct ocfs2_xattr_entry *last;
2380         int free, i;
2381         size_t min_offs = xs->end - xs->base;
2382
2383         if (!xs->header)
2384                 return 0;
2385
2386         last = xs->header->xh_entries;
2387
2388         for (i = 0; i < le16_to_cpu(xs->header->xh_count); i++) {
2389                 size_t offs = le16_to_cpu(last->xe_name_offset);
2390                 if (offs < min_offs)
2391                         min_offs = offs;
2392                 last += 1;
2393         }
2394
2395         free = min_offs - ((void *)last - xs->base) - OCFS2_XATTR_HEADER_GAP;
2396         if (free < 0)
2397                 return 0;
2398
2399         BUG_ON(!xs->not_found);
2400
2401         if (xi->value_len > OCFS2_XATTR_INLINE_SIZE)
2402                 value_size = OCFS2_XATTR_ROOT_SIZE;
2403         else
2404                 value_size = OCFS2_XATTR_SIZE(xi->value_len);
2405
2406         if (free >= sizeof(struct ocfs2_xattr_entry) +
2407                    OCFS2_XATTR_SIZE(strlen(xi->name)) + value_size)
2408                 return 1;
2409
2410         return 0;
2411 }
2412
2413 static int ocfs2_calc_xattr_set_need(struct inode *inode,
2414                                      struct ocfs2_dinode *di,
2415                                      struct ocfs2_xattr_info *xi,
2416                                      struct ocfs2_xattr_search *xis,
2417                                      struct ocfs2_xattr_search *xbs,
2418                                      int *clusters_need,
2419                                      int *meta_need,
2420                                      int *credits_need)
2421 {
2422         int ret = 0, old_in_xb = 0;
2423         int clusters_add = 0, meta_add = 0, credits = 0;
2424         struct buffer_head *bh = NULL;
2425         struct ocfs2_xattr_block *xb = NULL;
2426         struct ocfs2_xattr_entry *xe = NULL;
2427         struct ocfs2_xattr_value_root *xv = NULL;
2428         char *base = NULL;
2429         int name_offset, name_len = 0;
2430         u32 new_clusters = ocfs2_clusters_for_bytes(inode->i_sb,
2431                                                     xi->value_len);
2432         u64 value_size;
2433
2434         /*
2435          * Calculate the clusters we need to write.
2436          * No matter whether we replace an old one or add a new one,
2437          * we need this for writing.
2438          */
2439         if (xi->value_len > OCFS2_XATTR_INLINE_SIZE)
2440                 credits += new_clusters *
2441                            ocfs2_clusters_to_blocks(inode->i_sb, 1);
2442
2443         if (xis->not_found && xbs->not_found) {
2444                 credits += ocfs2_blocks_per_xattr_bucket(inode->i_sb);
2445
2446                 if (xi->value_len > OCFS2_XATTR_INLINE_SIZE) {
2447                         clusters_add += new_clusters;
2448                         credits += ocfs2_calc_extend_credits(inode->i_sb,
2449                                                         &def_xv.xv.xr_list,
2450                                                         new_clusters);
2451                 }
2452
2453                 goto meta_guess;
2454         }
2455
2456         if (!xis->not_found) {
2457                 xe = xis->here;
2458                 name_offset = le16_to_cpu(xe->xe_name_offset);
2459                 name_len = OCFS2_XATTR_SIZE(xe->xe_name_len);
2460                 base = xis->base;
2461                 credits += OCFS2_INODE_UPDATE_CREDITS;
2462         } else {
2463                 int i, block_off = 0;
2464                 xb = (struct ocfs2_xattr_block *)xbs->xattr_bh->b_data;
2465                 xe = xbs->here;
2466                 name_offset = le16_to_cpu(xe->xe_name_offset);
2467                 name_len = OCFS2_XATTR_SIZE(xe->xe_name_len);
2468                 i = xbs->here - xbs->header->xh_entries;
2469                 old_in_xb = 1;
2470
2471                 if (le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED) {
2472                         ret = ocfs2_xattr_bucket_get_name_value(inode->i_sb,
2473                                                         bucket_xh(xbs->bucket),
2474                                                         i, &block_off,
2475                                                         &name_offset);
2476                         base = bucket_block(xbs->bucket, block_off);
2477                         credits += ocfs2_blocks_per_xattr_bucket(inode->i_sb);
2478                 } else {
2479                         base = xbs->base;
2480                         credits += OCFS2_XATTR_BLOCK_UPDATE_CREDITS;
2481                 }
2482         }
2483
2484         /*
2485          * delete a xattr doesn't need metadata and cluster allocation.
2486          * so just calculate the credits and return.
2487          *
2488          * The credits for removing the value tree will be extended
2489          * by ocfs2_remove_extent itself.
2490          */
2491         if (!xi->value) {
2492                 if (!ocfs2_xattr_is_local(xe))
2493                         credits += ocfs2_remove_extent_credits(inode->i_sb);
2494
2495                 goto out;
2496         }
2497
2498         /* do cluster allocation guess first. */
2499         value_size = le64_to_cpu(xe->xe_value_size);
2500
2501         if (old_in_xb) {
2502                 /*
2503                  * In xattr set, we always try to set the xe in inode first,
2504                  * so if it can be inserted into inode successfully, the old
2505                  * one will be removed from the xattr block, and this xattr
2506                  * will be inserted into inode as a new xattr in inode.
2507                  */
2508                 if (ocfs2_xattr_can_be_in_inode(inode, xi, xis)) {
2509                         clusters_add += new_clusters;
2510                         credits += ocfs2_remove_extent_credits(inode->i_sb) +
2511                                     OCFS2_INODE_UPDATE_CREDITS;
2512                         if (!ocfs2_xattr_is_local(xe))
2513                                 credits += ocfs2_calc_extend_credits(
2514                                                         inode->i_sb,
2515                                                         &def_xv.xv.xr_list,
2516                                                         new_clusters);
2517                         goto out;
2518                 }
2519         }
2520
2521         if (xi->value_len > OCFS2_XATTR_INLINE_SIZE) {
2522                 /* the new values will be stored outside. */
2523                 u32 old_clusters = 0;
2524
2525                 if (!ocfs2_xattr_is_local(xe)) {
2526                         old_clusters =  ocfs2_clusters_for_bytes(inode->i_sb,
2527                                                                  value_size);
2528                         xv = (struct ocfs2_xattr_value_root *)
2529                              (base + name_offset + name_len);
2530                         value_size = OCFS2_XATTR_ROOT_SIZE;
2531                 } else
2532                         xv = &def_xv.xv;
2533
2534                 if (old_clusters >= new_clusters) {
2535                         credits += ocfs2_remove_extent_credits(inode->i_sb);
2536                         goto out;
2537                 } else {
2538                         meta_add += ocfs2_extend_meta_needed(&xv->xr_list);
2539                         clusters_add += new_clusters - old_clusters;
2540                         credits += ocfs2_calc_extend_credits(inode->i_sb,
2541                                                              &xv->xr_list,
2542                                                              new_clusters -
2543                                                              old_clusters);
2544                         if (value_size >= OCFS2_XATTR_ROOT_SIZE)
2545                                 goto out;
2546                 }
2547         } else {
2548                 /*
2549                  * Now the new value will be stored inside. So if the new
2550                  * value is smaller than the size of value root or the old
2551                  * value, we don't need any allocation, otherwise we have
2552                  * to guess metadata allocation.
2553                  */
2554                 if ((ocfs2_xattr_is_local(xe) && value_size >= xi->value_len) ||
2555                     (!ocfs2_xattr_is_local(xe) &&
2556                      OCFS2_XATTR_ROOT_SIZE >= xi->value_len))
2557                         goto out;
2558         }
2559
2560 meta_guess:
2561         /* calculate metadata allocation. */
2562         if (di->i_xattr_loc) {
2563                 if (!xbs->xattr_bh) {
2564                         ret = ocfs2_read_xattr_block(inode,
2565                                                      le64_to_cpu(di->i_xattr_loc),
2566                                                      &bh);
2567                         if (ret) {
2568                                 mlog_errno(ret);
2569                                 goto out;
2570                         }
2571
2572                         xb = (struct ocfs2_xattr_block *)bh->b_data;
2573                 } else
2574                         xb = (struct ocfs2_xattr_block *)xbs->xattr_bh->b_data;
2575
2576                 /*
2577                  * If there is already an xattr tree, good, we can calculate
2578                  * like other b-trees. Otherwise we may have the chance of
2579                  * create a tree, the credit calculation is borrowed from
2580                  * ocfs2_calc_extend_credits with root_el = NULL. And the
2581                  * new tree will be cluster based, so no meta is needed.
2582                  */
2583                 if (le16_to_cpu(xb->xb_flags) & OCFS2_XATTR_INDEXED) {
2584                         struct ocfs2_extent_list *el =
2585                                  &xb->xb_attrs.xb_root.xt_list;
2586                         meta_add += ocfs2_extend_meta_needed(el);
2587                         credits += ocfs2_calc_extend_credits(inode->i_sb,
2588                                                              el, 1);
2589                 } else
2590                         credits += OCFS2_SUBALLOC_ALLOC + 1;
2591
2592                 /*
2593                  * This cluster will be used either for new bucket or for
2594                  * new xattr block.
2595                  * If the cluster size is the same as the bucket size, one
2596                  * more is needed since we may need to extend the bucket
2597                  * also.
2598                  */
2599                 clusters_add += 1;
2600                 credits += ocfs2_blocks_per_xattr_bucket(inode->i_sb);
2601                 if (OCFS2_XATTR_BUCKET_SIZE ==
2602                         OCFS2_SB(inode->i_sb)->s_clustersize) {
2603                         credits += ocfs2_blocks_per_xattr_bucket(inode->i_sb);
2604                         clusters_add += 1;
2605                 }
2606         } else {
2607                 meta_add += 1;
2608                 credits += OCFS2_XATTR_BLOCK_CREATE_CREDITS;
2609         }
2610 out:
2611         if (clusters_need)
2612                 *clusters_need = clusters_add;
2613         if (meta_need)
2614                 *meta_need = meta_add;
2615         if (credits_need)
2616                 *credits_need = credits;
2617         brelse(bh);
2618         return ret;
2619 }
2620
2621 static int ocfs2_init_xattr_set_ctxt(struct inode *inode,
2622                                      struct ocfs2_dinode *di,
2623                                      struct ocfs2_xattr_info *xi,
2624                                      struct ocfs2_xattr_search *xis,
2625                                      struct ocfs2_xattr_search *xbs,
2626                                      struct ocfs2_xattr_set_ctxt *ctxt,
2627                                      int extra_meta,
2628                                      int *credits)
2629 {
2630         int clusters_add, meta_add, ret;
2631         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2632
2633         memset(ctxt, 0, sizeof(struct ocfs2_xattr_set_ctxt));
2634
2635         ocfs2_init_dealloc_ctxt(&ctxt->dealloc);
2636
2637         ret = ocfs2_calc_xattr_set_need(inode, di, xi, xis, xbs,
2638                                         &clusters_add, &meta_add, credits);
2639         if (ret) {
2640                 mlog_errno(ret);
2641                 return ret;
2642         }
2643
2644         meta_add += extra_meta;
2645         mlog(0, "Set xattr %s, reserve meta blocks = %d, clusters = %d, "
2646              "credits = %d\n", xi->name, meta_add, clusters_add, *credits);
2647
2648         if (meta_add) {
2649                 ret = ocfs2_reserve_new_metadata_blocks(osb, meta_add,
2650                                                         &ctxt->meta_ac);
2651                 if (ret) {
2652                         mlog_errno(ret);
2653                         goto out;
2654                 }
2655         }
2656
2657         if (clusters_add) {
2658                 ret = ocfs2_reserve_clusters(osb, clusters_add, &ctxt->data_ac);
2659                 if (ret)
2660                         mlog_errno(ret);
2661         }
2662 out:
2663         if (ret) {
2664                 if (ctxt->meta_ac) {
2665                         ocfs2_free_alloc_context(ctxt->meta_ac);
2666                         ctxt->meta_ac = NULL;
2667                 }
2668
2669                 /*
2670                  * We cannot have an error and a non null ctxt->data_ac.
2671                  */
2672         }
2673
2674         return ret;
2675 }
2676
2677 static int __ocfs2_xattr_set_handle(struct inode *inode,
2678                                     struct ocfs2_dinode *di,
2679                                     struct ocfs2_xattr_info *xi,
2680                                     struct ocfs2_xattr_search *xis,
2681                                     struct ocfs2_xattr_search *xbs,
2682                                     struct ocfs2_xattr_set_ctxt *ctxt)
2683 {
2684         int ret = 0, credits, old_found;
2685
2686         if (!xi->value) {
2687                 /* Remove existing extended attribute */
2688                 if (!xis->not_found)
2689                         ret = ocfs2_xattr_ibody_set(inode, xi, xis, ctxt);
2690                 else if (!xbs->not_found)
2691                         ret = ocfs2_xattr_block_set(inode, xi, xbs, ctxt);
2692         } else {
2693                 /* We always try to set extended attribute into inode first*/
2694                 ret = ocfs2_xattr_ibody_set(inode, xi, xis, ctxt);
2695                 if (!ret && !xbs->not_found) {
2696                         /*
2697                          * If succeed and that extended attribute existing in
2698                          * external block, then we will remove it.
2699                          */
2700                         xi->value = NULL;
2701                         xi->value_len = 0;
2702
2703                         old_found = xis->not_found;
2704                         xis->not_found = -ENODATA;
2705                         ret = ocfs2_calc_xattr_set_need(inode,
2706                                                         di,
2707                                                         xi,
2708                                                         xis,
2709                                                         xbs,
2710                                                         NULL,
2711                                                         NULL,
2712                                                         &credits);
2713                         xis->not_found = old_found;
2714                         if (ret) {
2715                                 mlog_errno(ret);
2716                                 goto out;
2717                         }
2718
2719                         ret = ocfs2_extend_trans(ctxt->handle, credits +
2720                                         ctxt->handle->h_buffer_credits);
2721                         if (ret) {
2722                                 mlog_errno(ret);
2723                                 goto out;
2724                         }
2725                         ret = ocfs2_xattr_block_set(inode, xi, xbs, ctxt);
2726                 } else if (ret == -ENOSPC) {
2727                         if (di->i_xattr_loc && !xbs->xattr_bh) {
2728                                 ret = ocfs2_xattr_block_find(inode,
2729                                                              xi->name_index,
2730                                                              xi->name, xbs);
2731                                 if (ret)
2732                                         goto out;
2733
2734                                 old_found = xis->not_found;
2735                                 xis->not_found = -ENODATA;
2736                                 ret = ocfs2_calc_xattr_set_need(inode,
2737                                                                 di,
2738                                                                 xi,
2739                                                                 xis,
2740                                                                 xbs,
2741                                                                 NULL,
2742                                                                 NULL,
2743                                                                 &credits);
2744                                 xis->not_found = old_found;
2745                                 if (ret) {
2746                                         mlog_errno(ret);
2747                                         goto out;
2748                                 }
2749
2750                                 ret = ocfs2_extend_trans(ctxt->handle, credits +
2751                                         ctxt->handle->h_buffer_credits);
2752                                 if (ret) {
2753                                         mlog_errno(ret);
2754                                         goto out;
2755                                 }
2756                         }
2757                         /*
2758                          * If no space in inode, we will set extended attribute
2759                          * into external block.
2760                          */
2761                         ret = ocfs2_xattr_block_set(inode, xi, xbs, ctxt);
2762                         if (ret)
2763                                 goto out;
2764                         if (!xis->not_found) {
2765                                 /*
2766                                  * If succeed and that extended attribute
2767                                  * existing in inode, we will remove it.
2768                                  */
2769                                 xi->value = NULL;
2770                                 xi->value_len = 0;
2771                                 xbs->not_found = -ENODATA;
2772                                 ret = ocfs2_calc_xattr_set_need(inode,
2773                                                                 di,
2774                                                                 xi,
2775                                                                 xis,
2776                                                                 xbs,
2777                                                                 NULL,
2778                                                                 NULL,
2779                                                                 &credits);
2780                                 if (ret) {
2781                                         mlog_errno(ret);
2782                                         goto out;
2783                                 }
2784
2785                                 ret = ocfs2_extend_trans(ctxt->handle, credits +
2786                                                 ctxt->handle->h_buffer_credits);
2787                                 if (ret) {
2788                                         mlog_errno(ret);
2789                                         goto out;
2790                                 }
2791                                 ret = ocfs2_xattr_ibody_set(inode, xi,
2792                                                             xis, ctxt);
2793                         }
2794                 }
2795         }
2796
2797         if (!ret) {
2798                 /* Update inode ctime. */
2799                 ret = ocfs2_journal_access_di(ctxt->handle, INODE_CACHE(inode),
2800                                               xis->inode_bh,
2801                                               OCFS2_JOURNAL_ACCESS_WRITE);
2802                 if (ret) {
2803                         mlog_errno(ret);
2804                         goto out;
2805                 }
2806
2807                 inode->i_ctime = CURRENT_TIME;
2808                 di->i_ctime = cpu_to_le64(inode->i_ctime.tv_sec);
2809                 di->i_ctime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
2810                 ocfs2_journal_dirty(ctxt->handle, xis->inode_bh);
2811         }
2812 out:
2813         return ret;
2814 }
2815
2816 /*
2817  * This function only called duing creating inode
2818  * for init security/acl xattrs of the new inode.
2819  * All transanction credits have been reserved in mknod.
2820  */
2821 int ocfs2_xattr_set_handle(handle_t *handle,
2822                            struct inode *inode,
2823                            struct buffer_head *di_bh,
2824                            int name_index,
2825                            const char *name,
2826                            const void *value,
2827                            size_t value_len,
2828                            int flags,
2829                            struct ocfs2_alloc_context *meta_ac,
2830                            struct ocfs2_alloc_context *data_ac)
2831 {
2832         struct ocfs2_dinode *di;
2833         int ret;
2834
2835         struct ocfs2_xattr_info xi = {
2836                 .name_index = name_index,
2837                 .name = name,
2838                 .value = value,
2839                 .value_len = value_len,
2840         };
2841
2842         struct ocfs2_xattr_search xis = {
2843                 .not_found = -ENODATA,
2844         };
2845
2846         struct ocfs2_xattr_search xbs = {
2847                 .not_found = -ENODATA,
2848         };
2849
2850         struct ocfs2_xattr_set_ctxt ctxt = {
2851                 .handle = handle,
2852                 .meta_ac = meta_ac,
2853                 .data_ac = data_ac,
2854         };
2855
2856         if (!ocfs2_supports_xattr(OCFS2_SB(inode->i_sb)))
2857                 return -EOPNOTSUPP;
2858
2859         /*
2860          * In extreme situation, may need xattr bucket when
2861          * block size is too small. And we have already reserved
2862          * the credits for bucket in mknod.
2863          */
2864         if (inode->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE) {
2865                 xbs.bucket = ocfs2_xattr_bucket_new(inode);
2866                 if (!xbs.bucket) {
2867                         mlog_errno(-ENOMEM);
2868                         return -ENOMEM;
2869                 }
2870         }
2871
2872         xis.inode_bh = xbs.inode_bh = di_bh;
2873         di = (struct ocfs2_dinode *)di_bh->b_data;
2874
2875         down_write(&OCFS2_I(inode)->ip_xattr_sem);
2876
2877         ret = ocfs2_xattr_ibody_find(inode, name_index, name, &xis);
2878         if (ret)
2879                 goto cleanup;
2880         if (xis.not_found) {
2881                 ret = ocfs2_xattr_block_find(inode, name_index, name, &xbs);
2882                 if (ret)
2883                         goto cleanup;
2884         }
2885
2886         ret = __ocfs2_xattr_set_handle(inode, di, &xi, &xis, &xbs, &ctxt);
2887
2888 cleanup:
2889         up_write(&OCFS2_I(inode)->ip_xattr_sem);
2890         brelse(xbs.xattr_bh);
2891         ocfs2_xattr_bucket_free(xbs.bucket);
2892
2893         return ret;
2894 }
2895
2896 /*
2897  * ocfs2_xattr_set()
2898  *
2899  * Set, replace or remove an extended attribute for this inode.
2900  * value is NULL to remove an existing extended attribute, else either
2901  * create or replace an extended attribute.
2902  */
2903 int ocfs2_xattr_set(struct inode *inode,
2904                     int name_index,
2905                     const char *name,
2906                     const void *value,
2907                     size_t value_len,
2908                     int flags)
2909 {
2910         struct buffer_head *di_bh = NULL;
2911         struct ocfs2_dinode *di;
2912         int ret, credits, ref_meta = 0, ref_credits = 0;
2913         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2914         struct inode *tl_inode = osb->osb_tl_inode;
2915         struct ocfs2_xattr_set_ctxt ctxt = { NULL, NULL, };
2916         struct ocfs2_refcount_tree *ref_tree = NULL;
2917
2918         struct ocfs2_xattr_info xi = {
2919                 .name_index = name_index,
2920                 .name = name,
2921                 .value = value,
2922                 .value_len = value_len,
2923         };
2924
2925         struct ocfs2_xattr_search xis = {
2926                 .not_found = -ENODATA,
2927         };
2928
2929         struct ocfs2_xattr_search xbs = {
2930                 .not_found = -ENODATA,
2931         };
2932
2933         if (!ocfs2_supports_xattr(OCFS2_SB(inode->i_sb)))
2934                 return -EOPNOTSUPP;
2935
2936         /*
2937          * Only xbs will be used on indexed trees.  xis doesn't need a
2938          * bucket.
2939          */
2940         xbs.bucket = ocfs2_xattr_bucket_new(inode);
2941         if (!xbs.bucket) {
2942                 mlog_errno(-ENOMEM);
2943                 return -ENOMEM;
2944         }
2945
2946         ret = ocfs2_inode_lock(inode, &di_bh, 1);
2947         if (ret < 0) {
2948                 mlog_errno(ret);
2949                 goto cleanup_nolock;
2950         }
2951         xis.inode_bh = xbs.inode_bh = di_bh;
2952         di = (struct ocfs2_dinode *)di_bh->b_data;
2953
2954         down_write(&OCFS2_I(inode)->ip_xattr_sem);
2955         /*
2956          * Scan inode and external block to find the same name
2957          * extended attribute and collect search infomation.
2958          */
2959         ret = ocfs2_xattr_ibody_find(inode, name_index, name, &xis);
2960         if (ret)
2961                 goto cleanup;
2962         if (xis.not_found) {
2963                 ret = ocfs2_xattr_block_find(inode, name_index, name, &xbs);
2964                 if (ret)
2965                         goto cleanup;
2966         }
2967
2968         if (xis.not_found && xbs.not_found) {
2969                 ret = -ENODATA;
2970                 if (flags & XATTR_REPLACE)
2971                         goto cleanup;
2972                 ret = 0;
2973                 if (!value)
2974                         goto cleanup;
2975         } else {
2976                 ret = -EEXIST;
2977                 if (flags & XATTR_CREATE)
2978                         goto cleanup;
2979         }
2980
2981         /* Check whether the value is refcounted and do some prepartion. */
2982         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL &&
2983             (!xis.not_found || !xbs.not_found)) {
2984                 ret = ocfs2_prepare_refcount_xattr(inode, di, &xi,
2985                                                    &xis, &xbs, &ref_tree,
2986                                                    &ref_meta, &ref_credits);
2987                 if (ret) {
2988                         mlog_errno(ret);
2989                         goto cleanup;
2990                 }
2991         }
2992
2993         mutex_lock(&tl_inode->i_mutex);
2994
2995         if (ocfs2_truncate_log_needs_flush(osb)) {
2996                 ret = __ocfs2_flush_truncate_log(osb);
2997                 if (ret < 0) {
2998                         mutex_unlock(&tl_inode->i_mutex);
2999                         mlog_errno(ret);
3000                         goto cleanup;
3001                 }
3002         }
3003         mutex_unlock(&tl_inode->i_mutex);
3004
3005         ret = ocfs2_init_xattr_set_ctxt(inode, di, &xi, &xis,
3006                                         &xbs, &ctxt, ref_meta, &credits);
3007         if (ret) {
3008                 mlog_errno(ret);
3009                 goto cleanup;
3010         }
3011
3012         /* we need to update inode's ctime field, so add credit for it. */
3013         credits += OCFS2_INODE_UPDATE_CREDITS;
3014         ctxt.handle = ocfs2_start_trans(osb, credits + ref_credits);
3015         if (IS_ERR(ctxt.handle)) {
3016                 ret = PTR_ERR(ctxt.handle);
3017                 mlog_errno(ret);
3018                 goto cleanup;
3019         }
3020
3021         ret = __ocfs2_xattr_set_handle(inode, di, &xi, &xis, &xbs, &ctxt);
3022
3023         ocfs2_commit_trans(osb, ctxt.handle);
3024
3025         if (ctxt.data_ac)
3026                 ocfs2_free_alloc_context(ctxt.data_ac);
3027         if (ctxt.meta_ac)
3028                 ocfs2_free_alloc_context(ctxt.meta_ac);
3029         if (ocfs2_dealloc_has_cluster(&ctxt.dealloc))
3030                 ocfs2_schedule_truncate_log_flush(osb, 1);
3031         ocfs2_run_deallocs(osb, &ctxt.dealloc);
3032
3033 cleanup:
3034         if (ref_tree)
3035                 ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
3036         up_write(&OCFS2_I(inode)->ip_xattr_sem);
3037         if (!value && !ret) {
3038                 ret = ocfs2_try_remove_refcount_tree(inode, di_bh);
3039                 if (ret)
3040                         mlog_errno(ret);
3041         }
3042         ocfs2_inode_unlock(inode, 1);
3043 cleanup_nolock:
3044         brelse(di_bh);
3045         brelse(xbs.xattr_bh);
3046         ocfs2_xattr_bucket_free(xbs.bucket);
3047
3048         return ret;
3049 }
3050
3051 /*
3052  * Find the xattr extent rec which may contains name_hash.
3053  * e_cpos will be the first name hash of the xattr rec.
3054  * el must be the ocfs2_xattr_header.xb_attrs.xb_root.xt_list.
3055  */
3056 static int ocfs2_xattr_get_rec(struct inode *inode,
3057                                u32 name_hash,
3058                                u64 *p_blkno,
3059                                u32 *e_cpos,
3060                                u32 *num_clusters,
3061                                struct ocfs2_extent_list *el)
3062 {
3063         int ret = 0, i;
3064         struct buffer_head *eb_bh = NULL;
3065         struct ocfs2_extent_block *eb;
3066         struct ocfs2_extent_rec *rec = NULL;
3067         u64 e_blkno = 0;
3068
3069         if (el->l_tree_depth) {
3070                 ret = ocfs2_find_leaf(INODE_CACHE(inode), el, name_hash,
3071                                       &eb_bh);
3072                 if (ret) {
3073                         mlog_errno(ret);
3074                         goto out;
3075                 }
3076
3077                 eb = (struct ocfs2_extent_block *) eb_bh->b_data;
3078                 el = &eb->h_list;
3079
3080                 if (el->l_tree_depth) {
3081                         ocfs2_error(inode->i_sb,
3082                                     "Inode %lu has non zero tree depth in "
3083                                     "xattr tree block %llu\n", inode->i_ino,
3084                                     (unsigned long long)eb_bh->b_blocknr);
3085                         ret = -EROFS;
3086                         goto out;
3087                 }
3088         }
3089
3090         for (i = le16_to_cpu(el->l_next_free_rec) - 1; i >= 0; i--) {
3091                 rec = &el->l_recs[i];
3092
3093                 if (le32_to_cpu(rec->e_cpos) <= name_hash) {
3094                         e_blkno = le64_to_cpu(rec->e_blkno);
3095                         break;
3096                 }
3097         }
3098
3099         if (!e_blkno) {
3100                 ocfs2_error(inode->i_sb, "Inode %lu has bad extent "
3101                             "record (%u, %u, 0) in xattr", inode->i_ino,
3102                             le32_to_cpu(rec->e_cpos),
3103                             ocfs2_rec_clusters(el, rec));
3104                 ret = -EROFS;
3105                 goto out;
3106         }
3107
3108         *p_blkno = le64_to_cpu(rec->e_blkno);
3109         *num_clusters = le16_to_cpu(rec->e_leaf_clusters);
3110         if (e_cpos)
3111                 *e_cpos = le32_to_cpu(rec->e_cpos);
3112 out:
3113         brelse(eb_bh);
3114         return ret;
3115 }
3116
3117 typedef int (xattr_bucket_func)(struct inode *inode,
3118                                 struct ocfs2_xattr_bucket *bucket,
3119                                 void *para);
3120
3121 static int ocfs2_find_xe_in_bucket(struct inode *inode,
3122                                    struct ocfs2_xattr_bucket *bucket,
3123                                    int name_index,
3124                                    const char *name,
3125                                    u32 name_hash,
3126                                    u16 *xe_index,
3127                                    int *found)
3128 {
3129         int i, ret = 0, cmp = 1, block_off, new_offset;
3130         struct ocfs2_xattr_header *xh = bucket_xh(bucket);
3131         size_t name_len = strlen(name);
3132         struct ocfs2_xattr_entry *xe = NULL;
3133         char *xe_name;
3134
3135         /*
3136          * We don't use binary search in the bucket because there
3137          * may be multiple entries with the same name hash.
3138          */
3139         for (i = 0; i < le16_to_cpu(xh->xh_count); i++) {
3140                 xe = &xh->xh_entries[i];
3141
3142                 if (name_hash > le32_to_cpu(xe->xe_name_hash))
3143                         continue;
3144                 else if (name_hash < le32_to_cpu(xe->xe_name_hash))
3145                         break;
3146
3147                 cmp = name_index - ocfs2_xattr_get_type(xe);
3148                 if (!cmp)
3149                         cmp = name_len - xe->xe_name_len;
3150                 if (cmp)
3151                         continue;
3152
3153                 ret = ocfs2_xattr_bucket_get_name_value(inode->i_sb,
3154                                                         xh,
3155                                                         i,
3156                                                         &block_off,
3157                                                         &new_offset);
3158                 if (ret) {
3159                         mlog_errno(ret);
3160                         break;
3161                 }
3162
3163
3164                 xe_name = bucket_block(bucket, block_off) + new_offset;
3165                 if (!memcmp(name, xe_name, name_len)) {
3166                         *xe_index = i;
3167                         *found = 1;
3168                         ret = 0;
3169                         break;
3170                 }
3171         }
3172
3173         return ret;
3174 }
3175
3176 /*
3177  * Find the specified xattr entry in a series of buckets.
3178  * This series start from p_blkno and last for num_clusters.
3179  * The ocfs2_xattr_header.xh_num_buckets of the first bucket contains
3180  * the num of the valid buckets.
3181  *
3182  * Return the buffer_head this xattr should reside in. And if the xattr's
3183  * hash is in the gap of 2 buckets, return the lower bucket.
3184  */
3185 static int ocfs2_xattr_bucket_find(struct inode *inode,
3186                                    int name_index,
3187                                    const char *name,
3188                                    u32 name_hash,
3189                                    u64 p_blkno,
3190                                    u32 first_hash,
3191                                    u32 num_clusters,
3192                                    struct ocfs2_xattr_search *xs)
3193 {
3194         int ret, found = 0;
3195         struct ocfs2_xattr_header *xh = NULL;
3196         struct ocfs2_xattr_entry *xe = NULL;
3197         u16 index = 0;
3198         u16 blk_per_bucket = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
3199         int low_bucket = 0, bucket, high_bucket;
3200         struct ocfs2_xattr_bucket *search;
3201         u32 last_hash;
3202         u64 blkno, lower_blkno = 0;
3203
3204         search = ocfs2_xattr_bucket_new(inode);
3205         if (!search) {
3206                 ret = -ENOMEM;
3207                 mlog_errno(ret);
3208                 goto out;
3209         }
3210
3211         ret = ocfs2_read_xattr_bucket(search, p_blkno);
3212         if (ret) {
3213                 mlog_errno(ret);
3214                 goto out;
3215         }
3216
3217         xh = bucket_xh(search);
3218         high_bucket = le16_to_cpu(xh->xh_num_buckets) - 1;
3219         while (low_bucket <= high_bucket) {
3220                 ocfs2_xattr_bucket_relse(search);
3221
3222                 bucket = (low_bucket + high_bucket) / 2;
3223                 blkno = p_blkno + bucket * blk_per_bucket;
3224                 ret = ocfs2_read_xattr_bucket(search, blkno);
3225                 if (ret) {
3226                         mlog_errno(ret);
3227                         goto out;
3228                 }
3229
3230                 xh = bucket_xh(search);
3231                 xe = &xh->xh_entries[0];
3232                 if (name_hash < le32_to_cpu(xe->xe_name_hash)) {
3233                         high_bucket = bucket - 1;
3234                         continue;
3235                 }
3236
3237                 /*
3238                  * Check whether the hash of the last entry in our
3239                  * bucket is larger than the search one. for an empty
3240                  * bucket, the last one is also the first one.
3241                  */
3242                 if (xh->xh_count)
3243                         xe = &xh->xh_entries[le16_to_cpu(xh->xh_count) - 1];
3244
3245                 last_hash = le32_to_cpu(xe->xe_name_hash);
3246
3247                 /* record lower_blkno which may be the insert place. */
3248                 lower_blkno = blkno;
3249
3250                 if (name_hash > le32_to_cpu(xe->xe_name_hash)) {
3251                         low_bucket = bucket + 1;
3252                         continue;
3253                 }
3254
3255                 /* the searched xattr should reside in this bucket if exists. */
3256                 ret = ocfs2_find_xe_in_bucket(inode, search,
3257                                               name_index, name, name_hash,
3258                                               &index, &found);
3259                 if (ret) {
3260                         mlog_errno(ret);
3261                         goto out;
3262                 }
3263                 break;
3264         }
3265
3266         /*
3267          * Record the bucket we have found.
3268          * When the xattr's hash value is in the gap of 2 buckets, we will
3269          * always set it to the previous bucket.
3270          */
3271         if (!lower_blkno)
3272                 lower_blkno = p_blkno;
3273
3274         /* This should be in cache - we just read it during the search */
3275         ret = ocfs2_read_xattr_bucket(xs->bucket, lower_blkno);
3276         if (ret) {
3277                 mlog_errno(ret);
3278                 goto out;
3279         }
3280
3281         xs->header = bucket_xh(xs->bucket);
3282         xs->base = bucket_block(xs->bucket, 0);
3283         xs->end = xs->base + inode->i_sb->s_blocksize;
3284
3285         if (found) {
3286                 xs->here = &xs->header->xh_entries[index];
3287                 mlog(0, "find xattr %s in bucket %llu, entry = %u\n", name,
3288                      (unsigned long long)bucket_blkno(xs->bucket), index);
3289         } else
3290                 ret = -ENODATA;
3291
3292 out:
3293         ocfs2_xattr_bucket_free(search);
3294         return ret;
3295 }
3296
3297 static int ocfs2_xattr_index_block_find(struct inode *inode,
3298                                         struct buffer_head *root_bh,
3299                                         int name_index,
3300                                         const char *name,
3301                                         struct ocfs2_xattr_search *xs)
3302 {
3303         int ret;
3304         struct ocfs2_xattr_block *xb =
3305                         (struct ocfs2_xattr_block *)root_bh->b_data;
3306         struct ocfs2_xattr_tree_root *xb_root = &xb->xb_attrs.xb_root;
3307         struct ocfs2_extent_list *el = &xb_root->xt_list;
3308         u64 p_blkno = 0;
3309         u32 first_hash, num_clusters = 0;
3310         u32 name_hash = ocfs2_xattr_name_hash(inode, name, strlen(name));
3311
3312         if (le16_to_cpu(el->l_next_free_rec) == 0)
3313                 return -ENODATA;
3314
3315         mlog(0, "find xattr %s, hash = %u, index = %d in xattr tree\n",
3316              name, name_hash, name_index);
3317
3318         ret = ocfs2_xattr_get_rec(inode, name_hash, &p_blkno, &first_hash,
3319                                   &num_clusters, el);
3320         if (ret) {
3321                 mlog_errno(ret);
3322                 goto out;
3323         }
3324
3325         BUG_ON(p_blkno == 0 || num_clusters == 0 || first_hash > name_hash);
3326
3327         mlog(0, "find xattr extent rec %u clusters from %llu, the first hash "
3328              "in the rec is %u\n", num_clusters, (unsigned long long)p_blkno,
3329              first_hash);
3330
3331         ret = ocfs2_xattr_bucket_find(inode, name_index, name, name_hash,
3332                                       p_blkno, first_hash, num_clusters, xs);
3333
3334 out:
3335         return ret;
3336 }
3337
3338 static int ocfs2_iterate_xattr_buckets(struct inode *inode,
3339                                        u64 blkno,
3340                                        u32 clusters,
3341                                        xattr_bucket_func *func,
3342                                        void *para)
3343 {
3344         int i, ret = 0;
3345         u32 bpc = ocfs2_xattr_buckets_per_cluster(OCFS2_SB(inode->i_sb));
3346         u32 num_buckets = clusters * bpc;
3347         struct ocfs2_xattr_bucket *bucket;
3348
3349         bucket = ocfs2_xattr_bucket_new(inode);
3350         if (!bucket) {
3351                 mlog_errno(-ENOMEM);
3352                 return -ENOMEM;
3353         }
3354
3355         mlog(0, "iterating xattr buckets in %u clusters starting from %llu\n",
3356              clusters, (unsigned long long)blkno);
3357
3358         for (i = 0; i < num_buckets; i++, blkno += bucket->bu_blocks) {
3359                 ret = ocfs2_read_xattr_bucket(bucket, blkno);
3360                 if (ret) {
3361                         mlog_errno(ret);
3362                         break;
3363                 }
3364
3365                 /*
3366                  * The real bucket num in this series of blocks is stored
3367                  * in the 1st bucket.
3368                  */
3369                 if (i == 0)
3370                         num_buckets = le16_to_cpu(bucket_xh(bucket)->xh_num_buckets);
3371
3372                 mlog(0, "iterating xattr bucket %llu, first hash %u\n",
3373                      (unsigned long long)blkno,
3374                      le32_to_cpu(bucket_xh(bucket)->xh_entries[0].xe_name_hash));
3375                 if (func) {
3376                         ret = func(inode, bucket, para);
3377                         if (ret && ret != -ERANGE)
3378                                 mlog_errno(ret);
3379                         /* Fall through to bucket_relse() */
3380                 }
3381
3382                 ocfs2_xattr_bucket_relse(bucket);
3383                 if (ret)
3384                         break;
3385         }
3386
3387         ocfs2_xattr_bucket_free(bucket);
3388         return ret;
3389 }
3390
3391 struct ocfs2_xattr_tree_list {
3392         char *buffer;
3393         size_t buffer_size;
3394         size_t result;
3395 };
3396
3397 static int ocfs2_xattr_bucket_get_name_value(struct super_block *sb,
3398                                              struct ocfs2_xattr_header *xh,
3399                                              int index,
3400                                              int *block_off,
3401                                              int *new_offset)
3402 {
3403         u16 name_offset;
3404
3405         if (index < 0 || index >= le16_to_cpu(xh->xh_count))
3406                 return -EINVAL;
3407
3408         name_offset = le16_to_cpu(xh->xh_entries[index].xe_name_offset);
3409
3410         *block_off = name_offset >> sb->s_blocksize_bits;
3411         *new_offset = name_offset % sb->s_blocksize;
3412
3413         return 0;
3414 }
3415
3416 static int ocfs2_list_xattr_bucket(struct inode *inode,
3417                                    struct ocfs2_xattr_bucket *bucket,
3418                                    void *para)
3419 {
3420         int ret = 0, type;
3421         struct ocfs2_xattr_tree_list *xl = (struct ocfs2_xattr_tree_list *)para;
3422         int i, block_off, new_offset;
3423         const char *prefix, *name;
3424
3425         for (i = 0 ; i < le16_to_cpu(bucket_xh(bucket)->xh_count); i++) {
3426                 struct ocfs2_xattr_entry *entry = &bucket_xh(bucket)->xh_entries[i];
3427                 type = ocfs2_xattr_get_type(entry);
3428                 prefix = ocfs2_xattr_prefix(type);
3429
3430                 if (prefix) {
3431                         ret = ocfs2_xattr_bucket_get_name_value(inode->i_sb,
3432                                                                 bucket_xh(bucket),
3433                                                                 i,
3434                                                                 &block_off,
3435                                                                 &new_offset);
3436                         if (ret)
3437                                 break;
3438
3439                         name = (const char *)bucket_block(bucket, block_off) +
3440                                 new_offset;
3441                         ret = ocfs2_xattr_list_entry(xl->buffer,
3442                                                      xl->buffer_size,
3443                                                      &xl->result,
3444                                                      prefix, name,
3445                                                      entry->xe_name_len);
3446                         if (ret)
3447                                 break;
3448                 }
3449         }
3450
3451         return ret;
3452 }
3453
3454 static int ocfs2_iterate_xattr_index_block(struct inode *inode,
3455                                            struct buffer_head *blk_bh,
3456                                            xattr_tree_rec_func *rec_func,
3457                                            void *para)
3458 {
3459         struct ocfs2_xattr_block *xb =
3460                         (struct ocfs2_xattr_block *)blk_bh->b_data;
3461         struct ocfs2_extent_list *el = &xb->xb_attrs.xb_root.xt_list;
3462         int ret = 0;
3463         u32 name_hash = UINT_MAX, e_cpos = 0, num_clusters = 0;
3464         u64 p_blkno = 0;
3465
3466         if (!el->l_next_free_rec || !rec_func)
3467                 return 0;
3468
3469         while (name_hash > 0) {
3470                 ret = ocfs2_xattr_get_rec(inode, name_hash, &p_blkno,
3471                                           &e_cpos, &num_clusters, el);
3472                 if (ret) {
3473                         mlog_errno(ret);
3474                         break;
3475                 }
3476
3477                 ret = rec_func(inode, blk_bh, p_blkno, e_cpos,
3478                                num_clusters, para);
3479                 if (ret) {
3480                         if (ret != -ERANGE)
3481                                 mlog_errno(ret);
3482                         break;
3483                 }
3484
3485                 if (e_cpos == 0)
3486                         break;
3487
3488                 name_hash = e_cpos - 1;
3489         }
3490
3491         return ret;
3492
3493 }
3494
3495 static int ocfs2_list_xattr_tree_rec(struct inode *inode,
3496                                      struct buffer_head *root_bh,
3497                                      u64 blkno, u32 cpos, u32 len, void *para)
3498 {
3499         return ocfs2_iterate_xattr_buckets(inode, blkno, len,
3500                                            ocfs2_list_xattr_bucket, para);
3501 }
3502
3503 static int ocfs2_xattr_tree_list_index_block(struct inode *inode,
3504                                              struct buffer_head *blk_bh,
3505                                              char *buffer,
3506                                              size_t buffer_size)
3507 {
3508         int ret;
3509         struct ocfs2_xattr_tree_list xl = {
3510                 .buffer = buffer,
3511                 .buffer_size = buffer_size,
3512                 .result = 0,
3513         };
3514
3515         ret = ocfs2_iterate_xattr_index_block(inode, blk_bh,
3516                                               ocfs2_list_xattr_tree_rec, &xl);
3517         if (ret) {
3518                 mlog_errno(ret);
3519                 goto out;
3520         }
3521
3522         ret = xl.result;
3523 out:
3524         return ret;
3525 }
3526
3527 static int cmp_xe(const void *a, const void *b)
3528 {
3529         const struct ocfs2_xattr_entry *l = a, *r = b;
3530         u32 l_hash = le32_to_cpu(l->xe_name_hash);
3531         u32 r_hash = le32_to_cpu(r->xe_name_hash);
3532
3533         if (l_hash > r_hash)
3534                 return 1;
3535         if (l_hash < r_hash)
3536                 return -1;
3537         return 0;
3538 }
3539
3540 static void swap_xe(void *a, void *b, int size)
3541 {
3542         struct ocfs2_xattr_entry *l = a, *r = b, tmp;
3543
3544         tmp = *l;
3545         memcpy(l, r, sizeof(struct ocfs2_xattr_entry));
3546         memcpy(r, &tmp, sizeof(struct ocfs2_xattr_entry));
3547 }
3548
3549 /*
3550  * When the ocfs2_xattr_block is filled up, new bucket will be created
3551  * and all the xattr entries will be moved to the new bucket.
3552  * The header goes at the start of the bucket, and the names+values are
3553  * filled from the end.  This is why *target starts as the last buffer.
3554  * Note: we need to sort the entries since they are not saved in order
3555  * in the ocfs2_xattr_block.
3556  */
3557 static void ocfs2_cp_xattr_block_to_bucket(struct inode *inode,
3558                                            struct buffer_head *xb_bh,
3559                                            struct ocfs2_xattr_bucket *bucket)
3560 {
3561         int i, blocksize = inode->i_sb->s_blocksize;
3562         int blks = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
3563         u16 offset, size, off_change;
3564         struct ocfs2_xattr_entry *xe;
3565         struct ocfs2_xattr_block *xb =
3566                                 (struct ocfs2_xattr_block *)xb_bh->b_data;
3567         struct ocfs2_xattr_header *xb_xh = &xb->xb_attrs.xb_header;
3568         struct ocfs2_xattr_header *xh = bucket_xh(bucket);
3569         u16 count = le16_to_cpu(xb_xh->xh_count);
3570         char *src = xb_bh->b_data;
3571         char *target = bucket_block(bucket, blks - 1);
3572
3573         mlog(0, "cp xattr from block %llu to bucket %llu\n",
3574              (unsigned long long)xb_bh->b_blocknr,
3575              (unsigned long long)bucket_blkno(bucket));
3576
3577         for (i = 0; i < blks; i++)
3578                 memset(bucket_block(bucket, i), 0, blocksize);
3579
3580         /*
3581          * Since the xe_name_offset is based on ocfs2_xattr_header,
3582          * there is a offset change corresponding to the change of
3583          * ocfs2_xattr_header's position.
3584          */
3585         off_change = offsetof(struct ocfs2_xattr_block, xb_attrs.xb_header);
3586         xe = &xb_xh->xh_entries[count - 1];
3587         offset = le16_to_cpu(xe->xe_name_offset) + off_change;
3588         size = blocksize - offset;
3589
3590         /* copy all the names and values. */
3591         memcpy(target + offset, src + offset, size);
3592
3593         /* Init new header now. */
3594         xh->xh_count = xb_xh->xh_count;
3595         xh->xh_num_buckets = cpu_to_le16(1);
3596         xh->xh_name_value_len = cpu_to_le16(size);
3597         xh->xh_free_start = cpu_to_le16(OCFS2_XATTR_BUCKET_SIZE - size);
3598
3599         /* copy all the entries. */
3600         target = bucket_block(bucket, 0);
3601         offset = offsetof(struct ocfs2_xattr_header, xh_entries);
3602         size = count * sizeof(struct ocfs2_xattr_entry);
3603         memcpy(target + offset, (char *)xb_xh + offset, size);
3604
3605         /* Change the xe offset for all the xe because of the move. */
3606         off_change = OCFS2_XATTR_BUCKET_SIZE - blocksize +
3607                  offsetof(struct ocfs2_xattr_block, xb_attrs.xb_header);
3608         for (i = 0; i < count; i++)
3609                 le16_add_cpu(&xh->xh_entries[i].xe_name_offset, off_change);
3610
3611         mlog(0, "copy entry: start = %u, size = %u, offset_change = %u\n",
3612              offset, size, off_change);
3613
3614         sort(target + offset, count, sizeof(struct ocfs2_xattr_entry),
3615              cmp_xe, swap_xe);
3616 }
3617
3618 /*
3619  * After we move xattr from block to index btree, we have to
3620  * update ocfs2_xattr_search to the new xe and base.
3621  *
3622  * When the entry is in xattr block, xattr_bh indicates the storage place.
3623  * While if the entry is in index b-tree, "bucket" indicates the
3624  * real place of the xattr.
3625  */
3626 static void ocfs2_xattr_update_xattr_search(struct inode *inode,
3627                                             struct ocfs2_xattr_search *xs,
3628                                             struct buffer_head *old_bh)
3629 {
3630         char *buf = old_bh->b_data;
3631         struct ocfs2_xattr_block *old_xb = (struct ocfs2_xattr_block *)buf;
3632         struct ocfs2_xattr_header *old_xh = &old_xb->xb_attrs.xb_header;
3633         int i;
3634
3635         xs->header = bucket_xh(xs->bucket);
3636         xs->base = bucket_block(xs->bucket, 0);
3637         xs->end = xs->base + inode->i_sb->s_blocksize;
3638
3639         if (xs->not_found)
3640                 return;
3641
3642         i = xs->here - old_xh->xh_entries;
3643         xs->here = &xs->header->xh_entries[i];
3644 }
3645
3646 static int ocfs2_xattr_create_index_block(struct inode *inode,
3647                                           struct ocfs2_xattr_search *xs,
3648                                           struct ocfs2_xattr_set_ctxt *ctxt)
3649 {
3650         int ret;
3651         u32 bit_off, len;
3652         u64 blkno;
3653         handle_t *handle = ctxt->handle;
3654         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3655         struct ocfs2_inode_info *oi = OCFS2_I(inode);
3656         struct buffer_head *xb_bh = xs->xattr_bh;
3657         struct ocfs2_xattr_block *xb =
3658                         (struct ocfs2_xattr_block *)xb_bh->b_data;
3659         struct ocfs2_xattr_tree_root *xr;
3660         u16 xb_flags = le16_to_cpu(xb->xb_flags);
3661
3662         mlog(0, "create xattr index block for %llu\n",
3663              (unsigned long long)xb_bh->b_blocknr);
3664
3665         BUG_ON(xb_flags & OCFS2_XATTR_INDEXED);
3666         BUG_ON(!xs->bucket);
3667
3668         /*
3669          * XXX:
3670          * We can use this lock for now, and maybe move to a dedicated mutex
3671          * if performance becomes a problem later.
3672          */
3673         down_write(&oi->ip_alloc_sem);
3674
3675         ret = ocfs2_journal_access_xb(handle, INODE_CACHE(inode), xb_bh,
3676                                       OCFS2_JOURNAL_ACCESS_WRITE);
3677         if (ret) {
3678                 mlog_errno(ret);
3679                 goto out;
3680         }
3681
3682         ret = __ocfs2_claim_clusters(osb, handle, ctxt->data_ac,
3683                                      1, 1, &bit_off, &len);
3684         if (ret) {
3685                 mlog_errno(ret);
3686                 goto out;
3687         }
3688
3689         /*
3690          * The bucket may spread in many blocks, and
3691          * we will only touch the 1st block and the last block
3692          * in the whole bucket(one for entry and one for data).
3693          */
3694         blkno = ocfs2_clusters_to_blocks(inode->i_sb, bit_off);
3695
3696         mlog(0, "allocate 1 cluster from %llu to xattr block\n",
3697              (unsigned long long)blkno);
3698
3699         ret = ocfs2_init_xattr_bucket(xs->bucket, blkno);
3700         if (ret) {
3701                 mlog_errno(ret);
3702                 goto out;
3703         }
3704
3705         ret = ocfs2_xattr_bucket_journal_access(handle, xs->bucket,
3706                                                 OCFS2_JOURNAL_ACCESS_CREATE);
3707         if (ret) {
3708                 mlog_errno(ret);
3709                 goto out;
3710         }
3711
3712         ocfs2_cp_xattr_block_to_bucket(inode, xb_bh, xs->bucket);
3713         ocfs2_xattr_bucket_journal_dirty(handle, xs->bucket);
3714
3715         ocfs2_xattr_update_xattr_search(inode, xs, xb_bh);
3716
3717         /* Change from ocfs2_xattr_header to ocfs2_xattr_tree_root */
3718         memset(&xb->xb_attrs, 0, inode->i_sb->s_blocksize -
3719                offsetof(struct ocfs2_xattr_block, xb_attrs));
3720
3721         xr = &xb->xb_attrs.xb_root;
3722         xr->xt_clusters = cpu_to_le32(1);
3723         xr->xt_last_eb_blk = 0;
3724         xr->xt_list.l_tree_depth = 0;
3725         xr->xt_list.l_count = cpu_to_le16(ocfs2_xattr_recs_per_xb(inode->i_sb));
3726         xr->xt_list.l_next_free_rec = cpu_to_le16(1);
3727
3728         xr->xt_list.l_recs[0].e_cpos = 0;
3729         xr->xt_list.l_recs[0].e_blkno = cpu_to_le64(blkno);
3730         xr->xt_list.l_recs[0].e_leaf_clusters = cpu_to_le16(1);
3731
3732         xb->xb_flags = cpu_to_le16(xb_flags | OCFS2_XATTR_INDEXED);
3733
3734         ocfs2_journal_dirty(handle, xb_bh);
3735
3736 out:
3737         up_write(&oi->ip_alloc_sem);
3738
3739         return ret;
3740 }
3741
3742 static int cmp_xe_offset(const void *a, const void *b)
3743 {
3744         const struct ocfs2_xattr_entry *l = a, *r = b;
3745         u32 l_name_offset = le16_to_cpu(l->xe_name_offset);
3746         u32 r_name_offset = le16_to_cpu(r->xe_name_offset);
3747
3748         if (l_name_offset < r_name_offset)
3749                 return 1;
3750         if (l_name_offset > r_name_offset)
3751                 return -1;
3752         return 0;
3753 }
3754
3755 /*
3756  * defrag a xattr bucket if we find that the bucket has some
3757  * holes beteen name/value pairs.
3758  * We will move all the name/value pairs to the end of the bucket
3759  * so that we can spare some space for insertion.
3760  */
3761 static int ocfs2_defrag_xattr_bucket(struct inode *inode,
3762                                      handle_t *handle,
3763                                      struct ocfs2_xattr_bucket *bucket)
3764 {
3765         int ret, i;
3766         size_t end, offset, len, value_len;
3767         struct ocfs2_xattr_header *xh;
3768         char *entries, *buf, *bucket_buf = NULL;
3769         u64 blkno = bucket_blkno(bucket);
3770         u16 xh_free_start;
3771         size_t blocksize = inode->i_sb->s_blocksize;
3772         struct ocfs2_xattr_entry *xe;
3773
3774         /*
3775          * In order to make the operation more efficient and generic,
3776          * we copy all the blocks into a contiguous memory and do the
3777          * defragment there, so if anything is error, we will not touch
3778          * the real block.
3779          */
3780         bucket_buf = kmalloc(OCFS2_XATTR_BUCKET_SIZE, GFP_NOFS);
3781         if (!bucket_buf) {
3782                 ret = -EIO;
3783                 goto out;
3784         }
3785
3786         buf = bucket_buf;
3787         for (i = 0; i < bucket->bu_blocks; i++, buf += blocksize)
3788                 memcpy(buf, bucket_block(bucket, i), blocksize);
3789
3790         ret = ocfs2_xattr_bucket_journal_access(handle, bucket,
3791                                                 OCFS2_JOURNAL_ACCESS_WRITE);
3792         if (ret < 0) {
3793                 mlog_errno(ret);
3794                 goto out;
3795         }
3796
3797         xh = (struct ocfs2_xattr_header *)bucket_buf;
3798         entries = (char *)xh->xh_entries;
3799         xh_free_start = le16_to_cpu(xh->xh_free_start);
3800
3801         mlog(0, "adjust xattr bucket in %llu, count = %u, "
3802              "xh_free_start = %u, xh_name_value_len = %u.\n",
3803              (unsigned long long)blkno, le16_to_cpu(xh->xh_count),
3804              xh_free_start, le16_to_cpu(xh->xh_name_value_len));
3805
3806         /*
3807          * sort all the entries by their offset.
3808          * the largest will be the first, so that we can
3809          * move them to the end one by one.
3810          */
3811         sort(entries, le16_to_cpu(xh->xh_count),
3812              sizeof(struct ocfs2_xattr_entry),
3813              cmp_xe_offset, swap_xe);
3814
3815         /* Move all name/values to the end of the bucket. */
3816         xe = xh->xh_entries;
3817         end = OCFS2_XATTR_BUCKET_SIZE;
3818         for (i = 0; i < le16_to_cpu(xh->xh_count); i++, xe++) {
3819                 offset = le16_to_cpu(xe->xe_name_offset);
3820                 if (ocfs2_xattr_is_local(xe))
3821                         value_len = OCFS2_XATTR_SIZE(
3822                                         le64_to_cpu(xe->xe_value_size));
3823                 else
3824                         value_len = OCFS2_XATTR_ROOT_SIZE;
3825                 len = OCFS2_XATTR_SIZE(xe->xe_name_len) + value_len;
3826
3827                 /*
3828                  * We must make sure that the name/value pair
3829                  * exist in the same block. So adjust end to
3830                  * the previous block end if needed.
3831                  */
3832                 if (((end - len) / blocksize !=
3833                         (end - 1) / blocksize))
3834                         end = end - end % blocksize;
3835
3836                 if (end > offset + len) {
3837                         memmove(bucket_buf + end - len,
3838                                 bucket_buf + offset, len);
3839                         xe->xe_name_offset = cpu_to_le16(end - len);
3840                 }
3841
3842                 mlog_bug_on_msg(end < offset + len, "Defrag check failed for "
3843                                 "bucket %llu\n", (unsigned long long)blkno);
3844
3845                 end -= len;
3846         }
3847
3848         mlog_bug_on_msg(xh_free_start > end, "Defrag check failed for "
3849                         "bucket %llu\n", (unsigned long long)blkno);
3850
3851         if (xh_free_start == end)
3852                 goto out;
3853
3854         memset(bucket_buf + xh_free_start, 0, end - xh_free_start);
3855         xh->xh_free_start = cpu_to_le16(end);
3856
3857         /* sort the entries by their name_hash. */
3858         sort(entries, le16_to_cpu(xh->xh_count),
3859              sizeof(struct ocfs2_xattr_entry),
3860              cmp_xe, swap_xe);
3861
3862         buf = bucket_buf;
3863         for (i = 0; i < bucket->bu_blocks; i++, buf += blocksize)
3864                 memcpy(bucket_block(bucket, i), buf, blocksize);
3865         ocfs2_xattr_bucket_journal_dirty(handle, bucket);
3866
3867 out:
3868         kfree(bucket_buf);
3869         return ret;
3870 }
3871
3872 /*
3873  * prev_blkno points to the start of an existing extent.  new_blkno
3874  * points to a newly allocated extent.  Because we know each of our
3875  * clusters contains more than bucket, we can easily split one cluster
3876  * at a bucket boundary.  So we take the last cluster of the existing
3877  * extent and split it down the middle.  We move the last half of the
3878  * buckets in the last cluster of the existing extent over to the new
3879  * extent.
3880  *
3881  * first_bh is the buffer at prev_blkno so we can update the existing
3882  * extent's bucket count.  header_bh is the bucket were we were hoping
3883  * to insert our xattr.  If the bucket move places the target in the new
3884  * extent, we'll update first_bh and header_bh after modifying the old
3885  * extent.
3886  *
3887  * first_hash will be set as the 1st xe's name_hash in the new extent.
3888  */
3889 static int ocfs2_mv_xattr_bucket_cross_cluster(struct inode *inode,
3890                                                handle_t *handle,
3891                                                struct ocfs2_xattr_bucket *first,
3892                                                struct ocfs2_xattr_bucket *target,
3893                                                u64 new_blkno,
3894                                                u32 num_clusters,
3895                                                u32 *first_hash)
3896 {
3897         int ret;
3898         struct super_block *sb = inode->i_sb;
3899         int blks_per_bucket = ocfs2_blocks_per_xattr_bucket(sb);
3900         int num_buckets = ocfs2_xattr_buckets_per_cluster(OCFS2_SB(sb));
3901         int to_move = num_buckets / 2;
3902         u64 src_blkno;
3903         u64 last_cluster_blkno = bucket_blkno(first) +
3904                 ((num_clusters - 1) * ocfs2_clusters_to_blocks(sb, 1));
3905
3906         BUG_ON(le16_to_cpu(bucket_xh(first)->xh_num_buckets) < num_buckets);
3907         BUG_ON(OCFS2_XATTR_BUCKET_SIZE == OCFS2_SB(sb)->s_clustersize);
3908
3909         mlog(0, "move half of xattrs in cluster %llu to %llu\n",
3910              (unsigned long long)last_cluster_blkno, (unsigned long long)new_blkno);
3911
3912         ret = ocfs2_mv_xattr_buckets(inode, handle, bucket_blkno(first),
3913                                      last_cluster_blkno, new_blkno,
3914                                      to_move, first_hash);
3915         if (ret) {
3916                 mlog_errno(ret);
3917                 goto out;
3918         }
3919
3920         /* This is the first bucket that got moved */
3921         src_blkno = last_cluster_blkno + (to_move * blks_per_bucket);
3922
3923         /*
3924          * If the target bucket was part of the moved buckets, we need to
3925          * update first and target.
3926          */
3927         if (bucket_blkno(target) >= src_blkno) {
3928                 /* Find the block for the new target bucket */
3929                 src_blkno = new_blkno +
3930                         (bucket_blkno(target) - src_blkno);
3931
3932                 ocfs2_xattr_bucket_relse(first);
3933                 ocfs2_xattr_bucket_relse(target);
3934
3935                 /*
3936                  * These shouldn't fail - the buffers are in the
3937                  * journal from ocfs2_cp_xattr_bucket().
3938                  */
3939                 ret = ocfs2_read_xattr_bucket(first, new_blkno);
3940                 if (ret) {
3941                         mlog_errno(ret);
3942                         goto out;
3943                 }
3944                 ret = ocfs2_read_xattr_bucket(target, src_blkno);
3945                 if (ret)
3946                         mlog_errno(ret);
3947
3948         }
3949
3950 out:
3951         return ret;
3952 }
3953
3954 /*
3955  * Find the suitable pos when we divide a bucket into 2.
3956  * We have to make sure the xattrs with the same hash value exist
3957  * in the same bucket.
3958  *
3959  * If this ocfs2_xattr_header covers more than one hash value, find a
3960  * place where the hash value changes.  Try to find the most even split.
3961  * The most common case is that all entries have different hash values,
3962  * and the first check we make will find a place to split.
3963  */
3964 static int ocfs2_xattr_find_divide_pos(struct ocfs2_xattr_header *xh)
3965 {
3966         struct ocfs2_xattr_entry *entries = xh->xh_entries;
3967         int count = le16_to_cpu(xh->xh_count);
3968         int delta, middle = count / 2;
3969
3970         /*
3971          * We start at the middle.  Each step gets farther away in both
3972          * directions.  We therefore hit the change in hash value
3973          * nearest to the middle.  Note that this loop does not execute for
3974          * count < 2.
3975          */
3976         for (delta = 0; delta < middle; delta++) {
3977                 /* Let's check delta earlier than middle */
3978                 if (cmp_xe(&entries[middle - delta - 1],
3979                            &entries[middle - delta]))
3980                         return middle - delta;
3981
3982                 /* For even counts, don't walk off the end */
3983                 if ((middle + delta + 1) == count)
3984                         continue;
3985
3986                 /* Now try delta past middle */
3987                 if (cmp_xe(&entries[middle + delta],
3988                            &entries[middle + delta + 1]))
3989                         return middle + delta + 1;
3990         }
3991
3992         /* Every entry had the same hash */
3993         return count;
3994 }
3995
3996 /*
3997  * Move some xattrs in old bucket(blk) to new bucket(new_blk).
3998  * first_hash will record the 1st hash of the new bucket.
3999  *
4000  * Normally half of the xattrs will be moved.  But we have to make
4001  * sure that the xattrs with the same hash value are stored in the
4002  * same bucket. If all the xattrs in this bucket have the same hash
4003  * value, the new bucket will be initialized as an empty one and the
4004  * first_hash will be initialized as (hash_value+1).
4005  */
4006 static int ocfs2_divide_xattr_bucket(struct inode *inode,
4007                                     handle_t *handle,
4008                                     u64 blk,
4009                                     u64 new_blk,
4010                                     u32 *first_hash,
4011                                     int new_bucket_head)
4012 {
4013         int ret, i;
4014         int count, start, len, name_value_len = 0, xe_len, name_offset = 0;
4015         struct ocfs2_xattr_bucket *s_bucket = NULL, *t_bucket = NULL;
4016         struct ocfs2_xattr_header *xh;
4017         struct ocfs2_xattr_entry *xe;
4018         int blocksize = inode->i_sb->s_blocksize;
4019
4020         mlog(0, "move some of xattrs from bucket %llu to %llu\n",
4021              (unsigned long long)blk, (unsigned long long)new_blk);
4022
4023         s_bucket = ocfs2_xattr_bucket_new(inode);
4024         t_bucket = ocfs2_xattr_bucket_new(inode);
4025         if (!s_bucket || !t_bucket) {
4026                 ret = -ENOMEM;
4027                 mlog_errno(ret);
4028                 goto out;
4029         }
4030
4031         ret = ocfs2_read_xattr_bucket(s_bucket, blk);
4032         if (ret) {
4033                 mlog_errno(ret);
4034                 goto out;
4035         }
4036
4037         ret = ocfs2_xattr_bucket_journal_access(handle, s_bucket,
4038                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4039         if (ret) {
4040                 mlog_errno(ret);
4041                 goto out;
4042         }
4043
4044         /*
4045          * Even if !new_bucket_head, we're overwriting t_bucket.  Thus,
4046          * there's no need to read it.
4047          */
4048         ret = ocfs2_init_xattr_bucket(t_bucket, new_blk);
4049         if (ret) {
4050                 mlog_errno(ret);
4051                 goto out;
4052         }
4053
4054         /*
4055          * Hey, if we're overwriting t_bucket, what difference does
4056          * ACCESS_CREATE vs ACCESS_WRITE make?  See the comment in the
4057          * same part of ocfs2_cp_xattr_bucket().
4058          */
4059         ret = ocfs2_xattr_bucket_journal_access(handle, t_bucket,
4060                                                 new_bucket_head ?
4061                                                 OCFS2_JOURNAL_ACCESS_CREATE :
4062                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4063         if (ret) {
4064                 mlog_errno(ret);
4065                 goto out;
4066         }
4067
4068         xh = bucket_xh(s_bucket);
4069         count = le16_to_cpu(xh->xh_count);
4070         start = ocfs2_xattr_find_divide_pos(xh);
4071
4072         if (start == count) {
4073                 xe = &xh->xh_entries[start-1];
4074
4075                 /*
4076                  * initialized a new empty bucket here.
4077                  * The hash value is set as one larger than
4078                  * that of the last entry in the previous bucket.
4079                  */
4080                 for (i = 0; i < t_bucket->bu_blocks; i++)
4081                         memset(bucket_block(t_bucket, i), 0, blocksize);
4082
4083                 xh = bucket_xh(t_bucket);
4084                 xh->xh_free_start = cpu_to_le16(blocksize);
4085                 xh->xh_entries[0].xe_name_hash = xe->xe_name_hash;
4086                 le32_add_cpu(&xh->xh_entries[0].xe_name_hash, 1);
4087
4088                 goto set_num_buckets;
4089         }
4090
4091         /* copy the whole bucket to the new first. */
4092         ocfs2_xattr_bucket_copy_data(t_bucket, s_bucket);
4093
4094         /* update the new bucket. */
4095         xh = bucket_xh(t_bucket);
4096
4097         /*
4098          * Calculate the total name/value len and xh_free_start for
4099          * the old bucket first.
4100          */
4101         name_offset = OCFS2_XATTR_BUCKET_SIZE;
4102         name_value_len = 0;
4103         for (i = 0; i < start; i++) {
4104                 xe = &xh->xh_entries[i];
4105                 xe_len = OCFS2_XATTR_SIZE(xe->xe_name_len);
4106                 if (ocfs2_xattr_is_local(xe))
4107                         xe_len +=
4108                            OCFS2_XATTR_SIZE(le64_to_cpu(xe->xe_value_size));
4109                 else
4110                         xe_len += OCFS2_XATTR_ROOT_SIZE;
4111                 name_value_len += xe_len;
4112                 if (le16_to_cpu(xe->xe_name_offset) < name_offset)
4113                         name_offset = le16_to_cpu(xe->xe_name_offset);
4114         }
4115
4116         /*
4117          * Now begin the modification to the new bucket.
4118          *
4119          * In the new bucket, We just move the xattr entry to the beginning
4120          * and don't touch the name/value. So there will be some holes in the
4121          * bucket, and they will be removed when ocfs2_defrag_xattr_bucket is
4122          * called.
4123          */
4124         xe = &xh->xh_entries[start];
4125         len = sizeof(struct ocfs2_xattr_entry) * (count - start);
4126         mlog(0, "mv xattr entry len %d from %d to %d\n", len,
4127              (int)((char *)xe - (char *)xh),
4128              (int)((char *)xh->xh_entries - (char *)xh));
4129         memmove((char *)xh->xh_entries, (char *)xe, len);
4130         xe = &xh->xh_entries[count - start];
4131         len = sizeof(struct ocfs2_xattr_entry) * start;
4132         memset((char *)xe, 0, len);
4133
4134         le16_add_cpu(&xh->xh_count, -start);
4135         le16_add_cpu(&xh->xh_name_value_len, -name_value_len);
4136
4137         /* Calculate xh_free_start for the new bucket. */
4138         xh->xh_free_start = cpu_to_le16(OCFS2_XATTR_BUCKET_SIZE);
4139         for (i = 0; i < le16_to_cpu(xh->xh_count); i++) {
4140                 xe = &xh->xh_entries[i];
4141                 xe_len = OCFS2_XATTR_SIZE(xe->xe_name_len);
4142                 if (ocfs2_xattr_is_local(xe))
4143                         xe_len +=
4144                            OCFS2_XATTR_SIZE(le64_to_cpu(xe->xe_value_size));
4145                 else
4146                         xe_len += OCFS2_XATTR_ROOT_SIZE;
4147                 if (le16_to_cpu(xe->xe_name_offset) <
4148                     le16_to_cpu(xh->xh_free_start))
4149                         xh->xh_free_start = xe->xe_name_offset;
4150         }
4151
4152 set_num_buckets:
4153         /* set xh->xh_num_buckets for the new xh. */
4154         if (new_bucket_head)
4155                 xh->xh_num_buckets = cpu_to_le16(1);
4156         else
4157                 xh->xh_num_buckets = 0;
4158
4159         ocfs2_xattr_bucket_journal_dirty(handle, t_bucket);
4160
4161         /* store the first_hash of the new bucket. */
4162         if (first_hash)
4163                 *first_hash = le32_to_cpu(xh->xh_entries[0].xe_name_hash);
4164
4165         /*
4166          * Now only update the 1st block of the old bucket.  If we
4167          * just added a new empty bucket, there is no need to modify
4168          * it.
4169          */
4170         if (start == count)
4171                 goto out;
4172
4173         xh = bucket_xh(s_bucket);
4174         memset(&xh->xh_entries[start], 0,
4175                sizeof(struct ocfs2_xattr_entry) * (count - start));
4176         xh->xh_count = cpu_to_le16(start);
4177         xh->xh_free_start = cpu_to_le16(name_offset);
4178         xh->xh_name_value_len = cpu_to_le16(name_value_len);
4179
4180         ocfs2_xattr_bucket_journal_dirty(handle, s_bucket);
4181
4182 out:
4183         ocfs2_xattr_bucket_free(s_bucket);
4184         ocfs2_xattr_bucket_free(t_bucket);
4185
4186         return ret;
4187 }
4188
4189 /*
4190  * Copy xattr from one bucket to another bucket.
4191  *
4192  * The caller must make sure that the journal transaction
4193  * has enough space for journaling.
4194  */
4195 static int ocfs2_cp_xattr_bucket(struct inode *inode,
4196                                  handle_t *handle,
4197                                  u64 s_blkno,
4198                                  u64 t_blkno,
4199                                  int t_is_new)
4200 {
4201         int ret;
4202         struct ocfs2_xattr_bucket *s_bucket = NULL, *t_bucket = NULL;
4203
4204         BUG_ON(s_blkno == t_blkno);
4205
4206         mlog(0, "cp bucket %llu to %llu, target is %d\n",
4207              (unsigned long long)s_blkno, (unsigned long long)t_blkno,
4208              t_is_new);
4209
4210         s_bucket = ocfs2_xattr_bucket_new(inode);
4211         t_bucket = ocfs2_xattr_bucket_new(inode);
4212         if (!s_bucket || !t_bucket) {
4213                 ret = -ENOMEM;
4214                 mlog_errno(ret);
4215                 goto out;
4216         }
4217
4218         ret = ocfs2_read_xattr_bucket(s_bucket, s_blkno);
4219         if (ret)
4220                 goto out;
4221
4222         /*
4223          * Even if !t_is_new, we're overwriting t_bucket.  Thus,
4224          * there's no need to read it.
4225          */
4226         ret = ocfs2_init_xattr_bucket(t_bucket, t_blkno);
4227         if (ret)
4228                 goto out;
4229
4230         /*
4231          * Hey, if we're overwriting t_bucket, what difference does
4232          * ACCESS_CREATE vs ACCESS_WRITE make?  Well, if we allocated a new
4233          * cluster to fill, we came here from
4234          * ocfs2_mv_xattr_buckets(), and it is really new -
4235          * ACCESS_CREATE is required.  But we also might have moved data
4236          * out of t_bucket before extending back into it.
4237          * ocfs2_add_new_xattr_bucket() can do this - its call to
4238          * ocfs2_add_new_xattr_cluster() may have created a new extent
4239          * and copied out the end of the old extent.  Then it re-extends
4240          * the old extent back to create space for new xattrs.  That's
4241          * how we get here, and the bucket isn't really new.
4242          */
4243         ret = ocfs2_xattr_bucket_journal_access(handle, t_bucket,
4244                                                 t_is_new ?
4245                                                 OCFS2_JOURNAL_ACCESS_CREATE :
4246                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4247         if (ret)
4248                 goto out;
4249
4250         ocfs2_xattr_bucket_copy_data(t_bucket, s_bucket);
4251         ocfs2_xattr_bucket_journal_dirty(handle, t_bucket);
4252
4253 out:
4254         ocfs2_xattr_bucket_free(t_bucket);
4255         ocfs2_xattr_bucket_free(s_bucket);
4256
4257         return ret;
4258 }
4259
4260 /*
4261  * src_blk points to the start of an existing extent.  last_blk points to
4262  * last cluster in that extent.  to_blk points to a newly allocated
4263  * extent.  We copy the buckets from the cluster at last_blk to the new
4264  * extent.  If start_bucket is non-zero, we skip that many buckets before
4265  * we start copying.  The new extent's xh_num_buckets gets set to the
4266  * number of buckets we copied.  The old extent's xh_num_buckets shrinks
4267  * by the same amount.
4268  */
4269 static int ocfs2_mv_xattr_buckets(struct inode *inode, handle_t *handle,
4270                                   u64 src_blk, u64 last_blk, u64 to_blk,
4271                                   unsigned int start_bucket,
4272                                   u32 *first_hash)
4273 {
4274         int i, ret, credits;
4275         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
4276         int blks_per_bucket = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
4277         int num_buckets = ocfs2_xattr_buckets_per_cluster(osb);
4278         struct ocfs2_xattr_bucket *old_first, *new_first;
4279
4280         mlog(0, "mv xattrs from cluster %llu to %llu\n",
4281              (unsigned long long)last_blk, (unsigned long long)to_blk);
4282
4283         BUG_ON(start_bucket >= num_buckets);
4284         if (start_bucket) {
4285                 num_buckets -= start_bucket;
4286                 last_blk += (start_bucket * blks_per_bucket);
4287         }
4288
4289         /* The first bucket of the original extent */
4290         old_first = ocfs2_xattr_bucket_new(inode);
4291         /* The first bucket of the new extent */
4292         new_first = ocfs2_xattr_bucket_new(inode);
4293         if (!old_first || !new_first) {
4294                 ret = -ENOMEM;
4295                 mlog_errno(ret);
4296                 goto out;
4297         }
4298
4299         ret = ocfs2_read_xattr_bucket(old_first, src_blk);
4300         if (ret) {
4301                 mlog_errno(ret);
4302                 goto out;
4303         }
4304
4305         /*
4306          * We need to update the first bucket of the old extent and all
4307          * the buckets going to the new extent.
4308          */
4309         credits = ((num_buckets + 1) * blks_per_bucket) +
4310                 handle->h_buffer_credits;
4311         ret = ocfs2_extend_trans(handle, credits);
4312         if (ret) {
4313                 mlog_errno(ret);
4314                 goto out;
4315         }
4316
4317         ret = ocfs2_xattr_bucket_journal_access(handle, old_first,
4318                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4319         if (ret) {
4320                 mlog_errno(ret);
4321                 goto out;
4322         }
4323
4324         for (i = 0; i < num_buckets; i++) {
4325                 ret = ocfs2_cp_xattr_bucket(inode, handle,
4326                                             last_blk + (i * blks_per_bucket),
4327                                             to_blk + (i * blks_per_bucket),
4328                                             1);
4329                 if (ret) {
4330                         mlog_errno(ret);
4331                         goto out;
4332                 }
4333         }
4334
4335         /*
4336          * Get the new bucket ready before we dirty anything
4337          * (This actually shouldn't fail, because we already dirtied
4338          * it once in ocfs2_cp_xattr_bucket()).
4339          */
4340         ret = ocfs2_read_xattr_bucket(new_first, to_blk);
4341         if (ret) {
4342                 mlog_errno(ret);
4343                 goto out;
4344         }
4345         ret = ocfs2_xattr_bucket_journal_access(handle, new_first,
4346                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4347         if (ret) {
4348                 mlog_errno(ret);
4349                 goto out;
4350         }
4351
4352         /* Now update the headers */
4353         le16_add_cpu(&bucket_xh(old_first)->xh_num_buckets, -num_buckets);
4354         ocfs2_xattr_bucket_journal_dirty(handle, old_first);
4355
4356         bucket_xh(new_first)->xh_num_buckets = cpu_to_le16(num_buckets);
4357         ocfs2_xattr_bucket_journal_dirty(handle, new_first);
4358
4359         if (first_hash)
4360                 *first_hash = le32_to_cpu(bucket_xh(new_first)->xh_entries[0].xe_name_hash);
4361
4362 out:
4363         ocfs2_xattr_bucket_free(new_first);
4364         ocfs2_xattr_bucket_free(old_first);
4365         return ret;
4366 }
4367
4368 /*
4369  * Move some xattrs in this cluster to the new cluster.
4370  * This function should only be called when bucket size == cluster size.
4371  * Otherwise ocfs2_mv_xattr_bucket_cross_cluster should be used instead.
4372  */
4373 static int ocfs2_divide_xattr_cluster(struct inode *inode,
4374                                       handle_t *handle,
4375                                       u64 prev_blk,
4376                                       u64 new_blk,
4377                                       u32 *first_hash)
4378 {
4379         u16 blk_per_bucket = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
4380         int ret, credits = 2 * blk_per_bucket + handle->h_buffer_credits;
4381
4382         BUG_ON(OCFS2_XATTR_BUCKET_SIZE < OCFS2_SB(inode->i_sb)->s_clustersize);
4383
4384         ret = ocfs2_extend_trans(handle, credits);
4385         if (ret) {
4386                 mlog_errno(ret);
4387                 return ret;
4388         }
4389
4390         /* Move half of the xattr in start_blk to the next bucket. */
4391         return  ocfs2_divide_xattr_bucket(inode, handle, prev_blk,
4392                                           new_blk, first_hash, 1);
4393 }
4394
4395 /*
4396  * Move some xattrs from the old cluster to the new one since they are not
4397  * contiguous in ocfs2 xattr tree.
4398  *
4399  * new_blk starts a new separate cluster, and we will move some xattrs from
4400  * prev_blk to it. v_start will be set as the first name hash value in this
4401  * new cluster so that it can be used as e_cpos during tree insertion and
4402  * don't collide with our original b-tree operations. first_bh and header_bh
4403  * will also be updated since they will be used in ocfs2_extend_xattr_bucket
4404  * to extend the insert bucket.
4405  *
4406  * The problem is how much xattr should we move to the new one and when should
4407  * we update first_bh and header_bh?
4408  * 1. If cluster size > bucket size, that means the previous cluster has more
4409  *    than 1 bucket, so just move half nums of bucket into the new cluster and
4410  *    update the first_bh and header_bh if the insert bucket has been moved
4411  *    to the new cluster.
4412  * 2. If cluster_size == bucket_size:
4413  *    a) If the previous extent rec has more than one cluster and the insert
4414  *       place isn't in the last cluster, copy the entire last cluster to the
4415  *       new one. This time, we don't need to upate the first_bh and header_bh
4416  *       since they will not be moved into the new cluster.
4417  *    b) Otherwise, move the bottom half of the xattrs in the last cluster into
4418  *       the new one. And we set the extend flag to zero if the insert place is
4419  *       moved into the new allocated cluster since no extend is needed.
4420  */
4421 static int ocfs2_adjust_xattr_cross_cluster(struct inode *inode,
4422                                             handle_t *handle,
4423                                             struct ocfs2_xattr_bucket *first,
4424                                             struct ocfs2_xattr_bucket *target,
4425                                             u64 new_blk,
4426                                             u32 prev_clusters,
4427                                             u32 *v_start,
4428                                             int *extend)
4429 {
4430         int ret;
4431
4432         mlog(0, "adjust xattrs from cluster %llu len %u to %llu\n",
4433              (unsigned long long)bucket_blkno(first), prev_clusters,
4434              (unsigned long long)new_blk);
4435
4436         if (ocfs2_xattr_buckets_per_cluster(OCFS2_SB(inode->i_sb)) > 1) {
4437                 ret = ocfs2_mv_xattr_bucket_cross_cluster(inode,
4438                                                           handle,
4439                                                           first, target,
4440                                                           new_blk,
4441                                                           prev_clusters,
4442                                                           v_start);
4443                 if (ret)
4444                         mlog_errno(ret);
4445         } else {
4446                 /* The start of the last cluster in the first extent */
4447                 u64 last_blk = bucket_blkno(first) +
4448                         ((prev_clusters - 1) *
4449                          ocfs2_clusters_to_blocks(inode->i_sb, 1));
4450
4451                 if (prev_clusters > 1 && bucket_blkno(target) != last_blk) {
4452                         ret = ocfs2_mv_xattr_buckets(inode, handle,
4453                                                      bucket_blkno(first),
4454                                                      last_blk, new_blk, 0,
4455                                                      v_start);
4456                         if (ret)
4457                                 mlog_errno(ret);
4458                 } else {
4459                         ret = ocfs2_divide_xattr_cluster(inode, handle,
4460                                                          last_blk, new_blk,
4461                                                          v_start);
4462                         if (ret)
4463                                 mlog_errno(ret);
4464
4465                         if ((bucket_blkno(target) == last_blk) && extend)
4466                                 *extend = 0;
4467                 }
4468         }
4469
4470         return ret;
4471 }
4472
4473 /*
4474  * Add a new cluster for xattr storage.
4475  *
4476  * If the new cluster is contiguous with the previous one, it will be
4477  * appended to the same extent record, and num_clusters will be updated.
4478  * If not, we will insert a new extent for it and move some xattrs in
4479  * the last cluster into the new allocated one.
4480  * We also need to limit the maximum size of a btree leaf, otherwise we'll
4481  * lose the benefits of hashing because we'll have to search large leaves.
4482  * So now the maximum size is OCFS2_MAX_XATTR_TREE_LEAF_SIZE(or clustersize,
4483  * if it's bigger).
4484  *
4485  * first_bh is the first block of the previous extent rec and header_bh
4486  * indicates the bucket we will insert the new xattrs. They will be updated
4487  * when the header_bh is moved into the new cluster.
4488  */
4489 static int ocfs2_add_new_xattr_cluster(struct inode *inode,
4490                                        struct buffer_head *root_bh,
4491                                        struct ocfs2_xattr_bucket *first,
4492                                        struct ocfs2_xattr_bucket *target,
4493                                        u32 *num_clusters,
4494                                        u32 prev_cpos,
4495                                        int *extend,
4496                                        struct ocfs2_xattr_set_ctxt *ctxt)
4497 {
4498         int ret;
4499         u16 bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
4500         u32 prev_clusters = *num_clusters;
4501         u32 clusters_to_add = 1, bit_off, num_bits, v_start = 0;
4502         u64 block;
4503         handle_t *handle = ctxt->handle;
4504         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
4505         struct ocfs2_extent_tree et;
4506
4507         mlog(0, "Add new xattr cluster for %llu, previous xattr hash = %u, "
4508              "previous xattr blkno = %llu\n",
4509              (unsigned long long)OCFS2_I(inode)->ip_blkno,
4510              prev_cpos, (unsigned long long)bucket_blkno(first));
4511
4512         ocfs2_init_xattr_tree_extent_tree(&et, INODE_CACHE(inode), root_bh);
4513
4514         ret = ocfs2_journal_access_xb(handle, INODE_CACHE(inode), root_bh,
4515                                       OCFS2_JOURNAL_ACCESS_WRITE);
4516         if (ret < 0) {
4517                 mlog_errno(ret);
4518                 goto leave;
4519         }
4520
4521         ret = __ocfs2_claim_clusters(osb, handle, ctxt->data_ac, 1,
4522                                      clusters_to_add, &bit_off, &num_bits);
4523         if (ret < 0) {
4524                 if (ret != -ENOSPC)
4525                         mlog_errno(ret);
4526                 goto leave;
4527         }
4528
4529         BUG_ON(num_bits > clusters_to_add);
4530
4531         block = ocfs2_clusters_to_blocks(osb->sb, bit_off);
4532         mlog(0, "Allocating %u clusters at block %u for xattr in inode %llu\n",
4533              num_bits, bit_off, (unsigned long long)OCFS2_I(inode)->ip_blkno);
4534
4535         if (bucket_blkno(first) + (prev_clusters * bpc) == block &&
4536             (prev_clusters + num_bits) << osb->s_clustersize_bits <=
4537              OCFS2_MAX_XATTR_TREE_LEAF_SIZE) {
4538                 /*
4539                  * If this cluster is contiguous with the old one and
4540                  * adding this new cluster, we don't surpass the limit of
4541                  * OCFS2_MAX_XATTR_TREE_LEAF_SIZE, cool. We will let it be
4542                  * initialized and used like other buckets in the previous
4543                  * cluster.
4544                  * So add it as a contiguous one. The caller will handle
4545                  * its init process.
4546                  */
4547                 v_start = prev_cpos + prev_clusters;
4548                 *num_clusters = prev_clusters + num_bits;
4549                 mlog(0, "Add contiguous %u clusters to previous extent rec.\n",
4550                      num_bits);
4551         } else {
4552                 ret = ocfs2_adjust_xattr_cross_cluster(inode,
4553                                                        handle,
4554                                                        first,
4555                                                        target,
4556                                                        block,
4557                                                        prev_clusters,
4558                                                        &v_start,
4559                                                        extend);
4560                 if (ret) {
4561                         mlog_errno(ret);
4562                         goto leave;
4563                 }
4564         }
4565
4566         mlog(0, "Insert %u clusters at block %llu for xattr at %u\n",
4567              num_bits, (unsigned long long)block, v_start);
4568         ret = ocfs2_insert_extent(handle, &et, v_start, block,
4569                                   num_bits, 0, ctxt->meta_ac);
4570         if (ret < 0) {
4571                 mlog_errno(ret);
4572                 goto leave;
4573         }
4574
4575         ret = ocfs2_journal_dirty(handle, root_bh);
4576         if (ret < 0)
4577                 mlog_errno(ret);
4578
4579 leave:
4580         return ret;
4581 }
4582
4583 /*
4584  * We are given an extent.  'first' is the bucket at the very front of
4585  * the extent.  The extent has space for an additional bucket past
4586  * bucket_xh(first)->xh_num_buckets.  'target_blkno' is the block number
4587  * of the target bucket.  We wish to shift every bucket past the target
4588  * down one, filling in that additional space.  When we get back to the
4589  * target, we split the target between itself and the now-empty bucket
4590  * at target+1 (aka, target_blkno + blks_per_bucket).
4591  */
4592 static int ocfs2_extend_xattr_bucket(struct inode *inode,
4593                                      handle_t *handle,
4594                                      struct ocfs2_xattr_bucket *first,
4595                                      u64 target_blk,
4596                                      u32 num_clusters)
4597 {
4598         int ret, credits;
4599         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
4600         u16 blk_per_bucket = ocfs2_blocks_per_xattr_bucket(inode->i_sb);
4601         u64 end_blk;
4602         u16 new_bucket = le16_to_cpu(bucket_xh(first)->xh_num_buckets);
4603
4604         mlog(0, "extend xattr bucket in %llu, xattr extend rec starting "
4605              "from %llu, len = %u\n", (unsigned long long)target_blk,
4606              (unsigned long long)bucket_blkno(first), num_clusters);
4607
4608         /* The extent must have room for an additional bucket */
4609         BUG_ON(new_bucket >=
4610                (num_clusters * ocfs2_xattr_buckets_per_cluster(osb)));
4611
4612         /* end_blk points to the last existing bucket */
4613         end_blk = bucket_blkno(first) + ((new_bucket - 1) * blk_per_bucket);
4614
4615         /*
4616          * end_blk is the start of the last existing bucket.
4617          * Thus, (end_blk - target_blk) covers the target bucket and
4618          * every bucket after it up to, but not including, the last
4619          * existing bucket.  Then we add the last existing bucket, the
4620          * new bucket, and the first bucket (3 * blk_per_bucket).
4621          */
4622         credits = (end_blk - target_blk) + (3 * blk_per_bucket) +
4623                   handle->h_buffer_credits;
4624         ret = ocfs2_extend_trans(handle, credits);
4625         if (ret) {
4626                 mlog_errno(ret);
4627                 goto out;
4628         }
4629
4630         ret = ocfs2_xattr_bucket_journal_access(handle, first,
4631                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4632         if (ret) {
4633                 mlog_errno(ret);
4634                 goto out;
4635         }
4636
4637         while (end_blk != target_blk) {
4638                 ret = ocfs2_cp_xattr_bucket(inode, handle, end_blk,
4639                                             end_blk + blk_per_bucket, 0);
4640                 if (ret)
4641                         goto out;
4642                 end_blk -= blk_per_bucket;
4643         }
4644
4645         /* Move half of the xattr in target_blkno to the next bucket. */
4646         ret = ocfs2_divide_xattr_bucket(inode, handle, target_blk,
4647                                         target_blk + blk_per_bucket, NULL, 0);
4648
4649         le16_add_cpu(&bucket_xh(first)->xh_num_buckets, 1);
4650         ocfs2_xattr_bucket_journal_dirty(handle, first);
4651
4652 out:
4653         return ret;
4654 }
4655
4656 /*
4657  * Add new xattr bucket in an extent record and adjust the buckets
4658  * accordingly.  xb_bh is the ocfs2_xattr_block, and target is the
4659  * bucket we want to insert into.
4660  *
4661  * In the easy case, we will move all the buckets after target down by
4662  * one. Half of target's xattrs will be moved to the next bucket.
4663  *
4664  * If current cluster is full, we'll allocate a new one.  This may not
4665  * be contiguous.  The underlying calls will make sure that there is
4666  * space for the insert, shifting buckets around if necessary.
4667  * 'target' may be moved by those calls.
4668  */
4669 static int ocfs2_add_new_xattr_bucket(struct inode *inode,
4670                                       struct buffer_head *xb_bh,
4671                                       struct ocfs2_xattr_bucket *target,
4672                                       struct ocfs2_xattr_set_ctxt *ctxt)
4673 {
4674         struct ocfs2_xattr_block *xb =
4675                         (struct ocfs2_xattr_block *)xb_bh->b_data;
4676         struct ocfs2_xattr_tree_root *xb_root = &xb->xb_attrs.xb_root;
4677         struct ocfs2_extent_list *el = &xb_root->xt_list;
4678         u32 name_hash =
4679                 le32_to_cpu(bucket_xh(target)->xh_entries[0].xe_name_hash);
4680         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
4681         int ret, num_buckets, extend = 1;
4682         u64 p_blkno;
4683         u32 e_cpos, num_clusters;
4684         /* The bucket at the front of the extent */
4685         struct ocfs2_xattr_bucket *first;
4686
4687         mlog(0, "Add new xattr bucket starting from %llu\n",
4688              (unsigned long long)bucket_blkno(target));
4689
4690         /* The first bucket of the original extent */
4691         first = ocfs2_xattr_bucket_new(inode);
4692         if (!first) {
4693                 ret = -ENOMEM;
4694                 mlog_errno(ret);
4695                 goto out;
4696         }
4697
4698         ret = ocfs2_xattr_get_rec(inode, name_hash, &p_blkno, &e_cpos,
4699                                   &num_clusters, el);
4700         if (ret) {
4701                 mlog_errno(ret);
4702                 goto out;
4703         }
4704
4705         ret = ocfs2_read_xattr_bucket(first, p_blkno);
4706         if (ret) {
4707                 mlog_errno(ret);
4708                 goto out;
4709         }
4710
4711         num_buckets = ocfs2_xattr_buckets_per_cluster(osb) * num_clusters;
4712         if (num_buckets == le16_to_cpu(bucket_xh(first)->xh_num_buckets)) {
4713                 /*
4714                  * This can move first+target if the target bucket moves
4715                  * to the new extent.
4716                  */
4717                 ret = ocfs2_add_new_xattr_cluster(inode,
4718                                                   xb_bh,
4719                                                   first,
4720                                                   target,
4721                                                   &num_clusters,
4722                                                   e_cpos,
4723                                                   &extend,
4724                                                   ctxt);
4725                 if (ret) {
4726                         mlog_errno(ret);
4727                         goto out;
4728                 }
4729         }
4730
4731         if (extend) {
4732                 ret = ocfs2_extend_xattr_bucket(inode,
4733                                                 ctxt->handle,
4734                                                 first,
4735                                                 bucket_blkno(target),
4736                                                 num_clusters);
4737                 if (ret)
4738                         mlog_errno(ret);
4739         }
4740
4741 out:
4742         ocfs2_xattr_bucket_free(first);
4743
4744         return ret;
4745 }
4746
4747 static inline char *ocfs2_xattr_bucket_get_val(struct inode *inode,
4748                                         struct ocfs2_xattr_bucket *bucket,
4749                                         int offs)
4750 {
4751         int block_off = offs >> inode->i_sb->s_blocksize_bits;
4752
4753         offs = offs % inode->i_sb->s_blocksize;
4754         return bucket_block(bucket, block_off) + offs;
4755 }
4756
4757 /*
4758  * Handle the normal xattr set, including replace, delete and new.
4759  *
4760  * Note: "local" indicates the real data's locality. So we can't
4761  * just its bucket locality by its length.
4762  */
4763 static void ocfs2_xattr_set_entry_normal(struct inode *inode,
4764                                          struct ocfs2_xattr_info *xi,
4765                                          struct ocfs2_xattr_search *xs,
4766                                          u32 name_hash,
4767                                          int local)
4768 {
4769         struct ocfs2_xattr_entry *last, *xe;
4770         int name_len = strlen(xi->name);
4771         struct ocfs2_xattr_header *xh = xs->header;
4772         u16 count = le16_to_cpu(xh->xh_count), start;
4773         size_t blocksize = inode->i_sb->s_blocksize;
4774         char *val;
4775         size_t offs, size, new_size;
4776
4777         last = &xh->xh_entries[count];
4778         if (!xs->not_found) {
4779                 xe = xs->here;
4780                 offs = le16_to_cpu(xe->xe_name_offset);
4781                 if (ocfs2_xattr_is_local(xe))
4782                         size = OCFS2_XATTR_SIZE(name_len) +
4783                         OCFS2_XATTR_SIZE(le64_to_cpu(xe->xe_value_size));
4784                 else
4785                         size = OCFS2_XATTR_SIZE(name_len) +
4786                         OCFS2_XATTR_SIZE(OCFS2_XATTR_ROOT_SIZE);
4787
4788                 /*
4789                  * If the new value will be stored outside, xi->value has been
4790                  * initalized as an empty ocfs2_xattr_value_root, and the same
4791                  * goes with xi->value_len, so we can set new_size safely here.
4792                  * See ocfs2_xattr_set_in_bucket.
4793                  */
4794                 new_size = OCFS2_XATTR_SIZE(name_len) +
4795                            OCFS2_XATTR_SIZE(xi->value_len);
4796
4797                 le16_add_cpu(&xh->xh_name_value_len, -size);
4798                 if (xi->value) {
4799                         if (new_size > size)
4800                                 goto set_new_name_value;
4801
4802                         /* Now replace the old value with new one. */
4803                         if (local)
4804                                 xe->xe_value_size = cpu_to_le64(xi->value_len);
4805                         else
4806                                 xe->xe_value_size = 0;
4807
4808                         val = ocfs2_xattr_bucket_get_val(inode,
4809                                                          xs->bucket, offs);
4810                         memset(val + OCFS2_XATTR_SIZE(name_len), 0,
4811                                size - OCFS2_XATTR_SIZE(name_len));
4812                         if (OCFS2_XATTR_SIZE(xi->value_len) > 0)
4813                                 memcpy(val + OCFS2_XATTR_SIZE(name_len),
4814                                        xi->value, xi->value_len);
4815
4816                         le16_add_cpu(&xh->xh_name_value_len, new_size);
4817                         ocfs2_xattr_set_local(xe, local);
4818                         return;
4819                 } else {
4820                         /*
4821                          * Remove the old entry if there is more than one.
4822                          * We don't remove the last entry so that we can
4823                          * use it to indicate the hash value of the empty
4824                          * bucket.
4825                          */
4826                         last -= 1;
4827                         le16_add_cpu(&xh->xh_count, -1);
4828                         if (xh->xh_count) {
4829                                 memmove(xe, xe + 1,
4830                                         (void *)last - (void *)xe);
4831                                 memset(last, 0,
4832                                        sizeof(struct ocfs2_xattr_entry));
4833                         } else
4834                                 xh->xh_free_start =
4835                                         cpu_to_le16(OCFS2_XATTR_BUCKET_SIZE);
4836
4837                         return;
4838                 }
4839         } else {
4840                 /* find a new entry for insert. */
4841                 int low = 0, high = count - 1, tmp;
4842                 struct ocfs2_xattr_entry *tmp_xe;
4843
4844                 while (low <= high && count) {
4845                         tmp = (low + high) / 2;
4846                         tmp_xe = &xh->xh_entries[tmp];
4847
4848                         if (name_hash > le32_to_cpu(tmp_xe->xe_name_hash))
4849                                 low = tmp + 1;
4850                         else if (name_hash <
4851                                  le32_to_cpu(tmp_xe->xe_name_hash))
4852                                 high = tmp - 1;
4853                         else {
4854                                 low = tmp;
4855                                 break;
4856                         }
4857                 }
4858
4859                 xe = &xh->xh_entries[low];
4860                 if (low != count)
4861                         memmove(xe + 1, xe, (void *)last - (void *)xe);
4862
4863                 le16_add_cpu(&xh->xh_count, 1);
4864                 memset(xe, 0, sizeof(struct ocfs2_xattr_entry));
4865                 xe->xe_name_hash = cpu_to_le32(name_hash);
4866                 xe->xe_name_len = name_len;
4867                 ocfs2_xattr_set_type(xe, xi->name_index);
4868         }
4869
4870 set_new_name_value:
4871         /* Insert the new name+value. */
4872         size = OCFS2_XATTR_SIZE(name_len) + OCFS2_XATTR_SIZE(xi->value_len);
4873
4874         /*
4875          * We must make sure that the name/value pair
4876          * exists in the same block.
4877          */
4878         offs = le16_to_cpu(xh->xh_free_start);
4879         start = offs - size;
4880
4881         if (start >> inode->i_sb->s_blocksize_bits !=
4882             (offs - 1) >> inode->i_sb->s_blocksize_bits) {
4883                 offs = offs - offs % blocksize;
4884                 xh->xh_free_start = cpu_to_le16(offs);
4885         }
4886
4887         val = ocfs2_xattr_bucket_get_val(inode, xs->bucket, offs - size);
4888         xe->xe_name_offset = cpu_to_le16(offs - size);
4889
4890         memset(val, 0, size);
4891         memcpy(val, xi->name, name_len);
4892         memcpy(val + OCFS2_XATTR_SIZE(name_len), xi->value, xi->value_len);
4893
4894         xe->xe_value_size = cpu_to_le64(xi->value_len);
4895         ocfs2_xattr_set_local(xe, local);
4896         xs->here = xe;
4897         le16_add_cpu(&xh->xh_free_start, -size);
4898         le16_add_cpu(&xh->xh_name_value_len, size);
4899
4900         return;
4901 }
4902
4903 /*
4904  * Set the xattr entry in the specified bucket.
4905  * The bucket is indicated by xs->bucket and it should have the enough
4906  * space for the xattr insertion.
4907  */
4908 static int ocfs2_xattr_set_entry_in_bucket(struct inode *inode,
4909                                            handle_t *handle,
4910                                            struct ocfs2_xattr_info *xi,
4911                                            struct ocfs2_xattr_search *xs,
4912                                            u32 name_hash,
4913                                            int local)
4914 {
4915         int ret;
4916         u64 blkno;
4917
4918         mlog(0, "Set xattr entry len = %lu index = %d in bucket %llu\n",
4919              (unsigned long)xi->value_len, xi->name_index,
4920              (unsigned long long)bucket_blkno(xs->bucket));
4921
4922         if (!xs->bucket->bu_bhs[1]) {
4923                 blkno = bucket_blkno(xs->bucket);
4924                 ocfs2_xattr_bucket_relse(xs->bucket);
4925                 ret = ocfs2_read_xattr_bucket(xs->bucket, blkno);
4926                 if (ret) {
4927                         mlog_errno(ret);
4928                         goto out;
4929                 }
4930         }
4931
4932         ret = ocfs2_xattr_bucket_journal_access(handle, xs->bucket,
4933                                                 OCFS2_JOURNAL_ACCESS_WRITE);
4934         if (ret < 0) {
4935                 mlog_errno(ret);
4936                 goto out;
4937         }
4938
4939         ocfs2_xattr_set_entry_normal(inode, xi, xs, name_hash, local);
4940         ocfs2_xattr_bucket_journal_dirty(handle, xs->bucket);
4941
4942 out:
4943         return ret;
4944 }
4945
4946 /*
4947  * Truncate the specified xe_off entry in xattr bucket.
4948  * bucket is indicated by header_bh and len is the new length.
4949  * Both the ocfs2_xattr_value_root and the entry will be updated here.
4950  *
4951  * Copy the new updated xe and xe_value_root to new_xe and new_xv if needed.
4952  */
4953 static int ocfs2_xattr_bucket_value_truncate(struct inode *inode,
4954                                              struct ocfs2_xattr_bucket *bucket,
4955                                              int xe_off,
4956                                              int len,
4957                                              struct ocfs2_xattr_set_ctxt *ctxt)
4958 {
4959         int ret, offset;
4960         u64 value_blk;
4961         struct ocfs2_xattr_entry *xe;
4962         struct ocfs2_xattr_header *xh = bucket_xh(bucket);
4963         size_t blocksize = inode->i_sb->s_blocksize;
4964         struct ocfs2_xattr_value_buf vb = {
4965                 .vb_access = ocfs2_journal_access,
4966         };
4967
4968         xe = &xh->xh_entries[xe_off];
4969
4970         BUG_ON(!xe || ocfs2_xattr_is_local(xe));
4971
4972         offset = le16_to_cpu(xe->xe_name_offset) +
4973                  OCFS2_XATTR_SIZE(xe->xe_name_len);
4974
4975         value_blk = offset / blocksize;
4976
4977         /* We don't allow ocfs2_xattr_value to be stored in different block. */
4978         BUG_ON(value_blk != (offset + OCFS2_XATTR_ROOT_SIZE - 1) / blocksize);
4979
4980         vb.vb_bh = bucket->bu_bhs[value_blk];
4981         BUG_ON(!vb.vb_bh);
4982
4983         vb.vb_xv = (struct ocfs2_xattr_value_root *)
4984                 (vb.vb_bh->b_data + offset % blocksize);
4985
4986         /*
4987          * From here on out we have to dirty the bucket.  The generic
4988          * value calls only modify one of the bucket's bhs, but we need
4989          * to send the bucket at once.  So if they error, they *could* have
4990          * modified something.  We have to assume they did, and dirty
4991          * the whole bucket.  This leaves us in a consistent state.
4992          */
4993         mlog(0, "truncate %u in xattr bucket %llu to %d bytes.\n",
4994              xe_off, (unsigned long long)bucket_blkno(bucket), len);
4995         ret = ocfs2_xattr_value_truncate(inode, &vb, len, ctxt);
4996         if (ret) {
4997                 mlog_errno(ret);
4998                 goto out;
4999         }
5000
5001         ret = ocfs2_xattr_bucket_journal_access(ctxt->handle, bucket,
5002                                                 OCFS2_JOURNAL_ACCESS_WRITE);
5003         if (ret) {
5004                 mlog_errno(ret);
5005                 goto out;
5006         }
5007
5008         xe->xe_value_size = cpu_to_le64(len);
5009
5010         ocfs2_xattr_bucket_journal_dirty(ctxt->handle, bucket);
5011
5012 out:
5013         return ret;
5014 }
5015
5016 static int ocfs2_xattr_bucket_value_truncate_xs(struct inode *inode,
5017                                         struct ocfs2_xattr_search *xs,
5018                                         int len,
5019                                         struct ocfs2_xattr_set_ctxt *ctxt)
5020 {
5021         int ret, offset;
5022         struct ocfs2_xattr_entry *xe = xs->here;
5023         struct ocfs2_xattr_header *xh = (struct ocfs2_xattr_header *)xs->base;
5024
5025         BUG_ON(!xs->bucket->bu_bhs[0] || !xe || ocfs2_xattr_is_local(xe));
5026
5027         offset = xe - xh->xh_entries;
5028         ret = ocfs2_xattr_bucket_value_truncate(inode, xs->bucket,
5029                                                 offset, len, ctxt);
5030         if (ret)
5031                 mlog_errno(ret);
5032
5033         return ret;
5034 }
5035
5036 static int ocfs2_xattr_bucket_set_value_outside(struct inode *inode,
5037                                                 handle_t *handle,
5038                                                 struct ocfs2_xattr_search *xs,
5039                                                 char *val,
5040                                                 int value_len)
5041 {
5042         int ret, offset, block_off;
5043         struct ocfs2_xattr_value_root *xv;
5044         struct ocfs2_xattr_entry *xe = xs->here;
5045         struct ocfs2_xattr_header *xh = bucket_xh(xs->bucket);
5046         void *base;
5047         struct ocfs2_xattr_value_buf vb = {
5048                 .vb_access = ocfs2_journal_access,
5049         };
5050
5051         BUG_ON(!xs->base || !xe || ocfs2_xattr_is_local(xe));
5052
5053         ret = ocfs2_xattr_bucket_get_name_value(inode->i_sb, xh,
5054                                                 xe - xh->xh_entries,
5055                                                 &block_off,
5056                                                 &offset);
5057         if (ret) {
5058                 mlog_errno(ret);
5059                 goto out;
5060         }
5061
5062         base = bucket_block(xs->bucket, block_off);
5063         xv = (struct ocfs2_xattr_value_root *)(base + offset +
5064                  OCFS2_XATTR_SIZE(xe->xe_name_len));
5065
5066         vb.vb_xv = xv;
5067         vb.vb_bh = xs->bucket->bu_bhs[block_off];
5068         ret = __ocfs2_xattr_set_value_outside(inode, handle,
5069                                               &vb, val, value_len);
5070         if (ret)
5071                 mlog_errno(ret);
5072 out:
5073         return ret;
5074 }
5075
5076 static int ocfs2_rm_xattr_cluster(struct inode *inode,
5077                                   struct buffer_head *root_bh,
5078                                   u64 blkno,
5079                                   u32 cpos,
5080                                   u32 len,
5081                                   void *para)
5082 {
5083         int ret;
5084         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
5085         struct inode *tl_inode = osb->osb_tl_inode;
5086         handle_t *handle;
5087         struct ocfs2_xattr_block *xb =
5088                         (struct ocfs2_xattr_block *)root_bh->b_data;
5089         struct ocfs2_alloc_context *meta_ac = NULL;
5090         struct ocfs2_cached_dealloc_ctxt dealloc;
5091         struct ocfs2_extent_tree et;
5092
5093         ret = ocfs2_iterate_xattr_buckets(inode, blkno, len,
5094                                           ocfs2_delete_xattr_in_bucket, para);
5095         if (ret) {
5096                 mlog_errno(ret);
5097                 return ret;
5098         }
5099
5100         ocfs2_init_xattr_tree_extent_tree(&et, INODE_CACHE(inode), root_bh);
5101
5102         ocfs2_init_dealloc_ctxt(&dealloc);
5103
5104         mlog(0, "rm xattr extent rec at %u len = %u, start from %llu\n",
5105              cpos, len, (unsigned long long)blkno);
5106
5107         ocfs2_remove_xattr_clusters_from_cache(INODE_CACHE(inode), blkno,
5108                                                len);
5109
5110         ret = ocfs2_lock_allocators(inode, &et, 0, 1, NULL, &meta_ac);
5111         if (ret) {
5112                 mlog_errno(ret);
5113                 return ret;
5114         }
5115
5116         mutex_lock(&tl_inode->i_mutex);
5117
5118         if (ocfs2_truncate_log_needs_flush(osb)) {
5119                 ret = __ocfs2_flush_truncate_log(osb);
5120                 if (ret < 0) {
5121                         mlog_errno(ret);
5122                         goto out;
5123                 }
5124         }
5125
5126         handle = ocfs2_start_trans(osb, ocfs2_remove_extent_credits(osb->sb));
5127         if (IS_ERR(handle)) {
5128                 ret = -ENOMEM;
5129                 mlog_errno(ret);
5130                 goto out;
5131         }
5132
5133         ret = ocfs2_journal_access_xb(handle, INODE_CACHE(inode), root_bh,
5134                                       OCFS2_JOURNAL_ACCESS_WRITE);
5135         if (ret) {
5136                 mlog_errno(ret);
5137                 goto out_commit;
5138         }
5139
5140         ret = ocfs2_remove_extent(handle, &et, cpos, len, meta_ac,
5141                                   &dealloc);
5142         if (ret) {
5143                 mlog_errno(ret);
5144                 goto out_commit;
5145         }
5146
5147         le32_add_cpu(&xb->xb_attrs.xb_root.xt_clusters, -len);
5148
5149         ret = ocfs2_journal_dirty(handle, root_bh);
5150         if (ret) {
5151                 mlog_errno(ret);
5152                 goto out_commit;
5153         }
5154
5155         ret = ocfs2_truncate_log_append(osb, handle, blkno, len);
5156         if (ret)
5157                 mlog_errno(ret);
5158
5159 out_commit:
5160         ocfs2_commit_trans(osb, handle);
5161 out:
5162         ocfs2_schedule_truncate_log_flush(osb, 1);
5163
5164         mutex_unlock(&tl_inode->i_mutex);
5165
5166         if (meta_ac)
5167                 ocfs2_free_alloc_context(meta_ac);
5168
5169         ocfs2_run_deallocs(osb, &dealloc);
5170
5171         return ret;
5172 }
5173
5174 static void ocfs2_xattr_bucket_remove_xs(struct inode *inode,
5175                                          handle_t *handle,
5176                                          struct ocfs2_xattr_search *xs)
5177 {
5178         struct ocfs2_xattr_header *xh = bucket_xh(xs->bucket);
5179         struct ocfs2_xattr_entry *last = &xh->xh_entries[
5180                                                 le16_to_cpu(xh->xh_count) - 1];
5181         int ret = 0;
5182
5183         ret = ocfs2_xattr_bucket_journal_access(handle, xs->bucket,
5184                                                 OCFS2_JOURNAL_ACCESS_WRITE);
5185         if (ret) {
5186                 mlog_errno(ret);
5187                 return;
5188         }
5189
5190         /* Remove the old entry. */
5191         memmove(xs->here, xs->here + 1,
5192                 (void *)last - (void *)xs->here);
5193         memset(last, 0, sizeof(struct ocfs2_xattr_entry));
5194         le16_add_cpu(&xh->xh_count, -1);
5195
5196         ocfs2_xattr_bucket_journal_dirty(handle, xs->bucket);
5197 }
5198
5199 /*
5200  * Set the xattr name/value in the bucket specified in xs.
5201  *
5202  * As the new value in xi may be stored in the bucket or in an outside cluster,
5203  * we divide the whole process into 3 steps:
5204  * 1. insert name/value in the bucket(ocfs2_xattr_set_entry_in_bucket)
5205  * 2. truncate of the outside cluster(ocfs2_xattr_bucket_value_truncate_xs)
5206  * 3. Set the value to the outside cluster(ocfs2_xattr_bucket_set_value_outside)
5207  * 4. If the clusters for the new outside value can't be allocated, we need
5208  *    to free the xattr we allocated in set.
5209  */
5210 static int ocfs2_xattr_set_in_bucket(struct inode *inode,
5211                                      struct ocfs2_xattr_info *xi,
5212                                      struct ocfs2_xattr_search *xs,
5213                                      struct ocfs2_xattr_set_ctxt *ctxt)
5214 {
5215         int ret, local = 1;
5216         size_t value_len;
5217         char *val = (char *)xi->value;
5218         struct ocfs2_xattr_entry *xe = xs->here;
5219         u32 name_hash = ocfs2_xattr_name_hash(inode, xi->name,
5220                                               strlen(xi->name));
5221
5222         if (!xs->not_found && !ocfs2_xattr_is_local(xe)) {
5223                 /*
5224                  * We need to truncate the xattr storage first.
5225                  *
5226                  * If both the old and new value are stored to
5227                  * outside block, we only need to truncate
5228                  * the storage and then set the value outside.
5229                  *
5230                  * If the new value should be stored within block,
5231                  * we should free all the outside block first and
5232                  * the modification to the xattr block will be done
5233                  * by following steps.
5234                  */
5235                 if (xi->value_len > OCFS2_XATTR_INLINE_SIZE)
5236                         value_len = xi->value_len;
5237                 else
5238                         value_len = 0;
5239
5240                 ret = ocfs2_xattr_bucket_value_truncate_xs(inode, xs,
5241                                                            value_len,
5242                                                            ctxt);
5243                 if (ret)
5244                         goto out;
5245
5246                 if (value_len)
5247                         goto set_value_outside;
5248         }
5249
5250         value_len = xi->value_len;
5251         /* So we have to handle the inside block change now. */
5252         if (value_len > OCFS2_XATTR_INLINE_SIZE) {
5253                 /*
5254                  * If the new value will be stored outside of block,
5255                  * initalize a new empty value root and insert it first.
5256                  */
5257                 local = 0;
5258                 xi->value = &def_xv;
5259                 xi->value_len = OCFS2_XATTR_ROOT_SIZE;
5260         }
5261
5262         ret = ocfs2_xattr_set_entry_in_bucket(inode, ctxt->handle, xi, xs,
5263                                               name_hash, local);
5264         if (ret) {
5265                 mlog_errno(ret);
5266                 goto out;
5267         }
5268
5269         if (value_len <= OCFS2_XATTR_INLINE_SIZE)
5270                 goto out;
5271
5272         /* allocate the space now for the outside block storage. */
5273         ret = ocfs2_xattr_bucket_value_truncate_xs(inode, xs,
5274                                                    value_len, ctxt);
5275         if (ret) {
5276                 mlog_errno(ret);
5277
5278                 if (xs->not_found) {
5279                         /*
5280                          * We can't allocate enough clusters for outside
5281                          * storage and we have allocated xattr already,
5282                          * so need to remove it.
5283                          */
5284                         ocfs2_xattr_bucket_remove_xs(inode, ctxt->handle, xs);
5285                 }
5286                 goto out;
5287         }
5288
5289 set_value_outside:
5290         ret = ocfs2_xattr_bucket_set_value_outside(inode, ctxt->handle,
5291                                                    xs, val, value_len);
5292 out:
5293         return ret;
5294 }
5295
5296 /*
5297  * check whether the xattr bucket is filled up with the same hash value.
5298  * If we want to insert the xattr with the same hash, return -ENOSPC.
5299  * If we want to insert a xattr with different hash value, go ahead
5300  * and ocfs2_divide_xattr_bucket will handle this.
5301  */
5302 static int ocfs2_check_xattr_bucket_collision(struct inode *inode,
5303                                               struct ocfs2_xattr_bucket *bucket,
5304                                               const char *name)
5305 {
5306         struct ocfs2_xattr_header *xh = bucket_xh(bucket);
5307         u32 name_hash = ocfs2_xattr_name_hash(inode, name, strlen(name));
5308
5309         if (name_hash != le32_to_cpu(xh->xh_entries[0].xe_name_hash))
5310                 return 0;
5311
5312         if (xh->xh_entries[le16_to_cpu(xh->xh_count) - 1].xe_name_hash ==
5313             xh->xh_entries[0].xe_name_hash) {
5314                 mlog(ML_ERROR, "Too much hash collision in xattr bucket %llu, "
5315                      "hash = %u\n",
5316                      (unsigned long long)bucket_blkno(bucket),
5317                      le32_to_cpu(xh->xh_entries[0].xe_name_hash));
5318                 return -ENOSPC;
5319         }
5320
5321         return 0;
5322 }
5323
5324 static int ocfs2_xattr_set_entry_index_block(struct inode *inode,
5325                                              struct ocfs2_xattr_info *xi,
5326                                              struct ocfs2_xattr_search *xs,
5327                                              struct ocfs2_xattr_set_ctxt *ctxt)
5328 {
5329         struct ocfs2_xattr_header *xh;
5330         struct ocfs2_xattr_entry *xe;
5331         u16 count, header_size, xh_free_start;
5332         int free, max_free, need, old;
5333         size_t value_size = 0, name_len = strlen(xi->name);
5334         size_t blocksize = inode->i_sb->s_blocksize;
5335         int ret, allocation = 0;
5336
5337         mlog_entry("Set xattr %s in xattr index block\n", xi->name);
5338
5339 try_again:
5340         xh = xs->header;
5341         count = le16_to_cpu(xh->xh_count);
5342         xh_free_start = le16_to_cpu(xh->xh_free_start);
5343         header_size = sizeof(struct ocfs2_xattr_header) +
5344                         count * sizeof(struct ocfs2_xattr_entry);
5345         max_free = OCFS2_XATTR_BUCKET_SIZE - header_size -
5346                 le16_to_cpu(xh->xh_name_value_len) - OCFS2_XATTR_HEADER_GAP;
5347
5348         mlog_bug_on_msg(header_size > blocksize, "bucket %llu has header size "
5349                         "of %u which exceed block size\n",
5350                         (unsigned long long)bucket_blkno(xs->bucket),
5351                         header_size);
5352
5353         if (xi->value && xi->value_len > OCFS2_XATTR_INLINE_SIZE)
5354                 value_size = OCFS2_XATTR_ROOT_SIZE;
5355         else if (xi->value)
5356                 value_size = OCFS2_XATTR_SIZE(xi->value_len);
5357
5358         if (xs->not_found)
5359                 need = sizeof(struct ocfs2_xattr_entry) +
5360                         OCFS2_XATTR_SIZE(name_len) + value_size;
5361         else {
5362                 need = value_size + OCFS2_XATTR_SIZE(name_len);
5363
5364                 /*
5365                  * We only replace the old value if the new length is smaller
5366                  * than the old one. Otherwise we will allocate new space in the
5367                  * bucket to store it.
5368                  */
5369                 xe = xs->here;
5370                 if (ocfs2_xattr_is_local(xe))
5371                         old = OCFS2_XATTR_SIZE(le64_to_cpu(xe->xe_value_size));
5372                 else
5373                         old = OCFS2_XATTR_SIZE(OCFS2_XATTR_ROOT_SIZE);
5374
5375                 if (old >= value_size)
5376                         need = 0;
5377         }
5378
5379         free = xh_free_start - header_size - OCFS2_XATTR_HEADER_GAP;
5380         /*
5381          * We need to make sure the new name/value pair
5382          * can exist in the same block.
5383          */
5384         if (xh_free_start % blocksize < need)
5385                 free -= xh_free_start % blocksize;
5386
5387         mlog(0, "xs->not_found = %d, in xattr bucket %llu: free = %d, "
5388              "need = %d, max_free = %d, xh_free_start = %u, xh_name_value_len ="
5389              " %u\n", xs->not_found,
5390              (unsigned long long)bucket_blkno(xs->bucket),
5391              free, need, max_free, le16_to_cpu(xh->xh_free_start),
5392              le16_to_cpu(xh->xh_name_value_len));
5393
5394         if (free < need ||
5395             (xs->not_found &&
5396              count == ocfs2_xattr_max_xe_in_bucket(inode->i_sb))) {
5397                 if (need <= max_free &&
5398                     count < ocfs2_xattr_max_xe_in_bucket(inode->i_sb)) {
5399                         /*
5400                          * We can create the space by defragment. Since only the
5401                          * name/value will be moved, the xe shouldn't be changed
5402                          * in xs.
5403                          */
5404                         ret = ocfs2_defrag_xattr_bucket(inode, ctxt->handle,
5405                                                         xs->bucket);
5406                         if (ret) {
5407                                 mlog_errno(ret);
5408                                 goto out;
5409                         }
5410
5411                         xh_free_start = le16_to_cpu(xh->xh_free_start);
5412                         free = xh_free_start - header_size
5413                                 - OCFS2_XATTR_HEADER_GAP;
5414                         if (xh_free_start % blocksize < need)
5415                                 free -= xh_free_start % blocksize;
5416
5417                         if (free >= need)
5418                                 goto xattr_set;
5419
5420                         mlog(0, "Can't get enough space for xattr insert by "
5421                              "defragment. Need %u bytes, but we have %d, so "
5422                              "allocate new bucket for it.\n", need, free);
5423                 }
5424
5425                 /*
5426                  * We have to add new buckets or clusters and one
5427                  * allocation should leave us enough space for insert.
5428                  */
5429                 BUG_ON(allocation);
5430
5431                 /*
5432                  * We do not allow for overlapping ranges between buckets. And
5433                  * the maximum number of collisions we will allow for then is
5434                  * one bucket's worth, so check it here whether we need to
5435                  * add a new bucket for the insert.
5436                  */
5437                 ret = ocfs2_check_xattr_bucket_collision(inode,
5438                                                          xs->bucket,
5439                                                          xi->name);
5440           &