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