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