xref: /linux/fs/ocfs2/refcounttree.c (revision e60255f07c6a1f5bbbd490a2db23fe9eee8c6fd4)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * refcounttree.c
4  *
5  * Copyright (C) 2009 Oracle.  All rights reserved.
6  */
7 
8 #include <linux/sort.h>
9 #include <cluster/masklog.h>
10 #include "ocfs2.h"
11 #include "inode.h"
12 #include "alloc.h"
13 #include "suballoc.h"
14 #include "journal.h"
15 #include "uptodate.h"
16 #include "super.h"
17 #include "buffer_head_io.h"
18 #include "blockcheck.h"
19 #include "refcounttree.h"
20 #include "sysfile.h"
21 #include "dlmglue.h"
22 #include "extent_map.h"
23 #include "aops.h"
24 #include "xattr.h"
25 #include "namei.h"
26 #include "ocfs2_trace.h"
27 #include "file.h"
28 
29 #include <linux/bio.h>
30 #include <linux/blkdev.h>
31 #include <linux/slab.h>
32 #include <linux/writeback.h>
33 #include <linux/pagevec.h>
34 #include <linux/swap.h>
35 #include <linux/security.h>
36 #include <linux/fsnotify.h>
37 #include <linux/quotaops.h>
38 #include <linux/namei.h>
39 #include <linux/mount.h>
40 #include <linux/posix_acl.h>
41 
42 struct ocfs2_cow_context {
43 	struct inode *inode;
44 	u32 cow_start;
45 	u32 cow_len;
46 	struct ocfs2_extent_tree data_et;
47 	struct ocfs2_refcount_tree *ref_tree;
48 	struct buffer_head *ref_root_bh;
49 	struct ocfs2_alloc_context *meta_ac;
50 	struct ocfs2_alloc_context *data_ac;
51 	struct ocfs2_cached_dealloc_ctxt dealloc;
52 	void *cow_object;
53 	struct ocfs2_post_refcount *post_refcount;
54 	int extra_credits;
55 	int (*get_clusters)(struct ocfs2_cow_context *context,
56 			    u32 v_cluster, u32 *p_cluster,
57 			    u32 *num_clusters,
58 			    unsigned int *extent_flags);
59 	int (*cow_duplicate_clusters)(handle_t *handle,
60 				      struct inode *inode,
61 				      u32 cpos, u32 old_cluster,
62 				      u32 new_cluster, u32 new_len);
63 };
64 
65 static inline struct ocfs2_refcount_tree *
66 cache_info_to_refcount(struct ocfs2_caching_info *ci)
67 {
68 	return container_of(ci, struct ocfs2_refcount_tree, rf_ci);
69 }
70 
71 static int ocfs2_validate_refcount_block(struct super_block *sb,
72 					 struct buffer_head *bh)
73 {
74 	int rc;
75 	struct ocfs2_refcount_block *rb =
76 		(struct ocfs2_refcount_block *)bh->b_data;
77 
78 	trace_ocfs2_validate_refcount_block((unsigned long long)bh->b_blocknr);
79 
80 	BUG_ON(!buffer_uptodate(bh));
81 
82 	/*
83 	 * If the ecc fails, we return the error but otherwise
84 	 * leave the filesystem running.  We know any error is
85 	 * local to this block.
86 	 */
87 	rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &rb->rf_check);
88 	if (rc) {
89 		mlog(ML_ERROR, "Checksum failed for refcount block %llu\n",
90 		     (unsigned long long)bh->b_blocknr);
91 		return rc;
92 	}
93 
94 
95 	if (!OCFS2_IS_VALID_REFCOUNT_BLOCK(rb)) {
96 		rc = ocfs2_error(sb,
97 				 "Refcount block #%llu has bad signature %.*s\n",
98 				 (unsigned long long)bh->b_blocknr, 7,
99 				 rb->rf_signature);
100 		goto out;
101 	}
102 
103 	if (le64_to_cpu(rb->rf_blkno) != bh->b_blocknr) {
104 		rc = ocfs2_error(sb,
105 				 "Refcount block #%llu has an invalid rf_blkno of %llu\n",
106 				 (unsigned long long)bh->b_blocknr,
107 				 (unsigned long long)le64_to_cpu(rb->rf_blkno));
108 		goto out;
109 	}
110 
111 	if (le32_to_cpu(rb->rf_fs_generation) != OCFS2_SB(sb)->fs_generation) {
112 		rc = ocfs2_error(sb,
113 				 "Refcount block #%llu has an invalid rf_fs_generation of #%u\n",
114 				 (unsigned long long)bh->b_blocknr,
115 				 le32_to_cpu(rb->rf_fs_generation));
116 		goto out;
117 	}
118 out:
119 	return rc;
120 }
121 
122 static int ocfs2_read_refcount_block(struct ocfs2_caching_info *ci,
123 				     u64 rb_blkno,
124 				     struct buffer_head **bh)
125 {
126 	int rc;
127 	struct buffer_head *tmp = *bh;
128 
129 	rc = ocfs2_read_block(ci, rb_blkno, &tmp,
130 			      ocfs2_validate_refcount_block);
131 
132 	/* If ocfs2_read_block() got us a new bh, pass it up. */
133 	if (!rc && !*bh)
134 		*bh = tmp;
135 
136 	return rc;
137 }
138 
139 static u64 ocfs2_refcount_cache_owner(struct ocfs2_caching_info *ci)
140 {
141 	struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
142 
143 	return rf->rf_blkno;
144 }
145 
146 static struct super_block *
147 ocfs2_refcount_cache_get_super(struct ocfs2_caching_info *ci)
148 {
149 	struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
150 
151 	return rf->rf_sb;
152 }
153 
154 static void ocfs2_refcount_cache_lock(struct ocfs2_caching_info *ci)
155 __acquires(&rf->rf_lock)
156 {
157 	struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
158 
159 	spin_lock(&rf->rf_lock);
160 }
161 
162 static void ocfs2_refcount_cache_unlock(struct ocfs2_caching_info *ci)
163 __releases(&rf->rf_lock)
164 {
165 	struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
166 
167 	spin_unlock(&rf->rf_lock);
168 }
169 
170 static void ocfs2_refcount_cache_io_lock(struct ocfs2_caching_info *ci)
171 {
172 	struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
173 
174 	mutex_lock(&rf->rf_io_mutex);
175 }
176 
177 static void ocfs2_refcount_cache_io_unlock(struct ocfs2_caching_info *ci)
178 {
179 	struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
180 
181 	mutex_unlock(&rf->rf_io_mutex);
182 }
183 
184 static const struct ocfs2_caching_operations ocfs2_refcount_caching_ops = {
185 	.co_owner		= ocfs2_refcount_cache_owner,
186 	.co_get_super		= ocfs2_refcount_cache_get_super,
187 	.co_cache_lock		= ocfs2_refcount_cache_lock,
188 	.co_cache_unlock	= ocfs2_refcount_cache_unlock,
189 	.co_io_lock		= ocfs2_refcount_cache_io_lock,
190 	.co_io_unlock		= ocfs2_refcount_cache_io_unlock,
191 };
192 
193 static struct ocfs2_refcount_tree *
194 ocfs2_find_refcount_tree(struct ocfs2_super *osb, u64 blkno)
195 {
196 	struct rb_node *n = osb->osb_rf_lock_tree.rb_node;
197 	struct ocfs2_refcount_tree *tree = NULL;
198 
199 	while (n) {
200 		tree = rb_entry(n, struct ocfs2_refcount_tree, rf_node);
201 
202 		if (blkno < tree->rf_blkno)
203 			n = n->rb_left;
204 		else if (blkno > tree->rf_blkno)
205 			n = n->rb_right;
206 		else
207 			return tree;
208 	}
209 
210 	return NULL;
211 }
212 
213 /* osb_lock is already locked. */
214 static void ocfs2_insert_refcount_tree(struct ocfs2_super *osb,
215 				       struct ocfs2_refcount_tree *new)
216 {
217 	u64 rf_blkno = new->rf_blkno;
218 	struct rb_node *parent = NULL;
219 	struct rb_node **p = &osb->osb_rf_lock_tree.rb_node;
220 	struct ocfs2_refcount_tree *tmp;
221 
222 	while (*p) {
223 		parent = *p;
224 
225 		tmp = rb_entry(parent, struct ocfs2_refcount_tree,
226 			       rf_node);
227 
228 		if (rf_blkno < tmp->rf_blkno)
229 			p = &(*p)->rb_left;
230 		else if (rf_blkno > tmp->rf_blkno)
231 			p = &(*p)->rb_right;
232 		else {
233 			/* This should never happen! */
234 			mlog(ML_ERROR, "Duplicate refcount block %llu found!\n",
235 			     (unsigned long long)rf_blkno);
236 			BUG();
237 		}
238 	}
239 
240 	rb_link_node(&new->rf_node, parent, p);
241 	rb_insert_color(&new->rf_node, &osb->osb_rf_lock_tree);
242 }
243 
244 static void ocfs2_free_refcount_tree(struct ocfs2_refcount_tree *tree)
245 {
246 	ocfs2_metadata_cache_exit(&tree->rf_ci);
247 	ocfs2_simple_drop_lockres(OCFS2_SB(tree->rf_sb), &tree->rf_lockres);
248 	ocfs2_lock_res_free(&tree->rf_lockres);
249 	kfree(tree);
250 }
251 
252 static inline void
253 ocfs2_erase_refcount_tree_from_list_no_lock(struct ocfs2_super *osb,
254 					struct ocfs2_refcount_tree *tree)
255 {
256 	rb_erase(&tree->rf_node, &osb->osb_rf_lock_tree);
257 	if (osb->osb_ref_tree_lru && osb->osb_ref_tree_lru == tree)
258 		osb->osb_ref_tree_lru = NULL;
259 }
260 
261 static void ocfs2_erase_refcount_tree_from_list(struct ocfs2_super *osb,
262 					struct ocfs2_refcount_tree *tree)
263 {
264 	spin_lock(&osb->osb_lock);
265 	ocfs2_erase_refcount_tree_from_list_no_lock(osb, tree);
266 	spin_unlock(&osb->osb_lock);
267 }
268 
269 static void ocfs2_kref_remove_refcount_tree(struct kref *kref)
270 {
271 	struct ocfs2_refcount_tree *tree =
272 		container_of(kref, struct ocfs2_refcount_tree, rf_getcnt);
273 
274 	ocfs2_free_refcount_tree(tree);
275 }
276 
277 static inline void
278 ocfs2_refcount_tree_get(struct ocfs2_refcount_tree *tree)
279 {
280 	kref_get(&tree->rf_getcnt);
281 }
282 
283 static inline void
284 ocfs2_refcount_tree_put(struct ocfs2_refcount_tree *tree)
285 {
286 	kref_put(&tree->rf_getcnt, ocfs2_kref_remove_refcount_tree);
287 }
288 
289 static inline void ocfs2_init_refcount_tree_ci(struct ocfs2_refcount_tree *new,
290 					       struct super_block *sb)
291 {
292 	ocfs2_metadata_cache_init(&new->rf_ci, &ocfs2_refcount_caching_ops);
293 	mutex_init(&new->rf_io_mutex);
294 	new->rf_sb = sb;
295 	spin_lock_init(&new->rf_lock);
296 }
297 
298 static inline void ocfs2_init_refcount_tree_lock(struct ocfs2_super *osb,
299 					struct ocfs2_refcount_tree *new,
300 					u64 rf_blkno, u32 generation)
301 {
302 	init_rwsem(&new->rf_sem);
303 	ocfs2_refcount_lock_res_init(&new->rf_lockres, osb,
304 				     rf_blkno, generation);
305 }
306 
307 static struct ocfs2_refcount_tree*
308 ocfs2_allocate_refcount_tree(struct ocfs2_super *osb, u64 rf_blkno)
309 {
310 	struct ocfs2_refcount_tree *new;
311 
312 	new = kzalloc(sizeof(struct ocfs2_refcount_tree), GFP_NOFS);
313 	if (!new)
314 		return NULL;
315 
316 	new->rf_blkno = rf_blkno;
317 	kref_init(&new->rf_getcnt);
318 	ocfs2_init_refcount_tree_ci(new, osb->sb);
319 
320 	return new;
321 }
322 
323 static int ocfs2_get_refcount_tree(struct ocfs2_super *osb, u64 rf_blkno,
324 				   struct ocfs2_refcount_tree **ret_tree)
325 {
326 	int ret = 0;
327 	struct ocfs2_refcount_tree *tree, *new = NULL;
328 	struct buffer_head *ref_root_bh = NULL;
329 	struct ocfs2_refcount_block *ref_rb;
330 
331 	spin_lock(&osb->osb_lock);
332 	if (osb->osb_ref_tree_lru &&
333 	    osb->osb_ref_tree_lru->rf_blkno == rf_blkno)
334 		tree = osb->osb_ref_tree_lru;
335 	else
336 		tree = ocfs2_find_refcount_tree(osb, rf_blkno);
337 	if (tree)
338 		goto out;
339 
340 	spin_unlock(&osb->osb_lock);
341 
342 	new = ocfs2_allocate_refcount_tree(osb, rf_blkno);
343 	if (!new) {
344 		ret = -ENOMEM;
345 		mlog_errno(ret);
346 		return ret;
347 	}
348 	/*
349 	 * We need the generation to create the refcount tree lock and since
350 	 * it isn't changed during the tree modification, we are safe here to
351 	 * read without protection.
352 	 * We also have to purge the cache after we create the lock since the
353 	 * refcount block may have the stale data. It can only be trusted when
354 	 * we hold the refcount lock.
355 	 */
356 	ret = ocfs2_read_refcount_block(&new->rf_ci, rf_blkno, &ref_root_bh);
357 	if (ret) {
358 		mlog_errno(ret);
359 		ocfs2_metadata_cache_exit(&new->rf_ci);
360 		kfree(new);
361 		return ret;
362 	}
363 
364 	ref_rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
365 	new->rf_generation = le32_to_cpu(ref_rb->rf_generation);
366 	ocfs2_init_refcount_tree_lock(osb, new, rf_blkno,
367 				      new->rf_generation);
368 	ocfs2_metadata_cache_purge(&new->rf_ci);
369 
370 	spin_lock(&osb->osb_lock);
371 	tree = ocfs2_find_refcount_tree(osb, rf_blkno);
372 	if (tree)
373 		goto out;
374 
375 	ocfs2_insert_refcount_tree(osb, new);
376 
377 	tree = new;
378 	new = NULL;
379 
380 out:
381 	*ret_tree = tree;
382 
383 	osb->osb_ref_tree_lru = tree;
384 
385 	spin_unlock(&osb->osb_lock);
386 
387 	if (new)
388 		ocfs2_free_refcount_tree(new);
389 
390 	brelse(ref_root_bh);
391 	return ret;
392 }
393 
394 static int ocfs2_get_refcount_block(struct inode *inode, u64 *ref_blkno)
395 {
396 	int ret;
397 	struct buffer_head *di_bh = NULL;
398 	struct ocfs2_dinode *di;
399 
400 	ret = ocfs2_read_inode_block(inode, &di_bh);
401 	if (ret) {
402 		mlog_errno(ret);
403 		goto out;
404 	}
405 
406 	BUG_ON(!ocfs2_is_refcount_inode(inode));
407 
408 	di = (struct ocfs2_dinode *)di_bh->b_data;
409 	*ref_blkno = le64_to_cpu(di->i_refcount_loc);
410 	brelse(di_bh);
411 out:
412 	return ret;
413 }
414 
415 static int __ocfs2_lock_refcount_tree(struct ocfs2_super *osb,
416 				      struct ocfs2_refcount_tree *tree, int rw)
417 {
418 	int ret;
419 
420 	ret = ocfs2_refcount_lock(tree, rw);
421 	if (ret) {
422 		mlog_errno(ret);
423 		goto out;
424 	}
425 
426 	if (rw)
427 		down_write(&tree->rf_sem);
428 	else
429 		down_read(&tree->rf_sem);
430 
431 out:
432 	return ret;
433 }
434 
435 /*
436  * Lock the refcount tree pointed by ref_blkno and return the tree.
437  * In most case, we lock the tree and read the refcount block.
438  * So read it here if the caller really needs it.
439  *
440  * If the tree has been re-created by other node, it will free the
441  * old one and re-create it.
442  */
443 int ocfs2_lock_refcount_tree(struct ocfs2_super *osb,
444 			     u64 ref_blkno, int rw,
445 			     struct ocfs2_refcount_tree **ret_tree,
446 			     struct buffer_head **ref_bh)
447 {
448 	int ret, delete_tree = 0;
449 	struct ocfs2_refcount_tree *tree = NULL;
450 	struct buffer_head *ref_root_bh = NULL;
451 	struct ocfs2_refcount_block *rb;
452 
453 again:
454 	ret = ocfs2_get_refcount_tree(osb, ref_blkno, &tree);
455 	if (ret) {
456 		mlog_errno(ret);
457 		return ret;
458 	}
459 
460 	ocfs2_refcount_tree_get(tree);
461 
462 	ret = __ocfs2_lock_refcount_tree(osb, tree, rw);
463 	if (ret) {
464 		mlog_errno(ret);
465 		ocfs2_refcount_tree_put(tree);
466 		goto out;
467 	}
468 
469 	ret = ocfs2_read_refcount_block(&tree->rf_ci, tree->rf_blkno,
470 					&ref_root_bh);
471 	if (ret) {
472 		mlog_errno(ret);
473 		ocfs2_unlock_refcount_tree(osb, tree, rw);
474 		goto out;
475 	}
476 
477 	rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
478 	/*
479 	 * If the refcount block has been freed and re-created, we may need
480 	 * to recreate the refcount tree also.
481 	 *
482 	 * Here we just remove the tree from the rb-tree, and the last
483 	 * kref holder will unlock and delete this refcount_tree.
484 	 * Then we goto "again" and ocfs2_get_refcount_tree will create
485 	 * the new refcount tree for us.
486 	 */
487 	if (tree->rf_generation != le32_to_cpu(rb->rf_generation)) {
488 		if (!tree->rf_removed) {
489 			ocfs2_erase_refcount_tree_from_list(osb, tree);
490 			tree->rf_removed = 1;
491 			delete_tree = 1;
492 		}
493 
494 		ocfs2_unlock_refcount_tree(osb, tree, rw);
495 		/*
496 		 * We get an extra reference when we create the refcount
497 		 * tree, so another put will destroy it.
498 		 */
499 		if (delete_tree)
500 			ocfs2_refcount_tree_put(tree);
501 		brelse(ref_root_bh);
502 		ref_root_bh = NULL;
503 		goto again;
504 	}
505 
506 	*ret_tree = tree;
507 	if (ref_bh) {
508 		*ref_bh = ref_root_bh;
509 		ref_root_bh = NULL;
510 	}
511 out:
512 	brelse(ref_root_bh);
513 	return ret;
514 }
515 
516 void ocfs2_unlock_refcount_tree(struct ocfs2_super *osb,
517 				struct ocfs2_refcount_tree *tree, int rw)
518 {
519 	if (rw)
520 		up_write(&tree->rf_sem);
521 	else
522 		up_read(&tree->rf_sem);
523 
524 	ocfs2_refcount_unlock(tree, rw);
525 	ocfs2_refcount_tree_put(tree);
526 }
527 
528 void ocfs2_purge_refcount_trees(struct ocfs2_super *osb)
529 {
530 	struct rb_node *node;
531 	struct ocfs2_refcount_tree *tree;
532 	struct rb_root *root = &osb->osb_rf_lock_tree;
533 
534 	while ((node = rb_last(root)) != NULL) {
535 		tree = rb_entry(node, struct ocfs2_refcount_tree, rf_node);
536 
537 		trace_ocfs2_purge_refcount_trees(
538 				(unsigned long long) tree->rf_blkno);
539 
540 		rb_erase(&tree->rf_node, root);
541 		ocfs2_free_refcount_tree(tree);
542 	}
543 }
544 
545 /*
546  * Create a refcount tree for an inode.
547  * We take for granted that the inode is already locked.
548  */
549 static int ocfs2_create_refcount_tree(struct inode *inode,
550 				      struct buffer_head *di_bh)
551 {
552 	int ret;
553 	handle_t *handle = NULL;
554 	struct ocfs2_alloc_context *meta_ac = NULL;
555 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
556 	struct ocfs2_inode_info *oi = OCFS2_I(inode);
557 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
558 	struct buffer_head *new_bh = NULL;
559 	struct ocfs2_refcount_block *rb;
560 	struct ocfs2_refcount_tree *new_tree = NULL, *tree = NULL;
561 	u16 suballoc_bit_start;
562 	u32 num_got;
563 	u64 suballoc_loc, first_blkno;
564 
565 	BUG_ON(ocfs2_is_refcount_inode(inode));
566 
567 	trace_ocfs2_create_refcount_tree(
568 		(unsigned long long)oi->ip_blkno);
569 
570 	ret = ocfs2_reserve_new_metadata_blocks(osb, 1, &meta_ac);
571 	if (ret) {
572 		mlog_errno(ret);
573 		goto out;
574 	}
575 
576 	handle = ocfs2_start_trans(osb, OCFS2_REFCOUNT_TREE_CREATE_CREDITS);
577 	if (IS_ERR(handle)) {
578 		ret = PTR_ERR(handle);
579 		mlog_errno(ret);
580 		goto out;
581 	}
582 
583 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
584 				      OCFS2_JOURNAL_ACCESS_WRITE);
585 	if (ret) {
586 		mlog_errno(ret);
587 		goto out_commit;
588 	}
589 
590 	ret = ocfs2_claim_metadata(handle, meta_ac, 1, &suballoc_loc,
591 				   &suballoc_bit_start, &num_got,
592 				   &first_blkno);
593 	if (ret) {
594 		mlog_errno(ret);
595 		goto out_commit;
596 	}
597 
598 	new_tree = ocfs2_allocate_refcount_tree(osb, first_blkno);
599 	if (!new_tree) {
600 		ret = -ENOMEM;
601 		mlog_errno(ret);
602 		goto out_commit;
603 	}
604 
605 	new_bh = sb_getblk(inode->i_sb, first_blkno);
606 	if (!new_bh) {
607 		ret = -ENOMEM;
608 		mlog_errno(ret);
609 		goto out_commit;
610 	}
611 	ocfs2_set_new_buffer_uptodate(&new_tree->rf_ci, new_bh);
612 
613 	ret = ocfs2_journal_access_rb(handle, &new_tree->rf_ci, new_bh,
614 				      OCFS2_JOURNAL_ACCESS_CREATE);
615 	if (ret) {
616 		mlog_errno(ret);
617 		goto out_commit;
618 	}
619 
620 	/* Initialize ocfs2_refcount_block. */
621 	rb = (struct ocfs2_refcount_block *)new_bh->b_data;
622 	memset(rb, 0, inode->i_sb->s_blocksize);
623 	strcpy((void *)rb, OCFS2_REFCOUNT_BLOCK_SIGNATURE);
624 	rb->rf_suballoc_slot = cpu_to_le16(meta_ac->ac_alloc_slot);
625 	rb->rf_suballoc_loc = cpu_to_le64(suballoc_loc);
626 	rb->rf_suballoc_bit = cpu_to_le16(suballoc_bit_start);
627 	rb->rf_fs_generation = cpu_to_le32(osb->fs_generation);
628 	rb->rf_blkno = cpu_to_le64(first_blkno);
629 	rb->rf_count = cpu_to_le32(1);
630 	rb->rf_records.rl_count =
631 			cpu_to_le16(ocfs2_refcount_recs_per_rb(osb->sb));
632 	spin_lock(&osb->osb_lock);
633 	rb->rf_generation = cpu_to_le32(osb->s_next_generation++);
634 	spin_unlock(&osb->osb_lock);
635 
636 	ocfs2_journal_dirty(handle, new_bh);
637 
638 	spin_lock(&oi->ip_lock);
639 	oi->ip_dyn_features |= OCFS2_HAS_REFCOUNT_FL;
640 	di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
641 	di->i_refcount_loc = cpu_to_le64(first_blkno);
642 	spin_unlock(&oi->ip_lock);
643 
644 	trace_ocfs2_create_refcount_tree_blkno((unsigned long long)first_blkno);
645 
646 	ocfs2_journal_dirty(handle, di_bh);
647 
648 	/*
649 	 * We have to init the tree lock here since it will use
650 	 * the generation number to create it.
651 	 */
652 	new_tree->rf_generation = le32_to_cpu(rb->rf_generation);
653 	ocfs2_init_refcount_tree_lock(osb, new_tree, first_blkno,
654 				      new_tree->rf_generation);
655 
656 	spin_lock(&osb->osb_lock);
657 	tree = ocfs2_find_refcount_tree(osb, first_blkno);
658 
659 	/*
660 	 * We've just created a new refcount tree in this block.  If
661 	 * we found a refcount tree on the ocfs2_super, it must be
662 	 * one we just deleted.  We free the old tree before
663 	 * inserting the new tree.
664 	 */
665 	BUG_ON(tree && tree->rf_generation == new_tree->rf_generation);
666 	if (tree)
667 		ocfs2_erase_refcount_tree_from_list_no_lock(osb, tree);
668 	ocfs2_insert_refcount_tree(osb, new_tree);
669 	spin_unlock(&osb->osb_lock);
670 	new_tree = NULL;
671 	if (tree)
672 		ocfs2_refcount_tree_put(tree);
673 
674 out_commit:
675 	ocfs2_commit_trans(osb, handle);
676 
677 out:
678 	if (new_tree) {
679 		ocfs2_metadata_cache_exit(&new_tree->rf_ci);
680 		kfree(new_tree);
681 	}
682 
683 	brelse(new_bh);
684 	if (meta_ac)
685 		ocfs2_free_alloc_context(meta_ac);
686 
687 	return ret;
688 }
689 
690 static int ocfs2_set_refcount_tree(struct inode *inode,
691 				   struct buffer_head *di_bh,
692 				   u64 refcount_loc)
693 {
694 	int ret;
695 	handle_t *handle = NULL;
696 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
697 	struct ocfs2_inode_info *oi = OCFS2_I(inode);
698 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
699 	struct buffer_head *ref_root_bh = NULL;
700 	struct ocfs2_refcount_block *rb;
701 	struct ocfs2_refcount_tree *ref_tree;
702 
703 	BUG_ON(ocfs2_is_refcount_inode(inode));
704 
705 	ret = ocfs2_lock_refcount_tree(osb, refcount_loc, 1,
706 				       &ref_tree, &ref_root_bh);
707 	if (ret) {
708 		mlog_errno(ret);
709 		return ret;
710 	}
711 
712 	handle = ocfs2_start_trans(osb, OCFS2_REFCOUNT_TREE_SET_CREDITS);
713 	if (IS_ERR(handle)) {
714 		ret = PTR_ERR(handle);
715 		mlog_errno(ret);
716 		goto out;
717 	}
718 
719 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
720 				      OCFS2_JOURNAL_ACCESS_WRITE);
721 	if (ret) {
722 		mlog_errno(ret);
723 		goto out_commit;
724 	}
725 
726 	ret = ocfs2_journal_access_rb(handle, &ref_tree->rf_ci, ref_root_bh,
727 				      OCFS2_JOURNAL_ACCESS_WRITE);
728 	if (ret) {
729 		mlog_errno(ret);
730 		goto out_commit;
731 	}
732 
733 	rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
734 	le32_add_cpu(&rb->rf_count, 1);
735 
736 	ocfs2_journal_dirty(handle, ref_root_bh);
737 
738 	spin_lock(&oi->ip_lock);
739 	oi->ip_dyn_features |= OCFS2_HAS_REFCOUNT_FL;
740 	di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
741 	di->i_refcount_loc = cpu_to_le64(refcount_loc);
742 	spin_unlock(&oi->ip_lock);
743 	ocfs2_journal_dirty(handle, di_bh);
744 
745 out_commit:
746 	ocfs2_commit_trans(osb, handle);
747 out:
748 	ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
749 	brelse(ref_root_bh);
750 
751 	return ret;
752 }
753 
754 int ocfs2_remove_refcount_tree(struct inode *inode, struct buffer_head *di_bh)
755 {
756 	int ret, delete_tree = 0;
757 	handle_t *handle = NULL;
758 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
759 	struct ocfs2_inode_info *oi = OCFS2_I(inode);
760 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
761 	struct ocfs2_refcount_block *rb;
762 	struct inode *alloc_inode = NULL;
763 	struct buffer_head *alloc_bh = NULL;
764 	struct buffer_head *blk_bh = NULL;
765 	struct ocfs2_refcount_tree *ref_tree;
766 	int credits = OCFS2_REFCOUNT_TREE_REMOVE_CREDITS;
767 	u64 blk = 0, bg_blkno = 0, ref_blkno = le64_to_cpu(di->i_refcount_loc);
768 	u16 bit = 0;
769 
770 	if (!ocfs2_is_refcount_inode(inode))
771 		return 0;
772 
773 	BUG_ON(!ref_blkno);
774 	ret = ocfs2_lock_refcount_tree(osb, ref_blkno, 1, &ref_tree, &blk_bh);
775 	if (ret) {
776 		mlog_errno(ret);
777 		return ret;
778 	}
779 
780 	rb = (struct ocfs2_refcount_block *)blk_bh->b_data;
781 
782 	/*
783 	 * If we are the last user, we need to free the block.
784 	 * So lock the allocator ahead.
785 	 */
786 	if (le32_to_cpu(rb->rf_count) == 1) {
787 		blk = le64_to_cpu(rb->rf_blkno);
788 		bit = le16_to_cpu(rb->rf_suballoc_bit);
789 		if (rb->rf_suballoc_loc)
790 			bg_blkno = le64_to_cpu(rb->rf_suballoc_loc);
791 		else
792 			bg_blkno = ocfs2_which_suballoc_group(blk, bit);
793 
794 		alloc_inode = ocfs2_get_system_file_inode(osb,
795 					EXTENT_ALLOC_SYSTEM_INODE,
796 					le16_to_cpu(rb->rf_suballoc_slot));
797 		if (!alloc_inode) {
798 			ret = -ENOMEM;
799 			mlog_errno(ret);
800 			goto out;
801 		}
802 		inode_lock(alloc_inode);
803 
804 		ret = ocfs2_inode_lock(alloc_inode, &alloc_bh, 1);
805 		if (ret) {
806 			mlog_errno(ret);
807 			goto out_mutex;
808 		}
809 
810 		credits += OCFS2_SUBALLOC_FREE;
811 	}
812 
813 	handle = ocfs2_start_trans(osb, credits);
814 	if (IS_ERR(handle)) {
815 		ret = PTR_ERR(handle);
816 		mlog_errno(ret);
817 		goto out_unlock;
818 	}
819 
820 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
821 				      OCFS2_JOURNAL_ACCESS_WRITE);
822 	if (ret) {
823 		mlog_errno(ret);
824 		goto out_commit;
825 	}
826 
827 	ret = ocfs2_journal_access_rb(handle, &ref_tree->rf_ci, blk_bh,
828 				      OCFS2_JOURNAL_ACCESS_WRITE);
829 	if (ret) {
830 		mlog_errno(ret);
831 		goto out_commit;
832 	}
833 
834 	spin_lock(&oi->ip_lock);
835 	oi->ip_dyn_features &= ~OCFS2_HAS_REFCOUNT_FL;
836 	di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
837 	di->i_refcount_loc = 0;
838 	spin_unlock(&oi->ip_lock);
839 	ocfs2_journal_dirty(handle, di_bh);
840 
841 	le32_add_cpu(&rb->rf_count , -1);
842 	ocfs2_journal_dirty(handle, blk_bh);
843 
844 	if (!rb->rf_count) {
845 		delete_tree = 1;
846 		ocfs2_erase_refcount_tree_from_list(osb, ref_tree);
847 		ret = ocfs2_free_suballoc_bits(handle, alloc_inode,
848 					       alloc_bh, bit, bg_blkno, 1);
849 		if (ret)
850 			mlog_errno(ret);
851 	}
852 
853 out_commit:
854 	ocfs2_commit_trans(osb, handle);
855 out_unlock:
856 	if (alloc_inode) {
857 		ocfs2_inode_unlock(alloc_inode, 1);
858 		brelse(alloc_bh);
859 	}
860 out_mutex:
861 	if (alloc_inode) {
862 		inode_unlock(alloc_inode);
863 		iput(alloc_inode);
864 	}
865 out:
866 	ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
867 	if (delete_tree)
868 		ocfs2_refcount_tree_put(ref_tree);
869 	brelse(blk_bh);
870 
871 	return ret;
872 }
873 
874 static void ocfs2_find_refcount_rec_in_rl(struct ocfs2_caching_info *ci,
875 					  struct buffer_head *ref_leaf_bh,
876 					  u64 cpos, unsigned int len,
877 					  struct ocfs2_refcount_rec *ret_rec,
878 					  int *index)
879 {
880 	int i = 0;
881 	struct ocfs2_refcount_block *rb =
882 		(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
883 	struct ocfs2_refcount_rec *rec = NULL;
884 
885 	for (; i < le16_to_cpu(rb->rf_records.rl_used); i++) {
886 		rec = &rb->rf_records.rl_recs[i];
887 
888 		if (le64_to_cpu(rec->r_cpos) +
889 		    le32_to_cpu(rec->r_clusters) <= cpos)
890 			continue;
891 		else if (le64_to_cpu(rec->r_cpos) > cpos)
892 			break;
893 
894 		/* ok, cpos fail in this rec. Just return. */
895 		if (ret_rec)
896 			*ret_rec = *rec;
897 		goto out;
898 	}
899 
900 	if (ret_rec) {
901 		/* We meet with a hole here, so fake the rec. */
902 		ret_rec->r_cpos = cpu_to_le64(cpos);
903 		ret_rec->r_refcount = 0;
904 		if (i < le16_to_cpu(rb->rf_records.rl_used) &&
905 		    le64_to_cpu(rec->r_cpos) < cpos + len)
906 			ret_rec->r_clusters =
907 				cpu_to_le32(le64_to_cpu(rec->r_cpos) - cpos);
908 		else
909 			ret_rec->r_clusters = cpu_to_le32(len);
910 	}
911 
912 out:
913 	*index = i;
914 }
915 
916 /*
917  * Try to remove refcount tree. The mechanism is:
918  * 1) Check whether i_clusters == 0, if no, exit.
919  * 2) check whether we have i_xattr_loc in dinode. if yes, exit.
920  * 3) Check whether we have inline xattr stored outside, if yes, exit.
921  * 4) Remove the tree.
922  */
923 int ocfs2_try_remove_refcount_tree(struct inode *inode,
924 				   struct buffer_head *di_bh)
925 {
926 	int ret;
927 	struct ocfs2_inode_info *oi = OCFS2_I(inode);
928 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
929 
930 	down_write(&oi->ip_xattr_sem);
931 	down_write(&oi->ip_alloc_sem);
932 
933 	if (oi->ip_clusters)
934 		goto out;
935 
936 	if ((oi->ip_dyn_features & OCFS2_HAS_XATTR_FL) && di->i_xattr_loc)
937 		goto out;
938 
939 	if (oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL &&
940 	    ocfs2_has_inline_xattr_value_outside(inode, di))
941 		goto out;
942 
943 	ret = ocfs2_remove_refcount_tree(inode, di_bh);
944 	if (ret)
945 		mlog_errno(ret);
946 out:
947 	up_write(&oi->ip_alloc_sem);
948 	up_write(&oi->ip_xattr_sem);
949 	return 0;
950 }
951 
952 /*
953  * Find the end range for a leaf refcount block indicated by
954  * el->l_recs[index].e_blkno.
955  */
956 static int ocfs2_get_refcount_cpos_end(struct ocfs2_caching_info *ci,
957 				       struct buffer_head *ref_root_bh,
958 				       struct ocfs2_extent_block *eb,
959 				       struct ocfs2_extent_list *el,
960 				       int index,  u32 *cpos_end)
961 {
962 	int ret, i, subtree_root;
963 	u32 cpos;
964 	u64 blkno;
965 	struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
966 	struct ocfs2_path *left_path = NULL, *right_path = NULL;
967 	struct ocfs2_extent_tree et;
968 	struct ocfs2_extent_list *tmp_el;
969 
970 	if (index < le16_to_cpu(el->l_next_free_rec) - 1) {
971 		/*
972 		 * We have a extent rec after index, so just use the e_cpos
973 		 * of the next extent rec.
974 		 */
975 		*cpos_end = le32_to_cpu(el->l_recs[index+1].e_cpos);
976 		return 0;
977 	}
978 
979 	if (!eb || !eb->h_next_leaf_blk) {
980 		/*
981 		 * We are the last extent rec, so any high cpos should
982 		 * be stored in this leaf refcount block.
983 		 */
984 		*cpos_end = UINT_MAX;
985 		return 0;
986 	}
987 
988 	/*
989 	 * If the extent block isn't the last one, we have to find
990 	 * the subtree root between this extent block and the next
991 	 * leaf extent block and get the corresponding e_cpos from
992 	 * the subroot. Otherwise we may corrupt the b-tree.
993 	 */
994 	ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
995 
996 	left_path = ocfs2_new_path_from_et(&et);
997 	if (!left_path) {
998 		ret = -ENOMEM;
999 		mlog_errno(ret);
1000 		goto out;
1001 	}
1002 
1003 	cpos = le32_to_cpu(eb->h_list.l_recs[index].e_cpos);
1004 	ret = ocfs2_find_path(ci, left_path, cpos);
1005 	if (ret) {
1006 		mlog_errno(ret);
1007 		goto out;
1008 	}
1009 
1010 	right_path = ocfs2_new_path_from_path(left_path);
1011 	if (!right_path) {
1012 		ret = -ENOMEM;
1013 		mlog_errno(ret);
1014 		goto out;
1015 	}
1016 
1017 	ret = ocfs2_find_cpos_for_right_leaf(sb, left_path, &cpos);
1018 	if (ret) {
1019 		mlog_errno(ret);
1020 		goto out;
1021 	}
1022 
1023 	ret = ocfs2_find_path(ci, right_path, cpos);
1024 	if (ret) {
1025 		mlog_errno(ret);
1026 		goto out;
1027 	}
1028 
1029 	subtree_root = ocfs2_find_subtree_root(&et, left_path,
1030 					       right_path);
1031 
1032 	tmp_el = left_path->p_node[subtree_root].el;
1033 	blkno = left_path->p_node[subtree_root+1].bh->b_blocknr;
1034 	for (i = 0; i < le16_to_cpu(tmp_el->l_next_free_rec); i++) {
1035 		if (le64_to_cpu(tmp_el->l_recs[i].e_blkno) == blkno) {
1036 			*cpos_end = le32_to_cpu(tmp_el->l_recs[i+1].e_cpos);
1037 			break;
1038 		}
1039 	}
1040 
1041 	BUG_ON(i == le16_to_cpu(tmp_el->l_next_free_rec));
1042 
1043 out:
1044 	ocfs2_free_path(left_path);
1045 	ocfs2_free_path(right_path);
1046 	return ret;
1047 }
1048 
1049 /*
1050  * Given a cpos and len, try to find the refcount record which contains cpos.
1051  * 1. If cpos can be found in one refcount record, return the record.
1052  * 2. If cpos can't be found, return a fake record which start from cpos
1053  *    and end at a small value between cpos+len and start of the next record.
1054  *    This fake record has r_refcount = 0.
1055  */
1056 static int ocfs2_get_refcount_rec(struct ocfs2_caching_info *ci,
1057 				  struct buffer_head *ref_root_bh,
1058 				  u64 cpos, unsigned int len,
1059 				  struct ocfs2_refcount_rec *ret_rec,
1060 				  int *index,
1061 				  struct buffer_head **ret_bh)
1062 {
1063 	int ret = 0, i, found;
1064 	u32 low_cpos, cpos_end;
1065 	struct ocfs2_extent_list *el;
1066 	struct ocfs2_extent_rec *rec = NULL;
1067 	struct ocfs2_extent_block *eb = NULL;
1068 	struct buffer_head *eb_bh = NULL, *ref_leaf_bh = NULL;
1069 	struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
1070 	struct ocfs2_refcount_block *rb =
1071 			(struct ocfs2_refcount_block *)ref_root_bh->b_data;
1072 
1073 	if (!(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL)) {
1074 		ocfs2_find_refcount_rec_in_rl(ci, ref_root_bh, cpos, len,
1075 					      ret_rec, index);
1076 		*ret_bh = ref_root_bh;
1077 		get_bh(ref_root_bh);
1078 		return 0;
1079 	}
1080 
1081 	el = &rb->rf_list;
1082 	low_cpos = cpos & OCFS2_32BIT_POS_MASK;
1083 
1084 	if (el->l_tree_depth) {
1085 		ret = ocfs2_find_leaf(ci, el, low_cpos, &eb_bh);
1086 		if (ret) {
1087 			mlog_errno(ret);
1088 			goto out;
1089 		}
1090 
1091 		eb = (struct ocfs2_extent_block *) eb_bh->b_data;
1092 		el = &eb->h_list;
1093 
1094 		if (el->l_tree_depth) {
1095 			ret = ocfs2_error(sb,
1096 					  "refcount tree %llu has non zero tree depth in leaf btree tree block %llu\n",
1097 					  (unsigned long long)ocfs2_metadata_cache_owner(ci),
1098 					  (unsigned long long)eb_bh->b_blocknr);
1099 			goto out;
1100 		}
1101 	}
1102 
1103 	found = 0;
1104 	for (i = le16_to_cpu(el->l_next_free_rec) - 1; i >= 0; i--) {
1105 		rec = &el->l_recs[i];
1106 
1107 		if (le32_to_cpu(rec->e_cpos) <= low_cpos) {
1108 			found = 1;
1109 			break;
1110 		}
1111 	}
1112 
1113 	if (found) {
1114 		ret = ocfs2_get_refcount_cpos_end(ci, ref_root_bh,
1115 						  eb, el, i, &cpos_end);
1116 		if (ret) {
1117 			mlog_errno(ret);
1118 			goto out;
1119 		}
1120 
1121 		if (cpos_end < low_cpos + len)
1122 			len = cpos_end - low_cpos;
1123 	}
1124 
1125 	ret = ocfs2_read_refcount_block(ci, le64_to_cpu(rec->e_blkno),
1126 					&ref_leaf_bh);
1127 	if (ret) {
1128 		mlog_errno(ret);
1129 		goto out;
1130 	}
1131 
1132 	ocfs2_find_refcount_rec_in_rl(ci, ref_leaf_bh, cpos, len,
1133 				      ret_rec, index);
1134 	*ret_bh = ref_leaf_bh;
1135 out:
1136 	brelse(eb_bh);
1137 	return ret;
1138 }
1139 
1140 enum ocfs2_ref_rec_contig {
1141 	REF_CONTIG_NONE = 0,
1142 	REF_CONTIG_LEFT,
1143 	REF_CONTIG_RIGHT,
1144 	REF_CONTIG_LEFTRIGHT,
1145 };
1146 
1147 static enum ocfs2_ref_rec_contig
1148 	ocfs2_refcount_rec_adjacent(struct ocfs2_refcount_block *rb,
1149 				    int index)
1150 {
1151 	if ((rb->rf_records.rl_recs[index].r_refcount ==
1152 	    rb->rf_records.rl_recs[index + 1].r_refcount) &&
1153 	    (le64_to_cpu(rb->rf_records.rl_recs[index].r_cpos) +
1154 	    le32_to_cpu(rb->rf_records.rl_recs[index].r_clusters) ==
1155 	    le64_to_cpu(rb->rf_records.rl_recs[index + 1].r_cpos)))
1156 		return REF_CONTIG_RIGHT;
1157 
1158 	return REF_CONTIG_NONE;
1159 }
1160 
1161 static enum ocfs2_ref_rec_contig
1162 	ocfs2_refcount_rec_contig(struct ocfs2_refcount_block *rb,
1163 				  int index)
1164 {
1165 	enum ocfs2_ref_rec_contig ret = REF_CONTIG_NONE;
1166 
1167 	if (index < le16_to_cpu(rb->rf_records.rl_used) - 1)
1168 		ret = ocfs2_refcount_rec_adjacent(rb, index);
1169 
1170 	if (index > 0) {
1171 		enum ocfs2_ref_rec_contig tmp;
1172 
1173 		tmp = ocfs2_refcount_rec_adjacent(rb, index - 1);
1174 
1175 		if (tmp == REF_CONTIG_RIGHT) {
1176 			if (ret == REF_CONTIG_RIGHT)
1177 				ret = REF_CONTIG_LEFTRIGHT;
1178 			else
1179 				ret = REF_CONTIG_LEFT;
1180 		}
1181 	}
1182 
1183 	return ret;
1184 }
1185 
1186 static void ocfs2_rotate_refcount_rec_left(struct ocfs2_refcount_block *rb,
1187 					   int index)
1188 {
1189 	BUG_ON(rb->rf_records.rl_recs[index].r_refcount !=
1190 	       rb->rf_records.rl_recs[index+1].r_refcount);
1191 
1192 	le32_add_cpu(&rb->rf_records.rl_recs[index].r_clusters,
1193 		     le32_to_cpu(rb->rf_records.rl_recs[index+1].r_clusters));
1194 
1195 	if (index < le16_to_cpu(rb->rf_records.rl_used) - 2)
1196 		memmove(&rb->rf_records.rl_recs[index + 1],
1197 			&rb->rf_records.rl_recs[index + 2],
1198 			sizeof(struct ocfs2_refcount_rec) *
1199 			(le16_to_cpu(rb->rf_records.rl_used) - index - 2));
1200 
1201 	memset(&rb->rf_records.rl_recs[le16_to_cpu(rb->rf_records.rl_used) - 1],
1202 	       0, sizeof(struct ocfs2_refcount_rec));
1203 	le16_add_cpu(&rb->rf_records.rl_used, -1);
1204 }
1205 
1206 /*
1207  * Merge the refcount rec if we are contiguous with the adjacent recs.
1208  */
1209 static void ocfs2_refcount_rec_merge(struct ocfs2_refcount_block *rb,
1210 				     int index)
1211 {
1212 	enum ocfs2_ref_rec_contig contig =
1213 				ocfs2_refcount_rec_contig(rb, index);
1214 
1215 	if (contig == REF_CONTIG_NONE)
1216 		return;
1217 
1218 	if (contig == REF_CONTIG_LEFT || contig == REF_CONTIG_LEFTRIGHT) {
1219 		BUG_ON(index == 0);
1220 		index--;
1221 	}
1222 
1223 	ocfs2_rotate_refcount_rec_left(rb, index);
1224 
1225 	if (contig == REF_CONTIG_LEFTRIGHT)
1226 		ocfs2_rotate_refcount_rec_left(rb, index);
1227 }
1228 
1229 /*
1230  * Change the refcount indexed by "index" in ref_bh.
1231  * If refcount reaches 0, remove it.
1232  */
1233 static int ocfs2_change_refcount_rec(handle_t *handle,
1234 				     struct ocfs2_caching_info *ci,
1235 				     struct buffer_head *ref_leaf_bh,
1236 				     int index, int merge, int change)
1237 {
1238 	int ret;
1239 	struct ocfs2_refcount_block *rb =
1240 			(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1241 	struct ocfs2_refcount_list *rl = &rb->rf_records;
1242 	struct ocfs2_refcount_rec *rec = &rl->rl_recs[index];
1243 
1244 	ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
1245 				      OCFS2_JOURNAL_ACCESS_WRITE);
1246 	if (ret) {
1247 		mlog_errno(ret);
1248 		goto out;
1249 	}
1250 
1251 	trace_ocfs2_change_refcount_rec(
1252 		(unsigned long long)ocfs2_metadata_cache_owner(ci),
1253 		index, le32_to_cpu(rec->r_refcount), change);
1254 	le32_add_cpu(&rec->r_refcount, change);
1255 
1256 	if (!rec->r_refcount) {
1257 		if (index != le16_to_cpu(rl->rl_used) - 1) {
1258 			memmove(rec, rec + 1,
1259 				(le16_to_cpu(rl->rl_used) - index - 1) *
1260 				sizeof(struct ocfs2_refcount_rec));
1261 			memset(&rl->rl_recs[le16_to_cpu(rl->rl_used) - 1],
1262 			       0, sizeof(struct ocfs2_refcount_rec));
1263 		}
1264 
1265 		le16_add_cpu(&rl->rl_used, -1);
1266 	} else if (merge)
1267 		ocfs2_refcount_rec_merge(rb, index);
1268 
1269 	ocfs2_journal_dirty(handle, ref_leaf_bh);
1270 out:
1271 	return ret;
1272 }
1273 
1274 static int ocfs2_expand_inline_ref_root(handle_t *handle,
1275 					struct ocfs2_caching_info *ci,
1276 					struct buffer_head *ref_root_bh,
1277 					struct buffer_head **ref_leaf_bh,
1278 					struct ocfs2_alloc_context *meta_ac)
1279 {
1280 	int ret;
1281 	u16 suballoc_bit_start;
1282 	u32 num_got;
1283 	u64 suballoc_loc, blkno;
1284 	struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
1285 	struct buffer_head *new_bh = NULL;
1286 	struct ocfs2_refcount_block *new_rb;
1287 	struct ocfs2_refcount_block *root_rb =
1288 			(struct ocfs2_refcount_block *)ref_root_bh->b_data;
1289 
1290 	ret = ocfs2_journal_access_rb(handle, ci, ref_root_bh,
1291 				      OCFS2_JOURNAL_ACCESS_WRITE);
1292 	if (ret) {
1293 		mlog_errno(ret);
1294 		goto out;
1295 	}
1296 
1297 	ret = ocfs2_claim_metadata(handle, meta_ac, 1, &suballoc_loc,
1298 				   &suballoc_bit_start, &num_got,
1299 				   &blkno);
1300 	if (ret) {
1301 		mlog_errno(ret);
1302 		goto out;
1303 	}
1304 
1305 	new_bh = sb_getblk(sb, blkno);
1306 	if (new_bh == NULL) {
1307 		ret = -ENOMEM;
1308 		mlog_errno(ret);
1309 		goto out;
1310 	}
1311 	ocfs2_set_new_buffer_uptodate(ci, new_bh);
1312 
1313 	ret = ocfs2_journal_access_rb(handle, ci, new_bh,
1314 				      OCFS2_JOURNAL_ACCESS_CREATE);
1315 	if (ret) {
1316 		mlog_errno(ret);
1317 		goto out;
1318 	}
1319 
1320 	/*
1321 	 * Initialize ocfs2_refcount_block.
1322 	 * It should contain the same information as the old root.
1323 	 * so just memcpy it and change the corresponding field.
1324 	 */
1325 	memcpy(new_bh->b_data, ref_root_bh->b_data, sb->s_blocksize);
1326 
1327 	new_rb = (struct ocfs2_refcount_block *)new_bh->b_data;
1328 	new_rb->rf_suballoc_slot = cpu_to_le16(meta_ac->ac_alloc_slot);
1329 	new_rb->rf_suballoc_loc = cpu_to_le64(suballoc_loc);
1330 	new_rb->rf_suballoc_bit = cpu_to_le16(suballoc_bit_start);
1331 	new_rb->rf_blkno = cpu_to_le64(blkno);
1332 	new_rb->rf_cpos = cpu_to_le32(0);
1333 	new_rb->rf_parent = cpu_to_le64(ref_root_bh->b_blocknr);
1334 	new_rb->rf_flags = cpu_to_le32(OCFS2_REFCOUNT_LEAF_FL);
1335 	ocfs2_journal_dirty(handle, new_bh);
1336 
1337 	/* Now change the root. */
1338 	memset(&root_rb->rf_list, 0, sb->s_blocksize -
1339 	       offsetof(struct ocfs2_refcount_block, rf_list));
1340 	root_rb->rf_list.l_count = cpu_to_le16(ocfs2_extent_recs_per_rb(sb));
1341 	root_rb->rf_clusters = cpu_to_le32(1);
1342 	root_rb->rf_list.l_next_free_rec = cpu_to_le16(1);
1343 	root_rb->rf_list.l_recs[0].e_blkno = cpu_to_le64(blkno);
1344 	root_rb->rf_list.l_recs[0].e_leaf_clusters = cpu_to_le16(1);
1345 	root_rb->rf_flags = cpu_to_le32(OCFS2_REFCOUNT_TREE_FL);
1346 
1347 	ocfs2_journal_dirty(handle, ref_root_bh);
1348 
1349 	trace_ocfs2_expand_inline_ref_root((unsigned long long)blkno,
1350 		le16_to_cpu(new_rb->rf_records.rl_used));
1351 
1352 	*ref_leaf_bh = new_bh;
1353 	new_bh = NULL;
1354 out:
1355 	brelse(new_bh);
1356 	return ret;
1357 }
1358 
1359 static int ocfs2_refcount_rec_no_intersect(struct ocfs2_refcount_rec *prev,
1360 					   struct ocfs2_refcount_rec *next)
1361 {
1362 	if (ocfs2_get_ref_rec_low_cpos(prev) + le32_to_cpu(prev->r_clusters) <=
1363 		ocfs2_get_ref_rec_low_cpos(next))
1364 		return 1;
1365 
1366 	return 0;
1367 }
1368 
1369 static int cmp_refcount_rec_by_low_cpos(const void *a, const void *b)
1370 {
1371 	const struct ocfs2_refcount_rec *l = a, *r = b;
1372 	u32 l_cpos = ocfs2_get_ref_rec_low_cpos(l);
1373 	u32 r_cpos = ocfs2_get_ref_rec_low_cpos(r);
1374 
1375 	if (l_cpos > r_cpos)
1376 		return 1;
1377 	if (l_cpos < r_cpos)
1378 		return -1;
1379 	return 0;
1380 }
1381 
1382 static int cmp_refcount_rec_by_cpos(const void *a, const void *b)
1383 {
1384 	const struct ocfs2_refcount_rec *l = a, *r = b;
1385 	u64 l_cpos = le64_to_cpu(l->r_cpos);
1386 	u64 r_cpos = le64_to_cpu(r->r_cpos);
1387 
1388 	if (l_cpos > r_cpos)
1389 		return 1;
1390 	if (l_cpos < r_cpos)
1391 		return -1;
1392 	return 0;
1393 }
1394 
1395 /*
1396  * The refcount cpos are ordered by their 64bit cpos,
1397  * But we will use the low 32 bit to be the e_cpos in the b-tree.
1398  * So we need to make sure that this pos isn't intersected with others.
1399  *
1400  * Note: The refcount block is already sorted by their low 32 bit cpos,
1401  *       So just try the middle pos first, and we will exit when we find
1402  *       the good position.
1403  */
1404 static int ocfs2_find_refcount_split_pos(struct ocfs2_refcount_list *rl,
1405 					 u32 *split_pos, int *split_index)
1406 {
1407 	int num_used = le16_to_cpu(rl->rl_used);
1408 	int delta, middle = num_used / 2;
1409 
1410 	for (delta = 0; delta < middle; delta++) {
1411 		/* Let's check delta earlier than middle */
1412 		if (ocfs2_refcount_rec_no_intersect(
1413 					&rl->rl_recs[middle - delta - 1],
1414 					&rl->rl_recs[middle - delta])) {
1415 			*split_index = middle - delta;
1416 			break;
1417 		}
1418 
1419 		/* For even counts, don't walk off the end */
1420 		if ((middle + delta + 1) == num_used)
1421 			continue;
1422 
1423 		/* Now try delta past middle */
1424 		if (ocfs2_refcount_rec_no_intersect(
1425 					&rl->rl_recs[middle + delta],
1426 					&rl->rl_recs[middle + delta + 1])) {
1427 			*split_index = middle + delta + 1;
1428 			break;
1429 		}
1430 	}
1431 
1432 	if (delta >= middle)
1433 		return -ENOSPC;
1434 
1435 	*split_pos = ocfs2_get_ref_rec_low_cpos(&rl->rl_recs[*split_index]);
1436 	return 0;
1437 }
1438 
1439 static int ocfs2_divide_leaf_refcount_block(struct buffer_head *ref_leaf_bh,
1440 					    struct buffer_head *new_bh,
1441 					    u32 *split_cpos)
1442 {
1443 	int split_index = 0, num_moved, ret;
1444 	u32 cpos = 0;
1445 	struct ocfs2_refcount_block *rb =
1446 			(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1447 	struct ocfs2_refcount_list *rl = &rb->rf_records;
1448 	struct ocfs2_refcount_block *new_rb =
1449 			(struct ocfs2_refcount_block *)new_bh->b_data;
1450 	struct ocfs2_refcount_list *new_rl = &new_rb->rf_records;
1451 
1452 	trace_ocfs2_divide_leaf_refcount_block(
1453 		(unsigned long long)ref_leaf_bh->b_blocknr,
1454 		le16_to_cpu(rl->rl_count), le16_to_cpu(rl->rl_used));
1455 
1456 	/*
1457 	 * XXX: Improvement later.
1458 	 * If we know all the high 32 bit cpos is the same, no need to sort.
1459 	 *
1460 	 * In order to make the whole process safe, we do:
1461 	 * 1. sort the entries by their low 32 bit cpos first so that we can
1462 	 *    find the split cpos easily.
1463 	 * 2. call ocfs2_insert_extent to insert the new refcount block.
1464 	 * 3. move the refcount rec to the new block.
1465 	 * 4. sort the entries by their 64 bit cpos.
1466 	 * 5. dirty the new_rb and rb.
1467 	 */
1468 	sort(&rl->rl_recs, le16_to_cpu(rl->rl_used),
1469 	     sizeof(struct ocfs2_refcount_rec),
1470 	     cmp_refcount_rec_by_low_cpos, NULL);
1471 
1472 	ret = ocfs2_find_refcount_split_pos(rl, &cpos, &split_index);
1473 	if (ret) {
1474 		mlog_errno(ret);
1475 		return ret;
1476 	}
1477 
1478 	new_rb->rf_cpos = cpu_to_le32(cpos);
1479 
1480 	/* move refcount records starting from split_index to the new block. */
1481 	num_moved = le16_to_cpu(rl->rl_used) - split_index;
1482 	memcpy(new_rl->rl_recs, &rl->rl_recs[split_index],
1483 	       num_moved * sizeof(struct ocfs2_refcount_rec));
1484 
1485 	/*ok, remove the entries we just moved over to the other block. */
1486 	memset(&rl->rl_recs[split_index], 0,
1487 	       num_moved * sizeof(struct ocfs2_refcount_rec));
1488 
1489 	/* change old and new rl_used accordingly. */
1490 	le16_add_cpu(&rl->rl_used, -num_moved);
1491 	new_rl->rl_used = cpu_to_le16(num_moved);
1492 
1493 	sort(&rl->rl_recs, le16_to_cpu(rl->rl_used),
1494 	     sizeof(struct ocfs2_refcount_rec),
1495 	     cmp_refcount_rec_by_cpos, NULL);
1496 
1497 	sort(&new_rl->rl_recs, le16_to_cpu(new_rl->rl_used),
1498 	     sizeof(struct ocfs2_refcount_rec),
1499 	     cmp_refcount_rec_by_cpos, NULL);
1500 
1501 	*split_cpos = cpos;
1502 	return 0;
1503 }
1504 
1505 static int ocfs2_new_leaf_refcount_block(handle_t *handle,
1506 					 struct ocfs2_caching_info *ci,
1507 					 struct buffer_head *ref_root_bh,
1508 					 struct buffer_head *ref_leaf_bh,
1509 					 struct ocfs2_alloc_context *meta_ac)
1510 {
1511 	int ret;
1512 	u16 suballoc_bit_start;
1513 	u32 num_got, new_cpos;
1514 	u64 suballoc_loc, blkno;
1515 	struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
1516 	struct ocfs2_refcount_block *root_rb =
1517 			(struct ocfs2_refcount_block *)ref_root_bh->b_data;
1518 	struct buffer_head *new_bh = NULL;
1519 	struct ocfs2_refcount_block *new_rb;
1520 	struct ocfs2_extent_tree ref_et;
1521 
1522 	BUG_ON(!(le32_to_cpu(root_rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL));
1523 
1524 	ret = ocfs2_journal_access_rb(handle, ci, ref_root_bh,
1525 				      OCFS2_JOURNAL_ACCESS_WRITE);
1526 	if (ret) {
1527 		mlog_errno(ret);
1528 		goto out;
1529 	}
1530 
1531 	ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
1532 				      OCFS2_JOURNAL_ACCESS_WRITE);
1533 	if (ret) {
1534 		mlog_errno(ret);
1535 		goto out;
1536 	}
1537 
1538 	ret = ocfs2_claim_metadata(handle, meta_ac, 1, &suballoc_loc,
1539 				   &suballoc_bit_start, &num_got,
1540 				   &blkno);
1541 	if (ret) {
1542 		mlog_errno(ret);
1543 		goto out;
1544 	}
1545 
1546 	new_bh = sb_getblk(sb, blkno);
1547 	if (new_bh == NULL) {
1548 		ret = -ENOMEM;
1549 		mlog_errno(ret);
1550 		goto out;
1551 	}
1552 	ocfs2_set_new_buffer_uptodate(ci, new_bh);
1553 
1554 	ret = ocfs2_journal_access_rb(handle, ci, new_bh,
1555 				      OCFS2_JOURNAL_ACCESS_CREATE);
1556 	if (ret) {
1557 		mlog_errno(ret);
1558 		goto out;
1559 	}
1560 
1561 	/* Initialize ocfs2_refcount_block. */
1562 	new_rb = (struct ocfs2_refcount_block *)new_bh->b_data;
1563 	memset(new_rb, 0, sb->s_blocksize);
1564 	strcpy((void *)new_rb, OCFS2_REFCOUNT_BLOCK_SIGNATURE);
1565 	new_rb->rf_suballoc_slot = cpu_to_le16(meta_ac->ac_alloc_slot);
1566 	new_rb->rf_suballoc_loc = cpu_to_le64(suballoc_loc);
1567 	new_rb->rf_suballoc_bit = cpu_to_le16(suballoc_bit_start);
1568 	new_rb->rf_fs_generation = cpu_to_le32(OCFS2_SB(sb)->fs_generation);
1569 	new_rb->rf_blkno = cpu_to_le64(blkno);
1570 	new_rb->rf_parent = cpu_to_le64(ref_root_bh->b_blocknr);
1571 	new_rb->rf_flags = cpu_to_le32(OCFS2_REFCOUNT_LEAF_FL);
1572 	new_rb->rf_records.rl_count =
1573 				cpu_to_le16(ocfs2_refcount_recs_per_rb(sb));
1574 	new_rb->rf_generation = root_rb->rf_generation;
1575 
1576 	ret = ocfs2_divide_leaf_refcount_block(ref_leaf_bh, new_bh, &new_cpos);
1577 	if (ret) {
1578 		mlog_errno(ret);
1579 		goto out;
1580 	}
1581 
1582 	ocfs2_journal_dirty(handle, ref_leaf_bh);
1583 	ocfs2_journal_dirty(handle, new_bh);
1584 
1585 	ocfs2_init_refcount_extent_tree(&ref_et, ci, ref_root_bh);
1586 
1587 	trace_ocfs2_new_leaf_refcount_block(
1588 			(unsigned long long)new_bh->b_blocknr, new_cpos);
1589 
1590 	/* Insert the new leaf block with the specific offset cpos. */
1591 	ret = ocfs2_insert_extent(handle, &ref_et, new_cpos, new_bh->b_blocknr,
1592 				  1, 0, meta_ac);
1593 	if (ret)
1594 		mlog_errno(ret);
1595 
1596 out:
1597 	brelse(new_bh);
1598 	return ret;
1599 }
1600 
1601 static int ocfs2_expand_refcount_tree(handle_t *handle,
1602 				      struct ocfs2_caching_info *ci,
1603 				      struct buffer_head *ref_root_bh,
1604 				      struct buffer_head *ref_leaf_bh,
1605 				      struct ocfs2_alloc_context *meta_ac)
1606 {
1607 	int ret;
1608 	struct buffer_head *expand_bh = NULL;
1609 
1610 	if (ref_root_bh == ref_leaf_bh) {
1611 		/*
1612 		 * the old root bh hasn't been expanded to a b-tree,
1613 		 * so expand it first.
1614 		 */
1615 		ret = ocfs2_expand_inline_ref_root(handle, ci, ref_root_bh,
1616 						   &expand_bh, meta_ac);
1617 		if (ret) {
1618 			mlog_errno(ret);
1619 			goto out;
1620 		}
1621 	} else {
1622 		expand_bh = ref_leaf_bh;
1623 		get_bh(expand_bh);
1624 	}
1625 
1626 
1627 	/* Now add a new refcount block into the tree.*/
1628 	ret = ocfs2_new_leaf_refcount_block(handle, ci, ref_root_bh,
1629 					    expand_bh, meta_ac);
1630 	if (ret)
1631 		mlog_errno(ret);
1632 out:
1633 	brelse(expand_bh);
1634 	return ret;
1635 }
1636 
1637 /*
1638  * Adjust the extent rec in b-tree representing ref_leaf_bh.
1639  *
1640  * Only called when we have inserted a new refcount rec at index 0
1641  * which means ocfs2_extent_rec.e_cpos may need some change.
1642  */
1643 static int ocfs2_adjust_refcount_rec(handle_t *handle,
1644 				     struct ocfs2_caching_info *ci,
1645 				     struct buffer_head *ref_root_bh,
1646 				     struct buffer_head *ref_leaf_bh,
1647 				     struct ocfs2_refcount_rec *rec)
1648 {
1649 	int ret = 0, i;
1650 	u32 new_cpos, old_cpos;
1651 	struct ocfs2_path *path = NULL;
1652 	struct ocfs2_extent_tree et;
1653 	struct ocfs2_refcount_block *rb =
1654 		(struct ocfs2_refcount_block *)ref_root_bh->b_data;
1655 	struct ocfs2_extent_list *el;
1656 
1657 	if (!(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL))
1658 		goto out;
1659 
1660 	rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1661 	old_cpos = le32_to_cpu(rb->rf_cpos);
1662 	new_cpos = le64_to_cpu(rec->r_cpos) & OCFS2_32BIT_POS_MASK;
1663 	if (old_cpos <= new_cpos)
1664 		goto out;
1665 
1666 	ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
1667 
1668 	path = ocfs2_new_path_from_et(&et);
1669 	if (!path) {
1670 		ret = -ENOMEM;
1671 		mlog_errno(ret);
1672 		goto out;
1673 	}
1674 
1675 	ret = ocfs2_find_path(ci, path, old_cpos);
1676 	if (ret) {
1677 		mlog_errno(ret);
1678 		goto out;
1679 	}
1680 
1681 	/*
1682 	 * 2 more credits, one for the leaf refcount block, one for
1683 	 * the extent block contains the extent rec.
1684 	 */
1685 	ret = ocfs2_extend_trans(handle, 2);
1686 	if (ret < 0) {
1687 		mlog_errno(ret);
1688 		goto out;
1689 	}
1690 
1691 	ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
1692 				      OCFS2_JOURNAL_ACCESS_WRITE);
1693 	if (ret < 0) {
1694 		mlog_errno(ret);
1695 		goto out;
1696 	}
1697 
1698 	ret = ocfs2_journal_access_eb(handle, ci, path_leaf_bh(path),
1699 				      OCFS2_JOURNAL_ACCESS_WRITE);
1700 	if (ret < 0) {
1701 		mlog_errno(ret);
1702 		goto out;
1703 	}
1704 
1705 	/* change the leaf extent block first. */
1706 	el = path_leaf_el(path);
1707 
1708 	for (i = 0; i < le16_to_cpu(el->l_next_free_rec); i++)
1709 		if (le32_to_cpu(el->l_recs[i].e_cpos) == old_cpos)
1710 			break;
1711 
1712 	BUG_ON(i == le16_to_cpu(el->l_next_free_rec));
1713 
1714 	el->l_recs[i].e_cpos = cpu_to_le32(new_cpos);
1715 
1716 	/* change the r_cpos in the leaf block. */
1717 	rb->rf_cpos = cpu_to_le32(new_cpos);
1718 
1719 	ocfs2_journal_dirty(handle, path_leaf_bh(path));
1720 	ocfs2_journal_dirty(handle, ref_leaf_bh);
1721 
1722 out:
1723 	ocfs2_free_path(path);
1724 	return ret;
1725 }
1726 
1727 static int ocfs2_insert_refcount_rec(handle_t *handle,
1728 				     struct ocfs2_caching_info *ci,
1729 				     struct buffer_head *ref_root_bh,
1730 				     struct buffer_head *ref_leaf_bh,
1731 				     struct ocfs2_refcount_rec *rec,
1732 				     int index, int merge,
1733 				     struct ocfs2_alloc_context *meta_ac)
1734 {
1735 	int ret;
1736 	struct ocfs2_refcount_block *rb =
1737 			(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1738 	struct ocfs2_refcount_list *rf_list = &rb->rf_records;
1739 	struct buffer_head *new_bh = NULL;
1740 
1741 	BUG_ON(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL);
1742 
1743 	if (rf_list->rl_used == rf_list->rl_count) {
1744 		u64 cpos = le64_to_cpu(rec->r_cpos);
1745 		u32 len = le32_to_cpu(rec->r_clusters);
1746 
1747 		ret = ocfs2_expand_refcount_tree(handle, ci, ref_root_bh,
1748 						 ref_leaf_bh, meta_ac);
1749 		if (ret) {
1750 			mlog_errno(ret);
1751 			goto out;
1752 		}
1753 
1754 		ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
1755 					     cpos, len, NULL, &index,
1756 					     &new_bh);
1757 		if (ret) {
1758 			mlog_errno(ret);
1759 			goto out;
1760 		}
1761 
1762 		ref_leaf_bh = new_bh;
1763 		rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1764 		rf_list = &rb->rf_records;
1765 	}
1766 
1767 	ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
1768 				      OCFS2_JOURNAL_ACCESS_WRITE);
1769 	if (ret) {
1770 		mlog_errno(ret);
1771 		goto out;
1772 	}
1773 
1774 	if (index < le16_to_cpu(rf_list->rl_used))
1775 		memmove(&rf_list->rl_recs[index + 1],
1776 			&rf_list->rl_recs[index],
1777 			(le16_to_cpu(rf_list->rl_used) - index) *
1778 			 sizeof(struct ocfs2_refcount_rec));
1779 
1780 	trace_ocfs2_insert_refcount_rec(
1781 		(unsigned long long)ref_leaf_bh->b_blocknr, index,
1782 		(unsigned long long)le64_to_cpu(rec->r_cpos),
1783 		le32_to_cpu(rec->r_clusters), le32_to_cpu(rec->r_refcount));
1784 
1785 	rf_list->rl_recs[index] = *rec;
1786 
1787 	le16_add_cpu(&rf_list->rl_used, 1);
1788 
1789 	if (merge)
1790 		ocfs2_refcount_rec_merge(rb, index);
1791 
1792 	ocfs2_journal_dirty(handle, ref_leaf_bh);
1793 
1794 	if (index == 0) {
1795 		ret = ocfs2_adjust_refcount_rec(handle, ci,
1796 						ref_root_bh,
1797 						ref_leaf_bh, rec);
1798 		if (ret)
1799 			mlog_errno(ret);
1800 	}
1801 out:
1802 	brelse(new_bh);
1803 	return ret;
1804 }
1805 
1806 /*
1807  * Split the refcount_rec indexed by "index" in ref_leaf_bh.
1808  * This is much simple than our b-tree code.
1809  * split_rec is the new refcount rec we want to insert.
1810  * If split_rec->r_refcount > 0, we are changing the refcount(in case we
1811  * increase refcount or decrease a refcount to non-zero).
1812  * If split_rec->r_refcount == 0, we are punching a hole in current refcount
1813  * rec( in case we decrease a refcount to zero).
1814  */
1815 static int ocfs2_split_refcount_rec(handle_t *handle,
1816 				    struct ocfs2_caching_info *ci,
1817 				    struct buffer_head *ref_root_bh,
1818 				    struct buffer_head *ref_leaf_bh,
1819 				    struct ocfs2_refcount_rec *split_rec,
1820 				    int index, int merge,
1821 				    struct ocfs2_alloc_context *meta_ac,
1822 				    struct ocfs2_cached_dealloc_ctxt *dealloc)
1823 {
1824 	int ret, recs_need;
1825 	u32 len;
1826 	struct ocfs2_refcount_block *rb =
1827 			(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1828 	struct ocfs2_refcount_list *rf_list = &rb->rf_records;
1829 	struct ocfs2_refcount_rec *orig_rec = &rf_list->rl_recs[index];
1830 	struct ocfs2_refcount_rec *tail_rec = NULL;
1831 	struct buffer_head *new_bh = NULL;
1832 
1833 	BUG_ON(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL);
1834 
1835 	trace_ocfs2_split_refcount_rec(le64_to_cpu(orig_rec->r_cpos),
1836 		le32_to_cpu(orig_rec->r_clusters),
1837 		le32_to_cpu(orig_rec->r_refcount),
1838 		le64_to_cpu(split_rec->r_cpos),
1839 		le32_to_cpu(split_rec->r_clusters),
1840 		le32_to_cpu(split_rec->r_refcount));
1841 
1842 	/*
1843 	 * If we just need to split the header or tail clusters,
1844 	 * no more recs are needed, just split is OK.
1845 	 * Otherwise we at least need one new recs.
1846 	 */
1847 	if (!split_rec->r_refcount &&
1848 	    (split_rec->r_cpos == orig_rec->r_cpos ||
1849 	     le64_to_cpu(split_rec->r_cpos) +
1850 	     le32_to_cpu(split_rec->r_clusters) ==
1851 	     le64_to_cpu(orig_rec->r_cpos) + le32_to_cpu(orig_rec->r_clusters)))
1852 		recs_need = 0;
1853 	else
1854 		recs_need = 1;
1855 
1856 	/*
1857 	 * We need one more rec if we split in the middle and the new rec have
1858 	 * some refcount in it.
1859 	 */
1860 	if (split_rec->r_refcount &&
1861 	    (split_rec->r_cpos != orig_rec->r_cpos &&
1862 	     le64_to_cpu(split_rec->r_cpos) +
1863 	     le32_to_cpu(split_rec->r_clusters) !=
1864 	     le64_to_cpu(orig_rec->r_cpos) + le32_to_cpu(orig_rec->r_clusters)))
1865 		recs_need++;
1866 
1867 	/* If the leaf block don't have enough record, expand it. */
1868 	if (le16_to_cpu(rf_list->rl_used) + recs_need >
1869 					 le16_to_cpu(rf_list->rl_count)) {
1870 		struct ocfs2_refcount_rec tmp_rec;
1871 		u64 cpos = le64_to_cpu(orig_rec->r_cpos);
1872 		len = le32_to_cpu(orig_rec->r_clusters);
1873 		ret = ocfs2_expand_refcount_tree(handle, ci, ref_root_bh,
1874 						 ref_leaf_bh, meta_ac);
1875 		if (ret) {
1876 			mlog_errno(ret);
1877 			goto out;
1878 		}
1879 
1880 		/*
1881 		 * We have to re-get it since now cpos may be moved to
1882 		 * another leaf block.
1883 		 */
1884 		ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
1885 					     cpos, len, &tmp_rec, &index,
1886 					     &new_bh);
1887 		if (ret) {
1888 			mlog_errno(ret);
1889 			goto out;
1890 		}
1891 
1892 		ref_leaf_bh = new_bh;
1893 		rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1894 		rf_list = &rb->rf_records;
1895 		orig_rec = &rf_list->rl_recs[index];
1896 	}
1897 
1898 	ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
1899 				      OCFS2_JOURNAL_ACCESS_WRITE);
1900 	if (ret) {
1901 		mlog_errno(ret);
1902 		goto out;
1903 	}
1904 
1905 	/*
1906 	 * We have calculated out how many new records we need and store
1907 	 * in recs_need, so spare enough space first by moving the records
1908 	 * after "index" to the end.
1909 	 */
1910 	if (index != le16_to_cpu(rf_list->rl_used) - 1)
1911 		memmove(&rf_list->rl_recs[index + 1 + recs_need],
1912 			&rf_list->rl_recs[index + 1],
1913 			(le16_to_cpu(rf_list->rl_used) - index - 1) *
1914 			 sizeof(struct ocfs2_refcount_rec));
1915 
1916 	len = (le64_to_cpu(orig_rec->r_cpos) +
1917 	      le32_to_cpu(orig_rec->r_clusters)) -
1918 	      (le64_to_cpu(split_rec->r_cpos) +
1919 	      le32_to_cpu(split_rec->r_clusters));
1920 
1921 	/*
1922 	 * If we have "len", the we will split in the tail and move it
1923 	 * to the end of the space we have just spared.
1924 	 */
1925 	if (len) {
1926 		tail_rec = &rf_list->rl_recs[index + recs_need];
1927 
1928 		memcpy(tail_rec, orig_rec, sizeof(struct ocfs2_refcount_rec));
1929 		le64_add_cpu(&tail_rec->r_cpos,
1930 			     le32_to_cpu(tail_rec->r_clusters) - len);
1931 		tail_rec->r_clusters = cpu_to_le32(len);
1932 	}
1933 
1934 	/*
1935 	 * If the split pos isn't the same as the original one, we need to
1936 	 * split in the head.
1937 	 *
1938 	 * Note: We have the chance that split_rec.r_refcount = 0,
1939 	 * recs_need = 0 and len > 0, which means we just cut the head from
1940 	 * the orig_rec and in that case we have done some modification in
1941 	 * orig_rec above, so the check for r_cpos is faked.
1942 	 */
1943 	if (split_rec->r_cpos != orig_rec->r_cpos && tail_rec != orig_rec) {
1944 		len = le64_to_cpu(split_rec->r_cpos) -
1945 		      le64_to_cpu(orig_rec->r_cpos);
1946 		orig_rec->r_clusters = cpu_to_le32(len);
1947 		index++;
1948 	}
1949 
1950 	le16_add_cpu(&rf_list->rl_used, recs_need);
1951 
1952 	if (split_rec->r_refcount) {
1953 		rf_list->rl_recs[index] = *split_rec;
1954 		trace_ocfs2_split_refcount_rec_insert(
1955 			(unsigned long long)ref_leaf_bh->b_blocknr, index,
1956 			(unsigned long long)le64_to_cpu(split_rec->r_cpos),
1957 			le32_to_cpu(split_rec->r_clusters),
1958 			le32_to_cpu(split_rec->r_refcount));
1959 
1960 		if (merge)
1961 			ocfs2_refcount_rec_merge(rb, index);
1962 	}
1963 
1964 	ocfs2_journal_dirty(handle, ref_leaf_bh);
1965 
1966 out:
1967 	brelse(new_bh);
1968 	return ret;
1969 }
1970 
1971 static int __ocfs2_increase_refcount(handle_t *handle,
1972 				     struct ocfs2_caching_info *ci,
1973 				     struct buffer_head *ref_root_bh,
1974 				     u64 cpos, u32 len, int merge,
1975 				     struct ocfs2_alloc_context *meta_ac,
1976 				     struct ocfs2_cached_dealloc_ctxt *dealloc)
1977 {
1978 	int ret = 0, index;
1979 	struct buffer_head *ref_leaf_bh = NULL;
1980 	struct ocfs2_refcount_rec rec;
1981 	unsigned int set_len = 0;
1982 
1983 	trace_ocfs2_increase_refcount_begin(
1984 	     (unsigned long long)ocfs2_metadata_cache_owner(ci),
1985 	     (unsigned long long)cpos, len);
1986 
1987 	while (len) {
1988 		ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
1989 					     cpos, len, &rec, &index,
1990 					     &ref_leaf_bh);
1991 		if (ret) {
1992 			mlog_errno(ret);
1993 			goto out;
1994 		}
1995 
1996 		set_len = le32_to_cpu(rec.r_clusters);
1997 
1998 		/*
1999 		 * Here we may meet with 3 situations:
2000 		 *
2001 		 * 1. If we find an already existing record, and the length
2002 		 *    is the same, cool, we just need to increase the r_refcount
2003 		 *    and it is OK.
2004 		 * 2. If we find a hole, just insert it with r_refcount = 1.
2005 		 * 3. If we are in the middle of one extent record, split
2006 		 *    it.
2007 		 */
2008 		if (rec.r_refcount && le64_to_cpu(rec.r_cpos) == cpos &&
2009 		    set_len <= len) {
2010 			trace_ocfs2_increase_refcount_change(
2011 				(unsigned long long)cpos, set_len,
2012 				le32_to_cpu(rec.r_refcount));
2013 			ret = ocfs2_change_refcount_rec(handle, ci,
2014 							ref_leaf_bh, index,
2015 							merge, 1);
2016 			if (ret) {
2017 				mlog_errno(ret);
2018 				goto out;
2019 			}
2020 		} else if (!rec.r_refcount) {
2021 			rec.r_refcount = cpu_to_le32(1);
2022 
2023 			trace_ocfs2_increase_refcount_insert(
2024 			     (unsigned long long)le64_to_cpu(rec.r_cpos),
2025 			     set_len);
2026 			ret = ocfs2_insert_refcount_rec(handle, ci, ref_root_bh,
2027 							ref_leaf_bh,
2028 							&rec, index,
2029 							merge, meta_ac);
2030 			if (ret) {
2031 				mlog_errno(ret);
2032 				goto out;
2033 			}
2034 		} else  {
2035 			set_len = min((u64)(cpos + len),
2036 				      le64_to_cpu(rec.r_cpos) + set_len) - cpos;
2037 			rec.r_cpos = cpu_to_le64(cpos);
2038 			rec.r_clusters = cpu_to_le32(set_len);
2039 			le32_add_cpu(&rec.r_refcount, 1);
2040 
2041 			trace_ocfs2_increase_refcount_split(
2042 			     (unsigned long long)le64_to_cpu(rec.r_cpos),
2043 			     set_len, le32_to_cpu(rec.r_refcount));
2044 			ret = ocfs2_split_refcount_rec(handle, ci,
2045 						       ref_root_bh, ref_leaf_bh,
2046 						       &rec, index, merge,
2047 						       meta_ac, dealloc);
2048 			if (ret) {
2049 				mlog_errno(ret);
2050 				goto out;
2051 			}
2052 		}
2053 
2054 		cpos += set_len;
2055 		len -= set_len;
2056 		brelse(ref_leaf_bh);
2057 		ref_leaf_bh = NULL;
2058 	}
2059 
2060 out:
2061 	brelse(ref_leaf_bh);
2062 	return ret;
2063 }
2064 
2065 static int ocfs2_remove_refcount_extent(handle_t *handle,
2066 				struct ocfs2_caching_info *ci,
2067 				struct buffer_head *ref_root_bh,
2068 				struct buffer_head *ref_leaf_bh,
2069 				struct ocfs2_alloc_context *meta_ac,
2070 				struct ocfs2_cached_dealloc_ctxt *dealloc)
2071 {
2072 	int ret;
2073 	struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
2074 	struct ocfs2_refcount_block *rb =
2075 			(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
2076 	struct ocfs2_extent_tree et;
2077 
2078 	BUG_ON(rb->rf_records.rl_used);
2079 
2080 	trace_ocfs2_remove_refcount_extent(
2081 		(unsigned long long)ocfs2_metadata_cache_owner(ci),
2082 		(unsigned long long)ref_leaf_bh->b_blocknr,
2083 		le32_to_cpu(rb->rf_cpos));
2084 
2085 	ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
2086 	ret = ocfs2_remove_extent(handle, &et, le32_to_cpu(rb->rf_cpos),
2087 				  1, meta_ac, dealloc);
2088 	if (ret) {
2089 		mlog_errno(ret);
2090 		goto out;
2091 	}
2092 
2093 	ocfs2_remove_from_cache(ci, ref_leaf_bh);
2094 
2095 	/*
2096 	 * add the freed block to the dealloc so that it will be freed
2097 	 * when we run dealloc.
2098 	 */
2099 	ret = ocfs2_cache_block_dealloc(dealloc, EXTENT_ALLOC_SYSTEM_INODE,
2100 					le16_to_cpu(rb->rf_suballoc_slot),
2101 					le64_to_cpu(rb->rf_suballoc_loc),
2102 					le64_to_cpu(rb->rf_blkno),
2103 					le16_to_cpu(rb->rf_suballoc_bit));
2104 	if (ret) {
2105 		mlog_errno(ret);
2106 		goto out;
2107 	}
2108 
2109 	ret = ocfs2_journal_access_rb(handle, ci, ref_root_bh,
2110 				      OCFS2_JOURNAL_ACCESS_WRITE);
2111 	if (ret) {
2112 		mlog_errno(ret);
2113 		goto out;
2114 	}
2115 
2116 	rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
2117 
2118 	le32_add_cpu(&rb->rf_clusters, -1);
2119 
2120 	/*
2121 	 * check whether we need to restore the root refcount block if
2122 	 * there is no leaf extent block at atll.
2123 	 */
2124 	if (!rb->rf_list.l_next_free_rec) {
2125 		BUG_ON(rb->rf_clusters);
2126 
2127 		trace_ocfs2_restore_refcount_block(
2128 		     (unsigned long long)ref_root_bh->b_blocknr);
2129 
2130 		rb->rf_flags = 0;
2131 		rb->rf_parent = 0;
2132 		rb->rf_cpos = 0;
2133 		memset(&rb->rf_records, 0, sb->s_blocksize -
2134 		       offsetof(struct ocfs2_refcount_block, rf_records));
2135 		rb->rf_records.rl_count =
2136 				cpu_to_le16(ocfs2_refcount_recs_per_rb(sb));
2137 	}
2138 
2139 	ocfs2_journal_dirty(handle, ref_root_bh);
2140 
2141 out:
2142 	return ret;
2143 }
2144 
2145 int ocfs2_increase_refcount(handle_t *handle,
2146 			    struct ocfs2_caching_info *ci,
2147 			    struct buffer_head *ref_root_bh,
2148 			    u64 cpos, u32 len,
2149 			    struct ocfs2_alloc_context *meta_ac,
2150 			    struct ocfs2_cached_dealloc_ctxt *dealloc)
2151 {
2152 	return __ocfs2_increase_refcount(handle, ci, ref_root_bh,
2153 					 cpos, len, 1,
2154 					 meta_ac, dealloc);
2155 }
2156 
2157 static int ocfs2_decrease_refcount_rec(handle_t *handle,
2158 				struct ocfs2_caching_info *ci,
2159 				struct buffer_head *ref_root_bh,
2160 				struct buffer_head *ref_leaf_bh,
2161 				int index, u64 cpos, unsigned int len,
2162 				struct ocfs2_alloc_context *meta_ac,
2163 				struct ocfs2_cached_dealloc_ctxt *dealloc)
2164 {
2165 	int ret;
2166 	struct ocfs2_refcount_block *rb =
2167 			(struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
2168 	struct ocfs2_refcount_rec *rec = &rb->rf_records.rl_recs[index];
2169 
2170 	BUG_ON(cpos < le64_to_cpu(rec->r_cpos));
2171 	BUG_ON(cpos + len >
2172 	       le64_to_cpu(rec->r_cpos) + le32_to_cpu(rec->r_clusters));
2173 
2174 	trace_ocfs2_decrease_refcount_rec(
2175 		(unsigned long long)ocfs2_metadata_cache_owner(ci),
2176 		(unsigned long long)cpos, len);
2177 
2178 	if (cpos == le64_to_cpu(rec->r_cpos) &&
2179 	    len == le32_to_cpu(rec->r_clusters))
2180 		ret = ocfs2_change_refcount_rec(handle, ci,
2181 						ref_leaf_bh, index, 1, -1);
2182 	else {
2183 		struct ocfs2_refcount_rec split = *rec;
2184 		split.r_cpos = cpu_to_le64(cpos);
2185 		split.r_clusters = cpu_to_le32(len);
2186 
2187 		le32_add_cpu(&split.r_refcount, -1);
2188 
2189 		ret = ocfs2_split_refcount_rec(handle, ci,
2190 					       ref_root_bh, ref_leaf_bh,
2191 					       &split, index, 1,
2192 					       meta_ac, dealloc);
2193 	}
2194 
2195 	if (ret) {
2196 		mlog_errno(ret);
2197 		goto out;
2198 	}
2199 
2200 	/* Remove the leaf refcount block if it contains no refcount record. */
2201 	if (!rb->rf_records.rl_used && ref_leaf_bh != ref_root_bh) {
2202 		ret = ocfs2_remove_refcount_extent(handle, ci, ref_root_bh,
2203 						   ref_leaf_bh, meta_ac,
2204 						   dealloc);
2205 		if (ret)
2206 			mlog_errno(ret);
2207 	}
2208 
2209 out:
2210 	return ret;
2211 }
2212 
2213 static int __ocfs2_decrease_refcount(handle_t *handle,
2214 				     struct ocfs2_caching_info *ci,
2215 				     struct buffer_head *ref_root_bh,
2216 				     u64 cpos, u32 len,
2217 				     struct ocfs2_alloc_context *meta_ac,
2218 				     struct ocfs2_cached_dealloc_ctxt *dealloc,
2219 				     int delete)
2220 {
2221 	int ret = 0, index = 0;
2222 	struct ocfs2_refcount_rec rec;
2223 	unsigned int r_count = 0, r_len;
2224 	struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
2225 	struct buffer_head *ref_leaf_bh = NULL;
2226 
2227 	trace_ocfs2_decrease_refcount(
2228 		(unsigned long long)ocfs2_metadata_cache_owner(ci),
2229 		(unsigned long long)cpos, len, delete);
2230 
2231 	while (len) {
2232 		ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
2233 					     cpos, len, &rec, &index,
2234 					     &ref_leaf_bh);
2235 		if (ret) {
2236 			mlog_errno(ret);
2237 			goto out;
2238 		}
2239 
2240 		r_count = le32_to_cpu(rec.r_refcount);
2241 		BUG_ON(r_count == 0);
2242 		if (!delete)
2243 			BUG_ON(r_count > 1);
2244 
2245 		r_len = min((u64)(cpos + len), le64_to_cpu(rec.r_cpos) +
2246 			      le32_to_cpu(rec.r_clusters)) - cpos;
2247 
2248 		ret = ocfs2_decrease_refcount_rec(handle, ci, ref_root_bh,
2249 						  ref_leaf_bh, index,
2250 						  cpos, r_len,
2251 						  meta_ac, dealloc);
2252 		if (ret) {
2253 			mlog_errno(ret);
2254 			goto out;
2255 		}
2256 
2257 		if (le32_to_cpu(rec.r_refcount) == 1 && delete) {
2258 			ret = ocfs2_cache_cluster_dealloc(dealloc,
2259 					  ocfs2_clusters_to_blocks(sb, cpos),
2260 							  r_len);
2261 			if (ret) {
2262 				mlog_errno(ret);
2263 				goto out;
2264 			}
2265 		}
2266 
2267 		cpos += r_len;
2268 		len -= r_len;
2269 		brelse(ref_leaf_bh);
2270 		ref_leaf_bh = NULL;
2271 	}
2272 
2273 out:
2274 	brelse(ref_leaf_bh);
2275 	return ret;
2276 }
2277 
2278 /* Caller must hold refcount tree lock. */
2279 int ocfs2_decrease_refcount(struct inode *inode,
2280 			    handle_t *handle, u32 cpos, u32 len,
2281 			    struct ocfs2_alloc_context *meta_ac,
2282 			    struct ocfs2_cached_dealloc_ctxt *dealloc,
2283 			    int delete)
2284 {
2285 	int ret;
2286 	u64 ref_blkno;
2287 	struct buffer_head *ref_root_bh = NULL;
2288 	struct ocfs2_refcount_tree *tree;
2289 
2290 	BUG_ON(!ocfs2_is_refcount_inode(inode));
2291 
2292 	ret = ocfs2_get_refcount_block(inode, &ref_blkno);
2293 	if (ret) {
2294 		mlog_errno(ret);
2295 		goto out;
2296 	}
2297 
2298 	ret = ocfs2_get_refcount_tree(OCFS2_SB(inode->i_sb), ref_blkno, &tree);
2299 	if (ret) {
2300 		mlog_errno(ret);
2301 		goto out;
2302 	}
2303 
2304 	ret = ocfs2_read_refcount_block(&tree->rf_ci, tree->rf_blkno,
2305 					&ref_root_bh);
2306 	if (ret) {
2307 		mlog_errno(ret);
2308 		goto out;
2309 	}
2310 
2311 	ret = __ocfs2_decrease_refcount(handle, &tree->rf_ci, ref_root_bh,
2312 					cpos, len, meta_ac, dealloc, delete);
2313 	if (ret)
2314 		mlog_errno(ret);
2315 out:
2316 	brelse(ref_root_bh);
2317 	return ret;
2318 }
2319 
2320 /*
2321  * Mark the already-existing extent at cpos as refcounted for len clusters.
2322  * This adds the refcount extent flag.
2323  *
2324  * If the existing extent is larger than the request, initiate a
2325  * split. An attempt will be made at merging with adjacent extents.
2326  *
2327  * The caller is responsible for passing down meta_ac if we'll need it.
2328  */
2329 static int ocfs2_mark_extent_refcounted(struct inode *inode,
2330 				struct ocfs2_extent_tree *et,
2331 				handle_t *handle, u32 cpos,
2332 				u32 len, u32 phys,
2333 				struct ocfs2_alloc_context *meta_ac,
2334 				struct ocfs2_cached_dealloc_ctxt *dealloc)
2335 {
2336 	int ret;
2337 
2338 	trace_ocfs2_mark_extent_refcounted(OCFS2_I(inode)->ip_blkno,
2339 					   cpos, len, phys);
2340 
2341 	if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb))) {
2342 		ret = ocfs2_error(inode->i_sb, "Inode %lu want to use refcount tree, but the feature bit is not set in the super block\n",
2343 				  inode->i_ino);
2344 		goto out;
2345 	}
2346 
2347 	ret = ocfs2_change_extent_flag(handle, et, cpos,
2348 				       len, phys, meta_ac, dealloc,
2349 				       OCFS2_EXT_REFCOUNTED, 0);
2350 	if (ret)
2351 		mlog_errno(ret);
2352 
2353 out:
2354 	return ret;
2355 }
2356 
2357 /*
2358  * Given some contiguous physical clusters, calculate what we need
2359  * for modifying their refcount.
2360  */
2361 static int ocfs2_calc_refcount_meta_credits(struct super_block *sb,
2362 					    struct ocfs2_caching_info *ci,
2363 					    struct buffer_head *ref_root_bh,
2364 					    u64 start_cpos,
2365 					    u32 clusters,
2366 					    int *meta_add,
2367 					    int *credits)
2368 {
2369 	int ret = 0, index, ref_blocks = 0, recs_add = 0;
2370 	u64 cpos = start_cpos;
2371 	struct ocfs2_refcount_block *rb;
2372 	struct ocfs2_refcount_rec rec;
2373 	struct buffer_head *ref_leaf_bh = NULL, *prev_bh = NULL;
2374 	u32 len;
2375 
2376 	while (clusters) {
2377 		ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
2378 					     cpos, clusters, &rec,
2379 					     &index, &ref_leaf_bh);
2380 		if (ret) {
2381 			mlog_errno(ret);
2382 			goto out;
2383 		}
2384 
2385 		if (ref_leaf_bh != prev_bh) {
2386 			/*
2387 			 * Now we encounter a new leaf block, so calculate
2388 			 * whether we need to extend the old leaf.
2389 			 */
2390 			if (prev_bh) {
2391 				rb = (struct ocfs2_refcount_block *)
2392 							prev_bh->b_data;
2393 
2394 				if (le16_to_cpu(rb->rf_records.rl_used) +
2395 				    recs_add >
2396 				    le16_to_cpu(rb->rf_records.rl_count))
2397 					ref_blocks++;
2398 			}
2399 
2400 			recs_add = 0;
2401 			*credits += 1;
2402 			brelse(prev_bh);
2403 			prev_bh = ref_leaf_bh;
2404 			get_bh(prev_bh);
2405 		}
2406 
2407 		trace_ocfs2_calc_refcount_meta_credits_iterate(
2408 				recs_add, (unsigned long long)cpos, clusters,
2409 				(unsigned long long)le64_to_cpu(rec.r_cpos),
2410 				le32_to_cpu(rec.r_clusters),
2411 				le32_to_cpu(rec.r_refcount), index);
2412 
2413 		len = min((u64)cpos + clusters, le64_to_cpu(rec.r_cpos) +
2414 			  le32_to_cpu(rec.r_clusters)) - cpos;
2415 		/*
2416 		 * We record all the records which will be inserted to the
2417 		 * same refcount block, so that we can tell exactly whether
2418 		 * we need a new refcount block or not.
2419 		 *
2420 		 * If we will insert a new one, this is easy and only happens
2421 		 * during adding refcounted flag to the extent, so we don't
2422 		 * have a chance of spliting. We just need one record.
2423 		 *
2424 		 * If the refcount rec already exists, that would be a little
2425 		 * complicated. we may have to:
2426 		 * 1) split at the beginning if the start pos isn't aligned.
2427 		 *    we need 1 more record in this case.
2428 		 * 2) split int the end if the end pos isn't aligned.
2429 		 *    we need 1 more record in this case.
2430 		 * 3) split in the middle because of file system fragmentation.
2431 		 *    we need 2 more records in this case(we can't detect this
2432 		 *    beforehand, so always think of the worst case).
2433 		 */
2434 		if (rec.r_refcount) {
2435 			recs_add += 2;
2436 			/* Check whether we need a split at the beginning. */
2437 			if (cpos == start_cpos &&
2438 			    cpos != le64_to_cpu(rec.r_cpos))
2439 				recs_add++;
2440 
2441 			/* Check whether we need a split in the end. */
2442 			if (cpos + clusters < le64_to_cpu(rec.r_cpos) +
2443 			    le32_to_cpu(rec.r_clusters))
2444 				recs_add++;
2445 		} else
2446 			recs_add++;
2447 
2448 		brelse(ref_leaf_bh);
2449 		ref_leaf_bh = NULL;
2450 		clusters -= len;
2451 		cpos += len;
2452 	}
2453 
2454 	if (prev_bh) {
2455 		rb = (struct ocfs2_refcount_block *)prev_bh->b_data;
2456 
2457 		if (le16_to_cpu(rb->rf_records.rl_used) + recs_add >
2458 		    le16_to_cpu(rb->rf_records.rl_count))
2459 			ref_blocks++;
2460 
2461 		*credits += 1;
2462 	}
2463 
2464 	if (!ref_blocks)
2465 		goto out;
2466 
2467 	*meta_add += ref_blocks;
2468 	*credits += ref_blocks;
2469 
2470 	/*
2471 	 * So we may need ref_blocks to insert into the tree.
2472 	 * That also means we need to change the b-tree and add that number
2473 	 * of records since we never merge them.
2474 	 * We need one more block for expansion since the new created leaf
2475 	 * block is also full and needs split.
2476 	 */
2477 	rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
2478 	if (le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL) {
2479 		struct ocfs2_extent_tree et;
2480 
2481 		ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
2482 		*meta_add += ocfs2_extend_meta_needed(et.et_root_el);
2483 		*credits += ocfs2_calc_extend_credits(sb,
2484 						      et.et_root_el);
2485 	} else {
2486 		*credits += OCFS2_EXPAND_REFCOUNT_TREE_CREDITS;
2487 		*meta_add += 1;
2488 	}
2489 
2490 out:
2491 
2492 	trace_ocfs2_calc_refcount_meta_credits(
2493 		(unsigned long long)start_cpos, clusters,
2494 		*meta_add, *credits);
2495 	brelse(ref_leaf_bh);
2496 	brelse(prev_bh);
2497 	return ret;
2498 }
2499 
2500 /*
2501  * For refcount tree, we will decrease some contiguous clusters
2502  * refcount count, so just go through it to see how many blocks
2503  * we gonna touch and whether we need to create new blocks.
2504  *
2505  * Normally the refcount blocks store these refcount should be
2506  * contiguous also, so that we can get the number easily.
2507  * We will at most add split 2 refcount records and 2 more
2508  * refcount blocks, so just check it in a rough way.
2509  *
2510  * Caller must hold refcount tree lock.
2511  */
2512 int ocfs2_prepare_refcount_change_for_del(struct inode *inode,
2513 					  u64 refcount_loc,
2514 					  u64 phys_blkno,
2515 					  u32 clusters,
2516 					  int *credits,
2517 					  int *ref_blocks)
2518 {
2519 	int ret;
2520 	struct buffer_head *ref_root_bh = NULL;
2521 	struct ocfs2_refcount_tree *tree;
2522 	u64 start_cpos = ocfs2_blocks_to_clusters(inode->i_sb, phys_blkno);
2523 
2524 	if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb))) {
2525 		ret = ocfs2_error(inode->i_sb, "Inode %lu want to use refcount tree, but the feature bit is not set in the super block\n",
2526 				  inode->i_ino);
2527 		goto out;
2528 	}
2529 
2530 	BUG_ON(!ocfs2_is_refcount_inode(inode));
2531 
2532 	ret = ocfs2_get_refcount_tree(OCFS2_SB(inode->i_sb),
2533 				      refcount_loc, &tree);
2534 	if (ret) {
2535 		mlog_errno(ret);
2536 		goto out;
2537 	}
2538 
2539 	ret = ocfs2_read_refcount_block(&tree->rf_ci, refcount_loc,
2540 					&ref_root_bh);
2541 	if (ret) {
2542 		mlog_errno(ret);
2543 		goto out;
2544 	}
2545 
2546 	ret = ocfs2_calc_refcount_meta_credits(inode->i_sb,
2547 					       &tree->rf_ci,
2548 					       ref_root_bh,
2549 					       start_cpos, clusters,
2550 					       ref_blocks, credits);
2551 	if (ret) {
2552 		mlog_errno(ret);
2553 		goto out;
2554 	}
2555 
2556 	trace_ocfs2_prepare_refcount_change_for_del(*ref_blocks, *credits);
2557 
2558 out:
2559 	brelse(ref_root_bh);
2560 	return ret;
2561 }
2562 
2563 #define	MAX_CONTIG_BYTES	1048576
2564 
2565 static inline unsigned int ocfs2_cow_contig_clusters(struct super_block *sb)
2566 {
2567 	return ocfs2_clusters_for_bytes(sb, MAX_CONTIG_BYTES);
2568 }
2569 
2570 static inline unsigned int ocfs2_cow_contig_mask(struct super_block *sb)
2571 {
2572 	return ~(ocfs2_cow_contig_clusters(sb) - 1);
2573 }
2574 
2575 /*
2576  * Given an extent that starts at 'start' and an I/O that starts at 'cpos',
2577  * find an offset (start + (n * contig_clusters)) that is closest to cpos
2578  * while still being less than or equal to it.
2579  *
2580  * The goal is to break the extent at a multiple of contig_clusters.
2581  */
2582 static inline unsigned int ocfs2_cow_align_start(struct super_block *sb,
2583 						 unsigned int start,
2584 						 unsigned int cpos)
2585 {
2586 	BUG_ON(start > cpos);
2587 
2588 	return start + ((cpos - start) & ocfs2_cow_contig_mask(sb));
2589 }
2590 
2591 /*
2592  * Given a cluster count of len, pad it out so that it is a multiple
2593  * of contig_clusters.
2594  */
2595 static inline unsigned int ocfs2_cow_align_length(struct super_block *sb,
2596 						  unsigned int len)
2597 {
2598 	unsigned int padded =
2599 		(len + (ocfs2_cow_contig_clusters(sb) - 1)) &
2600 		ocfs2_cow_contig_mask(sb);
2601 
2602 	/* Did we wrap? */
2603 	if (padded < len)
2604 		padded = UINT_MAX;
2605 
2606 	return padded;
2607 }
2608 
2609 /*
2610  * Calculate out the start and number of virtual clusters we need to CoW.
2611  *
2612  * cpos is vitual start cluster position we want to do CoW in a
2613  * file and write_len is the cluster length.
2614  * max_cpos is the place where we want to stop CoW intentionally.
2615  *
2616  * Normal we will start CoW from the beginning of extent record cotaining cpos.
2617  * We try to break up extents on boundaries of MAX_CONTIG_BYTES so that we
2618  * get good I/O from the resulting extent tree.
2619  */
2620 static int ocfs2_refcount_cal_cow_clusters(struct inode *inode,
2621 					   struct ocfs2_extent_list *el,
2622 					   u32 cpos,
2623 					   u32 write_len,
2624 					   u32 max_cpos,
2625 					   u32 *cow_start,
2626 					   u32 *cow_len)
2627 {
2628 	int ret = 0;
2629 	int tree_height = le16_to_cpu(el->l_tree_depth), i;
2630 	struct buffer_head *eb_bh = NULL;
2631 	struct ocfs2_extent_block *eb = NULL;
2632 	struct ocfs2_extent_rec *rec;
2633 	unsigned int want_clusters, rec_end = 0;
2634 	int contig_clusters = ocfs2_cow_contig_clusters(inode->i_sb);
2635 	int leaf_clusters;
2636 
2637 	BUG_ON(cpos + write_len > max_cpos);
2638 
2639 	if (tree_height > 0) {
2640 		ret = ocfs2_find_leaf(INODE_CACHE(inode), el, cpos, &eb_bh);
2641 		if (ret) {
2642 			mlog_errno(ret);
2643 			goto out;
2644 		}
2645 
2646 		eb = (struct ocfs2_extent_block *) eb_bh->b_data;
2647 		el = &eb->h_list;
2648 
2649 		if (el->l_tree_depth) {
2650 			ret = ocfs2_error(inode->i_sb,
2651 					  "Inode %lu has non zero tree depth in leaf block %llu\n",
2652 					  inode->i_ino,
2653 					  (unsigned long long)eb_bh->b_blocknr);
2654 			goto out;
2655 		}
2656 	}
2657 
2658 	*cow_len = 0;
2659 	for (i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
2660 		rec = &el->l_recs[i];
2661 
2662 		if (ocfs2_is_empty_extent(rec)) {
2663 			mlog_bug_on_msg(i != 0, "Inode %lu has empty record in "
2664 					"index %d\n", inode->i_ino, i);
2665 			continue;
2666 		}
2667 
2668 		if (le32_to_cpu(rec->e_cpos) +
2669 		    le16_to_cpu(rec->e_leaf_clusters) <= cpos)
2670 			continue;
2671 
2672 		if (*cow_len == 0) {
2673 			/*
2674 			 * We should find a refcounted record in the
2675 			 * first pass.
2676 			 */
2677 			BUG_ON(!(rec->e_flags & OCFS2_EXT_REFCOUNTED));
2678 			*cow_start = le32_to_cpu(rec->e_cpos);
2679 		}
2680 
2681 		/*
2682 		 * If we encounter a hole, a non-refcounted record or
2683 		 * pass the max_cpos, stop the search.
2684 		 */
2685 		if ((!(rec->e_flags & OCFS2_EXT_REFCOUNTED)) ||
2686 		    (*cow_len && rec_end != le32_to_cpu(rec->e_cpos)) ||
2687 		    (max_cpos <= le32_to_cpu(rec->e_cpos)))
2688 			break;
2689 
2690 		leaf_clusters = le16_to_cpu(rec->e_leaf_clusters);
2691 		rec_end = le32_to_cpu(rec->e_cpos) + leaf_clusters;
2692 		if (rec_end > max_cpos) {
2693 			rec_end = max_cpos;
2694 			leaf_clusters = rec_end - le32_to_cpu(rec->e_cpos);
2695 		}
2696 
2697 		/*
2698 		 * How many clusters do we actually need from
2699 		 * this extent?  First we see how many we actually
2700 		 * need to complete the write.  If that's smaller
2701 		 * than contig_clusters, we try for contig_clusters.
2702 		 */
2703 		if (!*cow_len)
2704 			want_clusters = write_len;
2705 		else
2706 			want_clusters = (cpos + write_len) -
2707 				(*cow_start + *cow_len);
2708 		if (want_clusters < contig_clusters)
2709 			want_clusters = contig_clusters;
2710 
2711 		/*
2712 		 * If the write does not cover the whole extent, we
2713 		 * need to calculate how we're going to split the extent.
2714 		 * We try to do it on contig_clusters boundaries.
2715 		 *
2716 		 * Any extent smaller than contig_clusters will be
2717 		 * CoWed in its entirety.
2718 		 */
2719 		if (leaf_clusters <= contig_clusters)
2720 			*cow_len += leaf_clusters;
2721 		else if (*cow_len || (*cow_start == cpos)) {
2722 			/*
2723 			 * This extent needs to be CoW'd from its
2724 			 * beginning, so all we have to do is compute
2725 			 * how many clusters to grab.  We align
2726 			 * want_clusters to the edge of contig_clusters
2727 			 * to get better I/O.
2728 			 */
2729 			want_clusters = ocfs2_cow_align_length(inode->i_sb,
2730 							       want_clusters);
2731 
2732 			if (leaf_clusters < want_clusters)
2733 				*cow_len += leaf_clusters;
2734 			else
2735 				*cow_len += want_clusters;
2736 		} else if ((*cow_start + contig_clusters) >=
2737 			   (cpos + write_len)) {
2738 			/*
2739 			 * Breaking off contig_clusters at the front
2740 			 * of the extent will cover our write.  That's
2741 			 * easy.
2742 			 */
2743 			*cow_len = contig_clusters;
2744 		} else if ((rec_end - cpos) <= contig_clusters) {
2745 			/*
2746 			 * Breaking off contig_clusters at the tail of
2747 			 * this extent will cover cpos.
2748 			 */
2749 			*cow_start = rec_end - contig_clusters;
2750 			*cow_len = contig_clusters;
2751 		} else if ((rec_end - cpos) <= want_clusters) {
2752 			/*
2753 			 * While we can't fit the entire write in this
2754 			 * extent, we know that the write goes from cpos
2755 			 * to the end of the extent.  Break that off.
2756 			 * We try to break it at some multiple of
2757 			 * contig_clusters from the front of the extent.
2758 			 * Failing that (ie, cpos is within
2759 			 * contig_clusters of the front), we'll CoW the
2760 			 * entire extent.
2761 			 */
2762 			*cow_start = ocfs2_cow_align_start(inode->i_sb,
2763 							   *cow_start, cpos);
2764 			*cow_len = rec_end - *cow_start;
2765 		} else {
2766 			/*
2767 			 * Ok, the entire write lives in the middle of
2768 			 * this extent.  Let's try to slice the extent up
2769 			 * nicely.  Optimally, our CoW region starts at
2770 			 * m*contig_clusters from the beginning of the
2771 			 * extent and goes for n*contig_clusters,
2772 			 * covering the entire write.
2773 			 */
2774 			*cow_start = ocfs2_cow_align_start(inode->i_sb,
2775 							   *cow_start, cpos);
2776 
2777 			want_clusters = (cpos + write_len) - *cow_start;
2778 			want_clusters = ocfs2_cow_align_length(inode->i_sb,
2779 							       want_clusters);
2780 			if (*cow_start + want_clusters <= rec_end)
2781 				*cow_len = want_clusters;
2782 			else
2783 				*cow_len = rec_end - *cow_start;
2784 		}
2785 
2786 		/* Have we covered our entire write yet? */
2787 		if ((*cow_start + *cow_len) >= (cpos + write_len))
2788 			break;
2789 
2790 		/*
2791 		 * If we reach the end of the extent block and don't get enough
2792 		 * clusters, continue with the next extent block if possible.
2793 		 */
2794 		if (i + 1 == le16_to_cpu(el->l_next_free_rec) &&
2795 		    eb && eb->h_next_leaf_blk) {
2796 			brelse(eb_bh);
2797 			eb_bh = NULL;
2798 
2799 			ret = ocfs2_read_extent_block(INODE_CACHE(inode),
2800 					       le64_to_cpu(eb->h_next_leaf_blk),
2801 					       &eb_bh);
2802 			if (ret) {
2803 				mlog_errno(ret);
2804 				goto out;
2805 			}
2806 
2807 			eb = (struct ocfs2_extent_block *) eb_bh->b_data;
2808 			el = &eb->h_list;
2809 			i = -1;
2810 		}
2811 	}
2812 
2813 out:
2814 	brelse(eb_bh);
2815 	return ret;
2816 }
2817 
2818 /*
2819  * Prepare meta_ac, data_ac and calculate credits when we want to add some
2820  * num_clusters in data_tree "et" and change the refcount for the old
2821  * clusters(starting form p_cluster) in the refcount tree.
2822  *
2823  * Note:
2824  * 1. since we may split the old tree, so we at most will need num_clusters + 2
2825  *    more new leaf records.
2826  * 2. In some case, we may not need to reserve new clusters(e.g, reflink), so
2827  *    just give data_ac = NULL.
2828  */
2829 static int ocfs2_lock_refcount_allocators(struct super_block *sb,
2830 					u32 p_cluster, u32 num_clusters,
2831 					struct ocfs2_extent_tree *et,
2832 					struct ocfs2_caching_info *ref_ci,
2833 					struct buffer_head *ref_root_bh,
2834 					struct ocfs2_alloc_context **meta_ac,
2835 					struct ocfs2_alloc_context **data_ac,
2836 					int *credits)
2837 {
2838 	int ret = 0, meta_add = 0;
2839 	int num_free_extents = ocfs2_num_free_extents(et);
2840 
2841 	if (num_free_extents < 0) {
2842 		ret = num_free_extents;
2843 		mlog_errno(ret);
2844 		goto out;
2845 	}
2846 
2847 	if (num_free_extents < num_clusters + 2)
2848 		meta_add =
2849 			ocfs2_extend_meta_needed(et->et_root_el);
2850 
2851 	*credits += ocfs2_calc_extend_credits(sb, et->et_root_el);
2852 
2853 	ret = ocfs2_calc_refcount_meta_credits(sb, ref_ci, ref_root_bh,
2854 					       p_cluster, num_clusters,
2855 					       &meta_add, credits);
2856 	if (ret) {
2857 		mlog_errno(ret);
2858 		goto out;
2859 	}
2860 
2861 	trace_ocfs2_lock_refcount_allocators(meta_add, *credits);
2862 	ret = ocfs2_reserve_new_metadata_blocks(OCFS2_SB(sb), meta_add,
2863 						meta_ac);
2864 	if (ret) {
2865 		mlog_errno(ret);
2866 		goto out;
2867 	}
2868 
2869 	if (data_ac) {
2870 		ret = ocfs2_reserve_clusters(OCFS2_SB(sb), num_clusters,
2871 					     data_ac);
2872 		if (ret)
2873 			mlog_errno(ret);
2874 	}
2875 
2876 out:
2877 	if (ret) {
2878 		if (*meta_ac) {
2879 			ocfs2_free_alloc_context(*meta_ac);
2880 			*meta_ac = NULL;
2881 		}
2882 	}
2883 
2884 	return ret;
2885 }
2886 
2887 static int ocfs2_clear_cow_buffer(handle_t *handle, struct buffer_head *bh)
2888 {
2889 	BUG_ON(buffer_dirty(bh));
2890 
2891 	clear_buffer_mapped(bh);
2892 
2893 	return 0;
2894 }
2895 
2896 int ocfs2_duplicate_clusters_by_page(handle_t *handle,
2897 				     struct inode *inode,
2898 				     u32 cpos, u32 old_cluster,
2899 				     u32 new_cluster, u32 new_len)
2900 {
2901 	int ret = 0, partial;
2902 	struct super_block *sb = inode->i_sb;
2903 	u64 new_block = ocfs2_clusters_to_blocks(sb, new_cluster);
2904 	struct page *page;
2905 	pgoff_t page_index;
2906 	unsigned int from, to;
2907 	loff_t offset, end, map_end;
2908 	struct address_space *mapping = inode->i_mapping;
2909 
2910 	trace_ocfs2_duplicate_clusters_by_page(cpos, old_cluster,
2911 					       new_cluster, new_len);
2912 
2913 	offset = ((loff_t)cpos) << OCFS2_SB(sb)->s_clustersize_bits;
2914 	end = offset + (new_len << OCFS2_SB(sb)->s_clustersize_bits);
2915 	/*
2916 	 * We only duplicate pages until we reach the page contains i_size - 1.
2917 	 * So trim 'end' to i_size.
2918 	 */
2919 	if (end > i_size_read(inode))
2920 		end = i_size_read(inode);
2921 
2922 	while (offset < end) {
2923 		page_index = offset >> PAGE_SHIFT;
2924 		map_end = ((loff_t)page_index + 1) << PAGE_SHIFT;
2925 		if (map_end > end)
2926 			map_end = end;
2927 
2928 		/* from, to is the offset within the page. */
2929 		from = offset & (PAGE_SIZE - 1);
2930 		to = PAGE_SIZE;
2931 		if (map_end & (PAGE_SIZE - 1))
2932 			to = map_end & (PAGE_SIZE - 1);
2933 
2934 retry:
2935 		page = find_or_create_page(mapping, page_index, GFP_NOFS);
2936 		if (!page) {
2937 			ret = -ENOMEM;
2938 			mlog_errno(ret);
2939 			break;
2940 		}
2941 
2942 		/*
2943 		 * In case PAGE_SIZE <= CLUSTER_SIZE, we do not expect a dirty
2944 		 * page, so write it back.
2945 		 */
2946 		if (PAGE_SIZE <= OCFS2_SB(sb)->s_clustersize) {
2947 			if (PageDirty(page)) {
2948 				unlock_page(page);
2949 				put_page(page);
2950 
2951 				ret = filemap_write_and_wait_range(mapping,
2952 						offset, map_end - 1);
2953 				goto retry;
2954 			}
2955 		}
2956 
2957 		if (!PageUptodate(page)) {
2958 			struct folio *folio = page_folio(page);
2959 
2960 			ret = block_read_full_folio(folio, ocfs2_get_block);
2961 			if (ret) {
2962 				mlog_errno(ret);
2963 				goto unlock;
2964 			}
2965 			folio_lock(folio);
2966 		}
2967 
2968 		if (page_has_buffers(page)) {
2969 			ret = walk_page_buffers(handle, page_buffers(page),
2970 						from, to, &partial,
2971 						ocfs2_clear_cow_buffer);
2972 			if (ret) {
2973 				mlog_errno(ret);
2974 				goto unlock;
2975 			}
2976 		}
2977 
2978 		ocfs2_map_and_dirty_page(inode,
2979 					 handle, from, to,
2980 					 page, 0, &new_block);
2981 		mark_page_accessed(page);
2982 unlock:
2983 		unlock_page(page);
2984 		put_page(page);
2985 		page = NULL;
2986 		offset = map_end;
2987 		if (ret)
2988 			break;
2989 	}
2990 
2991 	return ret;
2992 }
2993 
2994 int ocfs2_duplicate_clusters_by_jbd(handle_t *handle,
2995 				    struct inode *inode,
2996 				    u32 cpos, u32 old_cluster,
2997 				    u32 new_cluster, u32 new_len)
2998 {
2999 	int ret = 0;
3000 	struct super_block *sb = inode->i_sb;
3001 	struct ocfs2_caching_info *ci = INODE_CACHE(inode);
3002 	int i, blocks = ocfs2_clusters_to_blocks(sb, new_len);
3003 	u64 old_block = ocfs2_clusters_to_blocks(sb, old_cluster);
3004 	u64 new_block = ocfs2_clusters_to_blocks(sb, new_cluster);
3005 	struct ocfs2_super *osb = OCFS2_SB(sb);
3006 	struct buffer_head *old_bh = NULL;
3007 	struct buffer_head *new_bh = NULL;
3008 
3009 	trace_ocfs2_duplicate_clusters_by_page(cpos, old_cluster,
3010 					       new_cluster, new_len);
3011 
3012 	for (i = 0; i < blocks; i++, old_block++, new_block++) {
3013 		new_bh = sb_getblk(osb->sb, new_block);
3014 		if (new_bh == NULL) {
3015 			ret = -ENOMEM;
3016 			mlog_errno(ret);
3017 			break;
3018 		}
3019 
3020 		ocfs2_set_new_buffer_uptodate(ci, new_bh);
3021 
3022 		ret = ocfs2_read_block(ci, old_block, &old_bh, NULL);
3023 		if (ret) {
3024 			mlog_errno(ret);
3025 			break;
3026 		}
3027 
3028 		ret = ocfs2_journal_access(handle, ci, new_bh,
3029 					   OCFS2_JOURNAL_ACCESS_CREATE);
3030 		if (ret) {
3031 			mlog_errno(ret);
3032 			break;
3033 		}
3034 
3035 		memcpy(new_bh->b_data, old_bh->b_data, sb->s_blocksize);
3036 		ocfs2_journal_dirty(handle, new_bh);
3037 
3038 		brelse(new_bh);
3039 		brelse(old_bh);
3040 		new_bh = NULL;
3041 		old_bh = NULL;
3042 	}
3043 
3044 	brelse(new_bh);
3045 	brelse(old_bh);
3046 	return ret;
3047 }
3048 
3049 static int ocfs2_clear_ext_refcount(handle_t *handle,
3050 				    struct ocfs2_extent_tree *et,
3051 				    u32 cpos, u32 p_cluster, u32 len,
3052 				    unsigned int ext_flags,
3053 				    struct ocfs2_alloc_context *meta_ac,
3054 				    struct ocfs2_cached_dealloc_ctxt *dealloc)
3055 {
3056 	int ret, index;
3057 	struct ocfs2_extent_rec replace_rec;
3058 	struct ocfs2_path *path = NULL;
3059 	struct ocfs2_extent_list *el;
3060 	struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
3061 	u64 ino = ocfs2_metadata_cache_owner(et->et_ci);
3062 
3063 	trace_ocfs2_clear_ext_refcount((unsigned long long)ino,
3064 				       cpos, len, p_cluster, ext_flags);
3065 
3066 	memset(&replace_rec, 0, sizeof(replace_rec));
3067 	replace_rec.e_cpos = cpu_to_le32(cpos);
3068 	replace_rec.e_leaf_clusters = cpu_to_le16(len);
3069 	replace_rec.e_blkno = cpu_to_le64(ocfs2_clusters_to_blocks(sb,
3070 								   p_cluster));
3071 	replace_rec.e_flags = ext_flags;
3072 	replace_rec.e_flags &= ~OCFS2_EXT_REFCOUNTED;
3073 
3074 	path = ocfs2_new_path_from_et(et);
3075 	if (!path) {
3076 		ret = -ENOMEM;
3077 		mlog_errno(ret);
3078 		goto out;
3079 	}
3080 
3081 	ret = ocfs2_find_path(et->et_ci, path, cpos);
3082 	if (ret) {
3083 		mlog_errno(ret);
3084 		goto out;
3085 	}
3086 
3087 	el = path_leaf_el(path);
3088 
3089 	index = ocfs2_search_extent_list(el, cpos);
3090 	if (index == -1) {
3091 		ret = ocfs2_error(sb,
3092 				  "Inode %llu has an extent at cpos %u which can no longer be found\n",
3093 				  (unsigned long long)ino, cpos);
3094 		goto out;
3095 	}
3096 
3097 	ret = ocfs2_split_extent(handle, et, path, index,
3098 				 &replace_rec, meta_ac, dealloc);
3099 	if (ret)
3100 		mlog_errno(ret);
3101 
3102 out:
3103 	ocfs2_free_path(path);
3104 	return ret;
3105 }
3106 
3107 static int ocfs2_replace_clusters(handle_t *handle,
3108 				  struct ocfs2_cow_context *context,
3109 				  u32 cpos, u32 old,
3110 				  u32 new, u32 len,
3111 				  unsigned int ext_flags)
3112 {
3113 	int ret;
3114 	struct ocfs2_caching_info *ci = context->data_et.et_ci;
3115 	u64 ino = ocfs2_metadata_cache_owner(ci);
3116 
3117 	trace_ocfs2_replace_clusters((unsigned long long)ino,
3118 				     cpos, old, new, len, ext_flags);
3119 
3120 	/*If the old clusters is unwritten, no need to duplicate. */
3121 	if (!(ext_flags & OCFS2_EXT_UNWRITTEN)) {
3122 		ret = context->cow_duplicate_clusters(handle, context->inode,
3123 						      cpos, old, new, len);
3124 		if (ret) {
3125 			mlog_errno(ret);
3126 			goto out;
3127 		}
3128 	}
3129 
3130 	ret = ocfs2_clear_ext_refcount(handle, &context->data_et,
3131 				       cpos, new, len, ext_flags,
3132 				       context->meta_ac, &context->dealloc);
3133 	if (ret)
3134 		mlog_errno(ret);
3135 out:
3136 	return ret;
3137 }
3138 
3139 int ocfs2_cow_sync_writeback(struct super_block *sb,
3140 			     struct inode *inode,
3141 			     u32 cpos, u32 num_clusters)
3142 {
3143 	int ret;
3144 	loff_t start, end;
3145 
3146 	if (ocfs2_should_order_data(inode))
3147 		return 0;
3148 
3149 	start = ((loff_t)cpos) << OCFS2_SB(sb)->s_clustersize_bits;
3150 	end = start + (num_clusters << OCFS2_SB(sb)->s_clustersize_bits) - 1;
3151 
3152 	ret = filemap_write_and_wait_range(inode->i_mapping, start, end);
3153 	if (ret < 0)
3154 		mlog_errno(ret);
3155 
3156 	return ret;
3157 }
3158 
3159 static int ocfs2_di_get_clusters(struct ocfs2_cow_context *context,
3160 				 u32 v_cluster, u32 *p_cluster,
3161 				 u32 *num_clusters,
3162 				 unsigned int *extent_flags)
3163 {
3164 	return ocfs2_get_clusters(context->inode, v_cluster, p_cluster,
3165 				  num_clusters, extent_flags);
3166 }
3167 
3168 static int ocfs2_make_clusters_writable(struct super_block *sb,
3169 					struct ocfs2_cow_context *context,
3170 					u32 cpos, u32 p_cluster,
3171 					u32 num_clusters, unsigned int e_flags)
3172 {
3173 	int ret, delete, index, credits =  0;
3174 	u32 new_bit, new_len, orig_num_clusters;
3175 	unsigned int set_len;
3176 	struct ocfs2_super *osb = OCFS2_SB(sb);
3177 	handle_t *handle;
3178 	struct buffer_head *ref_leaf_bh = NULL;
3179 	struct ocfs2_caching_info *ref_ci = &context->ref_tree->rf_ci;
3180 	struct ocfs2_refcount_rec rec;
3181 
3182 	trace_ocfs2_make_clusters_writable(cpos, p_cluster,
3183 					   num_clusters, e_flags);
3184 
3185 	ret = ocfs2_lock_refcount_allocators(sb, p_cluster, num_clusters,
3186 					     &context->data_et,
3187 					     ref_ci,
3188 					     context->ref_root_bh,
3189 					     &context->meta_ac,
3190 					     &context->data_ac, &credits);
3191 	if (ret) {
3192 		mlog_errno(ret);
3193 		return ret;
3194 	}
3195 
3196 	if (context->post_refcount)
3197 		credits += context->post_refcount->credits;
3198 
3199 	credits += context->extra_credits;
3200 	handle = ocfs2_start_trans(osb, credits);
3201 	if (IS_ERR(handle)) {
3202 		ret = PTR_ERR(handle);
3203 		mlog_errno(ret);
3204 		goto out;
3205 	}
3206 
3207 	orig_num_clusters = num_clusters;
3208 
3209 	while (num_clusters) {
3210 		ret = ocfs2_get_refcount_rec(ref_ci, context->ref_root_bh,
3211 					     p_cluster, num_clusters,
3212 					     &rec, &index, &ref_leaf_bh);
3213 		if (ret) {
3214 			mlog_errno(ret);
3215 			goto out_commit;
3216 		}
3217 
3218 		BUG_ON(!rec.r_refcount);
3219 		set_len = min((u64)p_cluster + num_clusters,
3220 			      le64_to_cpu(rec.r_cpos) +
3221 			      le32_to_cpu(rec.r_clusters)) - p_cluster;
3222 
3223 		/*
3224 		 * There are many different situation here.
3225 		 * 1. If refcount == 1, remove the flag and don't COW.
3226 		 * 2. If refcount > 1, allocate clusters.
3227 		 *    Here we may not allocate r_len once at a time, so continue
3228 		 *    until we reach num_clusters.
3229 		 */
3230 		if (le32_to_cpu(rec.r_refcount) == 1) {
3231 			delete = 0;
3232 			ret = ocfs2_clear_ext_refcount(handle,
3233 						       &context->data_et,
3234 						       cpos, p_cluster,
3235 						       set_len, e_flags,
3236 						       context->meta_ac,
3237 						       &context->dealloc);
3238 			if (ret) {
3239 				mlog_errno(ret);
3240 				goto out_commit;
3241 			}
3242 		} else {
3243 			delete = 1;
3244 
3245 			ret = __ocfs2_claim_clusters(handle,
3246 						     context->data_ac,
3247 						     1, set_len,
3248 						     &new_bit, &new_len);
3249 			if (ret) {
3250 				mlog_errno(ret);
3251 				goto out_commit;
3252 			}
3253 
3254 			ret = ocfs2_replace_clusters(handle, context,
3255 						     cpos, p_cluster, new_bit,
3256 						     new_len, e_flags);
3257 			if (ret) {
3258 				mlog_errno(ret);
3259 				goto out_commit;
3260 			}
3261 			set_len = new_len;
3262 		}
3263 
3264 		ret = __ocfs2_decrease_refcount(handle, ref_ci,
3265 						context->ref_root_bh,
3266 						p_cluster, set_len,
3267 						context->meta_ac,
3268 						&context->dealloc, delete);
3269 		if (ret) {
3270 			mlog_errno(ret);
3271 			goto out_commit;
3272 		}
3273 
3274 		cpos += set_len;
3275 		p_cluster += set_len;
3276 		num_clusters -= set_len;
3277 		brelse(ref_leaf_bh);
3278 		ref_leaf_bh = NULL;
3279 	}
3280 
3281 	/* handle any post_cow action. */
3282 	if (context->post_refcount && context->post_refcount->func) {
3283 		ret = context->post_refcount->func(context->inode, handle,
3284 						context->post_refcount->para);
3285 		if (ret) {
3286 			mlog_errno(ret);
3287 			goto out_commit;
3288 		}
3289 	}
3290 
3291 	/*
3292 	 * Here we should write the new page out first if we are
3293 	 * in write-back mode.
3294 	 */
3295 	if (context->get_clusters == ocfs2_di_get_clusters) {
3296 		ret = ocfs2_cow_sync_writeback(sb, context->inode, cpos,
3297 					       orig_num_clusters);
3298 		if (ret)
3299 			mlog_errno(ret);
3300 	}
3301 
3302 out_commit:
3303 	ocfs2_commit_trans(osb, handle);
3304 
3305 out:
3306 	if (context->data_ac) {
3307 		ocfs2_free_alloc_context(context->data_ac);
3308 		context->data_ac = NULL;
3309 	}
3310 	if (context->meta_ac) {
3311 		ocfs2_free_alloc_context(context->meta_ac);
3312 		context->meta_ac = NULL;
3313 	}
3314 	brelse(ref_leaf_bh);
3315 
3316 	return ret;
3317 }
3318 
3319 static int ocfs2_replace_cow(struct ocfs2_cow_context *context)
3320 {
3321 	int ret = 0;
3322 	struct inode *inode = context->inode;
3323 	u32 cow_start = context->cow_start, cow_len = context->cow_len;
3324 	u32 p_cluster, num_clusters;
3325 	unsigned int ext_flags;
3326 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3327 
3328 	if (!ocfs2_refcount_tree(osb)) {
3329 		return ocfs2_error(inode->i_sb, "Inode %lu want to use refcount tree, but the feature bit is not set in the super block\n",
3330 				   inode->i_ino);
3331 	}
3332 
3333 	ocfs2_init_dealloc_ctxt(&context->dealloc);
3334 
3335 	while (cow_len) {
3336 		ret = context->get_clusters(context, cow_start, &p_cluster,
3337 					    &num_clusters, &ext_flags);
3338 		if (ret) {
3339 			mlog_errno(ret);
3340 			break;
3341 		}
3342 
3343 		BUG_ON(!(ext_flags & OCFS2_EXT_REFCOUNTED));
3344 
3345 		if (cow_len < num_clusters)
3346 			num_clusters = cow_len;
3347 
3348 		ret = ocfs2_make_clusters_writable(inode->i_sb, context,
3349 						   cow_start, p_cluster,
3350 						   num_clusters, ext_flags);
3351 		if (ret) {
3352 			mlog_errno(ret);
3353 			break;
3354 		}
3355 
3356 		cow_len -= num_clusters;
3357 		cow_start += num_clusters;
3358 	}
3359 
3360 	if (ocfs2_dealloc_has_cluster(&context->dealloc)) {
3361 		ocfs2_schedule_truncate_log_flush(osb, 1);
3362 		ocfs2_run_deallocs(osb, &context->dealloc);
3363 	}
3364 
3365 	return ret;
3366 }
3367 
3368 /*
3369  * Starting at cpos, try to CoW write_len clusters.  Don't CoW
3370  * past max_cpos.  This will stop when it runs into a hole or an
3371  * unrefcounted extent.
3372  */
3373 static int ocfs2_refcount_cow_hunk(struct inode *inode,
3374 				   struct buffer_head *di_bh,
3375 				   u32 cpos, u32 write_len, u32 max_cpos)
3376 {
3377 	int ret;
3378 	u32 cow_start = 0, cow_len = 0;
3379 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3380 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
3381 	struct buffer_head *ref_root_bh = NULL;
3382 	struct ocfs2_refcount_tree *ref_tree;
3383 	struct ocfs2_cow_context *context = NULL;
3384 
3385 	BUG_ON(!ocfs2_is_refcount_inode(inode));
3386 
3387 	ret = ocfs2_refcount_cal_cow_clusters(inode, &di->id2.i_list,
3388 					      cpos, write_len, max_cpos,
3389 					      &cow_start, &cow_len);
3390 	if (ret) {
3391 		mlog_errno(ret);
3392 		goto out;
3393 	}
3394 
3395 	trace_ocfs2_refcount_cow_hunk(OCFS2_I(inode)->ip_blkno,
3396 				      cpos, write_len, max_cpos,
3397 				      cow_start, cow_len);
3398 
3399 	BUG_ON(cow_len == 0);
3400 
3401 	context = kzalloc(sizeof(struct ocfs2_cow_context), GFP_NOFS);
3402 	if (!context) {
3403 		ret = -ENOMEM;
3404 		mlog_errno(ret);
3405 		goto out;
3406 	}
3407 
3408 	ret = ocfs2_lock_refcount_tree(osb, le64_to_cpu(di->i_refcount_loc),
3409 				       1, &ref_tree, &ref_root_bh);
3410 	if (ret) {
3411 		mlog_errno(ret);
3412 		goto out;
3413 	}
3414 
3415 	context->inode = inode;
3416 	context->cow_start = cow_start;
3417 	context->cow_len = cow_len;
3418 	context->ref_tree = ref_tree;
3419 	context->ref_root_bh = ref_root_bh;
3420 	context->cow_duplicate_clusters = ocfs2_duplicate_clusters_by_page;
3421 	context->get_clusters = ocfs2_di_get_clusters;
3422 
3423 	ocfs2_init_dinode_extent_tree(&context->data_et,
3424 				      INODE_CACHE(inode), di_bh);
3425 
3426 	ret = ocfs2_replace_cow(context);
3427 	if (ret)
3428 		mlog_errno(ret);
3429 
3430 	/*
3431 	 * truncate the extent map here since no matter whether we meet with
3432 	 * any error during the action, we shouldn't trust cached extent map
3433 	 * any more.
3434 	 */
3435 	ocfs2_extent_map_trunc(inode, cow_start);
3436 
3437 	ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
3438 	brelse(ref_root_bh);
3439 out:
3440 	kfree(context);
3441 	return ret;
3442 }
3443 
3444 /*
3445  * CoW any and all clusters between cpos and cpos+write_len.
3446  * Don't CoW past max_cpos.  If this returns successfully, all
3447  * clusters between cpos and cpos+write_len are safe to modify.
3448  */
3449 int ocfs2_refcount_cow(struct inode *inode,
3450 		       struct buffer_head *di_bh,
3451 		       u32 cpos, u32 write_len, u32 max_cpos)
3452 {
3453 	int ret = 0;
3454 	u32 p_cluster, num_clusters;
3455 	unsigned int ext_flags;
3456 
3457 	while (write_len) {
3458 		ret = ocfs2_get_clusters(inode, cpos, &p_cluster,
3459 					 &num_clusters, &ext_flags);
3460 		if (ret) {
3461 			mlog_errno(ret);
3462 			break;
3463 		}
3464 
3465 		if (write_len < num_clusters)
3466 			num_clusters = write_len;
3467 
3468 		if (ext_flags & OCFS2_EXT_REFCOUNTED) {
3469 			ret = ocfs2_refcount_cow_hunk(inode, di_bh, cpos,
3470 						      num_clusters, max_cpos);
3471 			if (ret) {
3472 				mlog_errno(ret);
3473 				break;
3474 			}
3475 		}
3476 
3477 		write_len -= num_clusters;
3478 		cpos += num_clusters;
3479 	}
3480 
3481 	return ret;
3482 }
3483 
3484 static int ocfs2_xattr_value_get_clusters(struct ocfs2_cow_context *context,
3485 					  u32 v_cluster, u32 *p_cluster,
3486 					  u32 *num_clusters,
3487 					  unsigned int *extent_flags)
3488 {
3489 	struct inode *inode = context->inode;
3490 	struct ocfs2_xattr_value_root *xv = context->cow_object;
3491 
3492 	return ocfs2_xattr_get_clusters(inode, v_cluster, p_cluster,
3493 					num_clusters, &xv->xr_list,
3494 					extent_flags);
3495 }
3496 
3497 /*
3498  * Given a xattr value root, calculate the most meta/credits we need for
3499  * refcount tree change if we truncate it to 0.
3500  */
3501 int ocfs2_refcounted_xattr_delete_need(struct inode *inode,
3502 				       struct ocfs2_caching_info *ref_ci,
3503 				       struct buffer_head *ref_root_bh,
3504 				       struct ocfs2_xattr_value_root *xv,
3505 				       int *meta_add, int *credits)
3506 {
3507 	int ret = 0, index, ref_blocks = 0;
3508 	u32 p_cluster, num_clusters;
3509 	u32 cpos = 0, clusters = le32_to_cpu(xv->xr_clusters);
3510 	struct ocfs2_refcount_block *rb;
3511 	struct ocfs2_refcount_rec rec;
3512 	struct buffer_head *ref_leaf_bh = NULL;
3513 
3514 	while (cpos < clusters) {
3515 		ret = ocfs2_xattr_get_clusters(inode, cpos, &p_cluster,
3516 					       &num_clusters, &xv->xr_list,
3517 					       NULL);
3518 		if (ret) {
3519 			mlog_errno(ret);
3520 			goto out;
3521 		}
3522 
3523 		cpos += num_clusters;
3524 
3525 		while (num_clusters) {
3526 			ret = ocfs2_get_refcount_rec(ref_ci, ref_root_bh,
3527 						     p_cluster, num_clusters,
3528 						     &rec, &index,
3529 						     &ref_leaf_bh);
3530 			if (ret) {
3531 				mlog_errno(ret);
3532 				goto out;
3533 			}
3534 
3535 			BUG_ON(!rec.r_refcount);
3536 
3537 			rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
3538 
3539 			/*
3540 			 * We really don't know whether the other clusters is in
3541 			 * this refcount block or not, so just take the worst
3542 			 * case that all the clusters are in this block and each
3543 			 * one will split a refcount rec, so totally we need
3544 			 * clusters * 2 new refcount rec.
3545 			 */
3546 			if (le16_to_cpu(rb->rf_records.rl_used) + clusters * 2 >
3547 			    le16_to_cpu(rb->rf_records.rl_count))
3548 				ref_blocks++;
3549 
3550 			*credits += 1;
3551 			brelse(ref_leaf_bh);
3552 			ref_leaf_bh = NULL;
3553 
3554 			if (num_clusters <= le32_to_cpu(rec.r_clusters))
3555 				break;
3556 			else
3557 				num_clusters -= le32_to_cpu(rec.r_clusters);
3558 			p_cluster += num_clusters;
3559 		}
3560 	}
3561 
3562 	*meta_add += ref_blocks;
3563 	if (!ref_blocks)
3564 		goto out;
3565 
3566 	rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
3567 	if (le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL)
3568 		*credits += OCFS2_EXPAND_REFCOUNT_TREE_CREDITS;
3569 	else {
3570 		struct ocfs2_extent_tree et;
3571 
3572 		ocfs2_init_refcount_extent_tree(&et, ref_ci, ref_root_bh);
3573 		*credits += ocfs2_calc_extend_credits(inode->i_sb,
3574 						      et.et_root_el);
3575 	}
3576 
3577 out:
3578 	brelse(ref_leaf_bh);
3579 	return ret;
3580 }
3581 
3582 /*
3583  * Do CoW for xattr.
3584  */
3585 int ocfs2_refcount_cow_xattr(struct inode *inode,
3586 			     struct ocfs2_dinode *di,
3587 			     struct ocfs2_xattr_value_buf *vb,
3588 			     struct ocfs2_refcount_tree *ref_tree,
3589 			     struct buffer_head *ref_root_bh,
3590 			     u32 cpos, u32 write_len,
3591 			     struct ocfs2_post_refcount *post)
3592 {
3593 	int ret;
3594 	struct ocfs2_xattr_value_root *xv = vb->vb_xv;
3595 	struct ocfs2_cow_context *context = NULL;
3596 	u32 cow_start, cow_len;
3597 
3598 	BUG_ON(!ocfs2_is_refcount_inode(inode));
3599 
3600 	ret = ocfs2_refcount_cal_cow_clusters(inode, &xv->xr_list,
3601 					      cpos, write_len, UINT_MAX,
3602 					      &cow_start, &cow_len);
3603 	if (ret) {
3604 		mlog_errno(ret);
3605 		goto out;
3606 	}
3607 
3608 	BUG_ON(cow_len == 0);
3609 
3610 	context = kzalloc(sizeof(struct ocfs2_cow_context), GFP_NOFS);
3611 	if (!context) {
3612 		ret = -ENOMEM;
3613 		mlog_errno(ret);
3614 		goto out;
3615 	}
3616 
3617 	context->inode = inode;
3618 	context->cow_start = cow_start;
3619 	context->cow_len = cow_len;
3620 	context->ref_tree = ref_tree;
3621 	context->ref_root_bh = ref_root_bh;
3622 	context->cow_object = xv;
3623 
3624 	context->cow_duplicate_clusters = ocfs2_duplicate_clusters_by_jbd;
3625 	/* We need the extra credits for duplicate_clusters by jbd. */
3626 	context->extra_credits =
3627 		ocfs2_clusters_to_blocks(inode->i_sb, 1) * cow_len;
3628 	context->get_clusters = ocfs2_xattr_value_get_clusters;
3629 	context->post_refcount = post;
3630 
3631 	ocfs2_init_xattr_value_extent_tree(&context->data_et,
3632 					   INODE_CACHE(inode), vb);
3633 
3634 	ret = ocfs2_replace_cow(context);
3635 	if (ret)
3636 		mlog_errno(ret);
3637 
3638 out:
3639 	kfree(context);
3640 	return ret;
3641 }
3642 
3643 /*
3644  * Insert a new extent into refcount tree and mark a extent rec
3645  * as refcounted in the dinode tree.
3646  */
3647 int ocfs2_add_refcount_flag(struct inode *inode,
3648 			    struct ocfs2_extent_tree *data_et,
3649 			    struct ocfs2_caching_info *ref_ci,
3650 			    struct buffer_head *ref_root_bh,
3651 			    u32 cpos, u32 p_cluster, u32 num_clusters,
3652 			    struct ocfs2_cached_dealloc_ctxt *dealloc,
3653 			    struct ocfs2_post_refcount *post)
3654 {
3655 	int ret;
3656 	handle_t *handle;
3657 	int credits = 1, ref_blocks = 0;
3658 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3659 	struct ocfs2_alloc_context *meta_ac = NULL;
3660 
3661 	/* We need to be able to handle at least an extent tree split. */
3662 	ref_blocks = ocfs2_extend_meta_needed(data_et->et_root_el);
3663 
3664 	ret = ocfs2_calc_refcount_meta_credits(inode->i_sb,
3665 					       ref_ci, ref_root_bh,
3666 					       p_cluster, num_clusters,
3667 					       &ref_blocks, &credits);
3668 	if (ret) {
3669 		mlog_errno(ret);
3670 		goto out;
3671 	}
3672 
3673 	trace_ocfs2_add_refcount_flag(ref_blocks, credits);
3674 
3675 	if (ref_blocks) {
3676 		ret = ocfs2_reserve_new_metadata_blocks(osb,
3677 							ref_blocks, &meta_ac);
3678 		if (ret) {
3679 			mlog_errno(ret);
3680 			goto out;
3681 		}
3682 	}
3683 
3684 	if (post)
3685 		credits += post->credits;
3686 
3687 	handle = ocfs2_start_trans(osb, credits);
3688 	if (IS_ERR(handle)) {
3689 		ret = PTR_ERR(handle);
3690 		mlog_errno(ret);
3691 		goto out;
3692 	}
3693 
3694 	ret = ocfs2_mark_extent_refcounted(inode, data_et, handle,
3695 					   cpos, num_clusters, p_cluster,
3696 					   meta_ac, dealloc);
3697 	if (ret) {
3698 		mlog_errno(ret);
3699 		goto out_commit;
3700 	}
3701 
3702 	ret = __ocfs2_increase_refcount(handle, ref_ci, ref_root_bh,
3703 					p_cluster, num_clusters, 0,
3704 					meta_ac, dealloc);
3705 	if (ret) {
3706 		mlog_errno(ret);
3707 		goto out_commit;
3708 	}
3709 
3710 	if (post && post->func) {
3711 		ret = post->func(inode, handle, post->para);
3712 		if (ret)
3713 			mlog_errno(ret);
3714 	}
3715 
3716 out_commit:
3717 	ocfs2_commit_trans(osb, handle);
3718 out:
3719 	if (meta_ac)
3720 		ocfs2_free_alloc_context(meta_ac);
3721 	return ret;
3722 }
3723 
3724 static int ocfs2_change_ctime(struct inode *inode,
3725 			      struct buffer_head *di_bh)
3726 {
3727 	int ret;
3728 	handle_t *handle;
3729 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
3730 
3731 	handle = ocfs2_start_trans(OCFS2_SB(inode->i_sb),
3732 				   OCFS2_INODE_UPDATE_CREDITS);
3733 	if (IS_ERR(handle)) {
3734 		ret = PTR_ERR(handle);
3735 		mlog_errno(ret);
3736 		goto out;
3737 	}
3738 
3739 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
3740 				      OCFS2_JOURNAL_ACCESS_WRITE);
3741 	if (ret) {
3742 		mlog_errno(ret);
3743 		goto out_commit;
3744 	}
3745 
3746 	inode_set_ctime_current(inode);
3747 	di->i_ctime = cpu_to_le64(inode_get_ctime_sec(inode));
3748 	di->i_ctime_nsec = cpu_to_le32(inode_get_ctime_nsec(inode));
3749 
3750 	ocfs2_journal_dirty(handle, di_bh);
3751 
3752 out_commit:
3753 	ocfs2_commit_trans(OCFS2_SB(inode->i_sb), handle);
3754 out:
3755 	return ret;
3756 }
3757 
3758 static int ocfs2_attach_refcount_tree(struct inode *inode,
3759 				      struct buffer_head *di_bh)
3760 {
3761 	int ret, data_changed = 0;
3762 	struct buffer_head *ref_root_bh = NULL;
3763 	struct ocfs2_inode_info *oi = OCFS2_I(inode);
3764 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
3765 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3766 	struct ocfs2_refcount_tree *ref_tree;
3767 	unsigned int ext_flags;
3768 	loff_t size;
3769 	u32 cpos, num_clusters, clusters, p_cluster;
3770 	struct ocfs2_cached_dealloc_ctxt dealloc;
3771 	struct ocfs2_extent_tree di_et;
3772 
3773 	ocfs2_init_dealloc_ctxt(&dealloc);
3774 
3775 	if (!ocfs2_is_refcount_inode(inode)) {
3776 		ret = ocfs2_create_refcount_tree(inode, di_bh);
3777 		if (ret) {
3778 			mlog_errno(ret);
3779 			goto out;
3780 		}
3781 	}
3782 
3783 	BUG_ON(!di->i_refcount_loc);
3784 	ret = ocfs2_lock_refcount_tree(osb,
3785 				       le64_to_cpu(di->i_refcount_loc), 1,
3786 				       &ref_tree, &ref_root_bh);
3787 	if (ret) {
3788 		mlog_errno(ret);
3789 		goto out;
3790 	}
3791 
3792 	if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL)
3793 		goto attach_xattr;
3794 
3795 	ocfs2_init_dinode_extent_tree(&di_et, INODE_CACHE(inode), di_bh);
3796 
3797 	size = i_size_read(inode);
3798 	clusters = ocfs2_clusters_for_bytes(inode->i_sb, size);
3799 
3800 	cpos = 0;
3801 	while (cpos < clusters) {
3802 		ret = ocfs2_get_clusters(inode, cpos, &p_cluster,
3803 					 &num_clusters, &ext_flags);
3804 		if (ret) {
3805 			mlog_errno(ret);
3806 			goto unlock;
3807 		}
3808 		if (p_cluster && !(ext_flags & OCFS2_EXT_REFCOUNTED)) {
3809 			ret = ocfs2_add_refcount_flag(inode, &di_et,
3810 						      &ref_tree->rf_ci,
3811 						      ref_root_bh, cpos,
3812 						      p_cluster, num_clusters,
3813 						      &dealloc, NULL);
3814 			if (ret) {
3815 				mlog_errno(ret);
3816 				goto unlock;
3817 			}
3818 
3819 			data_changed = 1;
3820 		}
3821 		cpos += num_clusters;
3822 	}
3823 
3824 attach_xattr:
3825 	if (oi->ip_dyn_features & OCFS2_HAS_XATTR_FL) {
3826 		ret = ocfs2_xattr_attach_refcount_tree(inode, di_bh,
3827 						       &ref_tree->rf_ci,
3828 						       ref_root_bh,
3829 						       &dealloc);
3830 		if (ret) {
3831 			mlog_errno(ret);
3832 			goto unlock;
3833 		}
3834 	}
3835 
3836 	if (data_changed) {
3837 		ret = ocfs2_change_ctime(inode, di_bh);
3838 		if (ret)
3839 			mlog_errno(ret);
3840 	}
3841 
3842 unlock:
3843 	ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
3844 	brelse(ref_root_bh);
3845 
3846 	if (!ret && ocfs2_dealloc_has_cluster(&dealloc)) {
3847 		ocfs2_schedule_truncate_log_flush(osb, 1);
3848 		ocfs2_run_deallocs(osb, &dealloc);
3849 	}
3850 out:
3851 	/*
3852 	 * Empty the extent map so that we may get the right extent
3853 	 * record from the disk.
3854 	 */
3855 	ocfs2_extent_map_trunc(inode, 0);
3856 
3857 	return ret;
3858 }
3859 
3860 static int ocfs2_add_refcounted_extent(struct inode *inode,
3861 				   struct ocfs2_extent_tree *et,
3862 				   struct ocfs2_caching_info *ref_ci,
3863 				   struct buffer_head *ref_root_bh,
3864 				   u32 cpos, u32 p_cluster, u32 num_clusters,
3865 				   unsigned int ext_flags,
3866 				   struct ocfs2_cached_dealloc_ctxt *dealloc)
3867 {
3868 	int ret;
3869 	handle_t *handle;
3870 	int credits = 0;
3871 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3872 	struct ocfs2_alloc_context *meta_ac = NULL;
3873 
3874 	ret = ocfs2_lock_refcount_allocators(inode->i_sb,
3875 					     p_cluster, num_clusters,
3876 					     et, ref_ci,
3877 					     ref_root_bh, &meta_ac,
3878 					     NULL, &credits);
3879 	if (ret) {
3880 		mlog_errno(ret);
3881 		goto out;
3882 	}
3883 
3884 	handle = ocfs2_start_trans(osb, credits);
3885 	if (IS_ERR(handle)) {
3886 		ret = PTR_ERR(handle);
3887 		mlog_errno(ret);
3888 		goto out;
3889 	}
3890 
3891 	ret = ocfs2_insert_extent(handle, et, cpos,
3892 			ocfs2_clusters_to_blocks(inode->i_sb, p_cluster),
3893 			num_clusters, ext_flags, meta_ac);
3894 	if (ret) {
3895 		mlog_errno(ret);
3896 		goto out_commit;
3897 	}
3898 
3899 	ret = ocfs2_increase_refcount(handle, ref_ci, ref_root_bh,
3900 				      p_cluster, num_clusters,
3901 				      meta_ac, dealloc);
3902 	if (ret) {
3903 		mlog_errno(ret);
3904 		goto out_commit;
3905 	}
3906 
3907 	ret = dquot_alloc_space_nodirty(inode,
3908 		ocfs2_clusters_to_bytes(osb->sb, num_clusters));
3909 	if (ret)
3910 		mlog_errno(ret);
3911 
3912 out_commit:
3913 	ocfs2_commit_trans(osb, handle);
3914 out:
3915 	if (meta_ac)
3916 		ocfs2_free_alloc_context(meta_ac);
3917 	return ret;
3918 }
3919 
3920 static int ocfs2_duplicate_inline_data(struct inode *s_inode,
3921 				       struct buffer_head *s_bh,
3922 				       struct inode *t_inode,
3923 				       struct buffer_head *t_bh)
3924 {
3925 	int ret;
3926 	handle_t *handle;
3927 	struct ocfs2_super *osb = OCFS2_SB(s_inode->i_sb);
3928 	struct ocfs2_dinode *s_di = (struct ocfs2_dinode *)s_bh->b_data;
3929 	struct ocfs2_dinode *t_di = (struct ocfs2_dinode *)t_bh->b_data;
3930 
3931 	BUG_ON(!(OCFS2_I(s_inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL));
3932 
3933 	handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
3934 	if (IS_ERR(handle)) {
3935 		ret = PTR_ERR(handle);
3936 		mlog_errno(ret);
3937 		goto out;
3938 	}
3939 
3940 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(t_inode), t_bh,
3941 				      OCFS2_JOURNAL_ACCESS_WRITE);
3942 	if (ret) {
3943 		mlog_errno(ret);
3944 		goto out_commit;
3945 	}
3946 
3947 	t_di->id2.i_data.id_count = s_di->id2.i_data.id_count;
3948 	memcpy(t_di->id2.i_data.id_data, s_di->id2.i_data.id_data,
3949 	       le16_to_cpu(s_di->id2.i_data.id_count));
3950 	spin_lock(&OCFS2_I(t_inode)->ip_lock);
3951 	OCFS2_I(t_inode)->ip_dyn_features |= OCFS2_INLINE_DATA_FL;
3952 	t_di->i_dyn_features = cpu_to_le16(OCFS2_I(t_inode)->ip_dyn_features);
3953 	spin_unlock(&OCFS2_I(t_inode)->ip_lock);
3954 
3955 	ocfs2_journal_dirty(handle, t_bh);
3956 
3957 out_commit:
3958 	ocfs2_commit_trans(osb, handle);
3959 out:
3960 	return ret;
3961 }
3962 
3963 static int ocfs2_duplicate_extent_list(struct inode *s_inode,
3964 				struct inode *t_inode,
3965 				struct buffer_head *t_bh,
3966 				struct ocfs2_caching_info *ref_ci,
3967 				struct buffer_head *ref_root_bh,
3968 				struct ocfs2_cached_dealloc_ctxt *dealloc)
3969 {
3970 	int ret = 0;
3971 	u32 p_cluster, num_clusters, clusters, cpos;
3972 	loff_t size;
3973 	unsigned int ext_flags;
3974 	struct ocfs2_extent_tree et;
3975 
3976 	ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(t_inode), t_bh);
3977 
3978 	size = i_size_read(s_inode);
3979 	clusters = ocfs2_clusters_for_bytes(s_inode->i_sb, size);
3980 
3981 	cpos = 0;
3982 	while (cpos < clusters) {
3983 		ret = ocfs2_get_clusters(s_inode, cpos, &p_cluster,
3984 					 &num_clusters, &ext_flags);
3985 		if (ret) {
3986 			mlog_errno(ret);
3987 			goto out;
3988 		}
3989 		if (p_cluster) {
3990 			ret = ocfs2_add_refcounted_extent(t_inode, &et,
3991 							  ref_ci, ref_root_bh,
3992 							  cpos, p_cluster,
3993 							  num_clusters,
3994 							  ext_flags,
3995 							  dealloc);
3996 			if (ret) {
3997 				mlog_errno(ret);
3998 				goto out;
3999 			}
4000 		}
4001 
4002 		cpos += num_clusters;
4003 	}
4004 
4005 out:
4006 	return ret;
4007 }
4008 
4009 /*
4010  * change the new file's attributes to the src.
4011  *
4012  * reflink creates a snapshot of a file, that means the attributes
4013  * must be identical except for three exceptions - nlink, ino, and ctime.
4014  */
4015 static int ocfs2_complete_reflink(struct inode *s_inode,
4016 				  struct buffer_head *s_bh,
4017 				  struct inode *t_inode,
4018 				  struct buffer_head *t_bh,
4019 				  bool preserve)
4020 {
4021 	int ret;
4022 	handle_t *handle;
4023 	struct ocfs2_dinode *s_di = (struct ocfs2_dinode *)s_bh->b_data;
4024 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)t_bh->b_data;
4025 	loff_t size = i_size_read(s_inode);
4026 
4027 	handle = ocfs2_start_trans(OCFS2_SB(t_inode->i_sb),
4028 				   OCFS2_INODE_UPDATE_CREDITS);
4029 	if (IS_ERR(handle)) {
4030 		ret = PTR_ERR(handle);
4031 		mlog_errno(ret);
4032 		return ret;
4033 	}
4034 
4035 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(t_inode), t_bh,
4036 				      OCFS2_JOURNAL_ACCESS_WRITE);
4037 	if (ret) {
4038 		mlog_errno(ret);
4039 		goto out_commit;
4040 	}
4041 
4042 	spin_lock(&OCFS2_I(t_inode)->ip_lock);
4043 	OCFS2_I(t_inode)->ip_clusters = OCFS2_I(s_inode)->ip_clusters;
4044 	OCFS2_I(t_inode)->ip_attr = OCFS2_I(s_inode)->ip_attr;
4045 	OCFS2_I(t_inode)->ip_dyn_features = OCFS2_I(s_inode)->ip_dyn_features;
4046 	spin_unlock(&OCFS2_I(t_inode)->ip_lock);
4047 	i_size_write(t_inode, size);
4048 	t_inode->i_blocks = s_inode->i_blocks;
4049 
4050 	di->i_xattr_inline_size = s_di->i_xattr_inline_size;
4051 	di->i_clusters = s_di->i_clusters;
4052 	di->i_size = s_di->i_size;
4053 	di->i_dyn_features = s_di->i_dyn_features;
4054 	di->i_attr = s_di->i_attr;
4055 
4056 	if (preserve) {
4057 		t_inode->i_uid = s_inode->i_uid;
4058 		t_inode->i_gid = s_inode->i_gid;
4059 		t_inode->i_mode = s_inode->i_mode;
4060 		di->i_uid = s_di->i_uid;
4061 		di->i_gid = s_di->i_gid;
4062 		di->i_mode = s_di->i_mode;
4063 
4064 		/*
4065 		 * update time.
4066 		 * we want mtime to appear identical to the source and
4067 		 * update ctime.
4068 		 */
4069 		inode_set_ctime_current(t_inode);
4070 
4071 		di->i_ctime = cpu_to_le64(inode_get_ctime_sec(t_inode));
4072 		di->i_ctime_nsec = cpu_to_le32(inode_get_ctime_nsec(t_inode));
4073 
4074 		inode_set_mtime_to_ts(t_inode, inode_get_mtime(s_inode));
4075 		di->i_mtime = s_di->i_mtime;
4076 		di->i_mtime_nsec = s_di->i_mtime_nsec;
4077 	}
4078 
4079 	ocfs2_journal_dirty(handle, t_bh);
4080 
4081 out_commit:
4082 	ocfs2_commit_trans(OCFS2_SB(t_inode->i_sb), handle);
4083 	return ret;
4084 }
4085 
4086 static int ocfs2_create_reflink_node(struct inode *s_inode,
4087 				     struct buffer_head *s_bh,
4088 				     struct inode *t_inode,
4089 				     struct buffer_head *t_bh,
4090 				     bool preserve)
4091 {
4092 	int ret;
4093 	struct buffer_head *ref_root_bh = NULL;
4094 	struct ocfs2_cached_dealloc_ctxt dealloc;
4095 	struct ocfs2_super *osb = OCFS2_SB(s_inode->i_sb);
4096 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)s_bh->b_data;
4097 	struct ocfs2_refcount_tree *ref_tree;
4098 
4099 	ocfs2_init_dealloc_ctxt(&dealloc);
4100 
4101 	ret = ocfs2_set_refcount_tree(t_inode, t_bh,
4102 				      le64_to_cpu(di->i_refcount_loc));
4103 	if (ret) {
4104 		mlog_errno(ret);
4105 		goto out;
4106 	}
4107 
4108 	if (OCFS2_I(s_inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
4109 		ret = ocfs2_duplicate_inline_data(s_inode, s_bh,
4110 						  t_inode, t_bh);
4111 		if (ret)
4112 			mlog_errno(ret);
4113 		goto out;
4114 	}
4115 
4116 	ret = ocfs2_lock_refcount_tree(osb, le64_to_cpu(di->i_refcount_loc),
4117 				       1, &ref_tree, &ref_root_bh);
4118 	if (ret) {
4119 		mlog_errno(ret);
4120 		goto out;
4121 	}
4122 
4123 	ret = ocfs2_duplicate_extent_list(s_inode, t_inode, t_bh,
4124 					  &ref_tree->rf_ci, ref_root_bh,
4125 					  &dealloc);
4126 	if (ret) {
4127 		mlog_errno(ret);
4128 		goto out_unlock_refcount;
4129 	}
4130 
4131 out_unlock_refcount:
4132 	ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
4133 	brelse(ref_root_bh);
4134 out:
4135 	if (ocfs2_dealloc_has_cluster(&dealloc)) {
4136 		ocfs2_schedule_truncate_log_flush(osb, 1);
4137 		ocfs2_run_deallocs(osb, &dealloc);
4138 	}
4139 
4140 	return ret;
4141 }
4142 
4143 static int __ocfs2_reflink(struct dentry *old_dentry,
4144 			   struct buffer_head *old_bh,
4145 			   struct inode *new_inode,
4146 			   bool preserve)
4147 {
4148 	int ret;
4149 	struct inode *inode = d_inode(old_dentry);
4150 	struct buffer_head *new_bh = NULL;
4151 
4152 	if (OCFS2_I(inode)->ip_flags & OCFS2_INODE_SYSTEM_FILE) {
4153 		ret = -EINVAL;
4154 		mlog_errno(ret);
4155 		goto out;
4156 	}
4157 
4158 	ret = filemap_fdatawrite(inode->i_mapping);
4159 	if (ret) {
4160 		mlog_errno(ret);
4161 		goto out;
4162 	}
4163 
4164 	ret = ocfs2_attach_refcount_tree(inode, old_bh);
4165 	if (ret) {
4166 		mlog_errno(ret);
4167 		goto out;
4168 	}
4169 
4170 	inode_lock_nested(new_inode, I_MUTEX_CHILD);
4171 	ret = ocfs2_inode_lock_nested(new_inode, &new_bh, 1,
4172 				      OI_LS_REFLINK_TARGET);
4173 	if (ret) {
4174 		mlog_errno(ret);
4175 		goto out_unlock;
4176 	}
4177 
4178 	ret = ocfs2_create_reflink_node(inode, old_bh,
4179 					new_inode, new_bh, preserve);
4180 	if (ret) {
4181 		mlog_errno(ret);
4182 		goto inode_unlock;
4183 	}
4184 
4185 	if (OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_XATTR_FL) {
4186 		ret = ocfs2_reflink_xattrs(inode, old_bh,
4187 					   new_inode, new_bh,
4188 					   preserve);
4189 		if (ret) {
4190 			mlog_errno(ret);
4191 			goto inode_unlock;
4192 		}
4193 	}
4194 
4195 	ret = ocfs2_complete_reflink(inode, old_bh,
4196 				     new_inode, new_bh, preserve);
4197 	if (ret)
4198 		mlog_errno(ret);
4199 
4200 inode_unlock:
4201 	ocfs2_inode_unlock(new_inode, 1);
4202 	brelse(new_bh);
4203 out_unlock:
4204 	inode_unlock(new_inode);
4205 out:
4206 	if (!ret) {
4207 		ret = filemap_fdatawait(inode->i_mapping);
4208 		if (ret)
4209 			mlog_errno(ret);
4210 	}
4211 	return ret;
4212 }
4213 
4214 static int ocfs2_reflink(struct dentry *old_dentry, struct inode *dir,
4215 			 struct dentry *new_dentry, bool preserve)
4216 {
4217 	int error, had_lock;
4218 	struct inode *inode = d_inode(old_dentry);
4219 	struct buffer_head *old_bh = NULL;
4220 	struct inode *new_orphan_inode = NULL;
4221 	struct ocfs2_lock_holder oh;
4222 
4223 	if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb)))
4224 		return -EOPNOTSUPP;
4225 
4226 
4227 	error = ocfs2_create_inode_in_orphan(dir, inode->i_mode,
4228 					     &new_orphan_inode);
4229 	if (error) {
4230 		mlog_errno(error);
4231 		goto out;
4232 	}
4233 
4234 	error = ocfs2_rw_lock(inode, 1);
4235 	if (error) {
4236 		mlog_errno(error);
4237 		goto out;
4238 	}
4239 
4240 	error = ocfs2_inode_lock(inode, &old_bh, 1);
4241 	if (error) {
4242 		mlog_errno(error);
4243 		ocfs2_rw_unlock(inode, 1);
4244 		goto out;
4245 	}
4246 
4247 	down_write(&OCFS2_I(inode)->ip_xattr_sem);
4248 	down_write(&OCFS2_I(inode)->ip_alloc_sem);
4249 	error = __ocfs2_reflink(old_dentry, old_bh,
4250 				new_orphan_inode, preserve);
4251 	up_write(&OCFS2_I(inode)->ip_alloc_sem);
4252 	up_write(&OCFS2_I(inode)->ip_xattr_sem);
4253 
4254 	ocfs2_inode_unlock(inode, 1);
4255 	ocfs2_rw_unlock(inode, 1);
4256 	brelse(old_bh);
4257 
4258 	if (error) {
4259 		mlog_errno(error);
4260 		goto out;
4261 	}
4262 
4263 	had_lock = ocfs2_inode_lock_tracker(new_orphan_inode, NULL, 1,
4264 					    &oh);
4265 	if (had_lock < 0) {
4266 		error = had_lock;
4267 		mlog_errno(error);
4268 		goto out;
4269 	}
4270 
4271 	/* If the security isn't preserved, we need to re-initialize them. */
4272 	if (!preserve) {
4273 		error = ocfs2_init_security_and_acl(dir, new_orphan_inode,
4274 						    &new_dentry->d_name);
4275 		if (error)
4276 			mlog_errno(error);
4277 	}
4278 	if (!error) {
4279 		error = ocfs2_mv_orphaned_inode_to_new(dir, new_orphan_inode,
4280 						       new_dentry);
4281 		if (error)
4282 			mlog_errno(error);
4283 	}
4284 	ocfs2_inode_unlock_tracker(new_orphan_inode, 1, &oh, had_lock);
4285 
4286 out:
4287 	if (new_orphan_inode) {
4288 		/*
4289 		 * We need to open_unlock the inode no matter whether we
4290 		 * succeed or not, so that other nodes can delete it later.
4291 		 */
4292 		ocfs2_open_unlock(new_orphan_inode);
4293 		if (error)
4294 			iput(new_orphan_inode);
4295 	}
4296 
4297 	return error;
4298 }
4299 
4300 /*
4301  * Below here are the bits used by OCFS2_IOC_REFLINK() to fake
4302  * sys_reflink().  This will go away when vfs_reflink() exists in
4303  * fs/namei.c.
4304  */
4305 
4306 /* copied from may_create in VFS. */
4307 static inline int ocfs2_may_create(struct inode *dir, struct dentry *child)
4308 {
4309 	if (d_really_is_positive(child))
4310 		return -EEXIST;
4311 	if (IS_DEADDIR(dir))
4312 		return -ENOENT;
4313 	return inode_permission(&nop_mnt_idmap, dir, MAY_WRITE | MAY_EXEC);
4314 }
4315 
4316 /**
4317  * ocfs2_vfs_reflink - Create a reference-counted link
4318  *
4319  * @old_dentry:        source dentry + inode
4320  * @dir:       directory to create the target
4321  * @new_dentry:        target dentry
4322  * @preserve:  if true, preserve all file attributes
4323  */
4324 static int ocfs2_vfs_reflink(struct dentry *old_dentry, struct inode *dir,
4325 			     struct dentry *new_dentry, bool preserve)
4326 {
4327 	struct inode *inode = d_inode(old_dentry);
4328 	int error;
4329 
4330 	if (!inode)
4331 		return -ENOENT;
4332 
4333 	error = ocfs2_may_create(dir, new_dentry);
4334 	if (error)
4335 		return error;
4336 
4337 	if (dir->i_sb != inode->i_sb)
4338 		return -EXDEV;
4339 
4340 	/*
4341 	 * A reflink to an append-only or immutable file cannot be created.
4342 	 */
4343 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4344 		return -EPERM;
4345 
4346 	/* Only regular files can be reflinked. */
4347 	if (!S_ISREG(inode->i_mode))
4348 		return -EPERM;
4349 
4350 	/*
4351 	 * If the caller wants to preserve ownership, they require the
4352 	 * rights to do so.
4353 	 */
4354 	if (preserve) {
4355 		if (!uid_eq(current_fsuid(), inode->i_uid) && !capable(CAP_CHOWN))
4356 			return -EPERM;
4357 		if (!in_group_p(inode->i_gid) && !capable(CAP_CHOWN))
4358 			return -EPERM;
4359 	}
4360 
4361 	/*
4362 	 * If the caller is modifying any aspect of the attributes, they
4363 	 * are not creating a snapshot.  They need read permission on the
4364 	 * file.
4365 	 */
4366 	if (!preserve) {
4367 		error = inode_permission(&nop_mnt_idmap, inode, MAY_READ);
4368 		if (error)
4369 			return error;
4370 	}
4371 
4372 	inode_lock(inode);
4373 	error = dquot_initialize(dir);
4374 	if (!error)
4375 		error = ocfs2_reflink(old_dentry, dir, new_dentry, preserve);
4376 	inode_unlock(inode);
4377 	if (!error)
4378 		fsnotify_create(dir, new_dentry);
4379 	return error;
4380 }
4381 /*
4382  * Most codes are copied from sys_linkat.
4383  */
4384 int ocfs2_reflink_ioctl(struct inode *inode,
4385 			const char __user *oldname,
4386 			const char __user *newname,
4387 			bool preserve)
4388 {
4389 	struct dentry *new_dentry;
4390 	struct path old_path, new_path;
4391 	int error;
4392 
4393 	if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb)))
4394 		return -EOPNOTSUPP;
4395 
4396 	error = user_path_at(AT_FDCWD, oldname, 0, &old_path);
4397 	if (error) {
4398 		mlog_errno(error);
4399 		return error;
4400 	}
4401 
4402 	new_dentry = user_path_create(AT_FDCWD, newname, &new_path, 0);
4403 	error = PTR_ERR(new_dentry);
4404 	if (IS_ERR(new_dentry)) {
4405 		mlog_errno(error);
4406 		goto out;
4407 	}
4408 
4409 	error = -EXDEV;
4410 	if (old_path.mnt != new_path.mnt) {
4411 		mlog_errno(error);
4412 		goto out_dput;
4413 	}
4414 
4415 	error = ocfs2_vfs_reflink(old_path.dentry,
4416 				  d_inode(new_path.dentry),
4417 				  new_dentry, preserve);
4418 out_dput:
4419 	done_path_create(&new_path, new_dentry);
4420 out:
4421 	path_put(&old_path);
4422 
4423 	return error;
4424 }
4425 
4426 /* Update destination inode size, if necessary. */
4427 int ocfs2_reflink_update_dest(struct inode *dest,
4428 			      struct buffer_head *d_bh,
4429 			      loff_t newlen)
4430 {
4431 	handle_t *handle;
4432 	int ret;
4433 
4434 	dest->i_blocks = ocfs2_inode_sector_count(dest);
4435 
4436 	if (newlen <= i_size_read(dest))
4437 		return 0;
4438 
4439 	handle = ocfs2_start_trans(OCFS2_SB(dest->i_sb),
4440 				   OCFS2_INODE_UPDATE_CREDITS);
4441 	if (IS_ERR(handle)) {
4442 		ret = PTR_ERR(handle);
4443 		mlog_errno(ret);
4444 		return ret;
4445 	}
4446 
4447 	/* Extend i_size if needed. */
4448 	spin_lock(&OCFS2_I(dest)->ip_lock);
4449 	if (newlen > i_size_read(dest))
4450 		i_size_write(dest, newlen);
4451 	spin_unlock(&OCFS2_I(dest)->ip_lock);
4452 	inode_set_mtime_to_ts(dest, inode_set_ctime_current(dest));
4453 
4454 	ret = ocfs2_mark_inode_dirty(handle, dest, d_bh);
4455 	if (ret) {
4456 		mlog_errno(ret);
4457 		goto out_commit;
4458 	}
4459 
4460 out_commit:
4461 	ocfs2_commit_trans(OCFS2_SB(dest->i_sb), handle);
4462 	return ret;
4463 }
4464 
4465 /* Remap the range pos_in:len in s_inode to pos_out:len in t_inode. */
4466 static loff_t ocfs2_reflink_remap_extent(struct inode *s_inode,
4467 					 struct buffer_head *s_bh,
4468 					 loff_t pos_in,
4469 					 struct inode *t_inode,
4470 					 struct buffer_head *t_bh,
4471 					 loff_t pos_out,
4472 					 loff_t len,
4473 					 struct ocfs2_cached_dealloc_ctxt *dealloc)
4474 {
4475 	struct ocfs2_extent_tree s_et;
4476 	struct ocfs2_extent_tree t_et;
4477 	struct ocfs2_dinode *dis;
4478 	struct buffer_head *ref_root_bh = NULL;
4479 	struct ocfs2_refcount_tree *ref_tree;
4480 	struct ocfs2_super *osb;
4481 	loff_t remapped_bytes = 0;
4482 	loff_t pstart, plen;
4483 	u32 p_cluster, num_clusters, slast, spos, tpos, remapped_clus = 0;
4484 	unsigned int ext_flags;
4485 	int ret = 0;
4486 
4487 	osb = OCFS2_SB(s_inode->i_sb);
4488 	dis = (struct ocfs2_dinode *)s_bh->b_data;
4489 	ocfs2_init_dinode_extent_tree(&s_et, INODE_CACHE(s_inode), s_bh);
4490 	ocfs2_init_dinode_extent_tree(&t_et, INODE_CACHE(t_inode), t_bh);
4491 
4492 	spos = ocfs2_bytes_to_clusters(s_inode->i_sb, pos_in);
4493 	tpos = ocfs2_bytes_to_clusters(t_inode->i_sb, pos_out);
4494 	slast = ocfs2_clusters_for_bytes(s_inode->i_sb, pos_in + len);
4495 
4496 	while (spos < slast) {
4497 		if (fatal_signal_pending(current)) {
4498 			ret = -EINTR;
4499 			goto out;
4500 		}
4501 
4502 		/* Look up the extent. */
4503 		ret = ocfs2_get_clusters(s_inode, spos, &p_cluster,
4504 					 &num_clusters, &ext_flags);
4505 		if (ret) {
4506 			mlog_errno(ret);
4507 			goto out;
4508 		}
4509 
4510 		num_clusters = min_t(u32, num_clusters, slast - spos);
4511 
4512 		/* Punch out the dest range. */
4513 		pstart = ocfs2_clusters_to_bytes(t_inode->i_sb, tpos);
4514 		plen = ocfs2_clusters_to_bytes(t_inode->i_sb, num_clusters);
4515 		ret = ocfs2_remove_inode_range(t_inode, t_bh, pstart, plen);
4516 		if (ret) {
4517 			mlog_errno(ret);
4518 			goto out;
4519 		}
4520 
4521 		if (p_cluster == 0)
4522 			goto next_loop;
4523 
4524 		/* Lock the refcount btree... */
4525 		ret = ocfs2_lock_refcount_tree(osb,
4526 					       le64_to_cpu(dis->i_refcount_loc),
4527 					       1, &ref_tree, &ref_root_bh);
4528 		if (ret) {
4529 			mlog_errno(ret);
4530 			goto out;
4531 		}
4532 
4533 		/* Mark s_inode's extent as refcounted. */
4534 		if (!(ext_flags & OCFS2_EXT_REFCOUNTED)) {
4535 			ret = ocfs2_add_refcount_flag(s_inode, &s_et,
4536 						      &ref_tree->rf_ci,
4537 						      ref_root_bh, spos,
4538 						      p_cluster, num_clusters,
4539 						      dealloc, NULL);
4540 			if (ret) {
4541 				mlog_errno(ret);
4542 				goto out_unlock_refcount;
4543 			}
4544 		}
4545 
4546 		/* Map in the new extent. */
4547 		ext_flags |= OCFS2_EXT_REFCOUNTED;
4548 		ret = ocfs2_add_refcounted_extent(t_inode, &t_et,
4549 						  &ref_tree->rf_ci,
4550 						  ref_root_bh,
4551 						  tpos, p_cluster,
4552 						  num_clusters,
4553 						  ext_flags,
4554 						  dealloc);
4555 		if (ret) {
4556 			mlog_errno(ret);
4557 			goto out_unlock_refcount;
4558 		}
4559 
4560 		ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
4561 		brelse(ref_root_bh);
4562 next_loop:
4563 		spos += num_clusters;
4564 		tpos += num_clusters;
4565 		remapped_clus += num_clusters;
4566 	}
4567 
4568 	goto out;
4569 out_unlock_refcount:
4570 	ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
4571 	brelse(ref_root_bh);
4572 out:
4573 	remapped_bytes = ocfs2_clusters_to_bytes(t_inode->i_sb, remapped_clus);
4574 	remapped_bytes = min_t(loff_t, len, remapped_bytes);
4575 
4576 	return remapped_bytes > 0 ? remapped_bytes : ret;
4577 }
4578 
4579 /* Set up refcount tree and remap s_inode to t_inode. */
4580 loff_t ocfs2_reflink_remap_blocks(struct inode *s_inode,
4581 				  struct buffer_head *s_bh,
4582 				  loff_t pos_in,
4583 				  struct inode *t_inode,
4584 				  struct buffer_head *t_bh,
4585 				  loff_t pos_out,
4586 				  loff_t len)
4587 {
4588 	struct ocfs2_cached_dealloc_ctxt dealloc;
4589 	struct ocfs2_super *osb;
4590 	struct ocfs2_dinode *dis;
4591 	struct ocfs2_dinode *dit;
4592 	loff_t ret;
4593 
4594 	osb = OCFS2_SB(s_inode->i_sb);
4595 	dis = (struct ocfs2_dinode *)s_bh->b_data;
4596 	dit = (struct ocfs2_dinode *)t_bh->b_data;
4597 	ocfs2_init_dealloc_ctxt(&dealloc);
4598 
4599 	/*
4600 	 * If we're reflinking the entire file and the source is inline
4601 	 * data, just copy the contents.
4602 	 */
4603 	if (pos_in == pos_out && pos_in == 0 && len == i_size_read(s_inode) &&
4604 	    i_size_read(t_inode) <= len &&
4605 	    (OCFS2_I(s_inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)) {
4606 		ret = ocfs2_duplicate_inline_data(s_inode, s_bh, t_inode, t_bh);
4607 		if (ret)
4608 			mlog_errno(ret);
4609 		goto out;
4610 	}
4611 
4612 	/*
4613 	 * If both inodes belong to two different refcount groups then
4614 	 * forget it because we don't know how (or want) to go merging
4615 	 * refcount trees.
4616 	 */
4617 	ret = -EOPNOTSUPP;
4618 	if (ocfs2_is_refcount_inode(s_inode) &&
4619 	    ocfs2_is_refcount_inode(t_inode) &&
4620 	    le64_to_cpu(dis->i_refcount_loc) !=
4621 	    le64_to_cpu(dit->i_refcount_loc))
4622 		goto out;
4623 
4624 	/* Neither inode has a refcount tree.  Add one to s_inode. */
4625 	if (!ocfs2_is_refcount_inode(s_inode) &&
4626 	    !ocfs2_is_refcount_inode(t_inode)) {
4627 		ret = ocfs2_create_refcount_tree(s_inode, s_bh);
4628 		if (ret) {
4629 			mlog_errno(ret);
4630 			goto out;
4631 		}
4632 	}
4633 
4634 	/* Ensure that both inodes end up with the same refcount tree. */
4635 	if (!ocfs2_is_refcount_inode(s_inode)) {
4636 		ret = ocfs2_set_refcount_tree(s_inode, s_bh,
4637 					      le64_to_cpu(dit->i_refcount_loc));
4638 		if (ret) {
4639 			mlog_errno(ret);
4640 			goto out;
4641 		}
4642 	}
4643 	if (!ocfs2_is_refcount_inode(t_inode)) {
4644 		ret = ocfs2_set_refcount_tree(t_inode, t_bh,
4645 					      le64_to_cpu(dis->i_refcount_loc));
4646 		if (ret) {
4647 			mlog_errno(ret);
4648 			goto out;
4649 		}
4650 	}
4651 
4652 	/* Turn off inline data in the dest file. */
4653 	if (OCFS2_I(t_inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
4654 		ret = ocfs2_convert_inline_data_to_extents(t_inode, t_bh);
4655 		if (ret) {
4656 			mlog_errno(ret);
4657 			goto out;
4658 		}
4659 	}
4660 
4661 	/* Actually remap extents now. */
4662 	ret = ocfs2_reflink_remap_extent(s_inode, s_bh, pos_in, t_inode, t_bh,
4663 					 pos_out, len, &dealloc);
4664 	if (ret < 0) {
4665 		mlog_errno(ret);
4666 		goto out;
4667 	}
4668 
4669 out:
4670 	if (ocfs2_dealloc_has_cluster(&dealloc)) {
4671 		ocfs2_schedule_truncate_log_flush(osb, 1);
4672 		ocfs2_run_deallocs(osb, &dealloc);
4673 	}
4674 
4675 	return ret;
4676 }
4677 
4678 /* Lock an inode and grab a bh pointing to the inode. */
4679 int ocfs2_reflink_inodes_lock(struct inode *s_inode,
4680 			      struct buffer_head **bh_s,
4681 			      struct inode *t_inode,
4682 			      struct buffer_head **bh_t)
4683 {
4684 	struct inode *inode1 = s_inode;
4685 	struct inode *inode2 = t_inode;
4686 	struct ocfs2_inode_info *oi1;
4687 	struct ocfs2_inode_info *oi2;
4688 	struct buffer_head *bh1 = NULL;
4689 	struct buffer_head *bh2 = NULL;
4690 	bool same_inode = (s_inode == t_inode);
4691 	bool need_swap = (inode1->i_ino > inode2->i_ino);
4692 	int status;
4693 
4694 	/* First grab the VFS and rw locks. */
4695 	lock_two_nondirectories(s_inode, t_inode);
4696 	if (need_swap)
4697 		swap(inode1, inode2);
4698 
4699 	status = ocfs2_rw_lock(inode1, 1);
4700 	if (status) {
4701 		mlog_errno(status);
4702 		goto out_i1;
4703 	}
4704 	if (!same_inode) {
4705 		status = ocfs2_rw_lock(inode2, 1);
4706 		if (status) {
4707 			mlog_errno(status);
4708 			goto out_i2;
4709 		}
4710 	}
4711 
4712 	/* Now go for the cluster locks */
4713 	oi1 = OCFS2_I(inode1);
4714 	oi2 = OCFS2_I(inode2);
4715 
4716 	trace_ocfs2_double_lock((unsigned long long)oi1->ip_blkno,
4717 				(unsigned long long)oi2->ip_blkno);
4718 
4719 	/* We always want to lock the one with the lower lockid first. */
4720 	if (oi1->ip_blkno > oi2->ip_blkno)
4721 		mlog_errno(-ENOLCK);
4722 
4723 	/* lock id1 */
4724 	status = ocfs2_inode_lock_nested(inode1, &bh1, 1,
4725 					 OI_LS_REFLINK_TARGET);
4726 	if (status < 0) {
4727 		if (status != -ENOENT)
4728 			mlog_errno(status);
4729 		goto out_rw2;
4730 	}
4731 
4732 	/* lock id2 */
4733 	if (!same_inode) {
4734 		status = ocfs2_inode_lock_nested(inode2, &bh2, 1,
4735 						 OI_LS_REFLINK_TARGET);
4736 		if (status < 0) {
4737 			if (status != -ENOENT)
4738 				mlog_errno(status);
4739 			goto out_cl1;
4740 		}
4741 	} else {
4742 		bh2 = bh1;
4743 	}
4744 
4745 	/*
4746 	 * If we swapped inode order above, we have to swap the buffer heads
4747 	 * before passing them back to the caller.
4748 	 */
4749 	if (need_swap)
4750 		swap(bh1, bh2);
4751 	*bh_s = bh1;
4752 	*bh_t = bh2;
4753 
4754 	trace_ocfs2_double_lock_end(
4755 			(unsigned long long)oi1->ip_blkno,
4756 			(unsigned long long)oi2->ip_blkno);
4757 
4758 	return 0;
4759 
4760 out_cl1:
4761 	ocfs2_inode_unlock(inode1, 1);
4762 	brelse(bh1);
4763 out_rw2:
4764 	ocfs2_rw_unlock(inode2, 1);
4765 out_i2:
4766 	ocfs2_rw_unlock(inode1, 1);
4767 out_i1:
4768 	unlock_two_nondirectories(s_inode, t_inode);
4769 	return status;
4770 }
4771 
4772 /* Unlock both inodes and release buffers. */
4773 void ocfs2_reflink_inodes_unlock(struct inode *s_inode,
4774 				 struct buffer_head *s_bh,
4775 				 struct inode *t_inode,
4776 				 struct buffer_head *t_bh)
4777 {
4778 	ocfs2_inode_unlock(s_inode, 1);
4779 	ocfs2_rw_unlock(s_inode, 1);
4780 	brelse(s_bh);
4781 	if (s_inode != t_inode) {
4782 		ocfs2_inode_unlock(t_inode, 1);
4783 		ocfs2_rw_unlock(t_inode, 1);
4784 		brelse(t_bh);
4785 	}
4786 	unlock_two_nondirectories(s_inode, t_inode);
4787 }
4788