ocfs2: CoW refcount tree improvement.
[safe/jmp/linux-2.6] / fs / ocfs2 / refcounttree.c
1 /* -*- mode: c; c-basic-offset: 8; -*-
2  * vim: noexpandtab sw=8 ts=8 sts=0:
3  *
4  * refcounttree.c
5  *
6  * Copyright (C) 2009 Oracle.  All rights reserved.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public
10  * License version 2 as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  */
17
18 #include <linux/sort.h>
19 #define MLOG_MASK_PREFIX ML_REFCOUNT
20 #include <cluster/masklog.h>
21 #include "ocfs2.h"
22 #include "inode.h"
23 #include "alloc.h"
24 #include "suballoc.h"
25 #include "journal.h"
26 #include "uptodate.h"
27 #include "super.h"
28 #include "buffer_head_io.h"
29 #include "blockcheck.h"
30 #include "refcounttree.h"
31 #include "sysfile.h"
32 #include "dlmglue.h"
33 #include "extent_map.h"
34 #include "aops.h"
35
36 #include <linux/bio.h>
37 #include <linux/blkdev.h>
38 #include <linux/gfp.h>
39 #include <linux/slab.h>
40 #include <linux/writeback.h>
41 #include <linux/pagevec.h>
42 #include <linux/swap.h>
43
44 struct ocfs2_cow_context {
45         struct inode *inode;
46         u32 cow_start;
47         u32 cow_len;
48         struct ocfs2_extent_tree di_et;
49         struct ocfs2_caching_info *ref_ci;
50         struct buffer_head *ref_root_bh;
51         struct ocfs2_alloc_context *meta_ac;
52         struct ocfs2_alloc_context *data_ac;
53         struct ocfs2_cached_dealloc_ctxt dealloc;
54 };
55
56 static inline struct ocfs2_refcount_tree *
57 cache_info_to_refcount(struct ocfs2_caching_info *ci)
58 {
59         return container_of(ci, struct ocfs2_refcount_tree, rf_ci);
60 }
61
62 static int ocfs2_validate_refcount_block(struct super_block *sb,
63                                          struct buffer_head *bh)
64 {
65         int rc;
66         struct ocfs2_refcount_block *rb =
67                 (struct ocfs2_refcount_block *)bh->b_data;
68
69         mlog(0, "Validating refcount block %llu\n",
70              (unsigned long long)bh->b_blocknr);
71
72         BUG_ON(!buffer_uptodate(bh));
73
74         /*
75          * If the ecc fails, we return the error but otherwise
76          * leave the filesystem running.  We know any error is
77          * local to this block.
78          */
79         rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &rb->rf_check);
80         if (rc) {
81                 mlog(ML_ERROR, "Checksum failed for refcount block %llu\n",
82                      (unsigned long long)bh->b_blocknr);
83                 return rc;
84         }
85
86
87         if (!OCFS2_IS_VALID_REFCOUNT_BLOCK(rb)) {
88                 ocfs2_error(sb,
89                             "Refcount block #%llu has bad signature %.*s",
90                             (unsigned long long)bh->b_blocknr, 7,
91                             rb->rf_signature);
92                 return -EINVAL;
93         }
94
95         if (le64_to_cpu(rb->rf_blkno) != bh->b_blocknr) {
96                 ocfs2_error(sb,
97                             "Refcount block #%llu has an invalid rf_blkno "
98                             "of %llu",
99                             (unsigned long long)bh->b_blocknr,
100                             (unsigned long long)le64_to_cpu(rb->rf_blkno));
101                 return -EINVAL;
102         }
103
104         if (le32_to_cpu(rb->rf_fs_generation) != OCFS2_SB(sb)->fs_generation) {
105                 ocfs2_error(sb,
106                             "Refcount block #%llu has an invalid "
107                             "rf_fs_generation of #%u",
108                             (unsigned long long)bh->b_blocknr,
109                             le32_to_cpu(rb->rf_fs_generation));
110                 return -EINVAL;
111         }
112
113         return 0;
114 }
115
116 static int ocfs2_read_refcount_block(struct ocfs2_caching_info *ci,
117                                      u64 rb_blkno,
118                                      struct buffer_head **bh)
119 {
120         int rc;
121         struct buffer_head *tmp = *bh;
122
123         rc = ocfs2_read_block(ci, rb_blkno, &tmp,
124                               ocfs2_validate_refcount_block);
125
126         /* If ocfs2_read_block() got us a new bh, pass it up. */
127         if (!rc && !*bh)
128                 *bh = tmp;
129
130         return rc;
131 }
132
133 static u64 ocfs2_refcount_cache_owner(struct ocfs2_caching_info *ci)
134 {
135         struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
136
137         return rf->rf_blkno;
138 }
139
140 static struct super_block *
141 ocfs2_refcount_cache_get_super(struct ocfs2_caching_info *ci)
142 {
143         struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
144
145         return rf->rf_sb;
146 }
147
148 static void ocfs2_refcount_cache_lock(struct ocfs2_caching_info *ci)
149 {
150         struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
151
152         spin_lock(&rf->rf_lock);
153 }
154
155 static void ocfs2_refcount_cache_unlock(struct ocfs2_caching_info *ci)
156 {
157         struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
158
159         spin_unlock(&rf->rf_lock);
160 }
161
162 static void ocfs2_refcount_cache_io_lock(struct ocfs2_caching_info *ci)
163 {
164         struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
165
166         mutex_lock(&rf->rf_io_mutex);
167 }
168
169 static void ocfs2_refcount_cache_io_unlock(struct ocfs2_caching_info *ci)
170 {
171         struct ocfs2_refcount_tree *rf = cache_info_to_refcount(ci);
172
173         mutex_unlock(&rf->rf_io_mutex);
174 }
175
176 static const struct ocfs2_caching_operations ocfs2_refcount_caching_ops = {
177         .co_owner               = ocfs2_refcount_cache_owner,
178         .co_get_super           = ocfs2_refcount_cache_get_super,
179         .co_cache_lock          = ocfs2_refcount_cache_lock,
180         .co_cache_unlock        = ocfs2_refcount_cache_unlock,
181         .co_io_lock             = ocfs2_refcount_cache_io_lock,
182         .co_io_unlock           = ocfs2_refcount_cache_io_unlock,
183 };
184
185 static struct ocfs2_refcount_tree *
186 ocfs2_find_refcount_tree(struct ocfs2_super *osb, u64 blkno)
187 {
188         struct rb_node *n = osb->osb_rf_lock_tree.rb_node;
189         struct ocfs2_refcount_tree *tree = NULL;
190
191         while (n) {
192                 tree = rb_entry(n, struct ocfs2_refcount_tree, rf_node);
193
194                 if (blkno < tree->rf_blkno)
195                         n = n->rb_left;
196                 else if (blkno > tree->rf_blkno)
197                         n = n->rb_right;
198                 else
199                         return tree;
200         }
201
202         return NULL;
203 }
204
205 /* osb_lock is already locked. */
206 static void ocfs2_insert_refcount_tree(struct ocfs2_super *osb,
207                                        struct ocfs2_refcount_tree *new)
208 {
209         u64 rf_blkno = new->rf_blkno;
210         struct rb_node *parent = NULL;
211         struct rb_node **p = &osb->osb_rf_lock_tree.rb_node;
212         struct ocfs2_refcount_tree *tmp;
213
214         while (*p) {
215                 parent = *p;
216
217                 tmp = rb_entry(parent, struct ocfs2_refcount_tree,
218                                rf_node);
219
220                 if (rf_blkno < tmp->rf_blkno)
221                         p = &(*p)->rb_left;
222                 else if (rf_blkno > tmp->rf_blkno)
223                         p = &(*p)->rb_right;
224                 else {
225                         /* This should never happen! */
226                         mlog(ML_ERROR, "Duplicate refcount block %llu found!\n",
227                              (unsigned long long)rf_blkno);
228                         BUG();
229                 }
230         }
231
232         rb_link_node(&new->rf_node, parent, p);
233         rb_insert_color(&new->rf_node, &osb->osb_rf_lock_tree);
234 }
235
236 static void ocfs2_free_refcount_tree(struct ocfs2_refcount_tree *tree)
237 {
238         ocfs2_metadata_cache_exit(&tree->rf_ci);
239         ocfs2_simple_drop_lockres(OCFS2_SB(tree->rf_sb), &tree->rf_lockres);
240         ocfs2_lock_res_free(&tree->rf_lockres);
241         kfree(tree);
242 }
243
244 static inline void
245 ocfs2_erase_refcount_tree_from_list_no_lock(struct ocfs2_super *osb,
246                                         struct ocfs2_refcount_tree *tree)
247 {
248         rb_erase(&tree->rf_node, &osb->osb_rf_lock_tree);
249         if (osb->osb_ref_tree_lru && osb->osb_ref_tree_lru == tree)
250                 osb->osb_ref_tree_lru = NULL;
251 }
252
253 static void ocfs2_erase_refcount_tree_from_list(struct ocfs2_super *osb,
254                                         struct ocfs2_refcount_tree *tree)
255 {
256         spin_lock(&osb->osb_lock);
257         ocfs2_erase_refcount_tree_from_list_no_lock(osb, tree);
258         spin_unlock(&osb->osb_lock);
259 }
260
261 void ocfs2_kref_remove_refcount_tree(struct kref *kref)
262 {
263         struct ocfs2_refcount_tree *tree =
264                 container_of(kref, struct ocfs2_refcount_tree, rf_getcnt);
265
266         ocfs2_free_refcount_tree(tree);
267 }
268
269 static inline void
270 ocfs2_refcount_tree_get(struct ocfs2_refcount_tree *tree)
271 {
272         kref_get(&tree->rf_getcnt);
273 }
274
275 static inline void
276 ocfs2_refcount_tree_put(struct ocfs2_refcount_tree *tree)
277 {
278         kref_put(&tree->rf_getcnt, ocfs2_kref_remove_refcount_tree);
279 }
280
281 static inline void ocfs2_init_refcount_tree_ci(struct ocfs2_refcount_tree *new,
282                                                struct super_block *sb)
283 {
284         ocfs2_metadata_cache_init(&new->rf_ci, &ocfs2_refcount_caching_ops);
285         mutex_init(&new->rf_io_mutex);
286         new->rf_sb = sb;
287         spin_lock_init(&new->rf_lock);
288 }
289
290 static inline void ocfs2_init_refcount_tree_lock(struct ocfs2_super *osb,
291                                         struct ocfs2_refcount_tree *new,
292                                         u64 rf_blkno, u32 generation)
293 {
294         init_rwsem(&new->rf_sem);
295         ocfs2_refcount_lock_res_init(&new->rf_lockres, osb,
296                                      rf_blkno, generation);
297 }
298
299 static struct ocfs2_refcount_tree*
300 ocfs2_allocate_refcount_tree(struct ocfs2_super *osb, u64 rf_blkno)
301 {
302         struct ocfs2_refcount_tree *new;
303
304         new = kzalloc(sizeof(struct ocfs2_refcount_tree), GFP_NOFS);
305         if (!new)
306                 return NULL;
307
308         new->rf_blkno = rf_blkno;
309         kref_init(&new->rf_getcnt);
310         ocfs2_init_refcount_tree_ci(new, osb->sb);
311
312         return new;
313 }
314
315 static int ocfs2_get_refcount_tree(struct ocfs2_super *osb, u64 rf_blkno,
316                                    struct ocfs2_refcount_tree **ret_tree)
317 {
318         int ret = 0;
319         struct ocfs2_refcount_tree *tree, *new = NULL;
320         struct buffer_head *ref_root_bh = NULL;
321         struct ocfs2_refcount_block *ref_rb;
322
323         spin_lock(&osb->osb_lock);
324         if (osb->osb_ref_tree_lru &&
325             osb->osb_ref_tree_lru->rf_blkno == rf_blkno)
326                 tree = osb->osb_ref_tree_lru;
327         else
328                 tree = ocfs2_find_refcount_tree(osb, rf_blkno);
329         if (tree)
330                 goto out;
331
332         spin_unlock(&osb->osb_lock);
333
334         new = ocfs2_allocate_refcount_tree(osb, rf_blkno);
335         if (!new) {
336                 ret = -ENOMEM;
337                 mlog_errno(ret);
338                 return ret;
339         }
340         /*
341          * We need the generation to create the refcount tree lock and since
342          * it isn't changed during the tree modification, we are safe here to
343          * read without protection.
344          * We also have to purge the cache after we create the lock since the
345          * refcount block may have the stale data. It can only be trusted when
346          * we hold the refcount lock.
347          */
348         ret = ocfs2_read_refcount_block(&new->rf_ci, rf_blkno, &ref_root_bh);
349         if (ret) {
350                 mlog_errno(ret);
351                 ocfs2_metadata_cache_exit(&new->rf_ci);
352                 kfree(new);
353                 return ret;
354         }
355
356         ref_rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
357         new->rf_generation = le32_to_cpu(ref_rb->rf_generation);
358         ocfs2_init_refcount_tree_lock(osb, new, rf_blkno,
359                                       new->rf_generation);
360         ocfs2_metadata_cache_purge(&new->rf_ci);
361
362         spin_lock(&osb->osb_lock);
363         tree = ocfs2_find_refcount_tree(osb, rf_blkno);
364         if (tree)
365                 goto out;
366
367         ocfs2_insert_refcount_tree(osb, new);
368
369         tree = new;
370         new = NULL;
371
372 out:
373         *ret_tree = tree;
374
375         osb->osb_ref_tree_lru = tree;
376
377         spin_unlock(&osb->osb_lock);
378
379         if (new)
380                 ocfs2_free_refcount_tree(new);
381
382         brelse(ref_root_bh);
383         return ret;
384 }
385
386 static int ocfs2_get_refcount_block(struct inode *inode, u64 *ref_blkno)
387 {
388         int ret;
389         struct buffer_head *di_bh = NULL;
390         struct ocfs2_dinode *di;
391
392         ret = ocfs2_read_inode_block(inode, &di_bh);
393         if (ret) {
394                 mlog_errno(ret);
395                 goto out;
396         }
397
398         BUG_ON(!(OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
399
400         di = (struct ocfs2_dinode *)di_bh->b_data;
401         *ref_blkno = le64_to_cpu(di->i_refcount_loc);
402         brelse(di_bh);
403 out:
404         return ret;
405 }
406
407 static int __ocfs2_lock_refcount_tree(struct ocfs2_super *osb,
408                                       struct ocfs2_refcount_tree *tree, int rw)
409 {
410         int ret;
411
412         ret = ocfs2_refcount_lock(tree, rw);
413         if (ret) {
414                 mlog_errno(ret);
415                 goto out;
416         }
417
418         if (rw)
419                 down_write(&tree->rf_sem);
420         else
421                 down_read(&tree->rf_sem);
422
423 out:
424         return ret;
425 }
426
427 /*
428  * Lock the refcount tree pointed by ref_blkno and return the tree.
429  * In most case, we lock the tree and read the refcount block.
430  * So read it here if the caller really needs it.
431  *
432  * If the tree has been re-created by other node, it will free the
433  * old one and re-create it.
434  */
435 int ocfs2_lock_refcount_tree(struct ocfs2_super *osb,
436                              u64 ref_blkno, int rw,
437                              struct ocfs2_refcount_tree **ret_tree,
438                              struct buffer_head **ref_bh)
439 {
440         int ret, delete_tree = 0;
441         struct ocfs2_refcount_tree *tree = NULL;
442         struct buffer_head *ref_root_bh = NULL;
443         struct ocfs2_refcount_block *rb;
444
445 again:
446         ret = ocfs2_get_refcount_tree(osb, ref_blkno, &tree);
447         if (ret) {
448                 mlog_errno(ret);
449                 return ret;
450         }
451
452         ocfs2_refcount_tree_get(tree);
453
454         ret = __ocfs2_lock_refcount_tree(osb, tree, rw);
455         if (ret) {
456                 mlog_errno(ret);
457                 ocfs2_refcount_tree_put(tree);
458                 goto out;
459         }
460
461         ret = ocfs2_read_refcount_block(&tree->rf_ci, tree->rf_blkno,
462                                         &ref_root_bh);
463         if (ret) {
464                 mlog_errno(ret);
465                 ocfs2_unlock_refcount_tree(osb, tree, rw);
466                 ocfs2_refcount_tree_put(tree);
467                 goto out;
468         }
469
470         rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
471         /*
472          * If the refcount block has been freed and re-created, we may need
473          * to recreate the refcount tree also.
474          *
475          * Here we just remove the tree from the rb-tree, and the last
476          * kref holder will unlock and delete this refcount_tree.
477          * Then we goto "again" and ocfs2_get_refcount_tree will create
478          * the new refcount tree for us.
479          */
480         if (tree->rf_generation != le32_to_cpu(rb->rf_generation)) {
481                 if (!tree->rf_removed) {
482                         ocfs2_erase_refcount_tree_from_list(osb, tree);
483                         tree->rf_removed = 1;
484                         delete_tree = 1;
485                 }
486
487                 ocfs2_unlock_refcount_tree(osb, tree, rw);
488                 /*
489                  * We get an extra reference when we create the refcount
490                  * tree, so another put will destroy it.
491                  */
492                 if (delete_tree)
493                         ocfs2_refcount_tree_put(tree);
494                 brelse(ref_root_bh);
495                 ref_root_bh = NULL;
496                 goto again;
497         }
498
499         *ret_tree = tree;
500         if (ref_bh) {
501                 *ref_bh = ref_root_bh;
502                 ref_root_bh = NULL;
503         }
504 out:
505         brelse(ref_root_bh);
506         return ret;
507 }
508
509 int ocfs2_lock_refcount_tree_by_inode(struct inode *inode, int rw,
510                                       struct ocfs2_refcount_tree **ret_tree,
511                                       struct buffer_head **ref_bh)
512 {
513         int ret;
514         u64 ref_blkno;
515
516         ret = ocfs2_get_refcount_block(inode, &ref_blkno);
517         if (ret) {
518                 mlog_errno(ret);
519                 return ret;
520         }
521
522         return ocfs2_lock_refcount_tree(OCFS2_SB(inode->i_sb), ref_blkno,
523                                         rw, ret_tree, ref_bh);
524 }
525
526 void ocfs2_unlock_refcount_tree(struct ocfs2_super *osb,
527                                 struct ocfs2_refcount_tree *tree, int rw)
528 {
529         if (rw)
530                 up_write(&tree->rf_sem);
531         else
532                 up_read(&tree->rf_sem);
533
534         ocfs2_refcount_unlock(tree, rw);
535         ocfs2_refcount_tree_put(tree);
536 }
537
538 void ocfs2_purge_refcount_trees(struct ocfs2_super *osb)
539 {
540         struct rb_node *node;
541         struct ocfs2_refcount_tree *tree;
542         struct rb_root *root = &osb->osb_rf_lock_tree;
543
544         while ((node = rb_last(root)) != NULL) {
545                 tree = rb_entry(node, struct ocfs2_refcount_tree, rf_node);
546
547                 mlog(0, "Purge tree %llu\n",
548                      (unsigned long long) tree->rf_blkno);
549
550                 rb_erase(&tree->rf_node, root);
551                 ocfs2_free_refcount_tree(tree);
552         }
553 }
554
555 /*
556  * Create a refcount tree for an inode.
557  * We take for granted that the inode is already locked.
558  */
559 static int ocfs2_create_refcount_tree(struct inode *inode,
560                                       struct buffer_head *di_bh)
561 {
562         int ret;
563         handle_t *handle = NULL;
564         struct ocfs2_alloc_context *meta_ac = NULL;
565         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
566         struct ocfs2_inode_info *oi = OCFS2_I(inode);
567         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
568         struct buffer_head *new_bh = NULL;
569         struct ocfs2_refcount_block *rb;
570         struct ocfs2_refcount_tree *new_tree = NULL, *tree = NULL;
571         u16 suballoc_bit_start;
572         u32 num_got;
573         u64 first_blkno;
574
575         BUG_ON(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL);
576
577         mlog(0, "create tree for inode %lu\n", inode->i_ino);
578
579         ret = ocfs2_reserve_new_metadata_blocks(osb, 1, &meta_ac);
580         if (ret) {
581                 mlog_errno(ret);
582                 goto out;
583         }
584
585         handle = ocfs2_start_trans(osb, OCFS2_REFCOUNT_TREE_CREATE_CREDITS);
586         if (IS_ERR(handle)) {
587                 ret = PTR_ERR(handle);
588                 mlog_errno(ret);
589                 goto out;
590         }
591
592         ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
593                                       OCFS2_JOURNAL_ACCESS_WRITE);
594         if (ret) {
595                 mlog_errno(ret);
596                 goto out_commit;
597         }
598
599         ret = ocfs2_claim_metadata(osb, handle, meta_ac, 1,
600                                    &suballoc_bit_start, &num_got,
601                                    &first_blkno);
602         if (ret) {
603                 mlog_errno(ret);
604                 goto out_commit;
605         }
606
607         new_tree = ocfs2_allocate_refcount_tree(osb, first_blkno);
608         if (!new_tree) {
609                 ret = -ENOMEM;
610                 mlog_errno(ret);
611                 goto out_commit;
612         }
613
614         new_bh = sb_getblk(inode->i_sb, first_blkno);
615         ocfs2_set_new_buffer_uptodate(&new_tree->rf_ci, new_bh);
616
617         ret = ocfs2_journal_access_rb(handle, &new_tree->rf_ci, new_bh,
618                                       OCFS2_JOURNAL_ACCESS_CREATE);
619         if (ret) {
620                 mlog_errno(ret);
621                 goto out_commit;
622         }
623
624         /* Initialize ocfs2_refcount_block. */
625         rb = (struct ocfs2_refcount_block *)new_bh->b_data;
626         memset(rb, 0, inode->i_sb->s_blocksize);
627         strcpy((void *)rb, OCFS2_REFCOUNT_BLOCK_SIGNATURE);
628         rb->rf_suballoc_slot = cpu_to_le16(osb->slot_num);
629         rb->rf_suballoc_bit = cpu_to_le16(suballoc_bit_start);
630         rb->rf_fs_generation = cpu_to_le32(osb->fs_generation);
631         rb->rf_blkno = cpu_to_le64(first_blkno);
632         rb->rf_count = cpu_to_le32(1);
633         rb->rf_records.rl_count =
634                         cpu_to_le16(ocfs2_refcount_recs_per_rb(osb->sb));
635         spin_lock(&osb->osb_lock);
636         rb->rf_generation = osb->s_next_generation++;
637         spin_unlock(&osb->osb_lock);
638
639         ocfs2_journal_dirty(handle, new_bh);
640
641         spin_lock(&oi->ip_lock);
642         oi->ip_dyn_features |= OCFS2_HAS_REFCOUNT_FL;
643         di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
644         di->i_refcount_loc = cpu_to_le64(first_blkno);
645         spin_unlock(&oi->ip_lock);
646
647         mlog(0, "created tree for inode %lu, refblock %llu\n",
648              inode->i_ino, (unsigned long long)first_blkno);
649
650         ocfs2_journal_dirty(handle, di_bh);
651
652         /*
653          * We have to init the tree lock here since it will use
654          * the generation number to create it.
655          */
656         new_tree->rf_generation = le32_to_cpu(rb->rf_generation);
657         ocfs2_init_refcount_tree_lock(osb, new_tree, first_blkno,
658                                       new_tree->rf_generation);
659
660         spin_lock(&osb->osb_lock);
661         tree = ocfs2_find_refcount_tree(osb, first_blkno);
662
663         /*
664          * We've just created a new refcount tree in this block.  If
665          * we found a refcount tree on the ocfs2_super, it must be
666          * one we just deleted.  We free the old tree before
667          * inserting the new tree.
668          */
669         BUG_ON(tree && tree->rf_generation == new_tree->rf_generation);
670         if (tree)
671                 ocfs2_erase_refcount_tree_from_list_no_lock(osb, tree);
672         ocfs2_insert_refcount_tree(osb, new_tree);
673         spin_unlock(&osb->osb_lock);
674         new_tree = NULL;
675         if (tree)
676                 ocfs2_refcount_tree_put(tree);
677
678 out_commit:
679         ocfs2_commit_trans(osb, handle);
680
681 out:
682         if (new_tree) {
683                 ocfs2_metadata_cache_exit(&new_tree->rf_ci);
684                 kfree(new_tree);
685         }
686
687         brelse(new_bh);
688         if (meta_ac)
689                 ocfs2_free_alloc_context(meta_ac);
690
691         return ret;
692 }
693
694 static int ocfs2_set_refcount_tree(struct inode *inode,
695                                    struct buffer_head *di_bh,
696                                    u64 refcount_loc)
697 {
698         int ret;
699         handle_t *handle = NULL;
700         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
701         struct ocfs2_inode_info *oi = OCFS2_I(inode);
702         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
703         struct buffer_head *ref_root_bh = NULL;
704         struct ocfs2_refcount_block *rb;
705         struct ocfs2_refcount_tree *ref_tree;
706
707         BUG_ON(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL);
708
709         ret = ocfs2_lock_refcount_tree(osb, refcount_loc, 1,
710                                        &ref_tree, &ref_root_bh);
711         if (ret) {
712                 mlog_errno(ret);
713                 return ret;
714         }
715
716         handle = ocfs2_start_trans(osb, OCFS2_REFCOUNT_TREE_SET_CREDITS);
717         if (IS_ERR(handle)) {
718                 ret = PTR_ERR(handle);
719                 mlog_errno(ret);
720                 goto out;
721         }
722
723         ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
724                                       OCFS2_JOURNAL_ACCESS_WRITE);
725         if (ret) {
726                 mlog_errno(ret);
727                 goto out_commit;
728         }
729
730         ret = ocfs2_journal_access_rb(handle, &ref_tree->rf_ci, ref_root_bh,
731                                       OCFS2_JOURNAL_ACCESS_WRITE);
732         if (ret) {
733                 mlog_errno(ret);
734                 goto out_commit;
735         }
736
737         rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
738         le32_add_cpu(&rb->rf_count, 1);
739
740         ocfs2_journal_dirty(handle, ref_root_bh);
741
742         spin_lock(&oi->ip_lock);
743         oi->ip_dyn_features |= OCFS2_HAS_REFCOUNT_FL;
744         di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
745         di->i_refcount_loc = cpu_to_le64(refcount_loc);
746         spin_unlock(&oi->ip_lock);
747         ocfs2_journal_dirty(handle, di_bh);
748
749 out_commit:
750         ocfs2_commit_trans(osb, handle);
751 out:
752         ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
753         brelse(ref_root_bh);
754
755         return ret;
756 }
757
758 int ocfs2_remove_refcount_tree(struct inode *inode, struct buffer_head *di_bh)
759 {
760         int ret, delete_tree = 0;
761         handle_t *handle = NULL;
762         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
763         struct ocfs2_inode_info *oi = OCFS2_I(inode);
764         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
765         struct ocfs2_refcount_block *rb;
766         struct inode *alloc_inode = NULL;
767         struct buffer_head *alloc_bh = NULL;
768         struct buffer_head *blk_bh = NULL;
769         struct ocfs2_refcount_tree *ref_tree;
770         int credits = OCFS2_REFCOUNT_TREE_REMOVE_CREDITS;
771         u64 blk = 0, bg_blkno = 0, ref_blkno = le64_to_cpu(di->i_refcount_loc);
772         u16 bit = 0;
773
774         if (!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL))
775                 return 0;
776
777         BUG_ON(!ref_blkno);
778         ret = ocfs2_lock_refcount_tree(osb, ref_blkno, 1, &ref_tree, &blk_bh);
779         if (ret) {
780                 mlog_errno(ret);
781                 return ret;
782         }
783
784         rb = (struct ocfs2_refcount_block *)blk_bh->b_data;
785
786         /*
787          * If we are the last user, we need to free the block.
788          * So lock the allocator ahead.
789          */
790         if (le32_to_cpu(rb->rf_count) == 1) {
791                 blk = le64_to_cpu(rb->rf_blkno);
792                 bit = le16_to_cpu(rb->rf_suballoc_bit);
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                 mutex_lock(&alloc_inode->i_mutex);
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                 mutex_unlock(&alloc_inode->i_mutex);
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  * Given a cpos and len, try to find the refcount record which contains cpos.
919  * 1. If cpos can be found in one refcount record, return the record.
920  * 2. If cpos can't be found, return a fake record which start from cpos
921  *    and end at a small value between cpos+len and start of the next record.
922  *    This fake record has r_refcount = 0.
923  */
924 static int ocfs2_get_refcount_rec(struct ocfs2_caching_info *ci,
925                                   struct buffer_head *ref_root_bh,
926                                   u64 cpos, unsigned int len,
927                                   struct ocfs2_refcount_rec *ret_rec,
928                                   int *index,
929                                   struct buffer_head **ret_bh)
930 {
931         int ret = 0, i, found;
932         u32 low_cpos;
933         struct ocfs2_extent_list *el;
934         struct ocfs2_extent_rec *tmp, *rec = NULL;
935         struct ocfs2_extent_block *eb;
936         struct buffer_head *eb_bh = NULL, *ref_leaf_bh = NULL;
937         struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
938         struct ocfs2_refcount_block *rb =
939                         (struct ocfs2_refcount_block *)ref_root_bh->b_data;
940
941         if (!(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL)) {
942                 ocfs2_find_refcount_rec_in_rl(ci, ref_root_bh, cpos, len,
943                                               ret_rec, index);
944                 *ret_bh = ref_root_bh;
945                 get_bh(ref_root_bh);
946                 return 0;
947         }
948
949         el = &rb->rf_list;
950         low_cpos = cpos & OCFS2_32BIT_POS_MASK;
951
952         if (el->l_tree_depth) {
953                 ret = ocfs2_find_leaf(ci, el, low_cpos, &eb_bh);
954                 if (ret) {
955                         mlog_errno(ret);
956                         goto out;
957                 }
958
959                 eb = (struct ocfs2_extent_block *) eb_bh->b_data;
960                 el = &eb->h_list;
961
962                 if (el->l_tree_depth) {
963                         ocfs2_error(sb,
964                         "refcount tree %llu has non zero tree "
965                         "depth in leaf btree tree block %llu\n",
966                         (unsigned long long)ocfs2_metadata_cache_owner(ci),
967                         (unsigned long long)eb_bh->b_blocknr);
968                         ret = -EROFS;
969                         goto out;
970                 }
971         }
972
973         found = 0;
974         for (i = le16_to_cpu(el->l_next_free_rec) - 1; i >= 0; i--) {
975                 rec = &el->l_recs[i];
976
977                 if (le32_to_cpu(rec->e_cpos) <= low_cpos) {
978                         found = 1;
979                         break;
980                 }
981         }
982
983         /* adjust len when we have ocfs2_extent_rec after it. */
984         if (found && i < le16_to_cpu(el->l_next_free_rec) - 1) {
985                 tmp = &el->l_recs[i+1];
986
987                 if (le32_to_cpu(tmp->e_cpos) < cpos + len)
988                         len = le32_to_cpu(tmp->e_cpos) - cpos;
989         }
990
991         ret = ocfs2_read_refcount_block(ci, le64_to_cpu(rec->e_blkno),
992                                         &ref_leaf_bh);
993         if (ret) {
994                 mlog_errno(ret);
995                 goto out;
996         }
997
998         ocfs2_find_refcount_rec_in_rl(ci, ref_leaf_bh, cpos, len,
999                                       ret_rec, index);
1000         *ret_bh = ref_leaf_bh;
1001 out:
1002         brelse(eb_bh);
1003         return ret;
1004 }
1005
1006 enum ocfs2_ref_rec_contig {
1007         REF_CONTIG_NONE = 0,
1008         REF_CONTIG_LEFT,
1009         REF_CONTIG_RIGHT,
1010         REF_CONTIG_LEFTRIGHT,
1011 };
1012
1013 static enum ocfs2_ref_rec_contig
1014         ocfs2_refcount_rec_adjacent(struct ocfs2_refcount_block *rb,
1015                                     int index)
1016 {
1017         if ((rb->rf_records.rl_recs[index].r_refcount ==
1018             rb->rf_records.rl_recs[index + 1].r_refcount) &&
1019             (le64_to_cpu(rb->rf_records.rl_recs[index].r_cpos) +
1020             le32_to_cpu(rb->rf_records.rl_recs[index].r_clusters) ==
1021             le64_to_cpu(rb->rf_records.rl_recs[index + 1].r_cpos)))
1022                 return REF_CONTIG_RIGHT;
1023
1024         return REF_CONTIG_NONE;
1025 }
1026
1027 static enum ocfs2_ref_rec_contig
1028         ocfs2_refcount_rec_contig(struct ocfs2_refcount_block *rb,
1029                                   int index)
1030 {
1031         enum ocfs2_ref_rec_contig ret = REF_CONTIG_NONE;
1032
1033         if (index < le16_to_cpu(rb->rf_records.rl_used) - 1)
1034                 ret = ocfs2_refcount_rec_adjacent(rb, index);
1035
1036         if (index > 0) {
1037                 enum ocfs2_ref_rec_contig tmp;
1038
1039                 tmp = ocfs2_refcount_rec_adjacent(rb, index - 1);
1040
1041                 if (tmp == REF_CONTIG_RIGHT) {
1042                         if (ret == REF_CONTIG_RIGHT)
1043                                 ret = REF_CONTIG_LEFTRIGHT;
1044                         else
1045                                 ret = REF_CONTIG_LEFT;
1046                 }
1047         }
1048
1049         return ret;
1050 }
1051
1052 static void ocfs2_rotate_refcount_rec_left(struct ocfs2_refcount_block *rb,
1053                                            int index)
1054 {
1055         BUG_ON(rb->rf_records.rl_recs[index].r_refcount !=
1056                rb->rf_records.rl_recs[index+1].r_refcount);
1057
1058         le32_add_cpu(&rb->rf_records.rl_recs[index].r_clusters,
1059                      le32_to_cpu(rb->rf_records.rl_recs[index+1].r_clusters));
1060
1061         if (index < le16_to_cpu(rb->rf_records.rl_used) - 2)
1062                 memmove(&rb->rf_records.rl_recs[index + 1],
1063                         &rb->rf_records.rl_recs[index + 2],
1064                         sizeof(struct ocfs2_refcount_rec) *
1065                         (le16_to_cpu(rb->rf_records.rl_used) - index - 2));
1066
1067         memset(&rb->rf_records.rl_recs[le16_to_cpu(rb->rf_records.rl_used) - 1],
1068                0, sizeof(struct ocfs2_refcount_rec));
1069         le16_add_cpu(&rb->rf_records.rl_used, -1);
1070 }
1071
1072 /*
1073  * Merge the refcount rec if we are contiguous with the adjacent recs.
1074  */
1075 static void ocfs2_refcount_rec_merge(struct ocfs2_refcount_block *rb,
1076                                      int index)
1077 {
1078         enum ocfs2_ref_rec_contig contig =
1079                                 ocfs2_refcount_rec_contig(rb, index);
1080
1081         if (contig == REF_CONTIG_NONE)
1082                 return;
1083
1084         if (contig == REF_CONTIG_LEFT || contig == REF_CONTIG_LEFTRIGHT) {
1085                 BUG_ON(index == 0);
1086                 index--;
1087         }
1088
1089         ocfs2_rotate_refcount_rec_left(rb, index);
1090
1091         if (contig == REF_CONTIG_LEFTRIGHT)
1092                 ocfs2_rotate_refcount_rec_left(rb, index);
1093 }
1094
1095 /*
1096  * Change the refcount indexed by "index" in ref_bh.
1097  * If refcount reaches 0, remove it.
1098  */
1099 static int ocfs2_change_refcount_rec(handle_t *handle,
1100                                      struct ocfs2_caching_info *ci,
1101                                      struct buffer_head *ref_leaf_bh,
1102                                      int index, int change)
1103 {
1104         int ret;
1105         struct ocfs2_refcount_block *rb =
1106                         (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1107         struct ocfs2_refcount_list *rl = &rb->rf_records;
1108         struct ocfs2_refcount_rec *rec = &rl->rl_recs[index];
1109
1110         ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
1111                                       OCFS2_JOURNAL_ACCESS_WRITE);
1112         if (ret) {
1113                 mlog_errno(ret);
1114                 goto out;
1115         }
1116
1117         mlog(0, "change index %d, old count %u, change %d\n", index,
1118              le32_to_cpu(rec->r_refcount), change);
1119         le32_add_cpu(&rec->r_refcount, change);
1120
1121         if (!rec->r_refcount) {
1122                 if (index != le16_to_cpu(rl->rl_used) - 1) {
1123                         memmove(rec, rec + 1,
1124                                 (le16_to_cpu(rl->rl_used) - index - 1) *
1125                                 sizeof(struct ocfs2_refcount_rec));
1126                         memset(&rl->rl_recs[le16_to_cpu(rl->rl_used) - 1],
1127                                0, sizeof(struct ocfs2_refcount_rec));
1128                 }
1129
1130                 le16_add_cpu(&rl->rl_used, -1);
1131         } else
1132                 ocfs2_refcount_rec_merge(rb, index);
1133
1134         ret = ocfs2_journal_dirty(handle, ref_leaf_bh);
1135         if (ret)
1136                 mlog_errno(ret);
1137 out:
1138         return ret;
1139 }
1140
1141 static int ocfs2_expand_inline_ref_root(handle_t *handle,
1142                                         struct ocfs2_caching_info *ci,
1143                                         struct buffer_head *ref_root_bh,
1144                                         struct buffer_head **ref_leaf_bh,
1145                                         struct ocfs2_alloc_context *meta_ac)
1146 {
1147         int ret;
1148         u16 suballoc_bit_start;
1149         u32 num_got;
1150         u64 blkno;
1151         struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
1152         struct buffer_head *new_bh = NULL;
1153         struct ocfs2_refcount_block *new_rb;
1154         struct ocfs2_refcount_block *root_rb =
1155                         (struct ocfs2_refcount_block *)ref_root_bh->b_data;
1156
1157         ret = ocfs2_journal_access_rb(handle, ci, ref_root_bh,
1158                                       OCFS2_JOURNAL_ACCESS_WRITE);
1159         if (ret) {
1160                 mlog_errno(ret);
1161                 goto out;
1162         }
1163
1164         ret = ocfs2_claim_metadata(OCFS2_SB(sb), handle, meta_ac, 1,
1165                                    &suballoc_bit_start, &num_got,
1166                                    &blkno);
1167         if (ret) {
1168                 mlog_errno(ret);
1169                 goto out;
1170         }
1171
1172         new_bh = sb_getblk(sb, blkno);
1173         if (new_bh == NULL) {
1174                 ret = -EIO;
1175                 mlog_errno(ret);
1176                 goto out;
1177         }
1178         ocfs2_set_new_buffer_uptodate(ci, new_bh);
1179
1180         ret = ocfs2_journal_access_rb(handle, ci, new_bh,
1181                                       OCFS2_JOURNAL_ACCESS_CREATE);
1182         if (ret) {
1183                 mlog_errno(ret);
1184                 goto out;
1185         }
1186
1187         /*
1188          * Initialize ocfs2_refcount_block.
1189          * It should contain the same information as the old root.
1190          * so just memcpy it and change the corresponding field.
1191          */
1192         memcpy(new_bh->b_data, ref_root_bh->b_data, sb->s_blocksize);
1193
1194         new_rb = (struct ocfs2_refcount_block *)new_bh->b_data;
1195         new_rb->rf_suballoc_slot = cpu_to_le16(OCFS2_SB(sb)->slot_num);
1196         new_rb->rf_suballoc_bit = cpu_to_le16(suballoc_bit_start);
1197         new_rb->rf_blkno = cpu_to_le64(blkno);
1198         new_rb->rf_cpos = cpu_to_le32(0);
1199         new_rb->rf_parent = cpu_to_le64(ref_root_bh->b_blocknr);
1200         new_rb->rf_flags = cpu_to_le32(OCFS2_REFCOUNT_LEAF_FL);
1201         ocfs2_journal_dirty(handle, new_bh);
1202
1203         /* Now change the root. */
1204         memset(&root_rb->rf_list, 0, sb->s_blocksize -
1205                offsetof(struct ocfs2_refcount_block, rf_list));
1206         root_rb->rf_list.l_count = cpu_to_le16(ocfs2_extent_recs_per_rb(sb));
1207         root_rb->rf_clusters = cpu_to_le32(1);
1208         root_rb->rf_list.l_next_free_rec = cpu_to_le16(1);
1209         root_rb->rf_list.l_recs[0].e_blkno = cpu_to_le64(blkno);
1210         root_rb->rf_list.l_recs[0].e_leaf_clusters = cpu_to_le16(1);
1211         root_rb->rf_flags = cpu_to_le32(OCFS2_REFCOUNT_TREE_FL);
1212
1213         ocfs2_journal_dirty(handle, ref_root_bh);
1214
1215         mlog(0, "new leaf block %llu, used %u\n", (unsigned long long)blkno,
1216              le16_to_cpu(new_rb->rf_records.rl_used));
1217
1218         *ref_leaf_bh = new_bh;
1219         new_bh = NULL;
1220 out:
1221         brelse(new_bh);
1222         return ret;
1223 }
1224
1225 static int ocfs2_refcount_rec_no_intersect(struct ocfs2_refcount_rec *prev,
1226                                            struct ocfs2_refcount_rec *next)
1227 {
1228         if (ocfs2_get_ref_rec_low_cpos(prev) + le32_to_cpu(prev->r_clusters) <=
1229                 ocfs2_get_ref_rec_low_cpos(next))
1230                 return 1;
1231
1232         return 0;
1233 }
1234
1235 static int cmp_refcount_rec_by_low_cpos(const void *a, const void *b)
1236 {
1237         const struct ocfs2_refcount_rec *l = a, *r = b;
1238         u32 l_cpos = ocfs2_get_ref_rec_low_cpos(l);
1239         u32 r_cpos = ocfs2_get_ref_rec_low_cpos(r);
1240
1241         if (l_cpos > r_cpos)
1242                 return 1;
1243         if (l_cpos < r_cpos)
1244                 return -1;
1245         return 0;
1246 }
1247
1248 static int cmp_refcount_rec_by_cpos(const void *a, const void *b)
1249 {
1250         const struct ocfs2_refcount_rec *l = a, *r = b;
1251         u64 l_cpos = le64_to_cpu(l->r_cpos);
1252         u64 r_cpos = le64_to_cpu(r->r_cpos);
1253
1254         if (l_cpos > r_cpos)
1255                 return 1;
1256         if (l_cpos < r_cpos)
1257                 return -1;
1258         return 0;
1259 }
1260
1261 static void swap_refcount_rec(void *a, void *b, int size)
1262 {
1263         struct ocfs2_refcount_rec *l = a, *r = b, tmp;
1264
1265         tmp = *(struct ocfs2_refcount_rec *)l;
1266         *(struct ocfs2_refcount_rec *)l =
1267                         *(struct ocfs2_refcount_rec *)r;
1268         *(struct ocfs2_refcount_rec *)r = tmp;
1269 }
1270
1271 /*
1272  * The refcount cpos are ordered by their 64bit cpos,
1273  * But we will use the low 32 bit to be the e_cpos in the b-tree.
1274  * So we need to make sure that this pos isn't intersected with others.
1275  *
1276  * Note: The refcount block is already sorted by their low 32 bit cpos,
1277  *       So just try the middle pos first, and we will exit when we find
1278  *       the good position.
1279  */
1280 static int ocfs2_find_refcount_split_pos(struct ocfs2_refcount_list *rl,
1281                                          u32 *split_pos, int *split_index)
1282 {
1283         int num_used = le16_to_cpu(rl->rl_used);
1284         int delta, middle = num_used / 2;
1285
1286         for (delta = 0; delta < middle; delta++) {
1287                 /* Let's check delta earlier than middle */
1288                 if (ocfs2_refcount_rec_no_intersect(
1289                                         &rl->rl_recs[middle - delta - 1],
1290                                         &rl->rl_recs[middle - delta])) {
1291                         *split_index = middle - delta;
1292                         break;
1293                 }
1294
1295                 /* For even counts, don't walk off the end */
1296                 if ((middle + delta + 1) == num_used)
1297                         continue;
1298
1299                 /* Now try delta past middle */
1300                 if (ocfs2_refcount_rec_no_intersect(
1301                                         &rl->rl_recs[middle + delta],
1302                                         &rl->rl_recs[middle + delta + 1])) {
1303                         *split_index = middle + delta + 1;
1304                         break;
1305                 }
1306         }
1307
1308         if (delta >= middle)
1309                 return -ENOSPC;
1310
1311         *split_pos = ocfs2_get_ref_rec_low_cpos(&rl->rl_recs[*split_index]);
1312         return 0;
1313 }
1314
1315 static int ocfs2_divide_leaf_refcount_block(struct buffer_head *ref_leaf_bh,
1316                                             struct buffer_head *new_bh,
1317                                             u32 *split_cpos)
1318 {
1319         int split_index = 0, num_moved, ret;
1320         u32 cpos = 0;
1321         struct ocfs2_refcount_block *rb =
1322                         (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1323         struct ocfs2_refcount_list *rl = &rb->rf_records;
1324         struct ocfs2_refcount_block *new_rb =
1325                         (struct ocfs2_refcount_block *)new_bh->b_data;
1326         struct ocfs2_refcount_list *new_rl = &new_rb->rf_records;
1327
1328         mlog(0, "split old leaf refcount block %llu, count = %u, used = %u\n",
1329              (unsigned long long)ref_leaf_bh->b_blocknr,
1330              le32_to_cpu(rl->rl_count), le32_to_cpu(rl->rl_used));
1331
1332         /*
1333          * XXX: Improvement later.
1334          * If we know all the high 32 bit cpos is the same, no need to sort.
1335          *
1336          * In order to make the whole process safe, we do:
1337          * 1. sort the entries by their low 32 bit cpos first so that we can
1338          *    find the split cpos easily.
1339          * 2. call ocfs2_insert_extent to insert the new refcount block.
1340          * 3. move the refcount rec to the new block.
1341          * 4. sort the entries by their 64 bit cpos.
1342          * 5. dirty the new_rb and rb.
1343          */
1344         sort(&rl->rl_recs, le16_to_cpu(rl->rl_used),
1345              sizeof(struct ocfs2_refcount_rec),
1346              cmp_refcount_rec_by_low_cpos, swap_refcount_rec);
1347
1348         ret = ocfs2_find_refcount_split_pos(rl, &cpos, &split_index);
1349         if (ret) {
1350                 mlog_errno(ret);
1351                 return ret;
1352         }
1353
1354         new_rb->rf_cpos = cpu_to_le32(cpos);
1355
1356         /* move refcount records starting from split_index to the new block. */
1357         num_moved = le16_to_cpu(rl->rl_used) - split_index;
1358         memcpy(new_rl->rl_recs, &rl->rl_recs[split_index],
1359                num_moved * sizeof(struct ocfs2_refcount_rec));
1360
1361         /*ok, remove the entries we just moved over to the other block. */
1362         memset(&rl->rl_recs[split_index], 0,
1363                num_moved * sizeof(struct ocfs2_refcount_rec));
1364
1365         /* change old and new rl_used accordingly. */
1366         le16_add_cpu(&rl->rl_used, -num_moved);
1367         new_rl->rl_used = cpu_to_le32(num_moved);
1368
1369         sort(&rl->rl_recs, le16_to_cpu(rl->rl_used),
1370              sizeof(struct ocfs2_refcount_rec),
1371              cmp_refcount_rec_by_cpos, swap_refcount_rec);
1372
1373         sort(&new_rl->rl_recs, le16_to_cpu(new_rl->rl_used),
1374              sizeof(struct ocfs2_refcount_rec),
1375              cmp_refcount_rec_by_cpos, swap_refcount_rec);
1376
1377         *split_cpos = cpos;
1378         return 0;
1379 }
1380
1381 static int ocfs2_new_leaf_refcount_block(handle_t *handle,
1382                                          struct ocfs2_caching_info *ci,
1383                                          struct buffer_head *ref_root_bh,
1384                                          struct buffer_head *ref_leaf_bh,
1385                                          struct ocfs2_alloc_context *meta_ac)
1386 {
1387         int ret;
1388         u16 suballoc_bit_start;
1389         u32 num_got, new_cpos;
1390         u64 blkno;
1391         struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
1392         struct ocfs2_refcount_block *root_rb =
1393                         (struct ocfs2_refcount_block *)ref_root_bh->b_data;
1394         struct buffer_head *new_bh = NULL;
1395         struct ocfs2_refcount_block *new_rb;
1396         struct ocfs2_extent_tree ref_et;
1397
1398         BUG_ON(!(le32_to_cpu(root_rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL));
1399
1400         ret = ocfs2_journal_access_rb(handle, ci, ref_root_bh,
1401                                       OCFS2_JOURNAL_ACCESS_WRITE);
1402         if (ret) {
1403                 mlog_errno(ret);
1404                 goto out;
1405         }
1406
1407         ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
1408                                       OCFS2_JOURNAL_ACCESS_WRITE);
1409         if (ret) {
1410                 mlog_errno(ret);
1411                 goto out;
1412         }
1413
1414         ret = ocfs2_claim_metadata(OCFS2_SB(sb), handle, meta_ac, 1,
1415                                    &suballoc_bit_start, &num_got,
1416                                    &blkno);
1417         if (ret) {
1418                 mlog_errno(ret);
1419                 goto out;
1420         }
1421
1422         new_bh = sb_getblk(sb, blkno);
1423         if (new_bh == NULL) {
1424                 ret = -EIO;
1425                 mlog_errno(ret);
1426                 goto out;
1427         }
1428         ocfs2_set_new_buffer_uptodate(ci, new_bh);
1429
1430         ret = ocfs2_journal_access_rb(handle, ci, new_bh,
1431                                       OCFS2_JOURNAL_ACCESS_CREATE);
1432         if (ret) {
1433                 mlog_errno(ret);
1434                 goto out;
1435         }
1436
1437         /* Initialize ocfs2_refcount_block. */
1438         new_rb = (struct ocfs2_refcount_block *)new_bh->b_data;
1439         memset(new_rb, 0, sb->s_blocksize);
1440         strcpy((void *)new_rb, OCFS2_REFCOUNT_BLOCK_SIGNATURE);
1441         new_rb->rf_suballoc_slot = cpu_to_le16(OCFS2_SB(sb)->slot_num);
1442         new_rb->rf_suballoc_bit = cpu_to_le16(suballoc_bit_start);
1443         new_rb->rf_fs_generation = cpu_to_le32(OCFS2_SB(sb)->fs_generation);
1444         new_rb->rf_blkno = cpu_to_le64(blkno);
1445         new_rb->rf_parent = cpu_to_le64(ref_root_bh->b_blocknr);
1446         new_rb->rf_flags = cpu_to_le32(OCFS2_REFCOUNT_LEAF_FL);
1447         new_rb->rf_records.rl_count =
1448                                 cpu_to_le16(ocfs2_refcount_recs_per_rb(sb));
1449         new_rb->rf_generation = root_rb->rf_generation;
1450
1451         ret = ocfs2_divide_leaf_refcount_block(ref_leaf_bh, new_bh, &new_cpos);
1452         if (ret) {
1453                 mlog_errno(ret);
1454                 goto out;
1455         }
1456
1457         ocfs2_journal_dirty(handle, ref_leaf_bh);
1458         ocfs2_journal_dirty(handle, new_bh);
1459
1460         ocfs2_init_refcount_extent_tree(&ref_et, ci, ref_root_bh);
1461
1462         mlog(0, "insert new leaf block %llu at %u\n",
1463              (unsigned long long)new_bh->b_blocknr, new_cpos);
1464
1465         /* Insert the new leaf block with the specific offset cpos. */
1466         ret = ocfs2_insert_extent(handle, &ref_et, new_cpos, new_bh->b_blocknr,
1467                                   1, 0, meta_ac);
1468         if (ret)
1469                 mlog_errno(ret);
1470
1471 out:
1472         brelse(new_bh);
1473         return ret;
1474 }
1475
1476 static int ocfs2_expand_refcount_tree(handle_t *handle,
1477                                       struct ocfs2_caching_info *ci,
1478                                       struct buffer_head *ref_root_bh,
1479                                       struct buffer_head *ref_leaf_bh,
1480                                       struct ocfs2_alloc_context *meta_ac)
1481 {
1482         int ret;
1483         struct buffer_head *expand_bh = NULL;
1484
1485         if (ref_root_bh == ref_leaf_bh) {
1486                 /*
1487                  * the old root bh hasn't been expanded to a b-tree,
1488                  * so expand it first.
1489                  */
1490                 ret = ocfs2_expand_inline_ref_root(handle, ci, ref_root_bh,
1491                                                    &expand_bh, meta_ac);
1492                 if (ret) {
1493                         mlog_errno(ret);
1494                         goto out;
1495                 }
1496         } else {
1497                 expand_bh = ref_leaf_bh;
1498                 get_bh(expand_bh);
1499         }
1500
1501
1502         /* Now add a new refcount block into the tree.*/
1503         ret = ocfs2_new_leaf_refcount_block(handle, ci, ref_root_bh,
1504                                             expand_bh, meta_ac);
1505         if (ret)
1506                 mlog_errno(ret);
1507 out:
1508         brelse(expand_bh);
1509         return ret;
1510 }
1511
1512 /*
1513  * Adjust the extent rec in b-tree representing ref_leaf_bh.
1514  *
1515  * Only called when we have inserted a new refcount rec at index 0
1516  * which means ocfs2_extent_rec.e_cpos may need some change.
1517  */
1518 static int ocfs2_adjust_refcount_rec(handle_t *handle,
1519                                      struct ocfs2_caching_info *ci,
1520                                      struct buffer_head *ref_root_bh,
1521                                      struct buffer_head *ref_leaf_bh,
1522                                      struct ocfs2_refcount_rec *rec)
1523 {
1524         int ret = 0, i;
1525         u32 new_cpos, old_cpos;
1526         struct ocfs2_path *path = NULL;
1527         struct ocfs2_extent_tree et;
1528         struct ocfs2_refcount_block *rb =
1529                 (struct ocfs2_refcount_block *)ref_root_bh->b_data;
1530         struct ocfs2_extent_list *el;
1531
1532         if (!(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL))
1533                 goto out;
1534
1535         rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1536         old_cpos = le32_to_cpu(rb->rf_cpos);
1537         new_cpos = le64_to_cpu(rec->r_cpos) & OCFS2_32BIT_POS_MASK;
1538         if (old_cpos <= new_cpos)
1539                 goto out;
1540
1541         ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
1542
1543         path = ocfs2_new_path_from_et(&et);
1544         if (!path) {
1545                 ret = -ENOMEM;
1546                 mlog_errno(ret);
1547                 goto out;
1548         }
1549
1550         ret = ocfs2_find_path(ci, path, old_cpos);
1551         if (ret) {
1552                 mlog_errno(ret);
1553                 goto out;
1554         }
1555
1556         /*
1557          * 2 more credits, one for the leaf refcount block, one for
1558          * the extent block contains the extent rec.
1559          */
1560         ret = ocfs2_extend_trans(handle, handle->h_buffer_credits + 2);
1561         if (ret < 0) {
1562                 mlog_errno(ret);
1563                 goto out;
1564         }
1565
1566         ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
1567                                       OCFS2_JOURNAL_ACCESS_WRITE);
1568         if (ret < 0) {
1569                 mlog_errno(ret);
1570                 goto out;
1571         }
1572
1573         ret = ocfs2_journal_access_eb(handle, ci, path_leaf_bh(path),
1574                                       OCFS2_JOURNAL_ACCESS_WRITE);
1575         if (ret < 0) {
1576                 mlog_errno(ret);
1577                 goto out;
1578         }
1579
1580         /* change the leaf extent block first. */
1581         el = path_leaf_el(path);
1582
1583         for (i = 0; i < le16_to_cpu(el->l_next_free_rec); i++)
1584                 if (le32_to_cpu(el->l_recs[i].e_cpos) == old_cpos)
1585                         break;
1586
1587         BUG_ON(i == le16_to_cpu(el->l_next_free_rec));
1588
1589         el->l_recs[i].e_cpos = cpu_to_le32(new_cpos);
1590
1591         /* change the r_cpos in the leaf block. */
1592         rb->rf_cpos = cpu_to_le32(new_cpos);
1593
1594         ocfs2_journal_dirty(handle, path_leaf_bh(path));
1595         ocfs2_journal_dirty(handle, ref_leaf_bh);
1596
1597 out:
1598         ocfs2_free_path(path);
1599         return ret;
1600 }
1601
1602 static int ocfs2_insert_refcount_rec(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_refcount_rec *rec,
1607                                      int index,
1608                                      struct ocfs2_alloc_context *meta_ac)
1609 {
1610         int ret;
1611         struct ocfs2_refcount_block *rb =
1612                         (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1613         struct ocfs2_refcount_list *rf_list = &rb->rf_records;
1614         struct buffer_head *new_bh = NULL;
1615
1616         BUG_ON(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL);
1617
1618         if (rf_list->rl_used == rf_list->rl_count) {
1619                 u64 cpos = le64_to_cpu(rec->r_cpos);
1620                 u32 len = le32_to_cpu(rec->r_clusters);
1621
1622                 ret = ocfs2_expand_refcount_tree(handle, ci, ref_root_bh,
1623                                                  ref_leaf_bh, meta_ac);
1624                 if (ret) {
1625                         mlog_errno(ret);
1626                         goto out;
1627                 }
1628
1629                 ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
1630                                              cpos, len, NULL, &index,
1631                                              &new_bh);
1632                 if (ret) {
1633                         mlog_errno(ret);
1634                         goto out;
1635                 }
1636
1637                 ref_leaf_bh = new_bh;
1638                 rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1639                 rf_list = &rb->rf_records;
1640         }
1641
1642         ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
1643                                       OCFS2_JOURNAL_ACCESS_WRITE);
1644         if (ret) {
1645                 mlog_errno(ret);
1646                 goto out;
1647         }
1648
1649         if (index < le16_to_cpu(rf_list->rl_used))
1650                 memmove(&rf_list->rl_recs[index + 1],
1651                         &rf_list->rl_recs[index],
1652                         (le16_to_cpu(rf_list->rl_used) - index) *
1653                          sizeof(struct ocfs2_refcount_rec));
1654
1655         mlog(0, "insert refcount record start %llu, len %u, count %u "
1656              "to leaf block %llu at index %d\n",
1657              (unsigned long long)le64_to_cpu(rec->r_cpos),
1658              le32_to_cpu(rec->r_clusters), le32_to_cpu(rec->r_refcount),
1659              (unsigned long long)ref_leaf_bh->b_blocknr, index);
1660
1661         rf_list->rl_recs[index] = *rec;
1662
1663         le16_add_cpu(&rf_list->rl_used, 1);
1664
1665         ocfs2_refcount_rec_merge(rb, index);
1666
1667         ret = ocfs2_journal_dirty(handle, ref_leaf_bh);
1668         if (ret) {
1669                 mlog_errno(ret);
1670                 goto out;
1671         }
1672
1673         if (index == 0) {
1674                 ret = ocfs2_adjust_refcount_rec(handle, ci,
1675                                                 ref_root_bh,
1676                                                 ref_leaf_bh, rec);
1677                 if (ret)
1678                         mlog_errno(ret);
1679         }
1680 out:
1681         brelse(new_bh);
1682         return ret;
1683 }
1684
1685 /*
1686  * Split the refcount_rec indexed by "index" in ref_leaf_bh.
1687  * This is much simple than our b-tree code.
1688  * split_rec is the new refcount rec we want to insert.
1689  * If split_rec->r_refcount > 0, we are changing the refcount(in case we
1690  * increase refcount or decrease a refcount to non-zero).
1691  * If split_rec->r_refcount == 0, we are punching a hole in current refcount
1692  * rec( in case we decrease a refcount to zero).
1693  */
1694 static int ocfs2_split_refcount_rec(handle_t *handle,
1695                                     struct ocfs2_caching_info *ci,
1696                                     struct buffer_head *ref_root_bh,
1697                                     struct buffer_head *ref_leaf_bh,
1698                                     struct ocfs2_refcount_rec *split_rec,
1699                                     int index,
1700                                     struct ocfs2_alloc_context *meta_ac,
1701                                     struct ocfs2_cached_dealloc_ctxt *dealloc)
1702 {
1703         int ret, recs_need;
1704         u32 len;
1705         struct ocfs2_refcount_block *rb =
1706                         (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1707         struct ocfs2_refcount_list *rf_list = &rb->rf_records;
1708         struct ocfs2_refcount_rec *orig_rec = &rf_list->rl_recs[index];
1709         struct ocfs2_refcount_rec *tail_rec = NULL;
1710         struct buffer_head *new_bh = NULL;
1711
1712         BUG_ON(le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL);
1713
1714         mlog(0, "original r_pos %llu, cluster %u, split %llu, cluster %u\n",
1715              le64_to_cpu(orig_rec->r_cpos), le32_to_cpu(orig_rec->r_clusters),
1716              le64_to_cpu(split_rec->r_cpos),
1717              le32_to_cpu(split_rec->r_clusters));
1718
1719         /*
1720          * If we just need to split the header or tail clusters,
1721          * no more recs are needed, just split is OK.
1722          * Otherwise we at least need one new recs.
1723          */
1724         if (!split_rec->r_refcount &&
1725             (split_rec->r_cpos == orig_rec->r_cpos ||
1726              le64_to_cpu(split_rec->r_cpos) +
1727              le32_to_cpu(split_rec->r_clusters) ==
1728              le64_to_cpu(orig_rec->r_cpos) + le32_to_cpu(orig_rec->r_clusters)))
1729                 recs_need = 0;
1730         else
1731                 recs_need = 1;
1732
1733         /*
1734          * We need one more rec if we split in the middle and the new rec have
1735          * some refcount in it.
1736          */
1737         if (split_rec->r_refcount &&
1738             (split_rec->r_cpos != orig_rec->r_cpos &&
1739              le64_to_cpu(split_rec->r_cpos) +
1740              le32_to_cpu(split_rec->r_clusters) !=
1741              le64_to_cpu(orig_rec->r_cpos) + le32_to_cpu(orig_rec->r_clusters)))
1742                 recs_need++;
1743
1744         /* If the leaf block don't have enough record, expand it. */
1745         if (le16_to_cpu(rf_list->rl_used) + recs_need > rf_list->rl_count) {
1746                 struct ocfs2_refcount_rec tmp_rec;
1747                 u64 cpos = le64_to_cpu(orig_rec->r_cpos);
1748                 len = le32_to_cpu(orig_rec->r_clusters);
1749                 ret = ocfs2_expand_refcount_tree(handle, ci, ref_root_bh,
1750                                                  ref_leaf_bh, meta_ac);
1751                 if (ret) {
1752                         mlog_errno(ret);
1753                         goto out;
1754                 }
1755
1756                 /*
1757                  * We have to re-get it since now cpos may be moved to
1758                  * another leaf block.
1759                  */
1760                 ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
1761                                              cpos, len, &tmp_rec, &index,
1762                                              &new_bh);
1763                 if (ret) {
1764                         mlog_errno(ret);
1765                         goto out;
1766                 }
1767
1768                 ref_leaf_bh = new_bh;
1769                 rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1770                 rf_list = &rb->rf_records;
1771                 orig_rec = &rf_list->rl_recs[index];
1772         }
1773
1774         ret = ocfs2_journal_access_rb(handle, ci, ref_leaf_bh,
1775                                       OCFS2_JOURNAL_ACCESS_WRITE);
1776         if (ret) {
1777                 mlog_errno(ret);
1778                 goto out;
1779         }
1780
1781         /*
1782          * We have calculated out how many new records we need and store
1783          * in recs_need, so spare enough space first by moving the records
1784          * after "index" to the end.
1785          */
1786         if (index != le16_to_cpu(rf_list->rl_used) - 1)
1787                 memmove(&rf_list->rl_recs[index + 1 + recs_need],
1788                         &rf_list->rl_recs[index + 1],
1789                         (le16_to_cpu(rf_list->rl_used) - index - 1) *
1790                          sizeof(struct ocfs2_refcount_rec));
1791
1792         len = (le64_to_cpu(orig_rec->r_cpos) +
1793               le32_to_cpu(orig_rec->r_clusters)) -
1794               (le64_to_cpu(split_rec->r_cpos) +
1795               le32_to_cpu(split_rec->r_clusters));
1796
1797         /*
1798          * If we have "len", the we will split in the tail and move it
1799          * to the end of the space we have just spared.
1800          */
1801         if (len) {
1802                 tail_rec = &rf_list->rl_recs[index + recs_need];
1803
1804                 memcpy(tail_rec, orig_rec, sizeof(struct ocfs2_refcount_rec));
1805                 le64_add_cpu(&tail_rec->r_cpos,
1806                              le32_to_cpu(tail_rec->r_clusters) - len);
1807                 tail_rec->r_clusters = le32_to_cpu(len);
1808         }
1809
1810         /*
1811          * If the split pos isn't the same as the original one, we need to
1812          * split in the head.
1813          *
1814          * Note: We have the chance that split_rec.r_refcount = 0,
1815          * recs_need = 0 and len > 0, which means we just cut the head from
1816          * the orig_rec and in that case we have done some modification in
1817          * orig_rec above, so the check for r_cpos is faked.
1818          */
1819         if (split_rec->r_cpos != orig_rec->r_cpos && tail_rec != orig_rec) {
1820                 len = le64_to_cpu(split_rec->r_cpos) -
1821                       le64_to_cpu(orig_rec->r_cpos);
1822                 orig_rec->r_clusters = cpu_to_le32(len);
1823                 index++;
1824         }
1825
1826         le16_add_cpu(&rf_list->rl_used, recs_need);
1827
1828         if (split_rec->r_refcount) {
1829                 rf_list->rl_recs[index] = *split_rec;
1830                 mlog(0, "insert refcount record start %llu, len %u, count %u "
1831                      "to leaf block %llu at index %d\n",
1832                      (unsigned long long)le64_to_cpu(split_rec->r_cpos),
1833                      le32_to_cpu(split_rec->r_clusters),
1834                      le32_to_cpu(split_rec->r_refcount),
1835                      (unsigned long long)ref_leaf_bh->b_blocknr, index);
1836
1837                 ocfs2_refcount_rec_merge(rb, index);
1838         }
1839
1840         ret = ocfs2_journal_dirty(handle, ref_leaf_bh);
1841         if (ret)
1842                 mlog_errno(ret);
1843
1844 out:
1845         brelse(new_bh);
1846         return ret;
1847 }
1848
1849 static int __ocfs2_increase_refcount(handle_t *handle,
1850                                      struct ocfs2_caching_info *ci,
1851                                      struct buffer_head *ref_root_bh,
1852                                      u64 cpos, u32 len,
1853                                      struct ocfs2_alloc_context *meta_ac,
1854                                      struct ocfs2_cached_dealloc_ctxt *dealloc)
1855 {
1856         int ret = 0, index;
1857         struct buffer_head *ref_leaf_bh = NULL;
1858         struct ocfs2_refcount_rec rec;
1859         unsigned int set_len = 0;
1860
1861         mlog(0, "Tree owner %llu, add refcount start %llu, len %u\n",
1862              (unsigned long long)ocfs2_metadata_cache_owner(ci),
1863              (unsigned long long)cpos, len);
1864
1865         while (len) {
1866                 ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
1867                                              cpos, len, &rec, &index,
1868                                              &ref_leaf_bh);
1869                 if (ret) {
1870                         mlog_errno(ret);
1871                         goto out;
1872                 }
1873
1874                 set_len = le32_to_cpu(rec.r_clusters);
1875
1876                 /*
1877                  * Here we may meet with 3 situations:
1878                  *
1879                  * 1. If we find an already existing record, and the length
1880                  *    is the same, cool, we just need to increase the r_refcount
1881                  *    and it is OK.
1882                  * 2. If we find a hole, just insert it with r_refcount = 1.
1883                  * 3. If we are in the middle of one extent record, split
1884                  *    it.
1885                  */
1886                 if (rec.r_refcount && le64_to_cpu(rec.r_cpos) == cpos &&
1887                     set_len <= len) {
1888                         mlog(0, "increase refcount rec, start %llu, len %u, "
1889                              "count %u\n", (unsigned long long)cpos, set_len,
1890                              le32_to_cpu(rec.r_refcount));
1891                         ret = ocfs2_change_refcount_rec(handle, ci,
1892                                                         ref_leaf_bh, index, 1);
1893                         if (ret) {
1894                                 mlog_errno(ret);
1895                                 goto out;
1896                         }
1897                 } else if (!rec.r_refcount) {
1898                         rec.r_refcount = cpu_to_le32(1);
1899
1900                         mlog(0, "insert refcount rec, start %llu, len %u\n",
1901                              (unsigned long long)le64_to_cpu(rec.r_cpos),
1902                              set_len);
1903                         ret = ocfs2_insert_refcount_rec(handle, ci, ref_root_bh,
1904                                                         ref_leaf_bh,
1905                                                         &rec, index, meta_ac);
1906                         if (ret) {
1907                                 mlog_errno(ret);
1908                                 goto out;
1909                         }
1910                 } else  {
1911                         set_len = min((u64)(cpos + len),
1912                                       le64_to_cpu(rec.r_cpos) + set_len) - cpos;
1913                         rec.r_cpos = cpu_to_le64(cpos);
1914                         rec.r_clusters = cpu_to_le32(set_len);
1915                         le32_add_cpu(&rec.r_refcount, 1);
1916
1917                         mlog(0, "split refcount rec, start %llu, "
1918                              "len %u, count %u\n",
1919                              (unsigned long long)le64_to_cpu(rec.r_cpos),
1920                              set_len, le32_to_cpu(rec.r_refcount));
1921                         ret = ocfs2_split_refcount_rec(handle, ci,
1922                                                        ref_root_bh, ref_leaf_bh,
1923                                                        &rec, index,
1924                                                        meta_ac, dealloc);
1925                         if (ret) {
1926                                 mlog_errno(ret);
1927                                 goto out;
1928                         }
1929                 }
1930
1931                 cpos += set_len;
1932                 len -= set_len;
1933                 brelse(ref_leaf_bh);
1934                 ref_leaf_bh = NULL;
1935         }
1936
1937 out:
1938         brelse(ref_leaf_bh);
1939         return ret;
1940 }
1941
1942 static int ocfs2_remove_refcount_extent(handle_t *handle,
1943                                 struct ocfs2_caching_info *ci,
1944                                 struct buffer_head *ref_root_bh,
1945                                 struct buffer_head *ref_leaf_bh,
1946                                 struct ocfs2_alloc_context *meta_ac,
1947                                 struct ocfs2_cached_dealloc_ctxt *dealloc)
1948 {
1949         int ret;
1950         struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
1951         struct ocfs2_refcount_block *rb =
1952                         (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
1953         struct ocfs2_extent_tree et;
1954
1955         BUG_ON(rb->rf_records.rl_used);
1956
1957         ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
1958         ret = ocfs2_remove_extent(handle, &et, le32_to_cpu(rb->rf_cpos),
1959                                   1, meta_ac, dealloc);
1960         if (ret) {
1961                 mlog_errno(ret);
1962                 goto out;
1963         }
1964
1965         ocfs2_remove_from_cache(ci, ref_leaf_bh);
1966
1967         /*
1968          * add the freed block to the dealloc so that it will be freed
1969          * when we run dealloc.
1970          */
1971         ret = ocfs2_cache_block_dealloc(dealloc, EXTENT_ALLOC_SYSTEM_INODE,
1972                                         le16_to_cpu(rb->rf_suballoc_slot),
1973                                         le64_to_cpu(rb->rf_blkno),
1974                                         le16_to_cpu(rb->rf_suballoc_bit));
1975         if (ret) {
1976                 mlog_errno(ret);
1977                 goto out;
1978         }
1979
1980         ret = ocfs2_journal_access_rb(handle, ci, ref_root_bh,
1981                                       OCFS2_JOURNAL_ACCESS_WRITE);
1982         if (ret) {
1983                 mlog_errno(ret);
1984                 goto out;
1985         }
1986
1987         rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
1988
1989         le32_add_cpu(&rb->rf_clusters, -1);
1990
1991         /*
1992          * check whether we need to restore the root refcount block if
1993          * there is no leaf extent block at atll.
1994          */
1995         if (!rb->rf_list.l_next_free_rec) {
1996                 BUG_ON(rb->rf_clusters);
1997
1998                 mlog(0, "reset refcount tree root %llu to be a record block.\n",
1999                      (unsigned long long)ref_root_bh->b_blocknr);
2000
2001                 rb->rf_flags = 0;
2002                 rb->rf_parent = 0;
2003                 rb->rf_cpos = 0;
2004                 memset(&rb->rf_records, 0, sb->s_blocksize -
2005                        offsetof(struct ocfs2_refcount_block, rf_records));
2006                 rb->rf_records.rl_count =
2007                                 cpu_to_le16(ocfs2_refcount_recs_per_rb(sb));
2008         }
2009
2010         ocfs2_journal_dirty(handle, ref_root_bh);
2011
2012 out:
2013         return ret;
2014 }
2015
2016 static int ocfs2_decrease_refcount_rec(handle_t *handle,
2017                                 struct ocfs2_caching_info *ci,
2018                                 struct buffer_head *ref_root_bh,
2019                                 struct buffer_head *ref_leaf_bh,
2020                                 int index, u64 cpos, unsigned int len,
2021                                 struct ocfs2_alloc_context *meta_ac,
2022                                 struct ocfs2_cached_dealloc_ctxt *dealloc)
2023 {
2024         int ret;
2025         struct ocfs2_refcount_block *rb =
2026                         (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
2027         struct ocfs2_refcount_rec *rec = &rb->rf_records.rl_recs[index];
2028
2029         BUG_ON(cpos < le64_to_cpu(rec->r_cpos));
2030         BUG_ON(cpos + len >
2031                le64_to_cpu(rec->r_cpos) + le32_to_cpu(rec->r_clusters));
2032
2033         if (cpos == le64_to_cpu(rec->r_cpos) &&
2034             len == le32_to_cpu(rec->r_clusters))
2035                 ret = ocfs2_change_refcount_rec(handle, ci,
2036                                                 ref_leaf_bh, index, -1);
2037         else {
2038                 struct ocfs2_refcount_rec split = *rec;
2039                 split.r_cpos = cpu_to_le64(cpos);
2040                 split.r_clusters = cpu_to_le32(len);
2041
2042                 le32_add_cpu(&split.r_refcount, -1);
2043
2044                 mlog(0, "split refcount rec, start %llu, "
2045                      "len %u, count %u, original start %llu, len %u\n",
2046                      (unsigned long long)le64_to_cpu(split.r_cpos),
2047                      len, le32_to_cpu(split.r_refcount),
2048                      (unsigned long long)le64_to_cpu(rec->r_cpos),
2049                      le32_to_cpu(rec->r_clusters));
2050                 ret = ocfs2_split_refcount_rec(handle, ci,
2051                                                ref_root_bh, ref_leaf_bh,
2052                                                &split, index,
2053                                                meta_ac, dealloc);
2054         }
2055
2056         if (ret) {
2057                 mlog_errno(ret);
2058                 goto out;
2059         }
2060
2061         /* Remove the leaf refcount block if it contains no refcount record. */
2062         if (!rb->rf_records.rl_used && ref_leaf_bh != ref_root_bh) {
2063                 ret = ocfs2_remove_refcount_extent(handle, ci, ref_root_bh,
2064                                                    ref_leaf_bh, meta_ac,
2065                                                    dealloc);
2066                 if (ret)
2067                         mlog_errno(ret);
2068         }
2069
2070 out:
2071         return ret;
2072 }
2073
2074 static int __ocfs2_decrease_refcount(handle_t *handle,
2075                                      struct ocfs2_caching_info *ci,
2076                                      struct buffer_head *ref_root_bh,
2077                                      u64 cpos, u32 len,
2078                                      struct ocfs2_alloc_context *meta_ac,
2079                                      struct ocfs2_cached_dealloc_ctxt *dealloc,
2080                                      int delete)
2081 {
2082         int ret = 0, index = 0;
2083         struct ocfs2_refcount_rec rec;
2084         unsigned int r_count = 0, r_len;
2085         struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
2086         struct buffer_head *ref_leaf_bh = NULL;
2087
2088         mlog(0, "Tree owner %llu, decrease refcount start %llu, "
2089              "len %u, delete %u\n",
2090              (unsigned long long)ocfs2_metadata_cache_owner(ci),
2091              (unsigned long long)cpos, len, delete);
2092
2093         while (len) {
2094                 ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
2095                                              cpos, len, &rec, &index,
2096                                              &ref_leaf_bh);
2097                 if (ret) {
2098                         mlog_errno(ret);
2099                         goto out;
2100                 }
2101
2102                 r_count = le32_to_cpu(rec.r_refcount);
2103                 BUG_ON(r_count == 0);
2104                 if (!delete)
2105                         BUG_ON(r_count > 1);
2106
2107                 r_len = min((u64)(cpos + len), le64_to_cpu(rec.r_cpos) +
2108                               le32_to_cpu(rec.r_clusters)) - cpos;
2109
2110                 ret = ocfs2_decrease_refcount_rec(handle, ci, ref_root_bh,
2111                                                   ref_leaf_bh, index,
2112                                                   cpos, r_len,
2113                                                   meta_ac, dealloc);
2114                 if (ret) {
2115                         mlog_errno(ret);
2116                         goto out;
2117                 }
2118
2119                 if (le32_to_cpu(rec.r_refcount) == 1 && delete) {
2120                         ret = ocfs2_cache_cluster_dealloc(dealloc,
2121                                           ocfs2_clusters_to_blocks(sb, cpos),
2122                                                           r_len);
2123                         if (ret) {
2124                                 mlog_errno(ret);
2125                                 goto out;
2126                         }
2127                 }
2128
2129                 cpos += r_len;
2130                 len -= r_len;
2131                 brelse(ref_leaf_bh);
2132                 ref_leaf_bh = NULL;
2133         }
2134
2135 out:
2136         brelse(ref_leaf_bh);
2137         return ret;
2138 }
2139
2140 /* Caller must hold refcount tree lock. */
2141 int ocfs2_decrease_refcount(struct inode *inode,
2142                             handle_t *handle, u32 cpos, u32 len,
2143                             struct ocfs2_alloc_context *meta_ac,
2144                             struct ocfs2_cached_dealloc_ctxt *dealloc,
2145                             int delete)
2146 {
2147         int ret;
2148         u64 ref_blkno;
2149         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2150         struct buffer_head *ref_root_bh = NULL;
2151         struct ocfs2_refcount_tree *tree;
2152
2153         BUG_ON(!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
2154
2155         ret = ocfs2_get_refcount_block(inode, &ref_blkno);
2156         if (ret) {
2157                 mlog_errno(ret);
2158                 goto out;
2159         }
2160
2161         ret = ocfs2_get_refcount_tree(OCFS2_SB(inode->i_sb), ref_blkno, &tree);
2162         if (ret) {
2163                 mlog_errno(ret);
2164                 goto out;
2165         }
2166
2167         ret = ocfs2_read_refcount_block(&tree->rf_ci, tree->rf_blkno,
2168                                         &ref_root_bh);
2169         if (ret) {
2170                 mlog_errno(ret);
2171                 goto out;
2172         }
2173
2174         ret = __ocfs2_decrease_refcount(handle, &tree->rf_ci, ref_root_bh,
2175                                         cpos, len, meta_ac, dealloc, delete);
2176         if (ret)
2177                 mlog_errno(ret);
2178 out:
2179         brelse(ref_root_bh);
2180         return ret;
2181 }
2182
2183 /*
2184  * Mark the already-existing extent at cpos as refcounted for len clusters.
2185  * This adds the refcount extent flag.
2186  *
2187  * If the existing extent is larger than the request, initiate a
2188  * split. An attempt will be made at merging with adjacent extents.
2189  *
2190  * The caller is responsible for passing down meta_ac if we'll need it.
2191  */
2192 static int ocfs2_mark_extent_refcounted(struct inode *inode,
2193                                 struct ocfs2_extent_tree *et,
2194                                 handle_t *handle, u32 cpos,
2195                                 u32 len, u32 phys,
2196                                 struct ocfs2_alloc_context *meta_ac,
2197                                 struct ocfs2_cached_dealloc_ctxt *dealloc)
2198 {
2199         int ret;
2200
2201         mlog(0, "Inode %lu refcount tree cpos %u, len %u, phys cluster %u\n",
2202              inode->i_ino, cpos, len, phys);
2203
2204         if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb))) {
2205                 ocfs2_error(inode->i_sb, "Inode %lu want to use refcount "
2206                             "tree, but the feature bit is not set in the "
2207                             "super block.", inode->i_ino);
2208                 ret = -EROFS;
2209                 goto out;
2210         }
2211
2212         ret = ocfs2_change_extent_flag(handle, et, cpos,
2213                                        len, phys, meta_ac, dealloc,
2214                                        OCFS2_EXT_REFCOUNTED, 0);
2215         if (ret)
2216                 mlog_errno(ret);
2217
2218 out:
2219         return ret;
2220 }
2221
2222 /*
2223  * Given some contiguous physical clusters, calculate what we need
2224  * for modifying their refcount.
2225  */
2226 static int ocfs2_calc_refcount_meta_credits(struct super_block *sb,
2227                                             struct ocfs2_caching_info *ci,
2228                                             struct buffer_head *ref_root_bh,
2229                                             u64 start_cpos,
2230                                             u32 clusters,
2231                                             int *meta_add,
2232                                             int *credits)
2233 {
2234         int ret = 0, index, ref_blocks = 0, recs_add = 0;
2235         u64 cpos = start_cpos;
2236         struct ocfs2_refcount_block *rb;
2237         struct ocfs2_refcount_rec rec;
2238         struct buffer_head *ref_leaf_bh = NULL, *prev_bh = NULL;
2239         u32 len;
2240
2241         mlog(0, "start_cpos %llu, clusters %u\n",
2242              (unsigned long long)start_cpos, clusters);
2243         while (clusters) {
2244                 ret = ocfs2_get_refcount_rec(ci, ref_root_bh,
2245                                              cpos, clusters, &rec,
2246                                              &index, &ref_leaf_bh);
2247                 if (ret) {
2248                         mlog_errno(ret);
2249                         goto out;
2250                 }
2251
2252                 if (ref_leaf_bh != prev_bh) {
2253                         /*
2254                          * Now we encounter a new leaf block, so calculate
2255                          * whether we need to extend the old leaf.
2256                          */
2257                         if (prev_bh) {
2258                                 rb = (struct ocfs2_refcount_block *)
2259                                                         prev_bh->b_data;
2260
2261                                 if (le64_to_cpu(rb->rf_records.rl_used) +
2262                                     recs_add >
2263                                     le16_to_cpu(rb->rf_records.rl_count))
2264                                         ref_blocks++;
2265                         }
2266
2267                         recs_add = 0;
2268                         *credits += 1;
2269                         brelse(prev_bh);
2270                         prev_bh = ref_leaf_bh;
2271                         get_bh(prev_bh);
2272                 }
2273
2274                 rb = (struct ocfs2_refcount_block *)ref_leaf_bh->b_data;
2275
2276                 mlog(0, "recs_add %d,cpos %llu, clusters %u, rec->r_cpos %llu,"
2277                      "rec->r_clusters %u, rec->r_refcount %u, index %d\n",
2278                      recs_add, (unsigned long long)cpos, clusters,
2279                      (unsigned long long)le64_to_cpu(rec.r_cpos),
2280                      le32_to_cpu(rec.r_clusters),
2281                      le32_to_cpu(rec.r_refcount), index);
2282
2283                 len = min((u64)cpos + clusters, le64_to_cpu(rec.r_cpos) +
2284                           le32_to_cpu(rec.r_clusters)) - cpos;
2285                 /*
2286                  * If the refcount rec already exist, cool. We just need
2287                  * to check whether there is a split. Otherwise we just need
2288                  * to increase the refcount.
2289                  * If we will insert one, increases recs_add.
2290                  *
2291                  * We record all the records which will be inserted to the
2292                  * same refcount block, so that we can tell exactly whether
2293                  * we need a new refcount block or not.
2294                  */
2295                 if (rec.r_refcount) {
2296                         /* Check whether we need a split at the beginning. */
2297                         if (cpos == start_cpos &&
2298                             cpos != le64_to_cpu(rec.r_cpos))
2299                                 recs_add++;
2300
2301                         /* Check whether we need a split in the end. */
2302                         if (cpos + clusters < le64_to_cpu(rec.r_cpos) +
2303                             le32_to_cpu(rec.r_clusters))
2304                                 recs_add++;
2305                 } else
2306                         recs_add++;
2307
2308                 brelse(ref_leaf_bh);
2309                 ref_leaf_bh = NULL;
2310                 clusters -= len;
2311                 cpos += len;
2312         }
2313
2314         if (prev_bh) {
2315                 rb = (struct ocfs2_refcount_block *)prev_bh->b_data;
2316
2317                 if (le64_to_cpu(rb->rf_records.rl_used) + recs_add >
2318                     le16_to_cpu(rb->rf_records.rl_count))
2319                         ref_blocks++;
2320
2321                 *credits += 1;
2322         }
2323
2324         if (!ref_blocks)
2325                 goto out;
2326
2327         mlog(0, "we need ref_blocks %d\n", ref_blocks);
2328         *meta_add += ref_blocks;
2329         *credits += ref_blocks;
2330
2331         /*
2332          * So we may need ref_blocks to insert into the tree.
2333          * That also means we need to change the b-tree and add that number
2334          * of records since we never merge them.
2335          * We need one more block for expansion since the new created leaf
2336          * block is also full and needs split.
2337          */
2338         rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
2339         if (le32_to_cpu(rb->rf_flags) & OCFS2_REFCOUNT_TREE_FL) {
2340                 struct ocfs2_extent_tree et;
2341
2342                 ocfs2_init_refcount_extent_tree(&et, ci, ref_root_bh);
2343                 *meta_add += ocfs2_extend_meta_needed(et.et_root_el);
2344                 *credits += ocfs2_calc_extend_credits(sb,
2345                                                       et.et_root_el,
2346                                                       ref_blocks);
2347         } else {
2348                 *credits += OCFS2_EXPAND_REFCOUNT_TREE_CREDITS;
2349                 *meta_add += 1;
2350         }
2351
2352 out:
2353         brelse(ref_leaf_bh);
2354         brelse(prev_bh);
2355         return ret;
2356 }
2357
2358 /*
2359  * For refcount tree, we will decrease some contiguous clusters
2360  * refcount count, so just go through it to see how many blocks
2361  * we gonna touch and whether we need to create new blocks.
2362  *
2363  * Normally the refcount blocks store these refcount should be
2364  * continguous also, so that we can get the number easily.
2365  * As for meta_ac, we will at most add split 2 refcount record and
2366  * 2 more refcount block, so just check it in a rough way.
2367  *
2368  * Caller must hold refcount tree lock.
2369  */
2370 int ocfs2_prepare_refcount_change_for_del(struct inode *inode,
2371                                           struct buffer_head *di_bh,
2372                                           u64 phys_blkno,
2373                                           u32 clusters,
2374                                           int *credits,
2375                                           struct ocfs2_alloc_context **meta_ac)
2376 {
2377         int ret, ref_blocks = 0;
2378         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
2379         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2380         struct buffer_head *ref_root_bh = NULL;
2381         struct ocfs2_refcount_tree *tree;
2382         u64 start_cpos = ocfs2_blocks_to_clusters(inode->i_sb, phys_blkno);
2383
2384         if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb))) {
2385                 ocfs2_error(inode->i_sb, "Inode %lu want to use refcount "
2386                             "tree, but the feature bit is not set in the "
2387                             "super block.", inode->i_ino);
2388                 ret = -EROFS;
2389                 goto out;
2390         }
2391
2392         BUG_ON(!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
2393
2394         ret = ocfs2_get_refcount_tree(OCFS2_SB(inode->i_sb),
2395                                       le64_to_cpu(di->i_refcount_loc), &tree);
2396         if (ret) {
2397                 mlog_errno(ret);
2398                 goto out;
2399         }
2400
2401         ret = ocfs2_read_refcount_block(&tree->rf_ci,
2402                                         le64_to_cpu(di->i_refcount_loc),
2403                                         &ref_root_bh);
2404         if (ret) {
2405                 mlog_errno(ret);
2406                 goto out;
2407         }
2408
2409         ret = ocfs2_calc_refcount_meta_credits(inode->i_sb,
2410                                                &tree->rf_ci,
2411                                                ref_root_bh,
2412                                                start_cpos, clusters,
2413                                                &ref_blocks, credits);
2414         if (ret) {
2415                 mlog_errno(ret);
2416                 goto out;
2417         }
2418
2419         mlog(0, "reserve new metadata %d, credits = %d\n",
2420              ref_blocks, *credits);
2421
2422         if (ref_blocks) {
2423                 ret = ocfs2_reserve_new_metadata_blocks(OCFS2_SB(inode->i_sb),
2424                                                         ref_blocks, meta_ac);
2425                 if (ret)
2426                         mlog_errno(ret);
2427         }
2428
2429 out:
2430         brelse(ref_root_bh);
2431         return ret;
2432 }
2433
2434 #define MAX_CONTIG_BYTES        1048576
2435
2436 static inline unsigned int ocfs2_cow_contig_clusters(struct super_block *sb)
2437 {
2438         return ocfs2_clusters_for_bytes(sb, MAX_CONTIG_BYTES);
2439 }
2440
2441 static inline unsigned int ocfs2_cow_contig_mask(struct super_block *sb)
2442 {
2443         return ~(ocfs2_cow_contig_clusters(sb) - 1);
2444 }
2445
2446 /*
2447  * Given an extent that starts at 'start' and an I/O that starts at 'cpos',
2448  * find an offset (start + (n * contig_clusters)) that is closest to cpos
2449  * while still being less than or equal to it.
2450  *
2451  * The goal is to break the extent at a multiple of contig_clusters.
2452  */
2453 static inline unsigned int ocfs2_cow_align_start(struct super_block *sb,
2454                                                  unsigned int start,
2455                                                  unsigned int cpos)
2456 {
2457         BUG_ON(start > cpos);
2458
2459         return start + ((cpos - start) & ocfs2_cow_contig_mask(sb));
2460 }
2461
2462 /*
2463  * Given a cluster count of len, pad it out so that it is a multiple
2464  * of contig_clusters.
2465  */
2466 static inline unsigned int ocfs2_cow_align_length(struct super_block *sb,
2467                                                   unsigned int len)
2468 {
2469         unsigned int padded =
2470                 (len + (ocfs2_cow_contig_clusters(sb) - 1)) &
2471                 ocfs2_cow_contig_mask(sb);
2472
2473         /* Did we wrap? */
2474         if (padded < len)
2475                 padded = UINT_MAX;
2476
2477         return padded;
2478 }
2479
2480 /*
2481  * Calculate out the start and number of virtual clusters we need to to CoW.
2482  *
2483  * cpos is vitual start cluster position we want to do CoW in a
2484  * file and write_len is the cluster length.
2485  *
2486  * Normal we will start CoW from the beginning of extent record cotaining cpos.
2487  * We try to break up extents on boundaries of MAX_CONTIG_BYTES so that we
2488  * get good I/O from the resulting extent tree.
2489  */
2490 static int ocfs2_refcount_cal_cow_clusters(struct inode *inode,
2491                                            struct buffer_head *di_bh,
2492                                            u32 cpos,
2493                                            u32 write_len,
2494                                            u32 *cow_start,
2495                                            u32 *cow_len)
2496 {
2497         int ret = 0;
2498         struct ocfs2_dinode *di = (struct ocfs2_dinode *) di_bh->b_data;
2499         struct ocfs2_extent_list *el = &di->id2.i_list;
2500         int tree_height = le16_to_cpu(el->l_tree_depth), i;
2501         struct buffer_head *eb_bh = NULL;
2502         struct ocfs2_extent_block *eb = NULL;
2503         struct ocfs2_extent_rec *rec;
2504         unsigned int want_clusters, rec_end = 0;
2505         int contig_clusters = ocfs2_cow_contig_clusters(inode->i_sb);
2506         int leaf_clusters;
2507
2508         if (tree_height > 0) {
2509                 ret = ocfs2_find_leaf(INODE_CACHE(inode), el, cpos, &eb_bh);
2510                 if (ret) {
2511                         mlog_errno(ret);
2512                         goto out;
2513                 }
2514
2515                 eb = (struct ocfs2_extent_block *) eb_bh->b_data;
2516                 el = &eb->h_list;
2517
2518                 if (el->l_tree_depth) {
2519                         ocfs2_error(inode->i_sb,
2520                                     "Inode %lu has non zero tree depth in "
2521                                     "leaf block %llu\n", inode->i_ino,
2522                                     (unsigned long long)eb_bh->b_blocknr);
2523                         ret = -EROFS;
2524                         goto out;
2525                 }
2526         }
2527
2528         *cow_len = 0;
2529         for (i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
2530                 rec = &el->l_recs[i];
2531
2532                 if (ocfs2_is_empty_extent(rec)) {
2533                         mlog_bug_on_msg(i != 0, "Inode %lu has empty record in "
2534                                         "index %d\n", inode->i_ino, i);
2535                         continue;
2536                 }
2537
2538                 if (le32_to_cpu(rec->e_cpos) +
2539                     le16_to_cpu(rec->e_leaf_clusters) <= cpos)
2540                         continue;
2541
2542                 if (*cow_len == 0) {
2543                         /*
2544                          * We should find a refcounted record in the
2545                          * first pass.
2546                          */
2547                         BUG_ON(!(rec->e_flags & OCFS2_EXT_REFCOUNTED));
2548                         *cow_start = le32_to_cpu(rec->e_cpos);
2549                 }
2550
2551                 /*
2552                  * If we encounter a hole or a non-refcounted record,
2553                  * stop the search.
2554                  */
2555                 if ((!(rec->e_flags & OCFS2_EXT_REFCOUNTED)) ||
2556                     (*cow_len && rec_end != le32_to_cpu(rec->e_cpos)))
2557                         break;
2558
2559                 leaf_clusters = le16_to_cpu(rec->e_leaf_clusters);
2560                 rec_end = le32_to_cpu(rec->e_cpos) + leaf_clusters;
2561
2562                 /*
2563                  * How many clusters do we actually need from
2564                  * this extent?  First we see how many we actually
2565                  * need to complete the write.  If that's smaller
2566                  * than contig_clusters, we try for contig_clusters.
2567                  */
2568                 if (!*cow_len)
2569                         want_clusters = write_len;
2570                 else
2571                         want_clusters = (cpos + write_len) -
2572                                 (*cow_start + *cow_len);
2573                 if (want_clusters < contig_clusters)
2574                         want_clusters = contig_clusters;
2575
2576                 /*
2577                  * If the write does not cover the whole extent, we
2578                  * need to calculate how we're going to split the extent.
2579                  * We try to do it on contig_clusters boundaries.
2580                  *
2581                  * Any extent smaller than contig_clusters will be
2582                  * CoWed in its entirety.
2583                  */
2584                 if (leaf_clusters <= contig_clusters)
2585                         *cow_len += leaf_clusters;
2586                 else if (*cow_len || (*cow_start == cpos)) {
2587                         /*
2588                          * This extent needs to be CoW'd from its
2589                          * beginning, so all we have to do is compute
2590                          * how many clusters to grab.  We align
2591                          * want_clusters to the edge of contig_clusters
2592                          * to get better I/O.
2593                          */
2594                         want_clusters = ocfs2_cow_align_length(inode->i_sb,
2595                                                                want_clusters);
2596
2597                         if (leaf_clusters < want_clusters)
2598                                 *cow_len += leaf_clusters;
2599                         else
2600                                 *cow_len += want_clusters;
2601                 } else if ((*cow_start + contig_clusters) >=
2602                            (cpos + write_len)) {
2603                         /*
2604                          * Breaking off contig_clusters at the front
2605                          * of the extent will cover our write.  That's
2606                          * easy.
2607                          */
2608                         *cow_len = contig_clusters;
2609                 } else if ((rec_end - cpos) <= contig_clusters) {
2610                         /*
2611                          * Breaking off contig_clusters at the tail of
2612                          * this extent will cover cpos.
2613                          */
2614                         *cow_start = rec_end - contig_clusters;
2615                         *cow_len = contig_clusters;
2616                 } else if ((rec_end - cpos) <= want_clusters) {
2617                         /*
2618                          * While we can't fit the entire write in this
2619                          * extent, we know that the write goes from cpos
2620                          * to the end of the extent.  Break that off.
2621                          * We try to break it at some multiple of
2622                          * contig_clusters from the front of the extent.
2623                          * Failing that (ie, cpos is within
2624                          * contig_clusters of the front), we'll CoW the
2625                          * entire extent.
2626                          */
2627                         *cow_start = ocfs2_cow_align_start(inode->i_sb,
2628                                                            *cow_start, cpos);
2629                         *cow_len = rec_end - *cow_start;
2630                 } else {
2631                         /*
2632                          * Ok, the entire write lives in the middle of
2633                          * this extent.  Let's try to slice the extent up
2634                          * nicely.  Optimally, our CoW region starts at
2635                          * m*contig_clusters from the beginning of the
2636                          * extent and goes for n*contig_clusters,
2637                          * covering the entire write.
2638                          */
2639                         *cow_start = ocfs2_cow_align_start(inode->i_sb,
2640                                                            *cow_start, cpos);
2641
2642                         want_clusters = (cpos + write_len) - *cow_start;
2643                         want_clusters = ocfs2_cow_align_length(inode->i_sb,
2644                                                                want_clusters);
2645                         if (*cow_start + want_clusters <= rec_end)
2646                                 *cow_len = want_clusters;
2647                         else
2648                                 *cow_len = rec_end - *cow_start;
2649                 }
2650
2651                 /* Have we covered our entire write yet? */
2652                 if ((*cow_start + *cow_len) >= (cpos + write_len))
2653                         break;
2654
2655                 /*
2656                  * If we reach the end of the extent block and don't get enough
2657                  * clusters, continue with the next extent block if possible.
2658                  */
2659                 if (i + 1 == le16_to_cpu(el->l_next_free_rec) &&
2660                     eb && eb->h_next_leaf_blk) {
2661                         brelse(eb_bh);
2662                         eb_bh = NULL;
2663
2664                         ret = ocfs2_read_extent_block(INODE_CACHE(inode),
2665                                                le64_to_cpu(eb->h_next_leaf_blk),
2666                                                &eb_bh);
2667                         if (ret) {
2668                                 mlog_errno(ret);
2669                                 goto out;
2670                         }
2671
2672                         eb = (struct ocfs2_extent_block *) eb_bh->b_data;
2673                         el = &eb->h_list;
2674                         i = -1;
2675                 }
2676         }
2677
2678 out:
2679         brelse(eb_bh);
2680         return ret;
2681 }
2682
2683 /*
2684  * Prepare meta_ac, data_ac and calculate credits when we want to add some
2685  * num_clusters in data_tree "et" and change the refcount for the old
2686  * clusters(starting form p_cluster) in the refcount tree.
2687  *
2688  * Note:
2689  * 1. since we may split the old tree, so we at most will need num_clusters + 2
2690  *    more new leaf records.
2691  * 2. In some case, we may not need to reserve new clusters(e.g, reflink), so
2692  *    just give data_ac = NULL.
2693  */
2694 static int ocfs2_lock_refcount_allocators(struct super_block *sb,
2695                                         u32 p_cluster, u32 num_clusters,
2696                                         struct ocfs2_extent_tree *et,
2697                                         struct ocfs2_caching_info *ref_ci,
2698                                         struct buffer_head *ref_root_bh,
2699                                         struct ocfs2_alloc_context **meta_ac,
2700                                         struct ocfs2_alloc_context **data_ac,
2701                                         int *credits)
2702 {
2703         int ret = 0, meta_add = 0;
2704         int num_free_extents = ocfs2_num_free_extents(OCFS2_SB(sb), et);
2705
2706         if (num_free_extents < 0) {
2707                 ret = num_free_extents;
2708                 mlog_errno(ret);
2709                 goto out;
2710         }
2711
2712         if (num_free_extents < num_clusters + 2)
2713                 meta_add =
2714                         ocfs2_extend_meta_needed(et->et_root_el);
2715
2716         *credits += ocfs2_calc_extend_credits(sb, et->et_root_el,
2717                                               num_clusters + 2);
2718
2719         ret = ocfs2_calc_refcount_meta_credits(sb, ref_ci, ref_root_bh,
2720                                                p_cluster, num_clusters,
2721                                                &meta_add, credits);
2722         if (ret) {
2723                 mlog_errno(ret);
2724                 goto out;
2725         }
2726
2727         mlog(0, "reserve new metadata %d, clusters %u, credits = %d\n",
2728              meta_add, num_clusters, *credits);
2729         ret = ocfs2_reserve_new_metadata_blocks(OCFS2_SB(sb), meta_add,
2730                                                 meta_ac);
2731         if (ret) {
2732                 mlog_errno(ret);
2733                 goto out;
2734         }
2735
2736         if (data_ac) {
2737                 ret = ocfs2_reserve_clusters(OCFS2_SB(sb), num_clusters,
2738                                              data_ac);
2739                 if (ret)
2740                         mlog_errno(ret);
2741         }
2742
2743 out:
2744         if (ret) {
2745                 if (*meta_ac) {
2746                         ocfs2_free_alloc_context(*meta_ac);
2747                         *meta_ac = NULL;
2748                 }
2749         }
2750
2751         return ret;
2752 }
2753
2754 static int ocfs2_clear_cow_buffer(handle_t *handle, struct buffer_head *bh)
2755 {
2756         BUG_ON(buffer_dirty(bh));
2757
2758         clear_buffer_mapped(bh);
2759
2760         return 0;
2761 }
2762
2763 static int ocfs2_duplicate_clusters(handle_t *handle,
2764                                     struct ocfs2_cow_context *context,
2765                                     u32 cpos, u32 old_cluster,
2766                                     u32 new_cluster, u32 new_len)
2767 {
2768         int ret = 0, partial;
2769         struct ocfs2_caching_info *ci = context->di_et.et_ci;
2770         struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
2771         u64 new_block = ocfs2_clusters_to_blocks(sb, new_cluster);
2772         struct page *page;
2773         pgoff_t page_index;
2774         unsigned int from, to;
2775         loff_t offset, end, map_end;
2776         struct address_space *mapping = context->inode->i_mapping;
2777
2778         mlog(0, "old_cluster %u, new %u, len %u at offset %u\n", old_cluster,
2779              new_cluster, new_len, cpos);
2780
2781         offset = ((loff_t)cpos) << OCFS2_SB(sb)->s_clustersize_bits;
2782         end = offset + (new_len << OCFS2_SB(sb)->s_clustersize_bits);
2783
2784         while (offset < end) {
2785                 page_index = offset >> PAGE_CACHE_SHIFT;
2786                 map_end = (page_index + 1) << PAGE_CACHE_SHIFT;
2787                 if (map_end > end)
2788                         map_end = end;
2789
2790                 /* from, to is the offset within the page. */
2791                 from = offset & (PAGE_CACHE_SIZE - 1);
2792                 to = PAGE_CACHE_SIZE;
2793                 if (map_end & (PAGE_CACHE_SIZE - 1))
2794                         to = map_end & (PAGE_CACHE_SIZE - 1);
2795
2796                 page = grab_cache_page(mapping, page_index);
2797
2798                 /* This page can't be dirtied before we CoW it out. */
2799                 BUG_ON(PageDirty(page));
2800
2801                 if (!PageUptodate(page)) {
2802                         ret = block_read_full_page(page, ocfs2_get_block);
2803                         if (ret) {
2804                                 mlog_errno(ret);
2805                                 goto unlock;
2806                         }
2807                         lock_page(page);
2808                 }
2809
2810                 if (page_has_buffers(page)) {
2811                         ret = walk_page_buffers(handle, page_buffers(page),
2812                                                 from, to, &partial,
2813                                                 ocfs2_clear_cow_buffer);
2814                         if (ret) {
2815                                 mlog_errno(ret);
2816                                 goto unlock;
2817                         }
2818                 }
2819
2820                 ocfs2_map_and_dirty_page(context->inode,
2821                                          handle, from, to,
2822                                          page, 0, &new_block);
2823                 mark_page_accessed(page);
2824 unlock:
2825                 unlock_page(page);
2826                 page_cache_release(page);
2827                 page = NULL;
2828                 offset = map_end;
2829                 if (ret)
2830                         break;
2831         }
2832
2833         return ret;
2834 }
2835
2836 static int ocfs2_clear_ext_refcount(handle_t *handle,
2837                                     struct ocfs2_extent_tree *et,
2838                                     u32 cpos, u32 p_cluster, u32 len,
2839                                     unsigned int ext_flags,
2840                                     struct ocfs2_alloc_context *meta_ac,
2841                                     struct ocfs2_cached_dealloc_ctxt *dealloc)
2842 {
2843         int ret, index;
2844         struct ocfs2_extent_rec replace_rec;
2845         struct ocfs2_path *path = NULL;
2846         struct ocfs2_extent_list *el;
2847         struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
2848         u64 ino = ocfs2_metadata_cache_owner(et->et_ci);
2849
2850         mlog(0, "inode %llu cpos %u, len %u, p_cluster %u, ext_flags %u\n",
2851              (unsigned long long)ino, cpos, len, p_cluster, ext_flags);
2852
2853         memset(&replace_rec, 0, sizeof(replace_rec));
2854         replace_rec.e_cpos = cpu_to_le32(cpos);
2855         replace_rec.e_leaf_clusters = cpu_to_le16(len);
2856         replace_rec.e_blkno = cpu_to_le64(ocfs2_clusters_to_blocks(sb,
2857                                                                    p_cluster));
2858         replace_rec.e_flags = ext_flags;
2859         replace_rec.e_flags &= ~OCFS2_EXT_REFCOUNTED;
2860
2861         path = ocfs2_new_path_from_et(et);
2862         if (!path) {
2863                 ret = -ENOMEM;
2864                 mlog_errno(ret);
2865                 goto out;
2866         }
2867
2868         ret = ocfs2_find_path(et->et_ci, path, cpos);
2869         if (ret) {
2870                 mlog_errno(ret);
2871                 goto out;
2872         }
2873
2874         el = path_leaf_el(path);
2875
2876         index = ocfs2_search_extent_list(el, cpos);
2877         if (index == -1 || index >= le16_to_cpu(el->l_next_free_rec)) {
2878                 ocfs2_error(sb,
2879                             "Inode %llu has an extent at cpos %u which can no "
2880                             "longer be found.\n",
2881                             (unsigned long long)ino, cpos);
2882                 ret = -EROFS;
2883                 goto out;
2884         }
2885
2886         ret = ocfs2_split_extent(handle, et, path, index,
2887                                  &replace_rec, meta_ac, dealloc);
2888         if (ret)
2889                 mlog_errno(ret);
2890
2891 out:
2892         ocfs2_free_path(path);
2893         return ret;
2894 }
2895
2896 static int ocfs2_replace_clusters(handle_t *handle,
2897                                   struct ocfs2_cow_context *context,
2898                                   u32 cpos, u32 old,
2899                                   u32 new, u32 len,
2900                                   unsigned int ext_flags)
2901 {
2902         int ret;
2903         struct ocfs2_caching_info *ci = context->di_et.et_ci;
2904         u64 ino = ocfs2_metadata_cache_owner(ci);
2905
2906         mlog(0, "inode %llu, cpos %u, old %u, new %u, len %u, ext_flags %u\n",
2907              (unsigned long long)ino, cpos, old, new, len, ext_flags);
2908
2909         /*If the old clusters is unwritten, no need to duplicate. */
2910         if (!(ext_flags & OCFS2_EXT_UNWRITTEN)) {
2911                 ret = ocfs2_duplicate_clusters(handle, context, cpos,
2912                                                old, new, len);
2913                 if (ret) {
2914                         mlog_errno(ret);
2915                         goto out;
2916                 }
2917         }
2918
2919         ret = ocfs2_clear_ext_refcount(handle, &context->di_et,
2920                                        cpos, new, len, ext_flags,
2921                                        context->meta_ac, &context->dealloc);
2922         if (ret)
2923                 mlog_errno(ret);
2924 out:
2925         return ret;
2926 }
2927
2928 static int ocfs2_cow_sync_writeback(struct super_block *sb,
2929                                     struct ocfs2_cow_context *context,
2930                                     u32 cpos, u32 num_clusters)
2931 {
2932         int ret = 0;
2933         loff_t offset, end, map_end;
2934         pgoff_t page_index;
2935         struct page *page;
2936
2937         if (ocfs2_should_order_data(context->inode))
2938                 return 0;
2939
2940         offset = ((loff_t)cpos) << OCFS2_SB(sb)->s_clustersize_bits;
2941         end = offset + (num_clusters << OCFS2_SB(sb)->s_clustersize_bits);
2942
2943         ret = filemap_fdatawrite_range(context->inode->i_mapping,
2944                                        offset, end - 1);
2945         if (ret < 0) {
2946                 mlog_errno(ret);
2947                 return ret;
2948         }
2949
2950         while (offset < end) {
2951                 page_index = offset >> PAGE_CACHE_SHIFT;
2952                 map_end = (page_index + 1) << PAGE_CACHE_SHIFT;
2953                 if (map_end > end)
2954                         map_end = end;
2955
2956                 page = grab_cache_page(context->inode->i_mapping, page_index);
2957                 BUG_ON(!page);
2958
2959                 wait_on_page_writeback(page);
2960                 if (PageError(page)) {
2961                         ret = -EIO;
2962                         mlog_errno(ret);
2963                 } else
2964                         mark_page_accessed(page);
2965
2966                 unlock_page(page);
2967                 page_cache_release(page);
2968                 page = NULL;
2969                 offset = map_end;
2970                 if (ret)
2971                         break;
2972         }
2973
2974         return ret;
2975 }
2976
2977 static int ocfs2_make_clusters_writable(struct super_block *sb,
2978                                         struct ocfs2_cow_context *context,
2979                                         u32 cpos, u32 p_cluster,
2980                                         u32 num_clusters, unsigned int e_flags)
2981 {
2982         int ret, delete, index, credits =  0;
2983         u32 new_bit, new_len;
2984         unsigned int set_len;
2985         struct ocfs2_super *osb = OCFS2_SB(sb);
2986         handle_t *handle;
2987         struct buffer_head *ref_leaf_bh = NULL;
2988         struct ocfs2_refcount_rec rec;
2989
2990         mlog(0, "cpos %u, p_cluster %u, num_clusters %u, e_flags %u\n",
2991              cpos, p_cluster, num_clusters, e_flags);
2992
2993         ret = ocfs2_lock_refcount_allocators(sb, p_cluster, num_clusters,
2994                                              &context->di_et,
2995                                              context->ref_ci,
2996                                              context->ref_root_bh,
2997                                              &context->meta_ac,
2998                                              &context->data_ac, &credits);
2999         if (ret) {
3000                 mlog_errno(ret);
3001                 return ret;
3002         }
3003
3004         handle = ocfs2_start_trans(osb, credits);
3005         if (IS_ERR(handle)) {
3006                 ret = PTR_ERR(handle);
3007                 mlog_errno(ret);
3008                 goto out;
3009         }
3010
3011         while (num_clusters) {
3012                 ret = ocfs2_get_refcount_rec(context->ref_ci,
3013                                              context->ref_root_bh,
3014                                              p_cluster, num_clusters,
3015                                              &rec, &index, &ref_leaf_bh);
3016                 if (ret) {
3017                         mlog_errno(ret);
3018                         goto out_commit;
3019                 }
3020
3021                 BUG_ON(!rec.r_refcount);
3022                 set_len = min((u64)p_cluster + num_clusters,
3023                               le64_to_cpu(rec.r_cpos) +
3024                               le32_to_cpu(rec.r_clusters)) - p_cluster;
3025
3026                 /*
3027                  * There are many different situation here.
3028                  * 1. If refcount == 1, remove the flag and don't COW.
3029                  * 2. If refcount > 1, allocate clusters.
3030                  *    Here we may not allocate r_len once at a time, so continue
3031                  *    until we reach num_clusters.
3032                  */
3033                 if (le32_to_cpu(rec.r_refcount) == 1) {
3034                         delete = 0;
3035                         ret = ocfs2_clear_ext_refcount(handle, &context->di_et,
3036                                                        cpos, p_cluster,
3037                                                        set_len, e_flags,
3038                                                        context->meta_ac,
3039                                                        &context->dealloc);
3040                         if (ret) {
3041                                 mlog_errno(ret);
3042                                 goto out_commit;
3043                         }
3044                 } else {
3045                         delete = 1;
3046
3047                         ret = __ocfs2_claim_clusters(osb, handle,
3048                                                      context->data_ac,
3049                                                      1, set_len,
3050                                                      &new_bit, &new_len);
3051                         if (ret) {
3052                                 mlog_errno(ret);
3053                                 goto out_commit;
3054                         }
3055
3056                         ret = ocfs2_replace_clusters(handle, context,
3057                                                      cpos, p_cluster, new_bit,
3058                                                      new_len, e_flags);
3059                         if (ret) {
3060                                 mlog_errno(ret);
3061                                 goto out_commit;
3062                         }
3063                         set_len = new_len;
3064                 }
3065
3066                 ret = __ocfs2_decrease_refcount(handle, context->ref_ci,
3067                                                 context->ref_root_bh,
3068                                                 p_cluster, set_len,
3069                                                 context->meta_ac,
3070                                                 &context->dealloc, delete);
3071                 if (ret) {
3072                         mlog_errno(ret);
3073                         goto out_commit;
3074                 }
3075
3076                 cpos += set_len;
3077                 p_cluster += set_len;
3078                 num_clusters -= set_len;
3079                 brelse(ref_leaf_bh);
3080                 ref_leaf_bh = NULL;
3081         }
3082
3083         /*
3084          * Here we should write the new page out first if we are
3085          * in write-back mode.
3086          */
3087         ret = ocfs2_cow_sync_writeback(sb, context, cpos, num_clusters);
3088         if (ret)
3089                 mlog_errno(ret);
3090
3091 out_commit:
3092         ocfs2_commit_trans(osb, handle);
3093
3094 out:
3095         if (context->data_ac) {
3096                 ocfs2_free_alloc_context(context->data_ac);
3097                 context->data_ac = NULL;
3098         }
3099         if (context->meta_ac) {
3100                 ocfs2_free_alloc_context(context->meta_ac);
3101                 context->meta_ac = NULL;
3102         }
3103         brelse(ref_leaf_bh);
3104
3105         return ret;
3106 }
3107
3108 static int ocfs2_replace_cow(struct inode *inode,
3109                              struct buffer_head *di_bh,
3110                              struct buffer_head *ref_root_bh,
3111                              struct ocfs2_caching_info *ref_ci,
3112                              u32 cow_start, u32 cow_len)
3113 {
3114         int ret = 0;
3115         u32 p_cluster, num_clusters, start = cow_start;
3116         unsigned int ext_flags;
3117         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3118         struct ocfs2_cow_context *context;
3119
3120         if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb))) {
3121                 ocfs2_error(inode->i_sb, "Inode %lu want to use refcount "
3122                             "tree, but the feature bit is not set in the "
3123                             "super block.", inode->i_ino);
3124                 return -EROFS;
3125         }
3126
3127         context = kzalloc(sizeof(struct ocfs2_cow_context), GFP_NOFS);
3128         if (!context) {
3129                 ret = -ENOMEM;
3130                 mlog_errno(ret);
3131                 return ret;
3132         }
3133
3134         context->inode = inode;
3135         context->cow_start = cow_start;
3136         context->cow_len = cow_len;
3137         context->ref_ci = ref_ci;
3138         context->ref_root_bh = ref_root_bh;
3139
3140         ocfs2_init_dealloc_ctxt(&context->dealloc);
3141         ocfs2_init_dinode_extent_tree(&context->di_et,
3142                                       INODE_CACHE(inode), di_bh);
3143
3144         while (cow_len) {
3145                 ret = ocfs2_get_clusters(inode, cow_start, &p_cluster,
3146                                          &num_clusters, &ext_flags);
3147                 if (ret) {
3148                         mlog_errno(ret);
3149                         break;
3150                 }
3151
3152                 BUG_ON(!(ext_flags & OCFS2_EXT_REFCOUNTED));
3153
3154                 if (cow_len < num_clusters)
3155                         num_clusters = cow_len;
3156
3157                 ret = ocfs2_make_clusters_writable(inode->i_sb, context,
3158                                                    cow_start, p_cluster,
3159                                                    num_clusters, ext_flags);
3160                 if (ret) {
3161                         mlog_errno(ret);
3162                         break;
3163                 }
3164
3165                 cow_len -= num_clusters;
3166                 cow_start += num_clusters;
3167         }
3168
3169
3170         /*
3171          * truncate the extent map here since no matter whether we meet with
3172          * any error during the action, we shouldn't trust cached extent map
3173          * any more.
3174          */
3175         ocfs2_extent_map_trunc(inode, start);
3176
3177         if (ocfs2_dealloc_has_cluster(&context->dealloc)) {
3178                 ocfs2_schedule_truncate_log_flush(osb, 1);
3179                 ocfs2_run_deallocs(osb, &context->dealloc);
3180         }
3181
3182         kfree(context);
3183         return ret;
3184 }
3185
3186 /*
3187  * Starting at cpos, try to CoW write_len clusters.
3188  * This will stop when it runs into a hole or an unrefcounted extent.
3189  */
3190 static int ocfs2_refcount_cow_hunk(struct inode *inode,
3191                                    struct buffer_head *di_bh,
3192                                    u32 cpos, u32 write_len)
3193 {
3194         int ret;
3195         u32 cow_start = 0, cow_len = 0;
3196         struct ocfs2_inode_info *oi = OCFS2_I(inode);
3197         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3198         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
3199         struct buffer_head *ref_root_bh = NULL;
3200         struct ocfs2_refcount_tree *ref_tree;
3201
3202         BUG_ON(!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
3203
3204         ret = ocfs2_refcount_cal_cow_clusters(inode, di_bh, cpos, write_len,
3205                                               &cow_start, &cow_len);
3206         if (ret) {
3207                 mlog_errno(ret);
3208                 goto out;
3209         }
3210         mlog(0, "CoW inode %lu, cpos %u, write_len %u, cow_start %u, "
3211              "cow_len %u\n", inode->i_ino,
3212              cpos, write_len, cow_start, cow_len);
3213
3214         BUG_ON(cow_len == 0);
3215
3216         ret = ocfs2_lock_refcount_tree(osb, le64_to_cpu(di->i_refcount_loc),
3217                                        1, &ref_tree, &ref_root_bh);
3218         if (ret) {
3219                 mlog_errno(ret);
3220                 goto out;
3221         }
3222
3223         ret = ocfs2_replace_cow(inode, di_bh, ref_root_bh, &ref_tree->rf_ci,
3224                                 cow_start, cow_len);
3225         if (ret)
3226                 mlog_errno(ret);
3227
3228         ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
3229         brelse(ref_root_bh);
3230 out:
3231         return ret;
3232 }
3233
3234 /*
3235  * CoW any and all clusters between cpos and cpos+write_len.
3236  * If this returns successfully, all clusters between cpos and
3237  * cpos+write_len are safe to modify.
3238  */
3239 int ocfs2_refcount_cow(struct inode *inode,
3240                        struct buffer_head *di_bh,
3241                        u32 cpos, u32 write_len)
3242 {
3243         int ret = 0;
3244         u32 p_cluster, num_clusters;
3245         unsigned int ext_flags;
3246
3247         while (write_len) {
3248                 ret = ocfs2_get_clusters(inode, cpos, &p_cluster,
3249                                          &num_clusters, &ext_flags);
3250                 if (ret) {
3251                         mlog_errno(ret);
3252                         break;
3253                 }
3254
3255                 if (write_len < num_clusters)
3256                         num_clusters = write_len;
3257
3258                 if (ext_flags & OCFS2_EXT_REFCOUNTED) {
3259                         ret = ocfs2_refcount_cow_hunk(inode, di_bh, cpos,
3260                                                       num_clusters);
3261                         if (ret) {
3262                                 mlog_errno(ret);
3263                                 break;
3264                         }
3265                 }
3266
3267                 write_len -= num_clusters;
3268                 cpos += num_clusters;
3269         }
3270
3271         return ret;
3272 }