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