ocfs2: Prefix the extent tree operations structure.
[safe/jmp/linux-2.6] / fs / ocfs2 / alloc.c
1 /* -*- mode: c; c-basic-offset: 8; -*-
2  * vim: noexpandtab sw=8 ts=8 sts=0:
3  *
4  * alloc.c
5  *
6  * Extent allocs and frees
7  *
8  * Copyright (C) 2002, 2004 Oracle.  All rights reserved.
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public
21  * License along with this program; if not, write to the
22  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23  * Boston, MA 021110-1307, USA.
24  */
25
26 #include <linux/fs.h>
27 #include <linux/types.h>
28 #include <linux/slab.h>
29 #include <linux/highmem.h>
30 #include <linux/swap.h>
31
32 #define MLOG_MASK_PREFIX ML_DISK_ALLOC
33 #include <cluster/masklog.h>
34
35 #include "ocfs2.h"
36
37 #include "alloc.h"
38 #include "aops.h"
39 #include "dlmglue.h"
40 #include "extent_map.h"
41 #include "inode.h"
42 #include "journal.h"
43 #include "localalloc.h"
44 #include "suballoc.h"
45 #include "sysfile.h"
46 #include "file.h"
47 #include "super.h"
48 #include "uptodate.h"
49
50 #include "buffer_head_io.h"
51
52 /*
53  * ocfs2_extent_tree and ocfs2_extent_tree_operations are used to abstract
54  * the b-tree operations in ocfs2. Now all the b-tree operations are not
55  * limited to ocfs2_dinode only. Any data which need to allocate clusters
56  * to store can use b-tree. And it only needs to implement its ocfs2_extent_tree
57  * and operation.
58  *
59  * ocfs2_extent_tree contains info for the root of the b-tree, it must have a
60  * root ocfs2_extent_list and a root_bh so that they can be used in the b-tree
61  * functions.
62  * ocfs2_extent_tree_operations abstract the normal operations we do for
63  * the root of extent b-tree.
64  */
65 struct ocfs2_extent_tree;
66
67 struct ocfs2_extent_tree_operations {
68         void (*eo_set_last_eb_blk)(struct ocfs2_extent_tree *et,
69                                    u64 blkno);
70         u64 (*eo_get_last_eb_blk)(struct ocfs2_extent_tree *et);
71         void (*eo_update_clusters)(struct inode *inode,
72                                    struct ocfs2_extent_tree *et,
73                                    u32 new_clusters);
74         int (*eo_sanity_check)(struct inode *inode, struct ocfs2_extent_tree *et);
75 };
76
77 struct ocfs2_extent_tree {
78         enum ocfs2_extent_tree_type type;
79         struct ocfs2_extent_tree_operations *eops;
80         struct buffer_head *root_bh;
81         struct ocfs2_extent_list *root_el;
82         void *private;
83         unsigned int max_leaf_clusters;
84 };
85
86 static void ocfs2_dinode_set_last_eb_blk(struct ocfs2_extent_tree *et,
87                                          u64 blkno)
88 {
89         struct ocfs2_dinode *di = (struct ocfs2_dinode *)et->root_bh->b_data;
90
91         BUG_ON(et->type != OCFS2_DINODE_EXTENT);
92         di->i_last_eb_blk = cpu_to_le64(blkno);
93 }
94
95 static u64 ocfs2_dinode_get_last_eb_blk(struct ocfs2_extent_tree *et)
96 {
97         struct ocfs2_dinode *di = (struct ocfs2_dinode *)et->root_bh->b_data;
98
99         BUG_ON(et->type != OCFS2_DINODE_EXTENT);
100         return le64_to_cpu(di->i_last_eb_blk);
101 }
102
103 static void ocfs2_dinode_update_clusters(struct inode *inode,
104                                          struct ocfs2_extent_tree *et,
105                                          u32 clusters)
106 {
107         struct ocfs2_dinode *di =
108                         (struct ocfs2_dinode *)et->root_bh->b_data;
109
110         le32_add_cpu(&di->i_clusters, clusters);
111         spin_lock(&OCFS2_I(inode)->ip_lock);
112         OCFS2_I(inode)->ip_clusters = le32_to_cpu(di->i_clusters);
113         spin_unlock(&OCFS2_I(inode)->ip_lock);
114 }
115
116 static int ocfs2_dinode_sanity_check(struct inode *inode,
117                                      struct ocfs2_extent_tree *et)
118 {
119         int ret = 0;
120         struct ocfs2_dinode *di;
121
122         BUG_ON(et->type != OCFS2_DINODE_EXTENT);
123
124         di = (struct ocfs2_dinode *)et->root_bh->b_data;
125         if (!OCFS2_IS_VALID_DINODE(di)) {
126                 ret = -EIO;
127                 ocfs2_error(inode->i_sb,
128                         "Inode %llu has invalid path root",
129                         (unsigned long long)OCFS2_I(inode)->ip_blkno);
130         }
131
132         return ret;
133 }
134
135 static struct ocfs2_extent_tree_operations ocfs2_dinode_et_ops = {
136         .eo_set_last_eb_blk     = ocfs2_dinode_set_last_eb_blk,
137         .eo_get_last_eb_blk     = ocfs2_dinode_get_last_eb_blk,
138         .eo_update_clusters     = ocfs2_dinode_update_clusters,
139         .eo_sanity_check        = ocfs2_dinode_sanity_check,
140 };
141
142 static void ocfs2_xattr_value_set_last_eb_blk(struct ocfs2_extent_tree *et,
143                                               u64 blkno)
144 {
145         struct ocfs2_xattr_value_root *xv =
146                 (struct ocfs2_xattr_value_root *)et->private;
147
148         xv->xr_last_eb_blk = cpu_to_le64(blkno);
149 }
150
151 static u64 ocfs2_xattr_value_get_last_eb_blk(struct ocfs2_extent_tree *et)
152 {
153         struct ocfs2_xattr_value_root *xv =
154                 (struct ocfs2_xattr_value_root *) et->private;
155
156         return le64_to_cpu(xv->xr_last_eb_blk);
157 }
158
159 static void ocfs2_xattr_value_update_clusters(struct inode *inode,
160                                               struct ocfs2_extent_tree *et,
161                                               u32 clusters)
162 {
163         struct ocfs2_xattr_value_root *xv =
164                 (struct ocfs2_xattr_value_root *)et->private;
165
166         le32_add_cpu(&xv->xr_clusters, clusters);
167 }
168
169 static int ocfs2_xattr_value_sanity_check(struct inode *inode,
170                                           struct ocfs2_extent_tree *et)
171 {
172         return 0;
173 }
174
175 static struct ocfs2_extent_tree_operations ocfs2_xattr_et_ops = {
176         .eo_set_last_eb_blk     = ocfs2_xattr_value_set_last_eb_blk,
177         .eo_get_last_eb_blk     = ocfs2_xattr_value_get_last_eb_blk,
178         .eo_update_clusters     = ocfs2_xattr_value_update_clusters,
179         .eo_sanity_check        = ocfs2_xattr_value_sanity_check,
180 };
181
182 static void ocfs2_xattr_tree_set_last_eb_blk(struct ocfs2_extent_tree *et,
183                                              u64 blkno)
184 {
185         struct ocfs2_xattr_block *xb =
186                 (struct ocfs2_xattr_block *) et->root_bh->b_data;
187         struct ocfs2_xattr_tree_root *xt = &xb->xb_attrs.xb_root;
188
189         xt->xt_last_eb_blk = cpu_to_le64(blkno);
190 }
191
192 static u64 ocfs2_xattr_tree_get_last_eb_blk(struct ocfs2_extent_tree *et)
193 {
194         struct ocfs2_xattr_block *xb =
195                 (struct ocfs2_xattr_block *) et->root_bh->b_data;
196         struct ocfs2_xattr_tree_root *xt = &xb->xb_attrs.xb_root;
197
198         return le64_to_cpu(xt->xt_last_eb_blk);
199 }
200
201 static void ocfs2_xattr_tree_update_clusters(struct inode *inode,
202                                              struct ocfs2_extent_tree *et,
203                                              u32 clusters)
204 {
205         struct ocfs2_xattr_block *xb =
206                         (struct ocfs2_xattr_block *)et->root_bh->b_data;
207
208         le32_add_cpu(&xb->xb_attrs.xb_root.xt_clusters, clusters);
209 }
210
211 static int ocfs2_xattr_tree_sanity_check(struct inode *inode,
212                                          struct ocfs2_extent_tree *et)
213 {
214         return 0;
215 }
216
217 static struct ocfs2_extent_tree_operations ocfs2_xattr_tree_et_ops = {
218         .eo_set_last_eb_blk     = ocfs2_xattr_tree_set_last_eb_blk,
219         .eo_get_last_eb_blk     = ocfs2_xattr_tree_get_last_eb_blk,
220         .eo_update_clusters     = ocfs2_xattr_tree_update_clusters,
221         .eo_sanity_check        = ocfs2_xattr_tree_sanity_check,
222 };
223
224 static struct ocfs2_extent_tree*
225          ocfs2_new_extent_tree(struct inode *inode,
226                                struct buffer_head *bh,
227                                enum ocfs2_extent_tree_type et_type,
228                                void *private)
229 {
230         struct ocfs2_extent_tree *et;
231
232         et = kzalloc(sizeof(*et), GFP_NOFS);
233         if (!et)
234                 return NULL;
235
236         et->type = et_type;
237         get_bh(bh);
238         et->root_bh = bh;
239         et->private = private;
240
241         if (et_type == OCFS2_DINODE_EXTENT) {
242                 et->root_el = &((struct ocfs2_dinode *)bh->b_data)->id2.i_list;
243                 et->eops = &ocfs2_dinode_et_ops;
244         } else if (et_type == OCFS2_XATTR_VALUE_EXTENT) {
245                 struct ocfs2_xattr_value_root *xv =
246                         (struct ocfs2_xattr_value_root *) private;
247                 et->root_el = &xv->xr_list;
248                 et->eops = &ocfs2_xattr_et_ops;
249         } else if (et_type == OCFS2_XATTR_TREE_EXTENT) {
250                 struct ocfs2_xattr_block *xb =
251                         (struct ocfs2_xattr_block *)bh->b_data;
252                 et->root_el = &xb->xb_attrs.xb_root.xt_list;
253                 et->eops = &ocfs2_xattr_tree_et_ops;
254                 et->max_leaf_clusters = ocfs2_clusters_for_bytes(inode->i_sb,
255                                                 OCFS2_MAX_XATTR_TREE_LEAF_SIZE);
256         }
257
258         return et;
259 }
260
261 static void ocfs2_free_extent_tree(struct ocfs2_extent_tree *et)
262 {
263         if (et) {
264                 brelse(et->root_bh);
265                 kfree(et);
266         }
267 }
268
269 static inline void ocfs2_et_set_last_eb_blk(struct ocfs2_extent_tree *et,
270                                             u64 new_last_eb_blk)
271 {
272         et->eops->eo_set_last_eb_blk(et, new_last_eb_blk);
273 }
274
275 static inline u64 ocfs2_et_get_last_eb_blk(struct ocfs2_extent_tree *et)
276 {
277         return et->eops->eo_get_last_eb_blk(et);
278 }
279
280 static inline void ocfs2_et_update_clusters(struct inode *inode,
281                                             struct ocfs2_extent_tree *et,
282                                             u32 clusters)
283 {
284         et->eops->eo_update_clusters(inode, et, clusters);
285 }
286
287 static inline int ocfs2_et_sanity_check(struct inode *inode,
288                                         struct ocfs2_extent_tree *et)
289 {
290         return et->eops->eo_sanity_check(inode, et);
291 }
292
293 static void ocfs2_free_truncate_context(struct ocfs2_truncate_context *tc);
294 static int ocfs2_cache_extent_block_free(struct ocfs2_cached_dealloc_ctxt *ctxt,
295                                          struct ocfs2_extent_block *eb);
296
297 /*
298  * Structures which describe a path through a btree, and functions to
299  * manipulate them.
300  *
301  * The idea here is to be as generic as possible with the tree
302  * manipulation code.
303  */
304 struct ocfs2_path_item {
305         struct buffer_head              *bh;
306         struct ocfs2_extent_list        *el;
307 };
308
309 #define OCFS2_MAX_PATH_DEPTH    5
310
311 struct ocfs2_path {
312         int                     p_tree_depth;
313         struct ocfs2_path_item  p_node[OCFS2_MAX_PATH_DEPTH];
314 };
315
316 #define path_root_bh(_path) ((_path)->p_node[0].bh)
317 #define path_root_el(_path) ((_path)->p_node[0].el)
318 #define path_leaf_bh(_path) ((_path)->p_node[(_path)->p_tree_depth].bh)
319 #define path_leaf_el(_path) ((_path)->p_node[(_path)->p_tree_depth].el)
320 #define path_num_items(_path) ((_path)->p_tree_depth + 1)
321
322 /*
323  * Reset the actual path elements so that we can re-use the structure
324  * to build another path. Generally, this involves freeing the buffer
325  * heads.
326  */
327 static void ocfs2_reinit_path(struct ocfs2_path *path, int keep_root)
328 {
329         int i, start = 0, depth = 0;
330         struct ocfs2_path_item *node;
331
332         if (keep_root)
333                 start = 1;
334
335         for(i = start; i < path_num_items(path); i++) {
336                 node = &path->p_node[i];
337
338                 brelse(node->bh);
339                 node->bh = NULL;
340                 node->el = NULL;
341         }
342
343         /*
344          * Tree depth may change during truncate, or insert. If we're
345          * keeping the root extent list, then make sure that our path
346          * structure reflects the proper depth.
347          */
348         if (keep_root)
349                 depth = le16_to_cpu(path_root_el(path)->l_tree_depth);
350
351         path->p_tree_depth = depth;
352 }
353
354 static void ocfs2_free_path(struct ocfs2_path *path)
355 {
356         if (path) {
357                 ocfs2_reinit_path(path, 0);
358                 kfree(path);
359         }
360 }
361
362 /*
363  * All the elements of src into dest. After this call, src could be freed
364  * without affecting dest.
365  *
366  * Both paths should have the same root. Any non-root elements of dest
367  * will be freed.
368  */
369 static void ocfs2_cp_path(struct ocfs2_path *dest, struct ocfs2_path *src)
370 {
371         int i;
372
373         BUG_ON(path_root_bh(dest) != path_root_bh(src));
374         BUG_ON(path_root_el(dest) != path_root_el(src));
375
376         ocfs2_reinit_path(dest, 1);
377
378         for(i = 1; i < OCFS2_MAX_PATH_DEPTH; i++) {
379                 dest->p_node[i].bh = src->p_node[i].bh;
380                 dest->p_node[i].el = src->p_node[i].el;
381
382                 if (dest->p_node[i].bh)
383                         get_bh(dest->p_node[i].bh);
384         }
385 }
386
387 /*
388  * Make the *dest path the same as src and re-initialize src path to
389  * have a root only.
390  */
391 static void ocfs2_mv_path(struct ocfs2_path *dest, struct ocfs2_path *src)
392 {
393         int i;
394
395         BUG_ON(path_root_bh(dest) != path_root_bh(src));
396
397         for(i = 1; i < OCFS2_MAX_PATH_DEPTH; i++) {
398                 brelse(dest->p_node[i].bh);
399
400                 dest->p_node[i].bh = src->p_node[i].bh;
401                 dest->p_node[i].el = src->p_node[i].el;
402
403                 src->p_node[i].bh = NULL;
404                 src->p_node[i].el = NULL;
405         }
406 }
407
408 /*
409  * Insert an extent block at given index.
410  *
411  * This will not take an additional reference on eb_bh.
412  */
413 static inline void ocfs2_path_insert_eb(struct ocfs2_path *path, int index,
414                                         struct buffer_head *eb_bh)
415 {
416         struct ocfs2_extent_block *eb = (struct ocfs2_extent_block *)eb_bh->b_data;
417
418         /*
419          * Right now, no root bh is an extent block, so this helps
420          * catch code errors with dinode trees. The assertion can be
421          * safely removed if we ever need to insert extent block
422          * structures at the root.
423          */
424         BUG_ON(index == 0);
425
426         path->p_node[index].bh = eb_bh;
427         path->p_node[index].el = &eb->h_list;
428 }
429
430 static struct ocfs2_path *ocfs2_new_path(struct buffer_head *root_bh,
431                                          struct ocfs2_extent_list *root_el)
432 {
433         struct ocfs2_path *path;
434
435         BUG_ON(le16_to_cpu(root_el->l_tree_depth) >= OCFS2_MAX_PATH_DEPTH);
436
437         path = kzalloc(sizeof(*path), GFP_NOFS);
438         if (path) {
439                 path->p_tree_depth = le16_to_cpu(root_el->l_tree_depth);
440                 get_bh(root_bh);
441                 path_root_bh(path) = root_bh;
442                 path_root_el(path) = root_el;
443         }
444
445         return path;
446 }
447
448 /*
449  * Convenience function to journal all components in a path.
450  */
451 static int ocfs2_journal_access_path(struct inode *inode, handle_t *handle,
452                                      struct ocfs2_path *path)
453 {
454         int i, ret = 0;
455
456         if (!path)
457                 goto out;
458
459         for(i = 0; i < path_num_items(path); i++) {
460                 ret = ocfs2_journal_access(handle, inode, path->p_node[i].bh,
461                                            OCFS2_JOURNAL_ACCESS_WRITE);
462                 if (ret < 0) {
463                         mlog_errno(ret);
464                         goto out;
465                 }
466         }
467
468 out:
469         return ret;
470 }
471
472 /*
473  * Return the index of the extent record which contains cluster #v_cluster.
474  * -1 is returned if it was not found.
475  *
476  * Should work fine on interior and exterior nodes.
477  */
478 int ocfs2_search_extent_list(struct ocfs2_extent_list *el, u32 v_cluster)
479 {
480         int ret = -1;
481         int i;
482         struct ocfs2_extent_rec *rec;
483         u32 rec_end, rec_start, clusters;
484
485         for(i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
486                 rec = &el->l_recs[i];
487
488                 rec_start = le32_to_cpu(rec->e_cpos);
489                 clusters = ocfs2_rec_clusters(el, rec);
490
491                 rec_end = rec_start + clusters;
492
493                 if (v_cluster >= rec_start && v_cluster < rec_end) {
494                         ret = i;
495                         break;
496                 }
497         }
498
499         return ret;
500 }
501
502 enum ocfs2_contig_type {
503         CONTIG_NONE = 0,
504         CONTIG_LEFT,
505         CONTIG_RIGHT,
506         CONTIG_LEFTRIGHT,
507 };
508
509
510 /*
511  * NOTE: ocfs2_block_extent_contig(), ocfs2_extents_adjacent() and
512  * ocfs2_extent_contig only work properly against leaf nodes!
513  */
514 static int ocfs2_block_extent_contig(struct super_block *sb,
515                                      struct ocfs2_extent_rec *ext,
516                                      u64 blkno)
517 {
518         u64 blk_end = le64_to_cpu(ext->e_blkno);
519
520         blk_end += ocfs2_clusters_to_blocks(sb,
521                                     le16_to_cpu(ext->e_leaf_clusters));
522
523         return blkno == blk_end;
524 }
525
526 static int ocfs2_extents_adjacent(struct ocfs2_extent_rec *left,
527                                   struct ocfs2_extent_rec *right)
528 {
529         u32 left_range;
530
531         left_range = le32_to_cpu(left->e_cpos) +
532                 le16_to_cpu(left->e_leaf_clusters);
533
534         return (left_range == le32_to_cpu(right->e_cpos));
535 }
536
537 static enum ocfs2_contig_type
538         ocfs2_extent_contig(struct inode *inode,
539                             struct ocfs2_extent_rec *ext,
540                             struct ocfs2_extent_rec *insert_rec)
541 {
542         u64 blkno = le64_to_cpu(insert_rec->e_blkno);
543
544         /*
545          * Refuse to coalesce extent records with different flag
546          * fields - we don't want to mix unwritten extents with user
547          * data.
548          */
549         if (ext->e_flags != insert_rec->e_flags)
550                 return CONTIG_NONE;
551
552         if (ocfs2_extents_adjacent(ext, insert_rec) &&
553             ocfs2_block_extent_contig(inode->i_sb, ext, blkno))
554                         return CONTIG_RIGHT;
555
556         blkno = le64_to_cpu(ext->e_blkno);
557         if (ocfs2_extents_adjacent(insert_rec, ext) &&
558             ocfs2_block_extent_contig(inode->i_sb, insert_rec, blkno))
559                 return CONTIG_LEFT;
560
561         return CONTIG_NONE;
562 }
563
564 /*
565  * NOTE: We can have pretty much any combination of contiguousness and
566  * appending.
567  *
568  * The usefulness of APPEND_TAIL is more in that it lets us know that
569  * we'll have to update the path to that leaf.
570  */
571 enum ocfs2_append_type {
572         APPEND_NONE = 0,
573         APPEND_TAIL,
574 };
575
576 enum ocfs2_split_type {
577         SPLIT_NONE = 0,
578         SPLIT_LEFT,
579         SPLIT_RIGHT,
580 };
581
582 struct ocfs2_insert_type {
583         enum ocfs2_split_type   ins_split;
584         enum ocfs2_append_type  ins_appending;
585         enum ocfs2_contig_type  ins_contig;
586         int                     ins_contig_index;
587         int                     ins_tree_depth;
588 };
589
590 struct ocfs2_merge_ctxt {
591         enum ocfs2_contig_type  c_contig_type;
592         int                     c_has_empty_extent;
593         int                     c_split_covers_rec;
594 };
595
596 /*
597  * How many free extents have we got before we need more meta data?
598  */
599 int ocfs2_num_free_extents(struct ocfs2_super *osb,
600                            struct inode *inode,
601                            struct buffer_head *root_bh,
602                            enum ocfs2_extent_tree_type type,
603                            void *private)
604 {
605         int retval;
606         struct ocfs2_extent_list *el = NULL;
607         struct ocfs2_extent_block *eb;
608         struct buffer_head *eb_bh = NULL;
609         u64 last_eb_blk = 0;
610
611         mlog_entry_void();
612
613         if (type == OCFS2_DINODE_EXTENT) {
614                 struct ocfs2_dinode *fe =
615                                 (struct ocfs2_dinode *)root_bh->b_data;
616                 if (!OCFS2_IS_VALID_DINODE(fe)) {
617                         OCFS2_RO_ON_INVALID_DINODE(inode->i_sb, fe);
618                         retval = -EIO;
619                         goto bail;
620                 }
621
622                 if (fe->i_last_eb_blk)
623                         last_eb_blk = le64_to_cpu(fe->i_last_eb_blk);
624                 el = &fe->id2.i_list;
625         } else if (type == OCFS2_XATTR_VALUE_EXTENT) {
626                 struct ocfs2_xattr_value_root *xv =
627                         (struct ocfs2_xattr_value_root *) private;
628
629                 last_eb_blk = le64_to_cpu(xv->xr_last_eb_blk);
630                 el = &xv->xr_list;
631         } else if (type == OCFS2_XATTR_TREE_EXTENT) {
632                 struct ocfs2_xattr_block *xb =
633                         (struct ocfs2_xattr_block *)root_bh->b_data;
634
635                 last_eb_blk = le64_to_cpu(xb->xb_attrs.xb_root.xt_last_eb_blk);
636                 el = &xb->xb_attrs.xb_root.xt_list;
637         }
638
639         if (last_eb_blk) {
640                 retval = ocfs2_read_block(osb, last_eb_blk,
641                                           &eb_bh, OCFS2_BH_CACHED, inode);
642                 if (retval < 0) {
643                         mlog_errno(retval);
644                         goto bail;
645                 }
646                 eb = (struct ocfs2_extent_block *) eb_bh->b_data;
647                 el = &eb->h_list;
648         }
649
650         BUG_ON(el->l_tree_depth != 0);
651
652         retval = le16_to_cpu(el->l_count) - le16_to_cpu(el->l_next_free_rec);
653 bail:
654         if (eb_bh)
655                 brelse(eb_bh);
656
657         mlog_exit(retval);
658         return retval;
659 }
660
661 /* expects array to already be allocated
662  *
663  * sets h_signature, h_blkno, h_suballoc_bit, h_suballoc_slot, and
664  * l_count for you
665  */
666 static int ocfs2_create_new_meta_bhs(struct ocfs2_super *osb,
667                                      handle_t *handle,
668                                      struct inode *inode,
669                                      int wanted,
670                                      struct ocfs2_alloc_context *meta_ac,
671                                      struct buffer_head *bhs[])
672 {
673         int count, status, i;
674         u16 suballoc_bit_start;
675         u32 num_got;
676         u64 first_blkno;
677         struct ocfs2_extent_block *eb;
678
679         mlog_entry_void();
680
681         count = 0;
682         while (count < wanted) {
683                 status = ocfs2_claim_metadata(osb,
684                                               handle,
685                                               meta_ac,
686                                               wanted - count,
687                                               &suballoc_bit_start,
688                                               &num_got,
689                                               &first_blkno);
690                 if (status < 0) {
691                         mlog_errno(status);
692                         goto bail;
693                 }
694
695                 for(i = count;  i < (num_got + count); i++) {
696                         bhs[i] = sb_getblk(osb->sb, first_blkno);
697                         if (bhs[i] == NULL) {
698                                 status = -EIO;
699                                 mlog_errno(status);
700                                 goto bail;
701                         }
702                         ocfs2_set_new_buffer_uptodate(inode, bhs[i]);
703
704                         status = ocfs2_journal_access(handle, inode, bhs[i],
705                                                       OCFS2_JOURNAL_ACCESS_CREATE);
706                         if (status < 0) {
707                                 mlog_errno(status);
708                                 goto bail;
709                         }
710
711                         memset(bhs[i]->b_data, 0, osb->sb->s_blocksize);
712                         eb = (struct ocfs2_extent_block *) bhs[i]->b_data;
713                         /* Ok, setup the minimal stuff here. */
714                         strcpy(eb->h_signature, OCFS2_EXTENT_BLOCK_SIGNATURE);
715                         eb->h_blkno = cpu_to_le64(first_blkno);
716                         eb->h_fs_generation = cpu_to_le32(osb->fs_generation);
717                         eb->h_suballoc_slot = cpu_to_le16(osb->slot_num);
718                         eb->h_suballoc_bit = cpu_to_le16(suballoc_bit_start);
719                         eb->h_list.l_count =
720                                 cpu_to_le16(ocfs2_extent_recs_per_eb(osb->sb));
721
722                         suballoc_bit_start++;
723                         first_blkno++;
724
725                         /* We'll also be dirtied by the caller, so
726                          * this isn't absolutely necessary. */
727                         status = ocfs2_journal_dirty(handle, bhs[i]);
728                         if (status < 0) {
729                                 mlog_errno(status);
730                                 goto bail;
731                         }
732                 }
733
734                 count += num_got;
735         }
736
737         status = 0;
738 bail:
739         if (status < 0) {
740                 for(i = 0; i < wanted; i++) {
741                         if (bhs[i])
742                                 brelse(bhs[i]);
743                         bhs[i] = NULL;
744                 }
745         }
746         mlog_exit(status);
747         return status;
748 }
749
750 /*
751  * Helper function for ocfs2_add_branch() and ocfs2_shift_tree_depth().
752  *
753  * Returns the sum of the rightmost extent rec logical offset and
754  * cluster count.
755  *
756  * ocfs2_add_branch() uses this to determine what logical cluster
757  * value should be populated into the leftmost new branch records.
758  *
759  * ocfs2_shift_tree_depth() uses this to determine the # clusters
760  * value for the new topmost tree record.
761  */
762 static inline u32 ocfs2_sum_rightmost_rec(struct ocfs2_extent_list  *el)
763 {
764         int i;
765
766         i = le16_to_cpu(el->l_next_free_rec) - 1;
767
768         return le32_to_cpu(el->l_recs[i].e_cpos) +
769                 ocfs2_rec_clusters(el, &el->l_recs[i]);
770 }
771
772 /*
773  * Add an entire tree branch to our inode. eb_bh is the extent block
774  * to start at, if we don't want to start the branch at the dinode
775  * structure.
776  *
777  * last_eb_bh is required as we have to update it's next_leaf pointer
778  * for the new last extent block.
779  *
780  * the new branch will be 'empty' in the sense that every block will
781  * contain a single record with cluster count == 0.
782  */
783 static int ocfs2_add_branch(struct ocfs2_super *osb,
784                             handle_t *handle,
785                             struct inode *inode,
786                             struct ocfs2_extent_tree *et,
787                             struct buffer_head *eb_bh,
788                             struct buffer_head **last_eb_bh,
789                             struct ocfs2_alloc_context *meta_ac)
790 {
791         int status, new_blocks, i;
792         u64 next_blkno, new_last_eb_blk;
793         struct buffer_head *bh;
794         struct buffer_head **new_eb_bhs = NULL;
795         struct ocfs2_extent_block *eb;
796         struct ocfs2_extent_list  *eb_el;
797         struct ocfs2_extent_list  *el;
798         u32 new_cpos;
799
800         mlog_entry_void();
801
802         BUG_ON(!last_eb_bh || !*last_eb_bh);
803
804         if (eb_bh) {
805                 eb = (struct ocfs2_extent_block *) eb_bh->b_data;
806                 el = &eb->h_list;
807         } else
808                 el = et->root_el;
809
810         /* we never add a branch to a leaf. */
811         BUG_ON(!el->l_tree_depth);
812
813         new_blocks = le16_to_cpu(el->l_tree_depth);
814
815         /* allocate the number of new eb blocks we need */
816         new_eb_bhs = kcalloc(new_blocks, sizeof(struct buffer_head *),
817                              GFP_KERNEL);
818         if (!new_eb_bhs) {
819                 status = -ENOMEM;
820                 mlog_errno(status);
821                 goto bail;
822         }
823
824         status = ocfs2_create_new_meta_bhs(osb, handle, inode, new_blocks,
825                                            meta_ac, new_eb_bhs);
826         if (status < 0) {
827                 mlog_errno(status);
828                 goto bail;
829         }
830
831         eb = (struct ocfs2_extent_block *)(*last_eb_bh)->b_data;
832         new_cpos = ocfs2_sum_rightmost_rec(&eb->h_list);
833
834         /* Note: new_eb_bhs[new_blocks - 1] is the guy which will be
835          * linked with the rest of the tree.
836          * conversly, new_eb_bhs[0] is the new bottommost leaf.
837          *
838          * when we leave the loop, new_last_eb_blk will point to the
839          * newest leaf, and next_blkno will point to the topmost extent
840          * block. */
841         next_blkno = new_last_eb_blk = 0;
842         for(i = 0; i < new_blocks; i++) {
843                 bh = new_eb_bhs[i];
844                 eb = (struct ocfs2_extent_block *) bh->b_data;
845                 if (!OCFS2_IS_VALID_EXTENT_BLOCK(eb)) {
846                         OCFS2_RO_ON_INVALID_EXTENT_BLOCK(inode->i_sb, eb);
847                         status = -EIO;
848                         goto bail;
849                 }
850                 eb_el = &eb->h_list;
851
852                 status = ocfs2_journal_access(handle, inode, bh,
853                                               OCFS2_JOURNAL_ACCESS_CREATE);
854                 if (status < 0) {
855                         mlog_errno(status);
856                         goto bail;
857                 }
858
859                 eb->h_next_leaf_blk = 0;
860                 eb_el->l_tree_depth = cpu_to_le16(i);
861                 eb_el->l_next_free_rec = cpu_to_le16(1);
862                 /*
863                  * This actually counts as an empty extent as
864                  * c_clusters == 0
865                  */
866                 eb_el->l_recs[0].e_cpos = cpu_to_le32(new_cpos);
867                 eb_el->l_recs[0].e_blkno = cpu_to_le64(next_blkno);
868                 /*
869                  * eb_el isn't always an interior node, but even leaf
870                  * nodes want a zero'd flags and reserved field so
871                  * this gets the whole 32 bits regardless of use.
872                  */
873                 eb_el->l_recs[0].e_int_clusters = cpu_to_le32(0);
874                 if (!eb_el->l_tree_depth)
875                         new_last_eb_blk = le64_to_cpu(eb->h_blkno);
876
877                 status = ocfs2_journal_dirty(handle, bh);
878                 if (status < 0) {
879                         mlog_errno(status);
880                         goto bail;
881                 }
882
883                 next_blkno = le64_to_cpu(eb->h_blkno);
884         }
885
886         /* This is a bit hairy. We want to update up to three blocks
887          * here without leaving any of them in an inconsistent state
888          * in case of error. We don't have to worry about
889          * journal_dirty erroring as it won't unless we've aborted the
890          * handle (in which case we would never be here) so reserving
891          * the write with journal_access is all we need to do. */
892         status = ocfs2_journal_access(handle, inode, *last_eb_bh,
893                                       OCFS2_JOURNAL_ACCESS_WRITE);
894         if (status < 0) {
895                 mlog_errno(status);
896                 goto bail;
897         }
898         status = ocfs2_journal_access(handle, inode, et->root_bh,
899                                       OCFS2_JOURNAL_ACCESS_WRITE);
900         if (status < 0) {
901                 mlog_errno(status);
902                 goto bail;
903         }
904         if (eb_bh) {
905                 status = ocfs2_journal_access(handle, inode, eb_bh,
906                                               OCFS2_JOURNAL_ACCESS_WRITE);
907                 if (status < 0) {
908                         mlog_errno(status);
909                         goto bail;
910                 }
911         }
912
913         /* Link the new branch into the rest of the tree (el will
914          * either be on the root_bh, or the extent block passed in. */
915         i = le16_to_cpu(el->l_next_free_rec);
916         el->l_recs[i].e_blkno = cpu_to_le64(next_blkno);
917         el->l_recs[i].e_cpos = cpu_to_le32(new_cpos);
918         el->l_recs[i].e_int_clusters = 0;
919         le16_add_cpu(&el->l_next_free_rec, 1);
920
921         /* fe needs a new last extent block pointer, as does the
922          * next_leaf on the previously last-extent-block. */
923         ocfs2_et_set_last_eb_blk(et, new_last_eb_blk);
924
925         eb = (struct ocfs2_extent_block *) (*last_eb_bh)->b_data;
926         eb->h_next_leaf_blk = cpu_to_le64(new_last_eb_blk);
927
928         status = ocfs2_journal_dirty(handle, *last_eb_bh);
929         if (status < 0)
930                 mlog_errno(status);
931         status = ocfs2_journal_dirty(handle, et->root_bh);
932         if (status < 0)
933                 mlog_errno(status);
934         if (eb_bh) {
935                 status = ocfs2_journal_dirty(handle, eb_bh);
936                 if (status < 0)
937                         mlog_errno(status);
938         }
939
940         /*
941          * Some callers want to track the rightmost leaf so pass it
942          * back here.
943          */
944         brelse(*last_eb_bh);
945         get_bh(new_eb_bhs[0]);
946         *last_eb_bh = new_eb_bhs[0];
947
948         status = 0;
949 bail:
950         if (new_eb_bhs) {
951                 for (i = 0; i < new_blocks; i++)
952                         if (new_eb_bhs[i])
953                                 brelse(new_eb_bhs[i]);
954                 kfree(new_eb_bhs);
955         }
956
957         mlog_exit(status);
958         return status;
959 }
960
961 /*
962  * adds another level to the allocation tree.
963  * returns back the new extent block so you can add a branch to it
964  * after this call.
965  */
966 static int ocfs2_shift_tree_depth(struct ocfs2_super *osb,
967                                   handle_t *handle,
968                                   struct inode *inode,
969                                   struct ocfs2_extent_tree *et,
970                                   struct ocfs2_alloc_context *meta_ac,
971                                   struct buffer_head **ret_new_eb_bh)
972 {
973         int status, i;
974         u32 new_clusters;
975         struct buffer_head *new_eb_bh = NULL;
976         struct ocfs2_extent_block *eb;
977         struct ocfs2_extent_list  *root_el;
978         struct ocfs2_extent_list  *eb_el;
979
980         mlog_entry_void();
981
982         status = ocfs2_create_new_meta_bhs(osb, handle, inode, 1, meta_ac,
983                                            &new_eb_bh);
984         if (status < 0) {
985                 mlog_errno(status);
986                 goto bail;
987         }
988
989         eb = (struct ocfs2_extent_block *) new_eb_bh->b_data;
990         if (!OCFS2_IS_VALID_EXTENT_BLOCK(eb)) {
991                 OCFS2_RO_ON_INVALID_EXTENT_BLOCK(inode->i_sb, eb);
992                 status = -EIO;
993                 goto bail;
994         }
995
996         eb_el = &eb->h_list;
997         root_el = et->root_el;
998
999         status = ocfs2_journal_access(handle, inode, new_eb_bh,
1000                                       OCFS2_JOURNAL_ACCESS_CREATE);
1001         if (status < 0) {
1002                 mlog_errno(status);
1003                 goto bail;
1004         }
1005
1006         /* copy the root extent list data into the new extent block */
1007         eb_el->l_tree_depth = root_el->l_tree_depth;
1008         eb_el->l_next_free_rec = root_el->l_next_free_rec;
1009         for (i = 0; i < le16_to_cpu(root_el->l_next_free_rec); i++)
1010                 eb_el->l_recs[i] = root_el->l_recs[i];
1011
1012         status = ocfs2_journal_dirty(handle, new_eb_bh);
1013         if (status < 0) {
1014                 mlog_errno(status);
1015                 goto bail;
1016         }
1017
1018         status = ocfs2_journal_access(handle, inode, et->root_bh,
1019                                       OCFS2_JOURNAL_ACCESS_WRITE);
1020         if (status < 0) {
1021                 mlog_errno(status);
1022                 goto bail;
1023         }
1024
1025         new_clusters = ocfs2_sum_rightmost_rec(eb_el);
1026
1027         /* update root_bh now */
1028         le16_add_cpu(&root_el->l_tree_depth, 1);
1029         root_el->l_recs[0].e_cpos = 0;
1030         root_el->l_recs[0].e_blkno = eb->h_blkno;
1031         root_el->l_recs[0].e_int_clusters = cpu_to_le32(new_clusters);
1032         for (i = 1; i < le16_to_cpu(root_el->l_next_free_rec); i++)
1033                 memset(&root_el->l_recs[i], 0, sizeof(struct ocfs2_extent_rec));
1034         root_el->l_next_free_rec = cpu_to_le16(1);
1035
1036         /* If this is our 1st tree depth shift, then last_eb_blk
1037          * becomes the allocated extent block */
1038         if (root_el->l_tree_depth == cpu_to_le16(1))
1039                 ocfs2_et_set_last_eb_blk(et, le64_to_cpu(eb->h_blkno));
1040
1041         status = ocfs2_journal_dirty(handle, et->root_bh);
1042         if (status < 0) {
1043                 mlog_errno(status);
1044                 goto bail;
1045         }
1046
1047         *ret_new_eb_bh = new_eb_bh;
1048         new_eb_bh = NULL;
1049         status = 0;
1050 bail:
1051         if (new_eb_bh)
1052                 brelse(new_eb_bh);
1053
1054         mlog_exit(status);
1055         return status;
1056 }
1057
1058 /*
1059  * Should only be called when there is no space left in any of the
1060  * leaf nodes. What we want to do is find the lowest tree depth
1061  * non-leaf extent block with room for new records. There are three
1062  * valid results of this search:
1063  *
1064  * 1) a lowest extent block is found, then we pass it back in
1065  *    *lowest_eb_bh and return '0'
1066  *
1067  * 2) the search fails to find anything, but the root_el has room. We
1068  *    pass NULL back in *lowest_eb_bh, but still return '0'
1069  *
1070  * 3) the search fails to find anything AND the root_el is full, in
1071  *    which case we return > 0
1072  *
1073  * return status < 0 indicates an error.
1074  */
1075 static int ocfs2_find_branch_target(struct ocfs2_super *osb,
1076                                     struct inode *inode,
1077                                     struct ocfs2_extent_tree *et,
1078                                     struct buffer_head **target_bh)
1079 {
1080         int status = 0, i;
1081         u64 blkno;
1082         struct ocfs2_extent_block *eb;
1083         struct ocfs2_extent_list  *el;
1084         struct buffer_head *bh = NULL;
1085         struct buffer_head *lowest_bh = NULL;
1086
1087         mlog_entry_void();
1088
1089         *target_bh = NULL;
1090
1091         el = et->root_el;
1092
1093         while(le16_to_cpu(el->l_tree_depth) > 1) {
1094                 if (le16_to_cpu(el->l_next_free_rec) == 0) {
1095                         ocfs2_error(inode->i_sb, "Dinode %llu has empty "
1096                                     "extent list (next_free_rec == 0)",
1097                                     (unsigned long long)OCFS2_I(inode)->ip_blkno);
1098                         status = -EIO;
1099                         goto bail;
1100                 }
1101                 i = le16_to_cpu(el->l_next_free_rec) - 1;
1102                 blkno = le64_to_cpu(el->l_recs[i].e_blkno);
1103                 if (!blkno) {
1104                         ocfs2_error(inode->i_sb, "Dinode %llu has extent "
1105                                     "list where extent # %d has no physical "
1106                                     "block start",
1107                                     (unsigned long long)OCFS2_I(inode)->ip_blkno, i);
1108                         status = -EIO;
1109                         goto bail;
1110                 }
1111
1112                 if (bh) {
1113                         brelse(bh);
1114                         bh = NULL;
1115                 }
1116
1117                 status = ocfs2_read_block(osb, blkno, &bh, OCFS2_BH_CACHED,
1118                                           inode);
1119                 if (status < 0) {
1120                         mlog_errno(status);
1121                         goto bail;
1122                 }
1123
1124                 eb = (struct ocfs2_extent_block *) bh->b_data;
1125                 if (!OCFS2_IS_VALID_EXTENT_BLOCK(eb)) {
1126                         OCFS2_RO_ON_INVALID_EXTENT_BLOCK(inode->i_sb, eb);
1127                         status = -EIO;
1128                         goto bail;
1129                 }
1130                 el = &eb->h_list;
1131
1132                 if (le16_to_cpu(el->l_next_free_rec) <
1133                     le16_to_cpu(el->l_count)) {
1134                         if (lowest_bh)
1135                                 brelse(lowest_bh);
1136                         lowest_bh = bh;
1137                         get_bh(lowest_bh);
1138                 }
1139         }
1140
1141         /* If we didn't find one and the fe doesn't have any room,
1142          * then return '1' */
1143         el = et->root_el;
1144         if (!lowest_bh && (el->l_next_free_rec == el->l_count))
1145                 status = 1;
1146
1147         *target_bh = lowest_bh;
1148 bail:
1149         if (bh)
1150                 brelse(bh);
1151
1152         mlog_exit(status);
1153         return status;
1154 }
1155
1156 /*
1157  * Grow a b-tree so that it has more records.
1158  *
1159  * We might shift the tree depth in which case existing paths should
1160  * be considered invalid.
1161  *
1162  * Tree depth after the grow is returned via *final_depth.
1163  *
1164  * *last_eb_bh will be updated by ocfs2_add_branch().
1165  */
1166 static int ocfs2_grow_tree(struct inode *inode, handle_t *handle,
1167                            struct ocfs2_extent_tree *et, int *final_depth,
1168                            struct buffer_head **last_eb_bh,
1169                            struct ocfs2_alloc_context *meta_ac)
1170 {
1171         int ret, shift;
1172         struct ocfs2_extent_list *el = et->root_el;
1173         int depth = le16_to_cpu(el->l_tree_depth);
1174         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1175         struct buffer_head *bh = NULL;
1176
1177         BUG_ON(meta_ac == NULL);
1178
1179         shift = ocfs2_find_branch_target(osb, inode, et, &bh);
1180         if (shift < 0) {
1181                 ret = shift;
1182                 mlog_errno(ret);
1183                 goto out;
1184         }
1185
1186         /* We traveled all the way to the bottom of the allocation tree
1187          * and didn't find room for any more extents - we need to add
1188          * another tree level */
1189         if (shift) {
1190                 BUG_ON(bh);
1191                 mlog(0, "need to shift tree depth (current = %d)\n", depth);
1192
1193                 /* ocfs2_shift_tree_depth will return us a buffer with
1194                  * the new extent block (so we can pass that to
1195                  * ocfs2_add_branch). */
1196                 ret = ocfs2_shift_tree_depth(osb, handle, inode, et,
1197                                              meta_ac, &bh);
1198                 if (ret < 0) {
1199                         mlog_errno(ret);
1200                         goto out;
1201                 }
1202                 depth++;
1203                 if (depth == 1) {
1204                         /*
1205                          * Special case: we have room now if we shifted from
1206                          * tree_depth 0, so no more work needs to be done.
1207                          *
1208                          * We won't be calling add_branch, so pass
1209                          * back *last_eb_bh as the new leaf. At depth
1210                          * zero, it should always be null so there's
1211                          * no reason to brelse.
1212                          */
1213                         BUG_ON(*last_eb_bh);
1214                         get_bh(bh);
1215                         *last_eb_bh = bh;
1216                         goto out;
1217                 }
1218         }
1219
1220         /* call ocfs2_add_branch to add the final part of the tree with
1221          * the new data. */
1222         mlog(0, "add branch. bh = %p\n", bh);
1223         ret = ocfs2_add_branch(osb, handle, inode, et, bh, last_eb_bh,
1224                                meta_ac);
1225         if (ret < 0) {
1226                 mlog_errno(ret);
1227                 goto out;
1228         }
1229
1230 out:
1231         if (final_depth)
1232                 *final_depth = depth;
1233         brelse(bh);
1234         return ret;
1235 }
1236
1237 /*
1238  * This function will discard the rightmost extent record.
1239  */
1240 static void ocfs2_shift_records_right(struct ocfs2_extent_list *el)
1241 {
1242         int next_free = le16_to_cpu(el->l_next_free_rec);
1243         int count = le16_to_cpu(el->l_count);
1244         unsigned int num_bytes;
1245
1246         BUG_ON(!next_free);
1247         /* This will cause us to go off the end of our extent list. */
1248         BUG_ON(next_free >= count);
1249
1250         num_bytes = sizeof(struct ocfs2_extent_rec) * next_free;
1251
1252         memmove(&el->l_recs[1], &el->l_recs[0], num_bytes);
1253 }
1254
1255 static void ocfs2_rotate_leaf(struct ocfs2_extent_list *el,
1256                               struct ocfs2_extent_rec *insert_rec)
1257 {
1258         int i, insert_index, next_free, has_empty, num_bytes;
1259         u32 insert_cpos = le32_to_cpu(insert_rec->e_cpos);
1260         struct ocfs2_extent_rec *rec;
1261
1262         next_free = le16_to_cpu(el->l_next_free_rec);
1263         has_empty = ocfs2_is_empty_extent(&el->l_recs[0]);
1264
1265         BUG_ON(!next_free);
1266
1267         /* The tree code before us didn't allow enough room in the leaf. */
1268         BUG_ON(el->l_next_free_rec == el->l_count && !has_empty);
1269
1270         /*
1271          * The easiest way to approach this is to just remove the
1272          * empty extent and temporarily decrement next_free.
1273          */
1274         if (has_empty) {
1275                 /*
1276                  * If next_free was 1 (only an empty extent), this
1277                  * loop won't execute, which is fine. We still want
1278                  * the decrement above to happen.
1279                  */
1280                 for(i = 0; i < (next_free - 1); i++)
1281                         el->l_recs[i] = el->l_recs[i+1];
1282
1283                 next_free--;
1284         }
1285
1286         /*
1287          * Figure out what the new record index should be.
1288          */
1289         for(i = 0; i < next_free; i++) {
1290                 rec = &el->l_recs[i];
1291
1292                 if (insert_cpos < le32_to_cpu(rec->e_cpos))
1293                         break;
1294         }
1295         insert_index = i;
1296
1297         mlog(0, "ins %u: index %d, has_empty %d, next_free %d, count %d\n",
1298              insert_cpos, insert_index, has_empty, next_free, le16_to_cpu(el->l_count));
1299
1300         BUG_ON(insert_index < 0);
1301         BUG_ON(insert_index >= le16_to_cpu(el->l_count));
1302         BUG_ON(insert_index > next_free);
1303
1304         /*
1305          * No need to memmove if we're just adding to the tail.
1306          */
1307         if (insert_index != next_free) {
1308                 BUG_ON(next_free >= le16_to_cpu(el->l_count));
1309
1310                 num_bytes = next_free - insert_index;
1311                 num_bytes *= sizeof(struct ocfs2_extent_rec);
1312                 memmove(&el->l_recs[insert_index + 1],
1313                         &el->l_recs[insert_index],
1314                         num_bytes);
1315         }
1316
1317         /*
1318          * Either we had an empty extent, and need to re-increment or
1319          * there was no empty extent on a non full rightmost leaf node,
1320          * in which case we still need to increment.
1321          */
1322         next_free++;
1323         el->l_next_free_rec = cpu_to_le16(next_free);
1324         /*
1325          * Make sure none of the math above just messed up our tree.
1326          */
1327         BUG_ON(le16_to_cpu(el->l_next_free_rec) > le16_to_cpu(el->l_count));
1328
1329         el->l_recs[insert_index] = *insert_rec;
1330
1331 }
1332
1333 static void ocfs2_remove_empty_extent(struct ocfs2_extent_list *el)
1334 {
1335         int size, num_recs = le16_to_cpu(el->l_next_free_rec);
1336
1337         BUG_ON(num_recs == 0);
1338
1339         if (ocfs2_is_empty_extent(&el->l_recs[0])) {
1340                 num_recs--;
1341                 size = num_recs * sizeof(struct ocfs2_extent_rec);
1342                 memmove(&el->l_recs[0], &el->l_recs[1], size);
1343                 memset(&el->l_recs[num_recs], 0,
1344                        sizeof(struct ocfs2_extent_rec));
1345                 el->l_next_free_rec = cpu_to_le16(num_recs);
1346         }
1347 }
1348
1349 /*
1350  * Create an empty extent record .
1351  *
1352  * l_next_free_rec may be updated.
1353  *
1354  * If an empty extent already exists do nothing.
1355  */
1356 static void ocfs2_create_empty_extent(struct ocfs2_extent_list *el)
1357 {
1358         int next_free = le16_to_cpu(el->l_next_free_rec);
1359
1360         BUG_ON(le16_to_cpu(el->l_tree_depth) != 0);
1361
1362         if (next_free == 0)
1363                 goto set_and_inc;
1364
1365         if (ocfs2_is_empty_extent(&el->l_recs[0]))
1366                 return;
1367
1368         mlog_bug_on_msg(el->l_count == el->l_next_free_rec,
1369                         "Asked to create an empty extent in a full list:\n"
1370                         "count = %u, tree depth = %u",
1371                         le16_to_cpu(el->l_count),
1372                         le16_to_cpu(el->l_tree_depth));
1373
1374         ocfs2_shift_records_right(el);
1375
1376 set_and_inc:
1377         le16_add_cpu(&el->l_next_free_rec, 1);
1378         memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
1379 }
1380
1381 /*
1382  * For a rotation which involves two leaf nodes, the "root node" is
1383  * the lowest level tree node which contains a path to both leafs. This
1384  * resulting set of information can be used to form a complete "subtree"
1385  *
1386  * This function is passed two full paths from the dinode down to a
1387  * pair of adjacent leaves. It's task is to figure out which path
1388  * index contains the subtree root - this can be the root index itself
1389  * in a worst-case rotation.
1390  *
1391  * The array index of the subtree root is passed back.
1392  */
1393 static int ocfs2_find_subtree_root(struct inode *inode,
1394                                    struct ocfs2_path *left,
1395                                    struct ocfs2_path *right)
1396 {
1397         int i = 0;
1398
1399         /*
1400          * Check that the caller passed in two paths from the same tree.
1401          */
1402         BUG_ON(path_root_bh(left) != path_root_bh(right));
1403
1404         do {
1405                 i++;
1406
1407                 /*
1408                  * The caller didn't pass two adjacent paths.
1409                  */
1410                 mlog_bug_on_msg(i > left->p_tree_depth,
1411                                 "Inode %lu, left depth %u, right depth %u\n"
1412                                 "left leaf blk %llu, right leaf blk %llu\n",
1413                                 inode->i_ino, left->p_tree_depth,
1414                                 right->p_tree_depth,
1415                                 (unsigned long long)path_leaf_bh(left)->b_blocknr,
1416                                 (unsigned long long)path_leaf_bh(right)->b_blocknr);
1417         } while (left->p_node[i].bh->b_blocknr ==
1418                  right->p_node[i].bh->b_blocknr);
1419
1420         return i - 1;
1421 }
1422
1423 typedef void (path_insert_t)(void *, struct buffer_head *);
1424
1425 /*
1426  * Traverse a btree path in search of cpos, starting at root_el.
1427  *
1428  * This code can be called with a cpos larger than the tree, in which
1429  * case it will return the rightmost path.
1430  */
1431 static int __ocfs2_find_path(struct inode *inode,
1432                              struct ocfs2_extent_list *root_el, u32 cpos,
1433                              path_insert_t *func, void *data)
1434 {
1435         int i, ret = 0;
1436         u32 range;
1437         u64 blkno;
1438         struct buffer_head *bh = NULL;
1439         struct ocfs2_extent_block *eb;
1440         struct ocfs2_extent_list *el;
1441         struct ocfs2_extent_rec *rec;
1442         struct ocfs2_inode_info *oi = OCFS2_I(inode);
1443
1444         el = root_el;
1445         while (el->l_tree_depth) {
1446                 if (le16_to_cpu(el->l_next_free_rec) == 0) {
1447                         ocfs2_error(inode->i_sb,
1448                                     "Inode %llu has empty extent list at "
1449                                     "depth %u\n",
1450                                     (unsigned long long)oi->ip_blkno,
1451                                     le16_to_cpu(el->l_tree_depth));
1452                         ret = -EROFS;
1453                         goto out;
1454
1455                 }
1456
1457                 for(i = 0; i < le16_to_cpu(el->l_next_free_rec) - 1; i++) {
1458                         rec = &el->l_recs[i];
1459
1460                         /*
1461                          * In the case that cpos is off the allocation
1462                          * tree, this should just wind up returning the
1463                          * rightmost record.
1464                          */
1465                         range = le32_to_cpu(rec->e_cpos) +
1466                                 ocfs2_rec_clusters(el, rec);
1467                         if (cpos >= le32_to_cpu(rec->e_cpos) && cpos < range)
1468                             break;
1469                 }
1470
1471                 blkno = le64_to_cpu(el->l_recs[i].e_blkno);
1472                 if (blkno == 0) {
1473                         ocfs2_error(inode->i_sb,
1474                                     "Inode %llu has bad blkno in extent list "
1475                                     "at depth %u (index %d)\n",
1476                                     (unsigned long long)oi->ip_blkno,
1477                                     le16_to_cpu(el->l_tree_depth), i);
1478                         ret = -EROFS;
1479                         goto out;
1480                 }
1481
1482                 brelse(bh);
1483                 bh = NULL;
1484                 ret = ocfs2_read_block(OCFS2_SB(inode->i_sb), blkno,
1485                                        &bh, OCFS2_BH_CACHED, inode);
1486                 if (ret) {
1487                         mlog_errno(ret);
1488                         goto out;
1489                 }
1490
1491                 eb = (struct ocfs2_extent_block *) bh->b_data;
1492                 el = &eb->h_list;
1493                 if (!OCFS2_IS_VALID_EXTENT_BLOCK(eb)) {
1494                         OCFS2_RO_ON_INVALID_EXTENT_BLOCK(inode->i_sb, eb);
1495                         ret = -EIO;
1496                         goto out;
1497                 }
1498
1499                 if (le16_to_cpu(el->l_next_free_rec) >
1500                     le16_to_cpu(el->l_count)) {
1501                         ocfs2_error(inode->i_sb,
1502                                     "Inode %llu has bad count in extent list "
1503                                     "at block %llu (next free=%u, count=%u)\n",
1504                                     (unsigned long long)oi->ip_blkno,
1505                                     (unsigned long long)bh->b_blocknr,
1506                                     le16_to_cpu(el->l_next_free_rec),
1507                                     le16_to_cpu(el->l_count));
1508                         ret = -EROFS;
1509                         goto out;
1510                 }
1511
1512                 if (func)
1513                         func(data, bh);
1514         }
1515
1516 out:
1517         /*
1518          * Catch any trailing bh that the loop didn't handle.
1519          */
1520         brelse(bh);
1521
1522         return ret;
1523 }
1524
1525 /*
1526  * Given an initialized path (that is, it has a valid root extent
1527  * list), this function will traverse the btree in search of the path
1528  * which would contain cpos.
1529  *
1530  * The path traveled is recorded in the path structure.
1531  *
1532  * Note that this will not do any comparisons on leaf node extent
1533  * records, so it will work fine in the case that we just added a tree
1534  * branch.
1535  */
1536 struct find_path_data {
1537         int index;
1538         struct ocfs2_path *path;
1539 };
1540 static void find_path_ins(void *data, struct buffer_head *bh)
1541 {
1542         struct find_path_data *fp = data;
1543
1544         get_bh(bh);
1545         ocfs2_path_insert_eb(fp->path, fp->index, bh);
1546         fp->index++;
1547 }
1548 static int ocfs2_find_path(struct inode *inode, struct ocfs2_path *path,
1549                            u32 cpos)
1550 {
1551         struct find_path_data data;
1552
1553         data.index = 1;
1554         data.path = path;
1555         return __ocfs2_find_path(inode, path_root_el(path), cpos,
1556                                  find_path_ins, &data);
1557 }
1558
1559 static void find_leaf_ins(void *data, struct buffer_head *bh)
1560 {
1561         struct ocfs2_extent_block *eb =(struct ocfs2_extent_block *)bh->b_data;
1562         struct ocfs2_extent_list *el = &eb->h_list;
1563         struct buffer_head **ret = data;
1564
1565         /* We want to retain only the leaf block. */
1566         if (le16_to_cpu(el->l_tree_depth) == 0) {
1567                 get_bh(bh);
1568                 *ret = bh;
1569         }
1570 }
1571 /*
1572  * Find the leaf block in the tree which would contain cpos. No
1573  * checking of the actual leaf is done.
1574  *
1575  * Some paths want to call this instead of allocating a path structure
1576  * and calling ocfs2_find_path().
1577  *
1578  * This function doesn't handle non btree extent lists.
1579  */
1580 int ocfs2_find_leaf(struct inode *inode, struct ocfs2_extent_list *root_el,
1581                     u32 cpos, struct buffer_head **leaf_bh)
1582 {
1583         int ret;
1584         struct buffer_head *bh = NULL;
1585
1586         ret = __ocfs2_find_path(inode, root_el, cpos, find_leaf_ins, &bh);
1587         if (ret) {
1588                 mlog_errno(ret);
1589                 goto out;
1590         }
1591
1592         *leaf_bh = bh;
1593 out:
1594         return ret;
1595 }
1596
1597 /*
1598  * Adjust the adjacent records (left_rec, right_rec) involved in a rotation.
1599  *
1600  * Basically, we've moved stuff around at the bottom of the tree and
1601  * we need to fix up the extent records above the changes to reflect
1602  * the new changes.
1603  *
1604  * left_rec: the record on the left.
1605  * left_child_el: is the child list pointed to by left_rec
1606  * right_rec: the record to the right of left_rec
1607  * right_child_el: is the child list pointed to by right_rec
1608  *
1609  * By definition, this only works on interior nodes.
1610  */
1611 static void ocfs2_adjust_adjacent_records(struct ocfs2_extent_rec *left_rec,
1612                                   struct ocfs2_extent_list *left_child_el,
1613                                   struct ocfs2_extent_rec *right_rec,
1614                                   struct ocfs2_extent_list *right_child_el)
1615 {
1616         u32 left_clusters, right_end;
1617
1618         /*
1619          * Interior nodes never have holes. Their cpos is the cpos of
1620          * the leftmost record in their child list. Their cluster
1621          * count covers the full theoretical range of their child list
1622          * - the range between their cpos and the cpos of the record
1623          * immediately to their right.
1624          */
1625         left_clusters = le32_to_cpu(right_child_el->l_recs[0].e_cpos);
1626         if (ocfs2_is_empty_extent(&right_child_el->l_recs[0])) {
1627                 BUG_ON(le16_to_cpu(right_child_el->l_next_free_rec) <= 1);
1628                 left_clusters = le32_to_cpu(right_child_el->l_recs[1].e_cpos);
1629         }
1630         left_clusters -= le32_to_cpu(left_rec->e_cpos);
1631         left_rec->e_int_clusters = cpu_to_le32(left_clusters);
1632
1633         /*
1634          * Calculate the rightmost cluster count boundary before
1635          * moving cpos - we will need to adjust clusters after
1636          * updating e_cpos to keep the same highest cluster count.
1637          */
1638         right_end = le32_to_cpu(right_rec->e_cpos);
1639         right_end += le32_to_cpu(right_rec->e_int_clusters);
1640
1641         right_rec->e_cpos = left_rec->e_cpos;
1642         le32_add_cpu(&right_rec->e_cpos, left_clusters);
1643
1644         right_end -= le32_to_cpu(right_rec->e_cpos);
1645         right_rec->e_int_clusters = cpu_to_le32(right_end);
1646 }
1647
1648 /*
1649  * Adjust the adjacent root node records involved in a
1650  * rotation. left_el_blkno is passed in as a key so that we can easily
1651  * find it's index in the root list.
1652  */
1653 static void ocfs2_adjust_root_records(struct ocfs2_extent_list *root_el,
1654                                       struct ocfs2_extent_list *left_el,
1655                                       struct ocfs2_extent_list *right_el,
1656                                       u64 left_el_blkno)
1657 {
1658         int i;
1659
1660         BUG_ON(le16_to_cpu(root_el->l_tree_depth) <=
1661                le16_to_cpu(left_el->l_tree_depth));
1662
1663         for(i = 0; i < le16_to_cpu(root_el->l_next_free_rec) - 1; i++) {
1664                 if (le64_to_cpu(root_el->l_recs[i].e_blkno) == left_el_blkno)
1665                         break;
1666         }
1667
1668         /*
1669          * The path walking code should have never returned a root and
1670          * two paths which are not adjacent.
1671          */
1672         BUG_ON(i >= (le16_to_cpu(root_el->l_next_free_rec) - 1));
1673
1674         ocfs2_adjust_adjacent_records(&root_el->l_recs[i], left_el,
1675                                       &root_el->l_recs[i + 1], right_el);
1676 }
1677
1678 /*
1679  * We've changed a leaf block (in right_path) and need to reflect that
1680  * change back up the subtree.
1681  *
1682  * This happens in multiple places:
1683  *   - When we've moved an extent record from the left path leaf to the right
1684  *     path leaf to make room for an empty extent in the left path leaf.
1685  *   - When our insert into the right path leaf is at the leftmost edge
1686  *     and requires an update of the path immediately to it's left. This
1687  *     can occur at the end of some types of rotation and appending inserts.
1688  *   - When we've adjusted the last extent record in the left path leaf and the
1689  *     1st extent record in the right path leaf during cross extent block merge.
1690  */
1691 static void ocfs2_complete_edge_insert(struct inode *inode, handle_t *handle,
1692                                        struct ocfs2_path *left_path,
1693                                        struct ocfs2_path *right_path,
1694                                        int subtree_index)
1695 {
1696         int ret, i, idx;
1697         struct ocfs2_extent_list *el, *left_el, *right_el;
1698         struct ocfs2_extent_rec *left_rec, *right_rec;
1699         struct buffer_head *root_bh = left_path->p_node[subtree_index].bh;
1700
1701         /*
1702          * Update the counts and position values within all the
1703          * interior nodes to reflect the leaf rotation we just did.
1704          *
1705          * The root node is handled below the loop.
1706          *
1707          * We begin the loop with right_el and left_el pointing to the
1708          * leaf lists and work our way up.
1709          *
1710          * NOTE: within this loop, left_el and right_el always refer
1711          * to the *child* lists.
1712          */
1713         left_el = path_leaf_el(left_path);
1714         right_el = path_leaf_el(right_path);
1715         for(i = left_path->p_tree_depth - 1; i > subtree_index; i--) {
1716                 mlog(0, "Adjust records at index %u\n", i);
1717
1718                 /*
1719                  * One nice property of knowing that all of these
1720                  * nodes are below the root is that we only deal with
1721                  * the leftmost right node record and the rightmost
1722                  * left node record.
1723                  */
1724                 el = left_path->p_node[i].el;
1725                 idx = le16_to_cpu(left_el->l_next_free_rec) - 1;
1726                 left_rec = &el->l_recs[idx];
1727
1728                 el = right_path->p_node[i].el;
1729                 right_rec = &el->l_recs[0];
1730
1731                 ocfs2_adjust_adjacent_records(left_rec, left_el, right_rec,
1732                                               right_el);
1733
1734                 ret = ocfs2_journal_dirty(handle, left_path->p_node[i].bh);
1735                 if (ret)
1736                         mlog_errno(ret);
1737
1738                 ret = ocfs2_journal_dirty(handle, right_path->p_node[i].bh);
1739                 if (ret)
1740                         mlog_errno(ret);
1741
1742                 /*
1743                  * Setup our list pointers now so that the current
1744                  * parents become children in the next iteration.
1745                  */
1746                 left_el = left_path->p_node[i].el;
1747                 right_el = right_path->p_node[i].el;
1748         }
1749
1750         /*
1751          * At the root node, adjust the two adjacent records which
1752          * begin our path to the leaves.
1753          */
1754
1755         el = left_path->p_node[subtree_index].el;
1756         left_el = left_path->p_node[subtree_index + 1].el;
1757         right_el = right_path->p_node[subtree_index + 1].el;
1758
1759         ocfs2_adjust_root_records(el, left_el, right_el,
1760                                   left_path->p_node[subtree_index + 1].bh->b_blocknr);
1761
1762         root_bh = left_path->p_node[subtree_index].bh;
1763
1764         ret = ocfs2_journal_dirty(handle, root_bh);
1765         if (ret)
1766                 mlog_errno(ret);
1767 }
1768
1769 static int ocfs2_rotate_subtree_right(struct inode *inode,
1770                                       handle_t *handle,
1771                                       struct ocfs2_path *left_path,
1772                                       struct ocfs2_path *right_path,
1773                                       int subtree_index)
1774 {
1775         int ret, i;
1776         struct buffer_head *right_leaf_bh;
1777         struct buffer_head *left_leaf_bh = NULL;
1778         struct buffer_head *root_bh;
1779         struct ocfs2_extent_list *right_el, *left_el;
1780         struct ocfs2_extent_rec move_rec;
1781
1782         left_leaf_bh = path_leaf_bh(left_path);
1783         left_el = path_leaf_el(left_path);
1784
1785         if (left_el->l_next_free_rec != left_el->l_count) {
1786                 ocfs2_error(inode->i_sb,
1787                             "Inode %llu has non-full interior leaf node %llu"
1788                             "(next free = %u)",
1789                             (unsigned long long)OCFS2_I(inode)->ip_blkno,
1790                             (unsigned long long)left_leaf_bh->b_blocknr,
1791                             le16_to_cpu(left_el->l_next_free_rec));
1792                 return -EROFS;
1793         }
1794
1795         /*
1796          * This extent block may already have an empty record, so we
1797          * return early if so.
1798          */
1799         if (ocfs2_is_empty_extent(&left_el->l_recs[0]))
1800                 return 0;
1801
1802         root_bh = left_path->p_node[subtree_index].bh;
1803         BUG_ON(root_bh != right_path->p_node[subtree_index].bh);
1804
1805         ret = ocfs2_journal_access(handle, inode, root_bh,
1806                                    OCFS2_JOURNAL_ACCESS_WRITE);
1807         if (ret) {
1808                 mlog_errno(ret);
1809                 goto out;
1810         }
1811
1812         for(i = subtree_index + 1; i < path_num_items(right_path); i++) {
1813                 ret = ocfs2_journal_access(handle, inode,
1814                                            right_path->p_node[i].bh,
1815                                            OCFS2_JOURNAL_ACCESS_WRITE);
1816                 if (ret) {
1817                         mlog_errno(ret);
1818                         goto out;
1819                 }
1820
1821                 ret = ocfs2_journal_access(handle, inode,
1822                                            left_path->p_node[i].bh,
1823                                            OCFS2_JOURNAL_ACCESS_WRITE);
1824                 if (ret) {
1825                         mlog_errno(ret);
1826                         goto out;
1827                 }
1828         }
1829
1830         right_leaf_bh = path_leaf_bh(right_path);
1831         right_el = path_leaf_el(right_path);
1832
1833         /* This is a code error, not a disk corruption. */
1834         mlog_bug_on_msg(!right_el->l_next_free_rec, "Inode %llu: Rotate fails "
1835                         "because rightmost leaf block %llu is empty\n",
1836                         (unsigned long long)OCFS2_I(inode)->ip_blkno,
1837                         (unsigned long long)right_leaf_bh->b_blocknr);
1838
1839         ocfs2_create_empty_extent(right_el);
1840
1841         ret = ocfs2_journal_dirty(handle, right_leaf_bh);
1842         if (ret) {
1843                 mlog_errno(ret);
1844                 goto out;
1845         }
1846
1847         /* Do the copy now. */
1848         i = le16_to_cpu(left_el->l_next_free_rec) - 1;
1849         move_rec = left_el->l_recs[i];
1850         right_el->l_recs[0] = move_rec;
1851
1852         /*
1853          * Clear out the record we just copied and shift everything
1854          * over, leaving an empty extent in the left leaf.
1855          *
1856          * We temporarily subtract from next_free_rec so that the
1857          * shift will lose the tail record (which is now defunct).
1858          */
1859         le16_add_cpu(&left_el->l_next_free_rec, -1);
1860         ocfs2_shift_records_right(left_el);
1861         memset(&left_el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
1862         le16_add_cpu(&left_el->l_next_free_rec, 1);
1863
1864         ret = ocfs2_journal_dirty(handle, left_leaf_bh);
1865         if (ret) {
1866                 mlog_errno(ret);
1867                 goto out;
1868         }
1869
1870         ocfs2_complete_edge_insert(inode, handle, left_path, right_path,
1871                                 subtree_index);
1872
1873 out:
1874         return ret;
1875 }
1876
1877 /*
1878  * Given a full path, determine what cpos value would return us a path
1879  * containing the leaf immediately to the left of the current one.
1880  *
1881  * Will return zero if the path passed in is already the leftmost path.
1882  */
1883 static int ocfs2_find_cpos_for_left_leaf(struct super_block *sb,
1884                                          struct ocfs2_path *path, u32 *cpos)
1885 {
1886         int i, j, ret = 0;
1887         u64 blkno;
1888         struct ocfs2_extent_list *el;
1889
1890         BUG_ON(path->p_tree_depth == 0);
1891
1892         *cpos = 0;
1893
1894         blkno = path_leaf_bh(path)->b_blocknr;
1895
1896         /* Start at the tree node just above the leaf and work our way up. */
1897         i = path->p_tree_depth - 1;
1898         while (i >= 0) {
1899                 el = path->p_node[i].el;
1900
1901                 /*
1902                  * Find the extent record just before the one in our
1903                  * path.
1904                  */
1905                 for(j = 0; j < le16_to_cpu(el->l_next_free_rec); j++) {
1906                         if (le64_to_cpu(el->l_recs[j].e_blkno) == blkno) {
1907                                 if (j == 0) {
1908                                         if (i == 0) {
1909                                                 /*
1910                                                  * We've determined that the
1911                                                  * path specified is already
1912                                                  * the leftmost one - return a
1913                                                  * cpos of zero.
1914                                                  */
1915                                                 goto out;
1916                                         }
1917                                         /*
1918                                          * The leftmost record points to our
1919                                          * leaf - we need to travel up the
1920                                          * tree one level.
1921                                          */
1922                                         goto next_node;
1923                                 }
1924
1925                                 *cpos = le32_to_cpu(el->l_recs[j - 1].e_cpos);
1926                                 *cpos = *cpos + ocfs2_rec_clusters(el,
1927                                                            &el->l_recs[j - 1]);
1928                                 *cpos = *cpos - 1;
1929                                 goto out;
1930                         }
1931                 }
1932
1933                 /*
1934                  * If we got here, we never found a valid node where
1935                  * the tree indicated one should be.
1936                  */
1937                 ocfs2_error(sb,
1938                             "Invalid extent tree at extent block %llu\n",
1939                             (unsigned long long)blkno);
1940                 ret = -EROFS;
1941                 goto out;
1942
1943 next_node:
1944                 blkno = path->p_node[i].bh->b_blocknr;
1945                 i--;
1946         }
1947
1948 out:
1949         return ret;
1950 }
1951
1952 /*
1953  * Extend the transaction by enough credits to complete the rotation,
1954  * and still leave at least the original number of credits allocated
1955  * to this transaction.
1956  */
1957 static int ocfs2_extend_rotate_transaction(handle_t *handle, int subtree_depth,
1958                                            int op_credits,
1959                                            struct ocfs2_path *path)
1960 {
1961         int credits = (path->p_tree_depth - subtree_depth) * 2 + 1 + op_credits;
1962
1963         if (handle->h_buffer_credits < credits)
1964                 return ocfs2_extend_trans(handle, credits);
1965
1966         return 0;
1967 }
1968
1969 /*
1970  * Trap the case where we're inserting into the theoretical range past
1971  * the _actual_ left leaf range. Otherwise, we'll rotate a record
1972  * whose cpos is less than ours into the right leaf.
1973  *
1974  * It's only necessary to look at the rightmost record of the left
1975  * leaf because the logic that calls us should ensure that the
1976  * theoretical ranges in the path components above the leaves are
1977  * correct.
1978  */
1979 static int ocfs2_rotate_requires_path_adjustment(struct ocfs2_path *left_path,
1980                                                  u32 insert_cpos)
1981 {
1982         struct ocfs2_extent_list *left_el;
1983         struct ocfs2_extent_rec *rec;
1984         int next_free;
1985
1986         left_el = path_leaf_el(left_path);
1987         next_free = le16_to_cpu(left_el->l_next_free_rec);
1988         rec = &left_el->l_recs[next_free - 1];
1989
1990         if (insert_cpos > le32_to_cpu(rec->e_cpos))
1991                 return 1;
1992         return 0;
1993 }
1994
1995 static int ocfs2_leftmost_rec_contains(struct ocfs2_extent_list *el, u32 cpos)
1996 {
1997         int next_free = le16_to_cpu(el->l_next_free_rec);
1998         unsigned int range;
1999         struct ocfs2_extent_rec *rec;
2000
2001         if (next_free == 0)
2002                 return 0;
2003
2004         rec = &el->l_recs[0];
2005         if (ocfs2_is_empty_extent(rec)) {
2006                 /* Empty list. */
2007                 if (next_free == 1)
2008                         return 0;
2009                 rec = &el->l_recs[1];
2010         }
2011
2012         range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
2013         if (cpos >= le32_to_cpu(rec->e_cpos) && cpos < range)
2014                 return 1;
2015         return 0;
2016 }
2017
2018 /*
2019  * Rotate all the records in a btree right one record, starting at insert_cpos.
2020  *
2021  * The path to the rightmost leaf should be passed in.
2022  *
2023  * The array is assumed to be large enough to hold an entire path (tree depth).
2024  *
2025  * Upon succesful return from this function:
2026  *
2027  * - The 'right_path' array will contain a path to the leaf block
2028  *   whose range contains e_cpos.
2029  * - That leaf block will have a single empty extent in list index 0.
2030  * - In the case that the rotation requires a post-insert update,
2031  *   *ret_left_path will contain a valid path which can be passed to
2032  *   ocfs2_insert_path().
2033  */
2034 static int ocfs2_rotate_tree_right(struct inode *inode,
2035                                    handle_t *handle,
2036                                    enum ocfs2_split_type split,
2037                                    u32 insert_cpos,
2038                                    struct ocfs2_path *right_path,
2039                                    struct ocfs2_path **ret_left_path)
2040 {
2041         int ret, start, orig_credits = handle->h_buffer_credits;
2042         u32 cpos;
2043         struct ocfs2_path *left_path = NULL;
2044
2045         *ret_left_path = NULL;
2046
2047         left_path = ocfs2_new_path(path_root_bh(right_path),
2048                                    path_root_el(right_path));
2049         if (!left_path) {
2050                 ret = -ENOMEM;
2051                 mlog_errno(ret);
2052                 goto out;
2053         }
2054
2055         ret = ocfs2_find_cpos_for_left_leaf(inode->i_sb, right_path, &cpos);
2056         if (ret) {
2057                 mlog_errno(ret);
2058                 goto out;
2059         }
2060
2061         mlog(0, "Insert: %u, first left path cpos: %u\n", insert_cpos, cpos);
2062
2063         /*
2064          * What we want to do here is:
2065          *
2066          * 1) Start with the rightmost path.
2067          *
2068          * 2) Determine a path to the leaf block directly to the left
2069          *    of that leaf.
2070          *
2071          * 3) Determine the 'subtree root' - the lowest level tree node
2072          *    which contains a path to both leaves.
2073          *
2074          * 4) Rotate the subtree.
2075          *
2076          * 5) Find the next subtree by considering the left path to be
2077          *    the new right path.
2078          *
2079          * The check at the top of this while loop also accepts
2080          * insert_cpos == cpos because cpos is only a _theoretical_
2081          * value to get us the left path - insert_cpos might very well
2082          * be filling that hole.
2083          *
2084          * Stop at a cpos of '0' because we either started at the
2085          * leftmost branch (i.e., a tree with one branch and a
2086          * rotation inside of it), or we've gone as far as we can in
2087          * rotating subtrees.
2088          */
2089         while (cpos && insert_cpos <= cpos) {
2090                 mlog(0, "Rotating a tree: ins. cpos: %u, left path cpos: %u\n",
2091                      insert_cpos, cpos);
2092
2093                 ret = ocfs2_find_path(inode, left_path, cpos);
2094                 if (ret) {
2095                         mlog_errno(ret);
2096                         goto out;
2097                 }
2098
2099                 mlog_bug_on_msg(path_leaf_bh(left_path) ==
2100                                 path_leaf_bh(right_path),
2101                                 "Inode %lu: error during insert of %u "
2102                                 "(left path cpos %u) results in two identical "
2103                                 "paths ending at %llu\n",
2104                                 inode->i_ino, insert_cpos, cpos,
2105                                 (unsigned long long)
2106                                 path_leaf_bh(left_path)->b_blocknr);
2107
2108                 if (split == SPLIT_NONE &&
2109                     ocfs2_rotate_requires_path_adjustment(left_path,
2110                                                           insert_cpos)) {
2111
2112                         /*
2113                          * We've rotated the tree as much as we
2114                          * should. The rest is up to
2115                          * ocfs2_insert_path() to complete, after the
2116                          * record insertion. We indicate this
2117                          * situation by returning the left path.
2118                          *
2119                          * The reason we don't adjust the records here
2120                          * before the record insert is that an error
2121                          * later might break the rule where a parent
2122                          * record e_cpos will reflect the actual
2123                          * e_cpos of the 1st nonempty record of the
2124                          * child list.
2125                          */
2126                         *ret_left_path = left_path;
2127                         goto out_ret_path;
2128                 }
2129
2130                 start = ocfs2_find_subtree_root(inode, left_path, right_path);
2131
2132                 mlog(0, "Subtree root at index %d (blk %llu, depth %d)\n",
2133                      start,
2134                      (unsigned long long) right_path->p_node[start].bh->b_blocknr,
2135                      right_path->p_tree_depth);
2136
2137                 ret = ocfs2_extend_rotate_transaction(handle, start,
2138                                                       orig_credits, right_path);
2139                 if (ret) {
2140                         mlog_errno(ret);
2141                         goto out;
2142                 }
2143
2144                 ret = ocfs2_rotate_subtree_right(inode, handle, left_path,
2145                                                  right_path, start);
2146                 if (ret) {
2147                         mlog_errno(ret);
2148                         goto out;
2149                 }
2150
2151                 if (split != SPLIT_NONE &&
2152                     ocfs2_leftmost_rec_contains(path_leaf_el(right_path),
2153                                                 insert_cpos)) {
2154                         /*
2155                          * A rotate moves the rightmost left leaf
2156                          * record over to the leftmost right leaf
2157                          * slot. If we're doing an extent split
2158                          * instead of a real insert, then we have to
2159                          * check that the extent to be split wasn't
2160                          * just moved over. If it was, then we can
2161                          * exit here, passing left_path back -
2162                          * ocfs2_split_extent() is smart enough to
2163                          * search both leaves.
2164                          */
2165                         *ret_left_path = left_path;
2166                         goto out_ret_path;
2167                 }
2168
2169                 /*
2170                  * There is no need to re-read the next right path
2171                  * as we know that it'll be our current left
2172                  * path. Optimize by copying values instead.
2173                  */
2174                 ocfs2_mv_path(right_path, left_path);
2175
2176                 ret = ocfs2_find_cpos_for_left_leaf(inode->i_sb, right_path,
2177                                                     &cpos);
2178                 if (ret) {
2179                         mlog_errno(ret);
2180                         goto out;
2181                 }
2182         }
2183
2184 out:
2185         ocfs2_free_path(left_path);
2186
2187 out_ret_path:
2188         return ret;
2189 }
2190
2191 static void ocfs2_update_edge_lengths(struct inode *inode, handle_t *handle,
2192                                       struct ocfs2_path *path)
2193 {
2194         int i, idx;
2195         struct ocfs2_extent_rec *rec;
2196         struct ocfs2_extent_list *el;
2197         struct ocfs2_extent_block *eb;
2198         u32 range;
2199
2200         /* Path should always be rightmost. */
2201         eb = (struct ocfs2_extent_block *)path_leaf_bh(path)->b_data;
2202         BUG_ON(eb->h_next_leaf_blk != 0ULL);
2203
2204         el = &eb->h_list;
2205         BUG_ON(le16_to_cpu(el->l_next_free_rec) == 0);
2206         idx = le16_to_cpu(el->l_next_free_rec) - 1;
2207         rec = &el->l_recs[idx];
2208         range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
2209
2210         for (i = 0; i < path->p_tree_depth; i++) {
2211                 el = path->p_node[i].el;
2212                 idx = le16_to_cpu(el->l_next_free_rec) - 1;
2213                 rec = &el->l_recs[idx];
2214
2215                 rec->e_int_clusters = cpu_to_le32(range);
2216                 le32_add_cpu(&rec->e_int_clusters, -le32_to_cpu(rec->e_cpos));
2217
2218                 ocfs2_journal_dirty(handle, path->p_node[i].bh);
2219         }
2220 }
2221
2222 static void ocfs2_unlink_path(struct inode *inode, handle_t *handle,
2223                               struct ocfs2_cached_dealloc_ctxt *dealloc,
2224                               struct ocfs2_path *path, int unlink_start)
2225 {
2226         int ret, i;
2227         struct ocfs2_extent_block *eb;
2228         struct ocfs2_extent_list *el;
2229         struct buffer_head *bh;
2230
2231         for(i = unlink_start; i < path_num_items(path); i++) {
2232                 bh = path->p_node[i].bh;
2233
2234                 eb = (struct ocfs2_extent_block *)bh->b_data;
2235                 /*
2236                  * Not all nodes might have had their final count
2237                  * decremented by the caller - handle this here.
2238                  */
2239                 el = &eb->h_list;
2240                 if (le16_to_cpu(el->l_next_free_rec) > 1) {
2241                         mlog(ML_ERROR,
2242                              "Inode %llu, attempted to remove extent block "
2243                              "%llu with %u records\n",
2244                              (unsigned long long)OCFS2_I(inode)->ip_blkno,
2245                              (unsigned long long)le64_to_cpu(eb->h_blkno),
2246                              le16_to_cpu(el->l_next_free_rec));
2247
2248                         ocfs2_journal_dirty(handle, bh);
2249                         ocfs2_remove_from_cache(inode, bh);
2250                         continue;
2251                 }
2252
2253                 el->l_next_free_rec = 0;
2254                 memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
2255
2256                 ocfs2_journal_dirty(handle, bh);
2257
2258                 ret = ocfs2_cache_extent_block_free(dealloc, eb);
2259                 if (ret)
2260                         mlog_errno(ret);
2261
2262                 ocfs2_remove_from_cache(inode, bh);
2263         }
2264 }
2265
2266 static void ocfs2_unlink_subtree(struct inode *inode, handle_t *handle,
2267                                  struct ocfs2_path *left_path,
2268                                  struct ocfs2_path *right_path,
2269                                  int subtree_index,
2270                                  struct ocfs2_cached_dealloc_ctxt *dealloc)
2271 {
2272         int i;
2273         struct buffer_head *root_bh = left_path->p_node[subtree_index].bh;
2274         struct ocfs2_extent_list *root_el = left_path->p_node[subtree_index].el;
2275         struct ocfs2_extent_list *el;
2276         struct ocfs2_extent_block *eb;
2277
2278         el = path_leaf_el(left_path);
2279
2280         eb = (struct ocfs2_extent_block *)right_path->p_node[subtree_index + 1].bh->b_data;
2281
2282         for(i = 1; i < le16_to_cpu(root_el->l_next_free_rec); i++)
2283                 if (root_el->l_recs[i].e_blkno == eb->h_blkno)
2284                         break;
2285
2286         BUG_ON(i >= le16_to_cpu(root_el->l_next_free_rec));
2287
2288         memset(&root_el->l_recs[i], 0, sizeof(struct ocfs2_extent_rec));
2289         le16_add_cpu(&root_el->l_next_free_rec, -1);
2290
2291         eb = (struct ocfs2_extent_block *)path_leaf_bh(left_path)->b_data;
2292         eb->h_next_leaf_blk = 0;
2293
2294         ocfs2_journal_dirty(handle, root_bh);
2295         ocfs2_journal_dirty(handle, path_leaf_bh(left_path));
2296
2297         ocfs2_unlink_path(inode, handle, dealloc, right_path,
2298                           subtree_index + 1);
2299 }
2300
2301 static int ocfs2_rotate_subtree_left(struct inode *inode, handle_t *handle,
2302                                      struct ocfs2_path *left_path,
2303                                      struct ocfs2_path *right_path,
2304                                      int subtree_index,
2305                                      struct ocfs2_cached_dealloc_ctxt *dealloc,
2306                                      int *deleted,
2307                                      struct ocfs2_extent_tree *et)
2308 {
2309         int ret, i, del_right_subtree = 0, right_has_empty = 0;
2310         struct buffer_head *root_bh, *et_root_bh = path_root_bh(right_path);
2311         struct ocfs2_extent_list *right_leaf_el, *left_leaf_el;
2312         struct ocfs2_extent_block *eb;
2313
2314         *deleted = 0;
2315
2316         right_leaf_el = path_leaf_el(right_path);
2317         left_leaf_el = path_leaf_el(left_path);
2318         root_bh = left_path->p_node[subtree_index].bh;
2319         BUG_ON(root_bh != right_path->p_node[subtree_index].bh);
2320
2321         if (!ocfs2_is_empty_extent(&left_leaf_el->l_recs[0]))
2322                 return 0;
2323
2324         eb = (struct ocfs2_extent_block *)path_leaf_bh(right_path)->b_data;
2325         if (ocfs2_is_empty_extent(&right_leaf_el->l_recs[0])) {
2326                 /*
2327                  * It's legal for us to proceed if the right leaf is
2328                  * the rightmost one and it has an empty extent. There
2329                  * are two cases to handle - whether the leaf will be
2330                  * empty after removal or not. If the leaf isn't empty
2331                  * then just remove the empty extent up front. The
2332                  * next block will handle empty leaves by flagging
2333                  * them for unlink.
2334                  *
2335                  * Non rightmost leaves will throw -EAGAIN and the
2336                  * caller can manually move the subtree and retry.
2337                  */
2338
2339                 if (eb->h_next_leaf_blk != 0ULL)
2340                         return -EAGAIN;
2341
2342                 if (le16_to_cpu(right_leaf_el->l_next_free_rec) > 1) {
2343                         ret = ocfs2_journal_access(handle, inode,
2344                                                    path_leaf_bh(right_path),
2345                                                    OCFS2_JOURNAL_ACCESS_WRITE);
2346                         if (ret) {
2347                                 mlog_errno(ret);
2348                                 goto out;
2349                         }
2350
2351                         ocfs2_remove_empty_extent(right_leaf_el);
2352                 } else
2353                         right_has_empty = 1;
2354         }
2355
2356         if (eb->h_next_leaf_blk == 0ULL &&
2357             le16_to_cpu(right_leaf_el->l_next_free_rec) == 1) {
2358                 /*
2359                  * We have to update i_last_eb_blk during the meta
2360                  * data delete.
2361                  */
2362                 ret = ocfs2_journal_access(handle, inode, et_root_bh,
2363                                            OCFS2_JOURNAL_ACCESS_WRITE);
2364                 if (ret) {
2365                         mlog_errno(ret);
2366                         goto out;
2367                 }
2368
2369                 del_right_subtree = 1;
2370         }
2371
2372         /*
2373          * Getting here with an empty extent in the right path implies
2374          * that it's the rightmost path and will be deleted.
2375          */
2376         BUG_ON(right_has_empty && !del_right_subtree);
2377
2378         ret = ocfs2_journal_access(handle, inode, root_bh,
2379                                    OCFS2_JOURNAL_ACCESS_WRITE);
2380         if (ret) {
2381                 mlog_errno(ret);
2382                 goto out;
2383         }
2384
2385         for(i = subtree_index + 1; i < path_num_items(right_path); i++) {
2386                 ret = ocfs2_journal_access(handle, inode,
2387                                            right_path->p_node[i].bh,
2388                                            OCFS2_JOURNAL_ACCESS_WRITE);
2389                 if (ret) {
2390                         mlog_errno(ret);
2391                         goto out;
2392                 }
2393
2394                 ret = ocfs2_journal_access(handle, inode,
2395                                            left_path->p_node[i].bh,
2396                                            OCFS2_JOURNAL_ACCESS_WRITE);
2397                 if (ret) {
2398                         mlog_errno(ret);
2399                         goto out;
2400                 }
2401         }
2402
2403         if (!right_has_empty) {
2404                 /*
2405                  * Only do this if we're moving a real
2406                  * record. Otherwise, the action is delayed until
2407                  * after removal of the right path in which case we
2408                  * can do a simple shift to remove the empty extent.
2409                  */
2410                 ocfs2_rotate_leaf(left_leaf_el, &right_leaf_el->l_recs[0]);
2411                 memset(&right_leaf_el->l_recs[0], 0,
2412                        sizeof(struct ocfs2_extent_rec));
2413         }
2414         if (eb->h_next_leaf_blk == 0ULL) {
2415                 /*
2416                  * Move recs over to get rid of empty extent, decrease
2417                  * next_free. This is allowed to remove the last
2418                  * extent in our leaf (setting l_next_free_rec to
2419                  * zero) - the delete code below won't care.
2420                  */
2421                 ocfs2_remove_empty_extent(right_leaf_el);
2422         }
2423
2424         ret = ocfs2_journal_dirty(handle, path_leaf_bh(left_path));
2425         if (ret)
2426                 mlog_errno(ret);
2427         ret = ocfs2_journal_dirty(handle, path_leaf_bh(right_path));
2428         if (ret)
2429                 mlog_errno(ret);
2430
2431         if (del_right_subtree) {
2432                 ocfs2_unlink_subtree(inode, handle, left_path, right_path,
2433                                      subtree_index, dealloc);
2434                 ocfs2_update_edge_lengths(inode, handle, left_path);
2435
2436                 eb = (struct ocfs2_extent_block *)path_leaf_bh(left_path)->b_data;
2437                 ocfs2_et_set_last_eb_blk(et, le64_to_cpu(eb->h_blkno));
2438
2439                 /*
2440                  * Removal of the extent in the left leaf was skipped
2441                  * above so we could delete the right path
2442                  * 1st.
2443                  */
2444                 if (right_has_empty)
2445                         ocfs2_remove_empty_extent(left_leaf_el);
2446
2447                 ret = ocfs2_journal_dirty(handle, et_root_bh);
2448                 if (ret)
2449                         mlog_errno(ret);
2450
2451                 *deleted = 1;
2452         } else
2453                 ocfs2_complete_edge_insert(inode, handle, left_path, right_path,
2454                                            subtree_index);
2455
2456 out:
2457         return ret;
2458 }
2459
2460 /*
2461  * Given a full path, determine what cpos value would return us a path
2462  * containing the leaf immediately to the right of the current one.
2463  *
2464  * Will return zero if the path passed in is already the rightmost path.
2465  *
2466  * This looks similar, but is subtly different to
2467  * ocfs2_find_cpos_for_left_leaf().
2468  */
2469 static int ocfs2_find_cpos_for_right_leaf(struct super_block *sb,
2470                                           struct ocfs2_path *path, u32 *cpos)
2471 {
2472         int i, j, ret = 0;
2473         u64 blkno;
2474         struct ocfs2_extent_list *el;
2475
2476         *cpos = 0;
2477
2478         if (path->p_tree_depth == 0)
2479                 return 0;
2480
2481         blkno = path_leaf_bh(path)->b_blocknr;
2482
2483         /* Start at the tree node just above the leaf and work our way up. */
2484         i = path->p_tree_depth - 1;
2485         while (i >= 0) {
2486                 int next_free;
2487
2488                 el = path->p_node[i].el;
2489
2490                 /*
2491                  * Find the extent record just after the one in our
2492                  * path.
2493                  */
2494                 next_free = le16_to_cpu(el->l_next_free_rec);
2495                 for(j = 0; j < le16_to_cpu(el->l_next_free_rec); j++) {
2496                         if (le64_to_cpu(el->l_recs[j].e_blkno) == blkno) {
2497                                 if (j == (next_free - 1)) {
2498                                         if (i == 0) {
2499                                                 /*
2500                                                  * We've determined that the
2501                                                  * path specified is already
2502                                                  * the rightmost one - return a
2503                                                  * cpos of zero.
2504                                                  */
2505                                                 goto out;
2506                                         }
2507                                         /*
2508                                          * The rightmost record points to our
2509                                          * leaf - we need to travel up the
2510                                          * tree one level.
2511                                          */
2512                                         goto next_node;
2513                                 }
2514
2515                                 *cpos = le32_to_cpu(el->l_recs[j + 1].e_cpos);
2516                                 goto out;
2517                         }
2518                 }
2519
2520                 /*
2521                  * If we got here, we never found a valid node where
2522                  * the tree indicated one should be.
2523                  */
2524                 ocfs2_error(sb,
2525                             "Invalid extent tree at extent block %llu\n",
2526                             (unsigned long long)blkno);
2527                 ret = -EROFS;
2528                 goto out;
2529
2530 next_node:
2531                 blkno = path->p_node[i].bh->b_blocknr;
2532                 i--;
2533         }
2534
2535 out:
2536         return ret;
2537 }
2538
2539 static int ocfs2_rotate_rightmost_leaf_left(struct inode *inode,
2540                                             handle_t *handle,
2541                                             struct buffer_head *bh,
2542                                             struct ocfs2_extent_list *el)
2543 {
2544         int ret;
2545
2546         if (!ocfs2_is_empty_extent(&el->l_recs[0]))
2547                 return 0;
2548
2549         ret = ocfs2_journal_access(handle, inode, bh,
2550                                    OCFS2_JOURNAL_ACCESS_WRITE);
2551         if (ret) {
2552                 mlog_errno(ret);
2553                 goto out;
2554         }
2555
2556         ocfs2_remove_empty_extent(el);
2557
2558         ret = ocfs2_journal_dirty(handle, bh);
2559         if (ret)
2560                 mlog_errno(ret);
2561
2562 out:
2563         return ret;
2564 }
2565
2566 static int __ocfs2_rotate_tree_left(struct inode *inode,
2567                                     handle_t *handle, int orig_credits,
2568                                     struct ocfs2_path *path,
2569                                     struct ocfs2_cached_dealloc_ctxt *dealloc,
2570                                     struct ocfs2_path **empty_extent_path,
2571                                     struct ocfs2_extent_tree *et)
2572 {
2573         int ret, subtree_root, deleted;
2574         u32 right_cpos;
2575         struct ocfs2_path *left_path = NULL;
2576         struct ocfs2_path *right_path = NULL;
2577
2578         BUG_ON(!ocfs2_is_empty_extent(&(path_leaf_el(path)->l_recs[0])));
2579
2580         *empty_extent_path = NULL;
2581
2582         ret = ocfs2_find_cpos_for_right_leaf(inode->i_sb, path,
2583                                              &right_cpos);
2584         if (ret) {
2585                 mlog_errno(ret);
2586                 goto out;
2587         }
2588
2589         left_path = ocfs2_new_path(path_root_bh(path),
2590                                    path_root_el(path));
2591         if (!left_path) {
2592                 ret = -ENOMEM;
2593                 mlog_errno(ret);
2594                 goto out;
2595         }
2596
2597         ocfs2_cp_path(left_path, path);
2598
2599         right_path = ocfs2_new_path(path_root_bh(path),
2600                                     path_root_el(path));
2601         if (!right_path) {
2602                 ret = -ENOMEM;
2603                 mlog_errno(ret);
2604                 goto out;
2605         }
2606
2607         while (right_cpos) {
2608                 ret = ocfs2_find_path(inode, right_path, right_cpos);
2609                 if (ret) {
2610                         mlog_errno(ret);
2611                         goto out;
2612                 }
2613
2614                 subtree_root = ocfs2_find_subtree_root(inode, left_path,
2615                                                        right_path);
2616
2617                 mlog(0, "Subtree root at index %d (blk %llu, depth %d)\n",
2618                      subtree_root,
2619                      (unsigned long long)
2620                      right_path->p_node[subtree_root].bh->b_blocknr,
2621                      right_path->p_tree_depth);
2622
2623                 ret = ocfs2_extend_rotate_transaction(handle, subtree_root,
2624                                                       orig_credits, left_path);
2625                 if (ret) {
2626                         mlog_errno(ret);
2627                         goto out;
2628                 }
2629
2630                 /*
2631                  * Caller might still want to make changes to the
2632                  * tree root, so re-add it to the journal here.
2633                  */
2634                 ret = ocfs2_journal_access(handle, inode,
2635                                            path_root_bh(left_path),
2636                                            OCFS2_JOURNAL_ACCESS_WRITE);
2637                 if (ret) {
2638                         mlog_errno(ret);
2639                         goto out;
2640                 }
2641
2642                 ret = ocfs2_rotate_subtree_left(inode, handle, left_path,
2643                                                 right_path, subtree_root,
2644                                                 dealloc, &deleted, et);
2645                 if (ret == -EAGAIN) {
2646                         /*
2647                          * The rotation has to temporarily stop due to
2648                          * the right subtree having an empty
2649                          * extent. Pass it back to the caller for a
2650                          * fixup.
2651                          */
2652                         *empty_extent_path = right_path;
2653                         right_path = NULL;
2654                         goto out;
2655                 }
2656                 if (ret) {
2657                         mlog_errno(ret);
2658                         goto out;
2659                 }
2660
2661                 /*
2662                  * The subtree rotate might have removed records on
2663                  * the rightmost edge. If so, then rotation is
2664                  * complete.
2665                  */
2666                 if (deleted)
2667                         break;
2668
2669                 ocfs2_mv_path(left_path, right_path);
2670
2671                 ret = ocfs2_find_cpos_for_right_leaf(inode->i_sb, left_path,
2672                                                      &right_cpos);
2673                 if (ret) {
2674                         mlog_errno(ret);
2675                         goto out;
2676                 }
2677         }
2678
2679 out:
2680         ocfs2_free_path(right_path);
2681         ocfs2_free_path(left_path);
2682
2683         return ret;
2684 }
2685
2686 static int ocfs2_remove_rightmost_path(struct inode *inode, handle_t *handle,
2687                                 struct ocfs2_path *path,
2688                                 struct ocfs2_cached_dealloc_ctxt *dealloc,
2689                                 struct ocfs2_extent_tree *et)
2690 {
2691         int ret, subtree_index;
2692         u32 cpos;
2693         struct ocfs2_path *left_path = NULL;
2694         struct ocfs2_extent_block *eb;
2695         struct ocfs2_extent_list *el;
2696
2697
2698         ret = ocfs2_et_sanity_check(inode, et);
2699         if (ret)
2700                 goto out;
2701         /*
2702          * There's two ways we handle this depending on
2703          * whether path is the only existing one.
2704          */
2705         ret = ocfs2_extend_rotate_transaction(handle, 0,
2706                                               handle->h_buffer_credits,
2707                                               path);
2708         if (ret) {
2709                 mlog_errno(ret);
2710                 goto out;
2711         }
2712
2713         ret = ocfs2_journal_access_path(inode, handle, path);
2714         if (ret) {
2715                 mlog_errno(ret);
2716                 goto out;
2717         }
2718
2719         ret = ocfs2_find_cpos_for_left_leaf(inode->i_sb, path, &cpos);
2720         if (ret) {
2721                 mlog_errno(ret);
2722                 goto out;
2723         }
2724
2725         if (cpos) {
2726                 /*
2727                  * We have a path to the left of this one - it needs
2728                  * an update too.
2729                  */
2730                 left_path = ocfs2_new_path(path_root_bh(path),
2731                                            path_root_el(path));
2732                 if (!left_path) {
2733                         ret = -ENOMEM;
2734                         mlog_errno(ret);
2735                         goto out;
2736                 }
2737
2738                 ret = ocfs2_find_path(inode, left_path, cpos);
2739                 if (ret) {
2740                         mlog_errno(ret);
2741                         goto out;
2742                 }
2743
2744                 ret = ocfs2_journal_access_path(inode, handle, left_path);
2745                 if (ret) {
2746                         mlog_errno(ret);
2747                         goto out;
2748                 }
2749
2750                 subtree_index = ocfs2_find_subtree_root(inode, left_path, path);
2751
2752                 ocfs2_unlink_subtree(inode, handle, left_path, path,
2753                                      subtree_index, dealloc);
2754                 ocfs2_update_edge_lengths(inode, handle, left_path);
2755
2756                 eb = (struct ocfs2_extent_block *)path_leaf_bh(left_path)->b_data;
2757                 ocfs2_et_set_last_eb_blk(et, le64_to_cpu(eb->h_blkno));
2758         } else {
2759                 /*
2760                  * 'path' is also the leftmost path which
2761                  * means it must be the only one. This gets
2762                  * handled differently because we want to
2763                  * revert the inode back to having extents
2764                  * in-line.
2765                  */
2766                 ocfs2_unlink_path(inode, handle, dealloc, path, 1);
2767
2768                 el = et->root_el;
2769                 el->l_tree_depth = 0;
2770                 el->l_next_free_rec = 0;
2771                 memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
2772
2773                 ocfs2_et_set_last_eb_blk(et, 0);
2774         }
2775
2776         ocfs2_journal_dirty(handle, path_root_bh(path));
2777
2778 out:
2779         ocfs2_free_path(left_path);
2780         return ret;
2781 }
2782
2783 /*
2784  * Left rotation of btree records.
2785  *
2786  * In many ways, this is (unsurprisingly) the opposite of right
2787  * rotation. We start at some non-rightmost path containing an empty
2788  * extent in the leaf block. The code works its way to the rightmost
2789  * path by rotating records to the left in every subtree.
2790  *
2791  * This is used by any code which reduces the number of extent records
2792  * in a leaf. After removal, an empty record should be placed in the
2793  * leftmost list position.
2794  *
2795  * This won't handle a length update of the rightmost path records if
2796  * the rightmost tree leaf record is removed so the caller is
2797  * responsible for detecting and correcting that.
2798  */
2799 static int ocfs2_rotate_tree_left(struct inode *inode, handle_t *handle,
2800                                   struct ocfs2_path *path,
2801                                   struct ocfs2_cached_dealloc_ctxt *dealloc,
2802                                   struct ocfs2_extent_tree *et)
2803 {
2804         int ret, orig_credits = handle->h_buffer_credits;
2805         struct ocfs2_path *tmp_path = NULL, *restart_path = NULL;
2806         struct ocfs2_extent_block *eb;
2807         struct ocfs2_extent_list *el;
2808
2809         el = path_leaf_el(path);
2810         if (!ocfs2_is_empty_extent(&el->l_recs[0]))
2811                 return 0;
2812
2813         if (path->p_tree_depth == 0) {
2814 rightmost_no_delete:
2815                 /*
2816                  * Inline extents. This is trivially handled, so do
2817                  * it up front.
2818                  */
2819                 ret = ocfs2_rotate_rightmost_leaf_left(inode, handle,
2820                                                        path_leaf_bh(path),
2821                                                        path_leaf_el(path));
2822                 if (ret)
2823                         mlog_errno(ret);
2824                 goto out;
2825         }
2826
2827         /*
2828          * Handle rightmost branch now. There's several cases:
2829          *  1) simple rotation leaving records in there. That's trivial.
2830          *  2) rotation requiring a branch delete - there's no more
2831          *     records left. Two cases of this:
2832          *     a) There are branches to the left.
2833          *     b) This is also the leftmost (the only) branch.
2834          *
2835          *  1) is handled via ocfs2_rotate_rightmost_leaf_left()
2836          *  2a) we need the left branch so that we can update it with the unlink
2837          *  2b) we need to bring the inode back to inline extents.
2838          */
2839
2840         eb = (struct ocfs2_extent_block *)path_leaf_bh(path)->b_data;
2841         el = &eb->h_list;
2842         if (eb->h_next_leaf_blk == 0) {
2843                 /*
2844                  * This gets a bit tricky if we're going to delete the
2845                  * rightmost path. Get the other cases out of the way
2846                  * 1st.
2847                  */
2848                 if (le16_to_cpu(el->l_next_free_rec) > 1)
2849                         goto rightmost_no_delete;
2850
2851                 if (le16_to_cpu(el->l_next_free_rec) == 0) {
2852                         ret = -EIO;
2853                         ocfs2_error(inode->i_sb,
2854                                     "Inode %llu has empty extent block at %llu",
2855                                     (unsigned long long)OCFS2_I(inode)->ip_blkno,
2856                                     (unsigned long long)le64_to_cpu(eb->h_blkno));
2857                         goto out;
2858                 }
2859
2860                 /*
2861                  * XXX: The caller can not trust "path" any more after
2862                  * this as it will have been deleted. What do we do?
2863                  *
2864                  * In theory the rotate-for-merge code will never get
2865                  * here because it'll always ask for a rotate in a
2866                  * nonempty list.
2867                  */
2868
2869                 ret = ocfs2_remove_rightmost_path(inode, handle, path,
2870                                                   dealloc, et);
2871                 if (ret)
2872                         mlog_errno(ret);
2873                 goto out;
2874         }
2875
2876         /*
2877          * Now we can loop, remembering the path we get from -EAGAIN
2878          * and restarting from there.
2879          */
2880 try_rotate:
2881         ret = __ocfs2_rotate_tree_left(inode, handle, orig_credits, path,
2882                                        dealloc, &restart_path, et);
2883         if (ret && ret != -EAGAIN) {
2884                 mlog_errno(ret);
2885                 goto out;
2886         }
2887
2888         while (ret == -EAGAIN) {
2889                 tmp_path = restart_path;
2890                 restart_path = NULL;
2891
2892                 ret = __ocfs2_rotate_tree_left(inode, handle, orig_credits,
2893                                                tmp_path, dealloc,
2894                                                &restart_path, et);
2895                 if (ret && ret != -EAGAIN) {
2896                         mlog_errno(ret);
2897                         goto out;
2898                 }
2899
2900                 ocfs2_free_path(tmp_path);
2901                 tmp_path = NULL;
2902
2903                 if (ret == 0)
2904                         goto try_rotate;
2905         }
2906
2907 out:
2908         ocfs2_free_path(tmp_path);
2909         ocfs2_free_path(restart_path);
2910         return ret;
2911 }
2912
2913 static void ocfs2_cleanup_merge(struct ocfs2_extent_list *el,
2914                                 int index)
2915 {
2916         struct ocfs2_extent_rec *rec = &el->l_recs[index];
2917         unsigned int size;
2918
2919         if (rec->e_leaf_clusters == 0) {
2920                 /*
2921                  * We consumed all of the merged-from record. An empty
2922                  * extent cannot exist anywhere but the 1st array
2923                  * position, so move things over if the merged-from
2924                  * record doesn't occupy that position.
2925                  *
2926                  * This creates a new empty extent so the caller
2927                  * should be smart enough to have removed any existing
2928                  * ones.
2929                  */
2930                 if (index > 0) {
2931                         BUG_ON(ocfs2_is_empty_extent(&el->l_recs[0]));
2932                         size = index * sizeof(struct ocfs2_extent_rec);
2933                         memmove(&el->l_recs[1], &el->l_recs[0], size);
2934                 }
2935
2936                 /*
2937                  * Always memset - the caller doesn't check whether it
2938                  * created an empty extent, so there could be junk in
2939                  * the other fields.
2940                  */
2941                 memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
2942         }
2943 }
2944
2945 static int ocfs2_get_right_path(struct inode *inode,
2946                                 struct ocfs2_path *left_path,
2947                                 struct ocfs2_path **ret_right_path)
2948 {
2949         int ret;
2950         u32 right_cpos;
2951         struct ocfs2_path *right_path = NULL;
2952         struct ocfs2_extent_list *left_el;
2953
2954         *ret_right_path = NULL;
2955
2956         /* This function shouldn't be called for non-trees. */
2957         BUG_ON(left_path->p_tree_depth == 0);
2958
2959         left_el = path_leaf_el(left_path);
2960         BUG_ON(left_el->l_next_free_rec != left_el->l_count);
2961
2962         ret = ocfs2_find_cpos_for_right_leaf(inode->i_sb, left_path,
2963                                              &right_cpos);
2964         if (ret) {
2965                 mlog_errno(ret);
2966                 goto out;
2967         }
2968
2969         /* This function shouldn't be called for the rightmost leaf. */
2970         BUG_ON(right_cpos == 0);
2971
2972         right_path = ocfs2_new_path(path_root_bh(left_path),
2973                                     path_root_el(left_path));
2974         if (!right_path) {
2975                 ret = -ENOMEM;
2976                 mlog_errno(ret);
2977                 goto out;
2978         }
2979
2980         ret = ocfs2_find_path(inode, right_path, right_cpos);
2981         if (ret) {
2982                 mlog_errno(ret);
2983                 goto out;
2984         }
2985
2986         *ret_right_path = right_path;
2987 out:
2988         if (ret)
2989                 ocfs2_free_path(right_path);
2990         return ret;
2991 }
2992
2993 /*
2994  * Remove split_rec clusters from the record at index and merge them
2995  * onto the beginning of the record "next" to it.
2996  * For index < l_count - 1, the next means the extent rec at index + 1.
2997  * For index == l_count - 1, the "next" means the 1st extent rec of the
2998  * next extent block.
2999  */
3000 static int ocfs2_merge_rec_right(struct inode *inode,
3001                                  struct ocfs2_path *left_path,
3002                                  handle_t *handle,
3003                                  struct ocfs2_extent_rec *split_rec,
3004                                  int index)
3005 {
3006         int ret, next_free, i;
3007         unsigned int split_clusters = le16_to_cpu(split_rec->e_leaf_clusters);
3008         struct ocfs2_extent_rec *left_rec;
3009         struct ocfs2_extent_rec *right_rec;
3010         struct ocfs2_extent_list *right_el;
3011         struct ocfs2_path *right_path = NULL;
3012         int subtree_index = 0;
3013         struct ocfs2_extent_list *el = path_leaf_el(left_path);
3014         struct buffer_head *bh = path_leaf_bh(left_path);
3015         struct buffer_head *root_bh = NULL;
3016
3017         BUG_ON(index >= le16_to_cpu(el->l_next_free_rec));
3018         left_rec = &el->l_recs[index];
3019
3020         if (index == le16_to_cpu(el->l_next_free_rec) - 1 &&
3021             le16_to_cpu(el->l_next_free_rec) == le16_to_cpu(el->l_count)) {
3022                 /* we meet with a cross extent block merge. */
3023                 ret = ocfs2_get_right_path(inode, left_path, &right_path);
3024                 if (ret) {
3025                         mlog_errno(ret);
3026                         goto out;
3027                 }
3028
3029                 right_el = path_leaf_el(right_path);
3030                 next_free = le16_to_cpu(right_el->l_next_free_rec);
3031                 BUG_ON(next_free <= 0);
3032                 right_rec = &right_el->l_recs[0];
3033                 if (ocfs2_is_empty_extent(right_rec)) {
3034                         BUG_ON(next_free <= 1);
3035                         right_rec = &right_el->l_recs[1];
3036                 }
3037
3038                 BUG_ON(le32_to_cpu(left_rec->e_cpos) +
3039                        le16_to_cpu(left_rec->e_leaf_clusters) !=
3040                        le32_to_cpu(right_rec->e_cpos));
3041
3042                 subtree_index = ocfs2_find_subtree_root(inode,
3043                                                         left_path, right_path);
3044
3045                 ret = ocfs2_extend_rotate_transaction(handle, subtree_index,
3046                                                       handle->h_buffer_credits,
3047                                                       right_path);
3048                 if (ret) {
3049                         mlog_errno(ret);
3050                         goto out;
3051                 }
3052
3053                 root_bh = left_path->p_node[subtree_index].bh;
3054                 BUG_ON(root_bh != right_path->p_node[subtree_index].bh);
3055
3056                 ret = ocfs2_journal_access(handle, inode, root_bh,
3057                                            OCFS2_JOURNAL_ACCESS_WRITE);
3058                 if (ret) {
3059                         mlog_errno(ret);
3060                         goto out;
3061                 }
3062
3063                 for (i = subtree_index + 1;
3064                      i < path_num_items(right_path); i++) {
3065                         ret = ocfs2_journal_access(handle, inode,
3066                                                    right_path->p_node[i].bh,
3067                                                    OCFS2_JOURNAL_ACCESS_WRITE);
3068                         if (ret) {
3069                                 mlog_errno(ret);
3070                                 goto out;
3071                         }
3072
3073                         ret = ocfs2_journal_access(handle, inode,
3074                                                    left_path->p_node[i].bh,
3075                                                    OCFS2_JOURNAL_ACCESS_WRITE);
3076                         if (ret) {
3077                                 mlog_errno(ret);
3078                                 goto out;
3079                         }
3080                 }
3081
3082         } else {
3083                 BUG_ON(index == le16_to_cpu(el->l_next_free_rec) - 1);
3084                 right_rec = &el->l_recs[index + 1];
3085         }
3086
3087         ret = ocfs2_journal_access(handle, inode, bh,
3088                                    OCFS2_JOURNAL_ACCESS_WRITE);
3089         if (ret) {
3090                 mlog_errno(ret);
3091                 goto out;
3092         }
3093
3094         le16_add_cpu(&left_rec->e_leaf_clusters, -split_clusters);
3095
3096         le32_add_cpu(&right_rec->e_cpos, -split_clusters);
3097         le64_add_cpu(&right_rec->e_blkno,
3098                      -ocfs2_clusters_to_blocks(inode->i_sb, split_clusters));
3099         le16_add_cpu(&right_rec->e_leaf_clusters, split_clusters);
3100
3101         ocfs2_cleanup_merge(el, index);
3102
3103         ret = ocfs2_journal_dirty(handle, bh);
3104         if (ret)
3105                 mlog_errno(ret);
3106
3107         if (right_path) {
3108                 ret = ocfs2_journal_dirty(handle, path_leaf_bh(right_path));
3109                 if (ret)
3110                         mlog_errno(ret);
3111
3112                 ocfs2_complete_edge_insert(inode, handle, left_path,
3113                                            right_path, subtree_index);
3114         }
3115 out:
3116         if (right_path)
3117                 ocfs2_free_path(right_path);
3118         return ret;
3119 }
3120
3121 static int ocfs2_get_left_path(struct inode *inode,
3122                                struct ocfs2_path *right_path,
3123                                struct ocfs2_path **ret_left_path)
3124 {
3125         int ret;
3126         u32 left_cpos;
3127         struct ocfs2_path *left_path = NULL;
3128
3129         *ret_left_path = NULL;
3130
3131         /* This function shouldn't be called for non-trees. */
3132         BUG_ON(right_path->p_tree_depth == 0);
3133
3134         ret = ocfs2_find_cpos_for_left_leaf(inode->i_sb,
3135                                             right_path, &left_cpos);
3136         if (ret) {
3137                 mlog_errno(ret);
3138                 goto out;
3139         }
3140
3141         /* This function shouldn't be called for the leftmost leaf. */
3142         BUG_ON(left_cpos == 0);
3143
3144         left_path = ocfs2_new_path(path_root_bh(right_path),
3145                                    path_root_el(right_path));
3146         if (!left_path) {
3147                 ret = -ENOMEM;
3148                 mlog_errno(ret);
3149                 goto out;
3150         }
3151
3152         ret = ocfs2_find_path(inode, left_path, left_cpos);
3153         if (ret) {
3154                 mlog_errno(ret);
3155                 goto out;
3156         }
3157
3158         *ret_left_path = left_path;
3159 out:
3160         if (ret)
3161                 ocfs2_free_path(left_path);
3162         return ret;
3163 }
3164
3165 /*
3166  * Remove split_rec clusters from the record at index and merge them
3167  * onto the tail of the record "before" it.
3168  * For index > 0, the "before" means the extent rec at index - 1.
3169  *
3170  * For index == 0, the "before" means the last record of the previous
3171  * extent block. And there is also a situation that we may need to
3172  * remove the rightmost leaf extent block in the right_path and change
3173  * the right path to indicate the new rightmost path.
3174  */
3175 static int ocfs2_merge_rec_left(struct inode *inode,
3176                                 struct ocfs2_path *right_path,
3177                                 handle_t *handle,
3178                                 struct ocfs2_extent_rec *split_rec,
3179                                 struct ocfs2_cached_dealloc_ctxt *dealloc,
3180                                 struct ocfs2_extent_tree *et,
3181                                 int index)
3182 {
3183         int ret, i, subtree_index = 0, has_empty_extent = 0;
3184         unsigned int split_clusters = le16_to_cpu(split_rec->e_leaf_clusters);
3185         struct ocfs2_extent_rec *left_rec;
3186         struct ocfs2_extent_rec *right_rec;
3187         struct ocfs2_extent_list *el = path_leaf_el(right_path);
3188         struct buffer_head *bh = path_leaf_bh(right_path);
3189         struct buffer_head *root_bh = NULL;
3190         struct ocfs2_path *left_path = NULL;
3191         struct ocfs2_extent_list *left_el;
3192
3193         BUG_ON(index < 0);
3194
3195         right_rec = &el->l_recs[index];
3196         if (index == 0) {
3197                 /* we meet with a cross extent block merge. */
3198                 ret = ocfs2_get_left_path(inode, right_path, &left_path);
3199                 if (ret) {
3200                         mlog_errno(ret);
3201                         goto out;
3202                 }
3203
3204                 left_el = path_leaf_el(left_path);
3205                 BUG_ON(le16_to_cpu(left_el->l_next_free_rec) !=
3206                        le16_to_cpu(left_el->l_count));
3207
3208                 left_rec = &left_el->l_recs[
3209                                 le16_to_cpu(left_el->l_next_free_rec) - 1];
3210                 BUG_ON(le32_to_cpu(left_rec->e_cpos) +
3211                        le16_to_cpu(left_rec->e_leaf_clusters) !=
3212                        le32_to_cpu(split_rec->e_cpos));
3213
3214                 subtree_index = ocfs2_find_subtree_root(inode,
3215                                                         left_path, right_path);
3216
3217                 ret = ocfs2_extend_rotate_transaction(handle, subtree_index,
3218                                                       handle->h_buffer_credits,
3219                                                       left_path);
3220                 if (ret) {
3221                         mlog_errno(ret);
3222                         goto out;
3223                 }
3224
3225                 root_bh = left_path->p_node[subtree_index].bh;
3226                 BUG_ON(root_bh != right_path->p_node[subtree_index].bh);
3227
3228                 ret = ocfs2_journal_access(handle, inode, root_bh,
3229                                            OCFS2_JOURNAL_ACCESS_WRITE);
3230                 if (ret) {
3231                         mlog_errno(ret);
3232                         goto out;
3233                 }
3234
3235                 for (i = subtree_index + 1;
3236                      i < path_num_items(right_path); i++) {
3237                         ret = ocfs2_journal_access(handle, inode,
3238                                                    right_path->p_node[i].bh,
3239                                                    OCFS2_JOURNAL_ACCESS_WRITE);
3240                         if (ret) {
3241                                 mlog_errno(ret);
3242                                 goto out;
3243                         }
3244
3245                         ret = ocfs2_journal_access(handle, inode,
3246                                                    left_path->p_node[i].bh,
3247                                                    OCFS2_JOURNAL_ACCESS_WRITE);
3248                         if (ret) {
3249                                 mlog_errno(ret);
3250                                 goto out;
3251                         }
3252                 }
3253         } else {
3254                 left_rec = &el->l_recs[index - 1];
3255                 if (ocfs2_is_empty_extent(&el->l_recs[0]))
3256                         has_empty_extent = 1;
3257         }
3258
3259         ret = ocfs2_journal_access(handle, inode, bh,
3260                                    OCFS2_JOURNAL_ACCESS_WRITE);
3261         if (ret) {
3262                 mlog_errno(ret);
3263                 goto out;
3264         }
3265
3266         if (has_empty_extent && index == 1) {
3267                 /*
3268                  * The easy case - we can just plop the record right in.
3269                  */
3270                 *left_rec = *split_rec;
3271
3272                 has_empty_extent = 0;
3273         } else
3274                 le16_add_cpu(&left_rec->e_leaf_clusters, split_clusters);
3275
3276         le32_add_cpu(&right_rec->e_cpos, split_clusters);
3277         le64_add_cpu(&right_rec->e_blkno,
3278                      ocfs2_clusters_to_blocks(inode->i_sb, split_clusters));
3279         le16_add_cpu(&right_rec->e_leaf_clusters, -split_clusters);
3280
3281         ocfs2_cleanup_merge(el, index);
3282
3283         ret = ocfs2_journal_dirty(handle, bh);
3284         if (ret)
3285                 mlog_errno(ret);
3286
3287         if (left_path) {
3288                 ret = ocfs2_journal_dirty(handle, path_leaf_bh(left_path));
3289                 if (ret)
3290                         mlog_errno(ret);
3291
3292                 /*
3293                  * In the situation that the right_rec is empty and the extent
3294                  * block is empty also,  ocfs2_complete_edge_insert can't handle
3295                  * it and we need to delete the right extent block.
3296                  */
3297                 if (le16_to_cpu(right_rec->e_leaf_clusters) == 0 &&
3298                     le16_to_cpu(el->l_next_free_rec) == 1) {
3299
3300                         ret = ocfs2_remove_rightmost_path(inode, handle,
3301                                                           right_path,
3302                                                           dealloc, et);
3303                         if (ret) {
3304                                 mlog_errno(ret);
3305                                 goto out;
3306                         }
3307
3308                         /* Now the rightmost extent block has been deleted.
3309                          * So we use the new rightmost path.
3310                          */
3311                         ocfs2_mv_path(right_path, left_path);
3312                         left_path = NULL;
3313                 } else
3314                         ocfs2_complete_edge_insert(inode, handle, left_path,
3315                                                    right_path, subtree_index);
3316         }
3317 out:
3318         if (left_path)
3319                 ocfs2_free_path(left_path);
3320         return ret;
3321 }
3322
3323 static int ocfs2_try_to_merge_extent(struct inode *inode,
3324                                      handle_t *handle,
3325                                      struct ocfs2_path *path,
3326                                      int split_index,
3327                                      struct ocfs2_extent_rec *split_rec,
3328                                      struct ocfs2_cached_dealloc_ctxt *dealloc,
3329                                      struct ocfs2_merge_ctxt *ctxt,
3330                                      struct ocfs2_extent_tree *et)
3331
3332 {
3333         int ret = 0;
3334         struct ocfs2_extent_list *el = path_leaf_el(path);
3335         struct ocfs2_extent_rec *rec = &el->l_recs[split_index];
3336
3337         BUG_ON(ctxt->c_contig_type == CONTIG_NONE);
3338
3339         if (ctxt->c_split_covers_rec && ctxt->c_has_empty_extent) {
3340                 /*
3341                  * The merge code will need to create an empty
3342                  * extent to take the place of the newly
3343                  * emptied slot. Remove any pre-existing empty
3344                  * extents - having more than one in a leaf is
3345                  * illegal.
3346                  */
3347                 ret = ocfs2_rotate_tree_left(inode, handle, path,
3348                                              dealloc, et);
3349                 if (ret) {
3350                         mlog_errno(ret);
3351                         goto out;
3352                 }
3353                 split_index--;
3354                 rec = &el->l_recs[split_index];
3355         }
3356
3357         if (ctxt->c_contig_type == CONTIG_LEFTRIGHT) {
3358                 /*
3359                  * Left-right contig implies this.
3360                  */
3361                 BUG_ON(!ctxt->c_split_covers_rec);
3362
3363                 /*
3364                  * Since the leftright insert always covers the entire
3365                  * extent, this call will delete the insert record
3366                  * entirely, resulting in an empty extent record added to
3367                  * the extent block.
3368                  *
3369                  * Since the adding of an empty extent shifts
3370                  * everything back to the right, there's no need to
3371                  * update split_index here.
3372                  *
3373                  * When the split_index is zero, we need to merge it to the
3374                  * prevoius extent block. It is more efficient and easier
3375                  * if we do merge_right first and merge_left later.
3376                  */
3377                 ret = ocfs2_merge_rec_right(inode, path,
3378                                             handle, split_rec,
3379                                             split_index);
3380                 if (ret) {
3381                         mlog_errno(ret);
3382                         goto out;
3383                 }
3384
3385                 /*
3386                  * We can only get this from logic error above.
3387                  */
3388                 BUG_ON(!ocfs2_is_empty_extent(&el->l_recs[0]));
3389
3390                 /* The merge left us with an empty extent, remove it. */
3391                 ret = ocfs2_rotate_tree_left(inode, handle, path,
3392                                              dealloc, et);
3393                 if (ret) {
3394                         mlog_errno(ret);
3395                         goto out;
3396                 }
3397
3398                 rec = &el->l_recs[split_index];
3399
3400                 /*
3401                  * Note that we don't pass split_rec here on purpose -
3402                  * we've merged it into the rec already.
3403                  */
3404                 ret = ocfs2_merge_rec_left(inode, path,
3405                                            handle, rec,
3406                                            dealloc, et,
3407                                            split_index);
3408
3409                 if (ret) {
3410                         mlog_errno(ret);
3411                         goto out;
3412                 }
3413
3414                 ret = ocfs2_rotate_tree_left(inode, handle, path,
3415                                              dealloc, et);
3416                 /*
3417                  * Error from this last rotate is not critical, so
3418                  * print but don't bubble it up.
3419                  */
3420                 if (ret)
3421                         mlog_errno(ret);
3422                 ret = 0;
3423         } else {
3424                 /*
3425                  * Merge a record to the left or right.
3426                  *
3427                  * 'contig_type' is relative to the existing record,
3428                  * so for example, if we're "right contig", it's to
3429                  * the record on the left (hence the left merge).
3430                  */
3431                 if (ctxt->c_contig_type == CONTIG_RIGHT) {
3432                         ret = ocfs2_merge_rec_left(inode,
3433                                                    path,
3434                                                    handle, split_rec,
3435                                                    dealloc, et,
3436                                                    split_index);
3437                         if (ret) {
3438                                 mlog_errno(ret);
3439                                 goto out;
3440                         }
3441                 } else {
3442                         ret = ocfs2_merge_rec_right(inode,
3443                                                     path,
3444                                                     handle, split_rec,
3445                                                     split_index);
3446                         if (ret) {
3447                                 mlog_errno(ret);
3448                                 goto out;
3449                         }
3450                 }
3451
3452                 if (ctxt->c_split_covers_rec) {
3453                         /*
3454                          * The merge may have left an empty extent in
3455                          * our leaf. Try to rotate it away.
3456                          */
3457                         ret = ocfs2_rotate_tree_left(inode, handle, path,
3458                                                      dealloc, et);
3459                         if (ret)
3460                                 mlog_errno(ret);
3461                         ret = 0;
3462                 }
3463         }
3464
3465 out:
3466         return ret;
3467 }
3468
3469 static void ocfs2_subtract_from_rec(struct super_block *sb,
3470                                     enum ocfs2_split_type split,
3471                                     struct ocfs2_extent_rec *rec,
3472                                     struct ocfs2_extent_rec *split_rec)
3473 {
3474         u64 len_blocks;
3475
3476         len_blocks = ocfs2_clusters_to_blocks(sb,
3477                                 le16_to_cpu(split_rec->e_leaf_clusters));
3478
3479         if (split == SPLIT_LEFT) {
3480                 /*
3481                  * Region is on the left edge of the existing
3482                  * record.
3483                  */
3484                 le32_add_cpu(&rec->e_cpos,
3485                              le16_to_cpu(split_rec->e_leaf_clusters));
3486                 le64_add_cpu(&rec->e_blkno, len_blocks);
3487                 le16_add_cpu(&rec->e_leaf_clusters,
3488                              -le16_to_cpu(split_rec->e_leaf_clusters));
3489         } else {
3490                 /*
3491                  * Region is on the right edge of the existing
3492                  * record.
3493                  */
3494                 le16_add_cpu(&rec->e_leaf_clusters,
3495                              -le16_to_cpu(split_rec->e_leaf_clusters));
3496         }
3497 }
3498
3499 /*
3500  * Do the final bits of extent record insertion at the target leaf
3501  * list. If this leaf is part of an allocation tree, it is assumed
3502  * that the tree above has been prepared.
3503  */
3504 static void ocfs2_insert_at_leaf(struct ocfs2_extent_rec *insert_rec,
3505                                  struct ocfs2_extent_list *el,
3506                                  struct ocfs2_insert_type *insert,
3507                                  struct inode *inode)
3508 {
3509         int i = insert->ins_contig_index;
3510         unsigned int range;
3511         struct ocfs2_extent_rec *rec;
3512
3513         BUG_ON(le16_to_cpu(el->l_tree_depth) != 0);
3514
3515         if (insert->ins_split != SPLIT_NONE) {
3516                 i = ocfs2_search_extent_list(el, le32_to_cpu(insert_rec->e_cpos));
3517                 BUG_ON(i == -1);
3518                 rec = &el->l_recs[i];
3519                 ocfs2_subtract_from_rec(inode->i_sb, insert->ins_split, rec,
3520                                         insert_rec);
3521                 goto rotate;
3522         }
3523
3524         /*
3525          * Contiguous insert - either left or right.
3526          */
3527         if (insert->ins_contig != CONTIG_NONE) {
3528                 rec = &el->l_recs[i];
3529                 if (insert->ins_contig == CONTIG_LEFT) {
3530                         rec->e_blkno = insert_rec->e_blkno;
3531                         rec->e_cpos = insert_rec->e_cpos;
3532                 }
3533                 le16_add_cpu(&rec->e_leaf_clusters,
3534                              le16_to_cpu(insert_rec->e_leaf_clusters));
3535                 return;
3536         }
3537
3538         /*
3539          * Handle insert into an empty leaf.
3540          */
3541         if (le16_to_cpu(el->l_next_free_rec) == 0 ||
3542             ((le16_to_cpu(el->l_next_free_rec) == 1) &&
3543              ocfs2_is_empty_extent(&el->l_recs[0]))) {
3544                 el->l_recs[0] = *insert_rec;
3545                 el->l_next_free_rec = cpu_to_le16(1);
3546                 return;
3547         }
3548
3549         /*
3550          * Appending insert.
3551          */
3552         if (insert->ins_appending == APPEND_TAIL) {
3553                 i = le16_to_cpu(el->l_next_free_rec) - 1;
3554                 rec = &el->l_recs[i];
3555                 range = le32_to_cpu(rec->e_cpos)
3556                         + le16_to_cpu(rec->e_leaf_clusters);
3557                 BUG_ON(le32_to_cpu(insert_rec->e_cpos) < range);
3558
3559                 mlog_bug_on_msg(le16_to_cpu(el->l_next_free_rec) >=
3560                                 le16_to_cpu(el->l_count),
3561                                 "inode %lu, depth %u, count %u, next free %u, "
3562                                 "rec.cpos %u, rec.clusters %u, "
3563                                 "insert.cpos %u, insert.clusters %u\n",
3564                                 inode->i_ino,
3565                                 le16_to_cpu(el->l_tree_depth),
3566                                 le16_to_cpu(el->l_count),
3567                                 le16_to_cpu(el->l_next_free_rec),
3568                                 le32_to_cpu(el->l_recs[i].e_cpos),
3569                                 le16_to_cpu(el->l_recs[i].e_leaf_clusters),
3570                                 le32_to_cpu(insert_rec->e_cpos),
3571                                 le16_to_cpu(insert_rec->e_leaf_clusters));
3572                 i++;
3573                 el->l_recs[i] = *insert_rec;
3574                 le16_add_cpu(&el->l_next_free_rec, 1);
3575                 return;
3576         }
3577
3578 rotate:
3579         /*
3580          * Ok, we have to rotate.
3581          *
3582          * At this point, it is safe to assume that inserting into an
3583          * empty leaf and appending to a leaf have both been handled
3584          * above.
3585          *
3586          * This leaf needs to have space, either by the empty 1st
3587          * extent record, or by virtue of an l_next_rec < l_count.
3588          */
3589         ocfs2_rotate_leaf(el, insert_rec);
3590 }
3591
3592 static void ocfs2_adjust_rightmost_records(struct inode *inode,
3593                                            handle_t *handle,
3594                                            struct ocfs2_path *path,
3595                                            struct ocfs2_extent_rec *insert_rec)
3596 {
3597         int ret, i, next_free;
3598         struct buffer_head *bh;
3599         struct ocfs2_extent_list *el;
3600         struct ocfs2_extent_rec *rec;
3601
3602         /*
3603          * Update everything except the leaf block.
3604          */
3605         for (i = 0; i < path->p_tree_depth; i++) {
3606                 bh = path->p_node[i].bh;
3607                 el = path->p_node[i].el;
3608
3609                 next_free = le16_to_cpu(el->l_next_free_rec);
3610                 if (next_free == 0) {
3611                         ocfs2_error(inode->i_sb,
3612                                     "Dinode %llu has a bad extent list",
3613                                     (unsigned long long)OCFS2_I(inode)->ip_blkno);
3614                         ret = -EIO;
3615                         return;
3616                 }
3617
3618                 rec = &el->l_recs[next_free - 1];
3619
3620                 rec->e_int_clusters = insert_rec->e_cpos;
3621                 le32_add_cpu(&rec->e_int_clusters,
3622                              le16_to_cpu(insert_rec->e_leaf_clusters));
3623                 le32_add_cpu(&rec->e_int_clusters,
3624                              -le32_to_cpu(rec->e_cpos));
3625
3626                 ret = ocfs2_journal_dirty(handle, bh);
3627                 if (ret)
3628                         mlog_errno(ret);
3629
3630         }
3631 }
3632
3633 static int ocfs2_append_rec_to_path(struct inode *inode, handle_t *handle,
3634                                     struct ocfs2_extent_rec *insert_rec,
3635                                     struct ocfs2_path *right_path,
3636                                     struct ocfs2_path **ret_left_path)
3637 {
3638         int ret, next_free;
3639         struct ocfs2_extent_list *el;
3640         struct ocfs2_path *left_path = NULL;
3641
3642         *ret_left_path = NULL;
3643
3644         /*
3645          * This shouldn't happen for non-trees. The extent rec cluster
3646          * count manipulation below only works for interior nodes.
3647          */
3648         BUG_ON(right_path->p_tree_depth == 0);
3649
3650         /*
3651          * If our appending insert is at the leftmost edge of a leaf,
3652          * then we might need to update the rightmost records of the
3653          * neighboring path.
3654          */
3655         el = path_leaf_el(right_path);
3656         next_free = le16_to_cpu(el->l_next_free_rec);
3657         if (next_free == 0 ||
3658             (next_free == 1 && ocfs2_is_empty_extent(&el->l_recs[0]))) {
3659                 u32 left_cpos;
3660
3661                 ret = ocfs2_find_cpos_for_left_leaf(inode->i_sb, right_path,
3662                                                     &left_cpos);
3663                 if (ret) {
3664                         mlog_errno(ret);
3665                         goto out;
3666                 }
3667
3668                 mlog(0, "Append may need a left path update. cpos: %u, "
3669                      "left_cpos: %u\n", le32_to_cpu(insert_rec->e_cpos),
3670                      left_cpos);
3671
3672                 /*
3673                  * No need to worry if the append is already in the
3674                  * leftmost leaf.
3675                  */
3676                 if (left_cpos) {
3677                         left_path = ocfs2_new_path(path_root_bh(right_path),
3678                                                    path_root_el(right_path));
3679                         if (!left_path) {
3680                                 ret = -ENOMEM;
3681                                 mlog_errno(ret);
3682                                 goto out;
3683                         }
3684
3685                         ret = ocfs2_find_path(inode, left_path, left_cpos);
3686                         if (ret) {
3687                                 mlog_errno(ret);
3688                                 goto out;
3689                         }
3690
3691                         /*
3692                          * ocfs2_insert_path() will pass the left_path to the
3693                          * journal for us.
3694                          */
3695                 }
3696         }
3697
3698         ret = ocfs2_journal_access_path(inode, handle, right_path);
3699         if (ret) {
3700                 mlog_errno(ret);
3701                 goto out;
3702         }
3703
3704         ocfs2_adjust_rightmost_records(inode, handle, right_path, insert_rec);
3705
3706         *ret_left_path = left_path;
3707         ret = 0;
3708 out:
3709         if (ret != 0)
3710                 ocfs2_free_path(left_path);
3711
3712         return ret;
3713 }
3714
3715 static void ocfs2_split_record(struct inode *inode,
3716                                struct ocfs2_path *left_path,
3717                                struct ocfs2_path *right_path,
3718                                struct ocfs2_extent_rec *split_rec,
3719                                enum ocfs2_split_type split)
3720 {
3721         int index;
3722         u32 cpos = le32_to_cpu(split_rec->e_cpos);
3723         struct ocfs2_extent_list *left_el = NULL, *right_el, *insert_el, *el;
3724         struct ocfs2_extent_rec *rec, *tmprec;
3725
3726         right_el = path_leaf_el(right_path);;
3727         if (left_path)
3728                 left_el = path_leaf_el(left_path);
3729
3730         el = right_el;
3731         insert_el = right_el;
3732         index = ocfs2_search_extent_list(el, cpos);
3733         if (index != -1) {
3734                 if (index == 0 && left_path) {
3735                         BUG_ON(ocfs2_is_empty_extent(&el->l_recs[0]));
3736
3737                         /*
3738                          * This typically means that the record
3739                          * started in the left path but moved to the
3740                          * right as a result of rotation. We either
3741                          * move the existing record to the left, or we
3742                          * do the later insert there.
3743                          *
3744                          * In this case, the left path should always
3745                          * exist as the rotate code will have passed
3746                          * it back for a post-insert update.
3747                          */
3748
3749                         if (split == SPLIT_LEFT) {
3750                                 /*
3751                                  * It's a left split. Since we know
3752                                  * that the rotate code gave us an
3753                                  * empty extent in the left path, we
3754                                  * can just do the insert there.
3755                                  */
3756                                 insert_el = left_el;
3757                         } else {
3758                                 /*
3759                                  * Right split - we have to move the
3760                                  * existing record over to the left
3761                                  * leaf. The insert will be into the
3762                                  * newly created empty extent in the
3763                                  * right leaf.
3764                                  */
3765                                 tmprec = &right_el->l_recs[index];
3766                                 ocfs2_rotate_leaf(left_el, tmprec);
3767                                 el = left_el;
3768
3769                                 memset(tmprec, 0, sizeof(*tmprec));
3770                                 index = ocfs2_search_extent_list(left_el, cpos);
3771                                 BUG_ON(index == -1);
3772                         }
3773                 }
3774         } else {
3775                 BUG_ON(!left_path);
3776                 BUG_ON(!ocfs2_is_empty_extent(&left_el->l_recs[0]));
3777                 /*
3778                  * Left path is easy - we can just allow the insert to
3779                  * happen.
3780                  */
3781                 el = left_el;
3782                 insert_el = left_el;
3783                 index = ocfs2_search_extent_list(el, cpos);
3784                 BUG_ON(index == -1);
3785         }
3786
3787         rec = &el->l_recs[index];
3788         ocfs2_subtract_from_rec(inode->i_sb, split, rec, split_rec);
3789         ocfs2_rotate_leaf(insert_el, split_rec);
3790 }
3791
3792 /*
3793  * This function only does inserts on an allocation b-tree. For tree
3794  * depth = 0, ocfs2_insert_at_leaf() is called directly.
3795  *
3796  * right_path is the path we want to do the actual insert
3797  * in. left_path should only be passed in if we need to update that
3798  * portion of the tree after an edge insert.
3799  */
3800 static int ocfs2_insert_path(struct inode *inode,
3801                              handle_t *handle,
3802                              struct ocfs2_path *left_path,
3803                              struct ocfs2_path *right_path,
3804                              struct ocfs2_extent_rec *insert_rec,
3805                              struct ocfs2_insert_type *insert)
3806 {
3807         int ret, subtree_index;
3808         struct buffer_head *leaf_bh = path_leaf_bh(right_path);
3809
3810         if (left_path) {
3811                 int credits = handle->h_buffer_credits;
3812
3813                 /*
3814                  * There's a chance that left_path got passed back to
3815                  * us without being accounted for in the
3816                  * journal. Extend our transaction here to be sure we
3817                  * can change those blocks.
3818                  */
3819                 credits += left_path->p_tree_depth;
3820
3821                 ret = ocfs2_extend_trans(handle, credits);
3822                 if (ret < 0) {
3823                         mlog_errno(ret);
3824                         goto out;
3825                 }
3826
3827                 ret = ocfs2_journal_access_path(inode, handle, left_path);
3828                 if (ret < 0) {
3829                         mlog_errno(ret);
3830                         goto out;
3831                 }
3832         }
3833
3834         /*
3835          * Pass both paths to the journal. The majority of inserts
3836          * will be touching all components anyway.
3837          */
3838         ret = ocfs2_journal_access_path(inode, handle, right_path);
3839         if (ret < 0) {
3840                 mlog_errno(ret);
3841                 goto out;
3842         }
3843
3844         if (insert->ins_split != SPLIT_NONE) {
3845                 /*
3846                  * We could call ocfs2_insert_at_leaf() for some types
3847                  * of splits, but it's easier to just let one separate
3848                  * function sort it all out.
3849                  */
3850                 ocfs2_split_record(inode, left_path, right_path,
3851                                    insert_rec, insert->ins_split);
3852
3853                 /*
3854                  * Split might have modified either leaf and we don't
3855                  * have a guarantee that the later edge insert will
3856                  * dirty this for us.
3857                  */
3858                 if (left_path)
3859                         ret = ocfs2_journal_dirty(handle,
3860                                                   path_leaf_bh(left_path));
3861                         if (ret)
3862                                 mlog_errno(ret);
3863         } else
3864                 ocfs2_insert_at_leaf(insert_rec, path_leaf_el(right_path),
3865                                      insert, inode);
3866
3867         ret = ocfs2_journal_dirty(handle, leaf_bh);
3868         if (ret)
3869                 mlog_errno(ret);
3870
3871         if (left_path) {
3872                 /*
3873                  * The rotate code has indicated that we need to fix
3874                  * up portions of the tree after the insert.
3875                  *
3876                  * XXX: Should we extend the transaction here?
3877                  */
3878                 subtree_index = ocfs2_find_subtree_root(inode, left_path,
3879                                                         right_path);
3880                 ocfs2_complete_edge_insert(inode, handle, left_path,
3881                                            right_path, subtree_index);
3882         }
3883
3884         ret = 0;
3885 out:
3886         return ret;
3887 }
3888
3889 static int ocfs2_do_insert_extent(struct inode *inode,
3890                                   handle_t *handle,
3891                                   struct ocfs2_extent_tree *et,
3892                                   struct ocfs2_extent_rec *insert_rec,
3893                                   struct ocfs2_insert_type *type)
3894 {
3895         int ret, rotate = 0;
3896         u32 cpos;
3897         struct ocfs2_path *right_path = NULL;
3898         struct ocfs2_path *left_path = NULL;
3899         struct ocfs2_extent_list *el;
3900
3901         el = et->root_el;
3902
3903         ret = ocfs2_journal_access(handle, inode, et->root_bh,
3904                                    OCFS2_JOURNAL_ACCESS_WRITE);
3905         if (ret) {
3906                 mlog_errno(ret);
3907                 goto out;
3908         }
3909
3910         if (le16_to_cpu(el->l_tree_depth) == 0) {
3911                 ocfs2_insert_at_leaf(insert_rec, el, type, inode);
3912                 goto out_update_clusters;
3913         }
3914
3915         right_path = ocfs2_new_path(et->root_bh, et->root_el);
3916         if (!right_path) {
3917                 ret = -ENOMEM;
3918                 mlog_errno(ret);
3919                 goto out;
3920         }
3921
3922         /*
3923          * Determine the path to start with. Rotations need the
3924          * rightmost path, everything else can go directly to the
3925          * target leaf.
3926          */
3927         cpos = le32_to_cpu(insert_rec->e_cpos);
3928         if (type->ins_appending == APPEND_NONE &&
3929             type->ins_contig == CONTIG_NONE) {
3930                 rotate = 1;
3931                 cpos = UINT_MAX;
3932         }
3933
3934         ret = ocfs2_find_path(inode, right_path, cpos);
3935         if (ret) {
3936                 mlog_errno(ret);
3937                 goto out;
3938         }
3939
3940         /*
3941          * Rotations and appends need special treatment - they modify
3942          * parts of the tree's above them.
3943          *
3944          * Both might pass back a path immediate to the left of the
3945          * one being inserted to. This will be cause
3946          * ocfs2_insert_path() to modify the rightmost records of
3947          * left_path to account for an edge insert.
3948          *
3949          * XXX: When modifying this code, keep in mind that an insert
3950          * can wind up skipping both of these two special cases...
3951          */
3952         if (rotate) {
3953                 ret = ocfs2_rotate_tree_right(inode, handle, type->ins_split,
3954                                               le32_to_cpu(insert_rec->e_cpos),
3955                                               right_path, &left_path);
3956                 if (ret) {
3957                         mlog_errno(ret);
3958                         goto out;
3959                 }
3960
3961                 /*
3962                  * ocfs2_rotate_tree_right() might have extended the
3963                  * transaction without re-journaling our tree root.
3964                  */
3965                 ret = ocfs2_journal_access(handle, inode, et->root_bh,
3966                                            OCFS2_JOURNAL_ACCESS_WRITE);
3967                 if (ret) {
3968                         mlog_errno(ret);
3969                         goto out;
3970                 }
3971         } else if (type->ins_appending == APPEND_TAIL
3972                    && type->ins_contig != CONTIG_LEFT) {
3973                 ret = ocfs2_append_rec_to_path(inode, handle, insert_rec,
3974                                                right_path, &left_path);
3975                 if (ret) {
3976                         mlog_errno(ret);
3977                         goto out;
3978                 }
3979         }
3980
3981         ret = ocfs2_insert_path(inode, handle, left_path, right_path,
3982                                 insert_rec, type);
3983         if (ret) {
3984                 mlog_errno(ret);
3985                 goto out;
3986         }
3987
3988 out_update_clusters:
3989         if (type->ins_split == SPLIT_NONE)
3990                 ocfs2_et_update_clusters(inode, et,
3991                                          le16_to_cpu(insert_rec->e_leaf_clusters));
3992
3993         ret = ocfs2_journal_dirty(handle, et->root_bh);
3994         if (ret)
3995                 mlog_errno(ret);
3996
3997 out:
3998         ocfs2_free_path(left_path);
3999         ocfs2_free_path(right_path);
4000
4001         return ret;
4002 }
4003
4004 static enum ocfs2_contig_type
4005 ocfs2_figure_merge_contig_type(struct inode *inode, struct ocfs2_path *path,
4006                                struct ocfs2_extent_list *el, int index,
4007                                struct ocfs2_extent_rec *split_rec)
4008 {
4009         int status;
4010         enum ocfs2_contig_type ret = CONTIG_NONE;
4011         u32 left_cpos, right_cpos;
4012         struct ocfs2_extent_rec *rec = NULL;
4013         struct ocfs2_extent_list *new_el;
4014         struct ocfs2_path *left_path = NULL, *right_path = NULL;
4015         struct buffer_head *bh;
4016         struct ocfs2_extent_block *eb;
4017
4018         if (index > 0) {
4019                 rec = &el->l_recs[index - 1];
4020         } else if (path->p_tree_depth > 0) {
4021                 status = ocfs2_find_cpos_for_left_leaf(inode->i_sb,
4022                                                        path, &left_cpos);
4023                 if (status)
4024                         goto out;
4025
4026                 if (left_cpos != 0) {
4027                         left_path = ocfs2_new_path(path_root_bh(path),
4028                                                    path_root_el(path));
4029                         if (!left_path)
4030                                 goto out;
4031
4032                         status = ocfs2_find_path(inode, left_path, left_cpos);
4033                         if (status)
4034                                 goto out;
4035
4036                         new_el = path_leaf_el(left_path);
4037
4038                         if (le16_to_cpu(new_el->l_next_free_rec) !=
4039                             le16_to_cpu(new_el->l_count)) {
4040                                 bh = path_leaf_bh(left_path);
4041                                 eb = (struct ocfs2_extent_block *)bh->b_data;
4042                                 OCFS2_RO_ON_INVALID_EXTENT_BLOCK(inode->i_sb,
4043                                                                  eb);
4044                                 goto out;
4045                         }
4046                         rec = &new_el->l_recs[
4047                                 le16_to_cpu(new_el->l_next_free_rec) - 1];
4048                 }
4049         }
4050
4051         /*
4052          * We're careful to check for an empty extent record here -
4053          * the merge code will know what to do if it sees one.
4054          */
4055         if (rec) {
4056                 if (index == 1 && ocfs2_is_empty_extent(rec)) {
4057                         if (split_rec->e_cpos == el->l_recs[index].e_cpos)
4058                                 ret = CONTIG_RIGHT;
4059                 } else {
4060                         ret = ocfs2_extent_contig(inode, rec, split_rec);
4061                 }
4062         }
4063
4064         rec = NULL;
4065         if (index < (le16_to_cpu(el->l_next_free_rec) - 1))
4066                 rec = &el->l_recs[index + 1];
4067         else if (le16_to_cpu(el->l_next_free_rec) == le16_to_cpu(el->l_count) &&
4068                  path->p_tree_depth > 0) {
4069                 status = ocfs2_find_cpos_for_right_leaf(inode->i_sb,
4070                                                         path, &right_cpos);
4071                 if (status)
4072                         goto out;
4073
4074                 if (right_cpos == 0)
4075                         goto out;
4076
4077                 right_path = ocfs2_new_path(path_root_bh(path),
4078                                             path_root_el(path));
4079                 if (!right_path)
4080                         goto out;
4081
4082                 status = ocfs2_find_path(inode, right_path, right_cpos);
4083                 if (status)
4084                         goto out;
4085
4086                 new_el = path_leaf_el(right_path);
4087                 rec = &new_el->l_recs[0];
4088                 if (ocfs2_is_empty_extent(rec)) {
4089                         if (le16_to_cpu(new_el->l_next_free_rec) <= 1) {
4090                                 bh = path_leaf_bh(right_path);
4091                                 eb = (struct ocfs2_extent_block *)bh->b_data;
4092                                 OCFS2_RO_ON_INVALID_EXTENT_BLOCK(inode->i_sb,
4093                                                                  eb);
4094                                 goto out;
4095                         }
4096                         rec = &new_el->l_recs[1];
4097                 }
4098         }
4099
4100         if (rec) {
4101                 enum ocfs2_contig_type contig_type;
4102
4103                 contig_type = ocfs2_extent_contig(inode, rec, split_rec);
4104
4105                 if (contig_type == CONTIG_LEFT && ret == CONTIG_RIGHT)
4106                         ret = CONTIG_LEFTRIGHT;
4107                 else if (ret == CONTIG_NONE)
4108                         ret = contig_type;
4109         }
4110
4111 out:
4112         if (left_path)
4113                 ocfs2_free_path(left_path);
4114         if (right_path)
4115                 ocfs2_free_path(right_path);
4116
4117         return ret;
4118 }
4119
4120 static void ocfs2_figure_contig_type(struct inode *inode,
4121                                      struct ocfs2_insert_type *insert,
4122                                      struct ocfs2_extent_list *el,
4123                                      struct ocfs2_extent_rec *insert_rec,
4124                                      struct ocfs2_extent_tree *et)
4125 {
4126         int i;
4127         enum ocfs2_contig_type contig_type = CONTIG_NONE;
4128
4129         BUG_ON(le16_to_cpu(el->l_tree_depth) != 0);
4130
4131         for(i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
4132                 contig_type = ocfs2_extent_contig(inode, &el->l_recs[i],
4133                                                   insert_rec);
4134                 if (contig_type != CONTIG_NONE) {
4135                         insert->ins_contig_index = i;
4136                         break;
4137                 }
4138         }
4139         insert->ins_contig = contig_type;
4140
4141         if (insert->ins_contig != CONTIG_NONE) {
4142                 struct ocfs2_extent_rec *rec =
4143                                 &el->l_recs[insert->ins_contig_index];
4144                 unsigned int len = le16_to_cpu(rec->e_leaf_clusters) +
4145                                    le16_to_cpu(insert_rec->e_leaf_clusters);
4146
4147                 /*
4148                  * Caller might want us to limit the size of extents, don't
4149                  * calculate contiguousness if we might exceed that limit.
4150                  */
4151                 if (et->max_leaf_clusters && len > et->max_leaf_clusters)
4152                         insert->ins_contig = CONTIG_NONE;
4153         }
4154 }
4155
4156 /*
4157  * This should only be called against the righmost leaf extent list.
4158  *
4159  * ocfs2_figure_appending_type() will figure out whether we'll have to
4160  * insert at the tail of the rightmost leaf.
4161  *
4162  * This should also work against the root extent list for tree's with 0
4163  * depth. If we consider the root extent list to be the rightmost leaf node
4164  * then the logic here makes sense.
4165  */
4166 static void ocfs2_figure_appending_type(struct ocfs2_insert_type *insert,
4167                                         struct ocfs2_extent_list *el,
4168                                         struct ocfs2_extent_rec *insert_rec)
4169 {
4170         int i;
4171         u32 cpos = le32_to_cpu(insert_rec->e_cpos);
4172         struct ocfs2_extent_rec *rec;
4173
4174         insert->ins_appending = APPEND_NONE;
4175
4176         BUG_ON(le16_to_cpu(el->l_tree_depth) != 0);
4177
4178         if (!el->l_next_free_rec)
4179                 goto set_tail_append;
4180
4181         if (ocfs2_is_empty_extent(&el->l_recs[0])) {
4182                 /* Were all records empty? */
4183                 if (le16_to_cpu(el->l_next_free_rec) == 1)
4184                         goto set_tail_append;
4185         }
4186
4187         i = le16_to_cpu(el->l_next_free_rec) - 1;
4188         rec = &el->l_recs[i];
4189
4190         if (cpos >=
4191             (le32_to_cpu(rec->e_cpos) + le16_to_cpu(rec->e_leaf_clusters)))
4192                 goto set_tail_append;
4193
4194         return;
4195
4196 set_tail_append:
4197         insert->ins_appending = APPEND_TAIL;
4198 }
4199
4200 /*
4201  * Helper function called at the begining of an insert.
4202  *
4203  * This computes a few things that are commonly used in the process of
4204  * inserting into the btree:
4205  *   - Whether the new extent is contiguous with an existing one.
4206  *   - The current tree depth.
4207  *   - Whether the insert is an appending one.
4208  *   - The total # of free records in the tree.
4209  *
4210  * All of the information is stored on the ocfs2_insert_type
4211  * structure.
4212  */
4213 static int ocfs2_figure_insert_type(struct inode *inode,
4214                                     struct ocfs2_extent_tree *et,
4215                                     struct buffer_head **last_eb_bh,
4216                                     struct ocfs2_extent_rec *insert_rec,
4217                                     int *free_records,
4218                                     struct ocfs2_insert_type *insert)
4219 {
4220         int ret;
4221         struct ocfs2_extent_block *eb;
4222         struct ocfs2_extent_list *el;
4223         struct ocfs2_path *path = NULL;
4224         struct buffer_head *bh = NULL;
4225
4226         insert->ins_split = SPLIT_NONE;
4227
4228         el = et->root_el;
4229         insert->ins_tree_depth = le16_to_cpu(el->l_tree_depth);
4230
4231         if (el->l_tree_depth) {
4232                 /*
4233                  * If we have tree depth, we read in the
4234                  * rightmost extent block ahead of time as
4235                  * ocfs2_figure_insert_type() and ocfs2_add_branch()
4236                  * may want it later.
4237                  */
4238                 ret = ocfs2_read_block(OCFS2_SB(inode->i_sb),
4239                                        ocfs2_et_get_last_eb_blk(et), &bh,
4240                                        OCFS2_BH_CACHED, inode);
4241                 if (ret) {
4242                         mlog_exit(ret);
4243                         goto out;
4244                 }
4245                 eb = (struct ocfs2_extent_block *) bh->b_data;
4246                 el = &eb->h_list;
4247         }
4248
4249         /*
4250          * Unless we have a contiguous insert, we'll need to know if
4251          * there is room left in our allocation tree for another
4252          * extent record.
4253          *
4254          * XXX: This test is simplistic, we can search for empty
4255          * extent records too.
4256          */
4257         *free_records = le16_to_cpu(el->l_count) -
4258                 le16_to_cpu(el->l_next_free_rec);
4259
4260         if (!insert->ins_tree_depth) {
4261                 ocfs2_figure_contig_type(inode, insert, el, insert_rec, et);
4262                 ocfs2_figure_appending_type(insert, el, insert_rec);
4263                 return 0;
4264         }
4265
4266         path = ocfs2_new_path(et->root_bh, et->root_el);
4267         if (!path) {
4268                 ret = -ENOMEM;
4269                 mlog_errno(ret);
4270                 goto out;
4271         }
4272
4273         /*
4274          * In the case that we're inserting past what the tree
4275          * currently accounts for, ocfs2_find_path() will return for
4276          * us the rightmost tree path. This is accounted for below in
4277          * the appending code.
4278          */
4279         ret = ocfs2_find_path(inode, path, le32_to_cpu(insert_rec->e_cpos));
4280         if (ret) {
4281                 mlog_errno(ret);
4282                 goto out;
4283         }
4284
4285         el = path_leaf_el(path);
4286
4287         /*
4288          * Now that we have the path, there's two things we want to determine:
4289          * 1) Contiguousness (also set contig_index if this is so)
4290          *
4291          * 2) Are we doing an append? We can trivially break this up
4292          *     into two types of appends: simple record append, or a
4293          *     rotate inside the tail leaf.
4294          */
4295         ocfs2_figure_contig_type(inode, insert, el, insert_rec, et);
4296
4297         /*
4298          * The insert code isn't quite ready to deal with all cases of
4299          * left contiguousness. Specifically, if it's an insert into
4300          * the 1st record in a leaf, it will require the adjustment of
4301          * cluster count on the last record of the path directly to it's
4302          * left. For now, just catch that case and fool the layers
4303          * above us. This works just fine for tree_depth == 0, which
4304          * is why we allow that above.
4305          */
4306         if (insert->ins_contig == CONTIG_LEFT &&
4307             insert->ins_contig_index == 0)
4308                 insert->ins_contig = CONTIG_NONE;
4309
4310         /*
4311          * Ok, so we can simply compare against last_eb to figure out
4312          * whether the path doesn't exist. This will only happen in
4313          * the case that we're doing a tail append, so maybe we can
4314          * take advantage of that information somehow.
4315          */
4316         if (ocfs2_et_get_last_eb_blk(et) ==
4317             path_leaf_bh(path)->b_blocknr) {
4318                 /*
4319                  * Ok, ocfs2_find_path() returned us the rightmost
4320                  * tree path. This might be an appending insert. There are
4321                  * two cases:
4322                  *    1) We're doing a true append at the tail:
4323                  *      -This might even be off the end of the leaf
4324                  *    2) We're "appending" by rotating in the tail
4325                  */
4326                 ocfs2_figure_appending_type(insert, el, insert_rec);
4327         }
4328
4329 out:
4330         ocfs2_free_path(path);
4331
4332         if (ret == 0)
4333                 *last_eb_bh = bh;
4334         else
4335                 brelse(bh);
4336         return ret;
4337 }
4338
4339 /*
4340  * Insert an extent into an inode btree.
4341  *
4342  * The caller needs to update fe->i_clusters
4343  */
4344 static int ocfs2_insert_extent(struct ocfs2_super *osb,
4345                                handle_t *handle,
4346                                struct inode *inode,
4347                                struct buffer_head *root_bh,
4348                                u32 cpos,
4349                                u64 start_blk,
4350                                u32 new_clusters,
4351                                u8 flags,
4352                                struct ocfs2_alloc_context *meta_ac,
4353                                struct ocfs2_extent_tree *et)
4354 {
4355         int status;
4356         int uninitialized_var(free_records);
4357         struct buffer_head *last_eb_bh = NULL;
4358         struct ocfs2_insert_type insert = {0, };
4359         struct ocfs2_extent_rec rec;
4360
4361         BUG_ON(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL);
4362
4363         mlog(0, "add %u clusters at position %u to inode %llu\n",
4364              new_clusters, cpos, (unsigned long long)OCFS2_I(inode)->ip_blkno);
4365
4366         mlog_bug_on_msg(!ocfs2_sparse_alloc(osb) &&
4367                         (OCFS2_I(inode)->ip_clusters != cpos),
4368                         "Device %s, asking for sparse allocation: inode %llu, "
4369                         "cpos %u, clusters %u\n",
4370                         osb->dev_str,
4371                         (unsigned long long)OCFS2_I(inode)->ip_blkno, cpos,
4372                         OCFS2_I(inode)->ip_clusters);
4373
4374         memset(&rec, 0, sizeof(rec));
4375         rec.e_cpos = cpu_to_le32(cpos);
4376         rec.e_blkno = cpu_to_le64(start_blk);
4377         rec.e_leaf_clusters = cpu_to_le16(new_clusters);
4378         rec.e_flags = flags;
4379
4380         status = ocfs2_figure_insert_type(inode, et, &last_eb_bh, &rec,
4381                                           &free_records, &insert);
4382         if (status < 0) {
4383                 mlog_errno(status);
4384                 goto bail;
4385         }
4386
4387         mlog(0, "Insert.appending: %u, Insert.Contig: %u, "
4388              "Insert.contig_index: %d, Insert.free_records: %d, "
4389              "Insert.tree_depth: %d\n",
4390              insert.ins_appending, insert.ins_contig, insert.ins_contig_index,
4391              free_records, insert.ins_tree_depth);
4392
4393         if (insert.ins_contig == CONTIG_NONE && free_records == 0) {
4394                 status = ocfs2_grow_tree(inode, handle, et,
4395                                          &insert.ins_tree_depth, &last_eb_bh,
4396                                          meta_ac);
4397                 if (status) {
4398                         mlog_errno(status);
4399                         goto bail;
4400                 }
4401         }
4402
4403         /* Finally, we can add clusters. This might rotate the tree for us. */
4404         status = ocfs2_do_insert_extent(inode, handle, et, &rec, &insert);
4405         if (status < 0)
4406                 mlog_errno(status);
4407         else if (et->type == OCFS2_DINODE_EXTENT)
4408                 ocfs2_extent_map_insert_rec(inode, &rec);
4409
4410 bail:
4411         if (last_eb_bh)
4412                 brelse(last_eb_bh);
4413
4414         mlog_exit(status);
4415         return status;
4416 }
4417
4418 int ocfs2_dinode_insert_extent(struct ocfs2_super *osb,
4419                                handle_t *handle,
4420                                struct inode *inode,
4421                                struct buffer_head *root_bh,
4422                                u32 cpos,
4423                                u64 start_blk,
4424                                u32 new_clusters,
4425                                u8 flags,
4426                                struct ocfs2_alloc_context *meta_ac)
4427 {
4428         int status;
4429         struct ocfs2_extent_tree *et = NULL;
4430
4431         et = ocfs2_new_extent_tree(inode, root_bh, OCFS2_DINODE_EXTENT, NULL);
4432         if (!et) {
4433                 status = -ENOMEM;
4434                 mlog_errno(status);
4435                 goto bail;
4436         }
4437
4438         status = ocfs2_insert_extent(osb, handle, inode, root_bh,
4439                                      cpos, start_blk, new_clusters,
4440                                      flags, meta_ac, et);
4441
4442         if (et)
4443                 ocfs2_free_extent_tree(et);
4444 bail:
4445         return status;
4446 }
4447
4448 int ocfs2_xattr_value_insert_extent(struct ocfs2_super *osb,
4449                                     handle_t *handle,
4450                                     struct inode *inode,
4451                                     struct buffer_head *root_bh,
4452                                     u32 cpos,
4453                                     u64 start_blk,
4454                                     u32 new_clusters,
4455                                     u8 flags,
4456                                     struct ocfs2_alloc_context *meta_ac,
4457                                     void *private)
4458 {
4459         int status;
4460         struct ocfs2_extent_tree *et = NULL;
4461
4462         et = ocfs2_new_extent_tree(inode, root_bh,
4463                                    OCFS2_XATTR_VALUE_EXTENT, private);
4464         if (!et) {
4465                 status = -ENOMEM;
4466                 mlog_errno(status);
4467                 goto bail;
4468         }
4469
4470         status = ocfs2_insert_extent(osb, handle, inode, root_bh,
4471                                      cpos, start_blk, new_clusters,
4472                                      flags, meta_ac, et);
4473
4474         if (et)
4475                 ocfs2_free_extent_tree(et);
4476 bail:
4477         return status;
4478 }
4479
4480 int ocfs2_xattr_tree_insert_extent(struct ocfs2_super *osb,
4481                                    handle_t *handle,
4482                                    struct inode *inode,
4483                                    struct buffer_head *root_bh,
4484                                    u32 cpos,
4485                                    u64 start_blk,
4486                                    u32 new_clusters,
4487                                    u8 flags,
4488                                    struct ocfs2_alloc_context *meta_ac)
4489 {
4490         int status;
4491         struct ocfs2_extent_tree *et = NULL;
4492
4493         et = ocfs2_new_extent_tree(inode, root_bh, OCFS2_XATTR_TREE_EXTENT,
4494                                    NULL);
4495         if (!et) {
4496                 status = -ENOMEM;
4497                 mlog_errno(status);
4498                 goto bail;
4499         }
4500
4501         status = ocfs2_insert_extent(osb, handle, inode, root_bh,
4502                                      cpos, start_blk, new_clusters,
4503                                      flags, meta_ac, et);
4504
4505         if (et)
4506                 ocfs2_free_extent_tree(et);
4507 bail:
4508         return status;
4509 }
4510
4511 /*
4512  * Allcate and add clusters into the extent b-tree.
4513  * The new clusters(clusters_to_add) will be inserted at logical_offset.
4514  * The extent b-tree's root is root_el and it should be in root_bh, and
4515  * it is not limited to the file storage. Any extent tree can use this
4516  * function if it implements the proper ocfs2_extent_tree.
4517  */
4518 int ocfs2_add_clusters_in_btree(struct ocfs2_super *osb,
4519                                 struct inode *inode,
4520                                 u32 *logical_offset,
4521                                 u32 clusters_to_add,
4522                                 int mark_unwritten,
4523                                 struct buffer_head *root_bh,
4524                                 struct ocfs2_extent_list *root_el,
4525                                 handle_t *handle,
4526                                 struct ocfs2_alloc_context *data_ac,
4527                                 struct ocfs2_alloc_context *meta_ac,
4528                                 enum ocfs2_alloc_restarted *reason_ret,
4529                                 enum ocfs2_extent_tree_type type,
4530                                 void *private)
4531 {
4532         int status = 0;
4533         int free_extents;
4534         enum ocfs2_alloc_restarted reason = RESTART_NONE;
4535         u32 bit_off, num_bits;
4536         u64 block;
4537         u8 flags = 0;
4538
4539         BUG_ON(!clusters_to_add);
4540
4541         if (mark_unwritten)
4542                 flags = OCFS2_EXT_UNWRITTEN;
4543
4544         free_extents = ocfs2_num_free_extents(osb, inode, root_bh, type,
4545                                               private);
4546         if (free_extents < 0) {
4547                 status = free_extents;
4548                 mlog_errno(status);
4549                 goto leave;
4550         }
4551
4552         /* there are two cases which could cause us to EAGAIN in the
4553          * we-need-more-metadata case:
4554          * 1) we haven't reserved *any*
4555          * 2) we are so fragmented, we've needed to add metadata too
4556          *    many times. */
4557         if (!free_extents && !meta_ac) {
4558                 mlog(0, "we haven't reserved any metadata!\n");
4559                 status = -EAGAIN;
4560                 reason = RESTART_META;
4561                 goto leave;
4562         } else if ((!free_extents)
4563                    && (ocfs2_alloc_context_bits_left(meta_ac)
4564                        < ocfs2_extend_meta_needed(root_el))) {
4565                 mlog(0, "filesystem is really fragmented...\n");
4566                 status = -EAGAIN;
4567                 reason = RESTART_META;
4568                 goto leave;
4569         }
4570
4571         status = __ocfs2_claim_clusters(osb, handle, data_ac, 1,
4572                                         clusters_to_add, &bit_off, &num_bits);
4573         if (status < 0) {
4574                 if (status != -ENOSPC)
4575                         mlog_errno(status);
4576                 goto leave;
4577         }
4578
4579         BUG_ON(num_bits > clusters_to_add);
4580
4581         /* reserve our write early -- insert_extent may update the inode */
4582         status = ocfs2_journal_access(handle, inode, root_bh,
4583                                       OCFS2_JOURNAL_ACCESS_WRITE);
4584         if (status < 0) {
4585                 mlog_errno(status);
4586                 goto leave;
4587         }
4588
4589         block = ocfs2_clusters_to_blocks(osb->sb, bit_off);
4590         mlog(0, "Allocating %u clusters at block %u for inode %llu\n",
4591              num_bits, bit_off, (unsigned long long)OCFS2_I(inode)->ip_blkno);
4592         if (type == OCFS2_DINODE_EXTENT)
4593                 status = ocfs2_dinode_insert_extent(osb, handle, inode, root_bh,
4594                                                     *logical_offset, block,
4595                                                     num_bits, flags, meta_ac);
4596         else if (type == OCFS2_XATTR_TREE_EXTENT)
4597                 status = ocfs2_xattr_tree_insert_extent(osb, handle,
4598                                                         inode, root_bh,
4599                                                         *logical_offset,
4600                                                         block, num_bits, flags,
4601                                                         meta_ac);
4602         else
4603                 status = ocfs2_xattr_value_insert_extent(osb, handle,
4604                                                          inode, root_bh,
4605                                                          *logical_offset,
4606                                                          block, num_bits, flags,
4607                                                          meta_ac, private);
4608         if (status < 0) {
4609                 mlog_errno(status);
4610                 goto leave;
4611         }
4612
4613         status = ocfs2_journal_dirty(handle, root_bh);
4614         if (status < 0) {
4615                 mlog_errno(status);
4616                 goto leave;
4617         }
4618
4619         clusters_to_add -= num_bits;
4620         *logical_offset += num_bits;
4621
4622         if (clusters_to_add) {
4623                 mlog(0, "need to alloc once more, wanted = %u\n",
4624                      clusters_to_add);
4625                 status = -EAGAIN;
4626                 reason = RESTART_TRANS;
4627         }
4628
4629 leave:
4630         mlog_exit(status);
4631         if (reason_ret)
4632                 *reason_ret = reason;
4633         return status;
4634 }
4635
4636 static void ocfs2_make_right_split_rec(struct super_block *sb,
4637                                        struct ocfs2_extent_rec *split_rec,
4638                                        u32 cpos,
4639                                        struct ocfs2_extent_rec *rec)
4640 {
4641         u32 rec_cpos = le32_to_cpu(rec->e_cpos);
4642         u32 rec_range = rec_cpos + le16_to_cpu(rec->e_leaf_clusters);
4643
4644         memset(split_rec, 0, sizeof(struct ocfs2_extent_rec));
4645
4646         split_rec->e_cpos = cpu_to_le32(cpos);
4647         split_rec->e_leaf_clusters = cpu_to_le16(rec_range - cpos);
4648
4649         split_rec->e_blkno = rec->e_blkno;
4650         le64_add_cpu(&split_rec->e_blkno,
4651                      ocfs2_clusters_to_blocks(sb, cpos - rec_cpos));
4652
4653         split_rec->e_flags = rec->e_flags;
4654 }
4655
4656 static int ocfs2_split_and_insert(struct inode *inode,
4657                                   handle_t *handle,
4658                                   struct ocfs2_path *path,
4659                                   struct ocfs2_extent_tree *et,
4660                                   struct buffer_head **last_eb_bh,
4661                                   int split_index,
4662                                   struct ocfs2_extent_rec *orig_split_rec,
4663                                   struct ocfs2_alloc_context *meta_ac)
4664 {
4665         int ret = 0, depth;
4666         unsigned int insert_range, rec_range, do_leftright = 0;
4667         struct ocfs2_extent_rec tmprec;
4668         struct ocfs2_extent_list *rightmost_el;
4669         struct ocfs2_extent_rec rec;
4670         struct ocfs2_extent_rec split_rec = *orig_split_rec;
4671         struct ocfs2_insert_type insert;
4672         struct ocfs2_extent_block *eb;
4673
4674 leftright:
4675         /*
4676          * Store a copy of the record on the stack - it might move
4677          * around as the tree is manipulated below.
4678          */
4679         rec = path_leaf_el(path)->l_recs[split_index];
4680
4681         rightmost_el = et->root_el;
4682
4683         depth = le16_to_cpu(rightmost_el->l_tree_depth);
4684         if (depth) {
4685                 BUG_ON(!(*last_eb_bh));
4686                 eb = (struct ocfs2_extent_block *) (*last_eb_bh)->b_data;
4687                 rightmost_el = &eb->h_list;
4688         }
4689
4690         if (le16_to_cpu(rightmost_el->l_next_free_rec) ==
4691             le16_to_cpu(rightmost_el->l_count)) {
4692                 ret = ocfs2_grow_tree(inode, handle, et,
4693                                       &depth, last_eb_bh, meta_ac);
4694                 if (ret) {
4695                         mlog_errno(ret);
4696                         goto out;
4697                 }
4698         }
4699
4700         memset(&insert, 0, sizeof(struct ocfs2_insert_type));
4701         insert.ins_appending = APPEND_NONE;
4702         insert.ins_contig = CONTIG_NONE;
4703         insert.ins_tree_depth = depth;
4704
4705         insert_range = le32_to_cpu(split_rec.e_cpos) +
4706                 le16_to_cpu(split_rec.e_leaf_clusters);
4707         rec_range = le32_to_cpu(rec.e_cpos) +
4708                 le16_to_cpu(rec.e_leaf_clusters);
4709
4710         if (split_rec.e_cpos == rec.e_cpos) {
4711                 insert.ins_split = SPLIT_LEFT;
4712         } else if (insert_range == rec_range) {
4713                 insert.ins_split = SPLIT_RIGHT;
4714         } else {
4715                 /*
4716                  * Left/right split. We fake this as a right split
4717                  * first and then make a second pass as a left split.
4718                  */
4719                 insert.ins_split = SPLIT_RIGHT;
4720
4721                 ocfs2_make_right_split_rec(inode->i_sb, &tmprec, insert_range,
4722                                            &rec);
4723
4724                 split_rec = tmprec;
4725
4726                 BUG_ON(do_leftright);
4727                 do_leftright = 1;
4728         }
4729
4730         ret = ocfs2_do_insert_extent(inode, handle, et, &split_rec, &insert);
4731         if (ret) {
4732                 mlog_errno(ret);
4733                 goto out;
4734         }
4735
4736         if (do_leftright == 1) {
4737                 u32 cpos;
4738                 struct ocfs2_extent_list *el;
4739
4740                 do_leftright++;
4741                 split_rec = *orig_split_rec;
4742
4743                 ocfs2_reinit_path(path, 1);
4744
4745                 cpos = le32_to_cpu(split_rec.e_cpos);
4746                 ret = ocfs2_find_path(inode, path, cpos);
4747                 if (ret) {
4748                         mlog_errno(ret);
4749                         goto out;
4750                 }
4751
4752                 el = path_leaf_el(path);
4753                 split_index = ocfs2_search_extent_list(el, cpos);
4754                 goto leftright;
4755         }
4756 out:
4757
4758         return ret;
4759 }
4760
4761 /*
4762  * Mark part or all of the extent record at split_index in the leaf
4763  * pointed to by path as written. This removes the unwritten
4764  * extent flag.
4765  *
4766  * Care is taken to handle contiguousness so as to not grow the tree.
4767  *
4768  * meta_ac is not strictly necessary - we only truly need it if growth
4769  * of the tree is required. All other cases will degrade into a less
4770  * optimal tree layout.
4771  *
4772  * last_eb_bh should be the rightmost leaf block for any extent
4773  * btree. Since a split may grow the tree or a merge might shrink it,
4774  * the caller cannot trust the contents of that buffer after this call.
4775  *
4776  * This code is optimized for readability - several passes might be
4777  * made over certain portions of the tree. All of those blocks will
4778  * have been brought into cache (and pinned via the journal), so the
4779  * extra overhead is not expressed in terms of disk reads.
4780  */
4781 static int __ocfs2_mark_extent_written(struct inode *inode,
4782                                        struct ocfs2_extent_tree *et,
4783                                        handle_t *handle,
4784                                        struct ocfs2_path *path,
4785                                        int split_index,
4786                                        struct ocfs2_extent_rec *split_rec,
4787                                        struct ocfs2_alloc_context *meta_ac,
4788                                        struct ocfs2_cached_dealloc_ctxt *dealloc)
4789 {
4790         int ret = 0;
4791         struct ocfs2_extent_list *el = path_leaf_el(path);
4792         struct buffer_head *last_eb_bh = NULL;
4793         struct ocfs2_extent_rec *rec = &el->l_recs[split_index];
4794         struct ocfs2_merge_ctxt ctxt;
4795         struct ocfs2_extent_list *rightmost_el;
4796
4797         if (!(rec->e_flags & OCFS2_EXT_UNWRITTEN)) {
4798                 ret = -EIO;
4799                 mlog_errno(ret);
4800                 goto out;
4801         }
4802
4803         if (le32_to_cpu(rec->e_cpos) > le32_to_cpu(split_rec->e_cpos) ||
4804             ((le32_to_cpu(rec->e_cpos) + le16_to_cpu(rec->e_leaf_clusters)) <
4805              (le32_to_cpu(split_rec->e_cpos) + le16_to_cpu(split_rec->e_leaf_clusters)))) {
4806                 ret = -EIO;
4807                 mlog_errno(ret);
4808                 goto out;
4809         }
4810
4811         ctxt.c_contig_type = ocfs2_figure_merge_contig_type(inode, path, el,
4812                                                             split_index,
4813                                                             split_rec);
4814
4815         /*
4816          * The core merge / split code wants to know how much room is
4817          * left in this inodes allocation tree, so we pass the
4818          * rightmost extent list.
4819          */
4820         if (path->p_tree_depth) {
4821                 struct ocfs2_extent_block *eb;
4822
4823                 ret = ocfs2_read_block(OCFS2_SB(inode->i_sb),
4824                                        ocfs2_et_get_last_eb_blk(et),
4825                                        &last_eb_bh, OCFS2_BH_CACHED, inode);
4826                 if (ret) {
4827                         mlog_exit(ret);
4828                         goto out;
4829                 }
4830
4831                 eb = (struct ocfs2_extent_block *) last_eb_bh->b_data;
4832                 if (!OCFS2_IS_VALID_EXTENT_BLOCK(eb)) {
4833                         OCFS2_RO_ON_INVALID_EXTENT_BLOCK(inode->i_sb, eb);
4834                         ret = -EROFS;
4835                         goto out;
4836                 }
4837
4838                 rightmost_el = &eb->h_list;
4839         } else
4840                 rightmost_el = path_root_el(path);
4841
4842         if (rec->e_cpos == split_rec->e_cpos &&
4843             rec->e_leaf_clusters == split_rec->e_leaf_clusters)
4844                 ctxt.c_split_covers_rec = 1;
4845         else
4846                 ctxt.c_split_covers_rec = 0;
4847
4848         ctxt.c_has_empty_extent = ocfs2_is_empty_extent(&el->l_recs[0]);
4849
4850         mlog(0, "index: %d, contig: %u, has_empty: %u, split_covers: %u\n",
4851              split_index, ctxt.c_contig_type, ctxt.c_has_empty_extent,
4852              ctxt.c_split_covers_rec);
4853
4854         if (ctxt.c_contig_type == CONTIG_NONE) {
4855                 if (ctxt.c_split_covers_rec)
4856                         el->l_recs[split_index] = *split_rec;
4857                 else
4858                         ret = ocfs2_split_and_insert(inode, handle, path, et,
4859                                                      &last_eb_bh, split_index,
4860                                                      split_rec, meta_ac);
4861                 if (ret)
4862                         mlog_errno(ret);
4863         } else {
4864                 ret = ocfs2_try_to_merge_extent(inode, handle, path,
4865                                                 split_index, split_rec,
4866                                                 dealloc, &ctxt, et);
4867                 if (ret)
4868                         mlog_errno(ret);
4869         }
4870
4871 out:
4872         brelse(last_eb_bh);
4873         return ret;
4874 }
4875
4876 /*
4877  * Mark the already-existing extent at cpos as written for len clusters.
4878  *
4879  * If the existing extent is larger than the request, initiate a
4880  * split. An attempt will be made at merging with adjacent extents.
4881  *
4882  * The caller is responsible for passing down meta_ac if we'll need it.
4883  */
4884 int ocfs2_mark_extent_written(struct inode *inode, struct buffer_head *root_bh,
4885                               handle_t *handle, u32 cpos, u32 len, u32 phys,
4886                               struct ocfs2_alloc_context *meta_ac,
4887                               struct ocfs2_cached_dealloc_ctxt *dealloc,
4888                               enum ocfs2_extent_tree_type et_type,
4889                               void *private)
4890 {
4891         int ret, index;
4892         u64 start_blkno = ocfs2_clusters_to_blocks(inode->i_sb, phys);
4893         struct ocfs2_extent_rec split_rec;
4894         struct ocfs2_path *left_path = NULL;
4895         struct ocfs2_extent_list *el;
4896         struct ocfs2_extent_tree *et = NULL;
4897
4898         mlog(0, "Inode %lu cpos %u, len %u, phys %u (%llu)\n",
4899              inode->i_ino, cpos, len, phys, (unsigned long long)start_blkno);
4900
4901         if (!ocfs2_writes_unwritten_extents(OCFS2_SB(inode->i_sb))) {
4902                 ocfs2_error(inode->i_sb, "Inode %llu has unwritten extents "
4903                             "that are being written to, but the feature bit "
4904                             "is not set in the super block.",
4905                             (unsigned long long)OCFS2_I(inode)->ip_blkno);
4906                 ret = -EROFS;
4907                 goto out;
4908         }
4909
4910         et = ocfs2_new_extent_tree(inode, root_bh, et_type, private);
4911         if (!et) {
4912                 ret = -ENOMEM;
4913                 mlog_errno(ret);
4914                 goto out;
4915         }
4916
4917         /*
4918          * XXX: This should be fixed up so that we just re-insert the
4919          * next extent records.
4920          */
4921         if (et_type == OCFS2_DINODE_EXTENT)
4922                 ocfs2_extent_map_trunc(inode, 0);
4923
4924         left_path = ocfs2_new_path(et->root_bh, et->root_el);
4925         if (!left_path) {
4926                 ret = -ENOMEM;
4927                 mlog_errno(ret);
4928                 goto out;
4929         }
4930
4931         ret = ocfs2_find_path(inode, left_path, cpos);
4932         if (ret) {
4933                 mlog_errno(ret);
4934                 goto out;
4935         }
4936         el = path_leaf_el(left_path);
4937
4938         index = ocfs2_search_extent_list(el, cpos);
4939         if (index == -1 || index >= le16_to_cpu(el->l_next_free_rec)) {
4940                 ocfs2_error(inode->i_sb,
4941                             "Inode %llu has an extent at cpos %u which can no "
4942                             "longer be found.\n",
4943                             (unsigned long long)OCFS2_I(inode)->ip_blkno, cpos);
4944                 ret = -EROFS;
4945                 goto out;
4946         }
4947
4948         memset(&split_rec, 0, sizeof(struct ocfs2_extent_rec));
4949         split_rec.e_cpos = cpu_to_le32(cpos);
4950         split_rec.e_leaf_clusters = cpu_to_le16(len);
4951         split_rec.e_blkno = cpu_to_le64(start_blkno);
4952         split_rec.e_flags = path_leaf_el(left_path)->l_recs[index].e_flags;
4953         split_rec.e_flags &= ~OCFS2_EXT_UNWRITTEN;
4954
4955         ret = __ocfs2_mark_extent_written(inode, et, handle, left_path,
4956                                           index, &split_rec, meta_ac,
4957                                           dealloc);
4958         if (ret)
4959                 mlog_errno(ret);
4960
4961 out:
4962         ocfs2_free_path(left_path);
4963         if (et)
4964                 ocfs2_free_extent_tree(et);
4965         return ret;
4966 }
4967
4968 static int ocfs2_split_tree(struct inode *inode, struct ocfs2_extent_tree *et,
4969                             handle_t *handle, struct ocfs2_path *path,
4970                             int index, u32 new_range,
4971                             struct ocfs2_alloc_context *meta_ac)
4972 {
4973         int ret, depth, credits = handle->h_buffer_credits;
4974         struct buffer_head *last_eb_bh = NULL;
4975         struct ocfs2_extent_block *eb;
4976         struct ocfs2_extent_list *rightmost_el, *el;
4977         struct ocfs2_extent_rec split_rec;
4978         struct ocfs2_extent_rec *rec;
4979         struct ocfs2_insert_type insert;
4980
4981         /*
4982          * Setup the record to split before we grow the tree.
4983          */
4984         el = path_leaf_el(path);
4985         rec = &el->l_recs[index];
4986         ocfs2_make_right_split_rec(inode->i_sb, &split_rec, new_range, rec);
4987
4988         depth = path->p_tree_depth;
4989         if (depth > 0) {
4990                 ret = ocfs2_read_block(OCFS2_SB(inode->i_sb),
4991                                        ocfs2_et_get_last_eb_blk(et),
4992                                        &last_eb_bh, OCFS2_BH_CACHED, inode);
4993                 if (ret < 0) {
4994                         mlog_errno(ret);
4995                         goto out;
4996                 }
4997
4998                 eb = (struct ocfs2_extent_block *) last_eb_bh->b_data;
4999                 rightmost_el = &eb->h_list;
5000         } else
5001                 rightmost_el = path_leaf_el(path);
5002
5003         credits += path->p_tree_depth +
5004                    ocfs2_extend_meta_needed(et->root_el);
5005         ret = ocfs2_extend_trans(handle, credits);
5006         if (ret) {
5007                 mlog_errno(ret);
5008                 goto out;
5009         }
5010
5011         if (le16_to_cpu(rightmost_el->l_next_free_rec) ==
5012             le16_to_cpu(rightmost_el->l_count)) {
5013                 ret = ocfs2_grow_tree(inode, handle, et, &depth, &last_eb_bh,
5014                                       meta_ac);
5015                 if (ret) {
5016                         mlog_errno(ret);
5017                         goto out;
5018                 }
5019         }
5020
5021         memset(&insert, 0, sizeof(struct ocfs2_insert_type));
5022         insert.ins_appending = APPEND_NONE;
5023         insert.ins_contig = CONTIG_NONE;
5024         insert.ins_split = SPLIT_RIGHT;
5025         insert.ins_tree_depth = depth;
5026
5027         ret = ocfs2_do_insert_extent(inode, handle, et, &split_rec, &insert);
5028         if (ret)
5029                 mlog_errno(ret);
5030
5031 out:
5032         brelse(last_eb_bh);
5033         return ret;
5034 }
5035
5036 static int ocfs2_truncate_rec(struct inode *inode, handle_t *handle,
5037                               struct ocfs2_path *path, int index,
5038                               struct ocfs2_cached_dealloc_ctxt *dealloc,
5039                               u32 cpos, u32 len,
5040                               struct ocfs2_extent_tree *et)
5041 {
5042         int ret;
5043         u32 left_cpos, rec_range, trunc_range;
5044         int wants_rotate = 0, is_rightmost_tree_rec = 0;
5045         struct super_block *sb = inode->i_sb;
5046         struct ocfs2_path *left_path = NULL;
5047         struct ocfs2_extent_list *el = path_leaf_el(path);
5048         struct ocfs2_extent_rec *rec;
5049         struct ocfs2_extent_block *eb;
5050
5051         if (ocfs2_is_empty_extent(&el->l_recs[0]) && index > 0) {
5052                 ret = ocfs2_rotate_tree_left(inode, handle, path, dealloc, et);
5053                 if (ret) {
5054                         mlog_errno(ret);
5055                         goto out;
5056                 }
5057
5058                 index--;
5059         }
5060
5061         if (index == (le16_to_cpu(el->l_next_free_rec) - 1) &&
5062             path->p_tree_depth) {
5063                 /*
5064                  * Check whether this is the rightmost tree record. If
5065                  * we remove all of this record or part of its right
5066                  * edge then an update of the record lengths above it
5067                  * will be required.
5068                  */
5069                 eb = (struct ocfs2_extent_block *)path_leaf_bh(path)->b_data;
5070                 if (eb->h_next_leaf_blk == 0)
5071                         is_rightmost_tree_rec = 1;
5072         }
5073
5074         rec = &el->l_recs[index];
5075         if (index == 0 && path->p_tree_depth &&
5076             le32_to_cpu(rec->e_cpos) == cpos) {
5077                 /*
5078                  * Changing the leftmost offset (via partial or whole
5079                  * record truncate) of an interior (or rightmost) path
5080                  * means we have to update the subtree that is formed
5081                  * by this leaf and the one to it's left.
5082                  *
5083                  * There are two cases we can skip:
5084                  *   1) Path is the leftmost one in our inode tree.
5085                  *   2) The leaf is rightmost and will be empty after
5086                  *      we remove the extent record - the rotate code
5087                  *      knows how to update the newly formed edge.
5088                  */
5089
5090                 ret = ocfs2_find_cpos_for_left_leaf(inode->i_sb, path,
5091                                                     &left_cpos);
5092                 if (ret) {
5093                         mlog_errno(ret);
5094                         goto out;
5095                 }
5096
5097                 if (left_cpos && le16_to_cpu(el->l_next_free_rec) > 1) {
5098                         left_path = ocfs2_new_path(path_root_bh(path),
5099                                                    path_root_el(path));
5100                         if (!left_path) {
5101                                 ret = -ENOMEM;
5102                                 mlog_errno(ret);
5103                                 goto out;
5104                         }
5105
5106                         ret = ocfs2_find_path(inode, left_path, left_cpos);
5107                         if (ret) {
5108                                 mlog_errno(ret);
5109                                 goto out;
5110                         }
5111                 }
5112         }
5113
5114         ret = ocfs2_extend_rotate_transaction(handle, 0,
5115                                               handle->h_buffer_credits,
5116                                               path);
5117         if (ret) {
5118                 mlog_errno(ret);
5119                 goto out;
5120         }
5121
5122         ret = ocfs2_journal_access_path(inode, handle, path);
5123         if (ret) {
5124                 mlog_errno(ret);
5125                 goto out;
5126         }
5127
5128         ret = ocfs2_journal_access_path(inode, handle, left_path);
5129         if (ret) {
5130                 mlog_errno(ret);
5131                 goto out;
5132         }
5133
5134         rec_range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
5135         trunc_range = cpos + len;
5136
5137         if (le32_to_cpu(rec->e_cpos) == cpos && rec_range == trunc_range) {
5138                 int next_free;
5139
5140                 memset(rec, 0, sizeof(*rec));
5141                 ocfs2_cleanup_merge(el, index);
5142                 wants_rotate = 1;
5143
5144                 next_free = le16_to_cpu(el->l_next_free_rec);
5145                 if (is_rightmost_tree_rec && next_free > 1) {
5146                         /*
5147                          * We skip the edge update if this path will
5148                          * be deleted by the rotate code.
5149                          */
5150                         rec = &el->l_recs[next_free - 1];
5151                         ocfs2_adjust_rightmost_records(inode, handle, path,
5152                                                        rec);
5153                 }
5154         } else if (le32_to_cpu(rec->e_cpos) == cpos) {
5155                 /* Remove leftmost portion of the record. */
5156                 le32_add_cpu(&rec->e_cpos, len);
5157                 le64_add_cpu(&rec->e_blkno, ocfs2_clusters_to_blocks(sb, len));
5158                 le16_add_cpu(&rec->e_leaf_clusters, -len);
5159         } else if (rec_range == trunc_range) {
5160                 /* Remove rightmost portion of the record */
5161                 le16_add_cpu(&rec->e_leaf_clusters, -len);
5162                 if (is_rightmost_tree_rec)
5163                         ocfs2_adjust_rightmost_records(inode, handle, path, rec);
5164         } else {
5165                 /* Caller should have trapped this. */
5166                 mlog(ML_ERROR, "Inode %llu: Invalid record truncate: (%u, %u) "
5167                      "(%u, %u)\n", (unsigned long long)OCFS2_I(inode)->ip_blkno,
5168                      le32_to_cpu(rec->e_cpos),
5169                      le16_to_cpu(rec->e_leaf_clusters), cpos, len);
5170                 BUG();
5171         }
5172
5173         if (left_path) {
5174                 int subtree_index;
5175
5176                 subtree_index = ocfs2_find_subtree_root(inode, left_path, path);
5177                 ocfs2_complete_edge_insert(inode, handle, left_path, path,
5178                                            subtree_index);
5179         }
5180
5181         ocfs2_journal_dirty(handle, path_leaf_bh(path));
5182
5183         ret = ocfs2_rotate_tree_left(inode, handle, path, dealloc, et);
5184         if (ret) {
5185                 mlog_errno(ret);
5186                 goto out;
5187         }
5188
5189 out:
5190         ocfs2_free_path(left_path);
5191         return ret;
5192 }
5193
5194 int ocfs2_remove_extent(struct inode *inode, struct buffer_head *root_bh,
5195                         u32 cpos, u32 len, handle_t *handle,
5196                         struct ocfs2_alloc_context *meta_ac,
5197                         struct ocfs2_cached_dealloc_ctxt *dealloc,
5198                         enum ocfs2_extent_tree_type et_type,
5199                         void *private)
5200 {
5201         int ret, index;
5202         u32 rec_range, trunc_range;
5203         struct ocfs2_extent_rec *rec;
5204         struct ocfs2_extent_list *el;
5205         struct ocfs2_path *path = NULL;
5206         struct ocfs2_extent_tree *et = NULL;
5207
5208         et = ocfs2_new_extent_tree(inode, root_bh, et_type, private);
5209         if (!et) {
5210                 ret = -ENOMEM;
5211                 mlog_errno(ret);
5212                 goto out;
5213         }
5214
5215         ocfs2_extent_map_trunc(inode, 0);
5216
5217         path = ocfs2_new_path(et->root_bh, et->root_el);
5218         if (!path) {
5219                 ret = -ENOMEM;
5220                 mlog_errno(ret);
5221                 goto out;
5222         }
5223
5224         ret = ocfs2_find_path(inode, path, cpos);
5225         if (ret) {
5226                 mlog_errno(ret);
5227                 goto out;
5228         }
5229
5230         el = path_leaf_el(path);
5231         index = ocfs2_search_extent_list(el, cpos);
5232         if (index == -1 || index >= le16_to_cpu(el->l_next_free_rec)) {
5233                 ocfs2_error(inode->i_sb,
5234                             "Inode %llu has an extent at cpos %u which can no "
5235                             "longer be found.\n",
5236                             (unsigned long long)OCFS2_I(inode)->ip_blkno, cpos);
5237                 ret = -EROFS;
5238                 goto out;
5239         }
5240
5241         /*
5242          * We have 3 cases of extent removal:
5243          *   1) Range covers the entire extent rec
5244          *   2) Range begins or ends on one edge of the extent rec
5245          *   3) Range is in the middle of the extent rec (no shared edges)
5246          *
5247          * For case 1 we remove the extent rec and left rotate to
5248          * fill the hole.
5249          *
5250          * For case 2 we just shrink the existing extent rec, with a
5251          * tree update if the shrinking edge is also the edge of an
5252          * extent block.
5253          *
5254          * For case 3 we do a right split to turn the extent rec into
5255          * something case 2 can handle.
5256          */
5257         rec = &el->l_recs[index];
5258         rec_range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
5259         trunc_range = cpos + len;
5260
5261         BUG_ON(cpos < le32_to_cpu(rec->e_cpos) || trunc_range > rec_range);
5262
5263         mlog(0, "Inode %llu, remove (cpos %u, len %u). Existing index %d "
5264              "(cpos %u, len %u)\n",
5265              (unsigned long long)OCFS2_I(inode)->ip_blkno, cpos, len, index,
5266              le32_to_cpu(rec->e_cpos), ocfs2_rec_clusters(el, rec));
5267
5268         if (le32_to_cpu(rec->e_cpos) == cpos || rec_range == trunc_range) {
5269                 ret = ocfs2_truncate_rec(inode, handle, path, index, dealloc,
5270                                          cpos, len, et);
5271                 if (ret) {
5272                         mlog_errno(ret);
5273                         goto out;
5274                 }
5275         } else {
5276                 ret = ocfs2_split_tree(inode, et, handle, path, index,
5277                                        trunc_range, meta_ac);
5278                 if (ret) {
5279                         mlog_errno(ret);
5280                         goto out;
5281                 }
5282
5283                 /*
5284                  * The split could have manipulated the tree enough to
5285                  * move the record location, so we have to look for it again.
5286                  */
5287                 ocfs2_reinit_path(path, 1);
5288
5289                 ret = ocfs2_find_path(inode, path, cpos);
5290                 if (ret) {
5291                         mlog_errno(ret);
5292                         goto out;
5293                 }
5294
5295                 el = path_leaf_el(path);
5296                 index = ocfs2_search_extent_list(el, cpos);
5297                 if (index == -1 || index >= le16_to_cpu(el->l_next_free_rec)) {
5298                         ocfs2_error(inode->i_sb,
5299                                     "Inode %llu: split at cpos %u lost record.",
5300                                     (unsigned long long)OCFS2_I(inode)->ip_blkno,
5301                                     cpos);
5302                         ret = -EROFS;
5303                         goto out;
5304                 }
5305
5306                 /*
5307                  * Double check our values here. If anything is fishy,
5308                  * it's easier to catch it at the top level.
5309                  */
5310                 rec = &el->l_recs[index];
5311                 rec_range = le32_to_cpu(rec->e_cpos) +
5312                         ocfs2_rec_clusters(el, rec);
5313                 if (rec_range != trunc_range) {
5314                         ocfs2_error(inode->i_sb,
5315                                     "Inode %llu: error after split at cpos %u"
5316                                     "trunc len %u, existing record is (%u,%u)",
5317                                     (unsigned long long)OCFS2_I(inode)->ip_blkno,
5318                                     cpos, len, le32_to_cpu(rec->e_cpos),
5319                                     ocfs2_rec_clusters(el, rec));
5320                         ret = -EROFS;
5321                         goto out;
5322                 }
5323
5324                 ret = ocfs2_truncate_rec(inode, handle, path, index, dealloc,
5325                                          cpos, len, et);
5326                 if (ret) {
5327                         mlog_errno(ret);
5328                         goto out;
5329                 }
5330         }
5331
5332 out:
5333         ocfs2_free_path(path);
5334         if (et)
5335                 ocfs2_free_extent_tree(et);
5336         return ret;
5337 }
5338
5339 int ocfs2_truncate_log_needs_flush(struct ocfs2_super *osb)
5340 {
5341         struct buffer_head *tl_bh = osb->osb_tl_bh;
5342         struct ocfs2_dinode *di;
5343         struct ocfs2_truncate_log *tl;
5344
5345         di = (struct ocfs2_dinode *) tl_bh->b_data;
5346         tl = &di->id2.i_dealloc;
5347
5348         mlog_bug_on_msg(le16_to_cpu(tl->tl_used) > le16_to_cpu(tl->tl_count),
5349                         "slot %d, invalid truncate log parameters: used = "
5350                         "%u, count = %u\n", osb->slot_num,
5351                         le16_to_cpu(tl->tl_used), le16_to_cpu(tl->tl_count));
5352         return le16_to_cpu(tl->tl_used) == le16_to_cpu(tl->tl_count);
5353 }
5354
5355 static int ocfs2_truncate_log_can_coalesce(struct ocfs2_truncate_log *tl,
5356                                            unsigned int new_start)
5357 {
5358         unsigned int tail_index;
5359         unsigned int current_tail;
5360
5361         /* No records, nothing to coalesce */
5362         if (!le16_to_cpu(tl->tl_used))
5363                 return 0;
5364
5365         tail_index = le16_to_cpu(tl->tl_used) - 1;
5366         current_tail = le32_to_cpu(tl->tl_recs[tail_index].t_start);
5367         current_tail += le32_to_cpu(tl->tl_recs[tail_index].t_clusters);
5368
5369         return current_tail == new_start;
5370 }
5371
5372 int ocfs2_truncate_log_append(struct ocfs2_super *osb,
5373                               handle_t *handle,
5374                               u64 start_blk,
5375                               unsigned int num_clusters)
5376 {
5377         int status, index;
5378         unsigned int start_cluster, tl_count;
5379         struct inode *tl_inode = osb->osb_tl_inode;
5380         struct buffer_head *tl_bh = osb->osb_tl_bh;
5381         struct ocfs2_dinode *di;
5382         struct ocfs2_truncate_log *tl;
5383
5384         mlog_entry("start_blk = %llu, num_clusters = %u\n",
5385                    (unsigned long long)start_blk, num_clusters);
5386
5387         BUG_ON(mutex_trylock(&tl_inode->i_mutex));
5388
5389         start_cluster = ocfs2_blocks_to_clusters(osb->sb, start_blk);
5390
5391         di = (struct ocfs2_dinode *) tl_bh->b_data;
5392         tl = &di->id2.i_dealloc;
5393         if (!OCFS2_IS_VALID_DINODE(di)) {
5394                 OCFS2_RO_ON_INVALID_DINODE(osb->sb, di);
5395                 status = -EIO;
5396                 goto bail;
5397         }
5398
5399         tl_count = le16_to_cpu(tl->tl_count);
5400         mlog_bug_on_msg(tl_count > ocfs2_truncate_recs_per_inode(osb->sb) ||
5401                         tl_count == 0,
5402                         "Truncate record count on #%llu invalid "
5403                         "wanted %u, actual %u\n",
5404                         (unsigned long long)OCFS2_I(tl_inode)->ip_blkno,
5405                         ocfs2_truncate_recs_per_inode(osb->sb),
5406                         le16_to_cpu(tl->tl_count));
5407
5408         /* Caller should have known to flush before calling us. */
5409         index = le16_to_cpu(tl->tl_used);
5410         if (index >= tl_count) {
5411                 status = -ENOSPC;
5412                 mlog_errno(status);
5413                 goto bail;
5414         }
5415
5416         status = ocfs2_journal_access(handle, tl_inode, tl_bh,
5417                                       OCFS2_JOURNAL_ACCESS_WRITE);
5418         if (status < 0) {
5419                 mlog_errno(status);
5420                 goto bail;
5421         }
5422
5423         mlog(0, "Log truncate of %u clusters starting at cluster %u to "
5424              "%llu (index = %d)\n", num_clusters, start_cluster,
5425              (unsigned long long)OCFS2_I(tl_inode)->ip_blkno, index);
5426
5427         if (ocfs2_truncate_log_can_coalesce(tl, start_cluster)) {
5428                 /*
5429                  * Move index back to the record we are coalescing with.
5430                  * ocfs2_truncate_log_can_coalesce() guarantees nonzero
5431                  */
5432                 index--;
5433
5434                 num_clusters += le32_to_cpu(tl->tl_recs[index].t_clusters);
5435                 mlog(0, "Coalesce with index %u (start = %u, clusters = %u)\n",
5436                      index, le32_to_cpu(tl->tl_recs[index].t_start),
5437                      num_clusters);
5438         } else {
5439                 tl->tl_recs[index].t_start = cpu_to_le32(start_cluster);
5440                 tl->tl_used = cpu_to_le16(index + 1);
5441         }
5442         tl->tl_recs[index].t_clusters = cpu_to_le32(num_clusters);
5443
5444         status = ocfs2_journal_dirty(handle, tl_bh);
5445         if (status < 0) {
5446                 mlog_errno(status);
5447                 goto bail;
5448         }
5449
5450 bail:
5451         mlog_exit(status);
5452         return status;
5453 }
5454
5455 static int ocfs2_replay_truncate_records(struct ocfs2_super *osb,
5456                                          handle_t *handle,
5457                                          struct inode *data_alloc_inode,
5458                                          struct buffer_head *data_alloc_bh)
5459 {
5460         int status = 0;
5461         int i;
5462         unsigned int num_clusters;
5463         u64 start_blk;
5464         struct ocfs2_truncate_rec rec;
5465         struct ocfs2_dinode *di;
5466         struct ocfs2_truncate_log *tl;
5467         struct inode *tl_inode = osb->osb_tl_inode;
5468         struct buffer_head *tl_bh = osb->osb_tl_bh;
5469
5470         mlog_entry_void();
5471
5472         di = (struct ocfs2_dinode *) tl_bh->b_data;
5473         tl = &di->id2.i_dealloc;
5474         i = le16_to_cpu(tl->tl_used) - 1;
5475         while (i >= 0) {
5476                 /* Caller has given us at least enough credits to
5477                  * update the truncate log dinode */
5478                 status = ocfs2_journal_access(handle, tl_inode, tl_bh,
5479                                               OCFS2_JOURNAL_ACCESS_WRITE);
5480                 if (status < 0) {
5481                         mlog_errno(status);
5482                         goto bail;
5483                 }
5484
5485                 tl->tl_used = cpu_to_le16(i);
5486
5487                 status = ocfs2_journal_dirty(handle, tl_bh);
5488                 if (status < 0) {
5489                         mlog_errno(status);
5490                         goto bail;
5491                 }
5492
5493                 /* TODO: Perhaps we can calculate the bulk of the
5494                  * credits up front rather than extending like
5495                  * this. */
5496                 status = ocfs2_extend_trans(handle,
5497                                             OCFS2_TRUNCATE_LOG_FLUSH_ONE_REC);
5498                 if (status < 0) {
5499                         mlog_errno(status);
5500                         goto bail;
5501                 }
5502
5503                 rec = tl->tl_recs[i];
5504                 start_blk = ocfs2_clusters_to_blocks(data_alloc_inode->i_sb,
5505                                                     le32_to_cpu(rec.t_start));
5506                 num_clusters = le32_to_cpu(rec.t_clusters);
5507
5508                 /* if start_blk is not set, we ignore the record as
5509                  * invalid. */
5510                 if (start_blk) {
5511                         mlog(0, "free record %d, start = %u, clusters = %u\n",
5512                              i, le32_to_cpu(rec.t_start), num_clusters);
5513
5514                         status = ocfs2_free_clusters(handle, data_alloc_inode,
5515                                                      data_alloc_bh, start_blk,
5516                                                      num_clusters);
5517                         if (status < 0) {
5518                                 mlog_errno(status);
5519                                 goto bail;
5520                         }
5521                 }
5522                 i--;
5523         }
5524
5525 bail:
5526         mlog_exit(status);
5527         return status;
5528 }
5529
5530 /* Expects you to already be holding tl_inode->i_mutex */
5531 int __ocfs2_flush_truncate_log(struct ocfs2_super *osb)
5532 {
5533         int status;
5534         unsigned int num_to_flush;
5535         handle_t *handle;
5536         struct inode *tl_inode = osb->osb_tl_inode;
5537         struct inode *data_alloc_inode = NULL;
5538         struct buffer_head *tl_bh = osb->osb_tl_bh;
5539         struct buffer_head *data_alloc_bh = NULL;
5540         struct ocfs2_dinode *di;
5541         struct ocfs2_truncate_log *tl;
5542
5543         mlog_entry_void();
5544
5545         BUG_ON(mutex_trylock(&tl_inode->i_mutex));
5546
5547         di = (struct ocfs2_dinode *) tl_bh->b_data;
5548         tl = &di->id2.i_dealloc;
5549         if (!OCFS2_IS_VALID_DINODE(di)) {
5550                 OCFS2_RO_ON_INVALID_DINODE(osb->sb, di);
5551                 status = -EIO;
5552                 goto out;
5553         }
5554
5555         num_to_flush = le16_to_cpu(tl->tl_used);
5556         mlog(0, "Flush %u records from truncate log #%llu\n",
5557              num_to_flush, (unsigned long long)OCFS2_I(tl_inode)->ip_blkno);
5558         if (!num_to_flush) {
5559                 status = 0;
5560                 goto out;
5561         }
5562
5563         data_alloc_inode = ocfs2_get_system_file_inode(osb,
5564                                                        GLOBAL_BITMAP_SYSTEM_INODE,
5565                                                        OCFS2_INVALID_SLOT);
5566         if (!data_alloc_inode) {
5567                 status = -EINVAL;
5568                 mlog(ML_ERROR, "Could not get bitmap inode!\n");
5569                 goto out;
5570         }
5571
5572         mutex_lock(&data_alloc_inode->i_mutex);
5573
5574         status = ocfs2_inode_lock(data_alloc_inode, &data_alloc_bh, 1);
5575         if (status < 0) {
5576                 mlog_errno(status);
5577                 goto out_mutex;
5578         }
5579
5580         handle = ocfs2_start_trans(osb, OCFS2_TRUNCATE_LOG_UPDATE);
5581         if (IS_ERR(handle)) {
5582                 status = PTR_ERR(handle);
5583                 mlog_errno(status);
5584                 goto out_unlock;
5585         }
5586
5587         status = ocfs2_replay_truncate_records(osb, handle, data_alloc_inode,
5588                                                data_alloc_bh);
5589         if (status < 0)
5590                 mlog_errno(status);
5591
5592         ocfs2_commit_trans(osb, handle);
5593
5594 out_unlock:
5595         brelse(data_alloc_bh);
5596         ocfs2_inode_unlock(data_alloc_inode, 1);
5597
5598 out_mutex:
5599         mutex_unlock(&data_alloc_inode->i_mutex);
5600         iput(data_alloc_inode);
5601
5602 out:
5603         mlog_exit(status);
5604         return status;
5605 }
5606
5607 int ocfs2_flush_truncate_log(struct ocfs2_super *osb)
5608 {
5609         int status;
5610         struct inode *tl_inode = osb->osb_tl_inode;
5611
5612         mutex_lock(&tl_inode->i_mutex);
5613         status = __ocfs2_flush_truncate_log(osb);
5614         mutex_unlock(&tl_inode->i_mutex);
5615
5616         return status;
5617 }
5618
5619 static void ocfs2_truncate_log_worker(struct work_struct *work)
5620 {
5621         int status;
5622         struct ocfs2_super *osb =
5623                 container_of(work, struct ocfs2_super,
5624                              osb_truncate_log_wq.work);
5625
5626         mlog_entry_void();
5627
5628         status = ocfs2_flush_truncate_log(osb);
5629         if (status < 0)
5630                 mlog_errno(status);
5631         else
5632                 ocfs2_init_inode_steal_slot(osb);
5633
5634         mlog_exit(status);
5635 }
5636
5637 #define OCFS2_TRUNCATE_LOG_FLUSH_INTERVAL (2 * HZ)
5638 void ocfs2_schedule_truncate_log_flush(struct ocfs2_super *osb,
5639                                        int cancel)
5640 {
5641         if (osb->osb_tl_inode) {
5642                 /* We want to push off log flushes while truncates are
5643                  * still running. */
5644                 if (cancel)
5645                         cancel_delayed_work(&osb->osb_truncate_log_wq);
5646
5647                 queue_delayed_work(ocfs2_wq, &osb->osb_truncate_log_wq,
5648                                    OCFS2_TRUNCATE_LOG_FLUSH_INTERVAL);
5649         }
5650 }
5651
5652 static int ocfs2_get_truncate_log_info(struct ocfs2_super *osb,
5653                                        int slot_num,
5654                                        struct inode **tl_inode,
5655                                        struct buffer_head **tl_bh)
5656 {
5657         int status;
5658         struct inode *inode = NULL;
5659         struct buffer_head *bh = NULL;
5660
5661         inode = ocfs2_get_system_file_inode(osb,
5662                                            TRUNCATE_LOG_SYSTEM_INODE,
5663                                            slot_num);
5664         if (!inode) {
5665                 status = -EINVAL;
5666                 mlog(ML_ERROR, "Could not get load truncate log inode!\n");
5667                 goto bail;
5668         }
5669
5670         status = ocfs2_read_block(osb, OCFS2_I(inode)->ip_blkno, &bh,
5671                                   OCFS2_BH_CACHED, inode);
5672         if (status < 0) {
5673                 iput(inode);
5674                 mlog_errno(status);
5675                 goto bail;
5676         }
5677
5678         *tl_inode = inode;
5679         *tl_bh    = bh;
5680 bail:
5681         mlog_exit(status);
5682         return status;
5683 }
5684
5685 /* called during the 1st stage of node recovery. we stamp a clean
5686  * truncate log and pass back a copy for processing later. if the
5687  * truncate log does not require processing, a *tl_copy is set to
5688  * NULL. */
5689 int ocfs2_begin_truncate_log_recovery(struct ocfs2_super *osb,
5690                                       int slot_num,
5691                                       struct ocfs2_dinode **tl_copy)
5692 {
5693         int status;
5694         struct inode *tl_inode = NULL;
5695         struct buffer_head *tl_bh = NULL;
5696         struct ocfs2_dinode *di;
5697         struct ocfs2_truncate_log *tl;
5698
5699         *tl_copy = NULL;
5700
5701         mlog(0, "recover truncate log from slot %d\n", slot_num);
5702
5703         status = ocfs2_get_truncate_log_info(osb, slot_num, &tl_inode, &tl_bh);
5704         if (status < 0) {
5705                 mlog_errno(status);
5706                 goto bail;
5707         }
5708
5709         di = (struct ocfs2_dinode *) tl_bh->b_data;
5710         tl = &di->id2.i_dealloc;
5711         if (!OCFS2_IS_VALID_DINODE(di)) {
5712                 OCFS2_RO_ON_INVALID_DINODE(tl_inode->i_sb, di);
5713                 status = -EIO;
5714                 goto bail;
5715         }
5716
5717         if (le16_to_cpu(tl->tl_used)) {
5718                 mlog(0, "We'll have %u logs to recover\n",
5719                      le16_to_cpu(tl->tl_used));
5720
5721                 *tl_copy = kmalloc(tl_bh->b_size, GFP_KERNEL);
5722                 if (!(*tl_copy)) {
5723                         status = -ENOMEM;
5724                         mlog_errno(status);
5725                         goto bail;
5726                 }
5727
5728                 /* Assuming the write-out below goes well, this copy
5729                  * will be passed back to recovery for processing. */
5730                 memcpy(*tl_copy, tl_bh->b_data, tl_bh->b_size);
5731
5732                 /* All we need to do to clear the truncate log is set
5733                  * tl_used. */
5734                 tl->tl_used = 0;
5735
5736                 status = ocfs2_write_block(osb, tl_bh, tl_inode);
5737                 if (status < 0) {
5738                         mlog_errno(status);
5739                         goto bail;
5740                 }
5741         }
5742
5743 bail:
5744         if (tl_inode)
5745                 iput(tl_inode);
5746         if (tl_bh)
5747                 brelse(tl_bh);
5748
5749         if (status < 0 && (*tl_copy)) {
5750                 kfree(*tl_copy);
5751                 *tl_copy = NULL;
5752         }
5753
5754         mlog_exit(status);
5755         return status;
5756 }
5757
5758 int ocfs2_complete_truncate_log_recovery(struct ocfs2_super *osb,
5759                                          struct ocfs2_dinode *tl_copy)
5760 {
5761         int status = 0;
5762         int i;
5763         unsigned int clusters, num_recs, start_cluster;
5764         u64 start_blk;
5765         handle_t *handle;
5766         struct inode *tl_inode = osb->osb_tl_inode;
5767         struct ocfs2_truncate_log *tl;
5768
5769         mlog_entry_void();
5770
5771         if (OCFS2_I(tl_inode)->ip_blkno == le64_to_cpu(tl_copy->i_blkno)) {
5772                 mlog(ML_ERROR, "Asked to recover my own truncate log!\n");
5773                 return -EINVAL;
5774         }
5775
5776         tl = &tl_copy->id2.i_dealloc;
5777         num_recs = le16_to_cpu(tl->tl_used);
5778         mlog(0, "cleanup %u records from %llu\n", num_recs,
5779              (unsigned long long)le64_to_cpu(tl_copy->i_blkno));
5780
5781         mutex_lock(&tl_inode->i_mutex);
5782         for(i = 0; i < num_recs; i++) {
5783                 if (ocfs2_truncate_log_needs_flush(osb)) {
5784                         status = __ocfs2_flush_truncate_log(osb);
5785                         if (status < 0) {
5786                                 mlog_errno(status);
5787                                 goto bail_up;
5788                         }
5789                 }
5790
5791                 handle = ocfs2_start_trans(osb, OCFS2_TRUNCATE_LOG_UPDATE);
5792                 if (IS_ERR(handle)) {
5793                         status = PTR_ERR(handle);
5794                         mlog_errno(status);
5795                         goto bail_up;
5796                 }
5797
5798                 clusters = le32_to_cpu(tl->tl_recs[i].t_clusters);
5799                 start_cluster = le32_to_cpu(tl->tl_recs[i].t_start);
5800                 start_blk = ocfs2_clusters_to_blocks(osb->sb, start_cluster);
5801
5802                 status = ocfs2_truncate_log_append(osb, handle,
5803                                                    start_blk, clusters);
5804                 ocfs2_commit_trans(osb, handle);
5805                 if (status < 0) {
5806                         mlog_errno(status);
5807                         goto bail_up;
5808                 }
5809         }
5810
5811 bail_up:
5812         mutex_unlock(&tl_inode->i_mutex);
5813
5814         mlog_exit(status);
5815         return status;
5816 }
5817
5818 void ocfs2_truncate_log_shutdown(struct ocfs2_super *osb)
5819 {
5820         int status;
5821         struct inode *tl_inode = osb->osb_tl_inode;
5822
5823         mlog_entry_void();
5824
5825         if (tl_inode) {
5826                 cancel_delayed_work(&osb->osb_truncate_log_wq);
5827                 flush_workqueue(ocfs2_wq);
5828
5829                 status = ocfs2_flush_truncate_log(osb);
5830                 if (status < 0)
5831                         mlog_errno(status);
5832
5833                 brelse(osb->osb_tl_bh);
5834                 iput(osb->osb_tl_inode);
5835         }
5836
5837         mlog_exit_void();
5838 }
5839
5840 int ocfs2_truncate_log_init(struct ocfs2_super *osb)
5841 {
5842         int status;
5843         struct inode *tl_inode = NULL;
5844         struct buffer_head *tl_bh = NULL;
5845
5846         mlog_entry_void();
5847
5848         status = ocfs2_get_truncate_log_info(osb,
5849                                              osb->slot_num,
5850                                              &tl_inode,
5851                                              &tl_bh);
5852         if (status < 0)
5853                 mlog_errno(status);
5854
5855         /* ocfs2_truncate_log_shutdown keys on the existence of
5856          * osb->osb_tl_inode so we don't set any of the osb variables
5857          * until we're sure all is well. */
5858         INIT_DELAYED_WORK(&osb->osb_truncate_log_wq,
5859                           ocfs2_truncate_log_worker);
5860         osb->osb_tl_bh    = tl_bh;
5861         osb->osb_tl_inode = tl_inode;
5862
5863         mlog_exit(status);
5864         return status;
5865 }
5866
5867 /*
5868  * Delayed de-allocation of suballocator blocks.
5869  *
5870  * Some sets of block de-allocations might involve multiple suballocator inodes.
5871  *
5872  * The locking for this can get extremely complicated, especially when
5873  * the suballocator inodes to delete from aren't known until deep
5874  * within an unrelated codepath.
5875  *
5876  * ocfs2_extent_block structures are a good example of this - an inode
5877  * btree could have been grown by any number of nodes each allocating
5878  * out of their own suballoc inode.
5879  *
5880  * These structures allow the delay of block de-allocation until a
5881  * later time, when locking of multiple cluster inodes won't cause
5882  * deadlock.
5883  */
5884
5885 /*
5886  * Describes a single block free from a suballocator
5887  */
5888 struct ocfs2_cached_block_free {
5889         struct ocfs2_cached_block_free          *free_next;
5890         u64                                     free_blk;
5891         unsigned int                            free_bit;
5892 };
5893
5894 struct ocfs2_per_slot_free_list {
5895         struct ocfs2_per_slot_free_list         *f_next_suballocator;
5896         int                                     f_inode_type;
5897         int                                     f_slot;
5898         struct ocfs2_cached_block_free          *f_first;
5899 };
5900
5901 static int ocfs2_free_cached_items(struct ocfs2_super *osb,
5902                                    int sysfile_type,
5903                                    int slot,
5904                                    struct ocfs2_cached_block_free *head)
5905 {
5906         int ret;
5907         u64 bg_blkno;
5908         handle_t *handle;
5909         struct inode *inode;
5910         struct buffer_head *di_bh = NULL;
5911         struct ocfs2_cached_block_free *tmp;
5912
5913         inode = ocfs2_get_system_file_inode(osb, sysfile_type, slot);
5914         if (!inode) {
5915                 ret = -EINVAL;
5916                 mlog_errno(ret);
5917                 goto out;
5918         }
5919
5920         mutex_lock(&inode->i_mutex);
5921
5922         ret = ocfs2_inode_lock(inode, &di_bh, 1);
5923         if (ret) {
5924                 mlog_errno(ret);
5925                 goto out_mutex;
5926         }
5927
5928         handle = ocfs2_start_trans(osb, OCFS2_SUBALLOC_FREE);
5929         if (IS_ERR(handle)) {
5930                 ret = PTR_ERR(handle);
5931                 mlog_errno(ret);
5932                 goto out_unlock;
5933         }
5934
5935         while (head) {
5936                 bg_blkno = ocfs2_which_suballoc_group(head->free_blk,
5937                                                       head->free_bit);
5938                 mlog(0, "Free bit: (bit %u, blkno %llu)\n",
5939                      head->free_bit, (unsigned long long)head->free_blk);
5940
5941                 ret = ocfs2_free_suballoc_bits(handle, inode, di_bh,
5942                                                head->free_bit, bg_blkno, 1);
5943                 if (ret) {
5944                         mlog_errno(ret);
5945                         goto out_journal;
5946                 }
5947
5948                 ret = ocfs2_extend_trans(handle, OCFS2_SUBALLOC_FREE);
5949                 if (ret) {
5950                         mlog_errno(ret);
5951                         goto out_journal;
5952                 }
5953
5954                 tmp = head;
5955                 head = head->free_next;
5956                 kfree(tmp);
5957         }
5958
5959 out_journal:
5960         ocfs2_commit_trans(osb, handle);
5961
5962 out_unlock:
5963         ocfs2_inode_unlock(inode, 1);
5964         brelse(di_bh);
5965 out_mutex:
5966         mutex_unlock(&inode->i_mutex);
5967         iput(inode);
5968 out:
5969         while(head) {
5970                 /* Premature exit may have left some dangling items. */
5971                 tmp = head;
5972                 head = head->free_next;
5973                 kfree(tmp);
5974         }
5975
5976         return ret;
5977 }
5978
5979 int ocfs2_run_deallocs(struct ocfs2_super *osb,
5980                        struct ocfs2_cached_dealloc_ctxt *ctxt)
5981 {
5982         int ret = 0, ret2;
5983         struct ocfs2_per_slot_free_list *fl;
5984
5985         if (!ctxt)
5986                 return 0;
5987
5988         while (ctxt->c_first_suballocator) {
5989                 fl = ctxt->c_first_suballocator;
5990
5991                 if (fl->f_first) {
5992                         mlog(0, "Free items: (type %u, slot %d)\n",
5993                              fl->f_inode_type, fl->f_slot);
5994                         ret2 = ocfs2_free_cached_items(osb, fl->f_inode_type,
5995                                                        fl->f_slot, fl->f_first);
5996                         if (ret2)
5997                                 mlog_errno(ret2);
5998                         if (!ret)
5999                                 ret = ret2;
6000                 }
6001
6002                 ctxt->c_first_suballocator = fl->f_next_suballocator;
6003                 kfree(fl);
6004         }
6005
6006         return ret;
6007 }
6008
6009 static struct ocfs2_per_slot_free_list *
6010 ocfs2_find_per_slot_free_list(int type,
6011                               int slot,
6012                               struct ocfs2_cached_dealloc_ctxt *ctxt)
6013 {
6014         struct ocfs2_per_slot_free_list *fl = ctxt->c_first_suballocator;
6015
6016         while (fl) {
6017                 if (fl->f_inode_type == type && fl->f_slot == slot)
6018                         return fl;
6019
6020                 fl = fl->f_next_suballocator;
6021         }
6022
6023         fl = kmalloc(sizeof(*fl), GFP_NOFS);
6024         if (fl) {
6025                 fl->f_inode_type = type;
6026                 fl->f_slot = slot;
6027                 fl->f_first = NULL;
6028                 fl->f_next_suballocator = ctxt->c_first_suballocator;
6029
6030                 ctxt->c_first_suballocator = fl;
6031         }
6032         return fl;
6033 }
6034
6035 static int ocfs2_cache_block_dealloc(struct ocfs2_cached_dealloc_ctxt *ctxt,
6036                                      int type, int slot, u64 blkno,
6037                                      unsigned int bit)
6038 {
6039         int ret;
6040         struct ocfs2_per_slot_free_list *fl;
6041         struct ocfs2_cached_block_free *item;
6042
6043         fl = ocfs2_find_per_slot_free_list(type, slot, ctxt);
6044         if (fl == NULL) {
6045                 ret = -ENOMEM;
6046                 mlog_errno(ret);
6047                 goto out;
6048         }
6049
6050         item = kmalloc(sizeof(*item), GFP_NOFS);
6051         if (item == NULL) {
6052                 ret = -ENOMEM;
6053                 mlog_errno(ret);
6054                 goto out;
6055         }
6056
6057         mlog(0, "Insert: (type %d, slot %u, bit %u, blk %llu)\n",
6058              type, slot, bit, (unsigned long long)blkno);
6059
6060         item->free_blk = blkno;
6061         item->free_bit = bit;
6062         item->free_next = fl->f_first;
6063
6064         fl->f_first = item;
6065
6066         ret = 0;
6067 out:
6068         return ret;
6069 }
6070
6071 static int ocfs2_cache_extent_block_free(struct ocfs2_cached_dealloc_ctxt *ctxt,
6072                                          struct ocfs2_extent_block *eb)
6073 {
6074         return ocfs2_cache_block_dealloc(ctxt, EXTENT_ALLOC_SYSTEM_INODE,
6075                                          le16_to_cpu(eb->h_suballoc_slot),
6076                                          le64_to_cpu(eb->h_blkno),
6077                                          le16_to_cpu(eb->h_suballoc_bit));
6078 }
6079
6080 /* This function will figure out whether the currently last extent
6081  * block will be deleted, and if it will, what the new last extent
6082  * block will be so we can update his h_next_leaf_blk field, as well
6083  * as the dinodes i_last_eb_blk */
6084 static int ocfs2_find_new_last_ext_blk(struct inode *inode,
6085                                        unsigned int clusters_to_del,
6086                                        struct ocfs2_path *path,
6087                                        struct buffer_head **new_last_eb)
6088 {
6089         int next_free, ret = 0;
6090         u32 cpos;
6091         struct ocfs2_extent_rec *rec;
6092         struct ocfs2_extent_block *eb;
6093         struct ocfs2_extent_list *el;
6094         struct buffer_head *bh = NULL;
6095
6096         *new_last_eb = NULL;
6097
6098         /* we have no tree, so of course, no last_eb. */
6099         if (!path->p_tree_depth)
6100                 goto out;
6101
6102         /* trunc to zero special case - this makes tree_depth = 0
6103          * regardless of what it is.  */
6104         if (OCFS2_I(inode)->ip_clusters == clusters_to_del)
6105                 goto out;
6106
6107         el = path_leaf_el(path);
6108         BUG_ON(!el->l_next_free_rec);
6109
6110         /*
6111          * Make sure that this extent list will actually be empty
6112          * after we clear away the data. We can shortcut out if
6113          * there's more than one non-empty extent in the
6114          * list. Otherwise, a check of the remaining extent is
6115          * necessary.
6116          */
6117         next_free = le16_to_cpu(el->l_next_free_rec);
6118         rec = NULL;
6119         if (ocfs2_is_empty_extent(&el->l_recs[0])) {
6120                 if (next_free > 2)
6121                         goto out;
6122
6123                 /* We may have a valid extent in index 1, check it. */
6124                 if (next_free == 2)
6125                         rec = &el->l_recs[1];
6126
6127                 /*
6128                  * Fall through - no more nonempty extents, so we want
6129                  * to delete this leaf.
6130                  */
6131         } else {
6132                 if (next_free > 1)
6133                         goto out;
6134
6135                 rec = &el->l_recs[0];
6136         }
6137
6138         if (rec) {
6139                 /*
6140                  * Check it we'll only be trimming off the end of this
6141                  * cluster.
6142                  */
6143                 if (le16_to_cpu(rec->e_leaf_clusters) > clusters_to_del)
6144                         goto out;
6145         }
6146
6147         ret = ocfs2_find_cpos_for_left_leaf(inode->i_sb, path, &cpos);
6148         if (ret) {
6149                 mlog_errno(ret);
6150                 goto out;
6151         }
6152
6153         ret = ocfs2_find_leaf(inode, path_root_el(path), cpos, &bh);
6154         if (ret) {
6155                 mlog_errno(ret);
6156                 goto out;
6157         }
6158
6159         eb = (struct ocfs2_extent_block *) bh->b_data;
6160         el = &eb->h_list;
6161         if (!OCFS2_IS_VALID_EXTENT_BLOCK(eb)) {
6162                 OCFS2_RO_ON_INVALID_EXTENT_BLOCK(inode->i_sb, eb);
6163                 ret = -EROFS;
6164                 goto out;
6165         }
6166
6167         *new_last_eb = bh;
6168         get_bh(*new_last_eb);
6169         mlog(0, "returning block %llu, (cpos: %u)\n",
6170              (unsigned long long)le64_to_cpu(eb->h_blkno), cpos);
6171 out:
6172         brelse(bh);
6173
6174         return ret;
6175 }
6176
6177 /*
6178  * Trim some clusters off the rightmost edge of a tree. Only called
6179  * during truncate.
6180  *
6181  * The caller needs to:
6182  *   - start journaling of each path component.
6183  *   - compute and fully set up any new last ext block
6184  */
6185 static int ocfs2_trim_tree(struct inode *inode, struct ocfs2_path *path,
6186                            handle_t *handle, struct ocfs2_truncate_context *tc,
6187                            u32 clusters_to_del, u64 *delete_start)
6188 {
6189         int ret, i, index = path->p_tree_depth;
6190         u32 new_edge = 0;
6191         u64 deleted_eb = 0;
6192         struct buffer_head *bh;
6193         struct ocfs2_extent_list *el;
6194         struct ocfs2_extent_rec *rec;
6195
6196         *delete_start = 0;
6197
6198         while (index >= 0) {
6199                 bh = path->p_node[index].bh;
6200                 el = path->p_node[index].el;
6201
6202                 mlog(0, "traveling tree (index = %d, block = %llu)\n",
6203                      index,  (unsigned long long)bh->b_blocknr);
6204
6205                 BUG_ON(le16_to_cpu(el->l_next_free_rec) == 0);
6206
6207                 if (index !=
6208                     (path->p_tree_depth - le16_to_cpu(el->l_tree_depth))) {
6209                         ocfs2_error(inode->i_sb,
6210                                     "Inode %lu has invalid ext. block %llu",
6211                                     inode->i_ino,
6212                                     (unsigned long long)bh->b_blocknr);
6213                         ret = -EROFS;
6214                         goto out;
6215                 }
6216
6217 find_tail_record:
6218                 i = le16_to_cpu(el->l_next_free_rec) - 1;
6219                 rec = &el->l_recs[i];
6220
6221                 mlog(0, "Extent list before: record %d: (%u, %u, %llu), "
6222                      "next = %u\n", i, le32_to_cpu(rec->e_cpos),
6223                      ocfs2_rec_clusters(el, rec),
6224                      (unsigned long long)le64_to_cpu(rec->e_blkno),
6225                      le16_to_cpu(el->l_next_free_rec));
6226
6227                 BUG_ON(ocfs2_rec_clusters(el, rec) < clusters_to_del);
6228
6229                 if (le16_to_cpu(el->l_tree_depth) == 0) {
6230                         /*
6231                          * If the leaf block contains a single empty
6232                          * extent and no records, we can just remove
6233                          * the block.
6234                          */
6235                         if (i == 0 && ocfs2_is_empty_extent(rec)) {
6236                                 memset(rec, 0,
6237                                        sizeof(struct ocfs2_extent_rec));
6238                                 el->l_next_free_rec = cpu_to_le16(0);
6239
6240                                 goto delete;
6241                         }
6242
6243                         /*
6244                          * Remove any empty extents by shifting things
6245                          * left. That should make life much easier on
6246                          * the code below. This condition is rare
6247                          * enough that we shouldn't see a performance
6248                          * hit.
6249                          */
6250                         if (ocfs2_is_empty_extent(&el->l_recs[0])) {
6251                                 le16_add_cpu(&el->l_next_free_rec, -1);
6252
6253                                 for(i = 0;
6254                                     i < le16_to_cpu(el->l_next_free_rec); i++)
6255                                         el->l_recs[i] = el->l_recs[i + 1];
6256
6257                                 memset(&el->l_recs[i], 0,
6258                                        sizeof(struct ocfs2_extent_rec));
6259
6260                                 /*
6261                                  * We've modified our extent list. The
6262                                  * simplest way to handle this change
6263                                  * is to being the search from the
6264                                  * start again.
6265                                  */
6266                                 goto find_tail_record;
6267                         }
6268
6269                         le16_add_cpu(&rec->e_leaf_clusters, -clusters_to_del);
6270
6271                         /*
6272                          * We'll use "new_edge" on our way back up the
6273                          * tree to know what our rightmost cpos is.
6274                          */
6275                         new_edge = le16_to_cpu(rec->e_leaf_clusters);
6276                         new_edge += le32_to_cpu(rec->e_cpos);
6277
6278                         /*
6279                          * The caller will use this to delete data blocks.
6280                          */
6281                         *delete_start = le64_to_cpu(rec->e_blkno)
6282                                 + ocfs2_clusters_to_blocks(inode->i_sb,
6283                                         le16_to_cpu(rec->e_leaf_clusters));
6284
6285                         /*
6286                          * If it's now empty, remove this record.
6287                          */
6288                         if (le16_to_cpu(rec->e_leaf_clusters) == 0) {
6289                                 memset(rec, 0,
6290                                        sizeof(struct ocfs2_extent_rec));
6291                                 le16_add_cpu(&el->l_next_free_rec, -1);
6292                         }
6293                 } else {
6294                         if (le64_to_cpu(rec->e_blkno) == deleted_eb) {
6295                                 memset(rec, 0,
6296                                        sizeof(struct ocfs2_extent_rec));
6297                                 le16_add_cpu(&el->l_next_free_rec, -1);
6298
6299                                 goto delete;
6300                         }
6301
6302                         /* Can this actually happen? */
6303                         if (le16_to_cpu(el->l_next_free_rec) == 0)
6304                                 goto delete;
6305
6306                         /*
6307                          * We never actually deleted any clusters
6308                          * because our leaf was empty. There's no
6309                          * reason to adjust the rightmost edge then.
6310                          */
6311                         if (new_edge == 0)
6312                                 goto delete;
6313
6314                         rec->e_int_clusters = cpu_to_le32(new_edge);
6315                         le32_add_cpu(&rec->e_int_clusters,
6316                                      -le32_to_cpu(rec->e_cpos));
6317
6318                          /*
6319                           * A deleted child record should have been
6320                           * caught above.
6321                           */
6322                          BUG_ON(le32_to_cpu(rec->e_int_clusters) == 0);
6323                 }
6324
6325 delete:
6326                 ret = ocfs2_journal_dirty(handle, bh);
6327                 if (ret) {
6328                         mlog_errno(ret);
6329                         goto out;
6330                 }
6331
6332                 mlog(0, "extent list container %llu, after: record %d: "
6333                      "(%u, %u, %llu), next = %u.\n",
6334                      (unsigned long long)bh->b_blocknr, i,
6335                      le32_to_cpu(rec->e_cpos), ocfs2_rec_clusters(el, rec),
6336                      (unsigned long long)le64_to_cpu(rec->e_blkno),
6337                      le16_to_cpu(el->l_next_free_rec));
6338
6339                 /*
6340                  * We must be careful to only attempt delete of an
6341                  * extent block (and not the root inode block).
6342                  */
6343                 if (index > 0 && le16_to_cpu(el->l_next_free_rec) == 0) {
6344                         struct ocfs2_extent_block *eb =
6345                                 (struct ocfs2_extent_block *)bh->b_data;
6346
6347                         /*
6348                          * Save this for use when processing the
6349                          * parent block.
6350                          */
6351                         deleted_eb = le64_to_cpu(eb->h_blkno);
6352
6353                         mlog(0, "deleting this extent block.\n");
6354
6355                         ocfs2_remove_from_cache(inode, bh);
6356
6357                         BUG_ON(ocfs2_rec_clusters(el, &el->l_recs[0]));
6358                         BUG_ON(le32_to_cpu(el->l_recs[0].e_cpos));
6359                         BUG_ON(le64_to_cpu(el->l_recs[0].e_blkno));
6360
6361                         ret = ocfs2_cache_extent_block_free(&tc->tc_dealloc, eb);
6362                         /* An error here is not fatal. */
6363                         if (ret < 0)
6364                                 mlog_errno(ret);
6365                 } else {
6366                         deleted_eb = 0;
6367                 }
6368
6369                 index--;
6370         }
6371
6372         ret = 0;
6373 out:
6374         return ret;
6375 }
6376
6377 static int ocfs2_do_truncate(struct ocfs2_super *osb,
6378                              unsigned int clusters_to_del,
6379                              struct inode *inode,
6380                              struct buffer_head *fe_bh,
6381                              handle_t *handle,
6382                              struct ocfs2_truncate_context *tc,
6383                              struct ocfs2_path *path)
6384 {
6385         int status;
6386         struct ocfs2_dinode *fe;
6387         struct ocfs2_extent_block *last_eb = NULL;
6388         struct ocfs2_extent_list *el;
6389         struct buffer_head *last_eb_bh = NULL;
6390         u64 delete_blk = 0;
6391
6392         fe = (struct ocfs2_dinode *) fe_bh->b_data;
6393
6394         status = ocfs2_find_new_last_ext_blk(inode, clusters_to_del,
6395                                              path, &last_eb_bh);
6396         if (status < 0) {
6397                 mlog_errno(status);
6398                 goto bail;
6399         }
6400
6401         /*
6402          * Each component will be touched, so we might as well journal
6403          * here to avoid having to handle errors later.
6404          */
6405         status = ocfs2_journal_access_path(inode, handle, path);
6406         if (status < 0) {
6407                 mlog_errno(status);
6408                 goto bail;
6409         }
6410
6411         if (last_eb_bh) {
6412                 status = ocfs2_journal_access(handle, inode, last_eb_bh,
6413                                               OCFS2_JOURNAL_ACCESS_WRITE);
6414                 if (status < 0) {
6415                         mlog_errno(status);
6416                         goto bail;
6417                 }
6418
6419                 last_eb = (struct ocfs2_extent_block *) last_eb_bh->b_data;
6420         }
6421
6422         el = &(fe->id2.i_list);
6423
6424         /*
6425          * Lower levels depend on this never happening, but it's best
6426          * to check it up here before changing the tree.
6427          */
6428         if (el->l_tree_depth && el->l_recs[0].e_int_clusters == 0) {
6429                 ocfs2_error(inode->i_sb,
6430                             "Inode %lu has an empty extent record, depth %u\n",
6431                             inode->i_ino, le16_to_cpu(el->l_tree_depth));
6432                 status = -EROFS;
6433                 goto bail;
6434         }
6435
6436         spin_lock(&OCFS2_I(inode)->ip_lock);
6437         OCFS2_I(inode)->ip_clusters = le32_to_cpu(fe->i_clusters) -
6438                                       clusters_to_del;
6439         spin_unlock(&OCFS2_I(inode)->ip_lock);
6440         le32_add_cpu(&fe->i_clusters, -clusters_to_del);
6441         inode->i_blocks = ocfs2_inode_sector_count(inode);
6442
6443         status = ocfs2_trim_tree(inode, path, handle, tc,
6444                                  clusters_to_del, &delete_blk);
6445         if (status) {
6446                 mlog_errno(status);
6447                 goto bail;
6448         }
6449
6450         if (le32_to_cpu(fe->i_clusters) == 0) {
6451                 /* trunc to zero is a special case. */
6452                 el->l_tree_depth = 0;
6453                 fe->i_last_eb_blk = 0;
6454         } else if (last_eb)
6455                 fe->i_last_eb_blk = last_eb->h_blkno;
6456
6457         status = ocfs2_journal_dirty(handle, fe_bh);
6458         if (status < 0) {
6459                 mlog_errno(status);
6460                 goto bail;
6461         }
6462
6463         if (last_eb) {
6464                 /* If there will be a new last extent block, then by
6465                  * definition, there cannot be any leaves to the right of
6466                  * him. */
6467                 last_eb->h_next_leaf_blk = 0;
6468                 status = ocfs2_journal_dirty(handle, last_eb_bh);
6469                 if (status < 0) {
6470                         mlog_errno(status);
6471                         goto bail;
6472                 }
6473         }
6474
6475         if (delete_blk) {
6476                 status = ocfs2_truncate_log_append(osb, handle, delete_blk,
6477                                                    clusters_to_del);
6478                 if (status < 0) {
6479                         mlog_errno(status);
6480                         goto bail;
6481                 }
6482         }
6483         status = 0;
6484 bail:
6485
6486         mlog_exit(status);
6487         return status;
6488 }
6489
6490 static int ocfs2_writeback_zero_func(handle_t *handle, struct buffer_head *bh)
6491 {
6492         set_buffer_uptodate(bh);
6493         mark_buffer_dirty(bh);
6494         return 0;
6495 }
6496
6497 static int ocfs2_ordered_zero_func(handle_t *handle, struct buffer_head *bh)
6498 {
6499         set_buffer_uptodate(bh);
6500         mark_buffer_dirty(bh);
6501         return ocfs2_journal_dirty_data(handle, bh);
6502 }
6503
6504 static void ocfs2_map_and_dirty_page(struct inode *inode, handle_t *handle,
6505                                      unsigned int from, unsigned int to,
6506                                      struct page *page, int zero, u64 *phys)
6507 {
6508         int ret, partial = 0;
6509
6510         ret = ocfs2_map_page_blocks(page, phys, inode, from, to, 0);
6511         if (ret)
6512                 mlog_errno(ret);
6513
6514         if (zero)
6515                 zero_user_segment(page, from, to);
6516
6517         /*
6518          * Need to set the buffers we zero'd into uptodate
6519          * here if they aren't - ocfs2_map_page_blocks()
6520          * might've skipped some
6521          */
6522         if (ocfs2_should_order_data(inode)) {
6523                 ret = walk_page_buffers(handle,
6524                                         page_buffers(page),
6525                                         from, to, &partial,
6526                                         ocfs2_ordered_zero_func);
6527                 if (ret < 0)
6528                         mlog_errno(ret);
6529         } else {
6530                 ret = walk_page_buffers(handle, page_buffers(page),
6531                                         from, to, &partial,
6532                                         ocfs2_writeback_zero_func);
6533                 if (ret < 0)
6534                         mlog_errno(ret);
6535         }
6536
6537         if (!partial)
6538                 SetPageUptodate(page);
6539
6540         flush_dcache_page(page);
6541 }
6542
6543 static void ocfs2_zero_cluster_pages(struct inode *inode, loff_t start,
6544                                      loff_t end, struct page **pages,
6545                                      int numpages, u64 phys, handle_t *handle)
6546 {
6547         int i;
6548         struct page *page;
6549         unsigned int from, to = PAGE_CACHE_SIZE;
6550         struct super_block *sb = inode->i_sb;
6551
6552         BUG_ON(!ocfs2_sparse_alloc(OCFS2_SB(sb)));
6553
6554         if (numpages == 0)
6555                 goto out;
6556
6557         to = PAGE_CACHE_SIZE;
6558         for(i = 0; i < numpages; i++) {
6559                 page = pages[i];
6560
6561                 from = start & (PAGE_CACHE_SIZE - 1);
6562                 if ((end >> PAGE_CACHE_SHIFT) == page->index)
6563                         to = end & (PAGE_CACHE_SIZE - 1);
6564
6565                 BUG_ON(from > PAGE_CACHE_SIZE);
6566                 BUG_ON(to > PAGE_CACHE_SIZE);
6567
6568                 ocfs2_map_and_dirty_page(inode, handle, from, to, page, 1,
6569                                          &phys);
6570
6571                 start = (page->index + 1) << PAGE_CACHE_SHIFT;
6572         }
6573 out:
6574         if (pages)
6575                 ocfs2_unlock_and_free_pages(pages, numpages);
6576 }
6577
6578 static int ocfs2_grab_eof_pages(struct inode *inode, loff_t start, loff_t end,
6579                                 struct page **pages, int *num)
6580 {
6581         int numpages, ret = 0;
6582         struct super_block *sb = inode->i_sb;
6583         struct address_space *mapping = inode->i_mapping;
6584         unsigned long index;
6585         loff_t last_page_bytes;
6586
6587         BUG_ON(start > end);
6588
6589         BUG_ON(start >> OCFS2_SB(sb)->s_clustersize_bits !=
6590                (end - 1) >> OCFS2_SB(sb)->s_clustersize_bits);
6591
6592         numpages = 0;
6593         last_page_bytes = PAGE_ALIGN(end);
6594         index = start >> PAGE_CACHE_SHIFT;
6595         do {
6596                 pages[numpages] = grab_cache_page(mapping, index);
6597                 if (!pages[numpages]) {
6598                         ret = -ENOMEM;
6599                         mlog_errno(ret);
6600                         goto out;
6601                 }
6602
6603                 numpages++;
6604                 index++;
6605         } while (index < (last_page_bytes >> PAGE_CACHE_SHIFT));
6606
6607 out:
6608         if (ret != 0) {
6609                 if (pages)
6610                         ocfs2_unlock_and_free_pages(pages, numpages);
6611                 numpages = 0;
6612         }
6613
6614         *num = numpages;
6615
6616         return ret;
6617 }
6618
6619 /*
6620  * Zero the area past i_size but still within an allocated
6621  * cluster. This avoids exposing nonzero data on subsequent file
6622  * extends.
6623  *
6624  * We need to call this before i_size is updated on the inode because
6625  * otherwise block_write_full_page() will skip writeout of pages past
6626  * i_size. The new_i_size parameter is passed for this reason.
6627  */
6628 int ocfs2_zero_range_for_truncate(struct inode *inode, handle_t *handle,
6629                                   u64 range_start, u64 range_end)
6630 {
6631         int ret = 0, numpages;
6632         struct page **pages = NULL;
6633         u64 phys;
6634         unsigned int ext_flags;
6635         struct super_block *sb = inode->i_sb;
6636
6637         /*
6638          * File systems which don't support sparse files zero on every
6639          * extend.
6640          */
6641         if (!ocfs2_sparse_alloc(OCFS2_SB(sb)))
6642                 return 0;
6643
6644         pages = kcalloc(ocfs2_pages_per_cluster(sb),
6645                         sizeof(struct page *), GFP_NOFS);
6646         if (pages == NULL) {
6647                 ret = -ENOMEM;
6648                 mlog_errno(ret);
6649                 goto out;
6650         }
6651
6652         if (range_start == range_end)
6653                 goto out;
6654
6655         ret = ocfs2_extent_map_get_blocks(inode,
6656                                           range_start >> sb->s_blocksize_bits,
6657                                           &phys, NULL, &ext_flags);
6658         if (ret) {
6659                 mlog_errno(ret);
6660                 goto out;
6661         }
6662
6663         /*
6664          * Tail is a hole, or is marked unwritten. In either case, we
6665          * can count on read and write to return/push zero's.
6666          */
6667         if (phys == 0 || ext_flags & OCFS2_EXT_UNWRITTEN)
6668                 goto out;
6669
6670         ret = ocfs2_grab_eof_pages(inode, range_start, range_end, pages,
6671                                    &numpages);
6672         if (ret) {
6673                 mlog_errno(ret);
6674                 goto out;
6675         }
6676
6677         ocfs2_zero_cluster_pages(inode, range_start, range_end, pages,
6678                                  numpages, phys, handle);
6679
6680         /*
6681          * Initiate writeout of the pages we zero'd here. We don't
6682          * wait on them - the truncate_inode_pages() call later will
6683          * do that for us.
6684          */
6685         ret = do_sync_mapping_range(inode->i_mapping, range_start,
6686                                     range_end - 1, SYNC_FILE_RANGE_WRITE);
6687         if (ret)
6688                 mlog_errno(ret);
6689
6690 out:
6691         if (pages)
6692                 kfree(pages);
6693
6694         return ret;
6695 }
6696
6697 static void ocfs2_zero_dinode_id2_with_xattr(struct inode *inode,
6698                                              struct ocfs2_dinode *di)
6699 {
6700         unsigned int blocksize = 1 << inode->i_sb->s_blocksize_bits;
6701         unsigned int xattrsize = le16_to_cpu(di->i_xattr_inline_size);
6702
6703         if (le16_to_cpu(di->i_dyn_features) & OCFS2_INLINE_XATTR_FL)
6704                 memset(&di->id2, 0, blocksize -
6705                                     offsetof(struct ocfs2_dinode, id2) -
6706                                     xattrsize);
6707         else
6708                 memset(&di->id2, 0, blocksize -
6709                                     offsetof(struct ocfs2_dinode, id2));
6710 }
6711
6712 void ocfs2_dinode_new_extent_list(struct inode *inode,
6713                                   struct ocfs2_dinode *di)
6714 {
6715         ocfs2_zero_dinode_id2_with_xattr(inode, di);
6716         di->id2.i_list.l_tree_depth = 0;
6717         di->id2.i_list.l_next_free_rec = 0;
6718         di->id2.i_list.l_count = cpu_to_le16(
6719                 ocfs2_extent_recs_per_inode_with_xattr(inode->i_sb, di));
6720 }
6721
6722 void ocfs2_set_inode_data_inline(struct inode *inode, struct ocfs2_dinode *di)
6723 {
6724         struct ocfs2_inode_info *oi = OCFS2_I(inode);
6725         struct ocfs2_inline_data *idata = &di->id2.i_data;
6726
6727         spin_lock(&oi->ip_lock);
6728         oi->ip_dyn_features |= OCFS2_INLINE_DATA_FL;
6729         di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
6730         spin_unlock(&oi->ip_lock);
6731
6732         /*
6733          * We clear the entire i_data structure here so that all
6734          * fields can be properly initialized.
6735          */
6736         ocfs2_zero_dinode_id2_with_xattr(inode, di);
6737
6738         idata->id_count = cpu_to_le16(
6739                         ocfs2_max_inline_data_with_xattr(inode->i_sb, di));
6740 }
6741
6742 int ocfs2_convert_inline_data_to_extents(struct inode *inode,
6743                                          struct buffer_head *di_bh)
6744 {
6745         int ret, i, has_data, num_pages = 0;
6746         handle_t *handle;
6747         u64 uninitialized_var(block);
6748         struct ocfs2_inode_info *oi = OCFS2_I(inode);
6749         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
6750         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
6751         struct ocfs2_alloc_context *data_ac = NULL;
6752         struct page **pages = NULL;
6753         loff_t end = osb->s_clustersize;
6754
6755         has_data = i_size_read(inode) ? 1 : 0;
6756
6757         if (has_data) {
6758                 pages = kcalloc(ocfs2_pages_per_cluster(osb->sb),
6759                                 sizeof(struct page *), GFP_NOFS);
6760                 if (pages == NULL) {
6761                         ret = -ENOMEM;
6762                         mlog_errno(ret);
6763                         goto out;
6764                 }
6765
6766                 ret = ocfs2_reserve_clusters(osb, 1, &data_ac);
6767                 if (ret) {
6768                         mlog_errno(ret);
6769                         goto out;
6770                 }
6771         }
6772
6773         handle = ocfs2_start_trans(osb, OCFS2_INLINE_TO_EXTENTS_CREDITS);
6774         if (IS_ERR(handle)) {
6775                 ret = PTR_ERR(handle);
6776                 mlog_errno(ret);
6777                 goto out_unlock;
6778         }
6779
6780         ret = ocfs2_journal_access(handle, inode, di_bh,
6781                                    OCFS2_JOURNAL_ACCESS_WRITE);
6782         if (ret) {
6783                 mlog_errno(ret);
6784                 goto out_commit;
6785         }
6786
6787         if (has_data) {
6788                 u32 bit_off, num;
6789                 unsigned int page_end;
6790                 u64 phys;
6791
6792                 ret = ocfs2_claim_clusters(osb, handle, data_ac, 1, &bit_off,
6793                                            &num);
6794                 if (ret) {
6795                         mlog_errno(ret);
6796                         goto out_commit;
6797                 }
6798
6799                 /*
6800                  * Save two copies, one for insert, and one that can
6801                  * be changed by ocfs2_map_and_dirty_page() below.
6802                  */
6803                 block = phys = ocfs2_clusters_to_blocks(inode->i_sb, bit_off);
6804
6805                 /*
6806                  * Non sparse file systems zero on extend, so no need
6807                  * to do that now.
6808                  */
6809                 if (!ocfs2_sparse_alloc(osb) &&
6810                     PAGE_CACHE_SIZE < osb->s_clustersize)
6811                         end = PAGE_CACHE_SIZE;
6812
6813                 ret = ocfs2_grab_eof_pages(inode, 0, end, pages, &num_pages);
6814                 if (ret) {
6815                         mlog_errno(ret);
6816                         goto out_commit;
6817                 }
6818
6819                 /*
6820                  * This should populate the 1st page for us and mark
6821                  * it up to date.
6822                  */
6823                 ret = ocfs2_read_inline_data(inode, pages[0], di_bh);
6824                 if (ret) {
6825                         mlog_errno(ret);
6826                         goto out_commit;
6827                 }
6828
6829                 page_end = PAGE_CACHE_SIZE;
6830                 if (PAGE_CACHE_SIZE > osb->s_clustersize)
6831                         page_end = osb->s_clustersize;
6832
6833                 for (i = 0; i < num_pages; i++)
6834                         ocfs2_map_and_dirty_page(inode, handle, 0, page_end,
6835                                                  pages[i], i > 0, &phys);
6836         }
6837
6838         spin_lock(&oi->ip_lock);
6839         oi->ip_dyn_features &= ~OCFS2_INLINE_DATA_FL;
6840         di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
6841         spin_unlock(&oi->ip_lock);
6842
6843         ocfs2_dinode_new_extent_list(inode, di);
6844
6845         ocfs2_journal_dirty(handle, di_bh);
6846
6847         if (has_data) {
6848                 /*
6849                  * An error at this point should be extremely rare. If
6850                  * this proves to be false, we could always re-build
6851                  * the in-inode data from our pages.
6852                  */
6853                 ret = ocfs2_dinode_insert_extent(osb, handle, inode, di_bh,
6854                                                  0, block, 1, 0, NULL);
6855                 if (ret) {
6856                         mlog_errno(ret);
6857                         goto out_commit;
6858                 }
6859
6860                 inode->i_blocks = ocfs2_inode_sector_count(inode);
6861         }
6862
6863 out_commit:
6864         ocfs2_commit_trans(osb, handle);
6865
6866 out_unlock:
6867         if (data_ac)
6868                 ocfs2_free_alloc_context(data_ac);
6869
6870 out:
6871         if (pages) {
6872                 ocfs2_unlock_and_free_pages(pages, num_pages);
6873                 kfree(pages);
6874         }
6875
6876         return ret;
6877 }
6878
6879 /*
6880  * It is expected, that by the time you call this function,
6881  * inode->i_size and fe->i_size have been adjusted.
6882  *
6883  * WARNING: This will kfree the truncate context
6884  */
6885 int ocfs2_commit_truncate(struct ocfs2_super *osb,
6886                           struct inode *inode,
6887                           struct buffer_head *fe_bh,
6888                           struct ocfs2_truncate_context *tc)
6889 {
6890         int status, i, credits, tl_sem = 0;
6891         u32 clusters_to_del, new_highest_cpos, range;
6892         struct ocfs2_extent_list *el;
6893         handle_t *handle = NULL;
6894         struct inode *tl_inode = osb->osb_tl_inode;
6895         struct ocfs2_path *path = NULL;
6896         struct ocfs2_dinode *di = (struct ocfs2_dinode *)fe_bh->b_data;
6897
6898         mlog_entry_void();
6899
6900         new_highest_cpos = ocfs2_clusters_for_bytes(osb->sb,
6901                                                      i_size_read(inode));
6902
6903         path = ocfs2_new_path(fe_bh, &di->id2.i_list);
6904         if (!path) {
6905                 status = -ENOMEM;
6906                 mlog_errno(status);
6907                 goto bail;
6908         }
6909
6910         ocfs2_extent_map_trunc(inode, new_highest_cpos);
6911
6912 start:
6913         /*
6914          * Check that we still have allocation to delete.
6915          */
6916         if (OCFS2_I(inode)->ip_clusters == 0) {
6917                 status = 0;
6918                 goto bail;
6919         }
6920
6921         /*
6922          * Truncate always works against the rightmost tree branch.
6923          */
6924         status = ocfs2_find_path(inode, path, UINT_MAX);
6925         if (status) {
6926                 mlog_errno(status);
6927                 goto bail;
6928         }
6929
6930         mlog(0, "inode->ip_clusters = %u, tree_depth = %u\n",
6931              OCFS2_I(inode)->ip_clusters, path->p_tree_depth);
6932
6933         /*
6934          * By now, el will point to the extent list on the bottom most
6935          * portion of this tree. Only the tail record is considered in
6936          * each pass.
6937          *
6938          * We handle the following cases, in order:
6939          * - empty extent: delete the remaining branch
6940          * - remove the entire record
6941          * - remove a partial record
6942          * - no record needs to be removed (truncate has completed)
6943          */
6944         el = path_leaf_el(path);
6945         if (le16_to_cpu(el->l_next_free_rec) == 0) {
6946                 ocfs2_error(inode->i_sb,
6947                             "Inode %llu has empty extent block at %llu\n",
6948                             (unsigned long long)OCFS2_I(inode)->ip_blkno,
6949                             (unsigned long long)path_leaf_bh(path)->b_blocknr);
6950                 status = -EROFS;
6951                 goto bail;
6952         }
6953
6954         i = le16_to_cpu(el->l_next_free_rec) - 1;
6955         range = le32_to_cpu(el->l_recs[i].e_cpos) +
6956                 ocfs2_rec_clusters(el, &el->l_recs[i]);
6957         if (i == 0 && ocfs2_is_empty_extent(&el->l_recs[i])) {
6958                 clusters_to_del = 0;
6959         } else if (le32_to_cpu(el->l_recs[i].e_cpos) >= new_highest_cpos) {
6960                 clusters_to_del = ocfs2_rec_clusters(el, &el->l_recs[i]);
6961         } else if (range > new_highest_cpos) {
6962                 clusters_to_del = (ocfs2_rec_clusters(el, &el->l_recs[i]) +
6963                                    le32_to_cpu(el->l_recs[i].e_cpos)) -
6964                                   new_highest_cpos;
6965         } else {
6966                 status = 0;
6967                 goto bail;
6968         }
6969
6970         mlog(0, "clusters_to_del = %u in this pass, tail blk=%llu\n",
6971              clusters_to_del, (unsigned long long)path_leaf_bh(path)->b_blocknr);
6972
6973         mutex_lock(&tl_inode->i_mutex);
6974         tl_sem = 1;
6975         /* ocfs2_truncate_log_needs_flush guarantees us at least one
6976          * record is free for use. If there isn't any, we flush to get
6977          * an empty truncate log.  */
6978         if (ocfs2_truncate_log_needs_flush(osb)) {
6979                 status = __ocfs2_flush_truncate_log(osb);
6980                 if (status < 0) {
6981                         mlog_errno(status);
6982                         goto bail;
6983                 }
6984         }
6985
6986         credits = ocfs2_calc_tree_trunc_credits(osb->sb, clusters_to_del,
6987                                                 (struct ocfs2_dinode *)fe_bh->b_data,
6988                                                 el);
6989         handle = ocfs2_start_trans(osb, credits);
6990         if (IS_ERR(handle)) {
6991                 status = PTR_ERR(handle);
6992                 handle = NULL;
6993                 mlog_errno(status);
6994                 goto bail;
6995         }
6996
6997         status = ocfs2_do_truncate(osb, clusters_to_del, inode, fe_bh, handle,
6998                                    tc, path);
6999         if (status < 0) {
7000                 mlog_errno(status);
7001                 goto bail;
7002         }
7003
7004         mutex_unlock(&tl_inode->i_mutex);
7005         tl_sem = 0;
7006
7007         ocfs2_commit_trans(osb, handle);
7008         handle = NULL;
7009
7010         ocfs2_reinit_path(path, 1);
7011
7012         /*
7013          * The check above will catch the case where we've truncated
7014          * away all allocation.
7015          */
7016         goto start;
7017
7018 bail:
7019
7020         ocfs2_schedule_truncate_log_flush(osb, 1);
7021
7022         if (tl_sem)
7023                 mutex_unlock(&tl_inode->i_mutex);
7024
7025         if (handle)
7026                 ocfs2_commit_trans(osb, handle);
7027
7028         ocfs2_run_deallocs(osb, &tc->tc_dealloc);
7029
7030         ocfs2_free_path(path);
7031
7032         /* This will drop the ext_alloc cluster lock for us */
7033         ocfs2_free_truncate_context(tc);
7034
7035         mlog_exit(status);
7036         return status;
7037 }
7038
7039 /*
7040  * Expects the inode to already be locked.
7041  */
7042 int ocfs2_prepare_truncate(struct ocfs2_super *osb,
7043                            struct inode *inode,
7044                            struct buffer_head *fe_bh,
7045                            struct ocfs2_truncate_context **tc)
7046 {
7047         int status;
7048         unsigned int new_i_clusters;
7049         struct ocfs2_dinode *fe;
7050         struct ocfs2_extent_block *eb;
7051         struct buffer_head *last_eb_bh = NULL;
7052
7053         mlog_entry_void();
7054
7055         *tc = NULL;
7056
7057         new_i_clusters = ocfs2_clusters_for_bytes(osb->sb,
7058                                                   i_size_read(inode));
7059         fe = (struct ocfs2_dinode *) fe_bh->b_data;
7060
7061         mlog(0, "fe->i_clusters = %u, new_i_clusters = %u, fe->i_size ="
7062              "%llu\n", le32_to_cpu(fe->i_clusters), new_i_clusters,
7063              (unsigned long long)le64_to_cpu(fe->i_size));
7064
7065         *tc = kzalloc(sizeof(struct ocfs2_truncate_context), GFP_KERNEL);
7066         if (!(*tc)) {
7067                 status = -ENOMEM;
7068                 mlog_errno(status);
7069                 goto bail;
7070         }
7071         ocfs2_init_dealloc_ctxt(&(*tc)->tc_dealloc);
7072
7073         if (fe->id2.i_list.l_tree_depth) {
7074                 status = ocfs2_read_block(osb, le64_to_cpu(fe->i_last_eb_blk),
7075                                           &last_eb_bh, OCFS2_BH_CACHED, inode);
7076                 if (status < 0) {
7077                         mlog_errno(status);
7078                         goto bail;
7079                 }
7080                 eb = (struct ocfs2_extent_block *) last_eb_bh->b_data;
7081                 if (!OCFS2_IS_VALID_EXTENT_BLOCK(eb)) {
7082                         OCFS2_RO_ON_INVALID_EXTENT_BLOCK(inode->i_sb, eb);
7083
7084                         brelse(last_eb_bh);
7085                         status = -EIO;
7086                         goto bail;
7087                 }
7088         }
7089
7090         (*tc)->tc_last_eb_bh = last_eb_bh;
7091
7092         status = 0;
7093 bail:
7094         if (status < 0) {
7095                 if (*tc)
7096                         ocfs2_free_truncate_context(*tc);
7097                 *tc = NULL;
7098         }
7099         mlog_exit_void();
7100         return status;
7101 }
7102
7103 /*
7104  * 'start' is inclusive, 'end' is not.
7105  */
7106 int ocfs2_truncate_inline(struct inode *inode, struct buffer_head *di_bh,
7107                           unsigned int start, unsigned int end, int trunc)
7108 {
7109         int ret;
7110         unsigned int numbytes;
7111         handle_t *handle;
7112         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
7113         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
7114         struct ocfs2_inline_data *idata = &di->id2.i_data;
7115
7116         if (end > i_size_read(inode))
7117                 end = i_size_read(inode);
7118
7119         BUG_ON(start >= end);
7120
7121         if (!(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) ||
7122             !(le16_to_cpu(di->i_dyn_features) & OCFS2_INLINE_DATA_FL) ||
7123             !ocfs2_supports_inline_data(osb)) {
7124                 ocfs2_error(inode->i_sb,
7125                             "Inline data flags for inode %llu don't agree! "
7126                             "Disk: 0x%x, Memory: 0x%x, Superblock: 0x%x\n",
7127                             (unsigned long long)OCFS2_I(inode)->ip_blkno,
7128                             le16_to_cpu(di->i_dyn_features),
7129                             OCFS2_I(inode)->ip_dyn_features,
7130                             osb->s_feature_incompat);
7131                 ret = -EROFS;
7132                 goto out;
7133         }
7134
7135         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
7136         if (IS_ERR(handle)) {
7137                 ret = PTR_ERR(handle);
7138                 mlog_errno(ret);
7139                 goto out;
7140         }
7141
7142         ret = ocfs2_journal_access(handle, inode, di_bh,
7143                                    OCFS2_JOURNAL_ACCESS_WRITE);
7144         if (ret) {
7145                 mlog_errno(ret);
7146                 goto out_commit;
7147         }
7148
7149         numbytes = end - start;
7150         memset(idata->id_data + start, 0, numbytes);
7151
7152         /*
7153          * No need to worry about the data page here - it's been
7154          * truncated already and inline data doesn't need it for
7155          * pushing zero's to disk, so we'll let readpage pick it up
7156          * later.
7157          */
7158         if (trunc) {
7159                 i_size_write(inode, start);
7160                 di->i_size = cpu_to_le64(start);
7161         }
7162
7163         inode->i_blocks = ocfs2_inode_sector_count(inode);
7164         inode->i_ctime = inode->i_mtime = CURRENT_TIME;
7165
7166         di->i_ctime = di->i_mtime = cpu_to_le64(inode->i_ctime.tv_sec);
7167         di->i_ctime_nsec = di->i_mtime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
7168
7169         ocfs2_journal_dirty(handle, di_bh);
7170
7171 out_commit:
7172         ocfs2_commit_trans(osb, handle);
7173
7174 out:
7175         return ret;
7176 }
7177
7178 static void ocfs2_free_truncate_context(struct ocfs2_truncate_context *tc)
7179 {
7180         /*
7181          * The caller is responsible for completing deallocation
7182          * before freeing the context.
7183          */
7184         if (tc->tc_dealloc.c_first_suballocator != NULL)
7185                 mlog(ML_NOTICE,
7186                      "Truncate completion has non-empty dealloc context\n");
7187
7188         if (tc->tc_last_eb_bh)
7189                 brelse(tc->tc_last_eb_bh);
7190
7191         kfree(tc);
7192 }