ocfs2: Add normal functions for reflink a normal file's extents.
[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  * max_cpos is the place where we want to stop CoW intentionally.
2486  *
2487  * Normal we will start CoW from the beginning of extent record cotaining cpos.
2488  * We try to break up extents on boundaries of MAX_CONTIG_BYTES so that we
2489  * get good I/O from the resulting extent tree.
2490  */
2491 static int ocfs2_refcount_cal_cow_clusters(struct inode *inode,
2492                                            struct buffer_head *di_bh,
2493                                            u32 cpos,
2494                                            u32 write_len,
2495                                            u32 max_cpos,
2496                                            u32 *cow_start,
2497                                            u32 *cow_len)
2498 {
2499         int ret = 0;
2500         struct ocfs2_dinode *di = (struct ocfs2_dinode *) di_bh->b_data;
2501         struct ocfs2_extent_list *el = &di->id2.i_list;
2502         int tree_height = le16_to_cpu(el->l_tree_depth), i;
2503         struct buffer_head *eb_bh = NULL;
2504         struct ocfs2_extent_block *eb = NULL;
2505         struct ocfs2_extent_rec *rec;
2506         unsigned int want_clusters, rec_end = 0;
2507         int contig_clusters = ocfs2_cow_contig_clusters(inode->i_sb);
2508         int leaf_clusters;
2509
2510         BUG_ON(cpos + write_len > max_cpos);
2511
2512         if (tree_height > 0) {
2513                 ret = ocfs2_find_leaf(INODE_CACHE(inode), el, cpos, &eb_bh);
2514                 if (ret) {
2515                         mlog_errno(ret);
2516                         goto out;
2517                 }
2518
2519                 eb = (struct ocfs2_extent_block *) eb_bh->b_data;
2520                 el = &eb->h_list;
2521
2522                 if (el->l_tree_depth) {
2523                         ocfs2_error(inode->i_sb,
2524                                     "Inode %lu has non zero tree depth in "
2525                                     "leaf block %llu\n", inode->i_ino,
2526                                     (unsigned long long)eb_bh->b_blocknr);
2527                         ret = -EROFS;
2528                         goto out;
2529                 }
2530         }
2531
2532         *cow_len = 0;
2533         for (i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
2534                 rec = &el->l_recs[i];
2535
2536                 if (ocfs2_is_empty_extent(rec)) {
2537                         mlog_bug_on_msg(i != 0, "Inode %lu has empty record in "
2538                                         "index %d\n", inode->i_ino, i);
2539                         continue;
2540                 }
2541
2542                 if (le32_to_cpu(rec->e_cpos) +
2543                     le16_to_cpu(rec->e_leaf_clusters) <= cpos)
2544                         continue;
2545
2546                 if (*cow_len == 0) {
2547                         /*
2548                          * We should find a refcounted record in the
2549                          * first pass.
2550                          */
2551                         BUG_ON(!(rec->e_flags & OCFS2_EXT_REFCOUNTED));
2552                         *cow_start = le32_to_cpu(rec->e_cpos);
2553                 }
2554
2555                 /*
2556                  * If we encounter a hole, a non-refcounted record or
2557                  * pass the max_cpos, stop the search.
2558                  */
2559                 if ((!(rec->e_flags & OCFS2_EXT_REFCOUNTED)) ||
2560                     (*cow_len && rec_end != le32_to_cpu(rec->e_cpos)) ||
2561                     (max_cpos <= le32_to_cpu(rec->e_cpos)))
2562                         break;
2563
2564                 leaf_clusters = le16_to_cpu(rec->e_leaf_clusters);
2565                 rec_end = le32_to_cpu(rec->e_cpos) + leaf_clusters;
2566                 if (rec_end > max_cpos) {
2567                         rec_end = max_cpos;
2568                         leaf_clusters = rec_end - le32_to_cpu(rec->e_cpos);
2569                 }
2570
2571                 /*
2572                  * How many clusters do we actually need from
2573                  * this extent?  First we see how many we actually
2574                  * need to complete the write.  If that's smaller
2575                  * than contig_clusters, we try for contig_clusters.
2576                  */
2577                 if (!*cow_len)
2578                         want_clusters = write_len;
2579                 else
2580                         want_clusters = (cpos + write_len) -
2581                                 (*cow_start + *cow_len);
2582                 if (want_clusters < contig_clusters)
2583                         want_clusters = contig_clusters;
2584
2585                 /*
2586                  * If the write does not cover the whole extent, we
2587                  * need to calculate how we're going to split the extent.
2588                  * We try to do it on contig_clusters boundaries.
2589                  *
2590                  * Any extent smaller than contig_clusters will be
2591                  * CoWed in its entirety.
2592                  */
2593                 if (leaf_clusters <= contig_clusters)
2594                         *cow_len += leaf_clusters;
2595                 else if (*cow_len || (*cow_start == cpos)) {
2596                         /*
2597                          * This extent needs to be CoW'd from its
2598                          * beginning, so all we have to do is compute
2599                          * how many clusters to grab.  We align
2600                          * want_clusters to the edge of contig_clusters
2601                          * to get better I/O.
2602                          */
2603                         want_clusters = ocfs2_cow_align_length(inode->i_sb,
2604                                                                want_clusters);
2605
2606                         if (leaf_clusters < want_clusters)
2607                                 *cow_len += leaf_clusters;
2608                         else
2609                                 *cow_len += want_clusters;
2610                 } else if ((*cow_start + contig_clusters) >=
2611                            (cpos + write_len)) {
2612                         /*
2613                          * Breaking off contig_clusters at the front
2614                          * of the extent will cover our write.  That's
2615                          * easy.
2616                          */
2617                         *cow_len = contig_clusters;
2618                 } else if ((rec_end - cpos) <= contig_clusters) {
2619                         /*
2620                          * Breaking off contig_clusters at the tail of
2621                          * this extent will cover cpos.
2622                          */
2623                         *cow_start = rec_end - contig_clusters;
2624                         *cow_len = contig_clusters;
2625                 } else if ((rec_end - cpos) <= want_clusters) {
2626                         /*
2627                          * While we can't fit the entire write in this
2628                          * extent, we know that the write goes from cpos
2629                          * to the end of the extent.  Break that off.
2630                          * We try to break it at some multiple of
2631                          * contig_clusters from the front of the extent.
2632                          * Failing that (ie, cpos is within
2633                          * contig_clusters of the front), we'll CoW the
2634                          * entire extent.
2635                          */
2636                         *cow_start = ocfs2_cow_align_start(inode->i_sb,
2637                                                            *cow_start, cpos);
2638                         *cow_len = rec_end - *cow_start;
2639                 } else {
2640                         /*
2641                          * Ok, the entire write lives in the middle of
2642                          * this extent.  Let's try to slice the extent up
2643                          * nicely.  Optimally, our CoW region starts at
2644                          * m*contig_clusters from the beginning of the
2645                          * extent and goes for n*contig_clusters,
2646                          * covering the entire write.
2647                          */
2648                         *cow_start = ocfs2_cow_align_start(inode->i_sb,
2649                                                            *cow_start, cpos);
2650
2651                         want_clusters = (cpos + write_len) - *cow_start;
2652                         want_clusters = ocfs2_cow_align_length(inode->i_sb,
2653                                                                want_clusters);
2654                         if (*cow_start + want_clusters <= rec_end)
2655                                 *cow_len = want_clusters;
2656                         else
2657                                 *cow_len = rec_end - *cow_start;
2658                 }
2659
2660                 /* Have we covered our entire write yet? */
2661                 if ((*cow_start + *cow_len) >= (cpos + write_len))
2662                         break;
2663
2664                 /*
2665                  * If we reach the end of the extent block and don't get enough
2666                  * clusters, continue with the next extent block if possible.
2667                  */
2668                 if (i + 1 == le16_to_cpu(el->l_next_free_rec) &&
2669                     eb && eb->h_next_leaf_blk) {
2670                         brelse(eb_bh);
2671                         eb_bh = NULL;
2672
2673                         ret = ocfs2_read_extent_block(INODE_CACHE(inode),
2674                                                le64_to_cpu(eb->h_next_leaf_blk),
2675                                                &eb_bh);
2676                         if (ret) {
2677                                 mlog_errno(ret);
2678                                 goto out;
2679                         }
2680
2681                         eb = (struct ocfs2_extent_block *) eb_bh->b_data;
2682                         el = &eb->h_list;
2683                         i = -1;
2684                 }
2685         }
2686
2687 out:
2688         brelse(eb_bh);
2689         return ret;
2690 }
2691
2692 /*
2693  * Prepare meta_ac, data_ac and calculate credits when we want to add some
2694  * num_clusters in data_tree "et" and change the refcount for the old
2695  * clusters(starting form p_cluster) in the refcount tree.
2696  *
2697  * Note:
2698  * 1. since we may split the old tree, so we at most will need num_clusters + 2
2699  *    more new leaf records.
2700  * 2. In some case, we may not need to reserve new clusters(e.g, reflink), so
2701  *    just give data_ac = NULL.
2702  */
2703 static int ocfs2_lock_refcount_allocators(struct super_block *sb,
2704                                         u32 p_cluster, u32 num_clusters,
2705                                         struct ocfs2_extent_tree *et,
2706                                         struct ocfs2_caching_info *ref_ci,
2707                                         struct buffer_head *ref_root_bh,
2708                                         struct ocfs2_alloc_context **meta_ac,
2709                                         struct ocfs2_alloc_context **data_ac,
2710                                         int *credits)
2711 {
2712         int ret = 0, meta_add = 0;
2713         int num_free_extents = ocfs2_num_free_extents(OCFS2_SB(sb), et);
2714
2715         if (num_free_extents < 0) {
2716                 ret = num_free_extents;
2717                 mlog_errno(ret);
2718                 goto out;
2719         }
2720
2721         if (num_free_extents < num_clusters + 2)
2722                 meta_add =
2723                         ocfs2_extend_meta_needed(et->et_root_el);
2724
2725         *credits += ocfs2_calc_extend_credits(sb, et->et_root_el,
2726                                               num_clusters + 2);
2727
2728         ret = ocfs2_calc_refcount_meta_credits(sb, ref_ci, ref_root_bh,
2729                                                p_cluster, num_clusters,
2730                                                &meta_add, credits);
2731         if (ret) {
2732                 mlog_errno(ret);
2733                 goto out;
2734         }
2735
2736         mlog(0, "reserve new metadata %d, clusters %u, credits = %d\n",
2737              meta_add, num_clusters, *credits);
2738         ret = ocfs2_reserve_new_metadata_blocks(OCFS2_SB(sb), meta_add,
2739                                                 meta_ac);
2740         if (ret) {
2741                 mlog_errno(ret);
2742                 goto out;
2743         }
2744
2745         if (data_ac) {
2746                 ret = ocfs2_reserve_clusters(OCFS2_SB(sb), num_clusters,
2747                                              data_ac);
2748                 if (ret)
2749                         mlog_errno(ret);
2750         }
2751
2752 out:
2753         if (ret) {
2754                 if (*meta_ac) {
2755                         ocfs2_free_alloc_context(*meta_ac);
2756                         *meta_ac = NULL;
2757                 }
2758         }
2759
2760         return ret;
2761 }
2762
2763 static int ocfs2_clear_cow_buffer(handle_t *handle, struct buffer_head *bh)
2764 {
2765         BUG_ON(buffer_dirty(bh));
2766
2767         clear_buffer_mapped(bh);
2768
2769         return 0;
2770 }
2771
2772 static int ocfs2_duplicate_clusters(handle_t *handle,
2773                                     struct ocfs2_cow_context *context,
2774                                     u32 cpos, u32 old_cluster,
2775                                     u32 new_cluster, u32 new_len)
2776 {
2777         int ret = 0, partial;
2778         struct ocfs2_caching_info *ci = context->di_et.et_ci;
2779         struct super_block *sb = ocfs2_metadata_cache_get_super(ci);
2780         u64 new_block = ocfs2_clusters_to_blocks(sb, new_cluster);
2781         struct page *page;
2782         pgoff_t page_index;
2783         unsigned int from, to;
2784         loff_t offset, end, map_end;
2785         struct address_space *mapping = context->inode->i_mapping;
2786
2787         mlog(0, "old_cluster %u, new %u, len %u at offset %u\n", old_cluster,
2788              new_cluster, new_len, cpos);
2789
2790         offset = ((loff_t)cpos) << OCFS2_SB(sb)->s_clustersize_bits;
2791         end = offset + (new_len << OCFS2_SB(sb)->s_clustersize_bits);
2792
2793         while (offset < end) {
2794                 page_index = offset >> PAGE_CACHE_SHIFT;
2795                 map_end = (page_index + 1) << PAGE_CACHE_SHIFT;
2796                 if (map_end > end)
2797                         map_end = end;
2798
2799                 /* from, to is the offset within the page. */
2800                 from = offset & (PAGE_CACHE_SIZE - 1);
2801                 to = PAGE_CACHE_SIZE;
2802                 if (map_end & (PAGE_CACHE_SIZE - 1))
2803                         to = map_end & (PAGE_CACHE_SIZE - 1);
2804
2805                 page = grab_cache_page(mapping, page_index);
2806
2807                 /* This page can't be dirtied before we CoW it out. */
2808                 BUG_ON(PageDirty(page));
2809
2810                 if (!PageUptodate(page)) {
2811                         ret = block_read_full_page(page, ocfs2_get_block);
2812                         if (ret) {
2813                                 mlog_errno(ret);
2814                                 goto unlock;
2815                         }
2816                         lock_page(page);
2817                 }
2818
2819                 if (page_has_buffers(page)) {
2820                         ret = walk_page_buffers(handle, page_buffers(page),
2821                                                 from, to, &partial,
2822                                                 ocfs2_clear_cow_buffer);
2823                         if (ret) {
2824                                 mlog_errno(ret);
2825                                 goto unlock;
2826                         }
2827                 }
2828
2829                 ocfs2_map_and_dirty_page(context->inode,
2830                                          handle, from, to,
2831                                          page, 0, &new_block);
2832                 mark_page_accessed(page);
2833 unlock:
2834                 unlock_page(page);
2835                 page_cache_release(page);
2836                 page = NULL;
2837                 offset = map_end;
2838                 if (ret)
2839                         break;
2840         }
2841
2842         return ret;
2843 }
2844
2845 static int ocfs2_clear_ext_refcount(handle_t *handle,
2846                                     struct ocfs2_extent_tree *et,
2847                                     u32 cpos, u32 p_cluster, u32 len,
2848                                     unsigned int ext_flags,
2849                                     struct ocfs2_alloc_context *meta_ac,
2850                                     struct ocfs2_cached_dealloc_ctxt *dealloc)
2851 {
2852         int ret, index;
2853         struct ocfs2_extent_rec replace_rec;
2854         struct ocfs2_path *path = NULL;
2855         struct ocfs2_extent_list *el;
2856         struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
2857         u64 ino = ocfs2_metadata_cache_owner(et->et_ci);
2858
2859         mlog(0, "inode %llu cpos %u, len %u, p_cluster %u, ext_flags %u\n",
2860              (unsigned long long)ino, cpos, len, p_cluster, ext_flags);
2861
2862         memset(&replace_rec, 0, sizeof(replace_rec));
2863         replace_rec.e_cpos = cpu_to_le32(cpos);
2864         replace_rec.e_leaf_clusters = cpu_to_le16(len);
2865         replace_rec.e_blkno = cpu_to_le64(ocfs2_clusters_to_blocks(sb,
2866                                                                    p_cluster));
2867         replace_rec.e_flags = ext_flags;
2868         replace_rec.e_flags &= ~OCFS2_EXT_REFCOUNTED;
2869
2870         path = ocfs2_new_path_from_et(et);
2871         if (!path) {
2872                 ret = -ENOMEM;
2873                 mlog_errno(ret);
2874                 goto out;
2875         }
2876
2877         ret = ocfs2_find_path(et->et_ci, path, cpos);
2878         if (ret) {
2879                 mlog_errno(ret);
2880                 goto out;
2881         }
2882
2883         el = path_leaf_el(path);
2884
2885         index = ocfs2_search_extent_list(el, cpos);
2886         if (index == -1 || index >= le16_to_cpu(el->l_next_free_rec)) {
2887                 ocfs2_error(sb,
2888                             "Inode %llu has an extent at cpos %u which can no "
2889                             "longer be found.\n",
2890                             (unsigned long long)ino, cpos);
2891                 ret = -EROFS;
2892                 goto out;
2893         }
2894
2895         ret = ocfs2_split_extent(handle, et, path, index,
2896                                  &replace_rec, meta_ac, dealloc);
2897         if (ret)
2898                 mlog_errno(ret);
2899
2900 out:
2901         ocfs2_free_path(path);
2902         return ret;
2903 }
2904
2905 static int ocfs2_replace_clusters(handle_t *handle,
2906                                   struct ocfs2_cow_context *context,
2907                                   u32 cpos, u32 old,
2908                                   u32 new, u32 len,
2909                                   unsigned int ext_flags)
2910 {
2911         int ret;
2912         struct ocfs2_caching_info *ci = context->di_et.et_ci;
2913         u64 ino = ocfs2_metadata_cache_owner(ci);
2914
2915         mlog(0, "inode %llu, cpos %u, old %u, new %u, len %u, ext_flags %u\n",
2916              (unsigned long long)ino, cpos, old, new, len, ext_flags);
2917
2918         /*If the old clusters is unwritten, no need to duplicate. */
2919         if (!(ext_flags & OCFS2_EXT_UNWRITTEN)) {
2920                 ret = ocfs2_duplicate_clusters(handle, context, cpos,
2921                                                old, new, len);
2922                 if (ret) {
2923                         mlog_errno(ret);
2924                         goto out;
2925                 }
2926         }
2927
2928         ret = ocfs2_clear_ext_refcount(handle, &context->di_et,
2929                                        cpos, new, len, ext_flags,
2930                                        context->meta_ac, &context->dealloc);
2931         if (ret)
2932                 mlog_errno(ret);
2933 out:
2934         return ret;
2935 }
2936
2937 static int ocfs2_cow_sync_writeback(struct super_block *sb,
2938                                     struct ocfs2_cow_context *context,
2939                                     u32 cpos, u32 num_clusters)
2940 {
2941         int ret = 0;
2942         loff_t offset, end, map_end;
2943         pgoff_t page_index;
2944         struct page *page;
2945
2946         if (ocfs2_should_order_data(context->inode))
2947                 return 0;
2948
2949         offset = ((loff_t)cpos) << OCFS2_SB(sb)->s_clustersize_bits;
2950         end = offset + (num_clusters << OCFS2_SB(sb)->s_clustersize_bits);
2951
2952         ret = filemap_fdatawrite_range(context->inode->i_mapping,
2953                                        offset, end - 1);
2954         if (ret < 0) {
2955                 mlog_errno(ret);
2956                 return ret;
2957         }
2958
2959         while (offset < end) {
2960                 page_index = offset >> PAGE_CACHE_SHIFT;
2961                 map_end = (page_index + 1) << PAGE_CACHE_SHIFT;
2962                 if (map_end > end)
2963                         map_end = end;
2964
2965                 page = grab_cache_page(context->inode->i_mapping, page_index);
2966                 BUG_ON(!page);
2967
2968                 wait_on_page_writeback(page);
2969                 if (PageError(page)) {
2970                         ret = -EIO;
2971                         mlog_errno(ret);
2972                 } else
2973                         mark_page_accessed(page);
2974
2975                 unlock_page(page);
2976                 page_cache_release(page);
2977                 page = NULL;
2978                 offset = map_end;
2979                 if (ret)
2980                         break;
2981         }
2982
2983         return ret;
2984 }
2985
2986 static int ocfs2_make_clusters_writable(struct super_block *sb,
2987                                         struct ocfs2_cow_context *context,
2988                                         u32 cpos, u32 p_cluster,
2989                                         u32 num_clusters, unsigned int e_flags)
2990 {
2991         int ret, delete, index, credits =  0;
2992         u32 new_bit, new_len;
2993         unsigned int set_len;
2994         struct ocfs2_super *osb = OCFS2_SB(sb);
2995         handle_t *handle;
2996         struct buffer_head *ref_leaf_bh = NULL;
2997         struct ocfs2_refcount_rec rec;
2998
2999         mlog(0, "cpos %u, p_cluster %u, num_clusters %u, e_flags %u\n",
3000              cpos, p_cluster, num_clusters, e_flags);
3001
3002         ret = ocfs2_lock_refcount_allocators(sb, p_cluster, num_clusters,
3003                                              &context->di_et,
3004                                              context->ref_ci,
3005                                              context->ref_root_bh,
3006                                              &context->meta_ac,
3007                                              &context->data_ac, &credits);
3008         if (ret) {
3009                 mlog_errno(ret);
3010                 return ret;
3011         }
3012
3013         handle = ocfs2_start_trans(osb, credits);
3014         if (IS_ERR(handle)) {
3015                 ret = PTR_ERR(handle);
3016                 mlog_errno(ret);
3017                 goto out;
3018         }
3019
3020         while (num_clusters) {
3021                 ret = ocfs2_get_refcount_rec(context->ref_ci,
3022                                              context->ref_root_bh,
3023                                              p_cluster, num_clusters,
3024                                              &rec, &index, &ref_leaf_bh);
3025                 if (ret) {
3026                         mlog_errno(ret);
3027                         goto out_commit;
3028                 }
3029
3030                 BUG_ON(!rec.r_refcount);
3031                 set_len = min((u64)p_cluster + num_clusters,
3032                               le64_to_cpu(rec.r_cpos) +
3033                               le32_to_cpu(rec.r_clusters)) - p_cluster;
3034
3035                 /*
3036                  * There are many different situation here.
3037                  * 1. If refcount == 1, remove the flag and don't COW.
3038                  * 2. If refcount > 1, allocate clusters.
3039                  *    Here we may not allocate r_len once at a time, so continue
3040                  *    until we reach num_clusters.
3041                  */
3042                 if (le32_to_cpu(rec.r_refcount) == 1) {
3043                         delete = 0;
3044                         ret = ocfs2_clear_ext_refcount(handle, &context->di_et,
3045                                                        cpos, p_cluster,
3046                                                        set_len, e_flags,
3047                                                        context->meta_ac,
3048                                                        &context->dealloc);
3049                         if (ret) {
3050                                 mlog_errno(ret);
3051                                 goto out_commit;
3052                         }
3053                 } else {
3054                         delete = 1;
3055
3056                         ret = __ocfs2_claim_clusters(osb, handle,
3057                                                      context->data_ac,
3058                                                      1, set_len,
3059                                                      &new_bit, &new_len);
3060                         if (ret) {
3061                                 mlog_errno(ret);
3062                                 goto out_commit;
3063                         }
3064
3065                         ret = ocfs2_replace_clusters(handle, context,
3066                                                      cpos, p_cluster, new_bit,
3067                                                      new_len, e_flags);
3068                         if (ret) {
3069                                 mlog_errno(ret);
3070                                 goto out_commit;
3071                         }
3072                         set_len = new_len;
3073                 }
3074
3075                 ret = __ocfs2_decrease_refcount(handle, context->ref_ci,
3076                                                 context->ref_root_bh,
3077                                                 p_cluster, set_len,
3078                                                 context->meta_ac,
3079                                                 &context->dealloc, delete);
3080                 if (ret) {
3081                         mlog_errno(ret);
3082                         goto out_commit;
3083                 }
3084
3085                 cpos += set_len;
3086                 p_cluster += set_len;
3087                 num_clusters -= set_len;
3088                 brelse(ref_leaf_bh);
3089                 ref_leaf_bh = NULL;
3090         }
3091
3092         /*
3093          * Here we should write the new page out first if we are
3094          * in write-back mode.
3095          */
3096         ret = ocfs2_cow_sync_writeback(sb, context, cpos, num_clusters);
3097         if (ret)
3098                 mlog_errno(ret);
3099
3100 out_commit:
3101         ocfs2_commit_trans(osb, handle);
3102
3103 out:
3104         if (context->data_ac) {
3105                 ocfs2_free_alloc_context(context->data_ac);
3106                 context->data_ac = NULL;
3107         }
3108         if (context->meta_ac) {
3109                 ocfs2_free_alloc_context(context->meta_ac);
3110                 context->meta_ac = NULL;
3111         }
3112         brelse(ref_leaf_bh);
3113
3114         return ret;
3115 }
3116
3117 static int ocfs2_replace_cow(struct inode *inode,
3118                              struct buffer_head *di_bh,
3119                              struct buffer_head *ref_root_bh,
3120                              struct ocfs2_caching_info *ref_ci,
3121                              u32 cow_start, u32 cow_len)
3122 {
3123         int ret = 0;
3124         u32 p_cluster, num_clusters, start = cow_start;
3125         unsigned int ext_flags;
3126         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3127         struct ocfs2_cow_context *context;
3128
3129         if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb))) {
3130                 ocfs2_error(inode->i_sb, "Inode %lu want to use refcount "
3131                             "tree, but the feature bit is not set in the "
3132                             "super block.", inode->i_ino);
3133                 return -EROFS;
3134         }
3135
3136         context = kzalloc(sizeof(struct ocfs2_cow_context), GFP_NOFS);
3137         if (!context) {
3138                 ret = -ENOMEM;
3139                 mlog_errno(ret);
3140                 return ret;
3141         }
3142
3143         context->inode = inode;
3144         context->cow_start = cow_start;
3145         context->cow_len = cow_len;
3146         context->ref_ci = ref_ci;
3147         context->ref_root_bh = ref_root_bh;
3148
3149         ocfs2_init_dealloc_ctxt(&context->dealloc);
3150         ocfs2_init_dinode_extent_tree(&context->di_et,
3151                                       INODE_CACHE(inode), di_bh);
3152
3153         while (cow_len) {
3154                 ret = ocfs2_get_clusters(inode, cow_start, &p_cluster,
3155                                          &num_clusters, &ext_flags);
3156                 if (ret) {
3157                         mlog_errno(ret);
3158                         break;
3159                 }
3160
3161                 BUG_ON(!(ext_flags & OCFS2_EXT_REFCOUNTED));
3162
3163                 if (cow_len < num_clusters)
3164                         num_clusters = cow_len;
3165
3166                 ret = ocfs2_make_clusters_writable(inode->i_sb, context,
3167                                                    cow_start, p_cluster,
3168                                                    num_clusters, ext_flags);
3169                 if (ret) {
3170                         mlog_errno(ret);
3171                         break;
3172                 }
3173
3174                 cow_len -= num_clusters;
3175                 cow_start += num_clusters;
3176         }
3177
3178
3179         /*
3180          * truncate the extent map here since no matter whether we meet with
3181          * any error during the action, we shouldn't trust cached extent map
3182          * any more.
3183          */
3184         ocfs2_extent_map_trunc(inode, start);
3185
3186         if (ocfs2_dealloc_has_cluster(&context->dealloc)) {
3187                 ocfs2_schedule_truncate_log_flush(osb, 1);
3188                 ocfs2_run_deallocs(osb, &context->dealloc);
3189         }
3190
3191         kfree(context);
3192         return ret;
3193 }
3194
3195 /*
3196  * Starting at cpos, try to CoW write_len clusters.  Don't CoW
3197  * past max_cpos.  This will stop when it runs into a hole or an
3198  * unrefcounted extent.
3199  */
3200 static int ocfs2_refcount_cow_hunk(struct inode *inode,
3201                                    struct buffer_head *di_bh,
3202                                    u32 cpos, u32 write_len, u32 max_cpos)
3203 {
3204         int ret;
3205         u32 cow_start = 0, cow_len = 0;
3206         struct ocfs2_inode_info *oi = OCFS2_I(inode);
3207         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3208         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
3209         struct buffer_head *ref_root_bh = NULL;
3210         struct ocfs2_refcount_tree *ref_tree;
3211
3212         BUG_ON(!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
3213
3214         ret = ocfs2_refcount_cal_cow_clusters(inode, di_bh,
3215                                               cpos, write_len, max_cpos,
3216                                               &cow_start, &cow_len);
3217         if (ret) {
3218                 mlog_errno(ret);
3219                 goto out;
3220         }
3221
3222         mlog(0, "CoW inode %lu, cpos %u, write_len %u, cow_start %u, "
3223              "cow_len %u\n", inode->i_ino,
3224              cpos, write_len, cow_start, cow_len);
3225
3226         BUG_ON(cow_len == 0);
3227
3228         ret = ocfs2_lock_refcount_tree(osb, le64_to_cpu(di->i_refcount_loc),
3229                                        1, &ref_tree, &ref_root_bh);
3230         if (ret) {
3231                 mlog_errno(ret);
3232                 goto out;
3233         }
3234
3235         ret = ocfs2_replace_cow(inode, di_bh, ref_root_bh, &ref_tree->rf_ci,
3236                                 cow_start, cow_len);
3237         if (ret)
3238                 mlog_errno(ret);
3239
3240         ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
3241         brelse(ref_root_bh);
3242 out:
3243         return ret;
3244 }
3245
3246 /*
3247  * CoW any and all clusters between cpos and cpos+write_len.
3248  * Don't CoW past max_cpos.  If this returns successfully, all
3249  * clusters between cpos and cpos+write_len are safe to modify.
3250  */
3251 int ocfs2_refcount_cow(struct inode *inode,
3252                        struct buffer_head *di_bh,
3253                        u32 cpos, u32 write_len, u32 max_cpos)
3254 {
3255         int ret = 0;
3256         u32 p_cluster, num_clusters;
3257         unsigned int ext_flags;
3258
3259         while (write_len) {
3260                 ret = ocfs2_get_clusters(inode, cpos, &p_cluster,
3261                                          &num_clusters, &ext_flags);
3262                 if (ret) {
3263                         mlog_errno(ret);
3264                         break;
3265                 }
3266
3267                 if (write_len < num_clusters)
3268                         num_clusters = write_len;
3269
3270                 if (ext_flags & OCFS2_EXT_REFCOUNTED) {
3271                         ret = ocfs2_refcount_cow_hunk(inode, di_bh, cpos,
3272                                                       num_clusters, max_cpos);
3273                         if (ret) {
3274                                 mlog_errno(ret);
3275                                 break;
3276                         }
3277                 }
3278
3279                 write_len -= num_clusters;
3280                 cpos += num_clusters;
3281         }
3282
3283         return ret;
3284 }
3285
3286 /*
3287  * Insert a new extent into refcount tree and mark a extent rec
3288  * as refcounted in the dinode tree.
3289  */
3290 int ocfs2_add_refcount_flag(struct inode *inode,
3291                             struct ocfs2_extent_tree *data_et,
3292                             struct ocfs2_caching_info *ref_ci,
3293                             struct buffer_head *ref_root_bh,
3294                             u32 cpos, u32 p_cluster, u32 num_clusters,
3295                             struct ocfs2_cached_dealloc_ctxt *dealloc)
3296 {
3297         int ret;
3298         handle_t *handle;
3299         int credits = 1, ref_blocks = 0;
3300         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3301         struct ocfs2_alloc_context *meta_ac = NULL;
3302
3303         ret = ocfs2_calc_refcount_meta_credits(inode->i_sb,
3304                                                ref_ci, ref_root_bh,
3305                                                p_cluster, num_clusters,
3306                                                &ref_blocks, &credits);
3307         if (ret) {
3308                 mlog_errno(ret);
3309                 goto out;
3310         }
3311
3312         mlog(0, "reserve new metadata %d, credits = %d\n",
3313              ref_blocks, credits);
3314
3315         if (ref_blocks) {
3316                 ret = ocfs2_reserve_new_metadata_blocks(OCFS2_SB(inode->i_sb),
3317                                                         ref_blocks, &meta_ac);
3318                 if (ret) {
3319                         mlog_errno(ret);
3320                         goto out;
3321                 }
3322         }
3323
3324         handle = ocfs2_start_trans(osb, credits);
3325         if (IS_ERR(handle)) {
3326                 ret = PTR_ERR(handle);
3327                 mlog_errno(ret);
3328                 goto out;
3329         }
3330
3331         ret = ocfs2_mark_extent_refcounted(inode, data_et, handle,
3332                                            cpos, num_clusters, p_cluster,
3333                                            meta_ac, dealloc);
3334         if (ret) {
3335                 mlog_errno(ret);
3336                 goto out_commit;
3337         }
3338
3339         ret = __ocfs2_increase_refcount(handle, ref_ci, ref_root_bh,
3340                                         p_cluster, num_clusters,
3341                                         meta_ac, dealloc);
3342         if (ret)
3343                 mlog_errno(ret);
3344
3345 out_commit:
3346         ocfs2_commit_trans(osb, handle);
3347 out:
3348         if (meta_ac)
3349                 ocfs2_free_alloc_context(meta_ac);
3350         return ret;
3351 }
3352
3353 static int ocfs2_attach_refcount_tree(struct inode *inode,
3354                                       struct buffer_head *di_bh)
3355 {
3356         int ret;
3357         struct buffer_head *ref_root_bh = NULL;
3358         struct ocfs2_inode_info *oi = OCFS2_I(inode);
3359         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
3360         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3361         struct ocfs2_refcount_tree *ref_tree;
3362         unsigned int ext_flags;
3363         loff_t size;
3364         u32 cpos, num_clusters, clusters, p_cluster;
3365         struct ocfs2_cached_dealloc_ctxt dealloc;
3366         struct ocfs2_extent_tree di_et;
3367
3368         ocfs2_init_dealloc_ctxt(&dealloc);
3369
3370         if (!(oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL)) {
3371                 ret = ocfs2_create_refcount_tree(inode, di_bh);
3372                 if (ret) {
3373                         mlog_errno(ret);
3374                         goto out;
3375                 }
3376         }
3377
3378         BUG_ON(!di->i_refcount_loc);
3379         ret = ocfs2_lock_refcount_tree(osb,
3380                                        le64_to_cpu(di->i_refcount_loc), 1,
3381                                        &ref_tree, &ref_root_bh);
3382         if (ret) {
3383                 mlog_errno(ret);
3384                 goto out;
3385         }
3386
3387         ocfs2_init_dinode_extent_tree(&di_et, INODE_CACHE(inode), di_bh);
3388
3389         size = i_size_read(inode);
3390         clusters = ocfs2_clusters_for_bytes(inode->i_sb, size);
3391
3392         cpos = 0;
3393         while (cpos < clusters) {
3394                 ret = ocfs2_get_clusters(inode, cpos, &p_cluster,
3395                                          &num_clusters, &ext_flags);
3396
3397                 if (p_cluster && !(ext_flags & OCFS2_EXT_REFCOUNTED)) {
3398                         ret = ocfs2_add_refcount_flag(inode, &di_et,
3399                                                       &ref_tree->rf_ci,
3400                                                       ref_root_bh, cpos,
3401                                                       p_cluster, num_clusters,
3402                                                       &dealloc);
3403                         if (ret) {
3404                                 mlog_errno(ret);
3405                                 break;
3406                         }
3407                 }
3408                 cpos += num_clusters;
3409         }
3410
3411         ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
3412         brelse(ref_root_bh);
3413
3414         if (!ret && ocfs2_dealloc_has_cluster(&dealloc)) {
3415                 ocfs2_schedule_truncate_log_flush(osb, 1);
3416                 ocfs2_run_deallocs(osb, &dealloc);
3417         }
3418 out:
3419         /*
3420          * Empty the extent map so that we may get the right extent
3421          * record from the disk.
3422          */
3423         ocfs2_extent_map_trunc(inode, 0);
3424
3425         return ret;
3426 }
3427
3428 static int ocfs2_add_refcounted_extent(struct inode *inode,
3429                                    struct ocfs2_extent_tree *et,
3430                                    struct ocfs2_caching_info *ref_ci,
3431                                    struct buffer_head *ref_root_bh,
3432                                    u32 cpos, u32 p_cluster, u32 num_clusters,
3433                                    unsigned int ext_flags,
3434                                    struct ocfs2_cached_dealloc_ctxt *dealloc)
3435 {
3436         int ret;
3437         handle_t *handle;
3438         int credits = 0;
3439         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
3440         struct ocfs2_alloc_context *meta_ac = NULL;
3441
3442         ret = ocfs2_lock_refcount_allocators(inode->i_sb,
3443                                              p_cluster, num_clusters,
3444                                              et, ref_ci,
3445                                              ref_root_bh, &meta_ac,
3446                                              NULL, &credits);
3447         if (ret) {
3448                 mlog_errno(ret);
3449                 goto out;
3450         }
3451
3452         handle = ocfs2_start_trans(osb, credits);
3453         if (IS_ERR(handle)) {
3454                 ret = PTR_ERR(handle);
3455                 mlog_errno(ret);
3456                 goto out;
3457         }
3458
3459         ret = ocfs2_insert_extent(handle, et, cpos,
3460                         cpu_to_le64(ocfs2_clusters_to_blocks(inode->i_sb,
3461                                                              p_cluster)),
3462                         num_clusters, ext_flags, meta_ac);
3463         if (ret) {
3464                 mlog_errno(ret);
3465                 goto out_commit;
3466         }
3467
3468         ret = __ocfs2_increase_refcount(handle, ref_ci, ref_root_bh,
3469                                         p_cluster, num_clusters,
3470                                         meta_ac, dealloc);
3471         if (ret)
3472                 mlog_errno(ret);
3473
3474 out_commit:
3475         ocfs2_commit_trans(osb, handle);
3476 out:
3477         if (meta_ac)
3478                 ocfs2_free_alloc_context(meta_ac);
3479         return ret;
3480 }
3481
3482 static int ocfs2_duplicate_extent_list(struct inode *s_inode,
3483                                 struct inode *t_inode,
3484                                 struct buffer_head *t_bh,
3485                                 struct ocfs2_caching_info *ref_ci,
3486                                 struct buffer_head *ref_root_bh,
3487                                 struct ocfs2_cached_dealloc_ctxt *dealloc)
3488 {
3489         int ret = 0;
3490         u32 p_cluster, num_clusters, clusters, cpos;
3491         loff_t size;
3492         unsigned int ext_flags;
3493         struct ocfs2_extent_tree et;
3494
3495         ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(t_inode), t_bh);
3496
3497         size = i_size_read(s_inode);
3498         clusters = ocfs2_clusters_for_bytes(s_inode->i_sb, size);
3499
3500         cpos = 0;
3501         while (cpos < clusters) {
3502                 ret = ocfs2_get_clusters(s_inode, cpos, &p_cluster,
3503                                          &num_clusters, &ext_flags);
3504
3505                 if (p_cluster) {
3506                         ret = ocfs2_add_refcounted_extent(t_inode, &et,
3507                                                           ref_ci, ref_root_bh,
3508                                                           cpos, p_cluster,
3509                                                           num_clusters,
3510                                                           ext_flags,
3511                                                           dealloc);
3512                         if (ret) {
3513                                 mlog_errno(ret);
3514                                 goto out;
3515                         }
3516                 }
3517
3518                 cpos += num_clusters;
3519         }
3520
3521 out:
3522         return ret;
3523 }
3524
3525 static int ocfs2_create_reflink_node(struct inode *s_inode,
3526                                      struct buffer_head *s_bh,
3527                                      struct inode *t_inode,
3528                                      struct buffer_head *t_bh)
3529 {
3530         int ret;
3531         struct buffer_head *ref_root_bh = NULL;
3532         struct ocfs2_cached_dealloc_ctxt dealloc;
3533         struct ocfs2_super *osb = OCFS2_SB(s_inode->i_sb);
3534         struct ocfs2_refcount_block *rb;
3535         struct ocfs2_dinode *di = (struct ocfs2_dinode *)s_bh->b_data;
3536         struct ocfs2_refcount_tree *ref_tree;
3537
3538         ocfs2_init_dealloc_ctxt(&dealloc);
3539
3540         ret = ocfs2_set_refcount_tree(t_inode, t_bh,
3541                                       le64_to_cpu(di->i_refcount_loc));
3542         if (ret) {
3543                 mlog_errno(ret);
3544                 goto out;
3545         }
3546
3547         ret = ocfs2_lock_refcount_tree(osb, le64_to_cpu(di->i_refcount_loc),
3548                                        1, &ref_tree, &ref_root_bh);
3549         if (ret) {
3550                 mlog_errno(ret);
3551                 goto out;
3552         }
3553         rb = (struct ocfs2_refcount_block *)ref_root_bh->b_data;
3554
3555         ret = ocfs2_duplicate_extent_list(s_inode, t_inode, t_bh,
3556                                           &ref_tree->rf_ci, ref_root_bh,
3557                                           &dealloc);
3558         if (ret)
3559                 mlog_errno(ret);
3560
3561         ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
3562         brelse(ref_root_bh);
3563 out:
3564         if (ocfs2_dealloc_has_cluster(&dealloc)) {
3565                 ocfs2_schedule_truncate_log_flush(osb, 1);
3566                 ocfs2_run_deallocs(osb, &dealloc);
3567         }
3568
3569         return ret;
3570 }