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