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