ocfs2: fstrim: Fix start offset of first cluster group during fstrim
[sfrench/cifs-2.6.git] / 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 #include <linux/blkdev.h>
33 #include <linux/sched/signal.h>
34
35 #include <cluster/masklog.h>
36
37 #include "ocfs2.h"
38
39 #include "alloc.h"
40 #include "aops.h"
41 #include "blockcheck.h"
42 #include "dlmglue.h"
43 #include "extent_map.h"
44 #include "inode.h"
45 #include "journal.h"
46 #include "localalloc.h"
47 #include "suballoc.h"
48 #include "sysfile.h"
49 #include "file.h"
50 #include "super.h"
51 #include "uptodate.h"
52 #include "xattr.h"
53 #include "refcounttree.h"
54 #include "ocfs2_trace.h"
55
56 #include "buffer_head_io.h"
57
58 enum ocfs2_contig_type {
59         CONTIG_NONE = 0,
60         CONTIG_LEFT,
61         CONTIG_RIGHT,
62         CONTIG_LEFTRIGHT,
63 };
64
65 static enum ocfs2_contig_type
66         ocfs2_extent_rec_contig(struct super_block *sb,
67                                 struct ocfs2_extent_rec *ext,
68                                 struct ocfs2_extent_rec *insert_rec);
69 /*
70  * Operations for a specific extent tree type.
71  *
72  * To implement an on-disk btree (extent tree) type in ocfs2, add
73  * an ocfs2_extent_tree_operations structure and the matching
74  * ocfs2_init_<thingy>_extent_tree() function.  That's pretty much it
75  * for the allocation portion of the extent tree.
76  */
77 struct ocfs2_extent_tree_operations {
78         /*
79          * last_eb_blk is the block number of the right most leaf extent
80          * block.  Most on-disk structures containing an extent tree store
81          * this value for fast access.  The ->eo_set_last_eb_blk() and
82          * ->eo_get_last_eb_blk() operations access this value.  They are
83          *  both required.
84          */
85         void (*eo_set_last_eb_blk)(struct ocfs2_extent_tree *et,
86                                    u64 blkno);
87         u64 (*eo_get_last_eb_blk)(struct ocfs2_extent_tree *et);
88
89         /*
90          * The on-disk structure usually keeps track of how many total
91          * clusters are stored in this extent tree.  This function updates
92          * that value.  new_clusters is the delta, and must be
93          * added to the total.  Required.
94          */
95         void (*eo_update_clusters)(struct ocfs2_extent_tree *et,
96                                    u32 new_clusters);
97
98         /*
99          * If this extent tree is supported by an extent map, insert
100          * a record into the map.
101          */
102         void (*eo_extent_map_insert)(struct ocfs2_extent_tree *et,
103                                      struct ocfs2_extent_rec *rec);
104
105         /*
106          * If this extent tree is supported by an extent map, truncate the
107          * map to clusters,
108          */
109         void (*eo_extent_map_truncate)(struct ocfs2_extent_tree *et,
110                                        u32 clusters);
111
112         /*
113          * If ->eo_insert_check() exists, it is called before rec is
114          * inserted into the extent tree.  It is optional.
115          */
116         int (*eo_insert_check)(struct ocfs2_extent_tree *et,
117                                struct ocfs2_extent_rec *rec);
118         int (*eo_sanity_check)(struct ocfs2_extent_tree *et);
119
120         /*
121          * --------------------------------------------------------------
122          * The remaining are internal to ocfs2_extent_tree and don't have
123          * accessor functions
124          */
125
126         /*
127          * ->eo_fill_root_el() takes et->et_object and sets et->et_root_el.
128          * It is required.
129          */
130         void (*eo_fill_root_el)(struct ocfs2_extent_tree *et);
131
132         /*
133          * ->eo_fill_max_leaf_clusters sets et->et_max_leaf_clusters if
134          * it exists.  If it does not, et->et_max_leaf_clusters is set
135          * to 0 (unlimited).  Optional.
136          */
137         void (*eo_fill_max_leaf_clusters)(struct ocfs2_extent_tree *et);
138
139         /*
140          * ->eo_extent_contig test whether the 2 ocfs2_extent_rec
141          * are contiguous or not. Optional. Don't need to set it if use
142          * ocfs2_extent_rec as the tree leaf.
143          */
144         enum ocfs2_contig_type
145                 (*eo_extent_contig)(struct ocfs2_extent_tree *et,
146                                     struct ocfs2_extent_rec *ext,
147                                     struct ocfs2_extent_rec *insert_rec);
148 };
149
150
151 /*
152  * Pre-declare ocfs2_dinode_et_ops so we can use it as a sanity check
153  * in the methods.
154  */
155 static u64 ocfs2_dinode_get_last_eb_blk(struct ocfs2_extent_tree *et);
156 static void ocfs2_dinode_set_last_eb_blk(struct ocfs2_extent_tree *et,
157                                          u64 blkno);
158 static void ocfs2_dinode_update_clusters(struct ocfs2_extent_tree *et,
159                                          u32 clusters);
160 static void ocfs2_dinode_extent_map_insert(struct ocfs2_extent_tree *et,
161                                            struct ocfs2_extent_rec *rec);
162 static void ocfs2_dinode_extent_map_truncate(struct ocfs2_extent_tree *et,
163                                              u32 clusters);
164 static int ocfs2_dinode_insert_check(struct ocfs2_extent_tree *et,
165                                      struct ocfs2_extent_rec *rec);
166 static int ocfs2_dinode_sanity_check(struct ocfs2_extent_tree *et);
167 static void ocfs2_dinode_fill_root_el(struct ocfs2_extent_tree *et);
168 static const struct ocfs2_extent_tree_operations ocfs2_dinode_et_ops = {
169         .eo_set_last_eb_blk     = ocfs2_dinode_set_last_eb_blk,
170         .eo_get_last_eb_blk     = ocfs2_dinode_get_last_eb_blk,
171         .eo_update_clusters     = ocfs2_dinode_update_clusters,
172         .eo_extent_map_insert   = ocfs2_dinode_extent_map_insert,
173         .eo_extent_map_truncate = ocfs2_dinode_extent_map_truncate,
174         .eo_insert_check        = ocfs2_dinode_insert_check,
175         .eo_sanity_check        = ocfs2_dinode_sanity_check,
176         .eo_fill_root_el        = ocfs2_dinode_fill_root_el,
177 };
178
179 static void ocfs2_dinode_set_last_eb_blk(struct ocfs2_extent_tree *et,
180                                          u64 blkno)
181 {
182         struct ocfs2_dinode *di = et->et_object;
183
184         BUG_ON(et->et_ops != &ocfs2_dinode_et_ops);
185         di->i_last_eb_blk = cpu_to_le64(blkno);
186 }
187
188 static u64 ocfs2_dinode_get_last_eb_blk(struct ocfs2_extent_tree *et)
189 {
190         struct ocfs2_dinode *di = et->et_object;
191
192         BUG_ON(et->et_ops != &ocfs2_dinode_et_ops);
193         return le64_to_cpu(di->i_last_eb_blk);
194 }
195
196 static void ocfs2_dinode_update_clusters(struct ocfs2_extent_tree *et,
197                                          u32 clusters)
198 {
199         struct ocfs2_inode_info *oi = cache_info_to_inode(et->et_ci);
200         struct ocfs2_dinode *di = et->et_object;
201
202         le32_add_cpu(&di->i_clusters, clusters);
203         spin_lock(&oi->ip_lock);
204         oi->ip_clusters = le32_to_cpu(di->i_clusters);
205         spin_unlock(&oi->ip_lock);
206 }
207
208 static void ocfs2_dinode_extent_map_insert(struct ocfs2_extent_tree *et,
209                                            struct ocfs2_extent_rec *rec)
210 {
211         struct inode *inode = &cache_info_to_inode(et->et_ci)->vfs_inode;
212
213         ocfs2_extent_map_insert_rec(inode, rec);
214 }
215
216 static void ocfs2_dinode_extent_map_truncate(struct ocfs2_extent_tree *et,
217                                              u32 clusters)
218 {
219         struct inode *inode = &cache_info_to_inode(et->et_ci)->vfs_inode;
220
221         ocfs2_extent_map_trunc(inode, clusters);
222 }
223
224 static int ocfs2_dinode_insert_check(struct ocfs2_extent_tree *et,
225                                      struct ocfs2_extent_rec *rec)
226 {
227         struct ocfs2_inode_info *oi = cache_info_to_inode(et->et_ci);
228         struct ocfs2_super *osb = OCFS2_SB(oi->vfs_inode.i_sb);
229
230         BUG_ON(oi->ip_dyn_features & OCFS2_INLINE_DATA_FL);
231         mlog_bug_on_msg(!ocfs2_sparse_alloc(osb) &&
232                         (oi->ip_clusters != le32_to_cpu(rec->e_cpos)),
233                         "Device %s, asking for sparse allocation: inode %llu, "
234                         "cpos %u, clusters %u\n",
235                         osb->dev_str,
236                         (unsigned long long)oi->ip_blkno,
237                         rec->e_cpos, oi->ip_clusters);
238
239         return 0;
240 }
241
242 static int ocfs2_dinode_sanity_check(struct ocfs2_extent_tree *et)
243 {
244         struct ocfs2_dinode *di = et->et_object;
245
246         BUG_ON(et->et_ops != &ocfs2_dinode_et_ops);
247         BUG_ON(!OCFS2_IS_VALID_DINODE(di));
248
249         return 0;
250 }
251
252 static void ocfs2_dinode_fill_root_el(struct ocfs2_extent_tree *et)
253 {
254         struct ocfs2_dinode *di = et->et_object;
255
256         et->et_root_el = &di->id2.i_list;
257 }
258
259
260 static void ocfs2_xattr_value_fill_root_el(struct ocfs2_extent_tree *et)
261 {
262         struct ocfs2_xattr_value_buf *vb = et->et_object;
263
264         et->et_root_el = &vb->vb_xv->xr_list;
265 }
266
267 static void ocfs2_xattr_value_set_last_eb_blk(struct ocfs2_extent_tree *et,
268                                               u64 blkno)
269 {
270         struct ocfs2_xattr_value_buf *vb = et->et_object;
271
272         vb->vb_xv->xr_last_eb_blk = cpu_to_le64(blkno);
273 }
274
275 static u64 ocfs2_xattr_value_get_last_eb_blk(struct ocfs2_extent_tree *et)
276 {
277         struct ocfs2_xattr_value_buf *vb = et->et_object;
278
279         return le64_to_cpu(vb->vb_xv->xr_last_eb_blk);
280 }
281
282 static void ocfs2_xattr_value_update_clusters(struct ocfs2_extent_tree *et,
283                                               u32 clusters)
284 {
285         struct ocfs2_xattr_value_buf *vb = et->et_object;
286
287         le32_add_cpu(&vb->vb_xv->xr_clusters, clusters);
288 }
289
290 static const struct ocfs2_extent_tree_operations ocfs2_xattr_value_et_ops = {
291         .eo_set_last_eb_blk     = ocfs2_xattr_value_set_last_eb_blk,
292         .eo_get_last_eb_blk     = ocfs2_xattr_value_get_last_eb_blk,
293         .eo_update_clusters     = ocfs2_xattr_value_update_clusters,
294         .eo_fill_root_el        = ocfs2_xattr_value_fill_root_el,
295 };
296
297 static void ocfs2_xattr_tree_fill_root_el(struct ocfs2_extent_tree *et)
298 {
299         struct ocfs2_xattr_block *xb = et->et_object;
300
301         et->et_root_el = &xb->xb_attrs.xb_root.xt_list;
302 }
303
304 static void ocfs2_xattr_tree_fill_max_leaf_clusters(struct ocfs2_extent_tree *et)
305 {
306         struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
307         et->et_max_leaf_clusters =
308                 ocfs2_clusters_for_bytes(sb, OCFS2_MAX_XATTR_TREE_LEAF_SIZE);
309 }
310
311 static void ocfs2_xattr_tree_set_last_eb_blk(struct ocfs2_extent_tree *et,
312                                              u64 blkno)
313 {
314         struct ocfs2_xattr_block *xb = et->et_object;
315         struct ocfs2_xattr_tree_root *xt = &xb->xb_attrs.xb_root;
316
317         xt->xt_last_eb_blk = cpu_to_le64(blkno);
318 }
319
320 static u64 ocfs2_xattr_tree_get_last_eb_blk(struct ocfs2_extent_tree *et)
321 {
322         struct ocfs2_xattr_block *xb = et->et_object;
323         struct ocfs2_xattr_tree_root *xt = &xb->xb_attrs.xb_root;
324
325         return le64_to_cpu(xt->xt_last_eb_blk);
326 }
327
328 static void ocfs2_xattr_tree_update_clusters(struct ocfs2_extent_tree *et,
329                                              u32 clusters)
330 {
331         struct ocfs2_xattr_block *xb = et->et_object;
332
333         le32_add_cpu(&xb->xb_attrs.xb_root.xt_clusters, clusters);
334 }
335
336 static const struct ocfs2_extent_tree_operations ocfs2_xattr_tree_et_ops = {
337         .eo_set_last_eb_blk     = ocfs2_xattr_tree_set_last_eb_blk,
338         .eo_get_last_eb_blk     = ocfs2_xattr_tree_get_last_eb_blk,
339         .eo_update_clusters     = ocfs2_xattr_tree_update_clusters,
340         .eo_fill_root_el        = ocfs2_xattr_tree_fill_root_el,
341         .eo_fill_max_leaf_clusters = ocfs2_xattr_tree_fill_max_leaf_clusters,
342 };
343
344 static void ocfs2_dx_root_set_last_eb_blk(struct ocfs2_extent_tree *et,
345                                           u64 blkno)
346 {
347         struct ocfs2_dx_root_block *dx_root = et->et_object;
348
349         dx_root->dr_last_eb_blk = cpu_to_le64(blkno);
350 }
351
352 static u64 ocfs2_dx_root_get_last_eb_blk(struct ocfs2_extent_tree *et)
353 {
354         struct ocfs2_dx_root_block *dx_root = et->et_object;
355
356         return le64_to_cpu(dx_root->dr_last_eb_blk);
357 }
358
359 static void ocfs2_dx_root_update_clusters(struct ocfs2_extent_tree *et,
360                                           u32 clusters)
361 {
362         struct ocfs2_dx_root_block *dx_root = et->et_object;
363
364         le32_add_cpu(&dx_root->dr_clusters, clusters);
365 }
366
367 static int ocfs2_dx_root_sanity_check(struct ocfs2_extent_tree *et)
368 {
369         struct ocfs2_dx_root_block *dx_root = et->et_object;
370
371         BUG_ON(!OCFS2_IS_VALID_DX_ROOT(dx_root));
372
373         return 0;
374 }
375
376 static void ocfs2_dx_root_fill_root_el(struct ocfs2_extent_tree *et)
377 {
378         struct ocfs2_dx_root_block *dx_root = et->et_object;
379
380         et->et_root_el = &dx_root->dr_list;
381 }
382
383 static const struct ocfs2_extent_tree_operations ocfs2_dx_root_et_ops = {
384         .eo_set_last_eb_blk     = ocfs2_dx_root_set_last_eb_blk,
385         .eo_get_last_eb_blk     = ocfs2_dx_root_get_last_eb_blk,
386         .eo_update_clusters     = ocfs2_dx_root_update_clusters,
387         .eo_sanity_check        = ocfs2_dx_root_sanity_check,
388         .eo_fill_root_el        = ocfs2_dx_root_fill_root_el,
389 };
390
391 static void ocfs2_refcount_tree_fill_root_el(struct ocfs2_extent_tree *et)
392 {
393         struct ocfs2_refcount_block *rb = et->et_object;
394
395         et->et_root_el = &rb->rf_list;
396 }
397
398 static void ocfs2_refcount_tree_set_last_eb_blk(struct ocfs2_extent_tree *et,
399                                                 u64 blkno)
400 {
401         struct ocfs2_refcount_block *rb = et->et_object;
402
403         rb->rf_last_eb_blk = cpu_to_le64(blkno);
404 }
405
406 static u64 ocfs2_refcount_tree_get_last_eb_blk(struct ocfs2_extent_tree *et)
407 {
408         struct ocfs2_refcount_block *rb = et->et_object;
409
410         return le64_to_cpu(rb->rf_last_eb_blk);
411 }
412
413 static void ocfs2_refcount_tree_update_clusters(struct ocfs2_extent_tree *et,
414                                                 u32 clusters)
415 {
416         struct ocfs2_refcount_block *rb = et->et_object;
417
418         le32_add_cpu(&rb->rf_clusters, clusters);
419 }
420
421 static enum ocfs2_contig_type
422 ocfs2_refcount_tree_extent_contig(struct ocfs2_extent_tree *et,
423                                   struct ocfs2_extent_rec *ext,
424                                   struct ocfs2_extent_rec *insert_rec)
425 {
426         return CONTIG_NONE;
427 }
428
429 static const struct ocfs2_extent_tree_operations ocfs2_refcount_tree_et_ops = {
430         .eo_set_last_eb_blk     = ocfs2_refcount_tree_set_last_eb_blk,
431         .eo_get_last_eb_blk     = ocfs2_refcount_tree_get_last_eb_blk,
432         .eo_update_clusters     = ocfs2_refcount_tree_update_clusters,
433         .eo_fill_root_el        = ocfs2_refcount_tree_fill_root_el,
434         .eo_extent_contig       = ocfs2_refcount_tree_extent_contig,
435 };
436
437 static void __ocfs2_init_extent_tree(struct ocfs2_extent_tree *et,
438                                      struct ocfs2_caching_info *ci,
439                                      struct buffer_head *bh,
440                                      ocfs2_journal_access_func access,
441                                      void *obj,
442                                      const struct ocfs2_extent_tree_operations *ops)
443 {
444         et->et_ops = ops;
445         et->et_root_bh = bh;
446         et->et_ci = ci;
447         et->et_root_journal_access = access;
448         if (!obj)
449                 obj = (void *)bh->b_data;
450         et->et_object = obj;
451
452         et->et_ops->eo_fill_root_el(et);
453         if (!et->et_ops->eo_fill_max_leaf_clusters)
454                 et->et_max_leaf_clusters = 0;
455         else
456                 et->et_ops->eo_fill_max_leaf_clusters(et);
457 }
458
459 void ocfs2_init_dinode_extent_tree(struct ocfs2_extent_tree *et,
460                                    struct ocfs2_caching_info *ci,
461                                    struct buffer_head *bh)
462 {
463         __ocfs2_init_extent_tree(et, ci, bh, ocfs2_journal_access_di,
464                                  NULL, &ocfs2_dinode_et_ops);
465 }
466
467 void ocfs2_init_xattr_tree_extent_tree(struct ocfs2_extent_tree *et,
468                                        struct ocfs2_caching_info *ci,
469                                        struct buffer_head *bh)
470 {
471         __ocfs2_init_extent_tree(et, ci, bh, ocfs2_journal_access_xb,
472                                  NULL, &ocfs2_xattr_tree_et_ops);
473 }
474
475 void ocfs2_init_xattr_value_extent_tree(struct ocfs2_extent_tree *et,
476                                         struct ocfs2_caching_info *ci,
477                                         struct ocfs2_xattr_value_buf *vb)
478 {
479         __ocfs2_init_extent_tree(et, ci, vb->vb_bh, vb->vb_access, vb,
480                                  &ocfs2_xattr_value_et_ops);
481 }
482
483 void ocfs2_init_dx_root_extent_tree(struct ocfs2_extent_tree *et,
484                                     struct ocfs2_caching_info *ci,
485                                     struct buffer_head *bh)
486 {
487         __ocfs2_init_extent_tree(et, ci, bh, ocfs2_journal_access_dr,
488                                  NULL, &ocfs2_dx_root_et_ops);
489 }
490
491 void ocfs2_init_refcount_extent_tree(struct ocfs2_extent_tree *et,
492                                      struct ocfs2_caching_info *ci,
493                                      struct buffer_head *bh)
494 {
495         __ocfs2_init_extent_tree(et, ci, bh, ocfs2_journal_access_rb,
496                                  NULL, &ocfs2_refcount_tree_et_ops);
497 }
498
499 static inline void ocfs2_et_set_last_eb_blk(struct ocfs2_extent_tree *et,
500                                             u64 new_last_eb_blk)
501 {
502         et->et_ops->eo_set_last_eb_blk(et, new_last_eb_blk);
503 }
504
505 static inline u64 ocfs2_et_get_last_eb_blk(struct ocfs2_extent_tree *et)
506 {
507         return et->et_ops->eo_get_last_eb_blk(et);
508 }
509
510 static inline void ocfs2_et_update_clusters(struct ocfs2_extent_tree *et,
511                                             u32 clusters)
512 {
513         et->et_ops->eo_update_clusters(et, clusters);
514 }
515
516 static inline void ocfs2_et_extent_map_insert(struct ocfs2_extent_tree *et,
517                                               struct ocfs2_extent_rec *rec)
518 {
519         if (et->et_ops->eo_extent_map_insert)
520                 et->et_ops->eo_extent_map_insert(et, rec);
521 }
522
523 static inline void ocfs2_et_extent_map_truncate(struct ocfs2_extent_tree *et,
524                                                 u32 clusters)
525 {
526         if (et->et_ops->eo_extent_map_truncate)
527                 et->et_ops->eo_extent_map_truncate(et, clusters);
528 }
529
530 static inline int ocfs2_et_root_journal_access(handle_t *handle,
531                                                struct ocfs2_extent_tree *et,
532                                                int type)
533 {
534         return et->et_root_journal_access(handle, et->et_ci, et->et_root_bh,
535                                           type);
536 }
537
538 static inline enum ocfs2_contig_type
539         ocfs2_et_extent_contig(struct ocfs2_extent_tree *et,
540                                struct ocfs2_extent_rec *rec,
541                                struct ocfs2_extent_rec *insert_rec)
542 {
543         if (et->et_ops->eo_extent_contig)
544                 return et->et_ops->eo_extent_contig(et, rec, insert_rec);
545
546         return ocfs2_extent_rec_contig(
547                                 ocfs2_metadata_cache_get_super(et->et_ci),
548                                 rec, insert_rec);
549 }
550
551 static inline int ocfs2_et_insert_check(struct ocfs2_extent_tree *et,
552                                         struct ocfs2_extent_rec *rec)
553 {
554         int ret = 0;
555
556         if (et->et_ops->eo_insert_check)
557                 ret = et->et_ops->eo_insert_check(et, rec);
558         return ret;
559 }
560
561 static inline int ocfs2_et_sanity_check(struct ocfs2_extent_tree *et)
562 {
563         int ret = 0;
564
565         if (et->et_ops->eo_sanity_check)
566                 ret = et->et_ops->eo_sanity_check(et);
567         return ret;
568 }
569
570 static int ocfs2_cache_extent_block_free(struct ocfs2_cached_dealloc_ctxt *ctxt,
571                                          struct ocfs2_extent_block *eb);
572 static void ocfs2_adjust_rightmost_records(handle_t *handle,
573                                            struct ocfs2_extent_tree *et,
574                                            struct ocfs2_path *path,
575                                            struct ocfs2_extent_rec *insert_rec);
576 /*
577  * Reset the actual path elements so that we can re-use the structure
578  * to build another path. Generally, this involves freeing the buffer
579  * heads.
580  */
581 void ocfs2_reinit_path(struct ocfs2_path *path, int keep_root)
582 {
583         int i, start = 0, depth = 0;
584         struct ocfs2_path_item *node;
585
586         if (keep_root)
587                 start = 1;
588
589         for(i = start; i < path_num_items(path); i++) {
590                 node = &path->p_node[i];
591
592                 brelse(node->bh);
593                 node->bh = NULL;
594                 node->el = NULL;
595         }
596
597         /*
598          * Tree depth may change during truncate, or insert. If we're
599          * keeping the root extent list, then make sure that our path
600          * structure reflects the proper depth.
601          */
602         if (keep_root)
603                 depth = le16_to_cpu(path_root_el(path)->l_tree_depth);
604         else
605                 path_root_access(path) = NULL;
606
607         path->p_tree_depth = depth;
608 }
609
610 void ocfs2_free_path(struct ocfs2_path *path)
611 {
612         if (path) {
613                 ocfs2_reinit_path(path, 0);
614                 kfree(path);
615         }
616 }
617
618 /*
619  * All the elements of src into dest. After this call, src could be freed
620  * without affecting dest.
621  *
622  * Both paths should have the same root. Any non-root elements of dest
623  * will be freed.
624  */
625 static void ocfs2_cp_path(struct ocfs2_path *dest, struct ocfs2_path *src)
626 {
627         int i;
628
629         BUG_ON(path_root_bh(dest) != path_root_bh(src));
630         BUG_ON(path_root_el(dest) != path_root_el(src));
631         BUG_ON(path_root_access(dest) != path_root_access(src));
632
633         ocfs2_reinit_path(dest, 1);
634
635         for(i = 1; i < OCFS2_MAX_PATH_DEPTH; i++) {
636                 dest->p_node[i].bh = src->p_node[i].bh;
637                 dest->p_node[i].el = src->p_node[i].el;
638
639                 if (dest->p_node[i].bh)
640                         get_bh(dest->p_node[i].bh);
641         }
642 }
643
644 /*
645  * Make the *dest path the same as src and re-initialize src path to
646  * have a root only.
647  */
648 static void ocfs2_mv_path(struct ocfs2_path *dest, struct ocfs2_path *src)
649 {
650         int i;
651
652         BUG_ON(path_root_bh(dest) != path_root_bh(src));
653         BUG_ON(path_root_access(dest) != path_root_access(src));
654
655         for(i = 1; i < OCFS2_MAX_PATH_DEPTH; i++) {
656                 brelse(dest->p_node[i].bh);
657
658                 dest->p_node[i].bh = src->p_node[i].bh;
659                 dest->p_node[i].el = src->p_node[i].el;
660
661                 src->p_node[i].bh = NULL;
662                 src->p_node[i].el = NULL;
663         }
664 }
665
666 /*
667  * Insert an extent block at given index.
668  *
669  * This will not take an additional reference on eb_bh.
670  */
671 static inline void ocfs2_path_insert_eb(struct ocfs2_path *path, int index,
672                                         struct buffer_head *eb_bh)
673 {
674         struct ocfs2_extent_block *eb = (struct ocfs2_extent_block *)eb_bh->b_data;
675
676         /*
677          * Right now, no root bh is an extent block, so this helps
678          * catch code errors with dinode trees. The assertion can be
679          * safely removed if we ever need to insert extent block
680          * structures at the root.
681          */
682         BUG_ON(index == 0);
683
684         path->p_node[index].bh = eb_bh;
685         path->p_node[index].el = &eb->h_list;
686 }
687
688 static struct ocfs2_path *ocfs2_new_path(struct buffer_head *root_bh,
689                                          struct ocfs2_extent_list *root_el,
690                                          ocfs2_journal_access_func access)
691 {
692         struct ocfs2_path *path;
693
694         BUG_ON(le16_to_cpu(root_el->l_tree_depth) >= OCFS2_MAX_PATH_DEPTH);
695
696         path = kzalloc(sizeof(*path), GFP_NOFS);
697         if (path) {
698                 path->p_tree_depth = le16_to_cpu(root_el->l_tree_depth);
699                 get_bh(root_bh);
700                 path_root_bh(path) = root_bh;
701                 path_root_el(path) = root_el;
702                 path_root_access(path) = access;
703         }
704
705         return path;
706 }
707
708 struct ocfs2_path *ocfs2_new_path_from_path(struct ocfs2_path *path)
709 {
710         return ocfs2_new_path(path_root_bh(path), path_root_el(path),
711                               path_root_access(path));
712 }
713
714 struct ocfs2_path *ocfs2_new_path_from_et(struct ocfs2_extent_tree *et)
715 {
716         return ocfs2_new_path(et->et_root_bh, et->et_root_el,
717                               et->et_root_journal_access);
718 }
719
720 /*
721  * Journal the buffer at depth idx.  All idx>0 are extent_blocks,
722  * otherwise it's the root_access function.
723  *
724  * I don't like the way this function's name looks next to
725  * ocfs2_journal_access_path(), but I don't have a better one.
726  */
727 int ocfs2_path_bh_journal_access(handle_t *handle,
728                                  struct ocfs2_caching_info *ci,
729                                  struct ocfs2_path *path,
730                                  int idx)
731 {
732         ocfs2_journal_access_func access = path_root_access(path);
733
734         if (!access)
735                 access = ocfs2_journal_access;
736
737         if (idx)
738                 access = ocfs2_journal_access_eb;
739
740         return access(handle, ci, path->p_node[idx].bh,
741                       OCFS2_JOURNAL_ACCESS_WRITE);
742 }
743
744 /*
745  * Convenience function to journal all components in a path.
746  */
747 int ocfs2_journal_access_path(struct ocfs2_caching_info *ci,
748                               handle_t *handle,
749                               struct ocfs2_path *path)
750 {
751         int i, ret = 0;
752
753         if (!path)
754                 goto out;
755
756         for(i = 0; i < path_num_items(path); i++) {
757                 ret = ocfs2_path_bh_journal_access(handle, ci, path, i);
758                 if (ret < 0) {
759                         mlog_errno(ret);
760                         goto out;
761                 }
762         }
763
764 out:
765         return ret;
766 }
767
768 /*
769  * Return the index of the extent record which contains cluster #v_cluster.
770  * -1 is returned if it was not found.
771  *
772  * Should work fine on interior and exterior nodes.
773  */
774 int ocfs2_search_extent_list(struct ocfs2_extent_list *el, u32 v_cluster)
775 {
776         int ret = -1;
777         int i;
778         struct ocfs2_extent_rec *rec;
779         u32 rec_end, rec_start, clusters;
780
781         for(i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
782                 rec = &el->l_recs[i];
783
784                 rec_start = le32_to_cpu(rec->e_cpos);
785                 clusters = ocfs2_rec_clusters(el, rec);
786
787                 rec_end = rec_start + clusters;
788
789                 if (v_cluster >= rec_start && v_cluster < rec_end) {
790                         ret = i;
791                         break;
792                 }
793         }
794
795         return ret;
796 }
797
798 /*
799  * NOTE: ocfs2_block_extent_contig(), ocfs2_extents_adjacent() and
800  * ocfs2_extent_rec_contig only work properly against leaf nodes!
801  */
802 static int ocfs2_block_extent_contig(struct super_block *sb,
803                                      struct ocfs2_extent_rec *ext,
804                                      u64 blkno)
805 {
806         u64 blk_end = le64_to_cpu(ext->e_blkno);
807
808         blk_end += ocfs2_clusters_to_blocks(sb,
809                                     le16_to_cpu(ext->e_leaf_clusters));
810
811         return blkno == blk_end;
812 }
813
814 static int ocfs2_extents_adjacent(struct ocfs2_extent_rec *left,
815                                   struct ocfs2_extent_rec *right)
816 {
817         u32 left_range;
818
819         left_range = le32_to_cpu(left->e_cpos) +
820                 le16_to_cpu(left->e_leaf_clusters);
821
822         return (left_range == le32_to_cpu(right->e_cpos));
823 }
824
825 static enum ocfs2_contig_type
826         ocfs2_extent_rec_contig(struct super_block *sb,
827                                 struct ocfs2_extent_rec *ext,
828                                 struct ocfs2_extent_rec *insert_rec)
829 {
830         u64 blkno = le64_to_cpu(insert_rec->e_blkno);
831
832         /*
833          * Refuse to coalesce extent records with different flag
834          * fields - we don't want to mix unwritten extents with user
835          * data.
836          */
837         if (ext->e_flags != insert_rec->e_flags)
838                 return CONTIG_NONE;
839
840         if (ocfs2_extents_adjacent(ext, insert_rec) &&
841             ocfs2_block_extent_contig(sb, ext, blkno))
842                         return CONTIG_RIGHT;
843
844         blkno = le64_to_cpu(ext->e_blkno);
845         if (ocfs2_extents_adjacent(insert_rec, ext) &&
846             ocfs2_block_extent_contig(sb, insert_rec, blkno))
847                 return CONTIG_LEFT;
848
849         return CONTIG_NONE;
850 }
851
852 /*
853  * NOTE: We can have pretty much any combination of contiguousness and
854  * appending.
855  *
856  * The usefulness of APPEND_TAIL is more in that it lets us know that
857  * we'll have to update the path to that leaf.
858  */
859 enum ocfs2_append_type {
860         APPEND_NONE = 0,
861         APPEND_TAIL,
862 };
863
864 enum ocfs2_split_type {
865         SPLIT_NONE = 0,
866         SPLIT_LEFT,
867         SPLIT_RIGHT,
868 };
869
870 struct ocfs2_insert_type {
871         enum ocfs2_split_type   ins_split;
872         enum ocfs2_append_type  ins_appending;
873         enum ocfs2_contig_type  ins_contig;
874         int                     ins_contig_index;
875         int                     ins_tree_depth;
876 };
877
878 struct ocfs2_merge_ctxt {
879         enum ocfs2_contig_type  c_contig_type;
880         int                     c_has_empty_extent;
881         int                     c_split_covers_rec;
882 };
883
884 static int ocfs2_validate_extent_block(struct super_block *sb,
885                                        struct buffer_head *bh)
886 {
887         int rc;
888         struct ocfs2_extent_block *eb =
889                 (struct ocfs2_extent_block *)bh->b_data;
890
891         trace_ocfs2_validate_extent_block((unsigned long long)bh->b_blocknr);
892
893         BUG_ON(!buffer_uptodate(bh));
894
895         /*
896          * If the ecc fails, we return the error but otherwise
897          * leave the filesystem running.  We know any error is
898          * local to this block.
899          */
900         rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &eb->h_check);
901         if (rc) {
902                 mlog(ML_ERROR, "Checksum failed for extent block %llu\n",
903                      (unsigned long long)bh->b_blocknr);
904                 return rc;
905         }
906
907         /*
908          * Errors after here are fatal.
909          */
910
911         if (!OCFS2_IS_VALID_EXTENT_BLOCK(eb)) {
912                 rc = ocfs2_error(sb,
913                                  "Extent block #%llu has bad signature %.*s\n",
914                                  (unsigned long long)bh->b_blocknr, 7,
915                                  eb->h_signature);
916                 goto bail;
917         }
918
919         if (le64_to_cpu(eb->h_blkno) != bh->b_blocknr) {
920                 rc = ocfs2_error(sb,
921                                  "Extent block #%llu has an invalid h_blkno of %llu\n",
922                                  (unsigned long long)bh->b_blocknr,
923                                  (unsigned long long)le64_to_cpu(eb->h_blkno));
924                 goto bail;
925         }
926
927         if (le32_to_cpu(eb->h_fs_generation) != OCFS2_SB(sb)->fs_generation) {
928                 rc = ocfs2_error(sb,
929                                  "Extent block #%llu has an invalid h_fs_generation of #%u\n",
930                                  (unsigned long long)bh->b_blocknr,
931                                  le32_to_cpu(eb->h_fs_generation));
932                 goto bail;
933         }
934 bail:
935         return rc;
936 }
937
938 int ocfs2_read_extent_block(struct ocfs2_caching_info *ci, u64 eb_blkno,
939                             struct buffer_head **bh)
940 {
941         int rc;
942         struct buffer_head *tmp = *bh;
943
944         rc = ocfs2_read_block(ci, eb_blkno, &tmp,
945                               ocfs2_validate_extent_block);
946
947         /* If ocfs2_read_block() got us a new bh, pass it up. */
948         if (!rc && !*bh)
949                 *bh = tmp;
950
951         return rc;
952 }
953
954
955 /*
956  * How many free extents have we got before we need more meta data?
957  */
958 int ocfs2_num_free_extents(struct ocfs2_extent_tree *et)
959 {
960         int retval;
961         struct ocfs2_extent_list *el = NULL;
962         struct ocfs2_extent_block *eb;
963         struct buffer_head *eb_bh = NULL;
964         u64 last_eb_blk = 0;
965
966         el = et->et_root_el;
967         last_eb_blk = ocfs2_et_get_last_eb_blk(et);
968
969         if (last_eb_blk) {
970                 retval = ocfs2_read_extent_block(et->et_ci, last_eb_blk,
971                                                  &eb_bh);
972                 if (retval < 0) {
973                         mlog_errno(retval);
974                         goto bail;
975                 }
976                 eb = (struct ocfs2_extent_block *) eb_bh->b_data;
977                 el = &eb->h_list;
978         }
979
980         BUG_ON(el->l_tree_depth != 0);
981
982         retval = le16_to_cpu(el->l_count) - le16_to_cpu(el->l_next_free_rec);
983 bail:
984         brelse(eb_bh);
985
986         trace_ocfs2_num_free_extents(retval);
987         return retval;
988 }
989
990 /* expects array to already be allocated
991  *
992  * sets h_signature, h_blkno, h_suballoc_bit, h_suballoc_slot, and
993  * l_count for you
994  */
995 static int ocfs2_create_new_meta_bhs(handle_t *handle,
996                                      struct ocfs2_extent_tree *et,
997                                      int wanted,
998                                      struct ocfs2_alloc_context *meta_ac,
999                                      struct buffer_head *bhs[])
1000 {
1001         int count, status, i;
1002         u16 suballoc_bit_start;
1003         u32 num_got;
1004         u64 suballoc_loc, first_blkno;
1005         struct ocfs2_super *osb =
1006                 OCFS2_SB(ocfs2_metadata_cache_get_super(et->et_ci));
1007         struct ocfs2_extent_block *eb;
1008
1009         count = 0;
1010         while (count < wanted) {
1011                 status = ocfs2_claim_metadata(handle,
1012                                               meta_ac,
1013                                               wanted - count,
1014                                               &suballoc_loc,
1015                                               &suballoc_bit_start,
1016                                               &num_got,
1017                                               &first_blkno);
1018                 if (status < 0) {
1019                         mlog_errno(status);
1020                         goto bail;
1021                 }
1022
1023                 for(i = count;  i < (num_got + count); i++) {
1024                         bhs[i] = sb_getblk(osb->sb, first_blkno);
1025                         if (bhs[i] == NULL) {
1026                                 status = -ENOMEM;
1027                                 mlog_errno(status);
1028                                 goto bail;
1029                         }
1030                         ocfs2_set_new_buffer_uptodate(et->et_ci, bhs[i]);
1031
1032                         status = ocfs2_journal_access_eb(handle, et->et_ci,
1033                                                          bhs[i],
1034                                                          OCFS2_JOURNAL_ACCESS_CREATE);
1035                         if (status < 0) {
1036                                 mlog_errno(status);
1037                                 goto bail;
1038                         }
1039
1040                         memset(bhs[i]->b_data, 0, osb->sb->s_blocksize);
1041                         eb = (struct ocfs2_extent_block *) bhs[i]->b_data;
1042                         /* Ok, setup the minimal stuff here. */
1043                         strcpy(eb->h_signature, OCFS2_EXTENT_BLOCK_SIGNATURE);
1044                         eb->h_blkno = cpu_to_le64(first_blkno);
1045                         eb->h_fs_generation = cpu_to_le32(osb->fs_generation);
1046                         eb->h_suballoc_slot =
1047                                 cpu_to_le16(meta_ac->ac_alloc_slot);
1048                         eb->h_suballoc_loc = cpu_to_le64(suballoc_loc);
1049                         eb->h_suballoc_bit = cpu_to_le16(suballoc_bit_start);
1050                         eb->h_list.l_count =
1051                                 cpu_to_le16(ocfs2_extent_recs_per_eb(osb->sb));
1052
1053                         suballoc_bit_start++;
1054                         first_blkno++;
1055
1056                         /* We'll also be dirtied by the caller, so
1057                          * this isn't absolutely necessary. */
1058                         ocfs2_journal_dirty(handle, bhs[i]);
1059                 }
1060
1061                 count += num_got;
1062         }
1063
1064         status = 0;
1065 bail:
1066         if (status < 0) {
1067                 for(i = 0; i < wanted; i++) {
1068                         brelse(bhs[i]);
1069                         bhs[i] = NULL;
1070                 }
1071                 mlog_errno(status);
1072         }
1073         return status;
1074 }
1075
1076 /*
1077  * Helper function for ocfs2_add_branch() and ocfs2_shift_tree_depth().
1078  *
1079  * Returns the sum of the rightmost extent rec logical offset and
1080  * cluster count.
1081  *
1082  * ocfs2_add_branch() uses this to determine what logical cluster
1083  * value should be populated into the leftmost new branch records.
1084  *
1085  * ocfs2_shift_tree_depth() uses this to determine the # clusters
1086  * value for the new topmost tree record.
1087  */
1088 static inline u32 ocfs2_sum_rightmost_rec(struct ocfs2_extent_list  *el)
1089 {
1090         int i;
1091
1092         i = le16_to_cpu(el->l_next_free_rec) - 1;
1093
1094         return le32_to_cpu(el->l_recs[i].e_cpos) +
1095                 ocfs2_rec_clusters(el, &el->l_recs[i]);
1096 }
1097
1098 /*
1099  * Change range of the branches in the right most path according to the leaf
1100  * extent block's rightmost record.
1101  */
1102 static int ocfs2_adjust_rightmost_branch(handle_t *handle,
1103                                          struct ocfs2_extent_tree *et)
1104 {
1105         int status;
1106         struct ocfs2_path *path = NULL;
1107         struct ocfs2_extent_list *el;
1108         struct ocfs2_extent_rec *rec;
1109
1110         path = ocfs2_new_path_from_et(et);
1111         if (!path) {
1112                 status = -ENOMEM;
1113                 return status;
1114         }
1115
1116         status = ocfs2_find_path(et->et_ci, path, UINT_MAX);
1117         if (status < 0) {
1118                 mlog_errno(status);
1119                 goto out;
1120         }
1121
1122         status = ocfs2_extend_trans(handle, path_num_items(path));
1123         if (status < 0) {
1124                 mlog_errno(status);
1125                 goto out;
1126         }
1127
1128         status = ocfs2_journal_access_path(et->et_ci, handle, path);
1129         if (status < 0) {
1130                 mlog_errno(status);
1131                 goto out;
1132         }
1133
1134         el = path_leaf_el(path);
1135         rec = &el->l_recs[le16_to_cpu(el->l_next_free_rec) - 1];
1136
1137         ocfs2_adjust_rightmost_records(handle, et, path, rec);
1138
1139 out:
1140         ocfs2_free_path(path);
1141         return status;
1142 }
1143
1144 /*
1145  * Add an entire tree branch to our inode. eb_bh is the extent block
1146  * to start at, if we don't want to start the branch at the root
1147  * structure.
1148  *
1149  * last_eb_bh is required as we have to update it's next_leaf pointer
1150  * for the new last extent block.
1151  *
1152  * the new branch will be 'empty' in the sense that every block will
1153  * contain a single record with cluster count == 0.
1154  */
1155 static int ocfs2_add_branch(handle_t *handle,
1156                             struct ocfs2_extent_tree *et,
1157                             struct buffer_head *eb_bh,
1158                             struct buffer_head **last_eb_bh,
1159                             struct ocfs2_alloc_context *meta_ac)
1160 {
1161         int status, new_blocks, i;
1162         u64 next_blkno, new_last_eb_blk;
1163         struct buffer_head *bh;
1164         struct buffer_head **new_eb_bhs = NULL;
1165         struct ocfs2_extent_block *eb;
1166         struct ocfs2_extent_list  *eb_el;
1167         struct ocfs2_extent_list  *el;
1168         u32 new_cpos, root_end;
1169
1170         BUG_ON(!last_eb_bh || !*last_eb_bh);
1171
1172         if (eb_bh) {
1173                 eb = (struct ocfs2_extent_block *) eb_bh->b_data;
1174                 el = &eb->h_list;
1175         } else
1176                 el = et->et_root_el;
1177
1178         /* we never add a branch to a leaf. */
1179         BUG_ON(!el->l_tree_depth);
1180
1181         new_blocks = le16_to_cpu(el->l_tree_depth);
1182
1183         eb = (struct ocfs2_extent_block *)(*last_eb_bh)->b_data;
1184         new_cpos = ocfs2_sum_rightmost_rec(&eb->h_list);
1185         root_end = ocfs2_sum_rightmost_rec(et->et_root_el);
1186
1187         /*
1188          * If there is a gap before the root end and the real end
1189          * of the righmost leaf block, we need to remove the gap
1190          * between new_cpos and root_end first so that the tree
1191          * is consistent after we add a new branch(it will start
1192          * from new_cpos).
1193          */
1194         if (root_end > new_cpos) {
1195                 trace_ocfs2_adjust_rightmost_branch(
1196                         (unsigned long long)
1197                         ocfs2_metadata_cache_owner(et->et_ci),
1198                         root_end, new_cpos);
1199
1200                 status = ocfs2_adjust_rightmost_branch(handle, et);
1201                 if (status) {
1202                         mlog_errno(status);
1203                         goto bail;
1204                 }
1205         }
1206
1207         /* allocate the number of new eb blocks we need */
1208         new_eb_bhs = kcalloc(new_blocks, sizeof(struct buffer_head *),
1209                              GFP_KERNEL);
1210         if (!new_eb_bhs) {
1211                 status = -ENOMEM;
1212                 mlog_errno(status);
1213                 goto bail;
1214         }
1215
1216         status = ocfs2_create_new_meta_bhs(handle, et, new_blocks,
1217                                            meta_ac, new_eb_bhs);
1218         if (status < 0) {
1219                 mlog_errno(status);
1220                 goto bail;
1221         }
1222
1223         /* Note: new_eb_bhs[new_blocks - 1] is the guy which will be
1224          * linked with the rest of the tree.
1225          * conversly, new_eb_bhs[0] is the new bottommost leaf.
1226          *
1227          * when we leave the loop, new_last_eb_blk will point to the
1228          * newest leaf, and next_blkno will point to the topmost extent
1229          * block. */
1230         next_blkno = new_last_eb_blk = 0;
1231         for(i = 0; i < new_blocks; i++) {
1232                 bh = new_eb_bhs[i];
1233                 eb = (struct ocfs2_extent_block *) bh->b_data;
1234                 /* ocfs2_create_new_meta_bhs() should create it right! */
1235                 BUG_ON(!OCFS2_IS_VALID_EXTENT_BLOCK(eb));
1236                 eb_el = &eb->h_list;
1237
1238                 status = ocfs2_journal_access_eb(handle, et->et_ci, bh,
1239                                                  OCFS2_JOURNAL_ACCESS_CREATE);
1240                 if (status < 0) {
1241                         mlog_errno(status);
1242                         goto bail;
1243                 }
1244
1245                 eb->h_next_leaf_blk = 0;
1246                 eb_el->l_tree_depth = cpu_to_le16(i);
1247                 eb_el->l_next_free_rec = cpu_to_le16(1);
1248                 /*
1249                  * This actually counts as an empty extent as
1250                  * c_clusters == 0
1251                  */
1252                 eb_el->l_recs[0].e_cpos = cpu_to_le32(new_cpos);
1253                 eb_el->l_recs[0].e_blkno = cpu_to_le64(next_blkno);
1254                 /*
1255                  * eb_el isn't always an interior node, but even leaf
1256                  * nodes want a zero'd flags and reserved field so
1257                  * this gets the whole 32 bits regardless of use.
1258                  */
1259                 eb_el->l_recs[0].e_int_clusters = cpu_to_le32(0);
1260                 if (!eb_el->l_tree_depth)
1261                         new_last_eb_blk = le64_to_cpu(eb->h_blkno);
1262
1263                 ocfs2_journal_dirty(handle, bh);
1264                 next_blkno = le64_to_cpu(eb->h_blkno);
1265         }
1266
1267         /* This is a bit hairy. We want to update up to three blocks
1268          * here without leaving any of them in an inconsistent state
1269          * in case of error. We don't have to worry about
1270          * journal_dirty erroring as it won't unless we've aborted the
1271          * handle (in which case we would never be here) so reserving
1272          * the write with journal_access is all we need to do. */
1273         status = ocfs2_journal_access_eb(handle, et->et_ci, *last_eb_bh,
1274                                          OCFS2_JOURNAL_ACCESS_WRITE);
1275         if (status < 0) {
1276                 mlog_errno(status);
1277                 goto bail;
1278         }
1279         status = ocfs2_et_root_journal_access(handle, et,
1280                                               OCFS2_JOURNAL_ACCESS_WRITE);
1281         if (status < 0) {
1282                 mlog_errno(status);
1283                 goto bail;
1284         }
1285         if (eb_bh) {
1286                 status = ocfs2_journal_access_eb(handle, et->et_ci, eb_bh,
1287                                                  OCFS2_JOURNAL_ACCESS_WRITE);
1288                 if (status < 0) {
1289                         mlog_errno(status);
1290                         goto bail;
1291                 }
1292         }
1293
1294         /* Link the new branch into the rest of the tree (el will
1295          * either be on the root_bh, or the extent block passed in. */
1296         i = le16_to_cpu(el->l_next_free_rec);
1297         el->l_recs[i].e_blkno = cpu_to_le64(next_blkno);
1298         el->l_recs[i].e_cpos = cpu_to_le32(new_cpos);
1299         el->l_recs[i].e_int_clusters = 0;
1300         le16_add_cpu(&el->l_next_free_rec, 1);
1301
1302         /* fe needs a new last extent block pointer, as does the
1303          * next_leaf on the previously last-extent-block. */
1304         ocfs2_et_set_last_eb_blk(et, new_last_eb_blk);
1305
1306         eb = (struct ocfs2_extent_block *) (*last_eb_bh)->b_data;
1307         eb->h_next_leaf_blk = cpu_to_le64(new_last_eb_blk);
1308
1309         ocfs2_journal_dirty(handle, *last_eb_bh);
1310         ocfs2_journal_dirty(handle, et->et_root_bh);
1311         if (eb_bh)
1312                 ocfs2_journal_dirty(handle, eb_bh);
1313
1314         /*
1315          * Some callers want to track the rightmost leaf so pass it
1316          * back here.
1317          */
1318         brelse(*last_eb_bh);
1319         get_bh(new_eb_bhs[0]);
1320         *last_eb_bh = new_eb_bhs[0];
1321
1322         status = 0;
1323 bail:
1324         if (new_eb_bhs) {
1325                 for (i = 0; i < new_blocks; i++)
1326                         brelse(new_eb_bhs[i]);
1327                 kfree(new_eb_bhs);
1328         }
1329
1330         return status;
1331 }
1332
1333 /*
1334  * adds another level to the allocation tree.
1335  * returns back the new extent block so you can add a branch to it
1336  * after this call.
1337  */
1338 static int ocfs2_shift_tree_depth(handle_t *handle,
1339                                   struct ocfs2_extent_tree *et,
1340                                   struct ocfs2_alloc_context *meta_ac,
1341                                   struct buffer_head **ret_new_eb_bh)
1342 {
1343         int status, i;
1344         u32 new_clusters;
1345         struct buffer_head *new_eb_bh = NULL;
1346         struct ocfs2_extent_block *eb;
1347         struct ocfs2_extent_list  *root_el;
1348         struct ocfs2_extent_list  *eb_el;
1349
1350         status = ocfs2_create_new_meta_bhs(handle, et, 1, meta_ac,
1351                                            &new_eb_bh);
1352         if (status < 0) {
1353                 mlog_errno(status);
1354                 goto bail;
1355         }
1356
1357         eb = (struct ocfs2_extent_block *) new_eb_bh->b_data;
1358         /* ocfs2_create_new_meta_bhs() should create it right! */
1359         BUG_ON(!OCFS2_IS_VALID_EXTENT_BLOCK(eb));
1360
1361         eb_el = &eb->h_list;
1362         root_el = et->et_root_el;
1363
1364         status = ocfs2_journal_access_eb(handle, et->et_ci, new_eb_bh,
1365                                          OCFS2_JOURNAL_ACCESS_CREATE);
1366         if (status < 0) {
1367                 mlog_errno(status);
1368                 goto bail;
1369         }
1370
1371         /* copy the root extent list data into the new extent block */
1372         eb_el->l_tree_depth = root_el->l_tree_depth;
1373         eb_el->l_next_free_rec = root_el->l_next_free_rec;
1374         for (i = 0; i < le16_to_cpu(root_el->l_next_free_rec); i++)
1375                 eb_el->l_recs[i] = root_el->l_recs[i];
1376
1377         ocfs2_journal_dirty(handle, new_eb_bh);
1378
1379         status = ocfs2_et_root_journal_access(handle, et,
1380                                               OCFS2_JOURNAL_ACCESS_WRITE);
1381         if (status < 0) {
1382                 mlog_errno(status);
1383                 goto bail;
1384         }
1385
1386         new_clusters = ocfs2_sum_rightmost_rec(eb_el);
1387
1388         /* update root_bh now */
1389         le16_add_cpu(&root_el->l_tree_depth, 1);
1390         root_el->l_recs[0].e_cpos = 0;
1391         root_el->l_recs[0].e_blkno = eb->h_blkno;
1392         root_el->l_recs[0].e_int_clusters = cpu_to_le32(new_clusters);
1393         for (i = 1; i < le16_to_cpu(root_el->l_next_free_rec); i++)
1394                 memset(&root_el->l_recs[i], 0, sizeof(struct ocfs2_extent_rec));
1395         root_el->l_next_free_rec = cpu_to_le16(1);
1396
1397         /* If this is our 1st tree depth shift, then last_eb_blk
1398          * becomes the allocated extent block */
1399         if (root_el->l_tree_depth == cpu_to_le16(1))
1400                 ocfs2_et_set_last_eb_blk(et, le64_to_cpu(eb->h_blkno));
1401
1402         ocfs2_journal_dirty(handle, et->et_root_bh);
1403
1404         *ret_new_eb_bh = new_eb_bh;
1405         new_eb_bh = NULL;
1406         status = 0;
1407 bail:
1408         brelse(new_eb_bh);
1409
1410         return status;
1411 }
1412
1413 /*
1414  * Should only be called when there is no space left in any of the
1415  * leaf nodes. What we want to do is find the lowest tree depth
1416  * non-leaf extent block with room for new records. There are three
1417  * valid results of this search:
1418  *
1419  * 1) a lowest extent block is found, then we pass it back in
1420  *    *lowest_eb_bh and return '0'
1421  *
1422  * 2) the search fails to find anything, but the root_el has room. We
1423  *    pass NULL back in *lowest_eb_bh, but still return '0'
1424  *
1425  * 3) the search fails to find anything AND the root_el is full, in
1426  *    which case we return > 0
1427  *
1428  * return status < 0 indicates an error.
1429  */
1430 static int ocfs2_find_branch_target(struct ocfs2_extent_tree *et,
1431                                     struct buffer_head **target_bh)
1432 {
1433         int status = 0, i;
1434         u64 blkno;
1435         struct ocfs2_extent_block *eb;
1436         struct ocfs2_extent_list  *el;
1437         struct buffer_head *bh = NULL;
1438         struct buffer_head *lowest_bh = NULL;
1439
1440         *target_bh = NULL;
1441
1442         el = et->et_root_el;
1443
1444         while(le16_to_cpu(el->l_tree_depth) > 1) {
1445                 if (le16_to_cpu(el->l_next_free_rec) == 0) {
1446                         ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
1447                                     "Owner %llu has empty extent list (next_free_rec == 0)\n",
1448                                     (unsigned long long)ocfs2_metadata_cache_owner(et->et_ci));
1449                         status = -EIO;
1450                         goto bail;
1451                 }
1452                 i = le16_to_cpu(el->l_next_free_rec) - 1;
1453                 blkno = le64_to_cpu(el->l_recs[i].e_blkno);
1454                 if (!blkno) {
1455                         ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
1456                                     "Owner %llu has extent list where extent # %d has no physical block start\n",
1457                                     (unsigned long long)ocfs2_metadata_cache_owner(et->et_ci), i);
1458                         status = -EIO;
1459                         goto bail;
1460                 }
1461
1462                 brelse(bh);
1463                 bh = NULL;
1464
1465                 status = ocfs2_read_extent_block(et->et_ci, blkno, &bh);
1466                 if (status < 0) {
1467                         mlog_errno(status);
1468                         goto bail;
1469                 }
1470
1471                 eb = (struct ocfs2_extent_block *) bh->b_data;
1472                 el = &eb->h_list;
1473
1474                 if (le16_to_cpu(el->l_next_free_rec) <
1475                     le16_to_cpu(el->l_count)) {
1476                         brelse(lowest_bh);
1477                         lowest_bh = bh;
1478                         get_bh(lowest_bh);
1479                 }
1480         }
1481
1482         /* If we didn't find one and the fe doesn't have any room,
1483          * then return '1' */
1484         el = et->et_root_el;
1485         if (!lowest_bh && (el->l_next_free_rec == el->l_count))
1486                 status = 1;
1487
1488         *target_bh = lowest_bh;
1489 bail:
1490         brelse(bh);
1491
1492         return status;
1493 }
1494
1495 /*
1496  * Grow a b-tree so that it has more records.
1497  *
1498  * We might shift the tree depth in which case existing paths should
1499  * be considered invalid.
1500  *
1501  * Tree depth after the grow is returned via *final_depth.
1502  *
1503  * *last_eb_bh will be updated by ocfs2_add_branch().
1504  */
1505 static int ocfs2_grow_tree(handle_t *handle, struct ocfs2_extent_tree *et,
1506                            int *final_depth, struct buffer_head **last_eb_bh,
1507                            struct ocfs2_alloc_context *meta_ac)
1508 {
1509         int ret, shift;
1510         struct ocfs2_extent_list *el = et->et_root_el;
1511         int depth = le16_to_cpu(el->l_tree_depth);
1512         struct buffer_head *bh = NULL;
1513
1514         BUG_ON(meta_ac == NULL);
1515
1516         shift = ocfs2_find_branch_target(et, &bh);
1517         if (shift < 0) {
1518                 ret = shift;
1519                 mlog_errno(ret);
1520                 goto out;
1521         }
1522
1523         /* We traveled all the way to the bottom of the allocation tree
1524          * and didn't find room for any more extents - we need to add
1525          * another tree level */
1526         if (shift) {
1527                 BUG_ON(bh);
1528                 trace_ocfs2_grow_tree(
1529                         (unsigned long long)
1530                         ocfs2_metadata_cache_owner(et->et_ci),
1531                         depth);
1532
1533                 /* ocfs2_shift_tree_depth will return us a buffer with
1534                  * the new extent block (so we can pass that to
1535                  * ocfs2_add_branch). */
1536                 ret = ocfs2_shift_tree_depth(handle, et, meta_ac, &bh);
1537                 if (ret < 0) {
1538                         mlog_errno(ret);
1539                         goto out;
1540                 }
1541                 depth++;
1542                 if (depth == 1) {
1543                         /*
1544                          * Special case: we have room now if we shifted from
1545                          * tree_depth 0, so no more work needs to be done.
1546                          *
1547                          * We won't be calling add_branch, so pass
1548                          * back *last_eb_bh as the new leaf. At depth
1549                          * zero, it should always be null so there's
1550                          * no reason to brelse.
1551                          */
1552                         BUG_ON(*last_eb_bh);
1553                         get_bh(bh);
1554                         *last_eb_bh = bh;
1555                         goto out;
1556                 }
1557         }
1558
1559         /* call ocfs2_add_branch to add the final part of the tree with
1560          * the new data. */
1561         ret = ocfs2_add_branch(handle, et, bh, last_eb_bh,
1562                                meta_ac);
1563         if (ret < 0) {
1564                 mlog_errno(ret);
1565                 goto out;
1566         }
1567
1568 out:
1569         if (final_depth)
1570                 *final_depth = depth;
1571         brelse(bh);
1572         return ret;
1573 }
1574
1575 /*
1576  * This function will discard the rightmost extent record.
1577  */
1578 static void ocfs2_shift_records_right(struct ocfs2_extent_list *el)
1579 {
1580         int next_free = le16_to_cpu(el->l_next_free_rec);
1581         int count = le16_to_cpu(el->l_count);
1582         unsigned int num_bytes;
1583
1584         BUG_ON(!next_free);
1585         /* This will cause us to go off the end of our extent list. */
1586         BUG_ON(next_free >= count);
1587
1588         num_bytes = sizeof(struct ocfs2_extent_rec) * next_free;
1589
1590         memmove(&el->l_recs[1], &el->l_recs[0], num_bytes);
1591 }
1592
1593 static void ocfs2_rotate_leaf(struct ocfs2_extent_list *el,
1594                               struct ocfs2_extent_rec *insert_rec)
1595 {
1596         int i, insert_index, next_free, has_empty, num_bytes;
1597         u32 insert_cpos = le32_to_cpu(insert_rec->e_cpos);
1598         struct ocfs2_extent_rec *rec;
1599
1600         next_free = le16_to_cpu(el->l_next_free_rec);
1601         has_empty = ocfs2_is_empty_extent(&el->l_recs[0]);
1602
1603         BUG_ON(!next_free);
1604
1605         /* The tree code before us didn't allow enough room in the leaf. */
1606         BUG_ON(el->l_next_free_rec == el->l_count && !has_empty);
1607
1608         /*
1609          * The easiest way to approach this is to just remove the
1610          * empty extent and temporarily decrement next_free.
1611          */
1612         if (has_empty) {
1613                 /*
1614                  * If next_free was 1 (only an empty extent), this
1615                  * loop won't execute, which is fine. We still want
1616                  * the decrement above to happen.
1617                  */
1618                 for(i = 0; i < (next_free - 1); i++)
1619                         el->l_recs[i] = el->l_recs[i+1];
1620
1621                 next_free--;
1622         }
1623
1624         /*
1625          * Figure out what the new record index should be.
1626          */
1627         for(i = 0; i < next_free; i++) {
1628                 rec = &el->l_recs[i];
1629
1630                 if (insert_cpos < le32_to_cpu(rec->e_cpos))
1631                         break;
1632         }
1633         insert_index = i;
1634
1635         trace_ocfs2_rotate_leaf(insert_cpos, insert_index,
1636                                 has_empty, next_free,
1637                                 le16_to_cpu(el->l_count));
1638
1639         BUG_ON(insert_index < 0);
1640         BUG_ON(insert_index >= le16_to_cpu(el->l_count));
1641         BUG_ON(insert_index > next_free);
1642
1643         /*
1644          * No need to memmove if we're just adding to the tail.
1645          */
1646         if (insert_index != next_free) {
1647                 BUG_ON(next_free >= le16_to_cpu(el->l_count));
1648
1649                 num_bytes = next_free - insert_index;
1650                 num_bytes *= sizeof(struct ocfs2_extent_rec);
1651                 memmove(&el->l_recs[insert_index + 1],
1652                         &el->l_recs[insert_index],
1653                         num_bytes);
1654         }
1655
1656         /*
1657          * Either we had an empty extent, and need to re-increment or
1658          * there was no empty extent on a non full rightmost leaf node,
1659          * in which case we still need to increment.
1660          */
1661         next_free++;
1662         el->l_next_free_rec = cpu_to_le16(next_free);
1663         /*
1664          * Make sure none of the math above just messed up our tree.
1665          */
1666         BUG_ON(le16_to_cpu(el->l_next_free_rec) > le16_to_cpu(el->l_count));
1667
1668         el->l_recs[insert_index] = *insert_rec;
1669
1670 }
1671
1672 static void ocfs2_remove_empty_extent(struct ocfs2_extent_list *el)
1673 {
1674         int size, num_recs = le16_to_cpu(el->l_next_free_rec);
1675
1676         BUG_ON(num_recs == 0);
1677
1678         if (ocfs2_is_empty_extent(&el->l_recs[0])) {
1679                 num_recs--;
1680                 size = num_recs * sizeof(struct ocfs2_extent_rec);
1681                 memmove(&el->l_recs[0], &el->l_recs[1], size);
1682                 memset(&el->l_recs[num_recs], 0,
1683                        sizeof(struct ocfs2_extent_rec));
1684                 el->l_next_free_rec = cpu_to_le16(num_recs);
1685         }
1686 }
1687
1688 /*
1689  * Create an empty extent record .
1690  *
1691  * l_next_free_rec may be updated.
1692  *
1693  * If an empty extent already exists do nothing.
1694  */
1695 static void ocfs2_create_empty_extent(struct ocfs2_extent_list *el)
1696 {
1697         int next_free = le16_to_cpu(el->l_next_free_rec);
1698
1699         BUG_ON(le16_to_cpu(el->l_tree_depth) != 0);
1700
1701         if (next_free == 0)
1702                 goto set_and_inc;
1703
1704         if (ocfs2_is_empty_extent(&el->l_recs[0]))
1705                 return;
1706
1707         mlog_bug_on_msg(el->l_count == el->l_next_free_rec,
1708                         "Asked to create an empty extent in a full list:\n"
1709                         "count = %u, tree depth = %u",
1710                         le16_to_cpu(el->l_count),
1711                         le16_to_cpu(el->l_tree_depth));
1712
1713         ocfs2_shift_records_right(el);
1714
1715 set_and_inc:
1716         le16_add_cpu(&el->l_next_free_rec, 1);
1717         memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
1718 }
1719
1720 /*
1721  * For a rotation which involves two leaf nodes, the "root node" is
1722  * the lowest level tree node which contains a path to both leafs. This
1723  * resulting set of information can be used to form a complete "subtree"
1724  *
1725  * This function is passed two full paths from the dinode down to a
1726  * pair of adjacent leaves. It's task is to figure out which path
1727  * index contains the subtree root - this can be the root index itself
1728  * in a worst-case rotation.
1729  *
1730  * The array index of the subtree root is passed back.
1731  */
1732 int ocfs2_find_subtree_root(struct ocfs2_extent_tree *et,
1733                             struct ocfs2_path *left,
1734                             struct ocfs2_path *right)
1735 {
1736         int i = 0;
1737
1738         /*
1739          * Check that the caller passed in two paths from the same tree.
1740          */
1741         BUG_ON(path_root_bh(left) != path_root_bh(right));
1742
1743         do {
1744                 i++;
1745
1746                 /*
1747                  * The caller didn't pass two adjacent paths.
1748                  */
1749                 mlog_bug_on_msg(i > left->p_tree_depth,
1750                                 "Owner %llu, left depth %u, right depth %u\n"
1751                                 "left leaf blk %llu, right leaf blk %llu\n",
1752                                 (unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
1753                                 left->p_tree_depth, right->p_tree_depth,
1754                                 (unsigned long long)path_leaf_bh(left)->b_blocknr,
1755                                 (unsigned long long)path_leaf_bh(right)->b_blocknr);
1756         } while (left->p_node[i].bh->b_blocknr ==
1757                  right->p_node[i].bh->b_blocknr);
1758
1759         return i - 1;
1760 }
1761
1762 typedef void (path_insert_t)(void *, struct buffer_head *);
1763
1764 /*
1765  * Traverse a btree path in search of cpos, starting at root_el.
1766  *
1767  * This code can be called with a cpos larger than the tree, in which
1768  * case it will return the rightmost path.
1769  */
1770 static int __ocfs2_find_path(struct ocfs2_caching_info *ci,
1771                              struct ocfs2_extent_list *root_el, u32 cpos,
1772                              path_insert_t *func, void *data)
1773 {
1774         int i, ret = 0;
1775         u32 range;
1776         u64 blkno;
1777         struct buffer_head *bh = NULL;
1778         struct ocfs2_extent_block *eb;
1779         struct ocfs2_extent_list *el;
1780         struct ocfs2_extent_rec *rec;
1781
1782         el = root_el;
1783         while (el->l_tree_depth) {
1784                 if (le16_to_cpu(el->l_next_free_rec) == 0) {
1785                         ocfs2_error(ocfs2_metadata_cache_get_super(ci),
1786                                     "Owner %llu has empty extent list at depth %u\n",
1787                                     (unsigned long long)ocfs2_metadata_cache_owner(ci),
1788                                     le16_to_cpu(el->l_tree_depth));
1789                         ret = -EROFS;
1790                         goto out;
1791
1792                 }
1793
1794                 for(i = 0; i < le16_to_cpu(el->l_next_free_rec) - 1; i++) {
1795                         rec = &el->l_recs[i];
1796
1797                         /*
1798                          * In the case that cpos is off the allocation
1799                          * tree, this should just wind up returning the
1800                          * rightmost record.
1801                          */
1802                         range = le32_to_cpu(rec->e_cpos) +
1803                                 ocfs2_rec_clusters(el, rec);
1804                         if (cpos >= le32_to_cpu(rec->e_cpos) && cpos < range)
1805                             break;
1806                 }
1807
1808                 blkno = le64_to_cpu(el->l_recs[i].e_blkno);
1809                 if (blkno == 0) {
1810                         ocfs2_error(ocfs2_metadata_cache_get_super(ci),
1811                                     "Owner %llu has bad blkno in extent list at depth %u (index %d)\n",
1812                                     (unsigned long long)ocfs2_metadata_cache_owner(ci),
1813                                     le16_to_cpu(el->l_tree_depth), i);
1814                         ret = -EROFS;
1815                         goto out;
1816                 }
1817
1818                 brelse(bh);
1819                 bh = NULL;
1820                 ret = ocfs2_read_extent_block(ci, blkno, &bh);
1821                 if (ret) {
1822                         mlog_errno(ret);
1823                         goto out;
1824                 }
1825
1826                 eb = (struct ocfs2_extent_block *) bh->b_data;
1827                 el = &eb->h_list;
1828
1829                 if (le16_to_cpu(el->l_next_free_rec) >
1830                     le16_to_cpu(el->l_count)) {
1831                         ocfs2_error(ocfs2_metadata_cache_get_super(ci),
1832                                     "Owner %llu has bad count in extent list at block %llu (next free=%u, count=%u)\n",
1833                                     (unsigned long long)ocfs2_metadata_cache_owner(ci),
1834                                     (unsigned long long)bh->b_blocknr,
1835                                     le16_to_cpu(el->l_next_free_rec),
1836                                     le16_to_cpu(el->l_count));
1837                         ret = -EROFS;
1838                         goto out;
1839                 }
1840
1841                 if (func)
1842                         func(data, bh);
1843         }
1844
1845 out:
1846         /*
1847          * Catch any trailing bh that the loop didn't handle.
1848          */
1849         brelse(bh);
1850
1851         return ret;
1852 }
1853
1854 /*
1855  * Given an initialized path (that is, it has a valid root extent
1856  * list), this function will traverse the btree in search of the path
1857  * which would contain cpos.
1858  *
1859  * The path traveled is recorded in the path structure.
1860  *
1861  * Note that this will not do any comparisons on leaf node extent
1862  * records, so it will work fine in the case that we just added a tree
1863  * branch.
1864  */
1865 struct find_path_data {
1866         int index;
1867         struct ocfs2_path *path;
1868 };
1869 static void find_path_ins(void *data, struct buffer_head *bh)
1870 {
1871         struct find_path_data *fp = data;
1872
1873         get_bh(bh);
1874         ocfs2_path_insert_eb(fp->path, fp->index, bh);
1875         fp->index++;
1876 }
1877 int ocfs2_find_path(struct ocfs2_caching_info *ci,
1878                     struct ocfs2_path *path, u32 cpos)
1879 {
1880         struct find_path_data data;
1881
1882         data.index = 1;
1883         data.path = path;
1884         return __ocfs2_find_path(ci, path_root_el(path), cpos,
1885                                  find_path_ins, &data);
1886 }
1887
1888 static void find_leaf_ins(void *data, struct buffer_head *bh)
1889 {
1890         struct ocfs2_extent_block *eb =(struct ocfs2_extent_block *)bh->b_data;
1891         struct ocfs2_extent_list *el = &eb->h_list;
1892         struct buffer_head **ret = data;
1893
1894         /* We want to retain only the leaf block. */
1895         if (le16_to_cpu(el->l_tree_depth) == 0) {
1896                 get_bh(bh);
1897                 *ret = bh;
1898         }
1899 }
1900 /*
1901  * Find the leaf block in the tree which would contain cpos. No
1902  * checking of the actual leaf is done.
1903  *
1904  * Some paths want to call this instead of allocating a path structure
1905  * and calling ocfs2_find_path().
1906  *
1907  * This function doesn't handle non btree extent lists.
1908  */
1909 int ocfs2_find_leaf(struct ocfs2_caching_info *ci,
1910                     struct ocfs2_extent_list *root_el, u32 cpos,
1911                     struct buffer_head **leaf_bh)
1912 {
1913         int ret;
1914         struct buffer_head *bh = NULL;
1915
1916         ret = __ocfs2_find_path(ci, root_el, cpos, find_leaf_ins, &bh);
1917         if (ret) {
1918                 mlog_errno(ret);
1919                 goto out;
1920         }
1921
1922         *leaf_bh = bh;
1923 out:
1924         return ret;
1925 }
1926
1927 /*
1928  * Adjust the adjacent records (left_rec, right_rec) involved in a rotation.
1929  *
1930  * Basically, we've moved stuff around at the bottom of the tree and
1931  * we need to fix up the extent records above the changes to reflect
1932  * the new changes.
1933  *
1934  * left_rec: the record on the left.
1935  * right_rec: the record to the right of left_rec
1936  * right_child_el: is the child list pointed to by right_rec
1937  *
1938  * By definition, this only works on interior nodes.
1939  */
1940 static void ocfs2_adjust_adjacent_records(struct ocfs2_extent_rec *left_rec,
1941                                   struct ocfs2_extent_rec *right_rec,
1942                                   struct ocfs2_extent_list *right_child_el)
1943 {
1944         u32 left_clusters, right_end;
1945
1946         /*
1947          * Interior nodes never have holes. Their cpos is the cpos of
1948          * the leftmost record in their child list. Their cluster
1949          * count covers the full theoretical range of their child list
1950          * - the range between their cpos and the cpos of the record
1951          * immediately to their right.
1952          */
1953         left_clusters = le32_to_cpu(right_child_el->l_recs[0].e_cpos);
1954         if (!ocfs2_rec_clusters(right_child_el, &right_child_el->l_recs[0])) {
1955                 BUG_ON(right_child_el->l_tree_depth);
1956                 BUG_ON(le16_to_cpu(right_child_el->l_next_free_rec) <= 1);
1957                 left_clusters = le32_to_cpu(right_child_el->l_recs[1].e_cpos);
1958         }
1959         left_clusters -= le32_to_cpu(left_rec->e_cpos);
1960         left_rec->e_int_clusters = cpu_to_le32(left_clusters);
1961
1962         /*
1963          * Calculate the rightmost cluster count boundary before
1964          * moving cpos - we will need to adjust clusters after
1965          * updating e_cpos to keep the same highest cluster count.
1966          */
1967         right_end = le32_to_cpu(right_rec->e_cpos);
1968         right_end += le32_to_cpu(right_rec->e_int_clusters);
1969
1970         right_rec->e_cpos = left_rec->e_cpos;
1971         le32_add_cpu(&right_rec->e_cpos, left_clusters);
1972
1973         right_end -= le32_to_cpu(right_rec->e_cpos);
1974         right_rec->e_int_clusters = cpu_to_le32(right_end);
1975 }
1976
1977 /*
1978  * Adjust the adjacent root node records involved in a
1979  * rotation. left_el_blkno is passed in as a key so that we can easily
1980  * find it's index in the root list.
1981  */
1982 static void ocfs2_adjust_root_records(struct ocfs2_extent_list *root_el,
1983                                       struct ocfs2_extent_list *left_el,
1984                                       struct ocfs2_extent_list *right_el,
1985                                       u64 left_el_blkno)
1986 {
1987         int i;
1988
1989         BUG_ON(le16_to_cpu(root_el->l_tree_depth) <=
1990                le16_to_cpu(left_el->l_tree_depth));
1991
1992         for(i = 0; i < le16_to_cpu(root_el->l_next_free_rec) - 1; i++) {
1993                 if (le64_to_cpu(root_el->l_recs[i].e_blkno) == left_el_blkno)
1994                         break;
1995         }
1996
1997         /*
1998          * The path walking code should have never returned a root and
1999          * two paths which are not adjacent.
2000          */
2001         BUG_ON(i >= (le16_to_cpu(root_el->l_next_free_rec) - 1));
2002
2003         ocfs2_adjust_adjacent_records(&root_el->l_recs[i],
2004                                       &root_el->l_recs[i + 1], right_el);
2005 }
2006
2007 /*
2008  * We've changed a leaf block (in right_path) and need to reflect that
2009  * change back up the subtree.
2010  *
2011  * This happens in multiple places:
2012  *   - When we've moved an extent record from the left path leaf to the right
2013  *     path leaf to make room for an empty extent in the left path leaf.
2014  *   - When our insert into the right path leaf is at the leftmost edge
2015  *     and requires an update of the path immediately to it's left. This
2016  *     can occur at the end of some types of rotation and appending inserts.
2017  *   - When we've adjusted the last extent record in the left path leaf and the
2018  *     1st extent record in the right path leaf during cross extent block merge.
2019  */
2020 static void ocfs2_complete_edge_insert(handle_t *handle,
2021                                        struct ocfs2_path *left_path,
2022                                        struct ocfs2_path *right_path,
2023                                        int subtree_index)
2024 {
2025         int i, idx;
2026         struct ocfs2_extent_list *el, *left_el, *right_el;
2027         struct ocfs2_extent_rec *left_rec, *right_rec;
2028         struct buffer_head *root_bh = left_path->p_node[subtree_index].bh;
2029
2030         /*
2031          * Update the counts and position values within all the
2032          * interior nodes to reflect the leaf rotation we just did.
2033          *
2034          * The root node is handled below the loop.
2035          *
2036          * We begin the loop with right_el and left_el pointing to the
2037          * leaf lists and work our way up.
2038          *
2039          * NOTE: within this loop, left_el and right_el always refer
2040          * to the *child* lists.
2041          */
2042         left_el = path_leaf_el(left_path);
2043         right_el = path_leaf_el(right_path);
2044         for(i = left_path->p_tree_depth - 1; i > subtree_index; i--) {
2045                 trace_ocfs2_complete_edge_insert(i);
2046
2047                 /*
2048                  * One nice property of knowing that all of these
2049                  * nodes are below the root is that we only deal with
2050                  * the leftmost right node record and the rightmost
2051                  * left node record.
2052                  */
2053                 el = left_path->p_node[i].el;
2054                 idx = le16_to_cpu(left_el->l_next_free_rec) - 1;
2055                 left_rec = &el->l_recs[idx];
2056
2057                 el = right_path->p_node[i].el;
2058                 right_rec = &el->l_recs[0];
2059
2060                 ocfs2_adjust_adjacent_records(left_rec, right_rec, right_el);
2061
2062                 ocfs2_journal_dirty(handle, left_path->p_node[i].bh);
2063                 ocfs2_journal_dirty(handle, right_path->p_node[i].bh);
2064
2065                 /*
2066                  * Setup our list pointers now so that the current
2067                  * parents become children in the next iteration.
2068                  */
2069                 left_el = left_path->p_node[i].el;
2070                 right_el = right_path->p_node[i].el;
2071         }
2072
2073         /*
2074          * At the root node, adjust the two adjacent records which
2075          * begin our path to the leaves.
2076          */
2077
2078         el = left_path->p_node[subtree_index].el;
2079         left_el = left_path->p_node[subtree_index + 1].el;
2080         right_el = right_path->p_node[subtree_index + 1].el;
2081
2082         ocfs2_adjust_root_records(el, left_el, right_el,
2083                                   left_path->p_node[subtree_index + 1].bh->b_blocknr);
2084
2085         root_bh = left_path->p_node[subtree_index].bh;
2086
2087         ocfs2_journal_dirty(handle, root_bh);
2088 }
2089
2090 static int ocfs2_rotate_subtree_right(handle_t *handle,
2091                                       struct ocfs2_extent_tree *et,
2092                                       struct ocfs2_path *left_path,
2093                                       struct ocfs2_path *right_path,
2094                                       int subtree_index)
2095 {
2096         int ret, i;
2097         struct buffer_head *right_leaf_bh;
2098         struct buffer_head *left_leaf_bh = NULL;
2099         struct buffer_head *root_bh;
2100         struct ocfs2_extent_list *right_el, *left_el;
2101         struct ocfs2_extent_rec move_rec;
2102
2103         left_leaf_bh = path_leaf_bh(left_path);
2104         left_el = path_leaf_el(left_path);
2105
2106         if (left_el->l_next_free_rec != left_el->l_count) {
2107                 ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
2108                             "Inode %llu has non-full interior leaf node %llu (next free = %u)\n",
2109                             (unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
2110                             (unsigned long long)left_leaf_bh->b_blocknr,
2111                             le16_to_cpu(left_el->l_next_free_rec));
2112                 return -EROFS;
2113         }
2114
2115         /*
2116          * This extent block may already have an empty record, so we
2117          * return early if so.
2118          */
2119         if (ocfs2_is_empty_extent(&left_el->l_recs[0]))
2120                 return 0;
2121
2122         root_bh = left_path->p_node[subtree_index].bh;
2123         BUG_ON(root_bh != right_path->p_node[subtree_index].bh);
2124
2125         ret = ocfs2_path_bh_journal_access(handle, et->et_ci, right_path,
2126                                            subtree_index);
2127         if (ret) {
2128                 mlog_errno(ret);
2129                 goto out;
2130         }
2131
2132         for(i = subtree_index + 1; i < path_num_items(right_path); i++) {
2133                 ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
2134                                                    right_path, i);
2135                 if (ret) {
2136                         mlog_errno(ret);
2137                         goto out;
2138                 }
2139
2140                 ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
2141                                                    left_path, i);
2142                 if (ret) {
2143                         mlog_errno(ret);
2144                         goto out;
2145                 }
2146         }
2147
2148         right_leaf_bh = path_leaf_bh(right_path);
2149         right_el = path_leaf_el(right_path);
2150
2151         /* This is a code error, not a disk corruption. */
2152         mlog_bug_on_msg(!right_el->l_next_free_rec, "Inode %llu: Rotate fails "
2153                         "because rightmost leaf block %llu is empty\n",
2154                         (unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
2155                         (unsigned long long)right_leaf_bh->b_blocknr);
2156
2157         ocfs2_create_empty_extent(right_el);
2158
2159         ocfs2_journal_dirty(handle, right_leaf_bh);
2160
2161         /* Do the copy now. */
2162         i = le16_to_cpu(left_el->l_next_free_rec) - 1;
2163         move_rec = left_el->l_recs[i];
2164         right_el->l_recs[0] = move_rec;
2165
2166         /*
2167          * Clear out the record we just copied and shift everything
2168          * over, leaving an empty extent in the left leaf.
2169          *
2170          * We temporarily subtract from next_free_rec so that the
2171          * shift will lose the tail record (which is now defunct).
2172          */
2173         le16_add_cpu(&left_el->l_next_free_rec, -1);
2174         ocfs2_shift_records_right(left_el);
2175         memset(&left_el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
2176         le16_add_cpu(&left_el->l_next_free_rec, 1);
2177
2178         ocfs2_journal_dirty(handle, left_leaf_bh);
2179
2180         ocfs2_complete_edge_insert(handle, left_path, right_path,
2181                                    subtree_index);
2182
2183 out:
2184         return ret;
2185 }
2186
2187 /*
2188  * Given a full path, determine what cpos value would return us a path
2189  * containing the leaf immediately to the left of the current one.
2190  *
2191  * Will return zero if the path passed in is already the leftmost path.
2192  */
2193 int ocfs2_find_cpos_for_left_leaf(struct super_block *sb,
2194                                   struct ocfs2_path *path, u32 *cpos)
2195 {
2196         int i, j, ret = 0;
2197         u64 blkno;
2198         struct ocfs2_extent_list *el;
2199
2200         BUG_ON(path->p_tree_depth == 0);
2201
2202         *cpos = 0;
2203
2204         blkno = path_leaf_bh(path)->b_blocknr;
2205
2206         /* Start at the tree node just above the leaf and work our way up. */
2207         i = path->p_tree_depth - 1;
2208         while (i >= 0) {
2209                 el = path->p_node[i].el;
2210
2211                 /*
2212                  * Find the extent record just before the one in our
2213                  * path.
2214                  */
2215                 for(j = 0; j < le16_to_cpu(el->l_next_free_rec); j++) {
2216                         if (le64_to_cpu(el->l_recs[j].e_blkno) == blkno) {
2217                                 if (j == 0) {
2218                                         if (i == 0) {
2219                                                 /*
2220                                                  * We've determined that the
2221                                                  * path specified is already
2222                                                  * the leftmost one - return a
2223                                                  * cpos of zero.
2224                                                  */
2225                                                 goto out;
2226                                         }
2227                                         /*
2228                                          * The leftmost record points to our
2229                                          * leaf - we need to travel up the
2230                                          * tree one level.
2231                                          */
2232                                         goto next_node;
2233                                 }
2234
2235                                 *cpos = le32_to_cpu(el->l_recs[j - 1].e_cpos);
2236                                 *cpos = *cpos + ocfs2_rec_clusters(el,
2237                                                            &el->l_recs[j - 1]);
2238                                 *cpos = *cpos - 1;
2239                                 goto out;
2240                         }
2241                 }
2242
2243                 /*
2244                  * If we got here, we never found a valid node where
2245                  * the tree indicated one should be.
2246                  */
2247                 ocfs2_error(sb, "Invalid extent tree at extent block %llu\n",
2248                             (unsigned long long)blkno);
2249                 ret = -EROFS;
2250                 goto out;
2251
2252 next_node:
2253                 blkno = path->p_node[i].bh->b_blocknr;
2254                 i--;
2255         }
2256
2257 out:
2258         return ret;
2259 }
2260
2261 /*
2262  * Extend the transaction by enough credits to complete the rotation,
2263  * and still leave at least the original number of credits allocated
2264  * to this transaction.
2265  */
2266 static int ocfs2_extend_rotate_transaction(handle_t *handle, int subtree_depth,
2267                                            int op_credits,
2268                                            struct ocfs2_path *path)
2269 {
2270         int ret = 0;
2271         int credits = (path->p_tree_depth - subtree_depth) * 2 + 1 + op_credits;
2272
2273         if (handle->h_buffer_credits < credits)
2274                 ret = ocfs2_extend_trans(handle,
2275                                          credits - handle->h_buffer_credits);
2276
2277         return ret;
2278 }
2279
2280 /*
2281  * Trap the case where we're inserting into the theoretical range past
2282  * the _actual_ left leaf range. Otherwise, we'll rotate a record
2283  * whose cpos is less than ours into the right leaf.
2284  *
2285  * It's only necessary to look at the rightmost record of the left
2286  * leaf because the logic that calls us should ensure that the
2287  * theoretical ranges in the path components above the leaves are
2288  * correct.
2289  */
2290 static int ocfs2_rotate_requires_path_adjustment(struct ocfs2_path *left_path,
2291                                                  u32 insert_cpos)
2292 {
2293         struct ocfs2_extent_list *left_el;
2294         struct ocfs2_extent_rec *rec;
2295         int next_free;
2296
2297         left_el = path_leaf_el(left_path);
2298         next_free = le16_to_cpu(left_el->l_next_free_rec);
2299         rec = &left_el->l_recs[next_free - 1];
2300
2301         if (insert_cpos > le32_to_cpu(rec->e_cpos))
2302                 return 1;
2303         return 0;
2304 }
2305
2306 static int ocfs2_leftmost_rec_contains(struct ocfs2_extent_list *el, u32 cpos)
2307 {
2308         int next_free = le16_to_cpu(el->l_next_free_rec);
2309         unsigned int range;
2310         struct ocfs2_extent_rec *rec;
2311
2312         if (next_free == 0)
2313                 return 0;
2314
2315         rec = &el->l_recs[0];
2316         if (ocfs2_is_empty_extent(rec)) {
2317                 /* Empty list. */
2318                 if (next_free == 1)
2319                         return 0;
2320                 rec = &el->l_recs[1];
2321         }
2322
2323         range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
2324         if (cpos >= le32_to_cpu(rec->e_cpos) && cpos < range)
2325                 return 1;
2326         return 0;
2327 }
2328
2329 /*
2330  * Rotate all the records in a btree right one record, starting at insert_cpos.
2331  *
2332  * The path to the rightmost leaf should be passed in.
2333  *
2334  * The array is assumed to be large enough to hold an entire path (tree depth).
2335  *
2336  * Upon successful return from this function:
2337  *
2338  * - The 'right_path' array will contain a path to the leaf block
2339  *   whose range contains e_cpos.
2340  * - That leaf block will have a single empty extent in list index 0.
2341  * - In the case that the rotation requires a post-insert update,
2342  *   *ret_left_path will contain a valid path which can be passed to
2343  *   ocfs2_insert_path().
2344  */
2345 static int ocfs2_rotate_tree_right(handle_t *handle,
2346                                    struct ocfs2_extent_tree *et,
2347                                    enum ocfs2_split_type split,
2348                                    u32 insert_cpos,
2349                                    struct ocfs2_path *right_path,
2350                                    struct ocfs2_path **ret_left_path)
2351 {
2352         int ret, start, orig_credits = handle->h_buffer_credits;
2353         u32 cpos;
2354         struct ocfs2_path *left_path = NULL;
2355         struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
2356
2357         *ret_left_path = NULL;
2358
2359         left_path = ocfs2_new_path_from_path(right_path);
2360         if (!left_path) {
2361                 ret = -ENOMEM;
2362                 mlog_errno(ret);
2363                 goto out;
2364         }
2365
2366         ret = ocfs2_find_cpos_for_left_leaf(sb, right_path, &cpos);
2367         if (ret) {
2368                 mlog_errno(ret);
2369                 goto out;
2370         }
2371
2372         trace_ocfs2_rotate_tree_right(
2373                 (unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
2374                 insert_cpos, cpos);
2375
2376         /*
2377          * What we want to do here is:
2378          *
2379          * 1) Start with the rightmost path.
2380          *
2381          * 2) Determine a path to the leaf block directly to the left
2382          *    of that leaf.
2383          *
2384          * 3) Determine the 'subtree root' - the lowest level tree node
2385          *    which contains a path to both leaves.
2386          *
2387          * 4) Rotate the subtree.
2388          *
2389          * 5) Find the next subtree by considering the left path to be
2390          *    the new right path.
2391          *
2392          * The check at the top of this while loop also accepts
2393          * insert_cpos == cpos because cpos is only a _theoretical_
2394          * value to get us the left path - insert_cpos might very well
2395          * be filling that hole.
2396          *
2397          * Stop at a cpos of '0' because we either started at the
2398          * leftmost branch (i.e., a tree with one branch and a
2399          * rotation inside of it), or we've gone as far as we can in
2400          * rotating subtrees.
2401          */
2402         while (cpos && insert_cpos <= cpos) {
2403                 trace_ocfs2_rotate_tree_right(
2404                         (unsigned long long)
2405                         ocfs2_metadata_cache_owner(et->et_ci),
2406                         insert_cpos, cpos);
2407
2408                 ret = ocfs2_find_path(et->et_ci, left_path, cpos);
2409                 if (ret) {
2410                         mlog_errno(ret);
2411                         goto out;
2412                 }
2413
2414                 mlog_bug_on_msg(path_leaf_bh(left_path) ==
2415                                 path_leaf_bh(right_path),
2416                                 "Owner %llu: error during insert of %u "
2417                                 "(left path cpos %u) results in two identical "
2418                                 "paths ending at %llu\n",
2419                                 (unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
2420                                 insert_cpos, cpos,
2421                                 (unsigned long long)
2422                                 path_leaf_bh(left_path)->b_blocknr);
2423
2424                 if (split == SPLIT_NONE &&
2425                     ocfs2_rotate_requires_path_adjustment(left_path,
2426                                                           insert_cpos)) {
2427
2428                         /*
2429                          * We've rotated the tree as much as we
2430                          * should. The rest is up to
2431                          * ocfs2_insert_path() to complete, after the
2432                          * record insertion. We indicate this
2433                          * situation by returning the left path.
2434                          *
2435                          * The reason we don't adjust the records here
2436                          * before the record insert is that an error
2437                          * later might break the rule where a parent
2438                          * record e_cpos will reflect the actual
2439                          * e_cpos of the 1st nonempty record of the
2440                          * child list.
2441                          */
2442                         *ret_left_path = left_path;
2443                         goto out_ret_path;
2444                 }
2445
2446                 start = ocfs2_find_subtree_root(et, left_path, right_path);
2447
2448                 trace_ocfs2_rotate_subtree(start,
2449                         (unsigned long long)
2450                         right_path->p_node[start].bh->b_blocknr,
2451                         right_path->p_tree_depth);
2452
2453                 ret = ocfs2_extend_rotate_transaction(handle, start,
2454                                                       orig_credits, right_path);
2455                 if (ret) {
2456                         mlog_errno(ret);
2457                         goto out;
2458                 }
2459
2460                 ret = ocfs2_rotate_subtree_right(handle, et, left_path,
2461                                                  right_path, start);
2462                 if (ret) {
2463                         mlog_errno(ret);
2464                         goto out;
2465                 }
2466
2467                 if (split != SPLIT_NONE &&
2468                     ocfs2_leftmost_rec_contains(path_leaf_el(right_path),
2469                                                 insert_cpos)) {
2470                         /*
2471                          * A rotate moves the rightmost left leaf
2472                          * record over to the leftmost right leaf
2473                          * slot. If we're doing an extent split
2474                          * instead of a real insert, then we have to
2475                          * check that the extent to be split wasn't
2476                          * just moved over. If it was, then we can
2477                          * exit here, passing left_path back -
2478                          * ocfs2_split_extent() is smart enough to
2479                          * search both leaves.
2480                          */
2481                         *ret_left_path = left_path;
2482                         goto out_ret_path;
2483                 }
2484
2485                 /*
2486                  * There is no need to re-read the next right path
2487                  * as we know that it'll be our current left
2488                  * path. Optimize by copying values instead.
2489                  */
2490                 ocfs2_mv_path(right_path, left_path);
2491
2492                 ret = ocfs2_find_cpos_for_left_leaf(sb, right_path, &cpos);
2493                 if (ret) {
2494                         mlog_errno(ret);
2495                         goto out;
2496                 }
2497         }
2498
2499 out:
2500         ocfs2_free_path(left_path);
2501
2502 out_ret_path:
2503         return ret;
2504 }
2505
2506 static int ocfs2_update_edge_lengths(handle_t *handle,
2507                                      struct ocfs2_extent_tree *et,
2508                                      struct ocfs2_path *path)
2509 {
2510         int i, idx, ret;
2511         struct ocfs2_extent_rec *rec;
2512         struct ocfs2_extent_list *el;
2513         struct ocfs2_extent_block *eb;
2514         u32 range;
2515
2516         ret = ocfs2_journal_access_path(et->et_ci, handle, path);
2517         if (ret) {
2518                 mlog_errno(ret);
2519                 goto out;
2520         }
2521
2522         /* Path should always be rightmost. */
2523         eb = (struct ocfs2_extent_block *)path_leaf_bh(path)->b_data;
2524         BUG_ON(eb->h_next_leaf_blk != 0ULL);
2525
2526         el = &eb->h_list;
2527         BUG_ON(le16_to_cpu(el->l_next_free_rec) == 0);
2528         idx = le16_to_cpu(el->l_next_free_rec) - 1;
2529         rec = &el->l_recs[idx];
2530         range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
2531
2532         for (i = 0; i < path->p_tree_depth; i++) {
2533                 el = path->p_node[i].el;
2534                 idx = le16_to_cpu(el->l_next_free_rec) - 1;
2535                 rec = &el->l_recs[idx];
2536
2537                 rec->e_int_clusters = cpu_to_le32(range);
2538                 le32_add_cpu(&rec->e_int_clusters, -le32_to_cpu(rec->e_cpos));
2539
2540                 ocfs2_journal_dirty(handle, path->p_node[i].bh);
2541         }
2542 out:
2543         return ret;
2544 }
2545
2546 static void ocfs2_unlink_path(handle_t *handle,
2547                               struct ocfs2_extent_tree *et,
2548                               struct ocfs2_cached_dealloc_ctxt *dealloc,
2549                               struct ocfs2_path *path, int unlink_start)
2550 {
2551         int ret, i;
2552         struct ocfs2_extent_block *eb;
2553         struct ocfs2_extent_list *el;
2554         struct buffer_head *bh;
2555
2556         for(i = unlink_start; i < path_num_items(path); i++) {
2557                 bh = path->p_node[i].bh;
2558
2559                 eb = (struct ocfs2_extent_block *)bh->b_data;
2560                 /*
2561                  * Not all nodes might have had their final count
2562                  * decremented by the caller - handle this here.
2563                  */
2564                 el = &eb->h_list;
2565                 if (le16_to_cpu(el->l_next_free_rec) > 1) {
2566                         mlog(ML_ERROR,
2567                              "Inode %llu, attempted to remove extent block "
2568                              "%llu with %u records\n",
2569                              (unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
2570                              (unsigned long long)le64_to_cpu(eb->h_blkno),
2571                              le16_to_cpu(el->l_next_free_rec));
2572
2573                         ocfs2_journal_dirty(handle, bh);
2574                         ocfs2_remove_from_cache(et->et_ci, bh);
2575                         continue;
2576                 }
2577
2578                 el->l_next_free_rec = 0;
2579                 memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
2580
2581                 ocfs2_journal_dirty(handle, bh);
2582
2583                 ret = ocfs2_cache_extent_block_free(dealloc, eb);
2584                 if (ret)
2585                         mlog_errno(ret);
2586
2587                 ocfs2_remove_from_cache(et->et_ci, bh);
2588         }
2589 }
2590
2591 static void ocfs2_unlink_subtree(handle_t *handle,
2592                                  struct ocfs2_extent_tree *et,
2593                                  struct ocfs2_path *left_path,
2594                                  struct ocfs2_path *right_path,
2595                                  int subtree_index,
2596                                  struct ocfs2_cached_dealloc_ctxt *dealloc)
2597 {
2598         int i;
2599         struct buffer_head *root_bh = left_path->p_node[subtree_index].bh;
2600         struct ocfs2_extent_list *root_el = left_path->p_node[subtree_index].el;
2601         struct ocfs2_extent_list *el;
2602         struct ocfs2_extent_block *eb;
2603
2604         el = path_leaf_el(left_path);
2605
2606         eb = (struct ocfs2_extent_block *)right_path->p_node[subtree_index + 1].bh->b_data;
2607
2608         for(i = 1; i < le16_to_cpu(root_el->l_next_free_rec); i++)
2609                 if (root_el->l_recs[i].e_blkno == eb->h_blkno)
2610                         break;
2611
2612         BUG_ON(i >= le16_to_cpu(root_el->l_next_free_rec));
2613
2614         memset(&root_el->l_recs[i], 0, sizeof(struct ocfs2_extent_rec));
2615         le16_add_cpu(&root_el->l_next_free_rec, -1);
2616
2617         eb = (struct ocfs2_extent_block *)path_leaf_bh(left_path)->b_data;
2618         eb->h_next_leaf_blk = 0;
2619
2620         ocfs2_journal_dirty(handle, root_bh);
2621         ocfs2_journal_dirty(handle, path_leaf_bh(left_path));
2622
2623         ocfs2_unlink_path(handle, et, dealloc, right_path,
2624                           subtree_index + 1);
2625 }
2626
2627 static int ocfs2_rotate_subtree_left(handle_t *handle,
2628                                      struct ocfs2_extent_tree *et,
2629                                      struct ocfs2_path *left_path,
2630                                      struct ocfs2_path *right_path,
2631                                      int subtree_index,
2632                                      struct ocfs2_cached_dealloc_ctxt *dealloc,
2633                                      int *deleted)
2634 {
2635         int ret, i, del_right_subtree = 0, right_has_empty = 0;
2636         struct buffer_head *root_bh, *et_root_bh = path_root_bh(right_path);
2637         struct ocfs2_extent_list *right_leaf_el, *left_leaf_el;
2638         struct ocfs2_extent_block *eb;
2639
2640         *deleted = 0;
2641
2642         right_leaf_el = path_leaf_el(right_path);
2643         left_leaf_el = path_leaf_el(left_path);
2644         root_bh = left_path->p_node[subtree_index].bh;
2645         BUG_ON(root_bh != right_path->p_node[subtree_index].bh);
2646
2647         if (!ocfs2_is_empty_extent(&left_leaf_el->l_recs[0]))
2648                 return 0;
2649
2650         eb = (struct ocfs2_extent_block *)path_leaf_bh(right_path)->b_data;
2651         if (ocfs2_is_empty_extent(&right_leaf_el->l_recs[0])) {
2652                 /*
2653                  * It's legal for us to proceed if the right leaf is
2654                  * the rightmost one and it has an empty extent. There
2655                  * are two cases to handle - whether the leaf will be
2656                  * empty after removal or not. If the leaf isn't empty
2657                  * then just remove the empty extent up front. The
2658                  * next block will handle empty leaves by flagging
2659                  * them for unlink.
2660                  *
2661                  * Non rightmost leaves will throw -EAGAIN and the
2662                  * caller can manually move the subtree and retry.
2663                  */
2664
2665                 if (eb->h_next_leaf_blk != 0ULL)
2666                         return -EAGAIN;
2667
2668                 if (le16_to_cpu(right_leaf_el->l_next_free_rec) > 1) {
2669                         ret = ocfs2_journal_access_eb(handle, et->et_ci,
2670                                                       path_leaf_bh(right_path),
2671                                                       OCFS2_JOURNAL_ACCESS_WRITE);
2672                         if (ret) {
2673                                 mlog_errno(ret);
2674                                 goto out;
2675                         }
2676
2677                         ocfs2_remove_empty_extent(right_leaf_el);
2678                 } else
2679                         right_has_empty = 1;
2680         }
2681
2682         if (eb->h_next_leaf_blk == 0ULL &&
2683             le16_to_cpu(right_leaf_el->l_next_free_rec) == 1) {
2684                 /*
2685                  * We have to update i_last_eb_blk during the meta
2686                  * data delete.
2687                  */
2688                 ret = ocfs2_et_root_journal_access(handle, et,
2689                                                    OCFS2_JOURNAL_ACCESS_WRITE);
2690                 if (ret) {
2691                         mlog_errno(ret);
2692                         goto out;
2693                 }
2694
2695                 del_right_subtree = 1;
2696         }
2697
2698         /*
2699          * Getting here with an empty extent in the right path implies
2700          * that it's the rightmost path and will be deleted.
2701          */
2702         BUG_ON(right_has_empty && !del_right_subtree);
2703
2704         ret = ocfs2_path_bh_journal_access(handle, et->et_ci, right_path,
2705                                            subtree_index);
2706         if (ret) {
2707                 mlog_errno(ret);
2708                 goto out;
2709         }
2710
2711         for(i = subtree_index + 1; i < path_num_items(right_path); i++) {
2712                 ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
2713                                                    right_path, i);
2714                 if (ret) {
2715                         mlog_errno(ret);
2716                         goto out;
2717                 }
2718
2719                 ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
2720                                                    left_path, i);
2721                 if (ret) {
2722                         mlog_errno(ret);
2723                         goto out;
2724                 }
2725         }
2726
2727         if (!right_has_empty) {
2728                 /*
2729                  * Only do this if we're moving a real
2730                  * record. Otherwise, the action is delayed until
2731                  * after removal of the right path in which case we
2732                  * can do a simple shift to remove the empty extent.
2733                  */
2734                 ocfs2_rotate_leaf(left_leaf_el, &right_leaf_el->l_recs[0]);
2735                 memset(&right_leaf_el->l_recs[0], 0,
2736                        sizeof(struct ocfs2_extent_rec));
2737         }
2738         if (eb->h_next_leaf_blk == 0ULL) {
2739                 /*
2740                  * Move recs over to get rid of empty extent, decrease
2741                  * next_free. This is allowed to remove the last
2742                  * extent in our leaf (setting l_next_free_rec to
2743                  * zero) - the delete code below won't care.
2744                  */
2745                 ocfs2_remove_empty_extent(right_leaf_el);
2746         }
2747
2748         ocfs2_journal_dirty(handle, path_leaf_bh(left_path));
2749         ocfs2_journal_dirty(handle, path_leaf_bh(right_path));
2750
2751         if (del_right_subtree) {
2752                 ocfs2_unlink_subtree(handle, et, left_path, right_path,
2753                                      subtree_index, dealloc);
2754                 ret = ocfs2_update_edge_lengths(handle, et, left_path);
2755                 if (ret) {
2756                         mlog_errno(ret);
2757                         goto out;
2758                 }
2759
2760                 eb = (struct ocfs2_extent_block *)path_leaf_bh(left_path)->b_data;
2761                 ocfs2_et_set_last_eb_blk(et, le64_to_cpu(eb->h_blkno));
2762
2763                 /*
2764                  * Removal of the extent in the left leaf was skipped
2765                  * above so we could delete the right path
2766                  * 1st.
2767                  */
2768                 if (right_has_empty)
2769                         ocfs2_remove_empty_extent(left_leaf_el);
2770
2771                 ocfs2_journal_dirty(handle, et_root_bh);
2772
2773                 *deleted = 1;
2774         } else
2775                 ocfs2_complete_edge_insert(handle, left_path, right_path,
2776                                            subtree_index);
2777
2778 out:
2779         return ret;
2780 }
2781
2782 /*
2783  * Given a full path, determine what cpos value would return us a path
2784  * containing the leaf immediately to the right of the current one.
2785  *
2786  * Will return zero if the path passed in is already the rightmost path.
2787  *
2788  * This looks similar, but is subtly different to
2789  * ocfs2_find_cpos_for_left_leaf().
2790  */
2791 int ocfs2_find_cpos_for_right_leaf(struct super_block *sb,
2792                                    struct ocfs2_path *path, u32 *cpos)
2793 {
2794         int i, j, ret = 0;
2795         u64 blkno;
2796         struct ocfs2_extent_list *el;
2797
2798         *cpos = 0;
2799
2800         if (path->p_tree_depth == 0)
2801                 return 0;
2802
2803         blkno = path_leaf_bh(path)->b_blocknr;
2804
2805         /* Start at the tree node just above the leaf and work our way up. */
2806         i = path->p_tree_depth - 1;
2807         while (i >= 0) {
2808                 int next_free;
2809
2810                 el = path->p_node[i].el;
2811
2812                 /*
2813                  * Find the extent record just after the one in our
2814                  * path.
2815                  */
2816                 next_free = le16_to_cpu(el->l_next_free_rec);
2817                 for(j = 0; j < le16_to_cpu(el->l_next_free_rec); j++) {
2818                         if (le64_to_cpu(el->l_recs[j].e_blkno) == blkno) {
2819                                 if (j == (next_free - 1)) {
2820                                         if (i == 0) {
2821                                                 /*
2822                                                  * We've determined that the
2823                                                  * path specified is already
2824                                                  * the rightmost one - return a
2825                                                  * cpos of zero.
2826                                                  */
2827                                                 goto out;
2828                                         }
2829                                         /*
2830                                          * The rightmost record points to our
2831                                          * leaf - we need to travel up the
2832                                          * tree one level.
2833                                          */
2834                                         goto next_node;
2835                                 }
2836
2837                                 *cpos = le32_to_cpu(el->l_recs[j + 1].e_cpos);
2838                                 goto out;
2839                         }
2840                 }
2841
2842                 /*
2843                  * If we got here, we never found a valid node where
2844                  * the tree indicated one should be.
2845                  */
2846                 ocfs2_error(sb, "Invalid extent tree at extent block %llu\n",
2847                             (unsigned long long)blkno);
2848                 ret = -EROFS;
2849                 goto out;
2850
2851 next_node:
2852                 blkno = path->p_node[i].bh->b_blocknr;
2853                 i--;
2854         }
2855
2856 out:
2857         return ret;
2858 }
2859
2860 static int ocfs2_rotate_rightmost_leaf_left(handle_t *handle,
2861                                             struct ocfs2_extent_tree *et,
2862                                             struct ocfs2_path *path)
2863 {
2864         int ret;
2865         struct buffer_head *bh = path_leaf_bh(path);
2866         struct ocfs2_extent_list *el = path_leaf_el(path);
2867
2868         if (!ocfs2_is_empty_extent(&el->l_recs[0]))
2869                 return 0;
2870
2871         ret = ocfs2_path_bh_journal_access(handle, et->et_ci, path,
2872                                            path_num_items(path) - 1);
2873         if (ret) {
2874                 mlog_errno(ret);
2875                 goto out;
2876         }
2877
2878         ocfs2_remove_empty_extent(el);
2879         ocfs2_journal_dirty(handle, bh);
2880
2881 out:
2882         return ret;
2883 }
2884
2885 static int __ocfs2_rotate_tree_left(handle_t *handle,
2886                                     struct ocfs2_extent_tree *et,
2887                                     int orig_credits,
2888                                     struct ocfs2_path *path,
2889                                     struct ocfs2_cached_dealloc_ctxt *dealloc,
2890                                     struct ocfs2_path **empty_extent_path)
2891 {
2892         int ret, subtree_root, deleted;
2893         u32 right_cpos;
2894         struct ocfs2_path *left_path = NULL;
2895         struct ocfs2_path *right_path = NULL;
2896         struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
2897
2898         if (!ocfs2_is_empty_extent(&(path_leaf_el(path)->l_recs[0])))
2899                 return 0;
2900
2901         *empty_extent_path = NULL;
2902
2903         ret = ocfs2_find_cpos_for_right_leaf(sb, path, &right_cpos);
2904         if (ret) {
2905                 mlog_errno(ret);
2906                 goto out;
2907         }
2908
2909         left_path = ocfs2_new_path_from_path(path);
2910         if (!left_path) {
2911                 ret = -ENOMEM;
2912                 mlog_errno(ret);
2913                 goto out;
2914         }
2915
2916         ocfs2_cp_path(left_path, path);
2917
2918         right_path = ocfs2_new_path_from_path(path);
2919         if (!right_path) {
2920                 ret = -ENOMEM;
2921                 mlog_errno(ret);
2922                 goto out;
2923         }
2924
2925         while (right_cpos) {
2926                 ret = ocfs2_find_path(et->et_ci, right_path, right_cpos);
2927                 if (ret) {
2928                         mlog_errno(ret);
2929                         goto out;
2930                 }
2931
2932                 subtree_root = ocfs2_find_subtree_root(et, left_path,
2933                                                        right_path);
2934
2935                 trace_ocfs2_rotate_subtree(subtree_root,
2936                      (unsigned long long)
2937                      right_path->p_node[subtree_root].bh->b_blocknr,
2938                      right_path->p_tree_depth);
2939
2940                 ret = ocfs2_extend_rotate_transaction(handle, 0,
2941                                                       orig_credits, left_path);
2942                 if (ret) {
2943                         mlog_errno(ret);
2944                         goto out;
2945                 }
2946
2947                 /*
2948                  * Caller might still want to make changes to the
2949                  * tree root, so re-add it to the journal here.
2950                  */
2951                 ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
2952                                                    left_path, 0);
2953                 if (ret) {
2954                         mlog_errno(ret);
2955                         goto out;
2956                 }
2957
2958                 ret = ocfs2_rotate_subtree_left(handle, et, left_path,
2959                                                 right_path, subtree_root,
2960                                                 dealloc, &deleted);
2961                 if (ret == -EAGAIN) {
2962                         /*
2963                          * The rotation has to temporarily stop due to
2964                          * the right subtree having an empty
2965                          * extent. Pass it back to the caller for a
2966                          * fixup.
2967                          */
2968                         *empty_extent_path = right_path;
2969                         right_path = NULL;
2970                         goto out;
2971                 }
2972                 if (ret) {
2973                         mlog_errno(ret);
2974                         goto out;
2975                 }
2976
2977                 /*
2978                  * The subtree rotate might have removed records on
2979                  * the rightmost edge. If so, then rotation is
2980                  * complete.
2981                  */
2982                 if (deleted)
2983                         break;
2984
2985                 ocfs2_mv_path(left_path, right_path);
2986
2987                 ret = ocfs2_find_cpos_for_right_leaf(sb, left_path,
2988                                                      &right_cpos);
2989                 if (ret) {
2990                         mlog_errno(ret);
2991                         goto out;
2992                 }
2993         }
2994
2995 out:
2996         ocfs2_free_path(right_path);
2997         ocfs2_free_path(left_path);
2998
2999         return ret;
3000 }
3001
3002 static int ocfs2_remove_rightmost_path(handle_t *handle,
3003                                 struct ocfs2_extent_tree *et,
3004                                 struct ocfs2_path *path,
3005                                 struct ocfs2_cached_dealloc_ctxt *dealloc)
3006 {
3007         int ret, subtree_index;
3008         u32 cpos;
3009         struct ocfs2_path *left_path = NULL;
3010         struct ocfs2_extent_block *eb;
3011         struct ocfs2_extent_list *el;
3012
3013         ret = ocfs2_et_sanity_check(et);
3014         if (ret)
3015                 goto out;
3016
3017         ret = ocfs2_journal_access_path(et->et_ci, handle, path);
3018         if (ret) {
3019                 mlog_errno(ret);
3020                 goto out;
3021         }
3022
3023         ret = ocfs2_find_cpos_for_left_leaf(ocfs2_metadata_cache_get_super(et->et_ci),
3024                                             path, &cpos);
3025         if (ret) {
3026                 mlog_errno(ret);
3027                 goto out;
3028         }
3029
3030         if (cpos) {
3031                 /*
3032                  * We have a path to the left of this one - it needs
3033                  * an update too.
3034                  */
3035                 left_path = ocfs2_new_path_from_path(path);
3036                 if (!left_path) {
3037                         ret = -ENOMEM;
3038                         mlog_errno(ret);
3039                         goto out;
3040                 }
3041
3042                 ret = ocfs2_find_path(et->et_ci, left_path, cpos);
3043                 if (ret) {
3044                         mlog_errno(ret);
3045                         goto out;
3046                 }
3047
3048                 ret = ocfs2_journal_access_path(et->et_ci, handle, left_path);
3049                 if (ret) {
3050                         mlog_errno(ret);
3051                         goto out;
3052                 }
3053
3054                 subtree_index = ocfs2_find_subtree_root(et, left_path, path);
3055
3056                 ocfs2_unlink_subtree(handle, et, left_path, path,
3057                                      subtree_index, dealloc);
3058                 ret = ocfs2_update_edge_lengths(handle, et, left_path);
3059                 if (ret) {
3060                         mlog_errno(ret);
3061                         goto out;
3062                 }
3063
3064                 eb = (struct ocfs2_extent_block *)path_leaf_bh(left_path)->b_data;
3065                 ocfs2_et_set_last_eb_blk(et, le64_to_cpu(eb->h_blkno));
3066         } else {
3067                 /*
3068                  * 'path' is also the leftmost path which
3069                  * means it must be the only one. This gets
3070                  * handled differently because we want to
3071                  * revert the root back to having extents
3072                  * in-line.
3073                  */
3074                 ocfs2_unlink_path(handle, et, dealloc, path, 1);
3075
3076                 el = et->et_root_el;
3077                 el->l_tree_depth = 0;
3078                 el->l_next_free_rec = 0;
3079                 memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
3080
3081                 ocfs2_et_set_last_eb_blk(et, 0);
3082         }
3083
3084         ocfs2_journal_dirty(handle, path_root_bh(path));
3085
3086 out:
3087         ocfs2_free_path(left_path);
3088         return ret;
3089 }
3090
3091 static int ocfs2_remove_rightmost_empty_extent(struct ocfs2_super *osb,
3092                                 struct ocfs2_extent_tree *et,
3093                                 struct ocfs2_path *path,
3094                                 struct ocfs2_cached_dealloc_ctxt *dealloc)
3095 {
3096         handle_t *handle;
3097         int ret;
3098         int credits = path->p_tree_depth * 2 + 1;
3099
3100         handle = ocfs2_start_trans(osb, credits);
3101         if (IS_ERR(handle)) {
3102                 ret = PTR_ERR(handle);
3103                 mlog_errno(ret);
3104                 return ret;
3105         }
3106
3107         ret = ocfs2_remove_rightmost_path(handle, et, path, dealloc);
3108         if (ret)
3109                 mlog_errno(ret);
3110
3111         ocfs2_commit_trans(osb, handle);
3112         return ret;
3113 }
3114
3115 /*
3116  * Left rotation of btree records.
3117  *
3118  * In many ways, this is (unsurprisingly) the opposite of right
3119  * rotation. We start at some non-rightmost path containing an empty
3120  * extent in the leaf block. The code works its way to the rightmost
3121  * path by rotating records to the left in every subtree.
3122  *
3123  * This is used by any code which reduces the number of extent records
3124  * in a leaf. After removal, an empty record should be placed in the
3125  * leftmost list position.
3126  *
3127  * This won't handle a length update of the rightmost path records if
3128  * the rightmost tree leaf record is removed so the caller is
3129  * responsible for detecting and correcting that.
3130  */
3131 static int ocfs2_rotate_tree_left(handle_t *handle,
3132                                   struct ocfs2_extent_tree *et,
3133                                   struct ocfs2_path *path,
3134                                   struct ocfs2_cached_dealloc_ctxt *dealloc)
3135 {
3136         int ret, orig_credits = handle->h_buffer_credits;
3137         struct ocfs2_path *tmp_path = NULL, *restart_path = NULL;
3138         struct ocfs2_extent_block *eb;
3139         struct ocfs2_extent_list *el;
3140
3141         el = path_leaf_el(path);
3142         if (!ocfs2_is_empty_extent(&el->l_recs[0]))
3143                 return 0;
3144
3145         if (path->p_tree_depth == 0) {
3146 rightmost_no_delete:
3147                 /*
3148                  * Inline extents. This is trivially handled, so do
3149                  * it up front.
3150                  */
3151                 ret = ocfs2_rotate_rightmost_leaf_left(handle, et, path);
3152                 if (ret)
3153                         mlog_errno(ret);
3154                 goto out;
3155         }
3156
3157         /*
3158          * Handle rightmost branch now. There's several cases:
3159          *  1) simple rotation leaving records in there. That's trivial.
3160          *  2) rotation requiring a branch delete - there's no more
3161          *     records left. Two cases of this:
3162          *     a) There are branches to the left.
3163          *     b) This is also the leftmost (the only) branch.
3164          *
3165          *  1) is handled via ocfs2_rotate_rightmost_leaf_left()
3166          *  2a) we need the left branch so that we can update it with the unlink
3167          *  2b) we need to bring the root back to inline extents.
3168          */
3169
3170         eb = (struct ocfs2_extent_block *)path_leaf_bh(path)->b_data;
3171         el = &eb->h_list;
3172         if (eb->h_next_leaf_blk == 0) {
3173                 /*
3174                  * This gets a bit tricky if we're going to delete the
3175                  * rightmost path. Get the other cases out of the way
3176                  * 1st.
3177                  */
3178                 if (le16_to_cpu(el->l_next_free_rec) > 1)
3179                         goto rightmost_no_delete;
3180
3181                 if (le16_to_cpu(el->l_next_free_rec) == 0) {
3182                         ret = -EIO;
3183                         ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
3184                                     "Owner %llu has empty extent block at %llu\n",
3185                                     (unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
3186                                     (unsigned long long)le64_to_cpu(eb->h_blkno));
3187                         goto out;
3188                 }
3189
3190                 /*
3191                  * XXX: The caller can not trust "path" any more after
3192                  * this as it will have been deleted. What do we do?
3193                  *
3194                  * In theory the rotate-for-merge code will never get
3195                  * here because it'll always ask for a rotate in a
3196                  * nonempty list.
3197                  */
3198
3199                 ret = ocfs2_remove_rightmost_path(handle, et, path,
3200                                                   dealloc);
3201                 if (ret)
3202                         mlog_errno(ret);
3203                 goto out;
3204         }
3205
3206         /*
3207          * Now we can loop, remembering the path we get from -EAGAIN
3208          * and restarting from there.
3209          */
3210 try_rotate:
3211         ret = __ocfs2_rotate_tree_left(handle, et, orig_credits, path,
3212                                        dealloc, &restart_path);
3213         if (ret && ret != -EAGAIN) {
3214                 mlog_errno(ret);
3215                 goto out;
3216         }
3217
3218         while (ret == -EAGAIN) {
3219                 tmp_path = restart_path;
3220                 restart_path = NULL;
3221
3222                 ret = __ocfs2_rotate_tree_left(handle, et, orig_credits,
3223                                                tmp_path, dealloc,
3224                                                &restart_path);