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