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