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