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