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