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