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